Skip to content

Extras

CommandPalette

Bit.BlazorUI.ExtrasCommandMenuCmdkSpotlight

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

Options & storage

The app-wide options, how parameters and BitParams override them, what the palette does for security, and where its history is stored.

Options

BitCommandPaletteOptions is the app-wide configuration, set once in 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 Keyboard & shortcuts topic.
  • 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).
The look is not an option: the palette follows the BlazorUI theme (a 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.

CloseOnBackdropClickA click on the backdrop closes the palette. true
CloseOnNavigationThe palette closes when the app navigates. true
ResetOnCloseClosing clears the query and the pages; false reopens where it was left. true
ShowFooterThe hint bar under the list, where toasts show. true
ShowShortcutsShortcut hints at the end of the rows. true
VirtualizeRenders only the visible rows; recommended above about 500. false
RowHeightA row's height in pixels while virtualized. Must be positive. 44
StringsEvery label and announcement of the palette. BitCommandPaletteStrings
EnableHistoryRecords recents, pins and frecency. true
MaxRecentsRecent commands listed on the empty query. Must not be negative. 5
MaxHistoryEntriesCommands the history keeps at most; pinned ones are never pruned. Must not be negative. 200
HistoryStorageKeyThe localStorage key of the default history store. bit-command-palette.history
ToggleShortcutOpens and closes the palette; null for none. The palette's ToggleShortcut parameter overrides it. mod+k
AdditionalToggleShortcutsMore shortcuts that open and close the palette. none
SuppressShortcutsInEditableElementsPlain keys pressed in an input, a text area or a content-editable element are typing, not shortcuts; chords with a modifier still fire, unless the element claims them itself. true
SequenceTimeoutMsHow long a sequence (G I) waits for its next chord. Must be positive. 1000
ShowSequenceHintShows and announces a sequence in progress. true
LoopArrowing past the last row comes back to the first. true
VimBindingsCtrl+J / Ctrl+K move inside the list; Ctrl+N / Ctrl+P always do. false
DebounceMsQuiet time after the last keystroke before async sources are asked. Must not be negative. 150
SourceTimeoutMsHow long a source may take before it counts as failed and gets a retry row; 0 waits for ever. 10000
ShowModeHintsThe Modes group listing the registered prefixes on the empty query. true
CommandsCommands registered at startup. none
ModesModes registered at startup. none
SourcesAsync sources asked in the default mode. none
MatcherScores and highlights every field: fuzzy by default, BitCommandPaletteSubstringMatcher or your own. BitCommandPaletteFuzzyMatcher
WeightsField weights: title, keywords, subtitle, group, path, description, tags. 1 / 0.9 / 0.7 / 0.5 / 0.5 / 0.4 / 0.3
MaxResultsRows kept per query, groups excluded; pinned and recent commands are listed beyond it. Must be positive. 150
GroupWhenSearchingResults keep their group headings while searching; false lists one flat ranked list. true
GroupOrderGroups listed first, in this order; the rest follow alphabetically. none
PriorityWeightHow much a command's priority nudges its rank while searching. 0.25
FrecencyWeightHow much frecency - use, weighted by how recent - nudges it. 6
SearchNestedCommandsNested commands are found from the root page, with their path. true
TypoToleranceA query that found nothing is retried allowing a typo per term. true
HighlightMatchesMatched characters in titles and subtitles are marked. true
AllowedUrlSchemesSchemes a command's Href may use; relative links always may. http, https, mailto, tel
RecordCommandIdsInTracesWhether traces and the log messages about running a command carry its id; metrics never do. true

OnQueryChanged: (empty), picked: nothing yet

Options, parameters and BitParams

A palette's settings come from three places, and the nearest wins:
  1. The palette's own parameter - <BitCommandPalette Loop="false" /> - always wins.
  2. A BitCommandPaletteParams cascaded through a BitParams: every palette under the BitParams takes 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 nested BitParams refines the one around it: it replaces only what it sets, unless it is Isolated.
  3. 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.

Banana
Mango
Orange
Pineapple
Banana
Mango
Orange
Pineapple

Security

Commands often carry data from an API - an async source's results, a page loaded on demand - so the palette treats what it shows and follows as untrusted:
  • 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 are RenderFragments you build, or a CSS class name.
  • Links are checked. A command's Href is followed only when it is relative or its scheme is in AllowedUrlSchemes (BitCommandPaletteOptions; http, https, mailto and tel by default, compared case-insensitively). A javascript:, data: or vbscript: 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's CommandFailed event.
  • Visibility is not authorization. VisibleWhen and Disabled only 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 data ExcludeFromHistory(), 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.command activities 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 localStorage holds are dropped.
  • Search is bounded. A query longer than BitCommandPaletteQuery.MaxLength (256) characters matches nothing instead of being searched, and a field longer than BitCommandPaletteFuzzyMatcher.MaxOptimalLength is 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.

Follow a javascript: linkjavascript:alert('This never runs')
Sam Rivera[email protected]
<img src=x onerror=alert(1)> stays text

Last run: nothing yet

History storage

Every run is recorded - unless the command has 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 localStorage under HistoryStorageKey (BitCommandPaletteOptions, default bit-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) and SaveAsync (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.
The action panel of any row also offers "Clear recent commands", which forgets every use and keeps the pins. Run a few commands below, pin one with Mod Shift P, then read what the default store wrote - or reload the page and clear the query: the recents are still there.

Open the calendar
Open the contacts
Open the notes
Open the tasks
Open the weather
Open the photos

Key: bit-command-palette.history, MaxRecents: 5, MaxHistoryEntries: 200
Not read yet.

Feedback

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