@trazum/cli 2.7.12 → 3.0.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 (47) hide show
  1. package/README.md +4 -2
  2. package/assets/trazum-statusline.sh +131 -0
  3. package/dist/git.d.ts +38 -0
  4. package/dist/git.d.ts.map +1 -1
  5. package/dist/git.js +54 -0
  6. package/dist/git.js.map +1 -1
  7. package/dist/i18n/en.d.ts.map +1 -1
  8. package/dist/i18n/en.js +170 -3
  9. package/dist/i18n/en.js.map +1 -1
  10. package/dist/i18n/es.d.ts.map +1 -1
  11. package/dist/i18n/es.js +174 -3
  12. package/dist/i18n/es.js.map +1 -1
  13. package/dist/i18n/types.d.ts +84 -0
  14. package/dist/i18n/types.d.ts.map +1 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +670 -262
  17. package/dist/index.js.map +1 -1
  18. package/dist/proactive.d.ts +344 -0
  19. package/dist/proactive.d.ts.map +1 -0
  20. package/dist/proactive.js +1079 -0
  21. package/dist/proactive.js.map +1 -0
  22. package/dist/style.d.ts +305 -26
  23. package/dist/style.d.ts.map +1 -1
  24. package/dist/style.js +449 -47
  25. package/dist/style.js.map +1 -1
  26. package/dist/watch-notify.d.ts +82 -0
  27. package/dist/watch-notify.d.ts.map +1 -0
  28. package/dist/watch-notify.js +118 -0
  29. package/dist/watch-notify.js.map +1 -0
  30. package/dist/watch-run.d.ts +7 -0
  31. package/dist/watch-run.d.ts.map +1 -1
  32. package/dist/watch-run.js.map +1 -1
  33. package/dist/weekly.d.ts +32 -0
  34. package/dist/weekly.d.ts.map +1 -0
  35. package/dist/weekly.js +119 -0
  36. package/dist/weekly.js.map +1 -0
  37. package/package.json +3 -2
  38. package/src/git.ts +77 -0
  39. package/src/i18n/en.ts +198 -3
  40. package/src/i18n/es.ts +202 -3
  41. package/src/i18n/types.ts +130 -0
  42. package/src/index.ts +715 -302
  43. package/src/proactive.ts +1319 -0
  44. package/src/style.ts +502 -54
  45. package/src/watch-notify.ts +152 -0
  46. package/src/watch-run.ts +7 -0
  47. package/src/weekly.ts +133 -0
package/src/style.ts CHANGED
@@ -1,20 +1,31 @@
1
1
  /**
2
- * The CLI's presentation layer — the 1.75 arc.
2
+ * The one module that draws the CLI's terminal reports (#758).
3
3
  *
4
- * Six painters, one measurer, one table renderer, one proportion bar, one
5
- * heading rule. Everything here decorates figures the prose already states;
6
- * the chapter-four guard strips the paint and asserts nothing was lost and
7
- * nothing was hiding in it.
4
+ * The commands hand it rows and sentences; it decides the colour, the width
5
+ * and the order a report is read in, so two commands cannot drift apart
6
+ * again. DESIGN.md, "Terminal", states the rules this file implements.
8
7
  *
9
- * Colour is on for a TTY unless `NO_COLOR` says otherwise, and on anywhere
10
- * when `FORCE_COLOR=1` — the door the guard itself walks through, since a
11
- * test that wants to see what colour does runs under a pipe. A plain pipe
12
- * stays plain: every `trazum ... | grep` in somebody's script is owed the
13
- * bytes their script was written against.
8
+ * **Colour depth comes from the terminal.** True colour where it says it has
9
+ * it (`COLORTERM`), the chosen nearest of the 256 where `TERM` says 256, the
10
+ * 16 otherwise, and nothing at all where `NO_COLOR` is set or stdout is not a
11
+ * terminal. `FORCE_COLOR` outranks all of that, with the levels other tools
12
+ * give it (1 the 16, 2 the 256, 3 true colour, 0 none): it is the door the
13
+ * tests and the drawing scripts walk through, since they run under a pipe. A
14
+ * plain pipe stays plain: every `trazum ... | grep` in somebody's script is
15
+ * owed the bytes their script was written against.
16
+ *
17
+ * **Colour never carries a meaning alone.** Every state has a word or a mark
18
+ * (`!`, `?`, `→`, `OK`, `OVER`) that a pipe carries too, and the paint only
19
+ * repeats it. The chapter-four guard in `style.test.js` strips the paint and
20
+ * asserts nothing was lost and nothing was hiding in it.
21
+ *
22
+ * **Width comes from the window**, between 60 and 76 columns: a table fits by
23
+ * narrowing its bars and then its names, never by wrapping a figure away from
24
+ * its label.
14
25
  */
