@inquirer/core 3.1.2 → 4.1.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 (53) hide show
  1. package/dist/cjs/index.js +17 -265
  2. package/dist/cjs/lib/Separator.js +2 -5
  3. package/dist/cjs/lib/create-prompt.js +111 -0
  4. package/dist/cjs/lib/hook-engine.js +100 -0
  5. package/dist/cjs/lib/read-line.type.js +2 -0
  6. package/dist/cjs/lib/screen-manager.js +3 -6
  7. package/dist/cjs/lib/use-effect.js +15 -0
  8. package/dist/cjs/lib/use-keypress.js +20 -0
  9. package/dist/cjs/lib/use-pagination.js +34 -0
  10. package/dist/cjs/lib/{prefix.js → use-prefix.js} +7 -9
  11. package/dist/cjs/lib/use-ref.js +8 -0
  12. package/dist/cjs/lib/use-state.js +28 -0
  13. package/dist/cjs/lib/utils.js +2 -5
  14. package/dist/cjs/types/index.d.ts +9 -36
  15. package/dist/cjs/types/lib/create-prompt.d.ts +11 -0
  16. package/dist/cjs/types/lib/hook-engine.d.ts +24 -0
  17. package/dist/cjs/types/lib/key.d.ts +1 -2
  18. package/dist/cjs/types/lib/read-line.type.d.ts +9 -0
  19. package/dist/cjs/types/lib/screen-manager.d.ts +1 -1
  20. package/dist/cjs/types/lib/use-effect.d.ts +2 -0
  21. package/dist/cjs/types/lib/use-keypress.d.ts +3 -0
  22. package/dist/cjs/types/lib/use-pagination.d.ts +4 -0
  23. package/dist/cjs/types/lib/use-ref.d.ts +3 -0
  24. package/dist/cjs/types/lib/use-state.d.ts +3 -0
  25. package/dist/esm/index.mjs +8 -241
  26. package/dist/esm/lib/create-prompt.mjs +99 -0
  27. package/dist/esm/lib/hook-engine.mjs +91 -0
  28. package/dist/esm/lib/read-line.type.mjs +1 -0
  29. package/dist/esm/lib/use-effect.mjs +11 -0
  30. package/dist/esm/lib/use-keypress.mjs +16 -0
  31. package/dist/esm/lib/use-pagination.mjs +30 -0
  32. package/dist/esm/lib/{prefix.mjs → use-prefix.mjs} +3 -2
  33. package/dist/esm/lib/use-ref.mjs +4 -0
  34. package/dist/esm/lib/use-state.mjs +24 -0
  35. package/dist/esm/lib/utils.mjs +1 -1
  36. package/dist/esm/types/index.d.mts +9 -36
  37. package/dist/esm/types/lib/create-prompt.d.mts +11 -0
  38. package/dist/esm/types/lib/hook-engine.d.mts +24 -0
  39. package/dist/esm/types/lib/key.d.mts +1 -2
  40. package/dist/esm/types/lib/read-line.type.d.mts +9 -0
  41. package/dist/esm/types/lib/screen-manager.d.mts +1 -1
  42. package/dist/esm/types/lib/use-effect.d.mts +2 -0
  43. package/dist/esm/types/lib/use-keypress.d.mts +3 -0
  44. package/dist/esm/types/lib/use-pagination.d.mts +4 -0
  45. package/dist/esm/types/lib/use-ref.d.mts +3 -0
  46. package/dist/esm/types/lib/use-state.d.mts +3 -0
  47. package/package.json +9 -9
  48. package/dist/cjs/lib/options.js +0 -19
  49. package/dist/cjs/types/lib/options.d.ts +0 -2
  50. package/dist/esm/lib/options.mjs +0 -8
  51. package/dist/esm/types/lib/options.d.mts +0 -2
  52. /package/dist/cjs/types/lib/{prefix.d.ts → use-prefix.d.ts} +0 -0
  53. /package/dist/esm/types/lib/{prefix.d.mts → use-prefix.d.mts} +0 -0
