Skip to content

Nested pages & flows

A palette is more than a list: a command can open a page of further commands, ask for text, collect a selection or ask to be confirmed, and every one of those steps happens inside the same box, with breadcrumbs above it and Esc or Backspace to step back. Each button below opens this site's palette on one of them.

The flows of this app
FlowDeclared withIn this app
Static page .Children(a, b, c) Theme - three options, the current one checked
Lazy page .Children(async (ctx, ct) => ...) Assign to… - loads people for 400 ms, with a spinner
Declarative page Nested <BaletteItem> New… in Quick create
Searching page .Source("Directory", async (query, ct) => ...) Find a person… - asks the "server" for every query typed on the page
Found from the root SearchNestedCommands (on by default) Language › Français - type francais without opening Language
Ad-hoc page BaletteCommandResult.Page(...) Export… - the handler decides the list, one row disabled
Prompt BaletteCommandResult.Prompt(...) Rename project… - pre-filled, validated as you type, and "admin" refused by the handler with Error
Multi-select .MultiSelect() Set labels… - Enter or Space checks, Ctrl Enter applies
A chain of steps Prompt → Page(..., multiSelect: true, onSubmit) Create webhook… - an https address, then the events to send; no event is an Error
Back to the root BaletteCommandResult.Reset Add a to-do… - registers the to-do and lands on the root, query cleared, where it is listed ahead of every group
Destructive .Destructive("message") Delete project - in the danger colour; the first Enter asks, the second runs, Esc or moving away disarms
Confirmation .Confirm("message") Sign out other devices - the same second Enter, for a command that deserves a pause but is not dangerous
Toast BaletteCommandResult.Toast(...) What's new - a message in the footer, palette kept open
Long-running ctx.CancellationToken Generate report… - three seconds of work: the palette shows it busy, and Esc cancels it
A handler that throws CommandFailed Sync with server - a generic message, never the exception's text
An error written for users e.Message = e.Exception.Message Publish release - a ValidationException whose text the page chose to show
A page that fails to load A loader that throws Recent deployments… - fails every other time: Try again (or Enter) loads it
Action panel .Actions(...) Any row: press Tab. People rows add their own two actions

Project: Acme Dashboard · Labels: bug · Open to-dos: 0 · Last: nothing yet

What a handler returns

A handler does its work and then tells the palette what comes next. 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.

ResultWhat the palette does
CloseCloses. The default of every handler that returns no result, and of navigation.
KeepOpenStays on the current page and rebuilds the list - the toggles use it.
BackGoes back one page - the theme options use it to land on the list again.
ResetClears the query and returns to the root page, still open - Add a to-do… uses it.
Page(title, commands, placeholder, multiSelect, onSubmit)Pushes a page listing these commands. They are not registered anywhere: they live on the page only. With multiSelect: true, Ctrl Enter runs onSubmit with the checked ones.
Prompt(title, onSubmit, validate, placeholder, initialValue)Turns the input into a text field; Enter calls onSubmit with ctx.PromptValue, once validate - null for a value that may be submitted, the message to show otherwise - accepts it.
Toast(message, keepOpen)Shows a message in the footer, then closes shortly afterwards - or stays, with keepOpen: true.
Error(message)Shows an error, announced assertively, and stays where the palette is - on a prompt, so the value can be corrected.
// Stay, and rebuild the list. Checked is fixed on the record, so the host builds its commands from state again on
// every state.Changed (Components/AppPalette.razor) and the rebuilt list shows the switch's new state.
BaletteCmd.New("Word wrap").Checked(state.WordWrap).Handler(_ =>
{
    state.ToggleWordWrap();
    return Task.FromResult(BaletteCommandResult.KeepOpen);
})

// Back to the root, the query cleared, where the new to-do is listed.
BaletteCmd.New("Add a to-do…").Handler(_ => Task.FromResult(BaletteCommandResult.Prompt(
    "New to-do",
    submit =>
    {
        Palette.Register(BaletteCmd.New(submit.PromptValue!.Trim()).Id($"todo:{++_todoCount}"));
        return Task.FromResult(BaletteCommandResult.Reset);
    })))

// A message in the footer, the palette kept open.
BaletteCmd.New("What's new").Handler(_ => Task.FromResult(BaletteCommandResult.Toast("You are on the latest version", keepOpen: true)))

// A second Enter first: in the danger colour, or - with Confirm - without it.
BaletteCmd.New("Delete project").Destructive("This permanently deletes the project").Handler(_ => DeleteProjectAsync())
BaletteCmd.New("Sign out other devices").Confirm("Sign out every other browser and device?").Handler(_ => SignOutOthersAsync())

The context a handler gets

