Extras
CommandPalette
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.
Notes
AddBitBlazorUIExtrasServices() in Program.cs (in both
projects of a Blazor Web App). The sections below go from the basics - a palette in markup, the setup, the hosting
models, the modal palette and its trigger - to the full API.
Usage
Every example is live. Open its code to see exactly what produced the component running underneath.
Basic
The simplest palette declares its commands in markup: a BitCommandPaletteGroup per heading, holding a BitCommandPaletteOption per command. Title is what is searched first and highlighted, Keywords (separated by commas or spaces) are other words that find it, Subtitle is a second line, Badge a small label, and Disabled with DisabledReason keeps a command listed but refuses to run it and says why.
Type to search: the matcher is fzf-style fuzzy matching, so "gs" finds "Go to settings" - it rewards word starts, camelCase humps and consecutive runs, ignores case unless the query has a capital, and highlights the characters it matched. "options" finds "Go to settings" through its keywords. Move with the arrow keys (they wrap around), Home and End, Page Up and Page Down; run the active command with Enter or a click. Escape clears the query of an inline palette.
This palette is Inline: it is part of the page and always open, for a settings search, a docs search page or a command list in a side panel. IncludeRegisteredCommands="false" makes it list only its own commands, not the ones registered app-wide with IBitCommandPaletteService (the next section is about those). OnCommandExecuted reports every command it ran.
The sections below add the rest: the modal Ctrl+K palette and its trigger, commands built in C#, nested pages, toggles, prompts and confirmations, global shortcuts, modes by prefix (">", "#", "@", "?"), async sources against your own API, multi-select, recents and pins, guards that check a permission every time a command is about to run, templates, theming and localization.
Getting started
1. Configure it, if the defaults do not suit, through the commandPalette argument of builder.Services.AddBitBlazorUIExtrasServices(commandPalette: options => ...), which sets BitCommandPaletteOptions (more toggle shortcuts, the order of the groups, startup commands, modes and sources). That call already registers the palette's services, so there is nothing else to register. The options are a singleton. The registry, the open state and the history are scoped: one per circuit on Blazor Server, one per application on WebAssembly.
- In a Blazor Web App, call it in both the server and the client project, through one extension method that both Program.cs files share.
- Both are needed because every page is prerendered on the server before it runs in the browser, so whatever a component injects, such as IBitCommandPaletteService, must resolve in both containers.
- A palette running in a project that did not call AddBitBlazorUIExtrasServices uses the default options and ignores yours, and it logs a warning that says so.
- A WebAssembly app that lazy loads Bit.BlazorUI.Extras skips this step, as the Hosting models section explains.
3. Register commands wherever they belong, by injecting IBitCommandPaletteService and calling Register. It returns an IDisposable: dispose it to remove the commands again, so commands registered by a page leave with the page. Commands that belong to the whole app are registered once, from the layout or at startup through options.Commands, and <BitCommandPaletteCommands Commands="..." /> registers a list while it is rendered and removes it when it goes. The sections of this page cover everything a command can be.
4. Open it. Ctrl+K (Cmd+K on a Mac) toggles the palette. Code opens it through OpenAsync of the service, optionally with a query (a mode prefix included) or directly on a command's page, and ExecuteAsync runs a command by its id without opening anything.
Requirements.
- It needs .NET 10 or .NET 11.
- It runs on Blazor WebAssembly, Blazor Server, a Blazor Web App in any interactive render mode, and Blazor Hybrid.
- It needs a browser with the dialog element, which every evergreen browser has had since 2022.
- It is trimming and AOT friendly.
- BitCommandPalette keeps the query, the mode prefix, the stack of pages and the active row.
- BitCommandPaletteQuery parses the query into terms and operators, once per keystroke.
- IBitCommandPaletteMatcher scores every visible command's fields, fzf style, and returns the positions to highlight.
- BitCommandPaletteRanker combines that score with priority and frecency and keeps the best MaxResults.
- The groups, pinned and recent commands and async source blocks are flattened into one list of rows, so keyboard navigation, aria-activedescendant, scrolling and virtualization all work on a single model.
- The native dialog shows them in the top layer, traps the focus and points aria-activedescendant at the active row.
- The model is BitCommandPaletteCommand and its fluent builder BitCommandPaletteCmd, with results, contexts, modes and keyboard shortcuts; it is immutable and free of UI.
- Search is BitCommandPaletteFuzzyMatcher, BitCommandPaletteSubstringMatcher, the field weights, BitCommandPaletteRanker and the async sources; it is pure C# that runs in a unit test.
- The service is IBitCommandPaletteService: the registry, the open state and the events, one per circuit or browser tab.
- History is recents, pins and frecency over a pluggable IBitCommandPaletteHistoryStore.
- The components are BitCommandPalette, BitCommandPaletteTrigger, BitCommandPaletteGroup, BitCommandPaletteOption, BitCommandPaletteCommands, BitCommandPaletteShortcutHint and BitCommandPaletteHighlightedText.
Hosting models
- Blazor WebAssembly: register the services in Program.cs, link the Extras stylesheet and script in index.html, and place the palette in MainLayout.razor. Searching runs on the browser's one thread, so a keystroke whose search took longer than a frame paints first, and keys typed meanwhile fold into one search; typing stays responsive with thousands of commands.
- Blazor Server: the setup is the same. Shortcuts and navigation keys are handled in the browser, so only the query and the chosen command cross the circuit, and handlers run on the server in the circuit's scope. Keys typed faster than a round trip are all kept, and the search runs at once instead of deferring to the next frame, because the network already separates typing from rendering.
- Blazor Web App: register the services in both the server and the client project, and link the stylesheet and script in App.razor. With global interactivity (
<Routes @rendermode="InteractiveServer" />, InteractiveWebAssembly or InteractiveAuto) the palette goes in MainLayout.razor. - With per-page interactivity the layout is static, so wrap the palette in a small component that the layout renders with an interactive mode, such as
<PaletteHost @rendermode="InteractiveAuto" />, and register commands from components that run in the same mode, because the registry is scoped to one circuit or one WebAssembly runtime. - While prerendering, the palette renders a closed dialog; once it is interactive and its browser layer listens for keys, it marks the dialog with data-ready="true", which is what an end-to-end test waits for before pressing Ctrl+K on a prerendered page.
- Blazor Hybrid: the palette works unchanged in a MAUI, WPF or Windows Forms BlazorWebView, set up as on WebAssembly, and its history goes to the web view's localStorage.
- Leave AddBitBlazorUIExtrasServices out of that project's Program.cs and register the core services with AddBitBlazorUIServices() instead. Calling it would reference the Extras types before the assembly is there; the palette then runs on the default options.
- For the same reason, only what renders after the assembly has loaded may use its types: the pages it is loaded for and a layout only they use, not App.razor, a layout every page shares or Program.cs. The other Extras components are then available on those pages only.
- No type in an assembly the router reads when the app starts, the app's own assembly first of all, may derive from or implement one of the palette's types: no IBitCommandPaletteSource class, no IBitCommandPaletteHistoryStore and no component that inherits BitCommandPalette. On WebAssembly a type whose base type or interface lives in an assembly that is not loaded yet fails to load, and keeps failing after the assembly has loaded, for the rest of the session. Put such a class in a library that is lazy loaded together with Bit.BlazorUI.Extras.
- The stylesheet and the script are plain link and script tags, served whether the assembly has loaded or not.
- Without the registration the palette runs on the default BitCommandPaletteOptions. Its parameters override most of them per instance (Strings, ToggleShortcut, Loop, EnableHistory and others), a trigger shows and announces the toggle shortcut and the strings of the palette it opens, and modes, sources and commands are registered through GetBitCommandPaletteService() instead of options.Modes, options.Sources and options.Commands.
- The remaining options, such as GroupOrder, AdditionalToggleShortcuts, the field weights, the matcher and AllowedUrlSchemes, keep their defaults; an app that needs them registers the services rather than lazy loading.
- The history store cannot be replaced either: recents, pins and frecency go to the browser's localStorage under the default HistoryStorageKey, bit-command-palette.history, which every app on the same origin shares. An app that must not write to the browser sets EnableHistory="false" on its palettes.
- The palette logs one warning that the services are not registered. That is expected here; it is what tells an app that should have registered them, such as the client project of a Blazor Web App that forgot to, why its options are ignored. A logging filter on the category Bit.BlazorUI.BitCommandPaletteServiceCollectionExtensions silences it without referencing the palette's types.
- Do not lazy load in an AOT build: AOT compiles every assembly into dotnet.native.wasm, so there is nothing left to download later, and lazy loading an AOT-compiled assembly can fail at startup.
Modal
It opens in four ways:
- its toggle shortcut, Ctrl+K (Cmd+K on a Mac), from anywhere on the page - pressed again, it closes the palette;
- a BitCommandPaletteTrigger, a button showing that shortcut (the next section covers it);
- binding Open: @bind-Open both opens and closes it, and follows the palette whichever way it was opened or closed;
- paletteService.OpenAsync() from code - with a query already typed (OpenAsync("hello"); a mode prefix such as ">" opens that mode) or straight on a command's page (OpenAsync(pageCommandId: "a-greetings")). CloseAsync() and ToggleAsync() drive it the same way, and ExecuteAsync(id) runs a command as if it had been picked, without opening anything unless the command needs the palette.
ToggleShortcut replaces the toggle shortcut of this palette (the default comes from options.ToggleShortcut, "Mod+K", where Mod is Cmd on a Mac and Ctrl elsewhere); turn on the switch to make it Alt+K and watch the trigger follow. options.AdditionalToggleShortcuts adds more, e.g. VS Code's "Mod+Shift+P". Inside the palette its own keys win over a toggle bound to the same keys. OnOpened and OnClosed are raised after the palette opened and closed, however it happened; IBitCommandPaletteService.Opened and Closed report the same to code anywhere else.
Trigger
- Label is its text; the default is "Search", and an empty one shows the icon alone. Its accessible name starts with the label it shows and goes on to say what it does - "Search the docs…, Open command palette" - so someone who says "click Search the docs" with voice control reaches it (WCAG 2.5.3, label in name). The words come from BitCommandPaletteStrings.OpenPalette and TriggerNameSeparator; a label that already says it all is the whole name, and an AriaLabel overrides both.
- Query opens the palette with a query already typed - a search, or a mode prefix such as ">" that opens that mode (modes come later on this page).
- PageCommandId opens the palette directly on the page of the command with that id - here the "Choose a greeting" page of the Modal section's palette.
- ShowShortcut="false" drops the shortcut hint.
- ChildContent replaces the whole content - icon, label and hint. The trigger cannot read the text of content you give it, so name it: content that shows only an icon sets Label="" and the button is named "Open command palette"; content that shows a word sets Label to that word and is named as the default trigger is; content with no Label is named by what it shows followed by a visually hidden ", Open command palette".
- MacKeys forces one platform's symbols - true for Cmd, false for Ctrl - instead of the detected one, e.g. for a screenshot or a page about one platform.
Commands from code
BitCommandPaletteCommand: a title, where it is listed, what it matches and what
it does. BitCommandPaletteCmd starts one and every method of the BitCommandPaletteCommandBuilder
it returns sets one member; a builder converts to a command on its own, so a list of them needs no Build()
calls - only a target that is not a BitCommandPaletteCommand does.
The entry points:
BitCommandPaletteCmd.New("Export…") starts a blank command;
Navigate("Settings", "/settings") sets Href and makes it a navigation;
Action("Save", () => Save()) runs an Action and closes the palette;
Action("Reload", ReloadAsync) does the same with a Func<Task>;
Action("Rename…", ctx => ...) takes a Func<BitCommandPaletteCommandContext, Task<BitCommandPaletteCommandResult>>
and so decides what happens next; Page("Theme", light, dark) makes a page of the commands it is given.
Handler has the same overloads: an Action, an Action<BitCommandPaletteCommandContext>
or a Func<BitCommandPaletteCommandContext, Task> close the palette when they are done, while a handler
returning a BitCommandPaletteCommandResult says what comes next (stay open with KeepOpen, go
Back, a page, a prompt, a toast or an error - see the sections on handlers and results).
Every member of the model, with the builder method that sets it:
Id- stable identity; derived from the title, group and parent when not set (.Id(...), see Identity).HasExplicitIdsays whether it was set.Title- the label, required; searched with the highest weight and highlighted (.Title(...)).Subtitle- a secondary label next to the title, such as a path or a category; searched and highlighted.Description- longer text for the detail pane; searched with a low weight.Keywords- aliases, synonyms and abbreviations (.Keywords("download", "save as")); a keyword hit is shown under the title.Group- the heading the command is listed under.Icon/IconCss- aRenderFragment(.Icon(fragment)) or a CSS class for an icon font (.Icon("bit-icon bit-icon--Save")); without either, the row shows its kind's icon.Shortcut/GlobalShortcut- aBitCommandPaletteKeyboardShortcut, a chord (Mod+S) or a sequence (G S); global by default, so it fires while the palette is closed, and.Shortcut("Mod+S", global: false)only shows it.Priority- a ranking nudge;BitCommandPaletteCommandPrioritynamesLowest(-100),Low(-50),Normal(0, the default),High(50) andHighest(100), and any other number works too.Parent- the id of the command whose page lists this one; set for you on static children.Children/ChildrenProvider/ChildSources- nested commands: static (.Children(a, b)), loaded when the page opens (.Children(async (ctx, ct) => ...)), or searched as the page is typed in (.Source(...)).HasChildrensays whether it opens a page.ChildrenPlaceholder/MultiSelectChildren- the search box placeholder on that page, and whether its rows are checkboxes (.MultiSelect()).Actions- secondary actions listed in the action panel onTab.Handler- what runs on selection:Func<BitCommandPaletteCommandContext, Task<BitCommandPaletteCommandResult>>.Href/ForceLoad/OpenInNewTab- a navigation target, used when there is no handler (.Href(url, forceLoad: false, newTab: true)); only relative links and the allowed schemes are followed.Kind-Action,Navigation,Toggle,Setting,Search,Page,HelporRecent: picks the default icon and is exposed asdata-kind.Href,Children,ValueandCheckedset it for you, so call.Kind(...)after them to override it.Disabled/DisabledReason- listed but not runnable; the reason replaces the subtitle (.Disabled(true, "Requires the Pro plan")).IsVisible- a predicate evaluated every time the list is built (.VisibleWhen(() => ...)).Guard- asked every time the command is about to run whether it may (.Guard(ctx => ..., "message")).Destructive/ConfirmMessage- drawn in the danger colour; with a message,Enterhas to be pressed twice (.Destructive("..."), or.Confirm("...")for the secondEnteralone).Badge/Value/Checked- a pill ("New", "3"), a setting's current value ("Dark"), or a toggle's switch.AlwaysShow- listed whatever the query, like cmdk'sforceMount, for a "couldn't find it?" row.ExcludeFromHistory- never recorded in recents or frecency.Tags- free-form labels that modes can scope to.Data- anything your templates or handlers need.
command.With(b => b.Title("Rename…").Badge("New")) derives one.
There are three ways to hand commands to the palettes, and they can all be used at once: the palette's
Commands parameter (a list of this one palette), IBitCommandPaletteService.Register(...) (the
scoped registry every palette of the scope lists), and markup (see Declarative markup). Register takes the
commands as a params array or an IEnumerable and returns an IDisposable: the
commands are in the registry - and in the modal palette, shortcuts included - from the moment they are registered until
that handle is disposed. Keep the handle and dispose it when the component that registered them goes.
Below, an inline palette lists the commands passed to its
Commands parameter: a blank command, actions
built from an Action, a Func<Task> and a handler that keeps the palette open, a page
(Backspace goes back), a navigation and a link that opens in a new tab, and a help row with a badge and an inline SVG
icon. The button registers Say hello with the service, so the modal palette lists it, and disposes the handle on
the next click.
Identity
Find, Update, Unregister, ExecuteAsync
and OpenAsync(pageCommandId: ...) all go by a command's Id. Without one it is derived: a
lower-case slug of the title (every character that is not a letter or a digit becomes a dash), prefixed with the parent's
id and the group, joined by dots - Settings in the group Navigation is
navigation.settings, and Dark under the page preferences.theme is
preferences.theme.dark. A static child registered with the service gets its parent's id as that prefix, and a
BitCommandPaletteOption derives its id the same way from its Title, its group's
Heading and the option it is nested in. A title made of symbols only, such as 🚀, derives its id
from its code points (u1f680). The table below is worked out by the library on this page, right now.
Set the id explicitly whenever the title can change - a toggle whose label says "Enable" or "Disable", a translated title - so recents, pins and the active row survive the change:
BitCommandPaletteCmd.New(wordWrap ? "Disable word wrap" : "Enable word wrap").Id("toggle:wordwrap").
A copy made with With keeps its id even when its title changes.
Different titles can derive the same id -
C# and C++ are both c - and then one
replaces the other. When two commands registered together share an id, the service logs a warning (through
ILogger) naming both titles; give them explicit ids.
Registering a command with an id that is already registered replaces it: the later registration wins, which lets a page override a global command of the layout (and its shortcut) while it is shown, and the earlier one comes back when the override's registration is disposed. Inside one palette there is one command per id: the registry's, then the one declared in its markup, then the one passed to its
Commands parameter.
Below, Greet the team is registered with the id
b-greet when the page starts. The button registers a
second command with the same id; while that registration lives, Find("b-greet") and the modal palette
return the override, and disposing it brings the first one back.
| Built as | Id |
|---|---|
New("Settings").Group("Navigation") | navigation.settings |
New("Rename project…").Group("Actions") | actions.rename-project |
New("What's new").Group("Help") | help.what-s-new |
New("Dark").Parent("preferences.theme") | preferences.theme.dark |
New("C#") | c |
New("C++") | c |
New("🚀") | u1f680 |
New("Word wrap").Id("toggle:wordwrap") | toggle:wordwrap |
New("Word wrap").Group("Editor").Build().With(b => b.Title("Soft wrap")) | editor.word-wrap |
Groups and ordering
Group puts a command under a heading. On the empty query the palette lists, in this order: pinned and recent
commands (when history is on), then the ungrouped commands - under a heading of their own, Suggestions, when pinned
or recent ones are listed above them, so they do not read like more recents - then the groups named in
BitCommandPaletteOptions.GroupOrder, in that order, then every other group: the group holding the
highest-priority (or most used) command first, alphabetically on a tie.
Inside a group, commands are ordered by
Priority, then by frecency, then in the order they were registered or
declared - list Light, Dark and Auto and that is the order they appear in. Priority is a
number; BitCommandPaletteCommandPriority names Lowest (-100), Low (-50),
Normal (0, the default), High (50) and Highest (100). It leads on the empty query,
and only nudges a search, where the match decides.
While searching, results are ordered by rank (equal ranks by title), and the groups by their best match.
GroupWhenSearching = false drops the headings while a query is typed and lists the results as one ranked list
instead. It is an app-wide option (AddBitBlazorUIExtrasServices(commandPalette: options => options.GroupWhenSearching = false))
that the palette's GroupWhenSearching parameter overrides for one palette. GroupOrder is only an
option, set once for the app.
The palette below lists the same commands this page would without a
GroupOrder: Search everywhere has
no group and comes first; Edit holds a High command (Undo), so it leads the groups, and
Undo leads it; Help and View tie and follow alphabetically; Reset zoom is Low and
Send feedback Lowest, so both sink to the end of their group. Send feedback is also
AlwaysShow: type anything and it is still there. EnableHistory="false" keeps recents out of this
palette, so the order you see is only the one described here. Type "o" and flip the toggle to compare a grouped and a flat
search.
Toggles and settings
.Checked(state) makes a command a
Toggle, .Value("Dark") makes it a Setting, and a setting with children opens a page of
its choices. Both usually answer BitCommandPaletteCommandResult.KeepOpen, so the change can be seen in the
palette, and a choice on a page answers Back, so the setting shows its new value. Give such commands an
explicit Id, so the active row, recents and pins survive the change of their state or label.
Because commands are immutable, the new state is a new command. There are three ways to hand it over:
- Build the list again and pass the palette a new collection: its
Commandsparameter is re-read when it is handed a new instance (a collection changed in place needspaletteService.Refresh()). That is what the inline palette below does - rebuilding a few records is cheap. - Re-register it: a
BitCommandPaletteCommandshanded a new collection swaps its registration (see Page-scoped commands). - Call
paletteService.Update(command), which replaces the command with the same id wherever it was registered - its static children included - or adds it when no command has that id. It suits a registry too large to rebuild, and a label that changes with the state.
paletteService.Update with a command of the same id
b-focus-mode, titled Leave focus mode and checked, and back again.
b-focus-mode: Enter focus modeDisabled, hidden and destructive commands
- Disabled, with a reason:
.Disabled(true, "Requires the Pro plan")lists the command but does not run it. The reason replaces the subtitle, andEnteron the row answers with it in the footer. Use it when the user should learn that the command exists and why it is not available. - Hidden until it applies:
.VisibleWhen(() => selection.Count > 1)setsIsVisible, a predicate evaluated every time the list is built, so an open palette is always right. The global shortcuts, though, are synced to the browser ahead of time: when state a predicate reads changes while the palette is closed - a selection, the signed-in user, the current route - callpaletteService.Refresh(). The command that just became available then answers its shortcut, and the one that went away leaves its keys to the page. Registering, updating or removing a command refreshes on its own. A row chosen after its predicate (or an ancestor's) turned false since the list was built - the user signed out in another tab and nobody calledRefresh()- does not run: the footer says "“Merge selected files” is no longer available." (BitCommandPaletteStrings.CommandUnavailable) and the list is rebuilt. - Destructive, confirmed:
.Destructive("This permanently deletes the draft")draws the command in the danger color, and with a message the firstEnterarms it and shows the message, the second runs it;Escor moving to another row disarms it..Confirm("message")asks for the secondEnterwithout the danger color, and.Destructive()without a message only colors the row. A command run from code withExecuteAsyncthat needs a confirmation opens the palette to ask.
Alt+M and
.VisibleWhen(() => bSelectedFiles.Count >= 2), and listed by the inline palette too. Select two files and
it is there - in both palettes and on the keyboard; select one and it is gone from all three, because every click calls
paletteService.Refresh(). Export as PDF is disabled with its reason, Publish the draft asks for a
second Enter, and Delete the draft is destructive (and Low priority, so the danger zone comes
last). Nothing here deletes anything.
Page-scoped commands
<BitCommandPaletteCommands Commands="..." /> renders nothing: it registers its Commands with
IBitCommandPaletteService while it is rendered and disposes the registration when it is - leave the page and its
commands are gone from the palette, shortcuts included (kbar calls this useRegisterActions). Handed a new
collection instance, it swaps the registration, so assigning a new list after a state change is enough to show the new
commands; the same instance changed in place is not noticed. It works even where AddBitBlazorUIExtrasServices
was never called. paletteService.Register(...) does the same from code and hands back the
IDisposable to dispose.
A
Shortcut is global by default: the modal palette - the one a layout places once - claims it on the whole
document, so it runs its command while the palette is closed, as long as the page that registered it is shown. An inline
palette never claims shortcuts. When several commands claim the same keys, the one registered last wins (the rule ids
follow too), so a page's own Mod+S takes over from the layout's while the page is shown.
A registered command is changed in place with
paletteService.Update: Find the current one, derive
a copy with With - same id, handler and shortcut - and hand it over. The registration
BitCommandPaletteCommands holds is edited in place, so disposing it when the page goes still removes the copies.
Below, Increment counter and Decrement counter are registered by this page. Open the modal palette and look for them under "Counter", or press
Alt+↑ / Alt+↓ anywhere on the page with the palette closed. Both
keep the palette open, so the value can be stepped from inside it, and both carry the count as a badge, updated through
Update on every change. Reset counter is destructive, so it asks first, and it is disabled, with its
reason, while the counter is at zero.
Declarative markup
BitCommandPaletteGroup gives its Heading (required) to the options inside it, its
Priority to every option that does not set its own, and adds its Tags to theirs.
BitCommandPaletteOption has a parameter for most members of the model:
Title(required),Id,Subtitle,Description, andKeywords- one comma or space separated string.Icon(aRenderFragment, written as an<Icon>child element) orIconCss.Shortcut(Mod+Shift+D,G I) andGlobalShortcut(defaulttrue;falseonly shows the keys).HrefandNewTab: an option with anHrefand noOnExecutenavigates.OnExecuteandKeepOpen:OnExecutereceives theBitCommandPaletteCommandContext, and the palette closes afterwards unlessKeepOpenis set (an inline palette goes back to its root page instead).Priority,Kind(inferred when not set),Tags,AlwaysShow.DisabledandDisabledReason;DestructiveandConfirmMessage- a message alone asks for the secondEnterwithout the danger color.Badge,ValueandChecked.- Nested options as its child content turn it into a page, with
ChildrenPlaceholderfor its search box;MultiSelectmakes that page's rows checkboxes -EnterorSpacechecks one,Ctrl+Enter(Cmd+Enter) calls the parent'sOnExecutewith the checked ones inSelectedCommands.
Checked or Value to state and the row follows it.
What markup cannot say needs the builder:
Data, VisibleWhen, Guard,
ExcludeFromHistory, Actions, ForceLoad, children loaded when the page opens, a page
that searches a source, and a handler that answers with a prompt, a page, a toast or an error rather than closing or
staying open. Pass such commands to the palette's Commands parameter, or register them with the service.
Where a palette's commands come from: the service's registry, shared by every palette in the scope; the markup inside that palette, which belongs to that palette alone; and its
Commands parameter, a third, per-instance list. A
palette with IncludeRegisteredCommands="false" - like every inline one on this page - lists only the last two.
Below, every parameter of both components in one palette: a group with a priority and tags, a page of choices, a multi-select page, a toggle and a setting that keep the palette open, a confirmation, a destructive and a disabled option, links, and an always-shown row with its own icon.
Inline palettes
Inline renders the palette in the page rather than over it - a settings search, a docs search page, a list of
commands in a side panel - with the same search, keyboard and templates. Set it before the first render; changing it later
is not supported. An inline palette is a <section> named like the dialog
(data-bit-cpl="inline", class bit-cpl-inl), always open and as wide as its container;
--bit-CommandPalette-max-height on its Style bounds its list. To make it denser, set
--bit-layout-density-scale (0.8, say) on its Style or an ancestor, and
ShowFooter="false" drops the footer and its key hints.
How it behaves in a page:
Escdisarms a confirmation, goes back a page or clears the query instead of closing; with nothing to undo it is left to the page, so a drawer or a dialog around the palette still closes on it.Tabmoves the focus on, as everywhere else on a page: there is no focus trap, no backdrop and no scroll lock.- A command that would close the palette resets it to its root page, and result counts are announced only while it has the focus.
OpenAsync, CloseAsync or ExecuteAsync, and it claims no global shortcuts (it still
shows them), so nothing runs twice. A key the modal palette claimed - Ctrl+K typed in the inline palette's box -
is left to it. IncludeRegisteredCommands="false" leaves out the registry's commands, sources and modes, so the
inline palette lists only what is declared in its markup or passed to Commands; leave it true for
a search page that should find everything the modal palette finds.
Below, an inline palette in a side panel. Open Go to symbol and press
Esc: the palette goes back. Type
and press Esc: it clears the query. Press Esc once more with nothing to undo: the panel, which
closes on Escape, closes. Format document shows Alt+Shift+F, but pressing it does nothing,
because an inline palette claims no shortcuts; Ctrl+K typed in its box opens the modal palette.
The service
IBitCommandPaletteService is the palette's programmatic surface, registered (scoped) by
AddBitBlazorUIExtrasServices and injected wherever it is needed. Its members:
Register(params BitCommandPaletteCommand[])/Register(IEnumerable<BitCommandPaletteCommand>)- add commands, their static children included; dispose the returnedIDisposableto remove them.Update(command)- replace the command with the same id wherever it was registered, or add it.Unregister(id)- remove one command by its id, nested ones included; returns whether it removed one.Find(id)- look a registered command up by its id, nested ones included;nullwhen there is none.Refresh()- re-evaluate theVisibleWhenpredicates for the global shortcuts and an open list after application state changed.RegisterMode(mode),RegisterSource(source)- add a mode or a default-mode async source at runtime; dispose the result to remove it (see the sections on modes and sources).OpenAsync(query, pageCommandId),CloseAsync()(which cancels a command still running),ToggleAsync()- drive the modal palette; a query may carry a mode prefix and operators, andpageCommandIdopens it directly on a command's page.ExecuteAsync(id)- run a command as if it had been chosen - one from the registry, or one declared in the modal palette's markup or passed to itsCommands- opening the palette when it needs it (a page, a confirmation, a prompt). Guards are asked first. It throwsKeyNotFoundExceptionfor an unknown id, and rethrows what the handler threw unless aCommandFailedsubscriber setHandled.IsOpen,IsMac(true once the palette detected a macOS or iOS browser - render ⌘ instead of Ctrl from it),Commands,Modes,Sources- state.- Events:
CommandsChanged(the registry changed),Opened,Closed,CommandExecuted(the command, itsResultand theDurationof its handler),CommandFailed(the command and theException; a subscriber can change theMessagethe palette shows, or setHandledto say it reported the error itself, which also stops the palette logging it andExecuteAsyncrethrowing it),CommandRefused(a guard refused a command: the command, theTrigger-Palette,ShortcutorProgrammatic- and theMessage; useful because a refused shortcut orExecuteAsyncruns while the palette is closed),PlatformDetected(re-render shortcut hints drawn fromIsMac) andSequencePending(the first chords of a sequence were pressed, thennullwhen it completed, broke off or timed out).
Dispose.
BitCommandPaletteShortcutHint draws a shortcut as key caps; pass it MacKeys="paletteService.IsMac".
Where the services were not registered (an app that lazy loads the palette on WebAssembly),
IServiceProvider.GetBitCommandPaletteService() returns the one the palette uses, and the registered one
otherwise, so code that has to work both ways can always call it. The BitCommandPalette component itself
exposes the same OpenAsync, CloseAsync and ToggleAsync, plus SetQueryAsync,
Query and ActiveCommand, the two-way bindable Open parameter, and the
OnCommandExecuted, OnQueryChanged, OnOpened and OnClosed callbacks.
Below, the buttons drive the service and the log lists its events, newest first. Enter focus mode runs without opening the palette; Sync with the server fails on purpose (its
CommandFailed subscriber replaces the message and
marks it handled); Transfer ownership has a guard that always refuses; Scratch note is removed with
Unregister and registered again. Open the palette, run commands from it, or start a sequence to see the rest.
Handlers and results
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
Checkedis fixed on it: build the commands again from your state after the change (orpaletteService.Updatea 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
keepOpenis true, or the palette is used again meanwhile.Escwhile 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. WithmultiSelect: true,Ctrl+EnterrunsonSubmitwith the checked ones (see Multi-select). - Prompt(title, onSubmit, validate, placeholder, initialValue): turns the search box into a text field and runs
onSubmitwith what was typed (see Prompts).
Enter on a to-do completes it and keeps the palette open.
The command context
BitCommandPaletteCommandContext, which carries what it may need to decide and to act:
- Command: the command being run - its
Id,Title,DataandTags, 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
onSubmitof aPromptresult. - 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
IBitCommandPaletteServiceitself, 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.
AlwaysShow), with the lowest priority so it comes last: type something that matches nothing and run it.
Prompts
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.
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.
Long-running commands
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.
Errors
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.
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 aBitCommandPaletteGuardResult. A command has one guard: a later.Guardreplaces 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
IBitCommandPaletteCommandGuardand register it withbuilder.Services.AddBitCommandPaletteCommandGuard<TGuard>(). It is resolved from the scope, so it can use scoped services such as anAuthenticationStateProvider, and reads the command'sTagsorDatafor 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.
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.
Nested pages
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)(orBitCommandPaletteCmd.Page(title, a, b, c)). Children registered with the service are flattened into the registry with theirParentset, soFind,ExecuteAsync, shortcuts andOpenAsync(pageCommandId: ...)reach them like any other command. "Language" below answersBackfrom 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 whoseServicescome 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 (Enterretries too) and raisesCommandFailed: "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.
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.
Recents, pins and the action panel
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.
Fuzzy matching
ScoreMatch(16) for every matched character;ScoreGapStart(-3) for the first character a gap skips andScoreGapExtension(-1) for each further one.BonusBoundary(8) for a match at the start of a word:gsfinds Go to settings.BonusCamel(7) for a camelCase hump or a letter-to-digit step:fmfinds FuzzyMatcher.cs.BonusNonWord(8) for punctuation the query itself typed, andBonusConsecutive(4) for a character right after the previous match, carrying the bonus that started the run.BonusFirstCharMultiplier(2): the first query character's bonus counts double;BonusCaseMatch(1) for a character whose case matches exactly.
mcp finds
"MCP server", Mcp does not. new BitCommandPaletteFuzzyMatcher { IgnoreCase = true } turns that off.
Between equal alignments the shorter text and the earlier match win, and the ranker puts equal ranks in title order.
The positions of the winning alignment are what the palette highlights with a
<mark> in titles and
subtitles - never splitting a letter from its combining accents or an emoji from its other half. Turn it off with
HighlightMatches="false" on one palette or options.HighlightMatches = false for all of them, and render
the same highlighting in markup of your own with <BitCommandPaletteHighlightedText Text="..." Positions="..." />,
as the table here does. While a query is typed, results stay under their group headings (GroupWhenSearching, on by
default); GroupWhenSearching="false" makes them one flat ranked list.
A field longer than
BitCommandPaletteFuzzyMatcher.MaxOptimalLength (4,096 characters), such as a long description, is
aligned greedily in linear time instead, as fzf does: the term is still found and highlighted, the alignment just is not always
the best one. A query is searched up to BitCommandPaletteQuery.MaxLength (256) characters; a longer one matches no
command (IsTooLong) but is not cut short: commands with AlwaysShow are still listed, and async sources
and handlers still receive all of it.
Type in the palette below. The table runs the palette's own steps with the public API on every keystroke -
BitCommandPaletteQuery.Parse, the Match(command, query) extension of
BitCommandPaletteMatcherExtensions and BitCommandPaletteRanker.Rank - and shows each command's score and
final rank. EnableHistory="false" keeps your own usage (frecency) out of the palette, so it lists the commands in
exactly the table's order. Try gs, fm, rc, mcp and Mcp.
| # | Command | Score | Rank |
|---|---|---|---|
| 1 | Go to settings | 0 | 0 |
| 2 | Git: stash changes | 0 | 0 |
| 3 | Toggle sidebar | 0 | 0 |
| 4 | FuzzyMatcher.cs | 0 | 0 |
| 5 | Format document | 0 | 0 |
| 6 | Open recent file | 0 | 0 |
| 7 | Reload window | 0 | 0 |
| 8 | Rename symbol | 0 | 0 |
| 9 | MCP server | 0 | 0 |
Text as people type it
BitCommandPaletteFuzzyMatcher.Normalize (on
by default) folds both sides before comparing them:
- Latin letters lose their diacritics:
cafefinds "Café",lodzfinds "Łódź" (letters with a stroke too, as in fzf) andturkcefinds "Türkçe". A term that types a diacritic itself means that letter, as in fzf:caféis matched as written. - Arabic and Persian letters that differ only by the keyboard they were typed on are one letter: the forms of yeh (
ي ى ئandی) and kaf (كandک), alef with hamza or madda (أ إ آ ٱandا), teh marbuta and heh with yeh (ة ۀandه), and waw with hamza (ؤandو). A name stored from an Arabic keyboard is found from a Persian one, and the other way round. - Digits are digits: Arabic-Indic and Persian digits are ASCII digits -
۱۲finds "Order 12",٣finds "Step 3" - and fullwidth ASCII, which some input methods type, is ASCII.
BitCommandPaletteTextFold, an internal class shared by the fuzzy matcher,
BitCommandPaletteSubstringMatcher and the query operators, so 'exact, ^prefix,
suffix$ and !negate fold exactly the same way. It is not public API; what an app controls is the
matcher's Normalize property. Every mapping is one character to one, so a position in the folded text is the same
position in the stored one and the highlight lands on the letters as they are stored: typing cafe marks all of
"Café", the é included, and nothing about the stored data changes.
new BitCommandPaletteFuzzyMatcher { Normalize = false } matches every character literally, like fzf's
--literal; set it as options.Matcher to make every palette of the app literal (see "A custom matcher").
The palette below always uses the app's matcher - type the examples into it. The table matches each example against the same
commands with the default matcher, or, with the switch on, with a literal one, so you can see what the folding finds.
| Typed | Finds | Why |
|---|---|---|
cafe |
Café | Latin letters lose their diacritics. |
café |
Café | A term that types a diacritic means that letter, and is matched as written. |
lodz |
Łódź | Letters with a stroke fold too: Ł is L, as in fzf. |
turkce |
Türkçe | ü and ç are u and c. |
علی |
علي | Typed with the Persian yeh (ی), stored with the Arabic one (ي). |
فارسي |
فارسی | The other way round: typed with the Arabic yeh, stored with the Persian one. |
کتاب |
كتاب | Typed with the Persian kaf (ک), stored with the Arabic one (ك). |
اسم |
إسم | Alef with hamza or madda is plain alef. |
العربيه |
العربية | Typed with heh (ه), stored with teh marbuta (ة). |
۱۲ |
Order 12 | Persian digits are ASCII digits. |
٣ |
Step 3 | Arabic-Indic digits too. |
order |
Order 12 | Fullwidth letters, which some input methods type, are ASCII. |
Query operators
'export- exact: the text itself, with no gaps, anywhere in a field.^set- prefix: a field starts with it.project$- suffix: a field ends with it.!minimap- negation: drops every command whose title, subtitle, group or keywords contain the text (description and tags are not looked at). It adds nothing to the score."word wrap"- a quoted phrase: one exact term, spaces included.!"..."excludes a phrase,^"..."and"..."$anchor it. Curly quotes, which some keyboards type, work as well as straight ones, and a quote left open takes the rest of the query while it is being typed, so typing one never shows "no results" midway.^change | ^set- alternatives: a|standing on its own between two terms means either will do, as in fzf.!docker | githolds for anything about git, or not about docker.
'cafe finds "Café"), and they work with any matcher,
the one you plug in included. BitCommandPaletteQuery.Parse(text) is the palette's own parser and is public: its
Terms give each term's Text, its Operator (a BitCommandPaletteQueryOperator:
Fuzzy, Exact, Prefix, Suffix or Negate) and its Group
- terms sharing a group are alternatives of which one has to hold. The palette parses a query once per keystroke, not once per
command.
Type the examples of the table into the palette; the line under it shows, live, what
BitCommandPaletteQuery.Parse
made of what you typed (the palette reports its query through OnQueryChanged).
| Query | Means |
|---|---|
wrap word |
Two fuzzy terms, both required, in any order. |
'export |
Exact: the text itself, no gaps. |
^set |
Prefix: a field starts with it. |
project$ |
Suffix: a field ends with it. |
show !minimap |
Negation: drops every command that contains the term. |
"word wrap" |
A quoted phrase: matched exactly, the space included. |
!"open project" project |
A negated phrase: the projects, except Open project. |
^"set the" |
An anchored phrase: a field starts with it. |
^change | ^set |
Alternatives: starts with change, or with set. |
Typos
settigns still finds
"Settings". What counts as one typo is one edit of the optimal string alignment: a missing, extra or wrong
letter, or two neighbouring letters swapped. A term of 4 to 7 characters may have one, a term of 8 to 64 characters two;
shorter terms (one edit would make them match almost anything), longer ones and terms with an operator get no second chance. A
missing letter is usually found without the retry, since the rest of the term is still in order and the fuzzy matcher allows
gaps.
Only a query that found nothing is retried, so a query that works never gets noisier. The close matches are scored below every exact one, async sources that opt into the matcher (
ApplyMatcher) are re-scored the same way, and the list is
marked and announced "No exact matches. Showing close ones." (BitCommandPaletteStrings.ApproximateResults);
BitCommandPaletteMatch.IsApproximate tells an ItemTemplate a row is a close match. A field is read a
machine word at a time, so a typo is found in a long description too.
The retry belongs to the palette, not to the matcher: calling a matcher directly, as the tables of the previous sections do, never finds a typo. Turn it off for every palette with
options.TypoTolerance = false, or for one palette with
TypoTolerance="false" - flip the switch and try settigns, langauge
(swapped), privacyy (extra), notefications (wrong) and apearence (two).
Field weights
BitCommandPaletteMatchWeights, set for the whole app through options.Weights:
Title1.0Keyword0.9 - Keywords are the synonyms a command is also found by:.Keywords("logo", "color")in C#,Keywords="logo, color"on aBitCommandPaletteOption. They are not shown, except that a row without a subtitle shows the keyword that matched, so the user sees why it is listed (BitCommandPaletteMatch.MatchedKeyword).Subtitle0.7Group0.5Path0.5 - the titles of a nested command's ancestors when it is found from the root page:theme darkfinds "Dark" on the page of "Theme".Description0.4Tag0.3
builder.Services.AddBitBlazorUIExtrasServices(commandPalette: options => options.Weights.Description = 0.6).
Every command below holds "color" in a different field. Type
color (or col, clr) into
the palette: it lists them in the order of the weights. The table shows, for what you typed taken as one fuzzy term, the field
that won, its raw score, its weight and the product. GroupWhenSearching="false" keeps the palette one flat ranked
list, so the group of "Contrast checker" does not move it under a heading of its own.
| Command | Field that won | Raw score | Weight | Weighted |
|---|
Priority and frecency
rank = score + Priority × PriorityWeight + ln(1 + frecency) × FrecencyWeight, with
options.PriorityWeight 0.25 and options.FrecencyWeight 6 by default - a clearly better match always
wins, and among close ones the command you use wins. Equal ranks go by title. On the empty query there is nothing to match, so
priority leads and frecency orders what is left (priority × 1000 + frecency), inside each group, and
commands of equal priority keep the order they were registered or declared in. Only the best options.MaxResults
(150) rows are kept per query; pinned and recent commands are listed beyond it.
A priority is any
int; BitCommandPaletteCommandPriority names the usual levels: Lowest
(-100, a feedback row with AlwaysShow), Low (-50, documentation hits), Normal (0, the
default), High (50) and Highest (100). Set it with .Priority(...) in C#, with
Priority on a BitCommandPaletteOption, or on a BitCommandPaletteGroup for all of its
options that set none.
Frecency is Firefox's idea: the number of uses, capped at 20, times a weight for how long ago the last one was - 100 within 4 hours, 70 within a day, 50 within three days, 30 within a week, 10 within a month, 5 after that - divided by 10. The palette records every run in its history (see recents), and
BitCommandPaletteHistory.ComputeFrecency(usage, now)
is the formula, public.
The table ranks five commands with a
BitCommandPaletteRanker built over options with the sliders' weights, using
frecencies computed from made-up usage: "Report a bug" was used 3 times five days ago, and "Weekly report" as often as the
third slider says, two hours ago. Raise its uses and watch it overtake the others on report; raise
PriorityWeight and "Reports overview" (High) pulls ahead; clear the query and priority alone decides. The palette
lists the same commands with the app's weights and no history (EnableHistory="false").
| # | Command | Priority | Frecency | Score | Rank |
|---|---|---|---|---|---|
| 1 | Reports overview | 50 | 0 | 151.68 | 164.18 |
| 2 | Report a bug | -50 | 9 | 151.76 | 153.08 |
| 3 | Sales report | 0 | 0 | 151.7 | 151.7 |
| 4 | Weekly report | 0 | 0 | 151.67 | 151.67 |
| 5 | Archived reports | -100 | 0 | 151.59 | 126.59 |
A custom matcher
IBitCommandPaletteMatcher is one method - Match(query, text) - returning a
BitCommandPaletteFieldMatch(Matched, Score, Positions): whether the text matches, how well, and the indexes of the
characters to highlight (BitCommandPaletteFieldMatch.None for no match, Empty for an empty query). The
palette calls it once per fuzzy term per field, so multi-term queries, the operators (which fold diacritics and Arabic-script
letters with any matcher but a literal one), field weights, ranking and the typo retry all keep working with a matcher of your
own. Set it for the whole app with options.Matcher in the commandPalette argument of AddBitBlazorUIExtrasServices; the ready-made ones
are:
BitCommandPaletteFuzzyMatcher.Default- the default;new BitCommandPaletteFuzzyMatcher { IgnoreCase = true }drops smart case,{ Normalize = false }matches literally.BitCommandPaletteSubstringMatcher.Default- a case-insensitive substring matcher that scores a match at the start higher, for data where fuzziness hurts more than it helps (codes, part numbers). It folds like the fuzzy one unless itsNormalizeis false.
Match(command, query, weights)
extension of BitCommandPaletteMatcherExtensions matches a whole command (with a query string, or one parsed once with
BitCommandPaletteQuery.Parse for many commands) and returns a BitCommandPaletteMatch, or null. It carries
the Score, the TitlePositions and SubtitlePositions to highlight, the
MatchedKeyword, the Path of a nested command found from the root, IsApproximate for a typo
match, FromSource and SourceName for a source's result, and - once BitCommandPaletteRanker.Rank
(injectable, or created over options) has ordered the matches as the palette does - its Rank and
Frecency. Matching runs over the command's own fields; an async source opts into it with ApplyMatcher.
options.Matcher is one setting for the whole app, so instead of changing it, this demo runs each matcher directly
over the commands of the "Fuzzy matching" section. DPrefixMatcher is a complete custom matcher: a field matches when
it starts with the term. Compare re, rc and Mcp across them.
| # | Command | Score |
|---|---|---|
| 1 | Reload window | 55.74 |
| 2 | Rename symbol | 55.74 |
| 3 | Open recent file | 55.63 |
| 4 | MCP server | 28.74 |
| 5 | Format document | 20.68 |
Modes
> in VS Code, # and @ on
GitHub - that scopes the palette to part of the registry, to its own async sources, or both. A
BitCommandPaletteCommandMode has:
Prefix(required) - what activates it. The longest matching prefix wins, so>>and>can coexist.Name(required) - the chip shown next to the search box while the mode is active, and the title of its hint.Description- the hint's subtitle.Placeholder- the search box's placeholder while the mode is active.Tags- only commands carrying one of these tags (.Tags(...)in C#,Tagson an option or a group).Groups- only commands in one of these groups.HideRegistryCommands- no registry commands at all, only the mode's sources.Sources- the async sources asked in this mode, instead of the default mode's (see "Async sources").ShowHint(default true) - whether the mode is listed as a hint.
options.Modes in the commandPalette argument of AddBitBlazorUIExtrasServices, or at runtime with
IBitCommandPaletteService.RegisterMode(mode), which returns an IDisposable that removes the mode again:
this page registers its modes when it opens and disposes them when you leave. IBitCommandPaletteService.Modes lists
what is registered - the table below. On the empty query of the default mode the palette lists every mode with
ShowHint under a "Modes" heading, so they can be discovered without reading any docs, and picking a hint types its
prefix; options.ShowModeHints = false drops the whole group. A mode scopes the registry and its sources only:
nested commands are never found from a mode.
To open the modal palette directly in a mode, give a
BitCommandPaletteTrigger a Query that starts with
the prefix (Query=">"), or call paletteService.OpenAsync(">"). Modes are registered with the
service, so a palette has them only while IncludeRegisteredCommands is on: the inline palette below leaves it on and
lists every command registered on this page, with the mode hints at the top. Type > for the commands tagged
"command", ? for the Help group, or >> - a mode with no hint - for everything.
| Prefix | Mode | Lists | Hint |
|---|---|---|---|
> |
Commands Run an editor command | commands tagged command | Yes |
? |
Help Browse the help topics | the Help group | Yes |
>> |
Everything Every registered command | every command | No |
@ |
People Find a teammate or a team | only its sources: People, Teams | Yes |
$ |
Packages Browse 60 packages, 10 at a time | only its sources: Packages | Yes |
Async sources
IBitCommandPaletteSource) searches what the registry does not hold - an API, a database, a
search index - as the user types. It has a Name (the heading of its results, and of its retry row) and
SearchAsync(query, context, cancellationToken), and three members with defaults: MinQueryLength
(1; 0 also asks on the empty query, so a mode opens on a list), MaxResults (20, the most rows taken from it) and
ApplyMatcher (false). Give every result an Id of its own - two people can share a name, and recents and
pins go by the id. The BitCommandPaletteSourceContext says which mode asked (ModePrefix), which page
asked (ParentCommandId) and carries the user's Services, to resolve a scoped API client from.
Re-ranked or ordered. With
ApplyMatcher = true the palette scores what the source returns with its own matcher
and sorts it in with everything else: the source only has to return candidates, and its rows are highlighted like the rest.
With false, the source's own order is kept and its rows are listed as one block under its name - right for a server
that already sorts by relevance.
Debounced, cancelled, timed out. A source is asked only after
options.DebounceMs (150 ms) without typing, so
most keystrokes never reach it, and a search still running when the next one starts is cancelled through its token - hand the
token to whatever waits, and stale results never show. While any source is pending a spinner replaces the search icon, and a mode
or page with nothing to show yet shows "Searching…" (LoadingTemplate replaces it). A source that throws, or has not
answered after options.SourceTimeoutMs (10 s; 0 waits forever) - whether or not it honours its token - is logged and
leaves a row in its place, "Couldn’t search Service status" in the danger color (BitCommandPaletteStrings.SourceFailed),
that asks it again when chosen. The other sources' results stay: one failing API does not take the whole list with it.
Registering them. Sources in
options.Sources are asked in the default mode, and so are the ones registered at
runtime with IBitCommandPaletteService.RegisterSource (which returns a handle that removes it) and the ones resolved
from DI with services.AddBitCommandPaletteSource<TSource>() - those are scoped, belong to the scope, and stay
registered whichever palette comes and goes. A mode asks its own Sources instead, and a command's page can ask one
too (see "Searching from a page"). Two ready-made sources cover the common cases: BitCommandPaletteDelegateSource
wraps a delegate (taking the query, or the query and the context, or - see "Paging" - a cursor too), and
BitCommandPaletteStaticSource serves an in-memory list, fixed or read again on every search, through the palette's
own matcher and weights, returning its best maxResults (50) - always re-ranked, asked from the first character.
This page registered an
@ People mode whose sources are a DPeopleSource (re-ranked, 250 ms of fake
latency) and a BitCommandPaletteStaticSource of teams, and a default-mode "Service status" source - a delegate
source, ordered, asked from 3 characters - whose behaviour you pick. Open the modal palette and type at your normal speed: the
table lists every call that reached a source, newest first, and how it ended. Pick "Never answers" and search "status": the
call is cancelled after 10 s and the retry row appears.
| Started | Source | Query | Outcome | Results | Took |
|---|---|---|---|---|---|
| No source has been asked yet. | |||||
Paging
SearchPageAsync(query, cursor, context, cancellationToken): the first page with a null cursor, each next
one with the NextCursor of the page before. It returns a BitCommandPaletteSourcePage(Commands, NextCursor,
TotalCount); HasMore is true while there is a next cursor. A page with a cursor gets a row after the source's
results - "Show 50 more…" when the page says TotalCount (BitCommandPaletteStrings.MoreResults), "Show
more…" when it does not (LoadMore) - which loads the next page, appends it without repeating what is already
listed, and selects its first row. A next page that fails keeps the pages already listed, with a row to try again. A source that
implements only SearchAsync answers a single page: SearchPageAsync has a default implementation that
calls it.
BitCommandPaletteDelegateSource has a paging constructor whose delegate takes the query, the cursor, the context and
the token. The cursor is whatever the server understands - an offset, as here, or an opaque continuation token.
This page registered a
$ Packages mode over 60 packages, 10 at a time, with
MinQueryLength = 0 so it opens on a list. Open it, scroll to "Show 50 more…" and choose it; the call log of the
"Async sources" section shows every page it loaded.
Searching from a page
.Source(name, search) on a command builder turns the command
into a page whose rows come from search(query, cancellationToken); it is asked when the page opens
(minQueryLength is 0 by default here, so the page never opens empty) and for every query typed on it, with the same
debounce, cancellation, timeout, retry row and loading state as the root's sources. .Source(name, searchPage) takes a
paging delegate - query, cursor, token - with its "Show more…" row, and .Source(IBitCommandPaletteSource) takes any
source, whose BitCommandPaletteSourceContext.ParentCommandId then says which page asked. ChildrenPlaceholder
sets the page's placeholder.
On a
MultiSelect page the checked rows are kept across searches, so Ctrl+Enter (Cmd+Enter)
hands the handler everything checked, whichever query listed it.
Open "Assign to…" and search people, open "Request reviews…" and check people from several searches before applying, or open "Browse packages…" for a paged page source.
Performance
- The registry is read once, not per keystroke: the palette keeps a snapshot and takes a new one only when the registry, the commands declared in its markup or its
Commandsparameter changed. PassCommandsa new collection to change it, or callIBitCommandPaletteService.Refresh()after changing one in place. Global shortcuts are re-evaluated when the snapshot changes, when the palette opens or closes, after a command ran and onRefresh()- not while typing. - The query is parsed once per keystroke, not once per command, and the matcher allocates nothing per field but the highlighted positions: it reuses per-thread buffers, keeps one row of scores, rejects texts that do not hold the term before the dynamic programming starts, and aligns a field past
MaxOptimalLengthgreedily without buffers. - Ranking only sorts what it keeps: only the best
options.MaxResults(150) rows are rendered per query, held in a heap and sorted. Raise it for long lists - and turn onVirtualize(on one palette, oroptions.Virtualize), recommended above about 500 visible rows, which renders only the rows on screen. While it is on, every row isoptions.RowHeight(44 px) tall, whatever--bit-CommandPalette-row-heightsays, and each option carriesaria-posinsetandaria-setsize, since rows cannot be wrapped in their groups. - Results arriving from async sources reuse the registry's matches for the same query instead of matching again.
- Typing never lags on WebAssembly, where search and painting share the page's only thread: when a search took longer than a frame (8 ms), the palette lets the keystroke paint first and folds the keys typed meanwhile into one search; navigation keys still act on the latest query. On the server each keystroke round-trips anyway, so it searches right away.
paletteService.Register(commands), or a palette's
Commands) are part of the registry: listed on the empty query, matched by every keystroke, reachable by
Find, ExecuteAsync and their shortcuts. A BitCommandPaletteStaticSource keeps a large list
out of the registry instead: asked only once something is typed, it matches its items with the app's matcher and weights and hands
back only its best maxResults (50), under its own heading - right for a catalog of thousands of records where only
what was searched for should show.
The numbers below are measured here, in your browser. Pick a size: the inline palette holds that many synthetic commands - type in it. "Measure searches" times the matcher and the ranker the palette runs, over the same commands (the median of 5 runs per query), and one whole
SearchAsync of a static source over them. "Register them with the service" adds them to the
modal palette's registry as well (and times it); they are removed when you unregister them or leave the page.
Keyboard inside the palette
Ctrl
on Windows and Linux and ⌘ on macOS and iOS.
| Keys | What they do |
|---|---|
| Mod K and the other toggle shortcuts | Open or close the modal palette (see "The toggle shortcut" below). |
| ↑ ↓, Ctrl N / Ctrl P | Move the active row, wrapping around at either end unless Loop is off. Ctrl N / P work on every platform, also on a Mac. |
| Ctrl J / Ctrl K | Move down / up, when VimBindings is on. |
| Home End | Jump to the first or the last row. |
| PgUp PgDn | Move ten rows up or down, stopping at the ends. |
| Enter | Run the active command, open its page, flip a toggle, check a row of a multi-select page, submit a prompt, or arm and then confirm a destructive command. On a page that failed to load it retries. |
| Space (empty search box) | Check or uncheck a row of a multi-select page. |
| Mod Enter (⌘ ↩) | Apply a multi-select page, run the active row's first secondary action, or open a plain link in a new tab (as GitHub's palette does). |
| Tab, → (empty search box), a right click | Open the action panel of the active row: its own actions, then "Pin to top" / "Unpin", "Remove from recents" and "Clear recent commands". |
| Backspace, ← (empty search box) | Go back one page. |
| Esc | Disarm a confirmation, then go back a page, then close the modal palette. An Inline palette clears its query instead of closing. |
| Mod Shift P | Pin or unpin the active row; pinned commands are listed first on the empty query. |
| Shift Del | Remove the active row from the recents. |
These keys are claimed in the browser before Blazor sees them, so Tab never leaves the modal dialog and Backspace never deletes text it should not, even over a slow Blazor Server connection. In right-to-left text ← and → trade places: → points back to the start of the line, so it goes back a page, and ← opens the action panel. Inside the open modal palette its own chords win over a toggle bound to the same keys: with Vim bindings on, Ctrl K moves up rather than closing it, and Mod Shift P pins even when it is also a toggle shortcut.
An Inline palette is a part of the page, not a dialog, so a few keys behave as they do anywhere else on it: Tab moves the focus on (open the action panel with → or a right click there), and the page's modal palette keeps its toggle - with the default Mod K, pressing Ctrl K in the Inline palette below opens the modal one on Windows and Linux even with
VimBindings on; Ctrl J and
Ctrl N / P are always the Inline palette's.
Three parameters tune the navigation of one palette, and the options of the same names (
BitCommandPaletteOptions.Loop, default true, and VimBindings, default false) set them for all:
- Loop: arrowing past the last row comes back to the first. Off, the arrows stop at the ends.
- VimBindings: adds Ctrl J / Ctrl K to the always-on Ctrl N / Ctrl P.
- DisablePointerSelection: hovering a row no longer makes it the active one - only the keys and a click do. Without it, hover moves the active row only after the pointer actually moves, so a list that scrolls under a resting pointer never steals the selection from the keyboard. Clicking a row leaves the focus in the search box.
Global shortcuts
Alt+Shift+N or a sequence such as G N (G, then N). Register such commands
through IBitCommandPaletteService (or with BitCommandPaletteCommands, for the commands of one
page): the modal palette on the page claims their keys, and while there is no modal palette - or only Inline ones,
which claim no global keys - the shortcuts do nothing, so nothing ever runs twice.
The registered shortcuts are synced to the browser as strings and matched there, so only a completed shortcut crosses the interop boundary - typing on the page never causes a round trip, even on Blazor Server. Whatever needs the palette opens it: a command with a page (
G C below opens on its colors), one with a confirmation
(Alt+Shift+D), and a handler that answers with a page, a prompt or a toast that stays open. A confirmation
started this way gets a page of its own, so the second Enter confirms that command and no other. Only a
command that can run claims its keys: the shortcut of a disabled command, or of one its VisibleWhen
predicate hides, is left to the page - call paletteService.Refresh() after the state such a predicate
reads changed.
Shortcut(text, global: false) keeps a shortcut to the palette's rows: it is shown as a hint on the row (Preview the note shows Space in the modal palette), but claims no key on the page - for keys the page or a component already handles itself.
Typing is not a shortcut. A plain key pressed while an input, a text area, a select or a content-editable element has the focus is typing, so G then N in the text field below does nothing; a chord with Ctrl, Alt or ⌘ still fires there, because nobody types those by accident. Set
BitCommandPaletteOptions.SuppressShortcutsInEditableElements (default true) to false to let plain keys fire
from text fields too.
The table below reads the registry right now: it lists every command with a global shortcut that this page's sections have registered, and updates through the service's
CommandsChanged event. Press one with the palette closed.
| Shortcut | Command | Kind |
|---|---|---|
| Alt+M | Merge selected files | chord |
| G then X | Export as PDF | sequence |
| Alt+Shift+N | New note | chord |
| G then N | Go to notes | sequence |
| G then C | Change the note color | sequence |
| Alt+Shift+D | Discard the draft | chord |
| Alt+Q | Save draft | chord |
| Alt+↑ | Increment counter | chord |
| Alt+↓ | Decrement counter | chord |
Keyboard layouts, held keys and input methods
- Non-Latin layouts. A shortcut is matched on the character the key types and, when that is not an ASCII
character, on the key it sits on as well (
KeyboardEvent.code, as VS Code does): Ctrl K works when a Russian layout typesл, G N when a Persian one typesلد, and the same holds for Arabic, Greek and every other layout whose letters are not ASCII. A Latin layout such as Dvorak or AZERTY keeps its own letters: thereMod+Qis the key that types Q. - Held keys. A held key's repeats are claimed - the browser does not act on them - but run nothing, so a held Ctrl K does not flicker the palette open and shut, and a held shortcut does not run its command over and over.
- AltGr and Option. A character typed with AltGr, or with Option or Alt alone (
Ωfor Option+Z on a Mac,@for AltGr+Q on a German layout), is typing when it lands in a text field, not the shortcut its physical key would make. - Input methods. Keys that belong to an input method's composition (
isComposing, orkeyCode229) are never shortcuts, inside the palette or out, so confirming a Japanese or Chinese candidate with Enter does not run the active row.
Sequences in progress
- SequenceTimeoutMs (
BitCommandPaletteOptions, default 1000): how long a sequence waits for its next chord before it breaks off. It must be positive; zero or less throws anArgumentOutOfRangeException. - ShowSequenceHint (default true): set it to false to show nothing - for an app that shows the pending keys itself.
- IBitCommandPaletteService.SequencePending reports the sequence to code either way: raised with the chords pressed so far, and again with null when it completed, broke off or timed out. The status line below listens to it.
bit-cpl-sequence element (data-bit-cpl="sequence", with
data-pending="true" while it shows), and its words are BitCommandPaletteStrings.SequencePending
("waiting for the next key…") and ShortcutThen ("then").
Shortcut conflicts
Mod+S
takes over from the layout's while the page is shown, and gives the keys back when it is disposed. The modal palette
checks the shortcuts whenever the registry changes and logs a warning through ILogger (the browser's
console on WebAssembly, the server's log on Blazor Server), once for each problem:
- A duplicate: a shortcut several commands claim - the warning names them all and the one that runs.
- Shadowed by the toggle: a command's shortcut that is also a toggle shortcut of the palette, which takes it, so the command never runs from it.
- An unreachable sequence: one whose first chords are a shortcut of their own and fire first -
Gregistered next toG I. - A browser-reserved key: one browsers keep for themselves and never hand to a page -
Mod+W,Mod+T,Mod+N, theirShiftvariants,Mod+Q,Ctrl+Tab,Alt+F4.
.Id(...). These configuration warnings always name the commands, even with
RecordCommandIdsInTraces off. Inline palettes claim no global keys, so they report none of this.
This page registers "Save draft" on Alt Q. Register "Save and publish" on the same keys and, with the palette closed, Alt Q runs it instead - the later registration wins - while the log shows the palette's warning naming both. Dispose it and the keys are "Save draft"'s again.
Shortcut syntax
BitCommandPaletteKeyboardShortcut: one or more BitCommandPaletteKeyChords
pressed in order. Write it as text: chords are separated by spaces and keys inside a chord by + -
Mod+K, Ctrl+Shift+P, G I, Alt+Z, F2,
Shift+?. A string converts implicitly wherever a shortcut is expected (.Shortcut("G I"), the
options' ToggleShortcut, the Shortcut of BitCommandPaletteShortcutHint).
- Mod is ⌘ on macOS and iOS and Ctrl elsewhere - the one to use for an app's own
shortcuts (
CmdOrCtrlandCommandOrControlmean the same).Ctrlis Ctrl (⌃) everywhere, andMetais ⌘ on a Mac and Win elsewhere. - Modifiers have aliases:
Controland⌃;⇧;Option,Optand⌥forAlt;Cmd,Command,Win,Superand⌘forMeta. - So do keys:
Esc,Return,Space(orSpacebar),Del,Ins,Up/Down/Left/Right,PgUp,PgDn,Plus,Minus,Comma,Period,Slash,Backslash. Any other key is the browser'sKeyboardEvent.keyname (F2,Home,Tab), matched case-insensitively. A shifted character also fires without itsShift:?fires on Shift / of a US layout. BitCommandPaletteKeyboardShortcut.Parsethrows aFormatExceptionfor a chord without a key (Ctrl+Shift) or with two (A+B);TryParsereturns false instead.- Two shortcuts are equal when their
Normalizedforms are - lower case, modifiers in a fixed order (mod+ctrl+alt+shift+meta+key) - soCtrl+Kequalscontrol+k.IsSequenceandChordstell a sequence from a chord,ToDisplayString(isMac)spells it out ("Ctrl+Shift+K", "G then I") andDisplayTokens(isMac)gives the key caps a hint renders.
| On macOS | ⌘⇧K |
|---|---|
| Elsewhere | Ctrl+Shift+K |
| In words | Ctrl+Shift+K |
| Normalized | mod+shift+k |
| Kind | a chord |
Platform-aware hints
- IBitCommandPaletteService.IsMac exposes the result to your own UI. It is false until the palette has
started, and the service's PlatformDetected event says when it is known: subscribe to it to render
again (and unsubscribe in
Dispose- the service outlives the page). - BitCommandPaletteShortcutHint renders any shortcut as the palette does: key caps in
<kbd>elements, laid out left to right even in right-to-left text, as on the keys themselves, and hidden from screen readers, which read its words instead ("Ctrl+Shift+K", "G then S"). Its MacKeys parameter picks the macOS symbols (passpaletteService.IsMacto follow the platform), and Strings the word between the chords of a sequence (ShortcutThen).ClassandStylestyle it. - BitCommandPaletteTrigger follows the detected platform by itself; its MacKeys parameter forces the symbols on or off.
| This platform | Ctrl+Shift+K | G then S |
|---|---|---|
| MacKeys | ⌘⇧K | G then S |
| MacKeys="false" | Ctrl+Shift+K | G then S |
The toggle shortcut
- ToggleShortcut (
BitCommandPaletteOptions, defaultMod+K: ⌘ K on a Mac, Ctrl K elsewhere) is the main one, and the oneBitCommandPaletteTriggershows. - AdditionalToggleShortcuts adds more keys that do the same -
Mod+Shift+Pfor people used to VS Code, or/; a sequence works too. - The palette's ToggleShortcut parameter overrides the option's main shortcut for that palette
(
ToggleShortcut="Mod+P"); a value that does not parse is ignored and the option applies. The additional shortcuts always come from the options. - A toggle of null: set
options.ToggleShortcut = nullfor no main toggle shortcut - the palette then opens only fromAdditionalToggleShortcuts, aBitCommandPaletteTrigger, its boundOpenor the service'sOpenAsync/ToggleAsync- for an app whose own editor uses Ctrl K.
Disabled one, claims none. While the
palette is open only single-chord toggles stay global, and its own chords win over a toggle bound to the same keys -
with Vim bindings on, Ctrl K moves up inside the palette rather than closing it. A command
shortcut that is also a toggle shortcut never runs, and the palette logs it (see Shortcut conflicts).
The toggle shortcuts of this site, read from the injected options:
Options
Program.cs through
builder.Services.AddBitBlazorUIExtrasServices(commandPalette: options => ...) - in both the server and the client project
of a Blazor Web App. The options are a singleton shared by every palette and every user of the app; the registry, the
open state and the history are scoped (per circuit on Blazor Server, per tab on WebAssembly). Numbers that must be
positive, or not negative, throw an ArgumentOutOfRangeException when set otherwise, so a bad value fails at
startup. What each group is for:
- Keyboard -
ToggleShortcut,AdditionalToggleShortcuts,SuppressShortcutsInEditableElements,SequenceTimeoutMs,ShowSequenceHint,Loop,VimBindings: the sections above. - Search and ranking -
Matcher,Weights,MaxResults,GroupWhenSearching,GroupOrder,PriorityWeight,FrecencyWeight,SearchNestedCommands,TypoTolerance,HighlightMatches: how a query is matched, ranked and shown. - Modes and sources -
DebounceMs,SourceTimeoutMs,ShowModeHints: how async sources are asked and when they count as failed. - Registered at startup -
Commands,Modes,Sources: what the registry holds before any page registers anything. - History -
EnableHistory,MaxRecents,MaxHistoryEntries,HistoryStorageKey: recents, pins and frecency (see History storage). - Display and behavior -
CloseOnBackdropClick,CloseOnNavigation,ResetOnClose(false reopens where it was left),ShowFooter,ShowShortcuts,Virtualize,RowHeight,Strings. - Security and diagnostics -
AllowedUrlSchemes,RecordCommandIdsInTraces(see Security).
bit-theme="dark" attribute on it or an
ancestor, or a BitThemeProvider), and its density follows --bit-layout-density-scale (e.g.
0.8 on its Style or an ancestor). The full table of options, with types and defaults, is in the
BitCommandPaletteOptions sub-class below.
The Inline palette below searches the options themselves, each listed with the value this site runs with - type
history or shortcut. It is driven through the component rather than the service: a
@ref to call SetQueryAsync (sets the query as if typed) from the buttons, and
OnQueryChanged to follow what is typed. The component also exposes IsOpen, Query and
ActiveCommand, and OpenAsync, CloseAsync and ToggleAsync - the same as
the service's, for the code that holds a reference to one palette.
Options, parameters and BitParams
- The palette's own parameter -
<BitCommandPalette Loop="false" />- always wins. - A BitCommandPaletteParams cascaded through a BitParams: every palette under the
BitParamstakes each parameter it did not set itself from it - the defaults of one area of an app, such as an admin section or the Inline palettes of a settings page. A nestedBitParamsrefines the one around it: it replaces only what it sets, unless it isIsolated. - BitCommandPaletteOptions, the app-wide default, for whatever neither of the above set.
BitCommandPaletteParams carries what the palettes of an app agree on - their look and words and how they
search and navigate: Classes, Styles, Placeholder, Strings,
DisablePointerSelection, and the option overrides EnableHistory,
GroupWhenSearching, HighlightMatches, Loop, SearchNestedCommands,
ShowFooter, ShowShortcuts, TypoTolerance, VimBindings and
Virtualize, plus the parameters every BlazorUI component shares (Class, Style,
Dir...). What makes one palette itself - Inline, Open, its
Commands, templates and callbacks - is not cascaded. The option overrides are nullable: left unset, on the
palette and in the params, the option applies.
Both palettes below sit in one
BitParams that sets a placeholder, hides the footer, turns highlighting and
history off and Vim bindings on. The first takes all of it; the second sets Placeholder,
ShowFooter and HighlightMatches itself, and those win. Type "an" in both. Loop,
set by neither, comes from the options.
Security
- Text is text. Titles, subtitles, descriptions, badges, values, queries and whatever a source returns are
rendered as text by Razor, never as HTML: the second row below has a title made of an
<img onerror>tag, shown as the characters it is. Icons areRenderFragments you build, or a CSS class name. - Links are checked. A command's
Hrefis followed only when it is relative or its scheme is in AllowedUrlSchemes (BitCommandPaletteOptions;http,https,mailtoandtelby default, compared case-insensitively). Ajavascript:,data:orvbscript:link - read the way a browser reads it, tabs and control characters included - is refused: the palette shows its generic failure message and logs a warning naming the command and the scheme. Choose the first row below: nothing runs. Add a scheme for links an app trusts (options.AllowedUrlSchemes.Add("vscode")) or remove one it does not need. - Errors are generic. A failed command shows
BitCommandPaletteStrings.CommandFailed("Couldn't run “…”"), never the exception's text, which can name a server, a table or a user; the exception goes to the log and to the service'sCommandFailedevent. - Visibility is not authorization.
VisibleWhenandDisabledonly shape the UI. Guards are asked every time a command is about to run - from a row, a shortcut or code - and refuse it when they say so (see the Guards section). On WebAssembly they run in the browser, so the server must still check every action a handler asks it to perform. - Ids and titles. The history stores command ids, use counts and times - never queries, titles or prompt
values - and traces carry the id of the command that ran. Keep personal data out of ids: use an opaque id
(
person:1042, not the e-mail address), and mark a command built from personal dataExcludeFromHistory(), as the third row below is. Titles are shown, searched and announced, but never stored or traced. - RecordCommandIdsInTraces (default true): set it to false when ids embed personal data anyway. The
bit.command_palette.commandactivities then carry no id, and the log messages about running a command - a failure, a refusal, a guard that threw, an unsafe link - read(hidden)instead of its id and title. Metrics never carry ids; the configuration warnings about shortcuts and duplicate ids still name the commands an app registers. - Stored history is validated when it is read: entries a hand-edited or corrupt
localStorageholds are dropped. - Search is bounded. A query longer than
BitCommandPaletteQuery.MaxLength(256) characters matches nothing instead of being searched, and a field longer thanBitCommandPaletteFuzzyMatcher.MaxOptimalLengthis aligned greedily in one pass, so a pasted wall of text cannot make a keystroke expensive. Search work still grows with the fields you give it: keep descriptions to what a row needs, and search large documents through an async source backed by a real index. - No inline script. The palette's browser layer adds no inline scripts and uses no
eval, so a content security policy needs nothing extra for it.
History storage
ExcludeFromHistory - as the command's id, how often it ran,
when it last ran, and whether and when it was pinned (BitCommandPaletteCommandUsage). The counts feed the
recents and pins on the empty query and the frecency that nudges ranking. The history is scoped - one per circuit on
Blazor Server, one per tab on WebAssembly - and shared by every palette in it, modal and Inline alike, keyed by command
id: give the commands of different palettes different ids.
- The default store keeps it in the browser's
localStorageunder HistoryStorageKey (BitCommandPaletteOptions, defaultbit-command-palette.history), so recents survive a reload. Change the key to keep two apps on one origin apart. While prerendering, with storage disabled or with corrupt data, it starts empty, and saving is best-effort. - AddBitCommandPaletteInMemoryHistoryStore() keeps it in memory only, for the lifetime of the scope, so nothing is written to the browser - for shared machines or kiosks.
- AddBitCommandPaletteHistoryStore<T>() replaces the store with your own
IBitCommandPaletteHistoryStore- for example per user, on the server, so a person's recents and pins follow them from device to device. It has two methods,LoadAsync(once, when a palette first needs the history) andSaveAsync(after every change, with the whole history); it is resolved from the scope, so it can take the signed-in user's services. A store that throws is logged; the palette then starts empty, or keeps the change for the session only. - MaxRecents (default 5) is how many recent commands the empty query lists, and MaxHistoryEntries (default 200) how many commands the history keeps at most: past it, the least recently used are pruned, pinned commands never. Both must not be negative.
- EnableHistory (default true) turns it all off - for every palette with the option, for one with the
parameter or through
BitCommandPaletteParams.
Not read yet.
Item template
Row: the BitCommandPaletteRow being drawn.Row.Commandis the command;Row.Matchsays how the query matched it:TitlePositionsandSubtitlePositions(the matched character indexes),MatchedKeyword(the keyword that matched when the title did not) andPath(the titles of the pages above a nested command found from the root page, "Theme › Dark").Row.Groupis its heading andRow.ItemIndexits position among the rows.IsActive: the row the arrow keys are on, which Enter runs.IsChecked: the row is checked on a multi-select page.IsPinned: the command is pinned to the top of the recents.IsConfirming: a destructive command waiting for its second Enter.IsMac: the palette runs on a Mac, so key names should be the Mac symbols (⌘, ↩).
role="option", its aria-selected,
aria-checked and aria-disabled, the id that aria-activedescendant points at, its
data-bit-cpl="item" and state attributes (data-active, data-disabled...), its
hover and click handling and its Classes.Item / Classes.ActiveItem. A template therefore
cannot break keyboard navigation or what a screen reader hears about the row.
Two helpers bring back what the default row draws:
- BitCommandPaletteHighlightedText (
Text,Positions) renders a text with each run of matched characters in a<mark>, painted with--bit-CommandPalette-mark-background. It widens a match to whole grapheme clusters, so an accent or half of an emoji is never split off. PassRow.Match?.TitlePositionsfor the title andSubtitlePositionsfor the subtitle. - BitCommandPaletteShortcutHint (
Shortcut,MacKeys,Strings,Class,Style) renders a shortcut as key caps, in the platform's symbols whenMacKeysis set. The caps always read left to right and are hidden from screen readers, which hear the shortcut in words ("Ctrl+K", "G then S").Stringsgives the word between the chords of a sequence.
aria-hidden, never put a button or a link inside a row (the focus
stays in the search box and rows are never focused), and draw nothing the palette already says: see Accessibility below.
EnableHistory="false" keeps this sample's runs out of the recents, so the list stays as it is.
Type
cs or src to see the highlighting, and open a file for the toast.
Icon & group header templates
ItemTemplate it leaves the rest of the row to the palette - the highlighted title, the subtitle, the badge, the
switch, the shortcut and the chevron - and only fills the icon slot, a small square at the start of the row that is hidden
from screen readers. It wins over a command's own Icon and IconCss and over the icon the palette
picks for the command's kind; render nothing for a row without an icon. It has no effect while an ItemTemplate
is set, since that replaces the whole content of the row, icon included.
GroupHeaderTemplate replaces the content of every group heading and receives the heading's text. The heading element stays the palette's: it sticks to the top of the list while its group scrolls, carries
Classes.GroupHeading,
and is what the group's role="group" is named by (aria-labelledby), so a screen reader announces
the group by the text the template renders. Keep the heading's words in it, and hide the decoration from screen readers
as the sample does with its glyph.
Here the icon is the extension's initial, colored by the extension, and each heading gets a glyph.
Header & footer templates
ShowFooter, on by default). Both receive a BitCommandPaletteStateContext, a snapshot of the palette
taken on every render:
Query: what is searched for, without a mode's prefix;ModePrefixandModeName: the mode typed, if any.Breadcrumbs: the titles of the pages opened, empty on the root page.ResultCount,ActiveIndexandActiveCommand: how many rows are listed and which one is active.IsLoading: a lazily loaded page or an async source has not answered yet.IsMultiSelectandSelectedCount: a multi-select page and how many rows are checked.Toast: the message a command returned, or a confirmation or an error, while it is shown.IsMac: whether to name the keys with the Mac symbols.
FooterTemplate
or no footer at all - so a footer template that shows Toast gives it no role="status" or
aria-live of its own, which would have it announced twice. Classes.Header and
Classes.Footer (see Style & Class) style the palette's own header and footer; a template is styled by
what it renders.
Here the header counts the files and follows the pages, and the footer shows the active file's path and size, or the toast of the file just opened. Open The archive… to see the header follow the page while it loads.
Detail pane
Description (which is searched too, with a low weight), its Data - any object, such as the
record of the file below - and its Shortcut, through BitCommandPaletteShortcutHint.
The pane is
--bit-CommandPalette-detail-width wide (40% by default) and is styled through
Classes.Detail / Styles.Detail. A modal palette with a detail pane opens wider, 920px instead of
640px, for the pane to have room (--bit-CommandPalette-width still decides when it is set); an inline palette
keeps the width of its container. Below 600px the pane is hidden, as the modal palette then fills the screen.
The pane is beside the list, not in it: a screen reader follows the active option, not the pane. Put what a reader needs to choose a command in its title or subtitle, and keep the pane for what adds to them.
Loading, no results & empty
- LoadingTemplate is shown while a lazily loaded page (
Childrengiven a loader) or an async source has nothing to show yet. It replaces the whole default state, a spinner andStrings.Loading, so give what it says arole="status"as the sample does. The search box's icon turns into a spinner as well, and the list is markedaria-busy. - NoResultsTemplate is shown when a search matched nothing and receives the query. NoResultsText
replaces only the sentence, keeping the icon and
Strings.NoResultsHintunder it. Without either, the palette showsStrings.NoResultswith the query in its{0}. - EmptyTemplate is shown by a page with nothing on it at all, before anything is typed: a folder with no files,
a lazy page whose loader returned nothing, a root page whose commands are not registered yet. EmptyText
replaces only the sentence. Without either, the palette shows
Strings.Empty.
role="status" element of the palette's (styled by Classes.NoResults and Classes.Empty),
so their templates need no live role of their own. A template's text is read by screen readers when it appears; the result
count is announced too, so keep it short.
In the first palette, type
zz for the no-results state, open The archive… for the loading state and
An empty folder for the empty one. The second palette has no commands at all: it shows its EmptyTemplate,
and its NoResultsText once something is typed.
No commands yet. They appear here once they are registered.
Localization
Breadcrumb), a switch's
On / Off, the "then" of G S (ShortcutThen) and the
announcement of a page (PageAnnouncement) - is a property of BitCommandPaletteStrings. To translate them:
- For one palette, set its Strings parameter, as the palette below does.
- For every palette, set
options.Stringsin thecommandPaletteargument ofAddBitBlazorUIExtrasServices. TheBitCommandPaletteShortcutHints andBitCommandPaletteTriggers outside a palette read these too; aBitCommandPaletteShortcutHintalso takes aStringsparameter of its own. - For an app serving several languages, subclass it: every property is
virtual, so a subclass can read them from anIStringLocalizer- the usual resource files - for the culture of each request.
{0} (and {1} in PageAnnouncement and
ApproximateResultsAnnouncement) is filled in with string.Format in the current culture
(CultureInfo.CurrentCulture) - the query in NoResults, the count in ResultsAnnouncement,
SelectedCount and MoreResults, the command's title in CommandFailed,
CommandRefused and CommandUnavailable, the source's name in SourceFailed. Keep the
placeholders when translating. The count announced after every search goes through
ResultsAnnouncementFor(count), which picks NoResultsAnnouncement, OneResultAnnouncement
or ResultsAnnouncement; a language whose plural forms one sentence per count cannot express - Polish, Russian,
Arabic - overrides it, as the C# tab shows.
NoResults and Empty default to the library-wide BitStrings.Current.NoResultsFound and
NoItemsFound, read each time they are shown: an app that already translates BlazorUI's own words through a
BitStrings subclass (set as BitStrings.Current, or through
AddBitBlazorUIServices(options => options.Strings = ...)) gets those two translated as well, unless the palette's
strings set them. The NoResultsText and EmptyText parameters win over both.
When command titles are translated, give each command an explicit
Id - an id derived from the title would change
with the language, and the recents, the pins and the active row with it - and add the untranslated title as a keyword
(.Keywords("Open settings") on Einstellungen öffnen), so people who learned the English name still find
it, as VS Code does with its English aliases. Search ignores case and accents, and folds the Arabic and Persian forms of a
letter and Persian and Arabic-Indic digits together (see the search sections above), so a query typed on another keyboard
layout still matches.
Switch the language below. The placeholder, the footer's hints, the empty state (type
xyz), the confirmation
(choose the destructive row), the disabled reason and the back hint (open Export…), the switch's spoken state and the
word between the key caps of G S all change, and typing settings or dark
finds the translated commands in every language. The ids stay the same, so the active row survives a switch.
CSS variables
:root in the app's
stylesheet re-skins every palette, one set on an element re-skins the palettes inside it, and one set through a palette's
Style re-skins that palette alone - with no selector of the library's to fight.
--bit-CommandPalette-width: the modal dialog's width (640px; 920px with a detail pane). Never wider than the viewport.--bit-CommandPalette-max-height: how tall the list grows with its header and footer (min(70vh, 560px)).--bit-CommandPalette-top: how far down the modal dialog opens (12vh).--bit-CommandPalette-radius: the corners of the dialog or of an inline palette (the theme's dialog radius).--bit-CommandPalette-backgroundand--bit-CommandPalette-color: the fill and the text (the theme's primary background and foreground).--bit-CommandPalette-border-color: the lines between the header, the list and the footer, the edge of an inline palette and of the detail pane.--bit-CommandPalette-shadowand--bit-CommandPalette-backdrop: the modal dialog's elevation and the fill of the page behind it.--bit-CommandPalette-row-height: a row's least height (44px at the default density). WhileVirtualizeis on, the rows are pinned toBitCommandPaletteOptions.RowHeightinstead.--bit-CommandPalette-item-radius: a row's corners.--bit-CommandPalette-active-background: the active row, the palette's only "focus" in the list.--bit-CommandPalette-accent: the mode chip, badges, checked rows, switches that are on, the selected count and the busy spinner (the theme's primary color).--bit-CommandPalette-mark-background: the matched characters.--bit-CommandPalette-detail-width: the detail pane (40%).--bit-CommandPalette-focus-color: the focus ring of the palette's buttons - back, breadcrumbs, close, retry (the global focus ring).
--bit-CommandPaletteTrigger-height, -background,
-color, -border-color, -radius and -focus-color.
Everything else follows the theme, so it is changed there, for the whole app: the footer and the detail pane are on
--bit-clr-bg-sec, subtitles and hints are --bit-clr-fg-sec, destructive rows and errors
--bit-clr-err (on --bit-clr-err-tint when active), badges and the mode chip sit on
--bit-clr-pri-tint, key caps are drawn in --bit-clr-bg-sec and --bit-clr-brd-pri,
the type is --bit-tpg-font-family, the stacking order --bit-zin-modal and the pop-in
--bit-mot-duration. Paddings, gaps and the heights of the search box and the footer follow the theme's spacing
unit and density (see Density). A part no variable reaches is restyled through Classes / Styles
(see Style & Class).
Every color a re-skin sets has to hold up in both light and dark: a color derived from the theme's own tokens, as the sample does with
color-mix(in srgb, #ea580c 5%, var(--bit-clr-bg-pri)), follows the theme by itself. Keep text at 4.5:1
against its background and the active row distinct from the rest (3:1). The modal-only variables (width, top, shadow,
backdrop) change nothing on an inline palette, which is as wide as its container and has an edge instead of a shadow: they
apply to the page's modal palette the same way, set on :root or on its Style.
Ready-made skins
Style it re-skins one palette; put in a class
of the app's stylesheet and given through Class, or set on :root, it re-skins every palette that
should look alike - the page's modal one included. The eight below are ready to copy. Every one derives its colors from the
theme's tokens with color-mix() or leaves them to the theme, so each works in light and in dark: switch the
site's theme to see them follow.
- Default: no variables, the theme's own look.
- Indigo: a deep blue-violet accent with softer, rounder corners.
- Teal and Rose: an accent, with the surface, the edges and the active row tinted by it.
- Flat: square corners, no shadow and a stronger edge, for a palette laid into a dense page.
- Pill: round rows and corners, taller rows.
- Dense list: short rows in a short list, for a palette in a side panel.
- Terminal: a monospaced font and a green accent - a skin may set more than variables, here
font-familyon the palette, which its parts inherit.
--bit-CommandPalette-accent: #4f46e5;--bit-CommandPalette-mark-background: rgba(79, 70, 229, .2);--bit-CommandPalette-active-background: rgba(79, 70, 229, .1);--bit-CommandPalette-radius: 14px;--bit-CommandPalette-item-radius: 8px;Light & dark
bit-theme the app's <html> carries,
which BitThemeManager sets - from the user's choice, or from the system's preference when the app follows it.
Nothing has to be set on the palette for that.
To give one palette a theme of its own - a dark palette over a light page, or a light one in a dark side panel - set the theme on it or on an element around it:
- A
bit-theme="dark"(or"light") attribute on the palette itself: an attribute the palette does not know lands on its root element, the modal<dialog>or the inline<section>. BlazorUI's theme declares every palette of tokens (colors, shadows,color-scheme) on:root [bit-theme="dark"]as well as on:root[bit-theme="dark"], so any element with the attribute re-themes itself and everything in it. - The same attribute on any ancestor:
<aside bit-theme="dark">re-themes the palette and every other component in it. - A BitThemeProvider around the palette, with a
BitThemeof its own - for instanceBitThemeFactory.CreateDarkThemeFromSeed(BitAccentColorPresets.Teal), a whole dark palette derived from a brand color - for a theme that is not one of the packaged ones.
<BitCommandPalette bit-theme="dark" />.
To change a palette variable in dark mode only, set it under both selectors the theme uses:
:root[bit-theme="dark"], :root [bit-theme="dark"] { --bit-CommandPalette-accent: #2dd4bf; }.
Density
--bit-layout-density-scale, a unitless number (1 by default). Set it on the palette's Style, or on
any element around it, and the palette tightens or loosens: the rows' padding and least height, the list's padding, the
group headings, the search box's row, the breadcrumbs, the footer, the empty and loading states, the detail pane's padding,
the key caps and the badges. Font sizes, icons and corner radii stay as they are, so text keeps its size. Below 1 is
compact (0.8 suits a dense app or an inline palette in a side panel), above 1 is airy (1.2 for touch).
The scale is read where each part is drawn, so it reaches every BlazorUI component under the element it is set on: a
BitThemeProvider with BitThemeDensityPresets.CreateCompactOverlay() (0.9) or
CreateSpaciousOverlay() (1.1), or a BitTheme whose Layout.DensityScale is set, makes a
whole region denser, palette included. BitCommandPaletteTrigger scales the same way, as the triggers below do.
A compact palette is
Style="--bit-layout-density-scale: 0.8". A density of your own is a class: one that sets the scale and, where
the scale is not enough, the palette's variables, such as
.cozy { --bit-layout-density-scale: 0.9; --bit-CommandPalette-row-height: 38px; } given through
Class. A --bit-CommandPalette-row-height that is set wins over the scaled row height; with
Virtualize on, the rows are pinned to BitCommandPaletteOptions.RowHeight, which should then match
the density.
Forced colors, contrast & motion
- Forced colors (Windows High Contrast and other forced palettes): backgrounds and shadows disappear in that
mode, so the dialog gets a border, the header, the footer, the breadcrumbs, the badges and the key caps are outlined,
the active row is outlined in the system's
Highlightcolor, a disabled row is drawn inGrayTextinstead of being faded, checked boxes and switches that are on are filled withHighlight, and matched characters are drawn asMark/MarkText. - More contrast (
prefers-contrast: more): the active row is outlined as well as filled, matched characters are underlined as well as tinted, and BlazorUI's theme draws borders twice as thick, focus rings wider and the faintest text and lines one step stronger. - Reduced motion (
prefers-reduced-motion: reduce): the dialog's pop-in, the backdrop's fade and the switches' slide are dropped, as every duration of the theme collapses; the spinners keep turning - they are the only sign that work is in progress - but slowly and evenly. - Small screens (below 600px): the modal palette fills the screen, the footer keeps only its last hint, and the detail pane and the rows' shortcuts are hidden. An inline palette keeps its place in the page.
- Right to left: see RTL below.
forced-colors, prefers-contrast,
prefers-reduced-motion) and move through the list: the switch, the badge, the destructive row (press Enter on it
once), the disabled row and the matched characters all change.
Restyling from scratch
BitCommandPalette's styles are part of the Extras bundle like every other component's, and the
palette is restyled on top of them, from the lightest touch to a look of its own:
- The CSS variables, for its colors and sizes (see CSS variables and Ready-made skins).
ClassandStyleon the root, andClasses/Styleson its parts: the header, the search box, the list, the group headings, the rows, the active row, the states, the footer and the detail pane (see Style & Class).- The templates, to replace what a row, a heading, the icon, the header, the footer and the states show.
- The stable
data-bit-cplattributes, as selectors under a class of your own, for the parts that have noClassesentry.
data-bit-cpl attributes name every part: dialog (inline for an inline palette),
root, main, header, breadcrumbs, crumb, mode,
input-row, input, spinner, selected-count, close,
notice, list, group, group-heading, item, path,
label, mark, badge, shortcut, empty (no results and empty
alike), loading, error, retry, prompt, prompt-error,
footer, toast, status, alert, detail, sequence
(the pending-sequence hint) and trigger on BitCommandPaletteTrigger. A row carries its state as attributes:
data-active, data-checked, data-disabled, data-destructive,
data-confirming, data-running and data-error (all "true" when set),
data-kind (the command's kind) and data-value (its id). The root carries data-open,
data-busy, data-multiselect, data-has-detail and data-ready - set once
its browser layer listens for keys, which is what an end-to-end test waits for before pressing Ctrl+K on a prerendered
page. They are also the stable hooks for tests; the bit-cpl-* classes may change between versions.
The palette below is styled by a handful of rules under its own class: no rounded rows, an inverted active row, underlined matches, struck-through unavailable rows and no footer.
Accessibility
- The focus stays in the search box. Rows are never focused: the box points at the active row through
aria-activedescendant, and a click on a row leaves the focus in the box. The active row's fill (--bit-CommandPalette-active-background) is therefore the only sign of where the keyboard is: keep it clearly distinct from the background. A template must not put a button, a link or any other focusable element in a row - it could never be reached with the keyboard. - The row's state is the palette's. The row element keeps
aria-selected(oraria-checkedon a multi-select page) andaria-disabled, and the reason a row is disabled is said in its subtitle. A switch's state and a pin are spoken by the default row in words (Strings.On,Strings.Off,Strings.Pinned), not only drawn; anItemTemplatereplaces them, so it says them itself, in visually hidden text, as the sample below does. - Groups are named by their headings, which are presentational: a
GroupHeaderTemplate's text is what a screen reader says when it enters the group. - Live regions say the rest: polite regions, present before anything is announced in them, read the result count
after every search, the page the palette moved to ("Theme. 3 results available"), the loading state and every toast,
whatever the footer shows; errors are announced assertively. An inline palette announces only while it has the focus.
A template therefore adds no
aria-liveorrole="status"for these - except aLoadingTemplate, which replaces a state that had one. - Key caps are hidden from screen readers and the shortcut is spoken in words: draw shortcuts with
BitCommandPaletteShortcutHintrather than bare<kbd>s, or hide yours. - The pointer moves the active row only once it actually moves, so a list scrolling under a resting mouse does not steal the keyboard's place. DisablePointerSelection stops hovering from moving it at all - only the keys and a click do - as in the palette below.
- Matched characters keep the text's own color on their tint: a muted color on the tint would fall below 4.5:1.
Keep that when restyling
[data-bit-cpl="mark"]. - The buttons (back, breadcrumbs, close, retry) are at least 24px, and their names hold what they show: the close button is "Close, Esc", and the trigger's name starts with its visible label (WCAG 2.5.3, label in name).
Accessibility of the dialog and the list
- The modal palette is a native modal dialog element: it sits in the top layer, traps the focus, makes the page behind it inert, holds the page's scroll still, and gives the focus back to whatever had it when it closes.
- The focus stays in the search input, which is a combobox controlling a listbox, and aria-activedescendant points at the active option, so screen readers follow the selection without the focus moving.
- A single-select list marks its active option aria-selected; a multi-select page adds aria-multiselectable and marks its checked options aria-checked and nothing else, so each list has one state.
- Each group is a role="group" named by its heading, so screen readers say which group an option is in, and the listbox owns only options and groups.
- The list is a listbox only while it lists something; the empty, loading and error states are statuses and alerts instead, and the combobox's aria-expanded follows.
- On a prompt the input is a plain text field named by the prompt's question.
- In a virtualized list, where rows cannot be wrapped in their groups, each option is described by its heading and carries aria-posinset and aria-setsize.
- Polite live regions, present before anything is announced in them, say the result count after every search, the page the palette moved to, loading, and every toast; errors are announced assertively, and the list is aria-busy while it loads.
- A toggle's state and a pinned command are spoken ("On", "Off", "Pinned"), not only drawn.
- A shortcut hint has an accessible name in words ("Ctrl+K", "G then S") while its key caps are hidden from screen readers, and the trigger declares aria-keyshortcuts.
- Disabled commands are aria-disabled and say why, and group headings are not read as options.
- Clicking a row leaves the focus in the input.
- Pointer hover moves the selection only once the pointer actually moves, so a list scrolling under a resting mouse does not steal the keyboard's selection; DisablePointerSelection turns hover off completely.
- The close button's accessible name holds its visible "Esc", and the trigger's name starts with its visible label (WCAG 2.5.3, label in name), as the Trigger section shows; the buttons are at least 24 pixels.
- Animations follow BlazorUI's motion tokens, which collapse under prefers-reduced-motion.
Diagnostics
- The bit.command_palette.command.executions counter (unit {execution}) counts the commands the palette ran, refused, or saw fail or be cancelled, tagged with bit.command_palette.command.kind, bit.command_palette.trigger (palette, shortcut or programmatic) and bit.command_palette.outcome (succeeded, failed, cancelled or refused).
- The bit.command_palette.command.duration histogram (in seconds) records how long handlers took, with the same tags; a refusal ran nothing and has no duration.
- The bit.command_palette.source.duration histogram (in seconds) records how long async sources took, tagged with bit.command_palette.source.name and bit.command_palette.outcome (succeeded, failed or timed_out); a search the palette abandoned is not recorded.
- The bit.command_palette.search.duration histogram (in seconds) records how long matching and ranking the in-memory commands took for a query, with no tags.
- Every handler runs inside a bit.command_palette.command activity, so the HttpClient calls it makes are its children, tagged with the kind, the trigger, the outcome and the command's id.
- A failure sets the activity's status to an error and records the exception's type, never its message, which can quote what the user typed.
- Every source search runs inside a bit.command_palette.source activity.
- The palette's own rows (pin, forget, retry, "Show more") are neither counted nor traced.
- Metrics never carry ids, and queries, prompt values, titles and selections are never recorded.
- Set options.RecordCommandIdsInTraces to false when command ids embed personal data (person:[email protected]); it also keeps a command's id and title out of the log entries about running it, which read "(hidden)" instead.
- On WebAssembly, metrics need the System.Diagnostics.Metrics feature switch (MetricsSupport), which the SDK turns off by default and Bit.Belemetry turns back on.
Troubleshooting
- When Ctrl+K does nothing, the palette is not interactive because it is in a statically rendered layout; also check that bit.blazorui.extras.js is linked and that no other script calls preventDefault on the key first.
- When options from Program.cs (a toggle shortcut, the group order, commands added through options.Commands) stop working once the page turns interactive, the services are registered in only one project of a Blazor Web App and the palette in the other runs on the default options; it logs a warning saying the services are not registered. Call AddBitBlazorUIExtrasServices in both projects, through one shared method.
- When the palette opens unstyled, the bit.blazorui.extras.css link is missing from the host page.
- When a toggle shows its old state, remember that commands are immutable: register a new command with the same id, call Update on the service, or give BitCommandPaletteCommands a new list.
- When recents forget a command whose title changed, its id was derived from the title; set an explicit Id.
- When a page's commands are still listed after leaving it, dispose the handle Register returned, or register them with BitCommandPaletteCommands.
- When a global shortcut does not fire in a text box, that is deliberate for plain keys; use a chord with a modifier, or set SuppressShortcutsInEditableElements to false.
- When two palettes open at once, there is more than one modal palette in a scope; keep one, since every instance answers the same service, and use Inline for a palette that is part of a page.
- When a command does nothing, or the wrong one runs, look at the app's log: the palette warns about duplicate ids, about shortcuts several commands claim or the toggle takes, and about links it refused, and it logs every failed command and page.
- When a command does nothing and the footer says "You can’t run …", a guard refused it; the log has an information entry naming the command and what started it, and IBitCommandPaletteService.CommandRefused reports it to code.
- When a command's shortcut works only after opening the palette, its VisibleWhen changed while the palette was closed; call Refresh() on the service after the state it reads changes.
- When commands passed to the Commands parameter do not update, remember that the palette re-reads the parameter only when it gets a new collection; assign a new list, or call Refresh() after changing the same one.
Style & Class
<dialog>, or the
<section> of an inline palette - next to its own class, so a CSS variable set there reaches the whole
palette. Classes and Styles, both a BitCommandPaletteClassStyles, reach its parts:
Root: the root element, likeClass/Style.Header: the header, with the breadcrumbs and the search box (not aHeaderTemplate, which is rendered above it).Input: the search box.List: the list.GroupHeading: every group heading.Item: every row;ActiveItem: the active row, added toItem(its style is written afterItem's, so it wins).Empty: what a page with nothing on it shows;NoResults: what a search that matched nothing shows (around their templates too).Footer: the footer (not aFooterTemplate, which replaces it).Detail: the detail pane, when aDetailTemplateis set.
Styles is written on the element, so it wins over the stylesheet. A class in Classes is
matched against the palette's own rules, so a rule that changes what the palette already sets for a state - the active row's
fill, say - needs a selector at least as specific (.my-item[data-active="true"]), or the variable that is meant
for it (--bit-CommandPalette-active-background). Open Nothing inside for the Empty part and
type zz for NoResults.
BitCommandPaletteTrigger has its own
Class / Style and Classes /
Styles, a BitCommandPaletteTriggerClassStyles: Root (the button), Icon (the
search icon), Label and Shortcut (the key caps). A trigger opens the page's modal palette.
RTL
Dir="BitDir.Rtl" lays the palette out from the right; so does a
dir="rtl" on any element around it (prefer Dir on the palette: the few browsers without the
:dir() selector mirror its arrows only then). Every rule uses logical properties, so:
- The search icon, the rows' icons and the back button start on the right; the footer's last hint, the detail pane and its border, and a switch's knob (on at the left) all follow.
- Arrows and chevrons are mirrored - the back arrow, a page's chevron, the arrow of a navigation command - and the
separator between a nested command's ancestors turns into ‹ ("خروجی گرفتن… ‹ به صورت PDF": type
PDF). - User text - titles, subtitles, badges, values, breadcrumbs, headings - isolates its own direction
(
dir="auto"), so an English title in a Persian palette, such as Open in VS Code… below, keeps its punctuation where it belongs. Shortcut key caps always read left to right, as on the keys: G S, withShortcutThenbetween them. - ArrowLeft and ArrowRight trade places. On an empty search box the palette reads the arrow pointing to the start of the line as "back" and the one pointing to its end as "into the action panel". In right-to-left text the start is on the right, so → goes back a page and ← opens the action panel of the active row. Open خروجی گرفتن… and press → to come back; on باز کردن تنظیمات, press ← for its action. Backspace on an empty box and Escape go back in either direction.
Strings (see Localization): the sample translates every one of them into Persian,
and overrides ResultsAnnouncementFor to announce the count in Persian digits (۱۲), which a screen reader reading
Persian expects. Search folds the Arabic and Persian forms of a letter and the Persian, Arabic-Indic and Latin digits
together, so 2 and ۲ both find the export's subtitle, and a shortcut such as G
S works when a Persian keyboard layout types ل س (see the keyboard sections above). In Persian and Arabic,
TriggerNameSeparator is "، ".
CSS variables
The public custom properties this component reads off its root, for what no parameter covers.
Every variable is read with a fallback and never declared by the component, so it inherits like any other custom property:
set one on :root (or in a [bit-theme] block) to restyle every instance, on any ancestor to restyle the ones inside it,
or on the Style of one instance to restyle it - and any instance nested inside it, which inherits the value too; a parameter changes one alone,
as does the real CSS property on the instance's Style / Styles when that property does not inherit (opacity: 1 keeps
one disabled instance undimmed without undimming a disabled one inside it), while an inherited one such as color or
font-family also reaches the nested instances that do not set it themselves. Leave a variable unset and the component
falls back to the theme token beside it.
BitCommandPalette CSS variables
| Name | Default value | Description |
|---|---|---|
| --bit-CommandPalette-width | 640px | Width of the dialog (920px with a detail pane). |
| --bit-CommandPalette-max-height | min(70vh, 560px) | Tallest the list grows, with its header and footer. |
| --bit-CommandPalette-top | 12vh | Distance of the dialog from the top of the viewport. |
| --bit-CommandPalette-radius | var(--bit-shp-radius-dialog) | Corner radius of the dialog. |
| --bit-CommandPalette-background | var(--bit-clr-bg-pri) | Fill of the dialog and of an inline palette. |
| --bit-CommandPalette-color | var(--bit-clr-fg-pri) | Text of the palette. |
| --bit-CommandPalette-border-color | var(--bit-clr-brd-sec) | Lines between the header, the list and the footer, and the edge of an inline palette. |
| --bit-CommandPalette-shadow | var(--bit-shd-dialog) | Elevation of the dialog. |
| --bit-CommandPalette-backdrop | var(--bit-clr-bg-overlay) | Fill of the page behind the dialog. |
| --bit-CommandPalette-row-height | var(--bit-siz-item-lg) | Least height of a row. Virtualize pins the rows to BitCommandPaletteOptions.RowHeight instead. |
| --bit-CommandPalette-item-radius | var(--bit-shp-radius-md) | Corner radius of a row. |
| --bit-CommandPalette-active-background | var(--bit-clr-bg-pri-hover) | Fill of the active row. |
| --bit-CommandPalette-accent | var(--bit-clr-pri) | The mode chip, badges, checked rows, switches that are on and the busy spinner. |
| --bit-CommandPalette-mark-background | var(--bit-clr-pri-tint) | Fill of the matched characters. |
| --bit-CommandPalette-detail-width | 40% | Width of the detail pane. |
| --bit-CommandPalette-focus-color | the global focus ring | Focus ring of the palette's buttons. |
| --bit-CommandPaletteTrigger-height | var(--bit-siz-ctrl-md) | Height of a BitCommandPaletteTrigger. |
| --bit-CommandPaletteTrigger-background | var(--bit-clr-bg-sec) | Fill of a BitCommandPaletteTrigger. |
| --bit-CommandPaletteTrigger-color | var(--bit-clr-fg-sec) | Text and icon of a BitCommandPaletteTrigger. |
| --bit-CommandPaletteTrigger-border-color | var(--bit-clr-brd-pri) | Edge of a BitCommandPaletteTrigger. |
| --bit-CommandPaletteTrigger-radius | var(--bit-shp-radius-control) | Corner radius of a BitCommandPaletteTrigger. |
| --bit-CommandPaletteTrigger-focus-color | the global focus ring | Focus ring of a BitCommandPaletteTrigger. |
API
Every parameter, public member, sub-class and enum this component exposes.
BitCommandPalette parameters
| Name | Type | Default value | Description |
|---|---|---|---|
| ChildContent | RenderFragment? | null | The declarative BitCommandPaletteGroup and BitCommandPaletteOption children of the palette. |
| Classes | BitCommandPaletteClassStyles? | null | Custom CSS classes for the different parts of the command palette. |
| Commands | IEnumerable<BitCommandPaletteCommand>? | null | Commands supplied directly to this palette, in addition to the ones registered through IBitCommandPaletteService and declared in its markup. |
| DetailTemplate | RenderFragment<BitCommandPaletteCommand>? | null | Renders a detail pane beside the list for the active command, Raycast style. |
| DisablePointerSelection | bool | false | Ignores the pointer hovering a row for choosing the active one: only the keys and a click move it. |
| EmptyTemplate | RenderFragment? | null | What a page with no commands on it at all shows, in place of EmptyText. |
| EmptyText | string? | null | The text a page with no commands on it at all shows. Default: the Empty of the palette's strings, which falls back to BitStrings.NoItemsFound. |
| EnableHistory | bool? | null | Overrides BitCommandPaletteOptions.EnableHistory: recents, pins and frecency. |
| FooterTemplate | RenderFragment<BitCommandPaletteStateContext>? | null | Replaces the footer with its keyboard hints and toasts, with a snapshot of the palette's state. |
| GroupHeaderTemplate | RenderFragment<string>? | null | Replaces the content of a group heading; receives the heading text. |
| GroupWhenSearching | bool? | null | Overrides BitCommandPaletteOptions.GroupWhenSearching: keeps the group headings while a query is typed. |
| HeaderTemplate | RenderFragment<BitCommandPaletteStateContext>? | null | Content rendered above the search box, with a snapshot of the palette's state. |
| HighlightMatches | bool? | null | Overrides BitCommandPaletteOptions.HighlightMatches: marks the matched characters. |
| IconTemplate | RenderFragment<BitCommandPaletteCommand>? | null | Renders the icon of every row; receives the command. Render nothing for no icon. |
| IncludeRegisteredCommands | bool | true | Whether the commands, sources and modes registered through IBitCommandPaletteService are part of this palette. Set it to false for a palette that lists only its own, such as an inline search of one page's settings. |
| Inline | bool | false | Renders the palette in the page instead of in a modal dialog. It is always open, Escape goes back a page or clears the query, and it leaves the toggle shortcut, the global shortcuts and the service's Open/Close/Execute to the modal palette. Set before the first render. |
| ItemTemplate | RenderFragment<BitCommandPaletteItemContext>? | null | Replaces the content of every row. The row element itself - its role, ARIA state and click handling - stays the palette's. |
| LoadingTemplate | RenderFragment? | null | Replaces the loading state shown while a lazily loaded page or an async source has nothing to show yet. |
| Loop | bool? | null | Overrides BitCommandPaletteOptions.Loop: the arrow keys wrap around the list. |
| NoResultsTemplate | RenderFragment<string>? | null | What a search that matched nothing shows, in place of NoResultsText; receives the query. |
| NoResultsText | string? | null | The text a search that matched nothing shows. Default: the NoResults of the palette's strings, which falls back to BitStrings.NoResultsFound. |
| OnClosed | EventCallback | Raised after the palette closed. | |
| OnCommandExecuted | EventCallback<BitCommandPaletteCommandExecutedEventArgs> | Raised after a command of this palette ran, with its result and how long the handler took. | |
| OnOpened | EventCallback | Raised after the palette opened. | |
| OnQueryChanged | EventCallback<string> | Raised after every change of the query, with the raw text (a mode prefix included). | |
| Open | bool | false | Whether the modal palette is open. Two-way bindable. |
| Placeholder | string? | null | The placeholder of the search box on the root page. |
| SearchNestedCommands | bool? | null | Overrides BitCommandPaletteOptions.SearchNestedCommands: finds nested commands from the root page. |
| ShowFooter | bool? | null | Overrides BitCommandPaletteOptions.ShowFooter. |
| ShowShortcuts | bool? | null | Overrides BitCommandPaletteOptions.ShowShortcuts: shows each command's shortcut on its row. |
| Strings | BitCommandPaletteStrings? | null | The words of the palette, the ones only screen readers hear included. Default: BitCommandPaletteOptions.Strings. |
| Styles | BitCommandPaletteClassStyles? | null | Custom CSS styles for the different parts of the command palette. |
| ToggleShortcut | string? | null | Overrides BitCommandPaletteOptions.ToggleShortcut (Mod+K), e.g. Ctrl+Shift+P. |
| TypoTolerance | bool? | null | Overrides BitCommandPaletteOptions.TypoTolerance: retries a query that found nothing allowing a typo per term. |
| VimBindings | bool? | null | Overrides BitCommandPaletteOptions.VimBindings: Ctrl+J / Ctrl+K move the selection. |
| Virtualize | bool? | null | Overrides BitCommandPaletteOptions.Virtualize: renders the list through Virtualize. |
BitCommandPalette public members
| Name | Type | Default value | Description |
|---|---|---|---|
| IsOpen | bool | Whether the dialog is open. | |
| Query | string | The current raw query, a mode prefix included. | |
| ActiveCommand | BitCommandPaletteCommand? | The command of the active row, if any. | |
| OpenAsync | (string? query, string? pageCommandId) => Task | Opens the palette, optionally with a query (a mode prefix is honoured) or directly on a command's page. | |
| CloseAsync | () => Task | Closes the palette. | |
| ToggleAsync | () => Task | Opens the palette when it is closed and closes it when it is open. | |
| SetQueryAsync | (string query) => Task | Sets the query as if typed, and renders the results. |
BitComponentBase parameters
| Name | Type | Default value | Description |
|---|---|---|---|
| AriaLabel | string? | null | Gets or sets the accessible label for the component, used by assistive technologies. |
| Class | string? | null | Gets or sets the CSS class name(s) to apply to the rendered element. |
| Dir | BitDir? | null | Gets or sets the text directionality for the component's content. |
| Disabled | bool | false | Gets or sets a value indicating whether the component is disabled and cannot respond to user interaction. |
| ForceAnimation | bool | false | Gets or sets a value indicating whether the component's animations play at their full duration even when reduced motion is requested. |
| HtmlAttributes | Dictionary<string, object> | new Dictionary<string, object>() | Captures additional HTML attributes to be applied to the rendered element, in addition to the component's parameters. An attribute written on the component wins over an entry of the same name. |
| Id | string? | null | Gets or sets the unique identifier for the component's root element. |
| Style | string? | null | Gets or sets the CSS style string to apply to the rendered element. |
| TabIndex | string? | null | Gets or sets the tab order index for the component when navigating with the keyboard. |
| Visibility | BitVisibility | BitVisibility.Visible | Gets or sets the visibility state (visible, hidden, or collapsed) of the component. |
BitComponentBase public members
| Name | Type | Default value | Description |
|---|---|---|---|
| UniqueId | Guid | Guid.NewGuid() | Gets the readonly unique identifier for the component's root element, assigned when the component instance is constructed. |
| RootElement | ElementReference | Gets the reference to the root HTML element associated with this component. |
BitCommandPaletteClassStyles properties
| Name | Type | Default value | Description |
|---|---|---|---|
| Root | string? | null | Custom CSS classes/styles for the root element of the BitCommandPalette: the modal dialog, or the section of an inline palette. |
| Header | string? | null | Custom CSS classes/styles for the header of the BitCommandPalette, which holds the breadcrumbs and the search box. |
| Input | string? | null | Custom CSS classes/styles for the search box of the BitCommandPalette. |
| List | string? | null | Custom CSS classes/styles for the list of the BitCommandPalette. |
| GroupHeading | string? | null | Custom CSS classes/styles for each group heading of the BitCommandPalette. |
| Item | string? | null | Custom CSS classes/styles for each row of the BitCommandPalette. |
| ActiveItem | string? | null | Custom CSS classes/styles for the active row of the BitCommandPalette. |
| Empty | string? | null | Custom CSS classes/styles for what a page of the BitCommandPalette with no commands at all shows. |
| NoResults | string? | null | Custom CSS classes/styles for what a search of the BitCommandPalette that matched nothing shows. |
| Footer | string? | null | Custom CSS classes/styles for the footer of the BitCommandPalette, with its keyboard hints and toasts. |
| Detail | string? | null | Custom CSS classes/styles for the detail pane of the BitCommandPalette. |
BitCommandPaletteStrings properties
Every word the palette says, the ones only screen readers hear included. Set its properties, or subclass it and override them (to read them from an IStringLocalizer), to localize. The templates are composite format strings: {0} is replaced.
| Name | Type | Default value | Description |
|---|---|---|---|
| Placeholder | string | "Type a command or search…" | The search box placeholder on the root page. |
| PromptPlaceholder | string | "Type a value and press Enter…" | The search box placeholder of a prompt that set none of its own. |
| NoResults | string | BitStrings.Current.NoResultsFound | The state of a query that found nothing; {0} is the query. Default: NoResultsFound of Current, read when it is shown, so a BitStrings set later still reaches it. |
| NoResultsHint | string | "Try a different search, or check for typos." | The hint under NoResults. |
| Empty | string | BitStrings.Current.NoItemsFound | The state of a page with nothing on it. Default: NoItemsFound of Current, read when it is shown, so a BitStrings set later still reaches it. |
| Loading | string | "Searching…" | The loading state, shown and announced while a lazily loaded page or an async source has not answered. |
| Recent | string | "Recent" | The heading of the recently used commands. |
| Pinned | string | "Pinned" | The heading of the pinned commands, and what a pinned row says to screen readers. |
| Suggestions | string | "Suggestions" | The heading of the ungrouped commands when pinned or recent ones are listed above them. |
| Modes | string | "Modes" | The heading of the mode hints on the empty query. |
| Actions | string | "Actions" | The search box placeholder of the action panel. |
| Results | string | "Results" | The accessible name of the result list on the root page. |
| Other | string | "Other" | Not used by the palette itself; kept for templates. |
| Navigate | string | "to navigate" | Footer hint after the ↑ ↓ keys. |
| Select | string | "to select" | Footer hint after the Enter key. |
| Close | string | "to close" | Footer hint after the Esc key on the root page. |
| ClearQuery | string | "to clear" | Footer hint after the Esc key in an inline palette with a query typed. |
| Back | string | "to go back" | Footer hint after the Esc key on a nested page and in a prompt. |
| OpenActions | string | "for actions" | Footer hint after the Tab key. |
| Toggle | string | "to toggle" | Footer hint after the Enter key on a multi-select page. |
| Apply | string | "to apply" | Footer hint after Ctrl+Enter on a multi-select page, and after Enter in a prompt. |
| Pin | string | "Pin to top" | The action panel entry that pins a command. |
| Unpin | string | "Unpin" | The action panel entry that unpins a command. |
| RemoveFromRecents | string | "Remove from recents" | The action panel entry that forgets a command's uses. |
| ClearRecents | string | "Clear recent commands" | The action panel entry that forgets every recent command (pins stay). |
| ConfirmPrefix | string | "Confirm: " | Put before the title of a command waiting for its confirming Enter. |
| ConfirmHint | string | "Press Enter again to confirm, Esc to cancel" | Announced with the confirmation message of a command waiting for its second Enter. |
| SelectedCount | string | "{0} selected" | How many rows are checked on a multi-select page; {0} is the count. |
| ResultsAnnouncement | string | "{0} results available" | Announced after a search with several results; {0} is the count. See ResultsAnnouncementFor. |
| OneResultAnnouncement | string | "1 result available" | Announced after a search with exactly one result. |
| NoResultsAnnouncement | string | "No results" | Announced after a search with no result. |
| PageAnnouncement | string | "{0}. {1}" | Announced when a page opens or the palette goes back to one; {0} is its title, {1} what it lists. |
| Disabled | string | "Unavailable" | Shown when a disabled command without a reason is chosen. |
| ModeHintTitle | string | "{0} — {1}" | Not used by the palette itself; kept for templates. |
| DialogLabel | string | "Command palette" | The accessible name of the dialog. |
| InputLabel | string | "Search commands" | The accessible name of the search box. |
| CloseButton | string | "Close" | The accessible name of the close button. |
| BackButton | string | "Back" | The accessible name of the back button. |
| Breadcrumb | string | "Breadcrumb" | The accessible name of the breadcrumb navigation. |
| OpenPalette | string | "Open command palette" | What BitCommandPaletteTrigger's accessible name says it does, after its visible label and TriggerNameSeparator (WCAG 2.5.3: the name starts with what is shown), and its whole name when the trigger shows no label. A string that already holds the label - a whole name such as "Search commands" for the label "Search" - is the name on its own, as is a label that already holds this string. |
| TriggerNameSeparator | string | ", " | What joins BitCommandPaletteTrigger's visible label and OpenPalette in its accessible name; a language with a comma of its own uses it ("، " in Persian and Arabic). |
| Search | string | "Search" | The label of BitCommandPaletteTrigger when it sets none of its own. |
| Home | string | "Home" | The title of the root page. |
| MoreResults | string | "Show {0} more…" | The row that loads a source's next page when it said how many results there are; {0} is how many are left. |
| LoadMore | string | "Show more…" | The row that loads a source's next page when it did not say how many results there are. |
| SequencePending | string | "waiting for the next key…" | Shown, and announced, after the first chords of a shortcut sequence (G of G S), until it completes or times out. |
| CommandFailed | string | "Couldn’t run “{0}”." | Shown when a command failed; {0} is its title. See Message. |
| CommandRefused | string | "You can’t run “{0}”." | Shown when a guard refused a command without a message of its own (see IBitCommandPaletteCommandGuard); {0} is its title. |
| CommandUnavailable | string | "“{0}” is no longer available." | Shown when a listed command was chosen after it stopped being available - its VisibleWhen, or an ancestor's, turned false since the list was built; {0} is its title. |
| LoadFailed | string | "Couldn’t load this list." | Shown when the children of a page failed to load. |
| Retry | string | "Try again" | The button and hint that load a failed list again. |
| ApproximateResults | string | "No exact matches. Showing close ones." | Shown above results found only by allowing typos (see TypoTolerance). |
| ApproximateResultsAnnouncement | string | "{0} {1}" | The announcement of such results: {0} is ApproximateResults, {1} the result count. |
| Running | string | "Working…" | Announced, and shown by a spinner, while a command's handler has been running for a moment. |
| SourceFailed | string | "Couldn’t search {0}" | The row an async source that failed or timed out leaves; {0} is its name. Choosing it retries. |
| On | string | "On" | What screen readers hear for a toggle that is on. |
| Off | string | "Off" | What screen readers hear for a toggle that is off. |
| ShortcutThen | string | "then" | The word between the chords of a sequence: "G then S". |
BitCommandPaletteOptions properties
The app-wide configuration, set through AddBitBlazorUIExtrasServices(commandPalette: options => ...). The palette's own parameters, and a BitCommandPaletteParams cascaded through a BitParams, override what they share with it.
| Name | Type | Default value | Description |
|---|---|---|---|
| ToggleShortcut | BitCommandPaletteKeyboardShortcut? | BitCommandPaletteKeyboardShortcut.Parse("Mod+K") | Shortcut that toggles the palette. Default Mod+K (⌘K on macOS, Ctrl+K elsewhere). |
| AdditionalToggleShortcuts | List<BitCommandPaletteKeyboardShortcut> | [] | Additional toggle shortcuts (e.g. Ctrl+Shift+P, /). |
| SuppressShortcutsInEditableElements | bool | true | Don't fire global command shortcuts while an input, textarea or contenteditable has focus. |
| Loop | bool | true | Wrap around when arrowing past the first/last item. |
| VimBindings | bool | false | Enable Ctrl+J/Ctrl+K navigation inside the list (Ctrl+N/Ctrl+P are always on). |
| EnableHistory | bool | true | Track recents and frecency. |
| HistoryStorageKey | string | "bit-command-palette.history" | localStorage key for BitCommandPaletteBrowserStorageHistoryStore. |
| GroupWhenSearching | bool | true | Keep group headings while searching (cmdk style). When false, results are a flat ranked list. |
| GroupOrder | List<string> | [] | Explicit group order. Groups not listed come after, alphabetically. |
| PriorityWeight | double | 0.25 | Weight of Priority when a query is present (score points per priority unit). |
| FrecencyWeight | double | 6 | Weight of frecency when a query is present. |
| SearchNestedCommands | bool | true | Find nested commands from the root page too (default true), as kbar does: typing dark lists "Theme › Dark" without opening Theme first, and theme dark matches the ancestors' titles as well. Only commands registered with the service or declared in markup are found - a lazily loaded page's children do not exist until it opens - and only where every ancestor is visible and enabled and none is a multi-select page. Their recents and pins are listed on the root page as well. |
| TypoTolerance | bool | true | When a query matches nothing, look again allowing a typo per term - one missing, extra, wrong or swapped letter in a term of 4 to 7 characters, two from 8 on - so settigns still finds "Settings" (default true). Only a query that found nothing is retried, so this never adds noise to one that works; the list says the results are close matches. |
| ShowSequenceHint | bool | true | After the first chords of a shortcut sequence (G of G S), show and announce that the next key is awaited, as VS Code does in its status bar (default true). SequencePending reports it to code either way. |
| ShowModeHints | bool | true | Show a "Modes" hint group on the empty query listing registered prefixes. |
| CloseOnBackdropClick | bool | true | Close when clicking the backdrop. |
| CloseOnNavigation | bool | true | Close when the app navigates (e.g. a handler called NavigationManager.NavigateTo). |
| ResetOnClose | bool | true | Reset query and page stack when closed. When false, reopening restores the previous state. |
| HighlightMatches | bool | true | Highlight matched characters in titles and subtitles. |
| ShowFooter | bool | true | Show the footer with keyboard hints. |
| ShowShortcuts | bool | true | Render shortcut hints on rows. |
| Virtualize | bool | false | Use <Virtualize> for the list (recommended above ~500 rows). Requires fixed RowHeight. |
| Matcher | IBitCommandPaletteMatcher | BitCommandPaletteFuzzyMatcher.Default | Text matcher used for scoring. Default BitCommandPaletteFuzzyMatcher. |
| Weights | BitCommandPaletteMatchWeights | new() | Per-field weights for scoring. |
| Strings | BitCommandPaletteStrings | new() | UI strings. Subclass or set properties to localize. |
| Commands | List<BitCommandPaletteCommand> | [] | Commands registered at startup. |
| Modes | List<BitCommandPaletteCommandMode> | [] | Modes registered at startup. |
| Sources | List<IBitCommandPaletteSource> | [] | Async sources queried in the default mode. |
| RecordCommandIdsInTraces | bool | true | Whether the bit.command_palette.command activities the palette traces carry the command's id (default true) - see BitCommandPaletteDiagnostics. Turn it off when ids embed personal data, as ids made from an API's records can (person:[email protected]). Metrics never carry ids, and queries, prompt values and titles are never recorded. Off, it also keeps a command's id and title out of the palette's log messages about running it - a failure, a refusal, a guard that threw, an unsafe link - which usually leave through the same pipeline; they read (hidden) instead. The configuration warnings about shortcuts and duplicate ids, which name the commands an app registers, still carry them. |
| AllowedUrlSchemes | HashSet<string> | new(StringComparer.OrdinalIgnoreCase) { "http", "https", "mailto", "tel" } | The URL schemes a command's Href may use; relative links are always allowed. A link with any other scheme - javascript:, data:, vbscript: - is refused and logged instead of followed, because commands often carry data from an API (see IBitCommandPaletteSource). Default http, https, mailto and tel; compared case-insensitively. |
| SequenceTimeoutMs | int | 1000 | Milliseconds a multi-chord sequence (G I) waits for the next chord. Must be positive. |
| DebounceMs | int | 150 | Debounce for async sources, in milliseconds. Must not be negative. |
| SourceTimeoutMs | int | 10000 | How long an async source may take, in milliseconds, before it counts as failed and its results are replaced by a retry row. 0 waits for ever. Must not be negative. |
| MaxRecents | int | 5 | How many recent commands to show on the empty query. Must not be negative. |
| MaxHistoryEntries | int | 200 | Upper bound of history entries kept; pinned commands are never pruned. Must not be negative. |
| MaxResults | int | 150 | Max rows rendered (groups excluded) for a query. Protects against huge registries. Must be positive. |
| RowHeight | float | 44 | Row height in pixels used by virtualization. Must be positive. |
BitCommandPaletteTrigger properties
A button that opens the modal palette - optionally with a query or on a command's page - and shows its toggle shortcut in the platform's own symbols.
| Name | Type | Default value | Description |
|---|---|---|---|
| ChildContent | RenderFragment? | null | Replaces the button's content (icon, label and shortcut hint). Without a Label the button is named by what the content shows, followed by ", Open command palette"; content that shows only an icon sets Label="", so the name does not start with the separator. |
| Classes | BitCommandPaletteTriggerClassStyles? | null | Custom CSS classes for the different parts of the trigger. |
| Label | string? | null | The label. Default: "Search"; an empty one shows the icon alone. The button's accessible name starts with it. With ChildContent it is not shown, only named: set it to the text the content shows, or to an empty string for content that shows only an icon, and the button is named as the default one is. |
| MacKeys | bool? | null | Forces the macOS key symbols on or off. Default: the platform the palette detected. |
| PageCommandId | string? | null | Opens the palette directly inside the page of the command with this id. |
| Query | string? | null | Opens the palette with this query (e.g. a mode prefix). |
| ShowShortcut | bool | true | Shows the toggle shortcut of the palette. Default: true. |
| Styles | BitCommandPaletteTriggerClassStyles? | null | Custom CSS styles for the different parts of the trigger. |
BitCommandPaletteTriggerClassStyles properties
| Name | Type | Default value | Description |
|---|---|---|---|
| Root | string? | null | Custom CSS classes/styles for the root element (the button) of the BitCommandPaletteTrigger. |
| Icon | string? | null | Custom CSS classes/styles for the search icon of the BitCommandPaletteTrigger. |
| Label | string? | null | Custom CSS classes/styles for the label of the BitCommandPaletteTrigger. |
| Shortcut | string? | null | Custom CSS classes/styles for the shortcut hint of the BitCommandPaletteTrigger. |
BitCommandPaletteOption properties
A command declared in markup inside a BitCommandPalette, directly or in a BitCommandPaletteGroup. Nested options turn it into a page.
| Name | Type | Default value | Description |
|---|---|---|---|
| AlwaysShow | bool | false | Listed whatever the query, e.g. for a "couldn't find it?" row. |
| Badge | string? | null | A small pill at the end of the row, e.g. "New" or "Beta". |
| Checked | bool? | null | The state of a toggle; renders a switch. |
| ChildContent | RenderFragment? | null | Nested BitCommandPaletteOptions turn this item into a page. |
| ChildrenPlaceholder | string? | null | Placeholder for the nested page when this item has child items. |
| ConfirmMessage | string? | null | Asks for a second Enter before running, showing this message. |
| Description | string? | null | Longer text for the detail pane. Searched with a low weight. |
| Destructive | bool | false | Styled as dangerous. With ConfirmMessage, Enter has to be pressed twice. |
| Disabled | bool | false | Listed but not runnable. |
| DisabledReason | string? | null | Why the item is disabled; shown instead of the subtitle and when it is selected. |
| GlobalShortcut | bool | true | Whether Shortcut also fires while the palette is closed. Default true. |
| Href | string? | null | Navigation target (used when OnExecute is not set). |
| Icon | RenderFragment? | null | An icon rendered before the title. |
| IconCss | string? | null | A CSS class for an icon element, e.g. bi bi-house. |
| Id | string? | null | Stable id. Defaults to a slug of Title. |
| KeepOpen | bool | false | Keep the palette open after OnExecute. |
| Keywords | string? | null | Comma or space separated keywords. |
| Kind | BitCommandPaletteCommandKind? | null | The semantic kind; picks the default icon. Inferred when not set. |
| MultiSelect | bool | false | Allow checking several children before applying with Ctrl+Enter (calls OnExecute with the selection). |
| NewTab | bool | false | Open Href in a new tab. |
| OnExecute | EventCallback<BitCommandPaletteCommandContext> | Invoked when the item is selected. The palette closes afterwards unless KeepOpen is set. | |
| Priority | int? | null | A ranking nudge; see BitCommandPaletteCommandPriority. Defaults to the group's priority. |
| Shortcut | string? | null | Shortcut, e.g. Mod+Shift+D or G I. |
| Subtitle | string? | null | A secondary label next to the title. Searched and highlighted. |
| Tags | string[]? | null | Free-form labels that modes can scope to; combined with the group's. |
| Title | string | string.Empty | The label. Searched with the highest weight and highlighted. |
| Value | string? | null | The current value of a setting, e.g. "Dark". |
BitCommandPaletteGroup properties
Groups the BitCommandPaletteOptions declared inside it under one heading.
| Name | Type | Default value | Description |
|---|---|---|---|
| ChildContent | RenderFragment? | null | The BitCommandPaletteOptions of the group. |
| Heading | string | string.Empty | Group heading applied to all BitCommandPaletteOption children. |
| Priority | int? | null | Priority applied to children that don't set their own. |
| Tags | string[]? | null | Tags applied to all children (for mode scoping). |
BitVisibility enum
| Name | Value | Description |
|---|---|---|
| Visible | 0 | The content of the component is visible. |
| Hidden | 1 | The content of the component is hidden, but the space it takes on the page remains (visibility:hidden). |
| Collapsed | 2 | The component is hidden (display:none). |
BitDir enum
| Name | Value | Description |
|---|---|---|
| Ltr | 0 | Ltr (left to right) is to be used for languages that are written from the left to the right (like English). |
| Rtl | 1 | Rtl (right to left) is to be used for languages that are written from the right to the left (like Arabic). |
| Auto | 2 | Auto lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element. |
Feedback
Found a mistake, a gap, or something that could be clearer? Every page and every component is one click from its source.