Engineering a command engine
On fuzzy matching, command representation and the architecture of Scoutbar: ranking a match, finding the best alignment, and keeping the engine apart from its interface.
When I built Scoutbar, I wanted integrating a command menu to be a relatively unremarkable engineering task. Install the library, describe the things your application can do, and let the library handle everything else.
I was particularly interested in two problems: how to search for an action without knowing its exact name, and how to represent that action in a way that wasn't excessively coupled to the application consuming it.
The second problem turned out to be considerably more consequential.
Searching for intent
A command menu has a slightly different search problem from a conventional search engine.
Somebody typing cp probably isn't looking for a document containing the word cp. They're trying to create a project, copy a path or change a password.
The simplest mechanism is subsequence matching. Characters must appear in order, but don't necessarily need to be adjacent.
function match(query: string, text: string) {
let cursor = 0;
const positions: number[] = [];
query = query.toLowerCase();
text = text.toLowerCase();
for (let i = 0; i < text.length; i++) {
if (text[i] === query[cursor]) {
positions.push(i);
cursor++;
}
}
return cursor === query.length
? positions
: null;
}
This requires a single traversal of the candidate string. The problem is that it tells us whether something matches, not how well it matches.
Matching cp against Create project and Open company preferences produces two valid results. Their relevance, however, is quite different.
A ranking mechanism can consider where the match begins, how close its characters are to one another, and whether they coincide with word boundaries.
- Copy pathFiles
- Create projectProjects
- Change passwordAccount
- Open company preferencesSettings
But there's an interesting complication. A greedy traversal finds the first valid alignment, not necessarily the best one.
Searching for pro in Preview project might begin at the first P, even though the second P begins a perfect contiguous match.
Finding the best alignment requires evaluating alternatives rather than accepting the first one.
The cost of a better match
One way to formulate this is through dynamic programming.
Let D[i][j] represent the highest-scoring alignment of the first i query characters, with the last character matched at position j in the candidate.
For each matching character, we consider the previous valid positions and choose the alignment with the highest accumulated reward.
score =
character reward
+ word boundary bonus
+ adjacency bonus
- gap penalty
A straightforward implementation requires O(mn²) time, where m is the query length and n is the candidate length.
For scoring rules with linear gap penalties, we can maintain the best preceding score as we traverse the candidate. That reduces the recurrence to O(mn), with O(n) working memory if we only need the final score.
This is the sort of optimisation that matters when the algorithm runs across hundreds or thousands of commands every time somebody enters a character.
Not all search problems warrant an index. Sometimes the more appropriate optimisation is simply making the work performed against each candidate cheaper.
A command is a description of a capability
Scoutbar's API was deliberately data-oriented.
<ScoutBar
actions={({ createScoutAction }) => [
createScoutAction({
label: "Get Started",
description: "Get started with scoutbar",
href: "/",
}),
]}
/>
The consumer describes the action. Scoutbar is responsible for interpreting it.
This creates an interesting architectural boundary. Commands can be constructed independently of their rendering, combined from multiple modules and inspected before anything is mounted.
A command definition could originate from a navigation configuration, an application module or even another programming language.
I quite enjoyed discovering that Scoutbar eventually found its way into the R ecosystem through , an adaptation for applications.
The original API had effectively become a boundary between two programming environments.
For an application with many capabilities, I still find a data-oriented command model incredibly useful.
Configuration versus composition
After releasing Scoutbar, I came across Paco Coursey's .
What I found particularly elegant about its API was that it exposed the constituent parts of a command menu rather than exclusively exposing the finished experience.
<Command>
<Command.Input />
<Command.List>
<Command.Item onSelect={createProject}>
Create project
</Command.Item>
<Command.Item onSelect={openSettings}>
Open settings
</Command.Item>
</Command.List>
</Command>
This changes where much of the complexity resides.
Scoutbar can inspect its action definitions before rendering them. A compositional library needs a mechanism for discovering the items its consumers actually render, maintaining their identity and coordinating them with the search and selection state.
Those items might be conditionally mounted, wrapped in arbitrary components or populated asynchronously.
The compositional API introduces more complexity inside the library, but allows developers considerably more freedom outside it.
Conversely, a data-oriented API gives the library more knowledge of its complete input and can operate on that input independently of the component tree.
I don't necessarily think these approaches need to be mutually exclusive.
If I were building Scoutbar today, I'd separate the command engine from its React presentation.
const engine = createCommandEngine(commands);
engine.search("cp");
engine.execute("create-project");
The finished Scoutbar component could consume that engine. So could an entirely different React component, a terminal or an application-specific integration.
The interesting bit of engineering is ensuring that the search, registration and execution mechanisms don't depend on the particular interface through which they're exposed.
The command menu is only one consumer of the engine.
— Adenekan
