@open-document/core 0.14.0 → 0.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/{build-CyBlmrjS.js → build-I0cgoERP.js} +1 -1
  2. package/dist/{check-DUKDEem-.js → check-Dys96QSL.js} +3 -3
  3. package/dist/cli/bin.js +9 -9
  4. package/dist/{context-BPApOW9n.js → context-C-osJW5f.js} +1 -1
  5. package/dist/{dev-DrnOvsX3.js → dev-CC4PrIOC.js} +1 -1
  6. package/dist/{diff-BPMD2Knh.js → diff-DhutD4TJ.js} +2 -2
  7. package/dist/{export-DeVtL8aX.js → export-KrajVJO7.js} +3 -3
  8. package/dist/{import-WAgWsuOv.js → import-Yv34za3L.js} +3 -3
  9. package/dist/ops/index.js +2 -2
  10. package/dist/{ops-raK6424A.js → ops-Dux5HlkH.js} +2 -422
  11. package/dist/{preview-B8Vw9QCh.js → preview-7eqn9Wzf.js} +1 -1
  12. package/dist/{config-cNpYUpF6.js → session-BSbrC5gK.js} +510 -4
  13. package/dist/{templates-D9jAFJ8R.js → templates-s-VLTSRc.js} +3 -3
  14. package/dist/vite/index.js +1 -1
  15. package/package.json +6 -1
  16. package/src/agent/check-after-turn.ts +59 -0
  17. package/src/agent/detect.ts +158 -0
  18. package/src/agent/install.ts +73 -0
  19. package/src/agent/prompt.ts +175 -0
  20. package/src/agent/provider.ts +126 -0
  21. package/src/agent/providers/codex.ts +209 -0
  22. package/src/agent/providers/index.ts +7 -0
  23. package/src/agent/providers/sdk-types.ts +71 -0
  24. package/src/agent/runner.ts +392 -0
  25. package/src/agent/status.ts +64 -0
  26. package/src/agent/store.ts +271 -0
  27. package/src/agent/types.ts +174 -0
  28. package/src/app/components/agent/agent-panel.tsx +6 -1
  29. package/src/app/components/agent/transcript.tsx +111 -3
  30. package/src/app/lib/i18n-ja/agent-panel.ts +8 -0
  31. package/src/app/lib/i18n-ko/agent-panel.ts +8 -0
  32. package/src/app/lib/i18n-zh-cn/agent-panel.ts +8 -0
  33. package/src/app/lib/i18n-zh-tw/agent-panel.ts +8 -0
  34. package/src/app/lib/use-locale.ts +7 -0
  35. package/src/diagram/index.ts +46 -0
  36. package/src/diagram/layout.ts +627 -0
  37. package/src/diagram/parse.ts +335 -0
  38. package/src/diagram/render.ts +162 -0
  39. package/src/editing/placeholder-id.ts +2 -0
  40. package/src/app/lib/chart.test.ts +0 -123
  41. package/src/app/lib/docx/ooxml.test.ts +0 -484
  42. package/src/app/lib/flow-measure.test.ts +0 -30
  43. package/src/app/lib/flow.test.ts +0 -129
  44. package/src/app/lib/footnotes.test.tsx +0 -102
  45. package/src/app/lib/i18n.test.ts +0 -24
  46. package/src/app/lib/inspector/inline-edit.test.ts +0 -244
  47. package/src/app/lib/page-range.test.ts +0 -104
  48. package/src/app/lib/records.test.ts +0 -38
  49. package/src/app/lib/sdk.test.ts +0 -30
  50. package/src/app/lib/view-mode.test.ts +0 -46
