@inquirer/core 11.1.6 → 11.1.8
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/dist/index.d.ts +13 -0
- package/dist/index.js +12 -0
- package/dist/lib/Separator.d.ts +10 -0
- package/dist/lib/Separator.js +21 -0
- package/dist/lib/create-prompt.d.ts +4 -0
- package/dist/lib/create-prompt.js +164 -0
- package/dist/lib/errors.d.ts +20 -0
- package/dist/lib/errors.js +21 -0
- package/dist/lib/hook-engine.d.ts +23 -0
- package/dist/lib/hook-engine.js +111 -0
- package/dist/lib/key.d.ts +14 -0
- package/dist/lib/key.js +20 -0
- package/dist/lib/make-theme.d.ts +3 -0
- package/dist/lib/make-theme.js +32 -0
- package/dist/lib/pagination/use-pagination.d.ts +16 -0
- package/dist/lib/pagination/use-pagination.js +121 -0
- package/dist/lib/promise-polyfill.d.ts +7 -0
- package/dist/lib/promise-polyfill.js +14 -0
- package/dist/lib/screen-manager.d.ts +14 -0
- package/dist/lib/screen-manager.js +79 -0
- package/dist/lib/theme.d.ts +155 -0
- package/dist/lib/theme.js +21 -0
- package/dist/lib/use-effect.d.ts +2 -0
- package/dist/lib/use-effect.js +11 -0
- package/dist/lib/use-keypress.d.ts +3 -0
- package/dist/lib/use-keypress.js +20 -0
- package/dist/lib/use-memo.d.ts +1 -0
- package/dist/lib/use-memo.js +14 -0
- package/dist/lib/use-prefix.d.ts +5 -0
- package/dist/lib/use-prefix.js +35 -0
- package/dist/lib/use-ref.d.ts +6 -0
- package/dist/lib/use-ref.js +4 -0
- package/dist/lib/use-state.d.ts +4 -0
- package/dist/lib/use-state.js +23 -0
- package/dist/lib/utils.d.ts +13 -0
- package/dist/lib/utils.js +25 -0
- package/package.json +7 -7
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { isUpKey, isDownKey, isSpaceKey, isBackspaceKey, isTabKey, isNumberKey, isEnterKey, isShiftKey, type KeypressEvent, type Keybinding, } from './lib/key.ts';
|
|
2
|
+
export * from './lib/errors.ts';
|
|
3
|
+
export { usePrefix } from './lib/use-prefix.ts';
|
|
4
|
+
export { useState } from './lib/use-state.ts';
|
|
5
|
+
export { useEffect } from './lib/use-effect.ts';
|
|
6
|
+
export { useMemo } from './lib/use-memo.ts';
|
|
7
|
+
export { useRef } from './lib/use-ref.ts';
|
|
8
|
+
export { useKeypress } from './lib/use-keypress.ts';
|
|
9
|
+
export { makeTheme } from './lib/make-theme.ts';
|
|
10
|
+
export type { Theme, Status } from './lib/theme.ts';
|
|
11
|
+
export { usePagination } from './lib/pagination/use-pagination.ts';
|
|
12
|
+
export { createPrompt } from './lib/create-prompt.ts';
|
|
13
|
+
export { Separator } from './lib/Separator.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { isUpKey, isDownKey, isSpaceKey, isBackspaceKey, isTabKey, isNumberKey, isEnterKey, isShiftKey, } from "./lib/key.js";
|
|
2
|
+
export * from "./lib/errors.js";
|
|
3
|
+
export { usePrefix } from "./lib/use-prefix.js";
|
|
4
|
+
export { useState } from "./lib/use-state.js";
|
|
5
|
+
export { useEffect } from "./lib/use-effect.js";
|
|
6
|
+
export { useMemo } from "./lib/use-memo.js";
|
|
7
|
+
export { useRef } from "./lib/use-ref.js";
|
|
8
|
+
export { useKeypress } from "./lib/use-keypress.js";
|
|
9
|
+
export { makeTheme } from "./lib/make-theme.js";
|
|
10
|
+
export { usePagination } from "./lib/pagination/use-pagination.js";
|
|
11
|
+
export { createPrompt } from "./lib/create-prompt.js";
|
|
12
|
+
export { Separator } from "./lib/Separator.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import figures from '@inquirer/figures';
|
|
3
|
+
/**
|
|
4
|
+
* Separator object
|
|
5
|
+
* Used to space/separate choices group
|
|
6
|
+
*/
|
|
7
|
+
export class Separator {
|
|
8
|
+
separator = styleText('dim', Array.from({ length: 15 }).join(figures.line));
|
|
9
|
+
type = 'separator';
|
|
10
|
+
constructor(separator) {
|
|
11
|
+
if (separator) {
|
|
12
|
+
this.separator = separator;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
static isSeparator(choice) {
|
|
16
|
+
return Boolean(choice &&
|
|
17
|
+
typeof choice === 'object' &&
|
|
18
|
+
'type' in choice &&
|
|
19
|
+
choice.type === 'separator');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Prompt, type Prettify } from '@inquirer/type';
|
|
2
|
+
type ViewFunction<Value, Config> = (config: Prettify<Config>, done: (value: Value) => void) => string | [string, string | undefined];
|
|
3
|
+
export declare function createPrompt<Value, Config>(view: ViewFunction<Value, Config>): Prompt<Value, Config>;
|
|
4
|
+
export {};
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import * as readline from 'node:readline';
|
|
2
|
+
import { AsyncResource } from 'node:async_hooks';
|
|
3
|
+
import MuteStream from 'mute-stream';
|
|
4
|
+
import { onExit as onSignalExit } from 'signal-exit';
|
|
5
|
+
import ScreenManager from "./screen-manager.js";
|
|
6
|
+
import { PromisePolyfill } from "./promise-polyfill.js";
|
|
7
|
+
import { withHooks, effectScheduler } from "./hook-engine.js";
|
|
8
|
+
import { AbortPromptError, CancelPromptError, ExitPromptError } from "./errors.js";
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
// Capture the real setImmediate at module load time so it works even when test
|
|
11
|
+
// frameworks mock timers with vi.useFakeTimers() or similar.
|
|
12
|
+
const nativeSetImmediate = globalThis.setImmediate;
|
|
13
|
+
function getCallSites() {
|
|
14
|
+
// oxlint-disable-next-line typescript/unbound-method
|
|
15
|
+
const _prepareStackTrace = Error.prepareStackTrace;
|
|
16
|
+
let result = [];
|
|
17
|
+
try {
|
|
18
|
+
Error.prepareStackTrace = (_, callSites) => {
|
|
19
|
+
const callSitesWithoutCurrent = callSites.slice(1);
|
|
20
|
+
result = callSitesWithoutCurrent;
|
|
21
|
+
return callSitesWithoutCurrent;
|
|
22
|
+
};
|
|
23
|
+
// oxlint-disable-next-line no-unused-expressions
|
|
24
|
+
new Error().stack;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
// An error will occur if the Node flag --frozen-intrinsics is used.
|
|
28
|
+
// https://nodejs.org/api/cli.html#--frozen-intrinsics
|
|
29
|
+
return result;
|
|
30
|
+
}
|
|
31
|
+
Error.prepareStackTrace = _prepareStackTrace;
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
export function createPrompt(view) {
|
|
35
|
+
const callSites = getCallSites();
|
|
36
|
+
const prompt = (config, context = {}) => {
|
|
37
|
+
// Default `input` to stdin
|
|
38
|
+
const { input = process.stdin, signal } = context;
|
|
39
|
+
const cleanups = new Set();
|
|
40
|
+
// Add mute capabilities to the output
|
|
41
|
+
const output = new MuteStream();
|
|
42
|
+
output.pipe(context.output ?? process.stdout);
|
|
43
|
+
// Pre-mute the output so that readline doesn't echo stale keystrokes
|
|
44
|
+
// to the terminal before the first render. ScreenManager will unmute/mute
|
|
45
|
+
// the output around each render call as needed.
|
|
46
|
+
output.mute();
|
|
47
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
48
|
+
const rl = readline.createInterface({
|
|
49
|
+
terminal: true,
|
|
50
|
+
input,
|
|
51
|
+
output,
|
|
52
|
+
});
|
|
53
|
+
const screen = new ScreenManager(rl);
|
|
54
|
+
const { promise, resolve, reject } = PromisePolyfill.withResolver();
|
|
55
|
+
const cancel = () => reject(new CancelPromptError());
|
|
56
|
+
if (signal) {
|
|
57
|
+
const abort = () => reject(new AbortPromptError({ cause: signal.reason }));
|
|
58
|
+
if (signal.aborted) {
|
|
59
|
+
abort();
|
|
60
|
+
return Object.assign(promise, { cancel });
|
|
61
|
+
}
|
|
62
|
+
signal.addEventListener('abort', abort);
|
|
63
|
+
cleanups.add(() => signal.removeEventListener('abort', abort));
|
|
64
|
+
}
|
|
65
|
+
cleanups.add(onSignalExit((code, signal) => {
|
|
66
|
+
reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));
|
|
67
|
+
}));
|
|
68
|
+
// SIGINT must be explicitly handled by the prompt so the ExitPromptError can be handled.
|
|
69
|
+
// Otherwise, the prompt will stop and in some scenarios never resolve.
|
|
70
|
+
// Ref issue #1741
|
|
71
|
+
const sigint = () => reject(new ExitPromptError(`User force closed the prompt with SIGINT`));
|
|
72
|
+
rl.on('SIGINT', sigint);
|
|
73
|
+
cleanups.add(() => rl.removeListener('SIGINT', sigint));
|
|
74
|
+
return withHooks(rl, (cycle) => {
|
|
75
|
+
// The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand
|
|
76
|
+
// triggers after the process is done (which happens after timeouts are done triggering.)
|
|
77
|
+
// We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.
|
|
78
|
+
const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll());
|
|
79
|
+
rl.on('close', hooksCleanup);
|
|
80
|
+
cleanups.add(() => rl.removeListener('close', hooksCleanup));
|
|
81
|
+
const startCycle = () => {
|
|
82
|
+
// Re-renders only happen when the state change; but the readline cursor could
|
|
83
|
+
// change position and that also requires a re-render (and a manual one because
|
|
84
|
+
// we mute the streams). We set the listener after the initial workLoop to avoid
|
|
85
|
+
// a double render if render triggered by a state change sets the cursor to the
|
|
86
|
+
// right position.
|
|
87
|
+
const checkCursorPos = () => screen.checkCursorPos();
|
|
88
|
+
rl.input.on('keypress', checkCursorPos);
|
|
89
|
+
cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));
|
|
90
|
+
let pendingDone = null;
|
|
91
|
+
cycle(() => {
|
|
92
|
+
let effectsSettled = false;
|
|
93
|
+
try {
|
|
94
|
+
const nextView = view(config, (value) => {
|
|
95
|
+
if (effectsSettled) {
|
|
96
|
+
// After the cycle completes (async validation path), the "done"
|
|
97
|
+
// render already flushed via setStatus → handleChange, so resolve
|
|
98
|
+
// immediately.
|
|
99
|
+
resolve(value);
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
pendingDone = { value };
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
// Typescript won't allow this, but not all users rely on typescript.
|
|
106
|
+
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
|
107
|
+
if (nextView === undefined) {
|
|
108
|
+
let callerFilename = callSites[1]?.getFileName();
|
|
109
|
+
if (callerFilename && !callerFilename.startsWith('file://')) {
|
|
110
|
+
callerFilename = path.resolve(callerFilename);
|
|
111
|
+
}
|
|
112
|
+
throw new Error(`Prompt functions must return a string.\n at ${callerFilename}`);
|
|
113
|
+
}
|
|
114
|
+
const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;
|
|
115
|
+
screen.render(content, bottomContent);
|
|
116
|
+
effectScheduler.run();
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
reject(error);
|
|
120
|
+
}
|
|
121
|
+
effectsSettled = true;
|
|
122
|
+
if (pendingDone !== null) {
|
|
123
|
+
const { value } = pendingDone;
|
|
124
|
+
pendingDone = null;
|
|
125
|
+
resolve(value);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
};
|
|
129
|
+
// Proper Readable streams (like process.stdin) may have OS-level buffered
|
|
130
|
+
// data that arrives in the poll phase when readline resumes the stream.
|
|
131
|
+
// Deferring the first render by one setImmediate tick (check phase, after
|
|
132
|
+
// poll) lets that stale data flow through readline harmlessly—no keypress
|
|
133
|
+
// handlers are registered yet and the output is muted, so the stale
|
|
134
|
+
// keystrokes are silently discarded.
|
|
135
|
+
// Old-style streams (like MuteStream) have no such buffering, so the
|
|
136
|
+
// render cycle starts immediately.
|
|
137
|
+
//
|
|
138
|
+
// @see https://github.com/SBoudrias/Inquirer.js/issues/1303
|
|
139
|
+
if ('readableFlowing' in input) {
|
|
140
|
+
nativeSetImmediate(startCycle);
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
startCycle();
|
|
144
|
+
}
|
|
145
|
+
return Object.assign(promise
|
|
146
|
+
.then((answer) => {
|
|
147
|
+
effectScheduler.clearAll();
|
|
148
|
+
return answer;
|
|
149
|
+
}, (error) => {
|
|
150
|
+
effectScheduler.clearAll();
|
|
151
|
+
throw error;
|
|
152
|
+
})
|
|
153
|
+
// Wait for the promise to settle, then cleanup.
|
|
154
|
+
.finally(() => {
|
|
155
|
+
cleanups.forEach((cleanup) => cleanup());
|
|
156
|
+
screen.done({ clearContent: Boolean(context.clearPromptOnDone) });
|
|
157
|
+
output.end();
|
|
158
|
+
})
|
|
159
|
+
// Once cleanup is done, let the expose promise resolve/reject to the internal one.
|
|
160
|
+
.then(() => promise), { cancel });
|
|
161
|
+
});
|
|
162
|
+
};
|
|
163
|
+
return prompt;
|
|
164
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare class AbortPromptError extends Error {
|
|
2
|
+
name: string;
|
|
3
|
+
message: string;
|
|
4
|
+
constructor(options?: {
|
|
5
|
+
cause?: unknown;
|
|
6
|
+
});
|
|
7
|
+
}
|
|
8
|
+
export declare class CancelPromptError extends Error {
|
|
9
|
+
name: string;
|
|
10
|
+
message: string;
|
|
11
|
+
}
|
|
12
|
+
export declare class ExitPromptError extends Error {
|
|
13
|
+
name: string;
|
|
14
|
+
}
|
|
15
|
+
export declare class HookError extends Error {
|
|
16
|
+
name: string;
|
|
17
|
+
}
|
|
18
|
+
export declare class ValidationError extends Error {
|
|
19
|
+
name: string;
|
|
20
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export class AbortPromptError extends Error {
|
|
2
|
+
name = 'AbortPromptError';
|
|
3
|
+
message = 'Prompt was aborted';
|
|
4
|
+
constructor(options) {
|
|
5
|
+
super();
|
|
6
|
+
this.cause = options?.cause;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export class CancelPromptError extends Error {
|
|
10
|
+
name = 'CancelPromptError';
|
|
11
|
+
message = 'Prompt was canceled';
|
|
12
|
+
}
|
|
13
|
+
export class ExitPromptError extends Error {
|
|
14
|
+
name = 'ExitPromptError';
|
|
15
|
+
}
|
|
16
|
+
export class HookError extends Error {
|
|
17
|
+
name = 'HookError';
|
|
18
|
+
}
|
|
19
|
+
export class ValidationError extends Error {
|
|
20
|
+
name = 'ValidationError';
|
|
21
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { InquirerReadline } from '@inquirer/type';
|
|
2
|
+
export declare function withHooks<T>(rl: InquirerReadline, cb: (cycle: (render: () => void) => void) => T): T;
|
|
3
|
+
export declare function readline(): InquirerReadline;
|
|
4
|
+
export declare function withUpdates<Args extends unknown[], R>(fn: (...args: Args) => R): (...args: Args) => R;
|
|
5
|
+
type SetPointer<Value> = {
|
|
6
|
+
get(): Value;
|
|
7
|
+
set(value: Value): void;
|
|
8
|
+
initialized: true;
|
|
9
|
+
};
|
|
10
|
+
type UnsetPointer<Value> = {
|
|
11
|
+
get(): void;
|
|
12
|
+
set(value: Value): void;
|
|
13
|
+
initialized: false;
|
|
14
|
+
};
|
|
15
|
+
type Pointer<Value> = SetPointer<Value> | UnsetPointer<Value>;
|
|
16
|
+
export declare function withPointer<Value, ReturnValue>(cb: (pointer: Pointer<Value>) => ReturnValue): ReturnValue;
|
|
17
|
+
export declare function handleChange(): void;
|
|
18
|
+
export declare const effectScheduler: {
|
|
19
|
+
queue(cb: (readline: InquirerReadline) => void | (() => void)): void;
|
|
20
|
+
run(): void;
|
|
21
|
+
clearAll(): void;
|
|
22
|
+
};
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/* eslint @typescript-eslint/no-explicit-any: ["off"] */
|
|
2
|
+
import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';
|
|
3
|
+
import { HookError, ValidationError } from "./errors.js";
|
|
4
|
+
const hookStorage = new AsyncLocalStorage();
|
|
5
|
+
function createStore(rl) {
|
|
6
|
+
const store = {
|
|
7
|
+
rl,
|
|
8
|
+
hooks: [],
|
|
9
|
+
hooksCleanup: [],
|
|
10
|
+
hooksEffect: [],
|
|
11
|
+
index: 0,
|
|
12
|
+
handleChange() { },
|
|
13
|
+
};
|
|
14
|
+
return store;
|
|
15
|
+
}
|
|
16
|
+
// Run callback in with the hook engine setup.
|
|
17
|
+
export function withHooks(rl, cb) {
|
|
18
|
+
const store = createStore(rl);
|
|
19
|
+
return hookStorage.run(store, () => {
|
|
20
|
+
function cycle(render) {
|
|
21
|
+
store.handleChange = () => {
|
|
22
|
+
store.index = 0;
|
|
23
|
+
render();
|
|
24
|
+
};
|
|
25
|
+
store.handleChange();
|
|
26
|
+
}
|
|
27
|
+
return cb(cycle);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
// Safe getStore utility that'll return the store or throw if undefined.
|
|
31
|
+
function getStore() {
|
|
32
|
+
const store = hookStorage.getStore();
|
|
33
|
+
if (!store) {
|
|
34
|
+
throw new HookError('[Inquirer] Hook functions can only be called from within a prompt');
|
|
35
|
+
}
|
|
36
|
+
return store;
|
|
37
|
+
}
|
|
38
|
+
export function readline() {
|
|
39
|
+
return getStore().rl;
|
|
40
|
+
}
|
|
41
|
+
// Merge state updates happening within the callback function to avoid multiple renders.
|
|
42
|
+
export function withUpdates(fn) {
|
|
43
|
+
const wrapped = (...args) => {
|
|
44
|
+
const store = getStore();
|
|
45
|
+
let shouldUpdate = false;
|
|
46
|
+
const oldHandleChange = store.handleChange;
|
|
47
|
+
store.handleChange = () => {
|
|
48
|
+
shouldUpdate = true;
|
|
49
|
+
};
|
|
50
|
+
const returnValue = fn(...args);
|
|
51
|
+
if (shouldUpdate) {
|
|
52
|
+
oldHandleChange();
|
|
53
|
+
}
|
|
54
|
+
store.handleChange = oldHandleChange;
|
|
55
|
+
return returnValue;
|
|
56
|
+
};
|
|
57
|
+
return AsyncResource.bind(wrapped);
|
|
58
|
+
}
|
|
59
|
+
export function withPointer(cb) {
|
|
60
|
+
const store = getStore();
|
|
61
|
+
const { index } = store;
|
|
62
|
+
const pointer = {
|
|
63
|
+
get() {
|
|
64
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
65
|
+
return store.hooks[index];
|
|
66
|
+
},
|
|
67
|
+
set(value) {
|
|
68
|
+
store.hooks[index] = value;
|
|
69
|
+
},
|
|
70
|
+
initialized: index in store.hooks,
|
|
71
|
+
};
|
|
72
|
+
const returnValue = cb(pointer);
|
|
73
|
+
store.index++;
|
|
74
|
+
return returnValue;
|
|
75
|
+
}
|
|
76
|
+
export function handleChange() {
|
|
77
|
+
getStore().handleChange();
|
|
78
|
+
}
|
|
79
|
+
export const effectScheduler = {
|
|
80
|
+
queue(cb) {
|
|
81
|
+
const store = getStore();
|
|
82
|
+
const { index } = store;
|
|
83
|
+
store.hooksEffect.push(() => {
|
|
84
|
+
store.hooksCleanup[index]?.();
|
|
85
|
+
const cleanFn = cb(readline());
|
|
86
|
+
if (cleanFn != null && typeof cleanFn !== 'function') {
|
|
87
|
+
throw new ValidationError('useEffect return value must be a cleanup function or nothing.');
|
|
88
|
+
}
|
|
89
|
+
store.hooksCleanup[index] = cleanFn;
|
|
90
|
+
});
|
|
91
|
+
},
|
|
92
|
+
run() {
|
|
93
|
+
const store = getStore();
|
|
94
|
+
withUpdates(() => {
|
|
95
|
+
store.hooksEffect.forEach((effect) => {
|
|
96
|
+
effect();
|
|
97
|
+
});
|
|
98
|
+
// Warning: Clean the hooks before exiting the `withUpdates` block.
|
|
99
|
+
// Failure to do so means an updates would hit the same effects again.
|
|
100
|
+
store.hooksEffect.length = 0;
|
|
101
|
+
})();
|
|
102
|
+
},
|
|
103
|
+
clearAll() {
|
|
104
|
+
const store = getStore();
|
|
105
|
+
store.hooksCleanup.forEach((cleanFn) => {
|
|
106
|
+
cleanFn?.();
|
|
107
|
+
});
|
|
108
|
+
store.hooksEffect.length = 0;
|
|
109
|
+
store.hooksCleanup.length = 0;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type KeypressEvent = {
|
|
2
|
+
name: string;
|
|
3
|
+
ctrl: boolean;
|
|
4
|
+
shift: boolean;
|
|
5
|
+
};
|
|
6
|
+
export type Keybinding = 'emacs' | 'vim';
|
|
7
|
+
export declare const isUpKey: (key: KeypressEvent, keybindings?: ReadonlyArray<Keybinding>) => boolean;
|
|
8
|
+
export declare const isDownKey: (key: KeypressEvent, keybindings?: ReadonlyArray<Keybinding>) => boolean;
|
|
9
|
+
export declare const isSpaceKey: (key: KeypressEvent) => boolean;
|
|
10
|
+
export declare const isBackspaceKey: (key: KeypressEvent) => boolean;
|
|
11
|
+
export declare const isTabKey: (key: KeypressEvent) => boolean;
|
|
12
|
+
export declare const isNumberKey: (key: KeypressEvent) => boolean;
|
|
13
|
+
export declare const isEnterKey: (key: KeypressEvent) => boolean;
|
|
14
|
+
export declare const isShiftKey: (key: KeypressEvent) => boolean;
|
package/dist/lib/key.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export const isUpKey = (key, keybindings = []) =>
|
|
2
|
+
// The up key
|
|
3
|
+
key.name === 'up' ||
|
|
4
|
+
// Vim keybinding: hjkl keys map to left/down/up/right
|
|
5
|
+
(keybindings.includes('vim') && key.name === 'k') ||
|
|
6
|
+
// Emacs keybinding: Ctrl+P means "previous" in Emacs navigation conventions
|
|
7
|
+
(keybindings.includes('emacs') && key.ctrl && key.name === 'p');
|
|
8
|
+
export const isDownKey = (key, keybindings = []) =>
|
|
9
|
+
// The down key
|
|
10
|
+
key.name === 'down' ||
|
|
11
|
+
// Vim keybinding: hjkl keys map to left/down/up/right
|
|
12
|
+
(keybindings.includes('vim') && key.name === 'j') ||
|
|
13
|
+
// Emacs keybinding: Ctrl+N means "next" in Emacs navigation conventions
|
|
14
|
+
(keybindings.includes('emacs') && key.ctrl && key.name === 'n');
|
|
15
|
+
export const isSpaceKey = (key) => key.name === 'space';
|
|
16
|
+
export const isBackspaceKey = (key) => key.name === 'backspace';
|
|
17
|
+
export const isTabKey = (key) => key.name === 'tab';
|
|
18
|
+
export const isNumberKey = (key) => '1234567890'.includes(key.name);
|
|
19
|
+
export const isEnterKey = (key) => key.name === 'enter' || key.name === 'return';
|
|
20
|
+
export const isShiftKey = (key) => key.shift;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { defaultTheme } from "./theme.js";
|
|
2
|
+
function isPlainObject(value) {
|
|
3
|
+
if (typeof value !== 'object' || value === null)
|
|
4
|
+
return false;
|
|
5
|
+
let proto = value;
|
|
6
|
+
while (Object.getPrototypeOf(proto) !== null) {
|
|
7
|
+
proto = Object.getPrototypeOf(proto);
|
|
8
|
+
}
|
|
9
|
+
return Object.getPrototypeOf(value) === proto;
|
|
10
|
+
}
|
|
11
|
+
function deepMerge(...objects) {
|
|
12
|
+
const output = {};
|
|
13
|
+
for (const obj of objects) {
|
|
14
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
15
|
+
const prevValue = output[key];
|
|
16
|
+
output[key] =
|
|
17
|
+
isPlainObject(prevValue) && isPlainObject(value)
|
|
18
|
+
? deepMerge(prevValue, value)
|
|
19
|
+
: value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
23
|
+
return output;
|
|
24
|
+
}
|
|
25
|
+
export function makeTheme(...themes) {
|
|
26
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
27
|
+
const themesToMerge = [
|
|
28
|
+
defaultTheme,
|
|
29
|
+
...themes.filter((theme) => theme != null),
|
|
30
|
+
];
|
|
31
|
+
return deepMerge(...themesToMerge);
|
|
32
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Prettify } from '@inquirer/type';
|
|
2
|
+
export declare function usePagination<T>({ items, active, renderItem, pageSize, loop, }: {
|
|
3
|
+
items: ReadonlyArray<T>;
|
|
4
|
+
/** The index of the active item. */
|
|
5
|
+
active: number;
|
|
6
|
+
/** Renders an item as part of a page. */
|
|
7
|
+
renderItem: (layout: Prettify<{
|
|
8
|
+
item: T;
|
|
9
|
+
index: number;
|
|
10
|
+
isActive: boolean;
|
|
11
|
+
}>) => string;
|
|
12
|
+
/** The size of the page. */
|
|
13
|
+
pageSize: number;
|
|
14
|
+
/** Allows creating an infinitely looping list. `true` if unspecified. */
|
|
15
|
+
loop?: boolean;
|
|
16
|
+
}): string;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { useRef } from "../use-ref.js";
|
|
2
|
+
import { readlineWidth, breakLines } from "../utils.js";
|
|
3
|
+
function usePointerPosition({ active, renderedItems, pageSize, loop, }) {
|
|
4
|
+
const state = useRef({
|
|
5
|
+
lastPointer: active,
|
|
6
|
+
lastActive: undefined,
|
|
7
|
+
});
|
|
8
|
+
const { lastPointer, lastActive } = state.current;
|
|
9
|
+
const middle = Math.floor(pageSize / 2);
|
|
10
|
+
const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
|
|
11
|
+
const defaultPointerPosition = renderedItems
|
|
12
|
+
.slice(0, active)
|
|
13
|
+
.reduce((acc, item) => acc + item.length, 0);
|
|
14
|
+
let pointer = defaultPointerPosition;
|
|
15
|
+
if (renderedLength > pageSize) {
|
|
16
|
+
if (loop) {
|
|
17
|
+
/**
|
|
18
|
+
* Creates the next position for the pointer considering an infinitely
|
|
19
|
+
* looping list of items to be rendered on the page.
|
|
20
|
+
*
|
|
21
|
+
* The goal is to progressively move the cursor to the middle position as the user move down, and then keep
|
|
22
|
+
* the cursor there. When the user move up, maintain the cursor position.
|
|
23
|
+
*/
|
|
24
|
+
// By default, keep the cursor position as-is.
|
|
25
|
+
pointer = lastPointer;
|
|
26
|
+
if (
|
|
27
|
+
// First render, skip this logic.
|
|
28
|
+
lastActive != null &&
|
|
29
|
+
// Only move the pointer down when the user moves down.
|
|
30
|
+
lastActive < active &&
|
|
31
|
+
// Check user didn't move up across page boundary.
|
|
32
|
+
active - lastActive < pageSize) {
|
|
33
|
+
pointer = Math.min(
|
|
34
|
+
// Furthest allowed position for the pointer is the middle of the list
|
|
35
|
+
middle, Math.abs(active - lastActive) === 1
|
|
36
|
+
? Math.min(
|
|
37
|
+
// Move the pointer at most the height of the last active item.
|
|
38
|
+
lastPointer + (renderedItems[lastActive]?.length ?? 0),
|
|
39
|
+
// If the user moved by one item, move the pointer to the natural position of the active item as
|
|
40
|
+
// long as it doesn't move the cursor up.
|
|
41
|
+
Math.max(defaultPointerPosition, lastPointer))
|
|
42
|
+
: // Otherwise, move the pointer down by the difference between the active and last active item.
|
|
43
|
+
lastPointer + active - lastActive);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
/**
|
|
48
|
+
* Creates the next position for the pointer considering a finite list of
|
|
49
|
+
* items to be rendered on a page.
|
|
50
|
+
*
|
|
51
|
+
* The goal is to keep the pointer in the middle of the page whenever possible, until
|
|
52
|
+
* we reach the bounds of the list (top or bottom). In which case, the cursor moves progressively
|
|
53
|
+
* to the bottom or top of the list.
|
|
54
|
+
*/
|
|
55
|
+
const spaceUnderActive = renderedItems
|
|
56
|
+
.slice(active)
|
|
57
|
+
.reduce((acc, item) => acc + item.length, 0);
|
|
58
|
+
pointer =
|
|
59
|
+
spaceUnderActive < pageSize - middle
|
|
60
|
+
? // If the active item is near the end of the list, progressively move the cursor towards the end.
|
|
61
|
+
pageSize - spaceUnderActive
|
|
62
|
+
: // Otherwise, progressively move the pointer to the middle of the list.
|
|
63
|
+
Math.min(defaultPointerPosition, middle);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Save state for the next render
|
|
67
|
+
state.current.lastPointer = pointer;
|
|
68
|
+
state.current.lastActive = active;
|
|
69
|
+
return pointer;
|
|
70
|
+
}
|
|
71
|
+
export function usePagination({ items, active, renderItem, pageSize, loop = true, }) {
|
|
72
|
+
const width = readlineWidth();
|
|
73
|
+
const bound = (num) => ((num % items.length) + items.length) % items.length;
|
|
74
|
+
const renderedItems = items.map((item, index) => {
|
|
75
|
+
if (item == null)
|
|
76
|
+
return [];
|
|
77
|
+
return breakLines(renderItem({ item, index, isActive: index === active }), width).split('\n');
|
|
78
|
+
});
|
|
79
|
+
const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);
|
|
80
|
+
const renderItemAtIndex = (index) => renderedItems[index] ?? [];
|
|
81
|
+
const pointer = usePointerPosition({ active, renderedItems, pageSize, loop });
|
|
82
|
+
// Render the active item to decide the position.
|
|
83
|
+
// If the active item fits under the pointer, we render it there.
|
|
84
|
+
// Otherwise, we need to render it to fit at the bottom of the page; moving the pointer up.
|
|
85
|
+
const activeItem = renderItemAtIndex(active).slice(0, pageSize);
|
|
86
|
+
const activeItemPosition = pointer + activeItem.length <= pageSize ? pointer : pageSize - activeItem.length;
|
|
87
|
+
// Create an array of lines for the page, and add the lines of the active item into the page
|
|
88
|
+
const pageBuffer = Array.from({ length: pageSize });
|
|
89
|
+
pageBuffer.splice(activeItemPosition, activeItem.length, ...activeItem);
|
|
90
|
+
// Store to prevent rendering the same item twice
|
|
91
|
+
const itemVisited = new Set([active]);
|
|
92
|
+
// Fill the page under the active item
|
|
93
|
+
let bufferPointer = activeItemPosition + activeItem.length;
|
|
94
|
+
let itemPointer = bound(active + 1);
|
|
95
|
+
while (bufferPointer < pageSize &&
|
|
96
|
+
!itemVisited.has(itemPointer) &&
|
|
97
|
+
(loop && renderedLength > pageSize ? itemPointer !== active : itemPointer > active)) {
|
|
98
|
+
const lines = renderItemAtIndex(itemPointer);
|
|
99
|
+
const linesToAdd = lines.slice(0, pageSize - bufferPointer);
|
|
100
|
+
pageBuffer.splice(bufferPointer, linesToAdd.length, ...linesToAdd);
|
|
101
|
+
// Move pointers for next iteration
|
|
102
|
+
itemVisited.add(itemPointer);
|
|
103
|
+
bufferPointer += linesToAdd.length;
|
|
104
|
+
itemPointer = bound(itemPointer + 1);
|
|
105
|
+
}
|
|
106
|
+
// Fill the page over the active item
|
|
107
|
+
bufferPointer = activeItemPosition - 1;
|
|
108
|
+
itemPointer = bound(active - 1);
|
|
109
|
+
while (bufferPointer >= 0 &&
|
|
110
|
+
!itemVisited.has(itemPointer) &&
|
|
111
|
+
(loop && renderedLength > pageSize ? itemPointer !== active : itemPointer < active)) {
|
|
112
|
+
const lines = renderItemAtIndex(itemPointer);
|
|
113
|
+
const linesToAdd = lines.slice(Math.max(0, lines.length - bufferPointer - 1));
|
|
114
|
+
pageBuffer.splice(bufferPointer - linesToAdd.length + 1, linesToAdd.length, ...linesToAdd);
|
|
115
|
+
// Move pointers for next iteration
|
|
116
|
+
itemVisited.add(itemPointer);
|
|
117
|
+
bufferPointer -= linesToAdd.length;
|
|
118
|
+
itemPointer = bound(itemPointer - 1);
|
|
119
|
+
}
|
|
120
|
+
return pageBuffer.filter((line) => typeof line === 'string').join('\n');
|
|
121
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// TODO: Remove this class once Node 22 becomes the minimum supported version.
|
|
2
|
+
export class PromisePolyfill extends Promise {
|
|
3
|
+
// Available starting from Node 22
|
|
4
|
+
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers
|
|
5
|
+
static withResolver() {
|
|
6
|
+
let resolve;
|
|
7
|
+
let reject;
|
|
8
|
+
const promise = new Promise((res, rej) => {
|
|
9
|
+
resolve = res;
|
|
10
|
+
reject = rej;
|
|
11
|
+
});
|
|
12
|
+
return { promise, resolve: resolve, reject: reject };
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { InquirerReadline } from '@inquirer/type';
|
|
2
|
+
export default class ScreenManager {
|
|
3
|
+
private height;
|
|
4
|
+
private extraLinesUnderPrompt;
|
|
5
|
+
private cursorPos;
|
|
6
|
+
private readonly rl;
|
|
7
|
+
constructor(rl: InquirerReadline);
|
|
8
|
+
write(content: string): void;
|
|
9
|
+
render(content: string, bottomContent?: string): void;
|
|
10
|
+
checkCursorPos(): void;
|
|
11
|
+
done({ clearContent }: {
|
|
12
|
+
clearContent: boolean;
|
|
13
|
+
}): void;
|
|
14
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { stripVTControlCharacters } from 'node:util';
|
|
2
|
+
import { breakLines, readlineWidth } from "./utils.js";
|
|
3
|
+
import { cursorDown, cursorUp, cursorTo, cursorShow, eraseLines } from '@inquirer/ansi';
|
|
4
|
+
const height = (content) => content.split('\n').length;
|
|
5
|
+
const lastLine = (content) => content.split('\n').pop() ?? '';
|
|
6
|
+
export default class ScreenManager {
|
|
7
|
+
// These variables are keeping information to allow correct prompt re-rendering
|
|
8
|
+
height = 0;
|
|
9
|
+
extraLinesUnderPrompt = 0;
|
|
10
|
+
cursorPos;
|
|
11
|
+
rl;
|
|
12
|
+
constructor(rl) {
|
|
13
|
+
this.rl = rl;
|
|
14
|
+
this.cursorPos = rl.getCursorPos();
|
|
15
|
+
}
|
|
16
|
+
write(content) {
|
|
17
|
+
this.rl.output.unmute();
|
|
18
|
+
this.rl.output.write(content);
|
|
19
|
+
this.rl.output.mute();
|
|
20
|
+
}
|
|
21
|
+
render(content, bottomContent = '') {
|
|
22
|
+
// Write message to screen and setPrompt to control backspace
|
|
23
|
+
const promptLine = lastLine(content);
|
|
24
|
+
const rawPromptLine = stripVTControlCharacters(promptLine);
|
|
25
|
+
// Remove the rl.line from our prompt. We can't rely on the content of
|
|
26
|
+
// rl.line (mainly because of the password prompt), so just rely on it's
|
|
27
|
+
// length.
|
|
28
|
+
let prompt = rawPromptLine;
|
|
29
|
+
if (this.rl.line.length > 0) {
|
|
30
|
+
prompt = prompt.slice(0, -this.rl.line.length);
|
|
31
|
+
}
|
|
32
|
+
this.rl.setPrompt(prompt);
|
|
33
|
+
// SetPrompt will change cursor position, now we can get correct value
|
|
34
|
+
this.cursorPos = this.rl.getCursorPos();
|
|
35
|
+
const width = readlineWidth();
|
|
36
|
+
content = breakLines(content, width);
|
|
37
|
+
bottomContent = breakLines(bottomContent, width);
|
|
38
|
+
// Manually insert an extra line if we're at the end of the line.
|
|
39
|
+
// This prevent the cursor from appearing at the beginning of the
|
|
40
|
+
// current line.
|
|
41
|
+
if (rawPromptLine.length % width === 0) {
|
|
42
|
+
content += '\n';
|
|
43
|
+
}
|
|
44
|
+
let output = content + (bottomContent ? '\n' + bottomContent : '');
|
|
45
|
+
/**
|
|
46
|
+
* Re-adjust the cursor at the correct position.
|
|
47
|
+
*/
|
|
48
|
+
// We need to consider parts of the prompt under the cursor as part of the bottom
|
|
49
|
+
// content in order to correctly cleanup and re-render.
|
|
50
|
+
const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows;
|
|
51
|
+
const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
|
|
52
|
+
// Return cursor to the input position (on top of the bottomContent)
|
|
53
|
+
if (bottomContentHeight > 0)
|
|
54
|
+
output += cursorUp(bottomContentHeight);
|
|
55
|
+
// Return cursor to the initial left offset.
|
|
56
|
+
output += cursorTo(this.cursorPos.cols);
|
|
57
|
+
/**
|
|
58
|
+
* Render and store state for future re-rendering
|
|
59
|
+
*/
|
|
60
|
+
this.write(cursorDown(this.extraLinesUnderPrompt) + eraseLines(this.height) + output);
|
|
61
|
+
this.extraLinesUnderPrompt = bottomContentHeight;
|
|
62
|
+
this.height = height(output);
|
|
63
|
+
}
|
|
64
|
+
checkCursorPos() {
|
|
65
|
+
const cursorPos = this.rl.getCursorPos();
|
|
66
|
+
if (cursorPos.cols !== this.cursorPos.cols) {
|
|
67
|
+
this.write(cursorTo(cursorPos.cols));
|
|
68
|
+
this.cursorPos = cursorPos;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
done({ clearContent }) {
|
|
72
|
+
this.rl.setPrompt('');
|
|
73
|
+
let output = cursorDown(this.extraLinesUnderPrompt);
|
|
74
|
+
output += clearContent ? eraseLines(this.height) : '\n';
|
|
75
|
+
output += cursorShow;
|
|
76
|
+
this.write(output);
|
|
77
|
+
this.rl.close();
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { Prettify } from '@inquirer/type';
|
|
2
|
+
/**
|
|
3
|
+
* Union type representing the possible statuses of a prompt.
|
|
4
|
+
*
|
|
5
|
+
* - `'loading'`: The prompt is currently loading.
|
|
6
|
+
* - `'idle'`: The prompt is loaded and currently waiting for the user to
|
|
7
|
+
* submit an answer.
|
|
8
|
+
* - `'done'`: The user has submitted an answer and the prompt is finished.
|
|
9
|
+
* - `string`: Any other string: The prompt is in a custom state.
|
|
10
|
+
*/
|
|
11
|
+
export type Status = 'loading' | 'idle' | 'done' | (string & {});
|
|
12
|
+
type DefaultTheme = {
|
|
13
|
+
/**
|
|
14
|
+
* Prefix to prepend to the message. If a function is provided, it will be
|
|
15
|
+
* called with the current status of the prompt, and the return value will be
|
|
16
|
+
* used as the prefix.
|
|
17
|
+
*
|
|
18
|
+
* @remarks
|
|
19
|
+
* If `status === 'loading'`, this property is ignored and the spinner (styled
|
|
20
|
+
* by the `spinner` property) will be displayed instead.
|
|
21
|
+
*
|
|
22
|
+
* @defaultValue
|
|
23
|
+
* ```ts
|
|
24
|
+
* // import { styleText } from 'node:util';
|
|
25
|
+
* (status) => status === 'done' ? styleText('green', '✔') : styleText('blue', '?')
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
prefix: string | Prettify<Omit<Record<Status, string>, 'loading'>>;
|
|
29
|
+
/**
|
|
30
|
+
* Configuration for the spinner that is displayed when the prompt is in the
|
|
31
|
+
* `'loading'` state.
|
|
32
|
+
*
|
|
33
|
+
* We recommend the use of {@link https://github.com/sindresorhus/cli-spinners|cli-spinners} for a list of available spinners.
|
|
34
|
+
*/
|
|
35
|
+
spinner: {
|
|
36
|
+
/**
|
|
37
|
+
* The time interval between frames, in milliseconds.
|
|
38
|
+
*
|
|
39
|
+
* @defaultValue
|
|
40
|
+
* ```ts
|
|
41
|
+
* 80
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
interval: number;
|
|
45
|
+
/**
|
|
46
|
+
* A list of frames to show for the spinner.
|
|
47
|
+
*
|
|
48
|
+
* @defaultValue
|
|
49
|
+
* ```ts
|
|
50
|
+
* ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
frames: string[];
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Object containing functions to style different parts of the prompt.
|
|
57
|
+
*/
|
|
58
|
+
style: {
|
|
59
|
+
/**
|
|
60
|
+
* Style to apply to the user's answer once it has been submitted.
|
|
61
|
+
*
|
|
62
|
+
* @param text - The user's answer.
|
|
63
|
+
* @returns The styled answer.
|
|
64
|
+
*
|
|
65
|
+
* @defaultValue
|
|
66
|
+
* ```ts
|
|
67
|
+
* // import { styleText } from 'node:util';
|
|
68
|
+
* (text) => styleText('cyan', text)
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
answer: (text: string) => string;
|
|
72
|
+
/**
|
|
73
|
+
* Style to apply to the message displayed to the user.
|
|
74
|
+
*
|
|
75
|
+
* @param text - The message to style.
|
|
76
|
+
* @param status - The current status of the prompt.
|
|
77
|
+
* @returns The styled message.
|
|
78
|
+
*
|
|
79
|
+
* @defaultValue
|
|
80
|
+
* ```ts
|
|
81
|
+
* // import { styleText } from 'node:util';
|
|
82
|
+
* (text, status) => styleText('bold', text)
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
message: (text: string, status: Status) => string;
|
|
86
|
+
/**
|
|
87
|
+
* Style to apply to error messages.
|
|
88
|
+
*
|
|
89
|
+
* @param text - The error message.
|
|
90
|
+
* @returns The styled error message.
|
|
91
|
+
*
|
|
92
|
+
* @defaultValue
|
|
93
|
+
* ```ts
|
|
94
|
+
* // import { styleText } from 'node:util';
|
|
95
|
+
* (text) => styleText('red', `> ${text}`)
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
error: (text: string) => string;
|
|
99
|
+
/**
|
|
100
|
+
* Style to apply to the default answer when one is provided.
|
|
101
|
+
*
|
|
102
|
+
* @param text - The default answer.
|
|
103
|
+
* @returns The styled default answer.
|
|
104
|
+
*
|
|
105
|
+
* @defaultValue
|
|
106
|
+
* ```ts
|
|
107
|
+
* // import { styleText } from 'node:util';
|
|
108
|
+
* (text) => styleText('dim', `(${text})`)
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
defaultAnswer: (text: string) => string;
|
|
112
|
+
/**
|
|
113
|
+
* Style to apply to help text.
|
|
114
|
+
*
|
|
115
|
+
* @param text - The help text.
|
|
116
|
+
* @returns The styled help text.
|
|
117
|
+
*
|
|
118
|
+
* @defaultValue
|
|
119
|
+
* ```ts
|
|
120
|
+
* // import { styleText } from 'node:util';
|
|
121
|
+
* (text) => styleText('dim', text)
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
help: (text: string) => string;
|
|
125
|
+
/**
|
|
126
|
+
* Style to apply to highlighted text.
|
|
127
|
+
*
|
|
128
|
+
* @param text - The text to highlight.
|
|
129
|
+
* @returns The highlighted text.
|
|
130
|
+
*
|
|
131
|
+
* @defaultValue
|
|
132
|
+
* ```ts
|
|
133
|
+
* // import { styleText } from 'node:util';
|
|
134
|
+
* (text) => styleText('cyan', text)
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
highlight: (text: string) => string;
|
|
138
|
+
/**
|
|
139
|
+
* Style to apply to keyboard keys referred to in help texts.
|
|
140
|
+
*
|
|
141
|
+
* @param text - The key to style.
|
|
142
|
+
* @returns The styled key.
|
|
143
|
+
*
|
|
144
|
+
* @defaultValue
|
|
145
|
+
* ```ts
|
|
146
|
+
* // import { styleText } from 'node:util';
|
|
147
|
+
* (text) => styleText('cyan', styleText('bold', `<${text}>`))
|
|
148
|
+
* ```
|
|
149
|
+
*/
|
|
150
|
+
key: (text: string) => string;
|
|
151
|
+
};
|
|
152
|
+
};
|
|
153
|
+
export type Theme<Extension extends object = object> = Prettify<Extension & DefaultTheme>;
|
|
154
|
+
export declare const defaultTheme: DefaultTheme;
|
|
155
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { styleText } from 'node:util';
|
|
2
|
+
import figures from '@inquirer/figures';
|
|
3
|
+
export const defaultTheme = {
|
|
4
|
+
prefix: {
|
|
5
|
+
idle: styleText('blue', '?'),
|
|
6
|
+
done: styleText('green', figures.tick),
|
|
7
|
+
},
|
|
8
|
+
spinner: {
|
|
9
|
+
interval: 80,
|
|
10
|
+
frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => styleText('yellow', frame)),
|
|
11
|
+
},
|
|
12
|
+
style: {
|
|
13
|
+
answer: (text) => styleText('cyan', text),
|
|
14
|
+
message: (text) => styleText('bold', text),
|
|
15
|
+
error: (text) => styleText('red', `> ${text}`),
|
|
16
|
+
defaultAnswer: (text) => styleText('dim', `(${text})`),
|
|
17
|
+
help: (text) => styleText('dim', text),
|
|
18
|
+
highlight: (text) => styleText('cyan', text),
|
|
19
|
+
key: (text) => styleText('cyan', styleText('bold', `<${text}>`)),
|
|
20
|
+
},
|
|
21
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { withPointer, effectScheduler } from "./hook-engine.js";
|
|
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,20 @@
|
|
|
1
|
+
import { useRef } from "./use-ref.js";
|
|
2
|
+
import { useEffect } from "./use-effect.js";
|
|
3
|
+
import { withUpdates } from "./hook-engine.js";
|
|
4
|
+
export function useKeypress(userHandler) {
|
|
5
|
+
const signal = useRef(userHandler);
|
|
6
|
+
signal.current = userHandler;
|
|
7
|
+
useEffect((rl) => {
|
|
8
|
+
let ignore = false;
|
|
9
|
+
const handler = withUpdates((_input, event) => {
|
|
10
|
+
if (ignore)
|
|
11
|
+
return;
|
|
12
|
+
void signal.current(event, rl);
|
|
13
|
+
});
|
|
14
|
+
rl.input.on('keypress', handler);
|
|
15
|
+
return () => {
|
|
16
|
+
ignore = true;
|
|
17
|
+
rl.input.removeListener('keypress', handler);
|
|
18
|
+
};
|
|
19
|
+
}, []);
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function useMemo<Value>(fn: () => Value, dependencies: ReadonlyArray<unknown>): Value;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { withPointer } from "./hook-engine.js";
|
|
2
|
+
export function useMemo(fn, dependencies) {
|
|
3
|
+
return withPointer((pointer) => {
|
|
4
|
+
const prev = pointer.get();
|
|
5
|
+
if (!prev ||
|
|
6
|
+
prev.dependencies.length !== dependencies.length ||
|
|
7
|
+
prev.dependencies.some((dep, i) => dep !== dependencies[i])) {
|
|
8
|
+
const value = fn();
|
|
9
|
+
pointer.set({ value, dependencies });
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
return prev.value;
|
|
13
|
+
});
|
|
14
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { useState } from "./use-state.js";
|
|
2
|
+
import { useEffect } from "./use-effect.js";
|
|
3
|
+
import { makeTheme } from "./make-theme.js";
|
|
4
|
+
export function usePrefix({ status = 'idle', theme, }) {
|
|
5
|
+
const [showLoader, setShowLoader] = useState(false);
|
|
6
|
+
const [tick, setTick] = useState(0);
|
|
7
|
+
const { prefix, spinner } = makeTheme(theme);
|
|
8
|
+
useEffect(() => {
|
|
9
|
+
if (status === 'loading') {
|
|
10
|
+
let tickInterval;
|
|
11
|
+
let inc = -1;
|
|
12
|
+
// Delay displaying spinner by 300ms, to avoid flickering
|
|
13
|
+
const delayTimeout = setTimeout(() => {
|
|
14
|
+
setShowLoader(true);
|
|
15
|
+
tickInterval = setInterval(() => {
|
|
16
|
+
inc = inc + 1;
|
|
17
|
+
setTick(inc % spinner.frames.length);
|
|
18
|
+
}, spinner.interval);
|
|
19
|
+
}, 300);
|
|
20
|
+
return () => {
|
|
21
|
+
clearTimeout(delayTimeout);
|
|
22
|
+
clearInterval(tickInterval);
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
setShowLoader(false);
|
|
27
|
+
}
|
|
28
|
+
}, [status]);
|
|
29
|
+
if (showLoader) {
|
|
30
|
+
return spinner.frames[tick];
|
|
31
|
+
}
|
|
32
|
+
// There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.
|
|
33
|
+
const iconName = status === 'loading' ? 'idle' : status;
|
|
34
|
+
return typeof prefix === 'string' ? prefix : (prefix[iconName] ?? prefix['idle']);
|
|
35
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
type NotFunction<T> = T extends (...args: never) => unknown ? never : T;
|
|
2
|
+
export declare function useState<Value>(defaultValue: NotFunction<Value> | (() => Value)): [Value, (newValue: Value) => void];
|
|
3
|
+
export declare function useState<Value>(defaultValue?: NotFunction<Value> | (() => Value)): [Value | undefined, (newValue?: Value) => void];
|
|
4
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { AsyncResource } from 'node:async_hooks';
|
|
2
|
+
import { withPointer, handleChange } from "./hook-engine.js";
|
|
3
|
+
function isFactory(value) {
|
|
4
|
+
return typeof value === 'function';
|
|
5
|
+
}
|
|
6
|
+
export function useState(defaultValue) {
|
|
7
|
+
return withPointer((pointer) => {
|
|
8
|
+
const setState = AsyncResource.bind(function setState(newValue) {
|
|
9
|
+
// Noop if the value is still the same.
|
|
10
|
+
if (pointer.get() !== newValue) {
|
|
11
|
+
pointer.set(newValue);
|
|
12
|
+
// Trigger re-render
|
|
13
|
+
handleChange();
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
if (pointer.initialized) {
|
|
17
|
+
return [pointer.get(), setState];
|
|
18
|
+
}
|
|
19
|
+
const value = isFactory(defaultValue) ? defaultValue() : defaultValue;
|
|
20
|
+
pointer.set(value);
|
|
21
|
+
return [value, setState];
|
|
22
|
+
});
|
|
23
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Force line returns at specific width. This function is ANSI code friendly and it'll
|
|
3
|
+
* ignore invisible codes during width calculation.
|
|
4
|
+
* @param {string} content
|
|
5
|
+
* @param {number} width
|
|
6
|
+
* @return {string}
|
|
7
|
+
*/
|
|
8
|
+
export declare function breakLines(content: string, width: number): string;
|
|
9
|
+
/**
|
|
10
|
+
* Returns the width of the active readline, or 80 as default value.
|
|
11
|
+
* @returns {number}
|
|
12
|
+
*/
|
|
13
|
+
export declare function readlineWidth(): number;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import cliWidth from 'cli-width';
|
|
2
|
+
import { wrapAnsi } from 'fast-wrap-ansi';
|
|
3
|
+
import { readline } from "./hook-engine.js";
|
|
4
|
+
/**
|
|
5
|
+
* Force line returns at specific width. This function is ANSI code friendly and it'll
|
|
6
|
+
* ignore invisible codes during width calculation.
|
|
7
|
+
* @param {string} content
|
|
8
|
+
* @param {number} width
|
|
9
|
+
* @return {string}
|
|
10
|
+
*/
|
|
11
|
+
export function breakLines(content, width) {
|
|
12
|
+
return content
|
|
13
|
+
.split('\n')
|
|
14
|
+
.flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true })
|
|
15
|
+
.split('\n')
|
|
16
|
+
.map((str) => str.trimEnd()))
|
|
17
|
+
.join('\n');
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Returns the width of the active readline, or 80 as default value.
|
|
21
|
+
* @returns {number}
|
|
22
|
+
*/
|
|
23
|
+
export function readlineWidth() {
|
|
24
|
+
return cliWidth({ defaultWidth: 80, output: readline().output });
|
|
25
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inquirer/core",
|
|
3
|
-
"version": "11.1.
|
|
3
|
+
"version": "11.1.8",
|
|
4
4
|
"description": "Core Inquirer prompt API",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"answer",
|
|
@@ -67,9 +67,9 @@
|
|
|
67
67
|
"tsc": "tsc"
|
|
68
68
|
},
|
|
69
69
|
"dependencies": {
|
|
70
|
-
"@inquirer/ansi": "^2.0.
|
|
71
|
-
"@inquirer/figures": "^2.0.
|
|
72
|
-
"@inquirer/type": "^4.0.
|
|
70
|
+
"@inquirer/ansi": "^2.0.5",
|
|
71
|
+
"@inquirer/figures": "^2.0.5",
|
|
72
|
+
"@inquirer/type": "^4.0.5",
|
|
73
73
|
"cli-width": "^4.1.0",
|
|
74
74
|
"fast-wrap-ansi": "^0.2.0",
|
|
75
75
|
"mute-stream": "^3.0.0",
|
|
@@ -77,8 +77,8 @@
|
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
79
|
"@types/mute-stream": "^0.0.4",
|
|
80
|
-
"@types/node": "^25.
|
|
81
|
-
"typescript": "^
|
|
80
|
+
"@types/node": "^25.5.2",
|
|
81
|
+
"typescript": "^6.0.2"
|
|
82
82
|
},
|
|
83
83
|
"peerDependencies": {
|
|
84
84
|
"@types/node": ">=18"
|
|
@@ -93,5 +93,5 @@
|
|
|
93
93
|
},
|
|
94
94
|
"main": "./dist/index.js",
|
|
95
95
|
"types": "./dist/index.d.ts",
|
|
96
|
-
"gitHead": "
|
|
96
|
+
"gitHead": "e68fe01d65359e083581c48c4a18cd8f97d88842"
|
|
97
97
|
}
|