@statelyai/flow 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +2 -1
  2. package/dist/esm/index.d.ts +5 -2
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +19 -14
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/layout/dagre.d.ts +2 -1
  7. package/dist/esm/layout/dagre.d.ts.map +1 -0
  8. package/dist/esm/layout/dagre.js +2 -0
  9. package/dist/esm/layout/dagre.js.map +1 -0
  10. package/dist/esm/layout/elk.d.ts +2 -1
  11. package/dist/esm/layout/elk.d.ts.map +1 -0
  12. package/dist/esm/layout/elk.js +2 -0
  13. package/dist/esm/layout/elk.js.map +1 -0
  14. package/dist/esm/layout/stately.d.ts +2 -1
  15. package/dist/esm/layout/stately.d.ts.map +1 -0
  16. package/dist/esm/layout/stately.js +2 -0
  17. package/dist/esm/layout/stately.js.map +1 -0
  18. package/dist/esm/shared.d.ts +2 -1
  19. package/dist/esm/shared.d.ts.map +1 -0
  20. package/dist/esm/shared.js +2 -0
  21. package/dist/esm/shared.js.map +1 -0
  22. package/package.json +4 -3
  23. package/src/__fixtures__/nested.ts +106 -0
  24. package/src/appearances.test.ts +428 -0
  25. package/src/appearances.ts +144 -0
  26. package/src/authoritative-route.ts +14 -0
  27. package/src/changeSet.test.ts +132 -0
  28. package/src/changeSet.ts +337 -0
  29. package/src/config.ts +41 -0
  30. package/src/configure.test.ts +212 -0
  31. package/src/connection-lifetime.ts +1 -0
  32. package/src/connectionPreview.test.ts +102 -0
  33. package/src/connectionPreview.ts +82 -0
  34. package/src/content.ts +203 -0
  35. package/src/createFlow.fit-frame.test.ts +256 -0
  36. package/src/createFlow.modern.test.ts +743 -0
  37. package/src/createFlow.test.ts +632 -0
  38. package/src/createFlow.ts +3463 -0
  39. package/src/createFlow.view.test.ts +212 -0
  40. package/src/createFlow.viewport-controls.test.ts +221 -0
  41. package/src/edge-geometry.ts +318 -0
  42. package/src/engine.cache.test.ts +728 -0
  43. package/src/engine.hierarchy.test.ts +1023 -0
  44. package/src/engine.test.ts +1965 -0
  45. package/src/engine.ts +3385 -0
  46. package/src/entity-changes.test.ts +309 -0
  47. package/src/entity-changes.ts +395 -0
  48. package/src/examples/flow-based-math.test.ts +25 -0
  49. package/src/examples/flow-based-math.ts +210 -0
  50. package/src/external-edit.test.ts +337 -0
  51. package/src/external-edit.ts +358 -0
  52. package/src/factories.test.ts +104 -0
  53. package/src/factories.ts +70 -0
  54. package/src/geometry.ts +13 -0
  55. package/src/graph-index.test.ts +56 -0
  56. package/src/graph-index.ts +194 -0
  57. package/src/hierarchy.test.ts +175 -0
  58. package/src/hierarchy.ts +330 -0
  59. package/src/highlights.test.ts +130 -0
  60. package/src/index.ts +469 -0
  61. package/src/input/index.ts +615 -0
  62. package/src/input/input.test.ts +2577 -0
  63. package/src/input/keymap.ts +111 -0
  64. package/src/input/modes.ts +1715 -0
  65. package/src/input/reparent.test.ts +214 -0
  66. package/src/layout/dagre.ts +138 -0
  67. package/src/layout/elk.ts +1382 -0
  68. package/src/layout/index.ts +12 -0
  69. package/src/layout/layout.test.ts +1248 -0
  70. package/src/layout/shared.ts +260 -0
  71. package/src/layout/stately-globals.d.ts +9 -0
  72. package/src/layout/stately.test.ts +246 -0
  73. package/src/layout/stately.ts +528 -0
  74. package/src/layout-animation.test.ts +223 -0
  75. package/src/layout-contract.test.ts +414 -0
  76. package/src/marker.test.ts +23 -0
  77. package/src/marker.ts +23 -0
  78. package/src/measurement-anchor.test.ts +232 -0
  79. package/src/minimap.test.ts +96 -0
  80. package/src/minimap.ts +137 -0
  81. package/src/nested-fixture.test.ts +178 -0
  82. package/src/port-measurement.test.ts +27 -0
  83. package/src/port-measurements.test.ts +187 -0
  84. package/src/profile.ts +124 -0
  85. package/src/projections.test.ts +103 -0
  86. package/src/projections.ts +295 -0
  87. package/src/render-invalidation.test.ts +62 -0
  88. package/src/render-invalidation.ts +55 -0
  89. package/src/renderer-geometry.test.ts +356 -0
  90. package/src/renderer-transactions.test.ts +234 -0
  91. package/src/routing/avoid.ts +417 -0
  92. package/src/routing/index.test.ts +361 -0
  93. package/src/routing/index.ts +366 -0
  94. package/src/routing/readTracking.test.ts +103 -0
  95. package/src/routing/readTracking.ts +233 -0
  96. package/src/selection-commands.test.ts +355 -0
  97. package/src/serialize.test.ts +167 -0
  98. package/src/serialize.ts +254 -0
  99. package/src/shapes/index.test.ts +45 -0
  100. package/src/shapes/index.ts +142 -0
  101. package/src/snap.test.ts +123 -0
  102. package/src/snap.ts +395 -0
  103. package/src/spatial.test.ts +676 -0
  104. package/src/spatial.ts +457 -0
  105. package/src/store/index.ts +4121 -0
  106. package/src/store.test.ts +2903 -0
  107. package/src/toolbar.test.ts +31 -0
  108. package/src/toolbar.ts +62 -0
  109. package/src/types.test.ts +15 -0
  110. package/src/types.ts +487 -0
  111. package/src/validation.ts +558 -0
  112. package/src/view.ts +172 -0
  113. package/src/viewport/animate.ts +285 -0
  114. package/src/viewport/index.ts +296 -0
  115. package/src/viewport.test.ts +569 -0