@@ -0,0 +1,627 @@
1
+ import type { Diagram, DiagramEdge, DiagramNode, Direction } from './parse.ts';
2
+
3
+ export type LaidOutNode = DiagramNode & {
4
+ x: number;
5
+ y: number;
6
+ width: number;
7
+ height: number;
8
+ lines: string[];
9
+ };
10
+
11
+ export type LaidOutEdge = DiagramEdge & {
12
+ /** Polyline through which the link is drawn, in diagram coordinates. */
13
+ points: Array<{ x: number; y: number }>;
14
+ labelAt: { x: number; y: number } | null;
15
+ };
16
+
17
+ export type LaidOutSubgraph = {
18
+ id: string;
19
+ label: string;
20
+ x: number;
21
+ y: number;
22
+ width: number;
23
+ height: number;
24
+ };
25
+
26
+ export type LaidOutLifeline = {
27
+ id: string;
28
+ x: number;
29
+ y1: number;
30
+ y2: number;
31
+ };
32
+
33
+ export type LaidOutDiagram = {
34
+ kind?: 'flowchart' | 'sequence';
35
+ direction: Direction;
36
+ nodes: LaidOutNode[];
37
+ edges: LaidOutEdge[];
38
+ subgraphs?: LaidOutSubgraph[];
39
+ lifelines?: LaidOutLifeline[];
40
+ width: number;
41
+ height: number;
42
+ };
43
+
44
+ export type LayoutOptions = {
45
+ fontSize?: number;
46
+ /** Gap between consecutive ranks, along the flow direction. */
47
+ rankGap?: number;
48
+ /** Gap between siblings within a rank. */
49
+ nodeGap?: number;
50
+ maxLabelWidth?: number;
51
+ padding?: number;
52
+ };
53
+
54
+ const DEFAULTS = {
55
+ fontSize: 13,
56
+ rankGap: 48,
57
+ nodeGap: 28,
58
+ maxLabelWidth: 190,
59
+ padding: 8,
60
+ } satisfies Required<LayoutOptions>;
61
+
62
+ const PAD_X = 14;
63
+ const PAD_Y = 10;
64
+ const MIN_WIDTH = 76;
65
+ const LINE_HEIGHT = 1.35;
66
+
67
+ /**
68
+ * Text has to be measured without a DOM: the SVG is produced in the Vite
69
+ * plugin, at build time, where there is no browser to ask. Full-width
70
+ * characters take about one em and Latin about half of one, which is close
71
+ * enough that a box never clips its own label.
72
+ */
73
+ export function measureText(text: string, fontSize: number): number {
74
+ let width = 0;
75
+ for (const char of text) {
76
+ const code = char.codePointAt(0) ?? 0;
77
+ const fullWidth =
78
+ (code >= 0x1100 && code <= 0x115f) ||
79
+ (code >= 0x2e80 && code <= 0xa4cf) ||
80
+ (code >= 0xac00 && code <= 0xd7a3) ||
81
+ (code >= 0xf900 && code <= 0xfaff) ||
82
+ (code >= 0xfe30 && code <= 0xfe6f) ||
83
+ (code >= 0xff00 && code <= 0xff60) ||
84
+ (code >= 0xffe0 && code <= 0xffe6);
85
+ width += fullWidth ? fontSize : fontSize * 0.53;
86
+ }
87
+ return width;
88
+ }
89
+
90
+ /** Wraps on spaces where there are any, and between characters where there are not. */
91
+ export function wrapLabel(text: string, fontSize: number, maxWidth: number): string[] {
92
+ const explicit = text.split(/<br\s*\/?>/);
93
+ const lines: string[] = [];
94
+
95
+ for (const segment of explicit) {
96
+ const trimmed = segment.trim();
97
+ if (!trimmed) continue;
98
+ if (measureText(trimmed, fontSize) <= maxWidth) {
99
+ lines.push(trimmed);
100
+ continue;
101
+ }
102
+
103
+ const words = trimmed.includes(' ') ? trimmed.split(/\s+/) : [...trimmed];
104
+ const joiner = trimmed.includes(' ') ? ' ' : '';
105
+ let current = '';
106
+ for (const word of words) {
107
+ const candidate = current ? current + joiner + word : word;
108
+ if (current && measureText(candidate, fontSize) > maxWidth) {
109
+ lines.push(current);
110
+ current = word;
111
+ } else {
112
+ current = candidate;
113
+ }
114
+ }
115
+ if (current) lines.push(current);
116
+ }
117
+
118
+ return lines.length > 0 ? lines : [''];
119
+ }
120
+
121
+ function sizeOf(node: DiagramNode, lines: string[], fontSize: number) {
122
+ const textWidth = Math.max(...lines.map((line) => measureText(line, fontSize)));
123
+ const textHeight = lines.length * fontSize * LINE_HEIGHT;
124
+ let width = Math.max(MIN_WIDTH, textWidth + PAD_X * 2);
125
+ let height = textHeight + PAD_Y * 2;
126
+
127
+ // The lids take height the label cannot use.
128
+ if (node.shape === 'cylinder') height += 12;
129
+ // A rhombus only offers an inscribed rectangle to its label: with half-extents
130
+ // a and b, the text fits when a/(W/2) + b/(H/2) <= 1. Doubling each extent and
131
+ // adding the padding satisfies it with room to spare.
132
+ if (node.shape === 'diamond') {
133
+ width = textWidth * 2 + PAD_X * 2;
134
+ height = textHeight * 2 + PAD_Y * 2;
135
+ }
136
+ if (node.shape === 'circle') {
137
+ const diameter = Math.max(textWidth, textHeight) + PAD_X * 2;
138
+ width = diameter;
139
+ height = diameter;
140
+ }
141
+ return { width: Math.round(width), height: Math.round(height) };
142
+ }
143
+
144
+ /**
145
+ * Ranks by longest path. Edges that close a cycle are excluded from ranking —
146
+ * a feedback arrow in an architecture diagram is normal, and it must not make
147
+ * the graph unrankable.
148
+ */
149
+ function assignRanks(nodes: DiagramNode[], edges: DiagramEdge[]): Map<string, number> {
150
+ const ids = nodes.map((n) => n.id);
151
+ const outgoing = new Map<string, string[]>(ids.map((id) => [id, []]));
152
+ for (const edge of edges) outgoing.get(edge.from)?.push(edge.to);
153
+
154
+ const state = new Map<string, 0 | 1 | 2>();
155
+ const backEdges = new Set<string>();
156
+ const key = (from: string, to: string) => `${from} ${to}`;
157
+
158
+ const visit = (id: string) => {
159
+ state.set(id, 1);
160
+ for (const next of outgoing.get(id) ?? []) {
161
+ const seen = state.get(next);
162
+ if (seen === 1) backEdges.add(key(id, next));
163
+ else if (seen === undefined) visit(next);
164
+ }
165
+ state.set(id, 2);
166
+ };
167
+ for (const id of ids) if (state.get(id) === undefined) visit(id);
168
+
169
+ const forward = edges.filter((e) => !backEdges.has(key(e.from, e.to)));
170
+ const incoming = new Map<string, string[]>(ids.map((id) => [id, []]));
171
+ for (const edge of forward) incoming.get(edge.to)?.push(edge.from);
172
+
173
+ const rank = new Map<string, number>();
174
+ const resolve = (id: string, guard: Set<string>): number => {
175
+ const cached = rank.get(id);
176
+ if (cached !== undefined) return cached;
177
+ if (guard.has(id)) return 0;
178
+ guard.add(id);
179
+ const parents = incoming.get(id) ?? [];
180
+ const value = parents.length === 0 ? 0 : Math.max(...parents.map((p) => resolve(p, guard) + 1));
181
+ guard.delete(id);
182
+ rank.set(id, value);
183
+ return value;
184
+ };
185
+ for (const id of ids) resolve(id, new Set());
186
+ return rank;
187
+ }
188
+
189
+ /** Barycenter sweeps — cheap, and enough to untangle the graphs a report contains. */
190
+ function orderRanks(ranks: string[][], edges: DiagramEdge[]): void {
191
+ const neighbours = new Map<string, { up: string[]; down: string[] }>();
192
+ for (const rank of ranks) {
193
+ for (const id of rank) neighbours.set(id, { up: [], down: [] });
194
+ }
195
+ for (const edge of edges) {
196
+ neighbours.get(edge.to)?.up.push(edge.from);
197
+ neighbours.get(edge.from)?.down.push(edge.to);
198
+ }
199
+
200
+ const positions = new Map<string, number>();
201
+ const index = () => {
202
+ for (const rank of ranks) {
203
+ rank.forEach((id, i) => {
204
+ positions.set(id, i);
205
+ });
206
+ }
207
+ };
208
+ index();
209
+
210
+ const sweep = (side: 'up' | 'down') => {
211
+ for (const rank of ranks) {
212
+ const scored = rank.map((id, i) => {
213
+ const related = neighbours.get(id)?.[side] ?? [];
214
+ const known: number[] = [];
215
+ for (const other of related) {
216
+ const at = positions.get(other);
217
+ if (at !== undefined) known.push(at);
218
+ }
219
+ return { id, score: known.length ? known.reduce((a, b) => a + b, 0) / known.length : i };
220
+ });
221
+ scored.sort((a, b) => a.score - b.score);
222
+ rank.splice(0, rank.length, ...scored.map((s) => s.id));
223
+ }
224
+ index();
225
+ };
226
+
227
+ for (let pass = 0; pass < 4; pass += 1) {
228
+ sweep('up');
229
+ sweep('down');
230
+ }
231
+ }
232
+
233
+ /**
234
+ * The point a given fraction along the polyline by length. Taking a *vertex*
235
+ * instead would park every label on an elbow, where two of them meet.
236
+ */
237
+ export function pointAlong(
238
+ points: Array<{ x: number; y: number }>,
239
+ fraction: number,
240
+ ): { x: number; y: number } {
241
+ let total = 0;
242
+ const spans: number[] = [];
243
+ for (let i = 1; i < points.length; i += 1) {
244
+ const span = Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);
245
+ spans.push(span);
246
+ total += span;
247
+ }
248
+
249
+ const target = total * fraction;
250
+ let walked = 0;
251
+ for (let i = 0; i < spans.length; i += 1) {
252
+ if (walked + spans[i] >= target) {
253
+ const into = spans[i] === 0 ? 0 : (target - walked) / spans[i];
254
+ return {
255
+ x: points[i].x + (points[i + 1].x - points[i].x) * into,
256
+ y: points[i].y + (points[i + 1].y - points[i].y) * into,
257
+ };
258
+ }
259
+ walked += spans[i];
260
+ }
261
+ return points[points.length - 1];
262
+ }
263
+
264
+ /** Where along an edge a label may sit, tried in order of how central it is. */
265
+ const LABEL_STOPS = [0.5, 0.34, 0.66, 0.24, 0.76];
266
+
267
+ /**
268
+ * Two edges leaving the same node reach their midpoints at the same height, so
269
+ * their labels land on top of each other. Each label slides along its own line
270
+ * until it clears the ones already placed.
271
+ */
272
+ function placeLabels(edges: LaidOutEdge[], fontSize: number): void {
273
+ const size = fontSize * 0.85;
274
+ const height = size * 1.7;
275
+ const placed: Array<{ x: number; y: number; w: number; h: number }> = [];
276
+
277
+ const hits = (a: { x: number; y: number; w: number; h: number }) =>
278
+ placed.some((b) => Math.abs(a.x - b.x) * 2 < a.w + b.w && Math.abs(a.y - b.y) * 2 < a.h + b.h);
279
+
280
+ for (const edge of edges) {
281
+ if (!edge.label) continue;
282
+ const width = measureText(edge.label, size) + 10;
283
+ let chosen = pointAlong(edge.points, LABEL_STOPS[0]);
284
+ for (const stop of LABEL_STOPS) {
285
+ const candidate = pointAlong(edge.points, stop);
286
+ if (!hits({ ...candidate, w: width, h: height })) {
287
+ chosen = candidate;
288
+ break;
289
+ }
290
+ }
291
+ placed.push({ ...chosen, w: width, h: height });
292
+ edge.labelAt = chosen;
293
+ }
294
+ }
295
+
296
+ const CHANNEL_GAP = 18;
297
+
298
+ /**
299
+ * A link that runs against the flow — a feedback arrow back to an earlier
300
+ * step. Drawn straight, it would cut through every box between the two ends
301
+ * and park its label on one of them; it goes round the side instead (the
302
+ * right in a column, underneath in a row), clear of everything it passes, and
303
+ * each such link a step further out than the last.
304
+ */
305
+ function routeBack(
306
+ from: LaidOutNode,
307
+ to: LaidOutNode,
308
+ nodes: LaidOutNode[],
309
+ horizontal: boolean,
310
+ lane: number,
311
+ ) {
312
+ if (horizontal) {
313
+ const left = Math.min(from.x, to.x);
314
+ const right = Math.max(from.x + from.width, to.x + to.width);
315
+ const passed = nodes.filter((n) => n.x < right && n.x + n.width > left);
316
+ const channel = Math.max(...passed.map((n) => n.y + n.height)) + CHANNEL_GAP * (lane + 1);
317
+ const start = { x: from.x + from.width / 2, y: from.y + from.height };
318
+ const end = { x: to.x + to.width / 2, y: to.y + to.height };
319
+ return [start, { x: start.x, y: channel }, { x: end.x, y: channel }, end];
320
+ }
321
+ const top = Math.min(from.y, to.y);
322
+ const bottom = Math.max(from.y + from.height, to.y + to.height);
323
+ const passed = nodes.filter((n) => n.y < bottom && n.y + n.height > top);
324
+ const channel = Math.max(...passed.map((n) => n.x + n.width)) + CHANNEL_GAP * (lane + 1);
325
+ const start = { x: from.x + from.width, y: from.y + from.height / 2 };
326
+ const end = { x: to.x + to.width, y: to.y + to.height / 2 };
327
+ return [start, { x: channel, y: start.y }, { x: channel, y: end.y }, end];
328
+ }
329
+
330
+ /** Straight where the two boxes line up, a single elbow where they do not. */
331
+ function route(from: LaidOutNode, to: LaidOutNode, horizontal: boolean) {
332
+ const fromCentre = { x: from.x + from.width / 2, y: from.y + from.height / 2 };
333
+ const toCentre = { x: to.x + to.width / 2, y: to.y + to.height / 2 };
334
+
335
+ if (horizontal) {
336
+ const start = { x: from.x + from.width, y: fromCentre.y };
337
+ const end = { x: to.x, y: toCentre.y };
338
+ if (Math.abs(start.y - end.y) < 1 || end.x <= start.x) return [start, end];
339
+ const midX = (start.x + end.x) / 2;
340
+ return [start, { x: midX, y: start.y }, { x: midX, y: end.y }, end];
341
+ }
342
+
343
+ const start = { x: fromCentre.x, y: from.y + from.height };
344
+ const end = { x: toCentre.x, y: to.y };
345
+ if (Math.abs(start.x - end.x) < 1 || end.y <= start.y) return [start, end];
346
+ const midY = (start.y + end.y) / 2;
347
+ return [start, { x: start.x, y: midY }, { x: end.x, y: midY }, end];
348
+ }
349
+
350
+ function layoutSequence(diagram: Diagram, opts: Required<LayoutOptions>): LaidOutDiagram {
351
+ const partNodes = diagram.nodes;
352
+ const messages = diagram.messages ?? [];
353
+ const labelSize = opts.fontSize * 0.85;
354
+
355
+ const boxSizes = partNodes.map((p) => {
356
+ const wrapped = wrapLabel(p.label, opts.fontSize, opts.maxLabelWidth);
357
+ const sz = sizeOf(p, wrapped, opts.fontSize);
358
+ return { node: p, lines: wrapped, width: sz.width, height: sz.height };
359
+ });
360
+
361
+ // Ensure adjacent participant centres are far enough apart for message labels between them.
362
+ const indexById = new Map(partNodes.map((p, i) => [p.id, i]));
363
+ const gapAfter = new Array<number>(Math.max(0, partNodes.length - 1)).fill(opts.nodeGap + 36);
364
+
365
+ for (const msg of messages) {
366
+ const fi = indexById.get(msg.from) ?? 0;
367
+ const ti = indexById.get(msg.to) ?? 0;
368
+ if (fi === ti) continue;
369
+ const lo = Math.min(fi, ti);
370
+ const hi = Math.max(fi, ti);
371
+ if (hi - lo === 1 && msg.label) {
372
+ const needed = measureText(msg.label, labelSize) + 36;
373
+ if (needed > gapAfter[lo]) gapAfter[lo] = needed;
374
+ }
375
+ }
376
+
377
+ const centres: number[] = [];
378
+ let cursorX = opts.padding;
379
+ boxSizes.forEach((box, i) => {
380
+ if (i === 0) {
381
+ centres.push(cursorX + box.width / 2);
382
+ cursorX += box.width;
383
+ } else {
384
+ const prevBox = boxSizes[i - 1];
385
+ const minCentreDist = (prevBox.width + box.width) / 2 + (gapAfter[i - 1] ?? opts.nodeGap);
386
+ const nextCentre = centres[i - 1] + minCentreDist;
387
+ centres.push(nextCentre);
388
+ cursorX = nextCentre + box.width / 2;
389
+ }
390
+ });
391
+
392
+ const topY = opts.padding;
393
+ const headerHeight = Math.max(...boxSizes.map((b) => b.height), 36);
394
+ const nodes: LaidOutNode[] = boxSizes.map((box, i) => ({
395
+ ...box.node,
396
+ lines: box.lines,
397
+ width: box.width,
398
+ height: headerHeight,
399
+ x: Math.round(centres[i] - box.width / 2),
400
+ y: topY,
401
+ }));
402
+
403
+ const centreById = new Map(partNodes.map((p, i) => [p.id, Math.round(centres[i])]));
404
+ const edges: LaidOutEdge[] = [];
405
+ let msgY = topY + headerHeight + 34;
406
+ const stepY = 42;
407
+ let maxRight = Math.max(...nodes.map((n) => n.x + n.width));
408
+
409
+ for (const msg of messages) {
410
+ const x1 = centreById.get(msg.from) ?? opts.padding;
411
+ const x2 = centreById.get(msg.to) ?? opts.padding;
412
+ if (msg.from === msg.to) {
413
+ const loopW = 36;
414
+ const loopH = 20;
415
+ const points = [
416
+ { x: x1, y: msgY },
417
+ { x: x1 + loopW, y: msgY },
418
+ { x: x1 + loopW, y: msgY + loopH },
419
+ { x: x1, y: msgY + loopH },
420
+ ];
421
+ const labelW = msg.label ? measureText(msg.label, labelSize) + 12 : 0;
422
+ const labelAt = msg.label ? { x: x1 + loopW + labelW / 2 + 4, y: msgY + loopH / 2 } : null;
423
+ if (labelAt) maxRight = Math.max(maxRight, labelAt.x + labelW / 2);
424
+ edges.push({
425
+ from: msg.from,
426
+ to: msg.to,
427
+ label: msg.label || null,
428
+ style: msg.style,
429
+ arrow: msg.arrow,
430
+ points,
431
+ labelAt,
432
+ });
433
+ msgY += stepY + 10;
434
+ } else {
435
+ const points = [
436
+ { x: x1, y: msgY },
437
+ { x: x2, y: msgY },
438
+ ];
439
+ const labelAt = msg.label ? { x: (x1 + x2) / 2, y: msgY - 10 } : null;
440
+ edges.push({
441
+ from: msg.from,
442
+ to: msg.to,
443
+ label: msg.label || null,
444
+ style: msg.style,
445
+ arrow: msg.arrow,
446
+ points,
447
+ labelAt,
448
+ });
449
+ msgY += stepY;
450
+ }
451
+ }
452
+
453
+ const lifelineBottom = Math.max(topY + headerHeight + 28, msgY - 10);
454
+ const lifelines: LaidOutLifeline[] = partNodes.map((p, i) => ({
455
+ id: p.id,
456
+ x: Math.round(centres[i]),
457
+ y1: topY + headerHeight,
458
+ y2: lifelineBottom,
459
+ }));
460
+
461
+ return {
462
+ kind: 'sequence',
463
+ direction: 'LR',
464
+ nodes,
465
+ edges,
466
+ lifelines,
467
+ width: Math.round(maxRight + opts.padding),
468
+ height: Math.round(lifelineBottom + opts.padding),
469
+ };
470
+ }
471
+
472
+ export function layoutDiagram(diagram: Diagram, options: LayoutOptions = {}): LaidOutDiagram {
473
+ const opts = { ...DEFAULTS, ...options };
474
+ if (diagram.kind === 'sequence') {
475
+ return layoutSequence(diagram, opts);
476
+ }
477
+
478
+ const horizontal = diagram.direction === 'LR';
479
+ const hasSubgraphs = (diagram.subgraphs?.length ?? 0) > 0;
480
+ const effectiveRankGap = hasSubgraphs ? Math.max(opts.rankGap, 62) : opts.rankGap;
481
+ const effectiveNodeGap = hasSubgraphs ? Math.max(opts.nodeGap, 38) : opts.nodeGap;
482
+ const outerPad = hasSubgraphs ? Math.max(opts.padding, 24) : opts.padding;
483
+
484
+ const lines = new Map<string, string[]>();
485
+ const sizes = new Map<string, { width: number; height: number }>();
486
+ for (const node of diagram.nodes) {
487
+ // A decision wraps earlier than a box: a wide rhombus reads as a bar, and
488
+ // the whole point of the shape is that it is recognisable at a glance.
489
+ const limit =
490
+ node.shape === 'diamond' ? Math.max(84, opts.maxLabelWidth * 0.5) : opts.maxLabelWidth;
491
+ const wrapped = wrapLabel(node.label, opts.fontSize, limit);
492
+ lines.set(node.id, wrapped);
493
+ sizes.set(node.id, sizeOf(node, wrapped, opts.fontSize));
494
+ }
495
+
496
+ const rankOf = assignRanks(diagram.nodes, diagram.edges);
497
+ const depth = Math.max(...rankOf.values()) + 1;
498
+ const ranks: string[][] = Array.from({ length: depth }, () => []);
499
+ for (const node of diagram.nodes) ranks[rankOf.get(node.id) ?? 0].push(node.id);
500
+ orderRanks(ranks, diagram.edges);
501
+
502
+ // Along the flow: each rank sits past the deepest node of the one before it.
503
+ const rankOffset: number[] = [];
504
+ let cursor = outerPad + (hasSubgraphs ? 18 : 0);
505
+ for (const rank of ranks) {
506
+ rankOffset.push(cursor);
507
+ const extent = Math.max(
508
+ ...rank.map((id) => {
509
+ const size = sizes.get(id);
510
+ return horizontal ? (size?.width ?? 0) : (size?.height ?? 0);
511
+ }),
512
+ );
513
+ cursor += extent + effectiveRankGap;
514
+ }
515
+
516
+ // Across the flow: lay each rank out end to end, then centre the ranks on
517
+ // each other so the drawing reads as a column rather than a staircase.
518
+ const cross = new Map<string, number>();
519
+ const rankSpan: number[] = [];
520
+ ranks.forEach((rank, i) => {
521
+ let offset = 0;
522
+ for (const id of rank) {
523
+ const size = sizes.get(id);
524
+ const extent = horizontal ? (size?.height ?? 0) : (size?.width ?? 0);
525
+ cross.set(id, offset + extent / 2);
526
+ offset += extent + effectiveNodeGap;
527
+ }
528
+ rankSpan[i] = Math.max(0, offset - effectiveNodeGap);
529
+ });
530
+
531
+ const widest = Math.max(...rankSpan, 0);
532
+ ranks.forEach((rank, i) => {
533
+ const shift = (widest - rankSpan[i]) / 2 + outerPad;
534
+ for (const id of rank) cross.set(id, (cross.get(id) ?? 0) + shift);
535
+ });
536
+
537
+ const nodes: LaidOutNode[] = diagram.nodes.map((node) => {
538
+ const size = sizes.get(node.id) ?? { width: MIN_WIDTH, height: 40 };
539
+ const along = rankOffset[rankOf.get(node.id) ?? 0];
540
+ const crossCentre = cross.get(node.id) ?? 0;
541
+ return {
542
+ ...node,
543
+ lines: lines.get(node.id) ?? [node.label],
544
+ width: size.width,
545
+ height: size.height,
546
+ x: horizontal ? along : crossCentre - size.width / 2,
547
+ y: horizontal ? crossCentre - size.height / 2 : along,
548
+ };
549
+ });
550
+
551
+ const byId = new Map(nodes.map((n) => [n.id, n]));
552
+ const edges: LaidOutEdge[] = [];
553
+ let lanes = 0;
554
+ for (const edge of diagram.edges) {
555
+ const from = byId.get(edge.from);
556
+ const to = byId.get(edge.to);
557
+ if (!from || !to) continue;
558
+ const backward = (rankOf.get(edge.to) ?? 0) < (rankOf.get(edge.from) ?? 0);
559
+ const points = backward
560
+ ? routeBack(from, to, nodes, horizontal, lanes++)
561
+ : route(from, to, horizontal);
562
+ edges.push({ ...edge, points, labelAt: null });
563
+ }
564
+ placeLabels(edges, opts.fontSize);
565
+
566
+ const subgraphs: LaidOutSubgraph[] = [];
567
+ if (diagram.subgraphs) {
568
+ const sgPadX = 14;
569
+ const sgPadTop = 26;
570
+ const sgPadBottom = 12;
571
+ for (const sg of diagram.subgraphs) {
572
+ const members = sg.nodeIds
573
+ .map((id) => byId.get(id))
574
+ .filter((n): n is LaidOutNode => n !== undefined);
575
+ if (members.length === 0) continue;
576
+ const minX = Math.min(...members.map((m) => m.x)) - sgPadX;
577
+ const minY = Math.min(...members.map((m) => m.y)) - sgPadTop;
578
+ const maxX = Math.max(...members.map((m) => m.x + m.width)) + sgPadX;
579
+ const maxY = Math.max(...members.map((m) => m.y + m.height)) + sgPadBottom;
580
+ const labelWidth = measureText(sg.label, opts.fontSize * 0.85) + sgPadX * 2;
581
+ subgraphs.push({
582
+ id: sg.id,
583
+ label: sg.label,
584
+ x: Math.max(2, Math.round(minX)),
585
+ y: Math.max(2, Math.round(minY)),
586
+ width: Math.round(Math.max(maxX - minX, labelWidth)),
587
+ height: Math.round(maxY - minY),
588
+ });
589
+ }
590
+ }
591
+
592
+ // A link routed round the side, and its label, reach past the boxes.
593
+ const labelSize = opts.fontSize * 0.85;
594
+ const reach = edges.flatMap((edge) => [
595
+ ...edge.points,
596
+ ...(edge.labelAt && edge.label
597
+ ? [
598
+ {
599
+ x: edge.labelAt.x + (measureText(edge.label, labelSize) + 10) / 2,
600
+ y: edge.labelAt.y + labelSize * 0.8,
601
+ },
602
+ ]
603
+ : []),
604
+ ]);
605
+ const sgReach = subgraphs.map((s) => ({ x: s.x + s.width, y: s.y + s.height }));
606
+ const width =
607
+ Math.max(
608
+ ...nodes.map((n) => n.x + n.width),
609
+ ...reach.map((p) => p.x),
610
+ ...sgReach.map((p) => p.x),
611
+ ) + opts.padding;
612
+ const height =
613
+ Math.max(
614
+ ...nodes.map((n) => n.y + n.height),
615
+ ...reach.map((p) => p.y),
616
+ ...sgReach.map((p) => p.y),
617
+ ) + opts.padding;
618
+ return {
619
+ kind: 'flowchart',
620
+ direction: diagram.direction,
621
+ nodes,
622
+ edges,
623
+ ...(subgraphs.length > 0 ? { subgraphs } : {}),
624
+ width,
625
+ height,
626
+ };
627
+ }