Skip to content

Modes & sources

A mode is a prefix typed at the start of the query - > in VS Code, # on GitHub - that scopes the palette to part of the registry, to its own asynchronous sources, or both. A source is anything that answers a query later: an API, a database, a search index. The palette debounces it, cancels it when the query moves on, pages it, times it out, and merges what it returns.

The modes of this app

PrefixModeListsSources
> Commands
Run any command
commands tagged “command” -
# Issues
Search issues by number or title
only its sources Issues
@ People
Find a teammate
only its sources People
? Help
Keyboard shortcuts and docs
the Help group -
$ Packages
Browse 60 packages, 10 at a time
only its sources Packages

The first four are registered at startup, in options.Modes. $ is this page's own: Palette.RegisterMode added it when the page opened, and disposing the handle it returned takes it away again when you leave. The active mode is shown as a chip next to the breadcrumbs, and on the empty query of the default mode every mode is listed as a hint under Modes, so they can be discovered without reading this page; picking a hint types its prefix.

PropertyWhat it does
PrefixWhat is typed at the start of the query. The longest matching prefix wins, so >> and > can coexist.
Name / DescriptionThe chip, and the hint's title and subtitle.
PlaceholderThe search box's placeholder while the mode is active.
TagsOnly commands carrying one of these tags - > lists those tagged command.
GroupsOnly commands in these groups - ? lists the Help group.
HideRegistryCommandsNo registry commands at all, only the mode's sources - #, @ and $.
SourcesAsked in this mode, instead of the default mode's sources.
ShowHintWhether the mode is listed under Modes; options.ShowModeHints = false drops the whole group.

A mode scopes the registry and the sources; nested commands are never found from a mode.

options.Modes.Add(new BaletteCommandMode
{
    Prefix = ">",
    Name = "Commands",
    Description = "Run any command",
    Placeholder = "Run a command…",
    Tags = ["command"],            // only the commands tagged "command"
});
options.Modes.Add(new BaletteCommandMode { Prefix = "?", Name = "Help", Groups = ["Help"] });

// At runtime, until the handle is disposed: this page's $ mode.
_packagesMode = Palette.RegisterMode(new BaletteCommandMode
{
    Prefix = "$",
    Name = "Packages",
    HideRegistryCommands = true,   // only its sources' rows
    Sources = [packages],
});

The sources

SourceAsked inFromAt mostOrderLatency
Documentation the default mode 2 chars 20 re-ranked with the registry 300 ms
Service status the default mode 1 char 20 its own, as one block 200 ms
Issues # Issues empty box 20 its own, as one block 180 ms
People @ People 1 char 20 re-ranked with the registry 250 ms
Packages $ Packages empty box 10 its own, as one block 200 ms

Re-ranked

With ApplyMatcher the palette scores what a source returns with its own matcher and sorts it in with everything else. The source only has to return candidates, and its rows are highlighted like the rest. People and Documentation work this way.

Ordered

Without it - the default - the source's order is kept and its rows are listed as one block under its name, right for a server that already sorts by relevance. Issues puts open issues first, newest first, and asks on the empty query too (MinQueryLength = 0), so # opens on a list.

Sources in options.Sources are asked in the default mode, and so are the ones registered at runtime with Palette.RegisterSource or resolved from DI with services.AddBitBaletteSource<TSource>() - those belong to the scope and stay registered whichever palette comes and goes. A mode asks its own Sources instead, and a command's page can ask one too (.Source(...), see nested pages). Each search gets a BaletteSourceContext: the ModePrefix, the ParentCommandId of the page that asked, and the user's Services.

// Ordered: the server already sorts by relevance, so its order is kept and its rows are one block.
public sealed class IssueSource(IssueClient issues) : IBaletteSource
{
    public string Name => "Issues";
    public int MinQueryLength => 0;     // asked on the empty query too, so # opens on a list

    public async Task<IReadOnlyList<BaletteCommand>> SearchAsync(
        string query, BaletteSourceContext context, CancellationToken cancellationToken)
    {
        // context.ModePrefix is "#" here, and context.Services the user's scope.
        var found = await issues.SearchAsync(query, openFirst: true, cancellationToken);
        return [.. found.Select(i => BaletteCmd.New($"#{i.Number} {i.Title}").Subtitle(i.State).Build())];
    }
}

Debounced and cancelled, live

Open the palette and type @ada lovelace at your normal speed. The palette waits 150 ms (DebounceMs) after the last keystroke before it asks a source, so most keystrokes never reach one; a search still running when the next one starts is cancelled through its token, so a slow API never shows stale results. A spinner replaces the search icon while any source is pending. Every call that did reach a source is listed here, newest first.