15
26
 
16
27
  /**
17
- * The variables the decision below reads.
28
+ * The variables the decisions below read: colour depth and width.
18
29
  *
19
30
  * Exported for the same reason `LOCALE_ENV_VARS` is: the test suite has to
20
31
  * neutralise the machine before asserting on output, and a list of what to
@@ -22,24 +33,165 @@
22
33
  * drifted once already, in the other direction: `env.mjs` set `NO_COLOR` and
23
34
  * left `FORCE_COLOR` alone, so a contributor whose shell exports `FORCE_COLOR`
24
35
  * ran the whole CLI suite against painted output and twenty-nine tests failed.
36
+ * `COLUMNS` is here because a shell that exports it would otherwise narrow
37
+ * every report a test reads.
25
38
  */
26
- export const COLOUR_ENV_VARS = ['FORCE_COLOR', 'NO_COLOR'] as const;
39
+ export const TERMINAL_ENV_VARS = ['FORCE_COLOR', 'NO_COLOR', 'COLORTERM', 'TERM', 'COLUMNS'] as const;
27
40
 
28
- const forced = process.env.FORCE_COLOR === '1';
29
- export const useColor = forced || (process.stdout.isTTY === true && process.env.NO_COLOR === undefined);
41
+ type TerminalEnv = Partial<Record<(typeof TERMINAL_ENV_VARS)[number], string>>;
30
42
 
