@statelyai/flow 0.0.1 → 0.1.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,2534 @@
1
+ import { createStore } from "@xstate/store";
2
+ import { undoRedo } from "@xstate/store/undo";
3
+ import { enableMapSet, produce } from "immer";
4
+ //#region src/viewport/index.ts
5
+ /** Create a default viewport (origin, no zoom) */
6
+ function createViewport(x = 0, y = 0, zoom = 1) {
7
+ return {
8
+ x,
9
+ y,
10
+ zoom
11
+ };
12
+ }
13
+ /**
14
+ * Convert viewport to SVG transform string.
15
+ * Use on the root <g> wrapping all entities.
16
+ *
17
+ * @example
18
+ * <g transform={toSVGTransform(viewport)}>...</g>
19
+ */
20
+ function toSVGTransform(viewport) {
21
+ return `translate(${viewport.x}, ${viewport.y}) scale(${viewport.zoom})`;
22
+ }
23
+ /**
24
+ * Convert viewport + container size to an SVG viewBox string.
25
+ *
26
+ * @example
27
+ * <svg viewBox={toViewBox(viewport, { width: 800, height: 600 })}>...</svg>
28
+ */
29
+ function toViewBox(viewport, size) {
30
+ return `${-viewport.x / viewport.zoom} ${-viewport.y / viewport.zoom} ${size.width / viewport.zoom} ${size.height / viewport.zoom}`;
31
+ }
32
+ /** Convert a screen-space point to canvas-space */
33
+ function screenToCanvas(point, viewport) {
34
+ return {
35
+ x: (point.x - viewport.x) / viewport.zoom,
36
+ y: (point.y - viewport.y) / viewport.zoom
37
+ };
38
+ }
39
+ /** Convert a canvas-space point to screen-space */
40
+ function canvasToScreen(point, viewport) {
41
+ return {
42
+ x: point.x * viewport.zoom + viewport.x,
43
+ y: point.y * viewport.zoom + viewport.y
44
+ };
45
+ }
46
+ /** Get the canvas-space bounding rect of what's visible on screen */
47
+ function getVisibleBounds(viewport, size) {
48
+ return {
49
+ x: -viewport.x / viewport.zoom,
50
+ y: -viewport.y / viewport.zoom,
51
+ width: size.width / viewport.zoom,
52
+ height: size.height / viewport.zoom
53
+ };
54
+ }
55
+ /**
56
+ * Compute a viewport that fits the given bounds into the given screen size.
57
+ */
58
+ function viewportForBounds(bounds, size, options = {}) {
59
+ const { padding = .1, minZoom = .1, maxZoom = 2 } = options;
60
+ const paddedWidth = bounds.width * (1 + padding);
61
+ const paddedHeight = bounds.height * (1 + padding);
62
+ if (paddedWidth === 0 || paddedHeight === 0) return {
63
+ x: 0,
64
+ y: 0,
65
+ zoom: 1
66
+ };
67
+ const zoomX = size.width / paddedWidth;
68
+ const zoomY = size.height / paddedHeight;
69
+ const zoom = Math.min(Math.max(Math.min(zoomX, zoomY), minZoom), maxZoom);
70
+ const centerX = bounds.x + bounds.width / 2;
71
+ const centerY = bounds.y + bounds.height / 2;
72
+ return {
73
+ x: size.width / 2 - centerX * zoom,
74
+ y: size.height / 2 - centerY * zoom,
75
+ zoom
76
+ };
77
+ }
78
+ /** Pan viewport by a delta */
79
+ function panBy(viewport, delta) {
80
+ return {
81
+ x: viewport.x + delta.x,
82
+ y: viewport.y + delta.y,
83
+ zoom: viewport.zoom
84
+ };
85
+ }
86
+ /** Zoom to a specific level, keeping a screen-space point fixed */
87
+ function zoomTo(viewport, zoom, center) {
88
+ const clampedZoom = zoom;
89
+ const ratio = clampedZoom / viewport.zoom;
90
+ return {
91
+ x: center.x - (center.x - viewport.x) * ratio,
92
+ y: center.y - (center.y - viewport.y) * ratio,
93
+ zoom: clampedZoom
94
+ };
95
+ }
96
+ /** Clamp zoom to min/max bounds */
97
+ function clampZoom(zoom, minZoom, maxZoom) {
98
+ return Math.min(Math.max(zoom, minZoom), maxZoom);
99
+ }
100
+ //#endregion
101
+ //#region src/spatial.ts
102
+ /** Resolved visual position: layout position + drag offset */
103
+ function resolvedPosition(node) {
104
+ return {
105
+ x: node.x + (node.dx ?? 0),
106
+ y: node.y + (node.dy ?? 0)
107
+ };
108
+ }
109
+ /** Resolved visual bounds: layout position + drag offset + dimensions.
110
+ * Uses style.customWidth/customHeight when set (from resize), otherwise inherent width/height. */
111
+ function resolvedBounds(node) {
112
+ return {
113
+ x: node.x + (node.dx ?? 0),
114
+ y: node.y + (node.dy ?? 0),
115
+ width: node.style?.customWidth ?? node.width,
116
+ height: node.style?.customHeight ?? node.height
117
+ };
118
+ }
119
+ /** Resolved bounds with visual snap — for rendering during drag.
120
+ * Applies grid snap and/or entity snap offset. */
121
+ function snappedBounds(node, grid, snapOffset) {
122
+ let x = node.x + (node.dx ?? 0);
123
+ let y = node.y + (node.dy ?? 0);
124
+ if (snapOffset) {
125
+ x += snapOffset.x;
126
+ y += snapOffset.y;
127
+ }
128
+ if (grid) {
129
+ x = snapToGrid(x, grid[0]);
130
+ y = snapToGrid(y, grid[1]);
131
+ }
132
+ return {
133
+ x,
134
+ y,
135
+ width: node.style?.customWidth ?? node.width,
136
+ height: node.style?.customHeight ?? node.height
137
+ };
138
+ }
139
+ /** Compute bounding rect of all nodes + edge labels (resolved positions) */
140
+ function getGraphBounds(nodes, edges) {
141
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
142
+ for (const n of nodes) {
143
+ const b = resolvedBounds(n);
144
+ minX = Math.min(minX, b.x);
145
+ minY = Math.min(minY, b.y);
146
+ maxX = Math.max(maxX, b.x + b.width);
147
+ maxY = Math.max(maxY, b.y + b.height);
148
+ }
149
+ if (edges) for (const e of edges) {
150
+ if (!e.label) continue;
151
+ const lx = e.label.x + (e.label.dx ?? 0);
152
+ const ly = e.label.y + (e.label.dy ?? 0);
153
+ minX = Math.min(minX, lx);
154
+ minY = Math.min(minY, ly);
155
+ maxX = Math.max(maxX, lx + e.label.width);
156
+ maxY = Math.max(maxY, ly + e.label.height);
157
+ }
158
+ if (!isFinite(minX)) return {
159
+ x: 0,
160
+ y: 0,
161
+ width: 0,
162
+ height: 0
163
+ };
164
+ return {
165
+ x: minX,
166
+ y: minY,
167
+ width: maxX - minX,
168
+ height: maxY - minY
169
+ };
170
+ }
171
+ /** AABB intersection test */
172
+ function rectsIntersect(a, b) {
173
+ return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
174
+ }
175
+ /** Snap a value to the nearest grid increment */
176
+ function snapToGrid(value, gridSize) {
177
+ return Math.round(value / gridSize) * gridSize;
178
+ }
179
+ /** Snap a point to grid */
180
+ function snapPointToGrid(point, gridSize) {
181
+ return {
182
+ x: snapToGrid(point.x, gridSize),
183
+ y: snapToGrid(point.y, gridSize)
184
+ };
185
+ }
186
+ /** Normalize a box (two points) into a Rect with positive width/height */
187
+ function boxToRect(p1, p2) {
188
+ return {
189
+ x: Math.min(p1.x, p2.x),
190
+ y: Math.min(p1.y, p2.y),
191
+ width: Math.abs(p2.x - p1.x),
192
+ height: Math.abs(p2.y - p1.y)
193
+ };
194
+ }
195
+ /** Get bounding rect of specific entities by id */
196
+ function getSelectionBounds(nodes, edges, selection) {
197
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
198
+ for (const n of nodes) {
199
+ if (!selection.has(n.id)) continue;
200
+ const b = resolvedBounds(n);
201
+ minX = Math.min(minX, b.x);
202
+ minY = Math.min(minY, b.y);
203
+ maxX = Math.max(maxX, b.x + b.width);
204
+ maxY = Math.max(maxY, b.y + b.height);
205
+ }
206
+ for (const e of edges) {
207
+ if (!selection.has(e.id) || !e.label) continue;
208
+ const lx = e.label.x + (e.label.dx ?? 0);
209
+ const ly = e.label.y + (e.label.dy ?? 0);
210
+ minX = Math.min(minX, lx);
211
+ minY = Math.min(minY, ly);
212
+ maxX = Math.max(maxX, lx + e.label.width);
213
+ maxY = Math.max(maxY, ly + e.label.height);
214
+ }
215
+ if (!isFinite(minX)) return null;
216
+ return {
217
+ x: minX,
218
+ y: minY,
219
+ width: maxX - minX,
220
+ height: maxY - minY
221
+ };
222
+ }
223
+ /** Determine select mode from a pointer/keyboard event */
224
+ function selectMode(e) {
225
+ return e.shiftKey || e.metaKey || e.ctrlKey ? "multi" : "single";
226
+ }
227
+ /** Does rect `a` fully contain rect `b`? */
228
+ function rectContains(a, b) {
229
+ return b.x >= a.x && b.y >= a.y && b.x + b.width <= a.x + a.width && b.y + b.height <= a.y + a.height;
230
+ }
231
+ const platform = globalThis.navigator?.platform ?? "";
232
+ const isMac = /Mac|iPhone|iPad/.test(platform);
233
+ /**
234
+ * Convert a wheel event into a logarithmic zoom exponent.
235
+ * Accounts for deltaMode (pixels/lines/pages) and trackpad pinch (ctrlKey on macOS).
236
+ * Use as: `newZoom = currentZoom * Math.pow(2, wheelZoomDelta(e))`
237
+ */
238
+ function wheelZoomDelta(e) {
239
+ const factor = e.ctrlKey && isMac ? 10 : 1;
240
+ const modeScale = e.deltaMode === 1 ? .05 : e.deltaMode ? 1 : .002;
241
+ return -e.deltaY * modeScale * factor;
242
+ }
243
+ /**
244
+ * Normalize wheel deltas for panning across browsers.
245
+ * Firefox fires deltaMode=1 (lines) with small values; Chrome fires deltaMode=0 (pixels) with large values.
246
+ */
247
+ function normalizeWheelPan(e) {
248
+ const scale = e.deltaMode === 1 ? 20 : 1;
249
+ return {
250
+ x: -e.deltaX * scale,
251
+ y: -e.deltaY * scale
252
+ };
253
+ }
254
+ /**
255
+ * Detect whether a wheel event is a trackpad pinch-to-zoom gesture.
256
+ * Browsers send wheel events with ctrlKey=true for trackpad pinch.
257
+ */
258
+ function isTrackpadPinch(e) {
259
+ return e.ctrlKey || e.metaKey;
260
+ }
261
+ /**
262
+ * Decide how a wheel event should be handled by a flow canvas.
263
+ *
264
+ * This mirrors the important React Flow / d3-zoom behavior: browser pinch
265
+ * gestures are always consumed over the canvas. Otherwise the whole page can
266
+ * zoom even though the user is interacting with the diagram.
267
+ */
268
+ function wheelInteraction(e, options = {}) {
269
+ if (isTrackpadPinch(e)) {
270
+ if (options.floatingLayerOpen || options.zoomOnPinch === false) return "block";
271
+ return "zoom";
272
+ }
273
+ if (options.floatingLayerOpen) return options.panOnScroll ? "block" : "ignore";
274
+ return options.panOnScroll ? "pan" : "ignore";
275
+ }
276
+ /**
277
+ * Constrain viewport so content can't be panned entirely off-screen.
278
+ * When zoomed out (content smaller than view), centers the content.
279
+ * Matches d3-zoom's defaultConstrain behavior.
280
+ */
281
+ function constrainViewport(viewport, viewportSize, translateExtent) {
282
+ const vx0 = -viewport.x / viewport.zoom;
283
+ const vy0 = -viewport.y / viewport.zoom;
284
+ const vx1 = vx0 + viewportSize.width / viewport.zoom;
285
+ const vy1 = vy0 + viewportSize.height / viewport.zoom;
286
+ const dx0 = vx0 - translateExtent[0].x;
287
+ const dx1 = vx1 - translateExtent[1].x;
288
+ const dy0 = vy0 - translateExtent[0].y;
289
+ const dy1 = vy1 - translateExtent[1].y;
290
+ const tx = dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1);
291
+ const ty = dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1);
292
+ if (tx === 0 && ty === 0) return viewport;
293
+ return {
294
+ x: viewport.x + tx * viewport.zoom,
295
+ y: viewport.y + ty * viewport.zoom,
296
+ zoom: viewport.zoom
297
+ };
298
+ }
299
+ /**
300
+ * Compute auto-pan velocity when dragging near the viewport edge.
301
+ * Returns screen-space delta to apply per frame. Returns {0,0} if cursor isn't near an edge.
302
+ */
303
+ function calcAutoPan(mousePosition, containerBounds, edgeWidth = 25, speed = 10) {
304
+ let dx = 0, dy = 0;
305
+ if (mousePosition.x < edgeWidth) dx = -speed * (1 - mousePosition.x / edgeWidth);
306
+ else if (mousePosition.x > containerBounds.width - edgeWidth) dx = speed * (1 - (containerBounds.width - mousePosition.x) / edgeWidth);
307
+ if (mousePosition.y < edgeWidth) dy = -speed * (1 - mousePosition.y / edgeWidth);
308
+ else if (mousePosition.y > containerBounds.height - edgeWidth) dy = speed * (1 - (containerBounds.height - mousePosition.y) / edgeWidth);
309
+ return {
310
+ x: dx,
311
+ y: dy
312
+ };
313
+ }
314
+ /**
315
+ * Compute anchor transform for positioning overlays relative to a rect.
316
+ * Returns canvas-space position + inverse zoom scale.
317
+ *
318
+ * Offsets are in screen pixels — divided by zoom so they stay constant.
319
+ *
320
+ * Usage (SVG): `transform="translate(${t.x}, ${t.y}) scale(${t.scale})"`
321
+ * Usage (CSS): `transform: translate(${t.x}px, ${t.y}px) scale(${t.scale})`
322
+ */
323
+ function getAnchorTransform(bounds, viewport, anchor) {
324
+ const scale = 1 / viewport.zoom;
325
+ const ax = parseAnchorValue(anchor.x, bounds.width);
326
+ const ay = parseAnchorValue(anchor.y, bounds.height);
327
+ return {
328
+ x: bounds.x + ax + (anchor.offsetX ?? 0) * scale,
329
+ y: bounds.y + ay + (anchor.offsetY ?? 0) * scale,
330
+ scale
331
+ };
332
+ }
333
+ function parseAnchorValue(value, dimension) {
334
+ if (typeof value === "number") return value;
335
+ if (typeof value === "string" && value.endsWith("%")) return parseFloat(value) / 100 * dimension;
336
+ return parseFloat(value) || 0;
337
+ }
338
+ //#endregion
339
+ //#region src/snap.ts
340
+ /**
341
+ * Compute snap lines for a dragged rect against other rects.
342
+ *
343
+ * Checks alignment of left/right/center-x and top/bottom/center-y
344
+ * against all target rects. Optionally checks equal spacing between elements.
345
+ *
346
+ * Returns null if no snap is within threshold.
347
+ */
348
+ function getSnapLines(rect, otherRects, { threshold = 5, enableSpacing = false } = {}) {
349
+ if (otherRects.length === 0) return null;
350
+ const getPoints = (r) => ({
351
+ left: r.x,
352
+ right: r.x + r.width,
353
+ top: r.y,
354
+ bottom: r.y + r.height,
355
+ centerX: r.x + r.width / 2,
356
+ centerY: r.y + r.height / 2
357
+ });
358
+ const rectPoints = getPoints(rect);
359
+ const snapLines = [];
360
+ let snapX = null;
361
+ let snapY = null;
362
+ let minDistX = threshold + 1;
363
+ let minDistY = threshold + 1;
364
+ let spacingGuides = [];
365
+ if (enableSpacing && otherRects.length >= 1) {
366
+ const hasVerticalOverlap = (a, b) => a.y < b.y + b.height && a.y + a.height > b.y;
367
+ const hasHorizontalOverlap = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x;
368
+ for (const target of otherRects) {
369
+ if (!hasVerticalOverlap(rect, target)) continue;
370
+ for (const other of otherRects) {
371
+ if (other === target) continue;
372
+ if (!hasVerticalOverlap(other, target)) continue;
373
+ const gapRight = other.x - (target.x + target.width);
374
+ const gapLeft = target.x - (other.x + other.width);
375
+ if (gapLeft > 0) {
376
+ const snapPos = target.x + target.width + gapLeft;
377
+ const dist = Math.abs(rectPoints.left - snapPos);
378
+ if (dist <= threshold && dist < minDistX) {
379
+ const guideY = (Math.max(rect.y, target.y, other.y) + Math.min(rect.y + rect.height, target.y + target.height, other.y + other.height)) / 2;
380
+ minDistX = dist;
381
+ snapX = snapPos;
382
+ spacingGuides = [{
383
+ axis: "x",
384
+ position: guideY,
385
+ spacing: gapLeft,
386
+ ranges: [{
387
+ start: other.x + other.width,
388
+ end: target.x
389
+ }, {
390
+ start: target.x + target.width,
391
+ end: snapPos
392
+ }]
393
+ }];
394
+ }
395
+ }
396
+ if (gapRight > 0) {
397
+ const snapPos = target.x - gapRight - rect.width;
398
+ const dist = Math.abs(rectPoints.left - snapPos);
399
+ if (dist <= threshold && dist < minDistX) {
400
+ const guideY = (Math.max(rect.y, target.y, other.y) + Math.min(rect.y + rect.height, target.y + target.height, other.y + other.height)) / 2;
401
+ minDistX = dist;
402
+ snapX = snapPos;
403
+ spacingGuides = [{
404
+ axis: "x",
405
+ position: guideY,
406
+ spacing: gapRight,
407
+ ranges: [{
408
+ start: snapPos + rect.width,
409
+ end: target.x
410
+ }, {
411
+ start: target.x + target.width,
412
+ end: other.x
413
+ }]
414
+ }];
415
+ }
416
+ }
417
+ }
418
+ }
419
+ for (const target of otherRects) {
420
+ if (!hasHorizontalOverlap(rect, target)) continue;
421
+ for (const other of otherRects) {
422
+ if (other === target) continue;
423
+ if (!hasHorizontalOverlap(other, target)) continue;
424
+ const gapBelow = other.y - (target.y + target.height);
425
+ const gapAbove = target.y - (other.y + other.height);
426
+ if (gapAbove > 0) {
427
+ const snapPos = target.y + target.height + gapAbove;
428
+ const dist = Math.abs(rectPoints.top - snapPos);
429
+ if (dist <= threshold && dist < minDistY) {
430
+ const guideX = (Math.max(rect.x, target.x, other.x) + Math.min(rect.x + rect.width, target.x + target.width, other.x + other.width)) / 2;
431
+ minDistY = dist;
432
+ snapY = snapPos;
433
+ spacingGuides = spacingGuides.filter((g) => g.axis !== "y");
434
+ spacingGuides.push({
435
+ axis: "y",
436
+ position: guideX,
437
+ spacing: gapAbove,
438
+ ranges: [{
439
+ start: other.y + other.height,
440
+ end: target.y
441
+ }, {
442
+ start: target.y + target.height,
443
+ end: snapPos
444
+ }]
445
+ });
446
+ }
447
+ }
448
+ if (gapBelow > 0) {
449
+ const snapPos = target.y - gapBelow - rect.height;
450
+ const dist = Math.abs(rectPoints.top - snapPos);
451
+ if (dist <= threshold && dist < minDistY) {
452
+ const guideX = (Math.max(rect.x, target.x, other.x) + Math.min(rect.x + rect.width, target.x + target.width, other.x + other.width)) / 2;
453
+ minDistY = dist;
454
+ snapY = snapPos;
455
+ spacingGuides = spacingGuides.filter((g) => g.axis !== "y");
456
+ spacingGuides.push({
457
+ axis: "y",
458
+ position: guideX,
459
+ spacing: gapBelow,
460
+ ranges: [{
461
+ start: snapPos + rect.height,
462
+ end: target.y
463
+ }, {
464
+ start: target.y + target.height,
465
+ end: other.y
466
+ }]
467
+ });
468
+ }
469
+ }
470
+ }
471
+ }
472
+ }
473
+ for (const target of otherRects) {
474
+ const tp = getPoints(target);
475
+ const xChecks = [
476
+ {
477
+ source: rectPoints.left,
478
+ target: tp.left
479
+ },
480
+ {
481
+ source: rectPoints.left,
482
+ target: tp.right
483
+ },
484
+ {
485
+ source: rectPoints.left,
486
+ target: tp.centerX
487
+ },
488
+ {
489
+ source: rectPoints.right,
490
+ target: tp.left
491
+ },
492
+ {
493
+ source: rectPoints.right,
494
+ target: tp.right
495
+ },
496
+ {
497
+ source: rectPoints.right,
498
+ target: tp.centerX
499
+ },
500
+ {
501
+ source: rectPoints.centerX,
502
+ target: tp.left
503
+ },
504
+ {
505
+ source: rectPoints.centerX,
506
+ target: tp.right
507
+ },
508
+ {
509
+ source: rectPoints.centerX,
510
+ target: tp.centerX
511
+ }
512
+ ];
513
+ for (const check of xChecks) {
514
+ const dist = Math.abs(check.source - check.target);
515
+ if (dist <= threshold && dist < minDistX) {
516
+ minDistX = dist;
517
+ snapX = check.target - (check.source - rect.x);
518
+ if (spacingGuides.some((g) => g.axis === "x")) spacingGuides = spacingGuides.filter((g) => g.axis !== "x");
519
+ }
520
+ }
521
+ const yChecks = [
522
+ {
523
+ source: rectPoints.top,
524
+ target: tp.top
525
+ },
526
+ {
527
+ source: rectPoints.top,
528
+ target: tp.bottom
529
+ },
530
+ {
531
+ source: rectPoints.top,
532
+ target: tp.centerY
533
+ },
534
+ {
535
+ source: rectPoints.bottom,
536
+ target: tp.top
537
+ },
538
+ {
539
+ source: rectPoints.bottom,
540
+ target: tp.bottom
541
+ },
542
+ {
543
+ source: rectPoints.bottom,
544
+ target: tp.centerY
545
+ },
546
+ {
547
+ source: rectPoints.centerY,
548
+ target: tp.top
549
+ },
550
+ {
551
+ source: rectPoints.centerY,
552
+ target: tp.bottom
553
+ },
554
+ {
555
+ source: rectPoints.centerY,
556
+ target: tp.centerY
557
+ }
558
+ ];
559
+ for (const check of yChecks) {
560
+ const dist = Math.abs(check.source - check.target);
561
+ if (dist <= threshold && dist < minDistY) {
562
+ minDistY = dist;
563
+ snapY = check.target - (check.source - rect.y);
564
+ if (spacingGuides.some((g) => g.axis === "y")) spacingGuides = spacingGuides.filter((g) => g.axis !== "y");
565
+ }
566
+ }
567
+ }
568
+ if (snapX === null && snapY === null) return null;
569
+ const snapRect = {
570
+ x: snapX ?? rect.x,
571
+ y: snapY ?? rect.y,
572
+ width: rect.width,
573
+ height: rect.height
574
+ };
575
+ const snappedPoints = getPoints(snapRect);
576
+ const seenLines = /* @__PURE__ */ new Set();
577
+ for (const target of otherRects) {
578
+ const tp = getPoints(target);
579
+ const xAligns = [
580
+ {
581
+ source: snappedPoints.left,
582
+ target: tp.left
583
+ },
584
+ {
585
+ source: snappedPoints.left,
586
+ target: tp.right
587
+ },
588
+ {
589
+ source: snappedPoints.left,
590
+ target: tp.centerX
591
+ },
592
+ {
593
+ source: snappedPoints.right,
594
+ target: tp.left
595
+ },
596
+ {
597
+ source: snappedPoints.right,
598
+ target: tp.right
599
+ },
600
+ {
601
+ source: snappedPoints.right,
602
+ target: tp.centerX
603
+ },
604
+ {
605
+ source: snappedPoints.centerX,
606
+ target: tp.left
607
+ },
608
+ {
609
+ source: snappedPoints.centerX,
610
+ target: tp.right
611
+ },
612
+ {
613
+ source: snappedPoints.centerX,
614
+ target: tp.centerX
615
+ }
616
+ ];
617
+ for (const a of xAligns) if (Math.abs(a.source - a.target) < .01) {
618
+ const key = `x:${a.target}`;
619
+ if (!seenLines.has(key)) {
620
+ seenLines.add(key);
621
+ snapLines.push({
622
+ axis: "x",
623
+ value: a.target
624
+ });
625
+ }
626
+ }
627
+ const yAligns = [
628
+ {
629
+ source: snappedPoints.top,
630
+ target: tp.top
631
+ },
632
+ {
633
+ source: snappedPoints.top,
634
+ target: tp.bottom
635
+ },
636
+ {
637
+ source: snappedPoints.top,
638
+ target: tp.centerY
639
+ },
640
+ {
641
+ source: snappedPoints.bottom,
642
+ target: tp.top
643
+ },
644
+ {
645
+ source: snappedPoints.bottom,
646
+ target: tp.bottom
647
+ },
648
+ {
649
+ source: snappedPoints.bottom,
650
+ target: tp.centerY
651
+ },
652
+ {
653
+ source: snappedPoints.centerY,
654
+ target: tp.top
655
+ },
656
+ {
657
+ source: snappedPoints.centerY,
658
+ target: tp.bottom
659
+ },
660
+ {
661
+ source: snappedPoints.centerY,
662
+ target: tp.centerY
663
+ }
664
+ ];
665
+ for (const a of yAligns) if (Math.abs(a.source - a.target) < .01) {
666
+ const key = `y:${a.target}`;
667
+ if (!seenLines.has(key)) {
668
+ seenLines.add(key);
669
+ snapLines.push({
670
+ axis: "y",
671
+ value: a.target
672
+ });
673
+ }
674
+ }
675
+ }
676
+ return {
677
+ snapLines,
678
+ snapRect,
679
+ spacingGuides: spacingGuides.length > 0 ? spacingGuides : void 0
680
+ };
681
+ }
682
+ //#endregion
683
+ //#region src/edge-geometry.ts
684
+ function isPointNearPath(point, path, tolerance) {
685
+ const samplePoints = samplePathPoints(path);
686
+ for (let i = 0; i < samplePoints.length - 1; i++) {
687
+ const start = samplePoints[i];
688
+ const end = samplePoints[i + 1];
689
+ if (start && end && distanceToSegment(point, start, end) <= tolerance) return true;
690
+ }
691
+ return false;
692
+ }
693
+ function rectIntersectsPath(rect, path) {
694
+ const samplePoints = samplePathPoints(path);
695
+ for (const point of samplePoints) if (pointInRect(point, rect)) return true;
696
+ const corners = rectCorners(rect);
697
+ for (let i = 0; i < samplePoints.length - 1; i++) {
698
+ const start = samplePoints[i];
699
+ const end = samplePoints[i + 1];
700
+ if (!start || !end) continue;
701
+ if (pointInRect(start, rect) || pointInRect(end, rect)) return true;
702
+ for (let cornerIndex = 0; cornerIndex < corners.length; cornerIndex++) {
703
+ const edgeStart = corners[cornerIndex];
704
+ const edgeEnd = corners[(cornerIndex + 1) % corners.length];
705
+ if (edgeStart && edgeEnd && segmentsIntersect(start, end, edgeStart, edgeEnd)) return true;
706
+ }
707
+ }
708
+ return false;
709
+ }
710
+ function basicEdgePath(edge, nodes) {
711
+ const source = nodes.find((node) => node.id === edge.sourceId);
712
+ const target = nodes.find((node) => node.id === edge.targetId);
713
+ if (!source || !target) return null;
714
+ return {
715
+ points: [resolveBasicEndpoint(source, edge.sourcePort), resolveBasicEndpoint(target, edge.targetPort)],
716
+ sourceDirection: "right",
717
+ targetDirection: "left"
718
+ };
719
+ }
720
+ function resolveBasicEndpoint(node, portName) {
721
+ if (portName && portName !== "*" && node.ports) {
722
+ const port = node.ports.find((candidate) => candidate.name === portName);
723
+ if (port) {
724
+ const position = resolvedPosition(node);
725
+ return {
726
+ x: position.x + port.x + port.width / 2,
727
+ y: position.y + port.y + port.height / 2
728
+ };
729
+ }
730
+ }
731
+ const bounds = resolvedBounds(node);
732
+ return {
733
+ x: bounds.x + bounds.width / 2,
734
+ y: bounds.y + bounds.height / 2
735
+ };
736
+ }
737
+ function samplePathPoints(path) {
738
+ if (path.points.length === 4) {
739
+ const [p0, p1, p2, p3] = path.points;
740
+ if (p0 && p1 && p2 && p3) return sampleCubicBezier(p0, p1, p2, p3, 20);
741
+ }
742
+ return path.points;
743
+ }
744
+ function sampleCubicBezier(p0, p1, p2, p3, steps) {
745
+ const points = [];
746
+ for (let i = 0; i <= steps; i++) {
747
+ const t = i / steps;
748
+ const mt = 1 - t;
749
+ points.push({
750
+ x: mt ** 3 * p0.x + 3 * mt ** 2 * t * p1.x + 3 * mt * t ** 2 * p2.x + t ** 3 * p3.x,
751
+ y: mt ** 3 * p0.y + 3 * mt ** 2 * t * p1.y + 3 * mt * t ** 2 * p2.y + t ** 3 * p3.y
752
+ });
753
+ }
754
+ return points;
755
+ }
756
+ function distanceToSegment(point, start, end) {
757
+ const dx = end.x - start.x;
758
+ const dy = end.y - start.y;
759
+ if (dx === 0 && dy === 0) return Math.hypot(point.x - start.x, point.y - start.y);
760
+ const t = Math.max(0, Math.min(1, ((point.x - start.x) * dx + (point.y - start.y) * dy) / (dx * dx + dy * dy)));
761
+ return Math.hypot(point.x - (start.x + t * dx), point.y - (start.y + t * dy));
762
+ }
763
+ function pointInRect(point, rect) {
764
+ return point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
765
+ }
766
+ function rectCorners(rect) {
767
+ return [
768
+ {
769
+ x: rect.x,
770
+ y: rect.y
771
+ },
772
+ {
773
+ x: rect.x + rect.width,
774
+ y: rect.y
775
+ },
776
+ {
777
+ x: rect.x + rect.width,
778
+ y: rect.y + rect.height
779
+ },
780
+ {
781
+ x: rect.x,
782
+ y: rect.y + rect.height
783
+ }
784
+ ];
785
+ }
786
+ function segmentsIntersect(a1, a2, b1, b2) {
787
+ const d1 = direction(b1, b2, a1);
788
+ const d2 = direction(b1, b2, a2);
789
+ const d3 = direction(a1, a2, b1);
790
+ const d4 = direction(a1, a2, b2);
791
+ if ((d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) && (d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0)) return true;
792
+ return d1 === 0 && onSegment(b1, b2, a1) || d2 === 0 && onSegment(b1, b2, a2) || d3 === 0 && onSegment(a1, a2, b1) || d4 === 0 && onSegment(a1, a2, b2);
793
+ }
794
+ function direction(a, b, c) {
795
+ return (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x);
796
+ }
797
+ function onSegment(a, b, c) {
798
+ return Math.min(a.x, b.x) <= c.x && c.x <= Math.max(a.x, b.x) && Math.min(a.y, b.y) <= c.y && c.y <= Math.max(a.y, b.y);
799
+ }
800
+ //#endregion
801
+ //#region src/store/index.ts
802
+ enableMapSet();
803
+ const UNDOABLE_EVENT_TYPES = [
804
+ "createNode",
805
+ "deleteNode",
806
+ "updateNodeData",
807
+ "createEdge",
808
+ "deleteEdge",
809
+ "updateEdgeData",
810
+ "deleteSelected",
811
+ "reparentNode",
812
+ "commitDrag",
813
+ "resizeEnd",
814
+ "reconnectEdge",
815
+ "applyLayoutResult",
816
+ "bakeLabelPositions"
817
+ ];
818
+ function applyBeforeDelete(options, draft, reason, nodes, edges) {
819
+ if (!options.beforeDelete) return false;
820
+ const result = options.beforeDelete({
821
+ graph: {
822
+ ...draft.graph,
823
+ nodes: [...draft.graph.nodes],
824
+ edges: [...draft.graph.edges]
825
+ },
826
+ reason,
827
+ nodes,
828
+ edges
829
+ });
830
+ if (result === false) return true;
831
+ if (result && (result.nodes || result.edges)) {
832
+ if (result.nodes) draft.graph.nodes = result.nodes;
833
+ if (result.edges) draft.graph.edges = result.edges;
834
+ draft.selection.clear();
835
+ draft.focusedEntityId = null;
836
+ if (draft.draggedEntityId && !draft.graph.nodes.some((node) => node.id === draft.draggedEntityId)) draft.draggedEntityId = null;
837
+ return true;
838
+ }
839
+ return false;
840
+ }
841
+ function isUndoableEventType(type) {
842
+ return UNDOABLE_EVENT_TYPES.includes(type);
843
+ }
844
+ function hasSelectedEntitiesToDelete(ctx) {
845
+ for (const id of ctx.selection) if (ctx.graph.nodes.some((node) => node.id === id) || ctx.graph.edges.some((edge) => edge.id === id)) return true;
846
+ return false;
847
+ }
848
+ function hasPendingDragDelta(ctx) {
849
+ return ctx.graph.nodes.some((node) => (node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0) || ctx.graph.edges.some((edge) => !!edge.label && ((edge.label.dx ?? 0) !== 0 || (edge.label.dy ?? 0) !== 0));
850
+ }
851
+ function shouldTrackUndoEvent(event, snapshot) {
852
+ if (!isUndoableEventType(event.type)) return false;
853
+ const ctx = snapshot.context;
854
+ switch (event.type) {
855
+ case "deleteNode": return ctx.graph.nodes.some((node) => node.id === event.id);
856
+ case "deleteEdge": return ctx.graph.edges.some((edge) => edge.id === event.id);
857
+ case "updateNodeData": {
858
+ const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);
859
+ return !!node && Object.entries(event.data).some(([key, value]) => node.data?.[key] !== value);
860
+ }
861
+ case "updateEdgeData": {
862
+ const edge = ctx.graph.edges.find((candidate) => candidate.id === event.id);
863
+ return !!edge && Object.entries(event.data).some(([key, value]) => edge.data?.[key] !== value);
864
+ }
865
+ case "deleteSelected": return hasSelectedEntitiesToDelete(ctx);
866
+ case "reparentNode": {
867
+ const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);
868
+ return !!node && (node.parentId ?? null) !== event.parentId;
869
+ }
870
+ case "commitDrag": return hasPendingDragDelta(ctx);
871
+ case "resizeEnd": return !!ctx.resizingEntityId && !!ctx.resizeCorners;
872
+ case "reconnectEdge": {
873
+ const edge = ctx.graph.edges.find((candidate) => candidate.id === event.edgeId);
874
+ if (!edge) return false;
875
+ return event.newSourceId !== void 0 && event.newSourceId !== edge.sourceId || event.newTargetId !== void 0 && event.newTargetId !== edge.targetId || event.newSourcePort !== void 0 && event.newSourcePort !== edge.sourcePort || event.newTargetPort !== void 0 && event.newTargetPort !== edge.targetPort;
876
+ }
877
+ case "applyLayoutResult": return event.positions.size > 0 || (event.edgeLabelPositions?.size ?? 0) > 0;
878
+ case "bakeLabelPositions": return event.positions.size > 0;
879
+ default: return true;
880
+ }
881
+ }
882
+ function createFlowStore(initialGraph = {
883
+ nodes: [],
884
+ edges: [],
885
+ direction: "down"
886
+ }, options = {}) {
887
+ const initialContext = {
888
+ graph: initialGraph,
889
+ parentNodeId: null,
890
+ depth: null,
891
+ viewport: createViewport(),
892
+ viewportSize: {
893
+ width: 0,
894
+ height: 0
895
+ },
896
+ viewportStack: [],
897
+ minZoom: options.minZoom ?? .1,
898
+ maxZoom: options.maxZoom ?? 4,
899
+ translateExtent: options.translateExtent ?? null,
900
+ nodeExtent: options.nodeExtent ?? null,
901
+ selection: /* @__PURE__ */ new Set(),
902
+ selectionBox: null,
903
+ highlights: /* @__PURE__ */ new Set(),
904
+ focusedEntityId: null,
905
+ canvasState: "idle",
906
+ draggedEntityId: null,
907
+ dragThreshold: options.dragThreshold ?? 3,
908
+ autoPanOnDrag: options.autoPanOnDrag ?? true,
909
+ autoPanThreshold: options.autoPanThreshold ?? 40,
910
+ autoPanSpeed: options.autoPanSpeed ?? 15,
911
+ connection: null,
912
+ connectOnClick: options.connectOnClick ?? false,
913
+ connectionClickStartHandle: null,
914
+ panOrigin: null,
915
+ panViewportOrigin: null,
916
+ resizingEntityId: null,
917
+ resizeHandle: null,
918
+ resizeCorners: null,
919
+ interactionMode: "default",
920
+ selectionMode: options.selectionMode ?? "partial",
921
+ snapToGrid: options.snapToGrid ?? false,
922
+ snapGrid: options.snapGrid ?? [10, 10],
923
+ enableSnapLines: options.enableSnapLines ?? false,
924
+ snapThreshold: options.snapThreshold ?? 5,
925
+ enableSpacingGuides: options.enableSpacingGuides ?? false,
926
+ autoLayout: {
927
+ status: "idle",
928
+ algorithm: null
929
+ }
930
+ };
931
+ return createStore({
932
+ context: initialContext,
933
+ emits: {
934
+ layoutRequested: (_event) => {},
935
+ connectionEnded: (_event) => {}
936
+ },
937
+ on: {
938
+ createNode: (ctx, event) => produce(ctx, (draft) => {
939
+ draft.graph.nodes.push(event.node);
940
+ }),
941
+ deleteNode: (ctx, event) => produce(ctx, (draft) => {
942
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
943
+ const edges = draft.graph.edges.filter((e) => e.sourceId === event.id || e.targetId === event.id);
944
+ if (node && applyBeforeDelete(options, draft, "deleteNode", [node], edges)) return;
945
+ draft.graph.nodes = draft.graph.nodes.filter((n) => n.id !== event.id);
946
+ draft.graph.edges = draft.graph.edges.filter((e) => e.sourceId !== event.id && e.targetId !== event.id);
947
+ draft.selection.delete(event.id);
948
+ if (draft.focusedEntityId === event.id) draft.focusedEntityId = null;
949
+ }),
950
+ updateNodeData: (ctx, event) => produce(ctx, (draft) => {
951
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
952
+ if (node) Object.assign(node.data, event.data);
953
+ }),
954
+ createEdge: (ctx, event) => produce(ctx, (draft) => {
955
+ draft.graph.edges.push(event.edge);
956
+ }),
957
+ deleteEdge: (ctx, event) => produce(ctx, (draft) => {
958
+ const edge = draft.graph.edges.find((e) => e.id === event.id);
959
+ if (edge && applyBeforeDelete(options, draft, "deleteEdge", [], [edge])) return;
960
+ draft.graph.edges = draft.graph.edges.filter((e) => e.id !== event.id);
961
+ draft.selection.delete(event.id);
962
+ }),
963
+ updateEdgeData: (ctx, event) => produce(ctx, (draft) => {
964
+ const edge = draft.graph.edges.find((e) => e.id === event.id);
965
+ if (edge) Object.assign(edge.data, event.data);
966
+ }),
967
+ deleteSelected: (ctx) => produce(ctx, (draft) => {
968
+ const sel = draft.selection;
969
+ const nodesToDelete = /* @__PURE__ */ new Set();
970
+ const edgesToDelete = /* @__PURE__ */ new Set();
971
+ for (const id of sel) {
972
+ if (draft.graph.nodes.some((n) => n.id === id)) nodesToDelete.add(id);
973
+ if (draft.graph.edges.some((e) => e.id === id)) edgesToDelete.add(id);
974
+ }
975
+ if (applyBeforeDelete(options, draft, "deleteSelected", draft.graph.nodes.filter((node) => nodesToDelete.has(node.id)), draft.graph.edges.filter((edge) => edgesToDelete.has(edge.id) || nodesToDelete.has(edge.sourceId) || nodesToDelete.has(edge.targetId)))) return;
976
+ const strategy = options.onDeleteNodes ?? "cascade";
977
+ if (typeof strategy === "function") {
978
+ const result = strategy({
979
+ ...draft.graph,
980
+ nodes: [...draft.graph.nodes],
981
+ edges: [...draft.graph.edges]
982
+ }, nodesToDelete);
983
+ draft.graph.nodes = result.nodes;
984
+ draft.graph.edges = result.edges;
985
+ } else if (strategy === "retarget") {
986
+ draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));
987
+ draft.graph.edges = draft.graph.edges.filter((e) => !sel.has(e.id));
988
+ for (const edge of draft.graph.edges) {
989
+ const srcDel = nodesToDelete.has(edge.sourceId);
990
+ const tgtDel = nodesToDelete.has(edge.targetId);
991
+ if (srcDel && tgtDel) draft.graph.edges = draft.graph.edges.filter((e) => e.id !== edge.id);
992
+ else if (srcDel) edge.sourceId = edge.targetId;
993
+ else if (tgtDel) edge.targetId = edge.sourceId;
994
+ }
995
+ } else {
996
+ draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));
997
+ draft.graph.edges = draft.graph.edges.filter((e) => !sel.has(e.id) && !nodesToDelete.has(e.sourceId) && !nodesToDelete.has(e.targetId));
998
+ }
999
+ draft.selection.clear();
1000
+ draft.focusedEntityId = null;
1001
+ }),
1002
+ setGraph: (ctx, event) => produce(ctx, (draft) => {
1003
+ draft.graph = event.graph;
1004
+ draft.selection.clear();
1005
+ draft.focusedEntityId = null;
1006
+ draft.canvasState = "idle";
1007
+ draft.draggedEntityId = null;
1008
+ draft.connection = null;
1009
+ draft.selectionBox = null;
1010
+ }),
1011
+ reset: (ctx) => produce(ctx, (draft) => {
1012
+ Object.assign(draft, {
1013
+ ...initialContext,
1014
+ viewportSize: draft.viewportSize
1015
+ });
1016
+ }),
1017
+ reparentNode: (ctx, event) => produce(ctx, (draft) => {
1018
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
1019
+ if (node) node.parentId = event.parentId;
1020
+ }),
1021
+ dragStart: (ctx, event) => produce(ctx, (draft) => {
1022
+ draft.canvasState = "dragging";
1023
+ draft.draggedEntityId = event.id;
1024
+ draft.selection.add(event.id);
1025
+ }),
1026
+ dragMove: (ctx, event) => produce(ctx, (draft) => {
1027
+ if (draft.canvasState !== "dragging") return;
1028
+ const { dx, dy } = event;
1029
+ if (dx === 0 && dy === 0) return;
1030
+ for (const id of draft.selection) {
1031
+ const node = draft.graph.nodes.find((n) => n.id === id);
1032
+ if (node) {
1033
+ let newDx = (node.dx ?? 0) + dx;
1034
+ let newDy = (node.dy ?? 0) + dy;
1035
+ if (draft.nodeExtent) {
1036
+ const newX = node.x + newDx;
1037
+ const newY = node.y + newDy;
1038
+ const clampedX = Math.max(draft.nodeExtent[0].x, Math.min(newX, draft.nodeExtent[1].x - node.width));
1039
+ const clampedY = Math.max(draft.nodeExtent[0].y, Math.min(newY, draft.nodeExtent[1].y - node.height));
1040
+ newDx = clampedX - node.x;
1041
+ newDy = clampedY - node.y;
1042
+ }
1043
+ node.dx = newDx;
1044
+ node.dy = newDy;
1045
+ continue;
1046
+ }
1047
+ const edge = draft.graph.edges.find((e) => e.id === id);
1048
+ if (edge?.label) {
1049
+ edge.label.dx = (edge.label.dx ?? 0) + dx;
1050
+ edge.label.dy = (edge.label.dy ?? 0) + dy;
1051
+ }
1052
+ }
1053
+ }),
1054
+ dragEnd: (ctx) => produce(ctx, (draft) => {
1055
+ draft.canvasState = "idle";
1056
+ draft.draggedEntityId = null;
1057
+ }),
1058
+ commitDrag: (ctx) => produce(ctx, (draft) => {
1059
+ let snapOffX = 0;
1060
+ let snapOffY = 0;
1061
+ if (draft.enableSnapLines && draft.selection.size > 0) {
1062
+ const selBounds = getSelectionBounds(draft.graph.nodes, draft.graph.edges, draft.selection);
1063
+ if (selBounds) {
1064
+ const sel = draft.selection;
1065
+ const otherRects = draft.graph.nodes.filter((n) => !sel.has(n.id) && !n.hidden).map((n) => resolvedBounds(n));
1066
+ for (const edge of draft.graph.edges) {
1067
+ if (sel.has(edge.id) || !edge.label) continue;
1068
+ otherRects.push({
1069
+ x: edge.label.x + (edge.label.dx ?? 0),
1070
+ y: edge.label.y + (edge.label.dy ?? 0),
1071
+ width: edge.label.width,
1072
+ height: edge.label.height
1073
+ });
1074
+ }
1075
+ const snapResult = getSnapLines(selBounds, otherRects, {
1076
+ threshold: draft.snapThreshold / draft.viewport.zoom,
1077
+ enableSpacing: draft.enableSpacingGuides
1078
+ });
1079
+ if (snapResult) {
1080
+ snapOffX = snapResult.snapRect.x - selBounds.x;
1081
+ snapOffY = snapResult.snapRect.y - selBounds.y;
1082
+ }
1083
+ }
1084
+ }
1085
+ const gridSnap = draft.snapToGrid;
1086
+ const [gx, gy] = draft.snapGrid;
1087
+ for (const node of draft.graph.nodes) if (node.dx || node.dy) {
1088
+ let x = node.x + (node.dx ?? 0) + snapOffX;
1089
+ let y = node.y + (node.dy ?? 0) + snapOffY;
1090
+ if (gridSnap) {
1091
+ x = snapToGrid(x, gx);
1092
+ y = snapToGrid(y, gy);
1093
+ }
1094
+ node.x = x;
1095
+ node.y = y;
1096
+ node.dx = 0;
1097
+ node.dy = 0;
1098
+ }
1099
+ for (const edge of draft.graph.edges) {
1100
+ if (!edge.label) continue;
1101
+ if (edge.label.dx || edge.label.dy) {
1102
+ let x = edge.label.x + (edge.label.dx ?? 0) + snapOffX;
1103
+ let y = edge.label.y + (edge.label.dy ?? 0) + snapOffY;
1104
+ if (gridSnap) {
1105
+ x = snapToGrid(x, gx);
1106
+ y = snapToGrid(y, gy);
1107
+ }
1108
+ edge.label.x = x;
1109
+ edge.label.y = y;
1110
+ edge.label.dx = 0;
1111
+ edge.label.dy = 0;
1112
+ }
1113
+ }
1114
+ }),
1115
+ select: (ctx, event) => produce(ctx, (draft) => {
1116
+ const mode = event.mode ?? "single";
1117
+ if (mode === "single") draft.selection.clear();
1118
+ if (mode === "multi" && event.ids.every((id) => draft.selection.has(id))) for (const id of event.ids) draft.selection.delete(id);
1119
+ else for (const id of event.ids) draft.selection.add(id);
1120
+ }),
1121
+ selectAll: (ctx) => produce(ctx, (draft) => {
1122
+ for (const node of draft.graph.nodes) draft.selection.add(node.id);
1123
+ for (const edge of draft.graph.edges) draft.selection.add(edge.id);
1124
+ }),
1125
+ clearSelection: (ctx) => produce(ctx, (draft) => {
1126
+ draft.selection.clear();
1127
+ }),
1128
+ selectionBoxStart: (ctx, event) => produce(ctx, (draft) => {
1129
+ draft.canvasState = "selecting";
1130
+ if ((event.mode ?? "single") === "single") draft.selection.clear();
1131
+ draft.selectionBox = [{
1132
+ x: event.point.x,
1133
+ y: event.point.y
1134
+ }, {
1135
+ x: event.point.x,
1136
+ y: event.point.y
1137
+ }];
1138
+ }),
1139
+ selectionBoxMove: (ctx, event) => produce(ctx, (draft) => {
1140
+ if (draft.canvasState !== "selecting" || !draft.selectionBox) return;
1141
+ draft.selectionBox[1] = {
1142
+ x: event.point.x,
1143
+ y: event.point.y
1144
+ };
1145
+ }),
1146
+ selectionBoxEnd: (ctx) => produce(ctx, (draft) => {
1147
+ if (!draft.selectionBox) return;
1148
+ const rect = boxToRect(draft.selectionBox[0], draft.selectionBox[1]);
1149
+ const contains = draft.selectionMode === "full" ? rectContains : rectsIntersect;
1150
+ for (const node of draft.graph.nodes) if (contains(rect, resolvedBounds(node))) draft.selection.add(node.id);
1151
+ for (const edge of draft.graph.edges) {
1152
+ if (edge.label) {
1153
+ if (contains(rect, {
1154
+ x: edge.label.x + (edge.label.dx ?? 0),
1155
+ y: edge.label.y + (edge.label.dy ?? 0),
1156
+ width: edge.label.width,
1157
+ height: edge.label.height
1158
+ })) {
1159
+ draft.selection.add(edge.id);
1160
+ continue;
1161
+ }
1162
+ }
1163
+ const edgePath = basicEdgePath(edge, draft.graph.nodes);
1164
+ const sourceNode = draft.graph.nodes.find((node) => node.id === edge.sourceId);
1165
+ const targetNode = draft.graph.nodes.find((node) => node.id === edge.targetId);
1166
+ const sourceSelectedByBox = sourceNode ? contains(rect, resolvedBounds(sourceNode)) : false;
1167
+ const targetSelectedByBox = targetNode ? contains(rect, resolvedBounds(targetNode)) : false;
1168
+ if (draft.selectionMode === "full" ? sourceSelectedByBox && targetSelectedByBox : !!edgePath && rectIntersectsPath(rect, edgePath) && !(sourceSelectedByBox && targetSelectedByBox)) draft.selection.add(edge.id);
1169
+ }
1170
+ draft.selectionBox = null;
1171
+ draft.canvasState = "idle";
1172
+ }),
1173
+ focus: (ctx, event) => produce(ctx, (draft) => {
1174
+ draft.focusedEntityId = event.entityId;
1175
+ }),
1176
+ clearFocus: (ctx) => produce(ctx, (draft) => {
1177
+ draft.focusedEntityId = null;
1178
+ }),
1179
+ updateParentNodeId: (ctx, event) => produce(ctx, (draft) => {
1180
+ draft.parentNodeId = event.parentNodeId;
1181
+ draft.selection.clear();
1182
+ draft.focusedEntityId = null;
1183
+ }),
1184
+ setViewport: (ctx, event) => produce(ctx, (draft) => {
1185
+ draft.viewport = {
1186
+ x: event.x,
1187
+ y: event.y,
1188
+ zoom: event.zoom
1189
+ };
1190
+ }),
1191
+ panBy: (ctx, event) => produce(ctx, (draft) => {
1192
+ draft.viewport.x += event.x;
1193
+ draft.viewport.y += event.y;
1194
+ if (draft.translateExtent) draft.viewport = constrainViewport(draft.viewport, draft.viewportSize, draft.translateExtent);
1195
+ }),
1196
+ zoomTo: (ctx, event) => produce(ctx, (draft) => {
1197
+ const clamped = Math.min(Math.max(event.zoom, draft.minZoom), draft.maxZoom);
1198
+ const ratio = clamped / draft.viewport.zoom;
1199
+ draft.viewport = {
1200
+ x: event.center.x - (event.center.x - draft.viewport.x) * ratio,
1201
+ y: event.center.y - (event.center.y - draft.viewport.y) * ratio,
1202
+ zoom: clamped
1203
+ };
1204
+ if (draft.translateExtent) draft.viewport = constrainViewport(draft.viewport, draft.viewportSize, draft.translateExtent);
1205
+ }),
1206
+ setMinZoom: (ctx, event) => produce(ctx, (draft) => {
1207
+ draft.minZoom = event.minZoom;
1208
+ if (draft.viewport.zoom < event.minZoom) draft.viewport.zoom = event.minZoom;
1209
+ }),
1210
+ setMaxZoom: (ctx, event) => produce(ctx, (draft) => {
1211
+ draft.maxZoom = event.maxZoom;
1212
+ if (draft.viewport.zoom > event.maxZoom) draft.viewport.zoom = event.maxZoom;
1213
+ }),
1214
+ setDragThreshold: (ctx, event) => produce(ctx, (draft) => {
1215
+ draft.dragThreshold = Math.max(0, event.dragThreshold);
1216
+ }),
1217
+ setAutoPanOptions: (ctx, event) => produce(ctx, (draft) => {
1218
+ if (event.autoPanOnDrag !== void 0) draft.autoPanOnDrag = event.autoPanOnDrag;
1219
+ if (event.autoPanThreshold !== void 0) draft.autoPanThreshold = Math.max(0, event.autoPanThreshold);
1220
+ if (event.autoPanSpeed !== void 0) draft.autoPanSpeed = Math.max(0, event.autoPanSpeed);
1221
+ }),
1222
+ setTranslateExtent: (ctx, event) => produce(ctx, (draft) => {
1223
+ draft.translateExtent = event.extent;
1224
+ }),
1225
+ setNodeExtent: (ctx, event) => produce(ctx, (draft) => {
1226
+ draft.nodeExtent = event.extent;
1227
+ }),
1228
+ updateViewportSize: (ctx, event) => produce(ctx, (draft) => {
1229
+ draft.viewportSize = {
1230
+ width: event.width,
1231
+ height: event.height
1232
+ };
1233
+ }),
1234
+ fitView: (ctx, event) => produce(ctx, (draft) => {
1235
+ if (draft.viewportSize.width === 0 || draft.viewportSize.height === 0) return;
1236
+ const nodeIds = event?.nodes?.map((node) => typeof node === "string" ? node : node.id);
1237
+ const bounds = getGraphBounds(nodeIds && nodeIds.length > 0 ? draft.graph.nodes.filter((node) => nodeIds.includes(node.id) && !node.hidden) : draft.graph.nodes.filter((node) => !node.hidden), nodeIds && nodeIds.length > 0 ? void 0 : draft.graph.edges.filter((edge) => !edge.hidden));
1238
+ if (bounds.width === 0 && bounds.height === 0) return;
1239
+ const { nodes: _nodes, ...options } = event ?? {};
1240
+ draft.viewport = viewportForBounds(bounds, draft.viewportSize, options);
1241
+ }),
1242
+ pushViewport: (ctx) => produce(ctx, (draft) => {
1243
+ draft.viewportStack.push({ ...draft.viewport });
1244
+ }),
1245
+ popViewport: (ctx) => produce(ctx, (draft) => {
1246
+ const prev = draft.viewportStack.pop();
1247
+ if (prev) draft.viewport = prev;
1248
+ }),
1249
+ panStart: (ctx, event) => produce(ctx, (draft) => {
1250
+ draft.canvasState = "panning";
1251
+ draft.panOrigin = {
1252
+ x: event.x,
1253
+ y: event.y
1254
+ };
1255
+ draft.panViewportOrigin = { ...draft.viewport };
1256
+ }),
1257
+ pan: (ctx, event) => produce(ctx, (draft) => {
1258
+ if (!draft.panOrigin || !draft.panViewportOrigin) return;
1259
+ let newX = draft.panViewportOrigin.x + (event.x - draft.panOrigin.x);
1260
+ let newY = draft.panViewportOrigin.y + (event.y - draft.panOrigin.y);
1261
+ if (draft.translateExtent) {
1262
+ const z = draft.viewport.zoom;
1263
+ newX = Math.max(-(draft.translateExtent[1].x * z - draft.viewportSize.width), Math.min(newX, -draft.translateExtent[0].x * z));
1264
+ newY = Math.max(-(draft.translateExtent[1].y * z - draft.viewportSize.height), Math.min(newY, -draft.translateExtent[0].y * z));
1265
+ }
1266
+ draft.viewport = {
1267
+ x: newX,
1268
+ y: newY,
1269
+ zoom: draft.panViewportOrigin.zoom
1270
+ };
1271
+ }),
1272
+ panEnd: (ctx) => produce(ctx, (draft) => {
1273
+ draft.canvasState = "idle";
1274
+ draft.panOrigin = null;
1275
+ draft.panViewportOrigin = null;
1276
+ }),
1277
+ setCanvasState: (ctx, event) => produce(ctx, (draft) => {
1278
+ draft.canvasState = event.state;
1279
+ }),
1280
+ connectionStart: (ctx, event) => produce(ctx, (draft) => {
1281
+ draft.canvasState = "connecting";
1282
+ draft.connection = {
1283
+ sourceId: event.sourceId,
1284
+ sourcePort: event.sourcePort,
1285
+ targetId: null,
1286
+ targetPort: null,
1287
+ startPosition: event.position,
1288
+ pointerPosition: event.position,
1289
+ active: false,
1290
+ isValid: false
1291
+ };
1292
+ }),
1293
+ connectionMove: (ctx, event) => produce(ctx, (draft) => {
1294
+ if (!draft.connection) return;
1295
+ draft.connection.pointerPosition = event.position;
1296
+ if (event.targetId !== void 0) draft.connection.targetId = event.targetId;
1297
+ if (event.targetPort !== void 0) draft.connection.targetPort = event.targetPort;
1298
+ if (event.isValid !== void 0) draft.connection.isValid = event.isValid;
1299
+ const dx = event.position.x - draft.connection.startPosition.x;
1300
+ const dy = event.position.y - draft.connection.startPosition.y;
1301
+ const threshold = options.connectionDragThreshold ?? draft.dragThreshold;
1302
+ if (!draft.connection.active && Math.hypot(dx, dy) >= threshold) draft.connection.active = true;
1303
+ }),
1304
+ connectionEnd: (ctx, event, enqueue) => produce(ctx, (draft) => {
1305
+ if (draft.connection) enqueue.emit.connectionEnded({
1306
+ source: {
1307
+ nodeId: draft.connection.sourceId,
1308
+ port: draft.connection.sourcePort
1309
+ },
1310
+ target: event?.target ?? { kind: "none" },
1311
+ connection: draft.connection
1312
+ });
1313
+ draft.canvasState = "idle";
1314
+ draft.connection = null;
1315
+ }),
1316
+ cancelConnection: (ctx) => produce(ctx, (draft) => {
1317
+ draft.connection = null;
1318
+ draft.connectionClickStartHandle = null;
1319
+ if (draft.canvasState === "connecting") draft.canvasState = "idle";
1320
+ }),
1321
+ setConnectionClickStartHandle: (ctx, event) => produce(ctx, (draft) => {
1322
+ draft.connectionClickStartHandle = event;
1323
+ }),
1324
+ resizeStart: (ctx, event) => produce(ctx, (draft) => {
1325
+ const node = draft.graph.nodes.find((n) => n.id === event.id);
1326
+ if (!node) return;
1327
+ draft.canvasState = "resizing";
1328
+ draft.resizingEntityId = event.id;
1329
+ draft.resizeHandle = event.handle;
1330
+ const x = node.x + (node.dx ?? 0);
1331
+ const y = node.y + (node.dy ?? 0);
1332
+ const w = node.style?.customWidth ?? node.width;
1333
+ const h = node.style?.customHeight ?? node.height;
1334
+ const tl = {
1335
+ x,
1336
+ y
1337
+ };
1338
+ const br = {
1339
+ x: x + w,
1340
+ y: y + h
1341
+ };
1342
+ const handle = event.handle;
1343
+ if (handle === "bottom-right") draft.resizeCorners = [tl, br];
1344
+ else if (handle === "bottom-left") draft.resizeCorners = [{
1345
+ x: br.x,
1346
+ y: tl.y
1347
+ }, {
1348
+ x: tl.x,
1349
+ y: br.y
1350
+ }];
1351
+ else if (handle === "top-right") draft.resizeCorners = [{
1352
+ x: tl.x,
1353
+ y: br.y
1354
+ }, {
1355
+ x: br.x,
1356
+ y: tl.y
1357
+ }];
1358
+ else if (handle === "top-left") draft.resizeCorners = [br, tl];
1359
+ else if (handle === "right") draft.resizeCorners = [tl, {
1360
+ x: br.x,
1361
+ y: br.y
1362
+ }];
1363
+ else if (handle === "left") draft.resizeCorners = [{
1364
+ x: br.x,
1365
+ y: tl.y
1366
+ }, {
1367
+ x: tl.x,
1368
+ y: br.y
1369
+ }];
1370
+ else if (handle === "bottom") draft.resizeCorners = [tl, {
1371
+ x: br.x,
1372
+ y: br.y
1373
+ }];
1374
+ else if (handle === "top") draft.resizeCorners = [{
1375
+ x: tl.x,
1376
+ y: br.y
1377
+ }, {
1378
+ x: br.x,
1379
+ y: tl.y
1380
+ }];
1381
+ }),
1382
+ resizeMove: (ctx, event) => produce(ctx, (draft) => {
1383
+ if (!draft.resizeCorners || !draft.resizingEntityId) return;
1384
+ const handle = draft.resizeHandle;
1385
+ if (handle === "left" || handle === "right") draft.resizeCorners[1].x = event.x;
1386
+ else if (handle === "top" || handle === "bottom") draft.resizeCorners[1].y = event.y;
1387
+ else draft.resizeCorners[1] = {
1388
+ x: event.x,
1389
+ y: event.y
1390
+ };
1391
+ }),
1392
+ resizeEnd: (ctx) => produce(ctx, (draft) => {
1393
+ if (draft.resizingEntityId && draft.resizeCorners) {
1394
+ const node = draft.graph.nodes.find((n) => n.id === draft.resizingEntityId);
1395
+ if (node) {
1396
+ const [a, b] = draft.resizeCorners;
1397
+ const x = Math.min(a.x, b.x);
1398
+ const y = Math.min(a.y, b.y);
1399
+ const w = Math.abs(b.x - a.x);
1400
+ const h = Math.abs(b.y - a.y);
1401
+ node.x = x;
1402
+ node.y = y;
1403
+ node.dx = 0;
1404
+ node.dy = 0;
1405
+ if (!node.style) node.style = {};
1406
+ node.style.customWidth = Math.max(10, w);
1407
+ node.style.customHeight = Math.max(10, h);
1408
+ }
1409
+ }
1410
+ draft.canvasState = "idle";
1411
+ draft.resizingEntityId = null;
1412
+ draft.resizeHandle = null;
1413
+ draft.resizeCorners = null;
1414
+ }),
1415
+ resizeCancel: (ctx) => produce(ctx, (draft) => {
1416
+ draft.canvasState = "idle";
1417
+ draft.resizingEntityId = null;
1418
+ draft.resizeHandle = null;
1419
+ draft.resizeCorners = null;
1420
+ }),
1421
+ reconnectEdge: (ctx, event) => produce(ctx, (draft) => {
1422
+ const edge = draft.graph.edges.find((e) => e.id === event.edgeId);
1423
+ if (!edge) return;
1424
+ if (event.newSourceId !== void 0) edge.sourceId = event.newSourceId;
1425
+ if (event.newTargetId !== void 0) edge.targetId = event.newTargetId;
1426
+ if (event.newSourcePort !== void 0) edge.sourcePort = event.newSourcePort;
1427
+ if (event.newTargetPort !== void 0) edge.targetPort = event.newTargetPort;
1428
+ }),
1429
+ reportPortMeasurements: (ctx, event) => produce(ctx, (draft) => {
1430
+ for (const m of event.measurements) {
1431
+ const node = draft.graph.nodes.find((n) => n.id === m.nodeId);
1432
+ if (!node?.ports) continue;
1433
+ const port = node.ports.find((p) => p.name === m.portName);
1434
+ if (port) {
1435
+ port.x = m.x;
1436
+ port.y = m.y;
1437
+ port.width = m.width;
1438
+ port.height = m.height;
1439
+ }
1440
+ }
1441
+ }),
1442
+ setInteractionMode: (ctx, event) => produce(ctx, (draft) => {
1443
+ draft.interactionMode = event.mode;
1444
+ }),
1445
+ setSnapToGrid: (ctx, event) => produce(ctx, (draft) => {
1446
+ draft.snapToGrid = event.enabled;
1447
+ if (event.grid) draft.snapGrid = event.grid;
1448
+ }),
1449
+ setSnapLines: (ctx, event) => produce(ctx, (draft) => {
1450
+ draft.enableSnapLines = event.enabled;
1451
+ if (event.threshold !== void 0) draft.snapThreshold = event.threshold;
1452
+ if (event.spacing !== void 0) draft.enableSpacingGuides = event.spacing;
1453
+ }),
1454
+ moveNodes: (ctx, event) => produce(ctx, (draft) => {
1455
+ const f = event.factor ?? 1;
1456
+ let dx = event.direction.x * f;
1457
+ let dy = event.direction.y * f;
1458
+ if (draft.snapToGrid) {
1459
+ dx = dx !== 0 ? Math.sign(dx) * draft.snapGrid[0] : 0;
1460
+ dy = dy !== 0 ? Math.sign(dy) * draft.snapGrid[1] : 0;
1461
+ }
1462
+ for (const id of draft.selection) {
1463
+ const node = draft.graph.nodes.find((n) => n.id === id);
1464
+ if (node) {
1465
+ node.dx = (node.dx ?? 0) + dx;
1466
+ node.dy = (node.dy ?? 0) + dy;
1467
+ }
1468
+ }
1469
+ }),
1470
+ requestLayout: (ctx, event, enqueue) => produce(ctx, (draft) => {
1471
+ if (draft.canvasState === "dragging") return;
1472
+ const algorithm = event.algorithm ?? draft.autoLayout.algorithm;
1473
+ if (!algorithm) return;
1474
+ draft.autoLayout = {
1475
+ status: "pending",
1476
+ algorithm
1477
+ };
1478
+ enqueue.emit.layoutRequested({
1479
+ algorithm,
1480
+ graph: ctx.graph
1481
+ });
1482
+ }),
1483
+ applyLayoutResult: (ctx, event) => produce(ctx, (draft) => {
1484
+ for (const [id, pos] of event.positions) {
1485
+ const node = draft.graph.nodes.find((n) => n.id === id);
1486
+ if (node) {
1487
+ node.x = pos.x;
1488
+ node.y = pos.y;
1489
+ node.dx = 0;
1490
+ node.dy = 0;
1491
+ }
1492
+ }
1493
+ if (event.edgeLabelPositions) for (const [id, pos] of event.edgeLabelPositions) {
1494
+ const edge = draft.graph.edges.find((e) => e.id === id);
1495
+ if (edge?.label) {
1496
+ edge.label.x = pos.x;
1497
+ edge.label.y = pos.y;
1498
+ edge.label.dx = 0;
1499
+ edge.label.dy = 0;
1500
+ }
1501
+ }
1502
+ draft.autoLayout.status = "idle";
1503
+ }),
1504
+ reportMeasurements: (ctx, event) => produce(ctx, (draft) => {
1505
+ for (const [id, dims] of event.measurements) {
1506
+ const node = draft.graph.nodes.find((n) => n.id === id);
1507
+ if (node) {
1508
+ node.width = dims.width;
1509
+ node.height = dims.height;
1510
+ continue;
1511
+ }
1512
+ const edge = draft.graph.edges.find((e) => e.id === id);
1513
+ if (edge?.label) {
1514
+ edge.label.width = dims.width;
1515
+ edge.label.height = dims.height;
1516
+ }
1517
+ }
1518
+ }),
1519
+ bakeLabelPositions: (ctx, event) => produce(ctx, (draft) => {
1520
+ for (const [edgeId, center] of event.positions) {
1521
+ const edge = draft.graph.edges.find((e) => e.id === edgeId);
1522
+ if (edge?.label) {
1523
+ edge.label.x = center.x - edge.label.width / 2;
1524
+ edge.label.y = center.y - edge.label.height / 2;
1525
+ edge.label.dx = 0;
1526
+ edge.label.dy = 0;
1527
+ }
1528
+ }
1529
+ })
1530
+ }
1531
+ }).with(undoRedo({
1532
+ strategy: "snapshot",
1533
+ historyLimit: options.historyLimit ?? 100,
1534
+ getTransactionId: (event) => event.transactionId,
1535
+ skipEvent: (event, snapshot) => !shouldTrackUndoEvent(event, snapshot)
1536
+ }));
1537
+ }
1538
+ //#endregion
1539
+ //#region src/shapes/index.ts
1540
+ const shapeRegistry = /* @__PURE__ */ new Map();
1541
+ function registerShape(name, handler) {
1542
+ shapeRegistry.set(name, handler);
1543
+ }
1544
+ function getShape(name) {
1545
+ return shapeRegistry.get(name);
1546
+ }
1547
+ function getShapeOrDefault(name) {
1548
+ return shapeRegistry.get(name) ?? rectHandler;
1549
+ }
1550
+ function rectHitTest(point, bounds) {
1551
+ return point.x >= bounds.x && point.x <= bounds.x + bounds.width && point.y >= bounds.y && point.y <= bounds.y + bounds.height;
1552
+ }
1553
+ function rectEdgeAnchor(bounds, direction) {
1554
+ switch (direction) {
1555
+ case "top": return {
1556
+ x: bounds.x + bounds.width / 2,
1557
+ y: bounds.y
1558
+ };
1559
+ case "bottom": return {
1560
+ x: bounds.x + bounds.width / 2,
1561
+ y: bounds.y + bounds.height
1562
+ };
1563
+ case "left": return {
1564
+ x: bounds.x,
1565
+ y: bounds.y + bounds.height / 2
1566
+ };
1567
+ case "right": return {
1568
+ x: bounds.x + bounds.width,
1569
+ y: bounds.y + bounds.height / 2
1570
+ };
1571
+ }
1572
+ }
1573
+ const rectHandler = {
1574
+ hitTest: rectHitTest,
1575
+ edgeAnchor: rectEdgeAnchor
1576
+ };
1577
+ const roundedHandler = {
1578
+ hitTest: rectHitTest,
1579
+ edgeAnchor: rectEdgeAnchor
1580
+ };
1581
+ function ellipseHitTest(point, bounds) {
1582
+ const cx = bounds.x + bounds.width / 2;
1583
+ const cy = bounds.y + bounds.height / 2;
1584
+ const rx = bounds.width / 2;
1585
+ const ry = bounds.height / 2;
1586
+ if (rx === 0 || ry === 0) return false;
1587
+ const dx = point.x - cx;
1588
+ const dy = point.y - cy;
1589
+ return dx * dx / (rx * rx) + dy * dy / (ry * ry) <= 1;
1590
+ }
1591
+ function ellipseEdgeAnchor(bounds, direction) {
1592
+ const cx = bounds.x + bounds.width / 2;
1593
+ const cy = bounds.y + bounds.height / 2;
1594
+ const rx = bounds.width / 2;
1595
+ const ry = bounds.height / 2;
1596
+ switch (direction) {
1597
+ case "top": return {
1598
+ x: cx,
1599
+ y: cy - ry
1600
+ };
1601
+ case "bottom": return {
1602
+ x: cx,
1603
+ y: cy + ry
1604
+ };
1605
+ case "left": return {
1606
+ x: cx - rx,
1607
+ y: cy
1608
+ };
1609
+ case "right": return {
1610
+ x: cx + rx,
1611
+ y: cy
1612
+ };
1613
+ }
1614
+ }
1615
+ const ellipseHandler = {
1616
+ hitTest: ellipseHitTest,
1617
+ edgeAnchor: ellipseEdgeAnchor
1618
+ };
1619
+ function diamondHitTest(point, bounds) {
1620
+ const cx = bounds.x + bounds.width / 2;
1621
+ const cy = bounds.y + bounds.height / 2;
1622
+ const hw = bounds.width / 2;
1623
+ const hh = bounds.height / 2;
1624
+ if (hw === 0 || hh === 0) return false;
1625
+ return Math.abs(point.x - cx) / hw + Math.abs(point.y - cy) / hh <= 1;
1626
+ }
1627
+ function diamondEdgeAnchor(bounds, direction) {
1628
+ const cx = bounds.x + bounds.width / 2;
1629
+ const cy = bounds.y + bounds.height / 2;
1630
+ switch (direction) {
1631
+ case "top": return {
1632
+ x: cx,
1633
+ y: bounds.y
1634
+ };
1635
+ case "bottom": return {
1636
+ x: cx,
1637
+ y: bounds.y + bounds.height
1638
+ };
1639
+ case "left": return {
1640
+ x: bounds.x,
1641
+ y: cy
1642
+ };
1643
+ case "right": return {
1644
+ x: bounds.x + bounds.width,
1645
+ y: cy
1646
+ };
1647
+ }
1648
+ }
1649
+ const diamondHandler = {
1650
+ hitTest: diamondHitTest,
1651
+ edgeAnchor: diamondEdgeAnchor
1652
+ };
1653
+ registerShape("rect", rectHandler);
1654
+ registerShape("rounded", roundedHandler);
1655
+ registerShape("ellipse", ellipseHandler);
1656
+ registerShape("diamond", diamondHandler);
1657
+ //#endregion
1658
+ //#region src/routing/index.ts
1659
+ const straightRouter = (_edge, ctx) => {
1660
+ return {
1661
+ points: [ctx.sourcePoint ?? centerOf(ctx.sourceBounds), ctx.targetPoint ?? centerOf(ctx.targetBounds)],
1662
+ sourceDirection: ctx.sourceDirection,
1663
+ targetDirection: ctx.targetDirection
1664
+ };
1665
+ };
1666
+ const stepRouter = (_edge, ctx) => {
1667
+ const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);
1668
+ const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);
1669
+ return {
1670
+ points: [
1671
+ source,
1672
+ computeStepMidpoint(source, target, ctx.sourceDirection),
1673
+ target
1674
+ ],
1675
+ sourceDirection: ctx.sourceDirection,
1676
+ targetDirection: ctx.targetDirection
1677
+ };
1678
+ };
1679
+ const bezierRouter = (_edge, ctx) => {
1680
+ const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);
1681
+ const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);
1682
+ const offset = Math.max(50, Math.abs(target.x - source.x) * .25, Math.abs(target.y - source.y) * .25);
1683
+ return {
1684
+ points: [
1685
+ source,
1686
+ offsetPoint(source, ctx.sourceDirection, offset),
1687
+ offsetPoint(target, ctx.targetDirection, offset),
1688
+ target
1689
+ ],
1690
+ sourceDirection: ctx.sourceDirection,
1691
+ targetDirection: ctx.targetDirection
1692
+ };
1693
+ };
1694
+ function centerOf(rect) {
1695
+ return {
1696
+ x: rect.x + rect.width / 2,
1697
+ y: rect.y + rect.height / 2
1698
+ };
1699
+ }
1700
+ function edgeMidpoint(rect, direction) {
1701
+ switch (direction) {
1702
+ case "top": return {
1703
+ x: rect.x + rect.width / 2,
1704
+ y: rect.y
1705
+ };
1706
+ case "bottom": return {
1707
+ x: rect.x + rect.width / 2,
1708
+ y: rect.y + rect.height
1709
+ };
1710
+ case "left": return {
1711
+ x: rect.x,
1712
+ y: rect.y + rect.height / 2
1713
+ };
1714
+ case "right": return {
1715
+ x: rect.x + rect.width,
1716
+ y: rect.y + rect.height / 2
1717
+ };
1718
+ }
1719
+ }
1720
+ function offsetPoint(point, direction, offset) {
1721
+ switch (direction) {
1722
+ case "top": return {
1723
+ x: point.x,
1724
+ y: point.y - offset
1725
+ };
1726
+ case "bottom": return {
1727
+ x: point.x,
1728
+ y: point.y + offset
1729
+ };
1730
+ case "left": return {
1731
+ x: point.x - offset,
1732
+ y: point.y
1733
+ };
1734
+ case "right": return {
1735
+ x: point.x + offset,
1736
+ y: point.y
1737
+ };
1738
+ }
1739
+ }
1740
+ function computeStepMidpoint(source, target, sourceDir) {
1741
+ if (sourceDir === "left" || sourceDir === "right") return {
1742
+ x: (source.x + target.x) / 2,
1743
+ y: source.y
1744
+ };
1745
+ return {
1746
+ x: source.x,
1747
+ y: (source.y + target.y) / 2
1748
+ };
1749
+ }
1750
+ /**
1751
+ * Determine the best side of `from` to connect toward `to`,
1752
+ * based on relative center positions.
1753
+ */
1754
+ function bestDirection(from, to) {
1755
+ const fromCx = from.x + from.width / 2;
1756
+ const fromCy = from.y + from.height / 2;
1757
+ const toCx = to.x + to.width / 2;
1758
+ const toCy = to.y + to.height / 2;
1759
+ const dx = toCx - fromCx;
1760
+ const dy = toCy - fromCy;
1761
+ if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? "right" : "left";
1762
+ return dy > 0 ? "bottom" : "top";
1763
+ }
1764
+ /**
1765
+ * Convert PathData points to an SVG path `d` attribute.
1766
+ * Handles 2 points (line), 3 points (quadratic), 4 points (cubic bezier).
1767
+ */
1768
+ function pathToSVG(path) {
1769
+ const pts = path.points;
1770
+ if (pts.length < 2) return "";
1771
+ const [p0, p1, p2, p3] = pts;
1772
+ if (!p0) return "";
1773
+ const start = `M ${p0.x} ${p0.y}`;
1774
+ if (pts.length === 2 && p1) return `${start} L ${p1.x} ${p1.y}`;
1775
+ if (pts.length === 3 && p1 && p2) return `${start} L ${p1.x} ${p1.y} L ${p2.x} ${p2.y}`;
1776
+ if (pts.length === 4 && p1 && p2 && p3) return `${start} C ${p1.x} ${p1.y}, ${p2.x} ${p2.y}, ${p3.x} ${p3.y}`;
1777
+ return start + pts.slice(1).map((p) => ` L ${p.x} ${p.y}`).join("");
1778
+ }
1779
+ //#endregion
1780
+ //#region src/config.ts
1781
+ /** Default config: everything enabled */
1782
+ const defaultConfig = {
1783
+ selectable: () => true,
1784
+ draggable: () => true,
1785
+ connectable: () => true,
1786
+ reconnectable: () => true,
1787
+ deletable: () => true,
1788
+ resizable: () => true,
1789
+ visible: () => true
1790
+ };
1791
+ /** Readonly preset: can select and view, cannot modify */
1792
+ const readonlyConfig = {
1793
+ draggable: false,
1794
+ connectable: false,
1795
+ reconnectable: false,
1796
+ deletable: false,
1797
+ resizable: false
1798
+ };
1799
+ /**
1800
+ * Resolve a behavior predicate.
1801
+ * If `false`, returns false. If function, calls it. If undefined, returns default.
1802
+ */
1803
+ function resolveBehavior(predicate, entity, state, defaultValue = true) {
1804
+ if (predicate === false) return false;
1805
+ if (predicate === void 0) return defaultValue;
1806
+ return predicate(entity, state);
1807
+ }
1808
+ //#endregion
1809
+ //#region src/engine.ts
1810
+ function createFlowEngine(store, options = {}) {
1811
+ const router = options.edgeRouter ?? bezierRouter;
1812
+ const defaultLabelAnchor = options.labelAnchor ?? "fixed";
1813
+ const canConnectHook = options.canConnect;
1814
+ const globalConfig = options.config ?? {};
1815
+ const isVisibleHook = options.isVisible;
1816
+ const edgeHitTolerance = 8;
1817
+ function ctx() {
1818
+ return store.getSnapshot().context;
1819
+ }
1820
+ function getNode(id) {
1821
+ return ctx().graph.nodes.find((n) => n.id === id);
1822
+ }
1823
+ function getEdge(id) {
1824
+ return ctx().graph.edges.find((e) => e.id === id);
1825
+ }
1826
+ function getEntity(id) {
1827
+ return getNode(id) ?? getEdge(id);
1828
+ }
1829
+ function screenToCanvas$1(screenPoint) {
1830
+ return screenToCanvas(screenPoint, ctx().viewport);
1831
+ }
1832
+ function canvasToScreen$1(canvasPoint) {
1833
+ return canvasToScreen(canvasPoint, ctx().viewport);
1834
+ }
1835
+ function entityAtPoint(canvasPoint) {
1836
+ const { graph } = ctx();
1837
+ for (let i = graph.nodes.length - 1; i >= 0; i--) {
1838
+ const node = graph.nodes[i];
1839
+ if (!node) continue;
1840
+ const bounds = resolvedBounds(node);
1841
+ if (getShapeOrDefault(node.shape ?? "rect").hitTest(canvasPoint, bounds)) return node;
1842
+ }
1843
+ const nodeMap = /* @__PURE__ */ new Map();
1844
+ for (const n of graph.nodes) nodeMap.set(n.id, n);
1845
+ for (let i = graph.edges.length - 1; i >= 0; i--) {
1846
+ const edge = graph.edges[i];
1847
+ if (!edge) continue;
1848
+ const lb = resolveEdgeLabelBounds(edge, nodeMap);
1849
+ if (lb && canvasPoint.x >= lb.x && canvasPoint.x <= lb.x + lb.width && canvasPoint.y >= lb.y && canvasPoint.y <= lb.y + lb.height) return edge;
1850
+ }
1851
+ const edgePaths = getAllEdgePaths();
1852
+ for (let i = graph.edges.length - 1; i >= 0; i--) {
1853
+ const edge = graph.edges[i];
1854
+ if (!edge) continue;
1855
+ const path = edgePaths.get(edge.id);
1856
+ if (!path) continue;
1857
+ if (path.segments.some((segment) => isPointNearPath(canvasPoint, segment, edgeHitTolerance))) return edge;
1858
+ }
1859
+ return null;
1860
+ }
1861
+ function entityIdAtPoint(canvasPoint) {
1862
+ return entityAtPoint(canvasPoint)?.id ?? null;
1863
+ }
1864
+ function getEdgePath(edgeId) {
1865
+ const { graph } = ctx();
1866
+ const edge = graph.edges.find((e) => e.id === edgeId);
1867
+ if (!edge) return null;
1868
+ const sourceNode = graph.nodes.find((n) => n.id === edge.sourceId);
1869
+ const targetNode = graph.nodes.find((n) => n.id === edge.targetId);
1870
+ if (!sourceNode || !targetNode) return null;
1871
+ const srcBounds = resolvedBounds(sourceNode);
1872
+ const tgtBounds = resolvedBounds(targetNode);
1873
+ const sourceDirection = bestDirection(srcBounds, tgtBounds);
1874
+ const targetDirection = bestDirection(tgtBounds, srcBounds);
1875
+ return router(edge, {
1876
+ sourceBounds: srcBounds,
1877
+ targetBounds: tgtBounds,
1878
+ sourceDirection,
1879
+ targetDirection,
1880
+ sourcePoint: getShapeAnchor(sourceNode, srcBounds, sourceDirection),
1881
+ targetPoint: getShapeAnchor(targetNode, tgtBounds, targetDirection),
1882
+ obstacles: []
1883
+ });
1884
+ }
1885
+ /** Resolve edge label bounds using committed (static) node positions */
1886
+ function resolveEdgeLabelBounds(edge, nodeMap) {
1887
+ if (!edge.label) return null;
1888
+ const src = nodeMap.get(edge.sourceId);
1889
+ const tgt = nodeMap.get(edge.targetId);
1890
+ if (!src || !tgt) return null;
1891
+ const srcB = {
1892
+ x: src.x,
1893
+ y: src.y,
1894
+ width: src.style?.customWidth ?? src.width,
1895
+ height: src.style?.customHeight ?? src.height
1896
+ };
1897
+ const tgtB = {
1898
+ x: tgt.x,
1899
+ y: tgt.y,
1900
+ width: tgt.style?.customWidth ?? tgt.width,
1901
+ height: tgt.style?.customHeight ?? tgt.height
1902
+ };
1903
+ const basePos = resolveLabelAnchor(edge.labelAnchor ?? defaultLabelAnchor, edge.label, srcB, tgtB);
1904
+ return {
1905
+ x: basePos.x + (edge.label.dx ?? 0),
1906
+ y: basePos.y + (edge.label.dy ?? 0),
1907
+ width: edge.label.width,
1908
+ height: edge.label.height
1909
+ };
1910
+ }
1911
+ /** Build selection bounding rect with properly resolved edge labels */
1912
+ function getSelectionSnapBounds(c) {
1913
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1914
+ const nodeMap = /* @__PURE__ */ new Map();
1915
+ for (const n of c.graph.nodes) nodeMap.set(n.id, n);
1916
+ for (const n of c.graph.nodes) {
1917
+ if (!c.selection.has(n.id)) continue;
1918
+ const b = resolvedBounds(n);
1919
+ minX = Math.min(minX, b.x);
1920
+ minY = Math.min(minY, b.y);
1921
+ maxX = Math.max(maxX, b.x + b.width);
1922
+ maxY = Math.max(maxY, b.y + b.height);
1923
+ }
1924
+ for (const e of c.graph.edges) {
1925
+ if (!c.selection.has(e.id)) continue;
1926
+ const lb = resolveEdgeLabelBounds(e, nodeMap);
1927
+ if (!lb) continue;
1928
+ minX = Math.min(minX, lb.x);
1929
+ minY = Math.min(minY, lb.y);
1930
+ maxX = Math.max(maxX, lb.x + lb.width);
1931
+ maxY = Math.max(maxY, lb.y + lb.height);
1932
+ }
1933
+ if (!isFinite(minX)) return null;
1934
+ return {
1935
+ x: minX,
1936
+ y: minY,
1937
+ width: maxX - minX,
1938
+ height: maxY - minY
1939
+ };
1940
+ }
1941
+ /** Collect snap target rects from non-selected nodes + resolved edge label bounds.
1942
+ * Filters to entities at least partially in viewport and not overlapped by selection. */
1943
+ function getSnapTargetRects(c, selection, selBounds) {
1944
+ const vp = c.viewport;
1945
+ const vs = c.viewportSize;
1946
+ const viewRect = {
1947
+ x: -vp.x / vp.zoom,
1948
+ y: -vp.y / vp.zoom,
1949
+ width: vs.width / vp.zoom,
1950
+ height: vs.height / vp.zoom
1951
+ };
1952
+ const rects = [];
1953
+ const nodeMap = /* @__PURE__ */ new Map();
1954
+ for (const n of c.graph.nodes) {
1955
+ nodeMap.set(n.id, n);
1956
+ if (!selection.has(n.id) && !n.hidden) {
1957
+ const b = resolvedBounds(n);
1958
+ if (rectsIntersect(b, viewRect) && (!selBounds || !rectContains(selBounds, b))) rects.push(b);
1959
+ }
1960
+ }
1961
+ for (const edge of c.graph.edges) {
1962
+ if (selection.has(edge.id)) continue;
1963
+ const lb = resolveEdgeLabelBounds(edge, nodeMap);
1964
+ if (lb && rectsIntersect(lb, viewRect) && (!selBounds || !rectContains(selBounds, lb))) rects.push(lb);
1965
+ }
1966
+ return rects;
1967
+ }
1968
+ /** Check if rect `a` fully contains rect `b` */
1969
+ function rectContains(a, b) {
1970
+ return b.x >= a.x && b.y >= a.y && b.x + b.width <= a.x + a.width && b.y + b.height <= a.y + a.height;
1971
+ }
1972
+ /**
1973
+ * Compute visual snap offset for edge routing.
1974
+ * Returns the offset to apply to selected nodes so edges follow the snapped visual position.
1975
+ */
1976
+ function getVisualSnapOffset() {
1977
+ const c = ctx();
1978
+ const selection = c.selection;
1979
+ const grid = c.snapToGrid ? c.snapGrid : null;
1980
+ let offset = {
1981
+ x: 0,
1982
+ y: 0
1983
+ };
1984
+ const nodesMoved = c.canvasState === "dragging" && c.graph.nodes.some((n) => selection.has(n.id) && ((n.dx ?? 0) !== 0 || (n.dy ?? 0) !== 0));
1985
+ const edgesMoved = c.canvasState === "dragging" && c.graph.edges.some((e) => selection.has(e.id) && e.label && ((e.label.dx ?? 0) !== 0 || (e.label.dy ?? 0) !== 0));
1986
+ if ((nodesMoved || edgesMoved) && c.enableSnapLines) {
1987
+ const selBounds = getSelectionSnapBounds(c);
1988
+ if (selBounds) {
1989
+ const snapResult = getSnapLines(selBounds, getSnapTargetRects(c, selection, selBounds), {
1990
+ threshold: c.snapThreshold / c.viewport.zoom,
1991
+ enableSpacing: c.enableSpacingGuides
1992
+ });
1993
+ if (snapResult) offset = {
1994
+ x: snapResult.snapRect.x - selBounds.x,
1995
+ y: snapResult.snapRect.y - selBounds.y
1996
+ };
1997
+ }
1998
+ }
1999
+ return {
2000
+ offset,
2001
+ grid,
2002
+ selection
2003
+ };
2004
+ }
2005
+ /** Get visual bounds for a node — applies snap offset for selected nodes during drag */
2006
+ function visualBounds(node, snap) {
2007
+ const entityOffset = snap.selection.has(node.id) ? snap.offset : null;
2008
+ return snappedBounds(node, snap.grid, entityOffset);
2009
+ }
2010
+ /** Get visual position for a node — applies snap offset for selected nodes during drag */
2011
+ function visualPosition(node, snap) {
2012
+ const b = visualBounds(node, snap);
2013
+ return {
2014
+ x: b.x,
2015
+ y: b.y
2016
+ };
2017
+ }
2018
+ /** Get bounds for edge endpoint — port bounds if specified, otherwise node bounds */
2019
+ function getEndpointBounds(node, portName, snap) {
2020
+ if (portName && portName !== "*" && node.ports) {
2021
+ const port = node.ports.find((p) => p.name === portName);
2022
+ if (port) {
2023
+ const np = snap ? visualPosition(node, snap) : resolvedPosition(node);
2024
+ return {
2025
+ x: np.x + port.x,
2026
+ y: np.y + port.y,
2027
+ width: port.width,
2028
+ height: port.height
2029
+ };
2030
+ }
2031
+ }
2032
+ if (snap) return visualBounds(node, snap);
2033
+ return resolvedBounds(node);
2034
+ }
2035
+ function getShapeAnchor(node, bounds, direction) {
2036
+ return getShapeOrDefault(node.shape ?? "rect").edgeAnchor(bounds, direction);
2037
+ }
2038
+ function resolveEndpointPoint(node, nodeBounds, portName, otherBounds, fallbackDirection, snap) {
2039
+ if (portName === "*" && node.ports?.length) return closestPortPosition(node, {
2040
+ x: otherBounds.x + otherBounds.width / 2,
2041
+ y: otherBounds.y + otherBounds.height / 2
2042
+ });
2043
+ if (portName && portName !== "*" && node.ports) {
2044
+ const port = node.ports.find((p) => p.name === portName);
2045
+ if (port) {
2046
+ const position = snap ? visualPosition(node, snap) : resolvedPosition(node);
2047
+ return {
2048
+ x: position.x + port.x + port.width / 2,
2049
+ y: position.y + port.y + port.height / 2
2050
+ };
2051
+ }
2052
+ }
2053
+ return getShapeAnchor(node, nodeBounds, fallbackDirection);
2054
+ }
2055
+ function getAllEdgePaths() {
2056
+ const { graph } = ctx();
2057
+ const paths = /* @__PURE__ */ new Map();
2058
+ const snap = getVisualSnapOffset();
2059
+ const nodeMap = /* @__PURE__ */ new Map();
2060
+ for (const n of graph.nodes) nodeMap.set(n.id, n);
2061
+ for (const edge of graph.edges) {
2062
+ const source = nodeMap.get(edge.sourceId);
2063
+ const target = nodeMap.get(edge.targetId);
2064
+ if (!source || !target) continue;
2065
+ const sourceBounds = getEndpointBounds(source, edge.sourcePort, snap);
2066
+ const targetBounds = getEndpointBounds(target, edge.targetPort, snap);
2067
+ const sourceDirection = bestDirection(sourceBounds, targetBounds);
2068
+ const targetDirection = bestDirection(targetBounds, sourceBounds);
2069
+ const sourcePoint = resolveEndpointPoint(source, sourceBounds, edge.sourcePort, targetBounds, targetDirection, snap);
2070
+ const targetPoint = resolveEndpointPoint(target, targetBounds, edge.targetPort, sourceBounds, sourceDirection, snap);
2071
+ if (edge.label) {
2072
+ const basePos = resolveLabelAnchor(edge.labelAnchor ?? defaultLabelAnchor, edge.label, sourceBounds, targetBounds);
2073
+ const snapOff = snap.selection.has(edge.id) ? snap.offset : {
2074
+ x: 0,
2075
+ y: 0
2076
+ };
2077
+ const labelBounds = {
2078
+ x: basePos.x + (edge.label.dx ?? 0) + snapOff.x,
2079
+ y: basePos.y + (edge.label.dy ?? 0) + snapOff.y,
2080
+ width: edge.label.width,
2081
+ height: edge.label.height
2082
+ };
2083
+ const seg1 = router(edge, {
2084
+ sourceBounds,
2085
+ targetBounds: labelBounds,
2086
+ sourceDirection: bestDirection(sourceBounds, labelBounds),
2087
+ targetDirection: bestDirection(labelBounds, sourceBounds),
2088
+ sourcePoint,
2089
+ obstacles: []
2090
+ });
2091
+ const seg2 = router(edge, {
2092
+ sourceBounds: labelBounds,
2093
+ targetBounds,
2094
+ sourceDirection: bestDirection(labelBounds, targetBounds),
2095
+ targetDirection: bestDirection(targetBounds, labelBounds),
2096
+ targetPoint,
2097
+ obstacles: []
2098
+ });
2099
+ paths.set(edge.id, {
2100
+ segments: [seg1, seg2],
2101
+ labelBounds
2102
+ });
2103
+ } else {
2104
+ const path = router(edge, {
2105
+ sourceBounds,
2106
+ targetBounds,
2107
+ sourceDirection: bestDirection(sourceBounds, targetBounds),
2108
+ targetDirection: bestDirection(targetBounds, sourceBounds),
2109
+ sourcePoint,
2110
+ targetPoint,
2111
+ obstacles: []
2112
+ });
2113
+ paths.set(edge.id, {
2114
+ segments: [path],
2115
+ labelBounds: null
2116
+ });
2117
+ }
2118
+ }
2119
+ return paths;
2120
+ }
2121
+ function subscribe(listener) {
2122
+ const subscription = store.subscribe((snapshot) => {
2123
+ listener(snapshot.context);
2124
+ });
2125
+ return () => subscription.unsubscribe();
2126
+ }
2127
+ return {
2128
+ store,
2129
+ trigger: store.trigger,
2130
+ getContext: ctx,
2131
+ getNode,
2132
+ getEdge,
2133
+ getEntity,
2134
+ screenToCanvas: screenToCanvas$1,
2135
+ canvasToScreen: canvasToScreen$1,
2136
+ entityAtPoint,
2137
+ entityIdAtPoint,
2138
+ getEdgePath,
2139
+ getAllEdgePaths,
2140
+ resolvedPosition: (nodeOrId) => {
2141
+ const node = typeof nodeOrId === "string" ? getNode(nodeOrId) : nodeOrId;
2142
+ if (!node) return {
2143
+ x: 0,
2144
+ y: 0
2145
+ };
2146
+ return resolvedPosition(node);
2147
+ },
2148
+ resolvedBounds: (nodeOrId) => {
2149
+ const node = typeof nodeOrId === "string" ? getNode(nodeOrId) : nodeOrId;
2150
+ if (!node) return {
2151
+ x: 0,
2152
+ y: 0,
2153
+ width: 0,
2154
+ height: 0
2155
+ };
2156
+ return resolvedBounds(node);
2157
+ },
2158
+ getGraphBounds: () => getGraphBounds(ctx().graph.nodes, ctx().graph.edges),
2159
+ getSelectionBounds: () => {
2160
+ const c = ctx();
2161
+ return getSelectionBounds(c.graph.nodes, c.graph.edges, c.selection);
2162
+ },
2163
+ entitiesInRect: (rect) => {
2164
+ const { graph } = ctx();
2165
+ const ids = [];
2166
+ for (const n of graph.nodes) if (rectsIntersect(rect, resolvedBounds(n))) ids.push(n.id);
2167
+ for (const e of graph.edges) {
2168
+ if (e.label) {
2169
+ if (rectsIntersect(rect, {
2170
+ x: e.label.x + (e.label.dx ?? 0),
2171
+ y: e.label.y + (e.label.dy ?? 0),
2172
+ width: e.label.width,
2173
+ height: e.label.height
2174
+ })) ids.push(e.id);
2175
+ continue;
2176
+ }
2177
+ const path = getAllEdgePaths().get(e.id);
2178
+ if (path && path.segments.some((segment) => rectIntersectsPath(rect, segment))) ids.push(e.id);
2179
+ }
2180
+ return ids;
2181
+ },
2182
+ getPortPosition: (nodeId, portName) => {
2183
+ const node = getNode(nodeId);
2184
+ if (!node?.ports) return null;
2185
+ const port = node.ports.find((p) => p.name === portName);
2186
+ if (!port) return null;
2187
+ const np = resolvedPosition(node);
2188
+ return {
2189
+ x: np.x + port.x + port.width / 2,
2190
+ y: np.y + port.y + port.height / 2
2191
+ };
2192
+ },
2193
+ getPortPositions: (nodeId) => {
2194
+ const result = /* @__PURE__ */ new Map();
2195
+ const node = getNode(nodeId);
2196
+ if (!node?.ports) return result;
2197
+ const np = resolvedPosition(node);
2198
+ for (const port of node.ports) result.set(port.name, {
2199
+ x: np.x + port.x + port.width / 2,
2200
+ y: np.y + port.y + port.height / 2
2201
+ });
2202
+ return result;
2203
+ },
2204
+ getEdgeEndpoints: (edgeId) => {
2205
+ const { graph } = ctx();
2206
+ const edge = graph.edges.find((e) => e.id === edgeId);
2207
+ if (!edge) return null;
2208
+ const srcNode = graph.nodes.find((n) => n.id === edge.sourceId);
2209
+ const tgtNode = graph.nodes.find((n) => n.id === edge.targetId);
2210
+ if (!srcNode || !tgtNode) return null;
2211
+ const snap = getVisualSnapOffset();
2212
+ const srcBounds = visualBounds(srcNode, snap);
2213
+ const tgtBounds = visualBounds(tgtNode, snap);
2214
+ let source;
2215
+ if (edge.sourcePort === "*" && srcNode.ports?.length) source = closestPortPosition(srcNode, {
2216
+ x: tgtBounds.x + tgtBounds.width / 2,
2217
+ y: tgtBounds.y + tgtBounds.height / 2
2218
+ });
2219
+ else if (edge.sourcePort && srcNode.ports) {
2220
+ const port = srcNode.ports.find((p) => p.name === edge.sourcePort);
2221
+ if (port) {
2222
+ const np = visualPosition(srcNode, snap);
2223
+ source = {
2224
+ x: np.x + port.x + port.width / 2,
2225
+ y: np.y + port.y + port.height / 2
2226
+ };
2227
+ } else source = {
2228
+ x: srcBounds.x + srcBounds.width / 2,
2229
+ y: srcBounds.y + srcBounds.height / 2
2230
+ };
2231
+ } else source = getShapeAnchor(srcNode, srcBounds, bestDirection(srcBounds, tgtBounds));
2232
+ let target;
2233
+ if (edge.targetPort === "*" && tgtNode.ports?.length) target = closestPortPosition(tgtNode, {
2234
+ x: srcBounds.x + srcBounds.width / 2,
2235
+ y: srcBounds.y + srcBounds.height / 2
2236
+ });
2237
+ else if (edge.targetPort && tgtNode.ports) {
2238
+ const port = tgtNode.ports.find((p) => p.name === edge.targetPort);
2239
+ if (port) {
2240
+ const np = visualPosition(tgtNode, snap);
2241
+ target = {
2242
+ x: np.x + port.x + port.width / 2,
2243
+ y: np.y + port.y + port.height / 2
2244
+ };
2245
+ } else target = {
2246
+ x: tgtBounds.x + tgtBounds.width / 2,
2247
+ y: tgtBounds.y + tgtBounds.height / 2
2248
+ };
2249
+ } else target = getShapeAnchor(tgtNode, tgtBounds, bestDirection(tgtBounds, srcBounds));
2250
+ return {
2251
+ source,
2252
+ target
2253
+ };
2254
+ },
2255
+ validateConnection: (proposed) => {
2256
+ const { graph } = ctx();
2257
+ const srcNode = graph.nodes.find((n) => n.id === proposed.sourceId);
2258
+ const tgtNode = graph.nodes.find((n) => n.id === proposed.targetId);
2259
+ if (!srcNode || !tgtNode) return false;
2260
+ if (proposed.sourcePort && srcNode.ports) {
2261
+ const port = srcNode.ports.find((p) => p.name === proposed.sourcePort);
2262
+ if (port && port.direction === "in") return false;
2263
+ }
2264
+ if (proposed.targetPort && tgtNode.ports) {
2265
+ const port = tgtNode.ports.find((p) => p.name === proposed.targetPort);
2266
+ if (port && port.direction === "out") return false;
2267
+ }
2268
+ if (canConnectHook && !canConnectHook(proposed)) return false;
2269
+ return true;
2270
+ },
2271
+ resolveEntityConfig: (entityOrId) => {
2272
+ const entity = typeof entityOrId === "string" ? getEntity(entityOrId) : entityOrId;
2273
+ if (!entity) return {
2274
+ hidden: false,
2275
+ selectable: true,
2276
+ draggable: true,
2277
+ connectable: true,
2278
+ reconnectable: true,
2279
+ deletable: true,
2280
+ resizable: true
2281
+ };
2282
+ const c = ctx();
2283
+ return {
2284
+ hidden: entity.hidden ?? (globalConfig.visible ? !resolveBehavior(globalConfig.visible, entity, c) : false),
2285
+ selectable: entity.selectable ?? resolveBehavior(globalConfig.selectable, entity, c, true),
2286
+ draggable: entity.draggable ?? resolveBehavior(globalConfig.draggable, entity, c, true),
2287
+ connectable: entity.connectable ?? resolveBehavior(globalConfig.connectable, entity, c, true),
2288
+ reconnectable: entity.reconnectable ?? resolveBehavior(globalConfig.reconnectable, entity, c, true),
2289
+ deletable: entity.deletable ?? resolveBehavior(globalConfig.deletable, entity, c, true),
2290
+ resizable: entity.resizable ?? resolveBehavior(globalConfig.resizable, entity, c, false)
2291
+ };
2292
+ },
2293
+ getVisibleEntities: () => {
2294
+ return {
2295
+ nodes: ctx().graph.nodes.filter((n) => {
2296
+ if (n.hidden) return false;
2297
+ if (globalConfig.visible && !resolveBehavior(globalConfig.visible, n, ctx())) return false;
2298
+ if (isVisibleHook && !isVisibleHook(n, ctx().viewport)) return false;
2299
+ return true;
2300
+ }),
2301
+ edges: ctx().graph.edges.filter((e) => {
2302
+ if (e.hidden) return false;
2303
+ if (globalConfig.visible && !resolveBehavior(globalConfig.visible, e, ctx())) return false;
2304
+ if (isVisibleHook && !isVisibleHook(e, ctx().viewport)) return false;
2305
+ return true;
2306
+ })
2307
+ };
2308
+ },
2309
+ getRenderableEntities: (options = {}) => {
2310
+ const c = ctx();
2311
+ const vp = c.viewport;
2312
+ const overscan = options.overscan ?? 0;
2313
+ const visibleRect = getVisibleBounds(vp, c.viewportSize);
2314
+ const cullRect = {
2315
+ x: visibleRect.x - overscan,
2316
+ y: visibleRect.y - overscan,
2317
+ width: visibleRect.width + overscan * 2,
2318
+ height: visibleRect.height + overscan * 2
2319
+ };
2320
+ const nodes = c.graph.nodes.filter((n) => {
2321
+ if (n.hidden) return false;
2322
+ if (globalConfig.visible && !resolveBehavior(globalConfig.visible, n, c)) return false;
2323
+ if (isVisibleHook && !isVisibleHook(n, vp)) return false;
2324
+ if (options.cull === "viewport" && !rectsIntersect(resolvedBounds(n), cullRect)) return false;
2325
+ return true;
2326
+ });
2327
+ const edgePaths = getAllEdgePaths();
2328
+ return {
2329
+ nodes,
2330
+ edges: c.graph.edges.filter((e) => {
2331
+ if (e.hidden) return false;
2332
+ if (globalConfig.visible && !resolveBehavior(globalConfig.visible, e, c)) return false;
2333
+ if (isVisibleHook && !isVisibleHook(e, vp)) return false;
2334
+ if (options.cull !== "viewport") return true;
2335
+ if (e.label) {
2336
+ if (rectsIntersect({
2337
+ x: e.label.x + (e.label.dx ?? 0),
2338
+ y: e.label.y + (e.label.dy ?? 0),
2339
+ width: e.label.width,
2340
+ height: e.label.height
2341
+ }, cullRect)) return true;
2342
+ }
2343
+ if (edgePaths.get(e.id)?.segments.some((segment) => rectIntersectsPath(cullRect, segment))) return true;
2344
+ const srcNode = getNode(e.sourceId);
2345
+ const tgtNode = getNode(e.targetId);
2346
+ return !!srcNode && !!tgtNode && (rectsIntersect(resolvedBounds(srcNode), cullRect) || rectsIntersect(resolvedBounds(tgtNode), cullRect));
2347
+ })
2348
+ };
2349
+ },
2350
+ getIntersectingNodes: (nodeId) => {
2351
+ const node = getNode(nodeId);
2352
+ if (!node) return [];
2353
+ const bounds = resolvedBounds(node);
2354
+ return ctx().graph.nodes.filter((n) => n.id !== nodeId && rectsIntersect(bounds, resolvedBounds(n)));
2355
+ },
2356
+ getAriaLabel: (entityId) => {
2357
+ const { graph } = ctx();
2358
+ const node = graph.nodes.find((n) => n.id === entityId);
2359
+ if (node) return `Node: ${node.label ?? node.id}`;
2360
+ const edge = graph.edges.find((e) => e.id === entityId);
2361
+ if (edge) {
2362
+ const src = graph.nodes.find((n) => n.id === edge.sourceId);
2363
+ const tgt = graph.nodes.find((n) => n.id === edge.targetId);
2364
+ const label = edge.label ? ` (${edge.label.data?.text ?? ""})` : "";
2365
+ return `Edge: ${src?.label ?? edge.sourceId} → ${tgt?.label ?? edge.targetId}${label}`;
2366
+ }
2367
+ return entityId;
2368
+ },
2369
+ /** Compute snap result during drag. Returns null if not dragging or snap lines disabled.
2370
+ * Only activates after actual movement (dx/dy != 0) to avoid showing on click. */
2371
+ getSnapResult: () => {
2372
+ const c = ctx();
2373
+ if (c.canvasState !== "dragging" || !c.enableSnapLines) return null;
2374
+ if (c.selection.size === 0) return null;
2375
+ const nodesMoved = c.graph.nodes.some((n) => c.selection.has(n.id) && ((n.dx ?? 0) !== 0 || (n.dy ?? 0) !== 0));
2376
+ const edgesMoved = c.graph.edges.some((e) => c.selection.has(e.id) && e.label && ((e.label.dx ?? 0) !== 0 || (e.label.dy ?? 0) !== 0));
2377
+ if (!nodesMoved && !edgesMoved) return null;
2378
+ const selBounds = getSelectionSnapBounds(c);
2379
+ if (!selBounds) return null;
2380
+ const otherRects = getSnapTargetRects(c, c.selection, selBounds);
2381
+ if (otherRects.length === 0) return null;
2382
+ return getSnapLines(selBounds, otherRects, {
2383
+ threshold: c.snapThreshold / c.viewport.zoom,
2384
+ enableSpacing: c.enableSpacingGuides
2385
+ });
2386
+ },
2387
+ /** Get in-progress resize bounds, or null if not resizing */
2388
+ getResizeBounds: () => {
2389
+ const c = ctx();
2390
+ if (!c.resizeCorners || !c.resizingEntityId) return null;
2391
+ const [a, b] = c.resizeCorners;
2392
+ return {
2393
+ x: Math.min(a.x, b.x),
2394
+ y: Math.min(a.y, b.y),
2395
+ width: Math.max(10, Math.abs(b.x - a.x)),
2396
+ height: Math.max(10, Math.abs(b.y - a.y))
2397
+ };
2398
+ },
2399
+ subscribe
2400
+ };
2401
+ }
2402
+ function closestPortPosition(node, target) {
2403
+ if (!node.ports?.length) {
2404
+ const b = resolvedBounds(node);
2405
+ return {
2406
+ x: b.x + b.width / 2,
2407
+ y: b.y + b.height / 2
2408
+ };
2409
+ }
2410
+ const np = resolvedPosition(node);
2411
+ let best = {
2412
+ x: np.x,
2413
+ y: np.y
2414
+ };
2415
+ let bestDist = Infinity;
2416
+ for (const port of node.ports) {
2417
+ const px = np.x + port.x + port.width / 2;
2418
+ const py = np.y + port.y + port.height / 2;
2419
+ const d = (px - target.x) ** 2 + (py - target.y) ** 2;
2420
+ if (d < bestDist) {
2421
+ bestDist = d;
2422
+ best = {
2423
+ x: px,
2424
+ y: py
2425
+ };
2426
+ }
2427
+ }
2428
+ return best;
2429
+ }
2430
+ /**
2431
+ * Resolve label anchor position. Returns the TOP-LEFT corner of the label.
2432
+ * For 'fixed': label.x/y IS the top-left (like a node).
2433
+ * For number: interpolates between source/target centers, then offsets to top-left.
2434
+ * For function: calls the function, then offsets to top-left.
2435
+ */
2436
+ function resolveLabelAnchor(anchor, label, sourceBounds, targetBounds) {
2437
+ if (anchor === "fixed") return {
2438
+ x: label.x,
2439
+ y: label.y
2440
+ };
2441
+ if (typeof anchor === "function") {
2442
+ const center = anchor(sourceBounds, targetBounds);
2443
+ return {
2444
+ x: center.x - label.width / 2,
2445
+ y: center.y - label.height / 2
2446
+ };
2447
+ }
2448
+ const t = anchor;
2449
+ const srcCx = sourceBounds.x + sourceBounds.width / 2;
2450
+ const srcCy = sourceBounds.y + sourceBounds.height / 2;
2451
+ const tgtCx = targetBounds.x + targetBounds.width / 2;
2452
+ const tgtCy = targetBounds.y + targetBounds.height / 2;
2453
+ return {
2454
+ x: srcCx + (tgtCx - srcCx) * t - label.width / 2,
2455
+ y: srcCy + (tgtCy - srcCy) * t - label.height / 2
2456
+ };
2457
+ }
2458
+ //#endregion
2459
+ //#region src/createFlow.ts
2460
+ function createFlow(options = {}) {
2461
+ const store = createFlowStore(options.graph, options.store);
2462
+ const engine = createFlowEngine(store, options.engine);
2463
+ const cleanup = /* @__PURE__ */ new Set();
2464
+ if (options.onConnectionEnd) {
2465
+ const subscription = store.on("connectionEnded", options.onConnectionEnd);
2466
+ cleanup.add(() => subscription.unsubscribe());
2467
+ }
2468
+ function destroy() {
2469
+ for (const dispose of cleanup) dispose();
2470
+ cleanup.clear();
2471
+ }
2472
+ async function runLayout(layout = options.layout ?? void 0) {
2473
+ if (!layout) throw new Error("No layout algorithm was provided");
2474
+ const positions = await layout(store.getSnapshot().context.graph);
2475
+ store.trigger.applyLayoutResult({ positions });
2476
+ }
2477
+ return {
2478
+ store,
2479
+ engine,
2480
+ trigger: store.trigger,
2481
+ destroy,
2482
+ getContext: engine.getContext,
2483
+ subscribe: engine.subscribe,
2484
+ getNode: engine.getNode,
2485
+ getEdge: engine.getEdge,
2486
+ getEntity: engine.getEntity,
2487
+ screenToCanvas: engine.screenToCanvas,
2488
+ canvasToScreen: engine.canvasToScreen,
2489
+ getAllEdgePaths: engine.getAllEdgePaths,
2490
+ getGraphBounds: engine.getGraphBounds,
2491
+ getSelectionBounds: engine.getSelectionBounds,
2492
+ getRenderableEntities: engine.getRenderableEntities,
2493
+ runLayout
2494
+ };
2495
+ }
2496
+ //#endregion
2497
+ //#region src/factories.ts
2498
+ function createNode(opts) {
2499
+ return {
2500
+ type: "node",
2501
+ x: 0,
2502
+ y: 0,
2503
+ width: 150,
2504
+ height: 50,
2505
+ data: {},
2506
+ ...opts
2507
+ };
2508
+ }
2509
+ function createEdge(opts) {
2510
+ const { label, ...rest } = opts;
2511
+ return {
2512
+ type: "edge",
2513
+ x: 0,
2514
+ y: 0,
2515
+ width: 0,
2516
+ height: 0,
2517
+ data: {},
2518
+ ...rest,
2519
+ label: label ? {
2520
+ x: 0,
2521
+ y: 0,
2522
+ data: {},
2523
+ ...label
2524
+ } : void 0
2525
+ };
2526
+ }
2527
+ function createGraph(opts) {
2528
+ return {
2529
+ direction: "down",
2530
+ ...opts
2531
+ };
2532
+ }
2533
+ //#endregion
2534
+ export { bestDirection, bezierRouter, boxToRect, calcAutoPan, canvasToScreen, clampZoom, constrainViewport, createEdge, createFlow, createFlowEngine, createFlowStore, createGraph, createNode, createViewport, defaultConfig, getAnchorTransform, getGraphBounds, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getVisibleBounds, isTrackpadPinch, normalizeWheelPan, panBy, pathToSVG, readonlyConfig, rectContains, rectsIntersect, registerShape, resolveBehavior, resolvedBounds, resolvedPosition, screenToCanvas, selectMode, snapPointToGrid, snapToGrid, snappedBounds, stepRouter, straightRouter, toSVGTransform, toViewBox, viewportForBounds, wheelInteraction, wheelZoomDelta, zoomTo };