@m3ui-vue/m3ui-vue 1.3.3 → 1.3.4

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.
@@ -44,8 +44,16 @@ const emptySelection = (): FlowSelection => ({ nodes: [], edges: [] })
44
44
  * @slot empty Shown while there are no nodes
45
45
  * @event connect A connection was made (it's also added to `edges` with `autoConnect`)
46
46
  * @event connect-start A connection drag started from a handle
47
+ * @event branch A branch was dragged off an edge (edgeBranching) and dropped: `{ edge, connection, position, direction, end }`,
48
+ * the connection null when it was dropped on nothing, `position` the point on the edge where it was grabbed (on the
49
+ * grid along the edge with snapToGrid), `direction` the way the edge runs there toward its target, `end` where it was
50
+ * dropped, and for an edge with its own `route`, `routes` that keep each half's shape. With `'junction'` this is all
51
+ * that happens: split the edge with a node there whose handles are at `position="auto"`, the first half arriving with
52
+ * `targetPosition` opposite to `direction` and the second leaving with `sourcePosition: direction`, so it runs on
53
+ * straight through
47
54
  * @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
55
  * @event reconnect An edge's end was moved to another handle: `{ edge, connection }`
56
+ * @event reroute A segment of an edge was dragged (`edgesReroutable`): the edge with its new `route`
49
57
  * @event insert A lone node was dropped onto an edge and spliced in: `{ node, edge, connections }` (with `autoConnect`
50
58
  * the edge is replaced by the two connections, keeping its type and look)
51
59
  * @event node-click / node-dblclick / node-contextmenu `(node, event)`
@@ -63,6 +71,7 @@ import {
63
71
  type FlowConnection,
64
72
  type FlowContext,
65
73
  type FlowEdgeGeometry as EdgeGeometry,
74
+ type FlowEdgeHit,
66
75
  type FlowFitOptions,
67
76
  type FlowHandleBounds,
68
77
  type FlowInternals,
@@ -71,7 +80,7 @@ import {
71
80
  type FlowXY,
72
81
  } from '../composables/useFlow'
73
82
  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'
83
+ import { distanceToPoints, edgePathPoints, getBezierPath, getRoutedPath, getSmoothStepPath, getStepPath, getStraightPath, pointsToRoute, routePoints, smoothStepPoints, type FlowEdgePath } from '../composables/flowPaths'
75
84
  import { DEFAULT_SPATIAL } from '../composables/_useSpring'
76
85
  import { prefersReducedMotion } from '../composables/_springAnimation'
77
86
  import { useLocale } from '../composables/useLocale'
@@ -112,6 +121,11 @@ const props = withDefaults(defineProps<{
112
121
  nodesConnectable?: boolean
113
122
  elementsSelectable?: boolean
114
123
  edgesReconnectable?: boolean
124
+ /**
125
+ * The segments of a selected `smoothstep`/`step` edge get grips: drag one sideways to reroute the edge (it keeps
126
+ * the route in `edge.route`), or drag a leg at either end to add a jog. Default off
127
+ */
128
+ edgesReroutable?: boolean
115
129
  /** Merged into edges made by connecting (`type`, `animated`, `markerEnd`…) */
116
130
  defaultEdgeOptions?: Partial<FlowEdge>
117
131
  /** Adds an edge to `edges` when a connection is made; off, only `connect` fires */
@@ -150,9 +164,11 @@ const props = withDefaults(defineProps<{
150
164
  /**
151
165
  * A drag that starts on an edge draws a new edge from the same source, a branch, as in a circuit editor (the
152
166
  * 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
167
+ * branches, so a swipe across one still pans. `'junction'`: the branch leaves from the very point you grabbed,
168
+ * as in Logisim: nothing is added, `branch` fires with that point on the edge, and you split the edge there with a
169
+ * junction node of your own (or leave a loose end where it was dropped on nothing)
154
170
  */
155
- edgeBranching?: boolean
171
+ edgeBranching?: boolean | 'junction'
156
172
  /**
157
173
  * Let the browser's own context menu open on the canvas (right click, or a long press on a phone). Off by default:
158
174
  * the `*-contextmenu` events still fire, for a menu of your own (MContextMenu's `showAt`). Text fields inside
@@ -182,6 +198,7 @@ const props = withDefaults(defineProps<{
182
198
  nodesConnectable: true,
183
199
  elementsSelectable: true,
184
200
  edgesReconnectable: true,
201
+ edgesReroutable: false,
185
202
  autoConnect: true,
186
203
  connectionRadius: 24,
187
204
  deleteKeys: () => ['Delete', 'Backspace'],
@@ -204,8 +221,10 @@ const emit = defineEmits<{
204
221
  'update:locked': [boolean]
205
222
  connect: [FlowConnection]
206
223
  'connect-start': [{ nodeId: string; handleId: string | null; type: 'source' | 'target' }]
224
+ branch: [{ edge: FlowEdge; connection: FlowConnection | null; position: FlowXY; direction: FlowPosition; end: FlowXY; routes?: { before: number[]; after: number[] } }]
207
225
  'connect-end': [{ connection: FlowConnection | null; position: FlowXY; from: { nodeId: string; handleId: string | null; type: 'source' | 'target' } }]
208
226
  reconnect: [{ edge: FlowEdge; connection: FlowConnection }]
227
+ reroute: [edge: FlowEdge]
209
228
  insert: [{ node: FlowNode; edge: FlowEdge; connections: [FlowConnection, FlowConnection] }]
210
229
  'node-click': [FlowNode, MouseEvent]
211
230
  'node-dblclick': [FlowNode, MouseEvent]
@@ -286,7 +305,7 @@ function descendants(id: string): string[] {
286
305
  const selectedNodes = computed(() => new Set(selLocal.value.nodes))
287
306
  const selectedEdges = computed(() => new Set(selLocal.value.edges))
288
307
  // Edges branch when dragged (edgeBranching)
289
- const branching = computed(() => props.edgeBranching && nodesConnectable.value && !locked.value)
308
+ const branching = computed(() => !!props.edgeBranching && nodesConnectable.value && !locked.value)
290
309
  function setSelection(s: Partial<FlowSelection>) {
291
310
  const next = { nodes: s.nodes ?? selLocal.value.nodes, edges: s.edges ?? selLocal.value.edges }
292
311
  if (sameIds(next.nodes, selLocal.value.nodes) && sameIds(next.edges, selLocal.value.edges)) return
@@ -585,7 +604,19 @@ function sidePoint(id: string, pos: FlowPosition): FlowXY {
585
604
  default: return { x: a.x + s.width, y: a.y + s.height / 2 }
586
605
  }
587
606
  }
588
- function handlePoint(nodeId: string, type: 'source' | 'target', handleId?: string | null): { x: number; y: number; position: FlowPosition; inset: number } | null {
607
+ // The side an 'auto' handle uses for an edge: the one facing its other end
608
+ function sideToward(from: FlowXY, to: FlowXY): FlowPosition {
609
+ const dx = to.x - from.x
610
+ const dy = to.y - from.y
611
+ return Math.abs(dx) >= Math.abs(dy) ? (dx >= 0 ? 'right' : 'left') : dy >= 0 ? 'bottom' : 'top'
612
+ }
613
+ const resolveSide = (side: FlowPosition | 'auto', at: FlowXY, toward: FlowXY | null, type: 'source' | 'target'): FlowPosition =>
614
+ side !== 'auto' ? side : toward ? sideToward(at, toward) : type === 'source' ? 'right' : 'left'
615
+ function handlePoint(nodeId: string, type: 'source' | 'target', handleId?: string | null, toward: FlowXY | null = null): { x: number; y: number; position: FlowPosition; inset: number } | null {
616
+ const raw = rawHandlePoint(nodeId, type, handleId)
617
+ return raw && { ...raw, position: resolveSide(raw.position, raw, toward, type) }
618
+ }
619
+ function rawHandlePoint(nodeId: string, type: 'source' | 'target', handleId?: string | null): { x: number; y: number; position: FlowPosition | 'auto'; inset: number } | null {
589
620
  const n = nodeById.value.get(nodeId)
590
621
  if (!n) return null
591
622
  const list = handles.get(nodeId)?.filter((h) => h.type === type)
@@ -646,14 +677,52 @@ function circleGeometry(e: FlowEdge): EdgeGeometry | null {
646
677
  }
647
678
  return { ...ends, ...pathFor(e.type ?? props.defaultEdgeOptions?.type ?? 'straight', ends), sourceInset: 0, targetInset: 0 }
648
679
  }
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 }
680
+ const isCircleEdge = (e: FlowEdge) => nodeById.value.get(e.source)?.type === 'circle' || nodeById.value.get(e.target)?.type === 'circle'
681
+ const isOrthogonal = (e: FlowEdge) => !isCircleEdge(e) && (edgeRoute(e) === 'smoothstep' || edgeRoute(e) === 'step')
682
+ // The route an edge runs: the one being dragged, else its own (orthogonal edges only)
683
+ function routeOf(e: FlowEdge) {
684
+ if (rerouting.value?.id === e.id) return rerouting.value.route
685
+ if (!e.route) return undefined
686
+ // Both ends being dragged: the route comes along
687
+ if (isLifted(e.source) && isLifted(e.target)) {
688
+ const d = disp.get(e.source)
689
+ const n = nodeById.value.get(e.source)
690
+ if (d && n && (d.x !== n.position.x || d.y !== n.position.y)) return shiftRoute(e, d.x - n.position.x, d.y - n.position.y)
691
+ }
692
+ return e.route
693
+ }
694
+ /** An edge's route moved by (dx, dy): its x's by dx and its y's by dy */
695
+ function shiftRoute(e: FlowEdge, dx: number, dy: number) {
696
+ const s = edgeEnds(e)?.s
697
+ const startX = !s || s.position === 'left' || s.position === 'right'
698
+ return e.route!.map((v, i) => v + ((i % 2 === 0) === startX ? dx : dy))
699
+ }
700
+ function edgeEnds(e: FlowEdge) {
701
+ const s0 = rawHandlePoint(e.source, 'source', e.sourceHandle)
702
+ const t0 = rawHandlePoint(e.target, 'target', e.targetHandle)
703
+ if (!s0 || !t0) return null
704
+ // An 'auto' handle: the side the edge asks for, else the one facing its other end
705
+ const s = { ...s0, position: s0.position === 'auto' && e.sourcePosition ? e.sourcePosition : resolveSide(s0.position, s0, t0, 'source') }
706
+ const t = { ...t0, position: t0.position === 'auto' && e.targetPosition ? e.targetPosition : resolveSide(t0.position, t0, s0, 'target') }
707
+ return { s, t, ends: { sourceX: s.x, sourceY: s.y, sourcePosition: s.position, targetX: t.x, targetY: t.y, targetPosition: t.position } }
656
708
  }
709
+ function edgeGeometry(e: FlowEdge): EdgeGeometry | null {
710
+ if (isCircleEdge(e)) return circleGeometry(e)
711
+ const at = edgeEnds(e)
712
+ if (!at) return null
713
+ const { s, t, ends } = at
714
+ const route = isOrthogonal(e) ? routeOf(e) : undefined
715
+ const path = route ? getRoutedPath({ ...ends, route, borderRadius: edgeRoute(e) === 'step' ? 0 : 8 }) : pathFor(edgeRoute(e), ends)
716
+ return { ...ends, ...path, sourceInset: s.inset, targetInset: t.inset }
717
+ }
718
+ function edgeCorners(e: FlowEdge): [number, number][] | null {
719
+ if (!isOrthogonal(e)) return null
720
+ const at = edgeEnds(e)
721
+ if (!at) return null
722
+ const route = routeOf(e)
723
+ return route ? routePoints({ ...at.ends, route }) : smoothStepPoints(at.ends)
724
+ }
725
+ const isReroutable = (e: FlowEdge) => !locked.value && isOrthogonal(e) && (e.reroutable ?? props.edgesReroutable)
657
726
 
658
727
  // What's drawn: groups under the edges, other nodes over them; children over their parents
659
728
  const visibleNodes = computed(() => nodesLocal.value.filter((n) => !isHidden(n.id)))
@@ -783,6 +852,10 @@ function addNodes(ns: FlowNode | FlowNode[]) {
783
852
  function addEdges(es: FlowEdge | FlowEdge[]) {
784
853
  commit({ edges: [...edgesLocal.value, ...asArray(es)] })
785
854
  }
855
+ /** Several changes as one undoable step: each list given replaces the current one */
856
+ function change(next: { nodes?: FlowNode[]; edges?: FlowEdge[] }) {
857
+ commit({ nodes: next.nodes, edges: next.edges })
858
+ }
786
859
  function updateNode(id: string, patch: Partial<FlowNode> | ((n: FlowNode) => FlowNode)) {
787
860
  commit({ nodes: nodesLocal.value.map((n) => (n.id !== id ? n : typeof patch === 'function' ? patch(n) : { ...n, ...patch })) })
788
861
  }
@@ -920,8 +993,9 @@ const NO_DRAG = 'input, textarea, select, button, a, label, [contenteditable], [
920
993
  type Gesture =
921
994
  | { kind: 'pan'; id: number; sx: number; sy: number; vx: number; vy: number; moved: boolean; target: 'pane'; touch?: boolean; branch?: FlowEdge }
922
995
  | { 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 }
996
+ | { kind: 'node'; id: number; nodeId: string; sx: number; sy: number; touch: boolean; active: boolean; starts: Map<string, FlowXY>; moved: boolean; reselect: boolean; select?: () => void }
997
+ | { kind: 'connect'; id: number; from: { nodeId: string; handleId: string | null; type: 'source' | 'target' }; reconnect?: { edge: FlowEdge; end: 'source' | 'target' }; branch?: { edge: FlowEdge; at: FlowXY; direction: FlowPosition; segment: number }; tap?: { x: number; y: number; touch: boolean; nodeId: string }; moved: boolean }
998
+ | { kind: 'reroute'; id: number; edge: FlowEdge; segment: number; corners: [number, number][]; sx: number; sy: number; moved: boolean }
925
999
  | { kind: 'pinch' }
926
1000
  let gesture: Gesture | null = null
927
1001
  // What the gesture's pointerdown landed on: a click is resolved against it, not the pointerup's target
@@ -931,11 +1005,13 @@ let pinch: { dist: number; cx: number; cy: number; zoom: number; fx: number; fy:
931
1005
  const pointer = { x: 0, y: 0, inside: false }
932
1006
 
933
1007
  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)
1008
+ const connection = shallowRef<{ from: { x: number; y: number; position: FlowPosition | 'auto' }; to: FlowXY; toPosition: FlowPosition | 'auto' | null; type: 'source' | 'target'; edgeType: string } | null>(null)
935
1009
  const connectionTarget = ref<{ key: string; valid: boolean } | null>(null)
936
1010
  const connecting = computed(() => !!connection.value)
937
1011
  const guideLines = shallowRef<{ x?: number; y?: number; from: number; to: number }[]>([])
938
1012
  const panning = ref(false)
1013
+ /** The route of the edge whose segment is being dragged, until it's dropped */
1014
+ const rerouting = shallowRef<{ id: string; route: number[] } | null>(null)
939
1015
 
940
1016
  function addWindowListeners() {
941
1017
  window.addEventListener('pointermove', onWindowMove)
@@ -998,6 +1074,18 @@ function onPointerDown(e: PointerEvent) {
998
1074
  remove({ edges: [deleteButton.dataset.flowEdgeDelete!] })
999
1075
  return
1000
1076
  }
1077
+ const segment = t.closest<HTMLElement>('[data-flow-segment]')
1078
+ if (segment && edgeEl) {
1079
+ const edge = edgeById.value.get(edgeEl.dataset.flowEdge!)
1080
+ const corners = edge && isReroutable(edge) ? edgeCorners(edge) : null
1081
+ if (edge && corners) {
1082
+ e.preventDefault()
1083
+ gesture = { kind: 'reroute', id: e.pointerId, edge, segment: Number(segment.dataset.flowSegment), corners, sx: e.clientX, sy: e.clientY, moved: false }
1084
+ addWindowListeners()
1085
+ if (e.pointerType === 'touch') blockTouchScroll(null)
1086
+ return
1087
+ }
1088
+ }
1001
1089
  if (reconnect && edgeEl) {
1002
1090
  const edge = edgeById.value.get(edgeEl.dataset.flowEdge!)
1003
1091
  if (edge && isReconnectable(edge)) {
@@ -1014,7 +1102,13 @@ function onPointerDown(e: PointerEvent) {
1014
1102
  const hid = handle.dataset.handleId || null
1015
1103
  const attached = visibleEdges.value.filter((ed) => ed.target === nodeId && (ed.targetHandle ?? null) === hid && isReconnectable(ed))
1016
1104
  const edge = attached[attached.length - 1]
1017
- if (edge) return startReconnect(e, edge, 'target')
1105
+ if (edge) {
1106
+ startReconnect(e, edge, 'target')
1107
+ // Tapped, not pulled: it selects the node like a tap on any other handle
1108
+ const g = gesture as Gesture | null
1109
+ if (g?.kind === 'connect') g.tap = { x: e.clientX, y: e.clientY, touch: e.pointerType === 'touch', nodeId }
1110
+ return
1111
+ }
1018
1112
  }
1019
1113
  return startConnection(e, nodeEl.dataset.flowNode!, handle.dataset.handleId || null, handle.dataset.flowHandle as 'source' | 'target')
1020
1114
  }
@@ -1069,16 +1163,20 @@ function startNode(e: PointerEvent, nodeId: string) {
1069
1163
  const n = nodeById.value.get(nodeId)
1070
1164
  if (!n) return
1071
1165
  let reselect = false
1166
+ let select: (() => void) | undefined
1072
1167
  if (canSelect.value && n.selectable !== false) {
1073
1168
  if (e.shiftKey || e.metaKey || e.ctrlKey) {
1074
1169
  const has = selectedNodes.value.has(nodeId)
1075
1170
  setSelection({ nodes: has ? selLocal.value.nodes.filter((i) => i !== nodeId) : [...selLocal.value.nodes, nodeId] })
1076
1171
  if (has) return
1077
1172
  } else if (!selectedNodes.value.has(nodeId)) {
1078
- setSelection({ nodes: [nodeId], edges: [] })
1173
+ select = () => setSelection({ nodes: [nodeId], edges: [] })
1079
1174
  } else reselect = true
1080
1175
  }
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 }
1176
+ const touch = e.pointerType === 'touch'
1177
+ // A finger waits for the drag or the tap to select: it may be the first of a pinch, which shouldn't select
1178
+ if (select && !touch) select()
1179
+ gesture = { kind: 'node', id: e.pointerId, nodeId, sx: e.clientX, sy: e.clientY, touch, active: false, starts: new Map(), moved: false, reselect, select: touch ? select : undefined }
1082
1180
  addWindowListeners()
1083
1181
  }
1084
1182
 
@@ -1125,9 +1223,48 @@ function onWindowMove(e: PointerEvent) {
1125
1223
  g.moved = true
1126
1224
  moveConnection(g, e.clientX, e.clientY)
1127
1225
  kick()
1226
+ } else if (g.kind === 'reroute') {
1227
+ if (!g.moved && Math.hypot(e.clientX - g.sx, e.clientY - g.sy) < (e.pointerType === 'touch' ? DRAG_SLOP_TOUCH : DRAG_SLOP_MOUSE)) return
1228
+ g.moved = true
1229
+ rerouting.value = { id: g.edge.id, route: rerouted(g, e) }
1128
1230
  }
1129
1231
  }
1130
1232
 
1233
+ // A segment dragged sideways: its two corners move with it. A leg at an end can't leave its handle, so it gets a
1234
+ // jog instead: it turns a grid step from the handle, runs where the pointer is, and comes back
1235
+ function rerouted(g: Extract<Gesture, { kind: 'reroute' }>, e: PointerEvent): number[] {
1236
+ const pts = g.corners.map((p) => [p[0], p[1]] as [number, number])
1237
+ const k = g.segment
1238
+ const a = pts[k]!
1239
+ const b = pts[k + 1]!
1240
+ const horizontal = Math.abs(a[1] - b[1]) < 0.01
1241
+ const axis: 0 | 1 = horizontal ? 1 : 0
1242
+ const step = props.gridSize || 20
1243
+ const snap = (v: number) => (props.snapToGrid ? Math.round(v / step) * step : Math.round(v))
1244
+ const delta = ((horizontal ? e.clientY - g.sy : e.clientX - g.sx) / vp.value.zoom)
1245
+ const to = snap(a[axis] + delta)
1246
+ const first = k === 0
1247
+ const last = k === pts.length - 2
1248
+ const along: 0 | 1 = axis === 1 ? 0 : 1
1249
+ const dir = Math.sign(b[along] - a[along]) || 1
1250
+ const len = Math.abs(b[along] - a[along])
1251
+ const room = Math.min(step, len / 3)
1252
+ const at = (p: [number, number], v: number): [number, number] => (axis === 1 ? [p[0], v] : [v, p[1]])
1253
+ const off = (p: [number, number], d: number): [number, number] => (along === 0 ? [p[0] + d, p[1]] : [p[0], p[1] + d])
1254
+ const inner: [number, number][] = []
1255
+ if (first) {
1256
+ const j = off(a, dir * room)
1257
+ inner.push(j, at(j, to))
1258
+ } else inner.push(at(a, to))
1259
+ if (last) {
1260
+ const j = off(b, -dir * room)
1261
+ inner.push(at(j, to), j)
1262
+ } else inner.push(at(b, to))
1263
+ const next = [...pts.slice(0, first ? 1 : k), ...inner, ...pts.slice(last ? k + 1 : k + 2)]
1264
+ const ends = edgeEnds(g.edge)
1265
+ return pointsToRoute(next, ends?.s.position, ends?.t.position)
1266
+ }
1267
+
1131
1268
  function onWindowUp(e: PointerEvent) {
1132
1269
  touches.delete(e.pointerId)
1133
1270
  if (pinch) {
@@ -1148,12 +1285,23 @@ function onWindowUp(e: PointerEvent) {
1148
1285
  } else if (g.kind === 'node') {
1149
1286
  if (g.active) endNodeDrag(g, e)
1150
1287
  else {
1288
+ g.select?.()
1151
1289
  if (g.reselect && !e.shiftKey) setSelection({ nodes: [g.nodeId], edges: [] })
1152
1290
  const n = nodeById.value.get(g.nodeId)
1153
1291
  if (n) emit('node-click', n, e)
1154
1292
  }
1155
1293
  } else if (g.kind === 'connect') {
1156
1294
  endConnection(g, e)
1295
+ } else if (g.kind === 'reroute') {
1296
+ const r = rerouting.value
1297
+ rerouting.value = null
1298
+ if (g.moved && r) {
1299
+ const edge = edgeById.value.get(g.edge.id)
1300
+ if (edge) {
1301
+ updateEdge(edge.id, { route: r.route })
1302
+ emit('reroute', { ...edge, route: r.route })
1303
+ }
1304
+ }
1157
1305
  }
1158
1306
  }
1159
1307
  function onWindowCancel(e: PointerEvent) {
@@ -1188,6 +1336,7 @@ function cancelGesture() {
1188
1336
  connection.value = null
1189
1337
  connectionTarget.value = null
1190
1338
  }
1339
+ if (g?.kind === 'reroute') rerouting.value = null
1191
1340
  }
1192
1341
 
1193
1342
  // What the click (a pointerup that didn't move) landed on
@@ -1316,6 +1465,8 @@ function updateMarquee(g: Extract<Gesture, { kind: 'marquee' }>) {
1316
1465
 
1317
1466
  // ── Dragging nodes ────────────────────────────────────────────────────────────────────────────────────────
1318
1467
  function beginNodeDrag(g: Extract<Gesture, { kind: 'node' }>, e: PointerEvent) {
1468
+ g.select?.()
1469
+ g.select = undefined
1319
1470
  const sel = selectedNodes.value.has(g.nodeId) ? selLocal.value.nodes : [g.nodeId]
1320
1471
  // A node whose group moves too comes along by itself
1321
1472
  const ids = sel.filter((id) => {
@@ -1367,8 +1518,9 @@ function moveNodes(g: Extract<Gesture, { kind: 'node' }>, cx: number, cy: number
1367
1518
  const leadId = g.starts.has(g.nodeId) ? g.nodeId : [...g.starts.keys()][0]!
1368
1519
  if (props.snapToGrid) {
1369
1520
  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
1521
+ const off = nodeById.value.get(leadId)?.gridOffset ?? { x: 0, y: 0 }
1522
+ dx = Math.round((lead.x + off.x + dx) / gs) * gs - lead.x - off.x
1523
+ dy = Math.round((lead.y + off.y + dy) / gs) * gs - lead.y - off.y
1372
1524
  guideLines.value = []
1373
1525
  } else if (props.guides && g.starts.size === 1) {
1374
1526
  const snapped = snapToGuides(leadId, lead, dx, dy)
@@ -1490,7 +1642,7 @@ function findInsert(g: Extract<Gesture, { kind: 'node' }>): typeof insertPlan {
1490
1642
  if (e.deletable === false) continue
1491
1643
  const geo = edgeGeometry(e)
1492
1644
  if (!geo) continue
1493
- const d = distanceToPoints(cx, cy, edgePathPoints(edgeType(e), geo))
1645
+ const d = distanceToPoints(cx, cy, edgeCorners(e) ?? edgePathPoints(edgeRoute(e), geo))
1494
1646
  if (d <= reach && (!best || d < best.d)) best = { edge: e, d }
1495
1647
  }
1496
1648
  if (!best) return null
@@ -1603,9 +1755,16 @@ function endNodeDrag(g: Extract<Gesture, { kind: 'node' }>, e: PointerEvent) {
1603
1755
  })
1604
1756
  // Spliced in without room: it moves to sit after A, and C with everything after it moves on to make room
1605
1757
  const placed = spliced && plan ? makeRoom(nodes, plan) : nodes
1758
+ // Routes between two moved nodes move with them
1759
+ const p0 = g.starts.get(g.nodeId)
1760
+ const s0 = springs.get(g.nodeId)
1761
+ let edges = spliced ? [...edgesLocal.value.filter((x) => x !== plan!.edge), ...spliced] : undefined
1762
+ if (p0 && s0 && !reparent.size && (s0.tx !== p0.x || s0.ty !== p0.y) && edgesLocal.value.some((x) => x.route && movedSet.has(x.source) && movedSet.has(x.target))) {
1763
+ edges = (edges ?? edgesLocal.value).map((x) => (x.route && movedSet.has(x.source) && movedSet.has(x.target) ? { ...x, route: shiftRoute(x, s0.tx - p0.x, s0.ty - p0.y) } : x))
1764
+ }
1606
1765
  // Let go first, so the spliced node springs to its place too
1607
1766
  if (spliced) dragging.value = new Set()
1608
- commit({ nodes: placed, edges: spliced ? [...edgesLocal.value.filter((x) => x !== plan!.edge), ...spliced] : undefined })
1767
+ commit({ nodes: placed, edges })
1609
1768
  const first = nodeById.value.get(g.nodeId)
1610
1769
  if (first) announce(locale.flowMoved.replace('{label}', nodeLabel(first)))
1611
1770
  }
@@ -1642,9 +1801,9 @@ function autoPan(dt: number) {
1642
1801
 
1643
1802
  // ── Connecting ────────────────────────────────────────────────────────────────────────────────────────────
1644
1803
  function startConnection(e: PointerEvent, nodeId: string, handleId: string | null, type: 'source' | 'target') {
1645
- const from = handlePoint(nodeId, type, handleId)
1804
+ const from = rawHandlePoint(nodeId, type, handleId)
1646
1805
  if (!from) return
1647
- gesture = { kind: 'connect', id: e.pointerId, from: { nodeId, handleId, type }, moved: false }
1806
+ gesture = { kind: 'connect', id: e.pointerId, from: { nodeId, handleId, type }, tap: { x: e.clientX, y: e.clientY, touch: e.pointerType === 'touch', nodeId }, moved: false }
1648
1807
  connection.value = { from, to: { x: from.x, y: from.y }, toPosition: null, type, edgeType: edgeRoute({ ...props.defaultEdgeOptions }) }
1649
1808
  pointer.x = e.clientX
1650
1809
  pointer.y = e.clientY
@@ -1653,21 +1812,78 @@ function startConnection(e: PointerEvent, nodeId: string, handleId: string | nul
1653
1812
  }
1654
1813
  // A branch: a new connection from the edge's source, its preview leaving from where the edge was grabbed
1655
1814
  function startBranch(pan: { id: number; sx: number; sy: number }, edge: FlowEdge, e: PointerEvent) {
1656
- const src = handlePoint(edge.source, 'source', edge.sourceHandle)
1815
+ const src = rawHandlePoint(edge.source, 'source', edge.sourceHandle)
1657
1816
  if (!src) return
1658
1817
  const handleId = edge.sourceHandle ?? null
1659
- const g: Gesture = { kind: 'connect', id: pan.id, from: { nodeId: edge.source, handleId, type: 'source' }, moved: true }
1818
+ const { direction, segment, ...at } = pointOnEdge(edge, screenToFlow({ x: pan.sx, y: pan.sy }))
1819
+ const g: Gesture = { kind: 'connect', id: pan.id, from: { nodeId: edge.source, handleId, type: 'source' }, branch: { edge, at, direction, segment }, moved: true }
1660
1820
  gesture = g
1661
- const at = screenToFlow({ x: pan.sx, y: pan.sy })
1662
1821
  connection.value = { from: { x: at.x, y: at.y, position: src.position }, to: at, toPosition: null, type: 'source', edgeType: edgeRoute(edge) }
1663
1822
  emit('connect-start', { nodeId: edge.source, handleId, type: 'source' })
1664
1823
  moveConnection(g, e.clientX, e.clientY)
1665
1824
  kick()
1666
1825
  }
1826
+ // The point of an edge nearest to p; with snapToGrid, on the grid along the segment it falls on (so it stays on the edge)
1827
+ function pointOnEdge(edge: FlowEdge, p: FlowXY): FlowXY & { direction: FlowPosition; segment: number } {
1828
+ const geo = edgeGeometry(edge)
1829
+ if (!geo) return { ...p, direction: 'right', segment: 0 }
1830
+ const pts = edgeCorners(edge) ?? edgePathPoints(edgeRoute(edge), geo)
1831
+ let best = { x: p.x, y: p.y, d: Infinity, a: pts[0]!, b: pts[0]!, i: 0 }
1832
+ for (let i = 1; i < pts.length; i++) {
1833
+ const [ax, ay] = pts[i - 1]!
1834
+ const [bx, by] = pts[i]!
1835
+ const dx = bx - ax
1836
+ const dy = by - ay
1837
+ const len = dx * dx + dy * dy
1838
+ const t = len ? Math.max(0, Math.min(1, ((p.x - ax) * dx + (p.y - ay) * dy) / len)) : 0
1839
+ const x = ax + t * dx
1840
+ const y = ay + t * dy
1841
+ const d = Math.hypot(x - p.x, y - p.y)
1842
+ if (d < best.d) best = { x, y, d, a: pts[i - 1]!, b: pts[i]!, i: i - 1 }
1843
+ }
1844
+ let { x, y } = best
1845
+ const step = props.gridSize || 20
1846
+ if (props.snapToGrid) {
1847
+ const clamp = (v: number, u: number, w: number) => Math.max(Math.min(u, w), Math.min(Math.max(u, w), v))
1848
+ if (Math.abs(best.a[1] - best.b[1]) < 0.01) x = clamp(Math.round(x / step) * step, best.a[0], best.b[0])
1849
+ else if (Math.abs(best.a[0] - best.b[0]) < 0.01) y = clamp(Math.round(y / step) * step, best.a[1], best.b[1])
1850
+ }
1851
+ const dx = best.b[0] - best.a[0]
1852
+ const dy = best.b[1] - best.a[1]
1853
+ const direction: FlowPosition = Math.abs(dx) >= Math.abs(dy) ? (dx >= 0 ? 'right' : 'left') : dy >= 0 ? 'bottom' : 'top'
1854
+ return { x, y, direction, segment: best.i }
1855
+ }
1856
+ function getEdgeAt(p: FlowXY, opts: { radius?: number; ignore?: (e: FlowEdge) => boolean } = {}): FlowEdgeHit | null {
1857
+ const radius = opts.radius ?? 8
1858
+ let best: { edge: FlowEdge; d: number } | null = null
1859
+ for (const e of visibleEdges.value) {
1860
+ if (opts.ignore?.(e)) continue
1861
+ const geo = edgeGeometry(e)
1862
+ if (!geo) continue
1863
+ const d = distanceToPoints(p.x, p.y, edgeCorners(e) ?? edgePathPoints(edgeRoute(e), geo))
1864
+ if (d <= radius && (!best || d < best.d)) best = { edge: e, d }
1865
+ }
1866
+ if (!best) return null
1867
+ const { direction, segment, ...position } = pointOnEdge(best.edge, p)
1868
+ return { edge: best.edge, position, direction, routes: splitRoute(best.edge, position, segment, direction) }
1869
+ }
1870
+ // An orthogonal edge's own route cut at a point of its segment `k`: the routes that keep each half's shape
1871
+ function splitRoute(edge: FlowEdge, at: FlowXY, k: number, direction: FlowPosition) {
1872
+ const corners = edgeCorners(edge)
1873
+ const ends = edgeEnds(edge)
1874
+ if (!corners || !ends || !edge.route) return undefined
1875
+ const p: [number, number] = [at.x, at.y]
1876
+ const back = OPPOSITE[direction]
1877
+ return {
1878
+ before: pointsToRoute([...corners.slice(0, k + 1), p], ends.s.position, back),
1879
+ after: pointsToRoute([p, ...corners.slice(k + 1)], direction, ends.t.position),
1880
+ }
1881
+ }
1882
+ const OPPOSITE: Record<FlowPosition, FlowPosition> = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }
1667
1883
  function startReconnect(e: PointerEvent, edge: FlowEdge, end: 'source' | 'target') {
1668
1884
  // Dragging the target end: the connection runs from the source, and the other way round
1669
1885
  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)
1886
+ const from = rawHandlePoint(fixed.nodeId, fixed.type, fixed.handleId)
1671
1887
  if (!from) return
1672
1888
  gesture = { kind: 'connect', id: e.pointerId, from: fixed, reconnect: { edge, end }, moved: false }
1673
1889
  const to = screenToFlow({ x: e.clientX, y: e.clientY })
@@ -1693,7 +1909,7 @@ function moveConnection(g: Extract<Gesture, { kind: 'connect' }>, cx: number, cy
1693
1909
  const p = screenToFlow({ x: cx, y: cy })
1694
1910
  const want = g.from.type === 'source' ? 'target' : 'source'
1695
1911
  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
1912
+ let best: { nodeId: string; h: FlowHandleBounds | null; d: number; x: number; y: number; position: FlowPosition | 'auto' } | null = null
1697
1913
  for (const n of visibleNodes.value) {
1698
1914
  if (n.connectable === false) continue
1699
1915
  const a = getAbsolutePosition(n.id)
@@ -1736,18 +1952,32 @@ function endConnection(g: Extract<Gesture, { kind: 'connect' }>, e: PointerEvent
1736
1952
  connection.value = null
1737
1953
  connectionTarget.value = null
1738
1954
  const position = screenToFlow({ x: e.clientX, y: e.clientY })
1955
+ // A tap on a handle (no drag) selects its node, as a tap anywhere else on it would
1956
+ const t = g.tap
1957
+ if (t && Math.hypot(e.clientX - t.x, e.clientY - t.y) < (t.touch ? DRAG_SLOP_TOUCH : DRAG_SLOP_MOUSE)) {
1958
+ const n = nodeById.value.get(t.nodeId)
1959
+ if (n && canSelect.value && n.selectable !== false) setSelection({ nodes: [n.id], edges: [] })
1960
+ if (n) emit('node-click', n, e)
1961
+ emit('connect-end', { connection: null, position, from: g.from })
1962
+ return
1963
+ }
1739
1964
  const c = cand?.valid ? connectionFor(g.from, cand.nodeId, cand.handleId) : null
1740
1965
  if (g.reconnect) {
1741
1966
  const edge = g.reconnect.edge
1742
1967
  if (c) {
1743
1968
  emit('reconnect', { edge, connection: c })
1744
- if (props.autoConnect) updateEdge(edge.id, { source: c.source, target: c.target, sourceHandle: c.sourceHandle, targetHandle: c.targetHandle })
1969
+ if (props.autoConnect) updateEdge(edge.id, { source: c.source, target: c.target, sourceHandle: c.sourceHandle, targetHandle: c.targetHandle, route: undefined, [g.reconnect.end === 'source' ? 'sourcePosition' : 'targetPosition']: undefined })
1745
1970
  } else if (g.moved && !cand && edge.deletable !== false) {
1746
1971
  // Pulled off and dropped on nothing: disconnected (dropped on a handle it can't join, it stays)
1747
1972
  remove({ edges: [edge.id] })
1748
1973
  }
1749
1974
  return
1750
1975
  }
1976
+ if (g.branch) {
1977
+ const b = g.branch
1978
+ emit('branch', { edge: b.edge, connection: c, position: b.at, direction: b.direction, end: position, routes: splitRoute(b.edge, b.at, b.segment, b.direction) })
1979
+ if (props.edgeBranching === 'junction') return
1980
+ }
1751
1981
  if (c) {
1752
1982
  emit('connect', c)
1753
1983
  if (props.autoConnect) {
@@ -1764,10 +1994,11 @@ const connectionPath = computed(() => {
1764
1994
  if (!c) return ''
1765
1995
  const flip = c.type === 'target'
1766
1996
  const opposite: Record<FlowPosition, FlowPosition> = { top: 'bottom', bottom: 'top', left: 'right', right: 'left' }
1767
- const toPos = c.toPosition ?? opposite[c.from.position]
1997
+ const fromPos = resolveSide(c.from.position, c.from, c.to, c.type)
1998
+ const toPos = c.toPosition && c.toPosition !== 'auto' ? c.toPosition : c.toPosition === 'auto' ? sideToward(c.to, c.from) : opposite[fromPos]
1768
1999
  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 }
2000
+ ? { sourceX: c.to.x, sourceY: c.to.y, sourcePosition: toPos, targetX: c.from.x, targetY: c.from.y, targetPosition: fromPos }
2001
+ : { sourceX: c.from.x, sourceY: c.from.y, sourcePosition: fromPos, targetX: c.to.x, targetY: c.to.y, targetPosition: toPos }
1771
2002
  return pathFor(c.edgeType, ends).path
1772
2003
  })
1773
2004
 
@@ -1859,6 +2090,7 @@ const context: FlowInternals = {
1859
2090
  getAbsolutePosition,
1860
2091
  getSize,
1861
2092
  getIntersectingNodes,
2093
+ getEdgeAt,
1862
2094
  screenToFlow,
1863
2095
  flowToScreen,
1864
2096
  setViewport,
@@ -1868,6 +2100,7 @@ const context: FlowInternals = {
1868
2100
  zoomOut,
1869
2101
  zoomTo,
1870
2102
  addNodes,
2103
+ change,
1871
2104
  addEdges,
1872
2105
  updateNode,
1873
2106
  updateEdge,
@@ -1900,6 +2133,8 @@ const context: FlowInternals = {
1900
2133
  zIndexOf,
1901
2134
  edgeGeometry,
1902
2135
  isReconnectable,
2136
+ isReroutable,
2137
+ edgeCorners,
1903
2138
  sidePositions,
1904
2139
  onNodeKey,
1905
2140
  onEdgeKey,
@@ -10,7 +10,8 @@ import { FLOW_KEY, FLOW_NODE_KEY, type FlowPosition } from '../composables/useFl
10
10
  const props = withDefaults(defineProps<{
11
11
  /** `source`: edges leave from it; `target`: they arrive */
12
12
  type?: 'source' | 'target'
13
- position?: FlowPosition
13
+ /** Its side; `'auto'` sits in the node's middle (or where you put it) and each edge leaves or arrives on the side facing its other end */
14
+ position?: FlowPosition | 'auto'
14
15
  id?: string
15
16
  connectable?: boolean
16
17
  }>(), {
@@ -23,12 +24,13 @@ const props = withDefaults(defineProps<{
23
24
  const flow = inject(FLOW_KEY, null)
24
25
  const state = inject(FLOW_NODE_KEY, null)
25
26
  const el = ref<HTMLElement>()
26
- const side = computed<FlowPosition>(() => props.position ?? (props.type === 'source' ? (flow?.direction.value === 'vertical' ? 'bottom' : 'right') : (flow?.direction.value === 'vertical' ? 'top' : 'left')))
27
+ const side = computed<FlowPosition | 'auto'>(() => props.position ?? (props.type === 'source' ? (flow?.direction.value === 'vertical' ? 'bottom' : 'right') : (flow?.direction.value === 'vertical' ? 'top' : 'left')))
27
28
  const canConnect = computed(() => props.connectable && !!flow?.nodesConnectable.value && state?.node.value.connectable !== false)
28
29
  const key = computed(() => `${state?.id}:${props.id ?? ''}:${props.type}`)
29
30
  const candidate = computed(() => flow?.connectionTarget.value?.key === key.value ? flow.connectionTarget.value : null)
30
31
 
31
- const PLACE: Record<FlowPosition, string> = {
32
+ const PLACE: Record<FlowPosition | 'auto', string> = {
33
+ auto: 'top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2',
32
34
  top: 'top-0 left-1/2 -translate-x-1/2 -translate-y-1/2',
33
35
  right: 'top-1/2 right-0 translate-x-1/2 -translate-y-1/2',
34
36
  bottom: 'bottom-0 left-1/2 -translate-x-1/2 translate-y-1/2',