@statelyai/flow-dom 3.6.2 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,1062 @@
1
+ export { attachInteractionCursor } from './interaction-cursor';
2
+ export { observeAppearanceBounds } from "./appearance-bounds";
3
+ import type { FlowStore, Point } from '@statelyai/flow';
4
+
5
+ export * from '@statelyai/flow';
6
+ export {
7
+ createFlowClipboard,
8
+ FLOW_CONTENT_MIME,
9
+ type ClipboardTransport,
10
+ type FlowClipboard,
11
+ } from './clipboard';
12
+ export {
13
+ createFlowView,
14
+ exportFlowImage,
15
+ type FlowImageExportOptions,
16
+ type FlowImageExportResult,
17
+ type FlowView,
18
+ } from './exportImage';
19
+
20
+ export {
21
+ computeRenderableIds,
22
+ computeSettledRenderableIds,
23
+ renderableIdsEqual,
24
+ type ComputeRenderableIdsOptions,
25
+ type RenderableIds,
26
+ type SettledRenderableIds,
27
+ } from './culling';
28
+
29
+ export {
30
+ nodePositionStyle,
31
+ viewportStyle,
32
+ type NodePositionStyle,
33
+ type ViewportStyle,
34
+ } from './render-styles';
35
+
36
+ export {
37
+ createEntityGeometryObserver,
38
+ type EntityBoundsTarget,
39
+ type EntityEdgeTarget,
40
+ type EntityGeometryObserver,
41
+ type EntityGeometryObserverOptions,
42
+ type EntityRectTarget,
43
+ } from './entity-geometry';
44
+
45
+ export {
46
+ resolveFlowColorMode,
47
+ applyFlowColorMode,
48
+ observeFlowColorMode,
49
+ type ResolvedFlowColorMode,
50
+ } from './color-mode';
51
+
52
+ export type MeasurementTarget =
53
+ | { appearanceId: string; relativeTo: Element }
54
+ | { nodeId: string }
55
+ | { nodeId: string; portName: string }
56
+ | { edgeId: string };
57
+
58
+ export type MeasurementObserver = {
59
+ observe(element: Element, target: MeasurementTarget): void;
60
+ /** Re-measure now (position-only changes don't fire ResizeObserver). */
61
+ measure(element: Element): void;
62
+ refresh(targets?: Iterable<string | Element>): void;
63
+ unobserve(element: Element): void;
64
+ disconnect(): void;
65
+ };
66
+
67
+ export type MeasurementObserverOptions = {
68
+ container?: Element | (() => Element | null | undefined) | null;
69
+ equalityThreshold?: number;
70
+ };
71
+
72
+ const containers = new WeakMap<FlowStore, Element>();
73
+
74
+ function hasOwnScale(element: Element): boolean {
75
+ const transform = element.ownerDocument.defaultView
76
+ ?.getComputedStyle(element).transform;
77
+ if (!transform || transform === 'none') return false;
78
+ const values = /^matrix\(([^)]*)\)$/.exec(transform)?.[1].split(',').map(Number);
79
+ if (!values) return true;
80
+ const [a, b, c, d] = values;
81
+ return a !== 1 || b !== 0 || c !== 0 || d !== 1;
82
+ }
83
+
84
+ export function createMeasurementObserver(
85
+ store: FlowStore,
86
+ options: MeasurementObserverOptions = {}
87
+ ): MeasurementObserver {
88
+ const equalityThreshold = options.equalityThreshold ?? 0.5;
89
+ type Registration = {
90
+ target: MeasurementTarget;
91
+ origin?: Point;
92
+ /** The element's last ResizeObserver layout size. */
93
+ layoutSize?: { width: number; height: number };
94
+ };
95
+ const elementMap = new Map<Element, Registration>();
96
+ let pendingMeasurements: Array<{
97
+ element: Element;
98
+ registration: Registration;
99
+ measurement: {
100
+ id: string;
101
+ origin?: Point;
102
+ rect: { x: number; y: number; width: number; height: number };
103
+ };
104
+ }> = [];
105
+ let rafId: number | null = null;
106
+
107
+ function flush() {
108
+ rafId = null;
109
+
110
+ const measurements = pendingMeasurements
111
+ .filter(({ element, registration }) => elementMap.get(element) === registration)
112
+ .map(({ measurement }) => measurement);
113
+ pendingMeasurements = [];
114
+ if (measurements.length > 0) {
115
+ store.trigger.updateMeasurements({ measurements });
116
+ }
117
+ }
118
+
119
+ function scheduleFlush() {
120
+ if (rafId === null) {
121
+ rafId = requestAnimationFrame(flush);
122
+ }
123
+ }
124
+
125
+ function pushMeasurement(
126
+ element: Element,
127
+ registration: Registration,
128
+ // Layout (border-box) size from a ResizeObserver entry. Preferred for
129
+ // width/height because it is independent of the canvas zoom transform —
130
+ // unlike getBoundingClientRect()/zoom, which races with an in-flight zoom
131
+ // and wrote corrupted sizes back into the graph (the "node resizing" bug).
132
+ layoutSize?: { width: number; height: number }
133
+ ): void {
134
+ const { target } = registration;
135
+ // A re-measure keeps the last observed layout size: only a resize changes
136
+ // it, and ResizeObserver reports every resize.
137
+ if (layoutSize) registration.layoutSize = layoutSize;
138
+ else layoutSize = registration.layoutSize;
139
+ // An element with its own scale (e.g. an inverse-zoom port) renders at a
140
+ // different size than its layout box, so only its screen rect is right.
141
+ if (layoutSize && hasOwnScale(element)) layoutSize = undefined;
142
+ const viewport = store.getSnapshot().context.viewport;
143
+ const zoom = viewport.zoom || 1;
144
+ const rect = element.getBoundingClientRect();
145
+ const containerRect = (
146
+ getContainer(options.container) ?? containers.get(store)
147
+ )?.getBoundingClientRect();
148
+ const relativeRect = "relativeTo" in target ? target.relativeTo.getBoundingClientRect() : undefined;
149
+ const measurement = {
150
+ x: (rect.left - (relativeRect?.left ?? (containerRect?.left ?? 0) + viewport.x)) / zoom,
151
+ y: (rect.top - (relativeRect?.top ?? (containerRect?.top ?? 0) + viewport.y)) / zoom,
152
+ width: layoutSize ? layoutSize.width : rect.width / zoom,
153
+ height: layoutSize ? layoutSize.height : rect.height / zoom,
154
+ };
155
+
156
+ const id =
157
+ 'appearanceId' in target ? target.appearanceId : 'portName' in target
158
+ ? `${target.nodeId}:${target.portName}`
159
+ : 'nodeId' in target
160
+ ? target.nodeId
161
+ : target.edgeId;
162
+
163
+ let origin: Point | undefined;
164
+ if ('portName' in target) {
165
+ for (let owner = element.parentElement; owner; owner = owner.parentElement) {
166
+ if (owner.getAttribute('data-entity-id') !== target.nodeId) continue;
167
+ const bounds = owner.getBoundingClientRect();
168
+ origin = {
169
+ x: (bounds.left - (containerRect?.left ?? 0) - viewport.x) / zoom,
170
+ y: (bounds.top - (containerRect?.top ?? 0) - viewport.y) / zoom,
171
+ };
172
+ break;
173
+ }
174
+ }
175
+ // Idempotence: skip when the store already holds this measurement —
176
+ // keeps repeated re-measures (e.g. per-render port reporting) from
177
+ // producing new store transitions every frame.
178
+ const existing = store.getSnapshot().context.measurements.get(id);
179
+ if (
180
+ existing &&
181
+ origin?.x === registration.origin?.x && origin?.y === registration.origin?.y &&
182
+ Math.abs(existing.x - measurement.x) < equalityThreshold &&
183
+ Math.abs(existing.y - measurement.y) < equalityThreshold &&
184
+ Math.abs(existing.width - measurement.width) < equalityThreshold &&
185
+ Math.abs(existing.height - measurement.height) < equalityThreshold
186
+ ) {
187
+ return;
188
+ }
189
+
190
+ registration.origin = origin;
191
+ pendingMeasurements.push({ element, registration, measurement: {
192
+ id, rect: measurement, ...(origin ? { origin } : {}),
193
+ } });
194
+ scheduleFlush();
195
+ }
196
+
197
+ const handleResize: ResizeObserverCallback = (entries, source) => {
198
+ if (source !== observer) return;
199
+ for (const entry of entries) {
200
+ const registration = elementMap.get(entry.target);
201
+ if (!registration) continue;
202
+ // Border-box size is the zoom-independent layout size; fall back to the
203
+ // content rect, then to getBoundingClientRect()/zoom inside pushMeasurement.
204
+ const box = entry.borderBoxSize?.[0];
205
+ const layoutSize = box
206
+ ? { width: box.inlineSize, height: box.blockSize }
207
+ : entry.contentRect
208
+ ? { width: entry.contentRect.width, height: entry.contentRect.height }
209
+ : undefined;
210
+ pushMeasurement(entry.target, registration, layoutSize);
211
+ }
212
+ };
213
+ let observer: ResizeObserver | null = null;
214
+
215
+ function getObserver(element: Element): ResizeObserver {
216
+ if (observer) return observer;
217
+ const ResizeObserverCtor = element.ownerDocument.defaultView?.ResizeObserver ?? ResizeObserver;
218
+ observer = new ResizeObserverCtor(handleResize);
219
+ return observer;
220
+ }
221
+
222
+ return {
223
+ observe(element: Element, target: MeasurementTarget) {
224
+ const replacing = elementMap.has(element);
225
+ const registration = { target };
226
+ elementMap.set(element, registration);
227
+ // Border-box observation also reports border-only size changes.
228
+ getObserver(element).observe(element, { box: 'border-box' });
229
+ // ResizeObserver need not notify again for an unchanged observed element.
230
+ if (replacing) pushMeasurement(element, registration);
231
+ },
232
+
233
+ /**
234
+ * Re-measure an observed element immediately. ResizeObserver only fires
235
+ * on SIZE changes — position-only changes (layout passes, graph swaps,
236
+ * a port moving within its node) need an explicit re-measure.
237
+ */
238
+ measure(element: Element) {
239
+ const registration = elementMap.get(element);
240
+ if (registration) pushMeasurement(element, registration);
241
+ },
242
+
243
+ refresh(targets) {
244
+ const requested = targets ? new Set(targets) : null;
245
+ for (const [element, registration] of elementMap) {
246
+ const { target } = registration;
247
+ const id =
248
+ 'appearanceId' in target ? target.appearanceId : 'portName' in target
249
+ ? `${target.nodeId}:${target.portName}`
250
+ : 'nodeId' in target
251
+ ? target.nodeId
252
+ : target.edgeId;
253
+ if (requested && !requested.has(element) && !requested.has(id)) continue;
254
+ pushMeasurement(element, registration);
255
+ }
256
+ },
257
+
258
+ unobserve(element: Element) {
259
+ elementMap.delete(element);
260
+ observer?.unobserve(element);
261
+ },
262
+
263
+ disconnect() {
264
+ elementMap.clear();
265
+ observer?.disconnect();
266
+ observer = null;
267
+
268
+ if (rafId !== null) {
269
+ cancelAnimationFrame(rafId);
270
+ rafId = null;
271
+ }
272
+
273
+ pendingMeasurements = [];
274
+ },
275
+ };
276
+ }
277
+
278
+ function getContainer(container: MeasurementObserverOptions['container']): Element | null {
279
+ return typeof container === 'function' ? container() ?? null : container ?? null;
280
+ }
281
+
282
+ /** The container element registered for this store via `attachContainer`. */
283
+ export function getAttachedContainer(store: FlowStore): Element | undefined {
284
+ return containers.get(store);
285
+ }
286
+
287
+ export function clientToCanvas(
288
+ store: FlowStore,
289
+ point: Point,
290
+ container: Element | null | undefined = containers.get(store)
291
+ ): Point {
292
+ const rect = container?.getBoundingClientRect();
293
+ const viewport = store.getSnapshot().context.viewport;
294
+ const zoom = viewport.zoom || 1;
295
+ return {
296
+ x: (point.x - (rect?.left ?? 0) - viewport.x) / zoom,
297
+ y: (point.y - (rect?.top ?? 0) - viewport.y) / zoom,
298
+ };
299
+ }
300
+
301
+ export function canvasToClient(
302
+ store: FlowStore,
303
+ point: Point,
304
+ container: Element | null | undefined = containers.get(store)
305
+ ): Point {
306
+ const rect = container?.getBoundingClientRect();
307
+ const viewport = store.getSnapshot().context.viewport;
308
+ return {
309
+ x: point.x * viewport.zoom + viewport.x + (rect?.left ?? 0),
310
+ y: point.y * viewport.zoom + viewport.y + (rect?.top ?? 0),
311
+ };
312
+ }
313
+
314
+ export function attachContainer(
315
+ store: FlowStore,
316
+ element: Element,
317
+ options: { preserveViewportCenter?: boolean } = {}
318
+ ): () => void {
319
+ containers.set(store, element);
320
+
321
+ const update = () => {
322
+ const rect = element.getBoundingClientRect();
323
+
324
+ if (rect.width > 0 && rect.height > 0) {
325
+ store.trigger.updateViewportSize({
326
+ width: rect.width,
327
+ height: rect.height,
328
+ preserveCenter: options.preserveViewportCenter,
329
+ });
330
+ }
331
+ };
332
+
333
+ // Browsers can scroll overflow:hidden containers to reveal focused inputs.
334
+ // Keep that reveal, but express it in the viewport so backgrounds, overlays,
335
+ // and client/canvas coordinate conversion stay aligned with the graph.
336
+ const onScroll = (event: Event) => {
337
+ if (event.target !== element) return;
338
+ const { scrollLeft, scrollTop } = element;
339
+ if (!scrollLeft && !scrollTop) return;
340
+ element.scrollLeft = 0;
341
+ element.scrollTop = 0;
342
+ store.trigger.panBy({ x: -scrollLeft, y: -scrollTop });
343
+ };
344
+ element.addEventListener('scroll', onScroll);
345
+
346
+ update();
347
+
348
+ const ResizeObserverCtor = element.ownerDocument.defaultView?.ResizeObserver ?? ResizeObserver;
349
+ const observer = new ResizeObserverCtor(update);
350
+ observer.observe(element);
351
+
352
+ return () => {
353
+ if (containers.get(store) === element) {
354
+ containers.delete(store);
355
+ }
356
+
357
+ element.removeEventListener('scroll', onScroll);
358
+ observer.disconnect();
359
+ };
360
+ }
361
+
362
+ // Viewport transform (framework-agnostic "source of rendering truth" for pan/zoom)
363
+ //
364
+ // Drives one canvas element's pan/zoom transform imperatively from the store —
365
+ // NOT through a framework's reactive style binding, which would re-render every
366
+ // node on every frame. It also GPU-promotes the element (`will-change:
367
+ // transform`) for the duration of any active interaction (dragging/panning/
368
+ // resizing/...), so the thousands of static nodes/edges inside are rasterized
369
+ // once and the GPU just slides the layer instead of repainting it each frame;
370
+ // the hint is dropped shortly after activity stops so layer memory isn't held
371
+ // at idle. Framework adapters should mount a single transformed viewport element
372
+ // (with all node/edge layers as static children) and hand it here. See
373
+ // ADAPTER_NOTES.md for the full set of rules a performant DOM adapter must follow.
374
+
375
+ export type ViewportTransformOptions = {
376
+ /** Idle delay (ms) before dropping the GPU-layer hint after interaction stops. */
377
+ promoteIdleMs?: number;
378
+ /**
379
+ * The zoom written to `--flow-zoom` and `--flow-inverse-zoom`, when it
380
+ * should differ from the live zoom. Every element below the viewport
381
+ * inherits these variables, so changing them restyles the whole canvas.
382
+ * Returning a settled zoom during a zoom gesture keeps each frame to a
383
+ * transform change. Defaults to the live zoom.
384
+ */
385
+ getVariableZoom?: () => number | undefined;
386
+ };
387
+
388
+ /**
389
+ * Write `--flow-zoom` and `--flow-inverse-zoom`. Every element below inherits
390
+ * them, so a change restyles the whole canvas; an unchanged value is skipped.
391
+ */
392
+ export function writeZoomVariables(element: HTMLElement, zoom: number): void {
393
+ const value = String(zoom);
394
+ if (element.style.getPropertyValue('--flow-zoom') === value) return;
395
+ element.style.setProperty('--flow-zoom', value);
396
+ element.style.setProperty('--flow-inverse-zoom', String(1 / zoom));
397
+ }
398
+
399
+ export function attachViewportTransform(
400
+ store: FlowStore,
401
+ element: HTMLElement,
402
+ options: ViewportTransformOptions = {}
403
+ ): () => void {
404
+ const promoteIdleMs = options.promoteIdleMs ?? 200;
405
+ let prevViewport = store.getSnapshot().context.viewport;
406
+ let prevState = store.getSnapshot().context.canvasState;
407
+ let idle: ReturnType<typeof setTimeout> | undefined;
408
+
409
+ const writeTransform = (viewport: { x: number; y: number; zoom: number }): void => {
410
+ element.style.transform = `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`;
411
+ // Expose zoom to CSS so descendants can keep on-screen sizes constant
412
+ // (e.g. selection outlines via `calc(1px / var(--flow-zoom))`).
413
+ writeZoomVariables(element, options.getVariableZoom?.() ?? viewport.zoom);
414
+ };
415
+ const promote = (): void => {
416
+ element.style.willChange = 'transform';
417
+ if (idle !== undefined) clearTimeout(idle);
418
+ };
419
+ const scheduleClear = (): void => {
420
+ if (idle !== undefined) clearTimeout(idle);
421
+ idle = setTimeout(() => {
422
+ element.style.willChange = 'auto';
423
+ }, promoteIdleMs);
424
+ };
425
+
426
+ writeTransform(prevViewport);
427
+ if (prevState === 'panning') promote();
428
+
429
+ const subscription = store.subscribe((snapshot) => {
430
+ const context = snapshot.context;
431
+ if (context.viewport !== prevViewport) {
432
+ prevViewport = context.viewport;
433
+ writeTransform(context.viewport);
434
+ // Wheel-zoom changes the viewport without entering a non-idle state.
435
+ promote();
436
+ if (context.canvasState !== 'panning') scheduleClear();
437
+ }
438
+ if (context.canvasState !== prevState) {
439
+ prevState = context.canvasState;
440
+ if (prevState === 'panning') promote();
441
+ else scheduleClear();
442
+ }
443
+ });
444
+
445
+ return () => {
446
+ if (idle !== undefined) clearTimeout(idle);
447
+ subscription.unsubscribe();
448
+ };
449
+ }
450
+
451
+ // Input binding (DOM → FlowInputRuntime)
452
+ //
453
+ // Normalizes browser pointer/wheel/keyboard events into FlowInputEvents and
454
+ // feeds them to a core input runtime (`createFlowInputRuntime` from
455
+ // @statelyai/flow). Target detection uses the data attributes that flow
456
+ // renderers set explicitly (`data-entity-id`, `data-flow-edge-label`,
457
+ // `data-flow-port-name`, `data-flow-canvas-layer`) — no magic class names.
458
+ //
459
+ // Only type imports from @statelyai/flow are used here so the peer stays
460
+ // optional for consumers that only need the measurement/color helpers.
461
+
462
+ import type {
463
+ FlowInputEffects,
464
+ FlowInputEvent,
465
+ FlowInputModifiers,
466
+ FlowInputTarget,
467
+ } from '@statelyai/flow';
468
+
469
+ type FlowPoint = { x: number; y: number };
470
+
471
+ export type AttachInputOptions = {
472
+ container: HTMLElement;
473
+ store: FlowStore;
474
+ runtime: {
475
+ send(event: FlowInputEvent): FlowInputEffects;
476
+ cancelSession(): void;
477
+ getActiveSession?(): string | null;
478
+ };
479
+ /**
480
+ * Where keyboard events are listened for. Defaults to the flow container so
481
+ * multiple flow instances do not all react to global Delete/undo/arrow keys.
482
+ */
483
+ keyboardTarget?: 'window' | 'container' | HTMLElement;
484
+ /**
485
+ * Auto-pan policy, evaluated once per animation frame while a gesture
486
+ * session holds the pointer near the container edge. Pass
487
+ * `getAutoPanDelta` from @statelyai/flow (injected as a function so this
488
+ * package keeps no runtime dependency on the optional peer). When it
489
+ * returns a delta, the binder pans the viewport and re-sends the
490
+ * stationary pointer so the dragged entity follows the canvas.
491
+ */
492
+ autoPan?: (
493
+ context: ReturnType<FlowStore['getSnapshot']>['context'],
494
+ screenPoint: { x: number; y: number }
495
+ ) => { x: number; y: number } | null;
496
+ };
497
+
498
+ export function attachInput(options: AttachInputOptions): () => void {
499
+ const { container, store, runtime } = options;
500
+ const doc = container.ownerDocument;
501
+ const win = doc.defaultView;
502
+ const ElementCtor = win?.Element;
503
+ const HTMLElementCtor = win?.HTMLElement;
504
+ const keyboardTarget = options.keyboardTarget ?? 'container';
505
+ const keyboardElement =
506
+ keyboardTarget === 'window' ? win : keyboardTarget === 'container' ? container : keyboardTarget;
507
+ let capturedPointerId: number | null = null;
508
+ let pointerCaptureOwner = {};
509
+ let gestureContainerOffset: { left: number; top: number } | null = null;
510
+ let lastContainerOffset: { left: number; top: number } | null = null;
511
+ let lastClient: {
512
+ x: number;
513
+ y: number;
514
+ pointerId: number;
515
+ modifiers: FlowInputModifiers;
516
+ } | null = null;
517
+ let autoPanFrame: number | null = null;
518
+ const activeTouchPointers = new Map<
519
+ number,
520
+ {
521
+ clientX: number;
522
+ clientY: number;
523
+ modifiers: FlowInputModifiers;
524
+ }
525
+ >();
526
+ let pinchActive = false;
527
+ // Native PointerEvent.detail is unreliable for click counting: most browsers
528
+ // leave `detail` as 0 on `pointerdown` (the click-count only lands on the
529
+ // compatibility mouse events / `click` / `dblclick`). doubleClickZoomMode
530
+ // gates on `detail >= 2`, so we derive the click count ourselves — mirroring
531
+ // how a browser increments MouseEvent.detail — for mouse/pen pointerdowns.
532
+ const DOUBLE_CLICK_MS = 500;
533
+ const DOUBLE_CLICK_DISTANCE = 4;
534
+ let lastClickDown: { time: number; x: number; y: number } | null = null;
535
+ let clickCount = 0;
536
+ let lastPinch: {
537
+ screenCenter: FlowPoint;
538
+ center: FlowPoint;
539
+ distance: number;
540
+ modifiers: FlowInputModifiers;
541
+ } | null = null;
542
+
543
+ function stopAutoPan(): void {
544
+ if (autoPanFrame !== null) {
545
+ win?.cancelAnimationFrame(autoPanFrame);
546
+ autoPanFrame = null;
547
+ }
548
+ }
549
+
550
+ function autoPanTick(): void {
551
+ autoPanFrame = null;
552
+ if (!options.autoPan || capturedPointerId === null || !lastClient) {
553
+ return;
554
+ }
555
+ const rect = gestureContainerOffset ?? container.getBoundingClientRect();
556
+ const screenPoint = {
557
+ x: lastClient.x - rect.left,
558
+ y: lastClient.y - rect.top,
559
+ };
560
+ const delta = options.autoPan(store.getSnapshot().context, screenPoint);
561
+ if (delta) {
562
+ store.trigger.panBy({ x: -delta.x, y: -delta.y });
563
+ // Re-send the stationary pointer through the runtime: the canvas moved
564
+ // under it, so the active session sees the new canvas position.
565
+ sendPointer('pointer.move', lastClient.x, lastClient.y, {
566
+ pointerId: lastClient.pointerId,
567
+ button: -1,
568
+ modifiers: lastClient.modifiers,
569
+ target: null,
570
+ });
571
+ }
572
+ scheduleAutoPan();
573
+ }
574
+
575
+ function scheduleAutoPan(): void {
576
+ if (options.autoPan && autoPanFrame === null && win) {
577
+ autoPanFrame = win.requestAnimationFrame(autoPanTick);
578
+ }
579
+ }
580
+
581
+ function modifiers(event: {
582
+ shiftKey: boolean;
583
+ metaKey: boolean;
584
+ ctrlKey: boolean;
585
+ altKey: boolean;
586
+ }): FlowInputModifiers {
587
+ return {
588
+ shift: event.shiftKey,
589
+ meta: event.metaKey,
590
+ ctrl: event.ctrlKey,
591
+ alt: event.altKey,
592
+ };
593
+ }
594
+
595
+ // Derive the click count for a mouse/pen pointerdown. Native
596
+ // PointerEvent.detail can't be trusted here (see clickCount declaration), so
597
+ // we count downs that land close together in time and space, resetting
598
+ // otherwise — matching browser MouseEvent.detail semantics.
599
+ function computeClickDetail(event: PointerEvent): number {
600
+ if (event.pointerType === 'touch') return event.detail || 0;
601
+ const now = event.timeStamp || (win ? win.performance.now() : Date.now());
602
+ if (
603
+ lastClickDown &&
604
+ now - lastClickDown.time <= DOUBLE_CLICK_MS &&
605
+ Math.abs(event.clientX - lastClickDown.x) <= DOUBLE_CLICK_DISTANCE &&
606
+ Math.abs(event.clientY - lastClickDown.y) <= DOUBLE_CLICK_DISTANCE
607
+ ) {
608
+ clickCount += 1;
609
+ } else {
610
+ clickCount = 1;
611
+ }
612
+ lastClickDown = { time: now, x: event.clientX, y: event.clientY };
613
+ return clickCount;
614
+ }
615
+
616
+ function toPoints(event: { clientX: number; clientY: number }): {
617
+ screenPoint: FlowPoint;
618
+ point: FlowPoint;
619
+ } {
620
+ const rect = gestureContainerOffset ?? container.getBoundingClientRect();
621
+ lastContainerOffset = { left: rect.left, top: rect.top };
622
+ if (capturedPointerId !== null && gestureContainerOffset === null) {
623
+ gestureContainerOffset = lastContainerOffset;
624
+ }
625
+ const screenPoint = {
626
+ x: event.clientX - rect.left,
627
+ y: event.clientY - rect.top,
628
+ };
629
+ const { viewport } = store.getSnapshot().context;
630
+ const zoom = viewport.zoom || 1;
631
+ return {
632
+ screenPoint,
633
+ point: {
634
+ x: (screenPoint.x - viewport.x) / zoom,
635
+ y: (screenPoint.y - viewport.y) / zoom,
636
+ },
637
+ };
638
+ }
639
+
640
+ function resolveTarget(event: {
641
+ clientX: number;
642
+ clientY: number;
643
+ target: EventTarget | null;
644
+ }): FlowInputTarget {
645
+ // While the container holds pointer capture, event.target is the capture
646
+ // element — hit-test the document instead so drags see what is under the
647
+ // pointer.
648
+ const element =
649
+ capturedPointerId !== null
650
+ ? doc.elementFromPoint(event.clientX, event.clientY)
651
+ : ElementCtor && event.target instanceof ElementCtor
652
+ ? event.target
653
+ : null;
654
+ if (!element) return { kind: 'none' };
655
+ if (!container.contains(element)) return { kind: 'none' };
656
+ const owningRoot = element.closest('[data-flow-root]');
657
+ if (owningRoot && owningRoot !== container) return { kind: 'none' };
658
+
659
+ const portElement = element.closest<HTMLElement>('[data-flow-port-name]');
660
+ if (portElement?.dataset.flowPortName) {
661
+ return {
662
+ kind: 'port',
663
+ nodeId: portElement.dataset.flowNodeId ?? '',
664
+ portName: portElement.dataset.flowPortName,
665
+ portId: portElement.dataset.flowPortId,
666
+ interaction:
667
+ portElement.dataset.flowPortInteraction === "inspect"
668
+ ? "inspect"
669
+ : "connect",
670
+ };
671
+ }
672
+
673
+ // Opt-out for custom interactive content inside entities (resize
674
+ // handles, buttons, inputs, control points): presses inside a
675
+ // [data-flow-interactive] subtree are invisible to gesture modes, so
676
+ // the element's own pointer handlers run unopposed.
677
+ if (
678
+ element.closest(
679
+ '[data-flow-interactive], .nodrag, input, textarea, select, button, a[href], [contenteditable]:not([contenteditable="false"])'
680
+ )
681
+ ) {
682
+ return { kind: 'none' };
683
+ }
684
+ const entityElement = element.closest<HTMLElement>('[data-entity-id]');
685
+ if (entityElement?.dataset.entityId) {
686
+ const isLabel = element.closest('[data-flow-edge-label]') !== null;
687
+ const partElement = element.closest<HTMLElement>('[data-flow-part]');
688
+ const part = partElement?.dataset.flowPart ?? (isLabel ? 'label' : undefined);
689
+ const entityHasDragHandle = entityElement.querySelector('[data-flow-drag-handle]') !== null;
690
+ const pressedDragHandle =
691
+ entityHasDragHandle && element.closest('[data-flow-drag-handle]') !== null;
692
+ return {
693
+ kind: 'entity',
694
+ id: entityElement.dataset.entityId,
695
+ ...(part ? { part } : {}),
696
+ ...(entityHasDragHandle ? { entityHasDragHandle, pressedDragHandle } : {}),
697
+ } as FlowInputTarget;
698
+ }
699
+
700
+ if (element === container || element.closest('[data-flow-canvas-layer]') !== null) {
701
+ return { kind: 'pane' };
702
+ }
703
+
704
+ return { kind: 'none' };
705
+ }
706
+
707
+ function applyEffects(event: Event, effects: FlowInputEffects): void {
708
+ if (effects.preventDefault) event.preventDefault();
709
+ if (effects.stopPropagation) event.stopPropagation();
710
+ }
711
+
712
+ function sendPointer(
713
+ kind: 'pointer.down' | 'pointer.move' | 'pointer.up' | 'pointer.cancel',
714
+ clientX: number,
715
+ clientY: number,
716
+ info: {
717
+ pointerId: number;
718
+ pointerType?: 'mouse' | 'pen' | 'touch';
719
+ button: number;
720
+ detail?: number;
721
+ modifiers: FlowInputModifiers;
722
+ /** Pass null to hit-test via elementFromPoint (synthetic re-sends). */
723
+ target: EventTarget | null;
724
+ }
725
+ ): FlowInputEffects {
726
+ const { screenPoint, point } = toPoints({ clientX, clientY });
727
+ const activeSession = runtime.getActiveSession?.() ?? null;
728
+ const targetIndependentSession =
729
+ activeSession === 'entity-press' ||
730
+ activeSession === 'pan' ||
731
+ activeSession === 'pane-press' ||
732
+ activeSession === 'box-select';
733
+ const effects = runtime.send({
734
+ kind,
735
+ pointerId: info.pointerId,
736
+ pointerType: info.pointerType ?? 'mouse',
737
+ button: info.button,
738
+ detail: info.detail,
739
+ point,
740
+ screenPoint,
741
+ // Built-in drag/pan/select sessions use pointer geometry only. Avoid a
742
+ // document hit test on every captured move; connection/reconnect and
743
+ // custom sessions still receive exact targets.
744
+ target:
745
+ kind === 'pointer.move' && targetIndependentSession
746
+ ? { kind: 'none' }
747
+ : resolveTarget({ clientX, clientY, target: info.target }),
748
+ modifiers: info.modifiers,
749
+ } as unknown as FlowInputEvent);
750
+
751
+ if (effects.sessionStarted && kind === 'pointer.down') {
752
+ try {
753
+ container.setPointerCapture(info.pointerId);
754
+ } catch {
755
+ // Inactive pointer (e.g. synthetic events) — capture is best-effort.
756
+ }
757
+ capturedPointerId = info.pointerId;
758
+ pointerCaptureOwner = {};
759
+ // Container geometry is stable for one captured gesture. Reusing the
760
+ // pointer-down offset avoids a forced layout read on every move.
761
+ gestureContainerOffset =
762
+ lastContainerOffset ?? (() => {
763
+ const rect = container.getBoundingClientRect();
764
+ return { left: rect.left, top: rect.top };
765
+ })();
766
+ scheduleAutoPan();
767
+ }
768
+ if (effects.sessionEnded && capturedPointerId !== null) {
769
+ releaseCapturedPointer();
770
+ }
771
+ return effects;
772
+ }
773
+
774
+ function touchPoints() {
775
+ return [...activeTouchPointers.values()];
776
+ }
777
+
778
+ function pinchGeometry(): {
779
+ screenCenter: FlowPoint;
780
+ center: FlowPoint;
781
+ distance: number;
782
+ modifiers: FlowInputModifiers;
783
+ } | null {
784
+ const touches = touchPoints();
785
+ if (touches.length < 2) return null;
786
+ const [a, b] = touches;
787
+ const screenCenter = {
788
+ x: (a.clientX + b.clientX) / 2 - container.getBoundingClientRect().left,
789
+ y: (a.clientY + b.clientY) / 2 - container.getBoundingClientRect().top,
790
+ };
791
+ const { point: center } = toPoints({
792
+ clientX: (a.clientX + b.clientX) / 2,
793
+ clientY: (a.clientY + b.clientY) / 2,
794
+ });
795
+ return {
796
+ screenCenter,
797
+ center,
798
+ distance: Math.hypot(b.clientX - a.clientX, b.clientY - a.clientY),
799
+ modifiers: a.modifiers,
800
+ };
801
+ }
802
+
803
+ function sendPinch(kind: 'pinch.start' | 'pinch.move' | 'pinch.end'): FlowInputEffects {
804
+ const geometry = kind === 'pinch.end' ? lastPinch : pinchGeometry();
805
+ const fallback = geometry ?? lastPinch;
806
+ if (!fallback) return makeNoEffects();
807
+ lastPinch = fallback;
808
+ return runtime.send({
809
+ kind,
810
+ center: fallback.center,
811
+ screenCenter: fallback.screenCenter,
812
+ distance: fallback.distance,
813
+ pointerCount: activeTouchPointers.size,
814
+ modifiers: fallback.modifiers,
815
+ } as unknown as FlowInputEvent);
816
+ }
817
+
818
+ function makeNoEffects(): FlowInputEffects {
819
+ return {
820
+ preventDefault: false,
821
+ stopPropagation: false,
822
+ sessionStarted: false,
823
+ sessionEnded: false,
824
+ handledBy: null,
825
+ };
826
+ }
827
+
828
+ function releaseCapturedPointer(): void {
829
+ if (capturedPointerId === null) return;
830
+ const pointerId = capturedPointerId;
831
+ capturedPointerId = null;
832
+ try {
833
+ if (container.hasPointerCapture(pointerId)) {
834
+ container.releasePointerCapture(pointerId);
835
+ }
836
+ } catch {
837
+ // Already released.
838
+ }
839
+ gestureContainerOffset = null;
840
+ lastClient = null;
841
+ stopAutoPan();
842
+ }
843
+
844
+ function handlePointer(kind: 'pointer.down' | 'pointer.move' | 'pointer.up' | 'pointer.cancel') {
845
+ return (event: PointerEvent) => {
846
+ if (kind === 'pointer.down') {
847
+ focusContainerForPanePress(event);
848
+ }
849
+ const pointerType =
850
+ event.pointerType === 'touch' ||
851
+ event.pointerType === 'pen' ||
852
+ event.pointerType === 'mouse'
853
+ ? event.pointerType
854
+ : 'mouse';
855
+ if (pointerType === 'touch') {
856
+ if (kind === 'pointer.down') {
857
+ activeTouchPointers.set(event.pointerId, {
858
+ clientX: event.clientX,
859
+ clientY: event.clientY,
860
+ modifiers: modifiers(event),
861
+ });
862
+ if (activeTouchPointers.size === 2) {
863
+ runtime.cancelSession();
864
+ releaseCapturedPointer();
865
+ pinchActive = true;
866
+ lastPinch = pinchGeometry();
867
+ const effects = sendPinch('pinch.start');
868
+ applyEffects(event, effects);
869
+ return;
870
+ }
871
+ if (activeTouchPointers.size > 2) {
872
+ applyEffects(event, sendPinch('pinch.move'));
873
+ return;
874
+ }
875
+ } else if (activeTouchPointers.has(event.pointerId)) {
876
+ if (kind === 'pointer.move') {
877
+ activeTouchPointers.set(event.pointerId, {
878
+ clientX: event.clientX,
879
+ clientY: event.clientY,
880
+ modifiers: modifiers(event),
881
+ });
882
+ if (pinchActive) {
883
+ const effects = sendPinch('pinch.move');
884
+ applyEffects(event, effects);
885
+ return;
886
+ }
887
+ } else if (kind === 'pointer.up' || kind === 'pointer.cancel') {
888
+ activeTouchPointers.delete(event.pointerId);
889
+ if (pinchActive) {
890
+ const effects = sendPinch('pinch.end');
891
+ pinchActive = false;
892
+ lastPinch = null;
893
+ applyEffects(event, effects);
894
+ return;
895
+ }
896
+ }
897
+ }
898
+ }
899
+
900
+ if (
901
+ kind === 'pointer.down' ||
902
+ (capturedPointerId !== null && event.pointerId === capturedPointerId)
903
+ ) {
904
+ lastClient = {
905
+ x: event.clientX,
906
+ y: event.clientY,
907
+ pointerId: event.pointerId,
908
+ modifiers: modifiers(event),
909
+ };
910
+ }
911
+ // Only left-button pointerdowns carry a derived click count; native
912
+ // detail is unreliable on pointer events, so we compute it here.
913
+ const detail =
914
+ kind === 'pointer.down' && event.button === 0 ? computeClickDetail(event) : event.detail;
915
+ const effects = sendPointer(kind, event.clientX, event.clientY, {
916
+ pointerId: event.pointerId,
917
+ pointerType,
918
+ button: event.button,
919
+ detail,
920
+ modifiers: modifiers(event),
921
+ target: event.target,
922
+ });
923
+ applyEffects(event, effects);
924
+ };
925
+ }
926
+
927
+ function handleWheel(event: WheelEvent): void {
928
+ const { screenPoint, point } = toPoints(event);
929
+ const effects = runtime.send({
930
+ kind: 'wheel',
931
+ deltaX: event.deltaX,
932
+ deltaY: event.deltaY,
933
+ deltaMode: event.deltaMode,
934
+ point,
935
+ screenPoint,
936
+ target: resolveTarget(event),
937
+ modifiers: modifiers(event),
938
+ });
939
+ applyEffects(event, effects);
940
+ }
941
+
942
+ function handleContextMenu(event: MouseEvent): void {
943
+ const effects = sendPointer('pointer.down', event.clientX, event.clientY, {
944
+ pointerId: -1,
945
+ pointerType: 'mouse',
946
+ button: 2,
947
+ detail: event.detail,
948
+ modifiers: modifiers(event),
949
+ target: event.target,
950
+ });
951
+ applyEffects(event, effects);
952
+ }
953
+
954
+ function isEditableTarget(target: EventTarget | null): boolean {
955
+ if (!HTMLElementCtor || !(target instanceof HTMLElementCtor)) return false;
956
+ return (
957
+ target.isContentEditable ||
958
+ target.matches("input, textarea, select, [contenteditable='true']")
959
+ );
960
+ }
961
+
962
+ function isInteractiveTarget(target: EventTarget | null): boolean {
963
+ return (
964
+ !!ElementCtor &&
965
+ target instanceof ElementCtor &&
966
+ target.closest('[data-flow-interactive]') !== null
967
+ );
968
+ }
969
+
970
+ function focusContainerForPanePress(event: PointerEvent): void {
971
+ if (keyboardTarget !== 'container') return;
972
+ if (isEditableTarget(event.target) || isInteractiveTarget(event.target)) return;
973
+ if (
974
+ resolveTarget({
975
+ clientX: event.clientX,
976
+ clientY: event.clientY,
977
+ target: event.target,
978
+ }).kind !== 'pane'
979
+ )
980
+ return;
981
+ container.focus({ preventScroll: true });
982
+ }
983
+
984
+ function handleKey(kind: 'key.down' | 'key.up') {
985
+ return (event: KeyboardEvent) => {
986
+ const previousCaptureOwner = pointerCaptureOwner;
987
+ const effects = runtime.send({
988
+ kind,
989
+ key: event.key,
990
+ editableTarget: isEditableTarget(event.target),
991
+ modifiers: modifiers(event),
992
+ });
993
+ if (effects.sessionEnded && pointerCaptureOwner === previousCaptureOwner) {
994
+ releaseCapturedPointer();
995
+ }
996
+ applyEffects(event, effects);
997
+ };
998
+ }
999
+
1000
+ const onPointerDown = handlePointer('pointer.down');
1001
+ const onPointerMove = handlePointer('pointer.move');
1002
+ const onPointerUp = handlePointer('pointer.up');
1003
+ const onPointerCancel = handlePointer('pointer.cancel');
1004
+ const onLostPointerCapture = (event: PointerEvent) => {
1005
+ if (capturedPointerId === null || capturedPointerId !== event.pointerId) return;
1006
+ stopAutoPan();
1007
+ runtime.cancelSession();
1008
+ capturedPointerId = null;
1009
+ gestureContainerOffset = null;
1010
+ lastClient = null;
1011
+ };
1012
+ const onWindowBlur = () => {
1013
+ stopAutoPan();
1014
+ runtime.cancelSession();
1015
+ activeTouchPointers.clear();
1016
+ capturedPointerId = null;
1017
+ gestureContainerOffset = null;
1018
+ lastClient = null;
1019
+ };
1020
+ const onContainerGeometryChange = () => {
1021
+ gestureContainerOffset = null;
1022
+ lastContainerOffset = null;
1023
+ };
1024
+ const onKeyDown = handleKey('key.down') as EventListener;
1025
+ const onKeyUp = handleKey('key.up') as EventListener;
1026
+
1027
+ if (keyboardTarget === 'container' && !container.hasAttribute('tabindex')) {
1028
+ container.tabIndex = 0;
1029
+ }
1030
+ container.addEventListener('pointerdown', onPointerDown);
1031
+ container.addEventListener('pointermove', onPointerMove);
1032
+ container.addEventListener('pointerup', onPointerUp);
1033
+ container.addEventListener('pointercancel', onPointerCancel);
1034
+ container.addEventListener('lostpointercapture', onLostPointerCapture);
1035
+ container.addEventListener('contextmenu', handleContextMenu);
1036
+ container.addEventListener('wheel', handleWheel, { passive: false });
1037
+ keyboardElement?.addEventListener('keydown', onKeyDown);
1038
+ keyboardElement?.addEventListener('keyup', onKeyUp);
1039
+ win?.addEventListener('blur', onWindowBlur);
1040
+ win?.addEventListener('resize', onContainerGeometryChange);
1041
+ win?.addEventListener('scroll', onContainerGeometryChange, true);
1042
+
1043
+ return () => {
1044
+ stopAutoPan();
1045
+ runtime.cancelSession();
1046
+ activeTouchPointers.clear();
1047
+ pinchActive = false;
1048
+ lastPinch = null;
1049
+ container.removeEventListener('pointerdown', onPointerDown);
1050
+ container.removeEventListener('pointermove', onPointerMove);
1051
+ container.removeEventListener('pointerup', onPointerUp);
1052
+ container.removeEventListener('pointercancel', onPointerCancel);
1053
+ container.removeEventListener('lostpointercapture', onLostPointerCapture);
1054
+ container.removeEventListener('contextmenu', handleContextMenu);
1055
+ container.removeEventListener('wheel', handleWheel);
1056
+ keyboardElement?.removeEventListener('keydown', onKeyDown);
1057
+ keyboardElement?.removeEventListener('keyup', onKeyUp);
1058
+ win?.removeEventListener('blur', onWindowBlur);
1059
+ win?.removeEventListener('resize', onContainerGeometryChange);
1060
+ win?.removeEventListener('scroll', onContainerGeometryChange, true);
1061
+ };
1062
+ }