@weasel-js/diagram 1.5.0 → 1.5.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.
@@ -0,0 +1,862 @@
1
+ import { rectPath, polygonFromPoints, PathBuilder, PATH_M, PATH_L, PATH_C, flattenCubic, PATH_Q, PATH_Z, AUTO_POSE_DESCRIPTOR, rotatePoint, createSimulation } from '@weasel-js/core/math';
2
+
3
+ // src/outline.ts
4
+ var LEAN = 0.2;
5
+ var KAPPA = 0.5522847498307936;
6
+ function outlinePath(outline, bounds) {
7
+ if (typeof outline !== "string") return outline;
8
+ const { x, y, width: w, height: h } = bounds;
9
+ if (w <= 0 || h <= 0) return rectPath(x, y, Math.max(w, 0), Math.max(h, 0));
10
+ switch (outline) {
11
+ case "rect":
12
+ return rectPath(x, y, w, h);
13
+ case "diamond":
14
+ return polygonFromPoints([
15
+ { x: x + w / 2, y },
16
+ { x: x + w, y: y + h / 2 },
17
+ { x: x + w / 2, y: y + h },
18
+ { x, y: y + h / 2 }
19
+ ]);
20
+ case "parallelogram": {
21
+ const lean = Math.min(w * LEAN, w / 2);
22
+ return polygonFromPoints([
23
+ { x: x + lean, y },
24
+ { x: x + w, y },
25
+ { x: x + w - lean, y: y + h },
26
+ { x, y: y + h }
27
+ ]);
28
+ }
29
+ case "stadium":
30
+ return stadiumPath(x, y, w, h);
31
+ }
32
+ }
33
+ function stadiumPath(x, y, w, h) {
34
+ const r = Math.min(w, h) / 2;
35
+ const k = r * KAPPA;
36
+ const b = new PathBuilder();
37
+ if (w >= h) {
38
+ const left2 = x + r;
39
+ const right2 = x + w - r;
40
+ const top2 = y;
41
+ const bottom2 = y + h;
42
+ const midY = y + h / 2;
43
+ 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();
44
+ }
45
+ const top = y + r;
46
+ const bottom = y + h - r;
47
+ const left = x;
48
+ const right = x + w;
49
+ const midX = x + w / 2;
50
+ 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();
51
+ }
52
+ function contentBox(outline, bounds) {
53
+ if (typeof outline !== "string") return bounds;
54
+ const { x, y, width: w, height: h } = bounds;
55
+ switch (outline) {
56
+ case "rect":
57
+ return bounds;
58
+ case "diamond":
59
+ return { x: x + w / 4, y: y + h / 4, width: w / 2, height: h / 2 };
60
+ case "parallelogram": {
61
+ const lean = Math.min(w * LEAN, w / 2);
62
+ return { x: x + lean, y, width: Math.max(w - lean * 2, 0), height: h };
63
+ }
64
+ case "stadium": {
65
+ const r = Math.min(w, h) / 2;
66
+ 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) };
67
+ }
68
+ }
69
+ }
70
+ function boxForContent(outline, content) {
71
+ if (typeof outline !== "string") return content;
72
+ switch (outline) {
73
+ case "rect":
74
+ return content;
75
+ case "diamond":
76
+ return { width: content.width * 2, height: content.height * 2 };
77
+ case "parallelogram":
78
+ return { width: content.width / (1 - LEAN * 2), height: content.height };
79
+ case "stadium":
80
+ return { width: content.width + content.height, height: content.height };
81
+ }
82
+ }
83
+ var TOLERANCE = 0.25;
84
+ function outlinePolyline(outline, bounds) {
85
+ const path = outlinePath(outline, bounds);
86
+ return flattenPath(path);
87
+ }
88
+ function flattenPath(path) {
89
+ if (path.kind === "rect") {
90
+ const { x, y, width: w, height: h } = path;
91
+ return [x, y, x + w, y, x + w, y + h, x, y + h, x, y];
92
+ }
93
+ const out = [];
94
+ const { commands, coords } = path;
95
+ let ci = 0;
96
+ let cx = 0;
97
+ let cy = 0;
98
+ let sx = 0;
99
+ let sy = 0;
100
+ for (const cmd of commands) {
101
+ if (cmd === PATH_M) {
102
+ cx = coords[ci];
103
+ cy = coords[ci + 1];
104
+ ci += 2;
105
+ sx = cx;
106
+ sy = cy;
107
+ out.push(cx, cy);
108
+ } else if (cmd === PATH_L) {
109
+ cx = coords[ci];
110
+ cy = coords[ci + 1];
111
+ ci += 2;
112
+ out.push(cx, cy);
113
+ } else if (cmd === PATH_C) {
114
+ const x1 = coords[ci], y1 = coords[ci + 1];
115
+ const x2 = coords[ci + 2], y2 = coords[ci + 3];
116
+ const x3 = coords[ci + 4], y3 = coords[ci + 5];
117
+ ci += 6;
118
+ flattenCubic(cx, cy, x1, y1, x2, y2, x3, y3, TOLERANCE, out);
119
+ cx = x3;
120
+ cy = y3;
121
+ } else if (cmd === PATH_Q) {
122
+ const qx = coords[ci], qy = coords[ci + 1];
123
+ const x3 = coords[ci + 2], y3 = coords[ci + 3];
124
+ ci += 4;
125
+ flattenCubic(
126
+ cx,
127
+ cy,
128
+ cx + 2 / 3 * (qx - cx),
129
+ cy + 2 / 3 * (qy - cy),
130
+ x3 + 2 / 3 * (qx - x3),
131
+ y3 + 2 / 3 * (qy - y3),
132
+ x3,
133
+ y3,
134
+ TOLERANCE,
135
+ out
136
+ );
137
+ cx = x3;
138
+ cy = y3;
139
+ } else if (cmd === PATH_Z) {
140
+ out.push(sx, sy);
141
+ cx = sx;
142
+ cy = sy;
143
+ }
144
+ }
145
+ if (out.length >= 2 && (out[0] !== out[out.length - 2] || out[1] !== out[out.length - 1])) {
146
+ out.push(out[0], out[1]);
147
+ }
148
+ return out;
149
+ }
150
+ function rayHit(poly, center2, point) {
151
+ const dx = point.x - center2.x;
152
+ const dy = point.y - center2.y;
153
+ if (dx === 0 && dy === 0) return null;
154
+ let bestT = -Infinity;
155
+ let hit = null;
156
+ for (let i = 0; i + 3 < poly.length; i += 2) {
157
+ const ax = poly[i], ay = poly[i + 1];
158
+ const bx = poly[i + 2], by = poly[i + 3];
159
+ const ex = bx - ax;
160
+ const ey = by - ay;
161
+ const denom = dx * ey - dy * ex;
162
+ if (denom === 0) continue;
163
+ const t = ((ax - center2.x) * ey - (ay - center2.y) * ex) / denom;
164
+ const u = ((ax - center2.x) * dy - (ay - center2.y) * dx) / denom;
165
+ if (t < 0 || u < 0 || u > 1) continue;
166
+ if (t > bestT) {
167
+ bestT = t;
168
+ hit = { x: center2.x + dx * t, y: center2.y + dy * t };
169
+ }
170
+ }
171
+ return hit;
172
+ }
173
+ function portsOnOutline(ports, outline, bounds) {
174
+ if (bounds.width <= 0 || bounds.height <= 0) return [...ports];
175
+ const poly = outlinePolyline(outline, bounds);
176
+ const center2 = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
177
+ return ports.map((port) => {
178
+ const hit = rayHit(poly, center2, port.point);
179
+ return hit === null ? port : { ...port, point: hit };
180
+ });
181
+ }
182
+
183
+ // src/trait.ts
184
+ var DIAGRAM_TRAIT_KEY = "diagram";
185
+ var dataKeyReader = (node) => {
186
+ const data = node.data;
187
+ if (data === null || typeof data !== "object") return null;
188
+ const trait = data[DIAGRAM_TRAIT_KEY];
189
+ if (trait === null || typeof trait !== "object") return null;
190
+ if ("from" in trait && "to" in trait) return null;
191
+ return trait;
192
+ };
193
+ function createDiagramNodes(entries) {
194
+ const seen = /* @__PURE__ */ new Set();
195
+ for (const entry of entries) {
196
+ if (seen.has(entry.name)) {
197
+ throw new Error(`createDiagramNodes: duplicate entry name "${entry.name}"`);
198
+ }
199
+ seen.add(entry.name);
200
+ }
201
+ return (node) => {
202
+ const own = dataKeyReader(node);
203
+ if (own !== null) return own;
204
+ for (const entry of entries) {
205
+ if (!entry.matches(node.data)) continue;
206
+ return typeof entry.trait === "function" ? entry.trait(node.data) : entry.trait;
207
+ }
208
+ return null;
209
+ };
210
+ }
211
+ function diagramNodeOf(node, read = dataKeyReader) {
212
+ return read(node);
213
+ }
214
+ function isPinned(node, read) {
215
+ return diagramNodeOf(node, read)?.pinned === true;
216
+ }
217
+ var COMPASS = {
218
+ nw: { u: 0, v: 0 },
219
+ n: { u: 0.5, v: 0 },
220
+ ne: { u: 1, v: 0 },
221
+ e: { u: 1, v: 0.5 },
222
+ se: { u: 1, v: 1 },
223
+ s: { u: 0.5, v: 1 },
224
+ sw: { u: 0, v: 1 },
225
+ w: { u: 0, v: 0.5 }
226
+ };
227
+ var DEFAULT_PORTS = Object.freeze([
228
+ { id: "n", at: COMPASS.n },
229
+ { id: "e", at: COMPASS.e },
230
+ { id: "s", at: COMPASS.s },
231
+ { id: "w", at: COMPASS.w }
232
+ ]);
233
+ function normalOf(at) {
234
+ const x = at.u * 2 - 1;
235
+ const y = at.v * 2 - 1;
236
+ const len = Math.hypot(x, y);
237
+ if (len === 0) return null;
238
+ return { x: x / len, y: y / len };
239
+ }
240
+ function portsOf(node, pose, opts = {}) {
241
+ const trait = diagramNodeOf(node, opts.read);
242
+ if (trait === null) return [];
243
+ const geometry = opts.geometry ?? AUTO_POSE_DESCRIPTOR;
244
+ const bounds = geometry.getBounds(pose);
245
+ const rotation = geometry.getRotation?.(pose) ?? 0;
246
+ const cx = bounds.x + bounds.width / 2;
247
+ const cy = bounds.y + bounds.height / 2;
248
+ const poly = trait.outline === void 0 || bounds.width <= 0 || bounds.height <= 0 ? null : outlinePolyline(trait.outline, bounds);
249
+ return (trait.ports ?? DEFAULT_PORTS).map((spec) => {
250
+ const anchored = {
251
+ x: bounds.x + spec.at.u * bounds.width,
252
+ y: bounds.y + spec.at.v * bounds.height
253
+ };
254
+ const flat = (poly === null ? null : rayHit(poly, { x: cx, y: cy }, anchored)) ?? anchored;
255
+ const normal = spec.normal === void 0 ? normalOf(spec.at) : spec.normal;
256
+ if (rotation === 0) {
257
+ return { id: spec.id, nodeId: node.id, point: flat, normal, ...typeOf(spec) };
258
+ }
259
+ return {
260
+ id: spec.id,
261
+ nodeId: node.id,
262
+ point: rotatePoint(flat.x, flat.y, cx, cy, rotation),
263
+ // A direction rotates about the origin, not about the node's center.
264
+ normal: normal === null ? null : rotatePoint(normal.x, normal.y, 0, 0, rotation),
265
+ ...typeOf(spec)
266
+ };
267
+ });
268
+ }
269
+ function portOf(node, pose, portId, opts = {}) {
270
+ return portsOf(node, pose, opts).find((p) => p.id === portId);
271
+ }
272
+ function typeOf(spec) {
273
+ return spec.type === void 0 ? {} : { type: spec.type };
274
+ }
275
+
276
+ // src/body.ts
277
+ var DEFAULT_PADDING = 8;
278
+ var DEFAULT_GAP = 4;
279
+ var FALLBACK_LINE = 16;
280
+ function canvasMeasure(ctx) {
281
+ return (text, style) => {
282
+ const size = style.fontSize ?? FALLBACK_LINE;
283
+ ctx.font = `${style.bold === true ? "bold " : ""}${size}px ${style.fontFamily ?? "sans-serif"}`;
284
+ return { width: ctx.measureText(text).width, height: Math.ceil(size * 1.2) };
285
+ };
286
+ }
287
+ function measureRow(row, measure) {
288
+ const text = (s, style) => measure === void 0 ? { width: s.length * ((style?.fontSize ?? FALLBACK_LINE) * 0.6), height: FALLBACK_LINE } : measure(s, style ?? {});
289
+ switch (row.kind) {
290
+ case "label":
291
+ return text(row.text, row.style);
292
+ case "field": {
293
+ const l = text(row.label, row.style);
294
+ const v = text(row.value, row.style);
295
+ return { width: l.width + DEFAULT_GAP * 2 + v.width, height: Math.max(l.height, v.height) };
296
+ }
297
+ case "ports": {
298
+ const side = (ports) => (ports ?? []).reduce((w, p) => Math.max(w, p.label === void 0 ? 0 : text(p.label).width), 0);
299
+ const rows = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);
300
+ return {
301
+ width: side(row.left) + DEFAULT_GAP * 2 + side(row.right),
302
+ height: row.height ?? rows * FALLBACK_LINE
303
+ };
304
+ }
305
+ case "slot":
306
+ return { width: 0, height: row.height };
307
+ }
308
+ }
309
+ function measureBody(spec, measure) {
310
+ const padding = spec.padding ?? DEFAULT_PADDING;
311
+ const gap = spec.gap ?? DEFAULT_GAP;
312
+ let width = 0;
313
+ let height = 0;
314
+ for (const [i, row] of spec.rows.entries()) {
315
+ const m = measureRow(row, measure);
316
+ width = Math.max(width, m.width);
317
+ height += m.height + (i > 0 ? gap : 0);
318
+ }
319
+ const box = boxForContent(spec.outline, {
320
+ width: width + padding * 2,
321
+ height: height + padding * 2
322
+ });
323
+ return { minWidth: box.width, minHeight: box.height };
324
+ }
325
+ function sizeToBody(pose, floor) {
326
+ const width = Math.max(pose.width, floor.minWidth);
327
+ const height = Math.max(pose.height, floor.minHeight);
328
+ if (width === pose.width && height === pose.height) return pose;
329
+ return { ...pose, width, height };
330
+ }
331
+ function layoutBody(spec, bounds, measure) {
332
+ const padding = spec.padding ?? DEFAULT_PADDING;
333
+ const gap = spec.gap ?? DEFAULT_GAP;
334
+ const inner = contentBox(spec.outline, bounds);
335
+ const width = Math.max(inner.width - padding * 2, 0);
336
+ let y = inner.y + padding;
337
+ return spec.rows.map((row, index) => {
338
+ const h = measureRow(row, measure).height;
339
+ const box = { row, index, x: inner.x + padding, y, width, height: h };
340
+ y += h + gap;
341
+ return box;
342
+ });
343
+ }
344
+ function layoutRowPorts(row, box, measure) {
345
+ const width = (label) => label === void 0 ? 0 : measureRow({ kind: "label", text: label }, measure).width;
346
+ const slots = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);
347
+ const slotHeight = box.height / slots;
348
+ const out = [];
349
+ const side = (ports, which) => {
350
+ for (const [index, port] of (ports ?? []).entries()) {
351
+ const w = width(port.label);
352
+ out.push({
353
+ port,
354
+ side: which,
355
+ index,
356
+ x: which === "left" ? box.x : box.x + box.width - w,
357
+ y: box.y + index * slotHeight,
358
+ width: w,
359
+ height: slotHeight
360
+ });
361
+ }
362
+ };
363
+ side(row.left, "left");
364
+ side(row.right, "right");
365
+ return out;
366
+ }
367
+ function bodyTrait(spec, bounds, measure) {
368
+ const outline = spec.outline;
369
+ const compass = [
370
+ { id: "n", at: COMPASS.n },
371
+ { id: "e", at: COMPASS.e },
372
+ { id: "s", at: COMPASS.s },
373
+ { id: "w", at: COMPASS.w }
374
+ ];
375
+ if (bounds.height <= 0) return { outline, ports: compass };
376
+ const rowPorts = [];
377
+ let hasLeft = false;
378
+ let hasRight = false;
379
+ for (const box of layoutBody(spec, bounds, measure)) {
380
+ if (box.row.kind !== "ports") continue;
381
+ for (const pb of layoutRowPorts(box.row, box, measure)) {
382
+ if (pb.side === "left") hasLeft = true;
383
+ else hasRight = true;
384
+ const v = (pb.y + pb.height / 2 - bounds.y) / bounds.height;
385
+ rowPorts.push(withType(
386
+ { id: pb.port.id, at: { u: pb.side === "left" ? 0 : 1, v } },
387
+ pb.port.type
388
+ ));
389
+ }
390
+ }
391
+ const kept = compass.filter((p) => !(p.id === "w" && hasLeft) && !(p.id === "e" && hasRight));
392
+ return { outline, ports: [...kept, ...rowPorts] };
393
+ }
394
+ function withType(spec, type) {
395
+ return type === void 0 ? spec : { ...spec, type };
396
+ }
397
+ function bodyOutline(spec, bounds) {
398
+ return outlinePath(spec.outline, bounds);
399
+ }
400
+ function buildBody(spec, at, opts) {
401
+ const pose = sizeToBody(at, measureBody(spec, opts.measure));
402
+ const specs = [{
403
+ kind: "container",
404
+ layer: opts.layer,
405
+ pose,
406
+ data: opts.body(bodyTrait(spec, pose, opts.measure), pose),
407
+ ...opts.id === void 0 ? {} : { id: opts.id }
408
+ }];
409
+ const leaf = (box, data) => {
410
+ specs.push({
411
+ kind: "leaf",
412
+ layer: opts.layer,
413
+ pose: { ...pose, x: box.x, y: box.y, width: box.width, height: box.height },
414
+ data,
415
+ pickable: false,
416
+ ...opts.id === void 0 ? {} : { parent: opts.id }
417
+ });
418
+ };
419
+ const portLabel = opts.portLabel;
420
+ for (const box of layoutBody(spec, pose, opts.measure)) {
421
+ const data = opts.row(rowText(box.row), box);
422
+ if (data !== null) leaf(box, data);
423
+ if (portLabel === void 0 || box.row.kind !== "ports") continue;
424
+ for (const pb of layoutRowPorts(box.row, box, opts.measure)) {
425
+ if (pb.port.label === void 0) continue;
426
+ const labelData = portLabel(pb.port.label, pb);
427
+ if (labelData !== null) leaf(pb, labelData);
428
+ }
429
+ }
430
+ return { pose, specs };
431
+ }
432
+ function rowText(row) {
433
+ if (row.kind === "label") return row.text;
434
+ if (row.kind === "field") return `${row.label}: ${row.value}`;
435
+ return "";
436
+ }
437
+
438
+ // src/layout.ts
439
+ var DEFAULT_NODE_GAP = 48;
440
+ var DEFAULT_RANK_GAP = 96;
441
+ var DEFAULT_TOLERANCE = 1e-6;
442
+ function axesFor(direction = "down") {
443
+ switch (direction) {
444
+ case "up":
445
+ return { rank: "y", cross: "x", sign: -1 };
446
+ case "right":
447
+ return { rank: "x", cross: "y", sign: 1 };
448
+ case "left":
449
+ return { rank: "x", cross: "y", sign: -1 };
450
+ default:
451
+ return { rank: "y", cross: "x", sign: 1 };
452
+ }
453
+ }
454
+ function extent(bounds, axis) {
455
+ return axis === "x" ? bounds.width : bounds.height;
456
+ }
457
+ function center(bounds, axis) {
458
+ return axis === "x" ? bounds.x + bounds.width / 2 : bounds.y + bounds.height / 2;
459
+ }
460
+ function pinnedSet(graph, opts = {}) {
461
+ const pinned = new Set(opts.pin ?? []);
462
+ for (const node of graph.nodes) {
463
+ if (node.pinned) pinned.add(node.id);
464
+ }
465
+ return pinned;
466
+ }
467
+ function settle(graph, slots, opts = {}) {
468
+ const axes = axesFor(opts.direction);
469
+ const pinned = pinnedSet(graph, opts);
470
+ const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE;
471
+ const placed = /* @__PURE__ */ new Map();
472
+ for (const node of graph.nodes) {
473
+ const slot = slots.get(node.id);
474
+ if (slot === void 0) continue;
475
+ const along = axes.sign === 1 ? slot.rank : -(slot.rank + extent(node.bounds, axes.rank));
476
+ placed.set(
477
+ node.id,
478
+ axes.rank === "y" ? { x: slot.cross, y: along } : { x: along, y: slot.cross }
479
+ );
480
+ }
481
+ return translated(graph, placed, pinned, tolerance);
482
+ }
483
+ function translated(graph, placed, pinned, tolerance = DEFAULT_TOLERANCE) {
484
+ const anchor = anchorDelta(graph, placed, pinned);
485
+ const out = /* @__PURE__ */ new Map();
486
+ for (const node of graph.nodes) {
487
+ const at = placed.get(node.id);
488
+ if (at === void 0 || pinned.has(node.id)) continue;
489
+ const x = at.x + anchor.x;
490
+ const y = at.y + anchor.y;
491
+ if (Math.abs(x - node.bounds.x) <= tolerance && Math.abs(y - node.bounds.y) <= tolerance) {
492
+ continue;
493
+ }
494
+ out.set(node.id, { x, y });
495
+ }
496
+ return out;
497
+ }
498
+ function anchorDelta(graph, placed, pinned) {
499
+ for (const node of graph.nodes) {
500
+ if (!pinned.has(node.id)) continue;
501
+ const at = placed.get(node.id);
502
+ if (at !== void 0) return { x: node.bounds.x - at.x, y: node.bounds.y - at.y };
503
+ }
504
+ let minCurX = Infinity;
505
+ let minCurY = Infinity;
506
+ let minNewX = Infinity;
507
+ let minNewY = Infinity;
508
+ for (const node of graph.nodes) {
509
+ const at = placed.get(node.id);
510
+ if (at === void 0) continue;
511
+ minCurX = Math.min(minCurX, node.bounds.x);
512
+ minCurY = Math.min(minCurY, node.bounds.y);
513
+ minNewX = Math.min(minNewX, at.x);
514
+ minNewY = Math.min(minNewY, at.y);
515
+ }
516
+ if (!Number.isFinite(minCurX)) return { x: 0, y: 0 };
517
+ return { x: minCurX - minNewX, y: minCurY - minNewY };
518
+ }
519
+ function packAcross(nodes, axis, gap) {
520
+ const at = /* @__PURE__ */ new Map();
521
+ let cursor = 0;
522
+ for (const node of nodes) {
523
+ at.set(node.id, cursor);
524
+ cursor += extent(node.bounds, axis) + gap;
525
+ }
526
+ return { at, span: nodes.length === 0 ? 0 : cursor - gap };
527
+ }
528
+ function seededOrder(nodes, axis, indexOf) {
529
+ return [...nodes].sort((a, b) => {
530
+ const d = center(a.bounds, axis) - center(b.bounds, axis);
531
+ return d !== 0 ? d : indexOf(a.id) - indexOf(b.id);
532
+ });
533
+ }
534
+ function graphOrder(graph) {
535
+ const index = /* @__PURE__ */ new Map();
536
+ graph.nodes.forEach((node, i) => index.set(node.id, i));
537
+ return (id) => index.get(id) ?? Number.MAX_SAFE_INTEGER;
538
+ }
539
+ var DEFAULTS = {
540
+ iterations: 300,
541
+ linkDistance: 160,
542
+ linkStrength: 0.35,
543
+ charge: -3e3,
544
+ gravity: 0.02,
545
+ padding: 24
546
+ };
547
+ var GOLDEN = Math.PI * (3 - Math.sqrt(5));
548
+ var NUDGE = 0.5;
549
+ function charge(bodies, strength) {
550
+ return (alpha) => {
551
+ for (let i = 0; i < bodies.length; i++) {
552
+ const a = bodies[i];
553
+ for (let j = i + 1; j < bodies.length; j++) {
554
+ const b = bodies[j];
555
+ const dx = b.x - a.x;
556
+ const dy = b.y - a.y;
557
+ const d2 = dx * dx + dy * dy;
558
+ if (d2 === 0) continue;
559
+ const w = strength * alpha / d2;
560
+ a.vx += dx * w;
561
+ a.vy += dy * w;
562
+ b.vx -= dx * w;
563
+ b.vy -= dy * w;
564
+ }
565
+ }
566
+ };
567
+ }
568
+ function links(bodies, graph, distance, strength) {
569
+ return (alpha) => {
570
+ for (const edge of graph.edges) {
571
+ const a = bodies.get(edge.from);
572
+ const b = bodies.get(edge.to);
573
+ if (a === void 0 || b === void 0 || a === b) continue;
574
+ const dx = b.x - a.x;
575
+ const dy = b.y - a.y;
576
+ const d = Math.hypot(dx, dy);
577
+ if (d === 0) continue;
578
+ const pull = (d - distance) / d * alpha * strength;
579
+ a.vx += dx * pull;
580
+ a.vy += dy * pull;
581
+ b.vx -= dx * pull;
582
+ b.vy -= dy * pull;
583
+ }
584
+ };
585
+ }
586
+ function separateBoxes(bodies, padding) {
587
+ return () => {
588
+ for (let i = 0; i < bodies.length; i++) {
589
+ const a = bodies[i];
590
+ for (let j = i + 1; j < bodies.length; j++) {
591
+ const b = bodies[j];
592
+ const dx = b.x - a.x;
593
+ const dy = b.y - a.y;
594
+ const gapX = a.hw + b.hw + padding - Math.abs(dx);
595
+ const gapY = a.hh + b.hh + padding - Math.abs(dy);
596
+ if (gapX <= 0 || gapY <= 0) continue;
597
+ if (gapX < gapY) {
598
+ const push = (Math.sign(dx) || 1) * gapX * 0.5;
599
+ a.vx -= push;
600
+ b.vx += push;
601
+ } else {
602
+ const push = (Math.sign(dy) || 1) * gapY * 0.5;
603
+ a.vy -= push;
604
+ b.vy += push;
605
+ }
606
+ }
607
+ }
608
+ };
609
+ }
610
+ function gravity(bodies, at, strength) {
611
+ return (alpha) => {
612
+ for (const body of bodies) {
613
+ body.vx += (at.x - body.x) * strength * alpha;
614
+ body.vy += (at.y - body.y) * strength * alpha;
615
+ }
616
+ };
617
+ }
618
+ function forceRelaxation(graph, opts = {}) {
619
+ const {
620
+ linkDistance = DEFAULTS.linkDistance,
621
+ linkStrength = DEFAULTS.linkStrength,
622
+ charge: chargeStrength = DEFAULTS.charge,
623
+ gravity: gravityStrength = DEFAULTS.gravity,
624
+ padding = DEFAULTS.padding
625
+ } = opts;
626
+ const pinned = pinnedSet(graph, opts);
627
+ const bodies = graph.nodes.map((node) => {
628
+ const body = {
629
+ id: node.id,
630
+ x: center(node.bounds, "x"),
631
+ y: center(node.bounds, "y"),
632
+ hw: node.bounds.width / 2,
633
+ hh: node.bounds.height / 2
634
+ };
635
+ if (pinned.has(node.id)) {
636
+ body.fx = body.x;
637
+ body.fy = body.y;
638
+ }
639
+ return body;
640
+ });
641
+ separate(bodies);
642
+ const byId = new Map(bodies.map((b) => [b.id, b]));
643
+ const centroid = {
644
+ x: bodies.reduce((sum, b) => sum + b.x, 0) / bodies.length,
645
+ y: bodies.reduce((sum, b) => sum + b.y, 0) / bodies.length
646
+ };
647
+ const sim = createSimulation({
648
+ nodes: bodies,
649
+ forces: [
650
+ charge(bodies, chargeStrength),
651
+ links(byId, graph, linkDistance, linkStrength),
652
+ gravity(bodies, centroid, gravityStrength),
653
+ separateBoxes(bodies, padding)
654
+ ]
655
+ });
656
+ return {
657
+ bodies,
658
+ byId,
659
+ pinned,
660
+ sim,
661
+ placed() {
662
+ const placed = /* @__PURE__ */ new Map();
663
+ for (const node of graph.nodes) {
664
+ const body = byId.get(node.id);
665
+ placed.set(node.id, {
666
+ x: body.x - node.bounds.width / 2,
667
+ y: body.y - node.bounds.height / 2
668
+ });
669
+ }
670
+ return placed;
671
+ }
672
+ };
673
+ }
674
+ var force = (graph, opts = {}) => {
675
+ if (graph.nodes.length === 0) return /* @__PURE__ */ new Map();
676
+ const relaxation = forceRelaxation(graph, opts);
677
+ relaxation.sim.tick(opts.iterations ?? DEFAULTS.iterations);
678
+ return translated(graph, relaxation.placed(), relaxation.pinned, opts.tolerance);
679
+ };
680
+ function separate(bodies) {
681
+ const seen = /* @__PURE__ */ new Map();
682
+ bodies.forEach((body, i) => {
683
+ const key = `${body.x},${body.y}`;
684
+ const nth = seen.get(key) ?? 0;
685
+ seen.set(key, nth + 1);
686
+ if (nth === 0 || body.fx != null || body.fy != null) return;
687
+ const angle = GOLDEN * i;
688
+ const radius = NUDGE * nth;
689
+ body.x += Math.cos(angle) * radius;
690
+ body.y += Math.sin(angle) * radius;
691
+ });
692
+ }
693
+
694
+ // src/layered.ts
695
+ function backEdges(graph) {
696
+ const back = /* @__PURE__ */ new Set();
697
+ const done = /* @__PURE__ */ new Set();
698
+ const onStack = /* @__PURE__ */ new Set();
699
+ const walk = (id) => {
700
+ if (done.has(id)) return;
701
+ onStack.add(id);
702
+ for (const edge of graph.outgoing(id)) {
703
+ if (onStack.has(edge.to)) back.add(edge.id);
704
+ else walk(edge.to);
705
+ }
706
+ onStack.delete(id);
707
+ done.add(id);
708
+ };
709
+ for (const node of graph.nodes) walk(node.id);
710
+ return back;
711
+ }
712
+ function ranksOf(graph, back) {
713
+ const ranks = /* @__PURE__ */ new Map();
714
+ const resolving = /* @__PURE__ */ new Set();
715
+ const rankOf = (id) => {
716
+ const known = ranks.get(id);
717
+ if (known !== void 0) return known;
718
+ if (resolving.has(id)) return 0;
719
+ resolving.add(id);
720
+ let rank = 0;
721
+ for (const edge of graph.incoming(id)) {
722
+ if (back.has(edge.id)) continue;
723
+ rank = Math.max(rank, rankOf(edge.from) + 1);
724
+ }
725
+ resolving.delete(id);
726
+ ranks.set(id, rank);
727
+ return rank;
728
+ };
729
+ for (const node of graph.nodes) rankOf(node.id);
730
+ return ranks;
731
+ }
732
+ var layered = (graph, opts = {}) => {
733
+ const axes = axesFor(opts.direction);
734
+ const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;
735
+ const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;
736
+ const order = graphOrder(graph);
737
+ const ranks = ranksOf(graph, backEdges(graph));
738
+ const byRank = /* @__PURE__ */ new Map();
739
+ for (const node of graph.nodes) {
740
+ const rank = ranks.get(node.id) ?? 0;
741
+ const list = byRank.get(rank);
742
+ if (list === void 0) byRank.set(rank, [node]);
743
+ else list.push(node);
744
+ }
745
+ const rows = [...byRank.keys()].sort((a, b) => a - b);
746
+ const packed = /* @__PURE__ */ new Map();
747
+ let widest = 0;
748
+ for (const rank of rows) {
749
+ const row = seededOrder(byRank.get(rank), axes.cross, order);
750
+ const p = packAcross(row, axes.cross, nodeGap);
751
+ packed.set(rank, p);
752
+ widest = Math.max(widest, p.span);
753
+ }
754
+ const slots = /* @__PURE__ */ new Map();
755
+ let along = 0;
756
+ for (const rank of rows) {
757
+ const row = byRank.get(rank);
758
+ const p = packed.get(rank);
759
+ const indent = (widest - p.span) / 2;
760
+ const depth = Math.max(0, ...row.map((n) => extent(n.bounds, axes.rank)));
761
+ for (const node of row) {
762
+ slots.set(node.id, {
763
+ cross: indent + p.at.get(node.id),
764
+ // Centered in its rank's band, so a tall node does not push its
765
+ // neighbors' edges off the line they read along.
766
+ rank: along + (depth - extent(node.bounds, axes.rank)) / 2
767
+ });
768
+ }
769
+ along += depth + rankGap;
770
+ }
771
+ return settle(graph, slots, opts);
772
+ };
773
+
774
+ // src/tree.ts
775
+ function forestOf(graph, crossAxis) {
776
+ const order = graphOrder(graph);
777
+ const children = /* @__PURE__ */ new Map();
778
+ const depth = /* @__PURE__ */ new Map();
779
+ const roots = [];
780
+ const claim = (node, at) => {
781
+ depth.set(node.id, at);
782
+ const kids = [];
783
+ for (const edge of graph.outgoing(node.id)) {
784
+ if (edge.to === node.id || depth.has(edge.to)) continue;
785
+ const child = graph.node(edge.to);
786
+ if (child === void 0) continue;
787
+ depth.set(child.id, at + 1);
788
+ kids.push(child);
789
+ }
790
+ const ordered = seededOrder(kids, crossAxis, order);
791
+ children.set(node.id, ordered);
792
+ for (const child of ordered) claim(child, at + 1);
793
+ };
794
+ const rootish = graph.nodes.filter((node) => graph.incoming(node.id).every((edge) => edge.from === node.id));
795
+ for (const node of seededOrder(rootish, crossAxis, order)) {
796
+ if (depth.has(node.id)) continue;
797
+ roots.push(node);
798
+ claim(node, 0);
799
+ }
800
+ for (const node of graph.nodes) {
801
+ if (depth.has(node.id)) continue;
802
+ roots.push(node);
803
+ claim(node, 0);
804
+ }
805
+ return { roots, children, depth };
806
+ }
807
+ var tree = (graph, opts = {}) => {
808
+ const axes = axesFor(opts.direction);
809
+ const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;
810
+ const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;
811
+ const { roots, children, depth } = forestOf(graph, axes.cross);
812
+ const bands = /* @__PURE__ */ new Map();
813
+ for (const node of graph.nodes) {
814
+ const at = depth.get(node.id) ?? 0;
815
+ bands.set(at, Math.max(bands.get(at) ?? 0, extent(node.bounds, axes.rank)));
816
+ }
817
+ const bandStart = /* @__PURE__ */ new Map();
818
+ let along = 0;
819
+ for (const at of [...bands.keys()].sort((a, b) => a - b)) {
820
+ bandStart.set(at, along);
821
+ along += bands.get(at) + rankGap;
822
+ }
823
+ const slots = /* @__PURE__ */ new Map();
824
+ const measured = /* @__PURE__ */ new Map();
825
+ const measure = (node) => {
826
+ const known = measured.get(node.id);
827
+ if (known !== void 0) return known;
828
+ const kids = children.get(node.id) ?? [];
829
+ let width = 0;
830
+ for (const child of kids) width += measure(child);
831
+ if (kids.length > 0) width += nodeGap * (kids.length - 1);
832
+ const block = Math.max(extent(node.bounds, axes.cross), width);
833
+ measured.set(node.id, block);
834
+ return block;
835
+ };
836
+ const place = (node, from) => {
837
+ const kids = children.get(node.id) ?? [];
838
+ const block = measure(node);
839
+ const width = kids.reduce((sum, k) => sum + measure(k), 0) + Math.max(0, kids.length - 1) * nodeGap;
840
+ let cursor2 = from + (block - width) / 2;
841
+ for (const child of kids) {
842
+ place(child, cursor2);
843
+ cursor2 += measure(child) + nodeGap;
844
+ }
845
+ const own = extent(node.bounds, axes.cross);
846
+ const at = depth.get(node.id) ?? 0;
847
+ slots.set(node.id, {
848
+ cross: from + (block - own) / 2,
849
+ rank: bandStart.get(at) + (bands.get(at) - extent(node.bounds, axes.rank)) / 2
850
+ });
851
+ };
852
+ let cursor = 0;
853
+ for (const root of roots) {
854
+ place(root, cursor);
855
+ cursor += measure(root) + nodeGap;
856
+ }
857
+ return settle(graph, slots, opts);
858
+ };
859
+
860
+ export { COMPASS, DEFAULT_NODE_GAP, DEFAULT_PORTS, DEFAULT_RANK_GAP, DIAGRAM_TRAIT_KEY, axesFor, backEdges, bodyOutline, bodyTrait, boxForContent, buildBody, canvasMeasure, center, contentBox, createDiagramNodes, dataKeyReader, diagramNodeOf, extent, force, forceRelaxation, forestOf, graphOrder, isPinned, layered, layoutBody, layoutRowPorts, measureBody, outlinePath, outlinePolyline, packAcross, pinnedSet, portOf, portsOf, portsOnOutline, ranksOf, rayHit, seededOrder, settle, sizeToBody, translated, tree };
861
+ //# sourceMappingURL=chunk-M34HI5RG.js.map
862
+ //# sourceMappingURL=chunk-M34HI5RG.js.map