Skip to content

Extras

CommandPalette

Bit.BlazorUI.ExtrasCommandMenuCmdkSpotlight

BitCommandPalette is an accessible, keyboard-first command palette: the Ctrl+K (Cmd+K on a Mac) box that fuzzy-searches every page, action and setting of an app and runs the one picked, with nested pages, prompts, multi-select, async sources, recents and global shortcuts. Matching, ranking and every decision run in C#; the browser only shows the native dialog and listens for keys.

Running commands

What happens when a command runs: handlers and their results, the command context, prompts, multi-select, long-running work, errors, guards, nested pages, recents, pins and the action panel.

Handlers and results

A handler does its work and then tells the palette what comes next by returning a BitCommandPaletteCommandResult. That is what keeps a multi-step flow in one place: the next step is a return value, not a callback wired up somewhere else. BitCommandPaletteCmd.Action(title, () => ...) and the Handler overloads that take an Action or return a plain Task answer Close; give Handler a Func<BitCommandPaletteCommandContext, Task<BitCommandPaletteCommandResult>> to pick another result:
  • Close: closes the palette. The default of every handler that returns no result, and of navigation. An inline palette, which never closes, goes back to its root page with the query cleared instead.
  • KeepOpen: stays open on the same page and rebuilds the list - what toggles use. A command is an immutable record, so a toggle's Checked is fixed on it: build the commands again from your state after the change (or paletteService.Update a registered one) and the rebuilt list shows the switch's new state.
  • Back: goes back one page, staying open - the options of a settings page use it to land on the list again. On the root page (an option found from the root) it stays there and rebuilds the list.
  • Reset: clears the query and returns to the root page, staying open - for a flow that is finished but whose user is likely to want the palette again.
  • Toast(message, keepOpen): shows a message in the footer, then closes shortly afterwards - unless keepOpen is true, or the palette is used again meanwhile. Esc while that close is pending is the close itself.
  • Error(message): shows an error, announced assertively, and stays where the palette is - on a prompt, so the value can be corrected. It is for the failures a handler expects (a name already taken, a plan that does not allow it); exceptions are for the ones it does not, see Errors below.
  • Page(title, commands, placeholder, multiSelect, onSubmit): pushes a page listing commands. They are not registered anywhere: they live on that page only, which is what a list the handler decides when it runs needs. With multiSelect: true, Ctrl+Enter runs onSubmit with the checked ones (see Multi-select).
  • Prompt(title, onSubmit, validate, placeholder, initialValue): turns the search box into a text field and runs onSubmit with what was typed (see Prompts).
Try each row below; each subtitle names the result its handler returns. "Add a to-do…" chains two of them: a prompt, then Reset, back on the root where the new to-do is listed first; Enter on a to-do completes it and keeps the palette open.

Say helloClose - an inline palette goes back to its root
Word wrapKeepOpen - the switch flips, the palette stays Off
DensityBack - each option returns to this list Comfortable
Add a to-do…Prompt, then Reset
Check for updatesToast with keepOpen
Save allToast - then the palette closes
Join the betaError
Export…Page

Nothing run yet.

The command context