31
- export const c = {
32
- bold: (s: string) => (useColor ? `\u001b[1m${s}\u001b[22m` : s),
33
- dim: (s: string) => (useColor ? `\u001b[2m${s}\u001b[22m` : s),
34
- green: (s: string) => (useColor ? `\u001b[32m${s}\u001b[39m` : s),
35
- red: (s: string) => (useColor ? `\u001b[31m${s}\u001b[39m` : s),
36
- yellow: (s: string) => (useColor ? `\u001b[33m${s}\u001b[39m` : s),
37
- cyan: (s: string) => (useColor ? `\u001b[36m${s}\u001b[39m` : s),
38
- };
43
+ /** How many colours the terminal has said it can show. */
44
+ export type ColourDepth = 'none' | '16' | '256' | 'truecolor';
45
+
46
+ /**
47
+ * The depth for an environment and a stdout, as a pure function so each of
48
+ * the four answers can be asked for directly.
49
+ */
50
+ export function colourDepth(env: TerminalEnv, isTTY: boolean): ColourDepth {
51
+ const force = env.FORCE_COLOR;
52
+ if (force !== undefined) {
53
+ if (force === '0' || force === 'false') return 'none';
54
+ if (force === '2') return '256';
55
+ if (force === '3') return 'truecolor';
56
+ return '16';
57
+ }
58
+ if (env.NO_COLOR !== undefined) return 'none';
59
+ if (!isTTY || env.TERM === 'dumb') return 'none';
60
+ const colorterm = (env.COLORTERM ?? '').toLowerCase();
61
+ if (colorterm === 'truecolor' || colorterm === '24bit') return 'truecolor';
62
+ if ((env.TERM ?? '').includes('256')) return '256';
63
+ return '16';
64
+ }
65
+
66
+ export const depth: ColourDepth = colourDepth(process.env, process.stdout.isTTY === true);
67
+ export const useColor = depth !== 'none';
68
+
69
+ /**
70
+ * The brand's colours, from DESIGN.md's token table, at each depth.
71
+ *
72
+ * Ink and paper are the reader's: a terminal's foreground and ground are
73
+ * whatever its owner chose, and the CLI cannot see which, so it never paints
74
+ * a foreground that reads on only one of them. The brand's ink appears as the
75
+ * type inside the mark, on the acid ground, which reads on a light terminal
76
+ * and a dark one alike. The 256 values are the nearest of the fixed cube and
77
+ * grey ramp (16 to 255) by distance in RGB, worked out in
78
+ * `terminal-report.test.js`; the first 16 are left out because every theme
79
+ * redefines them.
80
+ *
81
+ * **The accent is not the page's accent text.** The page knows its ground and
82
+ * changes the accent with it (#526014 on paper, the acid on the dark canvas);
83
+ * a terminal cannot tell its own ground, so its accent is one colour that has
84
+ * to hold on both. #526014 measured 2.37:1 on the dark canvas, and the bars
85
+ * and arrows went dull where the old cyan read. #70831b is the same olive,
86
+ * same hue and saturation, at the lightness that keeps 3.5:1 or more on
87
+ * paper, white and the two dark grounds; `terminal-report.test.js` computes it.
88
+ */
89
+ export const PALETTE = {
90
+ ink: { hex: '#20231e', c256: 234, c16: 30 },
91
+ acid: { hex: '#dce94d', c256: 185, c16: 43 },
92
+ accent: { hex: '#70831b', c256: 64, c16: 36 },
93
+ } as const;
94
+
95
+ const rgb = (hex: string): string =>
96
+ [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16)).join(';');
97
+
98
+ /** An SGR foreground (or, with `ground`, background) for a palette colour at a depth. */
99
+ function sgr(colour: (typeof PALETTE)[keyof typeof PALETTE], at: ColourDepth, ground = false): string {
100
+ if (at === 'truecolor') return `${ground ? 48 : 38};2;${rgb(colour.hex)}`;
101
+ if (at === '256') return `${ground ? 48 : 38};5;${colour.c256}`;
102
+ return String(colour.c16);
103
+ }
39
104
 
40
- /** The report's text column. Headings rule out to it; nothing else needs it. */
105
+ /**
106
+ * The painters, for a depth. Exported as a factory so the tests can paint at a
107
+ * depth the machine running them does not have.
108
+ *
109
+ * Success, caution and error stay the terminal's own green, yellow and red at
110
+ * every depth: its theme already tunes those to its ground, which the CLI
111
+ * cannot see. The accent (what points: the share bars and the lever arrows)
112
+ * is the brand's at 256 and true colour and cyan in the 16, the one colour of
113
+ * the 16 no state uses. The mark is the acid ground with ink type and bold,
114
+ * and a report puts it on one figure: the one that answers its question.
115
+ */
116
+ export function painters(at: ColourDepth) {
117
+ const wrap = (open: string, close: string) => (s: string) =>
118
+ at === 'none' || s === '' ? s : `\u001b[${open}m${s}\u001b[${close}m`;
119
+ const accent = wrap(sgr(PALETTE.accent, at), '39');
120
+ return {
121
+ bold: wrap('1', '22'),
122
+ dim: wrap('2', '22'),
123
+ green: wrap('32', '39'),
124
+ red: wrap('31', '39'),
125
+ yellow: wrap('33', '39'),
126
+ accent,
127
+ /** The name every caller used for what points; the accent now. */
128
+ cyan: accent,
129
+ mark: wrap(`1;${sgr(PALETTE.ink, at)};${sgr(PALETTE.acid, at, true)}`, '22;39;49'),
130
+ };
131
+ }
132
+
133
+ export const c = painters(depth);
134
+
135
+ /**
136
+ * The painters for standard error, which is a terminal or not on its own: the
137
+ * bill's notes on what it read are dimmed on a terminal and left plain in a
138
+ * pipe or a file.
139
+ */
140
+ export const cErr = painters(colourDepth(process.env, process.stderr.isTTY === true));
141
+
142
+ /** The report's text column when nothing says how wide the window is. */
41
143
  export const REPORT_WIDTH = 74;
