Skip to content

Commit

Permalink
finish updating entity editor for dataTypeId in metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
CiaranMn committed Dec 5, 2024
1 parent 929c94d commit 3c555c8
Show file tree
Hide file tree
Showing 18 changed files with 476 additions and 152 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ const Page: NextPageWithLayout = () => {
oldProperties: entityFromDb?.properties ?? {},
newProperties: mergePropertyObjectAndMetadata(
overrideProperties ?? draftEntity.properties,
undefined,
draftEntity.metadata.properties,
),
}),
},
Expand Down Expand Up @@ -457,6 +457,7 @@ const Page: NextPageWithLayout = () => {
omitProperties: [],
}),
);
setIsDirty(true);
}}
/>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { useMutation } from "@apollo/client";
import type { VersionedUrl } from "@blockprotocol/type-system";
import { AlertModal } from "@hashintel/design-system";
import {
Entity,
mergePropertyObjectAndMetadata,
} from "@local/hash-graph-sdk/entity";
import type { PropertyObject } from "@local/hash-graph-types/entity";
import { generateEntityLabel } from "@local/hash-isomorphic-utils/generate-entity-label";
import { blockProtocolEntityTypes } from "@local/hash-isomorphic-utils/ontology-type-ids";
Expand All @@ -10,9 +15,17 @@ import { Typography } from "@mui/material";
import { useRouter } from "next/router";
import { useCallback, useContext, useEffect, useState } from "react";

