inquirerer 4.1.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -62,6 +62,11 @@ npm install inquirerer
62
62
  - [Custom Resolvers](#custom-resolvers)
63
63
  - [Resolver Examples](#resolver-examples)
64
64
  - [CLI Helper](#cli-helper)
65
+ - [UI Components](#ui-components)
66
+ - [Spinner](#spinner)
67
+ - [Progress Bar](#progress-bar)
68
+ - [Streaming Text](#streaming-text)
69
+ - [Custom UI with UIEngine](#custom-ui-with-uiengine)
65
70
  - [Developing](#developing)
66
71
 
67
72
  ## Quick Start
@@ -1243,6 +1248,206 @@ const cli = new CLI(handler, options);
1243
1248
  await cli.run();
1244
1249
  ```
1245
1250
 
1251
+ ## UI Components
1252
+
1253
+ inquirerer includes a set of UI components for building rich terminal interfaces beyond simple prompts. These are useful for showing progress, loading states, and streaming output.
1254
+
1255
+ ### Spinner
1256
+
1257
+ Show an animated spinner while performing async operations:
1258
+
1259
+ ```typescript
1260
+ import { createSpinner } from 'inquirerer';
1261
+
1262
+ const spinner = createSpinner('Loading packages...');
1263
+ spinner.start();
1264
+
1265
+ const data = await fetchPackages();
1266
+
1267
+ spinner.succeed('Loaded 42 packages');
1268
+ // Or: spinner.fail('Failed to load'), spinner.warn('Warning'), spinner.info('Info')
1269
+ ```
1270
+
1271
+ **Spinner styles:**
1272
+
1273
+ ```typescript
1274
+ import { createSpinner, SPINNER_STYLES } from 'inquirerer';
1275
+
1276
+ // Use different spinner styles
1277
+ const spinner = createSpinner('Processing...', {
1278
+ frames: SPINNER_STYLES.dots, // ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏
1279
+ // frames: SPINNER_STYLES.line, // - \ | /
1280
+ // frames: SPINNER_STYLES.arc, // ◜ ◠ ◝ ◞ ◡ ◟
1281
+ // frames: SPINNER_STYLES.circle // ◐ ◓ ◑ ◒
1282
+ });
1283
+ ```
1284
+
1285
+ **Update text while spinning:**
1286
+
1287
+ ```typescript
1288
+ spinner.start();
1289
+ spinner.text('Step 1: Downloading...');
1290
+ await download();
1291
+ spinner.text('Step 2: Installing...');
1292
+ await install();
1293
+ spinner.succeed('Done!');
1294
+ ```
1295
+
1296
+ ### Progress Bar
1297
+
1298
+ Show progress for operations with known completion:
1299
+
1300
+ ```typescript
1301
+ import { createProgress } from 'inquirerer';
1302
+
1303
+ const progress = createProgress('Installing dependencies');
1304
+ progress.start();
1305
+
1306
+ for (let i = 0; i < packages.length; i++) {
1307
+ await installPackage(packages[i]);
1308
+ progress.update((i + 1) / packages.length);
1309
+ }
1310
+
1311
+ progress.complete('All packages installed');
1312
+ // Or: progress.error('Installation failed')
1313
+ ```
1314
+
1315
+ **Increment progress:**
1316
+
1317
+ ```typescript
1318
+ const progress = createProgress('Processing files');
1319
+ progress.start();
1320
+
1321
+ for (const file of files) {
1322
+ await processFile(file);
1323
+ progress.increment(1 / files.length);
1324
+ }
1325
+
1326
+ progress.complete();
1327
+ ```
1328
+
1329
+ ### Streaming Text
1330
+
1331
+ Display streaming output like AI chat responses:
1332
+
1333
+ ```typescript
1334
+ import { createStream } from 'inquirerer';
1335
+
1336
+ const stream = createStream({ showCursor: true });
1337
+ stream.start();
1338
+
1339
+ for await (const token of llmResponse) {
1340
+ stream.append(token);
1341
+ }
1342
+
1343
+ stream.done();
1344
+ ```
1345
+
1346
+ **With line prefix:**
1347
+
1348
+ ```typescript
1349
+ const stream = createStream({ prefix: '> ' });
1350
+ stream.start();
1351
+ stream.appendLine('First line of response');
1352
+ stream.appendLine('Second line of response');
1353
+ stream.done();
1354
+ ```
1355
+
1356
+ ### Custom UI with UIEngine
1357
+
1358
+ For fully custom interactive UIs, use the `UIEngine` directly:
1359
+
1360
+ ```typescript
1361
+ import { UIEngine, Key } from 'inquirerer';
1362
+
1363
+ interface MyState {
1364
+ items: string[];
1365
+ selectedIndex: number;
1366
+ }
1367
+
1368
+ const engine = new UIEngine();
1369
+
1370
+ const result = await engine.run<MyState, string>({
1371
+ initialState: {
1372
+ items: ['Option A', 'Option B', 'Option C'],
1373
+ selectedIndex: 0
1374
+ },
1375
+
1376
+ render: (state) => [
1377
+ 'Select an option:',
1378
+ ...state.items.map((item, i) =>
1379
+ i === state.selectedIndex ? `> ${item}` : ` ${item}`
1380
+ )
1381
+ ],
1382
+
1383
+ onEvent: (event, state) => {
1384
+ if (event.type === 'key') {
1385
+ switch (event.key) {
1386
+ case Key.UP:
1387
+ return {
1388
+ state: {
1389
+ ...state,
1390
+ selectedIndex: Math.max(0, state.selectedIndex - 1)
1391
+ }
1392
+ };
1393
+ case Key.DOWN:
1394
+ return {
1395
+ state: {
1396
+ ...state,
1397
+ selectedIndex: Math.min(state.items.length - 1, state.selectedIndex + 1)
1398
+ }
1399
+ };
1400
+ case Key.ENTER:
1401
+ return {
1402
+ state,
1403
+ done: true,
1404
+ value: state.items[state.selectedIndex]
1405
+ };
1406
+ }
1407
+ }
1408
+ return { state };
1409
+ }
1410
+ });
1411
+
1412
+ console.log('You selected:', result);
1413
+ ```
1414
+
1415
+ **With animations (tick events):**
1416
+
1417
+ ```typescript
1418
+ const engine = new UIEngine();
1419
+
1420
+ await engine.run({
1421
+ initialState: { frame: 0, message: 'Loading' },
1422
+ tickInterval: 100, // Trigger tick event every 100ms
1423
+
1424
+ render: (state) => {
1425
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
1426
+ return [`${frames[state.frame % frames.length]} ${state.message}...`];
1427
+ },
1428
+
1429
+ onEvent: (event, state) => {
1430
+ if (event.type === 'tick') {
1431
+ return { state: { ...state, frame: state.frame + 1 } };
1432
+ }
1433
+ if (event.type === 'key' && event.key === Key.ENTER) {
1434
+ return { state, done: true };
1435
+ }
1436
+ return { state };
1437
+ }
1438
+ });
1439
+ ```
1440
+
1441
+ **Run the demos:**
1442
+
1443
+ ```bash
1444
+ cd packages/inquirerer
1445
+ pnpm dev:spinner # Spinner styles demo
1446
+ pnpm dev:chat # Streaming text demo
1447
+ pnpm dev:upgrade # Interactive upgrade UI demo
1448
+ pnpm dev:prompts # All prompt types demo
1449
+ ```
1450
+
1246
1451
  ---
1247
1452
 
1248
1453
  ## Development
package/esm/index.js CHANGED
@@ -2,3 +2,4 @@ export * from './commander';
2
2
  export * from './prompt';
3
3
  export * from './question';
4
4
  export * from './resolvers';
5
+ export * from './ui';
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Event-driven UI Engine
3
+ *
4
+ * A flexible engine for building custom interactive terminal UIs
5
+ * with support for key events, timers, and async updates.
6
+ */
7
+ import { KEY_CODES, TerminalKeypress } from '../keypress';
8
+ import { Key } from './types';
9
+ /**
10
+ * Maps raw key codes to normalized Key enum
11
+ */
12
+ const KEY_MAP = {
13
+ [KEY_CODES.UP_ARROW]: Key.UP,
14
+ [KEY_CODES.DOWN_ARROW]: Key.DOWN,
15
+ [KEY_CODES.LEFT_ARROW]: Key.LEFT,
16
+ [KEY_CODES.RIGHT_ARROW]: Key.RIGHT,
17
+ [KEY_CODES.ENTER]: Key.ENTER,
18
+ [KEY_CODES.SPACE]: Key.SPACE,
19
+ [KEY_CODES.BACKSPACE]: Key.BACKSPACE,
20
+ [KEY_CODES.BACKSPACE_LEGACY]: Key.BACKSPACE,
21
+ [KEY_CODES.CTRL_C]: Key.CTRL_C,
22
+ '\u001b': Key.ESCAPE,
23
+ '\t': Key.TAB,
24
+ };
25
+ /**
26
+ * ANSI escape codes for terminal control
27
+ */
28
+ const ANSI = {
29
+ clearScreen: '\x1Bc',
30
+ hideCursor: '\x1B[?25l',
31
+ showCursor: '\x1B[?25h',
32
+ cursorUp: (n) => `\x1B[${n}A`,
33
+ cursorDown: (n) => `\x1B[${n}B`,
34
+ cursorTo: (x, y) => `\x1B[${y};${x}H`,
35
+ clearLine: '\x1B[2K',
36
+ clearToEnd: '\x1B[0J',
37
+ saveCursor: '\x1B[s',
38
+ restoreCursor: '\x1B[u',
39
+ };
40
+ export class UIEngine {
41
+ input;
42
+ output;
43
+ noTty;
44
+ keypress = null;
45
+ ownsKeypress;
46
+ clearScreenOnStart;
47
+ tickTimer = null;
48
+ lastLineCount = 0;
49
+ constructor(options = {}) {
50
+ this.input = options.input ?? process.stdin;
51
+ this.output = options.output ?? process.stdout;
52
+ this.noTty = options.noTty ?? false;
53
+ this.keypress = options.keypress ?? null;
54
+ this.ownsKeypress = options.ownsKeypress ?? (options.keypress === undefined);
55
+ this.clearScreenOnStart = options.clearScreenOnStart ?? false;
56
+ }
57
+ /**
58
+ * Write to output
59
+ */
60
+ write(text) {
61
+ this.output.write(text);
62
+ }
63
+ /**
64
+ * Clear the screen
65
+ */
66
+ clearScreen() {
67
+ this.write(ANSI.clearScreen);
68
+ }
69
+ /**
70
+ * Hide the cursor
71
+ */
72
+ hideCursor() {
73
+ this.write(ANSI.hideCursor);
74
+ }
75
+ /**
76
+ * Show the cursor
77
+ */
78
+ showCursor() {
79
+ this.write(ANSI.showCursor);
80
+ }
81
+ /**
82
+ * Render lines to the terminal, clearing previous output
83
+ */
84
+ render(lines) {
85
+ // Move cursor up to overwrite previous output
86
+ if (this.lastLineCount > 0) {
87
+ this.write(ANSI.cursorUp(this.lastLineCount));
88
+ }
89
+ // Clear and write each line
90
+ for (const line of lines) {
91
+ this.write(ANSI.clearLine + line + '\n');
92
+ }
93
+ // Clear any remaining lines from previous render
94
+ if (lines.length < this.lastLineCount) {
95
+ for (let i = 0; i < this.lastLineCount - lines.length; i++) {
96
+ this.write(ANSI.clearLine + '\n');
97
+ }
98
+ // Move cursor back up
99
+ this.write(ANSI.cursorUp(this.lastLineCount - lines.length));
100
+ }
101
+ this.lastLineCount = lines.length;
102
+ }
103
+ /**
104
+ * Run a custom UI screen
105
+ */
106
+ async run(config) {
107
+ if (this.noTty) {
108
+ // In non-TTY mode, just return undefined
109
+ return undefined;
110
+ }
111
+ let state = config.initialState;
112
+ let resolved = false;
113
+ let result;
114
+ const createdKeypress = !this.keypress;
115
+ // Setup keypress handler - reuse existing or create new
116
+ if (!this.keypress) {
117
+ this.keypress = new TerminalKeypress(this.noTty, this.input);
118
+ }
119
+ this.keypress.resume();
120
+ // Clear screen on start if requested (matches legacy prompt behavior)
121
+ if (this.clearScreenOnStart) {
122
+ this.clearScreen();
123
+ }
124
+ // Hide cursor if requested
125
+ if (config.hideCursor) {
126
+ this.hideCursor();
127
+ }
128
+ // Call onStart hook
129
+ config.onStart?.(state);
130
+ // Initial render
131
+ const lines = config.render(state);
132
+ this.render(lines);
133
+ // Setup tick timer if interval specified
134
+ if (config.tickInterval && config.tickInterval > 0) {
135
+ this.tickTimer = setInterval(() => {
136
+ if (resolved)
137
+ return;
138
+ const event = { type: 'tick' };
139
+ const eventResult = config.onEvent(event, state);
140
+ state = eventResult.state;
141
+ this.render(config.render(state));
142
+ if (eventResult.done) {
143
+ resolved = true;
144
+ result = eventResult.value;
145
+ }
146
+ }, config.tickInterval);
147
+ }
148
+ return new Promise((resolve) => {
149
+ const handleEvent = (event) => {
150
+ if (resolved)
151
+ return;
152
+ const eventResult = config.onEvent(event, state);
153
+ state = eventResult.state;
154
+ this.render(config.render(state));
155
+ if (eventResult.done) {
156
+ resolved = true;
157
+ result = eventResult.value;
158
+ cleanup();
159
+ resolve(result);
160
+ }
161
+ };
162
+ const cleanup = () => {
163
+ // Clear tick timer
164
+ if (this.tickTimer) {
165
+ clearInterval(this.tickTimer);
166
+ this.tickTimer = null;
167
+ }
168
+ // Cleanup keypress - pause clears handlers, which is what we want
169
+ // Only destroy if we created it and own it
170
+ if (this.keypress) {
171
+ this.keypress.pause();
172
+ if (createdKeypress && this.ownsKeypress) {
173
+ this.keypress.destroy();
174
+ this.keypress = null;
175
+ }
176
+ }
177
+ // Show cursor
178
+ if (config.hideCursor) {
179
+ this.showCursor();
180
+ }
181
+ // Call onExit hook
182
+ config.onExit?.(state, result);
183
+ };
184
+ // Register key handlers
185
+ // Handle special keys - but let TerminalKeypress handle CTRL+C exit
186
+ Object.entries(KEY_MAP).forEach(([code, key]) => {
187
+ this.keypress.on(code, () => {
188
+ // For CTRL+C, just cleanup - TerminalKeypress will call process.exit
189
+ if (key === Key.CTRL_C) {
190
+ cleanup();
191
+ return;
192
+ }
193
+ handleEvent({ type: 'key', key });
194
+ });
195
+ });
196
+ // Handle alphanumeric characters (lowercase only to match legacy behavior)
197
+ 'abcdefghijklmnopqrstuvwxyz0123456789'.split('').forEach(char => {
198
+ this.keypress.on(char, () => {
199
+ handleEvent({ type: 'char', char });
200
+ });
201
+ });
202
+ // Handle punctuation and special characters
203
+ '!@#$%^&*()_+-=[]{}|;:\'",.<>?/`~'.split('').forEach(char => {
204
+ this.keypress.on(char, () => {
205
+ handleEvent({ type: 'char', char });
206
+ });
207
+ });
208
+ });
209
+ }
210
+ /**
211
+ * Dispatch an external event (for async updates)
212
+ */
213
+ dispatch(event) {
214
+ // This would be used for external event dispatch
215
+ // Implementation depends on how we want to handle async updates
216
+ }
217
+ /**
218
+ * Cleanup resources
219
+ */
220
+ destroy() {
221
+ if (this.tickTimer) {
222
+ clearInterval(this.tickTimer);
223
+ this.tickTimer = null;
224
+ }
225
+ if (this.keypress) {
226
+ this.keypress.destroy();
227
+ this.keypress = null;
228
+ }
229
+ this.showCursor();
230
+ }
231
+ }
232
+ export { ANSI };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * UI Module
3
+ *
4
+ * Event-driven UI components for building rich terminal interfaces
5
+ */
6
+ // Core engine
7
+ export { UIEngine, ANSI } from './engine';
8
+ // Types
9
+ export { Key, } from './types';
10
+ // Components
11
+ export { Spinner, createSpinner, SPINNER_STYLES } from './spinner';
12
+ export { ProgressBar, createProgress } from './progress';
13
+ export { StreamingText, createStream } from './stream';
14
+ export { interactiveUpgrade, upgradePrompt } from './upgrade';
15
+ // Engine-based prompt implementations (internal use)
16
+ export { listPromptEngine, autocompletePromptEngine, checkboxPromptEngine, filterOptions, renderPromptHeader, } from './prompts';
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Progress Bar Component
3
+ *
4
+ * Visual progress indicator for operations with known completion
5
+ */
6
+ import { green, cyan, dim, white } from 'yanse';
7
+ /**
8
+ * Progress bar that can be controlled externally
9
+ */
10
+ export class ProgressBar {
11
+ width;
12
+ showPercentage;
13
+ state;
14
+ output;
15
+ isRunning = false;
16
+ constructor(config, output = process.stdout) {
17
+ this.width = config.width ?? 40;
18
+ this.showPercentage = config.showPercentage ?? true;
19
+ this.output = output;
20
+ this.state = {
21
+ value: 0,
22
+ text: config.text,
23
+ status: 'active',
24
+ };
25
+ }
26
+ /**
27
+ * Start the progress bar
28
+ */
29
+ start() {
30
+ if (this.isRunning)
31
+ return this;
32
+ this.isRunning = true;
33
+ // Hide cursor
34
+ this.output.write('\x1B[?25l');
35
+ // Initial render
36
+ this.render();
37
+ return this;
38
+ }
39
+ /**
40
+ * Update progress (0-1)
41
+ */
42
+ update(value, text) {
43
+ this.state.value = Math.max(0, Math.min(1, value));
44
+ if (text) {
45
+ this.state.text = text;
46
+ }
47
+ if (this.isRunning) {
48
+ this.render();
49
+ }
50
+ return this;
51
+ }
52
+ /**
53
+ * Increment progress
54
+ */
55
+ increment(amount = 0.1) {
56
+ return this.update(this.state.value + amount);
57
+ }
58
+ /**
59
+ * Complete the progress bar
60
+ */
61
+ complete(text) {
62
+ this.state.value = 1;
63
+ this.state.status = 'complete';
64
+ if (text) {
65
+ this.state.text = text;
66
+ }
67
+ this.render();
68
+ // Show cursor and newline
69
+ this.output.write('\x1B[?25h\n');
70
+ this.isRunning = false;
71
+ return this;
72
+ }
73
+ /**
74
+ * Mark as error
75
+ */
76
+ error(text) {
77
+ this.state.status = 'error';
78
+ if (text) {
79
+ this.state.text = text;
80
+ }
81
+ this.render();
82
+ // Show cursor and newline
83
+ this.output.write('\x1B[?25h\n');
84
+ this.isRunning = false;
85
+ return this;
86
+ }
87
+ /**
88
+ * Render the current state
89
+ */
90
+ render() {
91
+ const { value, text, status } = this.state;
92
+ const filled = Math.round(value * this.width);
93
+ const empty = this.width - filled;
94
+ let bar;
95
+ let icon;
96
+ switch (status) {
97
+ case 'complete':
98
+ bar = green('█'.repeat(this.width));
99
+ icon = green('✔');
100
+ break;
101
+ case 'error':
102
+ bar = dim('█'.repeat(filled) + '░'.repeat(empty));
103
+ icon = '\x1B[31m✖\x1B[0m'; // red
104
+ break;
105
+ default:
106
+ bar = cyan('█'.repeat(filled)) + dim('░'.repeat(empty));
107
+ icon = cyan('◐');
108
+ }
109
+ let line = `${icon} ${text} [${bar}]`;
110
+ if (this.showPercentage) {
111
+ const percent = Math.round(value * 100);
112
+ line += ` ${white(percent.toString().padStart(3))}%`;
113
+ }
114
+ // Clear line and write
115
+ this.output.write('\r\x1B[2K' + line);
116
+ }
117
+ }
118
+ /**
119
+ * Create and start a progress bar
120
+ */
121
+ export function createProgress(text, options) {
122
+ return new ProgressBar({ text, ...options });
123
+ }