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

feat(core): add search #208

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
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 examples/basic/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ async function main() {

const project = await p.group(
{
search: () =>
p.search({
message: "What's your gender?",
options: [{ value: 'male' }, { value: 'female' }],
}),
path: () =>
p.text({
message: 'Where should we create your project?',
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"devDependencies": {
"@changesets/cli": "^2.26.2",
"@types/node": "^18.16.0",
"fuzzy": "^0.1.3",
"organize-imports-cli": "^0.10.0",
"prettier": "^3.0.2",
"typescript": "^5.2.2",
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export { default as MultiSelectPrompt } from './prompts/multi-select';
export { default as PasswordPrompt } from './prompts/password';
export { default as Prompt, isCancel } from './prompts/prompt';
export type { State } from './prompts/prompt';
export { default as SearchPrompt } from './prompts/search';
export { default as SelectPrompt } from './prompts/select';
export { default as SelectKeyPrompt } from './prompts/select-key';
export { default as TextPrompt } from './prompts/text';
Expand Down
117 changes: 117 additions & 0 deletions packages/core/src/prompts/search.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import fuzzy from 'fuzzy';
import Prompt, { PromptOptions } from './prompt';
interface SearchOptions<T extends { value: any; label?: string }>
extends PromptOptions<SearchPrompt<T>> {
options: T[];
initialValue?: T['value'];
maxItems?: number;
}
export default class SearchPrompt<
T extends { value: any; label?: string; hint?: string },
> extends Prompt {
options: T[];
valueWithCursor = '';

selectCursor = 0;
inputCursor = 0;
maxItems: number;
selected: T[] = [];

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

private changeValue() {
this.value = this._value?.value;
}

constructor(opts: SearchOptions<T>) {
super(opts, false);
this.options = opts.options;
this.maxItems = opts.maxItems || 1;
this.valueWithCursor = opts.initialValue || '';
if (this.valueWithCursor) {
this.inputCursor = this.valueWithCursor.length;
this.fuzzyFilter(opts);
}

this.on('key', (v) => {
if (v.charCodeAt(0) === 127) {
this.valueWithCursor =
this.valueWithCursor.slice(0, this.inputCursor - 1) +
this.valueWithCursor.slice(this.inputCursor);
this.inputCursor = this.inputCursor === 0 ? 0 : this.inputCursor - 1;
this.selectCursor = 0;
} else if (v.charCodeAt(0) === 8) {
this.valueWithCursor =
this.valueWithCursor.slice(0, this.inputCursor) +
this.valueWithCursor.slice(this.inputCursor + 1);
this.selectCursor = 0;
} else if (v.charCodeAt(0) === 13 || v.charCodeAt(0) === 3) {
return;
} else if ((this.maxItems > 1 && v.charCodeAt(0) === 32) || v.charCodeAt(0) === 9) {
const value = this.options[this.selectCursor];
if (this.selected.includes(value)) {
this.selected = this.selected.filter((v) => v !== value);
} else if (this.selected.length >= this.maxItems) {
return;
} else {
this.selected.push(value);
}
} else {
this.valueWithCursor =
this.valueWithCursor.slice(0, this.inputCursor) +
v +
this.valueWithCursor.slice(this.inputCursor);
this.inputCursor = this.inputCursor + 1;
this.selectCursor = 0;
}
this.fuzzyFilter(opts);
});

this.on('finalize', () => {
this.value = this.selected.length
? this.selected.map((item) => item.value)
: this.maxItems > 1
? [this.options[this.selectCursor].value]
: this.options[this.selectCursor].value;
});

this.on('cursor', (key) => {
switch (key) {
case 'left':
this.inputCursor = Math.max(0, this.inputCursor - 1);
break;
case 'up':
this.selectCursor =
this.selectCursor === 0 ? this.options.length - 1 : this.selectCursor - 1;
break;
case 'down':
this.selectCursor =
this.selectCursor === this.options.length - 1 ? 0 : this.selectCursor + 1;
break;
case 'right':
this.inputCursor = Math.min(this.valueWithCursor.length, this.inputCursor + 1);
break;
}
this.changeValue();
});
}
fuzzyFilter(opts: SearchOptions<T>) {
const fuzzyOptions = fuzzy.filter(this.valueWithCursor, opts.options, {
extract: ({ label, value }) => String(label || value),
});
fuzzyOptions.sort((a, b) => {
if (a.index === b.index) {
return (
(a.original.label || a.original.value).indexOf(this.valueWithCursor) -
(b.original.label || b.original.value).indexOf(this.valueWithCursor)
);
}
return a.index - b.index;
});
this.options = fuzzyOptions.map((item) => item.original);
this.changeValue();
}
}
130 changes: 126 additions & 4 deletions packages/prompts/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@ import {
isCancel,
MultiSelectPrompt,
PasswordPrompt,
SearchPrompt,
SelectKeyPrompt,
SelectPrompt,
State,
TextPrompt
} from '@clack/core';
} from '@simon_he/clack-core';
import isUnicodeSupported from 'is-unicode-supported';
import color from 'picocolors';
import { cursor, erase } from 'sisteransi';

export { isCancel } from '@clack/core';
export { isCancel } from '@simon_he/clack-core';

const unicode = isUnicodeSupported();
const s = (c: string, fallback: string) => (unicode ? c : fallback);
Expand Down Expand Up @@ -218,6 +219,15 @@ export interface SelectOptions<Value> {
maxItems?: number;
}

export interface SearchOptions<Value, MaxItems> {
message?: string;
options: Option<Value>[];
initialValue?: Value;
placeholder?: string;
value?: MaxItems extends 1 ? string : string[];
maxItems?: MaxItems;
}

export const select = <Value>(opts: SelectOptions<Value>) => {
const opt = (option: Option<Value>, state: 'inactive' | 'active' | 'selected' | 'cancelled') => {
const label = option.label ?? String(option.value);
Expand Down Expand Up @@ -308,6 +318,118 @@ export const selectKey = <Value extends string>(opts: SelectOptions<Value>) => {
}).prompt() as Promise<Value | symbol>;
};

export const search = <Value, MaxItems extends number = 1>(
opts: SearchOptions<Value, MaxItems>
) => {
const opt = (
option: Option<Value>,
state:
| 'inactive'
| 'active'
| 'group-active'
| 'group-inactive'
| 'selected'
| 'active-selected'
| 'submitted'
| 'cancelled'
) => {
const label = option.label ?? String(option.value);
if (state === 'group-active') {
return `${color.cyan(S_CHECKBOX_ACTIVE)} ${label} ${
option.hint ? color.dim(`(${option.hint})`) : ''
}`;
} else if (state === 'selected') {
return `${color.green(S_CHECKBOX_SELECTED)} ${color.dim(label)}`;
} else if (state === 'cancelled') {
return `${color.strikethrough(color.dim(label))}`;
} else if (state === 'active-selected') {
return `${color.green(S_CHECKBOX_SELECTED)} ${label} ${
option.hint ? color.dim(`(${option.hint})`) : ''
}`;
} else if (state === 'active') {
return `${color.green(S_RADIO_ACTIVE)} ${label} ${
option.hint ? color.dim(`(${option.hint})`) : ''
}`;
} else if (state === 'group-inactive') {
return `${color.dim(S_CHECKBOX_INACTIVE)} ${color.dim(label)}`;
} else if (state === 'submitted') {
return `${color.dim(label)}`;
}
return `${color.dim(S_RADIO_INACTIVE)} ${color.dim(label)}`;
};

return new SearchPrompt({
options: opts.options,
initialValue: opts.initialValue,
maxItems: opts.maxItems,
render() {
const title = opts.message
? `${color.gray(S_BAR)}\n${symbol(this.state)} ${opts.message}\n`
: '';
const placeholder = opts.placeholder
? color.inverse(opts.placeholder[0]) + color.dim(opts.placeholder.slice(1))
: color.inverse(color.hidden('_'));
let value = '';
if (this.valueWithCursor) {
const pos = Math.min(Math.max(this.inputCursor - 1, 0));
value =
this.valueWithCursor.slice(0, pos) +
color.inverse(this.valueWithCursor[pos] || '') +
this.valueWithCursor.slice(pos + 1) || '';
} else {
value = placeholder;
}
switch (this.state) {
case 'submit':
return `${title}${color.gray(S_BAR)} ${opt(
{
label:
this.selected.map((item) => item.label || item.value).join(', ') ||
this.options[this.selectCursor].label ||
this.options[this.selectCursor].value,
} as Option<Value>,
'selected'
)}`;
case 'cancel':
return `${title}${color.gray(S_BAR)} ${opt(this.options[0], 'cancelled')}\n${color.gray(
S_BAR
)}`;
default: {
let getStatus = (option: Option<Value>, i: number) => {
if (this.maxItems > 1) {
if (i === this.selectCursor) {
return this.selected.some((item) => item.value === option.value)
? 'active-selected'
: 'group-active';
}
return this.selected.some((item) => item.value === option.value)
? 'selected'
: i === this.selectCursor
? 'group-active'
: 'group-inactive';
}
if (i === this.selectCursor) {
return this.selected.some((item) => item.value === option.value)
? 'active-selected'
: 'active';
}
return this.selected.some((item) => item.value === option.value)
? 'selected'
: i === this.selectCursor
? 'active'
: 'inactive';
};
return `${title}${color.cyan(S_BAR)}\n${color.cyan(S_INFO)} ${value}\n${color.cyan(
S_BAR
)} ${this.options
.map((option, i) => opt(option, getStatus(option, i)))
.join(`\n${color.cyan(S_BAR)} `)}\n${color.cyan(S_BAR_END)}\n`;
}
}
},
}).prompt() as Promise<MaxItems extends 1 ? Value | symbol : (Value | symbol)[]>;
};

export interface MultiSelectOptions<Value> {
message: string;
options: Option<Value>[];
Expand Down Expand Up @@ -699,8 +821,8 @@ export const spinner = () => {
code === 0
? color.green(S_STEP_SUBMIT)
: code === 1
? color.red(S_STEP_CANCEL)
: color.red(S_STEP_ERROR);
? color.red(S_STEP_CANCEL)
: color.red(S_STEP_ERROR);
process.stdout.write(cursor.move(-999, 0));
process.stdout.write(erase.down(1));
process.stdout.write(`${step} ${_message}\n`);
Expand Down
Loading