@m3ui-vue/m3ui-vue 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/dist/API.md +2776 -351
  2. package/dist/MButton-CuNzpoxm.js +172 -0
  3. package/dist/MButton-CuNzpoxm.js.map +1 -0
  4. package/dist/MDialog-HxEL-m58.js +173 -0
  5. package/dist/MDialog-HxEL-m58.js.map +1 -0
  6. package/dist/MIconButton-DoNotQ9v.js +282 -0
  7. package/dist/MIconButton-DoNotQ9v.js.map +1 -0
  8. package/dist/MListItem-DnPtv-hY.js +824 -0
  9. package/dist/MListItem-DnPtv-hY.js.map +1 -0
  10. package/dist/MLoadingIndicator-BQMNX6Dx.js +115 -0
  11. package/dist/MLoadingIndicator-BQMNX6Dx.js.map +1 -0
  12. package/dist/MMenuItem-Bih0h4-n.js +604 -0
  13. package/dist/MMenuItem-Bih0h4-n.js.map +1 -0
  14. package/dist/MProgressBar-BCoruxA-.js +184 -0
  15. package/dist/MProgressBar-BCoruxA-.js.map +1 -0
  16. package/dist/MSeekBar-LURE1Ah7.js +435 -0
  17. package/dist/MSeekBar-LURE1Ah7.js.map +1 -0
  18. package/dist/MSegmentedButton-DL9JtJFX.js +65 -0
  19. package/dist/MSegmentedButton-DL9JtJFX.js.map +1 -0
  20. package/dist/MSlider-_J4IS2_z.js +691 -0
  21. package/dist/MSlider-_J4IS2_z.js.map +1 -0
  22. package/dist/MSpinner-BhkMYKOM.js +65 -0
  23. package/dist/MSpinner-BhkMYKOM.js.map +1 -0
  24. package/dist/MTextField-CkzwNBWS.js +296 -0
  25. package/dist/MTextField-CkzwNBWS.js.map +1 -0
  26. package/dist/MTooltip-B67ZDSGp.js +756 -0
  27. package/dist/MTooltip-B67ZDSGp.js.map +1 -0
  28. package/dist/_storageKeys-CYXsUBwK.js +18 -0
  29. package/dist/_storageKeys-CYXsUBwK.js.map +1 -0
  30. package/dist/_useEscapeStack-CjndQhqg.js +19 -0
  31. package/dist/_useEscapeStack-CjndQhqg.js.map +1 -0
  32. package/dist/api.json +1 -1
  33. package/dist/chart.js +1 -1
  34. package/dist/code-editor.js +1 -1
  35. package/dist/components/MAudioPlayer.vue.d.ts +115 -0
  36. package/dist/components/MBadge.vue.d.ts +1 -1
  37. package/dist/components/MBottomSheetScaffold.vue.d.ts +1 -1
  38. package/dist/components/MBox.vue.d.ts +1 -1
  39. package/dist/components/MButton.vue.d.ts +1 -1
  40. package/dist/components/MConfirmDialog.vue.d.ts +1 -1
  41. package/dist/components/MCopyButton.vue.d.ts +2 -2
  42. package/dist/components/MDataTable.vue.d.ts +2 -2
  43. package/dist/components/MDialog.vue.d.ts +2 -2
  44. package/dist/components/MDivider.vue.d.ts +1 -1
  45. package/dist/components/MDragHandle.vue.d.ts +1 -1
  46. package/dist/components/MDrawCanvas.vue.d.ts +148 -0
  47. package/dist/components/MDrawLayers.vue.d.ts +3 -0
  48. package/dist/components/MDrawToolbar.vue.d.ts +34 -0
  49. package/dist/components/MExportButton.vue.d.ts +1 -1
  50. package/dist/components/MFab.vue.d.ts +2 -2
  51. package/dist/components/MFabMenu.vue.d.ts +2 -2
  52. package/dist/components/MFixed.vue.d.ts +1 -1
  53. package/dist/components/MFlex.vue.d.ts +2 -2
  54. package/dist/components/MFloorPlan.vue.d.ts +160 -0
  55. package/dist/components/MFlow.vue.d.ts +305 -0
  56. package/dist/components/MFlowControls.vue.d.ts +33 -0
  57. package/dist/components/MFlowHandle.vue.d.ts +16 -0
  58. package/dist/components/MFlowMinimap.vue.d.ts +22 -0
  59. package/dist/components/MFlowNode.vue.d.ts +35 -0
  60. package/dist/components/MGantt.vue.d.ts +141 -0
  61. package/dist/components/MGanttControls.vue.d.ts +32 -0
  62. package/dist/components/MIconButton.vue.d.ts +3 -1
  63. package/dist/components/MImageCropper.vue.d.ts +110 -0
  64. package/dist/components/MInfiniteScroll.vue.d.ts +1 -1
  65. package/dist/components/MLightbox.vue.d.ts +2 -2
  66. package/dist/components/MList.vue.d.ts +1 -1
  67. package/dist/components/MLoadingOverlay.vue.d.ts +1 -1
  68. package/dist/components/MMapControl.vue.d.ts +1 -1
  69. package/dist/components/MMapSearch.vue.d.ts +1 -1
  70. package/dist/components/MMaskField.vue.d.ts +12 -1
  71. package/dist/components/MMenu.vue.d.ts +1 -1
  72. package/dist/components/MNavigationDrawer.vue.d.ts +1 -1
  73. package/dist/components/MNumberField.vue.d.ts +11 -2
  74. package/dist/components/MPdfViewer.vue.d.ts +174 -0
  75. package/dist/components/MPullToRefresh.vue.d.ts +1 -1
  76. package/dist/components/MResourceTimeline.vue.d.ts +149 -0
  77. package/dist/components/MScheduler.vue.d.ts +3 -3
  78. package/dist/components/MScheme.vue.d.ts +1 -1
  79. package/dist/components/MSearchField.vue.d.ts +1 -1
  80. package/dist/components/MSeekBar.vue.d.ts +1 -1
  81. package/dist/components/MSimpleCarousel.vue.d.ts +1 -1
  82. package/dist/components/MSkeleton.vue.d.ts +1 -1
  83. package/dist/components/MSlider.vue.d.ts +2 -2
  84. package/dist/components/MSparkline.vue.d.ts +1 -1
  85. package/dist/components/MSplitter.vue.d.ts +1 -1
  86. package/dist/components/MStack.vue.d.ts +2 -2
  87. package/dist/components/MSwipeToDismiss.vue.d.ts +1 -1
  88. package/dist/components/MSwitch.vue.d.ts +1 -1
  89. package/dist/components/MTable.vue.d.ts +1 -1
  90. package/dist/components/MTagInput.vue.d.ts +12 -1
  91. package/dist/components/MTextField.vue.d.ts +13 -2
  92. package/dist/components/MToolbar.vue.d.ts +1 -1
  93. package/dist/components/MTree.vue.d.ts +2 -2
  94. package/dist/components/MVideoPlayer.vue.d.ts +253 -0
  95. package/dist/components/MVirtualTable.vue.d.ts +1 -1
  96. package/dist/components/MWindow.vue.d.ts +3 -3
  97. package/dist/components/_MFlowEdge.vue.d.ts +9 -0
  98. package/dist/components/_MFlowEdgeLabel.vue.d.ts +9 -0
  99. package/dist/components/_MFlowNodeShell.vue.d.ts +9 -0
  100. package/dist/components/_MPdfPage.vue.d.ts +76 -0
  101. package/dist/components/_MTimeBackground.vue.d.ts +14 -0
  102. package/dist/components/_MTimeHeader.vue.d.ts +20 -0
  103. package/dist/composables/_flowPanel.d.ts +2 -0
  104. package/dist/composables/_flowSlot.d.ts +5 -0
  105. package/dist/composables/_ganttTime.d.ts +41 -0
  106. package/dist/composables/_useTimeAxis.d.ts +90 -0
  107. package/dist/composables/drawGeometry.d.ts +119 -0
  108. package/dist/composables/flowFormats.d.ts +79 -0
  109. package/dist/composables/flowLayout.d.ts +45 -0
  110. package/dist/composables/flowPaths.d.ts +53 -0
  111. package/dist/composables/ganttFormats.d.ts +52 -0
  112. package/dist/composables/ganttSchedule.d.ts +99 -0
  113. package/dist/composables/useDrawing.d.ts +44 -0
  114. package/dist/composables/useFlow.d.ts +266 -0
  115. package/dist/composables/useGantt.d.ts +87 -0
  116. package/dist/composables/useLocale.d.ts +163 -0
  117. package/dist/composables/useMediaPlayer.d.ts +101 -0
  118. package/dist/composables/usePdf.d.ts +119 -0
  119. package/dist/composables/useResourceTimeline.d.ts +70 -0
  120. package/dist/draw.d.ts +7 -0
  121. package/dist/draw.js +1700 -0
  122. package/dist/draw.js.map +1 -0
  123. package/dist/flow.d.ts +14 -0
  124. package/dist/flow.js +3542 -0
  125. package/dist/flow.js.map +1 -0
  126. package/dist/flowPaths-CUc6X373.js +161 -0
  127. package/dist/flowPaths-CUc6X373.js.map +1 -0
  128. package/dist/gantt.d.ts +12 -0
  129. package/dist/gantt.js +3575 -0
  130. package/dist/gantt.js.map +1 -0
  131. package/dist/index.d.ts +4 -0
  132. package/dist/locales/index.js +1148 -7
  133. package/dist/locales/index.js.map +1 -1
  134. package/dist/m3ui-vue.css +1 -1
  135. package/dist/m3ui.js +7286 -7654
  136. package/dist/m3ui.js.map +1 -1
  137. package/dist/map.js +113 -108
  138. package/dist/map.js.map +1 -1
  139. package/dist/media.d.ts +5 -0
  140. package/dist/media.js +1311 -0
  141. package/dist/media.js.map +1 -0
  142. package/dist/pdf.d.ts +4 -0
  143. package/dist/pdf.js +1871 -0
  144. package/dist/pdf.js.map +1 -0
  145. package/dist/rich-text-editor.js +28 -26
  146. package/dist/rich-text-editor.js.map +1 -1
  147. package/dist/styles.css +1 -1
  148. package/dist/{useLocale-JYxDDeXC.js → useLocale-BpGxplLV.js} +165 -2
  149. package/dist/useLocale-BpGxplLV.js.map +1 -0
  150. package/dist/{useThemeTokens-y0HZpyhL.js → useThemeTokens-DQQcaWbE.js} +40 -54
  151. package/dist/useThemeTokens-DQQcaWbE.js.map +1 -0
  152. package/package.json +29 -5
  153. package/src/__tests__/MAudioPlayer.test.ts +75 -0
  154. package/src/__tests__/MDrawCanvas.test.ts +110 -0
  155. package/src/__tests__/MFloorPlan.test.ts +97 -0
  156. package/src/__tests__/MFlow.test.ts +575 -0
  157. package/src/__tests__/MGantt.test.ts +130 -0
  158. package/src/__tests__/MImageCropper.test.ts +89 -0
  159. package/src/__tests__/MPdfViewer.test.ts +235 -0
  160. package/src/__tests__/MResourceTimeline.test.ts +102 -0
  161. package/src/__tests__/MVideoPlayer.test.ts +201 -0
  162. package/src/__tests__/drawGeometry.test.ts +58 -0
  163. package/src/__tests__/fieldExpose.test.ts +30 -0
  164. package/src/__tests__/flowFormats.test.ts +185 -0
  165. package/src/__tests__/flowLayout.test.ts +113 -0
  166. package/src/__tests__/ganttFormats.test.ts +76 -0
  167. package/src/__tests__/ganttSchedule.test.ts +136 -0
  168. package/src/__tests__/pdfMock.ts +83 -0
  169. package/src/__tests__/useMediaPlayer.test.ts +182 -0
  170. package/src/__tests__/usePdf.test.ts +102 -0
  171. package/src/components/MAudioPlayer.vue +319 -0
  172. package/src/components/MDrawCanvas.vue +813 -0
  173. package/src/components/MDrawLayers.vue +114 -0
  174. package/src/components/MDrawToolbar.vue +171 -0
  175. package/src/components/MFloorPlan.vue +581 -0
  176. package/src/components/MFlow.vue +2049 -0
  177. package/src/components/MFlowControls.vue +110 -0
  178. package/src/components/MFlowHandle.vue +60 -0
  179. package/src/components/MFlowMinimap.vue +134 -0
  180. package/src/components/MFlowNode.vue +98 -0
  181. package/src/components/MGantt.vue +1609 -0
  182. package/src/components/MGanttControls.vue +77 -0
  183. package/src/components/MIconButton.vue +3 -1
  184. package/src/components/MImageCropper.vue +507 -0
  185. package/src/components/MMaskField.vue +13 -0
  186. package/src/components/MNumberField.vue +13 -0
  187. package/src/components/MPdfViewer.vue +1269 -0
  188. package/src/components/MResourceTimeline.vue +1020 -0
  189. package/src/components/MTagInput.vue +13 -0
  190. package/src/components/MTextField.vue +16 -0
  191. package/src/components/MVideoPlayer.vue +839 -0
  192. package/src/components/_MFlowEdge.vue +100 -0
  193. package/src/components/_MFlowEdgeLabel.vue +56 -0
  194. package/src/components/_MFlowNodeShell.vue +111 -0
  195. package/src/components/_MPdfPage.vue +456 -0
  196. package/src/components/_MTimeBackground.vue +16 -0
  197. package/src/components/_MTimeHeader.vue +31 -0
  198. package/src/composables/_flowPanel.ts +13 -0
  199. package/src/composables/_flowSlot.ts +6 -0
  200. package/src/composables/_ganttTime.ts +200 -0
  201. package/src/composables/_useTimeAxis.ts +224 -0
  202. package/src/composables/drawGeometry.ts +405 -0
  203. package/src/composables/flowFormats.ts +916 -0
  204. package/src/composables/flowLayout.ts +297 -0
  205. package/src/composables/flowPaths.ts +239 -0
  206. package/src/composables/ganttFormats.ts +366 -0
  207. package/src/composables/ganttSchedule.ts +403 -0
  208. package/src/composables/useDrawing.ts +53 -0
  209. package/src/composables/useFlow.ts +250 -0
  210. package/src/composables/useGantt.ts +92 -0
  211. package/src/composables/useLocale.ts +328 -0
  212. package/src/composables/useMediaPlayer.ts +406 -0
  213. package/src/composables/usePdf.ts +456 -0
  214. package/src/composables/useResourceTimeline.ts +76 -0
  215. package/src/draw.ts +25 -0
  216. package/src/flow.ts +26 -0
  217. package/src/gantt.ts +12 -0
  218. package/src/index.ts +4 -0
  219. package/src/locales/de.ts +163 -0
  220. package/src/locales/es.ts +163 -0
  221. package/src/locales/fr.ts +163 -0
  222. package/src/locales/ja.ts +163 -0
  223. package/src/locales/ko.ts +163 -0
  224. package/src/locales/pt.ts +163 -0
  225. package/src/locales/zh.ts +163 -0
  226. package/src/media.ts +5 -0
  227. package/src/pdf.ts +15 -0
  228. package/dist/MMenuItem-D4Gx_l3F.js +0 -929
  229. package/dist/MMenuItem-D4Gx_l3F.js.map +0 -1
  230. package/dist/MSlider-Dx_S3vJ9.js +0 -1506
  231. package/dist/MSlider-Dx_S3vJ9.js.map +0 -1
  232. package/dist/MTextField-Bz8JIsnl.js +0 -633
  233. package/dist/MTextField-Bz8JIsnl.js.map +0 -1
  234. package/dist/useLocale-JYxDDeXC.js.map +0 -1
  235. package/dist/useThemeTokens-y0HZpyhL.js.map +0 -1
