Skip to content

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

feat: add canvas relationship editor with inline controls (#996)

Jonathan Fishnerbeeb6c0ae597
diff --git a/src/context/canvas-context/canvas-context.tsx b/src/context/canvas-context/canvas-context.tsx
index e23bbedf..900c76a2 100644
--- a/src/context/canvas-context/canvas-context.tsx
+++ b/src/context/canvas-context/canvas-context.tsx
@@ -42,6 +42,15 @@ export interface CanvasContext {
fieldId?: string;
} | null>
>;
+ openRelationshipPopover: (params: {
+ relationshipId: string;
+ position: { x: number; y: number };
+ }) => void;
+ closeRelationshipPopover: () => void;
+ editRelationshipPopover: {
+ relationshipId: string;
+ position: { x: number; y: number };
+ } | null;
tempFloatingEdge: {
sourceNodeId: string;
targetNodeId?: string;
@@ -79,6 +88,9 @@ export const canvasContext = createContext<CanvasContext>({
showFilter: false,
editTableModeTable: null,
setEditTableModeTable: emptyFn,
+ openRelationshipPopover: emptyFn,
+ closeRelationshipPopover: emptyFn,
+ editRelationshipPopover: null,
tempFloatingEdge: null,
setTempFloatingEdge: emptyFn,
startFloatingEdgeCreation: emptyFn,
diff --git a/src/context/canvas-context/canvas-provider.tsx b/src/context/canvas-context/canvas-provider.tsx
index f922bce8..4f24aac9 100644
--- a/src/context/canvas-context/canvas-provider.tsx
+++ b/src/context/canvas-context/canvas-provider.tsx
@@ -46,6 +46,11 @@ export const CanvasProvider = ({ children }: CanvasProviderProps) => {
fieldId?: string;
} | null>(null);
+ const [editRelationshipPopover, setEditRelationshipPopover] = useState<{
+ relationshipId: string;
+ position: { x: number; y: number };
+ } | null>(null);
+
const events = useEventEmitter<CanvasEvent>();
const [showFilter, setShowFilter] = useState(false);
@@ -161,6 +166,16 @@ export const CanvasProvider = ({ children }: CanvasProviderProps) => {
endFloatingEdgeCreation();
}, [setNodes, endFloatingEdgeCreation]);
+ const openRelationshipPopover: CanvasContext['openRelationshipPopover'] =
+ useCallback(({ relationshipId, position }) => {
+ setEditRelationshipPopover({ relationshipId, position });
+ }, []);
+
+ const closeRelationshipPopover: CanvasContext['closeRelationshipPopover'] =
+ useCallback(() => {
+ setEditRelationshipPopover(null);
+ }, []);
+
const showCreateRelationshipNode: CanvasContext['showCreateRelationshipNode'] =
useCallback(
({ sourceTableId, targetTableId, x, y }) => {
@@ -211,6 +226,9 @@ export const CanvasProvider = ({ children }: CanvasProviderProps) => {
showFilter,
editTableModeTable,
setEditTableModeTable,
+ openRelationshipPopover,
+ closeRelationshipPopover,
+ editRelationshipPopover,
tempFloatingEdge: tempFloatingEdge,
setTempFloatingEdge: setTempFloatingEdge,
startFloatingEdgeCreation: startFloatingEdgeCreation,
diff --git a/src/pages/editor-page/canvas/canvas.tsx b/src/pages/editor-page/canvas/canvas.tsx
index 99801870..e7404a31 100644
--- a/src/pages/editor-page/canvas/canvas.tsx
+++ b/src/pages/editor-page/canvas/canvas.tsx
@@ -311,6 +311,7 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
endFloatingEdgeCreation,
hoveringTableId,
hideCreateRelationshipNode,
+ closeRelationshipPopover,
events: canvasEvents,
} = useCanvas();
const { filter, loading: filterLoading } = useDiagramFilter();
@@ -406,31 +407,47 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
{} as Record<string, number>
);
- setEdges([
- ...relationships.map(
- (relationship): RelationshipEdgeType => ({
- id: relationship.id,
- source: relationship.sourceTableId,
- target: relationship.targetTableId,
- sourceHandle: `${LEFT_HANDLE_ID_PREFIX}${relationship.sourceFieldId}`,
- targetHandle: `${TARGET_ID_PREFIX}${targetIndexes[`${relationship.targetTableId}${relationship.targetFieldId}`]++}_${relationship.targetFieldId}`,
- type: 'relationship-edge',
- data: { relationship },
- })
- ),
- ...dependencies.map(
- (dep): DependencyEdgeType => ({
- id: dep.id,
- source: dep.dependentTableId,
- target: dep.tableId,
- sourceHandle: `${TOP_SOURCE_HANDLE_ID_PREFIX}${dep.dependentTableId}`,
- targetHandle: `${TARGET_DEP_PREFIX}${targetDepIndexes[dep.tableId]++}_${dep.tableId}`,
- type: 'dependency-edge',
- data: { dependency: dep },
- hidden: !showDBViews,
- })
- ),
- ]);
+ setEdges((prevEdges) => {
+ // Create a map of previous edge states to preserve selection
+ const prevEdgeStates = new Map(
+ prevEdges.map((edge) => [
+ edge.id,
+ { selected: edge.selected, animated: edge.animated },
+ ])
+ );
+
+ return [
+ ...relationships.map((relationship): RelationshipEdgeType => {
+ const prevState = prevEdgeStates.get(relationship.id);
+ return {
+ id: relationship.id,
+ source: relationship.sourceTableId,
+ target: relationship.targetTableId,
+ sourceHandle: `${LEFT_HANDLE_ID_PREFIX}${relationship.sourceFieldId}`,
+ targetHandle: `${TARGET_ID_PREFIX}${targetIndexes[`${relationship.targetTableId}${relationship.targetFieldId}`]++}_${relationship.targetFieldId}`,
+ type: 'relationship-edge',
+ data: { relationship },
+ selected: prevState?.selected ?? false,
+ animated: prevState?.animated ?? false,
+ };
+ }),
+ ...dependencies.map((dep): DependencyEdgeType => {
+ const prevState = prevEdgeStates.get(dep.id);
+ return {
+ id: dep.id,
+ source: dep.dependentTableId,
+ target: dep.tableId,
+ sourceHandle: `${TOP_SOURCE_HANDLE_ID_PREFIX}${dep.dependentTableId}`,
+ targetHandle: `${TARGET_DEP_PREFIX}${targetDepIndexes[dep.tableId]++}_${dep.tableId}`,
+ type: 'dependency-edge',
+ data: { dependency: dep },
+ hidden: !showDBViews,
+ selected: prevState?.selected ?? false,
+ animated: prevState?.animated ?? false,
+ };
+ }),
+ ];
+ });
}, [relationships, dependencies, setEdges, showDBViews]);
useEffect(() => {
@@ -1447,7 +1464,7 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
};
}, []);
- // Handle escape key to cancel floating edge creation and close relationship node
+ // Handle escape key to cancel floating edge creation, close relationship node, and close relationship popover
useEffect(() => {
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
@@ -1457,11 +1474,21 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
}
// Also close CreateRelationshipNode if present
hideCreateRelationshipNode();
+ // Exit edit table mode
+ exitEditTableMode();
+ // Close relationship edit popover
+ closeRelationshipPopover();
}
};
document.addEventListener('keydown', handleEscape);
return () => document.removeEventListener('keydown', handleEscape);
- }, [tempFloatingEdge, endFloatingEdgeCreation, hideCreateRelationshipNode]);
+ }, [
+ tempFloatingEdge,
+ endFloatingEdgeCreation,
+ hideCreateRelationshipNode,
+ closeRelationshipPopover,
+ exitEditTableMode,
+ ]);
// Add temporary invisible node at cursor position and edge
const nodesWithCursor = useMemo(() => {
@@ -1523,6 +1550,9 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
// Exit edit table mode
exitEditTableMode();
+ // Close relationship edit popover
+ closeRelationshipPopover();
+
canvasEvents.emit({
action: 'pan_click',
data: {
@@ -1537,6 +1567,7 @@ export const Canvas: React.FC<CanvasProps> = ({ initialTables }) => {
exitEditTableMode,
endFloatingEdgeCreation,
hideCreateRelationshipNode,
+ closeRelationshipPopover,
]
);
diff --git a/src/pages/editor-page/canvas/relationship-edge/edit-relationship-popover.tsx b/src/pages/editor-page/canvas/relationship-edge/edit-relationship-popover.tsx
new file mode 100644
index 00000000..ae2a3d69
--- /dev/null
+++ b/src/pages/editor-page/canvas/relationship-edge/edit-relationship-popover.tsx
@@ -0,0 +1,111 @@
+import React, { useRef } from 'react';
+import { Trash2, ArrowLeftRight } from 'lucide-react';
+import { Button } from '@/components/button/button';
+import type { Cardinality } from '@/lib/domain/db-relationship';
+import { cn } from '@/lib/utils';
+import { useClickAway } from 'react-use';
+import { useCanvas } from '@/hooks/use-canvas';
+
+export interface EditRelationshipPopoverProps {
+ anchorPosition: { x: number; y: number };
+ sourceCardinality: Cardinality;
+ targetCardinality: Cardinality;
+ onCardinalityChange: (
+ sourceCardinality: Cardinality,
+ targetCardinality: Cardinality
+ ) => void;
+ onSwitch: () => void;
+ onDelete: () => void;
+}
+
+type RelationshipTypeOption = {
+ label: string;
+ sourceCardinality: Cardinality;
+ targetCardinality: Cardinality;
+};
+
+const relationshipTypes: RelationshipTypeOption[] = [
+ { label: '1:1', sourceCardinality: 'one', targetCardinality: 'one' },
+ { label: '1:N', sourceCardinality: 'one', targetCardinality: 'many' },
+ { label: 'N:1', sourceCardinality: 'many', targetCardinality: 'one' },
+];
+
+export const EditRelationshipPopover: React.FC<
+ EditRelationshipPopoverProps
+> = ({
+ anchorPosition,
+ sourceCardinality,
+ targetCardinality,
+ onCardinalityChange,
+ onSwitch,
+ onDelete,
+}) => {
+ const popoverRef = useRef<HTMLDivElement>(null);
+ const { closeRelationshipPopover } = useCanvas();
+
+ useClickAway(popoverRef, closeRelationshipPopover);
+
+ return (
+ <div
+ ref={popoverRef}
+ className="fixed z-50 rounded-md border bg-popover p-2 text-popover-foreground shadow-md"
+ style={{
+ left: anchorPosition.x,
+ top: anchorPosition.y + 10,
+ }}
+ >
+ <div className="flex items-center gap-1">
+ {relationshipTypes.map((type) => {
+ const isActive =
+ type.sourceCardinality === sourceCardinality &&
+ type.targetCardinality === targetCardinality;
+ return (
+ <Button
+ key={type.label}
+ variant={isActive ? 'default' : 'outline'}
+ size="sm"
+ className={cn(
+ 'h-7 w-11 text-xs font-medium',
+ isActive &&
+ 'bg-slate-700 text-white hover:bg-slate-600'
+ )}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onCardinalityChange(
+ type.sourceCardinality,
+ type.targetCardinality
+ );
+ }}
+ >
+ {type.label}
+ </Button>
+ );
+ })}
+ <div className="mx-1 h-6 w-px bg-slate-300" />
+ <Button
+ variant="ghost"
+ size="sm"
+ className="size-7 p-0 text-sky-600 hover:bg-sky-50 hover:text-sky-700"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onSwitch();
+ }}
+ title="Switch tables"
+ >
+ <ArrowLeftRight className="!size-3.5" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="size-7 p-0 text-red-600 hover:bg-red-50 hover:text-red-700"
+ onClick={onDelete}
+ title="Delete relationship"
+ >
+ <Trash2 className="!size-3.5" />
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx b/src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx
index 3b866085..54609f36 100644
--- a/src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx
+++ b/src/pages/editor-page/canvas/relationship-edge/relationship-edge.tsx
@@ -1,14 +1,17 @@
import React, { useCallback, useMemo } from 'react';
+import { createPortal } from 'react-dom';
import type { Edge, EdgeProps } from '@xyflow/react';
import { getSmoothStepPath, Position, useReactFlow } from '@xyflow/react';
-import type { DBRelationship } from '@/lib/domain/db-relationship';
+import type { DBRelationship, Cardinality } from '@/lib/domain/db-relationship';
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 { useDiff } from '@/context/diff-context/use-diff';
import { useLocalConfig } from '@/hooks/use-local-config';
+import { useCanvas } from '@/hooks/use-canvas';
+import { EditRelationshipPopover } from './edit-relationship-popover';
+import { EllipsisIcon } from 'lucide-react';
export type RelationshipEdgeType = Edge<
{
@@ -32,20 +35,108 @@ export const RelationshipEdge: React.FC<EdgeProps<RelationshipEdgeType>> =
data,
}) => {
const { getInternalNode, getEdge } = useReactFlow();
- const { openRelationshipFromSidebar, selectSidebarSection } =
- useLayout();
const { checkIfRelationshipRemoved, checkIfNewRelationship } =
useDiff();
const { showCardinality } = useLocalConfig();
- const { relationships } = useChartDB();
+ const { relationships, updateRelationship, removeRelationship } =
+ useChartDB();
+ const {
+ editRelationshipPopover,
+ openRelationshipPopover,
+ closeRelationshipPopover,
+ } = useCanvas();
const relationship = data?.relationship;
- const openRelationshipInEditor = useCallback(() => {
- selectSidebarSection('refs');
- openRelationshipFromSidebar(id);
- }, [id, openRelationshipFromSidebar, selectSidebarSection]);
+ const isPopoverOpen = useMemo(
+ () => editRelationshipPopover?.relationshipId === id,
+ [editRelationshipPopover, id]
+ );
+
+ const handleEdgeClick = useCallback(
+ (e: React.MouseEvent) => {
+ if (e.detail === 2) {
+ // Double click - open popover
+ openRelationshipPopover({
+ relationshipId: id,
+ position: { x: e.clientX, y: e.clientY },
+ });
+ }
+ // Single click just selects the edge, doesn't open popover
+ },
+ [openRelationshipPopover, id]
+ );
+
+ const handleContextMenu = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ openRelationshipPopover({
+ relationshipId: id,
+ position: { x: e.clientX, y: e.clientY },
+ });
+ },
+ [id, openRelationshipPopover]
+ );
+
+ const handleIndicatorClick = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ openRelationshipPopover({
+ relationshipId: id,
+ position: { x: e.clientX, y: e.clientY },
+ });
+ },
+ [id, openRelationshipPopover]
+ );
+
+ const handleSwitchTables = useCallback(async () => {
+ if (!relationship) return;
+ await updateRelationship(
+ id,
+ {
+ sourceTableId: relationship.targetTableId,
+ targetTableId: relationship.sourceTableId,
+ sourceFieldId: relationship.targetFieldId,
+ targetFieldId: relationship.sourceFieldId,
+ sourceCardinality: relationship.targetCardinality,
+ targetCardinality: relationship.sourceCardinality,
+ },
+ { updateHistory: true }
+ );
+
+ closeRelationshipPopover();
+ }, [
+ id,
+ relationship,
+ updateRelationship,
+ closeRelationshipPopover,
+ ]);
+
+ const handleCardinalityChange = useCallback(
+ async (
+ newSourceCardinality: Cardinality,
+ newTargetCardinality: Cardinality
+ ) => {
+ if (!relationship) return;
+ await updateRelationship(
+ id,
+ {
+ sourceCardinality: newSourceCardinality,
+ targetCardinality: newTargetCardinality,
+ },
+ { updateHistory: true }
+ );
+ closeRelationshipPopover();
+ },
+ [id, relationship, updateRelationship, closeRelationshipPopover]
+ );
+
+ const handleDelete = useCallback(() => {
+ removeRelationship(id, { updateHistory: true });
+ closeRelationshipPopover();
+ }, [id, removeRelationship, closeRelationshipPopover]);
const edgeNumber = useMemo(() => {
let index = 0;
@@ -201,6 +292,27 @@ export const RelationshipEdge: React.FC<EdgeProps<RelationshipEdgeType>> =
[checkIfRelationshipRemoved, relationship?.id]
);
+ // Calculate the midpoint of the edge for the indicator
+ const edgeMidpoint = useMemo(() => {
+ const sourceXPos =
+ sourceSide === 'left' ? sourceLeftX : sourceRightX;
+ const targetXPos =
+ targetSide === 'left' ? targetLeftX : targetRightX;
+ return {
+ x: (sourceXPos + targetXPos) / 2,
+ y: (sourceY + targetY) / 2,
+ };
+ }, [
+ sourceSide,
+ targetSide,
+ sourceLeftX,
+ sourceRightX,
+ targetLeftX,
+ targetRightX,
+ sourceY,
+ targetY,
+ ]);
+
return (
<>
<path
@@ -219,11 +331,8 @@ export const RelationshipEdge: React.FC<EdgeProps<RelationshipEdgeType>> =
isDiffRelationshipRemoved,
},
])}
- onClick={(e) => {
- if (e.detail === 2) {
- openRelationshipInEditor();
- }
- }}
+ onClick={handleEdgeClick}
+ onContextMenu={handleContextMenu}
/>
<path
d={edgePath}
@@ -232,12 +341,48 @@ export const RelationshipEdge: React.FC<EdgeProps<RelationshipEdgeType>> =
strokeWidth={20}
// eslint-disable-next-line tailwindcss/no-custom-classname
className="react-flow__edge-interaction"
- onClick={(e) => {
- if (e.detail === 2) {
- openRelationshipInEditor();
- }
- }}
+ onClick={handleEdgeClick}
+ onContextMenu={handleContextMenu}
/>
+ {selected && (
+ <foreignObject
+ width={24}
+ height={24}
+ x={edgeMidpoint.x - 12}
+ y={edgeMidpoint.y - 12}
+ className="overflow-visible"
+ style={{ pointerEvents: 'all' }}
+ >
+ <button
+ onClick={handleIndicatorClick}
+ className="relative flex size-6 items-center justify-center rounded-full border-2 border-pink-600 bg-background shadow-lg transition-all hover:scale-110 hover:bg-pink-50"
+ title="Edit relationship"
+ style={{ zIndex: 10 }}
+ >
+ <EllipsisIcon className="size-4 text-pink-600" />
+ </button>
+ </foreignObject>
+ )}
+ {relationship &&
+ isPopoverOpen &&
+ editRelationshipPopover?.position &&
+ createPortal(
+ <EditRelationshipPopover
+ anchorPosition={
+ editRelationshipPopover.position
+ }
+ sourceCardinality={
+ relationship.sourceCardinality ?? 'one'
+ }
+ targetCardinality={
+ relationship.targetCardinality ?? 'one'
+ }
+ onCardinalityChange={handleCardinalityChange}
+ onSwitch={handleSwitchTables}
+ onDelete={handleDelete}
+ />,
+ document.body
+ )}
</>
// <BaseEdge
// id={id}