@grethel-labs/excaliplant 0.1.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.
@@ -0,0 +1,517 @@
1
+ /**
2
+ * @module layout
3
+ *
4
+ * Layout chooses positions for every shape and routes every edge.
5
+ * Component / use-case / deployment diagrams flow through ELK
6
+ * (`elkjs`) using the `layered` algorithm with orthogonal edge
7
+ * routing. After ELK returns we chamfer 90° corners so the result
8
+ * matches Excalidraw's diagonal-corner aesthetic.
9
+ *
10
+ * Sequence diagrams skip ELK entirely — their layout is strictly
11
+ * tabular (lifelines on the X axis, time on the Y axis), so a
12
+ * deterministic ~90-line algorithm produces better, more compact
13
+ * results than a force-directed solver could.
14
+ */
15
+
16
+ // ELK-based layout & routing.
17
+ //
18
+ // Replaces the old multi-step pipeline (legacy/layout/step{1..7}*.mjs).
19
+ // Strategy:
20
+ // 1. Pre-size every Box from its text content (legacy sizing.mjs is
21
+ // reused — text geometry has not changed).
22
+ // 2. Hand the entire Diagram to ELK as a hierarchical graph:
23
+ // graph
24
+ // ├─ Plane (compound node, layoutOptions: layered)
25
+ // │ ├─ Box (leaf) (direct boxes)
26
+ // │ ├─ Subplane (compound node)
27
+ // │ │ └─ Box (leaf)
28
+ // │ └─ Box (leaf)
29
+ // └─ Plane …
30
+ // All connections become edges between leaf nodes; edges that span
31
+ // planes are routed through the common ancestor with
32
+ // `hierarchyHandling: INCLUDE_CHILDREN`.
33
+ // 3. Walk the ELK result, write absolute geometry back into the
34
+ // Diagram model: Plane/Subplane/Box `x,y,width,height`; Connection
35
+ // `path[]`, `fromSide`, `toSide`.
36
+ //
37
+ // The output stays inside the existing Excalidraw renderer's contract
38
+ // (orthogonal polylines, no wobble, planes/subplanes/boxes are
39
+ // rectangles, etc.).
40
+
41
+ import ELK from "elkjs/lib/elk.bundled.js";
42
+ import { Box, Plane, Subplane, SequenceDiagram } from "../model/diagram.mjs";
43
+ import { sizeDiagram, SIZING } from "./sizing.mjs";
44
+ import { layoutSequenceDiagram } from "./sequence_layout.mjs";
45
+
46
+ const elk = new ELK();
47
+
48
+ // ELK layout options. These are tuned for many-node, many-edge,
49
+ // hierarchical compound layouts with orthogonal edge routing — i.e.
50
+ // what we have. See https://eclipse.dev/elk/reference/options.html
51
+ const ROOT_OPTIONS = {
52
+ "elk.algorithm": "layered",
53
+ "elk.direction": "RIGHT",
54
+ "elk.hierarchyHandling": "INCLUDE_CHILDREN",
55
+ "elk.edgeRouting": "ORTHOGONAL",
56
+ "elk.layered.crossingMinimization.strategy": "LAYER_SWEEP",
57
+ "elk.layered.crossingMinimization.semiInteractive": "true",
58
+ "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX",
59
+ "elk.layered.nodePlacement.bk.fixedAlignment": "BALANCED",
60
+ "elk.layered.spacing.nodeNodeBetweenLayers": "60",
61
+ "elk.spacing.nodeNode": "30",
62
+ "elk.spacing.edgeNode": "20",
63
+ "elk.spacing.edgeEdge": "12",
64
+ "elk.spacing.edgeNodeBetweenLayers": "20",
65
+ "elk.spacing.edgeEdgeBetweenLayers": "12",
66
+ "elk.padding": "[top=24,left=24,bottom=24,right=24]",
67
+ };
68
+
69
+ const PLANE_OPTIONS = {
70
+ "elk.algorithm": "layered",
71
+ "elk.direction": "RIGHT",
72
+ "elk.padding": `[top=${SIZING.planeTitleHeight + SIZING.planePaddingY},left=${SIZING.planePaddingX},bottom=${SIZING.planePaddingY},right=${SIZING.planePaddingX}]`,
73
+ "elk.layered.spacing.nodeNodeBetweenLayers": "50",
74
+ "elk.spacing.nodeNode": "24",
75
+ };
76
+
77
+ const SUBPLANE_OPTIONS = {
78
+ "elk.algorithm": "layered",
79
+ "elk.direction": "RIGHT",
80
+ "elk.padding": `[top=${SIZING.subplaneTitleHeight + SIZING.subplanePaddingY},left=${SIZING.subplanePaddingX},bottom=${SIZING.subplanePaddingY},right=${SIZING.subplanePaddingX}]`,
81
+ "elk.layered.spacing.nodeNodeBetweenLayers": "40",
82
+ "elk.spacing.nodeNode": "16",
83
+ };
84
+
85
+ /**
86
+ * Lay out a `Diagram` (or `SequenceDiagram`) in place: assigns
87
+ * absolute `x`/`y` coordinates and edge waypoints to every shape.
88
+ *
89
+ * Component / use-case / deployment diagrams are routed via ELK
90
+ * (`elkjs`, layered algorithm + orthogonal routing). Sequence
91
+ * diagrams use a deterministic tabular layout.
92
+ *
93
+ * @param {import("../model/diagram.mjs").Diagram
94
+ * | import("../model/diagram.mjs").SequenceDiagram} diagram
95
+ * The diagram to mutate.
96
+ * @returns {Promise<void>}
97
+ */
98
+ export async function layoutDiagram(diagram) {
99
+ // Sequence diagrams use a separate, deterministic tabular layout.
100
+ if (diagram instanceof SequenceDiagram) {
101
+ return layoutSequenceDiagram(diagram);
102
+ }
103
+
104
+ // Step 1: text-based box sizing.
105
+ sizeDiagram(diagram);
106
+
107
+ // Step 2: build the ELK graph.
108
+ const graph = buildElkGraph(diagram);
109
+
110
+ // Step 3: run ELK.
111
+ const result = await elk.layout(graph);
112
+
113
+ // Step 4: write geometry back.
114
+ applyElkResult(diagram, result);
115
+
116
+ // Step 5: chamfer 90° corners where it doesn't introduce conflicts.
117
+ chamferAllCorners(diagram);
118
+ return diagram;
119
+ }
120
+
121
+ function buildElkGraph(diagram) {
122
+ const root = {
123
+ id: "__root",
124
+ layoutOptions: ROOT_OPTIONS,
125
+ children: [],
126
+ edges: [],
127
+ };
128
+
129
+ const nodeById = new Map(); // box.id / plane.id / subplane.id -> elk node ref
130
+ const containerOfBox = new Map(); // box.id -> elk node that holds the box
131
+ const planeOfBox = new Map(); // box.id -> plane elk node
132
+ const subplaneOfBox = new Map(); // box.id -> subplane elk node (or null)
133
+
134
+ for (const plane of diagram.planes) {
135
+ const planeNode = {
136
+ id: `plane:${plane.id}`,
137
+ layoutOptions: { ...PLANE_OPTIONS },
138
+ children: [],
139
+ edges: [],
140
+ labels: [{ text: plane.title || plane.id }],
141
+ };
142
+ root.children.push(planeNode);
143
+ nodeById.set(plane.id, planeNode);
144
+
145
+ for (const child of plane.children) {
146
+ if (child instanceof Subplane) {
147
+ const subNode = {
148
+ id: `sub:${child.id}`,
149
+ layoutOptions: { ...SUBPLANE_OPTIONS },
150
+ children: [],
151
+ edges: [],
152
+ labels: [{ text: child.title || child.id }],
153
+ };
154
+ planeNode.children.push(subNode);
155
+ nodeById.set(child.id, subNode);
156
+ for (const box of child.boxes) {
157
+ const boxNode = boxToElkNode(box);
158
+ subNode.children.push(boxNode);
159
+ nodeById.set(box.id, boxNode);
160
+ containerOfBox.set(box.id, subNode);
161
+ planeOfBox.set(box.id, planeNode);
162
+ subplaneOfBox.set(box.id, subNode);
163
+ }
164
+ } else if (child instanceof Box) {
165
+ const boxNode = boxToElkNode(child);
166
+ planeNode.children.push(boxNode);
167
+ nodeById.set(child.id, boxNode);
168
+ containerOfBox.set(child.id, planeNode);
169
+ planeOfBox.set(child.id, planeNode);
170
+ subplaneOfBox.set(child.id, null);
171
+ }
172
+ }
173
+ }
174
+
175
+ // Place each edge on the lowest common ancestor of its endpoints so
176
+ // ELK reports the edge coordinates in that ancestor's local frame —
177
+ // and applyElkResult can find them with the correct offset.
178
+ for (const conn of diagram.connections) {
179
+ const fromSub = subplaneOfBox.get(conn.from.id);
180
+ const toSub = subplaneOfBox.get(conn.to.id);
181
+ const fromPlane = planeOfBox.get(conn.from.id);
182
+ const toPlane = planeOfBox.get(conn.to.id);
183
+ let host;
184
+ if (fromSub && fromSub === toSub) host = fromSub;
185
+ else if (fromPlane === toPlane) host = fromPlane;
186
+ else host = root;
187
+ host.edges.push({
188
+ id: conn.id,
189
+ sources: [`box:${conn.from.id}`],
190
+ targets: [`box:${conn.to.id}`],
191
+ });
192
+ }
193
+
194
+ return root;
195
+ }
196
+
197
+ function boxToElkNode(box) {
198
+ return {
199
+ id: `box:${box.id}`,
200
+ width: box.width,
201
+ height: box.height,
202
+ labels: [{ text: box.title || box.id }],
203
+ layoutOptions: {
204
+ "elk.portConstraints": "FREE",
205
+ },
206
+ };
207
+ }
208
+
209
+ function applyElkResult(diagram, root) {
210
+ // ELK gives positions relative to each parent. We need absolute
211
+ // coordinates for the Diagram model, so we walk the tree.
212
+ const absolute = new Map(); // node.id -> { x, y, width, height }
213
+
214
+ function walk(node, ox, oy) {
215
+ const ax = ox + (node.x || 0);
216
+ const ay = oy + (node.y || 0);
217
+ absolute.set(node.id, { x: ax, y: ay, width: node.width, height: node.height });
218
+ if (node.children) {
219
+ for (const child of node.children) walk(child, ax, ay);
220
+ }
221
+ }
222
+ walk(root, 0, 0);
223
+
224
+ for (const plane of diagram.planes) {
225
+ const r = absolute.get(`plane:${plane.id}`);
226
+ if (r) Object.assign(plane, { x: r.x, y: r.y, width: r.width, height: r.height });
227
+ for (const child of plane.children) {
228
+ if (child instanceof Subplane) {
229
+ const sr = absolute.get(`sub:${child.id}`);
230
+ if (sr) Object.assign(child, { x: sr.x, y: sr.y, width: sr.width, height: sr.height });
231
+ for (const box of child.boxes) {
232
+ const br = absolute.get(`box:${box.id}`);
233
+ if (br) Object.assign(box, { x: br.x, y: br.y, width: br.width, height: br.height });
234
+ }
235
+ } else if (child instanceof Box) {
236
+ const br = absolute.get(`box:${child.id}`);
237
+ if (br) Object.assign(child, { x: br.x, y: br.y, width: br.width, height: br.height });
238
+ }
239
+ }
240
+ }
241
+
242
+ // Edges: ELK places the routed edge under whichever container is the
243
+ // edge's parent (with INCLUDE_CHILDREN that's the root). Sections give
244
+ // start/end and bend points in the parent's local coordinate system.
245
+ // Collect all edges by id from the tree.
246
+ const edgesById = new Map();
247
+ function collectEdges(node, ox, oy) {
248
+ const ax = ox + (node.x || 0);
249
+ const ay = oy + (node.y || 0);
250
+ if (node.edges) {
251
+ for (const edge of node.edges) edgesById.set(edge.id, { edge, ox: ax, oy: ay });
252
+ }
253
+ if (node.children) for (const child of node.children) collectEdges(child, ax, ay);
254
+ }
255
+ collectEdges(root, 0, 0);
256
+
257
+ for (const conn of diagram.connections) {
258
+ const entry = edgesById.get(conn.id);
259
+ if (!entry) {
260
+ conn.path = [];
261
+ continue;
262
+ }
263
+ const { edge, ox, oy } = entry;
264
+ const sections = edge.sections || [];
265
+ const path = [];
266
+ for (let i = 0; i < sections.length; i++) {
267
+ const s = sections[i];
268
+ if (i === 0) path.push({ x: ox + s.startPoint.x, y: oy + s.startPoint.y });
269
+ if (s.bendPoints) {
270
+ for (const bp of s.bendPoints) path.push({ x: ox + bp.x, y: oy + bp.y });
271
+ }
272
+ path.push({ x: ox + s.endPoint.x, y: oy + s.endPoint.y });
273
+ }
274
+ conn.path = snapOrthogonal(dedupe(path));
275
+ // Best-effort fromSide / toSide from first/last segment direction.
276
+ [conn.fromSide, conn.toSide] = inferSides(conn);
277
+ }
278
+ }
279
+
280
+ // ELK can return slightly offset stub segments (e.g. y=197.5 → y=198)
281
+ // when a port lies on a fractional boundary. Snap each segment to be
282
+ // strictly horizontal / vertical so Excalidraw renders crisp arrows.
283
+ function snapOrthogonal(points) {
284
+ if (points.length < 2) return points;
285
+ const out = [{ x: Math.round(points[0].x), y: Math.round(points[0].y) }];
286
+ for (let i = 1; i < points.length; i++) {
287
+ const prev = out[out.length - 1];
288
+ let { x, y } = points[i];
289
+ x = Math.round(x);
290
+ y = Math.round(y);
291
+ const dx = Math.abs(x - prev.x);
292
+ const dy = Math.abs(y - prev.y);
293
+ if (dx >= dy) y = prev.y; // dominant horizontal
294
+ else x = prev.x; // dominant vertical
295
+ if (x === prev.x && y === prev.y) continue;
296
+ out.push({ x, y });
297
+ }
298
+ return out;
299
+ }
300
+
301
+ function dedupe(points) {
302
+ const out = [];
303
+ for (const p of points) {
304
+ const last = out[out.length - 1];
305
+ if (!last || Math.abs(last.x - p.x) > 0.5 || Math.abs(last.y - p.y) > 0.5) {
306
+ out.push(p);
307
+ }
308
+ }
309
+ return out;
310
+ }
311
+
312
+ function inferSides(conn) {
313
+ const path = conn.path;
314
+ if (!path || path.length < 2) return [null, null];
315
+ const first = path[0];
316
+ const second = path[1];
317
+ const last = path[path.length - 1];
318
+ const prev = path[path.length - 2];
319
+ const fromSide = sideOf(conn.from, first, second);
320
+ const toSide = sideOf(conn.to, last, prev);
321
+ return [fromSide, toSide];
322
+ }
323
+
324
+ function sideOf(box, endpoint, neighbour) {
325
+ // Decide which side of the box this endpoint is on. Prefer the
326
+ // direction toward the neighbour point: if neighbour is to the right
327
+ // of the endpoint, the edge leaves to the right, so the port is on
328
+ // the right side. Fall back to which box edge `endpoint` lies on.
329
+ if (neighbour) {
330
+ const dx = neighbour.x - endpoint.x;
331
+ const dy = neighbour.y - endpoint.y;
332
+ if (Math.abs(dx) > Math.abs(dy)) return dx > 0 ? "right" : "left";
333
+ if (Math.abs(dy) > 0) return dy > 0 ? "bottom" : "top";
334
+ }
335
+ const eps = 1.0;
336
+ if (Math.abs(endpoint.x - box.x) <= eps) return "left";
337
+ if (Math.abs(endpoint.x - (box.x + box.width)) <= eps) return "right";
338
+ if (Math.abs(endpoint.y - box.y) <= eps) return "top";
339
+ if (Math.abs(endpoint.y - (box.y + box.height)) <= eps) return "bottom";
340
+ return null;
341
+ }
342
+
343
+ // ---------------------------------------------------------------------------
344
+ // Chamfering
345
+ // ---------------------------------------------------------------------------
346
+ //
347
+ // Replace selected 90° corners by 45° diagonals. A corner (prev → v → next)
348
+ // is replaced by (prev → a → b → next) with `a` on the incoming and `b`
349
+ // on the outgoing segment, both at distance `c` from `v`. A chamfer is
350
+ // only applied when ALL of the following hold:
351
+ //
352
+ // 1. The corner is a real 90° turn (one neighbour horizontal, the
353
+ // other vertical).
354
+ // 2. Both neighbouring segments are at least 2·c long (so a/b lie
355
+ // strictly inside their segments and a follow-up corner does not
356
+ // overlap).
357
+ // 3. The new diagonal does not enter any box's interior.
358
+ // 4. The new diagonal does not properly intersect any orthogonal
359
+ // segment of any other connection (or any non-adjacent segment of
360
+ // this connection).
361
+ // 5. The new diagonal does not touch / cross / lie within 2 px of any
362
+ // already-accepted chamfer diagonal.
363
+ //
364
+ // Greedy: try c ∈ {12, 10, 8, 6, 4} in that order and accept the first
365
+ // candidate that satisfies all conditions.
366
+
367
+ const CHAMFER_SIZES = [12, 10, 8, 6, 4];
368
+ const DIAG_SAFETY = 2; // min distance to other diagonals
369
+ const BOX_PAD = 1; // shrink box rect when checking interior
370
+
371
+ function chamferAllCorners(diagram) {
372
+ const accepted = []; // [{a, b}]
373
+ const boxes = diagram.allBoxes();
374
+
375
+ // Pre-collect axis-aligned segments per connection so the conflict
376
+ // test can skip the two segments that are adjacent to the corner
377
+ // being chamfered (which are about to be shortened anyway).
378
+ const segsByConn = new Map();
379
+ for (const conn of diagram.connections) {
380
+ const segs = [];
381
+ for (let i = 0; i < (conn.path?.length ?? 0) - 1; i++) {
382
+ segs.push({ a: conn.path[i], b: conn.path[i + 1] });
383
+ }
384
+ segsByConn.set(conn.id, segs);
385
+ }
386
+
387
+ for (const conn of diagram.connections) {
388
+ const path = conn.path;
389
+ if (!path || path.length < 3) continue;
390
+ const out = [path[0]];
391
+ let segIndex = 0; // index into segsByConn (incoming segment of this corner)
392
+ for (let i = 1; i < path.length - 1; i++) {
393
+ const prev = out[out.length - 1];
394
+ const v = path[i];
395
+ const next = path[i + 1];
396
+ const inHoriz = Math.abs(prev.y - v.y) < 0.5 && Math.abs(prev.x - v.x) > 0.5;
397
+ const outHoriz = Math.abs(v.y - next.y) < 0.5 && Math.abs(v.x - next.x) > 0.5;
398
+ const inVert = Math.abs(prev.x - v.x) < 0.5 && Math.abs(prev.y - v.y) > 0.5;
399
+ const outVert = Math.abs(v.x - next.x) < 0.5 && Math.abs(v.y - next.y) > 0.5;
400
+ const isCorner = (inHoriz && outVert) || (inVert && outHoriz);
401
+ if (!isCorner) {
402
+ out.push(v);
403
+ segIndex++;
404
+ continue;
405
+ }
406
+ const inLen = Math.hypot(v.x - prev.x, v.y - prev.y);
407
+ const outLen = Math.hypot(next.x - v.x, next.y - v.y);
408
+
409
+ let chosen = null;
410
+ for (const c of CHAMFER_SIZES) {
411
+ if (c * 2 > inLen || c * 2 > outLen) continue;
412
+ const a = pointAtDist(v, prev, c);
413
+ const b = pointAtDist(v, next, c);
414
+ if (chamferConflicts(a, b, conn, segIndex, segsByConn, accepted, boxes)) continue;
415
+ chosen = { a, b };
416
+ break;
417
+ }
418
+ if (chosen) {
419
+ out.push(chosen.a, chosen.b);
420
+ accepted.push(chosen);
421
+ } else {
422
+ out.push(v);
423
+ }
424
+ segIndex++;
425
+ }
426
+ out.push(path[path.length - 1]);
427
+ conn.path = out;
428
+ }
429
+ }
430
+
431
+ function pointAtDist(from, toward, dist) {
432
+ const len = Math.hypot(toward.x - from.x, toward.y - from.y);
433
+ const t = dist / len;
434
+ return { x: from.x + (toward.x - from.x) * t, y: from.y + (toward.y - from.y) * t };
435
+ }
436
+
437
+ function chamferConflicts(a, b, conn, segIndex, segsByConn, accepted, boxes) {
438
+ // 3. Box interior: check both endpoints + a few sample points along
439
+ // the diagonal. Endpoints lie on existing orthogonal segments that
440
+ // were already box-clear, so this primarily protects against
441
+ // cutting through a box that sits in the corner pocket.
442
+ for (const box of boxes) {
443
+ if (segmentEntersBox(a, b, box)) return true;
444
+ }
445
+ // 4. Orthogonal segments. Skip the two segments adjacent to this
446
+ // corner (segIndex and segIndex+1) on this connection, since we
447
+ // are replacing them with shortened versions.
448
+ for (const [cid, segs] of segsByConn) {
449
+ for (let i = 0; i < segs.length; i++) {
450
+ if (cid === conn.id && (i === segIndex || i === segIndex + 1)) continue;
451
+ const s = segs[i];
452
+ if (properIntersect(a, b, s.a, s.b)) return true;
453
+ }
454
+ }
455
+ // 5. Other accepted diagonals: no crossing AND min distance.
456
+ for (const d of accepted) {
457
+ if (segmentsClose(a, b, d.a, d.b, DIAG_SAFETY)) return true;
458
+ }
459
+ return false;
460
+ }
461
+
462
+ function segmentEntersBox(a, b, box) {
463
+ const x0 = box.x + BOX_PAD;
464
+ const y0 = box.y + BOX_PAD;
465
+ const x1 = box.x + box.width - BOX_PAD;
466
+ const y1 = box.y + box.height - BOX_PAD;
467
+ // Reject if either endpoint is strictly inside.
468
+ if (a.x > x0 && a.x < x1 && a.y > y0 && a.y < y1) return true;
469
+ if (b.x > x0 && b.x < x1 && b.y > y0 && b.y < y1) return true;
470
+ // Test against the four box edges.
471
+ const corners = [
472
+ { x: x0, y: y0 }, { x: x1, y: y0 },
473
+ { x: x1, y: y1 }, { x: x0, y: y1 },
474
+ ];
475
+ for (let i = 0; i < 4; i++) {
476
+ if (properIntersect(a, b, corners[i], corners[(i + 1) % 4])) return true;
477
+ }
478
+ return false;
479
+ }
480
+
481
+ function properIntersect(p1, p2, p3, p4) {
482
+ const d = (p2.x - p1.x) * (p4.y - p3.y) - (p2.y - p1.y) * (p4.x - p3.x);
483
+ if (Math.abs(d) < 1e-9) return false;
484
+ const t = ((p3.x - p1.x) * (p4.y - p3.y) - (p3.y - p1.y) * (p4.x - p3.x)) / d;
485
+ const u = ((p3.x - p1.x) * (p2.y - p1.y) - (p3.y - p1.y) * (p2.x - p1.x)) / d;
486
+ const eps = 1e-3;
487
+ return t > eps && t < 1 - eps && u > eps && u < 1 - eps;
488
+ }
489
+
490
+ // True iff the two segments come within `tol` of each other anywhere.
491
+ function segmentsClose(a1, a2, b1, b2, tol) {
492
+ // Crossing → distance 0.
493
+ const d = (a2.x - a1.x) * (b2.y - b1.y) - (a2.y - a1.y) * (b2.x - b1.x);
494
+ if (Math.abs(d) > 1e-9) {
495
+ const t = ((b1.x - a1.x) * (b2.y - b1.y) - (b1.y - a1.y) * (b2.x - b1.x)) / d;
496
+ const u = ((b1.x - a1.x) * (a2.y - a1.y) - (b1.y - a1.y) * (a2.x - a1.x)) / d;
497
+ if (t >= 0 && t <= 1 && u >= 0 && u <= 1) return true;
498
+ }
499
+ // Otherwise: minimum endpoint→segment distance.
500
+ const dists = [
501
+ pointSegDist(a1, b1, b2),
502
+ pointSegDist(a2, b1, b2),
503
+ pointSegDist(b1, a1, a2),
504
+ pointSegDist(b2, a1, a2),
505
+ ];
506
+ return Math.min(...dists) < tol;
507
+ }
508
+
509
+ function pointSegDist(p, a, b) {
510
+ const dx = b.x - a.x;
511
+ const dy = b.y - a.y;
512
+ const len2 = dx * dx + dy * dy;
513
+ if (len2 < 1e-9) return Math.hypot(p.x - a.x, p.y - a.y);
514
+ let t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2;
515
+ t = Math.max(0, Math.min(1, t));
516
+ return Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy));
517
+ }
@@ -0,0 +1,90 @@
1
+ // Sequence-diagram layout.
2
+ //
3
+ // Lifelines along x, time along y. No ELK needed — the structure is
4
+ // strictly tabular, so we lay it out with simple counters.
5
+ //
6
+ // Coordinate convention: head boxes sit at the top with their centre
7
+ // at participant.x; lifelines run vertically downward. Messages get a
8
+ // y position assigned in declaration order.
9
+
10
+ import { FONT, measureLine } from "../style/text.mjs";
11
+
12
+ const HEAD_PAD_X = 18;
13
+ const HEAD_PAD_Y = 10;
14
+ const HEAD_MIN_W = 110;
15
+ const HEAD_HEIGHT = 50;
16
+ const ACTOR_HEAD_HEIGHT = 80; // taller for stickman
17
+ const PARTICIPANT_GAP = 60;
18
+ const TOP_MARGIN = 60;
19
+ const SIDE_MARGIN = 40;
20
+ const MESSAGE_FIRST_Y = 50; // distance from lifeline top to first arrow
21
+ const MESSAGE_GAP = 50;
22
+ const SELF_HEIGHT = 36;
23
+ const NOTE_PAD = 8;
24
+ const NOTE_GAP = 14;
25
+ const BOTTOM_MARGIN = 60;
26
+
27
+ export function layoutSequenceDiagram(diagram) {
28
+ // 1. Size each participant head from its title.
29
+ for (const p of diagram.participants) {
30
+ const titleLines = String(p.title || "").split("\n");
31
+ const w = Math.max(HEAD_MIN_W,
32
+ Math.max(...titleLines.map((l) => measureLine(l, FONT.sizeTitle).width)) + HEAD_PAD_X * 2);
33
+ p.headWidth = Math.ceil(w);
34
+ p.headHeight = p.shape === "actor" ? ACTOR_HEAD_HEIGHT : HEAD_HEIGHT;
35
+ }
36
+
37
+ // 2. Lay out participants horizontally, centred on x.
38
+ let cursor = SIDE_MARGIN;
39
+ for (const p of diagram.participants) {
40
+ p.x = cursor + p.headWidth / 2;
41
+ p.headY = TOP_MARGIN;
42
+ cursor += p.headWidth + PARTICIPANT_GAP;
43
+ }
44
+ const totalWidth = cursor - PARTICIPANT_GAP + SIDE_MARGIN;
45
+
46
+ const lifelineTop = TOP_MARGIN + Math.max(...diagram.participants.map((p) => p.headHeight), 0);
47
+ for (const p of diagram.participants) p.lifelineTop = lifelineTop;
48
+
49
+ // 3. Walk messages and notes in their declaration order, assigning y.
50
+ // We interleave them by relying on the parser's declaration order. The
51
+ // model only has separate lists, so we just place messages first, then
52
+ // notes near the most recent message (good-enough heuristic).
53
+ let y = lifelineTop + MESSAGE_FIRST_Y;
54
+ for (const m of diagram.messages) {
55
+ m.y = y;
56
+ y += m.isSelf ? SELF_HEIGHT + MESSAGE_GAP : MESSAGE_GAP;
57
+ }
58
+
59
+ // Notes: place them between messages along the same y-axis, spaced
60
+ // after the last message. This is a pragmatic placement; a future
61
+ // pass could weave them into the message timeline based on parser
62
+ // index.
63
+ for (const n of diagram.notes) {
64
+ const lines = n.text.split("\n");
65
+ n.width = Math.max(120,
66
+ Math.max(...lines.map((l) => measureLine(l, FONT.sizeDescription).width)) + NOTE_PAD * 2);
67
+ n.height = lines.length * FONT.sizeDescription * FONT.lineHeight + NOTE_PAD * 2;
68
+ if (n.side === "over" && n.target2) {
69
+ const x1 = Math.min(n.target.x, n.target2.x);
70
+ const x2 = Math.max(n.target.x, n.target2.x);
71
+ n.x = (x1 + x2) / 2 - n.width / 2;
72
+ } else if (n.side === "left") {
73
+ n.x = n.target.x - n.target.headWidth / 2 - n.width - NOTE_GAP;
74
+ } else if (n.side === "right") {
75
+ n.x = n.target.x + n.target.headWidth / 2 + NOTE_GAP;
76
+ } else { // over single
77
+ n.x = n.target.x - n.width / 2;
78
+ }
79
+ n.y = y;
80
+ y += n.height + NOTE_GAP;
81
+ }
82
+
83
+ const lifelineBottom = y + BOTTOM_MARGIN;
84
+ for (const p of diagram.participants) p.lifelineBottom = lifelineBottom;
85
+
86
+ diagram.width = Math.max(totalWidth, 400);
87
+ diagram.height = lifelineBottom + BOTTOM_MARGIN;
88
+
89
+ return diagram;
90
+ }