@statelyai/flow 0.14.0 → 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.
Files changed (115) hide show
  1. package/README.md +2 -1
  2. package/dist/esm/index.d.ts +5 -2
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +19 -14
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/layout/dagre.d.ts +2 -1
  7. package/dist/esm/layout/dagre.d.ts.map +1 -0
  8. package/dist/esm/layout/dagre.js +2 -0
  9. package/dist/esm/layout/dagre.js.map +1 -0
  10. package/dist/esm/layout/elk.d.ts +2 -1
  11. package/dist/esm/layout/elk.d.ts.map +1 -0
  12. package/dist/esm/layout/elk.js +2 -0
  13. package/dist/esm/layout/elk.js.map +1 -0
  14. package/dist/esm/layout/stately.d.ts +2 -1
  15. package/dist/esm/layout/stately.d.ts.map +1 -0
  16. package/dist/esm/layout/stately.js +2 -0
  17. package/dist/esm/layout/stately.js.map +1 -0
  18. package/dist/esm/shared.d.ts +2 -1
  19. package/dist/esm/shared.d.ts.map +1 -0
  20. package/dist/esm/shared.js +2 -0
  21. package/dist/esm/shared.js.map +1 -0
  22. package/package.json +4 -3
  23. package/src/__fixtures__/nested.ts +106 -0
  24. package/src/appearances.test.ts +428 -0
  25. package/src/appearances.ts +144 -0
  26. package/src/authoritative-route.ts +14 -0
  27. package/src/changeSet.test.ts +132 -0
  28. package/src/changeSet.ts +337 -0
  29. package/src/config.ts +41 -0
  30. package/src/configure.test.ts +212 -0
  31. package/src/connection-lifetime.ts +1 -0
  32. package/src/connectionPreview.test.ts +102 -0
  33. package/src/connectionPreview.ts +82 -0
  34. package/src/content.ts +203 -0
  35. package/src/createFlow.fit-frame.test.ts +256 -0
  36. package/src/createFlow.modern.test.ts +743 -0
  37. package/src/createFlow.test.ts +632 -0
  38. package/src/createFlow.ts +3463 -0
  39. package/src/createFlow.view.test.ts +212 -0
  40. package/src/createFlow.viewport-controls.test.ts +221 -0
  41. package/src/edge-geometry.ts +318 -0
  42. package/src/engine.cache.test.ts +728 -0
  43. package/src/engine.hierarchy.test.ts +1023 -0
  44. package/src/engine.test.ts +1965 -0
  45. package/src/engine.ts +3385 -0
  46. package/src/entity-changes.test.ts +309 -0
  47. package/src/entity-changes.ts +395 -0
  48. package/src/examples/flow-based-math.test.ts +25 -0
  49. package/src/examples/flow-based-math.ts +210 -0
  50. package/src/external-edit.test.ts +337 -0
  51. package/src/external-edit.ts +358 -0
  52. package/src/factories.test.ts +104 -0
  53. package/src/factories.ts +70 -0
  54. package/src/geometry.ts +13 -0
  55. package/src/graph-index.test.ts +56 -0
  56. package/src/graph-index.ts +194 -0
  57. package/src/hierarchy.test.ts +175 -0
  58. package/src/hierarchy.ts +330 -0
  59. package/src/highlights.test.ts +130 -0
  60. package/src/index.ts +469 -0
  61. package/src/input/index.ts +615 -0
  62. package/src/input/input.test.ts +2577 -0
  63. package/src/input/keymap.ts +111 -0
  64. package/src/input/modes.ts +1715 -0
  65. package/src/input/reparent.test.ts +214 -0
  66. package/src/layout/dagre.ts +138 -0
  67. package/src/layout/elk.ts +1382 -0
  68. package/src/layout/index.ts +12 -0
  69. package/src/layout/layout.test.ts +1248 -0
  70. package/src/layout/shared.ts +260 -0
  71. package/src/layout/stately-globals.d.ts +9 -0
  72. package/src/layout/stately.test.ts +246 -0
  73. package/src/layout/stately.ts +528 -0
  74. package/src/layout-animation.test.ts +223 -0
  75. package/src/layout-contract.test.ts +414 -0
  76. package/src/marker.test.ts +23 -0
  77. package/src/marker.ts +23 -0
  78. package/src/measurement-anchor.test.ts +232 -0
  79. package/src/minimap.test.ts +96 -0
  80. package/src/minimap.ts +137 -0
  81. package/src/nested-fixture.test.ts +178 -0
  82. package/src/port-measurement.test.ts +27 -0
  83. package/src/port-measurements.test.ts +187 -0
  84. package/src/profile.ts +124 -0
  85. package/src/projections.test.ts +103 -0
  86. package/src/projections.ts +295 -0
  87. package/src/render-invalidation.test.ts +62 -0
  88. package/src/render-invalidation.ts +55 -0
  89. package/src/renderer-geometry.test.ts +356 -0
  90. package/src/renderer-transactions.test.ts +234 -0
  91. package/src/routing/avoid.ts +417 -0
  92. package/src/routing/index.test.ts +361 -0
  93. package/src/routing/index.ts +366 -0
  94. package/src/routing/readTracking.test.ts +103 -0
  95. package/src/routing/readTracking.ts +233 -0
  96. package/src/selection-commands.test.ts +355 -0
  97. package/src/serialize.test.ts +167 -0
  98. package/src/serialize.ts +254 -0
  99. package/src/shapes/index.test.ts +45 -0
  100. package/src/shapes/index.ts +142 -0
  101. package/src/snap.test.ts +123 -0
  102. package/src/snap.ts +395 -0
  103. package/src/spatial.test.ts +676 -0
  104. package/src/spatial.ts +457 -0
  105. package/src/store/index.ts +4121 -0
  106. package/src/store.test.ts +2903 -0
  107. package/src/toolbar.test.ts +31 -0
  108. package/src/toolbar.ts +62 -0
  109. package/src/types.test.ts +15 -0
  110. package/src/types.ts +487 -0
  111. package/src/validation.ts +558 -0
  112. package/src/view.ts +172 -0
  113. package/src/viewport/animate.ts +285 -0
  114. package/src/viewport/index.ts +296 -0
  115. package/src/viewport.test.ts +569 -0
