Command Palette
ProSpotlight-style launcher with four looks, 3 sizes, fuzzy search, ⌘K shortcut, grouped results, nested pages, per-command actions, a preview pane, prefix scopes, pinned and suggested commands, an Ask AI fallback, query highlighting, recent history, async/remote loading, disabled commands and keyboard navigation.
import { SvCommandPaletteComponent } from '@styloviz-pro/command-palette';Demo & usage
Basic usage
Usage example — open the gallery for the full interactive demo.
An interactive demo for this component lives in the gallery.
Open live demoMore examples
Remote search without the race
Cancelling the search the user typed past
Dark variant, large, fuzzy
Custom shortcut & no recents
Remote/async results
When to use
Giving power users a fast keyboard launcher for actions and navigation. Apps with many commands where menus would be unwieldy. Remote/async command sources — drive `[loading]` from `queryChange`. For searching data records specifically, use the Search Bar.
Async states
- loading
- error
- retry
Item identity & owned state
- Restorable state
- pinnedCommandIds
- recentCommandIds
Bind these to put a saved view back — the open sections, the hidden columns, the selected rows — and read their
Changeevents to store what the user does.
Inputs
| Name | Type | Default | Description |
|---|---|---|---|
| groups | CommandGroup[] | [] | Command groups to display. Provide all available commands here. |
| config | CommandPaletteConfig | {} | Optional configuration for placeholder, empty message and recent limit. |
| portalClass | string | '' | Classes applied to the body-portal container. The overlay is instantiated into `document.body` so its fixed backdrop escapes any ancestor `overflow`/`transform`/`filter` containment, which also means it is outside every scoped class on the host: a `.dark` on a section root or a `.tpl-*` token scope does not reach it. Pass the scopes the palette should inherit, e.g. `portalClass="dark tpl-dev"`; without them the palette opens light on a dark section and uses the kit's default accent. |
| variant | CommandPaletteVariant | 'default' | Panel theme. |
| size | CommandPaletteSize | 'md' | Panel width preset. |
| placement | CommandPalettePlacement | 'top' | Vertical anchoring of the panel. |
| loading | boolean | false | External loading flag — set true while a parent fetches remote results (drive it from `queryChange`). Shows a loading row in the results area. |
| serverSide | boolean | false | Let the server do the matching. The supplied `groups` are shown exactly as given — a palette over a large workspace searches documents and people, not just the commands already in the browser. |
| debounceMs | number | 200 | Delay before `queryChange` fires, in ms. `0` emits immediately. A palette wants this short — it is the primary interaction, not a filter. |
| minChars | number | 0 | Characters required before a remote search is sent. Below this the palette says so instead of "No results found". |
| error | SvDataError | string | null | null | Failure loading commands, rendered in place of the list. |
| resultsFor | string | null | null | Which term the supplied `groups` are the answer to. Without this the palette cannot know its results are stale, and is exactly that. The host answers "de" and then "del"; the slower "de" response lands second and the list shows commands for a term the user has already typed past. Nothing in the markup looks wrong, and the palette has no way to tell — `groups` is just an array. And it is worse than cosmetic. The highlighted row is whatever the stale list put first, so Enter runs a command the user never saw offered for what they typed. Set this and the palette keeps saying "Searching…", marks the listbox `aria-busy`, refuses to run a command from a list it knows is out of date, and — the quiet one — does NOT say "No results found" about an answer to a different question. Echo back the `term` the palette handed you. Only consulted with `serverSide`. |
| layout | CommandPaletteLayout | 'list' | `'split'` adds a preview pane beside the list for the highlighted command — its `preview` template or data, or its icon, label and shortcut. |
| scopes | readonly CommandScope[] | [] | Prefix scopes: typing a scope's prefix first (`>` commands, `#` channels, `@` people, `/` pages) turns it into a removable chip and searches only its groups. Backspace on an empty search removes it. |
| pinnedCommandIds | readonly string[] (two-way) | [] | Ids of pinned commands, shown first when the search is empty (two-way). With `config.pinnable`, every command's actions menu can pin and unpin. |
| suggestedCommandIds | readonly string[] | [] | Ids of suggested commands, shown after Pinned and Recent when the search is empty. |
| pages | readonly string[] (two-way) | [] | The page stack — ids of the commands drilled into, outermost first (two-way). Set it to open the palette on a page; it empties on close. |
| canClose | ((reason: SvCloseReason) => SvCloseVerdict) | null | null | Host veto over a USER-initiated close — Escape or the backdrop. The same `canClose` Modal, Drawer and Confirm Dialog take, so a half-typed multi-step command need not be lost to a stray backdrop click. Return `false` to keep the palette open; `closeCancelled` reports the refusal. `close()` stays unconditional: a host calling it IS the decision, the same rule `createCloseGuard` applies everywhere (`programmatic` is always allowed). |
| recentCommandIds | readonly string[] (two-way) | [] | IDs of recently selected commands, most-recent first (two-way). A `model` because a most-recently-used list that only lives in the component is reset by every page load — the one thing an MRU list must survive. Bind it to restore what you stored, and read `(recentCommandIdsChange)` to store it. IDs that do not match a command in `groups` are ignored, so a stale saved list is safe to hand back verbatim. |
Outputs
| Event | Payload type | Description |
|---|---|---|
| opened | void | Emitted when the palette opens. |
| closed | void | Emitted when the palette closes (any method). |
| closeCancelled | SvCloseReason | A user close (Escape / backdrop) was vetoed by `canClose`. |
| queryChange | string | Emitted whenever the search query changes (debounce/fetch in the parent). |
| searchRequest | CommandPaletteSearch | The same change, with a token and an `AbortSignal`. Emitted immediately after `queryChange`, for hosts that want to cancel the request the user has typed past rather than let it finish and be discarded. Ignore it and nothing changes. |
| commandSelected | CommandAction | Emitted when a command is confirmed (before its action runs). |
| commandError | { command: CommandAction; error: unknown } | Emitted when an async command's action rejects. |
| retry | void | The host should re-run the failed command load. |
| shortcutConflicts | readonly CommandShortcutConflict[] | Two or more commands declare the same `keys`. Reported whether or not anything is bound. Duplicate shortcuts were "undetected" because `shortcut` was a list of glyphs nobody parsed — two commands could claim ⌘K and the palette would draw both. Detection is a pure check over the command list, so it does not wait for `bindCommandKeys`: two commands claiming one binding is a bug in the list either way. |
| aiAsk | string | "Ask AI" was chosen (`config.aiFallback`) — the search, as typed. |
| scopeChange | CommandScope | null | A prefix scope was turned on, or off (`null`). |
| subActionSelected | { readonly command: CommandAction; readonly action: CommandSubAction } | A sub-action was run from a command's actions menu. |
| pinnedCommandIdsChange | readonly string[] | Emits the new `pinnedCommandIds` whenever it changes — the output half of `[(pinnedCommandIds)]`. |
| pagesChange | readonly string[] | Emits the new `pages` whenever it changes — the output half of `[(pages)]`. |
| recentCommandIdsChange | readonly string[] | Emits the new `recentCommandIds` whenever it changes — the output half of `[(recentCommandIds)]`. |
Wire it to your API
This component is headless about transport: it renders what you give it and reports what the user asks for. Nothing below requires @styloviz/data — drive it from whatever you already use.
Template
Bound to the names this component actually exposes.
Host class
Drive the three async inputs from your own fetch.
`queryChange` carries `string`, not an `SvDataQuery`, so `@styloviz/data`'s controller cannot take it as it is. The handler above keeps the latest one and fetches with it — map it to whatever your endpoint expects. `serverSide` switches **off** the built-in filtering, sorting and paging. Leave it false and the component works entirely from the array you pass — which is what you want for a few hundred rows. `debounceMs` (default 200) collapses a burst of typing into one request. Set it to 0 only when the query is driven by clicks. Normalize failures with `toSvDataError()` from `@styloviz/core`. It derives `retryable` from the status, so a 404 does not get a "Try again" button that can only fail again.
Full walkthrough: Connecting to a backend.
Customization & theming
Four looks (default · dark · glass · minimal), three sizes (sm · md · lg), and `top`, `center` or `spotlight` placement. A command with `children` opens a page of its own: a breadcrumb chip per level, Backspace on an empty search goes back, and `[(pages)]` holds the stack. `actions` gives a command a sub-menu (→ or ⌘K on the highlighted row, `(subActionSelected)`). `layout="split"` adds a preview pane for the highlighted command — its `preview` data or template. `scopes` turn a typed prefix (`>`, `#`, `@`, `/`) into a removable chip that searches only its groups. With the search empty: `[(pinnedCommandIds)]` first (`config.pinnable` adds Pin / Unpin to every actions menu), then Recent, then `suggestedCommandIds`. `config.aiFallback` adds an Ask AI row for whatever was typed (`(aiAsk)`); `config.placeholderHints` rotate in the empty search; the list is windowed above `config.virtualizeAbove` rows (200). Grouped, searchable commands with substring or fuzzy (subsequence, ranked) matching; recent history and badges. Configurable/optional global shortcut, `showRecent` toggle, disabled and keep-open commands. The open shortcut goes through the shared registry: `config.shortcutScope` puts it in the global, route or overlay band — so a palette inside a dialog outranks the app's own instead of competing on equal terms — and a second component claiming the same binding is refused and reported rather than firing alongside it. A command's `keys` (e.g. `'mod+shift+p'`) is a real binding: it renders itself for the running platform, colliding ones are reported through `(shortcutConflicts)`, and `config.bindCommandKeys` registers them so pressing one runs the command through the same path a click takes. `shortcut` remains the display-only glyph array. Rendered into `document.body` via a portal, so it always covers the full viewport and is never clipped by a parent `overflow`/`transform`. Return a `Promise` from a command `action` for an inline loading spinner; remote sources use `[loading]` + `queryChange`; failures keep the palette open with an error state and emit `commandError`.
Best practices
Do: Register the ⌘K/Ctrl+K shortcut and hint it in the UI (customise with `config.shortcutKey`). Do: Group commands and surface recents so frequent actions are one keystroke away. Do: Enable `config.fuzzy` for forgiving, ranked matching on large command sets. Tip: Keep command labels verb-first ("Create invoice") for scannability. Do: Give a command `keys` rather than a `shortcut` glyph array. `keys` is a binding: it renders itself as ⌘⇧P or Ctrl Shift P for the platform the user is on, and two commands claiming the same one are reported through `(shortcutConflicts)`. The glyph array binds nothing and cannot be checked against anything. Do: Set `config.shortcutScope` to `'overlay'` for a palette that lives inside a dialog, so its ⌘K outranks the app's while the dialog is open and hands it back on close. Tip: Turn on `config.bindCommandKeys` only if the app does not already bind its commands itself — otherwise every shortcut fires twice. Don't: Don't use a key the browser keeps for itself — ⌘/Ctrl + N, T, W, Q, Tab, or Shift + N/T/W — as the open key or a command key. The page never receives it in a browser tab; the palette warns about it in dev mode.
Accessibility
Combobox semantics with `aria-activedescendant` on the search input tracking the active result; `role="listbox"`/`option` results with `aria-selected` and `aria-disabled`. Full keyboard control (↑↓ skip disabled, Enter, Esc, Tab); focus returns to the prior element on close — and if a command removes that element (a navigation tearing down the old view), focus moves to a surviving neighbour or the main landmark once the exit transition ends, instead of `<body>`. Opened with nothing focused, it hands focus to the main landmark. With `resultsFor`, rows that answer an older term — including during the debounce window, before the new term has been requested — stay on screen dimmed but `inert`, are dropped from `aria-activedescendant`, and cannot be run. Running commands set `aria-busy`; async failures are announced via an assertive live region. Forced colours: the panel (the glass variant included) keeps a `CanvasText` edge when its tint and ring are stripped.
Feedback on Command Palette
Spotted a gap in this page, or something that didn't work as described? Comments are GitHub Discussions in the public styloviz/community repo, so posting needs a GitHub account.