Every handler receives a BitCommandPaletteCommandContext, which carries what it may need to decide and to act:
  • Command: the command being run - its Id, Title, Data and Tags, so one handler can serve many commands.
  • Query: what was typed when it ran, without a mode prefix; ModePrefix is that prefix (>, #...), or null in the default mode. A "couldn't find it?" row thanks the user for the very query it was reached with.
  • PromptValue: the text of a prompt step, in the onSubmit of a Prompt result.
  • SelectedCommands: the checked rows of a multi-select page, when its handler runs on Ctrl+Enter.
  • Services and GetRequiredService<T>(): the user's DI scope (the circuit on Blazor Server, the app on WebAssembly) - where an API client comes from in a command declared far from any component.
  • Navigation: the NavigationManager, for handlers that navigate.
  • Palette: the IBitCommandPaletteService itself, for handlers that register, open or run other commands.
  • CancellationToken: cancelled when the palette is closed while the handler is still running. What such a handler returns afterwards is ignored, so a late page or prompt never reopens a palette the user has dismissed. Pass it to every call the handler awaits.
Run "Inspect the context" after typing part of its name to see the members filled in. The second row is listed whatever is typed (AlwaysShow), with the lowest priority so it comes last: type something that matches nothing and run it.

Inspect the context
Feedback: couldn't find a command?

Run "Inspect the context".

Prompts

A handler that needs a value answers with BitCommandPaletteCommandResult.Prompt(title, onSubmit, ...): the search box becomes the text field, with the title above it, Enter submits and Esc goes back. onSubmit runs with the text in ctx.PromptValue and returns the next result like any handler - a toast, another page, another prompt.
initialValue pre-fills the field (the current name, for a rename) and placeholder says what is expected while it is empty.
A prompt can validate what is typed: validate returns null for a value that may be submitted and the message to show otherwise. Enter on an invalid value shows and announces the message and marks the box aria-invalid, and from then on the message follows the text as it is corrected. A check that needs a server belongs in onSubmit, which answers with BitCommandPaletteCommandResult.Error to keep the prompt open for a correction - an expected failure, so a result rather than an exception. Guards (see below) are asked again when a prompt is submitted, since what they read may have changed while the value was typed.
Try the three rows: a plain prompt, one pre-filled with the project's name, and an invitation whose address is validated as it is typed and refused by the "server" for [email protected], who is already a member.

Add a note…
Rename project…
Invite by e-mail…

Project: Apollo · Nothing submitted yet.

Multi-select

MultiSelect() turns a command's page into a list of checkboxes. Enter, a click or Space (on an empty search box) checks or unchecks a row, and Ctrl+Enter (Cmd+Enter on a Mac) runs the command's handler with the checked commands in ctx.SelectedCommands - checking a box runs nothing, the submit is what acts on the rows. ChildrenPlaceholder is the place to say so in the search box. Give the rows stable Ids: the checked state is kept by id.
A page a handler returns works the same way: BitCommandPaletteCommandResult.Page(title, commands, placeholder, multiSelect: true, onSubmit: ...) runs onSubmit with the checked rows. That is how a chain of steps is written - "Create webhook…" asks for an https address first, validated as it is typed, then answers with a page of events, and refuses a submit with no event checked with an Error.
A multi-select page can also search as the user types, with .Source(name, async (query, cancellationToken) => ...) instead of fixed children (the async sources are covered with the modes): rows checked in one search stay checked across the next ones, and Ctrl+Enter hands over every checked row, from every search typed on the page. In "Invite people…", type ada and check her, then grace and check her, then apply.
The rows of a multi-select page are choices rather than commands, so they are not found from the root page and have no action panel.

Set labels…
Invite people…
Create webhook…

Nothing applied yet.

Long-running commands

A handler that is still running after 150 ms shows the palette busy: a spinner replaces the search icon, the list is aria-busy, the running row carries data-running, and "Working…" (BitCommandPaletteStrings.Running) is announced to screen readers. A quick handler never flickers. While it runs, a second Enter is ignored, so the command cannot be started twice.
Esc closes the palette and cancels the handler's ctx.CancellationToken - pass it to every call the handler awaits, so the work really stops. What the handler returns after that is dropped, so a late page, prompt or toast never reopens a palette the user dismissed; a handler that ends by throwing OperationCanceledException simply stops, without being reported as a failure. paletteService.CloseAsync() cancels it the same way.
When the user leaves the page a handler was started on while it runs - Esc out of a prompt whose submit is still working - its answer about pages (Back, Page, Prompt, Reset) is dropped rather than applied to the page they are on now; closing, toasts and errors still apply.
An inline palette never closes, so its handlers always run to the end. This one is registered with the service and runs in the modal palette: open it, run "Generate report…" (three seconds of work), and press Esc halfway.



Not run yet.

Errors

An exception thrown by a handler - or by the loader of a page's children - raises IBitCommandPaletteService.CommandFailed, is logged through the palette's ILogger, and is reported in the palette: a handler's failure as a message in the footer, announced assertively, a page's as an error state with a Try again button (see "Recent deployments…" under Nested pages).
The message is the localized, generic BitCommandPaletteStrings.CommandFailed ("Couldn’t run “Sync with server”."), so an exception's own text - which can name a server, a table or a user - never reaches the screen by accident. A CommandFailed subscriber picks another through the event's Message (for example e.Exception.Message for a ValidationException, whose text is written for users), or sets it to "" to show nothing. Setting Handled = true says the subscriber reported the failure itself: the palette then does not log it, and ExecuteAsync does not rethrow it.
A failure in the palette's own UI - a row chosen with the keyboard or the mouse, a global shortcut - is never rethrown, so it can neither end a Blazor Server circuit nor vanish into the browser's console. paletteService.ExecuteAsync(id) rethrows an unhandled one to the code that called it; with the palette closed, that caller is the only one who can tell the user. Cancellation is not an error: a handler that throws OperationCanceledException simply stops - unless it wraps a TimeoutException, which is how HttpClient reports a timeout, and is reported like any other failure.
The application's own listeners are another matter: a CommandExecuted subscriber, an OnCommandExecuted, OnClosed or OnQueryChanged that throws is a bug in the app, not a failed command. The command's result is still applied - the palette closes, shows its page or its toast - and the exception then goes where one thrown from a click goes: to the nearest ErrorBoundary, or, without one, to the host's unhandled-exception handling, which on Blazor Server ends the circuit. Wrap the palette in an ErrorBoundary to keep a throwing listener from taking the circuit down.
Run both rows below: "Sync with server" throws with a server's name in its text, which is not shown; "Publish release" throws a ValidationException whose message this page chose to show. Both commands are also registered with the service, so the button runs one from code; clear the checkbox to see ExecuteAsync rethrow.


Sync with server
Publish release



The CommandFailed subscriber has seen nothing yet.

Guards

VisibleWhen and Disabled decide what is listed; a guard decides, every time a command is about to run, whether it may - a permission, a plan, a feature flag. Guards run at execution time, not while the list is built on every keystroke: hide what a user can never run with VisibleWhen, and enforce it with a guard.
A guard is asked on every path a command takes: a row chosen with the keyboard or the mouse, Mod+Enter, a global shortcut, paletteService.ExecuteAsync(id) - and again for the second Enter of a confirmation and when a prompt or a multi-select page is submitted, since what it reads can change in between. OpenAsync(pageCommandId: ...) asks a page's guards before the page is listed or loaded. The guard sees a BitCommandPaletteGuardContext: the Command about to run, the Trigger that started it (Palette, Shortcut or Programmatic) and the scope's Services.
There are three places for one:
  • Per command: .Guard(ctx => plan.IsPro, "Exports need the Pro plan.") for a check that needs nothing async, or .Guard(async (ctx, cancellationToken) => ...) returning a BitCommandPaletteGuardResult. A command has one guard: a later .Guard replaces an earlier one, so combine checks in one.
  • Per page: a page's guard covers every command under it - its registered descendants however they run, and, from the palette, whatever its page lists, lazily loaded children and source results included. So does the guard of a command whose handler returned a page, over that page's rows and its multi-select submit, and a row's guard over its secondary actions.
  • Registered: for rules that hold for many commands, implement IBitCommandPaletteCommandGuard and register it with builder.Services.AddBitCommandPaletteCommandGuard<TGuard>(). It is resolved from the scope, so it can use scoped services such as an AuthenticationStateProvider, and reads the command's Tags or Data for a convention of your own. A guard registered through DI is part of the app's startup, so this page cannot add one at runtime: its code is in the sample below.
The order is the command's ancestors' guards (outermost first), its own, then the registered ones, and the first refusal wins. Submitting a multi-select page also asks about every row checked. A command whose ancestor the palette cannot find (its Parent not registered, out of reach with IncludeRegisteredCommands off, or nested deeper than 32 levels) is refused, since that ancestor's guard could not be asked.
BitCommandPaletteGuardResult.Allow lets it run, Deny(message) refuses it, and a bool converts to either (default refuses, so a guard that forgets to answer fails closed). Read IsAllowed rather than comparing results: two refusals with different messages are different values.
A refused command does not run, arm or open: the footer shows the guard's message, or BitCommandPaletteStrings.CommandRefused ("You can’t run “Export as PDF”.") when it gave none (Deny("") shows nothing), IBitCommandPaletteService.CommandRefused is raised with the command, the trigger and the message, and an information entry is logged. ExecuteAsync does not throw for a refusal - the event is how code, a shortcut or an audit log hears of it while the palette is closed. A guard that throws refuses and is logged as an error. A guard still deciding about a row shows the palette busy after 150 ms and turns a second Enter away; closing the palette gives up on it. Without any guard the check costs nothing.
Guards keep the palette honest; they are not the last line. On WebAssembly they run in the browser with the rest of the app, so the server still checks every action a handler asks it to perform.
Below, "Export as PDF" needs the Pro plan and "Admin" - a page whose guard takes a moment, like a server call - needs an admin. Try them from the list, with G then X anywhere on the page, and from code, with and without the boxes checked.


Export as PDF G then X
Admin


Nothing run yet.
Nothing refused yet.

Nested pages

A command with children opens a page listing them, with breadcrumbs and a back button above the search box. Backspace or ← on an empty search box, the back button and Esc go back one page, and the query typed before the page opened comes back with it; with text in the box, Backspace just deletes a character. Each ancestor in the breadcrumbs is a button back to its page. There are four ways to give a command a page:
  • Static children: .Children(a, b, c) (or BitCommandPaletteCmd.Page(title, a, b, c)). Children registered with the service are flattened into the registry with their Parent set, so Find, ExecuteAsync, shortcuts and OpenAsync(pageCommandId: ...) reach them like any other command. "Language" below answers Back from each option, to land on the list again.
  • Lazily loaded children: .Children(async (ctx, cancellationToken) => ..., placeholder). The page opens at once with a loading state and fills in when the provider returns; the provider runs each time the page opens, with a context whose Services come from the user's scope - where a real app's API client comes from. The token is cancelled when the page is left, the palette is closed and reset, or the page is loaded again, and an abandoned load changes nothing. A provider that throws gets an error state with a Try again button (Enter retries too) and raises CommandFailed: "Recent deployments…" fails every other time.
  • Declarative children: nested BitCommandPaletteOptions in markup, as "Theme" is declared below.
  • Pages a handler returns: BitCommandPaletteCommandResult.Page(...), for a list that depends on what the handler found out when it ran ("Switch branch…"). These commands are not registered anywhere: they live on the page only. A page can also search as the user types, with .Source(...), as "Invite people…" in Multi-select does.
Finding nested commands from the root. Nested commands are found from the root page too (SearchNestedCommands, on by default, as in kbar): typing dark lists Theme › Dark under Theme's group, and theme dark matches the ancestors' titles as well (Weights.Path). A root command and a nested one that match equally well are listed root first. Choosing a nested command found this way opens with its ancestors' pages behind it, so Esc goes up one level at a time, and recently used and pinned nested commands are listed on the root page with their path. Only commands registered with the service or declared in markup are found - not the children of commands passed to an inline palette's Commands, and not a lazily loaded page's, which do not exist until it opens - and only when every ancestor is visible and enabled and none is a multi-select page. Modes never include them. Turn it off with SearchNestedCommands="false" on the palette or in the options.
Opening directly on a page. paletteService.OpenAsync(pageCommandId: "...") opens the modal palette straight inside a registered command's page, with its ancestors' pages behind it, so the breadcrumbs show the whole path; a BitCommandPaletteTrigger takes the same PageCommandId, so a "Change theme" button can be a trigger that lands on the theme options rather than on the root list. The page's guards are asked first. The buttons below open the modal palette on "Preferences › Editor theme", registered with the service.

Theme Light
Language English
Assign to…
Recent deployments…
Switch branch…

Nothing picked yet.


Editor theme: Light

Recents, pins and the action panel

On the empty query of the root page, pinned commands are listed first, in the order they were pinned, and the most recently used ones next - up to MaxRecents (5) of the options. Every run is recorded unless the command has ExcludeFromHistory() (a to-do, a search result, anything that will not be there next time), and the counts also feed frecency - how often and how lately a command was used - which lifts familiar commands when a query is typed (FrecencyWeight in the options).
Tab - or → on an empty search box, or a right click - opens the action panel of the active row: its own .Actions(...) first, then Pin to top or Unpin, Remove from recents when it has been used, and Clear recent commands, which forgets every use and keeps the pins - a privacy control within reach of the list it clears. Some keys skip the panel: Ctrl+Enter (Cmd+Enter) runs the row's first action directly - on a link without actions it opens the link in a new tab, as GitHub's palette does - Ctrl+Shift+P (Cmd+Shift+P) pins or unpins, and Shift+Delete forgets. A row with no actions and ExcludeFromHistory has no panel.
History is command ids, counts and times - never queries. It lives in BitCommandPaletteHistory, a scoped service an app can inject too: Pinned(), Recents(max), Get(id), IsPinned(id), Frecency(id), TogglePinAsync, RemoveAsync, ClearAsync and a Changed event (raised off the renderer's thread, so re-render through InvokeAsync). The default store keeps it in the browser's localStorage under HistoryStorageKey ("bit-command-palette.history"), capped at MaxHistoryEntries (200, pins never pruned) and validated when it is read back. To keep it elsewhere - per user on the server, or nowhere - register a store at startup (see the sample). Turn history off for every palette with options.EnableHistory = false, or on one palette with EnableHistory="false": no recents, no pins, no frecency and no action panel for rows without actions.
Run a few rows below, press Tab on one, pin another with Ctrl+Shift+P, clear the search box, and watch the lists. The people rows add two actions of their own; "Go to the Button demo" is a link, for Ctrl+Enter.


Ada LovelaceEngineering
Grace HopperEngineering
Alan TuringResearch
Start a timer
Go to the Button demoA link: Ctrl+Enter opens it in a new tab
Scratch noteExcludeFromHistory: never recent, no action panel

Nothing run yet.
Pinned: nothing - press Tab on a row and pick Pin to top
Recent: nothing used yet

Feedback

Found a mistake, a gap, or something that could be clearer? Every page and every component is one click from its source.