@@ -0,0 +1,4121 @@
1
+ import { connectionLifetime } from '../connection-lifetime';
2
+ import { resolveAppearance, appearanceMeasurementId } from '../appearances';
3
+ import { createStore } from '@xstate/store';
4
+ import type { ExtractEvents, StoreExtension, StoreSnapshot } from '@xstate/store';
5
+ import { undoRedo } from '@xstate/store/undo';
6
+ import { produce, enableMapSet, current, isDraft, castDraft } from 'immer';
7
+
8
+ enableMapSet();
9
+ import type {
10
+ AutoLayoutState,
11
+ CanvasState,
12
+ ConnectionState,
13
+ FlowEdge,
14
+ FlowGraph,
15
+ FlowNode,
16
+ FitViewOptions,
17
+ FlowAutoSizeAnchor,
18
+ LabelAnchor,
19
+ Point,
20
+ Rect,
21
+ ResizeHandle,
22
+ SelectionMode,
23
+ Size,
24
+ Viewport,
25
+ ViewportAnimationOptions,
26
+ } from '../types';
27
+ import type { FlowViewScope, FlowViewSelectionPolicy } from '../view';
28
+ import {
29
+ defaultFlowProfile,
30
+ type FlowEventObject,
31
+ type FlowProfile,
32
+ type FlowTransition,
33
+ } from '../profile';
34
+ import { createViewport, viewportForBounds } from '../viewport';
35
+ import {
36
+ getGraphBounds,
37
+ getSelectionBounds,
38
+ rectsIntersect,
39
+ resolvedBounds,
40
+ snappedBounds,
41
+ resolvedSelectionBounds,
42
+ resolvedSize,
43
+ boxToRect,
44
+ snapToGrid,
45
+ constrainViewport,
46
+ rectContains,
47
+ resolvedEdgeLabelBounds,
48
+ resolvedEdgeLabelSize,
49
+ } from '../spatial';
50
+ import { getSnapLines } from '../snap';
51
+ import {
52
+ indexChildren,
53
+ indexEdgePositions,
54
+ indexEdges,
55
+ indexNodePositions,
56
+ indexNodes,
57
+ } from '../graph-index';
58
+ import {
59
+ deriveGroupGeometry,
60
+ fixedGroupGeometry,
61
+ getEdgeOwnerFromIndex,
62
+ getNodeIdsWithDescendants,
63
+ type GroupGeometry,
64
+ } from '../hierarchy';
65
+ import { validateAndCloneGraph } from '../validation';
66
+ import {
67
+ invalidateAuthoritativeEdgePath,
68
+ nodeEndpointGeometryChanged,
69
+ withDerivedGroupAncestors,
70
+ } from '../edge-geometry';
71
+
72
+ // FlowStore
73
+ //
74
+ // XState Store + Immer for immutable updates.
75
+ // All interaction state lives here — engine is purely derived.
76
+
77
+ /**
78
+ * Decides whether an entity is captured by the box-select rectangle.
79
+ * `box` and `bounds` are both in canvas coordinates.
80
+ */
81
+ export type BoxSelectionTest = (box: Rect, bounds: Rect) => boolean;
82
+
83
+ function resolveAutoSizeAnchor(anchor: FlowAutoSizeAnchor | undefined): Point {
84
+ if (anchor === undefined || anchor === 'top-left') return { x: 0, y: 0 };
85
+ if (anchor === 'center') return { x: 0.5, y: 0.5 };
86
+ if (
87
+ !anchor ||
88
+ !Number.isFinite(anchor.x) ||
89
+ !Number.isFinite(anchor.y) ||
90
+ anchor.x < 0 ||
91
+ anchor.x > 1 ||
92
+ anchor.y < 0 ||
93
+ anchor.y > 1
94
+ ) {
95
+ throw new RangeError('autoSizeAnchor must be "top-left", "center", or fractional { x, y }.');
96
+ }
97
+ return anchor;
98
+ }
99
+
100
+ export type FlowStoreContext = {
101
+ /** Host presentation policies; never serialized with authored graph data. */
102
+ appearances?: import("../appearances").FlowAppearances;
103
+ // Graph data
104
+ graph: FlowGraph;
105
+
106
+ // Navigation
107
+ parentNodeId: string | null;
108
+ depth: number | null; // null = unlimited
109
+
110
+ // Viewport
111
+ viewport: Viewport;
112
+ viewportSize: Size;
113
+ /** Persistent screen-space target for fit/center commands; null = full viewport. */
114
+ fitFrame: Rect | null;
115
+ viewportStack: Viewport[];
116
+ minZoom: number;
117
+ maxZoom: number;
118
+ translateExtent: [Point, Point] | null; // pan boundary
119
+ nodeExtent: [Point, Point] | null; // node drag boundary
120
+
121
+ // Selection & focus
122
+ selection: Set<string>;
123
+ selectionBox: [Point, Point] | null; // active box-select corners
124
+ /** Selection snapshot when a box gesture began, so shift-drag adds to it. */
125
+ selectionBoxBase: ReadonlySet<string> | null;
126
+ /**
127
+ * Predicate deciding whether an entity (by its bounds) falls inside the
128
+ * box-select rectangle. Defaults to the `selectionMode` behavior (partial =
129
+ * any overlap, full = fully contained), but apps can supply any rule — e.g.
130
+ * a "≥75% overlap" test — without the package hardcoding the modes.
131
+ */
132
+ boxSelectionTest: BoxSelectionTest | null;
133
+ /** Entities currently under the pointer (driven by the input runtime). */
134
+ hoveredEntityIds: Set<string>;
135
+ /** Group nodes whose descendants are hidden by the engine. */
136
+ collapsedNodeIds: Set<string>;
137
+ /**
138
+ * Semantic highlights: kind → (entity id → metadata). Kinds are
139
+ * user-defined strings; metadata is user-defined (e.g. heatmap weights,
140
+ * colors). Visual-only state — not undoable.
141
+ */
142
+ highlights: FlowHighlights;
143
+ focusedEntityId: string | null;
144
+ measurements: Map<string, Rect>;
145
+ /** Renderer port rectangles in owner-local coordinates. */
146
+ derivedPortMeasurements: Map<string, Rect>;
147
+
148
+ // Interaction
149
+ canvasState: CanvasState;
150
+ draggedEntityId: string | null;
151
+ /** Monotonic signal for exact per-entity drag-frame notification. */
152
+ dragRevision: number;
153
+ dragThreshold: number; // px before drag starts
154
+ /**
155
+ * Constrains where a node may move during drags/keyboard nudges. Receives
156
+ * the node and its proposed absolute position (after extent/group clamps);
157
+ * return an adjusted position, or null/undefined to accept. Drag sessions
158
+ * are pointer-anchored, so constraint clamps never accumulate drift.
159
+ * Example: prevent sibling overlap (see the PreventOverlap story).
160
+ */
161
+ constrainNodeMovement:
162
+ | ((node: FlowNode, proposed: Point, context: FlowStoreContext) => Point | null | undefined)
163
+ | null;
164
+ autoPanOnDrag: boolean;
165
+ autoPanThreshold: number;
166
+ autoPanSpeed: number;
167
+ connection: ConnectionState | null;
168
+ connectOnClick: boolean;
169
+ connectionDragThreshold: number;
170
+ connectionClickStartHandle: { nodeId: string; port: string | null } | null;
171
+ // Pan state (screen-space bookkeeping for pan gesture)
172
+ panOrigin: Point | null;
173
+ panViewportOrigin: Viewport | null;
174
+ /** Default animation applied to viewport commands unless overridden per call. */
175
+ viewportAnimation: ViewportAnimationOptions | null;
176
+
177
+ // Resize state
178
+ resizingEntityId: string | null;
179
+ resizeHandle: ResizeHandle | null;
180
+ /** Two opposite corners during resize: [anchor, moving]. Derived bounds = min/max of these. */
181
+ resizeCorners: [Point, Point] | null;
182
+
183
+ // Profile mode — determines which profile transitions and input config apply
184
+ mode: string;
185
+ selectionMode: SelectionMode;
186
+
187
+ // Grid snapping
188
+ snapToGrid: boolean;
189
+ snapGrid: [number, number]; // [x, y] grid sizes
190
+
191
+ // Entity snap lines (Figma-style alignment guides)
192
+ enableSnapLines: boolean;
193
+ snapThreshold: number; // threshold in screen px (divided by zoom)
194
+ enableSpacingGuides: boolean;
195
+
196
+ // Layout
197
+ autoLayout: AutoLayoutState;
198
+ /** Transient visual offsets for an in-flight layout animation. */
199
+ layoutAnimation: {
200
+ status: 'idle' | 'running';
201
+ offsets: Map<string, Point>;
202
+ };
203
+
204
+ // Presentation
205
+ colorMode: FlowColorMode;
206
+
207
+ /**
208
+ * Default edge label anchor (mirrors the engine's default). Movement
209
+ * planning needs it to know whether a label auto-follows its endpoints
210
+ * (numeric/function anchors) or sits at a fixed position that must be
211
+ * carried along with a rigidly-dragged subtree.
212
+ */
213
+ labelAnchor: LabelAnchor;
214
+
215
+ /**
216
+ * Monotonic counter bumped whenever engine options change at runtime (via
217
+ * `flow.configure({ engine })`). Engine option changes mutate the engine and
218
+ * clear its memo caches but produce no graph/viewport change, so store
219
+ * subscribers (React's `useSyncExternalStore`) would never re-derive. Bumping
220
+ * this emits a fresh context reference so consumers recompute against the
221
+ * newly-configured engine. Visual-only — not undoable.
222
+ */
223
+ configRevision: number;
224
+ /** External router output changed without changing graph geometry or configuration. */
225
+ routingRevision: number;
226
+ };
227
+
228
+ export type FlowColorMode = 'light' | 'dark' | 'system';
229
+
230
+ /** kind → (entity id → metadata) */
231
+ export type FlowHighlights = Map<string, Map<string, unknown>>;
232
+
233
+ export type FlowHighlightEntry = { id: string; meta?: unknown };
234
+
235
+ /**
236
+ * Store creation options.
237
+ *
238
+ * Runtime-updatable through `flow.configure({ store })` / `updateSettings`:
239
+ * drag threshold, movement constraint, auto-pan settings, snap-line settings,
240
+ * box-selection test, and default label anchor. Other options are
241
+ * construct-only or have dedicated runtime events.
242
+ */
243
+ export type FlowStoreOptions = {
244
+ appearances?: import("../appearances").FlowAppearances;
245
+ minZoom?: number;
246
+ maxZoom?: number;
247
+ translateExtent?: [Point, Point] | null;
248
+ nodeExtent?: [Point, Point] | null;
249
+ dragThreshold?: number;
250
+ /** See `FlowStoreContext.constrainNodeMovement`. */
251
+ constrainNodeMovement?: (
252
+ node: FlowNode,
253
+ proposed: Point,
254
+ context: FlowStoreContext
255
+ ) => Point | null | undefined;
256
+ autoPanOnDrag?: boolean;
257
+ autoPanThreshold?: number;
258
+ autoPanSpeed?: number;
259
+ /** Default animation applied to viewport commands unless overridden per call. */
260
+ viewportAnimation?: ViewportAnimationOptions | null;
261
+ snapToGrid?: boolean;
262
+ snapGrid?: [number, number];
263
+ enableSnapLines?: boolean;
264
+ snapThreshold?: number;
265
+ enableSpacingGuides?: boolean;
266
+ connectOnClick?: boolean;
267
+ colorMode?: FlowColorMode;
268
+ /** Default edge label anchor; should mirror the engine's `labelAnchor`. */
269
+ labelAnchor?: LabelAnchor;
270
+ /** See `FlowStoreContext.boxSelectionTest`. */
271
+ boxSelectionTest?: BoxSelectionTest;
272
+ connectionDragThreshold?: number;
273
+ selectionMode?: SelectionMode;
274
+ historyLimit?: number;
275
+ mode?: string;
276
+ profile?: FlowProfile;
277
+ /**
278
+ * Controls what happens to edges when a node is deleted.
279
+ * - 'cascade' (default): delete all edges connected to the node
280
+ * - 'retarget': edges connected to deleted node become self-loops on the other endpoint
281
+ * - function: custom logic — receives graph + node ids to delete, returns { nodes, edges } to keep
282
+ */
283
+ onDeleteNodes?:
284
+ | 'cascade'
285
+ | 'retarget'
286
+ | ((graph: FlowGraph, nodeIds: Set<string>) => { nodes: FlowNode[]; edges: FlowEdge[] });
287
+ };
288
+
289
+ export type FlowRuntimeSettings = Pick<
290
+ FlowStoreOptions,
291
+ | 'dragThreshold'
292
+ | 'constrainNodeMovement'
293
+ | 'autoPanOnDrag'
294
+ | 'autoPanThreshold'
295
+ | 'autoPanSpeed'
296
+ | 'viewportAnimation'
297
+ | 'enableSnapLines'
298
+ | 'snapThreshold'
299
+ | 'enableSpacingGuides'
300
+ | 'boxSelectionTest'
301
+ | 'labelAnchor'
302
+ >;
303
+
304
+ export type LayoutRequestedEvent = {
305
+ algorithm: string;
306
+ graph: FlowGraph;
307
+ };
308
+
309
+ export type ConnectEndTarget =
310
+ | { kind: 'node'; nodeId: string; port: string | null }
311
+ | { kind: 'edge'; edgeId: string }
312
+ | { kind: 'canvas'; position: Point }
313
+ | { kind: 'none' };
314
+
315
+ export type ConnectionEndedEvent = {
316
+ status: 'connected' | 'cancelled' | 'invalid';
317
+ source: { nodeId: string; port: string | null };
318
+ target: ConnectEndTarget;
319
+ connection: ConnectionState;
320
+ reconnectedEdgeId?: string;
321
+ };
322
+
323
+ export type FlowGraphChangedEvent = {
324
+ graph: FlowGraph;
325
+ event: FlowEventObject;
326
+ };
327
+
328
+ export type FlowViewportChangedEvent = {
329
+ viewport: Viewport;
330
+ event: FlowEventObject;
331
+ };
332
+
333
+ export type FlowSelectionChangedEvent = {
334
+ selection: Set<string>;
335
+ event: FlowEventObject;
336
+ };
337
+
338
+ export type FlowViewChangedEvent = {
339
+ scope: FlowViewScope;
340
+ event: FlowEventObject;
341
+ };
342
+
343
+ export type FlowEntitiesDeletedEvent = {
344
+ ids: string[];
345
+ event: FlowEventObject;
346
+ };
347
+
348
+ export type FlowErrorEvent = {
349
+ error: unknown;
350
+ event?: FlowEventObject;
351
+ };
352
+
353
+ export type FlowGestureModifiers = {
354
+ shift: boolean;
355
+ meta: boolean;
356
+ ctrl: boolean;
357
+ alt: boolean;
358
+ };
359
+
360
+ export type FlowDragStartedEvent = {
361
+ ids: string[];
362
+ positions: Record<string, Point>;
363
+ };
364
+
365
+ export type FlowDragMovedEvent = FlowDragStartedEvent & {
366
+ delta: Point;
367
+ };
368
+
369
+ export type FlowDragEndedEvent = FlowDragStartedEvent;
370
+
371
+ export type FlowResizeStartedEvent = {
372
+ id: string;
373
+ handle: ResizeHandle;
374
+ bounds: Rect;
375
+ };
376
+
377
+ export type FlowResizeEndedEvent = {
378
+ id: string;
379
+ bounds: Rect;
380
+ };
381
+
382
+ export type FlowConnectStartedEvent = {
383
+ sourceId: string;
384
+ sourcePort: string | null;
385
+ point: Point;
386
+ };
387
+
388
+ export type FlowConnectMovedEvent = {
389
+ point: Point;
390
+ targetId: string | null;
391
+ targetPort: string | null;
392
+ isValid: boolean;
393
+ invalidReason?: string;
394
+ };
395
+
396
+ export type FlowPaneGestureEvent = {
397
+ point: Point;
398
+ modifiers: FlowGestureModifiers;
399
+ };
400
+
401
+ export type FlowEntityGestureEvent = FlowPaneGestureEvent & {
402
+ id: string;
403
+ };
404
+
405
+ type FlowEmittedPayloadMap = {
406
+ layoutRequested: LayoutRequestedEvent;
407
+ connectionEnded: ConnectionEndedEvent;
408
+ graphChanged: FlowGraphChangedEvent;
409
+ viewportChanged: FlowViewportChangedEvent;
410
+ selectionChanged: FlowSelectionChangedEvent;
411
+ viewChanged: FlowViewChangedEvent;
412
+ entitiesDeleted: FlowEntitiesDeletedEvent;
413
+ dragStarted: FlowDragStartedEvent;
414
+ dragMoved: FlowDragMovedEvent;
415
+ dragEnded: FlowDragEndedEvent;
416
+ resizeStarted: FlowResizeStartedEvent;
417
+ resizeEnded: FlowResizeEndedEvent;
418
+ connectStarted: FlowConnectStartedEvent;
419
+ connectMoved: FlowConnectMovedEvent;
420
+ paneClicked: FlowPaneGestureEvent;
421
+ paneContextMenu: FlowPaneGestureEvent;
422
+ entityClicked: FlowEntityGestureEvent;
423
+ entityDoubleClicked: FlowEntityGestureEvent;
424
+ entityContextMenu: FlowEntityGestureEvent;
425
+ error: FlowErrorEvent;
426
+ };
427
+
428
+ type FlowEventPayloadMap = {
429
+ createNode: { node: FlowNode } & TransactionMetadata;
430
+ deleteNode: { id: string } & TransactionMetadata;
431
+ updateNode: FlowUpdateNodeEvent;
432
+ updateNodeData: { id: string; data: Record<string, unknown> } & TransactionMetadata;
433
+ createEdge: { edge: FlowEdge } & TransactionMetadata;
434
+ deleteEdge: { id: string } & TransactionMetadata;
435
+ deleteEntities: {
436
+ nodeIds?: string[];
437
+ edgeIds?: string[];
438
+ } & TransactionMetadata;
439
+ updateEdge: FlowUpdateEdgeEvent;
440
+ updateEdgeData: { id: string; data: Record<string, unknown> } & TransactionMetadata;
441
+ deleteSelected: undefined;
442
+ setGraph: { graph: FlowGraph };
443
+ replaceGraph: {
444
+ graph: FlowGraph;
445
+ graphChanged?: boolean;
446
+ resetMeasurementIds?: readonly string[];
447
+ layoutAnimationOffsets?: Map<string, Point>;
448
+ } & ReplaceGraphMetadata;
449
+ setLayoutAnimationOffsets: { offsets: Map<string, Point> };
450
+ clearLayoutAnimation: undefined;
451
+ loadDocument: {
452
+ graph: FlowGraph;
453
+ collapsedNodeIds: string[];
454
+ viewport: Viewport;
455
+ } & TransactionMetadata;
456
+ setCollapsedNodes: { ids: string[] };
457
+ reset: undefined;
458
+ reparentNode: { id: string; parentId: string | null } & TransactionMetadata;
459
+ collapseNode: { id: string } & TransactionMetadata;
460
+ expandNode: { id: string } & TransactionMetadata;
461
+ dragStart: { id: string } & TransactionMetadata;
462
+ dragMove: { dx: number; dy: number };
463
+ dragEnd: undefined;
464
+ dragCancel: undefined;
465
+ commitDrag: (TransactionMetadata & { snapOffset?: Point }) | undefined;
466
+ select: { ids: string[]; mode?: 'single' | 'multi' };
467
+ selectAll: undefined;
468
+ clearSelection: undefined;
469
+ selectionBoxStart: { point: Point; mode?: 'single' | 'multi' };
470
+ selectionBoxMove: { point: Point };
471
+ selectionBoxEnd: undefined;
472
+ selectionBoxCancel: undefined;
473
+ focus: { entityId: string };
474
+ clearFocus: undefined;
475
+ setHover: { ids: string[] };
476
+ clearHover: undefined;
477
+ /** Replace one kind's highlight bucket (bulk update, e.g. heatmaps). */
478
+ setHighlights: { kind: string; entries: FlowHighlightEntry[] };
479
+ addHighlights: { kind: string; entries: FlowHighlightEntry[] };
480
+ removeHighlights: { kind: string; ids: string[] };
481
+ clearHighlights: { kind?: string } | undefined;
482
+ updateParentNodeId: { parentNodeId: string | null };
483
+ setViewScope: {
484
+ parentNodeId: string | null;
485
+ depth: number | null;
486
+ selection: FlowViewSelectionPolicy;
487
+ visibleEntityIds: string[];
488
+ };
489
+ setViewport: Viewport;
490
+ setFitFrame: { frame: Rect | null; preserveCenter?: boolean };
491
+ panBy: Point;
492
+ zoomTo: { zoom: number; center: Point };
493
+ zoomBy: { factor: number; center?: Point };
494
+ setMinZoom: { minZoom: number };
495
+ setMaxZoom: { maxZoom: number };
496
+ setDragThreshold: { dragThreshold: number };
497
+ setAutoPanOptions: {
498
+ autoPanOnDrag?: boolean;
499
+ autoPanThreshold?: number;
500
+ autoPanSpeed?: number;
501
+ };
502
+ updateSettings: Partial<FlowRuntimeSettings>;
503
+ configure: Partial<FlowStoreOptions>;
504
+ bumpConfigRevision: undefined;
505
+ bumpRoutingRevision: undefined;
506
+ setTranslateExtent: { extent: [Point, Point] | null };
507
+ setNodeExtent: { extent: [Point, Point] | null };
508
+ updateViewportSize: Size & { preserveCenter?: boolean };
509
+ fitView: FitViewOptions | undefined;
510
+ pushViewport: undefined;
511
+ popViewport: undefined;
512
+ panStart: Point;
513
+ pan: Point;
514
+ panEnd: undefined;
515
+ panCancel: undefined;
516
+ setCanvasState: { state: CanvasState };
517
+ connectionStart: {
518
+ sourceId: string;
519
+ sourcePort: string | null;
520
+ position: Point;
521
+ active?: boolean;
522
+ reconnectingEdgeId?: string | null;
523
+ reconnectingEnd?: 'source' | 'target' | null;
524
+ preview?: boolean;
525
+ };
526
+ connectionMove: {
527
+ position: Point;
528
+ targetId?: string | null;
529
+ targetPort?: string | null;
530
+ isValid?: boolean;
531
+ invalidReason?: string;
532
+ active?: boolean;
533
+ };
534
+ connectionEnd: { target?: ConnectEndTarget; reconnectedEdgeId?: string } | undefined;
535
+ cancelConnection: undefined;
536
+ setConnectionClickStartHandle: { nodeId: string; port: string | null } | null;
537
+ resizeStart: { id: string; handle: ResizeHandle } & TransactionMetadata;
538
+ resizeMove: Point;
539
+ resizeEnd: undefined;
540
+ resizeCancel: undefined;
541
+ paneClicked: FlowPaneGestureEvent;
542
+ paneContextMenu: FlowPaneGestureEvent;
543
+ entityClicked: FlowEntityGestureEvent;
544
+ entityDoubleClicked: FlowEntityGestureEvent;
545
+ entityContextMenu: FlowEntityGestureEvent;
546
+ reconnectEdge: {
547
+ edgeId: string;
548
+ newSourceId?: string;
549
+ newTargetId?: string;
550
+ newSourcePort?: string | null;
551
+ newTargetPort?: string | null;
552
+ } & TransactionMetadata;
553
+ setMode: { mode: string };
554
+ setSnapToGrid: { enabled: boolean; grid?: [number, number] };
555
+ setSnapLines: { enabled: boolean; threshold?: number; spacing?: boolean };
556
+ setColorMode: { colorMode: FlowColorMode };
557
+ moveNodes: { direction: Point; factor?: number } & TransactionMetadata;
558
+ requestLayout: { algorithm?: string };
559
+ applyLayoutResult: {
560
+ positions: Map<string, { x: number; y: number }>;
561
+ edgeLabelPositions?: Map<string, { x: number; y: number }>;
562
+ } & TransactionMetadata;
563
+ updateMeasurements: { measurements: Array<{ id: string; rect: Rect; origin?: Point }>; derivedOnly?: boolean };
564
+ removeMeasurements: { ids: string[]; derivedOnly?: boolean };
565
+ bakeLabelPositions: { positions: Map<string, Point> } & TransactionMetadata;
566
+ reportError: FlowErrorEvent;
567
+ };
568
+
569
+ export type FlowNodePatch = Partial<Omit<FlowNode, 'id' | 'type' | 'parentId'>>;
570
+ export type FlowEdgePatch = Partial<
571
+ Omit<FlowEdge, 'id' | 'type' | 'sourceId' | 'targetId' | 'sourcePort' | 'targetPort'>
572
+ >;
573
+ export type FlowNodeUpdater = (node: FlowNode) => FlowNode;
574
+ export type FlowEdgeUpdater = (edge: FlowEdge) => FlowEdge;
575
+ export type FlowUpdateNodeEvent = {
576
+ id: string;
577
+ patch?: FlowNodePatch;
578
+ updater?: FlowNodeUpdater;
579
+ } & TransactionMetadata;
580
+ export type FlowUpdateEdgeEvent = {
581
+ id: string;
582
+ patch?: FlowEdgePatch;
583
+ updater?: FlowEdgeUpdater;
584
+ } & TransactionMetadata;
585
+
586
+ const UNDOABLE_EVENT_TYPES = [
587
+ 'createNode',
588
+ 'deleteNode',
589
+ 'updateNode',
590
+ 'updateNodeData',
591
+ 'createEdge',
592
+ 'deleteEdge',
593
+ 'deleteEntities',
594
+ 'updateEdge',
595
+ 'updateEdgeData',
596
+ 'deleteSelected',
597
+ 'reparentNode',
598
+ 'collapseNode',
599
+ 'expandNode',
600
+ 'commitDrag',
601
+ 'resizeEnd',
602
+ 'reconnectEdge',
603
+ 'applyLayoutResult',
604
+ 'bakeLabelPositions',
605
+ 'replaceGraph',
606
+ ] as const;
607
+
608
+ type UndoableEventType = (typeof UNDOABLE_EVENT_TYPES)[number];
609
+ type UndoableStoreEvent = {
610
+ type: string;
611
+ transactionId?: string;
612
+ history?: FlowGraphHistoryPolicy;
613
+ [key: string]: any;
614
+ };
615
+ type UndoableStoreSnapshot = { context: FlowStoreContext };
616
+ type TransactionMetadata = { transactionId?: string; origin?: string };
617
+
618
+ export type FlowGraphRetentionPolicy = 'preserve' | 'reset';
619
+ export type FlowGraphHistoryPolicy = 'reset' | 'ignore' | 'record';
620
+
621
+ type ReplaceGraphMetadata = TransactionMetadata & {
622
+ retention?: FlowGraphRetentionPolicy;
623
+ history?: FlowGraphHistoryPolicy;
624
+ };
625
+
626
+ type FlowHistorySnapshot = StoreSnapshot<FlowStoreContext> & {
627
+ past: unknown[];
628
+ future: unknown[];
629
+ };
630
+
631
+ /**
632
+ * Validate an edge about to be inserted. Returns an actionable error message,
633
+ * or null when the edge is valid. Used by `createEdge` and undo tracking.
634
+ */
635
+ function validateNewEdge(
636
+ ctx: { graph: FlowGraph } | FlowStoreContext,
637
+ edge: FlowEdge
638
+ ): string | null {
639
+ if (ctx.graph.edges.some((e) => e.id === edge.id)) {
640
+ return (
641
+ `createEdge rejected: an edge with id "${edge.id}" already exists. ` +
642
+ `Edge ids must be unique — use reconnectEdge or updateEdgeData to modify the existing edge, or create the edge with a different id.`
643
+ );
644
+ }
645
+ const missing: string[] = [];
646
+ if (!ctx.graph.nodes.some((n) => n.id === edge.sourceId)) {
647
+ missing.push(`source node "${edge.sourceId}"`);
648
+ }
649
+ if (!ctx.graph.nodes.some((n) => n.id === edge.targetId)) {
650
+ missing.push(`target node "${edge.targetId}"`);
651
+ }
652
+ if (missing.length > 0) {
653
+ return (
654
+ `createEdge rejected: edge "${edge.id}" references ${missing.join(' and ')}, ` +
655
+ `which ${
656
+ missing.length === 1 ? 'does' : 'do'
657
+ } not exist in the graph. Create the node(s) first, then the edge.`
658
+ );
659
+ }
660
+ return null;
661
+ }
662
+
663
+ function validateUpdatedNode(previous: FlowNode, next: FlowNode): string | null {
664
+ if (next.id !== previous.id) {
665
+ return `updateNode rejected: node id cannot change from "${previous.id}" to "${next.id}".`;
666
+ }
667
+ if (next.type !== previous.type) {
668
+ return `updateNode rejected: node "${previous.id}" type cannot change.`;
669
+ }
670
+ if (next.parentId !== previous.parentId) {
671
+ return `updateNode rejected: node "${previous.id}" parentId must be changed with reparentNode.`;
672
+ }
673
+ return null;
674
+ }
675
+
676
+ function validateUpdatedEdge(previous: FlowEdge, next: FlowEdge): string | null {
677
+ if (next.id !== previous.id) {
678
+ return `updateEdge rejected: edge id cannot change from "${previous.id}" to "${next.id}".`;
679
+ }
680
+ if (next.type !== previous.type) {
681
+ return `updateEdge rejected: edge "${previous.id}" type cannot change.`;
682
+ }
683
+ if (
684
+ next.sourceId !== previous.sourceId ||
685
+ next.targetId !== previous.targetId ||
686
+ next.sourcePort !== previous.sourcePort ||
687
+ next.targetPort !== previous.targetPort
688
+ ) {
689
+ return `updateEdge rejected: edge "${previous.id}" endpoints and ports must be changed with reconnectEdge.`;
690
+ }
691
+ return null;
692
+ }
693
+
694
+ /**
695
+ * Validate a reparent operation. Returns an error message or null when valid.
696
+ * Rejects self-parenting, non-existent parents, and cycles (parentId is a
697
+ * descendant of nodeId).
698
+ */
699
+ function reparentProblem(graph: FlowGraph, nodeId: string, parentId: string | null): string | null {
700
+ if (parentId === null) return null;
701
+ if (parentId === nodeId) {
702
+ return `reparentNode rejected: node "${nodeId}" cannot be its own parent.`;
703
+ }
704
+ if (!graph.nodes.some((n) => n.id === parentId)) {
705
+ return `reparentNode rejected: parent node "${parentId}" does not exist in the graph.`;
706
+ }
707
+ // Walk up from parentId; if we reach nodeId, it's a cycle.
708
+ const nodeIndex = new Map(graph.nodes.map((n) => [n.id, n]));
709
+ let candidate: string | null = parentId;
710
+ const seen = new Set<string>();
711
+ while (candidate && !seen.has(candidate)) {
712
+ if (candidate === nodeId) {
713
+ return `reparentNode rejected: node "${parentId}" is a descendant of "${nodeId}", which would create a cycle.`;
714
+ }
715
+ seen.add(candidate);
716
+ candidate = nodeIndex.get(candidate)?.parentId ?? null;
717
+ }
718
+ return null;
719
+ }
720
+
721
+ /** Drop hover/highlight/collapse references to entities that no longer exist. */
722
+ function pruneVisualState(draft: FlowStoreContext, deletedIds: string[]): void {
723
+ const connection = draft.connection;
724
+ const pending = draft.connectionClickStartHandle;
725
+ if (
726
+ (connection && deletedIds.some((id) =>
727
+ id === connection.sourceId ||
728
+ (connection.sourcePort !== null && id === `${connection.sourceId}:${connection.sourcePort}`) ||
729
+ id === connection.targetId ||
730
+ (connection.targetId !== null && connection.targetPort !== null &&
731
+ id === `${connection.targetId}:${connection.targetPort}`) ||
732
+ id === connection.reconnectingEdgeId
733
+ )) ||
734
+ (pending && deletedIds.some((id) =>
735
+ id === pending.nodeId ||
736
+ (pending.port !== null && id === `${pending.nodeId}:${pending.port}`)
737
+ ))
738
+ ) {
739
+ draft.connection = null;
740
+ draft.connectionClickStartHandle = null;
741
+ if (draft.canvasState === 'connecting') draft.canvasState = 'idle';
742
+ }
743
+ for (const id of deletedIds) {
744
+ draft.hoveredEntityIds.delete(id);
745
+ draft.collapsedNodeIds.delete(id);
746
+ }
747
+ for (const [kind, bucket] of draft.highlights) {
748
+ for (const id of deletedIds) {
749
+ bucket.delete(id);
750
+ }
751
+ if (bucket.size === 0) draft.highlights.delete(kind);
752
+ }
753
+ }
754
+
755
+ function portAddressableIds(node: FlowNode): string[] {
756
+ const ids = new Set<string>();
757
+ for (const port of node.ports ?? []) {
758
+ ids.add(`${node.id}:${port.name}`);
759
+ const explicitId = (port as { id?: string }).id;
760
+ if (explicitId) ids.add(explicitId);
761
+ }
762
+ return [...ids];
763
+ }
764
+
765
+ function graphAddressableIds(graph: FlowGraph): Set<string> {
766
+ return new Set([
767
+ ...graph.nodes.flatMap((node) => [node.id, ...portAddressableIds(node)]),
768
+ ...graph.edges.map((edge) => edge.id),
769
+ ]);
770
+ }
771
+
772
+ function pruneDeletedAddressables(
773
+ draft: FlowStoreContext,
774
+ deletedIds: string[],
775
+ ): void {
776
+ const deleted = new Set(deletedIds);
777
+ for (const id of deleted) {
778
+ draft.selection.delete(id);
779
+ draft.measurements.delete(id);
780
+ draft.derivedPortMeasurements.delete(id);
781
+ }
782
+ if (draft.focusedEntityId && deleted.has(draft.focusedEntityId)) {
783
+ draft.focusedEntityId = null;
784
+ }
785
+ pruneVisualState(draft, deletedIds);
786
+ }
787
+
788
+ function invalidatePathsForNodeGeometry(
789
+ draft: FlowStoreContext,
790
+ changedNodeIds: ReadonlySet<string>,
791
+ topologyNodes: readonly FlowNode[] = draft.graph.nodes,
792
+ ): void {
793
+ const affectedNodeIds = withDerivedGroupAncestors(
794
+ topologyNodes,
795
+ changedNodeIds,
796
+ );
797
+ for (const edge of draft.graph.edges) {
798
+ if (
799
+ affectedNodeIds.has(edge.sourceId) ||
800
+ affectedNodeIds.has(edge.targetId)
801
+ ) {
802
+ invalidateAuthoritativeEdgePath(edge);
803
+ }
804
+ }
805
+ }
806
+
807
+ function isUndoableEventType(type: string): type is UndoableEventType {
808
+ return (UNDOABLE_EVENT_TYPES as readonly string[]).includes(type);
809
+ }
810
+
811
+ /**
812
+ * Movement plan for one drag/arrow-key step, computed entirely on the plain
813
+ * pre-transition context (draft proxy reads are ~10× slower than plain reads
814
+ * and movement runs once per pointer frame). Deltas are keyed by array index
815
+ * so the draft pass touches only the moved entities.
816
+ *
817
+ * Descendants of a moved node ride along with the parent's applied
818
+ * (post-clamp) delta — minimal subflow semantics: positions stay absolute;
819
+ * relative coordinate spaces and parent-extent clamping are tracked in
820
+ * REFRAME.md. Descendants that move on their own (selected + draggable) are
821
+ * skipped together with their subtrees. parentId cycles are tolerated.
822
+ */
823
+ type MovementPlan = {
824
+ nodeDeltasByIndex: Map<number, Point>;
825
+ edgeDeltasByIndex: Map<number, Point>;
826
+ labelDeltasByIndex: Map<number, Point>;
827
+ };
828
+
829
+ type MovementTopology = {
830
+ nodeIndices: Map<string, number>;
831
+ edgeIndices: Map<string, number>;
832
+ childrenByParent: Map<string, string[]> | null;
833
+ nodeCount: number;
834
+ edgeCount: number;
835
+ };
836
+
837
+ function createMovementTopology(
838
+ nodes: readonly FlowNode[],
839
+ edges: readonly FlowEdge[],
840
+ ): MovementTopology {
841
+ const nodeArray = nodes as FlowNode[];
842
+ const edgeArray = edges as FlowEdge[];
843
+ const nodeIndices = indexNodePositions(nodeArray);
844
+ const edgeIndices = indexEdgePositions(edgeArray);
845
+ const children = indexChildren(nodeArray);
846
+ const childrenByParent = children.size
847
+ ? new Map(
848
+ [...children].map(([parentId, childNodes]) => [
849
+ parentId,
850
+ childNodes.map((node) => node.id),
851
+ ]),
852
+ )
853
+ : null;
854
+ return {
855
+ nodeIndices,
856
+ edgeIndices,
857
+ childrenByParent,
858
+ nodeCount: nodes.length,
859
+ edgeCount: edges.length,
860
+ };
861
+ }
862
+
863
+ export function planNodeMovement(
864
+ ctx: FlowStoreContext,
865
+ dx: number,
866
+ dy: number,
867
+ options: { includeLabels?: boolean } = {},
868
+ topology?: MovementTopology,
869
+ ): MovementPlan | null {
870
+ const nodes = ctx.graph.nodes as FlowNode[];
871
+ const edges = ctx.graph.edges as FlowEdge[];
872
+ const usableTopology =
873
+ topology?.nodeCount === nodes.length && topology.edgeCount === edges.length
874
+ ? topology
875
+ : createMovementTopology(nodes, edges);
876
+ const nodeAt = (id: string) => {
877
+ const index = usableTopology.nodeIndices.get(id);
878
+ const node = index === undefined ? undefined : nodes[index];
879
+ return node?.id === id ? node : undefined;
880
+ };
881
+ const edgeAt = (id: string) => {
882
+ const index = usableTopology.edgeIndices.get(id);
883
+ const edge = index === undefined ? undefined : edges[index];
884
+ return edge?.id === id ? edge : undefined;
885
+ };
886
+
887
+ const movingNodeIds = new Set<string>();
888
+ const labelEdgeIds = new Set<string>();
889
+ for (const id of ctx.selection) {
890
+ const node = nodeAt(id);
891
+ if (node) {
892
+ if (node.draggable !== false) movingNodeIds.add(id);
893
+ continue;
894
+ }
895
+ if (options.includeLabels) {
896
+ const edge = edgeAt(id);
897
+ if (edge && edge.draggable !== false && edge.label) labelEdgeIds.add(id);
898
+ }
899
+ }
900
+ if (movingNodeIds.size === 0 && labelEdgeIds.size === 0) return null;
901
+
902
+ const childrenByParent = usableTopology.childrenByParent;
903
+ // Hierarchy-only operations need current node objects because parents may
904
+ // themselves have moved earlier in the gesture. Flat graphs avoid this map.
905
+ const hierarchyNodeIndex = childrenByParent ? indexNodes(nodes) : null;
906
+
907
+ const deltasById = new Map<string, Point>();
908
+ for (const id of movingNodeIds) {
909
+ const node = nodeAt(id)!;
910
+ const oldDx = node.dx ?? 0;
911
+ const oldDy = node.dy ?? 0;
912
+ let newDx = oldDx + dx;
913
+ let newDy = oldDy + dy;
914
+
915
+ if (ctx.nodeExtent) {
916
+ const nodeSize = resolvedSize(node);
917
+ const clampedX = Math.max(
918
+ ctx.nodeExtent[0].x,
919
+ Math.min(node.x + newDx, ctx.nodeExtent[1].x - nodeSize.width)
920
+ );
921
+ const clampedY = Math.max(
922
+ ctx.nodeExtent[0].y,
923
+ Math.min(node.y + newDy, ctx.nodeExtent[1].y - nodeSize.height)
924
+ );
925
+ newDx = clampedX - node.x;
926
+ newDy = clampedY - node.y;
927
+ }
928
+
929
+ // Fixed-layout parents may clamp their children to the child area (per
930
+ // axis). Derived parents never clamp — their bounds follow the children.
931
+ const parent = node.parentId
932
+ ? hierarchyNodeIndex?.get(node.parentId)
933
+ : undefined;
934
+ if (parent?.group?.type === 'fixed') {
935
+ const axes = parent.group.clampChildren ?? 'none';
936
+ if (axes !== 'none') {
937
+ const area = fixedGroupGeometry(
938
+ {
939
+ x: parent.x + (parent.dx ?? 0),
940
+ y: parent.y + (parent.dy ?? 0),
941
+ width: parent.style?.customWidth ?? parent.width,
942
+ height: parent.style?.customHeight ?? parent.height,
943
+ },
944
+ parent.group.contentSize ?? { width: 0, height: 0 },
945
+ parent.group
946
+ ).childArea;
947
+ const { width: nodeWidth, height: nodeHeight } = resolvedSize(node);
948
+ if (axes === 'x' || axes === 'both') {
949
+ const clampedX = Math.max(
950
+ area.x,
951
+ Math.min(node.x + newDx, area.x + area.width - nodeWidth)
952
+ );
953
+ newDx = clampedX - node.x;
954
+ }
955
+ if (axes === 'y' || axes === 'both') {
956
+ const clampedY = Math.max(
957
+ area.y,
958
+ Math.min(node.y + newDy, area.y + area.height - nodeHeight)
959
+ );
960
+ newDy = clampedY - node.y;
961
+ }
962
+ }
963
+ }
964
+
965
+ if (ctx.constrainNodeMovement) {
966
+ const adjusted = ctx.constrainNodeMovement(
967
+ node,
968
+ { x: node.x + newDx, y: node.y + newDy },
969
+ ctx
970
+ );
971
+ if (adjusted) {
972
+ newDx = adjusted.x - node.x;
973
+ newDy = adjusted.y - node.y;
974
+ }
975
+ }
976
+
977
+ const applied = { x: newDx - oldDx, y: newDy - oldDy };
978
+ if (applied.x === 0 && applied.y === 0) continue;
979
+ deltasById.set(id, applied);
980
+ if (childrenByParent) {
981
+ collectDescendantDeltas(childrenByParent, id, applied, movingNodeIds, deltasById);
982
+ }
983
+ }
984
+
985
+ const nodeDeltasByIndex = new Map<number, Point>();
986
+ if (deltasById.size > 0) {
987
+ for (const [id, delta] of deltasById) {
988
+ const index = usableTopology.nodeIndices.get(id);
989
+ if (index !== undefined && nodes[index]?.id === id) {
990
+ nodeDeltasByIndex.set(index, delta);
991
+ }
992
+ }
993
+ }
994
+ const edgeDeltasByIndex = new Map<number, Point>();
995
+ const labelDeltasByIndex = new Map<number, Point>();
996
+ if (childrenByParent && deltasById.size > 0) {
997
+ for (let i = 0; i < edges.length; i++) {
998
+ const edge = edges[i];
999
+ const carriesWaypoints = !!edge.waypoints?.length;
1000
+ const carriesFixedLabel =
1001
+ !!edge.label && (edge.labelAnchor ?? ctx.labelAnchor) === 'fixed';
1002
+ if (!carriesWaypoints && !carriesFixedLabel) continue;
1003
+ if (
1004
+ !deltasById.has(edge.sourceId) ||
1005
+ !deltasById.has(edge.targetId)
1006
+ ) {
1007
+ continue;
1008
+ }
1009
+
1010
+ const ownerId = getEdgeOwnerFromIndex(edge, hierarchyNodeIndex!);
1011
+ const ownerDelta = ownerId ? deltasById.get(ownerId) : undefined;
1012
+ if (!ownerDelta) continue;
1013
+ edgeDeltasByIndex.set(i, ownerDelta);
1014
+ if (carriesFixedLabel) labelDeltasByIndex.set(i, ownerDelta);
1015
+ }
1016
+ }
1017
+ if (labelEdgeIds.size > 0) {
1018
+ for (const id of labelEdgeIds) {
1019
+ const index = usableTopology.edgeIndices.get(id);
1020
+ if (index === undefined || edges[index]?.id !== id || labelDeltasByIndex.has(index)) {
1021
+ continue;
1022
+ }
1023
+ labelDeltasByIndex.set(index, { x: dx, y: dy });
1024
+ }
1025
+ }
1026
+ if (
1027
+ nodeDeltasByIndex.size === 0 &&
1028
+ edgeDeltasByIndex.size === 0 &&
1029
+ labelDeltasByIndex.size === 0
1030
+ ) {
1031
+ return null;
1032
+ }
1033
+ return { nodeDeltasByIndex, edgeDeltasByIndex, labelDeltasByIndex };
1034
+ }
1035
+
1036
+ function collectDescendantDeltas(
1037
+ childrenByParent: Map<string, string[]>,
1038
+ parentId: string,
1039
+ delta: Point,
1040
+ movingIds: Set<string>,
1041
+ out: Map<string, Point>,
1042
+ visited: Set<string> = new Set([parentId])
1043
+ ): void {
1044
+ const children = childrenByParent.get(parentId);
1045
+ if (!children) return;
1046
+ for (const childId of children) {
1047
+ if (visited.has(childId) || movingIds.has(childId)) continue;
1048
+ visited.add(childId);
1049
+ if (!out.has(childId)) out.set(childId, delta);
1050
+ collectDescendantDeltas(childrenByParent, childId, delta, movingIds, out, visited);
1051
+ }
1052
+ }
1053
+
1054
+ function applyMovementPlan(draft: FlowStoreContext, plan: MovementPlan): void {
1055
+ for (const [index, delta] of plan.nodeDeltasByIndex) {
1056
+ const node = draft.graph.nodes[index];
1057
+ if (!node) continue;
1058
+ node.dx = (node.dx ?? 0) + delta.x;
1059
+ node.dy = (node.dy ?? 0) + delta.y;
1060
+ }
1061
+ for (const [index, delta] of plan.edgeDeltasByIndex) {
1062
+ const edge = draft.graph.edges[index];
1063
+ if (!edge) continue;
1064
+ edge.dx = (edge.dx ?? 0) + delta.x;
1065
+ edge.dy = (edge.dy ?? 0) + delta.y;
1066
+ }
1067
+ for (const [index, delta] of plan.labelDeltasByIndex) {
1068
+ const edge = draft.graph.edges[index];
1069
+ if (!edge?.label) continue;
1070
+ edge.label.dx = (edge.label.dx ?? 0) + delta.x;
1071
+ edge.label.dy = (edge.label.dy ?? 0) + delta.y;
1072
+ }
1073
+ }
1074
+
1075
+ /**
1076
+ * Remove nodes from the draft graph and resolve connected edges according to
1077
+ * the configured `onDeleteNodes` strategy. Shared by `deleteNode` and
1078
+ * `deleteSelected` so both events always agree on edge handling.
1079
+ *
1080
+ * `edgesToDelete` are edge ids that must be removed regardless of strategy
1081
+ * (explicitly selected/targeted edges).
1082
+ */
1083
+ function applyNodeDeletionStrategy(
1084
+ draft: FlowStoreContext,
1085
+ nodesToDelete: Set<string>,
1086
+ edgesToDelete: Set<string>,
1087
+ strategy: NonNullable<FlowStoreOptions['onDeleteNodes']>
1088
+ ): void {
1089
+ if (typeof strategy === 'function') {
1090
+ const result = strategy(
1091
+ {
1092
+ ...draft.graph,
1093
+ nodes: [...draft.graph.nodes],
1094
+ edges: [...draft.graph.edges],
1095
+ } as FlowGraph,
1096
+ nodesToDelete
1097
+ );
1098
+ draft.graph.nodes = result.nodes as typeof draft.graph.nodes;
1099
+ draft.graph.edges = (result.edges as typeof draft.graph.edges).filter(
1100
+ (edge) => !edgesToDelete.has(edge.id)
1101
+ );
1102
+ return;
1103
+ }
1104
+
1105
+ nodesToDelete = getNodeIdsWithDescendants(draft.graph.nodes, nodesToDelete);
1106
+
1107
+ draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));
1108
+
1109
+ if (strategy === 'retarget') {
1110
+ const kept: typeof draft.graph.edges = [];
1111
+ for (const edge of draft.graph.edges) {
1112
+ if (edgesToDelete.has(edge.id)) continue;
1113
+ const srcDel = nodesToDelete.has(edge.sourceId);
1114
+ const tgtDel = nodesToDelete.has(edge.targetId);
1115
+ if (srcDel && tgtDel) continue;
1116
+ if (srcDel) {
1117
+ edge.sourceId = edge.targetId;
1118
+ invalidateAuthoritativeEdgePath(edge);
1119
+ } else if (tgtDel) {
1120
+ edge.targetId = edge.sourceId;
1121
+ invalidateAuthoritativeEdgePath(edge);
1122
+ }
1123
+ kept.push(edge);
1124
+ }
1125
+ draft.graph.edges = kept;
1126
+ return;
1127
+ }
1128
+
1129
+ // cascade (default)
1130
+ draft.graph.edges = draft.graph.edges.filter(
1131
+ (e) =>
1132
+ !edgesToDelete.has(e.id) && !nodesToDelete.has(e.sourceId) && !nodesToDelete.has(e.targetId)
1133
+ );
1134
+ }
1135
+
1136
+ function hasSelectedEntitiesToDelete(ctx: FlowStoreContext): boolean {
1137
+ for (const id of ctx.selection) {
1138
+ if (
1139
+ ctx.graph.nodes.some((node) => node.id === id) ||
1140
+ ctx.graph.edges.some((edge) => edge.id === id)
1141
+ ) {
1142
+ return true;
1143
+ }
1144
+ }
1145
+
1146
+ return false;
1147
+ }
1148
+
1149
+ function shouldTrackUndoEvent(event: UndoableStoreEvent, snapshot: UndoableStoreSnapshot): boolean {
1150
+ if (!isUndoableEventType(event.type)) {
1151
+ return false;
1152
+ }
1153
+
1154
+ const ctx = snapshot.context;
1155
+
1156
+ switch (event.type) {
1157
+ case 'createNode':
1158
+ return !ctx.graph.nodes.some((node) => node.id === event.node.id);
1159
+ case 'createEdge':
1160
+ return validateNewEdge(ctx, event.edge) === null;
1161
+ case 'deleteNode':
1162
+ return ctx.graph.nodes.some((node) => node.id === event.id);
1163
+ case 'deleteEdge':
1164
+ return ctx.graph.edges.some((edge) => edge.id === event.id);
1165
+ case 'deleteEntities':
1166
+ return (
1167
+ (event.nodeIds ?? []).some((id: string) =>
1168
+ ctx.graph.nodes.some((node) => node.id === id)
1169
+ ) ||
1170
+ (event.edgeIds ?? []).some((id: string) => ctx.graph.edges.some((edge) => edge.id === id))
1171
+ );
1172
+ case 'updateNodeData': {
1173
+ const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);
1174
+ return (
1175
+ !!node && Object.entries(event.data).some(([key, value]) => node.data?.[key] !== value)
1176
+ );
1177
+ }
1178
+ case 'updateEdgeData': {
1179
+ const edge = ctx.graph.edges.find((candidate) => candidate.id === event.id);
1180
+ return (
1181
+ !!edge && Object.entries(event.data).some(([key, value]) => edge.data?.[key] !== value)
1182
+ );
1183
+ }
1184
+ case 'deleteSelected':
1185
+ return hasSelectedEntitiesToDelete(ctx);
1186
+ case 'replaceGraph':
1187
+ return (
1188
+ event.history !== 'ignore' &&
1189
+ event.history !== 'reset' &&
1190
+ JSON.stringify(ctx.graph) !== JSON.stringify(event.graph)
1191
+ );
1192
+ case 'reparentNode': {
1193
+ const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);
1194
+ return !!node && (node.parentId ?? null) !== event.parentId;
1195
+ }
1196
+ case 'commitDrag':
1197
+ return (
1198
+ ctx.graph.nodes.some((node) => node.dx || node.dy) ||
1199
+ ctx.graph.edges.some((edge) => edge.dx || edge.dy || edge.label?.dx || edge.label?.dy)
1200
+ );
1201
+ case 'resizeEnd': {
1202
+ if (!ctx.resizingEntityId || !ctx.resizeCorners) return false;
1203
+ const node = ctx.graph.nodes.find((candidate) => candidate.id === ctx.resizingEntityId);
1204
+ const bounds = resizeBoundsFromDraft(ctx.resizeCorners);
1205
+ if (!node || !bounds) return false;
1206
+ const size = resolvedSize(node);
1207
+ return (
1208
+ bounds.x !== node.x + (node.dx ?? 0) ||
1209
+ bounds.y !== node.y + (node.dy ?? 0) ||
1210
+ bounds.width !== size.width ||
1211
+ bounds.height !== size.height
1212
+ );
1213
+ }
1214
+ case 'reconnectEdge': {
1215
+ const edge = ctx.graph.edges.find((candidate) => candidate.id === event.edgeId);
1216
+ if (!edge) {
1217
+ return false;
1218
+ }
1219
+
1220
+ return (
1221
+ (event.newSourceId !== undefined && event.newSourceId !== edge.sourceId) ||
1222
+ (event.newTargetId !== undefined && event.newTargetId !== edge.targetId) ||
1223
+ (event.newSourcePort !== undefined && event.newSourcePort !== edge.sourcePort) ||
1224
+ (event.newTargetPort !== undefined && event.newTargetPort !== edge.targetPort)
1225
+ );
1226
+ }
1227
+ case 'applyLayoutResult':
1228
+ return event.positions.size > 0 || (event.edgeLabelPositions?.size ?? 0) > 0;
1229
+ case 'bakeLabelPositions':
1230
+ return event.positions.size > 0;
1231
+ default:
1232
+ return true;
1233
+ }
1234
+ }
1235
+
1236
+ const resetGraphReplacementHistory: StoreExtension<
1237
+ FlowStoreContext,
1238
+ FlowEventPayloadMap & { undo: null; redo: null },
1239
+ Record<never, never>,
1240
+ ExtractEvents<FlowEmittedPayloadMap>
1241
+ > = (logic) => ({
1242
+ ...logic,
1243
+ transition: (snapshot, event) => {
1244
+ const result = logic.transition(snapshot, event);
1245
+ if (event.type !== 'replaceGraph' || event.history !== 'reset') {
1246
+ return result;
1247
+ }
1248
+ const [next, effects] = result;
1249
+ const nextWithHistory = next as FlowHistorySnapshot;
1250
+ return [{ ...nextWithHistory, past: [], future: [] }, effects];
1251
+ },
1252
+ });
1253
+
1254
+ /**
1255
+ * Snapshot a (possibly drafted) graph into plain data for emission — immer
1256
+ * drafts are revoked before listeners run. Plain values (e.g. right after
1257
+ * `draft.graph = event.graph`) pass through untouched.
1258
+ */
1259
+ function snapshotGraph(graph: FlowStoreContext['graph']): FlowGraph {
1260
+ return (isDraft(graph) ? current(graph) : graph) as FlowGraph;
1261
+ }
1262
+
1263
+ function graphWithoutTransientOffsets(graph: FlowGraph): FlowGraph {
1264
+ return {
1265
+ ...graph,
1266
+ nodes: graph.nodes.map((source) => {
1267
+ const node = { ...source };
1268
+ delete node.dx;
1269
+ delete node.dy;
1270
+ return node;
1271
+ }),
1272
+ edges: graph.edges.map((source) => {
1273
+ const edge = { ...source };
1274
+ delete edge.dx;
1275
+ delete edge.dy;
1276
+ if (source.label) {
1277
+ edge.label = { ...source.label };
1278
+ delete edge.label.dx;
1279
+ delete edge.label.dy;
1280
+ }
1281
+ return edge;
1282
+ }),
1283
+ };
1284
+ }
1285
+
1286
+ function restoreHistoryContext(
1287
+ currentContext: FlowStoreContext,
1288
+ historicalContext: FlowStoreContext
1289
+ ): FlowStoreContext {
1290
+ const graph = graphWithoutTransientOffsets(historicalContext.graph);
1291
+ const entityIds = new Set([
1292
+ ...graph.nodes.map((node) => node.id),
1293
+ ...graph.edges.map((edge) => edge.id),
1294
+ ]);
1295
+ const addressableIds = graphAddressableIds(graph);
1296
+ const filterIds = (ids: Iterable<string>) => new Set([...ids].filter((id) => entityIds.has(id)));
1297
+ const collapsedNodeIds = filterIds(historicalContext.collapsedNodeIds);
1298
+ const selection = filterIds(currentContext.selection);
1299
+ for (const id of selection) {
1300
+ if (
1301
+ [...collapsedNodeIds].some(
1302
+ (ancestorId) => id !== ancestorId && isDescendantOf(graph.nodes, id, ancestorId)
1303
+ )
1304
+ ) {
1305
+ selection.delete(id);
1306
+ }
1307
+ }
1308
+ const highlights = new Map<string, Map<string, unknown>>();
1309
+ for (const [kind, entries] of currentContext.highlights) {
1310
+ const filtered = new Map([...entries].filter(([id]) => entityIds.has(id)));
1311
+ if (filtered.size > 0) highlights.set(kind, filtered);
1312
+ }
1313
+
1314
+ return {
1315
+ ...currentContext,
1316
+ graph,
1317
+ parentNodeId:
1318
+ currentContext.parentNodeId && entityIds.has(currentContext.parentNodeId)
1319
+ ? currentContext.parentNodeId
1320
+ : null,
1321
+ selection,
1322
+ hoveredEntityIds: filterIds(currentContext.hoveredEntityIds),
1323
+ collapsedNodeIds,
1324
+ highlights,
1325
+ focusedEntityId:
1326
+ currentContext.focusedEntityId && entityIds.has(currentContext.focusedEntityId)
1327
+ ? currentContext.focusedEntityId
1328
+ : null,
1329
+ measurements: new Map([...currentContext.measurements].filter(([id]) => entityIds.has(id))),
1330
+ derivedPortMeasurements: new Map(
1331
+ [...currentContext.derivedPortMeasurements].filter(([id]) =>
1332
+ addressableIds.has(id),
1333
+ ),
1334
+ ),
1335
+ layoutAnimation: { status: 'idle', offsets: new Map() },
1336
+ canvasState: 'idle',
1337
+ draggedEntityId: null,
1338
+ dragRevision: 0,
1339
+ selectionBox: null,
1340
+ selectionBoxBase: null,
1341
+ connection: null,
1342
+ connectionClickStartHandle: null,
1343
+ panOrigin: null,
1344
+ panViewportOrigin: null,
1345
+ resizingEntityId: null,
1346
+ resizeHandle: null,
1347
+ resizeCorners: null,
1348
+ };
1349
+ }
1350
+
1351
+ /** Copy a (possibly drafted) viewport into plain data for emission. */
1352
+ function plainViewport(viewport: Viewport): Viewport {
1353
+ return { x: viewport.x, y: viewport.y, zoom: viewport.zoom };
1354
+ }
1355
+
1356
+ function entityPositions(
1357
+ graph: FlowStoreContext['graph'],
1358
+ ids: Iterable<string>,
1359
+ movement?: MovementPlan,
1360
+ topology?: MovementTopology,
1361
+ ): Record<string, Point> {
1362
+ const positions: Record<string, Point> = {};
1363
+ const usableTopology =
1364
+ topology?.nodeCount === graph.nodes.length &&
1365
+ topology.edgeCount === graph.edges.length
1366
+ ? topology
1367
+ : null;
1368
+ const nodes = usableTopology ? null : indexNodes(graph.nodes as FlowNode[]);
1369
+ const edges = usableTopology ? null : indexEdges(graph.edges as FlowEdge[]);
1370
+ const nodeAt = (id: string) => {
1371
+ const index = usableTopology?.nodeIndices.get(id);
1372
+ const node = index === undefined ? nodes?.get(id) : graph.nodes[index];
1373
+ return node?.id === id ? node : undefined;
1374
+ };
1375
+ const edgeAt = (id: string) => {
1376
+ const index = usableTopology?.edgeIndices.get(id);
1377
+ const edge = index === undefined ? edges?.get(id) : graph.edges[index];
1378
+ return edge?.id === id ? edge : undefined;
1379
+ };
1380
+ const nodeDeltas = new Map<string, Point>();
1381
+ const labelDeltas = new Map<string, Point>();
1382
+ if (movement) {
1383
+ for (const [index, delta] of movement.nodeDeltasByIndex) {
1384
+ const node = graph.nodes[index];
1385
+ if (node) nodeDeltas.set(node.id, delta);
1386
+ }
1387
+ for (const [index, delta] of movement.labelDeltasByIndex) {
1388
+ const edge = graph.edges[index];
1389
+ if (edge) labelDeltas.set(edge.id, delta);
1390
+ }
1391
+ }
1392
+ for (const id of ids) {
1393
+ const node = nodeAt(id);
1394
+ if (node) {
1395
+ const delta = nodeDeltas.get(id);
1396
+ positions[id] = {
1397
+ x: node.x + (node.dx ?? 0) + (delta?.x ?? 0),
1398
+ y: node.y + (node.dy ?? 0) + (delta?.y ?? 0),
1399
+ };
1400
+ continue;
1401
+ }
1402
+ const edge = edgeAt(id);
1403
+ if (edge?.label) {
1404
+ const delta = labelDeltas.get(id);
1405
+ positions[id] = {
1406
+ x: edge.label.x + (edge.label.dx ?? 0) + (delta?.x ?? 0),
1407
+ y: edge.label.y + (edge.label.dy ?? 0) + (delta?.y ?? 0),
1408
+ };
1409
+ }
1410
+ }
1411
+ return positions;
1412
+ }
1413
+
1414
+ function resizeBoundsFromDraft(corners: [Point, Point] | null): Rect | null {
1415
+ if (!corners) return null;
1416
+ const [a, b] = corners;
1417
+ return {
1418
+ x: Math.min(a.x, b.x),
1419
+ y: Math.min(a.y, b.y),
1420
+ width: Math.abs(b.x - a.x),
1421
+ height: Math.abs(b.y - a.y),
1422
+ };
1423
+ }
1424
+
1425
+ function clamp(value: number, min: number, max: number): number {
1426
+ return Math.min(max, Math.max(min, value));
1427
+ }
1428
+
1429
+ export function clampResizeMovingPoint(
1430
+ node: FlowNode,
1431
+ handle: ResizeHandle | null,
1432
+ anchor: Point,
1433
+ moving: Point
1434
+ ): Point {
1435
+ // Free by default: no implicit minimum. Explicit constraints via node.resize.min.
1436
+ const minWidth = node.resize?.min?.width ?? 0;
1437
+ const minHeight = node.resize?.min?.height ?? 0;
1438
+ const maxWidth = node.resize?.max?.width ?? Number.POSITIVE_INFINITY;
1439
+ const maxHeight = node.resize?.max?.height ?? Number.POSITIVE_INFINITY;
1440
+ const current = resolvedSize(node);
1441
+ const aspect =
1442
+ typeof node.resize?.aspect === 'number' && node.resize.aspect > 0
1443
+ ? node.resize.aspect
1444
+ : node.resize?.aspect === true && current.height > 0
1445
+ ? current.width / current.height
1446
+ : null;
1447
+
1448
+ const rawDx = moving.x - anchor.x;
1449
+ const rawDy = moving.y - anchor.y;
1450
+ const sx = rawDx < 0 ? -1 : 1;
1451
+ const sy = rawDy < 0 ? -1 : 1;
1452
+ let width = clamp(Math.abs(rawDx), minWidth, maxWidth);
1453
+ let height = clamp(Math.abs(rawDy), minHeight, maxHeight);
1454
+
1455
+ if (aspect) {
1456
+ if (handle === 'left' || handle === 'right') {
1457
+ height = width / aspect;
1458
+ } else if (handle === 'top' || handle === 'bottom') {
1459
+ width = height * aspect;
1460
+ } else if (width / height > aspect) {
1461
+ height = width / aspect;
1462
+ } else {
1463
+ width = height * aspect;
1464
+ }
1465
+ width = clamp(width, minWidth, maxWidth);
1466
+ height = clamp(height, minHeight, maxHeight);
1467
+ }
1468
+
1469
+ return {
1470
+ x: anchor.x + sx * width,
1471
+ y: anchor.y + sy * height,
1472
+ };
1473
+ }
1474
+
1475
+ function createEventObject<TEvent extends object>(
1476
+ type: string,
1477
+ event: TEvent | undefined
1478
+ ): FlowEventObject {
1479
+ return { type, ...(event ?? {}) };
1480
+ }
1481
+
1482
+ function isExplicitlyVisibleNode(node: FlowNode): boolean {
1483
+ return !node.hidden;
1484
+ }
1485
+
1486
+ /**
1487
+ * A collapsed group hides its descendants: they are not selectable and do not
1488
+ * contribute to any group's derived selection geometry. Mirrors the engine's
1489
+ * `isHiddenByCollapsedAncestor`.
1490
+ */
1491
+ function isHiddenByCollapsedAncestor(ctx: FlowStoreContext, nodeId: string): boolean {
1492
+ if (ctx.collapsedNodeIds.size === 0) return false;
1493
+ const nodeIndex = indexNodes(ctx.graph.nodes as FlowNode[]);
1494
+ let parentId = nodeIndex.get(nodeId)?.parentId;
1495
+ while (parentId) {
1496
+ if (ctx.collapsedNodeIds.has(parentId)) return true;
1497
+ parentId = nodeIndex.get(parentId)?.parentId;
1498
+ }
1499
+ return false;
1500
+ }
1501
+
1502
+ function isDescendantOf(nodes: readonly FlowNode[], nodeId: string, ancestorId: string): boolean {
1503
+ const byId = new Map(nodes.map((node) => [node.id, node]));
1504
+ let parentId = byId.get(nodeId)?.parentId;
1505
+ while (parentId) {
1506
+ if (parentId === ancestorId) return true;
1507
+ parentId = byId.get(parentId)?.parentId;
1508
+ }
1509
+ return false;
1510
+ }
1511
+
1512
+ function setsEqual(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {
1513
+ if (a.size !== b.size) return false;
1514
+ for (const value of a) if (!b.has(value)) return false;
1515
+ return true;
1516
+ }
1517
+
1518
+ function isExplicitlyVisibleEdge(edge: FlowEdge, nodes: readonly FlowNode[]): boolean {
1519
+ if (edge.hidden) return false;
1520
+ const source = nodes.find((node) => node.id === edge.sourceId);
1521
+ const target = nodes.find((node) => node.id === edge.targetId);
1522
+ return !!source && !!target && isExplicitlyVisibleNode(source) && isExplicitlyVisibleNode(target);
1523
+ }
1524
+
1525
+ /**
1526
+ * Entities captured by a box-select rectangle. Node and edge-label membership
1527
+ * is decided by `ctx.boxSelectionTest` when set,
1528
+ * otherwise by the built-in `selectionMode` (partial = any overlap via
1529
+ * `rectsIntersect`, full = fully contained via `rectContains`). Edge paths are
1530
+ * never marquee targets; an edge without a label cannot be box-selected.
1531
+ */
1532
+ function entitiesInBox(ctx: FlowStoreContext, rect: Rect): Set<string> {
1533
+ const ids = new Set<string>();
1534
+ const builtinFull = !ctx.boxSelectionTest && ctx.selectionMode === 'full';
1535
+ const test: BoxSelectionTest =
1536
+ ctx.boxSelectionTest ?? (builtinFull ? rectContains : rectsIntersect);
1537
+ const nodes = ctx.graph.nodes as FlowNode[];
1538
+
1539
+ for (const node of nodes) {
1540
+ if (!isExplicitlyVisibleNode(node)) continue;
1541
+ if (isHiddenByCollapsedAncestor(ctx, node.id)) continue;
1542
+ if (test(rect, nodeSelectionBounds(ctx, node))) ids.add(node.id);
1543
+ }
1544
+
1545
+ for (const edge of ctx.graph.edges as FlowEdge[]) {
1546
+ if (!isExplicitlyVisibleEdge(edge, nodes)) continue;
1547
+ if (!edge.label) continue;
1548
+ const labelBounds = resolvedEdgeLabelBounds(edge, ctx.measurements.get(edge.id))!;
1549
+ if (test(rect, labelBounds)) ids.add(edge.id);
1550
+ }
1551
+
1552
+ return ids;
1553
+ }
1554
+
1555
+ function nodeSelectionBounds(
1556
+ ctx: FlowStoreContext,
1557
+ node: FlowNode,
1558
+ visiting = new Set<string>(),
1559
+ ): Rect {
1560
+ if (node.selectionBounds) return resolvedSelectionBounds(node);
1561
+ if (!node.group || visiting.has(node.id)) return resolvedBounds(node);
1562
+ return groupGeometryForSelection(ctx, node, visiting).contentBounds;
1563
+ }
1564
+
1565
+ function groupGeometryForSelection(
1566
+ ctx: FlowStoreContext,
1567
+ node: FlowNode,
1568
+ visiting: ReadonlySet<string>,
1569
+ ): GroupGeometry {
1570
+ if (node.group!.type === 'fixed') {
1571
+ return fixedGroupGeometry(
1572
+ resolvedBounds(node),
1573
+ node.group!.contentSize ?? { width: 0, height: 0 },
1574
+ node.group!,
1575
+ );
1576
+ }
1577
+
1578
+ const nextVisiting = new Set(visiting).add(node.id);
1579
+ let childrenBounds: Rect | null = null;
1580
+ const addBounds = (bounds: Rect) => {
1581
+ if (!childrenBounds) {
1582
+ childrenBounds = bounds;
1583
+ return;
1584
+ }
1585
+ const x = Math.min(childrenBounds.x, bounds.x);
1586
+ const y = Math.min(childrenBounds.y, bounds.y);
1587
+ const right = Math.max(
1588
+ childrenBounds.x + childrenBounds.width,
1589
+ bounds.x + bounds.width,
1590
+ );
1591
+ const bottom = Math.max(
1592
+ childrenBounds.y + childrenBounds.height,
1593
+ bounds.y + bounds.height,
1594
+ );
1595
+ childrenBounds = { x, y, width: right - x, height: bottom - y };
1596
+ };
1597
+
1598
+ for (const child of ctx.graph.nodes as FlowNode[]) {
1599
+ if (child.parentId !== node.id || !isExplicitlyVisibleNode(child)) continue;
1600
+ if (isHiddenByCollapsedAncestor(ctx, child.id)) continue;
1601
+ addBounds(
1602
+ child.group && !nextVisiting.has(child.id)
1603
+ ? groupGeometryForSelection(ctx, child, nextVisiting).bounds
1604
+ : resolvedBounds(child),
1605
+ );
1606
+ }
1607
+ const nodeIndex = indexNodes(ctx.graph.nodes as FlowNode[]);
1608
+ for (const edge of ctx.graph.edges as FlowEdge[]) {
1609
+ if (edge.hidden || !edge.label) continue;
1610
+ if (edge.sourceId === node.id && edge.targetId === node.id) continue;
1611
+ if (getEdgeOwnerFromIndex(edge, nodeIndex) !== node.id) continue;
1612
+ const labelBounds = resolvedEdgeLabelBounds(
1613
+ edge,
1614
+ ctx.measurements.get(edge.id),
1615
+ );
1616
+ if (labelBounds) addBounds(labelBounds);
1617
+ }
1618
+
1619
+ return deriveGroupGeometry(
1620
+ resolvedSize(node),
1621
+ childrenBounds,
1622
+ node.group!,
1623
+ { x: node.x + (node.dx ?? 0), y: node.y + (node.dy ?? 0) },
1624
+ );
1625
+ }
1626
+
1627
+ function getMode(profile: FlowProfile, mode: string): string {
1628
+ return profile.modes[mode] ? mode : profile.defaultMode;
1629
+ }
1630
+
1631
+ function setModeTransition(
1632
+ profile: FlowProfile
1633
+ ): FlowTransition<{ type: 'setMode'; mode: string }> {
1634
+ return (ctx, event) =>
1635
+ produce(ctx, (draft) => {
1636
+ draft.mode = getMode(profile, event.mode);
1637
+ });
1638
+ }
1639
+
1640
+ function dispatchProfile<TEvent extends FlowEventObject>(
1641
+ profile: FlowProfile,
1642
+ ctx: FlowStoreContext,
1643
+ event: TEvent,
1644
+ enqueue: unknown,
1645
+ fallback?: FlowTransition<TEvent>
1646
+ ): FlowStoreContext {
1647
+ const mode = getMode(profile, ctx.mode);
1648
+ const transition = profile.modes[mode]?.on?.[event.type] ?? profile.on?.[event.type] ?? fallback;
1649
+
1650
+ if (!transition) {
1651
+ return ctx;
1652
+ }
1653
+
1654
+ return transition(ctx, event, enqueue);
1655
+ }
1656
+
1657
+ export function createFlowStore(
1658
+ initialGraph: FlowGraph = {
1659
+ nodes: [],
1660
+ edges: [],
1661
+ direction: 'down',
1662
+ },
1663
+ options: FlowStoreOptions = {}
1664
+ ) {
1665
+ const validatedInitialGraph = validateAndCloneGraph(initialGraph);
1666
+ let profile = options.profile ?? defaultFlowProfile;
1667
+ const initialMode = getMode(profile, options.mode ?? profile.defaultMode);
1668
+ const initialContext: FlowStoreContext = {
1669
+ graph: validatedInitialGraph,
1670
+ appearances: options.appearances,
1671
+ parentNodeId: null,
1672
+ depth: null,
1673
+ viewport: createViewport(),
1674
+ viewportSize: { width: 0, height: 0 },
1675
+ fitFrame: null,
1676
+ viewportStack: [],
1677
+ minZoom: options.minZoom ?? 0.1,
1678
+ maxZoom: options.maxZoom ?? 4,
1679
+ translateExtent: options.translateExtent ?? null,
1680
+ nodeExtent: options.nodeExtent ?? null,
1681
+ selection: new Set<string>(),
1682
+ selectionBox: null,
1683
+ selectionBoxBase: null,
1684
+ boxSelectionTest: options.boxSelectionTest ?? null,
1685
+ hoveredEntityIds: new Set<string>(),
1686
+ collapsedNodeIds: new Set<string>(),
1687
+ highlights: new Map<string, Map<string, unknown>>(),
1688
+ focusedEntityId: null,
1689
+ measurements: new Map<string, Rect>(),
1690
+ derivedPortMeasurements: new Map<string, Rect>(),
1691
+ canvasState: 'idle',
1692
+ draggedEntityId: null,
1693
+ dragRevision: 0,
1694
+ dragThreshold: options.dragThreshold ?? 3,
1695
+ constrainNodeMovement: options.constrainNodeMovement ?? null,
1696
+ autoPanOnDrag: options.autoPanOnDrag ?? true,
1697
+ autoPanThreshold: options.autoPanThreshold ?? 40,
1698
+ autoPanSpeed: options.autoPanSpeed ?? 15,
1699
+ connection: null,
1700
+ connectOnClick: options.connectOnClick ?? false,
1701
+ connectionDragThreshold: options.connectionDragThreshold ?? options.dragThreshold ?? 3,
1702
+ connectionClickStartHandle: null,
1703
+ panOrigin: null,
1704
+ panViewportOrigin: null,
1705
+ viewportAnimation: options.viewportAnimation ?? null,
1706
+ resizingEntityId: null,
1707
+ resizeHandle: null,
1708
+ resizeCorners: null,
1709
+ mode: initialMode,
1710
+ selectionMode: options.selectionMode ?? 'partial',
1711
+ labelAnchor: options.labelAnchor ?? 'fixed',
1712
+ configRevision: 0,
1713
+ routingRevision: 0,
1714
+ snapToGrid: options.snapToGrid ?? false,
1715
+ snapGrid: options.snapGrid ?? [10, 10],
1716
+ enableSnapLines: options.enableSnapLines ?? false,
1717
+ snapThreshold: options.snapThreshold ?? 5,
1718
+ enableSpacingGuides: options.enableSpacingGuides ?? false,
1719
+ autoLayout: {
1720
+ status: 'idle',
1721
+ algorithm: null,
1722
+ },
1723
+ layoutAnimation: {
1724
+ status: 'idle',
1725
+ offsets: new Map(),
1726
+ },
1727
+ colorMode: options.colorMode ?? 'system',
1728
+ };
1729
+ // Node/edge array order is fixed during a drag gesture. Build its topology
1730
+ // once at the boundary, then reuse direct indices on every pointer frame.
1731
+ let activeDragMovementTopology: MovementTopology | null = null;
1732
+
1733
+ const storeWithHistory = createStore<
1734
+ FlowStoreContext,
1735
+ FlowEventPayloadMap,
1736
+ FlowEmittedPayloadMap
1737
+ >({
1738
+ context: initialContext,
1739
+ on: {
1740
+ // Graph mutations
1741
+
1742
+ createNode: (ctx, event: { node: FlowNode } & TransactionMetadata, enqueue) =>
1743
+ produce(ctx, (draft) => {
1744
+ if (draft.graph.nodes.some((n) => n.id === event.node.id)) {
1745
+ enqueue.emit.error({
1746
+ error: new Error(
1747
+ `createNode rejected: a node with id "${event.node.id}" already exists. ` +
1748
+ `Node ids must be unique — use updateNodeData to modify the existing node, or create the node with a different id.`
1749
+ ),
1750
+ event: createEventObject('createNode', event),
1751
+ });
1752
+ return;
1753
+ }
1754
+ draft.graph.nodes.push(event.node);
1755
+ invalidatePathsForNodeGeometry(draft, new Set([event.node.id]));
1756
+ enqueue.emit.graphChanged({
1757
+ graph: snapshotGraph(draft.graph),
1758
+ event: createEventObject('createNode', event),
1759
+ });
1760
+ }),
1761
+
1762
+ deleteNode: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>
1763
+ produce(ctx, (draft) => {
1764
+ const nodesBefore = new Map(
1765
+ draft.graph.nodes.map((node) => [node.id, node]),
1766
+ );
1767
+ const edgeIdsBefore = draft.graph.edges.map((e) => e.id);
1768
+ applyNodeDeletionStrategy(
1769
+ draft,
1770
+ new Set([event.id]),
1771
+ new Set(),
1772
+ options.onDeleteNodes ?? 'cascade'
1773
+ );
1774
+ const remainingNodeIds = new Set(draft.graph.nodes.map((node) => node.id));
1775
+ const remainingEdgeIds = new Set(draft.graph.edges.map((e) => e.id));
1776
+ const deletedNodeIds = [...nodesBefore.keys()].filter(
1777
+ (id) => !remainingNodeIds.has(id),
1778
+ );
1779
+ const deletedNodeIdSet = new Set(deletedNodeIds);
1780
+ const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));
1781
+ const deletedIds = [...deletedNodeIds, ...deletedEdgeIds];
1782
+ const deletedPortIds = deletedNodeIds.flatMap((id) =>
1783
+ portAddressableIds(nodesBefore.get(id)!),
1784
+ );
1785
+ invalidatePathsForNodeGeometry(
1786
+ draft,
1787
+ deletedNodeIdSet,
1788
+ [...nodesBefore.values()],
1789
+ );
1790
+ pruneDeletedAddressables(draft, [...deletedIds, ...deletedPortIds]);
1791
+ enqueue.emit.entitiesDeleted({
1792
+ ids: deletedIds,
1793
+ event: createEventObject('deleteNode', event),
1794
+ });
1795
+ enqueue.emit.graphChanged({
1796
+ graph: snapshotGraph(draft.graph),
1797
+ event: createEventObject('deleteNode', event),
1798
+ });
1799
+ enqueue.emit.selectionChanged({
1800
+ selection: new Set(draft.selection),
1801
+ event: createEventObject('deleteNode', event),
1802
+ });
1803
+ }),
1804
+
1805
+ updateNodeData: (
1806
+ ctx,
1807
+ event: {
1808
+ id: string;
1809
+ data: Record<string, unknown>;
1810
+ } & TransactionMetadata,
1811
+ enqueue
1812
+ ) =>
1813
+ produce(ctx, (draft) => {
1814
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
1815
+ if (node) {
1816
+ if (!node.data) node.data = {};
1817
+ Object.assign(node.data, event.data);
1818
+ enqueue.emit.graphChanged({
1819
+ graph: snapshotGraph(draft.graph),
1820
+ event: createEventObject('updateNodeData', event),
1821
+ });
1822
+ }
1823
+ }),
1824
+
1825
+ updateNode: (ctx, event: FlowUpdateNodeEvent, enqueue) =>
1826
+ produce(ctx, (draft) => {
1827
+ const index = draft.graph.nodes.findIndex((n) => n.id === event.id);
1828
+ if (index < 0) {
1829
+ enqueue.emit.error({
1830
+ error: new Error(`updateNode rejected: node "${event.id}" does not exist.`),
1831
+ event: createEventObject('updateNode', event),
1832
+ });
1833
+ return;
1834
+ }
1835
+ const previous = current(draft.graph.nodes[index]) as FlowNode;
1836
+ const next = event.updater
1837
+ ? event.updater(previous)
1838
+ : ({ ...previous, ...event.patch } as FlowNode);
1839
+ const problem = validateUpdatedNode(previous, next);
1840
+ if (problem) {
1841
+ enqueue.emit.error({
1842
+ error: new Error(problem),
1843
+ event: createEventObject('updateNode', event),
1844
+ });
1845
+ return;
1846
+ }
1847
+ draft.graph.nodes[index] = { ...next };
1848
+ const nextPortIds = new Set(portAddressableIds(next));
1849
+ const removedPortIds = portAddressableIds(previous).filter((id) => !nextPortIds.has(id));
1850
+ if (removedPortIds.length > 0) {
1851
+ const previousSelection = new Set(draft.selection);
1852
+ pruneDeletedAddressables(draft, removedPortIds);
1853
+ if (!setsEqual(previousSelection, draft.selection)) {
1854
+ enqueue.emit.selectionChanged({
1855
+ selection: new Set(draft.selection),
1856
+ event: createEventObject('updateNode', event),
1857
+ });
1858
+ }
1859
+ }
1860
+ if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) {
1861
+ draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous, ctx.appearances)));
1862
+ const node = draft.graph.nodes[index];
1863
+ node.x -= previous.measured?.anchorOffset?.x ?? 0;
1864
+ node.y -= previous.measured?.anchorOffset?.y ?? 0;
1865
+ delete node.measured;
1866
+ draft.measurements.delete(node.id);
1867
+ }
1868
+ if (nodeEndpointGeometryChanged(previous, next)) {
1869
+ invalidatePathsForNodeGeometry(draft, new Set([event.id]));
1870
+ }
1871
+ enqueue.emit.graphChanged({
1872
+ graph: snapshotGraph(draft.graph),
1873
+ event: createEventObject('updateNode', event),
1874
+ });
1875
+ }),
1876
+
1877
+ createEdge: (ctx, event: { edge: FlowEdge } & TransactionMetadata, enqueue) =>
1878
+ produce(ctx, (draft) => {
1879
+ const problem = validateNewEdge(draft, event.edge);
1880
+ if (problem) {
1881
+ enqueue.emit.error({
1882
+ error: new Error(problem),
1883
+ event: createEventObject('createEdge', event),
1884
+ });
1885
+ return;
1886
+ }
1887
+ draft.graph.edges.push(event.edge);
1888
+ enqueue.emit.graphChanged({
1889
+ graph: snapshotGraph(draft.graph),
1890
+ event: createEventObject('createEdge', event),
1891
+ });
1892
+ }),
1893
+
1894
+ deleteEdge: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>
1895
+ produce(ctx, (draft) => {
1896
+ draft.graph.edges = draft.graph.edges.filter((e) => e.id !== event.id);
1897
+ pruneDeletedAddressables(draft, [event.id]);
1898
+ enqueue.emit.entitiesDeleted({
1899
+ ids: [event.id],
1900
+ event: createEventObject('deleteEdge', event),
1901
+ });
1902
+ enqueue.emit.graphChanged({
1903
+ graph: snapshotGraph(draft.graph),
1904
+ event: createEventObject('deleteEdge', event),
1905
+ });
1906
+ enqueue.emit.selectionChanged({
1907
+ selection: new Set(draft.selection),
1908
+ event: createEventObject('deleteEdge', event),
1909
+ });
1910
+ }),
1911
+
1912
+ deleteEntities: (
1913
+ ctx,
1914
+ event: {
1915
+ nodeIds?: string[];
1916
+ edgeIds?: string[];
1917
+ } & TransactionMetadata,
1918
+ enqueue
1919
+ ) =>
1920
+ produce(ctx, (draft) => {
1921
+ const nodesToDelete = new Set(event.nodeIds ?? []);
1922
+ const edgesToDelete = new Set(event.edgeIds ?? []);
1923
+ const existingNodes = draft.graph.nodes.filter((node) => nodesToDelete.has(node.id));
1924
+ const edgeIdsBefore = draft.graph.edges.map((edge) => edge.id);
1925
+ const nodesBefore = new Map(
1926
+ draft.graph.nodes.map((node) => [node.id, node]),
1927
+ );
1928
+ if (existingNodes.length === 0 && edgesToDelete.size === 0) return;
1929
+
1930
+ applyNodeDeletionStrategy(
1931
+ draft,
1932
+ nodesToDelete,
1933
+ edgesToDelete,
1934
+ options.onDeleteNodes ?? 'cascade'
1935
+ );
1936
+
1937
+ const remainingNodeIds = new Set(draft.graph.nodes.map((node) => node.id));
1938
+ const remainingEdgeIds = new Set(draft.graph.edges.map((edge) => edge.id));
1939
+ const deletedNodeIds = [...nodesBefore.keys()].filter(
1940
+ (id) => !remainingNodeIds.has(id),
1941
+ );
1942
+ const deletedNodeIdSet = new Set(deletedNodeIds);
1943
+ const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));
1944
+ if (deletedNodeIds.length === 0 && deletedEdgeIds.length === 0) return;
1945
+
1946
+ const deletedPortIds = deletedNodeIds.flatMap((id) =>
1947
+ portAddressableIds(nodesBefore.get(id)!),
1948
+ );
1949
+ invalidatePathsForNodeGeometry(
1950
+ draft,
1951
+ deletedNodeIdSet,
1952
+ [...nodesBefore.values()],
1953
+ );
1954
+ pruneDeletedAddressables(draft, [
1955
+ ...deletedNodeIds,
1956
+ ...deletedEdgeIds,
1957
+ ...deletedPortIds,
1958
+ ]);
1959
+ enqueue.emit.entitiesDeleted({
1960
+ ids: [...deletedNodeIds, ...deletedEdgeIds],
1961
+ event: createEventObject('deleteEntities', event),
1962
+ });
1963
+ enqueue.emit.graphChanged({
1964
+ graph: snapshotGraph(draft.graph),
1965
+ event: createEventObject('deleteEntities', event),
1966
+ });
1967
+ enqueue.emit.selectionChanged({
1968
+ selection: new Set(draft.selection),
1969
+ event: createEventObject('deleteEntities', event),
1970
+ });
1971
+ }),
1972
+
1973
+ updateEdgeData: (
1974
+ ctx,
1975
+ event: {
1976
+ id: string;
1977
+ data: Record<string, unknown>;
1978
+ } & TransactionMetadata,
1979
+ enqueue
1980
+ ) =>
1981
+ produce(ctx, (draft) => {
1982
+ const edge = draft.graph.edges.find((e) => e.id === event.id);
1983
+ if (edge) {
1984
+ if (!edge.data) edge.data = {};
1985
+ Object.assign(edge.data, event.data);
1986
+ enqueue.emit.graphChanged({
1987
+ graph: snapshotGraph(draft.graph),
1988
+ event: createEventObject('updateEdgeData', event),
1989
+ });
1990
+ }
1991
+ }),
1992
+
1993
+ updateEdge: (ctx, event: FlowUpdateEdgeEvent, enqueue) =>
1994
+ produce(ctx, (draft) => {
1995
+ const index = draft.graph.edges.findIndex((e) => e.id === event.id);
1996
+ if (index < 0) {
1997
+ enqueue.emit.error({
1998
+ error: new Error(`updateEdge rejected: edge "${event.id}" does not exist.`),
1999
+ event: createEventObject('updateEdge', event),
2000
+ });
2001
+ return;
2002
+ }
2003
+ const previous = current(draft.graph.edges[index]) as FlowEdge;
2004
+ const next = event.updater
2005
+ ? event.updater(previous)
2006
+ : ({ ...previous, ...event.patch } as FlowEdge);
2007
+ const problem = validateUpdatedEdge(previous, next);
2008
+ if (problem) {
2009
+ enqueue.emit.error({
2010
+ error: new Error(problem),
2011
+ event: createEventObject('updateEdge', event),
2012
+ });
2013
+ return;
2014
+ }
2015
+ draft.graph.edges[index] = next;
2016
+ if (JSON.stringify(previous.label?.appearance) !== JSON.stringify(next.label?.appearance)) {
2017
+ if (previous.label) draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous.label, ctx.appearances)));
2018
+ draft.measurements.delete(previous.id);
2019
+ invalidateAuthoritativeEdgePath(draft.graph.edges[index]);
2020
+ }
2021
+ enqueue.emit.graphChanged({
2022
+ graph: snapshotGraph(draft.graph),
2023
+ event: createEventObject('updateEdge', event),
2024
+ });
2025
+ }),
2026
+
2027
+ deleteSelected: (ctx, _event: object, enqueue) =>
2028
+ produce(ctx, (draft) => {
2029
+ const sel = draft.selection;
2030
+ const nodesToDelete = new Set<string>();
2031
+ const edgesToDelete = new Set<string>();
2032
+ for (const id of sel) {
2033
+ if (draft.graph.nodes.some((n) => n.id === id)) {
2034
+ nodesToDelete.add(id);
2035
+ }
2036
+ if (draft.graph.edges.some((e) => e.id === id)) {
2037
+ edgesToDelete.add(id);
2038
+ }
2039
+ }
2040
+ if (nodesToDelete.size === 0 && edgesToDelete.size === 0) return;
2041
+
2042
+ const nodesBefore = new Map(
2043
+ draft.graph.nodes.map((node) => [node.id, node]),
2044
+ );
2045
+ const edgeIdsBefore = draft.graph.edges.map((edge) => edge.id);
2046
+
2047
+ applyNodeDeletionStrategy(
2048
+ draft,
2049
+ nodesToDelete,
2050
+ edgesToDelete,
2051
+ options.onDeleteNodes ?? 'cascade'
2052
+ );
2053
+
2054
+ const remainingNodeIds = new Set(draft.graph.nodes.map((node) => node.id));
2055
+ const remainingEdgeIds = new Set(draft.graph.edges.map((edge) => edge.id));
2056
+ const deletedNodeIds = [...nodesBefore.keys()].filter(
2057
+ (id) => !remainingNodeIds.has(id),
2058
+ );
2059
+ const deletedNodeIdSet = new Set(deletedNodeIds);
2060
+ const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));
2061
+ const deletedIds = [...deletedNodeIds, ...deletedEdgeIds];
2062
+ const deletedPortIds = deletedNodeIds.flatMap((id) =>
2063
+ portAddressableIds(nodesBefore.get(id)!),
2064
+ );
2065
+ invalidatePathsForNodeGeometry(
2066
+ draft,
2067
+ deletedNodeIdSet,
2068
+ [...nodesBefore.values()],
2069
+ );
2070
+
2071
+ draft.selection.clear();
2072
+ draft.focusedEntityId = null;
2073
+ for (const id of [...deletedIds, ...deletedPortIds]) {
2074
+ draft.measurements.delete(id);
2075
+ draft.derivedPortMeasurements.delete(id);
2076
+ }
2077
+ pruneVisualState(draft, [...deletedIds, ...deletedPortIds]);
2078
+ enqueue.emit.entitiesDeleted({
2079
+ ids: deletedIds,
2080
+ event: createEventObject('deleteSelected', _event),
2081
+ });
2082
+ enqueue.emit.graphChanged({
2083
+ graph: snapshotGraph(draft.graph),
2084
+ event: createEventObject('deleteSelected', _event),
2085
+ });
2086
+ enqueue.emit.selectionChanged({
2087
+ selection: new Set(draft.selection),
2088
+ event: createEventObject('deleteSelected', _event),
2089
+ });
2090
+ }),
2091
+
2092
+ setGraph: (ctx, event: { graph: FlowGraph }, enqueue) => {
2093
+ let graph: FlowGraph;
2094
+ try {
2095
+ graph = validateAndCloneGraph(event.graph);
2096
+ } catch (error) {
2097
+ enqueue.emit.error({ error, event: createEventObject('setGraph', event) });
2098
+ return ctx;
2099
+ }
2100
+ return produce(ctx, (draft) => {
2101
+ draft.graph = graph;
2102
+ draft.selection.clear();
2103
+ draft.hoveredEntityIds = new Set();
2104
+ draft.highlights = new Map();
2105
+ draft.focusedEntityId = null;
2106
+ draft.canvasState = 'idle';
2107
+ draft.draggedEntityId = null;
2108
+ draft.connection = null;
2109
+ draft.connectionClickStartHandle = null;
2110
+ draft.selectionBox = null;
2111
+ draft.selectionBoxBase = null;
2112
+ draft.collapsedNodeIds = new Set();
2113
+ draft.measurements.clear();
2114
+ draft.derivedPortMeasurements.clear();
2115
+ enqueue.emit.graphChanged({
2116
+ graph: snapshotGraph(draft.graph),
2117
+ event: createEventObject('setGraph', event),
2118
+ });
2119
+ enqueue.emit.selectionChanged({
2120
+ selection: new Set(draft.selection),
2121
+ event: createEventObject('setGraph', event),
2122
+ });
2123
+ });
2124
+ },
2125
+
2126
+ replaceGraph: (
2127
+ ctx,
2128
+ event: {
2129
+ graph: FlowGraph;
2130
+ graphChanged?: boolean;
2131
+ resetMeasurementIds?: readonly string[];
2132
+ layoutAnimationOffsets?: Map<string, Point>;
2133
+ } & ReplaceGraphMetadata,
2134
+ enqueue
2135
+ ) =>
2136
+ event.graphChanged === false && event.retention !== 'reset' && !event.layoutAnimationOffsets && !event.resetMeasurementIds?.length
2137
+ ? ctx
2138
+ : produce(ctx, (draft) => {
2139
+ for (const id of event.resetMeasurementIds ?? []) {
2140
+ for (const key of draft.measurements.keys()) {
2141
+ if (key === id || key.startsWith(`${id}:`)) {
2142
+ draft.measurements.delete(key);
2143
+ draft.derivedPortMeasurements.delete(key);
2144
+ }
2145
+ }
2146
+ const previous = ctx.graph.nodes.find((node) => node.id === id);
2147
+ if (previous) {
2148
+ for (const key of portAddressableIds(previous)) {
2149
+ draft.measurements.delete(key);
2150
+ draft.derivedPortMeasurements.delete(key);
2151
+ }
2152
+ draft.measurements.delete(appearanceMeasurementId(id, resolveAppearance(previous, ctx.appearances)));
2153
+ }
2154
+ }
2155
+ const previousSelection = new Set(draft.selection);
2156
+ const previousNodes = new Map(ctx.graph.nodes.map((node) => [node.id, node]));
2157
+ const changedAppearances = new Set<string>();
2158
+ const nodes = event.graph.nodes.map((node) => {
2159
+ const previous = previousNodes.get(node.id);
2160
+ if (!previous || JSON.stringify(previous.appearance) === JSON.stringify(node.appearance)) return node;
2161
+ const next = { ...node,
2162
+ x: node.x - (node.measured?.anchorOffset?.x ?? 0),
2163
+ y: node.y - (node.measured?.anchorOffset?.y ?? 0),
2164
+ };
2165
+ delete next.measured;
2166
+ draft.measurements.delete(node.id);
2167
+ changedAppearances.add(node.id);
2168
+ return next;
2169
+ });
2170
+ draft.graph = {
2171
+ ...event.graph,
2172
+ // Keep the committed array when no appearance changed.
2173
+ nodes: changedAppearances.size ? nodes : event.graph.nodes,
2174
+ };
2175
+ if (changedAppearances.size) invalidatePathsForNodeGeometry(draft, changedAppearances);
2176
+ draft.layoutAnimation = event.layoutAnimationOffsets?.size
2177
+ ? {
2178
+ status: 'running',
2179
+ offsets: new Map(event.layoutAnimationOffsets),
2180
+ }
2181
+ : { status: 'idle', offsets: new Map() };
2182
+ const ids = graphAddressableIds(draft.graph);
2183
+ const nodeIds = new Set(draft.graph.nodes.map((node) => node.id));
2184
+ const edgeIds = new Set(draft.graph.edges.map((edge) => edge.id));
2185
+ if (event.retention === 'reset') {
2186
+ draft.selection.clear();
2187
+ draft.hoveredEntityIds.clear();
2188
+ draft.highlights.clear();
2189
+ draft.focusedEntityId = null;
2190
+ draft.parentNodeId = null;
2191
+ draft.canvasState = 'idle';
2192
+ draft.draggedEntityId = null;
2193
+ draft.connection = null;
2194
+ draft.connectionClickStartHandle = null;
2195
+ draft.selectionBox = null;
2196
+ draft.selectionBoxBase = null;
2197
+ draft.panOrigin = null;
2198
+ draft.panViewportOrigin = null;
2199
+ draft.resizingEntityId = null;
2200
+ draft.resizeHandle = null;
2201
+ draft.resizeCorners = null;
2202
+ draft.collapsedNodeIds.clear();
2203
+ draft.measurements.clear();
2204
+ draft.derivedPortMeasurements.clear();
2205
+ } else {
2206
+ // Replace these sets only when an id is gone: a new
2207
+ // `collapsedNodeIds` re-notifies every entity view.
2208
+ if ([...draft.selection].some((id) => !ids.has(id))) {
2209
+ draft.selection = new Set([...draft.selection].filter((id) => ids.has(id)));
2210
+ }
2211
+ if ([...draft.hoveredEntityIds].some((id) => !ids.has(id))) {
2212
+ draft.hoveredEntityIds = new Set(
2213
+ [...draft.hoveredEntityIds].filter((id) => ids.has(id))
2214
+ );
2215
+ }
2216
+ if ([...draft.collapsedNodeIds].some((id) => !nodeIds.has(id))) {
2217
+ draft.collapsedNodeIds = new Set(
2218
+ [...draft.collapsedNodeIds].filter((id) => nodeIds.has(id))
2219
+ );
2220
+ }
2221
+ for (const [kind, bucket] of draft.highlights) {
2222
+ for (const id of bucket.keys()) {
2223
+ if (!ids.has(id)) bucket.delete(id);
2224
+ }
2225
+ if (bucket.size === 0) draft.highlights.delete(kind);
2226
+ }
2227
+ draft.focusedEntityId =
2228
+ draft.focusedEntityId && ids.has(draft.focusedEntityId)
2229
+ ? draft.focusedEntityId
2230
+ : null;
2231
+ draft.parentNodeId =
2232
+ draft.parentNodeId && nodeIds.has(draft.parentNodeId) ? draft.parentNodeId : null;
2233
+ const measurementIds = new Set(ids);
2234
+ for (const node of draft.graph.nodes) {
2235
+ measurementIds.add(appearanceMeasurementId(node.id, resolveAppearance(node, ctx.appearances)));
2236
+ for (const port of node.ports ?? []) {
2237
+ const portId = (port as { id?: string }).id;
2238
+ if (portId) measurementIds.add(portId);
2239
+ measurementIds.add(`${node.id}:${port.name}`);
2240
+ }
2241
+ }
2242
+ for (const edge of draft.graph.edges) {
2243
+ if (edge.label) measurementIds.add(appearanceMeasurementId(edge.id, resolveAppearance(edge.label, ctx.appearances)));
2244
+ }
2245
+ for (const id of draft.measurements.keys()) {
2246
+ if (!measurementIds.has(id)) {
2247
+ draft.measurements.delete(id);
2248
+ draft.derivedPortMeasurements.delete(id);
2249
+ }
2250
+ }
2251
+ if (draft.draggedEntityId && !ids.has(draft.draggedEntityId)) {
2252
+ draft.draggedEntityId = null;
2253
+ if (draft.canvasState === 'dragging') draft.canvasState = 'idle';
2254
+ }
2255
+ if (draft.resizingEntityId && !nodeIds.has(draft.resizingEntityId)) {
2256
+ draft.resizingEntityId = null;
2257
+ draft.resizeHandle = null;
2258
+ draft.resizeCorners = null;
2259
+ if (draft.canvasState === 'resizing') draft.canvasState = 'idle';
2260
+ }
2261
+ const hasPort = (nodeId: string, portName: string | null) =>
2262
+ portName === null ||
2263
+ draft.graph.nodes
2264
+ .find((node) => node.id === nodeId)
2265
+ ?.ports?.some((port) => port.name === portName) === true;
2266
+ if (
2267
+ draft.connection &&
2268
+ (!nodeIds.has(draft.connection.sourceId) ||
2269
+ !hasPort(draft.connection.sourceId, draft.connection.sourcePort) ||
2270
+ (draft.connection.targetId !== null &&
2271
+ (!nodeIds.has(draft.connection.targetId) ||
2272
+ !hasPort(draft.connection.targetId, draft.connection.targetPort))) ||
2273
+ (draft.connection.reconnectingEdgeId != null &&
2274
+ !edgeIds.has(draft.connection.reconnectingEdgeId)))
2275
+ ) {
2276
+ draft.connection = null;
2277
+ draft.connectionClickStartHandle = null;
2278
+ if (draft.canvasState === 'connecting') draft.canvasState = 'idle';
2279
+ }
2280
+ if (
2281
+ draft.connectionClickStartHandle &&
2282
+ (!nodeIds.has(draft.connectionClickStartHandle.nodeId) ||
2283
+ !hasPort(
2284
+ draft.connectionClickStartHandle.nodeId,
2285
+ draft.connectionClickStartHandle.port
2286
+ ))
2287
+ ) {
2288
+ draft.connectionClickStartHandle = null;
2289
+ }
2290
+ }
2291
+ if (event.graphChanged !== false) {
2292
+ enqueue.emit.graphChanged({
2293
+ graph: snapshotGraph(draft.graph),
2294
+ event: createEventObject('replaceGraph', event),
2295
+ });
2296
+ }
2297
+ if (!setsEqual(previousSelection, draft.selection)) {
2298
+ enqueue.emit.selectionChanged({
2299
+ selection: new Set(draft.selection),
2300
+ event: createEventObject('replaceGraph', event),
2301
+ });
2302
+ }
2303
+ }),
2304
+
2305
+ setLayoutAnimationOffsets: (ctx, event: { offsets: Map<string, Point> }) =>
2306
+ produce(ctx, (draft) => {
2307
+ draft.layoutAnimation = event.offsets.size
2308
+ ? { status: 'running', offsets: new Map(event.offsets) }
2309
+ : { status: 'idle', offsets: new Map() };
2310
+ }),
2311
+
2312
+ clearLayoutAnimation: (ctx) =>
2313
+ ctx.layoutAnimation.status === 'idle'
2314
+ ? ctx
2315
+ : produce(ctx, (draft) => {
2316
+ draft.layoutAnimation = { status: 'idle', offsets: new Map() };
2317
+ }),
2318
+
2319
+ loadDocument: (
2320
+ ctx,
2321
+ event: {
2322
+ graph: FlowGraph;
2323
+ collapsedNodeIds: string[];
2324
+ viewport: Viewport;
2325
+ } & TransactionMetadata,
2326
+ enqueue
2327
+ ) =>
2328
+ produce(ctx, (draft) => {
2329
+ draft.graph = event.graph;
2330
+ draft.viewport = event.viewport;
2331
+ draft.collapsedNodeIds = new Set(event.collapsedNodeIds);
2332
+ draft.selection.clear();
2333
+ draft.hoveredEntityIds.clear();
2334
+ draft.highlights.clear();
2335
+ draft.focusedEntityId = null;
2336
+ draft.measurements.clear();
2337
+ draft.derivedPortMeasurements.clear();
2338
+ draft.canvasState = 'idle';
2339
+ draft.draggedEntityId = null;
2340
+ draft.connection = null;
2341
+ draft.connectionClickStartHandle = null;
2342
+ draft.selectionBox = null;
2343
+ draft.selectionBoxBase = null;
2344
+ enqueue.emit.graphChanged({
2345
+ graph: snapshotGraph(draft.graph),
2346
+ event: createEventObject('loadDocument', event),
2347
+ });
2348
+ enqueue.emit.viewportChanged({
2349
+ viewport: { ...draft.viewport },
2350
+ event: createEventObject('loadDocument', event),
2351
+ });
2352
+ enqueue.emit.selectionChanged({
2353
+ selection: new Set(),
2354
+ event: createEventObject('loadDocument', event),
2355
+ });
2356
+ }),
2357
+
2358
+ setCollapsedNodes: (ctx, event: { ids: string[] }) =>
2359
+ produce(ctx, (draft) => {
2360
+ draft.collapsedNodeIds = new Set(event.ids);
2361
+ }),
2362
+
2363
+ reset: (ctx, _event: object, enqueue) =>
2364
+ produce(ctx, (draft) => {
2365
+ Object.assign(draft, {
2366
+ ...initialContext,
2367
+ // Preserve viewport size (container hasn't changed)
2368
+ viewportSize: draft.viewportSize,
2369
+ });
2370
+ enqueue.emit.graphChanged({
2371
+ graph: snapshotGraph(draft.graph),
2372
+ event: createEventObject('reset', _event),
2373
+ });
2374
+ enqueue.emit.selectionChanged({
2375
+ selection: new Set(draft.selection),
2376
+ event: createEventObject('reset', _event),
2377
+ });
2378
+ }),
2379
+
2380
+ reparentNode: (
2381
+ ctx,
2382
+ event: { id: string; parentId: string | null } & TransactionMetadata,
2383
+ enqueue
2384
+ ) =>
2385
+ produce(ctx, (draft) => {
2386
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
2387
+ if (!node) return;
2388
+ const problem = reparentProblem(draft.graph as FlowGraph, event.id, event.parentId);
2389
+ if (problem) {
2390
+ enqueue.emit.error({
2391
+ error: new Error(problem),
2392
+ event: createEventObject('reparentNode', event),
2393
+ });
2394
+ return;
2395
+ }
2396
+ const beforeAffected = withDerivedGroupAncestors(
2397
+ draft.graph.nodes,
2398
+ new Set([event.id]),
2399
+ );
2400
+ node.parentId = event.parentId;
2401
+ const affected = new Set([
2402
+ ...beforeAffected,
2403
+ ...withDerivedGroupAncestors(
2404
+ draft.graph.nodes,
2405
+ new Set([event.id]),
2406
+ ),
2407
+ ]);
2408
+ invalidatePathsForNodeGeometry(draft, affected);
2409
+ enqueue.emit.graphChanged({
2410
+ graph: snapshotGraph(draft.graph),
2411
+ event: createEventObject('reparentNode', event),
2412
+ });
2413
+ }),
2414
+
2415
+ collapseNode: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>
2416
+ produce(ctx, (draft) => {
2417
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
2418
+ if (!node) {
2419
+ enqueue.emit.error({
2420
+ error: new Error(`collapseNode rejected: node "${event.id}" does not exist.`),
2421
+ event: createEventObject('collapseNode', event),
2422
+ });
2423
+ return;
2424
+ }
2425
+ draft.collapsedNodeIds.add(event.id);
2426
+ for (const id of draft.selection) {
2427
+ if (id !== event.id && isDescendantOf(draft.graph.nodes as FlowNode[], id, event.id)) {
2428
+ draft.selection.delete(id);
2429
+ }
2430
+ }
2431
+ enqueue.emit.graphChanged({
2432
+ graph: snapshotGraph(draft.graph),
2433
+ event: createEventObject('collapseNode', event),
2434
+ });
2435
+ enqueue.emit.selectionChanged({
2436
+ selection: new Set(draft.selection),
2437
+ event: createEventObject('collapseNode', event),
2438
+ });
2439
+ }),
2440
+
2441
+ expandNode: (ctx, event: { id: string } & TransactionMetadata, enqueue) =>
2442
+ produce(ctx, (draft) => {
2443
+ draft.collapsedNodeIds.delete(event.id);
2444
+ enqueue.emit.graphChanged({
2445
+ graph: snapshotGraph(draft.graph),
2446
+ event: createEventObject('expandNode', event),
2447
+ });
2448
+ }),
2449
+
2450
+ // Drag lifecycle
2451
+
2452
+ dragStart: (ctx, event: { id: string } & TransactionMetadata, enqueue) => {
2453
+ const topology = createMovementTopology(
2454
+ ctx.graph.nodes as FlowNode[],
2455
+ ctx.graph.edges as FlowEdge[],
2456
+ );
2457
+ const nodeIndex = topology.nodeIndices.get(event.id);
2458
+ const edgeIndex = topology.edgeIndices.get(event.id);
2459
+ const entity =
2460
+ nodeIndex === undefined
2461
+ ? edgeIndex === undefined
2462
+ ? undefined
2463
+ : ctx.graph.edges[edgeIndex]
2464
+ : ctx.graph.nodes[nodeIndex];
2465
+ if (!entity || entity.draggable === false) {
2466
+ activeDragMovementTopology = null;
2467
+ return ctx;
2468
+ }
2469
+ activeDragMovementTopology = topology;
2470
+ const selectedIds = new Set(ctx.selection);
2471
+ selectedIds.add(event.id);
2472
+ const ids = [...selectedIds];
2473
+ const positions = entityPositions(ctx.graph, ids, undefined, topology);
2474
+ return produce(ctx, (draft) => {
2475
+ draft.canvasState = 'dragging';
2476
+ draft.draggedEntityId = event.id;
2477
+ draft.selection.add(event.id);
2478
+ enqueue.emit.dragStarted({
2479
+ ids,
2480
+ positions,
2481
+ });
2482
+ });
2483
+ },
2484
+
2485
+ dragMove: (ctx, event: { dx: number; dy: number }, enqueue) => {
2486
+ if (ctx.canvasState !== 'dragging') return ctx;
2487
+
2488
+ const { dx, dy } = event;
2489
+ if (dx === 0 && dy === 0) return ctx;
2490
+
2491
+ // Raw dx/dy — no snapping here. Snap is visual (resolvedBounds)
2492
+ // and baked on commitDrag.
2493
+ // This runs once per pointer frame: compute everything on the plain
2494
+ // pre-transition context (draft proxy reads are ~10× slower), then
2495
+ // touch only the moved entities in the draft.
2496
+ const plan = planNodeMovement(
2497
+ ctx,
2498
+ dx,
2499
+ dy,
2500
+ { includeLabels: true },
2501
+ activeDragMovementTopology ?? undefined,
2502
+ );
2503
+ if (!plan) return ctx;
2504
+ const ids = [...ctx.selection];
2505
+ const positions = entityPositions(
2506
+ ctx.graph,
2507
+ ids,
2508
+ plan,
2509
+ activeDragMovementTopology ?? undefined,
2510
+ );
2511
+
2512
+ return produce(ctx, (draft) => {
2513
+ applyMovementPlan(draft, plan);
2514
+ draft.dragRevision++;
2515
+ enqueue.emit.dragMoved({
2516
+ ids,
2517
+ positions,
2518
+ delta: { x: dx, y: dy },
2519
+ });
2520
+ });
2521
+ },
2522
+
2523
+ dragEnd: (ctx, _event: object, enqueue) => {
2524
+ if (ctx.canvasState !== 'dragging') return ctx;
2525
+ activeDragMovementTopology = null;
2526
+ return produce(ctx, (draft) => {
2527
+ const ids = [...draft.selection];
2528
+ enqueue.emit.dragEnded({
2529
+ ids,
2530
+ positions: entityPositions(draft.graph, ids),
2531
+ });
2532
+ draft.canvasState = 'idle';
2533
+ draft.draggedEntityId = null;
2534
+ });
2535
+ },
2536
+
2537
+ dragCancel: (ctx) => {
2538
+ activeDragMovementTopology = null;
2539
+ return produce(ctx, (draft) => {
2540
+ for (const node of draft.graph.nodes) {
2541
+ delete node.dx;
2542
+ delete node.dy;
2543
+ }
2544
+ for (const edge of draft.graph.edges) {
2545
+ delete edge.dx;
2546
+ delete edge.dy;
2547
+ if (edge.label) {
2548
+ delete edge.label.dx;
2549
+ delete edge.label.dy;
2550
+ }
2551
+ }
2552
+ draft.canvasState = 'idle';
2553
+ draft.draggedEntityId = null;
2554
+ });
2555
+ },
2556
+
2557
+ commitDrag: (
2558
+ ctx,
2559
+ _event: (TransactionMetadata & { snapOffset?: Point }) | undefined,
2560
+ enqueue,
2561
+ ) =>
2562
+ produce(ctx, (draft) => {
2563
+ // Compute entity snap offset if snap lines enabled
2564
+ let snapOffX = _event?.snapOffset?.x ?? 0;
2565
+ let snapOffY = _event?.snapOffset?.y ?? 0;
2566
+ if (
2567
+ _event?.snapOffset === undefined &&
2568
+ draft.enableSnapLines &&
2569
+ draft.selection.size > 0
2570
+ ) {
2571
+ const selBounds = getSelectionBounds(
2572
+ draft.graph.nodes as FlowNode[],
2573
+ draft.graph.edges as FlowEdge[],
2574
+ draft.selection as Set<string>,
2575
+ draft.measurements as Map<string, Rect>,
2576
+ { includeEdgePoints: false }
2577
+ );
2578
+ if (selBounds) {
2579
+ const sel = draft.selection as Set<string>;
2580
+ const otherRects: Rect[] = (draft.graph.nodes as FlowNode[])
2581
+ .filter((n) => !sel.has(n.id) && !n.hidden)
2582
+ .map((n) => resolvedBounds(n));
2583
+ // Include edge label bounds as snap targets
2584
+ for (const edge of draft.graph.edges as FlowEdge[]) {
2585
+ if (sel.has(edge.id) || !edge.label) continue;
2586
+ otherRects.push(
2587
+ resolvedEdgeLabelBounds(
2588
+ edge,
2589
+ (draft.measurements as Map<string, Rect>).get(edge.id)
2590
+ )!
2591
+ );
2592
+ }
2593
+ const snapResult = getSnapLines(selBounds, otherRects, {
2594
+ threshold: draft.snapThreshold / draft.viewport.zoom,
2595
+ enableSpacing: draft.enableSpacingGuides,
2596
+ });
2597
+ if (snapResult) {
2598
+ snapOffX = snapResult.snapRect.x - selBounds.x;
2599
+ snapOffY = snapResult.snapRect.y - selBounds.y;
2600
+ }
2601
+ }
2602
+ }
2603
+
2604
+ // Bake dx/dy into x/y, apply snap offsets, reset
2605
+ const gridSnap = draft.snapToGrid;
2606
+ const [gx, gy] = draft.snapGrid;
2607
+ const committedNodeDeltas = new Map<string, Point>();
2608
+ for (const node of draft.graph.nodes) {
2609
+ if (node.dx || node.dy) {
2610
+ const from = { x: node.x, y: node.y };
2611
+ let x = node.x + (node.dx ?? 0) + snapOffX;
2612
+ let y = node.y + (node.dy ?? 0) + snapOffY;
2613
+ if (gridSnap) {
2614
+ x = snapToGrid(x, gx);
2615
+ y = snapToGrid(y, gy);
2616
+ }
2617
+ node.x = x;
2618
+ node.y = y;
2619
+ node.dx = 0;
2620
+ node.dy = 0;
2621
+ committedNodeDeltas.set(node.id, {
2622
+ x: x - from.x,
2623
+ y: y - from.y,
2624
+ });
2625
+ }
2626
+ }
2627
+ const nodes = draft.graph.nodes as unknown as FlowNode[];
2628
+ const committedNodeIndex = indexNodes(nodes);
2629
+ const affectedNodeIds = withDerivedGroupAncestors(
2630
+ nodes,
2631
+ new Set(committedNodeDeltas.keys()),
2632
+ );
2633
+ for (const edge of draft.graph.edges as unknown as FlowEdge[]) {
2634
+ if (
2635
+ edge.points?.length &&
2636
+ (affectedNodeIds.has(edge.sourceId) ||
2637
+ affectedNodeIds.has(edge.targetId))
2638
+ ) {
2639
+ invalidateAuthoritativeEdgePath(edge);
2640
+ }
2641
+
2642
+ const ownerId = getEdgeOwnerFromIndex(edge, committedNodeIndex);
2643
+ const committedDelta = ownerId
2644
+ ? committedNodeDeltas.get(ownerId)
2645
+ : undefined;
2646
+ const carriesTransientGeometry = !!edge.dx || !!edge.dy;
2647
+ const dx = committedDelta?.x ?? edge.dx ?? 0;
2648
+ const dy = committedDelta?.y ?? edge.dy ?? 0;
2649
+ if (edge.waypoints?.length && (committedDelta || carriesTransientGeometry)) {
2650
+ edge.waypoints = edge.waypoints.map((point) => ({
2651
+ x: point.x + dx,
2652
+ y: point.y + dy,
2653
+ }));
2654
+ }
2655
+ if (
2656
+ carriesTransientGeometry &&
2657
+ edge.label &&
2658
+ (edge.labelAnchor ?? draft.labelAnchor) === 'fixed' &&
2659
+ (edge.label.dx || edge.label.dy)
2660
+ ) {
2661
+ edge.label.x += dx;
2662
+ edge.label.y += dy;
2663
+ edge.label.dx = 0;
2664
+ edge.label.dy = 0;
2665
+ }
2666
+ if (carriesTransientGeometry) {
2667
+ edge.dx = 0;
2668
+ edge.dy = 0;
2669
+ }
2670
+ }
2671
+ for (const edge of draft.graph.edges) {
2672
+ if (!edge.label) continue;
2673
+ if (edge.label.dx || edge.label.dy) {
2674
+ let x = edge.label.x + (edge.label.dx ?? 0) + snapOffX;
2675
+ let y = edge.label.y + (edge.label.dy ?? 0) + snapOffY;
2676
+ if (gridSnap) {
2677
+ x = snapToGrid(x, gx);
2678
+ y = snapToGrid(y, gy);
2679
+ }
2680
+ edge.label.x = x;
2681
+ edge.label.y = y;
2682
+ edge.label.dx = 0;
2683
+ edge.label.dy = 0;
2684
+ }
2685
+ }
2686
+ enqueue.emit.graphChanged({
2687
+ graph: snapshotGraph(draft.graph),
2688
+ event: createEventObject('commitDrag', _event),
2689
+ });
2690
+ }),
2691
+
2692
+ // Selection & focus
2693
+
2694
+ select: (ctx, event: { ids: string[]; mode?: 'single' | 'multi' }, enqueue) =>
2695
+ produce(ctx, (draft) => {
2696
+ const mode = event.mode ?? 'single';
2697
+ if (mode === 'single') {
2698
+ draft.selection.clear();
2699
+ }
2700
+ // Toggle logic (from viz): if ALL ids already selected in multi mode, remove them
2701
+ if (mode === 'multi' && event.ids.every((id) => draft.selection.has(id))) {
2702
+ for (const id of event.ids) {
2703
+ draft.selection.delete(id);
2704
+ }
2705
+ } else {
2706
+ for (const id of event.ids) {
2707
+ draft.selection.add(id);
2708
+ }
2709
+ }
2710
+ enqueue.emit.selectionChanged({
2711
+ selection: new Set(draft.selection),
2712
+ event: createEventObject('select', event),
2713
+ });
2714
+ }),
2715
+
2716
+ selectAll: (ctx, _event: object, enqueue) =>
2717
+ produce(ctx, (draft) => {
2718
+ for (const node of draft.graph.nodes) {
2719
+ if (!isExplicitlyVisibleNode(node as FlowNode)) continue;
2720
+ draft.selection.add(node.id);
2721
+ }
2722
+ for (const edge of draft.graph.edges) {
2723
+ if (!isExplicitlyVisibleEdge(edge as FlowEdge, draft.graph.nodes as FlowNode[]))
2724
+ continue;
2725
+ draft.selection.add(edge.id);
2726
+ }
2727
+ enqueue.emit.selectionChanged({
2728
+ selection: new Set(draft.selection),
2729
+ event: createEventObject('selectAll', _event),
2730
+ });
2731
+ }),
2732
+
2733
+ clearSelection: (ctx, _event: object, enqueue) =>
2734
+ produce(ctx, (draft) => {
2735
+ draft.selection.clear();
2736
+ enqueue.emit.selectionChanged({
2737
+ selection: new Set(draft.selection),
2738
+ event: createEventObject('clearSelection', _event),
2739
+ });
2740
+ }),
2741
+
2742
+ // Box selection lifecycle (following viz patterns)
2743
+
2744
+ selectionBoxStart: (ctx, event: { point: Point; mode?: 'single' | 'multi' }, enqueue) =>
2745
+ produce(ctx, (draft) => {
2746
+ draft.canvasState = 'selecting';
2747
+ const mode = event.mode ?? 'single';
2748
+ // Snapshot the base selection so the box can update live and, in
2749
+ // additive (shift) mode, layer the boxed entities on top of it.
2750
+ draft.selectionBoxBase = mode === 'multi' ? new Set(draft.selection) : new Set();
2751
+ if (mode === 'single') {
2752
+ draft.selection.clear();
2753
+ enqueue.emit.selectionChanged({
2754
+ selection: new Set(draft.selection),
2755
+ event: createEventObject('selectionBoxStart', event),
2756
+ });
2757
+ }
2758
+ draft.selectionBox = [
2759
+ { x: event.point.x, y: event.point.y },
2760
+ { x: event.point.x, y: event.point.y },
2761
+ ];
2762
+ }),
2763
+
2764
+ selectionBoxMove: (ctx, event: { point: Point }, enqueue) =>
2765
+ produce(ctx, (draft) => {
2766
+ if (draft.canvasState !== 'selecting' || !draft.selectionBox) return;
2767
+ draft.selectionBox[1] = { x: event.point.x, y: event.point.y };
2768
+ // Recompute the selection live every move: base ∪ entities in the box
2769
+ // (recomputed so shrinking the box deselects too). Retain entities
2770
+ // already inside in their entry order, then append newly captured
2771
+ // entities. Selection order is user intent for ordered commands.
2772
+ const rect = boxToRect(draft.selectionBox[0], draft.selectionBox[1]);
2773
+ const boxed = entitiesInBox(draft, rect);
2774
+ const next = new Set(draft.selectionBoxBase ?? []);
2775
+ for (const id of draft.selection) {
2776
+ if (boxed.has(id)) next.add(id);
2777
+ }
2778
+ for (const id of boxed) next.add(id);
2779
+ if (!setsEqual(draft.selection, next)) {
2780
+ draft.selection = next;
2781
+ enqueue.emit.selectionChanged({
2782
+ selection: new Set(draft.selection),
2783
+ event: createEventObject('selectionBoxMove', event),
2784
+ });
2785
+ }
2786
+ }),
2787
+
2788
+ selectionBoxEnd: (ctx, _event: object, enqueue) =>
2789
+ produce(ctx, (draft) => {
2790
+ if (!draft.selectionBox) return;
2791
+ // Selection is already current from the last move; just settle.
2792
+ draft.selectionBox = null;
2793
+ draft.selectionBoxBase = null;
2794
+ draft.canvasState = 'idle';
2795
+ enqueue.emit.selectionChanged({
2796
+ selection: new Set(draft.selection),
2797
+ event: createEventObject('selectionBoxEnd', _event),
2798
+ });
2799
+ }),
2800
+
2801
+ selectionBoxCancel: (ctx, _event: object, enqueue) =>
2802
+ produce(ctx, (draft) => {
2803
+ if (draft.selectionBoxBase) {
2804
+ draft.selection = new Set(draft.selectionBoxBase);
2805
+ }
2806
+ draft.selectionBox = null;
2807
+ draft.selectionBoxBase = null;
2808
+ draft.canvasState = 'idle';
2809
+ enqueue.emit.selectionChanged({
2810
+ selection: new Set(draft.selection),
2811
+ event: createEventObject('selectionBoxCancel', _event),
2812
+ });
2813
+ }),
2814
+
2815
+ focus: (ctx, event: { entityId: string }) =>
2816
+ produce(ctx, (draft) => {
2817
+ draft.focusedEntityId = event.entityId;
2818
+ }),
2819
+
2820
+ clearFocus: (ctx) =>
2821
+ produce(ctx, (draft) => {
2822
+ draft.focusedEntityId = null;
2823
+ }),
2824
+
2825
+ // Hover & highlights (visual state — not undoable)
2826
+
2827
+ setHover: (ctx, event: { ids: string[] }) => {
2828
+ // No-op when unchanged so subscribers see a stable context identity.
2829
+ if (
2830
+ ctx.hoveredEntityIds.size === event.ids.length &&
2831
+ event.ids.every((id) => ctx.hoveredEntityIds.has(id))
2832
+ ) {
2833
+ return ctx;
2834
+ }
2835
+ return produce(ctx, (draft) => {
2836
+ draft.hoveredEntityIds = new Set(event.ids);
2837
+ });
2838
+ },
2839
+
2840
+ clearHover: (ctx) => {
2841
+ if (ctx.hoveredEntityIds.size === 0) return ctx;
2842
+ return produce(ctx, (draft) => {
2843
+ draft.hoveredEntityIds = new Set();
2844
+ });
2845
+ },
2846
+
2847
+ setHighlights: (ctx, event: { kind: string; entries: FlowHighlightEntry[] }) =>
2848
+ produce(ctx, (draft) => {
2849
+ const bucket = new Map<string, unknown>();
2850
+ for (const entry of event.entries) {
2851
+ bucket.set(entry.id, entry.meta);
2852
+ }
2853
+ if (bucket.size === 0) draft.highlights.delete(event.kind);
2854
+ else draft.highlights.set(event.kind, bucket);
2855
+ }),
2856
+
2857
+ addHighlights: (ctx, event: { kind: string; entries: FlowHighlightEntry[] }) =>
2858
+ produce(ctx, (draft) => {
2859
+ let bucket = draft.highlights.get(event.kind);
2860
+ if (!bucket) {
2861
+ bucket = new Map<string, unknown>();
2862
+ draft.highlights.set(event.kind, bucket);
2863
+ }
2864
+ for (const entry of event.entries) {
2865
+ bucket.set(entry.id, entry.meta);
2866
+ }
2867
+ }),
2868
+
2869
+ removeHighlights: (ctx, event: { kind: string; ids: string[] }) =>
2870
+ produce(ctx, (draft) => {
2871
+ const bucket = draft.highlights.get(event.kind);
2872
+ if (!bucket) return;
2873
+ for (const id of event.ids) {
2874
+ bucket.delete(id);
2875
+ }
2876
+ if (bucket.size === 0) draft.highlights.delete(event.kind);
2877
+ }),
2878
+
2879
+ clearHighlights: (ctx, event: { kind?: string } | undefined) =>
2880
+ produce(ctx, (draft) => {
2881
+ if (event?.kind !== undefined) draft.highlights.delete(event.kind);
2882
+ else draft.highlights.clear();
2883
+ }),
2884
+
2885
+ // Navigation
2886
+
2887
+ updateParentNodeId: (ctx, event: { parentNodeId: string | null }) =>
2888
+ produce(ctx, (draft) => {
2889
+ draft.parentNodeId = event.parentNodeId;
2890
+ draft.selection.clear();
2891
+ draft.focusedEntityId = null;
2892
+ }),
2893
+
2894
+ setViewScope: (
2895
+ ctx,
2896
+ event: {
2897
+ parentNodeId: string | null;
2898
+ depth: number | null;
2899
+ selection: FlowViewSelectionPolicy;
2900
+ visibleEntityIds: string[];
2901
+ },
2902
+ enqueue
2903
+ ) =>
2904
+ produce(ctx, (draft) => {
2905
+ const scopeChanged =
2906
+ draft.parentNodeId !== event.parentNodeId || draft.depth !== event.depth;
2907
+ const previousSelection = new Set(draft.selection);
2908
+ const visibleIds = new Set(event.visibleEntityIds);
2909
+ draft.parentNodeId = event.parentNodeId;
2910
+ draft.depth = event.depth;
2911
+ draft.selection =
2912
+ event.selection === 'clear'
2913
+ ? new Set()
2914
+ : new Set([...draft.selection].filter((id) => visibleIds.has(id)));
2915
+ draft.hoveredEntityIds = new Set(
2916
+ [...draft.hoveredEntityIds].filter((id) => visibleIds.has(id))
2917
+ );
2918
+ draft.focusedEntityId =
2919
+ draft.focusedEntityId && visibleIds.has(draft.focusedEntityId)
2920
+ ? draft.focusedEntityId
2921
+ : null;
2922
+ if (scopeChanged) {
2923
+ draft.canvasState = 'idle';
2924
+ draft.draggedEntityId = null;
2925
+ draft.connection = null;
2926
+ draft.connectionClickStartHandle = null;
2927
+ draft.selectionBox = null;
2928
+ draft.selectionBoxBase = null;
2929
+ draft.panOrigin = null;
2930
+ draft.panViewportOrigin = null;
2931
+ draft.resizingEntityId = null;
2932
+ draft.resizeHandle = null;
2933
+ draft.resizeCorners = null;
2934
+ enqueue.emit.viewChanged({
2935
+ scope: Object.freeze({
2936
+ parentId: event.parentNodeId,
2937
+ depth: event.depth,
2938
+ }),
2939
+ event: createEventObject('setViewScope', event),
2940
+ });
2941
+ }
2942
+ if (!setsEqual(previousSelection, draft.selection)) {
2943
+ enqueue.emit.selectionChanged({
2944
+ selection: new Set(draft.selection),
2945
+ event: createEventObject('setViewScope', event),
2946
+ });
2947
+ }
2948
+ }),
2949
+
2950
+ // Viewport (flat payloads)
2951
+
2952
+ setViewport: (ctx, event: Viewport, enqueue) =>
2953
+ produce(ctx, (draft) => {
2954
+ draft.viewport = { x: event.x, y: event.y, zoom: event.zoom };
2955
+ enqueue.emit.viewportChanged({
2956
+ viewport: plainViewport(draft.viewport),
2957
+ event: createEventObject('setViewport', event),
2958
+ });
2959
+ }),
2960
+
2961
+ setFitFrame: (ctx, event: { frame: Rect | null; preserveCenter?: boolean }, enqueue) =>
2962
+ produce(ctx, (draft) => {
2963
+ const previousFrame = draft.fitFrame ?? {
2964
+ x: 0,
2965
+ y: 0,
2966
+ width: draft.viewportSize.width,
2967
+ height: draft.viewportSize.height,
2968
+ };
2969
+ const nextFrame = event.frame ?? {
2970
+ x: 0,
2971
+ y: 0,
2972
+ width: draft.viewportSize.width,
2973
+ height: draft.viewportSize.height,
2974
+ };
2975
+ draft.fitFrame = event.frame ? { ...event.frame } : null;
2976
+ if (!event.preserveCenter) return;
2977
+
2978
+ draft.viewport.x +=
2979
+ nextFrame.x + nextFrame.width / 2 - (previousFrame.x + previousFrame.width / 2);
2980
+ draft.viewport.y +=
2981
+ nextFrame.y + nextFrame.height / 2 - (previousFrame.y + previousFrame.height / 2);
2982
+ enqueue.emit.viewportChanged({
2983
+ viewport: plainViewport(draft.viewport),
2984
+ event: createEventObject('setFitFrame', event),
2985
+ });
2986
+ }),
2987
+
2988
+ panBy: (ctx, event: Point, enqueue) =>
2989
+ produce(ctx, (draft) => {
2990
+ draft.viewport.x += event.x;
2991
+ draft.viewport.y += event.y;
2992
+ if (draft.translateExtent) {
2993
+ const constrained = constrainViewport(
2994
+ draft.viewport,
2995
+ draft.viewportSize,
2996
+ draft.translateExtent as unknown as [
2997
+ { x: number; y: number },
2998
+ { x: number; y: number }
2999
+ ]
3000
+ );
3001
+ draft.viewport = constrained;
3002
+ }
3003
+ enqueue.emit.viewportChanged({
3004
+ viewport: plainViewport(draft.viewport),
3005
+ event: createEventObject('panBy', event),
3006
+ });
3007
+ }),
3008
+
3009
+ zoomTo: (ctx, event: { zoom: number; center: Point }, enqueue) =>
3010
+ produce(ctx, (draft) => {
3011
+ const clamped = Math.min(Math.max(event.zoom, draft.minZoom), draft.maxZoom);
3012
+ const ratio = clamped / draft.viewport.zoom;
3013
+ draft.viewport = {
3014
+ x: event.center.x - (event.center.x - draft.viewport.x) * ratio,
3015
+ y: event.center.y - (event.center.y - draft.viewport.y) * ratio,
3016
+ zoom: clamped,
3017
+ };
3018
+ if (draft.translateExtent) {
3019
+ const constrained = constrainViewport(
3020
+ draft.viewport,
3021
+ draft.viewportSize,
3022
+ draft.translateExtent as unknown as [
3023
+ { x: number; y: number },
3024
+ { x: number; y: number }
3025
+ ]
3026
+ );
3027
+ draft.viewport = constrained;
3028
+ }
3029
+ enqueue.emit.viewportChanged({
3030
+ viewport: plainViewport(draft.viewport),
3031
+ event: createEventObject('zoomTo', event),
3032
+ });
3033
+ }),
3034
+
3035
+ zoomBy: (ctx, event: { factor: number; center?: Point }, enqueue) =>
3036
+ produce(ctx, (draft) => {
3037
+ // Default pivot: the center of the visible viewport.
3038
+ const center =
3039
+ event.center ??
3040
+ (draft.fitFrame
3041
+ ? {
3042
+ x: draft.fitFrame.x + draft.fitFrame.width / 2,
3043
+ y: draft.fitFrame.y + draft.fitFrame.height / 2,
3044
+ }
3045
+ : {
3046
+ x: draft.viewportSize.width / 2,
3047
+ y: draft.viewportSize.height / 2,
3048
+ });
3049
+ const clamped = Math.min(
3050
+ Math.max(draft.viewport.zoom * event.factor, draft.minZoom),
3051
+ draft.maxZoom
3052
+ );
3053
+ const ratio = clamped / draft.viewport.zoom;
3054
+ draft.viewport = {
3055
+ x: center.x - (center.x - draft.viewport.x) * ratio,
3056
+ y: center.y - (center.y - draft.viewport.y) * ratio,
3057
+ zoom: clamped,
3058
+ };
3059
+ if (draft.translateExtent) {
3060
+ draft.viewport = constrainViewport(
3061
+ draft.viewport,
3062
+ draft.viewportSize,
3063
+ draft.translateExtent as unknown as [
3064
+ { x: number; y: number },
3065
+ { x: number; y: number }
3066
+ ]
3067
+ );
3068
+ }
3069
+ enqueue.emit.viewportChanged({
3070
+ viewport: plainViewport(draft.viewport),
3071
+ event: createEventObject('zoomBy', event),
3072
+ });
3073
+ }),
3074
+
3075
+ setMinZoom: (ctx, event: { minZoom: number }) =>
3076
+ produce(ctx, (draft) => {
3077
+ draft.minZoom = event.minZoom;
3078
+ if (draft.viewport.zoom < event.minZoom) {
3079
+ draft.viewport.zoom = event.minZoom;
3080
+ }
3081
+ }),
3082
+
3083
+ setMaxZoom: (ctx, event: { maxZoom: number }) =>
3084
+ produce(ctx, (draft) => {
3085
+ draft.maxZoom = event.maxZoom;
3086
+ if (draft.viewport.zoom > event.maxZoom) {
3087
+ draft.viewport.zoom = event.maxZoom;
3088
+ }
3089
+ }),
3090
+
3091
+ setDragThreshold: (ctx, event: { dragThreshold: number }) =>
3092
+ produce(ctx, (draft) => {
3093
+ draft.dragThreshold = Math.max(0, event.dragThreshold);
3094
+ }),
3095
+
3096
+ setAutoPanOptions: (
3097
+ ctx,
3098
+ event: {
3099
+ autoPanOnDrag?: boolean;
3100
+ autoPanThreshold?: number;
3101
+ autoPanSpeed?: number;
3102
+ }
3103
+ ) =>
3104
+ produce(ctx, (draft) => {
3105
+ if (event.autoPanOnDrag !== undefined) {
3106
+ draft.autoPanOnDrag = event.autoPanOnDrag;
3107
+ }
3108
+ if (event.autoPanThreshold !== undefined) {
3109
+ draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);
3110
+ }
3111
+ if (event.autoPanSpeed !== undefined) {
3112
+ draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);
3113
+ }
3114
+ }),
3115
+
3116
+ updateSettings: (ctx, event: Partial<FlowRuntimeSettings>) =>
3117
+ produce(ctx, (draft) => {
3118
+ if (event.dragThreshold !== undefined) {
3119
+ draft.dragThreshold = Math.max(0, event.dragThreshold);
3120
+ }
3121
+ if (event.constrainNodeMovement !== undefined) {
3122
+ draft.constrainNodeMovement = event.constrainNodeMovement ?? null;
3123
+ }
3124
+ if (event.autoPanOnDrag !== undefined) {
3125
+ draft.autoPanOnDrag = event.autoPanOnDrag;
3126
+ }
3127
+ if (event.autoPanThreshold !== undefined) {
3128
+ draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);
3129
+ }
3130
+ if (event.autoPanSpeed !== undefined) {
3131
+ draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);
3132
+ }
3133
+ if (event.viewportAnimation !== undefined) {
3134
+ draft.viewportAnimation = event.viewportAnimation;
3135
+ }
3136
+ if (event.enableSnapLines !== undefined) {
3137
+ draft.enableSnapLines = event.enableSnapLines;
3138
+ }
3139
+ if (event.snapThreshold !== undefined) {
3140
+ draft.snapThreshold = Math.max(0, event.snapThreshold);
3141
+ }
3142
+ if (event.enableSpacingGuides !== undefined) {
3143
+ draft.enableSpacingGuides = event.enableSpacingGuides;
3144
+ }
3145
+ if (event.boxSelectionTest !== undefined) {
3146
+ draft.boxSelectionTest = event.boxSelectionTest ?? null;
3147
+ }
3148
+ if (event.labelAnchor !== undefined) {
3149
+ draft.labelAnchor = event.labelAnchor;
3150
+ }
3151
+ }),
3152
+
3153
+ configure: (ctx, event: Partial<FlowStoreOptions>) => {
3154
+ if (event.profile) profile = event.profile;
3155
+ const previousAppearances = ctx.appearances;
3156
+ return produce(ctx, (draft) => {
3157
+ if (event.minZoom !== undefined) draft.minZoom = Math.max(0.01, event.minZoom);
3158
+ if (event.maxZoom !== undefined) draft.maxZoom = Math.max(draft.minZoom, event.maxZoom);
3159
+ if (event.translateExtent !== undefined) draft.translateExtent = event.translateExtent;
3160
+ if (event.nodeExtent !== undefined) draft.nodeExtent = event.nodeExtent;
3161
+ if (event.dragThreshold !== undefined)
3162
+ draft.dragThreshold = Math.max(0, event.dragThreshold);
3163
+ if (event.connectionDragThreshold !== undefined) {
3164
+ draft.connectionDragThreshold = Math.max(0, event.connectionDragThreshold);
3165
+ }
3166
+ if (event.constrainNodeMovement !== undefined) {
3167
+ draft.constrainNodeMovement = event.constrainNodeMovement ?? null;
3168
+ }
3169
+ if (event.autoPanOnDrag !== undefined) draft.autoPanOnDrag = event.autoPanOnDrag;
3170
+ if (event.autoPanThreshold !== undefined)
3171
+ draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);
3172
+ if (event.autoPanSpeed !== undefined)
3173
+ draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);
3174
+ if (event.viewportAnimation !== undefined)
3175
+ draft.viewportAnimation = event.viewportAnimation;
3176
+ if (event.snapToGrid !== undefined) draft.snapToGrid = event.snapToGrid;
3177
+ if (event.snapGrid !== undefined) draft.snapGrid = event.snapGrid;
3178
+ if (event.enableSnapLines !== undefined) draft.enableSnapLines = event.enableSnapLines;
3179
+ if (event.snapThreshold !== undefined)
3180
+ draft.snapThreshold = Math.max(0, event.snapThreshold);
3181
+ if (event.enableSpacingGuides !== undefined)
3182
+ draft.enableSpacingGuides = event.enableSpacingGuides;
3183
+ if (event.connectOnClick !== undefined) draft.connectOnClick = event.connectOnClick;
3184
+ if (event.colorMode !== undefined) draft.colorMode = event.colorMode;
3185
+ if (event.boxSelectionTest !== undefined)
3186
+ draft.boxSelectionTest = event.boxSelectionTest ?? null;
3187
+ if (event.selectionMode !== undefined) draft.selectionMode = event.selectionMode;
3188
+ if (event.labelAnchor !== undefined) draft.labelAnchor = event.labelAnchor;
3189
+ if (event.profile || event.mode !== undefined) {
3190
+ draft.mode = getMode(profile, event.mode ?? draft.mode);
3191
+ }
3192
+ if (event.appearances !== undefined && event.appearances !== previousAppearances) {
3193
+ draft.appearances = castDraft(event.appearances);
3194
+ const appearanceNodes = new Set<string>();
3195
+ for (const node of draft.graph.nodes) {
3196
+ if (!resolveAppearance(node, previousAppearances).reference && !resolveAppearance(node, draft.appearances).reference) continue;
3197
+ node.x -= node.measured?.anchorOffset?.x ?? 0;
3198
+ node.y -= node.measured?.anchorOffset?.y ?? 0;
3199
+ delete node.measured;
3200
+ draft.measurements.delete(node.id);
3201
+ appearanceNodes.add(node.id);
3202
+ }
3203
+ if (appearanceNodes.size) invalidatePathsForNodeGeometry(draft, appearanceNodes);
3204
+ for (const edge of draft.graph.edges) {
3205
+ if (edge.label && (resolveAppearance(edge.label, previousAppearances).reference || resolveAppearance(edge.label, draft.appearances).reference)) { draft.measurements.delete(edge.id); invalidateAuthoritativeEdgePath(edge); }
3206
+ }
3207
+ for (const id of draft.measurements.keys()) {
3208
+ if (id.startsWith('["flow-appearance-boundary",')) draft.measurements.delete(id);
3209
+ }
3210
+ }
3211
+ draft.configRevision += 1;
3212
+ });
3213
+ },
3214
+
3215
+ bumpConfigRevision: (ctx) =>
3216
+ produce(ctx, (draft) => {
3217
+ draft.configRevision += 1;
3218
+ }),
3219
+
3220
+ bumpRoutingRevision: (ctx) =>
3221
+ produce(ctx, (draft) => {
3222
+ draft.routingRevision += 1;
3223
+ }),
3224
+
3225
+ setTranslateExtent: (ctx, event: { extent: [Point, Point] | null }) =>
3226
+ produce(ctx, (draft) => {
3227
+ draft.translateExtent = event.extent;
3228
+ }),
3229
+
3230
+ setNodeExtent: (ctx, event: { extent: [Point, Point] | null }) =>
3231
+ produce(ctx, (draft) => {
3232
+ draft.nodeExtent = event.extent;
3233
+ }),
3234
+
3235
+ updateViewportSize: (ctx, event: Size & { preserveCenter?: boolean }, enqueue) =>
3236
+ produce(ctx, (draft) => {
3237
+ const previousSize = { ...draft.viewportSize };
3238
+ draft.viewportSize = { width: event.width, height: event.height };
3239
+ if (!event.preserveCenter || previousSize.width <= 0 || previousSize.height <= 0) return;
3240
+
3241
+ draft.viewport.x += (event.width - previousSize.width) / 2;
3242
+ draft.viewport.y += (event.height - previousSize.height) / 2;
3243
+ enqueue.emit.viewportChanged({
3244
+ viewport: plainViewport(draft.viewport),
3245
+ event: createEventObject('updateViewportSize', event),
3246
+ });
3247
+ }),
3248
+
3249
+ fitView: (ctx, event: FitViewOptions | undefined, enqueue) =>
3250
+ produce(ctx, (draft) => {
3251
+ if (draft.viewportSize.width === 0 || draft.viewportSize.height === 0) return;
3252
+
3253
+ const ids = event?.nodes?.map((node) => (typeof node === 'string' ? node : node.id));
3254
+ const hasIds = ids && ids.length > 0;
3255
+ const idSet = hasIds ? new Set(ids) : null;
3256
+ const nodes = hasIds
3257
+ ? (draft.graph.nodes as FlowNode[]).filter(
3258
+ (node) => idSet!.has(node.id) && isExplicitlyVisibleNode(node)
3259
+ )
3260
+ : (draft.graph.nodes as FlowNode[]).filter((node) => isExplicitlyVisibleNode(node));
3261
+ const edges = hasIds
3262
+ ? (draft.graph.edges as FlowEdge[]).filter(
3263
+ (edge) =>
3264
+ idSet!.has(edge.id) &&
3265
+ isExplicitlyVisibleEdge(edge, draft.graph.nodes as FlowNode[])
3266
+ )
3267
+ : (draft.graph.edges as FlowEdge[]).filter((edge) =>
3268
+ isExplicitlyVisibleEdge(edge, draft.graph.nodes as FlowNode[])
3269
+ );
3270
+
3271
+ const bounds = getGraphBounds(nodes, edges, draft.measurements as Map<string, Rect>);
3272
+ if (bounds.width === 0 && bounds.height === 0) return;
3273
+ const { nodes: _nodes, ...options } = event ?? {};
3274
+ const vp = viewportForBounds(bounds, draft.viewportSize, {
3275
+ ...options,
3276
+ frame: options.frame ?? draft.fitFrame ?? undefined,
3277
+ });
3278
+ draft.viewport = vp;
3279
+ enqueue.emit.viewportChanged({
3280
+ viewport: plainViewport(draft.viewport),
3281
+ event: createEventObject('fitView', event),
3282
+ });
3283
+ }),
3284
+
3285
+ pushViewport: (ctx) =>
3286
+ produce(ctx, (draft) => {
3287
+ draft.viewportStack.push({ ...draft.viewport });
3288
+ }),
3289
+
3290
+ popViewport: (ctx, _event: object, enqueue) =>
3291
+ produce(ctx, (draft) => {
3292
+ const prev = draft.viewportStack.pop();
3293
+ if (prev) {
3294
+ draft.viewport = prev;
3295
+ enqueue.emit.viewportChanged({
3296
+ viewport: plainViewport(draft.viewport),
3297
+ event: createEventObject('popViewport', _event),
3298
+ });
3299
+ }
3300
+ }),
3301
+
3302
+ // Pan lifecycle
3303
+
3304
+ panStart: (ctx, event: Point) =>
3305
+ produce(ctx, (draft) => {
3306
+ draft.canvasState = 'panning';
3307
+ draft.panOrigin = { x: event.x, y: event.y };
3308
+ draft.panViewportOrigin = { ...draft.viewport };
3309
+ }),
3310
+
3311
+ pan: (ctx, event: Point, enqueue) =>
3312
+ produce(ctx, (draft) => {
3313
+ if (!draft.panOrigin || !draft.panViewportOrigin) return;
3314
+ let newX = draft.panViewportOrigin.x + (event.x - draft.panOrigin.x);
3315
+ let newY = draft.panViewportOrigin.y + (event.y - draft.panOrigin.y);
3316
+
3317
+ // Clamp to translateExtent
3318
+ if (draft.translateExtent) {
3319
+ const z = draft.viewport.zoom;
3320
+ newX = Math.max(
3321
+ -(draft.translateExtent[1].x * z - draft.viewportSize.width),
3322
+ Math.min(newX, -draft.translateExtent[0].x * z)
3323
+ );
3324
+ newY = Math.max(
3325
+ -(draft.translateExtent[1].y * z - draft.viewportSize.height),
3326
+ Math.min(newY, -draft.translateExtent[0].y * z)
3327
+ );
3328
+ }
3329
+
3330
+ draft.viewport = {
3331
+ x: newX,
3332
+ y: newY,
3333
+ zoom: draft.panViewportOrigin.zoom,
3334
+ };
3335
+ enqueue.emit.viewportChanged({
3336
+ viewport: plainViewport(draft.viewport),
3337
+ event: createEventObject('pan', event),
3338
+ });
3339
+ }),
3340
+
3341
+ panEnd: (ctx) =>
3342
+ produce(ctx, (draft) => {
3343
+ draft.canvasState = 'idle';
3344
+ draft.panOrigin = null;
3345
+ draft.panViewportOrigin = null;
3346
+ }),
3347
+
3348
+ panCancel: (ctx, _event: object, enqueue) =>
3349
+ produce(ctx, (draft) => {
3350
+ if (draft.panViewportOrigin) {
3351
+ draft.viewport = { ...draft.panViewportOrigin };
3352
+ enqueue.emit.viewportChanged({
3353
+ viewport: plainViewport(draft.viewport),
3354
+ event: createEventObject('panCancel', _event),
3355
+ });
3356
+ }
3357
+ draft.canvasState = 'idle';
3358
+ draft.panOrigin = null;
3359
+ draft.panViewportOrigin = null;
3360
+ }),
3361
+
3362
+ // Interaction state
3363
+
3364
+ setCanvasState: (ctx, event: { state: CanvasState }) =>
3365
+ produce(ctx, (draft) => {
3366
+ draft.canvasState = event.state;
3367
+ }),
3368
+
3369
+ // Connection lifecycle
3370
+
3371
+ connectionStart: (
3372
+ ctx,
3373
+ event: {
3374
+ sourceId: string;
3375
+ sourcePort: string | null;
3376
+ position: Point;
3377
+ active?: boolean;
3378
+ reconnectingEdgeId?: string | null;
3379
+ reconnectingEnd?: 'source' | 'target' | null;
3380
+ preview?: boolean;
3381
+ },
3382
+ enqueue
3383
+ ) =>
3384
+ produce(ctx, (draft) => {
3385
+ draft.canvasState = 'connecting';
3386
+ draft.connection = {
3387
+ [connectionLifetime]: {},
3388
+ sourceId: event.sourceId,
3389
+ sourcePort: event.sourcePort,
3390
+ targetId: null,
3391
+ targetPort: null,
3392
+ startPosition: event.position,
3393
+ pointerPosition: event.position,
3394
+ active: event.active ?? false,
3395
+ preview: event.preview ?? true,
3396
+ isValid: false,
3397
+ reconnectingEdgeId: event.reconnectingEdgeId ?? null,
3398
+ reconnectingEnd: event.reconnectingEnd ?? null,
3399
+ };
3400
+ enqueue.emit.connectStarted({
3401
+ sourceId: event.sourceId,
3402
+ sourcePort: event.sourcePort,
3403
+ point: event.position,
3404
+ });
3405
+ }),
3406
+
3407
+ connectionMove: (
3408
+ ctx,
3409
+ event: {
3410
+ position: Point;
3411
+ targetId?: string | null;
3412
+ targetPort?: string | null;
3413
+ isValid?: boolean;
3414
+ invalidReason?: string;
3415
+ active?: boolean;
3416
+ },
3417
+ enqueue
3418
+ ) =>
3419
+ produce(ctx, (draft) => {
3420
+ if (!draft.connection) return;
3421
+ draft.connection.pointerPosition = event.position;
3422
+ if (event.targetId !== undefined) draft.connection.targetId = event.targetId;
3423
+ if (event.targetPort !== undefined) draft.connection.targetPort = event.targetPort;
3424
+ if (event.isValid !== undefined) draft.connection.isValid = event.isValid;
3425
+ if (event.active !== undefined) draft.connection.active = event.active;
3426
+ draft.connection.invalidReason = event.invalidReason;
3427
+ const dx = event.position.x - draft.connection.startPosition.x;
3428
+ const dy = event.position.y - draft.connection.startPosition.y;
3429
+ const threshold = draft.connectionDragThreshold;
3430
+ if (event.active === undefined && !draft.connection.active && Math.hypot(dx, dy) >= threshold) {
3431
+ draft.connection.active = true;
3432
+ }
3433
+ enqueue.emit.connectMoved({
3434
+ point: event.position,
3435
+ targetId: draft.connection.targetId,
3436
+ targetPort: draft.connection.targetPort,
3437
+ isValid: draft.connection.isValid,
3438
+ invalidReason: draft.connection.invalidReason,
3439
+ });
3440
+ }),
3441
+
3442
+ connectionEnd: (
3443
+ ctx,
3444
+ event: { target?: ConnectEndTarget; reconnectedEdgeId?: string } | undefined,
3445
+ enqueue
3446
+ ) =>
3447
+ produce(ctx, (draft) => {
3448
+ // Emit the pre-transition connection: it is plain data, while
3449
+ // draft.connection is an immer proxy that is revoked before
3450
+ // listeners run.
3451
+ const connection = ctx.connection;
3452
+ if (connection) {
3453
+ const target = event?.target ?? { kind: 'none' as const };
3454
+ const status =
3455
+ target.kind === 'none' ? 'cancelled' : connection.isValid ? 'connected' : 'invalid';
3456
+ enqueue.emit.connectionEnded({
3457
+ status,
3458
+ source: {
3459
+ nodeId: connection.sourceId,
3460
+ port: connection.sourcePort,
3461
+ },
3462
+ target,
3463
+ connection,
3464
+ ...(event?.reconnectedEdgeId ? { reconnectedEdgeId: event.reconnectedEdgeId } : {}),
3465
+ });
3466
+ }
3467
+ draft.canvasState = 'idle';
3468
+ draft.connection = null;
3469
+ draft.connectionClickStartHandle = null;
3470
+ }),
3471
+
3472
+ cancelConnection: (ctx) =>
3473
+ produce(ctx, (draft) => {
3474
+ draft.connection = null;
3475
+ draft.connectionClickStartHandle = null;
3476
+ if (draft.canvasState === 'connecting') {
3477
+ draft.canvasState = 'idle';
3478
+ }
3479
+ }),
3480
+
3481
+ // Click-to-connect
3482
+ setConnectionClickStartHandle: (ctx, event: { nodeId: string; port: string | null } | null) =>
3483
+ produce(ctx, (draft) => {
3484
+ draft.connectionClickStartHandle = event?.nodeId !== undefined
3485
+ ? { nodeId: event.nodeId, port: event.port }
3486
+ : null;
3487
+ }),
3488
+
3489
+ // Resize lifecycle (corner-based: two opposite corners, mouse moves one)
3490
+
3491
+ resizeStart: (
3492
+ ctx,
3493
+ event: { id: string; handle: ResizeHandle } & TransactionMetadata,
3494
+ enqueue
3495
+ ) =>
3496
+ produce(ctx, (draft) => {
3497
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
3498
+ if (!node) return;
3499
+ draft.canvasState = 'resizing';
3500
+ draft.resizingEntityId = event.id;
3501
+ draft.resizeHandle = event.handle;
3502
+
3503
+ // Compute current rect corners
3504
+ const x = node.x + (node.dx ?? 0);
3505
+ const y = node.y + (node.dy ?? 0);
3506
+ const { width: w, height: h } = resolvedSize(node);
3507
+ const tl = { x, y };
3508
+ const br = { x: x + w, y: y + h };
3509
+
3510
+ // [anchor (fixed corner), moving (dragged corner)]
3511
+ const handle = event.handle;
3512
+ if (handle === 'bottom-right') draft.resizeCorners = [tl, br];
3513
+ else if (handle === 'bottom-left')
3514
+ draft.resizeCorners = [
3515
+ { x: br.x, y: tl.y },
3516
+ { x: tl.x, y: br.y },
3517
+ ];
3518
+ else if (handle === 'top-right')
3519
+ draft.resizeCorners = [
3520
+ { x: tl.x, y: br.y },
3521
+ { x: br.x, y: tl.y },
3522
+ ];
3523
+ else if (handle === 'top-left') draft.resizeCorners = [br, tl];
3524
+ else if (handle === 'right') draft.resizeCorners = [tl, { x: br.x, y: br.y }];
3525
+ else if (handle === 'left')
3526
+ draft.resizeCorners = [
3527
+ { x: br.x, y: tl.y },
3528
+ { x: tl.x, y: br.y },
3529
+ ];
3530
+ else if (handle === 'bottom') draft.resizeCorners = [tl, { x: br.x, y: br.y }];
3531
+ else if (handle === 'top')
3532
+ draft.resizeCorners = [
3533
+ { x: tl.x, y: br.y },
3534
+ { x: br.x, y: tl.y },
3535
+ ];
3536
+ const bounds = resizeBoundsFromDraft(draft.resizeCorners);
3537
+ if (bounds) {
3538
+ enqueue.emit.resizeStarted({
3539
+ id: event.id,
3540
+ handle: event.handle,
3541
+ bounds,
3542
+ });
3543
+ }
3544
+ }),
3545
+
3546
+ resizeMove: (ctx, event: Point) =>
3547
+ produce(ctx, (draft) => {
3548
+ if (!draft.resizeCorners || !draft.resizingEntityId) return;
3549
+ const handle = draft.resizeHandle;
3550
+ const node = draft.graph.nodes.find((n) => n.id === draft.resizingEntityId);
3551
+ if (!node) return;
3552
+ const anchor = draft.resizeCorners[0];
3553
+ let moving = draft.resizeCorners[1];
3554
+ // Move the dragged corner; anchor stays fixed
3555
+ // For edge handles (top/bottom/left/right), only move one axis
3556
+ if (handle === 'left' || handle === 'right') {
3557
+ moving = { ...moving, x: event.x };
3558
+ } else if (handle === 'top' || handle === 'bottom') {
3559
+ moving = { ...moving, y: event.y };
3560
+ } else {
3561
+ moving = { x: event.x, y: event.y };
3562
+ }
3563
+ draft.resizeCorners[1] = clampResizeMovingPoint(node, handle, anchor, moving);
3564
+ }),
3565
+
3566
+ resizeEnd: (ctx, _event: object, enqueue) =>
3567
+ produce(ctx, (draft) => {
3568
+ const resizedId = draft.resizingEntityId;
3569
+ if (draft.resizingEntityId && draft.resizeCorners) {
3570
+ const node = draft.graph.nodes.find((n) => n.id === draft.resizingEntityId);
3571
+ if (node) {
3572
+ const before = resolvedBounds(node);
3573
+ const [a, b] = draft.resizeCorners;
3574
+ const x = Math.min(a.x, b.x);
3575
+ const y = Math.min(a.y, b.y);
3576
+ const w = Math.abs(b.x - a.x);
3577
+ const h = Math.abs(b.y - a.y);
3578
+ // Commit: update position + custom size
3579
+ node.x = x;
3580
+ node.y = y;
3581
+ node.dx = 0;
3582
+ node.dy = 0;
3583
+ if (!node.style) node.style = {};
3584
+ // Honor the (possibly free) resize clamp; keep a 1px degeneracy
3585
+ // guard so a node never commits to a zero-area, unhittable box.
3586
+ node.style.customWidth = Math.max(1, w);
3587
+ node.style.customHeight = Math.max(1, h);
3588
+ const after = resolvedBounds(node);
3589
+ if (
3590
+ before.x !== after.x ||
3591
+ before.y !== after.y ||
3592
+ before.width !== after.width ||
3593
+ before.height !== after.height
3594
+ ) {
3595
+ invalidatePathsForNodeGeometry(draft, new Set([node.id]));
3596
+ }
3597
+ }
3598
+ }
3599
+ draft.canvasState = 'idle';
3600
+ draft.resizingEntityId = null;
3601
+ draft.resizeHandle = null;
3602
+ draft.resizeCorners = null;
3603
+ enqueue.emit.graphChanged({
3604
+ graph: snapshotGraph(draft.graph),
3605
+ event: createEventObject('resizeEnd', _event),
3606
+ });
3607
+ if (resizedId) {
3608
+ const node = draft.graph.nodes.find((n) => n.id === resizedId);
3609
+ if (node) {
3610
+ enqueue.emit.resizeEnded({
3611
+ id: resizedId,
3612
+ bounds: {
3613
+ x: node.x,
3614
+ y: node.y,
3615
+ width: resolvedSize(node).width,
3616
+ height: resolvedSize(node).height,
3617
+ },
3618
+ });
3619
+ }
3620
+ }
3621
+ }),
3622
+
3623
+ resizeCancel: (ctx) =>
3624
+ produce(ctx, (draft) => {
3625
+ draft.canvasState = 'idle';
3626
+ draft.resizingEntityId = null;
3627
+ draft.resizeHandle = null;
3628
+ draft.resizeCorners = null;
3629
+ }),
3630
+
3631
+ paneClicked: (ctx, event: FlowPaneGestureEvent, enqueue) => {
3632
+ enqueue.emit.paneClicked(event);
3633
+ return ctx;
3634
+ },
3635
+
3636
+ paneContextMenu: (ctx, event: FlowPaneGestureEvent, enqueue) => {
3637
+ enqueue.emit.paneContextMenu(event);
3638
+ return ctx;
3639
+ },
3640
+
3641
+ entityClicked: (ctx, event: FlowEntityGestureEvent, enqueue) => {
3642
+ enqueue.emit.entityClicked(event);
3643
+ return ctx;
3644
+ },
3645
+
3646
+ entityDoubleClicked: (ctx, event: FlowEntityGestureEvent, enqueue) => {
3647
+ enqueue.emit.entityDoubleClicked(event);
3648
+ return ctx;
3649
+ },
3650
+
3651
+ entityContextMenu: (ctx, event: FlowEntityGestureEvent, enqueue) => {
3652
+ enqueue.emit.entityContextMenu(event);
3653
+ return ctx;
3654
+ },
3655
+
3656
+ // Reconnect edge
3657
+
3658
+ reconnectEdge: (
3659
+ ctx,
3660
+ event: {
3661
+ edgeId: string;
3662
+ newSourceId?: string;
3663
+ newTargetId?: string;
3664
+ newSourcePort?: string | null;
3665
+ newTargetPort?: string | null;
3666
+ } & TransactionMetadata,
3667
+ enqueue
3668
+ ) =>
3669
+ produce(ctx, (draft) => {
3670
+ const edge = draft.graph.edges.find((e) => e.id === event.edgeId);
3671
+ if (!edge) return;
3672
+ const resultingSourceId = event.newSourceId ?? edge.sourceId;
3673
+ const resultingTargetId = event.newTargetId ?? edge.targetId;
3674
+ const missing: string[] = [];
3675
+ if (!draft.graph.nodes.some((n) => n.id === resultingSourceId))
3676
+ missing.push(`source node "${resultingSourceId}"`);
3677
+ if (!draft.graph.nodes.some((n) => n.id === resultingTargetId))
3678
+ missing.push(`target node "${resultingTargetId}"`);
3679
+ if (missing.length > 0) {
3680
+ enqueue.emit.error({
3681
+ error: new Error(
3682
+ `reconnectEdge rejected: edge "${event.edgeId}" references ${missing.join(
3683
+ ' and '
3684
+ )}, which ${missing.length === 1 ? 'does' : 'do'} not exist in the graph.`
3685
+ ),
3686
+ event: createEventObject('reconnectEdge', event),
3687
+ });
3688
+ return;
3689
+ }
3690
+ const nextSourceId = event.newSourceId ?? edge.sourceId;
3691
+ const nextTargetId = event.newTargetId ?? edge.targetId;
3692
+ const nextSourcePort =
3693
+ event.newSourcePort === undefined
3694
+ ? edge.sourcePort ?? undefined
3695
+ : event.newSourcePort ?? undefined;
3696
+ const nextTargetPort =
3697
+ event.newTargetPort === undefined
3698
+ ? edge.targetPort ?? undefined
3699
+ : event.newTargetPort ?? undefined;
3700
+ const endpointChanged =
3701
+ nextSourceId !== edge.sourceId ||
3702
+ nextTargetId !== edge.targetId ||
3703
+ nextSourcePort !== (edge.sourcePort ?? undefined) ||
3704
+ nextTargetPort !== (edge.targetPort ?? undefined);
3705
+ if (event.newSourceId !== undefined) edge.sourceId = event.newSourceId;
3706
+ if (event.newTargetId !== undefined) edge.targetId = event.newTargetId;
3707
+ if (event.newSourcePort !== undefined) edge.sourcePort = event.newSourcePort ?? undefined;
3708
+ if (event.newTargetPort !== undefined) edge.targetPort = event.newTargetPort ?? undefined;
3709
+ if (endpointChanged) {
3710
+ invalidateAuthoritativeEdgePath(edge);
3711
+ }
3712
+ enqueue.emit.graphChanged({
3713
+ graph: snapshotGraph(draft.graph),
3714
+ event: createEventObject('reconnectEdge', event),
3715
+ });
3716
+ }),
3717
+
3718
+ // Mode and grid snapping
3719
+
3720
+ setMode: (ctx, event: { mode: string }, enqueue) =>
3721
+ dispatchProfile(
3722
+ profile,
3723
+ ctx,
3724
+ createEventObject('setMode', event) as {
3725
+ type: 'setMode';
3726
+ mode: string;
3727
+ },
3728
+ enqueue,
3729
+ setModeTransition(profile)
3730
+ ),
3731
+
3732
+ setSnapToGrid: (ctx, event: { enabled: boolean; grid?: [number, number] }) =>
3733
+ produce(ctx, (draft) => {
3734
+ draft.snapToGrid = event.enabled;
3735
+ if (event.grid) draft.snapGrid = event.grid;
3736
+ }),
3737
+
3738
+ setSnapLines: (ctx, event: { enabled: boolean; threshold?: number; spacing?: boolean }) =>
3739
+ produce(ctx, (draft) => {
3740
+ draft.enableSnapLines = event.enabled;
3741
+ if (event.threshold !== undefined) draft.snapThreshold = event.threshold;
3742
+ if (event.spacing !== undefined) draft.enableSpacingGuides = event.spacing;
3743
+ }),
3744
+
3745
+ setColorMode: (ctx, event: { colorMode: FlowColorMode }) =>
3746
+ produce(ctx, (draft) => {
3747
+ draft.colorMode = event.colorMode;
3748
+ }),
3749
+
3750
+ // Arrow key movement
3751
+
3752
+ moveNodes: (ctx, event: { direction: Point; factor?: number }) => {
3753
+ const f = event.factor ?? 1;
3754
+ let dx = event.direction.x * f;
3755
+ let dy = event.direction.y * f;
3756
+
3757
+ if (ctx.snapToGrid) {
3758
+ dx = dx !== 0 ? Math.sign(dx) * ctx.snapGrid[0] : 0;
3759
+ dy = dy !== 0 ? Math.sign(dy) * ctx.snapGrid[1] : 0;
3760
+ }
3761
+ if (dx === 0 && dy === 0) return ctx;
3762
+
3763
+ const plan = planNodeMovement(ctx, dx, dy, { includeLabels: true });
3764
+ if (!plan) return ctx;
3765
+
3766
+ return produce(ctx, (draft) => {
3767
+ applyMovementPlan(draft, plan);
3768
+ });
3769
+ },
3770
+
3771
+ // Layout
3772
+
3773
+ requestLayout: (ctx, event: { algorithm?: string }, enqueue) =>
3774
+ produce(ctx, (draft) => {
3775
+ if (draft.canvasState === 'dragging') return;
3776
+
3777
+ const algorithm = event.algorithm ?? draft.autoLayout.algorithm;
3778
+ if (!algorithm) {
3779
+ return;
3780
+ }
3781
+
3782
+ draft.autoLayout = {
3783
+ status: 'pending',
3784
+ algorithm,
3785
+ };
3786
+
3787
+ enqueue.emit.layoutRequested({
3788
+ algorithm,
3789
+ graph: ctx.graph,
3790
+ });
3791
+ }),
3792
+
3793
+ applyLayoutResult: (
3794
+ ctx,
3795
+ event: {
3796
+ positions: Map<string, { x: number; y: number }>;
3797
+ edgeLabelPositions?: Map<string, { x: number; y: number }>;
3798
+ } & TransactionMetadata,
3799
+ enqueue
3800
+ ) =>
3801
+ produce(ctx, (draft) => {
3802
+ const changedNodeIds = new Set<string>();
3803
+ for (const [id, pos] of event.positions) {
3804
+ const node = draft.graph.nodes.find((n) => n.id === id);
3805
+ if (node) {
3806
+ const before = resolvedBounds(node);
3807
+ node.x = pos.x;
3808
+ node.y = pos.y;
3809
+ node.dx = 0;
3810
+ node.dy = 0;
3811
+ const after = resolvedBounds(node);
3812
+ if (
3813
+ before.x !== after.x ||
3814
+ before.y !== after.y ||
3815
+ before.width !== after.width ||
3816
+ before.height !== after.height
3817
+ ) {
3818
+ changedNodeIds.add(id);
3819
+ }
3820
+ }
3821
+ }
3822
+ invalidatePathsForNodeGeometry(draft, changedNodeIds);
3823
+ if (event.edgeLabelPositions) {
3824
+ for (const [id, pos] of event.edgeLabelPositions) {
3825
+ const edge = draft.graph.edges.find((e) => e.id === id);
3826
+ if (edge?.label) {
3827
+ edge.label.x = pos.x;
3828
+ edge.label.y = pos.y;
3829
+ edge.label.dx = 0;
3830
+ edge.label.dy = 0;
3831
+ }
3832
+ }
3833
+ }
3834
+ for (const edge of draft.graph.edges) {
3835
+ if ((edge.dx ?? 0) === 0 && (edge.dy ?? 0) === 0) continue;
3836
+ delete edge.dx;
3837
+ delete edge.dy;
3838
+ }
3839
+ draft.autoLayout.status = 'idle';
3840
+ enqueue.emit.graphChanged({
3841
+ graph: snapshotGraph(draft.graph),
3842
+ event: createEventObject('applyLayoutResult', event),
3843
+ });
3844
+ }),
3845
+
3846
+ // Measurement (renderer → engine)
3847
+
3848
+ updateMeasurements: (
3849
+ ctx,
3850
+ event: {
3851
+ measurements: Array<{ id: string; rect: Rect; origin?: Point }>;
3852
+ derivedOnly?: boolean;
3853
+ }
3854
+ ) => {
3855
+ // Resolve a measurement batch once on plain arrays. Repeated draft
3856
+ // `.find()` calls made node batches O(batch × nodes); port/unknown ids
3857
+ // also scanned every edge and port. Preserve first-match precedence:
3858
+ // node, then edge, then port.
3859
+ const nodeIndices = new Map<string, number>();
3860
+ for (let index = 0; index < ctx.graph.nodes.length; index++) {
3861
+ const id = ctx.graph.nodes[index].id;
3862
+ if (!nodeIndices.has(id)) nodeIndices.set(id, index);
3863
+ }
3864
+ const needsSecondaryIndices = event.measurements.some(
3865
+ (measurement) => !nodeIndices.has(measurement.id)
3866
+ );
3867
+ const edgeIndices = new Map<string, number>();
3868
+ const portIndices = new Map<
3869
+ string,
3870
+ { nodeIndex: number; portIndex: number }
3871
+ >();
3872
+ if (needsSecondaryIndices) {
3873
+ for (let index = 0; index < ctx.graph.edges.length; index++) {
3874
+ const id = ctx.graph.edges[index].id;
3875
+ if (!edgeIndices.has(id)) edgeIndices.set(id, index);
3876
+ }
3877
+ for (let nodeIndex = 0; nodeIndex < ctx.graph.nodes.length; nodeIndex++) {
3878
+ const node = ctx.graph.nodes[nodeIndex];
3879
+ for (let portIndex = 0; portIndex < (node.ports?.length ?? 0); portIndex++) {
3880
+ const port = node.ports![portIndex];
3881
+ const target = { nodeIndex, portIndex };
3882
+ const address = `${node.id}:${port.name}`;
3883
+ if (!portIndices.has(address)) portIndices.set(address, target);
3884
+ const explicitId = (port as { id?: string }).id;
3885
+ if (explicitId && !portIndices.has(explicitId)) {
3886
+ portIndices.set(explicitId, target);
3887
+ }
3888
+ }
3889
+ }
3890
+ }
3891
+
3892
+ return produce(ctx, (draft) => {
3893
+ const boundaryNodes = new Set<string>();
3894
+ const candidateNodes = new Set<string>();
3895
+ for (const measurement of event.measurements) {
3896
+ const nodeIndex = nodeIndices.get(measurement.id);
3897
+ if (nodeIndex !== undefined) {
3898
+ const node = draft.graph.nodes[nodeIndex];
3899
+ candidateNodes.add(node.id);
3900
+ // Only nodes whose size the DOM owns (autoSize) record a measured
3901
+ // size. It lands on `measured` — never on the authored
3902
+ // `width`/`height` — so the model is never clobbered (writing
3903
+ // measured back onto the authored box fed a render → measure →
3904
+ // render growth loop). `resolvedSize` derives geometry from it.
3905
+ if (resolveAppearance(node, draft.appearances).autoSize) {
3906
+ const previousSize = resolvedSize(node);
3907
+ const previousOffset = node.measured?.anchorOffset ?? {
3908
+ x: 0,
3909
+ y: 0,
3910
+ };
3911
+ const anchor = resolveAutoSizeAnchor(node.autoSizeAnchor);
3912
+ const nextSize = {
3913
+ width: node.style?.customWidth ?? measurement.rect.width,
3914
+ height: node.style?.customHeight ?? measurement.rect.height,
3915
+ };
3916
+ const delta = {
3917
+ x: (previousSize.width - nextSize.width) * anchor.x,
3918
+ y: (previousSize.height - nextSize.height) * anchor.y,
3919
+ };
3920
+ const anchorOffset = {
3921
+ x: previousOffset.x + delta.x,
3922
+ y: previousOffset.y + delta.y,
3923
+ };
3924
+ // A ResizeObserver reports the pre-transition DOM position.
3925
+ // Store the position Flow will render after applying the
3926
+ // anchor correction, so geometry is immediately coherent and
3927
+ // a position-only follow-up measurement is unnecessary.
3928
+ const normalizedRect = {
3929
+ x: anchor.x === 0 ? measurement.rect.x : node.x + delta.x + (node.dx ?? 0),
3930
+ y: anchor.y === 0 ? measurement.rect.y : node.y + delta.y + (node.dy ?? 0),
3931
+ width: measurement.rect.width,
3932
+ height: measurement.rect.height,
3933
+ };
3934
+ const existing = draft.measurements.get(measurement.id);
3935
+ if (
3936
+ delta.x === 0 &&
3937
+ delta.y === 0 &&
3938
+ node.measured?.appearanceKey === JSON.stringify(node.appearance ?? null) &&
3939
+ node.measured?.width === measurement.rect.width &&
3940
+ node.measured?.height === measurement.rect.height &&
3941
+ previousOffset.x === anchorOffset.x &&
3942
+ previousOffset.y === anchorOffset.y &&
3943
+ existing?.x === normalizedRect.x &&
3944
+ existing.y === normalizedRect.y &&
3945
+ existing.width === normalizedRect.width &&
3946
+ existing.height === normalizedRect.height
3947
+ ) {
3948
+ continue;
3949
+ }
3950
+
3951
+ node.measured = {
3952
+ width: measurement.rect.width,
3953
+ height: measurement.rect.height,
3954
+ appearanceAutoSize: resolveAppearance(node, draft.appearances).autoSize,
3955
+ appearanceKey: JSON.stringify(node.appearance ?? null),
3956
+ ...(anchorOffset.x !== 0 || anchorOffset.y !== 0 ? { anchorOffset } : {}),
3957
+ };
3958
+ node.x += delta.x;
3959
+ node.y += delta.y;
3960
+ draft.measurements.set(measurement.id, normalizedRect);
3961
+ } else {
3962
+ draft.measurements.set(measurement.id, measurement.rect);
3963
+ }
3964
+ continue;
3965
+ }
3966
+
3967
+ draft.measurements.set(measurement.id, measurement.rect);
3968
+ if (measurement.id.startsWith('["flow-appearance-boundary",')) {
3969
+ const [, id] = JSON.parse(measurement.id) as [string, string];
3970
+ if (nodeIndices.has(id)) boundaryNodes.add(id);
3971
+ const labelIndex = edgeIndices.get(id);
3972
+ if (!event.derivedOnly && labelIndex !== undefined) invalidateAuthoritativeEdgePath(draft.graph.edges[labelIndex]);
3973
+ }
3974
+
3975
+ const edgeIndex = edgeIndices.get(measurement.id);
3976
+ const edge =
3977
+ edgeIndex === undefined ? undefined : draft.graph.edges[edgeIndex];
3978
+ if (edge?.label) {
3979
+ if (!event.derivedOnly && resolveAppearance(edge.label, draft.appearances).registered) invalidateAuthoritativeEdgePath(edge);
3980
+ // DOM-owned labels keep measured geometry transient. External
3981
+ // graph replacement can safely restore authored fallback sizes
3982
+ // without starting a measure/render oscillation.
3983
+ if (!event.derivedOnly && !resolveAppearance(edge.label, draft.appearances).autoSize && !resolveAppearance(edge.label, draft.appearances).registered && !edge.label.appearance) {
3984
+ edge.label.width = measurement.rect.width;
3985
+ edge.label.height = measurement.rect.height;
3986
+ }
3987
+ continue;
3988
+ }
3989
+
3990
+ const portTarget = portIndices.get(measurement.id);
3991
+ if (portTarget && event.derivedOnly) {
3992
+ const candidate = ctx.graph.nodes[portTarget.nodeIndex];
3993
+ const origin = measurement.origin ?? snappedBounds(candidate, ctx.snapToGrid ? ctx.snapGrid : null);
3994
+ draft.derivedPortMeasurements.set(measurement.id, {
3995
+ ...measurement.rect,
3996
+ x: measurement.rect.x - origin.x,
3997
+ y: measurement.rect.y - origin.y,
3998
+ });
3999
+ } else if (portTarget) {
4000
+ draft.derivedPortMeasurements.delete(measurement.id);
4001
+ const candidate = draft.graph.nodes[portTarget.nodeIndex];
4002
+ candidateNodes.add(candidate.id);
4003
+ const port = candidate.ports?.[portTarget.portIndex];
4004
+ if (!port) continue;
4005
+ // The DOM bridge captures the rendered origin, including group
4006
+ // geometry and animation. Raw measurements without an origin
4007
+ // retain the authored, grid-snapped coordinate contract.
4008
+ const origin = measurement.origin ?? snappedBounds(
4009
+ candidate,
4010
+ draft.snapToGrid ? draft.snapGrid : null,
4011
+ );
4012
+ port.x = measurement.rect.x - origin.x;
4013
+ port.y = measurement.rect.y - origin.y;
4014
+ port.width = measurement.rect.width;
4015
+ port.height = measurement.rect.height;
4016
+ }
4017
+ }
4018
+ for (const id of candidateNodes) {
4019
+ const index = nodeIndices.get(id)!;
4020
+ if (nodeEndpointGeometryChanged(ctx.graph.nodes[index], draft.graph.nodes[index])) boundaryNodes.add(id);
4021
+ }
4022
+ if (!event.derivedOnly && boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4023
+ });
4024
+ },
4025
+
4026
+ removeMeasurements: (ctx, event: { ids: string[]; derivedOnly?: boolean }) =>
4027
+ produce(ctx, (draft) => {
4028
+ const boundaryNodes = new Set<string>();
4029
+ for (const id of event.ids) {
4030
+ const removed = draft.measurements.delete(id);
4031
+ draft.derivedPortMeasurements.delete(id);
4032
+ const node = draft.graph.nodes.find((candidate) => candidate.id === id);
4033
+ if (node?.measured) {
4034
+ node.x -= node.measured.anchorOffset?.x ?? 0;
4035
+ node.y -= node.measured.anchorOffset?.y ?? 0;
4036
+ delete node.measured;
4037
+ boundaryNodes.add(id);
4038
+ }
4039
+ if (!removed) continue;
4040
+ if (id.startsWith('["flow-appearance-boundary",')) {
4041
+ const [, entityId] = JSON.parse(id) as [string, string];
4042
+ boundaryNodes.add(entityId);
4043
+ const edge = draft.graph.edges.find((candidate) => candidate.id === entityId);
4044
+ if (!event.derivedOnly && edge) invalidateAuthoritativeEdgePath(edge);
4045
+ }
4046
+ }
4047
+ if (!event.derivedOnly && boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4048
+ }),
4049
+
4050
+ // Edge labels
4051
+
4052
+ bakeLabelPositions: (
4053
+ ctx,
4054
+ event: { positions: Map<string, Point> } & TransactionMetadata,
4055
+ enqueue
4056
+ ) =>
4057
+ produce(ctx, (draft) => {
4058
+ for (const [edgeId, center] of event.positions) {
4059
+ const edge = draft.graph.edges.find((e) => e.id === edgeId);
4060
+ if (edge?.label) {
4061
+ const size = resolvedEdgeLabelSize(
4062
+ edge.label,
4063
+ (draft.measurements as Map<string, Rect>).get(edge.id)
4064
+ );
4065
+ edge.label.x = center.x - size.width / 2;
4066
+ edge.label.y = center.y - size.height / 2;
4067
+ edge.label.dx = 0;
4068
+ edge.label.dy = 0;
4069
+ }
4070
+ }
4071
+ enqueue.emit.graphChanged({
4072
+ graph: snapshotGraph(draft.graph),
4073
+ event: createEventObject('bakeLabelPositions', event),
4074
+ });
4075
+ }),
4076
+
4077
+ reportError: (ctx, event: FlowErrorEvent, enqueue) => {
4078
+ enqueue.emit.error(event);
4079
+ return ctx;
4080
+ },
4081
+ },
4082
+ }).with(
4083
+ undoRedo({
4084
+ strategy: 'snapshot',
4085
+ historyLimit: options.historyLimit ?? 100,
4086
+ getTransactionId: (event) => (event as UndoableStoreEvent).transactionId,
4087
+ skipEvent: (event, snapshot) =>
4088
+ !shouldTrackUndoEvent(event, snapshot as UndoableStoreSnapshot),
4089
+ restore: ({ current, next, direction }, enqueue) => {
4090
+ const restored = restoreHistoryContext(current, next);
4091
+ enqueue.emit.graphChanged({
4092
+ graph: restored.graph,
4093
+ event: createEventObject(direction, undefined),
4094
+ });
4095
+ if (
4096
+ current.selection.size !== restored.selection.size ||
4097
+ [...current.selection].some((id) => !restored.selection.has(id))
4098
+ ) {
4099
+ enqueue.emit.selectionChanged({
4100
+ selection: new Set(restored.selection),
4101
+ event: createEventObject(direction, undefined),
4102
+ });
4103
+ }
4104
+ return restored;
4105
+ },
4106
+ })
4107
+ );
4108
+
4109
+ return storeWithHistory.with(resetGraphReplacementHistory);
4110
+ }
4111
+
4112
+ export type FlowStore = ReturnType<typeof createFlowStore>;
4113
+
4114
+ export function areNodesMeasured(context: FlowStoreContext): boolean {
4115
+ return context.graph.nodes.every((node) => {
4116
+ if (node.hidden || !resolveAppearance(node, context.appearances).autoSize) return true;
4117
+ return context.measurements.has(node.id) || node.measured !== undefined;
4118
+ });
4119
+ }
4120
+
4121
+ // Container attachment (auto-sync viewportSize via ResizeObserver)