@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.
@@ -0,0 +1,705 @@
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import {
3
+ createFlowEngine,
4
+ createFlowInputRuntime,
5
+ createFlowStore,
6
+ createGraph,
7
+ createNode,
8
+ } from '@statelyai/flow';
9
+ import type { FlowInputEffects, FlowInputEvent, FlowPointerInputEvent } from '@statelyai/flow';
10
+ import { attachInput } from './index';
11
+ import type { AttachInputOptions } from './index';
12
+
13
+ // jsdom does not implement PointerEvent — polyfill it with MouseEvent so that
14
+ // `new PointerEvent('pointerdown', ...)` dispatches an event that triggers the
15
+ // container's `pointerdown` listener (the listener type-checks the event name,
16
+ // not the constructor). The polyfill adds `pointerId` to the init dict.
17
+ if (typeof PointerEvent === 'undefined') {
18
+ class PointerEventPolyfill extends MouseEvent {
19
+ pointerId: number;
20
+ pointerType: string;
21
+ constructor(type: string, init: PointerEventInit & MouseEventInit = {}) {
22
+ super(type, init);
23
+ this.pointerId = (init as { pointerId?: number }).pointerId ?? 0;
24
+ this.pointerType = (init as { pointerType?: string }).pointerType ?? 'mouse';
25
+ }
26
+ }
27
+ (globalThis as Record<string, unknown>).PointerEvent = PointerEventPolyfill;
28
+ }
29
+
30
+ function makeEffects(): FlowInputEffects {
31
+ return {
32
+ preventDefault: false,
33
+ stopPropagation: false,
34
+ sessionStarted: false,
35
+ sessionEnded: false,
36
+ handledBy: null,
37
+ };
38
+ }
39
+
40
+ function makeFixture(options: Pick<AttachInputOptions, 'keyboardTarget'> = {}) {
41
+ const container = document.createElement('div');
42
+ document.body.appendChild(container);
43
+ const store = createFlowStore();
44
+ const runtime = {
45
+ send: vi.fn<(event: FlowInputEvent) => FlowInputEffects>(() => makeEffects()),
46
+ cancelSession: vi.fn(),
47
+ };
48
+ const cleanup = attachInput({ container, store, runtime, ...options });
49
+ return { container, store, runtime, cleanup };
50
+ }
51
+
52
+ function makeBoundFlow(id: string, options: Pick<AttachInputOptions, 'keyboardTarget'> = {}) {
53
+ const container = document.createElement('div');
54
+ document.body.appendChild(container);
55
+ const store = createFlowStore(
56
+ createGraph({
57
+ nodes: [createNode({ id, x: 0, y: 0 })],
58
+ edges: [],
59
+ })
60
+ );
61
+ const engine = createFlowEngine(store);
62
+ const runtime = createFlowInputRuntime({ store, engine });
63
+ const cleanup = attachInput({ container, store, runtime, ...options });
64
+ return { container, store, cleanup };
65
+ }
66
+
67
+ /** Return the last event sent to runtime.send, narrowed as a pointer event. */
68
+ function lastPointerEvent(runtime: ReturnType<typeof makeFixture>['runtime']): FlowPointerInputEvent {
69
+ const e = runtime.send.mock.calls.at(-1)?.[0];
70
+ if (!e || e.kind === 'key.down' || e.kind === 'key.up' || e.kind === 'wheel') {
71
+ throw new Error(`Expected a pointer event but got: ${e?.kind}`);
72
+ }
73
+ return e as FlowPointerInputEvent;
74
+ }
75
+
76
+ function pointerDown(target: Element, options?: PointerEventInit) {
77
+ target.dispatchEvent(
78
+ new PointerEvent('pointerdown', {
79
+ bubbles: true,
80
+ clientX: 5,
81
+ clientY: 5,
82
+ pointerId: 1,
83
+ button: 0,
84
+ ...options,
85
+ })
86
+ );
87
+ }
88
+
89
+ function pointerMove(target: Element, options?: PointerEventInit) {
90
+ target.dispatchEvent(
91
+ new PointerEvent('pointermove', {
92
+ bubbles: true,
93
+ clientX: 5,
94
+ clientY: 5,
95
+ pointerId: 1,
96
+ button: -1,
97
+ ...options,
98
+ })
99
+ );
100
+ }
101
+
102
+ function pointerUp(target: Element, options?: PointerEventInit) {
103
+ target.dispatchEvent(
104
+ new PointerEvent('pointerup', {
105
+ bubbles: true,
106
+ clientX: 5,
107
+ clientY: 5,
108
+ pointerId: 1,
109
+ button: 0,
110
+ ...options,
111
+ })
112
+ );
113
+ }
114
+
115
+ let fixture: ReturnType<typeof makeFixture>;
116
+
117
+ beforeEach(() => {
118
+ fixture = makeFixture();
119
+ });
120
+
121
+ afterEach(() => {
122
+ fixture.cleanup();
123
+ document.body.innerHTML = '';
124
+ });
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Step 2: Target classification
128
+ // ---------------------------------------------------------------------------
129
+
130
+ describe('resolveTarget — port', () => {
131
+ it('classifies a port element', () => {
132
+ const port = document.createElement('div');
133
+ port.setAttribute('data-flow-port-name', 'out');
134
+ port.setAttribute('data-flow-node-id', 'n1');
135
+ fixture.container.appendChild(port);
136
+
137
+ pointerDown(port);
138
+
139
+ expect(lastPointerEvent(fixture.runtime).target).toEqual({
140
+ kind: 'port',
141
+ nodeId: 'n1',
142
+ portName: 'out',
143
+ portId: undefined,
144
+ interaction: 'connect',
145
+ });
146
+ });
147
+
148
+ it('preserves inspection interaction and canonical port id', () => {
149
+ const port = document.createElement('div');
150
+ port.setAttribute('data-flow-port-name', 'out');
151
+ port.setAttribute('data-flow-port-id', 'port-1');
152
+ port.setAttribute('data-flow-node-id', 'n1');
153
+ port.setAttribute('data-flow-port-interaction', 'inspect');
154
+ fixture.container.appendChild(port);
155
+
156
+ pointerDown(port);
157
+
158
+ expect(lastPointerEvent(fixture.runtime).target).toEqual({
159
+ kind: 'port',
160
+ nodeId: 'n1',
161
+ portName: 'out',
162
+ portId: 'port-1',
163
+ interaction: 'inspect',
164
+ });
165
+ });
166
+ });
167
+
168
+ describe('resolveTarget — entity', () => {
169
+ it('classifies a plain entity element', () => {
170
+ const node = document.createElement('div');
171
+ node.setAttribute('data-entity-id', 'n1');
172
+ fixture.container.appendChild(node);
173
+
174
+ pointerDown(node);
175
+
176
+ const target = lastPointerEvent(fixture.runtime).target;
177
+ expect(target.kind).toBe('entity');
178
+ expect((target as { id: string }).id).toBe('n1');
179
+ });
180
+
181
+ it('sets entityHasDragHandle=true and pressedDragHandle=true when pressing the handle', () => {
182
+ const node = document.createElement('div');
183
+ node.setAttribute('data-entity-id', 'n1');
184
+ const handle = document.createElement('div');
185
+ handle.setAttribute('data-flow-drag-handle', '');
186
+ node.appendChild(handle);
187
+ fixture.container.appendChild(node);
188
+
189
+ pointerDown(handle);
190
+
191
+ expect(lastPointerEvent(fixture.runtime).target).toMatchObject({
192
+ kind: 'entity',
193
+ id: 'n1',
194
+ entityHasDragHandle: true,
195
+ pressedDragHandle: true,
196
+ });
197
+ });
198
+
199
+ it('sets entityHasDragHandle=true and pressedDragHandle=false when pressing entity body (not the handle)', () => {
200
+ const node = document.createElement('div');
201
+ node.setAttribute('data-entity-id', 'n1');
202
+ const handle = document.createElement('div');
203
+ handle.setAttribute('data-flow-drag-handle', '');
204
+ const body = document.createElement('div');
205
+ node.appendChild(handle);
206
+ node.appendChild(body);
207
+ fixture.container.appendChild(node);
208
+
209
+ pointerDown(body);
210
+
211
+ expect(lastPointerEvent(fixture.runtime).target).toMatchObject({
212
+ kind: 'entity',
213
+ id: 'n1',
214
+ entityHasDragHandle: true,
215
+ pressedDragHandle: false,
216
+ });
217
+ });
218
+
219
+ it('forwards data-flow-part from entity descendants', () => {
220
+ const node = document.createElement('div');
221
+ node.setAttribute('data-entity-id', 'n1');
222
+ const handle = document.createElement('div');
223
+ handle.setAttribute('data-flow-part', 'resize-handle:bottom-right');
224
+ node.appendChild(handle);
225
+ fixture.container.appendChild(node);
226
+
227
+ pointerDown(handle);
228
+
229
+ expect(lastPointerEvent(fixture.runtime).target).toMatchObject({
230
+ kind: 'entity',
231
+ id: 'n1',
232
+ part: 'resize-handle:bottom-right',
233
+ });
234
+ });
235
+ });
236
+
237
+ describe('resolveTarget — pane', () => {
238
+ it('classifies a press on the container itself as pane', () => {
239
+ pointerDown(fixture.container);
240
+
241
+ expect(lastPointerEvent(fixture.runtime).target).toEqual({ kind: 'pane' });
242
+ });
243
+
244
+ it('classifies a press on a data-flow-canvas-layer child as pane', () => {
245
+ const layer = document.createElement('div');
246
+ layer.setAttribute('data-flow-canvas-layer', '');
247
+ fixture.container.appendChild(layer);
248
+
249
+ pointerDown(layer);
250
+
251
+ expect(lastPointerEvent(fixture.runtime).target).toEqual({ kind: 'pane' });
252
+ });
253
+ });
254
+
255
+ describe('resolveTarget — none', () => {
256
+ it.each(['button', 'input', 'textarea', 'select', 'a'])(
257
+ 'keeps native interactive <%s> content out of entity gestures',
258
+ (tagName) => {
259
+ const node = document.createElement('div');
260
+ node.setAttribute('data-entity-id', 'n1');
261
+ const control = document.createElement(tagName);
262
+ if (tagName === 'a') control.setAttribute('href', '#target');
263
+ node.appendChild(control);
264
+ fixture.container.appendChild(node);
265
+
266
+ pointerDown(control);
267
+
268
+ expect(lastPointerEvent(fixture.runtime).target).toEqual({ kind: 'none' });
269
+ },
270
+ );
271
+
272
+ it('keeps contenteditable, nodrag, and explicit interactive content out of entity gestures', () => {
273
+ const node = document.createElement('div');
274
+ node.setAttribute('data-entity-id', 'n1');
275
+ fixture.container.appendChild(node);
276
+
277
+ for (const selector of [
278
+ 'contenteditable',
279
+ 'contenteditable-empty',
280
+ 'nodrag',
281
+ 'explicit',
282
+ ]) {
283
+ const control = document.createElement('div');
284
+ if (selector === 'contenteditable') {
285
+ control.setAttribute('contenteditable', 'true');
286
+ } else if (selector === 'contenteditable-empty') {
287
+ control.setAttribute('contenteditable', '');
288
+ } else if (selector === 'nodrag') {
289
+ control.className = 'nodrag';
290
+ } else {
291
+ control.setAttribute('data-flow-interactive', '');
292
+ }
293
+ node.appendChild(control);
294
+ pointerDown(control);
295
+ expect(lastPointerEvent(fixture.runtime).target).toEqual({ kind: 'none' });
296
+ }
297
+ });
298
+
299
+ it('classifies a press on a plain child (no recognized attributes) as none', () => {
300
+ const orphan = document.createElement('div');
301
+ // Append outside container so it has no canvas-layer ancestor
302
+ document.body.appendChild(orphan);
303
+
304
+ orphan.dispatchEvent(
305
+ new PointerEvent('pointerdown', {
306
+ bubbles: true,
307
+ clientX: 5,
308
+ clientY: 5,
309
+ pointerId: 1,
310
+ button: 0,
311
+ })
312
+ );
313
+
314
+ // The listener is only on fixture.container, so this event does NOT reach it.
315
+ // runtime.send should not have been called.
316
+ expect(fixture.runtime.send).not.toHaveBeenCalled();
317
+ });
318
+ });
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // Step 3: Event-kind, modifiers, wheel, key
322
+ // ---------------------------------------------------------------------------
323
+
324
+ describe('event kind normalization', () => {
325
+ it('sends kind pointer.down on pointerdown', () => {
326
+ pointerDown(fixture.container);
327
+
328
+ const event = fixture.runtime.send.mock.calls.at(-1)?.[0];
329
+ expect(event?.kind).toBe('pointer.down');
330
+ });
331
+
332
+ it('sends kind pointer.up on pointerup', () => {
333
+ fixture.container.dispatchEvent(
334
+ new PointerEvent('pointerup', { bubbles: true, pointerId: 1, button: 0 })
335
+ );
336
+
337
+ const event = fixture.runtime.send.mock.calls.at(-1)?.[0];
338
+ expect(event?.kind).toBe('pointer.up');
339
+ });
340
+
341
+ it('passes pointerType through pointer events', () => {
342
+ pointerDown(fixture.container, { pointerType: 'touch' });
343
+
344
+ expect((lastPointerEvent(fixture.runtime) as { pointerType?: string }).pointerType).toBe('touch');
345
+ });
346
+ });
347
+
348
+ describe('captured gesture hot path', () => {
349
+ it('reuses container geometry and skips hit testing for entity drag moves', () => {
350
+ fixture.cleanup();
351
+ const container = fixture.container;
352
+ const store = fixture.store;
353
+ const rect = vi.spyOn(container, 'getBoundingClientRect').mockReturnValue({
354
+ left: 10,
355
+ top: 20,
356
+ right: 210,
357
+ bottom: 220,
358
+ width: 200,
359
+ height: 200,
360
+ x: 10,
361
+ y: 20,
362
+ toJSON: () => ({}),
363
+ });
364
+ let activeSession: string | null = null;
365
+ const runtime = {
366
+ getActiveSession: () => activeSession,
367
+ cancelSession: vi.fn(),
368
+ send: vi.fn<(event: FlowInputEvent) => FlowInputEffects>((event) => {
369
+ if (event.kind === 'pointer.down') {
370
+ activeSession = 'entity-press';
371
+ return { ...makeEffects(), sessionStarted: true, handledBy: activeSession };
372
+ }
373
+ return { ...makeEffects(), handledBy: activeSession };
374
+ }),
375
+ };
376
+ fixture.cleanup = attachInput({ container, store, runtime });
377
+
378
+ pointerDown(container, { clientX: 25, clientY: 35 });
379
+ const readsAfterDown = rect.mock.calls.length;
380
+ pointerMove(container, { clientX: 30, clientY: 40 });
381
+ pointerMove(container, { clientX: 35, clientY: 45 });
382
+
383
+ expect(rect).toHaveBeenCalledTimes(readsAfterDown);
384
+ window.dispatchEvent(new Event('scroll'));
385
+ pointerMove(container, { clientX: 35, clientY: 45 });
386
+ expect(rect).toHaveBeenCalledTimes(readsAfterDown + 1);
387
+ expect(runtime.send.mock.calls.at(-1)?.[0]).toMatchObject({
388
+ screenPoint: { x: 25, y: 25 },
389
+ target: { kind: 'none' },
390
+ });
391
+ });
392
+ });
393
+
394
+ describe('auto-pan ticker', () => {
395
+ it('preserves the latest pointer modifiers on synthetic moves', () => {
396
+ const frameCallbacks: FrameRequestCallback[] = [];
397
+ const requestFrame = vi
398
+ .spyOn(window, 'requestAnimationFrame')
399
+ .mockImplementation((callback) => {
400
+ frameCallbacks.push(callback);
401
+ return frameCallbacks.length;
402
+ });
403
+ const cancelFrame = vi
404
+ .spyOn(window, 'cancelAnimationFrame')
405
+ .mockImplementation(() => {});
406
+
407
+ fixture.cleanup();
408
+
409
+ const runtime = {
410
+ getActiveSession: () => 'entity-press',
411
+ cancelSession: vi.fn(),
412
+ send: vi.fn<(event: FlowInputEvent) => FlowInputEffects>((event) => ({
413
+ ...makeEffects(),
414
+ handledBy: 'entity-press',
415
+ sessionStarted: event.kind === 'pointer.down',
416
+ })),
417
+ };
418
+
419
+ const cleanup = attachInput({
420
+ container: fixture.container,
421
+ store: fixture.store,
422
+ runtime,
423
+ autoPan: () => ({ x: 1, y: 0 }),
424
+ });
425
+ fixture.cleanup = () => {
426
+ cleanup();
427
+ requestFrame.mockRestore();
428
+ cancelFrame.mockRestore();
429
+ };
430
+
431
+ pointerDown(fixture.container);
432
+ pointerMove(fixture.container, {
433
+ clientX: 798,
434
+ clientY: 300,
435
+ shiftKey: true,
436
+ ctrlKey: true,
437
+ });
438
+
439
+ const frame = frameCallbacks.shift();
440
+ if (!frame) {
441
+ throw new Error('Expected auto-pan to schedule a frame');
442
+ }
443
+ frame(0);
444
+
445
+ const lastEvent = runtime.send.mock.calls.at(-1)?.[0];
446
+ expect(lastEvent).toMatchObject({
447
+ kind: 'pointer.move',
448
+ modifiers: { shift: true, meta: false, ctrl: true, alt: false },
449
+ });
450
+ });
451
+ });
452
+
453
+ describe('touch pinch normalization', () => {
454
+ it('cancels the active pointer session and emits pinch events for two touches', () => {
455
+ pointerDown(fixture.container, {
456
+ pointerId: 1,
457
+ pointerType: 'touch',
458
+ clientX: 0,
459
+ clientY: 0,
460
+ });
461
+ pointerDown(fixture.container, {
462
+ pointerId: 2,
463
+ pointerType: 'touch',
464
+ clientX: 0,
465
+ clientY: 100,
466
+ });
467
+
468
+ expect(fixture.runtime.cancelSession).toHaveBeenCalled();
469
+ expect(fixture.runtime.send.mock.calls.at(-1)?.[0]).toMatchObject({
470
+ kind: 'pinch.start',
471
+ screenCenter: { x: 0, y: 50 },
472
+ distance: 100,
473
+ pointerCount: 2,
474
+ });
475
+
476
+ pointerMove(fixture.container, {
477
+ pointerId: 2,
478
+ pointerType: 'touch',
479
+ clientX: 0,
480
+ clientY: 200,
481
+ });
482
+ expect(fixture.runtime.send.mock.calls.at(-1)?.[0]).toMatchObject({
483
+ kind: 'pinch.move',
484
+ screenCenter: { x: 0, y: 100 },
485
+ distance: 200,
486
+ pointerCount: 2,
487
+ });
488
+
489
+ pointerUp(fixture.container, {
490
+ pointerId: 2,
491
+ pointerType: 'touch',
492
+ clientX: 0,
493
+ clientY: 200,
494
+ });
495
+ expect(fixture.runtime.send.mock.calls.at(-1)?.[0]).toMatchObject({
496
+ kind: 'pinch.end',
497
+ pointerCount: 1,
498
+ });
499
+ });
500
+ });
501
+
502
+ describe('modifier normalization', () => {
503
+ it('passes shift and meta flags correctly', () => {
504
+ pointerDown(fixture.container, { shiftKey: true, metaKey: true });
505
+
506
+ const event = fixture.runtime.send.mock.calls.at(-1)?.[0];
507
+ expect(event?.modifiers).toEqual({ shift: true, meta: true, ctrl: false, alt: false });
508
+ });
509
+ });
510
+
511
+ describe('click detail and context menu normalization', () => {
512
+ const detailOf = (runtime: ReturnType<typeof makeFixture>['runtime']) =>
513
+ (lastPointerEvent(runtime) as FlowPointerInputEvent & { detail?: number }).detail;
514
+
515
+ it('derives the click count on pointerdown (native detail is unreliable)', () => {
516
+ // Browsers commonly leave detail=0 on pointerdown; flow-dom must still
517
+ // report a click count of 1 for the first press.
518
+ pointerDown(fixture.container, { detail: 0 });
519
+ expect(detailOf(fixture.runtime)).toBe(1);
520
+ });
521
+
522
+ it('reports detail 2 for the second press of a real double-click', () => {
523
+ // A real double-click: two downs close in time/space, each with the
524
+ // browser's native detail of 0 on pointerdown.
525
+ pointerDown(fixture.container, { detail: 0 });
526
+ pointerUp(fixture.container, { detail: 0 });
527
+ pointerDown(fixture.container, { detail: 0 });
528
+
529
+ expect(detailOf(fixture.runtime)).toBe(2);
530
+ });
531
+
532
+ it('normalizes contextmenu as a secondary pointer press without forcing preventDefault', () => {
533
+ fixture.container.dispatchEvent(
534
+ new MouseEvent('contextmenu', {
535
+ bubbles: true,
536
+ cancelable: true,
537
+ clientX: 5,
538
+ clientY: 5,
539
+ })
540
+ );
541
+
542
+ const event = lastPointerEvent(fixture.runtime);
543
+ expect(event).toMatchObject({ kind: 'pointer.down', button: 2 });
544
+ });
545
+ });
546
+
547
+ describe('wheel normalization', () => {
548
+ it('passes deltaX, deltaY, deltaMode', () => {
549
+ fixture.container.dispatchEvent(
550
+ new WheelEvent('wheel', { deltaX: 10, deltaY: -20, deltaMode: 0, bubbles: true })
551
+ );
552
+
553
+ const event = fixture.runtime.send.mock.calls.at(-1)?.[0];
554
+ expect(event).toMatchObject({ kind: 'wheel', deltaX: 10, deltaY: -20, deltaMode: 0 });
555
+ });
556
+ });
557
+
558
+ describe('key normalization', () => {
559
+ it('sends kind key.down and key for keydown', () => {
560
+ fixture.container.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true }));
561
+
562
+ const event = fixture.runtime.send.mock.calls.at(-1)?.[0];
563
+ expect(event).toMatchObject({ kind: 'key.down', key: 'a' });
564
+ });
565
+
566
+ it('sets editableTarget=false for a non-input target', () => {
567
+ fixture.container.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true }));
568
+
569
+ const event = fixture.runtime.send.mock.calls.at(-1)?.[0];
570
+ expect((event as { editableTarget?: boolean })?.editableTarget).toBe(false);
571
+ });
572
+
573
+ it('scopes keyboard events to the focused container by default', () => {
574
+ const flowA = makeBoundFlow('a');
575
+ const flowB = makeBoundFlow('b');
576
+ flowA.store.trigger.select({ ids: ['a'] });
577
+ flowB.store.trigger.select({ ids: ['b'] });
578
+
579
+ flowA.container.focus();
580
+ flowA.container.dispatchEvent(
581
+ new KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true })
582
+ );
583
+
584
+ expect(flowA.store.getSnapshot().context.graph.nodes).toHaveLength(0);
585
+ expect(flowB.store.getSnapshot().context.graph.nodes).toHaveLength(1);
586
+
587
+ flowA.cleanup();
588
+ flowB.cleanup();
589
+ });
590
+
591
+ it('supports window keyboard target for legacy global handling', () => {
592
+ const windowFixture = makeFixture({ keyboardTarget: 'window' });
593
+
594
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'a', bubbles: true }));
595
+
596
+ const event = windowFixture.runtime.send.mock.calls.at(-1)?.[0];
597
+ expect(event).toMatchObject({ kind: 'key.down', key: 'a' });
598
+ expect(fixture.runtime.send).not.toHaveBeenCalledWith(
599
+ expect.objectContaining({ kind: 'key.down' })
600
+ );
601
+
602
+ windowFixture.cleanup();
603
+ });
604
+
605
+ it('focuses the container on pane press so arrow keys work immediately', () => {
606
+ const flow = makeBoundFlow('a');
607
+ flow.store.trigger.select({ ids: ['a'] });
608
+
609
+ pointerDown(flow.container);
610
+ expect(document.activeElement).toBe(flow.container);
611
+
612
+ flow.container.dispatchEvent(
613
+ new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true, cancelable: true })
614
+ );
615
+
616
+ expect(flow.store.getSnapshot().context.graph.nodes[0].x).toBe(5);
617
+
618
+ flow.cleanup();
619
+ });
620
+ });
621
+
622
+ // ---------------------------------------------------------------------------
623
+ // Step 4: Cleanup
624
+ // ---------------------------------------------------------------------------
625
+
626
+ describe('pointer capture lifecycle', () => {
627
+ it('does not cancel input when a completed gesture releases capture', () => {
628
+ const { container, runtime } = fixture;
629
+ let captured = false;
630
+ container.setPointerCapture = () => { captured = true; };
631
+ container.hasPointerCapture = () => captured;
632
+ container.releasePointerCapture = (pointerId) => {
633
+ captured = false;
634
+ container.dispatchEvent(new PointerEvent('lostpointercapture', { pointerId }));
635
+ };
636
+ runtime.send.mockImplementation((event) => ({
637
+ ...makeEffects(),
638
+ sessionStarted: event.kind === 'pointer.down',
639
+ sessionEnded: event.kind === 'pointer.up',
640
+ }));
641
+
642
+ const previousHitTest = document.elementFromPoint;
643
+ document.elementFromPoint = () => container;
644
+ try {
645
+ pointerDown(container);
646
+ pointerUp(container);
647
+
648
+ expect(captured).toBe(false);
649
+ expect(runtime.cancelSession).not.toHaveBeenCalled();
650
+ } finally {
651
+ document.elementFromPoint = previousHitTest;
652
+ }
653
+ });
654
+
655
+ it.each([false, true])('releases an ended keyboard gesture without releasing a replacement capture %s', (replaceCapture) => {
656
+ const { container, runtime } = fixture;
657
+ let captured = false;
658
+ container.setPointerCapture = () => { captured = true; };
659
+ container.hasPointerCapture = () => captured;
660
+ container.releasePointerCapture = (pointerId) => {
661
+ captured = false;
662
+ container.dispatchEvent(new PointerEvent('lostpointercapture', { pointerId }));
663
+ };
664
+ runtime.send.mockImplementation((event) => {
665
+ if (event.kind === 'key.down') {
666
+ if (replaceCapture) pointerDown(container, { pointerId: 1 });
667
+ return { ...makeEffects(), sessionEnded: true };
668
+ }
669
+ return { ...makeEffects(), sessionStarted: event.kind === 'pointer.down' };
670
+ });
671
+ const previousHitTest = document.elementFromPoint;
672
+ document.elementFromPoint = () => container;
673
+ try {
674
+ pointerDown(container, { pointerId: 1 });
675
+ container.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
676
+ expect(captured).toBe(replaceCapture);
677
+ expect(runtime.cancelSession).not.toHaveBeenCalled();
678
+ } finally {
679
+ document.elementFromPoint = previousHitTest;
680
+ }
681
+ });
682
+
683
+ it('cancels only unexpected capture loss for the captured pointer', () => {
684
+ const { container, runtime } = fixture;
685
+ container.setPointerCapture = () => {};
686
+ runtime.send.mockReturnValue({ ...makeEffects(), sessionStarted: true });
687
+ pointerDown(container, { pointerId: 1 });
688
+
689
+ container.dispatchEvent(new PointerEvent('lostpointercapture', { pointerId: 2 }));
690
+ expect(runtime.cancelSession).not.toHaveBeenCalled();
691
+ container.dispatchEvent(new PointerEvent('lostpointercapture', { pointerId: 1 }));
692
+ expect(runtime.cancelSession).toHaveBeenCalledTimes(1);
693
+ });
694
+ });
695
+
696
+ describe('cleanup', () => {
697
+ it('removes listeners so send is not called after cleanup', () => {
698
+ fixture.cleanup();
699
+ const callsBefore = fixture.runtime.send.mock.calls.length;
700
+
701
+ pointerDown(fixture.container);
702
+
703
+ expect(fixture.runtime.send.mock.calls.length).toBe(callsBefore);
704
+ });
705
+ });