@zyro-sec/merman 0.0.0-stage → 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 (69) hide show
  1. package/package.json +29 -4
  2. package/script/layout-audit.ts +98 -0
  3. package/src/core/canvas.ts +228 -0
  4. package/src/core/color/style.ts +56 -0
  5. package/src/core/drawing.ts +301 -0
  6. package/src/core/geometry.ts +347 -0
  7. package/src/core/mermaid.ts +38 -0
  8. package/src/core/render-grid.ts +51 -0
  9. package/src/core/spatial.ts +243 -0
  10. package/src/core/text-lines.ts +32 -0
  11. package/src/core/text.ts +44 -0
  12. package/src/detect.ts +17 -0
  13. package/src/diagnostics.ts +16 -0
  14. package/src/flowchart/drawing.ts +340 -0
  15. package/src/flowchart/labels.ts +144 -0
  16. package/src/flowchart/layout.ts +1427 -0
  17. package/src/flowchart/options.ts +12 -0
  18. package/src/flowchart/parser.ts +467 -0
  19. package/src/flowchart/render.ts +10 -0
  20. package/src/flowchart/routing.ts +1542 -0
  21. package/src/flowchart/style.ts +79 -0
  22. package/src/flowchart/types.ts +65 -0
  23. package/src/gantt/diagram.ts +8 -0
  24. package/src/gantt/drawing.ts +191 -0
  25. package/src/gantt/parser.ts +161 -0
  26. package/src/gantt/render-grid.ts +17 -0
  27. package/src/gantt/style.ts +36 -0
  28. package/src/gantt/types.ts +44 -0
  29. package/src/gitgraph/diagram.ts +8 -0
  30. package/src/gitgraph/drawing.ts +234 -0
  31. package/src/gitgraph/parser.ts +219 -0
  32. package/src/gitgraph/render-grid.ts +17 -0
  33. package/src/gitgraph/style.ts +37 -0
  34. package/src/gitgraph/types.ts +36 -0
  35. package/src/markdown.ts +336 -0
  36. package/src/palette.ts +75 -0
  37. package/src/plugin.ts +15 -0
  38. package/src/sequence/diagram.ts +8 -0
  39. package/src/sequence/drawing.ts +287 -0
  40. package/src/sequence/options.ts +8 -0
  41. package/src/sequence/parser.ts +282 -0
  42. package/src/sequence/placement.ts +684 -0
  43. package/src/sequence/render-grid.ts +22 -0
  44. package/src/sequence/style.ts +81 -0
  45. package/src/sequence/types.ts +74 -0
  46. package/src/state/diagram.ts +8 -0
  47. package/src/state/drawing.ts +360 -0
  48. package/src/state/endpoint.ts +15 -0
  49. package/src/state/layout.ts +1134 -0
  50. package/src/state/note.ts +59 -0
  51. package/src/state/options.ts +11 -0
  52. package/src/state/parser.ts +224 -0
  53. package/src/state/render-grid.ts +22 -0
  54. package/src/state/routing.ts +1522 -0
  55. package/src/state/search.ts +103 -0
  56. package/src/state/style.ts +52 -0
  57. package/src/state/types.ts +63 -0
  58. package/src/state/visible-model.ts +77 -0
  59. package/src/test/diagram.ts +32 -0
  60. package/src/test/layout-audit/fixtures.ts +538 -0
  61. package/src/test/layout-audit/harness.ts +522 -0
  62. package/src/timeline/diagram.ts +8 -0
  63. package/src/timeline/drawing.ts +109 -0
  64. package/src/timeline/parser.ts +119 -0
  65. package/src/timeline/render-grid.ts +17 -0
  66. package/src/timeline/style.ts +36 -0
  67. package/src/timeline/types.ts +31 -0
  68. package/tsconfig.json +10 -0
  69. package/README.md +0 -3
