@diagc/cli 1.5.0 → 1.7.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 (76) hide show
  1. package/README.md +8 -3
  2. package/assets/guide/index.md +1 -1
  3. package/assets/skill/SKILL.md +1 -1
  4. package/dist/cli/io.d.ts +5 -0
  5. package/dist/cli/io.js +4 -0
  6. package/dist/cli/parse.d.ts +7 -0
  7. package/dist/cli/parse.js +25 -0
  8. package/dist/cli/run.js +4 -0
  9. package/dist/cli.js +24 -2
  10. package/dist/commands/shared.d.ts +4 -0
  11. package/dist/commands/shared.js +13 -0
  12. package/dist/commands/show.d.ts +5 -0
  13. package/dist/commands/show.js +115 -0
  14. package/dist/commands/tui.d.ts +3 -0
  15. package/dist/commands/tui.js +44 -0
  16. package/dist/init.d.ts +1 -1
  17. package/dist/init.js +1 -1
  18. package/dist/text/accents.d.ts +9 -0
  19. package/dist/text/accents.js +83 -0
  20. package/dist/text/ansi.d.ts +28 -0
  21. package/dist/text/ansi.js +117 -0
  22. package/dist/text/braille.d.ts +28 -0
  23. package/dist/text/braille.js +58 -0
  24. package/dist/text/canvas.d.ts +72 -0
  25. package/dist/text/canvas.js +173 -0
  26. package/dist/text/content.d.ts +32 -0
  27. package/dist/text/content.js +90 -0
  28. package/dist/text/dos.d.ts +69 -0
  29. package/dist/text/dos.js +93 -0
  30. package/dist/text/fish.d.ts +27 -0
  31. package/dist/text/fish.js +209 -0
  32. package/dist/text/folds.d.ts +14 -0
  33. package/dist/text/folds.js +45 -0
  34. package/dist/text/glyphs.d.ts +32 -0
  35. package/dist/text/glyphs.js +100 -0
  36. package/dist/text/layout.d.ts +70 -0
  37. package/dist/text/layout.js +337 -0
  38. package/dist/text/legend.d.ts +44 -0
  39. package/dist/text/legend.js +256 -0
  40. package/dist/text/paint.d.ts +27 -0
  41. package/dist/text/paint.js +260 -0
  42. package/dist/text/render.d.ts +11 -0
  43. package/dist/text/render.js +28 -0
  44. package/dist/text/scene.d.ts +44 -0
  45. package/dist/text/scene.js +58 -0
  46. package/dist/text/vocabulary.d.ts +37 -0
  47. package/dist/text/vocabulary.js +211 -0
  48. package/dist/text/width.d.ts +15 -0
  49. package/dist/text/width.js +181 -0
  50. package/dist/tui/actions.d.ts +15 -0
  51. package/dist/tui/actions.js +300 -0
  52. package/dist/tui/app.d.ts +34 -0
  53. package/dist/tui/app.js +402 -0
  54. package/dist/tui/details.d.ts +3 -0
  55. package/dist/tui/details.js +54 -0
  56. package/dist/tui/keys.d.ts +33 -0
  57. package/dist/tui/keys.js +113 -0
  58. package/dist/tui/kitty.d.ts +36 -0
  59. package/dist/tui/kitty.js +65 -0
  60. package/dist/tui/legend.d.ts +14 -0
  61. package/dist/tui/legend.js +18 -0
  62. package/dist/tui/nav.d.ts +31 -0
  63. package/dist/tui/nav.js +101 -0
  64. package/dist/tui/overview.d.ts +48 -0
  65. package/dist/tui/overview.js +145 -0
  66. package/dist/tui/pixels.d.ts +28 -0
  67. package/dist/tui/pixels.js +80 -0
  68. package/dist/tui/screen.d.ts +54 -0
  69. package/dist/tui/screen.js +416 -0
  70. package/dist/tui/state.d.ts +102 -0
  71. package/dist/tui/state.js +80 -0
  72. package/dist/tui/terminal.d.ts +21 -0
  73. package/dist/tui/terminal.js +53 -0
  74. package/dist/watch.d.ts +2 -0
  75. package/dist/watch.js +1 -0
  76. package/package.json +3 -2
