Skip to content

Registering commands

A command is an immutable record: a title, where it is listed, what it matches and what it does. There are three ways to hand one to the palette, and this app uses all of them at once - the palette merges them into one list and nothing in it says where a row came from.

Page-scoped commands

Counter: 0

Open the palette and look for Increment counter and Decrement counter under "This page", or press Ctrl ↑ / Ctrl ↓ 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.

Every change hands the registry a copy of each row made with command.With(...) - same id, handler and shortcut, a new badge - through Palette.Update. Reset counter is destructive, so it asks first, and it is disabled, with its reason, while the counter is at zero.

The programmatic API

IBaletteService is the palette's remote control: register, update, find, open, close and execute from anywhere that can inject it - and listen to what the palette does.

Register hands back an IDisposable: Say hello is in the palette - and Find("this-page.say-hello") finds it - from the moment it is registered until the handle is disposed (not registered now). Palette.Unregister(id) removes one command by its id instead; the to-dos on Nested pages & flows work that way.

Executed this visit: 0 · Last: nothing yet · The palette is closed · The registry holds 53 commands · Find("toggle:wordwrap") says it is on

// Palette is the IBaletteService, injected wherever it is needed.
IDisposable greeting = Palette.Register(BaletteCmd.New("Say hello").Group("This page"));
greeting.Dispose();                                  // gone again, shortcut included

Palette.Unregister("todo:3");                        // or one command, by its id
Palette.Update(Palette.Find("toggle:wordwrap")!.With(b => b.Badge("On")));

await Palette.OpenAsync("!delete");                  // a query, operators and mode prefixes included
await Palette.OpenAsync(pageCommandId: "actions.set-labels");
await Palette.ExecuteAsync("toggle:wordwrap");       // as if chosen, without opening

// The service outlives the page: subscribe named handlers, and remove them when the page is disposed.
Palette.Opened += OnOpened;
Palette.CommandsChanged += OnCommandsChanged;
Palette.CommandExecuted += OnExecuted;

private void OnOpened() => Log("Opened");
private void OnCommandsChanged() => Log($"{Palette.Commands.Count} commands registered");
private void OnExecuted(object? sender, BaletteCommandExecutedEventArgs e) => Log($"{e.Command.Id} -> {e.Result} in {e.Duration.TotalMilliseconds:0} ms");

public void Dispose()
{
    Palette.Opened -= OnOpened;
    Palette.CommandsChanged -= OnCommandsChanged;
    Palette.CommandExecuted -= OnExecuted;
}

The service's events, newest first:

00:07:10 CommandsChanged 53 commands registered
Shown only when it applies

Merge selected files is registered by this page with .VisibleWhen(() => _selected.Count >= 2) and the shortcut Alt M. Select two files, open the palette and it is there; select one and it is gone - from the list and from the keyboard: the shortcut of a command its predicate hides is left to the page.

Selected: nothing · Merge selected files is hidden, and Alt+M is the page's

// Registered by <BaletteCommands Commands="_pageCommands" /> in the markup, so it goes when the page does.
_pageCommands =
[
    BaletteCmd.New("Merge selected files")
        .Group("This page")
        .Shortcut("Alt+M")
        .VisibleWhen(() => _selected.Count >= 2)   // asked every time the list is built
        .Handler(_ => MergeAsync(_selected)),
];

private void ToggleFile(string file)
{
    if (!_selected.Remove(file))
    {
        _selected.Add(file);
    }

    // The palette is closed: tell it the predicate's answer may have changed, so Alt+M is claimed or released now.
    Palette.Refresh();
}
A predicate is evaluated every time the list is built, so an open palette is always right. The global shortcuts are synced to the browser ahead of time, though, so after state a predicate reads changes while the palette is closed - a selection, the signed-in user, the current route - call Palette.Refresh(): the command that just became available answers its keys, and the one that went away leaves them alone. This page calls it on every click above.

The model

Every member of BaletteCommand, with a command of this app that uses it - search for it and look. The builder has a method of the same name for each, and BaletteItem a parameter for most of them (see declarative markup).