@@ -0,0 +1,1427 @@
1
+ import {
2
+ diagramBoundsFromBounds,
3
+ diagramBoundsFromPoints,
4
+ segmentBetween,
5
+ segmentSpan,
6
+ translateDiagramBounds,
7
+ } from "../core/geometry.js"
8
+ import { diagramTextWidth, measureDiagramTextBox, splitDiagramLines } from "../core/text.js"
9
+ import {
10
+ flowchartEdgeLabelLayout,
11
+ flowchartHorizontalLabelRankGap,
12
+ flowchartLabelWidth,
13
+ flowchartRouteLabelLayout,
14
+ flowchartVerticalBranchLabelGap,
15
+ } from "./labels.js"
16
+ import type { FlowchartDiagramRenderOptions } from "./options.js"
17
+ import { avoidFlowchartFrameBorders, flowchartSourceConnector, routeFlowchartEdges } from "./routing.js"
18
+ import type {
19
+ FlowchartDiagram,
20
+ FlowchartDirection,
21
+ FlowchartEdge,
22
+ FlowchartEdgeRoute,
23
+ FlowchartNode,
24
+ FlowchartNodeBounds,
25
+ FlowchartNodeSize,
26
+ FlowchartPoint,
27
+ FlowchartSubgraph,
28
+ FlowchartSubgraphBounds,
29
+ } from "./types.js"
30
+
31
+ export const DEFAULT_MIN_NODE_GAP = 5
32
+ export const DEFAULT_MIN_BRANCH_LABEL_GAP = 12
33
+ const DEFAULT_MAX_UNLABELED_RANK_WIDTH = 120
34
+ export const DEFAULT_MIN_RANK_GAP = 7
35
+ export const DEFAULT_MIN_VERTICAL_RANK_GAP = 4
36
+ export const COMPACT_MIN_RANK_GAP = 4
37
+ export const COMPACT_MIN_VERTICAL_RANK_GAP = 2
38
+ const SUBGRAPH_PADDING_X = 2
39
+ const SUBGRAPH_PADDING_TOP = 1
40
+ const SUBGRAPH_PADDING_BOTTOM = 1
41
+ const MIN_SUBGRAPH_VERTICAL_EDGE_GAP = 3
42
+ const MIN_SUBGRAPH_HORIZONTAL_EDGE_GAP = 4
43
+
44
+ export interface FlowchartLayout {
45
+ diagram: FlowchartDiagram
46
+ bounds: Map<string, FlowchartNodeBounds>
47
+ routes: FlowchartEdgeRoute[]
48
+ subgraphBounds: Map<string, FlowchartSubgraphBounds>
49
+ width: number
50
+ height: number
51
+ }
52
+
53
+ type FlowchartBounds = Pick<FlowchartSubgraphBounds, "left" | "top" | "width" | "height" | "centerX" | "centerY">
54
+
55
+ function endpointRankSpan(
56
+ diagram: FlowchartDiagram,
57
+ edge: FlowchartEdge,
58
+ normalizedRanks: ReadonlyMap<string, number>,
59
+ nodeIds: ReadonlySet<string>,
60
+ ):
61
+ | { startRank: number; endRank: number; hasSubgraphEndpoint: boolean; unsharedSubgraphs: FlowchartSubgraph[] }
62
+ | undefined {
63
+ const fromRanks = (nodeIds.has(edge.from) ? [edge.from] : [...collectSubgraphNodeIds(diagram, edge.from)]).flatMap(
64
+ (id) => {
65
+ const rank = normalizedRanks.get(id)
66
+ return rank === undefined ? [] : [rank]
67
+ },
68
+ )
69
+ const toRanks = (nodeIds.has(edge.to) ? [edge.to] : [...collectSubgraphNodeIds(diagram, edge.to)]).flatMap((id) => {
70
+ const rank = normalizedRanks.get(id)
71
+ return rank === undefined ? [] : [rank]
72
+ })
73
+ if (fromRanks.length === 0 || toRanks.length === 0) return undefined
74
+ const forwardStart = Math.max(...fromRanks)
75
+ const forwardEnd = Math.min(...toRanks)
76
+ const reverseStart = Math.max(...toRanks)
77
+ const reverseEnd = Math.min(...fromRanks)
78
+ const span =
79
+ forwardStart < forwardEnd
80
+ ? { startRank: forwardStart, endRank: forwardEnd }
81
+ : reverseStart < reverseEnd
82
+ ? { startRank: reverseStart, endRank: reverseEnd }
83
+ : undefined
84
+ if (!span) return undefined
85
+
86
+ const hasSubgraphEndpoint = !nodeIds.has(edge.from) || !nodeIds.has(edge.to)
87
+ const subgraphs = diagram.subgraphs ?? []
88
+ const unsharedSubgraphs = hasSubgraphEndpoint
89
+ ? subgraphs.filter((subgraph) => {
90
+ const containsFrom = subgraph.id === edge.from || subgraphContainsEndpoint(diagram, subgraph, edge.from)
91
+ const containsTo = subgraph.id === edge.to || subgraphContainsEndpoint(diagram, subgraph, edge.to)
92
+ return containsFrom !== containsTo
93
+ })
94
+ : []
95
+ return { ...span, hasSubgraphEndpoint, unsharedSubgraphs }
96
+ }
97
+
98
+ function ensureRankSpanGap(gaps: number[], startIndex: number, endIndex: number, required: number): void {
99
+ const low = Math.min(startIndex, endIndex)
100
+ const high = Math.max(startIndex, endIndex)
101
+ if (low === high) return
102
+ if (high - low === 1) {
103
+ gaps[low] = Math.max(gaps[low]!, required)
104
+ return
105
+ }
106
+ const current = gaps.slice(low, high).reduce((sum, gap) => sum + gap, 0)
107
+ if (current < required) gaps[high - 1] = gaps[high - 1]! + (required - current)
108
+ }
109
+
110
+ function horizontalRankGaps(
111
+ diagram: FlowchartDiagram,
112
+ normalizedRanks: ReadonlyMap<string, number>,
113
+ rankKeys: readonly number[],
114
+ fallback: number,
115
+ ): number[] {
116
+ const gaps = Array.from({ length: Math.max(0, rankKeys.length - 1) }, () => fallback)
117
+ const rankIndexes = new Map(rankKeys.map((rank, index) => [rank, index]))
118
+ const nodeIds = new Set(diagram.nodes.map((node) => node.id))
119
+
120
+ for (const edge of diagram.edges) {
121
+ if (edge.orderOnly) continue
122
+ const hasSubgraphEndpoint = !nodeIds.has(edge.from) || !nodeIds.has(edge.to)
123
+ if (!edge.label && !hasSubgraphEndpoint) continue
124
+
125
+ if (!hasSubgraphEndpoint) {
126
+ const fromIndex = rankIndexes.get(normalizedRanks.get(edge.from) ?? -1)
127
+ const toIndex = rankIndexes.get(normalizedRanks.get(edge.to) ?? -1)
128
+ if (fromIndex === undefined || toIndex === undefined || fromIndex === toIndex) continue
129
+ const labelGap = flowchartHorizontalLabelRankGap(flowchartLabelWidth(edge.label, visualLength))
130
+ for (let index = Math.min(fromIndex, toIndex); index < Math.max(fromIndex, toIndex); index++) {
131
+ gaps[index] = Math.max(gaps[index]!, labelGap)
132
+ }
133
+ continue
134
+ }
135
+
136
+ const span = endpointRankSpan(diagram, edge, normalizedRanks, nodeIds)
137
+ if (!span) continue
138
+ const startIndex = rankIndexes.get(span.startRank)
139
+ const endIndex = rankIndexes.get(span.endRank)
140
+ if (startIndex === undefined || endIndex === undefined) continue
141
+ const padding = span.unsharedSubgraphs.length * SUBGRAPH_PADDING_X
142
+ const clearance = edge.label
143
+ ? Math.max(
144
+ MIN_SUBGRAPH_HORIZONTAL_EDGE_GAP,
145
+ flowchartHorizontalLabelRankGap(flowchartLabelWidth(edge.label, visualLength)),
146
+ )
147
+ : MIN_SUBGRAPH_HORIZONTAL_EDGE_GAP
148
+ ensureRankSpanGap(gaps, startIndex, endIndex, padding + clearance)
149
+ }
150
+
151
+ return gaps
152
+ }
153
+
154
+ function verticalRankGaps(
155
+ diagram: FlowchartDiagram,
156
+ normalizedRanks: ReadonlyMap<string, number>,
157
+ rankKeys: readonly number[],
158
+ fallback: number,
159
+ ): number[] {
160
+ const gaps = Array.from({ length: Math.max(0, rankKeys.length - 1) }, () => fallback)
161
+ const rankIndexes = new Map(rankKeys.map((rank, index) => [rank, index]))
162
+ const nodeIds = new Set(diagram.nodes.map((node) => node.id))
163
+
164
+ for (const edge of diagram.edges) {
165
+ if (edge.orderOnly) continue
166
+ const hasSubgraphEndpoint = !nodeIds.has(edge.from) || !nodeIds.has(edge.to)
167
+ if (!edge.label && !hasSubgraphEndpoint) continue
168
+
169
+ if (!hasSubgraphEndpoint) {
170
+ const fromIndex = rankIndexes.get(normalizedRanks.get(edge.from) ?? -1)
171
+ const toIndex = rankIndexes.get(normalizedRanks.get(edge.to) ?? -1)
172
+ if (fromIndex === undefined || toIndex === undefined || fromIndex === toIndex) continue
173
+ const labelHeight = splitDiagramLines(edge.label).length
174
+ for (let index = Math.min(fromIndex, toIndex); index < Math.max(fromIndex, toIndex); index++) {
175
+ gaps[index] = Math.max(gaps[index]!, labelHeight + 2)
176
+ }
177
+ continue
178
+ }
179
+
180
+ const span = endpointRankSpan(diagram, edge, normalizedRanks, nodeIds)
181
+ if (!span) continue
182
+ const startIndex = rankIndexes.get(span.startRank)
183
+ const endIndex = rankIndexes.get(span.endRank)
184
+ if (startIndex === undefined || endIndex === undefined) continue
185
+ const padding = span.unsharedSubgraphs.reduce(
186
+ (sum, subgraph) => sum + Math.max(SUBGRAPH_PADDING_TOP, splitDiagramLines(subgraph.label).length),
187
+ 0,
188
+ )
189
+ const clearance = edge.label
190
+ ? Math.max(MIN_SUBGRAPH_VERTICAL_EDGE_GAP, splitDiagramLines(edge.label).length + 2)
191
+ : MIN_SUBGRAPH_VERTICAL_EDGE_GAP
192
+ ensureRankSpanGap(gaps, startIndex, endIndex, padding + clearance)
193
+ }
194
+
195
+ return gaps
196
+ }
197
+
198
+ function isHorizontalDirection(direction: FlowchartDirection): boolean {
199
+ return direction === "LR" || direction === "RL"
200
+ }
201
+
202
+ export function visualLength(value: string): number {
203
+ return diagramTextWidth(value)
204
+ }
205
+
206
+ export function normalizePositiveInt(value: number | undefined, fallback: number): number {
207
+ if (value === undefined || !Number.isFinite(value)) return fallback
208
+ return Math.max(1, Math.trunc(value))
209
+ }
210
+
211
+ function nodeSize(node: FlowchartNode): FlowchartNodeSize {
212
+ const { lines, width } = measureDiagramTextBox(node.label, { paddingX: 2 })
213
+ const innerWidth = width - 4
214
+ if (node.shape === "decision") {
215
+ const width = innerWidth + 6
216
+ return {
217
+ width: width % 2 === 0 ? width + 1 : width,
218
+ height: Math.max(5, lines.length + 4),
219
+ lines,
220
+ }
221
+ }
222
+ if (node.shape === "database") return { width: innerWidth + 4, height: lines.length + 4, lines }
223
+ if (node.shape === "subroutine") return { width: innerWidth + 6, height: lines.length + 2, lines }
224
+ return { width: innerWidth + 4, height: lines.length + 2, lines }
225
+ }
226
+
227
+ function rankNodes(diagram: FlowchartDiagram): Map<string, number> {
228
+ const ranks = new Map<string, number>()
229
+ const outgoing = new Map<string, string[]>()
230
+ const incoming = new Set<string>()
231
+ const incomingCounts = new Map(diagram.nodes.map((node) => [node.id, 0]))
232
+
233
+ const nodeIds = new Set(diagram.nodes.map((node) => node.id))
234
+ const subgraphs = diagram.subgraphs ?? []
235
+ const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
236
+ const insideSubgraph = (endpointId: string, subgraphId: string): boolean => {
237
+ const subgraph = subgraphById.get(subgraphId)
238
+ return Boolean(subgraph && subgraphContainsEndpoint(diagram, subgraph, endpointId))
239
+ }
240
+ const subgraphExitNodes = (subgraphId: string): string[] => {
241
+ const members = collectSubgraphNodeIds(diagram, subgraphId)
242
+ const hasInternalOutgoing = new Set<string>()
243
+ for (const edge of diagram.edges) {
244
+ if (edge.from === edge.to || !insideSubgraph(edge.from, subgraphId) || !insideSubgraph(edge.to, subgraphId))
245
+ continue
246
+ const sources = nodeIds.has(edge.from) ? [edge.from] : [...collectSubgraphNodeIds(diagram, edge.from)]
247
+ for (const source of sources) hasInternalOutgoing.add(source)
248
+ }
249
+ const exits = [...members].filter((id) => !hasInternalOutgoing.has(id))
250
+ return exits.length > 0 ? exits : [...members]
251
+ }
252
+ const subgraphEntryNodes = (subgraphId: string): string[] => {
253
+ const members = collectSubgraphNodeIds(diagram, subgraphId)
254
+ const hasInternalIncoming = new Set<string>()
255
+ for (const edge of diagram.edges) {
256
+ if (edge.from === edge.to || !insideSubgraph(edge.from, subgraphId) || !insideSubgraph(edge.to, subgraphId))
257
+ continue
258
+ const targets = nodeIds.has(edge.to) ? [edge.to] : [...collectSubgraphNodeIds(diagram, edge.to)]
259
+ for (const target of targets) hasInternalIncoming.add(target)
260
+ }
261
+ const entries = [...members].filter((id) => !hasInternalIncoming.has(id))
262
+ return entries.length > 0 ? entries : [...members]
263
+ }
264
+ const rankEdges = diagram.edges.flatMap((edge) => {
265
+ if (nodeIds.has(edge.from) && nodeIds.has(edge.to)) return [edge]
266
+ const fromIds = nodeIds.has(edge.from) ? [edge.from] : subgraphExitNodes(edge.from)
267
+ const toIds = nodeIds.has(edge.to) ? [edge.to] : subgraphEntryNodes(edge.to)
268
+ return fromIds.flatMap((from) => toIds.map((to) => ({ ...edge, from, to })))
269
+ })
270
+
271
+ for (const edge of rankEdges) {
272
+ const list = outgoing.get(edge.from) ?? []
273
+ list.push(edge.to)
274
+ outgoing.set(edge.from, list)
275
+ incoming.add(edge.to)
276
+ incomingCounts.set(edge.to, (incomingCounts.get(edge.to) ?? 0) + 1)
277
+ }
278
+
279
+ const starts = diagram.nodes.filter((node) => !incoming.has(node.id))
280
+ if (starts.length === 0 && diagram.nodes[0]) starts.push(diagram.nodes[0])
281
+
282
+ const queue = starts.map((node) => node.id)
283
+ for (const node of starts) ranks.set(node.id, 0)
284
+
285
+ for (let index = 0; index < queue.length; index++) {
286
+ const id = queue[index]!
287
+ const rank = ranks.get(id) ?? 0
288
+ for (const to of outgoing.get(id) ?? []) {
289
+ const nextRank = rank + 1
290
+ if ((ranks.get(to) ?? Number.POSITIVE_INFINITY) <= nextRank) continue
291
+ ranks.set(to, nextRank)
292
+ queue.push(to)
293
+ }
294
+ }
295
+
296
+ for (const node of diagram.nodes) {
297
+ if (!ranks.has(node.id)) ranks.set(node.id, ranks.size)
298
+ }
299
+
300
+ const acyclicRanks = new Map<string, number>()
301
+ const acyclicQueue = diagram.nodes.filter((node) => incomingCounts.get(node.id) === 0).map((node) => node.id)
302
+ for (const id of acyclicQueue) acyclicRanks.set(id, 0)
303
+ for (let index = 0; index < acyclicQueue.length; index++) {
304
+ const id = acyclicQueue[index]!
305
+ const rank = acyclicRanks.get(id) ?? 0
306
+ for (const to of outgoing.get(id) ?? []) {
307
+ acyclicRanks.set(to, Math.max(acyclicRanks.get(to) ?? 0, rank + 1))
308
+ const remainingIncoming = (incomingCounts.get(to) ?? 0) - 1
309
+ incomingCounts.set(to, remainingIncoming)
310
+ if (remainingIncoming === 0) acyclicQueue.push(to)
311
+ }
312
+ }
313
+ for (const [id, rank] of acyclicRanks) ranks.set(id, rank)
314
+
315
+ return ranks
316
+ }
317
+
318
+ function translateBounds(bounds: FlowchartBounds, dx: number, dy: number): void {
319
+ translateDiagramBounds(bounds, dx, dy)
320
+ }
321
+
322
+ function translateRoutes(routes: readonly FlowchartEdgeRoute[], dx: number, dy: number): void {
323
+ for (const route of routes) {
324
+ for (const point of route.points) {
325
+ point.x += dx
326
+ point.y += dy
327
+ }
328
+ if (route.labelPoint) {
329
+ route.labelPoint.x += dx
330
+ route.labelPoint.y += dy
331
+ }
332
+ }
333
+ }
334
+
335
+ function freezeRouteLabelPoints(routes: readonly FlowchartEdgeRoute[]): void {
336
+ for (const route of routes) {
337
+ if (!route.edge.label || route.labelPoint) continue
338
+ route.labelPoint = flowchartEdgeLabelLayout(route.points, route.edge.label, visualLength, route.labelAxis).point
339
+ }
340
+ }
341
+
342
+ function boundsFromChildren(children: readonly FlowchartBounds[]): FlowchartBounds | undefined {
343
+ return diagramBoundsFromBounds(children)
344
+ }
345
+
346
+ function subgraphBoundFromChildren(
347
+ id: string,
348
+ label: string,
349
+ children: readonly FlowchartBounds[],
350
+ ): FlowchartSubgraphBounds {
351
+ const labelLines = splitDiagramLines(label)
352
+ const labelHeight = labelLines.length
353
+ let left = Math.min(...children.map((child) => child.left)) - SUBGRAPH_PADDING_X
354
+ const top = Math.min(...children.map((child) => child.top)) - Math.max(SUBGRAPH_PADDING_TOP, labelHeight)
355
+ let right = Math.max(...children.map((child) => child.left + child.width)) + SUBGRAPH_PADDING_X
356
+ const bottom =
357
+ Math.max(...children.map((child) => child.top + child.height)) + Math.max(SUBGRAPH_PADDING_BOTTOM, labelHeight)
358
+ const minWidth = Math.max(...labelLines.map(visualLength)) + 5
359
+
360
+ if (right - left < minWidth) {
361
+ const extra = minWidth - (right - left)
362
+ left -= Math.floor(extra / 2)
363
+ right += Math.ceil(extra / 2)
364
+ }
365
+
366
+ const width = right - left
367
+ const height = Math.max(3, bottom - top)
368
+ return {
369
+ id,
370
+ label,
371
+ left,
372
+ top,
373
+ width,
374
+ height,
375
+ centerX: left + Math.floor(width / 2),
376
+ centerY: top + Math.floor(height / 2),
377
+ labelSide: "top",
378
+ }
379
+ }
380
+
381
+ function spansOverlap(leftStart: number, leftEnd: number, rightStart: number, rightEnd: number): boolean {
382
+ return leftStart <= rightEnd && rightStart <= leftEnd
383
+ }
384
+
385
+ function labelSlot(bounds: FlowchartSubgraphBounds, side: FlowchartSubgraphBounds["labelSide"]): FlowchartBounds {
386
+ const lines = splitDiagramLines(bounds.label)
387
+ const left = bounds.left + 2
388
+ const height = lines.length
389
+ const top = side === "top" ? bounds.top : bounds.top + bounds.height - height
390
+ const width = Math.max(...lines.map((line) => visualLength(` ${line} `)))
391
+ return { left, top, width, height, centerX: left + Math.floor(width / 2), centerY: top + Math.floor(height / 2) }
392
+ }
393
+
394
+ function segmentOverlapsSlot(
395
+ from: { x: number; y: number },
396
+ to: { x: number; y: number },
397
+ slot: FlowchartBounds,
398
+ ): boolean {
399
+ const segment = segmentBetween(from, to)
400
+ if (!segment) return false
401
+
402
+ const slotRight = slot.left + slot.width - 1
403
+ const slotBottom = slot.top + slot.height - 1
404
+ const span = segmentSpan(segment)
405
+ if (segment.axis === "x") {
406
+ return (
407
+ segment.from.y >= slot.top &&
408
+ segment.from.y <= slotBottom &&
409
+ spansOverlap(span.start, span.end, slot.left, slotRight)
410
+ )
411
+ }
412
+ return (
413
+ segment.from.x >= slot.left &&
414
+ segment.from.x <= slotRight &&
415
+ spansOverlap(span.start, span.end, slot.top, slotBottom)
416
+ )
417
+ }
418
+
419
+ function routeOverlapsSlot(
420
+ route: FlowchartEdgeRoute,
421
+ bounds: FlowchartSubgraphBounds,
422
+ slot: FlowchartBounds,
423
+ nodeIds: ReadonlySet<string>,
424
+ ): boolean {
425
+ if (route.edge.from === bounds.id && !nodeIds.has(bounds.id) && route.points[0]) {
426
+ const connector = flowchartSourceConnector(bounds, route.points[0])
427
+ if (
428
+ connector.x >= slot.left &&
429
+ connector.x < slot.left + slot.width &&
430
+ connector.y >= slot.top &&
431
+ connector.y < slot.top + slot.height
432
+ ) {
433
+ return true
434
+ }
435
+ }
436
+ for (let index = 1; index < route.points.length; index++) {
437
+ if (segmentOverlapsSlot(route.points[index - 1]!, route.points[index]!, slot)) return true
438
+ }
439
+
440
+ const routeLabelBounds = labelBounds(route)
441
+ if (
442
+ !routeLabelBounds ||
443
+ !spansOverlap(
444
+ routeLabelBounds.top,
445
+ routeLabelBounds.top + routeLabelBounds.height - 1,
446
+ slot.top,
447
+ slot.top + slot.height - 1,
448
+ )
449
+ ) {
450
+ return false
451
+ }
452
+ return spansOverlap(
453
+ routeLabelBounds.left,
454
+ routeLabelBounds.left + routeLabelBounds.width - 1,
455
+ slot.left,
456
+ slot.left + slot.width - 1,
457
+ )
458
+ }
459
+
460
+ function chooseSubgraphLabelSide(
461
+ bounds: FlowchartSubgraphBounds,
462
+ routes: readonly FlowchartEdgeRoute[],
463
+ nodeIds: ReadonlySet<string>,
464
+ ): FlowchartSubgraphBounds["labelSide"] {
465
+ const topSlot = labelSlot(bounds, "top")
466
+ if (!routes.some((route) => routeOverlapsSlot(route, bounds, topSlot, nodeIds))) return "top"
467
+
468
+ const bottomSlot = labelSlot(bounds, "bottom")
469
+ return routes.some((route) => routeOverlapsSlot(route, bounds, bottomSlot, nodeIds)) ? "top" : "bottom"
470
+ }
471
+
472
+ function pathBounds(points: readonly { x: number; y: number }[]): FlowchartBounds | undefined {
473
+ return diagramBoundsFromPoints(points)
474
+ }
475
+
476
+ function labelBounds(route: FlowchartEdgeRoute): FlowchartBounds | undefined {
477
+ if (!route.edge.label) return undefined
478
+ const label = flowchartRouteLabelLayout(route, visualLength)
479
+ const { point, width, height } = label
480
+ return {
481
+ left: point.x,
482
+ top: point.y,
483
+ width,
484
+ height,
485
+ centerX: point.x + Math.floor(width / 2),
486
+ centerY: point.y + Math.floor(height / 2),
487
+ }
488
+ }
489
+
490
+ function subgraphRouteBounds(subgraphNodeIds: Set<string>, routes: readonly FlowchartEdgeRoute[]): FlowchartBounds[] {
491
+ return routeRenderBounds(
492
+ routes.filter((route) => subgraphNodeIds.has(route.edge.from) && subgraphNodeIds.has(route.edge.to)),
493
+ )
494
+ }
495
+
496
+ function routeRenderBounds(routes: readonly FlowchartEdgeRoute[]): FlowchartBounds[] {
497
+ const bounds: FlowchartBounds[] = []
498
+ for (const route of routes) {
499
+ const routeBounds = pathBounds(route.points)
500
+ if (routeBounds) bounds.push(routeBounds)
501
+ const routeLabelBounds = labelBounds(route)
502
+ if (routeLabelBounds) bounds.push(routeLabelBounds)
503
+ }
504
+ return bounds
505
+ }
506
+
507
+ function layoutRankedNodes(
508
+ diagram: FlowchartDiagram,
509
+ direction: FlowchartDirection,
510
+ sizes: ReadonlyMap<string, FlowchartNodeSize>,
511
+ minNodeGap: number,
512
+ requestedMinRankGap: number,
513
+ targetWidth?: number,
514
+ ): { bounds: Map<string, FlowchartNodeBounds>; wrapped: boolean } {
515
+ const horizontal = isHorizontalDirection(direction)
516
+ const ranks = rankNodes(diagram)
517
+ const maxRank = Math.max(0, ...ranks.values())
518
+ const ranksByIndex = new Map<number, FlowchartNode[]>()
519
+ const normalizedRanks = new Map<string, number>()
520
+
521
+ for (const node of diagram.nodes) {
522
+ const rank = ranks.get(node.id) ?? 0
523
+ const normalizedRank = direction === "RL" || direction === "BT" ? maxRank - rank : rank
524
+ normalizedRanks.set(node.id, normalizedRank)
525
+ const nodes = ranksByIndex.get(normalizedRank) ?? []
526
+ nodes.push(node)
527
+ ranksByIndex.set(normalizedRank, nodes)
528
+ }
529
+ reduceRankCrossings(diagram, ranks, normalizedRanks, ranksByIndex)
530
+
531
+ const spaciousNodeGap = Math.max(minNodeGap, DEFAULT_MIN_BRANCH_LABEL_GAP)
532
+ const widestUnlabeledRank = Math.max(
533
+ 0,
534
+ ...[...ranksByIndex.values()].map(
535
+ (nodes) =>
536
+ nodes.reduce((total, node) => total + sizes.get(node.id)!.width, 0) +
537
+ Math.max(0, nodes.length - 1) * spaciousNodeGap,
538
+ ),
539
+ )
540
+ const verticalNodeGap = (rank: number): number => {
541
+ const widestLabel = Math.max(
542
+ 0,
543
+ ...diagram.edges
544
+ .filter(
545
+ (edge) => edge.label && (normalizedRanks.get(edge.from) === rank || normalizedRanks.get(edge.to) === rank),
546
+ )
547
+ .map((edge) => flowchartLabelWidth(edge.label, visualLength)),
548
+ )
549
+ if (widestLabel > 0) return Math.max(spaciousNodeGap, flowchartVerticalBranchLabelGap(widestLabel))
550
+ return widestUnlabeledRank > DEFAULT_MAX_UNLABELED_RANK_WIDTH ? minNodeGap : spaciousNodeGap
551
+ }
552
+
553
+ const rankKeys = [...ranksByIndex.keys()].sort((a, b) => a - b)
554
+ const horizontalGaps = horizontal ? horizontalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap) : []
555
+ const verticalGaps = horizontal ? [] : verticalRankGaps(diagram, normalizedRanks, rankKeys, requestedMinRankGap)
556
+ const bounds = new Map<string, FlowchartNodeBounds>()
557
+ let wrapped = false
558
+
559
+ if (horizontal) {
560
+ const columnWidths = rankKeys.map((rank) =>
561
+ Math.max(...ranksByIndex.get(rank)!.map((node) => sizes.get(node.id)!.width)),
562
+ )
563
+ const columnHeights = rankKeys.map((rank) => {
564
+ const nodes = ranksByIndex.get(rank)!
565
+ return (
566
+ nodes.reduce((total, node) => total + sizes.get(node.id)!.height, 0) +
567
+ Math.max(0, nodes.length - 1) * minNodeGap
568
+ )
569
+ })
570
+ const canvasHeight = Math.max(1, ...columnHeights)
571
+ const centerBaseline = Math.floor(canvasHeight / 2)
572
+ let x = 0
573
+ for (let rankIndex = 0; rankIndex < rankKeys.length; rankIndex++) {
574
+ const rank = rankKeys[rankIndex]!
575
+ const nodes = ranksByIndex.get(rank)!
576
+ const columnWidth = columnWidths[rankIndex]!
577
+ let y = centerBaseline - Math.floor(columnHeights[rankIndex]! / 2)
578
+ for (const node of nodes) {
579
+ const size = sizes.get(node.id)!
580
+ const left = x + Math.floor((columnWidth - size.width) / 2)
581
+ bounds.set(node.id, {
582
+ id: node.id,
583
+ ...size,
584
+ left,
585
+ top: y,
586
+ centerX: left + Math.floor(size.width / 2),
587
+ centerY: y + Math.floor(size.height / 2),
588
+ })
589
+ y += size.height + minNodeGap
590
+ }
591
+ x += columnWidth + (horizontalGaps[rankIndex] ?? 0)
592
+ }
593
+ } else {
594
+ const rankBands = rankKeys.map((rank) => {
595
+ const nodes = ranksByIndex.get(rank)!
596
+ const roomyNodeGap = verticalNodeGap(rank)
597
+ const naturalWidth =
598
+ nodes.reduce((total, node) => total + sizes.get(node.id)!.width, 0) +
599
+ Math.max(0, nodes.length - 1) * roomyNodeGap
600
+ const labeledEdges = diagram.edges.filter(
601
+ (edge) => edge.label && (normalizedRanks.get(edge.from) === rank || normalizedRanks.get(edge.to) === rank),
602
+ )
603
+ const needsLabelLanes =
604
+ labeledEdges.length > 1 &&
605
+ labeledEdges.some((edge) => {
606
+ const targets = new Set(
607
+ labeledEdges.filter((candidate) => candidate.from === edge.from).map((candidate) => candidate.to),
608
+ )
609
+ const sources = new Set(
610
+ labeledEdges.filter((candidate) => candidate.to === edge.to).map((candidate) => candidate.from),
611
+ )
612
+ const grouped = (ids: readonly string[]) =>
613
+ !diagram.subgraphs?.length ||
614
+ diagram.subgraphs.some((subgraph) => ids.every((id) => subgraph.nodeIds.includes(id)))
615
+ return (
616
+ (targets.size > 1 && grouped([edge.from, ...targets])) ||
617
+ (sources.size > 1 && grouped([edge.to, ...sources]))
618
+ )
619
+ })
620
+ const nodeGap =
621
+ targetWidth !== undefined && naturalWidth > targetWidth && (!needsLabelLanes || !diagram.subgraphs?.length)
622
+ ? minNodeGap
623
+ : roomyNodeGap
624
+ const bands: { nodes: FlowchartNode[]; width: number; height: number }[] = []
625
+ for (const node of nodes) {
626
+ const size = sizes.get(node.id)!
627
+ const current = bands.at(-1)
628
+ const width = current ? current.width + nodeGap + size.width : size.width
629
+ if (current && targetWidth !== undefined && width > targetWidth) {
630
+ wrapped = true
631
+ bands.push({ nodes: [node], width: size.width, height: size.height })
632
+ continue
633
+ }
634
+ if (!current) {
635
+ bands.push({ nodes: [node], width: size.width, height: size.height })
636
+ continue
637
+ }
638
+ current.nodes.push(node)
639
+ current.width = width
640
+ current.height = Math.max(current.height, size.height)
641
+ }
642
+ return { bands, nodeGap }
643
+ })
644
+ const canvasWidth = Math.max(1, ...rankBands.flatMap((rank) => rank.bands.map((band) => band.width)))
645
+ let y = 0
646
+ for (let rankIndex = 0; rankIndex < rankKeys.length; rankIndex++) {
647
+ const rank = rankBands[rankIndex]!
648
+ for (const [bandIndex, band] of rank.bands.entries()) {
649
+ let x = Math.floor((canvasWidth - band.width) / 2)
650
+ for (const node of band.nodes) {
651
+ const size = sizes.get(node.id)!
652
+ const top = y + Math.floor((band.height - size.height) / 2)
653
+ bounds.set(node.id, {
654
+ id: node.id,
655
+ ...size,
656
+ left: x,
657
+ top,
658
+ centerX: x + Math.floor(size.width / 2),
659
+ centerY: top + Math.floor(size.height / 2),
660
+ })
661
+ x += size.width + rank.nodeGap
662
+ }
663
+ y += band.height + (bandIndex < rank.bands.length - 1 ? minNodeGap : 0)
664
+ }
665
+ y += verticalGaps[rankIndex] ?? 0
666
+ }
667
+ }
668
+
669
+ return { bounds, wrapped }
670
+ }
671
+
672
+ const CROSSING_SWEEPS = 8
673
+
674
+ // Barycenter ordering within ranks. Source order is kept unless a sweep strictly reduces crossings, so
675
+ // crossing-free diagrams render exactly as authored.
676
+ function reduceRankCrossings(
677
+ diagram: FlowchartDiagram,
678
+ ranks: ReadonlyMap<string, number>,
679
+ normalizedRanks: ReadonlyMap<string, number>,
680
+ ranksByIndex: Map<number, FlowchartNode[]>,
681
+ ): void {
682
+ // Reordering could interleave members of different subgraphs and break their frames.
683
+ if (diagram.subgraphs?.length) return
684
+ const rankKeys = [...ranksByIndex.keys()].sort((a, b) => a - b)
685
+ const layerByRank = new Map(rankKeys.map((rank, index) => [rank, index]))
686
+ // Feedback edges route around the diagram, so only forward edges between adjacent ranks can cross.
687
+ const links = diagram.edges.flatMap((edge) => {
688
+ const fromRank = ranks.get(edge.from)
689
+ const toRank = ranks.get(edge.to)
690
+ if (edge.orderOnly || fromRank === undefined || toRank === undefined || toRank !== fromRank + 1) return []
691
+ const from = normalizedRanks.get(edge.from)!
692
+ const to = normalizedRanks.get(edge.to)!
693
+ if (Math.abs(from - to) !== 1) return []
694
+ return [
695
+ from < to
696
+ ? { layer: layerByRank.get(from)!, upper: edge.from, lower: edge.to }
697
+ : { layer: layerByRank.get(to)!, upper: edge.to, lower: edge.from },
698
+ ]
699
+ })
700
+ const original = rankKeys.map((rank) => ranksByIndex.get(rank)!.map((node) => node.id))
701
+ const initialCrossings = layerCrossings(original, links)
702
+ if (initialCrossings === 0) return
703
+
704
+ const best = Array.from({ length: CROSSING_SWEEPS }).reduce(
705
+ (state: { current: string[][]; best: string[][]; crossings: number }, _, sweep) => {
706
+ const current = sweepLayers(state.current, links, sweep % 2 === 0)
707
+ const crossings = layerCrossings(current, links)
708
+ return crossings < state.crossings ? { current, best: current, crossings } : { ...state, current }
709
+ },
710
+ { current: original, best: original, crossings: initialCrossings },
711
+ ).best
712
+ if (best === original) return
713
+
714
+ const nodeById = new Map(diagram.nodes.map((node) => [node.id, node]))
715
+ for (const [index, rank] of rankKeys.entries()) {
716
+ ranksByIndex.set(
717
+ rank,
718
+ best[index]!.map((id) => nodeById.get(id)!),
719
+ )
720
+ }
721
+ }
722
+
723
+ function sweepLayers(
724
+ layers: readonly string[][],
725
+ links: readonly { layer: number; upper: string; lower: string }[],
726
+ down: boolean,
727
+ ): string[][] {
728
+ const next = layers.map((layer) => [...layer])
729
+ const indices = next.map((_, index) => index)
730
+ for (const index of down ? indices.slice(1) : indices.slice(0, -1).reverse()) {
731
+ const fixed = next[down ? index - 1 : index + 1]!
732
+ const keys = new Map(
733
+ next[index]!.map((id, position) => {
734
+ const neighbors = links.flatMap((link) => {
735
+ if (down && link.layer === index - 1 && link.lower === id) return [fixed.indexOf(link.upper)]
736
+ if (!down && link.layer === index && link.upper === id) return [fixed.indexOf(link.lower)]
737
+ return []
738
+ })
739
+ if (neighbors.length === 0) return [id, position]
740
+ return [id, neighbors.reduce((total, neighbor) => total + neighbor, 0) / neighbors.length]
741
+ }),
742
+ )
743
+ next[index] = next[index]!.toSorted((a, b) => keys.get(a)! - keys.get(b)!)
744
+ }
745
+ return next
746
+ }
747
+
748
+ function layerCrossings(
749
+ layers: readonly string[][],
750
+ links: readonly { layer: number; upper: string; lower: string }[],
751
+ ): number {
752
+ const position = new Map(layers.flatMap((layer) => layer.map((id, index) => [id, index] as const)))
753
+ return links.reduce(
754
+ (total, link, index) =>
755
+ total +
756
+ links
757
+ .slice(index + 1)
758
+ .filter(
759
+ (other) =>
760
+ other.layer === link.layer &&
761
+ (position.get(link.upper)! - position.get(other.upper)!) *
762
+ (position.get(link.lower)! - position.get(other.lower)!) <
763
+ 0,
764
+ ).length,
765
+ 0,
766
+ )
767
+ }
768
+
769
+ function layoutLocalSubgraphDirections(
770
+ diagram: FlowchartDiagram,
771
+ nodeBounds: Map<string, FlowchartNodeBounds>,
772
+ minNodeGap: number,
773
+ requestedMinRankGap: number,
774
+ targetWidth?: number,
775
+ ): boolean {
776
+ let wrapped = false
777
+ const subgraphs = diagram.subgraphs ?? []
778
+ const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
779
+ for (const subgraph of [...subgraphs].reverse()) {
780
+ let parent = subgraph.parentId ? subgraphById.get(subgraph.parentId) : undefined
781
+ while (parent && !parent.direction) parent = parent.parentId ? subgraphById.get(parent.parentId) : undefined
782
+ const direction =
783
+ subgraph.direction ??
784
+ (parent && subgraphs.filter((child) => child.parentId === parent.id).length > 1 ? parent.direction : undefined)
785
+ if (!direction || direction === diagram.direction) continue
786
+ const childSubgraphs = subgraphs.filter((child) => child.parentId === subgraph.id)
787
+ const coveredNodeIds = new Set(childSubgraphs.flatMap((child) => [...collectSubgraphNodeIds(diagram, child.id)]))
788
+ const items = [
789
+ ...childSubgraphs.flatMap((child) => {
790
+ const nodeIds = [...collectSubgraphNodeIds(diagram, child.id)]
791
+ const content = boundsFromChildren(nodeIds.flatMap((id) => nodeBounds.get(id) ?? []))
792
+ const bounds = content ? subgraphBoundFromChildren(child.id, child.label, [content]) : undefined
793
+ return bounds ? [{ id: `subgraph:${child.id}`, nodeIds, bounds, childId: child.id }] : []
794
+ }),
795
+ ...subgraph.nodeIds.flatMap((id) => {
796
+ if (coveredNodeIds.has(id)) return []
797
+ const bounds = nodeBounds.get(id)
798
+ return bounds ? [{ id, nodeIds: [id], bounds, childId: undefined }] : []
799
+ }),
800
+ ]
801
+ if (items.length === 0) continue
802
+
803
+ const currentBounds = boundsFromChildren(items.map((item) => item.bounds))
804
+ if (!currentBounds) continue
805
+
806
+ const itemByEndpoint = new Map<string, string>()
807
+ for (const item of items) {
808
+ for (const nodeId of item.nodeIds) itemByEndpoint.set(nodeId, item.id)
809
+ if (item.childId) {
810
+ itemByEndpoint.set(item.childId, item.id)
811
+ for (const nestedId of collectDescendantSubgraphIds(diagram, item.childId)) {
812
+ itemByEndpoint.set(nestedId, item.id)
813
+ }
814
+ }
815
+ }
816
+ const nodes = items.map((item): FlowchartNode => ({ id: item.id, label: item.id, shape: "box" }))
817
+ const localDiagram: FlowchartDiagram = {
818
+ direction,
819
+ nodes,
820
+ edges: diagram.edges.flatMap((edge) => {
821
+ const from = itemByEndpoint.get(edge.from)
822
+ const to = itemByEndpoint.get(edge.to)
823
+ return from && to && from !== to ? [{ ...edge, from, to }] : []
824
+ }),
825
+ subgraphs: [],
826
+ }
827
+ const itemSizes = new Map(
828
+ items.map((item) => [item.id, { width: item.bounds.width, height: item.bounds.height, lines: [item.id] }]),
829
+ )
830
+ const localLayout = layoutRankedNodes(
831
+ localDiagram,
832
+ direction,
833
+ itemSizes,
834
+ Math.max(minNodeGap, SUBGRAPH_PADDING_X * 2 + 1),
835
+ requestedMinRankGap,
836
+ targetWidth,
837
+ )
838
+ const localBounds = localLayout.bounds
839
+ wrapped ||= localLayout.wrapped
840
+ const localExtent = boundsFromChildren([...localBounds.values()])
841
+ if (!localExtent) continue
842
+
843
+ const targetLeft = currentBounds.left + Math.floor((currentBounds.width - localExtent.width) / 2)
844
+ const targetTop = currentBounds.top + Math.floor((currentBounds.height - localExtent.height) / 2)
845
+ const dx = targetLeft - localExtent.left
846
+ const dy = targetTop - localExtent.top
847
+
848
+ const translations = new Map<string, { dx: number; dy: number }>()
849
+ for (const item of items) {
850
+ const bound = localBounds.get(item.id)!
851
+ const itemDx = bound.left + dx - item.bounds.left
852
+ const itemDy = bound.top + dy - item.bounds.top
853
+ for (const nodeId of item.nodeIds) translations.set(nodeId, { dx: itemDx, dy: itemDy })
854
+ }
855
+
856
+ let groupOffset = { x: 0, y: 0 }
857
+ if (targetWidth !== undefined) {
858
+ const localNodeIds = new Set(translations.keys())
859
+ const external = [...nodeBounds.entries()].filter(([id]) => !localNodeIds.has(id)).map(([, bound]) => bound)
860
+ const overlaps = (offset: FlowchartPoint) =>
861
+ [...translations].some(([id, translation]) => {
862
+ const bound = nodeBounds.get(id)!
863
+ const left = bound.left + translation.dx + offset.x
864
+ const top = bound.top + translation.dy + offset.y
865
+ return external.some(
866
+ (other) =>
867
+ left < other.left + other.width + minNodeGap &&
868
+ left + bound.width + minNodeGap > other.left &&
869
+ top < other.top + other.height + minNodeGap &&
870
+ top + bound.height + minNodeGap > other.top,
871
+ )
872
+ })
873
+ if (overlaps(groupOffset)) {
874
+ const vertical = !isHorizontalDirection(diagram.direction)
875
+ const sign = diagram.direction === "RL" || diagram.direction === "BT" ? -1 : 1
876
+ let found = false
877
+ search: for (let distance = 1; distance < 1_000; distance++) {
878
+ const candidates = vertical
879
+ ? [
880
+ { x: 0, y: sign * distance },
881
+ { x: 0, y: -sign * distance },
882
+ { x: distance, y: 0 },
883
+ { x: -distance, y: 0 },
884
+ ]
885
+ : [
886
+ { x: sign * distance, y: 0 },
887
+ { x: -sign * distance, y: 0 },
888
+ { x: 0, y: distance },
889
+ { x: 0, y: -distance },
890
+ ]
891
+ for (const candidate of candidates) {
892
+ if (overlaps(candidate)) continue
893
+ groupOffset = candidate
894
+ found = true
895
+ break search
896
+ }
897
+ }
898
+ if (!found) throw new Error(`Subgraph ${subgraph.id} has no collision-free responsive position`)
899
+ }
900
+ }
901
+
902
+ for (const [nodeId, translation] of translations) {
903
+ const nodeBound = nodeBounds.get(nodeId)
904
+ if (nodeBound) translateBounds(nodeBound, translation.dx + groupOffset.x, translation.dy + groupOffset.y)
905
+ }
906
+ }
907
+ return wrapped
908
+ }
909
+
910
+ function collectDescendantSubgraphIds(diagram: FlowchartDiagram, subgraphId: string): Set<string> {
911
+ const ids = new Set<string>()
912
+ for (const child of diagram.subgraphs ?? []) {
913
+ if (child.parentId !== subgraphId) continue
914
+ ids.add(child.id)
915
+ for (const nested of collectDescendantSubgraphIds(diagram, child.id)) ids.add(nested)
916
+ }
917
+ return ids
918
+ }
919
+
920
+ function subgraphContainsEndpoint(diagram: FlowchartDiagram, subgraph: FlowchartSubgraph, endpointId: string): boolean {
921
+ return (
922
+ collectSubgraphNodeIds(diagram, subgraph.id).has(endpointId) ||
923
+ collectDescendantSubgraphIds(diagram, subgraph.id).has(endpointId)
924
+ )
925
+ }
926
+
927
+ function edgeDirection(diagram: FlowchartDiagram, edge: FlowchartEdge): FlowchartDirection {
928
+ for (const subgraph of [...(diagram.subgraphs ?? [])].reverse()) {
929
+ if (!subgraph.direction) continue
930
+ if (subgraphContainsEndpoint(diagram, subgraph, edge.from) && subgraphContainsEndpoint(diagram, subgraph, edge.to))
931
+ return subgraph.direction
932
+ }
933
+ return diagram.direction
934
+ }
935
+
936
+ function collectSubgraphNodeIds(diagram: FlowchartDiagram, subgraphId: string): Set<string> {
937
+ const nodeIds = new Set<string>()
938
+ for (const subgraph of diagram.subgraphs ?? []) {
939
+ if (subgraph.id !== subgraphId && subgraph.parentId !== subgraphId) continue
940
+ for (const nodeId of subgraph.nodeIds) nodeIds.add(nodeId)
941
+ if (subgraph.parentId === subgraphId) {
942
+ for (const nodeId of collectSubgraphNodeIds(diagram, subgraph.id)) nodeIds.add(nodeId)
943
+ }
944
+ }
945
+ return nodeIds
946
+ }
947
+
948
+ function rankGraphComponents(
949
+ ids: readonly string[],
950
+ outgoing: ReadonlyMap<string, ReadonlySet<string>>,
951
+ ): Map<string, number> {
952
+ const reachable = new Map<string, Set<string>>()
953
+ for (const id of ids) {
954
+ const seen = new Set<string>()
955
+ const queue = [id]
956
+ for (let index = 0; index < queue.length; index++) {
957
+ const current = queue[index]!
958
+ if (seen.has(current)) continue
959
+ seen.add(current)
960
+ queue.push(...(outgoing.get(current) ?? []))
961
+ }
962
+ reachable.set(id, seen)
963
+ }
964
+
965
+ const componentById = new Map<string, number>()
966
+ const components: string[][] = []
967
+ for (const id of ids) {
968
+ if (componentById.has(id)) continue
969
+ const component = ids.filter(
970
+ (candidate) =>
971
+ !componentById.has(candidate) && reachable.get(id)!.has(candidate) && reachable.get(candidate)!.has(id),
972
+ )
973
+ const componentIndex = components.length
974
+ components.push(component)
975
+ for (const member of component) componentById.set(member, componentIndex)
976
+ }
977
+
978
+ const componentOutgoing = new Map(components.map((_, index) => [index, new Set<number>()]))
979
+ const incoming = new Map(components.map((_, index) => [index, 0]))
980
+ for (const [from, targets] of outgoing) {
981
+ const fromComponent = componentById.get(from)!
982
+ for (const to of targets) {
983
+ const toComponent = componentById.get(to)!
984
+ if (fromComponent === toComponent || componentOutgoing.get(fromComponent)!.has(toComponent)) continue
985
+ componentOutgoing.get(fromComponent)!.add(toComponent)
986
+ incoming.set(toComponent, incoming.get(toComponent)! + 1)
987
+ }
988
+ }
989
+
990
+ const componentRanks = new Map<number, number>()
991
+ const queue = components.map((_, index) => index).filter((index) => incoming.get(index) === 0)
992
+ for (const component of queue) componentRanks.set(component, 0)
993
+ for (let index = 0; index < queue.length; index++) {
994
+ const component = queue[index]!
995
+ for (const to of componentOutgoing.get(component)!) {
996
+ componentRanks.set(to, Math.max(componentRanks.get(to) ?? 0, componentRanks.get(component)! + 1))
997
+ incoming.set(to, incoming.get(to)! - 1)
998
+ if (incoming.get(to) === 0) queue.push(to)
999
+ }
1000
+ }
1001
+
1002
+ return new Map(ids.map((id) => [id, componentRanks.get(componentById.get(id)!) ?? 0]))
1003
+ }
1004
+
1005
+ function separateTopLevelItems(
1006
+ diagram: FlowchartDiagram,
1007
+ nodeBounds: Map<string, FlowchartNodeBounds>,
1008
+ subgraphBounds: ReadonlyMap<string, FlowchartSubgraphBounds>,
1009
+ gap: number,
1010
+ targetWidth?: number,
1011
+ ): boolean {
1012
+ const hasLocalDirection = (diagram.subgraphs ?? []).some(
1013
+ (subgraph) => subgraph.direction && subgraph.direction !== diagram.direction,
1014
+ )
1015
+ const coveredNodeIds = new Set<string>()
1016
+ const items: {
1017
+ id: string
1018
+ bounds: FlowchartBounds
1019
+ nodeIds: Set<string>
1020
+ rank: number
1021
+ }[] = []
1022
+ const itemByEndpoint = new Map<string, string>()
1023
+ const subgraphs = diagram.subgraphs ?? []
1024
+ const topLevelIds = new Set(subgraphs.filter((subgraph) => !subgraph.parentId).map((subgraph) => subgraph.id))
1025
+ const subgraphById = new Map(subgraphs.map((subgraph) => [subgraph.id, subgraph]))
1026
+ const topLevelSubgraphId = (id: string): string => {
1027
+ let current = subgraphById.get(id)
1028
+ while (current?.parentId) current = subgraphById.get(current.parentId)
1029
+ return current?.id ?? id
1030
+ }
1031
+ for (const subgraph of subgraphs) {
1032
+ if (subgraph.parentId) continue
1033
+ const bounds = subgraphBounds.get(subgraph.id)
1034
+ const nodeIds = collectSubgraphNodeIds(diagram, subgraph.id)
1035
+ if (!bounds || nodeIds.size === 0) continue
1036
+ items.push({ id: subgraph.id, bounds, nodeIds, rank: 0 })
1037
+ itemByEndpoint.set(subgraph.id, subgraph.id)
1038
+ for (const nodeId of nodeIds) {
1039
+ coveredNodeIds.add(nodeId)
1040
+ itemByEndpoint.set(nodeId, subgraph.id)
1041
+ }
1042
+ }
1043
+ for (const subgraph of subgraphs) itemByEndpoint.set(subgraph.id, topLevelSubgraphId(subgraph.id))
1044
+
1045
+ for (const node of diagram.nodes) {
1046
+ if (coveredNodeIds.has(node.id)) continue
1047
+ const bounds = nodeBounds.get(node.id)
1048
+ if (!bounds) continue
1049
+ items.push({ id: node.id, bounds, nodeIds: new Set([node.id]), rank: 0 })
1050
+ itemByEndpoint.set(node.id, node.id)
1051
+ }
1052
+ if (items.length < 2) return false
1053
+
1054
+ const horizontal = isHorizontalDirection(diagram.direction)
1055
+ const moveItem = (item: (typeof items)[number], dx: number, dy: number): void => {
1056
+ for (const nodeId of item.nodeIds) {
1057
+ const bounds = nodeBounds.get(nodeId)
1058
+ if (bounds) translateBounds(bounds, dx, dy)
1059
+ }
1060
+ if (!topLevelIds.has(item.id)) return
1061
+ for (const subgraph of subgraphs) {
1062
+ if (topLevelSubgraphId(subgraph.id) !== item.id) continue
1063
+ const bounds = subgraphBounds.get(subgraph.id)
1064
+ if (bounds) translateBounds(bounds, dx, dy)
1065
+ }
1066
+ }
1067
+ const nodeIds = new Set(diagram.nodes.map((node) => node.id))
1068
+ const minSubgraphEdgeGap = (fromItemId: string, toItemId: string): number => {
1069
+ const matching = diagram.edges.filter(
1070
+ (edge) =>
1071
+ !edge.orderOnly &&
1072
+ (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) &&
1073
+ itemByEndpoint.get(edge.from) === fromItemId &&
1074
+ itemByEndpoint.get(edge.to) === toItemId,
1075
+ )
1076
+ if (matching.length === 0) return gap
1077
+ const labelRequirements = matching.map((edge) =>
1078
+ !edge.label
1079
+ ? 0
1080
+ : horizontal
1081
+ ? flowchartHorizontalLabelRankGap(flowchartLabelWidth(edge.label, visualLength))
1082
+ : splitDiagramLines(edge.label).length + 2,
1083
+ )
1084
+ return Math.max(
1085
+ gap,
1086
+ horizontal ? MIN_SUBGRAPH_HORIZONTAL_EDGE_GAP : MIN_SUBGRAPH_VERTICAL_EDGE_GAP,
1087
+ ...labelRequirements,
1088
+ )
1089
+ }
1090
+ if (hasLocalDirection) {
1091
+ const outgoing = new Map(items.map((item) => [item.id, new Set<string>()]))
1092
+ for (const edge of diagram.edges) {
1093
+ const from = itemByEndpoint.get(edge.from)
1094
+ const to = itemByEndpoint.get(edge.to)
1095
+ if (from && to && from !== to) outgoing.get(from)?.add(to)
1096
+ }
1097
+ const ranks = rankGraphComponents(
1098
+ items.map((item) => item.id),
1099
+ outgoing,
1100
+ )
1101
+ items.sort(
1102
+ (a, b) =>
1103
+ ranks.get(a.id)! - ranks.get(b.id)! ||
1104
+ (horizontal ? a.bounds.centerX - b.bounds.centerX : a.bounds.centerY - b.bounds.centerY),
1105
+ )
1106
+ let cursor: number | undefined
1107
+ let previousId: string | undefined
1108
+ let moved = false
1109
+ for (const item of items) {
1110
+ const start = horizontal ? item.bounds.left : item.bounds.top
1111
+ const size = horizontal ? item.bounds.width : item.bounds.height
1112
+ if (cursor === undefined) {
1113
+ cursor = start + size
1114
+ previousId = item.id
1115
+ continue
1116
+ }
1117
+ const pairGap = previousId
1118
+ ? Math.max(minSubgraphEdgeGap(previousId, item.id), minSubgraphEdgeGap(item.id, previousId))
1119
+ : gap
1120
+ const shift = cursor + pairGap - start
1121
+ moved ||= shift !== 0
1122
+ moveItem(item, horizontal ? shift : 0, horizontal ? 0 : shift)
1123
+ cursor = start + shift + size
1124
+ previousId = item.id
1125
+ }
1126
+ return moved
1127
+ }
1128
+
1129
+ const rankedItems = items.filter((item) => topLevelIds.has(item.id))
1130
+ const reversed = diagram.direction === "RL" || diagram.direction === "BT"
1131
+ const primaryStart = (bound: FlowchartBounds): number => {
1132
+ const start = horizontal ? bound.left : bound.top
1133
+ const size = horizontal ? bound.width : bound.height
1134
+ return reversed ? -(start + size) : start
1135
+ }
1136
+ const primaryEnd = (bound: FlowchartBounds): number => primaryStart(bound) + (horizontal ? bound.width : bound.height)
1137
+ const ensureSubgraphEdgeItemClearance = (): boolean => {
1138
+ const allItemById = new Map(items.map((item) => [item.id, item]))
1139
+ const endpoints = new Map<string, FlowchartBounds>([...subgraphBounds, ...nodeBounds])
1140
+ let adjusted = false
1141
+ for (const edge of diagram.edges) {
1142
+ if (edge.orderOnly || (nodeIds.has(edge.from) && nodeIds.has(edge.to))) continue
1143
+ const fromItem = allItemById.get(itemByEndpoint.get(edge.from) ?? "")
1144
+ const toItem = allItemById.get(itemByEndpoint.get(edge.to) ?? "")
1145
+ const fromBound = endpoints.get(edge.from)
1146
+ const toBound = endpoints.get(edge.to)
1147
+ if (!fromItem || !toItem || fromItem === toItem || !fromBound || !toBound) continue
1148
+ if (primaryStart(toBound) <= primaryStart(fromBound)) continue
1149
+ const required = minSubgraphEdgeGap(fromItem.id, toItem.id)
1150
+ const deficit = primaryEnd(fromBound) + required - primaryStart(toBound)
1151
+ if (deficit <= 0) continue
1152
+ adjusted = true
1153
+ const toStart = primaryStart(toItem.bounds)
1154
+ const offset = reversed ? -deficit : deficit
1155
+ for (const candidate of items) {
1156
+ if (candidate !== toItem && primaryStart(candidate.bounds) < toStart) continue
1157
+ if (candidate === fromItem) continue
1158
+ moveItem(candidate, horizontal ? offset : 0, horizontal ? 0 : offset)
1159
+ }
1160
+ }
1161
+ return adjusted
1162
+ }
1163
+ if (rankedItems.length < 2) return ensureSubgraphEdgeItemClearance()
1164
+
1165
+ const itemById = new Map(rankedItems.map((item) => [item.id, item]))
1166
+ const outgoing = new Map(rankedItems.map((item) => [item.id, new Set<string>()]))
1167
+ for (const edge of diagram.edges) {
1168
+ const from = itemByEndpoint.get(edge.from)
1169
+ const to = itemByEndpoint.get(edge.to)
1170
+ if (!from || !to || from === to || !itemById.has(from) || !itemById.has(to) || outgoing.get(from)!.has(to)) continue
1171
+ outgoing.get(from)!.add(to)
1172
+ }
1173
+
1174
+ const ranks = rankGraphComponents(
1175
+ rankedItems.map((item) => item.id),
1176
+ outgoing,
1177
+ )
1178
+ for (const item of rankedItems) item.rank = ranks.get(item.id)!
1179
+
1180
+ const itemsByRank = Map.groupBy(rankedItems, (item) => item.rank)
1181
+ const rankKeys = [...itemsByRank.keys()].sort((a, b) => a - b)
1182
+ let previousEnd: number | undefined
1183
+ let previousRankItems: (typeof items)[number][] = []
1184
+ let moved = false
1185
+ for (const rank of rankKeys) {
1186
+ const rankItems = itemsByRank.get(rank)!
1187
+ const start = Math.min(...rankItems.map((item) => primaryStart(item.bounds)))
1188
+ const end = Math.max(...rankItems.map((item) => primaryEnd(item.bounds)))
1189
+ if (previousEnd === undefined) {
1190
+ previousEnd = end
1191
+ previousRankItems = rankItems
1192
+ continue
1193
+ }
1194
+ const rankGap = Math.max(
1195
+ gap,
1196
+ ...previousRankItems.flatMap((prev) => rankItems.map((curr) => minSubgraphEdgeGap(prev.id, curr.id))),
1197
+ )
1198
+ const shift = Math.max(0, previousEnd + rankGap - start)
1199
+ if (shift > 0) {
1200
+ moved = true
1201
+ for (const item of rankItems) {
1202
+ const offset = reversed ? -shift : shift
1203
+ moveItem(item, horizontal ? offset : 0, horizontal ? 0 : offset)
1204
+ }
1205
+ }
1206
+ previousEnd = end + shift
1207
+ previousRankItems = rankItems
1208
+ }
1209
+
1210
+ for (const rank of rankKeys) {
1211
+ const rankItems = itemsByRank
1212
+ .get(rank)!
1213
+ .toSorted((a, b) => (horizontal ? a.bounds.top - b.bounds.top : a.bounds.left - b.bounds.left))
1214
+ let crossCursor: number | undefined
1215
+ for (const item of rankItems) {
1216
+ const start = horizontal ? item.bounds.top : item.bounds.left
1217
+ const size = horizontal ? item.bounds.height : item.bounds.width
1218
+ if (crossCursor === undefined) {
1219
+ crossCursor = start + size + gap
1220
+ continue
1221
+ }
1222
+ const shift = Math.max(0, crossCursor - start)
1223
+ if (shift > 0) {
1224
+ moved = true
1225
+ moveItem(item, horizontal ? 0 : shift, horizontal ? shift : 0)
1226
+ }
1227
+ crossCursor = start + shift + size + gap
1228
+ }
1229
+ }
1230
+ if (targetWidth !== undefined && !horizontal) {
1231
+ const intersects = (left: (typeof items)[number], right: (typeof items)[number]): boolean =>
1232
+ [...left.nodeIds].some((leftId) => {
1233
+ const leftBounds = nodeBounds.get(leftId)!
1234
+ return [...right.nodeIds].some((rightId) => {
1235
+ const rightBounds = nodeBounds.get(rightId)!
1236
+ return (
1237
+ leftBounds.left <= rightBounds.left + rightBounds.width - 1 &&
1238
+ leftBounds.left + leftBounds.width - 1 >= rightBounds.left &&
1239
+ leftBounds.top <= rightBounds.top + rightBounds.height - 1 &&
1240
+ leftBounds.top + leftBounds.height - 1 >= rightBounds.top
1241
+ )
1242
+ })
1243
+ })
1244
+ for (let rightIndex = 1; rightIndex < items.length; rightIndex++) {
1245
+ const right = items[rightIndex]!
1246
+ for (let leftIndex = 0; leftIndex < rightIndex; leftIndex++) {
1247
+ const left = items[leftIndex]!
1248
+ if (!intersects(left, right)) continue
1249
+ const leftBounds = boundsFromChildren([...left.nodeIds].map((id) => nodeBounds.get(id)!))!
1250
+ const rightBounds = boundsFromChildren([...right.nodeIds].map((id) => nodeBounds.get(id)!))!
1251
+ const shift = reversed
1252
+ ? leftBounds.top - gap - (rightBounds.top + rightBounds.height)
1253
+ : leftBounds.top + leftBounds.height + gap - rightBounds.top
1254
+ moved ||= shift !== 0
1255
+ moveItem(right, 0, shift)
1256
+ }
1257
+ }
1258
+ }
1259
+ moved = ensureSubgraphEdgeItemClearance() || moved
1260
+ return moved
1261
+ }
1262
+
1263
+ function layoutSubgraphs(
1264
+ diagram: FlowchartDiagram,
1265
+ nodeBounds: Map<string, FlowchartNodeBounds>,
1266
+ routes: readonly FlowchartEdgeRoute[],
1267
+ ): Map<string, FlowchartSubgraphBounds> {
1268
+ const subgraphBounds = new Map<string, FlowchartSubgraphBounds>()
1269
+ const subgraphs = diagram.subgraphs ?? []
1270
+ const nodeIds = new Set(diagram.nodes.map((node) => node.id))
1271
+
1272
+ for (const subgraph of [...subgraphs].reverse()) {
1273
+ const children: FlowchartBounds[] = []
1274
+ for (const nodeId of subgraph.nodeIds) {
1275
+ const bound = nodeBounds.get(nodeId)
1276
+ if (bound) children.push(bound)
1277
+ }
1278
+ children.push(...subgraphRouteBounds(new Set(subgraph.nodeIds), routes))
1279
+ for (const childSubgraph of subgraphs) {
1280
+ if (childSubgraph.parentId !== subgraph.id) continue
1281
+ const bound = subgraphBounds.get(childSubgraph.id)
1282
+ if (bound) children.push(bound)
1283
+ }
1284
+ if (children.length > 0) {
1285
+ const bound = subgraphBoundFromChildren(subgraph.id, subgraph.label, children)
1286
+ bound.labelSide = chooseSubgraphLabelSide(bound, routes, nodeIds)
1287
+ subgraphBounds.set(subgraph.id, bound)
1288
+ }
1289
+ }
1290
+
1291
+ return subgraphBounds
1292
+ }
1293
+
1294
+ function layoutFlowchartWithDirection(
1295
+ sourceDiagram: FlowchartDiagram,
1296
+ options: FlowchartDiagramRenderOptions,
1297
+ direction: FlowchartDirection,
1298
+ responsiveFallback = false,
1299
+ ): FlowchartLayout {
1300
+ const diagram = direction === sourceDiagram.direction ? sourceDiagram : { ...sourceDiagram, direction }
1301
+ const horizontal = isHorizontalDirection(direction)
1302
+ const minNodeGap = normalizePositiveInt(options.minNodeGap, DEFAULT_MIN_NODE_GAP)
1303
+ const requestedMinRankGap = normalizePositiveInt(
1304
+ options.minRankGap,
1305
+ options.compact
1306
+ ? horizontal
1307
+ ? COMPACT_MIN_RANK_GAP
1308
+ : COMPACT_MIN_VERTICAL_RANK_GAP
1309
+ : horizontal
1310
+ ? DEFAULT_MIN_RANK_GAP
1311
+ : DEFAULT_MIN_VERTICAL_RANK_GAP,
1312
+ )
1313
+ const sizes = new Map(diagram.nodes.map((node) => [node.id, nodeSize(node)]))
1314
+ const targetWidth =
1315
+ !horizontal && options.layoutMaxWidth !== undefined && Number.isFinite(options.layoutMaxWidth)
1316
+ ? Math.max(1, Math.trunc(options.layoutMaxWidth))
1317
+ : undefined
1318
+ const ranked = layoutRankedNodes(diagram, direction, sizes, minNodeGap, requestedMinRankGap, targetWidth)
1319
+ const bounds = ranked.bounds
1320
+ const responsive = layoutLocalSubgraphDirections(diagram, bounds, minNodeGap, requestedMinRankGap, targetWidth)
1321
+ const directionAligned = responsiveFallback || responsive || ranked.wrapped
1322
+ const nodeIds = new Set(diagram.nodes.map((node) => node.id))
1323
+ const hasSubgraphEndpoints = diagram.edges.some(
1324
+ (edge) => !edge.orderOnly && (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)),
1325
+ )
1326
+ const memberDiagram = hasSubgraphEndpoints
1327
+ ? { ...diagram, edges: diagram.edges.filter((edge) => nodeIds.has(edge.from) && nodeIds.has(edge.to)) }
1328
+ : diagram
1329
+ const route = (
1330
+ frames?: ReadonlyMap<string, FlowchartSubgraphBounds>,
1331
+ targetDiagram: FlowchartDiagram = memberDiagram,
1332
+ lockedRoutes?: ReadonlyMap<FlowchartEdge, FlowchartEdgeRoute>,
1333
+ ) =>
1334
+ routeFlowchartEdges(
1335
+ targetDiagram,
1336
+ bounds,
1337
+ (edge) => edgeDirection(diagram, edge),
1338
+ frames,
1339
+ targetWidth,
1340
+ directionAligned,
1341
+ lockedRoutes,
1342
+ )
1343
+
1344
+ const subgraphs = diagram.subgraphs ?? []
1345
+ let subgraphBounds = new Map<string, FlowchartSubgraphBounds>()
1346
+ let routes: FlowchartEdgeRoute[]
1347
+ if (subgraphs.length === 0) {
1348
+ routes = route(undefined, diagram)
1349
+ } else {
1350
+ routes = route()
1351
+ subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
1352
+ const moved = separateTopLevelItems(
1353
+ diagram,
1354
+ bounds,
1355
+ subgraphBounds,
1356
+ Math.max(1, Math.floor(requestedMinRankGap / 2)),
1357
+ targetWidth,
1358
+ )
1359
+ if (moved) {
1360
+ routes = route()
1361
+ subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
1362
+ }
1363
+ routes = route(subgraphBounds)
1364
+ subgraphBounds = layoutSubgraphs(diagram, bounds, routes)
1365
+ // Frame-aware routes can expand a group after initial separation. Move the expanded frame rigidly
1366
+ // before rerouting so external edges cannot grow it back across neighboring top-level items.
1367
+ const expanded = separateTopLevelItems(
1368
+ diagram,
1369
+ bounds,
1370
+ subgraphBounds,
1371
+ Math.max(1, Math.floor(requestedMinRankGap / 2)),
1372
+ targetWidth,
1373
+ )
1374
+ if (expanded) routes = route(subgraphBounds)
1375
+ if (hasSubgraphEndpoints) {
1376
+ const locked = new Map(routes.map((memberRoute) => [memberRoute.edge, memberRoute]))
1377
+ for (const edge of diagram.edges) {
1378
+ if (edge.orderOnly || nodeIds.has(edge.from)) continue
1379
+ const sourceFrame = subgraphBounds.get(edge.from)
1380
+ const targetBound = bounds.get(edge.to) ?? subgraphBounds.get(edge.to)
1381
+ if (!sourceFrame || !targetBound || sourceFrame.labelSide !== "top") continue
1382
+ if (!isHorizontalDirection(edgeDirection(diagram, edge)) && targetBound.centerY < sourceFrame.centerY) {
1383
+ const bottomSlot = labelSlot(sourceFrame, "bottom")
1384
+ if (!routes.some((route) => routeOverlapsSlot(route, sourceFrame, bottomSlot, nodeIds))) {
1385
+ sourceFrame.labelSide = "bottom"
1386
+ }
1387
+ }
1388
+ }
1389
+ routes = route(subgraphBounds, diagram, locked)
1390
+ let labelSideChanged = false
1391
+ for (const bound of subgraphBounds.values()) {
1392
+ const nextSide = chooseSubgraphLabelSide(bound, routes, nodeIds)
1393
+ if (nextSide !== bound.labelSide) {
1394
+ bound.labelSide = nextSide
1395
+ labelSideChanged = true
1396
+ }
1397
+ }
1398
+ if (labelSideChanged) routes = route(subgraphBounds, diagram, locked)
1399
+ }
1400
+ avoidFlowchartFrameBorders(routes, bounds, subgraphBounds)
1401
+ }
1402
+ freezeRouteLabelPoints(routes)
1403
+ const allBounds = [...bounds.values(), ...subgraphBounds.values(), ...routeRenderBounds(routes)]
1404
+ const dx = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.left)))
1405
+ const dy = Math.max(0, -Math.min(0, ...allBounds.map((bound) => bound.top)))
1406
+ if (dx > 0 || dy > 0) {
1407
+ for (const bound of allBounds) translateBounds(bound, dx, dy)
1408
+ translateRoutes(routes, dx, dy)
1409
+ }
1410
+
1411
+ const maxX = Math.max(0, ...allBounds.map((bound) => bound.left + bound.width))
1412
+ const maxY = Math.max(0, ...allBounds.map((bound) => bound.top + bound.height))
1413
+ return { diagram, bounds, routes, subgraphBounds, width: maxX + 4, height: maxY + 4 }
1414
+ }
1415
+
1416
+ export function layoutFlowchartDiagram(
1417
+ sourceDiagram: FlowchartDiagram,
1418
+ options: FlowchartDiagramRenderOptions = {},
1419
+ ): FlowchartLayout {
1420
+ const direction = options.direction ?? sourceDiagram.direction
1421
+ const layout = layoutFlowchartWithDirection(sourceDiagram, options, direction)
1422
+ const maxWidth = options.layoutMaxWidth
1423
+ if (!isHorizontalDirection(direction) || maxWidth === undefined || !Number.isFinite(maxWidth)) return layout
1424
+ if (layout.width <= Math.max(1, Math.trunc(maxWidth))) return layout
1425
+
1426
+ return layoutFlowchartWithDirection(sourceDiagram, options, direction === "RL" ? "BT" : "TD", true)
1427
+ }