@bazilio-san/glm-cc 1.0.19 → 1.0.22

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.
package/bin/lib/ui.js ADDED
@@ -0,0 +1,418 @@
1
+ // Minimal terminal UI toolkit for the glm configuration helper.
2
+ //
3
+ // Deliberately dependency-free: glm's whole value is that installing it pulls
4
+ // nothing but this package, so the arrow-key menus, masked input and spinner
5
+ // are implemented directly on top of node:readline and raw-mode stdin.
6
+
7
+ import process from 'node:process';
8
+ import readline from 'node:readline';
9
+
10
+ const ESC = '\x1b';
11
+
12
+ // No colour when the output is piped into a file or another program, when
13
+ // NO_COLOR is set, or on a terminal that cannot render escape sequences.
14
+ const colorEnabled = process.env.NO_COLOR == null
15
+ && process.env.TERM !== 'dumb'
16
+ && Boolean(process.stdout.isTTY);
17
+
18
+ const wrap = (open, close) => (s) => (colorEnabled ? `${ESC}[${open}m${s}${ESC}[${close}m` : String(s));
19
+
20
+ export const c = {
21
+ bold: wrap(1, 22),
22
+ dim: wrap(2, 22),
23
+ red: wrap(31, 39),
24
+ green: wrap(32, 39),
25
+ yellow: wrap(33, 39),
26
+ blue: wrap(34, 39),
27
+ cyan: wrap(36, 39),
28
+ gray: wrap(90, 39),
29
+ };
30
+
31
+ export function stripAnsi (s) {
32
+ // eslint-disable-next-line no-control-regex
33
+ return String(s).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '');
34
+ }
35
+
36
+ const width = () => process.stdout.columns || 80;
37
+
38
+ /** Cut a string to the terminal width without slicing an escape sequence apart. */
39
+ function fit (line) {
40
+ const max = width() - 1;
41
+ if (stripAnsi(line).length <= max) return line;
42
+ let out = '';
43
+ let visible = 0;
44
+ let i = 0;
45
+ while (i < line.length && visible < max - 1) {
46
+ if (line[i] === ESC) {
47
+ const end = line.indexOf('m', i);
48
+ if (end === -1) break;
49
+ out += line.slice(i, end + 1);
50
+ i = end + 1;
51
+ continue;
52
+ }
53
+ out += line[i];
54
+ visible += 1;
55
+ i += 1;
56
+ }
57
+ return `${out}…${colorEnabled ? `${ESC}[0m` : ''}`;
58
+ }
59
+
60
+ /**
61
+ * Print one line. Nothing is truncated here — only the in-place re-render of
62
+ * `select` needs lines to fit on a single terminal row.
63
+ */
64
+ export function write (line = '') {
65
+ process.stdout.write(`${line}\n`);
66
+ }
67
+
68
+ export function clearScreen () {
69
+ process.stdout.write(`${ESC}[2J${ESC}[H`);
70
+ }
71
+
72
+ const BOX_WIDTH = 66;
73
+
74
+ function centered (text, boxWidth) {
75
+ const inner = boxWidth - 2;
76
+ const len = stripAnsi(text).length;
77
+ const left = Math.max(0, Math.floor((inner - len) / 2));
78
+ const right = Math.max(0, inner - len - left);
79
+ return `║${' '.repeat(left)}${text}${' '.repeat(right)}║`;
80
+ }
81
+
82
+ /** Draw a double-line box with a centred title. */
83
+ export function box (title, subtitle) {
84
+ const top = `╔${'═'.repeat(BOX_WIDTH - 2)}╗`;
85
+ const bottom = `╚${'═'.repeat(BOX_WIDTH - 2)}╝`;
86
+ write('');
87
+ write(c.cyan(top));
88
+ write(c.cyan(centered(c.bold(title), BOX_WIDTH)));
89
+ if (subtitle) write(c.cyan(centered(c.gray(subtitle), BOX_WIDTH)));
90
+ write(c.cyan(bottom));
91
+ write('');
92
+ }
93
+
94
+ export function separator () {
95
+ return { separator: true };
96
+ }
97
+
98
+ function assertInteractive () {
99
+ if (!process.stdin.isTTY) {
100
+ throw new Error('glm configuration needs an interactive terminal. Run `glm -c` directly in your shell.');
101
+ }
102
+ }
103
+
104
+ function onCancel () {
105
+ process.stdout.write(`${ESC}[?25h\n`);
106
+ process.stdout.write(`${c.gray('Cancelled.')}\n`);
107
+ process.exit(130);
108
+ }
109
+
110
+ /**
111
+ * Arrow-key list. Returns the `value` of the chosen entry.
112
+ *
113
+ * choices: array of { name, value, disabled?, hint? } or separator() markers.
114
+ */
115
+ export function select ({ message, choices, pageSize = 12, initial = 0 }) {
116
+ assertInteractive();
117
+
118
+ const selectable = choices
119
+ .map((ch, i) => ({ ch, i }))
120
+ .filter(({ ch }) => !ch.separator && !ch.disabled)
121
+ .map(({ i }) => i);
122
+
123
+ if (selectable.length === 0) throw new Error('select() called without any selectable choice');
124
+
125
+ let cursor = selectable.includes(initial) ? initial : selectable[0];
126
+ let start = 0;
127
+ let printed = 0;
128
+
129
+ const visibleCount = Math.min(pageSize, choices.length);
130
+
131
+ const ensureVisible = () => {
132
+ if (cursor < start) start = cursor;
133
+ if (cursor >= start + visibleCount) start = cursor - visibleCount + 1;
134
+ start = Math.max(0, Math.min(start, choices.length - visibleCount));
135
+ };
136
+
137
+ const render = () => {
138
+ ensureVisible();
139
+ const lines = [];
140
+ if (message) lines.push(c.bold(message));
141
+ lines.push(c.gray(' Use ↑/↓ to move, Enter to confirm, Ctrl+C to cancel'));
142
+ lines.push('');
143
+
144
+ const slice = choices.slice(start, start + visibleCount);
145
+ slice.forEach((ch, offset) => {
146
+ const index = start + offset;
147
+ if (ch.separator) {
148
+ lines.push(c.gray(' ──────────────────────────────────────────────'));
149
+ return;
150
+ }
151
+ const label = ch.hint ? `${ch.name} ${c.gray(ch.hint)}` : ch.name;
152
+ if (ch.disabled) {
153
+ lines.push(` ${c.gray(stripAnsi(label))}`);
154
+ } else if (index === cursor) {
155
+ lines.push(c.cyan(` ❯ ${label}`));
156
+ } else {
157
+ lines.push(` ${label}`);
158
+ }
159
+ });
160
+
161
+ if (choices.length > visibleCount) {
162
+ const shown = `${start + 1}-${start + visibleCount} of ${choices.length}`;
163
+ lines.push(c.gray(` … ${shown}`));
164
+ }
165
+
166
+ if (printed) process.stdout.write(`${ESC}[${printed}A${ESC}[J`);
167
+ process.stdout.write(`${lines.map(fit).join('\n')}\n`);
168
+ printed = lines.length;
169
+ };
170
+
171
+ const move = (delta) => {
172
+ const pos = selectable.indexOf(cursor);
173
+ const next = (pos + delta + selectable.length) % selectable.length;
174
+ cursor = selectable[next];
175
+ };
176
+
177
+ return new Promise((resolve) => {
178
+ const stdin = process.stdin;
179
+ const wasRaw = stdin.isRaw;
180
+ stdin.setRawMode(true);
181
+ stdin.resume();
182
+ stdin.setEncoding('utf8');
183
+ process.stdout.write(`${ESC}[?25l`);
184
+ render();
185
+
186
+ const finish = (value) => {
187
+ stdin.removeListener('data', onData);
188
+ stdin.setRawMode(Boolean(wasRaw));
189
+ stdin.pause();
190
+ process.stdout.write(`${ESC}[?25h`);
191
+ resolve(value);
192
+ };
193
+
194
+ const onData = (key) => {
195
+ switch (key) {
196
+ case '\x03': // Ctrl+C
197
+ stdin.removeListener('data', onData);
198
+ stdin.setRawMode(Boolean(wasRaw));
199
+ onCancel();
200
+ return;
201
+ case `${ESC}[A`:
202
+ case 'k':
203
+ move(-1);
204
+ render();
205
+ return;
206
+ case `${ESC}[B`:
207
+ case 'j':
208
+ move(1);
209
+ render();
210
+ return;
211
+ case `${ESC}[5~`: // PageUp
212
+ for (let n = 0; n < visibleCount; n += 1) move(-1);
213
+ render();
214
+ return;
215
+ case `${ESC}[6~`: // PageDown
216
+ for (let n = 0; n < visibleCount; n += 1) move(1);
217
+ render();
218
+ return;
219
+ case `${ESC}[H`:
220
+ cursor = selectable[0];
221
+ render();
222
+ return;
223
+ case `${ESC}[F`:
224
+ cursor = selectable[selectable.length - 1];
225
+ render();
226
+ return;
227
+ case '\r':
228
+ case '\n':
229
+ finish(choices[cursor].value);
230
+ return;
231
+ default:
232
+ break;
233
+ }
234
+ // Digits 1-9 jump straight to a selectable entry.
235
+ if (/^[1-9]$/.test(key)) {
236
+ const idx = selectable[Number(key) - 1];
237
+ if (idx != null) {
238
+ cursor = idx;
239
+ render();
240
+ }
241
+ }
242
+ };
243
+
244
+ stdin.on('data', onData);
245
+ });
246
+ }
247
+
248
+ /** Free-text question with full line editing, courtesy of readline. */
249
+ export function input ({ message, defaultValue = '', validate }) {
250
+ assertInteractive();
251
+ const hint = defaultValue ? ` ${c.gray(`[${defaultValue}]`)}` : '';
252
+
253
+ return new Promise((resolve) => {
254
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
255
+ const askOnce = () => {
256
+ rl.question(`${c.bold(message)}${hint}: `, (answer) => {
257
+ const value = answer.trim() === '' ? defaultValue : answer.trim();
258
+ const problem = validate ? validate(value) : true;
259
+ if (problem !== true) {
260
+ process.stdout.write(`${c.red(` ${problem}`)}\n`);
261
+ askOnce();
262
+ return;
263
+ }
264
+ rl.close();
265
+ resolve(value);
266
+ });
267
+ };
268
+ rl.on('SIGINT', () => { rl.close(); onCancel(); });
269
+ askOnce();
270
+ });
271
+ }
272
+
273
+ /** Hidden question. Typed characters show up as dots; backspace works. */
274
+ export function password ({ message, validate }) {
275
+ assertInteractive();
276
+
277
+ const askOnce = () => new Promise((resolve) => {
278
+ const stdin = process.stdin;
279
+ const wasRaw = stdin.isRaw;
280
+ let buffer = '';
281
+
282
+ process.stdout.write(`${c.bold(message)}: `);
283
+ stdin.setRawMode(true);
284
+ stdin.resume();
285
+ stdin.setEncoding('utf8');
286
+
287
+ const onData = (key) => {
288
+ if (key === '\x03') { // Ctrl+C
289
+ stdin.removeListener('data', onData);
290
+ stdin.setRawMode(Boolean(wasRaw));
291
+ onCancel();
292
+ return;
293
+ }
294
+ if (key === '\r' || key === '\n') {
295
+ stdin.removeListener('data', onData);
296
+ stdin.setRawMode(Boolean(wasRaw));
297
+ stdin.pause();
298
+ process.stdout.write('\n');
299
+ resolve(buffer);
300
+ return;
301
+ }
302
+ if (key === '\x7f' || key === '\b') {
303
+ if (buffer.length > 0) {
304
+ buffer = buffer.slice(0, -1);
305
+ process.stdout.write('\b \b');
306
+ }
307
+ return;
308
+ }
309
+ // Ignore remaining control characters and escape sequences.
310
+ // eslint-disable-next-line no-control-regex
311
+ if (/[\x00-\x1f]/.test(key)) return;
312
+ buffer += key;
313
+ process.stdout.write('●'.repeat(key.length));
314
+ };
315
+
316
+ stdin.on('data', onData);
317
+ });
318
+
319
+ const loop = async () => {
320
+ for (;;) {
321
+ const value = (await askOnce()).trim();
322
+ const problem = validate ? validate(value) : true;
323
+ if (problem === true) return value;
324
+ process.stdout.write(`${c.red(` ${problem}`)}\n`);
325
+ }
326
+ };
327
+
328
+ return loop();
329
+ }
330
+
331
+ export async function confirm ({ message, defaultValue = false }) {
332
+ const answer = await select({
333
+ message,
334
+ choices: [
335
+ { name: 'Yes', value: true },
336
+ { name: 'No', value: false },
337
+ ],
338
+ initial: defaultValue ? 0 : 1,
339
+ });
340
+ return answer;
341
+ }
342
+
343
+ /** Wait for any single keypress. Ctrl+C still cancels. */
344
+ export function pause (text = 'Press any key to continue') {
345
+ assertInteractive();
346
+ process.stdout.write(`${c.gray(text)}`);
347
+
348
+ return new Promise((resolve) => {
349
+ const stdin = process.stdin;
350
+ const wasRaw = stdin.isRaw;
351
+ stdin.setRawMode(true);
352
+ stdin.resume();
353
+ stdin.setEncoding('utf8');
354
+
355
+ const onData = (key) => {
356
+ stdin.removeListener('data', onData);
357
+ stdin.setRawMode(Boolean(wasRaw));
358
+ stdin.pause();
359
+ if (key === '\x03') {
360
+ onCancel();
361
+ return;
362
+ }
363
+ process.stdout.write('\n');
364
+ resolve();
365
+ };
366
+
367
+ stdin.on('data', onData);
368
+ });
369
+ }
370
+
371
+ const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
372
+
373
+ /**
374
+ * Small indeterminate progress indicator. When the output is not a terminal
375
+ * there is nothing to animate in place, so it only prints the final line.
376
+ */
377
+ export function spinner (text) {
378
+ let frame = 0;
379
+ let current = text;
380
+ let timer = null;
381
+
382
+ if (!process.stdout.isTTY) {
383
+ return {
384
+ update (next) { current = next; },
385
+ succeed (line) { write(`✔ ${line ?? current}`); },
386
+ fail (line) { write(`✘ ${line ?? current}`); },
387
+ warn (line) { write(`! ${line ?? current}`); },
388
+ stop () {},
389
+ };
390
+ }
391
+
392
+ const paint = () => {
393
+ process.stdout.write(`\r${ESC}[2K${c.cyan(SPINNER_FRAMES[frame])} ${current}`);
394
+ frame = (frame + 1) % SPINNER_FRAMES.length;
395
+ };
396
+
397
+ const stopWith = (line) => {
398
+ if (timer) clearInterval(timer);
399
+ timer = null;
400
+ process.stdout.write(`\r${ESC}[2K`);
401
+ if (line) process.stdout.write(`${fit(line)}\n`);
402
+ process.stdout.write(`${ESC}[?25h`);
403
+ };
404
+
405
+ process.stdout.write(`${ESC}[?25l`);
406
+ paint();
407
+ timer = setInterval(paint, 90);
408
+
409
+ return {
410
+ update (next) { current = next; },
411
+ succeed (line) { stopWith(`${c.green('✔')} ${line ?? current}`); },
412
+ fail (line) { stopWith(`${c.red('✘')} ${line ?? current}`); },
413
+ warn (line) { stopWith(`${c.yellow('!')} ${line ?? current}`); },
414
+ stop () { stopWith(null); },
415
+ };
416
+ }
417
+
418
+ export const sleep = (ms) => new Promise((resolve) => { setTimeout(resolve, ms); });