Database diagrams editor that allows you to visualize and design your DB with a single query.
TypeScript databasedbdb-migrationeditorerdmariadbmssqlmysqlpostgresqlreactreact-flowschema-migrationssqlsqlitetypescriptvisualizationxyflow
feat(side-panel): Add functionality of order tables by drag & drop (#425)
Zer0S2ma0e966b64f80
diff --git a/src/context/chartdb-context/chartdb-provider.tsx b/src/context/chartdb-context/chartdb-provider.tsxindex 1aa6406a..521217ec 100644--- a/src/context/chartdb-context/chartdb-provider.tsx+++ b/src/context/chartdb-context/chartdb-provider.tsx@@ -27,6 +27,7 @@ export interface ChartDBProviderProps {diagram?: Diagram;readonly?: boolean;}+export const ChartDBProvider: React.FC<React.PropsWithChildren<ChartDBProviderProps>> = ({ children, diagram, readonly }) => {@@ -310,6 +311,7 @@ export const ChartDBProvider: React.FC<color: randomColor(),createdAt: Date.now(),isView: false,+ order: tables.length,...attributes,};await addTable(table);diff --git a/src/context/storage-context/storage-provider.tsx b/src/context/storage-context/storage-provider.tsxindex 190a661b..53086fce 100644--- a/src/context/storage-context/storage-provider.tsx+++ b/src/context/storage-context/storage-provider.tsx@@ -122,6 +122,18 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({config: '++id, defaultDiagramId',});+ db.version(8).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',+ config: '++id, defaultDiagramId',+ });+db.on('ready', async () => {const config = await getConfig();@@ -345,15 +357,7 @@ export const StorageProvider: React.FC<React.PropsWithChildren> = ({.equals(diagramId).toArray();- // Sort tables first alphabetically, then views alphabetically- return tables.sort((a, b) => {- if (a.isView === b.isView) {- // Both are either tables or views, so sort alphabetically by name- return a.name.localeCompare(b.name);- }- // If one is a view and the other is not, put tables first- return a.isView ? 1 : -1;- });+ return tables;};const addRelationship: StorageContext['addRelationship'] = async ({diff --git a/src/lib/domain/db-table.ts b/src/lib/domain/db-table.tsindex c106a40c..b71ed335 100644--- a/src/lib/domain/db-table.ts+++ b/src/lib/domain/db-table.ts@@ -40,7 +40,7 @@ export interface DBTable {createdAt: number;width?: number;comments?: string;- hidden?: boolean;+ order?: number;}export const dbTableSchema: z.ZodType<DBTable> = z.object({@@ -58,6 +58,7 @@ export const dbTableSchema: z.ZodType<DBTable> = z.object({width: z.number().optional(),comments: z.string().optional(),hidden: z.boolean().optional(),+ order: z.number().optional(),});export const shouldShowTablesBySchemaFilter = (diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-field/table-field.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-field/table-field.tsxindex 389547ee..40082971 100644--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-field/table-field.tsx+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-content/table-field/table-field.tsx@@ -48,7 +48,7 @@ export const TableField: React.FC<TableFieldProps> = ({}));const style = {- transform: CSS.Transform.toString(transform),+ transform: CSS.Translate.toString(transform),transition,};diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-header/table-list-item-header.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-header/table-list-item-header.tsxindex 989780d8..5413f711 100644--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-header/table-list-item-header.tsx+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item-header/table-list-item-header.tsx@@ -1,6 +1,7 @@import React, { useCallback } from 'react';import {CircleDotDashed,+ GripVertical,Pencil,EllipsisVertical,Trash2,@@ -15,6 +16,7 @@ import type { DBTable } from '@/lib/domain/db-table';import { Input } from '@/components/input/input';import { useChartDB } from '@/hooks/use-chartdb';import { useClickAway, useKeyPressEvent } from 'react-use';+import { useSortable } from '@dnd-kit/sortable';import {DropdownMenu,DropdownMenuContent,@@ -60,6 +62,7 @@ export const TableListItemHeader: React.FC<TableListItemHeaderProps> = ({const [tableName, setTableName] = React.useState(table.name);const { isMd: isDesktop } = useBreakpoint('md');const inputRef = React.useRef<HTMLInputElement>(null);+ const { listeners } = useSortable({ id: table.id });const editTableName = useCallback(() => {if (!editMode) return;@@ -252,6 +255,12 @@ export const TableListItemHeader: React.FC<TableListItemHeaderProps> = ({return (<div className="group flex h-11 flex-1 items-center justify-between gap-1 overflow-hidden">+ <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 px-1">{editMode ? (<Inputdiff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item.tsxindex cbd01db2..b1050a53 100644--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item.tsx+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list-item/table-list-item.tsx@@ -7,6 +7,8 @@ import {import { TableListItemHeader } from './table-list-item-header/table-list-item-header';import { TableListItemContent } from './table-list-item-content/table-list-item-content';import type { DBTable } from '@/lib/domain/db-table';+import { useSortable } from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';export interface TableListItemProps {table: DBTable;@@ -16,20 +18,35 @@ export const TableListItem = React.forwardRef<React.ElementRef<typeof AccordionItem>,TableListItemProps>(({ table }, ref) => {+ const { attributes, setNodeRef, transform, transition } = useSortable({+ id: table.id,+ });+ const style = {+ transform: CSS.Translate.toString(transform),+ transition,+ };+return (- <AccordionItem value={table.id} className="rounded-md" ref={ref}>- <AccordionTrigger- className="w-full rounded-md border-l-[6px] px-2 py-0 hover:bg-accent hover:no-underline data-[state=open]:rounded-b-none"- style={{- borderColor: table.color,- }}- asChild+ <AccordionItem value={table.id} className="border-none" ref={ref}>+ <div+ className="w-full rounded-md border-b"+ ref={setNodeRef}+ style={style}+ {...attributes}>- <TableListItemHeader table={table} />- </AccordionTrigger>- <AccordionContent>- <TableListItemContent table={table} />- </AccordionContent>+ <AccordionTrigger+ className="w-full rounded-md border-l-[6px] px-2 py-0 hover:bg-accent hover:no-underline data-[state=open]:rounded-b-none"+ style={{+ borderColor: table.color,+ }}+ asChild+ >+ <TableListItemHeader table={table} />+ </AccordionTrigger>+ <AccordionContent>+ <TableListItemContent table={table} />+ </AccordionContent>+ </div></AccordionItem>);});diff --git a/src/pages/editor-page/side-panel/tables-section/table-list/table-list.tsx b/src/pages/editor-page/side-panel/tables-section/table-list/table-list.tsxindex 15b5c299..aed63242 100644--- a/src/pages/editor-page/side-panel/tables-section/table-list/table-list.tsx+++ b/src/pages/editor-page/side-panel/tables-section/table-list/table-list.tsx@@ -3,12 +3,28 @@ import { Accordion } from '@/components/accordion/accordion';import { TableListItem } from './table-list-item/table-list-item';import type { DBTable } from '@/lib/domain/db-table';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 TableListProps {tables: DBTable[];}export const TableList: React.FC<TableListProps> = ({ tables }) => {+ const { updateTablesState } = useChartDB();+const { openTableFromSidebar, openedTableInSidebar } = useLayout();const lastOpenedTable = React.useRef<string | null>(null);const refs = useMemo(@@ -32,6 +48,35 @@ export const TableList: React.FC<TableListProps> = ({ tables }) => {[refs]);+ const sensors = useSensors(useSensor(PointerSensor));++ const handleDragEnd = (event: DragEndEvent) => {+ const { active, over } = event;++ if (active?.id !== over?.id && !!over && !!active) {+ const oldIndex = tables.findIndex(+ (table) => table.id === active.id+ );+ const newIndex = tables.findIndex((table) => table.id === over.id);++ const tablesOrders = arrayMove<DBTable>(+ tables,+ oldIndex,+ newIndex+ ).reduce((acc, table, index) => {+ acc.set(table.id, index);+ return acc;+ }, new Map<string, number>());++ updateTablesState((tables: DBTable[]) =>+ tables.map((table) => ({+ id: table.id,+ order: tablesOrders.get(table.id),+ }))+ );+ }+ };+const handleScrollToTable = useCallback(() => {if (openedTableInSidebar &&@@ -51,13 +96,51 @@ export const TableList: React.FC<TableListProps> = ({ tables }) => {onValueChange={openTableFromSidebar}onAnimationEnd={handleScrollToTable}>- {tables.map((table) => (- <TableListItem- key={table.id}- table={table}- ref={refs[table.id]}- />- ))}+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={tables}+ strategy={verticalListSortingStrategy}+ >+ {tables+ .sort((table1: DBTable, table2: DBTable) => {+ // if one table has order and the other doesn't, the one with order should come first+ if (table1.order && table2.order === undefined) {+ return -1;+ }++ if (table1.order === undefined && table2.order) {+ return 1;+ }++ // if both tables have order, sort by order+ if (+ table1.order !== undefined &&+ table2.order !== undefined+ ) {+ return table1.order - table2.order;+ }++ // if both tables don't have order, sort by name+ if (table1.isView === table2.isView) {+ // Both are either tables or views, so sort alphabetically by name+ return table1.name.localeCompare(table2.name);+ }+ // If one is a view and the other is not, put tables first+ return table1.isView ? 1 : -1;+ })+ .map((table) => (+ <TableListItem+ key={table.id}+ table={table}+ ref={refs[table.id]}+ />+ ))}+ </SortableContext>+ </DndContext></Accordion>);};