@statelyai/flow 0.7.0 → 0.9.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.
@@ -1,5 +1,5 @@
1
- import { a as mergedLayoutScope, i as layoutRunContext, n as edgeLabelPositionsFromNodePositions, o as rankDirection, r as graphForLayoutScope, s as throwIfAborted, t as boundsOf } from "../shared.js";
2
- import { isGroup, resolveGroupPadding } from "@statelyai/flow";
1
+ import { a as mergedLayoutScope, i as layoutRunContext, n as edgeLabelPositionsFromNodePositions, r as graphForLayoutScope, s as throwIfAborted, t as boundsOf } from "../shared.js";
2
+ import { deriveGroupGeometry, isGroup, resolveGroupPadding } from "@statelyai/flow";
3
3
  import ELK from "elkjs/lib/elk.bundled.js";
4
4
  //#region src/layout/elk.ts
5
5
  const elkLayout = (options = {}) => {
@@ -28,12 +28,47 @@ const elkLayout = (options = {}) => {
28
28
  edgeRoutes,
29
29
  fixedIds: context.fixedIds
30
30
  });
31
+ await restoreExplicitCompoundDirections(elk, layoutGraph, positions, nodeSizes, nodeBounds, edgeLabelBounds, edgeRoutes, context.fixedIds, options);
32
+ throwIfAborted(runOptions);
31
33
  const edgeLabelPositions = new Map([...edgeLabelBounds].map(([id, bounds]) => [id, {
32
34
  x: bounds.x,
33
35
  y: bounds.y
34
36
  }]));
35
- const fallbackLabels = edgeLabelPositionsFromNodePositions(layoutGraph, positions, options.getBounds);
36
- for (const [id, position] of fallbackLabels ?? []) if (!edgeLabelPositions.has(id) && !context.fixedIds.has(id)) edgeLabelPositions.set(id, position);
37
+ const fallbackLabels = edgeLabelPositionsFromNodePositions(layoutGraph, positions, options.getBounds, nodeBounds, options.direction ?? layoutGraph.direction);
38
+ const nodesById = new Map(layoutGraph.nodes.map((node) => [node.id, node]));
39
+ const edgesById = new Map(layoutGraph.edges.map((edge) => [edge.id, edge]));
40
+ const hasHierarchy = layoutGraph.nodes.some((node) => node.parentId);
41
+ for (const [id, position] of fallbackLabels ?? []) {
42
+ const edge = edgesById.get(id);
43
+ const containerId = edge ? elkEdgeContainerId(edge, nodesById) : void 0;
44
+ const containerOrigin = containerId ? nodeBounds.get(containerId) : {
45
+ x: 0,
46
+ y: 0
47
+ };
48
+ const reported = edgeLabelBounds.get(id);
49
+ const reportedAtContainerOrigin = !!reported && !!containerOrigin && Math.abs(reported.x - containerOrigin.x) <= .5 && Math.abs(reported.y - containerOrigin.y) <= .5;
50
+ const overlapsEndpoint = !!edge && !!reported && [nodeBounds.get(edge.sourceId), nodeBounds.get(edge.targetId)].some((bounds) => bounds && rectsOverlap(reported, bounds));
51
+ const invalidHierarchyPlacement = hasHierarchy && edge?.sourceId !== edge?.targetId && (reportedAtContainerOrigin || overlapsEndpoint);
52
+ if ((!edgeLabelPositions.has(id) || invalidHierarchyPlacement) && !context.fixedIds.has(id)) {
53
+ edgeLabelPositions.set(id, position);
54
+ const bounds = edgeLabelBounds.get(id);
55
+ const label = edge?.label;
56
+ if (bounds || label) edgeLabelBounds.set(id, {
57
+ ...position,
58
+ width: bounds?.width ?? label.width,
59
+ height: bounds?.height ?? label.height
60
+ });
61
+ }
62
+ }
63
+ if (hasHierarchy) {
64
+ centerCompoundEdgeLabels(layoutGraph, edgeLabelPositions, edgeLabelBounds, nodeBounds, nodesById, context.fixedIds);
65
+ centerAncestorDescendantEdgeLabels(layoutGraph, edgeLabelPositions, edgeLabelBounds, nodeBounds, nodesById, context.fixedIds, options);
66
+ for (let pass = 0; pass < 12; pass++) {
67
+ const labelsMoved = avoidEdgeLabelOverlaps(layoutGraph, edgeLabelPositions, edgeLabelBounds, nodeBounds, nodesById, context.fixedIds, options.direction ?? layoutGraph.direction);
68
+ const groupsMoved = reconcileDerivedGroupBounds(layoutGraph, positions, nodeSizes, nodeBounds, edgeLabelPositions, edgeLabelBounds, edgeRoutes, context.fixedIds, options);
69
+ if (!labelsMoved && !groupsMoved) break;
70
+ }
71
+ }
37
72
  const missingNodes = layoutGraph.nodes.map((node) => node.id).filter((id) => !context.fixedIds.has(id) && !positions.has(id)).sort();
38
73
  if (missingNodes.length > 0) {
39
74
  const message = `ELK omitted node geometry: ${missingNodes.join(", ")}`;
@@ -57,6 +92,440 @@ const elkLayout = (options = {}) => {
57
92
  };
58
93
  };
59
94
  };
