Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/itchy-coins-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@clack/prompts": patch
"@clack/core": patch
---

Allow disabled options in multi-select and select prompts.
28 changes: 20 additions & 8 deletions packages/core/src/prompts/multi-select.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,42 @@
import { findCursor } from '../utils/cursor.js';
import Prompt, { type PromptOptions } from './prompt.js';

interface MultiSelectOptions<T extends { value: any }>
interface OptionLike {
value: any;
disabled?: boolean;
}

interface MultiSelectOptions<T extends OptionLike>
extends PromptOptions<T['value'][], MultiSelectPrompt<T>> {
options: T[];
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
}
export default class MultiSelectPrompt<T extends { value: any }> extends Prompt<T['value'][]> {
export default class MultiSelectPrompt<T extends OptionLike> extends Prompt<T['value'][]> {
options: T[];
cursor = 0;

private get _value(): T['value'] {
return this.options[this.cursor].value;
}

private get _enabledOptions(): T[] {
return this.options.filter((option) => option.disabled !== true);
}

private toggleAll() {
const allSelected = this.value !== undefined && this.value.length === this.options.length;
this.value = allSelected ? [] : this.options.map((v) => v.value);
const enabledOptions = this._enabledOptions;
const allSelected = this.value !== undefined && this.value.length === enabledOptions.length;
this.value = allSelected ? [] : enabledOptions.map((v) => v.value);
}

private toggleInvert() {
const value = this.value;
if (!value) {
return;
}
const notSelected = this.options.filter((v) => !value.includes(v.value));
const notSelected = this._enabledOptions.filter((v) => !value.includes(v.value));
this.value = notSelected.map((v) => v.value);
}

Expand All @@ -44,10 +55,11 @@ export default class MultiSelectPrompt<T extends { value: any }> extends Prompt<

this.options = opts.options;
this.value = [...(opts.initialValues ?? [])];
this.cursor = Math.max(
const cursor = Math.max(
this.options.findIndex(({ value }) => value === opts.cursorAt),
0
);
this.cursor = this.options[cursor].disabled ? findCursor<T>(cursor, 1, this.options) : cursor;
this.on('key', (char) => {
if (char === 'a') {
this.toggleAll();
Expand All @@ -61,11 +73,11 @@ export default class MultiSelectPrompt<T extends { value: any }> extends Prompt<
switch (key) {
case 'left':
case 'up':
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
this.cursor = findCursor<T>(this.cursor, -1, this.options);
break;
case 'down':
case 'right':
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
this.cursor = findCursor<T>(this.cursor, 1, this.options);
break;
case 'space':
this.toggleValue();
Expand Down
17 changes: 11 additions & 6 deletions packages/core/src/prompts/select.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { findCursor } from '../utils/cursor.js';
import Prompt, { type PromptOptions } from './prompt.js';

interface SelectOptions<T extends { value: any }>
interface SelectOptions<T extends { value: any; disabled?: boolean }>
extends PromptOptions<T['value'], SelectPrompt<T>> {
options: T[];
initialValue?: T['value'];
}
export default class SelectPrompt<T extends { value: any }> extends Prompt<T['value']> {
export default class SelectPrompt<T extends { value: any; disabled?: boolean }> extends Prompt<
T['value']
> {
options: T[];
cursor = 0;

Expand All @@ -21,19 +24,21 @@ export default class SelectPrompt<T extends { value: any }> extends Prompt<T['va
super(opts, false);

this.options = opts.options;
this.cursor = this.options.findIndex(({ value }) => value === opts.initialValue);
if (this.cursor === -1) this.cursor = 0;

const initialCursor = this.options.findIndex(({ value }) => value === opts.initialValue);
const cursor = initialCursor === -1 ? 0 : initialCursor;
this.cursor = this.options[cursor].disabled ? findCursor<T>(cursor, 1, this.options) : cursor;
this.changeValue();

this.on('cursor', (key) => {
switch (key) {
case 'left':
case 'up':
this.cursor = this.cursor === 0 ? this.options.length - 1 : this.cursor - 1;
this.cursor = findCursor<T>(this.cursor, -1, this.options);
break;
case 'down':
case 'right':
this.cursor = this.cursor === this.options.length - 1 ? 0 : this.cursor + 1;
this.cursor = findCursor<T>(this.cursor, 1, this.options);
break;
}
this.changeValue();
Expand Down
14 changes: 14 additions & 0 deletions packages/core/src/utils/cursor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export function findCursor<T extends { disabled?: boolean }>(
cursor: number,
delta: number,
options: T[]
) {
const newCursor = cursor + delta;
const maxCursor = Math.max(options.length - 1, 0);
const clampedCursor = newCursor < 0 ? maxCursor : newCursor > maxCursor ? 0 : newCursor;
const newOption = options[clampedCursor];
if (newOption.disabled) {
return findCursor(clampedCursor, delta < 0 ? -1 : 1, options);
}
return clampedCursor;
}
79 changes: 79 additions & 0 deletions packages/core/test/prompts/multi-select.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,5 +130,84 @@ describe('MultiSelectPrompt', () => {
input.emit('keypress', 'i', { name: 'i' });
expect(instance.value).toEqual(['foo']);
});

test('disabled options are skipped', () => {
const instance = new MultiSelectPrompt({
input,
output,
render: () => 'foo',
options: [{ value: 'foo' }, { value: 'bar', disabled: true }, { value: 'baz' }],
});
instance.prompt();

expect(instance.cursor).to.equal(0);
input.emit('keypress', 'down', { name: 'down' });
expect(instance.cursor).to.equal(2);
input.emit('keypress', 'up', { name: 'up' });
expect(instance.cursor).to.equal(0);
});

test('initial cursorAt on disabled option', () => {
const instance = new MultiSelectPrompt({
input,
output,
render: () => 'foo',
options: [{ value: 'foo' }, { value: 'bar', disabled: true }, { value: 'baz' }],
cursorAt: 'bar',
});
instance.prompt();

expect(instance.cursor).to.equal(2);
});
});

describe('toggleAll', () => {
test('selects all enabled options', () => {
const instance = new MultiSelectPrompt({
input,
output,
render: () => 'foo',
options: [{ value: 'foo' }, { value: 'bar', disabled: true }, { value: 'baz' }],
});
instance.prompt();

input.emit('keypress', 'a', { name: 'a' });
expect(instance.value).toEqual(['foo', 'baz']);
});

test('unselects all enabled options if all selected', () => {
const instance = new MultiSelectPrompt({
input,
output,
render: () => 'foo',
options: [{ value: 'foo' }, { value: 'bar', disabled: true }, { value: 'baz' }],
initialValues: ['foo', 'baz'],
});
instance.prompt();

input.emit('keypress', 'a', { name: 'a' });
expect(instance.value).toEqual([]);
});
});

describe('toggleInvert', () => {
test('inverts selection of enabled options', () => {
const instance = new MultiSelectPrompt({
input,
output,
render: () => 'foo',
options: [
{ value: 'foo' },
{ value: 'bar', disabled: true },
{ value: 'baz' },
{ value: 'qux' },
],
initialValues: ['foo', 'baz'],
});
instance.prompt();

input.emit('keypress', 'i', { name: 'i' });
expect(instance.value).toEqual(['qux']);
});
});
});
38 changes: 38 additions & 0 deletions packages/core/test/prompts/select.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,5 +100,43 @@ describe('SelectPrompt', () => {
instance.prompt();
expect(instance.cursor).to.equal(1);
});

test('cursor skips disabled options (down)', () => {
const instance = new SelectPrompt({
input,
output,
render: () => 'foo',
options: [{ value: 'foo' }, { value: 'bar', disabled: true }, { value: 'baz' }],
});
instance.prompt();
expect(instance.cursor).to.equal(0);
input.emit('keypress', 'down', { name: 'down' });
expect(instance.cursor).to.equal(2);
});

test('cursor skips disabled options (up)', () => {
const instance = new SelectPrompt({
input,
output,
render: () => 'foo',
initialValue: 'baz',
options: [{ value: 'foo' }, { value: 'bar', disabled: true }, { value: 'baz' }],
});
instance.prompt();
expect(instance.cursor).to.equal(2);
input.emit('keypress', 'up', { name: 'up' });
expect(instance.cursor).to.equal(0);
});

test('cursor skips initial disabled option', () => {
const instance = new SelectPrompt({
input,
output,
render: () => 'foo',
options: [{ value: 'foo', disabled: true }, { value: 'bar' }, { value: 'baz' }],
});
instance.prompt();
expect(instance.cursor).to.equal(1);
});
});
});
4 changes: 2 additions & 2 deletions packages/prompts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const projectType = await select({
message: 'Pick a project type.',
options: [
{ value: 'ts', label: 'TypeScript' },
{ value: 'js', label: 'JavaScript' },
{ value: 'js', label: 'JavaScript', disabled: true },
{ value: 'coffee', label: 'CoffeeScript', hint: 'oh no' },
],
});
Expand All @@ -103,7 +103,7 @@ const additionalTools = await multiselect({
message: 'Select additional tools.',
options: [
{ value: 'eslint', label: 'ESLint', hint: 'recommended' },
{ value: 'prettier', label: 'Prettier' },
{ value: 'prettier', label: 'Prettier', disabled: true },
{ value: 'gh-action', label: 'GitHub Action' },
],
required: false,
Expand Down
29 changes: 24 additions & 5 deletions packages/prompts/src/multi-select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,21 @@ export interface MultiSelectOptions<Value> extends CommonOptions {
export const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {
const opt = (
option: Option<Value>,
state: 'inactive' | 'active' | 'selected' | 'active-selected' | 'submitted' | 'cancelled'
state:
| 'inactive'
| 'active'
| 'selected'
| 'active-selected'
| 'submitted'
| 'cancelled'
| 'disabled'
) => {
const label = option.label ?? String(option.value);
if (state === 'disabled') {
return `${color.gray(S_CHECKBOX_INACTIVE)} ${color.gray(label)}${
option.hint ? ` ${color.dim(`(${option.hint ?? 'disabled'})`)}` : ''
}`;
}
if (state === 'active') {
return `${color.cyan(S_CHECKBOX_ACTIVE)} ${label}${
option.hint ? ` ${color.dim(`(${option.hint})`)}` : ''
Expand Down Expand Up @@ -74,6 +86,9 @@ export const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {
const value = this.value ?? [];

const styleOption = (option: Option<Value>, active: boolean) => {
if (option.disabled) {
return opt(option, 'disabled');
}
const selected = value.includes(option.value);
if (active && selected) {
return opt(option, 'active-selected');
Expand Down Expand Up @@ -103,28 +118,32 @@ export const multiselect = <Value>(opts: MultiSelectOptions<Value>) => {
}`;
}
case 'error': {
const prefix = `${color.yellow(S_BAR)} `;
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({
return `${title}${prefix}${limitOptions({
output: opts.output,
options: this.options,
cursor: this.cursor,
maxItems: opts.maxItems,
columnPadding: prefix.length,
style: styleOption,
}).join(`\n${color.yellow(S_BAR)} `)}\n${footer}\n`;
}).join(`\n${prefix}`)}\n${footer}\n`;
}
default: {
return `${title}${color.cyan(S_BAR)} ${limitOptions({
const prefix = `${color.cyan(S_BAR)} `;
return `${title}${prefix}${limitOptions({
output: opts.output,
options: this.options,
cursor: this.cursor,
maxItems: opts.maxItems,
columnPadding: prefix.length,
style: styleOption,
}).join(`\n${color.cyan(S_BAR)} `)}\n${color.cyan(S_BAR_END)}\n`;
}).join(`\n${prefix}`)}\n${color.cyan(S_BAR_END)}\n`;
}
}
},
Expand Down
Loading
Loading