@jylups/flowable-bpmn-js 0.0.0-stage → 0.1.0-next.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +286 -2
  3. package/assets/flowable-bpmn-js-touch.css +76 -0
  4. package/assets/flowable-bpmn-js.css +70 -0
  5. package/dist/assets/bpmn-font/css/bpmn-codes.css +110 -0
  6. package/dist/assets/bpmn-font/css/bpmn-embedded.css +168 -0
  7. package/dist/assets/bpmn-font/css/bpmn.css +166 -0
  8. package/dist/assets/bpmn-font/font/bpmn.eot +0 -0
  9. package/dist/assets/bpmn-font/font/bpmn.svg +228 -0
  10. package/dist/assets/bpmn-font/font/bpmn.ttf +0 -0
  11. package/dist/assets/bpmn-font/font/bpmn.woff +0 -0
  12. package/dist/assets/bpmn-font/font/bpmn.woff2 +0 -0
  13. package/dist/assets/bpmn-js-bpmnlint.css +263 -0
  14. package/dist/assets/bpmn-js.css +151 -0
  15. package/dist/assets/diagram-js.css +1325 -0
  16. package/dist/assets/flowable-bpmn-js-touch.css +76 -0
  17. package/dist/assets/flowable-bpmn-js.css +70 -0
  18. package/dist/assets/properties-panel.css +1905 -0
  19. package/dist/flowable-bpmn-modeler.development.js +128087 -0
  20. package/dist/flowable-bpmn-modeler.development.js.map +1 -0
  21. package/dist/flowable-bpmn-modeler.production.min.js +348 -0
  22. package/dist/flowable-bpmn-navigated-viewer.development.js +28092 -0
  23. package/dist/flowable-bpmn-navigated-viewer.development.js.map +1 -0
  24. package/dist/flowable-bpmn-navigated-viewer.production.min.js +2 -0
  25. package/dist/flowable-bpmn-viewer.development.js +26751 -0
  26. package/dist/flowable-bpmn-viewer.development.js.map +1 -0
  27. package/dist/flowable-bpmn-viewer.production.min.js +2 -0
  28. package/index.d.ts +107 -0
  29. package/index.js +32 -0
  30. package/lib/Modeler.js +68 -0
  31. package/lib/NavigatedViewer.js +30 -0
  32. package/lib/NewDiagram.js +69 -0
  33. package/lib/Theme.js +32 -0
  34. package/lib/Viewer.js +32 -0
  35. package/lib/distro/Modeler.js +5 -0
  36. package/lib/distro/NavigatedViewer.js +5 -0
  37. package/lib/distro/Viewer.js +5 -0
  38. package/lib/draw/TypedTaskRenderer.js +81 -0
  39. package/lib/draw/index.js +10 -0
  40. package/lib/features/touch/InputTracker.js +34 -0
  41. package/lib/features/touch/LICENSE +21 -0
  42. package/lib/features/touch/TouchContextPad.js +197 -0
  43. package/lib/features/touch/TouchInteraction.js +1276 -0
  44. package/lib/features/touch/TouchLabelEditing.js +60 -0
  45. package/lib/features/touch/index.js +40 -0
  46. package/lib/features/typed-tasks/ReplaceWithTypedTaskHandler.js +63 -0
  47. package/lib/features/typed-tasks/TypedTaskPaletteProvider.js +76 -0
  48. package/lib/features/typed-tasks/TypedTaskReplaceMenuProvider.js +71 -0
  49. package/lib/features/typed-tasks/TypedTasks.js +127 -0
  50. package/lib/features/typed-tasks/icons.js +99 -0
  51. package/lib/features/typed-tasks/index.js +17 -0
  52. package/lib/lint/FlowableLinting.js +23 -0
  53. package/lib/lint/index.js +44 -0
  54. package/lib/lint/module.js +15 -0
  55. package/lib/lint/rules/called-element.js +19 -0
  56. package/lib/lint/rules/service-task-implementation.js +81 -0
  57. package/lib/lint/rules/valid-durations.js +102 -0
  58. package/lib/lint/values.js +71 -0
  59. package/lib/xml/FlowableXML.js +50 -0
  60. package/lib/xml/index.js +6 -0
  61. package/package.json +80 -4
