@weasel-js/diagram 1.10.1 → 1.11.1

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,1247 +0,0 @@
1
- import { rectPath, polygonFromPoints, PathBuilder, PATH_M, PATH_L, PATH_C, flattenCubic, PATH_Q, PATH_Z, AUTO_POSE_DESCRIPTOR, rotatePoint } from '@weasel-js/core/math';
2
- import { cssFamilyName } from '@weasel-js/font';
3
- import { createSimulation } from '@weasel-js/simulation';
4
-
5
- // src/outline.ts
6
- var LEAN = 0.2;
7
- var KAPPA = 0.5522847498307936;
8
- function outlinePath(outline, bounds) {
9
- if (typeof outline !== "string") return outline;
10
- const { x, y, width: w, height: h } = bounds;
11
- if (w <= 0 || h <= 0) return rectPath(x, y, Math.max(w, 0), Math.max(h, 0));
12
- switch (outline) {
13
- case "rect":
14
- return rectPath(x, y, w, h);
15
- case "diamond":
16
- return polygonFromPoints([
17
- { x: x + w / 2, y },
18
- { x: x + w, y: y + h / 2 },
19
- { x: x + w / 2, y: y + h },
20
- { x, y: y + h / 2 }
21
- ]);
22
- case "parallelogram": {
23
- const lean = Math.min(w * LEAN, w / 2);
24
- return polygonFromPoints([
25
- { x: x + lean, y },
26
- { x: x + w, y },
27
- { x: x + w - lean, y: y + h },
28
- { x, y: y + h }
29
- ]);
30
- }
31
- case "stadium":
32
- return stadiumPath(x, y, w, h);
33
- }
34
- }
35
- function stadiumPath(x, y, w, h) {
36
- const r = Math.min(w, h) / 2;
37
- const k = r * KAPPA;
38
- const b = new PathBuilder();
39
- if (w >= h) {
40
- const left2 = x + r;
41
- const right2 = x + w - r;
42
- const top2 = y;
43
- const bottom2 = y + h;
44
- const midY = y + h / 2;
45
- return b.moveTo(left2, top2).lineTo(right2, top2).curveTo(right2 + k, top2, x + w, midY - k, x + w, midY).curveTo(x + w, midY + k, right2 + k, bottom2, right2, bottom2).lineTo(left2, bottom2).curveTo(left2 - k, bottom2, x, midY + k, x, midY).curveTo(x, midY - k, left2 - k, top2, left2, top2).close().build();
46
- }
47
- const top = y + r;
48
- const bottom = y + h - r;
49
- const left = x;
50
- const right = x + w;
51
- const midX = x + w / 2;
52
- return b.moveTo(right, top).lineTo(right, bottom).curveTo(right, bottom + k, midX + k, y + h, midX, y + h).curveTo(midX - k, y + h, left, bottom + k, left, bottom).lineTo(left, top).curveTo(left, top - k, midX - k, y, midX, y).curveTo(midX + k, y, right, top - k, right, top).close().build();
53
- }
54
- function contentBox(outline, bounds) {
55
- if (typeof outline !== "string") return bounds;
56
- const { x, y, width: w, height: h } = bounds;
57
- switch (outline) {
58
- case "rect":
59
- return bounds;
60
- case "diamond":
61
- return { x: x + w / 4, y: y + h / 4, width: w / 2, height: h / 2 };
62
- case "parallelogram": {
63
- const lean = Math.min(w * LEAN, w / 2);
64
- return { x: x + lean, y, width: Math.max(w - lean * 2, 0), height: h };
65
- }
66
- case "stadium": {
67
- const r = Math.min(w, h) / 2;
68
- return w >= h ? { x: x + r, y, width: Math.max(w - r * 2, 0), height: h } : { x, y: y + r, width: w, height: Math.max(h - r * 2, 0) };
69
- }
70
- }
71
- }
72
- function boxForContent(outline, content) {
73
- if (typeof outline !== "string") return content;
74
- switch (outline) {
75
- case "rect":
76
- return content;
77
- case "diamond":
78
- return { width: content.width * 2, height: content.height * 2 };
79
- case "parallelogram":
80
- return { width: content.width / (1 - LEAN * 2), height: content.height };
81
- case "stadium":
82
- return { width: content.width + content.height, height: content.height };
83
- }
84
- }
85
- var TOLERANCE = 0.25;
86
- function outlinePolyline(outline, bounds) {
87
- const path = outlinePath(outline, bounds);
88
- return flattenPath(path);
89
- }
90
- function flattenPath(path) {
91
- if (path.kind === "rect") {
92
- const { x, y, width: w, height: h } = path;
93
- return [x, y, x + w, y, x + w, y + h, x, y + h, x, y];
94
- }
95
- const out = [];
96
- const { commands, coords } = path;
97
- let ci = 0;
98
- let cx = 0;
99
- let cy = 0;
100
- let sx = 0;
101
- let sy = 0;
102
- for (const cmd of commands) {
103
- if (cmd === PATH_M) {
104
- cx = coords[ci];
105
- cy = coords[ci + 1];
106
- ci += 2;
107
- sx = cx;
108
- sy = cy;
109
- out.push(cx, cy);
110
- } else if (cmd === PATH_L) {
111
- cx = coords[ci];
112
- cy = coords[ci + 1];
113
- ci += 2;
114
- out.push(cx, cy);
115
- } else if (cmd === PATH_C) {
116
- const x1 = coords[ci], y1 = coords[ci + 1];
117
- const x2 = coords[ci + 2], y2 = coords[ci + 3];
118
- const x3 = coords[ci + 4], y3 = coords[ci + 5];
119
- ci += 6;
120
- flattenCubic(cx, cy, x1, y1, x2, y2, x3, y3, TOLERANCE, out);
121
- cx = x3;
122
- cy = y3;
123
- } else if (cmd === PATH_Q) {
124
- const qx = coords[ci], qy = coords[ci + 1];
125
- const x3 = coords[ci + 2], y3 = coords[ci + 3];
126
- ci += 4;
127
- flattenCubic(
128
- cx,
129
- cy,
130
- cx + 2 / 3 * (qx - cx),
131
- cy + 2 / 3 * (qy - cy),
132
- x3 + 2 / 3 * (qx - x3),
133
- y3 + 2 / 3 * (qy - y3),
134
- x3,
135
- y3,
136
- TOLERANCE,
137
- out
138
- );
139
- cx = x3;
140
- cy = y3;
141
- } else if (cmd === PATH_Z) {
142
- out.push(sx, sy);
143
- cx = sx;
144
- cy = sy;
145
- }
146
- }
147
- if (out.length >= 2 && (out[0] !== out[out.length - 2] || out[1] !== out[out.length - 1])) {
148
- out.push(out[0], out[1]);
149
- }
150
- return out;
151
- }
152
- function rayHit(poly, center2, point) {
153
- const dx = point.x - center2.x;
154
- const dy = point.y - center2.y;
155
- if (dx === 0 && dy === 0) return null;
156
- let bestT = -Infinity;
157
- let hit = null;
158
- for (let i = 0; i + 3 < poly.length; i += 2) {
159
- const ax = poly[i], ay = poly[i + 1];
160
- const bx = poly[i + 2], by = poly[i + 3];
161
- const ex = bx - ax;
162
- const ey = by - ay;
163
- const denom = dx * ey - dy * ex;
164
- if (denom === 0) continue;
165
- const t = ((ax - center2.x) * ey - (ay - center2.y) * ex) / denom;
166
- const u = ((ax - center2.x) * dy - (ay - center2.y) * dx) / denom;
167
- if (t < 0 || u < 0 || u > 1) continue;
168
- if (t > bestT) {
169
- bestT = t;
170
- hit = { x: center2.x + dx * t, y: center2.y + dy * t };
171
- }
172
- }
173
- return hit;
174
- }
175
- function portsOnOutline(ports, outline, bounds) {
176
- if (bounds.width <= 0 || bounds.height <= 0) return [...ports];
177
- const poly = outlinePolyline(outline, bounds);
178
- const center2 = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
179
- return ports.map((port) => {
180
- const hit = rayHit(poly, center2, port.point);
181
- return hit === null ? port : { ...port, point: hit };
182
- });
183
- }
184
-
185
- // src/trait.ts
186
- var DIAGRAM_TRAIT_KEY = "diagram";
187
- var dataKeyReader = (node) => {
188
- const data = node.data;
189
- if (data === null || typeof data !== "object") return null;
190
- const trait = data[DIAGRAM_TRAIT_KEY];
191
- if (trait === null || typeof trait !== "object") return null;
192
- if ("from" in trait && "to" in trait) return null;
193
- if ("label" in trait || "anchor" in trait) return null;
194
- return trait;
195
- };
196
- function createDiagramNodes(entries) {
197
- const seen = /* @__PURE__ */ new Set();
198
- for (const entry of entries) {
199
- if (seen.has(entry.name)) {
200
- throw new Error(`createDiagramNodes: duplicate entry name "${entry.name}"`);
201
- }
202
- seen.add(entry.name);
203
- }
204
- return (node) => {
205
- const own = dataKeyReader(node);
206
- if (own !== null) return own;
207
- for (const entry of entries) {
208
- if (!entry.matches(node.data)) continue;
209
- return typeof entry.trait === "function" ? entry.trait(node.data) : entry.trait;
210
- }
211
- return null;
212
- };
213
- }
214
- function diagramNodeOf(node, read = dataKeyReader) {
215
- return read(node);
216
- }
217
- function isPinned(node, read) {
218
- return diagramNodeOf(node, read)?.pinned === true;
219
- }
220
- var COMPASS = {
221
- nw: { u: 0, v: 0 },
222
- n: { u: 0.5, v: 0 },
223
- ne: { u: 1, v: 0 },
224
- e: { u: 1, v: 0.5 },
225
- se: { u: 1, v: 1 },
226
- s: { u: 0.5, v: 1 },
227
- sw: { u: 0, v: 1 },
228
- w: { u: 0, v: 0.5 }
229
- };
230
- var DEFAULT_PORTS = Object.freeze([
231
- { id: "n", at: COMPASS.n },
232
- { id: "e", at: COMPASS.e },
233
- { id: "s", at: COMPASS.s },
234
- { id: "w", at: COMPASS.w }
235
- ]);
236
- function normalOf(at) {
237
- const x = at.u * 2 - 1;
238
- const y = at.v * 2 - 1;
239
- const len = Math.hypot(x, y);
240
- if (len === 0) return null;
241
- return { x: x / len, y: y / len };
242
- }
243
- function portsOf(node, pose, opts = {}) {
244
- const trait = diagramNodeOf(node, opts.read);
245
- if (trait === null) return [];
246
- const geometry = opts.geometry ?? AUTO_POSE_DESCRIPTOR;
247
- const bounds = geometry.getBounds(pose);
248
- const rotation = geometry.getRotation?.(pose) ?? 0;
249
- const cx = bounds.x + bounds.width / 2;
250
- const cy = bounds.y + bounds.height / 2;
251
- const poly = trait.outline === void 0 || bounds.width <= 0 || bounds.height <= 0 ? null : outlinePolyline(trait.outline, bounds);
252
- return (trait.ports ?? DEFAULT_PORTS).map((spec) => {
253
- const anchored = {
254
- x: bounds.x + spec.at.u * bounds.width,
255
- y: bounds.y + spec.at.v * bounds.height
256
- };
257
- const flat = (poly === null ? null : rayHit(poly, { x: cx, y: cy }, anchored)) ?? anchored;
258
- const normal = spec.normal === void 0 ? normalOf(spec.at) : spec.normal;
259
- if (rotation === 0) {
260
- return { id: spec.id, nodeId: node.id, point: flat, normal, ...typeOf(spec) };
261
- }
262
- return {
263
- id: spec.id,
264
- nodeId: node.id,
265
- point: rotatePoint(flat.x, flat.y, cx, cy, rotation),
266
- // A direction rotates about the origin, not about the node's center.
267
- normal: normal === null ? null : rotatePoint(normal.x, normal.y, 0, 0, rotation),
268
- ...typeOf(spec)
269
- };
270
- });
271
- }
272
- function portOf(node, pose, portId, opts = {}) {
273
- return portsOf(node, pose, opts).find((p) => p.id === portId);
274
- }
275
- function typeOf(spec) {
276
- return spec.type === void 0 ? {} : { type: spec.type };
277
- }
278
- var DEFAULT_PADDING = 8;
279
- var DEFAULT_GAP = 4;
280
- var FALLBACK_LINE = 16;
281
- function canvasMeasure(ctx) {
282
- return (text, style) => {
283
- const size = style.fontSize ?? FALLBACK_LINE;
284
- ctx.font = `${style.bold === true ? "bold " : ""}${size}px ${cssFamilyName(style.fontFamily ?? "sans-serif")}`;
285
- return { width: ctx.measureText(text).width, height: Math.ceil(size * 1.2) };
286
- };
287
- }
288
- function measureRow(row, measure) {
289
- const text = (s, style) => measure === void 0 ? {
290
- width: s.length * (style?.fontSize ?? FALLBACK_LINE) * 0.6,
291
- height: style?.fontSize === void 0 ? FALLBACK_LINE : Math.ceil(style.fontSize * 1.2)
292
- } : measure(s, style ?? {});
293
- switch (row.kind) {
294
- case "label":
295
- return text(row.text, row.style);
296
- case "field": {
297
- const l = text(row.label, row.style);
298
- const v = text(row.value, row.style);
299
- return { width: l.width + DEFAULT_GAP * 2 + v.width, height: Math.max(l.height, v.height) };
300
- }
301
- case "ports": {
302
- const side = (ports) => (ports ?? []).reduce((w, p) => Math.max(w, p.label === void 0 ? 0 : text(p.label).width), 0);
303
- const rows = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);
304
- return {
305
- width: side(row.left) + DEFAULT_GAP * 2 + side(row.right),
306
- height: row.height ?? rows * FALLBACK_LINE
307
- };
308
- }
309
- case "slot":
310
- return { width: 0, height: row.height };
311
- }
312
- }
313
- function measureBody(spec, measure) {
314
- const padding = spec.padding ?? DEFAULT_PADDING;
315
- const gap = spec.gap ?? DEFAULT_GAP;
316
- let width = 0;
317
- let height = 0;
318
- for (const [i, row] of spec.rows.entries()) {
319
- const m = measureRow(row, measure);
320
- width = Math.max(width, m.width);
321
- height += m.height + (i > 0 ? gap : 0);
322
- }
323
- const box = boxForContent(spec.outline, {
324
- width: width + padding * 2,
325
- height: height + padding * 2
326
- });
327
- return { minWidth: box.width, minHeight: box.height };
328
- }
329
- function sizeToBody(pose, floor) {
330
- const width = Math.max(pose.width, floor.minWidth);
331
- const height = Math.max(pose.height, floor.minHeight);
332
- if (width === pose.width && height === pose.height) return pose;
333
- return { ...pose, width, height };
334
- }
335
- function layoutBody(spec, bounds, measure) {
336
- const padding = spec.padding ?? DEFAULT_PADDING;
337
- const gap = spec.gap ?? DEFAULT_GAP;
338
- const inner = contentBox(spec.outline, bounds);
339
- const width = Math.max(inner.width - padding * 2, 0);
340
- const heights = spec.rows.map((row) => measureRow(row, measure).height);
341
- const used = heights.reduce((sum, h) => sum + h, 0) + gap * Math.max(heights.length - 1, 0);
342
- const slack = Math.max(inner.height - padding * 2 - used, 0);
343
- const share = { top: 0, center: 0.5, bottom: 1 }[spec.verticalAlign ?? "center"];
344
- let y = inner.y + padding + slack * share;
345
- return spec.rows.map((row, index) => {
346
- const h = heights[index];
347
- const box = { row, index, x: inner.x + padding, y, width, height: h };
348
- y += h + gap;
349
- return box;
350
- });
351
- }
352
- function layoutRowPorts(row, box, measure) {
353
- const width = (label) => label === void 0 ? 0 : measureRow({ kind: "label", text: label }, measure).width;
354
- const slots = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);
355
- const slotHeight = box.height / slots;
356
- const out = [];
357
- const side = (ports, which) => {
358
- for (const [index, port] of (ports ?? []).entries()) {
359
- const w = width(port.label);
360
- out.push({
361
- port,
362
- side: which,
363
- index,
364
- x: which === "left" ? box.x : box.x + box.width - w,
365
- y: box.y + index * slotHeight,
366
- width: w,
367
- height: slotHeight
368
- });
369
- }
370
- };
371
- side(row.left, "left");
372
- side(row.right, "right");
373
- return out;
374
- }
375
- function bodyTrait(spec, bounds, measure) {
376
- const outline = spec.outline;
377
- const compass = spec.ports ?? [
378
- { id: "n", at: COMPASS.n },
379
- { id: "e", at: COMPASS.e },
380
- { id: "s", at: COMPASS.s },
381
- { id: "w", at: COMPASS.w }
382
- ];
383
- if (bounds.height <= 0) return { outline, ports: [...compass] };
384
- const rowPorts = [];
385
- let hasLeft = false;
386
- let hasRight = false;
387
- for (const box of layoutBody(spec, bounds, measure)) {
388
- if (box.row.kind !== "ports") continue;
389
- for (const pb of layoutRowPorts(box.row, box, measure)) {
390
- if (pb.side === "left") hasLeft = true;
391
- else hasRight = true;
392
- const v = (pb.y + pb.height / 2 - bounds.y) / bounds.height;
393
- rowPorts.push(withType(
394
- { id: pb.port.id, at: { u: pb.side === "left" ? 0 : 1, v } },
395
- pb.port.type
396
- ));
397
- }
398
- }
399
- const kept = spec.ports !== void 0 ? compass : compass.filter((p) => !(p.id === "w" && hasLeft) && !(p.id === "e" && hasRight));
400
- return { outline, ports: [...kept, ...rowPorts] };
401
- }
402
- function withType(spec, type) {
403
- return type === void 0 ? spec : { ...spec, type };
404
- }
405
- function bodyOutline(spec, bounds) {
406
- return outlinePath(spec.outline, bounds);
407
- }
408
- function buildBody(spec, at, opts) {
409
- const pose = sizeToBody(at, measureBody(spec, opts.measure));
410
- const specs = [{
411
- kind: "container",
412
- layer: opts.layer,
413
- pose,
414
- data: opts.body(bodyTrait(spec, pose, opts.measure), pose),
415
- ...opts.id === void 0 ? {} : { id: opts.id }
416
- }];
417
- const leaf = (box, data) => {
418
- specs.push({
419
- kind: "leaf",
420
- layer: opts.layer,
421
- pose: { ...pose, x: box.x, y: box.y, width: box.width, height: box.height },
422
- data,
423
- pickable: false,
424
- ...opts.id === void 0 ? {} : { parent: opts.id }
425
- });
426
- };
427
- const portLabel = opts.portLabel;
428
- for (const box of layoutBody(spec, pose, opts.measure)) {
429
- const data = opts.row(rowText(box.row), box);
430
- if (data !== null) leaf(box, data);
431
- if (portLabel === void 0 || box.row.kind !== "ports") continue;
432
- for (const pb of layoutRowPorts(box.row, box, opts.measure)) {
433
- if (pb.port.label === void 0) continue;
434
- const labelData = portLabel(pb.port.label, pb);
435
- if (labelData !== null) leaf(pb, labelData);
436
- }
437
- }
438
- return { pose, specs };
439
- }
440
- function rowText(row) {
441
- if (row.kind === "label") return row.text;
442
- if (row.kind === "field") return `${row.label}: ${row.value}`;
443
- return "";
444
- }
445
-
446
- // src/layout.ts
447
- var DEFAULT_NODE_GAP = 48;
448
- var DEFAULT_RANK_GAP = 96;
449
- var DEFAULT_TOLERANCE = 1e-6;
450
- function axesFor(direction = "down") {
451
- switch (direction) {
452
- case "up":
453
- return { rank: "y", cross: "x", sign: -1 };
454
- case "right":
455
- return { rank: "x", cross: "y", sign: 1 };
456
- case "left":
457
- return { rank: "x", cross: "y", sign: -1 };
458
- default:
459
- return { rank: "y", cross: "x", sign: 1 };
460
- }
461
- }
462
- function extent(bounds, axis) {
463
- return axis === "x" ? bounds.width : bounds.height;
464
- }
465
- function center(bounds, axis) {
466
- return axis === "x" ? bounds.x + bounds.width / 2 : bounds.y + bounds.height / 2;
467
- }
468
- function pinnedSet(graph, opts = {}) {
469
- const pinned = new Set(opts.pin ?? []);
470
- for (const node of graph.nodes) {
471
- if (node.pinned) pinned.add(node.id);
472
- }
473
- return pinned;
474
- }
475
- function settle(graph, slots, opts = {}) {
476
- const axes = axesFor(opts.direction);
477
- const pinned = pinnedSet(graph, opts);
478
- const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE;
479
- const placed = /* @__PURE__ */ new Map();
480
- for (const node of graph.nodes) {
481
- const slot = slots.get(node.id);
482
- if (slot === void 0) continue;
483
- const along = axes.sign === 1 ? slot.rank : -(slot.rank + extent(node.bounds, axes.rank));
484
- placed.set(
485
- node.id,
486
- axes.rank === "y" ? { x: slot.cross, y: along } : { x: along, y: slot.cross }
487
- );
488
- }
489
- return translated(graph, placed, pinned, tolerance);
490
- }
491
- function untilSettled(once, graph, opts = {}, passes = 8) {
492
- const first = once(graph, opts);
493
- if (first.size === 0) return first;
494
- const at = new Map(first);
495
- for (let pass = 1; pass < passes; pass++) {
496
- const nodes = graph.nodes.map((node) => {
497
- const to = at.get(node.id);
498
- return to === void 0 ? node : { ...node, bounds: { ...node.bounds, x: to.x, y: to.y } };
499
- });
500
- const byId = new Map(nodes.map((n) => [n.id, n]));
501
- const next = once({ ...graph, nodes, node: (id) => byId.get(id) }, opts);
502
- if (next.size === 0) break;
503
- for (const [id, to] of next) at.set(id, to);
504
- }
505
- const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE;
506
- const out = /* @__PURE__ */ new Map();
507
- for (const node of graph.nodes) {
508
- const to = at.get(node.id);
509
- if (to === void 0) continue;
510
- if (Math.abs(to.x - node.bounds.x) <= tolerance && Math.abs(to.y - node.bounds.y) <= tolerance) continue;
511
- out.set(node.id, to);
512
- }
513
- return out;
514
- }
515
- function translated(graph, placed, pinned, tolerance = DEFAULT_TOLERANCE) {
516
- const anchor = anchorDelta(graph, placed, pinned);
517
- const out = /* @__PURE__ */ new Map();
518
- for (const node of graph.nodes) {
519
- const at = placed.get(node.id);
520
- if (at === void 0 || pinned.has(node.id)) continue;
521
- const x = at.x + anchor.x;
522
- const y = at.y + anchor.y;
523
- if (Math.abs(x - node.bounds.x) <= tolerance && Math.abs(y - node.bounds.y) <= tolerance) {
524
- continue;
525
- }
526
- out.set(node.id, { x, y });
527
- }
528
- return out;
529
- }
530
- function anchorDelta(graph, placed, pinned) {
531
- for (const node of graph.nodes) {
532
- if (!pinned.has(node.id)) continue;
533
- const at = placed.get(node.id);
534
- if (at !== void 0) return { x: node.bounds.x - at.x, y: node.bounds.y - at.y };
535
- }
536
- let minCurX = Infinity;
537
- let minCurY = Infinity;
538
- let minNewX = Infinity;
539
- let minNewY = Infinity;
540
- for (const node of graph.nodes) {
541
- const at = placed.get(node.id);
542
- if (at === void 0) continue;
543
- minCurX = Math.min(minCurX, node.bounds.x);
544
- minCurY = Math.min(minCurY, node.bounds.y);
545
- minNewX = Math.min(minNewX, at.x);
546
- minNewY = Math.min(minNewY, at.y);
547
- }
548
- if (!Number.isFinite(minCurX)) return { x: 0, y: 0 };
549
- return { x: minCurX - minNewX, y: minCurY - minNewY };
550
- }
551
- function packAcross(nodes, axis, gap) {
552
- const at = /* @__PURE__ */ new Map();
553
- let cursor = 0;
554
- for (const node of nodes) {
555
- at.set(node.id, cursor);
556
- cursor += extent(node.bounds, axis) + gap;
557
- }
558
- return { at, span: nodes.length === 0 ? 0 : cursor - gap };
559
- }
560
- function seededOrder(nodes, axis, indexOf) {
561
- return [...nodes].sort((a, b) => {
562
- const d = center(a.bounds, axis) - center(b.bounds, axis);
563
- return d !== 0 ? d : indexOf(a.id) - indexOf(b.id);
564
- });
565
- }
566
- function graphOrder(graph) {
567
- const index = /* @__PURE__ */ new Map();
568
- graph.nodes.forEach((node, i) => index.set(node.id, i));
569
- return (id) => index.get(id) ?? Number.MAX_SAFE_INTEGER;
570
- }
571
-
572
- // src/cluster.ts
573
- function insetOf(inset) {
574
- if (typeof inset === "number") return { top: inset, right: inset, bottom: inset, left: inset };
575
- return {
576
- top: inset?.top ?? DEFAULT_GROUP_INSET,
577
- right: inset?.right ?? DEFAULT_GROUP_INSET,
578
- bottom: inset?.bottom ?? DEFAULT_GROUP_INSET,
579
- left: inset?.left ?? DEFAULT_GROUP_INSET
580
- };
581
- }
582
- var DEFAULT_GROUP_INSET = 12;
583
- function canonical(inset, axes) {
584
- if (axes.rank === "y") {
585
- return axes.sign === 1 ? { crossLo: inset.left, crossHi: inset.right, rankLo: inset.top, rankHi: inset.bottom } : { crossLo: inset.left, crossHi: inset.right, rankLo: inset.bottom, rankHi: inset.top };
586
- }
587
- return axes.sign === 1 ? { crossLo: inset.top, crossHi: inset.bottom, rankLo: inset.left, rankHi: inset.right } : { crossLo: inset.top, crossHi: inset.bottom, rankLo: inset.right, rankHi: inset.left };
588
- }
589
- function rankGaps(graph, rows, axes, rankGap) {
590
- const gaps = rows.slice(1).map(() => rankGap);
591
- const ends = /* @__PURE__ */ new Map();
592
- const starts = /* @__PURE__ */ new Map();
593
- const reach = (span, side) => {
594
- const own = canonical(span.group.inset, axes)[side === "lo" ? "rankLo" : "rankHi"];
595
- const flush = span.children.filter((c) => c[side] === span[side]);
596
- return own + Math.max(0, ...flush.map((c) => reach(c, side)));
597
- };
598
- for (const span of groupSpans(graph, rows)) {
599
- ends.set(span.hi, Math.max(ends.get(span.hi) ?? 0, reach(span, "hi")));
600
- starts.set(span.lo, Math.max(starts.get(span.lo) ?? 0, reach(span, "lo")));
601
- }
602
- for (let i = 0; i < gaps.length; i++) {
603
- gaps[i] = Math.max(gaps[i], rankGap + (ends.get(i) ?? 0) + (starts.get(i + 1) ?? 0));
604
- }
605
- return gaps;
606
- }
607
- function groupSpans(graph, rows) {
608
- const rankOf = /* @__PURE__ */ new Map();
609
- rows.forEach((row, i) => row.forEach((n) => rankOf.set(n.id, i)));
610
- const spans = [];
611
- const byId = /* @__PURE__ */ new Map();
612
- for (const group of graph.groups ?? []) {
613
- const ranks = group.members.map((id) => rankOf.get(id)).filter((r) => r !== void 0);
614
- if (ranks.length === 0) continue;
615
- const span = { group, lo: Math.min(...ranks), hi: Math.max(...ranks), children: [] };
616
- spans.push(span);
617
- byId.set(group.id, span);
618
- }
619
- for (const span of spans) {
620
- const parent = span.group.parent === void 0 ? void 0 : byId.get(span.group.parent);
621
- if (parent === void 0) continue;
622
- span.parent = parent;
623
- parent.children.push(span);
624
- }
625
- return spans;
626
- }
627
- function packClusters(graph, rows, preferred, axes, nodeGap) {
628
- const spans = groupSpans(graph, rows);
629
- const spanById = new Map(spans.map((s) => [s.group.id, s]));
630
- const spanOf = (n) => n.group === void 0 ? void 0 : spanById.get(n.group);
631
- const width = (n) => extent(n.bounds, axes.cross);
632
- const pref = (n) => preferred.get(n.id) ?? 0;
633
- const insets = new Map(spans.map((s) => [s, canonical(s.group.inset, axes)]));
634
- const centerOf = /* @__PURE__ */ new Map();
635
- for (const span of spans) {
636
- const inside = new Set(span.group.members);
637
- let sum = 0;
638
- let count = 0;
639
- for (const row of rows) {
640
- for (const n of row) {
641
- if (!inside.has(n.id)) continue;
642
- sum += pref(n) + width(n) / 2;
643
- count++;
644
- }
645
- }
646
- centerOf.set(span, count === 0 ? 0 : sum / count);
647
- }
648
- const itemsByRow = (owner, among) => rows.map((row, r) => {
649
- const items = [];
650
- for (const node of row) {
651
- if (spanOf(node) === owner) items.push({ kind: "node", node, center: pref(node) + width(node) / 2 });
652
- }
653
- for (const span of among) {
654
- if (r >= span.lo && r <= span.hi) items.push({ kind: "group", span, center: centerOf.get(span) });
655
- }
656
- return items.map((item, i) => ({ item, i })).sort((a, b) => a.item.center - b.item.center || a.i - b.i).map(({ item }) => item);
657
- });
658
- const settle2 = (byRow, start2, nodeFloor, origin) => {
659
- const nodeAt = /* @__PURE__ */ new Map();
660
- let ends = [];
661
- for (let pass = 0; pass <= start2.size; pass++) {
662
- let raised = false;
663
- ends = byRow.map((items) => {
664
- let cursor = origin;
665
- for (const item of items) {
666
- if (item.kind === "node") {
667
- const x2 = Math.max(nodeFloor(item.node), cursor);
668
- nodeAt.set(item.node.id, x2);
669
- cursor = x2 + width(item.node) + nodeGap;
670
- continue;
671
- }
672
- const s = start2.get(item.span);
673
- const x = Math.max(s, cursor);
674
- if (x > s) {
675
- start2.set(item.span, x);
676
- raised = true;
677
- }
678
- cursor = x + outer(item.span) + nodeGap;
679
- }
680
- return items.length === 0 ? origin : cursor - nodeGap;
681
- });
682
- if (!raised) break;
683
- }
684
- return { nodeAt, ends };
685
- };
686
- const blocks = /* @__PURE__ */ new Map();
687
- const blockOf = (span) => {
688
- const known = blocks.get(span);
689
- if (known !== void 0) return known;
690
- const byRow = itemsByRow(span, span.children);
691
- const childAt = new Map(span.children.map((c) => [c, 0]));
692
- const { nodeAt, ends } = settle2(byRow, childAt, () => 0, 0);
693
- const block = { width: Math.max(0, ...ends), nodeAt, childAt };
694
- const slack = widen(block, span.group, insets.get(span), axes);
695
- byRow.forEach((items, r) => {
696
- const shift = items.some((item) => item.kind === "group") ? slack : (block.width - ends[r]) / 2;
697
- for (const item of items) {
698
- if (item.kind === "node") nodeAt.set(item.node.id, nodeAt.get(item.node.id) + shift);
699
- }
700
- });
701
- blocks.set(span, block);
702
- return block;
703
- };
704
- function outer(span) {
705
- const inset = insets.get(span);
706
- return blockOf(span).width + inset.crossLo + inset.crossHi;
707
- }
708
- const roots = spans.filter((s) => s.parent === void 0);
709
- const start = new Map(roots.map((s) => [s, centerOf.get(s) - outer(s) / 2]));
710
- const { nodeAt: at } = settle2(itemsByRow(void 0, roots), start, pref, -Infinity);
711
- const place = (span, from) => {
712
- const origin = from + insets.get(span).crossLo;
713
- const block = blockOf(span);
714
- for (const [id, local] of block.nodeAt) at.set(id, origin + local);
715
- for (const [child, local] of block.childAt) place(child, origin + local);
716
- };
717
- for (const root of roots) place(root, start.get(root));
718
- return at;
719
- }
720
- function widen(block, group, inset, axes) {
721
- const floor = axes.cross === "x" ? (group.minWidth ?? 0) - inset.crossLo - inset.crossHi : 0;
722
- const slack = Math.max(0, floor - block.width) / 2;
723
- block.width += 2 * slack;
724
- for (const [child, local] of block.childAt) block.childAt.set(child, local + slack);
725
- return slack;
726
- }
727
- function expandGroupEdges(edges, groups) {
728
- const byId = new Map(groups.map((g) => [g.id, g]));
729
- if (byId.size === 0) return [...edges];
730
- const within = (id, group) => {
731
- if (!byId.has(id)) return group.members.includes(id);
732
- for (let at = byId.get(id); at !== void 0; at = at.parent === void 0 ? void 0 : byId.get(at.parent)) {
733
- if (at === group) return true;
734
- }
735
- return false;
736
- };
737
- const entries = /* @__PURE__ */ new Map();
738
- const exits = /* @__PURE__ */ new Map();
739
- for (const g of groups) {
740
- const inside = new Set(g.members);
741
- const pointedAt = /* @__PURE__ */ new Set();
742
- const pointing = /* @__PURE__ */ new Set();
743
- for (const e of edges) {
744
- if (inside.has(e.from) && inside.has(e.to) && e.from !== e.to) {
745
- pointedAt.add(e.to);
746
- pointing.add(e.from);
747
- }
748
- }
749
- const entry = g.members.filter((m) => !pointedAt.has(m));
750
- const exit = g.members.filter((m) => !pointing.has(m));
751
- entries.set(g.id, entry.length > 0 ? entry : g.members);
752
- exits.set(g.id, exit.length > 0 ? exit : g.members);
753
- }
754
- const out = [];
755
- for (const e of edges) {
756
- const fromGroup = byId.has(e.from) ? e.from : void 0;
757
- const toGroup = byId.has(e.to) ? e.to : void 0;
758
- if (fromGroup === void 0 && toGroup === void 0) {
759
- out.push(e);
760
- continue;
761
- }
762
- if (fromGroup !== void 0 && within(e.to, byId.get(fromGroup))) continue;
763
- if (toGroup !== void 0 && within(e.from, byId.get(toGroup))) continue;
764
- const froms = fromGroup !== void 0 ? exits.get(fromGroup) : [e.from];
765
- const tos = toGroup !== void 0 ? entries.get(toGroup) : [e.to];
766
- let k = 0;
767
- for (const from of froms) {
768
- for (const to of tos) out.push({ id: `${e.id}#${k++}`, from, to });
769
- }
770
- }
771
- return out;
772
- }
773
-
774
- // src/forceGroups.ts
775
- function resolve(groups, byId) {
776
- const out = [];
777
- for (const group of groups) {
778
- const members = group.members.map((id) => byId.get(id)).filter((b) => b !== void 0);
779
- if (members.length > 0) out.push({ members, group, children: [] });
780
- }
781
- const byGroup = new Map(out.map((g) => [g.group.id, g]));
782
- for (const g of out) {
783
- const parent = g.group.parent === void 0 ? void 0 : byGroup.get(g.group.parent);
784
- if (parent === void 0) continue;
785
- g.parent = parent;
786
- parent.children.push(g);
787
- }
788
- return out;
789
- }
790
- function groupCohesion(groups, byId, strength) {
791
- const resolved = resolve(groups, byId);
792
- return (alpha) => {
793
- for (const { members } of resolved) {
794
- let cx = 0;
795
- let cy = 0;
796
- for (const m of members) {
797
- cx += m.x;
798
- cy += m.y;
799
- }
800
- cx /= members.length;
801
- cy /= members.length;
802
- for (const m of members) {
803
- m.vx += (cx - m.x) * strength * alpha;
804
- m.vy += (cy - m.y) * strength * alpha;
805
- }
806
- }
807
- };
808
- }
809
- function boxOf(g) {
810
- let x0 = Infinity;
811
- let y0 = Infinity;
812
- let x1 = -Infinity;
813
- let y1 = -Infinity;
814
- for (const m of g.members) {
815
- x0 = Math.min(x0, m.x - m.hw);
816
- y0 = Math.min(y0, m.y - m.hh);
817
- x1 = Math.max(x1, m.x + m.hw);
818
- y1 = Math.max(y1, m.y + m.hh);
819
- }
820
- for (const child of g.children) {
821
- const b = boxOf(child);
822
- x0 = Math.min(x0, b.x0);
823
- y0 = Math.min(y0, b.y0);
824
- x1 = Math.max(x1, b.x1);
825
- y1 = Math.max(y1, b.y1);
826
- }
827
- const { inset } = g.group;
828
- return { x0: x0 - inset.left, y0: y0 - inset.top, x1: x1 + inset.right, y1: y1 + inset.bottom };
829
- }
830
- function clearance(a, b, padding) {
831
- const gapX = Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0) + padding;
832
- const gapY = Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0) + padding;
833
- if (gapX <= 0 || gapY <= 0) return null;
834
- const dx = b.x0 + b.x1 - (a.x0 + a.x1);
835
- const dy = b.y0 + b.y1 - (a.y0 + a.y1);
836
- return gapX < gapY ? { x: (Math.sign(dx) || 1) * gapX, y: 0 } : { x: 0, y: (Math.sign(dy) || 1) * gapY };
837
- }
838
- function holds(outer, inner) {
839
- for (let at = inner.parent; at !== void 0; at = at.parent) {
840
- if (at === outer) return true;
841
- }
842
- return false;
843
- }
844
- function shove(bodies, x, y) {
845
- for (const body of bodies) {
846
- body.vx += x;
847
- body.vy += y;
848
- }
849
- }
850
- function separateGroups(groups, bodies, byId, padding) {
851
- const resolved = resolve(groups, byId);
852
- const memberSets = resolved.map((g) => new Set(g.members));
853
- return () => {
854
- const boxes = resolved.map(boxOf);
855
- for (let i = 0; i < resolved.length; i++) {
856
- for (let j = i + 1; j < resolved.length; j++) {
857
- if (holds(resolved[i], resolved[j]) || holds(resolved[j], resolved[i])) continue;
858
- const push = clearance(boxes[i], boxes[j], padding);
859
- if (push === null) continue;
860
- shove(resolved[i].members, -push.x / 2, -push.y / 2);
861
- shove(resolved[j].members, push.x / 2, push.y / 2);
862
- }
863
- for (const body of bodies) {
864
- if (memberSets[i].has(body)) continue;
865
- const box = { x0: body.x - body.hw, y0: body.y - body.hh, x1: body.x + body.hw, y1: body.y + body.hh };
866
- const push = clearance(boxes[i], box, padding);
867
- if (push === null) continue;
868
- shove(resolved[i].members, -push.x / 2, -push.y / 2);
869
- body.vx += push.x / 2;
870
- body.vy += push.y / 2;
871
- }
872
- }
873
- };
874
- }
875
-
876
- // src/force.ts
877
- var DEFAULTS = {
878
- iterations: 300,
879
- linkDistance: 160,
880
- linkStrength: 0.35,
881
- charge: -3e3,
882
- gravity: 0.02,
883
- padding: 24,
884
- groupStrength: 0.2
885
- };
886
- var GOLDEN = Math.PI * (3 - Math.sqrt(5));
887
- var NUDGE = 0.5;
888
- function charge(bodies, strength) {
889
- return (alpha) => {
890
- for (let i = 0; i < bodies.length; i++) {
891
- const a = bodies[i];
892
- for (let j = i + 1; j < bodies.length; j++) {
893
- const b = bodies[j];
894
- const dx = b.x - a.x;
895
- const dy = b.y - a.y;
896
- const d2 = dx * dx + dy * dy;
897
- if (d2 === 0) continue;
898
- const w = strength * alpha / d2;
899
- a.vx += dx * w;
900
- a.vy += dy * w;
901
- b.vx -= dx * w;
902
- b.vy -= dy * w;
903
- }
904
- }
905
- };
906
- }
907
- function links(bodies, graph, distance, strength) {
908
- return (alpha) => {
909
- for (const edge of graph.edges) {
910
- const a = bodies.get(edge.from);
911
- const b = bodies.get(edge.to);
912
- if (a === void 0 || b === void 0 || a === b) continue;
913
- const dx = b.x - a.x;
914
- const dy = b.y - a.y;
915
- const d = Math.hypot(dx, dy);
916
- if (d === 0) continue;
917
- const pull = (d - distance) / d * alpha * strength;
918
- a.vx += dx * pull;
919
- a.vy += dy * pull;
920
- b.vx -= dx * pull;
921
- b.vy -= dy * pull;
922
- }
923
- };
924
- }
925
- function separateBoxes(bodies, padding) {
926
- return () => {
927
- for (let i = 0; i < bodies.length; i++) {
928
- const a = bodies[i];
929
- for (let j = i + 1; j < bodies.length; j++) {
930
- const b = bodies[j];
931
- const dx = b.x - a.x;
932
- const dy = b.y - a.y;
933
- const gapX = a.hw + b.hw + padding - Math.abs(dx);
934
- const gapY = a.hh + b.hh + padding - Math.abs(dy);
935
- if (gapX <= 0 || gapY <= 0) continue;
936
- if (gapX < gapY) {
937
- const push = (Math.sign(dx) || 1) * gapX * 0.5;
938
- a.vx -= push;
939
- b.vx += push;
940
- } else {
941
- const push = (Math.sign(dy) || 1) * gapY * 0.5;
942
- a.vy -= push;
943
- b.vy += push;
944
- }
945
- }
946
- }
947
- };
948
- }
949
- function gravity(bodies, at, strength) {
950
- return (alpha) => {
951
- for (const body of bodies) {
952
- body.vx += (at.x - body.x) * strength * alpha;
953
- body.vy += (at.y - body.y) * strength * alpha;
954
- }
955
- };
956
- }
957
- function forceRelaxation(graph, opts = {}) {
958
- const {
959
- linkDistance = DEFAULTS.linkDistance,
960
- linkStrength = DEFAULTS.linkStrength,
961
- charge: chargeStrength = DEFAULTS.charge,
962
- gravity: gravityStrength = DEFAULTS.gravity,
963
- padding = DEFAULTS.padding,
964
- groupStrength = DEFAULTS.groupStrength
965
- } = opts;
966
- const pinned = pinnedSet(graph, opts);
967
- const bodies = graph.nodes.map((node) => {
968
- const body = {
969
- id: node.id,
970
- x: center(node.bounds, "x"),
971
- y: center(node.bounds, "y"),
972
- hw: node.bounds.width / 2,
973
- hh: node.bounds.height / 2
974
- };
975
- if (pinned.has(node.id)) {
976
- body.fx = body.x;
977
- body.fy = body.y;
978
- }
979
- return body;
980
- });
981
- separate(bodies);
982
- const byId = new Map(bodies.map((b) => [b.id, b]));
983
- const centroid = {
984
- x: bodies.reduce((sum, b) => sum + b.x, 0) / bodies.length,
985
- y: bodies.reduce((sum, b) => sum + b.y, 0) / bodies.length
986
- };
987
- const groups = graph.groups ?? [];
988
- const sim = createSimulation({
989
- nodes: bodies,
990
- forces: [
991
- charge(bodies, chargeStrength),
992
- links(byId, graph, linkDistance, linkStrength),
993
- gravity(bodies, centroid, gravityStrength),
994
- separateBoxes(bodies, padding),
995
- ...groups.length > 0 ? [groupCohesion(groups, byId, groupStrength), separateGroups(groups, bodies, byId, padding)] : []
996
- ]
997
- });
998
- return {
999
- bodies,
1000
- byId,
1001
- pinned,
1002
- sim,
1003
- placed() {
1004
- const placed = /* @__PURE__ */ new Map();
1005
- for (const node of graph.nodes) {
1006
- const body = byId.get(node.id);
1007
- placed.set(node.id, {
1008
- x: body.x - node.bounds.width / 2,
1009
- y: body.y - node.bounds.height / 2
1010
- });
1011
- }
1012
- return placed;
1013
- }
1014
- };
1015
- }
1016
- var force = (graph, opts = {}) => {
1017
- if (graph.nodes.length === 0) return /* @__PURE__ */ new Map();
1018
- const relaxation = forceRelaxation(graph, opts);
1019
- relaxation.sim.tick(opts.iterations ?? DEFAULTS.iterations);
1020
- return translated(graph, relaxation.placed(), relaxation.pinned, opts.tolerance);
1021
- };
1022
- function separate(bodies) {
1023
- const seen = /* @__PURE__ */ new Map();
1024
- bodies.forEach((body, i) => {
1025
- const key = `${body.x},${body.y}`;
1026
- const nth = seen.get(key) ?? 0;
1027
- seen.set(key, nth + 1);
1028
- if (nth === 0 || body.fx != null || body.fy != null) return;
1029
- const angle = GOLDEN * i;
1030
- const radius = NUDGE * nth;
1031
- body.x += Math.cos(angle) * radius;
1032
- body.y += Math.sin(angle) * radius;
1033
- });
1034
- }
1035
-
1036
- // src/barycenter.ts
1037
- var SWEEPS = 4;
1038
- function barycenterOrder(graph, rows, back) {
1039
- const out = rows.map((row) => [...row]);
1040
- const index = /* @__PURE__ */ new Map();
1041
- const reindex = (row) => row.forEach((n, i) => index.set(n.id, i));
1042
- out.forEach(reindex);
1043
- const reorder = (row, neighbors) => {
1044
- const key = /* @__PURE__ */ new Map();
1045
- for (const [i, n] of row.entries()) {
1046
- const at = neighbors(n.id).map((id) => index.get(id)).filter((v) => v !== void 0);
1047
- key.set(n.id, at.length === 0 ? i : at.reduce((s, v) => s + v, 0) / at.length);
1048
- }
1049
- row.sort((a, b) => key.get(a.id) - key.get(b.id) || index.get(a.id) - index.get(b.id));
1050
- reindex(row);
1051
- };
1052
- const ups = (id) => graph.incoming(id).filter((e) => !back.has(e.id)).map((e) => e.from);
1053
- const downs = (id) => graph.outgoing(id).filter((e) => !back.has(e.id)).map((e) => e.to);
1054
- for (let s = 0; s < SWEEPS; s++) {
1055
- for (let r = 1; r < out.length; r++) reorder(out[r], ups);
1056
- for (let r = out.length - 2; r >= 0; r--) reorder(out[r], downs);
1057
- }
1058
- return out;
1059
- }
1060
-
1061
- // src/layered.ts
1062
- function backEdges(graph) {
1063
- const back = /* @__PURE__ */ new Set();
1064
- const done = /* @__PURE__ */ new Set();
1065
- const onStack = /* @__PURE__ */ new Set();
1066
- const walk = (id) => {
1067
- if (done.has(id)) return;
1068
- onStack.add(id);
1069
- for (const edge of graph.outgoing(id)) {
1070
- if (onStack.has(edge.to)) back.add(edge.id);
1071
- else walk(edge.to);
1072
- }
1073
- onStack.delete(id);
1074
- done.add(id);
1075
- };
1076
- for (const node of graph.nodes) walk(node.id);
1077
- return back;
1078
- }
1079
- function ranksOf(graph, back) {
1080
- const ranks = /* @__PURE__ */ new Map();
1081
- const resolving = /* @__PURE__ */ new Set();
1082
- const rankOf = (id) => {
1083
- const known = ranks.get(id);
1084
- if (known !== void 0) return known;
1085
- if (resolving.has(id)) return 0;
1086
- resolving.add(id);
1087
- let rank = 0;
1088
- for (const edge of graph.incoming(id)) {
1089
- if (back.has(edge.id)) continue;
1090
- rank = Math.max(rank, rankOf(edge.from) + 1);
1091
- }
1092
- resolving.delete(id);
1093
- ranks.set(id, rank);
1094
- return rank;
1095
- };
1096
- for (const node of graph.nodes) rankOf(node.id);
1097
- return ranks;
1098
- }
1099
- var layered = (graph, opts = {}) => (
1100
- // Barycenter ordering reorders on every run by design, so it has no
1101
- // arrangement to settle on.
1102
- (graph.groups?.length ?? 0) > 0 && opts.order !== "barycenter" ? untilSettled(layeredOnce, graph, opts) : layeredOnce(graph, opts)
1103
- );
1104
- var layeredOnce = (graph, opts = {}) => {
1105
- const axes = axesFor(opts.direction);
1106
- const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;
1107
- const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;
1108
- const order = graphOrder(graph);
1109
- const back = backEdges(graph);
1110
- const ranks = ranksOf(graph, back);
1111
- const byRank = /* @__PURE__ */ new Map();
1112
- for (const node of graph.nodes) {
1113
- const rank = ranks.get(node.id) ?? 0;
1114
- const list = byRank.get(rank);
1115
- if (list === void 0) byRank.set(rank, [node]);
1116
- else list.push(node);
1117
- }
1118
- const rows = [...byRank.keys()].sort((a, b) => a - b);
1119
- let ordered = rows.map((rank) => seededOrder(byRank.get(rank), axes.cross, order));
1120
- if (opts.order === "barycenter") ordered = barycenterOrder(graph, ordered, back);
1121
- const packed = ordered.map((row) => packAcross(row, axes.cross, nodeGap));
1122
- const widest = Math.max(0, ...packed.map((p) => p.span));
1123
- const preferred = /* @__PURE__ */ new Map();
1124
- for (const [i, row] of ordered.entries()) {
1125
- const indent = (widest - packed[i].span) / 2;
1126
- for (const node of row) preferred.set(node.id, indent + packed[i].at.get(node.id));
1127
- }
1128
- const grouped = (graph.groups?.length ?? 0) > 0;
1129
- const crossAt = grouped ? packClusters(graph, ordered, preferred, axes, nodeGap) : preferred;
1130
- const gaps = grouped ? rankGaps(graph, ordered, axes, rankGap) : ordered.slice(1).map(() => rankGap);
1131
- const slots = /* @__PURE__ */ new Map();
1132
- let along = 0;
1133
- for (const [i, row] of ordered.entries()) {
1134
- const depth = Math.max(0, ...row.map((n) => extent(n.bounds, axes.rank)));
1135
- for (const node of row) {
1136
- slots.set(node.id, {
1137
- cross: crossAt.get(node.id),
1138
- // Centered in its rank's band, so a tall node does not push its
1139
- // neighbors' edges off the line they read along.
1140
- rank: along + (depth - extent(node.bounds, axes.rank)) / 2
1141
- });
1142
- }
1143
- along += depth + (gaps[i] ?? 0);
1144
- }
1145
- return settle(graph, slots, opts);
1146
- };
1147
-
1148
- // src/tree.ts
1149
- function forestOf(graph, crossAxis) {
1150
- const order = graphOrder(graph);
1151
- const children = /* @__PURE__ */ new Map();
1152
- const depth = /* @__PURE__ */ new Map();
1153
- const roots = [];
1154
- const claim = (node, at) => {
1155
- depth.set(node.id, at);
1156
- const kids = [];
1157
- for (const edge of graph.outgoing(node.id)) {
1158
- if (edge.to === node.id || depth.has(edge.to)) continue;
1159
- const child = graph.node(edge.to);
1160
- if (child === void 0) continue;
1161
- depth.set(child.id, at + 1);
1162
- kids.push(child);
1163
- }
1164
- const ordered = seededOrder(kids, crossAxis, order);
1165
- children.set(node.id, ordered);
1166
- for (const child of ordered) claim(child, at + 1);
1167
- };
1168
- const rootish = graph.nodes.filter((node) => graph.incoming(node.id).every((edge) => edge.from === node.id));
1169
- for (const node of seededOrder(rootish, crossAxis, order)) {
1170
- if (depth.has(node.id)) continue;
1171
- roots.push(node);
1172
- claim(node, 0);
1173
- }
1174
- for (const node of graph.nodes) {
1175
- if (depth.has(node.id)) continue;
1176
- roots.push(node);
1177
- claim(node, 0);
1178
- }
1179
- return { roots, children, depth };
1180
- }
1181
- var tree = (graph, opts = {}) => (graph.groups?.length ?? 0) > 0 ? untilSettled(treeOnce, graph, opts) : treeOnce(graph, opts);
1182
- var treeOnce = (graph, opts = {}) => {
1183
- const axes = axesFor(opts.direction);
1184
- const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;
1185
- const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;
1186
- const { roots, children, depth } = forestOf(graph, axes.cross);
1187
- const bands = /* @__PURE__ */ new Map();
1188
- for (const node of graph.nodes) {
1189
- const at = depth.get(node.id) ?? 0;
1190
- bands.set(at, Math.max(bands.get(at) ?? 0, extent(node.bounds, axes.rank)));
1191
- }
1192
- const depths = [...bands.keys()].sort((a, b) => a - b);
1193
- const rowsAt = depths.map((at) => graph.nodes.filter((n) => (depth.get(n.id) ?? 0) === at));
1194
- const grouped = (graph.groups?.length ?? 0) > 0;
1195
- const gaps = grouped ? rankGaps(graph, rowsAt, axes, rankGap) : depths.slice(1).map(() => rankGap);
1196
- const bandStart = /* @__PURE__ */ new Map();
1197
- let along = 0;
1198
- for (const [i, at] of depths.entries()) {
1199
- bandStart.set(at, along);
1200
- along += bands.get(at) + (gaps[i] ?? 0);
1201
- }
1202
- const slots = /* @__PURE__ */ new Map();
1203
- const measured = /* @__PURE__ */ new Map();
1204
- const measure = (node) => {
1205
- const known = measured.get(node.id);
1206
- if (known !== void 0) return known;
1207
- const kids = children.get(node.id) ?? [];
1208
- let width = 0;
1209
- for (const child of kids) width += measure(child);
1210
- if (kids.length > 0) width += nodeGap * (kids.length - 1);
1211
- const block = Math.max(extent(node.bounds, axes.cross), width);
1212
- measured.set(node.id, block);
1213
- return block;
1214
- };
1215
- const place = (node, from) => {
1216
- const kids = children.get(node.id) ?? [];
1217
- const block = measure(node);
1218
- const width = kids.reduce((sum, k) => sum + measure(k), 0) + Math.max(0, kids.length - 1) * nodeGap;
1219
- let cursor2 = from + (block - width) / 2;
1220
- for (const child of kids) {
1221
- place(child, cursor2);
1222
- cursor2 += measure(child) + nodeGap;
1223
- }
1224
- const own = extent(node.bounds, axes.cross);
1225
- const at = depth.get(node.id) ?? 0;
1226
- slots.set(node.id, {
1227
- cross: from + (block - own) / 2,
1228
- rank: bandStart.get(at) + (bands.get(at) - extent(node.bounds, axes.rank)) / 2
1229
- });
1230
- };
1231
- let cursor = 0;
1232
- for (const root of roots) {
1233
- place(root, cursor);
1234
- cursor += measure(root) + nodeGap;
1235
- }
1236
- if (grouped) {
1237
- const preferred = new Map([...slots].map(([id, slot]) => [id, slot.cross]));
1238
- const ordered = rowsAt.map((row) => [...row].sort((a, b) => preferred.get(a.id) - preferred.get(b.id)));
1239
- const crossAt = packClusters(graph, ordered, preferred, axes, nodeGap);
1240
- for (const [id, slot] of slots) slots.set(id, { ...slot, cross: crossAt.get(id) ?? slot.cross });
1241
- }
1242
- return settle(graph, slots, opts);
1243
- };
1244
-
1245
- export { COMPASS, DEFAULT_GROUP_INSET, DEFAULT_NODE_GAP, DEFAULT_PORTS, DEFAULT_RANK_GAP, DIAGRAM_TRAIT_KEY, axesFor, backEdges, bodyOutline, bodyTrait, boxForContent, buildBody, canvasMeasure, center, contentBox, createDiagramNodes, dataKeyReader, diagramNodeOf, expandGroupEdges, extent, force, forceRelaxation, forestOf, graphOrder, insetOf, isPinned, layered, layoutBody, layoutRowPorts, measureBody, outlinePath, outlinePolyline, packAcross, packClusters, pinnedSet, portOf, portsOf, portsOnOutline, rankGaps, ranksOf, rayHit, seededOrder, settle, sizeToBody, translated, tree, untilSettled };
1246
- //# sourceMappingURL=chunk-JZ4CVLAB.js.map
1247
- //# sourceMappingURL=chunk-JZ4CVLAB.js.map