@kolosal-ai/rivet 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/align.ts","../src/changes.ts","../src/clipboard.ts","../src/components/controls.tsx","../../utils/src/id.ts","../src/constants.ts","../src/edge-alignment.ts","../src/edge-ends.ts","../src/gesture-guard.ts","../src/graph.ts","../src/history.ts","../src/viewport.ts","../src/renderer/edge-paths.ts","../src/renderer/edge-geometry.ts","../src/store.ts","../src/connection.ts","../src/input/connection-drag.ts","../src/components/handle.tsx","../src/components/default-node.tsx","../src/components/group-node.tsx","../src/components/minimap.tsx","../src/components/node-resizer.tsx","../src/presence/local.ts","../src/hooks/use-local-presence.ts","../src/hooks/use-rivet-config.ts","../src/input/keyboard.ts","../src/input/keys.ts","../src/input/layer-hint.ts","../src/input/marquee-controller.ts","../src/input/pan-controller.ts","../src/input/resize-controller.ts","../src/input/zoom-controller.ts","../src/renderer/background.ts","../src/renderer/presence.ts","../src/renderer/swimlane.ts","../src/hooks/use-rivet-runtime.ts","../src/hooks/use-swimlanes.ts","../src/renderer/canvas-2d-edge-renderer.ts","../src/components/edge-label-layer.tsx","../src/input/group-drag.ts","../src/components/node-anchors.tsx","../src/components/node-wrapper.tsx","../src/components/nodes-selection.tsx","../src/components/node-layer.tsx","../src/components/swimlane-overlay.tsx","../src/components/rivet.tsx","../src/hooks/use-rivet.ts","../src/index.ts"],"names":["side","id","jsx","jsxs","baseStyle","hoveredStyle","selectedStyle","useRef","useEffect","Fragment","CULL_MARGIN_PX","useMemo","size","useState","useCallback","labelStyle","sameIds","useSyncExternalStore","NodeWrapper","node","memo","NodesSelection","rect","containerStyle"],"mappings":";;;;;;;;;;AAGA,IAAM,MAAA,GAAS,CAAC,CAAA,KAAsC,CAAC,EAAE,CAAA,EAAG,CAAA,CAAE,CAAA,GAAI,CAAA,CAAE,KAAA,GA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IACA,IAAA,EAAM,MAAM,KAAA,CAAM,IAAA,EAAK;AAAA,IACvB,IAAA,EAAM,MAAM,KAAA,CAAM,IAAA,EAAK;AAAA,IACvB,OAAA,EAAS,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,IAC7B,OAAA,EAAS,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,IAC7B,YAAA,EAAc,MAAM,KAAA,CAAM,YAAA;AAAa,GACzC;AACF;AAWO,SAAS,QAAA,GAGd;AACA,EAAA,MAAM,EAAE,KAAA,EAAO,QAAA,EAAU,mBAAA,KAAwB,eAAA,EAAgB;AACjE,EAAA,OAAOS,OAAAA;AAAA,IACL,MAAM,aAAA,CAAoC,KAAA,EAAO,QAAA,EAAU,mBAAmB,CAAA;AAAA,IAC9E,CAAC,KAAA,EAAO,QAAA,EAAU,mBAAmB;AAAA,GACvC;AACF;;;AC5NO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["import type { AlignmentGuide, Rect, Vec2 } from \"./types\"\n\n/** The three snap edges along X (left, center, right) and Y (top, center, bottom). */\nconst edgesX = (r: Rect): [number, number, number] => [r.x, r.x + r.width / 2, r.x + r.width]\nconst edgesY = (r: Rect): [number, number, number] => [r.y, r.y + r.height / 2, r.y + r.height]\n\ntype Best = { delta: number; position: number; other: Rect }\n\n/**\n * Find the closest edge alignment between the moving rect and any static rect,\n * within `threshold` (world units), independently per axis. Returns the offset\n * to apply to `moving` so its aligned edge lands exactly on the neighbor's, plus\n * the guide line(s) to draw. Pure — the drag loop supplies the rects.\n */\nexport function alignRect(\n moving: Rect,\n statics: readonly Rect[],\n threshold: number,\n): { offset: Vec2; guides: AlignmentGuide[] } {\n const mX = edgesX(moving)\n const mY = edgesY(moving)\n let bestX: Best | null = null\n let bestY: Best | null = null\n\n for (const other of statics) {\n const oX = edgesX(other)\n const oY = edgesY(other)\n for (const me of mX) {\n for (const oe of oX) {\n const delta = oe - me\n if (Math.abs(delta) <= threshold && (!bestX || Math.abs(delta) < Math.abs(bestX.delta))) {\n bestX = { delta, position: oe, other }\n }\n }\n }\n for (const me of mY) {\n for (const oe of oY) {\n const delta = oe - me\n if (Math.abs(delta) <= threshold && (!bestY || Math.abs(delta) < Math.abs(bestY.delta))) {\n bestY = { delta, position: oe, other }\n }\n }\n }\n }\n\n const offset: Vec2 = { x: bestX?.delta ?? 0, y: bestY?.delta ?? 0 }\n const guides: AlignmentGuide[] = []\n if (bestX) {\n const o = bestX.other\n guides.push({\n axis: \"x\",\n position: bestX.position,\n start: Math.min(moving.y + offset.y, o.y),\n end: Math.max(moving.y + moving.height + offset.y, o.y + o.height),\n })\n }\n if (bestY) {\n const o = bestY.other\n guides.push({\n axis: \"y\",\n position: bestY.position,\n start: Math.min(moving.x + offset.x, o.x),\n end: Math.max(moving.x + moving.width + offset.x, o.x + o.width),\n })\n }\n return { offset, guides }\n}\n","import type { EdgeChange, EdgeId, NodeChange, NodeId, RivetEdge, RivetNode } from \"./types\"\n\n/**\n * Apply a batch of {@link NodeChange}s to a nodes array, returning a new array\n * (the input is not mutated). Order is preserved; added nodes are appended.\n *\n * Pair this with the graph's `onNodesChange` to run controlled mode:\n * ```ts\n * const [nodes, setNodes] = useState(initial)\n * <Rivet nodes={nodes} onNodesChange={(c) => setNodes((ns) => applyNodeChanges(c, ns))} />\n * ```\n */\nexport function applyNodeChanges<TData = unknown>(\n changes: NodeChange<TData>[],\n nodes: RivetNode<TData>[],\n): RivetNode<TData>[] {\n if (changes.length === 0) return nodes\n\n const byId = new Map<NodeId, RivetNode<TData>>(nodes.map((node) => [node.id, node]))\n const order: NodeId[] = nodes.map((node) => node.id)\n\n for (const change of changes) {\n switch (change.type) {\n case \"add\": {\n if (!byId.has(change.item.id)) order.push(change.item.id)\n byId.set(change.item.id, change.item)\n break\n }\n case \"replace\": {\n byId.set(change.id, change.item)\n break\n }\n case \"remove\": {\n byId.delete(change.id)\n break\n }\n case \"position\": {\n const node = byId.get(change.id)\n if (node) {\n byId.set(change.id, {\n ...node,\n position: change.position ?? node.position,\n dragging: change.dragging,\n })\n }\n break\n }\n case \"dimensions\": {\n const node = byId.get(change.id)\n if (node) {\n byId.set(change.id, {\n ...node,\n size: change.dimensions,\n // A resize (not a measurement) sets explicit width/height.\n ...(change.resizing !== undefined\n ? { width: change.dimensions.width, height: change.dimensions.height }\n : {}),\n })\n }\n break\n }\n case \"select\": {\n const node = byId.get(change.id)\n if (node) byId.set(change.id, { ...node, selected: change.selected })\n break\n }\n }\n }\n\n const result: RivetNode<TData>[] = []\n for (const id of order) {\n const node = byId.get(id)\n if (node) result.push(node)\n }\n return result\n}\n\n/**\n * Apply a batch of {@link EdgeChange}s to an edges array, returning a new array.\n * Order is preserved; added edges are appended. See {@link applyNodeChanges}.\n */\nexport function applyEdgeChanges<TData = unknown>(\n changes: EdgeChange<TData>[],\n edges: RivetEdge<TData>[],\n): RivetEdge<TData>[] {\n if (changes.length === 0) return edges\n\n const byId = new Map<EdgeId, RivetEdge<TData>>(edges.map((edge) => [edge.id, edge]))\n const order: EdgeId[] = edges.map((edge) => edge.id)\n\n for (const change of changes) {\n switch (change.type) {\n case \"add\": {\n if (!byId.has(change.item.id)) order.push(change.item.id)\n byId.set(change.item.id, change.item)\n break\n }\n case \"replace\": {\n byId.set(change.id, change.item)\n break\n }\n case \"remove\": {\n byId.delete(change.id)\n break\n }\n case \"select\": {\n const edge = byId.get(change.id)\n if (edge) byId.set(change.id, { ...edge, selected: change.selected })\n break\n }\n }\n }\n\n const result: RivetEdge<TData>[] = []\n for (const id of order) {\n const edge = byId.get(id)\n if (edge) result.push(edge)\n }\n return result\n}\n","import type { NodeId, RivetEdge, RivetNode, Vec2 } from \"./types\"\n\nconst ORIGIN: Vec2 = { x: 0, y: 0 }\nconst defaultId = (): NodeId => crypto.randomUUID()\n\n/** Options for {@link cloneElements}. */\nexport type CloneOptions = {\n /**\n * World-space offset applied to every top-level clone's position. Children of\n * a copied parent keep their parent-relative position and ride along.\n * Default `{0,0}`.\n */\n offset?: Vec2\n /** Id generator for the clones. Default `crypto.randomUUID`. */\n makeId?: () => NodeId\n}\n\n/** The result of {@link cloneElements}: fresh nodes and their internal edges. */\nexport type ClonedElements<TNodeData = unknown, TEdgeData = unknown> = {\n nodes: RivetNode<TNodeData>[]\n edges: RivetEdge<TEdgeData>[]\n}\n\n/**\n * Clone a set of nodes (and the edges wholly between them) with fresh ids —\n * the core of copy/paste and duplicate. Edges are kept only when **both**\n * endpoints are in the set (dangling connections to un-copied nodes are\n * dropped). `parentId` is remapped when the parent is also copied, else cleared\n * so the clone isn't orphaned to a missing parent. Transient flags are stripped;\n * selecting the clones is the caller's job.\n */\nexport function cloneElements<TNodeData = unknown, TEdgeData = unknown>(\n nodes: RivetNode<TNodeData>[],\n edges: RivetEdge<TEdgeData>[],\n options: CloneOptions = {},\n): ClonedElements<TNodeData, TEdgeData> {\n const offset = options.offset ?? ORIGIN\n const makeId = options.makeId ?? defaultId\n\n const idMap = new Map<NodeId, NodeId>()\n for (const node of nodes) idMap.set(node.id, makeId())\n const remap = (id: NodeId): NodeId => idMap.get(id) ?? id\n\n const clonedNodes = nodes.map((node) => {\n // A child of a copied parent keeps its parent-relative position — the\n // subtree shifts once, through the parent. Offsetting it too would move it\n // a second time inside the cloned parent's box.\n const parentCopied = node.parentId !== undefined && idMap.has(node.parentId)\n const next: RivetNode<TNodeData> = {\n ...node,\n id: remap(node.id),\n position: parentCopied\n ? { ...node.position }\n : { x: node.position.x + offset.x, y: node.position.y + offset.y },\n }\n next.hovered = undefined\n next.dragging = undefined\n next.selected = undefined\n if (node.parentId) next.parentId = idMap.has(node.parentId) ? remap(node.parentId) : undefined\n return next\n })\n\n const clonedEdges = edges\n .filter((edge) => idMap.has(edge.source) && idMap.has(edge.target))\n .map((edge) => ({\n ...edge,\n id: makeId(),\n source: remap(edge.source),\n target: remap(edge.target),\n selected: undefined,\n }))\n\n return { nodes: clonedNodes, edges: clonedEdges }\n}\n","import type { CSSProperties, ReactNode } from \"react\"\nimport { useRivetControls } from \"../context\"\n\nconst panelStyle: CSSProperties = {\n position: \"absolute\",\n bottom: 16,\n left: 16,\n display: \"flex\",\n flexDirection: \"column\",\n borderRadius: 8,\n overflow: \"hidden\",\n border: \"1px solid rgba(100, 116, 139, 0.4)\",\n background: \"#ffffff\",\n boxShadow: \"0 1px 3px rgba(15, 23, 42, 0.12)\",\n}\n\nconst buttonStyle: CSSProperties = {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: 32,\n height: 32,\n padding: 0,\n border: \"none\",\n borderBottom: \"1px solid rgba(100, 116, 139, 0.25)\",\n background: \"transparent\",\n color: \"#0f172a\",\n cursor: \"pointer\",\n}\n\nexport type ControlsProps = {\n /** Show the zoom-in / zoom-out buttons (default true). */\n showZoom?: boolean\n /** Show the fit-view button (default true). */\n showFitView?: boolean\n /** Extra buttons appended after the defaults. */\n children?: ReactNode\n className?: string\n style?: CSSProperties\n}\n\n/** A small zoom / fit-view button panel. Must be a child of `<Rivet>`. */\nexport function Controls({\n showZoom = true,\n showFitView = true,\n children,\n className,\n style,\n}: ControlsProps): React.ReactElement {\n const controls = useRivetControls()\n return (\n <div data-nopan className={className} style={{ ...panelStyle, ...style }}>\n {showZoom && (\n <>\n <button\n type=\"button\"\n style={buttonStyle}\n onClick={() => controls.zoomIn()}\n aria-label=\"Zoom in\"\n >\n <Icon title=\"Zoom in\" path=\"M12 5v14M5 12h14\" />\n </button>\n <button\n type=\"button\"\n style={buttonStyle}\n onClick={() => controls.zoomOut()}\n aria-label=\"Zoom out\"\n >\n <Icon title=\"Zoom out\" path=\"M5 12h14\" />\n </button>\n </>\n )}\n {showFitView && (\n <button\n type=\"button\"\n style={buttonStyle}\n onClick={() => controls.fitView()}\n aria-label=\"Fit view\"\n >\n <Icon title=\"Fit view\" path=\"M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5\" />\n </button>\n )}\n {children}\n </div>\n )\n}\n\nfunction Icon({ title, path }: { title: string; path: string }): React.ReactElement {\n return (\n <svg\n width={16}\n height={16}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n role=\"img\"\n >\n <title>{title}</title>\n <path d={path} />\n </svg>\n )\n}\n","type MaybeCrypto = { randomUUID?: () => string }\n\n/**\n * Generate a short, collision-resistant id. Prefers `crypto.randomUUID` when\n * available and falls back to a timestamp + random suffix.\n */\nexport function createId(prefix = \"\"): string {\n const cryptoObj = (globalThis as { crypto?: MaybeCrypto }).crypto\n const base = cryptoObj?.randomUUID\n ? cryptoObj.randomUUID()\n : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n return prefix ? `${prefix}-${base}` : base\n}\n","import type { NodeId, Size } from \"./types\"\n\n/** Assumed node size before the DOM node has mounted and reported its own. */\nexport const DEFAULT_NODE_SIZE: Size = { width: 160, height: 44 }\n\n/** Composite key for the handle/anchor registries. */\nexport function handleKey(nodeId: NodeId, handleId: string): string {\n return `${nodeId} ${handleId}`\n}\n\n/**\n * DOM markers the library and its consumers key interactions off. `data-nopan` is\n * the consumer-facing opt-out (stamp it on toolbars/inputs so a press there doesn't\n * start a node drag or pane pan); the rest are internal hit-test hooks.\n */\nexport const SELECTOR = {\n node: \"[data-rivet-node]\",\n handle: \"[data-rivet-handle]\",\n noPan: \"[data-nopan]\",\n /** Press here starts no node drag (but the node can still be selected/clicked). */\n noDrag: \"[data-nodrag]\",\n /** Press here never changes the selection. */\n noSelect: \"[data-noselect]\",\n swimlaneHandle: \"[data-rivet-swimlane-handle]\",\n /** The draggable box a marquee leaves over its selection (owns its own drag). */\n nodesSelection: \"[data-rivet-nodes-selection]\",\n /** Elements that own their own pointer — a pane pointerdown here starts no gesture. */\n paneGestureExempt:\n \"[data-rivet-node], [data-rivet-swimlane-handle], [data-nopan], [data-rivet-nodes-selection]\",\n} as const\n","/**\n * Edge alignment — the library-level policy for when an edge's endpoints\n * re-side to face the peer node.\n *\n * A handle chosen by the user (grabbed or dropped on) is *pinned*: rivet\n * renders the edge exactly there. The alignment policy decides when geometry\n * may override that pin. Under `\"on-move\"`, a committed position change of an\n * endpoint node re-sides both ends of its edges toward each other — the user\n * visibly changed the layout, so the pin yields. Nothing else triggers it:\n * data replaces (description edits, history restores) and dimension echoes\n * must never move an edge the user didn't touch or rewrite handles an undo\n * just faithfully restored.\n *\n * The store performs the move and the re-side in one internal batch, so\n * \"move + realign = one undo step\" holds by construction.\n */\n\nimport type { HandlePosition, Rect } from \"./types\"\n\n/**\n * When pinned edge endpoints re-side to face the peer node.\n *\n * - `\"manual\"` — never; a chosen handle is kept until the user reconnects.\n * - `\"on-move\"` — on a committed position change of an endpoint node.\n * - `\"live\"` — as `\"on-move\"`, plus: while an endpoint node is dragging, the\n * edge's pinned ends *render* as if auto — re-siding per frame to face each\n * other, with hysteresis — and the displayed sides commit on drop, inside\n * the move's history step. Nothing is persisted mid-gesture.\n */\nexport type EdgeAlignment = \"manual\" | \"on-move\" | \"live\"\n\n/** The side of `node` that faces `peer`, by dominant center-to-center axis. */\nexport function facingSide(node: Rect, peer: Rect): HandlePosition {\n const dx = peer.x + peer.width / 2 - (node.x + node.width / 2)\n const dy = peer.y + peer.height / 2 - (node.y + node.height / 2)\n if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? \"right\" : \"left\"\n return dy > 0 ? \"bottom\" : \"top\"\n}\n\n/**\n * How much the losing axis must dominate before a per-frame resolved side\n * switches axes: with a current horizontal side, the edge flips to top/bottom\n * only once `|dy| > |dx| * ratio` (and symmetrically). `1` disables the band.\n */\nexport const DEFAULT_ALIGNMENT_HYSTERESIS = 1.2\n\n/**\n * Per-frame side resolution with hysteresis. Without a `previous` side this is\n * exactly {@link facingSide}; with one, the side keeps its current axis until\n * the other axis dominates by `hysteresis`, so near-diagonal positions don't\n * flicker between sides frame to frame. Within the kept axis the sign always\n * tracks (a left↔right swap at a mostly-horizontal layout is a real crossing,\n * not jitter — jitter near the diagonal is an axis change, which the band\n * absorbs).\n */\nexport function resolveFacingSide(\n node: Rect,\n peer: Rect,\n previous?: HandlePosition,\n hysteresis: number = DEFAULT_ALIGNMENT_HYSTERESIS,\n): HandlePosition {\n if (!previous) return facingSide(node, peer)\n const dx = peer.x + peer.width / 2 - (node.x + node.width / 2)\n const dy = peer.y + peer.height / 2 - (node.y + node.height / 2)\n if (previous === \"left\" || previous === \"right\") {\n if (Math.abs(dy) > Math.abs(dx) * hysteresis) return dy > 0 ? \"bottom\" : \"top\"\n return dx > 0 ? \"right\" : \"left\"\n }\n if (Math.abs(dx) > Math.abs(dy) * hysteresis) return dx > 0 ? \"right\" : \"left\"\n return dy > 0 ? \"bottom\" : \"top\"\n}\n\n/** The side in `allowed` that most faces `peer`, or `null` for an empty set. */\nfunction bestAllowedSide(\n node: Rect,\n peer: Rect,\n allowed: readonly HandlePosition[],\n): HandlePosition | null {\n const dx = peer.x + peer.width / 2 - (node.x + node.width / 2)\n const dy = peer.y + peer.height / 2 - (node.y + node.height / 2)\n // Scoring by signed offset agrees with `facingSide` when all four sides are\n // allowed: its dominant-axis-and-sign choice is exactly the maximum here.\n const score: Record<HandlePosition, number> = { left: -dx, right: dx, top: -dy, bottom: dy }\n let best: HandlePosition | null = null\n for (const side of allowed) {\n if (best === null || score[side] > score[best]) best = side\n }\n return best\n}\n\n/**\n * {@link resolveFacingSide} restricted to the sides an end can actually reach.\n *\n * A node only offers connection points where its handles are. Letting an auto\n * or live-aligned end resolve freely puts the edge on a bare side — a\n * left/right node gets its edge stuck to the top midpoint, where the consumer\n * put nothing. Passing the sides that carry a compatible handle keeps the edge\n * on a real connection point.\n *\n * An empty `allowed` means \"unconstrained\" — a node with no registered handles\n * attaches at side midpoints, so every side is equally valid, and anchors place\n * themselves along whichever side faces the peer.\n *\n * When the freely-resolved side isn't reachable, a still-reachable `previous`\n * wins over re-picking: with the peer straight above a left/right node the raw\n * choice hangs on the sign of a near-zero `dx`, which would flicker frame to\n * frame.\n */\nexport function resolveFacingSideAmong(\n node: Rect,\n peer: Rect,\n allowed: readonly HandlePosition[],\n previous?: HandlePosition,\n hysteresis: number = DEFAULT_ALIGNMENT_HYSTERESIS,\n): HandlePosition {\n const resolved = resolveFacingSide(node, peer, previous, hysteresis)\n if (allowed.length === 0 || allowed.includes(resolved)) return resolved\n if (previous && allowed.includes(previous)) return previous\n return bestAllowedSide(node, peer, allowed) ?? resolved\n}\n","/**\n * Structured edge ends — the semantic model over the string handle ids that\n * `RivetEdge.sourceHandle`/`targetHandle` persist.\n *\n * An end is `{ nodeId, anchorId?, side? }`:\n * - `anchorId` present — the end binds to a registered {@link Anchor}.\n * - `side` present — the end is *pinned*: the user chose it (grabbed a dot,\n * dropped on a handle) and rivet renders it exactly there until the\n * alignment policy says otherwise.\n * - `side` absent — the end is *auto* (floating): the renderer resolves the\n * facing side per frame from the two node boxes. Nothing is written while a\n * node drags, so live re-anchoring is free and cannot touch history.\n *\n * Strings remain the wire format, so persisted graphs and external schemas\n * keep working; this module is the codec between the two forms:\n *\n * | structured | handle string |\n * |---------------------------------|----------------------|\n * | `{ anchorId, side }` | `inode-<id>-<side>` |\n * | `{ anchorId }` (auto) | `inode-<id>-auto` |\n * | `{ side }` (plain, pinned) | `\"<side>\"` |\n * | `{}` (plain, auto) | `undefined` |\n *\n * A custom handle id (anything else) stays a plain pinned end whose side lives\n * in the handle registry; `parseEdgeEndpoint` reads it from there when given\n * the registry, and otherwise leaves `side` unset.\n */\n\nimport {\n anchorAutoHandleId,\n anchorHandleId,\n parseAnchorAutoHandleId,\n parseAnchorHandleId,\n} from \"./anchor/registry\"\nimport { handleKey } from \"./constants\"\nimport type { EdgeEnd, EdgeId, HandlePosition, HandleRecord, NodeId } from \"./types\"\n\n/** One end of an edge, structurally. See the module doc for the string mapping. */\nexport type EdgeEndpoint = {\n nodeId: NodeId\n /** Anchor this end binds to; absent for a plain node end. */\n anchorId?: string\n /** Pinned side; absent = auto — the renderer resolves the facing side per frame. */\n side?: HandlePosition\n}\n\n/**\n * Key into the displayed-sides map (`EdgeDrawExtras.displayedSides`) for one\n * end of an edge — the hysteresis memory shared between the renderer, which\n * writes each frame's resolved side, and the store, whose `\"live\"` alignment\n * commit re-sides to exactly what was last displayed.\n */\nexport function displayedSideKey(edgeId: EdgeId, end: EdgeEnd): string {\n return `${edgeId}:${end}`\n}\n\nconst SIDES: readonly string[] = [\"left\", \"right\", \"top\", \"bottom\"]\n\n/** Parse a bare-side handle id (`\"left\"`, `\"top\"`, …) — a side-pinned plain end. */\nexport function parseSideHandleId(handleId: string | null | undefined): HandlePosition | null {\n return handleId && SIDES.includes(handleId) ? (handleId as HandlePosition) : null\n}\n\n/**\n * The handle string for a structured end — what `sourceHandle`/`targetHandle`\n * stores. `undefined` (a plain auto end) means \"no handle\": the renderer\n * resolves the side per frame. A plain pinned end that should attach to a\n * specific registered handle keeps using that handle's own id directly; this\n * codec covers the library-owned grammars.\n */\nexport function edgeEndpointHandle(end: EdgeEndpoint): string | undefined {\n if (end.anchorId !== undefined) {\n return end.side ? anchorHandleId(end.anchorId, end.side) : anchorAutoHandleId(end.anchorId)\n }\n return end.side\n}\n\n/**\n * Parse one end of an edge into the structured form. Library grammars (anchor\n * stray/auto ids, bare sides, absent handles) round-trip exactly; a custom\n * handle id resolves its side through `handles` when provided (the store's\n * registry), and otherwise comes back with `side` unset — which callers must\n * not read as auto without that context.\n */\nexport function parseEdgeEndpoint(\n nodeId: NodeId,\n handleId: string | null | undefined,\n handles?: ReadonlyMap<string, HandleRecord>,\n): EdgeEndpoint {\n if (!handleId) return { nodeId }\n const auto = parseAnchorAutoHandleId(handleId)\n if (auto) return { nodeId, anchorId: auto }\n const stray = parseAnchorHandleId(handleId)\n if (stray) return { nodeId, anchorId: stray.anchorId, side: stray.side }\n const registered = handles?.get(handleKey(nodeId, handleId))\n if (registered) return { nodeId, side: registered.position }\n const side = parseSideHandleId(handleId)\n return side ? { nodeId, side } : { nodeId }\n}\n","import type { NodeChange, NodeId, RivetNode } from \"./types\"\n\n/**\n * Geometry is the only thing a local gesture owns exclusively. A drag or resize\n * is its own confirm signal — while the pointer is down, this client's position\n * and size are authoritative and an incoming write to them is stale by\n * definition, because the peer that sent it was looking at a box this client has\n * already moved.\n *\n * Everything else about a held node (its data, selection, whether it still\n * exists) stays server-authoritative and lands normally: holding a node is not\n * the same as owning it.\n */\nexport type GeometryFields = Pick<RivetNode, \"position\" | \"width\" | \"height\" | \"size\">\n\n/** Copy `local`'s geometry onto `incoming`, leaving every other field alone. */\nexport function keepLocalGeometry<TData>(\n incoming: RivetNode<TData>,\n local: GeometryFields,\n): RivetNode<TData> {\n return {\n ...incoming,\n position: local.position,\n width: local.width,\n height: local.height,\n size: local.size,\n }\n}\n\n/**\n * Drop the parts of a remote batch that would fight a live local gesture.\n *\n * - `position` / `dimensions` for a held node are dropped outright.\n * - `replace` for a held node is rewritten to keep local geometry, so a peer's\n * rename still lands on a node this client is dragging.\n * - everything else passes through untouched.\n *\n * The result is what actually gets applied *and* what gets re-emitted — a\n * consumer must never be told about a change the document didn't take, or its\n * state and the store's diverge until the next full round-trip.\n */\nexport function guardNodeChanges<TData>(\n changes: NodeChange<TData>[],\n isHeld: (id: NodeId) => boolean,\n getLocal: (id: NodeId) => GeometryFields | undefined,\n): NodeChange<TData>[] {\n // The common case is no gesture in flight at all; don't rebuild the array.\n if (!changes.some((change) => change.type !== \"add\" && isHeld(change.id))) return changes\n\n const guarded: NodeChange<TData>[] = []\n for (const change of changes) {\n if (change.type === \"add\" || !isHeld(change.id)) {\n guarded.push(change)\n continue\n }\n if (change.type === \"position\" || change.type === \"dimensions\") continue\n if (change.type === \"replace\") {\n const local = getLocal(change.id)\n guarded.push(local ? { ...change, item: keepLocalGeometry(change.item, local) } : change)\n continue\n }\n guarded.push(change)\n }\n return guarded\n}\n","import type {\n NodeId,\n Rect,\n RivetEdge,\n RivetNode,\n RivetSnapshot,\n Size,\n Vec2,\n Viewport,\n} from \"./types\"\n\n/**\n * Confine a child's parent-relative position so its box stays fully inside the\n * parent (the `extent: \"parent\"` sub-flow constraint). Pure geometry — the\n * caller supplies both measured sizes.\n */\nexport function clampChildToParent(position: Vec2, childSize: Size, parentSize: Size): Vec2 {\n const maxX = Math.max(0, parentSize.width - childSize.width)\n const maxY = Math.max(0, parentSize.height - childSize.height)\n return {\n x: Math.min(maxX, Math.max(0, position.x)),\n y: Math.min(maxY, Math.max(0, position.y)),\n }\n}\n\n/** Snap a position to the nearest multiple of `[gx, gy]`. A `0` axis is left free. */\nexport function snapToGrid(position: Vec2, grid: readonly [number, number]): Vec2 {\n const [gx, gy] = grid\n return {\n x: gx > 0 ? Math.round(position.x / gx) * gx : position.x,\n y: gy > 0 ? Math.round(position.y / gy) * gy : position.y,\n }\n}\n\n/** The tight bounding rect over a set of rects, or `null` when empty. */\nexport function boundingRect(rects: readonly Rect[]): Rect | null {\n if (rects.length === 0) return null\n let minX = Number.POSITIVE_INFINITY\n let minY = Number.POSITIVE_INFINITY\n let maxX = Number.NEGATIVE_INFINITY\n let maxY = Number.NEGATIVE_INFINITY\n for (const r of rects) {\n minX = Math.min(minX, r.x)\n minY = Math.min(minY, r.y)\n maxX = Math.max(maxX, r.x + r.width)\n maxY = Math.max(maxY, r.y + r.height)\n }\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }\n}\n\n/**\n * Pure, reusable graph algorithms over a node map. These take the node collection\n * explicitly (no hidden state), so they're trivially testable and shared by the\n * store without duplicating parent-chain / subtree walks.\n */\n\n/** Longest parent chain any walk will follow — a guard against accidental cycles. */\nexport const MAX_PARENT_DEPTH = 50\n\ntype Nodes = ReadonlyMap<NodeId, RivetNode>\n\n/** Absolute world position of a node, summing its parent chain's positions. */\nexport function worldPosition(nodes: Nodes, id: NodeId, maxDepth = MAX_PARENT_DEPTH): Vec2 {\n const node = nodes.get(id)\n if (!node) return { x: 0, y: 0 }\n let x = node.position.x\n let y = node.position.y\n let parentId = node.parentId\n let guard = 0\n while (parentId && guard++ < maxDepth) {\n const parent = nodes.get(parentId)\n if (!parent) break\n x += parent.position.x\n y += parent.position.y\n parentId = parent.parentId\n }\n return { x, y }\n}\n\n/** How many ancestors a node has (0 for a top-level node). */\nexport function nodeDepth(nodes: Nodes, id: NodeId, maxDepth = MAX_PARENT_DEPTH): number {\n let depth = 0\n let parentId = nodes.get(id)?.parentId\n while (parentId && depth < maxDepth) {\n depth++\n parentId = nodes.get(parentId)?.parentId\n }\n return depth\n}\n\n/** True if any ancestor of `id` is in `set`. */\nexport function hasAncestorIn(\n nodes: Nodes,\n id: NodeId,\n set: ReadonlySet<NodeId>,\n maxDepth = MAX_PARENT_DEPTH,\n): boolean {\n let parentId = nodes.get(id)?.parentId\n let guard = 0\n while (parentId && guard++ < maxDepth) {\n if (set.has(parentId)) return true\n parentId = nodes.get(parentId)?.parentId\n }\n return false\n}\n\n/** Parent id → its direct children, computed in one pass over all nodes. */\nexport function buildChildIndex(nodes: Nodes): Map<NodeId, NodeId[]> {\n const childrenOf = new Map<NodeId, NodeId[]>()\n for (const node of nodes.values()) {\n if (!node.parentId) continue\n const list = childrenOf.get(node.parentId)\n if (list) list.push(node.id)\n else childrenOf.set(node.parentId, [node.id])\n }\n return childrenOf\n}\n\n/** Append every descendant of `id` (children, grandchildren, …) to `out`. */\nexport function collectDescendants(\n id: NodeId,\n childIndex: ReadonlyMap<NodeId, NodeId[]>,\n out: NodeId[],\n): void {\n for (const child of childIndex.get(id) ?? []) {\n out.push(child)\n collectDescendants(child, childIndex, out)\n }\n}\n\n/** Every descendant of `id`, building the child index internally. */\nexport function descendantIds(nodes: Nodes, id: NodeId): NodeId[] {\n const out: NodeId[] = []\n collectDescendants(id, buildChildIndex(nodes), out)\n return out\n}\n\n/**\n * True when nothing the consumer controls has changed between two versions of a\n * node — so reconcile can keep the existing one (preserving store-owned transient\n * state like `hovered`). Compares only fields a controlled consumer owns.\n */\n/**\n * A serializable snapshot of the graph. Store-owned geometry (`position`, `size`)\n * is cloned so mutating the snapshot can't reach back into the store, and purely\n * transient node flags (`hovered`, `dragging`) are dropped — you never want to\n * persist \"was mid-drag\". `data` is copied by reference, matching the\n * controlled-mode contract (the consumer owns it).\n */\nexport function serializeGraph<TNodeData = unknown, TEdgeData = unknown>(\n nodes: Iterable<RivetNode<TNodeData>>,\n edges: Iterable<RivetEdge<TEdgeData>>,\n viewport: Viewport,\n): RivetSnapshot<TNodeData, TEdgeData> {\n const cleanNodes: RivetNode<TNodeData>[] = []\n for (const node of nodes) {\n const copy = { ...node, position: { ...node.position } }\n if (node.size) copy.size = { ...node.size }\n copy.hovered = undefined\n copy.dragging = undefined\n cleanNodes.push(copy)\n }\n return {\n nodes: cleanNodes,\n edges: [...edges].map((edge) => ({ ...edge })),\n viewport: { ...viewport },\n }\n}\n\nexport function nodeControlledEqual(a: RivetNode, b: RivetNode): boolean {\n return (\n a.position.x === b.position.x &&\n a.position.y === b.position.y &&\n Boolean(a.selected) === Boolean(b.selected) &&\n a.data === b.data &&\n a.type === b.type &&\n a.laneId === b.laneId &&\n a.ariaLabel === b.ariaLabel &&\n a.parentId === b.parentId &&\n a.extent === b.extent &&\n a.width === b.width &&\n a.height === b.height &&\n Boolean(a.dragging) === Boolean(b.dragging) &&\n a.size?.width === b.size?.width &&\n a.size?.height === b.size?.height\n )\n}\n","import type { EdgeChange, NodeChange, RivetEdge, RivetNode } from \"./types\"\n\n/** A structural snapshot of the graph (no selection/hover/drag state). */\nexport type HistorySnapshot = {\n nodes: RivetNode[]\n edges: RivetEdge[]\n}\n\n/**\n * True when a change batch alters graph structure and should create an undo\n * step. Selection is excluded (undo shouldn't churn selection); live drag/resize\n * frames are excluded so a whole gesture coalesces into a single committed step.\n */\nexport function hasRecordableChange(changes: ReadonlyArray<NodeChange | EdgeChange>): boolean {\n return changes.some((change) => {\n switch (change.type) {\n case \"add\":\n case \"remove\":\n case \"replace\":\n return true\n case \"position\":\n return !change.dragging\n case \"dimensions\":\n return !change.resizing\n default:\n return false // selection\n }\n })\n}\n\n/**\n * A bounded undo/redo stack over graph snapshots. Backend-agnostic: it takes a\n * `snapshot()` reader and, per undo/redo, an `apply()` writer — so it can be\n * unit-tested without a store, and the store stays the single source of truth.\n *\n * Coalescing: {@link record} schedules a single step per microtask, so all the\n * synchronous mutations of one user action (e.g. deleting a node and its edges,\n * which emit separately) collapse into one undo step. `snapshot()` is read at the\n * end of that microtask, capturing the fully-applied result; the *previous*\n * snapshot becomes the step's \"before\".\n */\nexport class HistoryManager {\n private undoStack: HistorySnapshot[] = []\n private redoStack: HistorySnapshot[] = []\n private last: HistorySnapshot\n private scheduled = false\n private rebaseScheduled = false\n private readonly listeners = new Set<() => void>()\n\n constructor(\n private readonly snapshot: () => HistorySnapshot,\n private readonly limit = 100,\n // Wrap rather than pass `queueMicrotask` directly: as a bare default it would\n // be invoked as `this.schedule(cb)` — a method call that binds `this` to the\n // manager, which browsers reject with \"Illegal invocation\". Calling it inside\n // an arrow keeps it a free-function call.\n private readonly schedule: (cb: () => void) => void = (cb) => queueMicrotask(cb),\n ) {\n this.last = snapshot()\n }\n\n /** Note that a recordable batch was applied; flushes one step next microtask. */\n record(recordable: boolean): void {\n if (!recordable || this.scheduled) return\n this.scheduled = true\n this.schedule(() => {\n if (this.scheduled) this.flush()\n })\n }\n\n /**\n * The graph changed *without* recording a step — a controlled reconcile\n * applying incoming props, or a measurement echo. Refresh the rolling\n * baseline so the next recorded step diffs against reality; a stale baseline\n * makes undo revert the unrecorded changes too (e.g. a prop-added node that\n * was then deleted through the store would undo to a graph without it).\n * Coalesced per microtask like {@link record}. When a step is pending, its\n * flush refreshes the baseline anyway, so this defers to it — with the\n * documented limit that unrecorded and recorded mutations landing in the\n * same microtask fold into that one step.\n */\n rebase(): void {\n if (this.scheduled || this.rebaseScheduled) return\n this.rebaseScheduled = true\n this.schedule(() => {\n this.rebaseScheduled = false\n if (this.scheduled) return\n this.last = this.snapshot()\n })\n }\n\n /**\n * Fold an external change into every stored snapshot.\n *\n * Snapshots are structural, so a restore rewrites the whole graph — which in a\n * shared document means undoing past a peer's edit would silently erase it.\n * {@link rebase} can't help: it only refreshes the rolling baseline, while the\n * stale states are the ones already on the stacks. Replaying the incoming\n * change over each of them keeps every stored step consistent with work this\n * client doesn't own.\n *\n * The trade-off is that an undo touching a node a peer has since changed no\n * longer moves it — the peer's newer value survives instead. That's the\n * intended precedence: a local undo may drop its own effect, never someone\n * else's edit.\n */\n rewrite(transform: (snapshot: HistorySnapshot) => HistorySnapshot): void {\n this.undoStack = this.undoStack.map(transform)\n this.redoStack = this.redoStack.map(transform)\n // A step scheduled but not yet flushed will push `last` as its \"before\", so\n // it needs the same treatment; when nothing is pending, the rebase that\n // follows re-reads it from the live graph and lands on the same state.\n this.last = transform(this.last)\n }\n\n private flush(): void {\n this.scheduled = false\n this.undoStack.push(this.last)\n if (this.undoStack.length > this.limit) this.undoStack.shift()\n this.redoStack = []\n this.last = this.snapshot()\n this.notify()\n }\n\n undo(apply: (snapshot: HistorySnapshot) => void): boolean {\n if (this.scheduled) this.flush() // finalize a pending step first\n const prev = this.undoStack.pop()\n if (!prev) return false\n this.redoStack.push(this.snapshot())\n apply(prev)\n this.last = prev\n this.notify()\n return true\n }\n\n redo(apply: (snapshot: HistorySnapshot) => void): boolean {\n const next = this.redoStack.pop()\n if (!next) return false\n this.undoStack.push(this.last)\n apply(next)\n this.last = next\n this.notify()\n return true\n }\n\n canUndo(): boolean {\n return this.undoStack.length > 0 || this.scheduled\n }\n\n canRedo(): boolean {\n return this.redoStack.length > 0\n }\n\n /** Drop all history and reset the baseline to the current graph. */\n clear(): void {\n this.scheduled = false\n this.rebaseScheduled = false\n this.undoStack = []\n this.redoStack = []\n this.last = this.snapshot()\n this.notify()\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n private notify(): void {\n for (const listener of this.listeners) listener()\n }\n}\n","import { clamp } from \"@rivet/utils\"\nimport type { Rect, Vec2, Viewport } from \"./types\"\n\n/** Convert a world-space point to screen-space pixels. */\nexport function worldToScreen(point: Vec2, viewport: Viewport): Vec2 {\n return {\n x: point.x * viewport.zoom + viewport.x,\n y: point.y * viewport.zoom + viewport.y,\n }\n}\n\n/** Convert a screen-space point (e.g. a pointer event) to world space. */\nexport function screenToWorld(point: Vec2, viewport: Viewport): Vec2 {\n return {\n x: (point.x - viewport.x) / viewport.zoom,\n y: (point.y - viewport.y) / viewport.zoom,\n }\n}\n\n/**\n * Zoom toward an anchor point (usually the cursor) so the world point under the\n * anchor stays put. Returns a new viewport; the input is not mutated.\n */\nexport function zoomAt(\n viewport: Viewport,\n anchor: Vec2,\n nextZoom: number,\n minZoom = 0.1,\n maxZoom = 4,\n): Viewport {\n const zoom = clamp(nextZoom, minZoom, maxZoom)\n const world = screenToWorld(anchor, viewport)\n return {\n zoom,\n x: anchor.x - world.x * zoom,\n y: anchor.y - world.y * zoom,\n }\n}\n\n/** The CSS transform string applied to the DOM node layer. */\nexport function viewportToCss(viewport: Viewport): string {\n return `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`\n}\n\n/** The visible world-space rectangle for a viewport of the given pixel size. */\nexport function visibleWorldRect(viewport: Viewport, width: number, height: number): Rect {\n const topLeft = screenToWorld({ x: 0, y: 0 }, viewport)\n const bottomRight = screenToWorld({ x: width, y: height }, viewport)\n return {\n x: topLeft.x,\n y: topLeft.y,\n width: bottomRight.x - topLeft.x,\n height: bottomRight.y - topLeft.y,\n }\n}\n\n/** True if two axis-aligned rectangles overlap (used for node culling). */\nexport function rectsIntersect(a: Rect, b: Rect): boolean {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y\n}\n","import type { EdgePath, EdgePathFn, EdgePathParams, HandlePosition, Vec2 } from \"../types\"\n\n/** Outward unit direction an edge leaves a handle, by the handle's side. */\nconst SIDE_DIR: Record<HandlePosition, Vec2> = {\n left: { x: -1, y: 0 },\n right: { x: 1, y: 0 },\n top: { x: 0, y: -1 },\n bottom: { x: 0, y: 1 },\n}\n\n/**\n * Bezier sampling is adaptive: roughly one segment per {@link BEZIER_SEGMENT_PX}\n * of curve, clamped to [{@link BEZIER_MIN_SAMPLES}, {@link BEZIER_MAX_SAMPLES}].\n * A fixed count faceted long curves (few big chords) and over-sampled short ones.\n * Paths are built in screen space, so this tracks the on-screen size at any zoom.\n */\nconst BEZIER_SEGMENT_PX = 8\nconst BEZIER_MIN_SAMPLES = 16\nconst BEZIER_MAX_SAMPLES = 160\nconst CORNER_RADIUS = 8\nconst ARC_SAMPLES = 6\n\nfunction cubicAt(a: number, b: number, c: number, d: number, t: number): number {\n const mt = 1 - t\n return mt * mt * mt * a + 3 * mt * mt * t * b + 3 * mt * t * t * c + t * t * t * d\n}\n\nfunction quadAt(a: number, b: number, c: number, t: number): number {\n const mt = 1 - t\n return mt * mt * a + 2 * mt * t * b + t * t * c\n}\n\n/** A straight line between the two ends. */\nexport const getStraightPath: EdgePathFn = ({ sourceX, sourceY, targetX, targetY }): EdgePath => ({\n points: [\n { x: sourceX, y: sourceY },\n { x: targetX, y: targetY },\n ],\n labelX: (sourceX + targetX) / 2,\n labelY: (sourceY + targetY) / 2,\n})\n\n/**\n * A cubic bezier that leaves each end perpendicular to its handle's side, so\n * edges curve cleanly out of left/right/top/bottom handles. This is the default.\n */\nexport const getBezierPath: EdgePathFn = (params): EdgePath => {\n const { sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = params\n const sDir = SIDE_DIR[sourcePosition]\n const tDir = SIDE_DIR[targetPosition]\n const dist = Math.hypot(targetX - sourceX, targetY - sourceY)\n const reach = Math.max(40, dist * 0.4)\n const p0 = { x: sourceX, y: sourceY }\n const p1 = { x: sourceX + sDir.x * reach, y: sourceY + sDir.y * reach }\n const p2 = { x: targetX + tDir.x * reach, y: targetY + tDir.y * reach }\n const p3 = { x: targetX, y: targetY }\n\n // Sample proportionally to the control polygon's length (an upper bound on the\n // arc length), so a long, curvy edge gets enough segments to read as smooth.\n const ctrlLen =\n Math.hypot(p1.x - p0.x, p1.y - p0.y) +\n Math.hypot(p2.x - p1.x, p2.y - p1.y) +\n Math.hypot(p3.x - p2.x, p3.y - p2.y)\n const samples = Math.max(\n BEZIER_MIN_SAMPLES,\n Math.min(BEZIER_MAX_SAMPLES, Math.ceil(ctrlLen / BEZIER_SEGMENT_PX)),\n )\n\n const points: Vec2[] = []\n for (let i = 0; i <= samples; i++) {\n const t = i / samples\n points.push({\n x: cubicAt(p0.x, p1.x, p2.x, p3.x, t),\n y: cubicAt(p0.y, p1.y, p2.y, p3.y, t),\n })\n }\n return {\n points,\n labelX: cubicAt(p0.x, p1.x, p2.x, p3.x, 0.5),\n labelY: cubicAt(p0.y, p1.y, p2.y, p3.y, 0.5),\n }\n}\n\n/** Minimum run an edge travels straight out of a handle before its first turn. */\nconst STEP_OFFSET = 20\n\n/** Drop consecutive duplicates and interior points collinear with their neighbors. */\nfunction simplifyCorners(corners: Vec2[]): Vec2[] {\n const out: Vec2[] = []\n for (const p of corners) {\n const a = out[out.length - 2]\n const b = out[out.length - 1]\n if (b && b.x === p.x && b.y === p.y) continue\n if (a && b && ((a.x === b.x && b.x === p.x) || (a.y === b.y && b.y === p.y))) out.pop()\n out.push(p)\n }\n return out\n}\n\n/**\n * Orthogonal waypoints (endpoints included) for an axis-aligned step path.\n * Direction-aware: the path leaves each handle along its outward side for at\n * least {@link STEP_OFFSET} before turning, so a route never doubles back\n * through the node it just left.\n */\nfunction stepCorners(params: EdgePathParams): Vec2[] {\n const { sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = params\n const s = { x: sourceX, y: sourceY }\n const t = { x: targetX, y: targetY }\n const sDir = SIDE_DIR[sourcePosition]\n const tDir = SIDE_DIR[targetPosition]\n // Where each end sits after its mandatory straight run out of the handle.\n const sg = { x: sourceX + sDir.x * STEP_OFFSET, y: sourceY + sDir.y * STEP_OFFSET }\n const tg = { x: targetX + tDir.x * STEP_OFFSET, y: targetY + tDir.y * STEP_OFFSET }\n return simplifyCorners(routeCorners(s, t, sg, tg, sDir, tDir))\n}\n\n/** Pick the orthogonal route between the two gapped ends, by handle-direction case. */\nfunction routeCorners(s: Vec2, t: Vec2, sg: Vec2, tg: Vec2, sDir: Vec2, tDir: Vec2): Vec2[] {\n const sHoriz = sDir.x !== 0\n const tHoriz = tDir.x !== 0\n\n if (sHoriz && tHoriz) {\n if (sDir.x * tDir.x < 0) {\n // Facing pair (e.g. right → left): split at the mid-line when the target\n // is far enough ahead; otherwise route around through a horizontal mid-lane.\n if ((t.x - s.x) * sDir.x >= 2 * STEP_OFFSET) {\n const midX = (s.x + t.x) / 2\n return [s, { x: midX, y: s.y }, { x: midX, y: t.y }, t]\n }\n const midY = (s.y + t.y) / 2\n return [s, sg, { x: sg.x, y: midY }, { x: tg.x, y: midY }, tg, t]\n }\n // Same side (e.g. right → right): share the outermost vertical rail.\n const railX = sDir.x > 0 ? Math.max(sg.x, tg.x) : Math.min(sg.x, tg.x)\n return [s, { x: railX, y: s.y }, { x: railX, y: t.y }, t]\n }\n\n if (!sHoriz && !tHoriz) {\n if (sDir.y * tDir.y < 0) {\n if ((t.y - s.y) * sDir.y >= 2 * STEP_OFFSET) {\n const midY = (s.y + t.y) / 2\n return [s, { x: s.x, y: midY }, { x: t.x, y: midY }, t]\n }\n const midX = (s.x + t.x) / 2\n return [s, sg, { x: midX, y: sg.y }, { x: midX, y: tg.y }, tg, t]\n }\n const railY = sDir.y > 0 ? Math.max(sg.y, tg.y) : Math.min(sg.y, tg.y)\n return [s, { x: s.x, y: railY }, { x: t.x, y: railY }, t]\n }\n\n // Perpendicular pair: a single L-bend when it exits both handles outward;\n // otherwise a Z through the gapped ends.\n const corner = sHoriz ? { x: t.x, y: s.y } : { x: s.x, y: t.y }\n const exitsSource = sHoriz\n ? (corner.x - s.x) * sDir.x >= STEP_OFFSET\n : (corner.y - s.y) * sDir.y >= STEP_OFFSET\n const exitsTarget = tHoriz\n ? (corner.x - t.x) * tDir.x >= STEP_OFFSET\n : (corner.y - t.y) * tDir.y >= STEP_OFFSET\n if (exitsSource && exitsTarget) return [s, corner, t]\n const bend = sHoriz ? { x: sg.x, y: tg.y } : { x: tg.x, y: sg.y }\n return [s, sg, bend, tg, t]\n}\n\n/** Round the interior corners of a waypoint list into a sampled polyline. */\nfunction roundCorners(corners: Vec2[], radius: number): Vec2[] {\n if (corners.length <= 2) return corners\n const points: Vec2[] = []\n const first = corners[0]\n if (first) points.push(first)\n\n for (let i = 1; i < corners.length - 1; i++) {\n const prev = corners[i - 1]\n const curr = corners[i]\n const next = corners[i + 1]\n if (!prev || !curr || !next) continue\n\n const inLen = Math.hypot(curr.x - prev.x, curr.y - prev.y)\n const outLen = Math.hypot(next.x - curr.x, next.y - curr.y)\n const r = Math.min(radius, inLen / 2, outLen / 2)\n const inPt = {\n x: curr.x + ((prev.x - curr.x) / (inLen || 1)) * r,\n y: curr.y + ((prev.y - curr.y) / (inLen || 1)) * r,\n }\n const outPt = {\n x: curr.x + ((next.x - curr.x) / (outLen || 1)) * r,\n y: curr.y + ((next.y - curr.y) / (outLen || 1)) * r,\n }\n points.push(inPt)\n for (let j = 1; j < ARC_SAMPLES; j++) {\n const tt = j / ARC_SAMPLES\n points.push({\n x: quadAt(inPt.x, curr.x, outPt.x, tt),\n y: quadAt(inPt.y, curr.y, outPt.y, tt),\n })\n }\n points.push(outPt)\n }\n\n const last = corners[corners.length - 1]\n if (last) points.push(last)\n return points\n}\n\n/** Label anchor: the midpoint of the path's middle segment. */\nfunction stepLabel(corners: Vec2[], params: EdgePathParams): Vec2 {\n const i = Math.floor((corners.length - 1) / 2)\n const a = corners[i]\n const b = corners[i + 1]\n if (!a || !b) return { x: params.sourceX, y: params.sourceY }\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }\n}\n\n/** An axis-aligned step path with rounded corners. */\nexport const getSmoothStepPath: EdgePathFn = (params): EdgePath => {\n const corners = stepCorners(params)\n const label = stepLabel(corners, params)\n return { points: roundCorners(corners, CORNER_RADIUS), labelX: label.x, labelY: label.y }\n}\n\n/** An axis-aligned step path with sharp corners. */\nexport const getStepPath: EdgePathFn = (params): EdgePath => {\n const corners = stepCorners(params)\n const label = stepLabel(corners, params)\n return { points: corners, labelX: label.x, labelY: label.y }\n}\n\n/** The built-in edge shapes, keyed by `type`. `bezier` is the default. */\nexport const BUILTIN_EDGE_TYPES: Record<string, EdgePathFn> = {\n bezier: getBezierPath,\n smoothstep: getSmoothStepPath,\n step: getStepPath,\n straight: getStraightPath,\n}\n","import { parseAnchorAutoHandleId, parseAnchorHandleId } from \"../anchor/registry\"\nimport { DEFAULT_NODE_SIZE, handleKey } from \"../constants\"\nimport { resolveFacingSideAmong } from \"../edge-alignment\"\nimport { displayedSideKey, parseSideHandleId } from \"../edge-ends\"\nimport type {\n DefaultEdgeOptions,\n EdgeDrawExtras,\n EdgeEnd,\n EdgeId,\n EdgeMarker,\n EdgePathParams,\n EdgeStyle,\n EdgeTypes,\n HandlePosition,\n HandleRecord,\n HandleType,\n NodeId,\n Rect,\n RivetEdge,\n RivetNode,\n Vec2,\n Viewport,\n} from \"../types\"\nimport { worldToScreen } from \"../viewport\"\nimport { getBezierPath } from \"./edge-paths\"\n\n/** Semantic edge colors, shared by every backend. */\nexport const EDGE_COLOR = \"rgba(100, 116, 139, 0.75)\"\nexport const EDGE_COLOR_SELECTED = \"#6366f1\"\nexport const EDGE_COLOR_HOVERED = \"rgba(99, 102, 241, 0.9)\"\nexport const EDGE_WIDTH = 1.5\nexport const EDGE_WIDTH_HOVERED = 2.5\nexport const PENDING_COLOR = \"#6366f1\"\n\n/** The opposite side, used to face the pending connection's loose end. */\nexport const OPPOSITE: Record<HandlePosition, HandlePosition> = {\n left: \"right\",\n right: \"left\",\n top: \"bottom\",\n bottom: \"top\",\n}\n\n/** One edge resolved to screen-space geometry plus its final visual style. */\nexport type ResolvedEdge = {\n id: EdgeId\n /** Screen-space polyline (>= 2 points). */\n points: Vec2[]\n /** Screen-space endpoints (for endpoint picking / reconnection). */\n source: Vec2\n target: Vec2\n /** Screen-space label anchor, when the edge has a label. */\n label?: Vec2\n /** Resolved stroke color (CSS string). */\n stroke: string\n width: number\n opacity: number\n animated: boolean\n /** Explicit dash pattern (ignored when `animated`). */\n dash?: number[]\n markerStart: Exclude<EdgeMarker, false> | null\n markerEnd: Exclude<EdgeMarker, false> | null\n}\n\n/** One end of an edge in screen space, plus the side it exits. */\ntype Anchor = { point: Vec2; position: HandlePosition }\n\n/** Collapse a marker to its drawable value, treating `false` as \"no marker\". */\nconst falseToNull = (m: EdgeMarker | undefined): Exclude<EdgeMarker, false> | null => m || null\n\n/**\n * Resolve every edge to backend-neutral screen-space geometry + style — the\n * form any {@link EdgeRenderer} backend consumes. Skips the edge currently\n * being reconnected and any edge whose endpoints are missing or degenerate.\n */\nexport function buildEdges(\n edges: RivetEdge[],\n nodes: Map<NodeId, RivetNode>,\n viewport: Viewport,\n edgeTypes: EdgeTypes,\n defaults: DefaultEdgeOptions,\n extras?: EdgeDrawExtras,\n): ResolvedEdge[] {\n const handles = extras?.handles\n const hovered = extras?.hovered\n const reconnecting = extras?.reconnecting\n const worldPositions = extras?.worldPositions\n const resolved: ResolvedEdge[] = []\n\n for (const edge of edges) {\n if (edge.id === reconnecting) continue\n const source = nodes.get(edge.source)\n const target = nodes.get(edge.target)\n if (!source || !target) continue\n\n const frame: EndFrame = { handles, viewport, worldPositions, extras }\n const start = resolveEnd(edge, \"source\", source, target, frame)\n const end = resolveEnd(edge, \"target\", target, source, frame)\n const params: EdgePathParams = {\n sourceX: start.point.x,\n sourceY: start.point.y,\n targetX: end.point.x,\n targetY: end.point.y,\n sourcePosition: start.position,\n targetPosition: end.position,\n }\n const pathFn = edgeTypes[edge.type ?? defaults.type ?? \"bezier\"] ?? getBezierPath\n const path = pathFn(params)\n if (path.points.length < 2) continue\n\n const style: EdgeStyle = { ...defaults.style, ...edge.style }\n const isHovered = edge.id === hovered\n resolved.push({\n id: edge.id,\n points: path.points,\n source: start.point,\n target: end.point,\n label: edge.label !== undefined ? { x: path.labelX, y: path.labelY } : undefined,\n stroke: edge.selected\n ? EDGE_COLOR_SELECTED\n : isHovered\n ? EDGE_COLOR_HOVERED\n : (style.stroke ?? EDGE_COLOR),\n width: style.strokeWidth ?? (isHovered ? EDGE_WIDTH_HOVERED : EDGE_WIDTH),\n opacity: style.opacity ?? 1,\n animated: edge.animated ?? defaults.animated ?? false,\n dash: style.strokeDasharray,\n markerStart: falseToNull(edge.markerStart ?? defaults.markerStart),\n markerEnd: falseToNull(edge.markerEnd ?? defaults.markerEnd),\n })\n }\n return resolved\n}\n\n/** Screen-space bezier polyline for the in-progress (pending) connection. */\nexport function buildPendingPath(\n pending: NonNullable<EdgeDrawExtras[\"pending\"]>,\n handles: Map<string, HandleRecord> | undefined,\n viewport: Viewport,\n): Vec2[] {\n const record = handles?.get(handleKey(pending.source, pending.sourceHandle))\n const sourcePosition: HandlePosition =\n record?.position ?? (pending.sourceType === \"target\" ? \"left\" : \"right\")\n const from = worldToScreen(pending.from, viewport)\n const to = worldToScreen(pending.to, viewport)\n // Snapped onto a target handle: enter from that handle's side so the preview\n // matches the committed edge. Otherwise face back toward the source.\n const targetPosition = pending.toPosition ?? OPPOSITE[sourcePosition]\n return getBezierPath({\n sourceX: from.x,\n sourceY: from.y,\n targetX: to.x,\n targetY: to.y,\n sourcePosition,\n targetPosition,\n }).points\n}\n\n/**\n * World point where an edge end meets `side` of a node box, `alongPct` percent\n * along that side (top→bottom for left/right, left→right for top/bottom).\n */\nexport function pointOnSide(rect: Rect, side: HandlePosition, alongPct = 50): Vec2 {\n const t = alongPct / 100\n switch (side) {\n case \"left\":\n return { x: rect.x, y: rect.y + rect.height * t }\n case \"right\":\n return { x: rect.x + rect.width, y: rect.y + rect.height * t }\n case \"top\":\n return { x: rect.x + rect.width * t, y: rect.y }\n case \"bottom\":\n return { x: rect.x + rect.width * t, y: rect.y + rect.height }\n }\n}\n\n/** The node's world-space box: parent-chain origin + measured/default size. */\nfunction nodeRect(node: RivetNode, worldPositions?: ReadonlyMap<NodeId, Vec2>): Rect {\n const origin = worldPositions?.get(node.id) ?? node.position\n const size = node.size ?? DEFAULT_NODE_SIZE\n return { x: origin.x, y: origin.y, width: size.width, height: size.height }\n}\n\n/** Handle types an edge end can attach to, mirroring the connection rules. */\nconst WANTED_TYPES: Record<EdgeEnd, readonly HandleType[]> = {\n source: [\"source\", \"either\"],\n target: [\"target\", \"either\"],\n}\n\n/** A registered handle on `side` of the node that `role` can use, or null. */\nfunction handleOnSide(\n nodeId: NodeId,\n side: HandlePosition,\n role: EdgeEnd,\n handles: Map<string, HandleRecord> | undefined,\n): HandleRecord | null {\n if (!handles) return null\n for (const record of handles.values()) {\n if (\n record.nodeId === nodeId &&\n record.position === side &&\n WANTED_TYPES[role].includes(record.type)\n ) {\n return record\n }\n }\n return null\n}\n\n/**\n * The distinct sides of `nodeId` carrying a handle `role` can use. Empty when\n * the node has no compatible handle at all — an unhandled node attaches at side\n * midpoints, so no side is preferable to another.\n */\nexport function reachableSides(\n nodeId: NodeId,\n role: EdgeEnd,\n handles: Map<string, HandleRecord> | undefined,\n): HandlePosition[] {\n if (!handles) return []\n const sides: HandlePosition[] = []\n for (const record of handles.values()) {\n if (record.nodeId !== nodeId) continue\n if (!WANTED_TYPES[role].includes(record.type)) continue\n if (!sides.includes(record.position)) sides.push(record.position)\n }\n return sides\n}\n\n/** Per-frame inputs shared by every end resolution in one {@link buildEdges} call. */\ntype EndFrame = {\n handles: Map<string, HandleRecord> | undefined\n viewport: Viewport\n worldPositions: ReadonlyMap<NodeId, Vec2> | undefined\n extras: EdgeDrawExtras | undefined\n}\n\n/**\n * Screen-space anchor for one end of an edge and the side it exits.\n *\n * A *pinned* end (a registered handle, an anchor stray id, a bare-side id)\n * renders exactly where it points. An *auto* end — no handle, an\n * `inode-<id>-auto` anchor end, or any end of an edge touching a node in\n * `liveAlignNodes` — resolves the side facing the peer per frame, stabilized\n * by the hysteresis memory in `displayedSides`, and places the point on that\n * side: at the anchor's measured row/column (via `anchorPlacement`), at a\n * compatible registered handle, or at the side's midpoint.\n */\nfunction resolveEnd(\n edge: RivetEdge,\n role: EdgeEnd,\n node: RivetNode,\n peer: RivetNode,\n frame: EndFrame,\n): Anchor {\n const { handles, viewport, worldPositions, extras } = frame\n const handleId = role === \"source\" ? edge.sourceHandle : edge.targetHandle\n const rect = nodeRect(node, worldPositions)\n const anchorId =\n parseAnchorAutoHandleId(handleId) ?? parseAnchorHandleId(handleId)?.anchorId ?? null\n\n /** Point `alongPct` percent along `side`, or at a compatible handle / midpoint. */\n const endAt = (side: HandlePosition): Anchor => {\n const alongPct =\n (anchorId ? extras?.anchorPlacement?.(node.id, anchorId, side) : null) ?? undefined\n if (alongPct === undefined && !anchorId) {\n const candidate = handleOnSide(node.id, side, role, handles)\n if (candidate) {\n return {\n point: worldToScreen(\n { x: rect.x + candidate.offset.x, y: rect.y + candidate.offset.y },\n viewport,\n ),\n position: side,\n }\n }\n }\n return { point: worldToScreen(pointOnSide(rect, side, alongPct), viewport), position: side }\n }\n\n // Pinned side, if any: an anchor stray's encoded side, a registered handle's\n // side, or a bare-side id. Ends with none (including custom ids whose handle\n // is unregistered — e.g. a culled peer) resolve as auto.\n const registered = handleId && handles ? handles.get(handleKey(node.id, handleId)) : undefined\n const pinnedSide =\n parseAnchorHandleId(handleId)?.side ?? registered?.position ?? parseSideHandleId(handleId)\n\n const live =\n extras?.liveAlignNodes !== undefined &&\n (extras.liveAlignNodes.has(edge.source) || extras.liveAlignNodes.has(edge.target)) &&\n edge.source !== edge.target\n\n if (pinnedSide && !live) {\n if (registered) {\n return {\n point: worldToScreen(\n { x: rect.x + registered.offset.x, y: rect.y + registered.offset.y },\n viewport,\n ),\n position: registered.position,\n }\n }\n // Unregistered but side-known: an anchor stray whose chrome isn't mounted\n // (culled node) places from measured geometry; a bare side uses a\n // compatible registered handle there, else the side midpoint.\n return endAt(pinnedSide)\n }\n\n // Auto: face the peer, with hysteresis against last frame's displayed side,\n // and constrained to the sides that actually carry a compatible handle — a\n // node with handles only on its left and right must not have its edge drift\n // onto the top or bottom midpoint. Anchors opt out: their strays are placed\n // along whichever side faces the peer, by design.\n const key = displayedSideKey(edge.id, role)\n const side = resolveFacingSideAmong(\n rect,\n nodeRect(peer, worldPositions),\n anchorId ? [] : reachableSides(node.id, role, handles),\n extras?.displayedSides?.get(key),\n )\n extras?.displayedSides?.set(key, side)\n return endAt(side)\n}\n\n/** Approximate min distance from a point to a polyline. */\nexport function distanceToPolyline(point: Vec2, points: Vec2[]): number {\n let best = Number.POSITIVE_INFINITY\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]\n const b = points[i + 1]\n if (!a || !b) continue\n best = Math.min(best, distanceToSegment(point, a, b))\n }\n return best\n}\n\nfunction distanceToSegment(p: Vec2, a: Vec2, b: Vec2): number {\n const dx = b.x - a.x\n const dy = b.y - a.y\n const lenSq = dx * dx + dy * dy\n if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y)\n let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq\n t = Math.max(0, Math.min(1, t))\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))\n}\n","import { clamp } from \"@rivet/utils\"\nimport {\n type AnchorRecord,\n type AnchorRegistrationOptions,\n anchorGeometryEqual,\n anchorHandleId,\n computeAnchorGeometry,\n parseAnchorAutoHandleId,\n parseAnchorHandleId,\n} from \"./anchor/registry\"\nimport { applyEdgeChanges, applyNodeChanges } from \"./changes\"\nimport { DEFAULT_NODE_SIZE, handleKey } from \"./constants\"\nimport { type EdgeAlignment, resolveFacingSideAmong } from \"./edge-alignment\"\nimport { displayedSideKey, parseSideHandleId } from \"./edge-ends\"\nimport { guardNodeChanges, keepLocalGeometry } from \"./gesture-guard\"\nimport {\n buildChildIndex,\n collectDescendants,\n descendantIds,\n hasAncestorIn,\n nodeControlledEqual,\n nodeDepth,\n worldPosition,\n} from \"./graph\"\nimport { HistoryManager, type HistorySnapshot, hasRecordableChange } from \"./history\"\nimport { createLockRegistry, type LockRegistry } from \"./locks/registry\"\nimport { createPresenceRegistry, type PresenceRegistry } from \"./presence/registry\"\nimport { reachableSides } from \"./renderer/edge-geometry\"\nimport type {\n AlignmentGuide,\n ChangeMeta,\n ChangeOrigin,\n Connection,\n EdgeChange,\n EdgeEnd,\n EdgeId,\n HandlePosition,\n HandleRecord,\n HandleType,\n NodeChange,\n NodeGestureEvent,\n NodeId,\n NodeLockConflictEvent,\n PendingConnection,\n ReconnectDelegate,\n Rect,\n RivetEdge,\n RivetNode,\n RivetSelection,\n Size,\n Vec2,\n Viewport,\n} from \"./types\"\n\nexport { handleKey } from \"./constants\"\n\nexport type RivetStoreInit = {\n nodes: RivetNode[]\n edges: RivetEdge[]\n viewport: Viewport\n}\n\ntype ViewportClamp = { minX: number; minY: number; maxY?: number }\ntype ChangeHandlers = {\n nodes?: (changes: NodeChange[], meta: ChangeMeta) => void\n edges?: (changes: EdgeChange[], meta: ChangeMeta) => void\n}\n/** Gesture lifecycle sinks — see {@link RivetStore.setGestureHandlers}. */\ntype GestureHandlers = {\n start?: (event: NodeGestureEvent) => void\n end?: (event: NodeGestureEvent) => void\n /** A peer's lock landed on a node this client is already holding. */\n conflict?: (event: NodeLockConflictEvent) => void\n}\n\n/** Changes to hand to {@link RivetStore.applyRemote}. */\nexport type RemoteChanges = {\n nodes?: NodeChange[]\n edges?: EdgeChange[]\n /** Defaults to `\"remote\"`. Pass a peer or transaction id to route on it. */\n origin?: ChangeOrigin\n}\n\n/**\n * The single source of truth for a graph instance — the public contract. It's an\n * interface so consumers depend on the shape, not the implementation ({@link\n * RivetGraphStore}); pure graph algorithms live in `graph.ts`.\n *\n * Subscriptions are deliberately granular so touching one node never re-renders\n * the others:\n * - **per-node** channel — a `NodeWrapper` subscribes to only its own node, so\n * selecting/moving/measuring node A re-renders A alone.\n * - the `NodeLayer`'s list is driven by the culled `visibleIds` prop, so it\n * re-renders only when the visible set changes, never on node data.\n * - **viewport** and **frame** channels drive the canvas (and the label\n * layer's imperative positioning) without touching React at all.\n */\nexport type RivetStore = {\n readonly nodes: Map<NodeId, RivetNode>\n readonly edges: Map<EdgeId, RivetEdge>\n readonly handles: Map<string, HandleRecord>\n\n // Per-node React channel.\n getNodeVersion: (id: NodeId) => number\n subscribeNode: (id: NodeId, listener: () => void) => () => void\n\n // DOM-element registry — lets group drags translate peers imperatively.\n registerNodeElement: (id: NodeId, el: HTMLElement) => void\n unregisterNodeElement: (id: NodeId, el: HTMLElement) => void\n getNodeElement: (id: NodeId) => HTMLElement | undefined\n\n /**\n * Register the controlled-mode change sinks. When set, node/edge mutations emit\n * {@link NodeChange}/{@link EdgeChange} batches so a consumer can own the state.\n * Emission is suppressed while {@link reconcile} is applying incoming props, so\n * feeding changes back in never loops.\n */\n setChangeHandlers: (handlers: ChangeHandlers) => void\n /**\n * Sync the store to controlled `nodes`/`edges` props. Adds/removes/updates to\n * match, without re-emitting changes. No-op writes are skipped so unrelated\n * nodes don't re-render.\n */\n reconcile: (nodes: RivetNode[], edges: RivetEdge[]) => void\n /**\n * Apply a change batch that happened somewhere else — a peer's edit arriving\n * over your transport. The graph updates and repaints immediately, then the\n * batch is re-emitted to the change handlers tagged `\"remote\"` so a controlled\n * owner applies it through the same path as everything else.\n *\n * Remote batches never create an undo step: undoing a peer's edit isn't undo,\n * and in a shared document it would silently revert work you don't own. The\n * history baseline is refreshed instead, so your next local step still diffs\n * against reality.\n */\n applyRemote: (changes: RemoteChanges) => void\n\n /** Add a node (imperative CRUD). Ignored if the id already exists. */\n addNode: (node: RivetNode) => void\n /** Replace a node wholesale by id (imperative CRUD). Ignored if absent. */\n replaceNode: (id: NodeId, node: RivetNode) => void\n\n getViewport: () => Viewport\n setViewport: (viewport: Viewport) => void\n subscribeViewport: (listener: (viewport: Viewport) => void) => () => void\n /**\n * Bound panning against the swimlane area. `minX`/`minY` pin the top-left: you\n * can't scroll left of `minX` or up above `minY`. `maxY` (optional) pins the\n * bottom: you can't scroll down far enough to push the world-y `maxY` above the\n * pane top. Pass `null` to remove the bound. Applied to every viewport change,\n * including zoom and programmatic sets.\n */\n setViewportClamp: (clamp: ViewportClamp | null) => void\n\n // Post-frame channel — fires after each rendered canvas frame (pan, zoom,\n // node move, add/remove). Lets secondary views (e.g. a MiniMap) stay in sync\n // without a render loop of their own. `notifyFrame` is called by the runtime.\n subscribeFrame: (listener: () => void) => () => void\n notifyFrame: () => void\n\n /** Move a node. `commit` re-renders just that node; skip it during drag. */\n moveNode: (id: NodeId, position: Vec2, commit: boolean) => void\n setNodeSize: (id: NodeId, size: Size) => void\n /**\n * Set a node's explicit `width`/`height` (from {@link NodeResizer}), optionally\n * moving its origin (for top/left resize handles). Re-renders the node every\n * frame so its box and geometry props update live; `commit` only marks the\n * emitted change final (`resizing`/`dragging` false → recordable to history).\n */\n resizeNode: (id: NodeId, size: Size, position?: Vec2, commit?: boolean) => void\n /** Absolute world position of a node, resolving its {@link RivetNode.parentId} chain. */\n getNodeWorldPosition: (id: NodeId) => Vec2\n /**\n * World positions for every node (parent chains applied), cached and rebuilt only\n * when node geometry changes — so pan/zoom frames, where nothing moved, reuse it.\n */\n getWorldPositions: () => ReadonlyMap<NodeId, Vec2>\n /** A node's world-space box (`getNodeWorldPosition` + measured/default size). */\n getNodeRect: (id: NodeId) => Rect\n /** How many ancestors a node has (0 for a top-level node). Drives z-stacking. */\n getNodeDepth: (id: NodeId) => number\n /** Ids of every descendant of a node (children, grandchildren, …). */\n getDescendantIds: (id: NodeId) => NodeId[]\n /**\n * Of the given ids, the ones whose ancestor isn't also in the set — the nodes a\n * group move should actually translate (a selected child of a selected parent\n * rides along with the parent, so moving it too would double its travel).\n */\n getMovers: (ids: NodeId[]) => NodeId[]\n /**\n * Reassign a node's swimlane. Returns the previous lane id if it changed (so\n * the caller can fire a lane-change callback), or `false` when unchanged.\n */\n setNodeLane: (id: NodeId, laneId: string | null) => string | null | false\n /**\n * Set the edge-alignment policy (the `edgeAlignment` prop). Under\n * `\"on-move\"`, a committed position change re-sides the moved node's edges\n * to face their peers, inside the same emission batch as the move.\n */\n setEdgeAlignment: (mode: EdgeAlignment) => void\n /** The current edge-alignment policy (the runtime reads it per frame). */\n getEdgeAlignment: () => EdgeAlignment\n /**\n * Hysteresis memory for per-frame side resolution, keyed by\n * `displayedSideKey(edgeId, end)`. The render loop hands this map to the\n * renderer, which reads each auto-resolved end's last displayed side and\n * writes the new one back; a `\"live\"` alignment commit re-sides pinned ends\n * to exactly what was displayed, then drops those entries. Never persisted.\n */\n getDisplayedSides: () => Map<string, HandlePosition>\n /**\n * Nodes currently mid-drag — populated by uncommitted {@link moveNode}\n * frames, emptied on commit (and cleared as a backstop when\n * {@link setNodeDragging} ends the gesture). Under `edgeAlignment: \"live\"`,\n * edges touching these nodes render both ends as auto.\n */\n getDraggingNodeIds: () => ReadonlySet<NodeId>\n /** True while a node drag is in progress (pauses swimlane auto-fit). */\n isNodeDragging: () => boolean\n setNodeDragging: (dragging: boolean) => void\n /**\n * Open a gesture on `ids` — a pointer drag, a resize, or a keyboard grab.\n * While it's open those nodes are *held*: this client's geometry for them wins\n * over anything arriving from elsewhere (see {@link isNodeHeld}), and\n * {@link GestureHandlers.start} fires so a consumer can take a lock.\n *\n * `id` is the node the gesture began on; `ids` is everything moving with it\n * (a group drag holds the whole selection). Re-opening an already-held node\n * is a no-op, so a gesture may safely widen.\n */\n beginNodeGesture: (id: NodeId, ids?: NodeId[]) => void\n /**\n * Close a gesture opened by {@link beginNodeGesture}, releasing its nodes.\n *\n * Normally the gesture calls this itself on drop. Calling it from outside is\n * how a consumer yields a contested node mid-drag: the running gesture sees\n * that it no longer holds its nodes, stops writing to them, and tears itself\n * down without committing.\n */\n endNodeGesture: (id: NodeId, ids?: NodeId[]) => void\n /**\n * Publish the lock table (the `lockedNodes` prop), and report any node it\n * claims that a local gesture is already holding to\n * {@link GestureHandlers.conflict}. The gesture itself is left running — see\n * {@link NodeLockConflictEvent} for why rivet doesn't pick the loser.\n */\n setLockedNodes: (locks: Record<NodeId, string> | undefined) => void\n /**\n * True while a local gesture holds this node. Held geometry is exclusively\n * this client's: {@link applyRemote} drops incoming `position`/`dimensions`\n * for it, and {@link reconcile} keeps the live box rather than the prop's.\n */\n isNodeHeld: (id: NodeId) => boolean\n /** Every node currently under a local gesture. */\n getHeldNodeIds: () => ReadonlySet<NodeId>\n /**\n * Subscribe to the held set opening or closing. Unlike\n * {@link setGestureHandlers} — a single sink the `onNodeDragStart` /\n * `onNodeDragEnd` props own — this is a broadcast channel, so presence can\n * watch the same gesture the consumer's lock handler is acting on.\n */\n subscribeHeldNodes: (listener: () => void) => () => void\n /** Register the gesture lifecycle handlers (the lock acquire/release signals). */\n setGestureHandlers: (handlers: GestureHandlers) => void\n /**\n * True while a resize gesture is in progress — set by {@link resizeNode}'s live\n * frames and cleared by its commit. Stomp protection is per-node and lives in\n * {@link isNodeHeld}; this stays a coarse \"is a resize happening at all\" flag.\n */\n isNodeResizing: () => boolean\n /**\n * Select node(s). `additive` toggles `id` in the current selection (Shift/Cmd\n * click); otherwise the selection is replaced. Passing `null` clears it.\n */\n selectNode: (id: NodeId | null, additive?: boolean) => void\n /** Replace (or, if `additive`, extend) the node selection with `ids`. */\n selectNodes: (ids: NodeId[], additive?: boolean) => void\n /** The currently selected node ids. */\n getSelectedNodes: () => NodeId[]\n /** True if the node is part of the current selection. */\n isNodeSelected: (id: NodeId) => boolean\n /** The current selection (nodes + edges) as full records. */\n getSelection: () => RivetSelection\n /** Subscribe to selection changes (nodes and/or edges). */\n subscribeSelection: (listener: (selection: RivetSelection) => void) => () => void\n /**\n * The persistent selection box left behind by a marquee — a draggable rect\n * over the selected nodes' bounding box. Activated by the marquee's end;\n * deactivated by any other selection change (a node/edge/pane click, a\n * programmatic select, Escape, or deleting the selection).\n */\n setSelectionBoxActive: (active: boolean) => void\n isSelectionBoxActive: () => boolean\n /**\n * Version channel for the selection box: bumped when the flag flips and, while\n * active, when the boxed selection's membership or geometry changes — so the\n * box component can re-render its bounding rect from a single subscription.\n */\n getSelectionBoxVersion: () => number\n subscribeSelectionBox: (listener: () => void) => () => void\n /** Set (or clear, with `null`) the hovered node. */\n hoverNode: (id: NodeId | null) => void\n /**\n * The node that currently holds keyboard focus, or `null`. View state, like\n * hover — never recorded to history, never emitted as a change, and stripped\n * from snapshots. Tracked from the node elements' focus/blur by the node\n * layer; set it programmatically to move real DOM focus to a node (the\n * runtime follows this channel, centering the viewport first when the node\n * is culled out of the DOM).\n */\n getFocusedNode: () => NodeId | null\n /** Focus a node by id, or clear with `null`. Unknown ids are ignored. */\n setFocusedNode: (id: NodeId | null) => void\n /** Subscribe to focused-node changes. */\n subscribeFocus: (listener: (id: NodeId | null) => void) => () => void\n selectEdge: (id: EdgeId | null) => void\n /** The selected edge's id, or null. */\n getSelectedEdge: () => EdgeId | null\n /**\n * Runtime binding for the reconnect gateway. `<Handle>` consults it on\n * pointer-down so a press that lands on a handle coinciding with a\n * reconnectable edge's endpoint moves that edge instead of starting a new\n * connection. Bound by the runtime (like {@link bindRenderRequester}).\n */\n bindReconnectDelegate: (delegate: ReconnectDelegate | null) => void\n getReconnectDelegate: () => ReconnectDelegate | null\n addEdge: (edge: RivetEdge) => void\n /** Replace an edge wholesale by id (imperative CRUD). Ignored if absent. */\n replaceEdge: (id: EdgeId, edge: RivetEdge) => void\n /** Re-point an edge's source/target (from an endpoint reconnection drag). */\n reconnectEdge: (id: EdgeId, connection: Connection) => void\n removeEdge: (id: EdgeId) => void\n removeNode: (id: NodeId) => void\n /** Delete the selected node (and its edges) and/or edge. Returns true if any. */\n deleteSelection: () => boolean\n\n // Undo / redo over structural graph history (positions, add/remove/replace).\n // Selection changes and live drag/resize frames don't create steps.\n /** Revert the last recordable change. Returns false when there's nothing to undo. */\n undo: () => boolean\n /** Re-apply the last undone change. Returns false when there's nothing to redo. */\n redo: () => boolean\n canUndo: () => boolean\n canRedo: () => boolean\n /** Drop all history and reset the baseline to the current graph. */\n clearHistory: () => void\n /** Subscribe to history changes (drives `canUndo`/`canRedo` reactivity). */\n subscribeHistory: (listener: () => void) => () => void\n\n // Screen-space label anchors, refreshed by the renderer each frame. The DOM\n // edge-label layer reads these on `subscribeFrame` to place labels.\n getEdgeLabelAnchors: () => Map<EdgeId, Vec2>\n setEdgeLabelAnchors: (anchors: Map<EdgeId, Vec2>) => void\n\n /** Alignment/snap guides to draw for the current drag (world space). Empty when idle. */\n getAlignmentGuides: () => AlignmentGuide[]\n setAlignmentGuides: (guides: AlignmentGuide[]) => void\n\n // Handle registry — canvas-only, never triggers a React re-render.\n registerHandle: (record: HandleRecord) => void\n unregisterHandle: (nodeId: NodeId, handleId: string) => void\n\n /**\n * Ephemeral peer presence — cursors, selections, and the boxes peers are\n * dragging right now. Never part of the graph, the change stream, or\n * history: presence describes people, not the document. Painted from the\n * render loop; see `rivet/presence`.\n */\n readonly presence: PresenceRegistry\n\n /**\n * Nodes peers have claimed, and the policy for what this client may still do\n * to them. Published whole by {@link setLockedNodes}; read by every input\n * path before it acts, and by the render loop to outline the holder. Like\n * presence, never part of the graph, the change stream, or history.\n */\n readonly locks: LockRegistry\n\n // Anchor registry — a connectable point bound to a DOM element inside a\n // node. Keyed like handles; per-node version channel drives the chrome.\n readonly anchors: Map<string, AnchorRecord>\n /**\n * Register (or re-bind) an anchor. Idempotent on the `(nodeId, anchorId)`\n * key: calling again with a new element re-attaches it, keeping any\n * last-known geometry until the next successful measurement.\n */\n registerAnchor: (\n nodeId: NodeId,\n anchorId: string,\n element: Element,\n options?: AnchorRegistrationOptions,\n ) => void\n /**\n * Mark an anchor's element gone without removing the anchor — the stale\n * retention signal. Geometry (and the stray handles rendered from it) is\n * kept so edges stay put while the display is unmounted.\n */\n detachAnchor: (nodeId: NodeId, anchorId: string) => void\n /** Explicitly remove an anchor and the chrome rendered for it. */\n unregisterAnchor: (nodeId: NodeId, anchorId: string) => void\n /**\n * Re-measure a node's anchors. Called automatically when the node's box\n * resizes; call it directly after content reflows *without* a resize (an\n * editor transaction, a font load) — rivet can't observe those.\n */\n remeasureAnchors: (nodeId: NodeId) => void\n /** The node's anchors, in registration order. */\n getNodeAnchors: (nodeId: NodeId) => AnchorRecord[]\n getNodeAnchorsVersion: (nodeId: NodeId) => number\n subscribeNodeAnchors: (nodeId: NodeId, listener: () => void) => () => void\n\n // Edge connectivity channel — bumped when edges are added/removed or change\n // endpoints/handles, so anchor chrome can follow which sides are connected.\n getEdgesVersion: () => number\n subscribeEdges: (listener: () => void) => () => void\n\n // In-progress connection (drag-to-connect).\n getPending: () => PendingConnection | null\n beginConnection: (pending: PendingConnection) => void\n updateConnection: (to: Vec2, toPosition?: HandlePosition) => void\n endConnection: () => void\n\n /** Ask the runtime to schedule a canvas frame. */\n requestRender: () => void\n bindRenderRequester: (fn: () => void) => void\n /**\n * Ask the runtime to repaint the peer-cursor layer only — everything else on\n * screen keeps last frame's pixels. Degrades to {@link requestRender} while\n * no runtime has claimed the layer, so a caller never has to check.\n */\n requestCursorRender: () => void\n bindCursorRenderRequester: (fn: (() => void) | null) => void\n}\n\n/**\n * The store implementation. Public methods are bound arrow fields so they can be\n * passed unbound (e.g. straight into `useSyncExternalStore`); internal bookkeeping\n * lives in private methods, and the graph walks come from `graph.ts`.\n */\nclass RivetGraphStore implements RivetStore {\n readonly nodes = new Map<NodeId, RivetNode>()\n readonly edges = new Map<EdgeId, RivetEdge>()\n readonly handles = new Map<string, HandleRecord>()\n readonly anchors = new Map<string, AnchorRecord>()\n // Arrow-wrapped so the (later-initialized) requestRender field is looked up\n // at call time, not while this field is being constructed.\n readonly presence = createPresenceRegistry({\n requestRender: () => this.requestRender(),\n requestCursorRender: () => this.requestCursorRender(),\n })\n readonly locks = createLockRegistry(() => this.requestRender())\n\n private viewport: Viewport\n private viewportClamp: ViewportClamp | null = null\n private pending: PendingConnection | null = null\n\n private readonly nodeVersions = new Map<NodeId, number>()\n private readonly nodeListeners = new Map<NodeId, Set<() => void>>()\n private readonly anchorVersions = new Map<NodeId, number>()\n private readonly anchorListeners = new Map<NodeId, Set<() => void>>()\n private edgesVersion = 0\n private readonly edgesListeners = new Set<() => void>()\n private readonly nodeElements = new Map<NodeId, HTMLElement>()\n private readonly viewportListeners = new Set<(viewport: Viewport) => void>()\n private readonly frameListeners = new Set<() => void>()\n private readonly selectionListeners = new Set<(selection: RivetSelection) => void>()\n private readonly selectedNodeIds = new Set<NodeId>()\n private selectionBoxActive = false\n private selectionBoxVersion = 0\n private readonly selectionBoxListeners = new Set<() => void>()\n\n private hoveredNodeId: NodeId | null = null\n private focusedNodeId: NodeId | null = null\n private readonly focusListeners = new Set<(id: NodeId | null) => void>()\n private selectedEdgeId: EdgeId | null = null\n private nodeDragging = false\n private nodeResizing = false\n private edgeAlignment: EdgeAlignment = \"manual\"\n private readonly draggingNodeIds = new Set<NodeId>()\n private readonly heldNodeIds = new Set<NodeId>()\n private readonly heldListeners = new Set<() => void>()\n private gestureStartHandler: GestureHandlers[\"start\"] | null = null\n private gestureEndHandler: GestureHandlers[\"end\"] | null = null\n private lockConflictHandler: GestureHandlers[\"conflict\"] | null = null\n private readonly displayedSides = new Map<string, HandlePosition>()\n private edgeLabelAnchors = new Map<EdgeId, Vec2>()\n private alignmentGuides: AlignmentGuide[] = []\n\n private nodeChangeHandler: ChangeHandlers[\"nodes\"] | null = null\n private edgeChangeHandler: ChangeHandlers[\"edges\"] | null = null\n private reconciling = false\n private readonly history = new HistoryManager(() => this.historySnapshot())\n\n private lastSelectionKey: string\n private worldCache: Map<NodeId, Vec2> | null = null\n /** {@link worldCache} with peers' live gesture boxes folded in. */\n private peerWorldCache: Map<NodeId, Vec2> | null = null\n /** Presence transform version {@link peerWorldCache} was built from. */\n private peerWorldVersion = -1\n private renderRequester: () => void = () => {}\n /**\n * Null until a runtime claims it, and then `requestCursorRender` narrows to\n * the cursor layer. Falling back to a full frame is the safe default: a\n * consumer without the layer mounted still gets its paint.\n */\n private cursorRenderRequester: (() => void) | null = null\n\n constructor(init: RivetStoreInit) {\n this.viewport = init.viewport\n for (const node of init.nodes) this.writeNode(node.id, node)\n for (const edge of init.edges) this.edges.set(edge.id, edge)\n // Seed selection so `selected` flags and the selection set agree from frame one.\n for (const node of init.nodes) if (node.selected) this.selectedNodeIds.add(node.id)\n this.selectedEdgeId = init.edges.find((edge) => edge.selected)?.id ?? null\n this.lastSelectionKey = this.selectionKey()\n // The history baseline is captured at field-init (before nodes loaded above),\n // so reset it now that the initial graph is in place.\n this.history.clear()\n }\n\n // --- internal bookkeeping ------------------------------------------------\n\n private invalidateWorld(): void {\n this.worldCache = null\n this.peerWorldCache = null\n }\n\n /**\n * The single node-map write path. Invalidates the world-position cache exactly\n * when a layout-affecting field changed (the node's position or its parent\n * chain) or the node is new — so size/lane/selection/hover writes skip the\n * O(n) rebuild, and no mutator can forget to invalidate.\n */\n private writeNode(id: NodeId, next: RivetNode): void {\n const prev = this.nodes.get(id)\n this.nodes.set(id, next)\n if (\n !prev ||\n prev.parentId !== next.parentId ||\n prev.position.x !== next.position.x ||\n prev.position.y !== next.position.y\n ) {\n this.invalidateWorld()\n }\n }\n\n /** The single node-map delete path. Always invalidates — a removal shifts descendants. */\n private deleteNode(id: NodeId): void {\n this.nodes.delete(id)\n this.invalidateWorld()\n }\n\n private selectionKey(): string {\n return `${[...this.selectedNodeIds].sort().join(\",\")}|${this.selectedEdgeId ?? \"\"}`\n }\n\n private buildSelection(): RivetSelection {\n return {\n nodes: [...this.selectedNodeIds]\n .map((id) => this.nodes.get(id))\n .filter((n) => n !== undefined),\n edges: this.selectedEdgeId\n ? [this.edges.get(this.selectedEdgeId)].filter((e) => e !== undefined)\n : [],\n }\n }\n\n private notifySelection(): void {\n const key = this.selectionKey()\n if (key === this.lastSelectionKey) return\n this.lastSelectionKey = key\n // Membership changes that bypass the select* methods (reconcile, node\n // removal) still reshape an active box.\n if (this.selectionBoxActive) this.bumpSelectionBox()\n if (this.selectionListeners.size === 0) return\n const selection = this.buildSelection()\n for (const listener of this.selectionListeners) listener(selection)\n }\n\n private notifyHeld(): void {\n // The held set decides whose gesture owns a node's geometry, so the folded\n // world positions have to be rebuilt when it changes: a node this client\n // just let go of takes its peer's live box again, and one just grabbed\n // stops taking it.\n this.peerWorldCache = null\n this.requestRender()\n for (const listener of this.heldListeners) listener()\n }\n\n /**\n * The one emission policy. Unless a `reconcile` is applying incoming props\n * (which must never echo them back out), record the batch to history — when\n * `record` is set — then hand it to the controlled consumer. Recording happens\n * before the handler so history works in uncontrolled mode too.\n */\n private emit<C extends NodeChange | EdgeChange>(\n changes: C[],\n handler: ((changes: C[], meta: ChangeMeta) => void) | null | undefined,\n record: boolean,\n origin: ChangeOrigin = \"local\",\n ): void {\n if (this.reconciling || changes.length === 0) return\n if (record) this.history.record(hasRecordableChange(changes))\n // Unrecorded structural changes (measurement echoes, history restores) still\n // move the graph — rebase so the next recorded step diffs against reality.\n else if (hasRecordableChange(changes)) this.history.rebase()\n handler?.(changes, { origin })\n }\n\n private emitNodeChanges(changes: NodeChange[], record = true): void {\n this.emit(changes, this.nodeChangeHandler, record)\n }\n\n private emitEdgeChanges(changes: EdgeChange[], record = true): void {\n this.emit(changes, this.edgeChangeHandler, record)\n }\n\n private bumpNode(id: NodeId): void {\n this.nodeVersions.set(id, (this.nodeVersions.get(id) ?? 0) + 1)\n const listeners = this.nodeListeners.get(id)\n if (listeners) for (const listener of listeners) listener()\n // A boxed node's committed geometry change (arrow nudge, undo, resize)\n // moves the selection box's bounding rect with it.\n if (this.selectionBoxActive && this.selectedNodeIds.has(id)) this.bumpSelectionBox()\n }\n\n private bumpSelectionBox(): void {\n this.selectionBoxVersion += 1\n for (const listener of this.selectionBoxListeners) listener()\n }\n\n private bumpAnchors(id: NodeId): void {\n this.anchorVersions.set(id, (this.anchorVersions.get(id) ?? 0) + 1)\n const listeners = this.anchorListeners.get(id)\n if (listeners) for (const listener of listeners) listener()\n }\n\n private bumpEdges(): void {\n this.edgesVersion += 1\n for (const listener of this.edgesListeners) listener()\n }\n\n // Node selection is React state (nodes are DOM), so bump only what flips.\n // `target` is the exact set that should end up selected.\n private applyNodeSelection(target: Set<NodeId>): void {\n const changes: NodeChange[] = []\n for (const [nodeId, node] of this.nodes) {\n const selected = target.has(nodeId)\n if (Boolean(node.selected) !== selected) {\n this.writeNode(nodeId, { ...node, selected })\n this.bumpNode(nodeId)\n changes.push({ type: \"select\", id: nodeId, selected })\n }\n }\n this.selectedNodeIds.clear()\n for (const id of target) if (this.nodes.has(id)) this.selectedNodeIds.add(id)\n this.emitNodeChanges(changes)\n }\n\n private setNodeHover(id: NodeId | null): void {\n if (this.hoveredNodeId === id) return\n const prev = this.hoveredNodeId\n this.hoveredNodeId = id\n if (prev !== null) {\n const node = this.nodes.get(prev)\n if (node) {\n this.writeNode(prev, { ...node, hovered: false })\n this.bumpNode(prev)\n }\n }\n if (id !== null) {\n const node = this.nodes.get(id)\n if (node) {\n this.writeNode(id, { ...node, hovered: true })\n this.bumpNode(id)\n }\n }\n }\n\n // Edge selection is canvas-only, so it just invalidates the frame.\n private setEdgeSelection(id: EdgeId | null): void {\n if (this.selectedEdgeId === id) return\n const changes: EdgeChange[] = []\n if (this.selectedEdgeId) {\n const prev = this.edges.get(this.selectedEdgeId)\n if (prev) {\n this.edges.set(this.selectedEdgeId, { ...prev, selected: false })\n changes.push({ type: \"select\", id: this.selectedEdgeId, selected: false })\n }\n }\n if (id) {\n const next = this.edges.get(id)\n if (next) {\n this.edges.set(id, { ...next, selected: true })\n changes.push({ type: \"select\", id, selected: true })\n }\n }\n this.selectedEdgeId = id\n this.emitEdgeChanges(changes)\n this.requestRender()\n }\n\n private removeEdgeInternal(id: EdgeId): boolean {\n if (!this.edges.delete(id)) return false\n if (this.selectedEdgeId === id) this.selectedEdgeId = null\n this.displayedSides.delete(displayedSideKey(id, \"source\"))\n this.displayedSides.delete(displayedSideKey(id, \"target\"))\n this.bumpEdges()\n return true\n }\n\n // Drop a node's bookkeeping (map entry, version, selection, hover, its\n // handles and anchors). Edges are handled by the caller — reconcile owns\n // edges separately from remove.\n private dropNodeState(id: NodeId): void {\n this.deleteNode(id)\n this.nodeVersions.delete(id)\n this.anchorVersions.delete(id)\n this.selectedNodeIds.delete(id)\n if (this.hoveredNodeId === id) this.hoveredNodeId = null\n if (this.focusedNodeId === id) this.setFocusedNode(null)\n const prefix = `${id} `\n for (const key of this.handles.keys()) {\n if (key.startsWith(prefix)) this.handles.delete(key)\n }\n for (const key of this.anchors.keys()) {\n if (key.startsWith(prefix)) this.anchors.delete(key)\n }\n }\n\n private removeNodeInternal(id: NodeId, removedEdges: EdgeId[]): boolean {\n if (!this.nodes.has(id)) return false\n this.dropNodeState(id)\n for (const [edgeId, edge] of this.edges) {\n if (edge.source === id || edge.target === id) {\n if (this.removeEdgeInternal(edgeId)) removedEdges.push(edgeId)\n }\n }\n return true\n }\n\n private edgeRemoveChanges(ids: EdgeId[]): EdgeChange[] {\n return ids.map((id) => ({ type: \"remove\", id }))\n }\n\n private clampViewport(next: Viewport): Viewport {\n const bound = this.viewportClamp\n if (!bound) return next\n const maxViewportX = -bound.minX * next.zoom\n const maxViewportY = -bound.minY * next.zoom\n const minViewportY =\n bound.maxY === undefined ? Number.NEGATIVE_INFINITY : -bound.maxY * next.zoom\n return {\n ...next,\n x: Math.min(next.x, maxViewportX),\n y: clamp(next.y, minViewportY, maxViewportY),\n }\n }\n\n private reconcileNodes(nextNodes: RivetNode[]): void {\n const incoming = new Set<NodeId>()\n const moved: NodeId[] = []\n for (const node of nextNodes) {\n incoming.add(node.id)\n const existing = this.nodes.get(node.id)\n if (!existing) {\n this.writeNode(node.id, node)\n continue\n }\n // A held node's geometry is this client's until the gesture ends: the\n // incoming props lag the live box (frames are dropped, and a measurement\n // echo carries `size` but not the explicit `width`/`height`), so taking\n // them would stomp the node back mid-drag. Everything else still lands.\n const settled = this.heldNodeIds.has(node.id) ? keepLocalGeometry(node, existing) : node\n if (nodeControlledEqual(existing, settled)) continue\n // Preserve hover (store-owned, never present in controlled props).\n this.writeNode(node.id, existing.hovered ? { ...settled, hovered: true } : settled)\n this.bumpNode(node.id)\n if (\n existing.position.x !== settled.position.x ||\n existing.position.y !== settled.position.y\n ) {\n moved.push(node.id)\n }\n }\n for (const id of [...this.nodes.keys()]) {\n if (!incoming.has(id)) this.dropNodeState(id)\n }\n // A moved node drags its descendants' world position; re-render them too. Build\n // the child index once for the whole batch rather than per moved node.\n if (moved.length > 0) {\n const childIndex = buildChildIndex(this.nodes)\n const descendants: NodeId[] = []\n for (const id of moved) collectDescendants(id, childIndex, descendants)\n for (const id of descendants) this.bumpNode(id)\n }\n this.selectedNodeIds.clear()\n for (const node of nextNodes) if (node.selected) this.selectedNodeIds.add(node.id)\n }\n\n private reconcileEdges(nextEdges: RivetEdge[]): void {\n const incoming = new Set<EdgeId>()\n // Reconcile runs on every controlled render; bump the connectivity channel\n // only when an edge appeared/disappeared or changed ends, so anchor chrome\n // doesn't re-render on unrelated prop round-trips.\n let connectivityChanged = false\n for (const edge of nextEdges) {\n incoming.add(edge.id)\n const prev = this.edges.get(edge.id)\n if (\n !prev ||\n prev.source !== edge.source ||\n prev.target !== edge.target ||\n prev.sourceHandle !== edge.sourceHandle ||\n prev.targetHandle !== edge.targetHandle\n ) {\n connectivityChanged = true\n }\n this.edges.set(edge.id, edge) // canvas-only; a wholesale replace is cheap\n }\n for (const id of [...this.edges.keys()]) {\n if (!incoming.has(id)) {\n this.edges.delete(id)\n connectivityChanged = true\n }\n }\n this.selectedEdgeId = nextEdges.find((edge) => edge.selected)?.id ?? null\n if (connectivityChanged) this.bumpEdges()\n }\n\n // --- per-node React channel ----------------------------------------------\n\n getNodeVersion = (id: NodeId): number => this.nodeVersions.get(id) ?? 0\n\n subscribeNode = (id: NodeId, listener: () => void): (() => void) => {\n let set = this.nodeListeners.get(id)\n if (!set) {\n set = new Set()\n this.nodeListeners.set(id, set)\n }\n set.add(listener)\n return () => {\n set.delete(listener)\n if (set.size === 0) this.nodeListeners.delete(id)\n }\n }\n\n registerNodeElement = (id: NodeId, el: HTMLElement): void => {\n this.nodeElements.set(id, el)\n }\n\n unregisterNodeElement = (id: NodeId, el: HTMLElement): void => {\n // Guard against a remount racing an unmount: only drop our own element.\n if (this.nodeElements.get(id) === el) this.nodeElements.delete(id)\n }\n\n getNodeElement = (id: NodeId): HTMLElement | undefined => this.nodeElements.get(id)\n\n // --- viewport ------------------------------------------------------------\n\n getViewport = (): Viewport => this.viewport\n\n setViewport = (next: Viewport): void => {\n this.viewport = this.clampViewport(next)\n for (const listener of this.viewportListeners) listener(this.viewport)\n }\n\n setViewportClamp = (clampBound: ViewportClamp | null): void => {\n this.viewportClamp = clampBound\n const clamped = this.clampViewport(this.viewport)\n if (clamped.x !== this.viewport.x || clamped.y !== this.viewport.y) {\n this.viewport = clamped\n for (const listener of this.viewportListeners) listener(this.viewport)\n this.requestRender()\n }\n }\n\n subscribeViewport = (listener: (viewport: Viewport) => void): (() => void) => {\n this.viewportListeners.add(listener)\n return () => {\n this.viewportListeners.delete(listener)\n }\n }\n\n subscribeFrame = (listener: () => void): (() => void) => {\n this.frameListeners.add(listener)\n return () => {\n this.frameListeners.delete(listener)\n }\n }\n\n notifyFrame = (): void => {\n for (const listener of this.frameListeners) listener()\n }\n\n // --- node geometry -------------------------------------------------------\n\n getWorldPositions = (): ReadonlyMap<NodeId, Vec2> => {\n if (!this.worldCache) {\n this.worldCache = new Map()\n for (const id of this.nodes.keys()) this.worldCache.set(id, worldPosition(this.nodes, id))\n }\n const version = this.presence.getTransformVersion()\n // Nobody else is mid-gesture: the graph's own positions are the whole story.\n if (this.presence.getNodeTransforms().size === 0) return this.worldCache\n if (this.peerWorldCache && this.peerWorldVersion === version) return this.peerWorldCache\n this.peerWorldVersion = version\n this.peerWorldCache = this.withPeerGestures(this.worldCache)\n return this.peerWorldCache\n }\n\n /**\n * Fold peers' live gesture boxes into world positions.\n *\n * A node somebody else is dragging is drawn, hit-tested and wired at the box\n * they last sent — the node moves, rather than a ghost of it appearing\n * elsewhere. The graph underneath is untouched: nothing here is written back,\n * so their drag never enters the document, the change stream, or history, and\n * the node lands for real when their commit arrives.\n *\n * Descendants ride along by the same delta, since their own positions are\n * relative to a parent this map has just moved.\n */\n private withPeerGestures(base: Map<NodeId, Vec2>): Map<NodeId, Vec2> {\n const merged = new Map(base)\n for (const [id, rect] of this.presence.getNodeTransforms()) {\n // A local gesture outranks a peer's: this client's pointer is on the node,\n // and ownership of geometry under a live gesture is exactly what the\n // guard exists to protect.\n if (this.heldNodeIds.has(id)) continue\n const origin = base.get(id)\n if (!origin) continue\n const dx = rect.x - origin.x\n const dy = rect.y - origin.y\n if (dx === 0 && dy === 0) continue\n merged.set(id, { x: rect.x, y: rect.y })\n for (const childId of this.getDescendantIds(id)) {\n const child = merged.get(childId)\n if (child) merged.set(childId, { x: child.x + dx, y: child.y + dy })\n }\n }\n return merged\n }\n\n getNodeWorldPosition = (id: NodeId): Vec2 => this.getWorldPositions().get(id) ?? { x: 0, y: 0 }\n\n getNodeRect = (id: NodeId): Rect => {\n const origin = this.getNodeWorldPosition(id)\n // A peer mid-resize sends a box, not just a point; take its size too, so the\n // node, its edges and its outline agree on how big it currently is.\n const live = this.heldNodeIds.has(id) ? undefined : this.presence.getNodeTransforms().get(id)\n if (live) return { x: origin.x, y: origin.y, width: live.width, height: live.height }\n // Explicit width/height outrank the measured size, the same order the node\n // element itself renders in — a controlled node arrives sized but unmeasured,\n // and reporting the default box for it would put edges, the minimap and\n // marquee hit-testing on a box nothing is drawn at.\n const node = this.nodes.get(id)\n return {\n x: origin.x,\n y: origin.y,\n width: node?.width ?? node?.size?.width ?? DEFAULT_NODE_SIZE.width,\n height: node?.height ?? node?.size?.height ?? DEFAULT_NODE_SIZE.height,\n }\n }\n\n getNodeDepth = (id: NodeId): number => nodeDepth(this.nodes, id)\n\n getDescendantIds = (id: NodeId): NodeId[] => descendantIds(this.nodes, id)\n\n getMovers = (ids: NodeId[]): NodeId[] => {\n const set = new Set(ids)\n return ids.filter((id) => !hasAncestorIn(this.nodes, id, set))\n }\n\n // --- node mutations ------------------------------------------------------\n\n moveNode = (id: NodeId, position: Vec2, commit: boolean): void => {\n const node = this.nodes.get(id)\n if (!node) return\n this.writeNode(id, { ...node, position })\n // Track which nodes are mid-drag (live frames open, the commit closes) so\n // `\"live\"` alignment knows whose edges to render as auto.\n if (commit) this.draggingNodeIds.delete(id)\n else this.draggingNodeIds.add(id)\n this.requestRender() // edges follow every frame\n if (commit) {\n this.bumpNode(id)\n // Descendants moved with this node in world space; re-render them so their\n // React transform (parent world + own offset) is recomputed.\n for (const descendant of descendantIds(this.nodes, id)) this.bumpNode(descendant)\n }\n this.emitNodeChanges([{ type: \"position\", id, position, dragging: !commit }])\n // After the position emission, so the edge rewrites coalesce into the\n // move's history step and the consumer sees the move before the re-side.\n if (commit) this.realignNodeEdges(id)\n }\n\n setNodeSize = (id: NodeId, size: Size): void => {\n const node = this.nodes.get(id)\n if (!node) return\n // Sub-pixel tolerance, not equality: measurements arrive as integer offset\n // dimensions, while an explicit size (from resizeNode) is fractional. During\n // a resize the observer echoes each frame back rounded; treating that echo\n // as a real measurement would emit an unflagged dimensions change mid-gesture.\n if (\n node.size &&\n Math.abs(node.size.width - size.width) < 1 &&\n Math.abs(node.size.height - size.height) < 1\n ) {\n return\n }\n this.writeNode(id, { ...node, size })\n this.requestRender()\n this.bumpNode(id)\n // Auto-measurement is store bookkeeping, not a user edit: emit it (controlled\n // mode needs the size) but never let it create an undo step.\n this.emitNodeChanges([{ type: \"dimensions\", id, dimensions: size }], false)\n }\n\n resizeNode = (id: NodeId, size: Size, position?: Vec2, commit = true): void => {\n const node = this.nodes.get(id)\n if (!node) return\n // Live frames open the gesture window; the commit closes it (before the\n // emission below, so the commit's own round-trip reconciles normally).\n this.nodeResizing = !commit\n const next: RivetNode = { ...node, width: size.width, height: size.height, size }\n if (position) next.position = position\n this.writeNode(id, next)\n this.requestRender()\n // Re-render the node every frame, not just on commit: a resize is always a\n // single node, so a per-frame re-render is cheap, and it keeps the box and the\n // node's geometry props live. (Group drag stays imperative — it can move many.)\n this.bumpNode(id)\n const changes: NodeChange[] = [{ type: \"dimensions\", id, dimensions: size, resizing: !commit }]\n if (position) changes.push({ type: \"position\", id, position, dragging: !commit })\n this.emitNodeChanges(changes)\n // A top/left resize handle moves the origin — that's a committed position\n // change, so it realigns like a move. A pure grow/shrink (dimensions only)\n // doesn't: auto-height echoes must never override a freshly chosen side.\n if (commit && position) this.realignNodeEdges(id)\n }\n\n setNodeLane = (id: NodeId, laneId: string | null): string | null | false => {\n const node = this.nodes.get(id)\n if (!node) return false\n const next = laneId ?? undefined\n if (node.laneId === next) return false\n const previous = node.laneId ?? null\n const updated = { ...node, laneId: next }\n this.writeNode(id, updated)\n this.bumpNode(id)\n // laneId isn't a standard change kind; round-trip it as a full replace.\n this.emitNodeChanges([{ type: \"replace\", id, item: updated }])\n return previous\n }\n\n addNode = (node: RivetNode): void => {\n if (this.nodes.has(node.id)) return\n this.writeNode(node.id, node)\n if (node.selected) this.selectedNodeIds.add(node.id)\n this.requestRender()\n this.emitNodeChanges([{ type: \"add\", item: node }])\n }\n\n replaceNode = (id: NodeId, node: RivetNode): void => {\n if (!this.nodes.has(id)) return\n this.writeNode(id, node)\n if (node.selected) this.selectedNodeIds.add(id)\n else this.selectedNodeIds.delete(id)\n this.bumpNode(id)\n this.requestRender()\n this.emitNodeChanges([{ type: \"replace\", id, item: node }])\n }\n\n removeNode = (id: NodeId): void => {\n const removedEdges: EdgeId[] = []\n if (this.removeNodeInternal(id, removedEdges)) {\n this.emitNodeChanges([{ type: \"remove\", id }])\n this.emitEdgeChanges(this.edgeRemoveChanges(removedEdges))\n this.requestRender()\n this.notifySelection()\n }\n }\n\n // --- edge alignment ------------------------------------------------------\n\n setEdgeAlignment = (mode: EdgeAlignment): void => {\n this.edgeAlignment = mode\n }\n\n getEdgeAlignment = (): EdgeAlignment => this.edgeAlignment\n\n getDisplayedSides = (): Map<string, HandlePosition> => this.displayedSides\n\n getDraggingNodeIds = (): ReadonlySet<NodeId> => this.draggingNodeIds\n\n /**\n * Re-side one edge end toward `side`. Auto ends (no handle, or an\n * `inode-…-auto` id) have no pin to rewrite and pass through. Anchor stray\n * and bare-side ids encode their side, so they rewrite as strings (the\n * anchor chrome follows connectivity, and the target stray may not be\n * rendered yet). A registered plain handle re-sides through the registry:\n * swap to a registered handle on the facing side with a compatible type. No\n * candidate (single-handle nodes, custom layouts, a culled peer whose\n * handles are unregistered) means the pin is kept.\n */\n /**\n * The side of `nodeId` that faces `peerRect` and can actually be reached by\n * this end. An anchor end is unconstrained — its stray places itself along\n * whichever side faces the peer — and so is a node with no compatible handle\n * at all, which attaches at side midpoints.\n */\n private reachableFacingSide(\n nodeId: NodeId,\n handleId: string | undefined,\n rect: Rect,\n peerRect: Rect,\n end: EdgeEnd,\n ): HandlePosition {\n const allowed =\n parseAnchorHandleId(handleId) || parseAnchorAutoHandleId(handleId)\n ? []\n : reachableSides(nodeId, end, this.handles)\n return resolveFacingSideAmong(rect, peerRect, allowed)\n }\n\n private realignEndHandle(\n nodeId: NodeId,\n handleId: string | undefined,\n side: HandlePosition,\n end: \"source\" | \"target\",\n ): string | undefined {\n if (!handleId || parseAnchorAutoHandleId(handleId)) return handleId\n const anchor = parseAnchorHandleId(handleId)\n if (anchor) return anchor.side === side ? handleId : anchorHandleId(anchor.anchorId, side)\n const record = this.handles.get(handleKey(nodeId, handleId))\n if (!record) return parseSideHandleId(handleId) ? side : handleId\n if (record.position === side) return handleId\n const wanted: readonly HandleType[] =\n end === \"source\" ? [\"source\", \"either\"] : [\"target\", \"either\"]\n for (const candidate of this.handles.values()) {\n if (\n candidate.nodeId === nodeId &&\n candidate.position === side &&\n wanted.includes(candidate.type)\n ) {\n return candidate.handleId\n }\n }\n return handleId\n }\n\n /**\n * Under `\"on-move\"` and `\"live\"`: re-side both ends of the moved node's\n * edges to face each other. Called only from committed position mutations —\n * never from replaces, dimension echoes, reconcile, or history restores,\n * which must not move an edge the user didn't touch or rewrite handles an\n * undo just restored. Emitting in the same synchronous batch as the move\n * keeps the rewrite inside the move's history step (microtask coalescing).\n *\n * `\"live\"` commits the *displayed* side when the renderer resolved one this\n * gesture — the hysteresis band means the raw facing side can differ near a\n * diagonal, and the drop must not flip what the user was just shown. The\n * consumed entries are dropped afterwards so a later commit without live\n * frames (an arrow-key move) can't re-side to a stale display.\n */\n private realignNodeEdges(nodeId: NodeId): void {\n if (this.edgeAlignment === \"manual\") return\n const live = this.edgeAlignment === \"live\"\n const changes: EdgeChange[] = []\n for (const [edgeId, edge] of this.edges) {\n if (edge.source !== nodeId && edge.target !== nodeId) continue\n // A self-edge has no facing side; re-siding would collapse both ends.\n if (edge.source === edge.target) continue\n if (!this.nodes.has(edge.source) || !this.nodes.has(edge.target)) continue\n const sourceRect = this.getNodeRect(edge.source)\n const targetRect = this.getNodeRect(edge.target)\n const sourceKey = displayedSideKey(edgeId, \"source\")\n const targetKey = displayedSideKey(edgeId, \"target\")\n // Constrained to the sides that carry a handle this end can use, the same\n // way the renderer resolves an auto end. Free resolution picks the\n // geometric facing side and then finds nothing there — a node with only\n // left and right handles never re-sides at all, because every vertical\n // layout resolves to a bare top or bottom.\n const sourceSide =\n (live ? this.displayedSides.get(sourceKey) : undefined) ??\n this.reachableFacingSide(edge.source, edge.sourceHandle, sourceRect, targetRect, \"source\")\n const targetSide =\n (live ? this.displayedSides.get(targetKey) : undefined) ??\n this.reachableFacingSide(edge.target, edge.targetHandle, targetRect, sourceRect, \"target\")\n const sourceHandle = this.realignEndHandle(\n edge.source,\n edge.sourceHandle,\n sourceSide,\n \"source\",\n )\n const targetHandle = this.realignEndHandle(\n edge.target,\n edge.targetHandle,\n targetSide,\n \"target\",\n )\n if (live) {\n // Keep auto ends' entries — they're refreshed every frame and carry the\n // hysteresis across the commit. Pinned ends' pins are now current.\n const pinned = (h: string | undefined) => Boolean(h) && !parseAnchorAutoHandleId(h)\n if (pinned(edge.sourceHandle)) this.displayedSides.delete(sourceKey)\n if (pinned(edge.targetHandle)) this.displayedSides.delete(targetKey)\n }\n if (sourceHandle === edge.sourceHandle && targetHandle === edge.targetHandle) continue\n const updated: RivetEdge = { ...edge, sourceHandle, targetHandle }\n this.edges.set(edgeId, updated)\n changes.push({ type: \"replace\", id: edgeId, item: updated })\n }\n if (changes.length === 0) return\n this.bumpEdges()\n this.requestRender()\n this.emitEdgeChanges(changes)\n }\n\n // --- drag / selection state ----------------------------------------------\n\n isNodeDragging = (): boolean => this.nodeDragging\n\n setNodeDragging = (dragging: boolean): void => {\n this.nodeDragging = dragging\n // Backstop: a gesture that ends without committing every mover (or at all)\n // must not leave nodes marked as dragging for `\"live\"` rendering.\n if (!dragging) this.draggingNodeIds.clear()\n }\n\n isNodeResizing = (): boolean => this.nodeResizing\n\n setGestureHandlers = (handlers: GestureHandlers): void => {\n this.gestureStartHandler = handlers.start ?? null\n this.gestureEndHandler = handlers.end ?? null\n this.lockConflictHandler = handlers.conflict ?? null\n }\n\n setLockedNodes = (locks: Record<NodeId, string> | undefined): void => {\n const opened = this.locks.setLocks(locks)\n if (opened.length === 0 || this.heldNodeIds.size === 0) return\n // A lock that lands on a node this client is already holding is the case\n // the gesture guard can't decide on its own: both clients started before\n // either lock arrived, so neither is obviously stale. Report it and leave\n // the gesture running — the consumer's transport knows who lost.\n const held = [...this.heldNodeIds]\n for (const nodeId of opened) {\n if (!this.heldNodeIds.has(nodeId)) continue\n const holderId = this.locks.getHolder(nodeId)\n if (holderId) this.lockConflictHandler?.({ nodeId, holderId, ids: held })\n }\n }\n\n isNodeHeld = (id: NodeId): boolean => this.heldNodeIds.has(id)\n\n getHeldNodeIds = (): ReadonlySet<NodeId> => this.heldNodeIds\n\n beginNodeGesture = (id: NodeId, ids: NodeId[] = [id]): void => {\n const opened = ids.filter((nodeId) => !this.heldNodeIds.has(nodeId))\n if (opened.length === 0) return\n for (const nodeId of opened) this.heldNodeIds.add(nodeId)\n this.gestureStartHandler?.({ id, ids: [...ids] })\n this.notifyHeld()\n }\n\n endNodeGesture = (id: NodeId, ids: NodeId[] = [id]): void => {\n const closed = ids.filter((nodeId) => this.heldNodeIds.delete(nodeId))\n if (closed.length === 0) return\n this.gestureEndHandler?.({ id, ids: [...ids] })\n this.notifyHeld()\n }\n\n subscribeHeldNodes = (listener: () => void): (() => void) => {\n this.heldListeners.add(listener)\n return () => {\n this.heldListeners.delete(listener)\n }\n }\n\n selectNode = (id: NodeId | null, additive = false): void => {\n // Any click-driven or programmatic (re)selection dismisses the marquee's\n // box; the marquee re-activates it after its own selectNodes calls.\n this.setSelectionBoxActive(false)\n if (id === null) {\n this.applyNodeSelection(new Set())\n this.notifySelection()\n return\n }\n let target: Set<NodeId>\n if (additive) {\n target = new Set(this.selectedNodeIds)\n if (target.has(id)) target.delete(id)\n else target.add(id)\n } else {\n target = new Set([id])\n }\n this.applyNodeSelection(target)\n this.setEdgeSelection(null)\n this.notifySelection()\n }\n\n selectNodes = (ids: NodeId[], additive = false): void => {\n this.setSelectionBoxActive(false)\n const target = additive ? new Set(this.selectedNodeIds) : new Set<NodeId>()\n for (const id of ids) target.add(id)\n this.applyNodeSelection(target)\n if (target.size > 0) this.setEdgeSelection(null)\n this.notifySelection()\n }\n\n getSelectedNodes = (): NodeId[] => [...this.selectedNodeIds]\n\n isNodeSelected = (id: NodeId): boolean => this.selectedNodeIds.has(id)\n\n getSelection = (): RivetSelection => this.buildSelection()\n\n subscribeSelection = (listener: (selection: RivetSelection) => void): (() => void) => {\n this.selectionListeners.add(listener)\n return () => {\n this.selectionListeners.delete(listener)\n }\n }\n\n setSelectionBoxActive = (active: boolean): void => {\n if (this.selectionBoxActive === active) return\n this.selectionBoxActive = active\n this.bumpSelectionBox()\n }\n\n isSelectionBoxActive = (): boolean => this.selectionBoxActive\n\n getSelectionBoxVersion = (): number => this.selectionBoxVersion\n\n subscribeSelectionBox = (listener: () => void): (() => void) => {\n this.selectionBoxListeners.add(listener)\n return () => {\n this.selectionBoxListeners.delete(listener)\n }\n }\n\n hoverNode = (id: NodeId | null): void => {\n this.setNodeHover(id)\n }\n\n getFocusedNode = (): NodeId | null => this.focusedNodeId\n\n setFocusedNode = (id: NodeId | null): void => {\n if (id !== null && !this.nodes.has(id)) return\n if (this.focusedNodeId === id) return\n this.focusedNodeId = id\n for (const listener of this.focusListeners) listener(id)\n }\n\n subscribeFocus = (listener: (id: NodeId | null) => void): (() => void) => {\n this.focusListeners.add(listener)\n return () => {\n this.focusListeners.delete(listener)\n }\n }\n\n // --- edges ---------------------------------------------------------------\n\n selectEdge = (id: EdgeId | null): void => {\n this.setSelectionBoxActive(false)\n this.setEdgeSelection(id)\n this.applyNodeSelection(new Set())\n this.notifySelection()\n }\n\n addEdge = (edge: RivetEdge): void => {\n if (this.edges.has(edge.id)) return\n this.edges.set(edge.id, edge)\n this.bumpEdges()\n this.requestRender() // edges are canvas-only, no React re-render\n this.emitEdgeChanges([{ type: \"add\", item: edge }])\n }\n\n replaceEdge = (id: EdgeId, edge: RivetEdge): void => {\n if (!this.edges.has(id)) return\n this.edges.set(id, edge)\n if (this.selectedEdgeId === id && !edge.selected) this.selectedEdgeId = null\n this.bumpEdges()\n this.requestRender()\n this.emitEdgeChanges([{ type: \"replace\", id, item: edge }])\n }\n\n reconnectEdge = (id: EdgeId, connection: Connection): void => {\n const edge = this.edges.get(id)\n if (!edge) return\n const updated: RivetEdge = {\n ...edge,\n source: connection.source,\n target: connection.target,\n sourceHandle: connection.sourceHandle ?? undefined,\n targetHandle: connection.targetHandle ?? undefined,\n }\n this.edges.set(id, updated)\n this.bumpEdges()\n this.requestRender()\n this.emitEdgeChanges([{ type: \"replace\", id, item: updated }])\n }\n\n removeEdge = (id: EdgeId): void => {\n if (this.removeEdgeInternal(id)) {\n this.emitEdgeChanges([{ type: \"remove\", id }])\n this.requestRender()\n this.notifySelection()\n }\n }\n\n deleteSelection = (): boolean => {\n const removedNodes: NodeId[] = []\n const removedEdges: EdgeId[] = []\n // Hoist the id: removeEdgeInternal clears `selectedEdgeId` as a side effect,\n // so re-reading the field after it would push null into the change batch.\n const selectedEdge = this.selectedEdgeId\n if (selectedEdge && this.removeEdgeInternal(selectedEdge)) {\n removedEdges.push(selectedEdge)\n }\n if (this.selectedNodeIds.size > 0) {\n for (const id of [...this.selectedNodeIds]) {\n // A locked node can be in the selection even though a lock refuses\n // selection: it was selected first and the lock arrived after. Deleting\n // the rest of the selection around it is the least surprising outcome —\n // the alternative is refusing the whole keystroke over one node.\n if (!this.locks.allows(id, \"delete\")) continue\n if (this.removeNodeInternal(id, removedEdges)) removedNodes.push(id)\n }\n }\n const changed = removedNodes.length > 0 || removedEdges.length > 0\n if (changed) {\n this.setSelectionBoxActive(false)\n this.emitNodeChanges(removedNodes.map((id) => ({ type: \"remove\", id })))\n this.emitEdgeChanges(this.edgeRemoveChanges(removedEdges))\n this.requestRender()\n this.notifySelection()\n }\n return changed\n }\n\n // --- controlled mode -----------------------------------------------------\n\n setChangeHandlers = (handlers: ChangeHandlers): void => {\n this.nodeChangeHandler = handlers.nodes ?? null\n this.edgeChangeHandler = handlers.edges ?? null\n }\n\n reconcile = (nextNodes: RivetNode[], nextEdges: RivetEdge[]): void => {\n this.reconciling = true\n try {\n this.reconcileNodes(nextNodes)\n this.reconcileEdges(nextEdges)\n } finally {\n this.reconciling = false\n }\n // Reconcile mutates without emitting or recording, so the history baseline\n // must catch up — otherwise the next recorded step's undo also reverts the\n // prop-applied changes (e.g. a prop-added node deleted through the store\n // would undo to a graph without it).\n this.history.rebase()\n // World-cache invalidation is handled per-node by writeNode/deleteNode above.\n this.requestRender() // re-cull for added/removed nodes and repaint edges\n }\n\n applyRemote = ({ nodes = [], edges = [], origin = \"remote\" }: RemoteChanges): void => {\n // A live local gesture owns its nodes' geometry, so a remote write to it is\n // stale on arrival — the peer was looking at a box this client has already\n // moved. Drop those parts here, before anything else sees them, so the\n // applied batch and the re-emitted batch stay the same thing.\n const guarded = guardNodeChanges(nodes, this.isNodeHeld, (id) => this.nodes.get(id))\n if (guarded.length === 0 && edges.length === 0) return\n // Route through reconcile so remote batches land through exactly the same\n // code as controlled props — one set of bumping, culling and cache rules,\n // and no second apply path that can drift from it. Reconcile suppresses\n // emission and rebases history, which is what a remote batch wants anyway.\n const currentNodes = [...this.nodes.values()]\n const currentEdges = [...this.edges.values()]\n this.reconcile(applyNodeChanges(guarded, currentNodes), applyEdgeChanges(edges, currentEdges))\n // Replay the batch over the stored undo/redo steps too, so undoing past a\n // peer's edit reverts only this client's work and leaves theirs standing.\n this.history.rewrite((snapshot) => ({\n nodes: guarded.length > 0 ? applyNodeChanges(guarded, snapshot.nodes) : snapshot.nodes,\n edges: edges.length > 0 ? applyEdgeChanges(edges, snapshot.edges) : snapshot.edges,\n }))\n // Then hand the batch on with its origin intact: a controlled owner has to\n // see it to keep its own state in step, and the tag is what stops it being\n // sent straight back out.\n this.emit(guarded, this.nodeChangeHandler, false, origin)\n this.emit(edges, this.edgeChangeHandler, false, origin)\n }\n\n // --- undo / redo ---------------------------------------------------------\n\n /** Structural snapshot for history — no selection/hover/drag state. */\n private historySnapshot(): HistorySnapshot {\n const nodes = [...this.nodes.values()].map((node) => {\n const copy = { ...node, position: { ...node.position } }\n if (node.size) copy.size = { ...node.size }\n copy.selected = undefined\n copy.hovered = undefined\n copy.dragging = undefined\n return copy\n })\n const edges = [...this.edges.values()].map((edge) => {\n const copy = { ...edge }\n copy.selected = undefined\n return copy\n })\n return { nodes, edges }\n }\n\n /**\n * Restore a snapshot, emitting the diff so controlled consumers update. Emits\n * with `record: false` so the restore itself isn't re-recorded, and preserves\n * live selection/hover (undo shouldn't churn what's selected).\n */\n private applyHistorySnapshot(snap: HistorySnapshot): void {\n const nodeChanges: NodeChange[] = []\n const snapNodeIds = new Set(snap.nodes.map((node) => node.id))\n for (const id of [...this.nodes.keys()]) {\n if (!snapNodeIds.has(id)) {\n this.dropNodeState(id)\n nodeChanges.push({ type: \"remove\", id })\n }\n }\n for (const node of snap.nodes) {\n const existing = this.nodes.get(node.id)\n const merged = existing\n ? { ...node, selected: existing.selected, hovered: existing.hovered }\n : node\n if (!existing) {\n this.writeNode(node.id, merged)\n nodeChanges.push({ type: \"add\", item: merged })\n } else if (!nodeControlledEqual(existing, merged)) {\n this.writeNode(node.id, merged)\n this.bumpNode(node.id)\n nodeChanges.push({ type: \"replace\", id: node.id, item: merged })\n }\n }\n\n const edgeChanges: EdgeChange[] = []\n const snapEdgeIds = new Set(snap.edges.map((edge) => edge.id))\n for (const id of [...this.edges.keys()]) {\n if (!snapEdgeIds.has(id)) {\n this.edges.delete(id)\n edgeChanges.push({ type: \"remove\", id })\n }\n }\n for (const edge of snap.edges) {\n const existing = this.edges.get(edge.id)\n const merged = existing ? { ...edge, selected: existing.selected } : edge\n this.edges.set(edge.id, merged)\n edgeChanges.push(\n existing ? { type: \"replace\", id: edge.id, item: merged } : { type: \"add\", item: merged },\n )\n }\n if (this.selectedEdgeId && !this.edges.has(this.selectedEdgeId)) this.selectedEdgeId = null\n\n if (edgeChanges.length > 0) this.bumpEdges()\n this.emitNodeChanges(nodeChanges, false)\n this.emitEdgeChanges(edgeChanges, false)\n this.requestRender()\n }\n\n undo = (): boolean => this.history.undo((snap) => this.applyHistorySnapshot(snap))\n redo = (): boolean => this.history.redo((snap) => this.applyHistorySnapshot(snap))\n canUndo = (): boolean => this.history.canUndo()\n canRedo = (): boolean => this.history.canRedo()\n clearHistory = (): void => this.history.clear()\n subscribeHistory = (listener: () => void): (() => void) => this.history.subscribe(listener)\n\n // --- edge labels (renderer ↔ label layer) --------------------------------\n\n getEdgeLabelAnchors = (): Map<EdgeId, Vec2> => this.edgeLabelAnchors\n\n setEdgeLabelAnchors = (anchors: Map<EdgeId, Vec2>): void => {\n this.edgeLabelAnchors = anchors\n }\n\n getAlignmentGuides = (): AlignmentGuide[] => this.alignmentGuides\n\n setAlignmentGuides = (guides: AlignmentGuide[]): void => {\n this.alignmentGuides = guides\n this.requestRender()\n }\n\n // --- handle registry -----------------------------------------------------\n\n registerHandle = (record: HandleRecord): void => {\n this.handles.set(handleKey(record.nodeId, record.handleId), record)\n this.requestRender()\n }\n\n unregisterHandle = (nodeId: NodeId, handleId: string): void => {\n this.handles.delete(handleKey(nodeId, handleId))\n this.requestRender()\n }\n\n // --- anchor registry -----------------------------------------------------\n\n /**\n * Measure one anchor against its node element. Returns true when geometry\n * changed beyond tolerance. Bails — keeping the last-known geometry — while\n * the element or node box can't produce a meaningful measurement (detached,\n * display:none, node not yet laid out).\n */\n private measureAnchor(key: string): boolean {\n const record = this.anchors.get(key)\n if (!record?.element?.isConnected) return false\n const element = record.element\n const nodeEl = this.nodeElements.get(record.nodeId)\n if (!nodeEl) return false\n const root = nodeEl.getBoundingClientRect()\n const box = element.getBoundingClientRect()\n if (root.width <= 0 || root.height <= 0 || (box.width <= 0 && box.height <= 0)) return false\n const rects = element.getClientRects()\n const first = rects.item(0) ?? box\n const last = rects.item(rects.length - 1) ?? first\n const geometry = computeAnchorGeometry(root, first, last, box)\n if (anchorGeometryEqual(record.geometry, geometry)) return false\n this.anchors.set(key, { ...record, geometry })\n return true\n }\n\n registerAnchor = (\n nodeId: NodeId,\n anchorId: string,\n element: Element,\n options?: AnchorRegistrationOptions,\n ): void => {\n const key = handleKey(nodeId, anchorId)\n const prev = this.anchors.get(key)\n this.anchors.set(key, {\n nodeId,\n anchorId,\n color: options?.color ?? prev?.color,\n strays: options?.strays ?? prev?.strays,\n element,\n // Keep the last-known geometry until the next successful measurement, so\n // a re-bind (display remount, editor DOM swap) never blanks the chrome.\n geometry: prev?.geometry ?? null,\n })\n this.measureAnchor(key)\n this.bumpAnchors(nodeId)\n this.requestRender()\n }\n\n detachAnchor = (nodeId: NodeId, anchorId: string): void => {\n const key = handleKey(nodeId, anchorId)\n const record = this.anchors.get(key)\n if (!record || record.element === null) return\n this.anchors.set(key, { ...record, element: null })\n this.bumpAnchors(nodeId)\n }\n\n unregisterAnchor = (nodeId: NodeId, anchorId: string): void => {\n if (!this.anchors.delete(handleKey(nodeId, anchorId))) return\n this.bumpAnchors(nodeId)\n this.requestRender()\n }\n\n remeasureAnchors = (nodeId: NodeId): void => {\n let changed = false\n for (const [key, record] of this.anchors) {\n if (record.nodeId === nodeId && this.measureAnchor(key)) changed = true\n }\n if (changed) {\n this.bumpAnchors(nodeId)\n this.requestRender()\n }\n }\n\n getNodeAnchors = (nodeId: NodeId): AnchorRecord[] => {\n const records: AnchorRecord[] = []\n for (const record of this.anchors.values()) {\n if (record.nodeId === nodeId) records.push(record)\n }\n return records\n }\n\n getNodeAnchorsVersion = (nodeId: NodeId): number => this.anchorVersions.get(nodeId) ?? 0\n\n subscribeNodeAnchors = (nodeId: NodeId, listener: () => void): (() => void) => {\n let set = this.anchorListeners.get(nodeId)\n if (!set) {\n set = new Set()\n this.anchorListeners.set(nodeId, set)\n }\n set.add(listener)\n return () => {\n set.delete(listener)\n if (set.size === 0) this.anchorListeners.delete(nodeId)\n }\n }\n\n getEdgesVersion = (): number => this.edgesVersion\n\n subscribeEdges = (listener: () => void): (() => void) => {\n this.edgesListeners.add(listener)\n return () => {\n this.edgesListeners.delete(listener)\n }\n }\n\n // --- in-progress connection ----------------------------------------------\n\n getPending = (): PendingConnection | null => this.pending\n\n beginConnection = (next: PendingConnection): void => {\n this.pending = next\n this.requestRender()\n }\n\n updateConnection = (to: Vec2, toPosition?: HandlePosition): void => {\n if (!this.pending) return\n this.pending = { ...this.pending, to, toPosition }\n this.requestRender()\n }\n\n endConnection = (): void => {\n if (!this.pending) return\n this.pending = null\n this.requestRender()\n }\n\n // --- render loop hook ----------------------------------------------------\n\n requestRender = (): void => {\n this.renderRequester()\n }\n\n bindRenderRequester = (fn: () => void): void => {\n this.renderRequester = fn\n }\n\n requestCursorRender = (): void => {\n if (this.cursorRenderRequester) this.cursorRenderRequester()\n else this.renderRequester()\n }\n\n bindCursorRenderRequester = (fn: (() => void) | null): void => {\n this.cursorRenderRequester = fn\n }\n\n // --- reconnect gateway (runtime-bound; consulted by <Handle>) ------------\n\n private reconnectDelegate: ReconnectDelegate | null = null\n\n getSelectedEdge = (): EdgeId | null => this.selectedEdgeId\n\n bindReconnectDelegate = (delegate: ReconnectDelegate | null): void => {\n this.reconnectDelegate = delegate\n }\n\n getReconnectDelegate = (): ReconnectDelegate | null => this.reconnectDelegate\n}\n\n/** Create a graph store. The public entry point; the class is an implementation detail. */\nexport function createRivetStore(init: RivetStoreInit): RivetStore {\n return new RivetGraphStore(init)\n}\n","import type { RefObject } from \"react\"\nimport { SELECTOR } from \"./constants\"\nimport type { RivetStore } from \"./store\"\nimport { handleKey } from \"./store\"\nimport type { Connection, HandlePosition, HandleType, NodeId, Vec2 } from \"./types\"\nimport { screenToWorld } from \"./viewport\"\n\n/** A resolved handle the pointer is over (or nearest on a hovered node). */\nexport type HandleHit = { nodeId: NodeId; handleId: string; type: HandleType }\n\n/** The fixed end a connection (or reconnection) is dragging from. */\nexport type ConnectionEnd = { nodeId: NodeId; handleId: string; type: HandleType }\n\n/** Convert a client (page) point to world coordinates via the pane rect + viewport. */\nexport function clientToWorld(\n store: RivetStore,\n paneRef: RefObject<HTMLElement | null>,\n clientX: number,\n clientY: number,\n): Vec2 {\n const rect = paneRef.current?.getBoundingClientRect()\n const point = { x: clientX - (rect?.left ?? 0), y: clientY - (rect?.top ?? 0) }\n return screenToWorld(point, store.getViewport())\n}\n\n/**\n * A pair is valid when one end can source and the other can target (\"either\" does\n * both). `from` is the end being dragged; `hit` is the candidate it may attach to.\n */\nexport function isCompatible(from: ConnectionEnd, hit: HandleHit): boolean {\n const canSource = from.type !== \"target\"\n const canTarget = from.type !== \"source\"\n return (\n hit.nodeId !== from.nodeId &&\n ((canSource && hit.type !== \"source\") || (canTarget && hit.type !== \"target\"))\n )\n}\n\n/** Resolve the handle element under a screen point via the DOM. */\nexport function findHandleAt(clientX: number, clientY: number): HandleHit | null {\n const element = document.elementFromPoint(clientX, clientY)\n const handleEl = element instanceof Element ? element.closest<HTMLElement>(SELECTOR.handle) : null\n if (!handleEl) return null\n const { rivetHandleNode, rivetHandleId, rivetHandleType } = handleEl.dataset\n if (!rivetHandleNode || !rivetHandleId || !rivetHandleType) return null\n return {\n nodeId: rivetHandleNode,\n handleId: rivetHandleId,\n type: rivetHandleType as HandleType,\n }\n}\n\n/** World position of a handle by hit, or null if the node/handle is gone. */\nexport function handleWorldPosition(store: RivetStore, hit: HandleHit): Vec2 | null {\n const record = store.handles.get(handleKey(hit.nodeId, hit.handleId))\n const node = store.nodes.get(hit.nodeId)\n if (!record || !node) return null\n const origin = store.getNodeWorldPosition(hit.nodeId)\n return { x: origin.x + record.offset.x, y: origin.y + record.offset.y }\n}\n\n/** The side a handle sits on (for facing a snapped pending connection), or null. */\nexport function handleSide(store: RivetStore, hit: HandleHit): HandlePosition | null {\n return store.handles.get(handleKey(hit.nodeId, hit.handleId))?.position ?? null\n}\n\n/**\n * Resolve what the dragged end should snap to: a compatible handle directly under\n * the pointer, else — while over another node — that node's nearest compatible\n * handle. Returns null when nothing valid is under the pointer.\n */\nexport function resolveConnectionHit(\n store: RivetStore,\n paneRef: RefObject<HTMLElement | null>,\n from: ConnectionEnd,\n clientX: number,\n clientY: number,\n): HandleHit | null {\n const direct = findHandleAt(clientX, clientY)\n if (direct && isCompatible(from, direct)) return direct\n\n const el = document.elementFromPoint(clientX, clientY)\n const nodeEl = el instanceof Element ? el.closest<HTMLElement>(SELECTOR.node) : null\n const overNodeId = nodeEl?.dataset.rivetNode\n if (!overNodeId || overNodeId === from.nodeId) return null\n\n const world = clientToWorld(store, paneRef, clientX, clientY)\n let best: HandleHit | null = null\n let bestDist = Number.POSITIVE_INFINITY\n for (const record of store.handles.values()) {\n if (record.nodeId !== overNodeId) continue\n const candidate: HandleHit = {\n nodeId: record.nodeId,\n handleId: record.handleId,\n type: record.type,\n }\n if (!isCompatible(from, candidate)) continue\n const node = store.nodes.get(record.nodeId)\n if (!node) continue\n const origin = store.getNodeWorldPosition(record.nodeId)\n const dx = origin.x + record.offset.x - world.x\n const dy = origin.y + record.offset.y - world.y\n const dist = dx * dx + dy * dy\n if (dist < bestDist) {\n bestDist = dist\n best = candidate\n }\n }\n return best\n}\n\n/**\n * Orient an edge between the dragged end and the hit: whichever end can source\n * into the other becomes the source. Mirrors the rule in {@link isCompatible}.\n */\nexport function orientConnection(from: ConnectionEnd, hit: HandleHit): Connection {\n const canSource = from.type !== \"target\"\n const draggedAsSource = canSource && hit.type !== \"source\"\n return draggedAsSource\n ? {\n source: from.nodeId,\n sourceHandle: from.handleId,\n target: hit.nodeId,\n targetHandle: hit.handleId,\n }\n : {\n source: hit.nodeId,\n sourceHandle: hit.handleId,\n target: from.nodeId,\n targetHandle: from.handleId,\n }\n}\n","import type { RefObject } from \"react\"\nimport {\n type ConnectionEnd,\n clientToWorld,\n type HandleHit,\n handleSide,\n handleWorldPosition,\n orientConnection,\n resolveConnectionHit,\n} from \"../connection\"\nimport type { RivetStore } from \"../store\"\nimport type { Connection, PendingConnection } from \"../types\"\n\n/**\n * Resolve the target handle under a screen point. Defaults to the DOM hit-test\n * ({@link resolveConnectionHit}); injectable so a test can drive the gesture's\n * commit/veto logic without a real layout (jsdom can't `elementFromPoint`).\n */\nexport type ResolveHit = (\n store: RivetStore,\n paneRef: RefObject<HTMLElement | null>,\n from: ConnectionEnd,\n clientX: number,\n clientY: number,\n) => HandleHit | null\n\nexport type ConnectionDragConfig = {\n store: RivetStore\n paneRef: RefObject<HTMLElement | null>\n /** The fixed end the drag pivots from (source of a new edge, or an edge's kept end). */\n from: ConnectionEnd\n /** Payload that seeds the store's pending connection (the source seed, or the reconnect ends). */\n begin: PendingConnection\n /** Apply a valid dropped connection — add a fresh edge, or re-point an existing one. */\n commit: (connection: Connection) => void\n /** Veto a proposed connection on drop. Absent ⇒ every drop is valid. */\n validate?: (connection: Connection) => boolean\n /**\n * Rewrite a validated connection before it commits — normalize handle ids,\n * force direction conventions, redirect to a canonical handle. Returning\n * `null` cancels the drop. Runs after {@link validate} (which sees the raw\n * connection) and before {@link commit}.\n */\n map?: (connection: Connection) => Connection | null\n /** Runs once the drag ends — on drop, on a miss, and on cancel. */\n onEnd?: () => void\n /** Resolve the target under the pointer. Defaults to the DOM hit-test; injected in tests. */\n resolveHit?: ResolveHit\n}\n\n/**\n * Drive a connection drag to completion: seed the pending connection, follow the\n * cursor (snapping the preview to a compatible handle), and on release commit the\n * oriented connection when it lands on a valid target. Self-cleaning — it removes\n * its own `window` listeners on pointerup/pointercancel. One implementation backs\n * both starting a new connection from a `<Handle>` and reconnecting an edge's\n * endpoint; the two differ only in `begin`, `commit`, `validate`, and `onEnd`.\n */\nexport function startConnectionDrag(config: ConnectionDragConfig): void {\n const {\n store,\n paneRef,\n from,\n begin,\n commit,\n validate,\n map,\n onEnd,\n resolveHit: resolveHitInput = resolveConnectionHit,\n } = config\n\n // Connecting a locked node is allowed by default — a lock claims the node,\n // not the graph around it — so this only bites when a policy says otherwise.\n if (!store.locks.allows(from.nodeId, \"connect\")) {\n onEnd?.()\n return\n }\n\n // A refused target reads as no target at all, which is exactly right for both\n // readers: the preview stops snapping to it, and the drop finds nothing to\n // commit. One wrap covers the move and the release.\n const resolveHit: ResolveHit = (...args) => {\n const hit = resolveHitInput(...args)\n if (hit && !store.locks.allows(hit.nodeId, \"connect\")) return null\n return hit\n }\n\n store.beginConnection(begin)\n\n const onMove = (event: PointerEvent) => {\n const hit = resolveHit(store, paneRef, from, event.clientX, event.clientY)\n const snapped = hit && handleWorldPosition(store, hit)\n store.updateConnection(\n snapped ?? clientToWorld(store, paneRef, event.clientX, event.clientY),\n snapped && hit ? (handleSide(store, hit) ?? undefined) : undefined,\n )\n }\n\n const detach = () => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n window.removeEventListener(\"pointercancel\", onCancel)\n }\n\n const onUp = (event: PointerEvent) => {\n detach()\n // Escape cleared the pending connection mid-drag (see input/keyboard) —\n // the gesture was cancelled, so the release must not commit.\n if (!store.getPending()) {\n onEnd?.()\n return\n }\n const hit = resolveHit(store, paneRef, from, event.clientX, event.clientY)\n if (hit) {\n const connection = orientConnection(from, hit)\n if (!validate || validate(connection)) {\n const mapped = map ? map(connection) : connection\n if (mapped) commit(mapped)\n }\n }\n onEnd?.()\n store.endConnection()\n }\n\n // A cancelled pointer (interrupted touch, browser-stolen capture) aborts without\n // committing — but still tears down and clears the preview so no ghost edge lingers.\n const onCancel = () => {\n detach()\n onEnd?.()\n store.endConnection()\n }\n\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n window.addEventListener(\"pointercancel\", onCancel)\n}\n","import { createId } from \"@rivet/utils\"\nimport {\n type CSSProperties,\n type KeyboardEvent as ReactKeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useEffect,\n useRef,\n} from \"react\"\nimport {\n type ConnectionEnd,\n clientToWorld,\n type HandleHit,\n handleWorldPosition,\n isCompatible,\n orientConnection,\n} from \"../connection\"\nimport { useRivetContext, useRivetNodeContext } from \"../context\"\nimport { startConnectionDrag } from \"../input/connection-drag\"\nimport type { HandlePosition, HandleType, NodeId } from \"../types\"\n\nconst SIZE = 10\n\nconst positionStyles: Record<HandlePosition, CSSProperties> = {\n right: { right: 0, top: \"50%\", transform: \"translate(50%, -50%)\" },\n left: { left: 0, top: \"50%\", transform: \"translate(-50%, -50%)\" },\n top: { top: 0, left: \"50%\", transform: \"translate(-50%, -50%)\" },\n bottom: { bottom: 0, left: \"50%\", transform: \"translate(-50%, 50%)\" },\n}\n\nexport type HandleProps = {\n /**\n * Whether this handle is a connection `source` or `target`. Optional — an\n * untyped handle resolves to `\"either\"` and can start or receive a\n * connection; a pair is valid when one end can source and the other can\n * target. Set an explicit type to constrain direction.\n */\n type?: HandleType\n /**\n * Distinguishes multiple handles on a node. Defaults to the resolved\n * `position`, since each side of a node is unique. Set an explicit `id` when a\n * node has several handles sharing one side.\n */\n id?: string\n position?: HandlePosition\n className?: string\n style?: CSSProperties\n /**\n * Accessible name for the handle. Defaults to naming the handle and its node\n * (e.g. `\"right handle of node a\"`) so a keyboard user tabbing across the\n * graph can tell same-sided handles on different nodes apart.\n */\n ariaLabel?: string\n}\n\n/**\n * A connection point placed inside a node component. It measures its own\n * position within the node (so edges anchor precisely) and starts a\n * drag-to-connect gesture.\n */\nexport function Handle({\n type,\n id,\n position,\n className,\n style,\n ariaLabel,\n}: HandleProps): React.ReactElement {\n const { store, paneRef, isValidConnection, mapConnection, onConnect, announce } =\n useRivetContext()\n const { nodeId, wrapperRef } = useRivetNodeContext()\n const ref = useRef<HTMLDivElement>(null)\n // Type is optional; an untyped handle is \"either\" (source or target). It's keyed\n // by position when untyped so several handles on one node stay distinct.\n const resolvedType: HandleType = type ?? \"either\"\n const place = position ?? (resolvedType === \"target\" ? \"left\" : \"right\")\n // Default to position, not type: a node commonly has several same-typed (or\n // untyped \"either\") handles, one per side, so keying by type collides them all\n // onto one registry entry. Position keeps each side distinct.\n const handleId = id ?? place\n\n // Measure and register the handle's world-space offset within its node.\n // getBoundingClientRect is post-transform, so divide by zoom to get world units.\n useEffect(() => {\n const el = ref.current\n const wrapper = wrapperRef.current\n if (!el || !wrapper) return\n\n const measure = () => {\n const zoom = store.getViewport().zoom || 1\n const hr = el.getBoundingClientRect()\n const wr = wrapper.getBoundingClientRect()\n store.registerHandle({\n nodeId,\n handleId,\n type: resolvedType,\n position: place,\n offset: {\n x: (hr.left + hr.width / 2 - wr.left) / zoom,\n y: (hr.top + hr.height / 2 - wr.top) / zoom,\n },\n })\n }\n\n measure()\n const observer = new ResizeObserver(measure)\n observer.observe(wrapper)\n observer.observe(el)\n return () => {\n observer.disconnect()\n store.unregisterHandle(nodeId, handleId)\n }\n }, [store, wrapperRef, nodeId, handleId, resolvedType, place])\n\n const nodeName = (id: NodeId) => store.nodes.get(id)?.ariaLabel ?? `node ${id}`\n\n // Keyboard connect: Enter/Space on a handle starts a pending connection from\n // it; Enter/Space on a compatible handle of another node completes the edge\n // (same validate → map → commit pipeline as the pointer drag); Enter on the\n // origin handle — or Escape anywhere — cancels.\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\") {\n if (!store.getPending()) return\n event.preventDefault()\n event.stopPropagation() // handled — the node wrapper must not also clear selection\n store.endConnection()\n announce(\"Connection cancelled.\")\n return\n }\n if (event.key !== \"Enter\" && event.key !== \" \") return\n event.preventDefault()\n\n const self: HandleHit = { nodeId, handleId, type: resolvedType }\n // Same refusal the pointer drag applies at both ends, and for the same\n // reason: only a consumer policy ever turns this on.\n if (!store.locks.allows(nodeId, \"connect\")) {\n announce(`${nodeName(nodeId)} is locked by someone else.`)\n return\n }\n const pending = store.getPending()\n if (!pending) {\n const origin = handleWorldPosition(store, self)\n if (!origin) return\n store.beginConnection({\n source: nodeId,\n sourceHandle: handleId,\n sourceType: resolvedType,\n from: origin,\n to: origin,\n })\n announce(\n `Connection started from ${nodeName(nodeId)}. Move focus to a handle on another node and press Enter to connect, or press Escape to cancel.`,\n )\n return\n }\n if (pending.source === nodeId && pending.sourceHandle === handleId) {\n store.endConnection()\n announce(\"Connection cancelled.\")\n return\n }\n\n const from: ConnectionEnd = {\n nodeId: pending.source,\n handleId: pending.sourceHandle,\n type: pending.sourceType,\n }\n // Invalid targets keep the pending connection alive so the user can move\n // on to another handle; only success, cancel, or a consumer veto end it.\n if (!isCompatible(from, self)) {\n announce(\"These handles cannot be connected.\")\n return\n }\n const connection = orientConnection(from, self)\n if (isValidConnection && !isValidConnection(connection)) {\n announce(\"Connection rejected.\")\n return\n }\n const mapped = mapConnection ? mapConnection(connection) : connection\n if (mapped) {\n store.addEdge({\n id: createId(\"edge\"),\n source: mapped.source,\n target: mapped.target,\n sourceHandle: mapped.sourceHandle ?? undefined,\n targetHandle: mapped.targetHandle ?? undefined,\n })\n onConnect?.(mapped)\n announce(`Connected ${nodeName(mapped.source)} to ${nodeName(mapped.target)}.`)\n }\n store.endConnection()\n }\n\n // While a connection is pending, focusing a handle previews the edge landing\n // on it — the keyboard analogue of the pointer drag's snap-to-handle.\n const onFocus = () => {\n const pending = store.getPending()\n if (!pending || (pending.source === nodeId && pending.sourceHandle === handleId)) return\n // Don't preview an edge landing where Enter would be refused.\n if (!store.locks.allows(nodeId, \"connect\")) return\n const world = handleWorldPosition(store, { nodeId, handleId, type: resolvedType })\n if (world) store.updateConnection(world, place)\n }\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n // Don't let this start a node drag (React-to-React stopPropagation works).\n event.stopPropagation()\n event.preventDefault()\n\n // A reconnectable edge ending here wins over starting a new connection —\n // the handle's DOM otherwise shadows the endpoint's grab zone entirely.\n // Alt forces a new connection from an occupied handle.\n if (!event.altKey) {\n const delegate = store.getReconnectDelegate()\n const endpointHit = delegate?.pickEndpoint(event.clientX, event.clientY)\n if (delegate && endpointHit) {\n delegate.begin(endpointHit.edgeId, endpointHit.end)\n return\n }\n }\n\n const from: ConnectionEnd = { nodeId, handleId, type: resolvedType }\n const start = handleWorldPosition(store, from)\n const origin = start ?? clientToWorld(store, paneRef, event.clientX, event.clientY)\n startConnectionDrag({\n store,\n paneRef,\n from,\n begin: {\n source: nodeId,\n sourceHandle: handleId,\n sourceType: resolvedType,\n from: origin,\n to: origin,\n },\n validate: isValidConnection,\n map: mapConnection,\n commit: (connection) => {\n store.addEdge({\n id: createId(\"edge\"),\n source: connection.source,\n target: connection.target,\n sourceHandle: connection.sourceHandle ?? undefined,\n targetHandle: connection.targetHandle ?? undefined,\n })\n onConnect?.(connection)\n },\n })\n }\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: the handle doubles as a drag affordance and measurement target, so it can't be a native <button>\n <div\n ref={ref}\n className={className}\n tabIndex={0}\n role=\"button\"\n aria-roledescription=\"connection handle\"\n aria-label={ariaLabel ?? `${handleId} handle of ${nodeName(nodeId)}`}\n onPointerDown={onPointerDown}\n onKeyDown={onKeyDown}\n onFocus={onFocus}\n data-rivet-handle=\"\"\n data-rivet-handle-node={nodeId}\n data-rivet-handle-id={handleId}\n data-rivet-handle-type={resolvedType}\n style={{\n position: \"absolute\",\n width: SIZE,\n height: SIZE,\n borderRadius: \"50%\",\n background: \"#ffffff\",\n border: \"1.5px solid #6366f1\",\n boxSizing: \"border-box\",\n pointerEvents: \"auto\",\n cursor: \"crosshair\",\n zIndex: 1,\n ...positionStyles[place],\n ...style,\n }}\n />\n )\n}\n","import type { CSSProperties } from \"react\"\nimport type { NodeProps } from \"../types\"\nimport { Handle } from \"./handle\"\n\nconst baseStyle: CSSProperties = {\n position: \"relative\",\n minWidth: 120,\n padding: \"10px 14px\",\n borderRadius: 8,\n // Longhand, not the `border` shorthand: the hover/selected styles below\n // override `borderColor` alone, and React warns when a shorthand and a\n // longhand for the same value are mixed across renders.\n borderWidth: 1,\n borderStyle: \"solid\",\n borderColor: \"rgba(100, 116, 139, 0.4)\",\n background: \"#ffffff\",\n color: \"#0f172a\",\n fontSize: 13,\n lineHeight: 1.3,\n boxShadow: \"0 1px 2px rgba(15, 23, 42, 0.08)\",\n}\n\nconst hoveredStyle: CSSProperties = {\n borderColor: \"rgba(99, 102, 241, 0.6)\",\n}\n\nconst selectedStyle: CSSProperties = {\n borderColor: \"#6366f1\",\n boxShadow: \"0 0 0 2px rgba(99, 102, 241, 0.35)\",\n}\n\n/** Fallback node used when a node's `type` has no entry in `nodeTypes`. */\nexport function DefaultNode({ data, selected, hovered }: NodeProps): React.ReactElement {\n const label = data && typeof data === \"object\" && \"label\" in data ? String(data.label) : \"Node\"\n // Selected wins over hover.\n const style = selected\n ? { ...baseStyle, ...selectedStyle }\n : hovered\n ? { ...baseStyle, ...hoveredStyle }\n : baseStyle\n return (\n <div style={style}>\n <Handle type=\"target\" position=\"left\" />\n {label}\n <Handle type=\"source\" position=\"right\" />\n </div>\n )\n}\n","import type { CSSProperties } from \"react\"\nimport type { NodeProps, NodeTypes } from \"../types\"\nimport { DefaultNode } from \"./default-node\"\n\nconst baseStyle: CSSProperties = {\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n // Keeps an unsized group visible; give real bounds via `width`/`height`.\n minWidth: 150,\n minHeight: 100,\n boxSizing: \"border-box\",\n borderRadius: 10,\n // Longhand — see the note in `default-node.tsx`.\n borderWidth: 1.5,\n borderStyle: \"dashed\",\n borderColor: \"rgba(100, 116, 139, 0.45)\",\n background: \"rgba(100, 116, 139, 0.06)\",\n}\n\nconst hoveredStyle: CSSProperties = {\n borderColor: \"rgba(99, 102, 241, 0.6)\",\n}\n\nconst selectedStyle: CSSProperties = {\n borderColor: \"#6366f1\",\n background: \"rgba(99, 102, 241, 0.08)\",\n}\n\nconst labelStyle: CSSProperties = {\n position: \"absolute\",\n top: 6,\n left: 10,\n fontSize: 11,\n fontWeight: 500,\n color: \"rgba(100, 116, 139, 0.9)\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n}\n\n/**\n * Built-in container node (`type: \"group\"`) — the visual basis for sub-flows.\n * A styled region with no content or handles of its own; children point at it\n * via `parentId` (and `extent: \"parent\"` to stay confined). Give it explicit\n * `width`/`height` — a group has no intrinsic content to measure. Children\n * render above it automatically (z-index follows nesting depth).\n */\nexport function GroupNode({ data, selected, hovered }: NodeProps): React.ReactElement {\n const label = data && typeof data === \"object\" && \"label\" in data ? String(data.label) : null\n // Selected wins over hover.\n const style = selected\n ? { ...baseStyle, ...selectedStyle }\n : hovered\n ? { ...baseStyle, ...hoveredStyle }\n : baseStyle\n return <div style={style}>{label !== null && <div style={labelStyle}>{label}</div>}</div>\n}\n\n/** The built-in node components, keyed by `type`. Consumer `nodeTypes` win. */\nexport const BUILTIN_NODE_TYPES: NodeTypes = {\n default: DefaultNode,\n group: GroupNode,\n}\n","import {\n type CSSProperties,\n type PointerEvent as ReactPointerEvent,\n useEffect,\n useRef,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport { visibleWorldRect } from \"../viewport\"\n\nconst MAP_PADDING = 8\n\nconst containerStyle: CSSProperties = {\n position: \"absolute\",\n bottom: 16,\n right: 16,\n borderRadius: 8,\n overflow: \"hidden\",\n border: \"1px solid rgba(100, 116, 139, 0.4)\",\n background: \"rgba(248, 250, 252, 0.9)\",\n boxShadow: \"0 1px 3px rgba(15, 23, 42, 0.12)\",\n cursor: \"pointer\",\n}\n\nexport type MiniMapProps = {\n width?: number\n height?: number\n nodeColor?: string\n selectedColor?: string\n /** Fill for the area outside the current viewport. */\n maskColor?: string\n className?: string\n style?: CSSProperties\n}\n\n/**\n * An overview of the whole graph with a viewport indicator. Redraws on every\n * canvas frame (via the store's frame channel) and recenters on click/drag.\n * Must be a child of `<Rivet>`.\n */\nexport function MiniMap({\n width = 200,\n height = 150,\n nodeColor = \"rgba(100, 116, 139, 0.7)\",\n selectedColor = \"#6366f1\",\n maskColor = \"rgba(15, 23, 42, 0.12)\",\n className,\n style,\n}: MiniMapProps): React.ReactElement {\n const { store, paneRef } = useRivetContext()\n const canvasRef = useRef<HTMLCanvasElement>(null)\n // Last frame's world→map transform, so pointer events can invert it.\n const transformRef = useRef({ scale: 1, offsetX: 0, offsetY: 0 })\n\n useEffect(() => {\n const canvas = canvasRef.current\n const ctx = canvas?.getContext(\"2d\")\n if (!canvas || !ctx) return\n\n const dpr = window.devicePixelRatio || 1\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n\n const draw = () => {\n const viewport = store.getViewport()\n const pane = paneRef.current\n const paneWidth = pane?.clientWidth ?? width\n const paneHeight = pane?.clientHeight ?? height\n const view = visibleWorldRect(viewport, paneWidth, paneHeight)\n\n // Fit the union of all node rects (world-space, parent chains resolved) and\n // the current viewport into the map.\n let minX = view.x\n let minY = view.y\n let maxX = view.x + view.width\n let maxY = view.y + view.height\n for (const id of store.nodes.keys()) {\n const box = store.getNodeRect(id)\n minX = Math.min(minX, box.x)\n minY = Math.min(minY, box.y)\n maxX = Math.max(maxX, box.x + box.width)\n maxY = Math.max(maxY, box.y + box.height)\n }\n\n const boundsWidth = maxX - minX || 1\n const boundsHeight = maxY - minY || 1\n const innerWidth = width - MAP_PADDING * 2\n const innerHeight = height - MAP_PADDING * 2\n const scale = Math.min(innerWidth / boundsWidth, innerHeight / boundsHeight)\n const offsetX = MAP_PADDING + (innerWidth - boundsWidth * scale) / 2 - minX * scale\n const offsetY = MAP_PADDING + (innerHeight - boundsHeight * scale) / 2 - minY * scale\n transformRef.current = { scale, offsetX, offsetY }\n\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n ctx.clearRect(0, 0, width, height)\n\n // Nodes.\n for (const node of store.nodes.values()) {\n const box = store.getNodeRect(node.id)\n ctx.fillStyle = node.selected ? selectedColor : nodeColor\n ctx.fillRect(\n box.x * scale + offsetX,\n box.y * scale + offsetY,\n Math.max(1, box.width * scale),\n Math.max(1, box.height * scale),\n )\n }\n\n // Viewport indicator: mask everything outside the visible rect.\n const vx = view.x * scale + offsetX\n const vy = view.y * scale + offsetY\n const vw = view.width * scale\n const vh = view.height * scale\n ctx.fillStyle = maskColor\n ctx.beginPath()\n ctx.rect(0, 0, width, height)\n ctx.rect(vx, vy, vw, vh)\n ctx.fill(\"evenodd\")\n ctx.strokeStyle = \"rgba(99, 102, 241, 0.9)\"\n ctx.lineWidth = 1\n ctx.strokeRect(vx, vy, vw, vh)\n }\n\n draw()\n return store.subscribeFrame(draw)\n }, [store, paneRef, width, height, nodeColor, selectedColor, maskColor])\n\n // Recenter the viewport on the clicked/dragged world point.\n const recenter = (event: ReactPointerEvent<HTMLCanvasElement>) => {\n const canvas = canvasRef.current\n const pane = paneRef.current\n if (!canvas || !pane) return\n const rect = canvas.getBoundingClientRect()\n const { scale, offsetX, offsetY } = transformRef.current\n const worldX = (event.clientX - rect.left - offsetX) / scale\n const worldY = (event.clientY - rect.top - offsetY) / scale\n const viewport = store.getViewport()\n store.setViewport({\n zoom: viewport.zoom,\n x: pane.clientWidth / 2 - worldX * viewport.zoom,\n y: pane.clientHeight / 2 - worldY * viewport.zoom,\n })\n store.requestRender()\n }\n\n const onPointerDown = (event: ReactPointerEvent<HTMLCanvasElement>) => {\n if (event.button !== 0) return\n event.currentTarget.setPointerCapture(event.pointerId)\n recenter(event)\n }\n const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {\n if (event.buttons & 1) recenter(event)\n }\n\n return (\n <div className={className} style={{ ...containerStyle, ...style, width, height }}>\n <canvas\n ref={canvasRef}\n style={{ width, height, display: \"block\" }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n />\n </div>\n )\n}\n","import { clamp } from \"@rivet/utils\"\nimport {\n type CSSProperties,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useSyncExternalStore,\n} from \"react\"\nimport { useRivetContext, useRivetNodeContext } from \"../context\"\nimport type { Size, Vec2 } from \"../types\"\n\n/** Which edges a resize handle moves. */\ntype HandleDir = {\n key: string\n left?: boolean\n right?: boolean\n top?: boolean\n bottom?: boolean\n style: CSSProperties\n cursor: string\n}\n\nconst NS = \"ns-resize\"\nconst EW = \"ew-resize\"\nconst NWSE = \"nwse-resize\"\nconst NESW = \"nesw-resize\"\n\nconst HANDLES: HandleDir[] = [\n { key: \"nw\", top: true, left: true, style: { top: 0, left: 0 }, cursor: NWSE },\n { key: \"n\", top: true, style: { top: 0, left: \"50%\" }, cursor: NS },\n { key: \"ne\", top: true, right: true, style: { top: 0, left: \"100%\" }, cursor: NESW },\n { key: \"e\", right: true, style: { top: \"50%\", left: \"100%\" }, cursor: EW },\n { key: \"se\", bottom: true, right: true, style: { top: \"100%\", left: \"100%\" }, cursor: NWSE },\n { key: \"s\", bottom: true, style: { top: \"100%\", left: \"50%\" }, cursor: NS },\n { key: \"sw\", bottom: true, left: true, style: { top: \"100%\", left: 0 }, cursor: NESW },\n { key: \"w\", left: true, style: { top: \"50%\", left: 0 }, cursor: EW },\n]\n\nexport type NodeResizerProps = {\n minWidth?: number\n minHeight?: number\n maxWidth?: number\n maxHeight?: number\n /** Lock the width/height ratio while resizing from a corner. */\n keepAspectRatio?: boolean\n /** Handle color. */\n color?: string\n /** Called on every resize step (live). */\n onResize?: (size: Size, position: Vec2) => void\n /** Called once when the resize gesture ends. */\n onResizeEnd?: (size: Size, position: Vec2) => void\n}\n\nconst dotStyle = (color: string): CSSProperties => ({\n position: \"absolute\",\n width: 8,\n height: 8,\n background: \"#ffffff\",\n border: `1.5px solid ${color}`,\n borderRadius: 2,\n boxSizing: \"border-box\",\n pointerEvents: \"auto\",\n zIndex: 2,\n})\n\n/**\n * Drop inside a node component to make it resizable. Renders eight drag handles\n * that write the node's explicit `width`/`height` (and move its origin for\n * top/left handles) via {@link RivetStore.resizeNode} — so it works with\n * controlled mode (emits dimension changes) and nested nodes alike.\n */\nexport function NodeResizer({\n minWidth = 20,\n minHeight = 20,\n maxWidth = Number.POSITIVE_INFINITY,\n maxHeight = Number.POSITIVE_INFINITY,\n keepAspectRatio = false,\n color = \"#6366f1\",\n onResize,\n onResizeEnd,\n}: NodeResizerProps): React.ReactElement | null {\n const { store } = useRivetContext()\n const { nodeId } = useRivetNodeContext()\n // A peer's lock hides the handles outright rather than letting them be\n // pressed and refused — a resize dot you can't pull is worse than no dot.\n const resizable = useSyncExternalStore(\n store.locks.subscribe,\n useCallback(() => store.locks.allows(nodeId, \"resize\"), [store, nodeId]),\n useCallback(() => store.locks.allows(nodeId, \"resize\"), [store, nodeId]),\n )\n\n const startResize = (dir: HandleDir) => (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n // Don't let this bubble into the node's own drag gesture.\n event.stopPropagation()\n event.preventDefault()\n\n const node = store.nodes.get(nodeId)\n if (!node) return\n const zoom = store.getViewport().zoom || 1\n const startW = node.width ?? node.size?.width ?? 0\n const startH = node.height ?? node.size?.height ?? 0\n const start = node.position\n const startX = event.clientX\n const startY = event.clientY\n const ratio = startH > 0 ? startW / startH : 1\n const isCorner = (dir.left || dir.right) && (dir.top || dir.bottom)\n\n const compute = (moveEvent: PointerEvent): { size: Size; position: Vec2 } => {\n const dx = (moveEvent.clientX - startX) / zoom\n const dy = (moveEvent.clientY - startY) / zoom\n let width = startW + (dir.right ? dx : dir.left ? -dx : 0)\n let height = startH + (dir.bottom ? dy : dir.top ? -dy : 0)\n width = clamp(width, minWidth, maxWidth)\n height = clamp(height, minHeight, maxHeight)\n if (keepAspectRatio && isCorner) {\n height = clamp(width / ratio, minHeight, maxHeight)\n width = height * ratio\n }\n // Left/top handles keep the opposite edge fixed by shifting the origin.\n const position = {\n x: dir.left ? start.x + (startW - width) : start.x,\n y: dir.top ? start.y + (startH - height) : start.y,\n }\n return { size: { width, height }, position }\n }\n\n // The gesture opens on the first move, not the press: a press that never\n // moves writes no geometry, and shouldn't churn a lock in a shared document.\n let started = false\n const onMove = (moveEvent: PointerEvent) => {\n if (!started) {\n started = true\n store.beginNodeGesture(nodeId)\n } else if (!store.isNodeHeld(nodeId)) {\n // Yielded to a peer mid-resize (`releaseNodeGesture` after a lock\n // conflict). Stop writing and let their box land; no commit.\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n return\n }\n const { size, position } = compute(moveEvent)\n const moved = dir.left || dir.top\n store.resizeNode(nodeId, size, moved ? position : undefined, false)\n onResize?.(size, position)\n }\n const onUp = (upEvent: PointerEvent) => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n if (started && !store.isNodeHeld(nodeId)) return\n const { size, position } = compute(upEvent)\n const moved = dir.left || dir.top\n store.resizeNode(nodeId, size, moved ? position : undefined, true)\n // Released after the commit, so the final size wins over anything that\n // arrived mid-gesture (see `endNodeGesture`).\n if (started) store.endNodeGesture(nodeId)\n onResizeEnd?.(size, position)\n }\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n }\n\n if (!resizable) return null\n\n return (\n <>\n {HANDLES.map((dir) => (\n <div\n key={dir.key}\n data-rivet-resize-handle={dir.key}\n onPointerDown={startResize(dir)}\n style={{\n ...dotStyle(color),\n ...dir.style,\n transform: \"translate(-50%, -50%)\",\n cursor: dir.cursor,\n }}\n />\n ))}\n </>\n )\n}\n","/**\n * The outbound half of presence: what this client tells everyone else.\n *\n * It publishes a *snapshot*, never an event stream. A snapshot is idempotent —\n * a dropped one costs nothing, a duplicate costs nothing, and a client that\n * reconnects mid-session is immediately correct rather than replaying history.\n * That's also how presence channels themselves model state, so this maps onto\n * any transport without a translation layer.\n *\n * Cursor movement is coalesced to `throttleMs`; selection and gesture changes\n * jump the queue, because they're the signals a peer acts on (a lock request\n * that waits 50ms is a lock request that can lose a race it should have won).\n */\n\nimport type { RivetStore } from \"../store\"\nimport type { NodeId, Vec2 } from \"../types\"\nimport { screenToWorld } from \"../viewport\"\n\n/** This client's presence, as handed to `onLocalPresence`. */\nexport type LocalPresence = {\n /**\n * Pointer position in **world** coordinates, or `null` when the pointer is\n * off the canvas. World, not screen: peers have their own viewports, and a\n * screen point means nothing on the other side.\n */\n cursor: Vec2 | null\n /** Currently selected node ids. */\n selection: NodeId[]\n /** Nodes under a live local gesture — the same set as `onNodeDragStart`. */\n holding: NodeId[]\n}\n\nexport type LocalPresenceParams = {\n store: RivetStore\n /** The graph pane; pointer position is read relative to it. */\n pane: HTMLElement\n /** Called with each snapshot, at most once per `throttleMs` for cursor moves. */\n emit: (presence: LocalPresence) => void\n throttleMs: number\n}\n\nconst sameIds = (a: NodeId[], b: NodeId[]): boolean =>\n a.length === b.length && a.every((id, i) => id === b[i])\n\nconst samePresence = (a: LocalPresence, b: LocalPresence): boolean =>\n a.cursor?.x === b.cursor?.x &&\n a.cursor?.y === b.cursor?.y &&\n sameIds(a.selection, b.selection) &&\n sameIds(a.holding, b.holding)\n\n/**\n * Track this client's presence and publish it. Returns a dispose function that\n * detaches every listener and cancels a pending emission.\n */\nexport function trackLocalPresence({\n store,\n pane,\n emit,\n throttleMs,\n}: LocalPresenceParams): () => void {\n let cursor: Vec2 | null = null\n /** Last pointer position in pane-relative px — re-projected when the viewport moves. */\n let screenPoint: Vec2 | null = null\n let last: LocalPresence | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n let lastEmit = Number.NEGATIVE_INFINITY\n\n const publish = () => {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n lastEmit = performance.now()\n const next: LocalPresence = {\n cursor,\n selection: store.getSelectedNodes(),\n holding: [...store.getHeldNodeIds()],\n }\n // Snapshots are idempotent, so an unchanged one is pure network noise.\n if (last && samePresence(last, next)) return\n last = next\n emit(next)\n }\n\n /** Coalesce to the throttle window, leading edge first, trailing edge kept. */\n const schedule = () => {\n if (timer !== null) return\n const wait = throttleMs - (performance.now() - lastEmit)\n if (wait <= 0) {\n publish()\n return\n }\n timer = setTimeout(() => {\n timer = null\n publish()\n }, wait)\n }\n\n const project = () => {\n if (!screenPoint) {\n cursor = null\n return\n }\n cursor = screenToWorld(screenPoint, store.getViewport())\n }\n\n const onPointerMove = (event: PointerEvent) => {\n const rect = pane.getBoundingClientRect()\n screenPoint = { x: event.clientX - rect.left, y: event.clientY - rect.top }\n project()\n schedule()\n }\n\n // Leaving the pane parks the cursor at once: a stale arrow sitting on the\n // canvas after someone tabbed away is worse than no arrow.\n const onPointerLeave = () => {\n screenPoint = null\n cursor = null\n publish()\n }\n\n // Panning or zooming with a still pointer moves it in world space, which is\n // the space peers see it in — so re-project rather than wait for a move.\n const unsubscribeViewport = store.subscribeViewport(() => {\n if (!screenPoint) return\n project()\n schedule()\n })\n\n // Selection and held nodes are low-frequency and act as signals; publish now.\n const unsubscribeSelection = store.subscribeSelection(() => publish())\n const unsubscribeHeld = store.subscribeHeldNodes(() => publish())\n\n pane.addEventListener(\"pointermove\", onPointerMove)\n pane.addEventListener(\"pointerleave\", onPointerLeave)\n\n return () => {\n if (timer !== null) clearTimeout(timer)\n pane.removeEventListener(\"pointermove\", onPointerMove)\n pane.removeEventListener(\"pointerleave\", onPointerLeave)\n unsubscribeViewport()\n unsubscribeSelection()\n unsubscribeHeld()\n }\n}\n","import { type RefObject, useEffect, useRef } from \"react\"\nimport { type LocalPresence, trackLocalPresence } from \"../presence/local\"\nimport type { RivetStore } from \"../store\"\n\nexport type UseLocalPresenceParams = {\n store: RivetStore\n paneRef: RefObject<HTMLDivElement | null>\n /** Absent = don't track at all; nothing is listening, so nothing is measured. */\n onLocalPresence: ((presence: LocalPresence) => void) | undefined\n throttleMs: number\n}\n\n/**\n * Publish this client's presence while `onLocalPresence` is set. The callback\n * is read through a ref so an inline handler doesn't re-attach the tracker\n * (and reset its throttle window) on every render — only appearing, going away,\n * or a changed throttle does that.\n */\nexport function useLocalPresence({\n store,\n paneRef,\n onLocalPresence,\n throttleMs,\n}: UseLocalPresenceParams): void {\n const handlerRef = useRef(onLocalPresence)\n handlerRef.current = onLocalPresence\n const enabled = Boolean(onLocalPresence)\n\n useEffect(() => {\n const pane = paneRef.current\n if (!enabled || !pane) return\n return trackLocalPresence({\n store,\n pane,\n emit: (presence) => handlerRef.current?.(presence),\n throttleMs,\n })\n }, [store, paneRef, enabled, throttleMs])\n}\n","import { type ReactNode, useMemo, useRef } from \"react\"\nimport {\n type AnchorOptions,\n DEFAULT_ANCHOR_OPTIONS,\n type ResolvedAnchorOptions,\n} from \"../anchor/registry\"\nimport {\n DEFAULT_PRESENCE_OPTIONS,\n type PresenceOptions,\n type ResolvedPresenceOptions,\n} from \"../presence/registry\"\nimport type {\n Connection,\n DefaultEdgeOptions,\n EdgeTypes,\n LaneChange,\n NodeTypes,\n SwimlaneHeaderProps,\n SwimlaneLabelProps,\n SwimlaneMargin,\n} from \"../types\"\n\n/** Object.is, or same-length arrays / same-key objects whose members are Object.is-equal. */\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return false\n const aArr = Array.isArray(a)\n if (aArr !== Array.isArray(b)) return false\n if (aArr) {\n const bArr = b as unknown[]\n if ((a as unknown[]).length !== bArr.length) return false\n return (a as unknown[]).every((v, i) => Object.is(v, bArr[i]))\n }\n const aKeys = Object.keys(a as object)\n const bObj = b as Record<string, unknown>\n if (aKeys.length !== Object.keys(bObj).length) return false\n return aKeys.every(\n (k) => Object.hasOwn(bObj, k) && Object.is((a as Record<string, unknown>)[k], bObj[k]),\n )\n}\n\n/**\n * Keep the previous reference when `value` is shallow-equal, so a consumer passing\n * a new-but-equal inline object/array each render doesn't change identity (and an\n * omitted prop's hoisted default stays stable).\n */\nfunction useShallowStable<T>(value: T): T {\n const ref = useRef(value)\n if (!shallowEqual(ref.current, value)) ref.current = value\n return ref.current\n}\n\n/**\n * A stable function that forwards to the latest `fn`, or `undefined` when `fn` is\n * absent. An inline handler never changes identity, while an unset prop still\n * reads as \"no handler\" (so default behavior is preserved). Identity only flips\n * when the prop appears or disappears.\n */\nfunction useStableOptional<A extends unknown[], R>(\n fn: ((...args: A) => R) | undefined,\n): ((...args: A) => R) | undefined {\n const ref = useRef(fn)\n ref.current = fn\n const stable = useRef<((...args: A) => R) | null>(null)\n if (stable.current === null) stable.current = (...args: A): R => ref.current?.(...args) as R\n return fn ? stable.current : undefined\n}\n\nexport type UseRivetConfigParams = {\n nodeTypes: NodeTypes\n edgeTypes: EdgeTypes | undefined\n defaultEdgeOptions: DefaultEdgeOptions | undefined\n snapGrid: [number, number] | undefined\n swimlaneMargin: number | SwimlaneMargin | undefined\n anchorOptions: AnchorOptions | undefined\n presenceOptions: PresenceOptions | undefined\n panOnDrag: boolean | number[]\n selectionKeyCode: string | string[] | null\n multiSelectionKeyCode: string | string[]\n isValidConnection: ((connection: Connection) => boolean) | undefined\n mapConnection: ((connection: Connection) => Connection | null) | undefined\n onConnect: ((connection: Connection) => void) | undefined\n onLaneChange: ((change: LaneChange) => void) | undefined\n renderSwimlaneHeader: ((props: SwimlaneHeaderProps) => ReactNode) | undefined\n renderSwimlaneLabel: ((props: SwimlaneLabelProps) => ReactNode) | undefined\n}\n\nexport type RivetConfig = {\n nodeTypes: NodeTypes\n edgeTypes: EdgeTypes | undefined\n defaultEdgeOptions: DefaultEdgeOptions | undefined\n snapGrid: [number, number] | null\n swimlaneMargin: number | SwimlaneMargin | undefined\n /** Anchor chrome placement policy, filled with defaults. */\n anchorOptions: ResolvedAnchorOptions\n /** Presence policy (outbound throttle, cursor painting), filled with defaults. */\n presenceOptions: ResolvedPresenceOptions\n /** `MouseEvent.button` codes that pan on drag, derived from `panOnDrag`. */\n panButtons: number[]\n /** Keys that force a marquee, derived from `selectionKeyCode`. */\n selectionKeys: string[]\n /** Keys that make selection additive, derived from `multiSelectionKeyCode`. */\n multiSelectionKeys: string[]\n isValidConnection: ((connection: Connection) => boolean) | undefined\n mapConnection: ((connection: Connection) => Connection | null) | undefined\n onConnect: ((connection: Connection) => void) | undefined\n onLaneChange: ((change: LaneChange) => void) | undefined\n renderSwimlaneHeader: ((props: SwimlaneHeaderProps) => ReactNode) | undefined\n renderSwimlaneLabel: ((props: SwimlaneLabelProps) => ReactNode) | undefined\n}\n\n/**\n * Resolve the identity-sensitive props once, to stable references — the inputs\n * that flow into the context memo and the render-loop effect's deps. Value props\n * are shallow-stabilized, key-code props are derived into their consumed shapes,\n * and callbacks become presence-preserving stable wrappers. So a consumer passing\n * inline objects/handlers can't churn the context or re-mount the render loop.\n */\nexport function useRivetConfig(params: UseRivetConfigParams): RivetConfig {\n const panOnDrag = useShallowStable(params.panOnDrag)\n const selectionKeyCode = useShallowStable(params.selectionKeyCode)\n const multiSelectionKeyCode = useShallowStable(params.multiSelectionKeyCode)\n\n const panButtons = useMemo<number[]>(\n () => (panOnDrag === true ? [0] : panOnDrag === false ? [] : panOnDrag),\n [panOnDrag],\n )\n const selectionKeys = useMemo<string[]>(\n () =>\n selectionKeyCode == null\n ? []\n : Array.isArray(selectionKeyCode)\n ? selectionKeyCode\n : [selectionKeyCode],\n [selectionKeyCode],\n )\n const multiSelectionKeys = useMemo<string[]>(\n () => (Array.isArray(multiSelectionKeyCode) ? multiSelectionKeyCode : [multiSelectionKeyCode]),\n [multiSelectionKeyCode],\n )\n\n const nodeTypes = useShallowStable(params.nodeTypes)\n const edgeTypes = useShallowStable(params.edgeTypes)\n const defaultEdgeOptions = useShallowStable(params.defaultEdgeOptions)\n const snapGrid = useShallowStable(params.snapGrid ?? null)\n const swimlaneMargin = useShallowStable(params.swimlaneMargin)\n const anchorOptionsInput = useShallowStable(params.anchorOptions)\n const anchorOptions = useMemo<ResolvedAnchorOptions>(\n () => ({ ...DEFAULT_ANCHOR_OPTIONS, ...anchorOptionsInput }),\n [anchorOptionsInput],\n )\n const presenceOptionsInput = useShallowStable(params.presenceOptions)\n const presenceOptions = useMemo<ResolvedPresenceOptions>(\n () => ({ ...DEFAULT_PRESENCE_OPTIONS, ...presenceOptionsInput }),\n [presenceOptionsInput],\n )\n const isValidConnection = useStableOptional(params.isValidConnection)\n const mapConnection = useStableOptional(params.mapConnection)\n const onConnect = useStableOptional(params.onConnect)\n const onLaneChange = useStableOptional(params.onLaneChange)\n const renderSwimlaneHeader = useStableOptional(params.renderSwimlaneHeader)\n const renderSwimlaneLabel = useStableOptional(params.renderSwimlaneLabel)\n\n return {\n nodeTypes,\n edgeTypes,\n defaultEdgeOptions,\n snapGrid,\n swimlaneMargin,\n anchorOptions,\n presenceOptions,\n panButtons,\n selectionKeys,\n multiSelectionKeys,\n isValidConnection,\n mapConnection,\n onConnect,\n onLaneChange,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n }\n}\n","import { snapToGrid } from \"../graph\"\nimport type { RivetStore } from \"../store\"\n\n/** World units a selected node nudges per arrow key (×{@link ARROW_STEP_SHIFT} with Shift). */\nexport const ARROW_STEP = 10\nexport const ARROW_STEP_SHIFT = 5\n/** Unit move vector per arrow key. */\nexport const ARROW_DIRS: Record<string, { x: number; y: number }> = {\n ArrowUp: { x: 0, y: -1 },\n ArrowDown: { x: 0, y: 1 },\n ArrowLeft: { x: -1, y: 0 },\n ArrowRight: { x: 1, y: 0 },\n}\n\n/**\n * Keyboard actions on the graph: Delete/Backspace removes the selection, Escape\n * dismisses the post-marquee selection box, arrow keys nudge the selected\n * node(s) (Shift = larger step). Bails when another handler\n * already claimed the key (`event.defaultPrevented` — an open menu/dialog, or any\n * consumer control) or when focus is in a text field.\n *\n * `getSnapGrid` is read at press time rather than captured, so toggling the\n * graph's `snapGrid` doesn't require re-installing the pane's listeners. With a\n * grid configured a press moves exactly one cell and lands on the grid, the\n * same contract as the grabbed-node arrow movement in `node-wrapper` — the two\n * arrow paths must not disagree about where a node ends up.\n */\nexport function createKeyboardHandler(\n store: RivetStore,\n getSnapGrid?: () => [number, number] | null,\n): (event: KeyboardEvent) => void {\n return (event) => {\n if (event.defaultPrevented) return\n const active = document.activeElement\n if (\n active instanceof HTMLElement &&\n (active.tagName === \"INPUT\" || active.tagName === \"TEXTAREA\" || active.isContentEditable)\n ) {\n return\n }\n\n if (event.key === \"Delete\" || event.key === \"Backspace\") {\n if (store.deleteSelection()) event.preventDefault()\n return\n }\n\n // Escape cancels an in-progress connection first (a keyboard-started one\n // has no drag gesture to tear it down), then dismisses the post-marquee\n // selection box (with its selection). Only those — a plain Escape on the\n // pane shouldn't clear a clicked node, which the focused node's own\n // handler already covers.\n if (event.key === \"Escape\") {\n if (store.getPending()) store.endConnection()\n else if (store.isSelectionBoxActive()) store.selectNode(null)\n return\n }\n\n const dir = ARROW_DIRS[event.key]\n if (!dir) return\n // A locked mover drops out of the nudge the same way it drops out of a\n // group drag: the rest of the selection still moves.\n const movers = store\n .getMovers(store.getSelectedNodes())\n .filter((id) => store.locks.allows(id, \"drag\"))\n if (movers.length === 0) return\n event.preventDefault()\n const snapGrid = getSnapGrid?.() ?? null\n const factor = event.shiftKey ? ARROW_STEP_SHIFT : 1\n // A `0` axis of the grid is free, so it keeps the default step.\n const stepX = (snapGrid?.[0] || ARROW_STEP) * factor\n const stepY = (snapGrid?.[1] || ARROW_STEP) * factor\n for (const id of movers) {\n const node = store.nodes.get(id)\n if (!node) continue\n let next = { x: node.position.x + dir.x * stepX, y: node.position.y + dir.y * stepY }\n if (snapGrid) next = snapToGrid(next, snapGrid)\n store.moveNode(id, next, true)\n }\n }\n}\n","/** Keys readable straight off an event via `getModifierState` — no key tracking. */\nconst MODIFIER_KEYS = new Set([\"Shift\", \"Control\", \"Meta\", \"Alt\"])\n\n/**\n * True when any of `keys` is currently held. Modifier keys are read from the\n * event via `getModifierState` (never stale); other keys need a `pressedKeys`\n * set maintained from keydown/keyup. With no set, only modifiers resolve.\n */\nexport function keyHeld(\n event: { getModifierState(key: string): boolean },\n keys: readonly string[],\n pressedKeys?: ReadonlySet<string>,\n): boolean {\n return keys.some((key) =>\n MODIFIER_KEYS.has(key) ? event.getModifierState(key) : (pressedKeys?.has(key) ?? false),\n )\n}\n","/**\n * Manages the node layer's transform and its `will-change` compositor hint. The\n * hint is applied only while the viewport is moving and dropped once it settles,\n * so the browser re-rasterizes DOM text crisply at the current zoom (a permanently\n * promoted layer upscales a stale bitmap and blurs text).\n */\nexport type LayerHint = {\n /** Set the layer transform; if it changed, promote the layer and arm the idle drop. */\n apply: (transform: string) => void\n dispose: () => void\n}\n\nexport function createLayerHint(layer: HTMLElement, idleMs: number): LayerHint {\n let lastTransform = \"\"\n let timer = 0\n return {\n apply(transform) {\n if (transform === lastTransform) return\n lastTransform = transform\n layer.style.transform = transform\n layer.style.willChange = \"transform\"\n if (timer) clearTimeout(timer)\n timer = window.setTimeout(() => {\n layer.style.willChange = \"auto\"\n }, idleMs)\n },\n dispose() {\n if (timer) clearTimeout(timer)\n },\n }\n}\n","import type { RivetStore } from \"../store\"\nimport type { NodeId } from \"../types\"\nimport { rectsIntersect, screenToWorld } from \"../viewport\"\n\nconst OVERLAY_STYLE =\n \"position:absolute;pointer-events:none;display:none;border:1px solid rgba(99,102,241,0.9);background:rgba(99,102,241,0.12);\"\n\nexport type MarqueeControllerDeps = {\n store: RivetStore\n pane: HTMLElement\n}\n\n/**\n * Marquee (rubber-band) selection state machine. Owns its screen-space overlay\n * element and the world-rect hit test. The pane dispatcher decides when a press\n * starts a marquee (empty-space drag, or the selection key held) and drives\n * start/move/end; `additive` (the multi-select key) unions the covered nodes with\n * the selection that was live when the marquee began. The overlay lives in screen\n * space, so it is never viewport-transformed.\n */\nexport type MarqueeController = {\n isActive: () => boolean\n start: (event: PointerEvent, px: number, py: number, additive: boolean) => void\n move: (px: number, py: number) => void\n end: (event: PointerEvent) => void\n /** Remove the overlay element (runtime teardown). */\n dispose: () => void\n}\n\nexport function createMarqueeController(deps: MarqueeControllerDeps): MarqueeController {\n const { store, pane } = deps\n let active = false\n let additive = false\n let base: NodeId[] = []\n let start = { x: 0, y: 0 }\n\n const overlay = document.createElement(\"div\")\n overlay.style.cssText = OVERLAY_STYLE\n pane.appendChild(overlay)\n\n const apply = (px: number, py: number) => {\n const left = Math.min(start.x, px)\n const top = Math.min(start.y, py)\n const width = Math.abs(px - start.x)\n const height = Math.abs(py - start.y)\n overlay.style.left = `${left}px`\n overlay.style.top = `${top}px`\n overlay.style.width = `${width}px`\n overlay.style.height = `${height}px`\n\n const viewport = store.getViewport()\n const topLeft = screenToWorld({ x: left, y: top }, viewport)\n const bottomRight = screenToWorld({ x: left + width, y: top + height }, viewport)\n const worldRect = {\n x: topLeft.x,\n y: topLeft.y,\n width: bottomRight.x - topLeft.x,\n height: bottomRight.y - topLeft.y,\n }\n const ids: NodeId[] = []\n for (const [id, node] of store.nodes) {\n if (node.selectable === false) continue\n // A peer's lock reads exactly like `selectable: false` here — the sweep\n // passes over the node instead of refusing to select anything.\n if (!store.locks.allows(id, \"select\")) continue\n if (rectsIntersect(worldRect, store.getNodeRect(id))) ids.push(id)\n }\n store.selectNodes(additive ? [...new Set([...base, ...ids])] : ids)\n }\n\n return {\n isActive: () => active,\n start(event, px, py, isAdditive) {\n active = true\n additive = isAdditive\n base = isAdditive ? store.getSelectedNodes() : []\n start = { x: px, y: py }\n overlay.style.display = \"block\"\n apply(px, py)\n pane.setPointerCapture(event.pointerId)\n },\n move(px, py) {\n if (!active) return\n apply(px, py)\n },\n end(event) {\n if (!active) return\n active = false\n overlay.style.display = \"none\"\n pane.releasePointerCapture(event.pointerId)\n // A marquee that ends over nodes leaves the persistent selection box\n // behind them (see NodesSelection); it dismisses on the next click.\n store.setSelectionBoxActive(store.getSelectedNodes().length > 0)\n },\n dispose() {\n overlay.remove()\n },\n }\n}\n","import type { RivetStore } from \"../store\"\n\n/** Pointer travel (px) before a press counts as a pan rather than a click. */\nconst PAN_MOVE_THRESHOLD = 3\n\nexport type PanControllerDeps = {\n store: RivetStore\n pane: HTMLElement\n /** Ask the runtime to schedule a repaint (a pan moved the viewport). */\n schedule: () => void\n}\n\n/**\n * Drag-to-pan state machine. The pane's pointer dispatcher decides when a press\n * is a pan and drives {@link PanController.start}/`move`/`end`; this owns the\n * pan's state and viewport math. A moved right-button pan arms\n * {@link PanController.suppressNextContextMenu} so the ensuing context menu is\n * swallowed instead of popping mid-pan.\n */\nexport type PanController = {\n isPanning: () => boolean\n start: (event: PointerEvent) => void\n move: (event: PointerEvent) => void\n end: (event: PointerEvent) => void\n /** Read-and-clear: true once if the last pan should swallow the next context menu. */\n suppressNextContextMenu: () => boolean\n}\n\nexport function createPanController(deps: PanControllerDeps): PanController {\n const { store, pane, schedule } = deps\n let panning = false\n let button = 0\n let moved = false\n let start = { x: 0, y: 0 }\n let origin = { x: 0, y: 0 }\n let suppressContextMenu = false\n\n return {\n isPanning: () => panning,\n start(event) {\n panning = true\n button = event.button\n moved = false\n const viewport = store.getViewport()\n start = { x: event.clientX, y: event.clientY }\n origin = { x: viewport.x, y: viewport.y }\n pane.setPointerCapture(event.pointerId)\n },\n move(event) {\n if (!panning) return\n const dx = event.clientX - start.x\n const dy = event.clientY - start.y\n if (!moved && Math.hypot(dx, dy) > PAN_MOVE_THRESHOLD) {\n moved = true\n if (button === 2) suppressContextMenu = true\n }\n const viewport = store.getViewport()\n store.setViewport({ ...viewport, x: origin.x + dx, y: origin.y + dy })\n schedule()\n },\n end(event) {\n if (!panning) return\n panning = false\n pane.releasePointerCapture(event.pointerId)\n },\n suppressNextContextMenu() {\n if (!suppressContextMenu) return false\n suppressContextMenu = false\n return true\n },\n }\n}\n","import type { EdgeRenderer } from \"../types\"\n\n/** Live pane pixel size, written on resize and read by the render loop. */\nexport type CanvasSize = { width: number; height: number; dpr: number }\n\nexport type ResizeControllerDeps = {\n pane: HTMLElement\n /** Background (grid + swimlane) canvas — sized here; edge canvases size via their renderers. */\n bgCanvas: HTMLCanvasElement\n size: CanvasSize\n edgeRenderer: EdgeRenderer\n foregroundRenderer: EdgeRenderer\n /**\n * Called with the new {@link CanvasSize} already written, for layers the\n * runtime owns conditionally (the peer-cursor canvas, which only exists when\n * cursors are being painted).\n */\n onResize?: () => void\n /** Repaint after a resize. */\n schedule: () => void\n}\n\n/**\n * Keep the canvases matched to the pane's CSS size and devicePixelRatio. Owns a\n * `ResizeObserver` on the pane and runs once immediately so the first frame is\n * sized. Writes the shared {@link CanvasSize} the render loop reads. `dispose`\n * disconnects the observer.\n */\nexport function createResizeController(deps: ResizeControllerDeps): { dispose: () => void } {\n const { pane, bgCanvas, size, edgeRenderer, foregroundRenderer, onResize, schedule } = deps\n\n const resize = () => {\n const rect = pane.getBoundingClientRect()\n size.width = rect.width\n size.height = rect.height\n size.dpr = window.devicePixelRatio || 1\n bgCanvas.width = Math.max(1, Math.round(rect.width * size.dpr))\n bgCanvas.height = Math.max(1, Math.round(rect.height * size.dpr))\n bgCanvas.style.width = `${rect.width}px`\n bgCanvas.style.height = `${rect.height}px`\n edgeRenderer.resize(rect.width, rect.height, size.dpr)\n foregroundRenderer.resize(rect.width, rect.height, size.dpr)\n onResize?.()\n schedule()\n }\n\n const observer = new ResizeObserver(resize)\n observer.observe(pane)\n resize()\n\n return { dispose: () => observer.disconnect() }\n}\n","import { clamp } from \"@rivet/utils\"\nimport type { RivetStore } from \"../store\"\nimport { zoomAt } from \"../viewport\"\n\n/** Approx px per wheel \"line\" / \"page\", to normalize non-pixel `deltaMode`. */\nconst WHEEL_LINE_PX = 16\n/** Fraction of the remaining zoom distance closed each frame (higher = snappier). */\nconst ZOOM_EASE = 0.22\n\nexport type ZoomControllerDeps = {\n store: RivetStore\n pane: HTMLElement\n /** Live pane pixel size (read for page-mode wheel normalization). */\n size: { height: number }\n minZoom: number\n maxZoom: number\n zoomSpeed: number\n /** Pan on wheel/trackpad scroll instead of zooming (pinch still zooms). */\n scrollToPan: boolean\n /** Ask the runtime to schedule a frame (to keep the ease running / repaint a pan). */\n schedule: () => void\n}\n\n/**\n * Wheel/pinch zoom with easing. Zoom accumulates onto a pending target so fast\n * ticks ramp up; {@link ZoomController.step} eases the on-screen zoom toward it\n * each frame. A new gesture calls {@link ZoomController.cancel}.\n */\nexport type ZoomController = {\n /** Advance the ease one frame; call at the top of the render loop. */\n step: () => void\n onWheel: (event: WheelEvent) => void\n /** Abandon any in-flight ease (a pan/reconnect/press is taking over). */\n cancel: () => void\n}\n\nexport function createZoomController(deps: ZoomControllerDeps): ZoomController {\n const { store, pane, size, minZoom, maxZoom, zoomSpeed, scrollToPan, schedule } = deps\n let target: { zoom: number; anchor: { x: number; y: number } } | null = null\n\n return {\n cancel() {\n target = null\n },\n step() {\n if (!target) return\n const vp = store.getViewport()\n const diff = target.zoom - vp.zoom\n if (Math.abs(diff) < 0.0005) {\n store.setViewport(zoomAt(vp, target.anchor, target.zoom, minZoom, maxZoom))\n target = null\n return\n }\n store.setViewport(zoomAt(vp, target.anchor, vp.zoom + diff * ZOOM_EASE, minZoom, maxZoom))\n schedule() // keep the ease running next frame\n },\n onWheel(event) {\n event.preventDefault()\n // Normalize non-pixel wheels (line/page mode) so step sizes are consistent.\n const scale = event.deltaMode === 1 ? WHEEL_LINE_PX : event.deltaMode === 2 ? size.height : 1\n const deltaX = event.deltaX * scale\n const deltaY = event.deltaY * scale\n\n // With scrollToPan on, a plain wheel/two-finger scroll pans; a pinch (which\n // the browser reports as ctrl+wheel) still zooms. Otherwise wheel zooms.\n if (scrollToPan && !event.ctrlKey) {\n target = null\n const viewport = store.getViewport()\n store.setViewport({ ...viewport, x: viewport.x - deltaX, y: viewport.y - deltaY })\n schedule()\n return\n }\n\n const rect = pane.getBoundingClientRect()\n const anchor = { x: event.clientX - rect.left, y: event.clientY - rect.top }\n // Accumulate onto the pending target (not the on-screen zoom) so fast ticks\n // ramp up, then the frame loop eases the visible zoom toward it.\n const base = target?.zoom ?? store.getViewport().zoom\n const nextZoom = clamp(base * Math.exp(-deltaY * zoomSpeed), minZoom, maxZoom)\n target = { zoom: nextZoom, anchor }\n schedule()\n },\n }\n}\n","import type { Viewport } from \"../types\"\n\nexport type DotGridOptions = {\n gap?: number\n radius?: number\n color?: string\n}\n\n/** Draw an infinite dot grid that tracks the viewport. Context is in CSS px. */\nexport function drawDotGrid(\n ctx: CanvasRenderingContext2D,\n width: number,\n height: number,\n viewport: Viewport,\n options?: DotGridOptions,\n): void {\n const gap = options?.gap ?? 24\n const radius = options?.radius ?? 1\n const color = options?.color ?? \"rgba(100, 116, 139, 0.35)\"\n\n const step = gap * viewport.zoom\n // Skip when dots would be denser than they are useful.\n if (step < 8) return\n\n const offsetX = ((viewport.x % step) + step) % step\n const offsetY = ((viewport.y % step) + step) % step\n\n ctx.fillStyle = color\n ctx.beginPath()\n for (let x = offsetX; x < width; x += step) {\n for (let y = offsetY; y < height; y += step) {\n ctx.moveTo(x + radius, y)\n ctx.arc(x, y, radius, 0, Math.PI * 2)\n }\n }\n ctx.fill()\n}\n","/**\n * Painting for presence — peer cursors, their selections, and the boxes they're\n * dragging right now.\n *\n * All of it is screen-space chrome above the nodes: it belongs to the frame,\n * not to the document, so it's drawn from the registry every tick and never\n * persisted. Nothing here reads or writes the graph — a node under a peer's\n * gesture is already being drawn at their live box (the store folds their\n * frames into world positions), so this file only says *whose* it is.\n *\n * It paints onto **two** canvases, split by what makes them dirty:\n *\n * - {@link drawPeerOutlines} — selections, held nodes and locks, on the shared\n * foreground canvas. They annotate node geometry and change when it does.\n * - {@link drawPeerCursors} — the arrows and name chips, on a canvas of their\n * own. Cursors arrive at pointer rate for every peer and nothing else on\n * screen depends on where they are, so a cursor frame repaints that layer\n * alone and leaves the foreground (pending connection, alignment guides,\n * endpoint bubbles) untouched.\n */\n\nimport { type PeerRecord, peerColor } from \"../presence/registry\"\nimport type { NodeId, Rect, Vec2, Viewport } from \"../types\"\nimport { worldToScreen } from \"../viewport\"\n\n/** Outline around a node a peer is holding or moving right now. */\nconst HELD_LINE_WIDTH = 2\n/** Outline around a node a peer merely has selected — thinner, and dashed. */\nconst SELECTED_LINE_WIDTH = 1.5\nconst SELECTED_DASH = [4, 4]\nconst OUTLINE_RADIUS = 6\n\n/** Cursor arrow, in px from the pointer tip. The classic seven-point pointer. */\nconst CURSOR_POINTS: readonly Vec2[] = [\n { x: 0, y: 0 },\n { x: 0, y: 16 },\n { x: 4.2, y: 12.2 },\n { x: 6.8, y: 17.6 },\n { x: 9.2, y: 16.6 },\n { x: 6.6, y: 11.4 },\n { x: 11.4, y: 11.4 },\n]\nconst CURSOR_LABEL_OFFSET: Vec2 = { x: 12, y: 17 }\nconst LABEL_FONT = \"500 11px ui-sans-serif, system-ui, -apple-system, sans-serif\"\nconst LABEL_PADDING_X = 6\nconst LABEL_HEIGHT = 17\nconst LABEL_RADIUS = 4\n/** How far off-pane a cursor or box may sit before it's skipped entirely. */\nconst CULL_MARGIN_PX = 64\n\n/** Pane size in CSS px, plus the device pixel ratio the canvas is scaled by. */\nexport type PresenceCanvasSize = { width: number; height: number; dpr: number }\n\nexport type PeerCursorDrawParams = {\n viewport: Viewport\n size: PresenceCanvasSize\n}\n\nexport type PeerOutlineDrawParams = {\n viewport: Viewport\n size: PresenceCanvasSize\n /** This client's box for a node, or `null` when it doesn't have that node. */\n getNodeRect: (id: NodeId) => Rect | null\n /**\n * Locked nodes, `nodeId -> holderId`. Painted exactly like a peer's held\n * node: to whoever is looking, \"they have this\" is the whole message, and a\n * second visual vocabulary for it would only ask them to learn the\n * difference between advisory and enforced. Holders don't have to be in the\n * roster — a lock can outlive the tab that took it.\n */\n locks: ReadonlyMap<NodeId, string>\n}\n\n/** Trace a rounded rect, degrading to a square one where `roundRect` is missing. */\nfunction traceRect(ctx: CanvasRenderingContext2D, rect: Rect, radius: number): void {\n ctx.beginPath()\n if (typeof ctx.roundRect === \"function\") {\n ctx.roundRect(rect.x, rect.y, rect.width, rect.height, radius)\n } else {\n ctx.rect(rect.x, rect.y, rect.width, rect.height)\n }\n}\n\n/** World rect → screen rect under the current viewport. */\nfunction projectRect(rect: Rect, viewport: Viewport): Rect {\n const origin = worldToScreen({ x: rect.x, y: rect.y }, viewport)\n return {\n x: origin.x,\n y: origin.y,\n width: rect.width * viewport.zoom,\n height: rect.height * viewport.zoom,\n }\n}\n\nfunction onScreen(rect: Rect, size: { width: number; height: number }): boolean {\n return (\n rect.x + rect.width >= -CULL_MARGIN_PX &&\n rect.y + rect.height >= -CULL_MARGIN_PX &&\n rect.x <= size.width + CULL_MARGIN_PX &&\n rect.y <= size.height + CULL_MARGIN_PX\n )\n}\n\n/** Outline one node in a peer's colour: solid for a claim, dashed for a selection. */\nfunction drawNodeOutline(\n ctx: CanvasRenderingContext2D,\n rect: Rect,\n color: string,\n mode: \"selected\" | \"held\",\n): void {\n ctx.strokeStyle = color\n ctx.lineWidth = mode === \"selected\" ? SELECTED_LINE_WIDTH : HELD_LINE_WIDTH\n ctx.setLineDash(mode === \"selected\" ? SELECTED_DASH : [])\n traceRect(ctx, rect, OUTLINE_RADIUS)\n ctx.stroke()\n ctx.setLineDash([])\n}\n\n/** The pointer arrow, plus a name chip when the peer has a name. */\nfunction drawCursor(\n ctx: CanvasRenderingContext2D,\n point: Vec2,\n color: string,\n name: string | undefined,\n): void {\n ctx.beginPath()\n const [first, ...rest] = CURSOR_POINTS\n if (!first) return\n ctx.moveTo(point.x + first.x, point.y + first.y)\n for (const offset of rest) ctx.lineTo(point.x + offset.x, point.y + offset.y)\n ctx.closePath()\n ctx.fillStyle = color\n ctx.fill()\n // A white keyline keeps the arrow legible over a node of the same hue.\n ctx.strokeStyle = \"#ffffff\"\n ctx.lineWidth = 1\n ctx.stroke()\n\n if (!name) return\n ctx.font = LABEL_FONT\n ctx.textBaseline = \"middle\"\n const width = ctx.measureText(name).width + LABEL_PADDING_X * 2\n const x = point.x + CURSOR_LABEL_OFFSET.x\n const y = point.y + CURSOR_LABEL_OFFSET.y\n traceRect(ctx, { x, y, width, height: LABEL_HEIGHT }, LABEL_RADIUS)\n ctx.fillStyle = color\n ctx.fill()\n ctx.fillStyle = \"#ffffff\"\n ctx.fillText(name, x + LABEL_PADDING_X, y + LABEL_HEIGHT / 2)\n}\n\n/**\n * Outline what every peer has a claim on, onto the foreground canvas: their\n * selections first, then whatever they're holding, then locks.\n *\n * Shares the canvas with the pending connection and the alignment guides, so it\n * draws over whatever they left and clears nothing.\n */\nexport function drawPeerOutlines(\n ctx: CanvasRenderingContext2D,\n peers: readonly PeerRecord[],\n { viewport, size, getNodeRect, locks }: PeerOutlineDrawParams,\n): void {\n if (peers.length === 0 && locks.size === 0) return\n ctx.save()\n // Screen space: outlines are chrome, so they keep their weight at any zoom\n // (the boxes they sit on scale, the strokes don't).\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n\n // Nodes a peer has already claimed this frame. A locked node is very often\n // also one its holder is dragging, and stroking it twice reads as a heavier\n // border rather than as two facts.\n const painted = new Set<NodeId>()\n\n for (const peer of peers) {\n // A node they're moving is held whether or not their roster entry has caught\n // up: the frames arriving are the more current fact, and `getNodeRect`\n // already returns it at their live box.\n const held = new Set([...peer.holding, ...peer.transforms.keys()])\n for (const id of peer.selection) {\n if (held.has(id)) continue\n const rect = getNodeRect(id)\n if (!rect) continue\n const screen = projectRect(rect, viewport)\n if (onScreen(screen, size)) drawNodeOutline(ctx, screen, peer.color, \"selected\")\n }\n for (const id of held) {\n painted.add(id)\n const rect = getNodeRect(id)\n if (!rect) continue\n const screen = projectRect(rect, viewport)\n if (onScreen(screen, size)) drawNodeOutline(ctx, screen, peer.color, \"held\")\n }\n }\n\n if (locks.size > 0) {\n // The roster's colour wins where it exists, so a peer who declared one\n // looks the same locked as they do holding; otherwise it's derived from the\n // holder id, which is how an unrostered holder still gets a stable colour.\n const declared = new Map(peers.map((peer) => [peer.id, peer.color]))\n for (const [id, holderId] of locks) {\n if (painted.has(id)) continue\n const rect = getNodeRect(id)\n if (!rect) continue\n const screen = projectRect(rect, viewport)\n if (!onScreen(screen, size)) continue\n drawNodeOutline(ctx, screen, declared.get(holderId) ?? peerColor(holderId), \"held\")\n }\n }\n\n ctx.restore()\n}\n\n/**\n * Paint every peer's pointer onto the cursor layer.\n *\n * Unlike {@link drawPeerOutlines} this owns its whole canvas, so it clears\n * first — a cursor frame is the only thing that ever writes here, and the\n * arrows have to be erased from wherever they were last frame.\n */\nexport function drawPeerCursors(\n ctx: CanvasRenderingContext2D,\n peers: readonly PeerRecord[],\n { viewport, size }: PeerCursorDrawParams,\n): void {\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n ctx.clearRect(0, 0, size.width, size.height)\n for (const peer of peers) {\n if (!peer.cursor) continue\n const point = worldToScreen(peer.cursor, viewport)\n if (!onScreen({ ...point, width: 0, height: 0 }, size)) continue\n drawCursor(ctx, point, peer.color, peer.name)\n }\n}\n","import { type ResolvedLane, withAlpha } from \"../swimlane/lanes\"\nimport type { Viewport } from \"../types\"\n\nexport type SwimlaneStyle = {\n /** Color of the divider drawn under each lane. */\n separator?: string\n /** Alpha applied to a lane's `color` when tinting its band. */\n tintAlpha?: number\n}\n\nconst DEFAULTS: Required<SwimlaneStyle> = {\n separator: \"rgba(100, 116, 139, 0.28)\",\n tintAlpha: 0.06,\n}\n\n/**\n * Draw swimlanes as full-viewport-width lanes — a low-alpha fill tint for lanes\n * with an explicit `color`, plus a bottom divider per lane (no side borders).\n * Only the vertical position tracks the viewport; horizontally a band always\n * spans the pane. Labels and the group header are sticky DOM overlays. Context\n * is in CSS px.\n */\nexport function drawSwimlanes(\n ctx: CanvasRenderingContext2D,\n width: number,\n height: number,\n viewport: Viewport,\n lanes: ResolvedLane[],\n style?: SwimlaneStyle,\n): void {\n if (lanes.length === 0) return\n const separator = style?.separator ?? DEFAULTS.separator\n const tintAlpha = style?.tintAlpha ?? DEFAULTS.tintAlpha\n\n for (const lane of lanes) {\n if (!lane.color) continue\n const top = viewport.y + lane.top * viewport.zoom\n const bottom = viewport.y + (lane.top + lane.height) * viewport.zoom\n if (bottom < 0 || top > height) continue\n ctx.fillStyle = withAlpha(lane.color, tintAlpha)\n ctx.fillRect(0, top, width, bottom - top)\n }\n\n ctx.strokeStyle = separator\n ctx.lineWidth = 1\n ctx.beginPath()\n for (const lane of lanes) {\n const bottom = viewport.y + (lane.top + lane.height) * viewport.zoom\n if (bottom < 0 || bottom > height) continue\n ctx.moveTo(0, bottom - 0.5)\n ctx.lineTo(width, bottom - 0.5)\n }\n ctx.stroke()\n}\n","import { clamp } from \"@rivet/utils\"\nimport { type RefObject, useEffect, useMemo, useRef, useState } from \"react\"\nimport {\n parseAnchorAutoHandleId,\n parseAnchorHandleId,\n type ResolvedAnchorOptions,\n strayPlacementPct,\n} from \"../anchor/registry\"\nimport { type ConnectionEnd, handleWorldPosition } from \"../connection\"\nimport { DEFAULT_NODE_SIZE, handleKey, SELECTOR } from \"../constants\"\nimport { displayedSideKey, parseSideHandleId } from \"../edge-ends\"\nimport { boundingRect } from \"../graph\"\nimport { startConnectionDrag } from \"../input/connection-drag\"\nimport { createKeyboardHandler } from \"../input/keyboard\"\nimport { keyHeld } from \"../input/keys\"\nimport { createLayerHint } from \"../input/layer-hint\"\nimport { createMarqueeController } from \"../input/marquee-controller\"\nimport { createPanController } from \"../input/pan-controller\"\nimport { createResizeController } from \"../input/resize-controller\"\nimport { createZoomController } from \"../input/zoom-controller\"\nimport { drawDotGrid } from \"../renderer/background\"\nimport { PENDING_COLOR, pointOnSide } from \"../renderer/edge-geometry\"\nimport { drawPeerCursors, drawPeerOutlines } from \"../renderer/presence\"\nimport { drawSwimlanes } from \"../renderer/swimlane\"\nimport type { RivetStore } from \"../store\"\nimport type { ResolvedLane, ViewportElements, VisibleLane } from \"../swimlane/lanes\"\nimport type {\n AlignmentGuide,\n Connection,\n DefaultEdgeOptions,\n EdgeEnd,\n EdgeRendererFactory,\n EdgeRendererOptions,\n EdgeTypes,\n FitViewOptions,\n HandlePosition,\n NodeId,\n Rect,\n RivetControls,\n RivetEdge,\n RivetNode,\n Vec2,\n Viewport,\n} from \"../types\"\nimport { rectsIntersect, viewportToCss, visibleWorldRect, worldToScreen, zoomAt } from \"../viewport\"\n\nconst CULL_MARGIN_PX = 240\n/** Default wheel/pinch zoom sensitivity (override via the `zoomSpeed` prop). */\nexport const DEFAULT_ZOOM_SPEED = 0.0015\nconst ZOOM_STEP = 1.2\n/**\n * How long after the last viewport change to drop `will-change: transform` from the\n * node layer, so the browser re-rasterizes DOM text crisply at the current zoom.\n */\nconst WILL_CHANGE_IDLE_MS = 180\n/** Stroke for alignment/snap guide lines. */\nconst GUIDE_COLOR = \"rgba(236, 72, 153, 0.9)\"\n\n/** Paint world-space alignment guides as thin screen-space lines. */\nfunction drawAlignmentGuides(\n ctx: CanvasRenderingContext2D,\n guides: AlignmentGuide[],\n viewport: Viewport,\n size: { dpr: number },\n): void {\n if (guides.length === 0) return\n ctx.save()\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n ctx.strokeStyle = GUIDE_COLOR\n ctx.lineWidth = 1\n ctx.beginPath()\n for (const guide of guides) {\n // +0.5 keeps the 1px line crisp on the pixel grid.\n if (guide.axis === \"x\") {\n const a = worldToScreen({ x: guide.position, y: guide.start }, viewport)\n const b = worldToScreen({ x: guide.position, y: guide.end }, viewport)\n ctx.moveTo(Math.round(a.x) + 0.5, a.y)\n ctx.lineTo(Math.round(b.x) + 0.5, b.y)\n } else {\n const a = worldToScreen({ x: guide.start, y: guide.position }, viewport)\n const b = worldToScreen({ x: guide.end, y: guide.position }, viewport)\n ctx.moveTo(a.x, Math.round(a.y) + 0.5)\n ctx.lineTo(b.x, Math.round(b.y) + 0.5)\n }\n }\n ctx.stroke()\n ctx.restore()\n}\n\n/** Radius of the reconnect affordance bubble drawn at a grabbable edge end. */\nconst ENDPOINT_BUBBLE_RADIUS = 6\n/**\n * Once an edge is hovered, it stays hovered while the pointer remains within\n * this distance of its path — looser than the acquire tolerance so tracking\n * the curve toward a grab bubble doesn't flicker the affordance away.\n */\nconst HOVER_KEEP_TOLERANCE = 16\n\n/**\n * Paint the reconnect affordance: a small grab bubble at each end of the\n * hovered/selected reconnectable edge, in the pending-connection accent so it\n * reads as \"this end is draggable\". Drawn on the foreground canvas (above\n * nodes) since endpoints sit on node borders.\n */\nexport function drawEndpointBubbles(\n ctx: CanvasRenderingContext2D,\n ends: { source: Vec2; target: Vec2 },\n size: { dpr: number },\n): void {\n ctx.save()\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n // Solid accent fill with a white ring — deliberately the inverse of the\n // white-filled handle dots the bubbles often sit on top of.\n ctx.fillStyle = PENDING_COLOR\n ctx.strokeStyle = \"#ffffff\"\n ctx.lineWidth = 1.5\n for (const point of [ends.source, ends.target]) {\n ctx.beginPath()\n ctx.arc(point.x, point.y, ENDPOINT_BUBBLE_RADIUS, 0, Math.PI * 2)\n ctx.fill()\n ctx.stroke()\n }\n ctx.restore()\n}\n\nexport type RivetRuntimeParams = {\n store: RivetStore\n paneRef: RefObject<HTMLDivElement | null>\n nodeContainerRef: RefObject<HTMLDivElement | null>\n backgroundCanvasRef: RefObject<HTMLCanvasElement | null>\n edgeCanvasRef: RefObject<HTMLCanvasElement | null>\n /** Foreground canvas above the node layer — draws the in-progress connection. */\n foregroundCanvasRef: RefObject<HTMLCanvasElement | null>\n /**\n * Peer-cursor canvas above the foreground, or a ref holding `null` when\n * `presenceOptions.renderCursors` is off. Read fresh each frame rather than\n * captured, so mounting or unmounting the layer doesn't tear the loop down.\n */\n cursorCanvasRef: RefObject<HTMLCanvasElement | null>\n /** Swimlane lanes to paint behind the graph. Empty when unused. */\n swimlaneLanes: ResolvedLane[]\n /** Registry of custom edge path builders, merged over the built-ins. */\n edgeTypes?: EdgeTypes\n /** Defaults merged into every edge (type, animated, style, markers). */\n defaultEdgeOptions?: DefaultEdgeOptions\n /** Resolved anchor chrome policy — places auto anchor ends along a side. */\n anchorOptions: ResolvedAnchorOptions\n /** Backend factory for the edge layers. Defaults to Canvas2D. */\n edgeRenderer: EdgeRendererFactory\n /** Default for whether edges can be reconnected by dragging an endpoint. */\n edgesReconnectable?: boolean\n /** Veto a proposed connection (shared with drag-to-connect). */\n isValidConnection?: (connection: Connection) => boolean\n /** Rewrite a validated connection before commit; null cancels (shared with drag-to-connect). */\n mapConnection?: (connection: Connection) => Connection | null\n /** Called when an endpoint drag re-points an edge (the edge is already updated). */\n onReconnect?: (edge: RivetEdge, connection: Connection) => void\n /** Called when an endpoint reconnection drag starts. */\n onReconnectStart?: (edge: RivetEdge) => void\n /** Called when an endpoint reconnection drag ends (committed or cancelled). */\n onReconnectEnd?: (edge: RivetEdge) => void\n /** Mouse buttons (`MouseEvent.button` codes) that pan on drag. Empty = never. */\n panButtons: number[]\n /** Draw a marquee on a plain left-drag instead of panning. */\n selectionOnDrag: boolean\n /** Keys that force marquee selection on a left-drag (held before dragging). */\n selectionKeys: string[]\n /** Keys that make a marquee/click add to the selection instead of replacing it. */\n multiSelectionKeys: string[]\n /** Pan on wheel/trackpad scroll instead of zooming (pinch still zooms). */\n scrollToPan: boolean\n /** Wheel/pinch zoom sensitivity — larger zooms faster per delta. */\n zoomSpeed: number\n minZoom: number\n maxZoom: number\n gridGap: number\n snapGrid: [number, number] | null\n}\n\n/**\n * Owns everything that must not go through React on every frame: the rAF loop,\n * pan/zoom input, the imperative node-layer transform, and node culling. Only\n * culling changes (which nodes are mounted) are pushed back into React state.\n */\nexport function useRivetRuntime(params: RivetRuntimeParams): {\n visibleIds: NodeId[]\n controls: RivetControls\n getViewportElements: () => ViewportElements\n} {\n const { store, paneRef, nodeContainerRef } = params\n const { backgroundCanvasRef, edgeCanvasRef, foregroundCanvasRef, cursorCanvasRef } = params\n const { swimlaneLanes, scrollToPan, zoomSpeed } = params\n const { minZoom, maxZoom, gridGap, edgeTypes, defaultEdgeOptions, anchorOptions } = params\n const { edgeRenderer: createEdgeRenderer } = params\n const { panButtons, selectionOnDrag, selectionKeys, multiSelectionKeys } = params\n const [visibleIds, setVisibleIds] = useState<NodeId[]>([])\n\n // Reconnection callbacks read through a ref so their changing identity doesn't\n // tear down the pointer/rAF effect below.\n const reconnectRef = useRef(params)\n reconnectRef.current = params\n\n // Current pane pixel size, kept in a ref so the (stable) controls below can\n // read it without re-subscribing.\n const sizeRef = useRef({ width: 0, height: 0, dpr: 1 })\n\n // The visible-node set signature, kept across effect re-runs. If it lived in\n // the effect closure it would reset to \"\" whenever the effect re-mounts (e.g.\n // an unstable prop identity), making the first render push `setVisibleIds`\n // again — that re-render re-mounts the effect, and the two feed each other\n // into an infinite loop whose per-frame `resize()` blanks the canvases.\n const visibleKeyRef = useRef(\"\")\n\n // Lanes change on live resize; keep them in a ref the render loop reads so a\n // resize just repaints the next frame instead of tearing down the rAF effect.\n const swimlaneLanesRef = useRef(swimlaneLanes)\n useEffect(() => {\n swimlaneLanesRef.current = swimlaneLanes\n store.requestRender()\n }, [store, swimlaneLanes])\n\n const controls = useMemo<RivetControls>(\n () => buildControls({ store, sizeRef, minZoom, maxZoom }),\n [store, minZoom, maxZoom],\n )\n\n // Stable imperative query of what's on screen. Reads live size/lanes/viewport\n // from refs, so consumers can inspect the viewport without subscribing to it.\n const getViewportElements = useMemo(\n () => buildViewportQuery({ store, sizeRef, lanesRef: swimlaneLanesRef }),\n [store],\n )\n\n useEffect(() => {\n const pane = paneRef.current\n const bgCanvas = backgroundCanvasRef.current\n const edgeCanvas = edgeCanvasRef.current\n const foregroundCanvas = foregroundCanvasRef.current\n const nodeContainer = nodeContainerRef.current\n if (!pane || !bgCanvas || !edgeCanvas || !foregroundCanvas || !nodeContainer) return\n\n const bgCtx = bgCanvas.getContext(\"2d\")\n if (!bgCtx) return\n const rendererOptions: EdgeRendererOptions = { edgeTypes, defaultEdgeOptions }\n const edgeRenderer = createEdgeRenderer(edgeCanvas, rendererOptions)\n // The in-progress connection is drawn on a canvas above the nodes so it never\n // hides behind them; committed edges stay on `edgeCanvas`, below the nodes.\n const foregroundRenderer = createEdgeRenderer(foregroundCanvas, rendererOptions)\n // Alignment guides paint on the foreground (above nodes) after the edge\n // renderer. Read the 2D context *after* the renderer claimed its own — null\n // for a non-2D custom backend, in which case guides just won't show.\n const fgCtx = foregroundCanvas.getContext(\"2d\")\n\n const size = sizeRef.current\n let frame = 0\n let dirty = true\n /** Set on its own by cursor frames — see {@link drawCursorLayer}. */\n let cursorsDirty = true\n let hoveredEdgeId: string | null = null\n /**\n * Nodes a peer moved on the previous frame. Kept so the frame they let go\n * can put each element back where the graph says it is — React doesn't\n * re-render on presence frames, and shouldn't: they arrive at pointer rate.\n */\n let peerPositioned = new Set<NodeId>()\n\n /**\n * Move the elements peers are dragging, imperatively — the same path a\n * local group drag uses. `worldPositions` already carries their boxes, so\n * this is only the DOM catching up with what everything else already draws.\n */\n const positionPeerNodes = (worldPositions: ReadonlyMap<NodeId, Vec2>) => {\n const transforms = store.presence.getNodeTransforms()\n if (transforms.size === 0 && peerPositioned.size === 0) return\n const current = new Set<NodeId>()\n for (const id of transforms.keys()) {\n current.add(id)\n for (const childId of store.getDescendantIds(id)) current.add(childId)\n }\n for (const id of new Set([...current, ...peerPositioned])) {\n const element = store.getNodeElement(id)\n const world = worldPositions.get(id)\n if (!element || !world) continue\n element.style.transform = `translate(${world.x}px, ${world.y}px)`\n const live = transforms.get(id)\n // A peer mid-resize sends a box; give the element that size until they\n // let go, then hand it back to whatever React last styled.\n if (live && !store.isNodeHeld(id)) {\n element.style.width = `${live.width}px`\n element.style.height = `${live.height}px`\n } else if (peerPositioned.has(id)) {\n element.style.width = \"\"\n element.style.height = \"\"\n }\n }\n peerPositioned = current\n }\n\n // --- peer-cursor layer ---------------------------------------------------\n // Cursors get a canvas of their own because they arrive at pointer rate for\n // every peer while nothing else on screen depends on where they are. On the\n // shared foreground they made the pending connection, the alignment guides\n // and the endpoint bubbles repaint at that rate too, for no reason.\n let cursorCanvas: HTMLCanvasElement | null = null\n let cursorCtx: CanvasRenderingContext2D | null = null\n /** Whether the layer has a backing store matched to the pane yet. */\n let cursorAllocated = false\n\n /**\n * Match the cursor canvas to the pane. Deliberately a no-op until something\n * has actually asked to paint on it: the element mounts with the graph, but\n * a document nobody else is in shouldn't pay for a fourth full-size canvas.\n */\n const sizeCursorLayer = () => {\n if (!cursorCanvas || !cursorAllocated) return\n cursorCanvas.width = Math.max(1, Math.round(size.width * size.dpr))\n cursorCanvas.height = Math.max(1, Math.round(size.height * size.dpr))\n cursorCanvas.style.width = `${size.width}px`\n cursorCanvas.style.height = `${size.height}px`\n }\n\n const drawCursorLayer = () => {\n // Resolved per frame: `renderCursors` mounts and unmounts the element, and\n // that must not cost a teardown of the loop the way a dep change would.\n const canvas = cursorCanvasRef.current\n if (canvas !== cursorCanvas) {\n cursorCanvas = canvas\n cursorCtx = canvas?.getContext(\"2d\") ?? null\n cursorAllocated = false\n }\n if (!cursorCtx) return\n const peers = store.presence.getPeers()\n const wanted = peers.some((peer) => peer.cursor)\n // Nothing to draw and nothing ever drawn: no canvas to clear, no pixels\n // to allocate. Once allocated it keeps clearing, so the last cursor of a\n // peer who left is erased rather than left behind.\n if (!wanted && !cursorAllocated) return\n if (!cursorAllocated) {\n cursorAllocated = true\n sizeCursorLayer()\n }\n drawPeerCursors(cursorCtx, peers, { viewport: store.getViewport(), size })\n }\n\n /**\n * Advance peer interpolation, then ask for whichever frame the motion needs.\n * A moving box changes world positions — and so edges, culling, outlines and\n * the DOM — while a moving cursor changes one canvas. The transform version\n * separates them: the registry bumps it exactly when a rendered box moves.\n */\n const stepPresence = () => {\n const version = store.presence.getTransformVersion()\n if (!store.presence.step(performance.now())) return\n if (store.presence.getTransformVersion() !== version) schedule()\n else scheduleCursors()\n }\n\n // Places an auto-resolved anchor end along a side of its node — the same\n // policy the stray-handle chrome uses, read from the live anchor registry.\n const anchorPlacement = (nodeId: NodeId, anchorId: string, side: HandlePosition) => {\n const record = store.anchors.get(handleKey(nodeId, anchorId))\n return record?.geometry ? strayPlacementPct(record.geometry, side, anchorOptions) : null\n }\n\n // Composable input controllers (see `input/`). The rAF `schedule` is defined\n // further down, so the zoom controller receives it via a thunk. The interwoven\n // pointer stream (pan / marquee / edge hover / reconnect) stays inline below.\n const layerHint = createLayerHint(nodeContainer, WILL_CHANGE_IDLE_MS)\n const zoom = createZoomController({\n store,\n pane,\n size,\n minZoom,\n maxZoom,\n zoomSpeed,\n scrollToPan,\n schedule: () => schedule(),\n })\n\n const render = () => {\n // Advance the zoom ease before reading the viewport so this frame draws the\n // interpolated value.\n zoom.step()\n // Same for peers: ease their cursors and gesture boxes toward the last\n // frame that arrived, and keep asking for frames while anything moves.\n // Stepping here means the world positions read below are already the\n // interpolated ones, so nodes, edges and outlines can't disagree.\n stepPresence()\n const viewport = store.getViewport()\n\n // 1. Node layer follows the viewport imperatively — no React on pan/zoom.\n // The hint promotes the layer while moving, then drops it so text stays crisp.\n layerHint.apply(viewportToCss(viewport))\n\n // 2. Background grid, then the swimlane bands on top of it (behind edges).\n bgCtx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n bgCtx.clearRect(0, 0, size.width, size.height)\n drawDotGrid(bgCtx, size.width, size.height, viewport, { gap: gridGap })\n drawSwimlanes(bgCtx, size.width, size.height, viewport, swimlaneLanesRef.current)\n\n // 3. Committed edges below the nodes; the in-progress connection above them.\n // World positions (parent chains) come from the store's cache — recomputed\n // only when nodes moved, so pan/zoom frames reuse them. Anchors and culling\n // both read it, so nested nodes stay wired to their edges.\n const worldPositions = store.getWorldPositions()\n positionPeerNodes(worldPositions)\n const edgeList = [...store.edges.values()]\n const pending = store.getPending()\n // Under `\"live\"` alignment, edges touching a mid-drag node render both\n // ends as auto; the resolved sides land in the store's displayed-sides\n // memory so the drop commits exactly what was shown.\n const liveAlignNodes =\n store.getEdgeAlignment() === \"live\" && store.isNodeDragging()\n ? store.getDraggingNodeIds()\n : undefined\n edgeRenderer.draw(edgeList, store.nodes, viewport, {\n handles: store.handles,\n pending: null,\n hovered: hoveredEdgeId,\n reconnecting: pending?.reconnecting ?? null,\n worldPositions,\n displayedSides: store.getDisplayedSides(),\n liveAlignNodes,\n anchorPlacement,\n })\n store.setEdgeLabelAnchors(edgeRenderer.getLabels())\n foregroundRenderer.draw([], store.nodes, viewport, {\n handles: store.handles,\n pending,\n })\n // Alignment guides, on top of the foreground edges the renderer just drew.\n if (fgCtx) drawAlignmentGuides(fgCtx, store.getAlignmentGuides(), viewport, size)\n\n // Reconnect affordance: grab bubbles at the ends of the hovered/selected\n // reconnectable edge (hidden while that edge is mid-reconnect).\n if (fgCtx) {\n const affordanceId = hoveredEdgeId ?? store.getSelectedEdge()\n const edge = affordanceId ? store.edges.get(affordanceId) : undefined\n const reconnectable = edge\n ? (edge.reconnectable ?? reconnectRef.current.edgesReconnectable)\n : false\n if (edge && reconnectable && edge.id !== pending?.reconnecting) {\n const ends = edgeRenderer.getEndpoints?.().get(edge.id)\n if (ends) drawEndpointBubbles(fgCtx, ends, size)\n }\n }\n\n // Peers, on top of everything: what they have selected, an outline on\n // whatever they're moving this instant, and outlines for what they've\n // locked. Read straight from the registries each frame — neither presence\n // nor locks enters the graph, so this is the only place they exist.\n if (fgCtx && (!store.presence.isEmpty() || store.locks.size() > 0)) {\n drawPeerOutlines(fgCtx, store.presence.getPeers(), {\n viewport,\n size,\n getNodeRect: (id) => (store.nodes.has(id) ? store.getNodeRect(id) : null),\n locks: store.locks.getLocks(),\n })\n }\n // Their cursors, one layer higher. A full frame owns every layer, so this\n // repaints them too — the viewport they project through just moved.\n drawCursorLayer()\n\n // Animated edges need a fresh frame each tick to march their dashes.\n if (edgeList.some((edge) => edge.animated ?? defaultEdgeOptions?.animated)) schedule()\n\n // 4. Culling — only re-render React when the visible set actually changes.\n const rect = visibleWorldRect(viewport, size.width, size.height)\n const margin = CULL_MARGIN_PX / viewport.zoom\n const view = {\n x: rect.x - margin,\n y: rect.y - margin,\n width: rect.width + margin * 2,\n height: rect.height + margin * 2,\n }\n const ids: NodeId[] = []\n for (const node of store.nodes.values()) {\n const nodeSize = node.size ?? DEFAULT_NODE_SIZE\n const origin = worldPositions.get(node.id) ?? node.position\n // Unmeasured nodes are always mounted so they can report their size.\n if (\n !node.size ||\n rectsIntersect(view, {\n x: origin.x,\n y: origin.y,\n width: nodeSize.width,\n height: nodeSize.height,\n })\n ) {\n ids.push(node.id)\n }\n }\n const key = ids.join(\"|\")\n if (key !== visibleKeyRef.current) {\n visibleKeyRef.current = key\n setVisibleIds(ids)\n }\n\n // 5. Let secondary views (MiniMap, etc.) mirror this frame.\n store.notifyFrame()\n }\n\n const tick = () => {\n frame = 0\n // A full frame owns the cursor layer as well, so it settles both flags —\n // and it wins the tie, because it draws strictly more.\n if (dirty) {\n dirty = false\n cursorsDirty = false\n render()\n return\n }\n if (!cursorsDirty) return\n cursorsDirty = false\n // Cursors are eased like everything else; stepping here is what keeps a\n // cursor-only frame asking for the next one while the ease is running.\n stepPresence()\n drawCursorLayer()\n }\n const schedule = () => {\n dirty = true\n if (frame) return\n frame = requestAnimationFrame(tick)\n }\n const scheduleCursors = () => {\n cursorsDirty = true\n if (frame) return\n frame = requestAnimationFrame(tick)\n }\n\n // Every canvas-affecting mutation calls store.requestRender(); route it here.\n store.bindRenderRequester(schedule)\n // Cursor frames take the narrow path — one canvas, no culling, no DOM.\n store.bindCursorRenderRequester(scheduleCursors)\n\n const setEdgeHover = (id: string | null) => {\n if (hoveredEdgeId === id) return\n hoveredEdgeId = id\n schedule()\n }\n\n // Pointer gestures the dispatcher below drives (the pane owns the listeners).\n const pan = createPanController({ store, pane, schedule })\n const marquee = createMarqueeController({ store, pane })\n\n // Tracks non-modifier keys for the configurable key props; modifier keys read\n // straight off the pointer event via getModifierState, so they never go stale.\n const pressedKeys = new Set<string>()\n const selectionKeyHeld = (event: PointerEvent) => keyHeld(event, selectionKeys, pressedKeys)\n const multiSelectHeld = (event: PointerEvent) => keyHeld(event, multiSelectionKeys, pressedKeys)\n\n // Start a marquee, clearing any edge hover first — the runtime owns hover state.\n const startMarquee = (event: PointerEvent, px: number, py: number) => {\n setEdgeHover(null)\n marquee.start(event, px, py, multiSelectHeld(event))\n }\n\n // World position of an edge end, matching the renderer's resolution: the\n // registered handle if any; else the pinned or last-displayed side (placed\n // at the anchor's measured row/column when the end is an anchor end); else\n // the node's right (source) / left (target) mid-edge.\n const endpointWorld = (\n edge: RivetEdge,\n nodeId: NodeId,\n handleId: string | undefined,\n role: EdgeEnd,\n ): Vec2 => {\n if (handleId) {\n const record = store.handles.get(handleKey(nodeId, handleId))\n if (record) {\n const wp = handleWorldPosition(store, { nodeId, handleId, type: record.type })\n if (wp) return wp\n }\n }\n const side =\n parseAnchorHandleId(handleId)?.side ??\n parseSideHandleId(handleId) ??\n store.getDisplayedSides().get(displayedSideKey(edge.id, role))\n if (side) {\n const anchorId =\n parseAnchorAutoHandleId(handleId) ?? parseAnchorHandleId(handleId)?.anchorId\n const pct = anchorId ? (anchorPlacement(nodeId, anchorId, side) ?? undefined) : undefined\n return pointOnSide(store.getNodeRect(nodeId), side, pct)\n }\n const node = store.nodes.get(nodeId)\n const size = node?.size ?? DEFAULT_NODE_SIZE\n const base = store.getNodeWorldPosition(nodeId)\n const x = role === \"source\" ? base.x + size.width : base.x\n return { x, y: base.y + size.height / 2 }\n }\n\n // Drag an existing edge's loose end to a new handle. The other end stays put.\n const beginReconnect = (edge: RivetEdge, end: EdgeEnd) => {\n zoom.cancel()\n const fixedIsSource = end === \"target\"\n const fixedNodeId = fixedIsSource ? edge.source : edge.target\n const fixedHandleId = fixedIsSource ? edge.sourceHandle : edge.targetHandle\n const from: ConnectionEnd = {\n nodeId: fixedNodeId,\n handleId: fixedHandleId ?? \"\",\n type: fixedIsSource ? \"source\" : \"target\",\n }\n const fixedWorld = endpointWorld(\n edge,\n fixedNodeId,\n fixedHandleId,\n fixedIsSource ? \"source\" : \"target\",\n )\n const looseWorld = endpointWorld(\n edge,\n fixedIsSource ? edge.target : edge.source,\n fixedIsSource ? edge.targetHandle : edge.sourceHandle,\n fixedIsSource ? \"target\" : \"source\",\n )\n startConnectionDrag({\n store,\n paneRef,\n from,\n begin: {\n source: from.nodeId,\n sourceHandle: from.handleId,\n sourceType: from.type,\n from: fixedWorld,\n to: looseWorld,\n reconnecting: edge.id,\n },\n // Callbacks read `reconnectRef.current` when the drag ends, so a late\n // prop change (this effect never re-runs on callback identity) is honored.\n validate: (connection) => reconnectRef.current.isValidConnection?.(connection) ?? true,\n map: (connection) => {\n // `null` from the consumer means \"cancel the drop\" — must propagate.\n const mapFn = reconnectRef.current.mapConnection\n return mapFn ? mapFn(connection) : connection\n },\n commit: (connection) => {\n store.reconnectEdge(edge.id, connection)\n reconnectRef.current.onReconnect?.(edge, connection)\n },\n onEnd: () => reconnectRef.current.onReconnectEnd?.(edge),\n })\n reconnectRef.current.onReconnectStart?.(edge)\n }\n\n // Gateway for <Handle>: a press on a handle that coincides with a\n // reconnectable edge's endpoint moves that edge instead of starting a new\n // connection (the handle's DOM otherwise shadows the endpoint grab zone).\n // Gated on the affordance: the edge must be hovered or selected — i.e. its\n // grab bubbles are showing — so a cold press on an occupied handle still\n // starts a NEW connection (the user never \"picked up\" the edge).\n store.bindReconnectDelegate({\n pickEndpoint: (clientX, clientY) => {\n const rect = pane.getBoundingClientRect()\n const hit = edgeRenderer.pickEndpoint(clientX - rect.left, clientY - rect.top)\n if (!hit) return null\n if (hit.edgeId !== hoveredEdgeId && hit.edgeId !== store.getSelectedEdge()) return null\n const edge = store.edges.get(hit.edgeId)\n const reconnectable = edge\n ? (edge.reconnectable ?? reconnectRef.current.edgesReconnectable)\n : false\n return reconnectable ? hit : null\n },\n begin: (edgeId, end) => {\n const edge = store.edges.get(edgeId)\n if (edge) beginReconnect(edge, end)\n },\n })\n\n const onPointerDown = (event: PointerEvent) => {\n // A press anywhere retires a keyboard-started pending connection — it has\n // no drag gesture to end it. Safe for pointer flows: they begin *after*\n // this native listener (in React handlers), so their pending isn't set yet.\n if (store.getPending()) store.endConnection()\n // The pane's native listener fires before React's synthetic node handler,\n // so we can't rely on stopPropagation — check the origin element instead.\n // Nodes drag themselves; swimlane resize handles own their own gesture; and\n // `data-nopan` elements (overlay controls, toolbars…) keep their own pointer.\n if (event.target instanceof Element && event.target.closest(SELECTOR.paneGestureExempt)) {\n return\n }\n const rect = pane.getBoundingClientRect()\n const px = event.clientX - rect.left\n const py = event.clientY - rect.top\n\n // Middle/right buttons only ever pan (when configured); no edge/selection.\n if (event.button !== 0) {\n if (panButtons.includes(event.button)) {\n event.preventDefault() // suppress middle-click autoscroll\n zoom.cancel()\n pan.start(event)\n }\n return\n }\n\n // A new gesture cancels any in-flight zoom ease.\n zoom.cancel()\n\n // Holding the selection key forces a marquee over any pan behavior.\n if (selectionKeyHeld(event)) {\n startMarquee(event, px, py)\n return\n }\n // Grabbing an edge near its endpoint starts a reconnection (takes priority\n // over selecting the edge body).\n const endpointHit = edgeRenderer.pickEndpoint(px, py)\n if (endpointHit) {\n const edge = store.edges.get(endpointHit.edgeId)\n const reconnectable = edge?.reconnectable ?? reconnectRef.current.edgesReconnectable\n if (edge && reconnectable) {\n beginReconnect(edge, endpointHit.end)\n return\n }\n }\n // Clicking a selectable edge selects it instead of panning. An edge with\n // `selectable: false` is click-through (still deselects on empty space below).\n const hitEdge = edgeRenderer.pick(px, py)\n if (hitEdge && store.edges.get(hitEdge)?.selectable !== false) {\n store.selectEdge(hitEdge)\n return\n }\n // Empty space: deselect, then marquee or pan per config.\n store.selectNode(null)\n if (selectionOnDrag) {\n startMarquee(event, px, py)\n return\n }\n if (panButtons.includes(0)) pan.start(event)\n }\n const onPointerMove = (event: PointerEvent) => {\n const rect = pane.getBoundingClientRect()\n const px = event.clientX - rect.left\n const py = event.clientY - rect.top\n\n if (marquee.isActive()) {\n marquee.move(px, py)\n return\n }\n if (pan.isPanning()) {\n pan.move(event)\n return\n }\n // Hover feedback: pointer cursor + highlight when over an edge (but not\n // over a node or the post-marquee selection box, and not mid-connection).\n if (store.getPending()) return\n const overNode =\n event.target instanceof Element &&\n event.target.closest(`${SELECTOR.node}, ${SELECTOR.nodesSelection}`)\n let overEdge = overNode ? null : edgeRenderer.pick(px, py)\n // Hysteresis: hover is *acquired* at the tight pick tolerance, but *kept*\n // while the pointer stays loosely near the hovered edge or within its\n // endpoint radius (even across a node border) — so traveling to a grab\n // bubble doesn't drop the affordance mid-way. Hover is never acquired\n // from proximity alone: a cold press on an occupied handle still means\n // \"new connection\".\n if (!overEdge && hoveredEdgeId) {\n const near =\n edgeRenderer.pick(px, py, HOVER_KEEP_TOLERANCE) === hoveredEdgeId ||\n edgeRenderer.pickEndpoint(px, py)?.edgeId === hoveredEdgeId\n if (near) overEdge = hoveredEdgeId\n }\n pane.style.cursor = overEdge ? \"pointer\" : \"\"\n setEdgeHover(overEdge)\n }\n const onPointerUp = (event: PointerEvent) => {\n if (marquee.isActive()) {\n marquee.end(event)\n return\n }\n pan.end(event)\n }\n\n // Read through the params ref so toggling `snapGrid` doesn't tear down and\n // re-install every pane listener this effect owns.\n const onKeyDown = createKeyboardHandler(store, () => reconnectRef.current.snapGrid)\n\n // Programmatic focus (store.setFocusedNode) moves real DOM focus to the\n // node's wrapper. A culled node has no DOM — center the viewport on it and\n // focus once the next culling pass mounts it. Wrapper-driven focus (the\n // user tabbing) re-enters here with the element already focused: no-op.\n let focusRetryFrame = 0\n const unsubscribeFocus = store.subscribeFocus((id) => {\n if (focusRetryFrame) {\n cancelAnimationFrame(focusRetryFrame)\n focusRetryFrame = 0\n }\n if (id === null) return\n const el = store.getNodeElement(id)\n if (el) {\n if (document.activeElement !== el) el.focus()\n return\n }\n controls.centerNode(id)\n let tries = 0\n const attempt = () => {\n focusRetryFrame = 0\n const mounted = store.getNodeElement(id)\n if (mounted) {\n mounted.focus()\n return\n }\n if (++tries < 10) focusRetryFrame = requestAnimationFrame(attempt)\n }\n focusRetryFrame = requestAnimationFrame(attempt)\n })\n\n // Swallow the context menu after a right-button pan actually moved.\n const onContextMenu = (event: MouseEvent) => {\n if (!pan.suppressNextContextMenu()) return\n event.preventDefault()\n event.stopPropagation()\n }\n // Track non-modifier keys for `selectionKeys`; clear on blur so a key held\n // across a focus change can't get stuck.\n const onTrackKeyDown = (event: KeyboardEvent) => pressedKeys.add(event.key)\n const onTrackKeyUp = (event: KeyboardEvent) => pressedKeys.delete(event.key)\n const clearPressedKeys = () => pressedKeys.clear()\n\n const resizer = createResizeController({\n pane,\n bgCanvas,\n size,\n edgeRenderer,\n foregroundRenderer,\n onResize: sizeCursorLayer,\n schedule,\n })\n\n pane.addEventListener(\"wheel\", zoom.onWheel, { passive: false })\n pane.addEventListener(\"pointerdown\", onPointerDown)\n pane.addEventListener(\"pointermove\", onPointerMove)\n pane.addEventListener(\"pointerup\", onPointerUp)\n pane.addEventListener(\"pointercancel\", onPointerUp)\n pane.addEventListener(\"contextmenu\", onContextMenu, { capture: true })\n window.addEventListener(\"keydown\", onKeyDown)\n window.addEventListener(\"keydown\", onTrackKeyDown)\n window.addEventListener(\"keyup\", onTrackKeyUp)\n window.addEventListener(\"blur\", clearPressedKeys)\n\n return () => {\n resizer.dispose()\n store.bindRenderRequester(() => {})\n store.bindCursorRenderRequester(null)\n store.bindReconnectDelegate(null)\n unsubscribeFocus()\n if (focusRetryFrame) cancelAnimationFrame(focusRetryFrame)\n if (frame) cancelAnimationFrame(frame)\n layerHint.dispose()\n pane.removeEventListener(\"wheel\", zoom.onWheel)\n pane.removeEventListener(\"pointerdown\", onPointerDown)\n pane.removeEventListener(\"pointermove\", onPointerMove)\n pane.removeEventListener(\"pointerup\", onPointerUp)\n pane.removeEventListener(\"pointercancel\", onPointerUp)\n pane.removeEventListener(\"contextmenu\", onContextMenu, { capture: true })\n window.removeEventListener(\"keydown\", onKeyDown)\n window.removeEventListener(\"keydown\", onTrackKeyDown)\n window.removeEventListener(\"keyup\", onTrackKeyUp)\n window.removeEventListener(\"blur\", clearPressedKeys)\n marquee.dispose()\n edgeRenderer.dispose()\n foregroundRenderer.dispose()\n }\n }, [\n store,\n controls,\n paneRef,\n nodeContainerRef,\n backgroundCanvasRef,\n edgeCanvasRef,\n foregroundCanvasRef,\n cursorCanvasRef,\n scrollToPan,\n zoomSpeed,\n minZoom,\n maxZoom,\n gridGap,\n edgeTypes,\n defaultEdgeOptions,\n anchorOptions,\n createEdgeRenderer,\n panButtons,\n selectionOnDrag,\n selectionKeys,\n multiSelectionKeys,\n ])\n\n return { visibleIds, controls, getViewportElements }\n}\n\ntype BuildViewportQueryParams = {\n store: RivetStore\n sizeRef: RefObject<{ width: number; height: number; dpr: number }>\n lanesRef: RefObject<ResolvedLane[]>\n}\n\n/**\n * Build the stable `getViewportElements` query. It reads the live pane size,\n * lanes, and viewport from refs on every call, so it never needs to subscribe\n * to viewport changes — inspecting the viewport costs nothing until you ask.\n */\nfunction buildViewportQuery({\n store,\n sizeRef,\n lanesRef,\n}: BuildViewportQueryParams): () => ViewportElements {\n return () => {\n const { width, height } = sizeRef.current\n const rect = visibleWorldRect(store.getViewport(), width, height)\n\n const nodes: RivetNode[] = []\n for (const node of store.nodes.values()) {\n if (rectsIntersect(store.getNodeRect(node.id), rect)) nodes.push(node)\n }\n\n const lanes: VisibleLane[] = []\n for (const lane of lanesRef.current) {\n // Lanes paint as full-viewport-width bands, so only vertical overlap decides\n // visibility. `lane.x`/`lane.width` are nominal and must NOT gate it — else a\n // lane vanishes from the query once you pan past its nominal right edge.\n const overlapH =\n Math.min(lane.top + lane.height, rect.y + rect.height) - Math.max(lane.top, rect.y)\n if (overlapH <= 0) continue\n lanes.push({ ...lane, visibleArea: overlapH * rect.width })\n }\n lanes.sort((a, b) => b.visibleArea - a.visibleArea)\n\n return { rect, nodes, lanes }\n }\n}\n\ntype BuildControlsParams = {\n store: RivetStore\n sizeRef: RefObject<{ width: number; height: number; dpr: number }>\n minZoom: number\n maxZoom: number\n}\n\nconst sameViewport = (a: Viewport, b: Viewport): boolean =>\n a.x === b.x && a.y === b.y && a.zoom === b.zoom\n\n/** Ease-in-out cubic — the standard smooth accel/decel curve for viewport tweens. */\nconst easeInOutCubic = (t: number): number => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2)\n\n/**\n * The imperative viewport controls. Kept out of the effect so they're stable\n * across renders; they read the live pane size from `sizeRef`.\n */\nfunction buildControls({ store, sizeRef, minZoom, maxZoom }: BuildControlsParams): RivetControls {\n // In-flight viewport tween. `written` is the last value we set, so the loop\n // can detect when something else (a user pan/zoom, another control) moved the\n // viewport and bail rather than fight it.\n let animId: number | null = null\n let written: Viewport | null = null\n\n const cancelAnim = () => {\n if (animId !== null) cancelAnimationFrame(animId)\n animId = null\n written = null\n }\n\n const commit = (viewport: Viewport) => {\n store.setViewport(viewport)\n store.requestRender()\n }\n\n /** Move to `target`, instantly or tweened over `duration` ms. */\n const applyViewport = (target: Viewport, duration?: number) => {\n cancelAnim()\n const from = store.getViewport()\n if (!duration || duration <= 0 || sameViewport(from, target)) {\n commit(target)\n return\n }\n const start = performance.now()\n const step = (now: number) => {\n // Someone else drove the viewport since our last frame — yield to them.\n if (written && !sameViewport(store.getViewport(), written)) {\n animId = null\n written = null\n return\n }\n const t = Math.min(1, (now - start) / duration)\n const e = easeInOutCubic(t)\n commit({\n x: from.x + (target.x - from.x) * e,\n y: from.y + (target.y - from.y) * e,\n zoom: from.zoom + (target.zoom - from.zoom) * e,\n })\n // Read back post-clamp so divergence detection compares apples to apples.\n written = store.getViewport()\n if (t < 1) {\n animId = requestAnimationFrame(step)\n } else {\n animId = null\n written = null\n }\n }\n animId = requestAnimationFrame(step)\n }\n\n const zoomToLevel = (nextZoom: number) => {\n cancelAnim()\n const { width, height } = sizeRef.current\n const anchor = { x: width / 2, y: height / 2 }\n commit(zoomAt(store.getViewport(), anchor, nextZoom, minZoom, maxZoom))\n }\n\n /** Zoom+pan so a world rect fills the pane (minus padding) and sits centered. */\n const frameBounds = (rect: Rect, options?: FitViewOptions) => {\n const { width, height } = sizeRef.current\n if (width === 0 || height === 0) return\n const padding = options?.padding ?? 0.1\n const availWidth = width * (1 - padding * 2)\n const availHeight = height * (1 - padding * 2)\n // Guard degenerate (zero-size) bounds so we don't divide by zero.\n const fitZoom = Math.min(\n rect.width > 0 ? availWidth / rect.width : maxZoom,\n rect.height > 0 ? availHeight / rect.height : maxZoom,\n )\n const zoom = clamp(fitZoom, minZoom, options?.maxZoom ?? maxZoom)\n const centerX = rect.x + rect.width / 2\n const centerY = rect.y + rect.height / 2\n applyViewport(\n { zoom, x: width / 2 - centerX * zoom, y: height / 2 - centerY * zoom },\n options?.duration,\n )\n }\n\n /** World bounding rect over a set of node ids, or null when none exist. */\n const boundsOfNodes = (ids: Iterable<NodeId>): Rect | null =>\n boundingRect([...ids].map((id) => store.getNodeRect(id)))\n\n return {\n zoomIn: () => zoomToLevel(store.getViewport().zoom * ZOOM_STEP),\n zoomOut: () => zoomToLevel(store.getViewport().zoom / ZOOM_STEP),\n zoomTo: (zoom) => zoomToLevel(zoom),\n fitView: (options) => {\n const rect = boundsOfNodes(store.nodes.keys())\n if (rect) frameBounds(rect, options)\n },\n fitSelection: (options) => {\n const rect = boundsOfNodes(store.getSelectedNodes())\n if (rect) frameBounds(rect, options)\n },\n fitBounds: (rect, options) => frameBounds(rect, options),\n centerNode: (id, options) => {\n if (!store.nodes.has(id)) return\n const { width, height } = sizeRef.current\n if (width === 0 || height === 0) return\n\n const box = store.getNodeRect(id)\n const zoom = clamp(options?.zoom ?? store.getViewport().zoom, minZoom, maxZoom)\n const centerX = box.x + box.width / 2\n const centerY = box.y + box.height / 2\n applyViewport(\n { zoom, x: width / 2 - centerX * zoom, y: height / 2 - centerY * zoom },\n options?.duration,\n )\n },\n getViewport: () => store.getViewport(),\n setViewport: (viewport) => {\n cancelAnim()\n commit(viewport)\n },\n }\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\"\nimport type { RivetStore } from \"../store\"\nimport {\n flattenLanes,\n type ResolvedLane,\n type ResolvedMargin,\n type ResolvedSwimlaneGroup,\n requiredLaneHeight,\n resolveMargin,\n resolveSwimlanes,\n} from \"../swimlane/lanes\"\nimport type { SwimlaneGroup, SwimlaneMargin, SwimlaneSizeChange } from \"../types\"\n\nexport type UseSwimlanesParams = {\n store: RivetStore\n swimlane?: SwimlaneGroup[]\n swimlaneMargin?: number | SwimlaneMargin\n swimlaneResizable?: boolean\n clampToSwimlane?: boolean\n /** Fraction of the last lane kept in view at the bottom-scroll stop. */\n swimlaneBottomReveal: number\n onSwimlaneSizeChange?: (change: SwimlaneSizeChange) => void\n}\n\nexport type SwimlanesResult = {\n /** Resolved groups (header + lanes, world space). Empty when unused. */\n groups: ResolvedSwimlaneGroup[]\n /** Every group's lanes, flattened — the clamp targets. */\n lanes: ResolvedLane[]\n /** Inner clearance kept between a clamped node and its lane edges. */\n margin: ResolvedMargin\n /** Whether node drags are bounded to a lane (clamp requested AND lanes exist). */\n clampEnabled: boolean\n /** Whether lanes show a bottom resize handle. */\n resizableEnabled: boolean\n /**\n * Resize a lane, floored at the height needed to keep its lowest node inside.\n * `commit` fires `onSwimlaneSizeChange`; `reason` tags it (`\"resize\"` drag vs\n * `\"autofit\"` fit-to-content).\n */\n resizeSwimlane: (\n laneId: string,\n height: number,\n commit: boolean,\n reason?: SwimlaneSizeChange[\"reason\"],\n ) => void\n}\n\n/**\n * Owns the swimlane subsystem: live per-lane heights (seeded from / overriding\n * the `swimlane` prop), resolution to world geometry, the resize floor, auto-fit\n * growth to contain nodes, and the swimlane-aware viewport clamp. Lane sizing is\n * graph-owned React state, notified out via `onSwimlaneSizeChange`.\n */\nexport function useSwimlanes(params: UseSwimlanesParams): SwimlanesResult {\n const { store, swimlane, swimlaneMargin, swimlaneResizable } = params\n const { clampToSwimlane, swimlaneBottomReveal, onSwimlaneSizeChange } = params\n\n // Live height per lane (seeded from / overriding the `swimlane` prop) so sizing\n // is owned by the graph — user resizes and auto-fit write here.\n const [laneHeights, setLaneHeights] = useState<Record<string, number>>({})\n const resizableEnabled = (swimlaneResizable ?? true) && Boolean(swimlane?.length)\n\n const effectiveSwimlane = useMemo<SwimlaneGroup[] | undefined>(() => {\n if (!swimlane) return undefined\n if (Object.keys(laneHeights).length === 0) return swimlane\n return swimlane.map((group) => ({\n ...group,\n lanes: group.lanes.map((lane) => ({\n ...lane,\n size: laneHeights[lane.id] ?? lane.size,\n })),\n }))\n }, [swimlane, laneHeights])\n\n const groups = useMemo(\n () => (effectiveSwimlane ? resolveSwimlanes(effectiveSwimlane) : []),\n [effectiveSwimlane],\n )\n const lanes = useMemo(() => flattenLanes(groups), [groups])\n const margin = useMemo(() => resolveMargin(swimlaneMargin), [swimlaneMargin])\n const clampEnabled = (clampToSwimlane ?? true) && lanes.length > 0\n\n // Refs so the stable `resizeSwimlane` and the auto-fit subscription read live\n // geometry/margins/callbacks without churning identity on every resize frame.\n const lanesRef = useRef(lanes)\n lanesRef.current = lanes\n const marginRef = useRef(margin)\n marginRef.current = margin\n const onSizeChangeRef = useRef(onSwimlaneSizeChange)\n onSizeChangeRef.current = onSwimlaneSizeChange\n\n const resizeSwimlane = useCallback<SwimlanesResult[\"resizeSwimlane\"]>(\n (laneId, height, commit, reason = \"resize\") => {\n const lane = lanesRef.current.find((l) => l.id === laneId)\n if (!lane) return\n // Can't shrink below what's needed to keep the lane's lowest node inside.\n const min = requiredLaneHeight(lane, store.nodes.values(), marginRef.current.bottom)\n const next = Math.max(min, height)\n setLaneHeights((prev) => (prev[laneId] === next ? prev : { ...prev, [laneId]: next }))\n if (commit) onSizeChangeRef.current?.({ laneId, height: next, reason })\n },\n [store],\n )\n\n // Auto-fit: when a node grows past its lane's bottom (with margin), grow the\n // lane to contain it. Expand-only, and paused during a node drag so a node's\n // transient position can't inflate lanes. Runs on rendered frames (node\n // measure, move-commit, add/remove) — not continuously.\n useEffect(() => {\n if (!clampEnabled) return\n return store.subscribeFrame(() => {\n if (store.isNodeDragging()) return\n const marginBottom = marginRef.current.bottom\n const grown: Record<string, number> = {}\n for (const lane of lanesRef.current) {\n const need = requiredLaneHeight(lane, store.nodes.values(), marginBottom)\n if (need > lane.height + 0.5) grown[lane.id] = need\n }\n const entries = Object.entries(grown)\n if (entries.length === 0) return\n setLaneHeights((prev) => ({ ...prev, ...grown }))\n for (const [id, height] of entries) {\n onSizeChangeRef.current?.({ laneId: id, height, reason: \"autofit\" })\n }\n })\n }, [store, clampEnabled])\n\n // With clamping on, bound panning to the swimlane box: top-left corner stays\n // pinned (no scroll up/left past the lanes) and the bottom stops once only\n // `swimlaneBottomReveal` of the last lane remains in view.\n useEffect(() => {\n if (!clampEnabled) {\n store.setViewportClamp(null)\n return\n }\n const minX = Math.min(...groups.map((group) => group.x))\n const minY = Math.min(...groups.map((group) => group.top))\n const last = lanes.reduce((a, b) => (b.top + b.height > a.top + a.height ? b : a))\n const maxY = last.top + (1 - swimlaneBottomReveal) * last.height\n store.setViewportClamp({ minX, minY, maxY })\n return () => store.setViewportClamp(null)\n }, [store, clampEnabled, groups, lanes, swimlaneBottomReveal])\n\n return { groups, lanes, margin, clampEnabled, resizableEnabled, resizeSwimlane }\n}\n","import type {\n DefaultEdgeOptions,\n EdgeDrawExtras,\n EdgeEnd,\n EdgeId,\n EdgeMarker,\n EdgeRenderer,\n EdgeRendererFactory,\n EdgeRendererOptions,\n EdgeTypes,\n NodeId,\n RivetEdge,\n RivetNode,\n Vec2,\n Viewport,\n} from \"../types\"\nimport {\n buildEdges,\n buildPendingPath,\n distanceToPolyline,\n EDGE_WIDTH,\n PENDING_COLOR,\n type ResolvedEdge,\n} from \"./edge-geometry\"\nimport { BUILTIN_EDGE_TYPES } from \"./edge-paths\"\n\nconst PICK_TOLERANCE = 6\nconst ENDPOINT_RADIUS = 12\nconst ARROW_SIZE = 9\n/** px/second the marching-dash animation advances. */\nconst DASH_SPEED = 40\n\n/**\n * The default {@link EdgeRenderer}. Strokes each edge's sampled polyline (built by\n * its {@link EdgePathFn}) on a 2D canvas, with per-edge style, arrowheads, and an\n * animated dash. The geometry it draws comes from {@link buildEdges}, which is\n * backend-neutral.\n */\nexport class Canvas2DEdgeRenderer implements EdgeRenderer {\n private readonly ctx: CanvasRenderingContext2D\n private dpr = 1\n private width = 0\n private height = 0\n private readonly edgeTypes: EdgeTypes\n private readonly defaults: DefaultEdgeOptions\n /** Screen-space polylines from the last frame, keyed by edge id, for picking. */\n private readonly geometry = new Map<EdgeId, Vec2[]>()\n /** Screen-space endpoints per edge, for endpoint (reconnection) picking. */\n private readonly endpoints = new Map<EdgeId, { source: Vec2; target: Vec2 }>()\n /** Screen-space label anchor per edge that has a label. */\n private readonly labels = new Map<EdgeId, Vec2>()\n\n constructor(\n private readonly canvas: HTMLCanvasElement,\n options: EdgeRendererOptions = {},\n ) {\n const ctx = canvas.getContext(\"2d\")\n if (!ctx) throw new Error(\"rivet: 2D canvas context is unavailable\")\n this.ctx = ctx\n this.edgeTypes = { ...BUILTIN_EDGE_TYPES, ...options.edgeTypes }\n this.defaults = options.defaultEdgeOptions ?? {}\n }\n\n resize(width: number, height: number, dpr: number): void {\n this.width = width\n this.height = height\n this.dpr = dpr\n this.canvas.width = Math.max(1, Math.round(width * dpr))\n this.canvas.height = Math.max(1, Math.round(height * dpr))\n this.canvas.style.width = `${width}px`\n this.canvas.style.height = `${height}px`\n }\n\n /** Screen-space label anchors for the edges drawn last frame. */\n getLabels(): Map<EdgeId, Vec2> {\n return this.labels\n }\n\n /** Screen-space endpoints per edge from the last frame (reconnect affordance). */\n getEndpoints(): ReadonlyMap<EdgeId, { source: Vec2; target: Vec2 }> {\n return this.endpoints\n }\n\n draw(\n edges: RivetEdge[],\n nodes: Map<NodeId, RivetNode>,\n viewport: Viewport,\n extras?: EdgeDrawExtras,\n ): void {\n const ctx = this.ctx\n const now = performance.now()\n ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0)\n ctx.clearRect(0, 0, this.width, this.height)\n ctx.lineJoin = \"round\"\n ctx.lineCap = \"round\"\n this.geometry.clear()\n this.endpoints.clear()\n this.labels.clear()\n\n const resolved = buildEdges(edges, nodes, viewport, this.edgeTypes, this.defaults, extras)\n for (const edge of resolved) {\n this.geometry.set(edge.id, edge.points)\n this.endpoints.set(edge.id, { source: edge.source, target: edge.target })\n if (edge.label) this.labels.set(edge.id, edge.label)\n\n ctx.strokeStyle = edge.stroke\n ctx.lineWidth = edge.width\n ctx.globalAlpha = edge.opacity\n if (edge.animated) {\n ctx.setLineDash([8, 6])\n ctx.lineDashOffset = -((now / 1000) * DASH_SPEED) % 14\n } else if (edge.dash) {\n ctx.setLineDash(edge.dash)\n ctx.lineDashOffset = 0\n } else {\n ctx.setLineDash([])\n ctx.lineDashOffset = 0\n }\n\n strokePolyline(ctx, edge.points)\n\n // Markers use the solid stroke color at full alpha and no dash.\n ctx.setLineDash([])\n ctx.globalAlpha = 1\n const markerColor = ctx.strokeStyle\n if (edge.markerEnd) drawMarker(ctx, edge.points, \"end\", edge.markerEnd, markerColor)\n if (edge.markerStart) drawMarker(ctx, edge.points, \"start\", edge.markerStart, markerColor)\n }\n\n const pending = extras?.pending\n if (pending) {\n const points = buildPendingPath(pending, extras?.handles, viewport)\n ctx.strokeStyle = PENDING_COLOR\n ctx.lineWidth = EDGE_WIDTH\n ctx.globalAlpha = 1\n ctx.setLineDash([6, 4])\n strokePolyline(ctx, points)\n ctx.setLineDash([])\n }\n ctx.globalAlpha = 1\n ctx.setLineDash([])\n }\n\n pick(x: number, y: number, tolerance = PICK_TOLERANCE): EdgeId | null {\n for (const [id, points] of this.geometry) {\n if (distanceToPolyline({ x, y }, points) <= tolerance) return id\n }\n return null\n }\n\n pickEndpoint(x: number, y: number): { edgeId: EdgeId; end: EdgeEnd } | null {\n let best: { edgeId: EdgeId; end: EdgeEnd } | null = null\n let bestDist = ENDPOINT_RADIUS\n for (const [edgeId, ends] of this.endpoints) {\n const ds = Math.hypot(x - ends.source.x, y - ends.source.y)\n if (ds < bestDist) {\n bestDist = ds\n best = { edgeId, end: \"source\" }\n }\n const dt = Math.hypot(x - ends.target.x, y - ends.target.y)\n if (dt < bestDist) {\n bestDist = dt\n best = { edgeId, end: \"target\" }\n }\n }\n return best\n }\n\n dispose(): void {\n this.geometry.clear()\n this.endpoints.clear()\n this.labels.clear()\n }\n}\n\n/** The built-in {@link EdgeRendererFactory} — the default backend for `<Rivet>`. */\nexport const canvas2DEdgeRenderer: EdgeRendererFactory = (canvas, options) =>\n new Canvas2DEdgeRenderer(canvas, options)\n\nfunction strokePolyline(ctx: CanvasRenderingContext2D, points: Vec2[]): void {\n const first = points[0]\n if (!first) return\n ctx.beginPath()\n ctx.moveTo(first.x, first.y)\n for (let i = 1; i < points.length; i++) {\n const p = points[i]\n if (p) ctx.lineTo(p.x, p.y)\n }\n ctx.stroke()\n}\n\n/** Draw an arrowhead at the `start` or `end` of the polyline, facing outward. */\nfunction drawMarker(\n ctx: CanvasRenderingContext2D,\n points: Vec2[],\n at: \"start\" | \"end\",\n kind: Exclude<EdgeMarker, false>,\n color: string | CanvasGradient | CanvasPattern,\n): void {\n const tip = at === \"end\" ? points[points.length - 1] : points[0]\n const prev = at === \"end\" ? points[points.length - 2] : points[1]\n if (!tip || !prev) return\n const angle = Math.atan2(tip.y - prev.y, tip.x - prev.x)\n const spread = 0.5\n const left = {\n x: tip.x - ARROW_SIZE * Math.cos(angle - spread),\n y: tip.y - ARROW_SIZE * Math.sin(angle - spread),\n }\n const right = {\n x: tip.x - ARROW_SIZE * Math.cos(angle + spread),\n y: tip.y - ARROW_SIZE * Math.sin(angle + spread),\n }\n ctx.beginPath()\n ctx.moveTo(left.x, left.y)\n ctx.lineTo(tip.x, tip.y)\n ctx.lineTo(right.x, right.y)\n if (kind === \"arrowclosed\") {\n ctx.closePath()\n ctx.fillStyle = color\n ctx.fill()\n } else {\n ctx.strokeStyle = color\n ctx.stroke()\n }\n}\n","import {\n type CSSProperties,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport type { EdgeId } from \"../types\"\n\nconst overlayStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n overflow: \"hidden\",\n pointerEvents: \"none\",\n}\n\nconst labelStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n padding: \"1px 6px\",\n borderRadius: 4,\n background: \"rgba(255, 255, 255, 0.9)\",\n color: \"#0f172a\",\n fontSize: 11,\n lineHeight: 1.4,\n whiteSpace: \"nowrap\",\n pointerEvents: \"none\",\n}\n\nfunction sameIds(a: EdgeId[], b: EdgeId[]): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n\n/**\n * Renders `edge.label` text at each edge's midpoint. The renderer publishes\n * screen-space label anchors every frame (`store.setEdgeLabelAnchors`); this layer\n * repositions the divs imperatively on `subscribeFrame` so labels track pan/zoom\n * without a React re-render — only a change in *which* edges have labels re-renders.\n * The chip's look is the built-in style, under `defaultEdgeOptions.labelStyle`,\n * under the edge's own `labelStyle`.\n */\nexport function EdgeLabelLayer(): React.ReactElement {\n const { store, defaultEdgeOptions } = useRivetContext()\n const [ids, setIds] = useState<EdgeId[]>([])\n const refs = useRef(new Map<EdgeId, HTMLDivElement | null>())\n\n const position = useCallback(() => {\n const anchors = store.getEdgeLabelAnchors()\n for (const [id, el] of refs.current) {\n if (!el) continue\n const anchor = anchors.get(id)\n if (anchor) {\n el.style.display = \"\"\n el.style.transform = `translate(${anchor.x}px, ${anchor.y}px) translate(-50%, -50%)`\n } else {\n el.style.display = \"none\"\n }\n }\n }, [store])\n\n useEffect(() => {\n return store.subscribeFrame(() => {\n const anchors = store.getEdgeLabelAnchors()\n const next = [...anchors.keys()]\n setIds((prev) => (sameIds(prev, next) ? prev : next))\n position()\n })\n }, [store, position])\n\n // Position after every render so freshly mounted labels land immediately.\n useLayoutEffect(position)\n\n return (\n <div style={overlayStyle}>\n {ids.map((id) => {\n const edge = store.edges.get(id)\n if (!edge || edge.label === undefined) return null\n return (\n <div\n key={id}\n ref={(el) => {\n refs.current.set(id, el)\n }}\n style={{ ...labelStyle, ...defaultEdgeOptions?.labelStyle, ...edge.labelStyle }}\n >\n {String(edge.label)}\n </div>\n )\n })}\n </div>\n )\n}\n","import { alignRect } from \"../align\"\nimport { clampChildToParent, snapToGrid } from \"../graph\"\nimport type { RivetStore } from \"../store\"\nimport { clampNodeToLanes, type ResolvedLane, type ResolvedMargin } from \"../swimlane/lanes\"\nimport type { LaneChange, NodeId, Rect, Vec2 } from \"../types\"\n\n/** Pixels the pointer must travel before a press turns into a node drag. */\nconst DRAG_THRESHOLD = 4\n/** Screen-px gap within which a dragged node snaps to a neighbor's edge/center. */\nconst ALIGN_THRESHOLD = 6\n\nexport type GroupDragParams = {\n store: RivetStore\n /** Element that captures the pointer and carries the grab/grabbing cursor. */\n el: HTMLElement\n /** The initiating press — client coords and pointer id are read once. */\n event: { clientX: number; clientY: number; pointerId: number }\n /**\n * The node the press landed on, reported as the gesture's initiator. The\n * selection box has no single node, so it omits this and the first mover\n * stands in.\n */\n nodeId?: NodeId\n /** Grid to snap dragged nodes to (`[x, y]` world units), or null for free movement. */\n snapGrid: [number, number] | null\n /** Whether a single-node drag shows alignment guides and snaps to neighbors. */\n alignmentGuides: boolean\n swimlaneLanes: ResolvedLane[]\n clampToSwimlane: boolean\n swimlaneMargin: ResolvedMargin\n swimlaneLabelWidth: number\n onLaneChange?: (change: LaneChange) => void\n /** Called after each frame's (and the drop's) node repositioning. */\n onFrame?: () => void\n}\n\n/**\n * The selection-drag gesture: threshold-gated, then moves the selected movers\n * live (snap → clamp each frame) and commits them on release. Shared by a press\n * on a node ({@link NodeWrapper}) and on the post-marquee selection box\n * ({@link NodesSelection}), so the two drag paths behave identically.\n * Selection itself is the caller's concern — by the time this starts, the\n * nodes to move are exactly the selected ones.\n */\nexport function startGroupDrag(params: GroupDragParams): void {\n const { store, el, snapGrid, alignmentGuides, onLaneChange, onFrame } = params\n const { swimlaneLanes, clampToSwimlane, swimlaneMargin, swimlaneLabelWidth } = params\n\n const { zoom } = store.getViewport()\n const originX = params.event.clientX\n const originY = params.event.clientY\n const pointerId = params.event.pointerId\n\n // With swimlanes, nodes follow the cursor freely during the drag and snap\n // into a single lane on drop (the lane they land in decides membership).\n const clampActive = clampToSwimlane && swimlaneLanes.length > 0\n\n // The drag doesn't begin until the pointer moves past this threshold. Below it\n // the press stays a plain click, so a click / double-click on the node (to edit\n // a title, say) is never swallowed — and the pointer isn't captured.\n let started = false\n let starts = new Map<NodeId, Vec2>()\n let affected = new Set<NodeId>()\n /** The node reported as the gesture's initiator, once it has one. */\n let initiator: NodeId | undefined\n /**\n * A mover this gesture definitely holds, for the yield check below. Distinct\n * from `initiator`: the grabbed node may be a child riding along inside a\n * selected ancestor, in which case it's reported but never held itself.\n */\n let anchor: NodeId | undefined\n\n const repositionAffected = () => {\n for (const affectedId of affected) {\n const affectedEl = store.getNodeElement(affectedId)\n if (!affectedEl) continue\n const world = store.getNodeWorldPosition(affectedId)\n affectedEl.style.transform = `translate(${world.x}px, ${world.y}px)`\n }\n onFrame?.()\n }\n\n const beginDrag = (): boolean => {\n // The movers are the selected nodes whose ancestors aren't also selected — a\n // selected child of a selected parent just rides along, so moving it too would\n // double its travel. Their `position` (relative to a parent) changes.\n // A peer's lock drops a node out of the group rather than blocking the drag:\n // the rest of the selection still moves, which is what the pointer asked for.\n const movers = store\n .getMovers(store.getSelectedNodes())\n .filter((moverId) => store.locks.allows(moverId, \"drag\"))\n if (movers.length === 0) return false\n started = true\n starts = new Map<NodeId, Vec2>()\n for (const moverId of movers) {\n const moverNode = store.nodes.get(moverId)\n if (moverNode) starts.set(moverId, moverNode.position)\n }\n // Elements to reposition each frame: the movers plus every descendant (their\n // world position shifts with the mover even though their own offset doesn't).\n affected = new Set<NodeId>()\n for (const moverId of movers) {\n affected.add(moverId)\n for (const descendant of store.getDescendantIds(moverId)) affected.add(descendant)\n }\n // Pause swimlane auto-fit while dragging so a node's transient position can't\n // grow the lane; it fits (if needed) only once it's dropped and clamped.\n store.setNodeDragging(true)\n // Only the movers are held: a descendant rides along in world space, but its\n // own (parent-relative) position isn't what this gesture is writing.\n initiator = params.nodeId ?? movers[0]\n anchor = movers[0]\n if (initiator) store.beginNodeGesture(initiator, movers)\n el.setPointerCapture(pointerId)\n el.style.cursor = \"grabbing\"\n // The press never preventDefault()s (clicks and focus must keep working),\n // so by now the browser may have armed a native text selection at the\n // press point. Drop it and suppress selection for the drag's duration.\n window.getSelection()?.removeAllRanges()\n document.body.style.userSelect = \"none\"\n document.body.style.webkitUserSelect = \"none\"\n return true\n }\n\n /** Undo everything {@link beginDrag} set up, without committing a position. */\n const teardown = () => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n if (!started) return\n started = false\n el.style.cursor = \"grab\"\n document.body.style.userSelect = \"\"\n document.body.style.webkitUserSelect = \"\"\n store.setAlignmentGuides([])\n store.setNodeDragging(false)\n if (el.hasPointerCapture(pointerId)) el.releasePointerCapture(pointerId)\n }\n\n /**\n * True once the gesture no longer holds its nodes — the consumer yielded them\n * with `releaseNodeGesture` after a lock conflict. The pointer is still down,\n * so this is the only signal that the drag has to stop writing.\n */\n const yielded = (): boolean => anchor !== undefined && !store.isNodeHeld(anchor)\n\n const onMove = (moveEvent: PointerEvent) => {\n if (!started) {\n const moved = Math.hypot(moveEvent.clientX - originX, moveEvent.clientY - originY)\n if (moved < DRAG_THRESHOLD) return\n // Every mover was locked: the press stays a click and no drag begins.\n if (!beginDrag()) {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n return\n }\n }\n // Yielded mid-drag: leave the nodes where they are and let the holder's\n // writes land. Reverting would fight the position about to arrive.\n if (yielded()) {\n teardown()\n return\n }\n const dx = (moveEvent.clientX - originX) / zoom\n const dy = (moveEvent.clientY - originY) / zoom\n // Alignment guides apply to a single top-level node drag.\n const single = starts.size === 1\n for (const [moverId, start] of starts) {\n const moverNode = store.nodes.get(moverId)\n let next = { x: start.x + dx, y: start.y + dy }\n // Snap to the grid first, then confine — the constraint always wins.\n if (snapGrid) next = snapToGrid(next, snapGrid)\n // `extent: \"parent\"` confines the child live, so it can't be dragged out.\n if (moverNode?.parentId && moverNode.extent === \"parent\" && moverNode.size) {\n next = clampToParent(store, moverNode.parentId, next, moverNode.size)\n } else if (alignmentGuides && single && moverNode?.size && !moverNode.parentId) {\n // Snap edges/center to nearby nodes and publish the guides to draw.\n const movingRect: Rect = {\n x: next.x,\n y: next.y,\n width: moverNode.size.width,\n height: moverNode.size.height,\n }\n const statics: Rect[] = []\n for (const [otherId, other] of store.nodes) {\n if (otherId === moverId || other.parentId) continue\n statics.push(store.getNodeRect(otherId))\n }\n const { offset, guides } = alignRect(movingRect, statics, ALIGN_THRESHOLD / zoom)\n next = { x: next.x + offset.x, y: next.y + offset.y }\n store.setAlignmentGuides(guides)\n }\n // Update the store (so canvas edges follow); DOM nodes move imperatively.\n store.moveNode(moverId, next, false)\n }\n repositionAffected()\n }\n const onUp = () => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n // Never crossed the threshold — it was a click, not a drag. Leave it for the\n // element's own onClick / onDoubleClick handlers.\n if (!started) return\n // Released between the last move and the drop: the commit below would write\n // geometry this client no longer owns.\n if (yielded()) {\n teardown()\n return\n }\n el.style.cursor = \"grab\"\n document.body.style.userSelect = \"\"\n document.body.style.webkitUserSelect = \"\"\n store.setAlignmentGuides([])\n // Clear the drag flag before the commit below so the resulting frame runs\n // auto-fit against the node's final, clamped position.\n store.setNodeDragging(false)\n for (const [moverId, start] of starts) {\n const moverNode = store.nodes.get(moverId)\n let position = moverNode?.position ?? start\n\n if (moverNode?.parentId && moverNode.extent === \"parent\" && moverNode.size) {\n // Confine a child to its parent's box (position is parent-relative).\n position = clampToParent(store, moverNode.parentId, position, moverNode.size)\n } else if (clampActive && moverNode?.size) {\n // Snap into a lane (the drop decides membership → cross-lane re-parent).\n const result = clampNodeToLanes(\n position,\n moverNode.size,\n swimlaneLanes,\n swimlaneMargin,\n swimlaneLabelWidth,\n )\n position = result.position\n const previousLaneId = store.setNodeLane(moverId, result.laneId)\n if (previousLaneId !== false) {\n onLaneChange?.({ nodeId: moverId, laneId: result.laneId, previousLaneId })\n }\n }\n store.moveNode(moverId, position, true)\n }\n // Released after the commits: the drop is the gesture's last write, and it\n // has to win against anything that arrived while the pointer was down.\n if (initiator) store.endNodeGesture(initiator, [...starts.keys()])\n repositionAffected()\n }\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n}\n\n/** Read the parent's measured box and confine a child's position inside it. */\nexport function clampToParent(\n store: RivetStore,\n parentId: NodeId,\n position: Vec2,\n size: { width: number; height: number },\n): Vec2 {\n const parent = store.nodes.get(parentId)\n const parentSize = {\n width: parent?.width ?? parent?.size?.width ?? 0,\n height: parent?.height ?? parent?.size?.height ?? 0,\n }\n return clampChildToParent(position, size, parentSize)\n}\n","import { Fragment, useCallback, useSyncExternalStore } from \"react\"\nimport {\n ANCHOR_SIDES,\n type AnchorRecord,\n anchorDotHandleId,\n anchorHandleId,\n parseAnchorHandleId,\n type ResolvedAnchorOptions,\n strayPlacementPct,\n} from \"../anchor/registry\"\nimport { useRivetContext } from \"../context\"\nimport type { HandlePosition, NodeId } from \"../types\"\nimport { Handle } from \"./handle\"\n\n/** Fallback accent when an anchor registers without a color (matches Handle's border). */\nconst DEFAULT_ANCHOR_COLOR = \"#6366f1\"\n\n/**\n * Library-rendered chrome for a node's registered anchors — overlay elements\n * positioned from measured geometry, never injected into the node's content\n * (so a consumer's DOM, including a contentEditable, is left untouched):\n *\n * - **Grab dots** on the anchor element's line boxes, shown while the node is\n * hovered and the element is live. Each is a real handle that only *starts*\n * a connection; its id is rewritten to the stray id before an edge commits.\n * - **Stray handles** on the node perimeter — the persisted connection\n * points. One default-side handle when unconnected; once edges exist, one\n * per *connected* side. Rendered from retained geometry even while the\n * anchor is detached, so edges stay put during display unmounts. Suppressed\n * entirely for anchors registered with `strays: \"none\"`.\n */\nexport function NodeAnchors({ nodeId }: { nodeId: NodeId }): React.ReactElement | null {\n const { store, anchorOptions } = useRivetContext()\n\n const subscribeAnchors = useCallback(\n (listener: () => void) => store.subscribeNodeAnchors(nodeId, listener),\n [store, nodeId],\n )\n const getAnchorsVersion = useCallback(() => store.getNodeAnchorsVersion(nodeId), [store, nodeId])\n useSyncExternalStore(subscribeAnchors, getAnchorsVersion, getAnchorsVersion)\n useSyncExternalStore(store.subscribeEdges, store.getEdgesVersion, store.getEdgesVersion)\n\n const records = store.getNodeAnchors(nodeId)\n if (records.length === 0) return null\n\n const dotsVisible = Boolean(store.nodes.get(nodeId)?.hovered)\n\n // Sides with at least one edge, per anchor — only persisted stray handles\n // count (a dot id never reaches an edge).\n const connectedSides = new Map<string, HandlePosition[]>()\n for (const edge of store.edges.values()) {\n const ends = [\n edge.source === nodeId ? parseAnchorHandleId(edge.sourceHandle) : null,\n edge.target === nodeId ? parseAnchorHandleId(edge.targetHandle) : null,\n ]\n for (const end of ends) {\n if (!end) continue\n const sides = connectedSides.get(end.anchorId) ?? []\n if (!sides.includes(end.side)) sides.push(end.side)\n connectedSides.set(end.anchorId, sides)\n }\n }\n\n return (\n <>\n {records.map((record) => (\n <Fragment key={record.anchorId}>\n <AnchorDots record={record} options={anchorOptions} visible={dotsVisible} />\n {record.strays !== \"none\" && (\n <AnchorStrayHandles\n record={record}\n options={anchorOptions}\n connectedSides={connectedSides.get(record.anchorId)}\n />\n )}\n </Fragment>\n ))}\n </>\n )\n}\n\n/**\n * The in-content grab dots, from measured line rects: left/top on the first\n * line box, right/bottom on the last. Hidden while the anchor is detached —\n * the element is unmounted, so the retained geometry may be stale.\n */\nfunction AnchorDots(props: {\n record: AnchorRecord\n options: ResolvedAnchorOptions\n visible: boolean\n}): React.ReactElement | null {\n const { record, options } = props\n if (!record.geometry || !record.element?.isConnected) return null\n const dots = record.geometry.dots\n return (\n <>\n {ANCHOR_SIDES.map((side) => {\n const dot = dots[side]\n return (\n <Handle\n // The measured position participates in the key: moving a dot\n // remounts its handle so the registered world offset re-measures\n // (Handle only re-measures on mount and box resizes).\n key={`${side}:${dot.xPct.toFixed(1)},${dot.yPct.toFixed(1)}`}\n id={anchorDotHandleId(record.anchorId, side)}\n type=\"either\"\n position={side}\n style={{\n left: `${dot.xPct}%`,\n top: `${dot.yPct}%`,\n right: \"auto\",\n bottom: \"auto\",\n transform: \"translate(-50%, -50%)\",\n width: options.dotSize,\n height: options.dotSize,\n background: record.color ?? DEFAULT_ANCHOR_COLOR,\n border: \"none\",\n opacity: props.visible ? 1 : 0,\n transition: \"opacity 150ms\",\n }}\n />\n )\n })}\n </>\n )\n}\n\n/**\n * The persisted perimeter handles, placed along each side near the anchor's\n * measured position — nudged out of the side-center keep-out band (where the\n * node's own handles sit) and off the corners.\n */\nfunction AnchorStrayHandles(props: {\n record: AnchorRecord\n options: ResolvedAnchorOptions\n connectedSides: HandlePosition[] | undefined\n}): React.ReactElement | null {\n const { record, options } = props\n const geometry = record.geometry\n if (!geometry) return null\n const sides =\n props.connectedSides && props.connectedSides.length > 0\n ? props.connectedSides\n : [options.defaultSide]\n return (\n <>\n {sides.map((side) => {\n const placed = strayPlacementPct(geometry, side, options)\n const axis =\n side === \"top\" || side === \"bottom\" ? { left: `${placed}%` } : { top: `${placed}%` }\n return (\n <Handle\n key={`${side}:${placed.toFixed(1)}`}\n id={anchorHandleId(record.anchorId, side)}\n type=\"either\"\n position={side}\n style={{\n width: options.strayHandleSize,\n height: options.strayHandleSize,\n background: record.color ?? DEFAULT_ANCHOR_COLOR,\n border: \"none\",\n ...axis,\n }}\n />\n )\n })}\n </>\n )\n}\n","import {\n type CSSProperties,\n memo,\n type FocusEvent as ReactFocusEvent,\n type KeyboardEvent as ReactKeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\"\nimport { SELECTOR } from \"../constants\"\nimport { RivetNodeContext, type RivetNodeContextValue, useRivetContext } from \"../context\"\nimport { snapToGrid } from \"../graph\"\nimport { clampToParent, startGroupDrag } from \"../input/group-drag\"\nimport { ARROW_DIRS, ARROW_STEP, ARROW_STEP_SHIFT } from \"../input/keyboard\"\nimport { keyHeld } from \"../input/keys\"\nimport type { NodeId, Vec2 } from \"../types\"\nimport { DefaultNode } from \"./default-node\"\nimport { BUILTIN_NODE_TYPES } from \"./group-node\"\nimport { NodeAnchors } from \"./node-anchors\"\n\nconst wrapperStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n pointerEvents: \"auto\",\n cursor: \"grab\",\n userSelect: \"none\",\n}\n\nexport type NodeWrapperProps = {\n id: NodeId\n}\n\n/**\n * Positions one node in world space, handles dragging, and reports its size.\n *\n * It subscribes to *only its own* node via `useSyncExternalStore` and is\n * memoized, so a change to any other node — or a re-render of the layer when the\n * visible set changes — never re-renders this one.\n */\nexport const NodeWrapper = memo(function NodeWrapper({ id }: NodeWrapperProps) {\n const { store, nodeTypes, onLaneChange, multiSelectionKeys, snapGrid } = useRivetContext()\n const { swimlaneLanes, clampToSwimlane, swimlaneMargin, swimlaneLabelWidth, alignmentGuides } =\n useRivetContext()\n const { announce, nodeDescriptionId } = useRivetContext()\n const ref = useRef<HTMLDivElement>(null)\n\n // Keyboard grab-to-move (ARIA drag-and-drop pattern): Enter/Space picks the\n // node up, arrows move it, Enter drops, Escape reverts to these origins.\n // Origins cover every mover (a grabbed node in a multi-selection moves the\n // group, like a pointer drag). `grabbed` mirrors the ref for rendering.\n const [grabbed, setGrabbed] = useState(false)\n const grabOrigins = useRef<Map<NodeId, Vec2> | null>(null)\n\n const nodeName = () => {\n const node = store.nodes.get(id)\n return node?.ariaLabel ?? `node ${id}`\n }\n\n const grab = () => {\n const movers = store\n .getMovers(store.isNodeSelected(id) ? store.getSelectedNodes() : [id])\n .filter((moverId) => store.locks.allows(moverId, \"drag\"))\n if (movers.length === 0) {\n announce(`${nodeName()} is locked by someone else.`)\n return\n }\n const origins = new Map<NodeId, Vec2>()\n for (const moverId of movers) {\n const mover = store.nodes.get(moverId)\n if (mover) origins.set(moverId, { ...mover.position })\n }\n grabOrigins.current = origins\n setGrabbed(true)\n // A grab holds its movers exactly like a pointer drag: arrow keys are this\n // client's geometry until it drops, so remote writes to it must not land.\n store.beginNodeGesture(id, movers)\n announce(`Grabbed ${nodeName()}. Use the arrow keys to move, Enter to drop, Escape to cancel.`)\n }\n\n const releaseGrab = (revert: boolean) => {\n const origins = grabOrigins.current\n grabOrigins.current = null\n setGrabbed(false)\n if (!origins) return\n if (revert) {\n for (const [moverId, origin] of origins) store.moveNode(moverId, origin, true)\n // Released after the reverting moves, so the gesture still owns its\n // geometry while they commit — the same order as a drop.\n store.endNodeGesture(id, [...origins.keys()])\n announce(\"Move cancelled.\")\n return\n }\n store.endNodeGesture(id, [...origins.keys()])\n const node = store.nodes.get(id)\n if (node) {\n const { x, y } = node.position\n announce(`Dropped ${nodeName()} at ${Math.round(x)}, ${Math.round(y)}.`)\n }\n }\n\n const subscribe = useCallback(\n (onChange: () => void) => store.subscribeNode(id, onChange),\n [store, id],\n )\n const getSnapshot = useCallback(() => store.getNodeVersion(id), [store, id])\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n // This node's holder, not the lock table's version: the registry notifies\n // every wrapper on any lock change, and comparing the holder id lets React\n // bail out of all but the one node that actually changed hands.\n const lockHolder = useSyncExternalStore(\n store.locks.subscribe,\n useCallback(() => store.locks.getHolder(id), [store, id]),\n useCallback(() => store.locks.getHolder(id), [store, id]),\n )\n\n const nodeContext = useMemo<RivetNodeContextValue>(() => ({ nodeId: id, wrapperRef: ref }), [id])\n\n // Report layout size (world units, since the element lives pre-transform) and\n // register the element so group drags can translate this node imperatively.\n useEffect(() => {\n const el = ref.current\n if (!el) return\n store.registerNodeElement(id, el)\n const observer = new ResizeObserver(() => {\n store.setNodeSize(id, { width: el.offsetWidth, height: el.offsetHeight })\n // Anchor geometry is measured against this box, so a resize (including\n // the initial observation) re-measures the node's anchors. Reflows that\n // don't change the box go through `remeasureAnchors` explicitly.\n store.remeasureAnchors(id)\n })\n observer.observe(el)\n return () => {\n observer.disconnect()\n store.unregisterNodeElement(id, el)\n }\n }, [id, store])\n\n const onPointerEnter = () => store.hoverNode(id)\n const onPointerLeave = () => store.hoverNode(null)\n\n // Track roving focus in the store. Self-only: a focused control inside the\n // node bubbles focusin here with a different target, and the node it lives in\n // is still the logically focused one, so nothing changes.\n const onFocus = (event: ReactFocusEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n store.setFocusedNode(id)\n }\n\n const onBlur = (event: ReactFocusEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n // Losing focus drops a grab in place — the moves are already committed.\n if (grabOrigins.current) releaseGrab(false)\n // When focus moves into a node (this one's interior or another wrapper),\n // that node's own handlers own the state — clearing here would flicker\n // `null` through the focus channel between two nodes.\n const next = event.relatedTarget\n if (next instanceof Element && next.closest(SELECTOR.node)) return\n if (store.getFocusedNode() === id) store.setFocusedNode(null)\n }\n\n // Keyboard, on the focused wrapper itself (not controls inside the node):\n // Enter/Space selects and grabs the node (additive modifier only toggles\n // selection), arrows move a grabbed node, Enter drops it, Escape reverts the\n // move — or clears the selection when nothing is grabbed. Delete (and the\n // ungrabbed selection nudge) are handled globally — see input/keyboard.\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n const node = store.nodes.get(id)\n if (!node || node.selectable === false) return\n\n // Before any lock guard: a grab that has lost its hold — yielded to a peer\n // with `releaseNodeGesture` — has to be cleaned up whatever key arrives.\n // The node is usually locked by then, so a refusal here would strand the\n // grab with no key left that could end it.\n if (grabOrigins.current && !store.isNodeHeld(id)) {\n grabOrigins.current = null\n setGrabbed(false)\n announce(`${nodeName()} was taken by someone else.`)\n return\n }\n if (!store.locks.allows(id, \"select\")) return\n\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault()\n if (grabOrigins.current) {\n releaseGrab(false)\n return\n }\n if (keyHeld(event, multiSelectionKeys)) {\n store.selectNode(id, true)\n return\n }\n // Mirror pointer-drag semantics: grabbing a node already in a\n // multi-selection keeps (and moves) the whole selection.\n if (!store.isNodeSelected(id)) store.selectNode(id)\n if (node.draggable !== false) grab()\n return\n }\n\n if (event.key === \"Escape\") {\n if (grabOrigins.current) {\n event.preventDefault()\n releaseGrab(true)\n return\n }\n store.selectNode(null)\n return\n }\n\n const dir = ARROW_DIRS[event.key]\n if (!dir || !grabOrigins.current) return\n // preventDefault also stops the global handler's selection nudge — while\n // grabbed, this handler owns arrow movement (snap + parent clamp applied).\n event.preventDefault()\n const factor = event.shiftKey ? ARROW_STEP_SHIFT : 1\n const stepX = (snapGrid?.[0] || ARROW_STEP) * factor\n const stepY = (snapGrid?.[1] || ARROW_STEP) * factor\n for (const moverId of grabOrigins.current.keys()) {\n const mover = store.nodes.get(moverId)\n if (!mover) continue\n let next = {\n x: mover.position.x + dir.x * stepX,\n y: mover.position.y + dir.y * stepY,\n }\n if (snapGrid) next = snapToGrid(next, snapGrid)\n if (mover.parentId && mover.extent === \"parent\" && mover.size) {\n next = clampToParent(store, mover.parentId, next, mover.size)\n }\n store.moveNode(moverId, next, true)\n }\n }\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n // A press that bubbled here through a React portal (a dropdown/tooltip/popover\n // rendered from inside this node) has a target outside the node's DOM. React\n // routes its synthetic events up the component tree regardless, so guard by\n // actual DOM containment — starting a drag would capture the pointer and\n // swallow that control's click.\n if (ref.current && event.target instanceof Node && !ref.current.contains(event.target)) return\n // In-DOM controls opt out of dragging with `data-nopan` (buttons, inputs, …).\n if (event.target instanceof Element && event.target.closest(SELECTOR.noPan)) return\n event.stopPropagation()\n const el = ref.current\n const node = store.nodes.get(id)\n if (!el || !node) return\n\n // Per-node interaction opt-outs — a `data-nodrag`/`data-noselect` attribute on\n // the pressed subtree wins over the node-level `draggable`/`selectable` field.\n // A peer's lock joins them as a third, transport-driven source of the same\n // two refusals, so a locked node behaves like a `selectable: false`,\n // `draggable: false` one for as long as they hold it.\n const target = event.target instanceof Element ? event.target : null\n const noSelect =\n node.selectable === false ||\n Boolean(target?.closest(SELECTOR.noSelect)) ||\n !store.locks.allows(id, \"select\")\n const noDrag =\n node.draggable === false ||\n Boolean(target?.closest(SELECTOR.noDrag)) ||\n !store.locks.allows(id, \"drag\")\n\n const additive = keyHeld(event, multiSelectionKeys)\n if (additive) {\n // Toggle this node in/out of the selection; don't start a drag.\n if (!noSelect) store.selectNode(id, true)\n return\n }\n // Dragging a node that's already part of a multi-selection moves the whole\n // group; dragging any other node selects just it first.\n if (!noSelect && !store.isNodeSelected(id)) store.selectNode(id)\n // A non-draggable node still selects/clicks, but starts no drag gesture.\n if (noDrag) return\n\n // The drag gesture itself (threshold, live snap/clamp, drop commit) is\n // shared with the post-marquee selection box — see input/group-drag.\n startGroupDrag({\n store,\n nodeId: id,\n el,\n event,\n snapGrid,\n alignmentGuides,\n swimlaneLanes,\n clampToSwimlane,\n swimlaneMargin,\n swimlaneLabelWidth,\n onLaneChange,\n })\n }\n\n const node = store.nodes.get(id)\n if (!node) return null\n const key = node.type ?? \"default\"\n const Component = nodeTypes[key] ?? BUILTIN_NODE_TYPES[key] ?? DefaultNode\n // Transform is the node's *world* position (parent chain resolved); z-index by\n // depth so children stack above their parent (flat layer, no DOM nesting).\n const world = store.getNodeWorldPosition(id)\n const depth = store.getNodeDepth(id)\n // The peer's outline is painted on the canvas; the DOM side is the cursor and\n // the focus/aria treatment, which the canvas can't reach. Both refusals are\n // asked separately, because a policy may allow one and not the other.\n const locked = lockHolder !== null\n const lockedForSelect = locked && !store.locks.allows(id, \"select\")\n const lockedForDrag = locked && !store.locks.allows(id, \"drag\")\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a node wraps arbitrary (often interactive) content, so it can't be a native <button>\n <div\n ref={ref}\n data-rivet-node={id}\n data-rivet-grabbed={grabbed ? \"\" : undefined}\n data-rivet-locked={locked ? (lockHolder ?? \"\") : undefined}\n tabIndex={node.selectable === false || lockedForSelect ? -1 : 0}\n role=\"button\"\n aria-roledescription=\"graph node\"\n aria-pressed={Boolean(node.selected)}\n aria-label={node.ariaLabel}\n aria-disabled={lockedForSelect || undefined}\n aria-describedby={\n node.selectable === false || lockedForSelect ? undefined : nodeDescriptionId\n }\n onPointerDown={onPointerDown}\n onPointerEnter={onPointerEnter}\n onPointerLeave={onPointerLeave}\n onKeyDown={onKeyDown}\n onFocus={onFocus}\n onBlur={onBlur}\n style={{\n ...wrapperStyle,\n ...(lockedForDrag ? { cursor: \"not-allowed\" } : {}),\n transform: `translate(${world.x}px, ${world.y}px)`,\n zIndex: depth,\n // Explicit dimensions from NodeResizer override the intrinsic size.\n ...(node.width !== undefined ? { width: node.width } : {}),\n ...(node.height !== undefined ? { height: node.height } : {}),\n }}\n >\n <RivetNodeContext.Provider value={nodeContext}>\n <Component\n id={id}\n type={node.type}\n data={node.data}\n selected={Boolean(node.selected)}\n hovered={Boolean(node.hovered)}\n width={node.width ?? node.size?.width}\n height={node.height ?? node.size?.height}\n position={node.position}\n positionAbsolute={world}\n />\n <NodeAnchors nodeId={id} />\n </RivetNodeContext.Provider>\n </div>\n )\n})\n","import {\n type CSSProperties,\n memo,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useRef,\n useSyncExternalStore,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport { boundingRect } from \"../graph\"\nimport { startGroupDrag } from \"../input/group-drag\"\nimport type { Rect } from \"../types\"\n\n/** Above every node — nodes z-stack by tree depth, which stays small. */\nconst NODES_SELECTION_Z = 1000\n\nconst boxStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n pointerEvents: \"auto\",\n cursor: \"grab\",\n userSelect: \"none\",\n zIndex: NODES_SELECTION_Z,\n // Same accent as the marquee overlay it succeeds, but dotted: the marquee is\n // the live gesture, this is the settled selection.\n border: \"1px dotted rgba(99, 102, 241, 0.8)\",\n background: \"rgba(99, 102, 241, 0.08)\",\n}\n\nconst applyRect = (el: HTMLElement, rect: Rect): void => {\n el.style.transform = `translate(${rect.x}px, ${rect.y}px)`\n el.style.width = `${rect.width}px`\n el.style.height = `${rect.height}px`\n}\n\n/**\n * The persistent box a marquee leaves behind: a draggable rect over the\n * selected nodes' bounding box (React Flow's \"NodesSelection\"). Dragging it\n * moves the whole selection as a group; any other selection change — a pane,\n * node, or edge click, Escape, deletion — dismisses it. It lives in the\n * viewport-transformed node layer, so it pans/zooms with the graph.\n */\nexport const NodesSelection = memo(function NodesSelection() {\n const { store, snapGrid, alignmentGuides, onLaneChange } = useRivetContext()\n const { swimlaneLanes, clampToSwimlane, swimlaneMargin, swimlaneLabelWidth } = useRivetContext()\n const ref = useRef<HTMLDivElement>(null)\n\n const subscribe = useCallback(\n (onChange: () => void) => store.subscribeSelectionBox(onChange),\n [store],\n )\n const getSnapshot = useCallback(() => store.getSelectionBoxVersion(), [store])\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n const selectionRect = (): Rect | null =>\n boundingRect(store.getSelectedNodes().map((id) => store.getNodeRect(id)))\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n const el = ref.current\n if (!el) return\n event.stopPropagation()\n startGroupDrag({\n store,\n el,\n event,\n snapGrid,\n alignmentGuides,\n swimlaneLanes,\n clampToSwimlane,\n swimlaneMargin,\n swimlaneLabelWidth,\n onLaneChange,\n // Node moves are imperative during the drag (no React re-render), so the\n // box tracks its nodes the same way; the drop's commit re-renders it.\n onFrame: () => {\n const rect = selectionRect()\n if (rect && ref.current) applyRect(ref.current, rect)\n },\n })\n }\n\n if (!store.isSelectionBoxActive()) return null\n const rect = selectionRect()\n if (!rect) return null\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a drag affordance over canvas-positioned nodes, not a form grouping — it can't be a <fieldset>\n <div\n ref={ref}\n data-rivet-nodes-selection\n role=\"group\"\n aria-label=\"Selected nodes\"\n onPointerDown={onPointerDown}\n style={{\n ...boxStyle,\n transform: `translate(${rect.x}px, ${rect.y}px)`,\n width: rect.width,\n height: rect.height,\n }}\n />\n )\n})\n","import type { CSSProperties, RefObject } from \"react\"\nimport type { NodeId } from \"../types\"\nimport { NodeWrapper } from \"./node-wrapper\"\nimport { NodesSelection } from \"./nodes-selection\"\n\nconst layerStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n transformOrigin: \"0 0\",\n // `will-change: transform` is applied imperatively only while panning/zooming\n // (see the runtime), then cleared — a permanently promoted layer would upscale a\n // cached bitmap and blur node text when zoomed in.\n pointerEvents: \"none\",\n}\n\nexport type NodeLayerProps = {\n containerRef: RefObject<HTMLDivElement | null>\n visibleIds: NodeId[]\n}\n\n/**\n * The DOM layer. Renders only the culled (visible) nodes. It re-renders solely\n * when the visible set changes (the `visibleIds` prop); node data changes are\n * handled by each memoized {@link NodeWrapper} subscribing to its own node, so\n * touching one node never re-renders the others.\n */\nexport function NodeLayer({ containerRef, visibleIds }: NodeLayerProps): React.ReactElement {\n return (\n <div ref={containerRef} style={layerStyle}>\n {visibleIds.map((id) => (\n <NodeWrapper key={id} id={id} />\n ))}\n {/* Post-marquee selection box — world-space, so it belongs in this\n transformed layer even though it isn't a node (and isn't culled:\n its nodes may be off-screen while the box edge is not). */}\n <NodesSelection />\n </div>\n )\n}\n","import {\n type CSSProperties,\n type KeyboardEvent as ReactKeyboardEvent,\n type MouseEvent as ReactMouseEvent,\n type ReactNode,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n} from \"react\"\nimport { useRivetContext, useRivetViewport } from \"../context\"\nimport { type ResolvedLane, requiredLaneHeight } from \"../swimlane/lanes\"\n\nconst containerStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n overflow: \"hidden\",\n // Chrome only — never intercept canvas panning or node dragging.\n pointerEvents: \"none\",\n zIndex: 5,\n}\n\nconst headerWrapperStyle: CSSProperties = {\n position: \"absolute\",\n left: 0,\n right: 0,\n overflow: \"hidden\",\n}\n\nconst defaultHeaderStyle: CSSProperties = {\n display: \"flex\",\n alignItems: \"center\",\n gap: 8,\n height: \"100%\",\n paddingLeft: 12,\n paddingRight: 12,\n background: \"#ffffff\",\n borderBottom: \"1px solid rgba(100, 116, 139, 0.2)\",\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n fontSize: 12,\n fontWeight: 600,\n letterSpacing: 0.4,\n textTransform: \"uppercase\",\n whiteSpace: \"nowrap\",\n}\n\nconst labelWrapperStyle: CSSProperties = {\n position: \"absolute\",\n overflow: \"hidden\",\n}\n\nconst defaultLabelStyle: CSSProperties = {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: \"100%\",\n height: \"100%\",\n background: \"#ffffff\",\n borderRight: \"1px solid rgba(100, 116, 139, 0.2)\",\n}\n\nconst labelTextStyle: CSSProperties = {\n writingMode: \"vertical-rl\",\n transform: \"rotate(180deg)\",\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n fontSize: 10,\n fontWeight: 600,\n letterSpacing: 0.6,\n textTransform: \"uppercase\",\n color: \"rgba(51, 65, 85, 0.85)\",\n whiteSpace: \"nowrap\",\n userSelect: \"none\",\n}\n\nconst RESIZE_HANDLE_HIT = 8\n\n/**\n * Sticky swimlane chrome, rendered in screen space above the graph: each group's\n * header pins to the top of the pane, each lane's label pins to the left edge,\n * and each lane gets a bottom resize handle. Re-renders on viewport changes.\n */\nexport function SwimlaneOverlay(): React.ReactElement | null {\n const {\n swimlaneGroups,\n swimlaneLabelWidth,\n swimlaneHeaderSize,\n swimlaneResizable,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n } = useRivetContext()\n const { x: vx, y: vy, zoom } = useRivetViewport()\n\n if (swimlaneGroups.length === 0) return null\n\n // Sticky header position per group — reused to keep lane labels below it.\n const headerBottomByGroup = new Map<string, number>()\n\n return (\n <div style={containerStyle}>\n {swimlaneGroups.map((group) => {\n const screenTop = group.top * zoom + vy\n const screenBottom = group.bottom * zoom + vy\n const stickyY = Math.max(0, Math.min(screenTop, screenBottom - swimlaneHeaderSize))\n headerBottomByGroup.set(group.id, stickyY + swimlaneHeaderSize)\n if (screenBottom <= 0) return null\n const sticky = stickyY > screenTop\n\n return (\n <div\n key={group.id}\n style={{ ...headerWrapperStyle, top: stickyY, height: swimlaneHeaderSize }}\n >\n {renderSwimlaneHeader ? (\n renderSwimlaneHeader({ id: group.id, label: group.label, color: group.color, sticky })\n ) : (\n <div\n style={{\n ...defaultHeaderStyle,\n boxShadow: sticky ? \"0 1px 2px rgba(0, 0, 0, 0.08)\" : undefined,\n }}\n >\n {group.label}\n </div>\n )}\n </div>\n )\n })}\n\n {swimlaneGroups.flatMap((group) =>\n group.lanes.map((lane) => {\n if (!lane.label) return null\n const headerBottom = headerBottomByGroup.get(group.id) ?? 0\n const screenX = lane.x * zoom + vx\n const screenTop = lane.top * zoom + vy\n const screenBottom = screenTop + lane.height * zoom\n const screenEndX = screenX + lane.width * zoom\n const stickyX = Math.max(0, Math.min(screenX, screenEndX - swimlaneLabelWidth))\n const clampedTop = Math.max(headerBottom, screenTop)\n const labelHeight = screenBottom - clampedTop\n if (screenBottom <= headerBottom || labelHeight <= 0) return null\n\n return (\n <div\n key={lane.id}\n style={{\n ...labelWrapperStyle,\n left: stickyX,\n top: clampedTop,\n width: swimlaneLabelWidth,\n height: labelHeight,\n }}\n >\n {renderSwimlaneLabel ? (\n renderSwimlaneLabel({\n id: lane.id,\n label: lane.label,\n color: lane.color,\n groupId: lane.groupId,\n })\n ) : (\n <div style={defaultLabelStyle}>\n <span style={labelTextStyle}>{lane.label}</span>\n </div>\n )}\n </div>\n )\n }),\n )}\n\n {swimlaneResizable &&\n swimlaneGroups.flatMap((group) =>\n group.lanes.map((lane) => {\n const bottom = (lane.top + lane.height) * zoom + vy\n // Above the pane top is clipped anyway; skip so we don't stack strips.\n if (bottom < 0) return null\n return (\n <LaneResizeHandle key={lane.id} lane={lane} top={bottom - RESIZE_HANDLE_HIT / 2} />\n )\n }),\n )}\n </div>\n )\n}\n\nconst handleStyle: CSSProperties = {\n position: \"absolute\",\n left: 0,\n right: 0,\n height: RESIZE_HANDLE_HIT,\n cursor: \"ns-resize\",\n pointerEvents: \"auto\",\n touchAction: \"none\",\n}\n\n/** A full-width grab strip on a lane's bottom edge that resizes the lane. */\nfunction LaneResizeHandle({ lane, top }: { lane: ResolvedLane; top: number }): ReactNode {\n const { store, resizeSwimlane, swimlaneMargin } = useRivetContext()\n\n // Double-click the handle to snap the lane's height to fit its nodes (the same\n // shrink-to-content you'd reach by dragging all the way down).\n const onDoubleClick = useCallback(\n (event: ReactMouseEvent<HTMLDivElement>) => {\n event.stopPropagation()\n const next = requiredLaneHeight(lane, store.nodes.values(), swimlaneMargin.bottom)\n resizeSwimlane(lane.id, next, true, \"autofit\")\n },\n [store, resizeSwimlane, swimlaneMargin.bottom, lane],\n )\n\n const onPointerDown = useCallback(\n (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n event.stopPropagation()\n event.preventDefault()\n const startClientY = event.clientY\n const startHeight = lane.height\n const laneId = lane.id\n\n const onMove = (moveEvent: PointerEvent) => {\n const zoom = store.getViewport().zoom || 1\n const next = startHeight + (moveEvent.clientY - startClientY) / zoom\n resizeSwimlane(laneId, next, false)\n }\n const onUp = (upEvent: PointerEvent) => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n const zoom = store.getViewport().zoom || 1\n const next = startHeight + (upEvent.clientY - startClientY) / zoom\n resizeSwimlane(laneId, next, true)\n }\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n },\n [store, resizeSwimlane, lane.id, lane.height],\n )\n\n // Arrow keys resize the focused handle's lane; each press commits (so it's\n // undoable/persistable via onSwimlaneSizeChange like a drag's drop).\n const onKeyDown = useCallback(\n (event: ReactKeyboardEvent<HTMLDivElement>) => {\n const dir = event.key === \"ArrowDown\" ? 1 : event.key === \"ArrowUp\" ? -1 : 0\n if (dir === 0) return\n event.preventDefault()\n const step = event.shiftKey ? 50 : 10\n resizeSwimlane(lane.id, lane.height + dir * step, true)\n },\n [resizeSwimlane, lane.id, lane.height],\n )\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a focusable, arrow-key-resizable separator is an interactive widget — <hr> can't take focus or gestures\n <div\n data-rivet-swimlane-handle=\"\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n aria-label={`Resize lane ${lane.label ?? lane.id}`}\n aria-valuenow={Math.round(lane.height)}\n tabIndex={0}\n style={{ ...handleStyle, top }}\n onPointerDown={onPointerDown}\n onDoubleClick={onDoubleClick}\n onKeyDown={onKeyDown}\n />\n )\n}\n","import {\n type CSSProperties,\n type MouseEvent as ReactMouseEvent,\n type ReactNode,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\"\nimport { type AnchorOptions, normalizeAnchorConnection } from \"../anchor/registry\"\nimport { SELECTOR } from \"../constants\"\nimport { RivetContext, type RivetContextValue } from \"../context\"\nimport type { EdgeAlignment } from \"../edge-alignment\"\nimport { useLocalPresence } from \"../hooks/use-local-presence\"\nimport { useRivetConfig } from \"../hooks/use-rivet-config\"\nimport { useRivetRuntime } from \"../hooks/use-rivet-runtime\"\nimport { useSwimlanes } from \"../hooks/use-swimlanes\"\nimport type { CanInteractWithLocked } from \"../locks/registry\"\nimport type { LocalPresence } from \"../presence/local\"\nimport type { Peer, PresenceOptions } from \"../presence/registry\"\nimport { canvas2DEdgeRenderer } from \"../renderer/canvas-2d-edge-renderer\"\nimport { createRivetStore, type RivetStore } from \"../store\"\nimport { type ResolvedLane, SWIMLANE_LABEL_WIDTH, swimlaneChromeAt } from \"../swimlane/lanes\"\nimport type {\n ChangeMeta,\n Connection,\n DefaultEdgeOptions,\n EdgeChange,\n EdgeRendererFactory,\n EdgeTypes,\n LaneChange,\n NodeChange,\n NodeGestureEvent,\n NodeId,\n NodeLockConflictEvent,\n NodeTypes,\n RivetEdge,\n RivetNode,\n RivetSelection,\n SwimlaneGroup,\n SwimlaneHeaderProps,\n SwimlaneLabelProps,\n SwimlaneMargin,\n SwimlaneSizeChange,\n Vec2,\n Viewport,\n} from \"../types\"\nimport { screenToWorld } from \"../viewport\"\nimport { EdgeLabelLayer } from \"./edge-label-layer\"\nimport { NodeLayer } from \"./node-layer\"\nimport { SwimlaneOverlay } from \"./swimlane-overlay\"\n\n/** Resolved graph context for a pane right-click, passed to `onPaneContextMenu`. */\nexport type PaneContextMenuContext = {\n /** The click position in world coordinates (already unprojected). */\n world: Vec2\n /** The swimlane lane whose body sits under the cursor, or `null`. */\n lane: ResolvedLane | null\n}\n\nexport type RivetProps = {\n /**\n * Nodes to seed the graph with (uncontrolled). Read once on mount to initialize\n * the internal store — later changes to this array are ignored. Use {@link nodes}\n * + {@link onNodesChange} for controlled mode instead. Defaults to `[]`.\n */\n defaultNodes?: RivetNode[]\n /**\n * Edges to seed the graph with (uncontrolled). See {@link defaultNodes}. An edge\n * whose `source` or `target` node is absent is skipped by the renderer. Defaults to `[]`.\n */\n defaultEdges?: RivetEdge[]\n /**\n * Controlled nodes. When provided, the graph mirrors this array — hold the nodes\n * in your own state and feed back the batches from {@link onNodesChange} (apply\n * them with `applyNodeChanges`). A node under a live gesture keeps its own\n * geometry rather than the array's, so a drag stays smooth while the props\n * lag behind it. Takes precedence over {@link defaultNodes}.\n */\n nodes?: RivetNode[]\n /** Controlled edges. See {@link nodes}. Takes precedence over {@link defaultEdges}. */\n edges?: RivetEdge[]\n /**\n * Change batches the graph wants applied to your nodes (controlled mode).\n *\n * `meta.origin` says where the batch came from: `\"local\"` for anything this\n * client did, `\"remote\"` for a batch that arrived through\n * {@link RivetInstance.applyRemote}. Multiplayer consumers apply both and send\n * only the local ones onward — an untagged echo is indistinguishable from a\n * peer's edit and loops straight back out.\n */\n onNodesChange?: (changes: NodeChange[], meta: ChangeMeta) => void\n /** Change batches the graph wants applied to your edges (controlled mode). See {@link onNodesChange}. */\n onEdgesChange?: (changes: EdgeChange[], meta: ChangeMeta) => void\n /**\n * Initial pan/zoom. `x`/`y` are the screen-space offset in pixels and `zoom`\n * is the scale factor. Defaults to `{ x: 0, y: 0, zoom: 1 }` (origin, 1:1).\n */\n defaultViewport?: Viewport\n /**\n * Maps a node's `type` to the React component that renders it. A node whose\n * `type` has no entry here (or no `type` at all) falls back to\n * {@link DefaultNode}. Defaults to `{}`.\n */\n nodeTypes?: NodeTypes\n /**\n * Registry of custom edge shapes, keyed by `edge.type`. Each is a pure geometry\n * function (see {@link EdgePathFn}) so edges stay canvas/GPU-renderable. Merged\n * over the built-ins `bezier` (default), `smoothstep`, `step`, and `straight`.\n */\n edgeTypes?: EdgeTypes\n /** Defaults merged into every edge that doesn't set the field (type, style, markers…). */\n defaultEdgeOptions?: DefaultEdgeOptions\n /** Accessible name for the graph surface (`aria-label` on the pane). Defaults to \"Node graph\". */\n ariaLabel?: string\n /**\n * Backend factory for the edge layers — swap Canvas2D for another\n * {@link EdgeRenderer}. Defaults to {@link canvas2DEdgeRenderer}. Pass a stable/memoized\n * reference; a new identity re-creates the renderers.\n */\n renderer?: EdgeRendererFactory\n /**\n * Lower bound on `viewport.zoom`. All zooming (wheel, controls, `fitView`) is\n * clamped to this. Defaults to `0.2` (zoomed out to 20%).\n */\n minZoom?: number\n /**\n * Upper bound on `viewport.zoom`. All zooming is clamped to this. Defaults to\n * `2.5` (zoomed in to 250%).\n */\n maxZoom?: number\n /**\n * Spacing in world units between background grid dots. The grid scales with\n * zoom, so this is measured at `zoom === 1`. Defaults to `24`.\n */\n gridGap?: number\n /**\n * Snap dragged nodes to a `[x, y]` world-unit grid. A `0` axis is left free.\n * Omit (default) for free positioning. Independent of {@link gridGap} (the\n * visual dot grid) — pass the same value to snap to the dots you see.\n */\n snapGrid?: [number, number]\n /**\n * While dragging a single node, show alignment guides and snap its edges/center\n * to nearby nodes' edges/centers. Defaults to `false`.\n */\n alignmentGuides?: boolean\n /**\n * Placement policy for anchor chrome — the grab dots and stray perimeter\n * handles rivet renders for registered anchors (see {@link Anchor}). Omitted\n * fields fall back to the defaults.\n */\n anchorOptions?: AnchorOptions\n /**\n * The other people in this document — the presence roster. Identity (name,\n * colour) plus the slow fields: what each peer has selected, and what they're\n * holding under a gesture. Rivet paints them: a cursor per peer, an outline\n * around what they've selected, and the nodes they're moving drawn where they\n * currently have them.\n *\n * Peer cursors move far faster than React should re-render, so the roster\n * carries only a seed for them — feed live cursors and drag boxes through\n * {@link RivetInstance.setPeerCursor} / `setPeerNodeTransform` instead.\n *\n * Presence is ephemeral: none of it reaches the graph, the change stream, or\n * history. Dropping a peer from the array is how they leave.\n */\n peers?: Peer[]\n /**\n * Called with this client's presence — cursor (in world coordinates),\n * selection, and held nodes — as a whole snapshot, ready to broadcast.\n *\n * Snapshots are idempotent, so a dropped or duplicated one costs nothing and\n * a reconnecting peer is instantly correct. Cursor movement is coalesced to\n * `presenceOptions.throttleMs`; selection and gesture changes are published\n * immediately.\n */\n onLocalPresence?: (presence: LocalPresence) => void\n /** Presence policy — outbound throttle, and whether rivet paints peer cursors. */\n presenceOptions?: PresenceOptions\n /**\n * Nodes a peer has claimed, as `nodeId -> peerId`. Locks are policy where\n * {@link peers} is description: rivet paints a locked node in its holder's\n * colour *and* refuses to act on it.\n *\n * By default it refuses selection, dragging, resizing and deletion, and\n * allows connections — a lock claims the node, not the graph around it.\n * {@link canInteractWithLocked} replaces that policy.\n *\n * Lifetime is yours: rivet never takes or releases a lock, it only reads the\n * table. Take one in {@link onNodeDragStart} and drop it in\n * {@link onNodeDragEnd} for drag-scoped locks, or hold through deselection\n * for something stickier. Like presence, none of this reaches the graph, the\n * change stream, or history.\n */\n lockedNodes?: Record<NodeId, string>\n /**\n * Decide what this client may do to a locked node, per attempt. Return `true`\n * to allow the intent, `false` to refuse it.\n *\n * A handler owns the whole policy — rivet's defaults are replaced, not\n * consulted — so answer every intent you care about:\n *\n * ```tsx\n * // locked nodes stay inspectable, but nothing may change them\n * canInteractWithLocked={({ intent }) => intent === \"select\" || intent === \"connect\"}\n * ```\n *\n * Called on the input path (every marquee frame, every mover), so keep it\n * cheap and free of side effects.\n */\n canInteractWithLocked?: CanInteractWithLocked\n /**\n * Called when a lock for a peer arrives on a node this client is already\n * holding — two clients started before either lock reached the other.\n *\n * rivet reports it and keeps going: the running gesture stays authoritative\n * over its geometry, because only your transport knows which client actually\n * lost the race. To yield, call {@link RivetInstance.releaseNodeGesture} —\n * the gesture stops writing and tears down without committing.\n */\n onNodeLockConflict?: (event: NodeLockConflictEvent) => void\n /**\n * Which mouse buttons pan when dragging the pane: `true` = left only, `false` =\n * none, or a list of `MouseEvent.button` codes (`0` left, `1` middle, `2` right).\n * e.g. `[1, 2]` pans with middle/right and frees left for selection. Defaults to\n * `true`. Pass a stable reference; a new array identity re-binds the listeners.\n */\n panOnDrag?: boolean | number[]\n /**\n * Draw a selection marquee on a plain left-drag instead of panning. Pair with\n * `panOnDrag={[1, 2]}` so left selects and middle/right pan. A marquee that\n * ends over nodes leaves a persistent selection box around them — drag it to\n * move the whole selection; a click elsewhere or Escape dismisses it.\n * Defaults to `false`.\n */\n selectionOnDrag?: boolean\n /**\n * Key(s) that force a marquee on a left-drag when held (e.g. `\"Shift\"`, `\"Meta\"`,\n * or `[\"Shift\", \"Meta\"]`). `null` disables. Defaults to `\"Shift\"`.\n */\n selectionKeyCode?: string | string[] | null\n /**\n * Key(s) that make a click or marquee **add to** the selection instead of\n * replacing it. Defaults to `[\"Meta\", \"Control\", \"Shift\"]`. Use modifier keys\n * (`Shift`/`Meta`/`Control`/`Alt`) — other keys only resolve during a pane drag.\n */\n multiSelectionKeyCode?: string | string[]\n /**\n * Pan the viewport on wheel / two-finger trackpad scroll instead of zooming.\n * A pinch gesture (reported by the browser as ctrl+wheel) still zooms. When\n * `false` (default), scrolling zooms toward the cursor.\n */\n scrollToPan?: boolean\n /**\n * Wheel/pinch zoom sensitivity — larger zooms faster per scroll delta.\n * Defaults to `0.0015`. Try `~0.003` for faster trackpad pinch zoom.\n */\n zoomSpeed?: number\n /**\n * Swimlanes drawn behind the graph — a decorative background of labeled lane\n * groups (like planout's swimlanes). Not nodes or edges; just layout regions.\n * Omit for no swimlanes.\n */\n swimlane?: SwimlaneGroup[]\n /**\n * Bind node dragging to the swimlanes: on drop each node snaps fully inside\n * one lane (honoring {@link swimlaneMargin}) and is reassigned to the lane it\n * lands in via {@link RivetNode.laneId}. Defaults to `true` when\n * {@link swimlane} is provided, `false` otherwise. Ignored with no swimlanes.\n */\n clampToSwimlane?: boolean\n /**\n * Inner clearance kept between a clamped node and its lane's edges. A number\n * applies to all sides; per-side values override it. Defaults to `16`.\n */\n swimlaneMargin?: number | SwimlaneMargin\n /** Screen height of the sticky group header band, in px. Defaults to `32`. */\n swimlaneHeaderHeight?: number\n /**\n * Show a resize handle on each lane's bottom edge to change its height.\n * Defaults to `true` when {@link swimlane} is provided.\n */\n swimlaneResizable?: boolean\n /**\n * Fraction of the last lane's height that must stay visible when scrolled to\n * the bottom — the down-scroll stop. `0.5` (default) keeps half of it in view.\n * Only applies when {@link clampToSwimlane} is on.\n */\n swimlaneBottomReveal?: number\n /** Render custom content for a group's sticky header (replaces the default). */\n renderSwimlaneHeader?: (props: SwimlaneHeaderProps) => ReactNode\n /** Render custom content for a lane's sticky label (replaces the default). */\n renderSwimlaneLabel?: (props: SwimlaneLabelProps) => ReactNode\n /**\n * Called when a lane's height changes — from a resize drag or from auto-fit\n * growing it to contain a node that grew. The graph owns lane heights, so this\n * is a notification (persist it if you like), not a request to update state.\n */\n onSwimlaneSizeChange?: (change: SwimlaneSizeChange) => void\n /**\n * Right-click on empty canvas (not over a node or swimlane chrome). The second\n * argument carries the resolved graph context — the world position and the lane\n * under the cursor — so you don't have to re-derive them.\n */\n onPaneContextMenu?: (event: ReactMouseEvent, context: PaneContextMenuContext) => void\n /** Right-click on a lane's sticky label. */\n onSwimlaneHeaderContextMenu?: (laneId: string, event: ReactMouseEvent) => void\n /** Right-click on a group's sticky header. */\n onSwimlaneGroupHeaderContextMenu?: (groupId: string, event: ReactMouseEvent) => void\n /** Called when a dragged node is reassigned to a different lane. */\n onLaneChange?: (change: LaneChange) => void\n /** Veto a proposed connection; return false to reject it. Applies to reconnection too. */\n isValidConnection?: (connection: Connection) => boolean\n /**\n * Rewrite a validated connection before it commits — normalize handle ids\n * (e.g. redirect an in-content grab handle to its canonical perimeter\n * handle), or force direction conventions. Returning `null` cancels the\n * drop. Applies to new connections and reconnections; `isValidConnection`\n * sees the raw connection, `onConnect`/`onReconnect` see the mapped one.\n */\n mapConnection?: (connection: Connection) => Connection | null\n /** Called after a valid connection is made (the edge is already added). */\n onConnect?: (connection: Connection) => void\n /**\n * Allow reconnecting edges by dragging an endpoint onto a new handle. Per-edge\n * `reconnectable` overrides this. Defaults to `false`.\n */\n edgesReconnectable?: boolean\n /**\n * When edge endpoints re-side to face the peer node. `\"manual\"` (default)\n * never rewrites a chosen handle; `\"on-move\"` re-sides both ends of a moved\n * node's edges when the move commits — in the same batch as the move, so one\n * undo restores position and handles together. `\"live\"` additionally renders\n * a dragging node's edges as if their ends were auto — re-siding per frame\n * to face each other, with hysteresis so near-diagonal positions don't\n * flicker — and commits the displayed sides on drop, inside the move's\n * history step; nothing is persisted mid-gesture. Only committed position\n * changes trigger a rewrite: data replaces and dimension changes never\n * re-side, and a freshly created or reconnected edge keeps exactly the\n * handles the user grabbed or dropped on. Anchor and bare-side ends rewrite\n * their side directly; plain handles re-side to a registered handle of a\n * compatible type on the facing side, or stay pinned when the node has none\n * there. Independent of the policy, an end with *no* side — a missing\n * handle, or an `anchorAutoHandleId` anchor end — always floats: the\n * renderer resolves its facing side per frame and never writes it back.\n */\n edgeAlignment?: EdgeAlignment\n /** Called when an endpoint drag re-points an edge (the edge is already updated). */\n onReconnect?: (edge: RivetEdge, connection: Connection) => void\n /** Called when an endpoint reconnection drag starts. */\n onReconnectStart?: (edge: RivetEdge) => void\n /** Called when an endpoint reconnection drag ends (committed or cancelled). */\n onReconnectEnd?: (edge: RivetEdge) => void\n /**\n * Called when a local gesture takes hold of one or more nodes — a pointer\n * drag, a resize, or a keyboard grab. While it's open, those nodes' geometry\n * belongs to this client: remote `position`/`dimensions` writes for them are\n * dropped, and controlled props can't stomp the live box.\n *\n * In a shared document this is where you acquire a lock. It's paired with\n * {@link onNodeDragEnd} — every start gets exactly one end, including a\n * cancelled keyboard grab.\n */\n onNodeDragStart?: (event: NodeGestureEvent) => void\n /** Called when a gesture releases its nodes. See {@link onNodeDragStart}. */\n onNodeDragEnd?: (event: NodeGestureEvent) => void\n /** Called whenever the selected nodes and/or edges change. */\n onSelectionChange?: (selection: RivetSelection) => void\n /**\n * Called when keyboard focus moves to a node (or leaves the graph — `null`).\n * The same state is available inside `<Rivet>` via {@link useRivetFocusedNode}.\n * Rivet draws no focus ring; use this (or the wrapper's `:focus-visible`) to\n * render your own indicator.\n */\n onFocusChange?: (id: NodeId | null) => void\n className?: string\n style?: CSSProperties\n children?: ReactNode\n}\n\nconst paneStyle: CSSProperties = {\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n overflow: \"hidden\",\n touchAction: \"none\",\n}\n\nconst canvasStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n pointerEvents: \"none\",\n}\n\n// Visually hidden but still read by screen readers (the live region and the\n// keyboard-instructions element the node wrappers point aria-describedby at).\nconst srOnlyStyle: CSSProperties = {\n position: \"absolute\",\n width: 1,\n height: 1,\n margin: -1,\n padding: 0,\n overflow: \"hidden\",\n clipPath: \"inset(50%)\",\n whiteSpace: \"nowrap\",\n border: 0,\n}\n\nconst NODE_KEYBOARD_INSTRUCTIONS =\n \"Press Enter to select and grab the node. While grabbed, use the arrow keys to move it, \" +\n \"Enter to drop, Escape to cancel. Press Delete to remove the selection.\"\n\n// Object/array defaults are hoisted so an omitted prop keeps a stable identity\n// across renders instead of allocating a fresh value each render (which would\n// churn the context / re-mount the render loop). Inline-passed values are\n// stabilized separately by useRivetConfig.\nconst DEFAULT_MULTI_SELECTION_KEY_CODE = [\"Meta\", \"Control\", \"Shift\"]\nconst EMPTY_NODE_TYPES: NodeTypes = {}\nconst EMPTY_NODES: RivetNode[] = []\nconst EMPTY_EDGES: RivetEdge[] = []\nconst DEFAULT_VIEWPORT: Viewport = { x: 0, y: 0, zoom: 1 }\n\n/**\n * The graph surface. Stacks a background grid canvas, an edge canvas, and a DOM\n * node layer — all driven by one shared viewport (see {@link useRivetRuntime}).\n */\nexport function Rivet({\n defaultNodes = EMPTY_NODES,\n defaultEdges = EMPTY_EDGES,\n nodes: controlledNodes,\n edges: controlledEdges,\n onNodesChange,\n onEdgesChange,\n defaultViewport = DEFAULT_VIEWPORT,\n nodeTypes = EMPTY_NODE_TYPES,\n edgeTypes,\n defaultEdgeOptions,\n ariaLabel,\n renderer = canvas2DEdgeRenderer,\n minZoom = 0.2,\n maxZoom = 2.5,\n gridGap = 24,\n snapGrid,\n alignmentGuides = false,\n anchorOptions,\n peers,\n onLocalPresence,\n presenceOptions,\n lockedNodes,\n canInteractWithLocked,\n onNodeLockConflict,\n panOnDrag = true,\n selectionOnDrag = false,\n selectionKeyCode = \"Shift\",\n multiSelectionKeyCode = DEFAULT_MULTI_SELECTION_KEY_CODE,\n scrollToPan = false,\n zoomSpeed = 0.0015,\n swimlane,\n clampToSwimlane,\n swimlaneMargin,\n swimlaneHeaderHeight = 32,\n swimlaneResizable,\n swimlaneBottomReveal = 0.5,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n onSwimlaneSizeChange,\n onPaneContextMenu,\n onSwimlaneHeaderContextMenu,\n onSwimlaneGroupHeaderContextMenu,\n onLaneChange,\n isValidConnection,\n mapConnection,\n onConnect,\n edgesReconnectable,\n edgeAlignment = \"manual\",\n onReconnect,\n onReconnectStart,\n onReconnectEnd,\n onNodeDragStart,\n onNodeDragEnd,\n onSelectionChange,\n onFocusChange,\n className,\n style,\n children,\n}: RivetProps): React.ReactElement {\n const storeRef = useRef<RivetStore | null>(null)\n if (storeRef.current === null) {\n // Controlled props seed the store too; reconcile keeps it in sync thereafter.\n storeRef.current = createRivetStore({\n nodes: controlledNodes ?? defaultNodes,\n edges: controlledEdges ?? defaultEdges,\n viewport: defaultViewport,\n })\n }\n const store = storeRef.current\n\n // Resolve every identity-sensitive prop to a stable reference once, so an inline\n // object/handler from the consumer can't churn the context or re-mount the loop.\n const cfg = useRivetConfig({\n nodeTypes,\n edgeTypes,\n defaultEdgeOptions,\n snapGrid,\n swimlaneMargin,\n anchorOptions,\n presenceOptions,\n panOnDrag,\n selectionKeyCode,\n multiSelectionKeyCode,\n isValidConnection,\n mapConnection,\n onConnect,\n onLaneChange,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n })\n\n // Anchor grab dot ids are chrome — rewrite them to the persisted stray ids\n // (same anchor, same side) before any edge commits. The consumer's\n // `mapConnection` still runs last, on the normalized connection;\n // `isValidConnection` keeps seeing the raw one.\n const mapConnectionWithAnchors = useMemo(\n () =>\n (connection: Connection): Connection | null => {\n const normalized = normalizeAnchorConnection(connection)\n return cfg.mapConnection ? cfg.mapConnection(normalized) : normalized\n },\n [cfg.mapConnection],\n )\n\n useEffect(() => {\n store.setEdgeAlignment(edgeAlignment)\n }, [store, edgeAlignment])\n\n // Keep the latest callback in a ref so we subscribe exactly once, even when an\n // inline `onSelectionChange` gets a new identity each render.\n const onSelectionChangeRef = useRef(onSelectionChange)\n onSelectionChangeRef.current = onSelectionChange\n useEffect(\n () => store.subscribeSelection((selection) => onSelectionChangeRef.current?.(selection)),\n [store],\n )\n\n const onFocusChangeRef = useRef(onFocusChange)\n onFocusChangeRef.current = onFocusChange\n useEffect(() => store.subscribeFocus((id) => onFocusChangeRef.current?.(id)), [store])\n\n // Screen-reader narration for keyboard interactions (grab/move/drop, connect).\n // Components publish through the context's `announce`; the pane renders the\n // message into a hidden polite live region.\n const [announcement, setAnnouncement] = useState(\"\")\n const announce = useCallback((message: string) => setAnnouncement(message), [])\n const nodeDescriptionId = useId()\n\n // Controlled mode: forward the store's change batches to the consumer. Handlers\n // read the latest callback via refs; presence toggles re-register them.\n const onNodesChangeRef = useRef(onNodesChange)\n onNodesChangeRef.current = onNodesChange\n const onEdgesChangeRef = useRef(onEdgesChange)\n onEdgesChangeRef.current = onEdgesChange\n const hasNodeChange = Boolean(onNodesChange)\n const hasEdgeChange = Boolean(onEdgesChange)\n useEffect(() => {\n store.setChangeHandlers({\n nodes: hasNodeChange\n ? (changes, meta) => onNodesChangeRef.current?.(changes, meta)\n : undefined,\n edges: hasEdgeChange\n ? (changes, meta) => onEdgesChangeRef.current?.(changes, meta)\n : undefined,\n })\n return () => store.setChangeHandlers({})\n }, [store, hasNodeChange, hasEdgeChange])\n\n const onNodeDragStartRef = useRef(onNodeDragStart)\n onNodeDragStartRef.current = onNodeDragStart\n const onNodeDragEndRef = useRef(onNodeDragEnd)\n onNodeDragEndRef.current = onNodeDragEnd\n const onNodeLockConflictRef = useRef(onNodeLockConflict)\n onNodeLockConflictRef.current = onNodeLockConflict\n useEffect(() => {\n store.setGestureHandlers({\n start: (event) => onNodeDragStartRef.current?.(event),\n end: (event) => onNodeDragEndRef.current?.(event),\n conflict: (event) => onNodeLockConflictRef.current?.(event),\n })\n return () => store.setGestureHandlers({})\n }, [store])\n\n // Controlled mode: mirror the incoming props into the store. A live gesture\n // isn't skipped wholesale — reconcile keeps held nodes' geometry (the props\n // lag the store while live frames are dropped, so taking them would stomp the\n // moving box) and applies everything else, so a peer's rename still lands on a\n // node this client is dragging. The commit emits a final change that re-runs\n // this and settles the store.\n const isControlled = controlledNodes !== undefined || controlledEdges !== undefined\n useEffect(() => {\n if (!isControlled) return\n store.reconcile(\n controlledNodes ?? [...store.nodes.values()],\n controlledEdges ?? [...store.edges.values()],\n )\n }, [store, isControlled, controlledNodes, controlledEdges])\n\n const swimlanes = useSwimlanes({\n store,\n swimlane,\n swimlaneMargin: cfg.swimlaneMargin,\n swimlaneResizable,\n clampToSwimlane,\n swimlaneBottomReveal,\n onSwimlaneSizeChange,\n })\n\n // Right-click routing: swimlane group header → lane label → empty pane.\n const handleContextMenu = useCallback(\n (event: ReactMouseEvent<HTMLDivElement>) => {\n if (event.target instanceof Element && event.target.closest(SELECTOR.node)) return\n const viewport = store.getViewport()\n const rect = paneRef.current?.getBoundingClientRect()\n const point = { x: event.clientX - (rect?.left ?? 0), y: event.clientY - (rect?.top ?? 0) }\n if (swimlanes.groups.length > 0) {\n const hit = swimlaneChromeAt(\n swimlanes.groups,\n viewport,\n point,\n swimlaneHeaderHeight,\n SWIMLANE_LABEL_WIDTH,\n )\n if (hit?.type === \"group\") return onSwimlaneGroupHeaderContextMenu?.(hit.id, event)\n if (hit?.type === \"lane\") return onSwimlaneHeaderContextMenu?.(hit.id, event)\n }\n // Resolve the click into graph terms: world position, and the lane whose\n // body it lands in (within its vertical band, right of its left edge).\n const world = screenToWorld(point, viewport)\n const lane =\n swimlanes.lanes.find(\n (l) => world.y >= l.top && world.y <= l.top + l.height && world.x >= l.x,\n ) ?? null\n onPaneContextMenu?.(event, { world, lane })\n },\n [\n store,\n swimlanes.groups,\n swimlanes.lanes,\n swimlaneHeaderHeight,\n onPaneContextMenu,\n onSwimlaneHeaderContextMenu,\n onSwimlaneGroupHeaderContextMenu,\n ],\n )\n\n const paneRef = useRef<HTMLDivElement>(null)\n const nodeContainerRef = useRef<HTMLDivElement>(null)\n const backgroundCanvasRef = useRef<HTMLCanvasElement>(null)\n const edgeCanvasRef = useRef<HTMLCanvasElement>(null)\n const foregroundCanvasRef = useRef<HTMLCanvasElement>(null)\n const cursorCanvasRef = useRef<HTMLCanvasElement>(null)\n\n // Presence, inbound: mirror the roster into the registry the render loop\n // paints from. Only when the prop is in use — a consumer driving presence\n // purely through `setPeerCursor` has no roster to be overwritten by.\n useEffect(() => {\n if (peers === undefined) return\n store.presence.setPeers(peers)\n }, [store, peers])\n\n // Locks. The policy goes in through a ref-backed forwarder because it's read\n // on the input path — an inline arrow would otherwise reinstall it on every\n // render, and `null` vs. a function is the difference between rivet's\n // defaults and the consumer's.\n const canInteractWithLockedRef = useRef(canInteractWithLocked)\n canInteractWithLockedRef.current = canInteractWithLocked\n const hasLockPolicy = Boolean(canInteractWithLocked)\n useEffect(() => {\n store.locks.setPolicy(\n hasLockPolicy ? (event) => canInteractWithLockedRef.current?.(event) ?? true : null,\n )\n return () => store.locks.setPolicy(null)\n }, [store, hasLockPolicy])\n // Installed after the policy, so the first refusal a freshly locked node\n // meets is already the consumer's. An unchanged table is a no-op, so an\n // inline object literal costs nothing.\n useEffect(() => {\n store.setLockedNodes(lockedNodes)\n }, [store, lockedNodes])\n\n // Presence, outbound: this client's cursor/selection/held snapshot.\n useLocalPresence({ store, paneRef, onLocalPresence, throttleMs: cfg.presenceOptions.throttleMs })\n\n const { visibleIds, controls, getViewportElements } = useRivetRuntime({\n store,\n paneRef,\n nodeContainerRef,\n backgroundCanvasRef,\n edgeCanvasRef,\n foregroundCanvasRef,\n cursorCanvasRef,\n swimlaneLanes: swimlanes.lanes,\n edgeTypes: cfg.edgeTypes,\n defaultEdgeOptions: cfg.defaultEdgeOptions,\n anchorOptions: cfg.anchorOptions,\n edgeRenderer: renderer,\n edgesReconnectable,\n isValidConnection: cfg.isValidConnection,\n mapConnection: mapConnectionWithAnchors,\n onReconnect,\n onReconnectStart,\n onReconnectEnd,\n panButtons: cfg.panButtons,\n selectionOnDrag,\n selectionKeys: cfg.selectionKeys,\n multiSelectionKeys: cfg.multiSelectionKeys,\n scrollToPan,\n zoomSpeed,\n minZoom,\n maxZoom,\n gridGap,\n snapGrid: cfg.snapGrid,\n })\n\n const contextValue = useMemo<RivetContextValue>(\n () => ({\n store,\n nodeTypes: cfg.nodeTypes,\n paneRef,\n controls,\n getViewportElements,\n multiSelectionKeys: cfg.multiSelectionKeys,\n announce,\n nodeDescriptionId,\n defaultEdgeOptions: cfg.defaultEdgeOptions,\n snapGrid: cfg.snapGrid,\n alignmentGuides,\n anchorOptions: cfg.anchorOptions,\n swimlaneGroups: swimlanes.groups,\n swimlaneLanes: swimlanes.lanes,\n clampToSwimlane: swimlanes.clampEnabled,\n swimlaneMargin: swimlanes.margin,\n swimlaneLabelWidth: SWIMLANE_LABEL_WIDTH,\n swimlaneHeaderSize: swimlaneHeaderHeight,\n swimlaneResizable: swimlanes.resizableEnabled,\n resizeSwimlane: swimlanes.resizeSwimlane,\n renderSwimlaneHeader: cfg.renderSwimlaneHeader,\n renderSwimlaneLabel: cfg.renderSwimlaneLabel,\n onLaneChange: cfg.onLaneChange,\n isValidConnection: cfg.isValidConnection,\n mapConnection: mapConnectionWithAnchors,\n onConnect: cfg.onConnect,\n }),\n [\n store,\n cfg.nodeTypes,\n controls,\n getViewportElements,\n cfg.multiSelectionKeys,\n announce,\n nodeDescriptionId,\n cfg.defaultEdgeOptions,\n cfg.snapGrid,\n alignmentGuides,\n cfg.anchorOptions,\n swimlanes.groups,\n swimlanes.lanes,\n swimlanes.clampEnabled,\n swimlanes.margin,\n swimlaneHeaderHeight,\n swimlanes.resizableEnabled,\n swimlanes.resizeSwimlane,\n cfg.renderSwimlaneHeader,\n cfg.renderSwimlaneLabel,\n cfg.onLaneChange,\n cfg.isValidConnection,\n mapConnectionWithAnchors,\n cfg.onConnect,\n ],\n )\n\n return (\n <RivetContext.Provider value={contextValue}>\n <div\n ref={paneRef}\n className={className}\n style={{ ...paneStyle, ...style }}\n onContextMenu={handleContextMenu}\n role=\"application\"\n aria-label={ariaLabel ?? \"Node graph\"}\n >\n <canvas ref={backgroundCanvasRef} style={canvasStyle} />\n <canvas ref={edgeCanvasRef} style={canvasStyle} />\n <NodeLayer containerRef={nodeContainerRef} visibleIds={visibleIds} />\n <canvas ref={foregroundCanvasRef} style={canvasStyle} />\n {/*\n Peer cursors, one layer up. They repaint at pointer rate and nothing\n below them depends on where they are, so they get a canvas that can be\n cleared alone. `renderCursors: false` doesn't hide the layer, it never\n creates it — the runtime resolves this ref every frame.\n */}\n {cfg.presenceOptions.renderCursors && <canvas ref={cursorCanvasRef} style={canvasStyle} />}\n <EdgeLabelLayer />\n <SwimlaneOverlay />\n {children}\n <div id={nodeDescriptionId} style={srOnlyStyle}>\n {NODE_KEYBOARD_INSTRUCTIONS}\n </div>\n <div style={srOnlyStyle} role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">\n {announcement}\n </div>\n </div>\n </RivetContext.Provider>\n )\n}\n","import { useMemo } from \"react\"\nimport type { AnchorRegistration, AnchorRegistrationOptions } from \"../anchor/registry\"\nimport { type ClonedElements, cloneElements } from \"../clipboard\"\nimport { useRivetContext } from \"../context\"\nimport { serializeGraph } from \"../graph\"\nimport type { RemoteChanges, RivetStore } from \"../store\"\nimport type { ViewportElements } from \"../swimlane/lanes\"\nimport type {\n EdgeId,\n NodeId,\n Rect,\n RivetControls,\n RivetEdge,\n RivetNode,\n RivetSnapshot,\n Vec2,\n} from \"../types\"\n\ntype Updater<T> = T | ((current: T) => T)\n\n/** In-memory clipboard shared by every instance of the same graph. */\nconst clipboards = new WeakMap<RivetStore, ClonedElements>()\n/** Default diagonal nudge so a paste/duplicate doesn't land exactly on top. */\nconst PASTE_OFFSET: Vec2 = { x: 24, y: 24 }\n\n/**\n * Imperative handle to the graph, returned by {@link useRivet}. Parameterize it\n * with your node/edge `data` types — `useRivet<MyNodeData, MyEdgeData>()` — so\n * `getNodes`, `toObject`, etc. hand those types back instead of `unknown`.\n */\nexport type RivetInstance<TNodeData = unknown, TEdgeData = unknown> = RivetControls & {\n /** Snapshot the nodes and lanes currently on screen. Reads the viewport once — never subscribes. */\n getViewportElements: () => ViewportElements<TNodeData>\n /** Serializable snapshot of nodes, edges, and viewport. Safe to `JSON.stringify`. */\n toObject: () => RivetSnapshot<TNodeData, TEdgeData>\n getNodes: () => RivetNode<TNodeData>[]\n getNode: (id: NodeId) => RivetNode<TNodeData> | undefined\n /**\n * A node's box in **world** coordinates — its `parentId` chain resolved, and\n * its explicit or measured size applied. `null` for an id that isn't in the\n * graph.\n *\n * This is where the node currently *is on screen*, not what the document\n * says: a node a peer is dragging or resizing reports the box they last sent\n * (see {@link setPeerNodeTransform}), which is what anything painting over\n * the graph wants. Reach for {@link getNode} instead when you're computing a\n * mutation — that position is the one the document will agree with.\n *\n * Reads once; never subscribes. Call it inside your own frame loop.\n */\n getNodeRect: (id: NodeId) => Rect | null\n setNodes: (nodes: Updater<RivetNode<TNodeData>[]>) => void\n addNodes: (nodes: RivetNode<TNodeData> | RivetNode<TNodeData>[]) => void\n updateNode: (id: NodeId, patch: Updater<RivetNode<TNodeData>>) => void\n getEdges: () => RivetEdge<TEdgeData>[]\n getEdge: (id: EdgeId) => RivetEdge<TEdgeData> | undefined\n setEdges: (edges: Updater<RivetEdge<TEdgeData>[]>) => void\n addEdges: (edges: RivetEdge<TEdgeData> | RivetEdge<TEdgeData>[]) => void\n updateEdge: (id: EdgeId, patch: Updater<RivetEdge<TEdgeData>>) => void\n /** Delete nodes (and their edges) and/or edges by id. */\n deleteElements: (elements: { nodes?: NodeId[]; edges?: EdgeId[] }) => void\n /**\n * Apply a change batch that already happened elsewhere — a peer's edit off\n * your transport. The graph updates and repaints, then re-emits the batch to\n * `onNodesChange`/`onEdgesChange` tagged `\"remote\"`, so a controlled owner\n * keeps its state in step through the one path it already has.\n *\n * Remote batches never create an undo step; in a shared document, undoing a\n * peer's edit would silently revert work you don't own.\n *\n * ```ts\n * connection.onNodeMoved((row) => {\n * if (row.caller === me) return // your own echo — already applied\n * rivet.applyRemote({\n * nodes: [{ type: \"position\", id: row.id, position: row.position }],\n * })\n * })\n * ```\n */\n applyRemote: (changes: RemoteChanges) => void\n /**\n * Bind an anchor — a connectable point — to a DOM element inside a node.\n * The imperative core behind `<Anchor>`, for consumers whose content DOM is\n * owned by another renderer (a rich-text editor's contentEditable, say).\n * Idempotent on `(nodeId, anchorId)`; the returned registration re-binds a\n * replaced element or unregisters explicitly.\n */\n registerAnchor: (\n nodeId: NodeId,\n anchorId: string,\n element: Element,\n options?: AnchorRegistrationOptions,\n ) => AnchorRegistration\n /**\n * Explicitly remove an anchor and its chrome. Unmounting `<Anchor>` (or\n * rebinding `null`) only *detaches* — geometry and edges are retained — so\n * call this when the anchored content is gone for good, alongside deleting\n * its edges.\n */\n unregisterAnchor: (nodeId: NodeId, anchorId: string) => void\n /**\n * Re-measure a node's anchors. Automatic on node resize; needed after a\n * content reflow that keeps the node box (an editor transaction, a font\n * load) — rivet can't observe those.\n */\n remeasureAnchors: (nodeId: NodeId) => void\n /**\n * Move a peer's cursor, in **world** coordinates (peers pan and zoom\n * independently, so a screen point means nothing to them). `null` parks it.\n *\n * The presence hot path: it paints on the next frame without going through\n * React, so call it as fast as your channel delivers. A peer the `peers`\n * roster hasn't mentioned yet still gets a cursor — a frame that beats the\n * join event shouldn't blink.\n */\n setPeerCursor: (peerId: string, point: Vec2 | null) => void\n /**\n * Show a node where a peer currently has it, in world space — their drag,\n * mid-flight. The node renders, hit-tests and wires at that box until their\n * change lands through {@link applyRemote}; the graph itself is untouched.\n * Pass `null` on their drop.\n */\n setPeerNodeTransform: (peerId: string, nodeId: NodeId, rect: Rect | null) => void\n /** Forget a peer entirely — cursor, held nodes and all. For a disconnect. */\n removePeer: (peerId: string) => void\n /**\n * Give up a gesture's hold on its nodes without committing — the yield lever\n * for `onNodeLockConflict`, when your transport says this client lost the\n * race for a node it's already dragging.\n *\n * The running gesture notices on its next frame, stops writing, and tears\n * itself down; the nodes stay where they are and the holder's positions land\n * normally from then on. `onNodeDragEnd` fires as it would on a drop, so a\n * consumer's own lock release runs unchanged. Pass the conflict event's\n * `ids` to release a whole group.\n *\n * Doing nothing is also a valid answer: without this call the gesture keeps\n * its nodes until the pointer lifts.\n */\n releaseNodeGesture: (id: NodeId, ids?: NodeId[]) => void\n /** Copy nodes (default: the current selection) to the in-memory clipboard. */\n copy: (ids?: NodeId[]) => void\n /** Copy then delete nodes (default: the current selection). */\n cut: (ids?: NodeId[]) => void\n /** Paste the clipboard as fresh, selected nodes offset from the originals. No-op when empty. */\n paste: (options?: { offset?: Vec2 }) => ClonedElements<TNodeData, TEdgeData> | undefined\n /** Clone nodes (default: the current selection) in place with fresh ids, and select them. */\n duplicate: (ids?: NodeId[]) => ClonedElements<TNodeData, TEdgeData> | undefined\n /** Revert the last recordable change. Returns false when there's nothing to undo. */\n undo: () => boolean\n /** Re-apply the last undone change. Returns false when there's nothing to redo. */\n redo: () => boolean\n canUndo: () => boolean\n canRedo: () => boolean\n /** Drop all undo/redo history and reset the baseline to the current graph. */\n clearHistory: () => void\n}\n\nfunction buildInstance<TNodeData, TEdgeData>(\n store: RivetStore,\n controls: RivetControls,\n getViewportElements: () => ViewportElements,\n): RivetInstance<TNodeData, TEdgeData> {\n // The store is data-agnostic (`unknown`); the generic asserts the caller's type\n // at this boundary, the way React Flow's typed `useReactFlow` does.\n const getNodes = () => [...store.nodes.values()] as RivetNode<TNodeData>[]\n const getEdges = () => [...store.edges.values()] as RivetEdge<TEdgeData>[]\n\n const setNodes: RivetInstance<TNodeData, TEdgeData>[\"setNodes\"] = (arg) => {\n const next = typeof arg === \"function\" ? arg(getNodes()) : arg\n const nextIds = new Set(next.map((node) => node.id))\n for (const current of getNodes()) {\n if (!nextIds.has(current.id)) store.removeNode(current.id)\n }\n for (const node of next) {\n if (store.nodes.has(node.id)) store.replaceNode(node.id, node)\n else store.addNode(node)\n }\n }\n\n const setEdges: RivetInstance<TNodeData, TEdgeData>[\"setEdges\"] = (arg) => {\n const next = typeof arg === \"function\" ? arg(getEdges()) : arg\n const nextIds = new Set(next.map((edge) => edge.id))\n for (const current of getEdges()) {\n if (!nextIds.has(current.id)) store.removeEdge(current.id)\n }\n for (const edge of next) {\n if (store.edges.has(edge.id)) store.replaceEdge(edge.id, edge)\n else store.addEdge(edge)\n }\n }\n\n // Copy `ids` (and the edges wholly between them) into a detached snapshot the\n // clipboard/paste path won't see mutate.\n const snapshot = (ids: NodeId[]): ClonedElements<TNodeData, TEdgeData> => {\n const nodes = ids\n .map((id) => store.nodes.get(id))\n .filter((node): node is RivetNode => node !== undefined)\n .map((node) => ({ ...node, position: { ...node.position } })) as RivetNode<TNodeData>[]\n const idSet = new Set(nodes.map((node) => node.id))\n const edges = (getEdges() as RivetEdge<TEdgeData>[])\n .filter((edge) => idSet.has(edge.source) && idSet.has(edge.target))\n .map((edge) => ({ ...edge }))\n return { nodes, edges }\n }\n\n // Clone a snapshot with fresh ids at `offset`, add it, and select the clones.\n const insert = (\n source: ClonedElements<TNodeData, TEdgeData>,\n offset: Vec2,\n ): ClonedElements<TNodeData, TEdgeData> => {\n const cloned = cloneElements(source.nodes, source.edges, { offset })\n for (const node of cloned.nodes) store.addNode(node)\n for (const edge of cloned.edges) store.addEdge(edge)\n store.selectNodes(cloned.nodes.map((node) => node.id))\n return cloned\n }\n\n return {\n ...controls,\n getViewportElements: getViewportElements as () => ViewportElements<TNodeData>,\n toObject: () =>\n serializeGraph<TNodeData, TEdgeData>(\n store.nodes.values() as Iterable<RivetNode<TNodeData>>,\n store.edges.values() as Iterable<RivetEdge<TEdgeData>>,\n store.getViewport(),\n ),\n getNodes,\n getNode: (id) => store.nodes.get(id) as RivetNode<TNodeData> | undefined,\n // The store's own `getNodeRect` answers for any id, falling back to the\n // origin and the default size; a public caller needs to tell \"it's there,\n // at 0,0\" from \"it isn't there\".\n getNodeRect: (id) => (store.nodes.has(id) ? store.getNodeRect(id) : null),\n setNodes,\n addNodes: (nodes) => {\n for (const node of Array.isArray(nodes) ? nodes : [nodes]) store.addNode(node)\n },\n updateNode: (id, patch) => {\n const current = store.nodes.get(id) as RivetNode<TNodeData> | undefined\n if (!current) return\n store.replaceNode(id, typeof patch === \"function\" ? patch(current) : patch)\n },\n getEdges,\n getEdge: (id) => store.edges.get(id) as RivetEdge<TEdgeData> | undefined,\n setEdges,\n addEdges: (edges) => {\n for (const edge of Array.isArray(edges) ? edges : [edges]) store.addEdge(edge)\n },\n updateEdge: (id, patch) => {\n const current = store.edges.get(id) as RivetEdge<TEdgeData> | undefined\n if (!current) return\n store.replaceEdge(id, typeof patch === \"function\" ? patch(current) : patch)\n },\n deleteElements: ({ nodes, edges }) => {\n for (const id of edges ?? []) store.removeEdge(id)\n for (const id of nodes ?? []) store.removeNode(id)\n },\n applyRemote: (changes) => store.applyRemote(changes),\n registerAnchor: (nodeId, anchorId, element, options) => {\n store.registerAnchor(nodeId, anchorId, element, options)\n return {\n rebind: (el) =>\n el === null\n ? store.detachAnchor(nodeId, anchorId)\n : store.registerAnchor(nodeId, anchorId, el, options),\n unregister: () => store.unregisterAnchor(nodeId, anchorId),\n }\n },\n unregisterAnchor: (nodeId, anchorId) => store.unregisterAnchor(nodeId, anchorId),\n remeasureAnchors: (nodeId) => store.remeasureAnchors(nodeId),\n setPeerCursor: (peerId, point) => store.presence.setPeerCursor(peerId, point),\n setPeerNodeTransform: (peerId, nodeId, rect) =>\n store.presence.setPeerNodeTransform(peerId, nodeId, rect),\n removePeer: (peerId) => store.presence.removePeer(peerId),\n releaseNodeGesture: (id, ids) => store.endNodeGesture(id, ids),\n copy: (ids) => {\n const targetIds = ids ?? store.getSelectedNodes()\n if (targetIds.length === 0) return\n clipboards.set(store, snapshot(targetIds))\n },\n cut: (ids) => {\n const targetIds = ids ?? store.getSelectedNodes()\n if (targetIds.length === 0) return\n clipboards.set(store, snapshot(targetIds))\n for (const id of targetIds) store.removeNode(id)\n },\n paste: (options) => {\n const clip = clipboards.get(store) as ClonedElements<TNodeData, TEdgeData> | undefined\n if (!clip || clip.nodes.length === 0) return\n return insert(clip, options?.offset ?? PASTE_OFFSET)\n },\n duplicate: (ids) => {\n const targetIds = ids ?? store.getSelectedNodes()\n if (targetIds.length === 0) return\n return insert(snapshot(targetIds), PASTE_OFFSET)\n },\n undo: () => store.undo(),\n redo: () => store.redo(),\n canUndo: () => store.canUndo(),\n canRedo: () => store.canRedo(),\n clearHistory: () => store.clearHistory(),\n }\n}\n\n/**\n * Imperative access to the graph from any component inside `<Rivet>` — CRUD on\n * nodes/edges plus the viewport controls. Backed by the same store that drives\n * rendering, so mutations are reflected immediately and (in controlled mode) emit\n * changes to `onNodesChange`/`onEdgesChange`.\n *\n * Parameterize with your `data` types to keep them through the API:\n * `const rivet = useRivet<MyNodeData, MyEdgeData>()`.\n */\nexport function useRivet<TNodeData = unknown, TEdgeData = unknown>(): RivetInstance<\n TNodeData,\n TEdgeData\n> {\n const { store, controls, getViewportElements } = useRivetContext()\n return useMemo(\n () => buildInstance<TNodeData, TEdgeData>(store, controls, getViewportElements),\n [store, controls, getViewportElements],\n )\n}\n","export { alignRect } from \"./align\"\nexport { applyEdgeChanges, applyNodeChanges } from \"./changes\"\nexport { type ClonedElements, type CloneOptions, cloneElements } from \"./clipboard\"\nexport { Controls, type ControlsProps } from \"./components/controls\"\nexport { DefaultNode } from \"./components/default-node\"\nexport { BUILTIN_NODE_TYPES, GroupNode } from \"./components/group-node\"\nexport { Handle, type HandleProps } from \"./components/handle\"\nexport { MiniMap, type MiniMapProps } from \"./components/minimap\"\nexport { NodeResizer, type NodeResizerProps } from \"./components/node-resizer\"\nexport { type PaneContextMenuContext, Rivet, type RivetProps } from \"./components/rivet\"\nexport {\n useRivetContext,\n useRivetControls,\n useRivetFocusedNode,\n useRivetHistory,\n useRivetViewport,\n} from \"./context\"\nexport {\n DEFAULT_ALIGNMENT_HYSTERESIS,\n type EdgeAlignment,\n facingSide,\n resolveFacingSide,\n resolveFacingSideAmong,\n} from \"./edge-alignment\"\nexport {\n type EdgeEndpoint,\n edgeEndpointHandle,\n parseEdgeEndpoint,\n parseSideHandleId,\n} from \"./edge-ends\"\nexport { boundingRect, clampChildToParent, serializeGraph, snapToGrid } from \"./graph\"\nexport { useNodeLock, useNodeLockAllows } from \"./hooks/use-node-lock\"\nexport { type RivetInstance, useRivet } from \"./hooks/use-rivet\"\nexport {\n type CanInteractWithLocked,\n LOCK_DEFAULT_REFUSED,\n type LockIntent,\n type LockInteraction,\n type LockRegistry,\n type NodeLock,\n} from \"./locks/registry\"\nexport { Canvas2DEdgeRenderer, canvas2DEdgeRenderer } from \"./renderer/canvas-2d-edge-renderer\"\nexport {\n BUILTIN_EDGE_TYPES,\n getBezierPath,\n getSmoothStepPath,\n getStepPath,\n getStraightPath,\n} from \"./renderer/edge-paths\"\nexport { createRivetStore, handleKey, type RemoteChanges, type RivetStore } from \"./store\"\nexport type {\n AlignmentGuide,\n CenterNodeOptions,\n ChangeMeta,\n ChangeOrigin,\n Connection,\n DefaultEdgeOptions,\n EdgeChange,\n EdgeDrawExtras,\n EdgeEnd,\n EdgeId,\n EdgeMarker,\n EdgePath,\n EdgePathFn,\n EdgePathParams,\n EdgeRenderer,\n EdgeRendererFactory,\n EdgeRendererOptions,\n EdgeStyle,\n EdgeTypes,\n FitViewOptions,\n HandlePosition,\n HandleRecord,\n HandleType,\n NodeChange,\n NodeComponent,\n NodeGestureEvent,\n NodeId,\n NodeLockConflictEvent,\n NodeProps,\n NodeTypes,\n PendingConnection,\n ReconnectDelegate,\n Rect,\n RivetControls,\n RivetEdge,\n RivetNode,\n RivetSelection,\n RivetSnapshot,\n Size,\n Vec2,\n Viewport,\n} from \"./types\"\nexport {\n rectsIntersect,\n screenToWorld,\n viewportToCss,\n visibleWorldRect,\n worldToScreen,\n zoomAt,\n} from \"./viewport\"\n\nexport const VERSION = \"0.0.0\"\n"]}
1
+ {"version":3,"sources":["../src/align.ts","../src/changes.ts","../src/clipboard.ts","../src/components/controls.tsx","../../utils/src/id.ts","../src/constants.ts","../src/edge-alignment.ts","../src/edge-ends.ts","../src/gesture-guard.ts","../src/history.ts","../src/viewport.ts","../src/renderer/edge-paths.ts","../src/renderer/edge-geometry.ts","../src/store.ts","../src/connection.ts","../src/input/connection-drag.ts","../src/components/handle.tsx","../src/components/default-node.tsx","../src/components/group-node.tsx","../src/components/minimap.tsx","../src/components/node-resizer.tsx","../src/presence/local.ts","../src/hooks/use-local-presence.ts","../src/hooks/use-rivet-config.ts","../src/input/keyboard.ts","../src/input/keys.ts","../src/input/layer-hint.ts","../src/input/marquee-controller.ts","../src/input/pan-controller.ts","../src/input/resize-controller.ts","../src/input/zoom-controller.ts","../src/renderer/background.ts","../src/renderer/presence.ts","../src/renderer/swimlane.ts","../src/hooks/use-rivet-runtime.ts","../src/hooks/use-swimlanes.ts","../src/renderer/canvas-2d-edge-renderer.ts","../src/components/edge-label-layer.tsx","../src/input/group-drag.ts","../src/anchor/select-gesture.ts","../src/components/node-anchors.tsx","../src/components/node-wrapper.tsx","../src/components/nodes-selection.tsx","../src/components/node-layer.tsx","../src/components/peer-cursor-layer.tsx","../src/components/peer-outline-layer.tsx","../src/components/swimlane-overlay.tsx","../src/components/rivet.tsx","../src/hooks/use-rivet.ts","../src/index.ts"],"names":["side","id","jsx","jsxs","baseStyle","hoveredStyle","selectedStyle","useRef","useEffect","Fragment","CULL_MARGIN_PX","useMemo","size","useState","useCallback","peerColor","labelStyle","sameIds","useSyncExternalStore","NodeWrapper","node","memo","NodesSelection","rect","overlayStyle","useLayoutEffect","wrapperStyle","projectRect","containerStyle"],"mappings":";;;;;;;;;;AAGA,IAAM,MAAA,GAAS,CAAC,CAAA,KAAsC,CAAC,EAAE,CAAA,EAAG,CAAA,CAAE,CAAA,GAAI,CAAA,CAAE,KAAA,GAAQ,CAAA,EAAG,CAAA,CAAE,CAAA,GAAI,EAAE,KAAK,CAAA;AAC5F,IAAM,MAAA,GAAS,CAAC,CAAA,KAAsC,CAAC,EAAE,CAAA,EAAG,CAAA,CAAE,CAAA,GAAI,CAAA,CAAE,MAAA,GAAS,CAAA,EAAG,CAAA,CAAE,CAAA,GAAI,EAAE,MAAM,CAAA;AAUvF,SAAS,SAAA,CACd,MAAA,EACA,OAAA,EACA,SAAA,EAC4C;AAC5C,EAAA,MAAM,EAAA,GAAK,OAAO,MAAM,CAAA;AACxB,EAAA,MAAM,EAAA,GAAK,OAAO,MAAM,CAAA;AACxB,EAAA,IAAI,KAAA,GAAqB,IAAA;AACzB,EAAA,IAAI,KAAA,GAAqB,IAAA;AAEzB,EAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,IAAA,MAAM,EAAA,GAAK,OAAO,KAAK,CAAA;AACvB,IAAA,MAAM,EAAA,GAAK,OAAO,KAAK,CAAA;AACvB,IAAA,KAAA,MAAW,MAAM,EAAA,EAAI;AACnB,MAAA,KAAA,MAAW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KAAA,CAAM,IAAA,EAAK;AAAA,IACvB,OAAA,EAAS,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,IAC7B,OAAA,EAAS,MAAM,KAAA,CAAM,OAAA,EAAQ;AAAA,IAC7B,YAAA,EAAc,MAAM,KAAA,CAAM,YAAA;AAAa,GACzC;AACF;AAWO,SAAS,QAAA,GAGd;AACA,EAAA,MAAM,EAAE,KAAA,EAAO,QAAA,EAAU,mBAAA,KAAwB,eAAA,EAAgB;AACjE,EAAA,OAAOS,OAAAA;AAAA,IACL,MAAM,aAAA,CAAoC,KAAA,EAAO,QAAA,EAAU,mBAAmB,CAAA;AAAA,IAC9E,CAAC,KAAA,EAAO,QAAA,EAAU,mBAAmB;AAAA,GACvC;AACF;;;AC7PO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["import type { AlignmentGuide, Rect, Vec2 } from \"./types\"\n\n/** The three snap edges along X (left, center, right) and Y (top, center, bottom). */\nconst edgesX = (r: Rect): [number, number, number] => [r.x, r.x + r.width / 2, r.x + r.width]\nconst edgesY = (r: Rect): [number, number, number] => [r.y, r.y + r.height / 2, r.y + r.height]\n\ntype Best = { delta: number; position: number; other: Rect }\n\n/**\n * Find the closest edge alignment between the moving rect and any static rect,\n * within `threshold` (world units), independently per axis. Returns the offset\n * to apply to `moving` so its aligned edge lands exactly on the neighbor's, plus\n * the guide line(s) to draw. Pure — the drag loop supplies the rects.\n */\nexport function alignRect(\n moving: Rect,\n statics: readonly Rect[],\n threshold: number,\n): { offset: Vec2; guides: AlignmentGuide[] } {\n const mX = edgesX(moving)\n const mY = edgesY(moving)\n let bestX: Best | null = null\n let bestY: Best | null = null\n\n for (const other of statics) {\n const oX = edgesX(other)\n const oY = edgesY(other)\n for (const me of mX) {\n for (const oe of oX) {\n const delta = oe - me\n if (Math.abs(delta) <= threshold && (!bestX || Math.abs(delta) < Math.abs(bestX.delta))) {\n bestX = { delta, position: oe, other }\n }\n }\n }\n for (const me of mY) {\n for (const oe of oY) {\n const delta = oe - me\n if (Math.abs(delta) <= threshold && (!bestY || Math.abs(delta) < Math.abs(bestY.delta))) {\n bestY = { delta, position: oe, other }\n }\n }\n }\n }\n\n const offset: Vec2 = { x: bestX?.delta ?? 0, y: bestY?.delta ?? 0 }\n const guides: AlignmentGuide[] = []\n if (bestX) {\n const o = bestX.other\n guides.push({\n axis: \"x\",\n position: bestX.position,\n start: Math.min(moving.y + offset.y, o.y),\n end: Math.max(moving.y + moving.height + offset.y, o.y + o.height),\n })\n }\n if (bestY) {\n const o = bestY.other\n guides.push({\n axis: \"y\",\n position: bestY.position,\n start: Math.min(moving.x + offset.x, o.x),\n end: Math.max(moving.x + moving.width + offset.x, o.x + o.width),\n })\n }\n return { offset, guides }\n}\n","import type { EdgeChange, EdgeId, NodeChange, NodeId, RivetEdge, RivetNode } from \"./types\"\n\n/**\n * Apply a batch of {@link NodeChange}s to a nodes array, returning a new array\n * (the input is not mutated). Order is preserved; added nodes are appended.\n *\n * Pair this with the graph's `onNodesChange` to run controlled mode:\n * ```ts\n * const [nodes, setNodes] = useState(initial)\n * <Rivet nodes={nodes} onNodesChange={(c) => setNodes((ns) => applyNodeChanges(c, ns))} />\n * ```\n */\nexport function applyNodeChanges<TData = unknown>(\n changes: NodeChange<TData>[],\n nodes: RivetNode<TData>[],\n): RivetNode<TData>[] {\n if (changes.length === 0) return nodes\n\n const byId = new Map<NodeId, RivetNode<TData>>(nodes.map((node) => [node.id, node]))\n const order: NodeId[] = nodes.map((node) => node.id)\n\n for (const change of changes) {\n switch (change.type) {\n case \"add\": {\n if (!byId.has(change.item.id)) order.push(change.item.id)\n byId.set(change.item.id, change.item)\n break\n }\n case \"replace\": {\n byId.set(change.id, change.item)\n break\n }\n case \"remove\": {\n byId.delete(change.id)\n break\n }\n case \"position\": {\n const node = byId.get(change.id)\n if (node) {\n byId.set(change.id, {\n ...node,\n position: change.position ?? node.position,\n dragging: change.dragging,\n })\n }\n break\n }\n case \"dimensions\": {\n const node = byId.get(change.id)\n if (node) {\n byId.set(change.id, {\n ...node,\n size: change.dimensions,\n // A resize (not a measurement) sets explicit width/height.\n ...(change.resizing !== undefined\n ? { width: change.dimensions.width, height: change.dimensions.height }\n : {}),\n })\n }\n break\n }\n case \"select\": {\n const node = byId.get(change.id)\n if (node) byId.set(change.id, { ...node, selected: change.selected })\n break\n }\n }\n }\n\n const result: RivetNode<TData>[] = []\n for (const id of order) {\n const node = byId.get(id)\n if (node) result.push(node)\n }\n return result\n}\n\n/**\n * Apply a batch of {@link EdgeChange}s to an edges array, returning a new array.\n * Order is preserved; added edges are appended. See {@link applyNodeChanges}.\n */\nexport function applyEdgeChanges<TData = unknown>(\n changes: EdgeChange<TData>[],\n edges: RivetEdge<TData>[],\n): RivetEdge<TData>[] {\n if (changes.length === 0) return edges\n\n const byId = new Map<EdgeId, RivetEdge<TData>>(edges.map((edge) => [edge.id, edge]))\n const order: EdgeId[] = edges.map((edge) => edge.id)\n\n for (const change of changes) {\n switch (change.type) {\n case \"add\": {\n if (!byId.has(change.item.id)) order.push(change.item.id)\n byId.set(change.item.id, change.item)\n break\n }\n case \"replace\": {\n byId.set(change.id, change.item)\n break\n }\n case \"remove\": {\n byId.delete(change.id)\n break\n }\n case \"select\": {\n const edge = byId.get(change.id)\n if (edge) byId.set(change.id, { ...edge, selected: change.selected })\n break\n }\n }\n }\n\n const result: RivetEdge<TData>[] = []\n for (const id of order) {\n const edge = byId.get(id)\n if (edge) result.push(edge)\n }\n return result\n}\n","import type { NodeId, RivetEdge, RivetNode, Vec2 } from \"./types\"\n\nconst ORIGIN: Vec2 = { x: 0, y: 0 }\nconst defaultId = (): NodeId => crypto.randomUUID()\n\n/** Options for {@link cloneElements}. */\nexport type CloneOptions = {\n /**\n * World-space offset applied to every top-level clone's position. Children of\n * a copied parent keep their parent-relative position and ride along.\n * Default `{0,0}`.\n */\n offset?: Vec2\n /** Id generator for the clones. Default `crypto.randomUUID`. */\n makeId?: () => NodeId\n}\n\n/** The result of {@link cloneElements}: fresh nodes and their internal edges. */\nexport type ClonedElements<TNodeData = unknown, TEdgeData = unknown> = {\n nodes: RivetNode<TNodeData>[]\n edges: RivetEdge<TEdgeData>[]\n}\n\n/**\n * Clone a set of nodes (and the edges wholly between them) with fresh ids —\n * the core of copy/paste and duplicate. Edges are kept only when **both**\n * endpoints are in the set (dangling connections to un-copied nodes are\n * dropped). `parentId` is remapped when the parent is also copied, else cleared\n * so the clone isn't orphaned to a missing parent. Transient flags are stripped;\n * selecting the clones is the caller's job.\n */\nexport function cloneElements<TNodeData = unknown, TEdgeData = unknown>(\n nodes: RivetNode<TNodeData>[],\n edges: RivetEdge<TEdgeData>[],\n options: CloneOptions = {},\n): ClonedElements<TNodeData, TEdgeData> {\n const offset = options.offset ?? ORIGIN\n const makeId = options.makeId ?? defaultId\n\n const idMap = new Map<NodeId, NodeId>()\n for (const node of nodes) idMap.set(node.id, makeId())\n const remap = (id: NodeId): NodeId => idMap.get(id) ?? id\n\n const clonedNodes = nodes.map((node) => {\n // A child of a copied parent keeps its parent-relative position — the\n // subtree shifts once, through the parent. Offsetting it too would move it\n // a second time inside the cloned parent's box.\n const parentCopied = node.parentId !== undefined && idMap.has(node.parentId)\n const next: RivetNode<TNodeData> = {\n ...node,\n id: remap(node.id),\n position: parentCopied\n ? { ...node.position }\n : { x: node.position.x + offset.x, y: node.position.y + offset.y },\n }\n next.hovered = undefined\n next.dragging = undefined\n next.selected = undefined\n if (node.parentId) next.parentId = idMap.has(node.parentId) ? remap(node.parentId) : undefined\n return next\n })\n\n const clonedEdges = edges\n .filter((edge) => idMap.has(edge.source) && idMap.has(edge.target))\n .map((edge) => ({\n ...edge,\n id: makeId(),\n source: remap(edge.source),\n target: remap(edge.target),\n selected: undefined,\n }))\n\n return { nodes: clonedNodes, edges: clonedEdges }\n}\n","import type { CSSProperties, ReactNode } from \"react\"\nimport { useRivetControls } from \"../context\"\n\nconst panelStyle: CSSProperties = {\n position: \"absolute\",\n bottom: 16,\n left: 16,\n display: \"flex\",\n flexDirection: \"column\",\n borderRadius: 8,\n overflow: \"hidden\",\n border: \"1px solid rgba(100, 116, 139, 0.4)\",\n background: \"#ffffff\",\n boxShadow: \"0 1px 3px rgba(15, 23, 42, 0.12)\",\n}\n\nconst buttonStyle: CSSProperties = {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: 32,\n height: 32,\n padding: 0,\n border: \"none\",\n borderBottom: \"1px solid rgba(100, 116, 139, 0.25)\",\n background: \"transparent\",\n color: \"#0f172a\",\n cursor: \"pointer\",\n}\n\nexport type ControlsProps = {\n /** Show the zoom-in / zoom-out buttons (default true). */\n showZoom?: boolean\n /** Show the fit-view button (default true). */\n showFitView?: boolean\n /** Extra buttons appended after the defaults. */\n children?: ReactNode\n className?: string\n style?: CSSProperties\n}\n\n/** A small zoom / fit-view button panel. Must be a child of `<Rivet>`. */\nexport function Controls({\n showZoom = true,\n showFitView = true,\n children,\n className,\n style,\n}: ControlsProps): React.ReactElement {\n const controls = useRivetControls()\n return (\n <div data-nopan className={className} style={{ ...panelStyle, ...style }}>\n {showZoom && (\n <>\n <button\n type=\"button\"\n style={buttonStyle}\n onClick={() => controls.zoomIn()}\n aria-label=\"Zoom in\"\n >\n <Icon title=\"Zoom in\" path=\"M12 5v14M5 12h14\" />\n </button>\n <button\n type=\"button\"\n style={buttonStyle}\n onClick={() => controls.zoomOut()}\n aria-label=\"Zoom out\"\n >\n <Icon title=\"Zoom out\" path=\"M5 12h14\" />\n </button>\n </>\n )}\n {showFitView && (\n <button\n type=\"button\"\n style={buttonStyle}\n onClick={() => controls.fitView()}\n aria-label=\"Fit view\"\n >\n <Icon title=\"Fit view\" path=\"M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5\" />\n </button>\n )}\n {children}\n </div>\n )\n}\n\nfunction Icon({ title, path }: { title: string; path: string }): React.ReactElement {\n return (\n <svg\n width={16}\n height={16}\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n role=\"img\"\n >\n <title>{title}</title>\n <path d={path} />\n </svg>\n )\n}\n","type MaybeCrypto = { randomUUID?: () => string }\n\n/**\n * Generate a short, collision-resistant id. Prefers `crypto.randomUUID` when\n * available and falls back to a timestamp + random suffix.\n */\nexport function createId(prefix = \"\"): string {\n const cryptoObj = (globalThis as { crypto?: MaybeCrypto }).crypto\n const base = cryptoObj?.randomUUID\n ? cryptoObj.randomUUID()\n : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n return prefix ? `${prefix}-${base}` : base\n}\n","import type { NodeId, Size } from \"./types\"\n\n/** Assumed node size before the DOM node has mounted and reported its own. */\nexport const DEFAULT_NODE_SIZE: Size = { width: 160, height: 44 }\n\n/** Composite key for the handle/anchor registries. */\nexport function handleKey(nodeId: NodeId, handleId: string): string {\n return `${nodeId} ${handleId}`\n}\n\n/**\n * DOM markers the library and its consumers key interactions off. `data-nopan` is\n * the consumer-facing opt-out (stamp it on toolbars/inputs so a press there doesn't\n * start a node drag or pane pan); the rest are internal hit-test hooks.\n */\n/**\n * How far the pointer may travel before a press stops being a click and becomes\n * a drag. Shared so the two gestures that race over one press — moving the node\n * and selecting the anchor under the pointer — agree on where the line is.\n */\nexport const DRAG_THRESHOLD = 4\n\nexport const SELECTOR = {\n node: \"[data-rivet-node]\",\n handle: \"[data-rivet-handle]\",\n noPan: \"[data-nopan]\",\n /** Press here starts no node drag (but the node can still be selected/clicked). */\n noDrag: \"[data-nodrag]\",\n /** Press here never changes the selection. */\n noSelect: \"[data-noselect]\",\n swimlaneHandle: \"[data-rivet-swimlane-handle]\",\n /** The draggable box a marquee leaves over its selection (owns its own drag). */\n nodesSelection: \"[data-rivet-nodes-selection]\",\n /** Elements that own their own pointer — a pane pointerdown here starts no gesture. */\n paneGestureExempt:\n \"[data-rivet-node], [data-rivet-swimlane-handle], [data-nopan], [data-rivet-nodes-selection]\",\n} as const\n","/**\n * Edge alignment — the library-level policy for when an edge's endpoints\n * re-side to face the peer node.\n *\n * A handle chosen by the user (grabbed or dropped on) is *pinned*: rivet\n * renders the edge exactly there. The alignment policy decides when geometry\n * may override that pin. Under `\"on-move\"`, a committed position change of an\n * endpoint node re-sides both ends of its edges toward each other — the user\n * visibly changed the layout, so the pin yields. Nothing else triggers it:\n * data replaces (description edits, history restores) and dimension echoes\n * must never move an edge the user didn't touch or rewrite handles an undo\n * just faithfully restored.\n *\n * The store performs the move and the re-side in one internal batch, so\n * \"move + realign = one undo step\" holds by construction.\n */\n\nimport type { HandlePosition, Rect } from \"./types\"\n\n/**\n * When pinned edge endpoints re-side to face the peer node.\n *\n * - `\"manual\"` — never; a chosen handle is kept until the user reconnects.\n * - `\"on-move\"` — on a committed position change of an endpoint node.\n * - `\"live\"` — as `\"on-move\"`, plus: while an endpoint node is dragging, the\n * edge's pinned ends *render* as if auto — re-siding per frame to face each\n * other, with hysteresis — and the displayed sides commit on drop, inside\n * the move's history step. Nothing is persisted mid-gesture.\n */\nexport type EdgeAlignment = \"manual\" | \"on-move\" | \"live\"\n\n/** The side of `node` that faces `peer`, by dominant center-to-center axis. */\nexport function facingSide(node: Rect, peer: Rect): HandlePosition {\n const dx = peer.x + peer.width / 2 - (node.x + node.width / 2)\n const dy = peer.y + peer.height / 2 - (node.y + node.height / 2)\n if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? \"right\" : \"left\"\n return dy > 0 ? \"bottom\" : \"top\"\n}\n\n/**\n * How much the losing axis must dominate before a per-frame resolved side\n * switches axes: with a current horizontal side, the edge flips to top/bottom\n * only once `|dy| > |dx| * ratio` (and symmetrically). `1` disables the band.\n */\nexport const DEFAULT_ALIGNMENT_HYSTERESIS = 1.2\n\n/**\n * Per-frame side resolution with hysteresis. Without a `previous` side this is\n * exactly {@link facingSide}; with one, the side keeps its current axis until\n * the other axis dominates by `hysteresis`, so near-diagonal positions don't\n * flicker between sides frame to frame. Within the kept axis the sign always\n * tracks (a left↔right swap at a mostly-horizontal layout is a real crossing,\n * not jitter — jitter near the diagonal is an axis change, which the band\n * absorbs).\n */\nexport function resolveFacingSide(\n node: Rect,\n peer: Rect,\n previous?: HandlePosition,\n hysteresis: number = DEFAULT_ALIGNMENT_HYSTERESIS,\n): HandlePosition {\n if (!previous) return facingSide(node, peer)\n const dx = peer.x + peer.width / 2 - (node.x + node.width / 2)\n const dy = peer.y + peer.height / 2 - (node.y + node.height / 2)\n if (previous === \"left\" || previous === \"right\") {\n if (Math.abs(dy) > Math.abs(dx) * hysteresis) return dy > 0 ? \"bottom\" : \"top\"\n return dx > 0 ? \"right\" : \"left\"\n }\n if (Math.abs(dx) > Math.abs(dy) * hysteresis) return dx > 0 ? \"right\" : \"left\"\n return dy > 0 ? \"bottom\" : \"top\"\n}\n\n/** The side in `allowed` that most faces `peer`, or `null` for an empty set. */\nfunction bestAllowedSide(\n node: Rect,\n peer: Rect,\n allowed: readonly HandlePosition[],\n): HandlePosition | null {\n const dx = peer.x + peer.width / 2 - (node.x + node.width / 2)\n const dy = peer.y + peer.height / 2 - (node.y + node.height / 2)\n // Scoring by signed offset agrees with `facingSide` when all four sides are\n // allowed: its dominant-axis-and-sign choice is exactly the maximum here.\n const score: Record<HandlePosition, number> = { left: -dx, right: dx, top: -dy, bottom: dy }\n let best: HandlePosition | null = null\n for (const side of allowed) {\n if (best === null || score[side] > score[best]) best = side\n }\n return best\n}\n\n/**\n * {@link resolveFacingSide} restricted to the sides an end can actually reach.\n *\n * A node only offers connection points where its handles are. Letting an auto\n * or live-aligned end resolve freely puts the edge on a bare side — a\n * left/right node gets its edge stuck to the top midpoint, where the consumer\n * put nothing. Passing the sides that carry a compatible handle keeps the edge\n * on a real connection point.\n *\n * An empty `allowed` means \"unconstrained\" — a node with no registered handles\n * attaches at side midpoints, so every side is equally valid, and anchors place\n * themselves along whichever side faces the peer.\n *\n * When the freely-resolved side isn't reachable, a still-reachable `previous`\n * wins over re-picking: with the peer straight above a left/right node the raw\n * choice hangs on the sign of a near-zero `dx`, which would flicker frame to\n * frame.\n */\nexport function resolveFacingSideAmong(\n node: Rect,\n peer: Rect,\n allowed: readonly HandlePosition[],\n previous?: HandlePosition,\n hysteresis: number = DEFAULT_ALIGNMENT_HYSTERESIS,\n): HandlePosition {\n const resolved = resolveFacingSide(node, peer, previous, hysteresis)\n if (allowed.length === 0 || allowed.includes(resolved)) return resolved\n if (previous && allowed.includes(previous)) return previous\n return bestAllowedSide(node, peer, allowed) ?? resolved\n}\n","/**\n * Structured edge ends — the semantic model over the string handle ids that\n * `RivetEdge.sourceHandle`/`targetHandle` persist.\n *\n * An end is `{ nodeId, anchorId?, side? }`:\n * - `anchorId` present — the end binds to a registered {@link Anchor}.\n * - `side` present — the end is *pinned*: the user chose it (grabbed a dot,\n * dropped on a handle) and rivet renders it exactly there until the\n * alignment policy says otherwise.\n * - `side` absent — the end is *auto* (floating): the renderer resolves the\n * facing side per frame from the two node boxes. Nothing is written while a\n * node drags, so live re-anchoring is free and cannot touch history.\n *\n * Strings remain the wire format, so persisted graphs and external schemas\n * keep working; this module is the codec between the two forms:\n *\n * | structured | handle string |\n * |---------------------------------|----------------------|\n * | `{ anchorId, side }` | `inode-<id>-<side>` |\n * | `{ anchorId }` (auto) | `inode-<id>-auto` |\n * | `{ side }` (plain, pinned) | `\"<side>\"` |\n * | `{}` (plain, auto) | `undefined` |\n *\n * A custom handle id (anything else) stays a plain pinned end whose side lives\n * in the handle registry; `parseEdgeEndpoint` reads it from there when given\n * the registry, and otherwise leaves `side` unset.\n */\n\nimport {\n anchorAutoHandleId,\n anchorHandleId,\n parseAnchorAutoHandleId,\n parseAnchorHandleId,\n} from \"./anchor/registry\"\nimport { handleKey } from \"./constants\"\nimport type { EdgeEnd, EdgeId, HandlePosition, HandleRecord, NodeId } from \"./types\"\n\n/** One end of an edge, structurally. See the module doc for the string mapping. */\nexport type EdgeEndpoint = {\n nodeId: NodeId\n /** Anchor this end binds to; absent for a plain node end. */\n anchorId?: string\n /** Pinned side; absent = auto — the renderer resolves the facing side per frame. */\n side?: HandlePosition\n}\n\n/**\n * Key into the displayed-sides map (`EdgeDrawExtras.displayedSides`) for one\n * end of an edge — the hysteresis memory shared between the renderer, which\n * writes each frame's resolved side, and the store, whose `\"live\"` alignment\n * commit re-sides to exactly what was last displayed.\n */\nexport function displayedSideKey(edgeId: EdgeId, end: EdgeEnd): string {\n return `${edgeId}:${end}`\n}\n\nconst SIDES: readonly string[] = [\"left\", \"right\", \"top\", \"bottom\"]\n\n/** Parse a bare-side handle id (`\"left\"`, `\"top\"`, …) — a side-pinned plain end. */\nexport function parseSideHandleId(handleId: string | null | undefined): HandlePosition | null {\n return handleId && SIDES.includes(handleId) ? (handleId as HandlePosition) : null\n}\n\n/**\n * The handle string for a structured end — what `sourceHandle`/`targetHandle`\n * stores. `undefined` (a plain auto end) means \"no handle\": the renderer\n * resolves the side per frame. A plain pinned end that should attach to a\n * specific registered handle keeps using that handle's own id directly; this\n * codec covers the library-owned grammars.\n */\nexport function edgeEndpointHandle(end: EdgeEndpoint): string | undefined {\n if (end.anchorId !== undefined) {\n return end.side ? anchorHandleId(end.anchorId, end.side) : anchorAutoHandleId(end.anchorId)\n }\n return end.side\n}\n\n/**\n * Parse one end of an edge into the structured form. Library grammars (anchor\n * stray/auto ids, bare sides, absent handles) round-trip exactly; a custom\n * handle id resolves its side through `handles` when provided (the store's\n * registry), and otherwise comes back with `side` unset — which callers must\n * not read as auto without that context.\n */\nexport function parseEdgeEndpoint(\n nodeId: NodeId,\n handleId: string | null | undefined,\n handles?: ReadonlyMap<string, HandleRecord>,\n): EdgeEndpoint {\n if (!handleId) return { nodeId }\n const auto = parseAnchorAutoHandleId(handleId)\n if (auto) return { nodeId, anchorId: auto }\n const stray = parseAnchorHandleId(handleId)\n if (stray) return { nodeId, anchorId: stray.anchorId, side: stray.side }\n const registered = handles?.get(handleKey(nodeId, handleId))\n if (registered) return { nodeId, side: registered.position }\n const side = parseSideHandleId(handleId)\n return side ? { nodeId, side } : { nodeId }\n}\n","import type { NodeChange, NodeId, RivetNode } from \"./types\"\n\n/**\n * Geometry is the only thing a local gesture owns exclusively. A drag or resize\n * is its own confirm signal — while the pointer is down, this client's position\n * and size are authoritative and an incoming write to them is stale by\n * definition, because the peer that sent it was looking at a box this client has\n * already moved.\n *\n * Everything else about a held node (its data, selection, whether it still\n * exists) stays server-authoritative and lands normally: holding a node is not\n * the same as owning it.\n */\nexport type GeometryFields = Pick<RivetNode, \"position\" | \"width\" | \"height\" | \"size\">\n\n/** Copy `local`'s geometry onto `incoming`, leaving every other field alone. */\nexport function keepLocalGeometry<TData>(\n incoming: RivetNode<TData>,\n local: GeometryFields,\n): RivetNode<TData> {\n return {\n ...incoming,\n position: local.position,\n width: local.width,\n height: local.height,\n size: local.size,\n }\n}\n\n/**\n * Drop the parts of a remote batch that would fight a live local gesture.\n *\n * - `position` / `dimensions` for a held node are dropped outright.\n * - `replace` for a held node is rewritten to keep local geometry, so a peer's\n * rename still lands on a node this client is dragging.\n * - everything else passes through untouched.\n *\n * The result is what actually gets applied *and* what gets re-emitted — a\n * consumer must never be told about a change the document didn't take, or its\n * state and the store's diverge until the next full round-trip.\n */\nexport function guardNodeChanges<TData>(\n changes: NodeChange<TData>[],\n isHeld: (id: NodeId) => boolean,\n getLocal: (id: NodeId) => GeometryFields | undefined,\n): NodeChange<TData>[] {\n // The common case is no gesture in flight at all; don't rebuild the array.\n if (!changes.some((change) => change.type !== \"add\" && isHeld(change.id))) return changes\n\n const guarded: NodeChange<TData>[] = []\n for (const change of changes) {\n if (change.type === \"add\" || !isHeld(change.id)) {\n guarded.push(change)\n continue\n }\n if (change.type === \"position\" || change.type === \"dimensions\") continue\n if (change.type === \"replace\") {\n const local = getLocal(change.id)\n guarded.push(local ? { ...change, item: keepLocalGeometry(change.item, local) } : change)\n continue\n }\n guarded.push(change)\n }\n return guarded\n}\n","import type { EdgeChange, NodeChange, RivetEdge, RivetNode } from \"./types\"\n\n/** A structural snapshot of the graph (no selection/hover/drag state). */\nexport type HistorySnapshot = {\n nodes: RivetNode[]\n edges: RivetEdge[]\n}\n\n/**\n * True when a change batch alters graph structure and should create an undo\n * step. Selection is excluded (undo shouldn't churn selection); live drag/resize\n * frames are excluded so a whole gesture coalesces into a single committed step.\n */\nexport function hasRecordableChange(changes: ReadonlyArray<NodeChange | EdgeChange>): boolean {\n return changes.some((change) => {\n switch (change.type) {\n case \"add\":\n case \"remove\":\n case \"replace\":\n return true\n case \"position\":\n return !change.dragging\n case \"dimensions\":\n return !change.resizing\n default:\n return false // selection\n }\n })\n}\n\n/**\n * A bounded undo/redo stack over graph snapshots. Backend-agnostic: it takes a\n * `snapshot()` reader and, per undo/redo, an `apply()` writer — so it can be\n * unit-tested without a store, and the store stays the single source of truth.\n *\n * Coalescing: {@link record} schedules a single step per microtask, so all the\n * synchronous mutations of one user action (e.g. deleting a node and its edges,\n * which emit separately) collapse into one undo step. `snapshot()` is read at the\n * end of that microtask, capturing the fully-applied result; the *previous*\n * snapshot becomes the step's \"before\".\n */\nexport class HistoryManager {\n private undoStack: HistorySnapshot[] = []\n private redoStack: HistorySnapshot[] = []\n private last: HistorySnapshot\n private scheduled = false\n private rebaseScheduled = false\n private readonly listeners = new Set<() => void>()\n\n constructor(\n private readonly snapshot: () => HistorySnapshot,\n private readonly limit = 100,\n // Wrap rather than pass `queueMicrotask` directly: as a bare default it would\n // be invoked as `this.schedule(cb)` — a method call that binds `this` to the\n // manager, which browsers reject with \"Illegal invocation\". Calling it inside\n // an arrow keeps it a free-function call.\n private readonly schedule: (cb: () => void) => void = (cb) => queueMicrotask(cb),\n ) {\n this.last = snapshot()\n }\n\n /** Note that a recordable batch was applied; flushes one step next microtask. */\n record(recordable: boolean): void {\n if (!recordable || this.scheduled) return\n this.scheduled = true\n this.schedule(() => {\n if (this.scheduled) this.flush()\n })\n }\n\n /**\n * The graph changed *without* recording a step — a controlled reconcile\n * applying incoming props, or a measurement echo. Refresh the rolling\n * baseline so the next recorded step diffs against reality; a stale baseline\n * makes undo revert the unrecorded changes too (e.g. a prop-added node that\n * was then deleted through the store would undo to a graph without it).\n * Coalesced per microtask like {@link record}. When a step is pending, its\n * flush refreshes the baseline anyway, so this defers to it — with the\n * documented limit that unrecorded and recorded mutations landing in the\n * same microtask fold into that one step.\n */\n rebase(): void {\n if (this.scheduled || this.rebaseScheduled) return\n this.rebaseScheduled = true\n this.schedule(() => {\n this.rebaseScheduled = false\n if (this.scheduled) return\n this.last = this.snapshot()\n })\n }\n\n /**\n * Fold an external change into every stored snapshot.\n *\n * Snapshots are structural, so a restore rewrites the whole graph — which in a\n * shared document means undoing past a peer's edit would silently erase it.\n * {@link rebase} can't help: it only refreshes the rolling baseline, while the\n * stale states are the ones already on the stacks. Replaying the incoming\n * change over each of them keeps every stored step consistent with work this\n * client doesn't own.\n *\n * The trade-off is that an undo touching a node a peer has since changed no\n * longer moves it — the peer's newer value survives instead. That's the\n * intended precedence: a local undo may drop its own effect, never someone\n * else's edit.\n */\n rewrite(transform: (snapshot: HistorySnapshot) => HistorySnapshot): void {\n this.undoStack = this.undoStack.map(transform)\n this.redoStack = this.redoStack.map(transform)\n // A step scheduled but not yet flushed will push `last` as its \"before\", so\n // it needs the same treatment; when nothing is pending, the rebase that\n // follows re-reads it from the live graph and lands on the same state.\n this.last = transform(this.last)\n }\n\n private flush(): void {\n this.scheduled = false\n this.undoStack.push(this.last)\n if (this.undoStack.length > this.limit) this.undoStack.shift()\n this.redoStack = []\n this.last = this.snapshot()\n this.notify()\n }\n\n undo(apply: (snapshot: HistorySnapshot) => void): boolean {\n if (this.scheduled) this.flush() // finalize a pending step first\n const prev = this.undoStack.pop()\n if (!prev) return false\n this.redoStack.push(this.snapshot())\n apply(prev)\n this.last = prev\n this.notify()\n return true\n }\n\n redo(apply: (snapshot: HistorySnapshot) => void): boolean {\n const next = this.redoStack.pop()\n if (!next) return false\n this.undoStack.push(this.last)\n apply(next)\n this.last = next\n this.notify()\n return true\n }\n\n canUndo(): boolean {\n return this.undoStack.length > 0 || this.scheduled\n }\n\n canRedo(): boolean {\n return this.redoStack.length > 0\n }\n\n /** Drop all history and reset the baseline to the current graph. */\n clear(): void {\n this.scheduled = false\n this.rebaseScheduled = false\n this.undoStack = []\n this.redoStack = []\n this.last = this.snapshot()\n this.notify()\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n private notify(): void {\n for (const listener of this.listeners) listener()\n }\n}\n","import { clamp } from \"@rivet/utils\"\nimport type { Rect, Vec2, Viewport } from \"./types\"\n\n/** Convert a world-space point to screen-space pixels. */\nexport function worldToScreen(point: Vec2, viewport: Viewport): Vec2 {\n return {\n x: point.x * viewport.zoom + viewport.x,\n y: point.y * viewport.zoom + viewport.y,\n }\n}\n\n/** Convert a screen-space point (e.g. a pointer event) to world space. */\nexport function screenToWorld(point: Vec2, viewport: Viewport): Vec2 {\n return {\n x: (point.x - viewport.x) / viewport.zoom,\n y: (point.y - viewport.y) / viewport.zoom,\n }\n}\n\n/**\n * Zoom toward an anchor point (usually the cursor) so the world point under the\n * anchor stays put. Returns a new viewport; the input is not mutated.\n */\nexport function zoomAt(\n viewport: Viewport,\n anchor: Vec2,\n nextZoom: number,\n minZoom = 0.1,\n maxZoom = 4,\n): Viewport {\n const zoom = clamp(nextZoom, minZoom, maxZoom)\n const world = screenToWorld(anchor, viewport)\n return {\n zoom,\n x: anchor.x - world.x * zoom,\n y: anchor.y - world.y * zoom,\n }\n}\n\n/** The CSS transform string applied to the DOM node layer. */\nexport function viewportToCss(viewport: Viewport): string {\n return `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`\n}\n\n/** The visible world-space rectangle for a viewport of the given pixel size. */\nexport function visibleWorldRect(viewport: Viewport, width: number, height: number): Rect {\n const topLeft = screenToWorld({ x: 0, y: 0 }, viewport)\n const bottomRight = screenToWorld({ x: width, y: height }, viewport)\n return {\n x: topLeft.x,\n y: topLeft.y,\n width: bottomRight.x - topLeft.x,\n height: bottomRight.y - topLeft.y,\n }\n}\n\n/** True if two axis-aligned rectangles overlap (used for node culling). */\nexport function rectsIntersect(a: Rect, b: Rect): boolean {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y\n}\n","import type { EdgePath, EdgePathFn, EdgePathParams, HandlePosition, Vec2 } from \"../types\"\n\n/** Outward unit direction an edge leaves a handle, by the handle's side. */\nconst SIDE_DIR: Record<HandlePosition, Vec2> = {\n left: { x: -1, y: 0 },\n right: { x: 1, y: 0 },\n top: { x: 0, y: -1 },\n bottom: { x: 0, y: 1 },\n}\n\n/**\n * Bezier sampling is adaptive: roughly one segment per {@link BEZIER_SEGMENT_PX}\n * of curve, clamped to [{@link BEZIER_MIN_SAMPLES}, {@link BEZIER_MAX_SAMPLES}].\n * A fixed count faceted long curves (few big chords) and over-sampled short ones.\n * Paths are built in screen space, so this tracks the on-screen size at any zoom.\n */\nconst BEZIER_SEGMENT_PX = 8\nconst BEZIER_MIN_SAMPLES = 16\nconst BEZIER_MAX_SAMPLES = 160\nconst CORNER_RADIUS = 8\nconst ARC_SAMPLES = 6\n\nfunction cubicAt(a: number, b: number, c: number, d: number, t: number): number {\n const mt = 1 - t\n return mt * mt * mt * a + 3 * mt * mt * t * b + 3 * mt * t * t * c + t * t * t * d\n}\n\nfunction quadAt(a: number, b: number, c: number, t: number): number {\n const mt = 1 - t\n return mt * mt * a + 2 * mt * t * b + t * t * c\n}\n\n/** A straight line between the two ends. */\nexport const getStraightPath: EdgePathFn = ({ sourceX, sourceY, targetX, targetY }): EdgePath => ({\n points: [\n { x: sourceX, y: sourceY },\n { x: targetX, y: targetY },\n ],\n labelX: (sourceX + targetX) / 2,\n labelY: (sourceY + targetY) / 2,\n})\n\n/**\n * A cubic bezier that leaves each end perpendicular to its handle's side, so\n * edges curve cleanly out of left/right/top/bottom handles. This is the default.\n */\nexport const getBezierPath: EdgePathFn = (params): EdgePath => {\n const { sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = params\n const sDir = SIDE_DIR[sourcePosition]\n const tDir = SIDE_DIR[targetPosition]\n const dist = Math.hypot(targetX - sourceX, targetY - sourceY)\n const reach = Math.max(40, dist * 0.4)\n const p0 = { x: sourceX, y: sourceY }\n const p1 = { x: sourceX + sDir.x * reach, y: sourceY + sDir.y * reach }\n const p2 = { x: targetX + tDir.x * reach, y: targetY + tDir.y * reach }\n const p3 = { x: targetX, y: targetY }\n\n // Sample proportionally to the control polygon's length (an upper bound on the\n // arc length), so a long, curvy edge gets enough segments to read as smooth.\n const ctrlLen =\n Math.hypot(p1.x - p0.x, p1.y - p0.y) +\n Math.hypot(p2.x - p1.x, p2.y - p1.y) +\n Math.hypot(p3.x - p2.x, p3.y - p2.y)\n const samples = Math.max(\n BEZIER_MIN_SAMPLES,\n Math.min(BEZIER_MAX_SAMPLES, Math.ceil(ctrlLen / BEZIER_SEGMENT_PX)),\n )\n\n const points: Vec2[] = []\n for (let i = 0; i <= samples; i++) {\n const t = i / samples\n points.push({\n x: cubicAt(p0.x, p1.x, p2.x, p3.x, t),\n y: cubicAt(p0.y, p1.y, p2.y, p3.y, t),\n })\n }\n return {\n points,\n labelX: cubicAt(p0.x, p1.x, p2.x, p3.x, 0.5),\n labelY: cubicAt(p0.y, p1.y, p2.y, p3.y, 0.5),\n }\n}\n\n/** Minimum run an edge travels straight out of a handle before its first turn. */\nconst STEP_OFFSET = 20\n\n/** Drop consecutive duplicates and interior points collinear with their neighbors. */\nfunction simplifyCorners(corners: Vec2[]): Vec2[] {\n const out: Vec2[] = []\n for (const p of corners) {\n const a = out[out.length - 2]\n const b = out[out.length - 1]\n if (b && b.x === p.x && b.y === p.y) continue\n if (a && b && ((a.x === b.x && b.x === p.x) || (a.y === b.y && b.y === p.y))) out.pop()\n out.push(p)\n }\n return out\n}\n\n/**\n * Orthogonal waypoints (endpoints included) for an axis-aligned step path.\n * Direction-aware: the path leaves each handle along its outward side for at\n * least {@link STEP_OFFSET} before turning, so a route never doubles back\n * through the node it just left.\n */\nfunction stepCorners(params: EdgePathParams): Vec2[] {\n const { sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = params\n const s = { x: sourceX, y: sourceY }\n const t = { x: targetX, y: targetY }\n const sDir = SIDE_DIR[sourcePosition]\n const tDir = SIDE_DIR[targetPosition]\n // Where each end sits after its mandatory straight run out of the handle.\n const sg = { x: sourceX + sDir.x * STEP_OFFSET, y: sourceY + sDir.y * STEP_OFFSET }\n const tg = { x: targetX + tDir.x * STEP_OFFSET, y: targetY + tDir.y * STEP_OFFSET }\n return simplifyCorners(routeCorners(s, t, sg, tg, sDir, tDir))\n}\n\n/** Pick the orthogonal route between the two gapped ends, by handle-direction case. */\nfunction routeCorners(s: Vec2, t: Vec2, sg: Vec2, tg: Vec2, sDir: Vec2, tDir: Vec2): Vec2[] {\n const sHoriz = sDir.x !== 0\n const tHoriz = tDir.x !== 0\n\n if (sHoriz && tHoriz) {\n if (sDir.x * tDir.x < 0) {\n // Facing pair (e.g. right → left): split at the mid-line when the target\n // is far enough ahead; otherwise route around through a horizontal mid-lane.\n if ((t.x - s.x) * sDir.x >= 2 * STEP_OFFSET) {\n const midX = (s.x + t.x) / 2\n return [s, { x: midX, y: s.y }, { x: midX, y: t.y }, t]\n }\n const midY = (s.y + t.y) / 2\n return [s, sg, { x: sg.x, y: midY }, { x: tg.x, y: midY }, tg, t]\n }\n // Same side (e.g. right → right): share the outermost vertical rail.\n const railX = sDir.x > 0 ? Math.max(sg.x, tg.x) : Math.min(sg.x, tg.x)\n return [s, { x: railX, y: s.y }, { x: railX, y: t.y }, t]\n }\n\n if (!sHoriz && !tHoriz) {\n if (sDir.y * tDir.y < 0) {\n if ((t.y - s.y) * sDir.y >= 2 * STEP_OFFSET) {\n const midY = (s.y + t.y) / 2\n return [s, { x: s.x, y: midY }, { x: t.x, y: midY }, t]\n }\n const midX = (s.x + t.x) / 2\n return [s, sg, { x: midX, y: sg.y }, { x: midX, y: tg.y }, tg, t]\n }\n const railY = sDir.y > 0 ? Math.max(sg.y, tg.y) : Math.min(sg.y, tg.y)\n return [s, { x: s.x, y: railY }, { x: t.x, y: railY }, t]\n }\n\n // Perpendicular pair: a single L-bend when it exits both handles outward;\n // otherwise a Z through the gapped ends.\n const corner = sHoriz ? { x: t.x, y: s.y } : { x: s.x, y: t.y }\n const exitsSource = sHoriz\n ? (corner.x - s.x) * sDir.x >= STEP_OFFSET\n : (corner.y - s.y) * sDir.y >= STEP_OFFSET\n const exitsTarget = tHoriz\n ? (corner.x - t.x) * tDir.x >= STEP_OFFSET\n : (corner.y - t.y) * tDir.y >= STEP_OFFSET\n if (exitsSource && exitsTarget) return [s, corner, t]\n const bend = sHoriz ? { x: sg.x, y: tg.y } : { x: tg.x, y: sg.y }\n return [s, sg, bend, tg, t]\n}\n\n/** Round the interior corners of a waypoint list into a sampled polyline. */\nfunction roundCorners(corners: Vec2[], radius: number): Vec2[] {\n if (corners.length <= 2) return corners\n const points: Vec2[] = []\n const first = corners[0]\n if (first) points.push(first)\n\n for (let i = 1; i < corners.length - 1; i++) {\n const prev = corners[i - 1]\n const curr = corners[i]\n const next = corners[i + 1]\n if (!prev || !curr || !next) continue\n\n const inLen = Math.hypot(curr.x - prev.x, curr.y - prev.y)\n const outLen = Math.hypot(next.x - curr.x, next.y - curr.y)\n const r = Math.min(radius, inLen / 2, outLen / 2)\n const inPt = {\n x: curr.x + ((prev.x - curr.x) / (inLen || 1)) * r,\n y: curr.y + ((prev.y - curr.y) / (inLen || 1)) * r,\n }\n const outPt = {\n x: curr.x + ((next.x - curr.x) / (outLen || 1)) * r,\n y: curr.y + ((next.y - curr.y) / (outLen || 1)) * r,\n }\n points.push(inPt)\n for (let j = 1; j < ARC_SAMPLES; j++) {\n const tt = j / ARC_SAMPLES\n points.push({\n x: quadAt(inPt.x, curr.x, outPt.x, tt),\n y: quadAt(inPt.y, curr.y, outPt.y, tt),\n })\n }\n points.push(outPt)\n }\n\n const last = corners[corners.length - 1]\n if (last) points.push(last)\n return points\n}\n\n/** Label anchor: the midpoint of the path's middle segment. */\nfunction stepLabel(corners: Vec2[], params: EdgePathParams): Vec2 {\n const i = Math.floor((corners.length - 1) / 2)\n const a = corners[i]\n const b = corners[i + 1]\n if (!a || !b) return { x: params.sourceX, y: params.sourceY }\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }\n}\n\n/** An axis-aligned step path with rounded corners. */\nexport const getSmoothStepPath: EdgePathFn = (params): EdgePath => {\n const corners = stepCorners(params)\n const label = stepLabel(corners, params)\n return { points: roundCorners(corners, CORNER_RADIUS), labelX: label.x, labelY: label.y }\n}\n\n/** An axis-aligned step path with sharp corners. */\nexport const getStepPath: EdgePathFn = (params): EdgePath => {\n const corners = stepCorners(params)\n const label = stepLabel(corners, params)\n return { points: corners, labelX: label.x, labelY: label.y }\n}\n\n/** The built-in edge shapes, keyed by `type`. `bezier` is the default. */\nexport const BUILTIN_EDGE_TYPES: Record<string, EdgePathFn> = {\n bezier: getBezierPath,\n smoothstep: getSmoothStepPath,\n step: getStepPath,\n straight: getStraightPath,\n}\n","import { parseAnchorAutoHandleId, parseAnchorHandleId } from \"../anchor/registry\"\nimport { DEFAULT_NODE_SIZE, handleKey } from \"../constants\"\nimport { resolveFacingSideAmong } from \"../edge-alignment\"\nimport { displayedSideKey, parseSideHandleId } from \"../edge-ends\"\nimport type {\n DefaultEdgeOptions,\n EdgeDrawExtras,\n EdgeEnd,\n EdgeId,\n EdgeMarker,\n EdgePathParams,\n EdgeStyle,\n EdgeTypes,\n HandlePosition,\n HandleRecord,\n HandleType,\n NodeId,\n Rect,\n RivetEdge,\n RivetNode,\n Vec2,\n Viewport,\n} from \"../types\"\nimport { worldToScreen } from \"../viewport\"\nimport { getBezierPath } from \"./edge-paths\"\n\n/** Semantic edge colors, shared by every backend. */\nexport const EDGE_COLOR = \"rgba(100, 116, 139, 0.75)\"\nexport const EDGE_COLOR_SELECTED = \"#6366f1\"\nexport const EDGE_COLOR_HOVERED = \"rgba(99, 102, 241, 0.9)\"\nexport const EDGE_WIDTH = 1.5\nexport const EDGE_WIDTH_HOVERED = 2.5\nexport const PENDING_COLOR = \"#6366f1\"\n\n/** The opposite side, used to face the pending connection's loose end. */\nexport const OPPOSITE: Record<HandlePosition, HandlePosition> = {\n left: \"right\",\n right: \"left\",\n top: \"bottom\",\n bottom: \"top\",\n}\n\n/** One edge resolved to screen-space geometry plus its final visual style. */\nexport type ResolvedEdge = {\n id: EdgeId\n /** Screen-space polyline (>= 2 points). */\n points: Vec2[]\n /** Screen-space endpoints (for endpoint picking / reconnection). */\n source: Vec2\n target: Vec2\n /** Screen-space label anchor, when the edge has a label. */\n label?: Vec2\n /** Resolved stroke color (CSS string). */\n stroke: string\n width: number\n opacity: number\n animated: boolean\n /** Explicit dash pattern (ignored when `animated`). */\n dash?: number[]\n markerStart: Exclude<EdgeMarker, false> | null\n markerEnd: Exclude<EdgeMarker, false> | null\n}\n\n/** One end of an edge in screen space, plus the side it exits. */\ntype Anchor = { point: Vec2; position: HandlePosition }\n\n/** Collapse a marker to its drawable value, treating `false` as \"no marker\". */\nconst falseToNull = (m: EdgeMarker | undefined): Exclude<EdgeMarker, false> | null => m || null\n\n/**\n * Resolve every edge to backend-neutral screen-space geometry + style — the\n * form any {@link EdgeRenderer} backend consumes. Skips the edge currently\n * being reconnected and any edge whose endpoints are missing or degenerate.\n */\nexport function buildEdges(\n edges: RivetEdge[],\n nodes: Map<NodeId, RivetNode>,\n viewport: Viewport,\n edgeTypes: EdgeTypes,\n defaults: DefaultEdgeOptions,\n extras?: EdgeDrawExtras,\n): ResolvedEdge[] {\n const handles = extras?.handles\n const hovered = extras?.hovered\n const reconnecting = extras?.reconnecting\n const worldPositions = extras?.worldPositions\n const resolved: ResolvedEdge[] = []\n\n for (const edge of edges) {\n if (edge.id === reconnecting) continue\n const source = nodes.get(edge.source)\n const target = nodes.get(edge.target)\n if (!source || !target) continue\n\n const frame: EndFrame = { handles, viewport, worldPositions, extras }\n const start = resolveEnd(edge, \"source\", source, target, frame)\n const end = resolveEnd(edge, \"target\", target, source, frame)\n const params: EdgePathParams = {\n sourceX: start.point.x,\n sourceY: start.point.y,\n targetX: end.point.x,\n targetY: end.point.y,\n sourcePosition: start.position,\n targetPosition: end.position,\n }\n const pathFn = edgeTypes[edge.type ?? defaults.type ?? \"bezier\"] ?? getBezierPath\n const path = pathFn(params)\n if (path.points.length < 2) continue\n\n const style: EdgeStyle = { ...defaults.style, ...edge.style }\n const isHovered = edge.id === hovered\n resolved.push({\n id: edge.id,\n points: path.points,\n source: start.point,\n target: end.point,\n label: edge.label !== undefined ? { x: path.labelX, y: path.labelY } : undefined,\n stroke: edge.selected\n ? EDGE_COLOR_SELECTED\n : isHovered\n ? EDGE_COLOR_HOVERED\n : (style.stroke ?? EDGE_COLOR),\n width: style.strokeWidth ?? (isHovered ? EDGE_WIDTH_HOVERED : EDGE_WIDTH),\n opacity: style.opacity ?? 1,\n animated: edge.animated ?? defaults.animated ?? false,\n dash: style.strokeDasharray,\n markerStart: falseToNull(edge.markerStart ?? defaults.markerStart),\n markerEnd: falseToNull(edge.markerEnd ?? defaults.markerEnd),\n })\n }\n return resolved\n}\n\n/** Screen-space bezier polyline for the in-progress (pending) connection. */\nexport function buildPendingPath(\n pending: NonNullable<EdgeDrawExtras[\"pending\"]>,\n handles: Map<string, HandleRecord> | undefined,\n viewport: Viewport,\n): Vec2[] {\n const record = handles?.get(handleKey(pending.source, pending.sourceHandle))\n const sourcePosition: HandlePosition =\n record?.position ?? (pending.sourceType === \"target\" ? \"left\" : \"right\")\n const from = worldToScreen(pending.from, viewport)\n const to = worldToScreen(pending.to, viewport)\n // Snapped onto a target handle: enter from that handle's side so the preview\n // matches the committed edge. Otherwise face back toward the source.\n const targetPosition = pending.toPosition ?? OPPOSITE[sourcePosition]\n return getBezierPath({\n sourceX: from.x,\n sourceY: from.y,\n targetX: to.x,\n targetY: to.y,\n sourcePosition,\n targetPosition,\n }).points\n}\n\n/**\n * World point where an edge end meets `side` of a node box, `alongPct` percent\n * along that side (top→bottom for left/right, left→right for top/bottom).\n */\nexport function pointOnSide(rect: Rect, side: HandlePosition, alongPct = 50): Vec2 {\n const t = alongPct / 100\n switch (side) {\n case \"left\":\n return { x: rect.x, y: rect.y + rect.height * t }\n case \"right\":\n return { x: rect.x + rect.width, y: rect.y + rect.height * t }\n case \"top\":\n return { x: rect.x + rect.width * t, y: rect.y }\n case \"bottom\":\n return { x: rect.x + rect.width * t, y: rect.y + rect.height }\n }\n}\n\n/** The node's world-space box: parent-chain origin + measured/default size. */\nfunction nodeRect(node: RivetNode, worldPositions?: ReadonlyMap<NodeId, Vec2>): Rect {\n const origin = worldPositions?.get(node.id) ?? node.position\n const size = node.size ?? DEFAULT_NODE_SIZE\n return { x: origin.x, y: origin.y, width: size.width, height: size.height }\n}\n\n/** Handle types an edge end can attach to, mirroring the connection rules. */\nconst WANTED_TYPES: Record<EdgeEnd, readonly HandleType[]> = {\n source: [\"source\", \"either\"],\n target: [\"target\", \"either\"],\n}\n\n/** A registered handle on `side` of the node that `role` can use, or null. */\nfunction handleOnSide(\n nodeId: NodeId,\n side: HandlePosition,\n role: EdgeEnd,\n handles: Map<string, HandleRecord> | undefined,\n): HandleRecord | null {\n if (!handles) return null\n for (const record of handles.values()) {\n if (\n record.nodeId === nodeId &&\n record.position === side &&\n WANTED_TYPES[role].includes(record.type)\n ) {\n return record\n }\n }\n return null\n}\n\n/**\n * The distinct sides of `nodeId` carrying a handle `role` can use. Empty when\n * the node has no compatible handle at all — an unhandled node attaches at side\n * midpoints, so no side is preferable to another.\n */\nexport function reachableSides(\n nodeId: NodeId,\n role: EdgeEnd,\n handles: Map<string, HandleRecord> | undefined,\n): HandlePosition[] {\n if (!handles) return []\n const sides: HandlePosition[] = []\n for (const record of handles.values()) {\n if (record.nodeId !== nodeId) continue\n if (!WANTED_TYPES[role].includes(record.type)) continue\n if (!sides.includes(record.position)) sides.push(record.position)\n }\n return sides\n}\n\n/** Per-frame inputs shared by every end resolution in one {@link buildEdges} call. */\ntype EndFrame = {\n handles: Map<string, HandleRecord> | undefined\n viewport: Viewport\n worldPositions: ReadonlyMap<NodeId, Vec2> | undefined\n extras: EdgeDrawExtras | undefined\n}\n\n/**\n * Screen-space anchor for one end of an edge and the side it exits.\n *\n * A *pinned* end (a registered handle, an anchor stray id, a bare-side id)\n * renders exactly where it points. An *auto* end — no handle, an\n * `inode-<id>-auto` anchor end, or any end of an edge touching a node in\n * `liveAlignNodes` — resolves the side facing the peer per frame, stabilized\n * by the hysteresis memory in `displayedSides`, and places the point on that\n * side: at the anchor's measured row/column (via `anchorPlacement`), at a\n * compatible registered handle, or at the side's midpoint.\n */\nfunction resolveEnd(\n edge: RivetEdge,\n role: EdgeEnd,\n node: RivetNode,\n peer: RivetNode,\n frame: EndFrame,\n): Anchor {\n const { handles, viewport, worldPositions, extras } = frame\n const handleId = role === \"source\" ? edge.sourceHandle : edge.targetHandle\n const rect = nodeRect(node, worldPositions)\n const anchorId =\n parseAnchorAutoHandleId(handleId) ?? parseAnchorHandleId(handleId)?.anchorId ?? null\n\n /** Point `alongPct` percent along `side`, or at a compatible handle / midpoint. */\n const endAt = (side: HandlePosition): Anchor => {\n const alongPct =\n (anchorId ? extras?.anchorPlacement?.(node.id, anchorId, side) : null) ?? undefined\n if (alongPct === undefined && !anchorId) {\n const candidate = handleOnSide(node.id, side, role, handles)\n if (candidate) {\n return {\n point: worldToScreen(\n { x: rect.x + candidate.offset.x, y: rect.y + candidate.offset.y },\n viewport,\n ),\n position: side,\n }\n }\n }\n return { point: worldToScreen(pointOnSide(rect, side, alongPct), viewport), position: side }\n }\n\n // Pinned side, if any: an anchor stray's encoded side, a registered handle's\n // side, or a bare-side id. Ends with none (including custom ids whose handle\n // is unregistered — e.g. a culled peer) resolve as auto.\n const registered = handleId && handles ? handles.get(handleKey(node.id, handleId)) : undefined\n const pinnedSide =\n parseAnchorHandleId(handleId)?.side ?? registered?.position ?? parseSideHandleId(handleId)\n\n const live =\n extras?.liveAlignNodes !== undefined &&\n (extras.liveAlignNodes.has(edge.source) || extras.liveAlignNodes.has(edge.target)) &&\n edge.source !== edge.target\n\n if (pinnedSide && !live) {\n if (registered) {\n return {\n point: worldToScreen(\n { x: rect.x + registered.offset.x, y: rect.y + registered.offset.y },\n viewport,\n ),\n position: registered.position,\n }\n }\n // Unregistered but side-known: an anchor stray whose chrome isn't mounted\n // (culled node) places from measured geometry; a bare side uses a\n // compatible registered handle there, else the side midpoint.\n return endAt(pinnedSide)\n }\n\n // Auto: face the peer, with hysteresis against last frame's displayed side,\n // and constrained to the sides that actually carry a compatible handle — a\n // node with handles only on its left and right must not have its edge drift\n // onto the top or bottom midpoint. Anchors opt out: their strays are placed\n // along whichever side faces the peer, by design.\n const key = displayedSideKey(edge.id, role)\n const side = resolveFacingSideAmong(\n rect,\n nodeRect(peer, worldPositions),\n anchorId ? [] : reachableSides(node.id, role, handles),\n extras?.displayedSides?.get(key),\n )\n extras?.displayedSides?.set(key, side)\n return endAt(side)\n}\n\n/**\n * The point half way *along* a polyline — by arc length, not by vertex count,\n * so a step edge's long leg doesn't drag the answer into a corner. Where chrome\n * that belongs to a whole edge (a claim chip, an avatar) sits.\n */\nexport function polylineMidpoint(points: Vec2[]): Vec2 {\n const first = points[0]\n if (!first) return { x: 0, y: 0 }\n let total = 0\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]\n const b = points[i + 1]\n if (a && b) total += Math.hypot(b.x - a.x, b.y - a.y)\n }\n let travelled = 0\n const half = total / 2\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]\n const b = points[i + 1]\n if (!a || !b) continue\n const length = Math.hypot(b.x - a.x, b.y - a.y)\n if (travelled + length >= half) {\n // Zero-length segments can't be interpolated through; the half mark is at\n // their shared point either way.\n const t = length === 0 ? 0 : (half - travelled) / length\n return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }\n }\n travelled += length\n }\n return points[points.length - 1] ?? first\n}\n\n/** Approximate min distance from a point to a polyline. */\nexport function distanceToPolyline(point: Vec2, points: Vec2[]): number {\n let best = Number.POSITIVE_INFINITY\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]\n const b = points[i + 1]\n if (!a || !b) continue\n best = Math.min(best, distanceToSegment(point, a, b))\n }\n return best\n}\n\nfunction distanceToSegment(p: Vec2, a: Vec2, b: Vec2): number {\n const dx = b.x - a.x\n const dy = b.y - a.y\n const lenSq = dx * dx + dy * dy\n if (lenSq === 0) return Math.hypot(p.x - a.x, p.y - a.y)\n let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / lenSq\n t = Math.max(0, Math.min(1, t))\n return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))\n}\n","import { clamp } from \"@rivet/utils\"\nimport {\n type AnchorRecord,\n type AnchorRef,\n type AnchorRegistrationOptions,\n anchorGeometryEqual,\n anchorHandleId,\n computeAnchorGeometry,\n parseAnchorAutoHandleId,\n parseAnchorHandleId,\n} from \"./anchor/registry\"\nimport { applyEdgeChanges, applyNodeChanges } from \"./changes\"\nimport { DEFAULT_NODE_SIZE, handleKey } from \"./constants\"\nimport { type EdgeAlignment, resolveFacingSideAmong } from \"./edge-alignment\"\nimport { displayedSideKey, parseSideHandleId } from \"./edge-ends\"\nimport { guardNodeChanges, keepLocalGeometry } from \"./gesture-guard\"\nimport {\n buildChildIndex,\n collectDescendants,\n descendantIds,\n hasAncestorIn,\n nodeControlledEqual,\n nodeDepth,\n worldPosition,\n} from \"./graph\"\nimport { HistoryManager, type HistorySnapshot, hasRecordableChange } from \"./history\"\nimport { createLockRegistry, type LockRegistry } from \"./locks/registry\"\nimport { createPresenceRegistry, type PresenceRegistry } from \"./presence/registry\"\nimport { edgeTargetKey, type PresenceTargetKey } from \"./presence/targets\"\nimport { reachableSides } from \"./renderer/edge-geometry\"\nimport type {\n AlignmentGuide,\n ChangeMeta,\n ChangeOrigin,\n Connection,\n EdgeChange,\n EdgeEnd,\n EdgeId,\n HandlePosition,\n HandleRecord,\n HandleType,\n NodeChange,\n NodeGestureEvent,\n NodeId,\n NodeLockConflictEvent,\n PendingConnection,\n ReconnectDelegate,\n Rect,\n RivetEdge,\n RivetNode,\n RivetSelection,\n Size,\n Vec2,\n Viewport,\n} from \"./types\"\n\nexport { handleKey } from \"./constants\"\n\nexport type RivetStoreInit = {\n nodes: RivetNode[]\n edges: RivetEdge[]\n viewport: Viewport\n}\n\ntype ViewportClamp = { minX: number; minY: number; maxY?: number }\ntype ChangeHandlers = {\n nodes?: (changes: NodeChange[], meta: ChangeMeta) => void\n edges?: (changes: EdgeChange[], meta: ChangeMeta) => void\n}\n/** Gesture lifecycle sinks — see {@link RivetStore.setGestureHandlers}. */\ntype GestureHandlers = {\n start?: (event: NodeGestureEvent) => void\n end?: (event: NodeGestureEvent) => void\n /** A peer's lock landed on a node this client is already holding. */\n conflict?: (event: NodeLockConflictEvent) => void\n}\n\n/** Changes to hand to {@link RivetStore.applyRemote}. */\nexport type RemoteChanges = {\n nodes?: NodeChange[]\n edges?: EdgeChange[]\n /** Defaults to `\"remote\"`. Pass a peer or transaction id to route on it. */\n origin?: ChangeOrigin\n}\n\n/**\n * The single source of truth for a graph instance — the public contract. It's an\n * interface so consumers depend on the shape, not the implementation ({@link\n * RivetGraphStore}); pure graph algorithms live in `graph.ts`.\n *\n * Subscriptions are deliberately granular so touching one node never re-renders\n * the others:\n * - **per-node** channel — a `NodeWrapper` subscribes to only its own node, so\n * selecting/moving/measuring node A re-renders A alone.\n * - the `NodeLayer`'s list is driven by the culled `visibleIds` prop, so it\n * re-renders only when the visible set changes, never on node data.\n * - **viewport** and **frame** channels drive the canvas (and the label\n * layer's imperative positioning) without touching React at all.\n */\nexport type RivetStore = {\n readonly nodes: Map<NodeId, RivetNode>\n readonly edges: Map<EdgeId, RivetEdge>\n readonly handles: Map<string, HandleRecord>\n\n // Per-node React channel.\n getNodeVersion: (id: NodeId) => number\n subscribeNode: (id: NodeId, listener: () => void) => () => void\n\n // DOM-element registry — lets group drags translate peers imperatively.\n registerNodeElement: (id: NodeId, el: HTMLElement) => void\n unregisterNodeElement: (id: NodeId, el: HTMLElement) => void\n getNodeElement: (id: NodeId) => HTMLElement | undefined\n\n /**\n * Register the controlled-mode change sinks. When set, node/edge mutations emit\n * {@link NodeChange}/{@link EdgeChange} batches so a consumer can own the state.\n * Emission is suppressed while {@link reconcile} is applying incoming props, so\n * feeding changes back in never loops.\n */\n setChangeHandlers: (handlers: ChangeHandlers) => void\n /**\n * Sync the store to controlled `nodes`/`edges` props. Adds/removes/updates to\n * match, without re-emitting changes. No-op writes are skipped so unrelated\n * nodes don't re-render.\n */\n reconcile: (nodes: RivetNode[], edges: RivetEdge[]) => void\n /**\n * Apply a change batch that happened somewhere else — a peer's edit arriving\n * over your transport. The graph updates and repaints immediately, then the\n * batch is re-emitted to the change handlers tagged `\"remote\"` so a controlled\n * owner applies it through the same path as everything else.\n *\n * Remote batches never create an undo step: undoing a peer's edit isn't undo,\n * and in a shared document it would silently revert work you don't own. The\n * history baseline is refreshed instead, so your next local step still diffs\n * against reality.\n */\n applyRemote: (changes: RemoteChanges) => void\n\n /** Add a node (imperative CRUD). Ignored if the id already exists. */\n addNode: (node: RivetNode) => void\n /** Replace a node wholesale by id (imperative CRUD). Ignored if absent. */\n replaceNode: (id: NodeId, node: RivetNode) => void\n\n getViewport: () => Viewport\n setViewport: (viewport: Viewport) => void\n subscribeViewport: (listener: (viewport: Viewport) => void) => () => void\n /**\n * Bound panning against the swimlane area. `minX`/`minY` pin the top-left: you\n * can't scroll left of `minX` or up above `minY`. `maxY` (optional) pins the\n * bottom: you can't scroll down far enough to push the world-y `maxY` above the\n * pane top. Pass `null` to remove the bound. Applied to every viewport change,\n * including zoom and programmatic sets.\n */\n setViewportClamp: (clamp: ViewportClamp | null) => void\n\n // Post-frame channel — fires after each rendered canvas frame (pan, zoom,\n // node move, add/remove). Lets secondary views (e.g. a MiniMap) stay in sync\n // without a render loop of their own. `notifyFrame` is called by the runtime.\n subscribeFrame: (listener: () => void) => () => void\n notifyFrame: () => void\n\n /**\n * Post-frame channel for peer cursors alone. Fires after every frame that\n * repainted them — the cursor-only frames a pointer move schedules, *and*\n * full frames, which own every layer.\n *\n * Its own channel because cursor frames are the ones that arrive at pointer\n * rate for every peer: chrome that follows a cursor needs all of them, while\n * everything else on {@link subscribeFrame} would be woken up for nothing.\n * Read positions off `presence.getPeers()` — they're the interpolated ones,\n * already stepped for this frame.\n */\n subscribeCursorFrame: (listener: () => void) => () => void\n notifyCursorFrame: () => void\n\n /** Move a node. `commit` re-renders just that node; skip it during drag. */\n moveNode: (id: NodeId, position: Vec2, commit: boolean) => void\n setNodeSize: (id: NodeId, size: Size) => void\n /**\n * Set a node's explicit `width`/`height` (from {@link NodeResizer}), optionally\n * moving its origin (for top/left resize handles). Re-renders the node every\n * frame so its box and geometry props update live; `commit` only marks the\n * emitted change final (`resizing`/`dragging` false → recordable to history).\n */\n resizeNode: (id: NodeId, size: Size, position?: Vec2, commit?: boolean) => void\n /** Absolute world position of a node, resolving its {@link RivetNode.parentId} chain. */\n getNodeWorldPosition: (id: NodeId) => Vec2\n /**\n * World positions for every node (parent chains applied), cached and rebuilt only\n * when node geometry changes — so pan/zoom frames, where nothing moved, reuse it.\n */\n getWorldPositions: () => ReadonlyMap<NodeId, Vec2>\n /** A node's world-space box (`getNodeWorldPosition` + measured/default size). */\n getNodeRect: (id: NodeId) => Rect\n /** How many ancestors a node has (0 for a top-level node). Drives z-stacking. */\n getNodeDepth: (id: NodeId) => number\n /** Ids of every descendant of a node (children, grandchildren, …). */\n getDescendantIds: (id: NodeId) => NodeId[]\n /**\n * Of the given ids, the ones whose ancestor isn't also in the set — the nodes a\n * group move should actually translate (a selected child of a selected parent\n * rides along with the parent, so moving it too would double its travel).\n */\n getMovers: (ids: NodeId[]) => NodeId[]\n /**\n * Reassign a node's swimlane. Returns the previous lane id if it changed (so\n * the caller can fire a lane-change callback), or `false` when unchanged.\n */\n setNodeLane: (id: NodeId, laneId: string | null) => string | null | false\n /**\n * Set the edge-alignment policy (the `edgeAlignment` prop). Under\n * `\"on-move\"`, a committed position change re-sides the moved node's edges\n * to face their peers, inside the same emission batch as the move.\n */\n setEdgeAlignment: (mode: EdgeAlignment) => void\n /** The current edge-alignment policy (the runtime reads it per frame). */\n getEdgeAlignment: () => EdgeAlignment\n /**\n * Hysteresis memory for per-frame side resolution, keyed by\n * `displayedSideKey(edgeId, end)`. The render loop hands this map to the\n * renderer, which reads each auto-resolved end's last displayed side and\n * writes the new one back; a `\"live\"` alignment commit re-sides pinned ends\n * to exactly what was displayed, then drops those entries. Never persisted.\n */\n getDisplayedSides: () => Map<string, HandlePosition>\n /**\n * Nodes currently mid-drag — populated by uncommitted {@link moveNode}\n * frames, emptied on commit (and cleared as a backstop when\n * {@link setNodeDragging} ends the gesture). Under `edgeAlignment: \"live\"`,\n * edges touching these nodes render both ends as auto.\n */\n getDraggingNodeIds: () => ReadonlySet<NodeId>\n /** True while a node drag is in progress (pauses swimlane auto-fit). */\n isNodeDragging: () => boolean\n setNodeDragging: (dragging: boolean) => void\n /**\n * Open a gesture on `ids` — a pointer drag, a resize, or a keyboard grab.\n * While it's open those nodes are *held*: this client's geometry for them wins\n * over anything arriving from elsewhere (see {@link isNodeHeld}), and\n * {@link GestureHandlers.start} fires so a consumer can take a lock.\n *\n * `id` is the node the gesture began on; `ids` is everything moving with it\n * (a group drag holds the whole selection). Re-opening an already-held node\n * is a no-op, so a gesture may safely widen.\n */\n beginNodeGesture: (id: NodeId, ids?: NodeId[]) => void\n /**\n * Close a gesture opened by {@link beginNodeGesture}, releasing its nodes.\n *\n * Normally the gesture calls this itself on drop. Calling it from outside is\n * how a consumer yields a contested node mid-drag: the running gesture sees\n * that it no longer holds its nodes, stops writing to them, and tears itself\n * down without committing.\n */\n endNodeGesture: (id: NodeId, ids?: NodeId[]) => void\n /**\n * Publish the lock table (the `lockedNodes` prop), keyed by\n * {@link PresenceTargetKey}, and report any node it claims that a local\n * gesture is already holding to {@link GestureHandlers.conflict}. The gesture\n * itself is left running — see {@link NodeLockConflictEvent} for why rivet\n * doesn't pick the loser.\n *\n * Only node gestures are scanned, because only nodes are held: an edge or an\n * anchor has no gesture to conflict with, so a lock on either is simply in\n * force from the moment it arrives.\n */\n setLockedNodes: (locks: Record<PresenceTargetKey, string> | undefined) => void\n /**\n * True while a local gesture holds this node. Held geometry is exclusively\n * this client's: {@link applyRemote} drops incoming `position`/`dimensions`\n * for it, and {@link reconcile} keeps the live box rather than the prop's.\n */\n isNodeHeld: (id: NodeId) => boolean\n /** Every node currently under a local gesture. */\n getHeldNodeIds: () => ReadonlySet<NodeId>\n /**\n * Subscribe to the held set opening or closing. Unlike\n * {@link setGestureHandlers} — a single sink the `onNodeDragStart` /\n * `onNodeDragEnd` props own — this is a broadcast channel, so presence can\n * watch the same gesture the consumer's lock handler is acting on.\n */\n subscribeHeldNodes: (listener: () => void) => () => void\n /** Register the gesture lifecycle handlers (the lock acquire/release signals). */\n setGestureHandlers: (handlers: GestureHandlers) => void\n /**\n * True while a resize gesture is in progress — set by {@link resizeNode}'s live\n * frames and cleared by its commit. Stomp protection is per-node and lives in\n * {@link isNodeHeld}; this stays a coarse \"is a resize happening at all\" flag.\n */\n isNodeResizing: () => boolean\n /**\n * Select node(s). `additive` toggles `id` in the current selection (Shift/Cmd\n * click); otherwise the selection is replaced. Passing `null` clears it.\n */\n selectNode: (id: NodeId | null, additive?: boolean) => void\n /** Replace (or, if `additive`, extend) the node selection with `ids`. */\n selectNodes: (ids: NodeId[], additive?: boolean) => void\n /** The currently selected node ids. */\n getSelectedNodes: () => NodeId[]\n /** True if the node is part of the current selection. */\n isNodeSelected: (id: NodeId) => boolean\n /**\n * The selected edge, if any — edge selection is single. The id alone, for\n * callers that would otherwise build {@link getSelection}'s records to read it.\n */\n getSelectedEdgeId: () => EdgeId | null\n /** The current selection (nodes + edges) as full records. */\n getSelection: () => RivetSelection\n /** Subscribe to selection changes (nodes and/or edges). */\n subscribeSelection: (listener: (selection: RivetSelection) => void) => () => void\n /**\n * The persistent selection box left behind by a marquee — a draggable rect\n * over the selected nodes' bounding box. Activated by the marquee's end;\n * deactivated by any other selection change (a node/edge/pane click, a\n * programmatic select, Escape, or deleting the selection).\n */\n setSelectionBoxActive: (active: boolean) => void\n isSelectionBoxActive: () => boolean\n /**\n * Version channel for the selection box: bumped when the flag flips and, while\n * active, when the boxed selection's membership or geometry changes — so the\n * box component can re-render its bounding rect from a single subscription.\n */\n getSelectionBoxVersion: () => number\n subscribeSelectionBox: (listener: () => void) => () => void\n /** Set (or clear, with `null`) the hovered node. */\n hoverNode: (id: NodeId | null) => void\n /**\n * The node that currently holds keyboard focus, or `null`. View state, like\n * hover — never recorded to history, never emitted as a change, and stripped\n * from snapshots. Tracked from the node elements' focus/blur by the node\n * layer; set it programmatically to move real DOM focus to a node (the\n * runtime follows this channel, centering the viewport first when the node\n * is culled out of the DOM).\n */\n getFocusedNode: () => NodeId | null\n /** Focus a node by id, or clear with `null`. Unknown ids are ignored. */\n setFocusedNode: (id: NodeId | null) => void\n /** Subscribe to focused-node changes. */\n subscribeFocus: (listener: (id: NodeId | null) => void) => () => void\n selectEdge: (id: EdgeId | null) => void\n /** The selected edge's id, or null. */\n getSelectedEdge: () => EdgeId | null\n /**\n * Runtime binding for the reconnect gateway. `<Handle>` consults it on\n * pointer-down so a press that lands on a handle coinciding with a\n * reconnectable edge's endpoint moves that edge instead of starting a new\n * connection. Bound by the runtime (like {@link bindRenderRequester}).\n */\n bindReconnectDelegate: (delegate: ReconnectDelegate | null) => void\n getReconnectDelegate: () => ReconnectDelegate | null\n addEdge: (edge: RivetEdge) => void\n /** Replace an edge wholesale by id (imperative CRUD). Ignored if absent. */\n replaceEdge: (id: EdgeId, edge: RivetEdge) => void\n /** Re-point an edge's source/target (from an endpoint reconnection drag). */\n reconnectEdge: (id: EdgeId, connection: Connection) => void\n removeEdge: (id: EdgeId) => void\n removeNode: (id: NodeId) => void\n /** Delete the selected node (and its edges) and/or edge. Returns true if any. */\n deleteSelection: () => boolean\n\n // Undo / redo over structural graph history (positions, add/remove/replace).\n // Selection changes and live drag/resize frames don't create steps.\n /** Revert the last recordable change. Returns false when there's nothing to undo. */\n undo: () => boolean\n /** Re-apply the last undone change. Returns false when there's nothing to redo. */\n redo: () => boolean\n canUndo: () => boolean\n canRedo: () => boolean\n /** Drop all history and reset the baseline to the current graph. */\n clearHistory: () => void\n /** Subscribe to history changes (drives `canUndo`/`canRedo` reactivity). */\n subscribeHistory: (listener: () => void) => () => void\n\n // Screen-space label anchors, refreshed by the renderer each frame. The DOM\n // edge-label layer reads these on `subscribeFrame` to place labels.\n getEdgeLabelAnchors: () => Map<EdgeId, Vec2>\n setEdgeLabelAnchors: (anchors: Map<EdgeId, Vec2>) => void\n\n /**\n * Screen-space anchor points for the edges peers have claimed, from the same\n * renderer pass — a point on each drawn path, which is the one thing a DOM\n * outline layer can't work out for itself. Empty unless something is claimed\n * and DOM outline chrome is mounted.\n */\n getPeerEdgeAnchors: () => ReadonlyMap<EdgeId, Vec2>\n setPeerEdgeAnchors: (anchors: ReadonlyMap<EdgeId, Vec2>) => void\n\n /** Alignment/snap guides to draw for the current drag (world space). Empty when idle. */\n getAlignmentGuides: () => AlignmentGuide[]\n setAlignmentGuides: (guides: AlignmentGuide[]) => void\n\n // Handle registry — canvas-only, never triggers a React re-render.\n registerHandle: (record: HandleRecord) => void\n unregisterHandle: (nodeId: NodeId, handleId: string) => void\n\n /**\n * Ephemeral peer presence — cursors, selections, and the boxes peers are\n * dragging right now. Never part of the graph, the change stream, or\n * history: presence describes people, not the document. Painted from the\n * render loop; see `rivet/presence`.\n */\n readonly presence: PresenceRegistry\n\n /**\n * Nodes peers have claimed, and the policy for what this client may still do\n * to them. Published whole by {@link setLockedNodes}; read by every input\n * path before it acts, and by the render loop to outline the holder. Like\n * presence, never part of the graph, the change stream, or history.\n */\n readonly locks: LockRegistry\n\n // Anchor registry — a connectable point bound to a DOM element inside a\n // node. Keyed like handles; per-node version channel drives the chrome.\n readonly anchors: Map<string, AnchorRecord>\n /**\n * Register (or re-bind) an anchor. Idempotent on the `(nodeId, anchorId)`\n * key: calling again with a new element re-attaches it, keeping any\n * last-known geometry until the next successful measurement.\n */\n registerAnchor: (\n nodeId: NodeId,\n anchorId: string,\n element: Element,\n options?: AnchorRegistrationOptions,\n ) => void\n /**\n * Mark an anchor's element gone without removing the anchor — the stale\n * retention signal. Geometry (and the stray handles rendered from it) is\n * kept so edges stay put while the display is unmounted.\n */\n detachAnchor: (nodeId: NodeId, anchorId: string) => void\n /** Explicitly remove an anchor and the chrome rendered for it. */\n unregisterAnchor: (nodeId: NodeId, anchorId: string) => void\n /**\n * Re-measure a node's anchors. Called automatically when the node's box\n * resizes; call it directly after content reflows *without* a resize (an\n * editor transaction, a font load) — rivet can't observe those.\n */\n remeasureAnchors: (nodeId: NodeId) => void\n /** The node's anchors, in registration order. */\n getNodeAnchors: (nodeId: NodeId) => AnchorRecord[]\n getNodeAnchorsVersion: (nodeId: NodeId) => number\n subscribeNodeAnchors: (nodeId: NodeId, listener: () => void) => () => void\n\n // Anchor selection — view state, like hover and focus. An anchor isn't in the\n // graph (it's registry state read off rendered DOM), so there's nowhere to\n // persist `selected`: it can't round-trip through `toObject`, can't arrive as\n // a controlled prop, and undo restores nodes and edges. Nothing here emits a\n // change or records to history, and `RivetSelection` stays graph-only.\n /** The selected anchors. A cached snapshot — identity changes with the data. */\n getSelectedAnchors: () => readonly AnchorRef[]\n /**\n * Replace the anchor selection. Selecting any anchor clears the node and edge\n * selection: one selection concept, so delete and the chrome never describe\n * two claims at once.\n */\n setSelectedAnchors: (refs: readonly AnchorRef[]) => void\n isAnchorSelected: (nodeId: NodeId, anchorId: string) => boolean\n subscribeAnchorSelection: (listener: () => void) => () => void\n\n // Edge connectivity channel — bumped when edges are added/removed or change\n // endpoints/handles, so anchor chrome can follow which sides are connected.\n getEdgesVersion: () => number\n subscribeEdges: (listener: () => void) => () => void\n\n // In-progress connection (drag-to-connect).\n getPending: () => PendingConnection | null\n beginConnection: (pending: PendingConnection) => void\n updateConnection: (to: Vec2, toPosition?: HandlePosition) => void\n endConnection: () => void\n /**\n * The local pending connection changing — started, moved, dropped. Its own\n * channel because presence has to publish it: the drag lives entirely in the\n * canvas otherwise, and nothing else would tell an outbound tracker that a\n * wire was let go of (a drop that moves the pointer no further would leave a\n * peer's copy hanging there).\n */\n subscribeConnection: (listener: () => void) => () => void\n\n /** Ask the runtime to schedule a canvas frame. */\n requestRender: () => void\n bindRenderRequester: (fn: () => void) => void\n /**\n * Ask the runtime to repaint the peer-cursor layer only — everything else on\n * screen keeps last frame's pixels. Degrades to {@link requestRender} while\n * no runtime has claimed the layer, so a caller never has to check.\n */\n requestCursorRender: () => void\n bindCursorRenderRequester: (fn: (() => void) | null) => void\n}\n\n/**\n * The store implementation. Public methods are bound arrow fields so they can be\n * passed unbound (e.g. straight into `useSyncExternalStore`); internal bookkeeping\n * lives in private methods, and the graph walks come from `graph.ts`.\n */\nclass RivetGraphStore implements RivetStore {\n readonly nodes = new Map<NodeId, RivetNode>()\n readonly edges = new Map<EdgeId, RivetEdge>()\n readonly handles = new Map<string, HandleRecord>()\n readonly anchors = new Map<string, AnchorRecord>()\n // Arrow-wrapped so the (later-initialized) requestRender field is looked up\n // at call time, not while this field is being constructed.\n readonly presence = createPresenceRegistry({\n requestRender: () => this.requestRender(),\n requestCursorRender: () => this.requestCursorRender(),\n })\n readonly locks = createLockRegistry(\n () => this.requestRender(),\n (id) => this.nodes.get(id)?.parentId,\n )\n\n private viewport: Viewport\n private viewportClamp: ViewportClamp | null = null\n private pending: PendingConnection | null = null\n\n private readonly nodeVersions = new Map<NodeId, number>()\n private readonly nodeListeners = new Map<NodeId, Set<() => void>>()\n private readonly anchorVersions = new Map<NodeId, number>()\n private readonly anchorListeners = new Map<NodeId, Set<() => void>>()\n private edgesVersion = 0\n private readonly edgesListeners = new Set<() => void>()\n private readonly nodeElements = new Map<NodeId, HTMLElement>()\n private readonly viewportListeners = new Set<(viewport: Viewport) => void>()\n private readonly frameListeners = new Set<() => void>()\n private readonly cursorFrameListeners = new Set<() => void>()\n private readonly connectionListeners = new Set<() => void>()\n private readonly selectionListeners = new Set<(selection: RivetSelection) => void>()\n private readonly selectedNodeIds = new Set<NodeId>()\n private selectionBoxActive = false\n private selectionBoxVersion = 0\n private readonly selectionBoxListeners = new Set<() => void>()\n\n private hoveredNodeId: NodeId | null = null\n private focusedNodeId: NodeId | null = null\n private readonly focusListeners = new Set<(id: NodeId | null) => void>()\n private selectedEdgeId: EdgeId | null = null\n /** Selected anchors, keyed like the registry so lookups are one hash. */\n private selectedAnchors = new Map<string, AnchorRef>()\n private selectedAnchorSnapshot: readonly AnchorRef[] = []\n private selectedAnchorsStale = false\n private readonly anchorSelectionListeners = new Set<() => void>()\n private nodeDragging = false\n private nodeResizing = false\n private edgeAlignment: EdgeAlignment = \"manual\"\n private readonly draggingNodeIds = new Set<NodeId>()\n private readonly heldNodeIds = new Set<NodeId>()\n private readonly heldListeners = new Set<() => void>()\n private gestureStartHandler: GestureHandlers[\"start\"] | null = null\n private gestureEndHandler: GestureHandlers[\"end\"] | null = null\n private lockConflictHandler: GestureHandlers[\"conflict\"] | null = null\n private readonly displayedSides = new Map<string, HandlePosition>()\n private edgeLabelAnchors = new Map<EdgeId, Vec2>()\n /** Screen-space points on claimed edges, published only while DOM outlines are on. */\n private peerEdgeAnchors: ReadonlyMap<EdgeId, Vec2> = new Map()\n private alignmentGuides: AlignmentGuide[] = []\n\n private nodeChangeHandler: ChangeHandlers[\"nodes\"] | null = null\n private edgeChangeHandler: ChangeHandlers[\"edges\"] | null = null\n private reconciling = false\n private readonly history = new HistoryManager(() => this.historySnapshot())\n\n private lastSelectionKey: string\n private worldCache: Map<NodeId, Vec2> | null = null\n /** {@link worldCache} with peers' live gesture boxes folded in. */\n private peerWorldCache: Map<NodeId, Vec2> | null = null\n /** Presence transform version {@link peerWorldCache} was built from. */\n private peerWorldVersion = -1\n private renderRequester: () => void = () => {}\n /**\n * Null until a runtime claims it, and then `requestCursorRender` narrows to\n * the cursor layer. Falling back to a full frame is the safe default: a\n * consumer without the layer mounted still gets its paint.\n */\n private cursorRenderRequester: (() => void) | null = null\n\n constructor(init: RivetStoreInit) {\n this.viewport = init.viewport\n for (const node of init.nodes) this.writeNode(node.id, node)\n for (const edge of init.edges) this.edges.set(edge.id, edge)\n // Seed selection so `selected` flags and the selection set agree from frame one.\n for (const node of init.nodes) if (node.selected) this.selectedNodeIds.add(node.id)\n this.selectedEdgeId = init.edges.find((edge) => edge.selected)?.id ?? null\n this.lastSelectionKey = this.selectionKey()\n // The history baseline is captured at field-init (before nodes loaded above),\n // so reset it now that the initial graph is in place.\n this.history.clear()\n }\n\n // --- internal bookkeeping ------------------------------------------------\n\n private invalidateWorld(): void {\n this.worldCache = null\n this.peerWorldCache = null\n }\n\n /**\n * The single node-map write path. Invalidates the world-position cache exactly\n * when a layout-affecting field changed (the node's position or its parent\n * chain) or the node is new — so size/lane/selection/hover writes skip the\n * O(n) rebuild, and no mutator can forget to invalidate.\n */\n private writeNode(id: NodeId, next: RivetNode): void {\n const prev = this.nodes.get(id)\n this.nodes.set(id, next)\n if (\n !prev ||\n prev.parentId !== next.parentId ||\n prev.position.x !== next.position.x ||\n prev.position.y !== next.position.y\n ) {\n this.invalidateWorld()\n }\n }\n\n /** The single node-map delete path. Always invalidates — a removal shifts descendants. */\n private deleteNode(id: NodeId): void {\n this.nodes.delete(id)\n this.invalidateWorld()\n }\n\n private selectionKey(): string {\n return `${[...this.selectedNodeIds].sort().join(\",\")}|${this.selectedEdgeId ?? \"\"}`\n }\n\n private buildSelection(): RivetSelection {\n return {\n nodes: [...this.selectedNodeIds]\n .map((id) => this.nodes.get(id))\n .filter((n) => n !== undefined),\n edges: this.selectedEdgeId\n ? [this.edges.get(this.selectedEdgeId)].filter((e) => e !== undefined)\n : [],\n }\n }\n\n private notifySelection(): void {\n const key = this.selectionKey()\n if (key === this.lastSelectionKey) return\n this.lastSelectionKey = key\n // Membership changes that bypass the select* methods (reconcile, node\n // removal) still reshape an active box.\n if (this.selectionBoxActive) this.bumpSelectionBox()\n if (this.selectionListeners.size === 0) return\n const selection = this.buildSelection()\n for (const listener of this.selectionListeners) listener(selection)\n }\n\n private notifyHeld(): void {\n // The held set decides whose gesture owns a node's geometry, so the folded\n // world positions have to be rebuilt when it changes: a node this client\n // just let go of takes its peer's live box again, and one just grabbed\n // stops taking it.\n this.peerWorldCache = null\n this.requestRender()\n for (const listener of this.heldListeners) listener()\n }\n\n /**\n * The one emission policy. Unless a `reconcile` is applying incoming props\n * (which must never echo them back out), record the batch to history — when\n * `record` is set — then hand it to the controlled consumer. Recording happens\n * before the handler so history works in uncontrolled mode too.\n */\n private emit<C extends NodeChange | EdgeChange>(\n changes: C[],\n handler: ((changes: C[], meta: ChangeMeta) => void) | null | undefined,\n record: boolean,\n origin: ChangeOrigin = \"local\",\n ): void {\n if (this.reconciling || changes.length === 0) return\n if (record) this.history.record(hasRecordableChange(changes))\n // Unrecorded structural changes (measurement echoes, history restores) still\n // move the graph — rebase so the next recorded step diffs against reality.\n else if (hasRecordableChange(changes)) this.history.rebase()\n handler?.(changes, { origin })\n }\n\n private emitNodeChanges(changes: NodeChange[], record = true): void {\n this.emit(changes, this.nodeChangeHandler, record)\n }\n\n private emitEdgeChanges(changes: EdgeChange[], record = true): void {\n this.emit(changes, this.edgeChangeHandler, record)\n }\n\n private bumpNode(id: NodeId): void {\n this.nodeVersions.set(id, (this.nodeVersions.get(id) ?? 0) + 1)\n const listeners = this.nodeListeners.get(id)\n if (listeners) for (const listener of listeners) listener()\n // A boxed node's committed geometry change (arrow nudge, undo, resize)\n // moves the selection box's bounding rect with it.\n if (this.selectionBoxActive && this.selectedNodeIds.has(id)) this.bumpSelectionBox()\n }\n\n private bumpSelectionBox(): void {\n this.selectionBoxVersion += 1\n for (const listener of this.selectionBoxListeners) listener()\n }\n\n private bumpAnchors(id: NodeId): void {\n this.anchorVersions.set(id, (this.anchorVersions.get(id) ?? 0) + 1)\n const listeners = this.anchorListeners.get(id)\n if (listeners) for (const listener of listeners) listener()\n }\n\n private bumpEdges(): void {\n this.edgesVersion += 1\n for (const listener of this.edgesListeners) listener()\n }\n\n // Node selection is React state (nodes are DOM), so bump only what flips.\n // `target` is the exact set that should end up selected.\n private applyNodeSelection(target: Set<NodeId>): void {\n const changes: NodeChange[] = []\n for (const [nodeId, node] of this.nodes) {\n const selected = target.has(nodeId)\n if (Boolean(node.selected) !== selected) {\n this.writeNode(nodeId, { ...node, selected })\n this.bumpNode(nodeId)\n changes.push({ type: \"select\", id: nodeId, selected })\n }\n }\n this.selectedNodeIds.clear()\n for (const id of target) if (this.nodes.has(id)) this.selectedNodeIds.add(id)\n this.emitNodeChanges(changes)\n }\n\n private setNodeHover(id: NodeId | null): void {\n if (this.hoveredNodeId === id) return\n const prev = this.hoveredNodeId\n this.hoveredNodeId = id\n if (prev !== null) {\n const node = this.nodes.get(prev)\n if (node) {\n this.writeNode(prev, { ...node, hovered: false })\n this.bumpNode(prev)\n }\n }\n if (id !== null) {\n const node = this.nodes.get(id)\n if (node) {\n this.writeNode(id, { ...node, hovered: true })\n this.bumpNode(id)\n }\n }\n }\n\n // Edge selection is canvas-only, so it just invalidates the frame.\n private setEdgeSelection(id: EdgeId | null): void {\n if (this.selectedEdgeId === id) return\n const changes: EdgeChange[] = []\n if (this.selectedEdgeId) {\n const prev = this.edges.get(this.selectedEdgeId)\n if (prev) {\n this.edges.set(this.selectedEdgeId, { ...prev, selected: false })\n changes.push({ type: \"select\", id: this.selectedEdgeId, selected: false })\n }\n }\n if (id) {\n const next = this.edges.get(id)\n if (next) {\n this.edges.set(id, { ...next, selected: true })\n changes.push({ type: \"select\", id, selected: true })\n }\n }\n this.selectedEdgeId = id\n this.emitEdgeChanges(changes)\n this.requestRender()\n }\n\n private removeEdgeInternal(id: EdgeId): boolean {\n if (!this.edges.delete(id)) return false\n if (this.selectedEdgeId === id) this.selectedEdgeId = null\n this.displayedSides.delete(displayedSideKey(id, \"source\"))\n this.displayedSides.delete(displayedSideKey(id, \"target\"))\n this.bumpEdges()\n return true\n }\n\n // Drop a node's bookkeeping (map entry, version, selection, hover, its\n // handles and anchors). Edges are handled by the caller — reconcile owns\n // edges separately from remove.\n private dropNodeState(id: NodeId): void {\n this.deleteNode(id)\n this.nodeVersions.delete(id)\n this.anchorVersions.delete(id)\n this.selectedNodeIds.delete(id)\n if (this.hoveredNodeId === id) this.hoveredNodeId = null\n if (this.focusedNodeId === id) this.setFocusedNode(null)\n const prefix = `${id} `\n for (const key of this.handles.keys()) {\n if (key.startsWith(prefix)) this.handles.delete(key)\n }\n for (const key of this.anchors.keys()) {\n if (key.startsWith(prefix)) this.anchors.delete(key)\n }\n this.dropSelectedAnchors((ref) => ref.nodeId === id)\n }\n\n private removeNodeInternal(id: NodeId, removedEdges: EdgeId[]): boolean {\n if (!this.nodes.has(id)) return false\n this.dropNodeState(id)\n for (const [edgeId, edge] of this.edges) {\n if (edge.source === id || edge.target === id) {\n if (this.removeEdgeInternal(edgeId)) removedEdges.push(edgeId)\n }\n }\n return true\n }\n\n private edgeRemoveChanges(ids: EdgeId[]): EdgeChange[] {\n return ids.map((id) => ({ type: \"remove\", id }))\n }\n\n private clampViewport(next: Viewport): Viewport {\n const bound = this.viewportClamp\n if (!bound) return next\n const maxViewportX = -bound.minX * next.zoom\n const maxViewportY = -bound.minY * next.zoom\n const minViewportY =\n bound.maxY === undefined ? Number.NEGATIVE_INFINITY : -bound.maxY * next.zoom\n return {\n ...next,\n x: Math.min(next.x, maxViewportX),\n y: clamp(next.y, minViewportY, maxViewportY),\n }\n }\n\n private reconcileNodes(nextNodes: RivetNode[]): void {\n const incoming = new Set<NodeId>()\n const moved: NodeId[] = []\n for (const node of nextNodes) {\n incoming.add(node.id)\n const existing = this.nodes.get(node.id)\n if (!existing) {\n this.writeNode(node.id, node)\n continue\n }\n // A held node's geometry is this client's until the gesture ends: the\n // incoming props lag the live box (frames are dropped, and a measurement\n // echo carries `size` but not the explicit `width`/`height`), so taking\n // them would stomp the node back mid-drag. Everything else still lands.\n const settled = this.heldNodeIds.has(node.id) ? keepLocalGeometry(node, existing) : node\n if (nodeControlledEqual(existing, settled)) continue\n // Preserve hover (store-owned, never present in controlled props).\n this.writeNode(node.id, existing.hovered ? { ...settled, hovered: true } : settled)\n this.bumpNode(node.id)\n if (\n existing.position.x !== settled.position.x ||\n existing.position.y !== settled.position.y\n ) {\n moved.push(node.id)\n }\n }\n for (const id of [...this.nodes.keys()]) {\n if (!incoming.has(id)) this.dropNodeState(id)\n }\n // A moved node drags its descendants' world position; re-render them too. Build\n // the child index once for the whole batch rather than per moved node.\n if (moved.length > 0) {\n const childIndex = buildChildIndex(this.nodes)\n const descendants: NodeId[] = []\n for (const id of moved) collectDescendants(id, childIndex, descendants)\n for (const id of descendants) this.bumpNode(id)\n }\n this.selectedNodeIds.clear()\n for (const node of nextNodes) if (node.selected) this.selectedNodeIds.add(node.id)\n }\n\n private reconcileEdges(nextEdges: RivetEdge[]): void {\n const incoming = new Set<EdgeId>()\n // Reconcile runs on every controlled render; bump the connectivity channel\n // only when an edge appeared/disappeared or changed ends, so anchor chrome\n // doesn't re-render on unrelated prop round-trips.\n let connectivityChanged = false\n for (const edge of nextEdges) {\n incoming.add(edge.id)\n const prev = this.edges.get(edge.id)\n if (\n !prev ||\n prev.source !== edge.source ||\n prev.target !== edge.target ||\n prev.sourceHandle !== edge.sourceHandle ||\n prev.targetHandle !== edge.targetHandle\n ) {\n connectivityChanged = true\n }\n this.edges.set(edge.id, edge) // canvas-only; a wholesale replace is cheap\n }\n for (const id of [...this.edges.keys()]) {\n if (!incoming.has(id)) {\n this.edges.delete(id)\n connectivityChanged = true\n }\n }\n this.selectedEdgeId = nextEdges.find((edge) => edge.selected)?.id ?? null\n if (connectivityChanged) this.bumpEdges()\n }\n\n // --- per-node React channel ----------------------------------------------\n\n getNodeVersion = (id: NodeId): number => this.nodeVersions.get(id) ?? 0\n\n subscribeNode = (id: NodeId, listener: () => void): (() => void) => {\n let set = this.nodeListeners.get(id)\n if (!set) {\n set = new Set()\n this.nodeListeners.set(id, set)\n }\n set.add(listener)\n return () => {\n set.delete(listener)\n if (set.size === 0) this.nodeListeners.delete(id)\n }\n }\n\n registerNodeElement = (id: NodeId, el: HTMLElement): void => {\n this.nodeElements.set(id, el)\n }\n\n unregisterNodeElement = (id: NodeId, el: HTMLElement): void => {\n // Guard against a remount racing an unmount: only drop our own element.\n if (this.nodeElements.get(id) === el) this.nodeElements.delete(id)\n }\n\n getNodeElement = (id: NodeId): HTMLElement | undefined => this.nodeElements.get(id)\n\n // --- viewport ------------------------------------------------------------\n\n getViewport = (): Viewport => this.viewport\n\n setViewport = (next: Viewport): void => {\n this.viewport = this.clampViewport(next)\n for (const listener of this.viewportListeners) listener(this.viewport)\n }\n\n setViewportClamp = (clampBound: ViewportClamp | null): void => {\n this.viewportClamp = clampBound\n const clamped = this.clampViewport(this.viewport)\n if (clamped.x !== this.viewport.x || clamped.y !== this.viewport.y) {\n this.viewport = clamped\n for (const listener of this.viewportListeners) listener(this.viewport)\n this.requestRender()\n }\n }\n\n subscribeViewport = (listener: (viewport: Viewport) => void): (() => void) => {\n this.viewportListeners.add(listener)\n return () => {\n this.viewportListeners.delete(listener)\n }\n }\n\n subscribeFrame = (listener: () => void): (() => void) => {\n this.frameListeners.add(listener)\n return () => {\n this.frameListeners.delete(listener)\n }\n }\n\n notifyFrame = (): void => {\n for (const listener of this.frameListeners) listener()\n }\n\n subscribeCursorFrame = (listener: () => void): (() => void) => {\n this.cursorFrameListeners.add(listener)\n return () => {\n this.cursorFrameListeners.delete(listener)\n }\n }\n\n notifyCursorFrame = (): void => {\n for (const listener of this.cursorFrameListeners) listener()\n }\n\n // --- node geometry -------------------------------------------------------\n\n getWorldPositions = (): ReadonlyMap<NodeId, Vec2> => {\n if (!this.worldCache) {\n this.worldCache = new Map()\n for (const id of this.nodes.keys()) this.worldCache.set(id, worldPosition(this.nodes, id))\n }\n const version = this.presence.getTransformVersion()\n // Nobody else is mid-gesture: the graph's own positions are the whole story.\n if (this.presence.getNodeTransforms().size === 0) return this.worldCache\n if (this.peerWorldCache && this.peerWorldVersion === version) return this.peerWorldCache\n this.peerWorldVersion = version\n this.peerWorldCache = this.withPeerGestures(this.worldCache)\n return this.peerWorldCache\n }\n\n /**\n * Fold peers' live gesture boxes into world positions.\n *\n * A node somebody else is dragging is drawn, hit-tested and wired at the box\n * they last sent — the node moves, rather than a ghost of it appearing\n * elsewhere. The graph underneath is untouched: nothing here is written back,\n * so their drag never enters the document, the change stream, or history, and\n * the node lands for real when their commit arrives.\n *\n * Descendants ride along by the same delta, since their own positions are\n * relative to a parent this map has just moved.\n */\n private withPeerGestures(base: Map<NodeId, Vec2>): Map<NodeId, Vec2> {\n const merged = new Map(base)\n for (const [id, rect] of this.presence.getNodeTransforms()) {\n // A local gesture outranks a peer's: this client's pointer is on the node,\n // and ownership of geometry under a live gesture is exactly what the\n // guard exists to protect.\n if (this.heldNodeIds.has(id)) continue\n const origin = base.get(id)\n if (!origin) continue\n const dx = rect.x - origin.x\n const dy = rect.y - origin.y\n if (dx === 0 && dy === 0) continue\n merged.set(id, { x: rect.x, y: rect.y })\n for (const childId of this.getDescendantIds(id)) {\n const child = merged.get(childId)\n if (child) merged.set(childId, { x: child.x + dx, y: child.y + dy })\n }\n }\n return merged\n }\n\n getNodeWorldPosition = (id: NodeId): Vec2 => this.getWorldPositions().get(id) ?? { x: 0, y: 0 }\n\n getNodeRect = (id: NodeId): Rect => {\n const origin = this.getNodeWorldPosition(id)\n // A peer mid-resize sends a box, not just a point; take its size too, so the\n // node, its edges and its outline agree on how big it currently is.\n const live = this.heldNodeIds.has(id) ? undefined : this.presence.getNodeTransforms().get(id)\n if (live) return { x: origin.x, y: origin.y, width: live.width, height: live.height }\n // Explicit width/height outrank the measured size, the same order the node\n // element itself renders in — a controlled node arrives sized but unmeasured,\n // and reporting the default box for it would put edges, the minimap and\n // marquee hit-testing on a box nothing is drawn at.\n const node = this.nodes.get(id)\n return {\n x: origin.x,\n y: origin.y,\n width: node?.width ?? node?.size?.width ?? DEFAULT_NODE_SIZE.width,\n height: node?.height ?? node?.size?.height ?? DEFAULT_NODE_SIZE.height,\n }\n }\n\n getNodeDepth = (id: NodeId): number => nodeDepth(this.nodes, id)\n\n getDescendantIds = (id: NodeId): NodeId[] => descendantIds(this.nodes, id)\n\n getMovers = (ids: NodeId[]): NodeId[] => {\n const set = new Set(ids)\n return ids.filter((id) => !hasAncestorIn(this.nodes, id, set))\n }\n\n // --- node mutations ------------------------------------------------------\n\n moveNode = (id: NodeId, position: Vec2, commit: boolean): void => {\n const node = this.nodes.get(id)\n if (!node) return\n this.writeNode(id, { ...node, position })\n // Track which nodes are mid-drag (live frames open, the commit closes) so\n // `\"live\"` alignment knows whose edges to render as auto.\n if (commit) this.draggingNodeIds.delete(id)\n else this.draggingNodeIds.add(id)\n this.requestRender() // edges follow every frame\n if (commit) {\n this.bumpNode(id)\n // Descendants moved with this node in world space; re-render them so their\n // React transform (parent world + own offset) is recomputed.\n for (const descendant of descendantIds(this.nodes, id)) this.bumpNode(descendant)\n }\n this.emitNodeChanges([{ type: \"position\", id, position, dragging: !commit }])\n // After the position emission, so the edge rewrites coalesce into the\n // move's history step and the consumer sees the move before the re-side.\n if (commit) this.realignNodeEdges(id)\n }\n\n setNodeSize = (id: NodeId, size: Size): void => {\n const node = this.nodes.get(id)\n if (!node) return\n // Sub-pixel tolerance, not equality: measurements arrive as integer offset\n // dimensions, while an explicit size (from resizeNode) is fractional. During\n // a resize the observer echoes each frame back rounded; treating that echo\n // as a real measurement would emit an unflagged dimensions change mid-gesture.\n if (\n node.size &&\n Math.abs(node.size.width - size.width) < 1 &&\n Math.abs(node.size.height - size.height) < 1\n ) {\n return\n }\n this.writeNode(id, { ...node, size })\n this.requestRender()\n this.bumpNode(id)\n // Auto-measurement is store bookkeeping, not a user edit: emit it (controlled\n // mode needs the size) but never let it create an undo step.\n this.emitNodeChanges([{ type: \"dimensions\", id, dimensions: size }], false)\n }\n\n resizeNode = (id: NodeId, size: Size, position?: Vec2, commit = true): void => {\n const node = this.nodes.get(id)\n if (!node) return\n // Live frames open the gesture window; the commit closes it (before the\n // emission below, so the commit's own round-trip reconciles normally).\n this.nodeResizing = !commit\n const next: RivetNode = { ...node, width: size.width, height: size.height, size }\n if (position) next.position = position\n this.writeNode(id, next)\n this.requestRender()\n // Re-render the node every frame, not just on commit: a resize is always a\n // single node, so a per-frame re-render is cheap, and it keeps the box and the\n // node's geometry props live. (Group drag stays imperative — it can move many.)\n this.bumpNode(id)\n const changes: NodeChange[] = [{ type: \"dimensions\", id, dimensions: size, resizing: !commit }]\n if (position) changes.push({ type: \"position\", id, position, dragging: !commit })\n this.emitNodeChanges(changes)\n // A top/left resize handle moves the origin — that's a committed position\n // change, so it realigns like a move. A pure grow/shrink (dimensions only)\n // doesn't: auto-height echoes must never override a freshly chosen side.\n if (commit && position) this.realignNodeEdges(id)\n }\n\n setNodeLane = (id: NodeId, laneId: string | null): string | null | false => {\n const node = this.nodes.get(id)\n if (!node) return false\n const next = laneId ?? undefined\n if (node.laneId === next) return false\n const previous = node.laneId ?? null\n const updated = { ...node, laneId: next }\n this.writeNode(id, updated)\n this.bumpNode(id)\n // laneId isn't a standard change kind; round-trip it as a full replace.\n this.emitNodeChanges([{ type: \"replace\", id, item: updated }])\n return previous\n }\n\n addNode = (node: RivetNode): void => {\n if (this.nodes.has(node.id)) return\n this.writeNode(node.id, node)\n if (node.selected) this.selectedNodeIds.add(node.id)\n this.requestRender()\n this.emitNodeChanges([{ type: \"add\", item: node }])\n }\n\n replaceNode = (id: NodeId, node: RivetNode): void => {\n if (!this.nodes.has(id)) return\n this.writeNode(id, node)\n if (node.selected) this.selectedNodeIds.add(id)\n else this.selectedNodeIds.delete(id)\n this.bumpNode(id)\n this.requestRender()\n this.emitNodeChanges([{ type: \"replace\", id, item: node }])\n }\n\n removeNode = (id: NodeId): void => {\n const removedEdges: EdgeId[] = []\n if (this.removeNodeInternal(id, removedEdges)) {\n this.emitNodeChanges([{ type: \"remove\", id }])\n this.emitEdgeChanges(this.edgeRemoveChanges(removedEdges))\n this.requestRender()\n this.notifySelection()\n }\n }\n\n // --- edge alignment ------------------------------------------------------\n\n setEdgeAlignment = (mode: EdgeAlignment): void => {\n this.edgeAlignment = mode\n }\n\n getEdgeAlignment = (): EdgeAlignment => this.edgeAlignment\n\n getDisplayedSides = (): Map<string, HandlePosition> => this.displayedSides\n\n getDraggingNodeIds = (): ReadonlySet<NodeId> => this.draggingNodeIds\n\n /**\n * Re-side one edge end toward `side`. Auto ends (no handle, or an\n * `inode-…-auto` id) have no pin to rewrite and pass through. Anchor stray\n * and bare-side ids encode their side, so they rewrite as strings (the\n * anchor chrome follows connectivity, and the target stray may not be\n * rendered yet). A registered plain handle re-sides through the registry:\n * swap to a registered handle on the facing side with a compatible type. No\n * candidate (single-handle nodes, custom layouts, a culled peer whose\n * handles are unregistered) means the pin is kept.\n */\n /**\n * The side of `nodeId` that faces `peerRect` and can actually be reached by\n * this end. An anchor end is unconstrained — its stray places itself along\n * whichever side faces the peer — and so is a node with no compatible handle\n * at all, which attaches at side midpoints.\n */\n private reachableFacingSide(\n nodeId: NodeId,\n handleId: string | undefined,\n rect: Rect,\n peerRect: Rect,\n end: EdgeEnd,\n ): HandlePosition {\n const allowed =\n parseAnchorHandleId(handleId) || parseAnchorAutoHandleId(handleId)\n ? []\n : reachableSides(nodeId, end, this.handles)\n return resolveFacingSideAmong(rect, peerRect, allowed)\n }\n\n private realignEndHandle(\n nodeId: NodeId,\n handleId: string | undefined,\n side: HandlePosition,\n end: \"source\" | \"target\",\n ): string | undefined {\n if (!handleId || parseAnchorAutoHandleId(handleId)) return handleId\n const anchor = parseAnchorHandleId(handleId)\n if (anchor) return anchor.side === side ? handleId : anchorHandleId(anchor.anchorId, side)\n const record = this.handles.get(handleKey(nodeId, handleId))\n if (!record) return parseSideHandleId(handleId) ? side : handleId\n if (record.position === side) return handleId\n const wanted: readonly HandleType[] =\n end === \"source\" ? [\"source\", \"either\"] : [\"target\", \"either\"]\n for (const candidate of this.handles.values()) {\n if (\n candidate.nodeId === nodeId &&\n candidate.position === side &&\n wanted.includes(candidate.type)\n ) {\n return candidate.handleId\n }\n }\n return handleId\n }\n\n /**\n * Under `\"on-move\"` and `\"live\"`: re-side both ends of the moved node's\n * edges to face each other. Called only from committed position mutations —\n * never from replaces, dimension echoes, reconcile, or history restores,\n * which must not move an edge the user didn't touch or rewrite handles an\n * undo just restored. Emitting in the same synchronous batch as the move\n * keeps the rewrite inside the move's history step (microtask coalescing).\n *\n * `\"live\"` commits the *displayed* side when the renderer resolved one this\n * gesture — the hysteresis band means the raw facing side can differ near a\n * diagonal, and the drop must not flip what the user was just shown. The\n * consumed entries are dropped afterwards so a later commit without live\n * frames (an arrow-key move) can't re-side to a stale display.\n */\n private realignNodeEdges(nodeId: NodeId): void {\n if (this.edgeAlignment === \"manual\") return\n const live = this.edgeAlignment === \"live\"\n const changes: EdgeChange[] = []\n for (const [edgeId, edge] of this.edges) {\n if (edge.source !== nodeId && edge.target !== nodeId) continue\n // A self-edge has no facing side; re-siding would collapse both ends.\n if (edge.source === edge.target) continue\n if (!this.nodes.has(edge.source) || !this.nodes.has(edge.target)) continue\n const sourceRect = this.getNodeRect(edge.source)\n const targetRect = this.getNodeRect(edge.target)\n const sourceKey = displayedSideKey(edgeId, \"source\")\n const targetKey = displayedSideKey(edgeId, \"target\")\n // Constrained to the sides that carry a handle this end can use, the same\n // way the renderer resolves an auto end. Free resolution picks the\n // geometric facing side and then finds nothing there — a node with only\n // left and right handles never re-sides at all, because every vertical\n // layout resolves to a bare top or bottom.\n const sourceSide =\n (live ? this.displayedSides.get(sourceKey) : undefined) ??\n this.reachableFacingSide(edge.source, edge.sourceHandle, sourceRect, targetRect, \"source\")\n const targetSide =\n (live ? this.displayedSides.get(targetKey) : undefined) ??\n this.reachableFacingSide(edge.target, edge.targetHandle, targetRect, sourceRect, \"target\")\n const sourceHandle = this.realignEndHandle(\n edge.source,\n edge.sourceHandle,\n sourceSide,\n \"source\",\n )\n const targetHandle = this.realignEndHandle(\n edge.target,\n edge.targetHandle,\n targetSide,\n \"target\",\n )\n if (live) {\n // Keep auto ends' entries — they're refreshed every frame and carry the\n // hysteresis across the commit. Pinned ends' pins are now current.\n const pinned = (h: string | undefined) => Boolean(h) && !parseAnchorAutoHandleId(h)\n if (pinned(edge.sourceHandle)) this.displayedSides.delete(sourceKey)\n if (pinned(edge.targetHandle)) this.displayedSides.delete(targetKey)\n }\n if (sourceHandle === edge.sourceHandle && targetHandle === edge.targetHandle) continue\n const updated: RivetEdge = { ...edge, sourceHandle, targetHandle }\n this.edges.set(edgeId, updated)\n changes.push({ type: \"replace\", id: edgeId, item: updated })\n }\n if (changes.length === 0) return\n this.bumpEdges()\n this.requestRender()\n this.emitEdgeChanges(changes)\n }\n\n // --- drag / selection state ----------------------------------------------\n\n isNodeDragging = (): boolean => this.nodeDragging\n\n setNodeDragging = (dragging: boolean): void => {\n this.nodeDragging = dragging\n // Backstop: a gesture that ends without committing every mover (or at all)\n // must not leave nodes marked as dragging for `\"live\"` rendering.\n if (!dragging) this.draggingNodeIds.clear()\n }\n\n isNodeResizing = (): boolean => this.nodeResizing\n\n setGestureHandlers = (handlers: GestureHandlers): void => {\n this.gestureStartHandler = handlers.start ?? null\n this.gestureEndHandler = handlers.end ?? null\n this.lockConflictHandler = handlers.conflict ?? null\n }\n\n setLockedNodes = (locks: Record<PresenceTargetKey, string> | undefined): void => {\n const opened = this.locks.setLocks(locks)\n if (opened.length === 0 || this.heldNodeIds.size === 0) return\n // A lock that lands on a node this client is already holding is the case\n // the gesture guard can't decide on its own: both clients started before\n // either lock arrived, so neither is obviously stale. Report it and leave\n // the gesture running — the consumer's transport knows who lost.\n //\n // Scanned from the held side rather than the opened side, because a lock\n // taken on a container conflicts with a gesture on anything inside it —\n // the held node is never in `opened` in that case, only its ancestor is.\n const held = [...this.heldNodeIds]\n const openedSet = new Set(opened)\n for (const nodeId of held) {\n const source = this.locks.getLockSource(nodeId)\n if (source === null || !openedSet.has(source)) continue\n const holderId = this.locks.getHolder(nodeId)\n if (holderId) this.lockConflictHandler?.({ nodeId, holderId, ids: held })\n }\n }\n\n isNodeHeld = (id: NodeId): boolean => this.heldNodeIds.has(id)\n\n getHeldNodeIds = (): ReadonlySet<NodeId> => this.heldNodeIds\n\n beginNodeGesture = (id: NodeId, ids: NodeId[] = [id]): void => {\n const opened = ids.filter((nodeId) => !this.heldNodeIds.has(nodeId))\n if (opened.length === 0) return\n for (const nodeId of opened) this.heldNodeIds.add(nodeId)\n this.gestureStartHandler?.({ id, ids: [...ids] })\n this.notifyHeld()\n }\n\n endNodeGesture = (id: NodeId, ids: NodeId[] = [id]): void => {\n const closed = ids.filter((nodeId) => this.heldNodeIds.delete(nodeId))\n if (closed.length === 0) return\n this.gestureEndHandler?.({ id, ids: [...ids] })\n this.notifyHeld()\n }\n\n subscribeHeldNodes = (listener: () => void): (() => void) => {\n this.heldListeners.add(listener)\n return () => {\n this.heldListeners.delete(listener)\n }\n }\n\n selectNode = (id: NodeId | null, additive = false): void => {\n // Any click-driven or programmatic (re)selection dismisses the marquee's\n // box; the marquee re-activates it after its own selectNodes calls.\n this.setSelectionBoxActive(false)\n this.dropSelectedAnchors(() => true)\n if (id === null) {\n this.applyNodeSelection(new Set())\n this.notifySelection()\n return\n }\n let target: Set<NodeId>\n if (additive) {\n target = new Set(this.selectedNodeIds)\n if (target.has(id)) target.delete(id)\n else target.add(id)\n } else {\n target = new Set([id])\n }\n this.applyNodeSelection(target)\n this.setEdgeSelection(null)\n this.notifySelection()\n }\n\n selectNodes = (ids: NodeId[], additive = false): void => {\n this.setSelectionBoxActive(false)\n this.dropSelectedAnchors(() => true)\n const target = additive ? new Set(this.selectedNodeIds) : new Set<NodeId>()\n for (const id of ids) target.add(id)\n this.applyNodeSelection(target)\n if (target.size > 0) this.setEdgeSelection(null)\n this.notifySelection()\n }\n\n getSelectedNodes = (): NodeId[] => [...this.selectedNodeIds]\n\n isNodeSelected = (id: NodeId): boolean => this.selectedNodeIds.has(id)\n\n getSelectedEdgeId = (): EdgeId | null => this.selectedEdgeId\n\n getSelection = (): RivetSelection => this.buildSelection()\n\n subscribeSelection = (listener: (selection: RivetSelection) => void): (() => void) => {\n this.selectionListeners.add(listener)\n return () => {\n this.selectionListeners.delete(listener)\n }\n }\n\n setSelectionBoxActive = (active: boolean): void => {\n if (this.selectionBoxActive === active) return\n this.selectionBoxActive = active\n this.bumpSelectionBox()\n }\n\n isSelectionBoxActive = (): boolean => this.selectionBoxActive\n\n getSelectionBoxVersion = (): number => this.selectionBoxVersion\n\n subscribeSelectionBox = (listener: () => void): (() => void) => {\n this.selectionBoxListeners.add(listener)\n return () => {\n this.selectionBoxListeners.delete(listener)\n }\n }\n\n hoverNode = (id: NodeId | null): void => {\n this.setNodeHover(id)\n }\n\n getFocusedNode = (): NodeId | null => this.focusedNodeId\n\n setFocusedNode = (id: NodeId | null): void => {\n if (id !== null && !this.nodes.has(id)) return\n if (this.focusedNodeId === id) return\n this.focusedNodeId = id\n for (const listener of this.focusListeners) listener(id)\n }\n\n subscribeFocus = (listener: (id: NodeId | null) => void): (() => void) => {\n this.focusListeners.add(listener)\n return () => {\n this.focusListeners.delete(listener)\n }\n }\n\n // --- edges ---------------------------------------------------------------\n\n selectEdge = (id: EdgeId | null): void => {\n this.setSelectionBoxActive(false)\n this.dropSelectedAnchors(() => true)\n this.setEdgeSelection(id)\n this.applyNodeSelection(new Set())\n this.notifySelection()\n }\n\n addEdge = (edge: RivetEdge): void => {\n if (this.edges.has(edge.id)) return\n this.edges.set(edge.id, edge)\n this.bumpEdges()\n this.requestRender() // edges are canvas-only, no React re-render\n this.emitEdgeChanges([{ type: \"add\", item: edge }])\n }\n\n replaceEdge = (id: EdgeId, edge: RivetEdge): void => {\n if (!this.edges.has(id)) return\n this.edges.set(id, edge)\n if (this.selectedEdgeId === id && !edge.selected) this.selectedEdgeId = null\n this.bumpEdges()\n this.requestRender()\n this.emitEdgeChanges([{ type: \"replace\", id, item: edge }])\n }\n\n reconnectEdge = (id: EdgeId, connection: Connection): void => {\n const edge = this.edges.get(id)\n if (!edge) return\n const updated: RivetEdge = {\n ...edge,\n source: connection.source,\n target: connection.target,\n sourceHandle: connection.sourceHandle ?? undefined,\n targetHandle: connection.targetHandle ?? undefined,\n }\n this.edges.set(id, updated)\n this.bumpEdges()\n this.requestRender()\n this.emitEdgeChanges([{ type: \"replace\", id, item: updated }])\n }\n\n removeEdge = (id: EdgeId): void => {\n if (this.removeEdgeInternal(id)) {\n this.emitEdgeChanges([{ type: \"remove\", id }])\n this.requestRender()\n this.notifySelection()\n }\n }\n\n deleteSelection = (): boolean => {\n const removedNodes: NodeId[] = []\n const removedEdges: EdgeId[] = []\n // Hoist the id: removeEdgeInternal clears `selectedEdgeId` as a side effect,\n // so re-reading the field after it would push null into the change batch.\n const selectedEdge = this.selectedEdgeId\n // An edge lock refuses the edge itself. Deleting a *node* still takes its\n // edges with it — those come off as a consequence of a delete the node's\n // own lock already had the chance to refuse, and leaving an edge behind\n // with nothing on one end would be a worse answer than removing it.\n if (\n selectedEdge &&\n this.locks.allows(edgeTargetKey(selectedEdge), \"delete\") &&\n this.removeEdgeInternal(selectedEdge)\n ) {\n removedEdges.push(selectedEdge)\n }\n if (this.selectedNodeIds.size > 0) {\n for (const id of [...this.selectedNodeIds]) {\n // A locked node can be in the selection even though a lock refuses\n // selection: it was selected first and the lock arrived after. Deleting\n // the rest of the selection around it is the least surprising outcome —\n // the alternative is refusing the whole keystroke over one node.\n if (!this.locks.allows(id, \"delete\")) continue\n if (this.removeNodeInternal(id, removedEdges)) removedNodes.push(id)\n }\n }\n const changed = removedNodes.length > 0 || removedEdges.length > 0\n if (changed) {\n this.setSelectionBoxActive(false)\n this.emitNodeChanges(removedNodes.map((id) => ({ type: \"remove\", id })))\n this.emitEdgeChanges(this.edgeRemoveChanges(removedEdges))\n this.requestRender()\n this.notifySelection()\n }\n return changed\n }\n\n // --- controlled mode -----------------------------------------------------\n\n setChangeHandlers = (handlers: ChangeHandlers): void => {\n this.nodeChangeHandler = handlers.nodes ?? null\n this.edgeChangeHandler = handlers.edges ?? null\n }\n\n reconcile = (nextNodes: RivetNode[], nextEdges: RivetEdge[]): void => {\n this.reconciling = true\n try {\n this.reconcileNodes(nextNodes)\n this.reconcileEdges(nextEdges)\n } finally {\n this.reconciling = false\n }\n // Reconcile mutates without emitting or recording, so the history baseline\n // must catch up — otherwise the next recorded step's undo also reverts the\n // prop-applied changes (e.g. a prop-added node deleted through the store\n // would undo to a graph without it).\n this.history.rebase()\n // World-cache invalidation is handled per-node by writeNode/deleteNode above.\n this.requestRender() // re-cull for added/removed nodes and repaint edges\n }\n\n applyRemote = ({ nodes = [], edges = [], origin = \"remote\" }: RemoteChanges): void => {\n // A live local gesture owns its nodes' geometry, so a remote write to it is\n // stale on arrival — the peer was looking at a box this client has already\n // moved. Drop those parts here, before anything else sees them, so the\n // applied batch and the re-emitted batch stay the same thing.\n const guarded = guardNodeChanges(nodes, this.isNodeHeld, (id) => this.nodes.get(id))\n if (guarded.length === 0 && edges.length === 0) return\n // Route through reconcile so remote batches land through exactly the same\n // code as controlled props — one set of bumping, culling and cache rules,\n // and no second apply path that can drift from it. Reconcile suppresses\n // emission and rebases history, which is what a remote batch wants anyway.\n const currentNodes = [...this.nodes.values()]\n const currentEdges = [...this.edges.values()]\n this.reconcile(applyNodeChanges(guarded, currentNodes), applyEdgeChanges(edges, currentEdges))\n // Replay the batch over the stored undo/redo steps too, so undoing past a\n // peer's edit reverts only this client's work and leaves theirs standing.\n this.history.rewrite((snapshot) => ({\n nodes: guarded.length > 0 ? applyNodeChanges(guarded, snapshot.nodes) : snapshot.nodes,\n edges: edges.length > 0 ? applyEdgeChanges(edges, snapshot.edges) : snapshot.edges,\n }))\n // Then hand the batch on with its origin intact: a controlled owner has to\n // see it to keep its own state in step, and the tag is what stops it being\n // sent straight back out.\n this.emit(guarded, this.nodeChangeHandler, false, origin)\n this.emit(edges, this.edgeChangeHandler, false, origin)\n }\n\n // --- undo / redo ---------------------------------------------------------\n\n /** Structural snapshot for history — no selection/hover/drag state. */\n private historySnapshot(): HistorySnapshot {\n const nodes = [...this.nodes.values()].map((node) => {\n const copy = { ...node, position: { ...node.position } }\n if (node.size) copy.size = { ...node.size }\n copy.selected = undefined\n copy.hovered = undefined\n copy.dragging = undefined\n return copy\n })\n const edges = [...this.edges.values()].map((edge) => {\n const copy = { ...edge }\n copy.selected = undefined\n return copy\n })\n return { nodes, edges }\n }\n\n /**\n * Restore a snapshot, emitting the diff so controlled consumers update. Emits\n * with `record: false` so the restore itself isn't re-recorded, and preserves\n * live selection/hover (undo shouldn't churn what's selected).\n */\n private applyHistorySnapshot(snap: HistorySnapshot): void {\n const nodeChanges: NodeChange[] = []\n const snapNodeIds = new Set(snap.nodes.map((node) => node.id))\n for (const id of [...this.nodes.keys()]) {\n if (!snapNodeIds.has(id)) {\n this.dropNodeState(id)\n nodeChanges.push({ type: \"remove\", id })\n }\n }\n for (const node of snap.nodes) {\n const existing = this.nodes.get(node.id)\n const merged = existing\n ? { ...node, selected: existing.selected, hovered: existing.hovered }\n : node\n if (!existing) {\n this.writeNode(node.id, merged)\n nodeChanges.push({ type: \"add\", item: merged })\n } else if (!nodeControlledEqual(existing, merged)) {\n this.writeNode(node.id, merged)\n this.bumpNode(node.id)\n nodeChanges.push({ type: \"replace\", id: node.id, item: merged })\n }\n }\n\n const edgeChanges: EdgeChange[] = []\n const snapEdgeIds = new Set(snap.edges.map((edge) => edge.id))\n for (const id of [...this.edges.keys()]) {\n if (!snapEdgeIds.has(id)) {\n this.edges.delete(id)\n edgeChanges.push({ type: \"remove\", id })\n }\n }\n for (const edge of snap.edges) {\n const existing = this.edges.get(edge.id)\n const merged = existing ? { ...edge, selected: existing.selected } : edge\n this.edges.set(edge.id, merged)\n edgeChanges.push(\n existing ? { type: \"replace\", id: edge.id, item: merged } : { type: \"add\", item: merged },\n )\n }\n if (this.selectedEdgeId && !this.edges.has(this.selectedEdgeId)) this.selectedEdgeId = null\n\n if (edgeChanges.length > 0) this.bumpEdges()\n this.emitNodeChanges(nodeChanges, false)\n this.emitEdgeChanges(edgeChanges, false)\n this.requestRender()\n }\n\n undo = (): boolean => this.history.undo((snap) => this.applyHistorySnapshot(snap))\n redo = (): boolean => this.history.redo((snap) => this.applyHistorySnapshot(snap))\n canUndo = (): boolean => this.history.canUndo()\n canRedo = (): boolean => this.history.canRedo()\n clearHistory = (): void => this.history.clear()\n subscribeHistory = (listener: () => void): (() => void) => this.history.subscribe(listener)\n\n // --- edge labels (renderer ↔ label layer) --------------------------------\n\n getEdgeLabelAnchors = (): Map<EdgeId, Vec2> => this.edgeLabelAnchors\n\n setEdgeLabelAnchors = (anchors: Map<EdgeId, Vec2>): void => {\n this.edgeLabelAnchors = anchors\n }\n\n getPeerEdgeAnchors = (): ReadonlyMap<EdgeId, Vec2> => this.peerEdgeAnchors\n\n setPeerEdgeAnchors = (anchors: ReadonlyMap<EdgeId, Vec2>): void => {\n this.peerEdgeAnchors = anchors\n }\n\n getAlignmentGuides = (): AlignmentGuide[] => this.alignmentGuides\n\n setAlignmentGuides = (guides: AlignmentGuide[]): void => {\n this.alignmentGuides = guides\n this.requestRender()\n }\n\n // --- handle registry -----------------------------------------------------\n\n registerHandle = (record: HandleRecord): void => {\n this.handles.set(handleKey(record.nodeId, record.handleId), record)\n this.requestRender()\n }\n\n unregisterHandle = (nodeId: NodeId, handleId: string): void => {\n this.handles.delete(handleKey(nodeId, handleId))\n this.requestRender()\n }\n\n // --- anchor registry -----------------------------------------------------\n\n /**\n * Measure one anchor against its node element. Returns true when geometry\n * changed beyond tolerance. Bails — keeping the last-known geometry — while\n * the element or node box can't produce a meaningful measurement (detached,\n * display:none, node not yet laid out).\n */\n private measureAnchor(key: string): boolean {\n const record = this.anchors.get(key)\n if (!record?.element?.isConnected) return false\n const element = record.element\n const nodeEl = this.nodeElements.get(record.nodeId)\n if (!nodeEl) return false\n const root = nodeEl.getBoundingClientRect()\n const box = element.getBoundingClientRect()\n if (root.width <= 0 || root.height <= 0 || (box.width <= 0 && box.height <= 0)) return false\n const rects = element.getClientRects()\n const first = rects.item(0) ?? box\n const last = rects.item(rects.length - 1) ?? first\n const geometry = computeAnchorGeometry(root, first, last, box)\n if (anchorGeometryEqual(record.geometry, geometry)) return false\n this.anchors.set(key, { ...record, geometry })\n return true\n }\n\n registerAnchor = (\n nodeId: NodeId,\n anchorId: string,\n element: Element,\n options?: AnchorRegistrationOptions,\n ): void => {\n const key = handleKey(nodeId, anchorId)\n const prev = this.anchors.get(key)\n this.anchors.set(key, {\n nodeId,\n anchorId,\n color: options?.color ?? prev?.color,\n strays: options?.strays ?? prev?.strays,\n selectable: options?.selectable ?? prev?.selectable,\n data: options?.data ?? prev?.data,\n element,\n // Keep the last-known geometry until the next successful measurement, so\n // a re-bind (display remount, editor DOM swap) never blanks the chrome.\n geometry: prev?.geometry ?? null,\n })\n this.measureAnchor(key)\n this.bumpAnchors(nodeId)\n this.requestRender()\n }\n\n detachAnchor = (nodeId: NodeId, anchorId: string): void => {\n const key = handleKey(nodeId, anchorId)\n const record = this.anchors.get(key)\n if (!record || record.element === null) return\n this.anchors.set(key, { ...record, element: null })\n this.bumpAnchors(nodeId)\n }\n\n unregisterAnchor = (nodeId: NodeId, anchorId: string): void => {\n if (!this.anchors.delete(handleKey(nodeId, anchorId))) return\n // Selection is view state over the registry, so it can't outlive the record\n // it points at. Detaching deliberately doesn't clear it — the anchor still\n // exists, its display is just gone for the moment.\n this.dropSelectedAnchors((ref) => ref.nodeId === nodeId && ref.anchorId === anchorId)\n this.bumpAnchors(nodeId)\n this.requestRender()\n }\n\n remeasureAnchors = (nodeId: NodeId): void => {\n let changed = false\n for (const [key, record] of this.anchors) {\n if (record.nodeId === nodeId && this.measureAnchor(key)) changed = true\n }\n if (changed) {\n this.bumpAnchors(nodeId)\n this.requestRender()\n }\n }\n\n getNodeAnchors = (nodeId: NodeId): AnchorRecord[] => {\n const records: AnchorRecord[] = []\n for (const record of this.anchors.values()) {\n if (record.nodeId === nodeId) records.push(record)\n }\n return records\n }\n\n getNodeAnchorsVersion = (nodeId: NodeId): number => this.anchorVersions.get(nodeId) ?? 0\n\n getSelectedAnchors = (): readonly AnchorRef[] => {\n if (this.selectedAnchorsStale) {\n this.selectedAnchorsStale = false\n this.selectedAnchorSnapshot = [...this.selectedAnchors.values()]\n }\n return this.selectedAnchorSnapshot\n }\n\n setSelectedAnchors = (refs: readonly AnchorRef[]): void => {\n const next = new Map<string, AnchorRef>()\n for (const ref of refs) next.set(handleKey(ref.nodeId, ref.anchorId), ref)\n if (\n next.size === this.selectedAnchors.size &&\n [...next.keys()].every((key) => this.selectedAnchors.has(key))\n ) {\n return\n }\n // Selecting an anchor is selecting *something*, so the graph selection goes.\n // Routed through the public mutators so their own bookkeeping runs (the\n // marquee box, node/edge exclusivity). They clear anchors in turn, so the\n // map is emptied first and assigned after — their drop finds nothing to do\n // and no listener sees a transient empty selection.\n const clearsGraph =\n next.size > 0 && (this.selectedNodeIds.size > 0 || this.selectedEdgeId !== null)\n this.selectedAnchors = new Map()\n if (clearsGraph) {\n this.selectNode(null)\n this.selectEdge(null)\n }\n this.selectedAnchors = next\n this.selectedAnchorsStale = true\n for (const listener of this.anchorSelectionListeners) listener()\n this.requestRender()\n }\n\n isAnchorSelected = (nodeId: NodeId, anchorId: string): boolean =>\n this.selectedAnchors.has(handleKey(nodeId, anchorId))\n\n subscribeAnchorSelection = (listener: () => void): (() => void) => {\n this.anchorSelectionListeners.add(listener)\n return () => {\n this.anchorSelectionListeners.delete(listener)\n }\n }\n\n /** Drop every selected anchor the predicate claims. No-op when none match. */\n private dropSelectedAnchors(matches: (ref: AnchorRef) => boolean): void {\n if (this.selectedAnchors.size === 0) return\n let changed = false\n for (const [key, ref] of this.selectedAnchors) {\n if (!matches(ref)) continue\n this.selectedAnchors.delete(key)\n changed = true\n }\n if (!changed) return\n this.selectedAnchorsStale = true\n for (const listener of this.anchorSelectionListeners) listener()\n this.requestRender()\n }\n\n subscribeNodeAnchors = (nodeId: NodeId, listener: () => void): (() => void) => {\n let set = this.anchorListeners.get(nodeId)\n if (!set) {\n set = new Set()\n this.anchorListeners.set(nodeId, set)\n }\n set.add(listener)\n return () => {\n set.delete(listener)\n if (set.size === 0) this.anchorListeners.delete(nodeId)\n }\n }\n\n getEdgesVersion = (): number => this.edgesVersion\n\n subscribeEdges = (listener: () => void): (() => void) => {\n this.edgesListeners.add(listener)\n return () => {\n this.edgesListeners.delete(listener)\n }\n }\n\n // --- in-progress connection ----------------------------------------------\n\n getPending = (): PendingConnection | null => this.pending\n\n beginConnection = (next: PendingConnection): void => {\n this.pending = next\n this.requestRender()\n this.notifyConnection()\n }\n\n updateConnection = (to: Vec2, toPosition?: HandlePosition): void => {\n if (!this.pending) return\n this.pending = { ...this.pending, to, toPosition }\n this.requestRender()\n this.notifyConnection()\n }\n\n endConnection = (): void => {\n if (!this.pending) return\n this.pending = null\n this.requestRender()\n this.notifyConnection()\n }\n\n subscribeConnection = (listener: () => void): (() => void) => {\n this.connectionListeners.add(listener)\n return () => {\n this.connectionListeners.delete(listener)\n }\n }\n\n private notifyConnection(): void {\n for (const listener of this.connectionListeners) listener()\n }\n\n // --- render loop hook ----------------------------------------------------\n\n requestRender = (): void => {\n this.renderRequester()\n }\n\n bindRenderRequester = (fn: () => void): void => {\n this.renderRequester = fn\n }\n\n requestCursorRender = (): void => {\n if (this.cursorRenderRequester) this.cursorRenderRequester()\n else this.renderRequester()\n }\n\n bindCursorRenderRequester = (fn: (() => void) | null): void => {\n this.cursorRenderRequester = fn\n }\n\n // --- reconnect gateway (runtime-bound; consulted by <Handle>) ------------\n\n private reconnectDelegate: ReconnectDelegate | null = null\n\n getSelectedEdge = (): EdgeId | null => this.selectedEdgeId\n\n bindReconnectDelegate = (delegate: ReconnectDelegate | null): void => {\n this.reconnectDelegate = delegate\n }\n\n getReconnectDelegate = (): ReconnectDelegate | null => this.reconnectDelegate\n}\n\n/** Create a graph store. The public entry point; the class is an implementation detail. */\nexport function createRivetStore(init: RivetStoreInit): RivetStore {\n return new RivetGraphStore(init)\n}\n","import type { RefObject } from \"react\"\nimport { SELECTOR } from \"./constants\"\nimport type { RivetStore } from \"./store\"\nimport { handleKey } from \"./store\"\nimport type { Connection, HandlePosition, HandleType, NodeId, Vec2 } from \"./types\"\nimport { screenToWorld } from \"./viewport\"\n\n/** A resolved handle the pointer is over (or nearest on a hovered node). */\nexport type HandleHit = { nodeId: NodeId; handleId: string; type: HandleType }\n\n/** The fixed end a connection (or reconnection) is dragging from. */\nexport type ConnectionEnd = { nodeId: NodeId; handleId: string; type: HandleType }\n\n/** Convert a client (page) point to world coordinates via the pane rect + viewport. */\nexport function clientToWorld(\n store: RivetStore,\n paneRef: RefObject<HTMLElement | null>,\n clientX: number,\n clientY: number,\n): Vec2 {\n const rect = paneRef.current?.getBoundingClientRect()\n const point = { x: clientX - (rect?.left ?? 0), y: clientY - (rect?.top ?? 0) }\n return screenToWorld(point, store.getViewport())\n}\n\n/**\n * A pair is valid when one end can source and the other can target (\"either\" does\n * both). `from` is the end being dragged; `hit` is the candidate it may attach to.\n */\nexport function isCompatible(from: ConnectionEnd, hit: HandleHit): boolean {\n const canSource = from.type !== \"target\"\n const canTarget = from.type !== \"source\"\n return (\n hit.nodeId !== from.nodeId &&\n ((canSource && hit.type !== \"source\") || (canTarget && hit.type !== \"target\"))\n )\n}\n\n/** Resolve the handle element under a screen point via the DOM. */\nexport function findHandleAt(clientX: number, clientY: number): HandleHit | null {\n const element = document.elementFromPoint(clientX, clientY)\n const handleEl = element instanceof Element ? element.closest<HTMLElement>(SELECTOR.handle) : null\n if (!handleEl) return null\n const { rivetHandleNode, rivetHandleId, rivetHandleType } = handleEl.dataset\n if (!rivetHandleNode || !rivetHandleId || !rivetHandleType) return null\n return {\n nodeId: rivetHandleNode,\n handleId: rivetHandleId,\n type: rivetHandleType as HandleType,\n }\n}\n\n/** World position of a handle by hit, or null if the node/handle is gone. */\nexport function handleWorldPosition(store: RivetStore, hit: HandleHit): Vec2 | null {\n const record = store.handles.get(handleKey(hit.nodeId, hit.handleId))\n const node = store.nodes.get(hit.nodeId)\n if (!record || !node) return null\n const origin = store.getNodeWorldPosition(hit.nodeId)\n return { x: origin.x + record.offset.x, y: origin.y + record.offset.y }\n}\n\n/** The side a handle sits on (for facing a snapped pending connection), or null. */\nexport function handleSide(store: RivetStore, hit: HandleHit): HandlePosition | null {\n return store.handles.get(handleKey(hit.nodeId, hit.handleId))?.position ?? null\n}\n\n/**\n * Resolve what the dragged end should snap to: a compatible handle directly under\n * the pointer, else — while over another node — that node's nearest compatible\n * handle. Returns null when nothing valid is under the pointer.\n */\nexport function resolveConnectionHit(\n store: RivetStore,\n paneRef: RefObject<HTMLElement | null>,\n from: ConnectionEnd,\n clientX: number,\n clientY: number,\n): HandleHit | null {\n const direct = findHandleAt(clientX, clientY)\n if (direct && isCompatible(from, direct)) return direct\n\n const el = document.elementFromPoint(clientX, clientY)\n const nodeEl = el instanceof Element ? el.closest<HTMLElement>(SELECTOR.node) : null\n const overNodeId = nodeEl?.dataset.rivetNode\n if (!overNodeId || overNodeId === from.nodeId) return null\n\n const world = clientToWorld(store, paneRef, clientX, clientY)\n let best: HandleHit | null = null\n let bestDist = Number.POSITIVE_INFINITY\n for (const record of store.handles.values()) {\n if (record.nodeId !== overNodeId) continue\n const candidate: HandleHit = {\n nodeId: record.nodeId,\n handleId: record.handleId,\n type: record.type,\n }\n if (!isCompatible(from, candidate)) continue\n const node = store.nodes.get(record.nodeId)\n if (!node) continue\n const origin = store.getNodeWorldPosition(record.nodeId)\n const dx = origin.x + record.offset.x - world.x\n const dy = origin.y + record.offset.y - world.y\n const dist = dx * dx + dy * dy\n if (dist < bestDist) {\n bestDist = dist\n best = candidate\n }\n }\n return best\n}\n\n/**\n * Orient an edge between the dragged end and the hit: whichever end can source\n * into the other becomes the source. Mirrors the rule in {@link isCompatible}.\n */\nexport function orientConnection(from: ConnectionEnd, hit: HandleHit): Connection {\n const canSource = from.type !== \"target\"\n const draggedAsSource = canSource && hit.type !== \"source\"\n return draggedAsSource\n ? {\n source: from.nodeId,\n sourceHandle: from.handleId,\n target: hit.nodeId,\n targetHandle: hit.handleId,\n }\n : {\n source: hit.nodeId,\n sourceHandle: hit.handleId,\n target: from.nodeId,\n targetHandle: from.handleId,\n }\n}\n","import type { RefObject } from \"react\"\nimport {\n type ConnectionEnd,\n clientToWorld,\n type HandleHit,\n handleSide,\n handleWorldPosition,\n orientConnection,\n resolveConnectionHit,\n} from \"../connection\"\nimport type { RivetStore } from \"../store\"\nimport type { Connection, PendingConnection } from \"../types\"\n\n/**\n * Resolve the target handle under a screen point. Defaults to the DOM hit-test\n * ({@link resolveConnectionHit}); injectable so a test can drive the gesture's\n * commit/veto logic without a real layout (jsdom can't `elementFromPoint`).\n */\nexport type ResolveHit = (\n store: RivetStore,\n paneRef: RefObject<HTMLElement | null>,\n from: ConnectionEnd,\n clientX: number,\n clientY: number,\n) => HandleHit | null\n\nexport type ConnectionDragConfig = {\n store: RivetStore\n paneRef: RefObject<HTMLElement | null>\n /** The fixed end the drag pivots from (source of a new edge, or an edge's kept end). */\n from: ConnectionEnd\n /** Payload that seeds the store's pending connection (the source seed, or the reconnect ends). */\n begin: PendingConnection\n /** Apply a valid dropped connection — add a fresh edge, or re-point an existing one. */\n commit: (connection: Connection) => void\n /** Veto a proposed connection on drop. Absent ⇒ every drop is valid. */\n validate?: (connection: Connection) => boolean\n /**\n * Rewrite a validated connection before it commits — normalize handle ids,\n * force direction conventions, redirect to a canonical handle. Returning\n * `null` cancels the drop. Runs after {@link validate} (which sees the raw\n * connection) and before {@link commit}.\n */\n map?: (connection: Connection) => Connection | null\n /** Runs once the drag ends — on drop, on a miss, and on cancel. */\n onEnd?: () => void\n /** Resolve the target under the pointer. Defaults to the DOM hit-test; injected in tests. */\n resolveHit?: ResolveHit\n}\n\n/**\n * Drive a connection drag to completion: seed the pending connection, follow the\n * cursor (snapping the preview to a compatible handle), and on release commit the\n * oriented connection when it lands on a valid target. Self-cleaning — it removes\n * its own `window` listeners on pointerup/pointercancel. One implementation backs\n * both starting a new connection from a `<Handle>` and reconnecting an edge's\n * endpoint; the two differ only in `begin`, `commit`, `validate`, and `onEnd`.\n */\nexport function startConnectionDrag(config: ConnectionDragConfig): void {\n const {\n store,\n paneRef,\n from,\n begin,\n commit,\n validate,\n map,\n onEnd,\n resolveHit: resolveHitInput = resolveConnectionHit,\n } = config\n\n // Connecting a locked node is allowed by default — a lock claims the node,\n // not the graph around it — so this only bites when a policy says otherwise.\n if (!store.locks.allows(from.nodeId, \"connect\")) {\n onEnd?.()\n return\n }\n\n // A refused target reads as no target at all, which is exactly right for both\n // readers: the preview stops snapping to it, and the drop finds nothing to\n // commit. One wrap covers the move and the release.\n const resolveHit: ResolveHit = (...args) => {\n const hit = resolveHitInput(...args)\n if (hit && !store.locks.allows(hit.nodeId, \"connect\")) return null\n return hit\n }\n\n store.beginConnection(begin)\n\n const onMove = (event: PointerEvent) => {\n const hit = resolveHit(store, paneRef, from, event.clientX, event.clientY)\n const snapped = hit && handleWorldPosition(store, hit)\n store.updateConnection(\n snapped ?? clientToWorld(store, paneRef, event.clientX, event.clientY),\n snapped && hit ? (handleSide(store, hit) ?? undefined) : undefined,\n )\n }\n\n const detach = () => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n window.removeEventListener(\"pointercancel\", onCancel)\n }\n\n const onUp = (event: PointerEvent) => {\n detach()\n // Escape cleared the pending connection mid-drag (see input/keyboard) —\n // the gesture was cancelled, so the release must not commit.\n if (!store.getPending()) {\n onEnd?.()\n return\n }\n const hit = resolveHit(store, paneRef, from, event.clientX, event.clientY)\n if (hit) {\n const connection = orientConnection(from, hit)\n if (!validate || validate(connection)) {\n const mapped = map ? map(connection) : connection\n if (mapped) commit(mapped)\n }\n }\n onEnd?.()\n store.endConnection()\n }\n\n // A cancelled pointer (interrupted touch, browser-stolen capture) aborts without\n // committing — but still tears down and clears the preview so no ghost edge lingers.\n const onCancel = () => {\n detach()\n onEnd?.()\n store.endConnection()\n }\n\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n window.addEventListener(\"pointercancel\", onCancel)\n}\n","import { createId } from \"@rivet/utils\"\nimport {\n type CSSProperties,\n type KeyboardEvent as ReactKeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useEffect,\n useRef,\n} from \"react\"\nimport {\n type ConnectionEnd,\n clientToWorld,\n type HandleHit,\n handleWorldPosition,\n isCompatible,\n orientConnection,\n} from \"../connection\"\nimport { useRivetContext, useRivetNodeContext } from \"../context\"\nimport { startConnectionDrag } from \"../input/connection-drag\"\nimport type { HandlePosition, HandleType, NodeId } from \"../types\"\n\nconst SIZE = 10\n\nconst positionStyles: Record<HandlePosition, CSSProperties> = {\n right: { right: 0, top: \"50%\", transform: \"translate(50%, -50%)\" },\n left: { left: 0, top: \"50%\", transform: \"translate(-50%, -50%)\" },\n top: { top: 0, left: \"50%\", transform: \"translate(-50%, -50%)\" },\n bottom: { bottom: 0, left: \"50%\", transform: \"translate(-50%, 50%)\" },\n}\n\nexport type HandleProps = {\n /**\n * Whether this handle is a connection `source` or `target`. Optional — an\n * untyped handle resolves to `\"either\"` and can start or receive a\n * connection; a pair is valid when one end can source and the other can\n * target. Set an explicit type to constrain direction.\n */\n type?: HandleType\n /**\n * Distinguishes multiple handles on a node. Defaults to the resolved\n * `position`, since each side of a node is unique. Set an explicit `id` when a\n * node has several handles sharing one side.\n */\n id?: string\n position?: HandlePosition\n className?: string\n style?: CSSProperties\n /**\n * Accessible name for the handle. Defaults to naming the handle and its node\n * (e.g. `\"right handle of node a\"`) so a keyboard user tabbing across the\n * graph can tell same-sided handles on different nodes apart.\n */\n ariaLabel?: string\n}\n\n/**\n * A connection point placed inside a node component. It measures its own\n * position within the node (so edges anchor precisely) and starts a\n * drag-to-connect gesture.\n */\nexport function Handle({\n type,\n id,\n position,\n className,\n style,\n ariaLabel,\n}: HandleProps): React.ReactElement {\n const { store, paneRef, isValidConnection, mapConnection, onConnect, announce } =\n useRivetContext()\n const { nodeId, wrapperRef } = useRivetNodeContext()\n const ref = useRef<HTMLDivElement>(null)\n // Type is optional; an untyped handle is \"either\" (source or target). It's keyed\n // by position when untyped so several handles on one node stay distinct.\n const resolvedType: HandleType = type ?? \"either\"\n const place = position ?? (resolvedType === \"target\" ? \"left\" : \"right\")\n // Default to position, not type: a node commonly has several same-typed (or\n // untyped \"either\") handles, one per side, so keying by type collides them all\n // onto one registry entry. Position keeps each side distinct.\n const handleId = id ?? place\n\n // Measure and register the handle's world-space offset within its node.\n // getBoundingClientRect is post-transform, so divide by zoom to get world units.\n useEffect(() => {\n const el = ref.current\n const wrapper = wrapperRef.current\n if (!el || !wrapper) return\n\n const measure = () => {\n const zoom = store.getViewport().zoom || 1\n const hr = el.getBoundingClientRect()\n const wr = wrapper.getBoundingClientRect()\n store.registerHandle({\n nodeId,\n handleId,\n type: resolvedType,\n position: place,\n offset: {\n x: (hr.left + hr.width / 2 - wr.left) / zoom,\n y: (hr.top + hr.height / 2 - wr.top) / zoom,\n },\n })\n }\n\n measure()\n const observer = new ResizeObserver(measure)\n observer.observe(wrapper)\n observer.observe(el)\n return () => {\n observer.disconnect()\n store.unregisterHandle(nodeId, handleId)\n }\n }, [store, wrapperRef, nodeId, handleId, resolvedType, place])\n\n const nodeName = (id: NodeId) => store.nodes.get(id)?.ariaLabel ?? `node ${id}`\n\n // Keyboard connect: Enter/Space on a handle starts a pending connection from\n // it; Enter/Space on a compatible handle of another node completes the edge\n // (same validate → map → commit pipeline as the pointer drag); Enter on the\n // origin handle — or Escape anywhere — cancels.\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.key === \"Escape\") {\n if (!store.getPending()) return\n event.preventDefault()\n event.stopPropagation() // handled — the node wrapper must not also clear selection\n store.endConnection()\n announce(\"Connection cancelled.\")\n return\n }\n if (event.key !== \"Enter\" && event.key !== \" \") return\n event.preventDefault()\n\n const self: HandleHit = { nodeId, handleId, type: resolvedType }\n // Same refusal the pointer drag applies at both ends, and for the same\n // reason: only a consumer policy ever turns this on.\n if (!store.locks.allows(nodeId, \"connect\")) {\n announce(`${nodeName(nodeId)} is locked by someone else.`)\n return\n }\n const pending = store.getPending()\n if (!pending) {\n const origin = handleWorldPosition(store, self)\n if (!origin) return\n store.beginConnection({\n source: nodeId,\n sourceHandle: handleId,\n sourceType: resolvedType,\n from: origin,\n to: origin,\n })\n announce(\n `Connection started from ${nodeName(nodeId)}. Move focus to a handle on another node and press Enter to connect, or press Escape to cancel.`,\n )\n return\n }\n if (pending.source === nodeId && pending.sourceHandle === handleId) {\n store.endConnection()\n announce(\"Connection cancelled.\")\n return\n }\n\n const from: ConnectionEnd = {\n nodeId: pending.source,\n handleId: pending.sourceHandle,\n type: pending.sourceType,\n }\n // Invalid targets keep the pending connection alive so the user can move\n // on to another handle; only success, cancel, or a consumer veto end it.\n if (!isCompatible(from, self)) {\n announce(\"These handles cannot be connected.\")\n return\n }\n const connection = orientConnection(from, self)\n if (isValidConnection && !isValidConnection(connection)) {\n announce(\"Connection rejected.\")\n return\n }\n const mapped = mapConnection ? mapConnection(connection) : connection\n if (mapped) {\n store.addEdge({\n id: createId(\"edge\"),\n source: mapped.source,\n target: mapped.target,\n sourceHandle: mapped.sourceHandle ?? undefined,\n targetHandle: mapped.targetHandle ?? undefined,\n })\n onConnect?.(mapped)\n announce(`Connected ${nodeName(mapped.source)} to ${nodeName(mapped.target)}.`)\n }\n store.endConnection()\n }\n\n // While a connection is pending, focusing a handle previews the edge landing\n // on it — the keyboard analogue of the pointer drag's snap-to-handle.\n const onFocus = () => {\n const pending = store.getPending()\n if (!pending || (pending.source === nodeId && pending.sourceHandle === handleId)) return\n // Don't preview an edge landing where Enter would be refused.\n if (!store.locks.allows(nodeId, \"connect\")) return\n const world = handleWorldPosition(store, { nodeId, handleId, type: resolvedType })\n if (world) store.updateConnection(world, place)\n }\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n // Don't let this start a node drag (React-to-React stopPropagation works).\n event.stopPropagation()\n event.preventDefault()\n\n // A reconnectable edge ending here wins over starting a new connection —\n // the handle's DOM otherwise shadows the endpoint's grab zone entirely.\n // Alt forces a new connection from an occupied handle.\n if (!event.altKey) {\n const delegate = store.getReconnectDelegate()\n const endpointHit = delegate?.pickEndpoint(event.clientX, event.clientY)\n if (delegate && endpointHit) {\n delegate.begin(endpointHit.edgeId, endpointHit.end)\n return\n }\n }\n\n const from: ConnectionEnd = { nodeId, handleId, type: resolvedType }\n const start = handleWorldPosition(store, from)\n const origin = start ?? clientToWorld(store, paneRef, event.clientX, event.clientY)\n startConnectionDrag({\n store,\n paneRef,\n from,\n begin: {\n source: nodeId,\n sourceHandle: handleId,\n sourceType: resolvedType,\n from: origin,\n to: origin,\n },\n validate: isValidConnection,\n map: mapConnection,\n commit: (connection) => {\n store.addEdge({\n id: createId(\"edge\"),\n source: connection.source,\n target: connection.target,\n sourceHandle: connection.sourceHandle ?? undefined,\n targetHandle: connection.targetHandle ?? undefined,\n })\n onConnect?.(connection)\n },\n })\n }\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: the handle doubles as a drag affordance and measurement target, so it can't be a native <button>\n <div\n ref={ref}\n className={className}\n tabIndex={0}\n role=\"button\"\n aria-roledescription=\"connection handle\"\n aria-label={ariaLabel ?? `${handleId} handle of ${nodeName(nodeId)}`}\n onPointerDown={onPointerDown}\n onKeyDown={onKeyDown}\n onFocus={onFocus}\n data-rivet-handle=\"\"\n data-rivet-handle-node={nodeId}\n data-rivet-handle-id={handleId}\n data-rivet-handle-type={resolvedType}\n style={{\n position: \"absolute\",\n width: SIZE,\n height: SIZE,\n borderRadius: \"50%\",\n background: \"#ffffff\",\n border: \"1.5px solid #6366f1\",\n boxSizing: \"border-box\",\n pointerEvents: \"auto\",\n cursor: \"crosshair\",\n zIndex: 1,\n ...positionStyles[place],\n ...style,\n }}\n />\n )\n}\n","import type { CSSProperties } from \"react\"\nimport type { NodeProps } from \"../types\"\nimport { Handle } from \"./handle\"\n\nconst baseStyle: CSSProperties = {\n position: \"relative\",\n minWidth: 120,\n padding: \"10px 14px\",\n borderRadius: 8,\n // Longhand, not the `border` shorthand: the hover/selected styles below\n // override `borderColor` alone, and React warns when a shorthand and a\n // longhand for the same value are mixed across renders.\n borderWidth: 1,\n borderStyle: \"solid\",\n borderColor: \"rgba(100, 116, 139, 0.4)\",\n background: \"#ffffff\",\n color: \"#0f172a\",\n fontSize: 13,\n lineHeight: 1.3,\n boxShadow: \"0 1px 2px rgba(15, 23, 42, 0.08)\",\n}\n\nconst hoveredStyle: CSSProperties = {\n borderColor: \"rgba(99, 102, 241, 0.6)\",\n}\n\nconst selectedStyle: CSSProperties = {\n borderColor: \"#6366f1\",\n boxShadow: \"0 0 0 2px rgba(99, 102, 241, 0.35)\",\n}\n\n/** Fallback node used when a node's `type` has no entry in `nodeTypes`. */\nexport function DefaultNode({ data, selected, hovered }: NodeProps): React.ReactElement {\n const label = data && typeof data === \"object\" && \"label\" in data ? String(data.label) : \"Node\"\n // Selected wins over hover.\n const style = selected\n ? { ...baseStyle, ...selectedStyle }\n : hovered\n ? { ...baseStyle, ...hoveredStyle }\n : baseStyle\n return (\n <div style={style}>\n <Handle type=\"target\" position=\"left\" />\n {label}\n <Handle type=\"source\" position=\"right\" />\n </div>\n )\n}\n","import type { CSSProperties } from \"react\"\nimport type { NodeProps, NodeTypes } from \"../types\"\nimport { DefaultNode } from \"./default-node\"\n\nconst baseStyle: CSSProperties = {\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n // Keeps an unsized group visible; give real bounds via `width`/`height`.\n minWidth: 150,\n minHeight: 100,\n boxSizing: \"border-box\",\n borderRadius: 10,\n // Longhand — see the note in `default-node.tsx`.\n borderWidth: 1.5,\n borderStyle: \"dashed\",\n borderColor: \"rgba(100, 116, 139, 0.45)\",\n background: \"rgba(100, 116, 139, 0.06)\",\n}\n\nconst hoveredStyle: CSSProperties = {\n borderColor: \"rgba(99, 102, 241, 0.6)\",\n}\n\nconst selectedStyle: CSSProperties = {\n borderColor: \"#6366f1\",\n background: \"rgba(99, 102, 241, 0.08)\",\n}\n\nconst labelStyle: CSSProperties = {\n position: \"absolute\",\n top: 6,\n left: 10,\n fontSize: 11,\n fontWeight: 500,\n color: \"rgba(100, 116, 139, 0.9)\",\n pointerEvents: \"none\",\n userSelect: \"none\",\n}\n\n/**\n * Built-in container node (`type: \"group\"`) — the visual basis for sub-flows.\n * A styled region with no content or handles of its own; children point at it\n * via `parentId` (and `extent: \"parent\"` to stay confined). Give it explicit\n * `width`/`height` — a group has no intrinsic content to measure. Children\n * render above it automatically (z-index follows nesting depth).\n */\nexport function GroupNode({ data, selected, hovered }: NodeProps): React.ReactElement {\n const label = data && typeof data === \"object\" && \"label\" in data ? String(data.label) : null\n // Selected wins over hover.\n const style = selected\n ? { ...baseStyle, ...selectedStyle }\n : hovered\n ? { ...baseStyle, ...hoveredStyle }\n : baseStyle\n return <div style={style}>{label !== null && <div style={labelStyle}>{label}</div>}</div>\n}\n\n/** The built-in node components, keyed by `type`. Consumer `nodeTypes` win. */\nexport const BUILTIN_NODE_TYPES: NodeTypes = {\n default: DefaultNode,\n group: GroupNode,\n}\n","import {\n type CSSProperties,\n type PointerEvent as ReactPointerEvent,\n useEffect,\n useRef,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport { visibleWorldRect } from \"../viewport\"\n\nconst MAP_PADDING = 8\n\nconst containerStyle: CSSProperties = {\n position: \"absolute\",\n bottom: 16,\n right: 16,\n borderRadius: 8,\n overflow: \"hidden\",\n border: \"1px solid rgba(100, 116, 139, 0.4)\",\n background: \"rgba(248, 250, 252, 0.9)\",\n boxShadow: \"0 1px 3px rgba(15, 23, 42, 0.12)\",\n cursor: \"pointer\",\n}\n\nexport type MiniMapProps = {\n width?: number\n height?: number\n nodeColor?: string\n selectedColor?: string\n /** Fill for the area outside the current viewport. */\n maskColor?: string\n className?: string\n style?: CSSProperties\n}\n\n/**\n * An overview of the whole graph with a viewport indicator. Redraws on every\n * canvas frame (via the store's frame channel) and recenters on click/drag.\n * Must be a child of `<Rivet>`.\n */\nexport function MiniMap({\n width = 200,\n height = 150,\n nodeColor = \"rgba(100, 116, 139, 0.7)\",\n selectedColor = \"#6366f1\",\n maskColor = \"rgba(15, 23, 42, 0.12)\",\n className,\n style,\n}: MiniMapProps): React.ReactElement {\n const { store, paneRef } = useRivetContext()\n const canvasRef = useRef<HTMLCanvasElement>(null)\n // Last frame's world→map transform, so pointer events can invert it.\n const transformRef = useRef({ scale: 1, offsetX: 0, offsetY: 0 })\n\n useEffect(() => {\n const canvas = canvasRef.current\n const ctx = canvas?.getContext(\"2d\")\n if (!canvas || !ctx) return\n\n const dpr = window.devicePixelRatio || 1\n canvas.width = Math.round(width * dpr)\n canvas.height = Math.round(height * dpr)\n\n const draw = () => {\n const viewport = store.getViewport()\n const pane = paneRef.current\n const paneWidth = pane?.clientWidth ?? width\n const paneHeight = pane?.clientHeight ?? height\n const view = visibleWorldRect(viewport, paneWidth, paneHeight)\n\n // Fit the union of all node rects (world-space, parent chains resolved) and\n // the current viewport into the map.\n let minX = view.x\n let minY = view.y\n let maxX = view.x + view.width\n let maxY = view.y + view.height\n for (const id of store.nodes.keys()) {\n const box = store.getNodeRect(id)\n minX = Math.min(minX, box.x)\n minY = Math.min(minY, box.y)\n maxX = Math.max(maxX, box.x + box.width)\n maxY = Math.max(maxY, box.y + box.height)\n }\n\n const boundsWidth = maxX - minX || 1\n const boundsHeight = maxY - minY || 1\n const innerWidth = width - MAP_PADDING * 2\n const innerHeight = height - MAP_PADDING * 2\n const scale = Math.min(innerWidth / boundsWidth, innerHeight / boundsHeight)\n const offsetX = MAP_PADDING + (innerWidth - boundsWidth * scale) / 2 - minX * scale\n const offsetY = MAP_PADDING + (innerHeight - boundsHeight * scale) / 2 - minY * scale\n transformRef.current = { scale, offsetX, offsetY }\n\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0)\n ctx.clearRect(0, 0, width, height)\n\n // Nodes.\n for (const node of store.nodes.values()) {\n const box = store.getNodeRect(node.id)\n ctx.fillStyle = node.selected ? selectedColor : nodeColor\n ctx.fillRect(\n box.x * scale + offsetX,\n box.y * scale + offsetY,\n Math.max(1, box.width * scale),\n Math.max(1, box.height * scale),\n )\n }\n\n // Viewport indicator: mask everything outside the visible rect.\n const vx = view.x * scale + offsetX\n const vy = view.y * scale + offsetY\n const vw = view.width * scale\n const vh = view.height * scale\n ctx.fillStyle = maskColor\n ctx.beginPath()\n ctx.rect(0, 0, width, height)\n ctx.rect(vx, vy, vw, vh)\n ctx.fill(\"evenodd\")\n ctx.strokeStyle = \"rgba(99, 102, 241, 0.9)\"\n ctx.lineWidth = 1\n ctx.strokeRect(vx, vy, vw, vh)\n }\n\n draw()\n return store.subscribeFrame(draw)\n }, [store, paneRef, width, height, nodeColor, selectedColor, maskColor])\n\n // Recenter the viewport on the clicked/dragged world point.\n const recenter = (event: ReactPointerEvent<HTMLCanvasElement>) => {\n const canvas = canvasRef.current\n const pane = paneRef.current\n if (!canvas || !pane) return\n const rect = canvas.getBoundingClientRect()\n const { scale, offsetX, offsetY } = transformRef.current\n const worldX = (event.clientX - rect.left - offsetX) / scale\n const worldY = (event.clientY - rect.top - offsetY) / scale\n const viewport = store.getViewport()\n store.setViewport({\n zoom: viewport.zoom,\n x: pane.clientWidth / 2 - worldX * viewport.zoom,\n y: pane.clientHeight / 2 - worldY * viewport.zoom,\n })\n store.requestRender()\n }\n\n const onPointerDown = (event: ReactPointerEvent<HTMLCanvasElement>) => {\n if (event.button !== 0) return\n event.currentTarget.setPointerCapture(event.pointerId)\n recenter(event)\n }\n const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {\n if (event.buttons & 1) recenter(event)\n }\n\n return (\n <div className={className} style={{ ...containerStyle, ...style, width, height }}>\n <canvas\n ref={canvasRef}\n style={{ width, height, display: \"block\" }}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n />\n </div>\n )\n}\n","import { clamp } from \"@rivet/utils\"\nimport {\n type CSSProperties,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useSyncExternalStore,\n} from \"react\"\nimport { useRivetContext, useRivetNodeContext } from \"../context\"\nimport type { Size, Vec2 } from \"../types\"\n\n/** Which edges a resize handle moves. */\ntype HandleDir = {\n key: string\n left?: boolean\n right?: boolean\n top?: boolean\n bottom?: boolean\n style: CSSProperties\n cursor: string\n}\n\nconst NS = \"ns-resize\"\nconst EW = \"ew-resize\"\nconst NWSE = \"nwse-resize\"\nconst NESW = \"nesw-resize\"\n\nconst HANDLES: HandleDir[] = [\n { key: \"nw\", top: true, left: true, style: { top: 0, left: 0 }, cursor: NWSE },\n { key: \"n\", top: true, style: { top: 0, left: \"50%\" }, cursor: NS },\n { key: \"ne\", top: true, right: true, style: { top: 0, left: \"100%\" }, cursor: NESW },\n { key: \"e\", right: true, style: { top: \"50%\", left: \"100%\" }, cursor: EW },\n { key: \"se\", bottom: true, right: true, style: { top: \"100%\", left: \"100%\" }, cursor: NWSE },\n { key: \"s\", bottom: true, style: { top: \"100%\", left: \"50%\" }, cursor: NS },\n { key: \"sw\", bottom: true, left: true, style: { top: \"100%\", left: 0 }, cursor: NESW },\n { key: \"w\", left: true, style: { top: \"50%\", left: 0 }, cursor: EW },\n]\n\nexport type NodeResizerProps = {\n minWidth?: number\n minHeight?: number\n maxWidth?: number\n maxHeight?: number\n /** Lock the width/height ratio while resizing from a corner. */\n keepAspectRatio?: boolean\n /** Handle color. */\n color?: string\n /** Called on every resize step (live). */\n onResize?: (size: Size, position: Vec2) => void\n /** Called once when the resize gesture ends. */\n onResizeEnd?: (size: Size, position: Vec2) => void\n}\n\nconst dotStyle = (color: string): CSSProperties => ({\n position: \"absolute\",\n width: 8,\n height: 8,\n background: \"#ffffff\",\n border: `1.5px solid ${color}`,\n borderRadius: 2,\n boxSizing: \"border-box\",\n pointerEvents: \"auto\",\n zIndex: 2,\n})\n\n/**\n * Drop inside a node component to make it resizable. Renders eight drag handles\n * that write the node's explicit `width`/`height` (and move its origin for\n * top/left handles) via {@link RivetStore.resizeNode} — so it works with\n * controlled mode (emits dimension changes) and nested nodes alike.\n */\nexport function NodeResizer({\n minWidth = 20,\n minHeight = 20,\n maxWidth = Number.POSITIVE_INFINITY,\n maxHeight = Number.POSITIVE_INFINITY,\n keepAspectRatio = false,\n color = \"#6366f1\",\n onResize,\n onResizeEnd,\n}: NodeResizerProps): React.ReactElement | null {\n const { store } = useRivetContext()\n const { nodeId } = useRivetNodeContext()\n // A peer's lock hides the handles outright rather than letting them be\n // pressed and refused — a resize dot you can't pull is worse than no dot.\n const resizable = useSyncExternalStore(\n store.locks.subscribe,\n useCallback(() => store.locks.allows(nodeId, \"resize\"), [store, nodeId]),\n useCallback(() => store.locks.allows(nodeId, \"resize\"), [store, nodeId]),\n )\n\n const startResize = (dir: HandleDir) => (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n // Don't let this bubble into the node's own drag gesture.\n event.stopPropagation()\n event.preventDefault()\n\n const node = store.nodes.get(nodeId)\n if (!node) return\n const zoom = store.getViewport().zoom || 1\n const startW = node.width ?? node.size?.width ?? 0\n const startH = node.height ?? node.size?.height ?? 0\n const start = node.position\n const startX = event.clientX\n const startY = event.clientY\n const ratio = startH > 0 ? startW / startH : 1\n const isCorner = (dir.left || dir.right) && (dir.top || dir.bottom)\n\n const compute = (moveEvent: PointerEvent): { size: Size; position: Vec2 } => {\n const dx = (moveEvent.clientX - startX) / zoom\n const dy = (moveEvent.clientY - startY) / zoom\n let width = startW + (dir.right ? dx : dir.left ? -dx : 0)\n let height = startH + (dir.bottom ? dy : dir.top ? -dy : 0)\n width = clamp(width, minWidth, maxWidth)\n height = clamp(height, minHeight, maxHeight)\n if (keepAspectRatio && isCorner) {\n height = clamp(width / ratio, minHeight, maxHeight)\n width = height * ratio\n }\n // Left/top handles keep the opposite edge fixed by shifting the origin.\n const position = {\n x: dir.left ? start.x + (startW - width) : start.x,\n y: dir.top ? start.y + (startH - height) : start.y,\n }\n return { size: { width, height }, position }\n }\n\n // The gesture opens on the first move, not the press: a press that never\n // moves writes no geometry, and shouldn't churn a lock in a shared document.\n let started = false\n const onMove = (moveEvent: PointerEvent) => {\n if (!started) {\n started = true\n store.beginNodeGesture(nodeId)\n } else if (!store.isNodeHeld(nodeId)) {\n // Yielded to a peer mid-resize (`releaseNodeGesture` after a lock\n // conflict). Stop writing and let their box land; no commit.\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n return\n }\n const { size, position } = compute(moveEvent)\n const moved = dir.left || dir.top\n store.resizeNode(nodeId, size, moved ? position : undefined, false)\n onResize?.(size, position)\n }\n const onUp = (upEvent: PointerEvent) => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n if (started && !store.isNodeHeld(nodeId)) return\n const { size, position } = compute(upEvent)\n const moved = dir.left || dir.top\n store.resizeNode(nodeId, size, moved ? position : undefined, true)\n // Released after the commit, so the final size wins over anything that\n // arrived mid-gesture (see `endNodeGesture`).\n if (started) store.endNodeGesture(nodeId)\n onResizeEnd?.(size, position)\n }\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n }\n\n if (!resizable) return null\n\n return (\n <>\n {HANDLES.map((dir) => (\n <div\n key={dir.key}\n data-rivet-resize-handle={dir.key}\n onPointerDown={startResize(dir)}\n style={{\n ...dotStyle(color),\n ...dir.style,\n transform: \"translate(-50%, -50%)\",\n cursor: dir.cursor,\n }}\n />\n ))}\n </>\n )\n}\n","/**\n * The outbound half of presence: what this client tells everyone else.\n *\n * It publishes a *snapshot*, never an event stream. A snapshot is idempotent —\n * a dropped one costs nothing, a duplicate costs nothing, and a client that\n * reconnects mid-session is immediately correct rather than replaying history.\n * That's also how presence channels themselves model state, so this maps onto\n * any transport without a translation layer.\n *\n * Cursor movement is coalesced to `throttleMs`; selection and gesture changes\n * jump the queue, because they're the signals a peer acts on (a lock request\n * that waits 50ms is a lock request that can lose a race it should have won).\n */\n\nimport type { RivetStore } from \"../store\"\nimport type { NodeId, Vec2 } from \"../types\"\nimport { screenToWorld } from \"../viewport\"\nimport type { PeerConnection } from \"./registry\"\nimport { type PresenceTargetKey, presenceTargetKey } from \"./targets\"\n\n/** This client's presence, as handed to `onLocalPresence`. */\nexport type LocalPresence = {\n /**\n * Pointer position in **world** coordinates, or `null` when the pointer is\n * off the canvas. World, not screen: peers have their own viewports, and a\n * screen point means nothing on the other side.\n */\n cursor: Vec2 | null\n /**\n * What this client has selected, as {@link PresenceTargetKey}s: node ids bare,\n * the selected edge as `edge:<id>`, selected anchors as `anchor:<node>:<id>`.\n * Feed it straight back to a peer's `selection` on the other side.\n *\n * Only nodes existed here in 0.2.0 and node ids are still bare strings, so a\n * transport that treats these as node ids keeps working — it just carries a\n * couple of keys it doesn't recognise once someone clicks an edge.\n */\n selection: PresenceTargetKey[]\n /** Nodes under a live local gesture — the same set as `onNodeDragStart`. */\n holding: NodeId[]\n /**\n * The wire this client is pulling out of a handle, or `null`. Both ends in\n * world coordinates; feed it straight back to a peer's `pending`.\n *\n * The local drag's `reconnecting` id is deliberately not here. It means \"the\n * edge this preview stands in for is hidden\", which is true for the client\n * doing the dragging and must not be true for anybody else — the edge is\n * still in the document until their change lands.\n */\n pending: PeerConnection | null\n}\n\nexport type LocalPresenceParams = {\n store: RivetStore\n /** The graph pane; pointer position is read relative to it. */\n pane: HTMLElement\n /** Called with each snapshot, at most once per `throttleMs` for cursor moves. */\n emit: (presence: LocalPresence) => void\n throttleMs: number\n}\n\nconst sameIds = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((id, i) => id === b[i])\n\nconst sameConnection = (a: PeerConnection | null, b: PeerConnection | null): boolean => {\n if (a === b) return true\n if (!a || !b) return false\n return (\n a.source === b.source &&\n a.sourceHandle === b.sourceHandle &&\n a.toPosition === b.toPosition &&\n a.to.x === b.to.x &&\n a.to.y === b.to.y\n )\n}\n\nconst samePresence = (a: LocalPresence, b: LocalPresence): boolean =>\n a.cursor?.x === b.cursor?.x &&\n a.cursor?.y === b.cursor?.y &&\n sameIds(a.selection, b.selection) &&\n sameIds(a.holding, b.holding) &&\n sameConnection(a.pending, b.pending)\n\n/**\n * Track this client's presence and publish it. Returns a dispose function that\n * detaches every listener and cancels a pending emission.\n */\nexport function trackLocalPresence({\n store,\n pane,\n emit,\n throttleMs,\n}: LocalPresenceParams): () => void {\n let cursor: Vec2 | null = null\n /** Last pointer position in pane-relative px — re-projected when the viewport moves. */\n let screenPoint: Vec2 | null = null\n let last: LocalPresence | null = null\n let timer: ReturnType<typeof setTimeout> | null = null\n let lastEmit = Number.NEGATIVE_INFINITY\n\n /**\n * Everything this client has selected, as target keys. Nodes and edges are\n * mutually exclusive with anchors (selecting an anchor clears the graph\n * selection), so in practice one kind is in flight at a time — but the wire\n * shape doesn't depend on that staying true.\n */\n const selectionTargets = (): PresenceTargetKey[] => {\n const targets: PresenceTargetKey[] = store.getSelectedNodes()\n const edgeId = store.getSelectedEdgeId()\n if (edgeId) targets.push(presenceTargetKey({ kind: \"edge\", id: edgeId }))\n for (const ref of store.getSelectedAnchors()) {\n targets.push(presenceTargetKey({ kind: \"anchor\", ...ref }))\n }\n return targets\n }\n\n /**\n * The local drag as peers should see it: the whole pending connection minus\n * `reconnecting`, which is a fact about this client's own display.\n */\n const localConnection = (): PeerConnection | null => {\n const pending = store.getPending()\n if (!pending) return null\n const { source, sourceHandle, sourceType, from, to, toPosition } = pending\n return toPosition === undefined\n ? { source, sourceHandle, sourceType, from, to }\n : { source, sourceHandle, sourceType, from, to, toPosition }\n }\n\n const publish = () => {\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n lastEmit = performance.now()\n const next: LocalPresence = {\n cursor,\n selection: selectionTargets(),\n holding: [...store.getHeldNodeIds()],\n pending: localConnection(),\n }\n // Snapshots are idempotent, so an unchanged one is pure network noise.\n if (last && samePresence(last, next)) return\n last = next\n emit(next)\n }\n\n /** Coalesce to the throttle window, leading edge first, trailing edge kept. */\n const schedule = () => {\n if (timer !== null) return\n const wait = throttleMs - (performance.now() - lastEmit)\n if (wait <= 0) {\n publish()\n return\n }\n timer = setTimeout(() => {\n timer = null\n publish()\n }, wait)\n }\n\n const project = () => {\n if (!screenPoint) {\n cursor = null\n return\n }\n cursor = screenToWorld(screenPoint, store.getViewport())\n }\n\n const onPointerMove = (event: PointerEvent) => {\n const rect = pane.getBoundingClientRect()\n screenPoint = { x: event.clientX - rect.left, y: event.clientY - rect.top }\n project()\n schedule()\n }\n\n // Leaving the pane parks the cursor at once: a stale arrow sitting on the\n // canvas after someone tabbed away is worse than no arrow.\n const onPointerLeave = () => {\n screenPoint = null\n cursor = null\n publish()\n }\n\n // Panning or zooming with a still pointer moves it in world space, which is\n // the space peers see it in — so re-project rather than wait for a move.\n const unsubscribeViewport = store.subscribeViewport(() => {\n if (!screenPoint) return\n project()\n schedule()\n })\n\n // Selection and held nodes are low-frequency and act as signals; publish now.\n const unsubscribeSelection = store.subscribeSelection(() => publish())\n // Anchor selection is view state on its own channel — it never reaches\n // `subscribeSelection`, which carries graph selection alone.\n const unsubscribeAnchors = store.subscribeAnchorSelection(() => publish())\n const unsubscribeHeld = store.subscribeHeldNodes(() => publish())\n // A connection drag is pointer movement, so its frames coalesce like the\n // cursor's — but picking a wire up and letting it go are state changes, and a\n // dropped wire that waits out the throttle hangs on every peer's canvas.\n let hadPending = store.getPending() !== null\n const unsubscribeConnection = store.subscribeConnection(() => {\n const has = store.getPending() !== null\n if (has === hadPending) {\n schedule()\n return\n }\n hadPending = has\n publish()\n })\n\n pane.addEventListener(\"pointermove\", onPointerMove)\n pane.addEventListener(\"pointerleave\", onPointerLeave)\n\n return () => {\n if (timer !== null) clearTimeout(timer)\n pane.removeEventListener(\"pointermove\", onPointerMove)\n pane.removeEventListener(\"pointerleave\", onPointerLeave)\n unsubscribeViewport()\n unsubscribeSelection()\n unsubscribeAnchors()\n unsubscribeHeld()\n unsubscribeConnection()\n }\n}\n","import { type RefObject, useEffect, useRef } from \"react\"\nimport { type LocalPresence, trackLocalPresence } from \"../presence/local\"\nimport type { RivetStore } from \"../store\"\n\nexport type UseLocalPresenceParams = {\n store: RivetStore\n paneRef: RefObject<HTMLDivElement | null>\n /** Absent = don't track at all; nothing is listening, so nothing is measured. */\n onLocalPresence: ((presence: LocalPresence) => void) | undefined\n throttleMs: number\n}\n\n/**\n * Publish this client's presence while `onLocalPresence` is set. The callback\n * is read through a ref so an inline handler doesn't re-attach the tracker\n * (and reset its throttle window) on every render — only appearing, going away,\n * or a changed throttle does that.\n */\nexport function useLocalPresence({\n store,\n paneRef,\n onLocalPresence,\n throttleMs,\n}: UseLocalPresenceParams): void {\n const handlerRef = useRef(onLocalPresence)\n handlerRef.current = onLocalPresence\n const enabled = Boolean(onLocalPresence)\n\n useEffect(() => {\n const pane = paneRef.current\n if (!enabled || !pane) return\n return trackLocalPresence({\n store,\n pane,\n emit: (presence) => handlerRef.current?.(presence),\n throttleMs,\n })\n }, [store, paneRef, enabled, throttleMs])\n}\n","import { type ReactNode, useMemo, useRef } from \"react\"\nimport {\n type AnchorOptions,\n DEFAULT_ANCHOR_OPTIONS,\n type ResolvedAnchorOptions,\n} from \"../anchor/registry\"\nimport {\n DEFAULT_PRESENCE_OPTIONS,\n type PresenceOptions,\n type ResolvedPresenceOptions,\n} from \"../presence/registry\"\nimport type {\n Connection,\n DefaultEdgeOptions,\n EdgeTypes,\n LaneChange,\n NodeTypes,\n SwimlaneHeaderProps,\n SwimlaneLabelProps,\n SwimlaneMargin,\n} from \"../types\"\n\n/** Object.is, or same-length arrays / same-key objects whose members are Object.is-equal. */\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true\n if (typeof a !== \"object\" || a === null || typeof b !== \"object\" || b === null) return false\n const aArr = Array.isArray(a)\n if (aArr !== Array.isArray(b)) return false\n if (aArr) {\n const bArr = b as unknown[]\n if ((a as unknown[]).length !== bArr.length) return false\n return (a as unknown[]).every((v, i) => Object.is(v, bArr[i]))\n }\n const aKeys = Object.keys(a as object)\n const bObj = b as Record<string, unknown>\n if (aKeys.length !== Object.keys(bObj).length) return false\n return aKeys.every(\n (k) => Object.hasOwn(bObj, k) && Object.is((a as Record<string, unknown>)[k], bObj[k]),\n )\n}\n\n/**\n * Keep the previous reference when `value` is shallow-equal, so a consumer passing\n * a new-but-equal inline object/array each render doesn't change identity (and an\n * omitted prop's hoisted default stays stable).\n */\nfunction useShallowStable<T>(value: T): T {\n const ref = useRef(value)\n if (!shallowEqual(ref.current, value)) ref.current = value\n return ref.current\n}\n\n/**\n * A stable function that forwards to the latest `fn`, or `undefined` when `fn` is\n * absent. An inline handler never changes identity, while an unset prop still\n * reads as \"no handler\" (so default behavior is preserved). Identity only flips\n * when the prop appears or disappears.\n */\nfunction useStableOptional<A extends unknown[], R>(\n fn: ((...args: A) => R) | undefined,\n): ((...args: A) => R) | undefined {\n const ref = useRef(fn)\n ref.current = fn\n const stable = useRef<((...args: A) => R) | null>(null)\n if (stable.current === null) stable.current = (...args: A): R => ref.current?.(...args) as R\n return fn ? stable.current : undefined\n}\n\nexport type UseRivetConfigParams = {\n nodeTypes: NodeTypes\n edgeTypes: EdgeTypes | undefined\n defaultEdgeOptions: DefaultEdgeOptions | undefined\n snapGrid: [number, number] | undefined\n swimlaneMargin: number | SwimlaneMargin | undefined\n anchorOptions: AnchorOptions | undefined\n presenceOptions: PresenceOptions | undefined\n panOnDrag: boolean | number[]\n selectionKeyCode: string | string[] | null\n multiSelectionKeyCode: string | string[]\n isValidConnection: ((connection: Connection) => boolean) | undefined\n mapConnection: ((connection: Connection) => Connection | null) | undefined\n onConnect: ((connection: Connection) => void) | undefined\n onLaneChange: ((change: LaneChange) => void) | undefined\n renderSwimlaneHeader: ((props: SwimlaneHeaderProps) => ReactNode) | undefined\n renderSwimlaneLabel: ((props: SwimlaneLabelProps) => ReactNode) | undefined\n}\n\nexport type RivetConfig = {\n nodeTypes: NodeTypes\n edgeTypes: EdgeTypes | undefined\n defaultEdgeOptions: DefaultEdgeOptions | undefined\n snapGrid: [number, number] | null\n swimlaneMargin: number | SwimlaneMargin | undefined\n /** Anchor chrome placement policy, filled with defaults. */\n anchorOptions: ResolvedAnchorOptions\n /** Presence policy (outbound throttle, cursor painting), filled with defaults. */\n presenceOptions: ResolvedPresenceOptions\n /** `MouseEvent.button` codes that pan on drag, derived from `panOnDrag`. */\n panButtons: number[]\n /** Keys that force a marquee, derived from `selectionKeyCode`. */\n selectionKeys: string[]\n /** Keys that make selection additive, derived from `multiSelectionKeyCode`. */\n multiSelectionKeys: string[]\n isValidConnection: ((connection: Connection) => boolean) | undefined\n mapConnection: ((connection: Connection) => Connection | null) | undefined\n onConnect: ((connection: Connection) => void) | undefined\n onLaneChange: ((change: LaneChange) => void) | undefined\n renderSwimlaneHeader: ((props: SwimlaneHeaderProps) => ReactNode) | undefined\n renderSwimlaneLabel: ((props: SwimlaneLabelProps) => ReactNode) | undefined\n}\n\n/**\n * Resolve the identity-sensitive props once, to stable references — the inputs\n * that flow into the context memo and the render-loop effect's deps. Value props\n * are shallow-stabilized, key-code props are derived into their consumed shapes,\n * and callbacks become presence-preserving stable wrappers. So a consumer passing\n * inline objects/handlers can't churn the context or re-mount the render loop.\n */\nexport function useRivetConfig(params: UseRivetConfigParams): RivetConfig {\n const panOnDrag = useShallowStable(params.panOnDrag)\n const selectionKeyCode = useShallowStable(params.selectionKeyCode)\n const multiSelectionKeyCode = useShallowStable(params.multiSelectionKeyCode)\n\n const panButtons = useMemo<number[]>(\n () => (panOnDrag === true ? [0] : panOnDrag === false ? [] : panOnDrag),\n [panOnDrag],\n )\n const selectionKeys = useMemo<string[]>(\n () =>\n selectionKeyCode == null\n ? []\n : Array.isArray(selectionKeyCode)\n ? selectionKeyCode\n : [selectionKeyCode],\n [selectionKeyCode],\n )\n const multiSelectionKeys = useMemo<string[]>(\n () => (Array.isArray(multiSelectionKeyCode) ? multiSelectionKeyCode : [multiSelectionKeyCode]),\n [multiSelectionKeyCode],\n )\n\n const nodeTypes = useShallowStable(params.nodeTypes)\n const edgeTypes = useShallowStable(params.edgeTypes)\n const defaultEdgeOptions = useShallowStable(params.defaultEdgeOptions)\n const snapGrid = useShallowStable(params.snapGrid ?? null)\n const swimlaneMargin = useShallowStable(params.swimlaneMargin)\n const anchorOptionsInput = useShallowStable(params.anchorOptions)\n const anchorOptions = useMemo<ResolvedAnchorOptions>(\n () => ({ ...DEFAULT_ANCHOR_OPTIONS, ...anchorOptionsInput }),\n [anchorOptionsInput],\n )\n const presenceOptionsInput = useShallowStable(params.presenceOptions)\n const presenceOptions = useMemo<ResolvedPresenceOptions>(\n () => ({ ...DEFAULT_PRESENCE_OPTIONS, ...presenceOptionsInput }),\n [presenceOptionsInput],\n )\n const isValidConnection = useStableOptional(params.isValidConnection)\n const mapConnection = useStableOptional(params.mapConnection)\n const onConnect = useStableOptional(params.onConnect)\n const onLaneChange = useStableOptional(params.onLaneChange)\n const renderSwimlaneHeader = useStableOptional(params.renderSwimlaneHeader)\n const renderSwimlaneLabel = useStableOptional(params.renderSwimlaneLabel)\n\n return {\n nodeTypes,\n edgeTypes,\n defaultEdgeOptions,\n snapGrid,\n swimlaneMargin,\n anchorOptions,\n presenceOptions,\n panButtons,\n selectionKeys,\n multiSelectionKeys,\n isValidConnection,\n mapConnection,\n onConnect,\n onLaneChange,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n }\n}\n","import { snapToGrid } from \"../graph\"\nimport type { RivetStore } from \"../store\"\n\n/** World units a selected node nudges per arrow key (×{@link ARROW_STEP_SHIFT} with Shift). */\nexport const ARROW_STEP = 10\nexport const ARROW_STEP_SHIFT = 5\n/** Unit move vector per arrow key. */\nexport const ARROW_DIRS: Record<string, { x: number; y: number }> = {\n ArrowUp: { x: 0, y: -1 },\n ArrowDown: { x: 0, y: 1 },\n ArrowLeft: { x: -1, y: 0 },\n ArrowRight: { x: 1, y: 0 },\n}\n\n/**\n * Keyboard actions on the graph: Delete/Backspace removes the selection, Escape\n * dismisses the post-marquee selection box, arrow keys nudge the selected\n * node(s) (Shift = larger step). Bails when another handler\n * already claimed the key (`event.defaultPrevented` — an open menu/dialog, or any\n * consumer control) or when focus is in a text field.\n *\n * `getSnapGrid` is read at press time rather than captured, so toggling the\n * graph's `snapGrid` doesn't require re-installing the pane's listeners. With a\n * grid configured a press moves exactly one cell and lands on the grid, the\n * same contract as the grabbed-node arrow movement in `node-wrapper` — the two\n * arrow paths must not disagree about where a node ends up.\n */\nexport function createKeyboardHandler(\n store: RivetStore,\n getSnapGrid?: () => [number, number] | null,\n): (event: KeyboardEvent) => void {\n return (event) => {\n if (event.defaultPrevented) return\n const active = document.activeElement\n if (\n active instanceof HTMLElement &&\n (active.tagName === \"INPUT\" || active.tagName === \"TEXTAREA\" || active.isContentEditable)\n ) {\n return\n }\n\n if (event.key === \"Delete\" || event.key === \"Backspace\") {\n if (store.deleteSelection()) event.preventDefault()\n return\n }\n\n // Escape cancels an in-progress connection first (a keyboard-started one\n // has no drag gesture to tear it down), then dismisses the post-marquee\n // selection box (with its selection). Only those — a plain Escape on the\n // pane shouldn't clear a clicked node, which the focused node's own\n // handler already covers.\n if (event.key === \"Escape\") {\n if (store.getPending()) store.endConnection()\n else if (store.isSelectionBoxActive()) store.selectNode(null)\n return\n }\n\n const dir = ARROW_DIRS[event.key]\n if (!dir) return\n // A locked mover drops out of the nudge the same way it drops out of a\n // group drag: the rest of the selection still moves.\n const movers = store\n .getMovers(store.getSelectedNodes())\n .filter((id) => store.locks.allows(id, \"drag\"))\n if (movers.length === 0) return\n event.preventDefault()\n const snapGrid = getSnapGrid?.() ?? null\n const factor = event.shiftKey ? ARROW_STEP_SHIFT : 1\n // A `0` axis of the grid is free, so it keeps the default step.\n const stepX = (snapGrid?.[0] || ARROW_STEP) * factor\n const stepY = (snapGrid?.[1] || ARROW_STEP) * factor\n for (const id of movers) {\n const node = store.nodes.get(id)\n if (!node) continue\n let next = { x: node.position.x + dir.x * stepX, y: node.position.y + dir.y * stepY }\n if (snapGrid) next = snapToGrid(next, snapGrid)\n store.moveNode(id, next, true)\n }\n }\n}\n","/** Keys readable straight off an event via `getModifierState` — no key tracking. */\nconst MODIFIER_KEYS = new Set([\"Shift\", \"Control\", \"Meta\", \"Alt\"])\n\n/**\n * True when any of `keys` is currently held. Modifier keys are read from the\n * event via `getModifierState` (never stale); other keys need a `pressedKeys`\n * set maintained from keydown/keyup. With no set, only modifiers resolve.\n */\nexport function keyHeld(\n event: { getModifierState(key: string): boolean },\n keys: readonly string[],\n pressedKeys?: ReadonlySet<string>,\n): boolean {\n return keys.some((key) =>\n MODIFIER_KEYS.has(key) ? event.getModifierState(key) : (pressedKeys?.has(key) ?? false),\n )\n}\n","/**\n * Manages the node layer's transform and its `will-change` compositor hint. The\n * hint is applied only while the viewport is moving and dropped once it settles,\n * so the browser re-rasterizes DOM text crisply at the current zoom (a permanently\n * promoted layer upscales a stale bitmap and blurs text).\n */\nexport type LayerHint = {\n /** Set the layer transform; if it changed, promote the layer and arm the idle drop. */\n apply: (transform: string) => void\n dispose: () => void\n}\n\nexport function createLayerHint(layer: HTMLElement, idleMs: number): LayerHint {\n let lastTransform = \"\"\n let timer = 0\n return {\n apply(transform) {\n if (transform === lastTransform) return\n lastTransform = transform\n layer.style.transform = transform\n layer.style.willChange = \"transform\"\n if (timer) clearTimeout(timer)\n timer = window.setTimeout(() => {\n layer.style.willChange = \"auto\"\n }, idleMs)\n },\n dispose() {\n if (timer) clearTimeout(timer)\n },\n }\n}\n","import type { RivetStore } from \"../store\"\nimport type { NodeId } from \"../types\"\nimport { rectsIntersect, screenToWorld } from \"../viewport\"\n\nconst OVERLAY_STYLE =\n \"position:absolute;pointer-events:none;display:none;border:1px solid rgba(99,102,241,0.9);background:rgba(99,102,241,0.12);\"\n\nexport type MarqueeControllerDeps = {\n store: RivetStore\n pane: HTMLElement\n}\n\n/**\n * Marquee (rubber-band) selection state machine. Owns its screen-space overlay\n * element and the world-rect hit test. The pane dispatcher decides when a press\n * starts a marquee (empty-space drag, or the selection key held) and drives\n * start/move/end; `additive` (the multi-select key) unions the covered nodes with\n * the selection that was live when the marquee began. The overlay lives in screen\n * space, so it is never viewport-transformed.\n */\nexport type MarqueeController = {\n isActive: () => boolean\n start: (event: PointerEvent, px: number, py: number, additive: boolean) => void\n move: (px: number, py: number) => void\n end: (event: PointerEvent) => void\n /** Remove the overlay element (runtime teardown). */\n dispose: () => void\n}\n\nexport function createMarqueeController(deps: MarqueeControllerDeps): MarqueeController {\n const { store, pane } = deps\n let active = false\n let additive = false\n let base: NodeId[] = []\n let start = { x: 0, y: 0 }\n\n const overlay = document.createElement(\"div\")\n overlay.style.cssText = OVERLAY_STYLE\n pane.appendChild(overlay)\n\n const apply = (px: number, py: number) => {\n const left = Math.min(start.x, px)\n const top = Math.min(start.y, py)\n const width = Math.abs(px - start.x)\n const height = Math.abs(py - start.y)\n overlay.style.left = `${left}px`\n overlay.style.top = `${top}px`\n overlay.style.width = `${width}px`\n overlay.style.height = `${height}px`\n\n const viewport = store.getViewport()\n const topLeft = screenToWorld({ x: left, y: top }, viewport)\n const bottomRight = screenToWorld({ x: left + width, y: top + height }, viewport)\n const worldRect = {\n x: topLeft.x,\n y: topLeft.y,\n width: bottomRight.x - topLeft.x,\n height: bottomRight.y - topLeft.y,\n }\n const ids: NodeId[] = []\n for (const [id, node] of store.nodes) {\n if (node.selectable === false) continue\n // A peer's lock reads exactly like `selectable: false` here — the sweep\n // passes over the node instead of refusing to select anything.\n if (!store.locks.allows(id, \"select\")) continue\n if (rectsIntersect(worldRect, store.getNodeRect(id))) ids.push(id)\n }\n store.selectNodes(additive ? [...new Set([...base, ...ids])] : ids)\n }\n\n return {\n isActive: () => active,\n start(event, px, py, isAdditive) {\n active = true\n additive = isAdditive\n base = isAdditive ? store.getSelectedNodes() : []\n start = { x: px, y: py }\n overlay.style.display = \"block\"\n apply(px, py)\n pane.setPointerCapture(event.pointerId)\n },\n move(px, py) {\n if (!active) return\n apply(px, py)\n },\n end(event) {\n if (!active) return\n active = false\n overlay.style.display = \"none\"\n pane.releasePointerCapture(event.pointerId)\n // A marquee that ends over nodes leaves the persistent selection box\n // behind them (see NodesSelection); it dismisses on the next click.\n store.setSelectionBoxActive(store.getSelectedNodes().length > 0)\n },\n dispose() {\n overlay.remove()\n },\n }\n}\n","import type { RivetStore } from \"../store\"\n\n/** Pointer travel (px) before a press counts as a pan rather than a click. */\nconst PAN_MOVE_THRESHOLD = 3\n\nexport type PanControllerDeps = {\n store: RivetStore\n pane: HTMLElement\n /** Ask the runtime to schedule a repaint (a pan moved the viewport). */\n schedule: () => void\n}\n\n/**\n * Drag-to-pan state machine. The pane's pointer dispatcher decides when a press\n * is a pan and drives {@link PanController.start}/`move`/`end`; this owns the\n * pan's state and viewport math. A moved right-button pan arms\n * {@link PanController.suppressNextContextMenu} so the ensuing context menu is\n * swallowed instead of popping mid-pan.\n */\nexport type PanController = {\n isPanning: () => boolean\n start: (event: PointerEvent) => void\n move: (event: PointerEvent) => void\n end: (event: PointerEvent) => void\n /** Read-and-clear: true once if the last pan should swallow the next context menu. */\n suppressNextContextMenu: () => boolean\n}\n\nexport function createPanController(deps: PanControllerDeps): PanController {\n const { store, pane, schedule } = deps\n let panning = false\n let button = 0\n let moved = false\n let start = { x: 0, y: 0 }\n let origin = { x: 0, y: 0 }\n let suppressContextMenu = false\n\n return {\n isPanning: () => panning,\n start(event) {\n panning = true\n button = event.button\n moved = false\n const viewport = store.getViewport()\n start = { x: event.clientX, y: event.clientY }\n origin = { x: viewport.x, y: viewport.y }\n pane.setPointerCapture(event.pointerId)\n },\n move(event) {\n if (!panning) return\n const dx = event.clientX - start.x\n const dy = event.clientY - start.y\n if (!moved && Math.hypot(dx, dy) > PAN_MOVE_THRESHOLD) {\n moved = true\n if (button === 2) suppressContextMenu = true\n }\n const viewport = store.getViewport()\n store.setViewport({ ...viewport, x: origin.x + dx, y: origin.y + dy })\n schedule()\n },\n end(event) {\n if (!panning) return\n panning = false\n pane.releasePointerCapture(event.pointerId)\n },\n suppressNextContextMenu() {\n if (!suppressContextMenu) return false\n suppressContextMenu = false\n return true\n },\n }\n}\n","import type { EdgeRenderer } from \"../types\"\n\n/** Live pane pixel size, written on resize and read by the render loop. */\nexport type CanvasSize = { width: number; height: number; dpr: number }\n\nexport type ResizeControllerDeps = {\n pane: HTMLElement\n /** Background (grid + swimlane) canvas — sized here; edge canvases size via their renderers. */\n bgCanvas: HTMLCanvasElement\n size: CanvasSize\n edgeRenderer: EdgeRenderer\n foregroundRenderer: EdgeRenderer\n /**\n * Called with the new {@link CanvasSize} already written, for layers the\n * runtime owns conditionally (the peer-cursor canvas, which only exists when\n * cursors are being painted).\n */\n onResize?: () => void\n /** Repaint after a resize. */\n schedule: () => void\n}\n\n/**\n * Keep the canvases matched to the pane's CSS size and devicePixelRatio. Owns a\n * `ResizeObserver` on the pane and runs once immediately so the first frame is\n * sized. Writes the shared {@link CanvasSize} the render loop reads. `dispose`\n * disconnects the observer.\n */\nexport function createResizeController(deps: ResizeControllerDeps): { dispose: () => void } {\n const { pane, bgCanvas, size, edgeRenderer, foregroundRenderer, onResize, schedule } = deps\n\n const resize = () => {\n const rect = pane.getBoundingClientRect()\n size.width = rect.width\n size.height = rect.height\n size.dpr = window.devicePixelRatio || 1\n bgCanvas.width = Math.max(1, Math.round(rect.width * size.dpr))\n bgCanvas.height = Math.max(1, Math.round(rect.height * size.dpr))\n bgCanvas.style.width = `${rect.width}px`\n bgCanvas.style.height = `${rect.height}px`\n edgeRenderer.resize(rect.width, rect.height, size.dpr)\n foregroundRenderer.resize(rect.width, rect.height, size.dpr)\n onResize?.()\n schedule()\n }\n\n const observer = new ResizeObserver(resize)\n observer.observe(pane)\n resize()\n\n return { dispose: () => observer.disconnect() }\n}\n","import { clamp } from \"@rivet/utils\"\nimport type { RivetStore } from \"../store\"\nimport { zoomAt } from \"../viewport\"\n\n/** Approx px per wheel \"line\" / \"page\", to normalize non-pixel `deltaMode`. */\nconst WHEEL_LINE_PX = 16\n/** Fraction of the remaining zoom distance closed each frame (higher = snappier). */\nconst ZOOM_EASE = 0.22\n\nexport type ZoomControllerDeps = {\n store: RivetStore\n pane: HTMLElement\n /** Live pane pixel size (read for page-mode wheel normalization). */\n size: { height: number }\n minZoom: number\n maxZoom: number\n zoomSpeed: number\n /** Pan on wheel/trackpad scroll instead of zooming (pinch still zooms). */\n scrollToPan: boolean\n /** Ask the runtime to schedule a frame (to keep the ease running / repaint a pan). */\n schedule: () => void\n}\n\n/**\n * Wheel/pinch zoom with easing. Zoom accumulates onto a pending target so fast\n * ticks ramp up; {@link ZoomController.step} eases the on-screen zoom toward it\n * each frame. A new gesture calls {@link ZoomController.cancel}.\n */\nexport type ZoomController = {\n /** Advance the ease one frame; call at the top of the render loop. */\n step: () => void\n onWheel: (event: WheelEvent) => void\n /** Abandon any in-flight ease (a pan/reconnect/press is taking over). */\n cancel: () => void\n}\n\nexport function createZoomController(deps: ZoomControllerDeps): ZoomController {\n const { store, pane, size, minZoom, maxZoom, zoomSpeed, scrollToPan, schedule } = deps\n let target: { zoom: number; anchor: { x: number; y: number } } | null = null\n\n return {\n cancel() {\n target = null\n },\n step() {\n if (!target) return\n const vp = store.getViewport()\n const diff = target.zoom - vp.zoom\n if (Math.abs(diff) < 0.0005) {\n store.setViewport(zoomAt(vp, target.anchor, target.zoom, minZoom, maxZoom))\n target = null\n return\n }\n store.setViewport(zoomAt(vp, target.anchor, vp.zoom + diff * ZOOM_EASE, minZoom, maxZoom))\n schedule() // keep the ease running next frame\n },\n onWheel(event) {\n event.preventDefault()\n // Normalize non-pixel wheels (line/page mode) so step sizes are consistent.\n const scale = event.deltaMode === 1 ? WHEEL_LINE_PX : event.deltaMode === 2 ? size.height : 1\n const deltaX = event.deltaX * scale\n const deltaY = event.deltaY * scale\n\n // With scrollToPan on, a plain wheel/two-finger scroll pans; a pinch (which\n // the browser reports as ctrl+wheel) still zooms. Otherwise wheel zooms.\n if (scrollToPan && !event.ctrlKey) {\n target = null\n const viewport = store.getViewport()\n store.setViewport({ ...viewport, x: viewport.x - deltaX, y: viewport.y - deltaY })\n schedule()\n return\n }\n\n const rect = pane.getBoundingClientRect()\n const anchor = { x: event.clientX - rect.left, y: event.clientY - rect.top }\n // Accumulate onto the pending target (not the on-screen zoom) so fast ticks\n // ramp up, then the frame loop eases the visible zoom toward it.\n const base = target?.zoom ?? store.getViewport().zoom\n const nextZoom = clamp(base * Math.exp(-deltaY * zoomSpeed), minZoom, maxZoom)\n target = { zoom: nextZoom, anchor }\n schedule()\n },\n }\n}\n","import type { Viewport } from \"../types\"\n\nexport type DotGridOptions = {\n gap?: number\n radius?: number\n color?: string\n}\n\n/** Draw an infinite dot grid that tracks the viewport. Context is in CSS px. */\nexport function drawDotGrid(\n ctx: CanvasRenderingContext2D,\n width: number,\n height: number,\n viewport: Viewport,\n options?: DotGridOptions,\n): void {\n const gap = options?.gap ?? 24\n const radius = options?.radius ?? 1\n const color = options?.color ?? \"rgba(100, 116, 139, 0.35)\"\n\n const step = gap * viewport.zoom\n // Skip when dots would be denser than they are useful.\n if (step < 8) return\n\n const offsetX = ((viewport.x % step) + step) % step\n const offsetY = ((viewport.y % step) + step) % step\n\n ctx.fillStyle = color\n ctx.beginPath()\n for (let x = offsetX; x < width; x += step) {\n for (let y = offsetY; y < height; y += step) {\n ctx.moveTo(x + radius, y)\n ctx.arc(x, y, radius, 0, Math.PI * 2)\n }\n }\n ctx.fill()\n}\n","/**\n * Painting for presence — peer cursors, their selections, and the boxes they're\n * dragging right now.\n *\n * All of it is screen-space chrome above the nodes: it belongs to the frame,\n * not to the document, so it's drawn from the registry every tick and never\n * persisted. Nothing here reads or writes the graph — a node under a peer's\n * gesture is already being drawn at their live box (the store folds their\n * frames into world positions), so this file only says *whose* it is.\n *\n * It paints onto **two** canvases, split by what makes them dirty:\n *\n * - {@link drawPeerOutlines} — selections, held nodes and locks, on the shared\n * foreground canvas. They annotate node geometry and change when it does.\n * - {@link drawPeerCursors} — the arrows and name chips, on a canvas of their\n * own. Cursors arrive at pointer rate for every peer and nothing else on\n * screen depends on where they are, so a cursor frame repaints that layer\n * alone and leaves the foreground (pending connection, alignment guides,\n * endpoint bubbles) untouched.\n */\n\nimport { type PeerRecord, peerColor } from \"../presence/registry\"\nimport { isNodeTarget, type PresenceTargetKey, presenceTargetEdgeId } from \"../presence/targets\"\nimport type { EdgeId, HandleRecord, NodeId, Rect, Vec2, Viewport } from \"../types\"\nimport { worldToScreen } from \"../viewport\"\nimport { buildPendingPath } from \"./edge-geometry\"\n\n/** Outline around a node a peer is holding or moving right now. */\nconst HELD_LINE_WIDTH = 2\n/** Outline around a node a peer merely has selected — thinner, and dashed. */\nconst SELECTED_LINE_WIDTH = 1.5\nconst SELECTED_DASH = [4, 4]\nconst OUTLINE_RADIUS = 6\n\n/** Cursor arrow, in px from the pointer tip. The classic seven-point pointer. */\nconst CURSOR_POINTS: readonly Vec2[] = [\n { x: 0, y: 0 },\n { x: 0, y: 16 },\n { x: 4.2, y: 12.2 },\n { x: 6.8, y: 17.6 },\n { x: 9.2, y: 16.6 },\n { x: 6.6, y: 11.4 },\n { x: 11.4, y: 11.4 },\n]\nconst CURSOR_LABEL_OFFSET: Vec2 = { x: 12, y: 17 }\nconst LABEL_FONT = \"500 11px ui-sans-serif, system-ui, -apple-system, sans-serif\"\nconst LABEL_PADDING_X = 6\nconst LABEL_HEIGHT = 17\nconst LABEL_RADIUS = 4\n/** How far off-pane a cursor or box may sit before it's skipped entirely. */\nconst CULL_MARGIN_PX = 64\n\n/** A peer's in-flight wire: the local pending connection's dash, their colour. */\nconst PENDING_DASH = [6, 4]\nconst PENDING_LINE_WIDTH = 2\n/** Dot on the loose end — the tip is their pointer, so it reads like their cursor. */\nconst PENDING_TIP_RADIUS = 3.5\n\n/** Pane size in CSS px, plus the device pixel ratio the canvas is scaled by. */\nexport type PresenceCanvasSize = { width: number; height: number; dpr: number }\n\nexport type PeerCursorDrawParams = {\n viewport: Viewport\n size: PresenceCanvasSize\n}\n\nexport type PeerPendingDrawParams = {\n viewport: Viewport\n size: PresenceCanvasSize\n /**\n * This client's handle registry — the source end's side comes from it, so a\n * peer's preview curves the same way theirs does.\n */\n handles: Map<string, HandleRecord> | undefined\n}\n\nexport type PeerOutlineDrawParams = {\n viewport: Viewport\n size: PresenceCanvasSize\n /** This client's box for a node, or `null` when it doesn't have that node. */\n getNodeRect: (id: NodeId) => Rect | null\n /**\n * The whole lock table, keyed by {@link PresenceTargetKey}. Locked nodes are\n * painted exactly like a peer's held node: to whoever is looking, \"they have\n * this\" is the whole message, and a second visual vocabulary for it would\n * only ask them to learn the difference between advisory and enforced.\n * Holders don't have to be in the roster — a lock can outlive the tab that\n * took it.\n *\n * Non-node entries are skipped here: an edge is drawn by the edge renderer\n * (which is the only thing that knows its path) and an anchor sits inside a\n * node box rather than on it.\n */\n locks: ReadonlyMap<PresenceTargetKey, string>\n}\n\n/** Trace a rounded rect, degrading to a square one where `roundRect` is missing. */\nfunction traceRect(ctx: CanvasRenderingContext2D, rect: Rect, radius: number): void {\n ctx.beginPath()\n if (typeof ctx.roundRect === \"function\") {\n ctx.roundRect(rect.x, rect.y, rect.width, rect.height, radius)\n } else {\n ctx.rect(rect.x, rect.y, rect.width, rect.height)\n }\n}\n\n/** World rect → screen rect under the current viewport. */\nfunction projectRect(rect: Rect, viewport: Viewport): Rect {\n const origin = worldToScreen({ x: rect.x, y: rect.y }, viewport)\n return {\n x: origin.x,\n y: origin.y,\n width: rect.width * viewport.zoom,\n height: rect.height * viewport.zoom,\n }\n}\n\nfunction onScreen(rect: Rect, size: { width: number; height: number }): boolean {\n return (\n rect.x + rect.width >= -CULL_MARGIN_PX &&\n rect.y + rect.height >= -CULL_MARGIN_PX &&\n rect.x <= size.width + CULL_MARGIN_PX &&\n rect.y <= size.height + CULL_MARGIN_PX\n )\n}\n\n/** Outline one node in a peer's colour: solid for a claim, dashed for a selection. */\nfunction drawNodeOutline(\n ctx: CanvasRenderingContext2D,\n rect: Rect,\n color: string,\n mode: \"selected\" | \"held\",\n): void {\n ctx.strokeStyle = color\n ctx.lineWidth = mode === \"selected\" ? SELECTED_LINE_WIDTH : HELD_LINE_WIDTH\n ctx.setLineDash(mode === \"selected\" ? SELECTED_DASH : [])\n traceRect(ctx, rect, OUTLINE_RADIUS)\n ctx.stroke()\n ctx.setLineDash([])\n}\n\n/** The pointer arrow, plus a name chip when the peer has a name. */\nfunction drawCursor(\n ctx: CanvasRenderingContext2D,\n point: Vec2,\n color: string,\n name: string | undefined,\n): void {\n ctx.beginPath()\n const [first, ...rest] = CURSOR_POINTS\n if (!first) return\n ctx.moveTo(point.x + first.x, point.y + first.y)\n for (const offset of rest) ctx.lineTo(point.x + offset.x, point.y + offset.y)\n ctx.closePath()\n ctx.fillStyle = color\n ctx.fill()\n // A white keyline keeps the arrow legible over a node of the same hue.\n ctx.strokeStyle = \"#ffffff\"\n ctx.lineWidth = 1\n ctx.stroke()\n\n if (!name) return\n ctx.font = LABEL_FONT\n ctx.textBaseline = \"middle\"\n const width = ctx.measureText(name).width + LABEL_PADDING_X * 2\n const x = point.x + CURSOR_LABEL_OFFSET.x\n const y = point.y + CURSOR_LABEL_OFFSET.y\n traceRect(ctx, { x, y, width, height: LABEL_HEIGHT }, LABEL_RADIUS)\n ctx.fillStyle = color\n ctx.fill()\n ctx.fillStyle = \"#ffffff\"\n ctx.fillText(name, x + LABEL_PADDING_X, y + LABEL_HEIGHT / 2)\n}\n\n/**\n * Outline what every peer has a claim on, onto the foreground canvas: their\n * selections first, then whatever they're holding, then locks.\n *\n * Shares the canvas with the pending connection and the alignment guides, so it\n * draws over whatever they left and clears nothing.\n */\nexport function drawPeerOutlines(\n ctx: CanvasRenderingContext2D,\n peers: readonly PeerRecord[],\n { viewport, size, getNodeRect, locks }: PeerOutlineDrawParams,\n): void {\n if (peers.length === 0 && locks.size === 0) return\n ctx.save()\n // Screen space: outlines are chrome, so they keep their weight at any zoom\n // (the boxes they sit on scale, the strokes don't).\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n\n // Nodes a peer has already claimed this frame. A locked node is very often\n // also one its holder is dragging, and stroking it twice reads as a heavier\n // border rather than as two facts.\n const painted = new Set<NodeId>()\n\n for (const peer of peers) {\n // A node they're moving is held whether or not their roster entry has caught\n // up: the frames arriving are the more current fact, and `getNodeRect`\n // already returns it at their live box.\n //\n // Claims can name an edge or an anchor as well as a node; those have their\n // own geometry, published by the edge renderer and the anchor registry\n // rather than sitting on a node box, so this pass leaves them alone.\n const held = new Set([\n ...peer.holding.filter((key) => isNodeTarget(key)),\n ...peer.transforms.keys(),\n ])\n for (const id of peer.selection) {\n if (!isNodeTarget(id) || held.has(id)) continue\n const rect = getNodeRect(id)\n if (!rect) continue\n const screen = projectRect(rect, viewport)\n if (onScreen(screen, size)) drawNodeOutline(ctx, screen, peer.color, \"selected\")\n }\n for (const id of held) {\n painted.add(id)\n const rect = getNodeRect(id)\n if (!rect) continue\n const screen = projectRect(rect, viewport)\n if (onScreen(screen, size)) drawNodeOutline(ctx, screen, peer.color, \"held\")\n }\n }\n\n if (locks.size > 0) {\n // The roster's colour wins where it exists, so a peer who declared one\n // looks the same locked as they do holding; otherwise it's derived from the\n // holder id, which is how an unrostered holder still gets a stable colour.\n const declared = new Map(peers.map((peer) => [peer.id, peer.color]))\n for (const [id, holderId] of locks) {\n if (!isNodeTarget(id) || painted.has(id)) continue\n const rect = getNodeRect(id)\n if (!rect) continue\n const screen = projectRect(rect, viewport)\n if (!onScreen(screen, size)) continue\n drawNodeOutline(ctx, screen, declared.get(holderId) ?? peerColor(holderId), \"held\")\n }\n }\n\n ctx.restore()\n}\n\n/**\n * Every edge somebody else has a claim on, `edgeId -> colour`, for\n * {@link EdgeDrawExtras.peerEdges}. Returns `undefined` when nothing is\n * claimed, so the common frame passes no map at all.\n *\n * One colour per edge, resolved in the order a reader would rank the claims:\n * a peer actively holding the edge, then a peer who has it selected, then a\n * lock. An edge has a single stroke to spend, and the most immediate claim is\n * the one worth spending it on.\n *\n * Locks are folded in last and never overwrite a peer, which keeps a holder\n * who is *also* the lock's owner painted in their roster colour rather than in\n * the one derived from their id.\n */\nexport function collectPeerEdges(\n peers: readonly PeerRecord[],\n lockedEdges: ReadonlyMap<EdgeId, string>,\n): ReadonlyMap<EdgeId, string> | undefined {\n if (peers.length === 0 && lockedEdges.size === 0) return undefined\n let claimed: Map<EdgeId, string> | null = null\n const claim = (key: PresenceTargetKey, color: string, override: boolean): void => {\n const edgeId = presenceTargetEdgeId(key)\n if (edgeId === null) return\n claimed ??= new Map()\n if (override || !claimed.has(edgeId)) claimed.set(edgeId, color)\n }\n\n for (const peer of peers) {\n for (const key of peer.selection) claim(key, peer.color, false)\n }\n // Held second and allowed to win: `holding` is the more current fact, the\n // same reason the node pass draws held boxes over selected ones.\n for (const peer of peers) {\n for (const key of peer.holding) claim(key, peer.color, true)\n }\n if (lockedEdges.size > 0) {\n const declared = new Map(peers.map((peer) => [peer.id, peer.color]))\n for (const [edgeId, holderId] of lockedEdges) {\n claimed ??= new Map()\n if (!claimed.has(edgeId)) {\n claimed.set(edgeId, declared.get(holderId) ?? peerColor(holderId))\n }\n }\n }\n return claimed ?? undefined\n}\n\n/**\n * Paint the wires peers are pulling out of handles, onto the foreground.\n *\n * Dashed, like the local pending connection, but in the claimant's colour and\n * with a dot on the loose end — the same vocabulary as their cursor, because\n * that's what the loose end is. Drawn *under* the outlines and above the nodes.\n *\n * The source handle's side comes from this client's own handle registry, which\n * only has the node while it's mounted; a wire out of a culled node falls back\n * to the side its handle type implies, exactly as the local preview does.\n */\nexport function drawPeerPending(\n ctx: CanvasRenderingContext2D,\n peers: readonly PeerRecord[],\n { viewport, size, handles }: PeerPendingDrawParams,\n): void {\n let saved = false\n for (const peer of peers) {\n if (!peer.pending) continue\n const from = worldToScreen(peer.pending.from, viewport)\n const to = worldToScreen(peer.pending.to, viewport)\n // The wire's own bounding box: a drag whose both ends are off-pane has\n // nothing on screen to draw, and the curve stays inside its ends' box.\n const bounds = {\n x: Math.min(from.x, to.x),\n y: Math.min(from.y, to.y),\n width: Math.abs(to.x - from.x),\n height: Math.abs(to.y - from.y),\n }\n if (!onScreen(bounds, size)) continue\n if (!saved) {\n saved = true\n ctx.save()\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n ctx.lineWidth = PENDING_LINE_WIDTH\n ctx.setLineDash(PENDING_DASH)\n }\n const points = buildPendingPath(peer.pending, handles, viewport)\n const [first, ...rest] = points\n if (!first) continue\n ctx.strokeStyle = peer.color\n ctx.beginPath()\n ctx.moveTo(first.x, first.y)\n for (const point of rest) ctx.lineTo(point.x, point.y)\n ctx.stroke()\n // A solid tip where their pointer is, so two wires crossing still read as\n // two people rather than as one tangle.\n ctx.setLineDash([])\n ctx.fillStyle = peer.color\n ctx.beginPath()\n ctx.arc(to.x, to.y, PENDING_TIP_RADIUS, 0, Math.PI * 2)\n ctx.fill()\n ctx.setLineDash(PENDING_DASH)\n }\n if (saved) ctx.restore()\n}\n\n/**\n * Paint every peer's pointer onto the cursor layer.\n *\n * Unlike {@link drawPeerOutlines} this owns its whole canvas, so it clears\n * first — a cursor frame is the only thing that ever writes here, and the\n * arrows have to be erased from wherever they were last frame.\n */\nexport function drawPeerCursors(\n ctx: CanvasRenderingContext2D,\n peers: readonly PeerRecord[],\n { viewport, size }: PeerCursorDrawParams,\n): void {\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n ctx.clearRect(0, 0, size.width, size.height)\n for (const peer of peers) {\n if (!peer.cursor) continue\n const point = worldToScreen(peer.cursor, viewport)\n if (!onScreen({ ...point, width: 0, height: 0 }, size)) continue\n drawCursor(ctx, point, peer.color, peer.name)\n }\n}\n","import { type ResolvedLane, withAlpha } from \"../swimlane/lanes\"\nimport type { Viewport } from \"../types\"\n\nexport type SwimlaneStyle = {\n /** Color of the divider drawn under each lane. */\n separator?: string\n /** Alpha applied to a lane's `color` when tinting its band. */\n tintAlpha?: number\n}\n\nconst DEFAULTS: Required<SwimlaneStyle> = {\n separator: \"rgba(100, 116, 139, 0.28)\",\n tintAlpha: 0.06,\n}\n\n/**\n * Draw swimlanes as full-viewport-width lanes — a low-alpha fill tint for lanes\n * with an explicit `color`, plus a bottom divider per lane (no side borders).\n * Only the vertical position tracks the viewport; horizontally a band always\n * spans the pane. Labels and the group header are sticky DOM overlays. Context\n * is in CSS px.\n */\nexport function drawSwimlanes(\n ctx: CanvasRenderingContext2D,\n width: number,\n height: number,\n viewport: Viewport,\n lanes: ResolvedLane[],\n style?: SwimlaneStyle,\n): void {\n if (lanes.length === 0) return\n const separator = style?.separator ?? DEFAULTS.separator\n const tintAlpha = style?.tintAlpha ?? DEFAULTS.tintAlpha\n\n for (const lane of lanes) {\n if (!lane.color) continue\n const top = viewport.y + lane.top * viewport.zoom\n const bottom = viewport.y + (lane.top + lane.height) * viewport.zoom\n if (bottom < 0 || top > height) continue\n ctx.fillStyle = withAlpha(lane.color, tintAlpha)\n ctx.fillRect(0, top, width, bottom - top)\n }\n\n ctx.strokeStyle = separator\n ctx.lineWidth = 1\n ctx.beginPath()\n for (const lane of lanes) {\n const bottom = viewport.y + (lane.top + lane.height) * viewport.zoom\n if (bottom < 0 || bottom > height) continue\n ctx.moveTo(0, bottom - 0.5)\n ctx.lineTo(width, bottom - 0.5)\n }\n ctx.stroke()\n}\n","import { clamp } from \"@rivet/utils\"\nimport { type RefObject, useEffect, useMemo, useRef, useState } from \"react\"\nimport {\n parseAnchorAutoHandleId,\n parseAnchorHandleId,\n type ResolvedAnchorOptions,\n strayPlacementPct,\n} from \"../anchor/registry\"\nimport { type ConnectionEnd, handleWorldPosition } from \"../connection\"\nimport { DEFAULT_NODE_SIZE, handleKey, SELECTOR } from \"../constants\"\nimport { displayedSideKey, parseSideHandleId } from \"../edge-ends\"\nimport { boundingRect } from \"../graph\"\nimport { startConnectionDrag } from \"../input/connection-drag\"\nimport { createKeyboardHandler } from \"../input/keyboard\"\nimport { keyHeld } from \"../input/keys\"\nimport { createLayerHint } from \"../input/layer-hint\"\nimport { createMarqueeController } from \"../input/marquee-controller\"\nimport { createPanController } from \"../input/pan-controller\"\nimport { createResizeController } from \"../input/resize-controller\"\nimport { createZoomController } from \"../input/zoom-controller\"\nimport type { PeerOutlineMode } from \"../presence/outlines\"\nimport { edgeTargetKey } from \"../presence/targets\"\nimport { drawDotGrid } from \"../renderer/background\"\nimport { PENDING_COLOR, pointOnSide } from \"../renderer/edge-geometry\"\nimport {\n collectPeerEdges,\n drawPeerCursors,\n drawPeerOutlines,\n drawPeerPending,\n} from \"../renderer/presence\"\nimport { drawSwimlanes } from \"../renderer/swimlane\"\nimport type { RivetStore } from \"../store\"\nimport type { ResolvedLane, ViewportElements, VisibleLane } from \"../swimlane/lanes\"\nimport type {\n AlignmentGuide,\n Connection,\n DefaultEdgeOptions,\n EdgeEnd,\n EdgeId,\n EdgeRendererFactory,\n EdgeRendererOptions,\n EdgeTypes,\n FitViewOptions,\n HandlePosition,\n NodeId,\n Rect,\n RivetControls,\n RivetEdge,\n RivetNode,\n Vec2,\n Viewport,\n} from \"../types\"\nimport { rectsIntersect, viewportToCss, visibleWorldRect, worldToScreen, zoomAt } from \"../viewport\"\n\nconst CULL_MARGIN_PX = 240\n/** Default wheel/pinch zoom sensitivity (override via the `zoomSpeed` prop). */\nexport const DEFAULT_ZOOM_SPEED = 0.0015\nconst ZOOM_STEP = 1.2\n/**\n * How long after the last viewport change to drop `will-change: transform` from the\n * node layer, so the browser re-rasterizes DOM text crisply at the current zoom.\n */\nconst WILL_CHANGE_IDLE_MS = 180\n/** Stroke for alignment/snap guide lines. */\nconst GUIDE_COLOR = \"rgba(236, 72, 153, 0.9)\"\n\n/** Paint world-space alignment guides as thin screen-space lines. */\nfunction drawAlignmentGuides(\n ctx: CanvasRenderingContext2D,\n guides: AlignmentGuide[],\n viewport: Viewport,\n size: { dpr: number },\n): void {\n if (guides.length === 0) return\n ctx.save()\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n ctx.strokeStyle = GUIDE_COLOR\n ctx.lineWidth = 1\n ctx.beginPath()\n for (const guide of guides) {\n // +0.5 keeps the 1px line crisp on the pixel grid.\n if (guide.axis === \"x\") {\n const a = worldToScreen({ x: guide.position, y: guide.start }, viewport)\n const b = worldToScreen({ x: guide.position, y: guide.end }, viewport)\n ctx.moveTo(Math.round(a.x) + 0.5, a.y)\n ctx.lineTo(Math.round(b.x) + 0.5, b.y)\n } else {\n const a = worldToScreen({ x: guide.start, y: guide.position }, viewport)\n const b = worldToScreen({ x: guide.end, y: guide.position }, viewport)\n ctx.moveTo(a.x, Math.round(a.y) + 0.5)\n ctx.lineTo(b.x, Math.round(b.y) + 0.5)\n }\n }\n ctx.stroke()\n ctx.restore()\n}\n\n/** Radius of the reconnect affordance bubble drawn at a grabbable edge end. */\nconst ENDPOINT_BUBBLE_RADIUS = 6\n/**\n * Once an edge is hovered, it stays hovered while the pointer remains within\n * this distance of its path — looser than the acquire tolerance so tracking\n * the curve toward a grab bubble doesn't flicker the affordance away.\n */\nconst HOVER_KEEP_TOLERANCE = 16\n\n/** Stand-in for a backend without the claim-anchor seam. Shared, so it allocates nothing. */\nconst EMPTY_EDGE_ANCHORS: ReadonlyMap<EdgeId, Vec2> = new Map()\n\n/**\n * Paint the reconnect affordance: a small grab bubble at each end of the\n * hovered/selected reconnectable edge, in the pending-connection accent so it\n * reads as \"this end is draggable\". Drawn on the foreground canvas (above\n * nodes) since endpoints sit on node borders.\n */\nexport function drawEndpointBubbles(\n ctx: CanvasRenderingContext2D,\n ends: { source: Vec2; target: Vec2 },\n size: { dpr: number },\n): void {\n ctx.save()\n ctx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n // Solid accent fill with a white ring — deliberately the inverse of the\n // white-filled handle dots the bubbles often sit on top of.\n ctx.fillStyle = PENDING_COLOR\n ctx.strokeStyle = \"#ffffff\"\n ctx.lineWidth = 1.5\n for (const point of [ends.source, ends.target]) {\n ctx.beginPath()\n ctx.arc(point.x, point.y, ENDPOINT_BUBBLE_RADIUS, 0, Math.PI * 2)\n ctx.fill()\n ctx.stroke()\n }\n ctx.restore()\n}\n\nexport type RivetRuntimeParams = {\n store: RivetStore\n paneRef: RefObject<HTMLDivElement | null>\n nodeContainerRef: RefObject<HTMLDivElement | null>\n backgroundCanvasRef: RefObject<HTMLCanvasElement | null>\n edgeCanvasRef: RefObject<HTMLCanvasElement | null>\n /** Foreground canvas above the node layer — draws the in-progress connection. */\n foregroundCanvasRef: RefObject<HTMLCanvasElement | null>\n /**\n * Peer-cursor canvas above the foreground, or a ref holding `null` when\n * `presenceOptions.renderCursors` is off. Read fresh each frame rather than\n * captured, so mounting or unmounting the layer doesn't tear the loop down.\n */\n cursorCanvasRef: RefObject<HTMLCanvasElement | null>\n /**\n * Who paints peer claims — rivet's canvas outlines, a DOM layer above them,\n * or nobody. Read fresh each frame for the same reason as the cursor canvas:\n * switching chrome must not tear the loop down.\n */\n outlineMode: PeerOutlineMode\n /** Swimlane lanes to paint behind the graph. Empty when unused. */\n swimlaneLanes: ResolvedLane[]\n /** Registry of custom edge path builders, merged over the built-ins. */\n edgeTypes?: EdgeTypes\n /** Defaults merged into every edge (type, animated, style, markers). */\n defaultEdgeOptions?: DefaultEdgeOptions\n /** Resolved anchor chrome policy — places auto anchor ends along a side. */\n anchorOptions: ResolvedAnchorOptions\n /** Backend factory for the edge layers. Defaults to Canvas2D. */\n edgeRenderer: EdgeRendererFactory\n /** Default for whether edges can be reconnected by dragging an endpoint. */\n edgesReconnectable?: boolean\n /** Veto a proposed connection (shared with drag-to-connect). */\n isValidConnection?: (connection: Connection) => boolean\n /** Rewrite a validated connection before commit; null cancels (shared with drag-to-connect). */\n mapConnection?: (connection: Connection) => Connection | null\n /** Called when an endpoint drag re-points an edge (the edge is already updated). */\n onReconnect?: (edge: RivetEdge, connection: Connection) => void\n /** Called when an endpoint reconnection drag starts. */\n onReconnectStart?: (edge: RivetEdge) => void\n /** Called when an endpoint reconnection drag ends (committed or cancelled). */\n onReconnectEnd?: (edge: RivetEdge) => void\n /** Mouse buttons (`MouseEvent.button` codes) that pan on drag. Empty = never. */\n panButtons: number[]\n /** Draw a marquee on a plain left-drag instead of panning. */\n selectionOnDrag: boolean\n /** Keys that force marquee selection on a left-drag (held before dragging). */\n selectionKeys: string[]\n /** Keys that make a marquee/click add to the selection instead of replacing it. */\n multiSelectionKeys: string[]\n /** Pan on wheel/trackpad scroll instead of zooming (pinch still zooms). */\n scrollToPan: boolean\n /** Wheel/pinch zoom sensitivity — larger zooms faster per delta. */\n zoomSpeed: number\n minZoom: number\n maxZoom: number\n gridGap: number\n snapGrid: [number, number] | null\n}\n\n/**\n * Owns everything that must not go through React on every frame: the rAF loop,\n * pan/zoom input, the imperative node-layer transform, and node culling. Only\n * culling changes (which nodes are mounted) are pushed back into React state.\n */\nexport function useRivetRuntime(params: RivetRuntimeParams): {\n visibleIds: NodeId[]\n controls: RivetControls\n getViewportElements: () => ViewportElements\n} {\n const { store, paneRef, nodeContainerRef } = params\n const { backgroundCanvasRef, edgeCanvasRef, foregroundCanvasRef, cursorCanvasRef } = params\n const { swimlaneLanes, scrollToPan, zoomSpeed } = params\n const { minZoom, maxZoom, gridGap, edgeTypes, defaultEdgeOptions, anchorOptions } = params\n const { edgeRenderer: createEdgeRenderer } = params\n const { panButtons, selectionOnDrag, selectionKeys, multiSelectionKeys } = params\n const [visibleIds, setVisibleIds] = useState<NodeId[]>([])\n\n // Reconnection callbacks read through a ref so their changing identity doesn't\n // tear down the pointer/rAF effect below.\n const reconnectRef = useRef(params)\n reconnectRef.current = params\n\n // Which layer paints peer claims, in a ref for the same reason the cursor\n // canvas is resolved per frame: a consumer swapping their outline component\n // in must not tear down the pointer/rAF effect.\n const outlineModeRef = useRef(params.outlineMode)\n outlineModeRef.current = params.outlineMode\n\n // Current pane pixel size, kept in a ref so the (stable) controls below can\n // read it without re-subscribing.\n const sizeRef = useRef({ width: 0, height: 0, dpr: 1 })\n\n // The visible-node set signature, kept across effect re-runs. If it lived in\n // the effect closure it would reset to \"\" whenever the effect re-mounts (e.g.\n // an unstable prop identity), making the first render push `setVisibleIds`\n // again — that re-render re-mounts the effect, and the two feed each other\n // into an infinite loop whose per-frame `resize()` blanks the canvases.\n const visibleKeyRef = useRef(\"\")\n\n // Lanes change on live resize; keep them in a ref the render loop reads so a\n // resize just repaints the next frame instead of tearing down the rAF effect.\n const swimlaneLanesRef = useRef(swimlaneLanes)\n useEffect(() => {\n swimlaneLanesRef.current = swimlaneLanes\n store.requestRender()\n }, [store, swimlaneLanes])\n\n const controls = useMemo<RivetControls>(\n () => buildControls({ store, sizeRef, minZoom, maxZoom }),\n [store, minZoom, maxZoom],\n )\n\n // Stable imperative query of what's on screen. Reads live size/lanes/viewport\n // from refs, so consumers can inspect the viewport without subscribing to it.\n const getViewportElements = useMemo(\n () => buildViewportQuery({ store, sizeRef, lanesRef: swimlaneLanesRef }),\n [store],\n )\n\n useEffect(() => {\n const pane = paneRef.current\n const bgCanvas = backgroundCanvasRef.current\n const edgeCanvas = edgeCanvasRef.current\n const foregroundCanvas = foregroundCanvasRef.current\n const nodeContainer = nodeContainerRef.current\n if (!pane || !bgCanvas || !edgeCanvas || !foregroundCanvas || !nodeContainer) return\n\n const bgCtx = bgCanvas.getContext(\"2d\")\n if (!bgCtx) return\n const rendererOptions: EdgeRendererOptions = { edgeTypes, defaultEdgeOptions }\n const edgeRenderer = createEdgeRenderer(edgeCanvas, rendererOptions)\n // The in-progress connection is drawn on a canvas above the nodes so it never\n // hides behind them; committed edges stay on `edgeCanvas`, below the nodes.\n const foregroundRenderer = createEdgeRenderer(foregroundCanvas, rendererOptions)\n // Alignment guides paint on the foreground (above nodes) after the edge\n // renderer. Read the 2D context *after* the renderer claimed its own — null\n // for a non-2D custom backend, in which case guides just won't show.\n const fgCtx = foregroundCanvas.getContext(\"2d\")\n\n const size = sizeRef.current\n let frame = 0\n let dirty = true\n /** Set on its own by cursor frames — see {@link drawCursorLayer}. */\n let cursorsDirty = true\n let hoveredEdgeId: string | null = null\n /**\n * Nodes a peer moved on the previous frame. Kept so the frame they let go\n * can put each element back where the graph says it is — React doesn't\n * re-render on presence frames, and shouldn't: they arrive at pointer rate.\n */\n let peerPositioned = new Set<NodeId>()\n\n /**\n * Move the elements peers are dragging, imperatively — the same path a\n * local group drag uses. `worldPositions` already carries their boxes, so\n * this is only the DOM catching up with what everything else already draws.\n */\n const positionPeerNodes = (worldPositions: ReadonlyMap<NodeId, Vec2>) => {\n const transforms = store.presence.getNodeTransforms()\n if (transforms.size === 0 && peerPositioned.size === 0) return\n const current = new Set<NodeId>()\n for (const id of transforms.keys()) {\n current.add(id)\n for (const childId of store.getDescendantIds(id)) current.add(childId)\n }\n for (const id of new Set([...current, ...peerPositioned])) {\n const element = store.getNodeElement(id)\n const world = worldPositions.get(id)\n if (!element || !world) continue\n element.style.transform = `translate(${world.x}px, ${world.y}px)`\n const live = transforms.get(id)\n // A peer mid-resize sends a box; give the element that size until they\n // let go, then hand it back to whatever React last styled.\n if (live && !store.isNodeHeld(id)) {\n element.style.width = `${live.width}px`\n element.style.height = `${live.height}px`\n } else if (peerPositioned.has(id)) {\n element.style.width = \"\"\n element.style.height = \"\"\n }\n }\n peerPositioned = current\n }\n\n // --- peer-cursor layer ---------------------------------------------------\n // Cursors get a canvas of their own because they arrive at pointer rate for\n // every peer while nothing else on screen depends on where they are. On the\n // shared foreground they made the pending connection, the alignment guides\n // and the endpoint bubbles repaint at that rate too, for no reason.\n let cursorCanvas: HTMLCanvasElement | null = null\n let cursorCtx: CanvasRenderingContext2D | null = null\n /** Whether the layer has a backing store matched to the pane yet. */\n let cursorAllocated = false\n\n /**\n * Match the cursor canvas to the pane. Deliberately a no-op until something\n * has actually asked to paint on it: the element mounts with the graph, but\n * a document nobody else is in shouldn't pay for a fourth full-size canvas.\n */\n const sizeCursorLayer = () => {\n if (!cursorCanvas || !cursorAllocated) return\n cursorCanvas.width = Math.max(1, Math.round(size.width * size.dpr))\n cursorCanvas.height = Math.max(1, Math.round(size.height * size.dpr))\n cursorCanvas.style.width = `${size.width}px`\n cursorCanvas.style.height = `${size.height}px`\n }\n\n const drawCursorLayer = () => {\n // Resolved per frame: `renderCursors` mounts and unmounts the element, and\n // that must not cost a teardown of the loop the way a dep change would.\n const canvas = cursorCanvasRef.current\n if (canvas !== cursorCanvas) {\n cursorCanvas = canvas\n cursorCtx = canvas?.getContext(\"2d\") ?? null\n cursorAllocated = false\n }\n if (!cursorCtx) return\n const peers = store.presence.getPeers()\n const wanted = peers.some((peer) => peer.cursor)\n // Nothing to draw and nothing ever drawn: no canvas to clear, no pixels\n // to allocate. Once allocated it keeps clearing, so the last cursor of a\n // peer who left is erased rather than left behind.\n if (!wanted && !cursorAllocated) return\n if (!cursorAllocated) {\n cursorAllocated = true\n sizeCursorLayer()\n }\n drawPeerCursors(cursorCtx, peers, { viewport: store.getViewport(), size })\n }\n\n /**\n * Advance peer interpolation, then ask for whichever frame the motion needs.\n * A moving box changes world positions — and so edges, culling, outlines and\n * the DOM — while a moving cursor changes one canvas. The transform version\n * separates them: the registry bumps it exactly when a rendered box moves.\n */\n const stepPresence = () => {\n const version = store.presence.getTransformVersion()\n if (!store.presence.step(performance.now())) return\n if (store.presence.getTransformVersion() !== version) schedule()\n else scheduleCursors()\n }\n\n // Places an auto-resolved anchor end along a side of its node — the same\n // policy the stray-handle chrome uses, read from the live anchor registry.\n const anchorPlacement = (nodeId: NodeId, anchorId: string, side: HandlePosition) => {\n const record = store.anchors.get(handleKey(nodeId, anchorId))\n return record?.geometry ? strayPlacementPct(record.geometry, side, anchorOptions) : null\n }\n\n // Composable input controllers (see `input/`). The rAF `schedule` is defined\n // further down, so the zoom controller receives it via a thunk. The interwoven\n // pointer stream (pan / marquee / edge hover / reconnect) stays inline below.\n const layerHint = createLayerHint(nodeContainer, WILL_CHANGE_IDLE_MS)\n const zoom = createZoomController({\n store,\n pane,\n size,\n minZoom,\n maxZoom,\n zoomSpeed,\n scrollToPan,\n schedule: () => schedule(),\n })\n\n // Whether a lock lets this client re-point an edge. Asked of the edge\n // itself: reconnection is what an edge lock exists to refuse, and the nodes\n // at either end deliberately allow `connect` while locked. Guarded on the\n // table being non-empty so the single-player frame builds no key at all.\n const canReconnect = (edgeId: EdgeId) =>\n store.locks.size() === 0 || store.locks.allows(edgeTargetKey(edgeId), \"reconnect\")\n\n const render = () => {\n // Advance the zoom ease before reading the viewport so this frame draws the\n // interpolated value.\n zoom.step()\n // Same for peers: ease their cursors and gesture boxes toward the last\n // frame that arrived, and keep asking for frames while anything moves.\n // Stepping here means the world positions read below are already the\n // interpolated ones, so nodes, edges and outlines can't disagree.\n stepPresence()\n const viewport = store.getViewport()\n\n // 1. Node layer follows the viewport imperatively — no React on pan/zoom.\n // The hint promotes the layer while moving, then drops it so text stays crisp.\n layerHint.apply(viewportToCss(viewport))\n\n // 2. Background grid, then the swimlane bands on top of it (behind edges).\n bgCtx.setTransform(size.dpr, 0, 0, size.dpr, 0, 0)\n bgCtx.clearRect(0, 0, size.width, size.height)\n drawDotGrid(bgCtx, size.width, size.height, viewport, { gap: gridGap })\n drawSwimlanes(bgCtx, size.width, size.height, viewport, swimlaneLanesRef.current)\n\n // 3. Committed edges below the nodes; the in-progress connection above them.\n // World positions (parent chains) come from the store's cache — recomputed\n // only when nodes moved, so pan/zoom frames reuse them. Anchors and culling\n // both read it, so nested nodes stay wired to their edges.\n const worldPositions = store.getWorldPositions()\n positionPeerNodes(worldPositions)\n const edgeList = [...store.edges.values()]\n const pending = store.getPending()\n // Under `\"live\"` alignment, edges touching a mid-drag node render both\n // ends as auto; the resolved sides land in the store's displayed-sides\n // memory so the drop commits exactly what was shown.\n const liveAlignNodes =\n store.getEdgeAlignment() === \"live\" && store.isNodeDragging()\n ? store.getDraggingNodeIds()\n : undefined\n // Edges a peer has selected, is holding, or has locked. Built here rather\n // than in the renderer because it's the same merge the node outlines do,\n // and the edge renderer is a swappable seam — a custom backend gets the\n // resolved colours, not the two registries.\n //\n // A consumer's outline component replaces the boxes rivet strokes, not\n // this: DOM can't follow an edge's path, so the halo stays the renderer's\n // job and only `renderOutlines: false` withholds it.\n const outlineMode = outlineModeRef.current\n const peerEdges =\n outlineMode === \"none\"\n ? undefined\n : collectPeerEdges(store.presence.getPeers(), store.locks.getLockedEdges())\n edgeRenderer.draw(edgeList, store.nodes, viewport, {\n handles: store.handles,\n pending: null,\n hovered: hoveredEdgeId,\n reconnecting: pending?.reconnecting ?? null,\n worldPositions,\n displayedSides: store.getDisplayedSides(),\n liveAlignNodes,\n anchorPlacement,\n peerEdges,\n })\n store.setEdgeLabelAnchors(edgeRenderer.getLabels())\n // Points on the claimed edges, for a DOM outline layer — the one piece of\n // its geometry it can't derive itself. Only published when something is\n // there to read it; the canvas paints claims off the map above instead.\n if (outlineMode === \"dom\") {\n store.setPeerEdgeAnchors(edgeRenderer.getPeerEdgeAnchors?.() ?? EMPTY_EDGE_ANCHORS)\n }\n foregroundRenderer.draw([], store.nodes, viewport, {\n handles: store.handles,\n pending,\n })\n // Wires other people are pulling out of handles, under this client's own\n // chrome: their gesture is context for mine, not the other way round.\n if (fgCtx && !store.presence.isEmpty()) {\n drawPeerPending(fgCtx, store.presence.getPeers(), {\n viewport,\n size,\n handles: store.handles,\n })\n }\n\n // Alignment guides, on top of the foreground edges the renderer just drew.\n if (fgCtx) drawAlignmentGuides(fgCtx, store.getAlignmentGuides(), viewport, size)\n\n // Reconnect affordance: grab bubbles at the ends of the hovered/selected\n // reconnectable edge (hidden while that edge is mid-reconnect).\n if (fgCtx) {\n const affordanceId = hoveredEdgeId ?? store.getSelectedEdge()\n const edge = affordanceId ? store.edges.get(affordanceId) : undefined\n const reconnectable = edge\n ? (edge.reconnectable ?? reconnectRef.current.edgesReconnectable)\n : false\n // No grab bubbles on an edge a lock won't let go of — an affordance\n // that refuses on press is worse than no affordance.\n if (edge && reconnectable && edge.id !== pending?.reconnecting && canReconnect(edge.id)) {\n const ends = edgeRenderer.getEndpoints?.().get(edge.id)\n if (ends) drawEndpointBubbles(fgCtx, ends, size)\n }\n }\n\n // Peers, on top of everything: what they have selected, an outline on\n // whatever they're moving this instant, and outlines for what they've\n // locked. Read straight from the registries each frame — neither presence\n // nor locks enters the graph, so this is the only place they exist.\n if (\n fgCtx &&\n outlineMode === \"canvas\" &&\n (!store.presence.isEmpty() || store.locks.size() > 0)\n ) {\n drawPeerOutlines(fgCtx, store.presence.getPeers(), {\n viewport,\n size,\n getNodeRect: (id) => (store.nodes.has(id) ? store.getNodeRect(id) : null),\n locks: store.locks.getLocks(),\n })\n }\n // Their cursors, one layer higher. A full frame owns every layer, so this\n // repaints them too — the viewport they project through just moved.\n drawCursorLayer()\n\n // Animated edges need a fresh frame each tick to march their dashes.\n if (edgeList.some((edge) => edge.animated ?? defaultEdgeOptions?.animated)) schedule()\n\n // 4. Culling — only re-render React when the visible set actually changes.\n const rect = visibleWorldRect(viewport, size.width, size.height)\n const margin = CULL_MARGIN_PX / viewport.zoom\n const view = {\n x: rect.x - margin,\n y: rect.y - margin,\n width: rect.width + margin * 2,\n height: rect.height + margin * 2,\n }\n const ids: NodeId[] = []\n for (const node of store.nodes.values()) {\n const nodeSize = node.size ?? DEFAULT_NODE_SIZE\n const origin = worldPositions.get(node.id) ?? node.position\n // Unmeasured nodes are always mounted so they can report their size.\n if (\n !node.size ||\n rectsIntersect(view, {\n x: origin.x,\n y: origin.y,\n width: nodeSize.width,\n height: nodeSize.height,\n })\n ) {\n ids.push(node.id)\n }\n }\n const key = ids.join(\"|\")\n if (key !== visibleKeyRef.current) {\n visibleKeyRef.current = key\n setVisibleIds(ids)\n }\n\n // 5. Let secondary views (MiniMap, etc.) mirror this frame. A full frame\n // repainted the cursor layer as well, so its channel fires too — DOM\n // cursor chrome has to follow the viewport, not just the pointer.\n store.notifyFrame()\n store.notifyCursorFrame()\n }\n\n const tick = () => {\n frame = 0\n // A full frame owns the cursor layer as well, so it settles both flags —\n // and it wins the tie, because it draws strictly more.\n if (dirty) {\n dirty = false\n cursorsDirty = false\n render()\n return\n }\n if (!cursorsDirty) return\n cursorsDirty = false\n // Cursors are eased like everything else; stepping here is what keeps a\n // cursor-only frame asking for the next one while the ease is running.\n stepPresence()\n drawCursorLayer()\n // The narrow path still ends in a frame notification — for the cursor\n // channel alone. Without it, chrome rendered off `subscribeCursorFrame`\n // (the DOM cursor layer, or a consumer's own) would only ever update when\n // something unrelated forced a full repaint.\n store.notifyCursorFrame()\n }\n const schedule = () => {\n dirty = true\n if (frame) return\n frame = requestAnimationFrame(tick)\n }\n const scheduleCursors = () => {\n cursorsDirty = true\n if (frame) return\n frame = requestAnimationFrame(tick)\n }\n\n // Every canvas-affecting mutation calls store.requestRender(); route it here.\n store.bindRenderRequester(schedule)\n // Cursor frames take the narrow path — one canvas, no culling, no DOM.\n store.bindCursorRenderRequester(scheduleCursors)\n\n const setEdgeHover = (id: string | null) => {\n if (hoveredEdgeId === id) return\n hoveredEdgeId = id\n schedule()\n }\n\n // Pointer gestures the dispatcher below drives (the pane owns the listeners).\n const pan = createPanController({ store, pane, schedule })\n const marquee = createMarqueeController({ store, pane })\n\n // Tracks non-modifier keys for the configurable key props; modifier keys read\n // straight off the pointer event via getModifierState, so they never go stale.\n const pressedKeys = new Set<string>()\n const selectionKeyHeld = (event: PointerEvent) => keyHeld(event, selectionKeys, pressedKeys)\n const multiSelectHeld = (event: PointerEvent) => keyHeld(event, multiSelectionKeys, pressedKeys)\n\n // Start a marquee, clearing any edge hover first — the runtime owns hover state.\n const startMarquee = (event: PointerEvent, px: number, py: number) => {\n setEdgeHover(null)\n marquee.start(event, px, py, multiSelectHeld(event))\n }\n\n // World position of an edge end, matching the renderer's resolution: the\n // registered handle if any; else the pinned or last-displayed side (placed\n // at the anchor's measured row/column when the end is an anchor end); else\n // the node's right (source) / left (target) mid-edge.\n const endpointWorld = (\n edge: RivetEdge,\n nodeId: NodeId,\n handleId: string | undefined,\n role: EdgeEnd,\n ): Vec2 => {\n if (handleId) {\n const record = store.handles.get(handleKey(nodeId, handleId))\n if (record) {\n const wp = handleWorldPosition(store, { nodeId, handleId, type: record.type })\n if (wp) return wp\n }\n }\n const side =\n parseAnchorHandleId(handleId)?.side ??\n parseSideHandleId(handleId) ??\n store.getDisplayedSides().get(displayedSideKey(edge.id, role))\n if (side) {\n const anchorId =\n parseAnchorAutoHandleId(handleId) ?? parseAnchorHandleId(handleId)?.anchorId\n const pct = anchorId ? (anchorPlacement(nodeId, anchorId, side) ?? undefined) : undefined\n return pointOnSide(store.getNodeRect(nodeId), side, pct)\n }\n const node = store.nodes.get(nodeId)\n const size = node?.size ?? DEFAULT_NODE_SIZE\n const base = store.getNodeWorldPosition(nodeId)\n const x = role === \"source\" ? base.x + size.width : base.x\n return { x, y: base.y + size.height / 2 }\n }\n\n // Drag an existing edge's loose end to a new handle. The other end stays put.\n const beginReconnect = (edge: RivetEdge, end: EdgeEnd) => {\n // The authoritative refusal: both entry points (the pane's endpoint grab\n // and <Handle>'s delegate) come through here, so neither can route around\n // it, and the affordance checks below only keep the UI honest.\n if (!canReconnect(edge.id)) return\n zoom.cancel()\n const fixedIsSource = end === \"target\"\n const fixedNodeId = fixedIsSource ? edge.source : edge.target\n const fixedHandleId = fixedIsSource ? edge.sourceHandle : edge.targetHandle\n const from: ConnectionEnd = {\n nodeId: fixedNodeId,\n handleId: fixedHandleId ?? \"\",\n type: fixedIsSource ? \"source\" : \"target\",\n }\n const fixedWorld = endpointWorld(\n edge,\n fixedNodeId,\n fixedHandleId,\n fixedIsSource ? \"source\" : \"target\",\n )\n const looseWorld = endpointWorld(\n edge,\n fixedIsSource ? edge.target : edge.source,\n fixedIsSource ? edge.targetHandle : edge.sourceHandle,\n fixedIsSource ? \"target\" : \"source\",\n )\n startConnectionDrag({\n store,\n paneRef,\n from,\n begin: {\n source: from.nodeId,\n sourceHandle: from.handleId,\n sourceType: from.type,\n from: fixedWorld,\n to: looseWorld,\n reconnecting: edge.id,\n },\n // Callbacks read `reconnectRef.current` when the drag ends, so a late\n // prop change (this effect never re-runs on callback identity) is honored.\n validate: (connection) => reconnectRef.current.isValidConnection?.(connection) ?? true,\n map: (connection) => {\n // `null` from the consumer means \"cancel the drop\" — must propagate.\n const mapFn = reconnectRef.current.mapConnection\n return mapFn ? mapFn(connection) : connection\n },\n commit: (connection) => {\n store.reconnectEdge(edge.id, connection)\n reconnectRef.current.onReconnect?.(edge, connection)\n },\n onEnd: () => reconnectRef.current.onReconnectEnd?.(edge),\n })\n reconnectRef.current.onReconnectStart?.(edge)\n }\n\n // Gateway for <Handle>: a press on a handle that coincides with a\n // reconnectable edge's endpoint moves that edge instead of starting a new\n // connection (the handle's DOM otherwise shadows the endpoint grab zone).\n // Gated on the affordance: the edge must be hovered or selected — i.e. its\n // grab bubbles are showing — so a cold press on an occupied handle still\n // starts a NEW connection (the user never \"picked up\" the edge).\n store.bindReconnectDelegate({\n pickEndpoint: (clientX, clientY) => {\n const rect = pane.getBoundingClientRect()\n const hit = edgeRenderer.pickEndpoint(clientX - rect.left, clientY - rect.top)\n if (!hit) return null\n if (hit.edgeId !== hoveredEdgeId && hit.edgeId !== store.getSelectedEdge()) return null\n const edge = store.edges.get(hit.edgeId)\n const reconnectable = edge\n ? (edge.reconnectable ?? reconnectRef.current.edgesReconnectable)\n : false\n // A locked edge declines the gateway rather than swallowing the press:\n // the handle underneath goes on to start a new connection, which is\n // what it would have done if the edge weren't there at all.\n return reconnectable && canReconnect(hit.edgeId) ? hit : null\n },\n begin: (edgeId, end) => {\n const edge = store.edges.get(edgeId)\n if (edge) beginReconnect(edge, end)\n },\n })\n\n const onPointerDown = (event: PointerEvent) => {\n // A press anywhere retires a keyboard-started pending connection — it has\n // no drag gesture to end it. Safe for pointer flows: they begin *after*\n // this native listener (in React handlers), so their pending isn't set yet.\n if (store.getPending()) store.endConnection()\n // The pane's native listener fires before React's synthetic node handler,\n // so we can't rely on stopPropagation — check the origin element instead.\n // Nodes drag themselves; swimlane resize handles own their own gesture; and\n // `data-nopan` elements (overlay controls, toolbars…) keep their own pointer.\n if (event.target instanceof Element && event.target.closest(SELECTOR.paneGestureExempt)) {\n return\n }\n const rect = pane.getBoundingClientRect()\n const px = event.clientX - rect.left\n const py = event.clientY - rect.top\n\n // Middle/right buttons only ever pan (when configured); no edge/selection.\n if (event.button !== 0) {\n if (panButtons.includes(event.button)) {\n event.preventDefault() // suppress middle-click autoscroll\n zoom.cancel()\n pan.start(event)\n }\n return\n }\n\n // A new gesture cancels any in-flight zoom ease.\n zoom.cancel()\n\n // Holding the selection key forces a marquee over any pan behavior.\n if (selectionKeyHeld(event)) {\n startMarquee(event, px, py)\n return\n }\n // Grabbing an edge near its endpoint starts a reconnection (takes priority\n // over selecting the edge body).\n const endpointHit = edgeRenderer.pickEndpoint(px, py)\n if (endpointHit) {\n const edge = store.edges.get(endpointHit.edgeId)\n const reconnectable = edge?.reconnectable ?? reconnectRef.current.edgesReconnectable\n if (edge && reconnectable) {\n beginReconnect(edge, endpointHit.end)\n return\n }\n }\n // Clicking a selectable edge selects it instead of panning. An edge with\n // `selectable: false` is click-through (still deselects on empty space below).\n // A locked edge is neither: the press stops here rather than falling\n // through to a marquee, the same way a locked node's press does.\n const hitEdge = edgeRenderer.pick(px, py)\n if (hitEdge && store.edges.get(hitEdge)?.selectable !== false) {\n if (store.locks.allows(edgeTargetKey(hitEdge), \"select\")) store.selectEdge(hitEdge)\n return\n }\n // Empty space: deselect, then marquee or pan per config.\n store.selectNode(null)\n if (selectionOnDrag) {\n startMarquee(event, px, py)\n return\n }\n if (panButtons.includes(0)) pan.start(event)\n }\n const onPointerMove = (event: PointerEvent) => {\n const rect = pane.getBoundingClientRect()\n const px = event.clientX - rect.left\n const py = event.clientY - rect.top\n\n if (marquee.isActive()) {\n marquee.move(px, py)\n return\n }\n if (pan.isPanning()) {\n pan.move(event)\n return\n }\n // Hover feedback: pointer cursor + highlight when over an edge (but not\n // over a node or the post-marquee selection box, and not mid-connection).\n if (store.getPending()) return\n const overNode =\n event.target instanceof Element &&\n event.target.closest(`${SELECTOR.node}, ${SELECTOR.nodesSelection}`)\n let overEdge = overNode ? null : edgeRenderer.pick(px, py)\n // Hysteresis: hover is *acquired* at the tight pick tolerance, but *kept*\n // while the pointer stays loosely near the hovered edge or within its\n // endpoint radius (even across a node border) — so traveling to a grab\n // bubble doesn't drop the affordance mid-way. Hover is never acquired\n // from proximity alone: a cold press on an occupied handle still means\n // \"new connection\".\n if (!overEdge && hoveredEdgeId) {\n const near =\n edgeRenderer.pick(px, py, HOVER_KEEP_TOLERANCE) === hoveredEdgeId ||\n edgeRenderer.pickEndpoint(px, py)?.edgeId === hoveredEdgeId\n if (near) overEdge = hoveredEdgeId\n }\n pane.style.cursor = overEdge ? \"pointer\" : \"\"\n setEdgeHover(overEdge)\n }\n const onPointerUp = (event: PointerEvent) => {\n if (marquee.isActive()) {\n marquee.end(event)\n return\n }\n pan.end(event)\n }\n\n // Read through the params ref so toggling `snapGrid` doesn't tear down and\n // re-install every pane listener this effect owns.\n const onKeyDown = createKeyboardHandler(store, () => reconnectRef.current.snapGrid)\n\n // Programmatic focus (store.setFocusedNode) moves real DOM focus to the\n // node's wrapper. A culled node has no DOM — center the viewport on it and\n // focus once the next culling pass mounts it. Wrapper-driven focus (the\n // user tabbing) re-enters here with the element already focused: no-op.\n let focusRetryFrame = 0\n const unsubscribeFocus = store.subscribeFocus((id) => {\n if (focusRetryFrame) {\n cancelAnimationFrame(focusRetryFrame)\n focusRetryFrame = 0\n }\n if (id === null) return\n const el = store.getNodeElement(id)\n if (el) {\n if (document.activeElement !== el) el.focus()\n return\n }\n controls.centerNode(id)\n let tries = 0\n const attempt = () => {\n focusRetryFrame = 0\n const mounted = store.getNodeElement(id)\n if (mounted) {\n mounted.focus()\n return\n }\n if (++tries < 10) focusRetryFrame = requestAnimationFrame(attempt)\n }\n focusRetryFrame = requestAnimationFrame(attempt)\n })\n\n // Swallow the context menu after a right-button pan actually moved.\n const onContextMenu = (event: MouseEvent) => {\n if (!pan.suppressNextContextMenu()) return\n event.preventDefault()\n event.stopPropagation()\n }\n // Track non-modifier keys for `selectionKeys`; clear on blur so a key held\n // across a focus change can't get stuck.\n const onTrackKeyDown = (event: KeyboardEvent) => pressedKeys.add(event.key)\n const onTrackKeyUp = (event: KeyboardEvent) => pressedKeys.delete(event.key)\n const clearPressedKeys = () => pressedKeys.clear()\n\n const resizer = createResizeController({\n pane,\n bgCanvas,\n size,\n edgeRenderer,\n foregroundRenderer,\n onResize: sizeCursorLayer,\n schedule,\n })\n\n pane.addEventListener(\"wheel\", zoom.onWheel, { passive: false })\n pane.addEventListener(\"pointerdown\", onPointerDown)\n pane.addEventListener(\"pointermove\", onPointerMove)\n pane.addEventListener(\"pointerup\", onPointerUp)\n pane.addEventListener(\"pointercancel\", onPointerUp)\n pane.addEventListener(\"contextmenu\", onContextMenu, { capture: true })\n window.addEventListener(\"keydown\", onKeyDown)\n window.addEventListener(\"keydown\", onTrackKeyDown)\n window.addEventListener(\"keyup\", onTrackKeyUp)\n window.addEventListener(\"blur\", clearPressedKeys)\n\n return () => {\n resizer.dispose()\n store.bindRenderRequester(() => {})\n store.bindCursorRenderRequester(null)\n store.bindReconnectDelegate(null)\n unsubscribeFocus()\n if (focusRetryFrame) cancelAnimationFrame(focusRetryFrame)\n if (frame) cancelAnimationFrame(frame)\n layerHint.dispose()\n pane.removeEventListener(\"wheel\", zoom.onWheel)\n pane.removeEventListener(\"pointerdown\", onPointerDown)\n pane.removeEventListener(\"pointermove\", onPointerMove)\n pane.removeEventListener(\"pointerup\", onPointerUp)\n pane.removeEventListener(\"pointercancel\", onPointerUp)\n pane.removeEventListener(\"contextmenu\", onContextMenu, { capture: true })\n window.removeEventListener(\"keydown\", onKeyDown)\n window.removeEventListener(\"keydown\", onTrackKeyDown)\n window.removeEventListener(\"keyup\", onTrackKeyUp)\n window.removeEventListener(\"blur\", clearPressedKeys)\n marquee.dispose()\n edgeRenderer.dispose()\n foregroundRenderer.dispose()\n }\n }, [\n store,\n controls,\n paneRef,\n nodeContainerRef,\n backgroundCanvasRef,\n edgeCanvasRef,\n foregroundCanvasRef,\n cursorCanvasRef,\n scrollToPan,\n zoomSpeed,\n minZoom,\n maxZoom,\n gridGap,\n edgeTypes,\n defaultEdgeOptions,\n anchorOptions,\n createEdgeRenderer,\n panButtons,\n selectionOnDrag,\n selectionKeys,\n multiSelectionKeys,\n ])\n\n return { visibleIds, controls, getViewportElements }\n}\n\ntype BuildViewportQueryParams = {\n store: RivetStore\n sizeRef: RefObject<{ width: number; height: number; dpr: number }>\n lanesRef: RefObject<ResolvedLane[]>\n}\n\n/**\n * Build the stable `getViewportElements` query. It reads the live pane size,\n * lanes, and viewport from refs on every call, so it never needs to subscribe\n * to viewport changes — inspecting the viewport costs nothing until you ask.\n */\nfunction buildViewportQuery({\n store,\n sizeRef,\n lanesRef,\n}: BuildViewportQueryParams): () => ViewportElements {\n return () => {\n const { width, height } = sizeRef.current\n const rect = visibleWorldRect(store.getViewport(), width, height)\n\n const nodes: RivetNode[] = []\n for (const node of store.nodes.values()) {\n if (rectsIntersect(store.getNodeRect(node.id), rect)) nodes.push(node)\n }\n\n const lanes: VisibleLane[] = []\n for (const lane of lanesRef.current) {\n // Lanes paint as full-viewport-width bands, so only vertical overlap decides\n // visibility. `lane.x`/`lane.width` are nominal and must NOT gate it — else a\n // lane vanishes from the query once you pan past its nominal right edge.\n const overlapH =\n Math.min(lane.top + lane.height, rect.y + rect.height) - Math.max(lane.top, rect.y)\n if (overlapH <= 0) continue\n lanes.push({ ...lane, visibleArea: overlapH * rect.width })\n }\n lanes.sort((a, b) => b.visibleArea - a.visibleArea)\n\n return { rect, nodes, lanes }\n }\n}\n\ntype BuildControlsParams = {\n store: RivetStore\n sizeRef: RefObject<{ width: number; height: number; dpr: number }>\n minZoom: number\n maxZoom: number\n}\n\nconst sameViewport = (a: Viewport, b: Viewport): boolean =>\n a.x === b.x && a.y === b.y && a.zoom === b.zoom\n\n/** Ease-in-out cubic — the standard smooth accel/decel curve for viewport tweens. */\nconst easeInOutCubic = (t: number): number => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2)\n\n/**\n * The imperative viewport controls. Kept out of the effect so they're stable\n * across renders; they read the live pane size from `sizeRef`.\n */\nfunction buildControls({ store, sizeRef, minZoom, maxZoom }: BuildControlsParams): RivetControls {\n // In-flight viewport tween. `written` is the last value we set, so the loop\n // can detect when something else (a user pan/zoom, another control) moved the\n // viewport and bail rather than fight it.\n let animId: number | null = null\n let written: Viewport | null = null\n\n const cancelAnim = () => {\n if (animId !== null) cancelAnimationFrame(animId)\n animId = null\n written = null\n }\n\n const commit = (viewport: Viewport) => {\n store.setViewport(viewport)\n store.requestRender()\n }\n\n /** Move to `target`, instantly or tweened over `duration` ms. */\n const applyViewport = (target: Viewport, duration?: number) => {\n cancelAnim()\n const from = store.getViewport()\n if (!duration || duration <= 0 || sameViewport(from, target)) {\n commit(target)\n return\n }\n const start = performance.now()\n const step = (now: number) => {\n // Someone else drove the viewport since our last frame — yield to them.\n if (written && !sameViewport(store.getViewport(), written)) {\n animId = null\n written = null\n return\n }\n const t = Math.min(1, (now - start) / duration)\n const e = easeInOutCubic(t)\n commit({\n x: from.x + (target.x - from.x) * e,\n y: from.y + (target.y - from.y) * e,\n zoom: from.zoom + (target.zoom - from.zoom) * e,\n })\n // Read back post-clamp so divergence detection compares apples to apples.\n written = store.getViewport()\n if (t < 1) {\n animId = requestAnimationFrame(step)\n } else {\n animId = null\n written = null\n }\n }\n animId = requestAnimationFrame(step)\n }\n\n const zoomToLevel = (nextZoom: number) => {\n cancelAnim()\n const { width, height } = sizeRef.current\n const anchor = { x: width / 2, y: height / 2 }\n commit(zoomAt(store.getViewport(), anchor, nextZoom, minZoom, maxZoom))\n }\n\n /** Zoom+pan so a world rect fills the pane (minus padding) and sits centered. */\n const frameBounds = (rect: Rect, options?: FitViewOptions) => {\n const { width, height } = sizeRef.current\n if (width === 0 || height === 0) return\n const padding = options?.padding ?? 0.1\n const availWidth = width * (1 - padding * 2)\n const availHeight = height * (1 - padding * 2)\n // Guard degenerate (zero-size) bounds so we don't divide by zero.\n const fitZoom = Math.min(\n rect.width > 0 ? availWidth / rect.width : maxZoom,\n rect.height > 0 ? availHeight / rect.height : maxZoom,\n )\n const zoom = clamp(fitZoom, minZoom, options?.maxZoom ?? maxZoom)\n const centerX = rect.x + rect.width / 2\n const centerY = rect.y + rect.height / 2\n applyViewport(\n { zoom, x: width / 2 - centerX * zoom, y: height / 2 - centerY * zoom },\n options?.duration,\n )\n }\n\n /** World bounding rect over a set of node ids, or null when none exist. */\n const boundsOfNodes = (ids: Iterable<NodeId>): Rect | null =>\n boundingRect([...ids].map((id) => store.getNodeRect(id)))\n\n return {\n zoomIn: () => zoomToLevel(store.getViewport().zoom * ZOOM_STEP),\n zoomOut: () => zoomToLevel(store.getViewport().zoom / ZOOM_STEP),\n zoomTo: (zoom) => zoomToLevel(zoom),\n fitView: (options) => {\n const rect = boundsOfNodes(store.nodes.keys())\n if (rect) frameBounds(rect, options)\n },\n fitSelection: (options) => {\n const rect = boundsOfNodes(store.getSelectedNodes())\n if (rect) frameBounds(rect, options)\n },\n fitBounds: (rect, options) => frameBounds(rect, options),\n centerNode: (id, options) => {\n if (!store.nodes.has(id)) return\n const { width, height } = sizeRef.current\n if (width === 0 || height === 0) return\n\n const box = store.getNodeRect(id)\n const zoom = clamp(options?.zoom ?? store.getViewport().zoom, minZoom, maxZoom)\n const centerX = box.x + box.width / 2\n const centerY = box.y + box.height / 2\n applyViewport(\n { zoom, x: width / 2 - centerX * zoom, y: height / 2 - centerY * zoom },\n options?.duration,\n )\n },\n getViewport: () => store.getViewport(),\n setViewport: (viewport) => {\n cancelAnim()\n commit(viewport)\n },\n }\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\"\nimport type { RivetStore } from \"../store\"\nimport {\n flattenLanes,\n type ResolvedLane,\n type ResolvedMargin,\n type ResolvedSwimlaneGroup,\n requiredLaneHeight,\n resolveMargin,\n resolveSwimlanes,\n} from \"../swimlane/lanes\"\nimport type { SwimlaneGroup, SwimlaneMargin, SwimlaneSizeChange } from \"../types\"\n\nexport type UseSwimlanesParams = {\n store: RivetStore\n swimlane?: SwimlaneGroup[]\n swimlaneMargin?: number | SwimlaneMargin\n swimlaneResizable?: boolean\n clampToSwimlane?: boolean\n /** Fraction of the last lane kept in view at the bottom-scroll stop. */\n swimlaneBottomReveal: number\n onSwimlaneSizeChange?: (change: SwimlaneSizeChange) => void\n}\n\nexport type SwimlanesResult = {\n /** Resolved groups (header + lanes, world space). Empty when unused. */\n groups: ResolvedSwimlaneGroup[]\n /** Every group's lanes, flattened — the clamp targets. */\n lanes: ResolvedLane[]\n /** Inner clearance kept between a clamped node and its lane edges. */\n margin: ResolvedMargin\n /** Whether node drags are bounded to a lane (clamp requested AND lanes exist). */\n clampEnabled: boolean\n /** Whether lanes show a bottom resize handle. */\n resizableEnabled: boolean\n /**\n * Resize a lane, floored at the height needed to keep its lowest node inside.\n * `commit` fires `onSwimlaneSizeChange`; `reason` tags it (`\"resize\"` drag vs\n * `\"autofit\"` fit-to-content).\n */\n resizeSwimlane: (\n laneId: string,\n height: number,\n commit: boolean,\n reason?: SwimlaneSizeChange[\"reason\"],\n ) => void\n}\n\n/**\n * Owns the swimlane subsystem: live per-lane heights (seeded from / overriding\n * the `swimlane` prop), resolution to world geometry, the resize floor, auto-fit\n * growth to contain nodes, and the swimlane-aware viewport clamp. Lane sizing is\n * graph-owned React state, notified out via `onSwimlaneSizeChange`.\n */\nexport function useSwimlanes(params: UseSwimlanesParams): SwimlanesResult {\n const { store, swimlane, swimlaneMargin, swimlaneResizable } = params\n const { clampToSwimlane, swimlaneBottomReveal, onSwimlaneSizeChange } = params\n\n // Live height per lane (seeded from / overriding the `swimlane` prop) so sizing\n // is owned by the graph — user resizes and auto-fit write here.\n const [laneHeights, setLaneHeights] = useState<Record<string, number>>({})\n const resizableEnabled = (swimlaneResizable ?? true) && Boolean(swimlane?.length)\n\n const effectiveSwimlane = useMemo<SwimlaneGroup[] | undefined>(() => {\n if (!swimlane) return undefined\n if (Object.keys(laneHeights).length === 0) return swimlane\n return swimlane.map((group) => ({\n ...group,\n lanes: group.lanes.map((lane) => ({\n ...lane,\n size: laneHeights[lane.id] ?? lane.size,\n })),\n }))\n }, [swimlane, laneHeights])\n\n const groups = useMemo(\n () => (effectiveSwimlane ? resolveSwimlanes(effectiveSwimlane) : []),\n [effectiveSwimlane],\n )\n const lanes = useMemo(() => flattenLanes(groups), [groups])\n const margin = useMemo(() => resolveMargin(swimlaneMargin), [swimlaneMargin])\n const clampEnabled = (clampToSwimlane ?? true) && lanes.length > 0\n\n // Refs so the stable `resizeSwimlane` and the auto-fit subscription read live\n // geometry/margins/callbacks without churning identity on every resize frame.\n const lanesRef = useRef(lanes)\n lanesRef.current = lanes\n const marginRef = useRef(margin)\n marginRef.current = margin\n const onSizeChangeRef = useRef(onSwimlaneSizeChange)\n onSizeChangeRef.current = onSwimlaneSizeChange\n\n const resizeSwimlane = useCallback<SwimlanesResult[\"resizeSwimlane\"]>(\n (laneId, height, commit, reason = \"resize\") => {\n const lane = lanesRef.current.find((l) => l.id === laneId)\n if (!lane) return\n // Can't shrink below what's needed to keep the lane's lowest node inside.\n const min = requiredLaneHeight(lane, store.nodes.values(), marginRef.current.bottom)\n const next = Math.max(min, height)\n setLaneHeights((prev) => (prev[laneId] === next ? prev : { ...prev, [laneId]: next }))\n if (commit) onSizeChangeRef.current?.({ laneId, height: next, reason })\n },\n [store],\n )\n\n // Auto-fit: when a node grows past its lane's bottom (with margin), grow the\n // lane to contain it. Expand-only, and paused during a node drag so a node's\n // transient position can't inflate lanes. Runs on rendered frames (node\n // measure, move-commit, add/remove) — not continuously.\n useEffect(() => {\n if (!clampEnabled) return\n return store.subscribeFrame(() => {\n if (store.isNodeDragging()) return\n const marginBottom = marginRef.current.bottom\n const grown: Record<string, number> = {}\n for (const lane of lanesRef.current) {\n const need = requiredLaneHeight(lane, store.nodes.values(), marginBottom)\n if (need > lane.height + 0.5) grown[lane.id] = need\n }\n const entries = Object.entries(grown)\n if (entries.length === 0) return\n setLaneHeights((prev) => ({ ...prev, ...grown }))\n for (const [id, height] of entries) {\n onSizeChangeRef.current?.({ laneId: id, height, reason: \"autofit\" })\n }\n })\n }, [store, clampEnabled])\n\n // With clamping on, bound panning to the swimlane box: top-left corner stays\n // pinned (no scroll up/left past the lanes) and the bottom stops once only\n // `swimlaneBottomReveal` of the last lane remains in view.\n useEffect(() => {\n if (!clampEnabled) {\n store.setViewportClamp(null)\n return\n }\n const minX = Math.min(...groups.map((group) => group.x))\n const minY = Math.min(...groups.map((group) => group.top))\n const last = lanes.reduce((a, b) => (b.top + b.height > a.top + a.height ? b : a))\n const maxY = last.top + (1 - swimlaneBottomReveal) * last.height\n store.setViewportClamp({ minX, minY, maxY })\n return () => store.setViewportClamp(null)\n }, [store, clampEnabled, groups, lanes, swimlaneBottomReveal])\n\n return { groups, lanes, margin, clampEnabled, resizableEnabled, resizeSwimlane }\n}\n","import type {\n DefaultEdgeOptions,\n EdgeDrawExtras,\n EdgeEnd,\n EdgeId,\n EdgeMarker,\n EdgeRenderer,\n EdgeRendererFactory,\n EdgeRendererOptions,\n EdgeTypes,\n NodeId,\n RivetEdge,\n RivetNode,\n Vec2,\n Viewport,\n} from \"../types\"\nimport {\n buildEdges,\n buildPendingPath,\n distanceToPolyline,\n EDGE_WIDTH,\n PENDING_COLOR,\n polylineMidpoint,\n type ResolvedEdge,\n} from \"./edge-geometry\"\nimport { BUILTIN_EDGE_TYPES } from \"./edge-paths\"\n\nconst PICK_TOLERANCE = 6\nconst ENDPOINT_RADIUS = 12\nconst ARROW_SIZE = 9\n/** px/second the marching-dash animation advances. */\nconst DASH_SPEED = 40\n/** How far the peer-claim halo extends past the edge's own stroke, each side. */\nconst PEER_HALO_EXTRA = 6\nconst PEER_HALO_ALPHA = 0.45\n\n/**\n * The default {@link EdgeRenderer}. Strokes each edge's sampled polyline (built by\n * its {@link EdgePathFn}) on a 2D canvas, with per-edge style, arrowheads, and an\n * animated dash. The geometry it draws comes from {@link buildEdges}, which is\n * backend-neutral.\n */\nexport class Canvas2DEdgeRenderer implements EdgeRenderer {\n private readonly ctx: CanvasRenderingContext2D\n private dpr = 1\n private width = 0\n private height = 0\n private readonly edgeTypes: EdgeTypes\n private readonly defaults: DefaultEdgeOptions\n /** Screen-space polylines from the last frame, keyed by edge id, for picking. */\n private readonly geometry = new Map<EdgeId, Vec2[]>()\n /** Screen-space endpoints per edge, for endpoint (reconnection) picking. */\n private readonly endpoints = new Map<EdgeId, { source: Vec2; target: Vec2 }>()\n /** Screen-space label anchor per edge that has a label. */\n private readonly labels = new Map<EdgeId, Vec2>()\n /** Screen-space midpoint per edge somebody has claimed, for DOM claim chrome. */\n private readonly peerAnchors = new Map<EdgeId, Vec2>()\n\n constructor(\n private readonly canvas: HTMLCanvasElement,\n options: EdgeRendererOptions = {},\n ) {\n const ctx = canvas.getContext(\"2d\")\n if (!ctx) throw new Error(\"rivet: 2D canvas context is unavailable\")\n this.ctx = ctx\n this.edgeTypes = { ...BUILTIN_EDGE_TYPES, ...options.edgeTypes }\n this.defaults = options.defaultEdgeOptions ?? {}\n }\n\n resize(width: number, height: number, dpr: number): void {\n this.width = width\n this.height = height\n this.dpr = dpr\n this.canvas.width = Math.max(1, Math.round(width * dpr))\n this.canvas.height = Math.max(1, Math.round(height * dpr))\n this.canvas.style.width = `${width}px`\n this.canvas.style.height = `${height}px`\n }\n\n /** Screen-space label anchors for the edges drawn last frame. */\n getLabels(): Map<EdgeId, Vec2> {\n return this.labels\n }\n\n /** Screen-space midpoints for the edges a peer had claimed last frame. */\n getPeerEdgeAnchors(): ReadonlyMap<EdgeId, Vec2> {\n return this.peerAnchors\n }\n\n /** Screen-space endpoints per edge from the last frame (reconnect affordance). */\n getEndpoints(): ReadonlyMap<EdgeId, { source: Vec2; target: Vec2 }> {\n return this.endpoints\n }\n\n draw(\n edges: RivetEdge[],\n nodes: Map<NodeId, RivetNode>,\n viewport: Viewport,\n extras?: EdgeDrawExtras,\n ): void {\n const ctx = this.ctx\n const now = performance.now()\n ctx.setTransform(this.dpr, 0, 0, this.dpr, 0, 0)\n ctx.clearRect(0, 0, this.width, this.height)\n ctx.lineJoin = \"round\"\n ctx.lineCap = \"round\"\n this.geometry.clear()\n this.endpoints.clear()\n this.labels.clear()\n this.peerAnchors.clear()\n\n const resolved = buildEdges(edges, nodes, viewport, this.edgeTypes, this.defaults, extras)\n const peerEdges = extras?.peerEdges\n for (const edge of resolved) {\n this.geometry.set(edge.id, edge.points)\n this.endpoints.set(edge.id, { source: edge.source, target: edge.target })\n if (edge.label) this.labels.set(edge.id, edge.label)\n\n // Somebody else's claim goes *under* the edge, widened and translucent,\n // so the edge keeps its own stroke — its selected/hovered colour still\n // reads, and the claim is the glow around it rather than a repaint.\n const peerColor = peerEdges?.get(edge.id)\n if (peerColor) {\n // Published for DOM claim chrome, which can't follow a path and needs a\n // point on it. Measured along the polyline rather than taken from the\n // label anchor, so a step edge's chip lands on the route it draws.\n this.peerAnchors.set(edge.id, polylineMidpoint(edge.points))\n ctx.strokeStyle = peerColor\n ctx.lineWidth = edge.width + PEER_HALO_EXTRA * 2\n ctx.globalAlpha = PEER_HALO_ALPHA\n ctx.setLineDash([])\n ctx.lineDashOffset = 0\n strokePolyline(ctx, edge.points)\n }\n\n ctx.strokeStyle = edge.stroke\n ctx.lineWidth = edge.width\n ctx.globalAlpha = edge.opacity\n if (edge.animated) {\n ctx.setLineDash([8, 6])\n ctx.lineDashOffset = -((now / 1000) * DASH_SPEED) % 14\n } else if (edge.dash) {\n ctx.setLineDash(edge.dash)\n ctx.lineDashOffset = 0\n } else {\n ctx.setLineDash([])\n ctx.lineDashOffset = 0\n }\n\n strokePolyline(ctx, edge.points)\n\n // Markers use the solid stroke color at full alpha and no dash.\n ctx.setLineDash([])\n ctx.globalAlpha = 1\n const markerColor = ctx.strokeStyle\n if (edge.markerEnd) drawMarker(ctx, edge.points, \"end\", edge.markerEnd, markerColor)\n if (edge.markerStart) drawMarker(ctx, edge.points, \"start\", edge.markerStart, markerColor)\n }\n\n const pending = extras?.pending\n if (pending) {\n const points = buildPendingPath(pending, extras?.handles, viewport)\n ctx.strokeStyle = PENDING_COLOR\n ctx.lineWidth = EDGE_WIDTH\n ctx.globalAlpha = 1\n ctx.setLineDash([6, 4])\n strokePolyline(ctx, points)\n ctx.setLineDash([])\n }\n ctx.globalAlpha = 1\n ctx.setLineDash([])\n }\n\n pick(x: number, y: number, tolerance = PICK_TOLERANCE): EdgeId | null {\n for (const [id, points] of this.geometry) {\n if (distanceToPolyline({ x, y }, points) <= tolerance) return id\n }\n return null\n }\n\n pickEndpoint(x: number, y: number): { edgeId: EdgeId; end: EdgeEnd } | null {\n let best: { edgeId: EdgeId; end: EdgeEnd } | null = null\n let bestDist = ENDPOINT_RADIUS\n for (const [edgeId, ends] of this.endpoints) {\n const ds = Math.hypot(x - ends.source.x, y - ends.source.y)\n if (ds < bestDist) {\n bestDist = ds\n best = { edgeId, end: \"source\" }\n }\n const dt = Math.hypot(x - ends.target.x, y - ends.target.y)\n if (dt < bestDist) {\n bestDist = dt\n best = { edgeId, end: \"target\" }\n }\n }\n return best\n }\n\n dispose(): void {\n this.geometry.clear()\n this.endpoints.clear()\n this.labels.clear()\n this.peerAnchors.clear()\n }\n}\n\n/** The built-in {@link EdgeRendererFactory} — the default backend for `<Rivet>`. */\nexport const canvas2DEdgeRenderer: EdgeRendererFactory = (canvas, options) =>\n new Canvas2DEdgeRenderer(canvas, options)\n\nfunction strokePolyline(ctx: CanvasRenderingContext2D, points: Vec2[]): void {\n const first = points[0]\n if (!first) return\n ctx.beginPath()\n ctx.moveTo(first.x, first.y)\n for (let i = 1; i < points.length; i++) {\n const p = points[i]\n if (p) ctx.lineTo(p.x, p.y)\n }\n ctx.stroke()\n}\n\n/** Draw an arrowhead at the `start` or `end` of the polyline, facing outward. */\nfunction drawMarker(\n ctx: CanvasRenderingContext2D,\n points: Vec2[],\n at: \"start\" | \"end\",\n kind: Exclude<EdgeMarker, false>,\n color: string | CanvasGradient | CanvasPattern,\n): void {\n const tip = at === \"end\" ? points[points.length - 1] : points[0]\n const prev = at === \"end\" ? points[points.length - 2] : points[1]\n if (!tip || !prev) return\n const angle = Math.atan2(tip.y - prev.y, tip.x - prev.x)\n const spread = 0.5\n const left = {\n x: tip.x - ARROW_SIZE * Math.cos(angle - spread),\n y: tip.y - ARROW_SIZE * Math.sin(angle - spread),\n }\n const right = {\n x: tip.x - ARROW_SIZE * Math.cos(angle + spread),\n y: tip.y - ARROW_SIZE * Math.sin(angle + spread),\n }\n ctx.beginPath()\n ctx.moveTo(left.x, left.y)\n ctx.lineTo(tip.x, tip.y)\n ctx.lineTo(right.x, right.y)\n if (kind === \"arrowclosed\") {\n ctx.closePath()\n ctx.fillStyle = color\n ctx.fill()\n } else {\n ctx.strokeStyle = color\n ctx.stroke()\n }\n}\n","import {\n type CSSProperties,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport type { EdgeId } from \"../types\"\n\nconst overlayStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n overflow: \"hidden\",\n pointerEvents: \"none\",\n}\n\nconst labelStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n padding: \"1px 6px\",\n borderRadius: 4,\n background: \"rgba(255, 255, 255, 0.9)\",\n color: \"#0f172a\",\n fontSize: 11,\n lineHeight: 1.4,\n whiteSpace: \"nowrap\",\n pointerEvents: \"none\",\n}\n\nfunction sameIds(a: EdgeId[], b: EdgeId[]): boolean {\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n return true\n}\n\n/**\n * Renders `edge.label` text at each edge's midpoint. The renderer publishes\n * screen-space label anchors every frame (`store.setEdgeLabelAnchors`); this layer\n * repositions the divs imperatively on `subscribeFrame` so labels track pan/zoom\n * without a React re-render — only a change in *which* edges have labels re-renders.\n * The chip's look is the built-in style, under `defaultEdgeOptions.labelStyle`,\n * under the edge's own `labelStyle`.\n */\nexport function EdgeLabelLayer(): React.ReactElement {\n const { store, defaultEdgeOptions } = useRivetContext()\n const [ids, setIds] = useState<EdgeId[]>([])\n const refs = useRef(new Map<EdgeId, HTMLDivElement | null>())\n\n const position = useCallback(() => {\n const anchors = store.getEdgeLabelAnchors()\n for (const [id, el] of refs.current) {\n if (!el) continue\n const anchor = anchors.get(id)\n if (anchor) {\n el.style.display = \"\"\n el.style.transform = `translate(${anchor.x}px, ${anchor.y}px) translate(-50%, -50%)`\n } else {\n el.style.display = \"none\"\n }\n }\n }, [store])\n\n useEffect(() => {\n return store.subscribeFrame(() => {\n const anchors = store.getEdgeLabelAnchors()\n const next = [...anchors.keys()]\n setIds((prev) => (sameIds(prev, next) ? prev : next))\n position()\n })\n }, [store, position])\n\n // Position after every render so freshly mounted labels land immediately.\n useLayoutEffect(position)\n\n return (\n <div style={overlayStyle}>\n {ids.map((id) => {\n const edge = store.edges.get(id)\n if (!edge || edge.label === undefined) return null\n return (\n <div\n key={id}\n ref={(el) => {\n refs.current.set(id, el)\n }}\n style={{ ...labelStyle, ...defaultEdgeOptions?.labelStyle, ...edge.labelStyle }}\n >\n {String(edge.label)}\n </div>\n )\n })}\n </div>\n )\n}\n","import { alignRect } from \"../align\"\nimport { DRAG_THRESHOLD } from \"../constants\"\nimport { clampChildToParent, snapToGrid } from \"../graph\"\nimport type { RivetStore } from \"../store\"\nimport { clampNodeToLanes, type ResolvedLane, type ResolvedMargin } from \"../swimlane/lanes\"\nimport type { LaneChange, NodeId, Rect, Vec2 } from \"../types\"\n\n/** Screen-px gap within which a dragged node snaps to a neighbor's edge/center. */\nconst ALIGN_THRESHOLD = 6\n\nexport type GroupDragParams = {\n store: RivetStore\n /** Element that captures the pointer and carries the grab/grabbing cursor. */\n el: HTMLElement\n /** The initiating press — client coords and pointer id are read once. */\n event: { clientX: number; clientY: number; pointerId: number }\n /**\n * The node the press landed on, reported as the gesture's initiator. The\n * selection box has no single node, so it omits this and the first mover\n * stands in.\n */\n nodeId?: NodeId\n /** Grid to snap dragged nodes to (`[x, y]` world units), or null for free movement. */\n snapGrid: [number, number] | null\n /** Whether a single-node drag shows alignment guides and snaps to neighbors. */\n alignmentGuides: boolean\n swimlaneLanes: ResolvedLane[]\n clampToSwimlane: boolean\n swimlaneMargin: ResolvedMargin\n swimlaneLabelWidth: number\n onLaneChange?: (change: LaneChange) => void\n /** Called after each frame's (and the drop's) node repositioning. */\n onFrame?: () => void\n /**\n * Run once, the moment the press crosses the drag threshold, before the\n * movers are read. For a press that held its selection back until it knew\n * whether it was a click or a drag.\n */\n selectOnDrag?: () => void\n}\n\n/**\n * The selection-drag gesture: threshold-gated, then moves the selected movers\n * live (snap → clamp each frame) and commits them on release. Shared by a press\n * on a node ({@link NodeWrapper}) and on the post-marquee selection box\n * ({@link NodesSelection}), so the two drag paths behave identically.\n * Selection itself is the caller's concern — by the time this starts, the\n * nodes to move are exactly the selected ones.\n */\nexport function startGroupDrag(params: GroupDragParams): void {\n const { store, el, snapGrid, alignmentGuides, onLaneChange, onFrame } = params\n const { swimlaneLanes, clampToSwimlane, swimlaneMargin, swimlaneLabelWidth } = params\n\n const { zoom } = store.getViewport()\n const originX = params.event.clientX\n const originY = params.event.clientY\n const pointerId = params.event.pointerId\n\n // With swimlanes, nodes follow the cursor freely during the drag and snap\n // into a single lane on drop (the lane they land in decides membership).\n const clampActive = clampToSwimlane && swimlaneLanes.length > 0\n\n // The drag doesn't begin until the pointer moves past this threshold. Below it\n // the press stays a plain click, so a click / double-click on the node (to edit\n // a title, say) is never swallowed — and the pointer isn't captured.\n let started = false\n let starts = new Map<NodeId, Vec2>()\n let affected = new Set<NodeId>()\n /** The node reported as the gesture's initiator, once it has one. */\n let initiator: NodeId | undefined\n /**\n * A mover this gesture definitely holds, for the yield check below. Distinct\n * from `initiator`: the grabbed node may be a child riding along inside a\n * selected ancestor, in which case it's reported but never held itself.\n */\n let anchor: NodeId | undefined\n\n const repositionAffected = () => {\n for (const affectedId of affected) {\n const affectedEl = store.getNodeElement(affectedId)\n if (!affectedEl) continue\n const world = store.getNodeWorldPosition(affectedId)\n affectedEl.style.transform = `translate(${world.x}px, ${world.y}px)`\n }\n onFrame?.()\n }\n\n const beginDrag = (): boolean => {\n // A press that deliberately didn't select (it landed on a selectable anchor,\n // where a click means the anchor rather than the node) still has to select\n // once it turns out to be a drag — the movers are read from the selection\n // just below, and an unselected node has none.\n params.selectOnDrag?.()\n // The movers are the selected nodes whose ancestors aren't also selected — a\n // selected child of a selected parent just rides along, so moving it too would\n // double its travel. Their `position` (relative to a parent) changes.\n // A peer's lock drops a node out of the group rather than blocking the drag:\n // the rest of the selection still moves, which is what the pointer asked for.\n const movers = store\n .getMovers(store.getSelectedNodes())\n .filter((moverId) => store.locks.allows(moverId, \"drag\"))\n if (movers.length === 0) return false\n started = true\n starts = new Map<NodeId, Vec2>()\n for (const moverId of movers) {\n const moverNode = store.nodes.get(moverId)\n if (moverNode) starts.set(moverId, moverNode.position)\n }\n // Elements to reposition each frame: the movers plus every descendant (their\n // world position shifts with the mover even though their own offset doesn't).\n affected = new Set<NodeId>()\n for (const moverId of movers) {\n affected.add(moverId)\n for (const descendant of store.getDescendantIds(moverId)) affected.add(descendant)\n }\n // Pause swimlane auto-fit while dragging so a node's transient position can't\n // grow the lane; it fits (if needed) only once it's dropped and clamped.\n store.setNodeDragging(true)\n // Only the movers are held: a descendant rides along in world space, but its\n // own (parent-relative) position isn't what this gesture is writing.\n initiator = params.nodeId ?? movers[0]\n anchor = movers[0]\n if (initiator) store.beginNodeGesture(initiator, movers)\n el.setPointerCapture(pointerId)\n el.style.cursor = \"grabbing\"\n // The press never preventDefault()s (clicks and focus must keep working),\n // so by now the browser may have armed a native text selection at the\n // press point. Drop it and suppress selection for the drag's duration.\n window.getSelection()?.removeAllRanges()\n document.body.style.userSelect = \"none\"\n document.body.style.webkitUserSelect = \"none\"\n return true\n }\n\n /** Undo everything {@link beginDrag} set up, without committing a position. */\n const teardown = () => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n if (!started) return\n started = false\n el.style.cursor = \"grab\"\n document.body.style.userSelect = \"\"\n document.body.style.webkitUserSelect = \"\"\n store.setAlignmentGuides([])\n store.setNodeDragging(false)\n if (el.hasPointerCapture(pointerId)) el.releasePointerCapture(pointerId)\n }\n\n /**\n * True once the gesture no longer holds its nodes — the consumer yielded them\n * with `releaseNodeGesture` after a lock conflict. The pointer is still down,\n * so this is the only signal that the drag has to stop writing.\n */\n const yielded = (): boolean => anchor !== undefined && !store.isNodeHeld(anchor)\n\n const onMove = (moveEvent: PointerEvent) => {\n if (!started) {\n const moved = Math.hypot(moveEvent.clientX - originX, moveEvent.clientY - originY)\n if (moved < DRAG_THRESHOLD) return\n // Every mover was locked: the press stays a click and no drag begins.\n if (!beginDrag()) {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n return\n }\n }\n // Yielded mid-drag: leave the nodes where they are and let the holder's\n // writes land. Reverting would fight the position about to arrive.\n if (yielded()) {\n teardown()\n return\n }\n const dx = (moveEvent.clientX - originX) / zoom\n const dy = (moveEvent.clientY - originY) / zoom\n // Alignment guides apply to a single top-level node drag.\n const single = starts.size === 1\n for (const [moverId, start] of starts) {\n const moverNode = store.nodes.get(moverId)\n let next = { x: start.x + dx, y: start.y + dy }\n // Snap to the grid first, then confine — the constraint always wins.\n if (snapGrid) next = snapToGrid(next, snapGrid)\n // `extent: \"parent\"` confines the child live, so it can't be dragged out.\n if (moverNode?.parentId && moverNode.extent === \"parent\" && moverNode.size) {\n next = clampToParent(store, moverNode.parentId, next, moverNode.size)\n } else if (alignmentGuides && single && moverNode?.size && !moverNode.parentId) {\n // Snap edges/center to nearby nodes and publish the guides to draw.\n const movingRect: Rect = {\n x: next.x,\n y: next.y,\n width: moverNode.size.width,\n height: moverNode.size.height,\n }\n const statics: Rect[] = []\n for (const [otherId, other] of store.nodes) {\n if (otherId === moverId || other.parentId) continue\n statics.push(store.getNodeRect(otherId))\n }\n const { offset, guides } = alignRect(movingRect, statics, ALIGN_THRESHOLD / zoom)\n next = { x: next.x + offset.x, y: next.y + offset.y }\n store.setAlignmentGuides(guides)\n }\n // Update the store (so canvas edges follow); DOM nodes move imperatively.\n store.moveNode(moverId, next, false)\n }\n repositionAffected()\n }\n const onUp = () => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n // Never crossed the threshold — it was a click, not a drag. Leave it for the\n // element's own onClick / onDoubleClick handlers.\n if (!started) return\n // Released between the last move and the drop: the commit below would write\n // geometry this client no longer owns.\n if (yielded()) {\n teardown()\n return\n }\n el.style.cursor = \"grab\"\n document.body.style.userSelect = \"\"\n document.body.style.webkitUserSelect = \"\"\n store.setAlignmentGuides([])\n // Clear the drag flag before the commit below so the resulting frame runs\n // auto-fit against the node's final, clamped position.\n store.setNodeDragging(false)\n for (const [moverId, start] of starts) {\n const moverNode = store.nodes.get(moverId)\n let position = moverNode?.position ?? start\n\n if (moverNode?.parentId && moverNode.extent === \"parent\" && moverNode.size) {\n // Confine a child to its parent's box (position is parent-relative).\n position = clampToParent(store, moverNode.parentId, position, moverNode.size)\n } else if (clampActive && moverNode?.size) {\n // Snap into a lane (the drop decides membership → cross-lane re-parent).\n const result = clampNodeToLanes(\n position,\n moverNode.size,\n swimlaneLanes,\n swimlaneMargin,\n swimlaneLabelWidth,\n )\n position = result.position\n const previousLaneId = store.setNodeLane(moverId, result.laneId)\n if (previousLaneId !== false) {\n onLaneChange?.({ nodeId: moverId, laneId: result.laneId, previousLaneId })\n }\n }\n store.moveNode(moverId, position, true)\n }\n // Released after the commits: the drop is the gesture's last write, and it\n // has to win against anything that arrived while the pointer was down.\n if (initiator) store.endNodeGesture(initiator, [...starts.keys()])\n repositionAffected()\n }\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n}\n\n/** Read the parent's measured box and confine a child's position inside it. */\nexport function clampToParent(\n store: RivetStore,\n parentId: NodeId,\n position: Vec2,\n size: { width: number; height: number },\n): Vec2 {\n const parent = store.nodes.get(parentId)\n const parentSize = {\n width: parent?.width ?? parent?.size?.width ?? 0,\n height: parent?.height ?? parent?.size?.height ?? 0,\n }\n return clampChildToParent(position, size, parentSize)\n}\n","/**\n * Click-to-select on an anchor's own element.\n *\n * Two gestures race over one press here: the node wants to move, and the anchor\n * under the pointer wants to be selected. They're separated by distance, not by\n * order — the press starts both, and whichever the pointer's travel resolves to\n * is the one that acts. Under {@link DRAG_THRESHOLD} the press was a click and\n * the anchor takes it; past it the node drag has already begun and the anchor\n * stays out of the way.\n *\n * The listener sits on the consumer's own element (the `<path>`, the `<span>`)\n * because that's what gives shape-accurate hit-testing — a press inside a\n * path's actual outline rather than inside its bounding box, which is the whole\n * difference for artwork that is neither rectangular nor non-overlapping. The\n * only thing written to that element is `pointer-events`, restored on cleanup,\n * and only for anchors registered `selectable`.\n */\n\nimport { DRAG_THRESHOLD } from \"../constants\"\nimport { anchorTargetKey } from \"../presence/targets\"\nimport type { RivetStore } from \"../store\"\nimport type { AnchorRecord } from \"./registry\"\n\n/**\n * Make one anchor's element selectable. Returns the cleanup, or `null` when\n * there's nothing to attach to (no element, or the anchor isn't selectable).\n */\nexport function attachAnchorSelection(\n store: RivetStore,\n record: AnchorRecord,\n): (() => void) | null {\n const element = record.element\n if (!record.selectable || !(element instanceof HTMLElement || element instanceof SVGElement)) {\n return null\n }\n const { nodeId, anchorId } = record\n\n // Artwork wrappers are pointer-transparent so the whole graphic stays\n // draggable; an opted-in element has to come back out of that.\n const previous = element.style.pointerEvents\n element.style.pointerEvents = \"auto\"\n\n // Typed as MouseEvent rather than PointerEvent throughout: PointerEvent\n // extends it, so this covers both, and environments that dispatch a plain\n // MouseEvent for a pointer gesture (jsdom, where PointerEvent may be absent)\n // still land here instead of being silently dropped by the guard.\n const onPointerDown = (event: Event) => {\n if (!(event instanceof MouseEvent)) return\n if (event.button !== 0) return\n const originX = event.clientX\n const originY = event.clientY\n const onUp = (upEvent: Event) => {\n // Detached first: the press is over either way, and bailing out before\n // this would leave the listener armed for somebody else's pointer.\n window.removeEventListener(\"pointerup\", onUp)\n if (!(upEvent instanceof MouseEvent)) return\n const moved = Math.hypot(upEvent.clientX - originX, upEvent.clientY - originY)\n // Past the threshold this press became a node drag, and the drag already\n // selected the node — claiming the anchor now would undo it on release.\n if (moved >= DRAG_THRESHOLD) return\n // Asked at release, not at press: the answer can only have become more\n // restrictive in between, and a lock arriving mid-press shouldn't leave a\n // selection nobody is allowed to have made.\n if (!store.locks.allows(anchorTargetKey(nodeId, anchorId), \"select\")) return\n store.setSelectedAnchors([{ nodeId, anchorId }])\n }\n window.addEventListener(\"pointerup\", onUp)\n }\n\n element.addEventListener(\"pointerdown\", onPointerDown)\n return () => {\n element.removeEventListener(\"pointerdown\", onPointerDown)\n element.style.pointerEvents = previous\n }\n}\n","import { Fragment, useCallback, useEffect, useSyncExternalStore } from \"react\"\nimport {\n ANCHOR_SIDES,\n type AnchorRecord,\n anchorDotHandleId,\n anchorHandleId,\n parseAnchorHandleId,\n type ResolvedAnchorOptions,\n strayPlacementPct,\n} from \"../anchor/registry\"\nimport { attachAnchorSelection } from \"../anchor/select-gesture\"\nimport { useRivetContext } from \"../context\"\nimport type { HandlePosition, NodeId } from \"../types\"\nimport { Handle } from \"./handle\"\n\n/** Fallback accent when an anchor registers without a color (matches Handle's border). */\nconst DEFAULT_ANCHOR_COLOR = \"#6366f1\"\n\n/**\n * Library-rendered chrome for a node's registered anchors — overlay elements\n * positioned from measured geometry, never injected into the node's content\n * (so a consumer's DOM, including a contentEditable, is left untouched):\n *\n * - **Grab dots** on the anchor element's line boxes, shown while the node is\n * hovered and the element is live. Each is a real handle that only *starts*\n * a connection; its id is rewritten to the stray id before an edge commits.\n * - **Stray handles** on the node perimeter — the persisted connection\n * points. One default-side handle when unconnected; once edges exist, one\n * per *connected* side. Rendered from retained geometry even while the\n * anchor is detached, so edges stay put during display unmounts. Suppressed\n * entirely for anchors registered with `strays: \"none\"`.\n */\nexport function NodeAnchors({ nodeId }: { nodeId: NodeId }): React.ReactElement | null {\n const { store, anchorOptions } = useRivetContext()\n\n const subscribeAnchors = useCallback(\n (listener: () => void) => store.subscribeNodeAnchors(nodeId, listener),\n [store, nodeId],\n )\n const getAnchorsVersion = useCallback(() => store.getNodeAnchorsVersion(nodeId), [store, nodeId])\n const anchorsVersion = useSyncExternalStore(\n subscribeAnchors,\n getAnchorsVersion,\n getAnchorsVersion,\n )\n useSyncExternalStore(store.subscribeEdges, store.getEdgesVersion, store.getEdgesVersion)\n useSyncExternalStore(\n store.subscribeAnchorSelection,\n store.getSelectedAnchors,\n store.getSelectedAnchors,\n )\n\n // Click-to-select lives on the consumer's own elements, so it's re-attached\n // whenever the registry changes one — a re-bind swaps the element out from\n // under a listener that would otherwise hold the old node forever.\n // biome-ignore lint/correctness/useExhaustiveDependencies: the version IS the dependency — the records are pulled imperatively, so nothing else says they changed.\n useEffect(() => {\n const cleanups: (() => void)[] = []\n for (const record of store.getNodeAnchors(nodeId)) {\n const cleanup = attachAnchorSelection(store, record)\n if (cleanup) cleanups.push(cleanup)\n }\n return () => {\n for (const cleanup of cleanups) cleanup()\n }\n }, [store, nodeId, anchorsVersion])\n\n const records = store.getNodeAnchors(nodeId)\n if (records.length === 0) return null\n\n const dotsVisible = Boolean(store.nodes.get(nodeId)?.hovered)\n\n // Sides with at least one edge, per anchor — only persisted stray handles\n // count (a dot id never reaches an edge).\n const connectedSides = new Map<string, HandlePosition[]>()\n for (const edge of store.edges.values()) {\n const ends = [\n edge.source === nodeId ? parseAnchorHandleId(edge.sourceHandle) : null,\n edge.target === nodeId ? parseAnchorHandleId(edge.targetHandle) : null,\n ]\n for (const end of ends) {\n if (!end) continue\n const sides = connectedSides.get(end.anchorId) ?? []\n if (!sides.includes(end.side)) sides.push(end.side)\n connectedSides.set(end.anchorId, sides)\n }\n }\n\n return (\n <>\n {records.map((record) => (\n <Fragment key={record.anchorId}>\n {store.isAnchorSelected(nodeId, record.anchorId) && (\n <AnchorSelectionOutline record={record} />\n )}\n <AnchorDots record={record} options={anchorOptions} visible={dotsVisible} />\n {record.strays !== \"none\" && (\n <AnchorStrayHandles\n record={record}\n options={anchorOptions}\n connectedSides={connectedSides.get(record.anchorId)}\n />\n )}\n </Fragment>\n ))}\n </>\n )\n}\n\n/**\n * The selected treatment: a box around the anchor's measured extent, in the\n * anchor's own accent. Overlay chrome like the dots and strays, so a selected\n * shape reads the same whether its element is an SVG path or a run of text, and\n * the consumer's markup is left alone.\n */\nfunction AnchorSelectionOutline({ record }: { record: AnchorRecord }): React.ReactElement | null {\n const geometry = record.geometry\n if (!geometry) return null\n const { dots } = geometry\n const left = dots.left.xPct\n const top = dots.top.yPct\n return (\n <div\n data-rivet-anchor-selected={record.anchorId}\n style={{\n position: \"absolute\",\n left: `${left}%`,\n top: `${top}%`,\n width: `${dots.right.xPct - left}%`,\n height: `${dots.bottom.yPct - top}%`,\n border: `1px solid ${record.color ?? DEFAULT_ANCHOR_COLOR}`,\n borderRadius: 2,\n // The box is a readout, never a target: presses belong to the element\n // underneath it, which is what put the selection here.\n pointerEvents: \"none\",\n }}\n />\n )\n}\n\n/**\n * The in-content grab dots, from measured line rects: left/top on the first\n * line box, right/bottom on the last. Hidden while the anchor is detached —\n * the element is unmounted, so the retained geometry may be stale.\n */\nfunction AnchorDots(props: {\n record: AnchorRecord\n options: ResolvedAnchorOptions\n visible: boolean\n}): React.ReactElement | null {\n const { record, options } = props\n if (!record.geometry || !record.element?.isConnected) return null\n const dots = record.geometry.dots\n return (\n <>\n {ANCHOR_SIDES.map((side) => {\n const dot = dots[side]\n return (\n <Handle\n // The measured position participates in the key: moving a dot\n // remounts its handle so the registered world offset re-measures\n // (Handle only re-measures on mount and box resizes).\n key={`${side}:${dot.xPct.toFixed(1)},${dot.yPct.toFixed(1)}`}\n id={anchorDotHandleId(record.anchorId, side)}\n type=\"either\"\n position={side}\n style={{\n left: `${dot.xPct}%`,\n top: `${dot.yPct}%`,\n right: \"auto\",\n bottom: \"auto\",\n transform: \"translate(-50%, -50%)\",\n width: options.dotSize,\n height: options.dotSize,\n background: record.color ?? DEFAULT_ANCHOR_COLOR,\n border: \"none\",\n opacity: props.visible ? 1 : 0,\n transition: \"opacity 150ms\",\n }}\n />\n )\n })}\n </>\n )\n}\n\n/**\n * The persisted perimeter handles, placed along each side near the anchor's\n * measured position — nudged out of the side-center keep-out band (where the\n * node's own handles sit) and off the corners.\n */\nfunction AnchorStrayHandles(props: {\n record: AnchorRecord\n options: ResolvedAnchorOptions\n connectedSides: HandlePosition[] | undefined\n}): React.ReactElement | null {\n const { record, options } = props\n const geometry = record.geometry\n if (!geometry) return null\n const sides =\n props.connectedSides && props.connectedSides.length > 0\n ? props.connectedSides\n : [options.defaultSide]\n return (\n <>\n {sides.map((side) => {\n const placed = strayPlacementPct(geometry, side, options)\n const axis =\n side === \"top\" || side === \"bottom\" ? { left: `${placed}%` } : { top: `${placed}%` }\n return (\n <Handle\n key={`${side}:${placed.toFixed(1)}`}\n id={anchorHandleId(record.anchorId, side)}\n type=\"either\"\n position={side}\n style={{\n width: options.strayHandleSize,\n height: options.strayHandleSize,\n background: record.color ?? DEFAULT_ANCHOR_COLOR,\n border: \"none\",\n ...axis,\n }}\n />\n )\n })}\n </>\n )\n}\n","import {\n type CSSProperties,\n memo,\n type FocusEvent as ReactFocusEvent,\n type KeyboardEvent as ReactKeyboardEvent,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\"\nimport { findSelectableAnchor } from \"../anchor/registry\"\nimport { SELECTOR } from \"../constants\"\nimport { RivetNodeContext, type RivetNodeContextValue, useRivetContext } from \"../context\"\nimport { snapToGrid } from \"../graph\"\nimport { clampToParent, startGroupDrag } from \"../input/group-drag\"\nimport { ARROW_DIRS, ARROW_STEP, ARROW_STEP_SHIFT } from \"../input/keyboard\"\nimport { keyHeld } from \"../input/keys\"\nimport type { NodeId, Vec2 } from \"../types\"\nimport { DefaultNode } from \"./default-node\"\nimport { BUILTIN_NODE_TYPES } from \"./group-node\"\nimport { NodeAnchors } from \"./node-anchors\"\n\nconst wrapperStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n pointerEvents: \"auto\",\n cursor: \"grab\",\n userSelect: \"none\",\n}\n\nexport type NodeWrapperProps = {\n id: NodeId\n}\n\n/**\n * Positions one node in world space, handles dragging, and reports its size.\n *\n * It subscribes to *only its own* node via `useSyncExternalStore` and is\n * memoized, so a change to any other node — or a re-render of the layer when the\n * visible set changes — never re-renders this one.\n */\nexport const NodeWrapper = memo(function NodeWrapper({ id }: NodeWrapperProps) {\n const { store, nodeTypes, onLaneChange, multiSelectionKeys, snapGrid } = useRivetContext()\n const { swimlaneLanes, clampToSwimlane, swimlaneMargin, swimlaneLabelWidth, alignmentGuides } =\n useRivetContext()\n const { announce, nodeDescriptionId } = useRivetContext()\n const ref = useRef<HTMLDivElement>(null)\n\n // Keyboard grab-to-move (ARIA drag-and-drop pattern): Enter/Space picks the\n // node up, arrows move it, Enter drops, Escape reverts to these origins.\n // Origins cover every mover (a grabbed node in a multi-selection moves the\n // group, like a pointer drag). `grabbed` mirrors the ref for rendering.\n const [grabbed, setGrabbed] = useState(false)\n const grabOrigins = useRef<Map<NodeId, Vec2> | null>(null)\n\n const nodeName = () => {\n const node = store.nodes.get(id)\n return node?.ariaLabel ?? `node ${id}`\n }\n\n const grab = () => {\n const movers = store\n .getMovers(store.isNodeSelected(id) ? store.getSelectedNodes() : [id])\n .filter((moverId) => store.locks.allows(moverId, \"drag\"))\n if (movers.length === 0) {\n announce(`${nodeName()} is locked by someone else.`)\n return\n }\n const origins = new Map<NodeId, Vec2>()\n for (const moverId of movers) {\n const mover = store.nodes.get(moverId)\n if (mover) origins.set(moverId, { ...mover.position })\n }\n grabOrigins.current = origins\n setGrabbed(true)\n // A grab holds its movers exactly like a pointer drag: arrow keys are this\n // client's geometry until it drops, so remote writes to it must not land.\n store.beginNodeGesture(id, movers)\n announce(`Grabbed ${nodeName()}. Use the arrow keys to move, Enter to drop, Escape to cancel.`)\n }\n\n const releaseGrab = (revert: boolean) => {\n const origins = grabOrigins.current\n grabOrigins.current = null\n setGrabbed(false)\n if (!origins) return\n if (revert) {\n for (const [moverId, origin] of origins) store.moveNode(moverId, origin, true)\n // Released after the reverting moves, so the gesture still owns its\n // geometry while they commit — the same order as a drop.\n store.endNodeGesture(id, [...origins.keys()])\n announce(\"Move cancelled.\")\n return\n }\n store.endNodeGesture(id, [...origins.keys()])\n const node = store.nodes.get(id)\n if (node) {\n const { x, y } = node.position\n announce(`Dropped ${nodeName()} at ${Math.round(x)}, ${Math.round(y)}.`)\n }\n }\n\n const subscribe = useCallback(\n (onChange: () => void) => store.subscribeNode(id, onChange),\n [store, id],\n )\n const getSnapshot = useCallback(() => store.getNodeVersion(id), [store, id])\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n // This node's holder, not the lock table's version: the registry notifies\n // every wrapper on any lock change, and comparing the holder id lets React\n // bail out of all but the one node that actually changed hands.\n const lockHolder = useSyncExternalStore(\n store.locks.subscribe,\n useCallback(() => store.locks.getHolder(id), [store, id]),\n useCallback(() => store.locks.getHolder(id), [store, id]),\n )\n\n const nodeContext = useMemo<RivetNodeContextValue>(() => ({ nodeId: id, wrapperRef: ref }), [id])\n\n // Report layout size (world units, since the element lives pre-transform) and\n // register the element so group drags can translate this node imperatively.\n useEffect(() => {\n const el = ref.current\n if (!el) return\n store.registerNodeElement(id, el)\n const observer = new ResizeObserver(() => {\n store.setNodeSize(id, { width: el.offsetWidth, height: el.offsetHeight })\n // Anchor geometry is measured against this box, so a resize (including\n // the initial observation) re-measures the node's anchors. Reflows that\n // don't change the box go through `remeasureAnchors` explicitly.\n store.remeasureAnchors(id)\n })\n observer.observe(el)\n return () => {\n observer.disconnect()\n store.unregisterNodeElement(id, el)\n }\n }, [id, store])\n\n const onPointerEnter = () => store.hoverNode(id)\n const onPointerLeave = () => store.hoverNode(null)\n\n // Track roving focus in the store. Self-only: a focused control inside the\n // node bubbles focusin here with a different target, and the node it lives in\n // is still the logically focused one, so nothing changes.\n const onFocus = (event: ReactFocusEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n store.setFocusedNode(id)\n }\n\n const onBlur = (event: ReactFocusEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n // Losing focus drops a grab in place — the moves are already committed.\n if (grabOrigins.current) releaseGrab(false)\n // When focus moves into a node (this one's interior or another wrapper),\n // that node's own handlers own the state — clearing here would flicker\n // `null` through the focus channel between two nodes.\n const next = event.relatedTarget\n if (next instanceof Element && next.closest(SELECTOR.node)) return\n if (store.getFocusedNode() === id) store.setFocusedNode(null)\n }\n\n // Keyboard, on the focused wrapper itself (not controls inside the node):\n // Enter/Space selects and grabs the node (additive modifier only toggles\n // selection), arrows move a grabbed node, Enter drops it, Escape reverts the\n // move — or clears the selection when nothing is grabbed. Delete (and the\n // ungrabbed selection nudge) are handled globally — see input/keyboard.\n const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget) return\n const node = store.nodes.get(id)\n if (!node || node.selectable === false) return\n\n // Before any lock guard: a grab that has lost its hold — yielded to a peer\n // with `releaseNodeGesture` — has to be cleaned up whatever key arrives.\n // The node is usually locked by then, so a refusal here would strand the\n // grab with no key left that could end it.\n if (grabOrigins.current && !store.isNodeHeld(id)) {\n grabOrigins.current = null\n setGrabbed(false)\n announce(`${nodeName()} was taken by someone else.`)\n return\n }\n if (!store.locks.allows(id, \"select\")) return\n\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault()\n if (grabOrigins.current) {\n releaseGrab(false)\n return\n }\n if (keyHeld(event, multiSelectionKeys)) {\n store.selectNode(id, true)\n return\n }\n // Mirror pointer-drag semantics: grabbing a node already in a\n // multi-selection keeps (and moves) the whole selection.\n if (!store.isNodeSelected(id)) store.selectNode(id)\n if (node.draggable !== false) grab()\n return\n }\n\n if (event.key === \"Escape\") {\n if (grabOrigins.current) {\n event.preventDefault()\n releaseGrab(true)\n return\n }\n store.selectNode(null)\n return\n }\n\n const dir = ARROW_DIRS[event.key]\n if (!dir || !grabOrigins.current) return\n // preventDefault also stops the global handler's selection nudge — while\n // grabbed, this handler owns arrow movement (snap + parent clamp applied).\n event.preventDefault()\n const factor = event.shiftKey ? ARROW_STEP_SHIFT : 1\n const stepX = (snapGrid?.[0] || ARROW_STEP) * factor\n const stepY = (snapGrid?.[1] || ARROW_STEP) * factor\n for (const moverId of grabOrigins.current.keys()) {\n const mover = store.nodes.get(moverId)\n if (!mover) continue\n let next = {\n x: mover.position.x + dir.x * stepX,\n y: mover.position.y + dir.y * stepY,\n }\n if (snapGrid) next = snapToGrid(next, snapGrid)\n if (mover.parentId && mover.extent === \"parent\" && mover.size) {\n next = clampToParent(store, mover.parentId, next, mover.size)\n }\n store.moveNode(moverId, next, true)\n }\n }\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n // A press that bubbled here through a React portal (a dropdown/tooltip/popover\n // rendered from inside this node) has a target outside the node's DOM. React\n // routes its synthetic events up the component tree regardless, so guard by\n // actual DOM containment — starting a drag would capture the pointer and\n // swallow that control's click.\n if (ref.current && event.target instanceof Node && !ref.current.contains(event.target)) return\n // In-DOM controls opt out of dragging with `data-nopan` (buttons, inputs, …).\n if (event.target instanceof Element && event.target.closest(SELECTOR.noPan)) return\n event.stopPropagation()\n const el = ref.current\n const node = store.nodes.get(id)\n if (!el || !node) return\n\n // Per-node interaction opt-outs — a `data-nodrag`/`data-noselect` attribute on\n // the pressed subtree wins over the node-level `draggable`/`selectable` field.\n // A peer's lock joins them as a third, transport-driven source of the same\n // two refusals, so a locked node behaves like a `selectable: false`,\n // `draggable: false` one for as long as they hold it.\n const target = event.target instanceof Element ? event.target : null\n const noSelect =\n node.selectable === false ||\n Boolean(target?.closest(SELECTOR.noSelect)) ||\n !store.locks.allows(id, \"select\")\n const noDrag =\n node.draggable === false ||\n Boolean(target?.closest(SELECTOR.noDrag)) ||\n !store.locks.allows(id, \"drag\")\n\n const additive = keyHeld(event, multiSelectionKeys)\n if (additive) {\n // Toggle this node in/out of the selection; don't start a drag.\n if (!noSelect) store.selectNode(id, true)\n return\n }\n // A press on a selectable anchor means the anchor if it stays a click, and\n // the node if it becomes a drag — so hold the node selection back until the\n // gesture says which. Selecting now would put the node's outline up for the\n // length of every click on a shape, then take it away again.\n const onAnchor =\n target !== null && findSelectableAnchor(store.getNodeAnchors(id), target) !== null\n const selectNode = () => {\n if (!noSelect && !store.isNodeSelected(id)) store.selectNode(id)\n }\n // Dragging a node that's already part of a multi-selection moves the whole\n // group; dragging any other node selects just it first.\n if (!onAnchor) selectNode()\n // A non-draggable node still selects/clicks, but starts no drag gesture.\n if (noDrag) return\n\n // The drag gesture itself (threshold, live snap/clamp, drop commit) is\n // shared with the post-marquee selection box — see input/group-drag.\n startGroupDrag({\n store,\n nodeId: id,\n el,\n event,\n snapGrid,\n alignmentGuides,\n swimlaneLanes,\n clampToSwimlane,\n swimlaneMargin,\n swimlaneLabelWidth,\n onLaneChange,\n selectOnDrag: onAnchor ? selectNode : undefined,\n })\n }\n\n const node = store.nodes.get(id)\n if (!node) return null\n const key = node.type ?? \"default\"\n const Component = nodeTypes[key] ?? BUILTIN_NODE_TYPES[key] ?? DefaultNode\n // Transform is the node's *world* position (parent chain resolved); z-index by\n // depth so children stack above their parent (flat layer, no DOM nesting).\n const world = store.getNodeWorldPosition(id)\n const depth = store.getNodeDepth(id)\n // The peer's outline is painted on the canvas; the DOM side is the cursor and\n // the focus/aria treatment, which the canvas can't reach. Both refusals are\n // asked separately, because a policy may allow one and not the other.\n const locked = lockHolder !== null\n const lockedForSelect = locked && !store.locks.allows(id, \"select\")\n const lockedForDrag = locked && !store.locks.allows(id, \"drag\")\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a node wraps arbitrary (often interactive) content, so it can't be a native <button>\n <div\n ref={ref}\n data-rivet-node={id}\n data-rivet-grabbed={grabbed ? \"\" : undefined}\n data-rivet-locked={locked ? (lockHolder ?? \"\") : undefined}\n tabIndex={node.selectable === false || lockedForSelect ? -1 : 0}\n role=\"button\"\n aria-roledescription=\"graph node\"\n aria-pressed={Boolean(node.selected)}\n aria-label={node.ariaLabel}\n aria-disabled={lockedForSelect || undefined}\n aria-describedby={\n node.selectable === false || lockedForSelect ? undefined : nodeDescriptionId\n }\n onPointerDown={onPointerDown}\n onPointerEnter={onPointerEnter}\n onPointerLeave={onPointerLeave}\n onKeyDown={onKeyDown}\n onFocus={onFocus}\n onBlur={onBlur}\n style={{\n ...wrapperStyle,\n ...(lockedForDrag ? { cursor: \"not-allowed\" } : {}),\n transform: `translate(${world.x}px, ${world.y}px)`,\n zIndex: depth,\n // Explicit dimensions from NodeResizer override the intrinsic size.\n ...(node.width !== undefined ? { width: node.width } : {}),\n ...(node.height !== undefined ? { height: node.height } : {}),\n }}\n >\n <RivetNodeContext.Provider value={nodeContext}>\n <Component\n id={id}\n type={node.type}\n data={node.data}\n selected={Boolean(node.selected)}\n hovered={Boolean(node.hovered)}\n width={node.width ?? node.size?.width}\n height={node.height ?? node.size?.height}\n position={node.position}\n positionAbsolute={world}\n />\n <NodeAnchors nodeId={id} />\n </RivetNodeContext.Provider>\n </div>\n )\n})\n","import {\n type CSSProperties,\n memo,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n useRef,\n useSyncExternalStore,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport { boundingRect } from \"../graph\"\nimport { startGroupDrag } from \"../input/group-drag\"\nimport type { Rect } from \"../types\"\n\n/** Above every node — nodes z-stack by tree depth, which stays small. */\nconst NODES_SELECTION_Z = 1000\n\nconst boxStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n pointerEvents: \"auto\",\n cursor: \"grab\",\n userSelect: \"none\",\n zIndex: NODES_SELECTION_Z,\n // Same accent as the marquee overlay it succeeds, but dotted: the marquee is\n // the live gesture, this is the settled selection.\n border: \"1px dotted rgba(99, 102, 241, 0.8)\",\n background: \"rgba(99, 102, 241, 0.08)\",\n}\n\nconst applyRect = (el: HTMLElement, rect: Rect): void => {\n el.style.transform = `translate(${rect.x}px, ${rect.y}px)`\n el.style.width = `${rect.width}px`\n el.style.height = `${rect.height}px`\n}\n\n/**\n * The persistent box a marquee leaves behind: a draggable rect over the\n * selected nodes' bounding box (React Flow's \"NodesSelection\"). Dragging it\n * moves the whole selection as a group; any other selection change — a pane,\n * node, or edge click, Escape, deletion — dismisses it. It lives in the\n * viewport-transformed node layer, so it pans/zooms with the graph.\n */\nexport const NodesSelection = memo(function NodesSelection() {\n const { store, snapGrid, alignmentGuides, onLaneChange } = useRivetContext()\n const { swimlaneLanes, clampToSwimlane, swimlaneMargin, swimlaneLabelWidth } = useRivetContext()\n const ref = useRef<HTMLDivElement>(null)\n\n const subscribe = useCallback(\n (onChange: () => void) => store.subscribeSelectionBox(onChange),\n [store],\n )\n const getSnapshot = useCallback(() => store.getSelectionBoxVersion(), [store])\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot)\n\n const selectionRect = (): Rect | null =>\n boundingRect(store.getSelectedNodes().map((id) => store.getNodeRect(id)))\n\n const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n const el = ref.current\n if (!el) return\n event.stopPropagation()\n startGroupDrag({\n store,\n el,\n event,\n snapGrid,\n alignmentGuides,\n swimlaneLanes,\n clampToSwimlane,\n swimlaneMargin,\n swimlaneLabelWidth,\n onLaneChange,\n // Node moves are imperative during the drag (no React re-render), so the\n // box tracks its nodes the same way; the drop's commit re-renders it.\n onFrame: () => {\n const rect = selectionRect()\n if (rect && ref.current) applyRect(ref.current, rect)\n },\n })\n }\n\n if (!store.isSelectionBoxActive()) return null\n const rect = selectionRect()\n if (!rect) return null\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a drag affordance over canvas-positioned nodes, not a form grouping — it can't be a <fieldset>\n <div\n ref={ref}\n data-rivet-nodes-selection\n role=\"group\"\n aria-label=\"Selected nodes\"\n onPointerDown={onPointerDown}\n style={{\n ...boxStyle,\n transform: `translate(${rect.x}px, ${rect.y}px)`,\n width: rect.width,\n height: rect.height,\n }}\n />\n )\n})\n","import type { CSSProperties, RefObject } from \"react\"\nimport type { NodeId } from \"../types\"\nimport { NodeWrapper } from \"./node-wrapper\"\nimport { NodesSelection } from \"./nodes-selection\"\n\nconst layerStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n transformOrigin: \"0 0\",\n // `will-change: transform` is applied imperatively only while panning/zooming\n // (see the runtime), then cleared — a permanently promoted layer would upscale a\n // cached bitmap and blur node text when zoomed in.\n pointerEvents: \"none\",\n}\n\nexport type NodeLayerProps = {\n containerRef: RefObject<HTMLDivElement | null>\n visibleIds: NodeId[]\n}\n\n/**\n * The DOM layer. Renders only the culled (visible) nodes. It re-renders solely\n * when the visible set changes (the `visibleIds` prop); node data changes are\n * handled by each memoized {@link NodeWrapper} subscribing to its own node, so\n * touching one node never re-renders the others.\n */\nexport function NodeLayer({ containerRef, visibleIds }: NodeLayerProps): React.ReactElement {\n return (\n <div ref={containerRef} style={layerStyle}>\n {visibleIds.map((id) => (\n <NodeWrapper key={id} id={id} />\n ))}\n {/* Post-marquee selection box — world-space, so it belongs in this\n transformed layer even though it isn't a node (and isn't culled:\n its nodes may be off-screen while the box edge is not). */}\n <NodesSelection />\n </div>\n )\n}\n","import {\n type ComponentType,\n type CSSProperties,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n} from \"react\"\nimport { useRivetContext } from \"../context\"\nimport { usePeerIdentities } from \"../hooks/use-peer-identities\"\nimport type { PeerCursorProps } from \"../presence/registry\"\nimport { worldToScreen } from \"../viewport\"\n\nconst overlayStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n // Cursor chrome belongs to the canvas: clipped to the pane rather than\n // escaping into whatever app UI surrounds it.\n overflow: \"hidden\",\n pointerEvents: \"none\",\n}\n\nconst cursorStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n // The wrapper is a point, not a box: it sits at the pointer tip and whatever\n // the consumer renders lays itself out from there.\n width: 0,\n height: 0,\n pointerEvents: \"none\",\n}\n\n/**\n * Peer cursors as DOM, from a consumer's own component\n * (`presenceOptions.cursorComponent`).\n *\n * The division of labour is the one {@link EdgeLabelLayer} established: React\n * mounts one wrapper per peer and re-renders only when the roster's *people*\n * change — joins, leaves, renames — while position is written imperatively on\n * every cursor frame. A room where everybody is moving their mouse re-renders\n * nothing.\n *\n * Screen space, matching the canvas paint: a name chip that scaled with zoom\n * would be unreadable at 0.2 and absurd at 2. The current zoom is written to\n * each wrapper as a `--rivet-zoom` custom property, so styling that *does* want\n * to react to it can, in CSS, without a re-render.\n */\nexport function PeerCursorLayer({\n component: Cursor,\n}: {\n component: ComponentType<PeerCursorProps>\n}): React.ReactElement {\n const { store, paneRef } = useRivetContext()\n const peers = usePeerIdentities()\n const refs = useRef(new Map<string, HTMLDivElement | null>())\n // Last zoom written to the wrappers. Writing a custom property invalidates\n // style for the subtree it lands on, and zoom changes on wheel frames rather\n // than pointer frames — so it's written when it moves, not every frame.\n const zoomRef = useRef<number | null>(null)\n // …and which wrappers have it at all. A peer joining at a settled zoom is the\n // case a \"did it change?\" test alone gets wrong: nothing moved, so their brand\n // new element would sit there without the property until somebody zoomed.\n const zoomWritten = useRef(new WeakSet<HTMLElement>())\n\n const position = useCallback(() => {\n const pane = paneRef.current\n if (!pane) return\n const viewport = store.getViewport()\n const zoomChanged = zoomRef.current !== viewport.zoom\n zoomRef.current = viewport.zoom\n // The same box the canvases are sized against, so both cursor layers cull at\n // exactly the same edge. Nothing written below dirties layout — transforms\n // and custom properties don't — so the read costs no reflow.\n const { width, height } = pane.getBoundingClientRect()\n // Rendered positions, already stepped for this frame by the render loop.\n const live = new Map(store.presence.getPeers().map((peer) => [peer.id, peer.cursor]))\n\n for (const [id, el] of refs.current) {\n if (!el) continue\n const cursor = live.get(id)\n // No cursor at all — off the canvas, or a peer known only by name. Not the\n // same as off-screen: there's nothing to point at, so nothing is shown.\n if (!cursor) {\n el.style.display = \"none\"\n continue\n }\n el.style.display = \"\"\n const point = worldToScreen(cursor, viewport)\n const x = Math.min(Math.max(point.x, 0), width)\n const y = Math.min(Math.max(point.y, 0), height)\n const offscreen = x !== point.x || y !== point.y\n el.style.transform = `translate(${x}px, ${y}px)`\n // Off-pane peers are clamped to the edge and hidden rather than dropped,\n // so an edge-of-pane indicator stays a consumer choice: `visibility` is\n // inherited, and a component that sets `visibility: visible` on its own\n // root reappears at the clamped point. `data-rivet-offscreen` is how it\n // knows to.\n el.style.visibility = offscreen ? \"hidden\" : \"\"\n if (offscreen) el.setAttribute(\"data-rivet-offscreen\", \"\")\n else el.removeAttribute(\"data-rivet-offscreen\")\n if (zoomChanged || !zoomWritten.current.has(el)) {\n el.style.setProperty(\"--rivet-zoom\", String(viewport.zoom))\n zoomWritten.current.add(el)\n }\n }\n }, [store, paneRef])\n\n useEffect(() => {\n // Cursor frames cover both kinds of movement: a peer's pointer (a cursor-only\n // frame) and the viewport their point projects through (a full frame, which\n // owns this layer too).\n return store.subscribeCursorFrame(position)\n }, [store, position])\n\n // Position after every render, so a peer who has just joined lands at their\n // cursor immediately instead of waiting for the next frame to arrive.\n useLayoutEffect(position)\n\n return (\n <div style={overlayStyle}>\n {peers.map((peer) => (\n <div\n key={peer.id}\n ref={(el) => {\n if (el) refs.current.set(peer.id, el)\n else refs.current.delete(peer.id)\n }}\n // Hidden until the first frame places it: a wrapper mounted at the\n // origin would flash in the corner before its cursor arrives.\n style={{ ...cursorStyle, display: \"none\" }}\n data-rivet-peer-cursor={peer.id}\n >\n <Cursor peer={peer} />\n </div>\n ))}\n </div>\n )\n}\n","import {\n type ComponentType,\n type CSSProperties,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\"\nimport { anchorRect } from \"../anchor/registry\"\nimport { handleKey } from \"../constants\"\nimport { useRivetContext } from \"../context\"\nimport { collectPeerOutlines, type PeerOutlineEntry, peerOutlinesEqual } from \"../presence/outlines\"\nimport type { PeerOutlineProps } from \"../presence/registry\"\nimport type { PresenceTarget } from \"../presence/targets\"\nimport type { Rect, Viewport } from \"../types\"\nimport { worldToScreen } from \"../viewport\"\n\nconst overlayStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n // Claim chrome belongs to the canvas, so a box that has been panned off the\n // pane is clipped rather than left hanging over the app around it.\n overflow: \"hidden\",\n pointerEvents: \"none\",\n}\n\nconst wrapperStyle: CSSProperties = {\n position: \"absolute\",\n top: 0,\n left: 0,\n pointerEvents: \"none\",\n}\n\n/** World rect → screen rect under the current viewport. */\nfunction projectRect(rect: Rect, viewport: Viewport): Rect {\n const origin = worldToScreen({ x: rect.x, y: rect.y }, viewport)\n return {\n x: origin.x,\n y: origin.y,\n width: rect.width * viewport.zoom,\n height: rect.height * viewport.zoom,\n }\n}\n\n/**\n * Peer claims as DOM, from a consumer's own component\n * (`presenceOptions.outlineComponent`).\n *\n * Same division of labour as {@link PeerCursorLayer}: React mounts one wrapper\n * per claimed *target* and re-renders only when the claims themselves change,\n * while the box is written imperatively on every frame. A peer dragging a node\n * across the canvas moves a wrapper 60 times a second and re-renders nothing.\n *\n * The wrapper is the target's box in screen space, so a border drawn on it\n * lands exactly where the canvas would have stroked one; an edge target has no\n * box, so its wrapper is a zero-size point at the midpoint of the drawn path.\n * Chrome keeps its own scale — a name chip that shrank with zoom would be\n * unreadable — and the current zoom rides along as a `--rivet-zoom` custom\n * property for styling that does want to react to it.\n */\nexport function PeerOutlineLayer({\n component: Outline,\n}: {\n component: ComponentType<PeerOutlineProps>\n}): React.ReactElement {\n const { store } = useRivetContext()\n const [entries, setEntries] = useState<readonly PeerOutlineEntry[]>([])\n const refs = useRef(new Map<string, HTMLDivElement>())\n // As in the cursor layer: written when it moves, and when an element is seen\n // for the first time — a claim arriving at a settled zoom moves nothing.\n const zoomRef = useRef<number | null>(null)\n const zoomWritten = useRef(new WeakSet<HTMLElement>())\n\n /** Where a target is on screen right now, or null when it has no geometry. */\n const rectOf = useCallback(\n (target: PresenceTarget, viewport: Viewport): Rect | null => {\n if (target.kind === \"edge\") {\n const point = store.getPeerEdgeAnchors().get(target.id)\n // Only edges the renderer actually drew have one — an edge scrolled out\n // of the graph, or a backend without the seam, reports nothing.\n return point ? { x: point.x, y: point.y, width: 0, height: 0 } : null\n }\n const nodeId = target.kind === \"node\" ? target.id : target.nodeId\n if (!store.nodes.has(nodeId)) return null\n // The painted box: a node under a peer's gesture is already being drawn\n // at their live position, and chrome that says so has to agree with it.\n const node = store.getNodeRect(nodeId)\n if (target.kind === \"node\") return projectRect(node, viewport)\n const record = store.anchors.get(handleKey(nodeId, target.anchorId))\n // Unregistered or never measured — the anchor exists as a claim, not yet\n // as a place on screen.\n if (!record?.geometry) return null\n return projectRect(anchorRect(node, record.geometry), viewport)\n },\n [store],\n )\n\n const position = useCallback(() => {\n const viewport = store.getViewport()\n const zoomChanged = zoomRef.current !== viewport.zoom\n zoomRef.current = viewport.zoom\n for (const entry of entries) {\n const el = refs.current.get(entry.key)\n if (!el) continue\n const rect = rectOf(entry.target, viewport)\n if (!rect) {\n el.style.display = \"none\"\n continue\n }\n el.style.display = \"\"\n el.style.transform = `translate(${rect.x}px, ${rect.y}px)`\n el.style.width = `${rect.width}px`\n el.style.height = `${rect.height}px`\n if (zoomChanged || !zoomWritten.current.has(el)) {\n el.style.setProperty(\"--rivet-zoom\", String(viewport.zoom))\n zoomWritten.current.add(el)\n }\n }\n }, [store, entries, rectOf])\n\n useEffect(() => {\n return store.subscribeFrame(() => {\n // Recollected per frame rather than off the claims channel, because one\n // input doesn't go through it: a peer's live gesture arrives as transform\n // frames, which never notify React, and can beat the roster entry that\n // describes it. The equality check below is what keeps that cheap.\n const next = collectPeerOutlines(\n store.presence.getPeers(),\n store.presence.getPeerIdentities(),\n store.locks.getLocks(),\n )\n setEntries((prev) => (peerOutlinesEqual(prev, next) ? prev : next))\n position()\n })\n }, [store, position])\n\n // Position after every render, so a claim that has just arrived lands on its\n // target in the same commit instead of a frame later.\n useLayoutEffect(position)\n\n return (\n <div style={overlayStyle}>\n {entries.map((entry) => (\n <div\n key={entry.key}\n ref={(el) => {\n if (el) refs.current.set(entry.key, el)\n else refs.current.delete(entry.key)\n }}\n // Hidden until the first pass places it: a wrapper mounted at the\n // origin would flash in the corner of the pane.\n style={{ ...wrapperStyle, display: \"none\" }}\n data-rivet-peer-outline={entry.key}\n data-rivet-outline-kind={entry.target.kind}\n >\n <Outline target={entry.target} claims={entry.claims} lock={entry.lock} />\n </div>\n ))}\n </div>\n )\n}\n","import {\n type CSSProperties,\n type KeyboardEvent as ReactKeyboardEvent,\n type MouseEvent as ReactMouseEvent,\n type ReactNode,\n type PointerEvent as ReactPointerEvent,\n useCallback,\n} from \"react\"\nimport { useRivetContext, useRivetViewport } from \"../context\"\nimport { type ResolvedLane, requiredLaneHeight } from \"../swimlane/lanes\"\n\nconst containerStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n overflow: \"hidden\",\n // Chrome only — never intercept canvas panning or node dragging.\n pointerEvents: \"none\",\n zIndex: 5,\n}\n\nconst headerWrapperStyle: CSSProperties = {\n position: \"absolute\",\n left: 0,\n right: 0,\n overflow: \"hidden\",\n}\n\nconst defaultHeaderStyle: CSSProperties = {\n display: \"flex\",\n alignItems: \"center\",\n gap: 8,\n height: \"100%\",\n paddingLeft: 12,\n paddingRight: 12,\n background: \"#ffffff\",\n borderBottom: \"1px solid rgba(100, 116, 139, 0.2)\",\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n fontSize: 12,\n fontWeight: 600,\n letterSpacing: 0.4,\n textTransform: \"uppercase\",\n whiteSpace: \"nowrap\",\n}\n\nconst labelWrapperStyle: CSSProperties = {\n position: \"absolute\",\n overflow: \"hidden\",\n}\n\nconst defaultLabelStyle: CSSProperties = {\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n width: \"100%\",\n height: \"100%\",\n background: \"#ffffff\",\n borderRight: \"1px solid rgba(100, 116, 139, 0.2)\",\n}\n\nconst labelTextStyle: CSSProperties = {\n writingMode: \"vertical-rl\",\n transform: \"rotate(180deg)\",\n fontFamily: \"ui-monospace, SFMono-Regular, Menlo, monospace\",\n fontSize: 10,\n fontWeight: 600,\n letterSpacing: 0.6,\n textTransform: \"uppercase\",\n color: \"rgba(51, 65, 85, 0.85)\",\n whiteSpace: \"nowrap\",\n userSelect: \"none\",\n}\n\nconst RESIZE_HANDLE_HIT = 8\n\n/**\n * Sticky swimlane chrome, rendered in screen space above the graph: each group's\n * header pins to the top of the pane, each lane's label pins to the left edge,\n * and each lane gets a bottom resize handle. Re-renders on viewport changes.\n */\nexport function SwimlaneOverlay(): React.ReactElement | null {\n const {\n swimlaneGroups,\n swimlaneLabelWidth,\n swimlaneHeaderSize,\n swimlaneResizable,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n } = useRivetContext()\n const { x: vx, y: vy, zoom } = useRivetViewport()\n\n if (swimlaneGroups.length === 0) return null\n\n // Sticky header position per group — reused to keep lane labels below it.\n const headerBottomByGroup = new Map<string, number>()\n\n return (\n <div style={containerStyle}>\n {swimlaneGroups.map((group) => {\n const screenTop = group.top * zoom + vy\n const screenBottom = group.bottom * zoom + vy\n const stickyY = Math.max(0, Math.min(screenTop, screenBottom - swimlaneHeaderSize))\n headerBottomByGroup.set(group.id, stickyY + swimlaneHeaderSize)\n if (screenBottom <= 0) return null\n const sticky = stickyY > screenTop\n\n return (\n <div\n key={group.id}\n style={{ ...headerWrapperStyle, top: stickyY, height: swimlaneHeaderSize }}\n >\n {renderSwimlaneHeader ? (\n renderSwimlaneHeader({ id: group.id, label: group.label, color: group.color, sticky })\n ) : (\n <div\n style={{\n ...defaultHeaderStyle,\n boxShadow: sticky ? \"0 1px 2px rgba(0, 0, 0, 0.08)\" : undefined,\n }}\n >\n {group.label}\n </div>\n )}\n </div>\n )\n })}\n\n {swimlaneGroups.flatMap((group) =>\n group.lanes.map((lane) => {\n if (!lane.label) return null\n const headerBottom = headerBottomByGroup.get(group.id) ?? 0\n const screenX = lane.x * zoom + vx\n const screenTop = lane.top * zoom + vy\n const screenBottom = screenTop + lane.height * zoom\n const screenEndX = screenX + lane.width * zoom\n const stickyX = Math.max(0, Math.min(screenX, screenEndX - swimlaneLabelWidth))\n const clampedTop = Math.max(headerBottom, screenTop)\n const labelHeight = screenBottom - clampedTop\n if (screenBottom <= headerBottom || labelHeight <= 0) return null\n\n return (\n <div\n key={lane.id}\n style={{\n ...labelWrapperStyle,\n left: stickyX,\n top: clampedTop,\n width: swimlaneLabelWidth,\n height: labelHeight,\n }}\n >\n {renderSwimlaneLabel ? (\n renderSwimlaneLabel({\n id: lane.id,\n label: lane.label,\n color: lane.color,\n groupId: lane.groupId,\n })\n ) : (\n <div style={defaultLabelStyle}>\n <span style={labelTextStyle}>{lane.label}</span>\n </div>\n )}\n </div>\n )\n }),\n )}\n\n {swimlaneResizable &&\n swimlaneGroups.flatMap((group) =>\n group.lanes.map((lane) => {\n const bottom = (lane.top + lane.height) * zoom + vy\n // Above the pane top is clipped anyway; skip so we don't stack strips.\n if (bottom < 0) return null\n return (\n <LaneResizeHandle key={lane.id} lane={lane} top={bottom - RESIZE_HANDLE_HIT / 2} />\n )\n }),\n )}\n </div>\n )\n}\n\nconst handleStyle: CSSProperties = {\n position: \"absolute\",\n left: 0,\n right: 0,\n height: RESIZE_HANDLE_HIT,\n cursor: \"ns-resize\",\n pointerEvents: \"auto\",\n touchAction: \"none\",\n}\n\n/** A full-width grab strip on a lane's bottom edge that resizes the lane. */\nfunction LaneResizeHandle({ lane, top }: { lane: ResolvedLane; top: number }): ReactNode {\n const { store, resizeSwimlane, swimlaneMargin } = useRivetContext()\n\n // Double-click the handle to snap the lane's height to fit its nodes (the same\n // shrink-to-content you'd reach by dragging all the way down).\n const onDoubleClick = useCallback(\n (event: ReactMouseEvent<HTMLDivElement>) => {\n event.stopPropagation()\n const next = requiredLaneHeight(lane, store.nodes.values(), swimlaneMargin.bottom)\n resizeSwimlane(lane.id, next, true, \"autofit\")\n },\n [store, resizeSwimlane, swimlaneMargin.bottom, lane],\n )\n\n const onPointerDown = useCallback(\n (event: ReactPointerEvent<HTMLDivElement>) => {\n if (event.button !== 0) return\n event.stopPropagation()\n event.preventDefault()\n const startClientY = event.clientY\n const startHeight = lane.height\n const laneId = lane.id\n\n const onMove = (moveEvent: PointerEvent) => {\n const zoom = store.getViewport().zoom || 1\n const next = startHeight + (moveEvent.clientY - startClientY) / zoom\n resizeSwimlane(laneId, next, false)\n }\n const onUp = (upEvent: PointerEvent) => {\n window.removeEventListener(\"pointermove\", onMove)\n window.removeEventListener(\"pointerup\", onUp)\n const zoom = store.getViewport().zoom || 1\n const next = startHeight + (upEvent.clientY - startClientY) / zoom\n resizeSwimlane(laneId, next, true)\n }\n window.addEventListener(\"pointermove\", onMove)\n window.addEventListener(\"pointerup\", onUp)\n },\n [store, resizeSwimlane, lane.id, lane.height],\n )\n\n // Arrow keys resize the focused handle's lane; each press commits (so it's\n // undoable/persistable via onSwimlaneSizeChange like a drag's drop).\n const onKeyDown = useCallback(\n (event: ReactKeyboardEvent<HTMLDivElement>) => {\n const dir = event.key === \"ArrowDown\" ? 1 : event.key === \"ArrowUp\" ? -1 : 0\n if (dir === 0) return\n event.preventDefault()\n const step = event.shiftKey ? 50 : 10\n resizeSwimlane(lane.id, lane.height + dir * step, true)\n },\n [resizeSwimlane, lane.id, lane.height],\n )\n\n return (\n // biome-ignore lint/a11y/useSemanticElements: a focusable, arrow-key-resizable separator is an interactive widget — <hr> can't take focus or gestures\n <div\n data-rivet-swimlane-handle=\"\"\n role=\"separator\"\n aria-orientation=\"horizontal\"\n aria-label={`Resize lane ${lane.label ?? lane.id}`}\n aria-valuenow={Math.round(lane.height)}\n tabIndex={0}\n style={{ ...handleStyle, top }}\n onPointerDown={onPointerDown}\n onDoubleClick={onDoubleClick}\n onKeyDown={onKeyDown}\n />\n )\n}\n","import {\n type CSSProperties,\n type MouseEvent as ReactMouseEvent,\n type ReactNode,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n} from \"react\"\nimport { type AnchorOptions, normalizeAnchorConnection } from \"../anchor/registry\"\nimport { SELECTOR } from \"../constants\"\nimport { RivetContext, type RivetContextValue } from \"../context\"\nimport type { EdgeAlignment } from \"../edge-alignment\"\nimport { useLocalPresence } from \"../hooks/use-local-presence\"\nimport { useRivetConfig } from \"../hooks/use-rivet-config\"\nimport { useRivetRuntime } from \"../hooks/use-rivet-runtime\"\nimport { useSwimlanes } from \"../hooks/use-swimlanes\"\nimport type { CanInteractWithLocked } from \"../locks/registry\"\nimport type { LocalPresence } from \"../presence/local\"\nimport type { PeerOutlineMode } from \"../presence/outlines\"\nimport type { Peer, PresenceOptions } from \"../presence/registry\"\nimport type { PresenceTargetKey } from \"../presence/targets\"\nimport { canvas2DEdgeRenderer } from \"../renderer/canvas-2d-edge-renderer\"\nimport { createRivetStore, type RivetStore } from \"../store\"\nimport { type ResolvedLane, SWIMLANE_LABEL_WIDTH, swimlaneChromeAt } from \"../swimlane/lanes\"\nimport type {\n ChangeMeta,\n Connection,\n DefaultEdgeOptions,\n EdgeChange,\n EdgeRendererFactory,\n EdgeTypes,\n LaneChange,\n NodeChange,\n NodeGestureEvent,\n NodeId,\n NodeLockConflictEvent,\n NodeTypes,\n RivetEdge,\n RivetNode,\n RivetSelection,\n SwimlaneGroup,\n SwimlaneHeaderProps,\n SwimlaneLabelProps,\n SwimlaneMargin,\n SwimlaneSizeChange,\n Vec2,\n Viewport,\n} from \"../types\"\nimport { screenToWorld } from \"../viewport\"\nimport { EdgeLabelLayer } from \"./edge-label-layer\"\nimport { NodeLayer } from \"./node-layer\"\nimport { PeerCursorLayer } from \"./peer-cursor-layer\"\nimport { PeerOutlineLayer } from \"./peer-outline-layer\"\nimport { SwimlaneOverlay } from \"./swimlane-overlay\"\n\n/** Resolved graph context for a pane right-click, passed to `onPaneContextMenu`. */\nexport type PaneContextMenuContext = {\n /** The click position in world coordinates (already unprojected). */\n world: Vec2\n /** The swimlane lane whose body sits under the cursor, or `null`. */\n lane: ResolvedLane | null\n}\n\nexport type RivetProps = {\n /**\n * Nodes to seed the graph with (uncontrolled). Read once on mount to initialize\n * the internal store — later changes to this array are ignored. Use {@link nodes}\n * + {@link onNodesChange} for controlled mode instead. Defaults to `[]`.\n */\n defaultNodes?: RivetNode[]\n /**\n * Edges to seed the graph with (uncontrolled). See {@link defaultNodes}. An edge\n * whose `source` or `target` node is absent is skipped by the renderer. Defaults to `[]`.\n */\n defaultEdges?: RivetEdge[]\n /**\n * Controlled nodes. When provided, the graph mirrors this array — hold the nodes\n * in your own state and feed back the batches from {@link onNodesChange} (apply\n * them with `applyNodeChanges`). A node under a live gesture keeps its own\n * geometry rather than the array's, so a drag stays smooth while the props\n * lag behind it. Takes precedence over {@link defaultNodes}.\n */\n nodes?: RivetNode[]\n /** Controlled edges. See {@link nodes}. Takes precedence over {@link defaultEdges}. */\n edges?: RivetEdge[]\n /**\n * Change batches the graph wants applied to your nodes (controlled mode).\n *\n * `meta.origin` says where the batch came from: `\"local\"` for anything this\n * client did, `\"remote\"` for a batch that arrived through\n * {@link RivetInstance.applyRemote}. Multiplayer consumers apply both and send\n * only the local ones onward — an untagged echo is indistinguishable from a\n * peer's edit and loops straight back out.\n */\n onNodesChange?: (changes: NodeChange[], meta: ChangeMeta) => void\n /** Change batches the graph wants applied to your edges (controlled mode). See {@link onNodesChange}. */\n onEdgesChange?: (changes: EdgeChange[], meta: ChangeMeta) => void\n /**\n * Initial pan/zoom. `x`/`y` are the screen-space offset in pixels and `zoom`\n * is the scale factor. Defaults to `{ x: 0, y: 0, zoom: 1 }` (origin, 1:1).\n */\n defaultViewport?: Viewport\n /**\n * Maps a node's `type` to the React component that renders it. A node whose\n * `type` has no entry here (or no `type` at all) falls back to\n * {@link DefaultNode}. Defaults to `{}`.\n */\n nodeTypes?: NodeTypes\n /**\n * Registry of custom edge shapes, keyed by `edge.type`. Each is a pure geometry\n * function (see {@link EdgePathFn}) so edges stay canvas/GPU-renderable. Merged\n * over the built-ins `bezier` (default), `smoothstep`, `step`, and `straight`.\n */\n edgeTypes?: EdgeTypes\n /** Defaults merged into every edge that doesn't set the field (type, style, markers…). */\n defaultEdgeOptions?: DefaultEdgeOptions\n /** Accessible name for the graph surface (`aria-label` on the pane). Defaults to \"Node graph\". */\n ariaLabel?: string\n /**\n * Backend factory for the edge layers — swap Canvas2D for another\n * {@link EdgeRenderer}. Defaults to {@link canvas2DEdgeRenderer}. Pass a stable/memoized\n * reference; a new identity re-creates the renderers.\n */\n renderer?: EdgeRendererFactory\n /**\n * Lower bound on `viewport.zoom`. All zooming (wheel, controls, `fitView`) is\n * clamped to this. Defaults to `0.2` (zoomed out to 20%).\n */\n minZoom?: number\n /**\n * Upper bound on `viewport.zoom`. All zooming is clamped to this. Defaults to\n * `2.5` (zoomed in to 250%).\n */\n maxZoom?: number\n /**\n * Spacing in world units between background grid dots. The grid scales with\n * zoom, so this is measured at `zoom === 1`. Defaults to `24`.\n */\n gridGap?: number\n /**\n * Snap dragged nodes to a `[x, y]` world-unit grid. A `0` axis is left free.\n * Omit (default) for free positioning. Independent of {@link gridGap} (the\n * visual dot grid) — pass the same value to snap to the dots you see.\n */\n snapGrid?: [number, number]\n /**\n * While dragging a single node, show alignment guides and snap its edges/center\n * to nearby nodes' edges/centers. Defaults to `false`.\n */\n alignmentGuides?: boolean\n /**\n * Placement policy for anchor chrome — the grab dots and stray perimeter\n * handles rivet renders for registered anchors (see {@link Anchor}). Omitted\n * fields fall back to the defaults.\n */\n anchorOptions?: AnchorOptions\n /**\n * The other people in this document — the presence roster. Identity (name,\n * colour, `data`) plus the slow fields: what each peer has selected, and what\n * they're holding under a gesture. Rivet paints them: a cursor per peer, an\n * outline around what they've selected, and the nodes they're moving drawn\n * where they currently have them.\n *\n * Claims are node ids, or `PresenceTarget`s for an edge or an anchor. Only\n * nodes are painted today — the rest travels and is readable through\n * {@link usePeers}, which is what a consumer rendering its own chrome needs.\n *\n * Peer cursors move far faster than React should re-render, so the roster\n * carries only a seed for them — feed live cursors and drag boxes through\n * {@link RivetInstance.setPeerCursor} / `setPeerNodeTransform` instead.\n *\n * Presence is ephemeral: none of it reaches the graph, the change stream, or\n * history. Dropping a peer from the array is how they leave.\n */\n peers?: Peer[]\n /**\n * Called with this client's presence — cursor (in world coordinates),\n * selection, and held nodes — as a whole snapshot, ready to broadcast.\n *\n * Snapshots are idempotent, so a dropped or duplicated one costs nothing and\n * a reconnecting peer is instantly correct. Cursor movement is coalesced to\n * `presenceOptions.throttleMs`; selection and gesture changes are published\n * immediately.\n */\n onLocalPresence?: (presence: LocalPresence) => void\n /**\n * Presence policy — the outbound throttle, and how peer cursors are drawn:\n * rivet's canvas arrow, your own component, or nothing.\n *\n * Compared shallowly, so `cursorComponent` must be a stable reference —\n * declared outside the render or memoized. An inline component would be a new\n * type on every render, and React remounts every cursor when the type changes.\n */\n presenceOptions?: PresenceOptions\n /**\n * What a peer has claimed, as `target -> peerId`. Locks are policy where\n * {@link peers} is description: rivet paints a claimed element in its\n * holder's colour *and* refuses to act on it.\n *\n * Keys are {@link PresenceTargetKey}s, and a bare node id is its own key — so\n * `{ n1: \"ada\" }` means exactly what it always did, and edges and anchors\n * join on the same table:\n *\n * ```tsx\n * <Rivet\n * lockedNodes={{\n * n1: \"ada\", // a node, and everything inside it\n * \"edge:e7\": \"kai\", // an edge — refuses reconnection\n * \"anchor:n2:door\": \"wren\", // one anchor inside n2\n * }}\n * />\n * ```\n *\n * By default it refuses selection, dragging, resizing, deletion and\n * reconnection, and allows connections — a lock claims the element, not the\n * graph around it. {@link canInteractWithLocked} replaces that policy.\n *\n * A node's lock reaches its contents and their anchors; an edge's reaches\n * nothing, since an edge belongs to no container.\n *\n * Lifetime is yours: rivet never takes or releases a lock, it only reads the\n * table. Take one in {@link onNodeDragStart} and drop it in\n * {@link onNodeDragEnd} for drag-scoped locks, or hold through deselection\n * for something stickier. Like presence, none of this reaches the graph, the\n * change stream, or history.\n */\n lockedNodes?: Record<PresenceTargetKey, string>\n /**\n * Decide what this client may do to a locked element, per attempt. Return\n * `true` to allow the intent, `false` to refuse it.\n *\n * A handler owns the whole policy — rivet's defaults are replaced, not\n * consulted — so answer every intent you care about:\n *\n * ```tsx\n * // locked nodes stay inspectable, but nothing may change them\n * canInteractWithLocked={({ intent }) => intent === \"select\" || intent === \"connect\"}\n * ```\n *\n * `target` is what was touched and `lockedTarget` is what carries the lock —\n * they differ when a lock is inherited, which is how a locked container can\n * hold itself while leaving its contents free:\n *\n * ```tsx\n * canInteractWithLocked={({ target, lockedTarget }) =>\n * target.kind === \"node\" && lockedTarget.kind === \"node\" && target.id !== lockedTarget.id\n * }\n * ```\n *\n * Called on the input path (every marquee frame, every mover), so keep it\n * cheap and free of side effects.\n */\n canInteractWithLocked?: CanInteractWithLocked\n /**\n * Called when a lock for a peer arrives on a node this client is already\n * holding — two clients started before either lock reached the other.\n *\n * rivet reports it and keeps going: the running gesture stays authoritative\n * over its geometry, because only your transport knows which client actually\n * lost the race. To yield, call {@link RivetInstance.releaseNodeGesture} —\n * the gesture stops writing and tears down without committing.\n */\n onNodeLockConflict?: (event: NodeLockConflictEvent) => void\n /**\n * Which mouse buttons pan when dragging the pane: `true` = left only, `false` =\n * none, or a list of `MouseEvent.button` codes (`0` left, `1` middle, `2` right).\n * e.g. `[1, 2]` pans with middle/right and frees left for selection. Defaults to\n * `true`. Pass a stable reference; a new array identity re-binds the listeners.\n */\n panOnDrag?: boolean | number[]\n /**\n * Draw a selection marquee on a plain left-drag instead of panning. Pair with\n * `panOnDrag={[1, 2]}` so left selects and middle/right pan. A marquee that\n * ends over nodes leaves a persistent selection box around them — drag it to\n * move the whole selection; a click elsewhere or Escape dismisses it.\n * Defaults to `false`.\n */\n selectionOnDrag?: boolean\n /**\n * Key(s) that force a marquee on a left-drag when held (e.g. `\"Shift\"`, `\"Meta\"`,\n * or `[\"Shift\", \"Meta\"]`). `null` disables. Defaults to `\"Shift\"`.\n */\n selectionKeyCode?: string | string[] | null\n /**\n * Key(s) that make a click or marquee **add to** the selection instead of\n * replacing it. Defaults to `[\"Meta\", \"Control\", \"Shift\"]`. Use modifier keys\n * (`Shift`/`Meta`/`Control`/`Alt`) — other keys only resolve during a pane drag.\n */\n multiSelectionKeyCode?: string | string[]\n /**\n * Pan the viewport on wheel / two-finger trackpad scroll instead of zooming.\n * A pinch gesture (reported by the browser as ctrl+wheel) still zooms. When\n * `false` (default), scrolling zooms toward the cursor.\n */\n scrollToPan?: boolean\n /**\n * Wheel/pinch zoom sensitivity — larger zooms faster per scroll delta.\n * Defaults to `0.0015`. Try `~0.003` for faster trackpad pinch zoom.\n */\n zoomSpeed?: number\n /**\n * Swimlanes drawn behind the graph — a decorative background of labeled lane\n * groups (like planout's swimlanes). Not nodes or edges; just layout regions.\n * Omit for no swimlanes.\n */\n swimlane?: SwimlaneGroup[]\n /**\n * Bind node dragging to the swimlanes: on drop each node snaps fully inside\n * one lane (honoring {@link swimlaneMargin}) and is reassigned to the lane it\n * lands in via {@link RivetNode.laneId}. Defaults to `true` when\n * {@link swimlane} is provided, `false` otherwise. Ignored with no swimlanes.\n */\n clampToSwimlane?: boolean\n /**\n * Inner clearance kept between a clamped node and its lane's edges. A number\n * applies to all sides; per-side values override it. Defaults to `16`.\n */\n swimlaneMargin?: number | SwimlaneMargin\n /** Screen height of the sticky group header band, in px. Defaults to `32`. */\n swimlaneHeaderHeight?: number\n /**\n * Show a resize handle on each lane's bottom edge to change its height.\n * Defaults to `true` when {@link swimlane} is provided.\n */\n swimlaneResizable?: boolean\n /**\n * Fraction of the last lane's height that must stay visible when scrolled to\n * the bottom — the down-scroll stop. `0.5` (default) keeps half of it in view.\n * Only applies when {@link clampToSwimlane} is on.\n */\n swimlaneBottomReveal?: number\n /** Render custom content for a group's sticky header (replaces the default). */\n renderSwimlaneHeader?: (props: SwimlaneHeaderProps) => ReactNode\n /** Render custom content for a lane's sticky label (replaces the default). */\n renderSwimlaneLabel?: (props: SwimlaneLabelProps) => ReactNode\n /**\n * Called when a lane's height changes — from a resize drag or from auto-fit\n * growing it to contain a node that grew. The graph owns lane heights, so this\n * is a notification (persist it if you like), not a request to update state.\n */\n onSwimlaneSizeChange?: (change: SwimlaneSizeChange) => void\n /**\n * Right-click on empty canvas (not over a node or swimlane chrome). The second\n * argument carries the resolved graph context — the world position and the lane\n * under the cursor — so you don't have to re-derive them.\n */\n onPaneContextMenu?: (event: ReactMouseEvent, context: PaneContextMenuContext) => void\n /** Right-click on a lane's sticky label. */\n onSwimlaneHeaderContextMenu?: (laneId: string, event: ReactMouseEvent) => void\n /** Right-click on a group's sticky header. */\n onSwimlaneGroupHeaderContextMenu?: (groupId: string, event: ReactMouseEvent) => void\n /** Called when a dragged node is reassigned to a different lane. */\n onLaneChange?: (change: LaneChange) => void\n /** Veto a proposed connection; return false to reject it. Applies to reconnection too. */\n isValidConnection?: (connection: Connection) => boolean\n /**\n * Rewrite a validated connection before it commits — normalize handle ids\n * (e.g. redirect an in-content grab handle to its canonical perimeter\n * handle), or force direction conventions. Returning `null` cancels the\n * drop. Applies to new connections and reconnections; `isValidConnection`\n * sees the raw connection, `onConnect`/`onReconnect` see the mapped one.\n */\n mapConnection?: (connection: Connection) => Connection | null\n /** Called after a valid connection is made (the edge is already added). */\n onConnect?: (connection: Connection) => void\n /**\n * Allow reconnecting edges by dragging an endpoint onto a new handle. Per-edge\n * `reconnectable` overrides this. Defaults to `false`.\n */\n edgesReconnectable?: boolean\n /**\n * When edge endpoints re-side to face the peer node. `\"manual\"` (default)\n * never rewrites a chosen handle; `\"on-move\"` re-sides both ends of a moved\n * node's edges when the move commits — in the same batch as the move, so one\n * undo restores position and handles together. `\"live\"` additionally renders\n * a dragging node's edges as if their ends were auto — re-siding per frame\n * to face each other, with hysteresis so near-diagonal positions don't\n * flicker — and commits the displayed sides on drop, inside the move's\n * history step; nothing is persisted mid-gesture. Only committed position\n * changes trigger a rewrite: data replaces and dimension changes never\n * re-side, and a freshly created or reconnected edge keeps exactly the\n * handles the user grabbed or dropped on. Anchor and bare-side ends rewrite\n * their side directly; plain handles re-side to a registered handle of a\n * compatible type on the facing side, or stay pinned when the node has none\n * there. Independent of the policy, an end with *no* side — a missing\n * handle, or an `anchorAutoHandleId` anchor end — always floats: the\n * renderer resolves its facing side per frame and never writes it back.\n */\n edgeAlignment?: EdgeAlignment\n /** Called when an endpoint drag re-points an edge (the edge is already updated). */\n onReconnect?: (edge: RivetEdge, connection: Connection) => void\n /** Called when an endpoint reconnection drag starts. */\n onReconnectStart?: (edge: RivetEdge) => void\n /** Called when an endpoint reconnection drag ends (committed or cancelled). */\n onReconnectEnd?: (edge: RivetEdge) => void\n /**\n * Called when a local gesture takes hold of one or more nodes — a pointer\n * drag, a resize, or a keyboard grab. While it's open, those nodes' geometry\n * belongs to this client: remote `position`/`dimensions` writes for them are\n * dropped, and controlled props can't stomp the live box.\n *\n * In a shared document this is where you acquire a lock. It's paired with\n * {@link onNodeDragEnd} — every start gets exactly one end, including a\n * cancelled keyboard grab.\n */\n onNodeDragStart?: (event: NodeGestureEvent) => void\n /** Called when a gesture releases its nodes. See {@link onNodeDragStart}. */\n onNodeDragEnd?: (event: NodeGestureEvent) => void\n /** Called whenever the selected nodes and/or edges change. */\n onSelectionChange?: (selection: RivetSelection) => void\n /**\n * Called when keyboard focus moves to a node (or leaves the graph — `null`).\n * The same state is available inside `<Rivet>` via {@link useRivetFocusedNode}.\n * Rivet draws no focus ring; use this (or the wrapper's `:focus-visible`) to\n * render your own indicator.\n */\n onFocusChange?: (id: NodeId | null) => void\n className?: string\n style?: CSSProperties\n children?: ReactNode\n}\n\nconst paneStyle: CSSProperties = {\n position: \"relative\",\n width: \"100%\",\n height: \"100%\",\n overflow: \"hidden\",\n touchAction: \"none\",\n}\n\nconst canvasStyle: CSSProperties = {\n position: \"absolute\",\n inset: 0,\n pointerEvents: \"none\",\n}\n\n// Visually hidden but still read by screen readers (the live region and the\n// keyboard-instructions element the node wrappers point aria-describedby at).\nconst srOnlyStyle: CSSProperties = {\n position: \"absolute\",\n width: 1,\n height: 1,\n margin: -1,\n padding: 0,\n overflow: \"hidden\",\n clipPath: \"inset(50%)\",\n whiteSpace: \"nowrap\",\n border: 0,\n}\n\nconst NODE_KEYBOARD_INSTRUCTIONS =\n \"Press Enter to select and grab the node. While grabbed, use the arrow keys to move it, \" +\n \"Enter to drop, Escape to cancel. Press Delete to remove the selection.\"\n\n// Object/array defaults are hoisted so an omitted prop keeps a stable identity\n// across renders instead of allocating a fresh value each render (which would\n// churn the context / re-mount the render loop). Inline-passed values are\n// stabilized separately by useRivetConfig.\nconst DEFAULT_MULTI_SELECTION_KEY_CODE = [\"Meta\", \"Control\", \"Shift\"]\nconst EMPTY_NODE_TYPES: NodeTypes = {}\nconst EMPTY_NODES: RivetNode[] = []\nconst EMPTY_EDGES: RivetEdge[] = []\nconst DEFAULT_VIEWPORT: Viewport = { x: 0, y: 0, zoom: 1 }\n\n/**\n * The graph surface. Stacks a background grid canvas, an edge canvas, and a DOM\n * node layer — all driven by one shared viewport (see {@link useRivetRuntime}).\n */\nexport function Rivet({\n defaultNodes = EMPTY_NODES,\n defaultEdges = EMPTY_EDGES,\n nodes: controlledNodes,\n edges: controlledEdges,\n onNodesChange,\n onEdgesChange,\n defaultViewport = DEFAULT_VIEWPORT,\n nodeTypes = EMPTY_NODE_TYPES,\n edgeTypes,\n defaultEdgeOptions,\n ariaLabel,\n renderer = canvas2DEdgeRenderer,\n minZoom = 0.2,\n maxZoom = 2.5,\n gridGap = 24,\n snapGrid,\n alignmentGuides = false,\n anchorOptions,\n peers,\n onLocalPresence,\n presenceOptions,\n lockedNodes,\n canInteractWithLocked,\n onNodeLockConflict,\n panOnDrag = true,\n selectionOnDrag = false,\n selectionKeyCode = \"Shift\",\n multiSelectionKeyCode = DEFAULT_MULTI_SELECTION_KEY_CODE,\n scrollToPan = false,\n zoomSpeed = 0.0015,\n swimlane,\n clampToSwimlane,\n swimlaneMargin,\n swimlaneHeaderHeight = 32,\n swimlaneResizable,\n swimlaneBottomReveal = 0.5,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n onSwimlaneSizeChange,\n onPaneContextMenu,\n onSwimlaneHeaderContextMenu,\n onSwimlaneGroupHeaderContextMenu,\n onLaneChange,\n isValidConnection,\n mapConnection,\n onConnect,\n edgesReconnectable,\n edgeAlignment = \"manual\",\n onReconnect,\n onReconnectStart,\n onReconnectEnd,\n onNodeDragStart,\n onNodeDragEnd,\n onSelectionChange,\n onFocusChange,\n className,\n style,\n children,\n}: RivetProps): React.ReactElement {\n const storeRef = useRef<RivetStore | null>(null)\n if (storeRef.current === null) {\n // Controlled props seed the store too; reconcile keeps it in sync thereafter.\n storeRef.current = createRivetStore({\n nodes: controlledNodes ?? defaultNodes,\n edges: controlledEdges ?? defaultEdges,\n viewport: defaultViewport,\n })\n }\n const store = storeRef.current\n\n // Resolve every identity-sensitive prop to a stable reference once, so an inline\n // object/handler from the consumer can't churn the context or re-mount the loop.\n const cfg = useRivetConfig({\n nodeTypes,\n edgeTypes,\n defaultEdgeOptions,\n snapGrid,\n swimlaneMargin,\n anchorOptions,\n presenceOptions,\n panOnDrag,\n selectionKeyCode,\n multiSelectionKeyCode,\n isValidConnection,\n mapConnection,\n onConnect,\n onLaneChange,\n renderSwimlaneHeader,\n renderSwimlaneLabel,\n })\n\n // Anchor grab dot ids are chrome — rewrite them to the persisted stray ids\n // (same anchor, same side) before any edge commits. The consumer's\n // `mapConnection` still runs last, on the normalized connection;\n // `isValidConnection` keeps seeing the raw one.\n const mapConnectionWithAnchors = useMemo(\n () =>\n (connection: Connection): Connection | null => {\n const normalized = normalizeAnchorConnection(connection)\n return cfg.mapConnection ? cfg.mapConnection(normalized) : normalized\n },\n [cfg.mapConnection],\n )\n\n useEffect(() => {\n store.setEdgeAlignment(edgeAlignment)\n }, [store, edgeAlignment])\n\n // Keep the latest callback in a ref so we subscribe exactly once, even when an\n // inline `onSelectionChange` gets a new identity each render.\n const onSelectionChangeRef = useRef(onSelectionChange)\n onSelectionChangeRef.current = onSelectionChange\n useEffect(\n () => store.subscribeSelection((selection) => onSelectionChangeRef.current?.(selection)),\n [store],\n )\n\n const onFocusChangeRef = useRef(onFocusChange)\n onFocusChangeRef.current = onFocusChange\n useEffect(() => store.subscribeFocus((id) => onFocusChangeRef.current?.(id)), [store])\n\n // Screen-reader narration for keyboard interactions (grab/move/drop, connect).\n // Components publish through the context's `announce`; the pane renders the\n // message into a hidden polite live region.\n const [announcement, setAnnouncement] = useState(\"\")\n const announce = useCallback((message: string) => setAnnouncement(message), [])\n const nodeDescriptionId = useId()\n\n // Controlled mode: forward the store's change batches to the consumer. Handlers\n // read the latest callback via refs; presence toggles re-register them.\n const onNodesChangeRef = useRef(onNodesChange)\n onNodesChangeRef.current = onNodesChange\n const onEdgesChangeRef = useRef(onEdgesChange)\n onEdgesChangeRef.current = onEdgesChange\n const hasNodeChange = Boolean(onNodesChange)\n const hasEdgeChange = Boolean(onEdgesChange)\n useEffect(() => {\n store.setChangeHandlers({\n nodes: hasNodeChange\n ? (changes, meta) => onNodesChangeRef.current?.(changes, meta)\n : undefined,\n edges: hasEdgeChange\n ? (changes, meta) => onEdgesChangeRef.current?.(changes, meta)\n : undefined,\n })\n return () => store.setChangeHandlers({})\n }, [store, hasNodeChange, hasEdgeChange])\n\n const onNodeDragStartRef = useRef(onNodeDragStart)\n onNodeDragStartRef.current = onNodeDragStart\n const onNodeDragEndRef = useRef(onNodeDragEnd)\n onNodeDragEndRef.current = onNodeDragEnd\n const onNodeLockConflictRef = useRef(onNodeLockConflict)\n onNodeLockConflictRef.current = onNodeLockConflict\n useEffect(() => {\n store.setGestureHandlers({\n start: (event) => onNodeDragStartRef.current?.(event),\n end: (event) => onNodeDragEndRef.current?.(event),\n conflict: (event) => onNodeLockConflictRef.current?.(event),\n })\n return () => store.setGestureHandlers({})\n }, [store])\n\n // Controlled mode: mirror the incoming props into the store. A live gesture\n // isn't skipped wholesale — reconcile keeps held nodes' geometry (the props\n // lag the store while live frames are dropped, so taking them would stomp the\n // moving box) and applies everything else, so a peer's rename still lands on a\n // node this client is dragging. The commit emits a final change that re-runs\n // this and settles the store.\n const isControlled = controlledNodes !== undefined || controlledEdges !== undefined\n useEffect(() => {\n if (!isControlled) return\n store.reconcile(\n controlledNodes ?? [...store.nodes.values()],\n controlledEdges ?? [...store.edges.values()],\n )\n }, [store, isControlled, controlledNodes, controlledEdges])\n\n const swimlanes = useSwimlanes({\n store,\n swimlane,\n swimlaneMargin: cfg.swimlaneMargin,\n swimlaneResizable,\n clampToSwimlane,\n swimlaneBottomReveal,\n onSwimlaneSizeChange,\n })\n\n // Right-click routing: swimlane group header → lane label → empty pane.\n const handleContextMenu = useCallback(\n (event: ReactMouseEvent<HTMLDivElement>) => {\n if (event.target instanceof Element && event.target.closest(SELECTOR.node)) return\n const viewport = store.getViewport()\n const rect = paneRef.current?.getBoundingClientRect()\n const point = { x: event.clientX - (rect?.left ?? 0), y: event.clientY - (rect?.top ?? 0) }\n if (swimlanes.groups.length > 0) {\n const hit = swimlaneChromeAt(\n swimlanes.groups,\n viewport,\n point,\n swimlaneHeaderHeight,\n SWIMLANE_LABEL_WIDTH,\n )\n if (hit?.type === \"group\") return onSwimlaneGroupHeaderContextMenu?.(hit.id, event)\n if (hit?.type === \"lane\") return onSwimlaneHeaderContextMenu?.(hit.id, event)\n }\n // Resolve the click into graph terms: world position, and the lane whose\n // body it lands in (within its vertical band, right of its left edge).\n const world = screenToWorld(point, viewport)\n const lane =\n swimlanes.lanes.find(\n (l) => world.y >= l.top && world.y <= l.top + l.height && world.x >= l.x,\n ) ?? null\n onPaneContextMenu?.(event, { world, lane })\n },\n [\n store,\n swimlanes.groups,\n swimlanes.lanes,\n swimlaneHeaderHeight,\n onPaneContextMenu,\n onSwimlaneHeaderContextMenu,\n onSwimlaneGroupHeaderContextMenu,\n ],\n )\n\n const paneRef = useRef<HTMLDivElement>(null)\n const nodeContainerRef = useRef<HTMLDivElement>(null)\n const backgroundCanvasRef = useRef<HTMLCanvasElement>(null)\n const edgeCanvasRef = useRef<HTMLCanvasElement>(null)\n const foregroundCanvasRef = useRef<HTMLCanvasElement>(null)\n const cursorCanvasRef = useRef<HTMLCanvasElement>(null)\n\n // Presence, inbound: mirror the roster into the registry the render loop\n // paints from. Only when the prop is in use — a consumer driving presence\n // purely through `setPeerCursor` has no roster to be overwritten by.\n useEffect(() => {\n if (peers === undefined) return\n store.presence.setPeers(peers)\n }, [store, peers])\n\n // Locks. The policy goes in through a ref-backed forwarder because it's read\n // on the input path — an inline arrow would otherwise reinstall it on every\n // render, and `null` vs. a function is the difference between rivet's\n // defaults and the consumer's.\n const canInteractWithLockedRef = useRef(canInteractWithLocked)\n canInteractWithLockedRef.current = canInteractWithLocked\n const hasLockPolicy = Boolean(canInteractWithLocked)\n useEffect(() => {\n store.locks.setPolicy(\n hasLockPolicy ? (event) => canInteractWithLockedRef.current?.(event) ?? true : null,\n )\n return () => store.locks.setPolicy(null)\n }, [store, hasLockPolicy])\n // Installed after the policy, so the first refusal a freshly locked node\n // meets is already the consumer's. An unchanged table is a no-op, so an\n // inline object literal costs nothing.\n useEffect(() => {\n store.setLockedNodes(lockedNodes)\n }, [store, lockedNodes])\n\n // Presence, outbound: this client's cursor/selection/held snapshot.\n useLocalPresence({ store, paneRef, onLocalPresence, throttleMs: cfg.presenceOptions.throttleMs })\n\n // Where peer claims are painted. Three states per layer, as with cursors:\n // rivet's own outlines, the consumer's component (in which case the canvas\n // pass is skipped), and nothing under `renderOutlines: false`.\n const outlineMode: PeerOutlineMode = !cfg.presenceOptions.renderOutlines\n ? \"none\"\n : cfg.presenceOptions.outlineComponent\n ? \"dom\"\n : \"canvas\"\n\n const { visibleIds, controls, getViewportElements } = useRivetRuntime({\n store,\n paneRef,\n nodeContainerRef,\n backgroundCanvasRef,\n edgeCanvasRef,\n foregroundCanvasRef,\n cursorCanvasRef,\n outlineMode,\n swimlaneLanes: swimlanes.lanes,\n edgeTypes: cfg.edgeTypes,\n defaultEdgeOptions: cfg.defaultEdgeOptions,\n anchorOptions: cfg.anchorOptions,\n edgeRenderer: renderer,\n edgesReconnectable,\n isValidConnection: cfg.isValidConnection,\n mapConnection: mapConnectionWithAnchors,\n onReconnect,\n onReconnectStart,\n onReconnectEnd,\n panButtons: cfg.panButtons,\n selectionOnDrag,\n selectionKeys: cfg.selectionKeys,\n multiSelectionKeys: cfg.multiSelectionKeys,\n scrollToPan,\n zoomSpeed,\n minZoom,\n maxZoom,\n gridGap,\n snapGrid: cfg.snapGrid,\n })\n\n const contextValue = useMemo<RivetContextValue>(\n () => ({\n store,\n nodeTypes: cfg.nodeTypes,\n paneRef,\n controls,\n getViewportElements,\n multiSelectionKeys: cfg.multiSelectionKeys,\n announce,\n nodeDescriptionId,\n defaultEdgeOptions: cfg.defaultEdgeOptions,\n snapGrid: cfg.snapGrid,\n alignmentGuides,\n anchorOptions: cfg.anchorOptions,\n swimlaneGroups: swimlanes.groups,\n swimlaneLanes: swimlanes.lanes,\n clampToSwimlane: swimlanes.clampEnabled,\n swimlaneMargin: swimlanes.margin,\n swimlaneLabelWidth: SWIMLANE_LABEL_WIDTH,\n swimlaneHeaderSize: swimlaneHeaderHeight,\n swimlaneResizable: swimlanes.resizableEnabled,\n resizeSwimlane: swimlanes.resizeSwimlane,\n renderSwimlaneHeader: cfg.renderSwimlaneHeader,\n renderSwimlaneLabel: cfg.renderSwimlaneLabel,\n onLaneChange: cfg.onLaneChange,\n isValidConnection: cfg.isValidConnection,\n mapConnection: mapConnectionWithAnchors,\n onConnect: cfg.onConnect,\n }),\n [\n store,\n cfg.nodeTypes,\n controls,\n getViewportElements,\n cfg.multiSelectionKeys,\n announce,\n nodeDescriptionId,\n cfg.defaultEdgeOptions,\n cfg.snapGrid,\n alignmentGuides,\n cfg.anchorOptions,\n swimlanes.groups,\n swimlanes.lanes,\n swimlanes.clampEnabled,\n swimlanes.margin,\n swimlaneHeaderHeight,\n swimlanes.resizableEnabled,\n swimlanes.resizeSwimlane,\n cfg.renderSwimlaneHeader,\n cfg.renderSwimlaneLabel,\n cfg.onLaneChange,\n cfg.isValidConnection,\n mapConnectionWithAnchors,\n cfg.onConnect,\n ],\n )\n\n return (\n <RivetContext.Provider value={contextValue}>\n <div\n ref={paneRef}\n className={className}\n style={{ ...paneStyle, ...style }}\n onContextMenu={handleContextMenu}\n role=\"application\"\n aria-label={ariaLabel ?? \"Node graph\"}\n >\n <canvas ref={backgroundCanvasRef} style={canvasStyle} />\n <canvas ref={edgeCanvasRef} style={canvasStyle} />\n <NodeLayer containerRef={nodeContainerRef} visibleIds={visibleIds} />\n <canvas ref={foregroundCanvasRef} style={canvasStyle} />\n {/*\n Peer claims as DOM, in place of the outlines the foreground canvas\n would have stroked — directly above it, since they annotate the same\n geometry. `outlineMode` has already folded in `renderOutlines`.\n */}\n {outlineMode === \"dom\" && cfg.presenceOptions.outlineComponent && (\n <PeerOutlineLayer component={cfg.presenceOptions.outlineComponent} />\n )}\n {/*\n Peer cursors, one layer up. They repaint at pointer rate and nothing\n below them depends on where they are, so they get a layer that can be\n redrawn alone — a canvas by default, or the consumer's component in a\n DOM overlay when `cursorComponent` is set, in which case the canvas is\n never created (nor is either one under `renderCursors: false` — the\n runtime resolves the canvas ref every frame, so it just stays null).\n */}\n {cfg.presenceOptions.renderCursors &&\n (cfg.presenceOptions.cursorComponent ? (\n <PeerCursorLayer component={cfg.presenceOptions.cursorComponent} />\n ) : (\n <canvas ref={cursorCanvasRef} style={canvasStyle} />\n ))}\n <EdgeLabelLayer />\n <SwimlaneOverlay />\n {children}\n <div id={nodeDescriptionId} style={srOnlyStyle}>\n {NODE_KEYBOARD_INSTRUCTIONS}\n </div>\n <div style={srOnlyStyle} role=\"status\" aria-live=\"polite\" aria-atomic=\"true\">\n {announcement}\n </div>\n </div>\n </RivetContext.Provider>\n )\n}\n","import { useMemo } from \"react\"\nimport type {\n AnchorRecord,\n AnchorRef,\n AnchorRegistration,\n AnchorRegistrationOptions,\n} from \"../anchor/registry\"\nimport { type ClonedElements, cloneElements } from \"../clipboard\"\nimport { useRivetContext } from \"../context\"\nimport { serializeGraph } from \"../graph\"\nimport type { PeerConnection } from \"../presence/registry\"\nimport type { RemoteChanges, RivetStore } from \"../store\"\nimport type { ViewportElements } from \"../swimlane/lanes\"\nimport type {\n EdgeId,\n NodeId,\n Rect,\n RivetControls,\n RivetEdge,\n RivetNode,\n RivetSnapshot,\n Vec2,\n} from \"../types\"\n\ntype Updater<T> = T | ((current: T) => T)\n\n/** In-memory clipboard shared by every instance of the same graph. */\nconst clipboards = new WeakMap<RivetStore, ClonedElements>()\n/** Default diagonal nudge so a paste/duplicate doesn't land exactly on top. */\nconst PASTE_OFFSET: Vec2 = { x: 24, y: 24 }\n\n/**\n * Imperative handle to the graph, returned by {@link useRivet}. Parameterize it\n * with your node/edge `data` types — `useRivet<MyNodeData, MyEdgeData>()` — so\n * `getNodes`, `toObject`, etc. hand those types back instead of `unknown`.\n */\nexport type RivetInstance<TNodeData = unknown, TEdgeData = unknown> = RivetControls & {\n /** Snapshot the nodes and lanes currently on screen. Reads the viewport once — never subscribes. */\n getViewportElements: () => ViewportElements<TNodeData>\n /** Serializable snapshot of nodes, edges, and viewport. Safe to `JSON.stringify`. */\n toObject: () => RivetSnapshot<TNodeData, TEdgeData>\n getNodes: () => RivetNode<TNodeData>[]\n getNode: (id: NodeId) => RivetNode<TNodeData> | undefined\n /**\n * A node's box in **world** coordinates — its `parentId` chain resolved, and\n * its explicit or measured size applied. `null` for an id that isn't in the\n * graph.\n *\n * This is where the node currently *is on screen*, not what the document\n * says: a node a peer is dragging or resizing reports the box they last sent\n * (see {@link setPeerNodeTransform}), which is what anything painting over\n * the graph wants. Reach for {@link getNode} instead when you're computing a\n * mutation — that position is the one the document will agree with.\n *\n * Reads once; never subscribes. Call it inside your own frame loop.\n */\n getNodeRect: (id: NodeId) => Rect | null\n setNodes: (nodes: Updater<RivetNode<TNodeData>[]>) => void\n addNodes: (nodes: RivetNode<TNodeData> | RivetNode<TNodeData>[]) => void\n updateNode: (id: NodeId, patch: Updater<RivetNode<TNodeData>>) => void\n getEdges: () => RivetEdge<TEdgeData>[]\n getEdge: (id: EdgeId) => RivetEdge<TEdgeData> | undefined\n setEdges: (edges: Updater<RivetEdge<TEdgeData>[]>) => void\n addEdges: (edges: RivetEdge<TEdgeData> | RivetEdge<TEdgeData>[]) => void\n updateEdge: (id: EdgeId, patch: Updater<RivetEdge<TEdgeData>>) => void\n /** Delete nodes (and their edges) and/or edges by id. */\n deleteElements: (elements: { nodes?: NodeId[]; edges?: EdgeId[] }) => void\n /**\n * Apply a change batch that already happened elsewhere — a peer's edit off\n * your transport. The graph updates and repaints, then re-emits the batch to\n * `onNodesChange`/`onEdgesChange` tagged `\"remote\"`, so a controlled owner\n * keeps its state in step through the one path it already has.\n *\n * Remote batches never create an undo step; in a shared document, undoing a\n * peer's edit would silently revert work you don't own.\n *\n * ```ts\n * connection.onNodeMoved((row) => {\n * if (row.caller === me) return // your own echo — already applied\n * rivet.applyRemote({\n * nodes: [{ type: \"position\", id: row.id, position: row.position }],\n * })\n * })\n * ```\n */\n applyRemote: (changes: RemoteChanges) => void\n /**\n * Bind an anchor — a connectable point — to a DOM element inside a node.\n * The imperative core behind `<Anchor>`, for consumers whose content DOM is\n * owned by another renderer (a rich-text editor's contentEditable, say).\n * Idempotent on `(nodeId, anchorId)`; the returned registration re-binds a\n * replaced element or unregisters explicitly.\n */\n registerAnchor: (\n nodeId: NodeId,\n anchorId: string,\n element: Element,\n options?: AnchorRegistrationOptions,\n ) => AnchorRegistration\n /**\n * Explicitly remove an anchor and its chrome. Unmounting `<Anchor>` (or\n * rebinding `null`) only *detaches* — geometry and edges are retained — so\n * call this when the anchored content is gone for good, alongside deleting\n * its edges.\n */\n unregisterAnchor: (nodeId: NodeId, anchorId: string) => void\n /**\n * Re-measure a node's anchors. Automatic on node resize; needed after a\n * content reflow that keeps the node box (an editor transaction, a font\n * load) — rivet can't observe those.\n */\n remeasureAnchors: (nodeId: NodeId) => void\n /**\n * One anchor's record — geometry, colour, and whatever `data` was registered\n * with it — or `null` when the node has no such anchor.\n */\n getAnchor: (nodeId: NodeId, anchorId: string) => AnchorRecord | null\n /**\n * Replace the anchor selection. Selecting an anchor clears the node and edge\n * selection. View state: no change is emitted and nothing is recorded to\n * history, so this is safe to call from a render-driven effect.\n */\n setSelectedAnchors: (refs: readonly AnchorRef[]) => void\n /** The selected anchors. Reactive through `useSelectedAnchors()`. */\n getSelectedAnchors: () => readonly AnchorRef[]\n /**\n * Move a peer's cursor, in **world** coordinates (peers pan and zoom\n * independently, so a screen point means nothing to them). `null` parks it.\n *\n * The presence hot path: it paints on the next frame without going through\n * React, so call it as fast as your channel delivers. A peer the `peers`\n * roster hasn't mentioned yet still gets a cursor — a frame that beats the\n * join event shouldn't blink.\n */\n setPeerCursor: (peerId: string, point: Vec2 | null) => void\n /**\n * Show a node where a peer currently has it, in world space — their drag,\n * mid-flight. The node renders, hit-tests and wires at that box until their\n * change lands through {@link applyRemote}; the graph itself is untouched.\n * Pass `null` on their drop.\n */\n setPeerNodeTransform: (peerId: string, nodeId: NodeId, rect: Rect | null) => void\n /**\n * Draw the wire a peer is pulling out of a handle — their `LocalPresence.pending`,\n * fed straight back. Both ends are in **world** coordinates. Pass `null` when\n * they let go, which their next snapshot says either way.\n *\n * Painted on the foreground in their colour, with a dot on the loose end. It\n * changes nothing about the graph: a connection exists when their change\n * lands, not while they're dragging toward it.\n */\n setPeerConnection: (peerId: string, connection: PeerConnection | null) => void\n /** Forget a peer entirely — cursor, held nodes and all. For a disconnect. */\n removePeer: (peerId: string) => void\n /**\n * Give up a gesture's hold on its nodes without committing — the yield lever\n * for `onNodeLockConflict`, when your transport says this client lost the\n * race for a node it's already dragging.\n *\n * The running gesture notices on its next frame, stops writing, and tears\n * itself down; the nodes stay where they are and the holder's positions land\n * normally from then on. `onNodeDragEnd` fires as it would on a drop, so a\n * consumer's own lock release runs unchanged. Pass the conflict event's\n * `ids` to release a whole group.\n *\n * Doing nothing is also a valid answer: without this call the gesture keeps\n * its nodes until the pointer lifts.\n */\n releaseNodeGesture: (id: NodeId, ids?: NodeId[]) => void\n /** Copy nodes (default: the current selection) to the in-memory clipboard. */\n copy: (ids?: NodeId[]) => void\n /** Copy then delete nodes (default: the current selection). */\n cut: (ids?: NodeId[]) => void\n /** Paste the clipboard as fresh, selected nodes offset from the originals. No-op when empty. */\n paste: (options?: { offset?: Vec2 }) => ClonedElements<TNodeData, TEdgeData> | undefined\n /** Clone nodes (default: the current selection) in place with fresh ids, and select them. */\n duplicate: (ids?: NodeId[]) => ClonedElements<TNodeData, TEdgeData> | undefined\n /** Revert the last recordable change. Returns false when there's nothing to undo. */\n undo: () => boolean\n /** Re-apply the last undone change. Returns false when there's nothing to redo. */\n redo: () => boolean\n canUndo: () => boolean\n canRedo: () => boolean\n /** Drop all undo/redo history and reset the baseline to the current graph. */\n clearHistory: () => void\n}\n\nfunction buildInstance<TNodeData, TEdgeData>(\n store: RivetStore,\n controls: RivetControls,\n getViewportElements: () => ViewportElements,\n): RivetInstance<TNodeData, TEdgeData> {\n // The store is data-agnostic (`unknown`); the generic asserts the caller's type\n // at this boundary, the way React Flow's typed `useReactFlow` does.\n const getNodes = () => [...store.nodes.values()] as RivetNode<TNodeData>[]\n const getEdges = () => [...store.edges.values()] as RivetEdge<TEdgeData>[]\n\n const setNodes: RivetInstance<TNodeData, TEdgeData>[\"setNodes\"] = (arg) => {\n const next = typeof arg === \"function\" ? arg(getNodes()) : arg\n const nextIds = new Set(next.map((node) => node.id))\n for (const current of getNodes()) {\n if (!nextIds.has(current.id)) store.removeNode(current.id)\n }\n for (const node of next) {\n if (store.nodes.has(node.id)) store.replaceNode(node.id, node)\n else store.addNode(node)\n }\n }\n\n const setEdges: RivetInstance<TNodeData, TEdgeData>[\"setEdges\"] = (arg) => {\n const next = typeof arg === \"function\" ? arg(getEdges()) : arg\n const nextIds = new Set(next.map((edge) => edge.id))\n for (const current of getEdges()) {\n if (!nextIds.has(current.id)) store.removeEdge(current.id)\n }\n for (const edge of next) {\n if (store.edges.has(edge.id)) store.replaceEdge(edge.id, edge)\n else store.addEdge(edge)\n }\n }\n\n // Copy `ids` (and the edges wholly between them) into a detached snapshot the\n // clipboard/paste path won't see mutate.\n const snapshot = (ids: NodeId[]): ClonedElements<TNodeData, TEdgeData> => {\n const nodes = ids\n .map((id) => store.nodes.get(id))\n .filter((node): node is RivetNode => node !== undefined)\n .map((node) => ({ ...node, position: { ...node.position } })) as RivetNode<TNodeData>[]\n const idSet = new Set(nodes.map((node) => node.id))\n const edges = (getEdges() as RivetEdge<TEdgeData>[])\n .filter((edge) => idSet.has(edge.source) && idSet.has(edge.target))\n .map((edge) => ({ ...edge }))\n return { nodes, edges }\n }\n\n // Clone a snapshot with fresh ids at `offset`, add it, and select the clones.\n const insert = (\n source: ClonedElements<TNodeData, TEdgeData>,\n offset: Vec2,\n ): ClonedElements<TNodeData, TEdgeData> => {\n const cloned = cloneElements(source.nodes, source.edges, { offset })\n for (const node of cloned.nodes) store.addNode(node)\n for (const edge of cloned.edges) store.addEdge(edge)\n store.selectNodes(cloned.nodes.map((node) => node.id))\n return cloned\n }\n\n return {\n ...controls,\n getViewportElements: getViewportElements as () => ViewportElements<TNodeData>,\n toObject: () =>\n serializeGraph<TNodeData, TEdgeData>(\n store.nodes.values() as Iterable<RivetNode<TNodeData>>,\n store.edges.values() as Iterable<RivetEdge<TEdgeData>>,\n store.getViewport(),\n ),\n getNodes,\n getNode: (id) => store.nodes.get(id) as RivetNode<TNodeData> | undefined,\n // The store's own `getNodeRect` answers for any id, falling back to the\n // origin and the default size; a public caller needs to tell \"it's there,\n // at 0,0\" from \"it isn't there\".\n getNodeRect: (id) => (store.nodes.has(id) ? store.getNodeRect(id) : null),\n setNodes,\n addNodes: (nodes) => {\n for (const node of Array.isArray(nodes) ? nodes : [nodes]) store.addNode(node)\n },\n updateNode: (id, patch) => {\n const current = store.nodes.get(id) as RivetNode<TNodeData> | undefined\n if (!current) return\n store.replaceNode(id, typeof patch === \"function\" ? patch(current) : patch)\n },\n getEdges,\n getEdge: (id) => store.edges.get(id) as RivetEdge<TEdgeData> | undefined,\n setEdges,\n addEdges: (edges) => {\n for (const edge of Array.isArray(edges) ? edges : [edges]) store.addEdge(edge)\n },\n updateEdge: (id, patch) => {\n const current = store.edges.get(id) as RivetEdge<TEdgeData> | undefined\n if (!current) return\n store.replaceEdge(id, typeof patch === \"function\" ? patch(current) : patch)\n },\n deleteElements: ({ nodes, edges }) => {\n for (const id of edges ?? []) store.removeEdge(id)\n for (const id of nodes ?? []) store.removeNode(id)\n },\n applyRemote: (changes) => store.applyRemote(changes),\n registerAnchor: (nodeId, anchorId, element, options) => {\n store.registerAnchor(nodeId, anchorId, element, options)\n return {\n rebind: (el) =>\n el === null\n ? store.detachAnchor(nodeId, anchorId)\n : store.registerAnchor(nodeId, anchorId, el, options),\n unregister: () => store.unregisterAnchor(nodeId, anchorId),\n }\n },\n unregisterAnchor: (nodeId, anchorId) => store.unregisterAnchor(nodeId, anchorId),\n remeasureAnchors: (nodeId) => store.remeasureAnchors(nodeId),\n getAnchor: (nodeId, anchorId) =>\n store.getNodeAnchors(nodeId).find((record) => record.anchorId === anchorId) ?? null,\n setSelectedAnchors: (refs) => store.setSelectedAnchors(refs),\n getSelectedAnchors: () => store.getSelectedAnchors(),\n setPeerCursor: (peerId, point) => store.presence.setPeerCursor(peerId, point),\n setPeerNodeTransform: (peerId, nodeId, rect) =>\n store.presence.setPeerNodeTransform(peerId, nodeId, rect),\n setPeerConnection: (peerId, connection) => store.presence.setPeerConnection(peerId, connection),\n removePeer: (peerId) => store.presence.removePeer(peerId),\n releaseNodeGesture: (id, ids) => store.endNodeGesture(id, ids),\n copy: (ids) => {\n const targetIds = ids ?? store.getSelectedNodes()\n if (targetIds.length === 0) return\n clipboards.set(store, snapshot(targetIds))\n },\n cut: (ids) => {\n const targetIds = ids ?? store.getSelectedNodes()\n if (targetIds.length === 0) return\n clipboards.set(store, snapshot(targetIds))\n for (const id of targetIds) store.removeNode(id)\n },\n paste: (options) => {\n const clip = clipboards.get(store) as ClonedElements<TNodeData, TEdgeData> | undefined\n if (!clip || clip.nodes.length === 0) return\n return insert(clip, options?.offset ?? PASTE_OFFSET)\n },\n duplicate: (ids) => {\n const targetIds = ids ?? store.getSelectedNodes()\n if (targetIds.length === 0) return\n return insert(snapshot(targetIds), PASTE_OFFSET)\n },\n undo: () => store.undo(),\n redo: () => store.redo(),\n canUndo: () => store.canUndo(),\n canRedo: () => store.canRedo(),\n clearHistory: () => store.clearHistory(),\n }\n}\n\n/**\n * Imperative access to the graph from any component inside `<Rivet>` — CRUD on\n * nodes/edges plus the viewport controls. Backed by the same store that drives\n * rendering, so mutations are reflected immediately and (in controlled mode) emit\n * changes to `onNodesChange`/`onEdgesChange`.\n *\n * Parameterize with your `data` types to keep them through the API:\n * `const rivet = useRivet<MyNodeData, MyEdgeData>()`.\n */\nexport function useRivet<TNodeData = unknown, TEdgeData = unknown>(): RivetInstance<\n TNodeData,\n TEdgeData\n> {\n const { store, controls, getViewportElements } = useRivetContext()\n return useMemo(\n () => buildInstance<TNodeData, TEdgeData>(store, controls, getViewportElements),\n [store, controls, getViewportElements],\n )\n}\n","export { alignRect } from \"./align\"\nexport { applyEdgeChanges, applyNodeChanges } from \"./changes\"\nexport { type ClonedElements, type CloneOptions, cloneElements } from \"./clipboard\"\nexport { Controls, type ControlsProps } from \"./components/controls\"\nexport { DefaultNode } from \"./components/default-node\"\nexport { BUILTIN_NODE_TYPES, GroupNode } from \"./components/group-node\"\nexport { Handle, type HandleProps } from \"./components/handle\"\nexport { MiniMap, type MiniMapProps } from \"./components/minimap\"\nexport { NodeResizer, type NodeResizerProps } from \"./components/node-resizer\"\nexport { type PaneContextMenuContext, Rivet, type RivetProps } from \"./components/rivet\"\nexport {\n useRivetContext,\n useRivetControls,\n useRivetFocusedNode,\n useRivetHistory,\n useRivetViewport,\n} from \"./context\"\nexport {\n DEFAULT_ALIGNMENT_HYSTERESIS,\n type EdgeAlignment,\n facingSide,\n resolveFacingSide,\n resolveFacingSideAmong,\n} from \"./edge-alignment\"\nexport {\n type EdgeEndpoint,\n edgeEndpointHandle,\n parseEdgeEndpoint,\n parseSideHandleId,\n} from \"./edge-ends\"\nexport { boundingRect, clampChildToParent, serializeGraph, snapToGrid } from \"./graph\"\nexport { useNodeLock, useNodeLockAllows } from \"./hooks/use-node-lock\"\nexport { type RivetInstance, useRivet } from \"./hooks/use-rivet\"\nexport {\n type CanInteractWithLocked,\n LOCK_DEFAULT_REFUSED,\n type LockIntent,\n type LockInteraction,\n type LockRegistry,\n type LockTarget,\n type NodeLock,\n} from \"./locks/registry\"\nexport { Canvas2DEdgeRenderer, canvas2DEdgeRenderer } from \"./renderer/canvas-2d-edge-renderer\"\nexport {\n BUILTIN_EDGE_TYPES,\n getBezierPath,\n getSmoothStepPath,\n getStepPath,\n getStraightPath,\n} from \"./renderer/edge-paths\"\nexport { createRivetStore, handleKey, type RemoteChanges, type RivetStore } from \"./store\"\nexport type {\n AlignmentGuide,\n CenterNodeOptions,\n ChangeMeta,\n ChangeOrigin,\n Connection,\n DefaultEdgeOptions,\n EdgeChange,\n EdgeDrawExtras,\n EdgeEnd,\n EdgeId,\n EdgeMarker,\n EdgePath,\n EdgePathFn,\n EdgePathParams,\n EdgeRenderer,\n EdgeRendererFactory,\n EdgeRendererOptions,\n EdgeStyle,\n EdgeTypes,\n FitViewOptions,\n HandlePosition,\n HandleRecord,\n HandleType,\n NodeChange,\n NodeComponent,\n NodeGestureEvent,\n NodeId,\n NodeLockConflictEvent,\n NodeProps,\n NodeTypes,\n PendingConnection,\n ReconnectDelegate,\n Rect,\n RivetControls,\n RivetEdge,\n RivetNode,\n RivetSelection,\n RivetSnapshot,\n Size,\n Vec2,\n Viewport,\n} from \"./types\"\nexport {\n rectsIntersect,\n screenToWorld,\n viewportToCss,\n visibleWorldRect,\n worldToScreen,\n zoomAt,\n} from \"./viewport\"\n\nexport const VERSION = \"0.0.0\"\n"]}