@standarx/graph 0.0.0-stage → 1.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.
Files changed (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +438 -0
  3. package/README.md +437 -2
  4. package/THIRD_PARTY_NOTICES.md +22 -0
  5. package/assets/fonts/Inter-Regular.ttf +0 -0
  6. package/assets/fonts/Inter-SemiBold.ttf +0 -0
  7. package/assets/fonts/OFL.txt +92 -0
  8. package/dist/adapter-0bggwh8x.js +393 -0
  9. package/dist/cli-4m00785g.js +20 -0
  10. package/dist/cli-5v9761s9.js +330 -0
  11. package/dist/cli-9f1pdw5q.js +462 -0
  12. package/dist/cli-a4ax1vkc.js +172 -0
  13. package/dist/cli-abzdy8pn.js +1144 -0
  14. package/dist/cli-gh5166k6.js +1565 -0
  15. package/dist/cli-m29a3wgx.js +579 -0
  16. package/dist/cli-mzmjkk5v.js +11 -0
  17. package/dist/cli-nhmh6yxk.js +2485 -0
  18. package/dist/cli-nyckgf1t.js +4 -0
  19. package/dist/cli-sfdqkbd1.js +433 -0
  20. package/dist/cli-txrzzr2q.js +0 -0
  21. package/dist/cli-vecew2na.js +709 -0
  22. package/dist/cli-wt9dmbhm.js +560 -0
  23. package/dist/cli-ywgtv1cg.js +39 -0
  24. package/dist/cli-z3ccx2y4.js +141 -0
  25. package/dist/cli.d.ts +2 -0
  26. package/dist/cli.js +413 -0
  27. package/dist/core/index.d.ts +6 -0
  28. package/dist/core/index.js +91 -0
  29. package/dist/core/spatial.d.ts +16 -0
  30. package/dist/core/threshold.d.ts +1 -0
  31. package/dist/core/view.d.ts +80 -0
  32. package/dist/export/index.d.ts +18 -0
  33. package/dist/export/index.js +170 -0
  34. package/dist/export/pdf.d.ts +5 -0
  35. package/dist/export/png.d.ts +4 -0
  36. package/dist/format/index.d.ts +4 -0
  37. package/dist/format/index.js +69 -0
  38. package/dist/format/json-schema.d.ts +2 -0
  39. package/dist/format/schema.d.ts +787 -0
  40. package/dist/format/semantic/er.d.ts +3 -0
  41. package/dist/format/semantic/graph.d.ts +3 -0
  42. package/dist/format/semantic/sequence.d.ts +3 -0
  43. package/dist/format/semantic/shared.d.ts +14 -0
  44. package/dist/format/semantic/state.d.ts +3 -0
  45. package/dist/format/semantic/tree.d.ts +3 -0
  46. package/dist/format/transition-label.d.ts +2 -0
  47. package/dist/format/validate.d.ts +11 -0
  48. package/dist/html/index.d.ts +3 -0
  49. package/dist/html/index.js +125 -0
  50. package/dist/html/layout-worker.d.ts +1 -0
  51. package/dist/html/layout-worker.generated.d.ts +1 -0
  52. package/dist/html/mount.d.ts +12 -0
  53. package/dist/html/page.d.ts +14 -0
  54. package/dist/html/render.d.ts +7 -0
  55. package/dist/html/runtime.d.ts +1 -0
  56. package/dist/html/runtime.generated.d.ts +1 -0
  57. package/dist/html/shell.d.ts +10 -0
  58. package/dist/html/svg-adapter.d.ts +8 -0
  59. package/dist/html/ui.d.ts +34 -0
  60. package/dist/language/actions.d.ts +3 -0
  61. package/dist/language/analysis.d.ts +38 -0
  62. package/dist/language/complete.d.ts +3 -0
  63. package/dist/language/diagnostics.d.ts +14 -0
  64. package/dist/language/docs.d.ts +11 -0
  65. package/dist/language/format.d.ts +17 -0
  66. package/dist/language/hover.d.ts +3 -0
  67. package/dist/language/index.d.ts +8 -0
  68. package/dist/language/index.js +1560 -0
  69. package/dist/language/navigation.d.ts +9 -0
  70. package/dist/language/positions.d.ts +7 -0
  71. package/dist/language/symbols.d.ts +3 -0
  72. package/dist/language/types.d.ts +46 -0
  73. package/dist/layout/elk.d.ts +35 -0
  74. package/dist/layout/er.d.ts +3 -0
  75. package/dist/layout/font-metrics.d.ts +9 -0
  76. package/dist/layout/graph.d.ts +3 -0
  77. package/dist/layout/index.d.ts +5 -0
  78. package/dist/layout/index.js +16 -0
  79. package/dist/layout/measure.d.ts +10 -0
  80. package/dist/layout/sequence.d.ts +3 -0
  81. package/dist/layout/shapes.d.ts +16 -0
  82. package/dist/layout/shared.d.ts +31 -0
  83. package/dist/layout/state.d.ts +3 -0
  84. package/dist/layout/tree.d.ts +3 -0
  85. package/dist/layout/types.d.ts +198 -0
  86. package/dist/layout-worker.generated-xsmtzrfj.js +34 -0
  87. package/dist/mermaid/common.d.ts +36 -0
  88. package/dist/mermaid/er.d.ts +3 -0
  89. package/dist/mermaid/graph.d.ts +4 -0
  90. package/dist/mermaid/index.d.ts +6 -0
  91. package/dist/mermaid/index.js +6 -0
  92. package/dist/mermaid/mindmap.d.ts +3 -0
  93. package/dist/mermaid/sequence.d.ts +3 -0
  94. package/dist/mermaid/state.d.ts +3 -0
  95. package/dist/remark/index.d.ts +9 -0
  96. package/dist/remark/index.js +102 -0
  97. package/dist/shared/errors.d.ts +6 -0
  98. package/dist/shared/package-root.d.ts +5 -0
  99. package/dist/svg/escape.d.ts +1 -0
  100. package/dist/svg/index.d.ts +3 -0
  101. package/dist/svg/index.js +25 -0
  102. package/dist/svg/render.d.ts +9 -0
  103. package/dist/svg/theme.d.ts +62 -0
  104. package/dist/svg-adapter-gq5vmp6q.js +227 -0
  105. package/dist/text/build.d.ts +10 -0
  106. package/dist/text/canonical.d.ts +10 -0
  107. package/dist/text/errors.d.ts +33 -0
  108. package/dist/text/highlight.d.ts +13 -0
  109. package/dist/text/index.d.ts +33 -0
  110. package/dist/text/index.js +25 -0
  111. package/dist/text/lexer.d.ts +29 -0
  112. package/dist/text/parser.d.ts +160 -0
  113. package/dist/text/print.d.ts +6 -0
  114. package/dist/text/slug.d.ts +1 -0
  115. package/dist/text/syntax.d.ts +8 -0
  116. package/dist/version.d.ts +1 -0
  117. package/dist/webgl/adapter.d.ts +4 -0
  118. package/dist/webgl/index.d.ts +7 -0
  119. package/dist/webgl/index.js +15 -0
  120. package/dist/webgl/runtime.d.ts +1 -0
  121. package/dist/webgl/runtime.generated.d.ts +1 -0
  122. package/grammars/standargraph.tmLanguage.json +599 -0
  123. package/language-configuration.json +35 -0
  124. package/licenses/EPL-2.0.txt +277 -0
  125. package/licenses/MPL-2.0.txt +373 -0
  126. package/package.json +133 -4
  127. package/schema/graph-document.v1.json +1737 -0
@@ -0,0 +1,1144 @@
1
+ import {
2
+ validate2
3
+ } from "./cli-m29a3wgx.js";
4
+ import {
5
+ measureText2,
6
+ MARGIN,
7
+ CAPTION_FONT,
8
+ EDGE_LABEL_FONT,
9
+ GROUP_FONT,
10
+ PAD_X,
11
+ PAD_Y,
12
+ SELF_LOOP_WIDTH,
13
+ SELF_LOOP_HEIGHT,
14
+ round,
15
+ compact,
16
+ boxSize,
17
+ labelBoxSize,
18
+ groupTopPadding,
19
+ actionsHeight,
20
+ actionsWidth,
21
+ ER_ROW_HEIGHT,
22
+ ER_ROWS_PAD,
23
+ keysText,
24
+ attributeTypeText,
25
+ shapeSize,
26
+ clipEnds,
27
+ clipToShape
28
+ } from "./cli-gh5166k6.js";
29
+ import {
30
+ transitionLabel2
31
+ } from "./cli-mzmjkk5v.js";
32
+
33
+ // src/layout/elk.ts
34
+ import ELK from "elkjs/lib/elk.bundled.js";
35
+ var DIRECTIONS = {
36
+ down: "DOWN",
37
+ right: "RIGHT",
38
+ up: "UP",
39
+ left: "LEFT"
40
+ };
41
+ function toElkNode(box) {
42
+ if (box.children === undefined) {
43
+ return { id: box.id, width: box.width, height: box.height };
44
+ }
45
+ const options = {};
46
+ if (box.padding !== undefined) {
47
+ const { top, left, bottom, right } = box.padding;
48
+ options["elk.padding"] = `[top=${top},left=${left},bottom=${bottom},right=${right}]`;
49
+ }
50
+ if (box.minWidth !== undefined) {
51
+ options["elk.nodeSize.constraints"] = "MINIMUM_SIZE";
52
+ options["elk.nodeSize.minimum"] = `(${box.minWidth}, 0)`;
53
+ }
54
+ return {
55
+ id: box.id,
56
+ layoutOptions: options,
57
+ children: box.children.map(toElkNode)
58
+ };
59
+ }
60
+ async function runElk(direction, children, edges) {
61
+ const elkEdges = edges.map((edge) => {
62
+ const elkEdge = {
63
+ id: edge.id,
64
+ sources: [edge.from],
65
+ targets: [edge.to]
66
+ };
67
+ if (edge.label !== undefined) {
68
+ elkEdge.labels = [
69
+ {
70
+ id: `l:${edge.id}`,
71
+ text: edge.id,
72
+ width: edge.label.width,
73
+ height: edge.label.height
74
+ }
75
+ ];
76
+ }
77
+ return elkEdge;
78
+ });
79
+ const root = {
80
+ id: "root",
81
+ layoutOptions: {
82
+ "elk.algorithm": "layered",
83
+ "elk.direction": DIRECTIONS[direction],
84
+ "elk.edgeRouting": "ORTHOGONAL",
85
+ "elk.hierarchyHandling": "INCLUDE_CHILDREN",
86
+ "elk.spacing.nodeNode": "40",
87
+ "elk.layered.spacing.nodeNodeBetweenLayers": "60",
88
+ "elk.padding": `[top=${MARGIN},left=${MARGIN},bottom=${MARGIN},right=${MARGIN}]`
89
+ },
90
+ children: children.map(toElkNode),
91
+ edges: elkEdges
92
+ };
93
+ const scope = globalThis;
94
+ const previousHandler = scope.onmessage;
95
+ let result;
96
+ try {
97
+ result = await new ELK().layout(root);
98
+ } finally {
99
+ scope.onmessage = previousHandler;
100
+ }
101
+ const absolute = new Map;
102
+ const boxes = new Map;
103
+ const walk = (node, ox, oy) => {
104
+ const x = ox + (node.x ?? 0);
105
+ const y = oy + (node.y ?? 0);
106
+ absolute.set(node.id, { x, y });
107
+ boxes.set(node.id, { x, y, width: node.width ?? 0, height: node.height ?? 0 });
108
+ for (const child of node.children ?? [])
109
+ walk(child, x, y);
110
+ };
111
+ for (const child of result.children ?? [])
112
+ walk(child, 0, 0);
113
+ const routedById = new Map;
114
+ for (const routed of result.edges ?? [])
115
+ routedById.set(routed.id, routed);
116
+ const routes = new Map;
117
+ for (const edge of edges) {
118
+ const routed = routedById.get(edge.id);
119
+ const offset = absolute.get(routed?.container ?? "root") ?? { x: 0, y: 0 };
120
+ const points = [];
121
+ for (const section of routed?.sections ?? []) {
122
+ const chain = [
123
+ section.startPoint,
124
+ ...section.bendPoints ?? [],
125
+ section.endPoint
126
+ ];
127
+ for (const point of chain) {
128
+ const shifted = { x: point.x + offset.x, y: point.y + offset.y };
129
+ const last = points[points.length - 1];
130
+ if (last === undefined || last.x !== shifted.x || last.y !== shifted.y) {
131
+ points.push(shifted);
132
+ }
133
+ }
134
+ }
135
+ const label = routed?.labels?.[0];
136
+ const route = { points };
137
+ if (label !== undefined) {
138
+ route.labelBox = {
139
+ x: (label.x ?? 0) + offset.x,
140
+ y: (label.y ?? 0) + offset.y,
141
+ width: label.width ?? 0,
142
+ height: label.height ?? 0
143
+ };
144
+ }
145
+ routes.set(edge.id, route);
146
+ }
147
+ return {
148
+ width: result.width ?? 0,
149
+ height: result.height ?? 0,
150
+ boxes,
151
+ routes
152
+ };
153
+ }
154
+
155
+ // src/layout/er.ts
156
+ function widest(texts, font) {
157
+ return Math.max(0, ...texts.map((text) => measureText2(text, font).width));
158
+ }
159
+ function entityMetrics(entity) {
160
+ const header = boxSize(entity.label ?? entity.id, entity.type, 0);
161
+ const attributes = entity.attributes ?? [];
162
+ const keyWidth = widest(attributes.map((attribute) => keysText(attribute.keys)), CAPTION_FONT);
163
+ const nameWidth = widest(attributes.map((attribute) => attribute.name), EDGE_LABEL_FONT);
164
+ const typeWidth = widest(attributes.map(attributeTypeText), EDGE_LABEL_FONT);
165
+ const key = PAD_X;
166
+ const name = key + (keyWidth > 0 ? keyWidth + 8 : 0);
167
+ const type = name + nameWidth + 16;
168
+ return {
169
+ width: Math.ceil(Math.max(120, header.width, type + typeWidth + PAD_X)),
170
+ height: header.height + attributes.length * ER_ROW_HEIGHT + (attributes.length > 0 ? 2 * ER_ROWS_PAD : 0),
171
+ headerHeight: header.height,
172
+ columns: { key, name, type }
173
+ };
174
+ }
175
+ async function layoutEr(doc) {
176
+ const metrics = new Map;
177
+ for (const entity of doc.entities) {
178
+ if (!metrics.has(entity.id))
179
+ metrics.set(entity.id, entityMetrics(entity));
180
+ }
181
+ const relations = doc.relations ?? [];
182
+ const elkEdges = relations.map((relation, index) => {
183
+ const edge = {
184
+ id: `r:${index}`,
185
+ from: `e:${relation.from}`,
186
+ to: `e:${relation.to}`
187
+ };
188
+ if (relation.label !== undefined && relation.label !== "") {
189
+ const size = labelBoxSize(relation.label);
190
+ edge.label = { width: size.width, height: size.height };
191
+ }
192
+ return edge;
193
+ });
194
+ const result = await runElk(doc.direction ?? "down", doc.entities.map((entity) => {
195
+ const size = metrics.get(entity.id);
196
+ return { id: `e:${entity.id}`, width: size.width, height: size.height };
197
+ }), elkEdges);
198
+ const entities = doc.entities.map((entity) => {
199
+ const size = metrics.get(entity.id);
200
+ const box = result.boxes.get(`e:${entity.id}`) ?? {
201
+ x: 0,
202
+ y: 0,
203
+ width: size.width,
204
+ height: size.height
205
+ };
206
+ const top = box.y + size.headerHeight + ER_ROWS_PAD;
207
+ const attributes = (entity.attributes ?? []).map((attribute, index) => compact({
208
+ name: attribute.name,
209
+ type: attribute.type,
210
+ keys: attribute.keys,
211
+ nullable: attribute.nullable,
212
+ note: attribute.note,
213
+ y: round(top + index * ER_ROW_HEIGHT),
214
+ height: ER_ROW_HEIGHT
215
+ }));
216
+ return compact({
217
+ id: entity.id,
218
+ label: entity.label ?? entity.id,
219
+ type: entity.type,
220
+ x: round(box.x),
221
+ y: round(box.y),
222
+ width: round(box.width),
223
+ height: round(box.height),
224
+ headerHeight: size.headerHeight,
225
+ columns: {
226
+ key: round(size.columns.key),
227
+ name: round(size.columns.name),
228
+ type: round(size.columns.type)
229
+ },
230
+ attributes,
231
+ description: entity.description,
232
+ link: entity.link,
233
+ meta: entity.meta
234
+ });
235
+ });
236
+ const laidOutRelations = relations.map((relation, index) => {
237
+ const route = result.routes.get(`r:${index}`);
238
+ const labelBox = route?.labelBox;
239
+ return compact({
240
+ id: relation.id ?? `r${index}`,
241
+ from: relation.from,
242
+ to: relation.to,
243
+ label: relation.label === "" ? undefined : relation.label,
244
+ fromCardinality: relation.fromCardinality,
245
+ toCardinality: relation.toCardinality,
246
+ identifying: relation.identifying ?? true,
247
+ type: relation.type,
248
+ points: (route?.points ?? []).map((point) => ({
249
+ x: round(point.x),
250
+ y: round(point.y)
251
+ })),
252
+ labelBox: labelBox === undefined ? undefined : {
253
+ x: round(labelBox.x),
254
+ y: round(labelBox.y),
255
+ width: round(labelBox.width),
256
+ height: round(labelBox.height)
257
+ },
258
+ meta: relation.meta
259
+ });
260
+ });
261
+ return compact({
262
+ kind: "er",
263
+ width: round(result.width),
264
+ height: round(result.height),
265
+ title: doc.title,
266
+ entities,
267
+ relations: laidOutRelations
268
+ });
269
+ }
270
+
271
+ // src/layout/graph.ts
272
+ function orderGroups(groups) {
273
+ const children = new Map;
274
+ for (const group of groups) {
275
+ const list = children.get(group.parent) ?? [];
276
+ list.push(group);
277
+ children.set(group.parent, list);
278
+ }
279
+ const ordered = [];
280
+ const visit = (parent, depth) => {
281
+ for (const group of children.get(parent) ?? []) {
282
+ ordered.push({ group, depth });
283
+ visit(group.id, depth + 1);
284
+ }
285
+ };
286
+ visit(undefined, 0);
287
+ return ordered;
288
+ }
289
+ function nodeLabel(node) {
290
+ return node.label ?? node.id;
291
+ }
292
+ function groupLabelWidth(group) {
293
+ if (group.label === undefined || group.label === "")
294
+ return 0;
295
+ return measureText2(group.label, GROUP_FONT).width;
296
+ }
297
+ function emptyGroupSize(group) {
298
+ return {
299
+ width: Math.ceil(Math.max(80, groupLabelWidth(group) + 2 * PAD_X)),
300
+ height: groupTopPadding(group.label) + 24
301
+ };
302
+ }
303
+ function laidOutNode(node, box) {
304
+ return compact({
305
+ id: node.id,
306
+ label: nodeLabel(node),
307
+ type: node.type,
308
+ shape: node.shape,
309
+ x: round(box.x),
310
+ y: round(box.y),
311
+ width: round(box.width),
312
+ height: round(box.height),
313
+ group: node.group,
314
+ link: node.link,
315
+ description: node.description,
316
+ meta: node.meta
317
+ });
318
+ }
319
+ function laidOutGroup(group, depth, box) {
320
+ return compact({
321
+ id: group.id,
322
+ label: group.label,
323
+ x: round(box.x),
324
+ y: round(box.y),
325
+ width: round(box.width),
326
+ height: round(box.height),
327
+ depth,
328
+ meta: group.meta
329
+ });
330
+ }
331
+ function laidOutEdge(edge, index, points, labelBox) {
332
+ return compact({
333
+ id: edge.id ?? `e${index}`,
334
+ from: edge.from,
335
+ to: edge.to,
336
+ label: edge.label,
337
+ type: edge.type,
338
+ directed: edge.directed ?? true,
339
+ points: points.map((point) => ({ x: round(point.x), y: round(point.y) })),
340
+ labelBox: labelBox === undefined ? undefined : {
341
+ x: round(labelBox.x),
342
+ y: round(labelBox.y),
343
+ width: round(labelBox.width),
344
+ height: round(labelBox.height)
345
+ },
346
+ meta: edge.meta
347
+ });
348
+ }
349
+ function finish(doc, width, height, groups, nodes, edges) {
350
+ return compact({
351
+ kind: "graph",
352
+ width: round(width),
353
+ height: round(height),
354
+ title: doc.title,
355
+ groups,
356
+ nodes,
357
+ edges
358
+ });
359
+ }
360
+ async function layoutWithElk(doc) {
361
+ const groups = orderGroups(doc.groups ?? []);
362
+ const nodesByGroup = new Map;
363
+ for (const node of doc.nodes) {
364
+ const list = nodesByGroup.get(node.group) ?? [];
365
+ list.push(node);
366
+ nodesByGroup.set(node.group, list);
367
+ }
368
+ const subgroups = new Map;
369
+ for (const { group } of groups) {
370
+ if (group.parent === undefined)
371
+ continue;
372
+ const list = subgroups.get(group.parent) ?? [];
373
+ list.push(group);
374
+ subgroups.set(group.parent, list);
375
+ }
376
+ const nodeElk = (node) => {
377
+ const size = shapeSize(node.shape, nodeLabel(node), node.type, 80);
378
+ return { id: `n:${node.id}`, width: size.width, height: size.height };
379
+ };
380
+ const groupElk = (group) => {
381
+ const members = nodesByGroup.get(group.id) ?? [];
382
+ const nested = subgroups.get(group.id) ?? [];
383
+ if (members.length === 0 && nested.length === 0) {
384
+ const size = emptyGroupSize(group);
385
+ return { id: `g:${group.id}`, width: size.width, height: size.height };
386
+ }
387
+ return {
388
+ id: `g:${group.id}`,
389
+ width: 0,
390
+ height: 0,
391
+ padding: {
392
+ top: groupTopPadding(group.label),
393
+ left: PAD_X,
394
+ bottom: PAD_X,
395
+ right: PAD_X
396
+ },
397
+ minWidth: Math.ceil(groupLabelWidth(group) + 2 * PAD_X),
398
+ children: [...members.map(nodeElk), ...nested.map(groupElk)]
399
+ };
400
+ };
401
+ const edges = doc.edges ?? [];
402
+ const elkEdges = edges.map((edge, index) => {
403
+ const elkEdge = {
404
+ id: `e:${index}`,
405
+ from: `n:${edge.from}`,
406
+ to: `n:${edge.to}`
407
+ };
408
+ if (edge.label !== undefined && edge.label !== "") {
409
+ const size = labelBoxSize(edge.label);
410
+ elkEdge.label = { width: size.width, height: size.height };
411
+ }
412
+ return elkEdge;
413
+ });
414
+ const result = await runElk(doc.direction ?? "down", [
415
+ ...(nodesByGroup.get(undefined) ?? []).map(nodeElk),
416
+ ...groups.filter(({ group }) => group.parent === undefined).map(({ group }) => groupElk(group))
417
+ ], elkEdges);
418
+ const boxOf = (id) => result.boxes.get(id) ?? { x: 0, y: 0, width: 0, height: 0 };
419
+ const shapeById = new Map(doc.nodes.map((node) => [node.id, node.shape]));
420
+ const laidOutEdges = edges.map((edge, index) => {
421
+ const route = result.routes.get(`e:${index}`);
422
+ const clipped = clipEnds(route?.points ?? [], shapeById.get(edge.from), boxOf(`n:${edge.from}`), shapeById.get(edge.to), boxOf(`n:${edge.to}`));
423
+ return laidOutEdge(edge, index, clipped, route?.labelBox);
424
+ });
425
+ return finish(doc, result.width, result.height, groups.map(({ group, depth }) => laidOutGroup(group, depth, boxOf(`g:${group.id}`))), doc.nodes.map((node) => laidOutNode(node, boxOf(`n:${node.id}`))), laidOutEdges);
426
+ }
427
+ function boundsOf(boxes) {
428
+ if (boxes.length === 0)
429
+ return { x: 0, y: 0, width: 0, height: 0 };
430
+ const minX = Math.min(...boxes.map((box) => box.x));
431
+ const minY = Math.min(...boxes.map((box) => box.y));
432
+ const maxX = Math.max(...boxes.map((box) => box.x + box.width));
433
+ const maxY = Math.max(...boxes.map((box) => box.y + box.height));
434
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
435
+ }
436
+ function layoutPrecomputed(doc) {
437
+ const nodeBoxes = new Map;
438
+ for (const node of doc.nodes) {
439
+ nodeBoxes.set(node.id, {
440
+ x: node.position?.x ?? 0,
441
+ y: node.position?.y ?? 0,
442
+ ...shapeSize(node.shape, nodeLabel(node), node.type, 80)
443
+ });
444
+ }
445
+ const groups = orderGroups(doc.groups ?? []);
446
+ const groupBoxes = new Map;
447
+ const compute = (group) => {
448
+ const cached = groupBoxes.get(group.id);
449
+ if (cached !== undefined)
450
+ return cached;
451
+ const parts = [];
452
+ for (const node of doc.nodes) {
453
+ if (node.group === group.id)
454
+ parts.push(nodeBoxes.get(node.id));
455
+ }
456
+ for (const { group: child } of groups) {
457
+ if (child.parent !== group.id)
458
+ continue;
459
+ const box = compute(child);
460
+ if (box !== undefined)
461
+ parts.push(box);
462
+ }
463
+ if (parts.length === 0)
464
+ return;
465
+ const bounds = boundsOf(parts);
466
+ const top = groupTopPadding(group.label);
467
+ const box = {
468
+ x: bounds.x - PAD_X,
469
+ y: bounds.y - top,
470
+ width: Math.max(bounds.width + 2 * PAD_X, Math.ceil(groupLabelWidth(group) + 2 * PAD_X)),
471
+ height: bounds.height + top + PAD_X
472
+ };
473
+ groupBoxes.set(group.id, box);
474
+ return box;
475
+ };
476
+ const emptyGroups = [];
477
+ for (const { group } of groups) {
478
+ if (compute(group) === undefined)
479
+ emptyGroups.push(group);
480
+ }
481
+ if (emptyGroups.length > 0) {
482
+ const bounds = boundsOf([...nodeBoxes.values(), ...groupBoxes.values()]);
483
+ let cursor = bounds.y + bounds.height + 20;
484
+ for (const group of emptyGroups) {
485
+ const size = emptyGroupSize(group);
486
+ groupBoxes.set(group.id, { x: bounds.x, y: cursor, ...size });
487
+ cursor += size.height + 20;
488
+ }
489
+ }
490
+ const shapeById = new Map(doc.nodes.map((node) => [node.id, node.shape]));
491
+ const labelBoxes = [];
492
+ const laidOutEdges = (doc.edges ?? []).map((edge, index) => {
493
+ const from = nodeBoxes.get(edge.from);
494
+ const to = nodeBoxes.get(edge.to);
495
+ const fromShape = shapeById.get(edge.from);
496
+ const toShape = shapeById.get(edge.to);
497
+ let points;
498
+ let anchor;
499
+ if (edge.from === edge.to) {
500
+ const right = from.x + from.width;
501
+ const mid = from.y + from.height / 2;
502
+ points = [
503
+ { x: right, y: mid - 8 },
504
+ { x: right + 20, y: mid - 8 },
505
+ { x: right + 20, y: mid + 8 },
506
+ { x: right, y: mid + 8 }
507
+ ];
508
+ anchor = { x: right + 20, y: mid };
509
+ } else {
510
+ const fromCenter = {
511
+ x: from.x + from.width / 2,
512
+ y: from.y + from.height / 2
513
+ };
514
+ const toCenter = { x: to.x + to.width / 2, y: to.y + to.height / 2 };
515
+ const start = clipToShape(fromShape, from, toCenter);
516
+ const end = clipToShape(toShape, to, fromCenter);
517
+ points = [start, end];
518
+ anchor = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
519
+ }
520
+ let labelBox;
521
+ if (edge.label !== undefined && edge.label !== "") {
522
+ const size = labelBoxSize(edge.label);
523
+ labelBox = {
524
+ x: anchor.x - size.width / 2,
525
+ y: anchor.y - size.height / 2,
526
+ ...size
527
+ };
528
+ labelBoxes.push(labelBox);
529
+ }
530
+ return laidOutEdge(edge, index, points, labelBox);
531
+ });
532
+ const bounds = boundsOf([
533
+ ...nodeBoxes.values(),
534
+ ...groupBoxes.values(),
535
+ ...labelBoxes,
536
+ ...laidOutEdges.flatMap((edge) => edge.points.map((point) => ({ ...point, width: 0, height: 0 })))
537
+ ]);
538
+ return finish(doc, bounds.x + bounds.width + MARGIN, bounds.y + bounds.height + MARGIN, groups.map(({ group, depth }) => laidOutGroup(group, depth, groupBoxes.get(group.id))), doc.nodes.map((node) => laidOutNode(node, nodeBoxes.get(node.id))), laidOutEdges);
539
+ }
540
+ function layoutGraph(doc) {
541
+ if (doc.nodes.length > 0 && doc.nodes.every((node) => node.position !== undefined)) {
542
+ return Promise.resolve(layoutPrecomputed(doc));
543
+ }
544
+ return layoutWithElk(doc);
545
+ }
546
+
547
+ // src/layout/sequence.ts
548
+ var MIN_GAP = 40;
549
+ var FIRST_ROW_OFFSET = 40;
550
+ var MIN_ROW = 36;
551
+ var LIFELINE_TAIL = 30;
552
+ var SELF_LABEL_OFFSET = 6;
553
+ function layoutSequence(doc) {
554
+ const sizes = doc.participants.map((participant) => boxSize(participant.label ?? participant.id, participant.type, 100));
555
+ const headerHeight = Math.max(...sizes.map((size) => size.height));
556
+ const indexOf = new Map;
557
+ doc.participants.forEach((participant, index) => indexOf.set(participant.id, index));
558
+ const gaps = [];
559
+ for (let i = 0;i < sizes.length - 1; i++) {
560
+ gaps.push(sizes[i].width / 2 + sizes[i + 1].width / 2 + MIN_GAP);
561
+ }
562
+ const requirements = [];
563
+ const selfExtent = [];
564
+ for (const message of doc.messages) {
565
+ const a = indexOf.get(message.from);
566
+ const b = indexOf.get(message.to);
567
+ const labelWidth = message.label === undefined || message.label === "" ? 0 : labelBoxSize(message.label).width;
568
+ if (a === b) {
569
+ const extent = SELF_LOOP_WIDTH + SELF_LABEL_OFFSET + labelWidth;
570
+ selfExtent.push({ participant: a, extent });
571
+ if (a < sizes.length - 1) {
572
+ requirements.push({ from: a, to: a + 1, distance: extent + 10 });
573
+ }
574
+ } else if (labelWidth > 0) {
575
+ requirements.push({
576
+ from: Math.min(a, b),
577
+ to: Math.max(a, b),
578
+ distance: labelWidth + 16
579
+ });
580
+ }
581
+ }
582
+ requirements.sort((x, y) => x.to - x.from - (y.to - y.from));
583
+ for (const requirement of requirements) {
584
+ const span = requirement.to - requirement.from;
585
+ let current = 0;
586
+ for (let k = requirement.from;k < requirement.to; k++)
587
+ current += gaps[k];
588
+ if (current < requirement.distance) {
589
+ const extra = (requirement.distance - current) / span;
590
+ for (let k = requirement.from;k < requirement.to; k++)
591
+ gaps[k] += extra;
592
+ }
593
+ }
594
+ const centers = [MARGIN + sizes[0].width / 2];
595
+ for (let i = 0;i < gaps.length; i++) {
596
+ centers.push(centers[i] + gaps[i]);
597
+ }
598
+ const participants = doc.participants.map((participant, index) => {
599
+ const size = sizes[index];
600
+ return compact({
601
+ id: participant.id,
602
+ label: participant.label ?? participant.id,
603
+ type: participant.type,
604
+ x: round(centers[index] - size.width / 2),
605
+ y: MARGIN,
606
+ width: size.width,
607
+ height: headerHeight,
608
+ lifelineX: round(centers[index]),
609
+ meta: participant.meta
610
+ });
611
+ });
612
+ let cursor = MARGIN + headerHeight + FIRST_ROW_OFFSET;
613
+ const messages = doc.messages.map((message, index) => {
614
+ const a = indexOf.get(message.from);
615
+ const b = indexOf.get(message.to);
616
+ const self = a === b;
617
+ const hasLabel = message.label !== undefined && message.label !== "";
618
+ const textHeight = hasLabel ? measureText2(message.label, EDGE_LABEL_FONT).height : 0;
619
+ const row = Math.max(MIN_ROW, textHeight + 20);
620
+ const x1 = centers[a];
621
+ const x2 = centers[b];
622
+ let y;
623
+ let rowHeight;
624
+ let labelBox;
625
+ if (self) {
626
+ rowHeight = row * 1.5;
627
+ y = cursor + 10;
628
+ if (hasLabel) {
629
+ const size = labelBoxSize(message.label);
630
+ labelBox = {
631
+ x: x1 + SELF_LOOP_WIDTH + SELF_LABEL_OFFSET,
632
+ y: y + SELF_LOOP_HEIGHT / 2 - size.height / 2,
633
+ ...size
634
+ };
635
+ }
636
+ } else {
637
+ rowHeight = row;
638
+ y = cursor + row - 8;
639
+ if (hasLabel) {
640
+ const size = labelBoxSize(message.label);
641
+ labelBox = {
642
+ x: (x1 + x2) / 2 - size.width / 2,
643
+ y: y - 3 - size.height,
644
+ ...size
645
+ };
646
+ }
647
+ }
648
+ cursor += rowHeight;
649
+ return compact({
650
+ index,
651
+ from: message.from,
652
+ to: message.to,
653
+ label: message.label,
654
+ style: message.style ?? "sync",
655
+ y: round(y),
656
+ x1: round(x1),
657
+ x2: round(x2),
658
+ self,
659
+ labelBox: labelBox === undefined ? undefined : {
660
+ x: round(labelBox.x),
661
+ y: round(labelBox.y),
662
+ width: labelBox.width,
663
+ height: labelBox.height
664
+ },
665
+ meta: message.meta
666
+ });
667
+ });
668
+ const lifelineBottom = cursor + LIFELINE_TAIL;
669
+ let right = 0;
670
+ for (let i = 0;i < sizes.length; i++) {
671
+ right = Math.max(right, centers[i] + sizes[i].width / 2);
672
+ }
673
+ for (const { participant, extent } of selfExtent) {
674
+ right = Math.max(right, centers[participant] + extent);
675
+ }
676
+ return compact({
677
+ kind: "sequence",
678
+ width: round(right + MARGIN),
679
+ height: round(lifelineBottom + MARGIN),
680
+ title: doc.title,
681
+ participants,
682
+ messages,
683
+ lifelineBottom: round(lifelineBottom)
684
+ });
685
+ }
686
+
687
+ // src/layout/state.ts
688
+ var CLIP_SHAPES = {
689
+ initial: "circle",
690
+ final: "circle",
691
+ history: "circle",
692
+ choice: "diamond"
693
+ };
694
+ function stateLabel(state) {
695
+ return state.label ?? state.id;
696
+ }
697
+ function pseudoSize(pseudo, vertical) {
698
+ switch (pseudo) {
699
+ case "initial":
700
+ return { width: 20, height: 20 };
701
+ case "final":
702
+ case "history":
703
+ return { width: 24, height: 24 };
704
+ case "choice":
705
+ return { width: 28, height: 28 };
706
+ case "fork":
707
+ case "join":
708
+ return vertical ? { width: 6, height: 64 } : { width: 64, height: 6 };
709
+ }
710
+ }
711
+ function simpleSize(state) {
712
+ const base = boxSize(stateLabel(state), state.type, 80);
713
+ const actions = state.actions ?? [];
714
+ if (actions.length === 0)
715
+ return base;
716
+ return {
717
+ width: Math.ceil(Math.max(base.width, actionsWidth(actions) + 2 * PAD_X)),
718
+ height: Math.ceil(base.height + actionsHeight(actions.length) + PAD_Y)
719
+ };
720
+ }
721
+ async function layoutState(doc) {
722
+ const direction = doc.direction ?? "down";
723
+ const children = new Map;
724
+ for (const state of doc.states) {
725
+ const list = children.get(state.parent) ?? [];
726
+ list.push(state);
727
+ children.set(state.parent, list);
728
+ }
729
+ const stateElk = (state) => {
730
+ const members = children.get(state.id);
731
+ if (members === undefined) {
732
+ const size = state.pseudo === undefined ? simpleSize(state) : pseudoSize(state.pseudo, direction === "right" || direction === "left");
733
+ return { id: `s:${state.id}`, width: size.width, height: size.height };
734
+ }
735
+ const title = stateLabel(state);
736
+ const actions = state.actions ?? [];
737
+ return {
738
+ id: `s:${state.id}`,
739
+ width: 0,
740
+ height: 0,
741
+ padding: {
742
+ top: groupTopPadding(title) + actionsHeight(actions.length),
743
+ left: PAD_X,
744
+ bottom: PAD_X,
745
+ right: PAD_X
746
+ },
747
+ minWidth: Math.ceil(Math.max(measureText2(title, GROUP_FONT).width, actionsWidth(actions)) + 2 * PAD_X),
748
+ children: members.map(stateElk)
749
+ };
750
+ };
751
+ const transitions = doc.transitions ?? [];
752
+ const labels = transitions.map(transitionLabel2);
753
+ const elkEdges = transitions.map((transition, index) => {
754
+ const edge = {
755
+ id: `t:${index}`,
756
+ from: `s:${transition.from}`,
757
+ to: `s:${transition.to}`
758
+ };
759
+ const label = labels[index];
760
+ if (label !== "") {
761
+ const size = labelBoxSize(label);
762
+ edge.label = { width: size.width, height: size.height };
763
+ }
764
+ return edge;
765
+ });
766
+ const result = await runElk(direction, (children.get(undefined) ?? []).map(stateElk), elkEdges);
767
+ const boxOf = (id) => result.boxes.get(`s:${id}`) ?? { x: 0, y: 0, width: 0, height: 0 };
768
+ const byId = new Map(doc.states.map((state) => [state.id, state]));
769
+ const depthOf = (state) => {
770
+ let depth = 0;
771
+ for (let parent = state.parent;parent !== undefined; parent = byId.get(parent)?.parent) {
772
+ depth += 1;
773
+ }
774
+ return depth;
775
+ };
776
+ const clipShape = (id) => {
777
+ const pseudo = byId.get(id)?.pseudo;
778
+ return pseudo === undefined ? undefined : CLIP_SHAPES[pseudo];
779
+ };
780
+ const laidOutStates = doc.states.map((state) => {
781
+ const box = boxOf(state.id);
782
+ return compact({
783
+ id: state.id,
784
+ label: stateLabel(state),
785
+ type: state.type,
786
+ pseudo: state.pseudo,
787
+ composite: children.has(state.id),
788
+ parent: state.parent,
789
+ depth: depthOf(state),
790
+ actions: state.actions,
791
+ description: state.description,
792
+ link: state.link,
793
+ x: round(box.x),
794
+ y: round(box.y),
795
+ width: round(box.width),
796
+ height: round(box.height),
797
+ meta: state.meta
798
+ });
799
+ });
800
+ const laidOutTransitions = transitions.map((transition, index) => {
801
+ const route = result.routes.get(`t:${index}`);
802
+ const points = clipEnds(route?.points ?? [], clipShape(transition.from), boxOf(transition.from), clipShape(transition.to), boxOf(transition.to)).map((point) => ({ x: round(point.x), y: round(point.y) }));
803
+ const labelBox = route?.labelBox;
804
+ return compact({
805
+ id: transition.id ?? `t${index}`,
806
+ from: transition.from,
807
+ to: transition.to,
808
+ label: labels[index] === "" ? undefined : labels[index],
809
+ event: transition.event,
810
+ guard: transition.guard,
811
+ action: transition.action,
812
+ type: transition.type,
813
+ points,
814
+ labelBox: labelBox === undefined ? undefined : {
815
+ x: round(labelBox.x),
816
+ y: round(labelBox.y),
817
+ width: round(labelBox.width),
818
+ height: round(labelBox.height)
819
+ },
820
+ meta: transition.meta
821
+ });
822
+ });
823
+ return compact({
824
+ kind: "state",
825
+ width: round(result.width),
826
+ height: round(result.height),
827
+ title: doc.title,
828
+ states: laidOutStates,
829
+ transitions: laidOutTransitions
830
+ });
831
+ }
832
+
833
+ // src/layout/tree.ts
834
+ var TREE_GAPS = { level: 48, sibling: 20 };
835
+ var MINDMAP_GAPS = { level: 40, sibling: 12 };
836
+ var AXES = {
837
+ down: {
838
+ breadth: (size) => size.width,
839
+ depth: (size) => size.height,
840
+ at: (breadth, depth) => ({ x: breadth, y: depth })
841
+ },
842
+ up: {
843
+ breadth: (size) => size.width,
844
+ depth: (size) => size.height,
845
+ at: (breadth, depth) => ({ x: breadth, y: -depth })
846
+ },
847
+ right: {
848
+ breadth: (size) => size.height,
849
+ depth: (size) => size.width,
850
+ at: (breadth, depth) => ({ x: depth, y: breadth })
851
+ },
852
+ left: {
853
+ breadth: (size) => size.height,
854
+ depth: (size) => size.width,
855
+ at: (breadth, depth) => ({ x: -depth, y: breadth })
856
+ }
857
+ };
858
+ function place(root, first, kids, sizes, axes, gaps) {
859
+ const childrenOf = (id) => id === root ? first : kids.get(id) ?? [];
860
+ const level = new Map([[root, 0]]);
861
+ const order = [];
862
+ const stack = [root];
863
+ while (stack.length > 0) {
864
+ const id = stack.pop();
865
+ order.push(id);
866
+ const list = childrenOf(id);
867
+ for (let index = list.length - 1;index >= 0; index--) {
868
+ const child = list[index];
869
+ level.set(child, level.get(id) + 1);
870
+ stack.push(child);
871
+ }
872
+ }
873
+ const contours = new Map;
874
+ const relative = new Map;
875
+ for (let position = order.length - 1;position >= 0; position--) {
876
+ const id = order[position];
877
+ const extent = axes.breadth(sizes.get(id));
878
+ const list = childrenOf(id);
879
+ if (list.length === 0) {
880
+ contours.set(id, [[-extent / 2, extent / 2]]);
881
+ continue;
882
+ }
883
+ const merged = [];
884
+ const offsets = [];
885
+ for (const child of list) {
886
+ const contour = contours.get(child);
887
+ let offset = 0;
888
+ if (offsets.length > 0) {
889
+ offset = -Infinity;
890
+ const common = Math.min(merged.length, contour.length);
891
+ for (let depth = 0;depth < common; depth++) {
892
+ offset = Math.max(offset, merged[depth][1] - contour[depth][0] + gaps.sibling);
893
+ }
894
+ }
895
+ offsets.push(offset);
896
+ contour.forEach(([min, max], depth) => {
897
+ const shifted = [min + offset, max + offset];
898
+ const current = merged[depth];
899
+ if (current === undefined)
900
+ merged.push(shifted);
901
+ else
902
+ merged[depth] = [Math.min(current[0], shifted[0]), Math.max(current[1], shifted[1])];
903
+ });
904
+ contours.delete(child);
905
+ }
906
+ const center = (offsets[0] + offsets[offsets.length - 1]) / 2;
907
+ list.forEach((child, index) => relative.set(child, offsets[index] - center));
908
+ contours.set(id, [
909
+ [-extent / 2, extent / 2],
910
+ ...merged.map(([min, max]) => [min - center, max - center])
911
+ ]);
912
+ }
913
+ const breadth = new Map([[root, 0]]);
914
+ for (const id of order) {
915
+ for (const child of childrenOf(id)) {
916
+ breadth.set(child, breadth.get(id) + relative.get(child));
917
+ }
918
+ }
919
+ const extents = [];
920
+ for (const id of order) {
921
+ const at = level.get(id);
922
+ extents[at] = Math.max(extents[at] ?? 0, axes.depth(sizes.get(id)));
923
+ }
924
+ const origin = (extents[0] ?? 0) / 2;
925
+ const centers = [];
926
+ const levelEnd = [];
927
+ let cursor = 0;
928
+ extents.forEach((extent, at) => {
929
+ centers[at] = cursor + extent / 2 - origin;
930
+ levelEnd[at] = cursor + extent - origin;
931
+ cursor += extent + gaps.level;
932
+ });
933
+ const depth = new Map;
934
+ for (const id of order)
935
+ depth.set(id, centers[level.get(id)]);
936
+ return { breadth, depth, level, levelEnd };
937
+ }
938
+ function boxAround(center, size) {
939
+ return {
940
+ x: center.x - size.width / 2,
941
+ y: center.y - size.height / 2,
942
+ width: size.width,
943
+ height: size.height
944
+ };
945
+ }
946
+ function leafCounts(order, kids) {
947
+ const counts = new Map;
948
+ for (let index = order.length - 1;index >= 0; index--) {
949
+ const id = order[index];
950
+ const list = kids.get(id);
951
+ counts.set(id, list === undefined || list.length === 0 ? 1 : list.reduce((sum, child) => sum + counts.get(child), 0));
952
+ }
953
+ return counts;
954
+ }
955
+ function layoutTree(doc) {
956
+ const mindmap = doc.layout === "mindmap";
957
+ const kids = new Map;
958
+ const parentOf = new Map;
959
+ let root = "";
960
+ for (const node of doc.nodes) {
961
+ if (node.parent === undefined) {
962
+ root = node.id;
963
+ continue;
964
+ }
965
+ parentOf.set(node.id, node.parent);
966
+ const list = kids.get(node.parent) ?? [];
967
+ list.push(node.id);
968
+ kids.set(node.parent, list);
969
+ }
970
+ const byId = new Map(doc.nodes.map((node) => [node.id, node]));
971
+ const sizes = new Map(doc.nodes.map((node) => [node.id, shapeSize(node.shape, node.label, node.type, 80)]));
972
+ const order = [];
973
+ const depthOf = new Map([[root, 0]]);
974
+ const stack = [root];
975
+ while (stack.length > 0) {
976
+ const id = stack.pop();
977
+ order.push(id);
978
+ const list = kids.get(id) ?? [];
979
+ for (let index = list.length - 1;index >= 0; index--) {
980
+ depthOf.set(list[index], depthOf.get(id) + 1);
981
+ stack.push(list[index]);
982
+ }
983
+ }
984
+ const boxes = new Map;
985
+ const sides = new Map;
986
+ const routes = new Map;
987
+ if (!mindmap) {
988
+ const axes = AXES[doc.direction ?? "down"];
989
+ const placement = place(root, kids.get(root) ?? [], kids, sizes, axes, TREE_GAPS);
990
+ for (const id of order) {
991
+ const center = axes.at(placement.breadth.get(id), placement.depth.get(id));
992
+ boxes.set(id, boxAround(center, sizes.get(id)));
993
+ }
994
+ for (const id of order) {
995
+ const parent = parentOf.get(id);
996
+ if (parent === undefined)
997
+ continue;
998
+ const parentBreadth = placement.breadth.get(parent);
999
+ const childBreadth = placement.breadth.get(id);
1000
+ const start = axes.at(parentBreadth, placement.depth.get(parent) + axes.depth(sizes.get(parent)) / 2);
1001
+ const end = axes.at(childBreadth, placement.depth.get(id) - axes.depth(sizes.get(id)) / 2);
1002
+ const middle = placement.levelEnd[placement.level.get(parent)] + TREE_GAPS.level / 2;
1003
+ routes.set(id, {
1004
+ curve: "elbow",
1005
+ points: round(parentBreadth) === round(childBreadth) ? [start, end] : [start, axes.at(parentBreadth, middle), axes.at(childBreadth, middle), end]
1006
+ });
1007
+ }
1008
+ } else {
1009
+ boxes.set(root, boxAround({ x: 0, y: 0 }, sizes.get(root)));
1010
+ const rootKids = kids.get(root) ?? [];
1011
+ const leaves = leafCounts(order, kids);
1012
+ const total = rootKids.reduce((sum, child) => sum + leaves.get(child), 0);
1013
+ let count = 0;
1014
+ for (let cumulative = 0;count < rootKids.length && cumulative * 2 < total; count++) {
1015
+ cumulative += leaves.get(rootKids[count]);
1016
+ }
1017
+ for (const [side, first] of [
1018
+ ["right", rootKids.slice(0, count)],
1019
+ ["left", rootKids.slice(count)]
1020
+ ]) {
1021
+ if (first.length === 0)
1022
+ continue;
1023
+ const axes = AXES[side];
1024
+ const placement = place(root, first, kids, sizes, axes, MINDMAP_GAPS);
1025
+ for (const id of order) {
1026
+ if (id === root || !placement.level.has(id))
1027
+ continue;
1028
+ sides.set(id, side);
1029
+ const center = axes.at(placement.breadth.get(id), placement.depth.get(id));
1030
+ boxes.set(id, boxAround(center, sizes.get(id)));
1031
+ }
1032
+ }
1033
+ for (const id of order) {
1034
+ const parent = parentOf.get(id);
1035
+ if (parent === undefined)
1036
+ continue;
1037
+ const from = boxes.get(parent);
1038
+ const to = boxes.get(id);
1039
+ const right = sides.get(id) === "right";
1040
+ const start = {
1041
+ x: right ? from.x + from.width : from.x,
1042
+ y: from.y + from.height / 2
1043
+ };
1044
+ const end = {
1045
+ x: right ? to.x : to.x + to.width,
1046
+ y: to.y + to.height / 2
1047
+ };
1048
+ const dx = end.x - start.x;
1049
+ routes.set(id, {
1050
+ curve: "bezier",
1051
+ points: [
1052
+ start,
1053
+ { x: start.x + dx / 2, y: start.y },
1054
+ { x: end.x - dx / 2, y: end.y },
1055
+ end
1056
+ ]
1057
+ });
1058
+ }
1059
+ }
1060
+ let minX = Infinity;
1061
+ let minY = Infinity;
1062
+ let maxX = -Infinity;
1063
+ let maxY = -Infinity;
1064
+ for (const box of boxes.values()) {
1065
+ minX = Math.min(minX, box.x);
1066
+ minY = Math.min(minY, box.y);
1067
+ maxX = Math.max(maxX, box.x + box.width);
1068
+ maxY = Math.max(maxY, box.y + box.height);
1069
+ }
1070
+ const shiftX = MARGIN - minX;
1071
+ const shiftY = MARGIN - minY;
1072
+ const moved = (point) => ({
1073
+ x: round(point.x + shiftX),
1074
+ y: round(point.y + shiftY)
1075
+ });
1076
+ const nodes = order.map((id) => {
1077
+ const node = byId.get(id);
1078
+ const box = boxes.get(id);
1079
+ return compact({
1080
+ id,
1081
+ label: node.label,
1082
+ type: node.type,
1083
+ shape: node.shape,
1084
+ x: round(box.x + shiftX),
1085
+ y: round(box.y + shiftY),
1086
+ width: round(box.width),
1087
+ height: round(box.height),
1088
+ link: node.link,
1089
+ description: node.description,
1090
+ meta: node.meta,
1091
+ depth: depthOf.get(id),
1092
+ parent: node.parent,
1093
+ side: sides.get(id)
1094
+ });
1095
+ });
1096
+ const edges = [];
1097
+ for (const id of order) {
1098
+ const parent = parentOf.get(id);
1099
+ const route = routes.get(id);
1100
+ if (parent === undefined || route === undefined)
1101
+ continue;
1102
+ edges.push({ id, from: parent, to: id, points: route.points.map(moved), curve: route.curve });
1103
+ }
1104
+ return compact({
1105
+ kind: "tree",
1106
+ layout: mindmap ? "mindmap" : "tree",
1107
+ width: round(maxX - minX + 2 * MARGIN),
1108
+ height: round(maxY - minY + 2 * MARGIN),
1109
+ title: doc.title,
1110
+ nodes,
1111
+ edges
1112
+ });
1113
+ }
1114
+
1115
+ // src/layout/index.ts
1116
+ async function layout2(document) {
1117
+ const result = validate2(document);
1118
+ if (!result.ok) {
1119
+ const lines = result.errors.map((error) => `${error.path === "" ? "/" : error.path}: ${error.message}`);
1120
+ throw new Error(`Invalid document:
1121
+ ${lines.join(`
1122
+ `)}`);
1123
+ }
1124
+ const doc = result.document;
1125
+ switch (doc.kind) {
1126
+ case "graph":
1127
+ return layoutGraph(doc);
1128
+ case "sequence":
1129
+ return layoutSequence(doc);
1130
+ case "state":
1131
+ return layoutState(doc);
1132
+ case "er":
1133
+ return layoutEr(doc);
1134
+ case "tree":
1135
+ return layoutTree(doc);
1136
+ default:
1137
+ return unreachable(doc);
1138
+ }
1139
+ }
1140
+ function unreachable(value) {
1141
+ throw new Error(`Unsupported document: ${JSON.stringify(value)}`);
1142
+ }
1143
+
1144
+ export { layout2 };