Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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/nasty-parrots-laugh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@clack/prompts": minor
"@clack/core": minor
---

Adds `AutocompletePrompt` to core with comprehensive tests and implement both `autocomplete` and `autocomplete-multiselect` components in prompts package.
100 changes: 100 additions & 0 deletions examples/basic/autocomplete-multiselect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import * as p from '@clack/prompts';
import color from 'picocolors';

/**
* Example demonstrating the integrated autocomplete multiselect component
* Which combines filtering and selection in a single interface
*/

async function main() {
console.clear();

p.intro(`${color.bgCyan(color.black(' Integrated Autocomplete Multiselect Example '))}`);

p.note(
`
${color.cyan('Filter and select multiple items in a single interface:')}
- ${color.yellow('Type')} to filter the list in real-time
- Use ${color.yellow('up/down arrows')} to navigate with improved stability
- Press ${color.yellow('Space')} to select/deselect the highlighted item ${color.green('(multiple selections allowed)')}
- Use ${color.yellow('Backspace')} to modify your filter text when searching for different options
- Press ${color.yellow('Enter')} when done selecting all items
- Press ${color.yellow('Ctrl+C')} to cancel
`,
'Instructions'
);

// Frameworks in alphabetical order
const frameworks = [
{ value: 'angular', label: 'Angular', hint: 'Frontend/UI' },
{ value: 'django', label: 'Django', hint: 'Python Backend' },
{ value: 'dotnet', label: '.NET Core', hint: 'C# Backend' },
{ value: 'electron', label: 'Electron', hint: 'Desktop' },
{ value: 'express', label: 'Express', hint: 'Node.js Backend' },
{ value: 'flask', label: 'Flask', hint: 'Python Backend' },
{ value: 'flutter', label: 'Flutter', hint: 'Mobile' },
{ value: 'laravel', label: 'Laravel', hint: 'PHP Backend' },
{ value: 'nestjs', label: 'NestJS', hint: 'Node.js Backend' },
{ value: 'nextjs', label: 'Next.js', hint: 'React Framework' },
{ value: 'nuxt', label: 'Nuxt.js', hint: 'Vue Framework' },
{ value: 'rails', label: 'Ruby on Rails', hint: 'Ruby Backend' },
{ value: 'react', label: 'React', hint: 'Frontend/UI' },
{ value: 'reactnative', label: 'React Native', hint: 'Mobile' },
{ value: 'spring', label: 'Spring Boot', hint: 'Java Backend' },
{ value: 'svelte', label: 'Svelte', hint: 'Frontend/UI' },
{ value: 'tauri', label: 'Tauri', hint: 'Desktop' },
{ value: 'vue', label: 'Vue.js', hint: 'Frontend/UI' },
];

// Use the new integrated autocompleteMultiselect component
const result = await p.autocompleteMultiselect<string>({
message: 'Select frameworks (type to filter)',
options: frameworks,
placeholder: 'Type to filter...',
maxItems: 8,
});

if (p.isCancel(result)) {
p.cancel('Operation cancelled.');
process.exit(0);
}

// Type guard: if not a cancel symbol, result must be a string array
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((item) => typeof item === 'string');
}

// We can now use the type guard to ensure type safety
if (!isStringArray(result)) {
throw new Error('Unexpected result type');
}

const selectedFrameworks = result;

// If no items selected, show a message
if (selectedFrameworks.length === 0) {
p.note('No frameworks were selected', 'Empty Selection');
process.exit(0);
}

// Display selected frameworks with detailed information
p.note(
`You selected ${color.green(selectedFrameworks.length)} frameworks:`,
'Selection Complete'
);

// Show each selected framework with its details
const selectedDetails = selectedFrameworks
.map((value) => {
const framework = frameworks.find((f) => f.value === value);
return framework
? `${color.cyan(framework.label)} ${color.dim(`- ${framework.hint}`)}`
: value;
})
.join('\n');

p.log.message(selectedDetails);
p.outro(`Successfully selected ${color.green(selectedFrameworks.length)} frameworks.`);
}