@@ -1,10 +1,7 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.breakLines = void 0;
7
- const wrap_ansi_1 = __importDefault(require("wrap-ansi"));
4
+ const wrap_ansi_1 = require("wrap-ansi");
8
5
  /**
9
6
  * Force line returns at specific width. This function is ANSI code friendly and it'll
10
7
  * ignore invisible codes during width calculation.
@@ -16,6 +13,6 @@ const breakLines = (content, width) => content
16
13
  .split('\n')
17
14
  .flatMap((line) => (0, wrap_ansi_1.default)(line, width, { trim: false, hard: true })
18
15
  .split('\n')
19
- .map((line) => line.trimEnd()))
16
+ .map((str) => str.trimEnd()))
20
17
  .join('\n');
21
18
  exports.breakLines = breakLines;
@@ -1,37 +1,10 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import * as readline from 'node:readline';
4
- import { type Prompt } from '@inquirer/type';
5
- import MuteStream from 'mute-stream';
6
- export { usePrefix } from './lib/prefix.js';
7
1
  export * from './lib/key.js';
8
- export * from './lib/Separator.js';
9
- export type InquirerReadline = readline.ReadLine & {
10
- output: MuteStream;
11
- input: NodeJS.ReadableStream;
12
- clearLine: (dir: 0 | 1 | -1) => void;
13
- };
14
- export type KeypressEvent = {
15
- name: string;
16
- ctrl: boolean;
17
- };
18
- type NotFunction<T> = T extends Function ? never : T;
19
- export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
20
- export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: unknown[]): void;
21
- export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
22
- export declare function useRef<Value>(val: Value): {
23
- current: Value;
24
- };
25
- export declare function usePagination(output: string, { active, pageSize, }: {
26
- active: number;
27
- pageSize?: number;
28
- }): string;
29
- export type AsyncPromptConfig = {
30
- message: string | Promise<string> | (() => Promise<string>);
31
- validate?: (value: string) => boolean | string | Promise<string | boolean>;
32
- };
33
- export type ResolvedPromptConfig = {
34
- message: string;
35
- validate: (value: string) => boolean | string | Promise<string | boolean>;
36
- };
37
- export declare function createPrompt<Value, Config extends AsyncPromptConfig>(view: (config: Config & ResolvedPromptConfig, done: (value: Value) => void) => string | [string, string | undefined]): Prompt<Value, Config>;
2
+ export { usePrefix } from './lib/use-prefix.js';
3
+ export { useState } from './lib/use-state.js';
4
+ export { useEffect } from './lib/use-effect.js';
5
+ export { useRef } from './lib/use-ref.js';
6
+ export { useKeypress } from './lib/use-keypress.js';
7
+ export { usePagination } from './lib/use-pagination.js';
8
+ export { createPrompt, type AsyncPromptConfig } from './lib/create-prompt.js';
9
+ export { Separator } from './lib/Separator.js';
10
+ export { type InquirerReadline } from './lib/read-line.type.js';
@@ -0,0 +1,11 @@
1
+ import { type Prompt } from '@inquirer/type';
2
+ export type AsyncPromptConfig = {
3
+ message: string | Promise<string> | (() => Promise<string>);
4
+ validate?: (value: string) => boolean | string | Promise<string | boolean>;
5
+ };
6
+ type ResolvedPromptConfig = {
7
+ message: string;
8
+ validate: (value: string) => boolean | string | Promise<string | boolean>;
9
+ };
10
+ export declare function createPrompt<Value, Config extends AsyncPromptConfig>(view: (config: Config & ResolvedPromptConfig, done: (value: Value) => void) => string | [string, string | undefined]): Prompt<Value, Config>;
11
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { InquirerReadline } from './read-line.type.js';
2
+ type HookStore = {
3
+ rl: InquirerReadline;
4
+ hooks: any[];
5
+ hooksCleanup: Array<void | (() => void)>;
6
+ hooksEffect: Array<() => void>;
7
+ index: number;
8
+ handleChange: () => void;
9
+ };
10
+ type Pointer = {
11
+ get(): any;
12
+ set(value: any): void;
13
+ initialized: boolean;
14
+ };
15
+ export declare function withHooks(rl: InquirerReadline, cb: (store: HookStore) => void): void;
16
+ export declare function readline(): InquirerReadline;
17
+ export declare function withUpdates<T extends (...args: any) => any>(fn: T): (...args: Parameters<T>) => ReturnType<T>;
18
+ export declare function withPointer<Value>(cb: (pointer: Pointer) => Value): Value;
19
+ export declare function handleChange(): void;
20
+ export declare const effectScheduler: {
21
+ queue(cb: (readline: InquirerReadline) => void): void;
22
+ run(): void;
23
+ };
24
+ export {};
@@ -1,4 +1,4 @@
1
- type KeypressEvent = {
1
+ export type KeypressEvent = {
2
2
  name: string;
3
3
  ctrl: boolean;
4
4
  };
@@ -8,4 +8,3 @@ export declare const isSpaceKey: (key: KeypressEvent) => boolean;
8
8
  export declare const isBackspaceKey: (key: KeypressEvent) => boolean;
9
9
  export declare const isNumberKey: (key: KeypressEvent) => boolean;
10
10
  export declare const isEnterKey: (key: KeypressEvent) => boolean;
11
- export {};
@@ -0,0 +1,9 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ import * as readline from 'node:readline';
4
+ import MuteStream from 'mute-stream';
5
+ export type InquirerReadline = readline.ReadLine & {
6
+ output: MuteStream;
7
+ input: NodeJS.ReadableStream;
8
+ clearLine: (dir: 0 | 1 | -1) => void;
9
+ };
@@ -1,4 +1,4 @@
1
- import { InquirerReadline } from '../index.js';
1
+ import type { InquirerReadline } from './read-line.type.js';
2
2
  export default class ScreenManager {
3
3
  private readonly rl;
4
4
  private height;
@@ -0,0 +1,2 @@
1
+ import type { InquirerReadline } from './read-line.type.js';
2
+ export declare function useEffect(cb: (rl: InquirerReadline) => void | (() => void), depArray: unknown[]): void;
@@ -0,0 +1,3 @@
1
+ import { type InquirerReadline } from './read-line.type.js';
2
+ import { type KeypressEvent } from './key.js';
3
+ export declare function useKeypress(userHandler: (event: KeypressEvent, rl: InquirerReadline) => void): void;
@@ -0,0 +1,4 @@
1
+ export declare function usePagination(output: string, { active, pageSize, }: {
2
+ active: number;
3
+ pageSize?: number;
4
+ }): string;
@@ -0,0 +1,3 @@
1
+ export declare function useRef<Value>(val: Value): {
2
+ current: Value;
3
+ };
@@ -0,0 +1,3 @@
1
+ type NotFunction<T> = T extends Function ? never : T;
2
+ export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
3
+ export {};
@@ -1,242 +1,9 @@
1
- import * as readline from 'node:readline';
2
- import { CancelablePromise } from '@inquirer/type';
3
- import chalk from 'chalk';
4
- import cliWidth from 'cli-width';
5
- import MuteStream from 'mute-stream';
6
- import ScreenManager from './lib/screen-manager.mjs';
7
- import { getPromptConfig } from './lib/options.mjs';
8
- import { breakLines } from './lib/utils.mjs';
9
- export { usePrefix } from './lib/prefix.mjs';
10
1
  export * from './lib/key.mjs';
11
- export * from './lib/Separator.mjs';
12
- const hooks = [];
13
- const hooksCleanup = [];
14
- const hooksEffect = [];
15
- let index = 0;
16
- let handleChange = () => { };
17
- let sessionRl;
18
- function resetHookState() {
19
- hooks.length = 0;
20
- hooksCleanup.length = 0;
21
- hooksEffect.length = 0;
22
- index = 0;
23
- handleChange = () => { };
24
- sessionRl = undefined;
25
- }
26
- function mergeStateUpdates(fn) {
27
- const wrapped = (...args) => {
28
- let shouldUpdate = false;
29
- const oldHandleChange = handleChange;
30
- handleChange = () => {
31
- shouldUpdate = true;
32
- };
33
- const returnValue = fn(...args);
34
- if (shouldUpdate) {
35
- oldHandleChange();
36
- }
37
- handleChange = oldHandleChange;
38
- return returnValue;
39
- };
40
- return wrapped;
41
- }
42
- function cleanupHook(index) {
43
- const cleanFn = hooksCleanup[index];
44
- if (typeof cleanFn === 'function') {
45
- cleanFn();
46
- }
47
- }
48
- const runEffects = mergeStateUpdates(() => {
49
- for (const effect of hooksEffect) {
50
- effect();
51
- }
52
- });
53
- export function useState(defaultValue) {
54
- const _idx = index;
55
- index++;
56
- if (!(_idx in hooks)) {
57
- if (typeof defaultValue === 'function') {
58
- hooks[_idx] = defaultValue();
59
- }
60
- else {
61
- hooks[_idx] = defaultValue;
62
- }
63
- }
64
- return [
65
- hooks[_idx],
66
- (newValue) => {
67
- // Noop if the value is still the same.
68
- if (hooks[_idx] !== newValue) {
69
- hooks[_idx] = newValue;
70
- // Trigger re-render
71
- handleChange();
72
- }
73
- },
74
- ];
75
- }
76
- export function useEffect(cb, depArray) {
77
- const rl = sessionRl;
78
- if (!rl) {
79
- throw new Error('useEffect must be used within a prompt');
80
- }
81
- const _idx = index;
82
- index++;
83
- const oldDeps = hooks[_idx];
84
- let hasChanged = true;
85
- if (oldDeps) {
86
- hasChanged = depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
87
- }
88
- if (hasChanged) {
89
- hooksEffect.push(() => {
90
- cleanupHook(_idx);
91
- const cleanFn = cb(rl);
92
- if (cleanFn != null && typeof cleanFn !== 'function') {
93
- throw new Error('useEffect return value must be a cleanup function or nothing.');
94
- }
95
- hooksCleanup[_idx] = cleanFn;
96
- });
97
- }
98
- hooks[_idx] = depArray;
99
- }
100
- export function useKeypress(userHandler) {
101
- const rl = sessionRl;
102
- if (!rl) {
103
- throw new Error('useKeypress must be used within a prompt');
104
- }
105
- useEffect(() => {
106
- const handler = mergeStateUpdates((_input, event) => {
107
- userHandler(event, rl);
108
- });
109
- rl.input.on('keypress', handler);
110
- return () => {
111
- rl.input.removeListener('keypress', handler);
112
- };
113
- }, [userHandler]);
114
- }
115
- export function useRef(val) {
116
- return useState({ current: val })[0];
117
- }
118
- export function usePagination(output, { active, pageSize = 7, }) {
119
- const state = useRef({
120
- pointer: 0,
121
- lastIndex: 0,
122
- });
123
- const rl = sessionRl;
124
- if (!rl) {
125
- throw new Error('usePagination must be used within a prompt');
126
- }
127
- const width = cliWidth({ defaultWidth: 80, output: rl.output });
128
- const lines = breakLines(output, width).split('\n');
129
- // Make sure there's enough lines to paginate
130
- if (lines.length <= pageSize) {
131
- return output;
132
- }
133
- const middleOfList = Math.floor(pageSize / 2);
134
- // Move the pointer only when the user go down and limit it to the middle of the list
135
- const { pointer: prevPointer, lastIndex } = state.current;
136
- if (prevPointer < middleOfList && lastIndex < active && active - lastIndex < pageSize) {
137
- state.current.pointer = Math.min(middleOfList, prevPointer + active - lastIndex);
138
- }
139
- state.current.lastIndex = active;
140
- // Duplicate the lines so it give an infinite list look
141
- const infinite = [lines, lines, lines].flat();
142
- const topIndex = Math.max(0, active + lines.length - state.current.pointer);
143
- const section = infinite.splice(topIndex, pageSize).join('\n');
144
- return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
145
- }
146
- export function createPrompt(view) {
147
- const prompt = (config, context) => {
148
- if (sessionRl) {
149
- throw new Error('An inquirer prompt is already running.\nMake sure you await the result of the previous prompt before calling another prompt.');
150
- }
151
- // Default `input` to stdin
152
- const input = context?.input ?? process.stdin;
153
- // Add mute capabilities to the output
154
- const output = new MuteStream();
155
- output.pipe(context?.output ?? process.stdout);
156
- sessionRl = readline.createInterface({
157
- terminal: true,
158
- input,
159
- output,
160
- });
161
- const screen = new ScreenManager(sessionRl);
162
- let cancel = () => { };
163
- const answer = new CancelablePromise((resolve, reject) => {
164
- const checkCursorPos = () => {
165
- screen.checkCursorPos();
166
- };
167
- const onExit = () => {
168
- try {
169
- let len = hooksCleanup.length;
170
- while (len--) {
171
- cleanupHook(len);
172
- }
173
- }
174
- catch (err) {
175
- reject(err);
176
- }
177
- if (context?.clearPromptOnDone) {
178
- screen.clean();
179
- }
180
- else {
181
- screen.clearContent();
182
- }
183
- screen.done();
184
- process.removeListener('SIGINT', onForceExit);
185
- sessionRl?.input.removeListener('keypress', checkCursorPos);
186
- resetHookState();
187
- };
188
- cancel = () => {
189
- onExit();
190
- reject(new Error('Prompt was canceled'));
191
- };
192
- let shouldHandleExit = true;
193
- const onForceExit = () => {
194
- if (shouldHandleExit) {
195
- shouldHandleExit = false;
196
- onExit();
197
- reject(new Error('User force closed the prompt with CTRL+C'));
198
- }
199
- };
200
- // Handle cleanup on force exit. Main reason is so we restore the cursor if a prompt hide it.
201
- process.on('SIGINT', onForceExit);
202
- const done = (value) => {
203
- // Delay execution to let time to the hookCleanup functions to registers.
204
- setImmediate(() => {
205
- onExit();
206
- // Finally we resolve our promise
207
- resolve(value);
208
- });
209
- };
210
- const workLoop = (resolvedConfig) => {
211
- index = 0;
212
- hooksEffect.length = 0;
213
- handleChange = () => workLoop(resolvedConfig);
214
- try {
215
- const nextView = view(resolvedConfig, done);
216
- const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
217
- screen.render(content, bottomContent);
218
- runEffects();
219
- }
220
- catch (err) {
221
- onExit();
222
- reject(err);
223
- }
224
- };
225
- // TODO: we should display a loader while we get the default options.
226
- getPromptConfig(config).then((resolvedConfig) => {
227
- workLoop(resolvedConfig);
228
- // Re-renders only happen when the state change; but the readline cursor could change position
229
- // and that also requires a re-render (and a manual one because we mute the streams).
230
- // We set the listener after the initial workLoop to avoid a double render if render triggered
231
- // by a state change sets the cursor to the right position.
232
- sessionRl?.input.on('keypress', checkCursorPos);
233
- }, reject);
234
- });
235
- answer.catch(() => {
236
- resetHookState();
237
- });
238
- answer.cancel = cancel;
239
- return answer;
240
- };
241
- return prompt;
242
- }
2
+ export { usePrefix } from './lib/use-prefix.mjs';
3
+ export { useState } from './lib/use-state.mjs';
4
+ export { useEffect } from './lib/use-effect.mjs';
5
+ export { useRef } from './lib/use-ref.mjs';
6
+ export { useKeypress } from './lib/use-keypress.mjs';
7
+ export { usePagination } from './lib/use-pagination.mjs';
8
+ export { createPrompt } from './lib/create-prompt.mjs';
9
+ export { Separator } from './lib/Separator.mjs';
@@ -0,0 +1,99 @@
1
+ import * as readline from 'node:readline';
2
+ import { CancelablePromise } from '@inquirer/type';
3
+ import MuteStream from 'mute-stream';
4
+ import { onExit as onSignalExit } from 'signal-exit';
5
+ import ScreenManager from './screen-manager.mjs';
6
+ import { withHooks, effectScheduler } from './hook-engine.mjs';
7
+ // Take an AsyncPromptConfig and resolves all it's values.
8
+ async function getPromptConfig(config) {
9
+ const message = typeof config.message === 'function' ? config.message() : config.message;
10
+ return {
11
+ validate: () => true,
12
+ ...config,
13
+ message: await message,
14
+ };
15
+ }
16
+ export function createPrompt(view) {
17
+ const prompt = (config, context) => {
18
+ // Default `input` to stdin
19
+ const input = context?.input ?? process.stdin;
20
+ // Add mute capabilities to the output
21
+ const output = new MuteStream();
22
+ output.pipe(context?.output ?? process.stdout);
23
+ const rl = readline.createInterface({
24
+ terminal: true,
25
+ input,
26
+ output,
27
+ });
28
+ const screen = new ScreenManager(rl);
29
+ let cancel = () => { };
30
+ const answer = new CancelablePromise((resolve, reject) => {
31
+ withHooks(rl, (store) => {
32
+ function checkCursorPos() {
33
+ screen.checkCursorPos();
34
+ }
35
+ const removeExitListener = onSignalExit((code, signal) => {
36
+ onExit();
37
+ reject(new Error(`User force closed the prompt with ${code} ${signal}`));
38
+ });
39
+ function onExit() {
40
+ try {
41
+ store.hooksCleanup.forEach((cleanFn) => {
42
+ cleanFn?.();
43
+ });
44
+ }
45
+ catch (err) {
46
+ reject(err);
47
+ }
48
+ if (context?.clearPromptOnDone) {
49
+ screen.clean();
50
+ }
51
+ else {
52
+ screen.clearContent();
53
+ }
54
+ screen.done();
55
+ removeExitListener();
56
+ store.rl.input.removeListener('keypress', checkCursorPos);
57
+ }
58
+ cancel = () => {
59
+ onExit();
60
+ reject(new Error('Prompt was canceled'));
61
+ };
62
+ function done(value) {
63
+ // Delay execution to let time to the hookCleanup functions to registers.
64
+ setImmediate(() => {
65
+ onExit();
66
+ // Finally we resolve our promise
67
+ resolve(value);
68
+ });
69
+ }
70
+ function workLoop(resolvedConfig) {
71
+ store.index = 0;
72
+ store.handleChange = () => workLoop(resolvedConfig);
73
+ try {
74
+ const nextView = view(resolvedConfig, done);
75
+ const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
76
+ screen.render(content, bottomContent);
77
+ effectScheduler.run();
78
+ }
79
+ catch (err) {
80
+ onExit();
81
+ reject(err);
82
+ }
83
+ }
84
+ // TODO: we should display a loader while we get the default options.
85
+ getPromptConfig(config).then((resolvedConfig) => {
86
+ workLoop(resolvedConfig);
87
+ // Re-renders only happen when the state change; but the readline cursor could change position
88
+ // and that also requires a re-render (and a manual one because we mute the streams).
89
+ // We set the listener after the initial workLoop to avoid a double render if render triggered
90
+ // by a state change sets the cursor to the right position.
91
+ store.rl.input.on('keypress', checkCursorPos);
92
+ }, reject);
93
+ });
94
+ });
95
+ answer.cancel = cancel;
96
+ return answer;
97
+ };
98
+ return prompt;
99
+ }
@@ -0,0 +1,91 @@
1
+ import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
2
+ const hookStorage = new AsyncLocalStorage();
3
+ function createStore(rl) {
4
+ const store = {
5
+ rl,
6
+ hooks: [],
7
+ hooksCleanup: [],
8
+ hooksEffect: [],
9
+ index: 0,
10
+ handleChange() { },
11
+ };
12
+ return store;
13
+ }
14
+ // Run callback in with the hook engine setup.
15
+ export function withHooks(rl, cb) {
16
+ const store = createStore(rl);
17
+ return hookStorage.run(store, () => {
18
+ cb(store);
19
+ });
20
+ }
21
+ // Safe getStore utility that'll return the store or throw if undefined.
22
+ function getStore() {
23
+ const store = hookStorage.getStore();
24
+ if (!store) {
25
+ throw new Error('[Inquirer] Hook functions can only be called from within a prompt');
26
+ }
27
+ return store;
28
+ }
29
+ export function readline() {
30
+ return getStore().rl;
31
+ }
32
+ // Merge state updates happening within the callback function to avoid multiple renders.
33
+ export function withUpdates(fn) {
34
+ const wrapped = (...args) => {
35
+ const store = getStore();
36
+ let shouldUpdate = false;
37
+ const oldHandleChange = store.handleChange;
38
+ store.handleChange = () => {
39
+ shouldUpdate = true;
40
+ };
41
+ const returnValue = fn(...args);
42
+ if (shouldUpdate) {
43
+ oldHandleChange();
44
+ }
45
+ store.handleChange = oldHandleChange;
46
+ return returnValue;
47
+ };
48
+ return AsyncResource.bind(wrapped);
49
+ }
50
+ export function withPointer(cb) {
51
+ const store = getStore();
52
+ const { index } = store;
53
+ const pointer = {
54
+ get() {
55
+ return store.hooks[index];
56
+ },
57
+ set(value) {
58
+ store.hooks[index] = value;
59
+ },
60
+ initialized: index in store.hooks,
61
+ };
62
+ const returnValue = cb(pointer);
63
+ store.index++;
64
+ return returnValue;
65
+ }
66
+ export function handleChange() {
67
+ getStore().handleChange();
68
+ }
69
+ export const effectScheduler = {
70
+ queue(cb) {
71
+ const store = getStore();
72
+ const { index } = store;
73
+ store.hooksEffect.push(() => {
74
+ store.hooksCleanup[index]?.();
75
+ const cleanFn = cb(readline());
76
+ if (cleanFn != null && typeof cleanFn !== 'function') {
77
+ throw new Error('useEffect return value must be a cleanup function or nothing.');
78
+ }
79
+ store.hooksCleanup[index] = cleanFn;
80
+ });
81
+ },
82
+ run() {
83
+ const store = getStore();
84
+ withUpdates(() => {
85
+ store.hooksEffect.forEach((effect) => {
86
+ effect();
87
+ });
88
+ })();
89
+ store.hooksEffect.length = 0;
90
+ },
91
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { withPointer, effectScheduler } from './hook-engine.mjs';
2
+ export function useEffect(cb, depArray) {
3
+ withPointer((pointer) => {
4
+ const oldDeps = pointer.get();
5
+ const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
6
+ if (hasChanged) {
7
+ effectScheduler.queue(cb);
8
+ }
9
+ pointer.set(depArray);
10
+ });
11
+ }
@@ -0,0 +1,16 @@
1
+ import { useRef } from './use-ref.mjs';
2
+ import { useEffect } from './use-effect.mjs';
3
+ import { withUpdates } from './hook-engine.mjs';
4
+ export function useKeypress(userHandler) {
5
+ const signal = useRef(userHandler);
6
+ signal.current = userHandler;
7
+ useEffect((rl) => {
8
+ const handler = withUpdates((_input, event) => {
9
+ signal.current(event, rl);
10
+ });
11
+ rl.input.on('keypress', handler);
12
+ return () => {
13
+ rl.input.removeListener('keypress', handler);
14
+ };
15
+ }, []);
16
+ }
@@ -0,0 +1,30 @@
1
+ import chalk from 'chalk';
2
+ import cliWidth from 'cli-width';
3
+ import { breakLines } from './utils.mjs';
4
+ import { readline } from './hook-engine.mjs';
5
+ import { useRef } from './use-ref.mjs';
6
+ export function usePagination(output, { active, pageSize = 7, }) {
7
+ const rl = readline();
8
+ const state = useRef({
9
+ pointer: 0,
10
+ lastIndex: 0,
11
+ });
12
+ const width = cliWidth({ defaultWidth: 80, output: rl.output });
13
+ const lines = breakLines(output, width).split('\n');
14
+ // Make sure there's enough lines to paginate
15
+ if (lines.length <= pageSize) {
16
+ return output;
17
+ }
18
+ const middleOfList = Math.floor(pageSize / 2);
19
+ // Move the pointer only when the user go down and limit it to the middle of the list
20
+ const { pointer: prevPointer, lastIndex } = state.current;
21
+ if (prevPointer < middleOfList && lastIndex < active && active - lastIndex < pageSize) {
22
+ state.current.pointer = Math.min(middleOfList, prevPointer + active - lastIndex);
23
+ }
24
+ state.current.lastIndex = active;
25
+ // Duplicate the lines so it give an infinite list look
26
+ const infinite = [lines, lines, lines].flat();
27
+ const topIndex = Math.max(0, active + lines.length - state.current.pointer);
28
+ const section = infinite.splice(topIndex, pageSize).join('\n');
29
+ return section + '\n' + chalk.dim('(Use arrow keys to reveal more choices)');
30
+ }