cseen 0.1.0 → 0.2.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 (52) hide show
  1. package/README.md +10 -2
  2. package/dist/all.d.ts +1 -0
  3. package/dist/all.js +1 -0
  4. package/dist/all.js.map +1 -1
  5. package/dist/anim/mount.js +58 -2
  6. package/dist/anim/mount.js.map +1 -1
  7. package/dist/anim/orbit.js +2 -0
  8. package/dist/anim/orbit.js.map +1 -1
  9. package/dist/core/nodes.d.ts +67 -2
  10. package/dist/core/nodes.js +68 -0
  11. package/dist/core/nodes.js.map +1 -1
  12. package/dist/core/render.d.ts +13 -1
  13. package/dist/core/render.js +47 -6
  14. package/dist/core/render.js.map +1 -1
  15. package/dist/core/scene.js +10 -3
  16. package/dist/core/scene.js.map +1 -1
  17. package/dist/cseen.css +2 -0
  18. package/dist/draw/heads.d.ts +11 -0
  19. package/dist/draw/heads.js +26 -0
  20. package/dist/draw/heads.js.map +1 -0
  21. package/dist/draw/overlap.d.ts +50 -0
  22. package/dist/draw/overlap.js +80 -0
  23. package/dist/draw/overlap.js.map +1 -0
  24. package/dist/draw/shapes.d.ts +27 -2
  25. package/dist/draw/shapes.js +26 -1
  26. package/dist/draw/shapes.js.map +1 -1
  27. package/dist/draw/svgplane.d.ts +30 -1
  28. package/dist/draw/svgplane.js +34 -0
  29. package/dist/draw/svgplane.js.map +1 -1
  30. package/dist/draw/words.d.ts +29 -0
  31. package/dist/draw/words.js +30 -0
  32. package/dist/draw/words.js.map +1 -0
  33. package/dist/flow/flow.d.ts +10 -2
  34. package/dist/flow/flow.js +18 -26
  35. package/dist/flow/flow.js.map +1 -1
  36. package/dist/flow/index.d.ts +1 -1
  37. package/dist/flow/sequence.d.ts +40 -3
  38. package/dist/flow/sequence.js +241 -81
  39. package/dist/flow/sequence.js.map +1 -1
  40. package/dist/index.d.ts +4 -4
  41. package/dist/index.js +2 -2
  42. package/dist/index.js.map +1 -1
  43. package/dist/uml/factory.d.ts +15 -0
  44. package/dist/uml/factory.js +16 -0
  45. package/dist/uml/factory.js.map +1 -0
  46. package/dist/uml/index.d.ts +3 -0
  47. package/dist/uml/index.js +3 -0
  48. package/dist/uml/index.js.map +1 -0
  49. package/dist/uml/uml.d.ts +187 -0
  50. package/dist/uml/uml.js +599 -0
  51. package/dist/uml/uml.js.map +1 -0
  52. package/package.json +6 -2