@@ -0,0 +1,1276 @@
1
+ /*
2
+ * Touch gestures for diagram-js, from bpmn-js-touch-interaction 0.1.2
3
+ * (https://github.com/krasucki/bpmn-js-touch-interaction, MIT licence, see
4
+ * LICENSE in this folder): dist/bpmn-js-touch-interaction.esm.js as published
5
+ * on npm. Conscia Modeler copied and adapted it for iPads and Android tablets
6
+ * (Conscia-LLC/conscia-modeler, docs/spikes/touch.md), and it moved into
7
+ * @jylups/cmmn-js in jylups/cmmn-js-env#55. This copy is taken from
8
+ * @jylups/cmmn-js 0.23.0 (lib/features/touch, commit 23141a5) for the BPMN editor
9
+ * (jylups/bpmn-js-env#43); the CMMN module stays as it is.
10
+ *
11
+ * Changes here are marked with "CHANGED:":
12
+ * - ES modules, as published on npm (the cmmn-js copy is CommonJS).
13
+ * - touch-action: none for the bpmn-js container only, as published (the
14
+ * cmmn-js copy adds its own container).
15
+ * - The source map comment is removed; the map isn't copied.
16
+ * - The touch hover tracking updates the hover before a drag handles the
17
+ * touch, so taps and the last move of a drag see the right element.
18
+ * - The replaced tool starts (lasso, space, global connect) call the
19
+ * originals after a mouse or trackpad press, for an iPad with a trackpad.
20
+ * - A drag on a connection's bendpoint or segment handle moves it instead of
21
+ * panning the canvas.
22
+ * - A dragged shape moves from where the finger went down, so it stays under
23
+ * the finger instead of lagging by the pan threshold.
24
+ *
25
+ * It turns itself on only where (pointer: coarse) matches.
26
+ */
27
+ import InteractionEventsModule from 'diagram-js/lib/features/interaction-events';
28
+ import { closest } from 'min-dom';
29
+ import { append, attr, create } from 'tiny-svg';
30
+ // CHANGED: which kind of pointer was pressed last, for an iPad with a trackpad
31
+ import { createInputTracker } from './InputTracker.js';
32
+
33
+ const STATES = {
34
+ IDLE: 'IDLE',
35
+ TOUCH_START: 'TOUCH_START',
36
+ PAN: 'PAN',
37
+ PRESS: 'PRESS',
38
+ PINCH: 'PINCH',
39
+ };
40
+
41
+ function createGestureRecognizer(element, {
42
+ onTap, onDoubleTap, onPanStart, onPanMove, onPanEnd,
43
+ onPinchStart, onPinchMove, onPinchEnd, onPress,
44
+ tapThreshold = 10, panThreshold = 10,
45
+ doubleTapWindow = 300, pressDelay = 300,
46
+ } = {}) {
47
+
48
+ let state = STATES.IDLE;
49
+ let startTouch = null; // { x, y, time, target, id }
50
+ let pressTimer = null;
51
+ let lastTapTime = 0;
52
+ let lastTapCenter = null;
53
+
54
+ // Pinch state
55
+ let pinchStartDist = 0;
56
+
57
+ function dist(a, b) {
58
+ return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
59
+ }
60
+
61
+ function midpoint(a, b) {
62
+ return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
63
+ }
64
+
65
+ function clearPress() {
66
+ if (pressTimer) {
67
+ clearTimeout(pressTimer);
68
+ pressTimer = null;
69
+ }
70
+ }
71
+
72
+ function getTouch(e, id) {
73
+ for (const t of e.changedTouches) {
74
+ if (t.identifier === id) return t;
75
+ }
76
+ return null;
77
+ }
78
+
79
+ function handleTouchStart(e) {
80
+ const touches = e.touches;
81
+
82
+ if (touches.length === 2 && state !== STATES.PINCH) {
83
+ clearPress();
84
+
85
+ // End active pan before entering pinch — prevents panActive staying true
86
+ if (state === STATES.PAN) {
87
+ onPanEnd?.({ originalEvent: e });
88
+ }
89
+ const t0 = touches[0], t1 = touches[1];
90
+ const a = { x: t0.clientX, y: t0.clientY };
91
+ const b = { x: t1.clientX, y: t1.clientY };
92
+ pinchStartDist = dist(a, b);
93
+ state = STATES.PINCH;
94
+ const center = midpoint(a, b);
95
+ onPinchStart?.({
96
+ center,
97
+ scale: 1,
98
+ originalEvent: e,
99
+ });
100
+ e.preventDefault();
101
+ return;
102
+ }
103
+
104
+ // Reset stuck state: if a drag system (e.g. diagram-js Dragging) consumed
105
+ // touchend via stopPropagation in capture phase, we never received it and
106
+ // are stuck in PAN/PRESS. A new touchstart means the previous gesture is over.
107
+ if (touches.length === 1 && state !== STATES.IDLE && state !== STATES.PINCH) {
108
+ clearPress();
109
+ state = STATES.IDLE;
110
+ startTouch = null;
111
+ }
112
+
113
+ if (touches.length !== 1 || state !== STATES.IDLE) return;
114
+
115
+ const t = touches[0];
116
+ startTouch = {
117
+ x: t.clientX,
118
+ y: t.clientY,
119
+ time: Date.now(),
120
+ target: t.target,
121
+ id: t.identifier,
122
+ event: e, // preserve touchstart — touchend has no coordinates for toPoint()
123
+ };
124
+
125
+ state = STATES.TOUCH_START;
126
+ pressTimer = setTimeout(() => {
127
+ if (state === STATES.TOUCH_START) {
128
+ state = STATES.PRESS;
129
+ onPress?.({
130
+ center: { x: startTouch.x, y: startTouch.y },
131
+ target: startTouch.target,
132
+ originalEvent: e,
133
+ });
134
+ }
135
+ }, pressDelay);
136
+
137
+ e.preventDefault();
138
+ }
139
+
140
+ function handleTouchMove(e) {
141
+ if (state === STATES.PINCH) {
142
+ if (e.touches.length < 2) return;
143
+ const t0 = e.touches[0], t1 = e.touches[1];
144
+ const a = { x: t0.clientX, y: t0.clientY };
145
+ const b = { x: t1.clientX, y: t1.clientY };
146
+ const currentDist = dist(a, b);
147
+ const scale = pinchStartDist > 0 ? currentDist / pinchStartDist : 1;
148
+ const center = midpoint(a, b);
149
+ onPinchMove?.({
150
+ center,
151
+ scale,
152
+ originalEvent: e,
153
+ });
154
+ e.preventDefault();
155
+ return;
156
+ }
157
+
158
+ if (!startTouch) return;
159
+ const t = getTouch(e, startTouch.id);
160
+ if (!t) return;
161
+
162
+ const dx = t.clientX - startTouch.x;
163
+ const dy = t.clientY - startTouch.y;
164
+ const moved = Math.sqrt(dx * dx + dy * dy);
165
+
166
+ if (state === STATES.TOUCH_START && moved > panThreshold) {
167
+ clearPress();
168
+ state = STATES.PAN;
169
+ onPanStart?.({
170
+ center: { x: startTouch.x, y: startTouch.y },
171
+ target: startTouch.target,
172
+ originalEvent: e,
173
+ // CHANGED: the touchstart too, for drags that must start where the finger went down
174
+ startEvent: startTouch.event,
175
+ });
176
+ }
177
+
178
+ if (state === STATES.PRESS && moved > panThreshold) {
179
+ state = STATES.PAN;
180
+ onPanStart?.({
181
+ center: { x: startTouch.x, y: startTouch.y },
182
+ target: startTouch.target,
183
+ originalEvent: e,
184
+ // CHANGED: the touchstart too, for drags that must start where the finger went down
185
+ startEvent: startTouch.event,
186
+ });
187
+ }
188
+
189
+ if (state === STATES.PAN) {
190
+ onPanMove?.({
191
+ center: { x: t.clientX, y: t.clientY },
192
+ deltaX: dx,
193
+ deltaY: dy,
194
+ target: startTouch.target,
195
+ originalEvent: e,
196
+ });
197
+ e.preventDefault();
198
+ }
199
+ }
200
+
201
+ function handleTouchEnd(e) {
202
+
203
+ // First touchend during pinch ends the entire gesture (even if one finger remains).
204
+ // The remaining finger's touchend will arrive with state=IDLE and no-op.
205
+ if (state === STATES.PINCH) {
206
+ onPinchEnd?.({ originalEvent: e });
207
+ pinchStartDist = 0;
208
+ state = STATES.IDLE;
209
+ startTouch = null;
210
+ return;
211
+ }
212
+
213
+ clearPress();
214
+
215
+ if (state === STATES.TOUCH_START || state === STATES.PRESS) {
216
+ const center = { x: startTouch.x, y: startTouch.y };
217
+ const target = startTouch.target;
218
+
219
+ // Use touchstart event, not touchend — touchend.touches is empty so
220
+ // toPoint() in diagram-js can't extract coordinates, producing NaN.
221
+ const originalEvent = startTouch.event;
222
+
223
+ // Check for double-tap
224
+ const now = Date.now();
225
+ if (lastTapTime && (now - lastTapTime) < doubleTapWindow && lastTapCenter &&
226
+ dist(center, lastTapCenter) < tapThreshold) {
227
+ onDoubleTap?.({ center, target, originalEvent });
228
+ lastTapTime = 0;
229
+ lastTapCenter = null;
230
+ } else {
231
+ onTap?.({ center, target, originalEvent });
232
+ lastTapTime = now;
233
+ lastTapCenter = center;
234
+ }
235
+ }
236
+
237
+ if (state === STATES.PAN) {
238
+ onPanEnd?.({ originalEvent: e });
239
+ }
240
+
241
+ state = STATES.IDLE;
242
+ startTouch = null;
243
+ }
244
+
245
+ function handleTouchCancel(e) {
246
+ clearPress();
247
+ if (state === STATES.PAN) {
248
+ onPanEnd?.({ originalEvent: e });
249
+ }
250
+ if (state === STATES.PINCH) {
251
+ onPinchEnd?.({ originalEvent: e });
252
+ }
253
+ state = STATES.IDLE;
254
+ startTouch = null;
255
+ pinchStartDist = 0;
256
+ }
257
+
258
+ const opts = { passive: false };
259
+ element.addEventListener('touchstart', handleTouchStart, opts);
260
+ element.addEventListener('touchmove', handleTouchMove, opts);
261
+ element.addEventListener('touchend', handleTouchEnd, opts);
262
+ element.addEventListener('touchcancel', handleTouchCancel, opts);
263
+
264
+ return function cleanup() {
265
+ clearPress();
266
+ element.removeEventListener('touchstart', handleTouchStart, opts);
267
+ element.removeEventListener('touchmove', handleTouchMove, opts);
268
+ element.removeEventListener('touchend', handleTouchEnd, opts);
269
+ element.removeEventListener('touchcancel', handleTouchCancel, opts);
270
+ };
271
+ }
272
+
273
+ /**
274
+ * Pure event-construction helpers for the touch interaction plugin.
275
+ *
276
+ * These wrap or synthesize DOM events to satisfy diagram-js's mouse-only
277
+ * assumptions (`isPrimaryButton`, `isTouchEvent`, `toPoint`).
278
+ */
279
+
280
+ /**
281
+ * Wrap a TouchEvent so it passes diagram-js `isPrimaryButton(event)` check
282
+ * (which reads `event.button === 0` — undefined on TouchEvent).
283
+ *
284
+ * Cannot use `Object.create(touchEvent)` — native DOM methods (`stopPropagation`,
285
+ * `preventDefault`) throw "Illegal invocation" when called with a non-Event `this`.
286
+ * Use a plain object with bound delegate methods instead.
287
+ *
288
+ * NOTE: lost `instanceof TouchEvent`. Only use for `interactionEvents.fire`,
289
+ * NOT for `dragging.init` (which checks `isTouchEvent` via `instanceof`).
290
+ */
291
+ function asPrimaryButtonEvent(touchEvent) {
292
+ return {
293
+ button: 0,
294
+ target: touchEvent.target,
295
+ clientX: touchEvent.clientX,
296
+ clientY: touchEvent.clientY,
297
+ preventDefault: () => touchEvent.preventDefault(),
298
+ stopPropagation: () => touchEvent.stopPropagation(),
299
+ stopImmediatePropagation: () => touchEvent.stopImmediatePropagation(),
300
+ };
301
+ }
302
+
303
+ /**
304
+ * Synthetic event for `palette.trigger` / `contextPad.trigger`. Both methods
305
+ * expect an event with `delegateTarget` (the element with `data-action`) and
306
+ * may call `preventDefault()` on the fallback path — provide no-op stubs.
307
+ */
308
+ function syntheticEvent(delegateTarget, originalEvent) {
309
+ return {
310
+ delegateTarget,
311
+ originalEvent,
312
+ preventDefault() {},
313
+ stopPropagation() {},
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Construct a real TouchEvent that passes `isTouchEvent()` (instanceof check)
319
+ * AND has populated `touches` so `toPoint()` can extract coordinates.
320
+ *
321
+ * Used to substitute for `null` events passed to `connect.start(null, ...)` —
322
+ * without this, `Dragging.init` binds mouse handlers and touch events are lost.
323
+ *
324
+ * TouchEvent constructor requires REAL Touch instances (not plain objects),
325
+ * hence the `new Touch({...})` call.
326
+ *
327
+ * @returns {TouchEvent|null} null if Touch/TouchEvent unavailable or construction fails
328
+ */
329
+ function createSyntheticTouchEvent(type, target, x = 0, y = 0) {
330
+ if (typeof TouchEvent === 'undefined' || typeof Touch === 'undefined') return null;
331
+ try {
332
+ const touch = new Touch({
333
+ identifier: 0,
334
+ target,
335
+ clientX: x,
336
+ clientY: y,
337
+ pageX: x,
338
+ pageY: y,
339
+ screenX: x,
340
+ screenY: y,
341
+ });
342
+ return new TouchEvent(type, {
343
+ bubbles: true,
344
+ cancelable: true,
345
+ touches: [ touch ],
346
+ changedTouches: [ touch ],
347
+ targetTouches: [ touch ],
348
+ });
349
+ } catch (e) {
350
+ console.warn('[touch] failed to construct synthetic TouchEvent:', e);
351
+ return null;
352
+ }
353
+ }
354
+
355
+ /**
356
+ * Create a gesture recognizer for a "button surface" (palette or context pad).
357
+ *
358
+ * Both surfaces share the same touch flow:
359
+ * - tap → trigger('click', synthEvent) on the entry under the finger
360
+ * - pan/press → trigger('dragstart', synthEvent, true) on the entry
361
+ *
362
+ * The `onTapExtra` hook lets the caller intercept the tap before the default
363
+ * `trigger('click')` runs (used by context pad to short-circuit the connect
364
+ * entry into single-gesture mode).
365
+ *
366
+ * @param {Element} container
367
+ * @param {{ trigger: Function }} service — palette or contextPad
368
+ * @param {{ onTapExtra?: (button: Element, originalEvent: TouchEvent) => boolean, onTouch: () => void }} hooks
369
+ * - onTapExtra: return true to skip default trigger('click') (handled the tap yourself)
370
+ * - onTouch: called whenever any tap/pan/press fires (for mouse suppression)
371
+ * @returns {() => void} cleanup
372
+ */
373
+ function createButtonRecognizer(container, service, hooks = {}) {
374
+ const { onTapExtra, onTouch } = hooks;
375
+
376
+ return createGestureRecognizer(container, {
377
+ onTap({ target, originalEvent }) {
378
+ onTouch?.();
379
+ const button = closest(target, '[data-action]', true);
380
+ if (!button) return;
381
+ if (onTapExtra && onTapExtra(button, originalEvent) === true) return;
382
+ service.trigger('click', syntheticEvent(button, originalEvent));
383
+ },
384
+
385
+ onPanStart({ target, originalEvent }) {
386
+ onTouch?.();
387
+ const button = closest(target, '[data-action]', true);
388
+ if (button) {
389
+ service.trigger('dragstart', syntheticEvent(button, originalEvent), true);
390
+ }
391
+ },
392
+
393
+ onPress({ target, originalEvent }) {
394
+ onTouch?.();
395
+ const button = closest(target, '[data-action]', true);
396
+ if (button) {
397
+ service.trigger('dragstart', syntheticEvent(button, originalEvent), true);
398
+ }
399
+ },
400
+ });
401
+ }
402
+
403
+ /**
404
+ * Plugin-wide constants. Hoisted from inline magic numbers for clarity.
405
+ */
406
+
407
+ /** How long to suppress synthesized mouse events after a touch (ms). */
408
+ const MOUSE_SUPPRESSION_MS = 500;
409
+
410
+ /** Event priority for tool-end interceptors — must run before tool handlers (default 1000). */
411
+ const TOOL_EVENT_PRIORITY = 1500;
412
+
413
+ /** Pinch zoom bounds. Mirrors the old diagram-js TouchInteractionEvents module. */
414
+ const MIN_ZOOM = 0.2;
415
+ const MAX_ZOOM = 4;
416
+
417
+ /** Mouse events suppressed during touch (capture phase on canvas container). */
418
+ const SUPPRESSED_MOUSE_EVENTS = [
419
+ 'mousedown',
420
+ 'mouseup',
421
+ 'mouseover',
422
+ 'mouseout',
423
+ 'click',
424
+ 'dblclick',
425
+ ];
426
+
427
+ /**
428
+ * Tool end events whose `originalEvent` (touchend with empty `touches`) gets
429
+ * passed to subsequent `dragging.init` / `activate*` calls. Patched at high
430
+ * priority to a synthetic TouchEvent with valid coordinates from `changedTouches`.
431
+ */
432
+ const PATCHED_TOOL_EVENTS = [
433
+ 'lasso.selection.end', // → activateLasso(event.originalEvent)
434
+ 'spaceTool.selection.end', // → activateMakeSpace(event.originalEvent)
435
+ 'spaceTool.ended', // → activateSelection(event.originalEvent) after make-space
436
+ ];
437
+
438
+ /**
439
+ * Mouse event suppression — prevents browser-synthesized mouse events
440
+ * (click from tap, etc.) from firing during and shortly after a touch.
441
+ *
442
+ * Uses capture-phase listeners on the canvas container, scoped to bpmn-js.
443
+ * Does NOT affect document-level handlers (like Dragging's), which is correct.
444
+ *
445
+ * @param {() => Element} getContainer — accessor for the canvas container
446
+ * (lazy: container may not exist when this is constructed)
447
+ * @returns {{ start, schedule, end, destroy }}
448
+ */
449
+ function createMouseSuppression(getContainer) {
450
+ let suppressing = false;
451
+ let timer = null;
452
+
453
+ function stopEvent(e) {
454
+ e.preventDefault();
455
+ e.stopPropagation();
456
+ e.stopImmediatePropagation();
457
+ }
458
+
459
+ function start() {
460
+ if (suppressing) return;
461
+ const container = getContainer();
462
+ if (!container) return;
463
+ suppressing = true;
464
+ SUPPRESSED_MOUSE_EVENTS.forEach((type) => {
465
+ container.addEventListener(type, stopEvent, true);
466
+ });
467
+ }
468
+
469
+ function schedule() {
470
+ clearTimeout(timer);
471
+ timer = setTimeout(end, MOUSE_SUPPRESSION_MS);
472
+ }
473
+
474
+ function end() {
475
+ if (!suppressing) return;
476
+ const container = getContainer();
477
+ if (!container) {
478
+ suppressing = false;
479
+ return;
480
+ }
481
+ suppressing = false;
482
+ SUPPRESSED_MOUSE_EVENTS.forEach((type) => {
483
+ container.removeEventListener(type, stopEvent, true);
484
+ });
485
+ }
486
+
487
+ function destroy() {
488
+ clearTimeout(timer);
489
+ end();
490
+ }
491
+
492
+ return { start, schedule, end, destroy };
493
+ }
494
+
495
+ /**
496
+ * Touch drag hover tracking.
497
+ *
498
+ * On mouse, `mouseover`/`mouseout` events fire as the cursor moves and HoverFix
499
+ * sets `dragging.hover()` for the drag system. On touch, those events don't fire
500
+ * (no hover concept). This module mirrors HoverFix._findTargetGfx specifically
501
+ * for touch — it listens to `drag.move` and uses `document.elementFromPoint()`
502
+ * to find the BPMN element under the finger, then calls `dragging.hover()/out()`.
503
+ *
504
+ * NOTE: HoverFix explicitly bails on non-MouseEvent — that's why we need this.
505
+ *
506
+ * @param {EventBus} eventBus
507
+ * @param {Dragging} dragging
508
+ * @param {ElementRegistry} elementRegistry
509
+ * @param {Canvas} canvas
510
+ * @returns {{ destroy: () => void }}
511
+ */
512
+ function createHoverTracking(eventBus, dragging, elementRegistry, canvas) {
513
+
514
+ // lastHover stays null until the first drag.move with a hit; comparing
515
+ // null !== element on first move correctly fires the initial hover.
516
+ let lastHover = null;
517
+
518
+ // Match either '.djs-element' (specific BPMN element) or 'svg' (canvas root).
519
+ // SVG fallback handles the empty-canvas case where elementFromPoint returns
520
+ // the <svg> itself, which has no .djs-element class.
521
+ function findElementAtPoint(x, y) {
522
+ const target = document.elementFromPoint(x, y);
523
+ if (!target) return null;
524
+
525
+ const gfx = closest(target, '.djs-element', true);
526
+ if (gfx) {
527
+ const element = elementRegistry.get(gfx);
528
+ if (element) return { element, gfx };
529
+ }
530
+
531
+ if (closest(target, 'svg', true)) {
532
+ const root = canvas.getRootElement();
533
+ if (root) {
534
+ return { element: root, gfx: elementRegistry.getGraphics(root) };
535
+ }
536
+ }
537
+
538
+ return null;
539
+ }
540
+
541
+ function updateHover(touch) {
542
+ const hit = findElementAtPoint(touch.clientX, touch.clientY);
543
+
544
+ if (hit && hit.element !== lastHover) {
545
+ if (lastHover) {
546
+ dragging.out({ element: lastHover, gfx: elementRegistry.getGraphics(lastHover) });
547
+ }
548
+ lastHover = hit.element;
549
+ dragging.hover({ element: hit.element, gfx: hit.gfx });
550
+ } else if (!hit && lastHover) {
551
+ dragging.out({ element: lastHover, gfx: elementRegistry.getGraphics(lastHover) });
552
+ lastHover = null;
553
+ }
554
+ }
555
+
556
+ function onDragMove(event) {
557
+ if (!event.isTouch) return;
558
+
559
+ const originalEvent = event.originalEvent;
560
+ if (!originalEvent) return;
561
+
562
+ const touch = originalEvent.touches?.[0] || originalEvent.changedTouches?.[0];
563
+ if (!touch) return;
564
+
565
+ updateHover(touch);
566
+ }
567
+
568
+ // CHANGED: update the hover from the touch itself, before Dragging handles
569
+ // it. Dragging builds each move event from the hover it knows at that
570
+ // moment, so a hover changed on drag.move only reached the next move: a tap
571
+ // (a single move) was judged against the previous element and rejected, and
572
+ // the previous element kept its drop marker. These capture listeners are
573
+ // registered before any drag binds its own, so they run first.
574
+ function onTouch(event) {
575
+ const context = dragging.context();
576
+ if (!context || !context.isTouch) return;
577
+
578
+ const touch = event.touches?.[0];
579
+ if (touch) updateHover(touch);
580
+ }
581
+
582
+ document.addEventListener('touchstart', onTouch, true);
583
+ document.addEventListener('touchmove', onTouch, true);
584
+
585
+ function onDragLifecycleEnd() {
586
+ lastHover = null;
587
+ }
588
+
589
+ eventBus.on('drag.move', onDragMove);
590
+ eventBus.on([ 'drag.end', 'drag.cancel', 'drag.cleanup' ], onDragLifecycleEnd);
591
+
592
+ // EventBus listeners are released when the diagram is destroyed (eventBus is
593
+ // garbage collected with the Modeler), so no explicit destroy is required.
594
+ // Function provided for symmetry/future-proofing.
595
+ return {
596
+ destroy() {
597
+ // CHANGED: the document listeners above are removed here
598
+ document.removeEventListener('touchstart', onTouch, true);
599
+ document.removeEventListener('touchmove', onTouch, true);
600
+ },
601
+ };
602
+ }
603
+
604
+ /**
605
+ * Single-gesture tool mode for connect / lasso / space.
606
+ *
607
+ * Desktop flow is: tap palette, tap canvas, drag, release. Three steps. That
608
+ * two-step canvas/drag pattern does not translate to touch: for connect,
609
+ * `hover.startTarget` updates as the finger moves, so on release `startTarget`
610
+ * is the destination, not the source. For all three tools the "tap to confirm
611
+ * start, then drag" desktop flow becomes a wasted tap on touch.
612
+ *
613
+ * Fix: replace each tool's `activateSelection` / `start` with a flag-setter
614
+ * (`setActiveTool('connect' | 'lasso' | 'space')`). A capture-phase touchstart
615
+ * handler on the canvas SVG then dispatches the touch directly to the real
616
+ * `*.activate*` / `connect.start` method.
617
+ *
618
+ * Touch flow: tap palette, touch + drag + release. Two steps, single gesture.
619
+ *
620
+ * The context pad's "connect" entry knows the source up front (the element the
621
+ * pad is open for). The caller passes it via `setActiveTool('connect', source)`
622
+ * and the dispatcher skips touch-based element discovery.
623
+ *
624
+ * @param {Object} services — { canvas, palette, elementRegistry, rules, connect, lassoTool, spaceTool, globalConnect }
625
+ * @returns {{ setActiveTool, isActive, getActiveTool, attachCanvasInterceptor }}
626
+ */
627
+ /** CHANGED: the index of the waypoint closest to a point. */
628
+ function nearestWaypoint(waypoints, point) {
629
+ let best = 0;
630
+ let bestDistance = Infinity;
631
+ waypoints.forEach((waypoint, index) => {
632
+ const distance = Math.hypot(waypoint.x - point.x, waypoint.y - point.y);
633
+ if (distance < bestDistance) {
634
+ best = index;
635
+ bestDistance = distance;
636
+ }
637
+ });
638
+ return best;
639
+ }
640
+
641
+ function createToolMode(services) {
642
+ const { canvas, palette, elementRegistry, rules, connect, lassoTool, spaceTool, globalConnect, input } = services;
643
+
644
+ let activeTool = null;
645
+ let connectSource = null;
646
+
647
+ // Maps internal tool name → palette entry id (sans `-tool` suffix that
648
+ // diagram-js strips in updateToolHighlight).
649
+ const TOOL_HIGHLIGHT = {
650
+ connect: 'global-connect',
651
+ lasso: 'lasso',
652
+ space: 'space',
653
+ };
654
+
655
+ function setActiveTool(tool, source = null) {
656
+ activeTool = tool;
657
+ connectSource = source;
658
+ if (palette && typeof palette.updateToolHighlight === 'function') {
659
+ palette.updateToolHighlight(tool ? TOOL_HIGHLIGHT[tool] : '');
660
+ }
661
+ const container = canvas.getContainer();
662
+ if (container) {
663
+ container.classList.toggle('djs-touch-tool-active', !!tool);
664
+ }
665
+ }
666
+
667
+ // Replace tool activation methods with flag-setters. The dispatcher will
668
+ // call the real activation methods on the next canvas touch.
669
+ // CHANGED: each one calls the original after a mouse or trackpad press
670
+
671
+ // PATCH: globalConnect.start
672
+ if (globalConnect && connect) {
673
+ const origStart = globalConnect.start;
674
+ globalConnect.start = function() {
675
+ if (input.isMouse()) return origStart.apply(this, arguments);
676
+ setActiveTool('connect');
677
+ };
678
+ }
679
+
680
+ // PATCH: lassoTool.activateSelection
681
+ if (lassoTool) {
682
+ const origActivate = lassoTool.activateSelection;
683
+ lassoTool.activateSelection = function() {
684
+ if (input.isMouse()) return origActivate.apply(this, arguments);
685
+ setActiveTool('lasso');
686
+ };
687
+ }
688
+
689
+ // PATCH: spaceTool.activateSelection
690
+ if (spaceTool) {
691
+ const origActivate = spaceTool.activateSelection;
692
+ spaceTool.activateSelection = function(event, autoActivate, reactivate) {
693
+ if (input.isMouse()) return origActivate.apply(this, arguments);
694
+ // CHANGED: diagram-js reactivates the tool after each make space, for a
695
+ // mouse that leaves it with Escape. By touch it ends after one gesture,
696
+ // as the lasso does, or every later touch on the canvas would make space.
697
+ if (reactivate) {
698
+ setActiveTool(null);
699
+ return;
700
+ }
701
+ setActiveTool('space');
702
+ };
703
+ }
704
+
705
+ /**
706
+ * Attach a capture-phase touchstart listener on the canvas SVG to dispatch
707
+ * to the active tool's real activation method.
708
+ *
709
+ * @param {SVGElement} svg
710
+ * @returns {() => void} cleanup
711
+ */
712
+ function attachCanvasInterceptor(svg) {
713
+ function handleToolModeTouch(e) {
714
+ if (!activeTool) return;
715
+ if (e.touches.length !== 1) return;
716
+
717
+ if (activeTool === 'connect') {
718
+ let element = connectSource;
719
+ if (!element) {
720
+
721
+ // Palette flow: discover source from touch position
722
+ const touch = e.touches[0];
723
+ const target = document.elementFromPoint(touch.clientX, touch.clientY);
724
+ if (!target) return;
725
+ const gfx = closest(target, '.djs-element', true);
726
+ if (!gfx) return;
727
+ element = elementRegistry.get(gfx);
728
+ if (!element || !element.parent) return; // skip root
729
+ if (rules && !rules.allowed('connection.start', { source: element })) return;
730
+ }
731
+ setActiveTool(null);
732
+ e.preventDefault();
733
+ e.stopPropagation();
734
+ connect.start(e, element);
735
+ } else if (activeTool === 'lasso') {
736
+ setActiveTool(null);
737
+ e.preventDefault();
738
+ e.stopPropagation();
739
+ lassoTool.activateLasso(e, true);
740
+ } else if (activeTool === 'space') {
741
+ setActiveTool(null);
742
+ e.preventDefault();
743
+ e.stopPropagation();
744
+ spaceTool.activateMakeSpace(e);
745
+ }
746
+ }
747
+ svg.addEventListener('touchstart', handleToolModeTouch, { passive: false, capture: true });
748
+ return () => svg.removeEventListener('touchstart', handleToolModeTouch, { capture: true });
749
+ }
750
+
751
+ return {
752
+ setActiveTool,
753
+ isActive: () => !!activeTool,
754
+ getActiveTool: () => activeTool,
755
+ attachCanvasInterceptor,
756
+ };
757
+ }
758
+
759
+ /**
760
+ * Patch `event.originalEvent` on tool end events.
761
+ *
762
+ * Several diagram-js tools (LassoTool, SpaceTool) read `event.originalEvent`
763
+ * from drag end events and pass it forward to `dragging.init` / `activate*`.
764
+ * On touch, `event.originalEvent` is a touchend with empty `touches` →
765
+ * `toPoint()` returns `{x: undefined, y: undefined}` → NaN propagates through
766
+ * SVG transforms and crashes (`setTranslate` non-finite, `<rect> NaN`).
767
+ *
768
+ * Fix: at high priority (before tool handlers), replace `event.originalEvent`
769
+ * with a real `TouchEvent('touchstart')` carrying the same touches from
770
+ * `changedTouches`. The synthetic event has populated `touches`, passes
771
+ * `isTouchEvent()`, and `target` is preserved via `Object.defineProperty`
772
+ * (target is read-only on Event prototype).
773
+ *
774
+ * @param {EventBus} eventBus
775
+ */
776
+ function installToolEventPatcher(eventBus) {
777
+ eventBus.on(PATCHED_TOOL_EVENTS, TOOL_EVENT_PRIORITY, function(event) {
778
+ const orig = event.originalEvent;
779
+ if (!orig || typeof TouchEvent === 'undefined') return;
780
+ if (!(orig instanceof TouchEvent)) return;
781
+ if (orig.touches?.length) return; // already has populated touches
782
+
783
+ const touches = Array.from(orig.changedTouches || []);
784
+ if (!touches.length) return;
785
+
786
+ const patched = new TouchEvent('touchstart', {
787
+ bubbles: true,
788
+ cancelable: true,
789
+ touches,
790
+ changedTouches: touches,
791
+ targetTouches: touches,
792
+ });
793
+ Object.defineProperty(patched, 'target', { value: orig.target });
794
+ event.originalEvent = patched;
795
+ });
796
+ }
797
+
798
+ /**
799
+ * Minimap touch support via mouse event synthesis.
800
+ *
801
+ * `diagram-js-minimap` uses ONLY mouse events. It binds `mousedown` on its
802
+ * container/svg, then `mousemove`/`mouseup` on `document`. Since it doesn't
803
+ * register any touch handlers, we synthesize mouse events from touch events
804
+ * on the `.djs-minimap` container.
805
+ *
806
+ * This is the ONE place mouse synthesis is correct — minimap is a self-
807
+ * contained mouse-only component with no touch handlers to conflict with.
808
+ *
809
+ * @param {Element} minimapEl — the .djs-minimap DOM element
810
+ * @returns {() => void} cleanup function
811
+ */
812
+ function attachMinimapTouchBridge(minimapEl) {
813
+ function synthMouse(type, touch) {
814
+ return new MouseEvent(type, {
815
+ bubbles: true,
816
+ cancelable: true,
817
+ clientX: touch.clientX,
818
+ clientY: touch.clientY,
819
+ button: 0,
820
+ });
821
+ }
822
+
823
+ let activeTouch = null;
824
+
825
+ function onTouchStart(e) {
826
+ if (e.touches.length !== 1) return;
827
+ activeTouch = e.touches[0];
828
+ e.target.dispatchEvent(synthMouse('mousedown', activeTouch));
829
+ e.preventDefault();
830
+ }
831
+
832
+ function onTouchMove(e) {
833
+ if (!activeTouch) return;
834
+ const t = e.touches[0];
835
+ if (t) {
836
+
837
+ // mousemove dispatched on document — that's where minimap binds it
838
+ document.dispatchEvent(synthMouse('mousemove', t));
839
+ }
840
+ e.preventDefault();
841
+ }
842
+
843
+ function onTouchEnd(e) {
844
+ if (!activeTouch) return;
845
+ const t = e.changedTouches[0];
846
+ if (t) {
847
+ document.dispatchEvent(synthMouse('mouseup', t));
848
+ }
849
+ activeTouch = null;
850
+ }
851
+
852
+ const opts = { passive: false };
853
+ minimapEl.addEventListener('touchstart', onTouchStart, opts);
854
+ minimapEl.addEventListener('touchmove', onTouchMove, opts);
855
+ minimapEl.addEventListener('touchend', onTouchEnd, opts);
856
+ minimapEl.addEventListener('touchcancel', onTouchEnd, opts);
857
+
858
+ return function cleanup() {
859
+ minimapEl.removeEventListener('touchstart', onTouchStart, opts);
860
+ minimapEl.removeEventListener('touchmove', onTouchMove, opts);
861
+ minimapEl.removeEventListener('touchend', onTouchEnd, opts);
862
+ minimapEl.removeEventListener('touchcancel', onTouchEnd, opts);
863
+ };
864
+ }
865
+
866
+ /**
867
+ * Detect whether the current device uses touch as its primary input.
868
+ *
869
+ * Uses the `(pointer: coarse)` media query, which is the standard CSS-spec
870
+ * way to detect "primary input is coarse" (touch). This correctly handles:
871
+ *
872
+ * - Mobile phones / tablets → true (primary input is touch)
873
+ * - Desktop with mouse → false
874
+ * - Laptops with touchscreen + trackpad → false (primary is the trackpad,
875
+ * not touch — we don't want to break mouse interactions)
876
+ * - iPad with attached keyboard/mouse → still true (primary is the screen)
877
+ *
878
+ * The plugin's monkey-patches REPLACE several diagram-js methods (e.g.
879
+ * globalConnect.start, lassoTool.activateSelection) with touch-only flag-setters.
880
+ * Activating those on a mouse-primary device would break the mouse tool flow.
881
+ * Returning false here causes services to early-return without patching anything.
882
+ *
883
+ * @returns {boolean}
884
+ */
885
+ function isTouchPrimaryDevice() {
886
+ if (typeof window === 'undefined') return false;
887
+ if (typeof window.matchMedia !== 'function') return false;
888
+ return window.matchMedia('(pointer: coarse)').matches;
889
+ }
890
+
891
+ /**
892
+ * Main service. Wires touch gestures to diagram-js APIs by composing focused
893
+ * modules from `recognizers/`, `patches/`, `bridges/` and `util/`.
894
+ *
895
+ * Search for `// PATCH:` to find every monkey-patch and the bug it fixes.
896
+ *
897
+ * `_touchFix` is unused at runtime but listed in $inject so diagram-js eagerly
898
+ * instantiates the TouchFix service before this one (Safari iOS workaround).
899
+ */
900
+ // CHANGED: the lint rule for the unused, injected TouchFix is turned off here
901
+ // eslint-disable-next-line no-unused-vars
902
+ function TouchInteraction(injector, canvas, eventBus, elementRegistry, interactionEvents, _touchFix) {
903
+
904
+ // --- Auto-detect: skip on mouse-primary devices ---
905
+ // The plugin's monkey-patches replace tool activation methods with touch-only
906
+ // flag-setters; activating them on desktop would break the mouse tool flow.
907
+ // Use (pointer: coarse) media query to detect touch-primary devices.
908
+ if (!isTouchPrimaryDevice()) return;
909
+
910
+ // --- Required services ---
911
+ const dragging = injector.get('dragging', false);
912
+ const move = injector.get('move', false);
913
+
914
+ // --- Optional services (some only present in Modeler, not Viewer) ---
915
+ const palette = injector.get('palette', false);
916
+ const contextPad = injector.get('contextPad', false);
917
+ const connect = injector.get('connect', false);
918
+ const globalConnect = injector.get('globalConnect', false);
919
+ const lassoTool = injector.get('lassoTool', false);
920
+ const spaceTool = injector.get('spaceTool', false);
921
+ const rules = injector.get('rules', false);
922
+ const resizeHandles = injector.get('resizeHandles', false);
923
+ const resize = injector.get('resize', false);
924
+
925
+ const cleanupFns = [];
926
+
927
+ // --- Mouse suppression: prevent ghost click/mousedown after touches ---
928
+ const suppression = createMouseSuppression(() => canvas.getContainer());
929
+
930
+ // --- Hover tracking: HoverFix bails on non-MouseEvent → reimplement for touch ---
931
+ if (dragging) {
932
+ // CHANGED: destroyed with the diagram, since it now listens on the document
933
+ const hoverTracking = createHoverTracking(eventBus, dragging, elementRegistry, canvas);
934
+ cleanupFns.push(() => hoverTracking.destroy());
935
+ }
936
+
937
+ // CHANGED: removed with the diagram, since it listens on the document
938
+ const input = createInputTracker();
939
+ cleanupFns.push(() => input.destroy());
940
+
941
+ // --- Tool mode: single-gesture connect/lasso/space ---
942
+ // setActiveTool(tool, source?) — replaces tool activation methods + dispatches canvas touches
943
+ const toolMode = createToolMode({
944
+ canvas, palette, elementRegistry, rules,
945
+ connect, lassoTool, spaceTool, globalConnect,
946
+ input,
947
+ });
948
+
949
+ // --- Tool event patcher: fix NaN coords from touchend originalEvent ---
950
+ installToolEventPatcher(eventBus);
951
+
952
+ // --- PATCH: ResizeHandles.makeDraggable ---
953
+ // Original binds touchstart but startResize() bails on isPrimaryButton (TouchEvent
954
+ // has no .button → false). Replace with version that skips the check on touch.
955
+ if (resizeHandles && resize) {
956
+ resizeHandles.makeDraggable = function(element, gfx, direction) {
957
+ function startResize(event) {
958
+ resize.activate(event, element, direction);
959
+ }
960
+ gfx.addEventListener('mousedown', function(event) {
961
+ if (event.button === 0) startResize(event);
962
+ });
963
+ gfx.addEventListener('touchstart', startResize, { passive: false });
964
+ };
965
+ }
966
+
967
+ // --- PATCH: dragging.init injects keepSelection for resize ---
968
+ // Without keepSelection, move(event, true) clears selection → ResizeHandles
969
+ // removes the handle DOM mid-drag → browser fires touchcancel on the removed
970
+ // target → drag ends immediately. With keepSelection, handles stay in DOM.
971
+ if (dragging) {
972
+ const origInit = dragging.init;
973
+ dragging.init = function(event, relativeTo, prefix, options) {
974
+ if (prefix === 'resize') {
975
+ options = Object.assign({ keepSelection: true }, options || {});
976
+ }
977
+ return origInit.call(this, event, relativeTo, prefix, options);
978
+ };
979
+ }
980
+
981
+ // --- PATCH: connect.start substitutes synthetic TouchEvent for null event ---
982
+ // GlobalConnect calls connect.start(null, ...) — null event makes Dragging
983
+ // bind mouse handlers → touch events never caught.
984
+ // NOTE: this patches `connect`, but is only triggered when activeTool='connect'
985
+ // (which only `globalConnect.start` can set, see toolMode.js). The two
986
+ // patches are co-dependent — if globalConnect is missing the patch is dead code.
987
+ if (connect) {
988
+ const origConnectStart = connect.start;
989
+ connect.start = function(event, start, connectionStart, autoActivate) {
990
+ // CHANGED: not after a mouse or trackpad press, which needs the mouse drag
991
+ if (!event && !input.isMouse()) {
992
+
993
+ // 0,0 matches desktop's null event behavior (globalStart={0,0}).
994
+ // Actual connection start position is in `connectionStart` arg, stored in data.
995
+ const synthetic = createSyntheticTouchEvent('touchstart', canvas._svg, 0, 0);
996
+ if (synthetic) event = synthetic;
997
+ }
998
+ return origConnectStart.call(this, event, start, connectionStart, autoActivate);
999
+ };
1000
+ }
1001
+
1002
+ // CHANGED: moves the segment or bendpoint handle under a touch
1003
+ const connectionSegmentMove = injector.get('connectionSegmentMove', false);
1004
+ const bendpointMove = injector.get('bendpointMove', false);
1005
+
1006
+ function startConnectionHandleMove(target, connection, event) {
1007
+ const dragger = closest(target, '.djs-segment-dragger', true);
1008
+ if (dragger && connectionSegmentMove) {
1009
+ connectionSegmentMove.start(event, connection, Number(dragger.getAttribute('data-segment-idx')));
1010
+ return;
1011
+ }
1012
+
1013
+ const bendpoint = closest(target, '.djs-bendpoint', true);
1014
+ if (bendpoint && bendpointMove && !bendpoint.classList.contains('floating')) {
1015
+ const matrix = bendpoint.transform.baseVal.consolidate()?.matrix;
1016
+ if (matrix) {
1017
+ const index = nearestWaypoint(connection.waypoints, { x: matrix.e, y: matrix.f });
1018
+ bendpointMove.start(event, connection, index, false);
1019
+ return;
1020
+ }
1021
+ }
1022
+
1023
+ // anything else: let diagram-js decide from the position, as for a mouse
1024
+ Object.defineProperty(event, 'button', { value: 0 });
1025
+ interactionEvents.fire('element.mousedown', event, connection);
1026
+ }
1027
+
1028
+ // --- Canvas gesture setup (runs once per diagram) ---
1029
+ eventBus.on('canvas.init', function(event) {
1030
+ const svg = event.svg;
1031
+
1032
+ // Tool-mode capture interceptor must run BEFORE the bubble-phase canvas
1033
+ // recognizer below, so that tap-on-element-during-tool-mode is handled
1034
+ // by the tool dispatcher (which calls preventDefault + stopPropagation).
1035
+ cleanupFns.push(toolMode.attachCanvasInterceptor(svg));
1036
+
1037
+ // panActive separates "canvas pan" (canvas.scroll) from "element drag"
1038
+ // (move.start). Both come from the same recognizer onPanStart callback,
1039
+ // distinguished by whether the touch target is a .djs-element with parent.
1040
+ let panActive = false;
1041
+ let lastPanX = 0;
1042
+ let lastPanY = 0;
1043
+
1044
+ // pinchInitialZoom is captured at pinchStart so onPinchMove can compute
1045
+ // newZoom = initialZoom * cumulativeScale (recognizer reports cumulative).
1046
+ let pinchInitialZoom = 1;
1047
+
1048
+ const cleanup = createGestureRecognizer(svg, {
1049
+ onTap({ target, originalEvent }) {
1050
+ suppression.start();
1051
+ suppression.schedule();
1052
+ const gfx = closest(target, '.djs-element', true);
1053
+ const element = gfx ? elementRegistry.get(gfx) : elementRegistry.getAll().find(e => !e.parent);
1054
+ if (element) {
1055
+ interactionEvents.fire('element.click', asPrimaryButtonEvent(originalEvent), element);
1056
+ }
1057
+ },
1058
+
1059
+ onDoubleTap({ target, originalEvent }) {
1060
+ suppression.start();
1061
+ suppression.schedule();
1062
+ const gfx = closest(target, '.djs-element', true);
1063
+ const element = gfx ? elementRegistry.get(gfx) : null;
1064
+ if (element) {
1065
+ interactionEvents.fire('element.dblclick', asPrimaryButtonEvent(originalEvent), element);
1066
+ }
1067
+ },
1068
+
1069
+ onPanStart({ center, target, originalEvent, startEvent }) {
1070
+ suppression.start();
1071
+ const gfx = closest(target, '.djs-element', true);
1072
+ const element = gfx ? elementRegistry.get(gfx) : null;
1073
+
1074
+ // CHANGED: a drag on a connection's bendpoint or segment handle moves
1075
+ // it, starting where the finger went down. diagram-js starts these
1076
+ // from element.mousedown and looks for the line within 10 units of
1077
+ // the pointer, which the larger touch handles go beyond.
1078
+ const bendpoints = closest(target, '.djs-bendpoints', true);
1079
+ const connection = bendpoints ? elementRegistry.get(bendpoints.getAttribute('data-element-id')) : null;
1080
+ if (connection && connection.waypoints) {
1081
+ startConnectionHandleMove(target, connection, startEvent || originalEvent);
1082
+ return;
1083
+ }
1084
+
1085
+ if (element && element.parent && move) {
1086
+
1087
+ // Drag a BPMN element — diagram-js Move handles the rest
1088
+ // CHANGED: from where the finger went down, not from where it
1089
+ // passed the pan threshold, so the shape stays under the finger
1090
+ move.start(startEvent || originalEvent, element, true);
1091
+ } else {
1092
+
1093
+ // Pan the canvas viewport
1094
+ panActive = true;
1095
+ lastPanX = center.x;
1096
+ lastPanY = center.y;
1097
+ }
1098
+ },
1099
+
1100
+ onPanMove({ center }) {
1101
+ if (!panActive) return;
1102
+ const dx = center.x - lastPanX;
1103
+ const dy = center.y - lastPanY;
1104
+ if (!isFinite(dx) || !isFinite(dy)) return;
1105
+ lastPanX = center.x;
1106
+ lastPanY = center.y;
1107
+ canvas.scroll({ dx, dy });
1108
+ },
1109
+
1110
+ onPanEnd() {
1111
+ panActive = false;
1112
+ suppression.schedule();
1113
+ },
1114
+
1115
+ onPress() {
1116
+
1117
+ // Long press on element — drag starts when recognizer transitions to PAN
1118
+ },
1119
+
1120
+ onPinchStart() {
1121
+ suppression.start();
1122
+ pinchInitialZoom = canvas.zoom();
1123
+ },
1124
+
1125
+ onPinchMove({ center, scale }) {
1126
+ if (!isFinite(scale) || !isFinite(center.x) || !isFinite(center.y)) return;
1127
+ const newZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, pinchInitialZoom * scale));
1128
+ canvas.zoom(newZoom, center);
1129
+ },
1130
+
1131
+ onPinchEnd() {
1132
+ suppression.schedule();
1133
+ },
1134
+ });
1135
+
1136
+ cleanupFns.push(cleanup);
1137
+
1138
+ // --- Minimap touch bridge ---
1139
+ // Wired here (vs. its own canvas.init listener) so init order is obvious.
1140
+ const minimapEl = canvas.getContainer()?.querySelector('.djs-minimap');
1141
+ if (minimapEl) {
1142
+ cleanupFns.push(attachMinimapTouchBridge(minimapEl));
1143
+ }
1144
+ });
1145
+
1146
+ // --- Palette touch ---
1147
+ if (palette) {
1148
+ eventBus.on('palette.create', function(event) {
1149
+ const cleanup = createButtonRecognizer(event.container, palette, {
1150
+ onTouch: () => {
1151
+ suppression.start();
1152
+ suppression.schedule();
1153
+
1154
+ // Reset any active tool — replaced activate methods will set it back
1155
+ // if this tap activates a tool (connect/lasso/space).
1156
+ toolMode.setActiveTool(null);
1157
+ },
1158
+ });
1159
+ cleanupFns.push(cleanup);
1160
+ });
1161
+ }
1162
+
1163
+ // --- Context pad touch ---
1164
+ // contextPad.create fires on every element select — clean up the previous recognizer
1165
+ let contextPadCleanup = null;
1166
+ let contextPadTarget = null;
1167
+
1168
+ if (contextPad) {
1169
+ eventBus.on('contextPad.create', function(event) {
1170
+ if (contextPadCleanup) {
1171
+ contextPadCleanup();
1172
+ contextPadCleanup = null;
1173
+ }
1174
+ contextPadTarget = event.target || null;
1175
+
1176
+ contextPadCleanup = createButtonRecognizer(event.pad, contextPad, {
1177
+ onTouch: () => {
1178
+ suppression.start();
1179
+ suppression.schedule();
1180
+ },
1181
+ onTapExtra: (button) => {
1182
+
1183
+ // Short-circuit the connect entry: standard flow calls connect.start
1184
+ // immediately on tap, but the user hasn't moved their finger yet →
1185
+ // drag waits for movement → user must touch canvas again to continue.
1186
+ // Mobile: tap pad → touch + drag from element to target = single gesture.
1187
+ if (button.getAttribute('data-action') === 'connect' && contextPadTarget && connect) {
1188
+ toolMode.setActiveTool('connect', contextPadTarget);
1189
+
1190
+ // Close the context pad so it doesn't obstruct the next touch
1191
+ if (typeof contextPad.close === 'function') contextPad.close();
1192
+ return true; // skip default trigger('click')
1193
+ }
1194
+ return false;
1195
+ },
1196
+ });
1197
+ });
1198
+
1199
+ // Clear stale target reference when context pad is closed (defensive)
1200
+ eventBus.on([ 'contextPad.close', 'selection.changed' ], function() {
1201
+
1202
+ // Don't clear immediately — selection.changed fires before contextPad.create.
1203
+ // Target will be overwritten on next contextPad.create. Only clear on close.
1204
+ if (!contextPad.isOpen?.()) {
1205
+ contextPadTarget = null;
1206
+ }
1207
+ });
1208
+ }
1209
+
1210
+ // --- Cleanup on diagram destroy ---
1211
+ eventBus.on('diagram.destroy', function() {
1212
+ suppression.destroy();
1213
+ if (contextPadCleanup) contextPadCleanup();
1214
+ cleanupFns.forEach(fn => fn());
1215
+ cleanupFns.length = 0;
1216
+ });
1217
+ }
1218
+
1219
+ TouchInteraction.$inject = [
1220
+ 'injector', 'canvas', 'eventBus',
1221
+ 'elementRegistry', 'interactionEvents', 'touchFix',
1222
+ ];
1223
+
1224
+ /**
1225
+ * Safari iOS workaround: touchstart does not fire on empty SVG areas.
1226
+ *
1227
+ * Adding invisible 10x10 rects at far-off coordinates extends the SVG's
1228
+ * bounding box, which makes touchstart events fire reliably anywhere
1229
+ * inside the canvas. Two opposite corners (top-right and top-left at
1230
+ * y=10000) are sufficient to span the diagonal — additional rects would
1231
+ * be redundant. Ported from the old diagram-js TouchInteractionEvents.
1232
+ *
1233
+ * `_canvas` is injected (not used at runtime) so diagram-js eagerly
1234
+ * instantiates the Canvas service before this one — guarantees `canvas.init`
1235
+ * fires after our listener is registered.
1236
+ */
1237
+
1238
+ function TouchFix(_canvas, eventBus) {
1239
+
1240
+ // Skip on mouse-primary devices — the workaround is iOS-specific.
1241
+ if (!isTouchPrimaryDevice()) return;
1242
+
1243
+ eventBus.on('canvas.init', function(event) {
1244
+ const svg = event.svg;
1245
+
1246
+ function addRect(x, y) {
1247
+ const rect = create('rect');
1248
+ attr(rect, {
1249
+ x, y,
1250
+ width: 10,
1251
+ height: 10,
1252
+ fill: 'none',
1253
+ stroke: 'none',
1254
+ 'pointer-events': 'all',
1255
+ });
1256
+ append(svg, rect);
1257
+ }
1258
+
1259
+ addRect(-1e4, 10000);
1260
+ addRect(10000, 10000);
1261
+ });
1262
+ }
1263
+
1264
+ TouchFix.$inject = [ 'canvas', 'eventBus' ];
1265
+
1266
+ function __inject(css){if(typeof document != "undefined")document.head.appendChild(document.createElement("style")).textContent=css;}
1267
+
1268
+ __inject(".bjs-container,.bjs-container *,.djs-palette,.djs-palette *{touch-action:none;}.djs-touch-tool-active .djs-svg{cursor:crosshair;}");
1269
+
1270
+ // CHANGED: the parts are exported, and index.js makes the module of them
1271
+ export {
1272
+ InteractionEventsModule,
1273
+ TouchInteraction,
1274
+ TouchFix,
1275
+ nearestWaypoint
1276
+ };