-
-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathautocomplete.ts
More file actions
375 lines (339 loc) · 11.5 KB
/
autocomplete.ts
File metadata and controls
375 lines (339 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import { styleText } from 'node:util';
import { AutocompletePrompt, settings } from '@clack/core';
import {
type CommonOptions,
S_BAR,
S_BAR_END,
S_CHECKBOX_INACTIVE,
S_CHECKBOX_SELECTED,
S_RADIO_ACTIVE,
S_RADIO_INACTIVE,
symbol,
} from './common.js';
import { limitOptions } from './limit-options.js';
import type { Option } from './select.js';
function getLabel<T>(option: Option<T>) {
return option.label ?? String(option.value ?? '');
}
function getFilteredOption<T>(searchText: string, option: Option<T>): boolean {
if (!searchText) {
return true;
}
const label = (option.label ?? String(option.value ?? '')).toLowerCase();
const hint = (option.hint ?? '').toLowerCase();
const value = String(option.value).toLowerCase();
const term = searchText.toLowerCase();
return label.includes(term) || hint.includes(term) || value.includes(term);
}
function getSelectedOptions<T>(values: T[], options: Option<T>[]): Option<T>[] {
const results: Option<T>[] = [];
for (const option of options) {
if (values.includes(option.value)) {
results.push(option);
}
}
return results;
}
interface AutocompleteSharedOptions<Value> extends CommonOptions {
/**
* The message to display to the user.
*/
message: string;
/**
* Available options for the autocomplete prompt.
*/
options: Option<Value>[] | ((this: AutocompletePrompt<Option<Value>>) => Option<Value>[]);
/**
* Maximum number of items to display at once.
*/
maxItems?: number;
/**
* Placeholder text to display when no input is provided.
*/
placeholder?: string;
/**
* Validates the value
*/
validate?: (value: Value | Value[] | undefined) => string | Error | undefined;
/**
* Custom filter function to match options against search input.
* If not provided, a default filter that matches label, hint, and value is used.
*/
filter?: (search: string, option: Option<Value>) => boolean;
}
export interface AutocompleteOptions<Value> extends AutocompleteSharedOptions<Value> {
/**
* The initial selected value.
*/
initialValue?: Value;
/**
* The initial user input
*/
initialUserInput?: string;
}
export const autocomplete = <Value>(opts: AutocompleteOptions<Value>) => {
const prompt = new AutocompletePrompt({
options: opts.options,
initialValue: opts.initialValue ? [opts.initialValue] : undefined,
initialUserInput: opts.initialUserInput,
filter:
opts.filter ??
((search: string, opt: Option<Value>) => {
return getFilteredOption(search, opt);
}),
signal: opts.signal,
input: opts.input,
output: opts.output,
validate: opts.validate,
render() {
const hasGuide = opts.withGuide ?? settings.withGuide;
// Title and message display
const headings = hasGuide
? [`${styleText('gray', S_BAR)}`, `${symbol(this.state)} ${opts.message}`]
: [`${symbol(this.state)} ${opts.message}`];
const userInput = this.userInput;
const options = this.options;
const placeholder = opts.placeholder;
const showPlaceholder = userInput === '' && placeholder !== undefined;
const opt = (option: Option<Value>, state: 'inactive' | 'active' | 'disabled') => {
const label = getLabel(option);
const hint =
option.hint && option.value === this.focusedValue
? styleText('dim', ` (${option.hint})`)
: '';
switch (state) {
case 'active':
return `${styleText('green', S_RADIO_ACTIVE)} ${label}${hint}`;
case 'inactive':
return `${styleText('dim', S_RADIO_INACTIVE)} ${styleText('dim', label)}`;
case 'disabled':
return `${styleText('gray', S_RADIO_INACTIVE)} ${styleText(['strikethrough', 'gray'], label)}`;
}
};
// Handle different states
switch (this.state) {
case 'submit': {
// Show selected value
const selected = getSelectedOptions(this.selectedValues, options);
const label =
selected.length > 0 ? ` ${styleText('dim', selected.map(getLabel).join(', '))}` : '';
const submitPrefix = hasGuide ? styleText('gray', S_BAR) : '';
return `${headings.join('\n')}\n${submitPrefix}${label}`;
}
case 'cancel': {
const userInputText = userInput
? ` ${styleText(['strikethrough', 'dim'], userInput)}`
: '';
const cancelPrefix = hasGuide ? styleText('gray', S_BAR) : '';
return `${headings.join('\n')}\n${cancelPrefix}${userInputText}`;
}
default: {
const barStyle = this.state === 'error' ? 'yellow' : 'cyan';
const guidePrefix = hasGuide ? `${styleText(barStyle, S_BAR)} ` : '';
const guidePrefixEnd = hasGuide ? styleText(barStyle, S_BAR_END) : '';
// Display cursor position - show plain text in navigation mode
let searchText = '';
if (this.isNavigating || showPlaceholder) {
const searchTextValue = showPlaceholder ? placeholder : userInput;
searchText = searchTextValue !== '' ? ` ${styleText('dim', searchTextValue)}` : '';
} else {
searchText = ` ${this.userInputWithCursor}`;
}
// Show match count if filtered
const matches =
this.filteredOptions.length !== options.length
? styleText(
'dim',
` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? '' : 'es'})`
)
: '';
// No matches message
const noResults =
this.filteredOptions.length === 0 && userInput
? [`${guidePrefix}${styleText('yellow', 'No matches found')}`]
: [];
const validationError =
this.state === 'error' ? [`${guidePrefix}${styleText('yellow', this.error)}`] : [];
if (hasGuide) {
headings.push(`${guidePrefix.trimEnd()}`);
}
headings.push(
`${guidePrefix}${styleText('dim', 'Search:')}${searchText}${matches}`,
...noResults,
...validationError
);
// Show instructions
const instructions = [
`${styleText('dim', '↑/↓')} to select`,
`${styleText('dim', 'Enter:')} confirm`,
`${styleText('dim', 'Type:')} to search`,
];
const footers = [`${guidePrefix}${instructions.join(' • ')}`, guidePrefixEnd];
// Render options with selection
const displayOptions =
this.filteredOptions.length === 0
? []
: limitOptions({
cursor: this.cursor,
options: this.filteredOptions,
columnPadding: hasGuide ? 3 : 0, // for `| ` when guide is shown
rowPadding: headings.length + footers.length,
style: (option, active) => {
return opt(
option,
option.disabled ? 'disabled' : active ? 'active' : 'inactive'
);
},
maxItems: opts.maxItems,
output: opts.output,
});
// Return the formatted prompt
return [
...headings,
...displayOptions.map((option) => `${guidePrefix}${option}`),
...footers,
].join('\n');
}
}
},
});
// Return the result or cancel symbol
return prompt.prompt() as Promise<Value | symbol>;
};
// Type definition for the autocompleteMultiselect component
export interface AutocompleteMultiSelectOptions<Value> extends AutocompleteSharedOptions<Value> {
/**
* The initial selected values
*/
initialValues?: Value[];
/**
* If true, at least one option must be selected
*/
required?: boolean;
}
/**
* Integrated autocomplete multiselect - combines type-ahead filtering with multiselect in one UI
*/
export const autocompleteMultiselect = <Value>(opts: AutocompleteMultiSelectOptions<Value>) => {
const formatOption = (
option: Option<Value>,
active: boolean,
selectedValues: Value[],
focusedValue: Value | undefined
) => {
const isSelected = selectedValues.includes(option.value);
const label = option.label ?? String(option.value ?? '');
const hint =
option.hint && focusedValue !== undefined && option.value === focusedValue
? styleText('dim', ` (${option.hint})`)
: '';
const checkbox = isSelected
? styleText('green', S_CHECKBOX_SELECTED)
: styleText('dim', S_CHECKBOX_INACTIVE);
if (option.disabled) {
return `${styleText('gray', S_CHECKBOX_INACTIVE)} ${styleText(['strikethrough', 'gray'], label)}`;
}
if (active) {
return `${checkbox} ${label}${hint}`;
}
return `${checkbox} ${styleText('dim', label)}`;
};
// Create text prompt which we'll use as foundation
const prompt = new AutocompletePrompt<Option<Value>>({
options: opts.options,
multiple: true,
filter:
opts.filter ??
((search, opt) => {
return getFilteredOption(search, opt);
}),
validate: () => {
if (opts.required && prompt.selectedValues.length === 0) {
return 'Please select at least one item';
}
return undefined;
},
initialValue: opts.initialValues,
signal: opts.signal,
input: opts.input,
output: opts.output,
render() {
// Title and symbol
const title = `${styleText('gray', S_BAR)}\n${symbol(this.state)} ${opts.message}\n`;
// Selection counter
const userInput = this.userInput;
const placeholder = opts.placeholder;
const showPlaceholder = userInput === '' && placeholder !== undefined;
// Search input display
const searchText =
this.isNavigating || showPlaceholder
? styleText('dim', showPlaceholder ? placeholder : userInput) // Just show plain text when in navigation mode
: this.userInputWithCursor;
const options = this.options;
const matches =
this.filteredOptions.length !== options.length
? styleText(
'dim',
` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? '' : 'es'})`
)
: '';
// Render prompt state
switch (this.state) {
case 'submit': {
return `${title}${styleText('gray', S_BAR)} ${styleText('dim', `${this.selectedValues.length} items selected`)}`;
}
case 'cancel': {
return `${title}${styleText('gray', S_BAR)} ${styleText(['strikethrough', 'dim'], userInput)}`;
}
default: {
const barStyle = this.state === 'error' ? 'yellow' : 'cyan';
// Instructions
const instructions = [
`${styleText('dim', '↑/↓')} to navigate`,
`${styleText('dim', this.isNavigating ? 'Space/Tab:' : 'Tab:')} select`,
`${styleText('dim', 'Enter:')} confirm`,
`${styleText('dim', 'Type:')} to search`,
];
// No results message
const noResults =
this.filteredOptions.length === 0 && userInput
? [`${styleText(barStyle, S_BAR)} ${styleText('yellow', 'No matches found')}`]
: [];
const errorMessage =
this.state === 'error'
? [`${styleText(barStyle, S_BAR)} ${styleText('yellow', this.error)}`]
: [];
// Calculate header and footer line counts for rowPadding
const headerLines = [
...`${title}${styleText(barStyle, S_BAR)}`.split('\n'),
`${styleText(barStyle, S_BAR)} ${styleText('dim', 'Search:')} ${searchText}${matches}`,
...noResults,
...errorMessage,
];
const footerLines = [
`${styleText(barStyle, S_BAR)} ${instructions.join(' • ')}`,
styleText(barStyle, S_BAR_END),
];
// Get limited options for display
const displayOptions = limitOptions({
cursor: this.cursor,
options: this.filteredOptions,
style: (option, active) =>
formatOption(option, active, this.selectedValues, this.focusedValue),
maxItems: opts.maxItems,
output: opts.output,
rowPadding: headerLines.length + footerLines.length,
});
// Build the prompt display
return [
...headerLines,
...displayOptions.map((option) => `${styleText(barStyle, S_BAR)} ${option}`),
...footerLines,
].join('\n');
}
}
},
});
// Return the result or cancel symbol
return prompt.prompt() as Promise<Value[] | symbol>;
};