We are going to design a command palette interaction model that is keyboard-first, supports fuzzy search, and provides contextual actions.
The command palette is a UI pattern that allows users to quickly access commands, settings, or navigate within an application by typing.
Key features:
Keyboard-first: The palette should be openable with a keyboard shortcut (e.g., Ctrl/Cmd+P). Navigation within the palette should be possible with arrow keys, Enter, Esc, etc.
Fuzzy search: The user can type a fuzzy search string to filter commands. Fuzzy search means that the matching is not necessarily contiguous, but the characters must appear in order (e.g., "abc" matches "a b c" or "axbycz").
Contextual actions: The commands shown may depend on the current context (e.g., current page, selected element, etc.). Also, some commands might have dynamic parameters or show additional UI (like a date picker for a "set date" command).
Design:
Components:
Command Palette Modal:
A modal that appears centered (or at a fixed position) with:
a. A search input at the top that automatically receives focus.
b. A list of command items (each with an icon, title, and optional shortcut or description).
c. Possibly a footer for additional information or actions.
Command Registration:
We need a way to register commands. Each command should have:
id: unique string
title: string (displayed)
description: optional string (shown as subtitle)
icon: optional (React component or SVG)
shortcut: optional (string, e.g., "Ctrl+P")
keywords: optional array of strings for fuzzy search (if not provided, use title and description)
action: function to execute when the command is selected. This function may return a promise, and we should handle loading states.
context: optional condition function (appState) => boolean that determines if the command is available in the current context.
group: optional string to group commands (e.g., "Navigation", "Editing", etc.)
Fuzzy Search Algorithm:
We'll use a simple fuzzy search: given a pattern and a string, we want to check if the pattern's characters appear in order in the string (case-insensitive).
We can also assign scores for matches (like consecutive matches, matches at word boundaries) but for simplicity we can start with a boolean match and then rank by order of appearance? Actually, we want to rank by:
Matches in title are more important than in description or keywords.
Consecutive matches (like "abc" in "abc") are better than non-consecutive.
We might also consider the position: earlier in the string is better.
However, note that fuzzy search can be complex. We might use an existing library (like fuzzy-score or fuse.js) but for the purpose of this design, we can implement a simple version.
State Management:
We need to store:
whether the palette is open
the current search string
the list of filtered commands (based on search and context)
the selected index (highlighted command in the list)
loading state (if action of a command is being executed)
Keyboard Navigation:
When the palette is open:
ArrowDown: move selection down (wrap around)
ArrowUp: move selection up (wrap around)
Enter: execute the selected command
Esc: close the palette
Any key: update the search input (unless it's a navigation key)
Also, we might want to support:
- Typeahead: if the user types a string that exactly matches the beginning of a command title, we can select that command? But with fuzzy search it's not necessary.
Contextual Actions:
The set of commands that are available can change based on the current app state (e.g., if something is selected, if we are on a particular page, etc.).
We can recompute the available commands whenever the palette is opened and also when the app state changes (but note: the palette might be open while the app state changes, so we need to update the list accordingly).
Dynamic Commands:
Some commands might need to ask for input (like a file name) or show a sub-palette. We can handle this by having the action return a promise that resolves to a new set of commands? Or we can have a two-step command: first select the command, then ask for input and then execute.
Alternatively, we can design the action function to be able to return a React component to show (like a form) and then on submit, execute. But that might complicate the action model.
Another idea: commands can have a params property that defines what parameters they need. When the user selects a command that requires parameters, we show a form in the palette to fill them, then execute.
However, to keep it simple, we can say that the action function can return a promise, and while it's running we show a loading indicator. For more complex interactions, the action can open a new modal or change the app state.
Performance:
We might have a large number of commands (hundreds). We need to filter and sort quickly. We can debounce the search input if we are doing expensive operations.
Implementation Plan:
We'll create a React context for the command palette so that we can open it from anywhere and also register commands globally.
Steps:
Create a CommandPaletteProvider that holds the state and provides:
openPalette function
registerCommand function
unregisterCommand function
The provider will maintain:
commands: Command[] (all registered commands)
filteredCommands: Command[] (computed based on search string and context)
search: string
selectedIndex: number
isOpen: boolean
isLoading: boolean (optional, for when an action is running)
The filtering logic:
We'll have a function getAvailableCommands(appState) that returns commands that are available (context condition true) and then filter by fuzzy search.
We'll compute a score for each command based on:
Title match: exact match at the beginning? consecutive? etc.
We can use a simple fuzzy matching function that returns a score (higher is better) or just a boolean and then sort by the order of the first character match? Actually, we want to sort by relevance.
Let's define a scoring function:
code
code
We should manage focus properly. When the palette opens, focus the search input. When the user navigates with arrows, we should move the highlight and also scroll the list to keep the highlighted item in view.
code
We can use `useEffect` to set focus on the input when the palette opens.
Also, we should trap focus inside the palette (with a focus trap) and allow closing with Esc.
11. Implementation:
code
We'll create:
- CommandPaletteContext: to hold the state and provide openPalette, registerCommand, etc.
- CommandPaletteModal: the actual modal component that is rendered when isOpen is true.
The modal will use the filteredCommands and the current selectedIndex to render the list.
We'll handle keyboard events on the search input and also on the modal (to catch arrow keys when the input is not focused? Actually, we want to always capture arrow keys when the modal is open).
We can attach a keydown listener on the modal (or on the document when open) to handle navigation keys.
Steps in the modal:
- When open, focus the search input.
- On keydown in the input: update search state (if not arrow keys, etc.)
- On keydown in the modal (or we can capture on the document):
ArrowDown: increment selectedIndex (modulo length)
ArrowUp: decrement selectedIndex
Enter: execute the selected command
Esc: close palette
We must prevent default for these keys to avoid scrolling the page.
Also, we should handle typing in the input: the input's onChange updates the search state.
12. Example usage:
code
const { openPalette } = useContext(CommandPaletteContext);
// In a component, on keydown (like Ctrl+P) we call openPalette.
// Somewhere else, we register commands:
registerCommand({
id: 'new-file',
title: 'New File',
description: 'Create a new file',
icon: <FileIcon />,
action: () => { /* ... */ },
group: 'File'
});
13. Additional features:
code
- Show keyboard shortcuts for commands that have them.
- Show description in the list (maybe in a smaller font under the title).
- Show icons if provided.
14. Styling:
code
We can use a CSS-in-JS solution or plain CSS. We'll leave that to the implementation.
15. Potential issues:
code
- If the appState changes while the palette is open, we need to recompute the available commands and the filtered list. We can use an effect that runs when appState changes and update the filteredCommands accordingly.
But note: the appState might be large and change frequently. We might want to memoize the context function and only recompute when the appState changes in a way that affects the context? We can let the consumer provide a memoized version of the appState that only changes when needed.
Alternatively, we can have the provider accept a `getAppState` function that returns the relevant part of the state for the command palette? Or we can just pass the entire state and rely on the consumer to memoize.
We'll do:
<CommandPaletteProvider appState={appState}>
Then, in the provider, we use `useMemo` to compute the available commands when appState changes.
16. Code Structure:
code
17. Given the complexity, we might decide to not support dynamic parameters in the first version and just have a simple action without parameters. Then we can extend later.
code
Let's start with:
- No parameter forms. The action function can receive the appState and return a boolean for closing.
Then, we can add parameter support in a future version.
18. Revised plan without parameters:
code
We remove the `params` and `getParams` from the Command interface.
The action function:
action: (appState: any) => Promise<boolean | void> | boolean | void
Then, in handleSelect:
const result = await command.action(appState);
if (result !== false) {
closePalette();
} else {
// do nothing, keep the palette open.
}
And we don't have currentCommand state.
19. But what about commands that need input? They can open their own modal? That's acceptable.
Now, we design the components:
CommandPaletteProvider:
It provides:
openPalette, closePalette, registerCommand, unregisterCommand, and the state (if needed by children?).
We might not need to expose the state, but we do need to render the modal. So we can have:
code
{isOpen && <CommandPaletteModal />}
inside the provider.
CommandPaletteModal:
It uses the context to get:
isOpen, search, setSearch, filteredCommands, selectedIndex, setSelectedIndex, handleSelect, isLoading, error, closePalette.
It renders:
- A search input (with the current search value, and onChange updates the context's search)
- A list of commands (mapped from filteredCommands). The selected one is highlighted.
- Each command item: shows icon, title, description, shortcut.
- If isLoading, show a spinner? Or disable the list? We can disable the list and show a loading indicator next to the selected command? Or in the footer.
We also handle keyboard events:
code
- On the modal (or on the search input) we capture:
ArrowDown, ArrowUp: change selectedIndex
Enter: call handleSelect with the selected command
Esc: closePalette
We also capture typing in the search input.
We must manage focus: when the modal opens, focus the search input.
We use a focus trap: when the modal is open, tab and shift+tab should cycle through the search input and the command list? But we don't have focusable elements in the list? We can make each command item focusable (with tabIndex) but we are using arrow keys for navigation.
Alternatively, we can only have the search input focusable and use arrow keys to change the selection. Then we don't need to manage focus in the list.
So:
The search input is the only focusable element in the modal.
The list is not focusable, but we render the selected item with a highlight.
Then, when the user presses arrow keys, we change the selectedIndex and update the highlight.
We also need to scroll the list so that the selected item is in view. We can use a ref on the list and then scroll the selected item into view.
However, note that the above design does not support command grouping in the modal when there's a search? We are grouping only when there's no search? Actually, in the filteredCommands we are not grouping. We are just sorting by group and title when there's no search.
code
When there's search, we are not grouping. We can change:
In the filteredCommands, we can keep the group information and then in the modal we can group by group? But then the order of groups might be broken because we are sorting by score.
We can do:
In the modal, we can group the filteredCommands by group (if group exists) and then render each group with a header.
But then the selectedIndex is across all groups? We have a flat list of filteredCommands, so the selectedIndex is the index in that flat array. But when we render groups, we have to compute the position of each item in the flat list? Actually, we are rendering the flat list, but with group headers in between.
We can change the filteredCommands to be an array of either a group header or a command? Then the selectedIndex would skip the group headers? That complicates.
Alternatively, we can render the groups and then the selectedIndex is the index in the flat list of commands (without group headers). But then we have to map the selectedIndex to the actual command and also scroll to the right element.
Let's not support groups in the modal for now. We can just show the commands in a flat list, sorted by group and title when no search, and by score when searching.
We can show the group as a prefix in the title? Or we can show a group column? We can leave that to the styling.
Alternatively, we can render the list without groups and just sort by group and then by title when no search. That way, commands from the same group are together.
So in the no-search case, we sort by group and title. In the search case, we sort by score and then by title.
This is acceptable.
32. Given the time, we'll go with the flat list.
Let's code the modal without groups.
We'll also add a way to close the palette when clicking outside? We can add a backdrop that closes on click.
We'll wrap the modal content in a backdrop div that covers the screen and has a semi-transparent background. Then we stop propagation on the modal content so that clicking inside doesn't close.
But note: we want to close when clicking outside. We can do:
We'll also handle the escape key on the backdrop? Actually, we are already handling on the modal.
Now, we write the code.
However, note that the above design is a basic one. We might need to adjust for production use.
Let's write the code in a structured way.
Due to the complexity and length, I'll provide a simplified version of the code without the parameter mode and without groups.
In your app:
<CommandPaletteProvider appState={appState}>
<YourApp />
</CommandPaletteProvider>
Then, in any component, you can register commands:
const { registerCommand } = useCommandPalette();
useEffect(() => {
const unregister = registerCommand({
id: 'new-file',
title: 'New File',
description: 'Create a new file',
icon: <FileIcon />,
action: (appState) => {
// do something
return true; // close palette
},
group: 'File',
});
return unregister;
}, [registerCommand]);
And to open the palette:
const { openPalette } = useCommandPalette();
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
e.preventDefault();
openPalette();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [openPalette]);
39. Limitations:
code
- The fuzzy search is simple and might not be as good as fuse.js.
- No support for parameters.
- No support for nested groups or categories.
- No support for dynamic commands that change based on the current selection (except via context function).
40. Future improvements:
code
- Use a better fuzzy search algorithm (like match-elsewhere).
- Add support for command parameters.
- Add support for command groups with headers.
- Add support for recent commands or frequently used commands.
- Add support for command history (up/down arrow to cycle through previous searches?).
- Add support for mouse selection (we have onClick and onMouseEnter).
- Add support for keyboard shortcuts display and execution (like pressing the shortcut key directly in the palette?).
This is a starting point.
I'll design a comprehensive command palette interaction model that prioritizes keyboard navigation, intelligent fuzzy search, and context-aware actions. This pattern is inspired by tools like VS Code, Raycast, and Alfred.
User: ⌘K (palette opens, input focused)
↓ types "new fi"
↓ sees "File: New" (score: 95), "File: Find" (score: 70)
↓ ArrowDown to "File: New"
↓ Enter (creates new file)
↓ Palette closes
Contextual Example:
code
When in editor with text selected:
- "Copy" appears (score: +20 boost)
- "Search web for [selection]" appears (dynamic)
- "Format code" only if language matches
This model provides zero mouse interaction for power users while maintaining discoverability for casual users through visual grouping, descriptions, and previews. The fuzzy search is forgiving yet precise, and context ensures relevance.
score = 0
pattern = search string in lowercase
text = (title + ' ' + description + ' ' + keywords.join(' ')).toLowerCase()
We'll find the indices of the pattern characters in text in order.
If we can't find, score = -1 (exclude).
Otherwise, we can compute:
- consecutive bonus: if the matched characters are consecutive in the text, we give a bonus.
- word boundary bonus: if a matched character is at the start of a word (or after a space) we give a bonus.
- position bonus: earlier the first match, the better.
But note: we want to match in order, but we might also want to match the pattern as a substring? Actually, fuzzy search is about matching in order but not necessarily contiguous.
We can use the following algorithm:
let score = 0;
let lastIndex = -1;
for each char in pattern:
index = text.indexOf(char, lastIndex+1)
if index == -1: return -1
if index == lastIndex+1: score += 10 // consecutive
if (index == 0 || text[index-1] == ' ') score += 5 // word boundary
lastIndex = index
Then, we can also subtract the first index (to prefer earlier matches) but we are already adding word boundary bonuses.
However, note that we are matching in order and the above gives a higher score for consecutive and word boundary.
We can also add a bonus for matches in the title (if the matched part is in the title, we can boost the score). We can split the text into title and rest and give a multiplier for matches in the title.
Alternatively, we can compute two scores: one for title and one for the rest, and then combine.
Let's keep it simple and use one text string (title + ' ' + description + ' ' + keywords) but then we lose the ability to weight title more.
We can do:
let titleScore = 0;
let restScore = 0;
// match in title
let titleText = command.title.toLowerCase();
let restText = (command.description + ' ' + command.keywords.join(' ')).toLowerCase();
Then compute the same algorithm for the pattern in titleText and restText separately and then combine:
totalScore = (titleScore * 2) + restScore;
But note: the pattern might match across title and rest? That's not captured. So maybe we should do the matching on the combined string but then check which part of the string the matches are in and give more weight to title.
Alternatively, we can do:
combined = title + ' ' + rest
Then we do the fuzzy matching on combined, but for each matched character, if its index is within the title length, we give an extra point.
However, this is getting complex.
Let's use an existing fuzzy scoring library? But for the purpose of this design, we can assume we have a `fuzzyScore(pattern, text)` function that returns a number (higher is better) and we can then sort by that score.
We can implement a simple version:
function fuzzyScore(pattern, text) {
pattern = pattern.toLowerCase();
text = text.toLowerCase();
let score = 0;
let patternIndex = 0;
let textIndex = 0;
let consecutiveCount = 0;
let lastMatchedIndex = -1;
while (patternIndex < pattern.length && textIndex < text.length) {
if (pattern[patternIndex] === text[textIndex]) {
// Consecutive bonus
if (textIndex === lastMatchedIndex + 1) {
consecutiveCount++;
} else {
consecutiveCount = 1;
}
score += consecutiveCount * 10; // consecutive bonus
if (textIndex === 0 || text[textIndex-1] === ' ') {
score += 5; // word boundary bonus
}
patternIndex++;
lastMatchedIndex = textIndex;
}
textIndex++;
}
if (patternIndex === pattern.length) {
// All pattern characters matched
// Bonus for matching the entire pattern? But we already have consecutive and word boundary.
// Also, we can subtract the starting index? Actually, we want earlier matches to be better? We are already adding word boundary at the beginning.
// But if the match is at the end of a long string, it's not as good. So we can subtract the index of the first matched character?
// Alternatively, we can add a bonus for matching the beginning of the string? We already have word boundary for the first character if at index 0.
// However, note that we are not capturing the overall position. Let's add:
score += (text.length - lastMatchedIndex); // This gives higher score for matches closer to the beginning? Actually, lastMatchedIndex is the last matched index. We want the first matched index to be small.
// Actually, we want the first matched character to be as early as possible. So we can record the first matched index.
// Let's change:
// We'll record the index of the first match and then subtract it? Or add (text.length - firstMatchedIndex) but then if firstMatchedIndex is 0, we get text.length, which is large.
// Alternatively, we can do:
// score += (text.length - firstMatchedIndex) * 10; but then we are already adding word boundary for the first character if at 0.
// Actually, the consecutive and word boundary bonuses might be enough.
return score;
} else {
return -1; // no match
}
}
This is just a simple example. We might want to adjust.
But note: we are matching in order, and we are giving bonuses for consecutive and word boundaries. We are not allowing skips? Actually, we are allowing skips because we increment textIndex until we find the pattern character.
However, the above algorithm does not skip non-matching characters? It does because we increment textIndex in every step. But note: if we don't match, we just move textIndex. So it's a simple linear scan.
But what if the pattern is "abc" and the text is "a x b c"? We will match:
a: at index0 -> score 10 (consecutive count 1) and word boundary at 0 -> +5 -> 15
then we look for b: we start at index1, then index2 (x) doesn't match, index3 (b) matches -> consecutive? lastMatchedIndex was 0, so textIndex=3 is not consecutive, so consecutiveCount=1 -> score 10 (so total 25) and then word boundary? at index3, text[2] is space -> word boundary -> +5 -> total 30.
then c: at index4 -> consecutive? lastMatchedIndex=3, so consecutive -> consecutiveCount=2 -> score 20 -> total 50.
So we get 50.
If the pattern is "abc" and text is "a b c", we get:
a: index0 -> 15
b: index2 (because index1 is space) -> consecutive? no, because lastMatchedIndex=0, so not consecutive -> 10 + word boundary (because at index2, text[1] is space) -> +5 -> total 30 so far? Wait, we had 15 then we add 15? Actually, we are adding 10 for consecutive? No, for b we have consecutiveCount=1 -> 10, and word boundary -> 5 -> so 15 for b -> total 30.
c: index4 -> consecutive? no (last was 2) -> 10 + word boundary (index4, text[3] is space) -> 15 -> total 45.
So consecutive matches get a higher score.
This seems reasonable.
But note: we are not considering the length of the text. A match in a short text might be better? We can adjust.
However, for simplicity, we can use an existing library. But for the sake of the design, we assume we have a fuzzyScore function.
Filtering and Sorting:
We'll compute the available commands by:
Filtering by context: only commands that return true for context?.(appState) are included.
Then, if there is a search string, we compute the fuzzy score for each command (using the command's title, description, and keywords). We can combine these into one string: command.title + ' ' + command.description + ' ' + command.keywords.join(' ').
We then sort by score (descending) and then by title (ascending) if scores are equal? But note: we might want to show grouped commands? We can also sort by group.
However, note that the user might have registered commands with groups. We might want to keep the groups together? But then the fuzzy search might break the group order.
We can do:
filteredCommands = availableCommands
.map(command => {
const score = fuzzyScore(search, command.title + ' ' + (command.description || '') + ' ' + (command.keywords || []).join(' '));
return { command, score };
})
.filter(item => item.score > 0)
.sort((a, b) => {
if (a.score !== b.score) {
return b.score - a.score; // descending
}
// If same score, then by group? or by title?
return a.command.title.localeCompare(b.command.title);
})
.map(item => item.command);
But note: we might want to show commands in a specific order (like by group and then by title) when there's no search? When there's no search, we can show all available commands in a predefined order (by group and title). So we can have:
if (search.trim() === '') {
// show in predefined order: by group (if any) and then by title
filteredCommands = availableCommands.sort((a, b) => {
const groupA = a.group || '';
const groupB = b.group || '';
if (groupA !== groupB) {
return groupA.localeCompare(groupB);
}
return a.title.localeCompare(b.title);
});
} else {
// do fuzzy search and sort by score
}
Context:
We need to provide the current app state to the context condition function. The app state might be large, so we can let the consumer of the palette provide a selector or the entire state? We can have:
Then, when we filter, we pass the appState to the context function.
Action Execution:
When the user selects a command (by pressing Enter or clicking), we call the command's action function. This function might be async. We should set a loading state so that the user knows something is happening.
We can do:
const handleSelect = async (command) => {
setIsLoading(true);
try {
await command.action(appState); // we might want to pass the appState and a way to update it? Or the action can be self-contained.
// After action, we might want to close the palette? Not necessarily. Some actions might be like "toggle something" and we want to keep the palette open? Maybe we let the action decide by returning a boolean? Or we always close? Let's always close on action, but if the action fails, we show an error and keep open? Actually, we can let the action throw an error and we catch it and show an error message.
code
// But note: some actions might be non-destructive (like copy to clipboard) and we might want to keep the palette open for more actions. So we can have:
// Option 1: always close on successful action.
// Option 2: never close, but then the user might run multiple actions.
// Let's provide a way: the action can return { close: boolean }? Or we can have a setting in the command: `closeAfterExecute: boolean` (default true).
// Alternatively, we can have two types of actions:
// - one that executes and closes (most commands)
// - one that executes and stays open (like a toggle) but then the user can press Esc to close.
// We can decide: by default, close after execute. But if the command returns false (or a specific object) then don't close.
// Let's do: the action function can return a boolean (or a promise that resolves to a boolean) that indicates if we should close the palette.
const shouldClose = await command.action(appState);
if (shouldClose !== false) {
closePalette();
}
} catch (error) {
// Show error in the palette? We can set an error state and display it.
setError(error.message);
} finally {
setIsLoading(false);
}
};
Dynamic Parameters:
If a command requires parameters (like a file name), we can have:
Then, when the user selects the command, instead of executing the action, we show a form in the palette for the parameters. We can have a state for the current command being parameterized and the current parameter values.
But this complicates the model. Alternatively, we can have the action function return a promise that resolves to a React node (a form) and then we show that form in the palette? That would break the separation.
Another idea: the action function can be a two-step function. The first step returns the parameters needed, and then we show a form, and then the second step executes with the parameters.
We can design the command as:
action: (params) => Promise
and then we have a separate getParams function that returns the parameter definitions.
But then we need to store the intermediate state.
Alternatively, we can have a execute function that is called with the command and the current app state, and if the command requires parameters, we show a form and then call the action with the filled parameters.
We can change the handleSelect:
if (command.params) {
// Show parameter form for this command
setCurrentCommand(command);
setParams(initialParams); // we can compute initialParams from command.params
} else {
// execute directly
}
Then, when the form is submitted, we call the action with the params and then close if needed.
But note: the parameter form might be complex (like a date picker). We can let the command provide a React component for the parameter form? That would be too heavy.
Alternatively, we can have simple parameter types: string, number, boolean, select (with options). We can generate a form automatically.
Then, when we are in the parameter mode, we show a form with inputs for each param.
But note: the command might need dynamic parameters (like based on current selection). We can let the getParams function receive the appState and return the param definitions.
Then, in the palette, if currentCommand is set, we show the form instead of the command list? Or we can show the form in the same list? We can replace the list with the form.
But note: we might want to cancel the parameter entry (Esc) and go back to the list.
We can have:
if (currentCommand) {
// Show parameter form for currentCommand
} else {
// Show command list
}
And when the form is submitted, we call the action and then reset currentCommand and close (if needed).
Groups:
We might want to group commands in the list. We can render the list with group headers. We need to adjust the filtering and sorting to preserve group order? Actually, when we filter, we might break the groups.
We can do:
In the list, we group by command.group (if any). Then within each group, we sort by the score or by title.
But when we filter by search, we might get commands from multiple groups. We can still group them by the same group property.
So, when rendering, we can:
const groups = new Map<string, Command[]>();
filteredCommands.forEach(cmd => {
const group = cmd.group || 'Other';
if (!groups.has(group)) groups.set(group, []);
groups.get(group).push(cmd);
});
Then we render each group with a header.
Debouncing:
We don't want to run the fuzzy search on every keystroke if the list is huge. We can debounce the search input.
But note: the search input is controlled by the state, and we compute filteredCommands in a useEffect or useMemo. We can use a debounced value for the search.
Alternatively, we can use a library for fuzzy search that is fast enough. But if we have thousands of commands, we might need to debounce.
We can do:
const debouncedSearch = useDebounce(search, 150);
Then compute filteredCommands based on debouncedSearch.
Accessibility:
We'll create:
types.ts
context.tsx
palette.tsx
utils/fuzzy.ts
Let's define the types:
interface Command {
id: string;
title: string;
description?: string;
icon?: React.ReactNode;
shortcut?: string;
keywords?: string[];
action: (params?: Record<string, any>, appState?: any) => Promise<boolean | void> | boolean | void;
context?: (appState: any) => boolean;
group?: string;
params?: ParamDefinition[]; // if present, we show a form before action
getParams?: (appState: any) => ParamDefinition[]; // dynamic params
}
interface ParamDefinition {
name: string;
type: 'string' | 'number' | 'boolean' | 'select';
label: string;
options?: Array<{label: string, value: string}>; // for select
defaultValue?: any;
}
In the provider:
const [isOpen, setIsOpen] = useState(false);
const [search, setSearch] = useState('');
const [selectedIndex, setSelectedIndex] = useState(0);
const [commands, setCommands] = useState<Command[]>([]);
const [currentCommand, setCurrentCommand] = useState<Command | null>(null);
const [paramValues, setParamValues] = useState<Record<string, any>>({});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// We'll have a debouncedSearch
const debouncedSearch = useDebounce(search, 150);
// Compute available commands based on context and appState
const availableCommands = useMemo(() => {
return commands.filter(cmd => !cmd.context || cmd.context(appState));
}, [commands, appState]);
// Compute filteredCommands based on debouncedSearch and availableCommands
const filteredCommands = useMemo(() => {
if (debouncedSearch.trim() === '') {
// No search, return sorted by group and title
return [...availableCommands].sort((a, b) => {
const groupA = a.group || '';
const groupB = b.group || '';
if (groupA !== groupB) {
return groupA.localeCompare(groupB);
}
return a.title.localeCompare(b.title);
});
} else {
const pattern = debouncedSearch.toLowerCase();
return availableCommands
.map(cmd => {
const text = (cmd.title + ' ' + (cmd.description || '') + ' ' + (cmd.keywords || []).join(' ')).toLowerCase();
const score = fuzzyScore(pattern, text);
return { cmd, score };
})
.filter(item => item.score > 0)
.sort((a, b) => b.score - a.score || a.cmd.title.localeCompare(b.cmd.title))
.map(item => item.cmd);
}
}, [availableCommands, debouncedSearch]);
// When filteredCommands change, adjust selectedIndex to be within bounds
useEffect(() => {
if (selectedIndex >= filteredCommands.length) {
setSelectedIndex(Math.max(0, filteredCommands.length - 1));
}
}, [filteredCommands, selectedIndex]);
// Register command
const registerCommand = (command: Command) => {
setCommands(prev => [...prev, command]);
// return an unsubscribe function?
return () => {
setCommands(prev => prev.filter(c => c.id !== command.id));
};
};
// Open palette
const openPalette = () => {
setIsOpen(true);
setSearch('');
setSelectedIndex(0);
setCurrentCommand(null);
setError(null);
};
// Close palette
const closePalette = () => {
setIsOpen(false);
setSearch('');
setSelectedIndex(0);
setCurrentCommand(null);
setError(null);
};
// Handle command selection (when Enter is pressed)
const handleSelect = async (command: Command) => {
setIsLoading(true);
setError(null);
try {
let paramsToUse = paramValues;
// If the command has dynamic params (via getParams) and we are in the parameter mode for this command?
// Actually, we are in parameter mode if currentCommand is set and equals to command? But note: we might have set currentCommand when the command was selected (if it has params). So we should check if currentCommand is set and then use the paramValues we have.
// Alternatively, we can have: when the user selects a command that has params (or getParams returns non-empty), we setCurrentCommand and show the form. Then the form submission calls handleSelect again with the same command but now with params filled.
// So we can change: when the command is selected and it has params (or getParams returns non-empty), we setCurrentCommand and do not execute the action yet.
// Let's adjust:
if (currentCommand) {
// We are in parameter mode for currentCommand. The command we are handling is the currentCommand.
// We have paramValues from the form.
paramsToUse = paramValues;
} else {
// Check if we need to show parameter form
const paramDefs = command.params || (command.getParams?.(appState) || []);
if (paramDefs.length > 0) {
// We need to show the parameter form for this command.
setCurrentCommand(command);
// Initialize paramValues with defaults
const initialParams: Record<string, any> = {};
paramDefs.forEach(param => {
initialParams[param.name] = param.defaultValue;
});
setParamValues(initialParams);
setIsLoading(false);
return; // do not execute action yet
}
}
// Now execute the action
const result = await command.action(paramsToUse, appState);
// If the action returns false, we don't close
if (result !== false) {
closePalette();
} else {
// We don't close, so we reset the current command and paramValues? But the user might want to run the same command again with different parameters?
// We can leave the palette open and reset the search? Not sure.
// Let's close the parameter form and go back to the list? But the command might have changed the appState and we want to show updated list.
// We can reset the currentCommand and paramValues and setSearch('') to refresh the list? But then the user loses the search string.
// Alternatively, we can just reset the currentCommand and paramValues and keep the search string? But then the list might be different.
// We can do: after executing, we reset currentCommand and paramValues, and re-run the filtering (which will happen because appState might have changed). But we don't change the search string.
setCurrentCommand(null);
setParamValues({});
}
} catch (err) {
setError(err.message);
} finally {
setIsLoading(false);
}
};
// We'll also handle the form change for parameters.
This is getting complex. We might want to separate the parameter mode into a separate component and state.
But note: the modal needs access to the state and functions like setSearch, setSelectedIndex, handleSelect, etc. So we might want to provide a richer context.
Alternatively, we can have the modal use the same context and then we provide all the state and functions in the context.
Let's define:
code
interface CommandPaletteContextValue {
isOpen: boolean;
search: string;
setSearch: (search: string) => void;
selectedIndex: number;
setSelectedIndex: (index: number) => void;
filteredCommands: Command[];
handleSelect: (command: Command) => Promise<void>;
isLoading: boolean;
error: string | null;
closePalette: () => void;
registerCommand: (command: Command) => () => void;
appState: any; // maybe we don't want to expose the entire appState? But the modal doesn't need it.
}
Then the provider will provide this.
But note: the registerCommand is used by components to register commands, so we need to expose it.
Then, in a component, we can call useCommandPalette().openPalette() to open.
And we can use useCommandPalette().registerCommand to register.
However, note that the appState is also in the context? We don't want the modal to depend on the entire appState? Actually, the modal uses filteredCommands which is computed from appState, so we don't need to expose appState.
But the registerCommand might need the appState? No, the command's context function will be called by the provider with the appState.
So we don't need to expose appState in the context.
const [appState, setAppState] = useState(initialState); // but we don't want to manage appState in the palette provider? The palette provider should not own the appState. We should let the parent pass the appState as a prop.
So:
code
<CommandPaletteProvider appState={appState}>
Then, in the provider, we compute availableCommands and filteredCommands using that appState.
A ref for the list container (to scroll the selected item into view)
We'll handle:
useEffect(() => {
if (isOpen) {
inputRef.current?.focus();
}
}, [isOpen]);
useEffect(() => {
// Scroll the selected item into view when selectedIndex changes
const selectedNode = listRef.current?.children[selectedIndex] as HTMLElement;
selectedNode?.scrollIntoView({ block: 'nearest' });
}, [selectedIndex]);
Keyboard events:
We'll attach a keydown handler to the modal (or to the document when open). But note: we want to capture keys even when the input is focused? Yes.
We can attach to the modal div.
const handleKeyDown = (e: React.KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setSelectedIndex(prev => (prev + 1) % filteredCommands.length);
break;
case 'ArrowUp':
e.preventDefault();
setSelectedIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length);
break;
case 'Enter':
e.preventDefault();
if (filteredCommands[selectedIndex]) {
handleSelect(filteredCommands[selectedIndex]);
}
break;
case 'Escape':
e.preventDefault();
closePalette();
break;
default:
// Let the input handle the key (for typing)
break;
}
};
But note: when the user types, we don't want to prevent default because we want the input to get the character. So we only prevent for the navigation keys.
We also want to handle typing in the input: the input's onChange should call setSearch.
We'll render:
We should also handle the case when there are no commands:
{filteredCommands.length === 0 && No commands found}
Styling:
We'll leave that to the user. We can provide a basic CSS file or use CSS-in-JS.
Debounce hook:
We can write a simple useDebounce:
function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
We'll implement a simple one as described. But note: we might want to improve it.
However, for simplicity, we can use an existing library. But to avoid dependencies, we'll write a simple one.
We'll write:
function fuzzyScore(pattern: string, text: string): number {
pattern = pattern.toLowerCase();
text = text.toLowerCase();
code
let score = 0;
let patternIndex = 0;
let textIndex = 0;
let consecutiveCount = 0;
let firstMatchIndex = -1;
while (patternIndex < pattern.length && textIndex < text.length) {
if (pattern[patternIndex] === text[textIndex]) {
if (firstMatchIndex === -1) {
firstMatchIndex = textIndex;
}
if (textIndex === (firstMatchIndex + consecutiveCount)) {
consecutiveCount++;
} else {
consecutiveCount = 1;
}
score += consecutiveCount * 10; // consecutive bonus
if (textIndex === 0 || text[textIndex - 1] === ' ') {
score += 5; // word boundary bonus
}
patternIndex++;
}
textIndex++;
}
if (patternIndex === pattern.length) {
// All pattern characters matched
// Bonus for matching the entire pattern? Already have consecutive.
// Bonus for early match: subtract the firstMatchIndex? Actually, we want to encourage early matches.
// We can add:
score += (text.length - firstMatchIndex); // This gives higher score for earlier first match? Actually, if firstMatchIndex is 0, we add text.length, which is large. But if firstMatchIndex is at the end, we add a small number.
// But note: we are already adding word boundary for the first character if at the beginning.
return score;
} else {
return -1;
}
}
This is a simple version. It might not be perfect, but it's a start.
Edge cases:
When there are no commands, we show "No commands found".
When there's an error, we show it and keep the palette open? Or close? We show the error and keep open so the user can try again.
When a command is loading, we disable the list? We can set isLoading and then in the handleSelect we set isLoading to true. Then we can disable the list and show a spinner.
We might want to prevent multiple simultaneous executions? We set isLoading and then disable the list and the input? Actually, we can disable the input and the list when loading.
Final note:
This is a complex component and we might need to adjust based on actual usage.
We'll provide a basic implementation and then iterate.
Let's code the useDebounce and fuzzyScore in separate files.
utils/debounce.ts
utils/fuzzy.ts
We'll also provide a way to set the appState from the outside? Actually, the appState is passed as a prop to the provider and we assume the parent re-renders the provider when appState changes.