Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checkbox - add validation if no choice is selected #1316

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/checkbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const answer = await checkbox({
| choices | `Array<{ value: string, name?: string, disabled?: boolean \| string, checked?: boolean } \| Separator>` | yes | List of the available choices. The `value` will be returned as the answer, and used as display if no `name` is defined. Choices who're `disabled` will be displayed, but not selectable. |
| pageSize | `number` | no | By default, lists of choice longer than 7 will be paginated. Use this option to control how many choices will appear on the screen at once. |
| loop | `boolean` | no | Defaults to `true`. When set to `false`, the cursor will be constrained to the top and bottom of the choice list without looping. |
| required | `boolean` | no | When set to `true`, ensures at least one choice must be selected. |

The `Separator` object can be used to render non-selectable lines in the choice list. By default it'll render a line, but you can provide the text as argument (`new Separator('-- Dependencies --')`). This option is often used to add labels to groups within long list of options.

Expand Down
39 changes: 39 additions & 0 deletions packages/checkbox/checkbox.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -624,4 +624,43 @@ describe('checkbox prompt', () => {
'"[checkbox prompt] No selectable choices. All choices are disabled."',
);
});

it('shows validation message if user did not select any choice', async () => {
const { answer, events, getScreen } = await render(checkbox, {
message: 'Select a number',
choices: numberedChoices,
required: true,
});

events.keypress('enter');
expect(getScreen()).toMatchInlineSnapshot(`
"? Select a number (Press <space> to select, <a> to toggle all, <i> to invert
selection, and <enter> to proceed)
❯◯ 1
◯ 2
◯ 3
◯ 4
◯ 5
◯ 6
◯ 7
(Use arrow keys to reveal more choices)
> At least one choice must be selected"
`);

events.keypress('space');
expect(getScreen()).toMatchInlineSnapshot(`
"? Select a number
❯◉ 1
◯ 2
◯ 3
◯ 4
◯ 5
◯ 6
◯ 7
(Use arrow keys to reveal more choices)"
`);

events.keypress('enter');
await expect(answer).resolves.toEqual([1]);
});
});
27 changes: 23 additions & 4 deletions packages/checkbox/src/index.mts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
instructions?: string | boolean;
choices: ReadonlyArray<Choice<Value> | Separator>;
loop?: boolean;
required?: boolean;
}>;

type Item<Value> = Separator | Choice<Value>;
Expand Down Expand Up @@ -74,7 +75,14 @@

export default createPrompt(
<Value extends unknown>(config: Config<Value>, done: (value: Array<Value>) => void) => {
const { prefix = usePrefix(), instructions, pageSize, loop = true, choices } = config;
const {
prefix = usePrefix(),
instructions,
pageSize,
loop = true,
choices,
required,
} = config;
const [status, setStatus] = useState('pending');
const [items, setItems] = useState<ReadonlyArray<Item<Value>>>(
choices.map((choice) => ({ ...choice })),
Expand All @@ -82,7 +90,7 @@

const bounds = useMemo(() => {
const first = items.findIndex(isSelectable);
// TODO: Replace with `findLastIndex` when it's available.

Check warning on line 93 in packages/checkbox/src/index.mts

View workflow job for this annotation

GitHub Actions / Linting

Unexpected 'todo' comment: 'TODO: Replace with `findLastIndex` when...'
const last = items.length - 1 - [...items].reverse().findIndex(isSelectable);

if (first < 0) {
Expand All @@ -96,11 +104,16 @@

const [active, setActive] = useState(bounds.first);
const [showHelpTip, setShowHelpTip] = useState(true);
const [errorMsg, setError] = useState<string | undefined>(undefined);

useKeypress((key) => {
if (isEnterKey(key)) {
setStatus('done');
done(items.filter(isChecked).map((choice) => choice.value));
if (required && !items.some(isChecked)) {
setError('At least one choice must be selected');
} else {
setStatus('done');
done(items.filter(isChecked).map((choice) => choice.value));
}
} else if (isUpKey(key) || isDownKey(key)) {
if (!loop && active === bounds.first && isUpKey(key)) return;
if (!loop && active === bounds.last && isDownKey(key)) return;
Expand All @@ -111,6 +124,7 @@
} while (!isSelectable(items[next]!));
setActive(next);
} else if (isSpaceKey(key)) {
setError(undefined);
setShowHelpTip(false);
setItems(items.map((choice, i) => (i === active ? toggle(choice) : choice)));
} else if (key.name === 'a') {
Expand Down Expand Up @@ -162,7 +176,12 @@
}
}

return `${prefix} ${message}${helpTip}\n${page}${ansiEscapes.cursorHide}`;
let error = '';
if (errorMsg) {
error = chalk.red(`> ${errorMsg}`);
}

return `${prefix} ${message}${helpTip}\n${page}\n${error}${ansiEscapes.cursorHide}`;
},
);

Expand Down