main().catch(console.error);
59 changes: 59 additions & 0 deletions examples/basic/autocomplete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import * as p from '@clack/prompts';
import color from 'picocolors';

async function main() {
console.clear();

p.intro(`${color.bgCyan(color.black(' Autocomplete Example '))}`);

p.note(
`
${color.cyan('This example demonstrates the type-ahead autocomplete feature:')}
- ${color.yellow('Type')} to filter the list in real-time
- Use ${color.yellow('up/down arrows')} to navigate the filtered results
- Press ${color.yellow('Enter')} to select the highlighted option
- Press ${color.yellow('Ctrl+C')} to cancel
`,
'Instructions'
);

const countries = [
{ value: 'us', label: 'United States', hint: 'NA' },
{ value: 'ca', label: 'Canada', hint: 'NA' },
{ value: 'mx', label: 'Mexico', hint: 'NA' },
{ value: 'br', label: 'Brazil', hint: 'SA' },
{ value: 'ar', label: 'Argentina', hint: 'SA' },
{ value: 'uk', label: 'United Kingdom', hint: 'EU' },
{ value: 'fr', label: 'France', hint: 'EU' },
{ value: 'de', label: 'Germany', hint: 'EU' },
{ value: 'it', label: 'Italy', hint: 'EU' },
{ value: 'es', label: 'Spain', hint: 'EU' },
{ value: 'pt', label: 'Portugal', hint: 'EU' },
{ value: 'ru', label: 'Russia', hint: 'EU/AS' },
{ value: 'cn', label: 'China', hint: 'AS' },
{ value: 'jp', label: 'Japan', hint: 'AS' },
{ value: 'in', label: 'India', hint: 'AS' },
{ value: 'kr', label: 'South Korea', hint: 'AS' },
{ value: 'au', label: 'Australia', hint: 'OC' },
{ value: 'nz', label: 'New Zealand', hint: 'OC' },
{ value: 'za', label: 'South Africa', hint: 'AF' },
{ value: 'eg', label: 'Egypt', hint: 'AF' },
];

const result = await p.autocomplete({
message: 'Select a country',
options: countries,
placeholder: 'Type to search countries...',
maxItems: 8,
});

if (p.isCancel(result)) {
p.cancel('Operation cancelled.');
process.exit(0);
}

const selected = countries.find((c) => c.value === result);
p.outro(`You selected: ${color.cyan(selected?.label)} (${color.yellow(selected?.hint)})`);
}

main().catch(console.error);
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ export { default as Prompt } from './prompts/prompt.js';
export { default as SelectPrompt } from './prompts/select.js';
export { default as SelectKeyPrompt } from './prompts/select-key.js';
export { default as TextPrompt } from './prompts/text.js';
export { default as AutocompletePrompt } from './prompts/autocomplete.js';
export { block, isCancel, getColumns } from './utils/index.js';
export { updateSettings, settings } from './utils/settings.js';
193 changes: 193 additions & 0 deletions packages/core/src/prompts/autocomplete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import type { Key } from 'node:readline';
import color from 'picocolors';
import Prompt, { type PromptOptions } from './prompt.js';

interface OptionLike {
value: unknown;
label?: string;
}

type FilterFunction<T extends OptionLike> = (search: string, opt: T) => boolean;

function getCursorForValue<T extends OptionLike>(
selected: T['value'] | undefined,
items: T[]
): number {
if (selected === undefined) {
return 0;
}

const currLength = items.length;

// If filtering changed the available options, update cursor
if (currLength === 0) {
return 0;
}

// Try to maintain the same selected item
const index = items.findIndex((item) => item.value === selected);
return index !== -1 ? index : 0;
}

function defaultFilter<T extends OptionLike>(input: string, option: T): boolean {
const label = option.label ?? String(option.value);
return label.toLowerCase().includes(input.toLowerCase());
}

function normalisedValue<T>(multiple: boolean, values: T[] | undefined): T | T[] | undefined {
if (!values) {
return undefined;
}
if (multiple) {
return values;
}
return values[0];
}

