-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
index.mts
107 lines (91 loc) · 2.74 KB
/
index.mts
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
import {
createPrompt,
useState,
useKeypress,
usePrefix,
isEnterKey,
Separator,
makeTheme,
type Theme,
} from '@inquirer/core';
import type { PartialDeep } from '@inquirer/type';
import chalk from 'chalk';
const numberRegex = /\d+/;
type Choice<Value> = {
value: Value;
name?: string;
key?: string;
};
type RawlistConfig<Value> = {
message: string;
choices: ReadonlyArray<Choice<Value> | Separator>;
theme?: PartialDeep<Theme>;
};
function isSelectableChoice<T>(
choice: undefined | Separator | Choice<T>,
): choice is Choice<T> {
return choice != null && !Separator.isSeparator(choice);
}
export default createPrompt(
<Value,>(config: RawlistConfig<Value>, done: (value: Value) => void) => {
const { choices } = config;
const [status, setStatus] = useState<string>('pending');
const [value, setValue] = useState<string>('');
const [errorMsg, setError] = useState<string>();
const theme = makeTheme(config.theme);
const prefix = usePrefix({ theme });
useKeypress((key, rl) => {
if (isEnterKey(key)) {
let selectedChoice;
if (numberRegex.test(value)) {
const answer = Number.parseInt(value, 10) - 1;
selectedChoice = choices.filter(isSelectableChoice)[answer];
} else {
const answer = value.toLowerCase();
selectedChoice = choices.find(
(choice) => isSelectableChoice(choice) && choice.key === answer,
);
}
if (isSelectableChoice(selectedChoice)) {
setValue(selectedChoice.name || String(selectedChoice.value));
setStatus('done');
done(selectedChoice.value);
} else if (value === '') {
setError('Please input a value');
} else {
setError(`"${chalk.red(value)}" isn't an available option`);
}
} else {
setValue(rl.line);
setError(undefined);
}
});
const message = theme.style.message(config.message);
if (status === 'done') {
return `${prefix} ${message} ${theme.style.answer(value)}`;
}
let index = 0;
const choicesStr = choices
.map((choice) => {
if (Separator.isSeparator(choice)) {
return ` ${choice.separator}`;
}
index += 1;
const line = ` ${choice.key || index}) ${choice.name || choice.value}`;
if (choice.key === value.toLowerCase() || String(index) === value) {
return theme.style.highlight(line);
}
return line;
})
.join('\n');
let error = '';
if (errorMsg) {
error = theme.style.error(errorMsg);
}
return [
`${prefix} ${message} ${value}`,
[choicesStr, error].filter(Boolean).join('\n'),
];
},
);
export { Separator } from '@inquirer/core';