95
+ async function restoreExplicitCompoundDirections(elk, graph, positions, nodeSizes, nodeBounds, edgeLabelBounds, edgeRoutes, fixedIds, options) {
96
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
97
+ const childrenByParent = /* @__PURE__ */ new Map();
98
+ for (const node of graph.nodes) {
99
+ if (!node.parentId) continue;
100
+ const children = childrenByParent.get(node.parentId) ?? [];
101
+ children.push(node);
102
+ childrenByParent.set(node.parentId, children);
103
+ }
104
+ const depthOf = (node) => {
105
+ let depth = 0;
106
+ let marker = node.parentId ? nodesById.get(node.parentId) : void 0;
107
+ while (marker) {
108
+ depth++;
109
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
110
+ }
111
+ return depth;
112
+ };
113
+ const descendantsOf = (id) => {
114
+ const descendants = /* @__PURE__ */ new Set([id]);
115
+ const pending = [id];
116
+ while (pending.length > 0) for (const child of childrenByParent.get(pending.pop()) ?? []) {
117
+ descendants.add(child.id);
118
+ pending.push(child.id);
119
+ }
120
+ return descendants;
121
+ };
122
+ const directChildOf = (id, groupId) => {
123
+ let marker = nodesById.get(id);
124
+ while (marker?.parentId && marker.parentId !== groupId) marker = nodesById.get(marker.parentId);
125
+ return marker?.parentId === groupId ? marker.id : void 0;
126
+ };
127
+ const groups = graph.nodes.filter((node) => node.group?.direction && node.group.direction !== (options.direction ?? graph.direction ?? "down") && (childrenByParent.get(node.id)?.length ?? 0) > 1).sort((a, b) => depthOf(b) - depthOf(a));
128
+ for (const group of groups) {
129
+ const children = childrenByParent.get(group.id);
130
+ const childDescendants = new Map(children.map((child) => [child.id, descendantsOf(child.id)]));
131
+ if ([...childDescendants.values()].some((ids) => [...ids].some((id) => fixedIds.has(id)))) continue;
132
+ const currentChildren = children.flatMap((child) => {
133
+ const bounds = nodeBounds.get(child.id);
134
+ return bounds ? [{
135
+ child,
136
+ bounds
137
+ }] : [];
138
+ });
139
+ if (currentChildren.length < 2) continue;
140
+ const centers = currentChildren.map(({ bounds }) => ({
141
+ x: bounds.x + bounds.width / 2,
142
+ y: bounds.y + bounds.height / 2
143
+ }));
144
+ const dx = Math.max(...centers.map((center) => center.x)) - Math.min(...centers.map((center) => center.x));
145
+ const dy = Math.max(...centers.map((center) => center.y)) - Math.min(...centers.map((center) => center.y));
146
+ if ((group.group.direction === "right" || group.group.direction === "left") && dx >= dy || (group.group.direction === "down" || group.group.direction === "up") && dy >= dx) continue;
147
+ const localEdges = [];
148
+ for (const edge of graph.edges) {
149
+ const sourceId = directChildOf(edge.sourceId, group.id);
150
+ const targetId = edge.targetId ? directChildOf(edge.targetId, group.id) : void 0;
151
+ if (!sourceId || !targetId || sourceId === targetId) continue;
152
+ localEdges.push({
153
+ id: `direction:${edge.id}`,
154
+ sources: [sourceId],
155
+ targets: [targetId],
156
+ labels: edge.label ? [{
157
+ id: `direction:${edge.id}:label`,
158
+ width: edge.label.width,
159
+ height: edge.label.height
160
+ }] : void 0
161
+ });
162
+ }
163
+ const direction = group.group.direction;
164
+ const localLayoutOptions = {
165
+ "elk.algorithm": "layered",
166
+ "elk.direction": elkDirection(direction),
167
+ "elk.spacing.nodeNode": String(options.nodeSpacing ?? 60)
168
+ };
169
+ applyCompoundLayeredOptions(localLayoutOptions, localEdges, direction, options);
170
+ const laidOutChildren = (await elk.layout({
171
+ id: `direction:${group.id}`,
172
+ layoutOptions: localLayoutOptions,
173
+ children: currentChildren.map(({ child, bounds }) => ({
174
+ id: child.id,
175
+ width: bounds.width,
176
+ height: bounds.height
177
+ })),
178
+ edges: localEdges
179
+ })).children ?? [];
180
+ const currentX = Math.min(...currentChildren.map(({ bounds }) => bounds.x));
181
+ const currentY = Math.min(...currentChildren.map(({ bounds }) => bounds.y));
182
+ const localX = Math.min(...laidOutChildren.map((child) => child.x ?? 0));
183
+ const localY = Math.min(...laidOutChildren.map((child) => child.y ?? 0));
184
+ if (group.group?.type === "fixed") {
185
+ const groupBounds = nodeBounds.get(group.id);
186
+ const candidateBounds = laidOutChildren.reduce((bounds, child) => unionRect(bounds, {
187
+ x: currentX + (child.x ?? 0) - localX,
188
+ y: currentY + (child.y ?? 0) - localY,
189
+ width: child.width ?? 0,
190
+ height: child.height ?? 0
191
+ }), null);
192
+ if (!groupBounds || !candidateBounds || candidateBounds.x < groupBounds.x || candidateBounds.y < groupBounds.y || candidateBounds.x + candidateBounds.width > groupBounds.x + groupBounds.width || candidateBounds.y + candidateBounds.height > groupBounds.y + groupBounds.height) continue;
193
+ }
194
+ const movedIds = /* @__PURE__ */ new Set();
195
+ for (const laidOut of laidOutChildren) {
196
+ const current = nodeBounds.get(laidOut.id);
197
+ if (!current) continue;
198
+ const dx = currentX + (laidOut.x ?? 0) - localX - current.x;
199
+ const dy = currentY + (laidOut.y ?? 0) - localY - current.y;
200
+ if (dx === 0 && dy === 0) continue;
201
+ const descendants = childDescendants.get(laidOut.id);
202
+ for (const id of descendants) {
203
+ movedIds.add(id);
204
+ const position = positions.get(id);
205
+ if (position) positions.set(id, {
206
+ x: position.x + dx,
207
+ y: position.y + dy
208
+ });
209
+ const bounds = nodeBounds.get(id);
210
+ if (bounds) nodeBounds.set(id, {
211
+ ...bounds,
212
+ x: bounds.x + dx,
213
+ y: bounds.y + dy
214
+ });
215
+ }
216
+ }
217
+ for (const edge of graph.edges) if (movedIds.has(edge.sourceId) || movedIds.has(edge.targetId)) {
218
+ edgeLabelBounds.delete(edge.id);
219
+ edgeRoutes.set(edge.id, { waypoints: [] });
220
+ }
221
+ if (group.group?.type === "derived") {
222
+ let content = null;
223
+ for (const child of children) {
224
+ const bounds = nodeBounds.get(child.id);
225
+ if (bounds) content = unionRect(content, bounds);
226
+ }
227
+ const stored = boundsOf(group, options.getBounds);
228
+ const derived = deriveGroupGeometry({
229
+ width: stored.width,
230
+ height: stored.height
231
+ }, content, group.group, nodeBounds.get(group.id)).bounds;
232
+ positions.set(group.id, {
233
+ x: derived.x,
234
+ y: derived.y
235
+ });
236
+ nodeBounds.set(group.id, derived);
237
+ nodeSizes.set(group.id, {
238
+ width: derived.width,
239
+ height: derived.height
240
+ });
241
+ }
242
+ }
243
+ }
244
+ function rectsOverlap(a, b) {
245
+ return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
246
+ }
247
+ function centerCompoundEdgeLabels(graph, positions, boundsById, nodeBounds, nodesById, fixedIds) {
248
+ for (const edge of graph.edges) {
249
+ if (fixedIds.has(edge.id) || edge.sourceId === edge.targetId) continue;
250
+ const sourceNode = nodesById.get(edge.sourceId);
251
+ const targetNode = nodesById.get(edge.targetId);
252
+ if (!sourceNode?.parentId || sourceNode.parentId !== targetNode?.parentId) continue;
253
+ const direction = nodesById.get(sourceNode.parentId)?.group?.direction ?? graph.direction ?? "down";
254
+ const source = nodeBounds.get(edge.sourceId);
255
+ const target = nodeBounds.get(edge.targetId);
256
+ const label = boundsById.get(edge.id);
257
+ if (!source || !target || !label) continue;
258
+ const horizontal = direction === "left" || direction === "right";
259
+ const sourceBeforeTarget = horizontal ? source.x + source.width / 2 < target.x + target.width / 2 : source.y + source.height / 2 < target.y + target.height / 2;
260
+ const before = sourceBeforeTarget ? source : target;
261
+ const after = sourceBeforeTarget ? target : source;
262
+ const available = horizontal ? after.x - (before.x + before.width) : after.y - (before.y + before.height);
263
+ if (available < (horizontal ? label.width : label.height) + 48) continue;
264
+ const position = horizontal ? {
265
+ x: before.x + before.width + (available - label.width) / 2,
266
+ y: (source.y + source.height / 2 + target.y + target.height / 2) / 2 - label.height / 2
267
+ } : {
268
+ x: (source.x + source.width / 2 + target.x + target.width / 2) / 2 - label.width / 2,
269
+ y: before.y + before.height + (available - label.height) / 2
270
+ };
271
+ positions.set(edge.id, position);
272
+ boundsById.set(edge.id, {
273
+ ...label,
274
+ ...position
275
+ });
276
+ }
277
+ }
278
+ function centerAncestorDescendantEdgeLabels(graph, positions, boundsById, nodeBounds, nodesById, fixedIds, options) {
279
+ for (const edge of graph.edges) {
280
+ if (fixedIds.has(edge.id) || edge.sourceId === edge.targetId) continue;
281
+ const relation = ancestorEndpoint(edge, nodesById);
282
+ const label = boundsById.get(edge.id);
283
+ const ancestorBounds = relation ? nodeBounds.get(relation.ancestor.id) : void 0;
284
+ const descendantBounds = relation ? nodeBounds.get(relation.descendant.id) : void 0;
285
+ if (!relation || !label || !ancestorBounds || !descendantBounds) continue;
286
+ const content = groupContentBounds(relation.ancestor, ancestorBounds, options.getBounds);
287
+ const side = relation.ancestor.group?.content ?? "top";
288
+ const vertical = side === "top" || side === "bottom";
289
+ const before = side === "top" || side === "left" ? content : descendantBounds;
290
+ const after = side === "top" || side === "left" ? descendantBounds : content;
291
+ const available = vertical ? after.y - (before.y + before.height) : after.x - (before.x + before.width);
292
+ if (available < (vertical ? label.height : label.width) + 24) continue;
293
+ const position = vertical ? {
294
+ x: descendantBounds.x + descendantBounds.width / 2 - label.width / 2,
295
+ y: before.y + before.height + (available - label.height) / 2
296
+ } : {
297
+ x: before.x + before.width + (available - label.width) / 2,
298
+ y: descendantBounds.y + descendantBounds.height / 2 - label.height / 2
299
+ };
300
+ positions.set(edge.id, position);
301
+ boundsById.set(edge.id, {
302
+ ...label,
303
+ ...position
304
+ });
305
+ }
306
+ }
307
+ function avoidEdgeLabelOverlaps(graph, positions, boundsById, nodeBounds, nodesById, fixedIds, direction = graph.direction ?? "down") {
308
+ const settledLabels = [];
309
+ let moved = false;
310
+ for (const edge of graph.edges) {
311
+ const bounds = boundsById.get(edge.id);
312
+ if (!bounds || fixedIds.has(edge.id)) continue;
313
+ const ignoredNodeIds = /* @__PURE__ */ new Set();
314
+ const containerId = semanticEdgeOwnerId(edge, nodesById);
315
+ if (edge.sourceId === edge.targetId) ignoredNodeIds.add(edge.sourceId);
316
+ if (containerId) {
317
+ let container = nodesById.get(containerId);
318
+ while (container) {
319
+ ignoredNodeIds.add(container.id);
320
+ container = container.parentId ? nodesById.get(container.parentId) : void 0;
321
+ }
322
+ }
323
+ const obstacles = [...[...nodeBounds].flatMap(([id, rect]) => ignoredNodeIds.has(id) ? [] : [rect]), ...settledLabels];
324
+ const contentSide = (ancestorEndpoint(edge, nodesById)?.ancestor)?.group?.content;
325
+ const position = nearestClearLabelPosition(bounds, obstacles, contentSide === "top" || contentSide === "bottom" ? "down" : contentSide === "left" || contentSide === "right" ? "right" : direction);
326
+ if (position.x !== bounds.x || position.y !== bounds.y) moved = true;
327
+ const placed = {
328
+ ...bounds,
329
+ ...position
330
+ };
331
+ positions.set(edge.id, position);
332
+ boundsById.set(edge.id, placed);
333
+ settledLabels.push(placed);
334
+ }
335
+ return moved;
336
+ }
337
+ function nearestClearLabelPosition(label, obstacles, direction) {
338
+ const gap = 12;
339
+ const origin = {
340
+ x: label.x,
341
+ y: label.y
342
+ };
343
+ const horizontal = direction === "left" || direction === "right";
344
+ const score = (point) => {
345
+ const dx = point.x - origin.x;
346
+ const dy = point.y - origin.y;
347
+ return horizontal ? dx * dx * 2 + dy * dy : dx * dx + dy * dy * 2;
348
+ };
349
+ const candidates = [origin];
350
+ const visited = /* @__PURE__ */ new Set();
351
+ for (let attempts = 0; candidates.length > 0 && attempts < 1e3; attempts++) {
352
+ candidates.sort((a, b) => score(a) - score(b));
353
+ const candidate = candidates.shift();
354
+ const key = `${candidate.x.toFixed(3)},${candidate.y.toFixed(3)}`;
355
+ if (visited.has(key)) continue;
356
+ visited.add(key);
357
+ const candidateBounds = {
358
+ ...label,
359
+ ...candidate
360
+ };
361
+ const overlapping = obstacles.filter((obstacle) => rectsOverlap(candidateBounds, obstacle));
362
+ if (overlapping.length === 0) return candidate;
363
+ for (const obstacle of overlapping) candidates.push({
364
+ x: obstacle.x - label.width - gap,
365
+ y: candidate.y
366
+ }, {
367
+ x: obstacle.x + obstacle.width + gap,
368
+ y: candidate.y
369
+ }, {
370
+ x: candidate.x,
371
+ y: obstacle.y - label.height - gap
372
+ }, {
373
+ x: candidate.x,
374
+ y: obstacle.y + obstacle.height + gap
375
+ });
376
+ }
377
+ return origin;
378
+ }
379
+ function reconcileDerivedGroupBounds(graph, positions, nodeSizes, nodeBounds, edgeLabelPositions, edgeLabelBounds, edgeRoutes, fixedIds, options) {
380
+ const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
381
+ const childrenByParent = /* @__PURE__ */ new Map();
382
+ for (const node of graph.nodes) {
383
+ const parentId = node.parentId ?? void 0;
384
+ const children = childrenByParent.get(parentId) ?? [];
385
+ children.push(node.id);
386
+ childrenByParent.set(parentId, children);
387
+ }
388
+ const edgesByOwner = /* @__PURE__ */ new Map();
389
+ for (const edge of graph.edges) {
390
+ const ownerId = semanticEdgeOwnerId(edge, nodesById);
391
+ if (!ownerId) continue;
392
+ const edges = edgesByOwner.get(ownerId) ?? [];
393
+ edges.push(edge);
394
+ edgesByOwner.set(ownerId, edges);
395
+ }
396
+ const effectiveBounds = (id, cache) => {
397
+ const cached = cache.get(id);
398
+ if (cached) return cached;
399
+ const node = nodesById.get(id);
400
+ const base = nodeBounds.get(id) ?? boundsOf(node, options.getBounds);
401
+ if (node.group?.type !== "derived") {
402
+ cache.set(id, base);
403
+ return base;
404
+ }
405
+ let content = null;
406
+ for (const childId of childrenByParent.get(id) ?? []) content = unionRect(content, effectiveBounds(childId, cache));
407
+ for (const edge of edgesByOwner.get(id) ?? []) {
408
+ if (edge.sourceId === id && edge.targetId === id) continue;
409
+ const label = edgeLabelBounds.get(edge.id);
410
+ if (label) content = unionRect(content, label);
411
+ }
412
+ const stored = boundsOf(node, options.getBounds);
413
+ const derived = deriveGroupGeometry({
414
+ width: stored.width,
415
+ height: stored.height
416
+ }, content, node.group, base).bounds;
417
+ cache.set(id, derived);
418
+ return derived;
419
+ };
420
+ const descendantsOf = (id) => {
421
+ const descendants = /* @__PURE__ */ new Set([id]);
422
+ const pending = [id];
423
+ while (pending.length > 0) for (const childId of childrenByParent.get(pending.pop()) ?? []) {
424
+ descendants.add(childId);
425
+ pending.push(childId);
426
+ }
427
+ return descendants;
428
+ };
429
+ const shiftSubtree = (id, dx, dy) => {
430
+ const descendants = descendantsOf(id);
431
+ for (const nodeId of descendants) {
432
+ const position = positions.get(nodeId);
433
+ if (position) positions.set(nodeId, {
434
+ x: position.x + dx,
435
+ y: position.y + dy
436
+ });
437
+ const bounds = nodeBounds.get(nodeId);
438
+ if (bounds) nodeBounds.set(nodeId, {
439
+ ...bounds,
440
+ x: bounds.x + dx,
441
+ y: bounds.y + dy
442
+ });
443
+ }
444
+ for (const edge of graph.edges) {
445
+ const ownerId = semanticEdgeOwnerId(edge, nodesById);
446
+ if (ownerId && descendants.has(ownerId)) {
447
+ const position = edgeLabelPositions.get(edge.id);
448
+ if (position) edgeLabelPositions.set(edge.id, {
449
+ x: position.x + dx,
450
+ y: position.y + dy
451
+ });
452
+ const bounds = edgeLabelBounds.get(edge.id);
453
+ if (bounds) edgeLabelBounds.set(edge.id, {
454
+ ...bounds,
455
+ x: bounds.x + dx,
456
+ y: bounds.y + dy
457
+ });
458
+ const route = edgeRoutes.get(edge.id);
459
+ if (route) edgeRoutes.set(edge.id, { waypoints: route.waypoints.map((point) => ({
460
+ x: point.x + dx,
461
+ y: point.y + dy
462
+ })) });
463
+ } else if (descendants.has(edge.sourceId) || descendants.has(edge.targetId)) edgeRoutes.set(edge.id, { waypoints: [] });
464
+ }
465
+ };
466
+ const direction = options.direction ?? graph.direction ?? "down";
467
+ const horizontal = direction === "left" || direction === "right";
468
+ const reverse = direction === "left" || direction === "up";
469
+ let cache = /* @__PURE__ */ new Map();
470
+ let changed = false;
471
+ const gap = options.nodeSpacing ?? 60;
472
+ const depthOf = (parentId) => {
473
+ let depth = 0;
474
+ let marker = parentId ? nodesById.get(parentId) : void 0;
475
+ while (marker) {
476
+ depth++;
477
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
478
+ }
479
+ return depth;
480
+ };
481
+ const containers = [...childrenByParent.keys()].sort((a, b) => depthOf(b) - depthOf(a));
482
+ for (const containerId of containers) {
483
+ const ordered = [...childrenByParent.get(containerId) ?? []].sort((a, b) => {
484
+ const aBounds = effectiveBounds(a, cache);
485
+ const bBounds = effectiveBounds(b, cache);
486
+ const delta = horizontal ? aBounds.x - bBounds.x : aBounds.y - bBounds.y;
487
+ return reverse ? -delta : delta;
488
+ });
489
+ for (let i = 0; i < ordered.length; i++) for (let j = i + 1; j < ordered.length; j++) {
490
+ const first = effectiveBounds(ordered[i], cache);
491
+ const second = effectiveBounds(ordered[j], cache);
492
+ if (!rectsOverlap(first, second)) continue;
493
+ if ([...descendantsOf(ordered[j])].some((id) => fixedIds.has(id))) continue;
494
+ const delta = horizontal ? reverse ? first.x - gap - (second.x + second.width) : first.x + first.width + gap - second.x : reverse ? first.y - gap - (second.y + second.height) : first.y + first.height + gap - second.y;
495
+ shiftSubtree(ordered[j], horizontal ? delta : 0, horizontal ? 0 : delta);
496
+ cache = /* @__PURE__ */ new Map();
497
+ changed = true;
498
+ }
499
+ }
500
+ cache = /* @__PURE__ */ new Map();
501
+ for (const node of graph.nodes) {
502
+ if (node.group?.type !== "derived" || fixedIds.has(node.id)) continue;
503
+ const bounds = effectiveBounds(node.id, cache);
504
+ positions.set(node.id, {
505
+ x: bounds.x,
506
+ y: bounds.y
507
+ });
508
+ nodeBounds.set(node.id, bounds);
509
+ nodeSizes.set(node.id, {
510
+ width: bounds.width,
511
+ height: bounds.height
512
+ });
513
+ }
514
+ return changed;
515
+ }
516
+ function unionRect(a, b) {
517
+ if (!a) return { ...b };
518
+ const x = Math.min(a.x, b.x);
519
+ const y = Math.min(a.y, b.y);
520
+ const right = Math.max(a.x + a.width, b.x + b.width);
521
+ const bottom = Math.max(a.y + a.height, b.y + b.height);
522
+ return {
523
+ x,
524
+ y,
525
+ width: right - x,
526
+ height: bottom - y
527
+ };
528
+ }
60
529
  const SIDE_TO_ELK = {
61
530
  top: "NORTH",
62
531
  bottom: "SOUTH",
@@ -72,28 +541,52 @@ function toElkGraph(graph, options) {
72
541
  childIdsByParent.set(parentId, siblings);
73
542
  }
74
543
  const nodesById = new Map(graph.nodes.map((node) => [node.id, node]));
544
+ const ancestorLabelClearance = /* @__PURE__ */ new Map();
545
+ for (const edge of graph.edges) {
546
+ if (!edge.label) continue;
547
+ const ancestor = ancestorEndpoint(edge, nodesById)?.ancestor;
548
+ if (!ancestor?.group) continue;
549
+ const side = ancestor.group.content ?? "top";
550
+ const extent = (side === "top" || side === "bottom" ? edge.label.height : edge.label.width) + 24;
551
+ ancestorLabelClearance.set(ancestor.id, Math.max(ancestorLabelClearance.get(ancestor.id) ?? 0, extent));
552
+ }
75
553
  const edgesByContainer = /* @__PURE__ */ new Map();
76
554
  for (const edge of graph.edges) {
77
- const containerId = edgeContainerId(edge, nodesById);
555
+ const containerId = elkEdgeContainerId(edge, nodesById);
78
556
  const bucket = edgesByContainer.get(containerId) ?? [];
79
557
  bucket.push(toElkEdge(edge, options));
80
558
  edgesByContainer.set(containerId, bucket);
81
559
  }
560
+ const rootEdges = edgesByContainer.get(void 0) ?? [];
561
+ const hasRootHierarchyEdge = hasRootHierarchyEdges(graph, nodesById);
562
+ const rootDirection = options.direction ?? graph.direction;
563
+ const graphOptions = stringOptions(options.graph);
564
+ const configuredRootRankSpacing = finiteNumberOption(graphOptions["elk.layered.spacing.nodeNodeBetweenLayers"] ?? options.rankSpacing, 90);
565
+ const hasDerivedGroup = graph.nodes.some((node) => node.group?.type === "derived");
82
566
  return {
83
567
  id: "root",
84
568
  layoutOptions: {
85
569
  "elk.algorithm": "layered",
86
- "elk.direction": rankDirection(options.direction ?? graph.direction),
570
+ "elk.direction": elkDirection(rootDirection),
87
571
  "elk.spacing.nodeNode": String(options.nodeSpacing ?? 60),
88
572
  "elk.layered.spacing.nodeNodeBetweenLayers": String(options.rankSpacing ?? 90),
89
573
  ...options.scope ? { "elk.interactive": "true" } : {},
90
- ...stringOptions(options.graph)
574
+ ...graphOptions,
575
+ ...hasRootHierarchyEdge ? { "elk.hierarchyHandling": "INCLUDE_CHILDREN" } : {},
576
+ ...hasDerivedGroup ? { "elk.layered.spacing.nodeNodeBetweenLayers": String(labelAwareRankSpacing(rootEdges, rootDirection === "left" || rootDirection === "right", configuredRootRankSpacing)) } : {}
91
577
  },
92
- children: (childIdsByParent.get(void 0) ?? []).map((id) => toElkNode(nodesById.get(id), childIdsByParent, nodesById, edgesByContainer, options)),
93
- edges: edgesByContainer.get(void 0) ?? []
578
+ children: (childIdsByParent.get(void 0) ?? []).map((id) => toElkNode(nodesById.get(id), childIdsByParent, nodesById, edgesByContainer, ancestorLabelClearance, options)),
579
+ edges: rootEdges
94
580
  };
95
581
  }
