forked from SBoudrias/Inquirer.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
217 lines (178 loc) · 5.59 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
const readline = require('readline');
const chalk = require('chalk');
const MuteStream = require('mute-stream');
const runAsync = require('run-async');
const spinner = require('cli-spinners').dots;
const ScreenManager = require('./lib/screen-manager');
const defaultState = {
validate: () => true,
filter: (val) => val,
transformer: (val) => val,
};
const defaultMapStateToValue = (state) => {
if (!state.value) {
return state.default;
}
return state.value;
};
const defaultOnLine = (state, { submit }) => submit();
class StateManager {
constructor(configFactory, initialState, render) {
this.initialState = initialState;
this.render = render;
this.currentState = {
loadingIncrement: 0,
value: '',
status: 'idle',
};
// Default `input` to stdin
const input = process.stdin;
// Add mute capabilities to the output
const output = new MuteStream();
output.pipe(process.stdout);
this.rl = readline.createInterface({
terminal: true,
input,
output,
});
this.screen = new ScreenManager(this.rl);
let config = configFactory;
if (typeof configFactory === 'function') {
config = configFactory(this.rl);
}
this.config = config;
this.onKeypress = this.onKeypress.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.startLoading = this.startLoading.bind(this);
this.onLoaderTick = this.onLoaderTick.bind(this);
this.setState = this.setState.bind(this);
this.handleLineEvent = this.handleLineEvent.bind(this);
}
async execute(cb) {
let { message } = this.getState();
this.cb = cb;
// Load asynchronous properties
const showLoader = setTimeout(this.startLoading, 500);
if (typeof message === 'function') {
message = await runAsync(message)();
}
this.setState({ message, status: 'idle' });
// Disable the loader if it didn't launch
clearTimeout(showLoader);
// Setup event listeners once we're done fetching the configs
this.rl.input.on('keypress', this.onKeypress);
this.rl.on('line', this.handleLineEvent);
}
onKeypress(value, key) {
const { onKeypress } = this.config;
// Ignore enter keypress. The "line" event is handling those.
if (key.name === 'enter' || key.name === 'return') {
return;
}
this.setState({ value: this.rl.line, error: null });
if (onKeypress) {
onKeypress(this.rl.line, key, this.getState(), this.setState);
}
}
startLoading() {
this.setState({ loadingIncrement: 0, status: 'loading' });
setTimeout(this.onLoaderTick, spinner.interval);
}
onLoaderTick() {
const { status, loadingIncrement } = this.getState();
if (status === 'loading') {
this.setState({ loadingIncrement: loadingIncrement + 1 });
setTimeout(this.onLoaderTick, spinner.interval);
}
}
handleLineEvent() {
const { onLine = defaultOnLine } = this.config;
onLine(this.getState(), {
submit: this.onSubmit,
setState: this.setState,
});
}
async onSubmit() {
const state = this.getState();
const { validate, filter } = state;
const { validate: configValidate = () => true } = this.config;
const { mapStateToValue = defaultMapStateToValue } = this.config;
const value = mapStateToValue(state);
const showLoader = setTimeout(this.startLoading, 500);
this.rl.pause();
try {
const filteredValue = await runAsync(filter)(value);
let isValid = configValidate(value, state);
if (isValid === true) {
isValid = await runAsync(validate)(filteredValue);
}
if (isValid === true) {
this.onDone(filteredValue);
clearTimeout(showLoader);
return;
}
this.onError(isValid);
} catch (err) {
this.onError(err.message + '\n' + err.stack);
}
clearTimeout(showLoader);
this.rl.resume();
}
onError(error) {
this.setState({
status: 'idle',
error: error || 'You must provide a valid value',
});
}
onDone(value) {
this.setState({ status: 'done' });
this.rl.input.removeListener('keypress', this.onKeypress);
this.rl.removeListener('line', this.handleLineEvent);
this.screen.done();
this.cb(value);
}
setState(partialState) {
this.currentState = { ...this.currentState, ...partialState };
this.onChange(this.getState());
}
getState() {
return { ...defaultState, ...this.initialState, ...this.currentState };
}
getPrefix() {
const { status, loadingIncrement } = this.getState();
let prefix = chalk.green('?');
if (status === 'loading') {
const frame = loadingIncrement % spinner.frames.length;
prefix = chalk.yellow(spinner.frames[frame]);
}
return prefix;
}
onChange(state) {
const { status, message, value, transformer } = this.getState();
let error;
if (state.error) {
error = `${chalk.red('>>')} ${state.error}`;
}
const renderState = {
prefix: this.getPrefix(),
...state,
// Only pass message down if it's a string. Otherwise we're still in init state
message: typeof message === 'function' ? 'Loading...' : message,
value: transformer(value, { isFinal: status === 'done' }),
validate: undefined,
filter: undefined,
transformer: undefined,
};
this.screen.render(this.render(renderState, this.config), error);
}
}
exports.createPrompt = (config, render) => {
const run = (initialState) =>
new Promise((resolve) => {
const prompt = new StateManager(config, initialState, render);
prompt.execute(resolve);
});
run.render = render;
run.config = config;
return run;
};