@inquirer/core 9.0.7 → 9.0.9

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
@@ -31,116 +31,136 @@ yarn add @inquirer/core
31
31
 
32
32
  # Usage
33
33
 
34
+ ## Basic concept
35
+
36
+ Visual terminal apps are at their core strings rendered onto the terminal.
37
+
38
+ The most basic prompt is a function returning a string that'll be rendered in the terminal. This function will run every time the prompt state change, and the new returned string will replace the previously rendered one. The prompt cursor appears after the string.
39
+
40
+ Wrapping the rendering function with `createPrompt()` will setup the rendering layer, inject the state management utilities, and wait until the `done` callback is called.
41
+
34
42
  ```ts
35
- import colors from 'yoctocolors';
36
- import {
37
- createPrompt,
38
- useState,
39
- useKeypress,
40
- isEnterKey,
41
- usePrefix,
42
- } from '@inquirer/core';
43
+ import { createPrompt } from '@inquirer/core';
43
44
 
44
- const confirm = createPrompt<boolean, { message: string; default?: boolean }>(
45
- (config, done) => {
46
- const [status, setStatus] = useState('pending');
47
- const [value, setValue] = useState('');
48
- const prefix = usePrefix({});
45
+ const input = createPrompt((config, done) => {
46
+ // Implement logic
49
47
 
50
- useKeypress((key, rl) => {
51
- if (isEnterKey(key)) {
52
- const answer = value ? /^y(es)?/i.test(value) : config.default !== false;
53
- setValue(answer ? 'yes' : 'no');
54
- setStatus('done');
55
- done(answer);
56
- } else {
57
- setValue(rl.line);
58
- }
59
- });
48
+ return '? My question';
49
+ });
60
50
 
61
- let formattedValue = value;
62
- let defaultValue = '';
63
- if (status === 'done') {
64
- formattedValue = colors.cyan(value);
65
- } else {
66
- defaultValue = colors.dim(config.default === false ? ' (y/N)' : ' (Y/n)');
67
- }
51
+ // And it is then called as
52
+ const answer = await input({
53
+ /* config */
54
+ });
55
+ ```
68
56
 
69
- const message = colors.bold(config.message);
70
- return `${prefix} ${message}${defaultValue} ${formattedValue}`;
71
- },
72
- );
57
+ ## Hooks
73
58
 