export interface AutocompleteOptions<T extends OptionLike>
extends PromptOptions<AutocompletePrompt<T>> {
options: T[];
filter?: FilterFunction<T>;
multiple?: boolean;
}

export default class AutocompletePrompt<T extends OptionLike> extends Prompt {
options: T[];
filteredOptions: T[];
multiple: boolean;
isNavigating = false;
selectedValues: Array<T['value']> = [];

focusedValue: T['value'] | undefined;
#cursor = 0;
#lastValue: T['value'] | undefined;
#filterFn: FilterFunction<T>;

get cursor(): number {
return this.#cursor;
}

get valueWithCursor() {
if (!this.value) {
return color.inverse(color.hidden('_'));
}
if (this._cursor >= this.value.length) {
return `${this.value}█`;
}
const s1 = this.value.slice(0, this._cursor);
const [s2, ...s3] = this.value.slice(this._cursor);
return `${s1}${color.inverse(s2)}${s3.join('')}`;
}

constructor(opts: AutocompleteOptions<T>) {
super(opts);

this.options = opts.options;
this.filteredOptions = [...this.options];
this.multiple = opts.multiple === true;
this._usePlaceholderAsValue = false;
this.#filterFn = opts.filter ?? defaultFilter;
let initialValues: unknown[] | undefined;
if (opts.initialValue && Array.isArray(opts.initialValue)) {
if (this.multiple) {
initialValues = opts.initialValue;
} else {
initialValues = opts.initialValue.slice(0, 1);
}
}

if (initialValues) {
this.selectedValues = initialValues;
for (const selectedValue of initialValues) {
const selectedIndex = this.options.findIndex((opt) => opt.value === selectedValue);
if (selectedIndex !== -1) {
this.toggleSelected(selectedValue);
this.#cursor = selectedIndex;
this.focusedValue = this.options[this.#cursor]?.value;
}
}
}

this.on('finalize', () => {
if (!this.value) {
this.value = normalisedValue(this.multiple, initialValues);
}

if (this.state === 'submit') {
this.value = normalisedValue(this.multiple, this.selectedValues);
}
});

this.on('key', (char, key) => this.#onKey(char, key));
this.on('value', (value) => this.#onValueChanged(value));
}

protected override _isActionKey(char: string | undefined, key: Key): boolean {
return (
char === '\t' ||
(this.multiple &&
this.isNavigating &&
key.name === 'space' &&
char !== undefined &&
char !== '')
);
}

#onKey(_char: string | undefined, key: Key): void {
const isUpKey = key.name === 'up';
const isDownKey = key.name === 'down';

// Start navigation mode with up/down arrows
if (isUpKey || isDownKey) {
this.#cursor = Math.max(
0,
Math.min(this.#cursor + (isUpKey ? -1 : 1), this.filteredOptions.length - 1)
);
this.focusedValue = this.filteredOptions[this.#cursor]?.value;
if (!this.multiple) {
this.selectedValues = [this.focusedValue];
}
this.isNavigating = true;
} else {
if (
this.multiple &&
this.focusedValue !== undefined &&
(key.name === 'tab' || (this.isNavigating && key.name === 'space'))
) {
this.toggleSelected(this.focusedValue);
} else {
this.isNavigating = false;
}
}
}

toggleSelected(value: T['value']) {
if (this.filteredOptions.length === 0) {
return;
}

if (this.multiple) {
if (this.selectedValues.includes(value)) {
this.selectedValues = this.selectedValues.filter((v) => v !== value);
} else {
this.selectedValues = [...this.selectedValues, value];
}
} else {
this.selectedValues = [value];
}
}

#onValueChanged(value: string | undefined): void {
if (value !== this.#lastValue) {
this.#lastValue = value;

if (value) {
this.filteredOptions = this.options.filter((opt) => this.#filterFn(value, opt));
} else {
this.filteredOptions = [...this.options];
}
this.#cursor = getCursorForValue(this.focusedValue, this.filteredOptions);
this.focusedValue = this.filteredOptions[this.#cursor]?.value;
}
}
}
Loading