Skip to content

Commit

Permalink
Include input in autocomplete prompt choices
Browse files Browse the repository at this point in the history
  • Loading branch information
ryangoree committed Oct 17, 2024
1 parent 5b3a7ef commit 8fa42e2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/slow-chairs-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"clide-js": patch
---

Changed the default bahavior of `autocomplete` and `autocompleteMultiselect` prompt options to include the current input as one of the choices.
44 changes: 43 additions & 1 deletion packages/clide-js/src/core/options/option-getter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export function createOptionGetter<

// Prompt for the option value if not provided and a prompt is provided
if (value === undefined && prompt) {
let didCancel = false;
const promptOptions: PromptOptions = {
type,
validate: validateFn
Expand All @@ -134,8 +135,49 @@ export function createOptionGetter<
: undefined,
// options passed to the getter take precedence over the config
...(typeof prompt === 'string' ? { message: prompt } : prompt),

onState: (state) => {
if (state.aborted || state.exited) {
didCancel = true;
}
return state;
},
};

// Add additional options for specific prompt types
switch (promptOptions.type) {
case 'autocomplete':
case 'autocompleteMultiselect': {
// These options are not part of the types package, but do exist.
(promptOptions as any).fallback ??= 'other';
(promptOptions as any).clearFirst ??= true;

// If no choices are matched, accept the input as-is
promptOptions.suggest ??= async (input, choices) => {
if (!input) return choices;
const lowerInput = input.toLowerCase();
const filtered = choices.filter((choice) => {
const lowerTitle = choice.title.toLowerCase();
if (
lowerTitle.slice(0, lowerInput.length) === lowerInput ||
lowerInput.slice(0, lowerTitle.length) === lowerTitle
) {
return true;
}
const lowerValue = choice.value?.toLowerCase();
return (
lowerValue &&
(lowerValue.slice(0, lowerInput.length) === lowerInput ||
lowerInput.slice(0, lowerValue.length) === lowerValue)
);
});
return [{ title: input }, ...filtered];
};

break;
}
}

// If an initial value is not provided, use the default value
if (
promptOptions.initial === undefined &&
Expand Down Expand Up @@ -170,7 +212,7 @@ export function createOptionGetter<
}

value = await client.prompt(promptOptions);
if (value === undefined) {
if (didCancel) {
onPromptCancel?.();
}
}
Expand Down

0 comments on commit 8fa42e2

Please sign in to comment.