@@ -0,0 +1,1382 @@
1
+ import ELK from 'elkjs/lib/elk.bundled.js';
2
+ import type { ElkExtendedEdge, ElkNode } from 'elkjs/lib/elk-api';
3
+ import type {
4
+ FlowEdge,
5
+ FlowGraph,
6
+ FlowNode,
7
+ GroupContentSide,
8
+ GroupInsets,
9
+ GroupLayout,
10
+ LayoutResult,
11
+ Point,
12
+ Rect,
13
+ Size,
14
+ } from '@statelyai/flow';
15
+ import {
16
+ deriveGroupGeometry,
17
+ isGroup,
18
+ resolveGroupPadding,
19
+ } from '@statelyai/flow';
20
+ import {
21
+ boundsOf,
22
+ edgeLabelPositionsFromNodePositions,
23
+ graphForLayoutScope,
24
+ layoutRunContext,
25
+ mergedLayoutScope,
26
+ throwIfAborted,
27
+ type FlowLayoutFactory,
28
+ type FlowLayoutOptions,
29
+ } from './shared';
30
+
31
+ export type ElkLayoutOptions<TNodeData = any, TEdgeData = any, TLabelData = any> =
32
+ FlowLayoutOptions<TNodeData, TEdgeData, TLabelData>;
33
+
34
+ export const elkLayout: FlowLayoutFactory = (options = {}) => {
35
+ const elk = new ELK();
36
+ return async (graph, runOptions = {}) => {
37
+ throwIfAborted(runOptions);
38
+ const mutableGraph = graph as FlowGraph;
39
+ const scope = mergedLayoutScope(mutableGraph, options.scope, runOptions);
40
+ const layoutGraph = graphForLayoutScope(mutableGraph, scope);
41
+ const context = layoutRunContext(mutableGraph, options, runOptions, 'elk');
42
+ const result = await elk.layout(
43
+ toElkGraph(layoutGraph, { ...options, scope }),
44
+ );
45
+ throwIfAborted(runOptions);
46
+ const positions = new Map<string, Point>();
47
+ const nodeSizes = new Map<string, Size>();
48
+ const nodeBounds = new Map<string, Rect>();
49
+ const edgeLabelBounds = new Map<string, Rect>();
50
+ const edgeRoutes = new Map<string, { waypoints: Point[] }>();
51
+ collectElkGeometry(result, {
52
+ positions,
53
+ nodeSizes,
54
+ nodeBounds,
55
+ edgeLabelBounds,
56
+ edgeRoutes,
57
+ fixedIds: context.fixedIds,
58
+ });
59
+ await restoreExplicitCompoundDirections(
60
+ elk,
61
+ layoutGraph,
62
+ positions,
63
+ nodeSizes,
64
+ nodeBounds,
65
+ edgeLabelBounds,
66
+ edgeRoutes,
67
+ context.fixedIds,
68
+ options,
69
+ );
70
+ throwIfAborted(runOptions);
71
+ const edgeLabelPositions = new Map(
72
+ [...edgeLabelBounds].map(([id, bounds]) => [
73
+ id,
74
+ { x: bounds.x, y: bounds.y },
75
+ ]),
76
+ );
77
+ const fallbackLabels = edgeLabelPositionsFromNodePositions(
78
+ layoutGraph,
79
+ positions,
80
+ options.getBounds as ((node: FlowNode) => Rect) | undefined,
81
+ nodeBounds,
82
+ options.direction ?? layoutGraph.direction,
83
+ );
84
+ const nodesById = new Map(layoutGraph.nodes.map((node) => [node.id, node]));
85
+ const edgesById = new Map(
86
+ layoutGraph.edges.map((edge) => [edge.id, edge]),
87
+ );
88
+ const hasHierarchy = layoutGraph.nodes.some((node) => node.parentId);
89
+ for (const [id, position] of fallbackLabels ?? []) {
90
+ const edge = edgesById.get(id);
91
+ const containerId = edge
92
+ ? elkEdgeContainerId(edge, nodesById)
93
+ : undefined;
94
+ const containerOrigin = containerId
95
+ ? nodeBounds.get(containerId)
96
+ : { x: 0, y: 0 };
97
+ const reported = edgeLabelBounds.get(id);
98
+ const reportedAtContainerOrigin =
99
+ !!reported &&
100
+ !!containerOrigin &&
101
+ Math.abs(reported.x - containerOrigin.x) <= 0.5 &&
102
+ Math.abs(reported.y - containerOrigin.y) <= 0.5;
103
+ const overlapsEndpoint =
104
+ !!edge &&
105
+ !!reported &&
106
+ [nodeBounds.get(edge.sourceId), nodeBounds.get(edge.targetId)].some(
107
+ (bounds) => bounds && rectsOverlap(reported, bounds),
108
+ );
109
+ const invalidHierarchyPlacement =
110
+ hasHierarchy &&
111
+ edge?.sourceId !== edge?.targetId &&
112
+ (reportedAtContainerOrigin || overlapsEndpoint);
113
+ if (
114
+ (!edgeLabelPositions.has(id) || invalidHierarchyPlacement) &&
115
+ !context.fixedIds.has(id)
116
+ ) {
117
+ edgeLabelPositions.set(id, position);
118
+ const bounds = edgeLabelBounds.get(id);
119
+ const label = edge?.label;
120
+ if (bounds || label) {
121
+ edgeLabelBounds.set(id, {
122
+ ...position,
123
+ width: bounds?.width ?? label!.width,
124
+ height: bounds?.height ?? label!.height,
125
+ });
126
+ }
127
+ }
128
+ }
129
+ if (hasHierarchy) {
130
+ centerCompoundEdgeLabels(
131
+ layoutGraph,
132
+ edgeLabelPositions,
133
+ edgeLabelBounds,
134
+ nodeBounds,
135
+ nodesById,
136
+ context.fixedIds,
137
+ );
138
+ centerAncestorDescendantEdgeLabels(
139
+ layoutGraph,
140
+ edgeLabelPositions,
141
+ edgeLabelBounds,
142
+ nodeBounds,
143
+ nodesById,
144
+ context.fixedIds,
145
+ options,
146
+ );
147
+ for (let pass = 0; pass < 12; pass++) {
148
+ const labelsMoved = avoidEdgeLabelOverlaps(
149
+ layoutGraph,
150
+ edgeLabelPositions,
151
+ edgeLabelBounds,
152
+ nodeBounds,
153
+ nodesById,
154
+ context.fixedIds,
155
+ options.direction ?? layoutGraph.direction,
156
+ );
157
+ const groupsMoved = reconcileDerivedGroupBounds(
158
+ layoutGraph,
159
+ positions,
160
+ nodeSizes,
161
+ nodeBounds,
162
+ edgeLabelPositions,
163
+ edgeLabelBounds,
164
+ edgeRoutes,
165
+ context.fixedIds,
166
+ options,
167
+ );
168
+ if (!labelsMoved && !groupsMoved) break;
169
+ }
170
+ }
171
+ const missingNodes = layoutGraph.nodes
172
+ .map((node) => node.id)
173
+ .filter((id) => !context.fixedIds.has(id) && !positions.has(id))
174
+ .sort();
175
+ if (missingNodes.length > 0) {
176
+ const message = `ELK omitted node geometry: ${missingNodes.join(', ')}`;
177
+ context.diagnostics.push({ severity: 'warning', code: 'missing-node', message });
178
+ options.onWarning?.(message);
179
+ }
180
+ return {
181
+ positions,
182
+ nodeSizes,
183
+ nodeBounds,
184
+ ...(edgeLabelPositions.size > 0 ? { edgeLabelPositions } : {}),
185
+ ...(edgeLabelBounds.size > 0 ? { edgeLabelBounds } : {}),
186
+ ...(edgeRoutes.size > 0 ? { edgeRoutes } : {}),
187
+ ...(context.diagnostics.length > 0
188
+ ? { diagnostics: context.diagnostics }
189
+ : {}),
190
+ source: context.source,
191
+ metadata: context.metadata,
192
+ } satisfies LayoutResult;
193
+ };
194
+ };
195
+
196
+ async function restoreExplicitCompoundDirections(
197
+ elk: InstanceType<typeof ELK>,
198
+ graph: FlowGraph,
199
+ positions: Map<string, Point>,
200
+ nodeSizes: Map<string, Size>,
201
+ nodeBounds: Map<string, Rect>,
202
+ edgeLabelBounds: Map<string, Rect>,
203
+ edgeRoutes: Map<string, { waypoints: Point[] }>,
204
+ fixedIds: ReadonlySet<string>,
205
+ options: FlowLayoutOptions,
206
+ ): Promise<void> {
207
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
208
+ const childrenByParent = new Map<string, FlowNode[]>();
209
+ for (const node of graph.nodes) {
210
+ if (!node.parentId) continue;
211
+ const children = childrenByParent.get(node.parentId) ?? [];
212
+ children.push(node);
213
+ childrenByParent.set(node.parentId, children);
214
+ }
215
+ const depthOf = (node: FlowNode) => {
216
+ let depth = 0;
217
+ let marker = node.parentId ? nodesById.get(node.parentId) : undefined;
218
+ while (marker) {
219
+ depth++;
220
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
221
+ }
222
+ return depth;
223
+ };
224
+ const descendantsOf = (id: string) => {
225
+ const descendants = new Set<string>([id]);
226
+ const pending = [id];
227
+ while (pending.length > 0) {
228
+ for (const child of childrenByParent.get(pending.pop()!) ?? []) {
229
+ descendants.add(child.id);
230
+ pending.push(child.id);
231
+ }
232
+ }
233
+ return descendants;
234
+ };
235
+ const directChildOf = (id: string, groupId: string): string | undefined => {
236
+ let marker = nodesById.get(id);
237
+ while (marker?.parentId && marker.parentId !== groupId) {
238
+ marker = nodesById.get(marker.parentId);
239
+ }
240
+ return marker?.parentId === groupId ? marker.id : undefined;
241
+ };
242
+ const groups = graph.nodes
243
+ .filter(
244
+ (node) =>
245
+ node.group?.direction &&
246
+ node.group.direction !==
247
+ (options.direction ?? graph.direction ?? 'down') &&
248
+ (childrenByParent.get(node.id)?.length ?? 0) > 1,
249
+ )
250
+ .sort((a, b) => depthOf(b) - depthOf(a));
251
+
252
+ for (const group of groups) {
253
+ const children = childrenByParent.get(group.id)!;
254
+ const childDescendants = new Map(
255
+ children.map((child) => [child.id, descendantsOf(child.id)]),
256
+ );
257
+ if (
258
+ [...childDescendants.values()].some((ids) =>
259
+ [...ids].some((id) => fixedIds.has(id)),
260
+ )
261
+ ) {
262
+ continue;
263
+ }
264
+ const currentChildren = children.flatMap((child) => {
265
+ const bounds = nodeBounds.get(child.id);
266
+ return bounds ? [{ child, bounds }] : [];
267
+ });
268
+ if (currentChildren.length < 2) continue;
269
+ const centers = currentChildren.map(({ bounds }) => ({
270
+ x: bounds.x + bounds.width / 2,
271
+ y: bounds.y + bounds.height / 2,
272
+ }));
273
+ const dx =
274
+ Math.max(...centers.map((center) => center.x)) -
275
+ Math.min(...centers.map((center) => center.x));
276
+ const dy =
277
+ Math.max(...centers.map((center) => center.y)) -
278
+ Math.min(...centers.map((center) => center.y));
279
+ const alreadyDirected =
280
+ ((group.group!.direction === 'right' ||
281
+ group.group!.direction === 'left') &&
282
+ dx >= dy) ||
283
+ ((group.group!.direction === 'down' ||
284
+ group.group!.direction === 'up') &&
285
+ dy >= dx);
286
+ if (alreadyDirected) continue;
287
+
288
+ const localEdges: ElkExtendedEdge[] = [];
289
+ for (const edge of graph.edges) {
290
+ const sourceId = directChildOf(edge.sourceId, group.id);
291
+ const targetId = edge.targetId
292
+ ? directChildOf(edge.targetId, group.id)
293
+ : undefined;
294
+ if (!sourceId || !targetId || sourceId === targetId) continue;
295
+ localEdges.push({
296
+ id: `direction:${edge.id}`,
297
+ sources: [sourceId],
298
+ targets: [targetId],
299
+ labels: edge.label
300
+ ? [
301
+ {
302
+ id: `direction:${edge.id}:label`,
303
+ width: edge.label.width,
304
+ height: edge.label.height,
305
+ },
306
+ ]
307
+ : undefined,
308
+ });
309
+ }
310
+ const direction = group.group!.direction!;
311
+ const localLayoutOptions: Record<string, string> = {
312
+ 'elk.algorithm': 'layered',
313
+ 'elk.direction': elkDirection(direction),
314
+ 'elk.spacing.nodeNode': String(options.nodeSpacing ?? 60),
315
+ };
316
+ applyCompoundLayeredOptions(
317
+ localLayoutOptions,
318
+ localEdges,
319
+ direction,
320
+ options,
321
+ );
322
+ // A compound's local rerun must retain its configured cycle orientation.
323
+ const nestedNodeOptions = options.node?.layoutOptions;
324
+ const cycleBreakingStrategy =
325
+ options.node?.['elk.layered.cycleBreaking.strategy'] ??
326
+ (nestedNodeOptions && typeof nestedNodeOptions === 'object'
327
+ ? (nestedNodeOptions as Record<string, unknown>)['elk.layered.cycleBreaking.strategy']
328
+ : undefined) ??
329
+ options.graph?.['elk.layered.cycleBreaking.strategy'];
330
+ if (cycleBreakingStrategy !== undefined) {
331
+ localLayoutOptions['elk.layered.cycleBreaking.strategy'] = String(cycleBreakingStrategy);
332
+ }
333
+ const localResult = await elk.layout({
334
+ id: `direction:${group.id}`,
335
+ layoutOptions: localLayoutOptions,
336
+ children: currentChildren.map(({ child, bounds }) => ({
337
+ id: child.id,
338
+ width: bounds.width,
339
+ height: bounds.height,
340
+ })),
341
+ edges: localEdges,
342
+ });
343
+ const laidOutChildren: ElkNode[] = localResult.children ?? [];
344
+ const currentX = Math.min(...currentChildren.map(({ bounds }) => bounds.x));
345
+ const currentY = Math.min(...currentChildren.map(({ bounds }) => bounds.y));
346
+ const localX = Math.min(...laidOutChildren.map((child) => child.x ?? 0));
347
+ const localY = Math.min(...laidOutChildren.map((child) => child.y ?? 0));
348
+ if (group.group?.type === 'fixed') {
349
+ const groupBounds = nodeBounds.get(group.id);
350
+ const candidateBounds = laidOutChildren.reduce<Rect | null>(
351
+ (bounds, child) =>
352
+ unionRect(bounds, {
353
+ x: currentX + (child.x ?? 0) - localX,
354
+ y: currentY + (child.y ?? 0) - localY,
355
+ width: child.width ?? 0,
356
+ height: child.height ?? 0,
357
+ }),
358
+ null,
359
+ );
360
+ if (
361
+ !groupBounds ||
362
+ !candidateBounds ||
363
+ candidateBounds.x < groupBounds.x ||
364
+ candidateBounds.y < groupBounds.y ||
365
+ candidateBounds.x + candidateBounds.width >
366
+ groupBounds.x + groupBounds.width ||
367
+ candidateBounds.y + candidateBounds.height >
368
+ groupBounds.y + groupBounds.height
369
+ ) {
370
+ continue;
371
+ }
372
+ }
373
+ const movedIds = new Set<string>();
374
+
375
+ for (const laidOut of laidOutChildren) {
376
+ const current = nodeBounds.get(laidOut.id);
377
+ if (!current) continue;
378
+ const dx = currentX + (laidOut.x ?? 0) - localX - current.x;
379
+ const dy = currentY + (laidOut.y ?? 0) - localY - current.y;
380
+ if (dx === 0 && dy === 0) continue;
381
+ const descendants = childDescendants.get(laidOut.id)!;
382
+ for (const id of descendants) {
383
+ movedIds.add(id);
384
+ const position = positions.get(id);
385
+ if (position) positions.set(id, { x: position.x + dx, y: position.y + dy });
386
+ const bounds = nodeBounds.get(id);
387
+ if (bounds) nodeBounds.set(id, { ...bounds, x: bounds.x + dx, y: bounds.y + dy });
388
+ }
389
+ }
390
+ for (const edge of graph.edges) {
391
+ if (movedIds.has(edge.sourceId) || movedIds.has(edge.targetId)) {
392
+ edgeLabelBounds.delete(edge.id);
393
+ edgeRoutes.set(edge.id, { waypoints: [] });
394
+ }
395
+ }
396
+
397
+ if (group.group?.type === 'derived') {
398
+ let content: Rect | null = null;
399
+ for (const child of children) {
400
+ const bounds = nodeBounds.get(child.id);
401
+ if (bounds) content = unionRect(content, bounds);
402
+ }
403
+ const stored = boundsOf(
404
+ group,
405
+ options.getBounds as ((node: FlowNode) => Rect) | undefined,
406
+ );
407
+ const derived = deriveGroupGeometry(
408
+ { width: stored.width, height: stored.height },
409
+ content,
410
+ group.group,
411
+ nodeBounds.get(group.id),
412
+ ).bounds;
413
+ positions.set(group.id, { x: derived.x, y: derived.y });
414
+ nodeBounds.set(group.id, derived);
415
+ nodeSizes.set(group.id, { width: derived.width, height: derived.height });
416
+ }
417
+ }
418
+ }
419
+
420
+ function rectsOverlap(a: Rect, b: Rect): boolean {
421
+ return (
422
+ a.x < b.x + b.width &&
423
+ a.x + a.width > b.x &&
424
+ a.y < b.y + b.height &&
425
+ a.y + a.height > b.y
426
+ );
427
+ }
428
+
429
+ function centerCompoundEdgeLabels(
430
+ graph: FlowGraph,
431
+ positions: Map<string, Point>,
432
+ boundsById: Map<string, Rect>,
433
+ nodeBounds: ReadonlyMap<string, Rect>,
434
+ nodesById: ReadonlyMap<string, FlowNode>,
435
+ fixedIds: ReadonlySet<string>,
436
+ ): void {
437
+ for (const edge of graph.edges) {
438
+ if (fixedIds.has(edge.id) || edge.sourceId === edge.targetId) continue;
439
+ const sourceNode = nodesById.get(edge.sourceId);
440
+ const targetNode = nodesById.get(edge.targetId);
441
+ if (
442
+ !sourceNode?.parentId ||
443
+ sourceNode.parentId !== targetNode?.parentId
444
+ ) {
445
+ continue;
446
+ }
447
+ const parent = nodesById.get(sourceNode.parentId);
448
+ const direction = parent?.group?.direction ?? graph.direction ?? 'down';
449
+ const source = nodeBounds.get(edge.sourceId);
450
+ const target = nodeBounds.get(edge.targetId);
451
+ const label = boundsById.get(edge.id);
452
+ if (!source || !target || !label) continue;
453
+
454
+ const horizontal = direction === 'left' || direction === 'right';
455
+ const sourceBeforeTarget = horizontal
456
+ ? source.x + source.width / 2 < target.x + target.width / 2
457
+ : source.y + source.height / 2 < target.y + target.height / 2;
458
+ const before = sourceBeforeTarget ? source : target;
459
+ const after = sourceBeforeTarget ? target : source;
460
+ const available = horizontal
461
+ ? after.x - (before.x + before.width)
462
+ : after.y - (before.y + before.height);
463
+ const labelSize = horizontal ? label.width : label.height;
464
+ if (available < labelSize + 48) continue;
465
+
466
+ const position = horizontal
467
+ ? {
468
+ x: before.x + before.width + (available - label.width) / 2,
469
+ y:
470
+ (source.y + source.height / 2 +
471
+ target.y +
472
+ target.height / 2) /
473
+ 2 -
474
+ label.height / 2,
475
+ }
476
+ : {
477
+ x:
478
+ (source.x + source.width / 2 +
479
+ target.x +
480
+ target.width / 2) /
481
+ 2 -
482
+ label.width / 2,
483
+ y: before.y + before.height + (available - label.height) / 2,
484
+ };
485
+ positions.set(edge.id, position);
486
+ boundsById.set(edge.id, { ...label, ...position });
487
+ }
488
+ }
489
+
490
+ function centerAncestorDescendantEdgeLabels(
491
+ graph: FlowGraph,
492
+ positions: Map<string, Point>,
493
+ boundsById: Map<string, Rect>,
494
+ nodeBounds: ReadonlyMap<string, Rect>,
495
+ nodesById: ReadonlyMap<string, FlowNode>,
496
+ fixedIds: ReadonlySet<string>,
497
+ options: FlowLayoutOptions,
498
+ ): void {
499
+ for (const edge of graph.edges) {
500
+ if (fixedIds.has(edge.id) || edge.sourceId === edge.targetId) continue;
501
+ const relation = ancestorEndpoint(edge, nodesById);
502
+ const label = boundsById.get(edge.id);
503
+ const ancestorBounds = relation
504
+ ? nodeBounds.get(relation.ancestor.id)
505
+ : undefined;
506
+ const descendantBounds = relation
507
+ ? nodeBounds.get(relation.descendant.id)
508
+ : undefined;
509
+ if (!relation || !label || !ancestorBounds || !descendantBounds) continue;
510
+
511
+ const content = groupContentBounds(
512
+ relation.ancestor,
513
+ ancestorBounds,
514
+ options.getBounds as ((node: FlowNode) => Rect) | undefined,
515
+ );
516
+ const side = relation.ancestor.group?.content ?? 'top';
517
+ const vertical = side === 'top' || side === 'bottom';
518
+ const before =
519
+ side === 'top' || side === 'left' ? content : descendantBounds;
520
+ const after =
521
+ side === 'top' || side === 'left' ? descendantBounds : content;
522
+ const available = vertical
523
+ ? after.y - (before.y + before.height)
524
+ : after.x - (before.x + before.width);
525
+ const labelSize = vertical ? label.height : label.width;
526
+ if (available < labelSize + 24) continue;
527
+
528
+ const position = vertical
529
+ ? {
530
+ x:
531
+ descendantBounds.x +
532
+ descendantBounds.width / 2 -
533
+ label.width / 2,
534
+ y: before.y + before.height + (available - label.height) / 2,
535
+ }
536
+ : {
537
+ x: before.x + before.width + (available - label.width) / 2,
538
+ y:
539
+ descendantBounds.y +
540
+ descendantBounds.height / 2 -
541
+ label.height / 2,
542
+ };
543
+ positions.set(edge.id, position);
544
+ boundsById.set(edge.id, { ...label, ...position });
545
+ }
546
+ }
547
+
548
+ function avoidEdgeLabelOverlaps(
549
+ graph: FlowGraph,
550
+ positions: Map<string, Point>,
551
+ boundsById: Map<string, Rect>,
552
+ nodeBounds: ReadonlyMap<string, Rect>,
553
+ nodesById: ReadonlyMap<string, FlowNode>,
554
+ fixedIds: ReadonlySet<string>,
555
+ direction = graph.direction ?? 'down',
556
+ ): boolean {
557
+ const settledLabels: Rect[] = [];
558
+ let moved = false;
559
+
560
+ for (const edge of graph.edges) {
561
+ const bounds = boundsById.get(edge.id);
562
+ if (!bounds || fixedIds.has(edge.id)) continue;
563
+
564
+ const ignoredNodeIds = new Set<string>();
565
+ const containerId = semanticEdgeOwnerId(edge, nodesById);
566
+ if (edge.sourceId === edge.targetId) {
567
+ ignoredNodeIds.add(edge.sourceId);
568
+ }
569
+ if (containerId) {
570
+ let container = nodesById.get(containerId);
571
+ while (container) {
572
+ ignoredNodeIds.add(container.id);
573
+ container = container.parentId
574
+ ? nodesById.get(container.parentId)
575
+ : undefined;
576
+ }
577
+ }
578
+
579
+ const obstacles = [
580
+ ...[...nodeBounds].flatMap(([id, rect]) =>
581
+ ignoredNodeIds.has(id) ? [] : [rect],
582
+ ),
583
+ ...settledLabels,
584
+ ];
585
+ const ancestor = ancestorEndpoint(edge, nodesById)?.ancestor;
586
+ const contentSide = ancestor?.group?.content;
587
+ const labelDirection =
588
+ contentSide === 'top' || contentSide === 'bottom'
589
+ ? 'down'
590
+ : contentSide === 'left' || contentSide === 'right'
591
+ ? 'right'
592
+ : direction;
593
+ const position = nearestClearLabelPosition(
594
+ bounds,
595
+ obstacles,
596
+ labelDirection,
597
+ );
598
+ if (position.x !== bounds.x || position.y !== bounds.y) moved = true;
599
+ const placed = { ...bounds, ...position };
600
+ positions.set(edge.id, position);
601
+ boundsById.set(edge.id, placed);
602
+ settledLabels.push(placed);
603
+ }
604
+ return moved;
605
+ }
606
+
607
+ function nearestClearLabelPosition(
608
+ label: Rect,
609
+ obstacles: readonly Rect[],
610
+ direction: string,
611
+ ): Point {
612
+ const gap = 12;
613
+ const origin = { x: label.x, y: label.y };
614
+ const horizontal = direction === 'left' || direction === 'right';
615
+ const score = (point: Point) => {
616
+ const dx = point.x - origin.x;
617
+ const dy = point.y - origin.y;
618
+ return horizontal ? dx * dx * 2 + dy * dy : dx * dx + dy * dy * 2;
619
+ };
620
+ const candidates: Point[] = [origin];
621
+ const visited = new Set<string>();
622
+
623
+ for (let attempts = 0; candidates.length > 0 && attempts < 1_000; attempts++) {
624
+ candidates.sort((a, b) => score(a) - score(b));
625
+ const candidate = candidates.shift()!;
626
+ const key = `${candidate.x.toFixed(3)},${candidate.y.toFixed(3)}`;
627
+ if (visited.has(key)) continue;
628
+ visited.add(key);
629
+
630
+ const candidateBounds = { ...label, ...candidate };
631
+ const overlapping = obstacles.filter((obstacle) =>
632
+ rectsOverlap(candidateBounds, obstacle),
633
+ );
634
+ if (overlapping.length === 0) return candidate;
635
+
636
+ for (const obstacle of overlapping) {
637
+ candidates.push(
638
+ { x: obstacle.x - label.width - gap, y: candidate.y },
639
+ { x: obstacle.x + obstacle.width + gap, y: candidate.y },
640
+ { x: candidate.x, y: obstacle.y - label.height - gap },
641
+ { x: candidate.x, y: obstacle.y + obstacle.height + gap },
642
+ );
643
+ }
644
+ }
645
+
646
+ return origin;
647
+ }
648
+
649
+ function reconcileDerivedGroupBounds(
650
+ graph: FlowGraph,
651
+ positions: Map<string, Point>,
652
+ nodeSizes: Map<string, Size>,
653
+ nodeBounds: Map<string, Rect>,
654
+ edgeLabelPositions: Map<string, Point>,
655
+ edgeLabelBounds: Map<string, Rect>,
656
+ edgeRoutes: Map<string, { waypoints: Point[] }>,
657
+ fixedIds: ReadonlySet<string>,
658
+ options: FlowLayoutOptions,
659
+ ): boolean {
660
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
661
+ const childrenByParent = new Map<string | undefined, string[]>();
662
+ for (const node of graph.nodes) {
663
+ const parentId = node.parentId ?? undefined;
664
+ const children = childrenByParent.get(parentId) ?? [];
665
+ children.push(node.id);
666
+ childrenByParent.set(parentId, children);
667
+ }
668
+ const edgesByOwner = new Map<string, FlowEdge[]>();
669
+ for (const edge of graph.edges) {
670
+ const ownerId = semanticEdgeOwnerId(edge, nodesById);
671
+ if (!ownerId) continue;
672
+ const edges = edgesByOwner.get(ownerId) ?? [];
673
+ edges.push(edge);
674
+ edgesByOwner.set(ownerId, edges);
675
+ }
676
+
677
+ const effectiveBounds = (id: string, cache: Map<string, Rect>): Rect => {
678
+ const cached = cache.get(id);
679
+ if (cached) return cached;
680
+ const node = nodesById.get(id)!;
681
+ const base = nodeBounds.get(id) ?? boundsOf(node, options.getBounds as (node: FlowNode) => Rect);
682
+ if (node.group?.type !== 'derived') {
683
+ cache.set(id, base);
684
+ return base;
685
+ }
686
+
687
+ let content: Rect | null = null;
688
+ for (const childId of childrenByParent.get(id) ?? []) {
689
+ content = unionRect(content, effectiveBounds(childId, cache));
690
+ }
691
+ for (const edge of edgesByOwner.get(id) ?? []) {
692
+ if (edge.sourceId === id && edge.targetId === id) continue;
693
+ const label = edgeLabelBounds.get(edge.id);
694
+ if (label) content = unionRect(content, label);
695
+ }
696
+ const stored = boundsOf(node, options.getBounds as (node: FlowNode) => Rect);
697
+ const derived = deriveGroupGeometry(
698
+ { width: stored.width, height: stored.height },
699
+ content,
700
+ node.group,
701
+ base,
702
+ ).bounds;
703
+ cache.set(id, derived);
704
+ return derived;
705
+ };
706
+
707
+ const descendantsOf = (id: string): Set<string> => {
708
+ const descendants = new Set<string>([id]);
709
+ const pending = [id];
710
+ while (pending.length > 0) {
711
+ for (const childId of childrenByParent.get(pending.pop()!) ?? []) {
712
+ descendants.add(childId);
713
+ pending.push(childId);
714
+ }
715
+ }
716
+ return descendants;
717
+ };
718
+
719
+ const shiftSubtree = (id: string, dx: number, dy: number): void => {
720
+ const descendants = descendantsOf(id);
721
+ for (const nodeId of descendants) {
722
+ const position = positions.get(nodeId);
723
+ if (position) positions.set(nodeId, { x: position.x + dx, y: position.y + dy });
724
+ const bounds = nodeBounds.get(nodeId);
725
+ if (bounds) nodeBounds.set(nodeId, { ...bounds, x: bounds.x + dx, y: bounds.y + dy });
726
+ }
727
+ for (const edge of graph.edges) {
728
+ const ownerId = semanticEdgeOwnerId(edge, nodesById);
729
+ if (ownerId && descendants.has(ownerId)) {
730
+ const position = edgeLabelPositions.get(edge.id);
731
+ if (position) {
732
+ edgeLabelPositions.set(edge.id, {
733
+ x: position.x + dx,
734
+ y: position.y + dy,
735
+ });
736
+ }
737
+ const bounds = edgeLabelBounds.get(edge.id);
738
+ if (bounds) {
739
+ edgeLabelBounds.set(edge.id, {
740
+ ...bounds,
741
+ x: bounds.x + dx,
742
+ y: bounds.y + dy,
743
+ });
744
+ }
745
+ const route = edgeRoutes.get(edge.id);
746
+ if (route) {
747
+ edgeRoutes.set(edge.id, {
748
+ waypoints: route.waypoints.map((point) => ({
749
+ x: point.x + dx,
750
+ y: point.y + dy,
751
+ })),
752
+ });
753
+ }
754
+ } else if (
755
+ descendants.has(edge.sourceId) ||
756
+ descendants.has(edge.targetId)
757
+ ) {
758
+ edgeRoutes.set(edge.id, { waypoints: [] });
759
+ }
760
+ }
761
+ };
762
+
763
+ const direction = options.direction ?? graph.direction ?? 'down';
764
+ const horizontal = direction === 'left' || direction === 'right';
765
+ const reverse = direction === 'left' || direction === 'up';
766
+ let cache = new Map<string, Rect>();
767
+ let changed = false;
768
+ const gap = options.nodeSpacing ?? 60;
769
+
770
+ const depthOf = (parentId: string | undefined): number => {
771
+ let depth = 0;
772
+ let marker = parentId ? nodesById.get(parentId) : undefined;
773
+ while (marker) {
774
+ depth++;
775
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
776
+ }
777
+ return depth;
778
+ };
779
+ const containers = [...childrenByParent.keys()].sort(
780
+ (a, b) => depthOf(b) - depthOf(a),
781
+ );
782
+
783
+ for (const containerId of containers) {
784
+ const ordered = [...(childrenByParent.get(containerId) ?? [])].sort(
785
+ (a, b) => {
786
+ const aBounds = effectiveBounds(a, cache);
787
+ const bBounds = effectiveBounds(b, cache);
788
+ const delta = horizontal
789
+ ? aBounds.x - bBounds.x
790
+ : aBounds.y - bBounds.y;
791
+ return reverse ? -delta : delta;
792
+ },
793
+ );
794
+ for (let i = 0; i < ordered.length; i++) {
795
+ for (let j = i + 1; j < ordered.length; j++) {
796
+ const first = effectiveBounds(ordered[i]!, cache);
797
+ const second = effectiveBounds(ordered[j]!, cache);
798
+ if (!rectsOverlap(first, second)) continue;
799
+ if ([...descendantsOf(ordered[j]!)].some((id) => fixedIds.has(id))) {
800
+ continue;
801
+ }
802
+ const delta = horizontal
803
+ ? reverse
804
+ ? first.x - gap - (second.x + second.width)
805
+ : first.x + first.width + gap - second.x
806
+ : reverse
807
+ ? first.y - gap - (second.y + second.height)
808
+ : first.y + first.height + gap - second.y;
809
+ shiftSubtree(
810
+ ordered[j]!,
811
+ horizontal ? delta : 0,
812
+ horizontal ? 0 : delta,
813
+ );
814
+ cache = new Map();
815
+ changed = true;
816
+ }
817
+ }
818
+ }
819
+
820
+ cache = new Map();
821
+ for (const node of graph.nodes) {
822
+ if (node.group?.type !== 'derived' || fixedIds.has(node.id)) continue;
823
+ const bounds = effectiveBounds(node.id, cache);
824
+ positions.set(node.id, { x: bounds.x, y: bounds.y });
825
+ nodeBounds.set(node.id, bounds);
826
+ nodeSizes.set(node.id, { width: bounds.width, height: bounds.height });
827
+ }
828
+ return changed;
829
+ }
830
+
831
+ function unionRect(a: Rect | null, b: Rect): Rect {
832
+ if (!a) return { ...b };
833
+ const x = Math.min(a.x, b.x);
834
+ const y = Math.min(a.y, b.y);
835
+ const right = Math.max(a.x + a.width, b.x + b.width);
836
+ const bottom = Math.max(a.y + a.height, b.y + b.height);
837
+ return { x, y, width: right - x, height: bottom - y };
838
+ }
839
+
840
+ const SIDE_TO_ELK: Record<string, string> = {
841
+ top: 'NORTH',
842
+ bottom: 'SOUTH',
843
+ left: 'WEST',
844
+ right: 'EAST',
845
+ };
846
+
847
+ export function toElkGraph(
848
+ graph: FlowGraph,
849
+ options: FlowLayoutOptions,
850
+ ): ElkNode {
851
+ const childIdsByParent = new Map<string | undefined, string[]>();
852
+ for (const node of graph.nodes) {
853
+ const parentId = node.parentId ?? undefined;
854
+ const siblings = childIdsByParent.get(parentId) ?? [];
855
+ siblings.push(node.id);
856
+ childIdsByParent.set(parentId, siblings);
857
+ }
858
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
859
+ const ancestorLabelClearance = new Map<string, number>();
860
+ for (const edge of graph.edges) {
861
+ if (!edge.label) continue;
862
+ const ancestor = ancestorEndpoint(edge, nodesById)?.ancestor;
863
+ if (!ancestor?.group) continue;
864
+ const side = ancestor.group.content ?? 'top';
865
+ const extent =
866
+ (side === 'top' || side === 'bottom'
867
+ ? edge.label.height
868
+ : edge.label.width) + 24;
869
+ ancestorLabelClearance.set(
870
+ ancestor.id,
871
+ Math.max(ancestorLabelClearance.get(ancestor.id) ?? 0, extent),
872
+ );
873
+ }
874
+
875
+ // Assign each edge to the Lowest Common Ancestor (LCA) of its source &
876
+ // target and nest it in THAT container's ELK subtree (not root), so ELK
877
+ // routes intra-group edges INSIDE the group. Edges crossing group
878
+ // boundaries — or with no common group — live at the root.
879
+ const edgesByContainer = new Map<string | undefined, ElkExtendedEdge[]>();
880
+ for (const edge of graph.edges) {
881
+ const containerId = elkEdgeContainerId(edge, nodesById);
882
+ const bucket = edgesByContainer.get(containerId) ?? [];
883
+ bucket.push(toElkEdge(edge, options));
884
+ edgesByContainer.set(containerId, bucket);
885
+ }
886
+ const rootEdges = edgesByContainer.get(undefined) ?? [];
887
+ const hasRootHierarchyEdge = hasRootHierarchyEdges(graph, nodesById);
888
+ const rootDirection = options.direction ?? graph.direction;
889
+ const graphOptions = stringOptions(options.graph);
890
+ const configuredRootRankSpacing = finiteNumberOption(
891
+ graphOptions['elk.layered.spacing.nodeNodeBetweenLayers'] ??
892
+ options.rankSpacing,
893
+ 90,
894
+ );
895
+ const hasDerivedGroup = graph.nodes.some(
896
+ (node) => node.group?.type === 'derived',
897
+ );
898
+
899
+ return {
900
+ id: 'root',
901
+ layoutOptions: {
902
+ 'elk.algorithm': 'layered',
903
+ 'elk.direction': elkDirection(rootDirection),
904
+ 'elk.spacing.nodeNode': String(options.nodeSpacing ?? 60),
905
+ 'elk.layered.spacing.nodeNodeBetweenLayers': String(options.rankSpacing ?? 90),
906
+ ...(options.scope ? { 'elk.interactive': 'true' } : {}),
907
+ ...graphOptions,
908
+ ...(hasRootHierarchyEdge
909
+ ? { 'elk.hierarchyHandling': 'INCLUDE_CHILDREN' }
910
+ : {}),
911
+ ...(hasDerivedGroup
912
+ ? {
913
+ 'elk.layered.spacing.nodeNodeBetweenLayers': String(
914
+ labelAwareRankSpacing(
915
+ rootEdges,
916
+ rootDirection === 'left' || rootDirection === 'right',
917
+ configuredRootRankSpacing,
918
+ ),
919
+ ),
920
+ }
921
+ : {}),
922
+ },
923
+ children: (childIdsByParent.get(undefined) ?? []).map((id) =>
924
+ toElkNode(
925
+ nodesById.get(id)!,
926
+ childIdsByParent,
927
+ nodesById,
928
+ edgesByContainer,
929
+ ancestorLabelClearance,
930
+ options,
931
+ ),
932
+ ),
933
+ edges: rootEdges,
934
+ };
935
+ }
936
+
937
+ function hasRootHierarchyEdges(
938
+ graph: FlowGraph,
939
+ nodesById: ReadonlyMap<string, FlowNode>,
940
+ ): boolean {
941
+ return graph.edges.some((edge) => {
942
+ if (elkEdgeContainerId(edge, nodesById) !== undefined) return false;
943
+ return ancestorEndpoint(edge, nodesById) !== undefined;
944
+ });
945
+ }
946
+
947
+ function toElkEdge(edge: FlowEdge, options: FlowLayoutOptions): ElkExtendedEdge {
948
+ const labelLayoutOptions = stringOptions(options.label);
949
+ return {
950
+ id: edge.id,
951
+ sources: [edge.sourcePort ? `${edge.sourceId}:${edge.sourcePort}` : edge.sourceId],
952
+ targets: [edge.targetPort ? `${edge.targetId}:${edge.targetPort}` : edge.targetId],
953
+ labels: edge.label
954
+ ? [
955
+ {
956
+ id: `${edge.id}:label`,
957
+ width: edge.label.width,
958
+ height: edge.label.height,
959
+ ...(Object.keys(labelLayoutOptions).length > 0
960
+ ? { layoutOptions: labelLayoutOptions }
961
+ : {}),
962
+ },
963
+ ]
964
+ : undefined,
965
+ ...options.edge,
966
+ } as ElkExtendedEdge;
967
+ }
968
+
969
+ /**
970
+ * The semantic owner whose derived bounds include the edge label: the Lowest
971
+ * Common Ancestor of its source & target (undefined = root). Walk the source's
972
+ * ancestor chain (including the source itself) into a set, then walk the
973
+ * target's chain up until it hits a member of that set. An edge whose
974
+ * endpoints are both children of group G resolves to G; a cross-boundary edge
975
+ * resolves to the shared ancestor (often root/undefined).
976
+ */
977
+ function semanticEdgeOwnerId(
978
+ edge: FlowEdge,
979
+ nodesById: ReadonlyMap<string, FlowNode>,
980
+ ): string | undefined {
981
+ const source = nodesById.get(edge.sourceId);
982
+ const target = edge.targetId ? nodesById.get(edge.targetId) : undefined;
983
+ if (!source) return undefined;
984
+ if (!target || source === target) return source.parentId ?? undefined;
985
+
986
+ const ancestors = new Set<string>([source.id]);
987
+ let marker: FlowNode | undefined = source.parentId
988
+ ? nodesById.get(source.parentId)
989
+ : undefined;
990
+ while (marker) {
991
+ ancestors.add(marker.id);
992
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
993
+ }
994
+ marker = target;
995
+ while (marker) {
996
+ if (ancestors.has(marker.id)) return marker.id;
997
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
998
+ }
999
+ return undefined;
1000
+ }
1001
+
1002
+ function ancestorEndpoint(
1003
+ edge: FlowEdge,
1004
+ nodesById: ReadonlyMap<string, FlowNode>,
1005
+ ): { ancestor: FlowNode; descendant: FlowNode } | undefined {
1006
+ const source = nodesById.get(edge.sourceId);
1007
+ const target = edge.targetId ? nodesById.get(edge.targetId) : undefined;
1008
+ if (!source || !target) return undefined;
1009
+
1010
+ const isAncestor = (ancestor: FlowNode, descendant: FlowNode) => {
1011
+ let marker = descendant.parentId
1012
+ ? nodesById.get(descendant.parentId)
1013
+ : undefined;
1014
+ while (marker) {
1015
+ if (marker.id === ancestor.id) return true;
1016
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
1017
+ }
1018
+ return false;
1019
+ };
1020
+
1021
+ if (source.group && isAncestor(source, target)) {
1022
+ return { ancestor: source, descendant: target };
1023
+ }
1024
+ if (target.group && isAncestor(target, source)) {
1025
+ return { ancestor: target, descendant: source };
1026
+ }
1027
+ return undefined;
1028
+ }
1029
+
1030
+ function groupContentBounds(
1031
+ node: FlowNode,
1032
+ bounds: Rect,
1033
+ getBounds?: (node: FlowNode) => Rect,
1034
+ ): Rect {
1035
+ const side = node.group?.content ?? 'top';
1036
+ const size =
1037
+ node.group?.type === 'fixed'
1038
+ ? (node.group.contentSize ?? { width: 0, height: 0 })
1039
+ : boundsOf(node, getBounds);
1040
+ if (side === 'top' || side === 'bottom') {
1041
+ const height = Math.min(size.height, bounds.height);
1042
+ return {
1043
+ x: bounds.x,
1044
+ y: side === 'top' ? bounds.y : bounds.y + bounds.height - height,
1045
+ width: bounds.width,
1046
+ height,
1047
+ };
1048
+ }
1049
+ const width = Math.min(size.width, bounds.width);
1050
+ return {
1051
+ x: side === 'left' ? bounds.x : bounds.x + bounds.width - width,
1052
+ y: bounds.y,
1053
+ width,
1054
+ height: bounds.height,
1055
+ };
1056
+ }
1057
+
1058
+ function elkEdgeContainerId(
1059
+ edge: FlowEdge,
1060
+ nodesById: ReadonlyMap<string, FlowNode>,
1061
+ ): string | undefined {
1062
+ const source = nodesById.get(edge.sourceId);
1063
+ const target = edge.targetId ? nodesById.get(edge.targetId) : undefined;
1064
+ // Self-edge or dangling target: nest in the source's parent group.
1065
+ if (!source) return undefined;
1066
+ if (!target || source === target) return source.parentId ?? undefined;
1067
+
1068
+ const isAncestorOf = (ancestor: FlowNode, descendant: FlowNode): boolean => {
1069
+ let marker = descendant.parentId
1070
+ ? nodesById.get(descendant.parentId)
1071
+ : undefined;
1072
+ while (marker) {
1073
+ if (marker.id === ancestor.id) return true;
1074
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
1075
+ }
1076
+ return false;
1077
+ };
1078
+
1079
+ // A container cannot also be an endpoint of an edge nested inside itself.
1080
+ // Keep ancestor-descendant edges on the ancestor's parent canvas for ELK;
1081
+ // semantic ownership still belongs to the ancestor.
1082
+ if (isAncestorOf(source, target)) return source.parentId ?? undefined;
1083
+ if (isAncestorOf(target, source)) return target.parentId ?? undefined;
1084
+
1085
+ // Source's ancestor chain, including the source itself.
1086
+ const ancestors = new Set<string>([source.id]);
1087
+ let marker: FlowNode | undefined = source.parentId
1088
+ ? nodesById.get(source.parentId)
1089
+ : undefined;
1090
+ while (marker) {
1091
+ ancestors.add(marker.id);
1092
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
1093
+ }
1094
+
1095
+ // First target-chain node (including target itself) that's a source
1096
+ // ancestor is the LCA — the deepest node containing both endpoints. When
1097
+ // both endpoints are children of group G, this is G, so the edge nests in
1098
+ // G. A cross-boundary edge resolves to a higher shared node (often root).
1099
+ marker = target;
1100
+ while (marker) {
1101
+ if (ancestors.has(marker.id)) return marker.id;
1102
+ marker = marker.parentId ? nodesById.get(marker.parentId) : undefined;
1103
+ }
1104
+ return undefined;
1105
+ }
1106
+
1107
+ function toElkNode(
1108
+ node: FlowNode,
1109
+ childIdsByParent: Map<string | undefined, string[]>,
1110
+ nodesById: Map<string, FlowNode>,
1111
+ edgesByContainer: Map<string | undefined, ElkExtendedEdge[]>,
1112
+ ancestorLabelClearance: ReadonlyMap<string, number>,
1113
+ options: FlowLayoutOptions,
1114
+ ): ElkNode {
1115
+ const bounds = boundsOf(node, options.getBounds as (node: FlowNode) => any);
1116
+ const children = (childIdsByParent.get(node.id) ?? []).map((id) =>
1117
+ toElkNode(
1118
+ nodesById.get(id)!,
1119
+ childIdsByParent,
1120
+ nodesById,
1121
+ edgesByContainer,
1122
+ ancestorLabelClearance,
1123
+ options,
1124
+ ),
1125
+ );
1126
+ const ports = (node.ports ?? []).map((port) => ({
1127
+ id: `${node.id}:${port.name}`,
1128
+ x: port.x,
1129
+ y: port.y,
1130
+ width: port.width,
1131
+ height: port.height,
1132
+ layoutOptions: {
1133
+ 'elk.port.side': SIDE_TO_ELK[(port as { side?: string }).side ?? 'right'] ?? 'EAST',
1134
+ },
1135
+ }));
1136
+
1137
+ // Edges whose LCA is this node nest here so ELK routes them within it.
1138
+ const nestedEdges = edgesByContainer.get(node.id);
1139
+ const isCompound = children.length > 0 && isGroup(node);
1140
+ const configuredNode = { ...(options.node ?? {}) };
1141
+ const configuredLayoutOptions =
1142
+ configuredNode.layoutOptions &&
1143
+ typeof configuredNode.layoutOptions === 'object' &&
1144
+ !Array.isArray(configuredNode.layoutOptions)
1145
+ ? stringOptions(configuredNode.layoutOptions as Record<string, unknown>)
1146
+ : {};
1147
+ delete configuredNode.layoutOptions;
1148
+ for (const [key, value] of Object.entries(configuredNode)) {
1149
+ if (!key.startsWith('elk.')) continue;
1150
+ configuredLayoutOptions[key] = String(value);
1151
+ delete configuredNode[key];
1152
+ }
1153
+ const layoutOptions: Record<string, string> = configuredLayoutOptions;
1154
+ if (ports.length > 0) layoutOptions['elk.portConstraints'] = 'FIXED_SIDE';
1155
+ if (isCompound) {
1156
+ // Lay out this compound's descendants as one graph so it's sized to
1157
+ // contain them and its intra-group edges route INSIDE it. Set on the
1158
+ // compound (not root): setting it on root would force the root direction
1159
+ // onto every descendant.
1160
+ layoutOptions['elk.hierarchyHandling'] = 'INCLUDE_CHILDREN';
1161
+ // Let ELK size the compound around its children (a fixed authored
1162
+ // width/height would fight the child union and clip them), and reserve
1163
+ // the content block (header) side via padding so children never overlap
1164
+ // it.
1165
+ layoutOptions['elk.padding'] = elkPadding(
1166
+ groupInsets(
1167
+ node.group!,
1168
+ { width: bounds.width, height: bounds.height },
1169
+ ancestorLabelClearance.get(node.id),
1170
+ ),
1171
+ );
1172
+ layoutOptions['elk.nodeSize.constraints'] = 'NODE_LABELS PORTS MINIMUM_SIZE';
1173
+ layoutOptions['elk.nodeSize.minimum'] = `(${bounds.width},${bounds.height})`;
1174
+ const contentSide = node.group?.content ?? 'top';
1175
+ layoutOptions['elk.contentAlignment'] =
1176
+ contentSide === 'top' || contentSide === 'bottom'
1177
+ ? 'H_CENTER'
1178
+ : 'V_CENTER';
1179
+ const direction = node.group?.direction ?? options.direction ?? 'down';
1180
+ layoutOptions['elk.direction'] = elkDirection(direction);
1181
+ applyCompoundLayeredOptions(
1182
+ layoutOptions,
1183
+ nestedEdges ?? [],
1184
+ direction,
1185
+ options,
1186
+ );
1187
+ }
1188
+
1189
+ const elkNode: ElkNode = {
1190
+ id: node.id,
1191
+ x: node.x,
1192
+ y: node.y,
1193
+ ports,
1194
+ children: children.length > 0 ? children : undefined,
1195
+ edges: nestedEdges && nestedEdges.length > 0 ? nestedEdges : undefined,
1196
+ ...configuredNode,
1197
+ layoutOptions:
1198
+ Object.keys(layoutOptions).length > 0 ? layoutOptions : undefined,
1199
+ };
1200
+ // Compounds are sized by ELK from their children; a fixed authored size
1201
+ // fights the child union and clips them. The width/height keys must be
1202
+ // OMITTED entirely (not set to undefined) — elkjs crashes on present-but-
1203
+ // undefined size keys.
1204
+ if (!isCompound) {
1205
+ elkNode.width = bounds.width;
1206
+ elkNode.height = bounds.height;
1207
+ }
1208
+ return elkNode;
1209
+ }
1210
+
1211
+ /**
1212
+ * A compound is an independent layered graph. Root graph options are not
1213
+ * inherited reliably by that nested graph, so propagate the readability
1214
+ * options that matter there and reserve enough rank space for native labels.
1215
+ */
1216
+ function applyCompoundLayeredOptions(
1217
+ layoutOptions: Record<string, string>,
1218
+ edges: readonly ElkExtendedEdge[],
1219
+ direction: string,
1220
+ options: FlowLayoutOptions,
1221
+ ): void {
1222
+ const graphOptions = stringOptions(options.graph);
1223
+ const propagatedOptions = [
1224
+ 'elk.spacing.edgeNode',
1225
+ 'elk.layered.spacing.edgeNodeBetweenLayers',
1226
+ 'elk.layered.nodePlacement.favorStraightEdges',
1227
+ 'elk.layered.nodePlacement.bk.edgeStraightening',
1228
+ 'elk.layered.feedbackEdges',
1229
+ 'elk.layered.unnecessaryBendpoints',
1230
+ ] as const;
1231
+
1232
+ for (const key of propagatedOptions) {
1233
+ if (layoutOptions[key] === undefined && graphOptions[key] !== undefined) {
1234
+ layoutOptions[key] = graphOptions[key];
1235
+ }
1236
+ }
1237
+
1238
+ layoutOptions['elk.layered.nodePlacement.favorStraightEdges'] ??= 'true';
1239
+ layoutOptions['elk.layered.nodePlacement.bk.edgeStraightening'] ??=
1240
+ 'IMPROVE_STRAIGHTNESS';
1241
+
1242
+ const horizontal = direction === 'left' || direction === 'right';
1243
+ const spacingKey = 'elk.layered.spacing.nodeNodeBetweenLayers';
1244
+ const configuredSpacing = finiteNumberOption(
1245
+ layoutOptions[spacingKey] ??
1246
+ graphOptions[spacingKey] ??
1247
+ options.rankSpacing,
1248
+ 20,
1249
+ );
1250
+ // Keep a native edge label between ranks, with enough clearance that the
1251
+ // source -> event -> target chain remains readable instead of doglegging.
1252
+ layoutOptions[spacingKey] = String(
1253
+ labelAwareRankSpacing(edges, horizontal, configuredSpacing),
1254
+ );
1255
+ }
1256
+
1257
+ function labelAwareRankSpacing(
1258
+ edges: readonly ElkExtendedEdge[],
1259
+ horizontal: boolean,
1260
+ configuredSpacing: number,
1261
+ ): number {
1262
+ const largestLabel = Math.max(
1263
+ 0,
1264
+ ...edges.flatMap((edge) =>
1265
+ (edge.labels ?? []).map((label) =>
1266
+ horizontal ? label.width ?? 0 : label.height ?? 0,
1267
+ ),
1268
+ ),
1269
+ );
1270
+ return Math.max(configuredSpacing, largestLabel + 48);
1271
+ }
1272
+
1273
+ function finiteNumberOption(value: unknown, fallback: number): number {
1274
+ const parsed = Number(value);
1275
+ return Number.isFinite(parsed) ? parsed : fallback;
1276
+ }
1277
+
1278
+ /**
1279
+ * The inset ELK must leave inside a compound so children clear the group's
1280
+ * content block (header) and honor its padding. The content block occupies
1281
+ * one side at `contentSize` (fixed groups) or the node's own size (derived
1282
+ * groups); every side also carries the group's padding.
1283
+ */
1284
+ function groupInsets(
1285
+ group: NonNullable<FlowNode['group']>,
1286
+ bounds: Size,
1287
+ contentClearance = 0,
1288
+ ): GroupInsets {
1289
+ const padding = resolveGroupPadding((group as GroupLayout).padding);
1290
+ const side: GroupContentSide = (group as GroupLayout).content ?? 'top';
1291
+ const contentSize: Size =
1292
+ group.type === 'fixed'
1293
+ ? group.contentSize ?? { width: 0, height: 0 }
1294
+ : bounds;
1295
+ const insets: GroupInsets = { ...padding };
1296
+ if (side === 'top')
1297
+ insets.top = contentSize.height + Math.max(padding.top, contentClearance);
1298
+ else if (side === 'bottom')
1299
+ insets.bottom =
1300
+ contentSize.height + Math.max(padding.bottom, contentClearance);
1301
+ else if (side === 'left')
1302
+ insets.left = contentSize.width + Math.max(padding.left, contentClearance);
1303
+ else
1304
+ insets.right =
1305
+ contentSize.width + Math.max(padding.right, contentClearance);
1306
+ return insets;
1307
+ }
1308
+
1309
+ function elkPadding(insets: GroupInsets): string {
1310
+ return `[top=${insets.top},left=${insets.left},bottom=${insets.bottom},right=${insets.right}]`;
1311
+ }
1312
+
1313
+ function collectElkGeometry(
1314
+ node: ElkNode,
1315
+ output: {
1316
+ positions: Map<string, Point>;
1317
+ nodeSizes: Map<string, Size>;
1318
+ nodeBounds: Map<string, Rect>;
1319
+ edgeLabelBounds: Map<string, Rect>;
1320
+ edgeRoutes: Map<string, { waypoints: Point[] }>;
1321
+ fixedIds: ReadonlySet<string>;
1322
+ },
1323
+ offsetX = 0,
1324
+ offsetY = 0,
1325
+ ): void {
1326
+ const x = offsetX + (node.x ?? 0);
1327
+ const y = offsetY + (node.y ?? 0);
1328
+ if (
1329
+ node.id !== 'root' &&
1330
+ !output.fixedIds.has(node.id) &&
1331
+ Number.isFinite(x) &&
1332
+ Number.isFinite(y) &&
1333
+ Number.isFinite(node.width) &&
1334
+ Number.isFinite(node.height)
1335
+ ) {
1336
+ const size = { width: node.width!, height: node.height! };
1337
+ output.positions.set(node.id, { x, y });
1338
+ output.nodeSizes.set(node.id, size);
1339
+ output.nodeBounds.set(node.id, { x, y, ...size });
1340
+ }
1341
+ for (const edge of node.edges ?? []) {
1342
+ if (output.fixedIds.has(edge.id)) continue;
1343
+ const label = edge.labels?.[0];
1344
+ if (
1345
+ label &&
1346
+ Number.isFinite(label.x) &&
1347
+ Number.isFinite(label.y) &&
1348
+ Number.isFinite(label.width) &&
1349
+ Number.isFinite(label.height)
1350
+ ) {
1351
+ output.edgeLabelBounds.set(edge.id, {
1352
+ x: x + label.x!,
1353
+ y: y + label.y!,
1354
+ width: label.width!,
1355
+ height: label.height!,
1356
+ });
1357
+ }
1358
+ const sections = edge.sections ?? [];
1359
+ if (sections.length === 1) {
1360
+ output.edgeRoutes.set(edge.id, {
1361
+ waypoints: (sections[0]!.bendPoints ?? []).map((point) => ({
1362
+ x: x + point.x,
1363
+ y: y + point.y,
1364
+ })),
1365
+ });
1366
+ }
1367
+ }
1368
+ for (const child of node.children ?? []) {
1369
+ collectElkGeometry(child, output, x, y);
1370
+ }
1371
+ }
1372
+
1373
+ function stringOptions(options: Record<string, unknown> | undefined): Record<string, string> {
1374
+ if (!options) return {};
1375
+ return Object.fromEntries(
1376
+ Object.entries(options).map(([key, value]) => [key, String(value)]),
1377
+ );
1378
+ }
1379
+
1380
+ function elkDirection(direction: string | undefined): string {
1381
+ return (direction ?? 'down').toUpperCase();
1382
+ }