@sccharts-lab/diagram 0.0.0-stage → 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.
Files changed (44) hide show
  1. package/LICENSE +277 -0
  2. package/README.md +169 -2
  3. package/dist/dataflow.d.ts +18 -0
  4. package/dist/dataflow.js +216 -0
  5. package/dist/dataflow.js.map +1 -0
  6. package/dist/diagram.css +521 -0
  7. package/dist/elk-types.d.ts +50 -0
  8. package/dist/elk-types.js +5 -0
  9. package/dist/elk-types.js.map +1 -0
  10. package/dist/elk-worker.d.ts +10 -0
  11. package/dist/elk-worker.js +18 -0
  12. package/dist/elk-worker.js.map +1 -0
  13. package/dist/font-metrics.d.ts +13 -0
  14. package/dist/font-metrics.js +23 -0
  15. package/dist/font-metrics.js.map +1 -0
  16. package/dist/fonts/atkinson-hyperlegible-mono-latin-ext-wght-normal.woff2 +0 -0
  17. package/dist/fonts/atkinson-hyperlegible-mono-latin-wght-normal.woff2 +0 -0
  18. package/dist/fonts/atkinson-hyperlegible-mono.LICENSE.txt +93 -0
  19. package/dist/fonts/atkinson-hyperlegible-next-latin-ext-wght-normal.woff2 +0 -0
  20. package/dist/fonts/atkinson-hyperlegible-next-latin-wght-normal.woff2 +0 -0
  21. package/dist/fonts/atkinson-hyperlegible-next.LICENSE.txt +93 -0
  22. package/dist/fonts.css +42 -0
  23. package/dist/geometry.d.ts +24 -0
  24. package/dist/geometry.js +115 -0
  25. package/dist/geometry.js.map +1 -0
  26. package/dist/highlight.d.ts +35 -0
  27. package/dist/highlight.js +83 -0
  28. package/dist/highlight.js.map +1 -0
  29. package/dist/index.d.ts +16 -0
  30. package/dist/index.js +32 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/layout.d.ts +6 -0
  33. package/dist/layout.js +838 -0
  34. package/dist/layout.js.map +1 -0
  35. package/dist/measure.d.ts +23 -0
  36. package/dist/measure.js +73 -0
  37. package/dist/measure.js.map +1 -0
  38. package/dist/render.d.ts +3 -0
  39. package/dist/render.js +327 -0
  40. package/dist/render.js.map +1 -0
  41. package/dist/types.d.ts +221 -0
  42. package/dist/types.js +4 -0
  43. package/dist/types.js.map +1 -0
  44. package/package.json +70 -3
