@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,1715 @@
1
+ import type {
2
+ FlowInputMode,
3
+ FlowInputModeContext,
4
+ FlowPinchInputEvent,
5
+ FlowInputSessionHandlers,
6
+ FlowInputTarget,
7
+ FlowPointerInputEvent,
8
+ FlowCommand,
9
+ } from './index';
10
+ import { trigger } from './index';
11
+ import {
12
+ matchesKeyBinding,
13
+ matchesMultiSelect,
14
+ resolveKeymap,
15
+ type FlowKeymap,
16
+ } from './keymap';
17
+ import type { ConnectEndTarget } from '../store';
18
+ import { normalizeConnection } from '../engine';
19
+ import type { FlowEdge, FlowNode, Point, Rect } from '../types';
20
+ import { rectsIntersect } from '../spatial';
21
+ import { indexChildren, indexNodes } from '../graph-index';
22
+
23
+ // Local literal rather than importing the `preventDefault` const from
24
+ // ./index: modes.ts evaluates first in the circular import between the two
25
+ // files, so consts from ./index would still be in their temporal dead zone.
26
+ const preventDefault = { type: 'preventDefault' } as const;
27
+ import {
28
+ isTrackpadPinch,
29
+ normalizeWheelPan,
30
+ wheelZoomDelta,
31
+ } from '../spatial';
32
+
33
+ // Built-in input modes
34
+ //
35
+ // These replicate (and centralize) the gesture semantics that previously
36
+ // lived as ad hoc handlers in the React adapter. Priorities: keyboard 100,
37
+ // wheel 90, space/middle pan 80, entity press/drag 50, pane press/pan 10.
38
+
39
+
40
+ function distance(a: Point, b: Point): number {
41
+ return Math.hypot(b.x - a.x, b.y - a.y);
42
+ }
43
+
44
+ function isMulti(event: FlowPointerInputEvent): boolean {
45
+ return event.modifiers.shift || event.modifiers.meta || event.modifiers.ctrl;
46
+ }
47
+
48
+
49
+ // Keyboard: escape, undo/redo, delete, space (tracked by the runtime)
50
+
51
+
52
+ export function keyboardMode(
53
+ options: {
54
+ /** @deprecated Use `keymap.delete = null`. */
55
+ allowDelete?: boolean;
56
+ /** @deprecated Use `keymap.undo = null` and `keymap.redo = null`. */
57
+ allowUndo?: boolean;
58
+ keymap?: Partial<FlowKeymap>;
59
+ escapeSelection?: 'all' | 'focused' | 'none';
60
+ } = {},
61
+ ): FlowInputMode {
62
+ const keymap = resolveKeymap({
63
+ ...options.keymap,
64
+ ...(options.allowDelete === false ? { delete: null } : {}),
65
+ ...(options.allowUndo === false ? { undo: null, redo: null } : {}),
66
+ });
67
+ return {
68
+ id: 'keyboard',
69
+ priority: 100,
70
+ start(event, { context }) {
71
+ if (event.kind !== 'key.down') return null;
72
+ if (event.editableTarget) return null;
73
+
74
+ if (
75
+ matchesKeyBinding(event, keymap.panActivation) &&
76
+ !context.focusedEntityId
77
+ ) {
78
+ // panKeyHeld is tracked by the runtime; just stop the page scrolling.
79
+ return { commands: [preventDefault] };
80
+ }
81
+ if (matchesKeyBinding(event, keymap.cancel)) {
82
+ const commands: FlowCommand[] = [trigger('cancelConnection'), trigger('resizeCancel')];
83
+ if (context.canvasState === 'idle' && !context.connection && !context.connectionClickStartHandle) {
84
+ switch (options.escapeSelection ?? 'all') {
85
+ case 'all':
86
+ commands.push(trigger('clearSelection'), trigger('clearFocus'));
87
+ break;
88
+ case 'focused':
89
+ if (context.focusedEntityId && context.selection.has(context.focusedEntityId)) {
90
+ commands.push(trigger('select', {
91
+ ids: [...context.selection].filter((id) => id !== context.focusedEntityId),
92
+ mode: 'single',
93
+ }));
94
+ }
95
+ commands.push(trigger('clearFocus'));
96
+ break;
97
+ case 'none':
98
+ break;
99
+ }
100
+ }
101
+ return { commands };
102
+ }
103
+ if (matchesKeyBinding(event, keymap.redo)) {
104
+ return {
105
+ commands: [preventDefault, trigger('redo')],
106
+ };
107
+ }
108
+ if (matchesKeyBinding(event, keymap.undo)) {
109
+ return {
110
+ commands: [preventDefault, trigger('undo')],
111
+ };
112
+ }
113
+ if (matchesKeyBinding(event, keymap.selectAll)) {
114
+ return { commands: [preventDefault, trigger('selectAll')] };
115
+ }
116
+ if (matchesKeyBinding(event, keymap.delete)) {
117
+ if (context.selection.size === 0) return null;
118
+ return { commands: [preventDefault, trigger('deleteSelected')] };
119
+ }
120
+ return null;
121
+ },
122
+ };
123
+ }
124
+
125
+
126
+ // Keyboard navigation: arrows nudge the selection (undoable), Enter selects
127
+ // the focused entity. Focus itself is driven by the renderer (DOM focus on
128
+ // node elements syncs to `trigger.focus`), so traversal order stays native.
129
+
130
+
131
+ const ARROW_DIRECTIONS: Record<string, Point> = {
132
+ ArrowLeft: { x: -1, y: 0 },
133
+ ArrowRight: { x: 1, y: 0 },
134
+ ArrowUp: { x: 0, y: -1 },
135
+ ArrowDown: { x: 0, y: 1 },
136
+ };
137
+
138
+ export function keyboardNavMode(
139
+ options: {
140
+ allowMove?: boolean;
141
+ step?: number;
142
+ shiftStep?: number;
143
+ keymap?: Partial<FlowKeymap>;
144
+ /** Literal KeyboardEvent.key names; null disables focused activation. */
145
+ activationKeys?: readonly string[] | null;
146
+ preventDefault?: boolean;
147
+ selectionBehavior?: 'replace' | 'preserve';
148
+ nudge?: 'selection' | 'focused-selection';
149
+ } = {},
150
+ ): FlowInputMode {
151
+ const allowMove = options.allowMove ?? true;
152
+ const step = options.step ?? 5;
153
+ const shiftStep = options.shiftStep ?? 20;
154
+ const keymap = resolveKeymap(options.keymap);
155
+ const activationKeys = options.activationKeys === undefined
156
+ ? ['Enter', ' ', 'Spacebar']
157
+ : options.activationKeys;
158
+ return {
159
+ id: 'keyboard-nav',
160
+ priority: 95,
161
+ start(event, { context, engine }) {
162
+ if (event.kind !== 'key.down' || event.editableTarget) return null;
163
+
164
+ if (activationKeys?.includes(event.key) && context.focusedEntityId) {
165
+ const multiSelect = matchesMultiSelect(event.modifiers, keymap);
166
+ const commands: FlowCommand[] = options.preventDefault === false ? [] : [preventDefault];
167
+ if (
168
+ multiSelect ||
169
+ options.selectionBehavior !== 'preserve' ||
170
+ !context.selection.has(context.focusedEntityId)
171
+ ) {
172
+ commands.push(trigger('select', {
173
+ ids: [context.focusedEntityId],
174
+ mode: multiSelect ? 'multi' : 'single',
175
+ }));
176
+ }
177
+ return { commands };
178
+ }
179
+
180
+ if (!allowMove) return null;
181
+ if (
182
+ options.nudge === 'focused-selection' &&
183
+ (!context.focusedEntityId ||
184
+ !context.selection.has(context.focusedEntityId) ||
185
+ !engine.getNode(context.focusedEntityId))
186
+ ) return null;
187
+ const direction =
188
+ matchesKeyBinding(event, keymap.nudgeLeft) ? ARROW_DIRECTIONS.ArrowLeft :
189
+ matchesKeyBinding(event, keymap.nudgeRight) ? ARROW_DIRECTIONS.ArrowRight :
190
+ matchesKeyBinding(event, keymap.nudgeUp) ? ARROW_DIRECTIONS.ArrowUp :
191
+ matchesKeyBinding(event, keymap.nudgeDown) ? ARROW_DIRECTIONS.ArrowDown :
192
+ undefined;
193
+ if (!direction || context.selection.size === 0) return null;
194
+ // moveNodes is undoable; commitDrag bakes the offset so each press is
195
+ // one complete, undoable step. snapToGrid moves by grid increments.
196
+ return {
197
+ commands: [
198
+ preventDefault,
199
+ trigger('moveNodes', {
200
+ direction,
201
+ factor:
202
+ keymap.nudgeLargeModifier && event.modifiers[keymap.nudgeLargeModifier]
203
+ ? shiftStep
204
+ : step,
205
+ }),
206
+ trigger('commitDrag'),
207
+ ],
208
+ };
209
+ },
210
+ };
211
+ }
212
+
213
+ export function doubleClickZoomMode(
214
+ options: { enabled?: boolean; factor?: number } = {},
215
+ ): FlowInputMode {
216
+ const enabled = options.enabled ?? true;
217
+ const factor = options.factor ?? 2;
218
+ return {
219
+ id: 'double-click-zoom',
220
+ priority: 70,
221
+ start(event) {
222
+ if (!enabled) return null;
223
+ if (event.kind !== 'pointer.down') return null;
224
+ if ((event.detail ?? 0) < 2) return null;
225
+ if (event.button !== 0) return null;
226
+ // Pane-only, matching react-flow's default: a node double-click must not
227
+ // zoom the canvas. Entity double-clicks are emitted by entityPressMode.
228
+ if (event.target.kind !== 'pane') return null;
229
+ const zoomFactor = event.modifiers.shift ? 1 / factor : factor;
230
+ return {
231
+ commands: [
232
+ preventDefault,
233
+ trigger('zoomBy', { factor: zoomFactor, center: event.screenPoint }),
234
+ ],
235
+ };
236
+ },
237
+ };
238
+ }
239
+
240
+
241
+ // Wheel: trackpad pinch zooms; everything else pans
242
+
243
+
244
+ export function wheelMode(): FlowInputMode {
245
+ return {
246
+ id: 'wheel',
247
+ priority: 90,
248
+ start(event, { context }) {
249
+ if (event.kind !== 'wheel') return null;
250
+
251
+ if (
252
+ isTrackpadPinch({
253
+ ctrlKey: event.modifiers.ctrl,
254
+ metaKey: event.modifiers.meta,
255
+ })
256
+ ) {
257
+ const zoom =
258
+ context.viewport.zoom *
259
+ Math.pow(
260
+ 2,
261
+ wheelZoomDelta({
262
+ deltaY: event.deltaY,
263
+ deltaMode: event.deltaMode,
264
+ ctrlKey: event.modifiers.ctrl,
265
+ }),
266
+ );
267
+ return {
268
+ commands: [
269
+ preventDefault,
270
+ trigger('zoomTo', { zoom, center: event.screenPoint }),
271
+ ],
272
+ };
273
+ }
274
+
275
+ return {
276
+ commands: [
277
+ preventDefault,
278
+ trigger(
279
+ 'panBy',
280
+ normalizeWheelPan({
281
+ deltaX: event.deltaX,
282
+ deltaY: event.deltaY,
283
+ deltaMode: event.deltaMode,
284
+ }),
285
+ ),
286
+ ],
287
+ };
288
+ },
289
+ };
290
+ }
291
+
292
+
293
+ // Space-held / middle-button pan — works from any target
294
+
295
+
296
+ export function panMode(): FlowInputMode {
297
+ return {
298
+ id: 'pan',
299
+ priority: 80,
300
+ start(event, { input }) {
301
+ if (event.kind !== 'pointer.down') return null;
302
+ const middle = event.button === 1;
303
+ const space = input.panKeyHeld && event.button === 0;
304
+ if (!middle && !space) return null;
305
+
306
+ return {
307
+ commands: [trigger('panStart', event.screenPoint)],
308
+ session: panSession(),
309
+ };
310
+ },
311
+ };
312
+ }
313
+
314
+ function panSession(): FlowInputSessionHandlers {
315
+ return {
316
+ update(event) {
317
+ if (event.kind === 'pointer.move') {
318
+ return { commands: [trigger('pan', event.screenPoint)] };
319
+ }
320
+ if (event.kind === 'pointer.up' || event.kind === 'pointer.cancel') {
321
+ return { commands: [trigger('panEnd')], status: 'end' };
322
+ }
323
+ return {};
324
+ },
325
+ cancel() {
326
+ return [trigger('panCancel')];
327
+ },
328
+ };
329
+ }
330
+
331
+
332
+ // Touch pinch: two fingers pan and zoom together.
333
+
334
+
335
+ export function pinchMode(): FlowInputMode {
336
+ return {
337
+ id: 'pinch',
338
+ priority: 85,
339
+ start(event, { context }) {
340
+ if (event.kind !== 'pinch.start') return null;
341
+ return {
342
+ commands: [preventDefault],
343
+ session: pinchSession(event, context.viewport),
344
+ };
345
+ },
346
+ };
347
+ }
348
+
349
+ function pinchSession(
350
+ down: FlowPinchInputEvent,
351
+ viewport: FlowInputModeContext['context']['viewport'],
352
+ ): FlowInputSessionHandlers {
353
+ let initialDistance = down.distance > 0 ? down.distance : null;
354
+ const anchor = {
355
+ x: (down.screenCenter.x - viewport.x) / viewport.zoom,
356
+ y: (down.screenCenter.y - viewport.y) / viewport.zoom,
357
+ };
358
+
359
+ return {
360
+ update(event, { context }) {
361
+ if (event.kind === 'pinch.move') {
362
+ if (initialDistance === null && event.distance > 0) {
363
+ initialDistance = event.distance;
364
+ }
365
+ const zoom = initialDistance !== null
366
+ ? Math.max(context.minZoom, Math.min(context.maxZoom, viewport.zoom * event.distance / initialDistance))
367
+ : context.viewport.zoom;
368
+ const center = {
369
+ x: context.viewport.x + anchor.x * context.viewport.zoom,
370
+ y: context.viewport.y + anchor.y * context.viewport.zoom,
371
+ };
372
+ return {
373
+ commands: [
374
+ preventDefault,
375
+ trigger('zoomTo', { zoom, center }),
376
+ trigger('panBy', {
377
+ x: event.screenCenter.x - center.x,
378
+ y: event.screenCenter.y - center.y,
379
+ }),
380
+ ],
381
+ };
382
+ }
383
+ if (event.kind === 'pinch.end') {
384
+ return { commands: [preventDefault], status: 'end' };
385
+ }
386
+ return {};
387
+ },
388
+ cancel() {
389
+ return [];
390
+ },
391
+ };
392
+ }
393
+
394
+ // Entity press: select on pointer down, drag past the threshold
395
+ // (nodes drag themselves; edges drag their label when pressed on it)
396
+
397
+
398
+ export type ReparentDropContext = {
399
+ /** Top-level dragged nodes (descendants of dragged nodes excluded). */
400
+ nodes: FlowNode[];
401
+ /** Combined visual bounds of the dragged nodes. */
402
+ bounds: Rect;
403
+ /** Best drop candidate (evaluated as if the dragged nodes were absent). */
404
+ candidate: { id: string; overlap: number } | null;
405
+ /** Continuous time the current candidate has been hovered, in ms. */
406
+ hoverMs: number;
407
+ modifiers: { shift: boolean; meta: boolean; ctrl: boolean; alt: boolean };
408
+ };
409
+
410
+ export type ReparentDecision = string | null | undefined;
411
+
412
+ export type ReparentOptions = {
413
+ /** Minimum overlap ratio (dragged bounds ∩ child area / dragged area). Default 0.5. */
414
+ minOverlap?: number;
415
+ /** Required continuous hover time over a candidate before it counts. Default 0. */
416
+ delayMs?: number;
417
+ /**
418
+ * Geometric unparenting: when no candidate exists AND the current parent's
419
+ * rendered child area no longer touches the dragged bounds, clear the
420
+ * parent. Only ever fires for `fixed` groups — `derived` groups stretch to
421
+ * keep containing their children, so they can only be left via the
422
+ * modifier gesture or a custom `decide`. Default true.
423
+ */
424
+ unparent?: boolean;
425
+ /**
426
+ * Holding this modifier at drop forces unparenting (release it before
427
+ * dropping to cancel). Default 'alt'; null disables.
428
+ */
429
+ unparentModifier?: 'alt' | 'shift' | 'meta' | 'ctrl' | null;
430
+ /**
431
+ * Full custom policy. Return a node id to reparent into it, null to clear
432
+ * the parent, undefined to keep current parents. When provided, it
433
+ * replaces the built-in decision entirely.
434
+ */
435
+ decide?: (
436
+ drop: ReparentDropContext,
437
+ ctx: FlowInputModeContext,
438
+ ) => ReparentDecision;
439
+ };
440
+
441
+ const REPARENT_HIGHLIGHT_KIND = 'drop-target';
442
+
443
+ export function entityPressMode(
444
+ options: {
445
+ drag?:
446
+ | boolean
447
+ | ((
448
+ event: FlowPointerInputEvent,
449
+ context: FlowInputModeContext,
450
+ ) => boolean);
451
+ reparent?: boolean | ReparentOptions;
452
+ keymap?: Partial<FlowKeymap>;
453
+ } = {},
454
+ ): FlowInputMode {
455
+ const allowDrag = options.drag ?? true;
456
+ // Keymap-driven multi-select. Falls back to the legacy `isMulti`
457
+ // (shift||meta||ctrl) when no keymap is threaded, so default behavior is
458
+ // byte-identical to the pre-keymap call sites.
459
+ const multiSelect = options.keymap
460
+ ? (event: FlowPointerInputEvent) =>
461
+ matchesMultiSelect(event.modifiers, resolveKeymap(options.keymap))
462
+ : isMulti;
463
+ const reparent: ReparentOptions | null =
464
+ options.reparent === true
465
+ ? {}
466
+ : typeof options.reparent === 'object'
467
+ ? options.reparent
468
+ : null;
469
+ return {
470
+ id: 'entity-press',
471
+ priority: 50,
472
+ start(event, modeContext) {
473
+ const { context, engine } = modeContext;
474
+ if (event.kind !== 'pointer.down') return null;
475
+ if (event.target.kind !== 'entity') return null;
476
+ if (event.target.part?.startsWith('resize-handle:')) return null;
477
+
478
+ const id = event.target.id;
479
+ if (event.button === 2) {
480
+ return {
481
+ commands: [
482
+ trigger('entityContextMenu', {
483
+ id,
484
+ point: event.point,
485
+ modifiers: event.modifiers,
486
+ }),
487
+ ],
488
+ };
489
+ }
490
+ if (event.button !== 0) return null;
491
+ if (event.target.part === 'connection-boundary') return null;
492
+ const entity = engine.getEntity(id);
493
+ if (!entity) return null;
494
+ const config = engine.resolveEntityConfig(entity);
495
+
496
+ const commands: FlowCommand[] = [];
497
+ if (config.selectable) {
498
+ const selection = context.selection;
499
+ const isMultiSelect = multiSelect(event);
500
+ // A plain press inside an existing multi-selection keeps it intact so
501
+ // the whole selection can be dragged. An explicit multi-select press
502
+ // still toggles the pressed entity through the store's multi mode.
503
+ if (!(selection.size > 1 && selection.has(id) && !isMultiSelect)) {
504
+ commands.push(
505
+ trigger('select', {
506
+ ids: [id],
507
+ mode: isMultiSelect ? 'multi' : 'single',
508
+ }),
509
+ );
510
+ }
511
+ }
512
+
513
+ const draggablePart =
514
+ entity.type === 'node' || event.target.part === 'label';
515
+ const handleAllows =
516
+ !event.target.entityHasDragHandle ||
517
+ event.target.pressedDragHandle === true;
518
+ const dragAllowed =
519
+ typeof allowDrag === 'function'
520
+ ? allowDrag(event, modeContext)
521
+ : allowDrag;
522
+ if (!dragAllowed || !draggablePart || !handleAllows || !config.draggable) {
523
+ return {
524
+ commands,
525
+ session: entityClickSession(id, event),
526
+ };
527
+ }
528
+
529
+ return {
530
+ commands,
531
+ session: dragSession(id, event, entity.type === 'node' ? reparent : null),
532
+ };
533
+ },
534
+ };
535
+ }
536
+
537
+ function entityClickSession(
538
+ id: string,
539
+ down: FlowPointerInputEvent,
540
+ ): FlowInputSessionHandlers {
541
+ return {
542
+ update(event) {
543
+ if (event.kind === 'pointer.up') {
544
+ return {
545
+ commands: [
546
+ trigger(down.detail === 2 ? 'entityDoubleClicked' : 'entityClicked', {
547
+ id,
548
+ point: down.point,
549
+ modifiers: down.modifiers,
550
+ }),
551
+ ],
552
+ status: 'end',
553
+ };
554
+ }
555
+ if (event.kind === 'pointer.cancel') return { status: 'end' };
556
+ return {};
557
+ },
558
+ };
559
+ }
560
+
561
+ function dragSession(
562
+ id: string,
563
+ down: FlowPointerInputEvent,
564
+ reparent: ReparentOptions | null,
565
+ ): FlowInputSessionHandlers {
566
+ const transactionId = `drag:${id}:${down.pointerId}:${Date.now()}`;
567
+ let dragging = false;
568
+ let baseOffset: Point = { x: 0, y: 0 };
569
+ let candidateId: string | null = null;
570
+ let candidateOverlap = 0;
571
+ let candidateSince = 0;
572
+
573
+ const minOverlap = reparent?.minOverlap ?? 0.5;
574
+ const unparentModifier =
575
+ reparent?.unparentModifier === undefined ? 'alt' : reparent.unparentModifier;
576
+
577
+ /**
578
+ * Currently applied drag offset of the primary entity. The session anchors
579
+ * requests to the virtual pointer (`base + pointerTravel`) and asks the
580
+ * store for the difference — so store-side clamping (extents, fixed-group
581
+ * child areas) is idempotent against pointer position: overshoot stays
582
+ * virtual and the entity doesn't move again until the pointer returns.
583
+ */
584
+ function appliedOffset(ctx: FlowInputModeContext): Point {
585
+ const node = ctx.engine.getNode(id);
586
+ if (node) return { x: node.dx ?? 0, y: node.dy ?? 0 };
587
+ const edge = ctx.engine.getEdge(id);
588
+ if (edge?.label) {
589
+ return { x: edge.label.dx ?? 0, y: edge.label.dy ?? 0 };
590
+ }
591
+ return { x: 0, y: 0 };
592
+ }
593
+
594
+ /** Top-level moving nodes + the full excluded (moving) subtree. */
595
+ function movingInfo(ctx: FlowInputModeContext): {
596
+ topLevel: FlowNode[];
597
+ exclude: Set<string>;
598
+ bounds: Rect | null;
599
+ } {
600
+ const { context, engine } = ctx;
601
+ const nodes = context.graph.nodes as FlowNode[];
602
+ const nodeIndex = indexNodes(nodes);
603
+ const childrenIndex = indexChildren(nodes);
604
+ const movingIds = new Set<string>();
605
+ for (const selectedId of context.selection) {
606
+ const node = nodeIndex.get(selectedId);
607
+ if (node && node.draggable !== false) movingIds.add(selectedId);
608
+ }
609
+ const topLevel: FlowNode[] = [];
610
+ for (const movingId of movingIds) {
611
+ let ancestor = nodeIndex.get(movingId)?.parentId ?? null;
612
+ let nested = false;
613
+ const seen = new Set<string>();
614
+ while (ancestor && !seen.has(ancestor)) {
615
+ if (movingIds.has(ancestor)) {
616
+ nested = true;
617
+ break;
618
+ }
619
+ seen.add(ancestor);
620
+ ancestor = nodeIndex.get(ancestor)?.parentId ?? null;
621
+ }
622
+ if (!nested) topLevel.push(nodeIndex.get(movingId)!);
623
+ }
624
+ // moving subtree = moving nodes + all their descendants
625
+ const exclude = new Set(movingIds);
626
+ const queue = [...movingIds];
627
+ while (queue.length > 0) {
628
+ const current = queue.pop()!;
629
+ for (const child of childrenIndex.get(current) ?? []) {
630
+ if (!exclude.has(child.id)) {
631
+ exclude.add(child.id);
632
+ queue.push(child.id);
633
+ }
634
+ }
635
+ }
636
+ let bounds: Rect | null = null;
637
+ for (const node of topLevel) {
638
+ const b = engine.resolvedBounds(node.id);
639
+ bounds = bounds
640
+ ? {
641
+ x: Math.min(bounds.x, b.x),
642
+ y: Math.min(bounds.y, b.y),
643
+ width: Math.max(bounds.x + bounds.width, b.x + b.width) - Math.min(bounds.x, b.x),
644
+ height: Math.max(bounds.y + bounds.height, b.y + b.height) - Math.min(bounds.y, b.y),
645
+ }
646
+ : { ...b };
647
+ }
648
+ return { topLevel, exclude, bounds };
649
+ }
650
+
651
+ function trackCandidate(
652
+ ctx: FlowInputModeContext,
653
+ pending: Point,
654
+ ): FlowCommand[] {
655
+ // Commands in one batch are computed before any of them apply, so the
656
+ // store hasn't seen the dragMove yet — project the pending delta.
657
+ const { exclude, bounds } = movingInfo(ctx);
658
+ const projected = bounds
659
+ ? { ...bounds, x: bounds.x + pending.x, y: bounds.y + pending.y }
660
+ : null;
661
+ const found = projected
662
+ ? ctx.engine.getGroupDropTarget(projected, { exclude })
663
+ : null;
664
+ const nextId = found && found.overlap >= minOverlap ? found.id : null;
665
+ candidateOverlap = found?.overlap ?? 0;
666
+ if (nextId === candidateId) return [];
667
+ const commands: FlowCommand[] = [];
668
+ if (candidateId) {
669
+ commands.push(
670
+ trigger('removeHighlights', {
671
+ kind: REPARENT_HIGHLIGHT_KIND,
672
+ ids: [candidateId],
673
+ }),
674
+ );
675
+ }
676
+ if (nextId) {
677
+ commands.push(
678
+ trigger('addHighlights', {
679
+ kind: REPARENT_HIGHLIGHT_KIND,
680
+ entries: [{ id: nextId }],
681
+ }),
682
+ );
683
+ }
684
+ candidateId = nextId;
685
+ candidateSince = Date.now();
686
+ return commands;
687
+ }
688
+
689
+ function decideAndApply(
690
+ event: FlowPointerInputEvent,
691
+ ctx: FlowInputModeContext,
692
+ ): FlowCommand[] {
693
+ const commands: FlowCommand[] = [];
694
+ if (candidateId) {
695
+ commands.push(
696
+ trigger('removeHighlights', {
697
+ kind: REPARENT_HIGHLIGHT_KIND,
698
+ ids: [candidateId],
699
+ }),
700
+ );
701
+ }
702
+ if (event.kind !== 'pointer.up' || !reparent) return commands;
703
+
704
+ const { topLevel, exclude, bounds } = movingInfo(ctx);
705
+ if (!bounds || topLevel.length === 0) return commands;
706
+
707
+ // Recompute fresh at drop (tracking is projected per-move; the drop
708
+ // happens at the last tracked position, so ids should agree — but the
709
+ // final geometry is authoritative).
710
+ const found = ctx.engine.getGroupDropTarget(bounds, { exclude });
711
+ const finalId = found && found.overlap >= minOverlap ? found.id : null;
712
+ const hoverMs =
713
+ finalId && finalId === candidateId ? Date.now() - candidateSince : 0;
714
+ candidateId = finalId;
715
+ candidateOverlap = found?.overlap ?? 0;
716
+ const drop: ReparentDropContext = {
717
+ nodes: topLevel,
718
+ bounds,
719
+ candidate: candidateId
720
+ ? { id: candidateId, overlap: candidateOverlap }
721
+ : null,
722
+ hoverMs,
723
+ modifiers: event.modifiers,
724
+ };
725
+
726
+ let decision: ReparentDecision;
727
+ if (reparent.decide) {
728
+ decision = reparent.decide(drop, ctx);
729
+ } else if (unparentModifier && event.modifiers[unparentModifier]) {
730
+ decision = null;
731
+ } else if (candidateId && hoverMs >= (reparent.delayMs ?? 0)) {
732
+ decision = candidateId;
733
+ } else if (!candidateId && (reparent.unparent ?? true)) {
734
+ // Geometric unparenting: only when the current parent's rendered child
735
+ // area no longer touches the dragged bounds (never true for derived
736
+ // groups — they stretch to contain their children).
737
+ const escaped = topLevel.some((node) => {
738
+ if (!node.parentId) return false;
739
+ const geometry = ctx.engine.getGroupGeometry(node.parentId);
740
+ return geometry ? !rectsIntersect(bounds, geometry.childArea) : false;
741
+ });
742
+ decision = escaped ? null : undefined;
743
+ }
744
+
745
+ if (decision !== undefined) {
746
+ for (const node of topLevel) {
747
+ if ((node.parentId ?? null) === decision || node.id === decision) {
748
+ continue;
749
+ }
750
+ commands.push(
751
+ trigger('reparentNode', {
752
+ id: node.id,
753
+ parentId: decision,
754
+ transactionId,
755
+ }),
756
+ );
757
+ }
758
+ }
759
+ return commands;
760
+ }
761
+
762
+ return {
763
+ update(event, ctx) {
764
+ const { context } = ctx;
765
+ if (event.kind === 'pointer.move') {
766
+ if (!dragging) {
767
+ if (
768
+ distance(down.screenPoint, event.screenPoint) <
769
+ context.dragThreshold
770
+ ) {
771
+ return {};
772
+ }
773
+ dragging = true;
774
+ baseOffset = appliedOffset(ctx);
775
+ }
776
+ // Pointer-anchored request: ask the store for whatever delta brings
777
+ // the applied offset to the virtual target. Clamps simply truncate
778
+ // the request, and re-derive from the pointer on the next move.
779
+ const applied = appliedOffset(ctx);
780
+ const dx =
781
+ baseOffset.x + (event.point.x - down.point.x) - applied.x;
782
+ const dy =
783
+ baseOffset.y + (event.point.y - down.point.y) - applied.y;
784
+ const starting = !context.draggedEntityId;
785
+ return {
786
+ commands: [
787
+ ...(starting
788
+ ? [trigger('dragStart', { id, transactionId })]
789
+ : []),
790
+ trigger('dragMove', { dx, dy }),
791
+ ...(reparent ? trackCandidate(ctx, { x: dx, y: dy }) : []),
792
+ ],
793
+ };
794
+ }
795
+ if (event.kind === 'pointer.up' || event.kind === 'pointer.cancel') {
796
+ const snapResult = ctx.engine.getSnapResult();
797
+ const snapOffset =
798
+ snapResult
799
+ ? {
800
+ x: snapResult.snapRect.x - snapResult.sourceRect.x,
801
+ y: snapResult.snapRect.y - snapResult.sourceRect.y,
802
+ }
803
+ : { x: 0, y: 0 };
804
+ return {
805
+ commands: dragging
806
+ ? [
807
+ trigger('dragEnd'),
808
+ trigger('commitDrag', { transactionId, snapOffset }),
809
+ ...(reparent ? decideAndApply(event, ctx) : []),
810
+ ]
811
+ : event.kind === 'pointer.up'
812
+ ? [
813
+ trigger(down.detail === 2 ? 'entityDoubleClicked' : 'entityClicked', {
814
+ id,
815
+ point: down.point,
816
+ modifiers: down.modifiers,
817
+ }),
818
+ ]
819
+ : [],
820
+ status: 'end',
821
+ };
822
+ }
823
+ return {};
824
+ },
825
+ cancel() {
826
+ const commands: FlowCommand[] = dragging
827
+ ? [trigger('dragCancel')]
828
+ : [];
829
+ if (candidateId) {
830
+ commands.push(
831
+ trigger('removeHighlights', {
832
+ kind: REPARENT_HIGHLIGHT_KIND,
833
+ ids: [candidateId],
834
+ }),
835
+ );
836
+ }
837
+ return commands;
838
+ },
839
+ };
840
+ }
841
+
842
+
843
+ // Connect: dragging from a port starts a connection; validity is checked
844
+ // against the engine on every move; release emits `connectionEnded` with the
845
+ // drop target (node/port, edge, canvas position, or none).
846
+
847
+
848
+ export type ConnectModeOptions = {
849
+ /**
850
+ * Validity check for the current hover target during a connection drag.
851
+ * Defaults to `engine.validateConnection` for node/port targets (rejecting
852
+ * the source node itself) and `false` for everything else. Engine-level
853
+ * validation policy belongs in `createFlowEngine({ canConnect })`; use this
854
+ * override for gesture-specific rules (e.g. allowing canvas drops).
855
+ */
856
+ isValid?: (
857
+ args: {
858
+ source: { nodeId: string; port: string };
859
+ target: FlowInputTarget;
860
+ point: Point;
861
+ },
862
+ ctx: FlowInputModeContext,
863
+ ) => boolean;
864
+ };
865
+
866
+ export function connectMode(options: ConnectModeOptions = {}): FlowInputMode {
867
+ return {
868
+ id: 'connect',
869
+ priority: 60,
870
+ start(event, ctx) {
871
+ const { engine, context } = ctx;
872
+ const pending = context.connectionClickStartHandle;
873
+ if (pending && context.connection) {
874
+ if (!context.connectOnClick || event.kind === 'pointer.cancel') {
875
+ return { commands: [trigger('cancelConnection')] };
876
+ }
877
+ if (pending.port === null) return { commands: [trigger('cancelConnection')] };
878
+ const source = { nodeId: pending.nodeId, port: pending.port };
879
+ if (event.kind === 'pointer.move') {
880
+ return { commands: [connectionMoveCommand(resolveConnectionTarget(event, source, ctx, options.isValid), true)] };
881
+ }
882
+ if (event.kind !== 'pointer.down' || event.button !== 0) return null;
883
+ const target = event.target;
884
+ const completesOnPort = target.kind === 'port' &&
885
+ target.interaction !== 'inspect' &&
886
+ (target.nodeId !== source.nodeId || target.portName !== source.port);
887
+ const completesOnNode = target.kind === 'entity' &&
888
+ target.id !== source.nodeId && engine.getNode(target.id) !== undefined;
889
+ if (!completesOnPort && !completesOnNode) {
890
+ return { commands: [trigger('cancelConnection')] };
891
+ }
892
+ return { session: connectSession(source, options, { kind: 'completing' }) };
893
+ }
894
+ if (event.kind !== 'pointer.down' || event.button !== 0) return null;
895
+ if (event.target.kind !== 'port') return null;
896
+ if (event.target.interaction === 'inspect') return null;
897
+
898
+ const { nodeId, portName } = event.target;
899
+ const node = engine.getNode(nodeId);
900
+ if (!node?.ports?.some((port) => port.name === portName)) return null;
901
+ if (!engine.isPortAllowed(node, portName)) return null;
902
+ if (!engine.resolveEntityConfig(node).connectable) return null;
903
+
904
+ return {
905
+ commands: [
906
+ trigger('connectionStart', {
907
+ sourceId: nodeId,
908
+ sourcePort: portName,
909
+ position: event.point,
910
+ }),
911
+ ],
912
+ session: connectSession({ nodeId, port: portName }, options, { kind: 'pressed', screenPoint: event.screenPoint }),
913
+ };
914
+ },
915
+ };
916
+ }
917
+
918
+ /** Select/focus graph-owned ports explicitly rendered for readonly inspection. */
919
+ export function portPressMode(
920
+ options: { keymap?: Partial<FlowKeymap> } = {},
921
+ ): FlowInputMode {
922
+ const multiSelect = options.keymap
923
+ ? (event: FlowPointerInputEvent) =>
924
+ matchesMultiSelect(event.modifiers, resolveKeymap(options.keymap))
925
+ : isMulti;
926
+ return {
927
+ id: 'port-press',
928
+ priority: 55,
929
+ start(event, { engine }) {
930
+ if (event.kind !== 'pointer.down') return null;
931
+ if (event.target.kind !== 'port' || event.target.interaction !== 'inspect') {
932
+ return null;
933
+ }
934
+
935
+ const { nodeId, portName } = event.target;
936
+ const portId = event.target.portId ?? `${nodeId}:${portName}`;
937
+ const addressable = engine.getEntityRef(portId);
938
+ if (!addressable || addressable.kind !== 'port') return null;
939
+
940
+ if (event.button === 2) {
941
+ return {
942
+ commands: [
943
+ trigger('entityContextMenu', {
944
+ id: portId,
945
+ point: event.point,
946
+ modifiers: event.modifiers,
947
+ }),
948
+ ],
949
+ };
950
+ }
951
+ if (event.button !== 0) return null;
952
+
953
+ const owner = engine.getNode(nodeId);
954
+ if (!owner) return null;
955
+ const config = engine.resolveEntityConfig(owner);
956
+ const commands: FlowCommand[] = [];
957
+ if (config.selectable) {
958
+ commands.push(
959
+ trigger('select', {
960
+ ids: [portId],
961
+ mode: multiSelect(event) ? 'multi' : 'single',
962
+ }),
963
+ );
964
+ }
965
+ if (config.focusable) {
966
+ commands.push(trigger('focus', { entityId: portId }));
967
+ }
968
+ return {
969
+ commands,
970
+ session: entityClickSession(portId, event),
971
+ };
972
+ },
973
+ };
974
+ }
975
+
976
+ function defaultConnectionValidityDetailed(
977
+ args: {
978
+ source: { nodeId: string; port: string };
979
+ target: FlowInputTarget;
980
+ point: Point;
981
+ },
982
+ ctx: FlowInputModeContext,
983
+ ): { valid: boolean; reason?: string } {
984
+ const { source, target } = args;
985
+ if (target.kind === 'port') {
986
+ if (target.nodeId === source.nodeId) return { valid: false, reason: 'same-node' };
987
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
988
+ sourceId: source.nodeId,
989
+ sourcePort: source.port,
990
+ targetId: target.nodeId,
991
+ targetPort: target.portName,
992
+ }, ctx.context.graph));
993
+ }
994
+ if (target.kind === 'entity') {
995
+ if (target.id === source.nodeId) return { valid: false, reason: 'same-node' };
996
+ if (!ctx.engine.getNode(target.id)) return { valid: false, reason: 'not-node-target' };
997
+ const candidate = ctx.engine.getConnectionCandidate(args.point, { source });
998
+ if (!candidate || candidate.nodeId !== target.id || candidate.portName !== null) {
999
+ return { valid: false, reason: 'outside-connection-radius' };
1000
+ }
1001
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
1002
+ sourceId: source.nodeId,
1003
+ sourcePort: source.port,
1004
+ targetId: target.id,
1005
+ targetPort: null,
1006
+ }, ctx.context.graph));
1007
+ }
1008
+ return { valid: false, reason: 'invalid-target' };
1009
+ }
1010
+
1011
+ function connectEndTargetFor(
1012
+ target: FlowInputTarget,
1013
+ point: Point,
1014
+ ctx: FlowInputModeContext,
1015
+ ): ConnectEndTarget {
1016
+ if (target.kind === 'port') {
1017
+ return { kind: 'node', nodeId: target.nodeId, port: target.portName };
1018
+ }
1019
+ if (target.kind === 'entity') {
1020
+ const entity = ctx.engine.getEntity(target.id);
1021
+ if (entity?.type === 'node') {
1022
+ return { kind: 'node', nodeId: target.id, port: null };
1023
+ }
1024
+ if (entity?.type === 'edge') {
1025
+ return { kind: 'edge', edgeId: target.id };
1026
+ }
1027
+ }
1028
+ if (target.kind === 'pane') {
1029
+ return { kind: 'canvas', position: point };
1030
+ }
1031
+ return { kind: 'none' };
1032
+ }
1033
+
1034
+ type ResolvedConnectionTarget = {
1035
+ target: FlowInputTarget;
1036
+ targetId: string | null;
1037
+ targetPort: string | null;
1038
+ position: Point;
1039
+ isValid: boolean;
1040
+ invalidReason?: string;
1041
+ endTarget: ConnectEndTarget;
1042
+ };
1043
+
1044
+ function targetFromConnectionCandidate(candidate: {
1045
+ nodeId: string;
1046
+ portName: string | null;
1047
+ }): FlowInputTarget {
1048
+ return candidate.portName
1049
+ ? {
1050
+ kind: 'port',
1051
+ nodeId: candidate.nodeId,
1052
+ portName: candidate.portName,
1053
+ }
1054
+ : { kind: 'entity', id: candidate.nodeId };
1055
+ }
1056
+
1057
+ function targetIdsFor(
1058
+ target: FlowInputTarget,
1059
+ ctx: FlowInputModeContext,
1060
+ ): { targetId: string | null; targetPort: string | null } {
1061
+ if (target.kind === 'port') {
1062
+ return { targetId: target.nodeId, targetPort: target.portName };
1063
+ }
1064
+ if (target.kind === 'entity' && ctx.engine.getNode(target.id)) {
1065
+ return { targetId: target.id, targetPort: null };
1066
+ }
1067
+ return { targetId: null, targetPort: null };
1068
+ }
1069
+
1070
+ function resolveConnectionTarget(
1071
+ event: FlowPointerInputEvent,
1072
+ source: { nodeId: string; port: string },
1073
+ ctx: FlowInputModeContext,
1074
+ isValid: ConnectModeOptions['isValid'],
1075
+ ): ResolvedConnectionTarget {
1076
+ const candidate = ctx.engine.getConnectionCandidate(event.point, {
1077
+ source,
1078
+ });
1079
+ if (
1080
+ candidate &&
1081
+ (event.target.kind !== 'port' ||
1082
+ (candidate.nodeId === event.target.nodeId && candidate.portName === event.target.portName))
1083
+ ) {
1084
+ const target = targetFromConnectionCandidate(candidate);
1085
+ const validity = isValid
1086
+ ? isValid({ source, target, point: event.point }, ctx)
1087
+ : candidate.isValid;
1088
+ return {
1089
+ target,
1090
+ targetId: candidate.nodeId,
1091
+ targetPort: candidate.portName,
1092
+ position: candidate.position,
1093
+ isValid: validity,
1094
+ endTarget: connectEndTargetFor(target, candidate.position, ctx),
1095
+ };
1096
+ }
1097
+
1098
+ const { targetId, targetPort } = targetIdsFor(event.target, ctx);
1099
+ const detailed = isValid
1100
+ ? { valid: isValid({ source, target: event.target, point: event.point }, ctx) }
1101
+ : defaultConnectionValidityDetailed({ source, target: event.target, point: event.point }, ctx);
1102
+ return {
1103
+ target: event.target,
1104
+ targetId,
1105
+ targetPort,
1106
+ position: event.point,
1107
+ isValid: detailed.valid,
1108
+ invalidReason: detailed.reason,
1109
+ endTarget: connectEndTargetFor(event.target, event.point, ctx),
1110
+ };
1111
+ }
1112
+
1113
+ function connectionMoveCommand(target: ResolvedConnectionTarget, active?: boolean): FlowCommand {
1114
+ return trigger('connectionMove', {
1115
+ position: target.position,
1116
+ targetId: target.targetId,
1117
+ targetPort: target.targetPort,
1118
+ isValid: target.isValid,
1119
+ invalidReason: target.invalidReason,
1120
+ ...(active === undefined ? {} : { active }),
1121
+ });
1122
+ }
1123
+
1124
+ function connectSession(
1125
+ source: { nodeId: string; port: string },
1126
+ options: ConnectModeOptions,
1127
+ phase: { kind: 'pressed'; screenPoint: Point } | { kind: 'completing' },
1128
+ ): FlowInputSessionHandlers {
1129
+ return {
1130
+ update(event, ctx) {
1131
+ if (!ctx.context.connection) {
1132
+ return { status: 'end' };
1133
+ }
1134
+ if (event.kind === 'pointer.move') {
1135
+ const target = resolveConnectionTarget(event, source, ctx, options.isValid);
1136
+ const travel = phase.kind === 'pressed' ? distance(phase.screenPoint, event.screenPoint) : 0;
1137
+ const active = ctx.context.connection.active || phase.kind === 'completing' ||
1138
+ (travel > 0 && travel >= ctx.context.connectionDragThreshold);
1139
+ return { commands: [connectionMoveCommand(target, active)] };
1140
+ }
1141
+ if (event.kind === 'pointer.up') {
1142
+ if (
1143
+ phase.kind === 'pressed' &&
1144
+ ctx.context.connectOnClick &&
1145
+ !ctx.context.connection.active &&
1146
+ (distance(phase.screenPoint, event.screenPoint) === 0 ||
1147
+ distance(phase.screenPoint, event.screenPoint) < ctx.context.connectionDragThreshold)
1148
+ ) {
1149
+ return {
1150
+ commands: [
1151
+ trigger('setConnectionClickStartHandle', source),
1152
+ trigger('connectionMove', { position: event.point, active: true }),
1153
+ ],
1154
+ status: 'end',
1155
+ };
1156
+ }
1157
+ const target = resolveConnectionTarget(event, source, ctx, options.isValid);
1158
+ return {
1159
+ commands: [
1160
+ connectionMoveCommand(target),
1161
+ trigger('connectionEnd', { target: target.endTarget }),
1162
+ ],
1163
+ status: 'end',
1164
+ };
1165
+ }
1166
+ if (event.kind === 'pointer.cancel') {
1167
+ return { commands: [trigger('cancelConnection')], status: 'end' };
1168
+ }
1169
+ return {};
1170
+ },
1171
+ cancel() {
1172
+ return [trigger('cancelConnection')];
1173
+ },
1174
+ };
1175
+ }
1176
+
1177
+ // Reconnect: drag one selected edge endpoint and reuse connection preview state.
1178
+
1179
+
1180
+ export type ReconnectModeOptions = {
1181
+ /**
1182
+ * Mutate the Flow graph after a valid drop. Disable for controlled graphs
1183
+ * whose domain store consumes `connectionEnded` and owns the mutation.
1184
+ * Defaults to true.
1185
+ */
1186
+ commit?: boolean;
1187
+ /** Render Flow's generic preview edge. Disable when an external store owns
1188
+ * temporary preview geometry. Defaults to true. */
1189
+ preview?: boolean;
1190
+ /**
1191
+ * Delay reconnect activation until pointer travel crosses a screen-pixel
1192
+ * threshold. `true` uses the store's `connectionDragThreshold`; a number
1193
+ * uses that exact threshold. Defaults to immediate activation.
1194
+ */
1195
+ dragThreshold?: boolean | number;
1196
+ isValid?: (
1197
+ args: {
1198
+ edge: FlowEdge;
1199
+ end: 'source' | 'target';
1200
+ target: FlowInputTarget;
1201
+ point: Point;
1202
+ },
1203
+ ctx: FlowInputModeContext,
1204
+ ) => boolean;
1205
+ };
1206
+
1207
+ function edgeEndpointFromPart(
1208
+ part: string | undefined,
1209
+ ): 'source' | 'target' | null {
1210
+ if (part === 'edge-endpoint:source') return 'source';
1211
+ if (part === 'edge-endpoint:target') return 'target';
1212
+ return null;
1213
+ }
1214
+
1215
+ function reconnectTarget(
1216
+ target: FlowInputTarget,
1217
+ ctx: FlowInputModeContext,
1218
+ point?: Point,
1219
+ ): { nodeId: string; port: string | null } | null {
1220
+ if (target.kind === 'port') {
1221
+ return { nodeId: target.nodeId, port: target.portName };
1222
+ }
1223
+ if (target.kind === 'entity' && ctx.engine.getNode(target.id)) {
1224
+ return { nodeId: target.id, port: null };
1225
+ }
1226
+ if (point) {
1227
+ const candidate = ctx.engine.getConnectionCandidate(point);
1228
+ if (candidate) {
1229
+ return { nodeId: candidate.nodeId, port: candidate.portName };
1230
+ }
1231
+ }
1232
+ return null;
1233
+ }
1234
+
1235
+ function defaultReconnectValidity(
1236
+ args: {
1237
+ edge: FlowEdge;
1238
+ end: 'source' | 'target';
1239
+ target: FlowInputTarget;
1240
+ point: Point;
1241
+ },
1242
+ ctx: FlowInputModeContext,
1243
+ ): boolean {
1244
+ const candidate = reconnectTarget(args.target, ctx, args.point);
1245
+ if (!candidate) return false;
1246
+ if (args.end === 'source') {
1247
+ return ctx.engine.validateConnection({
1248
+ sourceId: candidate.nodeId,
1249
+ sourcePort: candidate.port,
1250
+ targetId: args.edge.targetId,
1251
+ targetPort: args.edge.targetPort ?? null,
1252
+ });
1253
+ }
1254
+ return ctx.engine.validateConnection({
1255
+ sourceId: args.edge.sourceId,
1256
+ sourcePort: args.edge.sourcePort ?? null,
1257
+ targetId: candidate.nodeId,
1258
+ targetPort: candidate.port,
1259
+ });
1260
+ }
1261
+
1262
+ export function reconnectMode(options: ReconnectModeOptions = {}): FlowInputMode {
1263
+ return {
1264
+ id: 'reconnect',
1265
+ priority: 75,
1266
+ start(event, { context, engine }) {
1267
+ if (event.kind !== 'pointer.down' || event.button !== 0) return null;
1268
+ if (event.target.kind !== 'entity') return null;
1269
+ const end = edgeEndpointFromPart(event.target.part);
1270
+ if (!end) return null;
1271
+
1272
+ const edge = engine.getEdge(event.target.id);
1273
+ if (!edge) return null;
1274
+ if (!engine.resolveEntityConfig(edge).reconnectable) return null;
1275
+
1276
+ const fixedNodeId = end === 'source' ? edge.targetId : edge.sourceId;
1277
+ if (!engine.getNode(fixedNodeId)) return null;
1278
+ const fixedPort =
1279
+ end === 'source' ? edge.targetPort ?? null : edge.sourcePort ?? null;
1280
+ const transactionId = `reconnect:${edge.id}:${event.pointerId}:${Date.now()}`;
1281
+ const threshold =
1282
+ options.dragThreshold === true
1283
+ ? context.connectionDragThreshold
1284
+ : typeof options.dragThreshold === 'number'
1285
+ ? Math.max(0, options.dragThreshold)
1286
+ : 0;
1287
+
1288
+ return {
1289
+ commands: [
1290
+ preventDefault,
1291
+ trigger('connectionStart', {
1292
+ sourceId: fixedNodeId,
1293
+ sourcePort: fixedPort,
1294
+ position: event.point,
1295
+ active: threshold === 0,
1296
+ reconnectingEdgeId: edge.id,
1297
+ reconnectingEnd: end,
1298
+ preview: options.preview !== false,
1299
+ }),
1300
+ ],
1301
+ session: reconnectSession(
1302
+ {
1303
+ edgeId: edge.id,
1304
+ end,
1305
+ transactionId,
1306
+ startScreenPoint: event.screenPoint,
1307
+ threshold,
1308
+ },
1309
+ options,
1310
+ ),
1311
+ };
1312
+ },
1313
+ };
1314
+ }
1315
+
1316
+ function reconnectSession(
1317
+ reconnect: {
1318
+ edgeId: string;
1319
+ end: 'source' | 'target';
1320
+ transactionId: string;
1321
+ startScreenPoint: Point;
1322
+ threshold: number;
1323
+ },
1324
+ options: ReconnectModeOptions,
1325
+ ): FlowInputSessionHandlers {
1326
+ const isValid = options.isValid ?? defaultReconnectValidity;
1327
+ let active = reconnect.threshold === 0;
1328
+
1329
+ function moveCommands(
1330
+ event: FlowPointerInputEvent,
1331
+ ctx: FlowInputModeContext,
1332
+ activate = false,
1333
+ ): { commands: FlowCommand[]; candidate: { nodeId: string; port: string | null } | null; valid: boolean } {
1334
+ const edge = ctx.engine.getEdge(reconnect.edgeId);
1335
+ const candidate = reconnectTarget(event.target, ctx, event.point);
1336
+ const valid =
1337
+ !!edge &&
1338
+ isValid(
1339
+ { edge, end: reconnect.end, target: event.target, point: event.point },
1340
+ ctx,
1341
+ );
1342
+ return {
1343
+ candidate,
1344
+ valid,
1345
+ commands: [
1346
+ trigger('connectionMove', {
1347
+ position: event.point,
1348
+ targetId: candidate?.nodeId ?? null,
1349
+ targetPort: candidate?.port ?? null,
1350
+ isValid: valid,
1351
+ ...(activate ? { active: true } : {}),
1352
+ }),
1353
+ ],
1354
+ };
1355
+ }
1356
+
1357
+ return {
1358
+ update(event, ctx) {
1359
+ if (!ctx.context.connection) {
1360
+ return { status: 'end' };
1361
+ }
1362
+ if (event.kind === 'pointer.move') {
1363
+ if (!active) {
1364
+ if (
1365
+ distance(reconnect.startScreenPoint, event.screenPoint) <
1366
+ reconnect.threshold
1367
+ ) {
1368
+ return {};
1369
+ }
1370
+ active = true;
1371
+ return { commands: moveCommands(event, ctx, true).commands };
1372
+ }
1373
+ return { commands: moveCommands(event, ctx).commands };
1374
+ }
1375
+ if (event.kind === 'pointer.up') {
1376
+ if (!active) {
1377
+ return {
1378
+ commands: [
1379
+ trigger('connectionEnd', {
1380
+ target: { kind: 'none' },
1381
+ reconnectedEdgeId: reconnect.edgeId,
1382
+ }),
1383
+ ],
1384
+ status: 'end',
1385
+ };
1386
+ }
1387
+ const result = moveCommands(event, ctx);
1388
+ const commands: FlowCommand[] = [...result.commands];
1389
+ if (result.candidate && result.valid) {
1390
+ const endTarget = connectEndTargetFor(
1391
+ targetFromConnectionCandidate({
1392
+ nodeId: result.candidate.nodeId,
1393
+ portName: result.candidate.port,
1394
+ }),
1395
+ event.point,
1396
+ ctx,
1397
+ );
1398
+ if (options.commit !== false) {
1399
+ commands.push(
1400
+ trigger('reconnectEdge', {
1401
+ edgeId: reconnect.edgeId,
1402
+ ...(reconnect.end === 'source'
1403
+ ? {
1404
+ newSourceId: result.candidate.nodeId,
1405
+ newSourcePort: result.candidate.port,
1406
+ }
1407
+ : {
1408
+ newTargetId: result.candidate.nodeId,
1409
+ newTargetPort: result.candidate.port,
1410
+ }),
1411
+ transactionId: reconnect.transactionId,
1412
+ }),
1413
+ );
1414
+ }
1415
+ commands.push(
1416
+ trigger('connectionEnd', {
1417
+ target: endTarget,
1418
+ reconnectedEdgeId: reconnect.edgeId,
1419
+ }),
1420
+ );
1421
+ } else {
1422
+ commands.push(
1423
+ trigger('connectionEnd', {
1424
+ target: connectEndTargetFor(event.target, event.point, ctx),
1425
+ reconnectedEdgeId: reconnect.edgeId,
1426
+ }),
1427
+ );
1428
+ }
1429
+ return { commands, status: 'end' };
1430
+ }
1431
+ if (event.kind === 'pointer.cancel') {
1432
+ return {
1433
+ commands: [
1434
+ trigger('connectionEnd', {
1435
+ target: { kind: 'none' },
1436
+ reconnectedEdgeId: reconnect.edgeId,
1437
+ }),
1438
+ ],
1439
+ status: 'end',
1440
+ };
1441
+ }
1442
+ return {};
1443
+ },
1444
+ cancel() {
1445
+ return [
1446
+ trigger('connectionEnd', {
1447
+ target: { kind: 'none' },
1448
+ reconnectedEdgeId: reconnect.edgeId,
1449
+ }),
1450
+ ];
1451
+ },
1452
+ };
1453
+ }
1454
+
1455
+
1456
+ // Hover: bare pointer moves (no active session) track the entity under the
1457
+ // pointer. Triggers only when the hovered entity actually changes, and the
1458
+ // store bails on identical sets — most moves cost nothing downstream.
1459
+
1460
+
1461
+ export function hoverMode(): FlowInputMode {
1462
+ return {
1463
+ id: 'hover',
1464
+ priority: 5,
1465
+ start(event, { context }) {
1466
+ if (event.kind !== 'pointer.move') return null;
1467
+ const target = event.target;
1468
+ const id =
1469
+ target.kind === 'entity'
1470
+ ? target.id
1471
+ : target.kind === 'port'
1472
+ ? target.nodeId
1473
+ : null;
1474
+ const current = context.hoveredEntityIds;
1475
+ if (id) {
1476
+ if (current.size === 1 && current.has(id)) return null;
1477
+ return { commands: [trigger('setHover', { ids: [id] })] };
1478
+ }
1479
+ if (current.size === 0) return null;
1480
+ return { commands: [trigger('clearHover')] };
1481
+ },
1482
+ };
1483
+ }
1484
+
1485
+
1486
+ // Pane press: click clears selection; drag past the threshold pans
1487
+
1488
+
1489
+ export function panePressMode(): FlowInputMode {
1490
+ return {
1491
+ id: 'pane-press',
1492
+ priority: 10,
1493
+ start(event) {
1494
+ if (event.kind !== 'pointer.down') return null;
1495
+ if (event.target.kind !== 'pane') return null;
1496
+ if (event.button === 2) {
1497
+ return {
1498
+ commands: [
1499
+ trigger('paneContextMenu', {
1500
+ point: event.point,
1501
+ modifiers: event.modifiers,
1502
+ }),
1503
+ ],
1504
+ };
1505
+ }
1506
+ if (event.button !== 0) return null;
1507
+ return { session: panePressSession(event) };
1508
+ },
1509
+ };
1510
+ }
1511
+
1512
+ function panePressSession(
1513
+ down: FlowPointerInputEvent,
1514
+ ): FlowInputSessionHandlers {
1515
+ let panning = false;
1516
+
1517
+ return {
1518
+ update(event, { context }) {
1519
+ if (event.kind === 'pointer.move') {
1520
+ if (!panning) {
1521
+ if (
1522
+ distance(down.screenPoint, event.screenPoint) <
1523
+ context.dragThreshold
1524
+ ) {
1525
+ return {};
1526
+ }
1527
+ panning = true;
1528
+ return {
1529
+ commands: [
1530
+ trigger('clearSelection'),
1531
+ trigger('clearFocus'),
1532
+ trigger('panStart', down.screenPoint),
1533
+ trigger('pan', event.screenPoint),
1534
+ ],
1535
+ };
1536
+ }
1537
+ return { commands: [trigger('pan', event.screenPoint)] };
1538
+ }
1539
+ if (event.kind === 'pointer.up') {
1540
+ return {
1541
+ commands: panning
1542
+ ? [trigger('panEnd')]
1543
+ : [
1544
+ trigger('clearSelection'),
1545
+ trigger('clearFocus'),
1546
+ trigger('paneClicked', {
1547
+ point: down.point,
1548
+ modifiers: down.modifiers,
1549
+ }),
1550
+ ],
1551
+ status: 'end',
1552
+ };
1553
+ }
1554
+ if (event.kind === 'pointer.cancel') {
1555
+ return {
1556
+ commands: panning ? [trigger('panEnd')] : [],
1557
+ status: 'end',
1558
+ };
1559
+ }
1560
+ return {};
1561
+ },
1562
+ cancel() {
1563
+ return panning ? [trigger('panCancel')] : [];
1564
+ },
1565
+ };
1566
+ }
1567
+
1568
+
1569
+ // Box selection: shift + drag on the pane sweeps a marquee that selects every
1570
+ // entity it touches. Sits above pane-press so the modifier diverts the pane
1571
+ // drag from panning to selecting; a plain pane drag still pans.
1572
+
1573
+
1574
+ export type BoxSelectModeOptions = {
1575
+ /**
1576
+ * Whether a pane pointer-down should begin a box select. Default: only with
1577
+ * a multi modifier (shift/ctrl/meta) held, so a plain pane drag still pans.
1578
+ * Pass `() => true` for a selection-first canvas where every pane drag boxes
1579
+ * (and the modifier instead adds to the existing selection).
1580
+ */
1581
+ enabled?: (event: FlowPointerInputEvent) => boolean;
1582
+ keymap?: Partial<FlowKeymap>;
1583
+ };
1584
+
1585
+ export function boxSelectMode(
1586
+ options: BoxSelectModeOptions = {},
1587
+ ): FlowInputMode {
1588
+ // Keymap-driven multi-select, falling back to the legacy `isMulti`
1589
+ // (shift||meta||ctrl) so default behavior is byte-identical.
1590
+ const multiSelect = options.keymap
1591
+ ? (event: FlowPointerInputEvent) =>
1592
+ matchesMultiSelect(event.modifiers, resolveKeymap(options.keymap))
1593
+ : isMulti;
1594
+ const enabled = options.enabled ?? multiSelect;
1595
+ return {
1596
+ id: 'box-select',
1597
+ priority: 20,
1598
+ start(event) {
1599
+ if (event.kind !== 'pointer.down' || event.button !== 0) return null;
1600
+ if (event.target.kind !== 'pane') return null;
1601
+ // follow-up: touch box-select bails here; touch long-press box-select is
1602
+ // a deferred follow-up (WP4) — for now a touch pane drag always pans.
1603
+ if (event.pointerType === 'touch') return null;
1604
+ if (!enabled(event)) return null;
1605
+ return { session: boxSelectSession(event, multiSelect) };
1606
+ },
1607
+ };
1608
+ }
1609
+
1610
+ function boxSelectSession(
1611
+ down: FlowPointerInputEvent,
1612
+ multiSelect: (event: FlowPointerInputEvent) => boolean,
1613
+ ): FlowInputSessionHandlers {
1614
+ let selecting = false;
1615
+
1616
+ return {
1617
+ update(event, { context }) {
1618
+ if (event.kind === 'pointer.move') {
1619
+ if (!selecting) {
1620
+ if (
1621
+ distance(down.screenPoint, event.screenPoint) <
1622
+ context.dragThreshold
1623
+ ) {
1624
+ return {};
1625
+ }
1626
+ selecting = true;
1627
+ return {
1628
+ commands: [
1629
+ trigger('selectionBoxStart', {
1630
+ point: down.point,
1631
+ mode: multiSelect(down) ? 'multi' : 'single',
1632
+ }),
1633
+ trigger('selectionBoxMove', { point: event.point }),
1634
+ ],
1635
+ };
1636
+ }
1637
+ return {
1638
+ commands: [trigger('selectionBoxMove', { point: event.point })],
1639
+ };
1640
+ }
1641
+ if (event.kind === 'pointer.up' || event.kind === 'pointer.cancel') {
1642
+ if (selecting) {
1643
+ return { commands: [trigger('selectionBoxEnd')], status: 'end' };
1644
+ }
1645
+ // A tap with no drag: clear selection + focus like a pane click would
1646
+ // (this mode pre-empts pane-press, so it must own that behavior). A
1647
+ // modifier tap is left alone — it's an additive intent.
1648
+ return {
1649
+ commands: multiSelect(down)
1650
+ ? []
1651
+ : [
1652
+ trigger('clearSelection'),
1653
+ trigger('clearFocus'),
1654
+ trigger('paneClicked', {
1655
+ point: down.point,
1656
+ modifiers: down.modifiers,
1657
+ }),
1658
+ ],
1659
+ status: 'end',
1660
+ };
1661
+ }
1662
+ return {};
1663
+ },
1664
+ cancel() {
1665
+ return selecting ? [trigger('selectionBoxCancel')] : [];
1666
+ },
1667
+ };
1668
+ }
1669
+
1670
+
1671
+ // Presets
1672
+
1673
+
1674
+ /** Interactive default: full editing gestures. */
1675
+ export function defaultInputModesForKeymap(
1676
+ keymap?: Partial<FlowKeymap>,
1677
+ ): FlowInputMode[] {
1678
+ return [
1679
+ keyboardMode({ keymap }),
1680
+ keyboardNavMode({ keymap }),
1681
+ wheelMode(),
1682
+ pinchMode(),
1683
+ doubleClickZoomMode(),
1684
+ panMode(),
1685
+ connectMode(),
1686
+ portPressMode({ keymap }),
1687
+ reconnectMode(),
1688
+ entityPressMode({ keymap }),
1689
+ boxSelectMode({ keymap }),
1690
+ panePressMode(),
1691
+ hoverMode(),
1692
+ ];
1693
+ }
1694
+
1695
+ export const defaultInputModes: FlowInputMode[] = defaultInputModesForKeymap();
1696
+
1697
+ /** Readonly: select and navigate, no mutation gestures. */
1698
+ export function readonlyInputModesForKeymap(
1699
+ keymap?: Partial<FlowKeymap>,
1700
+ ): FlowInputMode[] {
1701
+ return [
1702
+ keyboardMode({ allowDelete: false, allowUndo: false, keymap }),
1703
+ keyboardNavMode({ allowMove: false, keymap }),
1704
+ wheelMode(),
1705
+ doubleClickZoomMode(),
1706
+ panMode(),
1707
+ portPressMode({ keymap }),
1708
+ entityPressMode({ drag: false, keymap }),
1709
+ boxSelectMode({ keymap }),
1710
+ panePressMode(),
1711
+ hoverMode(),
1712
+ ];
1713
+ }
1714
+
1715
+ export const readonlyInputModes: FlowInputMode[] = readonlyInputModesForKeymap();