@@ -0,0 +1,337 @@
1
+ import ELK from 'elkjs/lib/elk.bundled.js';
2
+ import { DOWN, LEFT, RIGHT, UP } from './glyphs.js';
3
+ import { cellWidth } from './width.js';
4
+ /**
5
+ * elk `layered`, in character cells: a node is as big as its text, and the gaps
6
+ * are a few cells. elk's options do not inherit into nested graphs, and every one it
7
+ * is not told falls back to its pixel-sized default (10, 12, 20 …), which in cells
8
+ * opens tens of rows between the levels of a container — so this set goes on the
9
+ * root and on every container alike.
10
+ */
11
+ export const CELL_OPTIONS = {
12
+ 'elk.algorithm': 'layered',
13
+ 'elk.edgeRouting': 'ORTHOGONAL',
14
+ 'elk.spacing.nodeNode': '4',
15
+ 'elk.layered.spacing.nodeNodeBetweenLayers': '2',
16
+ 'elk.spacing.edgeNode': '2',
17
+ 'elk.spacing.edgeEdge': '1',
18
+ 'elk.layered.spacing.edgeNodeBetweenLayers': '1',
19
+ 'elk.layered.spacing.edgeEdgeBetweenLayers': '1',
20
+ 'elk.spacing.edgeLabel': '1',
21
+ 'elk.spacing.labelLabel': '0',
22
+ 'elk.spacing.labelNode': '0',
23
+ 'elk.spacing.portPort': '1',
24
+ 'elk.spacing.componentComponent': '4',
25
+ 'elk.separateConnectedComponents': 'true',
26
+ };
27
+ /** Inside a container's frame: the title row and a blank one above the children, a
28
+ * row below, two columns either side, and the reach of a child's shadow beyond that,
29
+ * as the page's padding holds it. */
30
+ const containerPadding = ({ x, y } = { x: 0, y: 0 }) => `[top=2,left=2,bottom=${1 + y},right=${2 + x}]`;
31
+ /** The gaps for a flow. A cell is about twice as tall as it is wide, so a sideways
32
+ * flow's gap between neighbours, counted in rows, is half a downward one's, counted in
33
+ * columns, and its gap between levels twice: turned, the boxes keep their spacing. Only
34
+ * those two gaps are scaled. The clearances around lines are a cell or two already,
35
+ * near the least a grid of cells can hold, so they stay as written in every flow. */
36
+ function cellOptions(direction) {
37
+ if (direction === 'DOWN' || direction === 'UP')
38
+ return CELL_OPTIONS;
39
+ return { ...CELL_OPTIONS, 'elk.spacing.nodeNode': '2', 'elk.layered.spacing.nodeNodeBetweenLayers': '4' };
40
+ }
41
+ const elk = new ELK();
42
+ function elkNode(vn, boxes, flow) {
43
+ const { direction } = flow;
44
+ const box = boxes.get(vn.id);
45
+ const width = box?.width ?? 5;
46
+ const height = box?.height ?? 3;
47
+ if (vn.state !== 'expanded' || vn.children.length === 0)
48
+ return { id: vn.id, width, height };
49
+ // layered works left to right and turns a vertical flow afterwards, and the minimum
50
+ // size of a hierarchical node is read before the turn: under DOWN or UP it has to
51
+ // be given as (height, width) to come out as (width, height). Measured on elkjs
52
+ // 0.12 with INCLUDE_CHILDREN — layout.test.ts pins all four directions.
53
+ const vertical = direction === 'DOWN' || direction === 'UP';
54
+ return {
55
+ id: vn.id,
56
+ layoutOptions: {
57
+ ...cellOptions(direction),
58
+ 'elk.direction': direction,
59
+ 'elk.padding': containerPadding(flow.shadow),
60
+ 'elk.nodeSize.constraints': 'MINIMUM_SIZE',
61
+ 'elk.nodeSize.minimum': vertical ? `(${height}, ${width})` : `(${width}, ${height})`,
62
+ },
63
+ children: vn.children.map((c) => elkNode(c, boxes, flow)),
64
+ };
65
+ }
66
+ function elkEdges(view, labels) {
67
+ return view.layoutEdges.map((e) => {
68
+ const text = labels.get(e.id) ?? '';
69
+ return {
70
+ id: e.id,
71
+ sources: [e.from],
72
+ targets: [e.to],
73
+ ...(text !== '' ? { labels: [{ text, width: cellWidth(text), height: 1 }] } : {}),
74
+ };
75
+ });
76
+ }
77
+ /** elk's tree, read back into absolute cells. A box's edges are rounded, not its
78
+ * size, so two boxes elk set side by side stay side by side after rounding. */
79
+ function collect(root) {
80
+ const out = { boxes: new Map(), origins: new Map(), edges: [] };
81
+ const walk = (n, ax, ay) => {
82
+ const x = ax + (n.x ?? 0);
83
+ const y = ay + (n.y ?? 0);
84
+ out.origins.set(n.id, { x, y });
85
+ if (n !== root) {
86
+ const left = Math.round(x);
87
+ const top = Math.round(y);
88
+ out.boxes.set(n.id, {
89
+ x: left,
90
+ y: top,
91
+ width: Math.round(x + (n.width ?? 0)) - left,
92
+ height: Math.round(y + (n.height ?? 0)) - top,
93
+ });
94
+ }
95
+ for (const edge of (n.edges ?? []))
96
+ out.edges.push({ edge, owner: { x, y } });
97
+ n.children?.forEach((c) => walk(c, x, y));
98
+ };
99
+ walk(root, 0, 0);
100
+ return out;
101
+ }
102
+ const onBorder = (p, b) => {
103
+ const inX = p.x >= b.x && p.x < b.x + b.width;
104
+ const inY = p.y >= b.y && p.y < b.y + b.height;
105
+ return (inX && (p.y === b.y || p.y === b.y + b.height - 1)) || (inY && (p.x === b.x || p.x === b.x + b.width - 1));
106
+ };
107
+ /** An end that lands on its box's border, moved one cell towards where the route
108
+ * comes from. elk ends a route ON the box's outline; a cell is either border or not,
109
+ * and the border cell belongs to the box, so the end — the arrowhead — has to sit in
110
+ * the next cell out (or in, for a container's edge to something inside it). */
111
+ function offBorder(end, from, box) {
112
+ if (box === undefined || !onBorder(end, box))
113
+ return end;
114
+ if (from.x !== end.x)
115
+ return { x: end.x + Math.sign(from.x - end.x), y: end.y };
116
+ if (from.y !== end.y)
117
+ return { x: end.x, y: end.y + Math.sign(from.y - end.y) };
118
+ return end;
119
+ }
120
+ /** Where a box is from an end of a route that stops beside it: the direction (a
121
+ * glyph mask bit) to step from the end to reach its border; undefined when the end is
122
+ * not beside it. */
123
+ export function towardBox(end, g) {
124
+ const inX = end.x >= g.x && end.x < g.x + g.width;
125
+ const inY = end.y >= g.y && end.y < g.y + g.height;
126
+ if (inX && end.y === g.y + g.height)
127
+ return UP;
128
+ if (inX && end.y === g.y - 1)
129
+ return DOWN;
130
+ if (inY && end.x === g.x - 1)
131
+ return RIGHT;
132
+ if (inY && end.x === g.x + g.width)
133
+ return LEFT;
134
+ return undefined;
135
+ }
136
+ /** One cell's step in each direction. */
137
+ export const STEP = {
138
+ [UP]: { x: 0, y: -1 },
139
+ [DOWN]: { x: 0, y: 1 },
140
+ [LEFT]: { x: -1, y: 0 },
141
+ [RIGHT]: { x: 1, y: 0 },
142
+ };
143
+ const encloses = (outer, inner) => outer.x <= inner.x &&
144
+ outer.y <= inner.y &&
145
+ outer.x + outer.width >= inner.x + inner.width &&
146
+ outer.y + outer.height >= inner.y + inner.height;
147
+ const clamp = (v, low, high) => Math.max(low, Math.min(v, high));
148
+ /** Where an end goes: beside its box (`offBorder`) — unless the box is a container
149
+ * holding the other end, where it goes on the container's frame. Between a child and
150
+ * its own frame there is no cell to spare, and an end moved outside would draw the
151
+ * edge leaving the box it points into. */
152
+ function placeEnd(end, next, box, other) {
153
+ if (box === undefined || other === undefined || box === other || !encloses(box, other))
154
+ return offBorder(end, next, box);
155
+ return { x: clamp(end.x, box.x, box.x + box.width - 1), y: clamp(end.y, box.y, box.y + box.height - 1) };
156
+ }
157
+ /**
158
+ * A route squeezed into one cell: a child flush against its own frame, where the
159
+ * cell is the frame's. From the child, the route starts on the child's border, so
160
+ * the cell has a way in; into the child, the cell is both ends, beside the child.
161
+ * Anything else that folds to one cell is no route at all.
162
+ */
163
+ function oneCell(cell, source, target) {
164
+ const out = source === undefined ? undefined : towardBox(cell, source);
165
+ if (out !== undefined)
166
+ return [{ x: cell.x + STEP[out].x, y: cell.y + STEP[out].y }, cell];
167
+ if (target !== undefined && towardBox(cell, target) !== undefined)
168
+ return [cell, cell];
169
+ return [cell];
170
+ }
171
+ const sameCell = (a, b) => a.x === b.x && a.y === b.y;
172
+ /** Where an end beside a corner of its box goes: beside the nearest cell of that side
173
+ * that is not a corner, so the arrow points at the box and not at its corner. An end
174
+ * beside the middle of a side, or not beside the box at all, stays. */
175
+ function besideSide(end, box) {
176
+ const toward = towardBox(end, box);
177
+ if (toward === LEFT || toward === RIGHT)
178
+ return { x: end.x, y: clamp(end.y, box.y + 1, box.y + box.height - 2) };
179
+ if (toward === UP || toward === DOWN)
180
+ return { x: clamp(end.x, box.x + 1, box.x + box.width - 2), y: end.y };
181
+ return end;
182
+ }
183
+ /**
184
+ * The route with its last point beside the side of its box (`besideSide`). A box one
185
+ * line of text tall has one row between its corners, and on a sideways flow elk's ends
186
+ * miss it: a lone end, in the middle of the side, is half a cell into that row and
187
+ * rounds onto the border's, and several are spread over the whole side. Where the
188
+ * last segment meets the side square on it moves along
189
+ * with the end, staying straight; on a route of one segment that moves the other end
190
+ * too, so where that one would leave the middle of its own box's side the route jogs
191
+ * halfway instead.
192
+ */
193
+ function slideEnd(points, box, other) {
194
+ const end = points.at(-1);
195
+ const before = points.at(-2);
196
+ const to = box === undefined ? end : besideSide(end, box);
197
+ if (sameCell(to, end))
198
+ return points;
199
+ const [dx, dy] = [to.x - end.x, to.y - end.y];
200
+ const squareOn = dx !== 0 ? before.x === end.x : before.y === end.y;
201
+ if (!squareOn)
202
+ return [...points.slice(0, -1), to];
203
+ const moved = { x: before.x + dx, y: before.y + dy };
204
+ const stays = points.length > 2 ||
205
+ other === undefined ||
206
+ (towardBox(moved, other) !== undefined && sameCell(besideSide(moved, other), moved));
207
+ if (stays)
208
+ return [...points.slice(0, -2), moved, to];
209
+ const half = dy !== 0 ? Math.floor((before.x + end.x) / 2) : Math.floor((before.y + end.y) / 2);
210
+ const jog = dy !== 0
211
+ ? [
212
+ { x: half, y: before.y },
213
+ { x: half, y: to.y },
214
+ ]
215
+ : [
216
+ { x: before.x, y: half },
217
+ { x: to.x, y: half },
218
+ ];
219
+ return [before, ...jog, to];
220
+ }
221
+ /** Both ends of a route beside the sides of their boxes, not their corners. */
222
+ function offCorners(points, source, target) {
223
+ const ended = slideEnd(points, target, source);
224
+ return orthogonal(slideEnd([...ended].reverse(), source, target).reverse());
225
+ }
226
+ /** Points with repeats and straight-through middles dropped, and a corner put in
227
+ * wherever rounding left two consecutive points apart on both axes. */
228
+ function orthogonal(points) {
229
+ const out = [];
230
+ for (const p of points) {
231
+ const last = out.at(-1);
232
+ if (last !== undefined && last.x === p.x && last.y === p.y)
233
+ continue;
234
+ if (last !== undefined && last.x !== p.x && last.y !== p.y)
235
+ out.push({ x: p.x, y: last.y });
236
+ out.push(p);
237
+ }
238
+ return out.filter((p, i) => {
239
+ const [a, b] = [out[i - 1], out[i + 1]];
240
+ return a === undefined || b === undefined || !((a.x === p.x && p.x === b.x) || (a.y === p.y && p.y === b.y));
241
+ });
242
+ }
243
+ function routeOf(entry, laid, labels) {
244
+ const { edge, owner } = entry;
245
+ const section = edge.sections?.[0];
246
+ if (section === undefined)
247
+ return undefined;
248
+ // Under INCLUDE_CHILDREN elk states a route in the frame of the endpoints' lowest
249
+ // common ancestor (`container`), not of the node the edge was declared on; see the
250
+ // renderer's collectLaid for the long version.
251
+ const o = (edge.container !== undefined ? laid.origins.get(edge.container) : undefined) ?? owner;
252
+ const raw = [section.startPoint, ...(section.bendPoints ?? []), section.endPoint].map((p) => ({
253
+ x: Math.round(o.x + p.x),
254
+ y: Math.round(o.y + p.y),
255
+ }));
256
+ const points = orthogonal(raw);
257
+ if (points.length < 2)
258
+ return undefined;
259
+ const [source, target] = [laid.boxes.get(edge.sources[0]), laid.boxes.get(edge.targets[0])];
260
+ points[0] = placeEnd(points[0], points[1], source, target);
261
+ points[points.length - 1] = placeEnd(points.at(-1), points.at(-2), target, source);
262
+ let placed = orthogonal(points);
263
+ if (placed.length >= 2)
264
+ placed = offCorners(placed, source, target);
265
+ if (placed.length === 1)
266
+ placed = oneCell(placed[0], source, target);
267
+ if (placed.length < 2)
268
+ return undefined;
269
+ const text = labels.get(edge.id) ?? '';
270
+ const spot = edge.labels?.[0];
271
+ return {
272
+ points: placed,
273
+ ...(text !== '' && spot?.x !== undefined && spot.y !== undefined
274
+ ? { label: { x: Math.round(o.x + spot.x), y: Math.round(o.y + spot.y), text } }
275
+ : {}),
276
+ };
277
+ }
278
+ /** Shifts everything so nothing sits left of or above the origin, and measures the
279
+ * picture as what it holds. */
280
+ function normalize(boxes, routes) {
281
+ const xs = [];
282
+ const ys = [];
283
+ const span = (x0, x1, y0, y1) => {
284
+ xs.push(x0, x1);
285
+ ys.push(y0, y1);
286
+ };
287
+ for (const b of boxes.values())
288
+ span(b.x, b.x + b.width - 1, b.y, b.y + b.height - 1);
289
+ for (const r of routes.values()) {
290
+ for (const p of r.points)
291
+ span(p.x, p.x, p.y, p.y);
292
+ if (r.label !== undefined)
293
+ span(r.label.x, r.label.x + cellWidth(r.label.text) - 1, r.label.y, r.label.y);
294
+ }
295
+ if (xs.length === 0)
296
+ return { width: 0, height: 0, boxes, routes };
297
+ const dx = -Math.min(0, ...xs);
298
+ const dy = -Math.min(0, ...ys);
299
+ const shift = (p) => ({ ...p, x: p.x + dx, y: p.y + dy });
300
+ if (dx !== 0 || dy !== 0) {
301
+ for (const [id, b] of boxes)
302
+ boxes.set(id, shift(b));
303
+ for (const [id, r] of routes) {
304
+ routes.set(id, { points: r.points.map(shift), ...(r.label !== undefined ? { label: shift(r.label) } : {}) });
305
+ }
306
+ }
307
+ return { width: Math.max(...xs) + dx + 1, height: Math.max(...ys) + dy + 1, boxes, routes };
308
+ }
309
+ /**
310
+ * Lays the view out in cells. Every one of `layoutEdges` takes part, drawn or not,
311
+ * so that turning a layer on or off never moves a box (the renderer's rule); the
312
+ * routes of the edges actually drawn are picked from the result by id.
313
+ */
314
+ export async function layoutCells(view, boxes, flow, labels) {
315
+ const { direction } = flow;
316
+ if (view.roots.length === 0)
317
+ return { width: 0, height: 0, boxes: new Map(), routes: new Map() };
318
+ const graph = {
319
+ id: '__root',
320
+ layoutOptions: {
321
+ ...cellOptions(direction),
322
+ 'elk.direction': direction,
323
+ 'elk.padding': '[top=0,left=0,bottom=0,right=0]',
324
+ 'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
325
+ },
326
+ children: view.roots.map((vn) => elkNode(vn, boxes, flow)),
327
+ edges: elkEdges(view, labels),
328
+ };
329
+ const laid = collect(await elk.layout(graph));
330
+ const routes = new Map();
331
+ for (const entry of laid.edges) {
332
+ const route = routeOf(entry, laid, labels);
333
+ if (route !== undefined)
334
+ routes.set(entry.edge.id, route);
335
+ }
336
+ return normalize(laid.boxes, routes);
337
+ }
@@ -0,0 +1,44 @@
1
+ import { type LegendPosition } from '@diagc/core/internal';
2
+ import { type Cell, type Style } from './canvas.js';
3
+ import { type Glyphs } from './glyphs.js';
4
+ import type { Scene } from './scene.js';
5
+ export interface LegendRow {
6
+ /** `${section}:${key}`, which an item that names the same kind or type recaptions */
7
+ id: string;
8
+ /** `SWATCH` cells */
9
+ swatch: string;
10
+ style: Style;
11
+ label: string;
12
+ /** a shape, a line or a mark that says nothing about itself on the canvas: one such
13
+ * row is what offers a legend on a diagram that declared none */
14
+ vocabulary?: true;
15
+ }
16
+ export interface TextLegend {
17
+ title: string;
18
+ position: LegendPosition;
19
+ /** the diagram asked for it; one it did not ask for is only offered (the TUI's `L`) */
20
+ declared: boolean;
21
+ /** the sections with rows, each under the browser's title for it */
22
+ sections: {
23
+ title: string;
24
+ rows: LegendRow[];
25
+ }[];
26
+ }
27
+ /** What the legend is read from: a scene, before its legend is added to it. */
28
+ type Keyed = Pick<Scene, 'input' | 'view' | 'nodes' | 'notation' | 'accents'>;
29
+ /** The legend of a scene: the one its diagram declares, or the one it is offered for
30
+ * what its picture cannot say; none when there is nothing to key. */
31
+ export declare function legendOf(scene: Keyed, glyphs: Glyphs): TextLegend | undefined;
32
+ /** The cells the framed legend needs: its lines with a border and a cell of padding
33
+ * each side, and its title in the top border. */
34
+ export declare function legendSize(legend: TextLegend): {
35
+ width: number;
36
+ height: number;
37
+ };
38
+ /** The legend framed, its title in the top border as an open container's is. In less
39
+ * room than it needs its labels are cut and its last line says how many are left out. */
40
+ export declare function legendCells(legend: TextLegend, glyphs: Glyphs, room?: {
41
+ width: number;
42
+ height: number;
43
+ }): Cell[][];
44
+ export {};
@@ -0,0 +1,256 @@
1
+ import { buildHierarchy, presetLayers, relationLayer, relationOnPlane, scopeToRoot, } from '@diagc/core/internal';
2
+ import { Canvas } from './canvas.js';
3
+ import { typeMark } from './content.js';
4
+ import { dosFill, dosSlots } from './dos.js';
5
+ import { DOWN, LEFT, RIGHT } from './glyphs.js';
6
+ import { accentCss, colorCss, CORNER, rgb, WEIGHT } from './paint.js';
7
+ import { KIND_LOOKS, kindLook, TYPE_LOOKS, typeLook } from './vocabulary.js';
8
+ import { cellWidth, fitCells, printable } from './width.js';
9
+ /** A swatch's cells: three, the width of a line with a mark at each end. */
10
+ const SWATCH = 3;
11
+ const TITLES = {
12
+ layers: 'Layers',
13
+ kinds: 'Connections',
14
+ types: 'Elements',
15
+ marks: 'Marks',
16
+ items: 'Notes',
17
+ };
18
+ /** What a legend with no `show` derives; the types are keyed only where they need it. */
19
+ const DEFAULT_SECTIONS = ['layers', 'kinds', 'marks'];
20
+ const MARKS = { pk: ['PK', 'Primary key'], fk: ['FK', 'Foreign key column'] };
21
+ const DIM = { dim: true };
22
+ /** `text` in the middle of the swatch's cells. */
23
+ function centre(text) {
24
+ const left = Math.max(0, (SWATCH - cellWidth(text)) >> 1);
25
+ return `${' '.repeat(left)}${text}${' '.repeat(Math.max(0, SWATCH - left - cellWidth(text)))}`;
26
+ }
27
+ const colour = (css) => {
28
+ const fg = rgb(css);
29
+ return fg === undefined ? {} : { fg };
30
+ };
31
+ /** Each key with its value where every entry for it agrees, else undefined: a swatch
32
+ * takes a colour only when all it stands for are drawn in that colour. */
33
+ function agreed(entries) {
34
+ const out = new Map();
35
+ for (const [key, value] of entries) {
36
+ if (!out.has(key))
37
+ out.set(key, value);
38
+ else if (out.get(key) !== value)
39
+ out.set(key, undefined);
40
+ }
41
+ return out;
42
+ }
43
+ /** The vocabulary's own order first (an authored one), then unknown ids alphabetically:
44
+ * never the order things are met in, which would reshuffle the key at every fold. */
45
+ function ordered(ids, known) {
46
+ const rank = new Map(known.map((k, i) => [k, i]));
47
+ const at = (id) => rank.get(id) ?? known.length;
48
+ return [...ids].sort((a, b) => at(a) - at(b) || a.localeCompare(b));
49
+ }
50
+ /** A line as the picture draws one of the kind: its weight, then its ends' marks. */
51
+ function lineSwatch(look, glyphs) {
52
+ const line = glyphs.line(LEFT | RIGHT, WEIGHT[look.line]);
53
+ const end = (mark, toward) => mark === undefined || mark === 'none' ? line : mark === 'arrow' ? glyphs.arrow(toward) : glyphs.mark(mark);
54
+ return `${end(look.start, 'left')}${line}${end(look.end, 'right')}`;
55
+ }
56
+ /** A box of the type as the picture draws it: the mark its name follows where it has
57
+ * one, else the top of its border, which carries its corners and its dashes (in `dos`,
58
+ * square and double). */
59
+ function shapeSwatch(type, look, glyphs, dos) {
60
+ const mark = typeMark(type, look.shape, glyphs);
61
+ if (mark !== undefined)
62
+ return centre(mark);
63
+ const weight = look.shape === 'bar' ? 'heavy' : look.dashed === true ? 'dashed' : dos ? 'double' : 'light';
64
+ const corner = dos ? undefined : CORNER[look.shape];
65
+ return `${glyphs.line(DOWN | RIGHT, weight, corner)}${glyphs.line(LEFT | RIGHT, weight)}${glyphs.line(DOWN | LEFT, weight, corner)}`;
66
+ }
67
+ const vocabulary = (caption) => caption !== undefined ? { vocabulary: true } : {};
68
+ /** The layers something in this view carries, folded away or not: what the plane holds,
69
+ * or a drill's inside. The browser's rule (legendRows' `drawableSlice`), so a layer's row
70
+ * does not come and go as its boxes fold. */
71
+ function carriedLayers({ model, plane, root }) {
72
+ const hierarchy = buildHierarchy(model, plane);
73
+ const viewed = plane ?? model.planes[0]?.id;
74
+ const visible = new Set(hierarchy.childrenOf.keys());
75
+ const { nodes, relations } = root !== undefined && hierarchy.childrenOf.has(root)
76
+ ? scopeToRoot(model, hierarchy, root).model
77
+ : {
78
+ nodes: model.nodes.filter((n) => visible.has(n.id)),
79
+ relations: model.relations.filter((r) => visible.has(r.from) && visible.has(r.to)),
80
+ };
81
+ const carried = new Set();
82
+ for (const n of nodes) {
83
+ if (n.layer !== undefined)
84
+ carried.add(n.layer);
85
+ for (const c of n.columns ?? [])
86
+ if (c.layer !== undefined)
87
+ carried.add(c.layer);
88
+ }
89
+ // the effective layer: one a `layerRules` entry puts a relation on counts as a tag does
90
+ for (const r of relations) {
91
+ const layer = relationOnPlane(r, viewed) ? relationLayer(model, r) : undefined;
92
+ if (layer !== undefined)
93
+ carried.add(layer);
94
+ }
95
+ return carried;
96
+ }
97
+ function layerRows(scene, glyphs) {
98
+ const { model, plane, layers } = scene.input;
99
+ const carried = carriedLayers(scene.input);
100
+ const on = new Set(layers ?? presetLayers(model.planes, plane));
101
+ return model.layers
102
+ .filter((l) => carried.has(l.id) && on.has(l.id))
103
+ .map((l) => ({
104
+ id: `layers:${l.id}`,
105
+ swatch: centre(glyphs.mark('square')),
106
+ style: colour(l.tint),
107
+ label: printable(l.name),
108
+ }));
109
+ }
110
+ function kindRows(scene, glyphs) {
111
+ // the layer's tint, not a relation's own colour: that is one arrow's, not the kind's
112
+ const inks = agreed(scene.view.edges.map((e) => [e.kind, e.tint]));
113
+ return ordered(inks.keys(), Object.keys(KIND_LOOKS)).map((kind) => {
114
+ const look = kindLook({ kind }, scene.notation);
115
+ return {
116
+ id: `kinds:${kind}`,
117
+ swatch: lineSwatch(look, glyphs),
118
+ style: colour(inks.get(kind)),
119
+ label: look.legend ?? printable(kind),
120
+ ...vocabulary(look.legend),
121
+ };
122
+ });
123
+ }
124
+ function typeRows(scene, glyphs) {
125
+ const { model } = scene.input;
126
+ const slots = scene.input.style === 'dos' ? dosSlots(model, scene.notation) : undefined;
127
+ // a DOS box is filled in its own colour or its type's slot, never the notation's accent
128
+ const css = (node) => slots === undefined ? accentCss(model, node, scene.notation, scene.accents) : colorCss(model, node, scene.accents);
129
+ const accents = agreed([...scene.nodes.values()].flatMap((vn) => vn.node.type === undefined ? [] : [[vn.node.type, css(vn.node)]]));
130
+ return ordered(accents.keys(), Object.keys(TYPE_LOOKS)).map((type) => {
131
+ const look = typeLook(type, scene.notation);
132
+ // `label: ''` keeps a glyph type's box free of a subtitle; it is not a caption
133
+ const label = look.legend ?? (look.label === undefined || look.label === '' ? printable(type) : look.label);
134
+ return {
135
+ id: `types:${type}`,
136
+ swatch: shapeSwatch(type, look, glyphs, slots !== undefined),
137
+ style: slots === undefined ? colour(accents.get(type)) : { fg: dosFill(look.shape, accents.get(type), type, slots) },
138
+ label,
139
+ ...vocabulary(look.legend),
140
+ };
141
+ });
142
+ }
143
+ /** A table's key columns, which the picture tags `PK` and `FK`. */
144
+ function markRows(scene) {
145
+ const seen = new Set();
146
+ for (const vn of scene.nodes.values()) {
147
+ if (typeLook(vn.node.type, scene.notation).shape !== 'table')
148
+ continue;
149
+ for (const c of vn.columns ?? vn.node.columns ?? []) {
150
+ if (c.pk === true)
151
+ seen.add('pk');
152
+ else if (c.fk === true)
153
+ seen.add('fk');
154
+ }
155
+ }
156
+ return Object.keys(MARKS)
157
+ .filter((m) => seen.has(m))
158
+ .map((m) => ({ id: `marks:${m}`, swatch: centre(MARKS[m][0]), style: {}, label: MARKS[m][1], vocabulary: true }));
159
+ }
160
+ /** The hand-written rows. One naming a kind or a type already keyed recaptions that row
161
+ * in place, keeping its swatch; the rest are rows of their own. */
162
+ function itemRows(items, derived, scene, glyphs) {
163
+ const { notation } = scene;
164
+ return items.flatMap((item, i) => {
165
+ const label = printable(item.label);
166
+ const target = item.kind !== undefined ? `kinds:${item.kind}` : item.type !== undefined ? `types:${item.type}` : '';
167
+ const hit = derived.find((r) => r.id === target);
168
+ if (hit !== undefined) {
169
+ hit.label = label;
170
+ if (item.color !== undefined)
171
+ hit.style = colour(item.color);
172
+ return [];
173
+ }
174
+ const swatch = item.kind !== undefined
175
+ ? lineSwatch(kindLook({ kind: item.kind }, notation), glyphs)
176
+ : item.type !== undefined
177
+ ? shapeSwatch(item.type, typeLook(item.type, notation), glyphs, scene.input.style === 'dos')
178
+ : item.color !== undefined
179
+ ? centre(glyphs.mark('square'))
180
+ : centre('');
181
+ return [{ id: `items:${i}`, swatch, style: colour(item.color), label }];
182
+ });
183
+ }
184
+ /** The legend of a scene: the one its diagram declares, or the one it is offered for
185
+ * what its picture cannot say; none when there is nothing to key. */
186
+ export function legendOf(scene, glyphs) {
187
+ const config = scene.input.model.legend ?? {};
188
+ const shown = config.show ?? DEFAULT_SECTIONS;
189
+ // As the browser: an explicit `show` to the letter; without one, types only where the
190
+ // box says nothing of its own — elsewhere a box prints its type and the key repeats it.
191
+ const types = shown.includes('types')
192
+ ? typeRows(scene, glyphs)
193
+ : config.show === undefined
194
+ ? typeRows(scene, glyphs).filter((r) => r.vocabulary === true)
195
+ : [];
196
+ const derived = {
197
+ layers: shown.includes('layers') ? layerRows(scene, glyphs) : [],
198
+ kinds: shown.includes('kinds') ? kindRows(scene, glyphs) : [],
199
+ types,
200
+ marks: shown.includes('marks') ? markRows(scene) : [],
201
+ };
202
+ const items = itemRows(config.items ?? [], [...derived.kinds, ...derived.types], scene, glyphs);
203
+ const sections = ['layers', 'kinds', 'types', 'marks', 'items']
204
+ .map((s) => ({ title: TITLES[s], rows: s === 'items' ? items : derived[s] }))
205
+ .filter((s) => s.rows.length > 0);
206
+ const declared = scene.input.model.legend !== undefined;
207
+ if (sections.length === 0)
208
+ return undefined;
209
+ if (!declared && !sections.some((s) => s.rows.some((r) => r.vocabulary === true)))
210
+ return undefined;
211
+ return {
212
+ title: printable(config.title ?? 'Legend'),
213
+ position: config.position ?? 'bottom-right',
214
+ declared,
215
+ sections,
216
+ };
217
+ }
218
+ const linesOf = (legend) => legend.sections.flatMap((s) => [
219
+ { text: s.title, style: DIM },
220
+ ...s.rows.map((r) => ({ swatch: { text: r.swatch, style: r.style }, text: r.label, style: {} })),
221
+ ]);
222
+ const lineWidth = (line) => (line.swatch === undefined ? 0 : SWATCH + 1) + cellWidth(line.text);
223
+ /** The cells the framed legend needs: its lines with a border and a cell of padding
224
+ * each side, and its title in the top border. */
225
+ export function legendSize(legend) {
226
+ const lines = linesOf(legend);
227
+ return {
228
+ width: Math.max(Math.max(...lines.map(lineWidth)) + 4, cellWidth(legend.title) + 6),
229
+ height: lines.length + 2,
230
+ };
231
+ }
232
+ /** The legend framed, its title in the top border as an open container's is. In less
233
+ * room than it needs its labels are cut and its last line says how many are left out. */
234
+ export function legendCells(legend, glyphs, room = legendSize(legend)) {
235
+ const natural = legendSize(legend);
236
+ const width = Math.min(natural.width, room.width);
237
+ const height = Math.min(natural.height, room.height);
238
+ const canvas = new Canvas(width, height);
239
+ canvas.rect({ x: 0, y: 0, width, height }, 'light', DIM);
240
+ canvas.text({ x: 2, y: 0 }, ` ${legend.title} `, { bold: true }, width - 2);
241
+ const lines = linesOf(legend);
242
+ const inside = Math.max(0, height - 2);
243
+ const shown = lines.length <= inside
244
+ ? lines
245
+ : [...lines.slice(0, inside - 1), { text: `${glyphs.ellipsis} ${lines.length - inside + 1} more`, style: DIM }];
246
+ const maxX = width - 2;
247
+ shown.forEach((line, i) => {
248
+ let x = 2;
249
+ if (line.swatch !== undefined) {
250
+ canvas.text({ x, y: i + 1 }, line.swatch.text, line.swatch.style, maxX);
251
+ x += SWATCH + 1;
252
+ }
253
+ canvas.text({ x, y: i + 1 }, fitCells(line.text, maxX - x, glyphs.ellipsis), line.style, maxX);
254
+ });
255
+ return canvas.cells(glyphs);
256
+ }
@@ -0,0 +1,27 @@
1
+ import type { DiagramModel, DiagramNode, NotationId } from '@diagc/core/internal';
2
+ import type { Accents } from './accents.js';
3
+ import { Canvas, type Color } from './canvas.js';
4
+ import { type Corner, type Glyphs, type Weight } from './glyphs.js';
5
+ import type { Scene } from './scene.js';
6
+ import { type LineStyle, type TextShape } from './vocabulary.js';
7
+ export interface PaintOptions {
8
+ glyphs: Glyphs;
9
+ /** the box the TUI has selected: drawn heavy, its edges bold, every other edge dim */
10
+ selected?: string;
11
+ }
12
+ export declare const WEIGHT: Record<LineStyle, Weight>;
13
+ export declare const CORNER: Partial<Record<TextShape, Corner>>;
14
+ export declare const rgb: (css: string | undefined) => Color | undefined;
15
+ /** A node's own colour, as the renderer resolves it: its own, the one its notation
16
+ * gives it (a lane's, a bone's), the model's for its type (or for every type). */
17
+ export declare function colorCss(model: DiagramModel, node: DiagramNode, accents: Accents): string | undefined;
18
+ /** A node's accent: its own colour, then the notation's for the type. */
19
+ export declare function accentCss(model: DiagramModel, node: DiagramNode, notation: NotationId | undefined, accents: Accents): string | undefined;
20
+ /**
21
+ * The scene as a canvas, in layers: open containers' frames from the outside in,
22
+ * then the edges' lines, then the boxes over them (a box clears what is under it)
23
+ * and the frames' titles, then edge labels and the ends of the edges, last so
24
+ * nothing covers an arrowhead. In the DOS style (the scene's `style`) it all lies on
25
+ * the desktop, the boxes' shadows laid on it first.
26
+ */
27
+ export declare function paint(scene: Scene, options: PaintOptions): Canvas;