MemberMeaningIn this app
IdStable identity, derived from the title, group and parent unless set (see identity).The toggles' toggle:wordwrap
TitleThe label. Required, searched with the highest weight, highlighted.Every row
SubtitleA secondary label next to the title. Searched and highlighted.Theme › Dark: "Always dark"
DescriptionLonger text for the detail pane. Searched with a low weight.New issue, in the detail pane
KeywordsAliases, synonyms, abbreviations. A keyword hit is shown under the title.Settings also matches config
GroupThe heading the command is listed under.Navigation, Actions, Preferences…
Icon / IconCssA RenderFragment, or a CSS class such as bi bi-house for an icon font. Without one, the kind's icon.Icon: the counter's + and − on this page, inline SVG. IconCss: the labels' coloured dots, the people's avatars
Shortcut / GlobalShortcutA chord or a sequence. Global by default, so it fires while the palette is closed; global: false only shows it.G S, Alt Z, F2
PriorityA ranking nudge: BaletteCommandPriority names Lowest (-100), Low (-50), Normal (0, the default), High (50) and Highest (100); any other number works too. It leads on the empty query and only nudges a search (see ranking).Introduction is High, the feedback row Lowest
ParentThe id of the command whose page lists this one. Set for you on registered children.The theme options: preferences.theme
Children / ChildrenProvider / SourceNested commands: static, loaded when the page opens, or searched as the page is typed in.Theme, Assign to…, Find a person…
ChildrenPlaceholder / MultiSelectChildrenThe search box placeholder on that page, and whether its rows are checkboxes.Set labels…
ActionsSecondary actions, listed in the action panel on Tab before pin and forget.People rows: @ada, then Tab
HandlerWhat runs on selection, and what it answers decides what happens next (see flows).Every action
Href / ForceLoad / OpenInNewTabA navigation target, used when there is no handler. Only relative links and the allowed schemes are followed.GitHub repository opens a new tab
KindAction, Navigation, Toggle, Setting, Search, Page, Help or Recent: picks the default icon and is exposed as data-kind.The Help group sets Help after Href
Disabled / DisabledReasonListed but not runnable; the reason replaces the subtitle, and Enter answers with it.Export… › PDF, Reset counter at zero
IsVisibleA predicate (VisibleWhen) evaluated every time the list is built.Merge selected files, above
Destructive / ConfirmMessageDrawn in the danger colour; with a message, the first Enter arms it and the second runs it. .Confirm("message") asks for the second Enter without the danger colour.Delete project
Badge / Value / CheckedA pill ("New", "3"), a current value ("Dark"), or a toggle's switch.What's new, Theme, Word wrap
AlwaysShowListed whatever the query, like cmdk's forceMount.Feedback: couldn't find a command?
ExcludeFromHistoryNever recorded in recents or frecency.The rows Find a person… finds
TagsFree-form labels that modes can scope to.command, which the > mode lists
DataAnything your templates or handlers need.The Person a people row shows in the detail pane

The fluent builder

Every command in this app's Navigation, Actions, Preferences, Danger zone and Help groups is built in Services/DemoCommands.cs and registered once, from Components/AppPalette.razor. BaletteCmd is the entry point; 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 BaletteCommand does.

BaletteCmd.Navigate("Settings", "/commands#settings")
    .Group("Navigation")
    .Shortcut("G S")
    .Keywords("preferences", "options", "config"),

BaletteCmd.New("Word wrap")
    .Id("toggle:wordwrap")
    .Group("Preferences")
    .Shortcut("Alt+Z")
    .Checked(state.WordWrap)
    .Handler(_ =>
    {
        state.ToggleWordWrap();
        return Task.FromResult(BaletteCommandResult.KeepOpen);
    }),
BaletteCmd.New("Export…")                       // a blank command
BaletteCmd.Navigate("Settings", "/settings")    // Kind = Navigation, Href set
BaletteCmd.Action("Save", () => Save())         // runs and closes
BaletteCmd.Action("Reload", ReloadAsync)        // a Func<Task>
BaletteCmd.Action("Rename…", ctx => ...)        // full control over the result
BaletteCmd.Page("Theme", light, dark)           // Kind = Page, with children

