Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Shared graph canvas under the FableLoom editor, with zoom (#12898)

[._.]/c7a3dc1e921f
diff --git a/client/src/components/fableloom/LoomCanvas.jsx b/client/src/components/fableloom/LoomCanvas.jsx
index 7cda93f086..ba1b620a7b 100644
--- a/client/src/components/fableloom/LoomCanvas.jsx
+++ b/client/src/components/fableloom/LoomCanvas.jsx
@@ -3,46 +3,29 @@
*
* Renders scene nodes as SVG cards with intent-labeled decision edges and
* compact, unlabeled automatic cuts. Placement, orientation, and orthogonal
- * routing come from `layoutLoomGraph`.
+ * routing come from `layoutLoomGraph`; selection, card drag, pan and zoom come
+ * from the shared `GraphCanvas`.
* The canvas measures itself for card wrapping. Flow direction comes from
* the parent when it knows the page breakpoint (editor rail beside vs
* under); otherwise `pickLoomOrientation` keys off canvas width.
* Click (or tap) selects a scene (selection lives in the URL — the parent
* navigates); mouse-drag repositions a card and persists `pos` on release.
- * Dragging anywhere a card did NOT claim pans the view instead — a graph
- * larger than its pane was otherwise only reachable by scrollbar or trackpad.
- * On the stacked layout no card claims a drag, so the whole surface pans.
- * Touch never drags — it would fight scrolling, and desktop `pos` is the
- * wrong coordinate space for the stacked layout. Selecting a scene dims
- * every edge that doesn't touch it, and on the stacked layout a path strip
- * lists the inbound/outbound intents so a dense graph stays traversable
+ * On the stacked layout no card claims a drag — its coordinates are not the
+ * desktop space `pos` lives in — so the whole surface pans. Selecting a scene
+ * dims every edge that doesn't touch it, and on the stacked layout a path
+ * strip lists the inbound/outbound intents so a dense graph stays traversable
* without tracing overlapping strokes.
*/
-import { useEffect, useId, useMemo, useRef } from 'react';
+import { useId, useMemo } from 'react';
import { Flag, Play } from 'lucide-react';
import useContainerWidth from '../../hooks/useContainerWidth';
-import useDragToPan from '../../hooks/useDragToPan';
-import { isTapGesture } from '../../lib/graphPicking';
import {
layoutLoomGraph, LOOM_EDGE_LABEL_MAX, LOOM_ORIENTATION,
} from '../../lib/loomLayout';
+import GraphCanvas from '../graphCanvas/GraphCanvas';
import LoomSceneMedia from './LoomSceneMedia';
-const DRAG_THRESHOLD_PX = 4;
-
-/**
- * Shared by both canvas gestures: how far the pointer has travelled since
- * pointerdown, or `null` while it is still close enough to read as a click.
- * Latches `moved` on the gesture once the threshold is cleared.
- */
-const gestureDelta = (gesture, event) => {
- const point = { x: event.clientX, y: event.clientY };
- if (!gesture.moved && isTapGesture(gesture.start, point, DRAG_THRESHOLD_PX)) return null;
- gesture.moved = true;
- return { dx: point.x - gesture.start.x, dy: point.y - gesture.start.y };
-};
-
const truncate = (text, max) => {
const s = typeof text === 'string' ? text : '';
return s.length > max ? `${s.slice(0, max - 1)}…` : s;
@@ -60,26 +43,6 @@ export default function LoomCanvas({
onAutomateFalVideo,
generationDisabled = false, generationDisabledReason = '',
}) {
- // An in-flight drag lives entirely outside React state: the dragged <g>'s
- // transform is mutated directly per pointermove, and the position commits
- // once on release. Routing it through setState re-rendered every node card
- // (each with a foreignObject media surface) ~60×/s. Edges catch up on release.
- const dragRef = useRef(null);
- // Set by whichever gesture actually moved, read once by the surface's
- // click-capture handler — one mechanism for "this click was a drag".
- const draggedRef = useRef(false);
- // A pan is the same story one level up: scrollLeft/scrollTop are mutated
- // directly per pointermove so no node re-renders while the view moves. A
- // card's own drag wins when both could claim the gesture (`canStart`), and
- // a completed pan folds into `draggedRef` so the shared click-capture below
- // swallows it exactly like a card drag does.
- const pan = useDragToPan({
- slop: DRAG_THRESHOLD_PX,
- canStart: () => !dragRef.current,
- onPanEnd: () => { draggedRef.current = true; },
- });
- const cardRefs = useRef(new Map());
- const mediaRefs = useRef(new Map());
const [measureRef, measuredWidth] = useContainerWidth();
const viewportWidth = viewportWidthProp ?? measuredWidth;
const markerId = useId().replace(/:/g, '');
@@ -94,297 +57,174 @@ export default function LoomCanvas({
const nodes = episode?.nodes || [];
const byId = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
- useEffect(() => {
- if (!selectedNodeId || !measureRef.current) return undefined;
- const el = measureRef.current.querySelector(`[data-node-id="${selectedNodeId}"]`);
- el?.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
- return undefined;
- }, [selectedNodeId, measureRef, layout.width, layout.height]);
-
- const handlePointerDown = (event, node) => {
- if (event.button !== 0) return;
- // Touch/pen: tap-to-select only. Capturing the pointer would steal the
- // scroll gesture, and a stacked layout's coordinates must not persist as
- // desktop `pos`.
- if (event.pointerType !== 'mouse' || stacked) return;
- event.currentTarget.setPointerCapture(event.pointerId);
- const origin = positions[node.id] || { x: 0, y: 0 };
- dragRef.current = {
- id: node.id,
- cardEl: cardRefs.current.get(node.id),
- mediaEl: mediaRefs.current.get(node.id),
- start: { x: event.clientX, y: event.clientY },
- origin,
- x: origin.x,
- y: origin.y,
- moved: false,
- };
- };
-
- const handlePointerMove = (event) => {
- const drag = dragRef.current;
- const delta = drag && gestureDelta(drag, event);
- if (!delta) return;
- drag.x = Math.max(0, drag.origin.x + delta.dx);
- drag.y = Math.max(0, drag.origin.y + delta.dy);
- drag.cardEl?.setAttribute('transform', `translate(${drag.x}, ${drag.y})`);
- // Media foreignObjects are deliberately NOT children of the transformed
- // card group. Move their absolute coordinates in lockstep while dragging.
- drag.mediaEl?.setAttribute('x', drag.x + 8);
- drag.mediaEl?.setAttribute('y', drag.y + 24);
- };
-
- const handlePointerUp = () => {
- const drag = dragRef.current;
- dragRef.current = null;
- if (!drag?.moved) return;
- draggedRef.current = true;
- onMoveNode?.(drag.id, { x: Math.round(drag.x), y: Math.round(drag.y) });
- };
-
- const handleSurfacePointerDown = (event) => {
- // Cleared at the START of every gesture: a drag released outside the canvas
- // (or cancelled) never gets its click, and a stale flag would then swallow
- // the next genuine select. `canStart` (above) already answers "did a scene
- // card claim this drag?" by asking `dragRef` — on the stacked layout cards
- // never claim a drag, so a card is pannable surface there.
- draggedRef.current = false;
- pan.panProps.onPointerDown(event);
- };
-
- // Either drag still fires a click when it ends — on the card, on an edge, or
- // (once the pointer was captured) on the surface itself. One capture-phase
- // handler on the common ancestor swallows it wherever it lands, so a drag
- // never also selects.
- const handleSurfaceClickCapture = (event) => {
- if (!draggedRef.current) return;
- draggedRef.current = false;
- event.stopPropagation();
- };
-
if (!nodes.length) return null;
- const { width, height } = layout;
const titleMax = Math.max(12, Math.floor((nodeW - 20) / 7.2));
const accentMarker = `loom-arrow-accent-${markerId}`;
const mutedMarker = `loom-arrow-${markerId}`;
const showStrip = stacked && selectedNodeId && byId.has(selectedNodeId);
+ const renderEdges = () => edges.map((edge) => {
+ // With a scene selected, its own edges come forward and the rest
+ // recede — the only way to read one path through a dense graph.
+ const connected = edge.sourceId === selectedNodeId || edge.targetId === selectedNodeId;
+ const outgoing = edge.sourceId === selectedNodeId;
+ const start = startOfPath(edge.d);
+ return (
+ <g key={edge.id} className={!selectedNodeId ? 'opacity-80' : connected ? 'opacity-100' : 'opacity-20'}>
+ <path
+ d={edge.d}
+ fill="none"
+ strokeWidth={connected ? 2.25 : 1.5}
+ markerEnd={`url(#${outgoing || (!selectedNodeId && connected) ? accentMarker : mutedMarker})`}
+ className={outgoing ? 'stroke-port-accent' : 'stroke-port-border'}
+ />
+ {/* Invisible fat stroke so a label-less jog is still easy to hover/tap. */}
+ <path
+ d={edge.d}
+ fill="none"
+ stroke="transparent"
+ strokeWidth={16}
+ className="cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectNode?.(edge.targetId);
+ }}
+ />
+ {edge.intent && edge.showLabel !== false && (
+ <text
+ x={edge.labelX}
+ y={edge.labelY}
+ textAnchor="middle"
+ role="button"
+ tabIndex={0}
+ aria-label={`Path: ${edge.intent}`}
+ style={{ paintOrder: 'stroke' }}
+ strokeWidth={4}
+ strokeLinejoin="round"
+ className="fill-port-text-muted stroke-port-bg text-[10px] cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectNode?.(edge.targetId);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onSelectNode?.(edge.targetId);
+ }
+ }}
+ >
+ {truncate(edge.intent, LOOM_EDGE_LABEL_MAX)}
+ </text>
+ )}
+ {outgoing && start && (
+ <circle cx={start.x} cy={start.y} r={3} className="fill-port-accent" />
+ )}
+ </g>
+ );
+ });
+
+ const renderNode = (node, { selected }) => {
+ const isStart = node.id === episode.startNodeId;
+ return (
+ <>
+ <rect
+ width={nodeW}
+ height={nodeH}
+ rx={10}
+ strokeWidth={selected ? 2.5 : 1}
+ className={`${node.isEnding ? 'fill-port-success/10' : 'fill-port-card'} ${
+ selected ? 'stroke-port-accent' : 'stroke-port-border'
+ }`}
+ />
+ <text x={10} y={17} className="fill-port-text text-[11px] font-semibold pointer-events-none">
+ {truncate(node.title || 'Untitled scene', titleMax)}
+ </text>
+ <g transform={`translate(10, ${nodeH - 13})`} className="pointer-events-none">
+ {isStart && (
+ <g>
+ <Play size={10} className="text-port-accent" x={0} y={-8} />
+ <text x={14} y={1} className="fill-port-accent text-[9px] font-medium">Opening</text>
+ </g>
+ )}
+ {node.isEnding && (
+ <g transform={isStart ? 'translate(64, 0)' : ''}>
+ <Flag size={10} className="text-port-success" x={0} y={-8} />
+ <text x={14} y={1} className="fill-port-success text-[9px] font-medium">
+ {truncate(node.endingLabel || 'Ending', 20)}
+ </text>
+ </g>
+ )}
+ </g>
+ {!node.isEnding && (
+ <text
+ x={nodeW - 10}
+ y={nodeH - 12}
+ textAnchor="end"
+ className={node.playbackMode === 'cut'
+ ? 'fill-port-accent text-[9px] font-medium pointer-events-none'
+ : 'fill-port-warning text-[9px] font-medium pointer-events-none'}
+ >
+ {node.playbackMode === 'cut' ? 'Auto cut' : 'Decision loop'}
+ </text>
+ )}
+ </>
+ );
+ };
+
return (
- <div className="relative h-full w-full">
- <div
- ref={(el) => { measureRef.current = el; pan.surfaceRef.current = el; }}
- className={`overflow-auto h-full w-full overscroll-contain cursor-grab active:cursor-grabbing ${showStrip ? 'pb-28' : ''}`}
- data-testid="loom-canvas"
- data-orientation={orientation}
- {...pan.panProps}
- onPointerDown={handleSurfacePointerDown}
- onClickCapture={handleSurfaceClickCapture}
+ <div ref={measureRef} className="h-full w-full">
+ <GraphCanvas
+ width={layout.width}
+ height={layout.height}
+ nodes={nodes}
+ positions={positions}
+ nodeW={nodeW}
+ nodeH={nodeH}
+ selectedId={selectedNodeId}
+ canDragNodes={!stacked}
+ onSelect={onSelectNode}
+ onMove={onMoveNode}
+ ariaLabel="Episode scene graph"
+ nodeLabel={(node) => `Scene: ${node.title || 'Untitled'}`}
+ surfaceProps={{ 'data-testid': 'loom-canvas', 'data-orientation': orientation }}
+ surfaceClassName={showStrip ? 'pb-28' : ''}
+ renderDefs={() => (
+ <>
+ <marker id={mutedMarker} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
+ <path d="M0,1 L8,4 L0,7 Z" className="fill-port-border" />
+ </marker>
+ <marker id={accentMarker} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
+ <path d="M0,1 L8,4 L0,7 Z" className="fill-port-accent" />
+ </marker>
+ </>
+ )}
+ renderEdges={renderEdges}
+ renderNode={renderNode}
+ htmlInset={{ x: 8, y: 24, width: nodeW - 16, height: nodeH - 52 }}
+ renderNodeHtml={(node) => (
+ <LoomSceneMedia
+ node={node}
+ jobs={mediaJobs[node.id]}
+ onGenerateImage={onGenerateImage}
+ onGenerateVideo={onGenerateVideo}
+ onAutomateFalVideo={onAutomateFalVideo}
+ compact
+ generationDisabled={generationDisabled}
+ generationDisabledReason={generationDisabledReason}
+ />
+ )}
>
- <svg
- width={width}
- height={height}
- className="block select-none"
- aria-label="Episode scene graph"
- >
- <defs>
- <marker id={mutedMarker} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
- <path d="M0,1 L8,4 L0,7 Z" className="fill-port-border" />
- </marker>
- <marker id={accentMarker} markerWidth="8" markerHeight="8" refX="7" refY="4" orient="auto">
- <path d="M0,1 L8,4 L0,7 Z" className="fill-port-accent" />
- </marker>
- </defs>
- <g>
- {edges.map((edge) => {
- // With a scene selected, its own edges come forward and the rest
- // recede — the only way to read one path through a dense graph.
- const connected = edge.sourceId === selectedNodeId || edge.targetId === selectedNodeId;
- const outgoing = edge.sourceId === selectedNodeId;
- const start = startOfPath(edge.d);
- return (
- <g key={edge.id} className={!selectedNodeId ? 'opacity-80' : connected ? 'opacity-100' : 'opacity-20'}>
- <path
- d={edge.d}
- fill="none"
- strokeWidth={connected ? 2.25 : 1.5}
- markerEnd={`url(#${outgoing || (!selectedNodeId && connected) ? accentMarker : mutedMarker})`}
- className={outgoing ? 'stroke-port-accent' : 'stroke-port-border'}
- />
- {/* Invisible fat stroke so a label-less jog is still easy to hover/tap. */}
- <path
- d={edge.d}
- fill="none"
- stroke="transparent"
- strokeWidth={16}
- className="cursor-pointer"
- onClick={(e) => {
- e.stopPropagation();
- onSelectNode?.(edge.targetId);
- }}
- />
- {edge.intent && edge.showLabel !== false && (
- <text
- x={edge.labelX}
- y={edge.labelY}
- textAnchor="middle"
- role="button"
- tabIndex={0}
- aria-label={`Path: ${edge.intent}`}
- style={{ paintOrder: 'stroke' }}
- strokeWidth={4}
- strokeLinejoin="round"
- className="fill-port-text-muted stroke-port-bg text-[10px] cursor-pointer"
- onClick={(e) => {
- e.stopPropagation();
- onSelectNode?.(edge.targetId);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- onSelectNode?.(edge.targetId);
- }
- }}
- >
- {truncate(edge.intent, LOOM_EDGE_LABEL_MAX)}
- </text>
- )}
- {outgoing && start && (
- <circle cx={start.x} cy={start.y} r={3} className="fill-port-accent" />
- )}
- </g>
- );
- })}
- </g>
- <g>
- {nodes.map((node) => {
- const pos = positions[node.id];
- if (!pos) return null;
- const selected = node.id === selectedNodeId;
- const isStart = node.id === episode.startNodeId;
- return (
- <g
- key={node.id}
- ref={(element) => {
- if (element) cardRefs.current.set(node.id, element);
- else cardRefs.current.delete(node.id);
- }}
- data-node-id={node.id}
- transform={`translate(${pos.x}, ${pos.y})`}
- className={stacked ? 'cursor-pointer' : 'cursor-grab'}
- role="button"
- tabIndex={0}
- aria-label={`Scene: ${node.title || 'Untitled'}`}
- aria-current={selected ? 'true' : undefined}
- onPointerDown={(e) => handlePointerDown(e, node)}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerUp}
- onClick={() => onSelectNode?.(node.id)}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- onSelectNode?.(node.id);
- }
- }}
- >
- <rect
- width={nodeW}
- height={nodeH}
- rx={10}
- strokeWidth={selected ? 2.5 : 1}
- className={`${node.isEnding ? 'fill-port-success/10' : 'fill-port-card'} ${
- selected ? 'stroke-port-accent' : 'stroke-port-border'
- }`}
- />
- <text x={10} y={17} className="fill-port-text text-[11px] font-semibold pointer-events-none">
- {truncate(node.title || 'Untitled scene', titleMax)}
- </text>
- <g transform={`translate(10, ${nodeH - 13})`} className="pointer-events-none">
- {isStart && (
- <g>
- <Play size={10} className="text-port-accent" x={0} y={-8} />
- <text x={14} y={1} className="fill-port-accent text-[9px] font-medium">Opening</text>
- </g>
- )}
- {node.isEnding && (
- <g transform={isStart ? 'translate(64, 0)' : ''}>
- <Flag size={10} className="text-port-success" x={0} y={-8} />
- <text x={14} y={1} className="fill-port-success text-[9px] font-medium">
- {truncate(node.endingLabel || 'Ending', 20)}
- </text>
- </g>
- )}
- </g>
- {!node.isEnding && (
- <text
- x={nodeW - 10}
- y={nodeH - 12}
- textAnchor="end"
- className={node.playbackMode === 'cut'
- ? 'fill-port-accent text-[9px] font-medium pointer-events-none'
- : 'fill-port-warning text-[9px] font-medium pointer-events-none'}
- >
- {node.playbackMode === 'cut' ? 'Auto cut' : 'Decision loop'}
- </text>
- )}
- </g>
- );
- })}
- </g>
- {/* WebKit/iOS paints HTML inside a foreignObject at the wrong place
- when an ancestor SVG group is transformed. Keep each media surface
- at the SVG root and give it already-resolved canvas coordinates so
- images and videos stay inside their scene card on every engine. */}
- <g>
- {nodes.map((node) => {
- const pos = positions[node.id];
- if (!pos) return null;
- return (
- <foreignObject
- key={node.id}
- ref={(element) => {
- if (element) mediaRefs.current.set(node.id, element);
- else mediaRefs.current.delete(node.id);
- }}
- data-node-media-id={node.id}
- x={pos.x + 8}
- y={pos.y + 24}
- width={nodeW - 16}
- height={nodeH - 52}
- onPointerDown={(event) => handlePointerDown(event, node)}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerCancel={handlePointerUp}
- onClick={() => onSelectNode?.(node.id)}
- >
- <div className="h-full w-full min-w-0 overflow-hidden" xmlns="http://www.w3.org/1999/xhtml">
- <LoomSceneMedia
- node={node}
- jobs={mediaJobs[node.id]}
- onGenerateImage={onGenerateImage}
- onGenerateVideo={onGenerateVideo}
- onAutomateFalVideo={onAutomateFalVideo}
- compact
- generationDisabled={generationDisabled}
- generationDisabledReason={generationDisabledReason}
- />
- </div>
- </foreignObject>
- );
- })}
- </g>
- </svg>
- </div>
- {showStrip && (
- <PathStrip
- episode={episode}
- node={byId.get(selectedNodeId)}
- byId={byId}
- onSelectNode={onSelectNode}
- />
- )}
+ {showStrip && (
+ <PathStrip
+ episode={episode}
+ node={byId.get(selectedNodeId)}
+ byId={byId}
+ onSelectNode={onSelectNode}
+ />
+ )}
+ </GraphCanvas>
</div>
);
}
diff --git a/client/src/components/graphCanvas/GraphCanvas.jsx b/client/src/components/graphCanvas/GraphCanvas.jsx
new file mode 100644
index 0000000000..eaa91dda06
--- /dev/null
+++ b/client/src/components/graphCanvas/GraphCanvas.jsx
@@ -0,0 +1,301 @@
+/**
+ * Shared SVG graph canvas — the gesture and viewport layer under every node
+ * editor (FableLoom's scene graph today; storyboard recipes next).
+ *
+ * The caller owns layout and drawing: it passes node positions, draws edges
+ * with `renderEdges`, a card's SVG body with `renderNode`, and optional HTML
+ * media with `renderNodeHtml`. The canvas owns what every graph editor needs
+ * the same way:
+ *
+ * - tap/click/keyboard selection (`onSelect`; selection lives in the URL, so
+ * the parent navigates) and scrolling the selected card into view;
+ * - mouse-drag to reposition a card, committed once on release (`onMove`).
+ * A drag mutates the card's transform directly per pointermove; routing it
+ * through state re-rendered every card (each with a foreignObject) ~60×/s;
+ * - drag-to-pan wherever a card did not claim the gesture, and one
+ * capture-phase handler that swallows the click any drag ends with;
+ * - zoom (buttons, Fit, and ctrl/⌘ + wheel, which is also a trackpad pinch).
+ * The SVG keeps its canvas-unit `viewBox` and scales its pixel size, so
+ * positions and `onMove` coordinates stay in canvas units at any zoom.
+ *
+ * Touch never drags a card (it would fight scrolling), and `canDragNodes={false}`
+ * turns card drags off entirely — a stacked phone layout's coordinates must
+ * not persist as desktop positions; its cards are pannable surface instead.
+ *
+ * WebKit/iOS paints HTML inside a foreignObject at the wrong place when an
+ * ancestor SVG group is transformed, so `renderNodeHtml` content is placed at
+ * the SVG root with resolved coordinates (`htmlInset` relative to the card)
+ * and moved in lockstep with its card during a drag.
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { Maximize, Minus, Plus } from 'lucide-react';
+import useDragToPan from '../../hooks/useDragToPan';
+import { isTapGesture } from '../../lib/graphPicking';
+
+const DRAG_THRESHOLD_PX = 4;
+export const GRAPH_ZOOM_MIN = 0.25;
+export const GRAPH_ZOOM_MAX = 2;
+const ZOOM_STEP = 1.25;
+
+// Unrounded: a slow trackpad pinch arrives as many sub-percent wheel steps,
+// and rounding each one against the last rounded zoom would drop them all.
+const clampZoom = (z) => Math.min(GRAPH_ZOOM_MAX, Math.max(GRAPH_ZOOM_MIN, z));
+
+/**
+ * How far the pointer has travelled since pointerdown in screen px, or `null`
+ * while it is still close enough to read as a click. Latches `moved` once the
+ * threshold is cleared.
+ */
+const gestureDelta = (gesture, event) => {
+ const point = { x: event.clientX, y: event.clientY };
+ if (!gesture.moved && isTapGesture(gesture.start, point, DRAG_THRESHOLD_PX)) return null;
+ gesture.moved = true;
+ return { dx: point.x - gesture.start.x, dy: point.y - gesture.start.y };
+};
+
+export default function GraphCanvas({
+ width, height, nodes, positions, nodeW, nodeH,
+ selectedId = null, canDragNodes = true,
+ onSelect, onMove,
+ renderDefs, renderEdges, renderNode, renderNodeHtml, htmlInset,
+ nodeLabel, nodeClassName,
+ ariaLabel, surfaceProps = {}, surfaceClassName = '',
+ zoomControls = true, children,
+}) {
+ const dragRef = useRef(null);
+ const draggedRef = useRef(false);
+ const pan = useDragToPan({
+ slop: DRAG_THRESHOLD_PX,
+ canStart: () => !dragRef.current,
+ onPanEnd: () => { draggedRef.current = true; },
+ });
+ const cardRefs = useRef(new Map());
+ const htmlRefs = useRef(new Map());
+ const measureRef = useRef(null);
+ const [zoom, setZoom] = useState(1);
+ const zoomRef = useRef(zoom);
+ zoomRef.current = zoom;
+
+ useEffect(() => {
+ if (!selectedId || !measureRef.current) return undefined;
+ const el = measureRef.current.querySelector(`[data-node-id="${selectedId}"]`);
+ el?.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
+ return undefined;
+ }, [selectedId, measureRef, width, height]);
+
+ // Zoom about a point in surface (client-relative) coordinates so the canvas
+ // spot under it stays put — the viewport centre for buttons, the pointer
+ // for a wheel/pinch.
+ const applyZoom = useCallback((next, anchor) => {
+ const surface = measureRef.current;
+ const prev = zoomRef.current;
+ const target = clampZoom(next);
+ if (target === prev) return;
+ zoomRef.current = target;
+ setZoom(target);
+ if (!surface) return;
+ const ax = anchor?.x ?? surface.clientWidth / 2;
+ const ay = anchor?.y ?? surface.clientHeight / 2;
+ const cx = (surface.scrollLeft + ax) / prev;
+ const cy = (surface.scrollTop + ay) / prev;
+ // The new SVG size lands on the next frame; scroll after it does.
+ requestAnimationFrame(() => {
+ surface.scrollLeft = cx * target - ax;
+ surface.scrollTop = cy * target - ay;
+ });
+ }, [measureRef]);
+
+ const fit = useCallback(() => {
+ const surface = measureRef.current;
+ if (!surface || !width || !height) return;
+ const scale = Math.min(surface.clientWidth / width, surface.clientHeight / height, 1);
+ applyZoom(scale || 1);
+ }, [measureRef, width, height, applyZoom]);
+
+ // React's onWheel is passive, so preventDefault (keep the page from zooming
+ // under a pinch) needs a native listener.
+ useEffect(() => {
+ const surface = measureRef.current;
+ if (!surface) return undefined;
+ const onWheel = (event) => {
+ if (!event.ctrlKey && !event.metaKey) return;
+ event.preventDefault();
+ const rect = surface.getBoundingClientRect();
+ const factor = Math.exp(-event.deltaY / 200);
+ applyZoom(zoomRef.current * factor, { x: event.clientX - rect.left, y: event.clientY - rect.top });
+ };
+ surface.addEventListener('wheel', onWheel, { passive: false });
+ return () => surface.removeEventListener('wheel', onWheel);
+ });
+
+ const handlePointerDown = (event, node) => {
+ if (event.button !== 0) return;
+ if (event.pointerType !== 'mouse' || !canDragNodes || !onMove) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ const origin = positions[node.id] || { x: 0, y: 0 };
+ dragRef.current = {
+ id: node.id,
+ cardEl: cardRefs.current.get(node.id),
+ htmlEl: htmlRefs.current.get(node.id),
+ start: { x: event.clientX, y: event.clientY },
+ origin,
+ x: origin.x,
+ y: origin.y,
+ moved: false,
+ };
+ };
+
+ const handlePointerMove = (event) => {
+ const drag = dragRef.current;
+ const delta = drag && gestureDelta(drag, event);
+ if (!delta) return;
+ const z = zoomRef.current;
+ drag.x = Math.max(0, drag.origin.x + delta.dx / z);
+ drag.y = Math.max(0, drag.origin.y + delta.dy / z);
+ drag.cardEl?.setAttribute('transform', `translate(${drag.x}, ${drag.y})`);
+ if (drag.htmlEl && htmlInset) {
+ drag.htmlEl.setAttribute('x', drag.x + htmlInset.x);
+ drag.htmlEl.setAttribute('y', drag.y + htmlInset.y);
+ }
+ };
+
+ const handlePointerUp = () => {
+ const drag = dragRef.current;
+ dragRef.current = null;
+ if (!drag?.moved) return;
+ draggedRef.current = true;
+ onMove?.(drag.id, { x: Math.round(drag.x), y: Math.round(drag.y) });
+ };
+
+ const handleSurfacePointerDown = (event) => {
+ // Cleared at the START of every gesture: a drag released outside the
+ // canvas (or cancelled) never gets its click, and a stale flag would then
+ // swallow the next genuine select.
+ draggedRef.current = false;
+ pan.panProps.onPointerDown(event);
+ };
+
+ const handleSurfaceClickCapture = (event) => {
+ if (!draggedRef.current) return;
+ draggedRef.current = false;
+ event.stopPropagation();
+ };
+
+ const cardHandlers = (node) => ({
+ onPointerDown: (e) => handlePointerDown(e, node),
+ onPointerMove: handlePointerMove,
+ onPointerUp: handlePointerUp,
+ onPointerCancel: handlePointerUp,
+ onClick: () => onSelect?.(node.id),
+ });
+
+ const zoomPct = Math.round(zoom * 100);
+
+ return (
+ <div className="relative h-full w-full">
+ <div
+ ref={(el) => { measureRef.current = el; pan.surfaceRef.current = el; }}
+ className={`overflow-auto h-full w-full overscroll-contain cursor-grab active:cursor-grabbing ${surfaceClassName}`}
+ data-zoom={zoom}
+ {...surfaceProps}
+ {...pan.panProps}
+ onPointerDown={handleSurfacePointerDown}
+ onClickCapture={handleSurfaceClickCapture}
+ >
+ <svg
+ width={Math.ceil(width * zoom)}
+ height={Math.ceil(height * zoom)}
+ viewBox={`0 0 ${width} ${height}`}
+ className="block select-none"
+ aria-label={ariaLabel}
+ >
+ {renderDefs && <defs>{renderDefs()}</defs>}
+ <g>{renderEdges?.()}</g>
+ <g>
+ {nodes.map((node) => {
+ const pos = positions[node.id];
+ if (!pos) return null;
+ const selected = node.id === selectedId;
+ return (
+ <g
+ key={node.id}
+ ref={(element) => {
+ if (element) cardRefs.current.set(node.id, element);
+ else cardRefs.current.delete(node.id);
+ }}
+ data-node-id={node.id}
+ transform={`translate(${pos.x}, ${pos.y})`}
+ className={`${canDragNodes && onMove ? 'cursor-grab' : 'cursor-pointer'} ${nodeClassName?.(node) || ''}`}
+ role="button"
+ tabIndex={0}
+ aria-label={nodeLabel?.(node)}
+ aria-current={selected ? 'true' : undefined}
+ {...cardHandlers(node)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ onSelect?.(node.id);
+ }
+ }}
+ >
+ {renderNode(node, { selected, width: nodeW, height: nodeH })}
+ </g>
+ );
+ })}
+ </g>
+ {renderNodeHtml && htmlInset && (
+ <g>
+ {nodes.map((node) => {
+ const pos = positions[node.id];
+ if (!pos) return null;
+ return (
+ <foreignObject
+ key={node.id}
+ ref={(element) => {
+ if (element) htmlRefs.current.set(node.id, element);
+ else htmlRefs.current.delete(node.id);
+ }}
+ data-node-media-id={node.id}
+ x={pos.x + htmlInset.x}
+ y={pos.y + htmlInset.y}
+ width={htmlInset.width}
+ height={htmlInset.height}
+ {...cardHandlers(node)}
+ >
+ <div className="h-full w-full min-w-0 overflow-hidden" xmlns="http://www.w3.org/1999/xhtml">
+ {renderNodeHtml(node)}
+ </div>
+ </foreignObject>
+ );
+ })}
+ </g>
+ )}
+ </svg>
+ </div>
+ {zoomControls && (
+ <div
+ className="absolute top-2 right-2 flex items-center gap-0.5 rounded-lg border border-port-border bg-port-card/95 p-0.5 shadow-sm"
+ data-testid="graph-zoom-controls"
+ >
+ <button type="button" onClick={() => applyZoom(zoom / ZOOM_STEP)} disabled={zoom <= GRAPH_ZOOM_MIN}
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded hover:bg-port-border/50 disabled:opacity-40" aria-label="Zoom out">
+ <Minus size={14} />
+ </button>
+ <button type="button" onClick={() => applyZoom(1)}
+ className="min-h-[44px] min-w-[3rem] px-1 text-[11px] tabular-nums text-port-text-muted hover:text-port-text" aria-label="Reset zoom to 100%">
+ {zoomPct}%
+ </button>
+ <button type="button" onClick={() => applyZoom(zoom * ZOOM_STEP)} disabled={zoom >= GRAPH_ZOOM_MAX}
+ className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded hover:bg-port-border/50 disabled:opacity-40" aria-label="Zoom in">
+ <Plus size={14} />
+ </button>
+ <button type="button" onClick={fit} className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center rounded hover:bg-port-border/50" aria-label="Fit graph to view">
+ <Maximize size={14} />
+ </button>
+ </div>
+ )}
+ {children}
+ </div>
+ );
+}
diff --git a/client/src/components/graphCanvas/GraphCanvas.test.jsx b/client/src/components/graphCanvas/GraphCanvas.test.jsx
new file mode 100644
index 0000000000..1da8d98d2b
--- /dev/null
+++ b/client/src/components/graphCanvas/GraphCanvas.test.jsx
@@ -0,0 +1,89 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import GraphCanvas from './GraphCanvas';
+
+const nodes = [{ id: 'a', label: 'Alpha' }, { id: 'b', label: 'Beta' }];
+const positions = { a: { x: 20, y: 20 }, b: { x: 300, y: 20 } };
+
+const renderCanvas = (props = {}) => render(
+ <GraphCanvas
+ width={600}
+ height={200}
+ nodes={nodes}
+ positions={positions}
+ nodeW={160}
+ nodeH={80}
+ nodeLabel={(n) => `Node: ${n.label}`}
+ renderNode={() => <rect width={160} height={80} />}
+ surfaceProps={{ 'data-testid': 'surface' }}
+ {...props}
+ />,
+);
+
+describe('GraphCanvas', () => {
+ it('zooms by scaling the SVG while positions stay in canvas units', () => {
+ renderCanvas();
+ const svg = screen.getByTestId('surface').querySelector('svg');
+ expect(svg).toHaveAttribute('width', '600');
+
+ fireEvent.click(screen.getByLabelText('Zoom in'));
+ expect(svg).toHaveAttribute('width', '750');
+ expect(svg).toHaveAttribute('viewBox', '0 0 600 200');
+ expect(screen.getByLabelText('Node: Alpha')).toHaveAttribute('transform', 'translate(20, 20)');
+ expect(screen.getByLabelText('Reset zoom to 100%')).toHaveTextContent('125%');
+
+ fireEvent.click(screen.getByLabelText('Reset zoom to 100%'));
+ expect(svg).toHaveAttribute('width', '600');
+ });
+
+ it('commits a drag at zoom in canvas units, not screen pixels', () => {
+ const onMove = vi.fn();
+ renderCanvas({ onMove });
+ fireEvent.click(screen.getByLabelText('Zoom in'));
+ fireEvent.click(screen.getByLabelText('Zoom in'));
+ expect(screen.getByLabelText('Reset zoom to 100%')).toHaveTextContent('156%');
+
+ const card = screen.getByLabelText('Node: Alpha');
+ fireEvent.pointerDown(card, { pointerId: 1, pointerType: 'mouse', button: 0, clientX: 100, clientY: 100 });
+ fireEvent.pointerMove(card, { pointerId: 1, pointerType: 'mouse', clientX: 256, clientY: 100 });
+ fireEvent.pointerUp(card, { pointerId: 1, pointerType: 'mouse' });
+
+ // 156 screen px at 1.56× is 100 canvas units.
+ expect(onMove).toHaveBeenCalledWith('a', { x: 120, y: 20 });
+ });
+
+ it('zooms with ctrl + wheel (a trackpad pinch) and blocks the page zoom', () => {
+ renderCanvas();
+ const surface = screen.getByTestId('surface');
+ // happy-dom's WheelEvent drops ctrlKey, so build the event by hand.
+ const wheel = (init) => Object.assign(new Event('wheel', { bubbles: true, cancelable: true }), { deltaY: -200, clientX: 0, clientY: 0, ...init });
+ const pinch = wheel({ ctrlKey: true });
+ act(() => { surface.dispatchEvent(pinch); });
+ expect(pinch.defaultPrevented).toBe(true);
+ expect(Number(surface.dataset.zoom)).toBeGreaterThan(1);
+
+ const scroll = wheel({});
+ act(() => { surface.dispatchEvent(scroll); });
+ expect(scroll.defaultPrevented).toBe(false);
+ });
+
+ it('follows a slow pinch made of sub-percent wheel steps', () => {
+ renderCanvas();
+ const surface = screen.getByTestId('surface');
+ for (let i = 0; i < 8; i += 1) {
+ const step = Object.assign(new Event('wheel', { bubbles: true, cancelable: true }), { deltaY: -0.5, clientX: 0, clientY: 0, ctrlKey: true });
+ act(() => { surface.dispatchEvent(step); });
+ }
+ expect(Number(surface.dataset.zoom)).toBeCloseTo(Math.exp(8 * 0.5 / 200), 6);
+ });
+
+ it('never drags a card when dragging is off, so a stacked layout keeps its positions', () => {
+ const onMove = vi.fn();
+ renderCanvas({ onMove, canDragNodes: false });
+ const card = screen.getByLabelText('Node: Beta');
+ fireEvent.pointerDown(card, { pointerId: 2, pointerType: 'mouse', button: 0, clientX: 100, clientY: 100 });
+ fireEvent.pointerMove(card, { pointerId: 2, pointerType: 'mouse', clientX: 200, clientY: 100 });
+ fireEvent.pointerUp(card, { pointerId: 2, pointerType: 'mouse' });
+ expect(onMove).not.toHaveBeenCalled();
+ });
+});