Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
useKeypress(async (key, rl) => {
// Ignore keypress while our prompt is doing other processing.
if (status !== 'pending') {
return;
}
if (isEnterKey(key)) {
const answer = value || defaultValue || '';
setStatus('loading');
const isValid = await config.validate(answer);
if (isValid === true) {
setValue(answer);
setStatus('done');
done(answer);
} else {
// TODO: Can we keep the value after validation failure?
// `rl.line = value` works but it looses the cursor position.
setValue('');
setError(isValid || 'You must provide a valid value');
setStatus('pending');
}
} else if (isBackspaceKey(key) && !value) {
setDefaultValue(undefined);
useKeypress(key => {
if (isEnterKey(key)) {
setStatus('done');
done(choices[cursorPosition].value);
} else if (isUpKey(key) || isDownKey(key)) {
let newCursorPosition = cursorPosition;
const offset = isUpKey(key) ? -1 : 1;
let selectedOption;
while (!selectedOption || selectedOption.disabled) {
newCursorPosition =
(newCursorPosition + offset + choices.length) % choices.length;
selectedOption = choices[newCursorPosition];
}
setCursorPos(newCursorPosition);
} else if (isNumberKey(key)) {
// Adjust index to start at 1
useKeypress((key, rl) => {
if (isEnterKey(key)) {
const answer = value ? /^y(es)?/i.test(value) : config.default !== false;
setValue(answer ? 'yes' : 'no');
setStatus('done');
done(answer);
} else {
setValue(rl.line);
}
});
useKeypress((key, rl) => {
if (isEnterKey(key)) {
const answer = (value || defaultKey).toLowerCase();
if (answer === 'h' && !expanded) {
setExpanded(true);
} else {
const selectedChoice = choices.find(({ key }) => key === answer);
if (selectedChoice) {
const finalValue = selectedChoice.value || selectedChoice.name;
setValue(finalValue);
setStatus('done');
done(finalValue);
} else if (value === '') {
setError('Please input a value');
} else {
setError(`"${chalk.red(value)}" isn't an available option`);
}
}