@inquirer/core 0.0.20-alpha.0 → 0.0.21-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +34 -0
- package/dist/index.js +105 -0
- package/dist/lib/Paginator.d.ts +9 -0
- package/dist/lib/Paginator.js +46 -0
- package/dist/lib/key.d.ts +11 -0
- package/dist/lib/key.js +6 -0
- package/dist/lib/options.d.ts +2 -0
- package/dist/lib/options.js +8 -0
- package/dist/lib/prefix.d.ts +1 -0
- package/dist/lib/prefix.js +20 -0
- package/{lib/readline.js → dist/lib/readline.d.ts} +6 -25
- package/dist/lib/readline.js +49 -0
- package/dist/lib/screen-manager.d.ts +10 -0
- package/dist/lib/screen-manager.js +93 -0
- package/dist/lib/utils.d.ts +8 -0
- package/{lib → dist/lib}/utils.js +3 -4
- package/package.json +14 -9
- package/src/index.ts +163 -0
- package/{lib/Paginator.js → src/lib/Paginator.ts} +7 -15
- package/src/lib/index.d.ts +3 -0
- package/src/lib/key.ts +20 -0
- package/src/lib/options.ts +14 -0
- package/{lib/prefix.js → src/lib/prefix.ts} +8 -6
- package/src/lib/readline.ts +55 -0
- package/{lib/screen-manager.js → src/lib/screen-manager.ts} +31 -44
- package/src/lib/utils.ts +15 -0
- package/test.ts +92 -0
- package/tsconfig.json +7 -0
- package/hooks.js +0 -119
- package/index.js +0 -217
- package/lib/key.js +0 -13
- package/lib/options.js +0 -12
- package/test.js +0 -265
package/src/index.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import readline from 'node:readline';
|
|
2
|
+
import MuteStream from 'mute-stream';
|
|
3
|
+
import ScreenManager from './lib/screen-manager.js';
|
|
4
|
+
import { getPromptConfig } from './lib/options.js';
|
|
5
|
+
|
|
6
|
+
export { usePrefix } from './lib/prefix.js';
|
|
7
|
+
export * from './lib/key.js';
|
|
8
|
+
export * from './lib/Paginator.js';
|
|
9
|
+
|
|
10
|
+
type StdioOptions = {
|
|
11
|
+
input?: NodeJS.ReadableStream;
|
|
12
|
+
output?: NodeJS.WritableStream;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export type InquirerReadline = readline.ReadLine & {
|
|
16
|
+
output: MuteStream;
|
|
17
|
+
input: NodeJS.ReadableStream;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type KeypressEvent = {
|
|
21
|
+
name: string;
|
|
22
|
+
ctrl: boolean;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
let sessionRl: InquirerReadline | void;
|
|
26
|
+
let hooks: any[] = [];
|
|
27
|
+
const hooksCleanup: any[] = [];
|
|
28
|
+
let index = 0;
|
|
29
|
+
let handleChange = () => {};
|
|
30
|
+
|
|
31
|
+
const cleanupHook = (index: number) => {
|
|
32
|
+
const cleanFn = hooksCleanup[index];
|
|
33
|
+
if (typeof cleanFn === 'function') {
|
|
34
|
+
cleanFn();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export function useState<Value>(defaultValue: Value): [Value, (newValue: Value) => void] {
|
|
39
|
+
const _idx = index;
|
|
40
|
+
const value = _idx in hooks ? hooks[_idx] : defaultValue;
|
|
41
|
+
|
|
42
|
+
index++;
|
|
43
|
+
|
|
44
|
+
return [
|
|
45
|
+
value,
|
|
46
|
+
(newValue) => {
|
|
47
|
+
hooks[_idx] = newValue;
|
|
48
|
+
|
|
49
|
+
// Trigger re-render
|
|
50
|
+
handleChange();
|
|
51
|
+
},
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function useEffect(cb: () => void | (() => void), depArray: unknown[]): void {
|
|
56
|
+
const _idx = index;
|
|
57
|
+
|
|
58
|
+
const oldDeps = hooks[_idx];
|
|
59
|
+
let hasChanged = true;
|
|
60
|
+
if (oldDeps) {
|
|
61
|
+
hasChanged = depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
|
|
62
|
+
}
|
|
63
|
+
if (hasChanged) {
|
|
64
|
+
cleanupHook(_idx);
|
|
65
|
+
hooksCleanup[_idx] = cb();
|
|
66
|
+
}
|
|
67
|
+
hooks[_idx] = depArray;
|
|
68
|
+
|
|
69
|
+
index++;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function useKeypress(
|
|
73
|
+
userHandler: (event: KeypressEvent, rl: InquirerReadline) => void
|
|
74
|
+
) {
|
|
75
|
+
const rl = sessionRl;
|
|
76
|
+
|
|
77
|
+
if (!rl) {
|
|
78
|
+
throw new Error('useKeypress must be used within a prompt');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
const handler = (_input: string, event: KeypressEvent) => {
|
|
83
|
+
userHandler(event, rl);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
rl.input.on('keypress', handler);
|
|
87
|
+
return () => {
|
|
88
|
+
rl.input.removeListener('keypress', handler);
|
|
89
|
+
};
|
|
90
|
+
}, [userHandler]);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function useRef<Value>(val: Value): { current: Value } {
|
|
94
|
+
return useState({ current: val })[0];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type AsyncPromptConfig = {
|
|
98
|
+
message: string | Promise<string> | (() => Promise<string>);
|
|
99
|
+
validate?: () => boolean;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export type ResolvedPromptConfig = {
|
|
103
|
+
message: string;
|
|
104
|
+
validate: () => boolean;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export function createPrompt<Value, Config extends AsyncPromptConfig>(
|
|
108
|
+
view: (
|
|
109
|
+
config: Config & ResolvedPromptConfig,
|
|
110
|
+
done: (value: Value) => void
|
|
111
|
+
) => string | [string, string | undefined]
|
|
112
|
+
) {
|
|
113
|
+
return async function (options: Config, stdio?: StdioOptions): Promise<Value> {
|
|
114
|
+
// Default `input` to stdin
|
|
115
|
+
const input = stdio?.input ?? process.stdin;
|
|
116
|
+
|
|
117
|
+
// Add mute capabilities to the output
|
|
118
|
+
const output = new MuteStream();
|
|
119
|
+
output.pipe(stdio?.output ?? process.stdout);
|
|
120
|
+
|
|
121
|
+
const rl = readline.createInterface({
|
|
122
|
+
terminal: true,
|
|
123
|
+
input,
|
|
124
|
+
output,
|
|
125
|
+
}) as InquirerReadline;
|
|
126
|
+
const screen = new ScreenManager(rl);
|
|
127
|
+
|
|
128
|
+
// TODO: we should display a loader while we get the default options.
|
|
129
|
+
const resolvedConfig = await getPromptConfig(options);
|
|
130
|
+
|
|
131
|
+
return new Promise((resolve) => {
|
|
132
|
+
const done = (value: Value) => {
|
|
133
|
+
let len = cleanupHook.length;
|
|
134
|
+
while (len--) {
|
|
135
|
+
cleanupHook(len);
|
|
136
|
+
}
|
|
137
|
+
screen.done();
|
|
138
|
+
|
|
139
|
+
// Reset hooks state
|
|
140
|
+
hooks = [];
|
|
141
|
+
index = 0;
|
|
142
|
+
sessionRl = undefined;
|
|
143
|
+
|
|
144
|
+
// Finally we resolve our promise
|
|
145
|
+
resolve(value);
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
hooks = [];
|
|
149
|
+
const workLoop = (config: Config & ResolvedPromptConfig) => {
|
|
150
|
+
sessionRl = rl;
|
|
151
|
+
index = 0;
|
|
152
|
+
handleChange = () => workLoop(config);
|
|
153
|
+
|
|
154
|
+
const nextView = view(config, done);
|
|
155
|
+
const [content, bottomContent] =
|
|
156
|
+
typeof nextView === 'string' ? [nextView] : nextView;
|
|
157
|
+
screen.render(content, bottomContent);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
workLoop(resolvedConfig);
|
|
161
|
+
});
|
|
162
|
+
};
|
|
163
|
+
}
|
|
@@ -1,23 +1,17 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
const cliWidth = require('cli-width');
|
|
5
|
-
const { breakLines } = require('./utils');
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import cliWidth from 'cli-width';
|
|
3
|
+
import { breakLines } from './utils.js';
|
|
6
4
|
|
|
7
5
|
/**
|
|
8
6
|
* The paginator keeps track of a pointer index in a list and returns
|
|
9
7
|
* a subset of the choices if the list is too long.
|
|
10
8
|
*/
|
|
11
9
|
|
|
12
|
-
class Paginator {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
this.lastIndex = 0;
|
|
16
|
-
this.rl = rl;
|
|
17
|
-
}
|
|
10
|
+
export class Paginator {
|
|
11
|
+
pointer = 0;
|
|
12
|
+
lastIndex = 0;
|
|
18
13
|
|
|
19
|
-
paginate(output, active, pageSize) {
|
|
20
|
-
pageSize = pageSize || 7;
|
|
14
|
+
paginate(output: string, active: number, pageSize: number = 7) {
|
|
21
15
|
const middleOfList = Math.floor(pageSize / 2);
|
|
22
16
|
|
|
23
17
|
// TODO: I've remove the dependency on readline here. But we should refactor the
|
|
@@ -49,5 +43,3 @@ class Paginator {
|
|
|
49
43
|
return section + '\n' + chalk.dim('(Move up and down to reveal more choices)');
|
|
50
44
|
}
|
|
51
45
|
}
|
|
52
|
-
|
|
53
|
-
module.exports = Paginator;
|
package/src/lib/key.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
type KeypressEvent = {
|
|
2
|
+
name: string;
|
|
3
|
+
ctrl: boolean;
|
|
4
|
+
};
|
|
5
|
+
|
|
6
|
+
export const isUpKey = (key: KeypressEvent): boolean =>
|
|
7
|
+
key.name === 'up' || key.name === 'k' || (key.name === 'p' && key.ctrl);
|
|
8
|
+
|
|
9
|
+
export const isDownKey = (key: KeypressEvent): boolean =>
|
|
10
|
+
key.name === 'down' || key.name === 'j' || (key.name === 'n' && key.ctrl);
|
|
11
|
+
|
|
12
|
+
export const isSpaceKey = (key: KeypressEvent): boolean => key.name === 'space';
|
|
13
|
+
|
|
14
|
+
export const isBackspaceKey = (key: KeypressEvent): boolean => key.name === 'backspace';
|
|
15
|
+
|
|
16
|
+
export const isNumberKey = (key: KeypressEvent): boolean =>
|
|
17
|
+
'123456789'.includes(key.name);
|
|
18
|
+
|
|
19
|
+
export const isEnterKey = (key: KeypressEvent): boolean =>
|
|
20
|
+
key.name === 'enter' || key.name === 'return';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AsyncPromptConfig, ResolvedPromptConfig } from '../index.js';
|
|
2
|
+
|
|
3
|
+
export async function getPromptConfig<In extends AsyncPromptConfig>(
|
|
4
|
+
option: In
|
|
5
|
+
): Promise<In & ResolvedPromptConfig> {
|
|
6
|
+
const message =
|
|
7
|
+
typeof option.message === 'function' ? option.message() : option.message;
|
|
8
|
+
|
|
9
|
+
return {
|
|
10
|
+
validate: () => true,
|
|
11
|
+
...option,
|
|
12
|
+
message: await message,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import spinners from 'cli-spinners';
|
|
3
|
+
import { useState, useEffect } from '../index.js';
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
const spinner = spinners.dots;
|
|
6
|
+
|
|
7
|
+
export function usePrefix(isLoading: boolean = false): string {
|
|
6
8
|
const [tick, setTick] = useState(0);
|
|
7
9
|
|
|
8
|
-
useEffect(() => {
|
|
10
|
+
useEffect((): void | (() => unknown) => {
|
|
9
11
|
if (isLoading) {
|
|
10
12
|
const timeout = setTimeout(() => {
|
|
11
13
|
setTick(tick + 1);
|
|
@@ -21,4 +23,4 @@ exports.usePrefix = (isLoading) => {
|
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
return chalk.green('?');
|
|
24
|
-
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import ansiEscapes from 'ansi-escapes';
|
|
2
|
+
import type { InquirerReadline } from '../index.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Move cursor left by `x`
|
|
6
|
+
* @param {Readline} rl - Readline instance
|
|
7
|
+
* @param {Number} x - How far to go left (default to 1)
|
|
8
|
+
*/
|
|
9
|
+
export function left(rl: InquirerReadline, x: number) {
|
|
10
|
+
if (x > 0) {
|
|
11
|
+
rl.output.write(ansiEscapes.cursorBackward(x));
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Move cursor right by `x`
|
|
17
|
+
* @param {Readline} rl - Readline instance
|
|
18
|
+
* @param {Number} x - How far to go left (default to 1)
|
|
19
|
+
*/
|
|
20
|
+
export function right(rl: InquirerReadline, x: number) {
|
|
21
|
+
if (x > 0) {
|
|
22
|
+
rl.output.write(ansiEscapes.cursorForward(x));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Move cursor up by `x`
|
|
28
|
+
* @param {Readline} rl - Readline instance
|
|
29
|
+
* @param {Number} x - How far to go up (default to 1)
|
|
30
|
+
*/
|
|
31
|
+
export function up(rl: InquirerReadline, x: number) {
|
|
32
|
+
if (x > 0) {
|
|
33
|
+
rl.output.write(ansiEscapes.cursorUp(x));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Move cursor down by `x`
|
|
39
|
+
* @param {Readline} rl - Readline instance
|
|
40
|
+
* @param {Number} x - How far to go down (default to 1)
|
|
41
|
+
*/
|
|
42
|
+
export function down(rl: InquirerReadline, x: number) {
|
|
43
|
+
if (x > 0) {
|
|
44
|
+
rl.output.write(ansiEscapes.cursorDown(x));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Clear current line
|
|
50
|
+
* @param {Readline} rl - Readline instance
|
|
51
|
+
* @param {Number} len - number of line to delete
|
|
52
|
+
*/
|
|
53
|
+
export function clearLine(rl: InquirerReadline, len: number) {
|
|
54
|
+
rl.output.write(ansiEscapes.eraseLines(len));
|
|
55
|
+
}
|
|
@@ -1,23 +1,24 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
import cliWidth from 'cli-width';
|
|
2
|
+
import stripAnsi from 'strip-ansi';
|
|
3
|
+
import stringWidth from 'string-width';
|
|
4
|
+
import ansiEscapes from 'ansi-escapes';
|
|
5
|
+
import * as util from './readline.js';
|
|
6
|
+
import { breakLines } from './utils.js';
|
|
7
|
+
import { InquirerReadline } from '../index.js';
|
|
8
|
+
|
|
9
|
+
const height = (content: string): number => content.split('\n').length;
|
|
10
|
+
const lastLine = (content: string): string => content.split('\n').pop() ?? '';
|
|
11
|
+
|
|
12
|
+
export default class ScreenManager {
|
|
13
|
+
// These variables are keeping information to allow correct prompt re-rendering
|
|
14
|
+
private height: number = 0;
|
|
15
|
+
private extraLinesUnderPrompt: number = 0;
|
|
16
|
+
|
|
17
|
+
constructor(private readonly rl: InquirerReadline) {
|
|
17
18
|
this.rl = rl;
|
|
18
19
|
}
|
|
19
20
|
|
|
20
|
-
render(content, bottomContent) {
|
|
21
|
+
render(content: string, bottomContent: string = '') {
|
|
21
22
|
this.rl.output.unmute();
|
|
22
23
|
this.clean(this.extraLinesUnderPrompt);
|
|
23
24
|
|
|
@@ -39,13 +40,11 @@ module.exports = class ScreenManager {
|
|
|
39
40
|
this.rl.setPrompt(prompt);
|
|
40
41
|
|
|
41
42
|
// SetPrompt will change cursor position, now we can get correct value
|
|
42
|
-
const cursorPos = this.rl._getCursorPos();
|
|
43
|
+
const cursorPos = (this.rl as any)._getCursorPos();
|
|
43
44
|
const width = cliWidth({ defaultWidth: 80, output: this.rl.output });
|
|
44
45
|
|
|
45
46
|
content = breakLines(content, width);
|
|
46
|
-
|
|
47
|
-
bottomContent = breakLines(bottomContent, width);
|
|
48
|
-
}
|
|
47
|
+
bottomContent = breakLines(bottomContent, width);
|
|
49
48
|
|
|
50
49
|
// Manually insert an extra line if we're at the end of the line.
|
|
51
50
|
// This prevent the cursor from appearing at the beginning of the
|
|
@@ -66,17 +65,12 @@ module.exports = class ScreenManager {
|
|
|
66
65
|
const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - cursorPos.rows;
|
|
67
66
|
const bottomContentHeight =
|
|
68
67
|
promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);
|
|
69
|
-
if (bottomContentHeight > 0) {
|
|
70
|
-
util.up(this.rl, bottomContentHeight);
|
|
71
|
-
}
|
|
72
68
|
|
|
73
|
-
//
|
|
69
|
+
// Return cursor to the input position (on top of the bottomContent)
|
|
70
|
+
util.up(this.rl, bottomContentHeight);
|
|
71
|
+
// Move cursor at the start of the line, then return to the initial left offset.
|
|
74
72
|
util.left(this.rl, stringWidth(lastLine(fullContent)));
|
|
75
|
-
|
|
76
|
-
// Adjust cursor on the right
|
|
77
|
-
if (cursorPos.cols > 0) {
|
|
78
|
-
util.right(this.rl, cursorPos.cols);
|
|
79
|
-
}
|
|
73
|
+
util.right(this.rl, cursorPos.cols);
|
|
80
74
|
|
|
81
75
|
/**
|
|
82
76
|
* Set up state for next re-rendering
|
|
@@ -87,26 +81,19 @@ module.exports = class ScreenManager {
|
|
|
87
81
|
this.rl.output.mute();
|
|
88
82
|
}
|
|
89
83
|
|
|
90
|
-
clean(extraLines) {
|
|
91
|
-
|
|
92
|
-
util.down(this.rl, extraLines);
|
|
93
|
-
}
|
|
94
|
-
|
|
84
|
+
clean(extraLines: number) {
|
|
85
|
+
util.down(this.rl, extraLines);
|
|
95
86
|
util.clearLine(this.rl, this.height);
|
|
96
87
|
}
|
|
97
88
|
|
|
98
89
|
done() {
|
|
99
|
-
|
|
90
|
+
// Reset the cursor at the end of the previously displayed content
|
|
91
|
+
util.down(this.rl, this.extraLinesUnderPrompt);
|
|
92
|
+
|
|
100
93
|
this.rl.setPrompt('');
|
|
101
94
|
this.rl.output.unmute();
|
|
102
95
|
this.rl.output.write('\n');
|
|
103
|
-
this.rl.output.write(cursorShow);
|
|
96
|
+
this.rl.output.write(ansiEscapes.cursorShow);
|
|
104
97
|
this.rl.close();
|
|
105
98
|
}
|
|
106
|
-
|
|
107
|
-
releaseCursor() {
|
|
108
|
-
if (this.extraLinesUnderPrompt > 0) {
|
|
109
|
-
util.down(this.rl, this.extraLinesUnderPrompt);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
};
|
|
99
|
+
}
|
package/src/lib/utils.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import wrapAnsi from 'wrap-ansi';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Force line returns at specific width. This function is ANSI code friendly and it'll
|
|
5
|
+
* ignore invisible codes during width calculation.
|
|
6
|
+
* @param {string} content
|
|
7
|
+
* @param {number} width
|
|
8
|
+
* @return {string}
|
|
9
|
+
*/
|
|
10
|
+
export const breakLines = (content: string, width: number): string =>
|
|
11
|
+
content
|
|
12
|
+
.split('\n')
|
|
13
|
+
// @ts-expect-error broken type check from library
|
|
14
|
+
.map((line) => wrapAnsi(line, width, { trim: false, hard: true }).split('\n'))
|
|
15
|
+
.join('\n');
|
package/test.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import MuteStream from 'mute-stream';
|
|
2
|
+
import { jest } from '@jest/globals';
|
|
3
|
+
import { Stream } from 'node:stream';
|
|
4
|
+
import {
|
|
5
|
+
createPrompt,
|
|
6
|
+
useKeypress,
|
|
7
|
+
useState,
|
|
8
|
+
isDownKey,
|
|
9
|
+
isUpKey,
|
|
10
|
+
isEnterKey,
|
|
11
|
+
type KeypressEvent,
|
|
12
|
+
} from './src/index.js';
|
|
13
|
+
|
|
14
|
+
describe('createPrompt()', () => {
|
|
15
|
+
it('handle async function message', async () => {
|
|
16
|
+
const render = jest.fn(() => '');
|
|
17
|
+
const input = new MuteStream();
|
|
18
|
+
const prompt = createPrompt(render);
|
|
19
|
+
const promise = Promise.resolve('Async message:');
|
|
20
|
+
prompt({ message: () => promise }, { input });
|
|
21
|
+
|
|
22
|
+
// Initially, we leave a few ms for message to resolve
|
|
23
|
+
expect(render).not.toHaveBeenCalled();
|
|
24
|
+
|
|
25
|
+
await promise;
|
|
26
|
+
await Promise.resolve(); // Wait one extra tick
|
|
27
|
+
expect(render).toHaveBeenLastCalledWith(
|
|
28
|
+
expect.objectContaining({ message: 'Async message:' }),
|
|
29
|
+
expect.any(Function)
|
|
30
|
+
);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('handle deferred message', async () => {
|
|
34
|
+
const render = jest.fn(() => '');
|
|
35
|
+
const input = new MuteStream();
|
|
36
|
+
const prompt = createPrompt(render);
|
|
37
|
+
const promise = Promise.resolve('Async message:');
|
|
38
|
+
prompt({ message: promise }, { input });
|
|
39
|
+
|
|
40
|
+
// Initially, we leave a few ms for message to resolve
|
|
41
|
+
expect(render).not.toHaveBeenCalled();
|
|
42
|
+
|
|
43
|
+
await promise;
|
|
44
|
+
await Promise.resolve(); // Wait one extra tick
|
|
45
|
+
expect(render).toHaveBeenLastCalledWith(
|
|
46
|
+
expect.objectContaining({ message: 'Async message:' }),
|
|
47
|
+
expect.any(Function)
|
|
48
|
+
);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('onKeypress: allow to implement custom behavior on keypress', async () => {
|
|
52
|
+
const Prompt = (config: { message: string }, done: (value: string) => void) => {
|
|
53
|
+
const [value, setValue] = useState('');
|
|
54
|
+
|
|
55
|
+
useKeypress((key: KeypressEvent) => {
|
|
56
|
+
if (isEnterKey(key)) {
|
|
57
|
+
done(value);
|
|
58
|
+
} else if (isDownKey(key)) {
|
|
59
|
+
setValue('down');
|
|
60
|
+
} else if (isUpKey(key)) {
|
|
61
|
+
setValue('up');
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
return `${config.message} ${value}`;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const prompt = createPrompt(Prompt);
|
|
69
|
+
const input = new MuteStream();
|
|
70
|
+
const data = jest.fn();
|
|
71
|
+
const output = new Stream.Writable({
|
|
72
|
+
write(chunk, _encoding, next) {
|
|
73
|
+
data(chunk.toString());
|
|
74
|
+
next();
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
const answer = prompt({ message: 'Question' }, { input, output });
|
|
78
|
+
|
|
79
|
+
// Wait for event listeners to be ready
|
|
80
|
+
await Promise.resolve();
|
|
81
|
+
await Promise.resolve();
|
|
82
|
+
|
|
83
|
+
input.emit('keypress', null, { name: 'down' });
|
|
84
|
+
expect(data).toHaveBeenCalledWith('Question down');
|
|
85
|
+
expect(data).not.toHaveBeenCalledWith('Question up');
|
|
86
|
+
input.emit('keypress', null, { name: 'up' });
|
|
87
|
+
expect(data).toHaveBeenCalledWith('Question up');
|
|
88
|
+
input.emit('keypress', null, { name: 'enter' });
|
|
89
|
+
|
|
90
|
+
await expect(answer).resolves.toEqual('up');
|
|
91
|
+
});
|
|
92
|
+
});
|
package/tsconfig.json
ADDED
package/hooks.js
DELETED
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
const readline = require('readline');
|
|
2
|
-
const MuteStream = require('mute-stream');
|
|
3
|
-
const ScreenManager = require('./lib/screen-manager');
|
|
4
|
-
const { getPromptConfig } = require('./lib/options');
|
|
5
|
-
|
|
6
|
-
let sessionRl;
|
|
7
|
-
let hooks = [];
|
|
8
|
-
const hooksCleanup = [];
|
|
9
|
-
let index = 0;
|
|
10
|
-
let handleChange = () => {};
|
|
11
|
-
|
|
12
|
-
const cleanupHook = (index) => {
|
|
13
|
-
const cleanFn = hooksCleanup[index];
|
|
14
|
-
if (typeof cleanFn === 'function') {
|
|
15
|
-
cleanFn();
|
|
16
|
-
}
|
|
17
|
-
};
|
|
18
|
-
|
|
19
|
-
exports.useState = (defaultValue) => {
|
|
20
|
-
const _idx = index;
|
|
21
|
-
const value = _idx in hooks ? hooks[_idx] : defaultValue;
|
|
22
|
-
|
|
23
|
-
index++;
|
|
24
|
-
|
|
25
|
-
return [
|
|
26
|
-
value,
|
|
27
|
-
(newValue) => {
|
|
28
|
-
hooks[_idx] = newValue;
|
|
29
|
-
|
|
30
|
-
// Trigger re-render
|
|
31
|
-
handleChange();
|
|
32
|
-
},
|
|
33
|
-
];
|
|
34
|
-
};
|
|
35
|
-
|
|
36
|
-
exports.useKeypress = (userHandler) => {
|
|
37
|
-
const _idx = index;
|
|
38
|
-
const prevHandler = hooks[_idx];
|
|
39
|
-
const handler = (input, event) => {
|
|
40
|
-
userHandler(event, sessionRl);
|
|
41
|
-
};
|
|
42
|
-
|
|
43
|
-
if (prevHandler !== handler) {
|
|
44
|
-
cleanupHook(_idx);
|
|
45
|
-
|
|
46
|
-
sessionRl.input.on('keypress', handler);
|
|
47
|
-
hooks[_idx] = handler;
|
|
48
|
-
hooksCleanup[_idx] = () => {
|
|
49
|
-
sessionRl.input.removeListener('keypress', handler);
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
index++;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
exports.useEffect = (cb, depArray) => {
|
|
57
|
-
const _idx = index;
|
|
58
|
-
|
|
59
|
-
const oldDeps = hooks[_idx];
|
|
60
|
-
let hasChanged = true;
|
|
61
|
-
if (oldDeps) {
|
|
62
|
-
hasChanged = depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));
|
|
63
|
-
}
|
|
64
|
-
if (hasChanged) {
|
|
65
|
-
cleanupHook(_idx);
|
|
66
|
-
hooksCleanup[_idx] = cb();
|
|
67
|
-
}
|
|
68
|
-
hooks[_idx] = depArray;
|
|
69
|
-
|
|
70
|
-
index++;
|
|
71
|
-
};
|
|
72
|
-
|
|
73
|
-
exports.useRef = (val) => exports.useState({ current: val })[0];
|
|
74
|
-
|
|
75
|
-
exports.createPrompt = (view) => (options) => {
|
|
76
|
-
// Default `input` to stdin
|
|
77
|
-
const input = process.stdin;
|
|
78
|
-
|
|
79
|
-
// Add mute capabilities to the output
|
|
80
|
-
const output = new MuteStream();
|
|
81
|
-
output.pipe(process.stdout);
|
|
82
|
-
|
|
83
|
-
const rl = readline.createInterface({
|
|
84
|
-
terminal: true,
|
|
85
|
-
input,
|
|
86
|
-
output,
|
|
87
|
-
});
|
|
88
|
-
const screen = new ScreenManager(rl);
|
|
89
|
-
|
|
90
|
-
return new Promise((resolve, reject) => {
|
|
91
|
-
sessionRl = rl;
|
|
92
|
-
|
|
93
|
-
const done = (value) => {
|
|
94
|
-
let len = cleanupHook.length;
|
|
95
|
-
while (len--) {
|
|
96
|
-
cleanupHook(len);
|
|
97
|
-
}
|
|
98
|
-
screen.done();
|
|
99
|
-
|
|
100
|
-
// Reset hooks state
|
|
101
|
-
hooks = [];
|
|
102
|
-
index = 0;
|
|
103
|
-
sessionRl = undefined;
|
|
104
|
-
|
|
105
|
-
// Finally we resolve our promise
|
|
106
|
-
resolve(value);
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
hooks = [];
|
|
110
|
-
const workLoop = (config) => {
|
|
111
|
-
index = 0;
|
|
112
|
-
handleChange = () => workLoop(config);
|
|
113
|
-
screen.render(...[view(config, done)].flat().filter(Boolean));
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
// TODO: we should display a loader while we get the default options.
|
|
117
|
-
getPromptConfig(options).then(workLoop, reject);
|
|
118
|
-
});
|
|
119
|
-
};
|