@zyro-sec/merman 1.0.2 → 1.0.3

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 (91) hide show
  1. package/package.json +2 -2
  2. package/script/layout-audit.ts +98 -98
  3. package/src/core/canvas.ts +228 -228
  4. package/src/core/color/style.ts +56 -56
  5. package/src/core/drawing.ts +301 -301
  6. package/src/core/geometry.ts +347 -347
  7. package/src/core/mermaid.ts +38 -38
  8. package/src/core/render-grid.ts +51 -51
  9. package/src/core/spatial.ts +243 -243
  10. package/src/core/text-lines.ts +32 -32
  11. package/src/core/text.ts +44 -44
  12. package/src/detect.ts +17 -17
  13. package/src/diagnostics.ts +16 -16
  14. package/src/flowchart/drawing.ts +340 -340
  15. package/src/flowchart/labels.ts +144 -144
  16. package/src/flowchart/layout.ts +1427 -1427
  17. package/src/flowchart/options.ts +12 -12
  18. package/src/flowchart/parser.ts +467 -467
  19. package/src/flowchart/render.ts +10 -10
  20. package/src/flowchart/routing.ts +1542 -1542
  21. package/src/flowchart/style.ts +79 -79
  22. package/src/flowchart/types.ts +65 -65
  23. package/src/gantt/diagram.ts +8 -8
  24. package/src/gantt/drawing.ts +191 -191
  25. package/src/gantt/parser.ts +161 -161
  26. package/src/gantt/render-grid.ts +17 -17
  27. package/src/gantt/style.ts +36 -36
  28. package/src/gantt/types.ts +44 -44
  29. package/src/gitgraph/diagram.ts +8 -8
  30. package/src/gitgraph/drawing.ts +234 -234
  31. package/src/gitgraph/parser.ts +219 -219
  32. package/src/gitgraph/render-grid.ts +17 -17
  33. package/src/gitgraph/style.ts +37 -37
  34. package/src/gitgraph/types.ts +36 -36
  35. package/src/markdown.ts +336 -336
  36. package/src/palette.ts +75 -75
  37. package/src/plugin.ts +15 -15
  38. package/src/sequence/diagram.ts +8 -8
  39. package/src/sequence/drawing.ts +287 -287
  40. package/src/sequence/options.ts +8 -8
  41. package/src/sequence/parser.ts +282 -282
  42. package/src/sequence/placement.ts +684 -684
  43. package/src/sequence/render-grid.ts +22 -22
  44. package/src/sequence/style.ts +81 -81
  45. package/src/sequence/types.ts +74 -74
  46. package/src/state/diagram.ts +8 -8
  47. package/src/state/drawing.ts +360 -360
  48. package/src/state/endpoint.ts +15 -15
  49. package/src/state/layout.ts +1134 -1134
  50. package/src/state/note.ts +59 -59
  51. package/src/state/options.ts +11 -11
  52. package/src/state/parser.ts +224 -224
  53. package/src/state/render-grid.ts +22 -22
  54. package/src/state/routing.ts +1522 -1522
  55. package/src/state/search.ts +103 -103
  56. package/src/state/style.ts +52 -52
  57. package/src/state/types.ts +63 -63
  58. package/src/state/visible-model.ts +77 -77
  59. package/src/test/diagram.ts +32 -32
  60. package/src/test/layout-audit/fixtures.ts +538 -538
  61. package/src/test/layout-audit/harness.ts +522 -522
  62. package/src/timeline/diagram.ts +8 -8
  63. package/src/timeline/drawing.ts +109 -109
  64. package/src/timeline/parser.ts +119 -119
  65. package/src/timeline/render-grid.ts +17 -17
  66. package/src/timeline/style.ts +36 -36
  67. package/src/timeline/types.ts +31 -31
  68. package/tsconfig.json +10 -10
  69. package/src/core/canvas.test.ts +0 -203
  70. package/src/core/color/style.test.ts +0 -24
  71. package/src/core/drawing.test.ts +0 -116
  72. package/src/core/geometry.test.ts +0 -112
  73. package/src/core/spatial.test.ts +0 -87
  74. package/src/core/text.test.ts +0 -33
  75. package/src/flowchart/flowchart.test.ts +0 -2800
  76. package/src/flowchart/labels.test.ts +0 -127
  77. package/src/flowchart/routing.test.ts +0 -368
  78. package/src/gantt/diagram.test.ts +0 -124
  79. package/src/gitgraph/diagram.test.ts +0 -183
  80. package/src/layout-audit.test.ts +0 -92
  81. package/src/palette.test.ts +0 -103
  82. package/src/sequence/diagram.test.ts +0 -757
  83. package/src/sequence/placement.test.ts +0 -219
  84. package/src/state/diagram.test.ts +0 -1386
  85. package/src/state/layout.test.ts +0 -314
  86. package/src/state/routing.test.ts +0 -693
  87. package/src/state/style.test.ts +0 -113
  88. package/src/state/visible-model.test.ts +0 -84
  89. package/src/test/diagnostics.test.ts +0 -129
  90. package/src/test/markdown.test.ts +0 -474
  91. package/src/timeline/diagram.test.ts +0 -188
