Skip to content

fix: treat placeholders as visual element #323

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

Merged
merged 4 commits into from
May 26, 2025
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/mean-turkeys-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@clack/prompts": patch
"@clack/core": patch
---

Changes `placeholder` to be a visual hint rather than a tabbable value.
1 change: 0 additions & 1 deletion packages/core/src/prompts/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ export default class AutocompletePrompt<T extends OptionLike> extends Prompt {
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)) {
Expand Down
17 changes: 0 additions & 17 deletions packages/core/src/prompts/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ import type { Action } from '../utils/index.js';

export interface PromptOptions<Self extends Prompt> {
render(this: Omit<Self, 'prompt'>): string | undefined;
placeholder?: string;
initialValue?: any;
defaultValue?: any;
validate?: ((value: any) => string | Error | undefined) | undefined;
input?: Readable;
output?: Writable;
Expand All @@ -34,7 +32,6 @@ export default class Prompt {
private _prevFrame = '';
private _subscribers = new Map<string, { cb: (...args: any) => any; once?: boolean }[]>();
protected _cursor = 0;
protected _usePlaceholderAsValue = true;

public state: ClackState = 'initial';
public error = '';
Expand Down Expand Up @@ -212,25 +209,11 @@ export default class Prompt {
if (char && (char.toLowerCase() === 'y' || char.toLowerCase() === 'n')) {
this.emit('confirm', char.toLowerCase() === 'y');
}
if (this._usePlaceholderAsValue && char === '\t' && this.opts.placeholder) {
if (!this.value) {
this.rl?.write(this.opts.placeholder);
this._setValue(this.opts.placeholder);
}
}

// Call the key event handler and emit the key event
this.emit('key', char?.toLowerCase(), key);

if (key?.name === 'return') {
if (!this.value) {
if (this.opts.defaultValue) {
this._setValue(this.opts.defaultValue);
} else {
this._setValue('');
}
}

if (this.opts.validate) {
const problem = this.opts.validate(this.value);
if (problem) {
Expand Down
33 changes: 1 addition & 32 deletions packages/core/test/prompts/prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('Prompt', () => {
const resultPromise = instance.prompt();
input.emit('keypress', '', { name: 'return' });
const result = await resultPromise;
expect(result).to.equal('');
expect(result).to.equal(undefined);
expect(isCancel(result)).to.equal(false);
expect(instance.state).to.equal('submit');
expect(output.buffer).to.deep.equal([cursor.hide, 'foo', '\n', cursor.show]);
Expand Down Expand Up @@ -136,37 +136,6 @@ describe('Prompt', () => {
expect(eventFn).toBeCalledWith(false);
});

test('sets value as placeholder on tab if one is set', () => {
const instance = new Prompt({
input,
output,
render: () => 'foo',
placeholder: 'piwa',
});

instance.prompt();

input.emit('keypress', '\t', { name: 'tab' });

expect(instance.value).to.equal('piwa');
});

test('does not set placeholder value on tab if value already set', () => {
const instance = new Prompt({
input,
output,
render: () => 'foo',
placeholder: 'piwa',
initialValue: 'trzy',
});

instance.prompt();

input.emit('keypress', '\t', { name: 'tab' });

expect(instance.value).to.equal('trzy');
});

test('emits key event for unknown chars', () => {
const eventSpy = vi.fn();
const instance = new Prompt({
Expand Down
18 changes: 12 additions & 6 deletions packages/prompts/src/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ export interface AutocompleteOptions<Value> extends AutocompleteSharedOptions<Va
export const autocomplete = <Value>(opts: AutocompleteOptions<Value>) => {
const prompt = new AutocompletePrompt({
options: opts.options,
placeholder: opts.placeholder,
initialValue: opts.initialValue ? [opts.initialValue] : undefined,
filter: (search: string, opt: Option<Value>) => {
return getFilteredOption(search, opt);
Expand All @@ -81,6 +80,8 @@ export const autocomplete = <Value>(opts: AutocompleteOptions<Value>) => {
// Title and message display
const title = `${color.gray(S_BAR)}\n${symbol(this.state)} ${opts.message}\n`;
const valueAsString = String(this.value ?? '');
const placeholder = opts.placeholder;
const showPlaceholder = valueAsString === '' && placeholder !== undefined;

// Handle different states
switch (this.state) {
Expand All @@ -97,7 +98,10 @@ export const autocomplete = <Value>(opts: AutocompleteOptions<Value>) => {

default: {
// Display cursor position - show plain text in navigation mode
const searchText = this.isNavigating ? color.dim(valueAsString) : this.valueWithCursor;
const searchText =
this.isNavigating || showPlaceholder
? color.dim(showPlaceholder ? placeholder : valueAsString)
: this.valueWithCursor;

// Show match count if filtered
const matches =
Expand Down Expand Up @@ -209,7 +213,6 @@ export const autocompleteMultiselect = <Value>(opts: AutocompleteMultiSelectOpti
}
return undefined;
},
placeholder: opts.placeholder,
initialValue: opts.initialValues,
input: opts.input,
output: opts.output,
Expand All @@ -219,11 +222,14 @@ export const autocompleteMultiselect = <Value>(opts: AutocompleteMultiSelectOpti

// Selection counter
const value = String(this.value ?? '');
const placeholder = opts.placeholder;
const showPlaceholder = value === '' && placeholder !== undefined;

// Search input display
const searchText = this.isNavigating
? color.dim(value) // Just show plain text when in navigation mode
: this.valueWithCursor;
const searchText =
this.isNavigating || showPlaceholder
? color.dim(showPlaceholder ? placeholder : value) // Just show plain text when in navigation mode
: this.valueWithCursor;

const matches =
this.filteredOptions.length !== opts.options.length
Expand Down
2 changes: 1 addition & 1 deletion packages/prompts/src/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const text = (opts: TextOptions) => {
S_BAR_END
)} ${color.yellow(this.error)}\n`;
case 'submit': {
const displayValue = typeof this.value === 'undefined' ? '' : this.value;
const displayValue = this.value === undefined ? '' : this.value;
return `${title}${color.gray(S_BAR)} ${color.dim(displayValue)}`;
}
case 'cancel':
Expand Down
25 changes: 25 additions & 0 deletions packages/prompts/test/__snapshots__/autocomplete.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,31 @@ exports[`autocomplete > renders initial UI with message and instructions 1`] = `
]
`;

exports[`autocomplete > renders placeholder if set 1`] = `
[
"<cursor.hide>",
"│
◆ Select a fruit

│ Search: Type to search...
│ ● Apple
│ ○ Banana
│ ○ Cherry
│ ○ Grape
│ ○ Orange
│ ↑/↓ to select • Enter: confirm • Type: to search
└",
"<cursor.backward count=999><cursor.up count=10>",
"<cursor.down count=1>",
"<erase.down>",
"◇ Select a fruit
│ Apple",
"
",
"<cursor.show>",
]
`;

exports[`autocomplete > shows hint when option has hint and is focused 1`] = `
[
"<cursor.hide>",
Expand Down
16 changes: 16 additions & 0 deletions packages/prompts/test/autocomplete.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,21 @@ describe('autocomplete', () => {
expect(output.buffer).toMatchSnapshot();
});

test('renders placeholder if set', async () => {
const result = autocomplete({
message: 'Select a fruit',
placeholder: 'Type to search...',
options: testOptions,
input,
output,
});

input.emit('keypress', '', { name: 'return' });
const value = await result;
expect(output.buffer).toMatchSnapshot();
expect(value).toBe('apple');
});

test('supports initialValue', async () => {
const result = autocomplete({
message: 'Select a fruit',
Expand All @@ -132,6 +147,7 @@ describe('autocomplete', () => {

input.emit('keypress', '', { name: 'return' });
const value = await result;

expect(value).toBe('cherry');
expect(output.buffer).toMatchSnapshot();
});
Expand Down
16 changes: 0 additions & 16 deletions packages/prompts/test/text.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,6 @@ describe.each(['true', 'false'])('text (isCI = %s)', (isCI) => {
expect(value).toBe('');
});

test('<tab> applies placeholder', async () => {
const result = prompts.text({
message: 'foo',
placeholder: 'bar',
input,
output,
});

input.emit('keypress', '\t', { name: 'tab' });
input.emit('keypress', '', { name: 'return' });

const value = await result;

expect(value).toBe('bar');
});

test('can cancel', async () => {
const result = prompts.text({
message: 'foo',
Expand Down