74
- /**
75
- * Which then can be used like this:
76
- */
77
- const answer = await confirm({ message: 'Do you want to continue?' });
59
+ State management and user interactions are handled through hooks. Hooks are common [within the React ecosystem](https://react.dev/reference/react/hooks), and Inquirer reimplement the common ones.
60
+
61
+ ### State hook
62
+
63
+ State lets a component “remember” information like user input. For example, an input prompt can use state to store the input value, while a list prompt can use state to track the cursor index.
64
+
65
+ `useState` declares a state variable that you can update directly.
66
+
67
+ ```ts
68
+ import { createPrompt, useState } from '@inquirer/core';
69
+
70
+ const input = createPrompt((config, done) => {
71
+ const [index, setIndex] = useState(0);
72
+
73
+ // ...
78
74
  ```
79
75
 
80
- See more examples:
76
+ ### Keypress hook
81
77
 
82
- - [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/confirm/src/index.mts)
83
- - [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/input/src/index.mts)
84
- - [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/password/src/index.mts)
85
- - [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/editor/src/index.mts)
86
- - [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/select/src/index.mts)
87
- - [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/checkbox/src/index.mts)
88
- - [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/rawlist/src/index.mts)
89
- - [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/expand/src/index.mts)
78
+ Almost all prompts need to react to user actions. In a terminal, this is done through typing.
90
79
 
91
- ## API
80
+ `useKeypress` allows you to react to keypress events, and access the prompt line.
92
81
 
93
- ### `createPrompt(viewFn)`
82
+ ```ts
83
+ const input = createPrompt((config, done) => {
84
+ useKeypress((key) => {
85
+ if (key.name === 'enter') {
86
+ done(answer);
87
+ }
88
+ });
94
89
 
95
- The `createPrompt` function returns an asynchronous function that returns a cancelable promise resolving to the valid answer a user submit. This prompt function takes the prompt configuration as its first argument (this is defined by each prompt), and the context options as a second argument.
90
+ // ...
91
+ ```
96
92
 
97
- The prompt configuration is unique to each prompt. The context options are:
93
+ Behind the scenes, Inquirer prompts are wrappers around [readlines](https://nodejs.org/api/readline.html). Aside the keypress event object, the hook also pass the active readline instance to the event handler.
98
94
 
99
- | Property | Type | Required | Description |
100
- | ----------------- | ----------------------- | -------- | ------------------------------------------------------------ |
101
- | input | `NodeJS.ReadableStream` | no | The stdin stream (defaults to `process.stdin`) |
102
- | output | `NodeJS.WritableStream` | no | The stdout stream (defaults to `process.stdout`) |
103
- | clearPromptOnDone | `boolean` | no | If true, we'll clear the screen after the prompt is answered |
95
+ ```ts
96
+ const input = createPrompt((config, done) => {
97
+ useKeypress((key, readline) => {
98
+ setValue(readline.line);
99
+ });
104
100
 
105
- The cancelable promise exposes a `cancel` method that'll exit the prompt and reject the promise.
101
+ // ...
102
+ ```
106
103
 
107
- #### Typescript
104
+ ### Ref hook
108
105
 
109
- If using typescript, `createPrompt` takes 2 generic arguments (ex `createPrompt<string, { message: string }>()`)
106
+ Refs let a prompt hold some information that isn’t used for rendering, like a class instance or a timeout ID. Unlike with state, updating a ref does not re-render your prompt. Refs are an “escape hatch” from the rendering paradigm.
110
107
 
111
- The first one is the type of the resolved value; `function createPrompt<Value>(): Promise<Value> {}`
108
+ `useRef` declares a ref. You can hold any value in it, but most often it’s used to hold a timeout ID.
112
109
 
113
- The second one is the type of the prompt config; in other words the interface the created prompt will provide to users.
110
+ ```ts
111
+ const input = createPrompt((config, done) => {
112
+ const timeout = useRef(null);
114
113
 
115
- ### Hooks
114
+ // ...
115
+ ```
116
116
 
117
- Hooks can only be called within the prompt function and are used to handle state and events.
117
+ ### Effect Hook
118
118
 
119
- Those hooks are matching the React hooks API:
119
+ Effects let a prompt connect to and synchronize with external systems. This includes dealing with network or animations.
120
120
 
121
- - `useState`
122
- - `useRef`
123
- - `useEffect`
124
- - `useMemo`
121
+ `useEffect` connects a component to an external system.
125
122
 
126
- And those are custom utilities from Inquirer:
123
+ ```ts
124
+ const chat = createPrompt((config, done) => {
125
+ useEffect(() => {
126
+ const connection = createConnection(roomId);
127
+ connection.connect();
128
+ return () => connection.disconnect();
129
+ }, [roomId]);
130
+
131
+ // ...
132
+ ```
127
133
 
128
- - `useKeypress`
129
- - `usePagination`
130
- - `usePrefix`
134
+ ### Performance hook
131
135
 
132
- ### Key utilities
136
+ A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell Inquirer to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.
133
137
 
134
- Listening for keypress events inside an inquirer prompt is a very common pattern. To ease this, we export a few utility functions taking in the keypress event object and return a boolean:
138
+ `useMemo` lets you cache the result of an expensive calculation.
135
139
 
136
- - `isEnterKey()`
137
- - `isBackspaceKey()`
138
- - `isSpaceKey()`
139
- - `isUpKey()` - Note: this utility will handle vim and emacs keybindings (up, `k`, and `ctrl+p`)
140
- - `isDownKey()` - Note: this utility will handle vim and emacs keybindings (down, `j`, and `ctrl+n`)
141
- - `isNumberKey()` one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
140
+ ```ts
141
+ const todoSelect = createPrompt((config, done) => {
142
+ const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
143
+
144
+ // ...
145
+ ```
146
+
147
+ ### Rendering hooks
148
+
149
+ #### Prefix / loading
142
150
 
143
- ### `usePagination`
151
+ All default prompts, and most custom ones, uses a prefix at the beginning of the prompt line. This helps visually delineate different questions, and provides a convenient area to render a loading spinner.
152
+
153
+ `usePrefix` is a built-in hook to do this.
154
+
155
+ ```ts
156
+ const input = createPrompt((config, done) => {
157
+ const prefix = usePrefix({ isLoading });
158
+
159
+ return `${prefix} My question`;
160
+ });
161
+ ```
162
+
163
+ #### Pagination
144
164
 
145
165
  When looping through a long list of options (like in the `select` prompt), paginating the results appearing on the screen at once can be necessary. The `usePagination` hook is the utility used within the `select` and `checkbox` prompts to cycle through the list of options.
146
166
 
@@ -164,7 +184,71 @@ export default createPrompt((config, done) => {
164
184
  });
165
185
  ```
166
186
 
167
- ### Theming
187
+ ## `createPrompt()` API
188
+
189
+ As we saw earlier, the rendering function should return a string, and eventually call `done` to close the prompt and return the answer.
190
+
191
+ ```ts
192
+ const input = createPrompt((config, done) => {
193
+ const [value, setValue] = useState();
194
+
195
+ useKeypress((key, readline) => {
196
+ if (key.name === 'enter') {
197
+ done(answer);
198
+ } else {
199
+ setValue(readline.line);
200
+ }
201
+ });
202
+
203
+ return `? ${config.message} ${value}`;
204
+ });
205
+ ```
206
+
207
+ The rendering function can also return a tuple of 2 string (`[string, string]`.) The first string represents the prompt. The second one is content to render under the prompt, like an error message. The text input cursor will appear after the first string.
208
+
209
+ ```ts
210
+ const number = createPrompt((config, done) => {
211
+ // Add some logic here
212
+
213
+ return [`? My question ${input}`, `! The input must be a number`];
214
+ });
215
+ ```
216
+
217
+ ### Typescript
218
+
219
+ If using typescript, `createPrompt` takes 2 generic arguments.
220
+
221
+ ```ts
222
+ // createPrompt<Value, Config>
223
+ const input = createPrompt<string, { message: string }>(// ...
224
+ ```
225
+
226
+ The first one is the type of the resolved value
227
+
228
+ ```ts
229
+ const answer: string = await input();
230
+ ```
231
+
232
+ The second one is the type of the prompt config; in other words the interface the created prompt will provide to users.
233
+
234
+ ```ts
235
+ const answer = await input({
236
+ message: 'My question',
237
+ });
238
+ ```
239
+
240
+ ## Key utilities
241
+
242
+ Listening for keypress events inside an inquirer prompt is a very common pattern. To ease this, we export a few utility functions taking in the keypress event object and return a boolean:
243
+
244
+ - `isEnterKey()`
245
+ - `isBackspaceKey()`
246
+ - `isSpaceKey()`
247
+ - `isUpKey()` - Note: this utility will handle vim and emacs keybindings (up, `k`, and `ctrl+p`)
248
+ - `isDownKey()` - Note: this utility will handle vim and emacs keybindings (down, `j`, and `ctrl+n`)
249
+ - `isNumberKey()` one of 1, 2, 3, 4, 5, 6, 7, 8, 9, 0
250
+
251
+ ## Theming
168
252
 
169
253
  Theming utilities will allow you to expose customization of the prompt style. Inquirer also has a few standard theme values shared across all the official prompts.
170
254
 
@@ -233,6 +317,65 @@ type DefaultTheme = {
233
317
  };
234
318
  ```
235
319
 
320
+ # Examples
321
+
322
+ You can refer to any `@inquirer/prompts` prompts for real examples:
323
+
324
+ - [Confirm Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/confirm/src/index.mts)
325
+ - [Input Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/input/src/index.mts)
326
+ - [Password Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/password/src/index.mts)
327
+ - [Editor Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/editor/src/index.mts)
328
+ - [Select Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/select/src/index.mts)
329
+ - [Checkbox Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/checkbox/src/index.mts)
330
+ - [Rawlist Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/rawlist/src/index.mts)
331
+ - [Expand Prompt](https://github.com/SBoudrias/Inquirer.js/blob/main/packages/expand/src/index.mts)
332
+
333
+ ```ts
334
+ import colors from 'yoctocolors';
335
+ import {
336
+ createPrompt,
337
+ useState,
338
+ useKeypress,
339
+ isEnterKey,
340
+ usePrefix,
341
+ } from '@inquirer/core';
342
+
343
+ const confirm = createPrompt<boolean, { message: string; default?: boolean }>(
344
+ (config, done) => {
345
+ const [status, setStatus] = useState('pending');
346
+ const [value, setValue] = useState('');
347
+ const prefix = usePrefix({});
348
+
349
+ useKeypress((key, rl) => {
350
+ if (isEnterKey(key)) {
351
+ const answer = value ? /^y(es)?/i.test(value) : config.default !== false;
352
+ setValue(answer ? 'yes' : 'no');
353
+ setStatus('done');
354
+ done(answer);
355
+ } else {
356
+ setValue(rl.line);
357
+ }
358
+ });
359
+
360
+ let formattedValue = value;
361
+ let defaultValue = '';
362
+ if (status === 'done') {
363
+ formattedValue = colors.cyan(value);
364
+ } else {
365
+ defaultValue = colors.dim(config.default === false ? ' (y/N)' : ' (Y/n)');
366
+ }
367
+
368
+ const message = colors.bold(config.message);
369
+ return `${prefix} ${message}${defaultValue} ${formattedValue}`;
370
+ },
371
+ );
372
+
373
+ /**
374
+ * Which then can be used like this:
375
+ */
376
+ const answer = await confirm({ message: 'Do you want to continue?' });
377
+ ```
378
+
236
379
  # License
237
380
 
238
381
  Copyright (c) 2023 Simon Boudrias (twitter: [@vaxilart](https://twitter.com/Vaxilart))<br/>
@@ -59,23 +59,21 @@ function createPrompt(view) {
59
59
  onExit();
60
60
  reject(new errors_mjs_1.ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
61
61
  });
62
- const onExit = node_async_hooks_1.AsyncResource.bind(() => {
62
+ const hooksCleanup = node_async_hooks_1.AsyncResource.bind(() => {
63
63
  try {
64
64
  hook_engine_mjs_1.effectScheduler.clearAll();
65
65
  }
66
66
  catch (error) {
67
67
  reject(error);
68
68
  }
69
- if (context === null || context === void 0 ? void 0 : context.clearPromptOnDone) {
70
- screen.clean();
71
- }
72
- else {
73
- screen.clearContent();
74
- }
75
- screen.done();
69
+ });
70
+ function onExit() {
71
+ hooksCleanup();
72
+ screen.done({ clearContent: Boolean(context === null || context === void 0 ? void 0 : context.clearPromptOnDone) });
76
73
  removeExitListener();
77
74
  rl.input.removeListener('keypress', checkCursorPos);
78
- });
75
+ rl.removeListener('close', hooksCleanup);
76
+ }
79
77
  cancel = () => {
80
78
  onExit();
81
79
  reject(new errors_mjs_1.CancelPromptError());
@@ -105,6 +103,10 @@ function createPrompt(view) {
105
103
  // We set the listener after the initial workLoop to avoid a double render if render triggered
106
104
  // by a state change sets the cursor to the right position.
107
105
  rl.input.on('keypress', checkCursorPos);
106
+ // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
107
+ // triggers after the process is done (which happens after timeouts are done triggering.)
108
+ // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
109
+ rl.on('close', hooksCleanup);
108
110
  });
109
111
  });
110
112
  answer.cancel = cancel;
@@ -8,6 +8,9 @@ const ansi_escapes_1 = __importDefault(require("ansi-escapes"));
8
8
  const utils_mjs_1 = require('./utils.js');
9
9
  const height = (content) => content.split('\n').length;
10
10
  const lastLine = (content) => { var _a; return (_a = content.split('\n').pop()) !== null && _a !== void 0 ? _a : ''; };
11
+ function cursorDown(n) {
12
+ return n > 0 ? ansi_escapes_1.default.cursorDown(n) : '';
13
+ }
11
14
  class ScreenManager {
12
15
  constructor(rl) {
13
16
  Object.defineProperty(this, "rl", {
@@ -38,10 +41,13 @@ class ScreenManager {
38
41
  this.rl = rl;
39
42
  this.cursorPos = rl.getCursorPos();
40
43
  }
44
+ write(content) {
45
+ this.rl.output.unmute();
46
+ this.rl.output.write(content);
47
+ this.rl.output.mute();
48
+ }
41
49
  render(content, bottomContent = '') {
42
- /**
43
- * Write message to screen and setPrompt to control backspace
44
- */
50
+ // Write message to screen and setPrompt to control backspace
45
51
  const promptLine = lastLine(content);
46
52
  const rawPromptLine = (0, strip_ansi_1.default)(promptLine);
47
53
  // Remove the rl.line from our prompt. We can't rely on the content of
@@ -76,52 +82,28 @@ class ScreenManager {
76
82
  output += ansi_escapes_1.default.cursorUp(bottomContentHeight);
77
83
  // Return cursor to the initial left offset.
78
84
  output += ansi_escapes_1.default.cursorTo(this.cursorPos.cols);
79
- this.clean();
80
- this.rl.output.unmute();
81
85
  /**
82
- * Set up state for next re-rendering
86
+ * Render and store state for future re-rendering
83
87
  */
88
+ this.write(cursorDown(this.extraLinesUnderPrompt) +
89
+ ansi_escapes_1.default.eraseLines(this.height) +
90
+ output);
84
91
  this.extraLinesUnderPrompt = bottomContentHeight;
85
92
  this.height = height(output);
86
- this.rl.output.write(output);
87
- this.rl.output.mute();
88
93
  }
89
94
  checkCursorPos() {
90
95
  const cursorPos = this.rl.getCursorPos();
91
96
  if (cursorPos.cols !== this.cursorPos.cols) {
92
- this.rl.output.unmute();
93
- this.rl.output.write(ansi_escapes_1.default.cursorTo(cursorPos.cols));
94
- this.rl.output.mute();
97
+ this.write(ansi_escapes_1.default.cursorTo(cursorPos.cols));
95
98
  this.cursorPos = cursorPos;
96
99
  }
97
100
  }
98
- clean() {
99
- this.rl.output.unmute();
100
- this.rl.output.write([
101
- this.extraLinesUnderPrompt > 0
102
- ? ansi_escapes_1.default.cursorDown(this.extraLinesUnderPrompt)
103
- : '',
104
- ansi_escapes_1.default.eraseLines(this.height),
105
- ].join(''));
106
- this.extraLinesUnderPrompt = 0;
107
- this.rl.output.mute();
108
- }
109
- clearContent() {
110
- this.rl.output.unmute();
111
- // Reset the cursor at the end of the previously displayed content
112
- this.rl.output.write([
113
- this.extraLinesUnderPrompt > 0
114
- ? ansi_escapes_1.default.cursorDown(this.extraLinesUnderPrompt)
115
- : '',
116
- '\n',
117
- ].join(''));
118
- this.rl.output.mute();
119
- }
120
- done() {
101
+ done({ clearContent }) {
121
102
  this.rl.setPrompt('');
122
- this.rl.output.unmute();
123
- this.rl.output.write(ansi_escapes_1.default.cursorShow);
124
- this.rl.output.end();
103
+ let output = cursorDown(this.extraLinesUnderPrompt);
104
+ output += clearContent ? ansi_escapes_1.default.eraseLines(this.height) : '\n';
105
+ output += ansi_escapes_1.default.cursorShow;
106
+ this.write(output);
125
107
  this.rl.close();
126
108
  }
127
109
  }
@@ -8,11 +8,15 @@ function useKeypress(userHandler) {
8
8
  const signal = (0, use_ref_mjs_1.useRef)(userHandler);
9
9
  signal.current = userHandler;
10
10
  (0, use_effect_mjs_1.useEffect)((rl) => {
11
+ let ignore = false;
11
12
  const handler = (0, hook_engine_mjs_1.withUpdates)((_input, event) => {
12
- signal.current(event, rl);
13
+ if (ignore)
14
+ return;
15
+ void signal.current(event, rl);
13
16
  });
14
17
  rl.input.on('keypress', handler);
15
18
  return () => {
19
+ ignore = true;
16
20
  rl.input.removeListener('keypress', handler);
17
21
  };
18
22
  }, []);
@@ -1,7 +1,7 @@
1
1
  import type { InquirerReadline } from '@inquirer/type';
2
2
  export declare function withHooks(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => void): void;
3
3
  export declare function readline(): InquirerReadline;
4
- export declare function withUpdates<T extends (...args: any) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>;
4
+ export declare function withUpdates<R, T extends (...args: any[]) => R>(fn: T): (...args: Parameters<T>) => R;
5
5
  type SetPointer<Value> = {
6
6
  get(): Value;
7
7
  set(value: Value): void;
@@ -5,9 +5,10 @@ export default class ScreenManager {
5
5
  private extraLinesUnderPrompt;
6
6
  private cursorPos;
7
7
  constructor(rl: InquirerReadline);
8
+ write(content: string): void;
8
9
  render(content: string, bottomContent?: string): void;
9
10
  checkCursorPos(): void;
10
- clean(): void;
11
- clearContent(): void;
12
- done(): void;
11
+ done({ clearContent }: {
12
+ clearContent: boolean;
13
+ }): void;
13
14
  }
@@ -1,3 +1,3 @@
1
1
  import { type InquirerReadline } from '@inquirer/type';
2
2
  import { type KeypressEvent } from './key.js';
3
- export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
3
+ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void | Promise<void>): void;
@@ -1,4 +1,4 @@
1
- type NotFunction<T> = T extends Function ? never : T;
1
+ type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
2
  export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
3
  export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value | undefined) => void];
4
4
  export {};
@@ -29,23 +29,21 @@ export function createPrompt(view) {
29
29
  onExit();
30
30
  reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
31
31
  });
32
- const onExit = AsyncResource.bind(() => {
32
+ const hooksCleanup = AsyncResource.bind(() => {
33
33
  try {
34
34
  effectScheduler.clearAll();
35
35
  }
36
36
  catch (error) {
37
37
  reject(error);
38
38
  }
39
- if (context?.clearPromptOnDone) {
40
- screen.clean();
41
- }
42
- else {
43
- screen.clearContent();
44
- }
45
- screen.done();
39
+ });
40
+ function onExit() {
41
+ hooksCleanup();
42
+ screen.done({ clearContent: Boolean(context?.clearPromptOnDone) });
46
43
  removeExitListener();
47
44
  rl.input.removeListener('keypress', checkCursorPos);
48
- });
45
+ rl.removeListener('close', hooksCleanup);
46
+ }
49
47
  cancel = () => {
50
48
  onExit();
51
49
  reject(new CancelPromptError());
@@ -75,6 +73,10 @@ export function createPrompt(view) {
75
73
  // We set the listener after the initial workLoop to avoid a double render if render triggered
76
74
  // by a state change sets the cursor to the right position.
77
75
  rl.input.on('keypress', checkCursorPos);
76
+ // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
77
+ // triggers after the process is done (which happens after timeouts are done triggering.)
78
+ // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
79
+ rl.on('close', hooksCleanup);
78
80
  });
79
81
  });
80
82
  answer.cancel = cancel;
@@ -3,6 +3,9 @@ import ansiEscapes from 'ansi-escapes';
3
3
  import { breakLines, readlineWidth } from './utils.mjs';
4
4
  const height = (content) => content.split('\n').length;
5
5
  const lastLine = (content) => content.split('\n').pop() ?? '';
6
+ function cursorDown(n) {
7
+ return n > 0 ? ansiEscapes.cursorDown(n) : '';
8
+ }
6
9
  export default class ScreenManager {
7
10
  rl;
8
11
  // These variables are keeping information to allow correct prompt re-rendering
@@ -14,10 +17,13 @@ export default class ScreenManager {
14
17
  this.rl = rl;
15
18
  this.cursorPos = rl.getCursorPos();
16
19
  }
20
+ write(content) {
21
+ this.rl.output.unmute();
22
+ this.rl.output.write(content);
23
+ this.rl.output.mute();
24
+ }
17
25
  render(content, bottomContent = '') {
18
- /**
19
- * Write message to screen and setPrompt to control backspace
20
- */
26
+ // Write message to screen and setPrompt to control backspace
21
27
  const promptLine = lastLine(content);
22
28
  const rawPromptLine = stripAnsi(promptLine);
23
29
  // Remove the rl.line from our prompt. We can't rely on the content of
@@ -52,52 +58,28 @@ export default class ScreenManager {
52
58
  output += ansiEscapes.cursorUp(bottomContentHeight);
53
59
  // Return cursor to the initial left offset.
54
60
  output += ansiEscapes.cursorTo(this.cursorPos.cols);
55
- this.clean();
56
- this.rl.output.unmute();
57
61
  /**
58
- * Set up state for next re-rendering
62
+ * Render and store state for future re-rendering
59
63
  */
64
+ this.write(cursorDown(this.extraLinesUnderPrompt) +
65
+ ansiEscapes.eraseLines(this.height) +
66
+ output);
60
67
  this.extraLinesUnderPrompt = bottomContentHeight;
61
68
  this.height = height(output);
62
- this.rl.output.write(output);
63
- this.rl.output.mute();
64
69
  }
65
70
  checkCursorPos() {
66
71
  const cursorPos = this.rl.getCursorPos();
67
72
  if (cursorPos.cols !== this.cursorPos.cols) {
68
- this.rl.output.unmute();
69
- this.rl.output.write(ansiEscapes.cursorTo(cursorPos.cols));
70
- this.rl.output.mute();
73
+ this.write(ansiEscapes.cursorTo(cursorPos.cols));
71
74
  this.cursorPos = cursorPos;
72
75
  }
73
76
  }
74
- clean() {
75
- this.rl.output.unmute();
76
- this.rl.output.write([
77
- this.extraLinesUnderPrompt > 0
78
- ? ansiEscapes.cursorDown(this.extraLinesUnderPrompt)
79
- : '',
80
- ansiEscapes.eraseLines(this.height),
81
- ].join(''));
82
- this.extraLinesUnderPrompt = 0;
83
- this.rl.output.mute();
84
- }
85
- clearContent() {
86
- this.rl.output.unmute();
87
- // Reset the cursor at the end of the previously displayed content
88
- this.rl.output.write([
89
- this.extraLinesUnderPrompt > 0
90
- ? ansiEscapes.cursorDown(this.extraLinesUnderPrompt)
91
- : '',
92
- '\n',
93
- ].join(''));
94
- this.rl.output.mute();
95
- }
96
- done() {
77
+ done({ clearContent }) {
97
78
  this.rl.setPrompt('');
98
- this.rl.output.unmute();
99
- this.rl.output.write(ansiEscapes.cursorShow);
100
- this.rl.output.end();
79
+ let output = cursorDown(this.extraLinesUnderPrompt);
80
+ output += clearContent ? ansiEscapes.eraseLines(this.height) : '\n';
81
+ output += ansiEscapes.cursorShow;
82
+ this.write(output);
101
83
  this.rl.close();
102
84
  }
103
85
  }
@@ -5,11 +5,15 @@ export function useKeypress(userHandler) {
5
5
  const signal = useRef(userHandler);
6
6
  signal.current = userHandler;
7
7
  useEffect((rl) => {
8
+ let ignore = false;
8
9
  const handler = withUpdates((_input, event) => {
9
- signal.current(event, rl);
10
+ if (ignore)
11
+ return;
12
+ void signal.current(event, rl);
10
13
  });
11
14
  rl.input.on('keypress', handler);
12
15
  return () => {
16
+ ignore = true;
13
17
  rl.input.removeListener('keypress', handler);
14
18
  };
15
19
  }, []);
@@ -1,7 +1,7 @@
1
1
  import type { InquirerReadline } from '@inquirer/type';
2
2
  export declare function withHooks(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => void): void;
3
3
  export declare function readline(): InquirerReadline;
4
- export declare function withUpdates<T extends (...args: any) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>;
4
+ export declare function withUpdates<R, T extends (...args: any[]) => R>(fn: T): (...args: Parameters<T>) => R;
5
5
  type SetPointer<Value> = {
6
6
  get(): Value;
7
7
  set(value: Value): void;
@@ -5,9 +5,10 @@ export default class ScreenManager {
5
5
  private extraLinesUnderPrompt;
6
6
  private cursorPos;
7
7
  constructor(rl: InquirerReadline);
8
+ write(content: string): void;
8
9
  render(content: string, bottomContent?: string): void;
9
10
  checkCursorPos(): void;
10
- clean(): void;
11
- clearContent(): void;
12
- done(): void;
11
+ done({ clearContent }: {
12
+ clearContent: boolean;
13
+ }): void;
13
14
  }
@@ -1,3 +1,3 @@
1
1
  import { type InquirerReadline } from '@inquirer/type';
2
2
  import { type KeypressEvent } from './key.mjs';
3
- export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
3
+ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void | Promise<void>): void;
@@ -1,4 +1,4 @@
1
- type NotFunction<T> = T extends Function ? never : T;
1
+ type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
2
2
  export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
3
  export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value | undefined) => void];
4
4
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inquirer/core",
3
- "version": "9.0.7",
3
+ "version": "9.0.9",
4
4
  "engines": {
5
5
  "node": ">=18"
6
6
  },
@@ -58,9 +58,9 @@
58
58
  "homepage": "https://github.com/SBoudrias/Inquirer.js/blob/main/packages/core/README.md",
59
59
  "dependencies": {
60
60
  "@inquirer/figures": "^1.0.5",
61
- "@inquirer/type": "^1.5.1",
61
+ "@inquirer/type": "^1.5.2",
62
62
  "@types/mute-stream": "^0.0.4",
63
- "@types/node": "^22.0.0",
63
+ "@types/node": "^22.1.0",
64
64
  "@types/wrap-ansi": "^3.0.0",
65
65
  "ansi-escapes": "^4.3.2",
66
66
  "cli-spinners": "^2.9.2",
@@ -72,7 +72,7 @@
72
72
  "yoctocolors-cjs": "^2.1.2"
73
73
  },
74
74
  "devDependencies": {
75
- "@inquirer/testing": "^2.1.30"
75
+ "@inquirer/testing": "^2.1.31"
76
76
  },
77
77
  "scripts": {
78
78
  "tsc": "yarn run tsc:esm && yarn run tsc:cjs",
@@ -96,5 +96,5 @@
96
96
  }
97
97
  },
98
98
  "sideEffects": false,
99
- "gitHead": "b89972b992a65005afd6397b57aa4635010a5ef7"
99
+ "gitHead": "056e26aa6497e0036864d032f9eb8d821de821e7"
100
100
  }