Skip to content

Database diagrams editor that allows you to visualize and design your DB with a single query.

areas diff logic (#1011)

Guy Ben-Aharona237b525c3b6
diff --git a/src/context/chartdb-context/chartdb-provider.tsx b/src/context/chartdb-context/chartdb-provider.tsx
index b5a733d8..535d461c 100644
--- a/src/context/chartdb-context/chartdb-provider.tsx
+++ b/src/context/chartdb-context/chartdb-provider.tsx
@@ -77,7 +77,8 @@ export const ChartDBProvider: React.FC<
useState<string>();
const diffCalculatedHandler = useCallback((event: DiffCalculatedEvent) => {
- const { tablesToAdd, fieldsToAdd, relationshipsToAdd } = event.data;
+ const { tablesToAdd, fieldsToAdd, relationshipsToAdd, areasToAdd } =
+ event.data;
setTables((tables) =>
[...tables, ...(tablesToAdd ?? [])].map((table) => {
const fields = fieldsToAdd.get(table.id);
@@ -90,6 +91,7 @@ export const ChartDBProvider: React.FC<
...relationships,
...(relationshipsToAdd ?? []),
]);
+ setAreas((areas) => [...areas, ...(areasToAdd ?? [])]);
}, []);
diffEvents.useSubscription(diffCalculatedHandler);
diff --git a/src/context/diff-context/diff-context.tsx b/src/context/diff-context/diff-context.tsx
index 191b72da..3ea40afd 100644
--- a/src/context/diff-context/diff-context.tsx
+++ b/src/context/diff-context/diff-context.tsx
@@ -5,6 +5,7 @@ import type { EventEmitter } from 'ahooks/lib/useEventEmitter';
import type { DBField } from '@/lib/domain/db-field';
import type { DataType } from '@/lib/data/data-types/data-types';
import type { DBRelationship } from '@/lib/domain/db-relationship';
+import type { Area } from '@/lib/domain/area';
import type { DiffMap } from '@/lib/domain/diff/diff';
export type DiffEventType = 'diff_calculated';
@@ -18,6 +19,7 @@ export type DiffCalculatedData = {
tablesToAdd: DBTable[];
fieldsToAdd: Map<string, DBField[]>;
relationshipsToAdd: DBRelationship[];
+ areasToAdd: Area[];
};
export type DiffCalculatedEvent = DiffEventBase<
@@ -123,6 +125,10 @@ export interface DiffContext {
relationshipId: string;
}) => boolean;
+ // area diff
+ checkIfNewArea: ({ areaId }: { areaId: string }) => boolean;
+ checkIfAreaRemoved: ({ areaId }: { areaId: string }) => boolean;
+
events: EventEmitter<DiffEvent>;
}
diff --git a/src/context/diff-context/diff-provider.tsx b/src/context/diff-context/diff-provider.tsx
index 59daad00..c90e3449 100644
--- a/src/context/diff-context/diff-provider.tsx
+++ b/src/context/diff-context/diff-provider.tsx
@@ -15,6 +15,7 @@ import { useEventEmitter } from 'ahooks';
import type { DBField } from '@/lib/domain/db-field';
import type { DataType } from '@/lib/data/data-types/data-types';
import type { DBRelationship } from '@/lib/domain/db-relationship';
+import type { Area } from '@/lib/domain/area';
import type { ChartDBDiff, DiffMap } from '@/lib/domain/diff/diff';
export const DiffProvider: React.FC<React.PropsWithChildren> = ({
@@ -92,6 +93,32 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
[]
);
+ const findAreasToAdd = useCallback(
+ ({
+ diffMap,
+ newDiagram,
+ }: {
+ diffMap: DiffMap;
+ newDiagram: Diagram;
+ }) => {
+ const areas: Area[] = [];
+ diffMap.forEach((diff) => {
+ if (diff.object === 'area' && diff.type === 'added') {
+ const area = newDiagram?.areas?.find(
+ (a) => a.id === diff.areaAdded.id
+ );
+
+ if (area) {
+ areas.push(area);
+ }
+ }
+ });
+
+ return areas;
+ },
+ []
+ );
+
const generateDiffCalculatedData = useCallback(
({
newDiagram,
@@ -122,9 +149,13 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
diffMap: diffMap,
newDiagram: newDiagram,
}),
+ areasToAdd: findAreasToAdd({
+ diffMap: diffMap,
+ newDiagram: newDiagram,
+ }),
};
},
- [findRelationshipsToAdd, generateFieldsToAddMap]
+ [findRelationshipsToAdd, generateFieldsToAddMap, findAreasToAdd]
);
const calculateDiff: DiffContext['calculateDiff'] = useCallback(
@@ -505,6 +536,34 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
[diffMap]
);
+ const checkIfNewArea = useCallback<DiffContext['checkIfNewArea']>(
+ ({ areaId }) => {
+ const areaKey = getDiffMapKey({
+ diffObject: 'area',
+ objectId: areaId,
+ });
+
+ return (
+ diffMap.has(areaKey) && diffMap.get(areaKey)?.type === 'added'
+ );
+ },
+ [diffMap]
+ );
+
+ const checkIfAreaRemoved = useCallback<DiffContext['checkIfAreaRemoved']>(
+ ({ areaId }) => {
+ const areaKey = getDiffMapKey({
+ diffObject: 'area',
+ objectId: areaId,
+ });
+
+ return (
+ diffMap.has(areaKey) && diffMap.get(areaKey)?.type === 'removed'
+ );
+ },
+ [diffMap]
+ );
+
const resetDiff = useCallback<DiffContext['resetDiff']>(() => {
setDiffMap(new Map<string, ChartDBDiff>());
setTablesChanged(new Map<string, boolean>());
@@ -550,6 +609,10 @@ export const DiffProvider: React.FC<React.PropsWithChildren> = ({
checkIfNewRelationship,
checkIfRelationshipRemoved,
+ // area diff
+ checkIfNewArea,
+ checkIfAreaRemoved,
+
events,
}}
>
diff --git a/src/lib/domain/db-table.ts b/src/lib/domain/db-table.ts
index 87f6e62f..27ee7d50 100644
--- a/src/lib/domain/db-table.ts
+++ b/src/lib/domain/db-table.ts
@@ -1,7 +1,7 @@
import { dbIndexSchema, type DBIndex } from './db-index';
import { dbFieldSchema, type DBField } from './db-field';
import type { DBRelationship } from './db-relationship';
-import { deepCopy } from '../utils';
+import { deepCopy, findContainingArea } from '../utils';
import { schemaNameToDomainSchemaName } from './db-schema';
import { z } from 'zod';
import type { Area } from './area';
@@ -78,6 +78,13 @@ export const adjustTablePositions = ({
return adjustTablePositionsWithoutAreas(tables, relationships, mode);
}
+ // Update parentAreaId based on geometric containment before grouping
+ // This ensures tables that are visually inside an area get assigned to it
+ tables.forEach((table) => {
+ const containingArea = findContainingArea(table, areas);
+ table.parentAreaId = containingArea?.id || null;
+ });
+
// Group tables by their parent area
const tablesByArea = new Map<string | null, DBTable[]>();
diff --git a/src/lib/domain/diff/diff-check/diff-check.ts b/src/lib/domain/diff/diff-check/diff-check.ts
index 087be1ad..48f24362 100644
--- a/src/lib/domain/diff/diff-check/diff-check.ts
+++ b/src/lib/domain/diff/diff-check/diff-check.ts
@@ -40,6 +40,23 @@ const normalizeBoolean = (value: boolean | undefined | null): boolean => {
return value === true;
};
+// Helper to determine if an attribute change should add to the changed map
+// - undefined: always add (current behavior)
+// - empty array: never add
+// - array with values: only add if attribute is in the array
+const shouldAddToChangedMap = <T>(
+ attribute: T,
+ changedAttributes?: T[]
+): boolean => {
+ if (changedAttributes === undefined) {
+ return true;
+ }
+ if (changedAttributes.length === 0) {
+ return false;
+ }
+ return changedAttributes.includes(attribute);
+};
+
export interface GenerateDiffOptions {
includeTables?: boolean;
includeFields?: boolean;
@@ -53,6 +70,12 @@ export interface GenerateDiffOptions {
areas?: AreaDiffAttribute[];
notes?: NoteDiffAttribute[];
};
+ changedMaps?: {
+ changedTablesAttributes?: TableDiffAttribute[];
+ changedFieldsAttributes?: FieldDiffAttribute[];
+ changedAreasAttributes?: AreaDiffAttribute[];
+ changedNotesAttributes?: NoteDiffAttribute[];
+ };
changeTypes?: {
tables?: TableDiff['type'][];
fields?: FieldDiff['type'][];
@@ -98,6 +121,7 @@ export function generateDiff({
includeAreas: options.includeAreas ?? false,
includeNotes: options.includeNotes ?? false,
attributes: options.attributes ?? {},
+ changedMaps: options.changedMaps,
changeTypes: options.changeTypes ?? {},
matchers: options.matchers ?? {},
};
@@ -125,6 +149,8 @@ export function generateDiff({
diffMap: newDiffs,
changedTables,
attributes: mergedOptions.attributes?.tables,
+ changedTablesAttributes:
+ mergedOptions.changedMaps?.changedTablesAttributes,
changeTypes: mergedOptions.changeTypes?.tables,
tableMatcher,
});
@@ -138,6 +164,10 @@ export function generateDiff({
changedTables,
changedFields,
options: mergedOptions,
+ changedTablesAttributes:
+ mergedOptions.changedMaps?.changedTablesAttributes,
+ changedFieldsAttributes:
+ mergedOptions.changedMaps?.changedFieldsAttributes,
tableMatcher,
fieldMatcher,
indexMatcher,
@@ -162,6 +192,8 @@ export function generateDiff({
diffMap: newDiffs,
changedAreas,
attributes: mergedOptions.attributes?.areas,
+ changedAreasAttributes:
+ mergedOptions.changedMaps?.changedAreasAttributes,
changeTypes: mergedOptions.changeTypes?.areas,
areaMatcher,
});
@@ -175,6 +207,8 @@ export function generateDiff({
diffMap: newDiffs,
changedNotes,
attributes: mergedOptions.attributes?.notes,
+ changedNotesAttributes:
+ mergedOptions.changedMaps?.changedNotesAttributes,
changeTypes: mergedOptions.changeTypes?.notes,
noteMatcher,
});
@@ -196,6 +230,7 @@ function compareTables({
diffMap,
changedTables,
attributes,
+ changedTablesAttributes,
changeTypes,
tableMatcher,
}: {
@@ -204,6 +239,7 @@ function compareTables({
diffMap: DiffMap;
changedTables: Map<string, boolean>;
attributes?: TableDiffAttribute[];
+ changedTablesAttributes?: TableDiffAttribute[];
changeTypes?: TableDiff['type'][];
tableMatcher: (table: DBTable, tables: DBTable[]) => DBTable | undefined;
}) {
@@ -292,7 +328,9 @@ function compareTables({
}
);
- changedTables.set(oldTable.id, true);
+ if (shouldAddToChangedMap('name', changedTablesAttributes)) {
+ changedTables.set(oldTable.id, true);
+ }
}
if (
@@ -316,7 +354,11 @@ function compareTables({
}
);
- changedTables.set(oldTable.id, true);
+ if (
+ shouldAddToChangedMap('comments', changedTablesAttributes)
+ ) {
+ changedTables.set(oldTable.id, true);
+ }
}
if (
@@ -339,7 +381,9 @@ function compareTables({
}
);
- changedTables.set(oldTable.id, true);
+ if (shouldAddToChangedMap('color', changedTablesAttributes)) {
+ changedTables.set(oldTable.id, true);
+ }
}
if (attributesToCheck.includes('x') && oldTable.x !== newTable.x) {
@@ -359,7 +403,9 @@ function compareTables({
}
);
- changedTables.set(oldTable.id, true);
+ if (shouldAddToChangedMap('x', changedTablesAttributes)) {
+ changedTables.set(oldTable.id, true);
+ }
}
if (attributesToCheck.includes('y') && oldTable.y !== newTable.y) {
@@ -379,7 +425,9 @@ function compareTables({
}
);
- changedTables.set(oldTable.id, true);
+ if (shouldAddToChangedMap('y', changedTablesAttributes)) {
+ changedTables.set(oldTable.id, true);
+ }
}
if (
@@ -402,7 +450,9 @@ function compareTables({
}
);
- changedTables.set(oldTable.id, true);
+ if (shouldAddToChangedMap('width', changedTablesAttributes)) {
+ changedTables.set(oldTable.id, true);
+ }
}
}
}
@@ -416,6 +466,8 @@ function compareTableContents({
changedTables,
changedFields,
options,
+ changedTablesAttributes,
+ changedFieldsAttributes,
tableMatcher,
fieldMatcher,
indexMatcher,
@@ -426,6 +478,8 @@ function compareTableContents({
changedTables: Map<string, boolean>;
changedFields: Map<string, boolean>;
options?: GenerateDiffOptions;
+ changedTablesAttributes?: TableDiffAttribute[];
+ changedFieldsAttributes?: FieldDiffAttribute[];
tableMatcher: (table: DBTable, tables: DBTable[]) => DBTable | undefined;
fieldMatcher: (field: DBField, fields: DBField[]) => DBField | undefined;
indexMatcher: (index: DBIndex, indexes: DBIndex[]) => DBIndex | undefined;
@@ -448,6 +502,8 @@ function compareTableContents({
changedTables,
changedFields,
attributes: options?.attributes?.fields,
+ changedTablesAttributes,
+ changedFieldsAttributes,
changeTypes: options?.changeTypes?.fields,
fieldMatcher,
});
@@ -461,6 +517,7 @@ function compareTableContents({
newIndexes: newTable.indexes,
diffMap,
changedTables,
+ changedTablesAttributes,
changeTypes: options?.changeTypes?.indexes,
indexMatcher,
});
@@ -477,6 +534,8 @@ function compareFields({
changedTables,
changedFields,
attributes,
+ changedTablesAttributes,
+ changedFieldsAttributes,
changeTypes,
fieldMatcher,
}: {
@@ -487,6 +546,8 @@ function compareFields({
changedTables: Map<string, boolean>;
changedFields: Map<string, boolean>;
attributes?: FieldDiffAttribute[];
+ changedTablesAttributes?: TableDiffAttribute[];
+ changedFieldsAttributes?: FieldDiffAttribute[];
changeTypes?: FieldDiff['type'][];
fieldMatcher: (field: DBField, fields: DBField[]) => DBField | undefined;
}) {
@@ -557,6 +618,8 @@ function compareFields({
changedTables,
changedFields,
attributes,
+ changedTablesAttributes,
+ changedFieldsAttributes,
});
}
}
@@ -571,6 +634,8 @@ function compareFieldProperties({
changedTables,
changedFields,
attributes,
+ changedTablesAttributes,
+ changedFieldsAttributes,
}: {
tableId: string;
oldField: DBField;
@@ -579,6 +644,8 @@ function compareFieldProperties({
changedTables: Map<string, boolean>;
changedFields: Map<string, boolean>;
attributes?: FieldDiffAttribute[];
+ changedTablesAttributes?: TableDiffAttribute[];
+ changedFieldsAttributes?: FieldDiffAttribute[];
}) {
// If attributes are specified, only check those attributes
const attributesToCheck: FieldDiffAttribute[] = attributes ?? [
@@ -680,6 +747,11 @@ function compareFieldProperties({
}
if (changedAttributes.length > 0) {
+ // Track which attributes should trigger adding to changed maps
+ const attributesThatTriggerChange = changedAttributes.filter((attr) =>
+ shouldAddToChangedMap(attr, changedFieldsAttributes)
+ );
+
for (const attribute of changedAttributes) {
diffMap.set(
getDiffMapKey({
@@ -698,8 +770,22 @@ function compareFieldProperties({
}
);
}
- changedTables.set(tableId, true);
- changedFields.set(oldField.id, true);
+
+ // Only add to changed maps if at least one attribute should trigger a change
+ if (attributesThatTriggerChange.length > 0) {
+ // For changedTables, we need to check changedTablesAttributes
+ // undefined = always add, empty = never add, array = check if any field attribute qualifies
+ if (changedTablesAttributes === undefined) {
+ changedTables.set(tableId, true);
+ } else if (changedTablesAttributes.length > 0) {
+ // If changedTablesAttributes has values, we only add if explicitly configured
+ // Since these are field changes, we keep current behavior of adding to changedTables
+ changedTables.set(tableId, true);
+ }
+ // If changedTablesAttributes is empty array, don't add to changedTables
+
+ changedFields.set(oldField.id, true);
+ }
}
}
@@ -710,6 +796,7 @@ function compareIndexes({
newIndexes,
diffMap,
changedTables,
+ changedTablesAttributes,
changeTypes,
indexMatcher,
}: {
@@ -718,6 +805,7 @@ function compareIndexes({
newIndexes: DBIndex[];
diffMap: DiffMap;
changedTables: Map<string, boolean>;
+ changedTablesAttributes?: TableDiffAttribute[];
changeTypes?: IndexDiff['type'][];
indexMatcher: (index: DBIndex, indexes: DBIndex[]) => DBIndex | undefined;
}) {
@@ -728,6 +816,13 @@ function compareIndexes({
// If changeTypes is undefined, check all types
const typesToCheck = changeTypes ?? ['added', 'removed'];
+
+ // For structural changes (added/removed indexes), add to changedTables unless
+ // changedTablesAttributes is explicitly set to empty array
+ const shouldAddToChangedTables =
+ changedTablesAttributes === undefined ||
+ changedTablesAttributes.length > 0;
+
// Check for added indexes
if (typesToCheck.includes('added')) {
for (const newIndex of newIndexes) {
@@ -744,7 +839,9 @@ function compareIndexes({
tableId,
}
);
- changedTables.set(tableId, true);
+ if (shouldAddToChangedTables) {
+ changedTables.set(tableId, true);
+ }
}
}
}
@@ -765,7 +862,9 @@ function compareIndexes({
tableId,
}
);
- changedTables.set(tableId, true);
+ if (shouldAddToChangedTables) {
+ changedTables.set(tableId, true);
+ }
}
}
}
@@ -844,6 +943,7 @@ function compareAreas({
diffMap,
changedAreas,
attributes,
+ changedAreasAttributes,
changeTypes,
areaMatcher,
}: {
@@ -852,6 +952,7 @@ function compareAreas({
diffMap: DiffMap;
changedAreas: Map<string, boolean>;
attributes?: AreaDiffAttribute[];
+ changedAreasAttributes?: AreaDiffAttribute[];
changeTypes?: AreaDiff['type'][];
areaMatcher: (area: Area, areas: Area[]) => Area | undefined;
}) {
@@ -938,7 +1039,9 @@ function compareAreas({
oldValue: oldArea.name,
}
);
- changedAreas.set(oldArea.id, true);
+ if (shouldAddToChangedMap('name', changedAreasAttributes)) {
+ changedAreas.set(oldArea.id, true);
+ }
}
if (
@@ -960,7 +1063,9 @@ function compareAreas({
oldValue: oldArea.color,
}
);
- changedAreas.set(oldArea.id, true);
+ if (shouldAddToChangedMap('color', changedAreasAttributes)) {
+ changedAreas.set(oldArea.id, true);
+ }
}
if (attributesToCheck.includes('x') && oldArea.x !== newArea.x) {
@@ -979,7 +1084,9 @@ function compareAreas({
oldValue: oldArea.x,
}
);
- changedAreas.set(oldArea.id, true);
+ if (shouldAddToChangedMap('x', changedAreasAttributes)) {
+ changedAreas.set(oldArea.id, true);
+ }
}
if (attributesToCheck.includes('y') && oldArea.y !== newArea.y) {
@@ -998,7 +1105,9 @@ function compareAreas({
oldValue: oldArea.y,
}
);
- changedAreas.set(oldArea.id, true);
+ if (shouldAddToChangedMap('y', changedAreasAttributes)) {
+ changedAreas.set(oldArea.id, true);
+ }
}
if (
@@ -1020,7 +1129,9 @@ function compareAreas({
oldValue: oldArea.width,
}
);
- changedAreas.set(oldArea.id, true);
+ if (shouldAddToChangedMap('width', changedAreasAttributes)) {
+ changedAreas.set(oldArea.id, true);
+ }
}
if (
@@ -1042,7 +1153,9 @@ function compareAreas({
oldValue: oldArea.height,
}
);
- changedAreas.set(oldArea.id, true);
+ if (shouldAddToChangedMap('height', changedAreasAttributes)) {
+ changedAreas.set(oldArea.id, true);
+ }
}
}
}
@@ -1055,6 +1168,7 @@ function compareNotes({
diffMap,
changedNotes,
attributes,
+ changedNotesAttributes,
changeTypes,
noteMatcher,
}: {
@@ -1063,6 +1177,7 @@ function compareNotes({
diffMap: DiffMap;
changedNotes: Map<string, boolean>;
attributes?: NoteDiffAttribute[];
+ changedNotesAttributes?: NoteDiffAttribute[];
changeTypes?: NoteDiff['type'][];
noteMatcher: (note: Note, notes: Note[]) => Note | undefined;
}) {
@@ -1149,7 +1264,9 @@ function compareNotes({
oldValue: oldNote.content,
}
);
- changedNotes.set(oldNote.id, true);
+ if (shouldAddToChangedMap('content', changedNotesAttributes)) {
+ changedNotes.set(oldNote.id, true);
+ }
}
if (
@@ -1171,7 +1288,9 @@ function compareNotes({
oldValue: oldNote.color,
}
);
- changedNotes.set(oldNote.id, true);
+ if (shouldAddToChangedMap('color', changedNotesAttributes)) {
+ changedNotes.set(oldNote.id, true);
+ }
}
if (attributesToCheck.includes('x') && oldNote.x !== newNote.x) {
@@ -1190,7 +1309,9 @@ function compareNotes({
oldValue: oldNote.x,
}
);
- changedNotes.set(oldNote.id, true);
+ if (shouldAddToChangedMap('x', changedNotesAttributes)) {
+ changedNotes.set(oldNote.id, true);
+ }
}
if (attributesToCheck.includes('y') && oldNote.y !== newNote.y) {
@@ -1209,7 +1330,9 @@ function compareNotes({
oldValue: oldNote.y,
}
);
- changedNotes.set(oldNote.id, true);
+ if (shouldAddToChangedMap('y', changedNotesAttributes)) {
+ changedNotes.set(oldNote.id, true);
+ }
}
if (
@@ -1231,7 +1354,9 @@ function compareNotes({
oldValue: oldNote.width,
}
);
- changedNotes.set(oldNote.id, true);
+ if (shouldAddToChangedMap('width', changedNotesAttributes)) {
+ changedNotes.set(oldNote.id, true);
+ }
}
if (
@@ -1253,7 +1378,9 @@ function compareNotes({
oldValue: oldNote.height,
}
);
- changedNotes.set(oldNote.id, true);
+ if (shouldAddToChangedMap('height', changedNotesAttributes)) {
+ changedNotes.set(oldNote.id, true);
+ }
}
}
}
diff --git a/src/pages/editor-page/canvas/area-node/area-node-status/area-node-status.tsx b/src/pages/editor-page/canvas/area-node/area-node-status/area-node-status.tsx
new file mode 100644
index 00000000..28e3b730
--- /dev/null
+++ b/src/pages/editor-page/canvas/area-node/area-node-status/area-node-status.tsx
@@ -0,0 +1,29 @@
+import { cn } from '@/lib/utils';
+import React from 'react';
+
+export interface AreaNodeStatusProps {
+ status: 'new' | 'removed' | 'none';
+}
+
+export const AreaNodeStatus: React.FC<AreaNodeStatusProps> = ({ status }) => {
+ if (status === 'none') {
+ return null;
+ }
+ return (
+ <div className="absolute left-1/2 top-0 z-10 -translate-x-1/2 -translate-y-1/2">
+ <span
+ className={cn(
+ 'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
+ {
+ 'bg-green-100 text-green-800 dark:bg-green-800 dark:text-green-100':
+ status === 'new',
+ 'bg-red-100 text-red-800 dark:bg-red-800 dark:text-red-100':
+ status === 'removed',
+ }
+ )}
+ >
+ {status === 'new' ? 'New' : 'Deleted'}
+ </span>
+ </div>
+ );
+};
diff --git a/src/pages/editor-page/canvas/area-node/area-node.tsx b/src/pages/editor-page/canvas/area-node/area-node.tsx
index 47c3b622..c4b55ffd 100644
--- a/src/pages/editor-page/canvas/area-node/area-node.tsx
+++ b/src/pages/editor-page/canvas/area-node/area-node.tsx
@@ -1,4 +1,10 @@
-import React, { useCallback, useState } from 'react';
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
import type { NodeProps, Node } from '@xyflow/react';
import { NodeResizer } from '@xyflow/react';
import type { Area } from '@/lib/domain/area';
@@ -12,11 +18,19 @@ import {
} from '@/components/tooltip/tooltip';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
-import { Check, GripVertical, Pencil } from 'lucide-react';
+import {
+ Check,
+ GripVertical,
+ Pencil,
+ SquareMinus,
+ SquarePlus,
+} from 'lucide-react';
import { Button } from '@/components/button/button';
import { useLayout } from '@/hooks/use-layout';
import { AreaNodeContextMenu } from './area-node-context-menu';
import { useCanvas } from '@/hooks/use-canvas';
+import { useDiff } from '@/context/diff-context/use-diff';
+import { AreaNodeStatus } from './area-node-status/area-node-status';
export type AreaNodeType = Node<
{
@@ -37,6 +51,36 @@ export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
const focused = !!selected && !dragging;
+ const { checkIfNewArea, checkIfAreaRemoved } = useDiff();
+
+ const [diffState, setDiffState] = useState<{
+ isDiffNewArea: boolean;
+ isDiffAreaRemoved: boolean;
+ }>({
+ isDiffNewArea: false,
+ isDiffAreaRemoved: false,
+ });
+
+ const hasMountedRef = useRef(false);
+
+ useEffect(() => {
+ const calculateDiff = () => {
+ setDiffState({
+ isDiffNewArea: checkIfNewArea({ areaId: area.id }),
+ isDiffAreaRemoved: checkIfAreaRemoved({ areaId: area.id }),
+ });
+ };
+
+ if (!hasMountedRef.current) {
+ hasMountedRef.current = true;
+ requestAnimationFrame(calculateDiff);
+ } else {
+ calculateDiff();
+ }
+ }, [checkIfNewArea, checkIfAreaRemoved, area.id]);
+
+ const { isDiffNewArea, isDiffAreaRemoved } = diffState;
+
const editAreaName = useCallback(() => {
if (!editMode) return;
if (areaName.trim()) {
@@ -72,16 +116,28 @@ export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
setEditMode(true);
};
+ const containerClassName = useMemo(
+ () =>
+ cn(
+ 'relative flex h-full flex-col rounded-md border-2 shadow-sm',
+ selected ? 'border-pink-600' : 'border-transparent',
+ isDiffNewArea
+ ? 'outline outline-[3px] outline-green-500 dark:outline-green-900 outline-offset-[5px]'
+ : '',
+ isDiffAreaRemoved
+ ? 'outline outline-[3px] outline-red-500 dark:outline-red-900 outline-offset-[5px]'
+ : ''
+ ),
+ [selected, isDiffNewArea, isDiffAreaRemoved]
+ );
+
return (
<AreaNodeContextMenu
area={area}
onEditName={() => setEditMode(true)}
>
<div
- className={cn(
- 'flex h-full flex-col rounded-md border-2 shadow-sm',
- selected ? 'border-pink-600' : 'border-transparent'
- )}
+ className={containerClassName}
style={{
backgroundColor: `${area.color}15`,
borderColor: selected ? undefined : area.color,
@@ -93,6 +149,15 @@ export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
}
}}
>
+ <AreaNodeStatus
+ status={
+ isDiffNewArea
+ ? 'new'
+ : isDiffAreaRemoved
+ ? 'removed'
+ : 'none'
+ }
+ />
{!readonly ? (
<NodeResizer
isVisible={focused}
@@ -104,7 +169,31 @@ export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
) : null}
<div className="group flex h-8 items-center justify-between rounded-t-md px-2">
<div className="flex w-full items-center gap-1">
- <GripVertical className="size-4 shrink-0 text-slate-700 opacity-60 dark:text-slate-300" />
+ {isDiffNewArea ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <SquarePlus
+ className="size-3.5 shrink-0 text-green-600"
+ strokeWidth={2.5}
+ />
+ </TooltipTrigger>
+ <TooltipContent>New Area</TooltipContent>
+ </Tooltip>
+ ) : isDiffAreaRemoved ? (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <SquareMinus
+ className="size-3.5 shrink-0 text-red-600"
+ strokeWidth={2.5}
+ />
+ </TooltipTrigger>
+ <TooltipContent>
+ Area Removed
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <GripVertical className="size-3.5 shrink-0 text-slate-700 opacity-60 dark:text-slate-300" />
+ )}
{editMode && !readonly ? (
<div className="flex w-full items-center">
@@ -128,6 +217,22 @@ export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
<Check className="size-3.5 text-slate-700 dark:text-slate-300" />
</Button>
</div>
+ ) : isDiffNewArea ? (
+ <div
+ className={cn(
+ 'flex h-5 items-center truncate rounded-sm bg-green-200 px-2 py-0.5 text-sm font-normal text-green-900 dark:bg-green-800 dark:text-green-200'
+ )}
+ >
+ {area.name}
+ </div>
+ ) : isDiffAreaRemoved ? (
+ <div
+ className={cn(
+ 'flex h-5 items-center truncate rounded-sm bg-red-200 px-2 py-0.5 text-sm font-normal text-red-900 dark:bg-red-800 dark:text-red-200'
+ )}
+ >
+ {area.name}
+ </div>
) : !readonly ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -147,15 +252,18 @@ export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
{area.name}
</div>
)}
- {!editMode && !readonly && (
- <Button
- variant="ghost"
- className="ml-auto size-5 p-0 opacity-0 transition-opacity hover:bg-white/20 group-hover:opacity-100"
- onClick={enterEditMode}
- >
- <Pencil className="size-3 text-slate-700 dark:text-slate-300" />
- </Button>
- )}
+ {!editMode &&
+ !readonly &&
+ !isDiffNewArea &&
+ !isDiffAreaRemoved && (
+ <Button
+ variant="ghost"
+ className="ml-auto size-5 p-0 opacity-0 transition-opacity hover:bg-white/20 group-hover:opacity-100"
+ onClick={enterEditMode}
+ >
+ <Pencil className="size-3 text-slate-700 dark:text-slate-300" />
+ </Button>
+ )}
</div>
</div>
<div className="flex-1" />
diff --git a/src/pages/editor-page/canvas/canvas.tsx b/src/pages/editor-page/canvas/canvas.tsx
index e7404a31..76c7657d 100644
--- a/src/pages/editor-page/canvas/canvas.tsx
+++ b/src/pages/editor-page/canvas/canvas.tsx
@@ -1077,81 +1077,93 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
childTableMovements.size > 0 ||
areaRemoveChanges.length > 0
) {
- updateTablesState((currentTables) => {
- const updatedTables = currentTables
- .map((currentTable) => {
- // Handle area removal - clear parentAreaId
- const removedArea = areaRemoveChanges.find(
- (change) =>
- change.id === currentTable.parentAreaId
- );
- if (removedArea) {
- return {
- ...currentTable,
- parentAreaId: null,
- };
- }
-
- // Handle direct table changes
- const positionChange = positionChanges.find(
- (change) => change.id === currentTable.id
- );
- const sizeChange = sizeChanges.find(
- (change) => change.id === currentTable.id
- );
-
- // Handle child table movement from area drag
- const areaMovement = childTableMovements.get(
- currentTable.id
+ updateTablesState(
+ (currentTables) => {
+ const updatedTables = currentTables
+ .map((currentTable) => {
+ // Handle area removal - clear parentAreaId
+ const removedArea = areaRemoveChanges.find(
+ (change) =>
+ change.id === currentTable.parentAreaId
+ );
+ if (removedArea) {
+ return {
+ ...currentTable,
+ parentAreaId: null,
+ };
+ }
+
+ // Handle direct table changes
+ const positionChange = positionChanges.find(
+ (change) => change.id === currentTable.id
+ );
+ const sizeChange = sizeChanges.find(
+ (change) => change.id === currentTable.id
+ );
+
+ // Handle child table movement from area drag
+ const areaMovement = childTableMovements.get(
+ currentTable.id
+ );
+
+ if (
+ positionChange ||
+ sizeChange ||
+ areaMovement
+ ) {
+ const x = positionChange?.position?.x;
+ const y = positionChange?.position?.y;
+
+ return {
+ ...currentTable,
+ ...(positionChange &&
+ x !== undefined &&
+ y !== undefined &&
+ !isNaN(x) &&
+ !isNaN(y)
+ ? {
+ x,
+ y,
+ }
+ : {}),
+ ...(areaMovement && !positionChange
+ ? {
+ x:
+ currentTable.x +
+ areaMovement.deltaX,
+ y:
+ currentTable.y +
+ areaMovement.deltaY,
+ }
+ : {}),
+ ...(sizeChange
+ ? {
+ width:
+ sizeChange.dimensions
+ ?.width ??
+ currentTable.width,
+ }
+ : {}),
+ };
+ }
+ return currentTable;
+ })
+ .filter(
+ (table) =>
+ !removeChanges.some(
+ (change) => change.id === table.id
+ )
);
- if (positionChange || sizeChange || areaMovement) {
- const x = positionChange?.position?.x;
- const y = positionChange?.position?.y;
-
- return {
- ...currentTable,
- ...(positionChange &&
- x !== undefined &&
- y !== undefined &&
- !isNaN(x) &&
- !isNaN(y)
- ? {
- x,
- y,
- }
- : {}),
- ...(areaMovement && !positionChange
- ? {
- x:
- currentTable.x +
- areaMovement.deltaX,
- y:
- currentTable.y +
- areaMovement.deltaY,
- }
- : {}),
- ...(sizeChange
- ? {
- width:
- sizeChange.dimensions
- ?.width ??
- currentTable.width,
- }
- : {}),
- };
- }
- return currentTable;
- })
- .filter(
- (table) =>
- !removeChanges.some(
- (change) => change.id === table.id
- )
- );
-
- return updatedTables;
- });
+ return updatedTables;
+ },
+ {
+ updateHistory:
+ positionChanges.length > 0 ||
+ removeChanges.length > 0 ||
+ sizeChanges.length > 0,
+ }
+ );
}
updateOverlappingGraphOnChangesDebounced({