import { useBlockProtocolCreateEntity } from "../../../../components/hooks/block-protocol-functions/knowledge/use-block-protocol-create-entity";
import { PageErrorState } from "../../../../components/page-error-state";
import type {
CreateEntityMutation,
CreateEntityMutationVariables,
} from "../../../../graphql/api-types.gen";
import {
createEntityMutation,
getEntitySubgraphQuery,
} from "../../../../graphql/queries/knowledge/entity.queries";
import { Link } from "../../../../shared/ui/link";
import { generateUseEntityTypeEntitiesQueryVariables } from "../../../../shared/use-entity-type-entities";
import { useGetClosedMultiEntityType } from "../../../shared/use-get-closed-multi-entity-type";
import { WorkspaceContext } from "../../../shared/workspace-context";
import { EditBar } from "../../shared/edit-bar";
Expand Down Expand Up @@ -79,9 +92,25 @@ export const CreateEntityPage = ({ entityTypeId }: CreateEntityPageProps) => {

const { activeWorkspace, activeWorkspaceOwnedById } =
useContext(WorkspaceContext);
const { createEntity } = useBlockProtocolCreateEntity(
activeWorkspaceOwnedById ?? null,
);

const [createEntity] = useMutation<
CreateEntityMutation,
CreateEntityMutationVariables
>(createEntityMutation, {
refetchQueries: [
/**
* This refetch query accounts for the "Entities" section
* in the sidebar being updated when the first instance of
* a type is created by a user that is from a different web.
*/
{
query: getEntitySubgraphQuery,
variables: generateUseEntityTypeEntitiesQueryVariables({
ownedById: activeWorkspaceOwnedById,
}),
},
],
});

const [creating, setCreating] = useState(false);

Expand Down Expand Up @@ -110,13 +139,21 @@ export const CreateEntityPage = ({ entityTypeId }: CreateEntityPageProps) => {

try {
setCreating(true);
const { data: createdEntity } = await createEntity({
data: {
const { data } = await createEntity({
variables: {
entityTypeIds: entity.metadata.entityTypeIds,
properties: overrideProperties ?? draftEntity.properties,
ownedById: activeWorkspaceOwnedById,
properties: mergePropertyObjectAndMetadata(
overrideProperties ?? draftEntity.properties,
draftEntity.metadata.properties,
),
},
});

const createdEntity = data?.createEntity
? new Entity(data.createEntity)
: null;

if (!createdEntity) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,7 @@ const EditEntitySlideOver = memo(
omitProperties: [],
}),
);
setIsDirty(true);
}}
isDirty={isDirty}
onEntityClick={onEntityClick}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ import { extractBaseUrl, type VersionedUrl } from "@blockprotocol/type-system";
import { extractVersion } from "@blockprotocol/type-system/slim";
import { typedEntries } from "@local/advanced-types/typed-entries";
import type { EntityTypeIdDiff } from "@local/hash-graph-client";
import {
EntityId,
isValueMetadata,
PropertyPath,
} from "@local/hash-graph-types/entity";
import type { EntityId, PropertyPath } from "@local/hash-graph-types/entity";
import { isValueMetadata } from "@local/hash-graph-types/entity";
import type {
BaseUrl,
EntityTypeWithMetadata,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ export const createRenderChangeTypeCell = (

const newContent = produce(valueCellOfThisRow, (draft) => {
draft.data.propertyRow.value = undefined;
draft.data.propertyRow.valueMetadata = undefined;
});

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { VersionedUrl } from "@blockprotocol/type-system/slim";
import type { DragEndEvent } from "@dnd-kit/core";
import {
closestCenter,
Expand Down Expand Up @@ -54,8 +55,9 @@ export const ArrayEditor: ValueCellEditorComponent = ({
const {
value: propertyValue,
valueMetadata,
generateNewMetadataObject,
permittedDataTypes,
setPropertyMetadata,
propertyKeyChain,
maxItems,
minItems,
} = cell.data.propertyRow;
Expand Down Expand Up @@ -146,14 +148,22 @@ export const ArrayEditor: ValueCellEditorComponent = ({
setSelectedRow((prevId) => (id === prevId ? "" : id));
};

const addItem = (value: unknown) => {
const addItem = (value: unknown, dataTypeId: VersionedUrl) => {
setEditingRow("");

const { propertyMetadata } = generateNewMetadataObject({
propertyKeyChain,
valuePath: [...propertyKeyChain, items.length],
valueMetadata: { metadata: { dataTypeId } },
});

const newCell = produce(cell, (draftCell) => {
draftCell.data.propertyRow.value = [
...items.map((item) => item.value),
value,
];

draftCell.data.propertyRow.valueMetadata = propertyMetadata;
});
onChange(newCell);

Expand All @@ -166,11 +176,20 @@ export const ArrayEditor: ValueCellEditorComponent = ({
};

const removeItem = (indexToRemove: number) => {
const { propertyMetadata } = generateNewMetadataObject({
propertyKeyChain,
valuePath: [...propertyKeyChain, indexToRemove],
valueMetadata: "delete",
});

const newCell = produce(cell, (draftCell) => {
draftCell.data.propertyRow.value = items
.filter((_, index) => indexToRemove !== index)
.map(({ value }) => value);

draftCell.data.propertyRow.valueMetadata = propertyMetadata;
});

onChange(newCell);
};

Expand All @@ -192,6 +211,25 @@ export const ArrayEditor: ValueCellEditorComponent = ({
const newItems = arrayMove(items, oldIndex, newIndex);

draftCell.data.propertyRow.value = newItems.map(({ value }) => value);

if (!valueMetadata) {
throw new Error(
"Expected valueMetadata to be set when there are values",
);
}

if (!isArrayMetadata(valueMetadata)) {
throw new Error(
`Expected array metadata for value '${JSON.stringify(newItems)}', got ${JSON.stringify(valueMetadata)}`,
);
}

const newMetadata = arrayMove(valueMetadata.value, oldIndex, newIndex);

draftCell.data.propertyRow.valueMetadata = {
...valueMetadata,
value: newMetadata,
};
});
onChange(newCell);
};
Expand Down Expand Up @@ -233,7 +271,7 @@ export const ArrayEditor: ValueCellEditorComponent = ({

// add the value on click instead of showing draftRow
if (onlyOneExpectedType && noEditMode) {
return addItem(editorSpec.defaultValue);
return addItem(editorSpec.defaultValue, expectedType.$id);
}

setEditingRow(DRAFT_ROW_KEY);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ClosedDataType } from "@blockprotocol/type-system";
import type { ClosedDataType, VersionedUrl } from "@blockprotocol/type-system";
import { useState } from "react";

import { DRAFT_ROW_KEY } from "../array-editor";
Expand All @@ -9,7 +9,7 @@ import { SortableRow } from "./sortable-row";
interface DraftRowProps {
expectedTypes: ClosedDataType[];
existingItemCount: number;
onDraftSaved: (value: unknown) => void;
onDraftSaved: (value: unknown, dataTypeId: VersionedUrl) => void;
onDraftDiscarded: () => void;
}

Expand Down Expand Up @@ -56,7 +56,7 @@ export const DraftRow = ({
return onDraftDiscarded();
}

onDraftSaved(value);
onDraftSaved(value, dataType.$id);
}}
onDiscardChanges={onDraftDiscarded}
expectedTypes={expectedTypes}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
getMergedDataTypeSchema,
} from "@local/hash-isomorphic-utils/data-types";
import DragIndicatorIcon from "@mui/icons-material/DragIndicator";
import { Box, Divider, Typography } from "@mui/material";
import { Box, Divider, Stack, Typography } from "@mui/material";
import { useRef, useState } from "react";

import { getEditorSpecs } from "../editor-specs";
Expand Down Expand Up @@ -148,9 +148,16 @@ export const SortableRow = ({

return (
<ValueChip
title={formatDataValue(value as JsonValue, schema)
.map((part) => part.text)
.join("")}
title={
<Stack direction="row">
{formatDataValue(value as JsonValue, schema).map((part, idx) => (
// eslint-disable-next-line react/no-array-index-key
<Box component="span" key={idx} sx={{ color: part.color }}>
{part.text}
</Box>
))}
</Stack>
}
selected={!!selected}
icon={{ icon: editorSpec.icon }}
tooltip={dataType.title}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { IconDefinition } from "@fortawesome/free-solid-svg-icons";
import { faAsterisk } from "@fortawesome/free-solid-svg-icons";
import { Chip, FontAwesomeIcon } from "@hashintel/design-system";
import { Box, Tooltip } from "@mui/material";
import type { ReactNode } from "react";

export const ValueChip = ({
title,
Expand All @@ -10,7 +11,7 @@ export const ValueChip = ({
selected,
tooltip = "",
}: {
title: string;
title: ReactNode;
icon?: Pick<IconDefinition, "icon">;
imageSrc?: string;
selected: boolean;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ClosedDataType } from "@blockprotocol/type-system";
import { Chip } from "@hashintel/design-system";
import { GRID_CLICK_IGNORE_CLASS } from "@hashintel/design-system/constants";
import type { PropertyMetadataValue } from "@local/hash-graph-types/entity";
import { isValueMetadata } from "@local/hash-graph-types/entity";
import type { MergedDataTypeSingleSchema } from "@local/hash-isomorphic-utils/data-types";
import { getMergedDataTypeSchema } from "@local/hash-isomorphic-utils/data-types";
Expand All @@ -19,9 +20,9 @@ import type { ValueCell, ValueCellEditorComponent } from "./types";
export const SingleValueEditor: ValueCellEditorComponent = (props) => {
const { value: cell, onChange, onFinishedEditing } = props;
const {
generateNewMetadataObject,
permittedDataTypes,
propertyKeyChain,
setPropertyMetadata,
value,
valueMetadata,
} = cell.data.propertyRow;
Expand Down Expand Up @@ -86,21 +87,42 @@ export const SingleValueEditor: ValueCellEditorComponent = (props) => {
});

useEffect(() => {
if (chosenDataType) {
setPropertyMetadata(propertyKeyChain, {
metadata: {
dataTypeId: chosenDataType.dataType.$id,
if (
chosenDataType &&
(valueMetadata as PropertyMetadataValue | undefined)?.metadata
.dataTypeId !== chosenDataType.dataType.$id
) {
const { propertyMetadata } = generateNewMetadataObject({
propertyKeyChain,
valuePath: propertyKeyChain,
valueMetadata: {
metadata: {
dataTypeId: chosenDataType.dataType.$id,
},
},
});

const newCell = produce(cell, (draftCell) => {
draftCell.data.propertyRow.valueMetadata = propertyMetadata;
});

onChange(newCell);
}
}, [chosenDataType, propertyKeyChain, setPropertyMetadata]);
}, [
cell,
chosenDataType,
generateNewMetadataObject,
onChange,
propertyKeyChain,
valueMetadata,
]);

const latestValueCellRef = useRef<ValueCell>(cell);
useEffect(() => {
latestValueCellRef.current = cell;
});

if (!chosenDataType) {
if (!chosenDataType || !cell.data.propertyRow.valueMetadata) {
return (
<GridEditorWrapper>
<EditorTypePicker
Expand All @@ -116,19 +138,22 @@ export const SingleValueEditor: ValueCellEditorComponent = (props) => {

const editorSpec = getEditorSpecs(type, schema);

setChosenDataType({
dataType: type,
schema,
});

// if no edit mode supported for selected type, set the default value and close the editor
if (editorSpec.arrayEditException === "no-edit-mode") {
const newCell = produce(cell, (draftCell) => {
draftCell.data.propertyRow.value = editorSpec.defaultValue;
draftCell.data.propertyRow.valueMetadata = {
metadata: { dataTypeId: type.$id },
};
});

return onFinishedEditing(newCell);
}

setChosenDataType({
dataType: type,
schema,
});
}}
/>
</GridEditorWrapper>
Expand Down
Loading

0 comments on commit 3c555c8

Please sign in to comment.