options.DebounceMs = 150;   // the quiet time after the last keystroke before a source is asked

public async Task<IReadOnlyList<BaletteCommand>> SearchAsync(
    string query, BaletteSourceContext context, CancellationToken cancellationToken)
{
    // Cancelled when the next search starts: hand the token to whatever waits, and stale results never show.
    var people = await http.GetFromJsonAsync<Person[]>($"api/people?q={Uri.EscapeDataString(query)}", cancellationToken);
    // An id of its own: two people can share a name, and recents and pins go by the id.
    return [.. people!.Select(p => BaletteCmd.New(p.Name).Id($"person:{p.Email}").Subtitle(p.Role).Build())];
}
Source calls
StartedSourceQueryOutcomeResultsTook
No source has been asked yet.

Paging

A source with more results than it should send at once answers through SearchPageAsync(query, cursor, ...): the first page with a null cursor, each next one with the NextCursor of the page before. A page with a cursor gets a row after the source's results - "Show 50 more…" when the page says TotalCount, "Show more…" when it does not - which loads the next page, appends it without repeating what is listed, and selects its first row. A source that implements only SearchAsync answers one page.

The $ mode pages through 60 packages, 10 at a time, with a BaletteDelegateSource - the ready-made source over a delegate:

options.Modes.Add(new BaletteCommandMode
{
    Prefix = "$",
    Name = "Packages",
    HideRegistryCommands = true,
    Sources =
    [
        new BaletteDelegateSource("Packages", async (query, cursor, context, ct) =>
        {
            var page = await api.SearchPackagesAsync(query, after: cursor, take: 10, ct);
            return new BaletteSourcePage([.. page.Items.Select(ToCommand)], page.NextCursor, page.Total);
        }, minQueryLength: 0, maxResults: 10),
    ],
});

When a source fails

A source that throws, or that has not answered after SourceTimeoutMs (10 s here) - whether or not it honours its token - is logged and leaves a row in place of its results, "Couldn’t search Service status" in the danger colour, which asks it again when chosen. The other sources' results stay: one failing API does not take the whole list with it. A next page that fails keeps the pages already listed, and its row to try again.

This page registered a Service status source in the default mode with Palette.RegisterSource: status lists every service, and a service's name lists that one. Choose how it behaves, then search:

A source that hangs is cancelled through its token when the timeout passes, so the call log above shows it Cancelled while the palette offers to try again.

_status = Palette.RegisterSource(new StatusSource());   // asked in the default mode
// ... and when the page goes:
_status.Dispose();

public sealed class StatusSource : IBaletteSource
{
    public string Name => "Service status";             // its heading, and its retry row's text

    public async Task<IReadOnlyList<BaletteCommand>> SearchAsync(string query, BaletteSourceContext context, CancellationToken ct)
    {
        var services = await api.GetStatusAsync(ct);     // throws, or never answers: a retry row
        return [.. services.Where(s => s.Name.Contains(query)).Select(ToCommand)];
    }
}

Registering them

builder.Services.AddBitBaletteServices(options =>
{
    options.Modes.Add(new BaletteCommandMode
    {
        Prefix = "@",
        Name = "People",
        Description = "Find a teammate",
        Placeholder = "Search people…",
        HideRegistryCommands = true,       // only the source's rows
        Sources = [new PeopleSource()],
    });

    options.Sources.Add(new DocsSource()); // also asked in the default mode
    options.DebounceMs = 150;              // quiet time before a source is asked
    options.SourceTimeoutMs = 10_000;      // 0 waits for ever
});

builder.Services.AddBitBaletteSource<OrdersSource>(); // a default-mode source resolved from DI

public sealed class PeopleSource : IBaletteSource
{
    public string Name => "People";        // the group heading of its results
    public int MinQueryLength => 1;        // 0 also asks on the empty query
    public int MaxResults => 20;
    public bool ApplyMatcher => true;      // re-rank with the palette's matcher

    public async Task<IReadOnlyList<BaletteCommand>> SearchAsync(
        string query, BaletteSourceContext context, CancellationToken cancellationToken)
    {
        var people = await context.Services.GetRequiredService<PeopleClient>()
            .SearchAsync(query, cancellationToken);
        return [.. people.Select(p => BaletteCmd.New(p.Name).Id($"person:{p.Email}").Subtitle(p.Role).Build())];
    }
}

RegisterMode and RegisterSource return a handle that removes what they added. This page's two are registered while it is on screen:

Two ready-made sources cover the common cases: BaletteDelegateSource wraps a delegate - single page or paged - and BaletteStaticSource serves a large in-memory list through the palette's matcher without registering thousands of commands (see Large registry).
An unhandled error has occurred. Reload 🗙