Skip to content

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

feat(areas): implement area to enable logical diagram arrangement (#661)

Guy Ben-Aharon92e3ec785c91
diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/color-picker/color-picker.tsx b/src/components/color-picker/color-picker.tsx
similarity index 100%
rename from src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/color-picker/color-picker.tsx
rename to src/components/color-picker/color-picker.tsx
diff --git a/src/context/chartdb-context/chartdb-context.tsx b/src/context/chartdb-context/chartdb-context.tsx
index 9cba9ae5..6de818c0 100644
--- a/src/context/chartdb-context/chartdb-context.tsx
+++ b/src/context/chartdb-context/chartdb-context.tsx
@@ -10,6 +10,7 @@ import type { DatabaseEdition } from '@/lib/domain/database-edition';
import type { DBSchema } from '@/lib/domain/db-schema';
import type { DBDependency } from '@/lib/domain/db-dependency';
import { EventEmitter } from 'ahooks/lib/useEventEmitter';
+import type { Area } from '@/lib/domain/area';
export type ChartDBEventType =
| 'add_tables'
@@ -70,6 +71,7 @@ export interface ChartDBContext {
schemas: DBSchema[];
relationships: DBRelationship[];
dependencies: DBDependency[];
+ areas: Area[];
currentDiagram: Diagram;
events: EventEmitter<ChartDBEvent>;
readonly?: boolean;
@@ -221,6 +223,31 @@ export interface ChartDBContext {
dependency: Partial<DBDependency>,
options?: { updateHistory: boolean }
) => Promise<void>;
+
+ // Area operations
+ createArea: (attributes?: Partial<Omit<Area, 'id'>>) => Promise<Area>;
+ addArea: (
+ area: Area,
+ options?: { updateHistory: boolean }
+ ) => Promise<void>;
+ addAreas: (
+ areas: Area[],
+ options?: { updateHistory: boolean }
+ ) => Promise<void>;
+ getArea: (id: string) => Area | null;
+ removeArea: (
+ id: string,
+ options?: { updateHistory: boolean }
+ ) => Promise<void>;
+ removeAreas: (
+ ids: string[],
+ options?: { updateHistory: boolean }
+ ) => Promise<void>;
+ updateArea: (
+ id: string,
+ area: Partial<Area>,
+ options?: { updateHistory: boolean }
+ ) => Promise<void>;
}
export const chartDBContext = createContext<ChartDBContext>({
@@ -230,6 +257,7 @@ export const chartDBContext = createContext<ChartDBContext>({
tables: [],
relationships: [],
dependencies: [],
+ areas: [],
schemas: [],
filteredSchemas: [],
filterSchemas: emptyFn,
@@ -296,4 +324,13 @@ export const chartDBContext = createContext<ChartDBContext>({
removeDependencies: emptyFn,
addDependencies: emptyFn,
updateDependency: emptyFn,
+
+ // Area operations
+ createArea: emptyFn,
+ addArea: emptyFn,
+ addAreas: emptyFn,
+ getArea: emptyFn,
+ removeArea: emptyFn,
+ removeAreas: emptyFn,
+ updateArea: emptyFn,
});
diff --git a/src/context/chartdb-context/chartdb-provider.tsx b/src/context/chartdb-context/chartdb-provider.tsx
index bde83fdc..cb428bbe 100644
--- a/src/context/chartdb-context/chartdb-provider.tsx
+++ b/src/context/chartdb-context/chartdb-provider.tsx
@@ -21,6 +21,7 @@ import { useLocalConfig } from '@/hooks/use-local-config';
import { defaultSchemas } from '@/lib/data/default-schemas';
import { useEventEmitter } from 'ahooks';
import type { DBDependency } from '@/lib/domain/db-dependency';
+import type { Area } from '@/lib/domain/area';
import { storageInitialValue } from '../storage-context/storage-context';
import { useDiff } from '../diff-context/use-diff';
import type { DiffCalculatedEvent } from '../diff-context/diff-context';
@@ -56,6 +57,7 @@ export const ChartDBProvider: React.FC<
const [dependencies, setDependencies] = useState<DBDependency[]>(
diagram?.dependencies ?? []
);
+ const [areas, setAreas] = useState<Area[]>(diagram?.areas ?? []);
const { events: diffEvents } = useDiff();
const diffCalculatedHandler = useCallback((event: DiffCalculatedEvent) => {
@@ -152,6 +154,7 @@ export const ChartDBProvider: React.FC<
tables,
relationships,
dependencies,
+ areas,
}),
[
diagramId,
@@ -161,6 +164,7 @@ export const ChartDBProvider: React.FC<
tables,
relationships,
dependencies,
+ areas,
diagramCreatedAt,
diagramUpdatedAt,
]
@@ -172,6 +176,7 @@ export const ChartDBProvider: React.FC<
setTables([]);
setRelationships([]);
setDependencies([]);
+ setAreas([]);
setDiagramUpdatedAt(updatedAt);
resetRedoStack();
@@ -182,6 +187,7 @@ export const ChartDBProvider: React.FC<
db.deleteDiagramTables(diagramId),
db.deleteDiagramRelationships(diagramId),
db.deleteDiagramDependencies(diagramId),
+ db.deleteDiagramAreas(diagramId),
]);
}, [db, diagramId, resetRedoStack, resetUndoStack]);
@@ -194,6 +200,7 @@ export const ChartDBProvider: React.FC<
setTables([]);
setRelationships([]);
setDependencies([]);
+ setAreas([]);
resetRedoStack();
resetUndoStack();
@@ -202,6 +209,7 @@ export const ChartDBProvider: React.FC<
db.deleteDiagramRelationships(diagramId),
db.deleteDiagram(diagramId),
db.deleteDiagramDependencies(diagramId),
+ db.deleteDiagramAreas(diagramId),
]);
}, [db, diagramId, resetRedoStack, resetUndoStack]);
@@ -1363,6 +1371,130 @@ export const ChartDBProvider: React.FC<
]
);
+ // Area operations
+ const addAreas: ChartDBContext['addAreas'] = useCallback(
+ async (areas: Area[], options = { updateHistory: true }) => {
+ setAreas((currentAreas) => [...currentAreas, ...areas]);
+
+ const updatedAt = new Date();
+ setDiagramUpdatedAt(updatedAt);
+
+ await Promise.all([
+ ...areas.map((area) => db.addArea({ diagramId, area })),
+ db.updateDiagram({ id: diagramId, attributes: { updatedAt } }),
+ ]);
+
+ if (options.updateHistory) {
+ addUndoAction({
+ action: 'addAreas',
+ redoData: { areas },
+ undoData: { areaIds: areas.map((a) => a.id) },
+ });
+ resetRedoStack();
+ }
+ },
+ [db, diagramId, setAreas, addUndoAction, resetRedoStack]
+ );
+
+ const addArea: ChartDBContext['addArea'] = useCallback(
+ async (area: Area, options = { updateHistory: true }) => {
+ return addAreas([area], options);
+ },
+ [addAreas]
+ );
+
+ const createArea: ChartDBContext['createArea'] = useCallback(
+ async (attributes) => {
+ const area: Area = {
+ id: generateId(),
+ name: `Area ${areas.length + 1}`,
+ x: 0,
+ y: 0,
+ width: 300,
+ height: 200,
+ color: randomColor(),
+ ...attributes,
+ };
+
+ await addArea(area);
+
+ return area;
+ },
+ [areas, addArea]
+ );
+
+ const getArea: ChartDBContext['getArea'] = useCallback(
+ (id: string) => areas.find((area) => area.id === id) ?? null,
+ [areas]
+ );
+
+ const removeAreas: ChartDBContext['removeAreas'] = useCallback(
+ async (ids: string[], options = { updateHistory: true }) => {
+ const prevAreas = [
+ ...areas.filter((area) => ids.includes(area.id)),
+ ];
+
+ setAreas((areas) => areas.filter((area) => !ids.includes(area.id)));
+
+ const updatedAt = new Date();
+ setDiagramUpdatedAt(updatedAt);
+
+ await Promise.all([
+ ...ids.map((id) => db.deleteArea({ diagramId, id })),
+ db.updateDiagram({ id: diagramId, attributes: { updatedAt } }),
+ ]);
+
+ if (prevAreas.length > 0 && options.updateHistory) {
+ addUndoAction({
+ action: 'removeAreas',
+ redoData: { areaIds: ids },
+ undoData: { areas: prevAreas },
+ });
+ resetRedoStack();
+ }
+ },
+ [db, diagramId, setAreas, areas, addUndoAction, resetRedoStack]
+ );
+
+ const removeArea: ChartDBContext['removeArea'] = useCallback(
+ async (id: string, options = { updateHistory: true }) => {
+ return removeAreas([id], options);
+ },
+ [removeAreas]
+ );
+
+ const updateArea: ChartDBContext['updateArea'] = useCallback(
+ async (
+ id: string,
+ area: Partial<Area>,
+ options = { updateHistory: true }
+ ) => {
+ const prevArea = getArea(id);
+
+ setAreas((areas) =>
+ areas.map((a) => (a.id === id ? { ...a, ...area } : a))
+ );
+
+ const updatedAt = new Date();
+ setDiagramUpdatedAt(updatedAt);
+
+ await Promise.all([
+ db.updateDiagram({ id: diagramId, attributes: { updatedAt } }),
+ db.updateArea({ id, attributes: area }),
+ ]);
+
+ if (!!prevArea && options.updateHistory) {
+ addUndoAction({
+ action: 'updateArea',
+ redoData: { areaId: id, area },
+ undoData: { areaId: id, area: prevArea },
+ });
+ resetRedoStack();
+ }
+ },
+ [db, diagramId, setAreas, getArea, addUndoAction, resetRedoStack]
+ );
+
const loadDiagramFromData: ChartDBContext['loadDiagramFromData'] =
useCallback(
async (diagram) => {
@@ -1373,6 +1505,7 @@ export const ChartDBProvider: React.FC<
setTables(diagram?.tables ?? []);
setRelationships(diagram?.relationships ?? []);
setDependencies(diagram?.dependencies ?? []);
+ setAreas(diagram?.areas ?? []);
setDiagramCreatedAt(diagram.createdAt);
setDiagramUpdatedAt(diagram.updatedAt);
@@ -1386,6 +1519,7 @@ export const ChartDBProvider: React.FC<
setTables,
setRelationships,
setDependencies,
+ setAreas,
setDiagramCreatedAt,
setDiagramUpdatedAt,
events,
@@ -1398,6 +1532,7 @@ export const ChartDBProvider: React.FC<
includeRelationships: true,
includeTables: true,
includeDependencies: true,
+ includeAreas: true,
});
if (diagram) {
@@ -1418,6 +1553,7 @@ export const ChartDBProvider: React.FC<
tables,
relationships,
dependencies,
+ areas,
currentDiagram,
schemas,
filteredSchemas,
@@ -1465,6 +1601,13 @@ export const ChartDBProvider: React.FC<
removeDependency,
removeDependencies,
updateDependency,
+ createArea,
+ addArea,
+ addAreas,
+ getArea,
+ removeArea,
+ removeAreas,
+ updateArea,
}}
>
{children}
diff --git a/src/context/history-context/history-provider.tsx b/src/context/history-context/history-provider.tsx
index 6e50d40d..02a9ed57 100644
--- a/src/context/history-context/history-provider.tsx
+++ b/src/context/history-context/history-provider.tsx
@@ -33,6 +33,9 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({
removeIndex,
updateIndex,
removeRelationships,
+ addAreas,
+ removeAreas,
+ updateArea,
} = useChartDB();
const redoActionHandlers = useMemo(
@@ -107,6 +110,15 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({
updateHistory: false,
});
},
+ addAreas: ({ redoData: { areas } }) => {
+ return addAreas(areas, { updateHistory: false });
+ },
+ removeAreas: ({ redoData: { areaIds } }) => {
+ return removeAreas(areaIds, { updateHistory: false });
+ },
+ updateArea: ({ redoData: { areaId, area } }) => {
+ return updateArea(areaId, area, { updateHistory: false });
+ },
}),
[
addTables,
@@ -126,6 +138,9 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({
addDependencies,
removeDependencies,
updateDependency,
+ addAreas,
+ removeAreas,
+ updateArea,
]
);
@@ -215,6 +230,15 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({
updateHistory: false,
});
},
+ addAreas: ({ undoData: { areaIds } }) => {
+ return removeAreas(areaIds, { updateHistory: false });
+ },
+ removeAreas: ({ undoData: { areas } }) => {
+ return addAreas(areas, { updateHistory: false });
+ },
+ updateArea: ({ undoData: { areaId, area } }) => {
+ return updateArea(areaId, area, { updateHistory: false });
+ },
}),
[
addTables,
@@ -234,6 +258,9 @@ export const HistoryProvider: React.FC<React.PropsWithChildren> = ({
addDependencies,
removeDependencies,
updateDependency,
+ addAreas,
+ removeAreas,
+ updateArea,
]
);
diff --git a/src/context/history-context/redo-undo-action.ts b/src/context/history-context/redo-undo-action.ts
index e68d0854..cf7b8385 100644
--- a/src/context/history-context/redo-undo-action.ts
+++ b/src/context/history-context/redo-undo-action.ts
@@ -4,6 +4,7 @@ import type { DBField } from '@/lib/domain/db-field';
import type { DBIndex } from '@/lib/domain/db-index';
import type { DBRelationship } from '@/lib/domain/db-relationship';
import type { DBDependency } from '@/lib/domain/db-dependency';
+import type { Area } from '@/lib/domain/area';
type Action = keyof ChartDBContext;
@@ -123,6 +124,24 @@ type RedoUndoActionRemoveDependencies = RedoUndoActionBase<
{ dependencies: DBDependency[] }
>;
+type RedoUndoActionAddAreas = RedoUndoActionBase<
+ 'addAreas',
+ { areas: Area[] },
+ { areaIds: string[] }
+>;
+
+type RedoUndoActionUpdateArea = RedoUndoActionBase<
+ 'updateArea',
+ { areaId: string; area: Partial<Area> },
+ { areaId: string; area: Partial<Area> }
+>;
+
+type RedoUndoActionRemoveAreas = RedoUndoActionBase<
+ 'removeAreas',
+ { areaIds: string[] },
+ { areas: Area[] }
+>;
+
export type RedoUndoAction =
| RedoUndoActionAddTables
| RedoUndoActionRemoveTables
@@ -140,7 +159,10 @@ export type RedoUndoAction =
| RedoUndoActionRemoveRelationships
| RedoUndoActionAddDependencies
| RedoUndoActionUpdateDependency
- | RedoUndoActionRemoveDependencies;
+ | RedoUndoActionRemoveDependencies
+ | RedoUndoActionAddAreas
+ | RedoUndoActionUpdateArea
+ | RedoUndoActionRemoveAreas;
export type RedoActionData<T extends Action> = Extract<
RedoUndoAction,
diff --git a/src/context/layout-context/layout-context.tsx b/src/context/layout-context/layout-context.tsx
index 5b597d15..5875e35c 100644
--- a/src/context/layout-context/layout-context.tsx
+++ b/src/context/layout-context/layout-context.tsx
@@ -1,7 +1,11 @@
import { emptyFn } from '@/lib/utils';
import { createContext } from 'react';
-export type SidebarSection = 'tables' | 'relationships' | 'dependencies';
+export type SidebarSection =
+ | 'tables'
+ | 'relationships'
+ | 'dependencies'
+ | 'areas';
export interface LayoutContext {
openedTableInSidebar: string | undefined;
@@ -16,6 +20,10 @@ export interface LayoutContext {
openDependencyFromSidebar: (dependencyId: string) => void;
closeAllDependenciesInSidebar: () => void;
+ openedAreaInSidebar: string | undefined;
+ openAreaFromSidebar: (areaId: string) => void;
+ closeAllAreasInSidebar: () => void;
+
selectedSidebarSection: SidebarSection;
selectSidebarSection: (section: SidebarSection) => void;
@@ -41,6 +49,10 @@ export const layoutContext = createContext<LayoutContext>({
openDependencyFromSidebar: emptyFn,
closeAllDependenciesInSidebar: emptyFn,
+ openedAreaInSidebar: undefined,
+ openAreaFromSidebar: emptyFn,
+ closeAllAreasInSidebar: emptyFn,
+
selectSidebarSection: emptyFn,
openTableFromSidebar: emptyFn,
closeAllTablesInSidebar: emptyFn,
diff --git a/src/context/layout-context/layout-provider.tsx b/src/context/layout-context/layout-provider.tsx
index 32bed103..b7cdc07a 100644
--- a/src/context/layout-context/layout-provider.tsx
+++ b/src/context/layout-context/layout-provider.tsx
@@ -14,6 +14,9 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
React.useState<string | undefined>();
const [openedDependencyInSidebar, setOpenedDependencyInSidebar] =
React.useState<string | undefined>();
+ const [openedAreaInSidebar, setOpenedAreaInSidebar] = React.useState<
+ string | undefined
+ >();
const [selectedSidebarSection, setSelectedSidebarSection] =
React.useState<SidebarSection>('tables');
const [isSidePanelShowed, setIsSidePanelShowed] =
@@ -30,6 +33,9 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
const closeAllDependenciesInSidebar: LayoutContext['closeAllDependenciesInSidebar'] =
() => setOpenedDependencyInSidebar('');
+ const closeAllAreasInSidebar: LayoutContext['closeAllAreasInSidebar'] =
+ () => setOpenedAreaInSidebar('');
+
const hideSidePanel: LayoutContext['hideSidePanel'] = () =>
setIsSidePanelShowed(false);
@@ -62,6 +68,14 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
setOpenedDependencyInSidebar(dependencyId);
};
+ const openAreaFromSidebar: LayoutContext['openAreaFromSidebar'] = (
+ areaId
+ ) => {
+ showSidePanel();
+ setSelectedSidebarSection('areas');
+ setOpenedAreaInSidebar(areaId);
+ };
+
const openSelectSchema: LayoutContext['openSelectSchema'] = () =>
setIsSelectSchemaOpen(true);
@@ -88,6 +102,9 @@ export const LayoutProvider: React.FC<React.PropsWithChildren> = ({
openedDependencyInSidebar,
openDependencyFromSidebar,
closeAllDependenciesInSidebar,
+ openedAreaInSidebar,
+ openAreaFromSidebar,
+ closeAllAreasInSidebar,
}}
>
{children}
diff --git a/src/context/storage-context/storage-context.tsx b/src/context/storage-context/storage-context.tsx
index 94a4267c..06148ab1 100644
--- a/src/context/storage-context/storage-context.tsx
+++ b/src/context/storage-context/storage-context.tsx
@@ -5,6 +5,7 @@ import type { DBRelationship } from '@/lib/domain/db-relationship';
import type { DBTable } from '@/lib/domain/db-table';
import type { ChartDBConfig } from '@/lib/domain/config';
import type { DBDependency } from '@/lib/domain/db-dependency';
+import type { Area } from '@/lib/domain/area';
export interface StorageContext {
// Config operations
@@ -17,6 +18,7 @@ export interface StorageContext {
includeTables?: boolean;
includeRelationships?: boolean;
includeDependencies?: boolean;
+ includeAreas?: boolean;
}) => Promise<Diagram[]>;
getDiagram: (
id: string,
@@ -24,6 +26,7 @@ export interface StorageContext {
includeTables?: boolean;
includeRelationships?: boolean;
includeDependencies?: boolean;
+ includeAreas?: boolean;
}
) => Promise<Diagram | undefined>;
updateDiagram: (params: {
@@ -86,6 +89,20 @@ export interface StorageContext {
}) => Promise<void>;
listDependencies: (diagramId: string) => Promise<DBDependency[]>;
deleteDiagramDependencies: (diagramId: string) => Promise<void>;
+
+ // Area operations
+ addArea: (params: { diagramId: string; area: Area }) => Promise<void>;
+ getArea: (params: {
+ diagramId: string;
+ id: string;
+ }) => Promise<Area | undefined>;
+ updateArea: (params: {
+ id: string;
+ attributes: Partial<Area>;
+ }) => Promise<void>;
+ deleteArea: (params: { diagramId: string; id: string }) => Promise<void>;
+ listAreas: (diagramId: string) => Promise<Area[]>;
+ deleteDiagramAreas: (diagramId: string) => Promise<void>;
}
export const storageInitialValue: StorageContext = {
@@ -119,6 +136,13 @@ export const storageInitialValue: StorageContext = {
deleteDependency: emptyFn,
listDependencies: emptyFn,
deleteDiagramDependencies: emptyFn,
+
+ addArea: emptyFn,
+ getArea: emptyFn,
+ updateArea: emptyFn,
+ deleteArea: emptyFn,
+ listAreas: emptyFn,
+ deleteDiagramAreas: emptyFn,
};
export const storageContext =
diff --git a/src/context/storage-context/storage-provider.tsx b/src/context/storage-context/storage-provider.tsx
index aebebbd0..3602a192 100644
--- a/src/context/storage-context/storage-provider.tsx
+++ b/src/context/storage-context/storage-provider.tsx
@@ -8,6 +8,7 @@ import type { DBRelationship } from '@/lib/domain/db-relationship';
import { determineCardinalities } from '@/lib/domain/db-relationship';
import type { ChartDBConfig } from '@/lib/domain/config';
import type { DBDependency } from '@/lib/domain/db-dependency';
+import type { Area } from '@/lib/domain/area';
export const StorageProvider: React.FC<React.PropsWithChildren> = ({
children,
@@ -29,6 +30,10 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
DBDependency & { diagramId: string },
'id' // primary key "id" (for the typings only)
>;
+ areas: EntityTable<
+ Area & { diagramId: string },
+ 'id' // primary key "id" (for the typings only)
+ >;
config: EntityTable<
ChartDBConfig & { id: number },
'id' // primary key "id" (for the typings only)
@@ -148,6 +153,19 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
})
);
+ db.version(10).stores({
+ diagrams:
+ '++id, name, databaseType, databaseEdition, createdAt, updatedAt',
+ db_tables:
+ '++id, diagramId, name, schema, x, y, fields, indexes, color, createdAt, width, comment, isView, isMaterializedView, order',
+ db_relationships:
+ '++id, diagramId, name, sourceSchema, sourceTableId, targetSchema, targetTableId, sourceFieldId, targetFieldId, type, createdAt',
+ db_dependencies:
+ '++id, diagramId, schema, tableId, dependentSchema, dependentTableId, createdAt',
+ areas: '++id, diagramId, name, x, y, width, height, color',
+ config: '++id, defaultDiagramId',
+ });
+
db.on('ready', async () => {
const config = await getConfig();
@@ -209,6 +227,11 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
)
);
+ const areas = diagram.areas ?? [];
+ promises.push(
+ ...areas.map((area) => addArea({ diagramId: diagram.id, area }))
+ );
+
await Promise.all(promises);
};
@@ -217,10 +240,12 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
includeTables?: boolean;
includeRelationships?: boolean;
includeDependencies?: boolean;
+ includeAreas?: boolean;
} = {
includeRelationships: false,
includeTables: false,
includeDependencies: false,
+ includeAreas: false,
}
): Promise<Diagram[]> => {
let diagrams = await db.diagrams.toArray();
@@ -252,6 +277,15 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
);
}
+ if (options.includeAreas) {
+ diagrams = await Promise.all(
+ diagrams.map(async (diagram) => {
+ diagram.areas = await listAreas(diagram.id);
+ return diagram;
+ })
+ );
+ }
+
return diagrams;
};
@@ -261,10 +295,12 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
includeTables?: boolean;
includeRelationships?: boolean;
includeDependencies?: boolean;
+ includeAreas?: boolean;
} = {
includeRelationships: false,
includeTables: false,
includeDependencies: false,
+ includeAreas: false,
}
): Promise<Diagram | undefined> => {
const diagram = await db.diagrams.get(id);
@@ -285,6 +321,10 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
diagram.dependencies = await listDependencies(id);
}
+ if (options.includeAreas) {
+ diagram.areas = await listAreas(id);
+ }
+
return diagram;
};
@@ -323,6 +363,7 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
db.db_tables.where('diagramId').equals(id).delete(),
db.db_relationships.where('diagramId').equals(id).delete(),
db.db_dependencies.where('diagramId').equals(id).delete(),
+ db.areas.where('diagramId').equals(id).delete(),
]);
};
@@ -504,6 +545,41 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
.delete();
};
+ const addArea: StorageContext['addArea'] = async ({ area, diagramId }) => {
+ await db.areas.add({
+ ...area,
+ diagramId,
+ });
+ };
+
+ const getArea: StorageContext['getArea'] = async ({ diagramId, id }) => {
+ return await db.areas.get({ id, diagramId });
+ };
+
+ const updateArea: StorageContext['updateArea'] = async ({
+ id,
+ attributes,
+ }) => {
+ await db.areas.update(id, attributes);
+ };
+
+ const deleteArea: StorageContext['deleteArea'] = async ({
+ diagramId,
+ id,
+ }) => {
+ await db.areas.where({ id, diagramId }).delete();
+ };
+
+ const listAreas: StorageContext['listAreas'] = async (diagramId) => {
+ return await db.areas.where('diagramId').equals(diagramId).toArray();
+ };
+
+ const deleteDiagramAreas: StorageContext['deleteDiagramAreas'] = async (
+ diagramId
+ ) => {
+ await db.areas.where('diagramId').equals(diagramId).delete();
+ };
+
return (
<storageContext.Provider
value={{
@@ -533,6 +609,12 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({
deleteDependency,
listDependencies,
deleteDiagramDependencies,
+ addArea,
+ getArea,
+ updateArea,
+ deleteArea,
+ listAreas,
+ deleteDiagramAreas,
}}
>
{children}
diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts
index b64ce2f9..5962fa8d 100644
--- a/src/i18n/locales/ar.ts
+++ b/src/i18n/locales/ar.ts
@@ -210,6 +210,27 @@ export const ar: LanguageTranslation = {
description: 'إنشاء اعتماد للبدء',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -400,6 +421,8 @@ export const ar: LanguageTranslation = {
canvas_context_menu: {
new_table: 'جدول جديد',
new_relationship: 'علاقة جديدة',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/bn.ts b/src/i18n/locales/bn.ts
index 8ab68a71..2621c5e1 100644
--- a/src/i18n/locales/bn.ts
+++ b/src/i18n/locales/bn.ts
@@ -211,6 +211,27 @@ export const bn: LanguageTranslation = {
description: 'এই অংশে কোনো নির্ভরতা উপলব্ধ নেই।',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -404,6 +425,8 @@ export const bn: LanguageTranslation = {
canvas_context_menu: {
new_table: 'নতুন টেবিল',
new_relationship: 'নতুন সম্পর্ক',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts
index b22c889a..12de569f 100644
--- a/src/i18n/locales/de.ts
+++ b/src/i18n/locales/de.ts
@@ -213,6 +213,27 @@ export const de: LanguageTranslation = {
description: 'Erstellen Sie eine Ansicht, um zu beginnen',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -407,6 +428,8 @@ export const de: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Neue Tabelle',
new_relationship: 'Neue Beziehung',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts
index 8c7fc086..e4017642 100644
--- a/src/i18n/locales/en.ts
+++ b/src/i18n/locales/en.ts
@@ -206,6 +206,26 @@ export const en = {
description: 'Create a view to get started',
},
},
+
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -398,6 +418,7 @@ export const en = {
canvas_context_menu: {
new_table: 'New Table',
new_relationship: 'New Relationship',
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts
index 1f0980a8..b2548756 100644
--- a/src/i18n/locales/es.ts
+++ b/src/i18n/locales/es.ts
@@ -201,6 +201,27 @@ export const es: LanguageTranslation = {
description: 'Crea una vista para comenzar',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -405,6 +426,8 @@ export const es: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Nueva Tabla',
new_relationship: 'Nueva Relación',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts
index 48b4ef71..223ab436 100644
--- a/src/i18n/locales/fr.ts
+++ b/src/i18n/locales/fr.ts
@@ -199,6 +199,27 @@ export const fr: LanguageTranslation = {
description: 'Créez une vue pour commencer',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -402,6 +423,8 @@ export const fr: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Nouvelle Table',
new_relationship: 'Nouvelle Relation',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/gu.ts b/src/i18n/locales/gu.ts
index fbc8180b..ed3f8ac3 100644
--- a/src/i18n/locales/gu.ts
+++ b/src/i18n/locales/gu.ts
@@ -212,6 +212,27 @@ export const gu: LanguageTranslation = {
description: 'આ વિભાગમાં કોઈ નિર્ભરતા ઉપલબ્ધ નથી.',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -404,6 +425,8 @@ export const gu: LanguageTranslation = {
canvas_context_menu: {
new_table: 'નવું ટેબલ',
new_relationship: 'નવો સંબંધ',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/hi.ts b/src/i18n/locales/hi.ts
index b454947c..1675faaf 100644
--- a/src/i18n/locales/hi.ts
+++ b/src/i18n/locales/hi.ts
@@ -212,6 +212,27 @@ export const hi: LanguageTranslation = {
description: 'इस अनुभाग में कोई निर्भरता उपलब्ध नहीं है।',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -407,6 +428,8 @@ export const hi: LanguageTranslation = {
canvas_context_menu: {
new_table: 'नई तालिका',
new_relationship: 'नया संबंध',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/id_ID.ts b/src/i18n/locales/id_ID.ts
index e667df87..5fc30442 100644
--- a/src/i18n/locales/id_ID.ts
+++ b/src/i18n/locales/id_ID.ts
@@ -210,6 +210,27 @@ export const id_ID: LanguageTranslation = {
description: 'Buat tampilan untuk memulai',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -403,6 +424,8 @@ export const id_ID: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Tabel Baru',
new_relationship: 'Hubungan Baru',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts
index fdaa722b..dcfbc595 100644
--- a/src/i18n/locales/ja.ts
+++ b/src/i18n/locales/ja.ts
@@ -216,6 +216,27 @@ export const ja: LanguageTranslation = {
description: 'Create a view to get started',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -411,6 +432,8 @@ export const ja: LanguageTranslation = {
canvas_context_menu: {
new_table: '新しいテーブル',
new_relationship: '新しいリレーションシップ',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/ko_KR.ts b/src/i18n/locales/ko_KR.ts
index a458217d..ab14aa1e 100644
--- a/src/i18n/locales/ko_KR.ts
+++ b/src/i18n/locales/ko_KR.ts
@@ -210,6 +210,27 @@ export const ko_KR: LanguageTranslation = {
description: '뷰 테이블을 만들어 시작하세요.',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -400,6 +421,8 @@ export const ko_KR: LanguageTranslation = {
canvas_context_menu: {
new_table: '새 테이블',
new_relationship: '새 연관관계',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/mr.ts b/src/i18n/locales/mr.ts
index 79a7f4aa..b62f5a1e 100644
--- a/src/i18n/locales/mr.ts
+++ b/src/i18n/locales/mr.ts
@@ -215,6 +215,27 @@ export const mr: LanguageTranslation = {
description: 'सुरू करण्यासाठी एक दृश्य तयार करा',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -413,6 +434,8 @@ export const mr: LanguageTranslation = {
canvas_context_menu: {
new_table: 'नवीन टेबल',
new_relationship: 'नवीन रिलेशनशिप',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/ne.ts b/src/i18n/locales/ne.ts
index 124b3595..b2e7a5ed 100644
--- a/src/i18n/locales/ne.ts
+++ b/src/i18n/locales/ne.ts
@@ -212,6 +212,27 @@ export const ne: LanguageTranslation = {
'डिपेन्डेन्सीहरू देखाउनका लागि एक व्यू बनाउनुहोस्',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -407,6 +428,8 @@ export const ne: LanguageTranslation = {
canvas_context_menu: {
new_table: 'नयाँ तालिका',
new_relationship: 'नयाँ सम्बन्ध',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/pt_BR.ts b/src/i18n/locales/pt_BR.ts
index 9b6dc4af..36949600 100644
--- a/src/i18n/locales/pt_BR.ts
+++ b/src/i18n/locales/pt_BR.ts
@@ -211,6 +211,27 @@ export const pt_BR: LanguageTranslation = {
description: 'Crie uma visualização para começar',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -405,6 +426,8 @@ export const pt_BR: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Nova Tabela',
new_relationship: 'Novo Relacionamento',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts
index 2daba204..8c64469a 100644
--- a/src/i18n/locales/ru.ts
+++ b/src/i18n/locales/ru.ts
@@ -210,6 +210,27 @@ export const ru: LanguageTranslation = {
description: 'Создайте представление, чтобы начать',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -402,6 +423,8 @@ export const ru: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Создать таблицу',
new_relationship: 'Создать отношение',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/te.ts b/src/i18n/locales/te.ts
index 8299bb20..b3d4a359 100644
--- a/src/i18n/locales/te.ts
+++ b/src/i18n/locales/te.ts
@@ -212,6 +212,27 @@ export const te: LanguageTranslation = {
description: 'ప్రారంభించడానికి ఒక వీక్షణ సృష్టించండి',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -409,6 +430,8 @@ export const te: LanguageTranslation = {
canvas_context_menu: {
new_table: 'కొత్త పట్టిక',
new_relationship: 'కొత్త సంబంధం',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts
index 9a6928e0..16a3394e 100644
--- a/src/i18n/locales/tr.ts
+++ b/src/i18n/locales/tr.ts
@@ -211,6 +211,27 @@ export const tr: LanguageTranslation = {
description: 'Başlamak için bir görünüm oluşturun',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
zoom_in: 'Yakınlaştır',
@@ -394,6 +415,8 @@ export const tr: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Yeni Tablo',
new_relationship: 'Yeni İlişki',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
edit_table: 'Tabloyu Düzenle',
diff --git a/src/i18n/locales/uk.ts b/src/i18n/locales/uk.ts
index a374e08b..2f6ecf6d 100644
--- a/src/i18n/locales/uk.ts
+++ b/src/i18n/locales/uk.ts
@@ -209,6 +209,27 @@ export const uk: LanguageTranslation = {
description: 'Створіть подання, щоб почати',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -400,6 +421,8 @@ export const uk: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Нова таблиця',
new_relationship: 'Новий звʼязок',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts
index 17949910..05c67ee6 100644
--- a/src/i18n/locales/vi.ts
+++ b/src/i18n/locales/vi.ts
@@ -210,6 +210,27 @@ export const vi: LanguageTranslation = {
description: 'Tạo bảng xem phụ thuộc để bắt đầu',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -401,6 +422,8 @@ export const vi: LanguageTranslation = {
canvas_context_menu: {
new_table: 'Tạo bảng mới',
new_relationship: 'Tạo quan hệ mới',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/zh_CN.ts b/src/i18n/locales/zh_CN.ts
index 3b4d37fc..30ba6bb1 100644
--- a/src/i18n/locales/zh_CN.ts
+++ b/src/i18n/locales/zh_CN.ts
@@ -207,6 +207,27 @@ export const zh_CN: LanguageTranslation = {
description: '创建视图以开始',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -397,6 +418,8 @@ export const zh_CN: LanguageTranslation = {
canvas_context_menu: {
new_table: '新建表',
new_relationship: '新建关系',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/i18n/locales/zh_TW.ts b/src/i18n/locales/zh_TW.ts
index a43cc7d0..89cddea8 100644
--- a/src/i18n/locales/zh_TW.ts
+++ b/src/i18n/locales/zh_TW.ts
@@ -207,6 +207,27 @@ export const zh_TW: LanguageTranslation = {
description: '請建立檢視以開始',
},
},
+
+ // TODO: Translate
+ areas_section: {
+ areas: 'Areas',
+ add_area: 'Add Area',
+ filter: 'Filter',
+ clear: 'Clear Filter',
+ no_results: 'No areas found matching your filter.',
+
+ area: {
+ area_actions: {
+ title: 'Area Actions',
+ edit_name: 'Edit Name',
+ delete_area: 'Delete Area',
+ },
+ },
+ empty_state: {
+ title: 'No areas',
+ description: 'Create an area to get started',
+ },
+ },
},
toolbar: {
@@ -396,6 +417,8 @@ export const zh_TW: LanguageTranslation = {
canvas_context_menu: {
new_table: '新建表格',
new_relationship: '新建關聯',
+ // TODO: Translate
+ new_area: 'New Area',
},
table_node_context_menu: {
diff --git a/src/lib/domain/area.ts b/src/lib/domain/area.ts
new file mode 100644
index 00000000..7e070159
--- /dev/null
+++ b/src/lib/domain/area.ts
@@ -0,0 +1,23 @@
+import { z } from 'zod';
+
+export interface Area {
+ id: string;
+ name: string;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ color: string;
+ order?: number;
+}
+
+export const areaSchema: z.ZodType<Area> = z.object({
+ id: z.string(),
+ name: z.string(),
+ x: z.number(),
+ y: z.number(),
+ width: z.number(),
+ height: z.number(),
+ color: z.string(),
+ order: z.number().optional(),
+});
diff --git a/src/lib/domain/diagram.ts b/src/lib/domain/diagram.ts
index 347f6f61..3432ade8 100644
--- a/src/lib/domain/diagram.ts
+++ b/src/lib/domain/diagram.ts
@@ -19,6 +19,7 @@ import {
dbTableSchema,
} from './db-table';
import { generateDiagramId } from '@/lib/utils';
+import type { Area } from './area';
export interface Diagram {
id: string;
name: string;
@@ -27,6 +28,7 @@ export interface Diagram {
tables?: DBTable[];
relationships?: DBRelationship[];
dependencies?: DBDependency[];
+ areas?: Area[];
createdAt: Date;
updatedAt: Date;
}
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index 7a205f67..229e51bc 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -101,3 +101,25 @@ export const sha256 = async (message: string): Promise<string> => {
return hashHex;
};
+
+export function mergeRefs<T>(
+ ...inputRefs: (React.Ref<T> | undefined)[]
+): React.Ref<T> | React.RefCallback<T> {
+ const filteredInputRefs = inputRefs.filter(Boolean);
+
+ if (filteredInputRefs.length <= 1) {
+ const firstRef = filteredInputRefs[0];
+
+ return firstRef || null;
+ }
+
+ return function mergedRefs(ref) {
+ for (const inputRef of filteredInputRefs) {
+ if (typeof inputRef === 'function') {
+ inputRef(ref);
+ } else if (inputRef) {
+ (inputRef as React.MutableRefObject<T | null>).current = ref;
+ }
+ }
+ };
+}
diff --git a/src/pages/editor-page/canvas/area-node/area-node.tsx b/src/pages/editor-page/canvas/area-node/area-node.tsx
new file mode 100644
index 00000000..1f3ce0a6
--- /dev/null
+++ b/src/pages/editor-page/canvas/area-node/area-node.tsx
@@ -0,0 +1,134 @@
+import React, { useCallback, useState } from 'react';
+import type { NodeProps, Node } from '@xyflow/react';
+import { NodeResizer } from '@xyflow/react';
+import type { Area } from '@/lib/domain/area';
+import { useChartDB } from '@/hooks/use-chartdb';
+import { Input } from '@/components/input/input';
+import { useClickAway, useKeyPressEvent } from 'react-use';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/tooltip/tooltip';
+import { useTranslation } from 'react-i18next';
+import { cn } from '@/lib/utils';
+import { Check, GripVertical } from 'lucide-react';
+import { Button } from '@/components/button/button';
+import { useLayout } from '@/hooks/use-layout';
+
+export type AreaNodeType = Node<
+ {
+ area: Area;
+ },
+ 'area'
+>;
+
+export const AreaNode: React.FC<NodeProps<AreaNodeType>> = React.memo(
+ ({ selected, dragging, data: { area } }) => {
+ const { updateArea, readonly } = useChartDB();
+ const { t } = useTranslation();
+ const [editMode, setEditMode] = useState(false);
+ const [areaName, setAreaName] = useState(area.name);
+ const inputRef = React.useRef<HTMLInputElement>(null);
+ const { openAreaFromSidebar, selectSidebarSection } = useLayout();
+
+ const focused = !!selected && !dragging;
+
+ const editAreaName = useCallback(() => {
+ if (!editMode) return;
+ if (areaName.trim()) {
+ updateArea(area.id, { name: areaName.trim() });
+ }
+ setEditMode(false);
+ }, [areaName, area.id, updateArea, editMode]);
+
+ const abortEdit = useCallback(() => {
+ setEditMode(false);
+ setAreaName(area.name);
+ }, [area.name]);
+
+ const openAreaInEditor = useCallback(() => {
+ selectSidebarSection('areas');
+ openAreaFromSidebar(area.id);
+ }, [selectSidebarSection, openAreaFromSidebar, area.id]);
+
+ useClickAway(inputRef, editAreaName);
+ useKeyPressEvent('Enter', editAreaName);
+ useKeyPressEvent('Escape', abortEdit);
+
+ const enterEditMode = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setEditMode(true);
+ };
+
+ return (
+ <div
+ className={cn(
+ 'flex h-full flex-col rounded-md border-2 shadow-sm',
+ selected ? 'border-pink-600' : 'border-transparent'
+ )}
+ style={{
+ backgroundColor: `${area.color}15`,
+ borderColor: selected ? undefined : area.color,
+ }}
+ onClick={(e) => {
+ if (e.detail === 2) {
+ openAreaInEditor();
+ }
+ }}
+ >
+ <NodeResizer
+ isVisible={focused}
+ lineClassName="!border-4 !border-transparent"
+ handleClassName="!h-3 !w-3 !rounded-full !bg-pink-600"
+ />
+ <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 text-slate-700 opacity-60 dark:text-slate-300" />
+
+ {editMode && !readonly ? (
+ <div className="flex w-full items-center">
+ <Input
+ ref={inputRef}
+ autoFocus
+ type="text"
+ placeholder={area.name}
+ value={areaName}
+ onClick={(e) => e.stopPropagation()}
+ onChange={(e) =>
+ setAreaName(e.target.value)
+ }
+ className="h-6 bg-white/70 focus-visible:ring-0 dark:bg-slate-900/70"
+ />
+ <Button
+ variant="ghost"
+ className="ml-1 size-6 p-0 hover:bg-white/20"
+ onClick={editAreaName}
+ >
+ <Check className="size-3.5 text-slate-700 dark:text-slate-300" />
+ </Button>
+ </div>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div
+ className="text-editable max-w-[200px] cursor-text truncate px-1 py-0.5 text-base font-semibold text-slate-700 dark:text-slate-300"
+ onDoubleClick={enterEditMode}
+ >
+ {area.name}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {t('tool_tips.double_click_to_edit')}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ </div>
+ <div className="flex-1" />
+ </div>
+ );
+ }
+);
+
+AreaNode.displayName = 'AreaNode';
diff --git a/src/pages/editor-page/canvas/canvas-context-menu.tsx b/src/pages/editor-page/canvas/canvas-context-menu.tsx
index 15d3e713..b547ff72 100644
--- a/src/pages/editor-page/canvas/canvas-context-menu.tsx
+++ b/src/pages/editor-page/canvas/canvas-context-menu.tsx
@@ -10,11 +10,13 @@ import { useDialog } from '@/hooks/use-dialog';
import { useReactFlow } from '@xyflow/react';
import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { Table, Workflow, Group } from 'lucide-react';
export const CanvasContextMenu: React.FC<React.PropsWithChildren> = ({
children,
}) => {
- const { createTable, filteredSchemas, schemas, readonly } = useChartDB();
+ const { createTable, filteredSchemas, schemas, readonly, createArea } =
+ useChartDB();
const { openCreateRelationshipDialog, openTableSchemaDialog } = useDialog();
const { screenToFlowPosition } = useReactFlow();
const { t } = useTranslation();
@@ -61,6 +63,21 @@ export const CanvasContextMenu: React.FC<React.PropsWithChildren> = ({
]
);
+ const createAreaHandler = useCallback(
+ (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
+ const position = screenToFlowPosition({
+ x: event.clientX,
+ y: event.clientY,
+ });
+
+ createArea({
+ x: position.x,
+ y: position.y,
+ });
+ },
+ [createArea, screenToFlowPosition]
+ );
+
const createRelationshipHandler = useCallback(() => {
openCreateRelationshipDialog();
}, [openCreateRelationshipDialog]);
@@ -73,11 +90,26 @@ export const CanvasContextMenu: React.FC<React.PropsWithChildren> = ({
<ContextMenu>
<ContextMenuTrigger>{children}</ContextMenuTrigger>
<ContextMenuContent>
- <ContextMenuItem onClick={createTableHandler}>
+ <ContextMenuItem
+ onClick={createTableHandler}
+ className="flex justify-between gap-4"
+ >
{t('canvas_context_menu.new_table')}
+ <Table className="size-3.5" />
</ContextMenuItem>
- <ContextMenuItem onClick={createRelationshipHandler}>
+ <ContextMenuItem
+ onClick={createRelationshipHandler}
+ className="flex justify-between gap-4"
+ >
{t('canvas_context_menu.new_relationship')}
+ <Workflow className="size-3.5" />
+ </ContextMenuItem>
+ <ContextMenuItem
+ onClick={createAreaHandler}
+ className="flex justify-between gap-4"
+ >
+ {t('canvas_context_menu.new_area')}
+ <Group className="size-3.5" />
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
diff --git a/src/pages/editor-page/canvas/canvas.tsx b/src/pages/editor-page/canvas/canvas.tsx
index 1c92a46a..44789c8e 100644
--- a/src/pages/editor-page/canvas/canvas.tsx
+++ b/src/pages/editor-page/canvas/canvas.tsx
@@ -12,6 +12,9 @@ import type {
NodeDimensionChange,
OnEdgesChange,
OnNodesChange,
+ NodeTypes,
+ EdgeTypes,
+ NodeChange,
} from '@xyflow/react';
import {
ReactFlow,
@@ -28,8 +31,8 @@ import '@xyflow/react/dist/style.css';
import equal from 'fast-deep-equal';
import type { TableNodeType } from './table-node/table-node';
import { MIN_TABLE_SIZE, TableNode } from './table-node/table-node';
-import type { RelationshipEdgeType } from './relationship-edge';
-import { RelationshipEdge } from './relationship-edge';
+import type { RelationshipEdgeType } from './relationship-edge/relationship-edge';
+import { RelationshipEdge } from './relationship-edge/relationship-edge';
import { useChartDB } from '@/hooks/use-chartdb';
import {
LEFT_HANDLE_ID_PREFIX,
@@ -64,8 +67,8 @@ import type { Graph } from '@/lib/graph';
import { removeVertex } from '@/lib/graph';
import type { ChartDBEvent } from '@/context/chartdb-context/chartdb-context';
import { cn, debounce, getOperatingSystem } from '@/lib/utils';
-import type { DependencyEdgeType } from './dependency-edge';
-import { DependencyEdge } from './dependency-edge';
+import type { DependencyEdgeType } from './dependency-edge/dependency-edge';
+import { DependencyEdge } from './dependency-edge/dependency-edge';
import {
BOTTOM_SOURCE_HANDLE_ID_PREFIX,
TARGET_DEP_PREFIX,
@@ -74,16 +77,26 @@ import {
import { DatabaseType } from '@/lib/domain/database-type';
import { useAlert } from '@/context/alert-context/alert-context';
import { useCanvas } from '@/hooks/use-canvas';
+import type { AreaNodeType } from './area-node/area-node';
+import { AreaNode } from './area-node/area-node';
+import type { Area } from '@/lib/domain/area';
export type EdgeType = RelationshipEdgeType | DependencyEdgeType;
+export type NodeType = TableNodeType | AreaNodeType;
+
type AddEdgeParams = Parameters<typeof addEdge<EdgeType>>[0];
-const edgeTypes = {
+const edgeTypes: EdgeTypes = {
'relationship-edge': RelationshipEdge,
'dependency-edge': DependencyEdge,
};
+const nodeTypes: NodeTypes = {
+ table: TableNode,
+ area: AreaNode,
+};
+
const initialEdges: EdgeType[] = [];
const tableToTableNode = (
@@ -101,6 +114,16 @@ const tableToTableNode = (
hidden: !shouldShowTablesBySchemaFilter(table, filteredSchemas),
});
+const areaToAreaNode = (area: Area): AreaNodeType => ({
+ id: area.id,
+ type: 'area',
+ position: { x: area.x, y: area.y },
+ data: { area },
+ width: area.width,
+ height: area.height,
+ zIndex: -10,
+});
+
export interface CanvasProps {
initialTables: DBTable[];
}
@@ -115,6 +138,7 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
const { t } = useTranslation();
const {
tables,
+ areas,
relationships,
createRelationship,
createDependency,
@@ -127,6 +151,8 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
events,
dependencies,
readonly,
+ removeArea,
+ updateArea,
} = useChartDB();
const { showSidePanel } = useLayout();
const { effectiveTheme } = useTheme();
@@ -134,7 +160,6 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
useLocalConfig();
const { showAlert } = useAlert();
const { isMd: isDesktop } = useBreakpoint('md');
- const nodeTypes = useMemo(() => ({ table: TableNode }), []);
const [highlightOverlappingTables, setHighlightOverlappingTables] =
useState(false);
const { reorderTables, fitView, setOverlapGraph, overlapGraph } =
@@ -142,7 +167,7 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
const [isInitialLoadingNodes, setIsInitialLoadingNodes] = useState(true);
- const [nodes, setNodes, onNodesChange] = useNodesState<TableNodeType>(
+ const [nodes, setNodes, onNodesChange] = useNodesState<NodeType>(
initialTables.map((table) => tableToTableNode(table, filteredSchemas))
);
const [edges, setEdges, onEdgesChange] =
@@ -299,8 +324,8 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
}, [selectedRelationshipIds, selectedTableIds, setEdges, getEdges]);
useEffect(() => {
- setNodes(
- tables.map((table) => {
+ setNodes([
+ ...tables.map((table) => {
const isOverlapping =
(overlapGraph.graph.get(table.id) ?? []).length > 0;
const node = tableToTableNode(table, filteredSchemas);
@@ -313,10 +338,12 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
highlightOverlappingTables,
},
};
- })
- );
+ }),
+ ...areas.map(areaToAreaNode),
+ ]);
}, [
tables,
+ areas,
setNodes,
filteredSchemas,
overlapGraph.lastUpdated,
@@ -463,17 +490,43 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
let newOverlappingGraph: Graph<string> = overlapGraph;
for (const change of positionChanges) {
+ const node = getNode(change.id) as NodeType;
+ if (!node) {
+ continue;
+ }
+
+ if (node.type !== 'table') {
+ continue;
+ }
+
newOverlappingGraph = findTableOverlapping(
- { node: getNode(change.id) as TableNodeType },
- { nodes: nodes.filter((node) => !node.hidden) },
+ { node: node as TableNodeType },
+ {
+ nodes: nodes.filter(
+ (node) => !node.hidden && node.type === 'table'
+ ) as TableNodeType[],
+ },
newOverlappingGraph
);
}
for (const change of sizeChanges) {
+ const node = getNode(change.id) as NodeType;
+ if (!node) {
+ continue;
+ }
+
+ if (node.type !== 'table') {
+ continue;
+ }
+
newOverlappingGraph = findTableOverlapping(
- { node: getNode(change.id) as TableNodeType },
- { nodes: nodes.filter((node) => !node.hidden) },
+ { node: node as TableNodeType },
+ {
+ nodes: nodes.filter(
+ (node) => !node.hidden && node.type === 'table'
+ ) as TableNodeType[],
+ },
newOverlappingGraph
);
}
@@ -489,8 +542,8 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
200
);
- const onNodesChangeHandler: OnNodesChange<TableNodeType> = useCallback(
- (changes) => {
+ const findRelevantNodesChanges = useCallback(
+ (changes: NodeChange<NodeType>[], type: NodeType['type']) => {
let changesToApply = changes;
if (readonly) {
@@ -499,6 +552,28 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
);
}
+ // keeps only the changes that are on tables nodes
+ changesToApply = changesToApply.filter((change) => {
+ if (
+ change.type === 'position' ||
+ change.type === 'dimensions' ||
+ change.type === 'remove'
+ ) {
+ const node = getNode(change.id);
+ if (!node) {
+ return false;
+ }
+
+ if (node.type !== type) {
+ return false;
+ }
+
+ return true;
+ }
+
+ return false;
+ });
+
const positionChanges: NodePositionChange[] = changesToApply.filter(
(change) => change.type === 'position' && !change.dragging
) as NodePositionChange[];
@@ -511,6 +586,21 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
(change) => change.type === 'dimensions' && change.resizing
) as NodeDimensionChange[];
+ return {
+ positionChanges,
+ removeChanges,
+ sizeChanges,
+ };
+ },
+ [getNode, readonly]
+ );
+
+ const onNodesChangeHandler: OnNodesChange<NodeType> = useCallback(
+ (changes) => {
+ // Handle table changes
+ const { positionChanges, removeChanges, sizeChanges } =
+ findRelevantNodesChanges(changes, 'table');
+
if (
positionChanges.length > 0 ||
removeChanges.length > 0 ||
@@ -560,13 +650,52 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
sizeChanges,
});
- return onNodesChange(changesToApply);
+ // Handle area changes
+ const {
+ positionChanges: areaPositionChanges,
+ removeChanges: areaRemoveChanges,
+ sizeChanges: areaSizeChanges,
+ } = findRelevantNodesChanges(changes, 'area');
+
+ if (
+ areaPositionChanges.length > 0 ||
+ areaRemoveChanges.length > 0 ||
+ areaSizeChanges.length > 0
+ ) {
+ [...areaPositionChanges, ...areaSizeChanges].forEach(
+ (change) => {
+ const updateData: Partial<Area> = {};
+
+ if (change.type === 'position') {
+ updateData.x = change.position?.x;
+ updateData.y = change.position?.y;
+ }
+
+ if (change.type === 'dimensions') {
+ updateData.width = change.dimensions?.width;
+ updateData.height = change.dimensions?.height;
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ updateArea(change.id, updateData);
+ }
+ }
+ );
+
+ areaRemoveChanges.forEach((change) => {
+ removeArea(change.id);
+ });
+ }
+
+ return onNodesChange(changes);
},
[
onNodesChange,
updateTablesState,
updateOverlappingGraphOnChangesDebounced,
- readonly,
+ findRelevantNodesChanges,
+ updateArea,
+ removeArea,
]
);
@@ -577,7 +706,11 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
for (const table of event.data.tables) {
newOverlappingGraph = findTableOverlapping(
{ node: getNode(table.id) as TableNodeType },
- { nodes: nodes.filter((node) => !node.hidden) },
+ {
+ nodes: nodes.filter(
+ (node) => !node.hidden && node.type === 'table'
+ ) as TableNodeType[],
+ },
overlapGraph
);
}
@@ -610,7 +743,11 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
measured,
},
},
- { nodes: nodes.filter((node) => !node.hidden) },
+ {
+ nodes: nodes.filter(
+ (node) => !node.hidden && node.type === 'table'
+ ) as TableNodeType[],
+ },
overlapGraph
);
setOverlapGraph(newOverlappingGraph);
@@ -632,7 +769,11 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
measured,
},
},
- { nodes: nodes.filter((node) => !node.hidden) },
+ {
+ nodes: nodes.filter(
+ (node) => !node.hidden && node.type === 'table'
+ ) as TableNodeType[],
+ },
overlapGraph
);
setOverlapGraph(newOverlappingGraph);
diff --git a/src/pages/editor-page/canvas/dependency-edge.tsx b/src/pages/editor-page/canvas/dependency-edge/dependency-edge.tsx
similarity index 100%
rename from src/pages/editor-page/canvas/dependency-edge.tsx
rename to src/pages/editor-page/canvas/dependency-edge/dependency-edge.tsx
diff --git a/src/pages/editor-page/canvas/relationship-edge.tsx b/src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx
similarity index 98%
rename from src/pages/editor-page/canvas/relationship-edge.tsx
rename to src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx
index 1a17b08b..73854929 100644
--- a/src/pages/editor-page/canvas/relationship-edge.tsx
+++ b/src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx
@@ -2,11 +2,11 @@ import React, { useCallback, useMemo } from 'react';
import type { Edge, EdgeProps } from '@xyflow/react';
import { getSmoothStepPath, Position, useReactFlow } from '@xyflow/react';
import type { DBRelationship } from '@/lib/domain/db-relationship';
-import { RIGHT_HANDLE_ID_PREFIX } from './table-node/table-node-field';
+import { RIGHT_HANDLE_ID_PREFIX } from '../table-node/table-node-field';
import { useChartDB } from '@/hooks/use-chartdb';
import { useLayout } from '@/hooks/use-layout';
import { cn } from '@/lib/utils';
-import { getCardinalityMarkerId } from './canvas-utils';
+import { getCardinalityMarkerId } from '../canvas-utils';
import { useDiff } from '@/context/diff-context/use-diff';
export type RelationshipEdgeType = Edge<
diff --git a/src/pages/editor-page/canvas/table-node/table-node.tsx b/src/pages/editor-page/canvas/table-node/table-node.tsx
index cf32c5c5..1958380a 100644
--- a/src/pages/editor-page/canvas/table-node/table-node.tsx
+++ b/src/pages/editor-page/canvas/table-node/table-node.tsx
@@ -19,7 +19,7 @@ import type { DBTable } from '@/lib/domain/db-table';
import { TableNodeField } from './table-node-field';
import { useLayout } from '@/hooks/use-layout';
import { useChartDB } from '@/hooks/use-chartdb';
-import type { RelationshipEdgeType } from '../relationship-edge';
+import type { RelationshipEdgeType } from '../relationship-edge/relationship-edge';
import type { DBField } from '@/lib/domain/db-field';
import { useTranslation } from 'react-i18next';
import { TableNodeContextMenu } from './table-node-context-menu';
diff --git a/src/pages/editor-page/editor-sidebar/editor-sidebar.tsx b/src/pages/editor-page/editor-sidebar/editor-sidebar.tsx
index 574c50ad..f14c8b70 100644
--- a/src/pages/editor-page/editor-sidebar/editor-sidebar.tsx
+++ b/src/pages/editor-page/editor-sidebar/editor-sidebar.tsx
@@ -10,7 +10,7 @@ import {
SidebarMenuButton,
SidebarMenuItem,
} from '@/components/sidebar/sidebar';
-import { Twitter, BookOpen } from 'lucide-react';
+import { Twitter, BookOpen, Group } from 'lucide-react';
import { SquareStack, Table, Workflow } from 'lucide-react';
import { useLayout } from '@/hooks/use-layout';
import { useTranslation } from 'react-i18next';
@@ -65,6 +65,15 @@ export const EditorSidebar: React.FC<EditorSidebarProps> = () => {
},
active: selectedSidebarSection === 'dependencies',
},
+ {
+ title: t('side_panel.areas_section.areas'),
+ icon: Group,
+ onClick: () => {
+ showSidePanel();
+ selectSidebarSection('areas');
+ },
+ active: selectedSidebarSection === 'areas',
+ },
],
[selectSidebarSection, selectedSidebarSection, t, showSidePanel]
);
diff --git a/src/pages/editor-page/side-panel/areas-section/areas-list/area-list-item/area-list-item.tsx b/src/pages/editor-page/side-panel/areas-section/areas-list/area-list-item/area-list-item.tsx
new file mode 100644
index 00000000..1cfb4142
--- /dev/null
+++ b/src/pages/editor-page/side-panel/areas-section/areas-list/area-list-item/area-list-item.tsx
@@ -0,0 +1,254 @@
+import React, { useCallback } from 'react';
+import {
+ GripVertical,
+ Pencil,
+ Check,
+ Trash2,
+ EllipsisVertical,
+ CircleDotDashed,
+} from 'lucide-react';
+import { useSortable } from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import type { Area } from '@/lib/domain/area';
+import { Input } from '@/components/input/input';
+import { useChartDB } from '@/hooks/use-chartdb';
+import { useClickAway, useKeyPressEvent } from 'react-use';
+import { useTranslation } from 'react-i18next';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/tooltip/tooltip';
+import { ColorPicker } from '@/components/color-picker/color-picker';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from '@/components/dropdown-menu/dropdown-menu';
+import { ListItemHeaderButton } from '@/pages/editor-page/side-panel/list-item-header-button/list-item-header-button';
+import { mergeRefs } from '@/lib/utils';
+import { useReactFlow } from '@xyflow/react';
+import { useLayout } from '@/hooks/use-layout';
+import { useBreakpoint } from '@/hooks/use-breakpoint';
+
+export interface AreaListItemProps {
+ area: Area;
+}
+
+export const AreaListItem = React.forwardRef<HTMLDivElement, AreaListItemProps>(
+ ({ area }, forwardedRef) => {
+ const { updateArea, removeArea } = useChartDB();
+ const { t } = useTranslation();
+ const { fitView, setNodes } = useReactFlow();
+ const { hideSidePanel } = useLayout();
+ const { isMd: isDesktop } = useBreakpoint('md');
+ const [editMode, setEditMode] = React.useState(false);
+ const [areaName, setAreaName] = React.useState(area.name);
+ const inputRef = React.useRef<HTMLInputElement>(null);
+
+ const { attributes, listeners, setNodeRef, transform, transition } =
+ useSortable({
+ id: area.id,
+ });
+
+ // Merge the forwarded ref with the sortable ref
+ const combinedRef = mergeRefs<HTMLDivElement>(forwardedRef, setNodeRef);
+
+ const style = {
+ transform: CSS.Translate.toString(transform),
+ transition,
+ };
+
+ const saveAreaName = useCallback(() => {
+ if (!editMode) return;
+ if (areaName.trim()) {
+ updateArea(area.id, { name: areaName.trim() });
+ }
+ setEditMode(false);
+ }, [areaName, area.id, updateArea, editMode]);
+
+ const abortEdit = useCallback(() => {
+ setEditMode(false);
+ setAreaName(area.name);
+ }, [area.name]);
+
+ const enterEditMode = useCallback((e: React.MouseEvent) => {
+ e.stopPropagation();
+ setEditMode(true);
+ }, []);
+
+ const handleDelete = useCallback(() => {
+ removeArea(area.id);
+ }, [area.id, removeArea]);
+
+ const handleColorChange = useCallback(
+ (color: string) => {
+ updateArea(area.id, { color });
+ },
+ [area.id, updateArea]
+ );
+
+ const focusOnArea = useCallback(
+ (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
+ event.stopPropagation();
+ setNodes((nodes) =>
+ nodes.map((node) =>
+ node.id == area.id
+ ? {
+ ...node,
+ selected: true,
+ }
+ : {
+ ...node,
+ selected: false,
+ }
+ )
+ );
+ fitView({
+ duration: 500,
+ maxZoom: 1,
+ minZoom: 1,
+ nodes: [
+ {
+ id: area.id,
+ },
+ ],
+ });
+
+ if (!isDesktop) {
+ hideSidePanel();
+ }
+ },
+ [fitView, area.id, setNodes, hideSidePanel, isDesktop]
+ );
+
+ useClickAway(inputRef, saveAreaName);
+ useKeyPressEvent('Enter', saveAreaName);
+ useKeyPressEvent('Escape', abortEdit);
+
+ const renderDropDownMenu = useCallback(
+ () => (
+ <DropdownMenu>
+ <DropdownMenuTrigger>
+ <ListItemHeaderButton>
+ <EllipsisVertical />
+ </ListItemHeaderButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-fit min-w-40">
+ <DropdownMenuLabel>
+ {t(
+ 'side_panel.areas_section.area.area_actions.title'
+ )}
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ className="flex justify-between gap-4"
+ onClick={(e) => {
+ e.stopPropagation();
+ enterEditMode(e);
+ }}
+ >
+ {t(
+ 'side_panel.areas_section.area.area_actions.edit_name'
+ )}
+ <Pencil className="size-3.5" />
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ onClick={handleDelete}
+ className="flex justify-between !text-red-700"
+ >
+ {t(
+ 'side_panel.areas_section.area.area_actions.delete_area'
+ )}
+ <Trash2 className="size-3.5 text-red-700" />
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ),
+ [enterEditMode, handleDelete, t]
+ );
+
+ return (
+ <div
+ className="w-full rounded-md border border-border hover:bg-accent/5"
+ ref={combinedRef}
+ style={{
+ ...style,
+ borderLeftWidth: '6px',
+ borderLeftColor: area.color,
+ }}
+ {...attributes}
+ >
+ <div className="group flex h-11 items-center justify-between gap-1 overflow-hidden p-2">
+ <div
+ className="flex cursor-move items-center justify-center"
+ {...listeners}
+ >
+ <GripVertical className="size-4 text-muted-foreground" />
+ </div>
+
+ <div className="flex min-w-0 flex-1">
+ {editMode ? (
+ <Input
+ ref={inputRef}
+ autoFocus
+ type="text"
+ placeholder={area.name}
+ value={areaName}
+ onClick={(e) => e.stopPropagation()}
+ onChange={(e) => setAreaName(e.target.value)}
+ className="h-7 w-full focus-visible:ring-0"
+ />
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div
+ onDoubleClick={enterEditMode}
+ className="text-editable truncate px-2 py-0.5 text-sm font-medium"
+ >
+ {area.name}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ {t('tool_tips.double_click_to_edit')}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1">
+ {!editMode ? (
+ <div className="flex flex-row-reverse items-center gap-1">
+ {renderDropDownMenu()}
+ <ColorPicker
+ color={area.color}
+ onChange={handleColorChange}
+ />
+ <div className="hidden md:group-hover:flex">
+ <ListItemHeaderButton onClick={focusOnArea}>
+ <CircleDotDashed />
+ </ListItemHeaderButton>
+ </div>
+ </div>
+ ) : (
+ <ListItemHeaderButton onClick={saveAreaName}>
+ <Check />
+ </ListItemHeaderButton>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+);
+
+AreaListItem.displayName = 'AreaListItem';
diff --git a/src/pages/editor-page/side-panel/areas-section/areas-list/areas-list.tsx b/src/pages/editor-page/side-panel/areas-section/areas-list/areas-list.tsx
new file mode 100644
index 00000000..2b811e0c
--- /dev/null
+++ b/src/pages/editor-page/side-panel/areas-section/areas-list/areas-list.tsx
@@ -0,0 +1,123 @@
+import React, { useCallback, useMemo } from 'react';
+import { AreaListItem } from './area-list-item/area-list-item';
+import type { Area } from '@/lib/domain/area';
+import { useLayout } from '@/hooks/use-layout';
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ arrayMove,
+ SortableContext,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable';
+import { useChartDB } from '@/hooks/use-chartdb.ts';
+
+export interface AreaListProps {
+ areas: Area[];
+}
+
+export const AreaList: React.FC<AreaListProps> = ({ areas }) => {
+ const { updateArea } = useChartDB();
+
+ const { openedAreaInSidebar } = useLayout();
+ const lastSelectedArea = React.useRef<string | null>(null);
+ const refs = useMemo(
+ () =>
+ areas.reduce(
+ (acc, area) => {
+ acc[area.id] = React.createRef();
+ return acc;
+ },
+ {} as Record<string, React.RefObject<HTMLDivElement>>
+ ),
+ [areas]
+ );
+
+ const scrollToArea = useCallback(
+ (id: string) =>
+ refs[id]?.current?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'start',
+ }),
+ [refs]
+ );
+
+ const sensors = useSensors(useSensor(PointerSensor));
+
+ const handleDragEnd = (event: DragEndEvent) => {
+ const { active, over } = event;
+
+ if (active?.id !== over?.id && !!over && !!active) {
+ const oldIndex = areas.findIndex((area) => area.id === active.id);
+ const newIndex = areas.findIndex((area) => area.id === over.id);
+
+ const newAreasOrder = arrayMove<Area>(areas, oldIndex, newIndex);
+
+ newAreasOrder.forEach((area, index) => {
+ updateArea(area.id, { order: index });
+ });
+ }
+ };
+
+ const handleScrollToArea = useCallback(() => {
+ if (
+ openedAreaInSidebar &&
+ lastSelectedArea.current !== openedAreaInSidebar
+ ) {
+ lastSelectedArea.current = openedAreaInSidebar;
+ scrollToArea(openedAreaInSidebar);
+ }
+ }, [scrollToArea, openedAreaInSidebar]);
+
+ React.useEffect(() => {
+ handleScrollToArea();
+ }, [openedAreaInSidebar, handleScrollToArea]);
+
+ return (
+ <div className="flex w-full flex-col gap-1">
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={areas}
+ strategy={verticalListSortingStrategy}
+ >
+ {areas
+ .sort((area1: Area, area2: Area) => {
+ if (area1.order && area2.order === undefined) {
+ return -1;
+ }
+
+ if (area1.order === undefined && area2.order) {
+ return 1;
+ }
+
+ if (
+ area1.order !== undefined &&
+ area2.order !== undefined
+ ) {
+ return area1.order - area2.order;
+ }
+
+ // if both areas don't have order, sort by name
+ return area1.name.localeCompare(area2.name);
+ })
+ .map((area) => (
+ <AreaListItem
+ key={area.id}
+ area={area}
+ ref={refs[area.id]}
+ />
+ ))}
+ </SortableContext>
+ </DndContext>
+ </div>
+ );
+};
diff --git a/src/pages/editor-page/side-panel/areas-section/areas-section.tsx b/src/pages/editor-page/side-panel/areas-section/areas-section.tsx
new file mode 100644
index 00000000..2a29a262
--- /dev/null
+++ b/src/pages/editor-page/side-panel/areas-section/areas-section.tsx
@@ -0,0 +1,134 @@
+import React, { useCallback, useMemo } from 'react';
+import { AreaList } from './areas-list/areas-list';
+import { Button } from '@/components/button/button';
+import { Group, X } from 'lucide-react';
+import { Input } from '@/components/input/input';
+import type { Area } from '@/lib/domain/area';
+import { useChartDB } from '@/hooks/use-chartdb';
+import { useLayout } from '@/hooks/use-layout';
+import { EmptyState } from '@/components/empty-state/empty-state';
+import { ScrollArea } from '@/components/scroll-area/scroll-area';
+import { useTranslation } from 'react-i18next';
+import { useViewport } from '@xyflow/react';
+import { useHotkeys } from 'react-hotkeys-hook';
+import { getOperatingSystem } from '@/lib/utils';
+
+export interface AreasSectionProps {}
+
+export const AreasSection: React.FC<AreasSectionProps> = () => {
+ const { createArea, areas } = useChartDB();
+ const viewport = useViewport();
+ const { t } = useTranslation();
+ const { openAreaFromSidebar } = useLayout();
+ const [filterText, setFilterText] = React.useState('');
+ const filterInputRef = React.useRef<HTMLInputElement>(null);
+
+ const filteredAreas = useMemo(() => {
+ const filterAreaName: (area: Area) => boolean = (area) =>
+ !filterText?.trim?.() ||
+ area.name.toLowerCase().includes(filterText.toLowerCase());
+
+ return areas.filter(filterAreaName);
+ }, [areas, filterText]);
+
+ const createAreaWithLocation = useCallback(async () => {
+ const padding = 80;
+ const centerX = -viewport.x / viewport.zoom + padding / viewport.zoom;
+ const centerY = -viewport.y / viewport.zoom + padding / viewport.zoom;
+ const area = await createArea({
+ x: centerX,
+ y: centerY,
+ });
+ if (openAreaFromSidebar) {
+ openAreaFromSidebar(area.id);
+ }
+ }, [
+ createArea,
+ openAreaFromSidebar,
+ viewport.x,
+ viewport.y,
+ viewport.zoom,
+ ]);
+
+ const handleCreateArea = useCallback(async () => {
+ setFilterText('');
+ createAreaWithLocation();
+ }, [createAreaWithLocation, setFilterText]);
+
+ const handleClearFilter = useCallback(() => {
+ setFilterText('');
+ }, []);
+
+ const operatingSystem = useMemo(() => getOperatingSystem(), []);
+
+ useHotkeys(
+ operatingSystem === 'mac' ? 'meta+f' : 'ctrl+f',
+ () => {
+ filterInputRef.current?.focus();
+ },
+ {
+ preventDefault: true,
+ },
+ [filterInputRef]
+ );
+
+ return (
+ <section
+ className="flex flex-1 flex-col overflow-hidden px-2"
+ data-vaul-no-drag
+ >
+ <div className="flex items-center justify-between gap-4 py-1">
+ <div className="flex-1">
+ <Input
+ ref={filterInputRef}
+ type="text"
+ placeholder={t('side_panel.areas_section.filter')}
+ className="h-8 w-full focus-visible:ring-0"
+ value={filterText}
+ onChange={(e) => setFilterText(e.target.value)}
+ />
+ </div>
+ <Button
+ variant="secondary"
+ className="h-8 p-2 text-xs"
+ onClick={handleCreateArea}
+ >
+ <Group className="h-4" />
+ {t('side_panel.areas_section.add_area')}
+ </Button>
+ </div>
+ <div className="flex flex-1 flex-col overflow-hidden">
+ <ScrollArea className="h-full">
+ {areas.length === 0 ? (
+ <EmptyState
+ title={t(
+ 'side_panel.areas_section.empty_state.title'
+ )}
+ description={t(
+ 'side_panel.areas_section.empty_state.description'
+ )}
+ className="mt-20"
+ />
+ ) : filterText && filteredAreas.length === 0 ? (
+ <div className="mt-10 flex flex-col items-center gap-2">
+ <div className="text-sm text-muted-foreground">
+ {t('side_panel.areas_section.no_results')}
+ </div>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleClearFilter}
+ className="gap-1"
+ >
+ <X className="size-3.5" />
+ {t('side_panel.areas_section.clear')}
+ </Button>
+ </div>
+ ) : (
+ <AreaList areas={filteredAreas} />
+ )}
+ </ScrollArea>
+ </div>
+ </section>
+ );
+};
diff --git a/src/pages/editor-page/side-panel/side-panel.tsx b/src/pages/editor-page/side-panel/side-panel.tsx
index d24eff8d..1b698014 100644
--- a/src/pages/editor-page/side-panel/side-panel.tsx
+++ b/src/pages/editor-page/side-panel/side-panel.tsx
@@ -17,6 +17,7 @@ import { SelectBox } from '@/components/select-box/select-box';
import { useChartDB } from '@/hooks/use-chartdb';
import { DependenciesSection } from './dependencies-section/dependencies-section';
import { useBreakpoint } from '@/hooks/use-breakpoint';
+import { AreasSection } from './areas-section/areas-section';
export interface SidePanelProps {}
@@ -113,6 +114,9 @@ export const SidePanel: React.FC<SidePanelProps> = () => {
'side_panel.dependencies_section.dependencies'
)}
</SelectItem>
+ <SelectItem value="areas">
+ {t('side_panel.areas_section.areas')}
+ </SelectItem>
</SelectGroup>
</SelectContent>
</Select>
@@ -122,8 +126,10 @@ export const SidePanel: React.FC<SidePanelProps> = () => {
<TablesSection />
) : selectedSidebarSection === 'relationships' ? (
<RelationshipsSection />
- ) : (
+ ) : selectedSidebarSection === 'dependencies' ? (
<DependenciesSection />
+ ) : (
+ <AreasSection />
)}
</aside>
);
diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx
index 9db3584f..7bb24718 100644
--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx
+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-list-item-content.tsx
@@ -29,7 +29,7 @@ import {
SortableContext,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
-import { ColorPicker } from './color-picker/color-picker';
+import { ColorPicker } from '@/components/color-picker/color-picker';
type AccordionItemValue = 'fields' | 'indexes';