@m3ui-vue/m3ui-vue 1.2.2 → 1.3.1

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