@statelyai/flow 0.13.4 → 0.15.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/README.md +5 -1
- package/dist/esm/index.d.ts +13 -2
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +39 -14
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/layout/dagre.d.ts +2 -1
- package/dist/esm/layout/dagre.d.ts.map +1 -0
- package/dist/esm/layout/dagre.js +2 -0
- package/dist/esm/layout/dagre.js.map +1 -0
- package/dist/esm/layout/elk.d.ts +2 -1
- package/dist/esm/layout/elk.d.ts.map +1 -0
- package/dist/esm/layout/elk.js +2 -0
- package/dist/esm/layout/elk.js.map +1 -0
- package/dist/esm/layout/stately.d.ts +2 -1
- package/dist/esm/layout/stately.d.ts.map +1 -0
- package/dist/esm/layout/stately.js +2 -0
- package/dist/esm/layout/stately.js.map +1 -0
- package/dist/esm/shared.d.ts +2 -1
- package/dist/esm/shared.d.ts.map +1 -0
- package/dist/esm/shared.js +2 -0
- package/dist/esm/shared.js.map +1 -0
- package/package.json +4 -3
- package/src/__fixtures__/nested.ts +106 -0
- package/src/appearances.test.ts +428 -0
- package/src/appearances.ts +144 -0
- package/src/authoritative-route.ts +14 -0
- package/src/changeSet.test.ts +132 -0
- package/src/changeSet.ts +337 -0
- package/src/config.ts +41 -0
- package/src/configure.test.ts +212 -0
- package/src/connection-lifetime.ts +1 -0
- package/src/connectionPreview.test.ts +102 -0
- package/src/connectionPreview.ts +82 -0
- package/src/content.ts +203 -0
- package/src/createFlow.fit-frame.test.ts +256 -0
- package/src/createFlow.modern.test.ts +743 -0
- package/src/createFlow.test.ts +632 -0
- package/src/createFlow.ts +3463 -0
- package/src/createFlow.view.test.ts +212 -0
- package/src/createFlow.viewport-controls.test.ts +221 -0
- package/src/edge-geometry.ts +318 -0
- package/src/engine.cache.test.ts +728 -0
- package/src/engine.hierarchy.test.ts +1023 -0
- package/src/engine.test.ts +1965 -0
- package/src/engine.ts +3385 -0
- package/src/entity-changes.test.ts +309 -0
- package/src/entity-changes.ts +395 -0
- package/src/examples/flow-based-math.test.ts +25 -0
- package/src/examples/flow-based-math.ts +210 -0
- package/src/external-edit.test.ts +337 -0
- package/src/external-edit.ts +358 -0
- package/src/factories.test.ts +104 -0
- package/src/factories.ts +70 -0
- package/src/geometry.ts +13 -0
- package/src/graph-index.test.ts +56 -0
- package/src/graph-index.ts +194 -0
- package/src/hierarchy.test.ts +175 -0
- package/src/hierarchy.ts +330 -0
- package/src/highlights.test.ts +130 -0
- package/src/index.ts +469 -0
- package/src/input/index.ts +615 -0
- package/src/input/input.test.ts +2577 -0
- package/src/input/keymap.ts +111 -0
- package/src/input/modes.ts +1715 -0
- package/src/input/reparent.test.ts +214 -0
- package/src/layout/dagre.ts +138 -0
- package/src/layout/elk.ts +1382 -0
- package/src/layout/index.ts +12 -0
- package/src/layout/layout.test.ts +1248 -0
- package/src/layout/shared.ts +260 -0
- package/src/layout/stately-globals.d.ts +9 -0
- package/src/layout/stately.test.ts +246 -0
- package/src/layout/stately.ts +528 -0
- package/src/layout-animation.test.ts +223 -0
- package/src/layout-contract.test.ts +414 -0
- package/src/marker.test.ts +23 -0
- package/src/marker.ts +23 -0
- package/src/measurement-anchor.test.ts +232 -0
- package/src/minimap.test.ts +96 -0
- package/src/minimap.ts +137 -0
- package/src/nested-fixture.test.ts +178 -0
- package/src/port-measurement.test.ts +27 -0
- package/src/port-measurements.test.ts +187 -0
- package/src/profile.ts +124 -0
- package/src/projections.test.ts +103 -0
- package/src/projections.ts +295 -0
- package/src/render-invalidation.test.ts +62 -0
- package/src/render-invalidation.ts +55 -0
- package/src/renderer-geometry.test.ts +356 -0
- package/src/renderer-transactions.test.ts +234 -0
- package/src/routing/avoid.ts +417 -0
- package/src/routing/index.test.ts +361 -0
- package/src/routing/index.ts +366 -0
- package/src/routing/readTracking.test.ts +103 -0
- package/src/routing/readTracking.ts +233 -0
- package/src/selection-commands.test.ts +355 -0
- package/src/serialize.test.ts +167 -0
- package/src/serialize.ts +254 -0
- package/src/shapes/index.test.ts +45 -0
- package/src/shapes/index.ts +142 -0
- package/src/snap.test.ts +123 -0
- package/src/snap.ts +395 -0
- package/src/spatial.test.ts +676 -0
- package/src/spatial.ts +457 -0
- package/src/store/index.ts +4121 -0
- package/src/store.test.ts +2903 -0
- package/src/toolbar.test.ts +31 -0
- package/src/toolbar.ts +62 -0
- package/src/types.test.ts +15 -0
- package/src/types.ts +487 -0
- package/src/validation.ts +558 -0
- package/src/view.ts +172 -0
- package/src/viewport/animate.ts +285 -0
- package/src/viewport/index.ts +296 -0
- package/src/viewport.test.ts +569 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["edgeMidpoint","computeStepMidpoint","pushDistinct","nextWithHistory","exhaustive","defaultEdgeOwnerFromIndex","resolvedSize","baseResolvedSize","resolvedBounds","baseResolvedBounds","snappedBounds","baseSnappedBounds","resolvedEdgeLabelSize","baseResolvedEdgeLabelSize","screenToCanvas","_screenToCanvas","canvasToScreen","_canvasToScreen","getGraphIncomers","getGraphOutgoers","getGraphConnectedEdges","getGraphNeighbors","getDefaultEdgeOwner","viewportPanBy","viewportZoomTo","preventDefault"],"sources":["../../src/marker.ts","../../src/projections.ts","../../src/connection-lifetime.ts","../../src/appearances.ts","../../src/profile.ts","../../src/viewport/animate.ts","../../src/viewport/index.ts","../../src/authoritative-route.ts","../../src/spatial.ts","../../src/snap.ts","../../src/graph-index.ts","../../src/hierarchy.ts","../../src/routing/avoid.ts","../../src/routing/index.ts","../../src/validation.ts","../../src/edge-geometry.ts","../../src/store/index.ts","../../src/view.ts","../../src/geometry.ts","../../src/external-edit.ts","../../src/render-invalidation.ts","../../src/shapes/index.ts","../../src/routing/readTracking.ts","../../src/config.ts","../../src/engine.ts","../../src/factories.ts","../../src/serialize.ts","../../src/changeSet.ts","../../src/content.ts","../../src/createFlow.ts","../../src/connectionPreview.ts","../../src/toolbar.ts","../../src/minimap.ts","../../src/input/keymap.ts","../../src/input/modes.ts","../../src/input/index.ts","../../src/entity-changes.ts"],"sourcesContent":["import type { MarkerType } from './types';\n\nconst BUILT_IN_MARKERS = new Set<MarkerType>([\n 'arrow',\n 'arrow-closed',\n 'circle',\n]);\nconst SAFE_MARKER_ID = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\nconst LOCAL_MARKER_URL = /^url\\(#([A-Za-z_][A-Za-z0-9_.:-]*)\\)$/;\n\n/** Convert a marker contract value to a safe local SVG marker reference. */\nexport function markerToSVG(\n marker: MarkerType | undefined,\n builtInPrefix: string,\n): string | undefined {\n if (!marker || marker === 'none') return undefined;\n if (BUILT_IN_MARKERS.has(marker)) {\n return `url(#${builtInPrefix}-${marker})`;\n }\n const localReference = LOCAL_MARKER_URL.exec(marker);\n if (localReference) return `url(#${localReference[1]})`;\n return SAFE_MARKER_ID.test(marker) ? `url(#${marker})` : undefined;\n}\n","import type { FlowEdge, FlowGraph, FlowNode } from \"./types\";\n\nexport type GraphDecoration<TDecoration = unknown> =\n | TDecoration\n | readonly TDecoration[];\n\nexport type GraphNodeAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n> = {\n className?: string;\n style?: TStyle;\n color?: string;\n opacity?: number;\n badge?: GraphDecoration<TDecoration>;\n tooltip?: GraphDecoration<TDecoration>;\n};\n\nexport type GraphEdgeAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n> = {\n className?: string;\n style?: TStyle;\n color?: string;\n opacity?: number;\n strokeWidth?: number;\n label?: TDecoration;\n badge?: GraphDecoration<TDecoration>;\n tooltip?: GraphDecoration<TDecoration>;\n};\n\nexport type GraphProjection<TNodeDatum = unknown, TEdgeDatum = unknown> = {\n id: string;\n label?: string;\n nodes?: Record<string, TNodeDatum>;\n edges?: Record<string, TEdgeDatum>;\n};\n\nexport type GraphProjectionMapper<\n TNodeDatum = unknown,\n TEdgeDatum = unknown,\n TStyle extends object = object,\n TDecoration = unknown,\n> = {\n getNodeAttrs?: (args: {\n node: FlowNode;\n datum: TNodeDatum;\n projection: GraphProjection<TNodeDatum, TEdgeDatum>;\n graph: FlowGraph;\n }) => GraphNodeAttrs<TStyle, TDecoration> | null;\n getEdgeAttrs?: (args: {\n edge: FlowEdge;\n datum: TEdgeDatum;\n projection: GraphProjection<TNodeDatum, TEdgeDatum>;\n graph: FlowGraph;\n }) => GraphEdgeAttrs<TStyle, TDecoration> | null;\n};\n\nexport type ActiveGraphProjection<\n TNodeDatum = unknown,\n TEdgeDatum = unknown,\n TStyle extends object = object,\n TDecoration = unknown,\n> = {\n projection: GraphProjection<TNodeDatum, TEdgeDatum>;\n mapper: GraphProjectionMapper<TNodeDatum, TEdgeDatum, TStyle, TDecoration>;\n priority?: number;\n};\n\nexport type ComposedGraphProjectionAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n> = {\n nodes: Map<string, GraphNodeAttrs<TStyle, TDecoration>>;\n edges: Map<string, GraphEdgeAttrs<TStyle, TDecoration>>;\n};\n\ntype IndexedActiveProjection<TStyle extends object, TDecoration> =\n ActiveGraphProjection<any, any, TStyle, TDecoration> & {\n index: number;\n };\n\nexport function sortActiveGraphProjections<\n TStyle extends object = object,\n TDecoration = unknown,\n>(\n active: readonly ActiveGraphProjection<\n any,\n any,\n TStyle,\n TDecoration\n >[],\n): ActiveGraphProjection<any, any, TStyle, TDecoration>[] {\n return active\n .map((entry, index) => ({ ...entry, index }))\n .sort(compareActiveGraphProjections)\n .map(({ index: _index, ...entry }) => entry);\n}\n\nexport function mergeGraphNodeAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n>(\n base: GraphNodeAttrs<TStyle, TDecoration> | undefined,\n next: GraphNodeAttrs<TStyle, TDecoration> | null | undefined,\n): GraphNodeAttrs<TStyle, TDecoration> {\n if (!next) return base ? { ...base } : {};\n\n return {\n ...base,\n ...next,\n className: mergeClassName(base?.className, next.className),\n style: mergeStyle(base?.style, next.style),\n badge: mergeDecoration(base?.badge, next.badge),\n tooltip: mergeDecoration(base?.tooltip, next.tooltip),\n };\n}\n\nexport function mergeGraphEdgeAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n>(\n base: GraphEdgeAttrs<TStyle, TDecoration> | undefined,\n next: GraphEdgeAttrs<TStyle, TDecoration> | null | undefined,\n): GraphEdgeAttrs<TStyle, TDecoration> {\n if (!next) return base ? { ...base } : {};\n\n return {\n ...base,\n ...next,\n className: mergeClassName(base?.className, next.className),\n style: mergeStyle(base?.style, next.style),\n badge: mergeDecoration(base?.badge, next.badge),\n tooltip: mergeDecoration(base?.tooltip, next.tooltip),\n };\n}\n\nexport function getProjectedNodeAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n>(args: {\n graph: FlowGraph;\n node: FlowNode;\n projections?: readonly ActiveGraphProjection<\n any,\n any,\n TStyle,\n TDecoration\n >[];\n}): GraphNodeAttrs<TStyle, TDecoration> {\n if (!args.projections?.length) return {};\n\n let attrs: GraphNodeAttrs<TStyle, TDecoration> | undefined;\n for (const entry of sortActiveGraphProjections(args.projections)) {\n const records = entry.projection.nodes;\n if (!records || !Object.prototype.hasOwnProperty.call(records, args.node.id)) {\n continue;\n }\n const datum = records[args.node.id];\n if (datum === undefined) continue;\n const next = entry.mapper.getNodeAttrs?.({\n node: args.node,\n datum,\n projection: entry.projection,\n graph: args.graph,\n });\n attrs = mergeGraphNodeAttrs(attrs, next);\n }\n return attrs ?? {};\n}\n\nexport function getProjectedEdgeAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n>(args: {\n graph: FlowGraph;\n edge: FlowEdge;\n projections?: readonly ActiveGraphProjection<\n any,\n any,\n TStyle,\n TDecoration\n >[];\n}): GraphEdgeAttrs<TStyle, TDecoration> {\n if (!args.projections?.length) return {};\n\n let attrs: GraphEdgeAttrs<TStyle, TDecoration> | undefined;\n for (const entry of sortActiveGraphProjections(args.projections)) {\n const records = entry.projection.edges;\n if (!records || !Object.prototype.hasOwnProperty.call(records, args.edge.id)) {\n continue;\n }\n const datum = records[args.edge.id];\n if (datum === undefined) continue;\n const next = entry.mapper.getEdgeAttrs?.({\n edge: args.edge,\n datum,\n projection: entry.projection,\n graph: args.graph,\n });\n attrs = mergeGraphEdgeAttrs(attrs, next);\n }\n return attrs ?? {};\n}\n\nexport function composeGraphProjectionAttrs<\n TStyle extends object = object,\n TDecoration = unknown,\n>(args: {\n graph: FlowGraph;\n projections?: readonly ActiveGraphProjection<\n any,\n any,\n TStyle,\n TDecoration\n >[];\n}): ComposedGraphProjectionAttrs<TStyle, TDecoration> {\n const nodes = new Map<string, GraphNodeAttrs<TStyle, TDecoration>>();\n const edges = new Map<string, GraphEdgeAttrs<TStyle, TDecoration>>();\n if (!args.projections?.length) return { nodes, edges };\n\n const nodeById = new Map(args.graph.nodes.map((node) => [node.id, node]));\n const edgeById = new Map(args.graph.edges.map((edge) => [edge.id, edge]));\n\n for (const entry of sortActiveGraphProjections(args.projections)) {\n for (const [id, datum] of Object.entries(entry.projection.nodes ?? {})) {\n const node = nodeById.get(id);\n if (!node) continue;\n const next = entry.mapper.getNodeAttrs?.({\n node,\n datum,\n projection: entry.projection,\n graph: args.graph,\n });\n nodes.set(id, mergeGraphNodeAttrs(nodes.get(id), next));\n }\n\n for (const [id, datum] of Object.entries(entry.projection.edges ?? {})) {\n const edge = edgeById.get(id);\n if (!edge) continue;\n const next = entry.mapper.getEdgeAttrs?.({\n edge,\n datum,\n projection: entry.projection,\n graph: args.graph,\n });\n edges.set(id, mergeGraphEdgeAttrs(edges.get(id), next));\n }\n }\n\n return { nodes, edges };\n}\n\nfunction compareActiveGraphProjections<TStyle extends object, TDecoration>(\n a: IndexedActiveProjection<TStyle, TDecoration>,\n b: IndexedActiveProjection<TStyle, TDecoration>,\n): number {\n return (a.priority ?? 0) - (b.priority ?? 0) || a.index - b.index;\n}\n\nfunction mergeClassName(\n base: string | undefined,\n next: string | undefined,\n): string | undefined {\n if (!base) return next;\n if (!next) return base;\n return `${base} ${next}`;\n}\n\nfunction mergeStyle<TStyle extends object>(\n base: TStyle | undefined,\n next: TStyle | undefined,\n): TStyle | undefined {\n if (!base) return next;\n if (!next) return base;\n return { ...base, ...next };\n}\n\nfunction mergeDecoration<TDecoration>(\n base: GraphDecoration<TDecoration> | undefined,\n next: GraphDecoration<TDecoration> | undefined,\n): GraphDecoration<TDecoration> | undefined {\n if (base === undefined) return next;\n if (next === undefined) return base;\n return [...toDecorationArray(base), ...toDecorationArray(next)];\n}\n\nfunction toDecorationArray<TDecoration>(\n value: GraphDecoration<TDecoration>,\n): TDecoration[] {\n return Array.isArray(value)\n ? [...(value as readonly TDecoration[])]\n : [value as TDecoration];\n}\n","export const connectionLifetime = Symbol('flow.connectionLifetime');\n","import type { Direction, FlowEdgeLabel, FlowNode, Rect } from \"./types\";\n\n/** Authored, serializable reference to a reusable presentation. */\nexport type FlowAppearance = {\n name: string;\n options?: Record<string, unknown>;\n};\nexport type FlowAppearanceConnection = {\n /** Local rectangle, or a single descendant selected within the rendered entity. */\n bounds?: Rect | { selector: string };\n sides?: readonly Direction[];\n ports?: readonly string[];\n};\nexport type FlowAppearancePolicy = {\n connection?: FlowAppearanceConnection;\n /** Renderer registry key; defaults to the appearance name. */\n renderer?: string;\n sizing?: \"content\" | \"fixed\";\n /** Node-local / label-local connection rectangle, independent of visual bounds. */\n connectionBounds?: Rect;\n /** Restricts body attachment and ports, including gestures and routing. */\n sides?: readonly Direction[];\n /** Optional permitted authored port names. Port identities are never replaced. */\n ports?: readonly string[];\n};\nexport type FlowAppearanceDefinition =\n | FlowAppearancePolicy\n | ((args: {\n entity: FlowNode | FlowEdgeLabel;\n options: Readonly<Record<string, unknown>>;\n }) => FlowAppearancePolicy);\nexport type FlowAppearances = {\n definitions?: Readonly<Record<string, FlowAppearanceDefinition>>;\n defaults?: { node?: FlowAppearance; edgeLabel?: FlowAppearance };\n};\nexport type ResolvedFlowAppearance = FlowAppearancePolicy & {\n reference: FlowAppearance | undefined;\n registered: boolean;\n autoSize: boolean;\n connectionSelector?: string;\n sides: readonly Direction[];\n};\nexport const appearanceSides: readonly Direction[] = [\n \"top\",\n \"right\",\n \"bottom\",\n \"left\",\n];\n\nexport function resolveAppearance(\n entity: FlowNode | FlowEdgeLabel,\n appearances: FlowAppearances = {}\n): ResolvedFlowAppearance {\n const reference =\n entity.appearance ??\n appearances.defaults?.[\"type\" in entity ? \"node\" : \"edgeLabel\"];\n const definition =\n reference &&\n Object.prototype.hasOwnProperty.call(\n appearances.definitions ?? {},\n reference.name\n )\n ? appearances.definitions?.[reference.name]\n : undefined;\n const policy =\n typeof definition === \"function\"\n ? definition({ entity, options: reference?.options ?? {} })\n : definition ?? {};\n return {\n ...policy,\n reference,\n registered: definition !== undefined,\n renderer: definition ? policy.renderer ?? reference?.name : undefined,\n autoSize: entity.autoSize ?? policy.sizing === \"content\",\n connectionBounds:\n policy.connection?.bounds && !(\"selector\" in policy.connection.bounds)\n ? policy.connection.bounds\n : policy.connection?.bounds ? undefined : policy.connectionBounds,\n connectionSelector:\n policy.connection?.bounds && \"selector\" in policy.connection.bounds\n ? policy.connection.bounds.selector\n : undefined,\n sides: policy.connection?.sides ?? policy.sides ?? appearanceSides,\n ports: policy.connection?.ports ?? policy.ports,\n };\n}\n\n/** Keyed by authored reference, so stale local measurements cannot follow appearance switches. */\nexport function appearanceMeasurementId(\n id: string,\n appearance: ResolvedFlowAppearance\n): string {\n return JSON.stringify([\n \"flow-appearance-boundary\",\n id,\n appearance.reference ?? null,\n appearance.connectionSelector ?? null,\n ]);\n}\n\nexport function appearanceAllowsPort(\n node: FlowNode,\n portName: string,\n appearance: ResolvedFlowAppearance\n): boolean {\n const port = node.ports?.find((candidate) => candidate.name === portName);\n const side = (port as { side?: Direction } | undefined)?.side;\n return (\n !!port &&\n (side ? appearance.sides.includes(side) : appearance.sides.length === 4) &&\n (!appearance.ports || appearance.ports.includes(portName))\n );\n}\n\n/** Preserve the usual facing side; otherwise choose the closest permitted side anchor. */\nexport function appearanceDirection(\n bounds: Rect,\n other: Rect,\n preferred: Direction,\n sides: readonly Direction[]\n): Direction {\n if (sides.includes(preferred)) return preferred;\n const cx = other.x + other.width / 2,\n cy = other.y + other.height / 2;\n const distance = (side: Direction) => {\n const x =\n side === \"left\"\n ? bounds.x\n : side === \"right\"\n ? bounds.x + bounds.width\n : bounds.x + bounds.width / 2;\n const y =\n side === \"top\"\n ? bounds.y\n : side === \"bottom\"\n ? bounds.y + bounds.height\n : bounds.y + bounds.height / 2;\n return Math.hypot(cx - x, cy - y);\n };\n return sides.reduce(\n (best, side) => (distance(side) < distance(best) ? side : best),\n sides[0] ?? preferred\n );\n}\n","import type { FlowStoreContext } from \"./store\";\nimport type { FlowInputMode } from \"./input\";\n\nexport type FlowEventObject = {\n type: string;\n [key: string]: unknown;\n};\n\nexport type FlowTransition<TEvent extends FlowEventObject = FlowEventObject> = (\n context: FlowStoreContext,\n event: TEvent,\n enqueue: unknown\n) => FlowStoreContext;\n\nexport type FlowTransitions = Record<string, FlowTransition>;\n\nexport type FlowInputProfile = {\n /**\n * Input modes for this profile/mode. Resolved by\n * `profileModesForContext(profile)`: the active store mode's modes win,\n * then the profile-level modes, then the built-in defaults.\n */\n modes?: FlowInputMode[];\n options?: {\n dragThreshold?: number;\n clickDistance?: number;\n longPressDelay?: number;\n autoPan?: {\n enabled?: boolean;\n threshold?: number;\n speed?: number;\n };\n };\n};\n\nexport type FlowOrigin =\n | \"top-left\"\n | \"center\"\n | \"center-x\"\n | \"center-y\"\n | { x: number; y: number };\n\nexport type FlowSettings = {\n nodeMeasurementOrigin?: FlowOrigin;\n edgeLabelMeasurementOrigin?: FlowOrigin;\n snapToGrid?: boolean;\n snapGrid?: [number, number];\n};\n\nexport type FlowPolicies = {\n canSelect?: boolean;\n canFocus?: boolean;\n canHover?: boolean;\n canEdit?: boolean;\n canCreate?: boolean;\n canDelete?: boolean;\n canMove?: boolean;\n canResize?: boolean;\n canConnect?: boolean;\n canReconnect?: boolean;\n canReparent?: boolean;\n canCopy?: boolean;\n canPaste?: boolean;\n canExport?: boolean;\n canUndo?: boolean;\n canRedo?: boolean;\n canPan?: boolean;\n canZoom?: boolean;\n};\n\n/** @experimental Rule slots are intentionally loose until the profile API stabilizes. */\nexport type FlowRules = {\n delete?: unknown[];\n move?: unknown[];\n reparent?: unknown[];\n};\n\n/** @experimental Resolver slots are intentionally loose until the profile API stabilizes. */\nexport type FlowResolvers = {\n blocks?: unknown;\n bounds?: unknown;\n owner?: unknown;\n ports?: unknown;\n};\n\nexport type FlowModeDefinition = {\n on?: FlowTransitions;\n input?: FlowInputProfile;\n /** @experimental */\n policies?: Partial<FlowPolicies>;\n /** @experimental */\n rules?: Partial<FlowRules>;\n /** @experimental */\n settings?: Partial<FlowSettings>;\n};\n\nexport type FlowProfile = {\n defaultMode: string;\n on?: FlowTransitions;\n input?: FlowInputProfile;\n modes: Record<string, FlowModeDefinition>;\n /** @experimental */\n resolvers?: FlowResolvers;\n /** @experimental */\n policies?: FlowPolicies;\n /** @experimental */\n rules?: FlowRules;\n /** @experimental */\n settings?: FlowSettings;\n};\n\nexport function defineFlowProfile<TProfile extends FlowProfile>(\n profile: TProfile\n): TProfile {\n return profile;\n}\n\nexport const defaultFlowProfile = defineFlowProfile({\n defaultMode: \"interactive\",\n modes: {\n interactive: {},\n readonly: { policies: { canEdit: false } },\n },\n});\n","import type { FlowStore } from '../store';\nimport type { Point, Viewport, ViewportAnimationOptions } from '../types';\n\ndeclare const requestAnimationFrame:\n | ((callback: (time: number) => void) => number)\n | undefined;\ndeclare const cancelAnimationFrame: ((id: number) => void) | undefined;\ndeclare const setTimeout: (callback: () => void, ms: number) => number;\ndeclare const clearTimeout: (id: number) => void;\n\nexport type ViewportAnimationFrame = (callback: (time: number) => void) => number;\nexport type ViewportAnimationCancelFrame = (id: number) => void;\n\nexport type ViewportAnimationControls = {\n cancel: () => void;\n /** Resolves true on arrival, false on cancellation. */\n done: Promise<boolean>;\n};\n\nexport type AnimateViewportOptions = ViewportAnimationOptions & {\n raf?: ViewportAnimationFrame;\n cancelRaf?: ViewportAnimationCancelFrame;\n};\n\nfunction defaultEasing(t: number): number {\n return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;\n}\n\nfunction defaultRaf(callback: (time: number) => void): number {\n if (typeof requestAnimationFrame === 'function') {\n return requestAnimationFrame(callback);\n }\n return setTimeout(() => callback(Date.now()), 16) as unknown as number;\n}\n\nfunction defaultCancelRaf(id: number): void {\n if (typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(id);\n return;\n }\n clearTimeout(id as unknown as ReturnType<typeof setTimeout>);\n}\n\nfunction safeLog(zoom: number): number {\n return Math.log(Math.max(zoom, Number.EPSILON));\n}\n\n/**\n * Focal-zoom state: the animation interpolates the zoom (in log space) and the\n * screen-space position of a fixed canvas anchor. Deriving the viewport from\n * those each frame keeps the anchor pinned to a monotonically-moving screen\n * position, so the content zooms straight in/out instead of swimming along an\n * arc.\n */\ntype FocalPlan = {\n /** Canvas-space anchor kept visually fixed through the animation. */\n focal: Point;\n logZoomFrom: number;\n logZoomTo: number;\n /** Anchor's screen position in the start viewport. */\n screenFrom: Point;\n /** Anchor's screen position in the target viewport. */\n screenTo: Point;\n};\n\nfunction planFocalZoom(\n from: Viewport,\n to: Viewport,\n pivot: Point | undefined,\n viewportSize: { width: number; height: number } | undefined,\n): FocalPlan {\n // Choose the focal anchor in canvas space. Prefer an explicit pivot (a\n // screen-space point that should stay put). Otherwise anchor on the canvas\n // point the TARGET viewport places at the screen CENTER — that point ends the\n // animation dead-center, so the view glides straight to its final focus and\n // scales around it (a natural fit/zoom feel). Anchoring on the canvas origin\n // instead makes content swim toward the top-left corner.\n const screenCenter: Point | null =\n viewportSize && viewportSize.width > 0 && viewportSize.height > 0\n ? { x: viewportSize.width / 2, y: viewportSize.height / 2 }\n : null;\n const focal: Point = pivot\n ? {\n x: (pivot.x - from.x) / from.zoom,\n y: (pivot.y - from.y) / from.zoom,\n }\n : screenCenter\n ? {\n x: (screenCenter.x - to.x) / to.zoom,\n y: (screenCenter.y - to.y) / to.zoom,\n }\n : { x: 0, y: 0 };\n\n return {\n focal,\n logZoomFrom: safeLog(from.zoom),\n logZoomTo: safeLog(to.zoom),\n screenFrom: {\n x: focal.x * from.zoom + from.x,\n y: focal.y * from.zoom + from.y,\n },\n screenTo: {\n x: focal.x * to.zoom + to.x,\n y: focal.y * to.zoom + to.y,\n },\n };\n}\n\n/**\n * Derive a viewport at eased progress `t` such that the focal anchor sits at the\n * linearly-interpolated screen position under the log-interpolated zoom.\n */\nfunction focalViewport(plan: FocalPlan, t: number): Viewport {\n const zoom = Math.exp(plan.logZoomFrom + (plan.logZoomTo - plan.logZoomFrom) * t);\n const screenX = plan.screenFrom.x + (plan.screenTo.x - plan.screenFrom.x) * t;\n const screenY = plan.screenFrom.y + (plan.screenTo.y - plan.screenFrom.y) * t;\n return {\n x: screenX - plan.focal.x * zoom,\n y: screenY - plan.focal.y * zoom,\n zoom,\n };\n}\n\nfunction linearViewport(from: Viewport, to: Viewport, t: number): Viewport {\n return {\n x: from.x + (to.x - from.x) * t,\n y: from.y + (to.y - from.y) * t,\n zoom: from.zoom + (to.zoom - from.zoom) * t,\n };\n}\n\n// Spring defaults tuned to be near-critically-damped for a smooth, overshoot-\n// free settle.\nconst DEFAULT_SPRING_STIFFNESS = 170;\nconst DEFAULT_SPRING_DAMPING = 26;\nconst DEFAULT_SPRING_MASS = 1;\nconst SPRING_REST_DELTA = 1e-3;\nconst SPRING_REST_SPEED = 1e-3;\nconst MAX_SPRING_STEP_MS = 1000 / 60;\nconst LERP_FRAME_MS = 1000 / 60;\nconst LERP_POSITION_REST_DELTA = 0.1;\nconst LERP_ZOOM_REST_DELTA = 1e-4;\n\nexport function animateViewport(\n store: FlowStore,\n target: Viewport,\n options: AnimateViewportOptions = {},\n): ViewportAnimationControls {\n const useSpring = options.spring !== undefined;\n const useLerp = options.lerp !== undefined;\n if (useSpring && useLerp) {\n throw new TypeError('Viewport animation cannot use both spring and lerp.');\n }\n if (\n useLerp &&\n (!Number.isFinite(options.lerp) || options.lerp! <= 0 || options.lerp! > 1)\n ) {\n throw new TypeError('Viewport lerp factor must be finite and in (0, 1].');\n }\n const duration = options.duration ?? 0;\n if (!useSpring && !useLerp && duration <= 0) {\n store.trigger.setViewport(target);\n return { cancel: () => {}, done: Promise.resolve(true) };\n }\n\n const raf = options.raf ?? defaultRaf;\n const cancelRaf = options.cancelRaf ?? defaultCancelRaf;\n const easing = options.easing ?? defaultEasing;\n const from = { ...store.getSnapshot().context.viewport };\n const plan = planFocalZoom(\n from,\n target,\n options.center,\n store.getSnapshot().context.viewportSize,\n );\n\n let frame: number | null = null;\n let startTime: number | null = null;\n let lastTime: number | null = null;\n let canceled = false;\n let resolveDone: (reached: boolean) => void = () => {};\n const done = new Promise<boolean>((resolve) => {\n resolveDone = resolve;\n });\n\n const cancel = () => {\n if (canceled) return;\n canceled = true;\n if (frame !== null) {\n cancelRaf(frame);\n frame = null;\n }\n resolveDone(false);\n };\n\n const finish = () => {\n store.trigger.setViewport(target);\n frame = null;\n resolveDone(true);\n };\n\n // Spring integrator: drives a normalized progress value `p` (0 -> 1) with a\n // semi-implicit Euler step, then maps it through the same focal-zoom\n // derivation so the anchor stays pinned. Because both zoom-log and focal\n // screen-pos are linear in `p`, one spring settles the whole motion.\n const springConfig = options.spring ?? {};\n const stiffness = springConfig.stiffness ?? DEFAULT_SPRING_STIFFNESS;\n const damping = springConfig.damping ?? DEFAULT_SPRING_DAMPING;\n const mass = springConfig.mass ?? DEFAULT_SPRING_MASS;\n let springValue = 0;\n let springVelocity = 0;\n let lerpValue = from;\n\n const springStep = (dtMs: number): boolean => {\n // Sub-step for stability if the frame delta is large.\n let remaining = dtMs;\n while (remaining > 0) {\n const stepMs = Math.min(remaining, MAX_SPRING_STEP_MS);\n const dt = stepMs / 1000;\n const springForce = -stiffness * (springValue - 1);\n const dampingForce = -damping * springVelocity;\n const accel = (springForce + dampingForce) / mass;\n springVelocity += accel * dt;\n springValue += springVelocity * dt;\n remaining -= stepMs;\n }\n const settled =\n Math.abs(springVelocity) < SPRING_REST_SPEED &&\n Math.abs(1 - springValue) < SPRING_REST_DELTA;\n return settled;\n };\n\n const step = (time: number) => {\n if (canceled) return;\n if (startTime === null) {\n startTime = time;\n lastTime = time;\n }\n\n if (useSpring) {\n const dtMs = Math.max(0, time - (lastTime ?? time));\n lastTime = time;\n const settled = springStep(dtMs);\n if (settled) {\n finish();\n return;\n }\n store.trigger.setViewport(focalViewport(plan, springValue));\n frame = raf(step);\n return;\n }\n\n if (useLerp) {\n const dtMs = Math.max(0, time - (lastTime ?? time));\n lastTime = time;\n if (dtMs > 0) {\n const frameFactor =\n 1 - Math.pow(1 - options.lerp!, dtMs / LERP_FRAME_MS);\n lerpValue = linearViewport(lerpValue, target, frameFactor);\n }\n const settled =\n Math.abs(target.x - lerpValue.x) <= LERP_POSITION_REST_DELTA &&\n Math.abs(target.y - lerpValue.y) <= LERP_POSITION_REST_DELTA &&\n Math.abs(target.zoom - lerpValue.zoom) <= LERP_ZOOM_REST_DELTA;\n if (settled) {\n finish();\n return;\n }\n store.trigger.setViewport(lerpValue);\n frame = raf(step);\n return;\n }\n\n const progress = Math.min(1, (time - startTime) / duration);\n if (progress >= 1) {\n finish();\n return;\n }\n store.trigger.setViewport(focalViewport(plan, easing(progress)));\n frame = raf(step);\n };\n\n frame = raf(step);\n return { cancel, done };\n}\n","import type { Point, Rect, Size, Viewport, FitViewOptions } from '../types';\nexport { animateViewport } from './animate';\nexport type {\n AnimateViewportOptions,\n ViewportAnimationCancelFrame,\n ViewportAnimationControls,\n ViewportAnimationFrame,\n} from './animate';\n\nexport type FitViewExclusionSide = 'top' | 'right' | 'bottom' | 'left' | 'nearest';\n\nexport type FitViewExclusion = {\n /** Read the current exclusion in viewport-local screen pixels. */\n getRect: () => Rect | null;\n /** Edge whose band this overlay occupies. Defaults to the nearest edge. */\n side?: FitViewExclusionSide;\n /** Additional screen-pixel clearance beyond the measured overlay. */\n gap?: number;\n};\n\nexport type ResolvedFitViewExclusion = Omit<FitViewExclusion, 'getRect'> & {\n rect: Rect;\n};\n\n\n// Viewport utilities\n//\n// First-class Viewport type with SVG-friendly helpers.\n\n\n/** Create a default viewport (origin, no zoom) */\nexport function createViewport(\n x = 0,\n y = 0,\n zoom = 1,\n): Viewport {\n return { x, y, zoom };\n}\n\n\n// SVG helpers\n\n\n/**\n * Convert viewport to SVG transform string.\n * Use on the root <g> wrapping all entities.\n *\n * @example\n * <g transform={toSVGTransform(viewport)}>...</g>\n */\nexport function toSVGTransform(viewport: Viewport): string {\n return `translate(${viewport.x}, ${viewport.y}) scale(${viewport.zoom})`;\n}\n\n/**\n * Convert viewport + container size to an SVG viewBox string.\n *\n * @example\n * <svg viewBox={toViewBox(viewport, { width: 800, height: 600 })}>...</svg>\n */\nexport function toViewBox(viewport: Viewport, size: Size): string {\n const x = -viewport.x / viewport.zoom;\n const y = -viewport.y / viewport.zoom;\n const w = size.width / viewport.zoom;\n const h = size.height / viewport.zoom;\n return `${x} ${y} ${w} ${h}`;\n}\n\n\n// Coordinate conversion\n\n\n/** Convert a screen-space point to canvas-space */\nexport function screenToCanvas(point: Point, viewport: Viewport): Point {\n return {\n x: (point.x - viewport.x) / viewport.zoom,\n y: (point.y - viewport.y) / viewport.zoom,\n };\n}\n\n/** Convert a canvas-space point to screen-space */\nexport function canvasToScreen(point: Point, viewport: Viewport): Point {\n return {\n x: point.x * viewport.zoom + viewport.x,\n y: point.y * viewport.zoom + viewport.y,\n };\n}\n\n\n// Bounds\n\n\n/** Get the canvas-space bounding rect of what's visible on screen */\nexport function getVisibleBounds(viewport: Viewport, size: Size): Rect {\n return {\n x: -viewport.x / viewport.zoom,\n y: -viewport.y / viewport.zoom,\n width: size.width / viewport.zoom,\n height: size.height / viewport.zoom,\n };\n}\n\n/**\n * Compute a viewport that fits the given bounds into the given screen size.\n */\nexport function viewportForBounds(\n bounds: Rect,\n size: Size,\n options: FitViewOptions = {},\n): Viewport {\n const { padding = 0.1, minZoom = 0.1, maxZoom = 2 } = options;\n const frame = options.frame\n ? validateFitFrame(options.frame)\n : { x: 0, y: 0, width: size.width, height: size.height };\n\n const paddedWidth = bounds.width * (1 + padding);\n const paddedHeight = bounds.height * (1 + padding);\n\n if (paddedWidth === 0 || paddedHeight === 0) {\n return { x: 0, y: 0, zoom: 1 };\n }\n\n const zoomX = frame.width / paddedWidth;\n const zoomY = frame.height / paddedHeight;\n const zoom = Math.min(Math.max(Math.min(zoomX, zoomY), minZoom), maxZoom);\n\n const centerX = bounds.x + bounds.width / 2;\n const centerY = bounds.y + bounds.height / 2;\n\n return {\n x: frame.x + frame.width / 2 - centerX * zoom,\n y: frame.y + frame.height / 2 - centerY * zoom,\n zoom,\n };\n}\n\n\n// Viewport math helpers\n\n\n/** Pan viewport by a delta */\nexport function panBy(\n viewport: Viewport,\n delta: Point,\n): Viewport {\n return {\n x: viewport.x + delta.x,\n y: viewport.y + delta.y,\n zoom: viewport.zoom,\n };\n}\n\n/** Zoom to a specific level, keeping a screen-space point fixed */\nexport function zoomTo(\n viewport: Viewport,\n zoom: number,\n center: Point,\n): Viewport {\n const clampedZoom = zoom;\n const ratio = clampedZoom / viewport.zoom;\n return {\n x: center.x - (center.x - viewport.x) * ratio,\n y: center.y - (center.y - viewport.y) * ratio,\n zoom: clampedZoom,\n };\n}\n\n/** Clamp zoom to min/max bounds */\nexport function clampZoom(\n zoom: number,\n minZoom: number,\n maxZoom: number,\n): number {\n return Math.min(Math.max(zoom, minZoom), maxZoom);\n}\n\n/** Viewport that places the given canvas point at the center of the screen. */\nexport function viewportCenteredOn(\n center: Point,\n size: Size,\n zoom: number,\n frame?: Rect,\n): Viewport {\n const target = frame\n ? validateFitFrame(frame)\n : { x: 0, y: 0, width: size.width, height: size.height };\n return {\n x: target.x + target.width / 2 - center.x * zoom,\n y: target.y + target.height / 2 - center.y * zoom,\n zoom,\n };\n}\n\n/** Validate and clone a positive finite screen-space fit frame. */\nexport function validateFitFrame(frame: Rect): Rect {\n if (\n !Number.isFinite(frame.x) ||\n !Number.isFinite(frame.y) ||\n !Number.isFinite(frame.width) ||\n !Number.isFinite(frame.height) ||\n frame.width <= 0 ||\n frame.height <= 0\n ) {\n throw new RangeError(\n 'Fit frame must have finite x/y and positive finite width/height.',\n );\n }\n return {\n x: frame.x,\n y: frame.y,\n width: frame.width,\n height: frame.height,\n };\n}\n\n/**\n * Reduce a fit frame by measured floating overlays. Each overlay reserves the\n * band between itself and its assigned (or nearest) frame edge.\n */\nexport function fitFrameAroundExclusions(\n frame: Rect,\n exclusions: Iterable<ResolvedFitViewExclusion>,\n): Rect {\n const base = validateFitFrame(frame);\n const right = base.x + base.width;\n const bottom = base.y + base.height;\n let leftInset = 0;\n let rightInset = 0;\n let topInset = 0;\n let bottomInset = 0;\n\n for (const exclusion of exclusions) {\n const rect = exclusion.rect;\n if (\n !Number.isFinite(rect.x) ||\n !Number.isFinite(rect.y) ||\n !Number.isFinite(rect.width) ||\n !Number.isFinite(rect.height) ||\n rect.width <= 0 ||\n rect.height <= 0\n ) {\n continue;\n }\n const clippedLeft = Math.max(base.x, rect.x);\n const clippedTop = Math.max(base.y, rect.y);\n const clippedRight = Math.min(right, rect.x + rect.width);\n const clippedBottom = Math.min(bottom, rect.y + rect.height);\n if (clippedRight <= clippedLeft || clippedBottom <= clippedTop) continue;\n\n const gap = Number.isFinite(exclusion.gap)\n ? Math.max(0, exclusion.gap ?? 0)\n : 0;\n const side =\n exclusion.side && exclusion.side !== 'nearest'\n ? exclusion.side\n : nearestFrameEdge(base, {\n x: clippedLeft,\n y: clippedTop,\n width: clippedRight - clippedLeft,\n height: clippedBottom - clippedTop,\n });\n\n if (side === 'left') {\n leftInset = Math.max(leftInset, clippedRight + gap - base.x);\n } else if (side === 'right') {\n rightInset = Math.max(rightInset, right - clippedLeft + gap);\n } else if (side === 'top') {\n topInset = Math.max(topInset, clippedBottom + gap - base.y);\n } else {\n bottomInset = Math.max(bottomInset, bottom - clippedTop + gap);\n }\n }\n\n const width = base.width - leftInset - rightInset;\n const height = base.height - topInset - bottomInset;\n return width > 0 && height > 0\n ? {\n x: base.x + leftInset,\n y: base.y + topInset,\n width,\n height,\n }\n : base;\n}\n\nfunction nearestFrameEdge(frame: Rect, rect: Rect): Exclude<FitViewExclusionSide, 'nearest'> {\n const distances = [\n ['left', Math.abs(rect.x - frame.x)],\n ['right', Math.abs(frame.x + frame.width - (rect.x + rect.width))],\n ['top', Math.abs(rect.y - frame.y)],\n ['bottom', Math.abs(frame.y + frame.height - (rect.y + rect.height))],\n ] as const;\n return distances.reduce((best, candidate) =>\n candidate[1] < best[1] ? candidate : best,\n )[0];\n}\n","import type { FlowEdge, Point } from './types';\n\n/** Valid graph-owned points that may bypass renderer-side routing. */\nexport function authoritativeEdgePoints(edge: FlowEdge): Point[] | undefined {\n const points = edge.points;\n if (\n !points ||\n points.length < 2 ||\n points.some(({ x, y }) => !Number.isFinite(x) || !Number.isFinite(y))\n ) {\n return undefined;\n }\n return points;\n}\n","import type { FlowEdge, FlowNode, Point, Rect, Size, Viewport } from './types';\nimport { authoritativeEdgePoints } from './authoritative-route';\n\n\n// Spatial helpers\n//\n// Pure functions for resolved positions, bounds, and hit testing.\n// No dependencies on store or engine — safe to import anywhere.\n\n\n/** Visual position: layout position + drag offset. */\nexport function visualPosition(node: FlowNode): Point {\n return {\n x: node.x + (node.dx ?? 0),\n y: node.y + (node.dy ?? 0),\n };\n}\n\n/** @deprecated Use `visualPosition`. */\nexport const resolvedPosition = visualPosition;\n\n/** Resolved visual bounds: layout position + drag offset + dimensions.\n * Uses style.customWidth/customHeight when set (from resize), otherwise inherent width/height. */\n/** Size the geometry should use, in priority order:\n * 1. `style.customWidth/customHeight` (an explicit resize override),\n * 2. for `autoSize` nodes, the DOM-`measured` size (the renderer owns it),\n * 3. the authored `width/height`.\n * Authored `width/height` are never mutated — measured size lives on\n * `node.measured`, so this is the single place that reconciles the two. */\nexport function resolvedSize(node: FlowNode): Size {\n const measuredAppearance = node.measured?.appearanceKey !== undefined && node.measured.appearanceKey === JSON.stringify(node.appearance ?? null);\n const autoSize = node.autoSize ?? (measuredAppearance && node.measured?.appearanceAutoSize);\n return {\n width:\n node.style?.customWidth ??\n (autoSize ? node.measured?.width ?? node.width : node.width),\n height:\n node.style?.customHeight ??\n (autoSize ? node.measured?.height ?? node.height : node.height),\n };\n}\n\nexport function visualBounds(node: FlowNode): Rect {\n const size = resolvedSize(node);\n return {\n x: node.x + (node.dx ?? 0),\n y: node.y + (node.dy ?? 0),\n width: size.width,\n height: size.height,\n };\n}\n\n/** @deprecated Use `visualBounds`. */\nexport const resolvedBounds = visualBounds;\n\n/** Bounds used by marquee selection, including transient node movement. */\nexport function resolvedSelectionBounds(node: FlowNode): Rect {\n if (!node.selectionBounds) return visualBounds(node);\n return {\n ...node.selectionBounds,\n x: node.selectionBounds.x + (node.dx ?? 0),\n y: node.selectionBounds.y + (node.dy ?? 0),\n };\n}\n\n/**\n * Size used for edge-label geometry. `autoSize` labels retain authored\n * dimensions as a fallback while a transient DOM measurement owns the live\n * size. The measurement never becomes authored graph data.\n */\nexport function resolvedEdgeLabelSize(\n label: NonNullable<FlowEdge['label']>,\n measurement?: Rect,\n): Size {\n return label.autoSize && measurement\n ? { width: measurement.width, height: measurement.height }\n : { width: label.width, height: label.height };\n}\n\n/** Fixed-position visual bounds for an edge label. */\nexport function resolvedEdgeLabelBounds(\n edge: FlowEdge,\n measurement?: Rect,\n): Rect | null {\n if (!edge.label) return null;\n const size = resolvedEdgeLabelSize(edge.label, measurement);\n return {\n x: edge.label.x + (edge.label.dx ?? 0),\n y: edge.label.y + (edge.label.dy ?? 0),\n ...size,\n };\n}\n\n/** Visual bounds with grid snap and/or entity snap-line offset. */\nexport function snappedBounds(\n node: FlowNode,\n grid: [number, number] | null,\n /** Optional snap offset from entity snap lines (snapRect.x - selectionRect.x) */\n snapOffset?: Point | null,\n): Rect {\n let x = node.x + (node.dx ?? 0);\n let y = node.y + (node.dy ?? 0);\n if (snapOffset) {\n x += snapOffset.x;\n y += snapOffset.y;\n }\n if (grid) {\n x = snapToGrid(x, grid[0]);\n y = snapToGrid(y, grid[1]);\n }\n const size = resolvedSize(node);\n return { x, y, width: size.width, height: size.height };\n}\n\n/** Compute bounding rect of all nodes + edge labels (resolved positions) */\nexport function getGraphBounds(\n nodes: FlowNode[],\n edges?: FlowEdge[],\n measurements?: ReadonlyMap<string, Rect>,\n): Rect {\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (const n of nodes) {\n const b = resolvedBounds(n);\n minX = Math.min(minX, b.x);\n minY = Math.min(minY, b.y);\n maxX = Math.max(maxX, b.x + b.width);\n maxY = Math.max(maxY, b.y + b.height);\n }\n if (edges) {\n for (const e of edges) {\n for (const point of authoritativeEdgePoints(e) ?? []) {\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n }\n const labelBounds = resolvedEdgeLabelBounds(e, measurements?.get(e.id));\n if (!labelBounds) continue;\n const lx = labelBounds.x;\n const ly = labelBounds.y;\n minX = Math.min(minX, lx);\n minY = Math.min(minY, ly);\n maxX = Math.max(maxX, lx + labelBounds.width);\n maxY = Math.max(maxY, ly + labelBounds.height);\n }\n }\n if (!isFinite(minX)) return { x: 0, y: 0, width: 0, height: 0 };\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** AABB intersection test */\nexport function rectsIntersect(a: Rect, b: Rect): boolean {\n return (\n a.x < b.x + b.width &&\n a.x + a.width > b.x &&\n a.y < b.y + b.height &&\n a.y + a.height > b.y\n );\n}\n\n/** Smallest axis-aligned rect containing both `a` and `b`. */\nexport function unionRect(a: Rect, b: Rect): Rect {\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n return {\n x,\n y,\n width: Math.max(a.x + a.width, b.x + b.width) - x,\n height: Math.max(a.y + a.height, b.y + b.height) - y,\n };\n}\n\n/** Snap a value to the nearest grid increment */\nexport function snapToGrid(value: number, gridSize: number): number {\n return Math.round(value / gridSize) * gridSize;\n}\n\n/** Snap a point to grid */\nexport function snapPointToGrid(point: Point, gridSize: number): Point {\n return {\n x: snapToGrid(point.x, gridSize),\n y: snapToGrid(point.y, gridSize),\n };\n}\n\n/** Normalize a box (two points) into a Rect with positive width/height */\nexport function boxToRect(p1: Point, p2: Point): Rect {\n return {\n x: Math.min(p1.x, p2.x),\n y: Math.min(p1.y, p2.y),\n width: Math.abs(p2.x - p1.x),\n height: Math.abs(p2.y - p1.y),\n };\n}\n\n/** Get bounding rect of specific entities by id */\nexport function getSelectionBounds(\n nodes: FlowNode[],\n edges: FlowEdge[],\n selection: Set<string>,\n measurements?: ReadonlyMap<string, Rect>,\n options: { includeEdgePoints?: boolean } = {},\n): Rect | null {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n\n for (const n of nodes) {\n if (!selection.has(n.id)) continue;\n const b = resolvedBounds(n);\n minX = Math.min(minX, b.x);\n minY = Math.min(minY, b.y);\n maxX = Math.max(maxX, b.x + b.width);\n maxY = Math.max(maxY, b.y + b.height);\n }\n\n for (const e of edges) {\n if (!selection.has(e.id)) continue;\n if (options.includeEdgePoints === true) {\n for (const point of authoritativeEdgePoints(e) ?? []) {\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n }\n }\n if (e.label) {\n const labelBounds = resolvedEdgeLabelBounds(e, measurements?.get(e.id));\n if (!labelBounds) continue;\n const lx = labelBounds.x;\n const ly = labelBounds.y;\n minX = Math.min(minX, lx);\n minY = Math.min(minY, ly);\n maxX = Math.max(maxX, lx + labelBounds.width);\n maxY = Math.max(maxY, ly + labelBounds.height);\n }\n }\n\n if (!isFinite(minX)) return null;\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\n/** Determine select mode from a pointer/keyboard event */\nexport function selectMode(e: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean }): 'single' | 'multi' {\n return (e.shiftKey || e.metaKey || e.ctrlKey) ? 'multi' : 'single';\n}\n\n/** Does rect `a` fully contain rect `b`? */\nexport function rectContains(a: Rect, b: Rect): boolean {\n return b.x >= a.x && b.y >= a.y &&\n b.x + b.width <= a.x + a.width &&\n b.y + b.height <= a.y + a.height;\n}\n\n// ---------------------------------------------------------------------------\n// Wheel event utilities (ported from d3-zoom's wheelDelta logic)\n// ---------------------------------------------------------------------------\n\nconst platform =\n (globalThis as { navigator?: { platform?: string } }).navigator?.platform ?? '';\nconst isMac = /Mac|iPhone|iPad/.test(platform);\n\n/**\n * Convert a wheel event into a logarithmic zoom exponent.\n * Accounts for deltaMode (pixels/lines/pages) and trackpad pinch (ctrlKey on macOS).\n * Use as: `newZoom = currentZoom * Math.pow(2, wheelZoomDelta(e))`\n */\nexport function wheelZoomDelta(e: { deltaY: number; deltaMode: number; ctrlKey: boolean }): number {\n // ctrlKey + macOS = trackpad pinch — needs higher sensitivity\n const factor = e.ctrlKey && isMac ? 10 : 1;\n // deltaMode: 0=pixels, 1=lines(Firefox), 2=pages\n const modeScale = e.deltaMode === 1 ? 0.05 : e.deltaMode ? 1 : 0.002;\n return -e.deltaY * modeScale * factor;\n}\n\n/**\n * Normalize wheel deltas for panning across browsers.\n * Firefox fires deltaMode=1 (lines) with small values; Chrome fires deltaMode=0 (pixels) with large values.\n */\nexport function normalizeWheelPan(e: { deltaX: number; deltaY: number; deltaMode: number }): { x: number; y: number } {\n // Firefox line mode: ~3 lines per tick, multiply by ~20px/line to match Chrome pixel deltas\n const scale = e.deltaMode === 1 ? 20 : 1;\n return { x: -e.deltaX * scale, y: -e.deltaY * scale };\n}\n\n/**\n * Detect whether a wheel event is a trackpad pinch-to-zoom gesture.\n * Browsers send wheel events with ctrlKey=true for trackpad pinch.\n */\nexport function isTrackpadPinch(e: { ctrlKey: boolean; metaKey: boolean }): boolean {\n return e.ctrlKey || e.metaKey;\n}\n\nexport type WheelInteraction = 'zoom' | 'pan' | 'block' | 'ignore';\n\nexport type WheelInteractionOptions = {\n /**\n * Whether ordinary wheel gestures pan the canvas.\n */\n panOnScroll?: boolean;\n /**\n * Whether browser pinch gestures zoom the canvas.\n *\n * Even when disabled, pinch wheels should still be blocked while the pointer is\n * over the canvas so the browser page does not zoom behind the app.\n */\n zoomOnPinch?: boolean;\n /**\n * Whether a floating layer such as a context menu, popover, or dialog is open.\n */\n floatingLayerOpen?: boolean;\n};\n\n/**\n * Decide how a wheel event should be handled by a flow canvas.\n *\n * This mirrors the important React Flow / d3-zoom behavior: browser pinch\n * gestures are always consumed over the canvas. Otherwise the whole page can\n * zoom even though the user is interacting with the diagram.\n */\nexport function wheelInteraction(\n e: { ctrlKey: boolean; metaKey: boolean },\n options: WheelInteractionOptions = {},\n): WheelInteraction {\n if (isTrackpadPinch(e)) {\n if (options.floatingLayerOpen || options.zoomOnPinch === false) {\n return 'block';\n }\n return 'zoom';\n }\n\n if (options.floatingLayerOpen) {\n return options.panOnScroll ? 'block' : 'ignore';\n }\n\n return options.panOnScroll ? 'pan' : 'ignore';\n}\n\n/**\n * Constrain viewport so content can't be panned entirely off-screen.\n * When zoomed out (content smaller than view), centers the content.\n * Matches d3-zoom's defaultConstrain behavior.\n */\nexport function constrainViewport(\n viewport: Viewport,\n viewportSize: { width: number; height: number },\n translateExtent: [Point, Point],\n): Viewport {\n // Visible canvas bounds\n const vx0 = -viewport.x / viewport.zoom;\n const vy0 = -viewport.y / viewport.zoom;\n const vx1 = vx0 + viewportSize.width / viewport.zoom;\n const vy1 = vy0 + viewportSize.height / viewport.zoom;\n\n // Offsets from translate extent boundaries\n const dx0 = vx0 - translateExtent[0].x;\n const dx1 = vx1 - translateExtent[1].x;\n const dy0 = vy0 - translateExtent[0].y;\n const dy1 = vy1 - translateExtent[1].y;\n\n // If visible area exceeds extent, center; otherwise clamp to nearest boundary\n const tx = dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1);\n const ty = dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1);\n\n if (tx === 0 && ty === 0) return viewport;\n return {\n x: viewport.x + tx * viewport.zoom,\n y: viewport.y + ty * viewport.zoom,\n zoom: viewport.zoom,\n };\n}\n\n/**\n * Compute auto-pan velocity when dragging near the viewport edge.\n * Returns screen-space delta to apply per frame. Returns {0,0} if cursor isn't near an edge.\n */\nexport function calcAutoPan(\n mousePosition: Point,\n containerBounds: { width: number; height: number },\n edgeWidth = 25,\n speed = 10,\n): Point {\n if (edgeWidth <= 0 || speed <= 0) {\n return { x: 0, y: 0 };\n }\n\n const clamp01 = (value: number) => Math.min(1, Math.max(0, value));\n const getAxisDelta = (position: number, size: number) => {\n if (position < edgeWidth) {\n return -speed * clamp01(1 - position / edgeWidth);\n }\n\n if (position > size - edgeWidth) {\n return speed * clamp01(1 - (size - position) / edgeWidth);\n }\n\n return 0;\n };\n\n return {\n x: getAxisDelta(mousePosition.x, containerBounds.width),\n y: getAxisDelta(mousePosition.y, containerBounds.height),\n };\n}\n\n\n// Anchor transform (for toolbars, tooltips — accounts for inverse zoom)\n\n\nexport type AnchorSpec = {\n x: number | string; // px from left, or 'N%' for percentage\n y: number | string;\n offsetX?: number; // screen px (stays constant regardless of zoom)\n offsetY?: number;\n};\n\nexport type AnchorTransform = {\n x: number; // canvas x\n y: number; // canvas y\n scale: number; // 1/zoom — apply to keep constant screen size\n};\n\n/**\n * Compute anchor transform for positioning overlays relative to a rect.\n * Returns canvas-space position + inverse zoom scale.\n *\n * Offsets are in screen pixels — divided by zoom so they stay constant.\n *\n * Usage (SVG): `transform=\"translate(${t.x}, ${t.y}) scale(${t.scale})\"`\n * Usage (CSS): `transform: translate(${t.x}px, ${t.y}px) scale(${t.scale})`\n */\nexport function getAnchorTransform(\n bounds: Rect,\n viewport: Viewport,\n anchor: AnchorSpec,\n): AnchorTransform {\n const scale = 1 / viewport.zoom;\n\n // Parse anchor values\n const ax = parseAnchorValue(anchor.x, bounds.width);\n const ay = parseAnchorValue(anchor.y, bounds.height);\n\n // Canvas position = bounds origin + anchor offset + screen-px offset / zoom\n const x = bounds.x + ax + (anchor.offsetX ?? 0) * scale;\n const y = bounds.y + ay + (anchor.offsetY ?? 0) * scale;\n\n return { x, y, scale };\n}\n\nfunction parseAnchorValue(value: number | string, dimension: number): number {\n if (typeof value === 'number') return value;\n if (typeof value === 'string' && value.endsWith('%')) {\n return (parseFloat(value) / 100) * dimension;\n }\n return parseFloat(value) || 0;\n}\n","import type { Rect } from './types';\n\n\n// Snap Lines — Figma-style alignment guides\n//\n// Pure function: takes a dragged rect + other rects, returns snap result.\n// No dependencies on store or engine — safe to use anywhere.\n// Adapted from @statelyai/viz snap implementation.\n\n\nexport interface SnapLine {\n axis: 'x' | 'y';\n value: number;\n}\n\nexport interface SpacingGuide {\n axis: 'x' | 'y';\n /** Position on the perpendicular axis (y for 'x' axis, x for 'y') */\n position: number;\n /** The gap distance being matched */\n spacing: number;\n /** Segments showing where spacing applies */\n ranges: Array<{ start: number; end: number }>;\n}\n\nexport interface SnapResult {\n snapLines: SnapLine[];\n /** Exact input rect from which the snap delta was calculated */\n sourceRect: Rect;\n /** Adjusted rect position (size unchanged) */\n snapRect: Rect;\n spacingGuides?: SpacingGuide[];\n}\n\nexport interface SnapOptions {\n /** Distance threshold in canvas pixels (default 5) */\n threshold?: number;\n /** Enable equal-spacing guides (default false) */\n enableSpacing?: boolean;\n}\n\n/**\n * Compute snap lines for a dragged rect against other rects.\n *\n * Checks alignment of left/right/center-x and top/bottom/center-y\n * against all target rects. Optionally checks equal spacing between elements.\n *\n * Returns null if no snap is within threshold.\n */\nexport function getSnapLines(\n rect: Rect,\n otherRects: Rect[],\n { threshold = 5, enableSpacing = false }: SnapOptions = {},\n): SnapResult | null {\n if (otherRects.length === 0) return null;\n\n const getPoints = (r: Rect) => ({\n left: r.x,\n right: r.x + r.width,\n top: r.y,\n bottom: r.y + r.height,\n centerX: r.x + r.width / 2,\n centerY: r.y + r.height / 2,\n });\n\n const rectPoints = getPoints(rect);\n const snapLines: SnapLine[] = [];\n let snapX: number | null = null;\n let snapY: number | null = null;\n let minDistX = threshold + 1;\n let minDistY = threshold + 1;\n let spacingGuides: SpacingGuide[] = [];\n\n \n // Equal spacing detection\n \n if (enableSpacing && otherRects.length >= 1) {\n const hasVerticalOverlap = (a: Rect, b: Rect): boolean =>\n a.y < b.y + b.height && a.y + a.height > b.y;\n\n const hasHorizontalOverlap = (a: Rect, b: Rect): boolean =>\n a.x < b.x + b.width && a.x + a.width > b.x;\n\n // Horizontal spacing\n for (const target of otherRects) {\n if (!hasVerticalOverlap(rect, target)) continue;\n\n for (const other of otherRects) {\n if (other === target) continue;\n if (!hasVerticalOverlap(other, target)) continue;\n\n const gapRight = other.x - (target.x + target.width);\n const gapLeft = target.x - (other.x + other.width);\n\n // Dragged rect right of target, matching gap on left\n if (gapLeft > 0) {\n const snapPos = target.x + target.width + gapLeft;\n const dist = Math.abs(rectPoints.left - snapPos);\n if (dist <= threshold && dist < minDistX) {\n const oTop = Math.max(rect.y, target.y, other.y);\n const oBot = Math.min(rect.y + rect.height, target.y + target.height, other.y + other.height);\n const guideY = (oTop + oBot) / 2;\n minDistX = dist;\n snapX = snapPos;\n spacingGuides = [\n {\n axis: 'x',\n position: guideY,\n spacing: gapLeft,\n ranges: [\n { start: other.x + other.width, end: target.x },\n { start: target.x + target.width, end: snapPos },\n ],\n },\n ];\n }\n }\n\n // Dragged rect left of target, matching gap on right\n if (gapRight > 0) {\n const snapPos = target.x - gapRight - rect.width;\n const dist = Math.abs(rectPoints.left - snapPos);\n if (dist <= threshold && dist < minDistX) {\n const oTop = Math.max(rect.y, target.y, other.y);\n const oBot = Math.min(rect.y + rect.height, target.y + target.height, other.y + other.height);\n const guideY = (oTop + oBot) / 2;\n minDistX = dist;\n snapX = snapPos;\n spacingGuides = [\n {\n axis: 'x',\n position: guideY,\n spacing: gapRight,\n ranges: [\n { start: snapPos + rect.width, end: target.x },\n { start: target.x + target.width, end: other.x },\n ],\n },\n ];\n }\n }\n }\n }\n\n // Vertical spacing\n for (const target of otherRects) {\n if (!hasHorizontalOverlap(rect, target)) continue;\n\n for (const other of otherRects) {\n if (other === target) continue;\n if (!hasHorizontalOverlap(other, target)) continue;\n\n const gapBelow = other.y - (target.y + target.height);\n const gapAbove = target.y - (other.y + other.height);\n\n if (gapAbove > 0) {\n const snapPos = target.y + target.height + gapAbove;\n const dist = Math.abs(rectPoints.top - snapPos);\n if (dist <= threshold && dist < minDistY) {\n const oLeft = Math.max(rect.x, target.x, other.x);\n const oRight = Math.min(rect.x + rect.width, target.x + target.width, other.x + other.width);\n const guideX = (oLeft + oRight) / 2;\n minDistY = dist;\n snapY = snapPos;\n spacingGuides = spacingGuides.filter((g) => g.axis !== 'y');\n spacingGuides.push({\n axis: 'y',\n position: guideX,\n spacing: gapAbove,\n ranges: [\n { start: other.y + other.height, end: target.y },\n { start: target.y + target.height, end: snapPos },\n ],\n });\n }\n }\n\n if (gapBelow > 0) {\n const snapPos = target.y - gapBelow - rect.height;\n const dist = Math.abs(rectPoints.top - snapPos);\n if (dist <= threshold && dist < minDistY) {\n const oLeft = Math.max(rect.x, target.x, other.x);\n const oRight = Math.min(rect.x + rect.width, target.x + target.width, other.x + other.width);\n const guideX = (oLeft + oRight) / 2;\n minDistY = dist;\n snapY = snapPos;\n spacingGuides = spacingGuides.filter((g) => g.axis !== 'y');\n spacingGuides.push({\n axis: 'y',\n position: guideX,\n spacing: gapBelow,\n ranges: [\n { start: snapPos + rect.height, end: target.y },\n { start: target.y + target.height, end: other.y },\n ],\n });\n }\n }\n }\n }\n\n // Horizontal distribute: the dragged rect sits in the gap between a left and\n // a right neighbor, equidistant from both (equal spacing on each side).\n for (const left of otherRects) {\n if (!hasVerticalOverlap(rect, left)) continue;\n const leftEdge = left.x + left.width;\n for (const right of otherRects) {\n if (right === left) continue;\n if (!hasVerticalOverlap(rect, right)) continue;\n const rightEdge = right.x;\n if (leftEdge >= rightEdge) continue; // left must sit left of right, with a gap\n const snapPos = (leftEdge + rightEdge - rect.width) / 2;\n const gap = snapPos - leftEdge; // == rightEdge - (snapPos + rect.width)\n if (gap <= 0) continue; // no room for the rect between them\n const dist = Math.abs(rectPoints.left - snapPos);\n if (dist <= threshold && dist < minDistX) {\n const oTop = Math.max(rect.y, left.y, right.y);\n const oBot = Math.min(rect.y + rect.height, left.y + left.height, right.y + right.height);\n const guideY = (oTop + oBot) / 2;\n minDistX = dist;\n snapX = snapPos;\n spacingGuides = spacingGuides.filter((g) => g.axis !== 'x');\n spacingGuides.push({\n axis: 'x',\n position: guideY,\n spacing: gap,\n ranges: [\n { start: leftEdge, end: snapPos },\n { start: snapPos + rect.width, end: rightEdge },\n ],\n });\n }\n }\n }\n\n // Vertical distribute: equidistant between an above and a below neighbor.\n for (const above of otherRects) {\n if (!hasHorizontalOverlap(rect, above)) continue;\n const aboveEdge = above.y + above.height;\n for (const below of otherRects) {\n if (below === above) continue;\n if (!hasHorizontalOverlap(rect, below)) continue;\n const belowEdge = below.y;\n if (aboveEdge >= belowEdge) continue;\n const snapPos = (aboveEdge + belowEdge - rect.height) / 2;\n const gap = snapPos - aboveEdge;\n if (gap <= 0) continue;\n const dist = Math.abs(rectPoints.top - snapPos);\n if (dist <= threshold && dist < minDistY) {\n const oLeft = Math.max(rect.x, above.x, below.x);\n const oRight = Math.min(rect.x + rect.width, above.x + above.width, below.x + below.width);\n const guideX = (oLeft + oRight) / 2;\n minDistY = dist;\n snapY = snapPos;\n spacingGuides = spacingGuides.filter((g) => g.axis !== 'y');\n spacingGuides.push({\n axis: 'y',\n position: guideX,\n spacing: gap,\n ranges: [\n { start: aboveEdge, end: snapPos },\n { start: snapPos + rect.height, end: belowEdge },\n ],\n });\n }\n }\n }\n }\n\n\n // Edge & center alignment\n \n for (const target of otherRects) {\n const tp = getPoints(target);\n\n // X-axis checks: left/right/centerX vs target left/right/centerX\n const xChecks = [\n { source: rectPoints.left, target: tp.left },\n { source: rectPoints.left, target: tp.right },\n { source: rectPoints.left, target: tp.centerX },\n { source: rectPoints.right, target: tp.left },\n { source: rectPoints.right, target: tp.right },\n { source: rectPoints.right, target: tp.centerX },\n { source: rectPoints.centerX, target: tp.left },\n { source: rectPoints.centerX, target: tp.right },\n { source: rectPoints.centerX, target: tp.centerX },\n ];\n\n for (const check of xChecks) {\n const dist = Math.abs(check.source - check.target);\n if (dist <= threshold && dist < minDistX) {\n minDistX = dist;\n snapX = check.target - (check.source - rect.x);\n // Edge snapping closer than spacing → clear spacing guides for this axis\n if (spacingGuides.some((g) => g.axis === 'x')) {\n spacingGuides = spacingGuides.filter((g) => g.axis !== 'x');\n }\n }\n }\n\n // Y-axis checks\n const yChecks = [\n { source: rectPoints.top, target: tp.top },\n { source: rectPoints.top, target: tp.bottom },\n { source: rectPoints.top, target: tp.centerY },\n { source: rectPoints.bottom, target: tp.top },\n { source: rectPoints.bottom, target: tp.bottom },\n { source: rectPoints.bottom, target: tp.centerY },\n { source: rectPoints.centerY, target: tp.top },\n { source: rectPoints.centerY, target: tp.bottom },\n { source: rectPoints.centerY, target: tp.centerY },\n ];\n\n for (const check of yChecks) {\n const dist = Math.abs(check.source - check.target);\n if (dist <= threshold && dist < minDistY) {\n minDistY = dist;\n snapY = check.target - (check.source - rect.y);\n if (spacingGuides.some((g) => g.axis === 'y')) {\n spacingGuides = spacingGuides.filter((g) => g.axis !== 'y');\n }\n }\n }\n }\n\n if (snapX === null && snapY === null) return null;\n\n const snapRect: Rect = {\n x: snapX ?? rect.x,\n y: snapY ?? rect.y,\n width: rect.width,\n height: rect.height,\n };\n\n \n // Derive which alignment lines to display\n \n const snappedPoints = getPoints(snapRect);\n const seenLines = new Set<string>();\n\n for (const target of otherRects) {\n const tp = getPoints(target);\n\n const xAligns = [\n { source: snappedPoints.left, target: tp.left },\n { source: snappedPoints.left, target: tp.right },\n { source: snappedPoints.left, target: tp.centerX },\n { source: snappedPoints.right, target: tp.left },\n { source: snappedPoints.right, target: tp.right },\n { source: snappedPoints.right, target: tp.centerX },\n { source: snappedPoints.centerX, target: tp.left },\n { source: snappedPoints.centerX, target: tp.right },\n { source: snappedPoints.centerX, target: tp.centerX },\n ];\n\n for (const a of xAligns) {\n if (Math.abs(a.source - a.target) < 0.01) {\n const key = `x:${a.target}`;\n if (!seenLines.has(key)) {\n seenLines.add(key);\n snapLines.push({ axis: 'x', value: a.target });\n }\n }\n }\n\n const yAligns = [\n { source: snappedPoints.top, target: tp.top },\n { source: snappedPoints.top, target: tp.bottom },\n { source: snappedPoints.top, target: tp.centerY },\n { source: snappedPoints.bottom, target: tp.top },\n { source: snappedPoints.bottom, target: tp.bottom },\n { source: snappedPoints.bottom, target: tp.centerY },\n { source: snappedPoints.centerY, target: tp.top },\n { source: snappedPoints.centerY, target: tp.bottom },\n { source: snappedPoints.centerY, target: tp.centerY },\n ];\n\n for (const a of yAligns) {\n if (Math.abs(a.source - a.target) < 0.01) {\n const key = `y:${a.target}`;\n if (!seenLines.has(key)) {\n seenLines.add(key);\n snapLines.push({ axis: 'y', value: a.target });\n }\n }\n }\n }\n\n return {\n snapLines,\n sourceRect: rect,\n snapRect,\n spacingGuides: spacingGuides.length > 0 ? spacingGuides : undefined,\n };\n}\n","import type { FlowEdge, FlowGraph, FlowNode } from './types';\n\n// Id → entity indices, cached on array identity.\n//\n// The store's immer-based transitions produce a new nodes/edges array whenever\n// any entity changes, so array identity is a correct cache key: an index is\n// built at most once per store transition, turning the engine's per-query\n// O(N) `find` calls into O(1) lookups without changing any semantics.\n//\n// First occurrence wins on duplicate ids, matching `Array.prototype.find`.\n\nconst nodeIndexCache = new WeakMap<FlowNode[], Map<string, FlowNode>>();\nconst nodePositionCache = new WeakMap<FlowNode[], Map<string, number>>();\nconst childrenIndexCache = new WeakMap<FlowNode[], Map<string, FlowNode[]>>();\nconst edgeIndexCache = new WeakMap<FlowEdge[], Map<string, FlowEdge>>();\nconst edgePositionCache = new WeakMap<FlowEdge[], Map<string, number>>();\nconst edgeAdjacencyCache = new WeakMap<FlowEdge[], EdgeAdjacencyIndex>();\n\nexport type EdgeAdjacencyIndex = {\n bySource: Map<string, FlowEdge[]>;\n byTarget: Map<string, FlowEdge[]>;\n byNode: Map<string, FlowEdge[]>;\n};\n\nexport function indexNodes(nodes: FlowNode[]): Map<string, FlowNode> {\n let index = nodeIndexCache.get(nodes);\n if (!index) {\n index = new Map();\n const positions = new Map<string, number>();\n const children = new Map<string, FlowNode[]>();\n for (let position = 0; position < nodes.length; position++) {\n const node = nodes[position];\n if (!index.has(node.id)) index.set(node.id, node);\n if (!positions.has(node.id)) positions.set(node.id, position);\n const parentId = node.parentId ?? null;\n if (parentId == null || parentId === node.id) continue;\n const bucket = children.get(parentId);\n if (bucket) bucket.push(node);\n else children.set(parentId, [node]);\n }\n nodeIndexCache.set(nodes, index);\n nodePositionCache.set(nodes, positions);\n childrenIndexCache.set(nodes, children);\n }\n return index;\n}\n\nexport function indexNodePositions(nodes: FlowNode[]): Map<string, number> {\n if (!nodePositionCache.has(nodes)) indexNodes(nodes);\n return nodePositionCache.get(nodes)!;\n}\n\nexport function indexEdges(edges: FlowEdge[]): Map<string, FlowEdge> {\n let index = edgeIndexCache.get(edges);\n if (!index) {\n index = new Map();\n const positions = new Map<string, number>();\n const adjacency: EdgeAdjacencyIndex = {\n bySource: new Map(),\n byTarget: new Map(),\n byNode: new Map(),\n };\n for (let position = 0; position < edges.length; position++) {\n const edge = edges[position];\n if (!index.has(edge.id)) index.set(edge.id, edge);\n if (!positions.has(edge.id)) positions.set(edge.id, position);\n pushEdge(adjacency.bySource, edge.sourceId, edge);\n pushEdge(adjacency.byTarget, edge.targetId, edge);\n pushEdge(adjacency.byNode, edge.sourceId, edge);\n if (edge.targetId !== edge.sourceId) {\n pushEdge(adjacency.byNode, edge.targetId, edge);\n }\n }\n edgeIndexCache.set(edges, index);\n edgePositionCache.set(edges, positions);\n edgeAdjacencyCache.set(edges, adjacency);\n }\n return index;\n}\n\nexport function indexEdgePositions(edges: FlowEdge[]): Map<string, number> {\n if (!edgePositionCache.has(edges)) indexEdges(edges);\n return edgePositionCache.get(edges)!;\n}\n\nexport function indexEdgeAdjacency(edges: FlowEdge[]): EdgeAdjacencyIndex {\n let index = edgeAdjacencyCache.get(edges);\n if (!index) {\n indexEdges(edges);\n index = edgeAdjacencyCache.get(edges)!;\n }\n return index;\n}\n\nfunction pushEdge(\n index: Map<string, FlowEdge[]>,\n nodeId: string,\n edge: FlowEdge,\n): void {\n const bucket = index.get(nodeId);\n if (bucket) bucket.push(edge);\n else index.set(nodeId, [edge]);\n}\n\nexport function getIncomers(\n graph: FlowGraph,\n nodeId: string,\n): FlowNode[] {\n const nodes = indexNodes(graph.nodes);\n const sourceIds = new Set<string>();\n for (const edge of indexEdgeAdjacency(graph.edges).byTarget.get(nodeId) ?? []) {\n if (nodes.has(edge.sourceId)) sourceIds.add(edge.sourceId);\n }\n return graph.nodes.filter((node) => sourceIds.has(node.id));\n}\n\nexport function getOutgoers(\n graph: FlowGraph,\n nodeId: string,\n): FlowNode[] {\n const nodes = indexNodes(graph.nodes);\n const targetIds = new Set<string>();\n for (const edge of indexEdgeAdjacency(graph.edges).bySource.get(nodeId) ?? []) {\n if (nodes.has(edge.targetId)) targetIds.add(edge.targetId);\n }\n return graph.nodes.filter((node) => targetIds.has(node.id));\n}\n\nexport function getConnectedEdges(\n graph: FlowGraph,\n nodeIds: Iterable<string>,\n): FlowEdge[] {\n const ids = new Set(nodeIds);\n const nodes = indexNodes(graph.nodes);\n return graph.edges.filter(\n (edge) =>\n nodes.has(edge.sourceId) &&\n nodes.has(edge.targetId) &&\n (ids.has(edge.sourceId) || ids.has(edge.targetId)),\n );\n}\n\nexport function getNeighbors(\n graph: FlowGraph,\n nodeId: string,\n): FlowNode[] {\n const neighborIds = new Set<string>();\n for (const node of getIncomers(graph, nodeId)) neighborIds.add(node.id);\n for (const node of getOutgoers(graph, nodeId)) neighborIds.add(node.id);\n return graph.nodes.filter((node) => neighborIds.has(node.id));\n}\n\n/** parentId → child nodes, cached on array identity. Self-parents ignored. */\nexport function indexChildren(nodes: FlowNode[]): Map<string, FlowNode[]> {\n let index = childrenIndexCache.get(nodes);\n if (!index) {\n indexNodes(nodes);\n index = childrenIndexCache.get(nodes)!;\n }\n return index;\n}\n\nconst depthCache = new WeakMap<FlowNode[], Map<string, number>>();\n\n/**\n * Hierarchy depth per node id (roots = 0), cached on array identity.\n * Cycle-safe; missing parents count as roots. Renderers can sort by this so\n * parents paint beneath children regardless of array order.\n */\nexport function nodeDepths(nodes: FlowNode[]): Map<string, number> {\n let depths = depthCache.get(nodes);\n if (!depths) {\n const index = indexNodes(nodes);\n const resolved = new Map<string, number>();\n const depthOf = (node: FlowNode, seen: Set<string>): number => {\n const existing = resolved.get(node.id);\n if (existing !== undefined) return existing;\n const parentId = node.parentId ?? null;\n if (parentId == null || parentId === node.id || seen.has(node.id)) {\n resolved.set(node.id, 0);\n return 0;\n }\n seen.add(node.id);\n const parent = index.get(parentId);\n const depth = parent ? depthOf(parent, seen) + 1 : 0;\n resolved.set(node.id, depth);\n return depth;\n };\n for (const node of nodes) depthOf(node, new Set());\n depths = resolved;\n depthCache.set(nodes, depths);\n }\n return depths;\n}\n","import type { EdgeDirection, FlowNode, Point, Rect, Size } from './types';\nimport { indexNodes } from './graph-index';\n\n// Group hierarchy — pure geometry, fully policy-driven.\n//\n// Two sizing policies, configurable per node (`node.group`):\n//\n// - `derived` (default semantics à la the Stately editor): the parent's\n// bounds are a pure function of its children — content block of inherent\n// size on one side, children area (children union + padding) on the other.\n// Because nothing is stored, containment can never be violated and sizing\n// is perfectly reversible: move a child out and back, and the parent's\n// bounds are bit-identical. (Contrast React Flow's `expandParent`, which\n// bakes growth into the parent and has no auto-collapse.)\n//\n// - `fixed`: the parent's stored geometry is authoritative (resizable\n// container); children can optionally be clamped to the child area per\n// axis.\n//\n// Constraint-based child positioning (\"child A always at parent center-x\")\n// is intentionally out of scope for now; `deriveGroupGeometry` is the seam\n// where a constraint pass will slot in (adjust child rects before the union\n// is taken).\n\nexport type GroupContentSide = 'top' | 'left' | 'bottom' | 'right';\n\nexport type GroupInsets = {\n top: number;\n right: number;\n bottom: number;\n left: number;\n};\n\nexport type GroupLayout =\n | {\n type: 'derived';\n /** Which side the content block occupies (default 'top'). */\n content?: GroupContentSide;\n /** Padding around the children union (default 16). */\n padding?: number | Partial<GroupInsets>;\n /** Minimum child-area size when the group is empty or tiny. */\n minChildArea?: Size;\n /**\n * Width of the connectable boundary inside the child surface. When set,\n * the content block and this boundary are connectable, while the child\n * surface interior remains canvas. Omit to keep the full group body\n * connectable.\n */\n connectionBoundaryWidth?: number;\n /** Rank direction for this group's children during hierarchical layout. */\n direction?: EdgeDirection;\n }\n | {\n type: 'fixed';\n content?: GroupContentSide;\n padding?: number | Partial<GroupInsets>;\n /**\n * Size of the content block. Unlike `derived` groups (whose stored\n * width/height ARE the content size), a fixed group's stored\n * width/height describe the overall bounds, so the content block is\n * configured here (default: no content block).\n */\n contentSize?: Size;\n /** Clamp child drags to the child area (default 'none'). */\n clampChildren?: 'x' | 'y' | 'both' | 'none';\n /**\n * Width of the connectable boundary inside the child surface. When set,\n * the content block and this boundary are connectable, while the child\n * surface interior remains canvas. Omit to keep the full group body\n * connectable.\n */\n connectionBoundaryWidth?: number;\n /** Rank direction for this group's children during hierarchical layout. */\n direction?: EdgeDirection;\n };\n\nexport type GroupGeometry = {\n /** Overall group bounds. */\n bounds: Rect;\n /** The content block (title/body — the drag handle by convention). */\n contentBounds: Rect;\n /** Where children live (already inset by padding for `derived`). */\n childArea: Rect;\n};\n\nexport function resolveGroupPadding(\n padding: number | Partial<GroupInsets> | undefined,\n): GroupInsets {\n if (typeof padding === 'number') {\n return { top: padding, right: padding, bottom: padding, left: padding };\n }\n return {\n top: padding?.top ?? 16,\n right: padding?.right ?? 16,\n bottom: padding?.bottom ?? 16,\n left: padding?.left ?? 16,\n };\n}\n\nexport function isGroup(node: FlowNode): boolean {\n return node.group !== undefined;\n}\n\nexport function isDerivedGroup(node: FlowNode): boolean {\n return node.group?.type === 'derived';\n}\n\nexport function getNodeIdsWithDescendants(\n nodes: readonly FlowNode[],\n rootIds: ReadonlySet<string>,\n): Set<string> {\n const ids = new Set(rootIds);\n let changed = true;\n while (changed) {\n changed = false;\n for (const node of nodes) {\n if (node.parentId && ids.has(node.parentId) && !ids.has(node.id)) {\n ids.add(node.id);\n changed = true;\n }\n }\n }\n return ids;\n}\n\n/**\n * Derive a `derived` group's geometry from its content size and the union of\n * its children's bounds (pass null when the group has no children — the\n * anchor point then places the group's top-left).\n */\nexport function deriveGroupGeometry(\n contentSize: Size,\n childrenBounds: Rect | null,\n layout: Extract<GroupLayout, { type: 'derived' }>,\n /** Anchor (stored node position) used only when there are no children. */\n anchor: Point = { x: 0, y: 0 },\n): GroupGeometry {\n const side = layout.content ?? 'top';\n const padding = resolveGroupPadding(layout.padding);\n const minArea = layout.minChildArea ?? { width: 0, height: 0 };\n\n // Children area = children union expanded by padding (or the minimum).\n let childArea: Rect;\n if (childrenBounds) {\n childArea = {\n x: childrenBounds.x - padding.left,\n y: childrenBounds.y - padding.top,\n width: Math.max(\n childrenBounds.width + padding.left + padding.right,\n minArea.width,\n ),\n height: Math.max(\n childrenBounds.height + padding.top + padding.bottom,\n minArea.height,\n ),\n };\n } else {\n // Anchored placement for empty groups: content at the anchor, child area\n // adjacent to it.\n const horizontal = side === 'top' || side === 'bottom';\n childArea = {\n x: anchor.x,\n y: anchor.y,\n width: Math.max(\n minArea.width,\n padding.left + padding.right,\n horizontal ? contentSize.width : 0,\n ),\n height: Math.max(\n minArea.height,\n padding.top + padding.bottom,\n horizontal ? 0 : contentSize.height,\n ),\n };\n if (side === 'top') childArea.y += contentSize.height;\n if (side === 'left') childArea.x += contentSize.width;\n }\n\n return composeGeometry(contentSize, childArea, side);\n}\n\n/**\n * Geometry for a `fixed` group: stored bounds are authoritative; the content\n * block is carved from the configured side and the child area is the\n * remainder inset by padding.\n */\nexport function fixedGroupGeometry(\n bounds: Rect,\n contentSize: Size,\n layout: Extract<GroupLayout, { type: 'fixed' }>,\n): GroupGeometry {\n const side = layout.content ?? 'top';\n const padding = resolveGroupPadding(layout.padding);\n\n let contentBounds: Rect;\n let childArea: Rect;\n if (side === 'top' || side === 'bottom') {\n const contentHeight = Math.min(contentSize.height, bounds.height);\n contentBounds = {\n x: bounds.x,\n y: side === 'top' ? bounds.y : bounds.y + bounds.height - contentHeight,\n width: bounds.width,\n height: contentHeight,\n };\n childArea = {\n x: bounds.x + padding.left,\n y:\n (side === 'top' ? bounds.y + contentHeight : bounds.y) + padding.top,\n width: Math.max(bounds.width - padding.left - padding.right, 0),\n height: Math.max(\n bounds.height - contentHeight - padding.top - padding.bottom,\n 0,\n ),\n };\n } else {\n const contentWidth = Math.min(contentSize.width, bounds.width);\n contentBounds = {\n x: side === 'left' ? bounds.x : bounds.x + bounds.width - contentWidth,\n y: bounds.y,\n width: contentWidth,\n height: bounds.height,\n };\n childArea = {\n x:\n (side === 'left' ? bounds.x + contentWidth : bounds.x) + padding.left,\n y: bounds.y + padding.top,\n width: Math.max(\n bounds.width - contentWidth - padding.left - padding.right,\n 0,\n ),\n height: Math.max(bounds.height - padding.top - padding.bottom, 0),\n };\n }\n\n return { bounds, contentBounds, childArea };\n}\n\nfunction composeGeometry(\n contentSize: Size,\n childArea: Rect,\n side: GroupContentSide,\n): GroupGeometry {\n if (side === 'top' || side === 'bottom') {\n const width = Math.max(childArea.width, contentSize.width);\n const x = childArea.x - (width - childArea.width) / 2;\n const contentY =\n side === 'top'\n ? childArea.y - contentSize.height\n : childArea.y + childArea.height;\n return {\n bounds: {\n x,\n y: side === 'top' ? contentY : childArea.y,\n width,\n height: contentSize.height + childArea.height,\n },\n contentBounds: { x, y: contentY, width, height: contentSize.height },\n childArea,\n };\n }\n\n const height = Math.max(childArea.height, contentSize.height);\n const y = childArea.y - (height - childArea.height) / 2;\n const contentX =\n side === 'left'\n ? childArea.x - contentSize.width\n : childArea.x + childArea.width;\n return {\n bounds: {\n x: side === 'left' ? contentX : childArea.x,\n y,\n width: contentSize.width + childArea.width,\n height,\n },\n contentBounds: { x: contentX, y, width: contentSize.width, height },\n childArea,\n };\n}\n\n// Edge containment (studio digraph semantics)\n//\n// An edge \"belongs to\" the deepest node that contains both endpoints, where\n// an endpoint counts as containing itself — so A.X → A.Y belongs to A,\n// A.X → A.Y.Q belongs to A, A.X → A.X.Q belongs to X (the source contains\n// the target), A.X → B.Y belongs to the root (null), and a self-edge\n// A.X → A.X belongs to A (the source's parent). Renderless rule — derived\n// groups use it to include owned edge labels in their child bounds, with\n// one exception mirrored from the Stately editor: a node's self-edge never\n// constrains that node's own bounds (it may hang outside).\n\n/**\n * The id of the node that contains this edge, or null for the root.\n * Override per engine via `FlowEngineOptions.edgeOwner`.\n */\nexport function getEdgeOwner(\n edge: { sourceId: string; targetId: string },\n nodes: FlowNode[],\n): string | null {\n return getEdgeOwnerFromIndex(edge, indexNodes(nodes));\n}\n\n/** Internal indexed variant for hot paths that already index the graph. */\nexport function getEdgeOwnerFromIndex(\n edge: { sourceId: string; targetId: string },\n index: ReadonlyMap<string, FlowNode>,\n): string | null {\n const source = index.get(edge.sourceId);\n const target = index.get(edge.targetId);\n if (!source) return null;\n if (!target || source.id === target.id) return source.parentId ?? null;\n\n // Ancestor chain of the source, including the source itself.\n const sourceChain = new Set<string>([source.id]);\n let marker = source.parentId ?? null;\n while (marker && !sourceChain.has(marker)) {\n sourceChain.add(marker);\n marker = index.get(marker)?.parentId ?? null;\n }\n\n // First node on the target's chain (including the target) also on the\n // source's chain is the container.\n let candidate: string | null = target.id;\n const seen = new Set<string>();\n while (candidate && !seen.has(candidate)) {\n if (sourceChain.has(candidate)) return candidate;\n seen.add(candidate);\n candidate = index.get(candidate)?.parentId ?? null;\n }\n return null;\n}\n","import type { EdgeRouter, EdgeRouterContext } from './index';\nimport type { PathData, Point, Rect } from '../types';\n\nexport type AvoidRouterOptions = {\n margin?: number;\n maxGridLines?: number;\n};\n\nexport const avoidRouter: EdgeRouter = configureAvoidRouter();\n\nexport function configureAvoidRouter(options: AvoidRouterOptions = {}): EdgeRouter {\n return (edge, ctx) => {\n const margin = options.margin ?? 8;\n const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);\n const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);\n const obstacles = ctx.obstacles.map((rect) => inflateRect(rect, margin));\n\n // The Hanan grid needs two coordinates per obstacle plus the endpoints, so a\n // fixed cap bails whole edges to the (non-avoiding) fallback on dense graphs.\n // Scale the cap with the obstacle count so dense fields still route via A*.\n const gridCap = Math.max(\n options.maxGridLines ?? 96,\n obstacles.length * 2 + 8,\n );\n\n const points = routeThroughPoints(\n source,\n [...(ctx.waypoints ?? []), target],\n obstacles,\n gridCap,\n );\n\n if (!points) return fallbackStepPath(source, target, ctx, obstacles);\n return {\n points,\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n } satisfies PathData;\n };\n}\n\nfunction fallbackStepPath(\n source: Point,\n target: Point,\n ctx: EdgeRouterContext,\n obstacles: Rect[],\n): PathData {\n const targets = [...(ctx.waypoints ?? []), target];\n const naive = orthogonalFallback(source, targets, ctx.sourceDirection);\n return {\n points: detourAroundObstacles(naive, obstacles),\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n}\n\n/**\n * Last-resort obstacle avoidance for the orthogonal fallback: when a horizontal\n * or vertical segment cuts through an inflated obstacle interior, reroute it\n * over or under (or left/right of) the obstacle's outer edge. This keeps the\n * fallback orthogonal and off obstacle interiors even when A* bails.\n */\nfunction detourAroundObstacles(points: Point[], obstacles: Rect[]): Point[] {\n if (obstacles.length === 0) return points;\n let result = points;\n // A few passes let a detour introduced for one obstacle be re-checked\n // against the others it may now cross.\n for (let pass = 0; pass < 4; pass++) {\n const next: Point[] = [result[0]];\n let changed = false;\n for (let i = 1; i < result.length; i++) {\n const a = next.at(-1)!;\n const b = result[i];\n const blocker = firstBlockingObstacle(a, b, obstacles);\n if (!blocker) {\n pushDistinct(next, b);\n continue;\n }\n changed = true;\n for (const via of detourCorners(a, b, blocker)) pushDistinct(next, via);\n pushDistinct(next, b);\n }\n result = simplifyPolyline(next);\n if (!changed) break;\n }\n return result;\n}\n\nfunction firstBlockingObstacle(a: Point, b: Point, obstacles: Rect[]): Rect | null {\n for (const rect of obstacles) {\n if (segmentIntersectsInterior(a, b, rect)) return rect;\n }\n return null;\n}\n\n/**\n * Orthogonal corner points that route from `a` toward `b` around `rect`.\n * Picks the shorter side (above/below for horizontal, left/right for vertical).\n */\nfunction detourCorners(a: Point, b: Point, rect: Rect): Point[] {\n const pad = 1;\n if (a.y === b.y) {\n const above = rect.y - pad;\n const below = rect.y + rect.height + pad;\n const lane = Math.abs(a.y - above) <= Math.abs(a.y - below) ? above : below;\n const left = Math.min(a.x, b.x) === a.x ? rect.x - pad : rect.x + rect.width + pad;\n const right = left === rect.x - pad ? rect.x + rect.width + pad : rect.x - pad;\n return [\n { x: left, y: a.y },\n { x: left, y: lane },\n { x: right, y: lane },\n { x: right, y: b.y },\n ];\n }\n if (a.x === b.x) {\n const leftLane = rect.x - pad;\n const rightLane = rect.x + rect.width + pad;\n const lane = Math.abs(a.x - leftLane) <= Math.abs(a.x - rightLane) ? leftLane : rightLane;\n const top = Math.min(a.y, b.y) === a.y ? rect.y - pad : rect.y + rect.height + pad;\n const bottom = top === rect.y - pad ? rect.y + rect.height + pad : rect.y - pad;\n return [\n { x: a.x, y: top },\n { x: lane, y: top },\n { x: lane, y: bottom },\n { x: a.x, y: bottom },\n ];\n }\n return [];\n}\n\nfunction orthogonalFallback(\n source: Point,\n targets: Point[],\n sourceDirection: EdgeRouterContext['sourceDirection'],\n): Point[] {\n const points: Point[] = [source];\n let current = source;\n let direction = sourceDirection;\n for (const target of targets) {\n pushDistinct(points, computeStepMidpoint(current, target, direction));\n pushDistinct(points, target);\n direction = Math.abs(target.x - current.x) > Math.abs(target.y - current.y)\n ? target.x >= current.x ? 'right' : 'left'\n : target.y >= current.y ? 'bottom' : 'top';\n current = target;\n }\n return points;\n}\n\nfunction computeStepMidpoint(\n source: Point,\n target: Point,\n sourceDirection: EdgeRouterContext['sourceDirection'],\n): Point {\n if (sourceDirection === 'left' || sourceDirection === 'right') {\n return { x: (source.x + target.x) / 2, y: source.y };\n }\n return { x: source.x, y: (source.y + target.y) / 2 };\n}\n\nfunction routeThroughPoints(\n source: Point,\n targets: Point[],\n obstacles: Rect[],\n maxGridLines: number,\n): Point[] | null {\n const routed: Point[] = [source];\n let current = source;\n\n for (const target of targets) {\n const segment = routeSegment(current, target, obstacles, maxGridLines);\n if (!segment) return null;\n for (const point of segment.slice(1)) pushDistinct(routed, point);\n current = target;\n }\n\n return simplifyPolyline(routed);\n}\n\nfunction routeSegment(\n rawSource: Point,\n rawTarget: Point,\n obstacles: Rect[],\n maxGridLines: number,\n): Point[] | null {\n // When an endpoint falls inside an inflated obstacle (e.g. a large margin\n // swallows the point, or a neighbor's inflation overlaps it), snap it just\n // outside rather than bailing to the non-avoiding fallback. The original\n // endpoint is prepended/appended so the path still starts/ends exactly there.\n const source = snapOutside(rawSource, obstacles);\n const target = snapOutside(rawTarget, obstacles);\n if (pointInsideAny(source, obstacles) || pointInsideAny(target, obstacles)) return null;\n\n const xs = uniqueSorted([\n source.x,\n target.x,\n ...obstacles.flatMap((rect) => [rect.x, rect.x + rect.width]),\n ]);\n const ys = uniqueSorted([\n source.y,\n target.y,\n ...obstacles.flatMap((rect) => [rect.y, rect.y + rect.height]),\n ]);\n if (xs.length > maxGridLines || ys.length > maxGridLines) return null;\n\n const sourceKey = pointKey(source);\n const targetKey = pointKey(target);\n const open = new Set([sourceKey]);\n const cameFrom = new Map<string, string>();\n const gScore = new Map([[sourceKey, 0]]);\n const fScore = new Map([[sourceKey, manhattan(source, target)]]);\n\n while (open.size > 0) {\n const currentKey = lowestScore(open, fScore);\n const current = pointFromKey(currentKey);\n if (currentKey === targetKey) {\n const path = reconstruct(cameFrom, currentKey);\n // Reattach the true endpoints if we snapped them out of an obstacle.\n // The snapped point lies just outside the obstacle edge, so the extra\n // stub segment is short and stays orthogonal.\n if (rawSource.x !== source.x || rawSource.y !== source.y) path.unshift(rawSource);\n if (rawTarget.x !== target.x || rawTarget.y !== target.y) path.push(rawTarget);\n return path;\n }\n open.delete(currentKey);\n\n for (const neighbor of neighbors(current, xs, ys, obstacles)) {\n const neighborKey = pointKey(neighbor);\n const tentative = (gScore.get(currentKey) ?? Infinity) + manhattan(current, neighbor);\n if (tentative >= (gScore.get(neighborKey) ?? Infinity)) continue;\n cameFrom.set(neighborKey, currentKey);\n gScore.set(neighborKey, tentative);\n fScore.set(neighborKey, tentative + manhattan(neighbor, target));\n open.add(neighborKey);\n }\n }\n\n return null;\n}\n\nfunction neighbors(\n point: Point,\n xs: number[],\n ys: number[],\n obstacles: Rect[],\n): Point[] {\n const result: Point[] = [];\n const xIndex = xs.indexOf(point.x);\n const yIndex = ys.indexOf(point.y);\n if (xIndex < 0 || yIndex < 0) return result;\n\n for (const nextX of [xs[xIndex - 1], xs[xIndex + 1]]) {\n if (nextX === undefined) continue;\n const next = { x: nextX, y: point.y };\n if (!pointInsideAny(next, obstacles) && !segmentIntersectsAny(point, next, obstacles)) {\n result.push(next);\n }\n }\n for (const nextY of [ys[yIndex - 1], ys[yIndex + 1]]) {\n if (nextY === undefined) continue;\n const next = { x: point.x, y: nextY };\n if (!pointInsideAny(next, obstacles) && !segmentIntersectsAny(point, next, obstacles)) {\n result.push(next);\n }\n }\n\n return result;\n}\n\nfunction segmentIntersectsAny(a: Point, b: Point, obstacles: Rect[]): boolean {\n return obstacles.some((rect) => segmentIntersectsInterior(a, b, rect));\n}\n\nfunction segmentIntersectsInterior(a: Point, b: Point, rect: Rect): boolean {\n if (a.y === b.y) {\n const y = a.y;\n if (y <= rect.y || y >= rect.y + rect.height) return false;\n return Math.min(a.x, b.x) < rect.x + rect.width && Math.max(a.x, b.x) > rect.x;\n }\n if (a.x === b.x) {\n const x = a.x;\n if (x <= rect.x || x >= rect.x + rect.width) return false;\n return Math.min(a.y, b.y) < rect.y + rect.height && Math.max(a.y, b.y) > rect.y;\n }\n return false;\n}\n\n/**\n * If `point` is inside an inflated obstacle, move it just outside along the\n * nearest edge (keeping one coordinate fixed so the stub stays orthogonal).\n * Repeats a few times in case the point sits in overlapping inflated rects.\n */\nfunction snapOutside(point: Point, obstacles: Rect[]): Point {\n let current = point;\n for (let i = 0; i < obstacles.length + 1; i++) {\n const rect = obstacles.find((r) => pointStrictlyInside(current, r));\n if (!rect) return current;\n const pad = 1;\n const toLeft = current.x - (rect.x - pad);\n const toRight = rect.x + rect.width + pad - current.x;\n const toTop = current.y - (rect.y - pad);\n const toBottom = rect.y + rect.height + pad - current.y;\n const min = Math.min(toLeft, toRight, toTop, toBottom);\n if (min === toLeft) current = { x: rect.x - pad, y: current.y };\n else if (min === toRight) current = { x: rect.x + rect.width + pad, y: current.y };\n else if (min === toTop) current = { x: current.x, y: rect.y - pad };\n else current = { x: current.x, y: rect.y + rect.height + pad };\n }\n return current;\n}\n\nfunction pointStrictlyInside(point: Point, rect: Rect): boolean {\n return (\n point.x > rect.x &&\n point.x < rect.x + rect.width &&\n point.y > rect.y &&\n point.y < rect.y + rect.height\n );\n}\n\nfunction pointInsideAny(point: Point, obstacles: Rect[]): boolean {\n return obstacles.some(\n (rect) =>\n point.x > rect.x &&\n point.x < rect.x + rect.width &&\n point.y > rect.y &&\n point.y < rect.y + rect.height,\n );\n}\n\nfunction reconstruct(cameFrom: Map<string, string>, currentKey: string): Point[] {\n const path = [pointFromKey(currentKey)];\n while (cameFrom.has(currentKey)) {\n currentKey = cameFrom.get(currentKey)!;\n path.unshift(pointFromKey(currentKey));\n }\n return path;\n}\n\nfunction simplifyPolyline(points: Point[]): Point[] {\n const deduped: Point[] = [];\n for (const point of points) pushDistinct(deduped, point);\n\n const simplified: Point[] = [];\n for (const point of deduped) {\n simplified.push(point);\n while (simplified.length >= 3) {\n const a = simplified[simplified.length - 3];\n const b = simplified[simplified.length - 2];\n const c = simplified[simplified.length - 1];\n if ((a.x === b.x && b.x === c.x) || (a.y === b.y && b.y === c.y)) {\n simplified.splice(simplified.length - 2, 1);\n } else {\n break;\n }\n }\n }\n return simplified;\n}\n\nfunction pushDistinct(points: Point[], point: Point): void {\n const last = points.at(-1);\n if (last?.x === point.x && last.y === point.y) return;\n points.push(point);\n}\n\nfunction edgeMidpoint(rect: Rect, direction: EdgeRouterContext['sourceDirection']): Point {\n switch (direction) {\n case 'top':\n return { x: rect.x + rect.width / 2, y: rect.y };\n case 'bottom':\n return { x: rect.x + rect.width / 2, y: rect.y + rect.height };\n case 'left':\n return { x: rect.x, y: rect.y + rect.height / 2 };\n case 'right':\n return { x: rect.x + rect.width, y: rect.y + rect.height / 2 };\n }\n}\n\nfunction inflateRect(rect: Rect, margin: number): Rect {\n return {\n x: rect.x - margin,\n y: rect.y - margin,\n width: rect.width + margin * 2,\n height: rect.height + margin * 2,\n };\n}\n\nfunction uniqueSorted(values: number[]): number[] {\n return [...new Set(values)].sort((a, b) => a - b);\n}\n\nfunction lowestScore(open: Set<string>, scores: Map<string, number>): string {\n let best: string | undefined;\n let bestScore = Infinity;\n for (const key of open) {\n const score = scores.get(key) ?? Infinity;\n if (score < bestScore) {\n best = key;\n bestScore = score;\n }\n }\n return best!;\n}\n\nfunction manhattan(a: Point, b: Point): number {\n return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);\n}\n\nfunction pointKey(point: Point): string {\n return `${point.x},${point.y}`;\n}\n\nfunction pointFromKey(key: string): Point {\n const [x, y] = key.split(',').map(Number);\n return { x, y };\n}\n","import type {\n Direction,\n FlowEdge,\n FlowGraph,\n FlowNode,\n PathData,\n Point,\n Rect,\n} from '../types';\n\n\n// Edge routing\n//\n// Configurable router functions. Engine provides built-in routers.\n// Renderers convert PathData to SVG/Canvas.\n\n\nexport type EdgeRouterGraph<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = Omit<FlowGraph<TNodeData, TEdgeData, TLabelData>, 'nodes' | 'edges'> & {\n readonly nodes: readonly FlowNode<TNodeData>[];\n readonly edges: readonly FlowEdge<TEdgeData, TLabelData>[];\n};\n\nexport type EdgeRouterContext<\n TEdgeData = any,\n TLabelData = any,\n TNodeData = any,\n> = {\n /** Exact canonical or caller-provided projection graph currently being routed. */\n graph: EdgeRouterGraph<TNodeData, TEdgeData, TLabelData>;\n /**\n * Current visual bounds for a node or positioned edge label in `graph`.\n * Results are detached read-only values; looking up an edge never routes it.\n */\n getEntityBounds: (id: string) => Readonly<Rect> | undefined;\n sourceBounds: Rect;\n targetBounds: Rect;\n sourceDirection: Direction;\n targetDirection: Direction;\n sourcePoint?: Point;\n targetPoint?: Point;\n waypoints?: readonly Point[];\n /**\n * Sibling node bounds that custom routers can use for obstacle avoidance.\n *\n * @experimental Population rules may change as built-in obstacle routing lands.\n */\n obstacles: Rect[];\n};\n\n/**\n * Deterministic edge-routing function.\n *\n * Routers should depend only on the edge and supplied routing context. Do not\n * read viewport or external mutable state. With the default `graph`\n * dependencies, the edge and `context.graph` are read-only views that record\n * each field the router reads; Flow reuses a pass's paths while every recorded\n * read and every call's inputs are unchanged. A router that freezes or clones\n * those views is routed without tracking.\n */\nexport type EdgeRouter<\n TEdgeData = any,\n TLabelData = any,\n TNodeData = any,\n> = (\n edge: Readonly<FlowEdge<TEdgeData, TLabelData>>,\n context: EdgeRouterContext<TEdgeData, TLabelData, TNodeData>,\n) => PathData;\n\nexport type BezierRouterOptions = {\n curvature?: number;\n minOffset?: number;\n};\n\nexport type StepRouterOptions = {\n offset?: number;\n};\n\nexport {\n avoidRouter,\n configureAvoidRouter,\n type AvoidRouterOptions,\n} from './avoid';\n\n// Built-in: straight\n\n\nexport const straightRouter: EdgeRouter = (_edge, ctx) => {\n const source = ctx.sourcePoint ?? centerOf(ctx.sourceBounds);\n const target = ctx.targetPoint ?? centerOf(ctx.targetBounds);\n return {\n points: [source, ...(ctx.waypoints ?? []), target],\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n};\n\n\n// Built-in: step (orthogonal with one bend)\n\n\nexport const stepRouter: EdgeRouter = (_edge, ctx) => {\n const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);\n const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);\n if (ctx.waypoints?.length) {\n return {\n points: orthogonalPath(source, [...ctx.waypoints, target], ctx.sourceDirection),\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n }\n const mid = computeStepMidpoint(source, target, ctx.sourceDirection);\n\n return {\n points: [source, mid, target],\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n};\n\n\n// Built-in: bezier (cubic bezier control points)\n\n\nexport const bezierRouter: EdgeRouter = (_edge, ctx) => {\n const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);\n const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);\n return bezierPath(source, target, ctx, {});\n};\n\nexport function configureBezierRouter(options: BezierRouterOptions = {}): EdgeRouter {\n return (_edge, ctx) => {\n const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);\n const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);\n return bezierPath(source, target, ctx, options);\n };\n}\n\nexport function configureStepRouter(options: StepRouterOptions = {}): EdgeRouter {\n return (_edge, ctx) => {\n const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);\n const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);\n const mid = computeStepMidpoint(source, target, ctx.sourceDirection, options.offset);\n\n return {\n points: [source, mid, target],\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n };\n}\n\nfunction bezierPath(\n source: Point,\n target: Point,\n ctx: EdgeRouterContext,\n options: BezierRouterOptions,\n): PathData {\n if (ctx.waypoints?.length) {\n return {\n points: [source, ...ctx.waypoints, target],\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n }\n const curvature = options.curvature ?? 0.25;\n const offset = Math.max(\n options.minOffset ?? 50,\n Math.abs(target.x - source.x) * curvature,\n Math.abs(target.y - source.y) * curvature,\n );\n\n const cp1 = offsetPoint(source, ctx.sourceDirection, offset);\n const cp2 = offsetPoint(target, ctx.targetDirection, offset);\n\n return {\n points: [source, cp1, cp2, target],\n sourceDirection: ctx.sourceDirection,\n targetDirection: ctx.targetDirection,\n };\n}\n\nfunction orthogonalPath(\n source: Point,\n targets: Point[],\n sourceDir: Direction,\n): Point[] {\n const points: Point[] = [source];\n let current = source;\n let direction = sourceDir;\n for (const target of targets) {\n const mid = computeStepMidpoint(current, target, direction);\n pushDistinct(points, mid);\n pushDistinct(points, target);\n direction =\n Math.abs(target.x - current.x) > Math.abs(target.y - current.y)\n ? target.x >= current.x ? 'right' : 'left'\n : target.y >= current.y ? 'bottom' : 'top';\n current = target;\n }\n return points;\n}\n\nfunction pushDistinct(points: Point[], point: Point): void {\n const last = points.at(-1);\n if (last && last.x === point.x && last.y === point.y) return;\n points.push(point);\n}\n\n\n// Helpers\n\n\nfunction centerOf(rect: Rect): Point {\n return {\n x: rect.x + rect.width / 2,\n y: rect.y + rect.height / 2,\n };\n}\n\nfunction edgeMidpoint(rect: Rect, direction: Direction): Point {\n switch (direction) {\n case 'top':\n return { x: rect.x + rect.width / 2, y: rect.y };\n case 'bottom':\n return { x: rect.x + rect.width / 2, y: rect.y + rect.height };\n case 'left':\n return { x: rect.x, y: rect.y + rect.height / 2 };\n case 'right':\n return { x: rect.x + rect.width, y: rect.y + rect.height / 2 };\n }\n}\n\nfunction offsetPoint(point: Point, direction: Direction, offset: number): Point {\n switch (direction) {\n case 'top':\n return { x: point.x, y: point.y - offset };\n case 'bottom':\n return { x: point.x, y: point.y + offset };\n case 'left':\n return { x: point.x - offset, y: point.y };\n case 'right':\n return { x: point.x + offset, y: point.y };\n }\n}\n\nfunction computeStepMidpoint(\n source: Point,\n target: Point,\n sourceDir: Direction,\n offset?: number,\n): Point {\n if (offset !== undefined) {\n if (sourceDir === 'left') return { x: source.x - offset, y: target.y };\n if (sourceDir === 'right') return { x: source.x + offset, y: target.y };\n if (sourceDir === 'top') return { x: target.x, y: source.y - offset };\n return { x: target.x, y: source.y + offset };\n }\n if (sourceDir === 'left' || sourceDir === 'right') {\n return { x: (source.x + target.x) / 2, y: source.y };\n }\n return { x: source.x, y: (source.y + target.y) / 2 };\n}\n\n/**\n * Determine the side of `from` that faces `to`, based on relative centers.\n * The returned direction is from the perspective of `from`.\n */\nexport function bestDirection(from: Rect, to: Rect): Direction {\n const fromCx = from.x + from.width / 2;\n const fromCy = from.y + from.height / 2;\n const toCx = to.x + to.width / 2;\n const toCy = to.y + to.height / 2;\n\n const dx = toCx - fromCx;\n const dy = toCy - fromCy;\n\n if (Math.abs(dx) > Math.abs(dy)) {\n return dx > 0 ? 'right' : 'left';\n }\n return dy > 0 ? 'bottom' : 'top';\n}\n\n/**\n * Convert PathData to an SVG path `d` attribute. A valid router-provided\n * `svgPath` takes precedence over point-derived geometry.\n * Handles 2 points (line), 3 points (quadratic), 4 points (cubic bezier).\n */\nexport function pathToSVG(path: PathData): string {\n const pts = path.points;\n if (\n pts.length < 2 ||\n pts.some(({ x, y }) => !Number.isFinite(x) || !Number.isFinite(y))\n ) {\n return '';\n }\n\n const svgPath = validSvgPath(path.svgPath);\n if (svgPath) return svgPath;\n\n const [p0, p1, p2, p3] = pts;\n if (!p0) return '';\n\n const start = `M ${p0.x} ${p0.y}`;\n\n if (path.routing === 'polyline' || path.routing === 'orthogonal') {\n return start + pts.slice(1).map((p) => ` L ${p.x} ${p.y}`).join('');\n }\n\n if (\n path.routing === 'splines' &&\n pts.length >= 4 &&\n (pts.length - 1) % 3 === 0\n ) {\n let result = start;\n for (let index = 1; index + 2 < pts.length; index += 3) {\n const p1 = pts[index]!;\n const p2 = pts[index + 1]!;\n const p3 = pts[index + 2]!;\n result += ` C ${p1.x} ${p1.y}, ${p2.x} ${p2.y}, ${p3.x} ${p3.y}`;\n }\n return result;\n }\n\n if (pts.length === 2 && p1) {\n return `${start} L ${p1.x} ${p1.y}`;\n }\n\n if (pts.length === 3 && p1 && p2) {\n // Orthogonal step: line segments\n return `${start} L ${p1.x} ${p1.y} L ${p2.x} ${p2.y}`;\n }\n\n if (pts.length === 4 && p1 && p2 && p3) {\n // Cubic bezier\n return `${start} C ${p1.x} ${p1.y}, ${p2.x} ${p2.y}, ${p3.x} ${p3.y}`;\n }\n\n // Fallback: polyline\n return start + pts.slice(1).map((p) => ` L ${p.x} ${p.y}`).join('');\n}\n\nconst SVG_NUMBER_PATTERN = /[-+]?(?:\\d*\\.?\\d+)(?:[eE][-+]?\\d+)?/g;\nconst NON_FINITE_SVG_TOKEN = /NaN|[-+]?Infinity/i;\nconst SVG_PATH_TOKEN_PATTERN = /[MmZzLlHhVvCcSsQqTtAa]|[-+]?(?:\\d*\\.?\\d+)(?:[eE][-+]?\\d+)?/g;\n\nexport function isValidSvgPath(value: unknown): value is string {\n if (typeof value !== 'string') return false;\n const trimmed = value.trim();\n if (!trimmed || !/^[Mm]/.test(trimmed) || NON_FINITE_SVG_TOKEN.test(trimmed)) {\n return false;\n }\n const numbers = [...trimmed.matchAll(SVG_NUMBER_PATTERN)];\n if (!numbers.length || numbers.some((match) => !Number.isFinite(Number(match[0])))) {\n return false;\n }\n return trimmed.replace(SVG_PATH_TOKEN_PATTERN, '').replace(/[\\s,]/g, '') === '';\n}\n\nfunction validSvgPath(svgPath: string | undefined): string | undefined {\n const trimmed = svgPath?.trim();\n return isValidSvgPath(trimmed) ? trimmed : undefined;\n}\n","import type { FlowEdge, FlowGraph, FlowNode, Viewport } from './types';\nimport { isValidSvgPath } from './routing';\n\nexport type FlowResult<T, TError = FlowGraphValidationError> =\n | { ok: true; value: T }\n | { ok: false; error: TError };\n\nexport type FlowValidationIssue = {\n code: string;\n path: string;\n message: string;\n};\n\nexport class FlowGraphValidationError extends Error {\n readonly issues: readonly FlowValidationIssue[];\n\n constructor(issues: readonly FlowValidationIssue[]) {\n super(issues.map((issue) => `${issue.path}: ${issue.message}`).join('\\n'));\n this.name = 'FlowGraphValidationError';\n this.issues = issues;\n }\n}\n\nexport interface StandardSchemaV1Like<TOutput = unknown> {\n readonly '~standard': {\n readonly validate: (\n value: unknown,\n ) =>\n | { value: TOutput; issues?: undefined }\n | { value?: undefined; issues: readonly { message: string; path?: unknown }[] }\n | Promise<unknown>;\n };\n}\n\nexport type FlowDataKind = 'node' | 'edge' | 'label';\n\nexport type FlowDataSchema<TData = unknown> = {\n version: number;\n schema?: StandardSchemaV1Like<TData>;\n migrate?: (\n data: unknown,\n versions: { fromVersion: number; toVersion: number },\n ) => TData;\n remap?: (\n data: TData,\n context: { idMap: ReadonlyMap<string, string> },\n ) => TData;\n};\n\nexport type FlowDataSchemas<\n TNodeData = unknown,\n TEdgeData = unknown,\n TLabelData = unknown,\n> = {\n node?: FlowDataSchema<TNodeData>;\n edge?: FlowDataSchema<TEdgeData>;\n label?: FlowDataSchema<TLabelData>;\n};\n\nexport type FlowDataVersions = Partial<Record<FlowDataKind, number>>;\n\nconst OMIT = Symbol('omit');\n\nfunction issue(\n issues: FlowValidationIssue[],\n code: string,\n path: string,\n message: string,\n): void {\n issues.push({ code, path, message });\n}\n\nfunction cloneJsonValue(\n value: unknown,\n path: string,\n issues: FlowValidationIssue[],\n ancestors: Set<object>,\n inArray = false,\n): unknown | typeof OMIT {\n if (value === undefined) {\n if (inArray) {\n issue(issues, 'json_undefined', path, 'undefined is not JSON-safe in an array');\n }\n return OMIT;\n }\n if (value === null || typeof value === 'string' || typeof value === 'boolean') {\n return value;\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n issue(issues, 'json_non_finite', path, 'expected a finite number');\n }\n return value;\n }\n if (\n typeof value === 'function' &&\n /^\\$\\.graph\\.edges\\[\\d+\\]\\.labelAnchor$/.test(path)\n ) {\n return value;\n }\n if (\n typeof value === 'function' ||\n typeof value === 'symbol' ||\n typeof value === 'bigint'\n ) {\n issue(issues, 'json_unsupported', path, `${typeof value} is not JSON-safe`);\n return OMIT;\n }\n if (typeof value !== 'object') {\n issue(issues, 'json_unsupported', path, 'unsupported JSON value');\n return OMIT;\n }\n if (ancestors.has(value)) {\n issue(issues, 'json_cycle', path, 'cyclic references are not JSON-safe');\n return OMIT;\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) {\n issue(\n issues,\n 'json_non_plain_object',\n path,\n `${value.constructor?.name ?? 'non-plain object'} is not JSON-safe`,\n );\n return OMIT;\n }\n\n ancestors.add(value);\n if (Array.isArray(value)) {\n const result = value.map((entry, index) => {\n const cloned = cloneJsonValue(entry, `${path}[${index}]`, issues, ancestors, true);\n return cloned === OMIT ? null : cloned;\n });\n ancestors.delete(value);\n return result;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const cloned = cloneJsonValue(entry, `${path}.${key}`, issues, ancestors);\n if (cloned !== OMIT) {\n Object.defineProperty(result, key, {\n value: cloned,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n ancestors.delete(value);\n return result;\n}\n\nexport function cloneJsonSafe<T>(value: T, path = '$'): T {\n const issues: FlowValidationIssue[] = [];\n const cloned = cloneJsonValue(value, path, issues, new Set());\n if (cloned === OMIT) {\n issue(issues, 'json_unsupported', path, 'expected a JSON-safe value');\n }\n if (issues.length > 0) throw new FlowGraphValidationError(issues);\n return cloned as T;\n}\n\nfunction validateFiniteGeometry(\n value: Record<string, unknown>,\n path: string,\n issues: FlowValidationIssue[],\n): void {\n for (const key of ['x', 'y', 'width', 'height'] as const) {\n if (typeof value[key] !== 'number' || !Number.isFinite(value[key])) {\n issue(issues, 'invalid_geometry', `${path}.${key}`, 'expected a finite number');\n }\n }\n for (const key of ['dx', 'dy'] as const) {\n if (\n value[key] !== undefined &&\n (typeof value[key] !== 'number' || !Number.isFinite(value[key]))\n ) {\n issue(issues, 'invalid_geometry', `${path}.${key}`, 'expected a finite number');\n }\n }\n}\n\nfunction validateAutoSizeAnchor(\n value: unknown,\n path: string,\n issues: FlowValidationIssue[],\n): void {\n if (value === undefined || value === 'top-left' || value === 'center') return;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n issue(\n issues,\n 'invalid_auto_size_anchor',\n path,\n 'expected \"top-left\", \"center\", or fractional { x, y }',\n );\n return;\n }\n const anchor = value as Record<string, unknown>;\n for (const axis of ['x', 'y'] as const) {\n if (\n typeof anchor[axis] !== 'number' ||\n !Number.isFinite(anchor[axis]) ||\n anchor[axis] < 0 ||\n anchor[axis] > 1\n ) {\n issue(\n issues,\n 'invalid_auto_size_anchor',\n `${path}.${axis}`,\n 'expected a finite fraction from 0 through 1',\n );\n }\n }\n}\n\nfunction formatSchemaPath(path: unknown): string {\n if (!Array.isArray(path)) return '';\n return path\n .map((segment) =>\n typeof segment === 'object' && segment && 'key' in segment\n ? String((segment as { key: unknown }).key)\n : String(segment),\n )\n .filter(Boolean)\n .join('.');\n}\n\nfunction validateData<TData>(\n value: unknown,\n contract: FlowDataSchema<TData> | undefined,\n path: string,\n issues: FlowValidationIssue[],\n): unknown {\n if (!contract?.schema) return value;\n const result = contract.schema['~standard'].validate(value);\n if (result && typeof (result as { then?: unknown }).then === 'function') {\n issue(issues, 'async_schema', path, 'Flow data validation must be synchronous');\n return value;\n }\n const syncResult = result as Exclude<typeof result, Promise<unknown>>;\n if (syncResult.issues) {\n for (const schemaIssue of syncResult.issues) {\n const suffix = formatSchemaPath(schemaIssue.path);\n issue(\n issues,\n 'invalid_app_data',\n suffix ? `${path}.${suffix}` : path,\n schemaIssue.message,\n );\n }\n return value;\n }\n return syncResult.value;\n}\n\nfunction validateNodeData<TNodeData>(\n node: FlowNode<TNodeData>,\n index: number,\n schema: FlowDataSchema<TNodeData> | undefined,\n issues: FlowValidationIssue[],\n): void {\n node.data = validateData(node.data, schema, `$.graph.nodes[${index}].data`, issues) as TNodeData;\n}\n\nfunction validateEdgeData<TEdgeData, TLabelData>(\n edge: FlowEdge<TEdgeData, TLabelData>,\n index: number,\n schemas: Pick<FlowDataSchemas<unknown, TEdgeData, TLabelData>, 'edge' | 'label'> | undefined,\n issues: FlowValidationIssue[],\n): void {\n edge.data = validateData(edge.data, schemas?.edge, `$.graph.edges[${index}].data`, issues) as TEdgeData;\n if (edge.label != null) {\n if (typeof edge.label !== 'object' || Array.isArray(edge.label)) {\n issue(\n issues,\n 'invalid_label',\n `$.graph.edges[${index}].label`,\n 'expected a label object',\n );\n return;\n }\n edge.label.data = validateData(\n edge.label.data,\n schemas?.label,\n `$.graph.edges[${index}].label.data`,\n issues,\n ) as TLabelData;\n }\n}\n\nfunction validateAppearance(value: unknown, path: string, issues: FlowValidationIssue[]): void {\n if (value === undefined) return;\n if (!value || typeof value !== 'object' || Array.isArray(value) ||\n typeof (value as { name?: unknown }).name !== 'string' || !(value as { name: string }).name.length) {\n issue(issues, 'invalid_appearance', path, 'expected an appearance with a non-empty name');\n return;\n }\n const options = (value as { options?: unknown }).options;\n if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options))) {\n issue(issues, 'invalid_appearance', `${path}.options`, 'expected an options object');\n }\n}\n\nexport function validateAndCloneGraph<\n TNodeData = unknown,\n TEdgeData = unknown,\n TLabelData = unknown,\n>(\n input: unknown,\n schemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>,\n): FlowGraph<TNodeData, TEdgeData, TLabelData> {\n const issues: FlowValidationIssue[] = [];\n const cloned = cloneJsonValue(input, '$.graph', issues, new Set());\n if (!cloned || cloned === OMIT || typeof cloned !== 'object' || Array.isArray(cloned)) {\n issue(issues, 'invalid_graph', '$.graph', 'expected a graph object');\n throw new FlowGraphValidationError(issues);\n }\n\n const graph = cloned as FlowGraph<TNodeData, TEdgeData, TLabelData>;\n if (!Array.isArray(graph.nodes)) {\n issue(issues, 'invalid_nodes', '$.graph.nodes', 'expected an array');\n }\n if (!Array.isArray(graph.edges)) {\n issue(issues, 'invalid_edges', '$.graph.edges', 'expected an array');\n }\n if (issues.length > 0) throw new FlowGraphValidationError(issues);\n\n const ids = new Map<string, string>();\n const nodesById = new Map<string, FlowNode<TNodeData>>();\n graph.nodes.forEach((node, index) => {\n const path = `$.graph.nodes[${index}]`;\n if (!node || typeof node !== 'object' || Array.isArray(node)) {\n issue(issues, 'invalid_node', path, 'expected a node object');\n return;\n }\n if (typeof node.id !== 'string' || node.id.length === 0) {\n issue(issues, 'invalid_id', `${path}.id`, 'expected a non-empty string');\n } else if (ids.has(node.id)) {\n issue(issues, 'duplicate_id', `${path}.id`, `duplicate global entity id \"${node.id}\"`);\n } else {\n ids.set(node.id, path);\n nodesById.set(node.id, node);\n }\n validateFiniteGeometry(node as unknown as Record<string, unknown>, path, issues);\n validateAppearance(node.appearance, `${path}.appearance`, issues);\n validateAutoSizeAnchor(node.autoSizeAnchor, `${path}.autoSizeAnchor`, issues);\n validateNodeData(node, index, schemas?.node, issues);\n if (node.ports !== undefined) {\n if (!Array.isArray(node.ports)) {\n issue(issues, 'invalid_ports', `${path}.ports`, 'expected an array');\n return;\n }\n const portNames = new Set<string>();\n node.ports.forEach((port, portIndex) => {\n const portPath = `${path}.ports[${portIndex}]`;\n if (!port || typeof port !== 'object' || Array.isArray(port)) {\n issue(issues, 'invalid_port', portPath, 'expected a port object');\n return;\n }\n if (typeof port.name !== 'string' || port.name.length === 0) {\n issue(issues, 'invalid_port', `${portPath}.name`, 'expected a non-empty string');\n } else if (portNames.has(port.name)) {\n issue(issues, 'duplicate_port', `${portPath}.name`, `duplicate port \"${port.name}\"`);\n } else {\n portNames.add(port.name);\n }\n validateFiniteGeometry(port as unknown as Record<string, unknown>, portPath, issues);\n });\n }\n });\n\n graph.edges.forEach((edge, index) => {\n const path = `$.graph.edges[${index}]`;\n if (!edge || typeof edge !== 'object' || Array.isArray(edge)) {\n issue(issues, 'invalid_edge', path, 'expected an edge object');\n return;\n }\n if (typeof edge.id !== 'string' || edge.id.length === 0) {\n issue(issues, 'invalid_id', `${path}.id`, 'expected a non-empty string');\n } else if (ids.has(edge.id)) {\n issue(issues, 'duplicate_id', `${path}.id`, `duplicate global entity id \"${edge.id}\"`);\n } else {\n ids.set(edge.id, path);\n }\n validateFiniteGeometry(edge as unknown as Record<string, unknown>, path, issues);\n validateEdgeData(edge, index, schemas, issues);\n for (const [key, nodeId] of [\n ['sourceId', edge.sourceId],\n ['targetId', edge.targetId],\n ] as const) {\n if (typeof nodeId !== 'string' || !nodesById.has(nodeId)) {\n issue(issues, 'missing_endpoint', `${path}.${key}`, `node \"${String(nodeId)}\" does not exist`);\n }\n }\n for (const [key, nodeId, portName] of [\n ['sourcePort', edge.sourceId, edge.sourcePort],\n ['targetPort', edge.targetId, edge.targetPort],\n ] as const) {\n if (portName == null || portName === '*') continue;\n const node = nodesById.get(nodeId);\n if (\n !Array.isArray(node?.ports) ||\n !node.ports.some(\n (port) =>\n !!port &&\n typeof port === 'object' &&\n !Array.isArray(port) &&\n port.name === portName,\n )\n ) {\n issue(issues, 'missing_port', `${path}.${key}`, `port \"${portName}\" does not exist on node \"${nodeId}\"`);\n }\n }\n if (edge.label && typeof edge.label === \"object\") validateAppearance(edge.label.appearance, `${path}.label.appearance`, issues);\n if (edge.label && typeof edge.label === 'object' && !Array.isArray(edge.label)) {\n validateFiniteGeometry(\n edge.label as unknown as Record<string, unknown>,\n `${path}.label`,\n issues,\n );\n }\n if (edge.waypoints !== undefined) {\n if (!Array.isArray(edge.waypoints)) {\n issue(issues, 'invalid_waypoints', `${path}.waypoints`, 'expected an array');\n } else {\n edge.waypoints.forEach((point, pointIndex) => {\n if (\n !point ||\n typeof point !== 'object' ||\n Array.isArray(point) ||\n !Number.isFinite(point.x) ||\n !Number.isFinite(point.y)\n ) {\n issue(\n issues,\n 'invalid_geometry',\n `${path}.waypoints[${pointIndex}]`,\n 'expected finite x/y',\n );\n }\n });\n }\n }\n if (edge.points !== undefined) {\n if (!Array.isArray(edge.points)) {\n issue(\n issues,\n 'invalid_points',\n `${path}.points`,\n 'expected an array of points',\n );\n } else {\n edge.points.forEach((point, pointIndex) => {\n if (\n !point ||\n typeof point !== 'object' ||\n Array.isArray(point) ||\n !Number.isFinite(point.x) ||\n !Number.isFinite(point.y)\n ) {\n issue(\n issues,\n 'invalid_geometry',\n `${path}.points[${pointIndex}]`,\n 'expected finite x/y',\n );\n }\n });\n }\n }\n if (\n edge.routing !== undefined &&\n edge.routing !== 'polyline' &&\n edge.routing !== 'orthogonal' &&\n edge.routing !== 'splines'\n ) {\n issue(\n issues,\n 'invalid_routing',\n `${path}.routing`,\n 'expected polyline, orthogonal, or splines',\n );\n }\n if (edge.svgPath !== undefined && !isValidSvgPath(edge.svgPath)) {\n issue(\n issues,\n 'invalid_svg_path',\n `${path}.svgPath`,\n 'expected a finite SVG path beginning with M or m',\n );\n }\n });\n\n for (const [index, node] of graph.nodes.entries()) {\n if (!node || typeof node !== 'object' || Array.isArray(node)) continue;\n if (node.parentId == null) continue;\n if (!nodesById.has(node.parentId)) {\n issue(\n issues,\n 'missing_parent',\n `$.graph.nodes[${index}].parentId`,\n `parent node \"${node.parentId}\" does not exist`,\n );\n continue;\n }\n const seen = new Set([node.id]);\n let parentId: string | null | undefined = node.parentId;\n while (parentId != null) {\n if (seen.has(parentId)) {\n issue(\n issues,\n 'parent_cycle',\n `$.graph.nodes[${index}].parentId`,\n `parent cycle includes \"${parentId}\"`,\n );\n break;\n }\n seen.add(parentId);\n parentId = nodesById.get(parentId)?.parentId;\n }\n }\n\n if (issues.length > 0) throw new FlowGraphValidationError(issues);\n return graph;\n}\n\nexport function validateViewport(input: unknown, path = '$.viewport'): Viewport {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n throw new FlowGraphValidationError([\n { code: 'invalid_viewport', path, message: 'expected a viewport object' },\n ]);\n }\n const viewport = input as Viewport;\n const issues: FlowValidationIssue[] = [];\n for (const key of ['x', 'y', 'zoom'] as const) {\n if (typeof viewport[key] !== 'number' || !Number.isFinite(viewport[key])) {\n issue(issues, 'invalid_viewport', `${path}.${key}`, 'expected a finite number');\n }\n }\n if (viewport.zoom <= 0) {\n issue(issues, 'invalid_viewport', `${path}.zoom`, 'expected a positive zoom');\n }\n if (issues.length > 0) throw new FlowGraphValidationError(issues);\n return { ...viewport };\n}\n\nexport function currentDataVersions<TNodeData, TEdgeData, TLabelData>(\n schemas: FlowDataSchemas<TNodeData, TEdgeData, TLabelData> | undefined,\n): FlowDataVersions | undefined {\n if (!schemas) return undefined;\n const versions: FlowDataVersions = {};\n for (const kind of ['node', 'edge', 'label'] as const) {\n if (schemas[kind]) versions[kind] = schemas[kind]!.version;\n }\n return Object.keys(versions).length > 0 ? versions : undefined;\n}\n","import type { FlowEdge, FlowNode, PathData, Point, Rect } from './types';\nimport { authoritativeEdgePoints } from './authoritative-route';\nimport { isDerivedGroup } from './hierarchy';\nimport { resolvedBounds, resolvedPosition } from './spatial';\n\n/** A graph-owned route is authoritative whenever it contains valid endpoints. */\nexport function authoritativeEdgePath(edge: FlowEdge): PathData | null {\n const storedPoints = authoritativeEdgePoints(edge);\n if (!storedPoints) return null;\n const points = storedPoints.map((point) => ({ ...point }));\n\n const source = points[0]!;\n const sourceNext =\n points.find((point) => point.x !== source.x || point.y !== source.y) ??\n points[1]!;\n const target = points.at(-1)!;\n const targetPrevious =\n points.findLast((point) => point.x !== target.x || point.y !== target.y) ??\n points.at(-2)!;\n return {\n points,\n routing: edge.routing ?? 'polyline',\n svgPath: edge.svgPath,\n sourceDirection: directionBetween(source, sourceNext),\n targetDirection: directionBetween(target, targetPrevious),\n };\n}\n\n/** Remove layout-owned route geometry after an endpoint's geometry changes. */\nexport function invalidateAuthoritativeEdgePath(edge: FlowEdge): void {\n delete edge.points;\n delete edge.routing;\n delete edge.svgPath;\n}\n\n/** Whether a node mutation changes any position an incident edge can anchor to. */\nexport function nodeEndpointGeometryChanged(\n previous: FlowNode,\n next: FlowNode,\n): boolean {\n if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) return true;\n const previousBounds = resolvedBounds(previous);\n const nextBounds = resolvedBounds(next);\n if (\n previousBounds.x !== nextBounds.x ||\n previousBounds.y !== nextBounds.y ||\n previousBounds.width !== nextBounds.width ||\n previousBounds.height !== nextBounds.height\n ) {\n return true;\n }\n\n const previousPorts = previous.ports ?? [];\n const nextPorts = next.ports ?? [];\n if (previousPorts.length !== nextPorts.length) return true;\n return previousPorts.some((port) => {\n const nextPort = nextPorts.find((candidate) => candidate.name === port.name);\n return (\n !nextPort ||\n port.x !== nextPort.x ||\n port.y !== nextPort.y ||\n port.width !== nextPort.width ||\n port.height !== nextPort.height\n );\n });\n}\n\n/** Include derived groups whose rendered bounds depend on changed descendants. */\nexport function withDerivedGroupAncestors(\n nodes: readonly FlowNode[],\n changedNodeIds: ReadonlySet<string>,\n): Set<string> {\n const affected = new Set(changedNodeIds);\n const nodeIndex = new Map(nodes.map((node) => [node.id, node]));\n for (const changedNodeId of changedNodeIds) {\n let parentId = nodeIndex.get(changedNodeId)?.parentId;\n const visited = new Set<string>();\n while (parentId && !visited.has(parentId)) {\n visited.add(parentId);\n const parent = nodeIndex.get(parentId);\n if (!parent) break;\n if (isDerivedGroup(parent)) affected.add(parent.id);\n parentId = parent.parentId;\n }\n }\n return affected;\n}\n\nexport function isPointNearPath(point: Point, path: PathData, tolerance: number): boolean {\n const samplePoints = samplePathPoints(path);\n\n for (let i = 0; i < samplePoints.length - 1; i++) {\n const start = samplePoints[i];\n const end = samplePoints[i + 1];\n if (start && end && distanceToSegment(point, start, end) <= tolerance) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Axis-aligned bounding box of a path's control/anchor points. A cubic bezier\n * lies within the convex hull of its control points, so this is a conservative\n * superset of the rendered curve — exact enough for viewport culling (no false\n * negatives) and ~O(points) instead of sampling the curve. Returns null for an\n * empty path.\n */\nexport function pathBounds(path: PathData): Rect | null {\n let minX = Infinity,\n minY = Infinity,\n maxX = -Infinity,\n maxY = -Infinity;\n for (const point of path.points) {\n if (point.x < minX) minX = point.x;\n if (point.y < minY) minY = point.y;\n if (point.x > maxX) maxX = point.x;\n if (point.y > maxY) maxY = point.y;\n }\n if (!isFinite(minX)) return null;\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n}\n\nexport function rectIntersectsPath(rect: Rect, path: PathData): boolean {\n const samplePoints = samplePathPoints(path);\n\n for (const point of samplePoints) {\n if (pointInRect(point, rect)) {\n return true;\n }\n }\n\n const corners = rectCorners(rect);\n for (let i = 0; i < samplePoints.length - 1; i++) {\n const start = samplePoints[i];\n const end = samplePoints[i + 1];\n if (!start || !end) continue;\n\n if (pointInRect(start, rect) || pointInRect(end, rect)) {\n return true;\n }\n\n for (let cornerIndex = 0; cornerIndex < corners.length; cornerIndex++) {\n const edgeStart = corners[cornerIndex];\n const edgeEnd = corners[(cornerIndex + 1) % corners.length];\n if (edgeStart && edgeEnd && segmentsIntersect(start, end, edgeStart, edgeEnd)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function basicEdgePath(edge: FlowEdge, nodes: FlowNode[]): PathData | null {\n const authoritative = authoritativeEdgePath(edge);\n if (authoritative) return authoritative;\n\n const source = nodes.find((node) => node.id === edge.sourceId);\n const target = nodes.find((node) => node.id === edge.targetId);\n if (!source || !target) {\n return null;\n }\n\n return {\n points: [\n resolveBasicEndpoint(source, edge.sourcePort),\n resolveBasicEndpoint(target, edge.targetPort),\n ],\n sourceDirection: 'right',\n targetDirection: 'left',\n };\n}\n\nfunction directionBetween(from: Point, to: Point): PathData['sourceDirection'] {\n const dx = to.x - from.x;\n const dy = to.y - from.y;\n if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? 'right' : 'left';\n return dy >= 0 ? 'bottom' : 'top';\n}\n\nfunction resolveBasicEndpoint(node: FlowNode, portName: string | null | undefined): Point {\n if (portName && portName !== '*' && node.ports) {\n const port = node.ports.find((candidate) => candidate.name === portName);\n if (port) {\n const position = resolvedPosition(node);\n return {\n x: position.x + port.x + port.width / 2,\n y: position.y + port.y + port.height / 2,\n };\n }\n }\n\n const bounds = resolvedBounds(node);\n return {\n x: bounds.x + bounds.width / 2,\n y: bounds.y + bounds.height / 2,\n };\n}\n\nfunction samplePathPoints(path: PathData): Point[] {\n if (\n path.routing === 'splines' &&\n path.points.length >= 4 &&\n (path.points.length - 1) % 3 === 0\n ) {\n const sampled: Point[] = [];\n for (let index = 0; index + 3 < path.points.length; index += 3) {\n const [p0, p1, p2, p3] = path.points.slice(index, index + 4);\n if (!p0 || !p1 || !p2 || !p3) continue;\n const curve = sampleCubicBezier(p0, p1, p2, p3, 20);\n sampled.push(...(sampled.length ? curve.slice(1) : curve));\n }\n return sampled.length ? sampled : path.points;\n }\n\n if (!path.routing && path.points.length === 4) {\n const [p0, p1, p2, p3] = path.points;\n if (p0 && p1 && p2 && p3) {\n return sampleCubicBezier(p0, p1, p2, p3, 20);\n }\n }\n\n return path.points;\n}\n\nfunction sampleCubicBezier(\n p0: Point,\n p1: Point,\n p2: Point,\n p3: Point,\n steps: number,\n): Point[] {\n const points: Point[] = [];\n for (let i = 0; i <= steps; i++) {\n const t = i / steps;\n const mt = 1 - t;\n points.push({\n x:\n mt ** 3 * p0.x +\n 3 * mt ** 2 * t * p1.x +\n 3 * mt * t ** 2 * p2.x +\n t ** 3 * p3.x,\n y:\n mt ** 3 * p0.y +\n 3 * mt ** 2 * t * p1.y +\n 3 * mt * t ** 2 * p2.y +\n t ** 3 * p3.y,\n });\n }\n return points;\n}\n\nfunction distanceToSegment(point: Point, start: Point, end: Point): number {\n const dx = end.x - start.x;\n const dy = end.y - start.y;\n\n if (dx === 0 && dy === 0) {\n return Math.hypot(point.x - start.x, point.y - start.y);\n }\n\n const t = Math.max(\n 0,\n Math.min(1, ((point.x - start.x) * dx + (point.y - start.y) * dy) / (dx * dx + dy * dy)),\n );\n\n return Math.hypot(point.x - (start.x + t * dx), point.y - (start.y + t * dy));\n}\n\nfunction pointInRect(point: Point, rect: Rect): boolean {\n return (\n point.x >= rect.x &&\n point.x <= rect.x + rect.width &&\n point.y >= rect.y &&\n point.y <= rect.y + rect.height\n );\n}\n\nfunction rectCorners(rect: Rect): Point[] {\n return [\n { x: rect.x, y: rect.y },\n { x: rect.x + rect.width, y: rect.y },\n { x: rect.x + rect.width, y: rect.y + rect.height },\n { x: rect.x, y: rect.y + rect.height },\n ];\n}\n\nfunction segmentsIntersect(a1: Point, a2: Point, b1: Point, b2: Point): boolean {\n const d1 = direction(b1, b2, a1);\n const d2 = direction(b1, b2, a2);\n const d3 = direction(a1, a2, b1);\n const d4 = direction(a1, a2, b2);\n\n if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) {\n return true;\n }\n\n return (\n (d1 === 0 && onSegment(b1, b2, a1)) ||\n (d2 === 0 && onSegment(b1, b2, a2)) ||\n (d3 === 0 && onSegment(a1, a2, b1)) ||\n (d4 === 0 && onSegment(a1, a2, b2))\n );\n}\n\nfunction direction(a: Point, b: Point, c: Point): number {\n return (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x);\n}\n\nfunction onSegment(a: Point, b: Point, c: Point): boolean {\n return (\n Math.min(a.x, b.x) <= c.x &&\n c.x <= Math.max(a.x, b.x) &&\n Math.min(a.y, b.y) <= c.y &&\n c.y <= Math.max(a.y, b.y)\n );\n}\n","import { connectionLifetime } from '../connection-lifetime';\nimport { resolveAppearance, appearanceMeasurementId } from '../appearances';\nimport { createStore } from '@xstate/store';\nimport type { ExtractEvents, StoreExtension, StoreSnapshot } from '@xstate/store';\nimport { undoRedo } from '@xstate/store/undo';\nimport { produce, enableMapSet, current, isDraft, castDraft } from 'immer';\n\nenableMapSet();\nimport type {\n AutoLayoutState,\n CanvasState,\n ConnectionState,\n FlowEdge,\n FlowGraph,\n FlowNode,\n FitViewOptions,\n FlowAutoSizeAnchor,\n LabelAnchor,\n Point,\n Rect,\n ResizeHandle,\n SelectionMode,\n Size,\n Viewport,\n ViewportAnimationOptions,\n} from '../types';\nimport type { FlowViewScope, FlowViewSelectionPolicy } from '../view';\nimport {\n defaultFlowProfile,\n type FlowEventObject,\n type FlowProfile,\n type FlowTransition,\n} from '../profile';\nimport { createViewport, viewportForBounds } from '../viewport';\nimport {\n getGraphBounds,\n getSelectionBounds,\n rectsIntersect,\n resolvedBounds,\n snappedBounds,\n resolvedSelectionBounds,\n resolvedSize,\n boxToRect,\n snapToGrid,\n constrainViewport,\n rectContains,\n resolvedEdgeLabelBounds,\n resolvedEdgeLabelSize,\n} from '../spatial';\nimport { getSnapLines } from '../snap';\nimport {\n indexChildren,\n indexEdgePositions,\n indexEdges,\n indexNodePositions,\n indexNodes,\n} from '../graph-index';\nimport {\n deriveGroupGeometry,\n fixedGroupGeometry,\n getEdgeOwnerFromIndex,\n getNodeIdsWithDescendants,\n type GroupGeometry,\n} from '../hierarchy';\nimport { validateAndCloneGraph } from '../validation';\nimport {\n invalidateAuthoritativeEdgePath,\n nodeEndpointGeometryChanged,\n withDerivedGroupAncestors,\n} from '../edge-geometry';\n\n// FlowStore\n//\n// XState Store + Immer for immutable updates.\n// All interaction state lives here — engine is purely derived.\n\n/**\n * Decides whether an entity is captured by the box-select rectangle.\n * `box` and `bounds` are both in canvas coordinates.\n */\nexport type BoxSelectionTest = (box: Rect, bounds: Rect) => boolean;\n\nfunction resolveAutoSizeAnchor(anchor: FlowAutoSizeAnchor | undefined): Point {\n if (anchor === undefined || anchor === 'top-left') return { x: 0, y: 0 };\n if (anchor === 'center') return { x: 0.5, y: 0.5 };\n if (\n !anchor ||\n !Number.isFinite(anchor.x) ||\n !Number.isFinite(anchor.y) ||\n anchor.x < 0 ||\n anchor.x > 1 ||\n anchor.y < 0 ||\n anchor.y > 1\n ) {\n throw new RangeError('autoSizeAnchor must be \"top-left\", \"center\", or fractional { x, y }.');\n }\n return anchor;\n}\n\nexport type FlowStoreContext = {\n /** Host presentation policies; never serialized with authored graph data. */\n appearances?: import(\"../appearances\").FlowAppearances;\n // Graph data\n graph: FlowGraph;\n\n // Navigation\n parentNodeId: string | null;\n depth: number | null; // null = unlimited\n\n // Viewport\n viewport: Viewport;\n viewportSize: Size;\n /** Persistent screen-space target for fit/center commands; null = full viewport. */\n fitFrame: Rect | null;\n viewportStack: Viewport[];\n minZoom: number;\n maxZoom: number;\n translateExtent: [Point, Point] | null; // pan boundary\n nodeExtent: [Point, Point] | null; // node drag boundary\n\n // Selection & focus\n selection: Set<string>;\n selectionBox: [Point, Point] | null; // active box-select corners\n /** Selection snapshot when a box gesture began, so shift-drag adds to it. */\n selectionBoxBase: ReadonlySet<string> | null;\n /**\n * Predicate deciding whether an entity (by its bounds) falls inside the\n * box-select rectangle. Defaults to the `selectionMode` behavior (partial =\n * any overlap, full = fully contained), but apps can supply any rule — e.g.\n * a \"≥75% overlap\" test — without the package hardcoding the modes.\n */\n boxSelectionTest: BoxSelectionTest | null;\n /** Entities currently under the pointer (driven by the input runtime). */\n hoveredEntityIds: Set<string>;\n /** Group nodes whose descendants are hidden by the engine. */\n collapsedNodeIds: Set<string>;\n /**\n * Semantic highlights: kind → (entity id → metadata). Kinds are\n * user-defined strings; metadata is user-defined (e.g. heatmap weights,\n * colors). Visual-only state — not undoable.\n */\n highlights: FlowHighlights;\n focusedEntityId: string | null;\n measurements: Map<string, Rect>;\n /** Renderer port rectangles in owner-local coordinates. */\n derivedPortMeasurements: Map<string, Rect>;\n\n // Interaction\n canvasState: CanvasState;\n draggedEntityId: string | null;\n /** Monotonic signal for exact per-entity drag-frame notification. */\n dragRevision: number;\n dragThreshold: number; // px before drag starts\n /**\n * Constrains where a node may move during drags/keyboard nudges. Receives\n * the node and its proposed absolute position (after extent/group clamps);\n * return an adjusted position, or null/undefined to accept. Drag sessions\n * are pointer-anchored, so constraint clamps never accumulate drift.\n * Example: prevent sibling overlap (see the PreventOverlap story).\n */\n constrainNodeMovement:\n | ((node: FlowNode, proposed: Point, context: FlowStoreContext) => Point | null | undefined)\n | null;\n autoPanOnDrag: boolean;\n autoPanThreshold: number;\n autoPanSpeed: number;\n connection: ConnectionState | null;\n connectOnClick: boolean;\n connectionDragThreshold: number;\n connectionClickStartHandle: { nodeId: string; port: string | null } | null;\n // Pan state (screen-space bookkeeping for pan gesture)\n panOrigin: Point | null;\n panViewportOrigin: Viewport | null;\n /** Default animation applied to viewport commands unless overridden per call. */\n viewportAnimation: ViewportAnimationOptions | null;\n\n // Resize state\n resizingEntityId: string | null;\n resizeHandle: ResizeHandle | null;\n /** Two opposite corners during resize: [anchor, moving]. Derived bounds = min/max of these. */\n resizeCorners: [Point, Point] | null;\n\n // Profile mode — determines which profile transitions and input config apply\n mode: string;\n selectionMode: SelectionMode;\n\n // Grid snapping\n snapToGrid: boolean;\n snapGrid: [number, number]; // [x, y] grid sizes\n\n // Entity snap lines (Figma-style alignment guides)\n enableSnapLines: boolean;\n snapThreshold: number; // threshold in screen px (divided by zoom)\n enableSpacingGuides: boolean;\n\n // Layout\n autoLayout: AutoLayoutState;\n /** Transient visual offsets for an in-flight layout animation. */\n layoutAnimation: {\n status: 'idle' | 'running';\n offsets: Map<string, Point>;\n };\n\n // Presentation\n colorMode: FlowColorMode;\n\n /**\n * Default edge label anchor (mirrors the engine's default). Movement\n * planning needs it to know whether a label auto-follows its endpoints\n * (numeric/function anchors) or sits at a fixed position that must be\n * carried along with a rigidly-dragged subtree.\n */\n labelAnchor: LabelAnchor;\n\n /**\n * Monotonic counter bumped whenever engine options change at runtime (via\n * `flow.configure({ engine })`). Engine option changes mutate the engine and\n * clear its memo caches but produce no graph/viewport change, so store\n * subscribers (React's `useSyncExternalStore`) would never re-derive. Bumping\n * this emits a fresh context reference so consumers recompute against the\n * newly-configured engine. Visual-only — not undoable.\n */\n configRevision: number;\n /** External router output changed without changing graph geometry or configuration. */\n routingRevision: number;\n};\n\nexport type FlowColorMode = 'light' | 'dark' | 'system';\n\n/** kind → (entity id → metadata) */\nexport type FlowHighlights = Map<string, Map<string, unknown>>;\n\nexport type FlowHighlightEntry = { id: string; meta?: unknown };\n\n/**\n * Store creation options.\n *\n * Runtime-updatable through `flow.configure({ store })` / `updateSettings`:\n * drag threshold, movement constraint, auto-pan settings, snap-line settings,\n * box-selection test, and default label anchor. Other options are\n * construct-only or have dedicated runtime events.\n */\nexport type FlowStoreOptions = {\n appearances?: import(\"../appearances\").FlowAppearances;\n minZoom?: number;\n maxZoom?: number;\n translateExtent?: [Point, Point] | null;\n nodeExtent?: [Point, Point] | null;\n dragThreshold?: number;\n /** See `FlowStoreContext.constrainNodeMovement`. */\n constrainNodeMovement?: (\n node: FlowNode,\n proposed: Point,\n context: FlowStoreContext\n ) => Point | null | undefined;\n autoPanOnDrag?: boolean;\n autoPanThreshold?: number;\n autoPanSpeed?: number;\n /** Default animation applied to viewport commands unless overridden per call. */\n viewportAnimation?: ViewportAnimationOptions | null;\n snapToGrid?: boolean;\n snapGrid?: [number, number];\n enableSnapLines?: boolean;\n snapThreshold?: number;\n enableSpacingGuides?: boolean;\n connectOnClick?: boolean;\n colorMode?: FlowColorMode;\n /** Default edge label anchor; should mirror the engine's `labelAnchor`. */\n labelAnchor?: LabelAnchor;\n /** See `FlowStoreContext.boxSelectionTest`. */\n boxSelectionTest?: BoxSelectionTest;\n connectionDragThreshold?: number;\n selectionMode?: SelectionMode;\n historyLimit?: number;\n mode?: string;\n profile?: FlowProfile;\n /**\n * Controls what happens to edges when a node is deleted.\n * - 'cascade' (default): delete all edges connected to the node\n * - 'retarget': edges connected to deleted node become self-loops on the other endpoint\n * - function: custom logic — receives graph + node ids to delete, returns { nodes, edges } to keep\n */\n onDeleteNodes?:\n | 'cascade'\n | 'retarget'\n | ((graph: FlowGraph, nodeIds: Set<string>) => { nodes: FlowNode[]; edges: FlowEdge[] });\n};\n\nexport type FlowRuntimeSettings = Pick<\n FlowStoreOptions,\n | 'dragThreshold'\n | 'constrainNodeMovement'\n | 'autoPanOnDrag'\n | 'autoPanThreshold'\n | 'autoPanSpeed'\n | 'viewportAnimation'\n | 'enableSnapLines'\n | 'snapThreshold'\n | 'enableSpacingGuides'\n | 'boxSelectionTest'\n | 'labelAnchor'\n>;\n\nexport type LayoutRequestedEvent = {\n algorithm: string;\n graph: FlowGraph;\n};\n\nexport type ConnectEndTarget =\n | { kind: 'node'; nodeId: string; port: string | null }\n | { kind: 'edge'; edgeId: string }\n | { kind: 'canvas'; position: Point }\n | { kind: 'none' };\n\nexport type ConnectionEndedEvent = {\n status: 'connected' | 'cancelled' | 'invalid';\n source: { nodeId: string; port: string | null };\n target: ConnectEndTarget;\n connection: ConnectionState;\n reconnectedEdgeId?: string;\n};\n\nexport type FlowGraphChangedEvent = {\n graph: FlowGraph;\n event: FlowEventObject;\n};\n\nexport type FlowViewportChangedEvent = {\n viewport: Viewport;\n event: FlowEventObject;\n};\n\nexport type FlowSelectionChangedEvent = {\n selection: Set<string>;\n event: FlowEventObject;\n};\n\nexport type FlowViewChangedEvent = {\n scope: FlowViewScope;\n event: FlowEventObject;\n};\n\nexport type FlowEntitiesDeletedEvent = {\n ids: string[];\n event: FlowEventObject;\n};\n\nexport type FlowErrorEvent = {\n error: unknown;\n event?: FlowEventObject;\n};\n\nexport type FlowGestureModifiers = {\n shift: boolean;\n meta: boolean;\n ctrl: boolean;\n alt: boolean;\n};\n\nexport type FlowDragStartedEvent = {\n ids: string[];\n positions: Record<string, Point>;\n};\n\nexport type FlowDragMovedEvent = FlowDragStartedEvent & {\n delta: Point;\n};\n\nexport type FlowDragEndedEvent = FlowDragStartedEvent;\n\nexport type FlowResizeStartedEvent = {\n id: string;\n handle: ResizeHandle;\n bounds: Rect;\n};\n\nexport type FlowResizeEndedEvent = {\n id: string;\n bounds: Rect;\n};\n\nexport type FlowConnectStartedEvent = {\n sourceId: string;\n sourcePort: string | null;\n point: Point;\n};\n\nexport type FlowConnectMovedEvent = {\n point: Point;\n targetId: string | null;\n targetPort: string | null;\n isValid: boolean;\n invalidReason?: string;\n};\n\nexport type FlowPaneGestureEvent = {\n point: Point;\n modifiers: FlowGestureModifiers;\n};\n\nexport type FlowEntityGestureEvent = FlowPaneGestureEvent & {\n id: string;\n};\n\ntype FlowEmittedPayloadMap = {\n layoutRequested: LayoutRequestedEvent;\n connectionEnded: ConnectionEndedEvent;\n graphChanged: FlowGraphChangedEvent;\n viewportChanged: FlowViewportChangedEvent;\n selectionChanged: FlowSelectionChangedEvent;\n viewChanged: FlowViewChangedEvent;\n entitiesDeleted: FlowEntitiesDeletedEvent;\n dragStarted: FlowDragStartedEvent;\n dragMoved: FlowDragMovedEvent;\n dragEnded: FlowDragEndedEvent;\n resizeStarted: FlowResizeStartedEvent;\n resizeEnded: FlowResizeEndedEvent;\n connectStarted: FlowConnectStartedEvent;\n connectMoved: FlowConnectMovedEvent;\n paneClicked: FlowPaneGestureEvent;\n paneContextMenu: FlowPaneGestureEvent;\n entityClicked: FlowEntityGestureEvent;\n entityDoubleClicked: FlowEntityGestureEvent;\n entityContextMenu: FlowEntityGestureEvent;\n error: FlowErrorEvent;\n};\n\ntype FlowEventPayloadMap = {\n createNode: { node: FlowNode } & TransactionMetadata;\n deleteNode: { id: string } & TransactionMetadata;\n updateNode: FlowUpdateNodeEvent;\n updateNodeData: { id: string; data: Record<string, unknown> } & TransactionMetadata;\n createEdge: { edge: FlowEdge } & TransactionMetadata;\n deleteEdge: { id: string } & TransactionMetadata;\n deleteEntities: {\n nodeIds?: string[];\n edgeIds?: string[];\n } & TransactionMetadata;\n updateEdge: FlowUpdateEdgeEvent;\n updateEdgeData: { id: string; data: Record<string, unknown> } & TransactionMetadata;\n deleteSelected: undefined;\n setGraph: { graph: FlowGraph };\n replaceGraph: {\n graph: FlowGraph;\n graphChanged?: boolean;\n resetMeasurementIds?: readonly string[];\n layoutAnimationOffsets?: Map<string, Point>;\n } & ReplaceGraphMetadata;\n setLayoutAnimationOffsets: { offsets: Map<string, Point> };\n clearLayoutAnimation: undefined;\n loadDocument: {\n graph: FlowGraph;\n collapsedNodeIds: string[];\n viewport: Viewport;\n } & TransactionMetadata;\n setCollapsedNodes: { ids: string[] };\n reset: undefined;\n reparentNode: { id: string; parentId: string | null } & TransactionMetadata;\n collapseNode: { id: string } & TransactionMetadata;\n expandNode: { id: string } & TransactionMetadata;\n dragStart: { id: string } & TransactionMetadata;\n dragMove: { dx: number; dy: number };\n dragEnd: undefined;\n dragCancel: undefined;\n commitDrag: (TransactionMetadata & { snapOffset?: Point }) | undefined;\n select: { ids: string[]; mode?: 'single' | 'multi' };\n selectAll: undefined;\n clearSelection: undefined;\n selectionBoxStart: { point: Point; mode?: 'single' | 'multi' };\n selectionBoxMove: { point: Point };\n selectionBoxEnd: undefined;\n selectionBoxCancel: undefined;\n focus: { entityId: string };\n clearFocus: undefined;\n setHover: { ids: string[] };\n clearHover: undefined;\n /** Replace one kind's highlight bucket (bulk update, e.g. heatmaps). */\n setHighlights: { kind: string; entries: FlowHighlightEntry[] };\n addHighlights: { kind: string; entries: FlowHighlightEntry[] };\n removeHighlights: { kind: string; ids: string[] };\n clearHighlights: { kind?: string } | undefined;\n updateParentNodeId: { parentNodeId: string | null };\n setViewScope: {\n parentNodeId: string | null;\n depth: number | null;\n selection: FlowViewSelectionPolicy;\n visibleEntityIds: string[];\n };\n setViewport: Viewport;\n setFitFrame: { frame: Rect | null; preserveCenter?: boolean };\n panBy: Point;\n zoomTo: { zoom: number; center: Point };\n zoomBy: { factor: number; center?: Point };\n setMinZoom: { minZoom: number };\n setMaxZoom: { maxZoom: number };\n setDragThreshold: { dragThreshold: number };\n setAutoPanOptions: {\n autoPanOnDrag?: boolean;\n autoPanThreshold?: number;\n autoPanSpeed?: number;\n };\n updateSettings: Partial<FlowRuntimeSettings>;\n configure: Partial<FlowStoreOptions>;\n bumpConfigRevision: undefined;\n bumpRoutingRevision: undefined;\n setTranslateExtent: { extent: [Point, Point] | null };\n setNodeExtent: { extent: [Point, Point] | null };\n updateViewportSize: Size & { preserveCenter?: boolean };\n fitView: FitViewOptions | undefined;\n pushViewport: undefined;\n popViewport: undefined;\n panStart: Point;\n pan: Point;\n panEnd: undefined;\n panCancel: undefined;\n setCanvasState: { state: CanvasState };\n connectionStart: {\n sourceId: string;\n sourcePort: string | null;\n position: Point;\n active?: boolean;\n reconnectingEdgeId?: string | null;\n reconnectingEnd?: 'source' | 'target' | null;\n preview?: boolean;\n };\n connectionMove: {\n position: Point;\n targetId?: string | null;\n targetPort?: string | null;\n isValid?: boolean;\n invalidReason?: string;\n active?: boolean;\n };\n connectionEnd: { target?: ConnectEndTarget; reconnectedEdgeId?: string } | undefined;\n cancelConnection: undefined;\n setConnectionClickStartHandle: { nodeId: string; port: string | null } | null;\n resizeStart: { id: string; handle: ResizeHandle } & TransactionMetadata;\n resizeMove: Point;\n resizeEnd: undefined;\n resizeCancel: undefined;\n paneClicked: FlowPaneGestureEvent;\n paneContextMenu: FlowPaneGestureEvent;\n entityClicked: FlowEntityGestureEvent;\n entityDoubleClicked: FlowEntityGestureEvent;\n entityContextMenu: FlowEntityGestureEvent;\n reconnectEdge: {\n edgeId: string;\n newSourceId?: string;\n newTargetId?: string;\n newSourcePort?: string | null;\n newTargetPort?: string | null;\n } & TransactionMetadata;\n setMode: { mode: string };\n setSnapToGrid: { enabled: boolean; grid?: [number, number] };\n setSnapLines: { enabled: boolean; threshold?: number; spacing?: boolean };\n setColorMode: { colorMode: FlowColorMode };\n moveNodes: { direction: Point; factor?: number } & TransactionMetadata;\n requestLayout: { algorithm?: string };\n applyLayoutResult: {\n positions: Map<string, { x: number; y: number }>;\n edgeLabelPositions?: Map<string, { x: number; y: number }>;\n } & TransactionMetadata;\n updateMeasurements: { measurements: Array<{ id: string; rect: Rect; origin?: Point }>; derivedOnly?: boolean };\n removeMeasurements: { ids: string[]; derivedOnly?: boolean };\n bakeLabelPositions: { positions: Map<string, Point> } & TransactionMetadata;\n reportError: FlowErrorEvent;\n};\n\nexport type FlowNodePatch = Partial<Omit<FlowNode, 'id' | 'type' | 'parentId'>>;\nexport type FlowEdgePatch = Partial<\n Omit<FlowEdge, 'id' | 'type' | 'sourceId' | 'targetId' | 'sourcePort' | 'targetPort'>\n>;\nexport type FlowNodeUpdater = (node: FlowNode) => FlowNode;\nexport type FlowEdgeUpdater = (edge: FlowEdge) => FlowEdge;\nexport type FlowUpdateNodeEvent = {\n id: string;\n patch?: FlowNodePatch;\n updater?: FlowNodeUpdater;\n} & TransactionMetadata;\nexport type FlowUpdateEdgeEvent = {\n id: string;\n patch?: FlowEdgePatch;\n updater?: FlowEdgeUpdater;\n} & TransactionMetadata;\n\nconst UNDOABLE_EVENT_TYPES = [\n 'createNode',\n 'deleteNode',\n 'updateNode',\n 'updateNodeData',\n 'createEdge',\n 'deleteEdge',\n 'deleteEntities',\n 'updateEdge',\n 'updateEdgeData',\n 'deleteSelected',\n 'reparentNode',\n 'collapseNode',\n 'expandNode',\n 'commitDrag',\n 'resizeEnd',\n 'reconnectEdge',\n 'applyLayoutResult',\n 'bakeLabelPositions',\n 'replaceGraph',\n] as const;\n\ntype UndoableEventType = (typeof UNDOABLE_EVENT_TYPES)[number];\ntype UndoableStoreEvent = {\n type: string;\n transactionId?: string;\n history?: FlowGraphHistoryPolicy;\n [key: string]: any;\n};\ntype UndoableStoreSnapshot = { context: FlowStoreContext };\ntype TransactionMetadata = { transactionId?: string; origin?: string };\n\nexport type FlowGraphRetentionPolicy = 'preserve' | 'reset';\nexport type FlowGraphHistoryPolicy = 'reset' | 'ignore' | 'record';\n\ntype ReplaceGraphMetadata = TransactionMetadata & {\n retention?: FlowGraphRetentionPolicy;\n history?: FlowGraphHistoryPolicy;\n};\n\ntype FlowHistorySnapshot = StoreSnapshot<FlowStoreContext> & {\n past: unknown[];\n future: unknown[];\n};\n\n/**\n * Validate an edge about to be inserted. Returns an actionable error message,\n * or null when the edge is valid. Used by `createEdge` and undo tracking.\n */\nfunction validateNewEdge(\n ctx: { graph: FlowGraph } | FlowStoreContext,\n edge: FlowEdge\n): string | null {\n if (ctx.graph.edges.some((e) => e.id === edge.id)) {\n return (\n `createEdge rejected: an edge with id \"${edge.id}\" already exists. ` +\n `Edge ids must be unique — use reconnectEdge or updateEdgeData to modify the existing edge, or create the edge with a different id.`\n );\n }\n const missing: string[] = [];\n if (!ctx.graph.nodes.some((n) => n.id === edge.sourceId)) {\n missing.push(`source node \"${edge.sourceId}\"`);\n }\n if (!ctx.graph.nodes.some((n) => n.id === edge.targetId)) {\n missing.push(`target node \"${edge.targetId}\"`);\n }\n if (missing.length > 0) {\n return (\n `createEdge rejected: edge \"${edge.id}\" references ${missing.join(' and ')}, ` +\n `which ${\n missing.length === 1 ? 'does' : 'do'\n } not exist in the graph. Create the node(s) first, then the edge.`\n );\n }\n return null;\n}\n\nfunction validateUpdatedNode(previous: FlowNode, next: FlowNode): string | null {\n if (next.id !== previous.id) {\n return `updateNode rejected: node id cannot change from \"${previous.id}\" to \"${next.id}\".`;\n }\n if (next.type !== previous.type) {\n return `updateNode rejected: node \"${previous.id}\" type cannot change.`;\n }\n if (next.parentId !== previous.parentId) {\n return `updateNode rejected: node \"${previous.id}\" parentId must be changed with reparentNode.`;\n }\n return null;\n}\n\nfunction validateUpdatedEdge(previous: FlowEdge, next: FlowEdge): string | null {\n if (next.id !== previous.id) {\n return `updateEdge rejected: edge id cannot change from \"${previous.id}\" to \"${next.id}\".`;\n }\n if (next.type !== previous.type) {\n return `updateEdge rejected: edge \"${previous.id}\" type cannot change.`;\n }\n if (\n next.sourceId !== previous.sourceId ||\n next.targetId !== previous.targetId ||\n next.sourcePort !== previous.sourcePort ||\n next.targetPort !== previous.targetPort\n ) {\n return `updateEdge rejected: edge \"${previous.id}\" endpoints and ports must be changed with reconnectEdge.`;\n }\n return null;\n}\n\n/**\n * Validate a reparent operation. Returns an error message or null when valid.\n * Rejects self-parenting, non-existent parents, and cycles (parentId is a\n * descendant of nodeId).\n */\nfunction reparentProblem(graph: FlowGraph, nodeId: string, parentId: string | null): string | null {\n if (parentId === null) return null;\n if (parentId === nodeId) {\n return `reparentNode rejected: node \"${nodeId}\" cannot be its own parent.`;\n }\n if (!graph.nodes.some((n) => n.id === parentId)) {\n return `reparentNode rejected: parent node \"${parentId}\" does not exist in the graph.`;\n }\n // Walk up from parentId; if we reach nodeId, it's a cycle.\n const nodeIndex = new Map(graph.nodes.map((n) => [n.id, n]));\n let candidate: string | null = parentId;\n const seen = new Set<string>();\n while (candidate && !seen.has(candidate)) {\n if (candidate === nodeId) {\n return `reparentNode rejected: node \"${parentId}\" is a descendant of \"${nodeId}\", which would create a cycle.`;\n }\n seen.add(candidate);\n candidate = nodeIndex.get(candidate)?.parentId ?? null;\n }\n return null;\n}\n\n/** Drop hover/highlight/collapse references to entities that no longer exist. */\nfunction pruneVisualState(draft: FlowStoreContext, deletedIds: string[]): void {\n const connection = draft.connection;\n const pending = draft.connectionClickStartHandle;\n if (\n (connection && deletedIds.some((id) =>\n id === connection.sourceId ||\n (connection.sourcePort !== null && id === `${connection.sourceId}:${connection.sourcePort}`) ||\n id === connection.targetId ||\n (connection.targetId !== null && connection.targetPort !== null &&\n id === `${connection.targetId}:${connection.targetPort}`) ||\n id === connection.reconnectingEdgeId\n )) ||\n (pending && deletedIds.some((id) =>\n id === pending.nodeId ||\n (pending.port !== null && id === `${pending.nodeId}:${pending.port}`)\n ))\n ) {\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n if (draft.canvasState === 'connecting') draft.canvasState = 'idle';\n }\n for (const id of deletedIds) {\n draft.hoveredEntityIds.delete(id);\n draft.collapsedNodeIds.delete(id);\n }\n for (const [kind, bucket] of draft.highlights) {\n for (const id of deletedIds) {\n bucket.delete(id);\n }\n if (bucket.size === 0) draft.highlights.delete(kind);\n }\n}\n\nfunction portAddressableIds(node: FlowNode): string[] {\n const ids = new Set<string>();\n for (const port of node.ports ?? []) {\n ids.add(`${node.id}:${port.name}`);\n const explicitId = (port as { id?: string }).id;\n if (explicitId) ids.add(explicitId);\n }\n return [...ids];\n}\n\nfunction graphAddressableIds(graph: FlowGraph): Set<string> {\n return new Set([\n ...graph.nodes.flatMap((node) => [node.id, ...portAddressableIds(node)]),\n ...graph.edges.map((edge) => edge.id),\n ]);\n}\n\nfunction pruneDeletedAddressables(\n draft: FlowStoreContext,\n deletedIds: string[],\n): void {\n const deleted = new Set(deletedIds);\n for (const id of deleted) {\n draft.selection.delete(id);\n draft.measurements.delete(id);\n draft.derivedPortMeasurements.delete(id);\n }\n if (draft.focusedEntityId && deleted.has(draft.focusedEntityId)) {\n draft.focusedEntityId = null;\n }\n pruneVisualState(draft, deletedIds);\n}\n\nfunction invalidatePathsForNodeGeometry(\n draft: FlowStoreContext,\n changedNodeIds: ReadonlySet<string>,\n topologyNodes: readonly FlowNode[] = draft.graph.nodes,\n): void {\n const affectedNodeIds = withDerivedGroupAncestors(\n topologyNodes,\n changedNodeIds,\n );\n for (const edge of draft.graph.edges) {\n if (\n affectedNodeIds.has(edge.sourceId) ||\n affectedNodeIds.has(edge.targetId)\n ) {\n invalidateAuthoritativeEdgePath(edge);\n }\n }\n}\n\nfunction isUndoableEventType(type: string): type is UndoableEventType {\n return (UNDOABLE_EVENT_TYPES as readonly string[]).includes(type);\n}\n\n/**\n * Movement plan for one drag/arrow-key step, computed entirely on the plain\n * pre-transition context (draft proxy reads are ~10× slower than plain reads\n * and movement runs once per pointer frame). Deltas are keyed by array index\n * so the draft pass touches only the moved entities.\n *\n * Descendants of a moved node ride along with the parent's applied\n * (post-clamp) delta — minimal subflow semantics: positions stay absolute;\n * relative coordinate spaces and parent-extent clamping are tracked in\n * REFRAME.md. Descendants that move on their own (selected + draggable) are\n * skipped together with their subtrees. parentId cycles are tolerated.\n */\ntype MovementPlan = {\n nodeDeltasByIndex: Map<number, Point>;\n edgeDeltasByIndex: Map<number, Point>;\n labelDeltasByIndex: Map<number, Point>;\n};\n\ntype MovementTopology = {\n nodeIndices: Map<string, number>;\n edgeIndices: Map<string, number>;\n childrenByParent: Map<string, string[]> | null;\n nodeCount: number;\n edgeCount: number;\n};\n\nfunction createMovementTopology(\n nodes: readonly FlowNode[],\n edges: readonly FlowEdge[],\n): MovementTopology {\n const nodeArray = nodes as FlowNode[];\n const edgeArray = edges as FlowEdge[];\n const nodeIndices = indexNodePositions(nodeArray);\n const edgeIndices = indexEdgePositions(edgeArray);\n const children = indexChildren(nodeArray);\n const childrenByParent = children.size\n ? new Map(\n [...children].map(([parentId, childNodes]) => [\n parentId,\n childNodes.map((node) => node.id),\n ]),\n )\n : null;\n return {\n nodeIndices,\n edgeIndices,\n childrenByParent,\n nodeCount: nodes.length,\n edgeCount: edges.length,\n };\n}\n\nexport function planNodeMovement(\n ctx: FlowStoreContext,\n dx: number,\n dy: number,\n options: { includeLabels?: boolean } = {},\n topology?: MovementTopology,\n): MovementPlan | null {\n const nodes = ctx.graph.nodes as FlowNode[];\n const edges = ctx.graph.edges as FlowEdge[];\n const usableTopology =\n topology?.nodeCount === nodes.length && topology.edgeCount === edges.length\n ? topology\n : createMovementTopology(nodes, edges);\n const nodeAt = (id: string) => {\n const index = usableTopology.nodeIndices.get(id);\n const node = index === undefined ? undefined : nodes[index];\n return node?.id === id ? node : undefined;\n };\n const edgeAt = (id: string) => {\n const index = usableTopology.edgeIndices.get(id);\n const edge = index === undefined ? undefined : edges[index];\n return edge?.id === id ? edge : undefined;\n };\n\n const movingNodeIds = new Set<string>();\n const labelEdgeIds = new Set<string>();\n for (const id of ctx.selection) {\n const node = nodeAt(id);\n if (node) {\n if (node.draggable !== false) movingNodeIds.add(id);\n continue;\n }\n if (options.includeLabels) {\n const edge = edgeAt(id);\n if (edge && edge.draggable !== false && edge.label) labelEdgeIds.add(id);\n }\n }\n if (movingNodeIds.size === 0 && labelEdgeIds.size === 0) return null;\n\n const childrenByParent = usableTopology.childrenByParent;\n // Hierarchy-only operations need current node objects because parents may\n // themselves have moved earlier in the gesture. Flat graphs avoid this map.\n const hierarchyNodeIndex = childrenByParent ? indexNodes(nodes) : null;\n\n const deltasById = new Map<string, Point>();\n for (const id of movingNodeIds) {\n const node = nodeAt(id)!;\n const oldDx = node.dx ?? 0;\n const oldDy = node.dy ?? 0;\n let newDx = oldDx + dx;\n let newDy = oldDy + dy;\n\n if (ctx.nodeExtent) {\n const nodeSize = resolvedSize(node);\n const clampedX = Math.max(\n ctx.nodeExtent[0].x,\n Math.min(node.x + newDx, ctx.nodeExtent[1].x - nodeSize.width)\n );\n const clampedY = Math.max(\n ctx.nodeExtent[0].y,\n Math.min(node.y + newDy, ctx.nodeExtent[1].y - nodeSize.height)\n );\n newDx = clampedX - node.x;\n newDy = clampedY - node.y;\n }\n\n // Fixed-layout parents may clamp their children to the child area (per\n // axis). Derived parents never clamp — their bounds follow the children.\n const parent = node.parentId\n ? hierarchyNodeIndex?.get(node.parentId)\n : undefined;\n if (parent?.group?.type === 'fixed') {\n const axes = parent.group.clampChildren ?? 'none';\n if (axes !== 'none') {\n const area = fixedGroupGeometry(\n {\n x: parent.x + (parent.dx ?? 0),\n y: parent.y + (parent.dy ?? 0),\n width: parent.style?.customWidth ?? parent.width,\n height: parent.style?.customHeight ?? parent.height,\n },\n parent.group.contentSize ?? { width: 0, height: 0 },\n parent.group\n ).childArea;\n const { width: nodeWidth, height: nodeHeight } = resolvedSize(node);\n if (axes === 'x' || axes === 'both') {\n const clampedX = Math.max(\n area.x,\n Math.min(node.x + newDx, area.x + area.width - nodeWidth)\n );\n newDx = clampedX - node.x;\n }\n if (axes === 'y' || axes === 'both') {\n const clampedY = Math.max(\n area.y,\n Math.min(node.y + newDy, area.y + area.height - nodeHeight)\n );\n newDy = clampedY - node.y;\n }\n }\n }\n\n if (ctx.constrainNodeMovement) {\n const adjusted = ctx.constrainNodeMovement(\n node,\n { x: node.x + newDx, y: node.y + newDy },\n ctx\n );\n if (adjusted) {\n newDx = adjusted.x - node.x;\n newDy = adjusted.y - node.y;\n }\n }\n\n const applied = { x: newDx - oldDx, y: newDy - oldDy };\n if (applied.x === 0 && applied.y === 0) continue;\n deltasById.set(id, applied);\n if (childrenByParent) {\n collectDescendantDeltas(childrenByParent, id, applied, movingNodeIds, deltasById);\n }\n }\n\n const nodeDeltasByIndex = new Map<number, Point>();\n if (deltasById.size > 0) {\n for (const [id, delta] of deltasById) {\n const index = usableTopology.nodeIndices.get(id);\n if (index !== undefined && nodes[index]?.id === id) {\n nodeDeltasByIndex.set(index, delta);\n }\n }\n }\n const edgeDeltasByIndex = new Map<number, Point>();\n const labelDeltasByIndex = new Map<number, Point>();\n if (childrenByParent && deltasById.size > 0) {\n for (let i = 0; i < edges.length; i++) {\n const edge = edges[i];\n const carriesWaypoints = !!edge.waypoints?.length;\n const carriesFixedLabel =\n !!edge.label && (edge.labelAnchor ?? ctx.labelAnchor) === 'fixed';\n if (!carriesWaypoints && !carriesFixedLabel) continue;\n if (\n !deltasById.has(edge.sourceId) ||\n !deltasById.has(edge.targetId)\n ) {\n continue;\n }\n\n const ownerId = getEdgeOwnerFromIndex(edge, hierarchyNodeIndex!);\n const ownerDelta = ownerId ? deltasById.get(ownerId) : undefined;\n if (!ownerDelta) continue;\n edgeDeltasByIndex.set(i, ownerDelta);\n if (carriesFixedLabel) labelDeltasByIndex.set(i, ownerDelta);\n }\n }\n if (labelEdgeIds.size > 0) {\n for (const id of labelEdgeIds) {\n const index = usableTopology.edgeIndices.get(id);\n if (index === undefined || edges[index]?.id !== id || labelDeltasByIndex.has(index)) {\n continue;\n }\n labelDeltasByIndex.set(index, { x: dx, y: dy });\n }\n }\n if (\n nodeDeltasByIndex.size === 0 &&\n edgeDeltasByIndex.size === 0 &&\n labelDeltasByIndex.size === 0\n ) {\n return null;\n }\n return { nodeDeltasByIndex, edgeDeltasByIndex, labelDeltasByIndex };\n}\n\nfunction collectDescendantDeltas(\n childrenByParent: Map<string, string[]>,\n parentId: string,\n delta: Point,\n movingIds: Set<string>,\n out: Map<string, Point>,\n visited: Set<string> = new Set([parentId])\n): void {\n const children = childrenByParent.get(parentId);\n if (!children) return;\n for (const childId of children) {\n if (visited.has(childId) || movingIds.has(childId)) continue;\n visited.add(childId);\n if (!out.has(childId)) out.set(childId, delta);\n collectDescendantDeltas(childrenByParent, childId, delta, movingIds, out, visited);\n }\n}\n\nfunction applyMovementPlan(draft: FlowStoreContext, plan: MovementPlan): void {\n for (const [index, delta] of plan.nodeDeltasByIndex) {\n const node = draft.graph.nodes[index];\n if (!node) continue;\n node.dx = (node.dx ?? 0) + delta.x;\n node.dy = (node.dy ?? 0) + delta.y;\n }\n for (const [index, delta] of plan.edgeDeltasByIndex) {\n const edge = draft.graph.edges[index];\n if (!edge) continue;\n edge.dx = (edge.dx ?? 0) + delta.x;\n edge.dy = (edge.dy ?? 0) + delta.y;\n }\n for (const [index, delta] of plan.labelDeltasByIndex) {\n const edge = draft.graph.edges[index];\n if (!edge?.label) continue;\n edge.label.dx = (edge.label.dx ?? 0) + delta.x;\n edge.label.dy = (edge.label.dy ?? 0) + delta.y;\n }\n}\n\n/**\n * Remove nodes from the draft graph and resolve connected edges according to\n * the configured `onDeleteNodes` strategy. Shared by `deleteNode` and\n * `deleteSelected` so both events always agree on edge handling.\n *\n * `edgesToDelete` are edge ids that must be removed regardless of strategy\n * (explicitly selected/targeted edges).\n */\nfunction applyNodeDeletionStrategy(\n draft: FlowStoreContext,\n nodesToDelete: Set<string>,\n edgesToDelete: Set<string>,\n strategy: NonNullable<FlowStoreOptions['onDeleteNodes']>\n): void {\n if (typeof strategy === 'function') {\n const result = strategy(\n {\n ...draft.graph,\n nodes: [...draft.graph.nodes],\n edges: [...draft.graph.edges],\n } as FlowGraph,\n nodesToDelete\n );\n draft.graph.nodes = result.nodes as typeof draft.graph.nodes;\n draft.graph.edges = (result.edges as typeof draft.graph.edges).filter(\n (edge) => !edgesToDelete.has(edge.id)\n );\n return;\n }\n\n nodesToDelete = getNodeIdsWithDescendants(draft.graph.nodes, nodesToDelete);\n\n draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));\n\n if (strategy === 'retarget') {\n const kept: typeof draft.graph.edges = [];\n for (const edge of draft.graph.edges) {\n if (edgesToDelete.has(edge.id)) continue;\n const srcDel = nodesToDelete.has(edge.sourceId);\n const tgtDel = nodesToDelete.has(edge.targetId);\n if (srcDel && tgtDel) continue;\n if (srcDel) {\n edge.sourceId = edge.targetId;\n invalidateAuthoritativeEdgePath(edge);\n } else if (tgtDel) {\n edge.targetId = edge.sourceId;\n invalidateAuthoritativeEdgePath(edge);\n }\n kept.push(edge);\n }\n draft.graph.edges = kept;\n return;\n }\n\n // cascade (default)\n draft.graph.edges = draft.graph.edges.filter(\n (e) =>\n !edgesToDelete.has(e.id) && !nodesToDelete.has(e.sourceId) && !nodesToDelete.has(e.targetId)\n );\n}\n\nfunction hasSelectedEntitiesToDelete(ctx: FlowStoreContext): boolean {\n for (const id of ctx.selection) {\n if (\n ctx.graph.nodes.some((node) => node.id === id) ||\n ctx.graph.edges.some((edge) => edge.id === id)\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction shouldTrackUndoEvent(event: UndoableStoreEvent, snapshot: UndoableStoreSnapshot): boolean {\n if (!isUndoableEventType(event.type)) {\n return false;\n }\n\n const ctx = snapshot.context;\n\n switch (event.type) {\n case 'createNode':\n return !ctx.graph.nodes.some((node) => node.id === event.node.id);\n case 'createEdge':\n return validateNewEdge(ctx, event.edge) === null;\n case 'deleteNode':\n return ctx.graph.nodes.some((node) => node.id === event.id);\n case 'deleteEdge':\n return ctx.graph.edges.some((edge) => edge.id === event.id);\n case 'deleteEntities':\n return (\n (event.nodeIds ?? []).some((id: string) =>\n ctx.graph.nodes.some((node) => node.id === id)\n ) ||\n (event.edgeIds ?? []).some((id: string) => ctx.graph.edges.some((edge) => edge.id === id))\n );\n case 'updateNodeData': {\n const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);\n return (\n !!node && Object.entries(event.data).some(([key, value]) => node.data?.[key] !== value)\n );\n }\n case 'updateEdgeData': {\n const edge = ctx.graph.edges.find((candidate) => candidate.id === event.id);\n return (\n !!edge && Object.entries(event.data).some(([key, value]) => edge.data?.[key] !== value)\n );\n }\n case 'deleteSelected':\n return hasSelectedEntitiesToDelete(ctx);\n case 'replaceGraph':\n return (\n event.history !== 'ignore' &&\n event.history !== 'reset' &&\n JSON.stringify(ctx.graph) !== JSON.stringify(event.graph)\n );\n case 'reparentNode': {\n const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);\n return !!node && (node.parentId ?? null) !== event.parentId;\n }\n case 'commitDrag':\n return (\n ctx.graph.nodes.some((node) => node.dx || node.dy) ||\n ctx.graph.edges.some((edge) => edge.dx || edge.dy || edge.label?.dx || edge.label?.dy)\n );\n case 'resizeEnd': {\n if (!ctx.resizingEntityId || !ctx.resizeCorners) return false;\n const node = ctx.graph.nodes.find((candidate) => candidate.id === ctx.resizingEntityId);\n const bounds = resizeBoundsFromDraft(ctx.resizeCorners);\n if (!node || !bounds) return false;\n const size = resolvedSize(node);\n return (\n bounds.x !== node.x + (node.dx ?? 0) ||\n bounds.y !== node.y + (node.dy ?? 0) ||\n bounds.width !== size.width ||\n bounds.height !== size.height\n );\n }\n case 'reconnectEdge': {\n const edge = ctx.graph.edges.find((candidate) => candidate.id === event.edgeId);\n if (!edge) {\n return false;\n }\n\n return (\n (event.newSourceId !== undefined && event.newSourceId !== edge.sourceId) ||\n (event.newTargetId !== undefined && event.newTargetId !== edge.targetId) ||\n (event.newSourcePort !== undefined && event.newSourcePort !== edge.sourcePort) ||\n (event.newTargetPort !== undefined && event.newTargetPort !== edge.targetPort)\n );\n }\n case 'applyLayoutResult':\n return event.positions.size > 0 || (event.edgeLabelPositions?.size ?? 0) > 0;\n case 'bakeLabelPositions':\n return event.positions.size > 0;\n default:\n return true;\n }\n}\n\nconst resetGraphReplacementHistory: StoreExtension<\n FlowStoreContext,\n FlowEventPayloadMap & { undo: null; redo: null },\n Record<never, never>,\n ExtractEvents<FlowEmittedPayloadMap>\n> = (logic) => ({\n ...logic,\n transition: (snapshot, event) => {\n const result = logic.transition(snapshot, event);\n if (event.type !== 'replaceGraph' || event.history !== 'reset') {\n return result;\n }\n const [next, effects] = result;\n const nextWithHistory = next as FlowHistorySnapshot;\n return [{ ...nextWithHistory, past: [], future: [] }, effects];\n },\n});\n\n/**\n * Snapshot a (possibly drafted) graph into plain data for emission — immer\n * drafts are revoked before listeners run. Plain values (e.g. right after\n * `draft.graph = event.graph`) pass through untouched.\n */\nfunction snapshotGraph(graph: FlowStoreContext['graph']): FlowGraph {\n return (isDraft(graph) ? current(graph) : graph) as FlowGraph;\n}\n\nfunction graphWithoutTransientOffsets(graph: FlowGraph): FlowGraph {\n return {\n ...graph,\n nodes: graph.nodes.map((source) => {\n const node = { ...source };\n delete node.dx;\n delete node.dy;\n return node;\n }),\n edges: graph.edges.map((source) => {\n const edge = { ...source };\n delete edge.dx;\n delete edge.dy;\n if (source.label) {\n edge.label = { ...source.label };\n delete edge.label.dx;\n delete edge.label.dy;\n }\n return edge;\n }),\n };\n}\n\nfunction restoreHistoryContext(\n currentContext: FlowStoreContext,\n historicalContext: FlowStoreContext\n): FlowStoreContext {\n const graph = graphWithoutTransientOffsets(historicalContext.graph);\n const entityIds = new Set([\n ...graph.nodes.map((node) => node.id),\n ...graph.edges.map((edge) => edge.id),\n ]);\n const addressableIds = graphAddressableIds(graph);\n const filterIds = (ids: Iterable<string>) => new Set([...ids].filter((id) => entityIds.has(id)));\n const collapsedNodeIds = filterIds(historicalContext.collapsedNodeIds);\n const selection = filterIds(currentContext.selection);\n for (const id of selection) {\n if (\n [...collapsedNodeIds].some(\n (ancestorId) => id !== ancestorId && isDescendantOf(graph.nodes, id, ancestorId)\n )\n ) {\n selection.delete(id);\n }\n }\n const highlights = new Map<string, Map<string, unknown>>();\n for (const [kind, entries] of currentContext.highlights) {\n const filtered = new Map([...entries].filter(([id]) => entityIds.has(id)));\n if (filtered.size > 0) highlights.set(kind, filtered);\n }\n\n return {\n ...currentContext,\n graph,\n parentNodeId:\n currentContext.parentNodeId && entityIds.has(currentContext.parentNodeId)\n ? currentContext.parentNodeId\n : null,\n selection,\n hoveredEntityIds: filterIds(currentContext.hoveredEntityIds),\n collapsedNodeIds,\n highlights,\n focusedEntityId:\n currentContext.focusedEntityId && entityIds.has(currentContext.focusedEntityId)\n ? currentContext.focusedEntityId\n : null,\n measurements: new Map([...currentContext.measurements].filter(([id]) => entityIds.has(id))),\n derivedPortMeasurements: new Map(\n [...currentContext.derivedPortMeasurements].filter(([id]) =>\n addressableIds.has(id),\n ),\n ),\n layoutAnimation: { status: 'idle', offsets: new Map() },\n canvasState: 'idle',\n draggedEntityId: null,\n dragRevision: 0,\n selectionBox: null,\n selectionBoxBase: null,\n connection: null,\n connectionClickStartHandle: null,\n panOrigin: null,\n panViewportOrigin: null,\n resizingEntityId: null,\n resizeHandle: null,\n resizeCorners: null,\n };\n}\n\n/** Copy a (possibly drafted) viewport into plain data for emission. */\nfunction plainViewport(viewport: Viewport): Viewport {\n return { x: viewport.x, y: viewport.y, zoom: viewport.zoom };\n}\n\nfunction entityPositions(\n graph: FlowStoreContext['graph'],\n ids: Iterable<string>,\n movement?: MovementPlan,\n topology?: MovementTopology,\n): Record<string, Point> {\n const positions: Record<string, Point> = {};\n const usableTopology =\n topology?.nodeCount === graph.nodes.length &&\n topology.edgeCount === graph.edges.length\n ? topology\n : null;\n const nodes = usableTopology ? null : indexNodes(graph.nodes as FlowNode[]);\n const edges = usableTopology ? null : indexEdges(graph.edges as FlowEdge[]);\n const nodeAt = (id: string) => {\n const index = usableTopology?.nodeIndices.get(id);\n const node = index === undefined ? nodes?.get(id) : graph.nodes[index];\n return node?.id === id ? node : undefined;\n };\n const edgeAt = (id: string) => {\n const index = usableTopology?.edgeIndices.get(id);\n const edge = index === undefined ? edges?.get(id) : graph.edges[index];\n return edge?.id === id ? edge : undefined;\n };\n const nodeDeltas = new Map<string, Point>();\n const labelDeltas = new Map<string, Point>();\n if (movement) {\n for (const [index, delta] of movement.nodeDeltasByIndex) {\n const node = graph.nodes[index];\n if (node) nodeDeltas.set(node.id, delta);\n }\n for (const [index, delta] of movement.labelDeltasByIndex) {\n const edge = graph.edges[index];\n if (edge) labelDeltas.set(edge.id, delta);\n }\n }\n for (const id of ids) {\n const node = nodeAt(id);\n if (node) {\n const delta = nodeDeltas.get(id);\n positions[id] = {\n x: node.x + (node.dx ?? 0) + (delta?.x ?? 0),\n y: node.y + (node.dy ?? 0) + (delta?.y ?? 0),\n };\n continue;\n }\n const edge = edgeAt(id);\n if (edge?.label) {\n const delta = labelDeltas.get(id);\n positions[id] = {\n x: edge.label.x + (edge.label.dx ?? 0) + (delta?.x ?? 0),\n y: edge.label.y + (edge.label.dy ?? 0) + (delta?.y ?? 0),\n };\n }\n }\n return positions;\n}\n\nfunction resizeBoundsFromDraft(corners: [Point, Point] | null): Rect | null {\n if (!corners) return null;\n const [a, b] = corners;\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n };\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, value));\n}\n\nexport function clampResizeMovingPoint(\n node: FlowNode,\n handle: ResizeHandle | null,\n anchor: Point,\n moving: Point\n): Point {\n // Free by default: no implicit minimum. Explicit constraints via node.resize.min.\n const minWidth = node.resize?.min?.width ?? 0;\n const minHeight = node.resize?.min?.height ?? 0;\n const maxWidth = node.resize?.max?.width ?? Number.POSITIVE_INFINITY;\n const maxHeight = node.resize?.max?.height ?? Number.POSITIVE_INFINITY;\n const current = resolvedSize(node);\n const aspect =\n typeof node.resize?.aspect === 'number' && node.resize.aspect > 0\n ? node.resize.aspect\n : node.resize?.aspect === true && current.height > 0\n ? current.width / current.height\n : null;\n\n const rawDx = moving.x - anchor.x;\n const rawDy = moving.y - anchor.y;\n const sx = rawDx < 0 ? -1 : 1;\n const sy = rawDy < 0 ? -1 : 1;\n let width = clamp(Math.abs(rawDx), minWidth, maxWidth);\n let height = clamp(Math.abs(rawDy), minHeight, maxHeight);\n\n if (aspect) {\n if (handle === 'left' || handle === 'right') {\n height = width / aspect;\n } else if (handle === 'top' || handle === 'bottom') {\n width = height * aspect;\n } else if (width / height > aspect) {\n height = width / aspect;\n } else {\n width = height * aspect;\n }\n width = clamp(width, minWidth, maxWidth);\n height = clamp(height, minHeight, maxHeight);\n }\n\n return {\n x: anchor.x + sx * width,\n y: anchor.y + sy * height,\n };\n}\n\nfunction createEventObject<TEvent extends object>(\n type: string,\n event: TEvent | undefined\n): FlowEventObject {\n return { type, ...(event ?? {}) };\n}\n\nfunction isExplicitlyVisibleNode(node: FlowNode): boolean {\n return !node.hidden;\n}\n\n/**\n * A collapsed group hides its descendants: they are not selectable and do not\n * contribute to any group's derived selection geometry. Mirrors the engine's\n * `isHiddenByCollapsedAncestor`.\n */\nfunction isHiddenByCollapsedAncestor(ctx: FlowStoreContext, nodeId: string): boolean {\n if (ctx.collapsedNodeIds.size === 0) return false;\n const nodeIndex = indexNodes(ctx.graph.nodes as FlowNode[]);\n let parentId = nodeIndex.get(nodeId)?.parentId;\n while (parentId) {\n if (ctx.collapsedNodeIds.has(parentId)) return true;\n parentId = nodeIndex.get(parentId)?.parentId;\n }\n return false;\n}\n\nfunction isDescendantOf(nodes: readonly FlowNode[], nodeId: string, ancestorId: string): boolean {\n const byId = new Map(nodes.map((node) => [node.id, node]));\n let parentId = byId.get(nodeId)?.parentId;\n while (parentId) {\n if (parentId === ancestorId) return true;\n parentId = byId.get(parentId)?.parentId;\n }\n return false;\n}\n\nfunction setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const value of a) if (!b.has(value)) return false;\n return true;\n}\n\nfunction isExplicitlyVisibleEdge(edge: FlowEdge, nodes: readonly FlowNode[]): boolean {\n if (edge.hidden) return false;\n const source = nodes.find((node) => node.id === edge.sourceId);\n const target = nodes.find((node) => node.id === edge.targetId);\n return !!source && !!target && isExplicitlyVisibleNode(source) && isExplicitlyVisibleNode(target);\n}\n\n/**\n * Entities captured by a box-select rectangle. Node and edge-label membership\n * is decided by `ctx.boxSelectionTest` when set,\n * otherwise by the built-in `selectionMode` (partial = any overlap via\n * `rectsIntersect`, full = fully contained via `rectContains`). Edge paths are\n * never marquee targets; an edge without a label cannot be box-selected.\n */\nfunction entitiesInBox(ctx: FlowStoreContext, rect: Rect): Set<string> {\n const ids = new Set<string>();\n const builtinFull = !ctx.boxSelectionTest && ctx.selectionMode === 'full';\n const test: BoxSelectionTest =\n ctx.boxSelectionTest ?? (builtinFull ? rectContains : rectsIntersect);\n const nodes = ctx.graph.nodes as FlowNode[];\n\n for (const node of nodes) {\n if (!isExplicitlyVisibleNode(node)) continue;\n if (isHiddenByCollapsedAncestor(ctx, node.id)) continue;\n if (test(rect, nodeSelectionBounds(ctx, node))) ids.add(node.id);\n }\n\n for (const edge of ctx.graph.edges as FlowEdge[]) {\n if (!isExplicitlyVisibleEdge(edge, nodes)) continue;\n if (!edge.label) continue;\n const labelBounds = resolvedEdgeLabelBounds(edge, ctx.measurements.get(edge.id))!;\n if (test(rect, labelBounds)) ids.add(edge.id);\n }\n\n return ids;\n}\n\nfunction nodeSelectionBounds(\n ctx: FlowStoreContext,\n node: FlowNode,\n visiting = new Set<string>(),\n): Rect {\n if (node.selectionBounds) return resolvedSelectionBounds(node);\n if (!node.group || visiting.has(node.id)) return resolvedBounds(node);\n return groupGeometryForSelection(ctx, node, visiting).contentBounds;\n}\n\nfunction groupGeometryForSelection(\n ctx: FlowStoreContext,\n node: FlowNode,\n visiting: ReadonlySet<string>,\n): GroupGeometry {\n if (node.group!.type === 'fixed') {\n return fixedGroupGeometry(\n resolvedBounds(node),\n node.group!.contentSize ?? { width: 0, height: 0 },\n node.group!,\n );\n }\n\n const nextVisiting = new Set(visiting).add(node.id);\n let childrenBounds: Rect | null = null;\n const addBounds = (bounds: Rect) => {\n if (!childrenBounds) {\n childrenBounds = bounds;\n return;\n }\n const x = Math.min(childrenBounds.x, bounds.x);\n const y = Math.min(childrenBounds.y, bounds.y);\n const right = Math.max(\n childrenBounds.x + childrenBounds.width,\n bounds.x + bounds.width,\n );\n const bottom = Math.max(\n childrenBounds.y + childrenBounds.height,\n bounds.y + bounds.height,\n );\n childrenBounds = { x, y, width: right - x, height: bottom - y };\n };\n\n for (const child of ctx.graph.nodes as FlowNode[]) {\n if (child.parentId !== node.id || !isExplicitlyVisibleNode(child)) continue;\n if (isHiddenByCollapsedAncestor(ctx, child.id)) continue;\n addBounds(\n child.group && !nextVisiting.has(child.id)\n ? groupGeometryForSelection(ctx, child, nextVisiting).bounds\n : resolvedBounds(child),\n );\n }\n const nodeIndex = indexNodes(ctx.graph.nodes as FlowNode[]);\n for (const edge of ctx.graph.edges as FlowEdge[]) {\n if (edge.hidden || !edge.label) continue;\n if (edge.sourceId === node.id && edge.targetId === node.id) continue;\n if (getEdgeOwnerFromIndex(edge, nodeIndex) !== node.id) continue;\n const labelBounds = resolvedEdgeLabelBounds(\n edge,\n ctx.measurements.get(edge.id),\n );\n if (labelBounds) addBounds(labelBounds);\n }\n\n return deriveGroupGeometry(\n resolvedSize(node),\n childrenBounds,\n node.group!,\n { x: node.x + (node.dx ?? 0), y: node.y + (node.dy ?? 0) },\n );\n}\n\nfunction getMode(profile: FlowProfile, mode: string): string {\n return profile.modes[mode] ? mode : profile.defaultMode;\n}\n\nfunction setModeTransition(\n profile: FlowProfile\n): FlowTransition<{ type: 'setMode'; mode: string }> {\n return (ctx, event) =>\n produce(ctx, (draft) => {\n draft.mode = getMode(profile, event.mode);\n });\n}\n\nfunction dispatchProfile<TEvent extends FlowEventObject>(\n profile: FlowProfile,\n ctx: FlowStoreContext,\n event: TEvent,\n enqueue: unknown,\n fallback?: FlowTransition<TEvent>\n): FlowStoreContext {\n const mode = getMode(profile, ctx.mode);\n const transition = profile.modes[mode]?.on?.[event.type] ?? profile.on?.[event.type] ?? fallback;\n\n if (!transition) {\n return ctx;\n }\n\n return transition(ctx, event, enqueue);\n}\n\nexport function createFlowStore(\n initialGraph: FlowGraph = {\n nodes: [],\n edges: [],\n direction: 'down',\n },\n options: FlowStoreOptions = {}\n) {\n const validatedInitialGraph = validateAndCloneGraph(initialGraph);\n let profile = options.profile ?? defaultFlowProfile;\n const initialMode = getMode(profile, options.mode ?? profile.defaultMode);\n const initialContext: FlowStoreContext = {\n graph: validatedInitialGraph,\n appearances: options.appearances,\n parentNodeId: null,\n depth: null,\n viewport: createViewport(),\n viewportSize: { width: 0, height: 0 },\n fitFrame: null,\n viewportStack: [],\n minZoom: options.minZoom ?? 0.1,\n maxZoom: options.maxZoom ?? 4,\n translateExtent: options.translateExtent ?? null,\n nodeExtent: options.nodeExtent ?? null,\n selection: new Set<string>(),\n selectionBox: null,\n selectionBoxBase: null,\n boxSelectionTest: options.boxSelectionTest ?? null,\n hoveredEntityIds: new Set<string>(),\n collapsedNodeIds: new Set<string>(),\n highlights: new Map<string, Map<string, unknown>>(),\n focusedEntityId: null,\n measurements: new Map<string, Rect>(),\n derivedPortMeasurements: new Map<string, Rect>(),\n canvasState: 'idle',\n draggedEntityId: null,\n dragRevision: 0,\n dragThreshold: options.dragThreshold ?? 3,\n constrainNodeMovement: options.constrainNodeMovement ?? null,\n autoPanOnDrag: options.autoPanOnDrag ?? true,\n autoPanThreshold: options.autoPanThreshold ?? 40,\n autoPanSpeed: options.autoPanSpeed ?? 15,\n connection: null,\n connectOnClick: options.connectOnClick ?? false,\n connectionDragThreshold: options.connectionDragThreshold ?? options.dragThreshold ?? 3,\n connectionClickStartHandle: null,\n panOrigin: null,\n panViewportOrigin: null,\n viewportAnimation: options.viewportAnimation ?? null,\n resizingEntityId: null,\n resizeHandle: null,\n resizeCorners: null,\n mode: initialMode,\n selectionMode: options.selectionMode ?? 'partial',\n labelAnchor: options.labelAnchor ?? 'fixed',\n configRevision: 0,\n routingRevision: 0,\n snapToGrid: options.snapToGrid ?? false,\n snapGrid: options.snapGrid ?? [10, 10],\n enableSnapLines: options.enableSnapLines ?? false,\n snapThreshold: options.snapThreshold ?? 5,\n enableSpacingGuides: options.enableSpacingGuides ?? false,\n autoLayout: {\n status: 'idle',\n algorithm: null,\n },\n layoutAnimation: {\n status: 'idle',\n offsets: new Map(),\n },\n colorMode: options.colorMode ?? 'system',\n };\n // Node/edge array order is fixed during a drag gesture. Build its topology\n // once at the boundary, then reuse direct indices on every pointer frame.\n let activeDragMovementTopology: MovementTopology | null = null;\n\n const storeWithHistory = createStore<\n FlowStoreContext,\n FlowEventPayloadMap,\n FlowEmittedPayloadMap\n >({\n context: initialContext,\n on: {\n // Graph mutations\n\n createNode: (ctx, event: { node: FlowNode } & TransactionMetadata, enqueue) =>\n produce(ctx, (draft) => {\n if (draft.graph.nodes.some((n) => n.id === event.node.id)) {\n enqueue.emit.error({\n error: new Error(\n `createNode rejected: a node with id \"${event.node.id}\" already exists. ` +\n `Node ids must be unique — use updateNodeData to modify the existing node, or create the node with a different id.`\n ),\n event: createEventObject('createNode', event),\n });\n return;\n }\n draft.graph.nodes.push(event.node);\n invalidatePathsForNodeGeometry(draft, new Set([event.node.id]));\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('createNode', event),\n });\n }),\n\n deleteNode: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>\n produce(ctx, (draft) => {\n const nodesBefore = new Map(\n draft.graph.nodes.map((node) => [node.id, node]),\n );\n const edgeIdsBefore = draft.graph.edges.map((e) => e.id);\n applyNodeDeletionStrategy(\n draft,\n new Set([event.id]),\n new Set(),\n options.onDeleteNodes ?? 'cascade'\n );\n const remainingNodeIds = new Set(draft.graph.nodes.map((node) => node.id));\n const remainingEdgeIds = new Set(draft.graph.edges.map((e) => e.id));\n const deletedNodeIds = [...nodesBefore.keys()].filter(\n (id) => !remainingNodeIds.has(id),\n );\n const deletedNodeIdSet = new Set(deletedNodeIds);\n const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));\n const deletedIds = [...deletedNodeIds, ...deletedEdgeIds];\n const deletedPortIds = deletedNodeIds.flatMap((id) =>\n portAddressableIds(nodesBefore.get(id)!),\n );\n invalidatePathsForNodeGeometry(\n draft,\n deletedNodeIdSet,\n [...nodesBefore.values()],\n );\n pruneDeletedAddressables(draft, [...deletedIds, ...deletedPortIds]);\n enqueue.emit.entitiesDeleted({\n ids: deletedIds,\n event: createEventObject('deleteNode', event),\n });\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('deleteNode', event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('deleteNode', event),\n });\n }),\n\n updateNodeData: (\n ctx,\n event: {\n id: string;\n data: Record<string, unknown>;\n } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const node = draft.graph.nodes.find((n) => n.id === event.id);\n if (node) {\n if (!node.data) node.data = {};\n Object.assign(node.data, event.data);\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('updateNodeData', event),\n });\n }\n }),\n\n updateNode: (ctx, event: FlowUpdateNodeEvent, enqueue) =>\n produce(ctx, (draft) => {\n const index = draft.graph.nodes.findIndex((n) => n.id === event.id);\n if (index < 0) {\n enqueue.emit.error({\n error: new Error(`updateNode rejected: node \"${event.id}\" does not exist.`),\n event: createEventObject('updateNode', event),\n });\n return;\n }\n const previous = current(draft.graph.nodes[index]) as FlowNode;\n const next = event.updater\n ? event.updater(previous)\n : ({ ...previous, ...event.patch } as FlowNode);\n const problem = validateUpdatedNode(previous, next);\n if (problem) {\n enqueue.emit.error({\n error: new Error(problem),\n event: createEventObject('updateNode', event),\n });\n return;\n }\n draft.graph.nodes[index] = { ...next };\n const nextPortIds = new Set(portAddressableIds(next));\n const removedPortIds = portAddressableIds(previous).filter((id) => !nextPortIds.has(id));\n if (removedPortIds.length > 0) {\n const previousSelection = new Set(draft.selection);\n pruneDeletedAddressables(draft, removedPortIds);\n if (!setsEqual(previousSelection, draft.selection)) {\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('updateNode', event),\n });\n }\n }\n if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) {\n draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous, ctx.appearances)));\n const node = draft.graph.nodes[index];\n node.x -= previous.measured?.anchorOffset?.x ?? 0;\n node.y -= previous.measured?.anchorOffset?.y ?? 0;\n delete node.measured;\n draft.measurements.delete(node.id);\n }\n if (nodeEndpointGeometryChanged(previous, next)) {\n invalidatePathsForNodeGeometry(draft, new Set([event.id]));\n }\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('updateNode', event),\n });\n }),\n\n createEdge: (ctx, event: { edge: FlowEdge } & TransactionMetadata, enqueue) =>\n produce(ctx, (draft) => {\n const problem = validateNewEdge(draft, event.edge);\n if (problem) {\n enqueue.emit.error({\n error: new Error(problem),\n event: createEventObject('createEdge', event),\n });\n return;\n }\n draft.graph.edges.push(event.edge);\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('createEdge', event),\n });\n }),\n\n deleteEdge: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>\n produce(ctx, (draft) => {\n draft.graph.edges = draft.graph.edges.filter((e) => e.id !== event.id);\n pruneDeletedAddressables(draft, [event.id]);\n enqueue.emit.entitiesDeleted({\n ids: [event.id],\n event: createEventObject('deleteEdge', event),\n });\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('deleteEdge', event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('deleteEdge', event),\n });\n }),\n\n deleteEntities: (\n ctx,\n event: {\n nodeIds?: string[];\n edgeIds?: string[];\n } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const nodesToDelete = new Set(event.nodeIds ?? []);\n const edgesToDelete = new Set(event.edgeIds ?? []);\n const existingNodes = draft.graph.nodes.filter((node) => nodesToDelete.has(node.id));\n const edgeIdsBefore = draft.graph.edges.map((edge) => edge.id);\n const nodesBefore = new Map(\n draft.graph.nodes.map((node) => [node.id, node]),\n );\n if (existingNodes.length === 0 && edgesToDelete.size === 0) return;\n\n applyNodeDeletionStrategy(\n draft,\n nodesToDelete,\n edgesToDelete,\n options.onDeleteNodes ?? 'cascade'\n );\n\n const remainingNodeIds = new Set(draft.graph.nodes.map((node) => node.id));\n const remainingEdgeIds = new Set(draft.graph.edges.map((edge) => edge.id));\n const deletedNodeIds = [...nodesBefore.keys()].filter(\n (id) => !remainingNodeIds.has(id),\n );\n const deletedNodeIdSet = new Set(deletedNodeIds);\n const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));\n if (deletedNodeIds.length === 0 && deletedEdgeIds.length === 0) return;\n\n const deletedPortIds = deletedNodeIds.flatMap((id) =>\n portAddressableIds(nodesBefore.get(id)!),\n );\n invalidatePathsForNodeGeometry(\n draft,\n deletedNodeIdSet,\n [...nodesBefore.values()],\n );\n pruneDeletedAddressables(draft, [\n ...deletedNodeIds,\n ...deletedEdgeIds,\n ...deletedPortIds,\n ]);\n enqueue.emit.entitiesDeleted({\n ids: [...deletedNodeIds, ...deletedEdgeIds],\n event: createEventObject('deleteEntities', event),\n });\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('deleteEntities', event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('deleteEntities', event),\n });\n }),\n\n updateEdgeData: (\n ctx,\n event: {\n id: string;\n data: Record<string, unknown>;\n } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const edge = draft.graph.edges.find((e) => e.id === event.id);\n if (edge) {\n if (!edge.data) edge.data = {};\n Object.assign(edge.data, event.data);\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('updateEdgeData', event),\n });\n }\n }),\n\n updateEdge: (ctx, event: FlowUpdateEdgeEvent, enqueue) =>\n produce(ctx, (draft) => {\n const index = draft.graph.edges.findIndex((e) => e.id === event.id);\n if (index < 0) {\n enqueue.emit.error({\n error: new Error(`updateEdge rejected: edge \"${event.id}\" does not exist.`),\n event: createEventObject('updateEdge', event),\n });\n return;\n }\n const previous = current(draft.graph.edges[index]) as FlowEdge;\n const next = event.updater\n ? event.updater(previous)\n : ({ ...previous, ...event.patch } as FlowEdge);\n const problem = validateUpdatedEdge(previous, next);\n if (problem) {\n enqueue.emit.error({\n error: new Error(problem),\n event: createEventObject('updateEdge', event),\n });\n return;\n }\n draft.graph.edges[index] = next;\n if (JSON.stringify(previous.label?.appearance) !== JSON.stringify(next.label?.appearance)) {\n if (previous.label) draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous.label, ctx.appearances)));\n draft.measurements.delete(previous.id);\n invalidateAuthoritativeEdgePath(draft.graph.edges[index]);\n }\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('updateEdge', event),\n });\n }),\n\n deleteSelected: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n const sel = draft.selection;\n const nodesToDelete = new Set<string>();\n const edgesToDelete = new Set<string>();\n for (const id of sel) {\n if (draft.graph.nodes.some((n) => n.id === id)) {\n nodesToDelete.add(id);\n }\n if (draft.graph.edges.some((e) => e.id === id)) {\n edgesToDelete.add(id);\n }\n }\n if (nodesToDelete.size === 0 && edgesToDelete.size === 0) return;\n\n const nodesBefore = new Map(\n draft.graph.nodes.map((node) => [node.id, node]),\n );\n const edgeIdsBefore = draft.graph.edges.map((edge) => edge.id);\n\n applyNodeDeletionStrategy(\n draft,\n nodesToDelete,\n edgesToDelete,\n options.onDeleteNodes ?? 'cascade'\n );\n\n const remainingNodeIds = new Set(draft.graph.nodes.map((node) => node.id));\n const remainingEdgeIds = new Set(draft.graph.edges.map((edge) => edge.id));\n const deletedNodeIds = [...nodesBefore.keys()].filter(\n (id) => !remainingNodeIds.has(id),\n );\n const deletedNodeIdSet = new Set(deletedNodeIds);\n const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));\n const deletedIds = [...deletedNodeIds, ...deletedEdgeIds];\n const deletedPortIds = deletedNodeIds.flatMap((id) =>\n portAddressableIds(nodesBefore.get(id)!),\n );\n invalidatePathsForNodeGeometry(\n draft,\n deletedNodeIdSet,\n [...nodesBefore.values()],\n );\n\n draft.selection.clear();\n draft.focusedEntityId = null;\n for (const id of [...deletedIds, ...deletedPortIds]) {\n draft.measurements.delete(id);\n draft.derivedPortMeasurements.delete(id);\n }\n pruneVisualState(draft, [...deletedIds, ...deletedPortIds]);\n enqueue.emit.entitiesDeleted({\n ids: deletedIds,\n event: createEventObject('deleteSelected', _event),\n });\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('deleteSelected', _event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('deleteSelected', _event),\n });\n }),\n\n setGraph: (ctx, event: { graph: FlowGraph }, enqueue) => {\n let graph: FlowGraph;\n try {\n graph = validateAndCloneGraph(event.graph);\n } catch (error) {\n enqueue.emit.error({ error, event: createEventObject('setGraph', event) });\n return ctx;\n }\n return produce(ctx, (draft) => {\n draft.graph = graph;\n draft.selection.clear();\n draft.hoveredEntityIds = new Set();\n draft.highlights = new Map();\n draft.focusedEntityId = null;\n draft.canvasState = 'idle';\n draft.draggedEntityId = null;\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n draft.selectionBox = null;\n draft.selectionBoxBase = null;\n draft.collapsedNodeIds = new Set();\n draft.measurements.clear();\n draft.derivedPortMeasurements.clear();\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('setGraph', event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('setGraph', event),\n });\n });\n },\n\n replaceGraph: (\n ctx,\n event: {\n graph: FlowGraph;\n graphChanged?: boolean;\n resetMeasurementIds?: readonly string[];\n layoutAnimationOffsets?: Map<string, Point>;\n } & ReplaceGraphMetadata,\n enqueue\n ) =>\n event.graphChanged === false && event.retention !== 'reset' && !event.layoutAnimationOffsets && !event.resetMeasurementIds?.length\n ? ctx\n : produce(ctx, (draft) => {\n for (const id of event.resetMeasurementIds ?? []) {\n for (const key of draft.measurements.keys()) {\n if (key === id || key.startsWith(`${id}:`)) {\n draft.measurements.delete(key);\n draft.derivedPortMeasurements.delete(key);\n }\n }\n const previous = ctx.graph.nodes.find((node) => node.id === id);\n if (previous) {\n for (const key of portAddressableIds(previous)) {\n draft.measurements.delete(key);\n draft.derivedPortMeasurements.delete(key);\n }\n draft.measurements.delete(appearanceMeasurementId(id, resolveAppearance(previous, ctx.appearances)));\n }\n }\n const previousSelection = new Set(draft.selection);\n const previousNodes = new Map(ctx.graph.nodes.map((node) => [node.id, node]));\n const changedAppearances = new Set<string>();\n const nodes = event.graph.nodes.map((node) => {\n const previous = previousNodes.get(node.id);\n if (!previous || JSON.stringify(previous.appearance) === JSON.stringify(node.appearance)) return node;\n const next = { ...node,\n x: node.x - (node.measured?.anchorOffset?.x ?? 0),\n y: node.y - (node.measured?.anchorOffset?.y ?? 0),\n };\n delete next.measured;\n draft.measurements.delete(node.id);\n changedAppearances.add(node.id);\n return next;\n });\n draft.graph = {\n ...event.graph,\n // Keep the committed array when no appearance changed.\n nodes: changedAppearances.size ? nodes : event.graph.nodes,\n };\n if (changedAppearances.size) invalidatePathsForNodeGeometry(draft, changedAppearances);\n draft.layoutAnimation = event.layoutAnimationOffsets?.size\n ? {\n status: 'running',\n offsets: new Map(event.layoutAnimationOffsets),\n }\n : { status: 'idle', offsets: new Map() };\n const ids = graphAddressableIds(draft.graph);\n const nodeIds = new Set(draft.graph.nodes.map((node) => node.id));\n const edgeIds = new Set(draft.graph.edges.map((edge) => edge.id));\n if (event.retention === 'reset') {\n draft.selection.clear();\n draft.hoveredEntityIds.clear();\n draft.highlights.clear();\n draft.focusedEntityId = null;\n draft.parentNodeId = null;\n draft.canvasState = 'idle';\n draft.draggedEntityId = null;\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n draft.selectionBox = null;\n draft.selectionBoxBase = null;\n draft.panOrigin = null;\n draft.panViewportOrigin = null;\n draft.resizingEntityId = null;\n draft.resizeHandle = null;\n draft.resizeCorners = null;\n draft.collapsedNodeIds.clear();\n draft.measurements.clear();\n draft.derivedPortMeasurements.clear();\n } else {\n // Replace these sets only when an id is gone: a new\n // `collapsedNodeIds` re-notifies every entity view.\n if ([...draft.selection].some((id) => !ids.has(id))) {\n draft.selection = new Set([...draft.selection].filter((id) => ids.has(id)));\n }\n if ([...draft.hoveredEntityIds].some((id) => !ids.has(id))) {\n draft.hoveredEntityIds = new Set(\n [...draft.hoveredEntityIds].filter((id) => ids.has(id))\n );\n }\n if ([...draft.collapsedNodeIds].some((id) => !nodeIds.has(id))) {\n draft.collapsedNodeIds = new Set(\n [...draft.collapsedNodeIds].filter((id) => nodeIds.has(id))\n );\n }\n for (const [kind, bucket] of draft.highlights) {\n for (const id of bucket.keys()) {\n if (!ids.has(id)) bucket.delete(id);\n }\n if (bucket.size === 0) draft.highlights.delete(kind);\n }\n draft.focusedEntityId =\n draft.focusedEntityId && ids.has(draft.focusedEntityId)\n ? draft.focusedEntityId\n : null;\n draft.parentNodeId =\n draft.parentNodeId && nodeIds.has(draft.parentNodeId) ? draft.parentNodeId : null;\n const measurementIds = new Set(ids);\n for (const node of draft.graph.nodes) {\n measurementIds.add(appearanceMeasurementId(node.id, resolveAppearance(node, ctx.appearances)));\n for (const port of node.ports ?? []) {\n const portId = (port as { id?: string }).id;\n if (portId) measurementIds.add(portId);\n measurementIds.add(`${node.id}:${port.name}`);\n }\n }\n for (const edge of draft.graph.edges) {\n if (edge.label) measurementIds.add(appearanceMeasurementId(edge.id, resolveAppearance(edge.label, ctx.appearances)));\n }\n for (const id of draft.measurements.keys()) {\n if (!measurementIds.has(id)) {\n draft.measurements.delete(id);\n draft.derivedPortMeasurements.delete(id);\n }\n }\n if (draft.draggedEntityId && !ids.has(draft.draggedEntityId)) {\n draft.draggedEntityId = null;\n if (draft.canvasState === 'dragging') draft.canvasState = 'idle';\n }\n if (draft.resizingEntityId && !nodeIds.has(draft.resizingEntityId)) {\n draft.resizingEntityId = null;\n draft.resizeHandle = null;\n draft.resizeCorners = null;\n if (draft.canvasState === 'resizing') draft.canvasState = 'idle';\n }\n const hasPort = (nodeId: string, portName: string | null) =>\n portName === null ||\n draft.graph.nodes\n .find((node) => node.id === nodeId)\n ?.ports?.some((port) => port.name === portName) === true;\n if (\n draft.connection &&\n (!nodeIds.has(draft.connection.sourceId) ||\n !hasPort(draft.connection.sourceId, draft.connection.sourcePort) ||\n (draft.connection.targetId !== null &&\n (!nodeIds.has(draft.connection.targetId) ||\n !hasPort(draft.connection.targetId, draft.connection.targetPort))) ||\n (draft.connection.reconnectingEdgeId != null &&\n !edgeIds.has(draft.connection.reconnectingEdgeId)))\n ) {\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n if (draft.canvasState === 'connecting') draft.canvasState = 'idle';\n }\n if (\n draft.connectionClickStartHandle &&\n (!nodeIds.has(draft.connectionClickStartHandle.nodeId) ||\n !hasPort(\n draft.connectionClickStartHandle.nodeId,\n draft.connectionClickStartHandle.port\n ))\n ) {\n draft.connectionClickStartHandle = null;\n }\n }\n if (event.graphChanged !== false) {\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('replaceGraph', event),\n });\n }\n if (!setsEqual(previousSelection, draft.selection)) {\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('replaceGraph', event),\n });\n }\n }),\n\n setLayoutAnimationOffsets: (ctx, event: { offsets: Map<string, Point> }) =>\n produce(ctx, (draft) => {\n draft.layoutAnimation = event.offsets.size\n ? { status: 'running', offsets: new Map(event.offsets) }\n : { status: 'idle', offsets: new Map() };\n }),\n\n clearLayoutAnimation: (ctx) =>\n ctx.layoutAnimation.status === 'idle'\n ? ctx\n : produce(ctx, (draft) => {\n draft.layoutAnimation = { status: 'idle', offsets: new Map() };\n }),\n\n loadDocument: (\n ctx,\n event: {\n graph: FlowGraph;\n collapsedNodeIds: string[];\n viewport: Viewport;\n } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n draft.graph = event.graph;\n draft.viewport = event.viewport;\n draft.collapsedNodeIds = new Set(event.collapsedNodeIds);\n draft.selection.clear();\n draft.hoveredEntityIds.clear();\n draft.highlights.clear();\n draft.focusedEntityId = null;\n draft.measurements.clear();\n draft.derivedPortMeasurements.clear();\n draft.canvasState = 'idle';\n draft.draggedEntityId = null;\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n draft.selectionBox = null;\n draft.selectionBoxBase = null;\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('loadDocument', event),\n });\n enqueue.emit.viewportChanged({\n viewport: { ...draft.viewport },\n event: createEventObject('loadDocument', event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(),\n event: createEventObject('loadDocument', event),\n });\n }),\n\n setCollapsedNodes: (ctx, event: { ids: string[] }) =>\n produce(ctx, (draft) => {\n draft.collapsedNodeIds = new Set(event.ids);\n }),\n\n reset: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n Object.assign(draft, {\n ...initialContext,\n // Preserve viewport size (container hasn't changed)\n viewportSize: draft.viewportSize,\n });\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('reset', _event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('reset', _event),\n });\n }),\n\n reparentNode: (\n ctx,\n event: { id: string; parentId: string | null } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const node = draft.graph.nodes.find((n) => n.id === event.id);\n if (!node) return;\n const problem = reparentProblem(draft.graph as FlowGraph, event.id, event.parentId);\n if (problem) {\n enqueue.emit.error({\n error: new Error(problem),\n event: createEventObject('reparentNode', event),\n });\n return;\n }\n const beforeAffected = withDerivedGroupAncestors(\n draft.graph.nodes,\n new Set([event.id]),\n );\n node.parentId = event.parentId;\n const affected = new Set([\n ...beforeAffected,\n ...withDerivedGroupAncestors(\n draft.graph.nodes,\n new Set([event.id]),\n ),\n ]);\n invalidatePathsForNodeGeometry(draft, affected);\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('reparentNode', event),\n });\n }),\n\n collapseNode: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>\n produce(ctx, (draft) => {\n const node = draft.graph.nodes.find((n) => n.id === event.id);\n if (!node) {\n enqueue.emit.error({\n error: new Error(`collapseNode rejected: node \"${event.id}\" does not exist.`),\n event: createEventObject('collapseNode', event),\n });\n return;\n }\n draft.collapsedNodeIds.add(event.id);\n for (const id of draft.selection) {\n if (id !== event.id && isDescendantOf(draft.graph.nodes as FlowNode[], id, event.id)) {\n draft.selection.delete(id);\n }\n }\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('collapseNode', event),\n });\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('collapseNode', event),\n });\n }),\n\n expandNode: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>\n produce(ctx, (draft) => {\n draft.collapsedNodeIds.delete(event.id);\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('expandNode', event),\n });\n }),\n\n // Drag lifecycle\n\n dragStart: (ctx, event: { id: string } & TransactionMetadata, enqueue) => {\n const topology = createMovementTopology(\n ctx.graph.nodes as FlowNode[],\n ctx.graph.edges as FlowEdge[],\n );\n const nodeIndex = topology.nodeIndices.get(event.id);\n const edgeIndex = topology.edgeIndices.get(event.id);\n const entity =\n nodeIndex === undefined\n ? edgeIndex === undefined\n ? undefined\n : ctx.graph.edges[edgeIndex]\n : ctx.graph.nodes[nodeIndex];\n if (!entity || entity.draggable === false) {\n activeDragMovementTopology = null;\n return ctx;\n }\n activeDragMovementTopology = topology;\n const selectedIds = new Set(ctx.selection);\n selectedIds.add(event.id);\n const ids = [...selectedIds];\n const positions = entityPositions(ctx.graph, ids, undefined, topology);\n return produce(ctx, (draft) => {\n draft.canvasState = 'dragging';\n draft.draggedEntityId = event.id;\n draft.selection.add(event.id);\n enqueue.emit.dragStarted({\n ids,\n positions,\n });\n });\n },\n\n dragMove: (ctx, event: { dx: number; dy: number }, enqueue) => {\n if (ctx.canvasState !== 'dragging') return ctx;\n\n const { dx, dy } = event;\n if (dx === 0 && dy === 0) return ctx;\n\n // Raw dx/dy — no snapping here. Snap is visual (resolvedBounds)\n // and baked on commitDrag.\n // This runs once per pointer frame: compute everything on the plain\n // pre-transition context (draft proxy reads are ~10× slower), then\n // touch only the moved entities in the draft.\n const plan = planNodeMovement(\n ctx,\n dx,\n dy,\n { includeLabels: true },\n activeDragMovementTopology ?? undefined,\n );\n if (!plan) return ctx;\n const ids = [...ctx.selection];\n const positions = entityPositions(\n ctx.graph,\n ids,\n plan,\n activeDragMovementTopology ?? undefined,\n );\n\n return produce(ctx, (draft) => {\n applyMovementPlan(draft, plan);\n draft.dragRevision++;\n enqueue.emit.dragMoved({\n ids,\n positions,\n delta: { x: dx, y: dy },\n });\n });\n },\n\n dragEnd: (ctx, _event: object, enqueue) => {\n if (ctx.canvasState !== 'dragging') return ctx;\n activeDragMovementTopology = null;\n return produce(ctx, (draft) => {\n const ids = [...draft.selection];\n enqueue.emit.dragEnded({\n ids,\n positions: entityPositions(draft.graph, ids),\n });\n draft.canvasState = 'idle';\n draft.draggedEntityId = null;\n });\n },\n\n dragCancel: (ctx) => {\n activeDragMovementTopology = null;\n return produce(ctx, (draft) => {\n for (const node of draft.graph.nodes) {\n delete node.dx;\n delete node.dy;\n }\n for (const edge of draft.graph.edges) {\n delete edge.dx;\n delete edge.dy;\n if (edge.label) {\n delete edge.label.dx;\n delete edge.label.dy;\n }\n }\n draft.canvasState = 'idle';\n draft.draggedEntityId = null;\n });\n },\n\n commitDrag: (\n ctx,\n _event: (TransactionMetadata & { snapOffset?: Point }) | undefined,\n enqueue,\n ) =>\n produce(ctx, (draft) => {\n // Compute entity snap offset if snap lines enabled\n let snapOffX = _event?.snapOffset?.x ?? 0;\n let snapOffY = _event?.snapOffset?.y ?? 0;\n if (\n _event?.snapOffset === undefined &&\n draft.enableSnapLines &&\n draft.selection.size > 0\n ) {\n const selBounds = getSelectionBounds(\n draft.graph.nodes as FlowNode[],\n draft.graph.edges as FlowEdge[],\n draft.selection as Set<string>,\n draft.measurements as Map<string, Rect>,\n { includeEdgePoints: false }\n );\n if (selBounds) {\n const sel = draft.selection as Set<string>;\n const otherRects: Rect[] = (draft.graph.nodes as FlowNode[])\n .filter((n) => !sel.has(n.id) && !n.hidden)\n .map((n) => resolvedBounds(n));\n // Include edge label bounds as snap targets\n for (const edge of draft.graph.edges as FlowEdge[]) {\n if (sel.has(edge.id) || !edge.label) continue;\n otherRects.push(\n resolvedEdgeLabelBounds(\n edge,\n (draft.measurements as Map<string, Rect>).get(edge.id)\n )!\n );\n }\n const snapResult = getSnapLines(selBounds, otherRects, {\n threshold: draft.snapThreshold / draft.viewport.zoom,\n enableSpacing: draft.enableSpacingGuides,\n });\n if (snapResult) {\n snapOffX = snapResult.snapRect.x - selBounds.x;\n snapOffY = snapResult.snapRect.y - selBounds.y;\n }\n }\n }\n\n // Bake dx/dy into x/y, apply snap offsets, reset\n const gridSnap = draft.snapToGrid;\n const [gx, gy] = draft.snapGrid;\n const committedNodeDeltas = new Map<string, Point>();\n for (const node of draft.graph.nodes) {\n if (node.dx || node.dy) {\n const from = { x: node.x, y: node.y };\n let x = node.x + (node.dx ?? 0) + snapOffX;\n let y = node.y + (node.dy ?? 0) + snapOffY;\n if (gridSnap) {\n x = snapToGrid(x, gx);\n y = snapToGrid(y, gy);\n }\n node.x = x;\n node.y = y;\n node.dx = 0;\n node.dy = 0;\n committedNodeDeltas.set(node.id, {\n x: x - from.x,\n y: y - from.y,\n });\n }\n }\n const nodes = draft.graph.nodes as unknown as FlowNode[];\n const committedNodeIndex = indexNodes(nodes);\n const affectedNodeIds = withDerivedGroupAncestors(\n nodes,\n new Set(committedNodeDeltas.keys()),\n );\n for (const edge of draft.graph.edges as unknown as FlowEdge[]) {\n if (\n edge.points?.length &&\n (affectedNodeIds.has(edge.sourceId) ||\n affectedNodeIds.has(edge.targetId))\n ) {\n invalidateAuthoritativeEdgePath(edge);\n }\n\n const ownerId = getEdgeOwnerFromIndex(edge, committedNodeIndex);\n const committedDelta = ownerId\n ? committedNodeDeltas.get(ownerId)\n : undefined;\n const carriesTransientGeometry = !!edge.dx || !!edge.dy;\n const dx = committedDelta?.x ?? edge.dx ?? 0;\n const dy = committedDelta?.y ?? edge.dy ?? 0;\n if (edge.waypoints?.length && (committedDelta || carriesTransientGeometry)) {\n edge.waypoints = edge.waypoints.map((point) => ({\n x: point.x + dx,\n y: point.y + dy,\n }));\n }\n if (\n carriesTransientGeometry &&\n edge.label &&\n (edge.labelAnchor ?? draft.labelAnchor) === 'fixed' &&\n (edge.label.dx || edge.label.dy)\n ) {\n edge.label.x += dx;\n edge.label.y += dy;\n edge.label.dx = 0;\n edge.label.dy = 0;\n }\n if (carriesTransientGeometry) {\n edge.dx = 0;\n edge.dy = 0;\n }\n }\n for (const edge of draft.graph.edges) {\n if (!edge.label) continue;\n if (edge.label.dx || edge.label.dy) {\n let x = edge.label.x + (edge.label.dx ?? 0) + snapOffX;\n let y = edge.label.y + (edge.label.dy ?? 0) + snapOffY;\n if (gridSnap) {\n x = snapToGrid(x, gx);\n y = snapToGrid(y, gy);\n }\n edge.label.x = x;\n edge.label.y = y;\n edge.label.dx = 0;\n edge.label.dy = 0;\n }\n }\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('commitDrag', _event),\n });\n }),\n\n // Selection & focus\n\n select: (ctx, event: { ids: string[]; mode?: 'single' | 'multi' }, enqueue) =>\n produce(ctx, (draft) => {\n const mode = event.mode ?? 'single';\n if (mode === 'single') {\n draft.selection.clear();\n }\n // Toggle logic (from viz): if ALL ids already selected in multi mode, remove them\n if (mode === 'multi' && event.ids.every((id) => draft.selection.has(id))) {\n for (const id of event.ids) {\n draft.selection.delete(id);\n }\n } else {\n for (const id of event.ids) {\n draft.selection.add(id);\n }\n }\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('select', event),\n });\n }),\n\n selectAll: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n for (const node of draft.graph.nodes) {\n if (!isExplicitlyVisibleNode(node as FlowNode)) continue;\n draft.selection.add(node.id);\n }\n for (const edge of draft.graph.edges) {\n if (!isExplicitlyVisibleEdge(edge as FlowEdge, draft.graph.nodes as FlowNode[]))\n continue;\n draft.selection.add(edge.id);\n }\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('selectAll', _event),\n });\n }),\n\n clearSelection: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n draft.selection.clear();\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('clearSelection', _event),\n });\n }),\n\n // Box selection lifecycle (following viz patterns)\n\n selectionBoxStart: (ctx, event: { point: Point; mode?: 'single' | 'multi' }, enqueue) =>\n produce(ctx, (draft) => {\n draft.canvasState = 'selecting';\n const mode = event.mode ?? 'single';\n // Snapshot the base selection so the box can update live and, in\n // additive (shift) mode, layer the boxed entities on top of it.\n draft.selectionBoxBase = mode === 'multi' ? new Set(draft.selection) : new Set();\n if (mode === 'single') {\n draft.selection.clear();\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('selectionBoxStart', event),\n });\n }\n draft.selectionBox = [\n { x: event.point.x, y: event.point.y },\n { x: event.point.x, y: event.point.y },\n ];\n }),\n\n selectionBoxMove: (ctx, event: { point: Point }, enqueue) =>\n produce(ctx, (draft) => {\n if (draft.canvasState !== 'selecting' || !draft.selectionBox) return;\n draft.selectionBox[1] = { x: event.point.x, y: event.point.y };\n // Recompute the selection live every move: base ∪ entities in the box\n // (recomputed so shrinking the box deselects too). Retain entities\n // already inside in their entry order, then append newly captured\n // entities. Selection order is user intent for ordered commands.\n const rect = boxToRect(draft.selectionBox[0], draft.selectionBox[1]);\n const boxed = entitiesInBox(draft, rect);\n const next = new Set(draft.selectionBoxBase ?? []);\n for (const id of draft.selection) {\n if (boxed.has(id)) next.add(id);\n }\n for (const id of boxed) next.add(id);\n if (!setsEqual(draft.selection, next)) {\n draft.selection = next;\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('selectionBoxMove', event),\n });\n }\n }),\n\n selectionBoxEnd: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n if (!draft.selectionBox) return;\n // Selection is already current from the last move; just settle.\n draft.selectionBox = null;\n draft.selectionBoxBase = null;\n draft.canvasState = 'idle';\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('selectionBoxEnd', _event),\n });\n }),\n\n selectionBoxCancel: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n if (draft.selectionBoxBase) {\n draft.selection = new Set(draft.selectionBoxBase);\n }\n draft.selectionBox = null;\n draft.selectionBoxBase = null;\n draft.canvasState = 'idle';\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('selectionBoxCancel', _event),\n });\n }),\n\n focus: (ctx, event: { entityId: string }) =>\n produce(ctx, (draft) => {\n draft.focusedEntityId = event.entityId;\n }),\n\n clearFocus: (ctx) =>\n produce(ctx, (draft) => {\n draft.focusedEntityId = null;\n }),\n\n // Hover & highlights (visual state — not undoable)\n\n setHover: (ctx, event: { ids: string[] }) => {\n // No-op when unchanged so subscribers see a stable context identity.\n if (\n ctx.hoveredEntityIds.size === event.ids.length &&\n event.ids.every((id) => ctx.hoveredEntityIds.has(id))\n ) {\n return ctx;\n }\n return produce(ctx, (draft) => {\n draft.hoveredEntityIds = new Set(event.ids);\n });\n },\n\n clearHover: (ctx) => {\n if (ctx.hoveredEntityIds.size === 0) return ctx;\n return produce(ctx, (draft) => {\n draft.hoveredEntityIds = new Set();\n });\n },\n\n setHighlights: (ctx, event: { kind: string; entries: FlowHighlightEntry[] }) =>\n produce(ctx, (draft) => {\n const bucket = new Map<string, unknown>();\n for (const entry of event.entries) {\n bucket.set(entry.id, entry.meta);\n }\n if (bucket.size === 0) draft.highlights.delete(event.kind);\n else draft.highlights.set(event.kind, bucket);\n }),\n\n addHighlights: (ctx, event: { kind: string; entries: FlowHighlightEntry[] }) =>\n produce(ctx, (draft) => {\n let bucket = draft.highlights.get(event.kind);\n if (!bucket) {\n bucket = new Map<string, unknown>();\n draft.highlights.set(event.kind, bucket);\n }\n for (const entry of event.entries) {\n bucket.set(entry.id, entry.meta);\n }\n }),\n\n removeHighlights: (ctx, event: { kind: string; ids: string[] }) =>\n produce(ctx, (draft) => {\n const bucket = draft.highlights.get(event.kind);\n if (!bucket) return;\n for (const id of event.ids) {\n bucket.delete(id);\n }\n if (bucket.size === 0) draft.highlights.delete(event.kind);\n }),\n\n clearHighlights: (ctx, event: { kind?: string } | undefined) =>\n produce(ctx, (draft) => {\n if (event?.kind !== undefined) draft.highlights.delete(event.kind);\n else draft.highlights.clear();\n }),\n\n // Navigation\n\n updateParentNodeId: (ctx, event: { parentNodeId: string | null }) =>\n produce(ctx, (draft) => {\n draft.parentNodeId = event.parentNodeId;\n draft.selection.clear();\n draft.focusedEntityId = null;\n }),\n\n setViewScope: (\n ctx,\n event: {\n parentNodeId: string | null;\n depth: number | null;\n selection: FlowViewSelectionPolicy;\n visibleEntityIds: string[];\n },\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const scopeChanged =\n draft.parentNodeId !== event.parentNodeId || draft.depth !== event.depth;\n const previousSelection = new Set(draft.selection);\n const visibleIds = new Set(event.visibleEntityIds);\n draft.parentNodeId = event.parentNodeId;\n draft.depth = event.depth;\n draft.selection =\n event.selection === 'clear'\n ? new Set()\n : new Set([...draft.selection].filter((id) => visibleIds.has(id)));\n draft.hoveredEntityIds = new Set(\n [...draft.hoveredEntityIds].filter((id) => visibleIds.has(id))\n );\n draft.focusedEntityId =\n draft.focusedEntityId && visibleIds.has(draft.focusedEntityId)\n ? draft.focusedEntityId\n : null;\n if (scopeChanged) {\n draft.canvasState = 'idle';\n draft.draggedEntityId = null;\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n draft.selectionBox = null;\n draft.selectionBoxBase = null;\n draft.panOrigin = null;\n draft.panViewportOrigin = null;\n draft.resizingEntityId = null;\n draft.resizeHandle = null;\n draft.resizeCorners = null;\n enqueue.emit.viewChanged({\n scope: Object.freeze({\n parentId: event.parentNodeId,\n depth: event.depth,\n }),\n event: createEventObject('setViewScope', event),\n });\n }\n if (!setsEqual(previousSelection, draft.selection)) {\n enqueue.emit.selectionChanged({\n selection: new Set(draft.selection),\n event: createEventObject('setViewScope', event),\n });\n }\n }),\n\n // Viewport (flat payloads)\n\n setViewport: (ctx, event: Viewport, enqueue) =>\n produce(ctx, (draft) => {\n draft.viewport = { x: event.x, y: event.y, zoom: event.zoom };\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('setViewport', event),\n });\n }),\n\n setFitFrame: (ctx, event: { frame: Rect | null; preserveCenter?: boolean }, enqueue) =>\n produce(ctx, (draft) => {\n const previousFrame = draft.fitFrame ?? {\n x: 0,\n y: 0,\n width: draft.viewportSize.width,\n height: draft.viewportSize.height,\n };\n const nextFrame = event.frame ?? {\n x: 0,\n y: 0,\n width: draft.viewportSize.width,\n height: draft.viewportSize.height,\n };\n draft.fitFrame = event.frame ? { ...event.frame } : null;\n if (!event.preserveCenter) return;\n\n draft.viewport.x +=\n nextFrame.x + nextFrame.width / 2 - (previousFrame.x + previousFrame.width / 2);\n draft.viewport.y +=\n nextFrame.y + nextFrame.height / 2 - (previousFrame.y + previousFrame.height / 2);\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('setFitFrame', event),\n });\n }),\n\n panBy: (ctx, event: Point, enqueue) =>\n produce(ctx, (draft) => {\n draft.viewport.x += event.x;\n draft.viewport.y += event.y;\n if (draft.translateExtent) {\n const constrained = constrainViewport(\n draft.viewport,\n draft.viewportSize,\n draft.translateExtent as unknown as [\n { x: number; y: number },\n { x: number; y: number }\n ]\n );\n draft.viewport = constrained;\n }\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('panBy', event),\n });\n }),\n\n zoomTo: (ctx, event: { zoom: number; center: Point }, enqueue) =>\n produce(ctx, (draft) => {\n const clamped = Math.min(Math.max(event.zoom, draft.minZoom), draft.maxZoom);\n const ratio = clamped / draft.viewport.zoom;\n draft.viewport = {\n x: event.center.x - (event.center.x - draft.viewport.x) * ratio,\n y: event.center.y - (event.center.y - draft.viewport.y) * ratio,\n zoom: clamped,\n };\n if (draft.translateExtent) {\n const constrained = constrainViewport(\n draft.viewport,\n draft.viewportSize,\n draft.translateExtent as unknown as [\n { x: number; y: number },\n { x: number; y: number }\n ]\n );\n draft.viewport = constrained;\n }\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('zoomTo', event),\n });\n }),\n\n zoomBy: (ctx, event: { factor: number; center?: Point }, enqueue) =>\n produce(ctx, (draft) => {\n // Default pivot: the center of the visible viewport.\n const center =\n event.center ??\n (draft.fitFrame\n ? {\n x: draft.fitFrame.x + draft.fitFrame.width / 2,\n y: draft.fitFrame.y + draft.fitFrame.height / 2,\n }\n : {\n x: draft.viewportSize.width / 2,\n y: draft.viewportSize.height / 2,\n });\n const clamped = Math.min(\n Math.max(draft.viewport.zoom * event.factor, draft.minZoom),\n draft.maxZoom\n );\n const ratio = clamped / draft.viewport.zoom;\n draft.viewport = {\n x: center.x - (center.x - draft.viewport.x) * ratio,\n y: center.y - (center.y - draft.viewport.y) * ratio,\n zoom: clamped,\n };\n if (draft.translateExtent) {\n draft.viewport = constrainViewport(\n draft.viewport,\n draft.viewportSize,\n draft.translateExtent as unknown as [\n { x: number; y: number },\n { x: number; y: number }\n ]\n );\n }\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('zoomBy', event),\n });\n }),\n\n setMinZoom: (ctx, event: { minZoom: number }) =>\n produce(ctx, (draft) => {\n draft.minZoom = event.minZoom;\n if (draft.viewport.zoom < event.minZoom) {\n draft.viewport.zoom = event.minZoom;\n }\n }),\n\n setMaxZoom: (ctx, event: { maxZoom: number }) =>\n produce(ctx, (draft) => {\n draft.maxZoom = event.maxZoom;\n if (draft.viewport.zoom > event.maxZoom) {\n draft.viewport.zoom = event.maxZoom;\n }\n }),\n\n setDragThreshold: (ctx, event: { dragThreshold: number }) =>\n produce(ctx, (draft) => {\n draft.dragThreshold = Math.max(0, event.dragThreshold);\n }),\n\n setAutoPanOptions: (\n ctx,\n event: {\n autoPanOnDrag?: boolean;\n autoPanThreshold?: number;\n autoPanSpeed?: number;\n }\n ) =>\n produce(ctx, (draft) => {\n if (event.autoPanOnDrag !== undefined) {\n draft.autoPanOnDrag = event.autoPanOnDrag;\n }\n if (event.autoPanThreshold !== undefined) {\n draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);\n }\n if (event.autoPanSpeed !== undefined) {\n draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);\n }\n }),\n\n updateSettings: (ctx, event: Partial<FlowRuntimeSettings>) =>\n produce(ctx, (draft) => {\n if (event.dragThreshold !== undefined) {\n draft.dragThreshold = Math.max(0, event.dragThreshold);\n }\n if (event.constrainNodeMovement !== undefined) {\n draft.constrainNodeMovement = event.constrainNodeMovement ?? null;\n }\n if (event.autoPanOnDrag !== undefined) {\n draft.autoPanOnDrag = event.autoPanOnDrag;\n }\n if (event.autoPanThreshold !== undefined) {\n draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);\n }\n if (event.autoPanSpeed !== undefined) {\n draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);\n }\n if (event.viewportAnimation !== undefined) {\n draft.viewportAnimation = event.viewportAnimation;\n }\n if (event.enableSnapLines !== undefined) {\n draft.enableSnapLines = event.enableSnapLines;\n }\n if (event.snapThreshold !== undefined) {\n draft.snapThreshold = Math.max(0, event.snapThreshold);\n }\n if (event.enableSpacingGuides !== undefined) {\n draft.enableSpacingGuides = event.enableSpacingGuides;\n }\n if (event.boxSelectionTest !== undefined) {\n draft.boxSelectionTest = event.boxSelectionTest ?? null;\n }\n if (event.labelAnchor !== undefined) {\n draft.labelAnchor = event.labelAnchor;\n }\n }),\n\n configure: (ctx, event: Partial<FlowStoreOptions>) => {\n if (event.profile) profile = event.profile;\n const previousAppearances = ctx.appearances;\n return produce(ctx, (draft) => {\n if (event.minZoom !== undefined) draft.minZoom = Math.max(0.01, event.minZoom);\n if (event.maxZoom !== undefined) draft.maxZoom = Math.max(draft.minZoom, event.maxZoom);\n if (event.translateExtent !== undefined) draft.translateExtent = event.translateExtent;\n if (event.nodeExtent !== undefined) draft.nodeExtent = event.nodeExtent;\n if (event.dragThreshold !== undefined)\n draft.dragThreshold = Math.max(0, event.dragThreshold);\n if (event.connectionDragThreshold !== undefined) {\n draft.connectionDragThreshold = Math.max(0, event.connectionDragThreshold);\n }\n if (event.constrainNodeMovement !== undefined) {\n draft.constrainNodeMovement = event.constrainNodeMovement ?? null;\n }\n if (event.autoPanOnDrag !== undefined) draft.autoPanOnDrag = event.autoPanOnDrag;\n if (event.autoPanThreshold !== undefined)\n draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);\n if (event.autoPanSpeed !== undefined)\n draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);\n if (event.viewportAnimation !== undefined)\n draft.viewportAnimation = event.viewportAnimation;\n if (event.snapToGrid !== undefined) draft.snapToGrid = event.snapToGrid;\n if (event.snapGrid !== undefined) draft.snapGrid = event.snapGrid;\n if (event.enableSnapLines !== undefined) draft.enableSnapLines = event.enableSnapLines;\n if (event.snapThreshold !== undefined)\n draft.snapThreshold = Math.max(0, event.snapThreshold);\n if (event.enableSpacingGuides !== undefined)\n draft.enableSpacingGuides = event.enableSpacingGuides;\n if (event.connectOnClick !== undefined) draft.connectOnClick = event.connectOnClick;\n if (event.colorMode !== undefined) draft.colorMode = event.colorMode;\n if (event.boxSelectionTest !== undefined)\n draft.boxSelectionTest = event.boxSelectionTest ?? null;\n if (event.selectionMode !== undefined) draft.selectionMode = event.selectionMode;\n if (event.labelAnchor !== undefined) draft.labelAnchor = event.labelAnchor;\n if (event.profile || event.mode !== undefined) {\n draft.mode = getMode(profile, event.mode ?? draft.mode);\n }\n if (event.appearances !== undefined && event.appearances !== previousAppearances) {\n draft.appearances = castDraft(event.appearances);\n const appearanceNodes = new Set<string>();\n for (const node of draft.graph.nodes) {\n if (!resolveAppearance(node, previousAppearances).reference && !resolveAppearance(node, draft.appearances).reference) continue;\n node.x -= node.measured?.anchorOffset?.x ?? 0;\n node.y -= node.measured?.anchorOffset?.y ?? 0;\n delete node.measured;\n draft.measurements.delete(node.id);\n appearanceNodes.add(node.id);\n }\n if (appearanceNodes.size) invalidatePathsForNodeGeometry(draft, appearanceNodes);\n for (const edge of draft.graph.edges) {\n if (edge.label && (resolveAppearance(edge.label, previousAppearances).reference || resolveAppearance(edge.label, draft.appearances).reference)) { draft.measurements.delete(edge.id); invalidateAuthoritativeEdgePath(edge); }\n }\n for (const id of draft.measurements.keys()) {\n if (id.startsWith('[\"flow-appearance-boundary\",')) draft.measurements.delete(id);\n }\n }\n draft.configRevision += 1;\n });\n },\n\n bumpConfigRevision: (ctx) =>\n produce(ctx, (draft) => {\n draft.configRevision += 1;\n }),\n\n bumpRoutingRevision: (ctx) =>\n produce(ctx, (draft) => {\n draft.routingRevision += 1;\n }),\n\n setTranslateExtent: (ctx, event: { extent: [Point, Point] | null }) =>\n produce(ctx, (draft) => {\n draft.translateExtent = event.extent;\n }),\n\n setNodeExtent: (ctx, event: { extent: [Point, Point] | null }) =>\n produce(ctx, (draft) => {\n draft.nodeExtent = event.extent;\n }),\n\n updateViewportSize: (ctx, event: Size & { preserveCenter?: boolean }, enqueue) =>\n produce(ctx, (draft) => {\n const previousSize = { ...draft.viewportSize };\n draft.viewportSize = { width: event.width, height: event.height };\n if (!event.preserveCenter || previousSize.width <= 0 || previousSize.height <= 0) return;\n\n draft.viewport.x += (event.width - previousSize.width) / 2;\n draft.viewport.y += (event.height - previousSize.height) / 2;\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('updateViewportSize', event),\n });\n }),\n\n fitView: (ctx, event: FitViewOptions | undefined, enqueue) =>\n produce(ctx, (draft) => {\n if (draft.viewportSize.width === 0 || draft.viewportSize.height === 0) return;\n\n const ids = event?.nodes?.map((node) => (typeof node === 'string' ? node : node.id));\n const hasIds = ids && ids.length > 0;\n const idSet = hasIds ? new Set(ids) : null;\n const nodes = hasIds\n ? (draft.graph.nodes as FlowNode[]).filter(\n (node) => idSet!.has(node.id) && isExplicitlyVisibleNode(node)\n )\n : (draft.graph.nodes as FlowNode[]).filter((node) => isExplicitlyVisibleNode(node));\n const edges = hasIds\n ? (draft.graph.edges as FlowEdge[]).filter(\n (edge) =>\n idSet!.has(edge.id) &&\n isExplicitlyVisibleEdge(edge, draft.graph.nodes as FlowNode[])\n )\n : (draft.graph.edges as FlowEdge[]).filter((edge) =>\n isExplicitlyVisibleEdge(edge, draft.graph.nodes as FlowNode[])\n );\n\n const bounds = getGraphBounds(nodes, edges, draft.measurements as Map<string, Rect>);\n if (bounds.width === 0 && bounds.height === 0) return;\n const { nodes: _nodes, ...options } = event ?? {};\n const vp = viewportForBounds(bounds, draft.viewportSize, {\n ...options,\n frame: options.frame ?? draft.fitFrame ?? undefined,\n });\n draft.viewport = vp;\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('fitView', event),\n });\n }),\n\n pushViewport: (ctx) =>\n produce(ctx, (draft) => {\n draft.viewportStack.push({ ...draft.viewport });\n }),\n\n popViewport: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n const prev = draft.viewportStack.pop();\n if (prev) {\n draft.viewport = prev;\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('popViewport', _event),\n });\n }\n }),\n\n // Pan lifecycle\n\n panStart: (ctx, event: Point) =>\n produce(ctx, (draft) => {\n draft.canvasState = 'panning';\n draft.panOrigin = { x: event.x, y: event.y };\n draft.panViewportOrigin = { ...draft.viewport };\n }),\n\n pan: (ctx, event: Point, enqueue) =>\n produce(ctx, (draft) => {\n if (!draft.panOrigin || !draft.panViewportOrigin) return;\n let newX = draft.panViewportOrigin.x + (event.x - draft.panOrigin.x);\n let newY = draft.panViewportOrigin.y + (event.y - draft.panOrigin.y);\n\n // Clamp to translateExtent\n if (draft.translateExtent) {\n const z = draft.viewport.zoom;\n newX = Math.max(\n -(draft.translateExtent[1].x * z - draft.viewportSize.width),\n Math.min(newX, -draft.translateExtent[0].x * z)\n );\n newY = Math.max(\n -(draft.translateExtent[1].y * z - draft.viewportSize.height),\n Math.min(newY, -draft.translateExtent[0].y * z)\n );\n }\n\n draft.viewport = {\n x: newX,\n y: newY,\n zoom: draft.panViewportOrigin.zoom,\n };\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('pan', event),\n });\n }),\n\n panEnd: (ctx) =>\n produce(ctx, (draft) => {\n draft.canvasState = 'idle';\n draft.panOrigin = null;\n draft.panViewportOrigin = null;\n }),\n\n panCancel: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n if (draft.panViewportOrigin) {\n draft.viewport = { ...draft.panViewportOrigin };\n enqueue.emit.viewportChanged({\n viewport: plainViewport(draft.viewport),\n event: createEventObject('panCancel', _event),\n });\n }\n draft.canvasState = 'idle';\n draft.panOrigin = null;\n draft.panViewportOrigin = null;\n }),\n\n // Interaction state\n\n setCanvasState: (ctx, event: { state: CanvasState }) =>\n produce(ctx, (draft) => {\n draft.canvasState = event.state;\n }),\n\n // Connection lifecycle\n\n connectionStart: (\n ctx,\n event: {\n sourceId: string;\n sourcePort: string | null;\n position: Point;\n active?: boolean;\n reconnectingEdgeId?: string | null;\n reconnectingEnd?: 'source' | 'target' | null;\n preview?: boolean;\n },\n enqueue\n ) =>\n produce(ctx, (draft) => {\n draft.canvasState = 'connecting';\n draft.connection = {\n [connectionLifetime]: {},\n sourceId: event.sourceId,\n sourcePort: event.sourcePort,\n targetId: null,\n targetPort: null,\n startPosition: event.position,\n pointerPosition: event.position,\n active: event.active ?? false,\n preview: event.preview ?? true,\n isValid: false,\n reconnectingEdgeId: event.reconnectingEdgeId ?? null,\n reconnectingEnd: event.reconnectingEnd ?? null,\n };\n enqueue.emit.connectStarted({\n sourceId: event.sourceId,\n sourcePort: event.sourcePort,\n point: event.position,\n });\n }),\n\n connectionMove: (\n ctx,\n event: {\n position: Point;\n targetId?: string | null;\n targetPort?: string | null;\n isValid?: boolean;\n invalidReason?: string;\n active?: boolean;\n },\n enqueue\n ) =>\n produce(ctx, (draft) => {\n if (!draft.connection) return;\n draft.connection.pointerPosition = event.position;\n if (event.targetId !== undefined) draft.connection.targetId = event.targetId;\n if (event.targetPort !== undefined) draft.connection.targetPort = event.targetPort;\n if (event.isValid !== undefined) draft.connection.isValid = event.isValid;\n if (event.active !== undefined) draft.connection.active = event.active;\n draft.connection.invalidReason = event.invalidReason;\n const dx = event.position.x - draft.connection.startPosition.x;\n const dy = event.position.y - draft.connection.startPosition.y;\n const threshold = draft.connectionDragThreshold;\n if (event.active === undefined && !draft.connection.active && Math.hypot(dx, dy) >= threshold) {\n draft.connection.active = true;\n }\n enqueue.emit.connectMoved({\n point: event.position,\n targetId: draft.connection.targetId,\n targetPort: draft.connection.targetPort,\n isValid: draft.connection.isValid,\n invalidReason: draft.connection.invalidReason,\n });\n }),\n\n connectionEnd: (\n ctx,\n event: { target?: ConnectEndTarget; reconnectedEdgeId?: string } | undefined,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n // Emit the pre-transition connection: it is plain data, while\n // draft.connection is an immer proxy that is revoked before\n // listeners run.\n const connection = ctx.connection;\n if (connection) {\n const target = event?.target ?? { kind: 'none' as const };\n const status =\n target.kind === 'none' ? 'cancelled' : connection.isValid ? 'connected' : 'invalid';\n enqueue.emit.connectionEnded({\n status,\n source: {\n nodeId: connection.sourceId,\n port: connection.sourcePort,\n },\n target,\n connection,\n ...(event?.reconnectedEdgeId ? { reconnectedEdgeId: event.reconnectedEdgeId } : {}),\n });\n }\n draft.canvasState = 'idle';\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n }),\n\n cancelConnection: (ctx) =>\n produce(ctx, (draft) => {\n draft.connection = null;\n draft.connectionClickStartHandle = null;\n if (draft.canvasState === 'connecting') {\n draft.canvasState = 'idle';\n }\n }),\n\n // Click-to-connect\n setConnectionClickStartHandle: (ctx, event: { nodeId: string; port: string | null } | null) =>\n produce(ctx, (draft) => {\n draft.connectionClickStartHandle = event?.nodeId !== undefined\n ? { nodeId: event.nodeId, port: event.port }\n : null;\n }),\n\n // Resize lifecycle (corner-based: two opposite corners, mouse moves one)\n\n resizeStart: (\n ctx,\n event: { id: string; handle: ResizeHandle } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const node = draft.graph.nodes.find((n) => n.id === event.id);\n if (!node) return;\n draft.canvasState = 'resizing';\n draft.resizingEntityId = event.id;\n draft.resizeHandle = event.handle;\n\n // Compute current rect corners\n const x = node.x + (node.dx ?? 0);\n const y = node.y + (node.dy ?? 0);\n const { width: w, height: h } = resolvedSize(node);\n const tl = { x, y };\n const br = { x: x + w, y: y + h };\n\n // [anchor (fixed corner), moving (dragged corner)]\n const handle = event.handle;\n if (handle === 'bottom-right') draft.resizeCorners = [tl, br];\n else if (handle === 'bottom-left')\n draft.resizeCorners = [\n { x: br.x, y: tl.y },\n { x: tl.x, y: br.y },\n ];\n else if (handle === 'top-right')\n draft.resizeCorners = [\n { x: tl.x, y: br.y },\n { x: br.x, y: tl.y },\n ];\n else if (handle === 'top-left') draft.resizeCorners = [br, tl];\n else if (handle === 'right') draft.resizeCorners = [tl, { x: br.x, y: br.y }];\n else if (handle === 'left')\n draft.resizeCorners = [\n { x: br.x, y: tl.y },\n { x: tl.x, y: br.y },\n ];\n else if (handle === 'bottom') draft.resizeCorners = [tl, { x: br.x, y: br.y }];\n else if (handle === 'top')\n draft.resizeCorners = [\n { x: tl.x, y: br.y },\n { x: br.x, y: tl.y },\n ];\n const bounds = resizeBoundsFromDraft(draft.resizeCorners);\n if (bounds) {\n enqueue.emit.resizeStarted({\n id: event.id,\n handle: event.handle,\n bounds,\n });\n }\n }),\n\n resizeMove: (ctx, event: Point) =>\n produce(ctx, (draft) => {\n if (!draft.resizeCorners || !draft.resizingEntityId) return;\n const handle = draft.resizeHandle;\n const node = draft.graph.nodes.find((n) => n.id === draft.resizingEntityId);\n if (!node) return;\n const anchor = draft.resizeCorners[0];\n let moving = draft.resizeCorners[1];\n // Move the dragged corner; anchor stays fixed\n // For edge handles (top/bottom/left/right), only move one axis\n if (handle === 'left' || handle === 'right') {\n moving = { ...moving, x: event.x };\n } else if (handle === 'top' || handle === 'bottom') {\n moving = { ...moving, y: event.y };\n } else {\n moving = { x: event.x, y: event.y };\n }\n draft.resizeCorners[1] = clampResizeMovingPoint(node, handle, anchor, moving);\n }),\n\n resizeEnd: (ctx, _event: object, enqueue) =>\n produce(ctx, (draft) => {\n const resizedId = draft.resizingEntityId;\n if (draft.resizingEntityId && draft.resizeCorners) {\n const node = draft.graph.nodes.find((n) => n.id === draft.resizingEntityId);\n if (node) {\n const before = resolvedBounds(node);\n const [a, b] = draft.resizeCorners;\n const x = Math.min(a.x, b.x);\n const y = Math.min(a.y, b.y);\n const w = Math.abs(b.x - a.x);\n const h = Math.abs(b.y - a.y);\n // Commit: update position + custom size\n node.x = x;\n node.y = y;\n node.dx = 0;\n node.dy = 0;\n if (!node.style) node.style = {};\n // Honor the (possibly free) resize clamp; keep a 1px degeneracy\n // guard so a node never commits to a zero-area, unhittable box.\n node.style.customWidth = Math.max(1, w);\n node.style.customHeight = Math.max(1, h);\n const after = resolvedBounds(node);\n if (\n before.x !== after.x ||\n before.y !== after.y ||\n before.width !== after.width ||\n before.height !== after.height\n ) {\n invalidatePathsForNodeGeometry(draft, new Set([node.id]));\n }\n }\n }\n draft.canvasState = 'idle';\n draft.resizingEntityId = null;\n draft.resizeHandle = null;\n draft.resizeCorners = null;\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('resizeEnd', _event),\n });\n if (resizedId) {\n const node = draft.graph.nodes.find((n) => n.id === resizedId);\n if (node) {\n enqueue.emit.resizeEnded({\n id: resizedId,\n bounds: {\n x: node.x,\n y: node.y,\n width: resolvedSize(node).width,\n height: resolvedSize(node).height,\n },\n });\n }\n }\n }),\n\n resizeCancel: (ctx) =>\n produce(ctx, (draft) => {\n draft.canvasState = 'idle';\n draft.resizingEntityId = null;\n draft.resizeHandle = null;\n draft.resizeCorners = null;\n }),\n\n paneClicked: (ctx, event: FlowPaneGestureEvent, enqueue) => {\n enqueue.emit.paneClicked(event);\n return ctx;\n },\n\n paneContextMenu: (ctx, event: FlowPaneGestureEvent, enqueue) => {\n enqueue.emit.paneContextMenu(event);\n return ctx;\n },\n\n entityClicked: (ctx, event: FlowEntityGestureEvent, enqueue) => {\n enqueue.emit.entityClicked(event);\n return ctx;\n },\n\n entityDoubleClicked: (ctx, event: FlowEntityGestureEvent, enqueue) => {\n enqueue.emit.entityDoubleClicked(event);\n return ctx;\n },\n\n entityContextMenu: (ctx, event: FlowEntityGestureEvent, enqueue) => {\n enqueue.emit.entityContextMenu(event);\n return ctx;\n },\n\n // Reconnect edge\n\n reconnectEdge: (\n ctx,\n event: {\n edgeId: string;\n newSourceId?: string;\n newTargetId?: string;\n newSourcePort?: string | null;\n newTargetPort?: string | null;\n } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const edge = draft.graph.edges.find((e) => e.id === event.edgeId);\n if (!edge) return;\n const resultingSourceId = event.newSourceId ?? edge.sourceId;\n const resultingTargetId = event.newTargetId ?? edge.targetId;\n const missing: string[] = [];\n if (!draft.graph.nodes.some((n) => n.id === resultingSourceId))\n missing.push(`source node \"${resultingSourceId}\"`);\n if (!draft.graph.nodes.some((n) => n.id === resultingTargetId))\n missing.push(`target node \"${resultingTargetId}\"`);\n if (missing.length > 0) {\n enqueue.emit.error({\n error: new Error(\n `reconnectEdge rejected: edge \"${event.edgeId}\" references ${missing.join(\n ' and '\n )}, which ${missing.length === 1 ? 'does' : 'do'} not exist in the graph.`\n ),\n event: createEventObject('reconnectEdge', event),\n });\n return;\n }\n const nextSourceId = event.newSourceId ?? edge.sourceId;\n const nextTargetId = event.newTargetId ?? edge.targetId;\n const nextSourcePort =\n event.newSourcePort === undefined\n ? edge.sourcePort ?? undefined\n : event.newSourcePort ?? undefined;\n const nextTargetPort =\n event.newTargetPort === undefined\n ? edge.targetPort ?? undefined\n : event.newTargetPort ?? undefined;\n const endpointChanged =\n nextSourceId !== edge.sourceId ||\n nextTargetId !== edge.targetId ||\n nextSourcePort !== (edge.sourcePort ?? undefined) ||\n nextTargetPort !== (edge.targetPort ?? undefined);\n if (event.newSourceId !== undefined) edge.sourceId = event.newSourceId;\n if (event.newTargetId !== undefined) edge.targetId = event.newTargetId;\n if (event.newSourcePort !== undefined) edge.sourcePort = event.newSourcePort ?? undefined;\n if (event.newTargetPort !== undefined) edge.targetPort = event.newTargetPort ?? undefined;\n if (endpointChanged) {\n invalidateAuthoritativeEdgePath(edge);\n }\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('reconnectEdge', event),\n });\n }),\n\n // Mode and grid snapping\n\n setMode: (ctx, event: { mode: string }, enqueue) =>\n dispatchProfile(\n profile,\n ctx,\n createEventObject('setMode', event) as {\n type: 'setMode';\n mode: string;\n },\n enqueue,\n setModeTransition(profile)\n ),\n\n setSnapToGrid: (ctx, event: { enabled: boolean; grid?: [number, number] }) =>\n produce(ctx, (draft) => {\n draft.snapToGrid = event.enabled;\n if (event.grid) draft.snapGrid = event.grid;\n }),\n\n setSnapLines: (ctx, event: { enabled: boolean; threshold?: number; spacing?: boolean }) =>\n produce(ctx, (draft) => {\n draft.enableSnapLines = event.enabled;\n if (event.threshold !== undefined) draft.snapThreshold = event.threshold;\n if (event.spacing !== undefined) draft.enableSpacingGuides = event.spacing;\n }),\n\n setColorMode: (ctx, event: { colorMode: FlowColorMode }) =>\n produce(ctx, (draft) => {\n draft.colorMode = event.colorMode;\n }),\n\n // Arrow key movement\n\n moveNodes: (ctx, event: { direction: Point; factor?: number }) => {\n const f = event.factor ?? 1;\n let dx = event.direction.x * f;\n let dy = event.direction.y * f;\n\n if (ctx.snapToGrid) {\n dx = dx !== 0 ? Math.sign(dx) * ctx.snapGrid[0] : 0;\n dy = dy !== 0 ? Math.sign(dy) * ctx.snapGrid[1] : 0;\n }\n if (dx === 0 && dy === 0) return ctx;\n\n const plan = planNodeMovement(ctx, dx, dy, { includeLabels: true });\n if (!plan) return ctx;\n\n return produce(ctx, (draft) => {\n applyMovementPlan(draft, plan);\n });\n },\n\n // Layout\n\n requestLayout: (ctx, event: { algorithm?: string }, enqueue) =>\n produce(ctx, (draft) => {\n if (draft.canvasState === 'dragging') return;\n\n const algorithm = event.algorithm ?? draft.autoLayout.algorithm;\n if (!algorithm) {\n return;\n }\n\n draft.autoLayout = {\n status: 'pending',\n algorithm,\n };\n\n enqueue.emit.layoutRequested({\n algorithm,\n graph: ctx.graph,\n });\n }),\n\n applyLayoutResult: (\n ctx,\n event: {\n positions: Map<string, { x: number; y: number }>;\n edgeLabelPositions?: Map<string, { x: number; y: number }>;\n } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n const changedNodeIds = new Set<string>();\n for (const [id, pos] of event.positions) {\n const node = draft.graph.nodes.find((n) => n.id === id);\n if (node) {\n const before = resolvedBounds(node);\n node.x = pos.x;\n node.y = pos.y;\n node.dx = 0;\n node.dy = 0;\n const after = resolvedBounds(node);\n if (\n before.x !== after.x ||\n before.y !== after.y ||\n before.width !== after.width ||\n before.height !== after.height\n ) {\n changedNodeIds.add(id);\n }\n }\n }\n invalidatePathsForNodeGeometry(draft, changedNodeIds);\n if (event.edgeLabelPositions) {\n for (const [id, pos] of event.edgeLabelPositions) {\n const edge = draft.graph.edges.find((e) => e.id === id);\n if (edge?.label) {\n edge.label.x = pos.x;\n edge.label.y = pos.y;\n edge.label.dx = 0;\n edge.label.dy = 0;\n }\n }\n }\n for (const edge of draft.graph.edges) {\n if ((edge.dx ?? 0) === 0 && (edge.dy ?? 0) === 0) continue;\n delete edge.dx;\n delete edge.dy;\n }\n draft.autoLayout.status = 'idle';\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('applyLayoutResult', event),\n });\n }),\n\n // Measurement (renderer → engine)\n\n updateMeasurements: (\n ctx,\n event: {\n measurements: Array<{ id: string; rect: Rect; origin?: Point }>;\n derivedOnly?: boolean;\n }\n ) => {\n // Resolve a measurement batch once on plain arrays. Repeated draft\n // `.find()` calls made node batches O(batch × nodes); port/unknown ids\n // also scanned every edge and port. Preserve first-match precedence:\n // node, then edge, then port.\n const nodeIndices = new Map<string, number>();\n for (let index = 0; index < ctx.graph.nodes.length; index++) {\n const id = ctx.graph.nodes[index].id;\n if (!nodeIndices.has(id)) nodeIndices.set(id, index);\n }\n const needsSecondaryIndices = event.measurements.some(\n (measurement) => !nodeIndices.has(measurement.id)\n );\n const edgeIndices = new Map<string, number>();\n const portIndices = new Map<\n string,\n { nodeIndex: number; portIndex: number }\n >();\n if (needsSecondaryIndices) {\n for (let index = 0; index < ctx.graph.edges.length; index++) {\n const id = ctx.graph.edges[index].id;\n if (!edgeIndices.has(id)) edgeIndices.set(id, index);\n }\n for (let nodeIndex = 0; nodeIndex < ctx.graph.nodes.length; nodeIndex++) {\n const node = ctx.graph.nodes[nodeIndex];\n for (let portIndex = 0; portIndex < (node.ports?.length ?? 0); portIndex++) {\n const port = node.ports![portIndex];\n const target = { nodeIndex, portIndex };\n const address = `${node.id}:${port.name}`;\n if (!portIndices.has(address)) portIndices.set(address, target);\n const explicitId = (port as { id?: string }).id;\n if (explicitId && !portIndices.has(explicitId)) {\n portIndices.set(explicitId, target);\n }\n }\n }\n }\n\n return produce(ctx, (draft) => {\n const boundaryNodes = new Set<string>();\n const candidateNodes = new Set<string>();\n for (const measurement of event.measurements) {\n const nodeIndex = nodeIndices.get(measurement.id);\n if (nodeIndex !== undefined) {\n const node = draft.graph.nodes[nodeIndex];\n candidateNodes.add(node.id);\n // Only nodes whose size the DOM owns (autoSize) record a measured\n // size. It lands on `measured` — never on the authored\n // `width`/`height` — so the model is never clobbered (writing\n // measured back onto the authored box fed a render → measure →\n // render growth loop). `resolvedSize` derives geometry from it.\n if (resolveAppearance(node, draft.appearances).autoSize) {\n const previousSize = resolvedSize(node);\n const previousOffset = node.measured?.anchorOffset ?? {\n x: 0,\n y: 0,\n };\n const anchor = resolveAutoSizeAnchor(node.autoSizeAnchor);\n const nextSize = {\n width: node.style?.customWidth ?? measurement.rect.width,\n height: node.style?.customHeight ?? measurement.rect.height,\n };\n const delta = {\n x: (previousSize.width - nextSize.width) * anchor.x,\n y: (previousSize.height - nextSize.height) * anchor.y,\n };\n const anchorOffset = {\n x: previousOffset.x + delta.x,\n y: previousOffset.y + delta.y,\n };\n // A ResizeObserver reports the pre-transition DOM position.\n // Store the position Flow will render after applying the\n // anchor correction, so geometry is immediately coherent and\n // a position-only follow-up measurement is unnecessary.\n const normalizedRect = {\n x: anchor.x === 0 ? measurement.rect.x : node.x + delta.x + (node.dx ?? 0),\n y: anchor.y === 0 ? measurement.rect.y : node.y + delta.y + (node.dy ?? 0),\n width: measurement.rect.width,\n height: measurement.rect.height,\n };\n const existing = draft.measurements.get(measurement.id);\n if (\n delta.x === 0 &&\n delta.y === 0 &&\n node.measured?.appearanceKey === JSON.stringify(node.appearance ?? null) &&\n node.measured?.width === measurement.rect.width &&\n node.measured?.height === measurement.rect.height &&\n previousOffset.x === anchorOffset.x &&\n previousOffset.y === anchorOffset.y &&\n existing?.x === normalizedRect.x &&\n existing.y === normalizedRect.y &&\n existing.width === normalizedRect.width &&\n existing.height === normalizedRect.height\n ) {\n continue;\n }\n\n node.measured = {\n width: measurement.rect.width,\n height: measurement.rect.height,\n appearanceAutoSize: resolveAppearance(node, draft.appearances).autoSize,\n appearanceKey: JSON.stringify(node.appearance ?? null),\n ...(anchorOffset.x !== 0 || anchorOffset.y !== 0 ? { anchorOffset } : {}),\n };\n node.x += delta.x;\n node.y += delta.y;\n draft.measurements.set(measurement.id, normalizedRect);\n } else {\n draft.measurements.set(measurement.id, measurement.rect);\n }\n continue;\n }\n\n draft.measurements.set(measurement.id, measurement.rect);\n if (measurement.id.startsWith('[\"flow-appearance-boundary\",')) {\n const [, id] = JSON.parse(measurement.id) as [string, string];\n if (nodeIndices.has(id)) boundaryNodes.add(id);\n const labelIndex = edgeIndices.get(id);\n if (!event.derivedOnly && labelIndex !== undefined) invalidateAuthoritativeEdgePath(draft.graph.edges[labelIndex]);\n }\n\n const edgeIndex = edgeIndices.get(measurement.id);\n const edge =\n edgeIndex === undefined ? undefined : draft.graph.edges[edgeIndex];\n if (edge?.label) {\n if (!event.derivedOnly && resolveAppearance(edge.label, draft.appearances).registered) invalidateAuthoritativeEdgePath(edge);\n // DOM-owned labels keep measured geometry transient. External\n // graph replacement can safely restore authored fallback sizes\n // without starting a measure/render oscillation.\n if (!event.derivedOnly && !resolveAppearance(edge.label, draft.appearances).autoSize && !resolveAppearance(edge.label, draft.appearances).registered && !edge.label.appearance) {\n edge.label.width = measurement.rect.width;\n edge.label.height = measurement.rect.height;\n }\n continue;\n }\n\n const portTarget = portIndices.get(measurement.id);\n if (portTarget && event.derivedOnly) {\n const candidate = ctx.graph.nodes[portTarget.nodeIndex];\n const origin = measurement.origin ?? snappedBounds(candidate, ctx.snapToGrid ? ctx.snapGrid : null);\n draft.derivedPortMeasurements.set(measurement.id, {\n ...measurement.rect,\n x: measurement.rect.x - origin.x,\n y: measurement.rect.y - origin.y,\n });\n } else if (portTarget) {\n draft.derivedPortMeasurements.delete(measurement.id);\n const candidate = draft.graph.nodes[portTarget.nodeIndex];\n candidateNodes.add(candidate.id);\n const port = candidate.ports?.[portTarget.portIndex];\n if (!port) continue;\n // The DOM bridge captures the rendered origin, including group\n // geometry and animation. Raw measurements without an origin\n // retain the authored, grid-snapped coordinate contract.\n const origin = measurement.origin ?? snappedBounds(\n candidate,\n draft.snapToGrid ? draft.snapGrid : null,\n );\n port.x = measurement.rect.x - origin.x;\n port.y = measurement.rect.y - origin.y;\n port.width = measurement.rect.width;\n port.height = measurement.rect.height;\n }\n }\n for (const id of candidateNodes) {\n const index = nodeIndices.get(id)!;\n if (nodeEndpointGeometryChanged(ctx.graph.nodes[index], draft.graph.nodes[index])) boundaryNodes.add(id);\n }\n if (!event.derivedOnly && boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);\n });\n },\n\n removeMeasurements: (ctx, event: { ids: string[]; derivedOnly?: boolean }) =>\n produce(ctx, (draft) => {\n const boundaryNodes = new Set<string>();\n for (const id of event.ids) {\n const removed = draft.measurements.delete(id);\n draft.derivedPortMeasurements.delete(id);\n const node = draft.graph.nodes.find((candidate) => candidate.id === id);\n if (node?.measured) {\n node.x -= node.measured.anchorOffset?.x ?? 0;\n node.y -= node.measured.anchorOffset?.y ?? 0;\n delete node.measured;\n boundaryNodes.add(id);\n }\n if (!removed) continue;\n if (id.startsWith('[\"flow-appearance-boundary\",')) {\n const [, entityId] = JSON.parse(id) as [string, string];\n boundaryNodes.add(entityId);\n const edge = draft.graph.edges.find((candidate) => candidate.id === entityId);\n if (!event.derivedOnly && edge) invalidateAuthoritativeEdgePath(edge);\n }\n }\n if (!event.derivedOnly && boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);\n }),\n\n // Edge labels\n\n bakeLabelPositions: (\n ctx,\n event: { positions: Map<string, Point> } & TransactionMetadata,\n enqueue\n ) =>\n produce(ctx, (draft) => {\n for (const [edgeId, center] of event.positions) {\n const edge = draft.graph.edges.find((e) => e.id === edgeId);\n if (edge?.label) {\n const size = resolvedEdgeLabelSize(\n edge.label,\n (draft.measurements as Map<string, Rect>).get(edge.id)\n );\n edge.label.x = center.x - size.width / 2;\n edge.label.y = center.y - size.height / 2;\n edge.label.dx = 0;\n edge.label.dy = 0;\n }\n }\n enqueue.emit.graphChanged({\n graph: snapshotGraph(draft.graph),\n event: createEventObject('bakeLabelPositions', event),\n });\n }),\n\n reportError: (ctx, event: FlowErrorEvent, enqueue) => {\n enqueue.emit.error(event);\n return ctx;\n },\n },\n }).with(\n undoRedo({\n strategy: 'snapshot',\n historyLimit: options.historyLimit ?? 100,\n getTransactionId: (event) => (event as UndoableStoreEvent).transactionId,\n skipEvent: (event, snapshot) =>\n !shouldTrackUndoEvent(event, snapshot as UndoableStoreSnapshot),\n restore: ({ current, next, direction }, enqueue) => {\n const restored = restoreHistoryContext(current, next);\n enqueue.emit.graphChanged({\n graph: restored.graph,\n event: createEventObject(direction, undefined),\n });\n if (\n current.selection.size !== restored.selection.size ||\n [...current.selection].some((id) => !restored.selection.has(id))\n ) {\n enqueue.emit.selectionChanged({\n selection: new Set(restored.selection),\n event: createEventObject(direction, undefined),\n });\n }\n return restored;\n },\n })\n );\n\n return storeWithHistory.with(resetGraphReplacementHistory);\n}\n\nexport type FlowStore = ReturnType<typeof createFlowStore>;\n\nexport function areNodesMeasured(context: FlowStoreContext): boolean {\n return context.graph.nodes.every((node) => {\n if (node.hidden || !resolveAppearance(node, context.appearances).autoSize) return true;\n return context.measurements.has(node.id) || node.measured !== undefined;\n });\n}\n\n// Container attachment (auto-sync viewportSize via ResizeObserver)\n","import { getEdgeOwner } from './hierarchy';\nimport type { FlowGraph, FlowNode } from './types';\n\nexport type FlowViewScope = Readonly<{\n /** Null addresses the graph's virtual root. */\n parentId: string | null;\n /** Descendant levels to expose. Zero is empty; null is unlimited. */\n depth: number | null;\n}>;\n\nexport type FlowViewSelectionPolicy = 'prune' | 'clear';\n\nexport type FlowViewEndpoint = Readonly<{\n originalId: string;\n viewId: string;\n boundary: boolean;\n}>;\n\nexport type FlowViewBoundaryEndpoints = Readonly<{\n edgeId: string;\n source: FlowViewEndpoint;\n target: FlowViewEndpoint;\n}>;\n\nexport type FlowViewEntities<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = Readonly<{\n nodes: readonly FlowGraph<TNodeData, TEdgeData, TLabelData>['nodes'][number][];\n edges: readonly FlowGraph<TNodeData, TEdgeData, TLabelData>['edges'][number][];\n boundaryEndpoints: readonly FlowViewBoundaryEndpoints[];\n}>;\n\ntype DeriveFlowViewOptions<TNodeData, TEdgeData, TLabelData> = {\n nodes?: readonly FlowGraph<TNodeData, TEdgeData, TLabelData>['nodes'][number][];\n edges?: readonly FlowGraph<TNodeData, TEdgeData, TLabelData>['edges'][number][];\n edgeOwner?: (\n edge: FlowGraph<TNodeData, TEdgeData, TLabelData>['edges'][number],\n ) => string | null;\n};\n\nfunction relativeDepth(\n nodeId: string,\n parentId: string | null,\n nodes: ReadonlyMap<string, FlowNode>,\n): number | null {\n let current = nodes.get(nodeId);\n let depth = 0;\n const seen = new Set<string>();\n while (current && !seen.has(current.id)) {\n if (current.id === parentId) return depth;\n seen.add(current.id);\n depth += 1;\n if (current.parentId == null) return parentId === null ? depth : null;\n current = nodes.get(current.parentId);\n }\n return null;\n}\n\nfunction endpointAtDepth(\n nodeId: string,\n scope: FlowViewScope,\n nodes: ReadonlyMap<string, FlowNode>,\n): string | null {\n const initialDepth = relativeDepth(nodeId, scope.parentId, nodes);\n if (initialDepth === null || initialDepth === 0 || scope.depth === 0) {\n return null;\n }\n if (scope.depth === null || initialDepth <= scope.depth) return nodeId;\n\n let current = nodes.get(nodeId);\n let depth = initialDepth;\n while (current && depth > scope.depth) {\n current = current.parentId ? nodes.get(current.parentId) : undefined;\n depth -= 1;\n }\n return current?.id ?? null;\n}\n\nfunction ownerIsExposed(\n ownerId: string | null,\n scope: FlowViewScope,\n nodes: ReadonlyMap<string, FlowNode>,\n): boolean {\n if (ownerId === scope.parentId) return true;\n if (ownerId === null) return false;\n const depth = relativeDepth(ownerId, scope.parentId, nodes);\n if (depth === null || depth === 0) return false;\n return scope.depth === null || depth < scope.depth;\n}\n\nfunction frozenEndpoint(\n originalId: string,\n viewId: string,\n): FlowViewEndpoint {\n return Object.freeze({\n originalId,\n viewId,\n boundary: originalId !== viewId,\n });\n}\n\n/** Derive a structural view without mutating the canonical graph. */\nexport function deriveFlowView<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n scope: FlowViewScope,\n options: DeriveFlowViewOptions<TNodeData, TEdgeData, TLabelData> = {},\n): FlowViewEntities<TNodeData, TEdgeData, TLabelData> {\n const allNodes = new Map(\n graph.nodes.map((node) => [node.id, node as FlowNode]),\n );\n const candidateNodes = options.nodes ?? graph.nodes;\n const candidateNodeIds = new Set(candidateNodes.map((node) => node.id));\n const nodes = candidateNodes.filter((node) => {\n const depth = relativeDepth(node.id, scope.parentId, allNodes);\n return (\n depth !== null &&\n depth > 0 &&\n candidateNodeIds.has(node.id) &&\n (scope.depth === null || depth <= scope.depth)\n );\n });\n const viewNodeIds = new Set(nodes.map((node) => node.id));\n const edges: FlowViewEntities<TNodeData, TEdgeData, TLabelData>['edges'][number][] = [];\n const boundaryEndpoints: FlowViewBoundaryEndpoints[] = [];\n\n for (const edge of options.edges ?? graph.edges) {\n const customOwner = options.edgeOwner?.(edge);\n const owner = customOwner === undefined\n ? getEdgeOwner(edge, graph.nodes)\n : customOwner;\n if (!ownerIsExposed(owner, scope, allNodes)) continue;\n const sourceId = endpointAtDepth(edge.sourceId, scope, allNodes);\n const targetId = endpointAtDepth(edge.targetId, scope, allNodes);\n if (\n !sourceId ||\n !targetId ||\n !viewNodeIds.has(sourceId) ||\n !viewNodeIds.has(targetId)\n ) {\n continue;\n }\n if (sourceId === targetId && edge.sourceId !== edge.targetId) continue;\n\n const source = frozenEndpoint(edge.sourceId, sourceId);\n const target = frozenEndpoint(edge.targetId, targetId);\n const boundary = Object.freeze({ edgeId: edge.id, source, target });\n boundaryEndpoints.push(boundary);\n if (!source.boundary && !target.boundary) {\n edges.push(edge);\n continue;\n }\n edges.push(Object.freeze({\n ...edge,\n sourceId,\n targetId,\n sourcePort: source.boundary ? undefined : edge.sourcePort,\n targetPort: target.boundary ? undefined : edge.targetPort,\n }));\n }\n\n return Object.freeze({\n nodes: Object.freeze([...nodes]),\n edges: Object.freeze(edges),\n boundaryEndpoints: Object.freeze(boundaryEndpoints),\n });\n}\n","export function normalizeGeometryPosition(\n value: number,\n precision: 0 | 1 | 2 | 3 | 4 | 5 | 6 | null = 0\n): number {\n if (!Number.isFinite(value)) throw new TypeError('Position must be finite.');\n if (precision === null) return value || 0;\n if (!Number.isInteger(precision) || precision < 0 || precision > 6) {\n throw new TypeError(\n 'positionPrecision must be null or an integer from 0 to 6.'\n );\n }\n return Math.round(value * 10 ** precision) / 10 ** precision || 0;\n}\n","import type { FlowChangeSet } from './changeSet';\nimport type {\n CreateEdgeInput,\n CreateNodeInput,\n FlowController,\n FlowGeometryOptions,\n FlowTransactionOptions,\n} from './createFlow';\nimport { normalizeGeometryPosition } from './geometry';\nimport type { FlowEdge, FlowNode, Point, Rect, Size } from './types';\nimport { FlowGraphValidationError, type FlowResult } from './validation';\n\nexport type FlowExternalEditOperation<\n TNodeData = unknown,\n TEdgeData = unknown,\n TLabelData = unknown\n> =\n | { kind: 'node.create'; node: CreateNodeInput<TNodeData> & { id: string } }\n | { kind: 'node.delete'; id: string }\n | {\n kind: 'node.move';\n id: string;\n position: Partial<Point>;\n options?: FlowGeometryOptions;\n }\n | {\n kind: 'node.resize';\n id: string;\n bounds: Partial<Rect>;\n options?: FlowGeometryOptions;\n }\n | {\n kind: 'node.contentSize';\n id: string;\n size: Partial<Size>;\n position?: Partial<Point>;\n options?: FlowGeometryOptions;\n }\n | {\n kind: 'node.data';\n id: string;\n update: (data: TNodeData, node: FlowNode<TNodeData>) => TNodeData;\n }\n | {\n kind: 'edge.create';\n edge: CreateEdgeInput<TEdgeData, TLabelData> & { id: string };\n }\n | { kind: 'edge.delete'; id: string }\n | {\n kind: 'edge.reconnect';\n id: string;\n endpoints: {\n sourceId?: string;\n targetId?: string;\n sourcePort?: string | null;\n targetPort?: string | null;\n };\n }\n | {\n kind: 'edge.data';\n id: string;\n update: (\n data: TEdgeData,\n edge: FlowEdge<TEdgeData, TLabelData>\n ) => TEdgeData;\n };\n\nexport type FlowExternalEdit<\n TNodeData = unknown,\n TEdgeData = unknown,\n TLabelData = unknown\n> = {\n commit: (\n operations: readonly FlowExternalEditOperation<\n TNodeData,\n TEdgeData,\n TLabelData\n >[],\n options?: FlowTransactionOptions\n ) => FlowResult<FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null>;\n cancel: () => void;\n dispose: () => void;\n};\n\n/** Native hosts own previews. Supplied fields differing from the baseline win at commit. */\nexport function createFlowExternalEdit<TNodeData, TEdgeData, TLabelData>(\n flow: FlowController<TNodeData, TEdgeData, TLabelData>,\n options: FlowTransactionOptions = {}\n): FlowExternalEdit<TNodeData, TEdgeData, TLabelData> {\n const graph = flow.getContext().graph;\n const baselineNodes = new Map(\n graph.nodes.map((node) => [node.id, flow.getBounds(node.id)])\n );\n const baselineEdges = new Map(\n graph.edges.map((edge) => [\n edge.id,\n {\n sourceId: edge.sourceId,\n targetId: edge.targetId,\n sourcePort: edge.sourcePort,\n targetPort: edge.targetPort,\n },\n ])\n );\n const removedNodes = new Set<string>();\n const removedEdges = new Set<string>();\n let closed = false;\n let disposed = false;\n const commits = flow.on('commit', ({ changeSet }) => {\n for (const node of changeSet.nodes.removed) removedNodes.add(node.id);\n for (const edge of changeSet.edges.removed) removedEdges.add(edge.id);\n });\n const destruction = flow.on('destroy', () => dispose());\n function dispose() {\n if (disposed) return;\n disposed = true;\n closed = true;\n commits.unsubscribe();\n destruction.unsubscribe();\n baselineNodes.clear();\n baselineEdges.clear();\n removedNodes.clear();\n removedEdges.clear();\n }\n function failure(message: string): FlowResult<never> {\n return {\n ok: false,\n error: new FlowGraphValidationError([\n { code: 'external_edit_failed', path: '$', message },\n ]),\n };\n }\n return {\n cancel: dispose,\n dispose,\n commit(operations, commitOptions) {\n if (closed) return failure('Flow external edit session is closed.');\n closed = true;\n try {\n if (operations.length && !flow.can('edit'))\n return failure('Flow external edits are not allowed.');\n const finalFields = new Map<string, unknown>();\n for (const operation of operations) {\n const fields =\n operation.kind === 'node.move'\n ? operation.position\n : operation.kind === 'node.resize'\n ? operation.bounds\n : operation.kind === 'node.contentSize'\n ? { ...operation.size, ...operation.position }\n : operation.kind === 'edge.reconnect'\n ? operation.endpoints\n : undefined;\n if (!fields || !('id' in operation)) continue;\n const kind = operation.kind.startsWith('node.') ? 'node' : 'edge';\n for (const [key, value] of Object.entries(fields)) {\n if (value !== undefined)\n finalFields.set(`${kind}:${operation.id}:${key}`, value);\n }\n }\n function reconcile<T>(\n id: string,\n key: string,\n value: T | undefined,\n baseline: T,\n current: T,\n fresh = false\n ): T {\n if (fresh) return value === undefined ? current : value;\n if (\n value === undefined ||\n finalFields.get(`${id}:${key}`) === baseline ||\n value === baseline\n )\n return current;\n return value;\n }\n const result = flow.transaction(\n (draft) => {\n const createdNodes = new Set<string>();\n const createdEdges = new Set<string>();\n for (const operation of operations) {\n switch (operation.kind) {\n case 'node.create':\n if (removedNodes.has(operation.node.id)) break;\n draft.nodes.create(operation.node);\n createdNodes.add(operation.node.id);\n break;\n case 'edge.create':\n if (removedEdges.has(operation.edge.id)) break;\n draft.edges.create(operation.edge);\n createdEdges.add(operation.edge.id);\n break;\n case 'node.delete':\n case 'node.move':\n case 'node.resize':\n case 'node.contentSize':\n case 'node.data': {\n const { id } = operation;\n if (\n !createdNodes.has(id) &&\n (!baselineNodes.has(id) || removedNodes.has(id))\n )\n break;\n const node = draft.getNode(id);\n if (!node) break;\n if (operation.kind === 'node.delete') {\n draft.nodes.delete(id);\n break;\n }\n if (operation.kind === 'node.data') {\n draft.nodes.setData(id, operation.update);\n break;\n }\n const current = draft.getNodeBounds(id);\n if (!current) break;\n const baseline = createdNodes.has(id)\n ? current\n : baselineNodes.get(id) ?? current;\n const supplied =\n operation.kind === 'node.move'\n ? operation.position\n : operation.kind === 'node.resize'\n ? operation.bounds\n : { ...operation.size, ...operation.position };\n const next = { ...current };\n for (const key of ['x', 'y', 'width', 'height'] as const) {\n const raw = supplied[key as keyof typeof supplied] as\n | number\n | undefined;\n const value =\n baselineNodes.has(id) && !createdNodes.has(id)\n ? reconcile(\n `node:${id}`,\n key,\n raw,\n baseline[key],\n current[key]\n )\n : raw ?? current[key];\n next[key] =\n raw !== undefined &&\n raw !== baseline[key] &&\n value !== current[key] &&\n (key === 'x' || key === 'y')\n ? normalizeGeometryPosition(\n value,\n operation.options?.positionPrecision\n )\n : value;\n }\n const moved = next.x !== current.x || next.y !== current.y;\n const resized =\n next.width !== current.width ||\n next.height !== current.height;\n const geometryOptions = {\n ...operation.options,\n positionPrecision: null,\n };\n if (operation.kind === 'node.move') {\n if (moved) draft.nodes.move(id, next, geometryOptions);\n } else if (operation.kind === 'node.resize') {\n if (moved || resized)\n draft.nodes.resize(id, next, geometryOptions);\n } else if (moved || resized) {\n draft.nodes.setContentSize(id, next, {\n ...geometryOptions,\n ...(moved ? { position: { x: next.x, y: next.y } } : {}),\n });\n }\n break;\n }\n case 'edge.delete':\n case 'edge.reconnect':\n case 'edge.data': {\n const { id } = operation;\n if (\n !createdEdges.has(id) &&\n (!baselineEdges.has(id) || removedEdges.has(id))\n )\n break;\n const edge = draft.getEdge(id);\n if (!edge) break;\n if (operation.kind === 'edge.delete') {\n draft.edges.delete(id);\n } else if (operation.kind === 'edge.data') {\n draft.edges.setData(id, operation.update);\n } else {\n const baseline = baselineEdges.get(id) ?? edge;\n const endpoints = operation.endpoints;\n const sourceId = reconcile(\n `edge:${id}`,\n 'sourceId',\n endpoints.sourceId,\n baseline.sourceId,\n edge.sourceId,\n createdEdges.has(id)\n );\n const targetId = reconcile(\n `edge:${id}`,\n 'targetId',\n endpoints.targetId,\n baseline.targetId,\n edge.targetId,\n createdEdges.has(id)\n );\n const sourcePort = reconcile(\n `edge:${id}`,\n 'sourcePort',\n endpoints.sourcePort,\n baseline.sourcePort ?? null,\n edge.sourcePort ?? null,\n createdEdges.has(id)\n );\n const targetPort = reconcile(\n `edge:${id}`,\n 'targetPort',\n endpoints.targetPort,\n baseline.targetPort ?? null,\n edge.targetPort ?? null,\n createdEdges.has(id)\n );\n if (\n sourceId !== edge.sourceId ||\n targetId !== edge.targetId ||\n sourcePort !== (edge.sourcePort ?? null) ||\n targetPort !== (edge.targetPort ?? null)\n ) {\n draft.edges.reconnect(id, {\n newSourceId: sourceId,\n newTargetId: targetId,\n newSourcePort: sourcePort,\n newTargetPort: targetPort,\n });\n }\n }\n break;\n }\n default: {\n const exhaustive: never = operation;\n throw new Error(`Unknown external operation: ${exhaustive}`);\n }\n }\n }\n },\n { ...options, ...commitOptions }\n );\n return { ok: true, value: result.changeSet };\n } catch (error) {\n if (error instanceof FlowGraphValidationError)\n return { ok: false, error };\n return failure(error instanceof Error ? error.message : String(error));\n } finally {\n dispose();\n }\n },\n };\n}\n","import type { FlowController } from './createFlow';\n\nexport type FlowRenderInvalidation = {\n revision: number;\n reason: 'context' | 'projection' | 'commit';\n /** Notifications conservatively invalidate every rendered entity. */\n all: true;\n};\n\nexport type FlowRenderApi = {\n subscribe: (\n listener: (invalidation: FlowRenderInvalidation) => void\n ) => () => void;\n dispose: () => void;\n};\n\n/** Synchronous invalidation only; renderers own frame scheduling and coalescing. */\nexport function createFlowRenderApi<TNodeData, TEdgeData, TLabelData>(\n flow: FlowController<TNodeData, TEdgeData, TLabelData>\n): FlowRenderApi {\n const listeners = new Set<(invalidation: FlowRenderInvalidation) => void>();\n let revision = 0;\n let disposed = false;\n const notify = (reason: FlowRenderInvalidation['reason']) => {\n if (disposed) return;\n const event: FlowRenderInvalidation = {\n revision: ++revision,\n reason,\n all: true,\n };\n for (const listener of listeners) listener(event);\n };\n const context = flow.subscribe(() => notify('context'));\n const projection = flow.projections.subscribe(() => notify('projection'));\n const commits = flow.on('commit', () => notify('commit'));\n const destruction = flow.on('destroy', () => dispose());\n function dispose() {\n if (disposed) return;\n disposed = true;\n context();\n projection();\n commits.unsubscribe();\n destruction.unsubscribe();\n listeners.clear();\n }\n return {\n subscribe(listener) {\n if (!disposed) listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose,\n };\n}\n","import type { Direction, Point, Rect, ShapeHandler } from '../types';\n\n\n// Shape handlers\n//\n// Shapes are engine logic: hit testing + edge anchoring.\n// Renderers handle drawing.\n\n\nconst shapeRegistry = new Map<string, ShapeHandler>();\n\nexport function registerShape(name: string, handler: ShapeHandler): void {\n shapeRegistry.set(name, handler);\n}\n\nexport function getShape(name: string): ShapeHandler | undefined {\n return shapeRegistry.get(name);\n}\n\nexport function getShapeOrDefault(name: string): ShapeHandler {\n return shapeRegistry.get(name) ?? rectHandler;\n}\n\n\n// Built-in: rect\n\n\nfunction rectHitTest(point: Point, bounds: Rect): boolean {\n return (\n point.x >= bounds.x &&\n point.x <= bounds.x + bounds.width &&\n point.y >= bounds.y &&\n point.y <= bounds.y + bounds.height\n );\n}\n\nfunction rectEdgeAnchor(bounds: Rect, direction: Direction): Point {\n switch (direction) {\n case 'top':\n return { x: bounds.x + bounds.width / 2, y: bounds.y };\n case 'bottom':\n return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height };\n case 'left':\n return { x: bounds.x, y: bounds.y + bounds.height / 2 };\n case 'right':\n return { x: bounds.x + bounds.width, y: bounds.y + bounds.height / 2 };\n }\n}\n\nconst rectHandler: ShapeHandler = {\n hitTest: rectHitTest,\n edgeAnchor: rectEdgeAnchor,\n};\n\n\n// Built-in: rounded (same geometry as rect for hit/anchor, renderer rounds corners)\n\n\nconst roundedHandler: ShapeHandler = {\n hitTest: rectHitTest,\n edgeAnchor: rectEdgeAnchor,\n};\n\n\n// Built-in: ellipse\n\n\nfunction ellipseHitTest(point: Point, bounds: Rect): boolean {\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n const rx = bounds.width / 2;\n const ry = bounds.height / 2;\n if (rx === 0 || ry === 0) return false;\n const dx = point.x - cx;\n const dy = point.y - cy;\n return (dx * dx) / (rx * rx) + (dy * dy) / (ry * ry) <= 1;\n}\n\nfunction ellipseEdgeAnchor(bounds: Rect, direction: Direction): Point {\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n const rx = bounds.width / 2;\n const ry = bounds.height / 2;\n switch (direction) {\n case 'top':\n return { x: cx, y: cy - ry };\n case 'bottom':\n return { x: cx, y: cy + ry };\n case 'left':\n return { x: cx - rx, y: cy };\n case 'right':\n return { x: cx + rx, y: cy };\n }\n}\n\nconst ellipseHandler: ShapeHandler = {\n hitTest: ellipseHitTest,\n edgeAnchor: ellipseEdgeAnchor,\n};\n\n\n// Built-in: diamond\n\n\nfunction diamondHitTest(point: Point, bounds: Rect): boolean {\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n const hw = bounds.width / 2;\n const hh = bounds.height / 2;\n if (hw === 0 || hh === 0) return false;\n // Manhattan distance normalized to diamond\n return Math.abs(point.x - cx) / hw + Math.abs(point.y - cy) / hh <= 1;\n}\n\nfunction diamondEdgeAnchor(bounds: Rect, direction: Direction): Point {\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n switch (direction) {\n case 'top':\n return { x: cx, y: bounds.y };\n case 'bottom':\n return { x: cx, y: bounds.y + bounds.height };\n case 'left':\n return { x: bounds.x, y: cy };\n case 'right':\n return { x: bounds.x + bounds.width, y: cy };\n }\n}\n\nconst diamondHandler: ShapeHandler = {\n hitTest: diamondHitTest,\n edgeAnchor: diamondEdgeAnchor,\n};\n\n\n// Register built-in shapes\n\n\nregisterShape('rect', rectHandler);\nregisterShape('rounded', roundedHandler);\nregisterShape('ellipse', ellipseHandler);\nregisterShape('diamond', diamondHandler);\n","import type { FlowEdge, FlowGraph, Rect } from '../types';\n\n// Router read tracking\n//\n// A custom router may read anything on the edge and the routing graph. To\n// reuse its paths across graph changes that it never looked at (a node's\n// color, say), the routing pass hands it read-only proxies that record every\n// field read, `in` check, and key listing, keyed by entity so the check can\n// resolve them in the next graph. Reads are recorded for the whole pass, not\n// per call, because routers may share work across calls (batch caches). A view\n// the router hands back in its result is swapped for the raw value, and its\n// whole value becomes a dependency.\n\nexport type RouterRead = {\n /** `graph`, `node:<id>`, or `edge:<id>`. */\n root: string;\n path: readonly string[];\n op: 'get' | 'has' | 'keys' | 'value';\n value: unknown;\n};\n\nexport type RouterReadLog = {\n reads: RouterRead[];\n bounds: Map<string, Rect | undefined>;\n};\n\nconst OBJECT = '[object]';\nconst ARRAY = '[array]';\nconst FUNCTION = '[function]';\n\nfunction entityRootFor(root: string, path: readonly string[], value: unknown): string | null {\n if (root !== 'graph' || path.length !== 1) return null;\n if (!value || typeof value !== 'object') return null;\n const id = (value as { id?: unknown }).id;\n if (typeof id !== 'string') return null;\n if (path[0] === 'nodes') return `node:${id}`;\n if (path[0] === 'edges') return `edge:${id}`;\n return null;\n}\n\nfunction classify(root: string, path: readonly string[], value: unknown): unknown {\n const entityRoot = entityRootFor(root, path, value);\n if (entityRoot) return entityRoot;\n if (typeof value === 'function') return FUNCTION;\n if (value && typeof value === 'object') return Array.isArray(value) ? ARRAY : OBJECT;\n return value;\n}\n\nfunction stringKeys(value: object): string {\n return Reflect.ownKeys(value)\n .filter((key): key is string => typeof key === 'string')\n .join('\\u0000');\n}\n\n/**\n * Read-only views of `graph` and its entities that log what a router reads.\n * Views are stable for the tracker's lifetime, so routers that cache by\n * object identity see the same graph and entity objects across calls.\n */\nexport function createRouterReadTracker(\n graph: FlowGraph,\n getEntityBounds: (id: string) => Readonly<Rect> | undefined,\n) {\n const log: RouterReadLog = { reads: [], bounds: new Map() };\n const entityViews = new Map<string, object>();\n const sources = new WeakMap<object, { raw: object; root: string; path: readonly string[] }>();\n\n const view = (raw: object, root: string, path: readonly string[]): object => {\n const children = new Map<string, unknown>();\n const logged = new Set<string>();\n const record = (op: RouterRead['op'], key: string | null, value: unknown) => {\n const id = `${op}\\u0000${key ?? ''}`;\n if (logged.has(id)) return;\n logged.add(id);\n log.reads.push({ root, path: key === null ? path : [...path, key], op, value });\n };\n const child = (key: string): unknown => {\n if (children.has(key)) return children.get(key);\n const value = (raw as Record<string, unknown>)[key];\n let result = value;\n if (value && typeof value === 'object') {\n const entityRoot = entityRootFor(root, path, value);\n result = entityRoot\n ? entityView(entityRoot, value)\n : view(value, root, [...path, key]);\n }\n children.set(key, result);\n return result;\n };\n const proxy = new Proxy(Array.isArray(raw) ? [] : {}, {\n get(_target, key) {\n if (typeof key === 'symbol') return Reflect.get(raw, key);\n record('get', key, classify(root, path, (raw as Record<string, unknown>)[key]));\n return child(key);\n },\n has(_target, key) {\n const result = Reflect.has(raw, key);\n if (typeof key === 'string') record('has', key, result);\n return result;\n },\n ownKeys() {\n record('keys', null, stringKeys(raw));\n return Reflect.ownKeys(raw);\n },\n getOwnPropertyDescriptor(_target, key) {\n const descriptor = Reflect.getOwnPropertyDescriptor(raw, key);\n if (typeof key === 'string') {\n // `Object.hasOwn` and descriptor reads skip the `has` and `get` traps.\n record('has', key, descriptor !== undefined);\n if (descriptor) {\n record('get', key, classify(root, path, (raw as Record<string, unknown>)[key]));\n }\n }\n if (!descriptor) return undefined;\n if (Array.isArray(raw) && key === 'length') {\n return { value: raw.length, writable: true, enumerable: false, configurable: false };\n }\n return {\n value: typeof key === 'string' ? child(key) : Reflect.get(raw, key),\n writable: false,\n enumerable: descriptor.enumerable,\n configurable: true,\n };\n },\n getPrototypeOf() {\n return Reflect.getPrototypeOf(raw);\n },\n set() {\n return false;\n },\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n });\n sources.set(proxy, { raw, root, path });\n return proxy;\n };\n\n const release = (value: unknown): unknown => {\n if (!value || typeof value !== 'object') return value;\n const source = sources.get(value);\n if (source) {\n log.reads.push({ root: source.root, path: source.path, op: 'value', value: source.raw });\n return source.raw;\n }\n if (Array.isArray(value)) {\n const next = value.map(release);\n return next.some((entry, index) => entry !== value[index]) ? next : value;\n }\n if (Object.getPrototypeOf(value) !== Object.prototype) return value;\n let changed = false;\n const next: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n next[key] = release(entry);\n if (next[key] !== entry) changed = true;\n }\n return changed ? next : value;\n };\n\n const entityView = (root: string, raw: object): object => {\n let existing = entityViews.get(root);\n if (!existing) {\n existing = view(raw, root, []);\n entityViews.set(root, existing);\n }\n return existing;\n };\n\n return {\n log,\n graph: view(graph, 'graph', []) as FlowGraph,\n edge: (edge: FlowEdge): FlowEdge => entityView(`edge:${edge.id}`, edge) as FlowEdge,\n /** Swap any views in a router result for raw values, logging them as reads. */\n release: <T>(result: T): T => release(result) as T,\n getEntityBounds: (id: string): Readonly<Rect> | undefined => {\n const bounds = getEntityBounds(id);\n if (!log.bounds.has(id)) log.bounds.set(id, bounds && { ...bounds });\n return bounds;\n },\n };\n}\n\n/** Whether every logged read resolves to the same value against `graph`. */\nexport function routerReadsUnchanged(\n log: RouterReadLog,\n graph: FlowGraph,\n edgesById: ReadonlyMap<string, FlowEdge>,\n getEntityBounds: (id: string) => Readonly<Rect> | undefined,\n valuesEqual: (a: unknown, b: unknown) => boolean,\n): boolean {\n let nodesById: Map<string, unknown> | undefined;\n const resolveRoot = (root: string): unknown => {\n if (root === 'graph') return graph;\n if (root.startsWith('edge:')) return edgesById.get(root.slice(5));\n nodesById ??= new Map(graph.nodes.map((node) => [node.id, node]));\n return nodesById.get(root.slice(5));\n };\n for (const read of log.reads) {\n let current = resolveRoot(read.root);\n if (current === undefined) return false;\n if (read.op === 'value') {\n for (const key of read.path) {\n if (!current || typeof current !== 'object') return false;\n current = (current as Record<string, unknown>)[key];\n }\n if (!valuesEqual(current, read.value)) return false;\n continue;\n }\n const parentPath = read.op === 'keys' ? read.path : read.path.slice(0, -1);\n for (const key of parentPath) {\n if (!current || typeof current !== 'object') return false;\n current = (current as Record<string, unknown>)[key];\n }\n if (!current || typeof current !== 'object') return false;\n const key = read.path[read.path.length - 1]!;\n if (read.op === 'keys') {\n if (stringKeys(current) !== read.value) return false;\n } else if (read.op === 'has') {\n if (Reflect.has(current, key) !== read.value) return false;\n } else if (\n classify(read.root, parentPath, (current as Record<string, unknown>)[key]) !== read.value\n ) {\n return false;\n }\n }\n for (const [id, bounds] of log.bounds) {\n if (!valuesEqual(bounds, getEntityBounds(id))) return false;\n }\n return true;\n}\n","import type { FlowConfig } from './types';\n\n\n// Behavior config presets\n\n\n/** Default config: supported editing behaviors enabled */\nexport const defaultConfig: FlowConfig = {\n selectable: () => true,\n focusable: () => true,\n draggable: () => true,\n connectable: () => true,\n reconnectable: () => true,\n deletable: () => true,\n resizable: false,\n visible: () => true,\n};\n\n/** Readonly preset: can select and view, cannot modify */\nexport const readonlyConfig: Partial<FlowConfig> = {\n draggable: false,\n connectable: false,\n reconnectable: false,\n deletable: false,\n resizable: false,\n};\n\n/**\n * Resolve a behavior predicate.\n * If `false`, returns false. If function, calls it. If undefined, returns default.\n */\nexport function resolveBehavior<TEntity, TState>(\n predicate: ((entity: TEntity, state: TState) => boolean) | false | undefined,\n entity: TEntity,\n state: TState,\n defaultValue = true,\n): boolean {\n if (predicate === false) return false;\n if (predicate === undefined) return defaultValue;\n return predicate(entity, state);\n}\n","import { resolveAppearance, appearanceAllowsPort, appearanceDirection, appearanceMeasurementId, type FlowAppearances } from './appearances';\nimport type {\n Direction,\n EdgePathData,\n FlowConfig,\n FlowEdge,\n FlowEdgeLabel,\n FlowGraph,\n FlowEntityRef,\n FlowNode,\n LabelAnchor,\n PathData,\n Point,\n Rect,\n Viewport,\n VisualPort,\n} from './types';\nimport type { FlowStore, FlowStoreContext } from './store';\nimport { screenToCanvas as _screenToCanvas, canvasToScreen as _canvasToScreen, getVisibleBounds } from './viewport';\nimport { getShapeOrDefault } from './shapes';\nimport type { EdgeRouter, EdgeRouterContext } from './routing';\nimport { bezierRouter, bestDirection, pathToSVG } from './routing';\nimport {\n createRouterReadTracker,\n routerReadsUnchanged,\n type RouterReadLog,\n} from './routing/readTracking';\nimport { resolvedPosition, resolvedBounds as baseResolvedBounds, resolvedSelectionBounds, resolvedSize as baseResolvedSize, resolvedEdgeLabelSize as baseResolvedEdgeLabelSize, snappedBounds as baseSnappedBounds, getGraphBounds, rectsIntersect, rectContains, snapToGrid, unionRect } from './spatial';\nimport { resolveBehavior } from './config';\nimport { getSnapLines } from './snap';\nimport type { SnapResult } from './snap';\nimport {\n authoritativeEdgePath,\n isPointNearPath,\n pathBounds,\n} from './edge-geometry';\nimport {\n getConnectedEdges as getGraphConnectedEdges,\n getIncomers as getGraphIncomers,\n getNeighbors as getGraphNeighbors,\n getOutgoers as getGraphOutgoers,\n indexNodes,\n indexEdges,\n indexChildren,\n nodeDepths,\n} from './graph-index';\nimport {\n deriveGroupGeometry,\n fixedGroupGeometry,\n getEdgeOwnerFromIndex as defaultEdgeOwnerFromIndex,\n isDerivedGroup,\n type GroupGeometry,\n} from './hierarchy';\n\n\n// Shared, immutable \"no folded edges\" result. Returned by `foldedEdgesFor`\n// when nothing is collapsed, avoiding a per-snapshot O(E) loop + Map alloc.\n// Callers only read (spread `.edges` / `.byId.get`), never mutate.\nconst EMPTY_FOLDED: { edges: FlowEdge[]; byId: Map<string, FlowEdge> } =\n Object.freeze({\n edges: Object.freeze([]) as unknown as FlowEdge[],\n byId: new Map<string, FlowEdge>(),\n });\n\nfunction offsetEdgeWaypoints(\n edge: FlowEdge,\n offset: Point = { x: edge.dx ?? 0, y: edge.dy ?? 0 },\n): Point[] | undefined {\n if (!edge.waypoints?.length) return edge.waypoints;\n const { x: dx, y: dy } = offset;\n if (dx === 0 && dy === 0) return edge.waypoints;\n return edge.waypoints.map((point) => ({\n x: point.x + dx,\n y: point.y + dy,\n }));\n}\n\n\n// FlowEngine — purely derived projection over FlowStore\n//\n// No mutable state. All interaction state lives in the store.\n// The engine provides computed queries and convenience accessors.\n\n\nexport type ProposedConnection = {\n sourceId: string;\n targetId: string;\n sourcePort?: string | null;\n targetPort?: string | null;\n};\n\nexport function normalizeConnection(proposed: ProposedConnection, graph: FlowGraph): ProposedConnection {\n const source = graph.nodes.find((node) => node.id === proposed.sourceId);\n const port = source?.ports?.find((port) => port.name === proposed.sourcePort);\n if (port?.direction !== 'in') return proposed;\n return {\n sourceId: proposed.targetId,\n sourcePort: proposed.targetPort,\n targetId: proposed.sourceId,\n targetPort: proposed.sourcePort,\n };\n}\n\nexport type FlowConnectionMode = 'strict' | 'loose';\n\nexport type EdgeRouterDependencies = 'graph' | 'endpoints' | 'snapshot';\n\nexport type FlowConnectionOptions = {\n /** Magnet radius in canvas pixels. Default 24. */\n radius?: number;\n /**\n * In strict mode only ports can be connection targets. Loose mode, the\n * default/current behavior, falls back to node body targets.\n */\n mode?: FlowConnectionMode;\n};\n\nexport type ConnectionCandidateSource = {\n nodeId: string;\n port: string | null;\n};\n\nexport type ConnectionCandidate = {\n nodeId: string;\n portName: string | null;\n position: Point;\n isValid: boolean;\n};\n\nexport type ConnectionCandidateOptions = FlowConnectionOptions & {\n source?: ConnectionCandidateSource;\n};\n\nexport type ConnectionValidationContext = {\n graph: FlowStoreContext['graph'];\n context: FlowStoreContext;\n source: FlowNode;\n target: FlowNode;\n sourcePort: VisualPort | null;\n targetPort: VisualPort | null;\n connection: FlowStoreContext['connection'];\n};\n\nexport type ConnectionValidationResult = boolean | { valid: boolean; reason?: string };\n\nexport type FlowEngineOptions = {\n appearances?: FlowAppearances;\n /** Default edge router (default: bezierRouter) */\n edgeRouter?: EdgeRouter;\n /**\n * Geometry read by a custom edge router. Defaults to `graph`: Flow records\n * what the router reads from the edge, the graph, `getEntityBounds`, and\n * `obstacles` during a routing pass, and reroutes every edge when any of it,\n * any call's geometry, or any other routing state (measurements,\n * appearances, selection, connection, snapping) changes. Use `snapshot`\n * when the router also reads state those views don't cover, such as\n * `flow.getNode()` or measurements through a closure: Flow then reroutes on\n * every graph or routing state change. Use `endpoints` only\n * when the router depends on the edge and its endpoint/label inputs, not\n * arbitrary `graph`, `getEntityBounds`, or `obstacles` reads. That contract\n * lets Flow retain unaffected custom routes by identity.\n */\n edgeRouterDependencies?: EdgeRouterDependencies;\n /** Default label anchor (default: 'fixed' — labels use their own x/y) */\n labelAnchor?: LabelAnchor;\n /**\n * Override the rect an edge routes from while preserving its graph source.\n * Return null/undefined to keep the normal source node/port bounds.\n */\n resolveEdgeSourceBounds?: (context: EdgeSourceBoundsContext) => Rect | null | undefined;\n /** Connection validation hook */\n canConnect?: (\n proposed: ProposedConnection,\n context: ConnectionValidationContext,\n ) => ConnectionValidationResult;\n /** Connection magnet radius and port-strict/loose targeting behavior. */\n connection?: FlowConnectionOptions;\n /** Elevate selected entities above same-depth/same-zIndex siblings. */\n elevateOnSelect?: { nodes?: boolean; edges?: boolean };\n /** Global behavior config */\n config?: Partial<FlowConfig>;\n /** Custom visibility function */\n isVisible?: (entity: FlowNode | FlowEdge, viewport: Viewport) => boolean;\n /**\n * Which node an edge belongs to (its labels contribute to that group's\n * derived child bounds). Return a node id, null for the root, or undefined\n * to fall back to the default rule: the deepest node containing both\n * endpoints (an endpoint contains itself; self-edges go to the source's\n * parent) — Stately-editor semantics.\n */\n edgeOwner?: (\n edge: FlowEdge,\n context: FlowStoreContext,\n ) => string | null | undefined;\n};\n\nexport type EdgeSourceBoundsContext = {\n edge: FlowEdge;\n graph: FlowStoreContext['graph'];\n context: FlowStoreContext;\n source: FlowNode;\n target: FlowNode;\n sourceBounds: Rect;\n targetBounds: Rect;\n getEdgeLabelBounds: (edgeId: string) => Rect | null;\n};\n\nexport type RenderableEntitiesOptions = {\n cull?: 'none' | 'viewport';\n overscan?: number;\n};\n\nexport type EntityOrderOptions = {\n /** Include configured selection elevation. Defaults to true. */\n elevateSelected?: boolean;\n};\n\nexport type EdgePathOptions = {\n graph?: FlowStoreContext['graph'];\n};\n\ntype VisualSnapInfo = {\n offset: Point;\n grid: [number, number] | null;\n selection: Set<string>;\n};\n\ntype EdgePathsCacheInputs = {\n appearances: FlowStoreContext['appearances'];\n canonicalGraph: FlowStoreContext['graph'];\n selection: Set<string>;\n collapsedNodeIds: Set<string>;\n connection: FlowStoreContext['connection'];\n offsetX: number;\n offsetY: number;\n gridX: number | null;\n gridY: number | null;\n resizingEntityId: string | null;\n resizeCorners: FlowStoreContext['resizeCorners'];\n measurements: FlowStoreContext['measurements'];\n layoutOffsets: FlowStoreContext['layoutAnimation']['offsets'];\n};\n\ntype EntityOrderCache = {\n nodesInput: FlowStoreContext['graph']['nodes'];\n edgesInput: FlowStoreContext['graph']['edges'];\n selectionInput: FlowStoreContext['selection'] | null;\n collapsedInput: FlowStoreContext['collapsedNodeIds'];\n value: { nodes: FlowNode[]; edges: FlowEdge[] };\n};\n\ntype PaintZIndices = {\n nodes: Map<string, number>;\n edges: Map<string, number>;\n};\n\ntype RenderableSpatialIndex = {\n nodesInput: FlowStoreContext['graph']['nodes'];\n pathsInput: Map<string, EdgePathData>;\n measurementsInput: FlowStoreContext['measurements'];\n layoutOffsetsInput: FlowStoreContext['layoutAnimation']['offsets'];\n collapsedInput: FlowStoreContext['collapsedNodeIds'];\n nodeCells: Map<string, string[]>;\n edgeCells: Map<string, string[]>;\n globalNodeIds: string[];\n globalEdgeIds: string[];\n nodeBounds: Map<string, Rect>;\n edgeBounds: Map<string, Rect>;\n};\n\nconst SPATIAL_CELL_SIZE = 512;\nconst MAX_ENTITY_SPATIAL_CELLS = 4_096;\n\ntype RouterCallValues = Omit<EdgeRouterContext, 'graph' | 'getEntityBounds' | 'obstacles'>;\n\ntype RouteEdge = (\n edge: FlowEdge,\n key: string,\n values: RouterCallValues,\n getObstacles: () => Rect[],\n) => PathData;\n\n// `edgeObstacles` is a function of the owner's obstacle list and the\n// endpoints' lineage, so those stand in for the obstacles a call read.\ntype RouterCallObstacles = { owner: string | null; lineage: string };\n\ntype RoutingRecord = {\n router: EdgeRouter;\n inputs: EdgePathsCacheInputs;\n log: RouterReadLog;\n owners: Map<string | null, ReadonlyArray<{ id: string; bounds: Rect }>>;\n calls: {\n key: string;\n values: RouterCallValues;\n obstacles?: RouterCallObstacles;\n result: PathData;\n }[];\n};\n\nconst REPLAY_MISS = Symbol('replay miss');\n\n/** Structural equality for plain path data (objects, arrays, primitives). */\nfunction plainDataEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n const aRecord = a as Record<string, unknown>;\n const bRecord = b as Record<string, unknown>;\n const aKeys = Object.keys(aRecord);\n return (\n aKeys.length === Object.keys(bRecord).length &&\n aKeys.every((key) => plainDataEqual(aRecord[key], bRecord[key]))\n );\n}\n\n/**\n * Create the framework-agnostic derived-geometry and query layer for a store.\n *\n * The engine owns memoized graph indices, paint order, bounds, routing, and\n * hit-testing. Returned collections are read-only views and may retain identity\n * while their semantic inputs are unchanged.\n */\nexport function createFlowEngine(store: FlowStore, initialOptions: FlowEngineOptions = {}) {\n let engineOptions = initialOptions;\n let optionsVersion = 0;\n const edgeHitTolerance = 8;\n\n function ctx(): FlowStoreContext {\n return store.getSnapshot().context;\n }\n\n // Exact per-snapshot cache plus a graph-keyed cache for snapshots whose\n // routing inputs are unchanged (notably every frame of a viewport pan).\n let snapshotEdgePathsCache = new WeakMap<\n FlowStoreContext,\n WeakMap<object, Map<string, EdgePathData>>\n >();\n let stableEdgePathsCache = new WeakMap<\n object,\n {\n inputs: EdgePathsCacheInputs;\n paths: Map<string, EdgePathData>;\n context: FlowStoreContext;\n contextReads: ReadonlySet<PropertyKey>;\n }\n >();\n // Store-context keys `resolveEdgeSourceBounds` reads while the paths being\n // cached are computed. Null outside that computation.\n let edgeSourceBoundsContextReads: Set<PropertyKey> | null = null;\n const snapOffsetCache = new WeakMap<FlowStoreContext, VisualSnapInfo>();\n let renderableCache = new WeakMap<\n FlowStoreContext,\n Map<string, { nodes: FlowNode[]; edges: FlowEdge[] }>\n >();\n let entityOrderCache: EntityOrderCache | null = null;\n let baseEntityOrderCache: EntityOrderCache | null = null;\n let paintZIndicesCache = new WeakMap<\n FlowStoreContext,\n Map<string, PaintZIndices>\n >();\n let entityRankCache: {\n order: EntityOrderCache['value'];\n nodes: Map<string, number>;\n edges: Map<string, number>;\n } | null = null;\n let renderableSpatialIndex: RenderableSpatialIndex | null = null;\n let graphBoundsCache: {\n nodesInput: FlowStoreContext['graph']['nodes'];\n edgesInput: FlowStoreContext['graph']['edges'];\n measurementsInput: FlowStoreContext['measurements'];\n value: Rect;\n } | null = null;\n let groupGeometryCache = new WeakMap<\n FlowStoreContext,\n Map<string, GroupGeometry | null>\n >();\n let visualGroupGeometryCache = new WeakMap<\n FlowStoreContext,\n Map<string, GroupGeometry | null>\n >();\n let foldedEdgesCache = new WeakMap<\n FlowStoreContext,\n { edges: FlowEdge[]; byId: Map<string, FlowEdge> }\n >();\n // Edge ownership (containment) per snapshot: owner node id → edges.\n let edgeOwnerCache = new WeakMap<\n FlowStoreContext,\n Map<string, FlowEdge[]>\n >();\n let edgeOwnerByEdgeCache = new WeakMap<\n FlowStoreContext,\n WeakMap<FlowEdge, string | null>\n >();\n let nodeIndexCache = new WeakMap<\n FlowStoreContext,\n ReadonlyMap<string, FlowNode>\n >();\n // Edge-routing obstacles per snapshot: owner id → visible sibling nodes\n // (id + bounds). Identical for every edge sharing an owner, so it's computed\n // once per owner per snapshot; `edgeObstacles` then just drops the edge's own\n // endpoints. Keyed by context (WeakMap) so it auto-invalidates each snapshot.\n let obstacleCache = new WeakMap<\n FlowStoreContext,\n Map<string, ReadonlyArray<{ id: string; bounds: Rect }>>\n >();\n // Sentinel owner key for root-level edges (owner == null).\n const ROOT_OWNER_KEY = '\\0root';\n let edgeSourceDependents = new Map<string, Set<string>>();\n\n function ownedEdges(c: FlowStoreContext): Map<string, FlowEdge[]> {\n let index = edgeOwnerCache.get(c);\n if (!index) {\n index = new Map();\n for (const edge of c.graph.edges) {\n const owner = edgeOwnerOf(edge as FlowEdge, c);\n if (owner == null) continue;\n let bucket = index.get(owner);\n if (!bucket) index.set(owner, (bucket = []));\n bucket.push(edge as FlowEdge);\n }\n edgeOwnerCache.set(c, index);\n }\n return index;\n }\n\n function edgeOwnerOf(edge: FlowEdge, c: FlowStoreContext): string | null {\n let owners = edgeOwnerByEdgeCache.get(c);\n if (!owners) {\n owners = new WeakMap();\n edgeOwnerByEdgeCache.set(c, owners);\n }\n if (owners.has(edge)) return owners.get(edge)!;\n\n // null means \"root\" (no owner); only undefined falls back.\n const custom = engineOptions.edgeOwner?.(edge, c);\n const owner = engineOptions.edgeOwner && custom !== undefined\n ? custom\n : defaultEdgeOwnerFromIndex(edge, nodesById(c));\n owners.set(edge, owner);\n return owner;\n }\n\n function nodesById(c: FlowStoreContext): ReadonlyMap<string, FlowNode> {\n let index = nodeIndexCache.get(c);\n if (!index) {\n index = indexNodes(c.graph.nodes);\n nodeIndexCache.set(c, index);\n }\n return index;\n }\n\n let appearanceSettings = ctx().appearances;\n let appearanceCache = new WeakMap<\n FlowNode | FlowEdgeLabel,\n ReturnType<typeof resolveAppearance>\n >();\n let sizedNodeCache = new WeakMap<FlowNode, FlowNode>();\n if (\n initialOptions.appearances &&\n initialOptions.appearances !== appearanceSettings\n ) {\n store.trigger.configure({ appearances: initialOptions.appearances });\n }\n function appearanceFor(entity: FlowNode | FlowEdgeLabel) {\n if (appearanceSettings !== ctx().appearances) {\n appearanceSettings = ctx().appearances;\n appearanceCache = new WeakMap();\n sizedNodeCache = new WeakMap();\n }\n let appearance = appearanceCache.get(entity);\n if (!appearance) {\n appearance = resolveAppearance(entity, appearanceSettings);\n appearanceCache.set(entity, appearance);\n }\n return appearance;\n }\n\n function sizedNode(node: FlowNode): FlowNode {\n const autoSize = appearanceFor(node).autoSize;\n const cached = sizedNodeCache.get(node);\n if (cached) return cached;\n const measured =\n node.measured?.appearanceKey !== undefined &&\n node.measured.appearanceKey !== JSON.stringify(node.appearance ?? null)\n ? undefined\n : node.measured;\n const sized =\n (node.autoSize === autoSize ||\n (!autoSize && !node.autoSize && !node.measured?.appearanceAutoSize)) &&\n measured === node.measured\n ? node\n : { ...node, autoSize, measured };\n sizedNodeCache.set(node, sized);\n return sized;\n }\n const resolvedSize = (node: FlowNode) => baseResolvedSize(sizedNode(node));\n const resolvedBounds = (node: FlowNode) => baseResolvedBounds(sizedNode(node));\n const snappedBounds = (\n node: FlowNode,\n grid: [number, number] | null,\n offset?: Point | null\n ) => baseSnappedBounds(sizedNode(node), grid, offset);\n const resolvedEdgeLabelSize = (label: FlowEdgeLabel, measurement?: Rect) =>\n baseResolvedEdgeLabelSize(\n { ...label, autoSize: appearanceFor(label).autoSize },\n measurement\n );\n\n function connectionBounds(\n id: string,\n entity: FlowNode | FlowEdgeLabel,\n visual: Rect\n ): Rect {\n const appearance = appearanceFor(entity);\n const local =\n appearance.connectionBounds ??\n (appearance.registered\n ? ctx().measurements.get(appearanceMeasurementId(id, appearance))\n : undefined);\n return local\n ? { ...local, x: visual.x + local.x, y: visual.y + local.y }\n : visual;\n }\n /** A constrained presentation must not be bypassed by graph-owned route points. */\n function resolvedAuthoritativePath(\n edge: FlowEdge,\n source = getNode(edge.sourceId),\n target = getNode(edge.targetId)\n ): PathData | null {\n const path = authoritativeEdgePath(edge);\n if (!path) return null;\n const constrained = (\n id: string,\n entity: FlowNode | FlowEdgeLabel | undefined\n ) => {\n if (!entity) return false;\n const appearance = appearanceFor(entity);\n return (\n !!appearance.connectionBounds ||\n appearance.ports !== undefined ||\n ['top', 'right', 'bottom', 'left'].some(\n (side) => !appearance.sides.includes(side as Direction)\n ) ||\n (appearance.registered &&\n ctx().measurements.has(appearanceMeasurementId(id, appearance)))\n );\n };\n return constrained(edge.sourceId, source) ||\n constrained(edge.targetId, target) ||\n constrained(edge.id, edge.label ?? undefined)\n ? null\n : path;\n }\n\n function connectionDirection(\n entity: FlowNode | FlowEdgeLabel,\n bounds: Rect,\n other: Rect\n ): Direction {\n return appearanceDirection(\n bounds,\n other,\n bestDirection(bounds, other),\n appearanceFor(entity).sides\n );\n }\n function isPortAllowed(nodeOrId: FlowNode | string, portName: string): boolean {\n const node = typeof nodeOrId === 'string' ? getNode(nodeOrId) : nodeOrId;\n return !!node && appearanceAllowsPort(node, portName, appearanceFor(node));\n }\n\n function setOptions(partial: Partial<FlowEngineOptions>, replace = false): void {\n const previousAppearances = engineOptions.appearances;\n engineOptions = replace\n ? { ...partial }\n : {\n ...engineOptions,\n ...partial,\n config: partial.config\n ? { ...(engineOptions.config ?? {}), ...partial.config }\n : engineOptions.config,\n connection: partial.connection\n ? { ...(engineOptions.connection ?? {}), ...partial.connection }\n : engineOptions.connection,\n };\n optionsVersion++;\n snapshotEdgePathsCache = new WeakMap();\n stableEdgePathsCache = new WeakMap();\n renderableCache = new WeakMap();\n entityOrderCache = null;\n baseEntityOrderCache = null;\n paintZIndicesCache = new WeakMap();\n entityRankCache = null;\n renderableSpatialIndex = null;\n graphBoundsCache = null;\n groupGeometryCache = new WeakMap();\n visualGroupGeometryCache = new WeakMap();\n foldedEdgesCache = new WeakMap();\n edgeOwnerCache = new WeakMap();\n edgeOwnerByEdgeCache = new WeakMap();\n nodeIndexCache = new WeakMap();\n obstacleCache = new WeakMap();\n edgePathMemo.clear();\n lastCanonicalEdgePaths = null;\n lastRouting = null;\n routerReadTrackingDisabled = false;\n const appearances = replace ? partial.appearances ?? {} : partial.appearances;\n if (appearances !== undefined && appearances !== previousAppearances) store.trigger.configure({ appearances });\n }\n\n function invalidateRoutes(): void {\n snapshotEdgePathsCache = new WeakMap();\n stableEdgePathsCache = new WeakMap();\n renderableCache = new WeakMap();\n renderableSpatialIndex = null;\n edgePathMemo.clear();\n lastRouting = null;\n // Keep canonical paths: identical router output must retain its identity.\n store.trigger.bumpRoutingRevision();\n }\n\n // Visible sibling nodes (id + bounds) under an owner, memoized per snapshot.\n // The set is identical for all edges sharing an owner — the only per-edge\n // difference is dropping the edge's own endpoints, done cheaply in\n // `edgeObstacles`. This lifts the O(siblings) visibility + bounds work to once\n // per owner per snapshot instead of once per edge.\n function ownerObstacles(\n owner: string | null,\n c: FlowStoreContext,\n ): ReadonlyArray<{ id: string; bounds: Rect }> {\n let byOwner = obstacleCache.get(c);\n if (!byOwner) {\n byOwner = new Map();\n obstacleCache.set(c, byOwner);\n }\n const key = owner ?? ROOT_OWNER_KEY;\n let obstacles = byOwner.get(key);\n if (obstacles) return obstacles;\n\n const nodes = c.graph.nodes as FlowNode[];\n const siblings = owner == null\n ? nodes.filter((node) => node.parentId == null)\n : indexChildren(nodes).get(owner) ?? [];\n obstacles = siblings\n .filter((node) => isNodeVisible(node, c))\n .map((node) => ({ id: node.id, bounds: hierarchyBounds(node, c) }));\n byOwner.set(key, obstacles);\n return obstacles;\n }\n\n /** Both endpoints and their ancestors: never obstacles for their own edge. */\n function edgeEndpointLineage(edge: FlowEdge, c: FlowStoreContext): Set<string> {\n const nodeIndex = indexNodes(c.graph.nodes as FlowNode[]);\n const endpointLineage = new Set<string>();\n for (const endpointId of [edge.sourceId, edge.targetId]) {\n let node = nodeIndex.get(endpointId);\n while (node) {\n endpointLineage.add(node.id);\n node = node.parentId ? nodeIndex.get(node.parentId) : undefined;\n }\n }\n return endpointLineage;\n }\n\n function edgeObstacles(edge: FlowEdge, c: FlowStoreContext): Rect[] {\n const owner = edgeOwnerOf(edge, c);\n const endpointLineage = edgeEndpointLineage(edge, c);\n const result: Rect[] = [];\n for (const { id, bounds } of ownerObstacles(owner, c)) {\n if (endpointLineage.has(id)) continue;\n result.push(bounds);\n }\n return result;\n }\n\n // Inverted highlight index, keyed by the highlights Map identity — stable\n // across snapshots that don't touch highlights, so per-entity results keep\n // referential equality and subscribers can bail with Object.is.\n const highlightIndexCache = new WeakMap<\n FlowStoreContext['highlights'],\n Map<string, Array<{ kind: string; meta: unknown }>>\n >();\n const NO_HIGHLIGHTS: ReadonlyArray<{ kind: string; meta: unknown }> = [];\n\n /**\n * Group geometry per snapshot, derived bottom-up. `derived` groups are a\n * pure function of their children's (visual) bounds — recomputed per\n * transition, so containment can't drift and sizing is reversible.\n */\n function groupGeometryFor(\n c: FlowStoreContext,\n node: FlowNode,\n visiting?: Set<string>,\n ): GroupGeometry | null {\n if (!node.group) return null;\n let byId = groupGeometryCache.get(c);\n const cached = byId?.get(node.id);\n if (cached !== undefined) return cached;\n\n const geometry = computeGroupGeometryRaw(c, node, visiting, undefined);\n\n if (!byId) {\n byId = new Map();\n groupGeometryCache.set(c, byId);\n }\n byId.set(node.id, geometry);\n return geometry;\n }\n\n function visualGroupGeometryFor(\n c: FlowStoreContext,\n node: FlowNode,\n snap: VisualSnapInfo,\n ): GroupGeometry | null {\n if (!node.group) return null;\n let byId = visualGroupGeometryCache.get(c);\n const cached = byId?.get(node.id);\n if (cached !== undefined) return cached;\n\n const geometry = computeGroupGeometryRaw(\n c,\n node,\n undefined,\n undefined,\n snap,\n );\n if (!byId) {\n byId = new Map();\n visualGroupGeometryCache.set(c, byId);\n }\n byId.set(node.id, geometry);\n return geometry;\n }\n\n function computeGroupGeometryRaw(\n c: FlowStoreContext,\n node: FlowNode,\n visiting: Set<string> | undefined,\n excludeChildren: ReadonlySet<string> | undefined,\n visualSnap?: VisualSnapInfo,\n ): GroupGeometry {\n const contentSize = resolvedSize(node);\n if (node.group!.type === 'fixed') {\n return fixedGroupGeometry(\n withLayoutOffset(resolvedBounds(node), node.id, c),\n node.group!.contentSize ?? { width: 0, height: 0 },\n node.group!,\n );\n }\n const seen = visiting ?? new Set<string>();\n seen.add(node.id);\n let union: Rect | null = null;\n const children = indexChildren(c.graph.nodes as FlowNode[]).get(node.id);\n for (const child of children ?? []) {\n if (child.hidden || seen.has(child.id)) continue;\n // A collapsed group hides its descendants; they must not count toward its\n // derived bounds either, or the box stays full-size while empty. Excluding\n // them shrinks a collapsed group to its content block.\n if (isHiddenByCollapsedAncestor(child.id, c)) continue;\n if (excludeChildren?.has(child.id)) continue;\n // If this child is the one currently being resized, union its LIVE\n // resize bounds (the in-progress gesture rect) rather than its committed\n // `resolvedBounds`, so the parent group grows/shrinks live during the\n // drag — mirroring how dragging a child updates the group live. Committed\n // bounds are used again once the resize is committed.\n const liveResize =\n c.canvasState === 'resizing' && c.resizingEntityId === child.id\n ? getResizeBoundsFromContext(c)\n : null;\n const b = liveResize\n ? liveResize\n : visualSnap\n ? visualBounds(child, visualSnap)\n : isDerivedGroup(child)\n ? excludeChildren\n ? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds\n : groupGeometryFor(c, child, seen)?.bounds ??\n withLayoutOffset(resolvedBounds(child), child.id, c)\n : hierarchyBounds(child, c);\n union = uniteRects(union, b);\n }\n // Contained edge labels count as content (Stately-editor semantics) —\n // except a self-edge on this group itself, which may hang outside.\n const nodeMap = indexNodes(c.graph.nodes);\n for (const edge of ownedEdges(c).get(node.id) ?? []) {\n if (edge.hidden || !edge.label) continue;\n if (edge.sourceId === node.id && edge.targetId === node.id) continue;\n let labelBounds = resolveEdgeLabelBounds(\n edge,\n nodeMap,\n c.measurements.get(edge.id),\n );\n if (!labelBounds || (!labelBounds.width && !labelBounds.height)) continue;\n if (\n visualSnap &&\n ((edge.dx ?? 0) !== 0 || (edge.dy ?? 0) !== 0)\n ) {\n const visualOffset = visualOwnedEdgeOffset(edge, visualSnap);\n labelBounds = {\n ...labelBounds,\n x: labelBounds.x + visualOffset.x - (edge.dx ?? 0),\n y: labelBounds.y + visualOffset.y - (edge.dy ?? 0),\n };\n }\n union = uniteRects(union, labelBounds);\n }\n return deriveGroupGeometry(\n contentSize,\n union,\n node.group as Extract<NonNullable<FlowNode['group']>, { type: 'derived' }>,\n layoutPosition(node, c),\n );\n }\n\n function uniteRects(union: Rect | null, b: Rect): Rect {\n return union ? unionRect(union, b) : { ...b };\n }\n\n /** Bounds with group hierarchy applied (derived groups wrap their children). */\n function hierarchyBounds(node: FlowNode, c: FlowStoreContext): Rect {\n if (isDerivedGroup(node)) {\n const geometry = groupGeometryFor(c, node);\n if (geometry) return geometry.bounds;\n }\n return withLayoutOffset(resolvedBounds(node), node.id, c);\n }\n\n // Cross-snapshot per-edge path memo. Immer's structural sharing makes an\n // entity's object identity a precise dirty flag: an edge's path can only\n // change if the edge, one of its endpoint nodes, or one of the global\n // inputs below changed. During a drag this recomputes only the edges\n // attached to moving nodes instead of every edge in the graph.\n // The last paths routed for the store graph. A recomputed path that equals\n // its previous value keeps the previous object, so views keyed on path\n // identity skip edges whose geometry did not change.\n let lastCanonicalEdgePaths: Map<string, EdgePathData> | null = null;\n // What the custom router read during the last store-graph routing pass, and\n // each call's inputs and result. See `computeAllEdgePaths`.\n let lastRouting: RoutingRecord | null = null;\n let routerReadTrackingDisabled = false;\n const edgePathMemo = new Map<\n string,\n { edge: FlowEdge; source: FlowNode; target: FlowNode; path: EdgePathData }\n >();\n let edgePathMemoInputs: {\n appearances: FlowStoreContext['appearances'];\n selection: Set<string>;\n offsetX: number;\n offsetY: number;\n grid: [number, number] | null;\n resizingEntityId: string | null;\n resizeCorners: FlowStoreContext['resizeCorners'];\n measurements: FlowStoreContext['measurements'];\n layoutOffsets: FlowStoreContext['layoutAnimation']['offsets'];\n } | null = null;\n\n function layoutOffset(id: string, c = ctx()): Point {\n return c.layoutAnimation.offsets.get(id) ?? { x: 0, y: 0 };\n }\n\n function withLayoutOffset(rect: Rect, id: string, c = ctx()): Rect {\n const offset = layoutOffset(id, c);\n return {\n ...rect,\n x: rect.x + offset.x,\n y: rect.y + offset.y,\n };\n }\n\n function layoutPosition(node: FlowNode, c = ctx()): Point {\n const position = resolvedPosition(node);\n const offset = layoutOffset(node.id, c);\n return { x: position.x + offset.x, y: position.y + offset.y };\n }\n\n // Entity accessors\n\n function getNode(id: string): FlowNode | undefined {\n return indexNodes(ctx().graph.nodes).get(id);\n }\n\n function getEdge(id: string): FlowEdge | undefined {\n const c = ctx();\n return indexEdges(c.graph.edges).get(id) ?? foldedEdgesFor(c).byId.get(id);\n }\n\n function getEntity(id: string): FlowNode | FlowEdge | undefined {\n return getNode(id) ?? getEdge(id);\n }\n\n function isNodeVisible(node: FlowNode, c: FlowStoreContext, viewport = c.viewport): boolean {\n if (node.hidden) return false;\n if (isHiddenByCollapsedAncestor(node.id, c)) return false;\n const globalConfig = engineOptions.config ?? {};\n if (globalConfig.visible && !resolveBehavior(globalConfig.visible, node, c)) return false;\n if (engineOptions.isVisible && !engineOptions.isVisible(node, viewport)) return false;\n return true;\n }\n\n function isHiddenByCollapsedAncestor(nodeId: string, c: FlowStoreContext): boolean {\n if (c.collapsedNodeIds.size === 0) return false;\n const nodeIndex = indexNodes(c.graph.nodes as FlowNode[]);\n let parentId = nodeIndex.get(nodeId)?.parentId;\n while (parentId) {\n if (c.collapsedNodeIds.has(parentId)) return true;\n parentId = nodeIndex.get(parentId)?.parentId;\n }\n return false;\n }\n\n function visibleEndpointId(nodeId: string, c: FlowStoreContext): string | null {\n const nodeIndex = indexNodes(c.graph.nodes as FlowNode[]);\n const node = nodeIndex.get(nodeId);\n if (!node) return null;\n if (!isHiddenByCollapsedAncestor(nodeId, c)) return nodeId;\n\n let parentId = node.parentId;\n let visibleCollapsedAncestor: string | null = null;\n while (parentId) {\n if (c.collapsedNodeIds.has(parentId)) visibleCollapsedAncestor = parentId;\n parentId = nodeIndex.get(parentId)?.parentId;\n }\n return visibleCollapsedAncestor;\n }\n\n function foldedEdgesFor(c: FlowStoreContext): { edges: FlowEdge[]; byId: Map<string, FlowEdge> } {\n const cached = foldedEdgesCache.get(c);\n if (cached) return cached;\n\n // Fast path: nothing collapsed ⇒ no edges can fold. Skip the O(E) loop and\n // Map allocation and share a frozen empty result. Callers only read\n // `.edges`/`.byId` (spread or `.get`), never mutate, so sharing is safe.\n if (c.collapsedNodeIds.size === 0) {\n foldedEdgesCache.set(c, EMPTY_FOLDED);\n return EMPTY_FOLDED;\n }\n\n const merged = new Map<string, FlowEdge & { data: { foldedEdgeIds: string[] } }>();\n for (const edge of c.graph.edges as FlowEdge[]) {\n if (edge.hidden) continue;\n const sourceId = visibleEndpointId(edge.sourceId, c);\n const targetId = visibleEndpointId(edge.targetId, c);\n if (!sourceId || !targetId || sourceId === targetId) continue;\n if (sourceId === edge.sourceId && targetId === edge.targetId) continue;\n\n const key = `${sourceId}->${targetId}`;\n const existing = merged.get(key);\n if (existing) {\n existing.data.foldedEdgeIds.push(edge.id);\n continue;\n }\n merged.set(key, {\n ...edge,\n id: `flow:folded:${edge.id}`,\n sourceId,\n targetId,\n sourcePort: undefined,\n targetPort: undefined,\n label: undefined,\n waypoints: undefined,\n points: undefined,\n routing: undefined,\n svgPath: undefined,\n selectable: false,\n connectable: false,\n reconnectable: false,\n deletable: false,\n data: { foldedEdgeIds: [edge.id] },\n });\n }\n\n const edges = [...merged.values()];\n const byId = new Map(edges.map((edge) => [edge.id, edge]));\n const result = { edges, byId };\n foldedEdgesCache.set(c, result);\n return result;\n }\n\n function isEdgeVisible(\n edge: FlowEdge,\n graph: FlowStoreContext['graph'],\n c: FlowStoreContext,\n viewport = c.viewport,\n ): boolean {\n if (edge.hidden) return false;\n if (\n c.connection?.preview !== false &&\n c.connection?.reconnectingEdgeId === edge.id\n ) return false;\n const nodeIndex = indexNodes(graph.nodes);\n const source = nodeIndex.get(edge.sourceId);\n const target = nodeIndex.get(edge.targetId);\n if (!source || !target) return false;\n if (!isNodeVisible(source, c, viewport) || !isNodeVisible(target, c, viewport)) return false;\n const globalConfig = engineOptions.config ?? {};\n if (globalConfig.visible && !resolveBehavior(globalConfig.visible, edge, c)) return false;\n if (engineOptions.isVisible && !engineOptions.isVisible(edge, viewport)) return false;\n return true;\n }\n\n function getEntityRef(id: string): FlowEntityRef | undefined {\n const node = getNode(id);\n if (node) {\n return { kind: 'node', id, node };\n }\n\n const edge = getEdge(id);\n if (edge) {\n return { kind: 'edge', id, edge };\n }\n\n for (const candidate of ctx().graph.nodes) {\n const port = candidate.ports?.find(\n (p) => (p as { id?: string }).id === id || `${candidate.id}:${p.name}` === id,\n );\n if (port) {\n return {\n kind: 'port',\n id,\n nodeId: candidate.id,\n portName: port.name,\n port,\n };\n }\n }\n\n return undefined;\n }\n\n const getAddressable = getEntityRef;\n\n function getOwnerEntity(id: string): FlowNode | FlowEdge | undefined {\n const addressable = getEntityRef(id);\n if (!addressable) return undefined;\n if (addressable.kind === 'node') return addressable.node;\n if (addressable.kind === 'edge') return addressable.edge;\n if (addressable.kind === 'port') return getNode(addressable.nodeId);\n return getEntity(addressable.ownerId);\n }\n\n // Coordinate conversion\n\n function screenToCanvas(screenPoint: Point): Point {\n return _screenToCanvas(screenPoint, ctx().viewport);\n }\n\n function canvasToScreen(canvasPoint: Point): Point {\n return _canvasToScreen(canvasPoint, ctx().viewport);\n }\n\n // Hit testing\n\n function entityAtPoint(canvasPoint: Point): FlowNode | FlowEdge | null {\n const c = ctx();\n const { graph } = c;\n const order = getEntityOrderFor(c);\n // Reverse paint order (topmost first) so the returned entity matches the\n // rendered scene. Skip invisible nodes/edges (collapse-hidden or `hidden`)\n // — consistent with entitiesInRect and what the user actually sees.\n for (let i = order.nodes.length - 1; i >= 0; i--) {\n const node = order.nodes[i];\n if (!node) continue;\n if (!isNodeVisible(node, c)) continue;\n const bounds = hierarchyBounds(node, c);\n const shape = getShapeOrDefault(node.shape ?? 'rect');\n if (shape.hitTest(canvasPoint, bounds)) {\n return node;\n }\n }\n // Edge labels (treated like nodes for hit testing)\n const nodeMap = new Map<string, FlowNode>();\n for (const n of graph.nodes) nodeMap.set(n.id, n);\n for (let i = order.edges.length - 1; i >= 0; i--) {\n const edge = order.edges[i];\n if (!edge) continue;\n if (!isEdgeVisible(edge, graph, c)) continue;\n const lb = resolveEdgeLabelBounds(edge as FlowEdge, nodeMap);\n if (lb && canvasPoint.x >= lb.x && canvasPoint.x <= lb.x + lb.width &&\n canvasPoint.y >= lb.y && canvasPoint.y <= lb.y + lb.height) {\n return edge as FlowEdge;\n }\n }\n const edgePaths = getAllEdgePaths();\n for (let i = order.edges.length - 1; i >= 0; i--) {\n const edge = order.edges[i];\n if (!edge) continue;\n if (!isEdgeVisible(edge, graph, c)) continue;\n const path = edgePaths.get(edge.id);\n if (!path) continue;\n if (path.segments.some((segment) => isPointNearPath(canvasPoint, segment, edgeHitTolerance))) {\n return edge;\n }\n }\n return null;\n }\n\n function entityIdAtPoint(canvasPoint: Point): string | null {\n return entityAtPoint(canvasPoint)?.id ?? null;\n }\n\n function validateConnectionDetailed(proposed: ProposedConnection, context: FlowStoreContext = ctx()): { valid: boolean; reason?: string } {\n // Check direction compatibility\n const { graph } = context;\n const srcNode = graph.nodes.find((n) => n.id === proposed.sourceId);\n const tgtNode = graph.nodes.find((n) => n.id === proposed.targetId);\n if (!srcNode || !tgtNode) return { valid: false, reason: 'missing-endpoint' };\n if (context.mode === 'readonly') return { valid: false, reason: 'readonly' };\n if ([srcNode, tgtNode].some(node => !(node.connectable ?? resolveBehavior(engineOptions.config?.connectable, node, context, true)))) {\n return { valid: false, reason: 'connectable' };\n }\n\n const sourcePort =\n proposed.sourcePort && srcNode.ports\n ? srcNode.ports.find((p) => p.name === proposed.sourcePort) ?? null\n : null;\n const targetPort =\n proposed.targetPort && tgtNode.ports\n ? tgtNode.ports.find((p) => p.name === proposed.targetPort) ?? null\n : null;\n\n if (proposed.sourcePort && proposed.sourcePort !== '*' && !sourcePort) {\n return { valid: false, reason: 'missing-source-port' };\n }\n if (proposed.targetPort && proposed.targetPort !== '*' && !targetPort) {\n return { valid: false, reason: 'missing-target-port' };\n }\n\n if ((proposed.sourcePort && proposed.sourcePort !== '*' && appearanceFor(srcNode).registered && !isPortAllowed(srcNode, proposed.sourcePort)) ||\n (proposed.targetPort && proposed.targetPort !== '*' && appearanceFor(tgtNode).registered && !isPortAllowed(tgtNode, proposed.targetPort))) {\n return { valid: false, reason: 'appearance-port' };\n }\n if (!appearanceFor(srcNode).sides.length || !appearanceFor(tgtNode).sides.length) return { valid: false, reason: 'appearance-sides' };\n if (sourcePort) {\n if (sourcePort.direction === 'in') return { valid: false, reason: 'source-port-direction' };\n }\n if (targetPort) {\n if (targetPort.direction === 'out') return { valid: false, reason: 'target-port-direction' };\n }\n\n // User hook\n if (engineOptions.canConnect) {\n const result = engineOptions.canConnect(proposed, {\n graph,\n context,\n source: srcNode,\n target: tgtNode,\n sourcePort,\n targetPort,\n connection: context.connection,\n });\n if (typeof result === 'boolean') {\n if (!result) return { valid: false };\n } else if (!result.valid) {\n return { valid: false, reason: result.reason };\n }\n }\n\n return { valid: true };\n }\n\n function validateConnection(proposed: ProposedConnection): boolean {\n return validateConnectionDetailed(proposed).valid;\n }\n\n function connectionOptions(\n options: ConnectionCandidateOptions = {},\n ): Required<FlowConnectionOptions> {\n return {\n radius: options.radius ?? engineOptions.connection?.radius ?? 24,\n mode: options.mode ?? engineOptions.connection?.mode ?? 'loose',\n };\n }\n\n function isConnectionCandidateValid(\n source: ConnectionCandidateSource | undefined,\n nodeId: string,\n portName: string | null,\n ): boolean {\n if (!source) return true;\n if (nodeId === source.nodeId) return false;\n return validateConnection(normalizeConnection({\n sourceId: source.nodeId,\n sourcePort: source.port,\n targetId: nodeId,\n targetPort: portName,\n }, ctx().graph));\n }\n\n function resolveEntityConfig(entityOrId: FlowNode | FlowEdge | string): {\n hidden: boolean;\n selectable: boolean;\n focusable: boolean;\n draggable: boolean;\n connectable: boolean;\n reconnectable: boolean;\n deletable: boolean;\n resizable: boolean;\n } {\n const entity = typeof entityOrId === 'string' ? getEntity(entityOrId) : entityOrId;\n if (!entity) {\n return { hidden: false, selectable: true, focusable: true, draggable: true, connectable: true, reconnectable: true, deletable: true, resizable: true };\n }\n const c = ctx();\n return {\n hidden:\n entity.type === 'edge'\n ? !isEdgeVisible(entity as FlowEdge, c.graph, c)\n : !isNodeVisible(entity as FlowNode, c),\n selectable: entity.selectable ?? resolveBehavior((engineOptions.config ?? {}).selectable, entity, c, true),\n focusable: entity.focusable ?? resolveBehavior((engineOptions.config ?? {}).focusable, entity, c, true),\n draggable: entity.draggable ?? resolveBehavior((engineOptions.config ?? {}).draggable, entity, c, true),\n connectable: entity.connectable ?? resolveBehavior((engineOptions.config ?? {}).connectable, entity, c, true),\n reconnectable: (entity as FlowEdge).reconnectable ?? resolveBehavior((engineOptions.config ?? {}).reconnectable, entity, c, true),\n deletable: entity.deletable ?? resolveBehavior((engineOptions.config ?? {}).deletable, entity, c, true),\n resizable: (entity as FlowNode).resizable ?? resolveBehavior((engineOptions.config ?? {}).resizable, entity, c, false),\n };\n }\n\n function distanceToRect(point: Point, rect: Rect): number {\n const dx =\n point.x < rect.x ? rect.x - point.x :\n point.x > rect.x + rect.width ? point.x - (rect.x + rect.width) :\n 0;\n const dy =\n point.y < rect.y ? rect.y - point.y :\n point.y > rect.y + rect.height ? point.y - (rect.y + rect.height) :\n 0;\n return Math.hypot(dx, dy);\n }\n\n function groupConnectionDistance(\n point: Point,\n node: FlowNode,\n c: FlowStoreContext,\n ): number {\n const bounds = hierarchyBounds(node, c);\n const boundaryWidth = node.group?.connectionBoundaryWidth;\n if (boundaryWidth === undefined) return distanceToRect(point, bounds);\n\n const geometry = groupGeometryFor(c, node);\n if (!geometry) return distanceToRect(point, bounds);\n if (distanceToRect(point, geometry.contentBounds) === 0) return 0;\n\n const side = node.group?.content ?? 'top';\n const childSurface: Rect =\n side === 'top'\n ? {\n x: bounds.x,\n y: geometry.contentBounds.y + geometry.contentBounds.height,\n width: bounds.width,\n height:\n bounds.y + bounds.height -\n geometry.contentBounds.y -\n geometry.contentBounds.height,\n }\n : side === 'bottom'\n ? {\n x: bounds.x,\n y: bounds.y,\n width: bounds.width,\n height: geometry.contentBounds.y - bounds.y,\n }\n : side === 'left'\n ? {\n x: geometry.contentBounds.x + geometry.contentBounds.width,\n y: bounds.y,\n width:\n bounds.x + bounds.width -\n geometry.contentBounds.x -\n geometry.contentBounds.width,\n height: bounds.height,\n }\n : {\n x: bounds.x,\n y: bounds.y,\n width: geometry.contentBounds.x - bounds.x,\n height: bounds.height,\n };\n\n const childDistance = distanceToRect(point, childSurface);\n if (childDistance > 0) return distanceToRect(point, bounds);\n\n const inset = Math.max(0, boundaryWidth);\n const distanceFromBoundary = Math.min(\n point.x - childSurface.x,\n childSurface.x + childSurface.width - point.x,\n point.y - childSurface.y,\n childSurface.y + childSurface.height - point.y,\n );\n return distanceFromBoundary <= inset ? 0 : Number.POSITIVE_INFINITY;\n }\n\n function getConnectionCandidate(\n pointer: Point,\n options: ConnectionCandidateOptions = {},\n ): ConnectionCandidate | null {\n const c = ctx();\n const snap = getVisualSnapOffset();\n const { radius, mode } = connectionOptions(options);\n let bestPort:\n | (ConnectionCandidate & { distance: number })\n | null = null;\n let bestNode:\n | (ConnectionCandidate & { distance: number })\n | null = null;\n\n // Iterate in paint order (later == painted on top) so ties resolve to the\n // visually-topmost node. Accepting equal distances with `<=` lets a child\n // painted over an overlapping parent group win the tie-break.\n for (const node of getEntityOrderFor(c).nodes) {\n if (!isNodeVisible(node, c)) continue;\n if (!resolveEntityConfig(node).connectable) continue;\n\n for (const port of node.ports ?? []) {\n if (!isPortAllowed(node, port.name)) continue;\n const position = portCenter(node, port, snap);\n const distance = Math.hypot(pointer.x - position.x, pointer.y - position.y);\n if (distance > radius) continue;\n const isValid = isConnectionCandidateValid(options.source, node.id, port.name);\n if (!isValid) continue;\n if (!bestPort || distance <= bestPort.distance) {\n bestPort = {\n nodeId: node.id,\n portName: port.name,\n position,\n isValid,\n distance,\n };\n }\n }\n\n if (mode !== 'loose') continue;\n const bounds = connectionBounds(node.id, node, hierarchyBounds(node, c));\n const sides = appearanceFor(node).sides;\n if (!sides.length) continue;\n // Only permitted boundary segments attract a connection. Preserve unrestricted body targeting.\n const boundaryDistance = Math.min(...sides.map((side) => distanceToRect(pointer, {\n x: side === 'right' ? bounds.x + bounds.width : bounds.x,\n y: side === 'bottom' ? bounds.y + bounds.height : bounds.y,\n width: side === 'left' || side === 'right' ? 0 : bounds.width,\n height: side === 'top' || side === 'bottom' ? 0 : bounds.height,\n })));\n const distance = sides.length < 4 ? boundaryDistance : node.group\n ? groupConnectionDistance(pointer, node, c)\n : distanceToRect(pointer, bounds);\n if (distance > radius) continue;\n const isValid = isConnectionCandidateValid(options.source, node.id, null);\n if (!isValid) continue;\n if (!bestNode || distance <= bestNode.distance) {\n bestNode = {\n nodeId: node.id,\n portName: null,\n position: {\n x: bounds.x + bounds.width / 2,\n y: bounds.y + bounds.height / 2,\n },\n isValid,\n distance,\n };\n }\n }\n\n const best = bestPort ?? bestNode;\n if (!best) return null;\n return {\n nodeId: best.nodeId,\n portName: best.portName,\n position: best.position,\n isValid: best.isValid,\n };\n }\n\n // Edge routing\n\n function createRouterEntityBoundsLookup(\n graph: FlowStoreContext['graph'],\n snap: VisualSnapInfo,\n nodeMap = indexNodes(graph.nodes),\n edgeMap = indexEdges(graph.edges),\n ): EdgeRouterContext['getEntityBounds'] {\n return (id) => {\n const node = nodeMap.get(id);\n if (node) return { ...visualBounds(node, snap) };\n\n const edge = edgeMap.get(id);\n if (!edge?.label) return undefined;\n const source = nodeMap.get(edge.sourceId);\n const target = nodeMap.get(edge.targetId);\n if (!source || !target) return undefined;\n const sourceBounds = visualBounds(source, snap);\n const targetBounds = visualBounds(target, snap);\n const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed';\n const basePos = resolveLabelAnchor(\n anchor,\n edge.label,\n sourceBounds,\n targetBounds,\n edge,\n resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id)),\n );\n return { ...visualLabelBounds(edge, basePos, snap) };\n };\n }\n\n function getEdgePath(edgeId: string): PathData | null {\n const segments = getAllEdgePaths().get(edgeId)?.segments;\n if (!segments?.length) return null;\n if (segments.length === 1) return segments[0];\n return {\n points: segments.flatMap((segment) => segment.points),\n sourceDirection: segments[0].sourceDirection,\n targetDirection: segments.at(-1)!.targetDirection,\n routing: 'polyline',\n svgPath: segments.map(pathToSVG).join(' '),\n };\n }\n\n function getEdgePathBounds(edgeId: string): Rect | null {\n const path = getAllEdgePaths().get(edgeId);\n if (!path) return null;\n return boundsForPoints(path.segments.flatMap((segment) => segment.points));\n }\n\n function getEdgeLabelBounds(edgeId: string): Rect | null {\n const c = ctx();\n const edge = getEdge(edgeId);\n if (!edge?.label) return null;\n const measured = c.measurements.get(edgeId);\n\n const nodeMap = indexNodes(c.graph.nodes as FlowNode[]);\n return resolveEdgeLabelBounds(edge, nodeMap, measured);\n }\n\n function getBounds(id: string): Rect | undefined {\n const c = ctx();\n\n const addressable = getEntityRef(id);\n if (!addressable) return undefined;\n\n if (addressable.kind === 'node') {\n const bounds = hierarchyBounds(addressable.node, c);\n if (isDerivedGroup(addressable.node)) return bounds;\n const measured = c.measurements.get(id);\n if (!measured) return bounds;\n // ResizeObserver does not fire for position-only changes. Its x/y can\n // therefore describe the node's pre-layout position even though the\n // rendered node has moved. Position always comes from core geometry;\n // the live measurement contributes only the DOM border-box size.\n return { ...bounds, width: addressable.node.style?.customWidth ?? measured.width, height: addressable.node.style?.customHeight ?? measured.height };\n }\n\n if (addressable.kind === 'edge') {\n const labelBounds = getEdgeLabelBounds(id);\n if (resolvedAuthoritativePath(addressable.edge)) {\n const edgePathBounds = getEdgePathBounds(id);\n if (edgePathBounds) {\n return labelBounds\n ? unionRect(edgePathBounds, labelBounds)\n : edgePathBounds;\n }\n }\n return labelBounds ?? getEdgePathBounds(id) ?? undefined;\n }\n\n if (addressable.kind === 'port') {\n const owner = getNode(addressable.nodeId);\n return owner ? portBounds(owner, addressable.port) : undefined;\n }\n\n return undefined;\n }\n\n /** Resolve edge label bounds using committed (static) node positions */\n function resolveEdgeLabelBounds(\n edge: FlowEdge,\n nodeMap: Map<string, FlowNode>,\n measurement?: Rect,\n ): Rect | null {\n if (!edge.label) return null;\n const src = nodeMap.get(edge.sourceId);\n const tgt = nodeMap.get(edge.targetId);\n if (!src || !tgt) return null;\n const srcB = withLayoutOffset(\n { x: src.x, y: src.y, width: src.style?.customWidth ?? src.width, height: src.style?.customHeight ?? src.height },\n src.id,\n );\n const tgtB = withLayoutOffset(\n { x: tgt.x, y: tgt.y, width: tgt.style?.customWidth ?? tgt.width, height: tgt.style?.customHeight ?? tgt.height },\n tgt.id,\n );\n const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed';\n const size = resolvedEdgeLabelSize(edge.label, measurement);\n const basePos = resolveLabelAnchor(\n anchor,\n edge.label,\n srcB,\n tgtB,\n edge,\n size,\n );\n return withLayoutOffset({\n x: basePos.x + (edge.label.dx ?? 0),\n y: basePos.y + (edge.label.dy ?? 0),\n ...size,\n }, edge.id);\n }\n\n /** Build selection bounding rect with properly resolved edge labels */\n function getSelectionSnapBounds(\n c: FlowStoreContext,\n includeEdgePoints = false,\n ): Rect | null {\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const nodeMap = new Map<string, FlowNode>();\n for (const n of c.graph.nodes) nodeMap.set(n.id, n);\n\n for (const n of c.graph.nodes) {\n if (!c.selection.has(n.id)) continue;\n const b = hierarchyBounds(n, c);\n minX = Math.min(minX, b.x);\n minY = Math.min(minY, b.y);\n maxX = Math.max(maxX, b.x + b.width);\n maxY = Math.max(maxY, b.y + b.height);\n }\n for (const e of c.graph.edges) {\n if (!c.selection.has(e.id)) continue;\n if (includeEdgePoints) {\n for (const point of resolvedAuthoritativePath(e)?.points ?? []) {\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n }\n }\n const lb = resolveEdgeLabelBounds(e, nodeMap, c.measurements.get(e.id));\n if (!lb) continue;\n minX = Math.min(minX, lb.x);\n minY = Math.min(minY, lb.y);\n maxX = Math.max(maxX, lb.x + lb.width);\n maxY = Math.max(maxY, lb.y + lb.height);\n }\n if (!isFinite(minX)) return null;\n return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };\n }\n\n /** Collect visible snap targets outside the moving selection subtree. */\n function getSnapTargetRects(c: FlowStoreContext, selection: Set<string>): Rect[] {\n // Compute visible canvas area from viewport\n const vp = c.viewport;\n const vs = c.viewportSize;\n const viewRect: Rect = {\n x: -vp.x / vp.zoom,\n y: -vp.y / vp.zoom,\n width: vs.width / vp.zoom,\n height: vs.height / vp.zoom,\n };\n\n const rects: Rect[] = [];\n const nodeMap = new Map<string, FlowNode>();\n const selectedDerivedAncestorIds = new Set<string>();\n const visitedAncestorIds = new Set<string>();\n const nodeIndex = nodesById(c);\n const selectedSubtreeIds = new Set(selection);\n const childrenByParent = indexChildren(c.graph.nodes);\n const pendingDescendantIds = [...selection];\n while (pendingDescendantIds.length > 0) {\n const parentId = pendingDescendantIds.pop()!;\n for (const child of childrenByParent.get(parentId) ?? []) {\n if (selectedSubtreeIds.has(child.id)) continue;\n selectedSubtreeIds.add(child.id);\n pendingDescendantIds.push(child.id);\n }\n }\n for (const id of selection) {\n let parentId = nodeIndex.get(id)?.parentId;\n while (parentId && !visitedAncestorIds.has(parentId)) {\n visitedAncestorIds.add(parentId);\n const parent = nodeIndex.get(parentId);\n if (!parent) break;\n if (isDerivedGroup(parent)) {\n selectedDerivedAncestorIds.add(parentId);\n }\n parentId = parent.parentId;\n }\n }\n for (const n of c.graph.nodes) {\n nodeMap.set(n.id, n);\n if (\n !selectedSubtreeIds.has(n.id) &&\n !selectedDerivedAncestorIds.has(n.id) &&\n !n.hidden\n ) {\n const b = hierarchyBounds(n, c);\n if (rectsIntersect(b, viewRect)) {\n rects.push(b);\n }\n }\n }\n for (const edge of c.graph.edges) {\n if (selection.has(edge.id)) continue;\n const ownerId = edgeOwnerOf(edge, c);\n if (ownerId && selectedSubtreeIds.has(ownerId)) continue;\n const lb = resolveEdgeLabelBounds(\n edge,\n nodeMap,\n c.measurements.get(edge.id),\n );\n if (lb && rectsIntersect(lb, viewRect)) {\n rects.push(lb);\n }\n }\n return rects;\n }\n\n /**\n * Compute visual snap offset for edge routing.\n * Returns the offset to apply to selected nodes so edges follow the snapped visual position.\n * Memoized per store snapshot — callers invoke this once per node per frame.\n */\n function getVisualSnapOffset(): VisualSnapInfo {\n const c = ctx();\n const cached = snapOffsetCache.get(c);\n if (cached) return cached;\n const result = computeVisualSnapOffset(c);\n snapOffsetCache.set(c, result);\n return result;\n }\n\n function computeVisualSnapOffset(c: FlowStoreContext): VisualSnapInfo {\n const selection = c.selection;\n const grid = c.snapToGrid ? c.snapGrid as [number, number] : null;\n let offset: Point = { x: 0, y: 0 };\n const nodesMoved = c.canvasState === 'dragging' && c.graph.nodes.some(\n (n) => selection.has(n.id) && ((n.dx ?? 0) !== 0 || (n.dy ?? 0) !== 0),\n );\n const edgesMoved = c.canvasState === 'dragging' && c.graph.edges.some(\n (e) => selection.has(e.id) && e.label && ((e.label.dx ?? 0) !== 0 || (e.label.dy ?? 0) !== 0),\n );\n if ((nodesMoved || edgesMoved) && c.enableSnapLines) {\n const selBounds = getSelectionSnapBounds(c);\n if (selBounds) {\n const snapResult = getSnapLines(\n selBounds,\n getSnapTargetRects(c, selection),\n { threshold: c.snapThreshold / c.viewport.zoom, enableSpacing: c.enableSpacingGuides },\n );\n if (snapResult) {\n offset = { x: snapResult.snapRect.x - selBounds.x, y: snapResult.snapRect.y - selBounds.y };\n }\n }\n }\n return { offset, grid, selection };\n }\n\n function visualOwnedEdgeOffset(edge: FlowEdge, snap: VisualSnapInfo): Point {\n const raw = { x: edge.dx ?? 0, y: edge.dy ?? 0 };\n if (raw.x === 0 && raw.y === 0) return raw;\n const offset = {\n x: raw.x + snap.offset.x,\n y: raw.y + snap.offset.y,\n };\n if (!snap.grid) return offset;\n\n const c = ctx();\n const ownerId = edgeOwnerOf(edge, c);\n const owner = ownerId ? nodesById(c).get(ownerId) : undefined;\n if (!owner) return offset;\n return {\n x:\n snapToGrid(owner.x + (owner.dx ?? 0) + snap.offset.x, snap.grid[0]) -\n owner.x,\n y:\n snapToGrid(owner.y + (owner.dy ?? 0) + snap.offset.y, snap.grid[1]) -\n owner.y,\n };\n }\n\n /** Get visual bounds for a node — applies snap offset to the drag cohort. */\n function visualBounds(node: FlowNode, snap: VisualSnapInfo): Rect {\n const c = ctx();\n if (c.canvasState === 'resizing' && c.resizingEntityId === node.id) {\n const resizeBounds = getResizeBoundsFromContext(c);\n if (resizeBounds) return resizeBounds;\n }\n if (isDerivedGroup(node)) {\n const geometry = visualGroupGeometryFor(c, node, snap);\n if (geometry) {\n return geometry.bounds;\n }\n }\n const entityOffset =\n (node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0 ? snap.offset : null;\n return withLayoutOffset(\n snappedBounds(node, snap.grid, entityOffset),\n node.id,\n c,\n );\n }\n\n function visualLabelBounds(edge: FlowEdge, basePos: Point, snap: VisualSnapInfo): Rect {\n const isSelected = snap.selection.has(edge.id);\n const isMoved =\n (edge.dx ?? 0) !== 0 ||\n (edge.dy ?? 0) !== 0 ||\n (edge.label?.dx ?? 0) !== 0 ||\n (edge.label?.dy ?? 0) !== 0;\n const ownedOffset =\n !isSelected && ((edge.dx ?? 0) !== 0 || (edge.dy ?? 0) !== 0)\n ? visualOwnedEdgeOffset(edge, snap)\n : null;\n let x = basePos.x + (ownedOffset?.x ?? edge.label?.dx ?? 0);\n let y = basePos.y + (ownedOffset?.y ?? edge.label?.dy ?? 0);\n const layout = layoutOffset(edge.id);\n x += layout.x;\n y += layout.y;\n if (isMoved && !ownedOffset) {\n x += snap.offset.x;\n y += snap.offset.y;\n }\n if (isSelected) {\n if (snap.grid) {\n x = snapToGrid(x, snap.grid[0]);\n y = snapToGrid(y, snap.grid[1]);\n }\n }\n const size = edge.label\n ? resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id))\n : { width: 0, height: 0 };\n return {\n x,\n y,\n ...size,\n };\n }\n\n /** Get visual position for a node — applies snap offset to the drag cohort. */\n function visualPosition(node: FlowNode, snap: VisualSnapInfo): Point {\n const b = visualBounds(node, snap);\n return { x: b.x, y: b.y };\n }\n\n function portBounds(node: FlowNode, port: Rect & { name: string; id?: string }, snap?: VisualSnapInfo): Rect {\n const c = ctx();\n const id = port.id && c.measurements.has(port.id) ? port.id : `${node.id}:${port.name}`;\n const local = c.derivedPortMeasurements.get(id);\n // Measurements normalize into node-local port geometry in the store.\n // Their captured world coordinates become stale when the node moves.\n const position = visualPosition(node, snap ?? getVisualSnapOffset());\n const rect = local ?? port;\n return { x: position.x + rect.x, y: position.y + rect.y, width: rect.width, height: rect.height };\n }\n\n function portCenter(node: FlowNode, port: Rect & { name: string }, snap?: VisualSnapInfo): Point {\n const bounds = portBounds(node, port, snap);\n return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };\n }\n\n /** Get bounds for edge endpoint — port bounds if specified, otherwise node bounds */\n function getEndpointBounds(node: FlowNode, portName: string | null | undefined, snap?: VisualSnapInfo): Rect {\n if (portName && portName !== '*' && node.ports && isPortAllowed(node, portName)) {\n const port = node.ports.find((p) => p.name === portName);\n if (port) {\n return portBounds(node, port, snap);\n }\n }\n const visual = snap ? visualBounds(node, snap) : hierarchyBounds(node, ctx());\n return connectionBounds(node.id, node, visual);\n }\n\n function portSideOf(node: FlowNode, portName: string | null | undefined): Direction | null {\n if (!portName || portName === '*' || !node.ports) return null;\n const port = node.ports.find((p) => p.name === portName) as\n | { side?: Direction }\n | undefined;\n return port && isPortAllowed(node, portName) ? port.side ?? null : null;\n }\n\n function getShapeAnchor(node: FlowNode, bounds: Rect, direction: Direction): Point {\n const appearance = appearanceFor(node);\n if (appearance.connectionBounds || (appearance.registered && ctx().measurements.has(appearanceMeasurementId(node.id, appearance)))) return rectEdgeAnchor(bounds, direction);\n const shape = getShapeOrDefault(node.shape ?? 'rect');\n return shape.edgeAnchor(bounds, direction);\n }\n\n function resolveEndpointPoint(\n node: FlowNode,\n nodeBounds: Rect,\n portName: string | null | undefined,\n otherBounds: Rect,\n fallbackDirection: Direction,\n snap?: VisualSnapInfo,\n ): Point {\n if (portName === '*' && node.ports?.some((port) => isPortAllowed(node, port.name))) {\n const otherCenter = {\n x: otherBounds.x + otherBounds.width / 2,\n y: otherBounds.y + otherBounds.height / 2,\n };\n let closest = { x: nodeBounds.x, y: nodeBounds.y };\n let distance = Infinity;\n for (const port of node.ports) {\n if (!isPortAllowed(node, port.name)) continue;\n const point = portCenter(node, port, snap);\n const nextDistance = (point.x - otherCenter.x) ** 2 + (point.y - otherCenter.y) ** 2;\n if (nextDistance < distance) {\n closest = point;\n distance = nextDistance;\n }\n }\n return closest;\n }\n\n if (portName && portName !== '*' && node.ports && isPortAllowed(node, portName)) {\n const port = node.ports.find((p) => p.name === portName);\n if (port) {\n const bounds = getEndpointBounds(node, portName, snap);\n return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };\n }\n }\n\n return getShapeAnchor(node, nodeBounds, fallbackDirection);\n }\n\n function rectEdgeAnchor(bounds: Rect, direction: Direction): Point {\n switch (direction) {\n case 'top':\n return { x: bounds.x + bounds.width / 2, y: bounds.y };\n case 'bottom':\n return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height };\n case 'left':\n return { x: bounds.x, y: bounds.y + bounds.height / 2 };\n case 'right':\n return { x: bounds.x + bounds.width, y: bounds.y + bounds.height / 2 };\n }\n }\n\n /**\n * Resolve the geometry shared by edge rendering and endpoint queries: the\n * endpoint bounds, the facing direction of each end, and the anchor points.\n * Single source of truth so rendered paths and `getEdgeEndpoints` can never\n * disagree on which side of a node an edge attaches to.\n */\n function resolveEdgeGeometry(\n edge: FlowEdge,\n source: FlowNode,\n target: FlowNode,\n snap: VisualSnapInfo,\n getEdgeLabelBounds: (edgeId: string) => Rect | null,\n graph: FlowStoreContext['graph'],\n context: FlowStoreContext,\n ) {\n const naturalSourceBounds = getEndpointBounds(source, edge.sourcePort, snap);\n const targetBounds = getEndpointBounds(target, edge.targetPort, snap);\n const resolvedSourceBounds = engineOptions.resolveEdgeSourceBounds?.({\n edge,\n graph,\n context: edgeSourceBoundsContextReads\n ? trackContextReads(context, edgeSourceBoundsContextReads)\n : context,\n source,\n target,\n sourceBounds: naturalSourceBounds,\n targetBounds,\n getEdgeLabelBounds,\n });\n const sourceBounds = resolvedSourceBounds ?? naturalSourceBounds;\n // Ports have sides: the edge leaves/enters perpendicular through the\n // port's side. Portless endpoints face the other endpoint.\n const sourceDirection =\n portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);\n const targetDirection =\n portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);\n const sourcePoint = resolvedSourceBounds\n ? rectEdgeAnchor(sourceBounds, sourceDirection)\n : resolveEndpointPoint(source, sourceBounds, edge.sourcePort, targetBounds, sourceDirection, snap);\n const targetPoint = resolveEndpointPoint(target, targetBounds, edge.targetPort, sourceBounds, targetDirection, snap);\n return { sourceBounds, targetBounds, sourceDirection, targetDirection, sourcePoint, targetPoint };\n }\n\n function edgePathsCacheInputs(\n c: FlowStoreContext,\n snap: VisualSnapInfo,\n ): EdgePathsCacheInputs {\n return {\n appearances: c.appearances,\n canonicalGraph: c.graph,\n selection: c.selection,\n collapsedNodeIds: c.collapsedNodeIds,\n connection: c.connection,\n offsetX: snap.offset.x,\n offsetY: snap.offset.y,\n gridX: snap.grid?.[0] ?? null,\n gridY: snap.grid?.[1] ?? null,\n resizingEntityId: c.resizingEntityId,\n resizeCorners: c.resizeCorners,\n measurements: c.measurements,\n layoutOffsets: c.layoutAnimation.offsets,\n };\n }\n\n function trackContextReads(\n context: FlowStoreContext,\n reads: Set<PropertyKey>,\n ): FlowStoreContext {\n return new Proxy(context, {\n get(target, key, receiver) {\n reads.add(key);\n return Reflect.get(target, key, receiver);\n },\n });\n }\n\n function sameContextReads(\n previous: FlowStoreContext,\n next: FlowStoreContext,\n reads: ReadonlySet<PropertyKey>,\n ): boolean {\n for (const key of reads) {\n if (\n (previous as Record<PropertyKey, unknown>)[key] !==\n (next as Record<PropertyKey, unknown>)[key]\n ) {\n return false;\n }\n }\n return true;\n }\n\n function sameEdgePathsCacheInputs(\n a: EdgePathsCacheInputs,\n b: EdgePathsCacheInputs,\n ): boolean {\n return (\n a.appearances === b.appearances &&\n a.canonicalGraph === b.canonicalGraph &&\n a.selection === b.selection &&\n a.collapsedNodeIds === b.collapsedNodeIds &&\n a.connection === b.connection &&\n a.offsetX === b.offsetX &&\n a.offsetY === b.offsetY &&\n a.gridX === b.gridX &&\n a.gridY === b.gridY &&\n a.resizingEntityId === b.resizingEntityId &&\n a.resizeCorners === b.resizeCorners &&\n a.measurements === b.measurements &&\n a.layoutOffsets === b.layoutOffsets\n );\n }\n\n /**\n * Whether routing state outside the graph is unchanged. Graph updates\n * replace idle layout offsets with a new empty map, so empty maps match.\n */\n function sameRoutingState(\n a: EdgePathsCacheInputs,\n b: EdgePathsCacheInputs,\n ): boolean {\n return sameEdgePathsCacheInputs(a, {\n ...b,\n canonicalGraph: a.canonicalGraph,\n layoutOffsets:\n a.layoutOffsets.size === 0 && b.layoutOffsets.size === 0\n ? a.layoutOffsets\n : b.layoutOffsets,\n });\n }\n\n /** Route all edges. Callers must treat the returned Map as read-only. */\n function getAllEdgePaths(options: EdgePathOptions = {}): Map<string, EdgePathData> {\n const c = ctx();\n const graph = options.graph ?? c.graph;\n\n let byGraph = snapshotEdgePathsCache.get(c);\n const cached = byGraph?.get(graph);\n if (cached) return cached;\n\n const snap = getVisualSnapOffset();\n // These hooks receive viewport or the full store context, so they may\n // intentionally make routing viewport-dependent. Keep exact snapshot\n // semantics when any of them is configured. `resolveEdgeSourceBounds`\n // is tracked instead: paths are reused only while every context key it\n // read keeps its value.\n const canReuseAcrossSnapshots =\n !engineOptions.isVisible &&\n !engineOptions.config?.visible &&\n !engineOptions.edgeOwner;\n const inputs = edgePathsCacheInputs(c, snap);\n const stableCached = canReuseAcrossSnapshots\n ? stableEdgePathsCache.get(graph)\n : undefined;\n let paths: Map<string, EdgePathData>;\n if (\n stableCached &&\n sameEdgePathsCacheInputs(stableCached.inputs, inputs) &&\n sameContextReads(stableCached.context, c, stableCached.contextReads)\n ) {\n paths = stableCached.paths;\n } else {\n const outerReads = edgeSourceBoundsContextReads;\n const contextReads = new Set<PropertyKey>();\n edgeSourceBoundsContextReads = contextReads;\n try {\n paths = computeAllEdgePaths(c, graph, snap);\n } finally {\n edgeSourceBoundsContextReads = outerReads;\n for (const key of contextReads) outerReads?.add(key);\n }\n if (canReuseAcrossSnapshots) {\n stableEdgePathsCache.set(graph, { inputs, paths, context: c, contextReads });\n }\n }\n\n if (!byGraph) {\n byGraph = new WeakMap();\n snapshotEdgePathsCache.set(c, byGraph);\n }\n byGraph.set(graph, paths);\n return paths;\n }\n\n /**\n * Route every edge. A custom router that has not declared `endpoints`\n * dependencies reads through tracked views of the edge and graph. When a\n * later pass finds every logged read unchanged and the same calls with the\n * same inputs, it reuses the previous results instead of calling the router,\n * so edits the router never looked at (a node's color, say) skip routing.\n * Replay only bridges graph changes: any other routing state change\n * (measurements, appearances, selection, ...) reroutes, because a router\n * may read that state through a closure. Any difference reroutes the whole\n * pass, which keeps routers that share work across calls exact.\n */\n function computeAllEdgePaths(\n c: FlowStoreContext,\n graph: FlowStoreContext['graph'],\n snap = getVisualSnapOffset(),\n ): Map<string, EdgePathData> {\n const router = engineOptions.edgeRouter;\n if (\n !router ||\n (engineOptions.edgeRouterDependencies ?? 'graph') !== 'graph' ||\n graph !== c.graph ||\n routerReadTrackingDisabled\n ) {\n return computeEdgePathsPass(c, graph, snap, 'plain');\n }\n const previous =\n lastRouting?.router === router &&\n sameRoutingState(lastRouting.inputs, edgePathsCacheInputs(c, snap))\n ? lastRouting\n : null;\n if (previous) {\n try {\n return computeEdgePathsPass(c, graph, snap, previous);\n } catch (error) {\n if (error !== REPLAY_MISS) throw error;\n }\n }\n try {\n return computeEdgePathsPass(c, graph, snap, 'record');\n } catch {\n // The router rejected the tracked views (it mutates or clones them, for\n // example). Route without tracking from now on.\n routerReadTrackingDisabled = true;\n lastRouting = null;\n return computeEdgePathsPass(c, graph, snap, 'plain');\n }\n }\n\n function createRoute(\n c: FlowStoreContext,\n graph: FlowStoreContext['graph'],\n edgeMap: ReadonlyMap<string, FlowEdge>,\n getEntityBounds: EdgeRouterContext['getEntityBounds'],\n snap: VisualSnapInfo,\n mode: 'plain' | 'record' | RoutingRecord,\n ): { route: RouteEdge; finish: () => void } {\n const router = engineOptions.edgeRouter ?? bezierRouter;\n if (mode === 'plain') {\n return {\n route: (edge, _key, values, getObstacles) =>\n router(edge, {\n graph,\n getEntityBounds,\n ...values,\n get obstacles() {\n return getObstacles();\n },\n }),\n finish: () => {},\n };\n }\n if (mode === 'record') {\n const tracker = createRouterReadTracker(graph, getEntityBounds);\n const calls: RoutingRecord['calls'] = [];\n const owners: RoutingRecord['owners'] = new Map();\n return {\n route: (edge, key, values, getObstacles) => {\n const call: RoutingRecord['calls'][number] = { key, values, result: undefined! };\n call.result = tracker.release(router(tracker.edge(edge), {\n graph: tracker.graph,\n getEntityBounds: tracker.getEntityBounds,\n ...values,\n get obstacles() {\n if (!call.obstacles) {\n const owner = edgeOwnerOf(edge, c);\n if (!owners.has(owner)) owners.set(owner, ownerObstacles(owner, c));\n call.obstacles = { owner, lineage: [...edgeEndpointLineage(edge, c)].join('\\u0000') };\n }\n return getObstacles();\n },\n }));\n calls.push(call);\n return call.result;\n },\n finish: () => {\n lastRouting = {\n router,\n inputs: edgePathsCacheInputs(c, snap),\n log: tracker.log,\n owners,\n calls,\n };\n },\n };\n }\n const edgesById = new Map([...edgeMap, ...foldedEdgesFor(c).byId]);\n if (!routerReadsUnchanged(mode.log, graph, edgesById, getEntityBounds, plainDataEqual)) {\n throw REPLAY_MISS;\n }\n const ownersUnchanged = new Map<string | null, boolean>();\n const obstaclesUnchanged = (edge: FlowEdge, recorded: RouterCallObstacles): boolean => {\n const owner = edgeOwnerOf(edge, c);\n if (owner !== recorded.owner) return false;\n let unchanged = ownersUnchanged.get(owner);\n if (unchanged === undefined) {\n unchanged = plainDataEqual(mode.owners.get(owner), ownerObstacles(owner, c));\n ownersUnchanged.set(owner, unchanged);\n }\n return unchanged && [...edgeEndpointLineage(edge, c)].join('\\u0000') === recorded.lineage;\n };\n let index = 0;\n return {\n route: (edge, key, values) => {\n const call = mode.calls[index++];\n if (\n !call ||\n call.key !== key ||\n !plainDataEqual(call.values, values) ||\n (call.obstacles && !obstaclesUnchanged(edge, call.obstacles))\n ) {\n throw REPLAY_MISS;\n }\n return call.result;\n },\n finish: () => {\n if (index !== mode.calls.length) throw REPLAY_MISS;\n },\n };\n }\n\n function computeEdgePathsPass(\n c: FlowStoreContext,\n graph: FlowStoreContext['graph'],\n snap: VisualSnapInfo,\n mode: 'plain' | 'record' | RoutingRecord,\n ): Map<string, EdgePathData> {\n const paths = new Map<string, EdgePathData>();\n\n const nodeMap = indexNodes(graph.nodes);\n const edgeMap = indexEdges(graph.edges);\n const getEntityBounds = createRouterEntityBoundsLookup(\n graph,\n snap,\n nodeMap,\n edgeMap,\n );\n const { route, finish: finishRouting } = createRoute(c, graph, edgeMap, getEntityBounds, snap, mode);\n const computing = new Set<string>();\n const trackSourceDependencies = graph === c.graph;\n const nextEdgeSourceDependents = trackSourceDependencies\n ? new Map<string, Set<string>>()\n : edgeSourceDependents;\n\n // Custom visibility hooks can change a path set in ways entity identity\n // can't track — disable the cross-snapshot memo when they're configured.\n const globalConfig = engineOptions.config ?? {};\n const memoUsable = !engineOptions.isVisible && !globalConfig.visible && !engineOptions.resolveEdgeSourceBounds;\n if (memoUsable) {\n const inputs = edgePathMemoInputs;\n if (\n !inputs ||\n inputs.appearances !== c.appearances ||\n inputs.selection !== c.selection ||\n inputs.offsetX !== snap.offset.x ||\n inputs.offsetY !== snap.offset.y ||\n inputs.grid !== snap.grid ||\n inputs.resizingEntityId !== c.resizingEntityId ||\n inputs.resizeCorners !== c.resizeCorners ||\n inputs.measurements !== c.measurements ||\n inputs.layoutOffsets !== c.layoutAnimation.offsets\n ) {\n edgePathMemo.clear();\n edgePathMemoInputs = {\n appearances: c.appearances,\n selection: c.selection,\n offsetX: snap.offset.x,\n offsetY: snap.offset.y,\n grid: snap.grid,\n resizingEntityId: c.resizingEntityId,\n resizeCorners: c.resizeCorners,\n measurements: c.measurements,\n layoutOffsets: c.layoutAnimation.offsets,\n };\n }\n }\n\n const getComputedEdgeLabelBounds = (dependentEdgeId: string, edgeId: string): Rect | null => {\n if (trackSourceDependencies && edgeId !== dependentEdgeId) {\n let dependents = nextEdgeSourceDependents.get(edgeId);\n if (!dependents) {\n nextEdgeSourceDependents.set(edgeId, (dependents = new Set()));\n }\n dependents.add(dependentEdgeId);\n }\n const existing = paths.get(edgeId);\n if (existing) return existing.labelBounds;\n const edge = edgeMap.get(edgeId);\n if (!edge || computing.has(edgeId)) return null;\n return computeEdgePath(edge)?.labelBounds ?? null;\n };\n\n const computeEdgePath = (edge: FlowEdge): EdgePathData | null => {\n if (computing.has(edge.id)) return null;\n computing.add(edge.id);\n const source = nodeMap.get(edge.sourceId);\n const target = nodeMap.get(edge.targetId);\n if (!source || !target || !isEdgeVisible(edge, graph, c)) {\n computing.delete(edge.id);\n return null;\n }\n\n // Derived groups change bounds without changing identity (their\n // geometry follows their children), so edges touching them can't be\n // memoized on endpoint identity.\n const memoizableEdge =\n memoUsable &&\n (!engineOptions.edgeRouter ||\n engineOptions.edgeRouterDependencies === 'endpoints') &&\n !isDerivedGroup(source) &&\n !isDerivedGroup(target);\n if (memoizableEdge) {\n const entry = edgePathMemo.get(edge.id);\n if (\n entry &&\n entry.edge === edge &&\n entry.source === source &&\n entry.target === target\n ) {\n paths.set(edge.id, entry.path);\n computing.delete(edge.id);\n return entry.path;\n }\n }\n\n // Use visual (snapped) bounds so edges follow the snapped position\n const { sourceBounds, targetBounds, sourcePoint, targetPoint } =\n resolveEdgeGeometry(\n edge,\n source,\n target,\n snap,\n (edgeId) => getComputedEdgeLabelBounds(edge.id, edgeId),\n graph,\n c,\n );\n // Lazy + memoized within this edge's computation: obstacles are only\n // computed if a router reads them (avoidRouter). Built-in routers never\n // do, so the default path skips edgeObstacles. Cached so the two-segment\n // (labeled) case doesn't compute twice.\n let obstaclesCache: Rect[] | undefined;\n const getObstacles = (): Rect[] =>\n (obstaclesCache ??= edgeObstacles(edge, c));\n const waypoints = offsetEdgeWaypoints(\n edge,\n visualOwnedEdgeOffset(edge, snap),\n );\n\n let pathData: EdgePathData;\n const authoritative = resolvedAuthoritativePath(edge, source, target);\n if (authoritative) {\n pathData = {\n segments: [authoritative],\n labelBounds: edge.label\n ? visualLabelBounds(\n edge,\n resolveLabelAnchor(\n edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed',\n edge.label,\n sourceBounds,\n targetBounds,\n edge,\n resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id)),\n ),\n snap,\n )\n : null,\n };\n } else if (edge.label) {\n // Resolve label anchor: edge-level overrides engine-level\n const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed';\n const basePos = resolveLabelAnchor(\n anchor,\n edge.label,\n sourceBounds,\n targetBounds,\n edge,\n resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id)),\n );\n const labelBounds = visualLabelBounds(edge, basePos, snap);\n\n const labelConnectionBounds = connectionBounds(edge.id, edge.label, labelBounds);\n\n // Segment 1: source → label (port sides win at the node end)\n const srcDir =\n portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, labelConnectionBounds);\n const lblDir1 = connectionDirection(edge.label, labelConnectionBounds, sourceBounds);\n const seg1 = route(edge, `${edge.id}:0`, {\n sourceBounds,\n targetBounds: labelConnectionBounds,\n sourceDirection: srcDir,\n targetDirection: lblDir1,\n sourcePoint: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, labelConnectionBounds, srcDir, snap),\n waypoints,\n }, getObstacles);\n\n // Segment 2: label → target\n const lblDir2 = connectionDirection(edge.label, labelConnectionBounds, targetBounds);\n const tgtDir =\n portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, labelConnectionBounds);\n const seg2 = route(edge, `${edge.id}:1`, {\n sourceBounds: labelConnectionBounds,\n targetBounds,\n sourceDirection: lblDir2,\n targetDirection: tgtDir,\n targetPoint: resolveEndpointPoint(target, targetBounds, edge.targetPort, labelConnectionBounds, tgtDir, snap),\n waypoints,\n }, getObstacles);\n\n pathData = { segments: [seg1, seg2], labelBounds };\n } else {\n // No label — single segment; port sides override auto directions\n const srcDir =\n portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);\n const tgtDir =\n portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);\n const path = route(edge, `${edge.id}:0`, {\n sourceBounds,\n targetBounds,\n sourceDirection: srcDir,\n targetDirection: tgtDir,\n sourcePoint,\n targetPoint,\n waypoints,\n }, getObstacles);\n pathData = { segments: [path], labelBounds: null };\n }\n\n const previousPath = trackSourceDependencies\n ? lastCanonicalEdgePaths?.get(edge.id)\n : undefined;\n if (previousPath && plainDataEqual(previousPath, pathData)) {\n pathData = previousPath;\n }\n paths.set(edge.id, pathData);\n if (memoizableEdge) {\n edgePathMemo.set(edge.id, { edge, source, target, path: pathData });\n }\n computing.delete(edge.id);\n return pathData;\n };\n\n for (const edge of [...graph.edges, ...foldedEdgesFor(c).edges]) {\n computeEdgePath(edge);\n }\n finishRouting();\n\n if (trackSourceDependencies) {\n edgeSourceDependents = nextEdgeSourceDependents;\n lastCanonicalEdgePaths = paths;\n }\n\n // Bound memo growth across graph swaps (entries for removed edge ids).\n if (memoUsable && edgePathMemo.size > graph.edges.length * 2 + 16) {\n edgePathMemo.clear();\n }\n\n return paths;\n }\n\n // Subscribe\n\n function subscribe(listener: (ctx: FlowStoreContext) => void): () => void {\n const subscription = store.subscribe((snapshot) => {\n listener(snapshot.context);\n });\n return () => subscription.unsubscribe();\n }\n\n function graphBoundsFor(c: FlowStoreContext): Rect {\n if (\n graphBoundsCache?.nodesInput === c.graph.nodes &&\n graphBoundsCache.edgesInput === c.graph.edges &&\n graphBoundsCache.measurementsInput === c.measurements\n ) {\n return graphBoundsCache.value;\n }\n const value = c.appearances ? getGraphBounds(\n c.graph.nodes.map(sizedNode),\n c.graph.edges.map((edge) => edge.label ? { ...edge, label: { ...edge.label, autoSize: appearanceFor(edge.label).autoSize } } : edge),\n c.measurements,\n ) : getGraphBounds(c.graph.nodes, c.graph.edges, c.measurements);\n graphBoundsCache = {\n nodesInput: c.graph.nodes,\n edgesInput: c.graph.edges,\n measurementsInput: c.measurements,\n value,\n };\n return value;\n }\n\n function spatialCells(rect: Rect): string[] | null {\n const minX = Math.floor(rect.x / SPATIAL_CELL_SIZE);\n const minY = Math.floor(rect.y / SPATIAL_CELL_SIZE);\n const maxX = Math.floor((rect.x + Math.max(0, rect.width)) / SPATIAL_CELL_SIZE);\n const maxY = Math.floor((rect.y + Math.max(0, rect.height)) / SPATIAL_CELL_SIZE);\n const count = (maxX - minX + 1) * (maxY - minY + 1);\n if (count > MAX_ENTITY_SPATIAL_CELLS) return null;\n const cells: string[] = [];\n for (let y = minY; y <= maxY; y++) {\n for (let x = minX; x <= maxX; x++) cells.push(`${x}:${y}`);\n }\n return cells;\n }\n\n function addSpatialEntry(\n cells: Map<string, string[]>,\n globalIds: string[],\n id: string,\n bounds: Rect,\n ): void {\n const keys = spatialCells(bounds);\n if (!keys) {\n globalIds.push(id);\n return;\n }\n for (const key of keys) {\n const ids = cells.get(key);\n if (ids) ids.push(id);\n else cells.set(key, [id]);\n }\n }\n\n function edgeSpatialBounds(\n edge: FlowEdge,\n path: EdgePathData | undefined,\n c: FlowStoreContext,\n ): Rect | null {\n let bounds: Rect | null = path?.labelBounds ?? null;\n for (const segment of path?.segments ?? []) {\n const segmentBounds = pathBounds(segment);\n if (segmentBounds) bounds = bounds ? unionRect(bounds, segmentBounds) : segmentBounds;\n }\n if (bounds) return bounds;\n const source = getNode(edge.sourceId);\n const target = getNode(edge.targetId);\n if (!source || !target) return null;\n return unionRect(\n withLayoutOffset(resolvedBounds(source), source.id, c),\n withLayoutOffset(resolvedBounds(target), target.id, c),\n );\n }\n\n /**\n * Viewport-query index keyed by geometry identities, never viewport. Building\n * is O(n + m); subsequent pan/zoom queries visit occupied viewport cells and\n * visible candidates instead of scanning the graph. Very large entities stay\n * in a small global list to cap cell fanout and retained memory.\n */\n function spatialIndexFor(\n c: FlowStoreContext,\n order: EntityOrderCache['value'],\n paths: Map<string, EdgePathData>,\n ): RenderableSpatialIndex {\n const cached = renderableSpatialIndex;\n if (\n cached?.nodesInput === c.graph.nodes &&\n cached.pathsInput === paths &&\n cached.measurementsInput === c.measurements &&\n cached.layoutOffsetsInput === c.layoutAnimation.offsets &&\n cached.collapsedInput === c.collapsedNodeIds\n ) {\n return cached;\n }\n\n const next: RenderableSpatialIndex = {\n nodesInput: c.graph.nodes,\n pathsInput: paths,\n measurementsInput: c.measurements,\n layoutOffsetsInput: c.layoutAnimation.offsets,\n collapsedInput: c.collapsedNodeIds,\n nodeCells: new Map(),\n edgeCells: new Map(),\n globalNodeIds: [],\n globalEdgeIds: [],\n nodeBounds: new Map(),\n edgeBounds: new Map(),\n };\n for (const node of order.nodes) {\n const bounds = hierarchyBounds(node, c);\n next.nodeBounds.set(node.id, bounds);\n addSpatialEntry(next.nodeCells, next.globalNodeIds, node.id, bounds);\n }\n for (const edge of order.edges) {\n const bounds = edgeSpatialBounds(edge, paths.get(edge.id), c);\n if (!bounds) continue;\n next.edgeBounds.set(edge.id, bounds);\n addSpatialEntry(next.edgeCells, next.globalEdgeIds, edge.id, bounds);\n }\n renderableSpatialIndex = next;\n return next;\n }\n\n function spatialCandidates(\n cells: Map<string, string[]>,\n globalIds: string[],\n rect: Rect,\n ): Set<string> | null {\n const keys = spatialCells(rect);\n if (!keys) return null;\n const ids = new Set(globalIds);\n for (const key of keys) {\n for (const id of cells.get(key) ?? []) ids.add(id);\n }\n return ids;\n }\n\n function entityRanks(order: EntityOrderCache['value']): {\n nodes: Map<string, number>;\n edges: Map<string, number>;\n } {\n if (entityRankCache?.order === order) return entityRankCache;\n const ranks = {\n order,\n nodes: new Map(order.nodes.map((node, index) => [node.id, index])),\n edges: new Map(order.edges.map((edge, index) => [edge.id, index])),\n };\n entityRankCache = ranks;\n return ranks;\n }\n\n function computeRenderableEntities(\n c: FlowStoreContext,\n options: RenderableEntitiesOptions,\n ): { nodes: FlowNode[]; edges: FlowEdge[] } {\n const vp = c.viewport;\n const overscan = options.overscan ?? 0;\n const visibleRect = getVisibleBounds(vp, c.viewportSize);\n const cullRect: Rect = {\n x: visibleRect.x - overscan,\n y: visibleRect.y - overscan,\n width: visibleRect.width + overscan * 2,\n height: visibleRect.height + overscan * 2,\n };\n\n // Fast path: when the whole graph already fits inside the cull rect (e.g.\n // fully zoomed out), every entity trivially passes the viewport test —\n // every node's hierarchy bounds and every edge's endpoints lie within\n // getGraphBounds, which is ⊆ cullRect — so the per-entity geometry tests\n // would all return \"visible\". Skip them and cull by visibility only.\n // Identical result; avoids ~2N intersection tests per frame at scale.\n const cullMode: RenderableEntitiesOptions['cull'] =\n options.cull === 'viewport' &&\n rectContains(\n cullRect,\n graphBoundsFor(c),\n )\n ? 'none'\n : options.cull;\n\n const order = getEntityOrderFor(c);\n if (\n cullMode === 'viewport' &&\n (c.canvasState === 'idle' || c.canvasState === 'panning')\n ) {\n const edgePaths = getAllEdgePaths();\n const spatial = spatialIndexFor(c, order, edgePaths);\n const nodeIds = spatialCandidates(\n spatial.nodeCells,\n spatial.globalNodeIds,\n cullRect,\n );\n const edgeIds = spatialCandidates(\n spatial.edgeCells,\n spatial.globalEdgeIds,\n cullRect,\n );\n if (nodeIds && edgeIds) {\n const ranks = entityRanks(order);\n const nodes = [...nodeIds]\n .sort(\n (left, right) =>\n (ranks.nodes.get(left) ?? 0) - (ranks.nodes.get(right) ?? 0),\n )\n .flatMap((id) => {\n const node = getNode(id);\n const bounds = spatial.nodeBounds.get(id);\n return node &&\n bounds &&\n isNodeVisible(node, c, vp) &&\n rectsIntersect(bounds, cullRect)\n ? [node]\n : [];\n });\n const edges = [...edgeIds]\n .sort(\n (left, right) =>\n (ranks.edges.get(left) ?? 0) - (ranks.edges.get(right) ?? 0),\n )\n .flatMap((id) => {\n const edge = getEdge(id);\n const bounds = spatial.edgeBounds.get(id);\n return edge &&\n bounds &&\n isEdgeVisible(edge, c.graph, c, vp) &&\n rectsIntersect(bounds, cullRect)\n ? [edge]\n : [];\n });\n return { nodes, edges };\n }\n }\n\n const nodes = order.nodes.filter((n) => {\n if (!isNodeVisible(n, c, vp)) return false;\n if (\n cullMode === 'viewport' &&\n !rectsIntersect(hierarchyBounds(n, c), cullRect)\n ) {\n return false;\n }\n return true;\n });\n\n // Only the viewport cull reads edge geometry; skip routing otherwise.\n const edgePaths = cullMode === 'viewport' ? getAllEdgePaths() : undefined;\n const edges = order.edges.filter((e) => {\n if (!isEdgeVisible(e, c.graph, c, vp)) return false;\n if (cullMode !== 'viewport') {\n return true;\n }\n\n const path = edgePaths?.get(e.id);\n if (e.label) {\n const labelRect = path?.labelBounds ?? getEdgeLabelBounds(e.id);\n if (!labelRect) return false;\n if (rectsIntersect(labelRect, cullRect)) {\n return true;\n }\n }\n\n // Cull by the path's bounding box rather than sampling the curve: a\n // bezier is contained in its control points' AABB, so this is a\n // conservative (no false-negative) test that avoids re-sampling every\n // edge's curve on every frame — the dominant drag-frame cost at scale.\n if (\n path?.segments.some((segment) => {\n const bounds = pathBounds(segment);\n return bounds !== null && rectsIntersect(bounds, cullRect);\n })\n ) {\n return true;\n }\n\n const srcNode = getNode(e.sourceId);\n const tgtNode = getNode(e.targetId);\n return !!srcNode && !!tgtNode && (\n rectsIntersect(withLayoutOffset(resolvedBounds(srcNode), srcNode.id, c), cullRect) ||\n rectsIntersect(withLayoutOffset(resolvedBounds(tgtNode), tgtNode.id, c), cullRect)\n );\n });\n\n return { nodes, edges };\n }\n\n function selectedBoostEnabled(kind: 'node' | 'edge'): boolean {\n if (kind === 'node') return engineOptions.elevateOnSelect?.nodes ?? true;\n return engineOptions.elevateOnSelect?.edges ?? false;\n }\n\n function getEntityOrderFor(\n c: FlowStoreContext,\n options: EntityOrderOptions = {},\n ): { nodes: FlowNode[]; edges: FlowEdge[] } {\n const elevateSelected = options.elevateSelected ?? true;\n const selectionInput =\n elevateSelected &&\n (selectedBoostEnabled('node') || selectedBoostEnabled('edge'))\n ? c.selection\n : null;\n const cache = elevateSelected ? entityOrderCache : baseEntityOrderCache;\n if (\n cache?.nodesInput === c.graph.nodes &&\n cache.edgesInput === c.graph.edges &&\n cache.selectionInput === selectionInput &&\n cache.collapsedInput === c.collapsedNodeIds\n ) {\n return cache.value;\n }\n\n const depths = nodeDepths(c.graph.nodes as FlowNode[]);\n const foldedEdges = foldedEdgesFor(c).edges;\n const elevateNodes = elevateSelected && selectedBoostEnabled('node');\n const elevateEdges = elevateSelected && selectedBoostEnabled('edge');\n const nodes = [...(c.graph.nodes as FlowNode[])].sort((a, b) => {\n const depthDelta = (depths.get(a.id) ?? 0) - (depths.get(b.id) ?? 0);\n if (depthDelta !== 0) return depthDelta;\n const zDelta = (a.zIndex ?? 0) - (b.zIndex ?? 0);\n if (zDelta !== 0) return zDelta;\n const selectedDelta =\n Number(elevateNodes && c.selection.has(a.id)) -\n Number(elevateNodes && c.selection.has(b.id));\n if (selectedDelta !== 0) return selectedDelta;\n // Array#sort is stable: equal entities retain canonical graph order.\n return 0;\n });\n\n const edges = [...(c.graph.edges as FlowEdge[]), ...foldedEdges].sort((a, b) => {\n const aDepth = Math.max(depths.get(a.sourceId) ?? 0, depths.get(a.targetId) ?? 0);\n const bDepth = Math.max(depths.get(b.sourceId) ?? 0, depths.get(b.targetId) ?? 0);\n const depthDelta = aDepth - bDepth;\n if (depthDelta !== 0) return depthDelta;\n const zDelta = (a.zIndex ?? 0) - (b.zIndex ?? 0);\n if (zDelta !== 0) return zDelta;\n const selectedDelta =\n Number(elevateEdges && c.selection.has(a.id)) -\n Number(elevateEdges && c.selection.has(b.id));\n if (selectedDelta !== 0) return selectedDelta;\n return 0;\n });\n\n const value = { nodes, edges };\n const nextCache = {\n nodesInput: c.graph.nodes,\n edgesInput: c.graph.edges,\n selectionInput,\n collapsedInput: c.collapsedNodeIds,\n value,\n };\n if (elevateSelected) entityOrderCache = nextCache;\n else baseEntityOrderCache = nextCache;\n return value;\n }\n\n function getPaintZIndicesFor(\n c: FlowStoreContext,\n options: EntityOrderOptions = {},\n ): PaintZIndices {\n const elevateSelected = options.elevateSelected ?? true;\n const cacheKey = `${optionsVersion}:${elevateSelected}`;\n const snapshotCache = paintZIndicesCache.get(c);\n const cached = snapshotCache?.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const baseOrder = getEntityOrderFor(c, { elevateSelected: false });\n const depths = nodeDepths(c.graph.nodes as FlowNode[]);\n const visibleNodes = baseOrder.nodes.filter((node) =>\n isNodeVisible(node, c),\n );\n const visibleEdges = baseOrder.edges.filter((edge) =>\n isEdgeVisible(edge, c.graph, c),\n );\n const nodes = new Map<string, number>();\n const edges = new Map<string, number>();\n\n for (let start = 0; start < visibleNodes.length; ) {\n const first = visibleNodes[start]!;\n const depth = depths.get(first.id) ?? 0;\n const zIndex = first.zIndex ?? 0;\n let end = start + 1;\n while (end < visibleNodes.length) {\n const node = visibleNodes[end]!;\n if (\n (depths.get(node.id) ?? 0) !== depth ||\n (node.zIndex ?? 0) !== zIndex\n ) {\n break;\n }\n end++;\n }\n const elevatedZIndex = 2 * (end - 1) + 1;\n for (let index = start; index < end; index++) {\n const node = visibleNodes[index]!;\n nodes.set(\n node.id,\n elevateSelected &&\n selectedBoostEnabled('node') &&\n c.selection.has(node.id)\n ? elevatedZIndex\n : 2 * index,\n );\n }\n start = end;\n }\n\n for (let start = 0; start < visibleEdges.length; ) {\n const first = visibleEdges[start]!;\n const depth = Math.max(\n depths.get(first.sourceId) ?? 0,\n depths.get(first.targetId) ?? 0,\n );\n const zIndex = first.zIndex ?? 0;\n let end = start + 1;\n while (end < visibleEdges.length) {\n const edge = visibleEdges[end]!;\n if (\n Math.max(\n depths.get(edge.sourceId) ?? 0,\n depths.get(edge.targetId) ?? 0,\n ) !== depth ||\n (edge.zIndex ?? 0) !== zIndex\n ) {\n break;\n }\n end++;\n }\n const elevatedZIndex = 2 * (end - 1) + 1;\n for (let index = start; index < end; index++) {\n const edge = visibleEdges[index]!;\n edges.set(\n edge.id,\n elevateSelected &&\n selectedBoostEnabled('edge') &&\n c.selection.has(edge.id)\n ? elevatedZIndex\n : 2 * index,\n );\n }\n start = end;\n }\n\n const value = { nodes, edges };\n const nextSnapshotCache =\n snapshotCache ?? new Map<string, PaintZIndices>();\n nextSnapshotCache.set(cacheKey, value);\n if (!snapshotCache) paintZIndicesCache.set(c, nextSnapshotCache);\n return value;\n }\n\n // Public API (purely derived — no mutable state)\n\n function getPublicVisualBounds(nodeOrId: FlowNode | string): Rect {\n const node = typeof nodeOrId === 'string' ? getNode(nodeOrId) : nodeOrId;\n if (!node) return { x: 0, y: 0, width: 0, height: 0 };\n return visualBounds(node, getVisualSnapOffset());\n }\n\n function getPublicVisualPosition(nodeOrId: FlowNode | string): Point {\n const bounds = getPublicVisualBounds(nodeOrId);\n return { x: bounds.x, y: bounds.y };\n }\n\n return {\n store,\n trigger: store.trigger,\n getContext: ctx,\n setOptions,\n invalidateRoutes,\n\n resolveAppearance: appearanceFor,\n isPortAllowed,\n getConnectionBounds: (id: string): Rect | null => {\n const node = getNode(id);\n if (node) return connectionBounds(id, node, getPublicVisualBounds(node));\n const edge = getEdge(id);\n const bounds = getAllEdgePaths().get(id)?.labelBounds;\n return edge?.label && bounds ? connectionBounds(id, edge.label, bounds) : null;\n },\n // Entity accessors\n getNode,\n getEdge,\n getEntity,\n getAddressable,\n getEntityRef,\n getOwnerEntity,\n getBounds,\n\n // Coordinate conversion\n screenToCanvas,\n canvasToScreen,\n\n // Hit testing\n entityAtPoint,\n entityIdAtPoint,\n getConnectionCandidate,\n\n // Edge routing\n getEdgePath,\n getEdgePathBounds,\n getEdgeLabelBounds,\n getAllEdgePaths,\n getEdgeSourceDependents: (edgeId: string): readonly string[] => [\n ...(edgeSourceDependents.get(edgeId) ?? []),\n ],\n\n // Visual positions (accept node or id)\n visualPosition: getPublicVisualPosition,\n visualBounds: getPublicVisualBounds,\n /** @deprecated Use `visualPosition`. */\n resolvedPosition: getPublicVisualPosition,\n /** @deprecated Use `visualBounds`. */\n resolvedBounds: getPublicVisualBounds,\n\n /**\n * All highlights on an entity as `{ kind, meta }` entries. Returns a\n * referentially stable array (the same empty array when none), so\n * subscribers can use identity equality.\n */\n getHighlights: (entityId: string): ReadonlyArray<{ kind: string; meta: unknown }> => {\n const highlights = ctx().highlights;\n if (highlights.size === 0) return NO_HIGHLIGHTS;\n let index = highlightIndexCache.get(highlights);\n if (!index) {\n index = new Map();\n for (const [kind, bucket] of highlights) {\n for (const [id, meta] of bucket) {\n let entries = index.get(id);\n if (!entries) index.set(id, (entries = []));\n entries.push({ kind, meta });\n }\n }\n highlightIndexCache.set(highlights, index);\n }\n return index.get(entityId) ?? NO_HIGHLIGHTS;\n },\n\n /** Whether the entity is currently hovered. */\n isHovered: (entityId: string): boolean =>\n ctx().hoveredEntityIds.has(entityId),\n\n /**\n * Deepest group whose child area intersects `bounds`, with the overlap\n * ratio (intersection / bounds area). Groups in `exclude` (and groups\n * inside excluded subtrees) are skipped, and excluded nodes do not\n * contribute to derived child areas — i.e. each group is evaluated as it\n * would be without the moving nodes. Drives reparent-on-drop.\n */\n getGroupDropTarget: (\n bounds: Rect,\n options: { exclude?: Iterable<string> } = {},\n ): { id: string; overlap: number; childArea: Rect } | null => {\n const c = ctx();\n const excluded = new Set(options.exclude ?? []);\n const nodeIndex = indexNodes(c.graph.nodes);\n const depths = nodeDepths(c.graph.nodes as FlowNode[]);\n const area = Math.max(bounds.width * bounds.height, 1);\n\n let best:\n | { id: string; overlap: number; childArea: Rect; depth: number }\n | null = null;\n for (const node of c.graph.nodes) {\n if (!node.group || node.hidden || excluded.has(node.id)) continue;\n // skip groups inside an excluded (moving) subtree\n let ancestorId = node.parentId ?? null;\n let insideExcluded = false;\n const seen = new Set<string>();\n while (ancestorId && !seen.has(ancestorId)) {\n if (excluded.has(ancestorId)) {\n insideExcluded = true;\n break;\n }\n seen.add(ancestorId);\n ancestorId = nodeIndex.get(ancestorId)?.parentId ?? null;\n }\n if (insideExcluded) continue;\n\n const childArea = computeGroupGeometryRaw(\n c,\n node,\n undefined,\n excluded,\n ).childArea;\n const ix = Math.max(\n 0,\n Math.min(bounds.x + bounds.width, childArea.x + childArea.width) -\n Math.max(bounds.x, childArea.x),\n );\n const iy = Math.max(\n 0,\n Math.min(bounds.y + bounds.height, childArea.y + childArea.height) -\n Math.max(bounds.y, childArea.y),\n );\n const overlap = (ix * iy) / area;\n if (overlap <= 0) continue;\n const depth = depths.get(node.id) ?? 0;\n if (\n !best ||\n depth > best.depth ||\n (depth === best.depth && overlap > best.overlap)\n ) {\n best = { id: node.id, overlap, childArea, depth };\n }\n }\n return best\n ? { id: best.id, overlap: best.overlap, childArea: best.childArea }\n : null;\n },\n\n /**\n * Canvas-space anchor rect for toolbars: a node's (hierarchy-aware)\n * bounds, an edge's label bounds — or, with no label, an assumed 1×1\n * label at the path midpoint — and, given several ids (e.g. the\n * selection), the union of their anchors. Null when nothing resolves.\n */\n getToolbarAnchor: (idOrIds: string | Iterable<string>): Rect | null => {\n const ids = typeof idOrIds === 'string' ? [idOrIds] : [...idOrIds];\n const c = ctx();\n let union: Rect | null = null;\n for (const id of ids) {\n let rect: Rect | null = null;\n const node = getNode(id);\n if (node) {\n rect = hierarchyBounds(node, c);\n } else {\n const edge = getEdge(id);\n if (edge?.label) {\n const labelBounds = getEdgeLabelBounds(edge.id);\n if (labelBounds && (labelBounds.width || labelBounds.height)) {\n rect = labelBounds;\n }\n } else if (edge) {\n const points =\n getAllEdgePaths().get(id)?.segments[0]?.points ?? [];\n if (points.length > 0) {\n const mid =\n points.length % 2 === 1\n ? points[(points.length - 1) / 2]\n : {\n x: (points[points.length / 2 - 1].x + points[points.length / 2].x) / 2,\n y: (points[points.length / 2 - 1].y + points[points.length / 2].y) / 2,\n };\n rect = { x: mid.x, y: mid.y, width: 1, height: 1 };\n }\n }\n }\n if (!rect) continue;\n union = union ? uniteRects(union, rect) : rect;\n }\n return union;\n },\n\n /** The node containing this edge (null = root). See `edgeOwner` option. */\n getEdgeOwner: (edgeId: string): string | null => {\n const c = ctx();\n const edge = indexEdges(c.graph.edges).get(edgeId);\n if (!edge) return null;\n return edgeOwnerOf(edge as FlowEdge, c);\n },\n\n /** Group geometry (overall bounds, content block, child area), or null. */\n getGroupGeometry: (nodeOrId: FlowNode | string): GroupGeometry | null => {\n const node = typeof nodeOrId === 'string' ? getNode(nodeOrId) : nodeOrId;\n if (!node) return null;\n return groupGeometryFor(ctx(), node);\n },\n\n // Graph bounds\n getGraphBounds: () => {\n return graphBoundsFor(ctx());\n },\n\n // Graph traversal\n getIncomers: (nodeId: string): FlowNode[] => getGraphIncomers(ctx().graph, nodeId),\n getOutgoers: (nodeId: string): FlowNode[] => getGraphOutgoers(ctx().graph, nodeId),\n getConnectedEdges: (nodeIds: Iterable<string>): FlowEdge[] =>\n getGraphConnectedEdges(ctx().graph, nodeIds),\n getNeighbors: (nodeId: string): FlowNode[] => getGraphNeighbors(ctx().graph, nodeId),\n\n // Selection bounds\n getSelectionBounds: () => {\n const c = ctx();\n return getSelectionSnapBounds(c, true);\n },\n\n // Find entities within a rect (for box-select, etc.)\n entitiesInRect: (rect: Rect): string[] => {\n const c = ctx();\n const { graph } = c;\n const ids: string[] = [];\n for (const n of graph.nodes) {\n if (!isNodeVisible(n, c)) continue;\n const bounds = n.selectionBounds\n ? resolvedSelectionBounds(sizedNode(n))\n : visualBounds(n, getVisualSnapOffset());\n if (rectsIntersect(rect, bounds)) {\n ids.push(n.id);\n }\n }\n for (const e of graph.edges) {\n if (!isEdgeVisible(e, graph, c)) continue;\n if (!e.label) continue;\n const lb = getEdgeLabelBounds(e.id)!;\n if (rectsIntersect(rect, lb)) ids.push(e.id);\n }\n return ids;\n },\n\n // Port resolution\n \n getPortPosition: (nodeId: string, portName: string): Point | null => {\n const node = getNode(nodeId);\n if (!node?.ports) return null;\n const port = node.ports.find((p) => p.name === portName);\n if (!port) return null;\n return portCenter(node, port);\n },\n\n getPortPositions: (nodeId: string): Map<string, Point> => {\n const result = new Map<string, Point>();\n const node = getNode(nodeId);\n if (!node?.ports) return result;\n const snap = getVisualSnapOffset();\n for (const port of node.ports) {\n result.set(port.name, portCenter(node, port, snap));\n }\n return result;\n },\n\n getEdgeEndpoints: (edgeId: string): { source: Point; target: Point } | null => {\n const { graph } = ctx();\n const edge = graph.edges.find((e) => e.id === edgeId);\n if (!edge) return null;\n\n const authoritative = resolvedAuthoritativePath(edge);\n if (authoritative) {\n return {\n source: authoritative.points[0]!,\n target: authoritative.points.at(-1)!,\n };\n }\n\n if (edge.label) {\n const path = getAllEdgePaths().get(edgeId);\n const first = path?.segments[0]?.points[0];\n const last = path?.segments.at(-1)?.points.at(-1);\n if (first && last) return { source: first, target: last };\n }\n const srcNode = graph.nodes.find((n) => n.id === edge.sourceId);\n const tgtNode = graph.nodes.find((n) => n.id === edge.targetId);\n if (!srcNode || !tgtNode) return null;\n\n const snap = getVisualSnapOffset();\n const { sourcePoint, targetPoint } = resolveEdgeGeometry(\n edge,\n srcNode,\n tgtNode,\n snap,\n (id) => getAllEdgePaths().get(id)?.labelBounds ?? getEdgeLabelBounds(id),\n graph,\n ctx(),\n );\n return { source: sourcePoint, target: targetPoint };\n },\n\n // Connection validation\n \n validateConnection,\n validateConnectionDetailed,\n\n // Entity config resolution\n \n resolveEntityConfig,\n\n // Visibility\n \n getVisibleEntities: (\n options: EntityOrderOptions = {},\n ): { nodes: FlowNode[]; edges: FlowEdge[] } => {\n const c = ctx();\n const order = getEntityOrderFor(c, options);\n return {\n nodes: order.nodes.filter((n) => isNodeVisible(n, c)),\n edges: order.edges.filter((e) => isEdgeVisible(e, c.graph, c)),\n };\n },\n\n /** Deterministic paint order. Later items should paint above earlier ones. */\n getEntityOrder: (\n options: EntityOrderOptions = {},\n ): { nodes: FlowNode[]; edges: FlowEdge[] } => getEntityOrderFor(ctx(), options),\n\n /**\n * CSS z-indices for the visible entity set. Base values are spaced by 2.\n * When `elevateOnSelect` allows an entity kind, a selected entity is\n * raised just above its own depth/zIndex band while remaining below the\n * next band, so a selected parent never paints over its descendants.\n * Multiple selected entities in one band tie; the renderer's DOM order\n * resolves the tie and matches core's elevated order. The result is\n * memoized per store snapshot so callers can compare it by identity.\n */\n getPaintZIndices: (\n options: EntityOrderOptions = {},\n ): PaintZIndices => getPaintZIndicesFor(ctx(), options),\n\n /**\n * Renderable (visible, optionally viewport-culled) entities. Memoized per\n * (store snapshot, cull/overscan) so several render layers can share one\n * computation per frame. Treat the result as read-only.\n */\n getRenderableEntities: (options: RenderableEntitiesOptions = {}): { nodes: FlowNode[]; edges: FlowEdge[] } => {\n const c = ctx();\n const cacheKey = `${optionsVersion}:${options.cull ?? 'none'}:${options.overscan ?? 0}`;\n let byKey = renderableCache.get(c);\n const cached = byKey?.get(cacheKey);\n if (cached) return cached;\n const result = computeRenderableEntities(c, options);\n if (!byKey) {\n byKey = new Map();\n renderableCache.set(c, byKey);\n }\n byKey.set(cacheKey, result);\n return result;\n },\n\n // Intersection\n \n getIntersectingNodes: (nodeId: string): FlowNode[] => {\n const node = getNode(nodeId);\n if (!node) return [];\n const bounds = visualBounds(node, getVisualSnapOffset());\n return ctx().graph.nodes.filter(\n (n) =>\n n.id !== nodeId &&\n rectsIntersect(bounds, visualBounds(n, getVisualSnapOffset())),\n );\n },\n\n // A11y\n \n getAriaLabel: (entityId: string): string => {\n const { graph } = ctx();\n const node = graph.nodes.find((n) => n.id === entityId);\n if (node) return `Node: ${node.label ?? node.id}`;\n const edge = graph.edges.find((e) => e.id === entityId);\n if (edge) {\n const customLabel = (edge.data as { ariaLabel?: unknown } | undefined)?.ariaLabel;\n if (typeof customLabel === 'string') return customLabel;\n const src = graph.nodes.find((n) => n.id === edge.sourceId);\n const tgt = graph.nodes.find((n) => n.id === edge.targetId);\n const label = edge.label ? ` (${(edge.label.data as any)?.text ?? ''})` : '';\n return `Edge: ${src?.label ?? edge.sourceId} → ${tgt?.label ?? edge.targetId}${label}`;\n }\n return entityId;\n },\n\n // Snap lines (Figma-style alignment guides — purely derived)\n \n /** Compute snap result during drag. Returns null if not dragging or snap lines disabled.\n * Only activates after actual movement (dx/dy != 0) to avoid showing on click. */\n getSnapResult: (): SnapResult | null => {\n const c = ctx();\n if (c.canvasState !== 'dragging' || !c.enableSnapLines) return null;\n if (c.selection.size === 0) return null;\n\n // Don't show snap lines until user has actually moved\n const nodesMoved = c.graph.nodes.some((n) => c.selection.has(n.id) && ((n.dx ?? 0) !== 0 || (n.dy ?? 0) !== 0));\n const edgesMoved = c.graph.edges.some((e) => c.selection.has(e.id) && e.label && ((e.label.dx ?? 0) !== 0 || (e.label.dy ?? 0) !== 0));\n if (!nodesMoved && !edgesMoved) return null;\n\n const selBounds = getSelectionSnapBounds(c);\n if (!selBounds) return null;\n\n const otherRects = getSnapTargetRects(c, c.selection);\n if (otherRects.length === 0) return null;\n\n // Threshold: screen pixels → canvas pixels\n const canvasThreshold = c.snapThreshold / c.viewport.zoom;\n\n return getSnapLines(selBounds, otherRects, {\n threshold: canvasThreshold,\n enableSpacing: c.enableSpacingGuides,\n });\n },\n\n // Resize\n \n /** Get in-progress resize bounds, or null if not resizing */\n getResizeBounds: (): Rect | null => {\n return getResizeBoundsFromContext(ctx());\n },\n\n // Subscribe\n subscribe,\n };\n}\n\nexport type FlowEngine = ReturnType<typeof createFlowEngine>;\n\n\n// Helpers\n\nfunction getResizeBoundsFromContext(c: FlowStoreContext): Rect | null {\n if (!c.resizeCorners || !c.resizingEntityId) return null;\n const [a, b] = c.resizeCorners;\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n // Match the store's free-resize commit floor (1px degeneracy guard) so the\n // live preview never pops at commit time. The store's clampResizeMovingPoint\n // has already applied any explicit resize.min/max to the corners.\n width: Math.max(1, Math.abs(b.x - a.x)),\n height: Math.max(1, Math.abs(b.y - a.y)),\n };\n}\n\nfunction boundsForPoints(points: Point[]): Rect | null {\n if (points.length === 0) return null;\n\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const point of points) {\n minX = Math.min(minX, point.x);\n minY = Math.min(minY, point.y);\n maxX = Math.max(maxX, point.x);\n maxY = Math.max(maxY, point.y);\n }\n\n if (!isFinite(minX)) return null;\n\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY,\n };\n}\n\n/**\n * Resolve label anchor position. Returns the TOP-LEFT corner of the label.\n * For 'fixed': label.x/y IS the top-left (like a node).\n * For number: interpolates between source/target centers, then offsets to top-left.\n * For function: calls the function, then offsets to top-left.\n */\nfunction resolveLabelAnchor(\n anchor: LabelAnchor,\n label: FlowEdgeLabel,\n sourceBounds: Rect,\n targetBounds: Rect,\n edge: FlowEdge,\n size = { width: label.width, height: label.height },\n): Point {\n if (anchor === 'fixed') {\n // label.x/y is top-left, just like a node\n return { x: label.x, y: label.y };\n }\n\n if (typeof anchor === 'function') {\n const center = anchor(sourceBounds, targetBounds, edge);\n return { x: center.x - size.width / 2, y: center.y - size.height / 2 };\n }\n\n // number: interpolate between source center and target center, return top-left\n const t = anchor;\n const srcCx = sourceBounds.x + sourceBounds.width / 2;\n const srcCy = sourceBounds.y + sourceBounds.height / 2;\n const tgtCx = targetBounds.x + targetBounds.width / 2;\n const tgtCy = targetBounds.y + targetBounds.height / 2;\n return {\n x: srcCx + (tgtCx - srcCx) * t - size.width / 2,\n y: srcCy + (tgtCy - srcCy) * t - size.height / 2,\n };\n}\n","import type {\n FlowEdge,\n FlowEdgeLabel,\n FlowGraph,\n FlowNode,\n FlowPort,\n} from './types';\n\n// Factory functions — convenient constructors with sensible defaults\n\nexport function createNode<TData = any>(\n opts: Partial<FlowNode<TData>> & { id: string },\n): FlowNode<TData> {\n return {\n type: 'node',\n x: 0,\n y: 0,\n width: 150,\n height: 50,\n data: {} as TData,\n ...opts,\n };\n}\n\nexport function createEdge<TEdgeData = any, TLabelData = any>(\n opts: Omit<Partial<FlowEdge<TEdgeData, TLabelData>>, 'label'> &\n Pick<FlowEdge<TEdgeData, TLabelData>, 'id' | 'sourceId' | 'targetId'> & {\n label?: Partial<FlowEdgeLabel<TLabelData>> & { width: number; height: number };\n },\n): FlowEdge<TEdgeData, TLabelData> {\n const { label, ...rest } = opts;\n return {\n type: 'edge',\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n data: {} as TEdgeData,\n ...rest,\n label: label\n ? { x: 0, y: 0, data: {} as TLabelData, ...label }\n : undefined,\n };\n}\n\nexport function createGraph<TNodeData = any, TEdgeData = any>(\n opts: Partial<FlowGraph<TNodeData, TEdgeData>> & {\n nodes: FlowNode<TNodeData>[];\n edges: FlowEdge<TEdgeData>[];\n },\n): FlowGraph<TNodeData, TEdgeData> {\n return {\n direction: 'down',\n ...opts,\n };\n}\n\nexport function createPort<TData = any>(\n opts: Partial<FlowPort<TData>> &\n Pick<FlowPort<TData>, 'name' | 'side' | 'direction'>,\n): FlowPort<TData> {\n return {\n x: 0,\n y: 0,\n width: 12,\n height: 12,\n data: {} as TData,\n ...opts,\n };\n}\n","import type {\n FlowEdge,\n FlowEdgeLabel,\n FlowGraph,\n FlowNode,\n Viewport,\n} from './types';\nimport {\n cloneJsonSafe,\n currentDataVersions,\n FlowGraphValidationError,\n validateAndCloneGraph,\n validateViewport,\n type FlowDataKind,\n type FlowDataSchemas,\n type FlowDataVersions,\n type FlowValidationIssue,\n} from './validation';\n\nexport type FlowSerialized<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n version: 1;\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>;\n viewport: Viewport;\n collapsedNodeIds?: string[];\n dataVersions?: FlowDataVersions;\n};\n\nfunction migrateDataValue<TData>(\n value: unknown,\n kind: FlowDataKind,\n fromVersion: number,\n contract: import('./validation').FlowDataSchema<TData> | undefined,\n path: string,\n): unknown {\n if (!contract || fromVersion === contract.version) return value;\n if (fromVersion > contract.version) {\n throw new FlowGraphValidationError([\n {\n code: 'unsupported_data_version',\n path,\n message: `${kind} data version ${fromVersion} is newer than supported version ${contract.version}`,\n },\n ]);\n }\n if (!contract.migrate) {\n throw new FlowGraphValidationError([\n {\n code: 'missing_data_migration',\n path,\n message: `${kind} data requires migration from version ${fromVersion} to ${contract.version}`,\n },\n ]);\n }\n const migrated = contract.migrate(value, {\n fromVersion,\n toVersion: contract.version,\n });\n if (migrated && typeof (migrated as { then?: unknown }).then === 'function') {\n throw new FlowGraphValidationError([\n {\n code: 'async_data_migration',\n path,\n message: 'Flow data migrations must be synchronous',\n },\n ]);\n }\n return migrated;\n}\n\n/**\n * Parse, migrate, and validate a persisted Flow document.\n *\n * Versionless documents are treated as version 0. Data migrations must be\n * synchronous. The returned graph is detached from `input`; invalid documents\n * throw `FlowGraphValidationError` with stable issue paths.\n */\nexport function parseFlowSerialized<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n input: unknown,\n schemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>,\n): FlowSerialized<TNodeData, TEdgeData, TLabelData> {\n if (!input || typeof input !== 'object' || Array.isArray(input)) {\n throw new FlowGraphValidationError([\n { code: 'invalid_document', path: '$', message: 'expected a Flow document object' },\n ]);\n }\n const document = cloneJsonSafe(input, '$') as Record<string, unknown>;\n const version = document.version ?? 0;\n if (version !== 0 && version !== 1) {\n throw new FlowGraphValidationError([\n {\n code: 'unsupported_version',\n path: '$.version',\n message: `unsupported Flow document version ${String(version)}`,\n },\n ]);\n }\n if (!document.graph || typeof document.graph !== 'object') {\n throw new FlowGraphValidationError([\n { code: 'invalid_graph', path: '$.graph', message: 'expected a graph object' },\n ]);\n }\n\n const rawGraph = validateAndCloneGraph<TNodeData, TEdgeData, TLabelData>(\n document.graph,\n );\n const storedVersions =\n document.dataVersions && typeof document.dataVersions === 'object'\n ? (document.dataVersions as FlowDataVersions)\n : {};\n if (schemas) {\n rawGraph.nodes?.forEach((node, index) => {\n node.data = migrateDataValue(\n node.data,\n 'node',\n storedVersions.node ?? 0,\n schemas.node,\n `$.graph.nodes[${index}].data`,\n ) as TNodeData;\n });\n rawGraph.edges?.forEach((edge, index) => {\n edge.data = migrateDataValue(\n edge.data,\n 'edge',\n storedVersions.edge ?? 0,\n schemas.edge,\n `$.graph.edges[${index}].data`,\n ) as TEdgeData;\n if (edge.label) {\n edge.label.data = migrateDataValue(\n edge.label.data,\n 'label',\n storedVersions.label ?? 0,\n schemas.label,\n `$.graph.edges[${index}].label.data`,\n ) as TLabelData;\n }\n });\n }\n\n const graph = validateAndCloneGraph(rawGraph, schemas);\n const viewport = validateViewport(document.viewport ?? { x: 0, y: 0, zoom: 1 });\n const collapsedNodeIds = Array.isArray(document.collapsedNodeIds)\n ? document.collapsedNodeIds\n : [];\n const nodeIds = new Set(graph.nodes.map((node) => node.id));\n const issues: FlowValidationIssue[] = [];\n collapsedNodeIds.forEach((id, index) => {\n if (typeof id !== 'string' || !nodeIds.has(id)) {\n issues.push({\n code: 'missing_collapsed_node',\n path: `$.collapsedNodeIds[${index}]`,\n message: `node \"${String(id)}\" does not exist`,\n });\n }\n });\n if (issues.length > 0) throw new FlowGraphValidationError(issues);\n\n return {\n version: 1,\n graph,\n viewport,\n ...(collapsedNodeIds.length > 0 ? { collapsedNodeIds: [...collapsedNodeIds] } : {}),\n ...(currentDataVersions(schemas) ? { dataVersions: currentDataVersions(schemas) } : {}),\n };\n}\n\n/**\n * Create a persistence-safe graph snapshot.\n *\n * Transient drag and measurement state is folded into authored coordinates or\n * removed. Nested geometry objects are copied so callers can mutate the result\n * without changing the live graph.\n */\nexport function serializeFlowGraph<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n): FlowGraph<TNodeData, TEdgeData, TLabelData> {\n return {\n ...graph,\n nodes: graph.nodes.map(serializeNode) as FlowNode<TNodeData>[],\n edges: graph.edges.map(serializeEdge) as FlowEdge<TEdgeData, TLabelData>[],\n };\n}\n\nfunction serializeNode<TNodeData>(node: FlowNode<TNodeData>): FlowNode<TNodeData> {\n const anchorOffset = node.measured?.anchorOffset;\n const serialized: FlowNode<TNodeData> = {\n ...node,\n x: node.x + (node.dx ?? 0) - (anchorOffset?.x ?? 0),\n y: node.y + (node.dy ?? 0) - (anchorOffset?.y ?? 0),\n ...(node.style ? { style: { ...node.style } } : {}),\n ...(node.ports\n ? { ports: node.ports.map((port) => ({ ...port })) as FlowNode<TNodeData>['ports'] }\n : {}),\n ...(node.group ? { group: { ...node.group } } : {}),\n ...(node.resize ? { resize: { ...node.resize } } : {}),\n };\n delete serialized.dx;\n delete serialized.dy;\n delete serialized.measured;\n return serialized;\n}\n\nfunction serializeEdge<TEdgeData, TLabelData>(\n edge: FlowEdge<TEdgeData, TLabelData>,\n): FlowEdge<TEdgeData, TLabelData> {\n const dx = edge.dx ?? 0;\n const dy = edge.dy ?? 0;\n const serialized: FlowEdge<TEdgeData, TLabelData> = {\n ...edge,\n ...(edge.label ? { label: serializeLabel(edge.label) } : {}),\n ...(edge.style ? { style: { ...edge.style } } : {}),\n ...(edge.points ? { points: edge.points.map((point) => ({ ...point })) } : {}),\n ...(edge.waypoints\n ? {\n waypoints: edge.waypoints.map((point) => ({\n x: point.x + dx,\n y: point.y + dy,\n })),\n }\n : {}),\n };\n delete serialized.dx;\n delete serialized.dy;\n if (typeof serialized.labelAnchor === 'function') {\n delete serialized.labelAnchor;\n }\n return serialized;\n}\n\nfunction serializeLabel<TLabelData>(\n label: FlowEdgeLabel<TLabelData>,\n): FlowEdgeLabel<TLabelData> {\n const serialized: FlowEdgeLabel<TLabelData> = {\n ...label,\n x: label.x + (label.dx ?? 0),\n y: label.y + (label.dy ?? 0),\n ...(label.style ? { style: { ...label.style } } : {}),\n };\n delete serialized.dx;\n delete serialized.dy;\n return serialized;\n}\n","import { getPatches } from '@statelyai/graph';\nimport type { FlowEdge, FlowGraph, FlowNode } from './types';\nimport {\n validateAndCloneGraph,\n type FlowDataSchemas,\n type FlowResult,\n FlowGraphValidationError,\n} from './validation';\n\nexport type FlowPatch<TNodeData = any, TEdgeData = any, TLabelData = any> =\n | { op: 'addNode'; node: FlowNode<TNodeData> }\n | { op: 'updateNode'; id: string; before: FlowNode<TNodeData>; after: FlowNode<TNodeData> }\n | { op: 'deleteNode'; node: FlowNode<TNodeData> }\n | { op: 'addEdge'; edge: FlowEdge<TEdgeData, TLabelData> }\n | {\n op: 'updateEdge';\n id: string;\n before: FlowEdge<TEdgeData, TLabelData>;\n after: FlowEdge<TEdgeData, TLabelData>;\n }\n | { op: 'deleteEdge'; edge: FlowEdge<TEdgeData, TLabelData> }\n | {\n op: 'updateGraph';\n before: Omit<FlowGraph<TNodeData, TEdgeData, TLabelData>, 'nodes' | 'edges'>;\n after: Omit<FlowGraph<TNodeData, TEdgeData, TLabelData>, 'nodes' | 'edges'>;\n };\n\nexport type FlowEntityUpdate<TEntity> = {\n id: string;\n before: TEntity;\n after: TEntity;\n};\n\nexport type FlowChangeSet<TNodeData = any, TEdgeData = any, TLabelData = any> = {\n version: 1;\n origin?: string;\n transactionId?: string;\n revision: number;\n nodes: {\n added: FlowNode<TNodeData>[];\n removed: FlowNode<TNodeData>[];\n updated: FlowEntityUpdate<FlowNode<TNodeData>>[];\n };\n edges: {\n added: FlowEdge<TEdgeData, TLabelData>[];\n removed: FlowEdge<TEdgeData, TLabelData>[];\n updated: FlowEntityUpdate<FlowEdge<TEdgeData, TLabelData>>[];\n };\n forward: FlowPatch<TNodeData, TEdgeData, TLabelData>[];\n inverse: FlowPatch<TNodeData, TEdgeData, TLabelData>[];\n};\n\nfunction equal(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) &&\n a.length === b.length && a.every((value, index) => equal(value, b[index]));\n }\n const aRecord = a as Record<string, unknown>;\n const bRecord = b as Record<string, unknown>;\n // A key holding `undefined` counts as absent: stored graphs drop such keys,\n // so a projection that spells them out must still compare equal.\n const aKeys = Object.keys(aRecord).filter((key) => aRecord[key] !== undefined);\n const bKeys = Object.keys(bRecord).filter((key) => bRecord[key] !== undefined);\n return aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.prototype.hasOwnProperty.call(bRecord, key) &&\n equal(aRecord[key], bRecord[key]));\n}\n\nfunction graphAttrs<TNodeData, TEdgeData, TLabelData>(\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n): Omit<FlowGraph<TNodeData, TEdgeData, TLabelData>, 'nodes' | 'edges'> {\n const { nodes: _nodes, edges: _edges, ...attrs } = graph;\n return attrs;\n}\n\nfunction patchKey(patch: { op: string; id?: string; node?: { id: string }; edge?: { id: string } }): string {\n return `${patch.op}:${patch.id ?? patch.node?.id ?? patch.edge?.id ?? ''}`;\n}\n\nconst OP_ORDER: Record<FlowPatch['op'], number> = {\n addNode: 0,\n updateEdge: 1,\n deleteEdge: 2,\n deleteNode: 3,\n addEdge: 4,\n updateNode: 5,\n updateGraph: 6,\n};\n\nfunction orderPatches<TNodeData, TEdgeData, TLabelData>(\n before: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n after: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n patches: FlowPatch<TNodeData, TEdgeData, TLabelData>[],\n): FlowPatch<TNodeData, TEdgeData, TLabelData>[] {\n const upstreamBefore = { ...before, id: before.id ?? '' };\n const upstreamAfter = { ...after, id: after.id ?? '' };\n const upstreamOrder = new Map(\n getPatches(\n upstreamBefore as unknown as Parameters<typeof getPatches>[0],\n upstreamAfter as unknown as Parameters<typeof getPatches>[1],\n ).map((patch, index) => [patchKey(patch), index]),\n );\n return patches.sort((a, b) => {\n const operationOrder = OP_ORDER[a.op] - OP_ORDER[b.op];\n if (operationOrder !== 0) return operationOrder;\n return (\n (upstreamOrder.get(patchKey(a)) ?? Number.MAX_SAFE_INTEGER) -\n (upstreamOrder.get(patchKey(b)) ?? Number.MAX_SAFE_INTEGER)\n );\n });\n}\n\nfunction invertPatch<TNodeData, TEdgeData, TLabelData>(\n patch: FlowPatch<TNodeData, TEdgeData, TLabelData>,\n): FlowPatch<TNodeData, TEdgeData, TLabelData> {\n switch (patch.op) {\n case 'addNode':\n return { op: 'deleteNode', node: patch.node };\n case 'deleteNode':\n return { op: 'addNode', node: patch.node };\n case 'updateNode':\n return { ...patch, before: patch.after, after: patch.before };\n case 'addEdge':\n return { op: 'deleteEdge', edge: patch.edge };\n case 'deleteEdge':\n return { op: 'addEdge', edge: patch.edge };\n case 'updateEdge':\n return { ...patch, before: patch.after, after: patch.before };\n case 'updateGraph':\n return { ...patch, before: patch.after, after: patch.before };\n }\n}\n\nexport function createFlowChangeSet<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n before: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n after: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n metadata: { origin?: string; transactionId?: string; revision: number },\n): FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null {\n const beforeNodes = new Map(before.nodes.map((node) => [node.id, node]));\n const afterNodes = new Map(after.nodes.map((node) => [node.id, node]));\n const beforeEdges = new Map(before.edges.map((edge) => [edge.id, edge]));\n const afterEdges = new Map(after.edges.map((edge) => [edge.id, edge]));\n\n const nodes = {\n added: after.nodes.filter((node) => !beforeNodes.has(node.id)),\n removed: before.nodes.filter((node) => !afterNodes.has(node.id)),\n updated: before.nodes.flatMap((node) => {\n const next = afterNodes.get(node.id);\n return next && !equal(node, next) ? [{ id: node.id, before: node, after: next }] : [];\n }),\n };\n const edges = {\n added: after.edges.filter((edge) => !beforeEdges.has(edge.id)),\n removed: before.edges.filter((edge) => !afterEdges.has(edge.id)),\n updated: before.edges.flatMap((edge) => {\n const next = afterEdges.get(edge.id);\n return next && !equal(edge, next) ? [{ id: edge.id, before: edge, after: next }] : [];\n }),\n };\n\n const patches: FlowPatch<TNodeData, TEdgeData, TLabelData>[] = [\n ...nodes.added.map((node) => ({ op: 'addNode' as const, node })),\n ...nodes.updated.map(({ id, before: previous, after: next }) => ({\n op: 'updateNode' as const,\n id,\n before: previous,\n after: next,\n })),\n ...nodes.removed.map((node) => ({ op: 'deleteNode' as const, node })),\n ...edges.added.map((edge) => ({ op: 'addEdge' as const, edge })),\n ...edges.updated.map(({ id, before: previous, after: next }) => ({\n op: 'updateEdge' as const,\n id,\n before: previous,\n after: next,\n })),\n ...edges.removed.map((edge) => ({ op: 'deleteEdge' as const, edge })),\n ];\n const beforeAttrs = graphAttrs(before);\n const afterAttrs = graphAttrs(after);\n if (!equal(beforeAttrs, afterAttrs)) {\n patches.push({ op: 'updateGraph', before: beforeAttrs, after: afterAttrs });\n }\n if (patches.length === 0) return null;\n\n const forward = orderPatches(before, after, patches);\n const inverse = orderPatches(after, before, forward.map(invertPatch));\n return {\n version: 1,\n ...metadata,\n nodes,\n edges,\n forward,\n inverse,\n };\n}\n\n/**\n * Swap each entity the change set did not add or update for its object in\n * `before`, so memoized views keyed on entity identity skip unchanged\n * entities. An updated edge keeps its previous label object when the label is\n * unchanged. Arrays whose entries all match `before` are kept too. Mutates and\n * returns `after`, which must be a fresh clone.\n */\nexport function reuseUnchangedEntities<TNodeData, TEdgeData, TLabelData>(\n before: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n after: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null,\n): FlowGraph<TNodeData, TEdgeData, TLabelData> {\n const changedNodeIds = new Set([\n ...(changeSet?.nodes.added ?? []).map((node) => node.id),\n ...(changeSet?.nodes.updated ?? []).map((update) => update.id),\n ]);\n const changedEdgeIds = new Set([\n ...(changeSet?.edges.added ?? []).map((edge) => edge.id),\n ...(changeSet?.edges.updated ?? []).map((update) => update.id),\n ]);\n const beforeNodes = new Map(before.nodes.map((node) => [node.id, node]));\n const beforeEdges = new Map(before.edges.map((edge) => [edge.id, edge]));\n const nodes = after.nodes.map((node) =>\n changedNodeIds.has(node.id) ? node : (beforeNodes.get(node.id) ?? node),\n );\n const edges = after.edges.map((edge) => {\n const previous = beforeEdges.get(edge.id);\n if (!previous) return edge;\n if (!changedEdgeIds.has(edge.id)) return previous;\n if (previous.label && equal(previous.label, edge.label)) edge.label = previous.label;\n return edge;\n });\n after.nodes = sameEntries(nodes, before.nodes) ? before.nodes : nodes;\n after.edges = sameEntries(edges, before.edges) ? before.edges : edges;\n return after;\n}\n\nfunction sameEntries<T>(left: readonly T[], right: readonly T[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction strictConflict(path: string, message: string): FlowGraphValidationError {\n return new FlowGraphValidationError([{ code: 'change_set_conflict', path, message }]);\n}\n\nexport function applyFlowPatches<TNodeData = any, TEdgeData = any, TLabelData = any>(\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n patches: readonly FlowPatch<TNodeData, TEdgeData, TLabelData>[],\n options: {\n strict?: boolean;\n schemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>;\n } = {},\n): FlowResult<FlowGraph<TNodeData, TEdgeData, TLabelData>> {\n try {\n const next = validateAndCloneGraph(graph, options.schemas);\n for (const patch of patches) {\n switch (patch.op) {\n case 'addNode':\n if (options.strict && next.nodes.some((node) => node.id === patch.node.id)) {\n throw strictConflict('$.nodes', `node \"${patch.node.id}\" already exists`);\n }\n next.nodes.push(patch.node);\n break;\n case 'updateNode': {\n const index = next.nodes.findIndex((node) => node.id === patch.id);\n if (index < 0) throw strictConflict('$.nodes', `node \"${patch.id}\" does not exist`);\n if (options.strict && !equal(next.nodes[index], patch.before)) {\n throw strictConflict('$.nodes', `node \"${patch.id}\" no longer matches the expected value`);\n }\n next.nodes[index] = patch.after;\n break;\n }\n case 'deleteNode': {\n const index = next.nodes.findIndex((node) => node.id === patch.node.id);\n if (index < 0) {\n if (options.strict) throw strictConflict('$.nodes', `node \"${patch.node.id}\" does not exist`);\n break;\n }\n if (options.strict && !equal(next.nodes[index], patch.node)) {\n throw strictConflict('$.nodes', `node \"${patch.node.id}\" no longer matches the expected value`);\n }\n next.nodes.splice(index, 1);\n break;\n }\n case 'addEdge':\n if (options.strict && next.edges.some((edge) => edge.id === patch.edge.id)) {\n throw strictConflict('$.edges', `edge \"${patch.edge.id}\" already exists`);\n }\n next.edges.push(patch.edge);\n break;\n case 'updateEdge': {\n const index = next.edges.findIndex((edge) => edge.id === patch.id);\n if (index < 0) throw strictConflict('$.edges', `edge \"${patch.id}\" does not exist`);\n if (options.strict && !equal(next.edges[index], patch.before)) {\n throw strictConflict('$.edges', `edge \"${patch.id}\" no longer matches the expected value`);\n }\n next.edges[index] = patch.after;\n break;\n }\n case 'deleteEdge': {\n const index = next.edges.findIndex((edge) => edge.id === patch.edge.id);\n if (index < 0) {\n if (options.strict) throw strictConflict('$.edges', `edge \"${patch.edge.id}\" does not exist`);\n break;\n }\n if (options.strict && !equal(next.edges[index], patch.edge)) {\n throw strictConflict('$.edges', `edge \"${patch.edge.id}\" no longer matches the expected value`);\n }\n next.edges.splice(index, 1);\n break;\n }\n case 'updateGraph': {\n const current = graphAttrs(next);\n if (options.strict && !equal(current, patch.before)) {\n throw strictConflict('$', 'graph attributes no longer match the expected value');\n }\n Object.assign(next, patch.after);\n break;\n }\n }\n }\n return { ok: true, value: validateAndCloneGraph(next, options.schemas) };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof FlowGraphValidationError\n ? error\n : new FlowGraphValidationError([\n { code: 'change_set_error', path: '$', message: String(error) },\n ]),\n };\n }\n}\n","import { serializeFlowGraph, parseFlowSerialized } from './serialize';\nimport { invalidateAuthoritativeEdgePath } from './edge-geometry';\nimport type { FlowEdge, FlowGraph, FlowNode, Point } from './types';\nimport {\n currentDataVersions,\n type FlowDataSchemas,\n type FlowDataVersions,\n} from './validation';\n\nexport type FlowContent<TNodeData = any, TEdgeData = any, TLabelData = any> = {\n type: 'stately-flow-content';\n version: 1;\n nodes: FlowNode<TNodeData>[];\n edges: FlowEdge<TEdgeData, TLabelData>[];\n dataVersions?: FlowDataVersions;\n};\n\nexport type FlowContentInsertResult<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>;\n nodeIds: string[];\n edgeIds: string[];\n idMap: ReadonlyMap<string, string>;\n};\n\nexport function extractFlowContent<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n targets: Iterable<string>,\n schemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>,\n): FlowContent<TNodeData, TEdgeData, TLabelData> | null {\n const requested = new Set(targets);\n const nodeIds = new Set(\n graph.nodes.filter((node) => requested.has(node.id)).map((node) => node.id),\n );\n let changed = true;\n while (changed) {\n changed = false;\n for (const node of graph.nodes) {\n if (node.parentId && nodeIds.has(node.parentId) && !nodeIds.has(node.id)) {\n nodeIds.add(node.id);\n changed = true;\n }\n }\n }\n const edgeIds = new Set(\n graph.edges\n .filter(\n (edge) =>\n requested.has(edge.id) ||\n (nodeIds.has(edge.sourceId) && nodeIds.has(edge.targetId)),\n )\n .map((edge) => edge.id),\n );\n const selectedGraph = serializeFlowGraph({\n ...graph,\n nodes: graph.nodes\n .filter((node) => nodeIds.has(node.id))\n .map((node) =>\n node.parentId && !nodeIds.has(node.parentId)\n ? { ...node, parentId: null }\n : node,\n ),\n edges: graph.edges.filter(\n (edge) =>\n edgeIds.has(edge.id) &&\n nodeIds.has(edge.sourceId) &&\n nodeIds.has(edge.targetId),\n ),\n });\n if (selectedGraph.nodes.length === 0 && selectedGraph.edges.length === 0) {\n return null;\n }\n return {\n type: 'stately-flow-content',\n version: 1,\n nodes: selectedGraph.nodes,\n edges: selectedGraph.edges,\n ...(currentDataVersions(schemas)\n ? { dataVersions: currentDataVersions(schemas) }\n : {}),\n };\n}\n\nexport function insertFlowContent<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n content: unknown,\n options: {\n point?: Point;\n preservePosition?: boolean;\n schemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>;\n createId: (kind: 'node' | 'edge', sourceId: string, attempt: number) => string;\n },\n): FlowContentInsertResult<TNodeData, TEdgeData, TLabelData> {\n if (\n !content ||\n typeof content !== 'object' ||\n (content as { type?: unknown }).type !== 'stately-flow-content' ||\n (content as { version?: unknown }).version !== 1\n ) {\n throw new TypeError('Expected a supported stately-flow-content document.');\n }\n const raw = content as FlowContent<TNodeData, TEdgeData, TLabelData>;\n const parsed = parseFlowSerialized<TNodeData, TEdgeData, TLabelData>(\n {\n version: 1,\n graph: { nodes: raw.nodes, edges: raw.edges, direction: graph.direction },\n viewport: { x: 0, y: 0, zoom: 1 },\n dataVersions: raw.dataVersions,\n },\n options.schemas,\n );\n const existing = new Set([\n ...graph.nodes.map((node) => node.id),\n ...graph.edges.map((edge) => edge.id),\n ]);\n const idMap = new Map<string, string>();\n const allocate = (kind: 'node' | 'edge', sourceId: string): string => {\n for (let attempt = 0; attempt < 100; attempt++) {\n const id = options.createId(kind, sourceId, attempt);\n if (id && !existing.has(id)) {\n existing.add(id);\n idMap.set(sourceId, id);\n return id;\n }\n }\n throw new Error(`Unable to allocate a unique id for \"${sourceId}\".`);\n };\n for (const node of parsed.graph.nodes) allocate('node', node.id);\n for (const edge of parsed.graph.edges) allocate('edge', edge.id);\n\n const minX = parsed.graph.nodes.length\n ? Math.min(...parsed.graph.nodes.map((node) => node.x))\n : 0;\n const minY = parsed.graph.nodes.length\n ? Math.min(...parsed.graph.nodes.map((node) => node.y))\n : 0;\n const offset =\n options.point && !options.preservePosition\n ? { x: options.point.x - minX, y: options.point.y - minY }\n : { x: 0, y: 0 };\n const remapData = <TData>(\n data: TData,\n contract: { remap?: (value: TData, context: { idMap: ReadonlyMap<string, string> }) => TData } | undefined,\n ): TData => contract?.remap ? contract.remap(data, { idMap }) : data;\n const nodes = parsed.graph.nodes.map((node) => ({\n ...node,\n id: idMap.get(node.id)!,\n parentId: node.parentId ? idMap.get(node.parentId) ?? null : node.parentId,\n x: node.x + offset.x,\n y: node.y + offset.y,\n data: remapData(node.data, options.schemas?.node),\n }));\n const edges = parsed.graph.edges.map((edge) => {\n const inserted = {\n ...edge,\n id: idMap.get(edge.id)!,\n sourceId: idMap.get(edge.sourceId)!,\n targetId: idMap.get(edge.targetId)!,\n x: edge.x + offset.x,\n y: edge.y + offset.y,\n data: remapData(edge.data, options.schemas?.edge),\n ...(edge.waypoints\n ? {\n waypoints: edge.waypoints.map((point) => ({\n x: point.x + offset.x,\n y: point.y + offset.y,\n })),\n }\n : {}),\n ...(edge.label\n ? {\n label: {\n ...edge.label,\n x: edge.label.x + offset.x,\n y: edge.label.y + offset.y,\n data: remapData(edge.label.data, options.schemas?.label),\n },\n }\n : {}),\n };\n if (offset.x !== 0 || offset.y !== 0) {\n invalidateAuthoritativeEdgePath(inserted);\n }\n return inserted;\n });\n return {\n graph: { ...graph, nodes: [...graph.nodes, ...nodes], edges: [...graph.edges, ...edges] },\n nodeIds: nodes.map((node) => node.id),\n edgeIds: edges.map((edge) => edge.id),\n idMap,\n };\n}\n","import { createFlowExternalEdit, type FlowExternalEdit } from './external-edit';\nimport { createFlowRenderApi, type FlowRenderInvalidation } from './render-invalidation';\nimport { normalizeGeometryPosition } from './geometry';\nimport { createFlowEngine, normalizeConnection } from './engine';\nimport type {\n FlowEngine,\n FlowEngineOptions,\n ConnectionCandidate,\n ConnectionCandidateOptions,\n EdgePathOptions,\n EntityOrderOptions,\n RenderableEntitiesOptions,\n} from './engine';\nimport {\n createFlowStore,\n planNodeMovement,\n clampResizeMovingPoint,\n} from './store';\nimport type {\n ConnectionEndedEvent,\n FlowHighlightEntry,\n FlowStore,\n FlowStoreContext,\n FlowEdgePatch,\n FlowEdgeUpdater,\n FlowNodePatch,\n FlowNodeUpdater,\n FlowStoreOptions,\n FlowGraphHistoryPolicy,\n FlowGraphRetentionPolicy,\n} from './store';\nimport {\n createEdge,\n createNode,\n} from './factories';\nimport type {\n EdgePathData,\n EdgeRouting,\n FlowEntityRef,\n FlowEdge,\n FlowGraph,\n FlowNode,\n FitViewOptions,\n Point,\n Rect,\n Size,\n Viewport,\n ViewportAnimationOptions,\n} from './types';\nimport {\n animateViewport,\n fitFrameAroundExclusions,\n panBy as viewportPanBy,\n validateFitFrame,\n viewportCenteredOn,\n viewportForBounds,\n zoomTo as viewportZoomTo,\n type FitViewExclusion,\n type ViewportAnimationControls,\n} from './viewport';\nimport {\n serializeFlowGraph,\n parseFlowSerialized,\n type FlowSerialized,\n} from './serialize';\nimport {\n cloneJsonSafe,\n validateAndCloneGraph,\n currentDataVersions,\n type FlowDataSchemas,\n type FlowResult,\n FlowGraphValidationError,\n} from './validation';\nimport {\n applyFlowPatches,\n createFlowChangeSet,\n reuseUnchangedEntities,\n type FlowChangeSet,\n} from './changeSet';\nimport {\n extractFlowContent,\n insertFlowContent,\n type FlowContent,\n} from './content';\nimport {\n constrainViewport,\n getGraphBounds,\n resolvedBounds,\n} from './spatial';\nimport {\n invalidateAuthoritativeEdgePath,\n nodeEndpointGeometryChanged,\n withDerivedGroupAncestors,\n} from './edge-geometry';\nimport {\n composeGraphProjectionAttrs,\n type ActiveGraphProjection,\n type ComposedGraphProjectionAttrs,\n} from './projections';\nimport type { FlowPolicies } from './profile';\nimport { getNodeIdsWithDescendants } from './hierarchy';\nimport { getEdgeOwner as getDefaultEdgeOwner } from './hierarchy';\nimport { indexEdgeAdjacency } from './graph-index';\nimport { deriveFlowView } from './view';\nimport type {\n FlowViewBoundaryEndpoints,\n FlowViewEntities,\n FlowViewScope,\n FlowViewSelectionPolicy,\n} from './view';\n\ndeclare const requestAnimationFrame:\n | ((callback: (time: number) => void) => number)\n | undefined;\ndeclare const cancelAnimationFrame: ((id: number) => void) | undefined;\ndeclare const setTimeout: (callback: () => void, ms: number) => number;\ndeclare const clearTimeout: (id: number) => void;\n\nexport type LayoutDiagnostic = {\n message: string;\n severity?: 'info' | 'warning' | 'error';\n code?: string;\n entityId?: string;\n entityIds?: readonly string[];\n phase?: string;\n};\n\nexport type LayoutEdgeRoute =\n | { waypoints: readonly Point[] }\n | { points: readonly Point[]; routing?: EdgeRouting };\n\nfunction hasAuthoritativeLayoutPoints(\n route: LayoutEdgeRoute | readonly Point[],\n): route is Extract<LayoutEdgeRoute, { points: readonly Point[] }> {\n return !Array.isArray(route) && 'points' in route;\n}\n\nfunction layoutWaypoints(\n route: LayoutEdgeRoute | readonly Point[],\n): readonly Point[] {\n return Array.isArray(route)\n ? (route as readonly Point[])\n : (route as Extract<LayoutEdgeRoute, { waypoints: readonly Point[] }>).waypoints;\n}\n\nexport type LayoutResult = {\n positions: ReadonlyMap<string, Point>;\n nodeSizes?: ReadonlyMap<string, Size>;\n nodeBounds?: ReadonlyMap<string, Rect>;\n edgeLabelPositions?: ReadonlyMap<string, Point>;\n edgeLabelBounds?: ReadonlyMap<string, Rect>;\n edgeRoutes?: ReadonlyMap<string, LayoutEdgeRoute | readonly Point[]>;\n diagnostics?: readonly LayoutDiagnostic[];\n quality?: Readonly<Record<string, unknown>>;\n metadata?: Readonly<Record<string, unknown>>;\n source?: string;\n /** Fixed entities listed here may be changed by this result. */\n overrideFixedEntityIds?: ReadonlySet<string>;\n};\n\nexport type LayoutPositions = Map<string, Point>;\n\nexport type FlowAbortSignal = {\n readonly aborted: boolean;\n addEventListener: (\n type: 'abort',\n listener: () => void,\n options?: { once?: boolean },\n ) => void;\n removeEventListener: (type: 'abort', listener: () => void) => void;\n};\n\nexport type LayoutRunOptions = {\n signal?: FlowAbortSignal;\n /** Apply even if the graph changed while the algorithm was running. */\n force?: boolean;\n scope?: FlowViewScope;\n previousResult?: LayoutResult | null;\n fixedEntityIds?: ReadonlySet<string>;\n pinnedEntityIds?: ReadonlySet<string>;\n source?: string;\n metadata?: Readonly<Record<string, unknown>>;\n animation?: LayoutAnimationOptions;\n};\n\nexport type LayoutAnimationOptions = {\n duration?: number;\n easing?: (progress: number) => number;\n};\n\nexport type LayoutAnimationControls = {\n cancel: () => void;\n done: Promise<void>;\n};\n\nexport type LayoutApplyOptions = FlowTransactionOptions & {\n fixedEntityIds?: ReadonlySet<string>;\n pinnedEntityIds?: ReadonlySet<string>;\n overrideFixedEntityIds?: ReadonlySet<string>;\n animation?: LayoutAnimationOptions;\n};\n\nexport type LayoutRunResult = {\n applied: boolean;\n result: LayoutResult;\n source?: string;\n diagnostics?: readonly LayoutDiagnostic[];\n animation: LayoutAnimationControls;\n};\n\nexport type LayoutAlgorithm<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = (\n graph: Readonly<FlowGraph<TNodeData, TEdgeData, TLabelData>>,\n options: Readonly<LayoutRunOptions> & { signal: FlowAbortSignal },\n) => Promise<LayoutResult | LayoutPositions>;\n\nexport type FlowProjectionListener = (\n projections: readonly ActiveGraphProjection[],\n) => void;\n\nexport type FlowTransactionOptions = { transactionId?: string; origin?: string; history?: 'record' | 'ignore' };\n\nexport type FlowMeasurement = { id: string; rect: Rect };\n\nexport type FlowMeasurementsApi = {\n update: (batch: readonly FlowMeasurement[]) => void;\n remove: (ids: readonly string[]) => void;\n get: (id: string) => Rect | undefined;\n};\n\nexport type FlowGeometryOptions = FlowTransactionOptions & {\n /** Decimal places for settled positions. Defaults to whole CSS pixels; null preserves exact coordinates. Sizes stay precise. */\n positionPrecision?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | null;\n};\n\nexport type FlowContentSizeOptions = FlowGeometryOptions & {\n /** Settled visual origin when native content growth also shifts the box. */\n position?: Point;\n};\n\nexport type FlowReplaceGraphOptions = Omit<FlowTransactionOptions, 'history'> & {\n /**\n * `preserve` keeps state addressed to surviving entity ids and prunes stale\n * references. `reset` clears selection and other session-scoped graph state.\n * Defaults to `preserve`.\n */\n retention?: FlowGraphRetentionPolicy;\n /**\n * `reset` clears controller undo/redo history, `ignore` keeps existing\n * history without recording this replacement, and `record` creates an undo\n * step. Defaults to `reset` for authoritative external synchronization.\n */\n history?: FlowGraphHistoryPolicy;\n};\n\nexport type FlowCreateIdContext = {\n kind: 'node' | 'edge';\n reason: 'create' | 'content';\n sourceId?: string;\n attempt: number;\n};\n\nexport type CreateNodeInput<TNodeData = any> = Omit<\n Parameters<typeof createNode<TNodeData>>[0],\n 'id'\n> & { id?: string };\nexport type CreateEdgeInput<\n TEdgeData = any,\n TLabelData = any,\n> = Omit<Parameters<typeof createEdge<TEdgeData, TLabelData>>[0], 'id'> & {\n id?: string;\n};\n\nexport type FlowNodesApi<TNodeData = any> = {\n move: (id: string, position: Point, options?: FlowGeometryOptions) => FlowNode<TNodeData>;\n resize: (id: string, bounds: Rect, options?: FlowGeometryOptions) => FlowNode<TNodeData>;\n setContentSize: (id: string, size: Size, options?: FlowContentSizeOptions) => FlowNode<TNodeData>;\n create: (\n input: CreateNodeInput<TNodeData>,\n options?: FlowTransactionOptions,\n ) => FlowNode<TNodeData>;\n delete: (id: string, options?: FlowTransactionOptions) => boolean;\n update: (\n id: string,\n patchOrUpdater: FlowNodePatch | FlowNodeUpdater,\n options?: FlowTransactionOptions,\n ) => FlowNode<TNodeData>;\n setData: (\n id: string,\n data:\n | (TNodeData extends object ? Partial<TNodeData> : never)\n | ((current: TNodeData, node: FlowNode<TNodeData>) => TNodeData),\n options?: FlowTransactionOptions,\n ) => FlowNode<TNodeData>;\n reparent: (\n id: string,\n parentId: string | null,\n options?: FlowTransactionOptions,\n ) => FlowNode<TNodeData>;\n collapse: (id: string, options?: FlowTransactionOptions) => void;\n expand: (id: string, options?: FlowTransactionOptions) => void;\n};\n\nexport type FlowEdgesApi<TEdgeData = any, TLabelData = any> = {\n create: (\n input: CreateEdgeInput<TEdgeData, TLabelData>,\n options?: FlowTransactionOptions,\n ) => FlowEdge<TEdgeData, TLabelData>;\n delete: (id: string, options?: FlowTransactionOptions) => boolean;\n update: (\n id: string,\n patchOrUpdater: FlowEdgePatch | FlowEdgeUpdater,\n options?: FlowTransactionOptions,\n ) => FlowEdge<TEdgeData, TLabelData>;\n setData: (\n id: string,\n data:\n | (TEdgeData extends object ? Partial<TEdgeData> : never)\n | ((current: TEdgeData, edge: FlowEdge<TEdgeData, TLabelData>) => TEdgeData),\n options?: FlowTransactionOptions,\n ) => FlowEdge<TEdgeData, TLabelData>;\n reconnect: (\n edgeId: string,\n patch: {\n newSourceId?: string;\n newTargetId?: string;\n newSourcePort?: string | null;\n newTargetPort?: string | null;\n },\n options?: FlowTransactionOptions,\n ) => FlowEdge<TEdgeData, TLabelData>;\n};\n\nexport type FlowSelectionAlignment =\n | 'left'\n | 'right'\n | 'top'\n | 'bottom'\n | 'center-x'\n | 'center-y';\n\nexport type FlowSelectionDistribution = 'horizontal' | 'vertical';\n\nexport type FlowSelectionDuplicateResult = {\n nodeIds: string[];\n edgeIds: string[];\n idMap: ReadonlyMap<string, string>;\n};\n\nexport type FlowSelectionApi = {\n set: (ids: string[], mode?: 'single' | 'multi') => void;\n all: (options?: { includeHidden?: boolean }) => void;\n clear: () => void;\n delete: () => boolean;\n duplicate: (options?: { offset?: Point }) => FlowSelectionDuplicateResult | null;\n align: (alignment: FlowSelectionAlignment) => boolean;\n distribute: (distribution: FlowSelectionDistribution) => boolean;\n};\n\nexport type FlowViewApi<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n getScope: () => FlowViewScope;\n setScope: (\n scope: FlowViewScope,\n options?: { selection?: FlowViewSelectionPolicy },\n ) => void;\n getEntities: (options?: {\n includeHidden?: boolean;\n }) => FlowViewEntities<TNodeData, TEdgeData, TLabelData>;\n getBoundaryEndpoints: (\n edgeId: string,\n ) => FlowViewBoundaryEndpoints | undefined;\n contains: (id: string, options?: { includeHidden?: boolean }) => boolean;\n};\n\nexport type FlowViewportApi = {\n set: (\n viewport: FlowStoreContext['viewport'],\n options?: ViewportAnimationOptions,\n ) => ViewportAnimationControls;\n panBy: (\n point: Point,\n options?: ViewportAnimationOptions,\n ) => ViewportAnimationControls;\n zoomTo: (\n zoom: number,\n center?: Point,\n options?: ViewportAnimationOptions,\n ) => ViewportAnimationControls;\n zoomBy: (\n factor: number,\n center?: Point,\n options?: ViewportAnimationOptions,\n ) => ViewportAnimationControls;\n fit: (\n options?: FitViewOptions & { includeHidden?: boolean },\n ) => ViewportAnimationControls;\n fitBounds: (\n bounds: Rect,\n options?: Omit<FitViewOptions, 'nodes'>,\n ) => ViewportAnimationControls;\n centerOn: (\n point: Point,\n options?: Omit<ViewportAnimationOptions, 'center'> & {\n zoom?: number;\n frame?: Rect;\n },\n ) => ViewportAnimationControls;\n getFitFrame: () => Readonly<Rect>;\n setFitFrame: (\n frame: Rect | null,\n options?: { preserveCenter?: boolean },\n ) => void;\n /** Register a measured screen-space overlay that fit/center commands avoid. */\n registerFitExclusion: (exclusion: FitViewExclusion) => () => void;\n};\n\nexport type FlowLayoutApi<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n run: (\n layout?: LayoutAlgorithm<TNodeData, TEdgeData, TLabelData>,\n options?: LayoutRunOptions,\n ) => Promise<LayoutRunResult>;\n apply: (\n result: LayoutResult,\n options?: LayoutApplyOptions,\n ) => LayoutAnimationControls;\n request: (algorithm?: string) => void;\n};\n\nexport type FlowHistoryApi = {\n undo: () => void;\n redo: () => void;\n canUndo: () => boolean;\n canRedo: () => boolean;\n};\n\nexport type FlowConnection = {\n edge: FlowEdge;\n source: { nodeId: string; port: string | null };\n target: { nodeId: string; port: string | null };\n};\n\nexport type FlowConnectionsApi = {\n get: (input: {\n nodeId: string;\n port?: string | null;\n direction?: 'in' | 'out' | 'both';\n }) => FlowConnection[];\n};\n\nexport type FlowContentApi<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n extract: (targets?: Iterable<string>) => FlowContent<TNodeData, TEdgeData, TLabelData> | null;\n insert: (\n content: unknown,\n options?: { point?: Point; preservePosition?: boolean },\n ) => FlowResult<{\n nodeIds: string[];\n edgeIds: string[];\n idMap: ReadonlyMap<string, string>;\n changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>;\n }>;\n};\n\nexport type FlowCapabilityCommand =\n | 'edit'\n | 'create'\n | 'move'\n | 'resize'\n | 'connect'\n | 'reconnect'\n | 'reparent'\n | 'delete'\n | 'cut'\n | 'paste'\n | 'undo'\n | 'redo'\n | 'copy'\n | 'export'\n | 'select'\n | 'pan'\n | 'zoom';\n\nexport type FlowCapabilityResult =\n | { allowed: true }\n | {\n allowed: false;\n reason: { code: 'readonly' | 'policy' | 'entity' | 'empty' | 'history'; command: FlowCapabilityCommand };\n };\n\nexport type FlowHighlightsApi = {\n set: (kind: string, entries: FlowHighlightEntry[]) => void;\n add: (kind: string, entries: FlowHighlightEntry[]) => void;\n remove: (kind: string, ids: string[]) => void;\n clear: (kind?: string) => void;\n};\n\nexport type FlowProjectionsApi = {\n get: () => readonly ActiveGraphProjection[];\n set: (projections: readonly ActiveGraphProjection[]) => void;\n add: (projection: ActiveGraphProjection) => void;\n remove: (id: string) => void;\n clear: () => void;\n subscribe: (listener: FlowProjectionListener) => () => void;\n getAttrs: () => ComposedGraphProjectionAttrs;\n};\n\nexport type FlowConfigureOptions = {\n engine?: Partial<FlowEngineOptions>;\n store?: Partial<FlowStoreOptions>;\n defaultEdgeOptions?: Partial<CreateEdgeInput> | null;\n /**\n * Runtime toggle for auto-creating an edge when a connection gesture ends on a\n * node. See {@link CreateFlowOptions.createEdgeOnConnect}.\n */\n createEdgeOnConnect?: boolean;\n layout?: LayoutAlgorithm | null;\n historyLimit?: number;\n};\n\nexport type FlowConfiguration = {\n engine: FlowEngineOptions;\n store: FlowStoreOptions;\n defaultEdgeOptions: Partial<CreateEdgeInput> | null;\n createEdgeOnConnect: boolean;\n layout: LayoutAlgorithm | null;\n historyLimit: number;\n};\n\nfunction immutableConfiguration(\n configuration: FlowConfiguration,\n): Readonly<FlowConfiguration> {\n const seen = new WeakMap<object, unknown>();\n const clone = (value: unknown): unknown => {\n if (!value || typeof value !== 'object') return value;\n const previous = seen.get(value);\n if (previous) return previous;\n if (Array.isArray(value)) {\n const result: unknown[] = [];\n seen.set(value, result);\n for (const entry of value) result.push(clone(entry));\n return Object.freeze(result);\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return value;\n const result: Record<string, unknown> = {};\n seen.set(value, result);\n for (const [key, entry] of Object.entries(value)) result[key] = clone(entry);\n return Object.freeze(result);\n };\n return clone(configuration) as Readonly<FlowConfiguration>;\n}\n\nexport type FlowCommitEvent<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n type: 'commit';\n changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>;\n origin?: string;\n transactionId?: string;\n revision: number;\n};\n\nexport type FlowTransactionDraft<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> = {\n getNode: (id: string) => FlowNode<TNodeData> | undefined;\n getEdge: (id: string) => FlowEdge<TEdgeData, TLabelData> | undefined;\n /** Intrinsic staged geometry, excluding derived group bounds. */\n getNodeBounds: (id: string) => Rect | undefined;\n nodes: Omit<FlowNodesApi<TNodeData>, 'collapse' | 'expand'>;\n edges: FlowEdgesApi<TEdgeData, TLabelData>;\n};\n\n/** Options for creating an owning Flow controller. */\nexport interface CreateFlowOptions<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> {\n /** Initial graph owned by the controller. */\n graph?: FlowGraph<TNodeData, TEdgeData, TLabelData>;\n /** Construct-only default layout algorithm used by `flow.layout.run()`. */\n layout?: LayoutAlgorithm<TNodeData, TEdgeData, TLabelData> | null;\n /** Store creation options; runtime settings can later change via `flow.configure({ store })`. */\n store?: FlowStoreOptions;\n /** Engine options; runtime-updatable via `flow.configure({ engine })`. */\n engine?: FlowEngineOptions;\n /** Default options merged into controller-created edges; runtime-updatable via `flow.configure`. */\n defaultEdgeOptions?: Partial<CreateEdgeInput<TEdgeData, TLabelData>>;\n /** Initial active visual projections; runtime-updatable via `flow.projections`. */\n projections?: readonly ActiveGraphProjection[];\n /** Optional listener for completed connection gestures. */\n onConnectionEnd?: (event: ConnectionEndedEvent) => void;\n /**\n * When `true`, the controller auto-creates an edge whenever a connection\n * gesture ends on a valid target node (applying {@link CreateFlowOptions.defaultEdgeOptions},\n * and skipping reconnection gestures). Defaults to `false`: `connectionEnded`\n * is then a pure notification (`onConnectionEnd` still fires), leaving edge\n * creation to the consumer via `flow.edges.create(...)`. Runtime-updatable via\n * `flow.configure`.\n */\n createEdgeOnConnect?: boolean;\n /** Creates opaque entity ids when `create()` is called without an explicit id. */\n createId?: (context: FlowCreateIdContext) => string;\n /** Optional Standard Schema-compatible contracts for application data. */\n dataSchemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>;\n}\n\n/**\n * Framework-neutral owner of a Flow graph and its interaction session.\n *\n * Mutations go through the domain APIs (`nodes`, `edges`, `selection`,\n * `viewport`) so validation, history, commit events, and cleanup stay coherent.\n * Call `destroy()` when the controller is no longer used.\n */\nexport interface FlowController<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n> {\n measurements: FlowMeasurementsApi;\n internals: { store: FlowStore; engine: FlowEngine };\n on: FlowStore['on'] & ((\n type: 'commit',\n listener: (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void,\n ) => { unsubscribe: () => void }) & ((\n type: 'destroy', listener: (event: { type: 'destroy' }) => void,\n ) => { unsubscribe: () => void });\n destroy: () => void;\n beginExternalEdit: (options?: FlowTransactionOptions) => FlowExternalEdit<TNodeData, TEdgeData, TLabelData>;\n subscribeRender: (listener: (event: FlowRenderInvalidation) => void) => () => void;\n\n getContext: () => FlowStoreContext;\n getSnapshot: () => FlowStoreContext;\n subscribe: {\n (listener: (context: FlowStoreContext) => void): () => void;\n <TSelected>(\n selector: (context: FlowStoreContext) => TSelected,\n listener: (selected: TSelected, previous: TSelected) => void,\n options?: { equals?: (a: TSelected, b: TSelected) => boolean; emitInitial?: boolean; keys?: readonly (keyof FlowStoreContext)[] },\n ): () => void;\n };\n configure: (\n options:\n | FlowConfigureOptions\n | ((current: Readonly<FlowConfiguration>) => FlowConfiguration),\n ) => void;\n getConfiguration: () => Readonly<FlowConfiguration>;\n /** Publish changed external router output without changing configuration or history. */\n invalidateRoutes: () => void;\n toJSON: () => FlowSerialized<TNodeData, TEdgeData, TLabelData>;\n load: (data: unknown) => FlowResult<void>;\n replaceGraph: (\n graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,\n options?: FlowReplaceGraphOptions,\n ) => FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null;\n transaction: <TValue>(\n callback: (draft: FlowTransactionDraft<TNodeData, TEdgeData, TLabelData>) => TValue,\n options?: FlowTransactionOptions,\n ) => { value: TValue; changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null };\n applyChangeSet: (\n changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>,\n options?: FlowTransactionOptions & { strict?: boolean },\n ) => FlowResult<FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null>;\n\n getNode: (id: string) => FlowNode<TNodeData> | undefined;\n getEdge: (id: string) => FlowEdge<TEdgeData, TLabelData> | undefined;\n getEntity: (\n id: string,\n ) => FlowNode<TNodeData> | FlowEdge<TEdgeData, TLabelData> | undefined;\n getEntityRef: (id: string) => FlowEntityRef | undefined;\n /** @deprecated Use `getEntityRef()`. */\n getAddressable: (id: string) => FlowEntityRef | undefined;\n getOwnerEntity: (\n id: string,\n ) => FlowNode<TNodeData> | FlowEdge<TEdgeData, TLabelData> | undefined;\n getBounds: (id: string) => Rect | undefined;\n\n screenToCanvas: (point: Point) => Point;\n canvasToScreen: (point: Point) => Point;\n getAllEdgePaths: (options?: EdgePathOptions) => Map<string, EdgePathData>;\n getConnectionCandidate: (\n pointer: Point,\n options?: ConnectionCandidateOptions,\n ) => ConnectionCandidate | null;\n getGraphBounds: () => Rect;\n getIncomers: (nodeId: string) => FlowNode[];\n getOutgoers: (nodeId: string) => FlowNode[];\n getConnectedEdges: (nodeIds: Iterable<string>) => FlowEdge[];\n getNeighbors: (nodeId: string) => FlowNode[];\n getSelectionBounds: () => Rect | null;\n getRenderableEntities: (\n options?: RenderableEntitiesOptions,\n ) => { nodes: FlowNode[]; edges: FlowEdge[] };\n getEntityOrder: (\n options?: EntityOrderOptions,\n ) => { nodes: FlowNode[]; edges: FlowEdge[] };\n check: (command: FlowCapabilityCommand, input?: { id?: string }) => FlowCapabilityResult;\n can: (command: FlowCapabilityCommand, input?: { id?: string }) => boolean;\n mode: { get: () => string; set: (mode: string) => void };\n\n nodes: FlowNodesApi<TNodeData>;\n edges: FlowEdgesApi<TEdgeData, TLabelData>;\n selection: FlowSelectionApi;\n view: FlowViewApi<TNodeData, TEdgeData, TLabelData>;\n viewport: FlowViewportApi;\n layout: FlowLayoutApi<TNodeData, TEdgeData, TLabelData>;\n history: FlowHistoryApi;\n highlights: FlowHighlightsApi;\n projections: FlowProjectionsApi;\n connections: FlowConnectionsApi;\n content: FlowContentApi<TNodeData, TEdgeData, TLabelData>;\n}\n\n/** Final layout positions align to whole CSS pixels. */\nfunction roundLayoutPosition(value: number): number {\n const rounded = Math.round(value);\n return rounded === 0 ? 0 : rounded;\n}\n\nfunction roundLayoutPoint(point: Point): Point {\n return { x: roundLayoutPosition(point.x), y: roundLayoutPosition(point.y) };\n}\n\n/**\n * Create an owning Flow controller from an optional initial graph.\n *\n * The input graph is validated and cloned. Adapters should subscribe to this\n * controller and delegate behavior to its APIs instead of reimplementing graph\n * or viewport policy.\n */\nexport function createFlow<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n options: CreateFlowOptions<TNodeData, TEdgeData, TLabelData> = {},\n): FlowController<TNodeData, TEdgeData, TLabelData> {\n const initialGraph = validateAndCloneGraph(\n options.graph ?? { nodes: [], edges: [], direction: 'down' },\n options.dataSchemas,\n );\n const store = createFlowStore(initialGraph, {\n ...options.store,\n appearances: options.engine?.appearances ?? options.store?.appearances,\n // Keep the store's movement planning in sync with the engine's label\n // anchor default (engine owns label geometry; the store needs it to decide\n // which labels auto-follow their endpoints vs. must be carried along).\n labelAnchor: options.store?.labelAnchor ?? options.engine?.labelAnchor,\n });\n const engine = createFlowEngine(store, options.engine);\n const cleanup = new Set<() => void>();\n let projections = [...(options.projections ?? [])];\n let configuration: FlowConfiguration = {\n engine: { ...(options.engine ?? {}) },\n store: { ...(options.store ?? {}) },\n defaultEdgeOptions: options.defaultEdgeOptions\n ? { ...options.defaultEdgeOptions }\n : null,\n createEdgeOnConnect: options.createEdgeOnConnect ?? false,\n layout: options.layout ?? null,\n historyLimit: options.store?.historyLimit ?? 100,\n };\n let defaultEdgeOptions = options.defaultEdgeOptions\n ? { ...options.defaultEdgeOptions }\n : undefined;\n let createEdgeOnConnect = options.createEdgeOnConnect ?? false;\n const projectionListeners = new Set<FlowProjectionListener>();\n let activeViewportAnimation: ViewportAnimationControls | null = null;\n const fitExclusions = new Set<FitViewExclusion>();\n const pendingInternalViewportWrites: Viewport[] = [];\n let lastViewport = store.getSnapshot().context.viewport;\n let graphRevision = 0;\n let lastCommittedGraph = initialGraph;\n let latestLayoutRun = 0;\n let activeLayoutAbort: { abort: () => void } | null = null;\n let activeLayoutAnimation: {\n controls: LayoutAnimationControls;\n stop: (clear: boolean) => void;\n } | null = null;\n const commitListeners = new Set<\n (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void\n >();\n\n const viewportSubscription = store.subscribe((snapshot) => {\n const nextViewport = snapshot.context.viewport;\n if (nextViewport === lastViewport) return;\n lastViewport = nextViewport;\n const internalIndex = pendingInternalViewportWrites.findIndex(\n (viewport) =>\n viewport.x === nextViewport.x &&\n viewport.y === nextViewport.y &&\n viewport.zoom === nextViewport.zoom,\n );\n if (internalIndex >= 0) {\n pendingInternalViewportWrites.splice(0, internalIndex + 1);\n return;\n }\n pendingInternalViewportWrites.length = 0;\n if (activeViewportAnimation) {\n activeViewportAnimation.cancel();\n activeViewportAnimation = null;\n }\n });\n cleanup.add(() => viewportSubscription.unsubscribe());\n\n const graphEventSubscription = store.on('graphChanged', (event) => {\n if (activeLayoutAnimation && event.event.origin !== 'layout') {\n activeLayoutAnimation.stop(true);\n }\n const metadata = {\n origin: typeof event.event.origin === 'string' ? event.event.origin : event.event.type,\n transactionId:\n typeof event.event.transactionId === 'string'\n ? event.event.transactionId\n : undefined,\n };\n const nextGraph = event.graph as FlowGraph<\n TNodeData,\n TEdgeData,\n TLabelData\n >;\n const nextRevision = graphRevision + 1;\n const changeSet = createFlowChangeSet(lastCommittedGraph, nextGraph, {\n revision: nextRevision,\n ...metadata,\n });\n lastCommittedGraph = nextGraph;\n if (!changeSet) return;\n graphRevision = nextRevision;\n const commitEvent: FlowCommitEvent<TNodeData, TEdgeData, TLabelData> = {\n type: 'commit',\n changeSet,\n revision: graphRevision,\n origin: changeSet.origin,\n transactionId: changeSet.transactionId,\n };\n for (const listener of commitListeners) listener(commitEvent);\n });\n cleanup.add(() => graphEventSubscription.unsubscribe());\n\n const connectionSubscription = store.on('connectionEnded', (event) => {\n options.onConnectionEnd?.(event);\n if (!createEdgeOnConnect) return;\n if (event.reconnectedEdgeId) return;\n if (event.target.kind !== 'node') return;\n if (event.connection.isValid === false) return;\n edges.create(normalizeConnection({\n sourceId: event.source.nodeId,\n targetId: event.target.nodeId,\n sourcePort: event.source.port,\n targetPort: event.target.port,\n }, store.getSnapshot().context.graph) as CreateEdgeInput<TEdgeData, TLabelData>);\n });\n cleanup.add(() => connectionSubscription.unsubscribe());\n\n let destroyed = false;\n const destroyListeners = new Set<(event: { type: 'destroy' }) => void>();\n function destroy() {\n if (destroyed) return;\n destroyed = true;\n for (const listener of destroyListeners) listener({ type: 'destroy' });\n destroyListeners.clear();\n store.trigger.cancelConnection();\n activeLayoutAbort?.abort();\n activeLayoutAnimation?.stop(true);\n activeViewportAnimation?.cancel();\n activeViewportAnimation = null;\n for (const dispose of cleanup) {\n dispose();\n }\n cleanup.clear();\n fitExclusions.clear();\n projectionListeners.clear();\n commitListeners.clear();\n }\n\n function notifyProjectionListeners() {\n const snapshot = getProjections();\n for (const listener of projectionListeners) {\n listener(snapshot);\n }\n }\n\n function getProjections(): readonly ActiveGraphProjection[] {\n return projections;\n }\n\n function setProjections(next: readonly ActiveGraphProjection[]) {\n projections = [...next];\n notifyProjectionListeners();\n }\n\n function normalizeLayoutResult(\n result: LayoutResult | LayoutPositions,\n ): LayoutResult {\n const value = result instanceof Map ? { positions: result } : result;\n if (!value || !(value.positions instanceof Map)) {\n throw new TypeError('Layout result positions must be a Map.');\n }\n const points = (input: ReadonlyMap<string, Point> | undefined) =>\n input\n ? new Map(\n [...input].map(([id, point]) => [id, { x: point.x, y: point.y }]),\n )\n : undefined;\n const sizes = (input: ReadonlyMap<string, Size> | undefined) =>\n input\n ? new Map(\n [...input].map(([id, size]) => [\n id,\n { width: size.width, height: size.height },\n ]),\n )\n : undefined;\n const rects = (input: ReadonlyMap<string, Rect> | undefined) =>\n input\n ? new Map(\n [...input].map(([id, rect]) => [\n id,\n {\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n },\n ]),\n )\n : undefined;\n return {\n positions: points(value.positions)!,\n ...(value.nodeSizes ? { nodeSizes: sizes(value.nodeSizes) } : {}),\n ...(value.nodeBounds ? { nodeBounds: rects(value.nodeBounds) } : {}),\n ...(value.edgeLabelPositions\n ? { edgeLabelPositions: points(value.edgeLabelPositions) }\n : {}),\n ...(value.edgeLabelBounds\n ? { edgeLabelBounds: rects(value.edgeLabelBounds) }\n : {}),\n ...(value.edgeRoutes\n ? {\n edgeRoutes: new Map(\n [...value.edgeRoutes].map(([id, route]): [string, LayoutEdgeRoute] => {\n if (hasAuthoritativeLayoutPoints(route)) {\n return [\n id,\n {\n points: route.points.map((point) => ({\n x: point.x,\n y: point.y,\n })),\n ...(route.routing ? { routing: route.routing } : {}),\n },\n ];\n }\n return [\n id,\n {\n waypoints: layoutWaypoints(route).map((point) => ({\n x: point.x,\n y: point.y,\n })),\n },\n ];\n }),\n ),\n }\n : {}),\n ...(value.diagnostics\n ? { diagnostics: value.diagnostics.map((entry) => ({ ...entry })) }\n : {}),\n ...(value.quality\n ? { quality: cloneJsonSafe(value.quality, '$.layout.quality') }\n : {}),\n ...(value.metadata\n ? { metadata: cloneJsonSafe(value.metadata, '$.layout.metadata') }\n : {}),\n ...(value.source !== undefined ? { source: value.source } : {}),\n ...(value.overrideFixedEntityIds\n ? { overrideFixedEntityIds: new Set(value.overrideFixedEntityIds) }\n : {}),\n };\n }\n\n function immutableLayoutInput<T>(value: T): T {\n const seen = new WeakSet<object>();\n const freeze = (entry: unknown): unknown => {\n if (!entry || typeof entry !== 'object' || seen.has(entry)) return entry;\n seen.add(entry);\n if (Array.isArray(entry)) {\n for (const item of entry) freeze(item);\n } else {\n for (const item of Object.values(entry)) freeze(item);\n }\n return Object.freeze(entry);\n };\n return freeze(value) as T;\n }\n\n function immutableLayoutSet(\n values: ReadonlySet<string> | undefined,\n ): ReadonlySet<string> | undefined {\n if (!values) return undefined;\n const target = new Set(values);\n return new Proxy(target, {\n get(set, property) {\n if (property === 'add' || property === 'delete' || property === 'clear') {\n return () => {\n throw new TypeError('Layout option sets are readonly.');\n };\n }\n const value = Reflect.get(set, property, set);\n return typeof value === 'function' ? value.bind(set) : value;\n },\n });\n }\n\n function immutablePreviousLayoutResult(\n result: LayoutResult | null | undefined,\n ): LayoutResult | null | undefined {\n if (result == null) return result;\n const cloned = normalizeLayoutResult(result);\n const readonlyMap = <TValue>(map: ReadonlyMap<string, TValue>) =>\n new Proxy(new Map(map), {\n get(target, property) {\n if (property === 'set' || property === 'delete' || property === 'clear') {\n return () => {\n throw new TypeError('Previous layout result is readonly.');\n };\n }\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n }) as ReadonlyMap<string, TValue>;\n return Object.freeze({\n ...cloned,\n positions: readonlyMap(cloned.positions),\n ...(cloned.nodeSizes\n ? { nodeSizes: readonlyMap(cloned.nodeSizes) }\n : {}),\n ...(cloned.nodeBounds\n ? { nodeBounds: readonlyMap(cloned.nodeBounds) }\n : {}),\n ...(cloned.edgeLabelPositions\n ? { edgeLabelPositions: readonlyMap(cloned.edgeLabelPositions) }\n : {}),\n ...(cloned.edgeLabelBounds\n ? { edgeLabelBounds: readonlyMap(cloned.edgeLabelBounds) }\n : {}),\n ...(cloned.edgeRoutes\n ? { edgeRoutes: readonlyMap(cloned.edgeRoutes) }\n : {}),\n ...(cloned.overrideFixedEntityIds\n ? {\n overrideFixedEntityIds: immutableLayoutSet(\n cloned.overrideFixedEntityIds,\n ),\n }\n : {}),\n });\n }\n\n function configure(\n update:\n | FlowConfigureOptions\n | ((current: Readonly<FlowConfiguration>) => FlowConfiguration),\n ): void {\n const requested =\n typeof update === 'function'\n ? update(immutableConfiguration(configuration))\n : update;\n const replace = typeof update === 'function';\n const historyLimit =\n requested.historyLimit ?? requested.store?.historyLimit;\n if (\n historyLimit !== undefined &&\n historyLimit !== configuration.historyLimit\n ) {\n throw new TypeError(\n 'flow.configure(): historyLimit cannot be changed after creation.',\n );\n }\n const next = historyLimit === undefined\n ? requested\n : {\n ...requested,\n historyLimit,\n store: { ...requested.store, historyLimit },\n };\n if (replace) {\n for (const key of [\n 'engine',\n 'store',\n 'defaultEdgeOptions',\n 'createEdgeOnConnect',\n 'layout',\n 'historyLimit',\n ] as const) {\n if (!(key in next)) {\n throw new TypeError(`flow.configure() replacement is missing \"${key}\"`);\n }\n }\n }\n if (next.engine) {\n engine.setOptions(\n replace ? next.engine : { ...configuration.engine, ...next.engine },\n replace,\n );\n }\n // `undefined` means \"leave as-is\" (StatelyFlow always passes the key, often\n // undefined, and must not clobber options set at instance creation); pass\n // `null` to explicitly clear.\n if (next.defaultEdgeOptions !== undefined) {\n defaultEdgeOptions =\n next.defaultEdgeOptions === null\n ? undefined\n : { ...next.defaultEdgeOptions };\n }\n if (next.createEdgeOnConnect !== undefined) {\n createEdgeOnConnect = next.createEdgeOnConnect;\n }\n configuration = replace\n ? {\n ...(next as FlowConfiguration),\n engine: { ...next.engine },\n store: { ...next.store },\n defaultEdgeOptions: next.defaultEdgeOptions\n ? { ...next.defaultEdgeOptions }\n : null,\n }\n : {\n ...configuration,\n ...next,\n engine: { ...configuration.engine, ...next.engine },\n store: { ...configuration.store, ...next.store },\n defaultEdgeOptions:\n next.defaultEdgeOptions === undefined\n ? configuration.defaultEdgeOptions\n : next.defaultEdgeOptions === null\n ? null\n : { ...next.defaultEdgeOptions },\n };\n const storeSettings: Partial<FlowStoreOptions> = {\n ...next.store,\n ...(next.engine?.labelAnchor !== undefined && next.store?.labelAnchor === undefined\n ? { labelAnchor: next.engine.labelAnchor }\n : {}),\n };\n store.trigger.configure(storeSettings);\n }\n\n function toJSON(): FlowSerialized<TNodeData, TEdgeData, TLabelData> {\n const context = store.getSnapshot().context;\n return {\n version: 1,\n graph: serializeFlowGraph(\n context.graph as FlowGraph<TNodeData, TEdgeData, TLabelData>,\n ),\n viewport: { ...context.viewport },\n collapsedNodeIds: [...context.collapsedNodeIds],\n ...(currentDataVersions(options.dataSchemas)\n ? { dataVersions: currentDataVersions(options.dataSchemas) }\n : {}),\n };\n }\n\n function load(data: unknown): FlowResult<void> {\n try {\n const parsed = parseFlowSerialized<TNodeData, TEdgeData, TLabelData>(\n data,\n options.dataSchemas,\n );\n cancelViewportAnimation();\n store.trigger.loadDocument({\n graph: parsed.graph,\n collapsedNodeIds: parsed.collapsedNodeIds ?? [],\n viewport: parsed.viewport,\n origin: 'load',\n });\n return { ok: true, value: undefined };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof FlowGraphValidationError\n ? error\n : new FlowGraphValidationError([\n { code: 'load_failed', path: '$', message: String(error) },\n ]),\n };\n }\n }\n\n function resolvedLayoutAnimation(): LayoutAnimationControls {\n return { cancel: () => {}, done: Promise.resolve() };\n }\n\n function startLayoutAnimation(\n initialOffsets: Map<string, Point>,\n animation: LayoutAnimationOptions | undefined,\n ): LayoutAnimationControls {\n const duration = animation?.duration ?? 0;\n if (\n !Number.isFinite(duration) ||\n duration <= 0 ||\n initialOffsets.size === 0\n ) {\n store.trigger.clearLayoutAnimation();\n return resolvedLayoutAnimation();\n }\n\n const requestFrame = (callback: (time: number) => void): number => {\n if (typeof requestAnimationFrame === 'function') {\n return requestAnimationFrame(callback);\n }\n return setTimeout(() => callback(Date.now()), 16) as unknown as number;\n };\n const cancelFrame = (id: number) => {\n if (typeof cancelAnimationFrame === 'function') {\n cancelAnimationFrame(id);\n } else {\n clearTimeout(id);\n }\n };\n const easing = animation?.easing ?? ((t: number) =>\n t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);\n let frame: number | null = null;\n let startTime: number | null = null;\n let stopped = false;\n let resolveDone = () => {};\n const done = new Promise<void>((resolve) => {\n resolveDone = resolve;\n });\n const controls: LayoutAnimationControls = {\n cancel: () => session.stop(true),\n done,\n };\n const session = {\n controls,\n stop: (clear: boolean) => {\n if (stopped) return;\n stopped = true;\n if (frame !== null) cancelFrame(frame);\n frame = null;\n if (clear) store.trigger.clearLayoutAnimation();\n if (activeLayoutAnimation === session) activeLayoutAnimation = null;\n resolveDone();\n },\n };\n const step = (time: number) => {\n if (stopped) return;\n if (startTime === null) startTime = time;\n const progress = Math.min(1, (time - startTime) / duration);\n if (progress >= 1) {\n session.stop(true);\n return;\n }\n const eased = easing(progress);\n const remaining = 1 - (Number.isFinite(eased) ? eased : progress);\n const offsets = new Map<string, Point>();\n for (const [id, offset] of initialOffsets) {\n const next = { x: offset.x * remaining, y: offset.y * remaining };\n if (Math.abs(next.x) > 1e-6 || Math.abs(next.y) > 1e-6) {\n offsets.set(id, next);\n }\n }\n store.trigger.setLayoutAnimationOffsets({ offsets });\n frame = requestFrame(step);\n };\n activeLayoutAnimation = session;\n frame = requestFrame(step);\n return controls;\n }\n\n function applyLayout(\n input: LayoutResult,\n applyOptions: LayoutApplyOptions = {},\n ): LayoutAnimationControls {\n const result = normalizeLayoutResult(input);\n const graph = currentGraph();\n const nodeIds = new Set(graph.nodes.map((node) => node.id));\n const edgeIds = new Set(graph.edges.map((edge) => edge.id));\n const entityIds = new Set([...nodeIds, ...edgeIds]);\n const edgesWithLabels = new Set(\n graph.edges.filter((edge) => edge.label).map((edge) => edge.id),\n );\n const issues: Array<{ code: string; path: string; message: string }> = [];\n const finitePoint = (point: Point, path: string) => {\n if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {\n issues.push({\n code: 'invalid_layout_geometry',\n path,\n message: 'expected finite x/y',\n });\n }\n };\n const finiteSize = (size: Size, path: string) => {\n if (\n !Number.isFinite(size.width) ||\n !Number.isFinite(size.height) ||\n size.width < 0 ||\n size.height < 0\n ) {\n issues.push({\n code: 'invalid_layout_geometry',\n path,\n message: 'expected non-negative finite width/height',\n });\n }\n };\n const validateMap = <TValue>(\n field: string,\n map: ReadonlyMap<string, TValue> | undefined,\n ids: ReadonlySet<string>,\n validate: (value: TValue, path: string) => void,\n ) => {\n if (!map) return;\n for (const [id, value] of [...map].sort(([a], [b]) => a.localeCompare(b))) {\n const path = `$.layout.${field}.${id}`;\n if (!ids.has(id)) {\n issues.push({\n code: 'unknown_layout_entity',\n path,\n message: `unknown entity id \"${id}\"`,\n });\n continue;\n }\n validate(value, path);\n }\n };\n validateMap('positions', result.positions, nodeIds, finitePoint);\n validateMap('nodeSizes', result.nodeSizes, nodeIds, finiteSize);\n validateMap('nodeBounds', result.nodeBounds, nodeIds, (rect, path) => {\n finitePoint(rect, path);\n finiteSize(rect, path);\n });\n validateMap(\n 'edgeLabelPositions',\n result.edgeLabelPositions,\n edgesWithLabels,\n finitePoint,\n );\n validateMap(\n 'edgeLabelBounds',\n result.edgeLabelBounds,\n edgesWithLabels,\n (rect, path) => {\n finitePoint(rect, path);\n finiteSize(rect, path);\n },\n );\n validateMap('edgeRoutes', result.edgeRoutes, edgeIds, (route, path) => {\n const points = hasAuthoritativeLayoutPoints(route)\n ? route.points\n : layoutWaypoints(route);\n points.forEach((point, index) =>\n finitePoint(point, `${path}.points[${index}]`),\n );\n });\n for (const [field, ids] of [\n ['fixedEntityIds', applyOptions.fixedEntityIds],\n ['pinnedEntityIds', applyOptions.pinnedEntityIds],\n [\n 'overrideFixedEntityIds',\n applyOptions.overrideFixedEntityIds ?? result.overrideFixedEntityIds,\n ],\n ] as const) {\n for (const id of [...(ids ?? [])].sort()) {\n if (!entityIds.has(id)) {\n issues.push({\n code: 'unknown_layout_entity',\n path: `$.layout.${field}.${id}`,\n message: `unknown entity id \"${id}\"`,\n });\n }\n }\n }\n if (issues.length > 0) throw new FlowGraphValidationError(issues);\n\n const fixedIds = new Set([\n ...(applyOptions.fixedEntityIds ?? []),\n ...(applyOptions.pinnedEntityIds ?? []),\n ]);\n const overrideIds = new Set(\n applyOptions.overrideFixedEntityIds ??\n result.overrideFixedEntityIds ??\n [],\n );\n const animate = (applyOptions.animation?.duration ?? 0) > 0 && !activeTransaction;\n const beforeBounds = new Map<string, Rect>();\n if (animate) {\n for (const node of graph.nodes) {\n if (fixedIds.has(node.id) && !overrideIds.has(node.id)) continue;\n if (result.nodeBounds?.has(node.id) || result.positions.has(node.id)) {\n beforeBounds.set(node.id, engine.visualBounds(node.id));\n }\n }\n const paths = engine.getAllEdgePaths();\n for (const edge of graph.edges) {\n if (fixedIds.has(edge.id) && !overrideIds.has(edge.id)) continue;\n if (\n edge.label &&\n (edge.labelAnchor ?? configuration.engine.labelAnchor ?? 'fixed') ===\n 'fixed' &&\n (result.edgeLabelBounds?.has(edge.id) ||\n result.edgeLabelPositions?.has(edge.id))\n ) {\n const bounds =\n paths.get(edge.id)?.labelBounds ?? engine.getBounds(edge.id);\n if (bounds) beforeBounds.set(edge.id, bounds);\n }\n }\n }\n\n const draft = validateAndCloneGraph(currentGraph(), options.dataSchemas);\n const changedNodeIds = new Set<string>();\n for (const node of draft.nodes) {\n if (fixedIds.has(node.id) && !overrideIds.has(node.id)) continue;\n const before = resolvedBounds(node);\n const bounds = result.nodeBounds?.get(node.id);\n const position = result.positions.get(node.id);\n const size = result.nodeSizes?.get(node.id);\n if (bounds) {\n node.x = roundLayoutPosition(bounds.x);\n node.y = roundLayoutPosition(bounds.y);\n node.width = bounds.width;\n node.height = bounds.height;\n }\n if (position) {\n node.x = roundLayoutPosition(position.x);\n node.y = roundLayoutPosition(position.y);\n }\n if (size) {\n node.width = size.width;\n node.height = size.height;\n }\n if (bounds || position) {\n delete node.dx;\n delete node.dy;\n }\n const after = resolvedBounds(node);\n if (\n before.x !== after.x ||\n before.y !== after.y ||\n before.width !== after.width ||\n before.height !== after.height\n ) {\n changedNodeIds.add(node.id);\n }\n }\n const affectedNodeIds = withDerivedGroupAncestors(\n draft.nodes,\n changedNodeIds,\n );\n for (const edge of draft.edges) {\n if (fixedIds.has(edge.id) && !overrideIds.has(edge.id)) continue;\n delete edge.dx;\n delete edge.dy;\n const labelBounds = result.edgeLabelBounds?.get(edge.id);\n const labelPosition = result.edgeLabelPositions?.get(edge.id);\n const route = result.edgeRoutes?.get(edge.id);\n if (\n route ||\n affectedNodeIds.has(edge.sourceId) ||\n affectedNodeIds.has(edge.targetId)\n ) {\n invalidateAuthoritativeEdgePath(edge);\n }\n if (edge.label && labelBounds) {\n edge.label.x = roundLayoutPosition(labelBounds.x);\n edge.label.y = roundLayoutPosition(labelBounds.y);\n edge.label.width = labelBounds.width;\n edge.label.height = labelBounds.height;\n edge.x = roundLayoutPosition(labelBounds.x);\n edge.y = roundLayoutPosition(labelBounds.y);\n edge.width = labelBounds.width;\n edge.height = labelBounds.height;\n }\n if (edge.label && labelPosition) {\n edge.label.x = roundLayoutPosition(labelPosition.x);\n edge.label.y = roundLayoutPosition(labelPosition.y);\n edge.x = roundLayoutPosition(labelPosition.x);\n edge.y = roundLayoutPosition(labelPosition.y);\n }\n if (edge.label && (labelBounds || labelPosition)) {\n delete edge.label.dx;\n delete edge.label.dy;\n }\n if (route) {\n if (hasAuthoritativeLayoutPoints(route)) {\n edge.points = route.points.map(roundLayoutPoint);\n edge.routing = route.routing ?? 'polyline';\n delete edge.waypoints;\n } else {\n const waypoints = layoutWaypoints(route);\n edge.waypoints = waypoints.map(roundLayoutPoint);\n }\n }\n }\n\n const initialOffsets = new Map<string, Point>();\n if (animate) {\n for (const [id, before] of beforeBounds) {\n const node = draft.nodes.find((candidate) => candidate.id === id);\n const edge = draft.edges.find((candidate) => candidate.id === id);\n const target = node\n ? { x: node.x, y: node.y }\n : edge?.label\n ? { x: edge.label.x, y: edge.label.y }\n : null;\n if (!target) continue;\n const offset = { x: before.x - target.x, y: before.y - target.y };\n if (Math.abs(offset.x) > 1e-6 || Math.abs(offset.y) > 1e-6) {\n initialOffsets.set(id, offset);\n }\n }\n\n // A fixed label can keep the same authored coordinates while either\n // endpoint moves. Give it the midpoint endpoint offset so it follows\n // the animated edge instead of appearing detached until the final\n // frame. A label's own layout delta remains authoritative when present.\n for (const edge of draft.edges) {\n if (!beforeBounds.has(edge.id) || initialOffsets.has(edge.id)) continue;\n const sourceOffset = initialOffsets.get(edge.sourceId);\n const targetOffset = initialOffsets.get(edge.targetId);\n if (!sourceOffset && !targetOffset) continue;\n const offset = {\n x: ((sourceOffset?.x ?? 0) + (targetOffset?.x ?? 0)) / 2,\n y: ((sourceOffset?.y ?? 0) + (targetOffset?.y ?? 0)) / 2,\n };\n if (Math.abs(offset.x) > 1e-6 || Math.abs(offset.y) > 1e-6) {\n initialOffsets.set(edge.id, offset);\n }\n }\n }\n\n activeLayoutAnimation?.stop(false);\n commitGraph(\n draft,\n applyOptions,\n undefined,\n animate ? initialOffsets : undefined,\n );\n return startLayoutAnimation(initialOffsets, applyOptions.animation);\n }\n\n async function runLayout(\n layout = configuration.layout ?? undefined,\n runOptions: LayoutRunOptions = {},\n ): Promise<LayoutRunResult> {\n if (!layout) {\n throw new Error(\n 'flow.layout.run() was called without a layout algorithm. ' +\n 'Pass one to createFlow({ layout }) or call flow.layout.run(myLayout) directly.',\n );\n }\n const runId = ++latestLayoutRun;\n activeLayoutAbort?.abort();\n const abortListeners = new Set<() => void>();\n let aborted = false;\n const controller = {\n signal: {\n get aborted() {\n return aborted;\n },\n addEventListener: (_type: 'abort', listener: () => void) => {\n abortListeners.add(listener);\n },\n removeEventListener: (_type: 'abort', listener: () => void) => {\n abortListeners.delete(listener);\n },\n } satisfies FlowAbortSignal,\n abort: () => {\n if (aborted) return;\n aborted = true;\n for (const listener of abortListeners) listener();\n abortListeners.clear();\n },\n };\n Object.freeze(controller.signal);\n const abort = () => controller.abort();\n const startedRevision = graphRevision;\n const startedGraph = store.getSnapshot().context.graph;\n const entityIds = new Set([\n ...startedGraph.nodes.map((node) => node.id),\n ...startedGraph.edges.map((edge) => edge.id),\n ]);\n for (const [field, ids] of [\n ['fixedEntityIds', runOptions.fixedEntityIds],\n ['pinnedEntityIds', runOptions.pinnedEntityIds],\n ] as const) {\n const unknown = [...(ids ?? [])]\n .filter((id) => !entityIds.has(id))\n .sort();\n if (unknown.length > 0) {\n throw new FlowGraphValidationError(\n unknown.map((id) => ({\n code: 'unknown_layout_entity',\n path: `$.layout.${field}.${id}`,\n message: `unknown entity id \"${id}\"`,\n })),\n );\n }\n }\n const scope = runOptions.scope\n ? validateViewScope(runOptions.scope)\n : undefined;\n const graphInput = immutableLayoutInput(\n validateAndCloneGraph(startedGraph, options.dataSchemas) as FlowGraph<\n TNodeData,\n TEdgeData,\n TLabelData\n >,\n );\n const algorithmOptions = Object.freeze({\n signal: controller.signal,\n ...(runOptions.force !== undefined ? { force: runOptions.force } : {}),\n ...(scope ? { scope } : {}),\n ...(runOptions.previousResult !== undefined\n ? {\n previousResult: immutablePreviousLayoutResult(\n runOptions.previousResult,\n ),\n }\n : {}),\n ...(runOptions.fixedEntityIds\n ? { fixedEntityIds: immutableLayoutSet(runOptions.fixedEntityIds) }\n : {}),\n ...(runOptions.pinnedEntityIds\n ? { pinnedEntityIds: immutableLayoutSet(runOptions.pinnedEntityIds) }\n : {}),\n ...(runOptions.source !== undefined ? { source: runOptions.source } : {}),\n ...(runOptions.metadata\n ? {\n metadata: immutableLayoutInput(\n cloneJsonSafe(runOptions.metadata, '$.layout.metadata'),\n ),\n }\n : {}),\n ...(runOptions.animation\n ? { animation: Object.freeze({ ...runOptions.animation }) }\n : {}),\n }) satisfies Readonly<LayoutRunOptions> & { signal: FlowAbortSignal };\n activeLayoutAbort = controller;\n runOptions.signal?.addEventListener('abort', abort, { once: true });\n let result: LayoutResult | LayoutPositions;\n try {\n result = await layout(graphInput, algorithmOptions);\n } catch (error) {\n if (controller.signal.aborted) {\n const result: LayoutResult = {\n positions: new Map(),\n ...(runOptions.source ? { source: runOptions.source } : {}),\n };\n return {\n applied: false,\n result,\n animation: resolvedLayoutAnimation(),\n ...(result.source ? { source: result.source } : {}),\n };\n }\n throw error;\n } finally {\n runOptions.signal?.removeEventListener('abort', abort);\n if (activeLayoutAbort === controller) activeLayoutAbort = null;\n }\n let layoutResult = normalizeLayoutResult(result);\n if (!layoutResult.source && runOptions.source) {\n layoutResult = { ...layoutResult, source: runOptions.source };\n }\n const response = (\n applied: boolean,\n animation = resolvedLayoutAnimation(),\n ): LayoutRunResult => ({\n applied,\n result: layoutResult,\n animation,\n ...(layoutResult.source ? { source: layoutResult.source } : {}),\n ...(layoutResult.diagnostics\n ? { diagnostics: layoutResult.diagnostics }\n : {}),\n });\n if (\n controller.signal.aborted ||\n runId !== latestLayoutRun ||\n (!runOptions.force &&\n (graphRevision !== startedRevision ||\n store.getSnapshot().context.graph !== startedGraph))\n ) {\n return response(false);\n }\n const animation = applyLayout(layoutResult, {\n origin: 'layout',\n fixedEntityIds: runOptions.fixedEntityIds,\n pinnedEntityIds: runOptions.pinnedEntityIds,\n overrideFixedEntityIds: layoutResult.overrideFixedEntityIds,\n animation: runOptions.animation,\n });\n return response(true, animation);\n }\n\n function writeViewport(viewport: Viewport): void {\n pendingInternalViewportWrites.push({ ...viewport });\n try {\n store.trigger.setViewport(viewport);\n } catch (error) {\n pendingInternalViewportWrites.pop();\n throw error;\n }\n }\n\n function constrainedViewport(viewport: Viewport): Viewport {\n const context = store.getSnapshot().context;\n return context.translateExtent\n ? constrainViewport(viewport, context.viewportSize, context.translateExtent)\n : viewport;\n }\n\n function cancelViewportAnimation(): void {\n activeViewportAnimation?.cancel();\n activeViewportAnimation = null;\n pendingInternalViewportWrites.length = 0;\n }\n\n function resolvedViewportControls(reached = true): ViewportAnimationControls {\n return { cancel: () => {}, done: Promise.resolve(reached) };\n }\n\n function setViewportTarget(\n target: Viewport | null,\n animationOptions?: ViewportAnimationOptions,\n ): ViewportAnimationControls {\n if (!target) {\n cancelViewportAnimation();\n return resolvedViewportControls(false);\n }\n cancelViewportAnimation();\n const resolvedAnimationOptions = {\n ...(store.getSnapshot().context.viewportAnimation ?? {}),\n ...animationOptions,\n ...(animationOptions?.duration !== undefined\n ? { lerp: undefined, spring: undefined }\n : animationOptions?.lerp !== undefined\n ? { duration: undefined, easing: undefined, spring: undefined }\n : animationOptions?.spring !== undefined\n ? { duration: undefined, easing: undefined, lerp: undefined }\n : {}),\n };\n if (\n (resolvedAnimationOptions.duration ?? 0) <= 0 &&\n !resolvedAnimationOptions.spring &&\n resolvedAnimationOptions.lerp === undefined\n ) {\n store.trigger.setViewport(target);\n return resolvedViewportControls();\n }\n const animation = animateViewport(\n {\n ...store,\n trigger: {\n ...store.trigger,\n setViewport: writeViewport,\n },\n },\n target,\n resolvedAnimationOptions,\n );\n activeViewportAnimation = animation;\n void animation.done.then(() => {\n if (activeViewportAnimation === animation) {\n activeViewportAnimation = null;\n }\n });\n return animation;\n }\n\n function fitViewportTarget(\n fitOptions?: FitViewOptions & { includeHidden?: boolean },\n ): Viewport | null {\n const context = store.getSnapshot().context;\n if (context.viewportSize.width === 0 || context.viewportSize.height === 0) {\n return null;\n }\n\n const ids = fitOptions?.nodes?.map((node) =>\n typeof node === 'string' ? node : node.id,\n );\n const idSet = ids && ids.length > 0 ? new Set(ids) : null;\n const visible = getViewEntities({\n includeHidden: fitOptions?.includeHidden,\n });\n const nodes = (visible.nodes as readonly FlowNode[]).filter(\n (node) => !idSet || idSet.has(node.id),\n );\n const edges = (visible.edges as readonly FlowEdge[]).filter(\n (edge) => !idSet || idSet.has(edge.id),\n );\n const bounds = getGraphBounds(\n nodes.map((node) => {\n const visual = engine.visualBounds(node.id);\n return visual\n ? {\n ...node,\n ...visual,\n dx: 0,\n dy: 0,\n autoSize: false,\n style: undefined,\n }\n : node;\n }),\n edges.map((edge) => edge.label ? { ...edge, label: { ...edge.label, autoSize: engine.resolveAppearance(edge.label).autoSize } } : edge),\n context.measurements,\n );\n if (bounds.width === 0 && bounds.height === 0) return null;\n const { nodes: _nodes, includeHidden: _includeHidden, ...viewportOptions } = fitOptions ?? {};\n return viewportForBounds(bounds, context.viewportSize, {\n ...viewportOptions,\n frame: getFitFrame(viewportOptions.frame),\n });\n }\n\n function getFitFrame(frame?: Rect): Readonly<Rect> {\n const context = store.getSnapshot().context;\n const base = frame\n ? validateFitFrame(frame)\n : context.fitFrame\n ? validateFitFrame(context.fitFrame)\n : {\n x: 0,\n y: 0,\n width: context.viewportSize.width,\n height: context.viewportSize.height,\n };\n // A controller can receive viewport commands before its DOM adapter has\n // reported a size. Preserve the pre-existing zero-sized frame behavior;\n // exclusions only become meaningful once there is a measurable frame.\n if (base.width <= 0 || base.height <= 0) {\n return Object.freeze(base);\n }\n const resolved = [...fitExclusions].flatMap((exclusion) => {\n const rect = exclusion.getRect();\n return rect\n ? [{ rect, side: exclusion.side, gap: exclusion.gap }]\n : [];\n });\n return Object.freeze(fitFrameAroundExclusions(base, resolved));\n }\n\n function frameCenter(frame?: Rect): Point {\n const target = getFitFrame(frame);\n return {\n x: target.x + target.width / 2,\n y: target.y + target.height / 2,\n };\n }\n\n type Graph = FlowGraph<TNodeData, TEdgeData, TLabelData>;\n const viewScopeCache = new WeakMap<FlowStoreContext, FlowViewScope>();\n const viewEntitiesCache = new WeakMap<\n FlowStoreContext,\n Map<string, FlowViewEntities<TNodeData, TEdgeData, TLabelData>>\n >();\n let activeTransaction: {\n graph: Graph;\n options?: FlowTransactionOptions;\n authoredEdgeRouteIds: Set<string>;\n removedEntityIds: Set<string>;\n } | null = null;\n\n function scopedTransactionApi<TApi extends object>(\n api: TApi,\n assertOpen: () => void,\n ): TApi {\n return new Proxy(api, {\n get(target, property, receiver) {\n const value = Reflect.get(target, property, receiver);\n if (typeof value !== 'function') return value;\n return (...args: unknown[]) => {\n assertOpen();\n return Reflect.apply(value, target, args);\n };\n },\n });\n }\n\n function currentGraph(): Graph {\n return (activeTransaction?.graph ?? store.getSnapshot().context.graph) as Graph;\n }\n\n function currentViewScope(): FlowViewScope {\n const context = store.getSnapshot().context;\n const cached = viewScopeCache.get(context);\n if (cached) return cached;\n const scope = Object.freeze({\n parentId: context.parentNodeId,\n depth: context.depth,\n });\n viewScopeCache.set(context, scope);\n return scope;\n }\n\n function getViewEntities(\n viewOptions: { includeHidden?: boolean } = {},\n scope = currentViewScope(),\n ): FlowViewEntities<TNodeData, TEdgeData, TLabelData> {\n const context = store.getSnapshot().context;\n const graph = currentGraph();\n const isCurrentScope =\n scope.parentId === context.parentNodeId && scope.depth === context.depth;\n const cacheKey = viewOptions.includeHidden ? 'hidden' : 'visible';\n if (!activeTransaction && isCurrentScope) {\n const cached = viewEntitiesCache.get(context)?.get(cacheKey);\n if (cached) return cached;\n }\n\n const visible = viewOptions.includeHidden\n ? { nodes: graph.nodes, edges: graph.edges }\n : engine.getVisibleEntities();\n const canonicalEdgeIds = new Set(graph.edges.map((edge) => edge.id));\n const result = deriveFlowView(graph, scope, {\n nodes: visible.nodes,\n edges: visible.edges,\n edgeOwner: (edge) =>\n !activeTransaction && canonicalEdgeIds.has(edge.id)\n ? engine.getEdgeOwner(edge.id)\n : getDefaultEdgeOwner(edge, graph.nodes),\n });\n if (!activeTransaction && isCurrentScope) {\n let cache = viewEntitiesCache.get(context);\n if (!cache) {\n cache = new Map();\n viewEntitiesCache.set(context, cache);\n }\n cache.set(cacheKey, result);\n }\n return result;\n }\n\n function validateViewScope(scope: FlowViewScope): FlowViewScope {\n if (!scope || typeof scope !== 'object') {\n throw new TypeError('flow.view.setScope(): scope must be an object.');\n }\n if (scope.parentId !== null && typeof scope.parentId !== 'string') {\n throw new TypeError(\n 'flow.view.setScope(): parentId must be a node id or null.',\n );\n }\n if (scope.parentId !== null && !currentGraph().nodes.some(\n (node) => node.id === scope.parentId,\n )) {\n throw new RangeError(\n `flow.view.setScope(): parent node \"${scope.parentId}\" does not exist.`,\n );\n }\n if (\n scope.depth !== null &&\n (!Number.isInteger(scope.depth) || scope.depth < 0)\n ) {\n throw new RangeError(\n 'flow.view.setScope(): depth must be a non-negative integer or null.',\n );\n }\n return Object.freeze({ parentId: scope.parentId, depth: scope.depth });\n }\n\n function validateDraftConnections(graph: Graph): void {\n const previousGraph = store.getSnapshot().context.graph;\n const previousEdges = new Map(\n previousGraph.edges.map((edge) => [edge.id, edge]),\n );\n const currentNodeIds = new Set(graph.nodes.map((node) => node.id));\n const context = { ...store.getSnapshot().context, graph };\n for (const edge of graph.edges) {\n const previous = previousEdges.get(edge.id);\n if (\n previous &&\n previous.sourceId === edge.sourceId &&\n previous.targetId === edge.targetId &&\n previous.sourcePort === edge.sourcePort &&\n previous.targetPort === edge.targetPort\n )\n continue;\n const retargetedAfterDeletion =\n configuration.store.onDeleteNodes === 'retarget' &&\n previous !== undefined &&\n ((currentNodeIds.has(previous.sourceId) &&\n !currentNodeIds.has(previous.targetId) &&\n edge.sourceId === previous.sourceId &&\n edge.targetId === previous.sourceId &&\n edge.sourcePort === previous.sourcePort &&\n edge.targetPort === null) ||\n (!currentNodeIds.has(previous.sourceId) &&\n currentNodeIds.has(previous.targetId) &&\n edge.sourceId === previous.targetId &&\n edge.targetId === previous.targetId &&\n edge.sourcePort === null &&\n edge.targetPort === previous.targetPort));\n if (retargetedAfterDeletion) continue;\n if (\n context.mode === 'readonly' ||\n policyValue('canEdit') === false ||\n policyValue('canConnect') === false ||\n (previous && policyValue('canReconnect') === false)\n ) {\n throw new Error(`Connection for edge \"${edge.id}\" is not allowed.`);\n }\n if (!engine.validateConnectionDetailed(edge, context).valid) {\n throw new Error(`Connection for edge \"${edge.id}\" is not allowed.`);\n }\n }\n }\n\n function commitGraph(\n graph: Graph,\n transactionOptions: FlowTransactionOptions = {},\n replacementOptions?: {\n retention: FlowGraphRetentionPolicy;\n history: FlowGraphHistoryPolicy;\n },\n layoutAnimationOffsets?: Map<string, Point>,\n resetMeasurementIds: readonly string[] = [],\n ): FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null {\n assertTransactionOptions(transactionOptions);\n const validated = validateAndCloneGraph(graph, options.dataSchemas);\n if (activeTransaction) {\n activeTransaction.graph = validated;\n return null;\n }\n if (!replacementOptions) validateDraftConnections(validated);\n const before = currentGraph();\n const changeSet = createFlowChangeSet(before, validated, {\n revision: graphRevision + 1,\n ...transactionOptions,\n });\n if (\n !changeSet &&\n !replacementOptions &&\n !layoutAnimationOffsets &&\n !resetMeasurementIds.length\n )\n return null;\n store.trigger.replaceGraph({\n graph: reuseUnchangedEntities(before, validated, changeSet),\n graphChanged: changeSet !== null,\n resetMeasurementIds,\n ...transactionOptions,\n ...replacementOptions,\n ...(layoutAnimationOffsets ? { layoutAnimationOffsets } : {}),\n });\n return changeSet;\n }\n\n function replaceGraph(\n graph: Graph,\n replaceOptions: FlowReplaceGraphOptions = {},\n ): FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null {\n const retention = replaceOptions.retention ?? 'preserve';\n const history = replaceOptions.history ?? 'reset';\n if (retention !== 'preserve' && retention !== 'reset') {\n throw new TypeError(\n 'flow.replaceGraph(): retention must be \"preserve\" or \"reset\".',\n );\n }\n if (history !== 'reset' && history !== 'ignore' && history !== 'record') {\n throw new TypeError(\n 'flow.replaceGraph(): history must be \"reset\", \"ignore\", or \"record\".',\n );\n }\n if (activeTransaction) {\n throw new Error(\n 'flow.replaceGraph() cannot run inside flow.transaction().',\n );\n }\n return commitGraph(\n graph,\n {\n origin: replaceOptions.origin ?? 'external',\n transactionId: replaceOptions.transactionId,\n },\n { retention, history },\n );\n }\n\n function mutateGraph<TResult>(\n mutate: (graph: Graph) => TResult,\n transactionOptions?: FlowTransactionOptions,\n ): TResult {\n assertTransactionOptions(transactionOptions);\n const previous = currentGraph();\n const draft = validateAndCloneGraph(previous, options.dataSchemas);\n const result = mutate(draft);\n const previousNodes = new Map(previous.nodes.map((node) => [node.id, node]));\n const previousEdges = new Map(previous.edges.map((edge) => [edge.id, edge]));\n const changedNodeIds = new Set<string>();\n for (const node of draft.nodes) {\n const before = previousNodes.get(node.id);\n if (!before) {\n changedNodeIds.add(node.id);\n } else if (\n nodeEndpointGeometryChanged(before, node) ||\n (before.parentId ?? null) !== (node.parentId ?? null)\n ) {\n changedNodeIds.add(node.id);\n }\n }\n const draftNodeIds = new Set(draft.nodes.map((node) => node.id));\n for (const node of previous.nodes) {\n if (!draftNodeIds.has(node.id)) changedNodeIds.add(node.id);\n }\n if (activeTransaction) {\n const draftEdgeIds = new Set(draft.edges.map((edge) => edge.id));\n for (const edgeId of activeTransaction.authoredEdgeRouteIds) {\n if (!draftEdgeIds.has(edgeId)) {\n activeTransaction.authoredEdgeRouteIds.delete(edgeId);\n }\n }\n }\n const affectedNodeIds = new Set([\n ...withDerivedGroupAncestors(previous.nodes, changedNodeIds),\n ...withDerivedGroupAncestors(draft.nodes, changedNodeIds),\n ]);\n for (const edge of draft.edges) {\n const before = previousEdges.get(edge.id);\n const endpointChanged = before && (\n edge.sourceId !== before.sourceId ||\n edge.targetId !== before.targetId ||\n (edge.sourcePort ?? undefined) !== (before.sourcePort ?? undefined) ||\n (edge.targetPort ?? undefined) !== (before.targetPort ?? undefined)\n );\n const pointsUnchanged = before && pointsEqual(before.points, edge.points);\n if (activeTransaction && !pointsUnchanged) {\n if (edge.points && edge.points.length >= 2) {\n activeTransaction.authoredEdgeRouteIds.add(edge.id);\n } else {\n activeTransaction.authoredEdgeRouteIds.delete(edge.id);\n }\n }\n const routeAuthoredInTransaction =\n activeTransaction?.authoredEdgeRouteIds.has(edge.id) ?? false;\n if (\n pointsUnchanged &&\n !routeAuthoredInTransaction &&\n (endpointChanged ||\n affectedNodeIds.has(edge.sourceId) ||\n affectedNodeIds.has(edge.targetId))\n ) {\n invalidateAuthoritativeEdgePath(edge);\n }\n }\n commitGraph(draft, transactionOptions);\n if (activeTransaction) {\n const surviving = new Set([...draft.nodes, ...draft.edges].map(entity => entity.id));\n for (const entity of [...previous.nodes, ...previous.edges]) {\n if (!surviving.has(entity.id)) activeTransaction.removedEntityIds.add(entity.id);\n }\n }\n return result;\n }\n\n function pointsEqual(\n previous: readonly Point[] | undefined,\n next: readonly Point[] | undefined,\n ): boolean {\n if (!previous || !next) return previous === next;\n return (\n previous.length === next.length &&\n previous.every(\n (point, index) =>\n point.x === next[index]?.x && point.y === next[index]?.y,\n )\n );\n }\n\n function entityIds(graph = currentGraph()): Set<string> {\n return new Set([\n ...graph.nodes.map((node) => node.id),\n ...graph.edges.map((edge) => edge.id),\n ]);\n }\n\n function defaultCreateId(context: FlowCreateIdContext): string {\n const uuid = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n ?.randomUUID?.() ??\n `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;\n return `${context.kind}:${uuid}`;\n }\n\n function resolveId(\n explicitId: string | undefined,\n context: Omit<FlowCreateIdContext, 'attempt'>,\n ): string {\n const existing = entityIds();\n if (explicitId !== undefined) {\n if (!explicitId) throw new TypeError('Entity id must be a non-empty string.');\n if (existing.has(explicitId)) {\n throw new Error(`Entity id \"${explicitId}\" already exists.`);\n }\n return explicitId;\n }\n const createId = options.createId ?? defaultCreateId;\n for (let attempt = 0; attempt < 100; attempt++) {\n const id = createId({ ...context, attempt });\n if (typeof id !== 'string' || id.length === 0) {\n throw new TypeError('createId() must return a non-empty string.');\n }\n if (!existing.has(id)) return id;\n }\n throw new Error('createId() did not produce a unique id after 100 attempts.');\n }\n\n function deleteNodesFromGraph(graph: Graph, nodeIds: Set<string>): void {\n if (nodeIds.size === 0) return;\n const strategy = configuration.store.onDeleteNodes ?? 'cascade';\n if (typeof strategy === 'function') {\n const next = strategy(graph, nodeIds);\n graph.nodes = next.nodes as FlowNode<TNodeData>[];\n graph.edges = next.edges as FlowEdge<TEdgeData, TLabelData>[];\n return;\n }\n nodeIds = getNodeIdsWithDescendants(graph.nodes, nodeIds);\n graph.nodes = graph.nodes.filter((node) => !nodeIds.has(node.id));\n if (strategy === 'retarget') {\n graph.edges = graph.edges.flatMap((edge): FlowEdge<TEdgeData, TLabelData>[] => {\n const sourceDeleted = nodeIds.has(edge.sourceId);\n const targetDeleted = nodeIds.has(edge.targetId);\n if (sourceDeleted && targetDeleted) return [];\n if (sourceDeleted) {\n return [{ ...edge, sourceId: edge.targetId, sourcePort: null } as unknown as FlowEdge<TEdgeData, TLabelData>];\n }\n if (targetDeleted) {\n return [{ ...edge, targetId: edge.sourceId, targetPort: null } as unknown as FlowEdge<TEdgeData, TLabelData>];\n }\n return [edge];\n });\n } else {\n graph.edges = graph.edges.filter(\n (edge) => !nodeIds.has(edge.sourceId) && !nodeIds.has(edge.targetId),\n );\n }\n }\n\n function edgeInputWithDefaults(\n input: CreateEdgeInput<TEdgeData, TLabelData>,\n ): CreateEdgeInput<TEdgeData, TLabelData> {\n return {\n ...(defaultEdgeOptions as Partial<CreateEdgeInput<TEdgeData, TLabelData>> | undefined),\n ...input,\n } as CreateEdgeInput<TEdgeData, TLabelData>;\n }\n\n function validateGeometry(\n value: Point | Size | Rect,\n keys: readonly string[] = Object.keys(value),\n ): void {\n for (const key of keys) {\n const number = Reflect.get(value, key);\n if (\n !Number.isFinite(number) ||\n ((key === 'width' || key === 'height') && number < 0)\n ) {\n throw new TypeError(\n 'Geometry must contain finite coordinates and nonnegative sizes.',\n );\n }\n }\n }\n\n function settled(value: number, geometryOptions?: FlowGeometryOptions): number {\n return normalizeGeometryPosition(value, geometryOptions?.positionPrecision);\n }\n\n function sizeNode(node: FlowNode, size: Size): FlowNode {\n const { measured: _measured, ...authored } = node;\n return {\n ...authored,\n width: size.width,\n height: size.height,\n style: {\n ...node.style,\n customWidth: size.width,\n customHeight: size.height,\n },\n };\n }\n\n function measurementId(id: string): string {\n const ref = engine.getEntityRef(id);\n return ref?.kind === 'port' ? `${ref.nodeId}:${ref.portName}` : id;\n }\n\n const measurements: FlowMeasurementsApi = {\n update(batch) {\n for (const { rect } of batch)\n validateGeometry(rect, ['x', 'y', 'width', 'height']);\n store.trigger.updateMeasurements({\n measurements: batch.map(({ id, rect }) => {\n const ref = engine.getEntityRef(id);\n const origin =\n ref?.kind === 'port' ? engine.visualBounds(ref.nodeId) : undefined;\n return {\n id: measurementId(id),\n rect: { ...rect },\n ...(origin ? { origin: { x: origin.x, y: origin.y } } : {}),\n };\n }),\n derivedOnly: true,\n });\n },\n remove(ids) {\n store.trigger.removeMeasurements({\n ids: ids.map(measurementId),\n derivedOnly: true,\n });\n },\n get(id) {\n const rect = store\n .getSnapshot()\n .context.measurements.get(measurementId(id));\n return rect ? { ...rect } : undefined;\n },\n };\n\n function createNodeApi(): FlowNodesApi<TNodeData> {\n return {\n move: (id, position, geometryOptions) => {\n validateGeometry(position, ['x', 'y']);\n assertCommandAllowed('move', { id });\n return mutateGraph((graph) => {\n const node = graph.nodes.find((candidate) => candidate.id === id);\n if (!node) throw new Error(`Node \"${id}\" does not exist.`);\n const context = store.getSnapshot().context;\n const grid = context.snapToGrid ? context.snapGrid : null;\n const x = settled(\n grid ? Math.round(position.x / grid[0]) * grid[0] : position.x,\n geometryOptions,\n );\n const y = settled(\n grid ? Math.round(position.y / grid[1]) * grid[1] : position.y,\n geometryOptions,\n );\n const plan = planNodeMovement(\n { ...context, graph, selection: new Set([id]) },\n x - node.x - (node.dx ?? 0),\n y - node.y - (node.dy ?? 0),\n );\n if (plan) {\n for (const [index, delta] of plan.nodeDeltasByIndex) {\n const moved = graph.nodes[index];\n moved.x = settled(\n moved.x + (moved.dx ?? 0) + delta.x,\n geometryOptions,\n );\n moved.y = settled(\n moved.y + (moved.dy ?? 0) + delta.y,\n geometryOptions,\n );\n moved.dx = 0;\n moved.dy = 0;\n }\n for (const [index, delta] of plan.edgeDeltasByIndex) {\n const edge = graph.edges[index];\n edge.waypoints = edge.waypoints?.map((point) => ({\n x: point.x + delta.x,\n y: point.y + delta.y,\n }));\n }\n for (const [index, delta] of plan.labelDeltasByIndex) {\n const label = graph.edges[index].label;\n if (label) {\n label.x += delta.x;\n label.y += delta.y;\n }\n }\n }\n return node;\n }, geometryOptions);\n },\n resize: (id, bounds, geometryOptions) => {\n validateGeometry(bounds, ['x', 'y', 'width', 'height']);\n assertCommandAllowed('resize', { id });\n return createNodeApi().update(\n id,\n (node) => {\n const moving = clampResizeMovingPoint(\n node,\n 'bottom-right',\n { x: 0, y: 0 },\n { x: bounds.width, y: bounds.height },\n );\n return {\n ...sizeNode(node, { width: moving.x, height: moving.y }),\n x: settled(bounds.x, geometryOptions),\n y: settled(bounds.y, geometryOptions),\n dx: 0,\n dy: 0,\n };\n },\n geometryOptions,\n );\n },\n setContentSize: (id, size, geometryOptions) => {\n validateGeometry(size, ['width', 'height']);\n if (\n store.getSnapshot().context.mode === 'readonly' ||\n policyValue('canEdit') === false\n ) {\n throw new Error('Flow content sizing is not allowed: readonly.');\n }\n const position = geometryOptions?.position;\n if (position) validateGeometry(position, ['x', 'y']);\n return createNodeApi().update(\n id,\n (node) => ({\n ...sizeNode(node, size),\n ...(position\n ? {\n x: settled(position.x, geometryOptions),\n y: settled(position.y, geometryOptions),\n dx: 0,\n dy: 0,\n }\n : {}),\n }),\n geometryOptions,\n );\n },\n create: (input, transactionOptions) => {\n assertCommandAllowed('create');\n const id = resolveId(input.id, { kind: 'node', reason: 'create' });\n const node = createNode({ ...input, id } as Parameters<\n typeof createNode<TNodeData>\n >[0]);\n mutateGraph((graph) => graph.nodes.push(node), transactionOptions);\n return node;\n },\n delete: (id, transactionOptions) => {\n if (!currentGraph().nodes.some((node) => node.id === id)) return false;\n assertCommandAllowed('delete', { id });\n mutateGraph(\n (graph) => deleteNodesFromGraph(graph, new Set([id])),\n transactionOptions,\n );\n return true;\n },\n update: (id, patchOrUpdater, transactionOptions) => {\n let updated!: FlowNode<TNodeData>;\n mutateGraph((graph) => {\n const index = graph.nodes.findIndex((node) => node.id === id);\n if (index < 0) throw new Error(`Node \"${id}\" does not exist.`);\n const current = graph.nodes[index];\n updated = (\n typeof patchOrUpdater === 'function'\n ? patchOrUpdater(current)\n : { ...current, ...patchOrUpdater }\n ) as FlowNode<TNodeData>;\n if (updated.id !== id)\n throw new Error('Node update cannot change its id.');\n graph.nodes[index] = updated;\n }, transactionOptions);\n return updated;\n },\n setData: (id, data, transactionOptions) => {\n return createNodeApi().update(\n id,\n (node) => {\n const nextData =\n typeof data === 'function'\n ? data(node.data, node as FlowNode<TNodeData>)\n : ({ ...(node.data as object), ...data } as TNodeData);\n return { ...node, data: nextData };\n },\n transactionOptions,\n );\n },\n reparent: (id, parentId, transactionOptions) => {\n assertCommandAllowed('reparent', { id });\n return createNodeApi().update(\n id,\n (node) => ({ ...node, parentId }),\n transactionOptions,\n );\n },\n collapse: (id, transactionOptions) => {\n store.trigger.collapseNode({ id, ...transactionOptions });\n },\n expand: (id, transactionOptions) => {\n store.trigger.expandNode({ id, ...transactionOptions });\n },\n };\n }\n\n function createEdgeApi(): FlowEdgesApi<TEdgeData, TLabelData> {\n return {\n create: (input, transactionOptions) => {\n assertCommandAllowed('create');\n const withDefaults = edgeInputWithDefaults(input);\n const id = resolveId(withDefaults.id, { kind: 'edge', reason: 'create' });\n const edge = createEdge({\n ...withDefaults,\n id,\n } as Parameters<typeof createEdge<TEdgeData, TLabelData>>[0]);\n mutateGraph((graph) => graph.edges.push(edge), transactionOptions);\n return edge;\n },\n delete: (id, transactionOptions) => {\n if (!currentGraph().edges.some((edge) => edge.id === id)) return false;\n assertCommandAllowed('delete', { id });\n mutateGraph((graph) => {\n graph.edges = graph.edges.filter((edge) => edge.id !== id);\n }, transactionOptions);\n return true;\n },\n update: (id, patchOrUpdater, transactionOptions) => {\n let updated!: FlowEdge<TEdgeData, TLabelData>;\n mutateGraph((graph) => {\n const index = graph.edges.findIndex((edge) => edge.id === id);\n if (index < 0) throw new Error(`Edge \"${id}\" does not exist.`);\n const current = graph.edges[index];\n updated = (\n typeof patchOrUpdater === 'function'\n ? patchOrUpdater(current)\n : { ...current, ...patchOrUpdater }\n ) as FlowEdge<TEdgeData, TLabelData>;\n if (updated.id !== id)\n throw new Error('Edge update cannot change its id.');\n graph.edges[index] = updated;\n }, transactionOptions);\n return updated;\n },\n setData: (id, data, transactionOptions) => {\n return createEdgeApi().update(\n id,\n (edge) => {\n const nextData =\n typeof data === 'function'\n ? data(edge.data, edge as FlowEdge<TEdgeData, TLabelData>)\n : ({ ...(edge.data as object), ...data } as TEdgeData);\n return { ...edge, data: nextData };\n },\n transactionOptions,\n );\n },\n reconnect: (edgeId, patch, transactionOptions) => {\n assertCommandAllowed('reconnect', { id: edgeId });\n const edge = currentGraph().edges.find(\n (candidate) => candidate.id === edgeId,\n );\n if (!edge) throw new Error(`Edge \"${edgeId}\" does not exist.`);\n const proposed = {\n ...edge,\n sourceId: patch.newSourceId ?? edge.sourceId,\n targetId: patch.newTargetId ?? edge.targetId,\n sourcePort:\n patch.newSourcePort === undefined\n ? edge.sourcePort\n : patch.newSourcePort,\n targetPort:\n patch.newTargetPort === undefined\n ? edge.targetPort\n : patch.newTargetPort,\n };\n return createEdgeApi().update(edgeId, proposed, transactionOptions);\n },\n };\n }\n\n const nodes = createNodeApi();\n const edges = createEdgeApi();\n const view: FlowViewApi<TNodeData, TEdgeData, TLabelData> = {\n getScope: currentViewScope,\n setScope: (scope, viewOptions = {}) => {\n const validated = validateViewScope(scope);\n const selectionPolicy = viewOptions.selection ?? 'prune';\n if (selectionPolicy !== 'prune' && selectionPolicy !== 'clear') {\n throw new TypeError(\n 'flow.view.setScope(): selection must be \"prune\" or \"clear\".',\n );\n }\n const entities = getViewEntities({}, validated);\n store.trigger.setViewScope({\n parentNodeId: validated.parentId,\n depth: validated.depth,\n selection: selectionPolicy,\n visibleEntityIds: [\n ...entities.nodes.map((node) => node.id),\n ...entities.edges.map((edge) => edge.id),\n ],\n });\n },\n getEntities: getViewEntities,\n getBoundaryEndpoints: (edgeId) =>\n getViewEntities().boundaryEndpoints.find(\n (endpoints) => endpoints.edgeId === edgeId,\n ),\n contains: (id, viewOptions) => {\n const entities = getViewEntities(viewOptions);\n return (\n entities.nodes.some((node) => node.id === id) ||\n entities.edges.some((edge) => edge.id === id)\n );\n },\n };\n\n function selectedNodes(): FlowNode<TNodeData>[] {\n const selected = store.getSnapshot().context.selection;\n return currentGraph().nodes.filter((node) => selected.has(node.id));\n }\n\n function duplicateSelection(\n duplicateOptions: { offset?: Point } = {},\n ): FlowSelectionDuplicateResult | null {\n const selected = store.getSnapshot().context.selection;\n const selectedNodeList = selectedNodes();\n if (\n selectedNodeList.length === 0 ||\n !check('copy').allowed ||\n !check('create').allowed\n ) {\n return null;\n }\n const offset = duplicateOptions.offset ?? { x: 24, y: 24 };\n if (!Number.isFinite(offset.x) || !Number.isFinite(offset.y)) {\n throw new RangeError('selection.duplicate(): offset must have finite x/y.');\n }\n const graph = currentGraph();\n const extracted = extractFlowContent(graph, selected, options.dataSchemas);\n if (!extracted || extracted.nodes.length === 0) return null;\n const inserted = insertFlowContent(graph, extracted, {\n preservePosition: true,\n schemas: options.dataSchemas,\n createId: (kind, sourceId, attempt) =>\n (options.createId ?? defaultCreateId)({\n kind,\n reason: 'content',\n sourceId,\n attempt,\n }),\n });\n const copiedNodeIds = new Set(extracted.nodes.map((node) => node.id));\n const originalNodes = new Map(graph.nodes.map((node) => [node.id, node]));\n const clonedNodeIds = new Set(inserted.nodeIds);\n for (const [sourceId, cloneId] of inserted.idMap) {\n if (!copiedNodeIds.has(sourceId)) continue;\n const clone = inserted.graph.nodes.find((node) => node.id === cloneId);\n const original = originalNodes.get(sourceId);\n if (!clone || !original) continue;\n if (original.parentId && !copiedNodeIds.has(original.parentId)) {\n clone.parentId = original.parentId;\n }\n }\n for (const node of inserted.graph.nodes) {\n if (!clonedNodeIds.has(node.id)) continue;\n node.x += offset.x;\n node.y += offset.y;\n }\n const clonedEdgeIds = new Set(inserted.edgeIds);\n for (const edge of inserted.graph.edges) {\n if (!clonedEdgeIds.has(edge.id)) continue;\n edge.x += offset.x;\n edge.y += offset.y;\n if (edge.label) {\n edge.label.x += offset.x;\n edge.label.y += offset.y;\n }\n if (edge.waypoints) {\n edge.waypoints = edge.waypoints.map((point) => ({\n x: point.x + offset.x,\n y: point.y + offset.y,\n }));\n }\n if (offset.x !== 0 || offset.y !== 0) {\n invalidateAuthoritativeEdgePath(edge);\n }\n }\n const changeSet = commitGraph(inserted.graph, {\n origin: 'selection.duplicate',\n });\n if (!changeSet) return null;\n selection.set([...inserted.nodeIds, ...inserted.edgeIds]);\n return {\n nodeIds: inserted.nodeIds,\n edgeIds: inserted.edgeIds,\n idMap: inserted.idMap,\n };\n }\n\n function alignSelection(alignment: FlowSelectionAlignment): boolean {\n const eligible = selectedNodes();\n if (\n eligible.length < 2 ||\n eligible.some((node) => !check('move', { id: node.id }).allowed)\n ) {\n return false;\n }\n const items = eligible.map((node) => ({\n node,\n bounds: engine.getBounds(node.id)!,\n }));\n const minX = Math.min(...items.map(({ bounds }) => bounds.x));\n const maxX = Math.max(...items.map(({ bounds }) => bounds.x + bounds.width));\n const minY = Math.min(...items.map(({ bounds }) => bounds.y));\n const maxY = Math.max(...items.map(({ bounds }) => bounds.y + bounds.height));\n const centerX = (minX + maxX) / 2;\n const centerY = (minY + maxY) / 2;\n const deltas = new Map<string, Point>();\n for (const { node, bounds } of items) {\n const next = { x: bounds.x, y: bounds.y };\n switch (alignment) {\n case 'left':\n next.x = minX;\n break;\n case 'right':\n next.x = maxX - bounds.width;\n break;\n case 'top':\n next.y = minY;\n break;\n case 'bottom':\n next.y = maxY - bounds.height;\n break;\n case 'center-x':\n next.x = centerX - bounds.width / 2;\n break;\n case 'center-y':\n next.y = centerY - bounds.height / 2;\n break;\n default:\n throw new TypeError(`Unknown selection alignment: ${String(alignment)}`);\n }\n deltas.set(node.id, { x: next.x - bounds.x, y: next.y - bounds.y });\n }\n if ([...deltas.values()].every(({ x, y }) => x === 0 && y === 0)) {\n return false;\n }\n mutateGraph((next) => {\n for (const node of next.nodes) {\n const delta = deltas.get(node.id);\n if (!delta) continue;\n node.x += delta.x;\n node.y += delta.y;\n }\n }, { origin: `selection.align.${alignment}` });\n return true;\n }\n\n function distributeSelection(\n distribution: FlowSelectionDistribution,\n ): boolean {\n const eligible = selectedNodes();\n if (\n eligible.length < 3 ||\n eligible.some((node) => !check('move', { id: node.id }).allowed)\n ) {\n return false;\n }\n const horizontal = distribution === 'horizontal';\n if (!horizontal && distribution !== 'vertical') {\n throw new TypeError(\n `Unknown selection distribution: ${String(distribution)}`,\n );\n }\n const items = eligible\n .map((node) => ({ node, bounds: engine.getBounds(node.id)! }))\n .sort((a, b) => {\n const primary = horizontal\n ? a.bounds.x - b.bounds.x\n : a.bounds.y - b.bounds.y;\n if (primary !== 0) return primary;\n const secondary = horizontal\n ? a.bounds.y - b.bounds.y\n : a.bounds.x - b.bounds.x;\n return secondary !== 0\n ? secondary\n : a.node.id.localeCompare(b.node.id);\n });\n const first = items[0]!;\n const last = items[items.length - 1]!;\n const totalSize = items.reduce(\n (sum, item) =>\n sum + (horizontal ? item.bounds.width : item.bounds.height),\n 0,\n );\n const start = horizontal ? first.bounds.x : first.bounds.y;\n const end = horizontal\n ? last.bounds.x + last.bounds.width\n : last.bounds.y + last.bounds.height;\n const gap = (end - start - totalSize) / (items.length - 1);\n const deltas = new Map<string, Point>();\n let cursor = start;\n for (const [index, { node, bounds }] of items.entries()) {\n const target =\n index === 0\n ? start\n : index === items.length - 1\n ? horizontal\n ? bounds.x\n : bounds.y\n : cursor;\n deltas.set(node.id, {\n x: horizontal ? target - bounds.x : 0,\n y: horizontal ? 0 : target - bounds.y,\n });\n cursor += (horizontal ? bounds.width : bounds.height) + gap;\n }\n if ([...deltas.values()].every(({ x, y }) => x === 0 && y === 0)) {\n return false;\n }\n mutateGraph((next) => {\n for (const node of next.nodes) {\n const delta = deltas.get(node.id);\n if (!delta) continue;\n node.x += delta.x;\n node.y += delta.y;\n }\n }, { origin: `selection.distribute.${distribution}` });\n return true;\n }\n\n const selection: FlowSelectionApi = {\n set: (ids, mode = 'single') => store.trigger.select({ ids, mode }),\n all: (selectOptions) => {\n const entities = getViewEntities(selectOptions);\n selection.set(\n [...entities.nodes.map((node) => node.id), ...entities.edges.map((edge) => edge.id)],\n );\n },\n clear: () => store.trigger.clearSelection(),\n delete: () => {\n const selected = store.getSnapshot().context.selection;\n const graph = currentGraph();\n const nodeIds = new Set(\n graph.nodes.filter((node) => selected.has(node.id)).map((node) => node.id),\n );\n const edgeIds = new Set(\n graph.edges.filter((edge) => selected.has(edge.id)).map((edge) => edge.id),\n );\n if (nodeIds.size === 0 && edgeIds.size === 0) return false;\n assertCommandAllowed('delete');\n mutateGraph((next) => {\n deleteNodesFromGraph(next, nodeIds);\n next.edges = next.edges.filter((edge) => !edgeIds.has(edge.id));\n }, { origin: 'selection.delete' });\n return true;\n },\n duplicate: duplicateSelection,\n align: alignSelection,\n distribute: distributeSelection,\n };\n const viewport: FlowViewportApi = {\n set: (next, animationOptions) =>\n setViewportTarget(next, animationOptions),\n panBy: (point, animationOptions) =>\n setViewportTarget(\n constrainedViewport(\n viewportPanBy(store.getSnapshot().context.viewport, point),\n ),\n animationOptions,\n ),\n zoomTo: (zoom, center, animationOptions) => {\n const context = store.getSnapshot().context;\n const clamped = Math.min(Math.max(zoom, context.minZoom), context.maxZoom);\n return setViewportTarget(\n constrainedViewport(\n viewportZoomTo(\n context.viewport,\n clamped,\n center ?? frameCenter(),\n ),\n ),\n animationOptions,\n );\n },\n zoomBy: (factor, center, animationOptions) => {\n const context = store.getSnapshot().context;\n const pivot = center ?? frameCenter();\n const clamped = Math.min(\n Math.max(context.viewport.zoom * factor, context.minZoom),\n context.maxZoom,\n );\n return setViewportTarget(\n constrainedViewport(viewportZoomTo(context.viewport, clamped, pivot)),\n animationOptions,\n );\n },\n fit: (fitOptions) => {\n return setViewportTarget(fitViewportTarget(fitOptions), fitOptions);\n },\n fitBounds: (bounds, fitOptions) => {\n const context = store.getSnapshot().context;\n if (context.viewportSize.width === 0 || context.viewportSize.height === 0) {\n cancelViewportAnimation();\n return resolvedViewportControls(false);\n }\n if (bounds.width === 0 && bounds.height === 0) {\n cancelViewportAnimation();\n return resolvedViewportControls(false);\n }\n const target = viewportForBounds(bounds, context.viewportSize, {\n ...fitOptions,\n frame: getFitFrame(fitOptions?.frame),\n });\n return setViewportTarget(target, fitOptions);\n },\n centerOn: (point, centerOptions = {}) => {\n const context = store.getSnapshot().context;\n const {\n zoom = context.viewport.zoom,\n frame,\n ...animationOptions\n } = centerOptions;\n const clamped = Math.min(Math.max(zoom, context.minZoom), context.maxZoom);\n return setViewportTarget(\n viewportCenteredOn(\n point,\n context.viewportSize,\n clamped,\n getFitFrame(frame),\n ),\n animationOptions,\n );\n },\n getFitFrame,\n setFitFrame: (frame, options) => {\n store.trigger.setFitFrame({\n frame: frame ? validateFitFrame(frame) : null,\n preserveCenter: options?.preserveCenter,\n });\n },\n registerFitExclusion: (exclusion) => {\n if (!exclusion || typeof exclusion.getRect !== 'function') {\n throw new TypeError('Fit exclusion must provide getRect().');\n }\n fitExclusions.add(exclusion);\n return () => fitExclusions.delete(exclusion);\n },\n };\n const layout: FlowLayoutApi<TNodeData, TEdgeData, TLabelData> = {\n run: runLayout,\n apply: applyLayout,\n request: (algorithm) => store.trigger.requestLayout({ algorithm }),\n };\n const history: FlowHistoryApi = {\n undo: () => {\n assertCommandAllowed('undo');\n store.trigger.undo();\n },\n redo: () => {\n assertCommandAllowed('redo');\n store.trigger.redo();\n },\n canUndo: () => store.can.undo(),\n canRedo: () => store.can.redo(),\n };\n const highlights: FlowHighlightsApi = {\n set: (kind, entries) => store.trigger.setHighlights({ kind, entries }),\n add: (kind, entries) => store.trigger.addHighlights({ kind, entries }),\n remove: (kind, ids) => store.trigger.removeHighlights({ kind, ids }),\n clear: (kind) => store.trigger.clearHighlights(kind ? { kind } : undefined),\n };\n const projectionApi: FlowProjectionsApi = {\n get: getProjections,\n set: setProjections,\n add: (projection) => {\n setProjections([...projections, projection]);\n },\n remove: (id) => {\n setProjections(\n projections.filter((entry) => entry.projection.id !== id),\n );\n },\n clear: () => {\n setProjections([]);\n },\n subscribe: (listener) => {\n projectionListeners.add(listener);\n return () => {\n projectionListeners.delete(listener);\n };\n },\n getAttrs: () =>\n composeGraphProjectionAttrs({\n graph: store.getSnapshot().context.graph,\n projections,\n }),\n };\n\n const connections: FlowConnectionsApi = {\n get: ({ nodeId, port, direction = 'both' }) => {\n const edges = currentGraph().edges;\n const adjacency = indexEdgeAdjacency(edges);\n const candidates = direction === 'in'\n ? adjacency.byTarget.get(nodeId)\n : direction === 'out'\n ? adjacency.bySource.get(nodeId)\n : adjacency.byNode.get(nodeId);\n return (candidates ?? []).flatMap((edge) => {\n const sourceMatches =\n direction !== 'in' &&\n edge.sourceId === nodeId &&\n (port === undefined || (edge.sourcePort ?? null) === port);\n const targetMatches =\n direction !== 'out' &&\n edge.targetId === nodeId &&\n (port === undefined || (edge.targetPort ?? null) === port);\n if (!sourceMatches && !targetMatches) return [];\n return [{\n edge,\n source: { nodeId: edge.sourceId, port: edge.sourcePort ?? null },\n target: { nodeId: edge.targetId, port: edge.targetPort ?? null },\n }];\n });\n },\n };\n\n function policyValue(name: keyof FlowPolicies): boolean | undefined {\n const profile = configuration.store.profile;\n if (!profile) return undefined;\n const value = {\n ...profile.policies,\n ...profile.modes[store.getSnapshot().context.mode]?.policies,\n }[name];\n return typeof value === 'boolean' ? value : undefined;\n }\n\n function check(command: FlowCapabilityCommand, input?: { id?: string }): FlowCapabilityResult {\n const editCommands: readonly FlowCapabilityCommand[] = [\n 'edit', 'create', 'move', 'resize', 'connect', 'reconnect', 'reparent',\n 'delete', 'cut', 'paste', 'undo', 'redo',\n ];\n if (\n editCommands.includes(command) &&\n (store.getSnapshot().context.mode === 'readonly' || policyValue('canEdit') === false)\n ) {\n return { allowed: false, reason: { code: 'readonly', command } };\n }\n const policyNames: Partial<Record<FlowCapabilityCommand, readonly (keyof FlowPolicies)[]>> = {\n create: ['canCreate'],\n move: ['canMove'],\n resize: ['canResize'],\n connect: ['canConnect'],\n reconnect: ['canConnect', 'canReconnect'],\n reparent: ['canReparent'],\n delete: ['canDelete'],\n cut: ['canCopy', 'canDelete'],\n paste: ['canPaste'],\n undo: ['canUndo'],\n redo: ['canRedo'],\n copy: ['canCopy'],\n export: ['canExport'],\n select: ['canSelect'],\n pan: ['canPan'],\n zoom: ['canZoom'],\n };\n if (policyNames[command]?.some((name) => policyValue(name) === false)) {\n return { allowed: false, reason: { code: 'policy', command } };\n }\n if (command === 'undo' && !history.canUndo()) {\n return { allowed: false, reason: { code: 'history', command } };\n }\n if (command === 'redo' && !history.canRedo()) {\n return { allowed: false, reason: { code: 'history', command } };\n }\n const ids = input?.id\n ? [input.id]\n : [...store.getSnapshot().context.selection];\n if (['delete', 'cut', 'copy'].includes(command) && ids.length === 0) {\n return { allowed: false, reason: { code: 'empty', command } };\n }\n const flag =\n command === 'delete' || command === 'cut'\n ? 'deletable'\n : command === 'move'\n ? 'draggable'\n : command === 'resize'\n ? 'resizable'\n : command === 'connect' || command === 'reconnect'\n ? 'connectable'\n : command === 'select'\n ? 'selectable'\n : null;\n if (\n flag &&\n ids.some((id) => {\n const entity = currentGraph().nodes.find((node) => node.id === id) ?? engine.getEntity(id);\n return entity && !engine.resolveEntityConfig(entity)[flag];\n })\n ) {\n return { allowed: false, reason: { code: 'entity', command } };\n }\n return { allowed: true };\n }\n\n function assertCommandAllowed(\n command: FlowCapabilityCommand,\n input?: { id?: string },\n ): void {\n const result = check(command, input);\n if (!result.allowed) {\n throw new Error(`Flow command \"${command}\" is not allowed: ${result.reason.code}.`);\n }\n }\n\n const content: FlowContentApi<TNodeData, TEdgeData, TLabelData> = {\n extract: (targets = store.getSnapshot().context.selection) =>\n extractFlowContent(currentGraph(), targets, options.dataSchemas),\n insert: (value, insertOptions = {}) => {\n if (!check('paste').allowed) {\n return {\n ok: false,\n error: new FlowGraphValidationError([\n { code: 'capability_denied', path: '$', message: 'Paste is not allowed.' },\n ]),\n };\n }\n try {\n const inserted = insertFlowContent(currentGraph(), value, {\n ...insertOptions,\n schemas: options.dataSchemas,\n createId: (kind, sourceId, attempt) =>\n (options.createId ?? defaultCreateId)({\n kind,\n reason: 'content',\n sourceId,\n attempt,\n }),\n });\n if (inserted.nodeIds.length === 0 && inserted.edgeIds.length === 0) {\n throw new FlowGraphValidationError([\n { code: 'empty_content', path: '$', message: 'Flow content is empty.' },\n ]);\n }\n const changeSet = commitGraph(inserted.graph, { origin: 'content.insert' });\n if (!changeSet) throw new Error('Content insertion produced no graph change.');\n selection.set([...inserted.nodeIds, ...inserted.edgeIds], 'multi');\n return {\n ok: true,\n value: {\n nodeIds: inserted.nodeIds,\n edgeIds: inserted.edgeIds,\n idMap: inserted.idMap,\n changeSet,\n },\n };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof FlowGraphValidationError\n ? error\n : new FlowGraphValidationError([\n { code: 'content_insert_failed', path: '$', message: String(error) },\n ]),\n };\n }\n },\n };\n\n function assertTransactionOptions(next?: FlowTransactionOptions) {\n if (next?.history !== undefined && next.history !== 'record' && next.history !== 'ignore') {\n throw new TypeError('Transaction history must be \"record\" or \"ignore\".');\n }\n if (!activeTransaction || !next) return;\n const outer = activeTransaction.options;\n for (const key of ['history', 'origin', 'transactionId'] as const) {\n const inherited = key === 'history' ? outer?.history ?? 'record' : outer?.[key];\n if (next[key] !== undefined && next[key] !== inherited) {\n throw new Error(`Nested transaction cannot override ${key}.`);\n }\n }\n }\n\n function transaction<TValue>(\n callback: (\n draft: FlowTransactionDraft<TNodeData, TEdgeData, TLabelData>,\n ) => TValue,\n transactionOptions?: FlowTransactionOptions,\n ): {\n value: TValue;\n changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null;\n } {\n assertTransactionOptions(transactionOptions);\n const nested = activeTransaction !== null;\n const previousGraph = nested\n ? validateAndCloneGraph(activeTransaction!.graph, options.dataSchemas)\n : null;\n const previousAuthoredEdgeRouteIds = nested\n ? new Set(activeTransaction!.authoredEdgeRouteIds)\n : null;\n const previousRemovedEntityIds = nested ? new Set(activeTransaction!.removedEntityIds) : null;\n if (!nested) {\n activeTransaction = {\n graph: validateAndCloneGraph(currentGraph(), options.dataSchemas),\n options: transactionOptions,\n authoredEdgeRouteIds: new Set(),\n removedEntityIds: new Set(),\n };\n }\n const transactionState = activeTransaction!;\n let draftOpen = true;\n const assertDraftOpen = () => {\n if (!draftOpen || activeTransaction !== transactionState) {\n throw new Error('Flow transaction draft is closed.');\n }\n };\n const { collapse: _collapse, expand: _expand, ...draftNodes } = nodes;\n const draft: FlowTransactionDraft<TNodeData, TEdgeData, TLabelData> = {\n getNode: (id) => {\n assertDraftOpen();\n const node = currentGraph().nodes.find((candidate) => candidate.id === id);\n return node ? cloneJsonSafe(node) : undefined;\n },\n getEdge: (id) => {\n assertDraftOpen();\n const edge = currentGraph().edges.find((candidate) => candidate.id === id);\n return edge ? cloneJsonSafe(edge) : undefined;\n },\n getNodeBounds: (id) => {\n assertDraftOpen();\n const node = currentGraph().nodes.find((candidate) => candidate.id === id);\n return node ? resolvedBounds(node) : undefined;\n },\n nodes: scopedTransactionApi(draftNodes, assertDraftOpen),\n edges: scopedTransactionApi(edges, assertDraftOpen),\n };\n try {\n const value = callback(draft);\n draftOpen = false;\n if (value && typeof (value as { then?: unknown }).then === 'function') {\n throw new TypeError('flow.transaction() callback must be synchronous.');\n }\n if (nested) return { value, changeSet: null };\n const next = activeTransaction!.graph;\n const surviving = new Set([...next.nodes, ...next.edges].map(entity => entity.id));\n const resetMeasurementIds = [...activeTransaction!.removedEntityIds].filter(id => surviving.has(id));\n activeTransaction = null;\n return { value, changeSet: commitGraph(next, transactionOptions, undefined, undefined, resetMeasurementIds) };\n } catch (error) {\n draftOpen = false;\n if (nested) {\n activeTransaction!.graph = previousGraph!;\n activeTransaction!.authoredEdgeRouteIds = previousAuthoredEdgeRouteIds!;\n activeTransaction!.removedEntityIds = previousRemovedEntityIds!;\n } else {\n activeTransaction = null;\n }\n throw error;\n }\n }\n\n function applyChangeSet(\n changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>,\n applyOptions: FlowTransactionOptions & { strict?: boolean } = {},\n ): FlowResult<FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null> {\n const result = applyFlowPatches(currentGraph(), changeSet.forward, {\n strict: applyOptions.strict ?? true,\n schemas: options.dataSchemas,\n });\n if (!result.ok) return result;\n try {\n return {\n ok: true,\n value: commitGraph(result.value, {\n origin: applyOptions.origin ?? 'applyChangeSet',\n transactionId: applyOptions.transactionId,\n history: applyOptions.history,\n }),\n };\n } catch (error) {\n return {\n ok: false,\n error:\n error instanceof FlowGraphValidationError\n ? error\n : new FlowGraphValidationError([\n { code: 'change_set_error', path: '$', message: String(error) },\n ]),\n };\n }\n }\n\n const on = ((type: string, listener: (event: unknown) => void) => {\n if (type === 'destroy') {\n const destroyListener = listener as (event: { type: 'destroy' }) => void;\n if (!destroyed) destroyListeners.add(destroyListener);\n return { unsubscribe: () => { destroyListeners.delete(destroyListener); } };\n }\n if (type === 'commit') {\n commitListeners.add(listener as (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void);\n return {\n unsubscribe: () => {\n commitListeners.delete(\n listener as (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void,\n );\n },\n };\n }\n return store.on(type as Parameters<FlowStore['on']>[0], listener as never);\n }) as FlowController<TNodeData, TEdgeData, TLabelData>['on'];\n\n const subscribe = ((\n selectorOrListener: ((context: FlowStoreContext) => unknown),\n maybeListener?: (selected: unknown, previous: unknown) => void,\n subscribeOptions?: {\n equals?: (a: unknown, b: unknown) => boolean;\n emitInitial?: boolean;\n keys?: readonly (keyof FlowStoreContext)[];\n },\n ) => {\n if (!maybeListener) {\n const subscription = store.subscribe((snapshot) => {\n selectorOrListener(snapshot.context);\n });\n return () => subscription.unsubscribe();\n }\n const selector = selectorOrListener;\n const listener = maybeListener;\n const equals = subscribeOptions?.equals ?? Object.is;\n let previousContext = store.getSnapshot().context;\n let previous = selector(previousContext);\n if (subscribeOptions?.emitInitial) listener(previous, previous);\n const subscription = store.subscribe((snapshot) => {\n const context = snapshot.context;\n const unchanged = subscribeOptions?.keys?.every((key) =>\n Object.is(context[key], previousContext[key]),\n );\n previousContext = context;\n if (unchanged) return;\n const selected = selector(context);\n if (equals(selected, previous)) return;\n const old = previous;\n previous = selected;\n listener(selected, old);\n });\n return () => subscription.unsubscribe();\n }) as FlowController<TNodeData, TEdgeData, TLabelData>['subscribe'];\n\n const controller: FlowController<TNodeData, TEdgeData, TLabelData> = {\n internals: { store, engine },\n beginExternalEdit: (editOptions) => {\n if (destroyed) throw new Error('Flow controller is destroyed.');\n return createFlowExternalEdit(controller, editOptions);\n },\n subscribeRender: (listener) => renderApi.subscribe(listener),\n on,\n destroy,\n\n getContext: engine.getContext,\n getSnapshot: engine.getContext,\n subscribe,\n configure,\n invalidateRoutes: engine.invalidateRoutes,\n getConfiguration: () => immutableConfiguration(configuration),\n toJSON,\n load,\n replaceGraph,\n transaction,\n applyChangeSet,\n\n getNode: engine.getNode as FlowController<\n TNodeData,\n TEdgeData,\n TLabelData\n >['getNode'],\n getEdge: engine.getEdge as FlowController<\n TNodeData,\n TEdgeData,\n TLabelData\n >['getEdge'],\n getEntity: engine.getEntity,\n getEntityRef: engine.getEntityRef,\n getAddressable: engine.getAddressable,\n getOwnerEntity: engine.getOwnerEntity as FlowController<\n TNodeData,\n TEdgeData,\n TLabelData\n >['getOwnerEntity'],\n getBounds: engine.getBounds,\n\n screenToCanvas: engine.screenToCanvas,\n canvasToScreen: engine.canvasToScreen,\n getAllEdgePaths: engine.getAllEdgePaths,\n getConnectionCandidate: engine.getConnectionCandidate,\n getGraphBounds: engine.getGraphBounds,\n getIncomers: engine.getIncomers,\n getOutgoers: engine.getOutgoers,\n getConnectedEdges: engine.getConnectedEdges,\n getNeighbors: engine.getNeighbors,\n getSelectionBounds: engine.getSelectionBounds,\n getRenderableEntities: engine.getRenderableEntities,\n getEntityOrder: engine.getEntityOrder,\n check,\n can: (command, input) => check(command, input).allowed,\n mode: {\n get: () => store.getSnapshot().context.mode,\n set: (mode) => store.trigger.setMode({ mode }),\n },\n\n nodes,\n measurements,\n edges,\n selection,\n view,\n viewport,\n layout,\n history,\n highlights,\n projections: projectionApi,\n connections,\n content,\n };\n const renderApi = createFlowRenderApi(controller);\n return controller;\n}\n\n/**\n * Parse a persisted Flow document and create a controller from it.\n *\n * Restores graph, collapsed nodes, and viewport after applying configured data\n * migrations. Throws `FlowGraphValidationError` for invalid documents.\n */\nexport function fromJSON<\n TNodeData = any,\n TEdgeData = any,\n TLabelData = any,\n>(\n data: unknown,\n options: Omit<CreateFlowOptions<TNodeData, TEdgeData, TLabelData>, 'graph'> = {},\n): FlowController<TNodeData, TEdgeData, TLabelData> {\n const parsed = parseFlowSerialized<TNodeData, TEdgeData, TLabelData>(\n data,\n options.dataSchemas,\n );\n const flow = createFlow<TNodeData, TEdgeData, TLabelData>({\n ...options,\n graph: parsed.graph,\n });\n flow.internals.store.trigger.setCollapsedNodes({\n ids: parsed.collapsedNodeIds ?? [],\n });\n // Hydration is synchronous even when public viewport commands inherit a\n // default animation. Callers must receive the restored viewport immediately.\n flow.internals.store.trigger.setViewport(parsed.viewport);\n return flow;\n}\n","import { createEdge, createNode } from './factories';\nimport type { ConnectionState, FlowEdge, FlowGraph, FlowNode, Point } from './types';\n\nexport const CONNECTION_PREVIEW_NODE_ID = 'flow:connection-preview-node';\nexport const CONNECTION_PREVIEW_EDGE_ID = 'flow:connection-preview-edge';\n\nexport type ConnectionPreviewData = {\n /** canConnect result for the hovered target (undefined over empty space). */\n isValid?: boolean;\n temp: { kind: 'connection-preview' };\n};\n\nexport type ConnectionPreviewGraphOptions = {\n nodeId?: string;\n edgeId?: string;\n nodeSize?: number;\n};\n\nexport function createConnectionPreviewGraph<\n TNodeData = any,\n TEdgeData = any,\n>(\n graph: FlowGraph<TNodeData, TEdgeData>,\n connection: ConnectionState | null,\n options: ConnectionPreviewGraphOptions = {},\n): FlowGraph<TNodeData | ConnectionPreviewData, TEdgeData | ConnectionPreviewData> {\n if (!connection?.active || connection.preview === false) {\n return graph as FlowGraph<TNodeData | ConnectionPreviewData, TEdgeData | ConnectionPreviewData>;\n }\n\n const nodeId = options.nodeId ?? CONNECTION_PREVIEW_NODE_ID;\n const edgeId = options.edgeId ?? CONNECTION_PREVIEW_EDGE_ID;\n const nodeSize = options.nodeSize ?? 2;\n const targetId = connection.targetId ?? nodeId;\n const nodes: FlowNode<TNodeData | ConnectionPreviewData>[] =\n connection.targetId\n ? [...graph.nodes]\n : [\n ...graph.nodes,\n createPreviewNode(nodeId, connection.pointerPosition, nodeSize),\n ];\n const edges: FlowEdge<TEdgeData | ConnectionPreviewData>[] = [\n ...graph.edges,\n createEdge<ConnectionPreviewData>({\n id: edgeId,\n sourceId: connection.sourceId,\n targetId,\n sourcePort: connection.sourcePort ?? undefined,\n targetPort: connection.targetPort ?? undefined,\n selectable: false,\n draggable: false,\n deletable: false,\n // Validity travels with the preview so renderers can color it\n // (e.g. red when the hovered target would reject the connection).\n data: { temp: { kind: 'connection-preview' }, isValid: connection.isValid },\n }),\n ];\n\n return {\n ...graph,\n nodes,\n edges,\n };\n}\n\nfunction createPreviewNode(\n id: string,\n point: Point,\n size: number,\n): FlowNode<ConnectionPreviewData> {\n return createNode<ConnectionPreviewData>({\n id,\n x: point.x - size / 2,\n y: point.y - size / 2,\n width: size,\n height: size,\n selectable: false,\n draggable: false,\n deletable: false,\n data: { temp: { kind: 'connection-preview' } },\n });\n}\n","import type { Rect } from './types';\n\n// Toolbar placement — pure math, renderer-agnostic (Stately-editor\n// semantics). Anchors come from `engine.getToolbarAnchor` (a node's bounds,\n// an edge's label — or an assumed 1×1 label at the path midpoint — or the\n// union over a selection); this function decides where a measured toolbar\n// box sits: preferring above the anchor, flipping below when it would clip,\n// and always clamping inside the viewport.\n\nexport type ToolbarPlacementInput = {\n /** Anchor rect in container-relative screen px (canvas rect × viewport). */\n anchor: Rect;\n /** Measured toolbar size (border box). */\n toolbarWidth: number;\n toolbarHeight: number;\n /** Container size in px. */\n viewportWidth: number;\n viewportHeight: number;\n /** Gap between anchor and toolbar (default 10). */\n offset?: number;\n /** Minimum gap from container edges (default 8). */\n padding?: number;\n};\n\nexport type ToolbarPlacement = {\n /** Top-left of the toolbar box, container-relative px. */\n left: number;\n top: number;\n side: 'top' | 'bottom';\n};\n\nexport function getToolbarPlacement(\n input: ToolbarPlacementInput,\n): ToolbarPlacement {\n const offset = input.offset ?? 10;\n const padding = input.padding ?? 8;\n const { toolbarWidth: tw, toolbarHeight: th, anchor } = input;\n\n const topPlacementTop = anchor.y - offset - th;\n const bottomPlacementTop = anchor.y + anchor.height + offset;\n const topFits = topPlacementTop >= padding;\n const bottomFits = bottomPlacementTop + th <= input.viewportHeight - padding;\n\n let side: 'top' | 'bottom';\n if (topFits) side = 'top';\n else if (bottomFits) side = 'bottom';\n else {\n const topRoom = anchor.y;\n const bottomRoom = input.viewportHeight - (anchor.y + anchor.height);\n side = topRoom >= bottomRoom ? 'top' : 'bottom';\n }\n\n let top = side === 'top' ? topPlacementTop : bottomPlacementTop;\n const maxTop = Math.max(input.viewportHeight - padding - th, padding);\n top = Math.min(Math.max(top, padding), maxTop);\n\n let left = anchor.x + anchor.width / 2 - tw / 2;\n const maxLeft = Math.max(input.viewportWidth - padding - tw, padding);\n left = Math.min(Math.max(left, padding), maxLeft);\n\n return { left, top, side };\n}\n","import type { Point, Rect, Size, Viewport } from './types';\nimport { getVisibleBounds } from './viewport';\nimport { unionRect } from './spatial';\n\n// Minimap projection — pure math, renderer-agnostic.\n//\n// Maps canvas (graph/world) space onto a fixed-size minimap surface:\n// content bounds plus the currently visible area, padded and centered. A\n// renderer (React, vanilla, canvas) draws node rects via `rectToMinimap` and\n// the viewport lens via `viewportRect`, and maps pointer input back through\n// `toCanvas` — no rendering logic lives here, no math lives in renderers.\n\nexport type MinimapProjectionOptions = {\n /** Canvas-space bounds the minimap must cover (e.g. `getGraphBounds()`). */\n contentBounds: Rect;\n /** Current viewport — the lens rect derives from it. */\n viewport: Viewport;\n /** Main container size in screen px. */\n viewportSize: Size;\n /** Minimap surface size in px. */\n width: number;\n height: number;\n /** Padding around content as a fraction of its size (default 0.1). */\n padding?: number;\n};\n\nexport type MinimapProjection = {\n /** Canvas px → minimap px. */\n scale: number;\n /** The padded canvas-space rect the minimap covers. */\n bounds: Rect;\n /** The main view's visible area, in minimap coordinates (the \"lens\"). */\n viewportRect: Rect;\n toMinimap(point: Point): Point;\n toCanvas(point: Point): Point;\n rectToMinimap(rect: Rect): Rect;\n};\n\nexport type MinimapViewportCenterOptions = {\n /** Pointer position in canvas space. */\n point: Point;\n /** Pointer offset from the lens center, captured at pointer-down. */\n grabOffset?: Point;\n /** Graph bounds that minimap-driven navigation may move around. */\n contentBounds: Rect;\n /** Current visible canvas bounds; only its size is used. */\n viewportBounds: Rect;\n};\n\n/**\n * Resolve a minimap pointer to a bounded viewport center.\n *\n * This constraint applies only to minimap navigation. Each axis lets the lens\n * move fully past the graph, stopping when its nearest edge reaches the graph.\n */\nexport function getMinimapViewportCenter(\n options: MinimapViewportCenterOptions,\n): Point {\n const grabOffset = options.grabOffset ?? { x: 0, y: 0 };\n const target = {\n x: options.point.x - grabOffset.x,\n y: options.point.y - grabOffset.y,\n };\n const halfWidth = Math.max(0, options.viewportBounds.width) / 2;\n const halfHeight = Math.max(0, options.viewportBounds.height) / 2;\n const minX = options.contentBounds.x - halfWidth;\n const maxX =\n options.contentBounds.x + options.contentBounds.width + halfWidth;\n const minY = options.contentBounds.y - halfHeight;\n const maxY =\n options.contentBounds.y + options.contentBounds.height + halfHeight;\n\n return {\n x: Math.min(Math.max(target.x, minX), maxX),\n y: Math.min(Math.max(target.y, minY), maxY),\n };\n}\n\n\nexport function getMinimapProjection(\n options: MinimapProjectionOptions,\n): MinimapProjection {\n const padding = options.padding ?? 0.1;\n const content = options.contentBounds;\n const visible = getVisibleBounds(options.viewport, options.viewportSize);\n\n const padX = content.width * padding;\n const padY = content.height * padding;\n let bounds: Rect = {\n x: content.x - padX,\n y: content.y - padY,\n width: content.width + padX * 2,\n height: content.height + padY * 2,\n };\n // Always include the visible area so the lens never leaves the minimap.\n if (visible.width > 0 && visible.height > 0) {\n bounds = unionRect(bounds, visible);\n }\n if (bounds.width <= 0 || bounds.height <= 0) {\n bounds = { x: bounds.x, y: bounds.y, width: 1, height: 1 };\n }\n\n const scale = Math.min(\n options.width / bounds.width,\n options.height / bounds.height,\n );\n // Center the covered area on the minimap surface.\n const offsetX = (options.width - bounds.width * scale) / 2;\n const offsetY = (options.height - bounds.height * scale) / 2;\n\n const toMinimap = (point: Point): Point => ({\n x: (point.x - bounds.x) * scale + offsetX,\n y: (point.y - bounds.y) * scale + offsetY,\n });\n const toCanvas = (point: Point): Point => ({\n x: (point.x - offsetX) / scale + bounds.x,\n y: (point.y - offsetY) / scale + bounds.y,\n });\n const rectToMinimap = (rect: Rect): Rect => {\n const origin = toMinimap(rect);\n return {\n x: origin.x,\n y: origin.y,\n width: rect.width * scale,\n height: rect.height * scale,\n };\n };\n\n return {\n scale,\n bounds,\n viewportRect: rectToMinimap(visible),\n toMinimap,\n toCanvas,\n rectToMinimap,\n };\n}\n","export type FlowKeyBinding = string | string[] | null;\n\nexport type FlowMultiSelectModifier = 'shift' | 'meta' | 'ctrl' | 'alt';\n\nexport type FlowKeymap = {\n delete: FlowKeyBinding;\n undo: FlowKeyBinding;\n redo: FlowKeyBinding;\n selectAll: FlowKeyBinding;\n cancel: FlowKeyBinding;\n nudgeUp: FlowKeyBinding;\n nudgeDown: FlowKeyBinding;\n nudgeLeft: FlowKeyBinding;\n nudgeRight: FlowKeyBinding;\n nudgeLargeModifier: 'shift' | 'meta' | 'ctrl' | 'alt' | null;\n /**\n * Modifier(s) that turn a click into an additive (multi) select. A single\n * modifier or an array of them; multi-select fires when ANY listed modifier\n * is held. `null` disables multi-select entirely. The default is the explicit\n * legacy set `['shift','meta','ctrl']`; set exactly `'shift'` for shift-only.\n */\n multiSelectModifier:\n | FlowMultiSelectModifier\n | FlowMultiSelectModifier[]\n | null;\n panActivation: FlowKeyBinding;\n};\n\nexport const defaultKeymap: FlowKeymap = {\n delete: ['Delete', 'Backspace'],\n undo: 'mod+z',\n redo: ['mod+shift+z', 'mod+y'],\n selectAll: 'mod+a',\n cancel: 'Escape',\n nudgeUp: 'ArrowUp',\n nudgeDown: 'ArrowDown',\n nudgeLeft: 'ArrowLeft',\n nudgeRight: 'ArrowRight',\n nudgeLargeModifier: 'shift',\n multiSelectModifier: ['shift', 'meta', 'ctrl'],\n panActivation: ' ',\n};\n\nexport function resolveKeymap(keymap?: Partial<FlowKeymap>): FlowKeymap {\n return { ...defaultKeymap, ...keymap };\n}\n\ntype FlowInputModifiers = {\n shift: boolean;\n meta: boolean;\n ctrl: boolean;\n alt: boolean;\n};\n\n/**\n * Whether the active modifiers satisfy the keymap's `multiSelectModifier`.\n *\n * The field is one modifier or an array of them; multi-select fires when ANY\n * listed modifier is held. `null` disables multi-select entirely (never a multi\n * intent). The default is the explicit legacy set `['shift','meta','ctrl']`.\n */\nexport function matchesMultiSelect(\n modifiers: FlowInputModifiers,\n keymap: FlowKeymap,\n): boolean {\n const modifier = keymap.multiSelectModifier;\n if (modifier === null) return false;\n const list = Array.isArray(modifier) ? modifier : [modifier];\n return list.some((m) => modifiers[m]);\n}\n\nexport function matchesKeyBinding(\n event: {\n key: string;\n modifiers: { shift: boolean; meta: boolean; ctrl: boolean; alt: boolean };\n },\n binding: FlowKeyBinding,\n): boolean {\n if (binding == null) return false;\n const bindings = Array.isArray(binding) ? binding : [binding];\n return bindings.some((candidate) => matchesOneKeyBinding(event, candidate));\n}\n\nfunction matchesOneKeyBinding(\n event: {\n key: string;\n modifiers: { shift: boolean; meta: boolean; ctrl: boolean; alt: boolean };\n },\n binding: string,\n): boolean {\n if (binding === ' ') return event.key === ' ';\n const parts = binding.split('+').map((part) => part.trim()).filter(Boolean);\n const key = parts.pop() ?? '';\n const required = new Set(parts.map((part) => part.toLowerCase()));\n if (key.toLowerCase() !== event.key.toLowerCase()) return false;\n const usesMod = required.has('mod');\n if (usesMod && !(event.modifiers.meta || event.modifiers.ctrl)) return false;\n if (required.has('shift') && !event.modifiers.shift) return false;\n if (required.has('meta') && !event.modifiers.meta) return false;\n if (required.has('ctrl') && !event.modifiers.ctrl) return false;\n if (required.has('alt') && !event.modifiers.alt) return false;\n // Reject extra META/CTRL/ALT not required by the binding (e.g. Cmd+Backspace\n // must NOT match a plain Backspace delete). Extra SHIFT is tolerated so a\n // binding without shift still matches when shift is held (large-nudge arrows,\n // Escape mid-box-select, mod+shift+z falling through to mod+z). `mod` counts\n // as covering both meta and ctrl.\n if (event.modifiers.meta && !required.has('meta') && !usesMod) return false;\n if (event.modifiers.ctrl && !required.has('ctrl') && !usesMod) return false;\n if (event.modifiers.alt && !required.has('alt')) return false;\n return true;\n}\n","import type {\n FlowInputMode,\n FlowInputModeContext,\n FlowPinchInputEvent,\n FlowInputSessionHandlers,\n FlowInputTarget,\n FlowPointerInputEvent,\n FlowCommand,\n} from './index';\nimport { trigger } from './index';\nimport {\n matchesKeyBinding,\n matchesMultiSelect,\n resolveKeymap,\n type FlowKeymap,\n} from './keymap';\nimport type { ConnectEndTarget } from '../store';\nimport { normalizeConnection } from '../engine';\nimport type { FlowEdge, FlowNode, Point, Rect } from '../types';\nimport { rectsIntersect } from '../spatial';\nimport { indexChildren, indexNodes } from '../graph-index';\n\n// Local literal rather than importing the `preventDefault` const from\n// ./index: modes.ts evaluates first in the circular import between the two\n// files, so consts from ./index would still be in their temporal dead zone.\nconst preventDefault = { type: 'preventDefault' } as const;\nimport {\n isTrackpadPinch,\n normalizeWheelPan,\n wheelZoomDelta,\n} from '../spatial';\n\n// Built-in input modes\n//\n// These replicate (and centralize) the gesture semantics that previously\n// lived as ad hoc handlers in the React adapter. Priorities: keyboard 100,\n// wheel 90, space/middle pan 80, entity press/drag 50, pane press/pan 10.\n\n\nfunction distance(a: Point, b: Point): number {\n return Math.hypot(b.x - a.x, b.y - a.y);\n}\n\nfunction isMulti(event: FlowPointerInputEvent): boolean {\n return event.modifiers.shift || event.modifiers.meta || event.modifiers.ctrl;\n}\n\n\n// Keyboard: escape, undo/redo, delete, space (tracked by the runtime)\n\n\nexport function keyboardMode(\n options: {\n /** @deprecated Use `keymap.delete = null`. */\n allowDelete?: boolean;\n /** @deprecated Use `keymap.undo = null` and `keymap.redo = null`. */\n allowUndo?: boolean;\n keymap?: Partial<FlowKeymap>;\n escapeSelection?: 'all' | 'focused' | 'none';\n } = {},\n): FlowInputMode {\n const keymap = resolveKeymap({\n ...options.keymap,\n ...(options.allowDelete === false ? { delete: null } : {}),\n ...(options.allowUndo === false ? { undo: null, redo: null } : {}),\n });\n return {\n id: 'keyboard',\n priority: 100,\n start(event, { context }) {\n if (event.kind !== 'key.down') return null;\n if (event.editableTarget) return null;\n\n if (\n matchesKeyBinding(event, keymap.panActivation) &&\n !context.focusedEntityId\n ) {\n // panKeyHeld is tracked by the runtime; just stop the page scrolling.\n return { commands: [preventDefault] };\n }\n if (matchesKeyBinding(event, keymap.cancel)) {\n const commands: FlowCommand[] = [trigger('cancelConnection'), trigger('resizeCancel')];\n if (context.canvasState === 'idle' && !context.connection && !context.connectionClickStartHandle) {\n switch (options.escapeSelection ?? 'all') {\n case 'all':\n commands.push(trigger('clearSelection'), trigger('clearFocus'));\n break;\n case 'focused':\n if (context.focusedEntityId && context.selection.has(context.focusedEntityId)) {\n commands.push(trigger('select', {\n ids: [...context.selection].filter((id) => id !== context.focusedEntityId),\n mode: 'single',\n }));\n }\n commands.push(trigger('clearFocus'));\n break;\n case 'none':\n break;\n }\n }\n return { commands };\n }\n if (matchesKeyBinding(event, keymap.redo)) {\n return {\n commands: [preventDefault, trigger('redo')],\n };\n }\n if (matchesKeyBinding(event, keymap.undo)) {\n return {\n commands: [preventDefault, trigger('undo')],\n };\n }\n if (matchesKeyBinding(event, keymap.selectAll)) {\n return { commands: [preventDefault, trigger('selectAll')] };\n }\n if (matchesKeyBinding(event, keymap.delete)) {\n if (context.selection.size === 0) return null;\n return { commands: [preventDefault, trigger('deleteSelected')] };\n }\n return null;\n },\n };\n}\n\n\n// Keyboard navigation: arrows nudge the selection (undoable), Enter selects\n// the focused entity. Focus itself is driven by the renderer (DOM focus on\n// node elements syncs to `trigger.focus`), so traversal order stays native.\n\n\nconst ARROW_DIRECTIONS: Record<string, Point> = {\n ArrowLeft: { x: -1, y: 0 },\n ArrowRight: { x: 1, y: 0 },\n ArrowUp: { x: 0, y: -1 },\n ArrowDown: { x: 0, y: 1 },\n};\n\nexport function keyboardNavMode(\n options: {\n allowMove?: boolean;\n step?: number;\n shiftStep?: number;\n keymap?: Partial<FlowKeymap>;\n /** Literal KeyboardEvent.key names; null disables focused activation. */\n activationKeys?: readonly string[] | null;\n preventDefault?: boolean;\n selectionBehavior?: 'replace' | 'preserve';\n nudge?: 'selection' | 'focused-selection';\n } = {},\n): FlowInputMode {\n const allowMove = options.allowMove ?? true;\n const step = options.step ?? 5;\n const shiftStep = options.shiftStep ?? 20;\n const keymap = resolveKeymap(options.keymap);\n const activationKeys = options.activationKeys === undefined\n ? ['Enter', ' ', 'Spacebar']\n : options.activationKeys;\n return {\n id: 'keyboard-nav',\n priority: 95,\n start(event, { context, engine }) {\n if (event.kind !== 'key.down' || event.editableTarget) return null;\n\n if (activationKeys?.includes(event.key) && context.focusedEntityId) {\n const multiSelect = matchesMultiSelect(event.modifiers, keymap);\n const commands: FlowCommand[] = options.preventDefault === false ? [] : [preventDefault];\n if (\n multiSelect ||\n options.selectionBehavior !== 'preserve' ||\n !context.selection.has(context.focusedEntityId)\n ) {\n commands.push(trigger('select', {\n ids: [context.focusedEntityId],\n mode: multiSelect ? 'multi' : 'single',\n }));\n }\n return { commands };\n }\n\n if (!allowMove) return null;\n if (\n options.nudge === 'focused-selection' &&\n (!context.focusedEntityId ||\n !context.selection.has(context.focusedEntityId) ||\n !engine.getNode(context.focusedEntityId))\n ) return null;\n const direction =\n matchesKeyBinding(event, keymap.nudgeLeft) ? ARROW_DIRECTIONS.ArrowLeft :\n matchesKeyBinding(event, keymap.nudgeRight) ? ARROW_DIRECTIONS.ArrowRight :\n matchesKeyBinding(event, keymap.nudgeUp) ? ARROW_DIRECTIONS.ArrowUp :\n matchesKeyBinding(event, keymap.nudgeDown) ? ARROW_DIRECTIONS.ArrowDown :\n undefined;\n if (!direction || context.selection.size === 0) return null;\n // moveNodes is undoable; commitDrag bakes the offset so each press is\n // one complete, undoable step. snapToGrid moves by grid increments.\n return {\n commands: [\n preventDefault,\n trigger('moveNodes', {\n direction,\n factor:\n keymap.nudgeLargeModifier && event.modifiers[keymap.nudgeLargeModifier]\n ? shiftStep\n : step,\n }),\n trigger('commitDrag'),\n ],\n };\n },\n };\n}\n\nexport function doubleClickZoomMode(\n options: { enabled?: boolean; factor?: number } = {},\n): FlowInputMode {\n const enabled = options.enabled ?? true;\n const factor = options.factor ?? 2;\n return {\n id: 'double-click-zoom',\n priority: 70,\n start(event) {\n if (!enabled) return null;\n if (event.kind !== 'pointer.down') return null;\n if ((event.detail ?? 0) < 2) return null;\n if (event.button !== 0) return null;\n // Pane-only, matching react-flow's default: a node double-click must not\n // zoom the canvas. Entity double-clicks are emitted by entityPressMode.\n if (event.target.kind !== 'pane') return null;\n const zoomFactor = event.modifiers.shift ? 1 / factor : factor;\n return {\n commands: [\n preventDefault,\n trigger('zoomBy', { factor: zoomFactor, center: event.screenPoint }),\n ],\n };\n },\n };\n}\n\n\n// Wheel: trackpad pinch zooms; everything else pans\n\n\nexport function wheelMode(): FlowInputMode {\n return {\n id: 'wheel',\n priority: 90,\n start(event, { context }) {\n if (event.kind !== 'wheel') return null;\n\n if (\n isTrackpadPinch({\n ctrlKey: event.modifiers.ctrl,\n metaKey: event.modifiers.meta,\n })\n ) {\n const zoom =\n context.viewport.zoom *\n Math.pow(\n 2,\n wheelZoomDelta({\n deltaY: event.deltaY,\n deltaMode: event.deltaMode,\n ctrlKey: event.modifiers.ctrl,\n }),\n );\n return {\n commands: [\n preventDefault,\n trigger('zoomTo', { zoom, center: event.screenPoint }),\n ],\n };\n }\n\n return {\n commands: [\n preventDefault,\n trigger(\n 'panBy',\n normalizeWheelPan({\n deltaX: event.deltaX,\n deltaY: event.deltaY,\n deltaMode: event.deltaMode,\n }),\n ),\n ],\n };\n },\n };\n}\n\n\n// Space-held / middle-button pan — works from any target\n\n\nexport function panMode(): FlowInputMode {\n return {\n id: 'pan',\n priority: 80,\n start(event, { input }) {\n if (event.kind !== 'pointer.down') return null;\n const middle = event.button === 1;\n const space = input.panKeyHeld && event.button === 0;\n if (!middle && !space) return null;\n\n return {\n commands: [trigger('panStart', event.screenPoint)],\n session: panSession(),\n };\n },\n };\n}\n\nfunction panSession(): FlowInputSessionHandlers {\n return {\n update(event) {\n if (event.kind === 'pointer.move') {\n return { commands: [trigger('pan', event.screenPoint)] };\n }\n if (event.kind === 'pointer.up' || event.kind === 'pointer.cancel') {\n return { commands: [trigger('panEnd')], status: 'end' };\n }\n return {};\n },\n cancel() {\n return [trigger('panCancel')];\n },\n };\n}\n\n\n// Touch pinch: two fingers pan and zoom together.\n\n\nexport function pinchMode(): FlowInputMode {\n return {\n id: 'pinch',\n priority: 85,\n start(event, { context }) {\n if (event.kind !== 'pinch.start') return null;\n return {\n commands: [preventDefault],\n session: pinchSession(event, context.viewport),\n };\n },\n };\n}\n\nfunction pinchSession(\n down: FlowPinchInputEvent,\n viewport: FlowInputModeContext['context']['viewport'],\n): FlowInputSessionHandlers {\n let initialDistance = down.distance > 0 ? down.distance : null;\n const anchor = {\n x: (down.screenCenter.x - viewport.x) / viewport.zoom,\n y: (down.screenCenter.y - viewport.y) / viewport.zoom,\n };\n\n return {\n update(event, { context }) {\n if (event.kind === 'pinch.move') {\n if (initialDistance === null && event.distance > 0) {\n initialDistance = event.distance;\n }\n const zoom = initialDistance !== null\n ? Math.max(context.minZoom, Math.min(context.maxZoom, viewport.zoom * event.distance / initialDistance))\n : context.viewport.zoom;\n const center = {\n x: context.viewport.x + anchor.x * context.viewport.zoom,\n y: context.viewport.y + anchor.y * context.viewport.zoom,\n };\n return {\n commands: [\n preventDefault,\n trigger('zoomTo', { zoom, center }),\n trigger('panBy', {\n x: event.screenCenter.x - center.x,\n y: event.screenCenter.y - center.y,\n }),\n ],\n };\n }\n if (event.kind === 'pinch.end') {\n return { commands: [preventDefault], status: 'end' };\n }\n return {};\n },\n cancel() {\n return [];\n },\n };\n}\n\n// Entity press: select on pointer down, drag past the threshold\n// (nodes drag themselves; edges drag their label when pressed on it)\n\n\nexport type ReparentDropContext = {\n /** Top-level dragged nodes (descendants of dragged nodes excluded). */\n nodes: FlowNode[];\n /** Combined visual bounds of the dragged nodes. */\n bounds: Rect;\n /** Best drop candidate (evaluated as if the dragged nodes were absent). */\n candidate: { id: string; overlap: number } | null;\n /** Continuous time the current candidate has been hovered, in ms. */\n hoverMs: number;\n modifiers: { shift: boolean; meta: boolean; ctrl: boolean; alt: boolean };\n};\n\nexport type ReparentDecision = string | null | undefined;\n\nexport type ReparentOptions = {\n /** Minimum overlap ratio (dragged bounds ∩ child area / dragged area). Default 0.5. */\n minOverlap?: number;\n /** Required continuous hover time over a candidate before it counts. Default 0. */\n delayMs?: number;\n /**\n * Geometric unparenting: when no candidate exists AND the current parent's\n * rendered child area no longer touches the dragged bounds, clear the\n * parent. Only ever fires for `fixed` groups — `derived` groups stretch to\n * keep containing their children, so they can only be left via the\n * modifier gesture or a custom `decide`. Default true.\n */\n unparent?: boolean;\n /**\n * Holding this modifier at drop forces unparenting (release it before\n * dropping to cancel). Default 'alt'; null disables.\n */\n unparentModifier?: 'alt' | 'shift' | 'meta' | 'ctrl' | null;\n /**\n * Full custom policy. Return a node id to reparent into it, null to clear\n * the parent, undefined to keep current parents. When provided, it\n * replaces the built-in decision entirely.\n */\n decide?: (\n drop: ReparentDropContext,\n ctx: FlowInputModeContext,\n ) => ReparentDecision;\n};\n\nconst REPARENT_HIGHLIGHT_KIND = 'drop-target';\n\nexport function entityPressMode(\n options: {\n drag?:\n | boolean\n | ((\n event: FlowPointerInputEvent,\n context: FlowInputModeContext,\n ) => boolean);\n reparent?: boolean | ReparentOptions;\n keymap?: Partial<FlowKeymap>;\n } = {},\n): FlowInputMode {\n const allowDrag = options.drag ?? true;\n // Keymap-driven multi-select. Falls back to the legacy `isMulti`\n // (shift||meta||ctrl) when no keymap is threaded, so default behavior is\n // byte-identical to the pre-keymap call sites.\n const multiSelect = options.keymap\n ? (event: FlowPointerInputEvent) =>\n matchesMultiSelect(event.modifiers, resolveKeymap(options.keymap))\n : isMulti;\n const reparent: ReparentOptions | null =\n options.reparent === true\n ? {}\n : typeof options.reparent === 'object'\n ? options.reparent\n : null;\n return {\n id: 'entity-press',\n priority: 50,\n start(event, modeContext) {\n const { context, engine } = modeContext;\n if (event.kind !== 'pointer.down') return null;\n if (event.target.kind !== 'entity') return null;\n if (event.target.part?.startsWith('resize-handle:')) return null;\n\n const id = event.target.id;\n if (event.button === 2) {\n return {\n commands: [\n trigger('entityContextMenu', {\n id,\n point: event.point,\n modifiers: event.modifiers,\n }),\n ],\n };\n }\n if (event.button !== 0) return null;\n if (event.target.part === 'connection-boundary') return null;\n const entity = engine.getEntity(id);\n if (!entity) return null;\n const config = engine.resolveEntityConfig(entity);\n\n const commands: FlowCommand[] = [];\n if (config.selectable) {\n const selection = context.selection;\n const isMultiSelect = multiSelect(event);\n // A plain press inside an existing multi-selection keeps it intact so\n // the whole selection can be dragged. An explicit multi-select press\n // still toggles the pressed entity through the store's multi mode.\n if (!(selection.size > 1 && selection.has(id) && !isMultiSelect)) {\n commands.push(\n trigger('select', {\n ids: [id],\n mode: isMultiSelect ? 'multi' : 'single',\n }),\n );\n }\n }\n\n const draggablePart =\n entity.type === 'node' || event.target.part === 'label';\n const handleAllows =\n !event.target.entityHasDragHandle ||\n event.target.pressedDragHandle === true;\n const dragAllowed =\n typeof allowDrag === 'function'\n ? allowDrag(event, modeContext)\n : allowDrag;\n if (!dragAllowed || !draggablePart || !handleAllows || !config.draggable) {\n return {\n commands,\n session: entityClickSession(id, event),\n };\n }\n\n return {\n commands,\n session: dragSession(id, event, entity.type === 'node' ? reparent : null),\n };\n },\n };\n}\n\nfunction entityClickSession(\n id: string,\n down: FlowPointerInputEvent,\n): FlowInputSessionHandlers {\n return {\n update(event) {\n if (event.kind === 'pointer.up') {\n return {\n commands: [\n trigger(down.detail === 2 ? 'entityDoubleClicked' : 'entityClicked', {\n id,\n point: down.point,\n modifiers: down.modifiers,\n }),\n ],\n status: 'end',\n };\n }\n if (event.kind === 'pointer.cancel') return { status: 'end' };\n return {};\n },\n };\n}\n\nfunction dragSession(\n id: string,\n down: FlowPointerInputEvent,\n reparent: ReparentOptions | null,\n): FlowInputSessionHandlers {\n const transactionId = `drag:${id}:${down.pointerId}:${Date.now()}`;\n let dragging = false;\n let baseOffset: Point = { x: 0, y: 0 };\n let candidateId: string | null = null;\n let candidateOverlap = 0;\n let candidateSince = 0;\n\n const minOverlap = reparent?.minOverlap ?? 0.5;\n const unparentModifier =\n reparent?.unparentModifier === undefined ? 'alt' : reparent.unparentModifier;\n\n /**\n * Currently applied drag offset of the primary entity. The session anchors\n * requests to the virtual pointer (`base + pointerTravel`) and asks the\n * store for the difference — so store-side clamping (extents, fixed-group\n * child areas) is idempotent against pointer position: overshoot stays\n * virtual and the entity doesn't move again until the pointer returns.\n */\n function appliedOffset(ctx: FlowInputModeContext): Point {\n const node = ctx.engine.getNode(id);\n if (node) return { x: node.dx ?? 0, y: node.dy ?? 0 };\n const edge = ctx.engine.getEdge(id);\n if (edge?.label) {\n return { x: edge.label.dx ?? 0, y: edge.label.dy ?? 0 };\n }\n return { x: 0, y: 0 };\n }\n\n /** Top-level moving nodes + the full excluded (moving) subtree. */\n function movingInfo(ctx: FlowInputModeContext): {\n topLevel: FlowNode[];\n exclude: Set<string>;\n bounds: Rect | null;\n } {\n const { context, engine } = ctx;\n const nodes = context.graph.nodes as FlowNode[];\n const nodeIndex = indexNodes(nodes);\n const childrenIndex = indexChildren(nodes);\n const movingIds = new Set<string>();\n for (const selectedId of context.selection) {\n const node = nodeIndex.get(selectedId);\n if (node && node.draggable !== false) movingIds.add(selectedId);\n }\n const topLevel: FlowNode[] = [];\n for (const movingId of movingIds) {\n let ancestor = nodeIndex.get(movingId)?.parentId ?? null;\n let nested = false;\n const seen = new Set<string>();\n while (ancestor && !seen.has(ancestor)) {\n if (movingIds.has(ancestor)) {\n nested = true;\n break;\n }\n seen.add(ancestor);\n ancestor = nodeIndex.get(ancestor)?.parentId ?? null;\n }\n if (!nested) topLevel.push(nodeIndex.get(movingId)!);\n }\n // moving subtree = moving nodes + all their descendants\n const exclude = new Set(movingIds);\n const queue = [...movingIds];\n while (queue.length > 0) {\n const current = queue.pop()!;\n for (const child of childrenIndex.get(current) ?? []) {\n if (!exclude.has(child.id)) {\n exclude.add(child.id);\n queue.push(child.id);\n }\n }\n }\n let bounds: Rect | null = null;\n for (const node of topLevel) {\n const b = engine.resolvedBounds(node.id);\n bounds = bounds\n ? {\n x: Math.min(bounds.x, b.x),\n y: Math.min(bounds.y, b.y),\n width: Math.max(bounds.x + bounds.width, b.x + b.width) - Math.min(bounds.x, b.x),\n height: Math.max(bounds.y + bounds.height, b.y + b.height) - Math.min(bounds.y, b.y),\n }\n : { ...b };\n }\n return { topLevel, exclude, bounds };\n }\n\n function trackCandidate(\n ctx: FlowInputModeContext,\n pending: Point,\n ): FlowCommand[] {\n // Commands in one batch are computed before any of them apply, so the\n // store hasn't seen the dragMove yet — project the pending delta.\n const { exclude, bounds } = movingInfo(ctx);\n const projected = bounds\n ? { ...bounds, x: bounds.x + pending.x, y: bounds.y + pending.y }\n : null;\n const found = projected\n ? ctx.engine.getGroupDropTarget(projected, { exclude })\n : null;\n const nextId = found && found.overlap >= minOverlap ? found.id : null;\n candidateOverlap = found?.overlap ?? 0;\n if (nextId === candidateId) return [];\n const commands: FlowCommand[] = [];\n if (candidateId) {\n commands.push(\n trigger('removeHighlights', {\n kind: REPARENT_HIGHLIGHT_KIND,\n ids: [candidateId],\n }),\n );\n }\n if (nextId) {\n commands.push(\n trigger('addHighlights', {\n kind: REPARENT_HIGHLIGHT_KIND,\n entries: [{ id: nextId }],\n }),\n );\n }\n candidateId = nextId;\n candidateSince = Date.now();\n return commands;\n }\n\n function decideAndApply(\n event: FlowPointerInputEvent,\n ctx: FlowInputModeContext,\n ): FlowCommand[] {\n const commands: FlowCommand[] = [];\n if (candidateId) {\n commands.push(\n trigger('removeHighlights', {\n kind: REPARENT_HIGHLIGHT_KIND,\n ids: [candidateId],\n }),\n );\n }\n if (event.kind !== 'pointer.up' || !reparent) return commands;\n\n const { topLevel, exclude, bounds } = movingInfo(ctx);\n if (!bounds || topLevel.length === 0) return commands;\n\n // Recompute fresh at drop (tracking is projected per-move; the drop\n // happens at the last tracked position, so ids should agree — but the\n // final geometry is authoritative).\n const found = ctx.engine.getGroupDropTarget(bounds, { exclude });\n const finalId = found && found.overlap >= minOverlap ? found.id : null;\n const hoverMs =\n finalId && finalId === candidateId ? Date.now() - candidateSince : 0;\n candidateId = finalId;\n candidateOverlap = found?.overlap ?? 0;\n const drop: ReparentDropContext = {\n nodes: topLevel,\n bounds,\n candidate: candidateId\n ? { id: candidateId, overlap: candidateOverlap }\n : null,\n hoverMs,\n modifiers: event.modifiers,\n };\n\n let decision: ReparentDecision;\n if (reparent.decide) {\n decision = reparent.decide(drop, ctx);\n } else if (unparentModifier && event.modifiers[unparentModifier]) {\n decision = null;\n } else if (candidateId && hoverMs >= (reparent.delayMs ?? 0)) {\n decision = candidateId;\n } else if (!candidateId && (reparent.unparent ?? true)) {\n // Geometric unparenting: only when the current parent's rendered child\n // area no longer touches the dragged bounds (never true for derived\n // groups — they stretch to contain their children).\n const escaped = topLevel.some((node) => {\n if (!node.parentId) return false;\n const geometry = ctx.engine.getGroupGeometry(node.parentId);\n return geometry ? !rectsIntersect(bounds, geometry.childArea) : false;\n });\n decision = escaped ? null : undefined;\n }\n\n if (decision !== undefined) {\n for (const node of topLevel) {\n if ((node.parentId ?? null) === decision || node.id === decision) {\n continue;\n }\n commands.push(\n trigger('reparentNode', {\n id: node.id,\n parentId: decision,\n transactionId,\n }),\n );\n }\n }\n return commands;\n }\n\n return {\n update(event, ctx) {\n const { context } = ctx;\n if (event.kind === 'pointer.move') {\n if (!dragging) {\n if (\n distance(down.screenPoint, event.screenPoint) <\n context.dragThreshold\n ) {\n return {};\n }\n dragging = true;\n baseOffset = appliedOffset(ctx);\n }\n // Pointer-anchored request: ask the store for whatever delta brings\n // the applied offset to the virtual target. Clamps simply truncate\n // the request, and re-derive from the pointer on the next move.\n const applied = appliedOffset(ctx);\n const dx =\n baseOffset.x + (event.point.x - down.point.x) - applied.x;\n const dy =\n baseOffset.y + (event.point.y - down.point.y) - applied.y;\n const starting = !context.draggedEntityId;\n return {\n commands: [\n ...(starting\n ? [trigger('dragStart', { id, transactionId })]\n : []),\n trigger('dragMove', { dx, dy }),\n ...(reparent ? trackCandidate(ctx, { x: dx, y: dy }) : []),\n ],\n };\n }\n if (event.kind === 'pointer.up' || event.kind === 'pointer.cancel') {\n const snapResult = ctx.engine.getSnapResult();\n const snapOffset =\n snapResult\n ? {\n x: snapResult.snapRect.x - snapResult.sourceRect.x,\n y: snapResult.snapRect.y - snapResult.sourceRect.y,\n }\n : { x: 0, y: 0 };\n return {\n commands: dragging\n ? [\n trigger('dragEnd'),\n trigger('commitDrag', { transactionId, snapOffset }),\n ...(reparent ? decideAndApply(event, ctx) : []),\n ]\n : event.kind === 'pointer.up'\n ? [\n trigger(down.detail === 2 ? 'entityDoubleClicked' : 'entityClicked', {\n id,\n point: down.point,\n modifiers: down.modifiers,\n }),\n ]\n : [],\n status: 'end',\n };\n }\n return {};\n },\n cancel() {\n const commands: FlowCommand[] = dragging\n ? [trigger('dragCancel')]\n : [];\n if (candidateId) {\n commands.push(\n trigger('removeHighlights', {\n kind: REPARENT_HIGHLIGHT_KIND,\n ids: [candidateId],\n }),\n );\n }\n return commands;\n },\n };\n}\n\n\n// Connect: dragging from a port starts a connection; validity is checked\n// against the engine on every move; release emits `connectionEnded` with the\n// drop target (node/port, edge, canvas position, or none).\n\n\nexport type ConnectModeOptions = {\n /**\n * Validity check for the current hover target during a connection drag.\n * Defaults to `engine.validateConnection` for node/port targets (rejecting\n * the source node itself) and `false` for everything else. Engine-level\n * validation policy belongs in `createFlowEngine({ canConnect })`; use this\n * override for gesture-specific rules (e.g. allowing canvas drops).\n */\n isValid?: (\n args: {\n source: { nodeId: string; port: string };\n target: FlowInputTarget;\n point: Point;\n },\n ctx: FlowInputModeContext,\n ) => boolean;\n};\n\nexport function connectMode(options: ConnectModeOptions = {}): FlowInputMode {\n return {\n id: 'connect',\n priority: 60,\n start(event, ctx) {\n const { engine, context } = ctx;\n const pending = context.connectionClickStartHandle;\n if (pending && context.connection) {\n if (!context.connectOnClick || event.kind === 'pointer.cancel') {\n return { commands: [trigger('cancelConnection')] };\n }\n if (pending.port === null) return { commands: [trigger('cancelConnection')] };\n const source = { nodeId: pending.nodeId, port: pending.port };\n if (event.kind === 'pointer.move') {\n return { commands: [connectionMoveCommand(resolveConnectionTarget(event, source, ctx, options.isValid), true)] };\n }\n if (event.kind !== 'pointer.down' || event.button !== 0) return null;\n const target = event.target;\n const completesOnPort = target.kind === 'port' &&\n target.interaction !== 'inspect' &&\n (target.nodeId !== source.nodeId || target.portName !== source.port);\n const completesOnNode = target.kind === 'entity' &&\n target.id !== source.nodeId && engine.getNode(target.id) !== undefined;\n if (!completesOnPort && !completesOnNode) {\n return { commands: [trigger('cancelConnection')] };\n }\n return { session: connectSession(source, options, { kind: 'completing' }) };\n }\n if (event.kind !== 'pointer.down' || event.button !== 0) return null;\n if (event.target.kind !== 'port') return null;\n if (event.target.interaction === 'inspect') return null;\n\n const { nodeId, portName } = event.target;\n const node = engine.getNode(nodeId);\n if (!node?.ports?.some((port) => port.name === portName)) return null;\n if (!engine.isPortAllowed(node, portName)) return null;\n if (!engine.resolveEntityConfig(node).connectable) return null;\n\n return {\n commands: [\n trigger('connectionStart', {\n sourceId: nodeId,\n sourcePort: portName,\n position: event.point,\n }),\n ],\n session: connectSession({ nodeId, port: portName }, options, { kind: 'pressed', screenPoint: event.screenPoint }),\n };\n },\n };\n}\n\n/** Select/focus graph-owned ports explicitly rendered for readonly inspection. */\nexport function portPressMode(\n options: { keymap?: Partial<FlowKeymap> } = {},\n): FlowInputMode {\n const multiSelect = options.keymap\n ? (event: FlowPointerInputEvent) =>\n matchesMultiSelect(event.modifiers, resolveKeymap(options.keymap))\n : isMulti;\n return {\n id: 'port-press',\n priority: 55,\n start(event, { engine }) {\n if (event.kind !== 'pointer.down') return null;\n if (event.target.kind !== 'port' || event.target.interaction !== 'inspect') {\n return null;\n }\n\n const { nodeId, portName } = event.target;\n const portId = event.target.portId ?? `${nodeId}:${portName}`;\n const addressable = engine.getEntityRef(portId);\n if (!addressable || addressable.kind !== 'port') return null;\n\n if (event.button === 2) {\n return {\n commands: [\n trigger('entityContextMenu', {\n id: portId,\n point: event.point,\n modifiers: event.modifiers,\n }),\n ],\n };\n }\n if (event.button !== 0) return null;\n\n const owner = engine.getNode(nodeId);\n if (!owner) return null;\n const config = engine.resolveEntityConfig(owner);\n const commands: FlowCommand[] = [];\n if (config.selectable) {\n commands.push(\n trigger('select', {\n ids: [portId],\n mode: multiSelect(event) ? 'multi' : 'single',\n }),\n );\n }\n if (config.focusable) {\n commands.push(trigger('focus', { entityId: portId }));\n }\n return {\n commands,\n session: entityClickSession(portId, event),\n };\n },\n };\n}\n\nfunction defaultConnectionValidityDetailed(\n args: {\n source: { nodeId: string; port: string };\n target: FlowInputTarget;\n point: Point;\n },\n ctx: FlowInputModeContext,\n): { valid: boolean; reason?: string } {\n const { source, target } = args;\n if (target.kind === 'port') {\n if (target.nodeId === source.nodeId) return { valid: false, reason: 'same-node' };\n return ctx.engine.validateConnectionDetailed(normalizeConnection({\n sourceId: source.nodeId,\n sourcePort: source.port,\n targetId: target.nodeId,\n targetPort: target.portName,\n }, ctx.context.graph));\n }\n if (target.kind === 'entity') {\n if (target.id === source.nodeId) return { valid: false, reason: 'same-node' };\n if (!ctx.engine.getNode(target.id)) return { valid: false, reason: 'not-node-target' };\n const candidate = ctx.engine.getConnectionCandidate(args.point, { source });\n if (!candidate || candidate.nodeId !== target.id || candidate.portName !== null) {\n return { valid: false, reason: 'outside-connection-radius' };\n }\n return ctx.engine.validateConnectionDetailed(normalizeConnection({\n sourceId: source.nodeId,\n sourcePort: source.port,\n targetId: target.id,\n targetPort: null,\n }, ctx.context.graph));\n }\n return { valid: false, reason: 'invalid-target' };\n}\n\nfunction connectEndTargetFor(\n target: FlowInputTarget,\n point: Point,\n ctx: FlowInputModeContext,\n): ConnectEndTarget {\n if (target.kind === 'port') {\n return { kind: 'node', nodeId: target.nodeId, port: target.portName };\n }\n if (target.kind === 'entity') {\n const entity = ctx.engine.getEntity(target.id);\n if (entity?.type === 'node') {\n return { kind: 'node', nodeId: target.id, port: null };\n }\n if (entity?.type === 'edge') {\n return { kind: 'edge', edgeId: target.id };\n }\n }\n if (target.kind === 'pane') {\n return { kind: 'canvas', position: point };\n }\n return { kind: 'none' };\n}\n\ntype ResolvedConnectionTarget = {\n target: FlowInputTarget;\n targetId: string | null;\n targetPort: string | null;\n position: Point;\n isValid: boolean;\n invalidReason?: string;\n endTarget: ConnectEndTarget;\n};\n\nfunction targetFromConnectionCandidate(candidate: {\n nodeId: string;\n portName: string | null;\n}): FlowInputTarget {\n return candidate.portName\n ? {\n kind: 'port',\n nodeId: candidate.nodeId,\n portName: candidate.portName,\n }\n : { kind: 'entity', id: candidate.nodeId };\n}\n\nfunction targetIdsFor(\n target: FlowInputTarget,\n ctx: FlowInputModeContext,\n): { targetId: string | null; targetPort: string | null } {\n if (target.kind === 'port') {\n return { targetId: target.nodeId, targetPort: target.portName };\n }\n if (target.kind === 'entity' && ctx.engine.getNode(target.id)) {\n return { targetId: target.id, targetPort: null };\n }\n return { targetId: null, targetPort: null };\n}\n\nfunction resolveConnectionTarget(\n event: FlowPointerInputEvent,\n source: { nodeId: string; port: string },\n ctx: FlowInputModeContext,\n isValid: ConnectModeOptions['isValid'],\n): ResolvedConnectionTarget {\n const candidate = ctx.engine.getConnectionCandidate(event.point, {\n source,\n });\n if (\n candidate &&\n (event.target.kind !== 'port' ||\n (candidate.nodeId === event.target.nodeId && candidate.portName === event.target.portName))\n ) {\n const target = targetFromConnectionCandidate(candidate);\n const validity = isValid\n ? isValid({ source, target, point: event.point }, ctx)\n : candidate.isValid;\n return {\n target,\n targetId: candidate.nodeId,\n targetPort: candidate.portName,\n position: candidate.position,\n isValid: validity,\n endTarget: connectEndTargetFor(target, candidate.position, ctx),\n };\n }\n\n const { targetId, targetPort } = targetIdsFor(event.target, ctx);\n const detailed = isValid\n ? { valid: isValid({ source, target: event.target, point: event.point }, ctx) }\n : defaultConnectionValidityDetailed({ source, target: event.target, point: event.point }, ctx);\n return {\n target: event.target,\n targetId,\n targetPort,\n position: event.point,\n isValid: detailed.valid,\n invalidReason: detailed.reason,\n endTarget: connectEndTargetFor(event.target, event.point, ctx),\n };\n}\n\nfunction connectionMoveCommand(target: ResolvedConnectionTarget, active?: boolean): FlowCommand {\n return trigger('connectionMove', {\n position: target.position,\n targetId: target.targetId,\n targetPort: target.targetPort,\n isValid: target.isValid,\n invalidReason: target.invalidReason,\n ...(active === undefined ? {} : { active }),\n });\n}\n\nfunction connectSession(\n source: { nodeId: string; port: string },\n options: ConnectModeOptions,\n phase: { kind: 'pressed'; screenPoint: Point } | { kind: 'completing' },\n): FlowInputSessionHandlers {\n return {\n update(event, ctx) {\n if (!ctx.context.connection) {\n return { status: 'end' };\n }\n if (event.kind === 'pointer.move') {\n const target = resolveConnectionTarget(event, source, ctx, options.isValid);\n const travel = phase.kind === 'pressed' ? distance(phase.screenPoint, event.screenPoint) : 0;\n const active = ctx.context.connection.active || phase.kind === 'completing' ||\n (travel > 0 && travel >= ctx.context.connectionDragThreshold);\n return { commands: [connectionMoveCommand(target, active)] };\n }\n if (event.kind === 'pointer.up') {\n if (\n phase.kind === 'pressed' &&\n ctx.context.connectOnClick &&\n !ctx.context.connection.active &&\n (distance(phase.screenPoint, event.screenPoint) === 0 ||\n distance(phase.screenPoint, event.screenPoint) < ctx.context.connectionDragThreshold)\n ) {\n return {\n commands: [\n trigger('setConnectionClickStartHandle', source),\n trigger('connectionMove', { position: event.point, active: true }),\n ],\n status: 'end',\n };\n }\n const target = resolveConnectionTarget(event, source, ctx, options.isValid);\n return {\n commands: [\n connectionMoveCommand(target),\n trigger('connectionEnd', { target: target.endTarget }),\n ],\n status: 'end',\n };\n }\n if (event.kind === 'pointer.cancel') {\n return { commands: [trigger('cancelConnection')], status: 'end' };\n }\n return {};\n },\n cancel() {\n return [trigger('cancelConnection')];\n },\n };\n}\n\n// Reconnect: drag one selected edge endpoint and reuse connection preview state.\n\n\nexport type ReconnectModeOptions = {\n /**\n * Mutate the Flow graph after a valid drop. Disable for controlled graphs\n * whose domain store consumes `connectionEnded` and owns the mutation.\n * Defaults to true.\n */\n commit?: boolean;\n /** Render Flow's generic preview edge. Disable when an external store owns\n * temporary preview geometry. Defaults to true. */\n preview?: boolean;\n /**\n * Delay reconnect activation until pointer travel crosses a screen-pixel\n * threshold. `true` uses the store's `connectionDragThreshold`; a number\n * uses that exact threshold. Defaults to immediate activation.\n */\n dragThreshold?: boolean | number;\n isValid?: (\n args: {\n edge: FlowEdge;\n end: 'source' | 'target';\n target: FlowInputTarget;\n point: Point;\n },\n ctx: FlowInputModeContext,\n ) => boolean;\n};\n\nfunction edgeEndpointFromPart(\n part: string | undefined,\n): 'source' | 'target' | null {\n if (part === 'edge-endpoint:source') return 'source';\n if (part === 'edge-endpoint:target') return 'target';\n return null;\n}\n\nfunction reconnectTarget(\n target: FlowInputTarget,\n ctx: FlowInputModeContext,\n point?: Point,\n): { nodeId: string; port: string | null } | null {\n if (target.kind === 'port') {\n return { nodeId: target.nodeId, port: target.portName };\n }\n if (target.kind === 'entity' && ctx.engine.getNode(target.id)) {\n return { nodeId: target.id, port: null };\n }\n if (point) {\n const candidate = ctx.engine.getConnectionCandidate(point);\n if (candidate) {\n return { nodeId: candidate.nodeId, port: candidate.portName };\n }\n }\n return null;\n}\n\nfunction defaultReconnectValidity(\n args: {\n edge: FlowEdge;\n end: 'source' | 'target';\n target: FlowInputTarget;\n point: Point;\n },\n ctx: FlowInputModeContext,\n): boolean {\n const candidate = reconnectTarget(args.target, ctx, args.point);\n if (!candidate) return false;\n if (args.end === 'source') {\n return ctx.engine.validateConnection({\n sourceId: candidate.nodeId,\n sourcePort: candidate.port,\n targetId: args.edge.targetId,\n targetPort: args.edge.targetPort ?? null,\n });\n }\n return ctx.engine.validateConnection({\n sourceId: args.edge.sourceId,\n sourcePort: args.edge.sourcePort ?? null,\n targetId: candidate.nodeId,\n targetPort: candidate.port,\n });\n}\n\nexport function reconnectMode(options: ReconnectModeOptions = {}): FlowInputMode {\n return {\n id: 'reconnect',\n priority: 75,\n start(event, { context, engine }) {\n if (event.kind !== 'pointer.down' || event.button !== 0) return null;\n if (event.target.kind !== 'entity') return null;\n const end = edgeEndpointFromPart(event.target.part);\n if (!end) return null;\n\n const edge = engine.getEdge(event.target.id);\n if (!edge) return null;\n if (!engine.resolveEntityConfig(edge).reconnectable) return null;\n\n const fixedNodeId = end === 'source' ? edge.targetId : edge.sourceId;\n if (!engine.getNode(fixedNodeId)) return null;\n const fixedPort =\n end === 'source' ? edge.targetPort ?? null : edge.sourcePort ?? null;\n const transactionId = `reconnect:${edge.id}:${event.pointerId}:${Date.now()}`;\n const threshold =\n options.dragThreshold === true\n ? context.connectionDragThreshold\n : typeof options.dragThreshold === 'number'\n ? Math.max(0, options.dragThreshold)\n : 0;\n\n return {\n commands: [\n preventDefault,\n trigger('connectionStart', {\n sourceId: fixedNodeId,\n sourcePort: fixedPort,\n position: event.point,\n active: threshold === 0,\n reconnectingEdgeId: edge.id,\n reconnectingEnd: end,\n preview: options.preview !== false,\n }),\n ],\n session: reconnectSession(\n {\n edgeId: edge.id,\n end,\n transactionId,\n startScreenPoint: event.screenPoint,\n threshold,\n },\n options,\n ),\n };\n },\n };\n}\n\nfunction reconnectSession(\n reconnect: {\n edgeId: string;\n end: 'source' | 'target';\n transactionId: string;\n startScreenPoint: Point;\n threshold: number;\n },\n options: ReconnectModeOptions,\n): FlowInputSessionHandlers {\n const isValid = options.isValid ?? defaultReconnectValidity;\n let active = reconnect.threshold === 0;\n\n function moveCommands(\n event: FlowPointerInputEvent,\n ctx: FlowInputModeContext,\n activate = false,\n ): { commands: FlowCommand[]; candidate: { nodeId: string; port: string | null } | null; valid: boolean } {\n const edge = ctx.engine.getEdge(reconnect.edgeId);\n const candidate = reconnectTarget(event.target, ctx, event.point);\n const valid =\n !!edge &&\n isValid(\n { edge, end: reconnect.end, target: event.target, point: event.point },\n ctx,\n );\n return {\n candidate,\n valid,\n commands: [\n trigger('connectionMove', {\n position: event.point,\n targetId: candidate?.nodeId ?? null,\n targetPort: candidate?.port ?? null,\n isValid: valid,\n ...(activate ? { active: true } : {}),\n }),\n ],\n };\n }\n\n return {\n update(event, ctx) {\n if (!ctx.context.connection) {\n return { status: 'end' };\n }\n if (event.kind === 'pointer.move') {\n if (!active) {\n if (\n distance(reconnect.startScreenPoint, event.screenPoint) <\n reconnect.threshold\n ) {\n return {};\n }\n active = true;\n return { commands: moveCommands(event, ctx, true).commands };\n }\n return { commands: moveCommands(event, ctx).commands };\n }\n if (event.kind === 'pointer.up') {\n if (!active) {\n return {\n commands: [\n trigger('connectionEnd', {\n target: { kind: 'none' },\n reconnectedEdgeId: reconnect.edgeId,\n }),\n ],\n status: 'end',\n };\n }\n const result = moveCommands(event, ctx);\n const commands: FlowCommand[] = [...result.commands];\n if (result.candidate && result.valid) {\n const endTarget = connectEndTargetFor(\n targetFromConnectionCandidate({\n nodeId: result.candidate.nodeId,\n portName: result.candidate.port,\n }),\n event.point,\n ctx,\n );\n if (options.commit !== false) {\n commands.push(\n trigger('reconnectEdge', {\n edgeId: reconnect.edgeId,\n ...(reconnect.end === 'source'\n ? {\n newSourceId: result.candidate.nodeId,\n newSourcePort: result.candidate.port,\n }\n : {\n newTargetId: result.candidate.nodeId,\n newTargetPort: result.candidate.port,\n }),\n transactionId: reconnect.transactionId,\n }),\n );\n }\n commands.push(\n trigger('connectionEnd', {\n target: endTarget,\n reconnectedEdgeId: reconnect.edgeId,\n }),\n );\n } else {\n commands.push(\n trigger('connectionEnd', {\n target: connectEndTargetFor(event.target, event.point, ctx),\n reconnectedEdgeId: reconnect.edgeId,\n }),\n );\n }\n return { commands, status: 'end' };\n }\n if (event.kind === 'pointer.cancel') {\n return {\n commands: [\n trigger('connectionEnd', {\n target: { kind: 'none' },\n reconnectedEdgeId: reconnect.edgeId,\n }),\n ],\n status: 'end',\n };\n }\n return {};\n },\n cancel() {\n return [\n trigger('connectionEnd', {\n target: { kind: 'none' },\n reconnectedEdgeId: reconnect.edgeId,\n }),\n ];\n },\n };\n}\n\n\n// Hover: bare pointer moves (no active session) track the entity under the\n// pointer. Triggers only when the hovered entity actually changes, and the\n// store bails on identical sets — most moves cost nothing downstream.\n\n\nexport function hoverMode(): FlowInputMode {\n return {\n id: 'hover',\n priority: 5,\n start(event, { context }) {\n if (event.kind !== 'pointer.move') return null;\n const target = event.target;\n const id =\n target.kind === 'entity'\n ? target.id\n : target.kind === 'port'\n ? target.nodeId\n : null;\n const current = context.hoveredEntityIds;\n if (id) {\n if (current.size === 1 && current.has(id)) return null;\n return { commands: [trigger('setHover', { ids: [id] })] };\n }\n if (current.size === 0) return null;\n return { commands: [trigger('clearHover')] };\n },\n };\n}\n\n\n// Pane press: click clears selection; drag past the threshold pans\n\n\nexport function panePressMode(): FlowInputMode {\n return {\n id: 'pane-press',\n priority: 10,\n start(event) {\n if (event.kind !== 'pointer.down') return null;\n if (event.target.kind !== 'pane') return null;\n if (event.button === 2) {\n return {\n commands: [\n trigger('paneContextMenu', {\n point: event.point,\n modifiers: event.modifiers,\n }),\n ],\n };\n }\n if (event.button !== 0) return null;\n return { session: panePressSession(event) };\n },\n };\n}\n\nfunction panePressSession(\n down: FlowPointerInputEvent,\n): FlowInputSessionHandlers {\n let panning = false;\n\n return {\n update(event, { context }) {\n if (event.kind === 'pointer.move') {\n if (!panning) {\n if (\n distance(down.screenPoint, event.screenPoint) <\n context.dragThreshold\n ) {\n return {};\n }\n panning = true;\n return {\n commands: [\n trigger('clearSelection'),\n trigger('clearFocus'),\n trigger('panStart', down.screenPoint),\n trigger('pan', event.screenPoint),\n ],\n };\n }\n return { commands: [trigger('pan', event.screenPoint)] };\n }\n if (event.kind === 'pointer.up') {\n return {\n commands: panning\n ? [trigger('panEnd')]\n : [\n trigger('clearSelection'),\n trigger('clearFocus'),\n trigger('paneClicked', {\n point: down.point,\n modifiers: down.modifiers,\n }),\n ],\n status: 'end',\n };\n }\n if (event.kind === 'pointer.cancel') {\n return {\n commands: panning ? [trigger('panEnd')] : [],\n status: 'end',\n };\n }\n return {};\n },\n cancel() {\n return panning ? [trigger('panCancel')] : [];\n },\n };\n}\n\n\n// Box selection: shift + drag on the pane sweeps a marquee that selects every\n// entity it touches. Sits above pane-press so the modifier diverts the pane\n// drag from panning to selecting; a plain pane drag still pans.\n\n\nexport type BoxSelectModeOptions = {\n /**\n * Whether a pane pointer-down should begin a box select. Default: only with\n * a multi modifier (shift/ctrl/meta) held, so a plain pane drag still pans.\n * Pass `() => true` for a selection-first canvas where every pane drag boxes\n * (and the modifier instead adds to the existing selection).\n */\n enabled?: (event: FlowPointerInputEvent) => boolean;\n keymap?: Partial<FlowKeymap>;\n};\n\nexport function boxSelectMode(\n options: BoxSelectModeOptions = {},\n): FlowInputMode {\n // Keymap-driven multi-select, falling back to the legacy `isMulti`\n // (shift||meta||ctrl) so default behavior is byte-identical.\n const multiSelect = options.keymap\n ? (event: FlowPointerInputEvent) =>\n matchesMultiSelect(event.modifiers, resolveKeymap(options.keymap))\n : isMulti;\n const enabled = options.enabled ?? multiSelect;\n return {\n id: 'box-select',\n priority: 20,\n start(event) {\n if (event.kind !== 'pointer.down' || event.button !== 0) return null;\n if (event.target.kind !== 'pane') return null;\n // follow-up: touch box-select bails here; touch long-press box-select is\n // a deferred follow-up (WP4) — for now a touch pane drag always pans.\n if (event.pointerType === 'touch') return null;\n if (!enabled(event)) return null;\n return { session: boxSelectSession(event, multiSelect) };\n },\n };\n}\n\nfunction boxSelectSession(\n down: FlowPointerInputEvent,\n multiSelect: (event: FlowPointerInputEvent) => boolean,\n): FlowInputSessionHandlers {\n let selecting = false;\n\n return {\n update(event, { context }) {\n if (event.kind === 'pointer.move') {\n if (!selecting) {\n if (\n distance(down.screenPoint, event.screenPoint) <\n context.dragThreshold\n ) {\n return {};\n }\n selecting = true;\n return {\n commands: [\n trigger('selectionBoxStart', {\n point: down.point,\n mode: multiSelect(down) ? 'multi' : 'single',\n }),\n trigger('selectionBoxMove', { point: event.point }),\n ],\n };\n }\n return {\n commands: [trigger('selectionBoxMove', { point: event.point })],\n };\n }\n if (event.kind === 'pointer.up' || event.kind === 'pointer.cancel') {\n if (selecting) {\n return { commands: [trigger('selectionBoxEnd')], status: 'end' };\n }\n // A tap with no drag: clear selection + focus like a pane click would\n // (this mode pre-empts pane-press, so it must own that behavior). A\n // modifier tap is left alone — it's an additive intent.\n return {\n commands: multiSelect(down)\n ? []\n : [\n trigger('clearSelection'),\n trigger('clearFocus'),\n trigger('paneClicked', {\n point: down.point,\n modifiers: down.modifiers,\n }),\n ],\n status: 'end',\n };\n }\n return {};\n },\n cancel() {\n return selecting ? [trigger('selectionBoxCancel')] : [];\n },\n };\n}\n\n\n// Presets\n\n\n/** Interactive default: full editing gestures. */\nexport function defaultInputModesForKeymap(\n keymap?: Partial<FlowKeymap>,\n): FlowInputMode[] {\n return [\n keyboardMode({ keymap }),\n keyboardNavMode({ keymap }),\n wheelMode(),\n pinchMode(),\n doubleClickZoomMode(),\n panMode(),\n connectMode(),\n portPressMode({ keymap }),\n reconnectMode(),\n entityPressMode({ keymap }),\n boxSelectMode({ keymap }),\n panePressMode(),\n hoverMode(),\n ];\n}\n\nexport const defaultInputModes: FlowInputMode[] = defaultInputModesForKeymap();\n\n/** Readonly: select and navigate, no mutation gestures. */\nexport function readonlyInputModesForKeymap(\n keymap?: Partial<FlowKeymap>,\n): FlowInputMode[] {\n return [\n keyboardMode({ allowDelete: false, allowUndo: false, keymap }),\n keyboardNavMode({ allowMove: false, keymap }),\n wheelMode(),\n doubleClickZoomMode(),\n panMode(),\n portPressMode({ keymap }),\n entityPressMode({ drag: false, keymap }),\n boxSelectMode({ keymap }),\n panePressMode(),\n hoverMode(),\n ];\n}\n\nexport const readonlyInputModes: FlowInputMode[] = readonlyInputModesForKeymap();\n","import { connectionLifetime } from '../connection-lifetime';\nimport type { FlowStore, FlowStoreContext } from '../store';\nimport type { FlowEngine } from '../engine';\nimport type { Point } from '../types';\nimport {\n matchesKeyBinding,\n resolveKeymap,\n type FlowKeymap,\n} from './keymap';\nexport { defaultKeymap, matchesKeyBinding, resolveKeymap } from './keymap';\nexport type { FlowKeyBinding, FlowKeymap } from './keymap';\n\n// Flow input runtime\n//\n// Framework-neutral input recognition (see .notes/react-flow-soft-parity.md,\n// \"Input Recognition Model\"). Adapters normalize raw browser/framework events\n// into FlowInputEvents and feed them to a runtime; the runtime dispatches to\n// ordered input modes which return declarative commands. The runtime applies\n// commands through `store.trigger` — modes never perform side effects, which\n// keeps every gesture unit-testable without a DOM.\n//\n// raw event → adapter (flow-dom/flow-react) → FlowInputEvent\n// → runtime → mode.start(...) / session.update(...) → FlowCommand[]\n// → store.trigger.*\n//\n// One exclusive session at a time (a drag, a pan). While a session is active,\n// pointer events for its pointer go to the session; keyboard/wheel and other\n// pointers still flow to stateless modes.\n\n\n// Normalized events\n\n\nexport type FlowInputModifiers = {\n shift: boolean;\n meta: boolean;\n ctrl: boolean;\n alt: boolean;\n};\n\nexport type FlowInputTarget =\n | { kind: 'pane' }\n | {\n kind: 'entity';\n id: string;\n part?:\n | 'label'\n | `resize-handle:${string}`\n | `edge-endpoint:${string}`\n | (string & {});\n /**\n * Drag-handle gating (set by adapters from `data-flow-drag-handle`\n * markers): when the entity declares a handle, drags only start from\n * presses inside it — e.g. a group that is dragged by its content\n * block but not by its children area.\n */\n entityHasDragHandle?: boolean;\n pressedDragHandle?: boolean;\n }\n | {\n kind: 'port';\n nodeId: string;\n portName: string;\n portId?: string;\n /** `inspect` addresses the port without starting a connection gesture. */\n interaction?: 'connect' | 'inspect';\n }\n | { kind: 'none' };\n\nexport type FlowPointerInputEvent = {\n kind: 'pointer.down' | 'pointer.move' | 'pointer.up' | 'pointer.cancel';\n pointerId: number;\n pointerType: 'mouse' | 'pen' | 'touch';\n /** Pressed button for down events (0 left, 1 middle); -1 for moves. */\n button: number;\n /** Native click count from PointerEvent.detail; 2 means double-click. */\n detail?: number;\n /** Pointer position in canvas (graph/world) coordinates. */\n point: Point;\n /** Pointer position in container-relative screen pixels. */\n screenPoint: Point;\n target: FlowInputTarget;\n modifiers: FlowInputModifiers;\n};\n\nexport type FlowPinchInputEvent = {\n kind: 'pinch.start' | 'pinch.move' | 'pinch.end';\n /** Pinch center in canvas (graph/world) coordinates. */\n center: Point;\n /** Pinch center in container-relative screen pixels. */\n screenCenter: Point;\n /** Distance between the first two active touch pointers in screen pixels. */\n distance: number;\n pointerCount: number;\n modifiers: FlowInputModifiers;\n};\n\nexport type FlowWheelInputEvent = {\n kind: 'wheel';\n deltaX: number;\n deltaY: number;\n /** WheelEvent.deltaMode: 0 pixels, 1 lines, 2 pages. */\n deltaMode: number;\n point: Point;\n screenPoint: Point;\n target: FlowInputTarget;\n modifiers: FlowInputModifiers;\n};\n\nexport type FlowKeyInputEvent = {\n kind: 'key.down' | 'key.up';\n key: string;\n /** True when the event originated from a text input/contenteditable. */\n editableTarget: boolean;\n modifiers: FlowInputModifiers;\n};\n\nexport type FlowInputEvent =\n | FlowPointerInputEvent\n | FlowPinchInputEvent\n | FlowWheelInputEvent\n | FlowKeyInputEvent;\n\n\n// Commands\n\n\ntype FlowTriggerMap = FlowStore['trigger'];\nexport type FlowTriggerName = keyof FlowTriggerMap & string;\n\nexport type FlowTriggerCommand = {\n type: 'trigger';\n name: FlowTriggerName;\n params?: unknown;\n};\n\nexport type FlowCommand =\n | FlowTriggerCommand\n | { type: 'preventDefault' }\n | { type: 'stopPropagation' };\n\n/** Typed constructor for trigger commands. */\nexport function trigger<K extends FlowTriggerName>(\n name: K,\n ...params: Parameters<FlowTriggerMap[K]>\n): FlowTriggerCommand {\n return { type: 'trigger', name, params: params[0] };\n}\n\nexport const preventDefault: FlowCommand = { type: 'preventDefault' };\n\n\n// Modes & sessions\n\n\nexport type FlowInputModeContext = {\n /** Current store snapshot context. */\n context: FlowStoreContext;\n /** Engine for read-only queries (hit info, behavior config). */\n engine: FlowEngine;\n /** Runtime-tracked transient input state (lives outside the store). */\n input: { panKeyHeld: boolean; /** @deprecated Use panKeyHeld. */ spaceHeld: boolean };\n};\n\nexport type FlowSessionResult = {\n commands?: FlowCommand[];\n /** 'continue' (default) keeps the session; 'end' terminates it. */\n status?: 'continue' | 'end';\n};\n\nexport type FlowInputSessionHandlers = {\n /** Receives subsequent events for the session's pointer. */\n update: (\n event: FlowInputEvent,\n ctx: FlowInputModeContext,\n ) => FlowSessionResult | void;\n /** Called when the runtime cancels the session (dispose, external cancel). */\n cancel?: (ctx: FlowInputModeContext) => FlowCommand[] | void;\n};\n\nexport type FlowInputReaction = {\n commands?: FlowCommand[];\n /** Begin an exclusive session that receives subsequent events. */\n session?: FlowInputSessionHandlers;\n};\n\nexport type FlowInputMode = {\n id: string;\n /** Higher priority runs earlier. Default 0. */\n priority?: number;\n /**\n * Inspect an event and either claim it (return a reaction — the event is\n * consumed and lower-priority modes are skipped) or pass (return null).\n */\n start: (\n event: FlowInputEvent,\n ctx: FlowInputModeContext,\n ) => FlowInputReaction | null | undefined | void;\n};\n\n\n// Runtime\n\n\nexport type FlowInputEffects = {\n /** The adapter should call event.preventDefault(). */\n preventDefault: boolean;\n /** The adapter should call event.stopPropagation(). */\n stopPropagation: boolean;\n /** A session began on this event — adapters should capture the pointer. */\n sessionStarted: boolean;\n /** The active session ended — adapters should release the pointer. */\n sessionEnded: boolean;\n /** Id of the mode that handled the event, or null if unhandled. */\n handledBy: string | null;\n};\n\nexport type FlowInputRuntimeOptions = {\n store: FlowStore;\n engine: FlowEngine;\n /**\n * Input modes, or a resolver from store context (so the active set can\n * follow `context.mode`). Defaults to `defaultModesForContext`: the\n * interactive set, or the readonly set when `context.mode === 'readonly'`.\n */\n modes?: FlowInputMode[] | ((context: FlowStoreContext) => FlowInputMode[]);\n /** Keymap used by the built-in runtime state such as panActivation. */\n keymap?: Partial<FlowKeymap>;\n /** Profile policies resolved for the current mode. */\n policies?: FlowPolicies | ((context: FlowStoreContext) => FlowPolicies);\n};\n\nexport type FlowInputRuntime = {\n /** Feed one normalized event; apply resulting commands to the store. */\n send: (event: FlowInputEvent) => FlowInputEffects;\n /** Reconcile pending input after an adapter changes its mode set. */\n reconcileModes: () => void;\n /** Cancel the active session, if any (applies its cancel commands). */\n cancelSession: () => void;\n /** Id of the mode owning the active session, or null. */\n getActiveSession: () => string | null;\n};\n\nexport function createFlowInputRuntime(\n options: FlowInputRuntimeOptions,\n): FlowInputRuntime {\n const { store, engine } = options;\n const resolveModes: (context: FlowStoreContext) => FlowInputMode[] =\n typeof options.modes === 'function'\n ? options.modes\n : options.modes\n ? () => options.modes as FlowInputMode[]\n : (context) => defaultModesForContext(context, options.keymap);\n\n const keymap = resolveKeymap(options.keymap);\n const input = { panKeyHeld: false, spaceHeld: false };\n let session: {\n handlers: FlowInputSessionHandlers;\n modeId: string;\n pointerId: number | null;\n } | null = null;\n\n function modeContext(): FlowInputModeContext {\n return { context: store.getSnapshot().context, engine, input };\n }\n\n function apply(\n commands: FlowCommand[] | void | undefined,\n effects: FlowInputEffects,\n ): void {\n if (!commands) return;\n for (const command of commands) {\n if (command.type === 'preventDefault') {\n effects.preventDefault = true;\n } else if (command.type === 'stopPropagation') {\n effects.stopPropagation = true;\n } else {\n if (!isInputCommandAllowed(command.name, store.getSnapshot().context)) {\n continue;\n }\n const fire = (\n store.trigger as Record<string, (params?: unknown) => void>\n )[command.name];\n fire?.(command.params);\n }\n }\n }\n\n function isInputCommandAllowed(\n name: FlowTriggerName,\n context: FlowStoreContext,\n ): boolean {\n const policies = typeof options.policies === 'function'\n ? options.policies(context)\n : options.policies ?? {};\n const mutating: readonly FlowTriggerName[] = [\n 'createNode', 'deleteNode', 'updateNode', 'updateNodeData',\n 'createEdge', 'deleteEdge', 'deleteEntities', 'updateEdge',\n 'updateEdgeData', 'deleteSelected', 'reparentNode', 'dragStart',\n 'dragMove', 'dragEnd', 'commitDrag', 'resizeStart', 'resizeMove',\n 'resizeEnd', 'reconnectEdge', 'moveNodes', 'undo', 'redo',\n 'connectionStart', 'connectionMove', 'connectionEnd',\n 'collapseNode', 'expandNode',\n ];\n if (mutating.includes(name) && policies.canEdit === false) return false;\n if (\n ['deleteNode', 'deleteEdge', 'deleteEntities', 'deleteSelected'].includes(name) &&\n policies.canDelete === false\n ) return false;\n if (\n ['dragStart', 'dragMove', 'dragEnd', 'commitDrag', 'moveNodes'].includes(name) &&\n policies.canMove === false\n ) return false;\n if (name.startsWith('resize') && policies.canResize === false) return false;\n if (\n ['connectionStart', 'connectionMove', 'connectionEnd'].includes(name) &&\n policies.canConnect === false\n ) return false;\n if (name === 'reconnectEdge' && policies.canReconnect === false) return false;\n if (name === 'reparentNode' && policies.canReparent === false) return false;\n if (name === 'createNode' || name === 'createEdge') {\n if (policies.canCreate === false) return false;\n }\n if (name === 'undo' && policies.canUndo === false) return false;\n if (name === 'redo' && policies.canRedo === false) return false;\n if (\n ['panStart', 'pan', 'panEnd', 'panBy', 'setViewport'].includes(name) &&\n policies.canPan === false\n ) return false;\n if (['zoomTo', 'zoomBy'].includes(name) && policies.canZoom === false) return false;\n if (['select', 'selectAll'].includes(name) && policies.canSelect === false) return false;\n if (name === 'focus' && policies.canFocus === false) return false;\n if (name === 'setHover' && policies.canHover === false) return false;\n return true;\n }\n\n function cancelPendingConnection(previous: FlowStoreContext): void {\n const current = store.getSnapshot().context;\n if (\n previous.connectionClickStartHandle &&\n current.connectionClickStartHandle === previous.connectionClickStartHandle &&\n (previous.connection?.[connectionLifetime]\n ? current.connection?.[connectionLifetime] === previous.connection[connectionLifetime]\n : current.connection === previous.connection)\n ) {\n store.trigger.cancelConnection();\n }\n }\n\n function reconcileModes(): void {\n const context = store.getSnapshot().context;\n if (\n !session &&\n context.connectionClickStartHandle &&\n !resolveModes(context).some((mode) => mode.id === 'connect')\n ) {\n store.trigger.cancelConnection();\n }\n }\n\n function send(event: FlowInputEvent): FlowInputEffects {\n const effects: FlowInputEffects = {\n preventDefault: false,\n stopPropagation: false,\n sessionStarted: false,\n sessionEnded: false,\n handledBy: null,\n };\n\n if (\n session &&\n event.kind === 'key.down' &&\n !event.editableTarget &&\n matchesKeyBinding(event, keymap.cancel)\n ) {\n const previous = store.getSnapshot().context;\n const commands = session.handlers.cancel?.(modeContext());\n effects.handledBy = session.modeId;\n effects.sessionEnded = true;\n session = null;\n apply(commands ?? undefined, effects);\n cancelPendingConnection(previous);\n return effects;\n }\n\n // Built-in transient state: pan activation key tracking.\n if (event.kind === 'key.down' && !event.editableTarget && matchesKeyBinding(event, keymap.panActivation)) {\n input.panKeyHeld = true;\n input.spaceHeld = true;\n } else if (event.kind === 'key.up' && matchesKeyBinding(event, keymap.panActivation)) {\n input.panKeyHeld = false;\n input.spaceHeld = false;\n }\n\n const isPointer =\n event.kind === 'pointer.down' ||\n event.kind === 'pointer.move' ||\n event.kind === 'pointer.up' ||\n event.kind === 'pointer.cancel';\n const isPinch =\n event.kind === 'pinch.start' ||\n event.kind === 'pinch.move' ||\n event.kind === 'pinch.end';\n\n if (session && (isPointer || isPinch)) {\n if (isPinch) {\n const result = session.handlers.update(event, modeContext());\n apply(result?.commands, effects);\n effects.handledBy = session.modeId;\n if (result?.status === 'end') {\n session = null;\n effects.sessionEnded = true;\n }\n return effects;\n }\n const pointer = event as FlowPointerInputEvent;\n if (\n session.pointerId === null ||\n pointer.pointerId === session.pointerId\n ) {\n const result = session.handlers.update(event, modeContext());\n apply(result?.commands, effects);\n effects.handledBy = session.modeId;\n if (result?.status === 'end') {\n session = null;\n effects.sessionEnded = true;\n }\n return effects;\n }\n // A second pointer while a session is active: swallow new gestures.\n if (event.kind === 'pointer.down') {\n effects.handledBy = session.modeId;\n return effects;\n }\n return effects;\n }\n\n const ctx = modeContext();\n const modes = [...resolveModes(ctx.context)].sort(\n (a, b) => (b.priority ?? 0) - (a.priority ?? 0),\n );\n for (const mode of modes) {\n const reaction = mode.start(event, ctx);\n if (!reaction) continue;\n apply(reaction.commands, effects);\n effects.handledBy = mode.id;\n if (reaction.session) {\n session = {\n handlers: reaction.session,\n modeId: mode.id,\n pointerId: isPointer\n ? (event as FlowPointerInputEvent).pointerId\n : null,\n };\n effects.sessionStarted = true;\n }\n break;\n }\n return effects;\n }\n\n function cancelSession(): void {\n const previous = store.getSnapshot().context;\n if (!session) {\n cancelPendingConnection(previous);\n return;\n }\n const effects: FlowInputEffects = {\n preventDefault: false,\n stopPropagation: false,\n sessionStarted: false,\n sessionEnded: true,\n handledBy: session.modeId,\n };\n const commands = session.handlers.cancel?.(modeContext());\n session = null;\n apply(commands ?? undefined, effects);\n cancelPendingConnection(previous);\n }\n\n return {\n send,\n reconcileModes,\n cancelSession,\n getActiveSession: () => session?.modeId ?? null,\n };\n}\n\n// Re-exported here to keep `defaultModesForContext` colocated with the\n// runtime while mode implementations live in ./modes.\nimport {\n defaultInputModes,\n defaultInputModesForKeymap,\n readonlyInputModes,\n readonlyInputModesForKeymap,\n} from './modes';\nimport type { FlowPolicies, FlowProfile } from '../profile';\nimport { calcAutoPan } from '../spatial';\n\n/** Default mode resolution: follow the store's `context.mode`. */\nexport function defaultModesForContext(\n context: FlowStoreContext,\n keymap?: Partial<FlowKeymap>,\n): FlowInputMode[] {\n if (keymap) {\n return context.mode === 'readonly'\n ? readonlyInputModesForKeymap(keymap)\n : defaultInputModesForKeymap(keymap);\n }\n return context.mode === 'readonly' ? readonlyInputModes : defaultInputModes;\n}\n\n/**\n * Mode resolution driven by a store profile: the active store mode's\n * `input.modes` wins, then the profile-level `input.modes`, then the\n * built-in defaults.\n */\nexport function profileModesForContext(\n profile: FlowProfile,\n): (context: FlowStoreContext) => FlowInputMode[] {\n return (context) => {\n const mode = profile.modes[context.mode]\n ? context.mode\n : profile.defaultMode;\n return (\n profile.modes[mode]?.input?.modes ??\n profile.input?.modes ??\n defaultModesForContext(context)\n );\n };\n}\n\nexport function profilePoliciesForContext(\n profile: FlowProfile,\n): (context: FlowStoreContext) => FlowPolicies {\n return (context) => {\n const mode = profile.modes[context.mode]\n ? context.mode\n : profile.defaultMode;\n return {\n ...profile.policies,\n ...profile.modes[mode]?.policies,\n };\n };\n}\n\n/**\n * Per-frame, pointer-driven auto-pan step while a drag, connection, or resize\n * gesture is near the container edge. Returns the `calcAutoPan` screen-space\n * delta (negate it for `panBy`), or null when auto-pan should not run. Adapters\n * call this from a frame ticker while a gesture session is active and re-send\n * the stationary pointer afterwards so the dragged entity follows the panned\n * canvas.\n */\nexport function getAutoPanDelta(\n context: FlowStoreContext,\n screenPoint: Point,\n /**\n * Retained for source compatibility. Auto-pan is intentionally driven by the\n * pointer position, not by resolved entity bounds.\n */\n engine?: FlowEngine,\n): Point | null {\n if (!context.autoPanOnDrag) return null;\n if (\n context.canvasState !== 'dragging' &&\n context.canvasState !== 'connecting' &&\n context.canvasState !== 'resizing'\n ) {\n return null;\n }\n const size = context.viewportSize;\n if (size.width === 0 || size.height === 0) return null;\n const delta = calcAutoPan(\n screenPoint,\n size,\n context.autoPanThreshold,\n context.autoPanSpeed,\n );\n if (delta.x === 0 && delta.y === 0) return null;\n\n // Keep this policy pointer-driven. The pointer remains at the edge while the\n // canvas pans, so every animation frame must continue returning a delta even\n // when entity bounds are clamped or temporarily lag behind the gesture.\n void engine;\n return delta;\n}\n\nexport {\n defaultInputModes,\n defaultInputModesForKeymap,\n readonlyInputModes,\n readonlyInputModesForKeymap,\n keyboardMode,\n keyboardNavMode,\n doubleClickZoomMode,\n wheelMode,\n pinchMode,\n panMode,\n connectMode,\n portPressMode,\n reconnectMode,\n entityPressMode,\n boxSelectMode,\n panePressMode,\n hoverMode,\n} from './modes';\nexport type {\n ConnectModeOptions,\n ReconnectModeOptions,\n BoxSelectModeOptions,\n ReparentDecision,\n ReparentDropContext,\n ReparentOptions,\n} from './modes';\n","import type { FlowStore, FlowStoreContext } from './store';\nimport type { FlowEdge } from './types';\nimport {\n indexChildren,\n indexEdgeAdjacency,\n indexNodes,\n indexEdges,\n} from './graph-index';\n\n// Entity-change notifier\n//\n// One store subscription that diffs consecutive snapshots and notifies\n// per-entity listeners in O(changed) instead of O(listeners). Immer's\n// structural sharing makes the diff cheap and precise: an entity's object\n// identity changes exactly when the entity changed, so dragging one node\n// notifies that node and its incident edges — not the other N thousand\n// mounted entity views.\n//\n// Global fallbacks remain for mode/configuration/collapse changes. Gesture\n// boundaries and snap-line drags instead notify the selected cohort, its\n// hierarchy, and affected routes.\n//\n// Limitation: custom `visible` config predicates or engine `isVisible` hooks\n// that read context fields other than `mode` are not tracked — views whose\n// visibility depends on such predicates should subscribe via a plain store\n// subscription instead.\n\nexport type FlowEntityChangeNotifier = {\n /** Listen for changes that may affect the entity with this id. */\n subscribe(id: string, listener: () => void): () => void;\n /** Detach the underlying store subscription and drop all listeners. */\n destroy(): void;\n};\n\nexport type FlowEntityChangeNotifierOptions = {\n getEdgeDependents?: (edgeId: string) => Iterable<string>;\n};\n\nfunction adjacency(edges: FlowEdge[]): Map<string, FlowEdge[]> {\n return indexEdgeAdjacency(edges).byNode;\n}\n\nfunction computeDirty(\n prev: FlowStoreContext,\n next: FlowStoreContext,\n options: FlowEntityChangeNotifierOptions,\n dragDirtyIds?: ReadonlySet<string>,\n): Set<string> | 'all' {\n if (next.mode !== prev.mode) return 'all';\n // Runtime reconfigure (e.g. swapping the edge router / engine options) bumps\n // configRevision without touching the graph; it can change every entity's\n // derived rendering, so re-notify all per-entity subscribers.\n if (next.configRevision !== prev.configRevision) return 'all';\n // Collapsing/expanding a group flips descendant visibility and reshapes the\n // group's derived bounds (and reroutes boundary edges to proxies) without a\n // graph mutation — re-notify every entity.\n if (next.collapsedNodeIds !== prev.collapsedNodeIds) return 'all';\n const dirty = new Set<string>();\n const markEdge = (edgeId: string) => {\n dirty.add(edgeId);\n for (const dependentId of options.getEdgeDependents?.(edgeId) ?? []) {\n dirty.add(dependentId);\n }\n };\n if (next.routingRevision !== prev.routingRevision) {\n for (const edge of next.graph.edges) dirty.add(edge.id);\n }\n const markIncidentEdges = (nodeId: string, edges: FlowEdge[]) => {\n const incident = adjacency(edges).get(nodeId);\n if (incident) for (const edge of incident) markEdge(edge.id);\n };\n // Group hierarchy: a changed node also changes the derived bounds of every\n // ancestor group, so mark the parent chain (and its incident edges) dirty.\n const markAncestors = (node: { parentId?: string | null }) => {\n const nextIndex = indexNodes(next.graph.nodes);\n const seen = new Set<string>();\n let parentId = node.parentId ?? null;\n while (parentId && !seen.has(parentId)) {\n seen.add(parentId);\n dirty.add(parentId);\n markIncidentEdges(parentId, next.graph.edges);\n parentId = nextIndex.get(parentId)?.parentId ?? null;\n }\n };\n\n // `dragRevision` identifies the one hot transition whose exact affected\n // cohort was indexed at the gesture boundary. Avoid diffing both graph\n // arrays on every pointer frame; non-drag graph mutations retain the full\n // structural diff below.\n if (next.dragRevision !== prev.dragRevision && dragDirtyIds) {\n return new Set(dragDirtyIds);\n }\n\n // Gesture boundaries change transient styling only for their cohort. Pan,\n // box-selection, and connection state do not alter entity render state.\n if (\n next.canvasState !== prev.canvasState &&\n (next.canvasState === 'dragging' || prev.canvasState === 'dragging')\n ) {\n if (prev.canvasState === 'dragging' && dragDirtyIds) {\n // Imperative observers own transient geometry during the gesture. Wake\n // its exact affected cohort on exit so declarative consumers reconcile\n // to the committed node, label, and path data.\n for (const id of dragDirtyIds) dirty.add(id);\n } else {\n for (const id of new Set([...prev.selection, ...next.selection])) {\n dirty.add(id);\n }\n }\n }\n\n // Snap offsets move the selected cohort, its hierarchy, and affected paths;\n // target nodes remain fixed and do not need entity notifications.\n if (next.enableSnapLines && next.canvasState === 'dragging') {\n const nodes = indexNodes(next.graph.nodes);\n const edges = indexEdges(next.graph.edges);\n for (const id of next.selection) {\n dirty.add(id);\n const node = nodes.get(id);\n if (node) {\n markIncidentEdges(id, next.graph.edges);\n markAncestors(node);\n } else if (edges.has(id)) {\n markEdge(id);\n }\n }\n }\n\n if (next.layoutAnimation.offsets !== prev.layoutAnimation.offsets) {\n const prevNodes = indexNodes(prev.graph.nodes);\n const nextNodes = indexNodes(next.graph.nodes);\n const ids = new Set([\n ...prev.layoutAnimation.offsets.keys(),\n ...next.layoutAnimation.offsets.keys(),\n ]);\n for (const id of ids) {\n const before = prev.layoutAnimation.offsets.get(id);\n const after = next.layoutAnimation.offsets.get(id);\n if (before?.x === after?.x && before?.y === after?.y) continue;\n const node = nextNodes.get(id) ?? prevNodes.get(id);\n if (node) {\n dirty.add(id);\n markIncidentEdges(id, next.graph.edges);\n markAncestors(node);\n } else {\n markEdge(id);\n const edge =\n indexEdges(next.graph.edges).get(id) ??\n indexEdges(prev.graph.edges).get(id);\n if (edge) {\n const source = nextNodes.get(edge.sourceId) ?? prevNodes.get(edge.sourceId);\n const target = nextNodes.get(edge.targetId) ?? prevNodes.get(edge.targetId);\n if (source?.group) dirty.add(source.id);\n if (target?.group) dirty.add(target.id);\n markAncestors(source ?? {});\n markAncestors(target ?? {});\n }\n }\n }\n }\n\n if (next.graph.nodes !== prev.graph.nodes) {\n const prevIndex = indexNodes(prev.graph.nodes);\n const nextIndex = indexNodes(next.graph.nodes);\n for (const node of next.graph.nodes) {\n const before = prevIndex.get(node.id);\n if (before !== node) {\n dirty.add(node.id);\n markIncidentEdges(node.id, next.graph.edges);\n markAncestors(node);\n // Reparenting: the previous parent chain shrinks too.\n if (before && (before.parentId ?? null) !== (node.parentId ?? null)) {\n markAncestors(before);\n }\n }\n }\n for (const node of prev.graph.nodes) {\n if (!nextIndex.has(node.id)) {\n dirty.add(node.id);\n markIncidentEdges(node.id, prev.graph.edges);\n markAncestors(node);\n }\n }\n }\n\n if (next.graph.edges !== prev.graph.edges) {\n const prevIndex = indexEdges(prev.graph.edges);\n const nextIndex = indexEdges(next.graph.edges);\n const nodeIndex = indexNodes(next.graph.nodes);\n // A changed edge (e.g. a dragged label) can change the derived bounds of\n // the group containing it — dirty both endpoints' ancestor chains.\n const markEndpointAncestors = (edge: FlowEdge) => {\n const source = nodeIndex.get(edge.sourceId);\n const target = nodeIndex.get(edge.targetId);\n markAncestors(source ?? {});\n markAncestors(target ?? {});\n // The owner can be an endpoint itself (edge into its own descendant),\n // but only group endpoints derive bounds from contained labels.\n if (source?.group) dirty.add(source.id);\n if (target?.group) dirty.add(target.id);\n };\n for (const edge of next.graph.edges) {\n if (prevIndex.get(edge.id) !== edge) {\n markEdge(edge.id);\n markEndpointAncestors(edge as FlowEdge);\n }\n }\n for (const edge of prev.graph.edges) {\n if (!nextIndex.has(edge.id)) {\n markEdge(edge.id);\n markEndpointAncestors(edge as FlowEdge);\n }\n }\n }\n\n if (next.selection !== prev.selection) {\n for (const id of next.selection) {\n if (!prev.selection.has(id)) dirty.add(id);\n }\n for (const id of prev.selection) {\n if (!next.selection.has(id)) dirty.add(id);\n }\n }\n\n if (next.hoveredEntityIds !== prev.hoveredEntityIds) {\n for (const id of next.hoveredEntityIds) {\n if (!prev.hoveredEntityIds.has(id)) dirty.add(id);\n }\n for (const id of prev.hoveredEntityIds) {\n if (!next.hoveredEntityIds.has(id)) dirty.add(id);\n }\n }\n\n if (next.highlights !== prev.highlights) {\n const kinds = new Set([...prev.highlights.keys(), ...next.highlights.keys()]);\n for (const kind of kinds) {\n const before = prev.highlights.get(kind);\n const after = next.highlights.get(kind);\n if (before === after) continue;\n // Bucket changed: anything in either version may have different meta.\n if (before) for (const id of before.keys()) dirty.add(id);\n if (after) for (const id of after.keys()) dirty.add(id);\n }\n }\n\n const idPairs: Array<[string | null, string | null]> = [\n [prev.draggedEntityId, next.draggedEntityId],\n [prev.focusedEntityId, next.focusedEntityId],\n [prev.resizingEntityId, next.resizingEntityId],\n ];\n for (const [before, after] of idPairs) {\n if (before !== after) {\n if (before) dirty.add(before);\n if (after) dirty.add(after);\n }\n }\n\n // An in-flight resize changes the resized node's bounds (and its edges'\n // paths) on every move without touching the node object.\n if (next.resizeCorners !== prev.resizeCorners && next.resizingEntityId) {\n dirty.add(next.resizingEntityId);\n markIncidentEdges(next.resizingEntityId, next.graph.edges);\n }\n\n return dirty;\n}\n\nfunction dirtyIdsForDrag(\n context: FlowStoreContext,\n options: FlowEntityChangeNotifierOptions,\n): Set<string> {\n const dirty = new Set<string>();\n const nodes = indexNodes(context.graph.nodes);\n const edges = indexEdges(context.graph.edges);\n const children = indexChildren(context.graph.nodes);\n const markEdge = (id: string) => {\n dirty.add(id);\n for (const dependentId of options.getEdgeDependents?.(id) ?? []) {\n dirty.add(dependentId);\n }\n };\n const markIncident = (id: string) => {\n for (const edge of adjacency(context.graph.edges).get(id) ?? []) {\n markEdge(edge.id);\n }\n };\n const markAncestors = (id: string) => {\n const seen = new Set<string>();\n let parentId = nodes.get(id)?.parentId ?? null;\n while (parentId && !seen.has(parentId)) {\n seen.add(parentId);\n dirty.add(parentId);\n markIncident(parentId);\n parentId = nodes.get(parentId)?.parentId ?? null;\n }\n };\n const markNodeSubtree = (id: string, seen = new Set<string>()) => {\n if (seen.has(id)) return;\n seen.add(id);\n dirty.add(id);\n markIncident(id);\n markAncestors(id);\n for (const child of children.get(id) ?? []) {\n markNodeSubtree(child.id, seen);\n }\n };\n\n for (const id of context.selection) {\n if (nodes.has(id)) markNodeSubtree(id);\n else {\n const edge = edges.get(id);\n if (!edge) continue;\n markEdge(id);\n const source = nodes.get(edge.sourceId);\n const target = nodes.get(edge.targetId);\n if (source?.group) dirty.add(source.id);\n if (target?.group) dirty.add(target.id);\n markAncestors(edge.sourceId);\n markAncestors(edge.targetId);\n }\n }\n return dirty;\n}\n\nexport function createEntityChangeNotifier(\n store: FlowStore,\n options: FlowEntityChangeNotifierOptions = {},\n): FlowEntityChangeNotifier {\n const listeners = new Map<string, Set<() => void>>();\n let prev = store.getSnapshot().context;\n let activeDragDirtyIds: Set<string> | undefined;\n\n const subscription = store.subscribe((snapshot) => {\n const next = snapshot.context;\n if (next === prev) return;\n if (\n next.canvasState === 'dragging' &&\n (prev.canvasState !== 'dragging' || next.selection !== prev.selection)\n ) {\n activeDragDirtyIds = dirtyIdsForDrag(next, options);\n }\n const dirty = computeDirty(prev, next, options, activeDragDirtyIds);\n if (dirty !== 'all' && next.routingRevision !== prev.routingRevision) {\n // Folded edges have synthetic ids outside the authored edge array.\n const nodes = indexNodes(next.graph.nodes);\n for (const id of listeners.keys()) if (!nodes.has(id)) dirty.add(id);\n }\n if (\n next.canvasState === 'dragging' &&\n next.dragRevision === prev.dragRevision &&\n (next.graph.nodes !== prev.graph.nodes || next.graph.edges !== prev.graph.edges)\n ) {\n // A non-drag graph mutation occurred during the gesture; refresh the\n // next frame's exact cohort after the full structural diff above.\n activeDragDirtyIds = dirtyIdsForDrag(next, options);\n } else if (next.canvasState !== 'dragging') {\n activeDragDirtyIds = undefined;\n }\n prev = next;\n\n if (dirty === 'all') {\n for (const set of listeners.values()) {\n for (const listener of [...set]) listener();\n }\n return;\n }\n for (const id of dirty) {\n const set = listeners.get(id);\n if (set) {\n for (const listener of [...set]) listener();\n }\n }\n });\n\n return {\n subscribe(id, listener) {\n let set = listeners.get(id);\n if (!set) {\n set = new Set();\n listeners.set(id, set);\n }\n set.add(listener);\n return () => {\n set.delete(listener);\n if (set.size === 0) {\n listeners.delete(id);\n }\n };\n },\n destroy() {\n subscription.unsubscribe();\n listeners.clear();\n },\n };\n}\n"],"mappings":";;;;;AAEA,MAAM,mCAAmB,IAAI,IAAgB;CAC3C;CACA;CACA;AACF,CAAC;AACD,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;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