@statelyai/flow 0.13.4 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +5 -1
  2. package/dist/esm/index.d.ts +13 -2
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +39 -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,615 @@
1
+ import { connectionLifetime } from '../connection-lifetime';
2
+ import type { FlowStore, FlowStoreContext } from '../store';
3
+ import type { FlowEngine } from '../engine';
4
+ import type { Point } from '../types';
5
+ import {
6
+ matchesKeyBinding,
7
+ resolveKeymap,
8
+ type FlowKeymap,
9
+ } from './keymap';
10
+ export { defaultKeymap, matchesKeyBinding, resolveKeymap } from './keymap';
11
+ export type { FlowKeyBinding, FlowKeymap } from './keymap';
12
+
13
+ // Flow input runtime
14
+ //
15
+ // Framework-neutral input recognition (see .notes/react-flow-soft-parity.md,
16
+ // "Input Recognition Model"). Adapters normalize raw browser/framework events
17
+ // into FlowInputEvents and feed them to a runtime; the runtime dispatches to
18
+ // ordered input modes which return declarative commands. The runtime applies
19
+ // commands through `store.trigger` — modes never perform side effects, which
20
+ // keeps every gesture unit-testable without a DOM.
21
+ //
22
+ // raw event → adapter (flow-dom/flow-react) → FlowInputEvent
23
+ // → runtime → mode.start(...) / session.update(...) → FlowCommand[]
24
+ // → store.trigger.*
25
+ //
26
+ // One exclusive session at a time (a drag, a pan). While a session is active,
27
+ // pointer events for its pointer go to the session; keyboard/wheel and other
28
+ // pointers still flow to stateless modes.
29
+
30
+
31
+ // Normalized events
32
+
33
+
34
+ export type FlowInputModifiers = {
35
+ shift: boolean;
36
+ meta: boolean;
37
+ ctrl: boolean;
38
+ alt: boolean;
39
+ };
40
+
41
+ export type FlowInputTarget =
42
+ | { kind: 'pane' }
43
+ | {
44
+ kind: 'entity';
45
+ id: string;
46
+ part?:
47
+ | 'label'
48
+ | `resize-handle:${string}`
49
+ | `edge-endpoint:${string}`
50
+ | (string & {});
51
+ /**
52
+ * Drag-handle gating (set by adapters from `data-flow-drag-handle`
53
+ * markers): when the entity declares a handle, drags only start from
54
+ * presses inside it — e.g. a group that is dragged by its content
55
+ * block but not by its children area.
56
+ */
57
+ entityHasDragHandle?: boolean;
58
+ pressedDragHandle?: boolean;
59
+ }
60
+ | {
61
+ kind: 'port';
62
+ nodeId: string;
63
+ portName: string;
64
+ portId?: string;
65
+ /** `inspect` addresses the port without starting a connection gesture. */
66
+ interaction?: 'connect' | 'inspect';
67
+ }
68
+ | { kind: 'none' };
69
+
70
+ export type FlowPointerInputEvent = {
71
+ kind: 'pointer.down' | 'pointer.move' | 'pointer.up' | 'pointer.cancel';
72
+ pointerId: number;
73
+ pointerType: 'mouse' | 'pen' | 'touch';
74
+ /** Pressed button for down events (0 left, 1 middle); -1 for moves. */
75
+ button: number;
76
+ /** Native click count from PointerEvent.detail; 2 means double-click. */
77
+ detail?: number;
78
+ /** Pointer position in canvas (graph/world) coordinates. */
79
+ point: Point;
80
+ /** Pointer position in container-relative screen pixels. */
81
+ screenPoint: Point;
82
+ target: FlowInputTarget;
83
+ modifiers: FlowInputModifiers;
84
+ };
85
+
86
+ export type FlowPinchInputEvent = {
87
+ kind: 'pinch.start' | 'pinch.move' | 'pinch.end';
88
+ /** Pinch center in canvas (graph/world) coordinates. */
89
+ center: Point;
90
+ /** Pinch center in container-relative screen pixels. */
91
+ screenCenter: Point;
92
+ /** Distance between the first two active touch pointers in screen pixels. */
93
+ distance: number;
94
+ pointerCount: number;
95
+ modifiers: FlowInputModifiers;
96
+ };
97
+
98
+ export type FlowWheelInputEvent = {
99
+ kind: 'wheel';
100
+ deltaX: number;
101
+ deltaY: number;
102
+ /** WheelEvent.deltaMode: 0 pixels, 1 lines, 2 pages. */
103
+ deltaMode: number;
104
+ point: Point;
105
+ screenPoint: Point;
106
+ target: FlowInputTarget;
107
+ modifiers: FlowInputModifiers;
108
+ };
109
+
110
+ export type FlowKeyInputEvent = {
111
+ kind: 'key.down' | 'key.up';
112
+ key: string;
113
+ /** True when the event originated from a text input/contenteditable. */
114
+ editableTarget: boolean;
115
+ modifiers: FlowInputModifiers;
116
+ };
117
+
118
+ export type FlowInputEvent =
119
+ | FlowPointerInputEvent
120
+ | FlowPinchInputEvent
121
+ | FlowWheelInputEvent
122
+ | FlowKeyInputEvent;
123
+
124
+
125
+ // Commands
126
+
127
+
128
+ type FlowTriggerMap = FlowStore['trigger'];
129
+ export type FlowTriggerName = keyof FlowTriggerMap & string;
130
+
131
+ export type FlowTriggerCommand = {
132
+ type: 'trigger';
133
+ name: FlowTriggerName;
134
+ params?: unknown;
135
+ };
136
+
137
+ export type FlowCommand =
138
+ | FlowTriggerCommand
139
+ | { type: 'preventDefault' }
140
+ | { type: 'stopPropagation' };
141
+
142
+ /** Typed constructor for trigger commands. */
143
+ export function trigger<K extends FlowTriggerName>(
144
+ name: K,
145
+ ...params: Parameters<FlowTriggerMap[K]>
146
+ ): FlowTriggerCommand {
147
+ return { type: 'trigger', name, params: params[0] };
148
+ }
149
+
150
+ export const preventDefault: FlowCommand = { type: 'preventDefault' };
151
+
152
+
153
+ // Modes & sessions
154
+
155
+
156
+ export type FlowInputModeContext = {
157
+ /** Current store snapshot context. */
158
+ context: FlowStoreContext;
159
+ /** Engine for read-only queries (hit info, behavior config). */
160
+ engine: FlowEngine;
161
+ /** Runtime-tracked transient input state (lives outside the store). */
162
+ input: { panKeyHeld: boolean; /** @deprecated Use panKeyHeld. */ spaceHeld: boolean };
163
+ };
164
+
165
+ export type FlowSessionResult = {
166
+ commands?: FlowCommand[];
167
+ /** 'continue' (default) keeps the session; 'end' terminates it. */
168
+ status?: 'continue' | 'end';
169
+ };
170
+
171
+ export type FlowInputSessionHandlers = {
172
+ /** Receives subsequent events for the session's pointer. */
173
+ update: (
174
+ event: FlowInputEvent,
175
+ ctx: FlowInputModeContext,
176
+ ) => FlowSessionResult | void;
177
+ /** Called when the runtime cancels the session (dispose, external cancel). */
178
+ cancel?: (ctx: FlowInputModeContext) => FlowCommand[] | void;
179
+ };
180
+
181
+ export type FlowInputReaction = {
182
+ commands?: FlowCommand[];
183
+ /** Begin an exclusive session that receives subsequent events. */
184
+ session?: FlowInputSessionHandlers;
185
+ };
186
+
187
+ export type FlowInputMode = {
188
+ id: string;
189
+ /** Higher priority runs earlier. Default 0. */
190
+ priority?: number;
191
+ /**
192
+ * Inspect an event and either claim it (return a reaction — the event is
193
+ * consumed and lower-priority modes are skipped) or pass (return null).
194
+ */
195
+ start: (
196
+ event: FlowInputEvent,
197
+ ctx: FlowInputModeContext,
198
+ ) => FlowInputReaction | null | undefined | void;
199
+ };
200
+
201
+
202
+ // Runtime
203
+
204
+
205
+ export type FlowInputEffects = {
206
+ /** The adapter should call event.preventDefault(). */
207
+ preventDefault: boolean;
208
+ /** The adapter should call event.stopPropagation(). */
209
+ stopPropagation: boolean;
210
+ /** A session began on this event — adapters should capture the pointer. */
211
+ sessionStarted: boolean;
212
+ /** The active session ended — adapters should release the pointer. */
213
+ sessionEnded: boolean;
214
+ /** Id of the mode that handled the event, or null if unhandled. */
215
+ handledBy: string | null;
216
+ };
217
+
218
+ export type FlowInputRuntimeOptions = {
219
+ store: FlowStore;
220
+ engine: FlowEngine;
221
+ /**
222
+ * Input modes, or a resolver from store context (so the active set can
223
+ * follow `context.mode`). Defaults to `defaultModesForContext`: the
224
+ * interactive set, or the readonly set when `context.mode === 'readonly'`.
225
+ */
226
+ modes?: FlowInputMode[] | ((context: FlowStoreContext) => FlowInputMode[]);
227
+ /** Keymap used by the built-in runtime state such as panActivation. */
228
+ keymap?: Partial<FlowKeymap>;
229
+ /** Profile policies resolved for the current mode. */
230
+ policies?: FlowPolicies | ((context: FlowStoreContext) => FlowPolicies);
231
+ };
232
+
233
+ export type FlowInputRuntime = {
234
+ /** Feed one normalized event; apply resulting commands to the store. */
235
+ send: (event: FlowInputEvent) => FlowInputEffects;
236
+ /** Reconcile pending input after an adapter changes its mode set. */
237
+ reconcileModes: () => void;
238
+ /** Cancel the active session, if any (applies its cancel commands). */
239
+ cancelSession: () => void;
240
+ /** Id of the mode owning the active session, or null. */
241
+ getActiveSession: () => string | null;
242
+ };
243
+
244
+ export function createFlowInputRuntime(
245
+ options: FlowInputRuntimeOptions,
246
+ ): FlowInputRuntime {
247
+ const { store, engine } = options;
248
+ const resolveModes: (context: FlowStoreContext) => FlowInputMode[] =
249
+ typeof options.modes === 'function'
250
+ ? options.modes
251
+ : options.modes
252
+ ? () => options.modes as FlowInputMode[]
253
+ : (context) => defaultModesForContext(context, options.keymap);
254
+
255
+ const keymap = resolveKeymap(options.keymap);
256
+ const input = { panKeyHeld: false, spaceHeld: false };
257
+ let session: {
258
+ handlers: FlowInputSessionHandlers;
259
+ modeId: string;
260
+ pointerId: number | null;
261
+ } | null = null;
262
+
263
+ function modeContext(): FlowInputModeContext {
264
+ return { context: store.getSnapshot().context, engine, input };
265
+ }
266
+
267
+ function apply(
268
+ commands: FlowCommand[] | void | undefined,
269
+ effects: FlowInputEffects,
270
+ ): void {
271
+ if (!commands) return;
272
+ for (const command of commands) {
273
+ if (command.type === 'preventDefault') {
274
+ effects.preventDefault = true;
275
+ } else if (command.type === 'stopPropagation') {
276
+ effects.stopPropagation = true;
277
+ } else {
278
+ if (!isInputCommandAllowed(command.name, store.getSnapshot().context)) {
279
+ continue;
280
+ }
281
+ const fire = (
282
+ store.trigger as Record<string, (params?: unknown) => void>
283
+ )[command.name];
284
+ fire?.(command.params);
285
+ }
286
+ }
287
+ }
288
+
289
+ function isInputCommandAllowed(
290
+ name: FlowTriggerName,
291
+ context: FlowStoreContext,
292
+ ): boolean {
293
+ const policies = typeof options.policies === 'function'
294
+ ? options.policies(context)
295
+ : options.policies ?? {};
296
+ const mutating: readonly FlowTriggerName[] = [
297
+ 'createNode', 'deleteNode', 'updateNode', 'updateNodeData',
298
+ 'createEdge', 'deleteEdge', 'deleteEntities', 'updateEdge',
299
+ 'updateEdgeData', 'deleteSelected', 'reparentNode', 'dragStart',
300
+ 'dragMove', 'dragEnd', 'commitDrag', 'resizeStart', 'resizeMove',
301
+ 'resizeEnd', 'reconnectEdge', 'moveNodes', 'undo', 'redo',
302
+ 'connectionStart', 'connectionMove', 'connectionEnd',
303
+ 'collapseNode', 'expandNode',
304
+ ];
305
+ if (mutating.includes(name) && policies.canEdit === false) return false;
306
+ if (
307
+ ['deleteNode', 'deleteEdge', 'deleteEntities', 'deleteSelected'].includes(name) &&
308
+ policies.canDelete === false
309
+ ) return false;
310
+ if (
311
+ ['dragStart', 'dragMove', 'dragEnd', 'commitDrag', 'moveNodes'].includes(name) &&
312
+ policies.canMove === false
313
+ ) return false;
314
+ if (name.startsWith('resize') && policies.canResize === false) return false;
315
+ if (
316
+ ['connectionStart', 'connectionMove', 'connectionEnd'].includes(name) &&
317
+ policies.canConnect === false
318
+ ) return false;
319
+ if (name === 'reconnectEdge' && policies.canReconnect === false) return false;
320
+ if (name === 'reparentNode' && policies.canReparent === false) return false;
321
+ if (name === 'createNode' || name === 'createEdge') {
322
+ if (policies.canCreate === false) return false;
323
+ }
324
+ if (name === 'undo' && policies.canUndo === false) return false;
325
+ if (name === 'redo' && policies.canRedo === false) return false;
326
+ if (
327
+ ['panStart', 'pan', 'panEnd', 'panBy', 'setViewport'].includes(name) &&
328
+ policies.canPan === false
329
+ ) return false;
330
+ if (['zoomTo', 'zoomBy'].includes(name) && policies.canZoom === false) return false;
331
+ if (['select', 'selectAll'].includes(name) && policies.canSelect === false) return false;
332
+ if (name === 'focus' && policies.canFocus === false) return false;
333
+ if (name === 'setHover' && policies.canHover === false) return false;
334
+ return true;
335
+ }
336
+
337
+ function cancelPendingConnection(previous: FlowStoreContext): void {
338
+ const current = store.getSnapshot().context;
339
+ if (
340
+ previous.connectionClickStartHandle &&
341
+ current.connectionClickStartHandle === previous.connectionClickStartHandle &&
342
+ (previous.connection?.[connectionLifetime]
343
+ ? current.connection?.[connectionLifetime] === previous.connection[connectionLifetime]
344
+ : current.connection === previous.connection)
345
+ ) {
346
+ store.trigger.cancelConnection();
347
+ }
348
+ }
349
+
350
+ function reconcileModes(): void {
351
+ const context = store.getSnapshot().context;
352
+ if (
353
+ !session &&
354
+ context.connectionClickStartHandle &&
355
+ !resolveModes(context).some((mode) => mode.id === 'connect')
356
+ ) {
357
+ store.trigger.cancelConnection();
358
+ }
359
+ }
360
+
361
+ function send(event: FlowInputEvent): FlowInputEffects {
362
+ const effects: FlowInputEffects = {
363
+ preventDefault: false,
364
+ stopPropagation: false,
365
+ sessionStarted: false,
366
+ sessionEnded: false,
367
+ handledBy: null,
368
+ };
369
+
370
+ if (
371
+ session &&
372
+ event.kind === 'key.down' &&
373
+ !event.editableTarget &&
374
+ matchesKeyBinding(event, keymap.cancel)
375
+ ) {
376
+ const previous = store.getSnapshot().context;
377
+ const commands = session.handlers.cancel?.(modeContext());
378
+ effects.handledBy = session.modeId;
379
+ effects.sessionEnded = true;
380
+ session = null;
381
+ apply(commands ?? undefined, effects);
382
+ cancelPendingConnection(previous);
383
+ return effects;
384
+ }
385
+
386
+ // Built-in transient state: pan activation key tracking.
387
+ if (event.kind === 'key.down' && !event.editableTarget && matchesKeyBinding(event, keymap.panActivation)) {
388
+ input.panKeyHeld = true;
389
+ input.spaceHeld = true;
390
+ } else if (event.kind === 'key.up' && matchesKeyBinding(event, keymap.panActivation)) {
391
+ input.panKeyHeld = false;
392
+ input.spaceHeld = false;
393
+ }
394
+
395
+ const isPointer =
396
+ event.kind === 'pointer.down' ||
397
+ event.kind === 'pointer.move' ||
398
+ event.kind === 'pointer.up' ||
399
+ event.kind === 'pointer.cancel';
400
+ const isPinch =
401
+ event.kind === 'pinch.start' ||
402
+ event.kind === 'pinch.move' ||
403
+ event.kind === 'pinch.end';
404
+
405
+ if (session && (isPointer || isPinch)) {
406
+ if (isPinch) {
407
+ const result = session.handlers.update(event, modeContext());
408
+ apply(result?.commands, effects);
409
+ effects.handledBy = session.modeId;
410
+ if (result?.status === 'end') {
411
+ session = null;
412
+ effects.sessionEnded = true;
413
+ }
414
+ return effects;
415
+ }
416
+ const pointer = event as FlowPointerInputEvent;
417
+ if (
418
+ session.pointerId === null ||
419
+ pointer.pointerId === session.pointerId
420
+ ) {
421
+ const result = session.handlers.update(event, modeContext());
422
+ apply(result?.commands, effects);
423
+ effects.handledBy = session.modeId;
424
+ if (result?.status === 'end') {
425
+ session = null;
426
+ effects.sessionEnded = true;
427
+ }
428
+ return effects;
429
+ }
430
+ // A second pointer while a session is active: swallow new gestures.
431
+ if (event.kind === 'pointer.down') {
432
+ effects.handledBy = session.modeId;
433
+ return effects;
434
+ }
435
+ return effects;
436
+ }
437
+
438
+ const ctx = modeContext();
439
+ const modes = [...resolveModes(ctx.context)].sort(
440
+ (a, b) => (b.priority ?? 0) - (a.priority ?? 0),
441
+ );
442
+ for (const mode of modes) {
443
+ const reaction = mode.start(event, ctx);
444
+ if (!reaction) continue;
445
+ apply(reaction.commands, effects);
446
+ effects.handledBy = mode.id;
447
+ if (reaction.session) {
448
+ session = {
449
+ handlers: reaction.session,
450
+ modeId: mode.id,
451
+ pointerId: isPointer
452
+ ? (event as FlowPointerInputEvent).pointerId
453
+ : null,
454
+ };
455
+ effects.sessionStarted = true;
456
+ }
457
+ break;
458
+ }
459
+ return effects;
460
+ }
461
+
462
+ function cancelSession(): void {
463
+ const previous = store.getSnapshot().context;
464
+ if (!session) {
465
+ cancelPendingConnection(previous);
466
+ return;
467
+ }
468
+ const effects: FlowInputEffects = {
469
+ preventDefault: false,
470
+ stopPropagation: false,
471
+ sessionStarted: false,
472
+ sessionEnded: true,
473
+ handledBy: session.modeId,
474
+ };
475
+ const commands = session.handlers.cancel?.(modeContext());
476
+ session = null;
477
+ apply(commands ?? undefined, effects);
478
+ cancelPendingConnection(previous);
479
+ }
480
+
481
+ return {
482
+ send,
483
+ reconcileModes,
484
+ cancelSession,
485
+ getActiveSession: () => session?.modeId ?? null,
486
+ };
487
+ }
488
+
489
+ // Re-exported here to keep `defaultModesForContext` colocated with the
490
+ // runtime while mode implementations live in ./modes.
491
+ import {
492
+ defaultInputModes,
493
+ defaultInputModesForKeymap,
494
+ readonlyInputModes,
495
+ readonlyInputModesForKeymap,
496
+ } from './modes';
497
+ import type { FlowPolicies, FlowProfile } from '../profile';
498
+ import { calcAutoPan } from '../spatial';
499
+
500
+ /** Default mode resolution: follow the store's `context.mode`. */
501
+ export function defaultModesForContext(
502
+ context: FlowStoreContext,
503
+ keymap?: Partial<FlowKeymap>,
504
+ ): FlowInputMode[] {
505
+ if (keymap) {
506
+ return context.mode === 'readonly'
507
+ ? readonlyInputModesForKeymap(keymap)
508
+ : defaultInputModesForKeymap(keymap);
509
+ }
510
+ return context.mode === 'readonly' ? readonlyInputModes : defaultInputModes;
511
+ }
512
+
513
+ /**
514
+ * Mode resolution driven by a store profile: the active store mode's
515
+ * `input.modes` wins, then the profile-level `input.modes`, then the
516
+ * built-in defaults.
517
+ */
518
+ export function profileModesForContext(
519
+ profile: FlowProfile,
520
+ ): (context: FlowStoreContext) => FlowInputMode[] {
521
+ return (context) => {
522
+ const mode = profile.modes[context.mode]
523
+ ? context.mode
524
+ : profile.defaultMode;
525
+ return (
526
+ profile.modes[mode]?.input?.modes ??
527
+ profile.input?.modes ??
528
+ defaultModesForContext(context)
529
+ );
530
+ };
531
+ }
532
+
533
+ export function profilePoliciesForContext(
534
+ profile: FlowProfile,
535
+ ): (context: FlowStoreContext) => FlowPolicies {
536
+ return (context) => {
537
+ const mode = profile.modes[context.mode]
538
+ ? context.mode
539
+ : profile.defaultMode;
540
+ return {
541
+ ...profile.policies,
542
+ ...profile.modes[mode]?.policies,
543
+ };
544
+ };
545
+ }
546
+
547
+ /**
548
+ * Per-frame, pointer-driven auto-pan step while a drag, connection, or resize
549
+ * gesture is near the container edge. Returns the `calcAutoPan` screen-space
550
+ * delta (negate it for `panBy`), or null when auto-pan should not run. Adapters
551
+ * call this from a frame ticker while a gesture session is active and re-send
552
+ * the stationary pointer afterwards so the dragged entity follows the panned
553
+ * canvas.
554
+ */
555
+ export function getAutoPanDelta(
556
+ context: FlowStoreContext,
557
+ screenPoint: Point,
558
+ /**
559
+ * Retained for source compatibility. Auto-pan is intentionally driven by the
560
+ * pointer position, not by resolved entity bounds.
561
+ */
562
+ engine?: FlowEngine,
563
+ ): Point | null {
564
+ if (!context.autoPanOnDrag) return null;
565
+ if (
566
+ context.canvasState !== 'dragging' &&
567
+ context.canvasState !== 'connecting' &&
568
+ context.canvasState !== 'resizing'
569
+ ) {
570
+ return null;
571
+ }
572
+ const size = context.viewportSize;
573
+ if (size.width === 0 || size.height === 0) return null;
574
+ const delta = calcAutoPan(
575
+ screenPoint,
576
+ size,
577
+ context.autoPanThreshold,
578
+ context.autoPanSpeed,
579
+ );
580
+ if (delta.x === 0 && delta.y === 0) return null;
581
+
582
+ // Keep this policy pointer-driven. The pointer remains at the edge while the
583
+ // canvas pans, so every animation frame must continue returning a delta even
584
+ // when entity bounds are clamped or temporarily lag behind the gesture.
585
+ void engine;
586
+ return delta;
587
+ }
588
+
589
+ export {
590
+ defaultInputModes,
591
+ defaultInputModesForKeymap,
592
+ readonlyInputModes,
593
+ readonlyInputModesForKeymap,
594
+ keyboardMode,
595
+ keyboardNavMode,
596
+ doubleClickZoomMode,
597
+ wheelMode,
598
+ pinchMode,
599
+ panMode,
600
+ connectMode,
601
+ portPressMode,
602
+ reconnectMode,
603
+ entityPressMode,
604
+ boxSelectMode,
605
+ panePressMode,
606
+ hoverMode,
607
+ } from './modes';
608
+ export type {
609
+ ConnectModeOptions,
610
+ ReconnectModeOptions,
611
+ BoxSelectModeOptions,
612
+ ReparentDecision,
613
+ ReparentDropContext,
614
+ ReparentOptions,
615
+ } from './modes';