Handler takes an Action, an Action<BaletteCommandContext> or a Func<BaletteCommandContext, Task> - all of which close the palette when they are done - or a Func<BaletteCommandContext, Task<BaletteCommandResult>>, which says what happens next: stay open, go back, a page, a prompt, a toast or an error (see nested pages & flows).

Identity

Recents, pins, the active row, Find, ExecuteAsync and OpenAsync(pageCommandId: ...) all go by a command's Id. Without one it is a slug of the title, prefixed with the parent's id or the group. These are worked out by the library on this page, right now:

Built asId
BaletteCmd.New("Settings").Group("Navigation")navigation.settings
BaletteCmd.New("Rename project…").Group("Actions")actions.rename-project
BaletteCmd.New("What's new").Group("Help")help.what-s-new
BaletteCmd.New("Dark").Parent("preferences.theme")preferences.theme.dark
BaletteCmd.New("C#")c
BaletteCmd.New("C++")c
BaletteCmd.New("🚀")u1f680
BaletteCmd.New("Word wrap").Id("toggle:wordwrap")toggle:wordwrap

Set the id whenever the title can change - a toggle that says "On" or "Off", a translated title - so recents, pins and the active row survive the change. A copy made with With keeps its id even when its title changes. Registering an id that is already registered replaces it: the later registration wins, which lets a page override a global command. C# and C++ both derive c, so one would replace the other; when two commands registered together share an id, the palette logs a warning naming both titles.

// A title that changes needs an id that does not.
BaletteCmd.New(wordWrap ? "Disable word wrap" : "Enable word wrap").Id("toggle:wordwrap")

// A copy keeps the id, whatever it changes.
var renamed = command.With(b => b.Title("Rename…").Badge("New"));

Declarative markup

Commands can live in markup next to the component that owns them. A BaletteItem inside a BaletteItem turns the outer one into a page, and a BaletteGroup gives its heading to its items, its priority to every item that does not set its own, and adds its tags to theirs. The Quick create group of this app is declared like this in Components/AppPalette.razor:

<Balette>
    <BaletteGroup Heading="Quick create" Priority="20">
        <BaletteItem Title="New issue" Shortcut="C" Keywords="create add" IconCss="demo-plus"
                     OnExecute='_ => State.Record("New issue dialog opened")' />
        <BaletteItem Title="New…" ChildrenPlaceholder="What do you want to create?">
            <BaletteItem Title="Project" OnExecute='_ => State.Record("New project")' />
            <BaletteItem Title="Document" OnExecute='_ => State.Record("New document")' />
            <BaletteItem Title="Team" Badge="Beta" OnExecute='_ => State.Record("New team")' />
        </BaletteItem>
    </BaletteGroup>
</Balette>

OnExecute receives the BaletteCommandContext, and the palette closes after it unless KeepOpen is set; an item with an Href and no OnExecute navigates. An item re-registers only when one of its parameters actually changed, so re-rendering the layout is cheap. The parameters:

ComponentParameters
BaletteItem Title (required), Id, Subtitle, Description, Keywords (one comma or space separated string), Shortcut and GlobalShortcut, Icon or IconCss, Href and NewTab, OnExecute and KeepOpen, Priority, Disabled and DisabledReason, Destructive and ConfirmMessage (a message alone asks for the second Enter without the danger colour), Badge, Value, Checked, Kind, Tags, AlwaysShow, ChildrenPlaceholder, MultiSelect, and nested items as its child content.
BaletteGroup Heading (required), Priority, Tags, and the items as its child content.

What markup cannot say needs the builder: Data, VisibleWhen, 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 it alone; and its Commands parameter, a third, per-instance list - the only one the inline palette at the end of this page uses.

Scoped to a page

BaletteCommands registers its list when it renders and removes it when it is disposed, and hands a new registration over when it is passed a different list. IBaletteService.Register does the same from code and returns the handle to dispose. A registered command is changed in place with Update, which replaces the command with the same id wherever it was registered - its static children included.

