Let's Build Composable Keyboard Navigation Together
Let's Build Composable Keyboard Navigation Together#
Prerequisites: We'll assume you're comfortable with React and TypeScript. We'll introduce Entity-Component-System (ECS) concepts as we go - no prior game dev experience needed!
Time to read: ~15 minutes
What we'll learn: How to build keyboard navigation using composable plugins that don't know about each other
The Problem We're Solving#
We're building a complex UI, and we need keyboard shortcuts everywhere. Our text editor needs Cmd+B for bold, our cards need arrow keys for navigation, our buttons need Enter to activate.
We could write one giant keyboard handler that knows about every component. But we've been down that road before - it becomes a tangled mess the moment we need context-sensitive shortcuts or want to test things in isolation. Every time we add a component, we're editing that massive switch statement. Every time a shortcut conflicts, we're debugging spaghetti code.
Let's try something different. We'll build a system where components declare what they need, and a plugin wires everything together automatically. No tight coupling, no spaghetti code, and every piece testable in isolation.
What We're Building#
We'll create three interactive cards, each with different keyboard shortcuts. When we focus a card, its shortcuts become active. Press ↑/↓ to navigate between cards, then try each card's unique actions.
By the end, we'll understand how four small building blocks compose into a working keyboard system - without any of them knowing about the others.
Our Approach: Entities, Components, and Plugins#
We're borrowing a pattern from game development called Entity-Component-System (ECS):
- Entity = A unique identifier for a thing in the system, not a class or instance
- Component = Data attached to an entity via a component type key
- Plugin = Behavior that queries entities with specific component combinations and reacts to changes
The mapping to React:
React → ECS
─────────────────────────────────────
Component instance → Entity (just a UID)
Props/state shape → Component (data attached to UID)
Context + useEffect → Plugin (reactive behavior)
useState → Atom (Jotai reactive state)The key insight: Components are just data. Plugins add behavior by querying for that data. Nothing is tightly coupled.
Let's see this in practice.
Try It Out First#
Before diving into theory, let's play with what we're building:
Todo Item
Note
Task
Click a card to focus it, then use:
- ↑/↓ to navigate
- X to delete
- D to duplicate
- E to edit
- Tab/Shift+Tab for browser native navigation
Watch how the demo responds. Notice that only the focused card's shortcuts work - the others are "dormant" until focused.
Now let's understand how we built this.
Our Four Building Blocks#
Let's break down our keyboard system into four composable pieces.
Block 1: Making Things Focusable#
First, we need to mark which entities can receive focus. We'll create a CFocusable component:
export class CFocusable extends World.Component("focusable")<
CFocusable,
{
handler: Handler<ExitDirection>;
hasDirectFocusAtom: Atom<boolean>;
}
>() {
}What this gives us:
hasDirectFocusAtom: A reactive boolean that'struewhen this specific entity has focushandler: Called when focus enters from a direction (we'll use this later for spatial nav)
Let's use it:
const buttonUID = uid(null, null, "my-button");
world.addEntity(buttonUID, ButtonEntity, {
focusable: CFocusable.of({
hasDirectFocusAtom: atom(false),
handler: () => handled`button focused`,
}),
});Notice: Our component doesn't know HOW focus works, just that it CAN be focused. It's pure data.
Block 2: Tracking Which Entity Has Focus#
We have focusable entities, but we need to track which one currently has focus. That's a singleton concern - only one entity can have focus at a time.
We'll create a "Unique" (a singleton component):
export class UCurrentFocus extends World.Unique("currentFocus")<
UCurrentFocus,
{ activeFocusAtom: PrimitiveAtom<UID | null> }
>() {}What this gives us:
activeFocusAtom: Holds the UID of whichever entity currently has focus (ornull)
How it connects:
// When we focus a card:
const focusUnique = world.getUniqueOrThrow(UCurrentFocus);
world.store.set(focusUnique.activeFocusAtom, cardUID);
// Anywhere else in our app:
const focusedEntityUID = world.store.get(focusUnique.activeFocusAtom);Notice: CFocusable and UCurrentFocus don't import each other. They communicate through atoms. The CFocusable Plugin (which we'll see soon) is what wires them together.
Block 3: Declaring Actions#
Now we need entities to declare what keyboard actions they support:
export type AnyAction = {
label: string;
defaultKeybinding: DefaultKeyCombo;
description?: string;
icon?: any;
self?: boolean;
hideFromLastPressed?: boolean;
};
type AnyBindables = Record<string, AnyAction>;
export type ActionEvent = { target: UID };
export namespace CActions {
export type Bindings<T extends AnyBindables> = {
[P in keyof T]: Handler<ActionEvent> | Falsey;
};
}
export type ActionBindings<T extends AnyBindables = AnyBindables> = {
bindingSource: DevString;
registryKey: ActionRegistryKey<T>;
bindingsAtom: Atom<CActions.Bindings<T>>;
};
export class ActionRegistryKey<T extends AnyBindables = AnyBindables> {
constructor(
public readonly key: string,
public readonly meta: { source: DevString; sectionName: string },
public readonly bindables: T,
) {}
}
export class CActions extends World.Component("actions")<CActions, ActionBindings[]>() {
static bind<T extends AnyBindables>(key: ActionBindings<T>) {
return CActions.of([key as ActionBindings]);
}
static merge(...bindings: Array<ActionBindings | ActionBindings[]>) {
const out: ActionBindings[] = [];
for (const b of bindings) {
if (Array.isArray(b)) {
out.push(...b);
} else {
out.push(b);
}
}
return CActions.of(out);
}
static defineActions<T extends AnyBindables>(
key: string,
meta: { source: DevString; sectionName: string },
actions: T,
): ActionRegistryKey<T> {
return new ActionRegistryKey(key, meta, actions);
}
}What this gives us:
- A way to define available actions (
defineActions) - A way to bind handlers to those actions per entity
- Actions are just metadata: label, key binding, description
Let's define some actions for our cards:
const CardActions = CActions.defineActions(
"card-actions",
{ source: dev`Card actions`, sectionName: "Card Actions" },
{
delete: {
label: "Delete Card",
defaultKeybinding: "X" as const,
description: "Remove this card",
},
edit: {
label: "Edit Card",
defaultKeybinding: "E" as const,
description: "Edit card content",
},
},
);Now attach handlers to a specific card entity:
world.addEntity(cardUID, CardEntity, {
actions: CActions.bind({
bindingSource: dev`Card 1 actions`,
registryKey: CardActions,
bindingsAtom: atom({
delete: () => {
alert("Deleted!");
return handled`delete`;
},
edit: () => {
alert("Editing!");
return handled`edit`;
},
}),
}),
});Notice: We defined the action schema once, then bound different handlers per entity. One card might delete, another might archive. Same action definition, different behavior.
Block 4: Wiring It All Together - ActionsPlugin#
Here's where the magic happens. We need something that:
- Listens for keyboard events
- Finds the currently focused entity
- Matches keys to actions
- Executes the handler
That's what our ActionsPlugin does:
export const ActionsPlugin = World.definePlugin({
name: dev`ActionsPlugin`,
setup: (build) => {
const { store } = build;
// Track the currently focused entity
const currentFocusAtom = atom((get) =>
pipeNonNull(get(build.getUniqueAtom(UCurrentFocus)), (a) => get(a.activeFocusAtom)),
);
const rootUIDAtom = atom<UID | null>(null);
const currentDispatchSpotAtom = atom((get) => get(currentFocusAtom) ?? get(rootUIDAtom));
const handleOnce = new WeakSet<KeyboardEvent>();
build.addUnique(UKeydownRootHandler, {
handler(reason, keyboardEvent) {
if (handleOnce.has(keyboardEvent)) return Outcome.Passthrough;
handleOnce.add(keyboardEvent);
if (keyboardEvent.defaultPrevented) return Outcome.Passthrough;
const world = store.get(build.worldAtom);
if (!world) return Outcome.Passthrough;
const dispatchFromUID = store.get(currentDispatchSpotAtom);
if (!dispatchFromUID) return Outcome.Passthrough;
// Walk up the parent chain looking for keydown handlers
const result = CParent.dispatch(
dev`keydown from root`.because(reason),
world,
dispatchFromUID,
CKeydownHandler,
reason,
keyboardEvent,
);
// Prevent default browser behavior when we handle the key
if (result !== Outcome.Passthrough) {
keyboardEvent.preventDefault();
}
return result;
},
rootUIDAtom,
});Here's what happens when we press a key:
User presses "X"
↓
ActionsPlugin.UKeydownRootHandler receives event
↓
Query: Which entity has focus? (from UCurrentFocus)
↓
Walk up parent chain: Does this entity have CKeydownHandler?
↓
Match key "X" to action "delete"
↓
Call the handler we bound earlier
↓
preventDefault() so browser doesn't scrollThe beautiful part? None of these components import each other. The plugin queries the world: "Give me the focused entity. Does it have CActions? Great, wire up keyboard handling for it."
// Provide keydown handler for entities with CActions
build.onEntityCreated(
{
requires: [CActions],
provides: [CKeydownHandler],
},
(uid, { actions }) => {
const combinedCombosAtom = atom((get) => {
type ComboData = {
actionKey: string;
handler: (reason: DevString, event: ActionEvent) => Outcome;
} & AnyAction;
const combosMap = new Map<string, ComboData[]>();
for (const actionSet of actions) {
const resolvedBindings = get(actionSet.bindingsAtom);
for (const [actionKey, maybeHandler] of Object.entries(resolvedBindings)) {
if (!maybeHandler) continue;
const bindable = actionSet.registryKey.bindables[actionKey];
if (!bindable) continue;
const defaultKey = bindable.defaultKeybinding;
const combo = normalizedKeyCombo(defaultKey, ENV_KEYBOARD_KIND).normalized;
const comboData: ComboData = {
actionKey,
handler: maybeHandler,
...bindable,
};
const list = combosMap.get(combo);
if (!list) {
combosMap.set(combo, [comboData]);
} else {
list.push(comboData);
}
}
}
return combosMap;
});
const keydownHandler = CKeydownHandler.of({
handler(reason, event) {
// Omit shift for letter keys so "Shift+X" matches "X"
const combos = addModifiersToKeyCombo(ENV_KEYBOARD_KIND, event, true);
if (event.defaultPrevented) return Outcome.Passthrough;
const combosMap = store.get(combinedCombosAtom);
for (const combo of combos) {
const comboDatas = combosMap.get(combo.normalized);
if (!comboDatas) continue;
for (const comboData of comboDatas) {
const outcome = comboData.handler(dev`Key combo pressed: ${combo.normalized}`.because(reason), {
target: uid,
});
if (outcome !== Outcome.Passthrough) {
return outcome;
}
}
}
return Outcome.Passthrough;
},
});
return { keydownHandler };
},
);This is the actual per-entity handler creation. When we add an entity with CActions, the plugin automatically:
- Reads all action definitions
- Normalizes key combos (so "X" and "Shift-X" both match)
- Creates a
CKeydownHandlerthat matches keys to handlers - Plugs it into the event system
We don't call any of this ourselves. It Just Works™.
What We Learned#
Let's step back and appreciate what we built:
✅ We Can Test Everything In Isolation#
Want to test if "X" triggers delete? No React needed:
const world = createTestWorld();
const cardUID = addCardEntity(world, {
onDelete: mockFn,
});
// Simulate focus
world.store.set(focusAtom, cardUID);
// Simulate keypress
rootHandler.handler(dev`test`, { key: "x" });
expect(mockFn).toHaveBeenCalled();✅ Components Are Composable#
A simple button might only have CFocusable. A rich text editor adds CActions with 50 shortcuts. A card adds both plus CSelectable. Mix and match:
// Simple button
world.addEntity(uid, SimpleButton, {
focusable: CFocusable.of({...}),
});
// Rich editor
world.addEntity(uid, RichEditor, {
focusable: CFocusable.of({...}),
actions: CActions.merge(
TextFormattingActions, // Bold, italic, etc.
BlockActions, // Lists, headings
ClipboardActions, // Cut, copy, paste
),
});✅ Everything Is Observable#
All state lives in Jotai atoms. DevTools can show us:
- Which entity has focus right now
- What actions are available
- When each action was last pressed
✅ Nothing Is Tightly Coupled#
Look at what we didn't do:
- ❌ Import KeyboardManager in every component
- ❌ Call registerShortcut() imperatively
- ❌ Have components know about each other
- ❌ Write glue code to connect pieces
Instead:
- ✅ Components declare data ("I can be focused", "I have actions")
- ✅ Plugins react to component presence ("Oh, you have both? Let me wire you up")
- ✅ Everything communicates through atoms
- ✅ Adding a new entity requires zero changes to existing code
When Should We Use This Approach?#
Let's be honest about trade-offs.
This pattern shines when:
- ✅ We're already using ECS architecture in our app (like we do in Phosphor)
- ✅ We have complex nesting and need context-sensitive shortcuts
- ✅ We want every piece testable in isolation
- ✅ Our app has 10+ different shortcut contexts
- ✅ We value composition over simplicity
Consider simpler alternatives when:
- ❌ We're building a small app with <20 shortcuts
- ❌ We want minimal bundle size (this adds ~30KB with Jotai + ECS)
- ❌ Our team isn't familiar with reactive state patterns
- ❌ We just need basic "hotkey → function" mapping
Simpler Alternatives We Considered#
| Approach | Bundle Size | Learning Curve | Test Isolation | Context-Sensitive |
|---|---|---|---|---|
| ECS (Ours) | ~30KB | High | Excellent | Excellent |
| tinykeys | 2KB | Low | Good | Manual |
| React Context | 0KB | Medium | Medium | Good |
| Mousetrap | 8KB | Low | Poor | Manual |
For our use case (complex editor with nested contexts), the composition benefits outweigh the complexity cost. For most apps, a 2KB library like tinykeys is probably the right call.
Tracing a Keypress Together#
Let's walk through exactly what happens when we press "X" to delete a card. This demystifies the "magic":
📍 Step 1: DOM Event (keyboard-demo.entrypoint.tsx:29)
document.addEventListener('keydown', ...)
Event fires with event.key = "x"
↓
📍 Step 2: Root Handler (ActionsPlugin.ts:33-42)
UKeydownRootHandler.handler() receives event
Check currentDispatchSpotAtom: Is anything focused?
Result: Card 2 has focus
↓
📍 Step 3: Parent Walk (ActionsPlugin.ts:44-55)
CParent.dispatch() walks up the entity tree
Current: Card 2 → Does it have CKeydownHandler? YES ✓
↓
📍 Step 4: Key Normalization (ActionsPlugin.ts:105-107)
addModifiersToKeyCombo("x", event, omitShift=true)
"x" → "X" (uppercase)
No modifiers, final combo: "X"
↓
📍 Step 5: Action Lookup (ActionsPlugin.ts:110-115)
combosMap.get("X") → [{action: "delete", handler: fn}]
Call handler(dev`Key combo`, {target: card2UID})
↓
📍 Step 6: Our Handler (createKeyboardDemo.ts:83)
onDelete() runs
alert("Deleted Card 2!")
Returns: handled`delete`
↓
📍 Step 7: Prevent Default (ActionsPlugin.ts:50-52)
outcome !== Passthrough, so:
event.preventDefault() ← stops browser scroll
Return "handled" to stop propagationKey insight: Notice how information flows through atoms and component queries, never through direct imports or method calls. That's the decoupling in action.
What's Next?#
Now that we understand composable keyboard navigation, we can:
- Add spatial navigation (arrow keys navigate a 2D grid)
- Build focus trapping for modals
- Create a command palette with searchable actions
- Support user-customizable keybindings
The pattern scales because we're composing data, not coupling objects.
Reflection#
We started with a problem: keyboard shortcuts without spaghetti code.
We solved it by separating concerns:
CFocusablesays "I can receive focus" (data)CActionssays "I have these shortcuts" (data)ActionsPluginsays "When those exist together, wire them up" (behavior)
No component knows about the others. Add a new shortcut? Update one entity's CActions. Add a new focusable element? Add CFocusable. The plugin handles the rest.
That's the power of Entity-Component-System for UI.