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.
Building commands
Commands built in C# and declared in markup: their identity, groups and ordering, toggles, disabled, hidden and destructive commands, page-scoped commands, inline palettes and the service.
Commands from code
A command is an immutable
The entry points:
Every member of the model, with the builder method that sets it:
There are three ways to hand commands to the palettes, and they can all be used at once: the palette's
Below, an inline palette lists the commands passed to its
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.
Builder
Export…A blank command, filled in step by step
Save
Ctrl+S
Reload
Rename…
Theme
Links
Getting started
bit platform on GitHub
What's newNew
Last run: Nothing yet · "Say hello" is not registered
Identity
Recents, pins, the active row,
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:
Different titles can derive the same id -
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
Below, Greet the team is registered with the id
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 |
Find("b-greet"): Greet the team · Last run: Nothing yet
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.
Search everywhere
Edit
Undo
Cut
Copy
Paste
Help
Keyboard shortcuts
Send feedback
View
Zoom in
Zoom out
Reset zoom
Toggles and settings
A toggle shows a switch and a setting shows its current value:
Because commands are immutable, the new state is a new command. There are three ways to hand it over:
.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.
Editor
Word wrap
On
Show minimap
Off
Editor theme
Light
Registered as
b-focus-mode: Enter focus modeDisabled, hidden and destructive commands
Three ways to say a command cannot, or should not, simply run:
- 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.
Selected: nothing ·
"Merge selected files" is hidden, and Alt+M is left to the page
Files
Export as PDFProRequires the Pro plan
Publish the draft
Danger zone
Delete the draft
Last run: Nothing yet
Page-scoped commands
Commands that only make sense on one page are registered by that page and go with it.
A
A registered command is changed in place with
Below, Increment counter and Decrement counter are registered by this page. Open the modal palette and look for them under "Counter", or press
<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.
Counter: 0
Declarative markup
Commands can also be written in markup, as children of the palette, next to the component that owns them.
What markup cannot say needs the builder:
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
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.
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.
Couldn't find it?
Quick create
New issueIn this project
Alt+N
New…
Set labels…
Links
Getting started
bit platform on GitHub
Preferences
Word wrap
Off
Font size
14px
Publish
Clear the cache
Sync nowYou are offline
Last run: Nothing yet · Word wrap: False · Font size: 14 px
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.
Side panel
Edit
Format document
Alt+Shift+F
Navigate
Go to symbol
View
Show line numbers
Fold all regions
Last run: Nothing yet
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.
The palette is closed ·
IsMac: False, so the toggle reads Ctrl+K
·
the registry holds 38 commands ·
Find("b-focus-mode"): Enter focus mode ·
Find("b-scratch-note"): Scratch note
15:47:19 CommandsChanged 38 commands registered
Feedback
Found a mistake, a gap, or something that could be clearer? Every page and every component is one click from its source.