@@ -1,1542 +1,1542 @@
1
- import {
2
- advanceCoordinate,
3
- afterFarthestCoordinate,
4
- beforeNearestCoordinate,
5
- boundsCenter,
6
- boundsSidePoint,
7
- centerCoordinate,
8
- coordinate,
9
- keepAfter,
10
- keepBefore,
11
- lane,
12
- oppositeSide,
13
- orthogonalPath,
14
- orthogonalPathPoints,
15
- pathThrough,
16
- pathViaLane,
17
- segmentBetween,
18
- segmentSpan,
19
- sideForDirection,
20
- snapCoordinate,
21
- shiftPoint,
22
- withCoordinate,
23
- type DiagramAxis,
24
- type DiagramDirection,
25
- type DiagramLane,
26
- type DiagramSide,
27
- } from "../core/geometry.js"
28
- import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
29
- import { flowchartEdgeLabelLayout, flowchartRouteLabelLayout, type FlowchartEdgeLabelLayout } from "./labels.js"
30
- import type {
31
- FlowchartDiagram,
32
- FlowchartDirection,
33
- FlowchartEdge,
34
- FlowchartEdgeRoute,
35
- FlowchartEndpointBounds,
36
- FlowchartNodeBounds,
37
- FlowchartPoint,
38
- FlowchartSubgraph,
39
- FlowchartSubgraphBounds,
40
- } from "./types.js"
41
-
42
- export { directionBetween as flowchartDirectionBetween } from "../core/geometry.js"
43
-
44
- const BUS_CLEARANCE = 3
45
- const NODE_CLEARANCE = 2
46
- const ROUTING_CANDIDATE_BUDGET = 1024
47
- type HorizontalTravel = Extract<DiagramDirection, "left" | "right">
48
- type VerticalTravel = Extract<DiagramDirection, "up" | "down">
49
- type PortRole = "source" | "target"
50
-
51
- interface EdgeRecord {
52
- edge: FlowchartEdge
53
- sourcePort: FlowchartPoint
54
- targetPort: FlowchartPoint
55
- }
56
-
57
- function isVerticalDirection(direction: FlowchartDirection): boolean {
58
- return direction === "TB" || direction === "TD" || direction === "BT"
59
- }
60
-
61
- function verticalTravel(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): VerticalTravel {
62
- return centerCoordinate(to, "y") >= centerCoordinate(from, "y") ? "down" : "up"
63
- }
64
-
65
- function isVerticalBackEdge(
66
- from: FlowchartEndpointBounds,
67
- to: FlowchartEndpointBounds,
68
- direction: FlowchartDirection,
69
- ): boolean {
70
- return direction === "BT"
71
- ? centerCoordinate(to, "y") > centerCoordinate(from, "y")
72
- : centerCoordinate(to, "y") < centerCoordinate(from, "y")
73
- }
74
-
75
- function isHorizontalBackEdge(
76
- from: FlowchartEndpointBounds,
77
- to: FlowchartEndpointBounds,
78
- direction: FlowchartDirection,
79
- ): boolean {
80
- return direction === "RL"
81
- ? centerCoordinate(to, "x") > centerCoordinate(from, "x")
82
- : centerCoordinate(to, "x") < centerCoordinate(from, "x")
83
- }
84
-
85
- function horizontalTravel(
86
- from: FlowchartEndpointBounds,
87
- to: FlowchartEndpointBounds,
88
- direction: FlowchartDirection,
89
- ): HorizontalTravel {
90
- const targetIsRight = centerCoordinate(to, "x") > centerCoordinate(from, "x")
91
- const targetIsSameOrRight = centerCoordinate(to, "x") >= centerCoordinate(from, "x")
92
- return direction === "RL" ? (targetIsRight ? "right" : "left") : targetIsSameOrRight ? "right" : "left"
93
- }
94
-
95
- function isSubgraphBounds(bounds: FlowchartEndpointBounds): bounds is FlowchartSubgraphBounds {
96
- return "labelSide" in bounds
97
- }
98
-
99
- function clearSubgraphTitlePort(bounds: FlowchartEndpointBounds, port: FlowchartPoint, role: PortRole): FlowchartPoint {
100
- if (role !== "source" || !isSubgraphBounds(bounds) || bounds.label.length === 0) return port
101
- const connector = flowchartSourceConnector(bounds, port)
102
- const title = subgraphTitleBounds(bounds)
103
- const overlapsTitle =
104
- connector.y >= title.top &&
105
- connector.y < title.top + title.height &&
106
- connector.x >= title.left &&
107
- connector.x < title.left + title.width
108
- if (!overlapsTitle) return port
109
- const afterTitleX = title.left + title.width
110
- if (afterTitleX <= bounds.left + bounds.width - 2) return { x: afterTitleX, y: port.y }
111
- if (title.left - 1 >= bounds.left + 1) return { x: title.left - 1, y: port.y }
112
- return port
113
- }
114
-
115
- function endpointSidePoint(bounds: FlowchartEndpointBounds, side: DiagramSide, role: PortRole): FlowchartPoint {
116
- return clearSubgraphTitlePort(bounds, boundsSidePoint(bounds, side), role)
117
- }
118
-
119
- function verticalBackEdgePath(
120
- from: FlowchartEndpointBounds,
121
- to: FlowchartEndpointBounds,
122
- leftBoundary?: number,
123
- ): FlowchartPoint[] {
124
- const start = endpointSidePoint(from, "left", "source")
125
- const end = endpointSidePoint(to, "left", "target")
126
- const busX = Math.min(
127
- afterFarthestCoordinate([start, end], "x", "left", BUS_CLEARANCE),
128
- leftBoundary === undefined ? Number.POSITIVE_INFINITY : leftBoundary - BUS_CLEARANCE * 2,
129
- )
130
- return pathViaLane(start, lane("x", busX), end)
131
- }
132
-
133
- function verticalForwardEdgePath(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): FlowchartPoint[] {
134
- const travel = verticalTravel(from, to)
135
- const startSide = sideForDirection(travel)
136
- const endSide = oppositeSide(startSide)
137
- const sourceCenter = boundsCenter(from)
138
- const targetCenter = boundsCenter(to)
139
- const snapped = withCoordinate(
140
- boundsSidePoint(from, startSide),
141
- "x",
142
- snapCoordinate(sourceCenter.x, targetCenter.x, 1),
143
- )
144
- const start = clearSubgraphTitlePort(from, snapped, "source")
145
- const end = endpointSidePoint(to, endSide, "target")
146
- return orthogonalPath(start, end, { preferredAxis: "y" })
147
- }
148
-
149
- function horizontalBackEdgePath(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): FlowchartPoint[] {
150
- const start = endpointSidePoint(from, "top", "source")
151
- const end = endpointSidePoint(to, "top", "target")
152
- const busY = afterFarthestCoordinate([start, end], "y", "up", BUS_CLEARANCE)
153
- return pathViaLane(start, lane("y", busY), end)
154
- }
155
-
156
- function horizontalEdgePath(
157
- from: FlowchartEndpointBounds,
158
- to: FlowchartEndpointBounds,
159
- direction: FlowchartDirection,
160
- ): FlowchartPoint[] {
161
- const overlapsHorizontally = from.left < to.left + to.width && to.left < from.left + from.width
162
- if (overlapsHorizontally) return verticalForwardEdgePath(from, to)
163
-
164
- if (isHorizontalBackEdge(from, to, direction)) return horizontalBackEdgePath(from, to)
165
-
166
- const travel = horizontalTravel(from, to, direction)
167
- const startSide = sideForDirection(travel)
168
- return orthogonalPath(
169
- endpointSidePoint(from, startSide, "source"),
170
- endpointSidePoint(to, oppositeSide(startSide), "target"),
171
- {
172
- preferredAxis: "x",
173
- },
174
- )
175
- }
176
-
177
- function selfEdgePath(bounds: FlowchartEndpointBounds, laneOffset = 0): FlowchartPoint[] {
178
- const start = endpointSidePoint(bounds, "right", "source")
179
- const end = endpointSidePoint(bounds, "bottom", "target")
180
- const rightLaneX = bounds.left + bounds.width + BUS_CLEARANCE + laneOffset
181
- const bottomLaneY = bounds.top + bounds.height + 1 + laneOffset
182
- return [start, { x: rightLaneX, y: start.y }, { x: rightLaneX, y: bottomLaneY }, { x: end.x, y: bottomLaneY }, end]
183
- }
184
-
185
- function parallelEdgePath(
186
- from: FlowchartEndpointBounds,
187
- to: FlowchartEndpointBounds,
188
- axis: DiagramAxis,
189
- laneCoordinate: number,
190
- ): FlowchartPoint[] {
191
- if (axis === "y") {
192
- const start = endpointSidePoint(from, "bottom", "source")
193
- const end = endpointSidePoint(to, "bottom", "target")
194
- return pathViaLane(start, lane("y", laneCoordinate), end)
195
- }
196
-
197
- const start = endpointSidePoint(from, "right", "source")
198
- const end = endpointSidePoint(to, "right", "target")
199
- return pathViaLane(start, lane("x", laneCoordinate), end)
200
- }
201
-
202
- function labelHeight(edge: FlowchartEdge): number {
203
- return edge.label ? splitDiagramLines(edge.label).length : 0
204
- }
205
-
206
- function rightRenderExtent(route: FlowchartEdgeRoute): number {
207
- let right = Math.max(...route.points.map((point) => point.x))
208
- if (route.edge.label) {
209
- const label = flowchartRouteLabelLayout(route, diagramTextWidth)
210
- right = Math.max(right, label.point.x + label.width - 1)
211
- }
212
- return right
213
- }
214
-
215
- function parallelLaneAxis(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): DiagramAxis {
216
- return Math.abs(to.centerX - from.centerX) >= Math.abs(to.centerY - from.centerY) ? "y" : "x"
217
- }
218
-
219
- function edgePath(
220
- from: FlowchartEndpointBounds,
221
- to: FlowchartEndpointBounds,
222
- direction: FlowchartDirection,
223
- leftBoundary?: number,
224
- ): FlowchartPoint[] {
225
- if (from.id === to.id) return selfEdgePath(from)
226
- if (!isVerticalDirection(direction)) return horizontalEdgePath(from, to, direction)
227
- const overlapsVertically = from.top < to.top + to.height && to.top < from.top + from.height
228
- if (overlapsVertically) {
229
- const travel: HorizontalTravel = centerCoordinate(to, "x") >= centerCoordinate(from, "x") ? "right" : "left"
230
- return orthogonalPath(
231
- endpointSidePoint(from, sideForDirection(travel), "source"),
232
- endpointSidePoint(to, oppositeSide(sideForDirection(travel)), "target"),
233
- )
234
- }
235
- return isVerticalBackEdge(from, to, direction)
236
- ? verticalBackEdgePath(from, to, leftBoundary)
237
- : verticalForwardEdgePath(from, to)
238
- }
239
-
240
- function sourceFanOutLane(
241
- sourcePort: FlowchartPoint,
242
- targetPorts: readonly FlowchartPoint[],
243
- axis: DiagramAxis,
244
- travel: DiagramDirection,
245
- ): number {
246
- const sourceCoordinate = coordinate(sourcePort, axis)
247
- const unclamped = keepBefore(
248
- advanceCoordinate(coordinate(sourcePort, axis), travel, BUS_CLEARANCE),
249
- beforeNearestCoordinate(targetPorts, axis, travel, NODE_CLEARANCE),
250
- travel,
251
- )
252
- return keepAfter(unclamped, sourceCoordinate, travel)
253
- }
254
-
255
- function reserveFanOutLane(
256
- sourcePort: FlowchartPoint,
257
- targetPorts: readonly FlowchartPoint[],
258
- axis: DiagramAxis,
259
- travel: DiagramDirection,
260
- reserved: Set<number>,
261
- ): number {
262
- const preferred = sourceFanOutLane(sourcePort, targetPorts, axis, travel)
263
- const boundary = beforeNearestCoordinate(targetPorts, axis, travel, NODE_CLEARANCE)
264
- const source = coordinate(sourcePort, axis)
265
- const available = (() => {
266
- let checked = 0
267
- for (let offset = 0; offset <= Math.abs(boundary - preferred) && checked < ROUTING_CANDIDATE_BUDGET; offset++) {
268
- checked++
269
- const candidate = advanceCoordinate(preferred, travel, offset)
270
- if (
271
- keepBefore(candidate, boundary, travel) === candidate &&
272
- keepAfter(candidate, source, travel) === candidate &&
273
- !reserved.has(candidate)
274
- ) {
275
- return candidate
276
- }
277
- }
278
- for (let offset = 1; offset <= Math.abs(preferred - source) && checked < ROUTING_CANDIDATE_BUDGET; offset++) {
279
- checked++
280
- const candidate = advanceCoordinate(preferred, travel, -offset)
281
- if (
282
- keepBefore(candidate, boundary, travel) === candidate &&
283
- keepAfter(candidate, source, travel) === candidate &&
284
- !reserved.has(candidate)
285
- ) {
286
- return candidate
287
- }
288
- }
289
- })()
290
- const routeLane = available ?? preferred
291
- reserved.add(routeLane)
292
- return routeLane
293
- }
294
-
295
- function targetFanInLane(
296
- sourcePorts: readonly FlowchartPoint[],
297
- targetPort: FlowchartPoint,
298
- axis: DiagramAxis,
299
- travel: DiagramDirection,
300
- ): number {
301
- const targetCoordinate = coordinate(targetPort, axis)
302
- const unclamped = keepAfter(
303
- advanceCoordinate(coordinate(targetPort, axis), travel, -BUS_CLEARANCE),
304
- afterFarthestCoordinate(sourcePorts, axis, travel, NODE_CLEARANCE),
305
- travel,
306
- )
307
- return keepBefore(unclamped, advanceCoordinate(targetCoordinate, travel, -1), travel)
308
- }
309
-
310
- function portForTravel(bounds: FlowchartEndpointBounds, travel: DiagramDirection, role: PortRole): FlowchartPoint {
311
- const side = role === "source" ? sideForDirection(travel) : oppositeSide(sideForDirection(travel))
312
- return endpointSidePoint(bounds, side, role)
313
- }
314
-
315
- function subgraphContainsMember(
316
- subgraphs: readonly FlowchartSubgraph[],
317
- subgraph: FlowchartSubgraph,
318
- endpointId: string,
319
- ): boolean {
320
- return (
321
- subgraph.nodeIds.includes(endpointId) ||
322
- subgraphs.some(
323
- (child) =>
324
- child.parentId === subgraph.id &&
325
- (child.id === endpointId || subgraphContainsMember(subgraphs, child, endpointId)),
326
- )
327
- )
328
- }
329
-
330
- function horizontalForwardRecords(
331
- edges: FlowchartEdge[],
332
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
333
- direction: FlowchartDirection,
334
- ): EdgeRecord[] {
335
- const travel = direction === "RL" ? "left" : "right"
336
- const records: EdgeRecord[] = []
337
- for (const edge of edges) {
338
- const source = endpoints.get(edge.from)
339
- const target = endpoints.get(edge.to)
340
- if (!source || !target) continue
341
- const forward =
342
- direction === "RL"
343
- ? centerCoordinate(target, "x") < centerCoordinate(source, "x")
344
- : centerCoordinate(target, "x") > centerCoordinate(source, "x")
345
- if (!forward) continue
346
- records.push({
347
- edge,
348
- sourcePort: portForTravel(source, travel, "source"),
349
- targetPort: portForTravel(target, travel, "target"),
350
- })
351
- }
352
- return records
353
- }
354
-
355
- function verticalForwardRecords(
356
- edges: FlowchartEdge[],
357
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
358
- direction: FlowchartDirection,
359
- ): EdgeRecord[] {
360
- const travel = direction === "BT" ? "up" : "down"
361
- const records: EdgeRecord[] = []
362
- for (const edge of edges) {
363
- const source = endpoints.get(edge.from)
364
- const target = endpoints.get(edge.to)
365
- if (!source || !target) continue
366
- const forward =
367
- direction === "BT"
368
- ? centerCoordinate(target, "y") < centerCoordinate(source, "y")
369
- : centerCoordinate(target, "y") > centerCoordinate(source, "y")
370
- if (!forward) continue
371
- records.push({
372
- edge,
373
- sourcePort: portForTravel(source, travel, "source"),
374
- targetPort: portForTravel(target, travel, "target"),
375
- })
376
- }
377
- return records
378
- }
379
-
380
- function horizontalExitSubgraph(diagram: FlowchartDiagram, edge: FlowchartEdge): FlowchartSubgraph | undefined {
381
- const subgraphs = diagram.subgraphs ?? []
382
- for (const subgraph of [...subgraphs].reverse()) {
383
- if (subgraph.direction !== "LR" && subgraph.direction !== "RL") continue
384
- if (subgraph.id === edge.from || subgraph.id === edge.to) continue
385
- if (subgraphContainsMember(subgraphs, subgraph, edge.from) && !subgraphContainsMember(subgraphs, subgraph, edge.to))
386
- return subgraph
387
- }
388
- return undefined
389
- }
390
-
391
- function horizontalEntrySubgraph(diagram: FlowchartDiagram, edge: FlowchartEdge): FlowchartSubgraph | undefined {
392
- const subgraphs = diagram.subgraphs ?? []
393
- for (const subgraph of [...subgraphs].reverse()) {
394
- if (subgraph.direction !== "LR" && subgraph.direction !== "RL") continue
395
- if (subgraph.id === edge.from || subgraph.id === edge.to) continue
396
- if (subgraphContainsMember(subgraphs, subgraph, edge.to) && !subgraphContainsMember(subgraphs, subgraph, edge.from))
397
- return subgraph
398
- }
399
- return undefined
400
- }
401
-
402
- function horizontalSubgraphEntryTravel(subgraph: FlowchartSubgraph): HorizontalTravel {
403
- return subgraph.direction === "RL" ? "left" : "right"
404
- }
405
-
406
- function horizontalSubgraphEntryLane(subgraph: FlowchartSubgraph, subgraphBound: FlowchartSubgraphBounds): number {
407
- return subgraph.direction === "RL"
408
- ? subgraphBound.left + subgraphBound.width + BUS_CLEARANCE
409
- : subgraphBound.left - BUS_CLEARANCE
410
- }
411
-
412
- function horizontalSubgraphJoinY(from: FlowchartSubgraphBounds, targetSubgraphBound: FlowchartSubgraphBounds): number {
413
- if (from.centerY <= targetSubgraphBound.centerY) {
414
- const start = from.top + from.height
415
- const end = targetSubgraphBound.top - 1
416
- return start <= end ? Math.floor((start + end) / 2) : start
417
- }
418
-
419
- const start = targetSubgraphBound.top + targetSubgraphBound.height
420
- const end = from.top - 1
421
- return start <= end ? Math.floor((start + end) / 2) : end
422
- }
423
-
424
- function horizontalSubgraphExitJoinY(
425
- from: FlowchartSubgraphBounds,
426
- targetPort: FlowchartPoint,
427
- targetBelow: boolean,
428
- ): number {
429
- if (targetBelow) {
430
- const outside = from.top + from.height
431
- const beforeTarget = targetPort.y - 1
432
- const preferred = targetPort.y - BUS_CLEARANCE
433
- return outside <= beforeTarget ? Math.min(Math.max(outside, preferred), beforeTarget) : beforeTarget
434
- }
435
-
436
- const outside = from.top - 1
437
- const afterTarget = targetPort.y + 1
438
- const preferred = targetPort.y + BUS_CLEARANCE
439
- return afterTarget <= outside ? Math.max(Math.min(outside, preferred), afterTarget) : afterTarget
440
- }
441
-
442
- function groupRecords<Record>(records: readonly Record[], key: (record: Record) => string): Map<string, Record[]> {
443
- const groups = new Map<string, Record[]>()
444
- for (const record of records) {
445
- const groupKey = key(record)
446
- const group = groups.get(groupKey) ?? []
447
- group.push(record)
448
- groups.set(groupKey, group)
449
- }
450
- return groups
451
- }
452
-
453
- function fanRoute(
454
- edge: FlowchartEdge,
455
- sourcePort: FlowchartPoint,
456
- targetPort: FlowchartPoint,
457
- routeLane: DiagramLane,
458
- ): FlowchartEdgeRoute {
459
- return { edge, points: pathViaLane(sourcePort, routeLane, targetPort) }
460
- }
461
-
462
- function alignClusteredVerticalSources(records: readonly EdgeRecord[]): EdgeRecord[] {
463
- const xs = records.map((record) => record.sourcePort.x)
464
- const minX = Math.min(...xs)
465
- const maxX = Math.max(...xs)
466
- if (maxX - minX > 1) return [...records]
467
-
468
- const x = Math.round(xs.reduce((total, value) => total + value, 0) / xs.length)
469
- return records.map((record) => ({ ...record, sourcePort: { ...record.sourcePort, x } }))
470
- }
471
-
472
- function routeHorizontalFanOut(
473
- records: readonly EdgeRecord[],
474
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
475
- direction: FlowchartDirection,
476
- handled: Set<FlowchartEdge>,
477
- routes: FlowchartEdgeRoute[],
478
- ): void {
479
- const reservedBusLanes = new Set<number>()
480
- const targetOwners = new Map<string, string>()
481
- for (const [sourceId, sourceRecords] of groupRecords(records, (record) => record.edge.from)) {
482
- if (sourceRecords.length < 2) continue
483
- const travel = direction === "RL" ? "left" : "right"
484
- const sourcePort = sourceRecords[0]!.sourcePort
485
- const targetPorts = sourceRecords.map((record) => record.targetPort)
486
-
487
- const busX = reserveFanOutLane(sourcePort, targetPorts, "x", travel, reservedBusLanes)
488
- for (const record of sourceRecords) {
489
- const targetOwner = targetOwners.get(record.edge.to)
490
- targetOwners.set(record.edge.to, targetOwner ?? sourceId)
491
- const target = endpoints.get(record.edge.to)
492
- if (!targetOwner || targetOwner === sourceId || !target) {
493
- routes.push(fanRoute(record.edge, sourcePort, record.targetPort, lane("x", busX)))
494
- handled.add(record.edge)
495
- continue
496
- }
497
-
498
- const targetSide = sourcePort.y < record.targetPort.y ? "top" : "bottom"
499
- const targetPoint = endpointSidePoint(target, targetSide, "target")
500
- const approach = shiftPoint(targetPoint, targetSide === "top" ? "up" : "down")
501
- routes.push({
502
- edge: record.edge,
503
- points: pathThrough([
504
- sourcePort,
505
- { x: busX, y: sourcePort.y },
506
- { x: busX, y: approach.y },
507
- approach,
508
- targetPoint,
509
- ]),
510
- })
511
- handled.add(record.edge)
512
- }
513
- }
514
- }
515
-
516
- function routeHorizontalFanIn(
517
- records: readonly EdgeRecord[],
518
- direction: FlowchartDirection,
519
- handled: Set<FlowchartEdge>,
520
- routes: FlowchartEdgeRoute[],
521
- ): void {
522
- const unhandledRecords = records.filter((record) => !handled.has(record.edge))
523
- for (const targetRecords of groupRecords(unhandledRecords, (record) => record.edge.to).values()) {
524
- if (targetRecords.length < 2) continue
525
- const travel = direction === "RL" ? "left" : "right"
526
- const targetPort = targetRecords[0]!.targetPort
527
- const sourcePorts = targetRecords.map((record) => record.sourcePort)
528
-
529
- const busX = targetFanInLane(sourcePorts, targetPort, "x", travel)
530
- for (const record of targetRecords) {
531
- routes.push(fanRoute(record.edge, record.sourcePort, targetPort, lane("x", busX)))
532
- handled.add(record.edge)
533
- }
534
- }
535
- }
536
-
537
- function routeVerticalFanOut(
538
- records: readonly EdgeRecord[],
539
- direction: FlowchartDirection,
540
- handled: Set<FlowchartEdge>,
541
- routes: FlowchartEdgeRoute[],
542
- ): void {
543
- for (const sourceRecords of groupRecords(records, (record) => record.edge.from).values()) {
544
- if (sourceRecords.length < 2) continue
545
- const travel = direction === "BT" ? "up" : "down"
546
- const sourcePort = sourceRecords[0]!.sourcePort
547
- const targetPorts = sourceRecords.map((record) => record.targetPort)
548
-
549
- const busY = sourceFanOutLane(sourcePort, targetPorts, "y", travel)
550
- for (const record of sourceRecords) {
551
- routes.push(fanRoute(record.edge, sourcePort, record.targetPort, lane("y", busY)))
552
- handled.add(record.edge)
553
- }
554
- }
555
- }
556
-
557
- function routeVerticalFanIn(
558
- records: readonly EdgeRecord[],
559
- direction: FlowchartDirection,
560
- handled: Set<FlowchartEdge>,
561
- routes: FlowchartEdgeRoute[],
562
- ): void {
563
- const unhandledRecords = records.filter((record) => !handled.has(record.edge))
564
- for (const unalignedTargetRecords of groupRecords(unhandledRecords, (record) => record.edge.to).values()) {
565
- const targetRecords = alignClusteredVerticalSources(unalignedTargetRecords)
566
- if (targetRecords.length < 2) continue
567
- const travel = direction === "BT" ? "up" : "down"
568
- const targetPort = targetRecords[0]!.targetPort
569
- const sourcePorts = targetRecords.map((record) => record.sourcePort)
570
-
571
- const busY = targetFanInLane(sourcePorts, targetPort, "y", travel)
572
- for (const record of targetRecords) {
573
- routes.push(fanRoute(record.edge, record.sourcePort, targetPort, lane("y", busY)))
574
- handled.add(record.edge)
575
- }
576
- }
577
- }
578
-
579
- function routeParallelEdges(
580
- diagram: FlowchartDiagram,
581
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
582
- directionForEdge: (edge: FlowchartEdge) => FlowchartDirection,
583
- directionAligned: boolean,
584
- handled: Set<FlowchartEdge>,
585
- routes: FlowchartEdgeRoute[],
586
- ): void {
587
- const groups = groupRecords(diagram.edges, (edge) => `${edge.from}:${edge.to}`)
588
- for (const edges of groups.values()) {
589
- if (edges.length < 2) continue
590
- const from = endpoints.get(edges[0]!.from)
591
- const to = endpoints.get(edges[0]!.to)
592
- if (!from || !to) continue
593
- if (from.id === to.id) {
594
- let laneOffset = 0
595
- for (const edge of edges) {
596
- routes.push({ edge, points: selfEdgePath(from, laneOffset) })
597
- handled.add(edge)
598
- laneOffset++
599
- }
600
- continue
601
- }
602
- const parallelAxis =
603
- directionAligned && isVerticalDirection(directionForEdge(edges[0]!)) ? "x" : parallelLaneAxis(from, to)
604
- let previousRoute: FlowchartEdgeRoute | undefined
605
- for (const edge of edges) {
606
- const height = labelHeight(edge)
607
- const laneCoordinate =
608
- parallelAxis === "x"
609
- ? previousRoute
610
- ? rightRenderExtent(previousRoute) + NODE_CLEARANCE
611
- : Math.max(boundsSidePoint(from, "right").x, boundsSidePoint(to, "right").x) + (directionAligned ? 1 : 0)
612
- : previousRoute
613
- ? Math.max(...previousRoute.points.map((point) => point.y)) + (height > 1 ? height + 1 : 1)
614
- : Math.max(boundsSidePoint(from, "bottom").y, boundsSidePoint(to, "bottom").y) + (height > 1 ? height : 0)
615
- const route: FlowchartEdgeRoute = {
616
- edge,
617
- points: parallelEdgePath(from, to, parallelAxis, laneCoordinate),
618
- labelAxis: parallelAxis === "x" ? "y" : "x",
619
- }
620
- routes.push(route)
621
- handled.add(edge)
622
- previousRoute = route
623
- }
624
- }
625
- }
626
-
627
- function routeHorizontalSubgraphExitFanIn(
628
- diagram: FlowchartDiagram,
629
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
630
- subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
631
- handled: Set<FlowchartEdge>,
632
- routes: FlowchartEdgeRoute[],
633
- ): void {
634
- if (!subgraphBounds) return
635
-
636
- const groups = new Map<
637
- string,
638
- { edge: FlowchartEdge; subgraph: FlowchartSubgraph; source: FlowchartEndpointBounds }[]
639
- >()
640
- for (const edge of diagram.edges) {
641
- if (handled.has(edge)) continue
642
- const subgraph = horizontalExitSubgraph(diagram, edge)
643
- const source = endpoints.get(edge.from)
644
- const target = endpoints.get(edge.to)
645
- if (!subgraph || !source || !target) continue
646
-
647
- const key = `${subgraph.id}:${edge.to}`
648
- const group = groups.get(key) ?? []
649
- group.push({ edge, subgraph, source })
650
- groups.set(key, group)
651
- }
652
-
653
- for (const group of groups.values()) {
654
- const subgraph = group[0]!.subgraph
655
- const subgraphBound = subgraphBounds.get(subgraph.id)
656
- const target = endpoints.get(group[0]!.edge.to)
657
- if (!subgraphBound || !target) continue
658
-
659
- const travel: HorizontalTravel = subgraph.direction === "RL" ? "left" : "right"
660
- const busX =
661
- subgraph.direction === "RL"
662
- ? subgraphBound.left - BUS_CLEARANCE
663
- : subgraphBound.left + subgraphBound.width + BUS_CLEARANCE
664
- const targetSubgraph = horizontalEntrySubgraph(diagram, group[0]!.edge)
665
- const targetSubgraphBound = targetSubgraph ? subgraphBounds.get(targetSubgraph.id) : undefined
666
- const targetBelow = target.centerY >= subgraphBound.centerY
667
- const targetPort = targetSubgraph
668
- ? portForTravel(target, horizontalSubgraphEntryTravel(targetSubgraph), "target")
669
- : endpointSidePoint(target, targetBelow ? "top" : "bottom", "target")
670
- const joinY = targetSubgraphBound
671
- ? horizontalSubgraphJoinY(subgraphBound, targetSubgraphBound)
672
- : horizontalSubgraphExitJoinY(subgraphBound, targetPort, targetBelow)
673
- const entryX =
674
- targetSubgraph && targetSubgraphBound
675
- ? horizontalSubgraphEntryLane(targetSubgraph, targetSubgraphBound)
676
- : targetPort.x
677
-
678
- for (const record of group) {
679
- const sourcePort = portForTravel(record.source, travel, "source")
680
- routes.push({
681
- edge: record.edge,
682
- points: pathThrough([
683
- sourcePort,
684
- { x: busX, y: sourcePort.y },
685
- { x: busX, y: joinY },
686
- { x: entryX, y: joinY },
687
- { x: entryX, y: targetPort.y },
688
- targetPort,
689
- ]),
690
- })
691
- handled.add(record.edge)
692
- }
693
- }
694
- }
695
-
696
- function routeHorizontalSubgraphEntries(
697
- diagram: FlowchartDiagram,
698
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
699
- subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
700
- handled: Set<FlowchartEdge>,
701
- routes: FlowchartEdgeRoute[],
702
- ): void {
703
- if (!subgraphBounds) return
704
-
705
- for (const edge of diagram.edges) {
706
- if (handled.has(edge)) continue
707
- const subgraph = horizontalEntrySubgraph(diagram, edge)
708
- const subgraphBound = subgraph ? subgraphBounds.get(subgraph.id) : undefined
709
- const from = endpoints.get(edge.from)
710
- const to = endpoints.get(edge.to)
711
- if (!subgraph || !subgraphBound || !from || !to) continue
712
-
713
- const targetPort = portForTravel(to, horizontalSubgraphEntryTravel(subgraph), "target")
714
- const entryX = horizontalSubgraphEntryLane(subgraph, subgraphBound)
715
- const travel = verticalTravel(from, to)
716
- const sourcePort = portForTravel(from, travel, "source")
717
- routes.push({
718
- edge,
719
- points: pathThrough([sourcePort, { x: entryX, y: sourcePort.y }, { x: entryX, y: targetPort.y }, targetPort]),
720
- })
721
- handled.add(edge)
722
- }
723
- }
724
-
725
- function pathIntersectsBounds(
726
- points: readonly FlowchartPoint[],
727
- bounds: { left: number; top: number; width: number; height: number },
728
- allowedContact: "source" | "target" | "both" | undefined = undefined,
729
- ): boolean {
730
- const right = bounds.left + bounds.width - 1
731
- const bottom = bounds.top + bounds.height - 1
732
- for (let index = 1; index < points.length; index++) {
733
- const from = points[index - 1]!
734
- const to = points[index]!
735
- if (from.x === to.x) {
736
- if (from.x < bounds.left || from.x > right) continue
737
- const overlapTop = Math.max(Math.min(from.y, to.y), bounds.top)
738
- const overlapBottom = Math.min(Math.max(from.y, to.y), bottom)
739
- if (overlapTop > overlapBottom) continue
740
- const sourceContact =
741
- (allowedContact === "source" || allowedContact === "both") &&
742
- index === 1 &&
743
- overlapTop === overlapBottom &&
744
- from.x === points[0]!.x &&
745
- overlapTop === points[0]!.y
746
- const targetContact =
747
- (allowedContact === "target" || allowedContact === "both") &&
748
- index === points.length - 1 &&
749
- overlapTop === overlapBottom &&
750
- to.x === points.at(-1)!.x &&
751
- overlapTop === points.at(-1)!.y
752
- if (!sourceContact && !targetContact) return true
753
- continue
754
- }
755
- if (from.y < bounds.top || from.y > bottom) continue
756
- const overlapLeft = Math.max(Math.min(from.x, to.x), bounds.left)
757
- const overlapRight = Math.min(Math.max(from.x, to.x), right)
758
- if (overlapLeft > overlapRight) continue
759
- const sourceContact =
760
- (allowedContact === "source" || allowedContact === "both") &&
761
- index === 1 &&
762
- overlapLeft === overlapRight &&
763
- overlapLeft === points[0]!.x &&
764
- from.y === points[0]!.y
765
- const targetContact =
766
- (allowedContact === "target" || allowedContact === "both") &&
767
- index === points.length - 1 &&
768
- overlapLeft === overlapRight &&
769
- overlapLeft === points.at(-1)!.x &&
770
- to.y === points.at(-1)!.y
771
- if (!sourceContact && !targetContact) return true
772
- }
773
- return false
774
- }
775
-
776
- function labelIntersectsBounds(
777
- label: FlowchartEdgeLabelLayout | undefined,
778
- bounds: { left: number; top: number; width: number; height: number },
779
- ): boolean {
780
- if (!label) return false
781
- return (
782
- label.point.x <= bounds.left + bounds.width - 1 &&
783
- label.point.x + label.width - 1 >= bounds.left &&
784
- label.point.y <= bounds.top + bounds.height - 1 &&
785
- label.point.y + label.height - 1 >= bounds.top
786
- )
787
- }
788
-
789
- function labelIntersectsSubgraphFrame(
790
- label: FlowchartEdgeLabelLayout | undefined,
791
- bounds: FlowchartSubgraphBounds,
792
- ): boolean {
793
- if (!label) return false
794
- const labelRight = label.point.x + label.width - 1
795
- const labelBottom = label.point.y + label.height - 1
796
- const right = bounds.left + bounds.width - 1
797
- const bottom = bounds.top + bounds.height - 1
798
- return (
799
- (label.point.x <= right &&
800
- labelRight >= bounds.left &&
801
- ((label.point.y <= bounds.top && labelBottom >= bounds.top) ||
802
- (label.point.y <= bottom && labelBottom >= bottom))) ||
803
- (label.point.y <= bottom &&
804
- labelBottom >= bounds.top &&
805
- ((label.point.x <= bounds.left && labelRight >= bounds.left) || (label.point.x <= right && labelRight >= right)))
806
- )
807
- }
808
-
809
- function routeLength(route: FlowchartEdgeRoute): number {
810
- let length = 0
811
- for (let index = 1; index < route.points.length; index++) {
812
- const from = route.points[index - 1]!
813
- const to = route.points[index]!
814
- length += Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
815
- }
816
- return length
817
- }
818
-
819
- function labelIntersectsLabels(
820
- label: FlowchartEdgeLabelLayout | undefined,
821
- otherLabels: readonly FlowchartEdgeLabelLayout[],
822
- ): boolean {
823
- if (!label) return false
824
- return otherLabels.some((otherLabel) =>
825
- labelIntersectsBounds(label, {
826
- left: otherLabel.point.x,
827
- top: otherLabel.point.y,
828
- width: otherLabel.width,
829
- height: otherLabel.height,
830
- }),
831
- )
832
- }
833
-
834
- function labelIntersectsRoutePaths(
835
- label: FlowchartEdgeLabelLayout | undefined,
836
- routes: readonly FlowchartEdgeRoute[],
837
- ): boolean {
838
- if (!label) return false
839
- return label.lines.some((line, lineIndex) => {
840
- const width = diagramTextWidth(line) - 2
841
- if (width <= 0) return false
842
- return routes.some((route) =>
843
- pathIntersectsBounds(route.points, {
844
- left: label.point.x + 1,
845
- top: label.point.y + lineIndex,
846
- width,
847
- height: 1,
848
- }),
849
- )
850
- })
851
- }
852
-
853
- function routeIntersectsLabels(route: FlowchartEdgeRoute, labels: readonly FlowchartEdgeLabelLayout[]): boolean {
854
- return labels.some((label) =>
855
- label.lines.some((line, lineIndex) => {
856
- const width = diagramTextWidth(line) - 2
857
- return (
858
- width > 0 &&
859
- pathIntersectsBounds(route.points, {
860
- left: label.point.x + 1,
861
- top: label.point.y + lineIndex,
862
- width,
863
- height: 1,
864
- })
865
- )
866
- }),
867
- )
868
- }
869
-
870
- function pathsIntersect(left: readonly FlowchartPoint[], right: readonly FlowchartPoint[]): boolean {
871
- const occupied = new Set(orthogonalPathPoints(left).map((point) => `${point.x}:${point.y}`))
872
- return orthogonalPathPoints(right).some((point) => occupied.has(`${point.x}:${point.y}`))
873
- }
874
-
875
- function endpointDisjoint(left: FlowchartEdge, right: FlowchartEdge): boolean {
876
- return left.from !== right.from && left.from !== right.to && left.to !== right.from && left.to !== right.to
877
- }
878
-
879
- function endpointConflictsWithRoutes(route: FlowchartEdgeRoute, otherRoutes: readonly FlowchartEdgeRoute[]): boolean {
880
- const source = route.points[0]
881
- const target = route.points.at(-1)
882
- if (!source || !target) return false
883
- return otherRoutes.some((other) => {
884
- const otherSource = other.points[0]
885
- const otherTarget = other.points.at(-1)
886
- return (
887
- (otherSource && target.x === otherSource.x && target.y === otherSource.y) ||
888
- (otherTarget && source.x === otherTarget.x && source.y === otherTarget.y)
889
- )
890
- })
891
- }
892
-
893
- function pathRunsAlongFrame(points: readonly FlowchartPoint[], bounds: FlowchartSubgraphBounds): boolean {
894
- const right = bounds.left + bounds.width - 1
895
- const bottom = bounds.top + bounds.height - 1
896
- for (let index = 1; index < points.length; index++) {
897
- const segment = segmentBetween(points[index - 1]!, points[index]!)
898
- if (!segment) continue
899
- const span = segmentSpan(segment)
900
- if (
901
- segment.axis === "x" &&
902
- (segment.from.y === bounds.top || segment.from.y === bottom) &&
903
- Math.min(span.end, right) > Math.max(span.start, bounds.left)
904
- ) {
905
- return true
906
- }
907
- if (
908
- segment.axis === "y" &&
909
- (segment.from.x === bounds.left || segment.from.x === right) &&
910
- Math.min(span.end, bottom) > Math.max(span.start, bounds.top)
911
- ) {
912
- return true
913
- }
914
- }
915
- return false
916
- }
917
-
918
- function subgraphTitleBounds(bounds: FlowchartSubgraphBounds): {
919
- left: number
920
- top: number
921
- width: number
922
- height: number
923
- } {
924
- const lines = splitDiagramLines(bounds.label)
925
- return {
926
- left: bounds.left + 2,
927
- top: bounds.labelSide === "top" ? bounds.top : bounds.top + bounds.height - lines.length,
928
- width: Math.max(...lines.map((line) => diagramTextWidth(` ${line} `))),
929
- height: lines.length,
930
- }
931
- }
932
-
933
- function avoidNodeObstacles(
934
- route: FlowchartEdgeRoute,
935
- routes: readonly FlowchartEdgeRoute[],
936
- bounds: ReadonlyMap<string, FlowchartNodeBounds>,
937
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
938
- subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
939
- routeIndex: number,
940
- diagram: FlowchartDiagram,
941
- ): FlowchartEdgeRoute {
942
- const allNodeBounds = [...bounds.values()]
943
- const allSubgraphBounds = [...(subgraphBounds?.values() ?? [])]
944
- const subgraphs = diagram.subgraphs ?? []
945
- const contains = (subgraph: FlowchartSubgraph, endpointId: string): boolean =>
946
- subgraphContainsMember(subgraphs, subgraph, endpointId)
947
- const owner = [...subgraphs].reverse().find((subgraph) => {
948
- if (!contains(subgraph, route.edge.from) || !contains(subgraph, route.edge.to)) return false
949
- const children = subgraphs.filter((child) => child.parentId === subgraph.id)
950
- return (
951
- children.some((child) => child.id === route.edge.from || contains(child, route.edge.from)) &&
952
- children.some((child) => child.id === route.edge.to || contains(child, route.edge.to)) &&
953
- !children.some(
954
- (child) =>
955
- (child.id === route.edge.from || contains(child, route.edge.from)) &&
956
- (child.id === route.edge.to || contains(child, route.edge.to)),
957
- )
958
- )
959
- })
960
- const ownerBounds = owner ? subgraphBounds?.get(owner.id) : undefined
961
- const leavesOwner = (candidate: FlowchartEdgeRoute): boolean =>
962
- Boolean(
963
- ownerBounds &&
964
- candidate.points.some(
965
- (point) =>
966
- point.x <= ownerBounds.left ||
967
- point.x >= ownerBounds.left + ownerBounds.width - 1 ||
968
- point.y <= ownerBounds.top ||
969
- point.y >= ownerBounds.top + ownerBounds.height - 1,
970
- ),
971
- )
972
- const otherRoutes = routes.filter((_, index) => index !== routeIndex)
973
- const otherLabels = otherRoutes.flatMap((otherRoute) =>
974
- otherRoute.edge.label ? [flowchartRouteLabelLayout(otherRoute, diagramTextWidth)] : [],
975
- )
976
- const intersectsNode = (candidate: FlowchartEdgeRoute): boolean =>
977
- allNodeBounds.some((bound) => {
978
- const isSource = bound.id === route.edge.from
979
- const isTarget = bound.id === route.edge.to
980
- const allowedContact = isSource && isTarget ? "both" : isSource ? "source" : isTarget ? "target" : undefined
981
- return pathIntersectsBounds(candidate.points, bound, allowedContact)
982
- })
983
- const sourceSubgraph = bounds.has(route.edge.from) ? undefined : subgraphBounds?.get(route.edge.from)
984
- const intersectsSourceTitle = (candidate: FlowchartEdgeRoute): boolean => {
985
- if (!sourceSubgraph || sourceSubgraph.label.length === 0 || !candidate.points[0]) return false
986
- const connector = flowchartSourceConnector(sourceSubgraph, candidate.points[0])
987
- const title = subgraphTitleBounds(sourceSubgraph)
988
- return (
989
- connector.y >= title.top &&
990
- connector.y < title.top + title.height &&
991
- connector.x >= title.left &&
992
- connector.x < title.left + title.width
993
- )
994
- }
995
- const intersectsStructuralObstacle = (candidate: FlowchartEdgeRoute): boolean =>
996
- intersectsNode(candidate) ||
997
- intersectsSourceTitle(candidate) ||
998
- allSubgraphBounds.some(
999
- (bound) =>
1000
- pathRunsAlongFrame(candidate.points, bound) ||
1001
- (bound.label.length > 0 && pathIntersectsBounds(candidate.points, subgraphTitleBounds(bound))),
1002
- )
1003
- const intersectsRoutingObstacle = (candidate: FlowchartEdgeRoute): boolean =>
1004
- intersectsStructuralObstacle(candidate) ||
1005
- endpointConflictsWithRoutes(candidate, otherRoutes) ||
1006
- otherRoutes.some(
1007
- (other) => endpointDisjoint(candidate.edge, other.edge) && pathsIntersect(candidate.points, other.points),
1008
- )
1009
- const intersectsObstacle = (candidate: FlowchartEdgeRoute): boolean => {
1010
- const label = candidate.edge.label ? flowchartRouteLabelLayout(candidate, diagramTextWidth) : undefined
1011
- return (
1012
- leavesOwner(candidate) ||
1013
- intersectsRoutingObstacle(candidate) ||
1014
- allNodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
1015
- allSubgraphBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
1016
- labelIntersectsLabels(label, otherLabels) ||
1017
- labelIntersectsRoutePaths(label, otherRoutes) ||
1018
- routeIntersectsLabels(candidate, otherLabels)
1019
- )
1020
- }
1021
- if (!intersectsObstacle(route)) return route
1022
-
1023
- const from = endpoints.get(route.edge.from)
1024
- const to = endpoints.get(route.edge.to)
1025
- if (!from || !to) return route
1026
- const routingBounds = [...allNodeBounds, ...allSubgraphBounds]
1027
- const rightBusX = Math.max(...routingBounds.map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
1028
- const leftBusX = Math.min(...routingBounds.map((bound) => bound.left)) - BUS_CLEARANCE
1029
- const topBusY = Math.min(...routingBounds.map((bound) => bound.top)) - BUS_CLEARANCE
1030
- const bottomBusY = Math.max(...routingBounds.map((bound) => bound.top + bound.height - 1)) + BUS_CLEARANCE
1031
- const rightBusXs = [
1032
- ...new Set([
1033
- rightBusX,
1034
- ...(ownerBounds ? [ownerBounds.left + ownerBounds.width - 2] : []),
1035
- ...otherLabels.map((label) => Math.max(rightBusX, label.point.x + label.width - 1 + NODE_CLEARANCE)),
1036
- ]),
1037
- ].sort((left, right) => left - right)
1038
- const leftBusXs = [
1039
- ...new Set([
1040
- leftBusX,
1041
- ...(ownerBounds ? [ownerBounds.left + 1] : []),
1042
- ...otherLabels.map((label) => Math.min(leftBusX, label.point.x - NODE_CLEARANCE)),
1043
- ]),
1044
- ].sort((left, right) => right - left)
1045
- const topBusYs = [
1046
- ...new Set([
1047
- topBusY,
1048
- ...(ownerBounds ? [ownerBounds.top + 1] : []),
1049
- ...otherLabels.map((label) => Math.min(topBusY, label.point.y - NODE_CLEARANCE)),
1050
- ]),
1051
- ].sort((left, right) => right - left)
1052
- const bottomBusYs = [
1053
- ...new Set([
1054
- bottomBusY,
1055
- ...(ownerBounds ? [ownerBounds.top + ownerBounds.height - 2] : []),
1056
- ...otherLabels.map((label) => Math.max(bottomBusY, label.point.y + label.height - 1 + NODE_CLEARANCE)),
1057
- ]),
1058
- ].sort((left, right) => left - right)
1059
- const busLimit = Math.max(1, Math.floor(Math.sqrt(ROUTING_CANDIDATE_BUDGET / 4)))
1060
- const candidateLeftBusXs = leftBusXs.length > busLimit ? leftBusXs.slice(0, busLimit) : leftBusXs
1061
- const candidateRightBusXs = rightBusXs.length > busLimit ? rightBusXs.slice(0, busLimit) : rightBusXs
1062
- const candidateTopBusYs = topBusYs.length > busLimit ? topBusYs.slice(0, busLimit) : topBusYs
1063
- const candidateBottomBusYs = bottomBusYs.length > busLimit ? bottomBusYs.slice(0, busLimit) : bottomBusYs
1064
- const buses = [
1065
- ...candidateLeftBusXs.map((coordinate) => lane("x", coordinate)),
1066
- ...candidateRightBusXs.map((coordinate) => lane("x", coordinate)),
1067
- ...candidateTopBusYs.map((coordinate) => lane("y", coordinate)),
1068
- ...candidateBottomBusYs.map((coordinate) => lane("y", coordinate)),
1069
- ]
1070
- const routeViaBus = (start: FlowchartPoint, targetSide: DiagramSide, bus: DiagramLane): FlowchartEdgeRoute => {
1071
- const end = boundsSidePoint(to, targetSide)
1072
- const approach = shiftPoint(
1073
- end,
1074
- targetSide === "left" ? "left" : targetSide === "right" ? "right" : targetSide === "top" ? "up" : "down",
1075
- )
1076
- return {
1077
- ...route,
1078
- labelAxis: route.labelAxis === undefined ? undefined : bus.axis === "x" ? "y" : "x",
1079
- points:
1080
- bus.axis === "x"
1081
- ? pathThrough([start, { x: bus.coordinate, y: start.y }, { x: bus.coordinate, y: approach.y }, approach, end])
1082
- : pathThrough([
1083
- start,
1084
- { x: start.x, y: bus.coordinate },
1085
- { x: approach.x, y: bus.coordinate },
1086
- approach,
1087
- end,
1088
- ]),
1089
- }
1090
- }
1091
- const selfLoops =
1092
- from.id !== to.id
1093
- ? []
1094
- : [
1095
- ...candidateRightBusXs.flatMap((busX) =>
1096
- candidateBottomBusYs.map(
1097
- (busY): FlowchartEdgeRoute => ({
1098
- ...route,
1099
- points: pathThrough([
1100
- boundsSidePoint(from, "right"),
1101
- { x: busX, y: from.centerY },
1102
- { x: busX, y: busY },
1103
- { x: from.centerX, y: busY },
1104
- boundsSidePoint(from, "bottom"),
1105
- ]),
1106
- }),
1107
- ),
1108
- ),
1109
- ...candidateBottomBusYs.flatMap((busY) =>
1110
- candidateLeftBusXs.map(
1111
- (busX): FlowchartEdgeRoute => ({
1112
- ...route,
1113
- points: pathThrough([
1114
- boundsSidePoint(from, "bottom"),
1115
- { x: from.centerX, y: busY },
1116
- { x: busX, y: busY },
1117
- { x: busX, y: from.centerY },
1118
- boundsSidePoint(from, "left"),
1119
- ]),
1120
- }),
1121
- ),
1122
- ),
1123
- ...candidateLeftBusXs.flatMap((busX) =>
1124
- candidateTopBusYs.map(
1125
- (busY): FlowchartEdgeRoute => ({
1126
- ...route,
1127
- points: pathThrough([
1128
- boundsSidePoint(from, "left"),
1129
- { x: busX, y: from.centerY },
1130
- { x: busX, y: busY },
1131
- { x: from.centerX, y: busY },
1132
- boundsSidePoint(from, "top"),
1133
- ]),
1134
- }),
1135
- ),
1136
- ),
1137
- ...candidateTopBusYs.flatMap((busY) =>
1138
- candidateRightBusXs.map(
1139
- (busX): FlowchartEdgeRoute => ({
1140
- ...route,
1141
- points: pathThrough([
1142
- boundsSidePoint(from, "top"),
1143
- { x: from.centerX, y: busY },
1144
- { x: busX, y: busY },
1145
- { x: busX, y: from.centerY },
1146
- boundsSidePoint(from, "right"),
1147
- ]),
1148
- }),
1149
- ),
1150
- ),
1151
- ]
1152
- const targetSides = ["left", "right", "top", "bottom"] satisfies DiagramSide[]
1153
- const shortest = (candidates: FlowchartEdgeRoute[], accept: (candidate: FlowchartEdgeRoute) => boolean) =>
1154
- candidates.filter(accept).sort((left, right) => routeLength(left) - routeLength(right))[0]
1155
- if (from.id === to.id)
1156
- return (
1157
- shortest(selfLoops, (candidate) => !intersectsObstacle(candidate)) ??
1158
- shortest(selfLoops, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1159
- route
1160
- )
1161
- const currentTargetSide = sideForOutsidePoint(to, route.points.at(-1)!)
1162
- const preservedTargets = buses.map((bus) => routeViaBus(route.points[0]!, currentTargetSide, bus))
1163
- const sameSides: FlowchartEdgeRoute[] = [
1164
- ...candidateRightBusXs.map(
1165
- (busX): FlowchartEdgeRoute => ({
1166
- ...route,
1167
- labelAxis: route.labelAxis === undefined ? undefined : "y",
1168
- points: pathViaLane(
1169
- endpointSidePoint(from, "right", "source"),
1170
- lane("x", busX),
1171
- endpointSidePoint(to, "right", "target"),
1172
- ),
1173
- }),
1174
- ),
1175
- ...candidateLeftBusXs.map(
1176
- (busX): FlowchartEdgeRoute => ({
1177
- ...route,
1178
- labelAxis: route.labelAxis === undefined ? undefined : "y",
1179
- points: pathViaLane(
1180
- endpointSidePoint(from, "left", "source"),
1181
- lane("x", busX),
1182
- endpointSidePoint(to, "left", "target"),
1183
- ),
1184
- }),
1185
- ),
1186
- ...candidateTopBusYs.map(
1187
- (busY): FlowchartEdgeRoute => ({
1188
- ...route,
1189
- labelAxis: route.labelAxis === undefined ? undefined : "x",
1190
- points: pathViaLane(
1191
- endpointSidePoint(from, "top", "source"),
1192
- lane("y", busY),
1193
- endpointSidePoint(to, "top", "target"),
1194
- ),
1195
- }),
1196
- ),
1197
- ...candidateBottomBusYs.map(
1198
- (busY): FlowchartEdgeRoute => ({
1199
- ...route,
1200
- labelAxis: route.labelAxis === undefined ? undefined : "x",
1201
- points: pathViaLane(
1202
- endpointSidePoint(from, "bottom", "source"),
1203
- lane("y", busY),
1204
- endpointSidePoint(to, "bottom", "target"),
1205
- ),
1206
- }),
1207
- ),
1208
- ]
1209
- const preservedSources = targetSides.flatMap((targetSide) =>
1210
- buses.map((bus) => routeViaBus(route.points[0]!, targetSide, bus)),
1211
- )
1212
- const attachments = targetSides.flatMap((sourceSide) =>
1213
- targetSides.flatMap((targetSide) =>
1214
- buses.map((bus) => routeViaBus(endpointSidePoint(from, sourceSide, "source"), targetSide, bus)),
1215
- ),
1216
- )
1217
- if (subgraphBounds) {
1218
- return (
1219
- shortest(preservedTargets, (candidate) => !intersectsObstacle(candidate)) ??
1220
- shortest(sameSides, (candidate) => !intersectsObstacle(candidate)) ??
1221
- shortest(preservedSources, (candidate) => !intersectsObstacle(candidate)) ??
1222
- shortest(attachments, (candidate) => !intersectsObstacle(candidate)) ??
1223
- shortest(preservedSources, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1224
- shortest(attachments, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1225
- route
1226
- )
1227
- }
1228
- return (
1229
- sameSides.find((candidate) => !intersectsObstacle(candidate)) ??
1230
- shortest(preservedTargets, (candidate) => !intersectsObstacle(candidate)) ??
1231
- attachments.find((candidate) => !intersectsObstacle(candidate)) ??
1232
- shortest(preservedSources, (candidate) => !intersectsObstacle(candidate)) ??
1233
- shortest(attachments, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1234
- shortest(preservedSources, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1235
- route
1236
- )
1237
- }
1238
-
1239
- function avoidLabelOverlap(
1240
- route: FlowchartEdgeRoute,
1241
- otherRoutes: readonly FlowchartEdgeRoute[],
1242
- bounds: ReadonlyMap<string, FlowchartNodeBounds>,
1243
- endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
1244
- subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
1245
- targetWidth?: number,
1246
- includeLabelWidth = true,
1247
- ): FlowchartEdgeRoute {
1248
- if (!route.edge.label) return route
1249
- const nodeBounds = [...bounds.values()]
1250
- const frameBounds = [...(subgraphBounds?.values() ?? [])]
1251
- const otherLabels = otherRoutes.flatMap((other) =>
1252
- other.edge.label ? [flowchartRouteLabelLayout(other, diagramTextWidth)] : [],
1253
- )
1254
- const otherConnectorBounds = otherRoutes.flatMap((other) => {
1255
- const source = endpoints.get(other.edge.from)
1256
- const sourcePoint = other.points[0]
1257
- if (!source || !sourcePoint) return []
1258
- const connector = flowchartSourceConnector(source, sourcePoint)
1259
- return [
1260
- { left: connector.x, top: connector.y, width: 1, height: 1 },
1261
- { left: sourcePoint.x, top: sourcePoint.y, width: 1, height: 1 },
1262
- ]
1263
- })
1264
- const hasParallelRoute = otherRoutes.some(
1265
- (other) => other.edge.from === route.edge.from && other.edge.to === route.edge.to,
1266
- )
1267
- const intersectsObstacle = (label: FlowchartEdgeLabelLayout): boolean =>
1268
- (targetWidth !== undefined &&
1269
- (hasParallelRoute || !includeLabelWidth
1270
- ? label.point.x > targetWidth
1271
- : label.point.x + label.width > targetWidth)) ||
1272
- nodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
1273
- frameBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
1274
- labelIntersectsLabels(label, otherLabels) ||
1275
- labelIntersectsRoutePaths(label, otherRoutes) ||
1276
- otherConnectorBounds.some((bound) => labelIntersectsBounds(label, bound))
1277
- const current = flowchartRouteLabelLayout(route, diagramTextWidth)
1278
- if (!intersectsObstacle(current)) return route
1279
-
1280
- const seen = new Set<string>()
1281
- let remaining = ROUTING_CANDIDATE_BUDGET
1282
- const available = (candidate: FlowchartPoint) => {
1283
- remaining--
1284
- const key = `${candidate.x}:${candidate.y}`
1285
- if (seen.has(key)) return false
1286
- seen.add(key)
1287
- return !intersectsObstacle({ ...current, point: candidate })
1288
- }
1289
- for (let index = 1; index < route.points.length && remaining > 0; index++) {
1290
- const segment = segmentBetween(route.points[index - 1]!, route.points[index]!)
1291
- if (!segment) continue
1292
- const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth, route.labelAxis, index - 1)
1293
- const fixed =
1294
- segment.axis === "y"
1295
- ? [label.point, { x: segment.from.x - label.width, y: label.point.y }]
1296
- : [
1297
- label.point,
1298
- { x: label.point.x, y: segment.from.y - label.height },
1299
- { x: label.point.x, y: segment.from.y + 1 },
1300
- ]
1301
- for (const candidate of fixed) {
1302
- if (remaining <= 0) return route
1303
- if (available(candidate)) return { ...route, labelPoint: candidate }
1304
- }
1305
- if (segment.axis === "y") {
1306
- const bottom = Math.max(segment.from.y, segment.to.y) - label.height + 1
1307
- for (let y = Math.min(segment.from.y, segment.to.y); y <= bottom && remaining > 0; y++) {
1308
- for (const x of [segment.from.x + 1, segment.from.x - label.width]) {
1309
- const candidate = { x, y }
1310
- if (available(candidate)) return { ...route, labelPoint: candidate }
1311
- if (remaining <= 0) return route
1312
- }
1313
- }
1314
- continue
1315
- }
1316
- const right = Math.max(segment.from.x, segment.to.x) - label.width + 1
1317
- for (let x = Math.min(segment.from.x, segment.to.x); x <= right && remaining > 0; x++) {
1318
- for (const y of [segment.from.y, segment.from.y - label.height, segment.from.y + 1]) {
1319
- const candidate = { x, y }
1320
- if (available(candidate)) return { ...route, labelPoint: candidate }
1321
- if (remaining <= 0) return route
1322
- }
1323
- }
1324
- }
1325
- if (targetWidth !== undefined && includeLabelWidth && current.point.x + current.width > targetWidth) {
1326
- const x = Math.max(0, targetWidth - current.width)
1327
- for (let distance = 0; distance < 100; distance++) {
1328
- for (const y of distance === 0 ? [current.point.y] : [current.point.y - distance, current.point.y + distance]) {
1329
- if (y < 0 || intersectsObstacle({ ...current, point: { x, y } })) continue
1330
- return { ...route, labelPoint: { x, y } }
1331
- }
1332
- }
1333
- }
1334
- return route
1335
- }
1336
-
1337
- export function routeFlowchartEdges(
1338
- diagram: FlowchartDiagram,
1339
- bounds: Map<string, FlowchartNodeBounds>,
1340
- directionForEdge: (edge: FlowchartEdge) => FlowchartDirection = () => diagram.direction,
1341
- subgraphBounds?: ReadonlyMap<string, FlowchartSubgraphBounds>,
1342
- targetWidth?: number,
1343
- directionAligned = false,
1344
- lockedRoutes?: ReadonlyMap<FlowchartEdge, FlowchartEdgeRoute>,
1345
- ): FlowchartEdgeRoute[] {
1346
- const routedDiagram = { ...diagram, edges: diagram.edges.filter((edge) => !edge.orderOnly) }
1347
- const endpoints = new Map<string, FlowchartEndpointBounds>([
1348
- ...(subgraphBounds ? [...subgraphBounds] : []),
1349
- ...bounds,
1350
- ])
1351
- const handled = new Set<FlowchartEdge>()
1352
- const routes: FlowchartEdgeRoute[] = []
1353
- if (lockedRoutes) {
1354
- for (const [edge, route] of lockedRoutes) {
1355
- routes.push(route)
1356
- handled.add(edge)
1357
- }
1358
- }
1359
- const leftBoundary = subgraphBounds
1360
- ? Math.min(...[...bounds.values(), ...subgraphBounds.values()].map((bound) => bound.left))
1361
- : undefined
1362
-
1363
- routeParallelEdges(routedDiagram, endpoints, directionForEdge, directionAligned, handled, routes)
1364
-
1365
- for (const direction of ["LR", "RL"] satisfies FlowchartDirection[]) {
1366
- const horizontalEdges = routedDiagram.edges.filter(
1367
- (edge) => !handled.has(edge) && directionForEdge(edge) === direction,
1368
- )
1369
- if (horizontalEdges.length === 0) continue
1370
- const records = horizontalForwardRecords(horizontalEdges, endpoints, direction)
1371
- routeHorizontalFanOut(records, endpoints, direction, handled, routes)
1372
- routeHorizontalFanIn(records, direction, handled, routes)
1373
- }
1374
-
1375
- routeHorizontalSubgraphExitFanIn(routedDiagram, endpoints, subgraphBounds, handled, routes)
1376
- routeHorizontalSubgraphEntries(routedDiagram, endpoints, subgraphBounds, handled, routes)
1377
-
1378
- for (const direction of ["TD", "TB", "BT"] satisfies FlowchartDirection[]) {
1379
- const verticalEdges = routedDiagram.edges.filter(
1380
- (edge) => !handled.has(edge) && directionForEdge(edge) === direction,
1381
- )
1382
- if (verticalEdges.length === 0) continue
1383
- const records = verticalForwardRecords(verticalEdges, endpoints, direction)
1384
- routeVerticalFanOut(records, direction, handled, routes)
1385
- routeVerticalFanIn(records, direction, handled, routes)
1386
- }
1387
-
1388
- for (const edge of routedDiagram.edges) {
1389
- if (handled.has(edge)) continue
1390
- const from = endpoints.get(edge.from)
1391
- const to = endpoints.get(edge.to)
1392
- if (!from || !to) continue
1393
- routes.push({ edge, points: edgePath(from, to, directionForEdge(edge), leftBoundary) })
1394
- }
1395
- for (let index = routes.length - 1; index >= 0; index--) {
1396
- if (lockedRoutes?.has(routes[index]!.edge)) continue
1397
- routes[index] = avoidNodeObstacles(routes[index]!, routes, bounds, endpoints, subgraphBounds, index, routedDiagram)
1398
- }
1399
- const subgraphs = diagram.subgraphs ?? []
1400
- const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
1401
- const containers = (id: string) => {
1402
- const ids = new Set<string>()
1403
- const directSubgraph = subgraphById.get(id)
1404
- let current = directSubgraph
1405
- ? directSubgraph.parentId
1406
- ? subgraphById.get(directSubgraph.parentId)
1407
- : undefined
1408
- : subgraphs.find((subgraph) => subgraph.nodeIds.includes(id))
1409
- while (current) {
1410
- ids.add(current.id)
1411
- current = current.parentId ? subgraphById.get(current.parentId) : undefined
1412
- }
1413
- return ids
1414
- }
1415
- const groupedLabelEdge = (edge: FlowchartEdge) => {
1416
- const fromContainers = containers(edge.from)
1417
- if (![...containers(edge.to)].some((id) => fromContainers.has(id))) return false
1418
- const targets = new Set(
1419
- routedDiagram.edges
1420
- .filter((candidate) => candidate.label && candidate.from === edge.from)
1421
- .map((candidate) => candidate.to),
1422
- )
1423
- const sources = new Set(
1424
- routedDiagram.edges
1425
- .filter((candidate) => candidate.label && candidate.to === edge.to)
1426
- .map((candidate) => candidate.from),
1427
- )
1428
- return targets.size > 1 || sources.size > 1
1429
- }
1430
- return routes.reduce<FlowchartEdgeRoute[]>((resolved, route, index) => {
1431
- if (lockedRoutes?.has(route.edge)) return [...resolved, route]
1432
- const grouped = groupedLabelEdge(route.edge)
1433
- return [
1434
- ...resolved,
1435
- avoidLabelOverlap(
1436
- route,
1437
- [...resolved, ...routes.slice(index + 1)],
1438
- bounds,
1439
- endpoints,
1440
- subgraphBounds,
1441
- targetWidth !== undefined && subgraphs.length > 0 && grouped ? Math.max(1, targetWidth - 5) : targetWidth,
1442
- subgraphs.length === 0 || grouped,
1443
- ),
1444
- ]
1445
- }, [])
1446
- }
1447
-
1448
- export function avoidFlowchartFrameBorders(
1449
- routes: readonly FlowchartEdgeRoute[],
1450
- bounds: ReadonlyMap<string, FlowchartNodeBounds>,
1451
- subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
1452
- ): void {
1453
- const endpoints = new Map<string, FlowchartEndpointBounds>([...subgraphBounds, ...bounds])
1454
- const inside = (node: FlowchartEndpointBounds, frame: FlowchartSubgraphBounds) =>
1455
- node.id !== frame.id &&
1456
- node.left >= frame.left &&
1457
- node.top >= frame.top &&
1458
- node.left + node.width <= frame.left + frame.width &&
1459
- node.top + node.height <= frame.top + frame.height
1460
-
1461
- for (const route of routes) {
1462
- const source = endpoints.get(route.edge.from)
1463
- const target = endpoints.get(route.edge.to)
1464
- for (const frame of subgraphBounds.values()) {
1465
- const inward = Boolean(source && target && inside(source, frame) && inside(target, frame))
1466
- const right = frame.left + frame.width - 1
1467
- const bottom = frame.top + frame.height - 1
1468
- const points: FlowchartPoint[] = [route.points[0]!]
1469
- for (let index = 1; index < route.points.length; index++) {
1470
- const from = route.points[index - 1]!
1471
- const to = route.points[index]!
1472
- const segment = segmentBetween(from, to)
1473
- if (!segment) continue
1474
- const span = segmentSpan(segment)
1475
- const horizontalSide =
1476
- segment.axis === "x" && Math.min(span.end, right) > Math.max(span.start, frame.left)
1477
- ? segment.from.y === frame.top
1478
- ? "top"
1479
- : segment.from.y === bottom
1480
- ? "bottom"
1481
- : undefined
1482
- : undefined
1483
- const verticalSide =
1484
- segment.axis === "y" && Math.min(span.end, bottom) > Math.max(span.start, frame.top)
1485
- ? segment.from.x === frame.left
1486
- ? "left"
1487
- : segment.from.x === right
1488
- ? "right"
1489
- : undefined
1490
- : undefined
1491
- if (!horizontalSide && !verticalSide) {
1492
- points.push(to)
1493
- continue
1494
- }
1495
-
1496
- const offset = horizontalSide
1497
- ? horizontalSide === "top"
1498
- ? frame.top + (inward ? 1 : -1)
1499
- : bottom + (inward ? -1 : 1)
1500
- : verticalSide === "left"
1501
- ? frame.left + (inward ? 1 : -1)
1502
- : right + (inward ? -1 : 1)
1503
- if (horizontalSide) points.push({ x: from.x, y: offset }, { x: to.x, y: offset }, to)
1504
- else points.push({ x: offset, y: from.y }, { x: offset, y: to.y }, to)
1505
- }
1506
- route.points = pathThrough(points)
1507
- }
1508
- }
1509
- }
1510
-
1511
- function sideForOutsidePoint(bounds: FlowchartEndpointBounds, sourcePoint: FlowchartPoint): DiagramSide {
1512
- if (sourcePoint.x < bounds.left) return "left"
1513
- if (sourcePoint.x >= bounds.left + bounds.width) return "right"
1514
- if (sourcePoint.y < bounds.top) return "top"
1515
- return "bottom"
1516
- }
1517
-
1518
- function connectorChar(side: DiagramSide): string {
1519
- switch (side) {
1520
- case "left":
1521
- return "┤"
1522
- case "right":
1523
- return "├"
1524
- case "top":
1525
- return "┴"
1526
- case "bottom":
1527
- return "┬"
1528
- }
1529
- }
1530
-
1531
- export function flowchartSourceConnector(
1532
- from: FlowchartEndpointBounds,
1533
- sourcePoint: FlowchartPoint,
1534
- ): { x: number; y: number; char: string } {
1535
- const side = sideForOutsidePoint(from, sourcePoint)
1536
- const connector = boundsSidePoint(from, side, "border")
1537
- return {
1538
- x: side === "top" || side === "bottom" ? sourcePoint.x : connector.x,
1539
- y: side === "left" || side === "right" ? sourcePoint.y : connector.y,
1540
- char: connectorChar(side),
1541
- }
1542
- }
1
+ import {
2
+ advanceCoordinate,
3
+ afterFarthestCoordinate,
4
+ beforeNearestCoordinate,
5
+ boundsCenter,
6
+ boundsSidePoint,
7
+ centerCoordinate,
8
+ coordinate,
9
+ keepAfter,
10
+ keepBefore,
11
+ lane,
12
+ oppositeSide,
13
+ orthogonalPath,
14
+ orthogonalPathPoints,
15
+ pathThrough,
16
+ pathViaLane,
17
+ segmentBetween,
18
+ segmentSpan,
19
+ sideForDirection,
20
+ snapCoordinate,
21
+ shiftPoint,
22
+ withCoordinate,
23
+ type DiagramAxis,
24
+ type DiagramDirection,
25
+ type DiagramLane,
26
+ type DiagramSide,
27
+ } from "../core/geometry.js"
28
+ import { diagramTextWidth, splitDiagramLines } from "../core/text.js"
29
+ import { flowchartEdgeLabelLayout, flowchartRouteLabelLayout, type FlowchartEdgeLabelLayout } from "./labels.js"
30
+ import type {
31
+ FlowchartDiagram,
32
+ FlowchartDirection,
33
+ FlowchartEdge,
34
+ FlowchartEdgeRoute,
35
+ FlowchartEndpointBounds,
36
+ FlowchartNodeBounds,
37
+ FlowchartPoint,
38
+ FlowchartSubgraph,
39
+ FlowchartSubgraphBounds,
40
+ } from "./types.js"
41
+
42
+ export { directionBetween as flowchartDirectionBetween } from "../core/geometry.js"
43
+
44
+ const BUS_CLEARANCE = 3
45
+ const NODE_CLEARANCE = 2
46
+ const ROUTING_CANDIDATE_BUDGET = 1024
47
+ type HorizontalTravel = Extract<DiagramDirection, "left" | "right">
48
+ type VerticalTravel = Extract<DiagramDirection, "up" | "down">
49
+ type PortRole = "source" | "target"
50
+
51
+ interface EdgeRecord {
52
+ edge: FlowchartEdge
53
+ sourcePort: FlowchartPoint
54
+ targetPort: FlowchartPoint
55
+ }
56
+
57
+ function isVerticalDirection(direction: FlowchartDirection): boolean {
58
+ return direction === "TB" || direction === "TD" || direction === "BT"
59
+ }
60
+
61
+ function verticalTravel(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): VerticalTravel {
62
+ return centerCoordinate(to, "y") >= centerCoordinate(from, "y") ? "down" : "up"
63
+ }
64
+
65
+ function isVerticalBackEdge(
66
+ from: FlowchartEndpointBounds,
67
+ to: FlowchartEndpointBounds,
68
+ direction: FlowchartDirection,
69
+ ): boolean {
70
+ return direction === "BT"
71
+ ? centerCoordinate(to, "y") > centerCoordinate(from, "y")
72
+ : centerCoordinate(to, "y") < centerCoordinate(from, "y")
73
+ }
74
+
75
+ function isHorizontalBackEdge(
76
+ from: FlowchartEndpointBounds,
77
+ to: FlowchartEndpointBounds,
78
+ direction: FlowchartDirection,
79
+ ): boolean {
80
+ return direction === "RL"
81
+ ? centerCoordinate(to, "x") > centerCoordinate(from, "x")
82
+ : centerCoordinate(to, "x") < centerCoordinate(from, "x")
83
+ }
84
+
85
+ function horizontalTravel(
86
+ from: FlowchartEndpointBounds,
87
+ to: FlowchartEndpointBounds,
88
+ direction: FlowchartDirection,
89
+ ): HorizontalTravel {
90
+ const targetIsRight = centerCoordinate(to, "x") > centerCoordinate(from, "x")
91
+ const targetIsSameOrRight = centerCoordinate(to, "x") >= centerCoordinate(from, "x")
92
+ return direction === "RL" ? (targetIsRight ? "right" : "left") : targetIsSameOrRight ? "right" : "left"
93
+ }
94
+
95
+ function isSubgraphBounds(bounds: FlowchartEndpointBounds): bounds is FlowchartSubgraphBounds {
96
+ return "labelSide" in bounds
97
+ }
98
+
99
+ function clearSubgraphTitlePort(bounds: FlowchartEndpointBounds, port: FlowchartPoint, role: PortRole): FlowchartPoint {
100
+ if (role !== "source" || !isSubgraphBounds(bounds) || bounds.label.length === 0) return port
101
+ const connector = flowchartSourceConnector(bounds, port)
102
+ const title = subgraphTitleBounds(bounds)
103
+ const overlapsTitle =
104
+ connector.y >= title.top &&
105
+ connector.y < title.top + title.height &&
106
+ connector.x >= title.left &&
107
+ connector.x < title.left + title.width
108
+ if (!overlapsTitle) return port
109
+ const afterTitleX = title.left + title.width
110
+ if (afterTitleX <= bounds.left + bounds.width - 2) return { x: afterTitleX, y: port.y }
111
+ if (title.left - 1 >= bounds.left + 1) return { x: title.left - 1, y: port.y }
112
+ return port
113
+ }
114
+
115
+ function endpointSidePoint(bounds: FlowchartEndpointBounds, side: DiagramSide, role: PortRole): FlowchartPoint {
116
+ return clearSubgraphTitlePort(bounds, boundsSidePoint(bounds, side), role)
117
+ }
118
+
119
+ function verticalBackEdgePath(
120
+ from: FlowchartEndpointBounds,
121
+ to: FlowchartEndpointBounds,
122
+ leftBoundary?: number,
123
+ ): FlowchartPoint[] {
124
+ const start = endpointSidePoint(from, "left", "source")
125
+ const end = endpointSidePoint(to, "left", "target")
126
+ const busX = Math.min(
127
+ afterFarthestCoordinate([start, end], "x", "left", BUS_CLEARANCE),
128
+ leftBoundary === undefined ? Number.POSITIVE_INFINITY : leftBoundary - BUS_CLEARANCE * 2,
129
+ )
130
+ return pathViaLane(start, lane("x", busX), end)
131
+ }
132
+
133
+ function verticalForwardEdgePath(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): FlowchartPoint[] {
134
+ const travel = verticalTravel(from, to)
135
+ const startSide = sideForDirection(travel)
136
+ const endSide = oppositeSide(startSide)
137
+ const sourceCenter = boundsCenter(from)
138
+ const targetCenter = boundsCenter(to)
139
+ const snapped = withCoordinate(
140
+ boundsSidePoint(from, startSide),
141
+ "x",
142
+ snapCoordinate(sourceCenter.x, targetCenter.x, 1),
143
+ )
144
+ const start = clearSubgraphTitlePort(from, snapped, "source")
145
+ const end = endpointSidePoint(to, endSide, "target")
146
+ return orthogonalPath(start, end, { preferredAxis: "y" })
147
+ }
148
+
149
+ function horizontalBackEdgePath(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): FlowchartPoint[] {
150
+ const start = endpointSidePoint(from, "top", "source")
151
+ const end = endpointSidePoint(to, "top", "target")
152
+ const busY = afterFarthestCoordinate([start, end], "y", "up", BUS_CLEARANCE)
153
+ return pathViaLane(start, lane("y", busY), end)
154
+ }
155
+
156
+ function horizontalEdgePath(
157
+ from: FlowchartEndpointBounds,
158
+ to: FlowchartEndpointBounds,
159
+ direction: FlowchartDirection,
160
+ ): FlowchartPoint[] {
161
+ const overlapsHorizontally = from.left < to.left + to.width && to.left < from.left + from.width
162
+ if (overlapsHorizontally) return verticalForwardEdgePath(from, to)
163
+
164
+ if (isHorizontalBackEdge(from, to, direction)) return horizontalBackEdgePath(from, to)
165
+
166
+ const travel = horizontalTravel(from, to, direction)
167
+ const startSide = sideForDirection(travel)
168
+ return orthogonalPath(
169
+ endpointSidePoint(from, startSide, "source"),
170
+ endpointSidePoint(to, oppositeSide(startSide), "target"),
171
+ {
172
+ preferredAxis: "x",
173
+ },
174
+ )
175
+ }
176
+
177
+ function selfEdgePath(bounds: FlowchartEndpointBounds, laneOffset = 0): FlowchartPoint[] {
178
+ const start = endpointSidePoint(bounds, "right", "source")
179
+ const end = endpointSidePoint(bounds, "bottom", "target")
180
+ const rightLaneX = bounds.left + bounds.width + BUS_CLEARANCE + laneOffset
181
+ const bottomLaneY = bounds.top + bounds.height + 1 + laneOffset
182
+ return [start, { x: rightLaneX, y: start.y }, { x: rightLaneX, y: bottomLaneY }, { x: end.x, y: bottomLaneY }, end]
183
+ }
184
+
185
+ function parallelEdgePath(
186
+ from: FlowchartEndpointBounds,
187
+ to: FlowchartEndpointBounds,
188
+ axis: DiagramAxis,
189
+ laneCoordinate: number,
190
+ ): FlowchartPoint[] {
191
+ if (axis === "y") {
192
+ const start = endpointSidePoint(from, "bottom", "source")
193
+ const end = endpointSidePoint(to, "bottom", "target")
194
+ return pathViaLane(start, lane("y", laneCoordinate), end)
195
+ }
196
+
197
+ const start = endpointSidePoint(from, "right", "source")
198
+ const end = endpointSidePoint(to, "right", "target")
199
+ return pathViaLane(start, lane("x", laneCoordinate), end)
200
+ }
201
+
202
+ function labelHeight(edge: FlowchartEdge): number {
203
+ return edge.label ? splitDiagramLines(edge.label).length : 0
204
+ }
205
+
206
+ function rightRenderExtent(route: FlowchartEdgeRoute): number {
207
+ let right = Math.max(...route.points.map((point) => point.x))
208
+ if (route.edge.label) {
209
+ const label = flowchartRouteLabelLayout(route, diagramTextWidth)
210
+ right = Math.max(right, label.point.x + label.width - 1)
211
+ }
212
+ return right
213
+ }
214
+
215
+ function parallelLaneAxis(from: FlowchartEndpointBounds, to: FlowchartEndpointBounds): DiagramAxis {
216
+ return Math.abs(to.centerX - from.centerX) >= Math.abs(to.centerY - from.centerY) ? "y" : "x"
217
+ }
218
+
219
+ function edgePath(
220
+ from: FlowchartEndpointBounds,
221
+ to: FlowchartEndpointBounds,
222
+ direction: FlowchartDirection,
223
+ leftBoundary?: number,
224
+ ): FlowchartPoint[] {
225
+ if (from.id === to.id) return selfEdgePath(from)
226
+ if (!isVerticalDirection(direction)) return horizontalEdgePath(from, to, direction)
227
+ const overlapsVertically = from.top < to.top + to.height && to.top < from.top + from.height
228
+ if (overlapsVertically) {
229
+ const travel: HorizontalTravel = centerCoordinate(to, "x") >= centerCoordinate(from, "x") ? "right" : "left"
230
+ return orthogonalPath(
231
+ endpointSidePoint(from, sideForDirection(travel), "source"),
232
+ endpointSidePoint(to, oppositeSide(sideForDirection(travel)), "target"),
233
+ )
234
+ }
235
+ return isVerticalBackEdge(from, to, direction)
236
+ ? verticalBackEdgePath(from, to, leftBoundary)
237
+ : verticalForwardEdgePath(from, to)
238
+ }
239
+
240
+ function sourceFanOutLane(
241
+ sourcePort: FlowchartPoint,
242
+ targetPorts: readonly FlowchartPoint[],
243
+ axis: DiagramAxis,
244
+ travel: DiagramDirection,
245
+ ): number {
246
+ const sourceCoordinate = coordinate(sourcePort, axis)
247
+ const unclamped = keepBefore(
248
+ advanceCoordinate(coordinate(sourcePort, axis), travel, BUS_CLEARANCE),
249
+ beforeNearestCoordinate(targetPorts, axis, travel, NODE_CLEARANCE),
250
+ travel,
251
+ )
252
+ return keepAfter(unclamped, sourceCoordinate, travel)
253
+ }
254
+
255
+ function reserveFanOutLane(
256
+ sourcePort: FlowchartPoint,
257
+ targetPorts: readonly FlowchartPoint[],
258
+ axis: DiagramAxis,
259
+ travel: DiagramDirection,
260
+ reserved: Set<number>,
261
+ ): number {
262
+ const preferred = sourceFanOutLane(sourcePort, targetPorts, axis, travel)
263
+ const boundary = beforeNearestCoordinate(targetPorts, axis, travel, NODE_CLEARANCE)
264
+ const source = coordinate(sourcePort, axis)
265
+ const available = (() => {
266
+ let checked = 0
267
+ for (let offset = 0; offset <= Math.abs(boundary - preferred) && checked < ROUTING_CANDIDATE_BUDGET; offset++) {
268
+ checked++
269
+ const candidate = advanceCoordinate(preferred, travel, offset)
270
+ if (
271
+ keepBefore(candidate, boundary, travel) === candidate &&
272
+ keepAfter(candidate, source, travel) === candidate &&
273
+ !reserved.has(candidate)
274
+ ) {
275
+ return candidate
276
+ }
277
+ }
278
+ for (let offset = 1; offset <= Math.abs(preferred - source) && checked < ROUTING_CANDIDATE_BUDGET; offset++) {
279
+ checked++
280
+ const candidate = advanceCoordinate(preferred, travel, -offset)
281
+ if (
282
+ keepBefore(candidate, boundary, travel) === candidate &&
283
+ keepAfter(candidate, source, travel) === candidate &&
284
+ !reserved.has(candidate)
285
+ ) {
286
+ return candidate
287
+ }
288
+ }
289
+ })()
290
+ const routeLane = available ?? preferred
291
+ reserved.add(routeLane)
292
+ return routeLane
293
+ }
294
+
295
+ function targetFanInLane(
296
+ sourcePorts: readonly FlowchartPoint[],
297
+ targetPort: FlowchartPoint,
298
+ axis: DiagramAxis,
299
+ travel: DiagramDirection,
300
+ ): number {
301
+ const targetCoordinate = coordinate(targetPort, axis)
302
+ const unclamped = keepAfter(
303
+ advanceCoordinate(coordinate(targetPort, axis), travel, -BUS_CLEARANCE),
304
+ afterFarthestCoordinate(sourcePorts, axis, travel, NODE_CLEARANCE),
305
+ travel,
306
+ )
307
+ return keepBefore(unclamped, advanceCoordinate(targetCoordinate, travel, -1), travel)
308
+ }
309
+
310
+ function portForTravel(bounds: FlowchartEndpointBounds, travel: DiagramDirection, role: PortRole): FlowchartPoint {
311
+ const side = role === "source" ? sideForDirection(travel) : oppositeSide(sideForDirection(travel))
312
+ return endpointSidePoint(bounds, side, role)
313
+ }
314
+
315
+ function subgraphContainsMember(
316
+ subgraphs: readonly FlowchartSubgraph[],
317
+ subgraph: FlowchartSubgraph,
318
+ endpointId: string,
319
+ ): boolean {
320
+ return (
321
+ subgraph.nodeIds.includes(endpointId) ||
322
+ subgraphs.some(
323
+ (child) =>
324
+ child.parentId === subgraph.id &&
325
+ (child.id === endpointId || subgraphContainsMember(subgraphs, child, endpointId)),
326
+ )
327
+ )
328
+ }
329
+
330
+ function horizontalForwardRecords(
331
+ edges: FlowchartEdge[],
332
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
333
+ direction: FlowchartDirection,
334
+ ): EdgeRecord[] {
335
+ const travel = direction === "RL" ? "left" : "right"
336
+ const records: EdgeRecord[] = []
337
+ for (const edge of edges) {
338
+ const source = endpoints.get(edge.from)
339
+ const target = endpoints.get(edge.to)
340
+ if (!source || !target) continue
341
+ const forward =
342
+ direction === "RL"
343
+ ? centerCoordinate(target, "x") < centerCoordinate(source, "x")
344
+ : centerCoordinate(target, "x") > centerCoordinate(source, "x")
345
+ if (!forward) continue
346
+ records.push({
347
+ edge,
348
+ sourcePort: portForTravel(source, travel, "source"),
349
+ targetPort: portForTravel(target, travel, "target"),
350
+ })
351
+ }
352
+ return records
353
+ }
354
+
355
+ function verticalForwardRecords(
356
+ edges: FlowchartEdge[],
357
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
358
+ direction: FlowchartDirection,
359
+ ): EdgeRecord[] {
360
+ const travel = direction === "BT" ? "up" : "down"
361
+ const records: EdgeRecord[] = []
362
+ for (const edge of edges) {
363
+ const source = endpoints.get(edge.from)
364
+ const target = endpoints.get(edge.to)
365
+ if (!source || !target) continue
366
+ const forward =
367
+ direction === "BT"
368
+ ? centerCoordinate(target, "y") < centerCoordinate(source, "y")
369
+ : centerCoordinate(target, "y") > centerCoordinate(source, "y")
370
+ if (!forward) continue
371
+ records.push({
372
+ edge,
373
+ sourcePort: portForTravel(source, travel, "source"),
374
+ targetPort: portForTravel(target, travel, "target"),
375
+ })
376
+ }
377
+ return records
378
+ }
379
+
380
+ function horizontalExitSubgraph(diagram: FlowchartDiagram, edge: FlowchartEdge): FlowchartSubgraph | undefined {
381
+ const subgraphs = diagram.subgraphs ?? []
382
+ for (const subgraph of [...subgraphs].reverse()) {
383
+ if (subgraph.direction !== "LR" && subgraph.direction !== "RL") continue
384
+ if (subgraph.id === edge.from || subgraph.id === edge.to) continue
385
+ if (subgraphContainsMember(subgraphs, subgraph, edge.from) && !subgraphContainsMember(subgraphs, subgraph, edge.to))
386
+ return subgraph
387
+ }
388
+ return undefined
389
+ }
390
+
391
+ function horizontalEntrySubgraph(diagram: FlowchartDiagram, edge: FlowchartEdge): FlowchartSubgraph | undefined {
392
+ const subgraphs = diagram.subgraphs ?? []
393
+ for (const subgraph of [...subgraphs].reverse()) {
394
+ if (subgraph.direction !== "LR" && subgraph.direction !== "RL") continue
395
+ if (subgraph.id === edge.from || subgraph.id === edge.to) continue
396
+ if (subgraphContainsMember(subgraphs, subgraph, edge.to) && !subgraphContainsMember(subgraphs, subgraph, edge.from))
397
+ return subgraph
398
+ }
399
+ return undefined
400
+ }
401
+
402
+ function horizontalSubgraphEntryTravel(subgraph: FlowchartSubgraph): HorizontalTravel {
403
+ return subgraph.direction === "RL" ? "left" : "right"
404
+ }
405
+
406
+ function horizontalSubgraphEntryLane(subgraph: FlowchartSubgraph, subgraphBound: FlowchartSubgraphBounds): number {
407
+ return subgraph.direction === "RL"
408
+ ? subgraphBound.left + subgraphBound.width + BUS_CLEARANCE
409
+ : subgraphBound.left - BUS_CLEARANCE
410
+ }
411
+
412
+ function horizontalSubgraphJoinY(from: FlowchartSubgraphBounds, targetSubgraphBound: FlowchartSubgraphBounds): number {
413
+ if (from.centerY <= targetSubgraphBound.centerY) {
414
+ const start = from.top + from.height
415
+ const end = targetSubgraphBound.top - 1
416
+ return start <= end ? Math.floor((start + end) / 2) : start
417
+ }
418
+
419
+ const start = targetSubgraphBound.top + targetSubgraphBound.height
420
+ const end = from.top - 1
421
+ return start <= end ? Math.floor((start + end) / 2) : end
422
+ }
423
+
424
+ function horizontalSubgraphExitJoinY(
425
+ from: FlowchartSubgraphBounds,
426
+ targetPort: FlowchartPoint,
427
+ targetBelow: boolean,
428
+ ): number {
429
+ if (targetBelow) {
430
+ const outside = from.top + from.height
431
+ const beforeTarget = targetPort.y - 1
432
+ const preferred = targetPort.y - BUS_CLEARANCE
433
+ return outside <= beforeTarget ? Math.min(Math.max(outside, preferred), beforeTarget) : beforeTarget
434
+ }
435
+
436
+ const outside = from.top - 1
437
+ const afterTarget = targetPort.y + 1
438
+ const preferred = targetPort.y + BUS_CLEARANCE
439
+ return afterTarget <= outside ? Math.max(Math.min(outside, preferred), afterTarget) : afterTarget
440
+ }
441
+
442
+ function groupRecords<Record>(records: readonly Record[], key: (record: Record) => string): Map<string, Record[]> {
443
+ const groups = new Map<string, Record[]>()
444
+ for (const record of records) {
445
+ const groupKey = key(record)
446
+ const group = groups.get(groupKey) ?? []
447
+ group.push(record)
448
+ groups.set(groupKey, group)
449
+ }
450
+ return groups
451
+ }
452
+
453
+ function fanRoute(
454
+ edge: FlowchartEdge,
455
+ sourcePort: FlowchartPoint,
456
+ targetPort: FlowchartPoint,
457
+ routeLane: DiagramLane,
458
+ ): FlowchartEdgeRoute {
459
+ return { edge, points: pathViaLane(sourcePort, routeLane, targetPort) }
460
+ }
461
+
462
+ function alignClusteredVerticalSources(records: readonly EdgeRecord[]): EdgeRecord[] {
463
+ const xs = records.map((record) => record.sourcePort.x)
464
+ const minX = Math.min(...xs)
465
+ const maxX = Math.max(...xs)
466
+ if (maxX - minX > 1) return [...records]
467
+
468
+ const x = Math.round(xs.reduce((total, value) => total + value, 0) / xs.length)
469
+ return records.map((record) => ({ ...record, sourcePort: { ...record.sourcePort, x } }))
470
+ }
471
+
472
+ function routeHorizontalFanOut(
473
+ records: readonly EdgeRecord[],
474
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
475
+ direction: FlowchartDirection,
476
+ handled: Set<FlowchartEdge>,
477
+ routes: FlowchartEdgeRoute[],
478
+ ): void {
479
+ const reservedBusLanes = new Set<number>()
480
+ const targetOwners = new Map<string, string>()
481
+ for (const [sourceId, sourceRecords] of groupRecords(records, (record) => record.edge.from)) {
482
+ if (sourceRecords.length < 2) continue
483
+ const travel = direction === "RL" ? "left" : "right"
484
+ const sourcePort = sourceRecords[0]!.sourcePort
485
+ const targetPorts = sourceRecords.map((record) => record.targetPort)
486
+
487
+ const busX = reserveFanOutLane(sourcePort, targetPorts, "x", travel, reservedBusLanes)
488
+ for (const record of sourceRecords) {
489
+ const targetOwner = targetOwners.get(record.edge.to)
490
+ targetOwners.set(record.edge.to, targetOwner ?? sourceId)
491
+ const target = endpoints.get(record.edge.to)
492
+ if (!targetOwner || targetOwner === sourceId || !target) {
493
+ routes.push(fanRoute(record.edge, sourcePort, record.targetPort, lane("x", busX)))
494
+ handled.add(record.edge)
495
+ continue
496
+ }
497
+
498
+ const targetSide = sourcePort.y < record.targetPort.y ? "top" : "bottom"
499
+ const targetPoint = endpointSidePoint(target, targetSide, "target")
500
+ const approach = shiftPoint(targetPoint, targetSide === "top" ? "up" : "down")
501
+ routes.push({
502
+ edge: record.edge,
503
+ points: pathThrough([
504
+ sourcePort,
505
+ { x: busX, y: sourcePort.y },
506
+ { x: busX, y: approach.y },
507
+ approach,
508
+ targetPoint,
509
+ ]),
510
+ })
511
+ handled.add(record.edge)
512
+ }
513
+ }
514
+ }
515
+
516
+ function routeHorizontalFanIn(
517
+ records: readonly EdgeRecord[],
518
+ direction: FlowchartDirection,
519
+ handled: Set<FlowchartEdge>,
520
+ routes: FlowchartEdgeRoute[],
521
+ ): void {
522
+ const unhandledRecords = records.filter((record) => !handled.has(record.edge))
523
+ for (const targetRecords of groupRecords(unhandledRecords, (record) => record.edge.to).values()) {
524
+ if (targetRecords.length < 2) continue
525
+ const travel = direction === "RL" ? "left" : "right"
526
+ const targetPort = targetRecords[0]!.targetPort
527
+ const sourcePorts = targetRecords.map((record) => record.sourcePort)
528
+
529
+ const busX = targetFanInLane(sourcePorts, targetPort, "x", travel)
530
+ for (const record of targetRecords) {
531
+ routes.push(fanRoute(record.edge, record.sourcePort, targetPort, lane("x", busX)))
532
+ handled.add(record.edge)
533
+ }
534
+ }
535
+ }
536
+
537
+ function routeVerticalFanOut(
538
+ records: readonly EdgeRecord[],
539
+ direction: FlowchartDirection,
540
+ handled: Set<FlowchartEdge>,
541
+ routes: FlowchartEdgeRoute[],
542
+ ): void {
543
+ for (const sourceRecords of groupRecords(records, (record) => record.edge.from).values()) {
544
+ if (sourceRecords.length < 2) continue
545
+ const travel = direction === "BT" ? "up" : "down"
546
+ const sourcePort = sourceRecords[0]!.sourcePort
547
+ const targetPorts = sourceRecords.map((record) => record.targetPort)
548
+
549
+ const busY = sourceFanOutLane(sourcePort, targetPorts, "y", travel)
550
+ for (const record of sourceRecords) {
551
+ routes.push(fanRoute(record.edge, sourcePort, record.targetPort, lane("y", busY)))
552
+ handled.add(record.edge)
553
+ }
554
+ }
555
+ }
556
+
557
+ function routeVerticalFanIn(
558
+ records: readonly EdgeRecord[],
559
+ direction: FlowchartDirection,
560
+ handled: Set<FlowchartEdge>,
561
+ routes: FlowchartEdgeRoute[],
562
+ ): void {
563
+ const unhandledRecords = records.filter((record) => !handled.has(record.edge))
564
+ for (const unalignedTargetRecords of groupRecords(unhandledRecords, (record) => record.edge.to).values()) {
565
+ const targetRecords = alignClusteredVerticalSources(unalignedTargetRecords)
566
+ if (targetRecords.length < 2) continue
567
+ const travel = direction === "BT" ? "up" : "down"
568
+ const targetPort = targetRecords[0]!.targetPort
569
+ const sourcePorts = targetRecords.map((record) => record.sourcePort)
570
+
571
+ const busY = targetFanInLane(sourcePorts, targetPort, "y", travel)
572
+ for (const record of targetRecords) {
573
+ routes.push(fanRoute(record.edge, record.sourcePort, targetPort, lane("y", busY)))
574
+ handled.add(record.edge)
575
+ }
576
+ }
577
+ }
578
+
579
+ function routeParallelEdges(
580
+ diagram: FlowchartDiagram,
581
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
582
+ directionForEdge: (edge: FlowchartEdge) => FlowchartDirection,
583
+ directionAligned: boolean,
584
+ handled: Set<FlowchartEdge>,
585
+ routes: FlowchartEdgeRoute[],
586
+ ): void {
587
+ const groups = groupRecords(diagram.edges, (edge) => `${edge.from}:${edge.to}`)
588
+ for (const edges of groups.values()) {
589
+ if (edges.length < 2) continue
590
+ const from = endpoints.get(edges[0]!.from)
591
+ const to = endpoints.get(edges[0]!.to)
592
+ if (!from || !to) continue
593
+ if (from.id === to.id) {
594
+ let laneOffset = 0
595
+ for (const edge of edges) {
596
+ routes.push({ edge, points: selfEdgePath(from, laneOffset) })
597
+ handled.add(edge)
598
+ laneOffset++
599
+ }
600
+ continue
601
+ }
602
+ const parallelAxis =
603
+ directionAligned && isVerticalDirection(directionForEdge(edges[0]!)) ? "x" : parallelLaneAxis(from, to)
604
+ let previousRoute: FlowchartEdgeRoute | undefined
605
+ for (const edge of edges) {
606
+ const height = labelHeight(edge)
607
+ const laneCoordinate =
608
+ parallelAxis === "x"
609
+ ? previousRoute
610
+ ? rightRenderExtent(previousRoute) + NODE_CLEARANCE
611
+ : Math.max(boundsSidePoint(from, "right").x, boundsSidePoint(to, "right").x) + (directionAligned ? 1 : 0)
612
+ : previousRoute
613
+ ? Math.max(...previousRoute.points.map((point) => point.y)) + (height > 1 ? height + 1 : 1)
614
+ : Math.max(boundsSidePoint(from, "bottom").y, boundsSidePoint(to, "bottom").y) + (height > 1 ? height : 0)
615
+ const route: FlowchartEdgeRoute = {
616
+ edge,
617
+ points: parallelEdgePath(from, to, parallelAxis, laneCoordinate),
618
+ labelAxis: parallelAxis === "x" ? "y" : "x",
619
+ }
620
+ routes.push(route)
621
+ handled.add(edge)
622
+ previousRoute = route
623
+ }
624
+ }
625
+ }
626
+
627
+ function routeHorizontalSubgraphExitFanIn(
628
+ diagram: FlowchartDiagram,
629
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
630
+ subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
631
+ handled: Set<FlowchartEdge>,
632
+ routes: FlowchartEdgeRoute[],
633
+ ): void {
634
+ if (!subgraphBounds) return
635
+
636
+ const groups = new Map<
637
+ string,
638
+ { edge: FlowchartEdge; subgraph: FlowchartSubgraph; source: FlowchartEndpointBounds }[]
639
+ >()
640
+ for (const edge of diagram.edges) {
641
+ if (handled.has(edge)) continue
642
+ const subgraph = horizontalExitSubgraph(diagram, edge)
643
+ const source = endpoints.get(edge.from)
644
+ const target = endpoints.get(edge.to)
645
+ if (!subgraph || !source || !target) continue
646
+
647
+ const key = `${subgraph.id}:${edge.to}`
648
+ const group = groups.get(key) ?? []
649
+ group.push({ edge, subgraph, source })
650
+ groups.set(key, group)
651
+ }
652
+
653
+ for (const group of groups.values()) {
654
+ const subgraph = group[0]!.subgraph
655
+ const subgraphBound = subgraphBounds.get(subgraph.id)
656
+ const target = endpoints.get(group[0]!.edge.to)
657
+ if (!subgraphBound || !target) continue
658
+
659
+ const travel: HorizontalTravel = subgraph.direction === "RL" ? "left" : "right"
660
+ const busX =
661
+ subgraph.direction === "RL"
662
+ ? subgraphBound.left - BUS_CLEARANCE
663
+ : subgraphBound.left + subgraphBound.width + BUS_CLEARANCE
664
+ const targetSubgraph = horizontalEntrySubgraph(diagram, group[0]!.edge)
665
+ const targetSubgraphBound = targetSubgraph ? subgraphBounds.get(targetSubgraph.id) : undefined
666
+ const targetBelow = target.centerY >= subgraphBound.centerY
667
+ const targetPort = targetSubgraph
668
+ ? portForTravel(target, horizontalSubgraphEntryTravel(targetSubgraph), "target")
669
+ : endpointSidePoint(target, targetBelow ? "top" : "bottom", "target")
670
+ const joinY = targetSubgraphBound
671
+ ? horizontalSubgraphJoinY(subgraphBound, targetSubgraphBound)
672
+ : horizontalSubgraphExitJoinY(subgraphBound, targetPort, targetBelow)
673
+ const entryX =
674
+ targetSubgraph && targetSubgraphBound
675
+ ? horizontalSubgraphEntryLane(targetSubgraph, targetSubgraphBound)
676
+ : targetPort.x
677
+
678
+ for (const record of group) {
679
+ const sourcePort = portForTravel(record.source, travel, "source")
680
+ routes.push({
681
+ edge: record.edge,
682
+ points: pathThrough([
683
+ sourcePort,
684
+ { x: busX, y: sourcePort.y },
685
+ { x: busX, y: joinY },
686
+ { x: entryX, y: joinY },
687
+ { x: entryX, y: targetPort.y },
688
+ targetPort,
689
+ ]),
690
+ })
691
+ handled.add(record.edge)
692
+ }
693
+ }
694
+ }
695
+
696
+ function routeHorizontalSubgraphEntries(
697
+ diagram: FlowchartDiagram,
698
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
699
+ subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
700
+ handled: Set<FlowchartEdge>,
701
+ routes: FlowchartEdgeRoute[],
702
+ ): void {
703
+ if (!subgraphBounds) return
704
+
705
+ for (const edge of diagram.edges) {
706
+ if (handled.has(edge)) continue
707
+ const subgraph = horizontalEntrySubgraph(diagram, edge)
708
+ const subgraphBound = subgraph ? subgraphBounds.get(subgraph.id) : undefined
709
+ const from = endpoints.get(edge.from)
710
+ const to = endpoints.get(edge.to)
711
+ if (!subgraph || !subgraphBound || !from || !to) continue
712
+
713
+ const targetPort = portForTravel(to, horizontalSubgraphEntryTravel(subgraph), "target")
714
+ const entryX = horizontalSubgraphEntryLane(subgraph, subgraphBound)
715
+ const travel = verticalTravel(from, to)
716
+ const sourcePort = portForTravel(from, travel, "source")
717
+ routes.push({
718
+ edge,
719
+ points: pathThrough([sourcePort, { x: entryX, y: sourcePort.y }, { x: entryX, y: targetPort.y }, targetPort]),
720
+ })
721
+ handled.add(edge)
722
+ }
723
+ }
724
+
725
+ function pathIntersectsBounds(
726
+ points: readonly FlowchartPoint[],
727
+ bounds: { left: number; top: number; width: number; height: number },
728
+ allowedContact: "source" | "target" | "both" | undefined = undefined,
729
+ ): boolean {
730
+ const right = bounds.left + bounds.width - 1
731
+ const bottom = bounds.top + bounds.height - 1
732
+ for (let index = 1; index < points.length; index++) {
733
+ const from = points[index - 1]!
734
+ const to = points[index]!
735
+ if (from.x === to.x) {
736
+ if (from.x < bounds.left || from.x > right) continue
737
+ const overlapTop = Math.max(Math.min(from.y, to.y), bounds.top)
738
+ const overlapBottom = Math.min(Math.max(from.y, to.y), bottom)
739
+ if (overlapTop > overlapBottom) continue
740
+ const sourceContact =
741
+ (allowedContact === "source" || allowedContact === "both") &&
742
+ index === 1 &&
743
+ overlapTop === overlapBottom &&
744
+ from.x === points[0]!.x &&
745
+ overlapTop === points[0]!.y
746
+ const targetContact =
747
+ (allowedContact === "target" || allowedContact === "both") &&
748
+ index === points.length - 1 &&
749
+ overlapTop === overlapBottom &&
750
+ to.x === points.at(-1)!.x &&
751
+ overlapTop === points.at(-1)!.y
752
+ if (!sourceContact && !targetContact) return true
753
+ continue
754
+ }
755
+ if (from.y < bounds.top || from.y > bottom) continue
756
+ const overlapLeft = Math.max(Math.min(from.x, to.x), bounds.left)
757
+ const overlapRight = Math.min(Math.max(from.x, to.x), right)
758
+ if (overlapLeft > overlapRight) continue
759
+ const sourceContact =
760
+ (allowedContact === "source" || allowedContact === "both") &&
761
+ index === 1 &&
762
+ overlapLeft === overlapRight &&
763
+ overlapLeft === points[0]!.x &&
764
+ from.y === points[0]!.y
765
+ const targetContact =
766
+ (allowedContact === "target" || allowedContact === "both") &&
767
+ index === points.length - 1 &&
768
+ overlapLeft === overlapRight &&
769
+ overlapLeft === points.at(-1)!.x &&
770
+ to.y === points.at(-1)!.y
771
+ if (!sourceContact && !targetContact) return true
772
+ }
773
+ return false
774
+ }
775
+
776
+ function labelIntersectsBounds(
777
+ label: FlowchartEdgeLabelLayout | undefined,
778
+ bounds: { left: number; top: number; width: number; height: number },
779
+ ): boolean {
780
+ if (!label) return false
781
+ return (
782
+ label.point.x <= bounds.left + bounds.width - 1 &&
783
+ label.point.x + label.width - 1 >= bounds.left &&
784
+ label.point.y <= bounds.top + bounds.height - 1 &&
785
+ label.point.y + label.height - 1 >= bounds.top
786
+ )
787
+ }
788
+
789
+ function labelIntersectsSubgraphFrame(
790
+ label: FlowchartEdgeLabelLayout | undefined,
791
+ bounds: FlowchartSubgraphBounds,
792
+ ): boolean {
793
+ if (!label) return false
794
+ const labelRight = label.point.x + label.width - 1
795
+ const labelBottom = label.point.y + label.height - 1
796
+ const right = bounds.left + bounds.width - 1
797
+ const bottom = bounds.top + bounds.height - 1
798
+ return (
799
+ (label.point.x <= right &&
800
+ labelRight >= bounds.left &&
801
+ ((label.point.y <= bounds.top && labelBottom >= bounds.top) ||
802
+ (label.point.y <= bottom && labelBottom >= bottom))) ||
803
+ (label.point.y <= bottom &&
804
+ labelBottom >= bounds.top &&
805
+ ((label.point.x <= bounds.left && labelRight >= bounds.left) || (label.point.x <= right && labelRight >= right)))
806
+ )
807
+ }
808
+
809
+ function routeLength(route: FlowchartEdgeRoute): number {
810
+ let length = 0
811
+ for (let index = 1; index < route.points.length; index++) {
812
+ const from = route.points[index - 1]!
813
+ const to = route.points[index]!
814
+ length += Math.abs(to.x - from.x) + Math.abs(to.y - from.y)
815
+ }
816
+ return length
817
+ }
818
+
819
+ function labelIntersectsLabels(
820
+ label: FlowchartEdgeLabelLayout | undefined,
821
+ otherLabels: readonly FlowchartEdgeLabelLayout[],
822
+ ): boolean {
823
+ if (!label) return false
824
+ return otherLabels.some((otherLabel) =>
825
+ labelIntersectsBounds(label, {
826
+ left: otherLabel.point.x,
827
+ top: otherLabel.point.y,
828
+ width: otherLabel.width,
829
+ height: otherLabel.height,
830
+ }),
831
+ )
832
+ }
833
+
834
+ function labelIntersectsRoutePaths(
835
+ label: FlowchartEdgeLabelLayout | undefined,
836
+ routes: readonly FlowchartEdgeRoute[],
837
+ ): boolean {
838
+ if (!label) return false
839
+ return label.lines.some((line, lineIndex) => {
840
+ const width = diagramTextWidth(line) - 2
841
+ if (width <= 0) return false
842
+ return routes.some((route) =>
843
+ pathIntersectsBounds(route.points, {
844
+ left: label.point.x + 1,
845
+ top: label.point.y + lineIndex,
846
+ width,
847
+ height: 1,
848
+ }),
849
+ )
850
+ })
851
+ }
852
+
853
+ function routeIntersectsLabels(route: FlowchartEdgeRoute, labels: readonly FlowchartEdgeLabelLayout[]): boolean {
854
+ return labels.some((label) =>
855
+ label.lines.some((line, lineIndex) => {
856
+ const width = diagramTextWidth(line) - 2
857
+ return (
858
+ width > 0 &&
859
+ pathIntersectsBounds(route.points, {
860
+ left: label.point.x + 1,
861
+ top: label.point.y + lineIndex,
862
+ width,
863
+ height: 1,
864
+ })
865
+ )
866
+ }),
867
+ )
868
+ }
869
+
870
+ function pathsIntersect(left: readonly FlowchartPoint[], right: readonly FlowchartPoint[]): boolean {
871
+ const occupied = new Set(orthogonalPathPoints(left).map((point) => `${point.x}:${point.y}`))
872
+ return orthogonalPathPoints(right).some((point) => occupied.has(`${point.x}:${point.y}`))
873
+ }
874
+
875
+ function endpointDisjoint(left: FlowchartEdge, right: FlowchartEdge): boolean {
876
+ return left.from !== right.from && left.from !== right.to && left.to !== right.from && left.to !== right.to
877
+ }
878
+
879
+ function endpointConflictsWithRoutes(route: FlowchartEdgeRoute, otherRoutes: readonly FlowchartEdgeRoute[]): boolean {
880
+ const source = route.points[0]
881
+ const target = route.points.at(-1)
882
+ if (!source || !target) return false
883
+ return otherRoutes.some((other) => {
884
+ const otherSource = other.points[0]
885
+ const otherTarget = other.points.at(-1)
886
+ return (
887
+ (otherSource && target.x === otherSource.x && target.y === otherSource.y) ||
888
+ (otherTarget && source.x === otherTarget.x && source.y === otherTarget.y)
889
+ )
890
+ })
891
+ }
892
+
893
+ function pathRunsAlongFrame(points: readonly FlowchartPoint[], bounds: FlowchartSubgraphBounds): boolean {
894
+ const right = bounds.left + bounds.width - 1
895
+ const bottom = bounds.top + bounds.height - 1
896
+ for (let index = 1; index < points.length; index++) {
897
+ const segment = segmentBetween(points[index - 1]!, points[index]!)
898
+ if (!segment) continue
899
+ const span = segmentSpan(segment)
900
+ if (
901
+ segment.axis === "x" &&
902
+ (segment.from.y === bounds.top || segment.from.y === bottom) &&
903
+ Math.min(span.end, right) > Math.max(span.start, bounds.left)
904
+ ) {
905
+ return true
906
+ }
907
+ if (
908
+ segment.axis === "y" &&
909
+ (segment.from.x === bounds.left || segment.from.x === right) &&
910
+ Math.min(span.end, bottom) > Math.max(span.start, bounds.top)
911
+ ) {
912
+ return true
913
+ }
914
+ }
915
+ return false
916
+ }
917
+
918
+ function subgraphTitleBounds(bounds: FlowchartSubgraphBounds): {
919
+ left: number
920
+ top: number
921
+ width: number
922
+ height: number
923
+ } {
924
+ const lines = splitDiagramLines(bounds.label)
925
+ return {
926
+ left: bounds.left + 2,
927
+ top: bounds.labelSide === "top" ? bounds.top : bounds.top + bounds.height - lines.length,
928
+ width: Math.max(...lines.map((line) => diagramTextWidth(` ${line} `))),
929
+ height: lines.length,
930
+ }
931
+ }
932
+
933
+ function avoidNodeObstacles(
934
+ route: FlowchartEdgeRoute,
935
+ routes: readonly FlowchartEdgeRoute[],
936
+ bounds: ReadonlyMap<string, FlowchartNodeBounds>,
937
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
938
+ subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
939
+ routeIndex: number,
940
+ diagram: FlowchartDiagram,
941
+ ): FlowchartEdgeRoute {
942
+ const allNodeBounds = [...bounds.values()]
943
+ const allSubgraphBounds = [...(subgraphBounds?.values() ?? [])]
944
+ const subgraphs = diagram.subgraphs ?? []
945
+ const contains = (subgraph: FlowchartSubgraph, endpointId: string): boolean =>
946
+ subgraphContainsMember(subgraphs, subgraph, endpointId)
947
+ const owner = [...subgraphs].reverse().find((subgraph) => {
948
+ if (!contains(subgraph, route.edge.from) || !contains(subgraph, route.edge.to)) return false
949
+ const children = subgraphs.filter((child) => child.parentId === subgraph.id)
950
+ return (
951
+ children.some((child) => child.id === route.edge.from || contains(child, route.edge.from)) &&
952
+ children.some((child) => child.id === route.edge.to || contains(child, route.edge.to)) &&
953
+ !children.some(
954
+ (child) =>
955
+ (child.id === route.edge.from || contains(child, route.edge.from)) &&
956
+ (child.id === route.edge.to || contains(child, route.edge.to)),
957
+ )
958
+ )
959
+ })
960
+ const ownerBounds = owner ? subgraphBounds?.get(owner.id) : undefined
961
+ const leavesOwner = (candidate: FlowchartEdgeRoute): boolean =>
962
+ Boolean(
963
+ ownerBounds &&
964
+ candidate.points.some(
965
+ (point) =>
966
+ point.x <= ownerBounds.left ||
967
+ point.x >= ownerBounds.left + ownerBounds.width - 1 ||
968
+ point.y <= ownerBounds.top ||
969
+ point.y >= ownerBounds.top + ownerBounds.height - 1,
970
+ ),
971
+ )
972
+ const otherRoutes = routes.filter((_, index) => index !== routeIndex)
973
+ const otherLabels = otherRoutes.flatMap((otherRoute) =>
974
+ otherRoute.edge.label ? [flowchartRouteLabelLayout(otherRoute, diagramTextWidth)] : [],
975
+ )
976
+ const intersectsNode = (candidate: FlowchartEdgeRoute): boolean =>
977
+ allNodeBounds.some((bound) => {
978
+ const isSource = bound.id === route.edge.from
979
+ const isTarget = bound.id === route.edge.to
980
+ const allowedContact = isSource && isTarget ? "both" : isSource ? "source" : isTarget ? "target" : undefined
981
+ return pathIntersectsBounds(candidate.points, bound, allowedContact)
982
+ })
983
+ const sourceSubgraph = bounds.has(route.edge.from) ? undefined : subgraphBounds?.get(route.edge.from)
984
+ const intersectsSourceTitle = (candidate: FlowchartEdgeRoute): boolean => {
985
+ if (!sourceSubgraph || sourceSubgraph.label.length === 0 || !candidate.points[0]) return false
986
+ const connector = flowchartSourceConnector(sourceSubgraph, candidate.points[0])
987
+ const title = subgraphTitleBounds(sourceSubgraph)
988
+ return (
989
+ connector.y >= title.top &&
990
+ connector.y < title.top + title.height &&
991
+ connector.x >= title.left &&
992
+ connector.x < title.left + title.width
993
+ )
994
+ }
995
+ const intersectsStructuralObstacle = (candidate: FlowchartEdgeRoute): boolean =>
996
+ intersectsNode(candidate) ||
997
+ intersectsSourceTitle(candidate) ||
998
+ allSubgraphBounds.some(
999
+ (bound) =>
1000
+ pathRunsAlongFrame(candidate.points, bound) ||
1001
+ (bound.label.length > 0 && pathIntersectsBounds(candidate.points, subgraphTitleBounds(bound))),
1002
+ )
1003
+ const intersectsRoutingObstacle = (candidate: FlowchartEdgeRoute): boolean =>
1004
+ intersectsStructuralObstacle(candidate) ||
1005
+ endpointConflictsWithRoutes(candidate, otherRoutes) ||
1006
+ otherRoutes.some(
1007
+ (other) => endpointDisjoint(candidate.edge, other.edge) && pathsIntersect(candidate.points, other.points),
1008
+ )
1009
+ const intersectsObstacle = (candidate: FlowchartEdgeRoute): boolean => {
1010
+ const label = candidate.edge.label ? flowchartRouteLabelLayout(candidate, diagramTextWidth) : undefined
1011
+ return (
1012
+ leavesOwner(candidate) ||
1013
+ intersectsRoutingObstacle(candidate) ||
1014
+ allNodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
1015
+ allSubgraphBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
1016
+ labelIntersectsLabels(label, otherLabels) ||
1017
+ labelIntersectsRoutePaths(label, otherRoutes) ||
1018
+ routeIntersectsLabels(candidate, otherLabels)
1019
+ )
1020
+ }
1021
+ if (!intersectsObstacle(route)) return route
1022
+
1023
+ const from = endpoints.get(route.edge.from)
1024
+ const to = endpoints.get(route.edge.to)
1025
+ if (!from || !to) return route
1026
+ const routingBounds = [...allNodeBounds, ...allSubgraphBounds]
1027
+ const rightBusX = Math.max(...routingBounds.map((bound) => bound.left + bound.width - 1)) + BUS_CLEARANCE
1028
+ const leftBusX = Math.min(...routingBounds.map((bound) => bound.left)) - BUS_CLEARANCE
1029
+ const topBusY = Math.min(...routingBounds.map((bound) => bound.top)) - BUS_CLEARANCE
1030
+ const bottomBusY = Math.max(...routingBounds.map((bound) => bound.top + bound.height - 1)) + BUS_CLEARANCE
1031
+ const rightBusXs = [
1032
+ ...new Set([
1033
+ rightBusX,
1034
+ ...(ownerBounds ? [ownerBounds.left + ownerBounds.width - 2] : []),
1035
+ ...otherLabels.map((label) => Math.max(rightBusX, label.point.x + label.width - 1 + NODE_CLEARANCE)),
1036
+ ]),
1037
+ ].sort((left, right) => left - right)
1038
+ const leftBusXs = [
1039
+ ...new Set([
1040
+ leftBusX,
1041
+ ...(ownerBounds ? [ownerBounds.left + 1] : []),
1042
+ ...otherLabels.map((label) => Math.min(leftBusX, label.point.x - NODE_CLEARANCE)),
1043
+ ]),
1044
+ ].sort((left, right) => right - left)
1045
+ const topBusYs = [
1046
+ ...new Set([
1047
+ topBusY,
1048
+ ...(ownerBounds ? [ownerBounds.top + 1] : []),
1049
+ ...otherLabels.map((label) => Math.min(topBusY, label.point.y - NODE_CLEARANCE)),
1050
+ ]),
1051
+ ].sort((left, right) => right - left)
1052
+ const bottomBusYs = [
1053
+ ...new Set([
1054
+ bottomBusY,
1055
+ ...(ownerBounds ? [ownerBounds.top + ownerBounds.height - 2] : []),
1056
+ ...otherLabels.map((label) => Math.max(bottomBusY, label.point.y + label.height - 1 + NODE_CLEARANCE)),
1057
+ ]),
1058
+ ].sort((left, right) => left - right)
1059
+ const busLimit = Math.max(1, Math.floor(Math.sqrt(ROUTING_CANDIDATE_BUDGET / 4)))
1060
+ const candidateLeftBusXs = leftBusXs.length > busLimit ? leftBusXs.slice(0, busLimit) : leftBusXs
1061
+ const candidateRightBusXs = rightBusXs.length > busLimit ? rightBusXs.slice(0, busLimit) : rightBusXs
1062
+ const candidateTopBusYs = topBusYs.length > busLimit ? topBusYs.slice(0, busLimit) : topBusYs
1063
+ const candidateBottomBusYs = bottomBusYs.length > busLimit ? bottomBusYs.slice(0, busLimit) : bottomBusYs
1064
+ const buses = [
1065
+ ...candidateLeftBusXs.map((coordinate) => lane("x", coordinate)),
1066
+ ...candidateRightBusXs.map((coordinate) => lane("x", coordinate)),
1067
+ ...candidateTopBusYs.map((coordinate) => lane("y", coordinate)),
1068
+ ...candidateBottomBusYs.map((coordinate) => lane("y", coordinate)),
1069
+ ]
1070
+ const routeViaBus = (start: FlowchartPoint, targetSide: DiagramSide, bus: DiagramLane): FlowchartEdgeRoute => {
1071
+ const end = boundsSidePoint(to, targetSide)
1072
+ const approach = shiftPoint(
1073
+ end,
1074
+ targetSide === "left" ? "left" : targetSide === "right" ? "right" : targetSide === "top" ? "up" : "down",
1075
+ )
1076
+ return {
1077
+ ...route,
1078
+ labelAxis: route.labelAxis === undefined ? undefined : bus.axis === "x" ? "y" : "x",
1079
+ points:
1080
+ bus.axis === "x"
1081
+ ? pathThrough([start, { x: bus.coordinate, y: start.y }, { x: bus.coordinate, y: approach.y }, approach, end])
1082
+ : pathThrough([
1083
+ start,
1084
+ { x: start.x, y: bus.coordinate },
1085
+ { x: approach.x, y: bus.coordinate },
1086
+ approach,
1087
+ end,
1088
+ ]),
1089
+ }
1090
+ }
1091
+ const selfLoops =
1092
+ from.id !== to.id
1093
+ ? []
1094
+ : [
1095
+ ...candidateRightBusXs.flatMap((busX) =>
1096
+ candidateBottomBusYs.map(
1097
+ (busY): FlowchartEdgeRoute => ({
1098
+ ...route,
1099
+ points: pathThrough([
1100
+ boundsSidePoint(from, "right"),
1101
+ { x: busX, y: from.centerY },
1102
+ { x: busX, y: busY },
1103
+ { x: from.centerX, y: busY },
1104
+ boundsSidePoint(from, "bottom"),
1105
+ ]),
1106
+ }),
1107
+ ),
1108
+ ),
1109
+ ...candidateBottomBusYs.flatMap((busY) =>
1110
+ candidateLeftBusXs.map(
1111
+ (busX): FlowchartEdgeRoute => ({
1112
+ ...route,
1113
+ points: pathThrough([
1114
+ boundsSidePoint(from, "bottom"),
1115
+ { x: from.centerX, y: busY },
1116
+ { x: busX, y: busY },
1117
+ { x: busX, y: from.centerY },
1118
+ boundsSidePoint(from, "left"),
1119
+ ]),
1120
+ }),
1121
+ ),
1122
+ ),
1123
+ ...candidateLeftBusXs.flatMap((busX) =>
1124
+ candidateTopBusYs.map(
1125
+ (busY): FlowchartEdgeRoute => ({
1126
+ ...route,
1127
+ points: pathThrough([
1128
+ boundsSidePoint(from, "left"),
1129
+ { x: busX, y: from.centerY },
1130
+ { x: busX, y: busY },
1131
+ { x: from.centerX, y: busY },
1132
+ boundsSidePoint(from, "top"),
1133
+ ]),
1134
+ }),
1135
+ ),
1136
+ ),
1137
+ ...candidateTopBusYs.flatMap((busY) =>
1138
+ candidateRightBusXs.map(
1139
+ (busX): FlowchartEdgeRoute => ({
1140
+ ...route,
1141
+ points: pathThrough([
1142
+ boundsSidePoint(from, "top"),
1143
+ { x: from.centerX, y: busY },
1144
+ { x: busX, y: busY },
1145
+ { x: busX, y: from.centerY },
1146
+ boundsSidePoint(from, "right"),
1147
+ ]),
1148
+ }),
1149
+ ),
1150
+ ),
1151
+ ]
1152
+ const targetSides = ["left", "right", "top", "bottom"] satisfies DiagramSide[]
1153
+ const shortest = (candidates: FlowchartEdgeRoute[], accept: (candidate: FlowchartEdgeRoute) => boolean) =>
1154
+ candidates.filter(accept).sort((left, right) => routeLength(left) - routeLength(right))[0]
1155
+ if (from.id === to.id)
1156
+ return (
1157
+ shortest(selfLoops, (candidate) => !intersectsObstacle(candidate)) ??
1158
+ shortest(selfLoops, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1159
+ route
1160
+ )
1161
+ const currentTargetSide = sideForOutsidePoint(to, route.points.at(-1)!)
1162
+ const preservedTargets = buses.map((bus) => routeViaBus(route.points[0]!, currentTargetSide, bus))
1163
+ const sameSides: FlowchartEdgeRoute[] = [
1164
+ ...candidateRightBusXs.map(
1165
+ (busX): FlowchartEdgeRoute => ({
1166
+ ...route,
1167
+ labelAxis: route.labelAxis === undefined ? undefined : "y",
1168
+ points: pathViaLane(
1169
+ endpointSidePoint(from, "right", "source"),
1170
+ lane("x", busX),
1171
+ endpointSidePoint(to, "right", "target"),
1172
+ ),
1173
+ }),
1174
+ ),
1175
+ ...candidateLeftBusXs.map(
1176
+ (busX): FlowchartEdgeRoute => ({
1177
+ ...route,
1178
+ labelAxis: route.labelAxis === undefined ? undefined : "y",
1179
+ points: pathViaLane(
1180
+ endpointSidePoint(from, "left", "source"),
1181
+ lane("x", busX),
1182
+ endpointSidePoint(to, "left", "target"),
1183
+ ),
1184
+ }),
1185
+ ),
1186
+ ...candidateTopBusYs.map(
1187
+ (busY): FlowchartEdgeRoute => ({
1188
+ ...route,
1189
+ labelAxis: route.labelAxis === undefined ? undefined : "x",
1190
+ points: pathViaLane(
1191
+ endpointSidePoint(from, "top", "source"),
1192
+ lane("y", busY),
1193
+ endpointSidePoint(to, "top", "target"),
1194
+ ),
1195
+ }),
1196
+ ),
1197
+ ...candidateBottomBusYs.map(
1198
+ (busY): FlowchartEdgeRoute => ({
1199
+ ...route,
1200
+ labelAxis: route.labelAxis === undefined ? undefined : "x",
1201
+ points: pathViaLane(
1202
+ endpointSidePoint(from, "bottom", "source"),
1203
+ lane("y", busY),
1204
+ endpointSidePoint(to, "bottom", "target"),
1205
+ ),
1206
+ }),
1207
+ ),
1208
+ ]
1209
+ const preservedSources = targetSides.flatMap((targetSide) =>
1210
+ buses.map((bus) => routeViaBus(route.points[0]!, targetSide, bus)),
1211
+ )
1212
+ const attachments = targetSides.flatMap((sourceSide) =>
1213
+ targetSides.flatMap((targetSide) =>
1214
+ buses.map((bus) => routeViaBus(endpointSidePoint(from, sourceSide, "source"), targetSide, bus)),
1215
+ ),
1216
+ )
1217
+ if (subgraphBounds) {
1218
+ return (
1219
+ shortest(preservedTargets, (candidate) => !intersectsObstacle(candidate)) ??
1220
+ shortest(sameSides, (candidate) => !intersectsObstacle(candidate)) ??
1221
+ shortest(preservedSources, (candidate) => !intersectsObstacle(candidate)) ??
1222
+ shortest(attachments, (candidate) => !intersectsObstacle(candidate)) ??
1223
+ shortest(preservedSources, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1224
+ shortest(attachments, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1225
+ route
1226
+ )
1227
+ }
1228
+ return (
1229
+ sameSides.find((candidate) => !intersectsObstacle(candidate)) ??
1230
+ shortest(preservedTargets, (candidate) => !intersectsObstacle(candidate)) ??
1231
+ attachments.find((candidate) => !intersectsObstacle(candidate)) ??
1232
+ shortest(preservedSources, (candidate) => !intersectsObstacle(candidate)) ??
1233
+ shortest(attachments, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1234
+ shortest(preservedSources, (candidate) => !intersectsStructuralObstacle(candidate)) ??
1235
+ route
1236
+ )
1237
+ }
1238
+
1239
+ function avoidLabelOverlap(
1240
+ route: FlowchartEdgeRoute,
1241
+ otherRoutes: readonly FlowchartEdgeRoute[],
1242
+ bounds: ReadonlyMap<string, FlowchartNodeBounds>,
1243
+ endpoints: ReadonlyMap<string, FlowchartEndpointBounds>,
1244
+ subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds> | undefined,
1245
+ targetWidth?: number,
1246
+ includeLabelWidth = true,
1247
+ ): FlowchartEdgeRoute {
1248
+ if (!route.edge.label) return route
1249
+ const nodeBounds = [...bounds.values()]
1250
+ const frameBounds = [...(subgraphBounds?.values() ?? [])]
1251
+ const otherLabels = otherRoutes.flatMap((other) =>
1252
+ other.edge.label ? [flowchartRouteLabelLayout(other, diagramTextWidth)] : [],
1253
+ )
1254
+ const otherConnectorBounds = otherRoutes.flatMap((other) => {
1255
+ const source = endpoints.get(other.edge.from)
1256
+ const sourcePoint = other.points[0]
1257
+ if (!source || !sourcePoint) return []
1258
+ const connector = flowchartSourceConnector(source, sourcePoint)
1259
+ return [
1260
+ { left: connector.x, top: connector.y, width: 1, height: 1 },
1261
+ { left: sourcePoint.x, top: sourcePoint.y, width: 1, height: 1 },
1262
+ ]
1263
+ })
1264
+ const hasParallelRoute = otherRoutes.some(
1265
+ (other) => other.edge.from === route.edge.from && other.edge.to === route.edge.to,
1266
+ )
1267
+ const intersectsObstacle = (label: FlowchartEdgeLabelLayout): boolean =>
1268
+ (targetWidth !== undefined &&
1269
+ (hasParallelRoute || !includeLabelWidth
1270
+ ? label.point.x > targetWidth
1271
+ : label.point.x + label.width > targetWidth)) ||
1272
+ nodeBounds.some((bound) => labelIntersectsBounds(label, bound)) ||
1273
+ frameBounds.some((bound) => labelIntersectsSubgraphFrame(label, bound)) ||
1274
+ labelIntersectsLabels(label, otherLabels) ||
1275
+ labelIntersectsRoutePaths(label, otherRoutes) ||
1276
+ otherConnectorBounds.some((bound) => labelIntersectsBounds(label, bound))
1277
+ const current = flowchartRouteLabelLayout(route, diagramTextWidth)
1278
+ if (!intersectsObstacle(current)) return route
1279
+
1280
+ const seen = new Set<string>()
1281
+ let remaining = ROUTING_CANDIDATE_BUDGET
1282
+ const available = (candidate: FlowchartPoint) => {
1283
+ remaining--
1284
+ const key = `${candidate.x}:${candidate.y}`
1285
+ if (seen.has(key)) return false
1286
+ seen.add(key)
1287
+ return !intersectsObstacle({ ...current, point: candidate })
1288
+ }
1289
+ for (let index = 1; index < route.points.length && remaining > 0; index++) {
1290
+ const segment = segmentBetween(route.points[index - 1]!, route.points[index]!)
1291
+ if (!segment) continue
1292
+ const label = flowchartEdgeLabelLayout(route.points, route.edge.label, diagramTextWidth, route.labelAxis, index - 1)
1293
+ const fixed =
1294
+ segment.axis === "y"
1295
+ ? [label.point, { x: segment.from.x - label.width, y: label.point.y }]
1296
+ : [
1297
+ label.point,
1298
+ { x: label.point.x, y: segment.from.y - label.height },
1299
+ { x: label.point.x, y: segment.from.y + 1 },
1300
+ ]
1301
+ for (const candidate of fixed) {
1302
+ if (remaining <= 0) return route
1303
+ if (available(candidate)) return { ...route, labelPoint: candidate }
1304
+ }
1305
+ if (segment.axis === "y") {
1306
+ const bottom = Math.max(segment.from.y, segment.to.y) - label.height + 1
1307
+ for (let y = Math.min(segment.from.y, segment.to.y); y <= bottom && remaining > 0; y++) {
1308
+ for (const x of [segment.from.x + 1, segment.from.x - label.width]) {
1309
+ const candidate = { x, y }
1310
+ if (available(candidate)) return { ...route, labelPoint: candidate }
1311
+ if (remaining <= 0) return route
1312
+ }
1313
+ }
1314
+ continue
1315
+ }
1316
+ const right = Math.max(segment.from.x, segment.to.x) - label.width + 1
1317
+ for (let x = Math.min(segment.from.x, segment.to.x); x <= right && remaining > 0; x++) {
1318
+ for (const y of [segment.from.y, segment.from.y - label.height, segment.from.y + 1]) {
1319
+ const candidate = { x, y }
1320
+ if (available(candidate)) return { ...route, labelPoint: candidate }
1321
+ if (remaining <= 0) return route
1322
+ }
1323
+ }
1324
+ }
1325
+ if (targetWidth !== undefined && includeLabelWidth && current.point.x + current.width > targetWidth) {
1326
+ const x = Math.max(0, targetWidth - current.width)
1327
+ for (let distance = 0; distance < 100; distance++) {
1328
+ for (const y of distance === 0 ? [current.point.y] : [current.point.y - distance, current.point.y + distance]) {
1329
+ if (y < 0 || intersectsObstacle({ ...current, point: { x, y } })) continue
1330
+ return { ...route, labelPoint: { x, y } }
1331
+ }
1332
+ }
1333
+ }
1334
+ return route
1335
+ }
1336
+
1337
+ export function routeFlowchartEdges(
1338
+ diagram: FlowchartDiagram,
1339
+ bounds: Map<string, FlowchartNodeBounds>,
1340
+ directionForEdge: (edge: FlowchartEdge) => FlowchartDirection = () => diagram.direction,
1341
+ subgraphBounds?: ReadonlyMap<string, FlowchartSubgraphBounds>,
1342
+ targetWidth?: number,
1343
+ directionAligned = false,
1344
+ lockedRoutes?: ReadonlyMap<FlowchartEdge, FlowchartEdgeRoute>,
1345
+ ): FlowchartEdgeRoute[] {
1346
+ const routedDiagram = { ...diagram, edges: diagram.edges.filter((edge) => !edge.orderOnly) }
1347
+ const endpoints = new Map<string, FlowchartEndpointBounds>([
1348
+ ...(subgraphBounds ? [...subgraphBounds] : []),
1349
+ ...bounds,
1350
+ ])
1351
+ const handled = new Set<FlowchartEdge>()
1352
+ const routes: FlowchartEdgeRoute[] = []
1353
+ if (lockedRoutes) {
1354
+ for (const [edge, route] of lockedRoutes) {
1355
+ routes.push(route)
1356
+ handled.add(edge)
1357
+ }
1358
+ }
1359
+ const leftBoundary = subgraphBounds
1360
+ ? Math.min(...[...bounds.values(), ...subgraphBounds.values()].map((bound) => bound.left))
1361
+ : undefined
1362
+
1363
+ routeParallelEdges(routedDiagram, endpoints, directionForEdge, directionAligned, handled, routes)
1364
+
1365
+ for (const direction of ["LR", "RL"] satisfies FlowchartDirection[]) {
1366
+ const horizontalEdges = routedDiagram.edges.filter(
1367
+ (edge) => !handled.has(edge) && directionForEdge(edge) === direction,
1368
+ )
1369
+ if (horizontalEdges.length === 0) continue
1370
+ const records = horizontalForwardRecords(horizontalEdges, endpoints, direction)
1371
+ routeHorizontalFanOut(records, endpoints, direction, handled, routes)
1372
+ routeHorizontalFanIn(records, direction, handled, routes)
1373
+ }
1374
+
1375
+ routeHorizontalSubgraphExitFanIn(routedDiagram, endpoints, subgraphBounds, handled, routes)
1376
+ routeHorizontalSubgraphEntries(routedDiagram, endpoints, subgraphBounds, handled, routes)
1377
+
1378
+ for (const direction of ["TD", "TB", "BT"] satisfies FlowchartDirection[]) {
1379
+ const verticalEdges = routedDiagram.edges.filter(
1380
+ (edge) => !handled.has(edge) && directionForEdge(edge) === direction,
1381
+ )
1382
+ if (verticalEdges.length === 0) continue
1383
+ const records = verticalForwardRecords(verticalEdges, endpoints, direction)
1384
+ routeVerticalFanOut(records, direction, handled, routes)
1385
+ routeVerticalFanIn(records, direction, handled, routes)
1386
+ }
1387
+
1388
+ for (const edge of routedDiagram.edges) {
1389
+ if (handled.has(edge)) continue
1390
+ const from = endpoints.get(edge.from)
1391
+ const to = endpoints.get(edge.to)
1392
+ if (!from || !to) continue
1393
+ routes.push({ edge, points: edgePath(from, to, directionForEdge(edge), leftBoundary) })
1394
+ }
1395
+ for (let index = routes.length - 1; index >= 0; index--) {
1396
+ if (lockedRoutes?.has(routes[index]!.edge)) continue
1397
+ routes[index] = avoidNodeObstacles(routes[index]!, routes, bounds, endpoints, subgraphBounds, index, routedDiagram)
1398
+ }
1399
+ const subgraphs = diagram.subgraphs ?? []
1400
+ const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
1401
+ const containers = (id: string) => {
1402
+ const ids = new Set<string>()
1403
+ const directSubgraph = subgraphById.get(id)
1404
+ let current = directSubgraph
1405
+ ? directSubgraph.parentId
1406
+ ? subgraphById.get(directSubgraph.parentId)
1407
+ : undefined
1408
+ : subgraphs.find((subgraph) => subgraph.nodeIds.includes(id))
1409
+ while (current) {
1410
+ ids.add(current.id)
1411
+ current = current.parentId ? subgraphById.get(current.parentId) : undefined
1412
+ }
1413
+ return ids
1414
+ }
1415
+ const groupedLabelEdge = (edge: FlowchartEdge) => {
1416
+ const fromContainers = containers(edge.from)
1417
+ if (![...containers(edge.to)].some((id) => fromContainers.has(id))) return false
1418
+ const targets = new Set(
1419
+ routedDiagram.edges
1420
+ .filter((candidate) => candidate.label && candidate.from === edge.from)
1421
+ .map((candidate) => candidate.to),
1422
+ )
1423
+ const sources = new Set(
1424
+ routedDiagram.edges
1425
+ .filter((candidate) => candidate.label && candidate.to === edge.to)
1426
+ .map((candidate) => candidate.from),
1427
+ )
1428
+ return targets.size > 1 || sources.size > 1
1429
+ }
1430
+ return routes.reduce<FlowchartEdgeRoute[]>((resolved, route, index) => {
1431
+ if (lockedRoutes?.has(route.edge)) return [...resolved, route]
1432
+ const grouped = groupedLabelEdge(route.edge)
1433
+ return [
1434
+ ...resolved,
1435
+ avoidLabelOverlap(
1436
+ route,
1437
+ [...resolved, ...routes.slice(index + 1)],
1438
+ bounds,
1439
+ endpoints,
1440
+ subgraphBounds,
1441
+ targetWidth !== undefined && subgraphs.length > 0 && grouped ? Math.max(1, targetWidth - 5) : targetWidth,
1442
+ subgraphs.length === 0 || grouped,
1443
+ ),
1444
+ ]
1445
+ }, [])
1446
+ }
1447
+
1448
+ export function avoidFlowchartFrameBorders(
1449
+ routes: readonly FlowchartEdgeRoute[],
1450
+ bounds: ReadonlyMap<string, FlowchartNodeBounds>,
1451
+ subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
1452
+ ): void {
1453
+ const endpoints = new Map<string, FlowchartEndpointBounds>([...subgraphBounds, ...bounds])
1454
+ const inside = (node: FlowchartEndpointBounds, frame: FlowchartSubgraphBounds) =>
1455
+ node.id !== frame.id &&
1456
+ node.left >= frame.left &&
1457
+ node.top >= frame.top &&
1458
+ node.left + node.width <= frame.left + frame.width &&
1459
+ node.top + node.height <= frame.top + frame.height
1460
+
1461
+ for (const route of routes) {
1462
+ const source = endpoints.get(route.edge.from)
1463
+ const target = endpoints.get(route.edge.to)
1464
+ for (const frame of subgraphBounds.values()) {
1465
+ const inward = Boolean(source && target && inside(source, frame) && inside(target, frame))
1466
+ const right = frame.left + frame.width - 1
1467
+ const bottom = frame.top + frame.height - 1
1468
+ const points: FlowchartPoint[] = [route.points[0]!]
1469
+ for (let index = 1; index < route.points.length; index++) {
1470
+ const from = route.points[index - 1]!
1471
+ const to = route.points[index]!
1472
+ const segment = segmentBetween(from, to)
1473
+ if (!segment) continue
1474
+ const span = segmentSpan(segment)
1475
+ const horizontalSide =
1476
+ segment.axis === "x" && Math.min(span.end, right) > Math.max(span.start, frame.left)
1477
+ ? segment.from.y === frame.top
1478
+ ? "top"
1479
+ : segment.from.y === bottom
1480
+ ? "bottom"
1481
+ : undefined
1482
+ : undefined
1483
+ const verticalSide =
1484
+ segment.axis === "y" && Math.min(span.end, bottom) > Math.max(span.start, frame.top)
1485
+ ? segment.from.x === frame.left
1486
+ ? "left"
1487
+ : segment.from.x === right
1488
+ ? "right"
1489
+ : undefined
1490
+ : undefined
1491
+ if (!horizontalSide && !verticalSide) {
1492
+ points.push(to)
1493
+ continue
1494
+ }
1495
+
1496
+ const offset = horizontalSide
1497
+ ? horizontalSide === "top"
1498
+ ? frame.top + (inward ? 1 : -1)
1499
+ : bottom + (inward ? -1 : 1)
1500
+ : verticalSide === "left"
1501
+ ? frame.left + (inward ? 1 : -1)
1502
+ : right + (inward ? -1 : 1)
1503
+ if (horizontalSide) points.push({ x: from.x, y: offset }, { x: to.x, y: offset }, to)
1504
+ else points.push({ x: offset, y: from.y }, { x: offset, y: to.y }, to)
1505
+ }
1506
+ route.points = pathThrough(points)
1507
+ }
1508
+ }
1509
+ }
1510
+
1511
+ function sideForOutsidePoint(bounds: FlowchartEndpointBounds, sourcePoint: FlowchartPoint): DiagramSide {
1512
+ if (sourcePoint.x < bounds.left) return "left"
1513
+ if (sourcePoint.x >= bounds.left + bounds.width) return "right"
1514
+ if (sourcePoint.y < bounds.top) return "top"
1515
+ return "bottom"
1516
+ }
1517
+
1518
+ function connectorChar(side: DiagramSide): string {
1519
+ switch (side) {
1520
+ case "left":
1521
+ return "┤"
1522
+ case "right":
1523
+ return "├"
1524
+ case "top":
1525
+ return "┴"
1526
+ case "bottom":
1527
+ return "┬"
1528
+ }
1529
+ }
1530
+
1531
+ export function flowchartSourceConnector(
1532
+ from: FlowchartEndpointBounds,
1533
+ sourcePoint: FlowchartPoint,
1534
+ ): { x: number; y: number; char: string } {
1535
+ const side = sideForOutsidePoint(from, sourcePoint)
1536
+ const connector = boundsSidePoint(from, side, "border")
1537
+ return {
1538
+ x: side === "top" || side === "bottom" ? sourcePoint.x : connector.x,
1539
+ y: side === "left" || side === "right" ? sourcePoint.y : connector.y,
1540
+ char: connectorChar(side),
1541
+ }
1542
+ }