package/dist/layout.js ADDED
@@ -0,0 +1,838 @@
1
+ // layoutChart: KIELER's SCCharts diagram synthesis, reduced to what the guide needs, laid out with ELK.
2
+ //
3
+ // The ELK graph mirrors the one KIELER builds (sccharts.ui/.../synthesis/: StateSynthesis,
4
+ // ControlflowRegionSynthesis, TransitionSynthesis, the styles/ and hooks/ LayoutHook, ModelOrderHook,
5
+ // LabelPlacementSideHook, LabelShorteningHook), with the same layout options:
6
+ // - a state lays out its regions with rectpacking (regions expanded to fill, 5 apart);
7
+ // - a control-flow region lays out its states with ELK Layered, spline edges, inline ("on edge") labels,
8
+ // model order respected, the initial state in the first layer, and the direction alternating with the
9
+ // nesting depth (KIELER's default "HV": top level left to right, the next level top to bottom, ...);
10
+ // - sizes and paddings are KIELER's (simple states 34 px minimum with 10/8 px text padding, superstate title
11
+ // rows, 20 px region headers, ...). Text is measured with the guide's diagram font instead of KIELER's.
12
+ import { actionSegments, createFormatContext, declarationLines, formatEquation, formatExpression, isImplicitlyImmediate, mergeComponents, regionLabelSegments, stateDisplayName, stateTitleSegments, transitionLabelLines, } from "@sccharts-lab/engine/format";
13
+ import { buildCircuit } from "./dataflow.js";
14
+ import { flatten, nearest, r2 } from "./geometry.js";
15
+ import { lineMetrics, measureWithTable } from "./measure.js";
16
+ // ----- KIELER's constants ----------------------------------------------------------------------------
17
+ const STATE_LABEL = { size: 11, bold: true }; // StateStyles.addSimpleStateLabel
18
+ const TITLE = { size: 11 }; // StateStyles.addMacroStateLabel
19
+ const DECLARATION = { size: 10 }; // KLighD's default font size
20
+ const REGION_LABEL = { size: 10 }; // ControlflowRegionStyles.addRegionButton
21
+ const EDGE_LABEL = { size: 11, bold: true }; // TransitionStyles.configureTransitionLabelRendering
22
+ const EQUATION = { size: 10, mono: true };
23
+ // CommentStyles.addCommentText draws comment text at 7 pt; 9 here, so that it stays legible at the guide's scale.
24
+ const COMMENT = { size: 9 };
25
+ const COMMENT_PAD = 4; // CommentStyles: from(LEFT 4, TOP 4).to(RIGHT 4, BOTTOM 4)
26
+ const COMMENT_MIN = 16; // CommentStyles: setMinimalNodeSize(16, 16)
27
+ const CORNER = 17; // DEFAULT_FIGURE_CORNER_RADIUS
28
+ const MIN_SIZE = 2 * CORNER; // DEFAULT_FIGURE_MIN_NODE_SIZE
29
+ const CONNECTOR_SIZE = 10;
30
+ const MACRO_CORNER = 8;
31
+ const LABEL_PAD_X = 10; // simple state label and superstate title: from(LEFT 10, TOP 8).to(RIGHT 10, BOTTOM 8)
32
+ const LABEL_PAD_Y = 8;
33
+ const EMPTY_TITLE = 10; // addEmptyStateLabel
34
+ const BLOCK_PAD_X = 8; // declaration/action containers: from(LEFT 8, TOP -4).to(RIGHT 8, BOTTOM 6)
35
+ const BLOCK_PAD_TOP = -4;
36
+ const BLOCK_PAD_BOTTOM = 6;
37
+ const INDENT = 10;
38
+ const REGION_LABEL_X = 16.5;
39
+ const REGION_LABEL_Y = 1;
40
+ const REGION_HEADER = 20;
41
+ const REGION_PAD = 10;
42
+ const EDGE_LABEL_PAD = 2;
43
+ const DEFAULT_LABEL_WIDTH = 200; // LabelShorteningHook.SHORTEN_LABEL_WIDTH
44
+ const SOFTWRAP_FUZZINESS = 0.3;
45
+ // ----- ELK -------------------------------------------------------------------------------------------
46
+ //
47
+ // This module never loads ELK itself: the caller passes an instance (`options.elk`). `layoutChart` in
48
+ // ./index.ts supplies elkjs's bundled build (1.4 MB) when none is given, for Node and build-time rendering;
49
+ // the playground imports this module directly with a Web Worker behind elk-api, so its bundle never contains
50
+ // (or fetches) the bundled build.
51
+ const opt = (o) => {
52
+ const out = {};
53
+ for (const [k, v] of Object.entries(o))
54
+ if (v !== undefined)
55
+ out[k.startsWith('org.') ? k : `org.eclipse.elk.${k}`] = String(v);
56
+ return out;
57
+ };
58
+ const padding = (top, right, bottom, left) => `[top=${r2(top)},left=${r2(left)},bottom=${r2(bottom)},right=${r2(right)}]`;
59
+ /** StateSynthesis.configureLayout */
60
+ const STATE_LAYOUT = opt({
61
+ algorithm: 'org.eclipse.elk.rectpacking',
62
+ expandNodes: true,
63
+ 'rectpacking.whiteSpaceElimination.strategy': 'EQUAL_BETWEEN_STRUCTURES',
64
+ omitNodeMicroLayout: true,
65
+ 'spacing.nodeNode': 5,
66
+ });
67
+ /** ControlflowRegionSynthesis (KLay layered branch) + ModelOrderHook (tie-breaker) + LabelPlacementSideHook. */
68
+ const REGION_LAYOUT = opt({
69
+ algorithm: 'org.eclipse.elk.layered',
70
+ contentAlignment: 'V_TOP H_CENTER',
71
+ 'layered.nodePlacement.bk.fixedAlignment': 'BALANCED',
72
+ 'layered.edgeLabels.centerLabelPlacementStrategy': 'TAIL_LAYER',
73
+ 'nodeSize.constraints': 'MINIMUM_SIZE',
74
+ 'spacing.nodeSelfLoop': 18,
75
+ edgeRouting: 'SPLINES',
76
+ separateConnectedComponents: false,
77
+ 'layered.cycleBreaking.strategy': 'MODEL_ORDER',
78
+ 'layered.considerModelOrder.strategy': 'PREFER_EDGES',
79
+ 'layered.considerModelOrder.crossingCounterPortInfluence': 0.01,
80
+ 'layered.considerModelOrder.crossingCounterNodeInfluence': 0.01,
81
+ });
82
+ const LABEL_LAYOUT = opt({ 'edgeLabels.inline': true, 'edgeLabels.placement': 'CENTER' });
83
+ function makeLine(ctx, role, style, segments, indent = 0, ids) {
84
+ const runs = [];
85
+ let dx = 0;
86
+ for (const seg of segments) {
87
+ if (!seg.text)
88
+ continue;
89
+ const bold = style.bold || seg.format === 'keyword';
90
+ const width = ctx.measure(seg.text, { ...style, bold });
91
+ const text = seg.text.replace(/\s+$/, '');
92
+ if (text)
93
+ runs.push({ text, dx: r2(dx), width: r2(ctx.measure(text, { ...style, bold })), format: seg.format });
94
+ dx += width;
95
+ }
96
+ const last = runs[runs.length - 1];
97
+ return { role, style, runs, width: last ? last.dx + last.width : 0, indent, ids };
98
+ }
99
+ function plainLine(ctx, role, style, text) {
100
+ // Leading spaces (indentation of continued effect lines) become an offset.
101
+ const lead = /^ */.exec(text)[0];
102
+ const offset = lead ? ctx.measure(lead, style) : 0;
103
+ const body = text.slice(lead.length).replace(/\s+$/, '');
104
+ const width = body ? ctx.measure(body, style) : 0;
105
+ return { role, style, runs: body ? [{ text: body, dx: r2(offset), width: r2(width), format: 'text' }] : [], width: offset + width, indent: 0 };
106
+ }
107
+ /** KLighD's SoftWrappingLabelManager (approximately): wrap at spaces so lines stay within `target`, and
108
+ * pull a short remainder (< fuzziness × target) back onto the previous line. */
109
+ function softWrap(ctx, text, style, target) {
110
+ if (target <= 0 || ctx.measure(text, style) <= target)
111
+ return [text];
112
+ const lead = /^ */.exec(text)[0];
113
+ const words = text.slice(lead.length).split(' ').filter(w => w.length > 0);
114
+ const width = (s) => ctx.measure(s, style);
115
+ const limit = Math.max(target, ...words.map(width));
116
+ const lines = [];
117
+ let i = 0;
118
+ while (i < words.length) {
119
+ let line = (lines.length === 0 ? lead : '') + words[i++];
120
+ while (i < words.length && width(line + ' ' + words[i]) <= limit)
121
+ line += ' ' + words[i++];
122
+ const rest = words.slice(i).join(' ');
123
+ if (rest && width(rest) < limit * SOFTWRAP_FUZZINESS && width(line + ' ' + rest) <= limit * (1 + SOFTWRAP_FUZZINESS)) {
124
+ line += ' ' + rest;
125
+ i = words.length;
126
+ }
127
+ lines.push(line);
128
+ }
129
+ return lines;
130
+ }
131
+ function hasAnnotation(annotations, name) {
132
+ return !!annotations?.some(a => a.name.toLowerCase() === name.toLowerCase());
133
+ }
134
+ function directionAnnotation(annotations) {
135
+ for (const a of annotations ?? []) {
136
+ if (a.name !== 'layout')
137
+ continue;
138
+ const key = (a.type ?? a.values[0] ?? '').toLowerCase();
139
+ const value = (a.type ? a.values[0] : a.values[1])?.toUpperCase();
140
+ if (/(^|\.)direction$/.test(key) && (value === 'RIGHT' || value === 'DOWN' || value === 'LEFT' || value === 'UP'))
141
+ return value;
142
+ }
143
+ return undefined;
144
+ }
145
+ function alternating(annotations) {
146
+ for (const a of [...(annotations ?? [])].reverse()) {
147
+ const n = a.name.toLowerCase();
148
+ if (n === 'hvlayout')
149
+ return true;
150
+ if (n === 'vhlayout')
151
+ return false;
152
+ }
153
+ return undefined;
154
+ }
155
+ /** LayoutHook.setDepthDirection */
156
+ function depthDirection(isHV, depth) {
157
+ return isHV !== (depth % 2 === 0) ? 'DOWN' : 'RIGHT';
158
+ }
159
+ /** KIELER's StateSynthesis.isMacroState */
160
+ function isMacro(s) {
161
+ return s.regions.some(r => (r.regionType === 'controlflow' && r.states.length > 0) || r.regionType === 'dataflow')
162
+ || s.actions.length > 0 || s.declarations.length > 0 || !!s.reference || !!s.baseStates?.length;
163
+ }
164
+ function hasChildArea(s) {
165
+ return s.regions.some(r => (r.regionType === 'controlflow' && r.states.length > 0) || r.regionType === 'dataflow') || !!s.reference
166
+ || s.declarations.some(d => d.declKind === 'method');
167
+ }
168
+ function synthState(ctx, s, hv) {
169
+ const shape = s.isRoot ? 'root' : s.connector ? 'connector' : isMacro(s) ? 'superstate' : 'simple';
170
+ const initial = s.initial && !s.isRoot;
171
+ let lineWidth = initial ? 3 : 1;
172
+ // StateStyles.setFinalStyle: a second border, `offset` inside.
173
+ let finalInset = s.final && shape !== 'connector' ? lineWidth + (lineWidth === 1 ? 2 : 1) : 0;
174
+ // StateStyles.setViolationStyle: a violation state that cannot be left gets a double, 2 px border.
175
+ if (s.violation && shape !== 'connector' && !s.final && s.transitions.every(t => t.target === s.id)) {
176
+ finalInset = lineWidth + (lineWidth === 1 ? 3 : 1);
177
+ lineWidth = 2;
178
+ }
179
+ const v = {
180
+ ast: s, id: s.id, shape, initial, final: s.final, reference: !!s.reference, lineWidth,
181
+ radius: shape === 'simple' ? CORNER : MACRO_CORNER, finalInset, lines: [], regions: [], width: 0, height: 0, comments: [],
182
+ };
183
+ // CommentSynthesis: a comment node next to the state, joined to it by an edge (laid out as an ELK comment box),
184
+ // one per doc comment. The root's comments are placed in layoutChart.
185
+ if (ctx.comments && !s.isRoot)
186
+ docComments(s).forEach((text, i) => v.comments.push(synthComment(ctx, commentId(s.id, i), text, s.id)));
187
+ if (shape === 'connector') {
188
+ v.width = v.height = CONNECTOR_SIZE;
189
+ v.radius = 7;
190
+ return v;
191
+ }
192
+ const nameMetrics = lineMetrics(STATE_LABEL);
193
+ if (shape === 'simple') {
194
+ const name = stateDisplayName(s, ctx.format);
195
+ const line = makeLine(ctx, 'state-label', STATE_LABEL, [{ text: name, format: 'text' }]);
196
+ const inner = { w: Math.max(MIN_SIZE, line.width + 2 * LABEL_PAD_X), h: Math.max(MIN_SIZE, nameMetrics.lineHeight + 2 * LABEL_PAD_Y) };
197
+ v.width = inner.w + 2 * finalInset;
198
+ v.height = inner.h + 2 * finalInset;
199
+ v.radius = CORNER + finalInset;
200
+ // An empty label (`state S ""`) leaves the state blank (addEmptyStateLabel).
201
+ if (name)
202
+ v.lines.push({ line, y: finalInset + (inner.h - nameMetrics.lineHeight) / 2 + nameMetrics.baseline, align: 'centre' });
203
+ return v;
204
+ }
205
+ // Superstate (macro state) or the root: rows in a one-column grid.
206
+ const titleMetrics = lineMetrics(TITLE);
207
+ const declMetrics = lineMetrics(DECLARATION);
208
+ let y = 0;
209
+ let minWidth = 0;
210
+ const titleSegments = stateTitleSegments(s, ctx.format);
211
+ if (titleSegments.some(t => t.text.trim())) {
212
+ const line = makeLine(ctx, 'title', TITLE, titleSegments);
213
+ v.lines.push({ line, y: y + LABEL_PAD_Y + titleMetrics.baseline, align: 'centre' });
214
+ y += LABEL_PAD_Y + titleMetrics.lineHeight + LABEL_PAD_Y;
215
+ minWidth = Math.max(minWidth, line.width + 2 * LABEL_PAD_X);
216
+ }
217
+ else {
218
+ y += EMPTY_TITLE;
219
+ }
220
+ const block = (lines) => {
221
+ if (!lines.length)
222
+ return;
223
+ y += BLOCK_PAD_TOP;
224
+ for (const line of lines) {
225
+ v.lines.push({ line, y: y + declMetrics.baseline, align: 'left' });
226
+ y += declMetrics.lineHeight;
227
+ minWidth = Math.max(minWidth, line.width + line.indent * INDENT + 2 * BLOCK_PAD_X);
228
+ }
229
+ y += BLOCK_PAD_BOTTOM;
230
+ };
231
+ if (ctx.declarations) {
232
+ const lines = [];
233
+ for (const d of s.declarations) {
234
+ // KIELER draws methods as (collapsed) method regions, not as declaration lines.
235
+ if (hasAnnotation(d.annotations, 'hide') || d.declKind === 'method')
236
+ continue;
237
+ for (const dl of declarationLines(d, ctx.format)) {
238
+ lines.push(makeLine(ctx, 'declaration', DECLARATION, mergeComponents(dl.components), dl.indent, d.valuedObjects.map(vo => vo.id)));
239
+ }
240
+ }
241
+ block(lines);
242
+ }
243
+ if (ctx.actions) {
244
+ block(s.actions.filter(a => !hasAnnotation(a.annotations, 'hide'))
245
+ .map(a => makeLine(ctx, 'action', DECLARATION, actionSegments(a, { ...ctx.format, userLabels: ctx.userLabels }), 0, [a.id])));
246
+ }
247
+ if (hasChildArea(s)) {
248
+ // StateStyles.addRegionsArea: from(LEFT s, TOP -4).to(RIGHT s, BOTTOM s), s = 9 for initial states.
249
+ const side = (initial ? 9 : 7) + finalInset;
250
+ v.pad = { top: y - 4 + finalInset, right: side, bottom: side, left: side };
251
+ const regionDepth = hv.depth;
252
+ // StateSynthesis: methods come first among the state's children, then the regions.
253
+ for (const d of s.declarations)
254
+ if (d.declKind === 'method' && !hasAnnotation(d.annotations, 'hide'))
255
+ v.regions.push(methodRegion(ctx, d, s));
256
+ for (const region of s.regions) {
257
+ if (hasAnnotation(region.annotations, 'hide'))
258
+ continue;
259
+ v.regions.push(synthRegion(ctx, region, s, { isHV: hv.isHV, depth: regionDepth }));
260
+ }
261
+ if (s.reference && v.regions.length === 0)
262
+ v.regions.push(referenceRegion(ctx, s, { isHV: hv.isHV, depth: regionDepth }));
263
+ v.width = Math.max(MIN_SIZE, minWidth + 2 * finalInset);
264
+ v.height = Math.max(MIN_SIZE, v.pad.top + 20 + v.pad.bottom);
265
+ }
266
+ else {
267
+ v.width = Math.max(MIN_SIZE, minWidth + 2 * finalInset);
268
+ v.height = Math.max(MIN_SIZE, y + 2 * finalInset);
269
+ }
270
+ for (const entry of v.lines)
271
+ entry.y += finalInset;
272
+ v.radius = MACRO_CORNER + finalInset;
273
+ return v;
274
+ }
275
+ /** The id prefix of a referenced chart drawn inside a reference state (`references: 'expanded'`). */
276
+ export const REFERENCE_SEPARATOR = '/';
277
+ /** A copy of a chart whose element ids are prefixed, so it can be drawn inside a reference state. */
278
+ function prefixedCopy(chart, prefix) {
279
+ const visit = (value) => {
280
+ if (Array.isArray(value))
281
+ return value.map(visit);
282
+ if (!value || typeof value !== 'object')
283
+ return value;
284
+ const obj = value;
285
+ const out = {};
286
+ for (const [k, v] of Object.entries(obj))
287
+ out[k] = k === 'span' || k === 'nameSpan' || k === 'targetSpan' ? v : visit(v);
288
+ if (typeof obj.id === 'string' && obj.id)
289
+ out.id = prefix + obj.id;
290
+ if (obj.kind === 'transition') {
291
+ if (typeof obj.source === 'string')
292
+ out.source = prefix + obj.source;
293
+ if (typeof obj.target === 'string')
294
+ out.target = prefix + obj.target;
295
+ }
296
+ if (obj.kind === 'ref' && typeof obj.decl === 'string')
297
+ out.decl = prefix + obj.decl;
298
+ return out;
299
+ };
300
+ return { ...visit(chart), isRoot: false, initial: false, final: false };
301
+ }
302
+ /** ControlflowRegionSynthesis.createReferenceRegion: the body of a reference state, collapsed as KIELER
303
+ * shows it at first, or with the referenced chart inside (KIELER's ReferenceExpandAction). */
304
+ function referenceRegion(ctx, s, hv) {
305
+ const region = {
306
+ ast: { kind: 'region', id: `${s.id}:ref`, regionType: 'controlflow', implicit: true, annotations: [], declarations: [], actions: [], states: [], equations: [], span: s.span },
307
+ id: `${s.id}:ref`, dataflow: false, collapsed: true, lines: [], states: [], edges: [], direction: 'RIGHT',
308
+ pad: { top: REGION_PAD, right: REGION_PAD, bottom: REGION_PAD, left: REGION_PAD }, minWidth: 20, minHeight: 20, priority: 1, comments: [],
309
+ };
310
+ const target = s.reference ? ctx.chartOf(s.reference.target) : undefined;
311
+ const expand = ctx.references === 'expanded' || (ctx.references instanceof Set && ctx.references.has(s.id));
312
+ if (target && expand && !ctx.expanding.includes(target.name) && ctx.expanding.length < 4) {
313
+ ctx.expanding.push(target.name);
314
+ try {
315
+ const inner = prefixedCopy(target, s.id + REFERENCE_SEPARATOR);
316
+ region.ast = { ...region.ast, states: [inner] };
317
+ region.collapsed = false;
318
+ region.direction = ctx.direction === 'down' ? 'DOWN' : ctx.direction === 'right' ? 'RIGHT' : depthDirection(hv.isHV, hv.depth);
319
+ region.states.push(synthState(ctx, inner, { isHV: hv.isHV, depth: hv.depth + 1 }));
320
+ }
321
+ finally {
322
+ ctx.expanding.pop();
323
+ }
324
+ }
325
+ return region;
326
+ }
327
+ /** MethodSynthesis: a method as a grey region, collapsed (KIELER shows its SCG when expanded), labelled with
328
+ * its signature; dashed when it has no body. */
329
+ function methodRegion(ctx, d, s) {
330
+ const label = makeLine(ctx, 'region-label', REGION_LABEL, mergeComponents(declarationLines(d, ctx.format)[0]?.components ?? []));
331
+ const id = d.valuedObjects[0]?.id || `${s.id}$${d.valuedObjects[0]?.name ?? 'method'}`;
332
+ return {
333
+ ast: { kind: 'region', id, name: d.valuedObjects[0]?.name, regionType: 'controlflow', implicit: false, annotations: d.annotations, declarations: [], actions: [], states: [], equations: [], span: d.span },
334
+ // KIELER lays the (hidden) SCG of a method out top to bottom.
335
+ id, dataflow: false, collapsed: true, method: d.body ? 'implemented' : 'abstract', label, lines: [], states: [], edges: [], direction: 'DOWN',
336
+ pad: { top: REGION_HEADER, right: 4, bottom: 0, left: 4 }, minWidth: label.width + REGION_LABEL_X + 4,
337
+ minHeight: lineMetrics(REGION_LABEL).lineHeight + 4, priority: 0, comments: [],
338
+ };
339
+ }
340
+ /** The doc comments of a state, region or transition (KIELER's CommentAnnotations), in source order. */
341
+ function docComments(e) {
342
+ const texts = e.annotations.filter(a => a.name === 'comment' && a.values[0] !== undefined).map(a => a.values[0]);
343
+ return texts.length ? texts : e.doc !== undefined ? [e.doc] : [];
344
+ }
345
+ /** `<element id>#doc` for the first doc comment, `#doc1`, `#doc2`, ... for further ones. */
346
+ const commentId = (id, i) => `${id}#doc${i ? i : ''}`;
347
+ /** CommentSynthesis + CommentStyles: the comment's text as written (KIELER does not wrap it; blank lines stay),
348
+ * 4 px inside a box of at least 16 × 16. */
349
+ function synthComment(ctx, id, text, attachTo) {
350
+ const metrics = lineMetrics(COMMENT);
351
+ const lines = text.split('\n').map(l => plainLine(ctx, 'comment', COMMENT, l.trim()));
352
+ const width = Math.max(COMMENT_MIN, Math.max(0, ...lines.map(l => l.width)) + 2 * COMMENT_PAD);
353
+ const height = Math.max(COMMENT_MIN, lines.length * metrics.lineHeight + 2 * COMMENT_PAD);
354
+ return { id, lines, width, height, attachTo };
355
+ }
356
+ function synthRegion(ctx, r, parent, hv) {
357
+ const labelSegments = r.reference
358
+ ? [{ text: `${r.label ?? r.name ? `${r.label ?? r.name}@` : ''}${r.reference.target}${r.reference.parameters.length ? `(${r.reference.parameters.map(p => formatExpression(p.expression, ctx.format)).join(', ')})` : ''}`, format: 'text' }]
359
+ : regionLabelSegments(r, ctx.format);
360
+ // ControlflowRegionSynthesis: a referencing region (`region R is Other(...)`) is drawn collapsed, labelled
361
+ // `R@Other(...)`; a region without states is a bare frame, without label or button.
362
+ const collapsed = (ctx.collapsed.has(r.id) || hasAnnotation(r.annotations, 'collapse') || !!r.reference
363
+ || (ctx.collapseAll && !hasAnnotation(r.annotations, 'expand'))) && !(r.regionType === 'controlflow' && r.states.length === 0 && !r.reference);
364
+ const empty = r.regionType === 'controlflow' && r.states.length === 0 && !r.reference && !collapsed;
365
+ const label = labelSegments.length && !empty ? makeLine(ctx, 'region-label', REGION_LABEL, labelSegments) : undefined;
366
+ const index = parent.regions.indexOf(r);
367
+ const v = {
368
+ ast: r, id: r.id, dataflow: r.regionType === 'dataflow', collapsed, label, lines: [], states: [], edges: [],
369
+ direction: 'RIGHT', pad: { top: label ? REGION_HEADER : REGION_PAD, right: REGION_PAD, bottom: REGION_PAD, left: REGION_PAD },
370
+ minWidth: label ? label.width + REGION_LABEL_X : 20, minHeight: 20,
371
+ // LayoutHook.processRegion: earlier regions get a higher priority.
372
+ priority: parent.regions.length - index, comments: [], empty,
373
+ };
374
+ // Direction: an explicit @layout[direction] wins, then a chart-wide one, then HV/VH alternation.
375
+ const alt = alternating(r.annotations);
376
+ const local = alt !== undefined ? { isHV: alt, depth: 0 } : hv;
377
+ v.direction = directionAnnotation(r.annotations) ?? ctx.globalDirection ?? (ctx.direction === 'down' ? 'DOWN' : ctx.direction === 'right' ? 'RIGHT' : depthDirection(local.isHV, local.depth));
378
+ if (collapsed) {
379
+ v.pad = { top: label ? REGION_HEADER : REGION_PAD, right: 4, bottom: 0, left: 4 };
380
+ v.minHeight = label ? lineMetrics(REGION_LABEL).lineHeight + 4 : 20;
381
+ return v;
382
+ }
383
+ const declMetrics = lineMetrics(DECLARATION);
384
+ // Region-level declarations and actions (addStatesAndDeclarationsAndActionsArea, vertical variant).
385
+ const extra = [];
386
+ if (ctx.declarations)
387
+ for (const d of r.declarations)
388
+ for (const dl of declarationLines(d, ctx.format))
389
+ extra.push(makeLine(ctx, 'declaration', DECLARATION, mergeComponents(dl.components), dl.indent, d.valuedObjects.map(vo => vo.id)));
390
+ if (ctx.actions)
391
+ for (const a of r.actions)
392
+ extra.push(makeLine(ctx, 'action', DECLARATION, actionSegments(a, { ...ctx.format, userLabels: ctx.userLabels }), 0, [a.id]));
393
+ if (extra.length) {
394
+ let y = label ? REGION_HEADER : 6;
395
+ for (const line of extra) {
396
+ v.lines.push({ line, y: y + declMetrics.baseline });
397
+ y += declMetrics.lineHeight;
398
+ v.minWidth = Math.max(v.minWidth, line.width + line.indent * INDENT + 3 + 8);
399
+ }
400
+ v.pad.top = y + REGION_PAD;
401
+ }
402
+ if (v.dataflow) {
403
+ if (ctx.circuit) {
404
+ v.circuit = buildCircuit(r, { measure: ctx.measure, format: ctx.format, chartOf: ctx.chartOf });
405
+ }
406
+ else {
407
+ const metrics = lineMetrics(EQUATION);
408
+ let y = v.pad.top;
409
+ for (const eq of r.equations) {
410
+ const line = plainLine(ctx, 'equation', EQUATION, formatEquation(eq, ctx.format));
411
+ v.lines.push({ line, y: y + metrics.baseline });
412
+ y += metrics.lineHeight;
413
+ v.minWidth = Math.max(v.minWidth, line.width + 2 * REGION_PAD);
414
+ }
415
+ v.minHeight = Math.max(v.minHeight, y + REGION_PAD);
416
+ }
417
+ return v;
418
+ }
419
+ const depth = { isHV: local.isHV, depth: local.depth + 1 };
420
+ for (const s of r.states) {
421
+ if (hasAnnotation(s.annotations, 'hide'))
422
+ continue;
423
+ v.states.push(synthState(ctx, s, alternating(s.annotations) !== undefined ? { isHV: alternating(s.annotations), depth: 0 } : depth));
424
+ }
425
+ const visible = new Set(v.states.map(s => s.id));
426
+ for (const s of r.states) {
427
+ if (!visible.has(s.id))
428
+ continue;
429
+ for (const t of s.transitions) {
430
+ if (!t.target || !visible.has(t.target) || hasAnnotation(t.annotations, 'hide'))
431
+ continue;
432
+ v.edges.push(synthEdge(ctx, t, s));
433
+ }
434
+ }
435
+ if (ctx.comments) {
436
+ // ControlflowRegionSynthesis: the region's own comments are nodes of its graph, without an edge.
437
+ docComments(r).forEach((text, i) => v.comments.push(synthComment(ctx, commentId(r.id, i), text)));
438
+ for (const s of v.states)
439
+ v.comments.push(...s.comments);
440
+ }
441
+ return v;
442
+ }
443
+ function synthEdge(ctx, t, source) {
444
+ const raw = transitionLabelLines(t, source.transitions.length, { ...ctx.format, userLabels: ctx.userLabels });
445
+ // SemanticSoftWrappingLabelManager: one line per semantic part, each soft-wrapped.
446
+ const text = raw.join('\n').trim() ? raw.flatMap(line => softWrap(ctx, line, EDGE_LABEL, ctx.labelWidth)) : [];
447
+ const lines = text.map(l => plainLine(ctx, 'edge-label', EDGE_LABEL, l));
448
+ const metrics = lineMetrics(EDGE_LABEL);
449
+ const size = (ls) => ({
450
+ width: ls.length ? Math.max(...ls.map(l => l.width)) + 2 * EDGE_LABEL_PAD : 0,
451
+ height: ls.length ? ls.length * metrics.lineHeight + 2 * EDGE_LABEL_PAD + 1 : 0,
452
+ });
453
+ // TransitionSynthesis (SHOW_COMMENTS): a label per doc comment. KIELER asks for 7 pt text on a comment-coloured
454
+ // background, but KLighD's edge label decoration gives these labels the transition label's style (11 pt bold),
455
+ // and that is what its diagrams show; the label manager soft-wraps them like any label.
456
+ const comments = ctx.comments
457
+ ? docComments(t).map((text, i) => {
458
+ const ls = text.split('\n').flatMap(line => softWrap(ctx, line.trim(), EDGE_LABEL, ctx.labelWidth)).map(l => plainLine(ctx, 'edge-label', EDGE_LABEL, l));
459
+ return { id: commentId(t.id, i), lines: ls, ...size(ls) };
460
+ }).filter(c => c.lines.length)
461
+ : [];
462
+ const main = size(lines);
463
+ return {
464
+ ast: t, id: t.id, source: source.id, target: t.target, immediate: isImplicitlyImmediate(t, source), lines,
465
+ labelWidth: main.width, labelHeight: main.height, comments,
466
+ };
467
+ }
468
+ // ----- ELK graph -------------------------------------------------------------------------------------
469
+ /** `links`: the drawn transitions of the state's region that leave or enter the state (`loops`: to itself, `others`:
470
+ * to or from another state). `twoSides`: states whose self-loops go on two sides only (crowdedLoops). */
471
+ function elkState(v, isFirstInRegion, twoSides, links = { loops: 0, others: 0 }) {
472
+ const node = { id: v.id, layoutOptions: { ...STATE_LAYOUT } };
473
+ if (v.initial && isFirstInRegion)
474
+ node.layoutOptions['org.eclipse.elk.layered.layering.layerConstraint'] = 'FIRST';
475
+ // Several self-loops: ELK stacks them on one side of the state, each inside the next with its label on top, but
476
+ // makes each loop only as wide as its ports, so an outer loop runs through the labels of the loops inside it
477
+ // (KIELER's diagrams show this tangle); side by side on one side they are so narrow that a label is hard to match
478
+ // with its loop. They are spread over the two sides across the flow (above and below in a left-to-right region),
479
+ // or over all four when no other transition needs a side (one loop to a side for up to four), each with its
480
+ // label next to it; crowdedLoops catches the four-side layouts whose labels collide.
481
+ if (links.loops > 1) {
482
+ node.layoutOptions['org.eclipse.elk.layered.edgeRouting.selfLoopDistribution'] = links.others || twoSides.has(v.id) ? 'NORTH_SOUTH' : 'EQUALLY';
483
+ node.layoutOptions['org.eclipse.elk.layered.edgeRouting.selfLoopOrdering'] = 'SEQUENCED';
484
+ }
485
+ if (v.regions.length && v.pad) {
486
+ node.children = v.regions.map(r => elkRegion(r, twoSides));
487
+ Object.assign(node.layoutOptions, opt({
488
+ padding: padding(v.pad.top, v.pad.right, v.pad.bottom, v.pad.left),
489
+ 'nodeSize.constraints': 'MINIMUM_SIZE',
490
+ 'nodeSize.minimum': `(${r2(v.width)},${r2(v.height)})`,
491
+ }));
492
+ }
493
+ else {
494
+ node.width = r2(v.width);
495
+ node.height = r2(v.height);
496
+ }
497
+ return node;
498
+ }
499
+ function elkRegion(v, twoSides) {
500
+ const node = {
501
+ id: v.id,
502
+ layoutOptions: {
503
+ ...REGION_LAYOUT,
504
+ ...opt({
505
+ direction: v.direction,
506
+ padding: padding(v.pad.top, v.pad.right, v.pad.bottom, v.pad.left),
507
+ 'nodeSize.minimum': `(${r2(v.minWidth)},${r2(v.minHeight)})`,
508
+ priority: v.priority,
509
+ }),
510
+ },
511
+ children: [],
512
+ edges: [],
513
+ };
514
+ if (v.collapsed || (v.empty && !v.circuit)) {
515
+ // No children: ELK would not size the node before packing it, so give it its size.
516
+ node.width = r2(v.minWidth);
517
+ node.height = r2(Math.max(v.minHeight, v.pad.top + v.pad.bottom));
518
+ delete node.children;
519
+ delete node.edges;
520
+ return node;
521
+ }
522
+ if (v.circuit) {
523
+ node.children = v.circuit.nodes;
524
+ node.edges = v.circuit.edges;
525
+ Object.assign(node.layoutOptions, v.circuit.layoutOptions);
526
+ return node;
527
+ }
528
+ const first = v.ast.states[0]?.id;
529
+ const links = (id) => ({
530
+ loops: v.edges.filter(e => e.source === id && e.target === id).length,
531
+ others: v.edges.filter(e => (e.source === id) !== (e.target === id)).length,
532
+ });
533
+ node.children = v.states.map(s => elkState(s, s.id === first, twoSides, links(s.id)));
534
+ node.edges = v.edges.map(e => {
535
+ const edge = {
536
+ id: e.id, sources: [e.source], targets: [e.target],
537
+ layoutOptions: opt({ 'spacing.edgeLabel': 3, 'layered.priority.direction': e.immediate ? 6 : undefined }),
538
+ };
539
+ const text = (ls) => ls.map(l => l.runs.map(r => r.text).join(' ')).join('\n');
540
+ const labels = e.comments.map(c => ({ id: c.id, text: text(c.lines), width: r2(c.width), height: r2(c.height), layoutOptions: { ...LABEL_LAYOUT } }));
541
+ if (e.lines.length)
542
+ labels.push({ id: `${e.id}#label`, text: text(e.lines), width: r2(e.labelWidth), height: r2(e.labelHeight), layoutOptions: { ...LABEL_LAYOUT } });
543
+ if (labels.length)
544
+ edge.labels = labels;
545
+ return edge;
546
+ });
547
+ for (const c of v.comments) {
548
+ node.children.push(commentNode(c));
549
+ if (c.attachTo)
550
+ node.edges.push(commentEdge(c));
551
+ }
552
+ return node;
553
+ }
554
+ /** A comment box for ELK (CommentSynthesis: `CoreOptions.COMMENT_BOX`). */
555
+ function commentNode(c) {
556
+ return { id: c.id, width: r2(c.width), height: r2(c.height), layoutOptions: opt({ commentBox: true }) };
557
+ }
558
+ /** CommentSynthesis: the edge from the documented state to its comment box. */
559
+ function commentEdge(c) {
560
+ return { id: `${c.id}#edge`, sources: [c.attachTo], targets: [c.id] };
561
+ }
562
+ /** The states whose self-loops, spread over all four sides, came back with a label over another label: ELK places a
563
+ * side loop's label beside the state without looking at the label of the loop below it (Fan's wide labels). They
564
+ * are laid out again with their loops on two sides. */
565
+ function crowdedLoops(node, out = new Set()) {
566
+ const boxes = [];
567
+ for (const e of (node.edges ?? [])) {
568
+ const loop = e.sources[0] === e.targets[0] ? e.sources[0] : undefined;
569
+ for (const l of e.labels ?? [])
570
+ boxes.push({ state: loop, x: l.x ?? 0, y: l.y ?? 0, width: l.width ?? 0, height: l.height ?? 0 });
571
+ }
572
+ // Only loops on four sides can move (those on two already are).
573
+ const four = new Set((node.children ?? []).filter(c => c.layoutOptions?.['org.eclipse.elk.layered.edgeRouting.selfLoopDistribution'] === 'EQUALLY').map(c => c.id));
574
+ const apart = (a, b) => a.x + a.width <= b.x + 1 || b.x + b.width <= a.x + 1 || a.y + a.height <= b.y + 1 || b.y + b.height <= a.y + 1;
575
+ for (let i = 0; i < boxes.length; i++) {
576
+ for (let j = i + 1; j < boxes.length; j++) {
577
+ const a = boxes[i], b = boxes[j];
578
+ if (!apart(a, b))
579
+ for (const st of [a.state, b.state])
580
+ if (st && four.has(st))
581
+ out.add(st);
582
+ }
583
+ }
584
+ for (const c of node.children ?? [])
585
+ crowdedLoops(c, out);
586
+ return out;
587
+ }
588
+ // ----- Read back -------------------------------------------------------------------------------------
589
+ function textLine(line, x, y) {
590
+ const out = { x: r2(x), y: r2(y), width: r2(line.width), size: line.style.size, runs: line.runs, role: line.role };
591
+ if (line.style.bold)
592
+ out.bold = true;
593
+ if (line.style.mono)
594
+ out.mono = true;
595
+ if (line.ids?.length)
596
+ out.ids = line.ids;
597
+ return out;
598
+ }
599
+ function readState(v, n, ox, oy) {
600
+ const x = ox + (n.x ?? 0), y = oy + (n.y ?? 0);
601
+ const width = n.width ?? v.width, height = n.height ?? v.height;
602
+ const lines = v.lines.map(({ line, y: ly, align }) => {
603
+ if (align === 'centre') {
604
+ const innerX = x + v.finalInset + (v.shape === 'simple' ? 0 : LABEL_PAD_X);
605
+ const innerW = width - 2 * v.finalInset - (v.shape === 'simple' ? 0 : 2 * LABEL_PAD_X);
606
+ return textLine(line, innerX + (innerW - line.width) / 2, y + ly);
607
+ }
608
+ return textLine(line, x + v.finalInset + BLOCK_PAD_X + line.indent * INDENT, y + ly);
609
+ });
610
+ const regions = [];
611
+ const byId = new Map((n.children ?? []).map(c => [c.id, c]));
612
+ for (const r of v.regions) {
613
+ const rn = byId.get(r.id);
614
+ if (rn)
615
+ regions.push(readRegion(r, rn, x, y));
616
+ }
617
+ const out = {
618
+ kind: 'state', id: v.id, name: v.ast.name, shape: v.shape, initial: v.initial, final: v.final,
619
+ violation: v.ast.violation, reference: v.reference,
620
+ x: r2(x), y: r2(y), width: r2(width), height: r2(height), radius: v.radius, lineWidth: v.lineWidth,
621
+ lines, regions, comments: [], span: v.ast.span,
622
+ };
623
+ if (v.finalInset)
624
+ out.finalInset = v.finalInset;
625
+ return out;
626
+ }
627
+ function readComments(comments, byId, edges, x, y) {
628
+ const out = [];
629
+ const m = lineMetrics(COMMENT);
630
+ for (const c of comments) {
631
+ const cn = byId.get(c.id);
632
+ if (!cn)
633
+ continue;
634
+ const cx = x + (cn.x ?? 0), cy = y + (cn.y ?? 0);
635
+ const comment = {
636
+ id: c.id, x: r2(cx), y: r2(cy), width: r2(cn.width ?? c.width), height: r2(cn.height ?? c.height),
637
+ lines: c.lines.map((l, i) => textLine(l, cx + COMMENT_PAD, cy + COMMENT_PAD + i * m.lineHeight + m.baseline)),
638
+ };
639
+ const section = edges.get(`${c.id}#edge`)?.sections?.[0];
640
+ if (section)
641
+ comment.points = [section.startPoint, ...(section.bendPoints ?? []), section.endPoint].map(p => ({ x: r2(x + p.x), y: r2(y + p.y) }));
642
+ out.push(comment);
643
+ }
644
+ return out;
645
+ }
646
+ function labelDirection(points, box) {
647
+ const poly = flatten(points);
648
+ const { tangent } = nearest(poly, { x: box.x + box.width / 2, y: box.y + box.height / 2 });
649
+ if (Math.abs(tangent.x) >= Math.abs(tangent.y))
650
+ return tangent.x >= 0 ? 'right' : 'left';
651
+ return tangent.y >= 0 ? 'down' : 'up';
652
+ }
653
+ function readRegion(v, n, ox, oy) {
654
+ const x = ox + (n.x ?? 0), y = oy + (n.y ?? 0);
655
+ const out = {
656
+ kind: 'region', id: v.id, name: v.ast.name, dataflow: v.dataflow, collapsed: v.collapsed,
657
+ final: !!v.ast.final, abort: !!v.ast.abort, override: !!v.ast.override, direction: v.direction,
658
+ ...(v.ast.reference ? { reference: true } : {}),
659
+ ...(v.method ? { method: v.method } : {}),
660
+ ...(v.empty ? { empty: true } : {}),
661
+ x: r2(x), y: r2(y), width: r2(n.width ?? v.minWidth), height: r2(n.height ?? v.minHeight),
662
+ lines: v.lines.map(({ line, y: ly }) => textLine(line, x + (line.role === 'equation' ? REGION_PAD : 3 + line.indent * INDENT), y + ly)),
663
+ states: [], transitions: [], comments: [], span: v.ast.span,
664
+ };
665
+ if (v.label) {
666
+ const m = lineMetrics(REGION_LABEL);
667
+ out.label = textLine(v.label, x + REGION_LABEL_X, y + REGION_LABEL_Y + m.baseline);
668
+ }
669
+ const byId = new Map((n.children ?? []).map(c => [c.id, c]));
670
+ if (v.circuit) {
671
+ out.circuit = v.circuit.read(n, x, y);
672
+ return out;
673
+ }
674
+ for (const s of v.states) {
675
+ const sn = byId.get(s.id);
676
+ if (sn)
677
+ out.states.push(readState(s, sn, x, y));
678
+ }
679
+ const edges = new Map((n.edges ?? []).map(e => [e.id, e]));
680
+ for (const e of v.edges) {
681
+ const en = edges.get(e.id);
682
+ if (!en)
683
+ continue;
684
+ const points = [];
685
+ for (const section of en.sections ?? []) {
686
+ if (!points.length)
687
+ points.push(section.startPoint);
688
+ points.push(...(section.bendPoints ?? []), section.endPoint);
689
+ }
690
+ const abs = points.map(p => ({ x: r2(x + p.x), y: r2(y + p.y) }));
691
+ const t = {
692
+ kind: 'transition', id: e.id, source: e.source, target: e.target, priority: e.ast.priority, points: abs,
693
+ immediate: e.immediate, preemption: e.ast.preemption, span: e.ast.span,
694
+ };
695
+ if (e.ast.history && e.ast.history !== 'reset')
696
+ t.history = e.ast.history;
697
+ if (e.ast.deferred)
698
+ t.deferred = e.ast.deferred;
699
+ if (e.ast.nondeterministic)
700
+ t.nondeterministic = true;
701
+ if (e.ast.probability !== undefined)
702
+ t.probability = e.ast.probability;
703
+ const readLabel = (id, lines, width, height) => {
704
+ const label = en.labels?.find(l => l.id === id);
705
+ if (!label || !lines.length)
706
+ return undefined;
707
+ const box = { x: r2(x + (label.x ?? 0)), y: r2(y + (label.y ?? 0)), width: r2(label.width ?? width), height: r2(label.height ?? height) };
708
+ const m = lineMetrics(EDGE_LABEL);
709
+ const top = box.y + (box.height - lines.length * m.lineHeight) / 2;
710
+ return { ...box, lines: lines.map((l, i) => textLine(l, box.x + EDGE_LABEL_PAD, top + i * m.lineHeight + m.baseline)), direction: labelDirection(abs, box) };
711
+ };
712
+ const label = readLabel(`${e.id}#label`, e.lines, e.labelWidth, e.labelHeight);
713
+ if (label)
714
+ t.label = label;
715
+ const comments = e.comments.map(c => readLabel(c.id, c.lines, c.width, c.height)).filter((c) => !!c);
716
+ if (comments.length)
717
+ t.comments = comments;
718
+ out.transitions.push(t);
719
+ }
720
+ out.comments.push(...readComments(v.comments, byId, edges, x, y));
721
+ return out;
722
+ }
723
+ // ----- Entry point -----------------------------------------------------------------------------------
724
+ function referencesOption(value) {
725
+ if (value === undefined || value === 'collapsed')
726
+ return 'collapsed';
727
+ if (value === 'expanded')
728
+ return 'expanded';
729
+ return new Set(value);
730
+ }
731
+ /** Lays out a chart (a root state from `parse`/`compile`) in KIELER's notation. Deterministic: the same chart
732
+ * and options always give the same layout. */
733
+ /**
734
+ * SynthesisAnnotationHook: `@diagram[<option>] <value>` (or `@diagram <option>` for true) on the chart sets a
735
+ * synthesis option, matched by prefix of its name without spaces, case-insensitively, and wins over the
736
+ * options passed in, as in KIELER. Supported: Comment Nodes, User Labels, Declarations, State Actions,
737
+ * Initially Collapse Regions, Direction, Shadows.
738
+ */
739
+ function diagramAnnotations(chart, options) {
740
+ const out = { ...options };
741
+ const names = {
742
+ commentnodes: v => (out.comments = bool(v) ?? out.comments),
743
+ userlabels: v => (out.userLabels = bool(v) ?? out.userLabels),
744
+ declarations: v => (out.declarations = bool(v) ?? out.declarations),
745
+ stateactions: v => (out.actions = bool(v) ?? out.actions),
746
+ initiallycollapseregions: v => (out.collapseAll = bool(v) ?? out.collapseAll),
747
+ direction: v => {
748
+ const d = v.toLowerCase();
749
+ if (d === 'hv' || d === 'vh')
750
+ out.direction = d.toUpperCase();
751
+ else if (d === 'down' || d === 'right')
752
+ out.direction = d;
753
+ },
754
+ shadows: v => (out.shadows = bool(v) ?? out.shadows),
755
+ };
756
+ function bool(v) {
757
+ const l = v.toLowerCase();
758
+ return ['true', 'on', 'checked'].includes(l) ? true : ['false', 'off', 'unchecked'].includes(l) ? false : undefined;
759
+ }
760
+ for (const a of chart.annotations) {
761
+ if (a.name.toLowerCase() !== 'diagram')
762
+ continue;
763
+ const key = (a.type ?? a.values[0] ?? '').toLowerCase().replace(/\s+/g, '');
764
+ const value = a.type !== undefined ? a.values[0] ?? '' : 'true';
765
+ if (!key || !value)
766
+ continue;
767
+ for (const [name, apply] of Object.entries(names))
768
+ if (name.startsWith(key))
769
+ apply(value);
770
+ }
771
+ return out;
772
+ }
773
+ export async function layoutChart(chart, givenOptions = {}) {
774
+ const options = diagramAnnotations(chart, givenOptions);
775
+ const direction = options.direction ?? 'HV';
776
+ const ctx = {
777
+ measure: options.measure ?? measureWithTable,
778
+ format: options.format ?? createFormatContext(options.program ?? { charts: [chart], pragmas: [] }),
779
+ userLabels: options.userLabels ?? true,
780
+ // GeneralSynthesisOptions.SHOW_COMMENTS ("Comment Nodes") is on by default.
781
+ comments: options.comments ?? true,
782
+ declarations: options.declarations ?? true,
783
+ actions: options.actions ?? true,
784
+ labelWidth: options.labelWidth ?? DEFAULT_LABEL_WIDTH,
785
+ collapsed: new Set(options.collapsed ?? []),
786
+ direction,
787
+ globalDirection: directionAnnotation(chart.annotations),
788
+ circuit: options.dataflowCircuit ?? true,
789
+ chartOf: name => options.program?.charts.find(c => c.name === name) ?? options.charts?.find(c => c.name === name),
790
+ references: referencesOption(options.references),
791
+ expanding: [chart.name],
792
+ collapseAll: !!options.collapseAll,
793
+ };
794
+ const alt = alternating(chart.annotations);
795
+ // LayoutHook: the diagram root has depth 1, the root state 2; regions share their state's depth.
796
+ const hv = alt !== undefined ? { isHV: alt, depth: 0 } : { isHV: direction !== 'VH', depth: 2 };
797
+ const root = synthState(ctx, { ...chart, isRoot: true }, hv);
798
+ // CommentSynthesis on the root: its comment boxes are nodes of the diagram's top level, which KLighD lays out
799
+ // with ELK Layered (no algorithm set there; padding 0), so they sit above the root, joined to it by an edge.
800
+ const rootComments = ctx.comments ? docComments(chart).map((text, i) => synthComment(ctx, commentId(chart.id, i), text, chart.id)) : [];
801
+ const graph = (twoSides) => ({
802
+ id: '__diagram',
803
+ layoutOptions: rootComments.length
804
+ ? opt({ algorithm: 'org.eclipse.elk.layered', padding: padding(0, 0, 0, 0) })
805
+ : opt({ algorithm: 'org.eclipse.elk.rectpacking', padding: padding(0, 0, 0, 0), omitNodeMicroLayout: true }),
806
+ children: [elkState(root, false, twoSides), ...rootComments.map(commentNode)],
807
+ edges: rootComments.map(commentEdge),
808
+ });
809
+ const elk = options.elk;
810
+ if (!elk)
811
+ throw new Error('layoutChart needs an ELK instance (options.elk); the one from @sccharts-lab/diagram supplies elkjs\'s bundled build');
812
+ let result = await elk.layout(graph(new Set()));
813
+ // Self-loops on four sides whose labels collide: once more, with those loops on two sides.
814
+ const crowded = crowdedLoops(result);
815
+ if (crowded.size)
816
+ result = await elk.layout(graph(crowded));
817
+ const rootNode = result.children[0];
818
+ if (!rootComments.length) {
819
+ rootNode.x = 0;
820
+ rootNode.y = 0;
821
+ }
822
+ const layout = readState(root, rootNode, 0, 0);
823
+ let width = layout.width;
824
+ let height = layout.height;
825
+ if (rootComments.length) {
826
+ const byId = new Map((result.children ?? []).map(c => [c.id, c]));
827
+ const edges = new Map((result.edges ?? []).map(e => [e.id, e]));
828
+ layout.comments.push(...readComments(rootComments, byId, edges, 0, 0));
829
+ width = result.width ?? width;
830
+ height = result.height ?? height;
831
+ }
832
+ const diagram = { version: 1, chart: chart.id, width: r2(width), height: r2(height), root: layout, direction };
833
+ if (options.shadows === false)
834
+ diagram.shadows = false;
835
+ return diagram;
836
+ }
837
+ export { workerElk } from "./elk-worker.js";
838
+ //# sourceMappingURL=layout.js.map