582
+ function hasRootHierarchyEdges(graph, nodesById) {
583
+ return graph.edges.some((edge) => {
584
+ if (elkEdgeContainerId(edge, nodesById) !== void 0) return false;
585
+ return ancestorEndpoint(edge, nodesById) !== void 0;
586
+ });
587
+ }
96
588
  function toElkEdge(edge, options) {
589
+ const labelLayoutOptions = stringOptions(options.label);
97
590
  return {
98
591
  id: edge.id,
99
592
  sources: [edge.sourcePort ? `${edge.sourceId}:${edge.sourcePort}` : edge.sourceId],
@@ -101,24 +594,96 @@ function toElkEdge(edge, options) {
101
594
  labels: edge.label ? [{
102
595
  id: `${edge.id}:label`,
103
596
  width: edge.label.width,
104
- height: edge.label.height
597
+ height: edge.label.height,
598
+ ...Object.keys(labelLayoutOptions).length > 0 ? { layoutOptions: labelLayoutOptions } : {}
105
599
  }] : void 0,
106
600
  ...options.edge
107
601
  };
108
602
  }
109
603
  /**
110
- * The container node an edge belongs in for ELK hierarchy: the Lowest Common
111
- * Ancestor group of its source & target (undefined = root). Walk the source's
604
+ * The semantic owner whose derived bounds include the edge label: the Lowest
605
+ * Common Ancestor of its source & target (undefined = root). Walk the source's
112
606
  * ancestor chain (including the source itself) into a set, then walk the
113
607
  * target's chain up until it hits a member of that set. An edge whose
114
608
  * endpoints are both children of group G resolves to G; a cross-boundary edge
115
609
  * resolves to the shared ancestor (often root/undefined).
116
610
  */
117
- function edgeContainerId(edge, nodesById) {
611
+ function semanticEdgeOwnerId(edge, nodesById) {
612
+ const source = nodesById.get(edge.sourceId);
613
+ const target = edge.targetId ? nodesById.get(edge.targetId) : void 0;
614
+ if (!source) return void 0;
615
+ if (!target || source === target) return source.parentId ?? void 0;
616
+ const ancestors = /* @__PURE__ */ new Set([source.id]);
617
+ let marker = source.parentId ? nodesById.get(source.parentId) : void 0;
618
+ while (marker) {
619
+ ancestors.add(marker.id);
620
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
621
+ }
622
+ marker = target;
623
+ while (marker) {
624
+ if (ancestors.has(marker.id)) return marker.id;
625
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
626
+ }
627
+ }
628
+ function ancestorEndpoint(edge, nodesById) {
629
+ const source = nodesById.get(edge.sourceId);
630
+ const target = edge.targetId ? nodesById.get(edge.targetId) : void 0;
631
+ if (!source || !target) return void 0;
632
+ const isAncestor = (ancestor, descendant) => {
633
+ let marker = descendant.parentId ? nodesById.get(descendant.parentId) : void 0;
634
+ while (marker) {
635
+ if (marker.id === ancestor.id) return true;
636
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
637
+ }
638
+ return false;
639
+ };
640
+ if (source.group && isAncestor(source, target)) return {
641
+ ancestor: source,
642
+ descendant: target
643
+ };
644
+ if (target.group && isAncestor(target, source)) return {
645
+ ancestor: target,
646
+ descendant: source
647
+ };
648
+ }
649
+ function groupContentBounds(node, bounds, getBounds) {
650
+ const side = node.group?.content ?? "top";
651
+ const size = node.group?.type === "fixed" ? node.group.contentSize ?? {
652
+ width: 0,
653
+ height: 0
654
+ } : boundsOf(node, getBounds);
655
+ if (side === "top" || side === "bottom") {
656
+ const height = Math.min(size.height, bounds.height);
657
+ return {
658
+ x: bounds.x,
659
+ y: side === "top" ? bounds.y : bounds.y + bounds.height - height,
660
+ width: bounds.width,
661
+ height
662
+ };
663
+ }
664
+ const width = Math.min(size.width, bounds.width);
665
+ return {
666
+ x: side === "left" ? bounds.x : bounds.x + bounds.width - width,
667
+ y: bounds.y,
668
+ width,
669
+ height: bounds.height
670
+ };
671
+ }
672
+ function elkEdgeContainerId(edge, nodesById) {
118
673
  const source = nodesById.get(edge.sourceId);
119
674
  const target = edge.targetId ? nodesById.get(edge.targetId) : void 0;
120
675
  if (!source) return void 0;
121
676
  if (!target || source === target) return source.parentId ?? void 0;
677
+ const isAncestorOf = (ancestor, descendant) => {
678
+ let marker = descendant.parentId ? nodesById.get(descendant.parentId) : void 0;
679
+ while (marker) {
680
+ if (marker.id === ancestor.id) return true;
681
+ marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
682
+ }
683
+ return false;
684
+ };
685
+ if (isAncestorOf(source, target)) return source.parentId ?? void 0;
686
+ if (isAncestorOf(target, source)) return target.parentId ?? void 0;
122
687
  const ancestors = /* @__PURE__ */ new Set([source.id]);
123
688
  let marker = source.parentId ? nodesById.get(source.parentId) : void 0;
124
689
  while (marker) {
@@ -131,9 +696,9 @@ function edgeContainerId(edge, nodesById) {
131
696
  marker = marker.parentId ? nodesById.get(marker.parentId) : void 0;
132
697
  }
133
698
  }
134
- function toElkNode(node, childIdsByParent, nodesById, edgesByContainer, options) {
699
+ function toElkNode(node, childIdsByParent, nodesById, edgesByContainer, ancestorLabelClearance, options) {
135
700
  const bounds = boundsOf(node, options.getBounds);
136
- const children = (childIdsByParent.get(node.id) ?? []).map((id) => toElkNode(nodesById.get(id), childIdsByParent, nodesById, edgesByContainer, options));
701
+ const children = (childIdsByParent.get(node.id) ?? []).map((id) => toElkNode(nodesById.get(id), childIdsByParent, nodesById, edgesByContainer, ancestorLabelClearance, options));
137
702
  const ports = (node.ports ?? []).map((port) => ({
138
703
  id: `${node.id}:${port.name}`,
139
704
  x: port.x,
@@ -142,27 +707,41 @@ function toElkNode(node, childIdsByParent, nodesById, edgesByContainer, options)
142
707
  height: port.height,
143
708
  layoutOptions: { "elk.port.side": SIDE_TO_ELK[port.side ?? "right"] ?? "EAST" }
144
709
  }));
710
+ const nestedEdges = edgesByContainer.get(node.id);
145
711
  const isCompound = children.length > 0 && isGroup(node);
146
- const layoutOptions = {};
712
+ const configuredNode = { ...options.node ?? {} };
713
+ const configuredLayoutOptions = configuredNode.layoutOptions && typeof configuredNode.layoutOptions === "object" && !Array.isArray(configuredNode.layoutOptions) ? stringOptions(configuredNode.layoutOptions) : {};
714
+ delete configuredNode.layoutOptions;
715
+ for (const [key, value] of Object.entries(configuredNode)) {
716
+ if (!key.startsWith("elk.")) continue;
717
+ configuredLayoutOptions[key] = String(value);
718
+ delete configuredNode[key];
719
+ }
720
+ const layoutOptions = configuredLayoutOptions;
147
721
  if (ports.length > 0) layoutOptions["elk.portConstraints"] = "FIXED_SIDE";
148
722
  if (isCompound) {
149
723
  layoutOptions["elk.hierarchyHandling"] = "INCLUDE_CHILDREN";
150
724
  layoutOptions["elk.padding"] = elkPadding(groupInsets(node.group, {
151
725
  width: bounds.width,
152
726
  height: bounds.height
153
- }));
727
+ }, ancestorLabelClearance.get(node.id)));
154
728
  layoutOptions["elk.nodeSize.constraints"] = "NODE_LABELS PORTS MINIMUM_SIZE";
729
+ layoutOptions["elk.nodeSize.minimum"] = `(${bounds.width},${bounds.height})`;
730
+ const contentSide = node.group?.content ?? "top";
731
+ layoutOptions["elk.contentAlignment"] = contentSide === "top" || contentSide === "bottom" ? "H_CENTER" : "V_CENTER";
732
+ const direction = node.group?.direction ?? options.direction ?? "down";
733
+ layoutOptions["elk.direction"] = elkDirection(direction);
734
+ applyCompoundLayeredOptions(layoutOptions, nestedEdges ?? [], direction, options);
155
735
  }
156
- const nestedEdges = edgesByContainer.get(node.id);
157
736
  const elkNode = {
158
737
  id: node.id,
159
738
  x: node.x,
160
739
  y: node.y,
161
740
  ports,
162
- layoutOptions: Object.keys(layoutOptions).length > 0 ? layoutOptions : void 0,
163
741
  children: children.length > 0 ? children : void 0,
164
742
  edges: nestedEdges && nestedEdges.length > 0 ? nestedEdges : void 0,
165
- ...options.node
743
+ ...configuredNode,
744
+ layoutOptions: Object.keys(layoutOptions).length > 0 ? layoutOptions : void 0
166
745
  };
167
746
  if (!isCompound) {
168
747
  elkNode.width = bounds.width;
@@ -171,12 +750,42 @@ function toElkNode(node, childIdsByParent, nodesById, edgesByContainer, options)
171
750
  return elkNode;
172
751
  }
173
752
  /**
753
+ * A compound is an independent layered graph. Root graph options are not
754
+ * inherited reliably by that nested graph, so propagate the readability
755
+ * options that matter there and reserve enough rank space for native labels.
756
+ */
757
+ function applyCompoundLayeredOptions(layoutOptions, edges, direction, options) {
758
+ const graphOptions = stringOptions(options.graph);
759
+ for (const key of [
760
+ "elk.spacing.edgeNode",
761
+ "elk.layered.spacing.edgeNodeBetweenLayers",
762
+ "elk.layered.nodePlacement.favorStraightEdges",
763
+ "elk.layered.nodePlacement.bk.edgeStraightening",
764
+ "elk.layered.feedbackEdges",
765
+ "elk.layered.unnecessaryBendpoints"
766
+ ]) if (layoutOptions[key] === void 0 && graphOptions[key] !== void 0) layoutOptions[key] = graphOptions[key];
767
+ layoutOptions["elk.layered.nodePlacement.favorStraightEdges"] ??= "true";
768
+ layoutOptions["elk.layered.nodePlacement.bk.edgeStraightening"] ??= "IMPROVE_STRAIGHTNESS";
769
+ const horizontal = direction === "left" || direction === "right";
770
+ const spacingKey = "elk.layered.spacing.nodeNodeBetweenLayers";
771
+ const configuredSpacing = finiteNumberOption(layoutOptions[spacingKey] ?? graphOptions[spacingKey] ?? options.rankSpacing, 20);
772
+ layoutOptions[spacingKey] = String(labelAwareRankSpacing(edges, horizontal, configuredSpacing));
773
+ }
774
+ function labelAwareRankSpacing(edges, horizontal, configuredSpacing) {
775
+ const largestLabel = Math.max(0, ...edges.flatMap((edge) => (edge.labels ?? []).map((label) => horizontal ? label.width ?? 0 : label.height ?? 0)));
776
+ return Math.max(configuredSpacing, largestLabel + 48);
777
+ }
778
+ function finiteNumberOption(value, fallback) {
779
+ const parsed = Number(value);
780
+ return Number.isFinite(parsed) ? parsed : fallback;
781
+ }
782
+ /**
174
783
  * The inset ELK must leave inside a compound so children clear the group's
175
784
  * content block (header) and honor its padding. The content block occupies
176
785
  * one side at `contentSize` (fixed groups) or the node's own size (derived
177
786
  * groups); every side also carries the group's padding.
178
787
  */
179
- function groupInsets(group, bounds) {
788
+ function groupInsets(group, bounds, contentClearance = 0) {
180
789
  const padding = resolveGroupPadding(group.padding);
181
790
  const side = group.content ?? "top";
182
791
  const contentSize = group.type === "fixed" ? group.contentSize ?? {
@@ -184,10 +793,10 @@ function groupInsets(group, bounds) {
184
793
  height: 0
185
794
  } : bounds;
186
795
  const insets = { ...padding };
187
- if (side === "top") insets.top += contentSize.height;
188
- else if (side === "bottom") insets.bottom += contentSize.height;
189
- else if (side === "left") insets.left += contentSize.width;
190
- else insets.right += contentSize.width;
796
+ if (side === "top") insets.top = contentSize.height + Math.max(padding.top, contentClearance);
797
+ else if (side === "bottom") insets.bottom = contentSize.height + Math.max(padding.bottom, contentClearance);
798
+ else if (side === "left") insets.left = contentSize.width + Math.max(padding.left, contentClearance);
799
+ else insets.right = contentSize.width + Math.max(padding.right, contentClearance);
191
800
  return insets;
192
801
  }
193
802
  function elkPadding(insets) {
@@ -233,5 +842,8 @@ function stringOptions(options) {
233
842
  if (!options) return {};
234
843
  return Object.fromEntries(Object.entries(options).map(([key, value]) => [key, String(value)]));
235
844
  }
845
+ function elkDirection(direction) {
846
+ return (direction ?? "down").toUpperCase();
847
+ }
236
848
  //#endregion
237
849
  export { elkLayout, toElkGraph };