@inject IBaletteService Palette

<BaletteCommands Commands="_pageCommands" />

@code {
    private int _count;
    private List<BaletteCommand> _pageCommands = [];

    protected override void OnInitialized() => _pageCommands =
    [
        BaletteCmd.New("Increment counter")
            .Group("This page")
            .Shortcut("Ctrl+Up")
            .Badge("0")
            .Handler(_ =>
            {
                _count++;
                // The same command, with the new count: Update swaps it in by id.
                Palette.Update(Palette.Find("this-page.increment-counter")!.With(b => b.Badge($"{_count}")));
                StateHasChanged();
                return Task.FromResult(BaletteCommandResult.KeepOpen);
            }),
    ];
}

Groups and ordering

  • On the empty query, ungrouped commands come first, then the groups in options.GroupOrder - here Navigation, Actions, Preferences, Danger zone and Help - then the rest: the group holding the highest-priority or most-used command first, alphabetically on a tie. Quick create and This page are not in the list, so they follow it. Pinned and recent commands come before all of them, and ungrouped commands listed under those get a heading of their own, Suggestions, so they do not read like more recents.
  • Inside a group, commands are ordered by priority, then by frecency, then in the order they were registered or declared - list Auto, Light and Dark and that is the order they appear in.
  • While searching, results are ordered by rank - equal ranks by title - and groups by their best match. GroupWhenSearching = false flattens them into one ranked list; try it on Search & ranking.
builder.Services.AddBitBaletteServices(options =>
{
    // First on the empty query, in this order; the other groups follow.
    options.GroupOrder.AddRange(["Navigation", "Actions", "Preferences", "Danger zone", "Help"]);

    // While searching: one flat list ranked by match, instead of a heading per group.
    options.GroupWhenSearching = false;
});

// Inside a group: priority, then frecency, then the order of registration.
BaletteCmd.Navigate("Introduction", "/").Group("Navigation").Priority(BaletteCommandPriority.High)

Settings that stay in sync

These values are what the palette's Preferences commands change. Change one here and open the palette: the toggle shows it. Change it there and this page shows it. The palette host rebuilds its command list from DemoState whenever it changes, so a toggle's switch is never stale. The theme is the site's own - the header's toggle flips it too.

Or search them, with a palette in the page rather than over it: Inline="true", listing only its own commands (IncludeRegisteredCommands="false") in the compact density. It stays out of the layout's palette's way - Ctrl+K still opens that one, and Alt+Z still toggles word wrap once.

Word wrap On
Desktop notifications Off
Show minimap On
Theme: Auto On
Theme: Light Off
Theme: Dark Off
<Balette Inline="true"
         IncludeRegisteredCommands="false"
         Commands="_settingsCommands"
         Density="compact"
         ShowFooter="false"
         EnableHistory="false"
         Placeholder="Search these settings…"
         Style="--bit-balette-max-height: 260px" />
  • An inline palette is a <section> named like the dialog (data-balette="inline"), always open and as wide as its container; --bit-balette-max-height bounds its list.
  • Esc goes back a page or clears the query instead of closing, and with nothing to undo it is left to the page, so a drawer around the palette still closes on it. Tab moves the focus on - there is no focus trap.
  • A command that would close the palette resets it to its root page, and result counts are announced only while it has the focus.
  • It neither opens on the toggle shortcut nor answers OpenAsync, CloseAsync or ExecuteAsync, and claims no global shortcuts, so nothing runs twice; a key the modal palette claimed - Ctrl K typed in this box - is left to it.
  • IncludeRegisteredCommands="false" leaves out the registry's commands, sources and modes, so it lists only what is declared in its markup or passed to Commands.
Rebuilding the whole list is the simplest way to keep it current, and cheap: it is a few dozen records. IBaletteService.Update(command) replaces a single command by id instead, which suits a registry too large to rebuild on every change - the counter at the top of this page works that way.
An unhandled error has occurred. Reload 🗙