42
144
 
145
+ /** The narrowest and widest a report is drawn, the indent included. */
146
+ export const MIN_COLUMNS = 60;
147
+ export const MAX_COLUMNS = 76;
148
+
149
+ /**
150
+ * How wide a report is drawn: the window's width when there is a window (or
151
+ * `COLUMNS` says what it is), held between 60 and 76 columns. 76 is the
152
+ * widest line the reports printed before they knew the window, so a wide
153
+ * terminal gets the layout it always had.
154
+ *
155
+ * `window` is false when nothing said how wide: a pipe or a file. Then the
156
+ * report keeps the layout it always printed there, line for line, because a
157
+ * script reading it has no window to fit and was written against those bytes;
158
+ * a name in a table is never cut for a reader with no window.
159
+ */
160
+ export function columnsFor(env: TerminalEnv, ttyColumns: number | undefined): { columns: number; window: boolean } {
161
+ const asked = ttyColumns !== undefined && ttyColumns > 0 ? ttyColumns : Number.parseInt(env.COLUMNS ?? '', 10);
162
+ if (!Number.isFinite(asked) || asked <= 0) return { columns: MAX_COLUMNS, window: false };
163
+ return { columns: Math.min(MAX_COLUMNS, Math.max(MIN_COLUMNS, asked)), window: true };
164
+ }
165
+
166
+ const measured = columnsFor(process.env, process.stdout.isTTY === true ? process.stdout.columns : undefined);
167
+ export const COLUMNS = measured.columns;
168
+ export const WINDOW = measured.window;
169
+
170
+ /**
171
+ * A paragraph wrapped to `width` characters, its later lines under `indent`.
172
+ *
173
+ * Every paragraph of every command goes through here. With no window it cuts
174
+ * where it always cut; with one it also keeps the line, indent included,
175
+ * inside the window, so prose reflows down to 60 columns. Unpainted text in:
176
+ * the caller paints the result.
177
+ */
178
+ export function wrap(text: string, width: number, indent: string, columns = WINDOW ? COLUMNS : null): string {
179
+ const room = columns === null ? width : Math.min(width, Math.max(20, columns - indent.length));
180
+ const words = text.split(/\s+/);
181
+ const lines: string[] = [];
182
+ let line = '';
183
+ for (const word of words) {
184
+ if (line.length + word.length + 1 > room) {
185
+ lines.push(line);
186
+ line = word;
187
+ } else {
188
+ line = line ? `${line} ${word}` : word;
189
+ }
190
+ }
191
+ if (line) lines.push(line);
192
+ return lines.join(`\n${indent}`);
193
+ }
194
+
43
195
  const ANSI = /\u001b\[[0-9;]*m/g;
44
196
 
45
197
  /**
@@ -58,52 +210,152 @@ export function padCell(s: string, width: number, align: 'left' | 'right'): stri
58
210
  return align === 'right' ? ' '.repeat(gap) + s : s + ' '.repeat(gap);
59
211
  }
60
212
 
61
- export interface TableColumn {
62
- /** The header cell, already localized. Empty string for a headerless column. */
63
- header: string;
64
- align: 'left' | 'right';
65
- }
213
+ /** A word that states a figure: it holds a digit. */
214
+ const FIGURE = /\d/;
66
215
 
67
216
  /**
68
- * The one table renderer, for the eleven layouts that each rebuilt it.
217
+ * A paragraph as lines no wider than `width`, a word never split.
69
218
  *
70
- * Widths come from the content, headers print dimmed, and cells may arrive
71
- * painted — the measurement ignores the paint. Returns lines; the caller
72
- * owns the `console.log` and the indent, because some tables live inside a
73
- * bullet and some at the margin.
219
+ * A figure is held to the word after it, so `126 calls` or `$5.21 projected`
220
+ * never ends one line and starts the next. Unpainted text in, unpainted
221
+ * lines out: the caller paints a line once it is cut.
74
222
  */
