@litfamily/litmuse 0.1.19 → 0.1.21

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.
@@ -0,0 +1,401 @@
1
+ // The cards a person at a terminal sees during `litmuse install` and `litmuse uninstall`: the mark, the questions, the
2
+ // work, one row per answer, and the closing panel. Every value starts in column 24, and one blank row parts two blocks. cardsFor() returns null for everything else (a pipe, CI, --yes, --dry-run,
3
+ // TERM=dumb, a small window, LITMUSE_AGENT_FILE), and then install and uninstall print their plain lines.
4
+ import { emitKeypressEvents } from 'node:readline';
5
+ import { CAP_LEFT, CAP_RIGHT, roundGlyphs } from './glyphs.mjs';
6
+ import { SIZES, colourDepth, markRows, sample } from './mark.mjs';
7
+ import { displayWidth } from '../plugin/lib/rewind/gauge.mjs';
8
+
9
+ const MIN_COLS = 40;
10
+ const MIN_ROWS = 12;
11
+ const MAX_CARD = 100;
12
+ const FOLD = 20;
13
+ const LABEL = 19;
14
+ const STEP = 19;
15
+ const BUTTON = 15;
16
+ // Keys already typed when a card appears are dropped, and so is the Enter that follows a y or n out of habit.
17
+ const SETTLE_MS = 30;
18
+ const HABIT_MS = 400;
19
+
20
+ const ESC = '\u001b';
21
+ const PINK = '#ff2d95';
22
+ const VIOLET = '#b48cff';
23
+ const CYAN = '#8be9fd';
24
+ const ORANGE = '#ff8f3c';
25
+ const GREEN = '#50e68c';
26
+ const AMBER = '#ffb02e';
27
+ const RED = '#ff5577';
28
+ const INK = '#0b0e14';
29
+ const BASIC = { [PINK]: 95, [VIOLET]: 94, [CYAN]: 96, [ORANGE]: 93, [GREEN]: 92, [AMBER]: 93, [RED]: 91, [INK]: 30 };
30
+
31
+ const DRAWN = {
32
+ box: ['╭', '╮', '╰', '╯', '─', '│'], chosen: ['╔', '╗', '╚', '╝', '═', '║'], done: '✓', fail: '✗', warn: '!', note: '·', busy: '⠙', pointer: '❯', arrows: '← →',
33
+ };
34
+ const TYPED = {
35
+ box: ['+', '+', '+', '+', '-', '|'], chosen: ['#', '#', '#', '#', '=', '#'], done: 'ok', fail: 'x', warn: '!', note: '-', busy: '*', pointer: '>', arrows: 'Left Right',
36
+ };
37
+ const TYPED_FOR = { '·': '-', '—': '-', '→': '->', '…': '...' };
38
+
39
+ const bare = (text) => text.replace(/\u001b\[[0-9;]*m/g, '');
40
+ const cells = (text) => displayWidth(bare(text));
41
+ const pad = (text, width) => text + ' '.repeat(Math.max(0, width - cells(text)));
42
+
43
+ // Wraps at spaces, keeping a line's own indent. A longer word (a path) continues on the next line; nothing is dropped.
44
+ export function wrap(text, width) {
45
+ const indent = /^ */.exec(text)[0];
46
+ const lines = [indent];
47
+ for (const word of text.trim().split(/ +/)) {
48
+ const last = lines.length - 1;
49
+ const empty = lines[last].trim() === '';
50
+ if (cells(lines[last]) + (empty ? 0 : 1) + cells(word) <= width) {
51
+ lines[last] += empty ? word : ` ${word}`;
52
+ continue;
53
+ }
54
+ if (!empty) lines.push(indent);
55
+ for (const ch of word) {
56
+ if (cells(lines.at(-1) + ch) > width) lines.push(indent);
57
+ lines[lines.length - 1] += ch;
58
+ }
59
+ }
60
+ return lines;
61
+ }
62
+
63
+ const cubeLevel = (v) => (v < 48 ? 0 : v < 115 ? 1 : Math.floor((v - 35) / 40));
64
+
65
+ function painter(depth) {
66
+ const code = (hex, back, basic) => {
67
+ if (depth === '16') return String(basic + (back ? 10 : 0));
68
+ const [r, g, b] = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
69
+ const value = depth === 'truecolor' ? `2;${r};${g};${b}` : `5;${16 + 36 * cubeLevel(r) + 6 * cubeLevel(g) + cubeLevel(b)}`;
70
+ return `${back ? 48 : 38};${value}`;
71
+ };
72
+ const paint = (text, { fg, bg, bold, dim, basic }) => {
73
+ if (depth === 'none' || !text) return text;
74
+ const codes = [bold && 1, dim && 2, fg && code(fg, false, BASIC[fg] ?? basic), bg && code(bg, true, BASIC[bg] ?? basic)].filter(Boolean);
75
+ return `${ESC}[${codes.join(';')}m${text}${ESC}[0m`;
76
+ };
77
+ // `text` along `stops`; `at` and `of` say where it lies on a longer run, so a border cut by its title stays one ramp.
78
+ const ramp = (text, stops, { onto = 'fg', at = 0, of = [...text].length, bold = false } = {}) => {
79
+ if (depth === 'none') return text;
80
+ const parts = [];
81
+ [...text].forEach((ch, i) => {
82
+ const step = Math.round(((at + i) / Math.max(1, of - 1)) * 20) / 20;
83
+ if (parts.at(-1)?.step === step) parts.at(-1).text += ch;
84
+ else parts.push({ step, text: ch });
85
+ });
86
+ return parts.map((p) => paint(p.text, {
87
+ [onto]: sample(stops, p.step), basic: BASIC[stops[Math.round(p.step * (stops.length - 1))]], bold, ...(onto === 'bg' ? { fg: INK } : {}),
88
+ })).join('');
89
+ };
90
+ return { paint, ramp };
91
+ }
92
+
93
+ // NO_COLOR keeps the cards without colour; a terminal below 256 colours gets the sixteen basic ones.
94
+ function depthOf(env, stdout) {
95
+ if (env.NO_COLOR) return 'none';
96
+ const depth = colourDepth({ env, isTTY: stdout.isTTY });
97
+ return depth === 'none' ? '16' : depth;
98
+ }
99
+
100
+ const typedLocale = (env) => {
101
+ const locale = env.LC_ALL || env.LC_CTYPE || env.LANG || '';
102
+ return locale !== '' && !/utf-?8/i.test(locale);
103
+ };
104
+
105
+ /** Panel rows for `[label, value]` pairs of what is about to happen. */
106
+ export const planRows = (pairs) => pairs.map(([label, value]) => ({ mark: 'note', label, value }));
107
+
108
+ const lightTerminal = (env) => /;(7|15)$/.test(env.COLORFGBG ?? '');
109
+
110
+ /** The cards for this terminal, or null when the plain lines should be printed. */
111
+ export function cardsFor({ env = process.env, flags = {}, stdin = process.stdin, stdout = process.stdout, ...rest } = {}) {
112
+ const person = stdin.isTTY && stdout.isTTY && typeof stdin.setRawMode === 'function' && !env.CI && !/^dumb$/i.test(env.TERM ?? '');
113
+ if (!person || flags.yes || flags.dryRun || env.LITMUSE_AGENT_FILE) return null;
114
+ if ((stdout.columns || 80) < MIN_COLS || (stdout.rows || 24) < MIN_ROWS) return null;
115
+ return createCards({ env, stdin, stdout, ...rest });
116
+ }
117
+
118
+ export function createCards({ env, stdin, stdout, proc = process, now = Date.now, settleMs = SETTLE_MS }) {
119
+ const depth = depthOf(env, stdout);
120
+ const typed = typedLocale(env);
121
+ // Decided once, so a run never mixes round and square.
122
+ const round = depth === 'truecolor' && !typed && !lightTerminal(env) && roundGlyphs(env);
123
+ const sign = typed ? TYPED : DRAWN;
124
+ const { paint, ramp } = painter(depth);
125
+ const cols = () => stdout.columns || 80;
126
+ const rows = () => stdout.rows || 24;
127
+ const width = () => Math.min(MAX_CARD, cols() - 2);
128
+ const inner = () => width() - 4;
129
+ const say = (text) => (typed ? String(text).replace(/[·—→…]/g, (ch) => TYPED_FOR[ch]) : String(text));
130
+ const bold = (text) => paint(text, { bold: true });
131
+ const dim = (text) => paint(text, { dim: true });
132
+ let letterAt = -Infinity;
133
+ // Folded rows stand together; any other two blocks have one blank row between them.
134
+ let last = null;
135
+ const apart = (kind) => {
136
+ const blank = last !== null && !(last === 'fold' && kind === 'fold') ? '\n' : '';
137
+ last = kind;
138
+ return blank;
139
+ };
140
+ const home = env.HOME && env.HOME !== '/' ? `${env.HOME.replace(/[\\/]$/, '')}` : null;
141
+ /** Paths under the home folder start with `~`. */
142
+ const short = (value) => (home ? String(value).replaceAll(`${home}/`, '~/').replaceAll(`${home}\\`, '~\\') : String(value));
143
+
144
+ // Text on a gradient fill, one cell wider on each side: a round cap, or a cell of the fill.
145
+ const filled = (text, stops) => {
146
+ const size = cells(text) + 2;
147
+ if (!round) return ramp(` ${text} `, stops, { onto: 'bg', bold: true });
148
+ return paint(CAP_LEFT, { fg: stops[0] }) + ramp(text, stops, { onto: 'bg', bold: true, at: 1, of: size }) + paint(CAP_RIGHT, { fg: stops.at(-1) });
149
+ };
150
+
151
+ const frame = ({ tag = 'LIT', title, body, bad }) => {
152
+ const w = width();
153
+ const [tl, tr, bl, br, h, v] = sign.box;
154
+ const edge = (text, at) => ramp(text, bad ? [RED, RED] : [PINK, VIOLET, CYAN], { at, of: w });
155
+ const pill = depth === 'none' ? `[${tag}]` : filled(tag, [ORANGE, PINK]);
156
+ const name = say(title);
157
+ const fits = cells(pill) + cells(name) + 9 <= w;
158
+ const head = ` ${pill} ${fits ? `${dim(say('·'))} ${bold(name)} ` : ''}`;
159
+ const used = 2 + cells(head);
160
+ const inside = fits ? body : [...wrap(name, w - 4).map(bold), ...body];
161
+ return [
162
+ ` ${edge(tl + h, 0)}${head}${edge(h.repeat(w - used - 1) + tr, used)}`,
163
+ ...inside.map((row) => ` ${edge(v, 0)} ${pad(row, w - 4)} ${edge(v, w - 1)}`),
164
+ ` ${edge(bl + h.repeat(w - 2) + br, 0)}`,
165
+ ];
166
+ };
167
+
168
+ const marked = (mark) => paint(sign[mark], { fg: { done: GREEN, fail: RED, warn: AMBER, note: VIOLET, busy: PINK }[mark], bold: true });
169
+
170
+ // A folded row's value starts in column 24; a long label, or a narrow window, puts it after one space.
171
+ const rowLines = (mark, label, value) => {
172
+ const lead = ` ${marked(mark)} `;
173
+ const name = say(label);
174
+ const room = cols() - 1;
175
+ const wide = pad(lead + name, 3 + FOLD + 1);
176
+ const start = cells(wide) + cells(say(value)) <= room || room - cells(wide) >= 24 ? wide : `${lead}${name} `;
177
+ return wrap(say(value), Math.max(12, room - cells(start))).map((line, i) => (i ? ' '.repeat(cells(start)) : start) + bold(line));
178
+ };
179
+
180
+ /** One folded answer or step. */
181
+ const row = (mark, label, value) => { stdout.write(`${apart('fold')}${rowLines(mark, label, value).join('\n')}\n`); };
182
+
183
+ /** The LIT mark centred over the cards, as large as the window allows, then one dim line about the run. */
184
+ const intro = (line) => {
185
+ const most = rows() >= 48 ? 0 : rows() >= 34 ? 1 : 2;
186
+ const size = SIZES.slice(most).find(([, min]) => width() >= min);
187
+ const art = markRows({ cols: cols(), depth: colourDepth({ env, isTTY: true }), size: size?.[0] });
188
+ const indent = ' '.repeat(Math.max(0, 1 + Math.floor((width() - Math.max(...art.map(cells))) / 2)));
189
+ stdout.write(`\n${art.map((r) => indent + r).join('\n')}\n\n${wrap(say(short(line)), width()).map((l) => ` ${dim(l)}`).join('\n')}\n`);
190
+ last = 'text';
191
+ };
192
+
193
+ const textLines = (heading, lines) => [
194
+ ...wrap(say(heading), width()).map((l) => ` ${bold(l)}`),
195
+ ...lines.flatMap((line) => (/^ {4}/.test(line) ? [` ${line}`] : wrap(say(line), width() - 2).map((l) => ` ${l}`))),
196
+ ];
197
+ /** Wrapped text under a heading. A command (four spaces in) stays on one line, so it can be copied. */
198
+ const text = (heading, lines) => { stdout.write(`${apart('text')}${textLines(heading, lines).join('\n')}\n`); };
199
+
200
+ /** A finished card: sections of { head, rows: [{ mark, label, value }] }. Values wrap and are never cut. */
201
+ const panel = ({ title, sections, bad = false }) => {
202
+ const markCells = 2;
203
+ const labelCells = inner() < 56 ? 0 : LABEL;
204
+ const body = sections.flatMap(({ head, rows: list }) => [
205
+ '',
206
+ ...(head ? [paint(head, { fg: bad ? RED : PINK, bold: true })] : []),
207
+ ...list.flatMap(({ mark = 'done', label = '', value }) => {
208
+ const lead = pad(marked(mark), Math.max(markCells, cells(marked(mark)) + 1));
209
+ const loud = mark === 'warn' || mark === 'fail' ? bold : (line) => line;
210
+ const name = say(label);
211
+ if (label && !labelCells) return [...wrap(name, inner() - markCells).map((line, i) => (i ? ' '.repeat(markCells) : lead) + bold(line)), ...wrap(say(short(value)), inner() - markCells).map((line) => ' '.repeat(markCells) + loud(line))];
212
+ const named = label ? lead + bold(name) : lead;
213
+ const start = !label ? lead : cells(named) < markCells + labelCells ? pad(named, markCells + labelCells) : `${named} `;
214
+ return wrap(say(short(value)), inner() - cells(start)).map((line, i) => (i ? ' '.repeat(cells(start)) : start) + loud(line));
215
+ }),
216
+ ]);
217
+ stdout.write(`${apart('card')}${frame({ title, body, bad }).join('\n')}\n`);
218
+ };
219
+
220
+ /**
221
+ * The work card: `steps` are [name, what it does]. next() starts a step, done() folds the card to one row, and fail()
222
+ * leaves it on screen with the running step marked.
223
+ */
224
+ const work = (title, label, steps) => {
225
+ let at = -1;
226
+ let shown = 0;
227
+ const joins = last === 'fold';
228
+ const draw = (stopped = false) => {
229
+ const list = steps.map(([name, what], i) => {
230
+ const mark = i < at ? 'done' : i > at ? 'note' : stopped ? 'fail' : 'busy';
231
+ const lead = `${pad(marked(mark), 2)}${mark === 'done' || mark === 'note' ? name : bold(name)}`;
232
+ const start = pad(lead, 2 + (inner() < 56 ? Math.max(...steps.map(([n]) => cells(n))) + 2 : STEP));
233
+ return cells(start) + cells(what) <= inner() ? start + (mark === 'note' || mark === 'done' ? dim(say(what)) : say(what)) : lead;
234
+ });
235
+ const lines = frame({ title, body: ['', ...list] });
236
+ const lead = shown ? `${ESC}[${shown}A\r` : apart('card');
237
+ shown = lines.length;
238
+ stdout.write(`${lead}${lines.map((line) => `${line}${ESC}[K`).join('\n')}\n`);
239
+ };
240
+ return {
241
+ next: () => {
242
+ at += 1;
243
+ draw();
244
+ },
245
+ fail: () => draw(true),
246
+ done: () => {
247
+ // The blank row over the card goes too when the row joins others.
248
+ stdout.write(`${ESC}[${shown + (joins ? 1 : 0)}A\r${ESC}[J${rowLines('done', label, `${steps.length} of ${steps.length} checked`).join('\n')}\n`);
249
+ last = 'fold';
250
+ },
251
+ };
252
+ };
253
+
254
+ const buttons = (yes, defaultYes, small) => {
255
+ const ending = inner() >= 44 ? ' (default)' : ' default';
256
+ const size = inner() >= 44 ? BUTTON : BUTTON - 2;
257
+ const drawn = [true, false].map((value) => {
258
+ const on = value === yes;
259
+ const label = pad(`${on ? sign.pointer : ' '} ${value ? 'Yes' : 'No'}${value === defaultYes ? ending : ''}`, size);
260
+ const plain = depth === 'none' || typed;
261
+ if (small) return [on ? (depth === 'none' ? `[${label}]` : filled(label, [PINK, VIOLET])) : dim(` ${label} `)];
262
+ const [tl, tr, bl, br, h, v] = on && plain ? sign.chosen : sign.box;
263
+ const wide = size + 6;
264
+ const line = (chars, at) => (on ? ramp(chars, [PINK, VIOLET], { at, of: wide, bold: plain }) : dim(chars));
265
+ const face = !on ? ` ${label} ` : plain ? ` ${bold(label)} ` : filled(label, [PINK, VIOLET]);
266
+ return [line(tl + h.repeat(wide - 2) + tr, 0), `${line(v, 0)} ${face} ${line(v, wide - 1)}`, line(bl + h.repeat(wide - 2) + br, 0)];
267
+ });
268
+ return drawn[0].map((left, i) => `${left} ${drawn[1][i]}`);
269
+ };
270
+
271
+ const hints = (list) => list.reduce((lines, hint) => {
272
+ const joined = lines.length ? `${lines.at(-1)} ${hint}` : hint;
273
+ return lines.length && cells(joined) > inner() ? [...lines, hint] : [...lines.slice(0, -1), joined];
274
+ }, []).map(dim);
275
+
276
+ // Roomy when the window allows, then tighter; the note and both buttons always stay.
277
+ const question = ({ tag, title, note, list }, defaultYes, yes) => {
278
+ const noteLines = wrap(say(note), inner());
279
+ const enter = `Enter = ${yes ? 'Yes' : 'No'}`;
280
+ const see = list ? [list.hint] : [];
281
+ const keys = hints(['y / n answer', `${sign.arrows} switch`, enter, ...see, 'Ctrl+C stop']);
282
+ const small = buttons(yes, defaultYes, true);
283
+ const big = buttons(yes, defaultYes, false);
284
+ const pair = cells(big[0]) <= inner() ? big : small;
285
+ const heading = `${title} ${defaultYes ? '[Y/n]' : '[y/N]'}`;
286
+ const drawn = [
287
+ ['', ...noteLines, '', ...pair, '', ...keys],
288
+ [...noteLines, '', ...pair, '', ...keys],
289
+ [...noteLines, ...small, ...keys],
290
+ [...noteLines, ...small, ...hints(['y / n', enter, ...see, 'Ctrl+C stop'])],
291
+ ].map((body, i) => [...(i < 2 ? [''] : []), ...frame({ tag, title: heading, body })]);
292
+ return drawn.find((list) => list.length < rows()) ?? drawn.at(-1).slice(-(rows() - 1));
293
+ };
294
+
295
+ /** Asks with a card: `card` is { tag, title, note, yes, no, list? }; `list` is { hint, heading, lines }, printed above
296
+ * the card when the person types l. Ctrl+C and Ctrl+D throw, as they do at the plain prompt. */
297
+ const ask = async (_plain, { defaultYes = false, card }) => {
298
+ let yes = defaultYes;
299
+ let shown = [];
300
+ let held = false;
301
+ const lift = (count) => (count ? `${ESC}[${count}A` : '');
302
+ const draw = (over = shown.length) => {
303
+ shown = question(card, defaultYes, yes);
304
+ stdout.write(`${lift(over)}\r${shown.map((line) => `${line}${ESC}[K\r\n`).join('')}${ESC}[J`);
305
+ };
306
+ const wipe = () => `${lift(shown.length)}\r${ESC}[J`;
307
+ const fold = (mark, value) => stdout.write(`${wipe()}${apart('fold')}${rowLines(mark, card.title, value).join('\n')}\n`);
308
+ const showList = () => {
309
+ stdout.write(`${wipe()}${apart('text')}${textLines(card.list.heading, card.list.lines).join('\n')}\n`);
310
+ draw(0);
311
+ };
312
+ const take = () => {
313
+ held = true;
314
+ stdin.setRawMode(true);
315
+ stdin.resume();
316
+ stdout.write(`${ESC}[?25l`);
317
+ };
318
+ const give = () => {
319
+ if (!held) return;
320
+ held = false;
321
+ stdout.write(`${ESC}[?25h`);
322
+ stdin.setRawMode(false);
323
+ stdin.pause();
324
+ };
325
+ const undo = [];
326
+ const on = (source, event, fn) => {
327
+ source.on(event, fn);
328
+ undo.push(() => source.removeListener(event, fn));
329
+ };
330
+ const release = () => {
331
+ give();
332
+ for (const fn of undo.splice(0)) fn();
333
+ };
334
+
335
+ take();
336
+ on(proc, 'exit', give);
337
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
338
+ on(proc, signal, () => {
339
+ release();
340
+ proc.kill(proc.pid, signal);
341
+ });
342
+ }
343
+ try {
344
+ const answer = await new Promise((resolve, reject) => {
345
+ let ready = false;
346
+ let settling;
347
+ const stop = (reason) => {
348
+ clearTimeout(settling);
349
+ reject(new Error(reason));
350
+ };
351
+ const suspend = () => {
352
+ stdout.write(`${ESC}[?25h`);
353
+ stdin.setRawMode(false);
354
+ proc.once('SIGCONT', () => {
355
+ if (!held) return;
356
+ stdin.setRawMode(true);
357
+ stdout.write(`${ESC}[?25l`);
358
+ draw(0);
359
+ });
360
+ proc.kill(0, 'SIGTSTP');
361
+ };
362
+ emitKeypressEvents(stdin);
363
+ on(stdin, 'keypress', (ch, key = {}) => {
364
+ if (key.ctrl && key.name === 'c') stop('Aborted with Ctrl+C');
365
+ else if (!ready || key.meta || key.name === 'escape') return;
366
+ else if (key.ctrl && key.name === 'd') stop('Aborted with Ctrl+D');
367
+ else if (key.ctrl && key.name === 'z' && proc.platform !== 'win32') suspend();
368
+ else if (key.ctrl) return;
369
+ else if (key.name === 'return' || key.name === 'enter') {
370
+ if (now() - letterAt >= HABIT_MS) resolve(yes);
371
+ } else if (/^[yn]$/i.test(ch ?? '')) {
372
+ letterAt = now();
373
+ resolve(/y/i.test(ch));
374
+ } else if (card.list && /^l$/i.test(ch ?? '')) showList();
375
+ else if (['left', 'right', 'tab'].includes(key.name)) {
376
+ yes = !yes;
377
+ draw();
378
+ }
379
+ });
380
+ on(stdin, 'end', () => stop('Aborted: the terminal closed'));
381
+ on(stdout, 'resize', () => {
382
+ // The old rows may have wrapped in the new width: step over what they take up now.
383
+ if (ready) draw(Math.min(shown.reduce((sum, line) => sum + Math.max(1, Math.ceil(cells(line) / cols())), 0), rows() - 1));
384
+ });
385
+ settling = setTimeout(() => {
386
+ ready = true;
387
+ draw();
388
+ }, settleMs);
389
+ });
390
+ fold('done', answer ? card.yes : card.no);
391
+ return answer;
392
+ } catch (err) {
393
+ fold('fail', 'stopped');
394
+ throw err;
395
+ } finally {
396
+ release();
397
+ }
398
+ };
399
+
400
+ return { ask, row, text, panel, work, intro, short };
401
+ }