@@ -0,0 +1,2049 @@
1
+ <script lang="ts">
2
+ import type { FlowEdge, FlowNode, FlowSelection } from '../composables/useFlow'
3
+
4
+ // Copied nodes and edges, shared by every MFlow on the page (copy in one, paste in another)
5
+ let clipboard: { nodes: FlowNode[]; edges: FlowEdge[] } | null = null
6
+ let pasteCount = 0
7
+
8
+ const randomId = (prefix: string) => `${prefix}-${Math.random().toString(36).slice(2, 9)}`
9
+ const emptySelection = (): FlowSelection => ({ nodes: [], edges: [] })
10
+ </script>
11
+
12
+ <script setup lang="ts">
13
+ /**
14
+ * A node editor (not an M3 spec component): nodes you drag around on a canvas that pans and zooms, joined by edges
15
+ * drawn from handle to handle. Built from M3 pieces (nodes are cards, the controls a floating toolbar) with the
16
+ * API shape of Vue Flow / React Flow. Nodes and edges are `v-model`s of plain objects; the view, the selection
17
+ * and the lock are too. Pan by dragging the background (or the wheel, or two fingers), zoom with Ctrl + wheel, a
18
+ * trackpad or touch pinch, or a double click. Shift + drag (or `selectionOnDrag`; on touch, a long press on the
19
+ * background) draws a selection box; Delete
20
+ * removes what's selected, Ctrl+Z/Ctrl+Shift+Z undo and redo, Ctrl+C/X/V/A copy, cut, paste and select all, and
21
+ * the arrows move the selected nodes. A drag from a handle to another connects them; dropped on nothing it fires
22
+ * `connect-end` with the spot, to offer a new node there. To disconnect: the × on a selected edge, Delete, dragging
23
+ * an edge's end (or a connected input) away and dropping it on nothing. Alignment guides show while dragging one node.
24
+ *
25
+ * Nodes are drawn by type: `default`/`input`/`output` (an MFlowNode), `circle` (a vertex: `data.label`, `color`,
26
+ * `badge`, `ring`, `size`; its edges run center to center in any direction), `group` (a box its children move with), or
27
+ * a `#node-<type>` slot of your own with MFlowHandles in it; edges are `bezier`, `smoothstep`, `step`, `straight`
28
+ * or a `#edge-<type>` slot (with `getBezierPath` and friends); `color`, `width`, `dashed`, `animated` and
29
+ * `labelTone` restyle one without a slot, with a transition. `layout` lays them out (`'tree'`, `'layered'` or a
30
+ * function, e.g. one calling dagre) whenever the graph's shape changes. Put `MFlowControls`, `MFlowMinimap` or
31
+ * anything of yours in the default slot: it's drawn over the canvas, the canvas's gestures and wheel leave it alone,
32
+ * and `useFlow()` works inside it. Inside a node, controls (buttons, inputs, links) never start a drag; mark anything
33
+ * else that shouldn't with `data-flow-nodrag`, and an area that scrolls on its own with `data-flow-nowheel`.
34
+ * `startDrag(id, event)` hands a pointer that's already down to a node, to drag something in from outside (a palette).
35
+ *
36
+ * Positions spring to their new place when they change from outside (a layout, an undo); the view springs on
37
+ * `fitView()`/zoom buttons. Nodes are rendered by small components of their own so moving one only redraws it
38
+ * and its edges.
39
+ *
40
+ * @slot default Drawn over the canvas: MFlowControls, MFlowMinimap, panels of yours. Props: `{ flow }`
41
+ * @slot node-<type> A node of that type. Props: `{ node, data, selected, dragging }`
42
+ * @slot edge-<type> An edge of that type, SVG inside a `<g>`. Props: `{ edge, path, labelX, labelY, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, targetAngle, targetInset, selected, highlighted }` (`highlighted`: a dragged node would splice into it)
43
+ * @slot edge-label An edge's label, instead of the default chip. Props: `{ edge, selected }`
44
+ * @slot empty Shown while there are no nodes
45
+ * @event connect A connection was made (it's also added to `edges` with `autoConnect`)
46
+ * @event connect-start A connection drag started from a handle
47
+ * @event connect-end A connection drag ended: `{ connection }` when it connected, else the flow `position` it was dropped at and where it came from
48
+ * @event reconnect An edge's end was moved to another handle: `{ edge, connection }`
49
+ * @event insert A lone node was dropped onto an edge and spliced in: `{ node, edge, connections }` (with `autoConnect`
50
+ * the edge is replaced by the two connections, keeping its type and look)
51
+ * @event node-click / node-dblclick / node-contextmenu `(node, event)`
52
+ * @event node-drag-start / node-drag `(nodes, event)`
53
+ * @event node-drag-stop `{ nodes, intersecting, event }`: `intersecting` are the nodes under the dragged one
54
+ * @event edge-click / edge-dblclick / edge-contextmenu `(edge, event)`
55
+ * @event pane-click / pane-dblclick / pane-contextmenu `(position, event)` with the flow position (turn
56
+ * `zoomOnDoubleClick` off to use the double click yourself, e.g. to add a node there)
57
+ * @event delete Nodes and edges were deleted: `{ nodes, edges }`
58
+ * @event init The canvas measured its nodes (and laid out / fitted them): the flow context
59
+ */
60
+ import { computed, nextTick, onBeforeUnmount, onMounted, provide, reactive, ref, shallowReactive, shallowRef, toRaw, useSlots, watch } from 'vue'
61
+ import {
62
+ FLOW_KEY,
63
+ type FlowConnection,
64
+ type FlowContext,
65
+ type FlowEdgeGeometry as EdgeGeometry,
66
+ type FlowFitOptions,
67
+ type FlowHandleBounds,
68
+ type FlowInternals,
69
+ type FlowPosition,
70
+ type FlowViewport,
71
+ type FlowXY,
72
+ } from '../composables/useFlow'
73
+ import { layoutLayered, layoutTree, type FlowLayout, type FlowLayoutDirection, type FlowLayoutOptions } from '../composables/flowLayout'
74
+ import { distanceToPoints, edgePathPoints, getBezierPath, getSmoothStepPath, getStepPath, getStraightPath, type FlowEdgePath } from '../composables/flowPaths'
75
+ import { DEFAULT_SPATIAL } from '../composables/_useSpring'
76
+ import { prefersReducedMotion } from '../composables/_springAnimation'
77
+ import { useLocale } from '../composables/useLocale'
78
+ import NodeShell from './_MFlowNodeShell.vue'
79
+ import EdgeView from './_MFlowEdge.vue'
80
+ import EdgeLabel from './_MFlowEdgeLabel.vue'
81
+
82
+ defineOptions({ inheritAttrs: false })
83
+
84
+ const props = withDefaults(defineProps<{
85
+ nodes?: FlowNode[]
86
+ edges?: FlowEdge[]
87
+ /** The view (v-model) */
88
+ viewport?: FlowViewport
89
+ /** Selected node and edge ids (v-model) */
90
+ selection?: FlowSelection
91
+ /** Switches off moving, connecting, selecting and deleting; the view still pans and zooms (v-model) */
92
+ locked?: boolean
93
+ /** Which way edges run by default: where the default node's handles go and the layout's direction */
94
+ direction?: 'horizontal' | 'vertical'
95
+ background?: 'dots' | 'grid' | 'none'
96
+ /** The background's spacing, and the grid nodes snap to, px */
97
+ gridSize?: number
98
+ snapToGrid?: boolean
99
+ minZoom?: number
100
+ maxZoom?: number
101
+ /** Fits the nodes in view once they're measured, and again after each automatic `layout` */
102
+ fitView?: boolean
103
+ /** What the plain wheel does (Ctrl + wheel always zooms) */
104
+ wheel?: 'pan' | 'zoom'
105
+ /** A double click on the background zooms in */
106
+ zoomOnDoubleClick?: boolean
107
+ /** Dragging the background pans; off, it draws a selection box */
108
+ panOnDrag?: boolean
109
+ /** Dragging the background draws a selection box (Shift + drag always does) */
110
+ selectionOnDrag?: boolean
111
+ nodesDraggable?: boolean
112
+ nodesConnectable?: boolean
113
+ elementsSelectable?: boolean
114
+ edgesReconnectable?: boolean
115
+ /** Merged into edges made by connecting (`type`, `animated`, `markerEnd`…) */
116
+ defaultEdgeOptions?: Partial<FlowEdge>
117
+ /** Adds an edge to `edges` when a connection is made; off, only `connect` fires */
118
+ autoConnect?: boolean
119
+ /** Whether a connection may be made (no duplicates or same-node loops are offered either way) */
120
+ isValidConnection?: (c: FlowConnection) => boolean
121
+ /** How close to a handle a connection snaps to it, px */
122
+ connectionRadius?: number
123
+ /**
124
+ * Asked before anything is deleted (the keyboard, an edge's ×, an edge dropped on nothing, `remove()`), with what
125
+ * would go: return false to keep it, or a Promise (a confirm dialog) that resolves to whether to delete
126
+ */
127
+ beforeDelete?: (items: { nodes: FlowNode[]; edges: FlowEdge[] }) => boolean | Promise<boolean>
128
+ /** Keys that delete the selection; `null` turns deleting off */
129
+ deleteKeys?: string[] | null
130
+ /** Undo and redo (Ctrl+Z, Ctrl+Shift+Z / Ctrl+Y), over every change to nodes and edges */
131
+ history?: boolean
132
+ historySize?: number
133
+ /** Alignment guides while dragging one node */
134
+ guides?: boolean
135
+ /** Lays the nodes out when the graph's shape changes (nodes or edges added, removed, hidden) */
136
+ layout?: 'tree' | 'layered' | FlowLayout | null
137
+ layoutOptions?: FlowLayoutOptions
138
+ /**
139
+ * A node with no connections dropped onto an edge splices into it: A → C becomes A → B → C (the edge lights up
140
+ * while it's over one). Only when both new connections are valid. Without room between A and C, the node moves
141
+ * to sit after A and C moves on (with everything after it) along the flow's `direction`
142
+ */
143
+ insertOnEdge?: boolean
144
+ /** Nodes dropped onto a `group` join it (and leave it when dropped outside) */
145
+ dropIntoGroups?: boolean
146
+ /** Positions spring to their new place when they change from outside */
147
+ animate?: boolean
148
+ /** Makes ids for pasted nodes and new edges */
149
+ getId?: (kind: 'node' | 'edge') => string
150
+ /**
151
+ * A drag that starts on an edge draws a new edge from the same source, a branch, as in a circuit editor (the
152
+ * preview leaves from where you grabbed it). A click still selects the edge; with a finger, only a selected edge
153
+ * branches, so a swipe across one still pans
154
+ */
155
+ edgeBranching?: boolean
156
+ /** The canvas's accessible name */
157
+ label?: string
158
+ }>(), {
159
+ nodes: () => [],
160
+ edges: () => [],
161
+ viewport: undefined,
162
+ selection: undefined,
163
+ locked: false,
164
+ direction: 'horizontal',
165
+ background: 'dots',
166
+ gridSize: 20,
167
+ snapToGrid: false,
168
+ minZoom: 0.2,
169
+ maxZoom: 4,
170
+ fitView: false,
171
+ wheel: 'pan',
172
+ zoomOnDoubleClick: true,
173
+ panOnDrag: true,
174
+ selectionOnDrag: false,
175
+ nodesDraggable: true,
176
+ nodesConnectable: true,
177
+ elementsSelectable: true,
178
+ edgesReconnectable: true,
179
+ autoConnect: true,
180
+ connectionRadius: 24,
181
+ deleteKeys: () => ['Delete', 'Backspace'],
182
+ history: true,
183
+ historySize: 100,
184
+ guides: true,
185
+ layout: null,
186
+ dropIntoGroups: false,
187
+ insertOnEdge: true,
188
+ edgeBranching: false,
189
+ animate: true,
190
+ })
191
+
192
+ const emit = defineEmits<{
193
+ 'update:nodes': [FlowNode[]]
194
+ 'update:edges': [FlowEdge[]]
195
+ 'update:viewport': [FlowViewport]
196
+ 'update:selection': [FlowSelection]
197
+ 'update:locked': [boolean]
198
+ connect: [FlowConnection]
199
+ 'connect-start': [{ nodeId: string; handleId: string | null; type: 'source' | 'target' }]
200
+ 'connect-end': [{ connection: FlowConnection | null; position: FlowXY; from: { nodeId: string; handleId: string | null; type: 'source' | 'target' } }]
201
+ reconnect: [{ edge: FlowEdge; connection: FlowConnection }]
202
+ insert: [{ node: FlowNode; edge: FlowEdge; connections: [FlowConnection, FlowConnection] }]
203
+ 'node-click': [FlowNode, MouseEvent]
204
+ 'node-dblclick': [FlowNode, MouseEvent]
205
+ 'node-contextmenu': [FlowNode, MouseEvent]
206
+ 'node-drag-start': [FlowNode[], PointerEvent]
207
+ 'node-drag': [FlowNode[], PointerEvent]
208
+ 'node-drag-stop': [{ nodes: FlowNode[]; intersecting: FlowNode[]; event: PointerEvent }]
209
+ 'edge-click': [FlowEdge, MouseEvent]
210
+ 'edge-dblclick': [FlowEdge, MouseEvent]
211
+ 'edge-contextmenu': [FlowEdge, MouseEvent]
212
+ 'pane-click': [FlowXY, MouseEvent]
213
+ 'pane-contextmenu': [FlowXY, MouseEvent]
214
+ 'pane-dblclick': [FlowXY, MouseEvent]
215
+ delete: [{ nodes: FlowNode[]; edges: FlowEdge[] }]
216
+ init: [FlowContext]
217
+ }>()
218
+
219
+ const slots = useSlots()
220
+ const locale = useLocale()
221
+ const root = ref<HTMLElement>()
222
+ const layer = ref<HTMLElement>()
223
+ // What's in the default slot (controls, a minimap, panels of yours) sits over the canvas: the canvas's gestures and
224
+ // wheel leave it alone, so it needs no marking
225
+ const onOverlay = (t: EventTarget | null) => !!t && t !== root.value && !layer.value?.contains(t as Node)
226
+ const size = ref({ width: 0, height: 0 })
227
+ const ready = ref(false)
228
+ const announcement = ref('')
229
+ const announce = (m: string) => {
230
+ announcement.value = ''
231
+ nextTick(() => (announcement.value = m))
232
+ }
233
+ const makeId = (kind: 'node' | 'edge') => props.getId?.(kind) ?? randomId(kind === 'node' ? 'n' : 'e')
234
+
235
+ // ── Nodes, edges, selection, lock: local copies of the v-models (they work unbound too) ──────────────────
236
+ const nodesLocal = shallowRef<FlowNode[]>(props.nodes)
237
+ const edgesLocal = shallowRef<FlowEdge[]>(props.edges)
238
+ const selLocal = shallowRef<FlowSelection>(props.selection ?? emptySelection())
239
+ const lockedLocal = ref(props.locked)
240
+ watch(() => props.selection, (s) => { if (s && !same(s, selLocal.value)) selLocal.value = s })
241
+ watch(() => props.locked, (l) => { lockedLocal.value = l })
242
+ const locked = computed({
243
+ get: () => lockedLocal.value,
244
+ set: (v: boolean) => {
245
+ lockedLocal.value = v
246
+ emit('update:locked', v)
247
+ },
248
+ })
249
+
250
+ const nodeById = computed(() => new Map(nodesLocal.value.map((n) => [n.id, n])))
251
+ const edgeById = computed(() => new Map(edgesLocal.value.map((e) => [e.id, e])))
252
+ const getNode = (id: string) => nodeById.value.get(id)
253
+ const parentOf = (id: string) => {
254
+ const p = nodeById.value.get(id)?.parentId
255
+ return p && nodeById.value.has(p) ? p : undefined
256
+ }
257
+ function ancestors(id: string): string[] {
258
+ const out: string[] = []
259
+ for (let p = parentOf(id); p && out.length < 50; p = parentOf(p)) out.push(p)
260
+ return out
261
+ }
262
+ const depthOf = (id: string) => ancestors(id).length
263
+ function isHidden(id: string) {
264
+ const n = nodeById.value.get(id)
265
+ return !n || !!n.hidden || ancestors(id).some((a) => nodeById.value.get(a)?.hidden)
266
+ }
267
+ const childrenOf = computed(() => {
268
+ const m = new Map<string, string[]>()
269
+ for (const n of nodesLocal.value) if (n.parentId && nodeById.value.has(n.parentId)) (m.get(n.parentId) ?? m.set(n.parentId, []).get(n.parentId)!).push(n.id)
270
+ return m
271
+ })
272
+ function descendants(id: string): string[] {
273
+ const out: string[] = []
274
+ const walk = (i: string) => (childrenOf.value.get(i) ?? []).forEach((c) => { out.push(c); walk(c) })
275
+ walk(id)
276
+ return out
277
+ }
278
+
279
+ const selectedNodes = computed(() => new Set(selLocal.value.nodes))
280
+ const selectedEdges = computed(() => new Set(selLocal.value.edges))
281
+ // Edges branch when dragged (edgeBranching)
282
+ const branching = computed(() => props.edgeBranching && nodesConnectable.value && !locked.value)
283
+ function setSelection(s: Partial<FlowSelection>) {
284
+ const next = { nodes: s.nodes ?? selLocal.value.nodes, edges: s.edges ?? selLocal.value.edges }
285
+ if (sameIds(next.nodes, selLocal.value.nodes) && sameIds(next.edges, selLocal.value.edges)) return
286
+ selLocal.value = next
287
+ emit('update:selection', next)
288
+ }
289
+ const sameIds = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i])
290
+ const canSelect = computed(() => props.elementsSelectable && !locked.value)
291
+ const canDrag = computed(() => props.nodesDraggable && !locked.value)
292
+ const nodesConnectable = computed(() => props.nodesConnectable && !locked.value)
293
+
294
+ // ── History: every change to nodes/edges, ours or the parent's, is a step ────────────────────────────────
295
+ type Snapshot = { nodes: FlowNode[]; edges: FlowEdge[] }
296
+ const past = shallowRef<Snapshot[]>([])
297
+ const future = shallowRef<Snapshot[]>([])
298
+ let lastCoalesce: { key: string; at: number } | null = null
299
+ const snapshot = (): Snapshot => ({ nodes: nodesLocal.value, edges: edgesLocal.value })
300
+ function pushHistory(s: Snapshot, coalesce?: string) {
301
+ if (!props.history) return
302
+ const now = performance.now()
303
+ // Repeated steps of one gesture (arrow-key nudges) make one undo step
304
+ if (coalesce && lastCoalesce?.key === coalesce && now - lastCoalesce.at < 800) {
305
+ lastCoalesce.at = now
306
+ future.value = []
307
+ return
308
+ }
309
+ lastCoalesce = coalesce ? { key: coalesce, at: now } : null
310
+ past.value = [...past.value, s].slice(-props.historySize)
311
+ future.value = []
312
+ }
313
+ let pendingExternal: Snapshot | null = null
314
+ // What the parent hands back in the same tick as an emit of ours is that change coming back (maybe copied or
315
+ // normalized), not a new step
316
+ let echo = false
317
+ function externalChange() {
318
+ if (echo || pendingExternal) return
319
+ pendingExternal = snapshot()
320
+ queueMicrotask(() => {
321
+ if (pendingExternal) pushHistory(pendingExternal)
322
+ pendingExternal = null
323
+ })
324
+ }
325
+ // What comes back through v-model is often our own array behind a reactive proxy (a parent's `ref([])`)
326
+ const same = (a: unknown, b: unknown) => toRaw(a) === toRaw(b)
327
+ watch(() => props.nodes, (n) => {
328
+ if (same(n, nodesLocal.value)) return
329
+ externalChange()
330
+ nodesLocal.value = n
331
+ })
332
+ watch(() => props.edges, (e) => {
333
+ if (same(e, edgesLocal.value)) return
334
+ externalChange()
335
+ edgesLocal.value = e
336
+ })
337
+
338
+ function commit(next: Partial<Snapshot>, opts: { history?: boolean; coalesce?: string } = {}) {
339
+ if (opts.history !== false) pushHistory(snapshot(), opts.coalesce)
340
+ if (!echo) {
341
+ echo = true
342
+ nextTick(() => (echo = false))
343
+ }
344
+ if (next.nodes && !same(next.nodes, nodesLocal.value)) {
345
+ nodesLocal.value = next.nodes
346
+ emit('update:nodes', next.nodes)
347
+ }
348
+ if (next.edges && !same(next.edges, edgesLocal.value)) {
349
+ edgesLocal.value = next.edges
350
+ emit('update:edges', next.edges)
351
+ }
352
+ }
353
+ function applySnapshot(s: Snapshot) {
354
+ commit(s, { history: false })
355
+ const ids = new Set(s.nodes.map((n) => n.id))
356
+ const eids = new Set(s.edges.map((e) => e.id))
357
+ setSelection({ nodes: selLocal.value.nodes.filter((i) => ids.has(i)), edges: selLocal.value.edges.filter((i) => eids.has(i)) })
358
+ }
359
+ function undo() {
360
+ const s = past.value[past.value.length - 1]
361
+ if (!s) return
362
+ future.value = [...future.value, snapshot()]
363
+ past.value = past.value.slice(0, -1)
364
+ lastCoalesce = null
365
+ applySnapshot(s)
366
+ }
367
+ function redo() {
368
+ const s = future.value[future.value.length - 1]
369
+ if (!s) return
370
+ past.value = [...past.value, snapshot()]
371
+ future.value = future.value.slice(0, -1)
372
+ lastCoalesce = null
373
+ applySnapshot(s)
374
+ }
375
+ const canUndo = computed(() => past.value.length > 0)
376
+ const canRedo = computed(() => future.value.length > 0)
377
+
378
+ // ── Where nodes are drawn: their position, sprung when it changes from outside ──────────────────────────
379
+ // `disp` is reactive (edges and slots read it); the springs are plain and step in one rAF loop that writes
380
+ // each moving node's `disp` once per frame (the library's spring convention, see CLAUDE.md)
381
+ type Spring2 = { x: number; y: number; vx: number; vy: number; tx: number; ty: number }
382
+ const disp = shallowReactive(new Map<string, { x: number; y: number }>())
383
+ const springs = new Map<string, Spring2>()
384
+ const dragging = shallowRef(new Set<string>())
385
+ let instantNext = false
386
+
387
+ // Nodes hidden last time: one that shows again appears at its position instead of sliding in from where it was hidden
388
+ let wasHidden = new Set<string>()
389
+ function syncPositions() {
390
+ const seen = new Set<string>()
391
+ const hiddenNow = new Set<string>()
392
+ const animate = props.animate && ready.value && !instantNext && !prefersReducedMotion()
393
+ for (const n of nodesLocal.value) {
394
+ seen.add(n.id)
395
+ if (isHidden(n.id)) hiddenNow.add(n.id)
396
+ const reappears = wasHidden.has(n.id) && !hiddenNow.has(n.id)
397
+ const d = disp.get(n.id)
398
+ const { x, y } = n.position
399
+ if (!d) {
400
+ disp.set(n.id, reactive({ x, y }))
401
+ springs.set(n.id, { x, y, vx: 0, vy: 0, tx: x, ty: y })
402
+ continue
403
+ }
404
+ const s = springs.get(n.id)!
405
+ if (s.tx === x && s.ty === y && !reappears) continue
406
+ s.tx = x
407
+ s.ty = y
408
+ if (!animate || reappears || dragging.value.has(n.id)) {
409
+ s.x = x
410
+ s.y = y
411
+ s.vx = s.vy = 0
412
+ d.x = x
413
+ d.y = y
414
+ } else kick()
415
+ }
416
+ for (const id of [...disp.keys()]) if (!seen.has(id)) { disp.delete(id); springs.delete(id) }
417
+ wasHidden = hiddenNow
418
+ instantNext = false
419
+ }
420
+ watch(nodesLocal, syncPositions, { immediate: true })
421
+
422
+ const STIFF = DEFAULT_SPATIAL.stiffness
423
+ const DAMP = 2 * DEFAULT_SPATIAL.dampingRatio * Math.sqrt(STIFF)
424
+ const SUBSTEP = 0.004
425
+ let raf = 0
426
+ let last = 0
427
+ function kick() {
428
+ if (raf || typeof requestAnimationFrame === 'undefined') return
429
+ last = performance.now()
430
+ raf = requestAnimationFrame(frame)
431
+ }
432
+ function frame(now: number) {
433
+ raf = 0
434
+ const dt = Math.min((now - last) / 1000, 1 / 20)
435
+ last = now
436
+ let moving = false
437
+ for (const [id, s] of springs) {
438
+ if (s.x === s.tx && s.y === s.ty && !s.vx && !s.vy) continue
439
+ for (let t = 0; t < dt; t += SUBSTEP) {
440
+ const h = Math.min(SUBSTEP, dt - t)
441
+ s.vx += (-STIFF * (s.x - s.tx) - DAMP * s.vx) * h
442
+ s.vy += (-STIFF * (s.y - s.ty) - DAMP * s.vy) * h
443
+ s.x += s.vx * h
444
+ s.y += s.vy * h
445
+ }
446
+ if (Math.abs(s.x - s.tx) < 0.1 && Math.abs(s.y - s.ty) < 0.1 && Math.abs(s.vx) < 2 && Math.abs(s.vy) < 2) {
447
+ s.x = s.tx
448
+ s.y = s.ty
449
+ s.vx = s.vy = 0
450
+ } else moving = true
451
+ const d = disp.get(id)
452
+ if (d) { d.x = s.x; d.y = s.y }
453
+ }
454
+ if (stepViewport(dt)) moving = true
455
+ if (autoPan(dt)) moving = true
456
+ if (moving) raf = requestAnimationFrame(frame)
457
+ }
458
+
459
+ function getAbsolutePosition(id: string): FlowXY {
460
+ let x = 0
461
+ let y = 0
462
+ let cur: string | undefined = id
463
+ for (let i = 0; cur && i < 50; i++) {
464
+ const d = disp.get(cur)
465
+ const n = nodeById.value.get(cur)
466
+ x += d?.x ?? n?.position.x ?? 0
467
+ y += d?.y ?? n?.position.y ?? 0
468
+ cur = parentOf(cur)
469
+ }
470
+ return { x, y }
471
+ }
472
+
473
+ // ── Sizes and handles, measured by the node shells ───────────────────────────────────────────────────────
474
+ const dims = shallowReactive(new Map<string, { width: number; height: number }>())
475
+ const handles = shallowReactive(new Map<string, FlowHandleBounds[]>())
476
+ const nodeEls = new Map<string, HTMLElement>()
477
+ type HandleReg = { el: HTMLElement; info: () => Omit<FlowHandleBounds, 'x' | 'y'> }
478
+ const handleRegs = new Map<string, Set<HandleReg>>()
479
+
480
+ const GROUP_PAD = 24
481
+ const GROUP_HEAD = 36
482
+ // Groups around nodes being dragged keep their size until the drop: growing after the child would never let it
483
+ // leave (the pointer would always be inside)
484
+ const frozenGroups = shallowReactive(new Map<string, { width: number; height: number }>())
485
+ function getSize(id: string): { width: number; height: number } {
486
+ const n = nodeById.value.get(id)
487
+ if (!n) return { width: 0, height: 0 }
488
+ if (n.width && n.height) return { width: n.width, height: n.height }
489
+ if (n.type === 'group' && !n.width) {
490
+ const frozen = frozenGroups.get(id)
491
+ if (frozen) return frozen
492
+ // A group without a size wraps its children
493
+ let w = 200
494
+ let h = 120
495
+ for (const c of childrenOf.value.get(id) ?? []) {
496
+ if (isHidden(c)) continue
497
+ const d = disp.get(c)
498
+ const s = getSize(c)
499
+ w = Math.max(w, (d?.x ?? 0) + s.width + GROUP_PAD)
500
+ h = Math.max(h, (d?.y ?? 0) + s.height + GROUP_PAD)
501
+ }
502
+ return { width: n.width ?? w, height: n.height ?? Math.max(h, GROUP_HEAD + GROUP_PAD) }
503
+ }
504
+ const m = dims.get(id)
505
+ return { width: n.width ?? m?.width ?? 0, height: n.height ?? m?.height ?? 0 }
506
+ }
507
+
508
+ function measureNode(id: string) {
509
+ const el = nodeEls.get(id)
510
+ if (!el) return
511
+ const w = el.offsetWidth
512
+ const h = el.offsetHeight
513
+ const prev = dims.get(id)
514
+ if (!prev || prev.width !== w || prev.height !== h) dims.set(id, { width: w, height: h })
515
+ const regs = handleRegs.get(id)
516
+ if (!regs?.size) {
517
+ if (handles.has(id)) handles.delete(id)
518
+ return
519
+ }
520
+ // Handle centers relative to the node's corner, back in flow units (the layer is scaled by the zoom)
521
+ const r = el.getBoundingClientRect()
522
+ const z = vp.value.zoom || 1
523
+ const list: FlowHandleBounds[] = []
524
+ for (const reg of regs) {
525
+ const hr = reg.el.getBoundingClientRect()
526
+ list.push({ ...reg.info(), x: (hr.left + hr.width / 2 - r.left) / z, y: (hr.top + hr.height / 2 - r.top) / z })
527
+ }
528
+ handles.set(id, list)
529
+ }
530
+ let measureQueued = new Set<string>()
531
+ function queueMeasure(id: string) {
532
+ measureQueued.add(id)
533
+ if (measureQueued.size > 1) return
534
+ nextTick(() => {
535
+ const ids = measureQueued
536
+ measureQueued = new Set()
537
+ ids.forEach(measureNode)
538
+ })
539
+ }
540
+ function registerHandle(nodeId: string, el: HTMLElement, info: HandleReg['info']) {
541
+ const reg = { el, info }
542
+ ;(handleRegs.get(nodeId) ?? handleRegs.set(nodeId, new Set()).get(nodeId)!).add(reg)
543
+ queueMeasure(nodeId)
544
+ return () => {
545
+ handleRegs.get(nodeId)?.delete(reg)
546
+ queueMeasure(nodeId)
547
+ }
548
+ }
549
+ function registerNodeEl(id: string, el: HTMLElement | null) {
550
+ if (el) {
551
+ nodeEls.set(id, el)
552
+ measureNode(id)
553
+ ro?.observe(el)
554
+ } else {
555
+ const old = nodeEls.get(id)
556
+ if (old) ro?.unobserve(old)
557
+ nodeEls.delete(id)
558
+ dims.delete(id)
559
+ handles.delete(id)
560
+ }
561
+ }
562
+
563
+ // Where an edge's ends are: its handles, else the middle of the node's side
564
+ const sidePositions = (n: FlowNode) => {
565
+ const v = props.direction === 'vertical'
566
+ return {
567
+ source: n.sourcePosition ?? (v ? 'bottom' : 'right') as FlowPosition,
568
+ target: n.targetPosition ?? (v ? 'top' : 'left') as FlowPosition,
569
+ }
570
+ }
571
+ function sidePoint(id: string, pos: FlowPosition): FlowXY {
572
+ const a = getAbsolutePosition(id)
573
+ const s = getSize(id)
574
+ switch (pos) {
575
+ case 'top': return { x: a.x + s.width / 2, y: a.y }
576
+ case 'bottom': return { x: a.x + s.width / 2, y: a.y + s.height }
577
+ case 'left': return { x: a.x, y: a.y + s.height / 2 }
578
+ default: return { x: a.x + s.width, y: a.y + s.height / 2 }
579
+ }
580
+ }
581
+ function handlePoint(nodeId: string, type: 'source' | 'target', handleId?: string | null): { x: number; y: number; position: FlowPosition; inset: number } | null {
582
+ const n = nodeById.value.get(nodeId)
583
+ if (!n) return null
584
+ const list = handles.get(nodeId)?.filter((h) => h.type === type)
585
+ const h = list?.length ? (handleId != null ? list.find((x) => x.id === handleId) : list[0]) ?? list[0] : undefined
586
+ if (h) {
587
+ const a = getAbsolutePosition(nodeId)
588
+ return { x: a.x + h.x, y: a.y + h.y, position: h.position, inset: HANDLE_RADIUS }
589
+ }
590
+ const position = sidePositions(n)[type]
591
+ return { ...sidePoint(nodeId, position), position, inset: 0 }
592
+ }
593
+ // Arrowheads stop at a handle's rim instead of under it
594
+ const HANDLE_RADIUS = 5
595
+
596
+ function pathFor(type: string | undefined, p: Omit<EdgeGeometry, keyof FlowEdgePath | 'sourceInset' | 'targetInset'>): FlowEdgePath {
597
+ switch (type) {
598
+ case 'smoothstep': return getSmoothStepPath(p)
599
+ case 'step': return getStepPath(p)
600
+ case 'straight': return getStraightPath(p)
601
+ default: return getBezierPath(p)
602
+ }
603
+ }
604
+ const edgeType = (e: FlowEdge) => e.type ?? props.defaultEdgeOptions?.type ?? 'bezier'
605
+ // How it's routed: its own type, or for an `#edge-<type>` slot its `pathType` (default bezier)
606
+ const edgeRoute = (e: Partial<FlowEdge>) => e.pathType ?? props.defaultEdgeOptions?.pathType ?? edgeType(e as FlowEdge)
607
+ // Opposite edges between two circles sit side by side
608
+ const pairKeys = computed(() => new Set(edgesLocal.value.map((e) => `${e.source}>${e.target}`)))
609
+ function circleOf(id: string) {
610
+ const a = getAbsolutePosition(id)
611
+ const s = getSize(id)
612
+ return { x: a.x + s.width / 2, y: a.y + s.height / 2, r: Math.min(s.width, s.height) / 2 }
613
+ }
614
+ // An edge touching a circle runs between the centers (a straight line unless it has a type), cut at the rims
615
+ function circleGeometry(e: FlowEdge): EdgeGeometry | null {
616
+ const sc = nodeById.value.get(e.source)?.type === 'circle'
617
+ const tc = nodeById.value.get(e.target)?.type === 'circle'
618
+ const s = sc ? circleOf(e.source) : handlePoint(e.source, 'source', e.sourceHandle)
619
+ const t = tc ? circleOf(e.target) : handlePoint(e.target, 'target', e.targetHandle)
620
+ if (!s || !t) return null
621
+ const dx = t.x - s.x
622
+ const dy = t.y - s.y
623
+ const len = Math.hypot(dx, dy) || 1
624
+ const ux = dx / len
625
+ const uy = dy / len
626
+ const off = pairKeys.value.has(`${e.target}>${e.source}`) ? 6 : 0
627
+ const ox = -uy * off
628
+ const oy = ux * off
629
+ const rs = sc ? (s as { r: number }).r : 0
630
+ const rt = tc ? (t as { r: number }).r + 2 : 0
631
+ const horizontal = Math.abs(dx) >= Math.abs(dy)
632
+ const ends = {
633
+ sourceX: s.x + ux * rs + ox,
634
+ sourceY: s.y + uy * rs + oy,
635
+ sourcePosition: (horizontal ? (dx >= 0 ? 'right' : 'left') : dy >= 0 ? 'bottom' : 'top') as FlowPosition,
636
+ targetX: t.x - ux * rt + ox,
637
+ targetY: t.y - uy * rt + oy,
638
+ targetPosition: (horizontal ? (dx >= 0 ? 'left' : 'right') : dy >= 0 ? 'top' : 'bottom') as FlowPosition,
639
+ }
640
+ return { ...ends, ...pathFor(e.type ?? props.defaultEdgeOptions?.type ?? 'straight', ends), sourceInset: 0, targetInset: 0 }
641
+ }
642
+ function edgeGeometry(e: FlowEdge): EdgeGeometry | null {
643
+ if (nodeById.value.get(e.source)?.type === 'circle' || nodeById.value.get(e.target)?.type === 'circle') return circleGeometry(e)
644
+ const s = handlePoint(e.source, 'source', e.sourceHandle)
645
+ const t = handlePoint(e.target, 'target', e.targetHandle)
646
+ if (!s || !t) return null
647
+ const ends = { sourceX: s.x, sourceY: s.y, sourcePosition: s.position, targetX: t.x, targetY: t.y, targetPosition: t.position }
648
+ return { ...ends, ...pathFor(edgeRoute(e), ends), sourceInset: s.inset, targetInset: t.inset }
649
+ }
650
+
651
+ // What's drawn: groups under the edges, other nodes over them; children over their parents
652
+ const visibleNodes = computed(() => nodesLocal.value.filter((n) => !isHidden(n.id)))
653
+ const groupNodes = computed(() => visibleNodes.value.filter((n) => n.type === 'group').sort((a, b) => depthOf(a.id) - depthOf(b.id)))
654
+ const plainNodes = computed(() => visibleNodes.value.filter((n) => n.type !== 'group'))
655
+ const visibleEdges = computed(() => edgesLocal.value.filter((e) => !e.hidden && !isHidden(e.source) && !isHidden(e.target)))
656
+ const isLifted = (id: string) => dragging.value.has(id) || ancestors(id).some((a) => dragging.value.has(a))
657
+ const zIndexOf = (id: string) => (isLifted(id) ? 1000 : 0) + depthOf(id) * 10 + (selectedNodes.value.has(id) ? 3 : 0)
658
+ const nodeRenderer = (n: FlowNode) => slots[`node-${n.type ?? 'default'}`]
659
+ const edgeRenderer = (e: FlowEdge) => slots[`edge-${edgeType(e)}`]
660
+ const isReconnectable = (e: FlowEdge) => !locked.value && (e.reconnectable ?? props.edgesReconnectable)
661
+
662
+ // ── The view ──────────────────────────────────────────────────────────────────────────────────────────────
663
+ const vp = ref<FlowViewport>({ x: 0, y: 0, zoom: 1, ...props.viewport })
664
+ watch(() => props.viewport, (v) => {
665
+ if (!v || (v.x === vp.value.x && v.y === vp.value.y && v.zoom === vp.value.zoom)) return
666
+ vpAnim = null
667
+ vp.value = { ...v }
668
+ })
669
+ const clampZoom = (z: number) => Math.min(props.maxZoom, Math.max(props.minZoom, z))
670
+ function writeViewport(v: FlowViewport) {
671
+ if (v.x === vp.value.x && v.y === vp.value.y && v.zoom === vp.value.zoom) return
672
+ vp.value = v
673
+ emit('update:viewport', v)
674
+ }
675
+ type Spring1 = { p: number; v: number; t: number }
676
+ let vpAnim: { x: Spring1; y: Spring1; z: Spring1 } | null = null
677
+ function setViewport(v: Partial<FlowViewport>, opts: { animate?: boolean } = {}) {
678
+ const target = { x: v.x ?? vp.value.x, y: v.y ?? vp.value.y, zoom: clampZoom(v.zoom ?? vp.value.zoom) }
679
+ if (opts.animate === false || !ready.value || prefersReducedMotion() || typeof requestAnimationFrame === 'undefined') {
680
+ vpAnim = null
681
+ writeViewport(target)
682
+ return
683
+ }
684
+ const cur = vpAnim
685
+ vpAnim = {
686
+ x: { p: vp.value.x, v: cur?.x.v ?? 0, t: target.x },
687
+ y: { p: vp.value.y, v: cur?.y.v ?? 0, t: target.y },
688
+ z: { p: vp.value.zoom, v: cur?.z.v ?? 0, t: target.zoom },
689
+ }
690
+ kick()
691
+ }
692
+ function stepViewport(dt: number) {
693
+ const a = vpAnim
694
+ if (!a) return false
695
+ let done = true
696
+ for (const s of [a.x, a.y, a.z]) {
697
+ for (let t = 0; t < dt; t += SUBSTEP) {
698
+ const h = Math.min(SUBSTEP, dt - t)
699
+ s.v += (-STIFF * (s.p - s.t) - DAMP * s.v) * h
700
+ s.p += s.v * h
701
+ }
702
+ const eps = s === a.z ? 0.0005 : 0.1
703
+ if (Math.abs(s.p - s.t) < eps && Math.abs(s.v) < eps * 10) { s.p = s.t; s.v = 0 } else done = false
704
+ }
705
+ writeViewport({ x: a.x.p, y: a.y.p, zoom: a.z.p })
706
+ if (done) vpAnim = null
707
+ return !done
708
+ }
709
+
710
+ function rootRect() {
711
+ return root.value?.getBoundingClientRect() ?? ({ left: 0, top: 0, width: size.value.width, height: size.value.height } as DOMRect)
712
+ }
713
+ function screenToFlow(p: { x: number; y: number }): FlowXY {
714
+ const r = rootRect()
715
+ return { x: (p.x - r.left - vp.value.x) / vp.value.zoom, y: (p.y - r.top - vp.value.y) / vp.value.zoom }
716
+ }
717
+ function flowToScreen(p: FlowXY) {
718
+ const r = rootRect()
719
+ return { x: p.x * vp.value.zoom + vp.value.x + r.left, y: p.y * vp.value.zoom + vp.value.y + r.top }
720
+ }
721
+ /** Zoom to `zoom` keeping the canvas point (px from its corner) still */
722
+ function zoomAt(zoom: number, px: number, py: number, animate = false) {
723
+ const z = clampZoom(zoom)
724
+ const base = vpAnim && animate ? { x: vpAnim.x.t, y: vpAnim.y.t, zoom: vpAnim.z.t } : vp.value
725
+ const fx = (px - base.x) / base.zoom
726
+ const fy = (py - base.y) / base.zoom
727
+ setViewport({ x: px - fx * z, y: py - fy * z, zoom: z }, { animate })
728
+ }
729
+ const targetZoom = () => vpAnim?.z.t ?? vp.value.zoom
730
+ const zoomIn = () => zoomAt(targetZoom() * 1.25, size.value.width / 2, size.value.height / 2, true)
731
+ const zoomOut = () => zoomAt(targetZoom() / 1.25, size.value.width / 2, size.value.height / 2, true)
732
+ const zoomTo = (z: number, opts: { animate?: boolean } = {}) => zoomAt(z, size.value.width / 2, size.value.height / 2, opts.animate ?? true)
733
+ function setCenter(x: number, y: number, opts: { zoom?: number; animate?: boolean } = {}) {
734
+ const z = clampZoom(opts.zoom ?? targetZoom())
735
+ setViewport({ x: size.value.width / 2 - x * z, y: size.value.height / 2 - y * z, zoom: z }, { animate: opts.animate ?? true })
736
+ }
737
+ function boundsOf(ids: string[]) {
738
+ let x1 = Infinity
739
+ let y1 = Infinity
740
+ let x2 = -Infinity
741
+ let y2 = -Infinity
742
+ for (const id of ids) {
743
+ if (isHidden(id)) continue
744
+ const a = getAbsolutePosition(id)
745
+ const s = getSize(id)
746
+ x1 = Math.min(x1, a.x)
747
+ y1 = Math.min(y1, a.y)
748
+ x2 = Math.max(x2, a.x + s.width)
749
+ y2 = Math.max(y2, a.y + s.height)
750
+ }
751
+ return Number.isFinite(x1) ? { x: x1, y: y1, width: x2 - x1, height: y2 - y1 } : null
752
+ }
753
+ function fitView(opts: FlowFitOptions = {}) {
754
+ // Fit where the nodes are going, not where a spring has them right now
755
+ const ids = opts.nodes ?? nodesLocal.value.map((n) => n.id)
756
+ const saved = new Map<string, { x: number; y: number }>()
757
+ for (const [id, s] of springs) {
758
+ const d = disp.get(id)
759
+ if (d && (d.x !== s.tx || d.y !== s.ty)) { saved.set(id, { x: d.x, y: d.y }); d.x = s.tx; d.y = s.ty }
760
+ }
761
+ const b = boundsOf(ids)
762
+ for (const [id, p] of saved) { const d = disp.get(id)!; d.x = p.x; d.y = p.y }
763
+ if (!b || !size.value.width || !size.value.height) return
764
+ const pad = opts.padding ?? 0.1
765
+ const w = size.value.width * (1 - 2 * pad)
766
+ const h = size.value.height * (1 - 2 * pad)
767
+ const z = Math.min(opts.maxZoom ?? 1.5, Math.max(opts.minZoom ?? props.minZoom, Math.min(w / Math.max(1, b.width), h / Math.max(1, b.height))))
768
+ setCenter(b.x + b.width / 2, b.y + b.height / 2, { zoom: clampZoom(z), animate: opts.animate ?? true })
769
+ }
770
+
771
+ // ── Editing API ───────────────────────────────────────────────────────────────────────────────────────────
772
+ const asArray = <T,>(x: T | T[]) => (Array.isArray(x) ? x : [x])
773
+ function addNodes(ns: FlowNode | FlowNode[]) {
774
+ commit({ nodes: [...nodesLocal.value, ...asArray(ns)] })
775
+ }
776
+ function addEdges(es: FlowEdge | FlowEdge[]) {
777
+ commit({ edges: [...edgesLocal.value, ...asArray(es)] })
778
+ }
779
+ function updateNode(id: string, patch: Partial<FlowNode> | ((n: FlowNode) => FlowNode)) {
780
+ commit({ nodes: nodesLocal.value.map((n) => (n.id !== id ? n : typeof patch === 'function' ? patch(n) : { ...n, ...patch })) })
781
+ }
782
+ function updateEdge(id: string, patch: Partial<FlowEdge> | ((e: FlowEdge) => FlowEdge)) {
783
+ commit({ edges: edgesLocal.value.map((e) => (e.id !== id ? e : typeof patch === 'function' ? patch(e) : { ...e, ...patch })) })
784
+ }
785
+ function remove(ids: { nodes?: string[]; edges?: string[] }) {
786
+ const goneNodes = new Set<string>()
787
+ for (const id of ids.nodes ?? []) {
788
+ if (!nodeById.value.has(id)) continue
789
+ goneNodes.add(id)
790
+ descendants(id).forEach((d) => goneNodes.add(d))
791
+ }
792
+ const goneEdgeIds = new Set(ids.edges ?? [])
793
+ const nodes = nodesLocal.value.filter((n) => goneNodes.has(n.id))
794
+ const edges = edgesLocal.value.filter((e) => goneEdgeIds.has(e.id) || goneNodes.has(e.source) || goneNodes.has(e.target))
795
+ if (!nodes.length && !edges.length) return
796
+ if (props.beforeDelete) {
797
+ const ok = props.beforeDelete({ nodes, edges })
798
+ if (ok instanceof Promise) {
799
+ // Applied once confirmed, against whatever the nodes and edges are by then
800
+ ok.then((yes) => { if (yes) applyRemove(goneNodes, new Set(edges.map((e) => e.id))) })
801
+ return
802
+ }
803
+ if (!ok) return
804
+ }
805
+ applyRemove(goneNodes, new Set(edges.map((e) => e.id)))
806
+ }
807
+ function applyRemove(goneNodes: Set<string>, goneEdgeIds: Set<string>) {
808
+ const nodes = nodesLocal.value.filter((n) => goneNodes.has(n.id))
809
+ const edges = edgesLocal.value.filter((e) => goneEdgeIds.has(e.id) || goneNodes.has(e.source) || goneNodes.has(e.target))
810
+ if (!nodes.length && !edges.length) return
811
+ const goneEdges = new Set(edges)
812
+ commit({
813
+ nodes: nodes.length ? nodesLocal.value.filter((n) => !goneNodes.has(n.id)) : undefined,
814
+ edges: edges.length ? edgesLocal.value.filter((e) => !goneEdges.has(e)) : undefined,
815
+ })
816
+ setSelection({ nodes: selLocal.value.nodes.filter((i) => !goneNodes.has(i)), edges: selLocal.value.edges.filter((i) => !goneEdges.has(edgeById.value.get(i)!)) })
817
+ emit('delete', { nodes, edges })
818
+ announce(locale.flowDeleted.replace('{count}', String(nodes.length + edges.length)))
819
+ }
820
+ function deleteSelection() {
821
+ if (locked.value) return
822
+ const nodes = selLocal.value.nodes.filter((id) => nodeById.value.get(id)?.deletable !== false)
823
+ const edges = selLocal.value.edges.filter((id) => edgeById.value.get(id)?.deletable !== false)
824
+ remove({ nodes, edges })
825
+ }
826
+ function selectAll() {
827
+ if (!canSelect.value) return
828
+ setSelection({
829
+ nodes: visibleNodes.value.filter((n) => n.selectable !== false).map((n) => n.id),
830
+ edges: visibleEdges.value.filter((e) => e.selectable !== false).map((e) => e.id),
831
+ })
832
+ }
833
+
834
+ function copy() {
835
+ const ids = new Set(selLocal.value.nodes)
836
+ for (const id of [...ids]) descendants(id).forEach((d) => ids.add(d))
837
+ if (!ids.size) return
838
+ clipboard = {
839
+ nodes: nodesLocal.value.filter((n) => ids.has(n.id)).map((n) => {
840
+ // A node copied without its group keeps its place on the canvas
841
+ if (n.parentId && !ids.has(n.parentId)) {
842
+ const { parentId: _p, extent: _e, ...rest } = n
843
+ return { ...rest, position: getAbsolutePosition(n.id) }
844
+ }
845
+ return n
846
+ }),
847
+ edges: edgesLocal.value.filter((e) => ids.has(e.source) && ids.has(e.target)),
848
+ }
849
+ pasteCount = 0
850
+ }
851
+ function cut() {
852
+ if (locked.value) return
853
+ copy()
854
+ deleteSelection()
855
+ }
856
+ function paste(at?: FlowXY) {
857
+ if (!clipboard?.nodes.length || locked.value) return
858
+ pasteCount++
859
+ const tops = clipboard.nodes.filter((n) => !n.parentId || !clipboard!.nodes.some((m) => m.id === n.parentId))
860
+ const minX = Math.min(...tops.map((n) => n.position.x))
861
+ const minY = Math.min(...tops.map((n) => n.position.y))
862
+ const step = props.gridSize * 2 * pasteCount
863
+ const dx = at ? at.x - minX : step
864
+ const dy = at ? at.y - minY : step
865
+ const idMap = new Map(clipboard.nodes.map((n) => [n.id, makeId('node')]))
866
+ const topIds = new Set(tops.map((n) => n.id))
867
+ const nodes = clipboard.nodes.map((n) => ({
868
+ ...n,
869
+ id: idMap.get(n.id)!,
870
+ parentId: n.parentId ? idMap.get(n.parentId) ?? n.parentId : undefined,
871
+ position: topIds.has(n.id) ? { x: n.position.x + dx, y: n.position.y + dy } : n.position,
872
+ }))
873
+ const edges = clipboard.edges.map((e) => ({ ...e, id: makeId('edge'), source: idMap.get(e.source)!, target: idMap.get(e.target)! }))
874
+ instantNext = true
875
+ commit({ nodes: [...nodesLocal.value, ...nodes], edges: edges.length ? [...edgesLocal.value, ...edges] : undefined })
876
+ setSelection({ nodes: nodes.map((n) => n.id), edges: edges.map((e) => e.id) })
877
+ }
878
+
879
+ // ── Layout ────────────────────────────────────────────────────────────────────────────────────────────────
880
+ const layoutDirection = (): FlowLayoutDirection => props.layoutOptions?.direction ?? (props.direction === 'vertical' ? 'TB' : 'LR')
881
+ async function runLayout(fn?: 'tree' | 'layered' | FlowLayout | null, options?: FlowLayoutOptions, opts: { history?: boolean } = {}) {
882
+ const f = fn ?? props.layout ?? 'tree'
883
+ const impl: FlowLayout = f === 'tree' ? layoutTree : f === 'layered' ? layoutLayered : f
884
+ const sizes = new Map(nodesLocal.value.filter((n) => !n.parentId).map((n) => [n.id, getSize(n.id)]))
885
+ const o = { ...props.layoutOptions, ...options }
886
+ const result = await impl(nodesLocal.value, edgesLocal.value, { ...o, sizes, direction: o.direction ?? layoutDirection() })
887
+ let changed = false
888
+ const nodes = nodesLocal.value.map((n) => {
889
+ const p = result[n.id]
890
+ if (!p || (Math.abs(p.x - n.position.x) < 0.5 && Math.abs(p.y - n.position.y) < 0.5)) return n
891
+ changed = true
892
+ return { ...n, position: { x: Math.round(p.x), y: Math.round(p.y) } }
893
+ })
894
+ if (changed) commit({ nodes }, { history: opts.history })
895
+ }
896
+ // The graph's shape: which nodes show and how they're joined (not where they are)
897
+ const structureKey = computed(() =>
898
+ visibleNodes.value.map((n) => n.id).join(',') + '|' + visibleEdges.value.map((e) => `${e.source}>${e.target}`).join(','))
899
+ watch([structureKey, () => props.direction, () => JSON.stringify(props.layoutOptions ?? {})], () => {
900
+ if (!props.layout || !ready.value) return
901
+ // After the new nodes mount and measure; with fitView the view follows the graph as it grows
902
+ nextTick(async () => {
903
+ await runLayout(null, undefined, { history: false })
904
+ if (props.fitView) fitView()
905
+ })
906
+ })
907
+
908
+ // ── Pointer gestures, all dispatched from the canvas ──────────────────────────────────────────────────────
909
+ const DRAG_SLOP_MOUSE = 4
910
+ const DRAG_SLOP_TOUCH = 6
911
+ const NO_DRAG = 'input, textarea, select, button, a, label, [contenteditable], [data-flow-nodrag]'
912
+
913
+ type Gesture =
914
+ | { kind: 'pan'; id: number; sx: number; sy: number; vx: number; vy: number; moved: boolean; target: 'pane'; touch?: boolean; branch?: FlowEdge }
915
+ | { kind: 'marquee'; id: number; sx: number; sy: number; x: number; y: number; additive: string[]; moved: boolean }
916
+ | { kind: 'node'; id: number; nodeId: string; sx: number; sy: number; touch: boolean; active: boolean; starts: Map<string, FlowXY>; moved: boolean; reselect: boolean }
917
+ | { kind: 'connect'; id: number; from: { nodeId: string; handleId: string | null; type: 'source' | 'target' }; reconnect?: { edge: FlowEdge; end: 'source' | 'target' }; moved: boolean }
918
+ | { kind: 'pinch' }
919
+ let gesture: Gesture | null = null
920
+ // What the gesture's pointerdown landed on: a click is resolved against it, not the pointerup's target
921
+ let downTarget: HTMLElement | null = null
922
+ const touches = new Map<number, { x: number; y: number }>()
923
+ let pinch: { dist: number; cx: number; cy: number; zoom: number; fx: number; fy: number } | null = null
924
+ const pointer = { x: 0, y: 0, inside: false }
925
+
926
+ const marquee = ref<{ x: number; y: number; width: number; height: number } | null>(null)
927
+ const connection = shallowRef<{ from: { x: number; y: number; position: FlowPosition }; to: FlowXY; toPosition: FlowPosition | null; type: 'source' | 'target'; edgeType: string } | null>(null)
928
+ const connectionTarget = ref<{ key: string; valid: boolean } | null>(null)
929
+ const connecting = computed(() => !!connection.value)
930
+ const guideLines = shallowRef<{ x?: number; y?: number; from: number; to: number }[]>([])
931
+ const panning = ref(false)
932
+
933
+ function addWindowListeners() {
934
+ window.addEventListener('pointermove', onWindowMove)
935
+ window.addEventListener('pointerup', onWindowUp)
936
+ window.addEventListener('pointercancel', onWindowCancel)
937
+ }
938
+ function removeWindowListeners() {
939
+ window.removeEventListener('pointermove', onWindowMove)
940
+ window.removeEventListener('pointerup', onWindowUp)
941
+ window.removeEventListener('pointercancel', onWindowCancel)
942
+ unblockTouchScroll()
943
+ }
944
+
945
+ // A touch handed over by startDrag began outside the canvas (a palette, a sheet), so its touch-action is that
946
+ // element's and the browser would scroll or cancel it. Its touchmoves go to where it began, even once that's
947
+ // gone from the page, so they're cancelled there (and on window) until the drag ends
948
+ let touchBlocked: EventTarget[] = []
949
+ function preventTouch(e: TouchEvent) {
950
+ if (e.cancelable) e.preventDefault()
951
+ }
952
+ function blockTouchScroll(target: EventTarget | null) {
953
+ unblockTouchScroll()
954
+ touchBlocked = target && target !== window ? [target, window] : [window]
955
+ for (const t of touchBlocked) t.addEventListener('touchmove', preventTouch as EventListener, { passive: false })
956
+ }
957
+ function unblockTouchScroll() {
958
+ for (const t of touchBlocked) t.removeEventListener('touchmove', preventTouch as EventListener)
959
+ touchBlocked = []
960
+ }
961
+
962
+ function onPointerDown(e: PointerEvent) {
963
+ const t = e.target as HTMLElement
964
+ if (onOverlay(t)) return
965
+ if (e.pointerType === 'touch') {
966
+ // With no gesture running nothing listens for fingers lifting: whatever is left in the map is stale
967
+ if (!gesture) touches.clear()
968
+ touches.set(e.pointerId, { x: e.clientX, y: e.clientY })
969
+ if (touches.size === 2) {
970
+ // A second finger: whatever the first one started becomes a pinch
971
+ cancelGesture()
972
+ startPinch()
973
+ return
974
+ }
975
+ if (touches.size > 2) return
976
+ }
977
+ if (gesture) return
978
+ if (e.button === 2) return
979
+ downTarget = t
980
+ root.value?.focus({ preventScroll: true })
981
+
982
+ const handle = t.closest<HTMLElement>('[data-flow-handle]')
983
+ const reconnect = t.closest<HTMLElement>('[data-flow-reconnect]')
984
+ const nodeEl = t.closest<HTMLElement>('[data-flow-node]')
985
+ const edgeEl = t.closest<HTMLElement>('[data-flow-edge]')
986
+ if (e.button === 1) return startPan(e)
987
+
988
+ const deleteButton = t.closest<HTMLElement>('[data-flow-edge-delete]')
989
+ if (deleteButton) {
990
+ e.preventDefault()
991
+ remove({ edges: [deleteButton.dataset.flowEdgeDelete!] })
992
+ return
993
+ }
994
+ if (reconnect && edgeEl) {
995
+ const edge = edgeById.value.get(edgeEl.dataset.flowEdge!)
996
+ if (edge && isReconnectable(edge)) {
997
+ e.preventDefault()
998
+ return startReconnect(e, edge, reconnect.dataset.flowReconnect as 'source' | 'target')
999
+ }
1000
+ }
1001
+ if (handle && nodeEl && handle.dataset.flowConnectable === 'true' && nodesConnectable.value) {
1002
+ e.preventDefault()
1003
+ e.stopPropagation()
1004
+ // A connected input pulls its (last) edge off instead: drop it on another node, or on nothing to disconnect
1005
+ if (handle.dataset.flowHandle === 'target') {
1006
+ const nodeId = nodeEl.dataset.flowNode!
1007
+ const hid = handle.dataset.handleId || null
1008
+ const attached = visibleEdges.value.filter((ed) => ed.target === nodeId && (ed.targetHandle ?? null) === hid && isReconnectable(ed))
1009
+ const edge = attached[attached.length - 1]
1010
+ if (edge) return startReconnect(e, edge, 'target')
1011
+ }
1012
+ return startConnection(e, nodeEl.dataset.flowNode!, handle.dataset.handleId || null, handle.dataset.flowHandle as 'source' | 'target')
1013
+ }
1014
+ if (nodeEl) {
1015
+ if (t.closest(NO_DRAG) && t.closest(NO_DRAG) !== nodeEl) return
1016
+ return startNode(e, nodeEl.dataset.flowNode!)
1017
+ }
1018
+ if (edgeEl) {
1019
+ // Edges select on the click (pointerup) so a drag across them still pans, or branches (edgeBranching)
1020
+ const touch = e.pointerType === 'touch'
1021
+ const edge = edgeById.value.get(edgeEl.dataset.flowEdge!)
1022
+ const branch = edge && branching.value && (!touch || selectedEdges.value.has(edge.id)) ? edge : undefined
1023
+ if (branch) e.preventDefault()
1024
+ gesture = { kind: 'pan', id: e.pointerId, sx: e.clientX, sy: e.clientY, vx: vp.value.x, vy: vp.value.y, moved: false, target: 'pane', touch, branch }
1025
+ addWindowListeners()
1026
+ return
1027
+ }
1028
+ if (e.shiftKey || (props.selectionOnDrag && e.pointerType !== 'touch') || !props.panOnDrag) {
1029
+ if (canSelect.value) return startMarquee(e)
1030
+ }
1031
+ startPan(e)
1032
+ }
1033
+
1034
+ // On touch there's no Shift: holding a finger still on the background starts a selection box instead
1035
+ const LONG_PRESS = 450
1036
+ let longPress: ReturnType<typeof setTimeout> | undefined
1037
+ function startPan(e: PointerEvent) {
1038
+ const touch = e.pointerType === 'touch'
1039
+ const g: Gesture = { kind: 'pan', id: e.pointerId, sx: e.clientX, sy: e.clientY, vx: vp.value.x, vy: vp.value.y, moved: false, target: 'pane', touch }
1040
+ gesture = g
1041
+ vpAnim = null
1042
+ addWindowListeners()
1043
+ clearTimeout(longPress)
1044
+ if (touch && canSelect.value) {
1045
+ longPress = setTimeout(() => {
1046
+ if (gesture !== g || g.moved) return
1047
+ const r = rootRect()
1048
+ const x = g.sx - r.left
1049
+ const y = g.sy - r.top
1050
+ gesture = { kind: 'marquee', id: g.id, sx: x, sy: y, x, y, additive: [...selLocal.value.nodes], moved: true }
1051
+ marquee.value = { x, y, width: 0, height: 0 }
1052
+ navigator.vibrate?.(10)
1053
+ }, LONG_PRESS)
1054
+ }
1055
+ }
1056
+ function startMarquee(e: PointerEvent) {
1057
+ const r = rootRect()
1058
+ gesture = { kind: 'marquee', id: e.pointerId, sx: e.clientX - r.left, sy: e.clientY - r.top, x: e.clientX - r.left, y: e.clientY - r.top, additive: e.shiftKey ? [...selLocal.value.nodes] : [], moved: false }
1059
+ addWindowListeners()
1060
+ }
1061
+ function startNode(e: PointerEvent, nodeId: string) {
1062
+ const n = nodeById.value.get(nodeId)
1063
+ if (!n) return
1064
+ let reselect = false
1065
+ if (canSelect.value && n.selectable !== false) {
1066
+ if (e.shiftKey || e.metaKey || e.ctrlKey) {
1067
+ const has = selectedNodes.value.has(nodeId)
1068
+ setSelection({ nodes: has ? selLocal.value.nodes.filter((i) => i !== nodeId) : [...selLocal.value.nodes, nodeId] })
1069
+ if (has) return
1070
+ } else if (!selectedNodes.value.has(nodeId)) {
1071
+ setSelection({ nodes: [nodeId], edges: [] })
1072
+ } else reselect = true
1073
+ }
1074
+ gesture = { kind: 'node', id: e.pointerId, nodeId, sx: e.clientX, sy: e.clientY, touch: e.pointerType === 'touch', active: false, starts: new Map(), moved: false, reselect }
1075
+ addWindowListeners()
1076
+ }
1077
+
1078
+ function onWindowMove(e: PointerEvent) {
1079
+ pointer.x = e.clientX
1080
+ pointer.y = e.clientY
1081
+ if (e.pointerType === 'touch' && touches.has(e.pointerId)) {
1082
+ touches.set(e.pointerId, { x: e.clientX, y: e.clientY })
1083
+ if (pinch) return movePinch()
1084
+ }
1085
+ const g = gesture
1086
+ if (!g || g.kind === 'pinch' || g.id !== e.pointerId) return
1087
+ if (g.kind === 'pan') {
1088
+ const dx = e.clientX - g.sx
1089
+ const dy = e.clientY - g.sy
1090
+ if (!g.moved && Math.hypot(dx, dy) < (g.touch ? DRAG_SLOP_TOUCH : DRAG_SLOP_MOUSE)) return
1091
+ if (g.branch && !g.moved) return startBranch(g, g.branch, e)
1092
+ g.moved = true
1093
+ clearTimeout(longPress)
1094
+ panning.value = true
1095
+ writeViewport({ x: g.vx + dx, y: g.vy + dy, zoom: vp.value.zoom })
1096
+ } else if (g.kind === 'marquee') {
1097
+ const r = rootRect()
1098
+ g.x = e.clientX - r.left
1099
+ g.y = e.clientY - r.top
1100
+ if (!g.moved && Math.hypot(g.x - g.sx, g.y - g.sy) < DRAG_SLOP_MOUSE) return
1101
+ g.moved = true
1102
+ updateMarquee(g)
1103
+ } else if (g.kind === 'node') {
1104
+ if (!g.active) {
1105
+ if (Math.hypot(e.clientX - g.sx, e.clientY - g.sy) < (g.touch ? DRAG_SLOP_TOUCH : DRAG_SLOP_MOUSE)) return
1106
+ if (!canDrag.value || !beginNodeDrag(g, e)) {
1107
+ // Not draggable: the gesture pans instead
1108
+ gesture = { kind: 'pan', id: g.id, sx: e.clientX, sy: e.clientY, vx: vp.value.x, vy: vp.value.y, moved: true, target: 'pane' }
1109
+ return
1110
+ }
1111
+ }
1112
+ g.moved = true
1113
+ moveNodes(g, e.clientX, e.clientY)
1114
+ updateInsertTarget(g)
1115
+ emit('node-drag', [...g.starts.keys()].map((id) => nodeById.value.get(id)!), e)
1116
+ kick()
1117
+ } else if (g.kind === 'connect') {
1118
+ g.moved = true
1119
+ moveConnection(g, e.clientX, e.clientY)
1120
+ kick()
1121
+ }
1122
+ }
1123
+
1124
+ function onWindowUp(e: PointerEvent) {
1125
+ touches.delete(e.pointerId)
1126
+ if (pinch) {
1127
+ if (touches.size < 2) endPinch()
1128
+ return
1129
+ }
1130
+ const g = gesture
1131
+ if (!g || g.kind === 'pinch' || g.id !== e.pointerId) return
1132
+ gesture = null
1133
+ clearTimeout(longPress)
1134
+ removeWindowListeners()
1135
+ panning.value = false
1136
+ if (g.kind === 'pan') {
1137
+ if (!g.moved) clickAt(e)
1138
+ } else if (g.kind === 'marquee') {
1139
+ marquee.value = null
1140
+ if (!g.moved) clickAt(e)
1141
+ } else if (g.kind === 'node') {
1142
+ if (g.active) endNodeDrag(g, e)
1143
+ else {
1144
+ if (g.reselect && !e.shiftKey) setSelection({ nodes: [g.nodeId], edges: [] })
1145
+ const n = nodeById.value.get(g.nodeId)
1146
+ if (n) emit('node-click', n, e)
1147
+ }
1148
+ } else if (g.kind === 'connect') {
1149
+ endConnection(g, e)
1150
+ }
1151
+ }
1152
+ function onWindowCancel(e: PointerEvent) {
1153
+ clearTimeout(longPress)
1154
+ touches.delete(e.pointerId)
1155
+ if (pinch) {
1156
+ if (touches.size < 2) endPinch()
1157
+ return
1158
+ }
1159
+ cancelGesture()
1160
+ }
1161
+ function cancelGesture() {
1162
+ const g = gesture
1163
+ gesture = null
1164
+ removeWindowListeners()
1165
+ panning.value = false
1166
+ marquee.value = null
1167
+ if (g?.kind === 'node' && g.active) {
1168
+ // Back where they were
1169
+ for (const [id, p] of g.starts) {
1170
+ const s = springs.get(id)
1171
+ if (s) { s.tx = p.x; s.ty = p.y }
1172
+ }
1173
+ dragging.value = new Set()
1174
+ frozenGroups.clear()
1175
+ guideLines.value = []
1176
+ insertEdge.value = null
1177
+ insertPlan = null
1178
+ kick()
1179
+ }
1180
+ if (g?.kind === 'connect') {
1181
+ connection.value = null
1182
+ connectionTarget.value = null
1183
+ }
1184
+ }
1185
+
1186
+ // What the click (a pointerup that didn't move) landed on
1187
+ function clickAt(e: PointerEvent) {
1188
+ const t = downTarget ?? (e.target as HTMLElement)
1189
+ const edgeEl = t.closest<HTMLElement>('[data-flow-edge]')
1190
+ const edge = edgeEl ? edgeById.value.get(edgeEl.dataset.flowEdge!) : undefined
1191
+ if (edge) {
1192
+ if (canSelect.value && edge.selectable !== false) {
1193
+ if (e.shiftKey) {
1194
+ const has = selectedEdges.value.has(edge.id)
1195
+ setSelection({ edges: has ? selLocal.value.edges.filter((i) => i !== edge.id) : [...selLocal.value.edges, edge.id] })
1196
+ } else setSelection({ nodes: [], edges: [edge.id] })
1197
+ }
1198
+ emit('edge-click', edge, e)
1199
+ return
1200
+ }
1201
+ if (!e.shiftKey) setSelection(emptySelection())
1202
+ emit('pane-click', screenToFlow({ x: e.clientX, y: e.clientY }), e)
1203
+ }
1204
+
1205
+ // ── Pinch (two fingers on touch) ──────────────────────────────────────────────────────────────────────────
1206
+ function pinchInfo() {
1207
+ const [a, b] = [...touches.values()]
1208
+ const r = rootRect()
1209
+ return { dist: Math.hypot(a!.x - b!.x, a!.y - b!.y) || 1, cx: (a!.x + b!.x) / 2 - r.left, cy: (a!.y + b!.y) / 2 - r.top }
1210
+ }
1211
+ function startPinch() {
1212
+ clearTimeout(longPress)
1213
+ const p = pinchInfo()
1214
+ vpAnim = null
1215
+ gesture = { kind: 'pinch' }
1216
+ pinch = { ...p, zoom: vp.value.zoom, fx: (p.cx - vp.value.x) / vp.value.zoom, fy: (p.cy - vp.value.y) / vp.value.zoom }
1217
+ addWindowListeners()
1218
+ }
1219
+ // One finger lifted: the one left on keeps panning (and its pointerup still ends the gesture)
1220
+ function endPinch() {
1221
+ pinch = null
1222
+ const rest = [...touches][0]
1223
+ if (!rest) { gesture = null; removeWindowListeners(); return }
1224
+ const [id, p] = rest
1225
+ gesture = { kind: 'pan', id, sx: p.x, sy: p.y, vx: vp.value.x, vy: vp.value.y, moved: true, target: 'pane', touch: true }
1226
+ }
1227
+ function movePinch() {
1228
+ if (!pinch || touches.size < 2) return
1229
+ const p = pinchInfo()
1230
+ const z = clampZoom((pinch.zoom * p.dist) / pinch.dist)
1231
+ // The flow point first under the fingers' middle stays under it, wherever the fingers go
1232
+ writeViewport({ x: p.cx - pinch.fx * z, y: p.cy - pinch.fy * z, zoom: z })
1233
+ }
1234
+
1235
+ // ── Wheel and double click ────────────────────────────────────────────────────────────────────────────────
1236
+ function onWheel(e: WheelEvent) {
1237
+ const t = e.target as HTMLElement
1238
+ // Over a panel, or content inside a node marked to scroll on its own: the wheel is theirs
1239
+ if (onOverlay(t) || t.closest('[data-flow-nowheel]')) return
1240
+ e.preventDefault()
1241
+ const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? size.value.height : 1
1242
+ const r = rootRect()
1243
+ if (e.ctrlKey || e.metaKey || props.wheel === 'zoom') {
1244
+ const d = Math.max(-50, Math.min(50, e.deltaY * unit))
1245
+ zoomAt(vp.value.zoom * Math.exp(-d * 0.01), e.clientX - r.left, e.clientY - r.top)
1246
+ vpAnim = null
1247
+ return
1248
+ }
1249
+ const dx = (e.shiftKey && !e.deltaX ? e.deltaY : e.deltaX) * unit
1250
+ const dy = (e.shiftKey && !e.deltaX ? 0 : e.deltaY) * unit
1251
+ vpAnim = null
1252
+ writeViewport({ x: vp.value.x - dx, y: vp.value.y - dy, zoom: vp.value.zoom })
1253
+ }
1254
+ function onDblClick(e: MouseEvent) {
1255
+ const t = e.target as HTMLElement
1256
+ if (onOverlay(t)) return
1257
+ const nodeEl = t.closest<HTMLElement>('[data-flow-node]')
1258
+ const edgeEl = t.closest<HTMLElement>('[data-flow-edge]')
1259
+ if (nodeEl) {
1260
+ const n = nodeById.value.get(nodeEl.dataset.flowNode!)
1261
+ if (n) emit('node-dblclick', n, e)
1262
+ } else if (edgeEl) {
1263
+ const ed = edgeById.value.get(edgeEl.dataset.flowEdge!)
1264
+ if (ed) emit('edge-dblclick', ed, e)
1265
+ } else {
1266
+ emit('pane-dblclick', screenToFlow({ x: e.clientX, y: e.clientY }), e)
1267
+ if (props.zoomOnDoubleClick) {
1268
+ const r = rootRect()
1269
+ zoomAt(targetZoom() * 2, e.clientX - r.left, e.clientY - r.top, true)
1270
+ }
1271
+ }
1272
+ }
1273
+ function onContextMenu(e: MouseEvent) {
1274
+ const t = e.target as HTMLElement
1275
+ if (onOverlay(t)) return
1276
+ const nodeEl = t.closest<HTMLElement>('[data-flow-node]')
1277
+ const edgeEl = t.closest<HTMLElement>('[data-flow-edge]')
1278
+ const n = nodeEl ? nodeById.value.get(nodeEl.dataset.flowNode!) : undefined
1279
+ const ed = edgeEl ? edgeById.value.get(edgeEl.dataset.flowEdge!) : undefined
1280
+ if (n) emit('node-contextmenu', n, e)
1281
+ else if (ed) emit('edge-contextmenu', ed, e)
1282
+ else emit('pane-contextmenu', screenToFlow({ x: e.clientX, y: e.clientY }), e)
1283
+ }
1284
+
1285
+ // ── Selection box ─────────────────────────────────────────────────────────────────────────────────────────
1286
+ function updateMarquee(g: Extract<Gesture, { kind: 'marquee' }>) {
1287
+ const x = Math.min(g.sx, g.x)
1288
+ const y = Math.min(g.sy, g.y)
1289
+ const w = Math.abs(g.x - g.sx)
1290
+ const h = Math.abs(g.y - g.sy)
1291
+ marquee.value = { x, y, width: w, height: h }
1292
+ const z = vp.value.zoom
1293
+ const fx1 = (x - vp.value.x) / z
1294
+ const fy1 = (y - vp.value.y) / z
1295
+ const fx2 = fx1 + w / z
1296
+ const fy2 = fy1 + h / z
1297
+ const inside = visibleNodes.value.filter((n) => {
1298
+ if (n.selectable === false) return false
1299
+ const a = getAbsolutePosition(n.id)
1300
+ const s = getSize(n.id)
1301
+ return a.x < fx2 && a.x + s.width > fx1 && a.y < fy2 && a.y + s.height > fy1
1302
+ }).map((n) => n.id)
1303
+ const nodes = [...new Set([...g.additive, ...inside])]
1304
+ const set = new Set(nodes)
1305
+ setSelection({ nodes, edges: visibleEdges.value.filter((e) => e.selectable !== false && set.has(e.source) && set.has(e.target)).map((e) => e.id) })
1306
+ }
1307
+
1308
+ // ── Dragging nodes ────────────────────────────────────────────────────────────────────────────────────────
1309
+ function beginNodeDrag(g: Extract<Gesture, { kind: 'node' }>, e: PointerEvent) {
1310
+ const sel = selectedNodes.value.has(g.nodeId) ? selLocal.value.nodes : [g.nodeId]
1311
+ // A node whose group moves too comes along by itself
1312
+ const ids = sel.filter((id) => {
1313
+ const n = nodeById.value.get(id)
1314
+ return n && n.draggable !== false && !isHidden(id) && !ancestors(id).some((a) => sel.includes(a))
1315
+ })
1316
+ if (!ids.includes(g.nodeId) && nodeById.value.get(g.nodeId)?.draggable === false) return false
1317
+ if (!ids.length) return false
1318
+ for (const id of ids) {
1319
+ const s = springs.get(id)!
1320
+ g.starts.set(id, { x: s.tx, y: s.ty })
1321
+ }
1322
+ g.active = true
1323
+ for (const id of ids) for (const a of ancestors(id)) if (!frozenGroups.has(a)) frozenGroups.set(a, getSize(a))
1324
+ dragging.value = new Set(ids)
1325
+ document.body.style.userSelect = 'none'
1326
+ emit('node-drag-start', ids.map((id) => nodeById.value.get(id)!), e)
1327
+ return true
1328
+ }
1329
+
1330
+ /**
1331
+ * Drags a node with a pointer that's already down (from a palette outside the canvas: add the node under the
1332
+ * pointer, then hand it the event). It follows the pointer from there, with the guides and splicing into edges
1333
+ */
1334
+ function startDrag(id: string, e: PointerEvent) {
1335
+ if (!nodeById.value.has(id) || locked.value) return
1336
+ if (gesture) cancelGesture()
1337
+ // A node added this tick has no spring yet
1338
+ if (!springs.has(id)) syncPositions()
1339
+ if (canSelect.value) setSelection({ nodes: [id], edges: [] })
1340
+ const g: Extract<Gesture, { kind: 'node' }> = { kind: 'node', id: e.pointerId, nodeId: id, sx: e.clientX, sy: e.clientY, touch: e.pointerType === 'touch', active: false, starts: new Map(), moved: true, reselect: false }
1341
+ gesture = g
1342
+ pointer.x = e.clientX
1343
+ pointer.y = e.clientY
1344
+ addWindowListeners()
1345
+ if (g.touch) blockTouchScroll(e.target)
1346
+ if (!beginNodeDrag(g, e)) {
1347
+ gesture = null
1348
+ removeWindowListeners()
1349
+ }
1350
+ }
1351
+
1352
+ const GUIDE_SNAP = 6
1353
+ function moveNodes(g: Extract<Gesture, { kind: 'node' }>, cx: number, cy: number) {
1354
+ const z = vp.value.zoom
1355
+ let dx = (cx - g.sx) / z
1356
+ let dy = (cy - g.sy) / z
1357
+ const lead = g.starts.get(g.nodeId) ?? [...g.starts.values()][0]!
1358
+ const leadId = g.starts.has(g.nodeId) ? g.nodeId : [...g.starts.keys()][0]!
1359
+ if (props.snapToGrid) {
1360
+ const gs = props.gridSize
1361
+ dx = Math.round((lead.x + dx) / gs) * gs - lead.x
1362
+ dy = Math.round((lead.y + dy) / gs) * gs - lead.y
1363
+ guideLines.value = []
1364
+ } else if (props.guides && g.starts.size === 1) {
1365
+ const snapped = snapToGuides(leadId, lead, dx, dy)
1366
+ dx = snapped.dx
1367
+ dy = snapped.dy
1368
+ }
1369
+ for (const [id, p] of g.starts) {
1370
+ let x = p.x + dx
1371
+ let y = p.y + dy
1372
+ const n = nodeById.value.get(id)!
1373
+ const parent = parentOf(id)
1374
+ if (n.extent === 'parent' && parent) {
1375
+ const ps = getSize(parent)
1376
+ const s = getSize(id)
1377
+ x = Math.max(0, Math.min(ps.width - s.width, x))
1378
+ y = Math.max(0, Math.min(ps.height - s.height, y))
1379
+ }
1380
+ const s = springs.get(id)!
1381
+ s.x = s.tx = x
1382
+ s.y = s.ty = y
1383
+ s.vx = s.vy = 0
1384
+ const d = disp.get(id)!
1385
+ d.x = x
1386
+ d.y = y
1387
+ }
1388
+ }
1389
+ // Snaps the dragged node's edges and center to other nodes' within a few px, and draws the lines it lines up on
1390
+ function snapToGuides(id: string, start: FlowXY, dx: number, dy: number) {
1391
+ const parentAbs = parentOf(id) ? getAbsolutePosition(parentOf(id)!) : { x: 0, y: 0 }
1392
+ const s = getSize(id)
1393
+ const ax = parentAbs.x + start.x + dx
1394
+ const ay = parentAbs.y + start.y + dy
1395
+ const xs = [ax, ax + s.width / 2, ax + s.width]
1396
+ const ys = [ay, ay + s.height / 2, ay + s.height]
1397
+ const tol = GUIDE_SNAP / vp.value.zoom
1398
+ let bestX: { d: number; to: number; box: { y1: number; y2: number } } | null = null
1399
+ let bestY: { d: number; to: number; box: { x1: number; x2: number } } | null = null
1400
+ const skip = new Set([id, ...descendants(id), ...ancestors(id)])
1401
+ for (const n of visibleNodes.value) {
1402
+ if (skip.has(n.id)) continue
1403
+ const a = getAbsolutePosition(n.id)
1404
+ const ns = getSize(n.id)
1405
+ const oxs = [a.x, a.x + ns.width / 2, a.x + ns.width]
1406
+ const oys = [a.y, a.y + ns.height / 2, a.y + ns.height]
1407
+ for (const x of xs) for (const o of oxs) {
1408
+ const d = o - x
1409
+ if (Math.abs(d) <= tol && (!bestX || Math.abs(d) < Math.abs(bestX.d))) bestX = { d, to: o, box: { y1: a.y, y2: a.y + ns.height } }
1410
+ }
1411
+ for (const y of ys) for (const o of oys) {
1412
+ const d = o - y
1413
+ if (Math.abs(d) <= tol && (!bestY || Math.abs(d) < Math.abs(bestY.d))) bestY = { d, to: o, box: { x1: a.x, x2: a.x + ns.width } }
1414
+ }
1415
+ }
1416
+ const lines: { x?: number; y?: number; from: number; to: number }[] = []
1417
+ if (bestX) {
1418
+ dx += bestX.d
1419
+ lines.push({ x: bestX.to, from: Math.min(ay, bestX.box.y1), to: Math.max(ay + s.height, bestX.box.y2) })
1420
+ }
1421
+ if (bestY) {
1422
+ dy += bestY.d
1423
+ const nx = parentAbs.x + start.x + dx
1424
+ lines.push({ y: bestY.to, from: Math.min(nx, bestY.box.x1), to: Math.max(nx + s.width, bestY.box.x2) })
1425
+ }
1426
+ guideLines.value = lines
1427
+ return { dx, dy }
1428
+ }
1429
+
1430
+ function getIntersectingNodes(target: string | { x: number; y: number; width: number; height: number }) {
1431
+ let box: { x: number; y: number; width: number; height: number }
1432
+ const skip = new Set<string>()
1433
+ if (typeof target === 'string') {
1434
+ box = { ...getAbsolutePosition(target), ...getSize(target) }
1435
+ skip.add(target)
1436
+ descendants(target).forEach((d) => skip.add(d))
1437
+ ancestors(target).forEach((a) => skip.add(a))
1438
+ } else box = target
1439
+ return visibleNodes.value.filter((n) => {
1440
+ if (skip.has(n.id) || n.type === 'group') return false
1441
+ const a = getAbsolutePosition(n.id)
1442
+ const s = getSize(n.id)
1443
+ return a.x < box.x + box.width && a.x + s.width > box.x && a.y < box.y + box.height && a.y + s.height > box.y
1444
+ })
1445
+ }
1446
+
1447
+ // ── A lone node dropped onto an edge splices into it ─────────────────────────────────────────────────────
1448
+ const insertEdge = ref<string | null>(null)
1449
+ let insertPlan: { node: string; edge: FlowEdge; connections: [FlowConnection, FlowConnection] } | null = null
1450
+ function updateInsertTarget(g: Extract<Gesture, { kind: 'node' }>) {
1451
+ insertPlan = null
1452
+ const found = findInsert(g)
1453
+ insertPlan = found
1454
+ insertEdge.value = found?.edge.id ?? null
1455
+ }
1456
+ function findInsert(g: Extract<Gesture, { kind: 'node' }>): typeof insertPlan {
1457
+ if (!props.insertOnEdge || g.starts.size !== 1 || !nodesConnectable.value) return null
1458
+ const id = [...g.starts.keys()][0]!
1459
+ const n = nodeById.value.get(id)
1460
+ if (!n || n.type === 'group' || n.connectable === false || n.insertable === false) return null
1461
+ if (edgesLocal.value.some((e) => e.source === id || e.target === id)) return null
1462
+ // It needs a way in and a way out (or no handles at all: then edges meet its sides; a circle's meet the circle)
1463
+ let target: string | null = null
1464
+ let source: string | null = null
1465
+ const list = handles.get(id)
1466
+ if (list?.length) {
1467
+ const t = list.find((h) => h.type === 'target' && h.connectable)
1468
+ const s = list.find((h) => h.type === 'source' && h.connectable)
1469
+ if ((!t && n.type !== 'circle') || (!s && n.type !== 'circle')) return null
1470
+ target = t?.id ?? null
1471
+ source = s?.id ?? null
1472
+ }
1473
+ // The node's center over the edge, within half its height
1474
+ const a = getAbsolutePosition(id)
1475
+ const size = getSize(id)
1476
+ const cx = a.x + size.width / 2
1477
+ const cy = a.y + size.height / 2
1478
+ const reach = Math.max(8 / vp.value.zoom, Math.min(size.width, size.height) / 2)
1479
+ let best: { edge: FlowEdge; d: number } | null = null
1480
+ for (const e of visibleEdges.value) {
1481
+ if (e.deletable === false) continue
1482
+ const geo = edgeGeometry(e)
1483
+ if (!geo) continue
1484
+ const d = distanceToPoints(cx, cy, edgePathPoints(edgeType(e), geo))
1485
+ if (d <= reach && (!best || d < best.d)) best = { edge: e, d }
1486
+ }
1487
+ if (!best) return null
1488
+ const e = best.edge
1489
+ const c1: FlowConnection = { source: e.source, sourceHandle: e.sourceHandle ?? null, target: id, targetHandle: target }
1490
+ const c2: FlowConnection = { source: id, sourceHandle: source, target: e.target, targetHandle: e.targetHandle ?? null }
1491
+ if (!isValid(c1) || !isValid(c2)) return null
1492
+ return { node: id, edge: e, connections: [c1, c2] }
1493
+ }
1494
+
1495
+ // Room between spliced-in nodes, along the flow's direction
1496
+ const SPLICE_GAP = 48
1497
+ function makeRoom(nodes: FlowNode[], plan: NonNullable<typeof insertPlan>): FlowNode[] {
1498
+ const byId = new Map(nodes.map((n) => [n.id, n]))
1499
+ const a = byId.get(plan.edge.source)
1500
+ const b = byId.get(plan.node)
1501
+ const c = byId.get(plan.edge.target)
1502
+ // Only among siblings: positions are relative to the same parent
1503
+ if (!a || !b || !c || a.parentId !== b.parentId || b.parentId !== c.parentId) return nodes
1504
+ const horizontal = props.direction !== 'vertical'
1505
+ const k = horizontal ? 'x' : 'y'
1506
+ const len = (id: string) => (horizontal ? getSize(id).width : getSize(id).height)
1507
+ const aEnd = a.position[k] + len(a.id)
1508
+ // C must come after A for "after" to mean anything (a loop back or a sideways edge is left alone)
1509
+ if (c.position[k] < aEnd) return nodes
1510
+ const bStart = Math.max(b.position[k], aEnd + SPLICE_GAP)
1511
+ const push = Math.max(0, bStart + len(b.id) + SPLICE_GAP - c.position[k])
1512
+ // C and everything downstream of it (A, B and A's own ancestors stay put)
1513
+ const moving = new Set<string>()
1514
+ if (push > 0) {
1515
+ const out = new Map<string, string[]>()
1516
+ for (const e of edgesLocal.value) if (e !== plan.edge) (out.get(e.source) ?? out.set(e.source, []).get(e.source)!).push(e.target)
1517
+ const queue = [c.id]
1518
+ while (queue.length) {
1519
+ const id = queue.shift()!
1520
+ if (moving.has(id) || id === a.id || id === b.id) continue
1521
+ const n = byId.get(id)
1522
+ if (!n || n.parentId !== c.parentId) continue
1523
+ moving.add(id)
1524
+ queue.push(...(out.get(id) ?? []))
1525
+ }
1526
+ }
1527
+ if (bStart === b.position[k] && !moving.size) return nodes
1528
+ return nodes.map((n) => {
1529
+ if (n.id === b.id) return { ...n, position: { ...n.position, [k]: bStart } }
1530
+ if (moving.has(n.id)) return { ...n, position: { ...n.position, [k]: n.position[k] + push } }
1531
+ return n
1532
+ })
1533
+ }
1534
+
1535
+ function endNodeDrag(g: Extract<Gesture, { kind: 'node' }>, e: PointerEvent) {
1536
+ document.body.style.userSelect = ''
1537
+ const plan = insertPlan
1538
+ insertPlan = null
1539
+ insertEdge.value = null
1540
+ // The two edges that take the old one's place, with its look (not its label)
1541
+ let spliced: FlowEdge[] | undefined
1542
+ if (plan && props.autoConnect) {
1543
+ const { id: _id, label: _label, source: _s, target: _t, sourceHandle: _sh, targetHandle: _th, ...look } = plan.edge
1544
+ spliced = plan.connections.map((c) => ({ ...look, id: makeId('edge'), ...c }))
1545
+ }
1546
+ guideLines.value = []
1547
+ const moved = [...g.starts.keys()].filter((id) => {
1548
+ const s = springs.get(id)!
1549
+ const p = g.starts.get(id)!
1550
+ return s.tx !== p.x || s.ty !== p.y
1551
+ })
1552
+ // Reparent into the group under the pointer
1553
+ const reparent = new Map<string, string | undefined>()
1554
+ if (props.dropIntoGroups) {
1555
+ const at = screenToFlow({ x: e.clientX, y: e.clientY })
1556
+ for (const id of g.starts.keys()) {
1557
+ const n = nodeById.value.get(id)!
1558
+ if (n.type === 'group') continue
1559
+ const skip = new Set([id, ...descendants(id)])
1560
+ const group = groupNodes.value
1561
+ .filter((gn) => !skip.has(gn.id))
1562
+ .filter((gn) => {
1563
+ const a = getAbsolutePosition(gn.id)
1564
+ const s = getSize(gn.id)
1565
+ return at.x >= a.x && at.x <= a.x + s.width && at.y >= a.y && at.y <= a.y + s.height
1566
+ })
1567
+ .sort((a, b) => depthOf(b.id) - depthOf(a.id))[0]
1568
+ if ((group?.id ?? undefined) !== (n.parentId ?? undefined)) reparent.set(id, group?.id)
1569
+ }
1570
+ }
1571
+ if (moved.length || reparent.size) {
1572
+ const movedSet = new Set(moved)
1573
+ const nodes = nodesLocal.value.map((n) => {
1574
+ if (!movedSet.has(n.id) && !reparent.has(n.id)) return n
1575
+ const s = springs.get(n.id)!
1576
+ let position = { x: s.tx, y: s.ty }
1577
+ let parentId = n.parentId
1578
+ if (reparent.has(n.id)) {
1579
+ const abs = getAbsolutePosition(n.id)
1580
+ parentId = reparent.get(n.id)
1581
+ const pa = parentId ? getAbsolutePosition(parentId) : { x: 0, y: 0 }
1582
+ position = { x: abs.x - pa.x, y: abs.y - pa.y }
1583
+ const sp = springs.get(n.id)!
1584
+ sp.x = sp.tx = position.x
1585
+ sp.y = sp.ty = position.y
1586
+ const d = disp.get(n.id)!
1587
+ d.x = position.x
1588
+ d.y = position.y
1589
+ }
1590
+ const out: FlowNode = { ...n, position }
1591
+ if (parentId) out.parentId = parentId
1592
+ else delete out.parentId
1593
+ return out
1594
+ })
1595
+ // Spliced in without room: it moves to sit after A, and C with everything after it moves on to make room
1596
+ const placed = spliced && plan ? makeRoom(nodes, plan) : nodes
1597
+ // Let go first, so the spliced node springs to its place too
1598
+ if (spliced) dragging.value = new Set()
1599
+ commit({ nodes: placed, edges: spliced ? [...edgesLocal.value.filter((x) => x !== plan!.edge), ...spliced] : undefined })
1600
+ const first = nodeById.value.get(g.nodeId)
1601
+ if (first) announce(locale.flowMoved.replace('{label}', nodeLabel(first)))
1602
+ }
1603
+ dragging.value = new Set()
1604
+ frozenGroups.clear()
1605
+ const draggedNodes = [...g.starts.keys()].map((id) => nodeById.value.get(id)!).filter(Boolean)
1606
+ if (plan) emit('insert', { node: nodeById.value.get(plan.node)!, edge: plan.edge, connections: plan.connections })
1607
+ emit('node-drag-stop', { nodes: draggedNodes, intersecting: getIntersectingNodes(g.nodeId), event: e })
1608
+ }
1609
+
1610
+ // Near the edges while dragging, the view scrolls (and what's dragged comes along)
1611
+ const EDGE_ZONE = 40
1612
+ function autoPan(dt: number) {
1613
+ const g = gesture
1614
+ if (!g || (g.kind !== 'node' && g.kind !== 'connect') || !g.moved) return false
1615
+ const r = rootRect()
1616
+ const px = pointer.x - r.left
1617
+ const py = pointer.y - r.top
1618
+ const speed = 600
1619
+ const vx = px < EDGE_ZONE ? 1 - px / EDGE_ZONE : px > r.width - EDGE_ZONE ? -(1 - (r.width - px) / EDGE_ZONE) : 0
1620
+ const vy = py < EDGE_ZONE ? 1 - py / EDGE_ZONE : py > r.height - EDGE_ZONE ? -(1 - (r.height - py) / EDGE_ZONE) : 0
1621
+ if (!vx && !vy) return false
1622
+ const mx = Math.max(-1, Math.min(1, vx)) * speed * dt
1623
+ const my = Math.max(-1, Math.min(1, vy)) * speed * dt
1624
+ writeViewport({ x: vp.value.x + mx, y: vp.value.y + my, zoom: vp.value.zoom })
1625
+ if (g.kind === 'node') {
1626
+ // The drag's start shifts with the view so the nodes stay under the pointer
1627
+ g.sx += mx
1628
+ g.sy += my
1629
+ moveNodes(g, pointer.x, pointer.y)
1630
+ } else moveConnection(g, pointer.x, pointer.y)
1631
+ return true
1632
+ }
1633
+
1634
+ // ── Connecting ────────────────────────────────────────────────────────────────────────────────────────────
1635
+ function startConnection(e: PointerEvent, nodeId: string, handleId: string | null, type: 'source' | 'target') {
1636
+ const from = handlePoint(nodeId, type, handleId)
1637
+ if (!from) return
1638
+ gesture = { kind: 'connect', id: e.pointerId, from: { nodeId, handleId, type }, moved: false }
1639
+ connection.value = { from, to: { x: from.x, y: from.y }, toPosition: null, type, edgeType: edgeRoute({ ...props.defaultEdgeOptions }) }
1640
+ pointer.x = e.clientX
1641
+ pointer.y = e.clientY
1642
+ emit('connect-start', { nodeId, handleId, type })
1643
+ addWindowListeners()
1644
+ }
1645
+ // A branch: a new connection from the edge's source, its preview leaving from where the edge was grabbed
1646
+ function startBranch(pan: { id: number; sx: number; sy: number }, edge: FlowEdge, e: PointerEvent) {
1647
+ const src = handlePoint(edge.source, 'source', edge.sourceHandle)
1648
+ if (!src) return
1649
+ const handleId = edge.sourceHandle ?? null
1650
+ const g: Gesture = { kind: 'connect', id: pan.id, from: { nodeId: edge.source, handleId, type: 'source' }, moved: true }
1651
+ gesture = g
1652
+ const at = screenToFlow({ x: pan.sx, y: pan.sy })
1653
+ connection.value = { from: { x: at.x, y: at.y, position: src.position }, to: at, toPosition: null, type: 'source', edgeType: edgeRoute(edge) }
1654
+ emit('connect-start', { nodeId: edge.source, handleId, type: 'source' })
1655
+ moveConnection(g, e.clientX, e.clientY)
1656
+ kick()
1657
+ }
1658
+ function startReconnect(e: PointerEvent, edge: FlowEdge, end: 'source' | 'target') {
1659
+ // Dragging the target end: the connection runs from the source, and the other way round
1660
+ const fixed = end === 'target' ? { nodeId: edge.source, handleId: edge.sourceHandle ?? null, type: 'source' as const } : { nodeId: edge.target, handleId: edge.targetHandle ?? null, type: 'target' as const }
1661
+ const from = handlePoint(fixed.nodeId, fixed.type, fixed.handleId)
1662
+ if (!from) return
1663
+ gesture = { kind: 'connect', id: e.pointerId, from: fixed, reconnect: { edge, end }, moved: false }
1664
+ const to = screenToFlow({ x: e.clientX, y: e.clientY })
1665
+ connection.value = { from, to, toPosition: null, type: fixed.type, edgeType: edgeRoute(edge) }
1666
+ pointer.x = e.clientX
1667
+ pointer.y = e.clientY
1668
+ addWindowListeners()
1669
+ }
1670
+ const handleKey = (nodeId: string, h: { id: string | null; type: string }) => `${nodeId}:${h.id ?? ''}:${h.type}`
1671
+ function connectionFor(from: { nodeId: string; handleId: string | null; type: 'source' | 'target' }, nodeId: string, handleId: string | null): FlowConnection {
1672
+ return from.type === 'source'
1673
+ ? { source: from.nodeId, sourceHandle: from.handleId, target: nodeId, targetHandle: handleId }
1674
+ : { source: nodeId, sourceHandle: handleId, target: from.nodeId, targetHandle: from.handleId }
1675
+ }
1676
+ function isValid(c: FlowConnection, ignore?: FlowEdge) {
1677
+ if (c.source === c.target) return false
1678
+ const dup = edgesLocal.value.some((e) => e !== ignore && e.source === c.source && e.target === c.target && (e.sourceHandle ?? null) === c.sourceHandle && (e.targetHandle ?? null) === c.targetHandle)
1679
+ if (dup) return false
1680
+ return props.isValidConnection ? props.isValidConnection(c) : true
1681
+ }
1682
+ let connectionCandidate: { nodeId: string; handleId: string | null; valid: boolean } | null = null
1683
+ function moveConnection(g: Extract<Gesture, { kind: 'connect' }>, cx: number, cy: number) {
1684
+ const p = screenToFlow({ x: cx, y: cy })
1685
+ const want = g.from.type === 'source' ? 'target' : 'source'
1686
+ const radius = props.connectionRadius / vp.value.zoom
1687
+ let best: { nodeId: string; h: FlowHandleBounds | null; d: number; x: number; y: number; position: FlowPosition } | null = null
1688
+ for (const n of visibleNodes.value) {
1689
+ if (n.connectable === false) continue
1690
+ const a = getAbsolutePosition(n.id)
1691
+ const s = getSize(n.id)
1692
+ const over = p.x >= a.x && p.x <= a.x + s.width && p.y >= a.y && p.y <= a.y + s.height
1693
+ const list = (handles.get(n.id) ?? []).filter((h) => h.type === want && h.connectable)
1694
+ if (list.length) {
1695
+ for (const h of list) {
1696
+ const x = a.x + h.x
1697
+ const y = a.y + h.y
1698
+ const d = Math.hypot(x - p.x, y - p.y)
1699
+ // Over the node's body, its nearest handle counts too (easier on touch)
1700
+ if ((d <= radius || over) && (!best || d < best.d)) best = { nodeId: n.id, h, d: over && d > radius ? d + radius : d, x, y, position: h.position }
1701
+ }
1702
+ } else if (over) {
1703
+ // A node without a handle of that kind connects at its side (a circle, at its center)
1704
+ const position = sidePositions(n)[want]
1705
+ const sp = sidePoint(n.id, position)
1706
+ const d = Math.hypot(sp.x - p.x, sp.y - p.y)
1707
+ if (!best || d < best.d) best = { nodeId: n.id, h: null, d, x: sp.x, y: sp.y, position }
1708
+ }
1709
+ }
1710
+ if (best && best.nodeId === g.from.nodeId) best = null
1711
+ const cur = connection.value!
1712
+ if (best) {
1713
+ const c = connectionFor(g.from, best.nodeId, best.h?.id ?? null)
1714
+ const valid = isValid(c, g.reconnect?.edge)
1715
+ connectionCandidate = { nodeId: best.nodeId, handleId: best.h?.id ?? null, valid }
1716
+ connectionTarget.value = { key: handleKey(best.nodeId, { id: best.h?.id ?? null, type: want }), valid }
1717
+ connection.value = { ...cur, to: valid ? { x: best.x, y: best.y } : p, toPosition: valid ? best.position : null }
1718
+ } else {
1719
+ connectionCandidate = null
1720
+ connectionTarget.value = null
1721
+ connection.value = { ...cur, to: p, toPosition: null }
1722
+ }
1723
+ }
1724
+ function endConnection(g: Extract<Gesture, { kind: 'connect' }>, e: PointerEvent) {
1725
+ const cand = connectionCandidate
1726
+ connectionCandidate = null
1727
+ connection.value = null
1728
+ connectionTarget.value = null
1729
+ const position = screenToFlow({ x: e.clientX, y: e.clientY })
1730
+ const c = cand?.valid ? connectionFor(g.from, cand.nodeId, cand.handleId) : null
1731
+ if (g.reconnect) {
1732
+ const edge = g.reconnect.edge
1733
+ if (c) {
1734
+ emit('reconnect', { edge, connection: c })
1735
+ if (props.autoConnect) updateEdge(edge.id, { source: c.source, target: c.target, sourceHandle: c.sourceHandle, targetHandle: c.targetHandle })
1736
+ } else if (g.moved && !cand && edge.deletable !== false) {
1737
+ // Pulled off and dropped on nothing: disconnected (dropped on a handle it can't join, it stays)
1738
+ remove({ edges: [edge.id] })
1739
+ }
1740
+ return
1741
+ }
1742
+ if (c) {
1743
+ emit('connect', c)
1744
+ if (props.autoConnect) {
1745
+ addEdges({ ...props.defaultEdgeOptions, id: makeId('edge'), ...c })
1746
+ const s = nodeById.value.get(c.source)
1747
+ const t = nodeById.value.get(c.target)
1748
+ if (s && t) announce(locale.flowConnected.replace('{source}', nodeLabel(s)).replace('{target}', nodeLabel(t)))
1749
+ }
1750
+ }
1751
+ emit('connect-end', { connection: c, position, from: g.from })
1752
+ }
1753
+ const connectionPath = computed(() => {
1754
+ const c = connection.value
1755
+ if (!c) return ''
1756
+ const flip = c.type === 'target'
1757
+ const opposite: Record<FlowPosition, FlowPosition> = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }
1758
+ const toPos = c.toPosition ?? opposite[c.from.position]
1759
+ const ends = flip
1760
+ ? { sourceX: c.to.x, sourceY: c.to.y, sourcePosition: toPos, targetX: c.from.x, targetY: c.from.y, targetPosition: c.from.position }
1761
+ : { sourceX: c.from.x, sourceY: c.from.y, sourcePosition: c.from.position, targetX: c.to.x, targetY: c.to.y, targetPosition: toPos }
1762
+ return pathFor(c.edgeType, ends).path
1763
+ })
1764
+
1765
+ // ── Keyboard ──────────────────────────────────────────────────────────────────────────────────────────────
1766
+ const nodeLabel = (n: FlowNode) => String((n.data as { label?: unknown } | undefined)?.label ?? n.id)
1767
+ function isTyping(t: EventTarget | null) {
1768
+ const el = t as HTMLElement | null
1769
+ return !!el?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable="false"])')
1770
+ }
1771
+ function onKeyDown(e: KeyboardEvent) {
1772
+ if (isTyping(e.target)) return
1773
+ const mod = e.ctrlKey || e.metaKey
1774
+ const key = e.key.toLowerCase()
1775
+ if (e.key === 'Escape') {
1776
+ if (gesture) cancelGesture()
1777
+ else if (selLocal.value.nodes.length || selLocal.value.edges.length) setSelection(emptySelection())
1778
+ else return
1779
+ e.preventDefault()
1780
+ e.stopPropagation()
1781
+ return
1782
+ }
1783
+ if (mod && key === 'z' && !e.shiftKey) { e.preventDefault(); undo(); return }
1784
+ if (mod && ((key === 'z' && e.shiftKey) || key === 'y')) { e.preventDefault(); redo(); return }
1785
+ if (mod && key === 'a') { e.preventDefault(); selectAll(); return }
1786
+ if (mod && key === 'c') { copy(); return }
1787
+ if (mod && key === 'x') { e.preventDefault(); cut(); return }
1788
+ if (mod && key === 'v') {
1789
+ e.preventDefault()
1790
+ paste(pointer.inside ? screenToFlow(pointer) : undefined)
1791
+ return
1792
+ }
1793
+ if (props.deleteKeys?.includes(e.key)) { e.preventDefault(); deleteSelection(); return }
1794
+ if (!mod && (e.key === '+' || e.key === '=')) { e.preventDefault(); zoomIn(); return }
1795
+ if (!mod && (e.key === '-' || e.key === '_')) { e.preventDefault(); zoomOut(); return }
1796
+ if (e.key === '!' || (e.shiftKey && e.code === 'Digit1')) { e.preventDefault(); fitView(); return }
1797
+ const arrows: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }
1798
+ const dir = arrows[e.key]
1799
+ if (dir && selLocal.value.nodes.length && canDrag.value) {
1800
+ e.preventDefault()
1801
+ const step = props.snapToGrid ? props.gridSize : e.shiftKey ? 50 : 10
1802
+ const sel = selLocal.value.nodes
1803
+ const ids = new Set(sel.filter((id) => nodeById.value.get(id)?.draggable !== false && !ancestors(id).some((a) => sel.includes(a))))
1804
+ if (!ids.size) return
1805
+ instantNext = true
1806
+ commit({ nodes: nodesLocal.value.map((n) => (ids.has(n.id) ? { ...n, position: { x: n.position.x + dir[0] * step, y: n.position.y + dir[1] * step } } : n)) }, { coalesce: `move:${[...ids].join(',')}` })
1807
+ const first = nodeById.value.get([...ids][0]!)
1808
+ if (first) announce(locale.flowMoved.replace('{label}', nodeLabel(first)))
1809
+ } else if (dir && !selLocal.value.nodes.length) {
1810
+ e.preventDefault()
1811
+ writeViewport({ x: vp.value.x - dir[0] * 40, y: vp.value.y - dir[1] * 40, zoom: vp.value.zoom })
1812
+ }
1813
+ }
1814
+ // Focusing a node (Tab) and Enter/Space on it select it
1815
+ function onNodeKey(e: KeyboardEvent, id: string) {
1816
+ if (isTyping(e.target) || (e.target as HTMLElement).dataset.flowNode !== id) return
1817
+ if ((e.key === 'Enter' || e.key === ' ') && canSelect.value) {
1818
+ e.preventDefault()
1819
+ if (e.shiftKey) setSelection({ nodes: selectedNodes.value.has(id) ? selLocal.value.nodes.filter((i) => i !== id) : [...selLocal.value.nodes, id] })
1820
+ else setSelection({ nodes: [id], edges: [] })
1821
+ }
1822
+ }
1823
+ function onEdgeKey(e: KeyboardEvent, id: string) {
1824
+ if ((e.key === 'Enter' || e.key === ' ') && canSelect.value) {
1825
+ e.preventDefault()
1826
+ setSelection({ nodes: [], edges: [id] })
1827
+ }
1828
+ }
1829
+
1830
+ // ── Background ────────────────────────────────────────────────────────────────────────────────────────────
1831
+ const patternId = `m3-flow-bg-${Math.random().toString(36).slice(2, 8)}`
1832
+ const pattern = computed(() => {
1833
+ let gap = props.gridSize * vp.value.zoom
1834
+ // Coarser when zoomed out, so the dots don't turn into a gray haze
1835
+ while (gap < 10) gap *= 2
1836
+ return { gap, x: ((vp.value.x % gap) + gap) % gap, y: ((vp.value.y % gap) + gap) % gap, r: Math.max(0.6, Math.min(1.4, vp.value.zoom)) }
1837
+ })
1838
+
1839
+ // ── Context ───────────────────────────────────────────────────────────────────────────────────────────────
1840
+ const context: FlowInternals = {
1841
+ nodes: computed(() => nodesLocal.value),
1842
+ edges: computed(() => edgesLocal.value),
1843
+ viewport: vp,
1844
+ minZoom: computed(() => props.minZoom),
1845
+ maxZoom: computed(() => props.maxZoom),
1846
+ selection: computed(() => selLocal.value),
1847
+ size,
1848
+ locked,
1849
+ getNode,
1850
+ getAbsolutePosition,
1851
+ getSize,
1852
+ getIntersectingNodes,
1853
+ screenToFlow,
1854
+ flowToScreen,
1855
+ setViewport,
1856
+ fitView,
1857
+ setCenter,
1858
+ zoomIn,
1859
+ zoomOut,
1860
+ zoomTo,
1861
+ addNodes,
1862
+ addEdges,
1863
+ updateNode,
1864
+ updateEdge,
1865
+ remove,
1866
+ setSelection,
1867
+ layout: (fn, options) => runLayout(fn, options),
1868
+ undo,
1869
+ redo,
1870
+ canUndo,
1871
+ canRedo,
1872
+ copy,
1873
+ cut,
1874
+ paste,
1875
+ startDrag,
1876
+ registerHandle,
1877
+ measureNode: queueMeasure,
1878
+ startConnection,
1879
+ connectionTarget,
1880
+ connecting,
1881
+ insertEdge,
1882
+ branching,
1883
+ nodesConnectable,
1884
+ direction: computed(() => props.direction),
1885
+ // For the internal node shells and edges
1886
+ registerNodeEl,
1887
+ selectedNodes,
1888
+ selectedEdges,
1889
+ dragging,
1890
+ isLifted,
1891
+ zIndexOf,
1892
+ edgeGeometry,
1893
+ isReconnectable,
1894
+ sidePositions,
1895
+ onNodeKey,
1896
+ onEdgeKey,
1897
+ }
1898
+ provide(FLOW_KEY, context)
1899
+
1900
+ // ── Mount ─────────────────────────────────────────────────────────────────────────────────────────────────
1901
+ let ro: ResizeObserver | undefined
1902
+ onMounted(async () => {
1903
+ const el = root.value!
1904
+ el.addEventListener('wheel', onWheel, { passive: false })
1905
+ const sizeRo = new ResizeObserver(() => { size.value = { width: el.clientWidth, height: el.clientHeight } })
1906
+ sizeRo.observe(el)
1907
+ onBeforeUnmount(() => sizeRo.disconnect())
1908
+ size.value = { width: el.clientWidth, height: el.clientHeight }
1909
+ ro = new ResizeObserver((entries) => {
1910
+ for (const en of entries) {
1911
+ const id = (en.target as HTMLElement).dataset.flowNode
1912
+ if (id) measureNode(id)
1913
+ }
1914
+ })
1915
+ for (const [id, n] of nodeEls) { ro.observe(n); measureNode(id) }
1916
+ await nextTick()
1917
+ if (props.layout) await runLayout(null, undefined, { history: false })
1918
+ await nextTick()
1919
+ if (props.fitView) fitView({ animate: false })
1920
+ ready.value = true
1921
+ emit('init', context)
1922
+ })
1923
+ onBeforeUnmount(() => {
1924
+ root.value?.removeEventListener('wheel', onWheel)
1925
+ removeWindowListeners()
1926
+ ro?.disconnect()
1927
+ if (raf) cancelAnimationFrame(raf)
1928
+ clearTimeout(longPress)
1929
+ document.body.style.userSelect = ''
1930
+ })
1931
+
1932
+ defineExpose(context as FlowContext)
1933
+ </script>
1934
+
1935
+ <template>
1936
+ <div
1937
+ ref="root"
1938
+ v-bind="$attrs"
1939
+ class="m3-flow overflow-hidden bg-surface outline-none select-none"
1940
+ :class="[panning && 'cursor-grabbing', locked && 'm3-flow-locked']"
1941
+ tabindex="0"
1942
+ role="application"
1943
+ :aria-label="label ?? locale.flowCanvas"
1944
+ aria-roledescription="flow"
1945
+ @pointerdown="onPointerDown"
1946
+ @pointerenter="pointer.inside = true"
1947
+ @pointerleave="pointer.inside = false"
1948
+ @dblclick="onDblClick"
1949
+ @contextmenu="onContextMenu"
1950
+ @keydown="onKeyDown"
1951
+ >
1952
+ <svg v-if="background !== 'none'" class="pointer-events-none absolute inset-0 size-full" aria-hidden="true">
1953
+ <defs>
1954
+ <pattern :id="patternId" :x="pattern.x" :y="pattern.y" :width="pattern.gap" :height="pattern.gap" patternUnits="userSpaceOnUse">
1955
+ <circle v-if="background === 'dots'" :cx="pattern.r" :cy="pattern.r" :r="pattern.r" class="fill-outline-variant" />
1956
+ <path v-else :d="`M${pattern.gap} 0 L0 0 0 ${pattern.gap}`" fill="none" class="stroke-outline-variant" stroke-width="1" />
1957
+ </pattern>
1958
+ </defs>
1959
+ <rect width="100%" height="100%" :fill="`url(#${patternId})`" />
1960
+ </svg>
1961
+
1962
+ <div
1963
+ ref="layer"
1964
+ class="m3-flow-viewport absolute top-0 left-0 origin-top-left"
1965
+ :style="{ transform: `translate(${vp.x}px, ${vp.y}px) scale(${vp.zoom})`, visibility: ready ? undefined : 'hidden' }"
1966
+ >
1967
+ <NodeShell v-for="n in groupNodes" :key="n.id" :node="n" :render="nodeRenderer(n)" />
1968
+ <svg class="m3-flow-edges pointer-events-none absolute top-0 left-0 size-px overflow-visible" aria-hidden="false">
1969
+ <EdgeView v-for="e in visibleEdges" :key="e.id" :edge="e" :render="edgeRenderer(e)" />
1970
+ <path
1971
+ v-if="connection"
1972
+ class="m3-flow-connection-line fill-none stroke-primary"
1973
+ :d="connectionPath"
1974
+ stroke-width="2"
1975
+ :stroke-dasharray="connectionTarget?.valid ? undefined : '6 4'"
1976
+ />
1977
+ </svg>
1978
+ <div class="m3-flow-edge-labels absolute top-0 left-0">
1979
+ <template v-for="e in visibleEdges" :key="e.id">
1980
+ <EdgeLabel v-if="e.label || $slots['edge-label'] || selectedEdges.has(e.id)" :edge="e" :render="$slots['edge-label']" />
1981
+ </template>
1982
+ </div>
1983
+ <NodeShell v-for="n in plainNodes" :key="n.id" :node="n" :render="nodeRenderer(n)" />
1984
+ <svg v-if="guideLines.length" class="pointer-events-none absolute top-0 left-0 size-px overflow-visible" aria-hidden="true">
1985
+ <line
1986
+ v-for="(g, i) in guideLines"
1987
+ :key="i"
1988
+ class="stroke-primary"
1989
+ stroke-width="1"
1990
+ vector-effect="non-scaling-stroke"
1991
+ :x1="g.x ?? g.from"
1992
+ :x2="g.x ?? g.to"
1993
+ :y1="g.y ?? g.from"
1994
+ :y2="g.y ?? g.to"
1995
+ />
1996
+ </svg>
1997
+ </div>
1998
+
1999
+ <div
2000
+ v-if="marquee"
2001
+ class="m3-flow-marquee pointer-events-none absolute rounded-xs border border-primary bg-primary/8"
2002
+ :style="{ left: `${marquee.x}px`, top: `${marquee.y}px`, width: `${marquee.width}px`, height: `${marquee.height}px` }"
2003
+ />
2004
+
2005
+ <div v-if="!nodesLocal.length && $slots.empty" class="pointer-events-none absolute inset-0 flex items-center justify-center">
2006
+ <div class="pointer-events-auto">
2007
+ <slot name="empty" />
2008
+ </div>
2009
+ </div>
2010
+
2011
+ <slot :flow="context" />
2012
+
2013
+ <div class="sr-only" aria-live="polite">{{ announcement }}</div>
2014
+ </div>
2015
+ </template>
2016
+
2017
+ <style>
2018
+ @layer base {
2019
+ .m3-flow {
2020
+ position: relative;
2021
+ display: block;
2022
+ touch-action: none;
2023
+ }
2024
+ }
2025
+ .m3-flow-circle {
2026
+ transition: background-color 250ms cubic-bezier(0.2, 0, 0, 1), color 250ms cubic-bezier(0.2, 0, 0, 1), border-color 200ms, box-shadow 250ms cubic-bezier(0.2, 0, 0, 1);
2027
+ }
2028
+ .m3-flow-edge-line {
2029
+ transition: stroke 250ms cubic-bezier(0.2, 0, 0, 1), stroke-width 250ms cubic-bezier(0.2, 0, 0, 1), fill 250ms cubic-bezier(0.2, 0, 0, 1);
2030
+ }
2031
+ .m3-flow-edge-animated {
2032
+ stroke-dasharray: 6 4;
2033
+ animation: m3-flow-dash 400ms linear infinite;
2034
+ }
2035
+ .m3-flow-edge-reverse {
2036
+ animation-direction: reverse;
2037
+ }
2038
+ .m3-flow-edge-dashed {
2039
+ stroke-dasharray: 6 4;
2040
+ }
2041
+ @keyframes m3-flow-dash {
2042
+ from { stroke-dashoffset: 10; }
2043
+ to { stroke-dashoffset: 0; }
2044
+ }
2045
+ @media (prefers-reduced-motion: reduce) {
2046
+ .m3-flow-edge-animated { animation: none; }
2047
+ .m3-flow-edge-line { transition: none; }
2048
+ }
2049
+ </style>