@@ -0,0 +1,599 @@
1
+ import { Face, Group, LinkArea, Path } from "../core/nodes.js";
2
+ import { HeadMark } from "../draw/heads.js";
3
+ import { NARROW, UNIT, collisions, crosses, overlap, textWidth, wrap } from "../draw/overlap.js";
4
+ import { Words } from "../draw/words.js";
5
+ /* sizes are worked out in pixels and placed in world units at 40 pixels to the unit, like a diagram */
6
+ const U = UNIT, FONT = 12, LINE = 15, TOP = 34, MARGIN = 14, FRAME_PAD = 18, FRAME_TITLE = 26, REACH = 7.2;
7
+ const point = (x, y, top = 0) => [x / U, 0, -(y + top) / U];
8
+ const MARKS = '+-#~';
9
+ /** The node that was drawn for a key: its shape, size and place, in pixels from the top left of the diagram. */
10
+ export class UmlNode extends Group {
11
+ /** what it says */
12
+ name;
13
+ /** its box in pixels from the top left of the diagram area */
14
+ rect;
15
+ constructor(name, rect) { super(); this.name = name; this.rect = rect; }
16
+ }
17
+ /**
18
+ * A UML diagram: use cases, classes, states or activities, with the notation UML uses. Describe it once as a `UmlSpec`;
19
+ * it is drawn wide or narrow from the same description. Everything is placed on a grid, lines are routed around the
20
+ * boxes, and `problems()` lists whatever still sits on something else.
21
+ *
22
+ * @example
23
+ * const s = new Scene({ view: 'front', size: [360, 240] });
24
+ * const d = s.add(new Uml({
25
+ * kind: 'class',
26
+ * nodes: { shape: { class: 'Shape', stereotype: 'interface', ops: ['+ area() : float'] }, circle: { class: 'Circle', attrs: ['+ r : float'] } },
27
+ * edges: [{ from: 'circle', to: 'shape' }],
28
+ * wide: ['shape', 'circle'],
29
+ * }));
30
+ * d.check();
31
+ */
32
+ export class Uml extends Group {
33
+ /** the nodes by key */
34
+ nodes = new Map();
35
+ /** the lines, in the order of the spec */
36
+ lines = [];
37
+ placed = { area: { x0: 0, y0: 0, x1: 0, y1: 0 }, boxes: [], texts: [], segments: [], borders: [] };
38
+ extra = [];
39
+ top = 0;
40
+ narrow;
41
+ spec;
42
+ constructor(spec, o = {}) {
43
+ super(o);
44
+ this.spec = spec;
45
+ this.narrow = !!o.narrow;
46
+ // a phone gets the room it needs by wrapping, a screen by widening the gaps
47
+ for (let scale = 1; scale <= 2.6; scale += 0.4) {
48
+ this.clear();
49
+ this.build(scale);
50
+ if (this.narrow || !this.problems().length)
51
+ break;
52
+ }
53
+ }
54
+ /** the size of the whole diagram on the page, width and height in world units, outer frame and every label included */
55
+ extent() {
56
+ const { area } = this.placed;
57
+ return [(area.x1 - area.x0) / U, (area.y1 - area.y0 + this.top) / U];
58
+ }
59
+ /** every box, label or line that sits on another, every text wider than its box or leaving the diagram, and, for a narrow diagram, a width over 358 px. Empty when the diagram is clean. */
60
+ problems() {
61
+ const found = [...this.extra, ...collisions(this.placed)];
62
+ if (this.narrow && this.placed.area.x1 > NARROW + 0.5)
63
+ found.unshift(`${Math.ceil(this.placed.area.x1) + 16} px wide, and a narrow diagram has 358 px`);
64
+ const name = `${this.spec.kind} ${this.spec.name ?? ''}`.trim();
65
+ return [...new Set(found)].map((m) => `${name}: ${m}`);
66
+ }
67
+ /** throws when there are `problems`, otherwise returns the diagram */
68
+ check() {
69
+ const found = this.problems();
70
+ if (found.length)
71
+ throw new Error(`cseen: ${found.join('\n')}`);
72
+ return this;
73
+ }
74
+ clear() {
75
+ for (const c of [...this.children])
76
+ this.remove(c);
77
+ this.nodes.clear();
78
+ this.lines = [];
79
+ this.placed = { area: { x0: 0, y0: 0, x1: 0, y1: 0 }, boxes: [], texts: [], segments: [], borders: [] };
80
+ this.extra = [];
81
+ }
82
+ /* ------------------------------------------------------------ drawing helpers */
83
+ words(text, cx, cy, o = {}) {
84
+ const ls = text.split('\n'), w = o.width ?? Math.max(...ls.map((l) => textWidth(l, FONT))), h = ls.length * LINE;
85
+ const x = o.align === 'start' ? cx : cx - w / 2;
86
+ this.add(new Words(text, [w / U, h / U], { role: o.role, back: o.back, align: o.align, at: point(x, cy + h / 2, this.top), layer: o.layer ?? 2 }));
87
+ return { w, h };
88
+ }
89
+ /** records the lines of a text for the overlap check, with the left edge `x0` and the middle of its first line at `y` */
90
+ note(text, x0, y, o = {}) {
91
+ text.split('\n').forEach((s, i) => {
92
+ const w = textWidth(s, FONT), yy = y + i * LINE;
93
+ this.placed.texts.push({ x0, x1: x0 + w, y0: yy - REACH, y1: yy + REACH, s, ...o });
94
+ });
95
+ }
96
+ shape(pts, role, fill, layer = 0) {
97
+ this.add(new Face(pts.map(([x, y]) => point(x, y, this.top)), { role, fill, shade: false, width: 1.1, layer }));
98
+ }
99
+ stroke(pts, role = 'ink', o = {}) {
100
+ return this.add(new Path(pts.map(([x, y]) => point(x, y, this.top)), { role, width: o.width ?? 1.1, dash: o.dash, closed: o.closed, layer: o.layer ?? -1 }));
101
+ }
102
+ oval(cx, cy, rx, ry, role, fill, layer = 0) {
103
+ this.shape(Array.from({ length: 56 }, (_, i) => [cx + rx * Math.cos((i / 56) * 2 * Math.PI), cy + ry * Math.sin((i / 56) * 2 * Math.PI)]), role, fill, layer);
104
+ }
105
+ rounded(x, y, w, h, r, role, fill) {
106
+ const c = [[x + w - r, y + h - r, 0], [x + r, y + h - r, 90], [x + r, y + r, 180], [x + w - r, y + r, 270]];
107
+ this.shape(c.flatMap(([cx, cy, a0]) => Array.from({ length: 7 }, (_, i) => { const a = ((a0 + i * 15) * Math.PI) / 180; return [cx + r * Math.cos(a), cy + r * Math.sin(a)]; })), role, fill);
108
+ }
109
+ /* ------------------------------------------------------------ sizes */
110
+ /** gives a node its size. `room` is the width a narrow diagram can give it. */
111
+ size(key, spec, room, lane) {
112
+ const wrapTo = (t, pad, grow = 1) => (this.narrow ? wrap(t, Math.max(6, Math.floor((room - pad) / grow / (FONT * 0.62)))) : t.split('\n'));
113
+ const base = { key, spec, c0: 0, c1: 0, r0: 0, r1: 0, x: 0, y: 0, id: 0 };
114
+ const widest = (ls) => Math.max(0, ...ls.map((l) => textWidth(l, FONT)));
115
+ if ('actor' in spec) {
116
+ const text = this.narrow ? wrap(spec.actor, 12) : spec.actor.split('\n');
117
+ return { ...base, type: 'actor', text, name: spec.actor, w: Math.max(28, ...text.map((l) => textWidth(l, FONT))), h: 54 + Math.max(1, text.length) * 14 + 10 };
118
+ }
119
+ if ('useCase' in spec) {
120
+ const text = wrapTo(spec.useCase, 28, 1.3), rx = Math.max(60, (widest(text) / 2) * 1.3 + 14), ry = 22 + (text.length - 1) * 8;
121
+ return { ...base, type: 'usecase', text, name: spec.useCase, w: 2 * rx, h: 2 * ry };
122
+ }
123
+ if ('class' in spec) {
124
+ const attrs = spec.attrs ?? [], ops = spec.ops ?? [], head = spec.stereotype ? 44 : 30, part = (n) => (n ? n * LINE + 10 : 12);
125
+ const w = Math.max(96, 16 + widest([spec.class, spec.stereotype ? `«${spec.stereotype}»` : '', ...attrs, ...ops]));
126
+ return { ...base, type: 'class', text: [], name: spec.class, w, h: head + part(attrs.length) + part(ops.length) };
127
+ }
128
+ if ('state' in spec || 'action' in spec || 'box' in spec) {
129
+ const s = 'state' in spec ? spec.state : 'action' in spec ? spec.action : spec.box, text = [...(lane ? [`(${lane})`] : []), ...wrapTo(s, 32)];
130
+ return { ...base, type: 'state' in spec ? 'state' : 'action' in spec ? 'action' : 'box', text, name: s, w: Math.max(72, widest(text) + 32), h: Math.max(44, text.length * LINE + 22) };
131
+ }
132
+ if ('decision' in spec)
133
+ return { ...base, type: 'decision', text: [], name: 'decision', w: 32, h: 24 };
134
+ if ('start' in spec)
135
+ return { ...base, type: 'start', text: [], name: 'start', w: 14, h: 14 };
136
+ return { ...base, type: 'end', text: [], name: 'end', w: 18, h: 18 };
137
+ }
138
+ /* ------------------------------------------------------------ the build */
139
+ build(scale) {
140
+ const { spec } = this, narrow = this.narrow;
141
+ const keys = Object.keys(spec.nodes);
142
+ const rows = (narrow ? (spec.narrow ?? keys) : spec.wide).map((r) => r.trim().split(/\s+/));
143
+ const cols = Math.max(1, ...rows.map((r) => r.length));
144
+ if (!narrow && (spec.wide.length === 0))
145
+ throw new Error('cseen: a UML diagram needs a `wide` grid');
146
+ this.top = spec.name ? TOP : 0;
147
+ const framed = !!spec.frames?.length, lanes = !narrow && spec.lanes?.length ? spec.lanes : undefined;
148
+ const gx = (narrow ? 26 : 64) * scale, gy = (narrow ? 34 : 44) * scale;
149
+ const mx = lanes ? gx / 2 : MARGIN + (framed ? FRAME_PAD : 0), my = MARGIN + (framed ? FRAME_PAD + FRAME_TITLE - 8 : 0) + (lanes ? 36 : 0), myb = MARGIN + (framed ? FRAME_PAD : 0);
150
+ // where each key sits in the grid
151
+ const cells = new Map();
152
+ rows.forEach((r, ri) => r.forEach((k, ci) => {
153
+ if (k === '.')
154
+ return;
155
+ if (!(k in spec.nodes))
156
+ throw new Error(`cseen: the grid has "${k}", which is not a node`);
157
+ const c = cells.get(k);
158
+ if (!c)
159
+ cells.set(k, { c0: ci, c1: ci, r0: ri, r1: ri });
160
+ else {
161
+ c.c0 = Math.min(c.c0, ci);
162
+ c.c1 = Math.max(c.c1, ci);
163
+ c.r0 = Math.min(c.r0, ri);
164
+ c.r1 = Math.max(c.r1, ri);
165
+ }
166
+ }));
167
+ for (const k of keys) {
168
+ const c = cells.get(k);
169
+ if (!c)
170
+ throw new Error(`cseen: the node "${k}" is not in the ${narrow ? 'narrow' : 'wide'} grid`);
171
+ for (let r = c.r0; r <= c.r1; r++)
172
+ for (let q = c.c0; q <= c.c1; q++)
173
+ if (rows[r][q] !== k)
174
+ throw new Error(`cseen: "${k}" does not fill a rectangle of the grid`);
175
+ }
176
+ // on a phone the lanes are gone: an action names its lane when it differs from the one before it
177
+ const lane = (k) => spec.lanes?.[Math.max(0, ...spec.wide.map((r) => r.trim().split(/\s+/).indexOf(k)))];
178
+ const order = [...cells.keys()].sort((p, q) => cells.get(p).r0 - cells.get(q).r0 || cells.get(p).c0 - cells.get(q).c0);
179
+ const lead = new Map();
180
+ if (narrow && spec.lanes)
181
+ order.reduce((before, k) => { const l = lane(k); if (!('action' in spec.nodes[k]))
182
+ return before; if (l && l !== before)
183
+ lead.set(k, l); return l ?? before; }, undefined);
184
+ const nR = rows.length, edges = (spec.edges ?? []).map((e) => this.edgeOf(e));
185
+ for (const e of edges)
186
+ if (!(e.from in spec.nodes) || !(e.to in spec.nodes))
187
+ throw new Error(`cseen: the edge "${e.from}" to "${e.to}" names a node that does not exist`);
188
+ // On a phone, nodes wrap. Start with none, then narrow the widest column that can wrap until the diagram fits.
189
+ const caps = Array(cols).fill(Infinity);
190
+ let items = new Map(), colW = [], rowH = [], gapX = [], gapY = [];
191
+ for (let pass = 0;; pass++) {
192
+ items = new Map(keys.map((k, i) => [k, { ...this.size(k, spec.nodes[k], caps[cells.get(k).c0], lead.get(k)), ...cells.get(k), id: i + 1 }]));
193
+ colW = Array(cols).fill(0);
194
+ rowH = Array(nR).fill(0);
195
+ gapX = Array(Math.max(0, cols - 1)).fill(gx);
196
+ gapY = Array(Math.max(0, nR - 1)).fill(gy);
197
+ // a node that spans cells shares its size among them
198
+ for (const it of [...items.values()].sort((p, q) => (p.c1 - p.c0) - (q.c1 - q.c0))) {
199
+ let have = 0;
200
+ for (let c = it.c0; c <= it.c1; c++)
201
+ have += colW[c] + (c < it.c1 ? gapX[c] : 0);
202
+ if (have < it.w)
203
+ for (let c = it.c0; c <= it.c1; c++)
204
+ colW[c] += (it.w - have) / (it.c1 - it.c0 + 1);
205
+ have = 0;
206
+ for (let r = it.r0; r <= it.r1; r++)
207
+ have += rowH[r] + (r < it.r1 ? gapY[r] : 0);
208
+ if (have < it.h)
209
+ for (let r = it.r0; r <= it.r1; r++)
210
+ rowH[r] += (it.h - have) / (it.r1 - it.r0 + 1);
211
+ }
212
+ // words on a line between neighbours in a row need the gap to hold them, with a multiplicity at each end
213
+ for (const e of edges) {
214
+ const a = items.get(e.from), b = items.get(e.to), [l, r] = a.c1 < b.c0 ? [a.c1, b.c0] : b.c1 < a.c0 ? [b.c1, a.c0] : [0, 0];
215
+ if (r - l === 1 && a.r0 <= b.r1 && b.r0 <= a.r1 && e.label)
216
+ gapX[l] = Math.max(gapX[l], textWidth(e.label, FONT) + (e.ends ? 40 : 0) + 24);
217
+ // multiplicities at both ends of a short upright line would sit on each other
218
+ const [u, v] = a.r1 < b.r0 ? [a.r1, b.r0] : b.r1 < a.r0 ? [b.r1, a.r0] : [0, 0];
219
+ if (v - u === 1 && e.ends && e.ends[0] && e.ends[1])
220
+ gapY[u] = Math.max(gapY[u], 64);
221
+ }
222
+ const total = colW.reduce((p, q) => p + q, 0) + gapX.reduce((p, q) => p + q, 0) + 2 * mx;
223
+ if (!narrow || total <= NARROW || pass > 24)
224
+ break;
225
+ const wraps = colW.map((w, c) => ([...items.values()].some((it) => it.c0 === it.c1 && it.c0 === c && it.type !== 'class' && it.type !== 'actor' && it.w > 80) ? w : 0));
226
+ const c = wraps.indexOf(Math.max(...wraps));
227
+ if (wraps[c] === 0)
228
+ break;
229
+ caps[c] = Math.max(80, colW[c] - (total - NARROW));
230
+ }
231
+ const list = [...items.values()];
232
+ const colX = [], rowY = [];
233
+ colW.forEach((w, c) => { colX[c] = c ? colX[c - 1] + colW[c - 1] + gapX[c - 1] : mx; });
234
+ rowH.forEach((h, r) => { rowY[r] = r ? rowY[r - 1] + rowH[r - 1] + gapY[r - 1] : my; });
235
+ const W = colX[cols - 1] + colW[cols - 1] + mx, H = rowY[nR - 1] + rowH[nR - 1] + myb;
236
+ this.placed.area = { x0: 0, y0: 0, x1: W, y1: H };
237
+ for (const it of list) {
238
+ const x0 = colX[it.c0], x1 = colX[it.c1] + colW[it.c1], y0 = rowY[it.r0], y1 = rowY[it.r1] + rowH[it.r1];
239
+ const h = it.type === 'actor' ? 54 : it.h;
240
+ it.x = (x0 + x1) / 2 - it.w / 2;
241
+ it.y = it.type === 'actor' ? y0 + (y1 - y0 - (54 + it.text.length * 14 + 10)) / 2 : (y0 + y1) / 2 - h / 2;
242
+ it.h = h;
243
+ }
244
+ // the outer frame and its tab
245
+ const name = `${spec.kind} ${spec.name ?? ''}`.trim();
246
+ if (spec.name) {
247
+ const tw = textWidth(name, FONT) + 20;
248
+ if (tw + 10 > W)
249
+ this.extra.push(`the title "${name}" is wider than the diagram`);
250
+ this.stroke([[0, -TOP], [W, -TOP], [W, H], [0, H]], 'ink', { closed: true, layer: -3, width: 1 });
251
+ this.stroke([[0, -TOP + 22], [tw, -TOP + 22], [tw + 10, -TOP + 12], [tw + 10, -TOP]], 'ink', { layer: -3, width: 1 });
252
+ this.words(name, 10, -TOP + 11, { align: 'start', layer: 3, width: textWidth(name, FONT) });
253
+ }
254
+ if (lanes)
255
+ this.lanes(lanes, colX, colW, gapX, W, H);
256
+ // the nodes
257
+ for (const it of list)
258
+ this.draw(it);
259
+ const obstacles = this.placed.boxes.map((b) => b);
260
+ for (const it of list)
261
+ if (it.type === 'actor')
262
+ obstacles.push(this.actorTitle(it));
263
+ // frames: a rectangle round the nodes they hold, and nothing else may be inside it
264
+ const framed_ = [];
265
+ for (const f of spec.frames ?? []) {
266
+ const held = f.around.map((k) => { const it = items.get(k); if (!it)
267
+ throw new Error(`cseen: the frame "${f.title}" holds "${k}", which is not a node`); return it; });
268
+ const r = { x0: Math.min(...held.map((i) => i.x)) - FRAME_PAD, y0: Math.min(...held.map((i) => i.y)) - FRAME_PAD - FRAME_TITLE + 8, x1: Math.max(...held.map((i) => i.x + i.w)) + FRAME_PAD, y1: Math.max(...held.map((i) => i.y + i.h)) + FRAME_PAD };
269
+ framed_.push({ keys: new Set(f.around), r });
270
+ this.stroke([[r.x0, r.y0], [r.x1, r.y0], [r.x1, r.y1], [r.x0, r.y1]], 'ink', { closed: true, layer: -3, width: 1 });
271
+ this.words(f.title, r.x0 + 10, r.y0 + 14, { align: 'start', role: 'faint', layer: 3, width: textWidth(f.title, FONT) });
272
+ this.note(f.title, r.x0 + 10, r.y0 + 14);
273
+ if (r.x0 < 0 || r.y0 < 0 || r.x1 > W || r.y1 > H)
274
+ this.extra.push(`the frame "${f.title}" leaves the diagram`);
275
+ for (const it of list)
276
+ if (!f.around.includes(it.key) && overlap(r, { x0: it.x, y0: it.y, x1: it.x + it.w, y1: it.y + it.h }))
277
+ this.extra.push(`box "${it.name}" is inside the frame "${f.title}", which does not hold it`);
278
+ }
279
+ // the lines
280
+ // a line between two nodes of a frame stays inside it, so the frame gets channels of its own, just in from its sides
281
+ const inner = framed_.flatMap(({ r }) => [[r.x0 + FRAME_PAD / 2, r.x1 - FRAME_PAD / 2, r.y1 - FRAME_PAD / 2]]);
282
+ const grid = { xs: [...colX.flatMap((x, c) => [x + colW[c] / 2, x - (c ? gapX[c - 1] / 2 : mx / 2)]), W - mx / 2, ...inner.flatMap((q) => [q[0], q[1]])], ys: [...rowY.flatMap((y, r) => [y + rowH[r] / 2, y - (r ? gapY[r - 1] / 2 : my / 2)]), H - myb / 2, ...inner.map((q) => q[2])] };
283
+ const router = new Router(grid, W, H);
284
+ router.borders = this.placed.borders.map(([p]) => p[0]);
285
+ // every line is routed before any words are placed, so a word never lands where a later line will run
286
+ const routes = edges.map((e, k) => this.route(e, k + 1, items, router, obstacles, framed_.find((f) => f.keys.has(e.from) && f.keys.has(e.to))?.r));
287
+ edges.forEach((e, k) => this.line(e, k + 1, routes[k]));
288
+ }
289
+ /** the defaults of UML for a line: its head and whether it is dashed */
290
+ edgeOf(e) {
291
+ const a = this.spec.nodes[e.from], b = this.spec.nodes[e.to];
292
+ const actorUse = !!a && !!b && (('actor' in a && 'useCase' in b) || ('useCase' in a && 'actor' in b)), keyword = !!e.label && /^«/.test(e.label);
293
+ let label = e.label;
294
+ if (label && a && 'decision' in a && !/^[[«]/.test(label))
295
+ label = `[${label}]`;
296
+ const toInterface = !!b && 'class' in b && b.stereotype === 'interface' && !!a && 'class' in a && !e.label;
297
+ return { ...e, label, head: e.head ?? (toInterface ? 'inherit' : actorUse ? 'none' : 'open'), dash: e.dash ?? (keyword || (toInterface && !e.head)) };
298
+ }
299
+ actorTitle(it) {
300
+ const w = Math.max(...it.text.map((l) => textWidth(l, FONT)));
301
+ return { x0: it.x + it.w / 2 - w / 2, x1: it.x + it.w / 2 + w / 2, y0: it.y + 54, y1: it.y + 54 + it.text.length * 14 + 10 };
302
+ }
303
+ lanes(names, colX, colW, gapX, W, H) {
304
+ names.forEach((n, i) => {
305
+ const x0 = i ? colX[i] - gapX[i - 1] / 2 : 0, x1 = i < names.length - 1 ? colX[i] + colW[i] + gapX[i] / 2 : W;
306
+ this.stroke([[x0, 0], [x1, 0], [x1, H], [x0, H]], 'ink', { closed: true, layer: -3, width: 1 });
307
+ this.stroke([[x0, 30], [x1, 30]], 'ink', { layer: -3, width: 1 });
308
+ this.words(n, (x0 + x1) / 2, 15, { layer: 3 });
309
+ this.note(n, (x0 + x1) / 2 - textWidth(n, FONT) / 2, 15);
310
+ if (i)
311
+ this.placed.borders.push([[x0, 0], [x0, H]]);
312
+ });
313
+ }
314
+ /* ------------------------------------------------------------ one node */
315
+ draw(it) {
316
+ const { x, y, w, h } = it, cx = x + w / 2, cy = y + h / 2, role = it.spec.role ?? 'ink';
317
+ const accent = it.spec.role === 'accent';
318
+ const group = new UmlNode(it.name, { x0: x, y0: y, x1: x + w, y1: y + h });
319
+ this.nodes.set(it.key, this.add(group));
320
+ const text = it.text;
321
+ const claim = (rx, ry, rw, rh) => {
322
+ const b = { x0: rx, y0: ry, x1: rx + rw, y1: ry + rh, id: it.id, name: it.name };
323
+ this.placed.boxes.push(b);
324
+ return b;
325
+ };
326
+ const centred = (ls, tx, ty) => {
327
+ this.words(ls.join('\n'), tx, ty - (ls.length * LINE) / 2 + LINE / 2, { role: undefined, width: Math.max(...ls.map((l) => textWidth(l, FONT))) });
328
+ this.note(ls.join('\n'), tx - Math.max(...ls.map((l) => textWidth(l, FONT))) / 2, ty - ((ls.length - 1) * LINE) / 2, { box: it.id });
329
+ };
330
+ let outline = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
331
+ switch (it.type) {
332
+ case 'actor': {
333
+ claim(cx - 14, y, 28, 54);
334
+ this.oval(cx, y + 8, 8, 8, role, 0.04, 1);
335
+ for (const seg of [[[cx, y + 16], [cx, y + 38]], [[cx - 14, y + 24], [cx + 14, y + 24]], [[cx - 11, y + 54], [cx, y + 38], [cx + 11, y + 54]]])
336
+ this.stroke(seg, role, { layer: 1, width: 1.2 });
337
+ it.text.forEach((l, i) => {
338
+ const wl = textWidth(l, FONT);
339
+ this.words(l, cx, y + 54 + 13 + i * 14, { width: wl });
340
+ this.note(l, cx - wl / 2, y + 54 + 13 + i * 14);
341
+ });
342
+ outline = [[cx - 14, y], [cx + 14, y], [cx + 14, y + 54 + it.text.length * 14 + 10], [cx - 14, y + 54 + it.text.length * 14 + 10]];
343
+ break;
344
+ }
345
+ case 'usecase':
346
+ claim(x, y, w, h);
347
+ this.oval(cx, cy, w / 2, h / 2, role, accent ? 0.14 : 0.04);
348
+ centred(text, cx, cy);
349
+ break;
350
+ case 'state':
351
+ case 'action':
352
+ claim(x, y, w, h);
353
+ this.rounded(x, y, w, h, it.type === 'state' ? 10 : 14, role, accent ? 0.14 : 0.05);
354
+ centred(text, cx, cy);
355
+ break;
356
+ case 'box':
357
+ claim(x, y, w, h);
358
+ this.shape(outline, role, accent ? 0.14 : 0.04);
359
+ centred(text, cx, cy);
360
+ break;
361
+ case 'decision':
362
+ claim(x, y, w, h);
363
+ this.shape([[cx, y], [x + w, cy], [cx, y + h], [x, cy]], 'accent', 0.16);
364
+ outline = [[cx, y], [x + w, cy], [cx, y + h], [x, cy]];
365
+ break;
366
+ case 'start':
367
+ claim(x, y, w, h);
368
+ this.oval(cx, cy, 7, 7, role, 1);
369
+ break;
370
+ case 'end':
371
+ claim(x, y, w, h);
372
+ this.oval(cx, cy, 9, 9, role, 0);
373
+ this.oval(cx, cy, 5, 5, role, 1, 1);
374
+ break;
375
+ case 'class': {
376
+ const s = it.spec, attrs = s.attrs ?? [], ops = s.ops ?? [], head = s.stereotype ? 44 : 30, part = (n) => (n ? n * LINE + 10 : 12);
377
+ claim(x, y, w, h);
378
+ this.shape(outline, role, 0.04);
379
+ const own = (t, tx, ty, tone, align = 'middle') => {
380
+ const wl = textWidth(t, FONT);
381
+ this.words(t, tx, ty, { role: tone, align, width: wl });
382
+ this.note(t, align === 'start' ? tx : tx - wl / 2, ty, { box: it.id });
383
+ };
384
+ if (s.stereotype)
385
+ own(`«${s.stereotype}»`, cx, y + 14, 'faint');
386
+ own(s.class, cx, y + head - 14, 'accent');
387
+ let top = y + head;
388
+ for (const members of [attrs, ops]) {
389
+ this.stroke([[x, top], [x + w, top]], role, { layer: 1, width: 1 });
390
+ members.forEach((m, i) => own(m, x + 8, top + 12 + i * LINE, undefined, 'start'));
391
+ top += part(members.length);
392
+ }
393
+ break;
394
+ }
395
+ }
396
+ if (it.spec.href)
397
+ group.add(new LinkArea(outline.map(([px, py]) => [px / U, 0, -(py + this.top) / U]), it.spec.href, it.type === 'actor' || it.type === 'usecase' || it.type === 'class' ? it.name : it.text.join(' ') || it.name));
398
+ }
399
+ /* ------------------------------------------------------------ one line */
400
+ route(e, id, items, router, obstacles, within) {
401
+ const a = items.get(e.from), b = items.get(e.to);
402
+ const rect = (i) => (i.type === 'actor' ? { x0: i.x + i.w / 2 - 14, x1: i.x + i.w / 2 + 14, y0: i.y, y1: i.y + 54 } : { x0: i.x, y0: i.y, x1: i.x + i.w, y1: i.y + i.h });
403
+ const mine = new Set(this.placed.boxes.filter((x) => x.id === a.id || x.id === b.id)), ra = rect(a), rb = rect(b), others = obstacles.filter((o) => !mine.has(o));
404
+ let pts, straight = false;
405
+ if (this.spec.kind === 'uc') {
406
+ // an actor's line leaves from an arm and enters the use case at its tip that faces the actor; two use cases meet at the sides that face each other
407
+ const mid = (r) => [(r.x0 + r.x1) / 2, (r.y0 + r.y1) / 2], [ma, mb] = [mid(ra), mid(rb)];
408
+ const sideways = (r, q) => a.type === 'actor' || b.type === 'actor' || r.x1 <= q.x0 || q.x1 <= r.x0;
409
+ const tip = (i, r, q, towards) => (i.type !== 'usecase' ? this.edgePoint(i, r, towards) : sideways(r, q) ? [towards[0] > mid(r)[0] ? r.x1 : r.x0, mid(r)[1]] : [mid(r)[0], towards[1] > mid(r)[1] ? r.y1 : r.y0]);
410
+ const start = a.type === 'actor' ? [mb[0] > ma[0] ? ra.x1 : ra.x0, ra.y0 + 24] : tip(a, ra, rb, mb), end = tip(b, rb, ra, a.type === 'actor' ? start : ma);
411
+ if (!others.some((o) => crosses(start, end, o, 3)) && Math.hypot(end[0] - start[0], end[1] - start[1]) > 4) {
412
+ pts = [start, end];
413
+ straight = true;
414
+ }
415
+ }
416
+ pts ??= router.route(ra, rb, a, b, others, this.placed.segments, within);
417
+ const segs = pts.slice(1).map((q, i) => ({ a: pts[i], b: q, line: id, joins: straight ? [a.id, b.id] : undefined }));
418
+ this.placed.segments.push(...segs);
419
+ return pts;
420
+ }
421
+ line(e, id, pts) {
422
+ // the head replaces the last stretch of the line
423
+ const toW = (p) => [p[0] / U, -(p[1] + this.top) / U];
424
+ const mark = new HeadMark(e.head, e.role ?? 'ink');
425
+ const last = pts[pts.length - 1], prev = pts[pts.length - 2], cut = mark.aim(toW(last), toW(prev));
426
+ const drawn = [...pts.slice(0, -1).map(toW), cut];
427
+ this.lines.push(this.add(new Path(drawn.map(([px, pz]) => [px, 0, pz]), { role: e.role ?? 'ink', width: 1.1, dash: e.dash ? '5 4' : undefined, layer: -1 })));
428
+ this.add(mark);
429
+ if (e.label)
430
+ this.label(e.label, pts, id);
431
+ if (e.ends) {
432
+ const [from, to] = e.ends;
433
+ if (from)
434
+ this.endWord(from, pts[0], pts[1], id, 'none');
435
+ if (to)
436
+ this.endWord(to, last, prev, id, e.head);
437
+ }
438
+ }
439
+ /** where a straight line from the middle of a node towards `toward` leaves its outline */
440
+ edgePoint(i, r, toward) {
441
+ const cx = (r.x0 + r.x1) / 2, cy = (r.y0 + r.y1) / 2, dx = toward[0] - cx, dy = toward[1] - cy;
442
+ if (i.type === 'usecase') {
443
+ const t = 1 / Math.hypot(dx / ((r.x1 - r.x0) / 2), dy / ((r.y1 - r.y0) / 2) || 1);
444
+ return [cx + dx * t, cy + dy * t];
445
+ }
446
+ const t = Math.min(dx ? (r.x1 - r.x0) / 2 / Math.abs(dx) : Infinity, dy ? (r.y1 - r.y0) / 2 / Math.abs(dy) : Infinity);
447
+ return [cx + dx * t, cy + dy * t];
448
+ }
449
+ /** puts words on a line where nothing else is: above a flat stretch, beside an upright one, trying other places if the first is taken */
450
+ label(text, pts, id) {
451
+ const w = textWidth(text, FONT), spots = [];
452
+ const legs = pts.slice(1).map((q, i) => ({ a: pts[i], b: q, len: Math.hypot(q[0] - pts[i][0], q[1] - pts[i][1]) })).sort((p, q) => q.len - p.len);
453
+ for (const { a, b } of legs)
454
+ for (const t of [0.5, 0.4, 0.6, 0.3, 0.7, 0.2, 0.8, 0.12, 0.88]) {
455
+ const x = a[0] + (b[0] - a[0]) * t, y = a[1] + (b[1] - a[1]) * t;
456
+ if (Math.abs(b[1] - a[1]) < 1)
457
+ spots.push({ x, y: y - 10, mask: false }, { x, y: y + 11, mask: false });
458
+ else if (Math.abs(b[0] - a[0]) < 1)
459
+ spots.push({ x: x + w / 2 + 7, y, mask: false }, { x: x - w / 2 - 7, y, mask: false });
460
+ else
461
+ spots.push({ x, y, mask: true });
462
+ }
463
+ const rectOf = (s) => ({ x0: s.x - w / 2, x1: s.x + w / 2, y0: s.y - REACH, y1: s.y + REACH, s: text, line: id });
464
+ const taken = (s) => {
465
+ const r = rectOf(s), { area } = this.placed;
466
+ return r.x0 < area.x0 || r.x1 > area.x1 || r.y0 < area.y0 || r.y1 > area.y1
467
+ || this.placed.boxes.some((b) => overlap(r, b)) || this.placed.texts.some((t) => overlap(r, t))
468
+ || this.placed.borders.some(([p, q]) => crosses(p, q, r, 1))
469
+ || (!s.mask && this.placed.segments.some((g) => g.line !== id && crosses(g.a, g.b, r, 1)));
470
+ };
471
+ // of the free spots, the one with the least line around it, so a word is not mistaken for the words of the line next to it
472
+ const crowd = (s) => this.placed.segments.filter((g) => g.line !== id && crosses(g.a, g.b, rectOf(s), -14)).length;
473
+ // then the one furthest from the lines of others, so a word clearly belongs to its own line
474
+ const apart = (s) => Math.min(40, ...this.placed.segments.filter((g) => g.line !== id).map((g) => {
475
+ const x = Math.max(Math.min(g.a[0], g.b[0]), Math.min(s.x, Math.max(g.a[0], g.b[0]))), y = Math.max(Math.min(g.a[1], g.b[1]), Math.min(s.y, Math.max(g.a[1], g.b[1])));
476
+ return Math.hypot(s.x - x, s.y - y);
477
+ }));
478
+ const score = (s) => crowd(s) * 100 - apart(s);
479
+ const free = spots.filter((s) => !taken(s)), spot = free.length ? free.reduce((best, s) => (score(s) < score(best) ? s : best)) : spots[0];
480
+ const r = rectOf(spot);
481
+ this.placed.texts.push({ ...r, mask: spot.mask });
482
+ this.words(text, spot.x, spot.y, { role: 'faint', back: spot.mask, width: w, layer: 3 });
483
+ }
484
+ /** a multiplicity at the end of a line, beside it */
485
+ endWord(text, at, next, id, head) {
486
+ const dx = next[0] - at[0], dy = next[1] - at[1], w = textWidth(text, FONT), gap = head === 'none' ? 10 : 18;
487
+ const flat = Math.abs(dx) >= Math.abs(dy);
488
+ const x = flat ? at[0] + Math.sign(dx) * (gap + w / 2) : at[0] + 10 + w / 2, y = flat ? at[1] - 10 : at[1] + Math.sign(dy) * gap;
489
+ this.placed.texts.push({ x0: x - w / 2, x1: x + w / 2, y0: y - REACH, y1: y + REACH, s: text, line: id });
490
+ this.words(text, x, y, { role: 'faint', width: w, layer: 3 });
491
+ }
492
+ }
493
+ /**
494
+ * Finds a path of right angles between two boxes that goes through no other box. It searches the crossings of channel
495
+ * lines (the middles of the gaps and of the cells, and the ports) and charges for each turn, for crossing a line already
496
+ * drawn and for running along one.
497
+ */
498
+ class Router {
499
+ grid;
500
+ W;
501
+ H;
502
+ constructor(grid, W, H) { this.grid = grid; this.W = W; this.H = H; }
503
+ used = new Map();
504
+ /** x of the lane borders: running along one hides the line in it */
505
+ borders = [];
506
+ /** the ports of a box: the middle of each side, and a quarter of the way along when the shape allows it */
507
+ ports(r, node) {
508
+ const out = [], w = r.x1 - r.x0, h = r.y1 - r.y0;
509
+ const fr = node.type === 'class' || node.type === 'box' || node.type === 'state' || node.type === 'action' ? [0.5, 0.25, 0.75] : [0.5];
510
+ const arm = node.type === 'actor';
511
+ for (const f of fr) {
512
+ const cost = f === 0.5 ? 0 : 8;
513
+ out.push({ p: [r.x0 + w * f, r.y0], out: [0, -1], cost }, { p: [r.x0 + w * f, r.y1], out: [0, 1], cost });
514
+ out.push({ p: [r.x0, r.y0 + (arm ? 24 : h * f)], out: [-1, 0], cost }, { p: [r.x1, r.y0 + (arm ? 24 : h * f)], out: [1, 0], cost });
515
+ }
516
+ return out.map((q) => ({ ...q, cost: q.cost + 6 * (this.used.get(`${q.p}`) ?? 0) }));
517
+ }
518
+ /** a path that keeps `clear` pixels from every other box, or, failing that, as close as 3 */
519
+ route(ra, rb, a, b, others, laid, within) {
520
+ return this.find(ra, rb, a, b, others, laid, 9, within) ?? this.find(ra, rb, a, b, others, laid, -3, within) ?? [[ra.x1, (ra.y0 + ra.y1) / 2], [rb.x0, (rb.y0 + rb.y1) / 2]]; // nothing clears the boxes: draw it straight and let the check say so
521
+ }
522
+ find(ra, rb, a, b, others, laid, clear, within) {
523
+ const src = this.ports(ra, a), dst = this.ports(rb, b);
524
+ const xs = [...new Set([...this.grid.xs, 8, this.W - 8, ...src.concat(dst).map((q) => q.p[0])].map((v) => Math.round(v * 2) / 2))].sort((p, q) => p - q);
525
+ const ys = [...new Set([...this.grid.ys, 8, this.H - 8, ...src.concat(dst).map((q) => q.p[1])].map((v) => Math.round(v * 2) / 2))].sort((p, q) => p - q);
526
+ const xi = new Map(xs.map((v, i) => [v, i])), yi = new Map(ys.map((v, i) => [v, i]));
527
+ const at = (p) => [xi.get(Math.round(p[0] * 2) / 2), yi.get(Math.round(p[1] * 2) / 2)];
528
+ const dirs = [[1, 0], [0, 1], [-1, 0], [0, -1]];
529
+ const goal = new Map();
530
+ for (const q of dst) {
531
+ const [i, j] = at(q.p);
532
+ goal.set(`${i},${j},${dirs.findIndex((d) => d[0] === -q.out[0] && d[1] === -q.out[1])}`, q.cost);
533
+ }
534
+ const outside = (q) => !!within && (q[0] < within.x0 + 3 || q[0] > within.x1 - 3 || q[1] < within.y0 + 3 || q[1] > within.y1 - 3);
535
+ const blocked = (p, q) => outside(p) || outside(q) || others.some((o) => crosses(p, q, o, -clear));
536
+ const dist = new Map(), prev = new Map(), open = [];
537
+ const push = (k, c, from) => { if (c < (dist.get(k) ?? Infinity)) {
538
+ dist.set(k, c);
539
+ if (from)
540
+ prev.set(k, from);
541
+ open.push([c, k]);
542
+ } };
543
+ for (const q of src) {
544
+ const [i, j] = at(q.p);
545
+ push(`${i},${j},${dirs.findIndex((d) => d[0] === q.out[0] && d[1] === q.out[1])}`, q.cost);
546
+ }
547
+ let best, bestCost = Infinity;
548
+ while (open.length) {
549
+ open.sort((p, q) => q[0] - p[0]);
550
+ const [c, k] = open.pop();
551
+ if (c > (dist.get(k) ?? Infinity))
552
+ continue;
553
+ if (c >= bestCost)
554
+ break;
555
+ const [i, j, d] = k.split(',').map(Number);
556
+ if (goal.has(k) && c + goal.get(k) < bestCost) {
557
+ best = k;
558
+ bestCost = c + goal.get(k);
559
+ }
560
+ for (let nd = 0; nd < 4; nd++) {
561
+ if (nd === (d + 2) % 4)
562
+ continue;
563
+ const ni = i + dirs[nd][0], nj = j + dirs[nd][1];
564
+ if (ni < 0 || nj < 0 || ni >= xs.length || nj >= ys.length)
565
+ continue;
566
+ const p = [xs[i], ys[j]], q = [xs[ni], ys[nj]];
567
+ if (blocked(p, q))
568
+ continue;
569
+ let cost = Math.abs(q[0] - p[0]) + Math.abs(q[1] - p[1]) + (nd === d ? 0 : 26);
570
+ if (nd % 2 === 1 && this.borders.some((bx) => Math.abs(bx - p[0]) < 4))
571
+ cost += 90;
572
+ for (const s of laid) {
573
+ const flatS = Math.abs(s.a[1] - s.b[1]) < 0.5, flatQ = Math.abs(q[1] - p[1]) < 0.5;
574
+ if (flatS === flatQ) {
575
+ if (flatS ? Math.abs(s.a[1] - p[1]) < 0.5 && Math.min(s.a[0], s.b[0]) < Math.max(p[0], q[0]) - 1 && Math.max(s.a[0], s.b[0]) > Math.min(p[0], q[0]) + 1 : Math.abs(s.a[0] - p[0]) < 0.5 && Math.min(s.a[1], s.b[1]) < Math.max(p[1], q[1]) - 1 && Math.max(s.a[1], s.b[1]) > Math.min(p[1], q[1]) + 1)
576
+ cost += 70;
577
+ }
578
+ else if (crosses(s.a, s.b, { x0: Math.min(p[0], q[0]) - 1, x1: Math.max(p[0], q[0]) + 1, y0: Math.min(p[1], q[1]) - 1, y1: Math.max(p[1], q[1]) + 1 }, 0))
579
+ cost += 34;
580
+ }
581
+ push(`${ni},${nj},${nd}`, c + cost, k);
582
+ }
583
+ }
584
+ if (!best)
585
+ return undefined;
586
+ const path = [];
587
+ for (let k = best; k; k = prev.get(k)) {
588
+ const [i, j] = k.split(',').map(Number);
589
+ path.push([xs[i], ys[j]]);
590
+ }
591
+ path.reverse();
592
+ // drop the points where the line goes straight on
593
+ const out = path.filter((p, i) => !i || i === path.length - 1 || !((path[i - 1][0] === p[0] && p[0] === path[i + 1][0]) || (path[i - 1][1] === p[1] && p[1] === path[i + 1][1])));
594
+ for (const q of [out[0], out[out.length - 1]])
595
+ this.used.set(`${q}`, (this.used.get(`${q}`) ?? 0) + 1);
596
+ return out;
597
+ }
598
+ }
599
+ //# sourceMappingURL=uml.js.map