75
- export function table(columns: TableColumn[], rows: string[][], indent = ' '): string[] {
76
- const widths = columns.map((col, i) =>
77
- Math.max(visibleWidth(col.header), ...rows.map((row) => visibleWidth(row[i] ?? ''))),
78
- );
79
- const lines: string[] = [];
80
- if (columns.some((col) => col.header !== '')) {
81
- lines.push(
82
- indent +
83
- columns.map((col, i) => padCell(c.dim(col.header), widths[i] ?? 0, col.align)).join(' ').trimEnd(),
84
- );
223
+ export function wrapText(text: string, width: number): string[] {
224
+ const words = text.split(/\s+/).filter((word) => word !== '');
225
+ const units: string[] = [];
226
+ for (let i = 0; i < words.length; i++) {
227
+ let unit = words[i]!;
228
+ if (FIGURE.test(unit) && i + 1 < words.length && unit.length + 1 + words[i + 1]!.length <= width) {
229
+ unit = `${unit} ${words[++i]}`;
230
+ }
231
+ units.push(unit);
85
232
  }
86
- for (const row of rows) {
87
- lines.push(
88
- indent + columns.map((col, i) => padCell(row[i] ?? '', widths[i] ?? 0, col.align)).join(' ').trimEnd(),
89
- );
233
+ const lines: string[] = [];
234
+ let line = '';
235
+ for (const unit of units) {
236
+ if (line !== '' && line.length + unit.length + 1 > width) {
237
+ lines.push(line);
238
+ line = unit;
239
+ } else {
240
+ line = line === '' ? unit : `${line} ${unit}`;
241
+ }
90
242
  }
243
+ if (line !== '') lines.push(line);
91
244
  return lines;
92
245
  }
93
246
 
247
+ export interface TableColumn {
248
+ /** The header cell, already localized. Empty string for a headerless column. */
249
+ header: string;
250
+ align: 'left' | 'right';
251
+ }
252
+
94
253
  /**
95
- * A share the line already states, readable from further away: `███░░░░░░░`.
254
+ * A bar cell: a share drawn as `███░░░░░░░`, as wide as the table has room for.
96
255
  *
97
256
  * The bar is content, not paint — it prints in a pipe too, so the stripped
98
257
  * and plain outputs stay byte-identical. It never carries information the
99
258
  * text does not: the percentage beside it is the number, the bar is the
100
- * glance. Clamped, because a share over 1 is the caller's bug and a bar
101
- * wider than asked would make it the layout's.
259
+ * glance.
102
260
  */
103
- export function bar(share: number, width = 10): string {
261
+ export interface BarCell {
262
+ bar: number;
263
+ }
264
+
265
+ export type Cell = string | BarCell;
266
+
267
+ const isBar = (cell: Cell | undefined): cell is BarCell => typeof cell === 'object' && cell !== null;
268
+
269
+ /**
270
+ * A share the line already states, readable from further away: `███░░░░░░░`.
271
+ * Clamped, because a share over 1 is the caller's bug and a bar wider than
272
+ * asked would make it the layout's.
273
+ */
274
+ export function bar(share: number, width = 10, paint = c): string {
104
275
  const clamped = Math.max(0, Math.min(1, share));
105
276
  const filled = Math.round(clamped * width);
106
- return c.cyan('█'.repeat(filled)) + c.dim('░'.repeat(width - filled));
277
+ return paint.accent('█'.repeat(filled)) + paint.dim('░'.repeat(width - filled));
278
+ }
279
+
280
+ const BAR_WIDTHS = [10, 5, 0];
281
+ const ELLIPSIS = '…';
282
+
283
+ /** A name cut to `width` characters, saying it was cut. Unpainted names only. */
284
+ function cut(text: string, width: number): string {
285
+ if (visibleWidth(text) <= width) return text;
286
+ if (text !== text.replace(ANSI, '')) return text;
287
+ return `${text.slice(0, Math.max(1, width - 1))}${ELLIPSIS}`;
288
+ }
289
+
290
+ /**
291
+ * A path cut from its start to `room` characters, `…` saying so: the end of a
292
+ * path is the part that names the file. Untouched when it fits, or when there
293
+ * is no window to fit (`room` infinite).
294
+ */
295
+ export function fitPath(path: string, room: number): string {
296
+ if (!Number.isFinite(room) || path.length <= room) return path;
297
+ const keep = Math.max(11, room) - 1;
298
+ return `${ELLIPSIS}${path.slice(path.length - keep)}`;
299
+ }
300
+
301
+ /**
302
+ * The one table renderer.
303
+ *
304
+ * Widths come from the content, headers print dimmed, and cells may arrive
305
+ * painted — the measurement ignores the paint. When the table is wider than
306
+ * `width` it narrows its bars (ten cells, then five, then none) and then cuts
307
+ * its first left-aligned column, the name, with an ellipsis. A figure is never
308
+ * cut and a row never wraps, so every figure stays on the line of its label.
309
+ * Returns lines; the caller owns the indent, because some tables live inside a
310
+ * bullet and some at the margin.
311
+ */
312
+ export function table(
313
+ columns: TableColumn[],
314
+ rows: Cell[][],
315
+ indent = ' ',
316
+ width = Number.POSITIVE_INFINITY,
317
+ paint = c,
318
+ ): string[] {
319
+ const draw = (barWidth: number, nameWidth: number | null): string[] => {
320
+ const text = rows.map((row) =>
321
+ columns.map((_, i) => {
322
+ const cell = row[i];
323
+ if (isBar(cell)) return barWidth === 0 ? '' : bar(cell.bar, barWidth, paint);
324
+ const value = cell ?? '';
325
+ return nameWidth !== null && i === nameColumn ? cut(value, nameWidth) : value;
326
+ }),
327
+ );
328
+ const shown = columns.map((col, i) => {
329
+ const barColumn = rows.some((row) => isBar(row[i]));
330
+ return !(barColumn && barWidth === 0) || col.header !== '';
331
+ });
332
+ const widths = columns.map((col, i) =>
333
+ Math.max(visibleWidth(col.header), ...text.map((row) => visibleWidth(row[i] ?? ''))),
334
+ );
335
+ const join = (cells: string[]) =>
336
+ indent +
337
+ cells
338
+ .map((cell, i) => (shown[i] ? padCell(cell, widths[i] ?? 0, columns[i]!.align) : null))
339
+ .filter((cell): cell is string => cell !== null)
340
+ .join(' ')
341
+ .trimEnd();
342
+ const lines: string[] = [];
343
+ if (columns.some((col) => col.header !== '')) lines.push(join(columns.map((col) => paint.dim(col.header))));
344
+ for (const row of text) lines.push(join(row));
345
+ return lines;
346
+ };
347
+ const nameColumn = columns.findIndex((col) => col.align === 'left');
348
+ const fits = (lines: string[]) => lines.every((line) => visibleWidth(line) <= width);
349
+ const hasBars = rows.some((row) => row.some(isBar));
350
+ let lines: string[] = [];
351
+ for (const barWidth of hasBars ? BAR_WIDTHS : [0]) {
352
+ lines = draw(barWidth, null);
353
+ if (fits(lines)) return lines;
354
+ }
355
+ if (nameColumn === -1) return lines;
356
+ const over = Math.max(...lines.map(visibleWidth)) - width;
357
+ const longest = Math.max(visibleWidth(columns[nameColumn]!.header), ...rows.map((row) => (isBar(row[nameColumn]) ? 0 : visibleWidth((row[nameColumn] as string) ?? ''))));
358
+ return draw(0, Math.max(8, longest - over));
107
359
  }
108
360
 
109
361
  /**
@@ -114,7 +366,203 @@ export function bar(share: number, width = 10): string {
114
366
  *
115
367
  * The rule is content (it survives the strip); the weight is paint.
116
368
  */
117
- export function sectionHeading(text: string, width = REPORT_WIDTH): string {
369
+ export function sectionHeading(text: string, width = WINDOW ? COLUMNS - 2 : REPORT_WIDTH, paint = c): string {
118
370
  const room = Math.max(0, width - visibleWidth(text) - 1);
119
- return `${c.bold(text)} ${c.dim('─'.repeat(room))}`.trimEnd();
371
+ return `${paint.bold(text)} ${paint.dim('─'.repeat(room))}`.trimEnd();
372
+ }
373
+
374
+ /** What a line of prose is painted as. */
375
+ export type Tone = 'plain' | 'dim' | 'bold' | 'caution' | 'good' | 'error';
376
+
377
+ /**
378
+ * A state and the mark that says it without colour: the mark prints in a pipe,
379
+ * the colour only repeats it.
380
+ */
381
+ export type State = 'caution' | 'error' | 'good' | 'point' | 'aside' | 'question';
382
+
383
+ const MARKS: Record<State, string> = {
384
+ caution: '!',
385
+ error: '✗',
386
+ good: '✓',
387
+ point: '→',
388
+ aside: '·',
389
+ question: '?',
390
+ };
391
+
392
+ /**
393
+ * A report, drawn in one order: the question and the figure that answers it,
394
+ * then the breakdown, then the notes and what to do next. A reader who stops
395
+ * after the first three lines has the answer.
396
+ *
397
+ * The commands hand it sentences and rows; it wraps them to the window,
398
+ * paints them at the terminal's depth and puts the one mark on the figure the
399
+ * headline names. Nothing here computes a figure: every number arrives as
400
+ * text the command already formatted.
401
+ */
402
+ export class Report {
403
+ private readonly out: string[] = [];
404
+ private marked = false;
405
+
406
+ constructor(
407
+ readonly width: number = COLUMNS,
408
+ private readonly paint = c,
409
+ /** Whether a window is known; tables are fitted to one only then. */
410
+ private readonly window: boolean = WINDOW,
411
+ ) {}
412
+
413
+ private tone(text: string, tone: Tone): string {
414
+ switch (tone) {
415
+ case 'dim':
416
+ return this.paint.dim(text);
417
+ case 'bold':
418
+ return this.paint.bold(text);
419
+ case 'caution':
420
+ return this.paint.yellow(text);
421
+ case 'good':
422
+ return this.paint.green(text);
423
+ case 'error':
424
+ return this.paint.red(text);
425
+ default:
426
+ return text;
427
+ }
428
+ }
429
+
430
+ /** The state's mark, painted in the state's colour. */
431
+ markOf(state: State): string {
432
+ const glyph = MARKS[state];
433
+ switch (state) {
434
+ case 'caution':
435
+ case 'question':
436
+ return this.paint.yellow(glyph);
437
+ case 'error':
438
+ return this.paint.red(glyph);
439
+ case 'good':
440
+ return this.paint.green(glyph);
441
+ case 'point':
442
+ return this.paint.accent(glyph);
443
+ default:
444
+ return this.paint.dim(glyph);
445
+ }
446
+ }
447
+
448
+ blank(): this {
449
+ this.out.push('');
450
+ return this;
451
+ }
452
+
453
+ /**
454
+ * The question, as a heading ruled out to the width, and the line that
455
+ * answers it with `figure` marked. The mark goes on one figure per report:
456
+ * a second headline draws its figure bold instead.
457
+ */
458
+ headline(question: string, answer: string, figure?: string): this {
459
+ this.heading(question);
460
+ return this.answer(answer, figure);
461
+ }
462
+
463
+ /** The answering line on its own, under a heading drawn elsewhere. */
464
+ answer(answer: string, figure?: string, indent = ' '): this {
465
+ const lines = wrapText(answer, this.width - indent.length);
466
+ const at = figure === undefined ? -1 : (lines[0] ?? '').indexOf(figure);
467
+ lines.forEach((line, index) => {
468
+ if (index === 0 && figure !== undefined && at !== -1) {
469
+ const painted = this.marked ? this.paint.bold(figure) : this.paint.mark(figure);
470
+ this.marked = true;
471
+ this.out.push(`${indent}${this.paint.bold(line.slice(0, at))}${painted}${this.paint.bold(line.slice(at + figure.length))}`);
472
+ } else {
473
+ this.out.push(`${indent}${this.paint.bold(line)}`);
474
+ }
475
+ });
476
+ return this;
477
+ }
478
+
479
+ /** A section heading with its rule. */
480
+ heading(text: string): this {
481
+ this.out.push(sectionHeading(text, this.width - 2, this.paint));
482
+ return this;
483
+ }
484
+
485
+ /** A bold title on its own line, no rule: a subsection. */
486
+ title(text: string, indent = ''): this {
487
+ this.out.push(`${indent}${this.paint.bold(text)}`);
488
+ return this;
489
+ }
490
+
491
+ /** A paragraph, wrapped to the window under `indent`. */
492
+ text(text: string, options: { indent?: string; tone?: Tone; first?: string } = {}): this {
493
+ const indent = options.indent ?? ' ';
494
+ const first = options.first ?? indent;
495
+ const tone = options.tone ?? 'plain';
496
+ wrapText(text, this.width - Math.max(visibleWidth(first), indent.length)).forEach((line, index) => {
497
+ this.out.push(`${index === 0 ? first : indent}${this.tone(line, tone)}`);
498
+ });
499
+ return this;
500
+ }
501
+
502
+ /**
503
+ * A note with its mark: `! sentence`, the wrapped lines hanging under the
504
+ * sentence. The mark carries the state; the sentence keeps the reader's
505
+ * colour unless `tone` says otherwise.
506
+ */
507
+ note(state: State, text: string, options: { indent?: string; tone?: Tone } = {}): this {
508
+ const indent = options.indent ?? ' ';
509
+ return this.text(text, {
510
+ first: `${indent}${this.markOf(state)} `,
511
+ indent: `${indent} `,
512
+ tone: options.tone ?? 'plain',
513
+ });
514
+ }
515
+
516
+ /** Rows under columns, fitted to the window. */
517
+ table(columns: TableColumn[], rows: Cell[][], indent = ' '): this {
518
+ this.out.push(...table(columns, rows, indent, this.window ? this.width : Number.POSITIVE_INFINITY, this.paint));
519
+ return this;
520
+ }
521
+
522
+ /** Whether a composed line fits the window; always, when there is none. */
523
+ fits(line: string): boolean {
524
+ return !this.window || visibleWidth(line) <= this.width;
525
+ }
526
+
527
+ /**
528
+ * The room left on a line after `lead`, for a cell that can be cut to fit:
529
+ * infinite when no window is known, so a pipe never loses a character.
530
+ */
531
+ room(lead: string): number {
532
+ return this.window ? Math.max(12, this.width - visibleWidth(lead)) : Number.POSITIVE_INFINITY;
533
+ }
534
+
535
+ /**
536
+ * Shares drawn as a bar before the line that states them: `███░░░ Input
537
+ * $3.51 27.6%`. A table of two columns, so a narrow window narrows the bar
538
+ * and never the line.
539
+ */
540
+ shares(rows: { share: number; text: string }[], indent = ' '): this {
541
+ return this.table(
542
+ [
543
+ { header: '', align: 'left' },
544
+ { header: '', align: 'left' },
545
+ ],
546
+ rows.map((row) => [{ bar: row.share }, row.text]),
547
+ indent,
548
+ );
549
+ }
550
+
551
+ /**
552
+ * A line the caller composed. For the few lines whose layout is the
553
+ * content (a diff, a column of rule tags); they are not wrapped.
554
+ */
555
+ line(text: string): this {
556
+ this.out.push(text);
557
+ return this;
558
+ }
559
+
560
+ lines(): string[] {
561
+ return [...this.out];
562
+ }
563
+
564
+ print(write: (line: string) => void = (line) => console.log(line)): void {
565
+ for (const line of this.out) write(line);
566
+ this.out.length = 0;
567
+ }
120
568
  }