Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/young-mice-vanish.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clack/prompts': patch
---

feat(@clack/prompts): Add validate option for select and multiselect
21 changes: 21 additions & 0 deletions packages/prompts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ export interface SelectOptions<Value> {
options: Option<Value>[];
initialValue?: Value;
maxItems?: number;
validate?: (value: string) => string | void;
}

export const select = <Value>(opts: SelectOptions<Value>) => {
Expand All @@ -234,6 +235,7 @@ export const select = <Value>(opts: SelectOptions<Value>) => {
};

return new SelectPrompt({
validate: opts.validate,
options: opts.options,
initialValue: opts.initialValue,
render() {
Expand All @@ -247,6 +249,20 @@ export const select = <Value>(opts: SelectOptions<Value>) => {
this.options[this.cursor],
'cancelled'
)}\n${color.gray(S_BAR)}`;
case 'error': {
const footer = this.error
.split('\n')
.map((ln, i) =>
i === 0 ? `${color.yellow(S_BAR_END)} ${color.yellow(ln)}` : ` ${ln}`
)
.join('\n');
return `${title}${color.yellow(S_BAR)} ${limitOptions({
cursor: this.cursor,
options: this.options,
maxItems: opts.maxItems,
style: (item, active) => opt(item, active ? 'active' : 'inactive'),
}).join(`\n${color.yellow(S_BAR)} `)}\n${footer}`;
}
default: {
return `${title}${color.cyan(S_BAR)} ${limitOptions({
cursor: this.cursor,
Expand Down Expand Up @@ -313,6 +329,7 @@ export interface MultiSelectOptions<Value> {
maxItems?: number;
required?: boolean;
cursorAt?: Value;
validate?: (value: Value[]) => string | void;
}
export const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {
const opt = (
Expand Down Expand Up @@ -344,6 +361,10 @@ export const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {
required: opts.required ?? true,
cursorAt: opts.cursorAt,
validate(selected: Value[]) {
if (opts.validate) {
const error = opts.validate(selected);
if (error) return error;
}
if (this.required && selected.length === 0)
return `Please select at least one option.\n${color.reset(
color.dim(
Expand Down