MemberWhat it holds
CommandThe command being run.
Query / ModePrefixWhat was typed, without the mode prefix, and that prefix - the feedback row thanks you for the query it was reached with.
PromptValueThe text of a prompt step.
SelectedCommandsThe checked rows of a multi-select page.
Services / GetRequiredService<T>()The user's DI scope - where an API client comes from.
NavigationThe NavigationManager.
PaletteThe IBaletteService itself.
CancellationTokenCancelled when the palette is closed while the handler still runs; what such a handler returns afterwards is ignored, so a late page or prompt never reopens it.

A prompt

BaletteCmd.New("Rename project…")
    .Shortcut("F2")
    .Handler(_ => Task.FromResult(BaletteCommandResult.Prompt(
        "New project name",
        ctx =>
        {
            var name = ctx.PromptValue!.Trim();
            if (name == "admin")
            {
                // Expected, so not an exception: shown, and the prompt stays for a correction.
                return Task.FromResult(BaletteCommandResult.Error("“admin” is reserved."));
            }

            state.Rename(name);
            return Task.FromResult(BaletteCommandResult.Toast($"Renamed to {name}"));
        },
        // Null for a value Enter may submit, the message to show otherwise.
        validate: value => value.Trim().Length == 0 ? "A project needs a name." : null,
        placeholder: "Project name…",
        initialValue: state.ProjectName)))

The search box becomes the text field: Enter submits and Esc goes back. Enter on a value the validator refuses shows and announces its message and marks the box aria-invalid; from then on the message follows the text as it is corrected. A check that needs a server belongs in onSubmit, which answers with Error to keep the prompt open.

A multi-select page

BaletteCmd.New("Set labels…")
    .MultiSelect()
    .ChildrenPlaceholder("Toggle labels, Ctrl+Enter to apply…")
    .Children(
        BaletteCmd.New("bug").Id("label:bug"),
        BaletteCmd.New("enhancement").Id("label:enhancement"))
    // Runs on Ctrl+Enter, with the checked rows.
    .Handler(ctx =>
    {
        state.SetLabels(ctx.SelectedCommands.Select(c => c.Title));
        return Task.FromResult(BaletteCommandResult.Toast(ctx.SelectedCommands.Count == 1 ? "1 label applied" : $"{ctx.SelectedCommands.Count} labels applied"));
    })

Enter, a click or Space (on an empty box) toggles a row, and Ctrl Enter (⌘ ↩) runs the page's handler with the checked commands. A page a handler returns works the same way - Create webhook… asks for an address first, then answers with one:

BaletteCmd.New("Create webhook…").Handler(_ => Task.FromResult(BaletteCommandResult.Prompt(
    "Payload URL",
    address => Task.FromResult(BaletteCommandResult.Page(
        "Events to send",
        [.. events.Select(e => BaletteCmd.New(e).Id($"event:{e}").Build())],
        placeholder: "Check events, Ctrl+Enter to create…",
        multiSelect: true,
        onSubmit: picked => Task.FromResult(picked.SelectedCommands.Count == 0
            ? BaletteCommandResult.Error("Pick at least one event.")
            : BaletteCommandResult.Toast($"Webhook to {address.PromptValue} created")))),
    validate: value => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == "https" ? null : "Enter an https:// address.",
    initialValue: "https://")))

Lazy, searching and ad-hoc pages

The provider of a lazy page runs each time the page opens, with a context whose Services come from the user's scope - which is how a real application would reach its API client from here. A searching page asks a source for every query instead of downloading everything up front, and a handler can answer with a page whose list it decided when it ran:

// Loaded each time the page opens.
BaletteCmd.New("Assign to…")
    .Children(async (ctx, ct) =>
    {
        var people = await ctx.GetRequiredService<PeopleClient>().GetAllAsync(ct);
        return people.Select(p => BaletteCmd.New(p.Name).Subtitle(p.Role).Build()).ToList();
    }, placeholder: "Pick an assignee…")

// Asked for every query typed on the page (minQueryLength is 0 here, so also when it opens).
BaletteCmd.New("Find a person…")
    .ChildrenPlaceholder("Search the directory…")
    .Source("Directory", async (query, ct) =>
    {
        var people = await directory.SearchAsync(query, take: 20, ct);
        return people.Select(p => BaletteCmd.New(p.Name).Subtitle(p.Role).ExcludeFromHistory().Build()).ToList();
    })

// Decided by the handler when it runs; these rows are not registered anywhere.
BaletteCmd.New("Export…").Handler(_ => Task.FromResult(BaletteCommandResult.Page("Export format",
[
    BaletteCmd.Action("CSV", ExportCsv).Subtitle("Comma separated values").Build(),
    BaletteCmd.Action("PDF", ExportPdf).Disabled(true, "Requires the Pro plan").Build(),
])))
OpenAsync(pageCommandId: ...) opens straight inside a registered command's page, and BaletteTrigger takes the same PageCommandId: a "Change theme" button can be a trigger that lands on the theme options rather than on the root list.

