-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.mjs
88 lines (75 loc) · 2.32 KB
/
index.mjs
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
import {
createPrompt,
useState,
useKeypress,
usePrefix,
isEnterKey,
isUpKey,
isDownKey,
} from '@inquirer/core';
import chalk from 'chalk';
import readline from 'readline';
export default async (options) => {
const {
renderSelected = choice => chalk.green(`❯ ${choice.name} (${choice.key})`),
renderUnselected = choice => ` ${choice.name} (${choice.key})`,
hideCursor = true
} = options;
let rl;
if (hideCursor) {
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.output.write('\x1B[?25l'); // Hide cursor
}
const answer = await createPrompt((config, done) => {
const { choices, default: defaultKey } = config;
const [status, setStatus] = useState('pending');
const [index, setIndex] = useState(choices.findIndex((choice) => choice.value === defaultKey ?? ''));
const prefix = usePrefix();
useKeypress((key, _rl) => {
if (isEnterKey(key)) {
const selectedChoice = choices[index];
if (selectedChoice) {
setStatus('done');
done(selectedChoice.value);
}
} else if (isUpKey(key)) {
setIndex(index > 0 ? index - 1 : 0);
} else if (isDownKey(key)) {
setIndex(index < choices.length - 1 ? index + 1 : choices.length - 1);
} else {
const foundIndex = choices.findIndex((choice) => {
const choiceValue = choice.value.toLowerCase();
const keyName = key.name.toLowerCase();
return choiceValue.startsWith(keyName);
});
if (foundIndex !== -1) {
setIndex(foundIndex);
// This automatically finishes the prompt. Remove this if you don't want that.
setStatus('done');
done(choices[foundIndex].value);
}
}
})
const message = chalk.bold(config.message);
if (status === 'done') {
return `${prefix} ${message} ${chalk.cyan(choices[index].name)}`;
}
const renderedChoices = choices
.map((choice, i) => {
if (i === index) {
return renderSelected(choice, index);
}
return renderUnselected(choice, i);
})
.join('\n');
return [`${prefix} ${message}`, renderedChoices];
})(options);
if (hideCursor) {
rl.output.write('\x1B[?25h'); // Show cursor
rl.close();
}
return answer;
};