Getting started
One package, one service registration, one stylesheet and one component: install Bit.Balette, register it, link its stylesheet, place the palette once in an interactively rendered layout, and register commands from anywhere. The bar below is this site's own palette - it is set up exactly like this.
Install
dotnet add package Bit.Balette
Everything ships in that one package, under one namespace, Bit.Balette. In a Blazor Web App with an
interactive client, the package belongs in the .Client project, and the services are registered in
both projects.
It needs .NET 10 or 11; Blazor WebAssembly, Blazor Server, a Blazor Web App in any interactive render mode, or
Blazor Hybrid; and a browser with the <dialog> element - every evergreen browser since 2022. It
is trimming and AOT friendly.
Register the services
builder.Services.AddBitBaletteServices(options =>
{
// Ctrl+K / ⌘K is the default; this adds VS Code's Ctrl+Shift+P as well.
options.AdditionalToggleShortcuts.Add("Mod+Shift+P");
// Groups appear in this order on the empty query; any others follow alphabetically.
options.GroupOrder.AddRange(["Navigation", "Actions", "Preferences", "Help"]);
});
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. Every page of a Blazor Web App is prerendered on the server before it
runs in the browser, so anything a component injects must resolve in both containers - share one extension
method between the two Program.cs files, the way this demo does with AddDemoServices.
Every option is listed, with this site's value, on Options & security.
Reference the stylesheet
<link rel="stylesheet" href="_content/Bit.Balette/bit-balette.css" />
In App.razor or index.html, before your own stylesheet, so your overrides of its
--bit-balette-* variables win. It is a plain stylesheet with no dependencies, and it is not added for
you: leave it out and set Unstyled="true" to style everything yourself. Add the namespace to
_Imports.razor as well:
@using Bit.BalettePlace the palette
Put one Balette where it is rendered interactively on every page, and a BaletteTrigger
wherever a visible entry point helps:
@inherits LayoutComponentBase
<header>
<BaletteTrigger Label="Search…" />
</header>
<main>@Body</main>
<Balette />
The palette renders a closed <dialog> until it is opened, so it costs nothing while it is not in
use. It needs an interactive render mode: a statically rendered palette never attaches its keyboard handling.
This site renders it from Components/AppPalette.razor, which Routes.razor puts next to
the router so the one palette outlives every page and layout. One palette per scope is the rule: every instance
listens to the same service, so two of them would open together.
BaletteTrigger is a button that opens the palette and shows its toggle shortcut in the platform's own
symbols - ⌘ K on a Mac, Ctrl K elsewhere - and declares it with
aria-keyshortcuts. Label is its text, Query opens the palette with a query
already typed (a mode prefix included), PageCommandId opens it on a command's page,
ShowShortcut="false" drops the hint, IsMac forces one platform's symbols instead of the
detected one, Class adds classes, and ChildContent replaces the whole content. Any other
attribute lands on the button. These three are live:
<BaletteTrigger Label="Find a teammate" Query="@" />
<BaletteTrigger Label="Change theme" PageCommandId="preferences.theme" ShowShortcut="false" />
<BaletteTrigger Query=">"><kbd>></kbd> Commands mode</BaletteTrigger>
Register commands
Inject IBaletteService wherever commands belong and register them:
@inject IBaletteService Palette
@inject ProjectsApi Api
@implements IDisposable
@code {
private IDisposable? _commands;
protected override void OnInitialized()
{
_commands = Palette.Register(
BaletteCmd.Navigate("Home", "/").Group("Navigation").Shortcut("G H"),
BaletteCmd.Navigate("Settings", "/settings").Group("Navigation").Shortcut("G S").Keywords("preferences", "options"),
BaletteCmd.Action("Toggle sidebar", () => _sidebarOpen = !_sidebarOpen).Group("View").Shortcut("Mod+B"),
BaletteCmd.New("Delete project")
.Group("Danger zone")
.Destructive("This cannot be undone")
.Handler(async ctx =>
{
await Api.DeleteProjectAsync(ctx.CancellationToken);
return BaletteCommandResult.Toast("Project deleted");
}));
}
// Commands registered by a page leave with the page.
public void Dispose() => _commands?.Dispose();
}
Register returns an IDisposable: dispose it to remove the commands again. Commands that
belong to the whole app are registered once, from the layout or at startup through options.Commands;
<BaletteCommands Commands="_commands" /> registers a list while it is rendered and removes it
when it goes. Registering commands covers every member a command can have.
Open it
Ctrl K (⌘ K on a Mac) toggles the palette; this site adds Ctrl Shift P for hands trained on VS Code. Code opens it through the service, optionally with a query - a mode prefix included - or directly on a command's page, and runs a command by its id without opening anything:
await Palette.OpenAsync();
await Palette.OpenAsync(">"); // commands mode
await Palette.OpenAsync(pageCommandId: "preferences.theme"); // straight to the Theme page
await Palette.ExecuteAsync("toggle:wordwrap"); // run a command by its id, nothing opened
Word wrap is on.
Things to try
Every one of these runs on the palette of this site, right now:
- Type
rc- fuzzy matching jumps to Registering commands, with the word starts highlighted. - Type
themeand press Enter - a nested page; Backspace on an empty box goes back. - Type
francais- a command nested under Language, found from the root without its accent. - Type
settigns- nothing matches as typed, so the palette retries allowing a typo. - Type
>for commands only,#105to look up an issue,@adato search people (async),?for help. - Type
doc theming- both terms must match, and the async documentation source answers too. - Pick Set labels… - a multi-select page; Ctrl Enter applies.
- Pick Rename project… (or press F2 anywhere) - a free-text prompt step, validated as you type.
- Pick Delete project - destructive, so it needs a second Enter.
- Press Tab on any row - the action panel: pin, forget, and the row's own actions.
- Close the palette and press G then S - a sequence shortcut opens the settings.
- Try the operators
'exact,^prefix,suffix$,!exclude,"a phrase"anda | b.
How it is built
Key press (browser) -> bit-balette.js toggle, global chords and G-then-X sequences, navigation keys -> Balette query, mode prefix, page stack, active row (C#) -> BaletteQuery terms and operators, parsed once per keystroke -> IBaletteMatcher fzf-style score and highlight positions per field -> BaletteRanker score + priority + frecency, the best MaxResults kept -> rows groups, pinned, recents, async source blocks -> <dialog> native top layer, focus trap, aria-activedescendant
The browser layer is small on purpose: it decides which keys belong to the palette and hands them over. What
matches, in which order, what Enter does and which page comes next are all decided in C#, so they can be
unit tested, replaced (IBaletteMatcher, IBaletteHistoryStore, IBaletteSource)
and reasoned about like the rest of the app.
Hosting models
| Host | Setup | What to know |
|---|---|---|
| WebAssembly | Services in Program.cs, the stylesheet in index.html, <Balette /> in MainLayout.razor. |
Search runs on the browser's one thread: a keystroke whose search took longer than a frame paints first, and keys typed meanwhile fold into one search. Outside AOT builds the library can be lazy loaded instead. |
| Blazor Server | The same. | Shortcuts and navigation keys are handled in the browser, so only the query and the chosen command cross the circuit. Handlers run on the server, in the circuit's scope; keys typed faster than a round trip are all kept. |
| Blazor Web App | Services in both projects, the stylesheet in App.razor. |
With global interactivity (<Routes @rendermode="..." />) the palette goes in MainLayout.razor. With per-page interactivity the layout is static: wrap the palette in a small component the layout renders interactively - <PaletteHost @rendermode="InteractiveAuto" />, below - and register commands from components in the same mode, because the registry is scoped to one circuit or one WebAssembly runtime. |
| Blazor Hybrid | The same as WebAssembly, in a MAUI, WPF or Windows Forms BlazorWebView. |
Works unchanged; the history goes to the web view's localStorage. |
<Balette />
<BaletteCommands Commands="_appCommands" />
@code {
// Registered from inside the interactive component, so they land in the same scope as the palette.
private readonly List<BaletteCommand> _appCommands = [ /* ... */ ];
}
While prerendering, the palette renders a closed dialog. It attaches its keyboard handling once it is interactive and
then marks the dialog data-ready="true" - what an end-to-end test waits for before pressing
Ctrl K on a prerendered page.
_content/Bit.Balette/bit-balette.js; there are no inline scripts and no eval, so
script-src 'self' is enough.
Lazy loading on WebAssembly
The components also work without AddBitBaletteServices, so a WebAssembly app can fetch Balette only
when someone opens a part of the app that has a palette. When the services are not registered,
Balette, BaletteTrigger and BaletteCommands create every service they need
themselves, once per browser connection, and IServiceProvider.GetBaletteService() hands the app's own
code the same IBaletteService. Mark the assembly as lazy loaded in the project that runs in the
browser, and load it before the first page that uses it renders:
<!-- The browser project's .csproj -->
<ItemGroup>
<BlazorWebAssemblyLazyLoad Include="Bit.Balette.wasm" />
</ItemGroup>
@* App.razor: the router waits for OnNavigateAsync before it renders the page. *@
@using Microsoft.AspNetCore.Components.WebAssembly.Services
@inject LazyAssemblyLoader LazyAssemblyLoader
<Router AppAssembly="typeof(App).Assembly" OnNavigateAsync="OnNavigateAsync">
...
</Router>
@code {
private async Task OnNavigateAsync(NavigationContext context)
{
// The pages with the palette: fetch Balette before they render. A second call loads nothing again. Routes
// match regardless of case, so /Admin/users is one of them too.
if (context.Path.StartsWith("admin", StringComparison.OrdinalIgnoreCase))
await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Balette.wasm"]);
}
}
Those pages, or a layout only they use, hold the palette and register commands through
GetBaletteService() instead of injecting IBaletteService:
@* AdminLayout.razor *@
@inherits LayoutComponentBase
@inject IServiceProvider Services
@implements IDisposable
<BaletteTrigger Label="Search…" />
@Body
<Balette />
@code {
private IDisposable? _commands;
protected override void OnInitialized()
=> _commands = Services.GetBaletteService().Register(
BaletteCmd.Navigate("Users", "/admin/users").Group("Navigation"),
BaletteCmd.Navigate("Billing", "/admin/billing").Group("Navigation"));
public void Dispose() => _commands?.Dispose();
}
- Leave
AddBitBaletteServicesout of that project'sProgram.cs: calling it references Balette's types before the assembly is there. For the same reason only what renders after the assembly has loaded may use Balette's types - the pages it is loaded for and a layout only they use, notApp.razor, a layout every page shares orProgram.cs. - 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 Balette's: no
IBaletteSourceclass, noIBaletteHistoryStore, no component that inheritsBalette. The router reads the types of those assemblies at startup, and 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 Bit.Balette has loaded, breaking the app's use of it for the rest of the session. Put such a class in a library that is lazy loaded together with Bit.Balette. - The stylesheet is a plain
<link>, served whether the assembly has loaded or not, and the palette imports its JavaScript module the first time it renders. - Without the registration the palette runs on the default
BaletteOptions. Its parameters override most of them per instance (Strings,ToggleShortcut,Theme,Density,Loop,EnableHistory, ...) - aBaletteTriggershows and announces the toggle shortcut and the strings of the palette it opens - and modes, sources and commands are registered throughGetBaletteService(). The rest - such asGroupOrder,AdditionalToggleShortcuts, the field weights, the matcher andAllowedUrlSchemes- 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
localStorageunder the defaultHistoryStorageKey,bit-balette.history, which every app on the same origin shares. An app that must not write to the browser setsEnableHistory="false"on its palettes. - The palette logs one warning that the services are not registered - 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.
builder.Logging.AddFilter("Bit.Balette.BitBalette", LogLevel.None)inProgram.cssilences it without referencing Balette'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.
Troubleshooting
- Ctrl K does nothing. The palette is not interactive: it is in a statically rendered layout. Also check that no other script calls
preventDefaulton the key first. - Options from
Program.csstop working once the page turns interactive - a toggle shortcut, the group order, commands added throughoptions.Commands. 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. CallAddBitBaletteServicesin both, through one shared method. - The palette opens unstyled. The stylesheet link is missing.
- A toggle shows its old state. Commands are immutable: register a new command with the same id, call
Palette.Update, or giveBaletteCommandsa new list. - Recents forget a command whose title changed. Its id was derived from the title; set an explicit
Id. - A page's commands are still listed after leaving it. Dispose the handle
Registerreturned, or use<BaletteCommands>. - A global shortcut does not fire in a text box. Deliberate for plain keys; use a chord with a modifier, or set
SuppressShortcutsInEditableElements = false. - Two palettes open at once. Place one
Baletteper scope; every instance listens to the same service. - A command does nothing, or the wrong one runs. Look at the app's log: the palette warns about duplicate ids, shortcuts several commands claim or the toggle takes, links it refused, and logs every failed command and page.
- A command's shortcut works only after opening the palette. Its
VisibleWhenchanged while the palette was closed: callPalette.Refresh()after the state it reads changes. - Commands passed to the
Commandsparameter do not update. Assign a new list, or callPalette.Refresh()after changing the same one.