Long-running commands

A handler still running after 150 ms shows the palette busy: the spinner replaces the search icon, the list is aria-busy, the running row carries data-running, and "Working…" (BaletteStrings.Running) is announced. A quick handler never flickers. A second Enter is ignored while it runs, and Esc closes the palette and cancels the handler's token; what it returns afterwards is dropped. Run Generate report… and press Esc halfway.

BaletteCmd.New("Generate report…").Handler(async ctx =>
{
    // Esc closes the palette and cancels this token; the handler simply stops.
    await reports.GenerateAsync(ctx.CancellationToken);
    return BaletteCommandResult.Toast("Report ready", keepOpen: true);
})

When something fails

An exception thrown by a handler - or by the loader of a page's children - raises IBaletteService.CommandFailed, is logged through ILogger<Balette>, 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. The message is the localized, generic BaletteStrings.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 subscriber picks another:

Palette.CommandFailed += (_, e) =>
{
    if (e.Exception is ValidationException)
    {
        e.Message = e.Exception.Message; // written for users
    }

    e.Handled = true; // reported by the app: not logged, not rethrown
};
  • Handled = true says the subscriber reported it: the palette does not log it, and ExecuteAsync does not rethrow it. This page records its own commands' failures below, so it sets it.
  • Message = "" shows nothing. A failure in the palette's own UI - a row chosen by keyboard or mouse, a global shortcut - is never rethrown, so it can neither end a Blazor Server circuit nor vanish into the console; Palette.ExecuteAsync(id) rethrows an unhandled one to the code that called it.
  • 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.

What this page's CommandFailed subscriber saw, newest first:

Run Sync with server, Publish release or Recent deployments….

Recents, pins and the action panel

On the empty query of the root page, pinned commands are listed first, in the order they were pinned, and the most recently used ones next - up to MaxRecents (5). Every run is recorded unless the command has ExcludeFromHistory, and the counts feed frecency.

Tab - or → on an empty box, or a right click - opens the action panel of the active row: its own Actions, 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. Ctrl Enter runs the first secondary action directly - on a link without actions it opens the link in a new tab, as GitHub's palette does - Ctrl Shift P pins or unpins, and Shift Delete forgets.

Pinned

Loads once the page is interactive.

Recent

Read from BaletteHistory, the scoped service behind the palette's recents, pins and frecency, which an app can inject too: Pinned(), Recents(max), Get(id), Frecency(id), TogglePinAsync, RemoveAsync, ClearAsync and a Changed event.

// Listed first in the row's action panel (Tab), before Pin to top and Remove from recents; Ctrl+Enter runs the first.
BaletteCmd.New(person.Name)
    .Id($"person:{person.Id}")
    .Actions(
        BaletteCmd.Action("Copy e-mail", _ => Task.FromResult(BaletteCommandResult.Toast($"Copied {person.Email}"))).Build(),
        BaletteCmd.Action("Mention in issue", _ => Task.FromResult(BaletteCommandResult.Toast($"Mentioned {person.Name}"))).Build())

// The history behind the recents and the pins, injected like the service.
await History.EnsureLoadedAsync();
IReadOnlyList<string> pinned = History.Pinned();
IReadOnlyList<string> recent = History.Recents(5);
await History.TogglePinAsync("toggle:wordwrap");
History.Changed += Refresh;
// ... and when the page goes, since the history outlives it:
History.Changed -= Refresh;

History is ids, counts and times - never queries - and is kept by the default store, BaletteBrowserStorageHistoryStore, in localStorage under HistoryStorageKey (bit-balette.history), capped at MaxHistoryEntries (200), and validated when it is read back. To keep it elsewhere - per user on the server, or nowhere - plug in a store; turn it off with options.EnableHistory = false, or on one palette with EnableHistory="false", as the inline palette on Registering commands does.

builder.Services.AddBitBaletteHistoryStore<ServerHistoryStore>(); // per user, on your server
builder.Services.AddBitBaletteInMemoryHistoryStore();            // for the lifetime of the scope only

public sealed class ServerHistoryStore(HttpClient http) : IBaletteHistoryStore
{
    public async ValueTask<IDictionary<string, BaletteCommandUsage>> LoadAsync(CancellationToken ct = default)
        => await http.GetFromJsonAsync<Dictionary<string, BaletteCommandUsage>>("api/palette-history", ct)
           ?? new Dictionary<string, BaletteCommandUsage>();

    public async ValueTask SaveAsync(IReadOnlyDictionary<string, BaletteCommandUsage> usage, CancellationToken ct = default)
        => (await http.PutAsJsonAsync("api/palette-history", usage, ct)).EnsureSuccessStatusCode();
}
An unhandled error has occurred. Reload 🗙