DraftThis article is currently in draft mode

Writing Process - Phosphor Engineering

Macro Expansion (Pass 1)

Context: You are expanding section bullets from bones.md into full prose for draft.md.

Inputs: anchors.md (locked context) + bones.md section + current section ID

Output: Expanded prose for the specified [S#] section with natural transitions

Requirements:

  • Follow anchors.md constraints exactly
  • Maintain technical depth specified in anchors
  • Add smooth transitions between bullet points
  • Include concrete examples where bones mention them
  • Keep section IDs [S#] in draft.md headers
  • No inline tags yet (that's Pass 2)

Style: Technical advisor voice per be-a-technical-advisor.md


Micro Edit (Pass 3)

Context: You are resolving inline annotation tags from draft.md via unified diff

Inputs: anchors.md + draft.md section with inline tags + specific tags to resolve

Output: Unified diff showing exact changes to resolve tags

Requirements:

  • Address each tagged issue precisely
  • Follow tag modifiers ([!] = must-fix, [~] = nice-to-have, [->suggestion])
  • Maintain section structure and flow
  • Don't rewrite untagged content
  • Verify claims with concrete evidence
  • Add examples where [ex] tags appear

Quality Check (Pass 4)

Context: Final audit before publish

Checklist:

  • All [!] tags resolved
  • Evidence ratio met (per anchors.md)
  • Interactive demos working
  • Forbidden phrases removed
  • Success criteria achieved
  • Hook visceral, conclusion actionable
Tera Template Context (Zola data-loc)
{
  "config": {
    "base_url": "/",
    "mode": "build",
    "title": "Phosphor",
    "description": "Things we learned while building Phosphor",
    "languages": {},
    "default_language": "en",
    "generate_feed": true,
    "generate_feeds": true,
    "feed_filenames": [
      "atom.xml"
    ],
    "taxonomies": [],
    "author": null,
    "build_search_index": true,
    "extra": {
      "sections": [
        "Getting Started",
        "Managing Complexity",
        "Moving Quickly",
        "Understanding Quickly",
        "Architecture Patterns",
        "Interactive Demos",
        "Developer Tools",
        "Advanced Topics"
      ],
      "author": "Phosphor",
      "drafts": true
    },
    "markdown": {
      "highlight_code": true,
      "error_on_missing_highlight": false,
      "highlight_theme": "base16-ocean-dark",
      "highlight_themes_css": [],
      "render_emoji": false,
      "external_links_class": null,
      "external_links_target_blank": false,
      "external_links_no_follow": false,
      "external_links_no_referrer": false,
      "smart_punctuation": false,
      "definition_list": false,
      "bottom_footnotes": false,
      "extra_syntaxes_and_themes": [],
      "lazy_async_image": false,
      "insert_anchor_links": "none",
      "github_alerts": false
    },
    "search": {
      "index_format": "elasticlunr_javascript"
    },
    "generate_sitemap": true,
    "generate_robots_txt": true,
    "exclude_paginated_pages_in_sitemap": "none"
  },
  "current_path": "/incantations/",
  "current_url": "/incantations/",
  "lang": "en",
  "page": {
    "relative_path": "incantations.md",
    "colocated_path": null,
    "content": "

Writing Process - Phosphor Engineering

\n

Macro Expansion (Pass 1)

\n

Context: You are expanding section bullets from bones.md into full prose for draft.md.

\n

Inputs: anchors.md (locked context) + bones.md section + current section ID

\n

Output: Expanded prose for the specified [S#] section with natural transitions

\n

Requirements:

\n
    \n
  • Follow anchors.md constraints exactly
  • \n
  • Maintain technical depth specified in anchors
  • \n
  • Add smooth transitions between bullet points
  • \n
  • Include concrete examples where bones mention them
  • \n
  • Keep section IDs [S#] in draft.md headers
  • \n
  • No inline tags yet (that's Pass 2)
  • \n
\n

Style: Technical advisor voice per be-a-technical-advisor.md

\n
\n

Micro Edit (Pass 3)

\n

Context: You are resolving inline annotation tags from draft.md via unified diff

\n

Inputs: anchors.md + draft.md section with inline tags + specific tags to resolve

\n

Output: Unified diff showing exact changes to resolve tags

\n

Requirements:

\n
    \n
  • Address each tagged issue precisely
  • \n
  • Follow tag modifiers ([!] = must-fix, [~] = nice-to-have, [->suggestion])
  • \n
  • Maintain section structure and flow
  • \n
  • Don't rewrite untagged content
  • \n
  • Verify claims with concrete evidence
  • \n
  • Add examples where [ex] tags appear
  • \n
\n
\n

Quality Check (Pass 4)

\n

Context: Final audit before publish

\n

Checklist:

\n
    \n
  • \nAll [!] tags resolved
  • \n
  • \nEvidence ratio met (per anchors.md)
  • \n
  • \nInteractive demos working
  • \n
  • \nForbidden phrases removed
  • \n
  • \nSuccess criteria achieved
  • \n
  • \nHook visceral, conclusion actionable
  • \n
\n", "permalink": "/incantations/", "slug": "incantations", "ancestors": [ "_index.md" ], "title": "Incantations", "description": null, "updated": null, "date": "2025-10-20", "year": 2025, "month": 10, "day": 20, "taxonomies": {}, "authors": [], "extra": { "nav_section": "Advanced Topics", "nav_order": 1 }, "path": "/incantations/", "components": [ "incantations" ], "summary": null, "toc": [ { "level": 1, "id": "writing-process-phosphor-engineering", "permalink": "/incantations/#writing-process-phosphor-engineering", "title": "Writing Process - Phosphor Engineering ⋅", "children": [ { "level": 2, "id": "macro-expansion-pass-1", "permalink": "/incantations/#macro-expansion-pass-1", "title": "Macro Expansion (Pass 1) ⋅", "children": [] }, { "level": 2, "id": "micro-edit-pass-3", "permalink": "/incantations/#micro-edit-pass-3", "title": "Micro Edit (Pass 3) ⋅", "children": [] }, { "level": 2, "id": "quality-check-pass-4", "permalink": "/incantations/#quality-check-pass-4", "title": "Quality Check (Pass 4) ⋅", "children": [] } ] } ], "word_count": 230, "reading_time": 2, "assets": [], "draft": true, "lang": "en", "lower": { "relative_path": "click-to-source.md", "colocated_path": null, "content": "

Click to Source: Embedding Runtime Locations

\n\n\n
\n \n Anchors\n \n \n
- Anchors
\n
\n\n

Build-time transforms inject source locations into runtime code. Alt+Click any element to jump to its source file.

\n

Try It

\n
\nHold Alt and hover over any button, then click to view its source. The mock console shows what file would open, and the viewer displays the source code.\n
\n\n

React Component Locations

\n

Transform $ prop shorthand into data-loc attributes:

\n
\n \n
\n
        if (enableReact$Loc && path.endsWith(\".tsx\")) {\n          for (const match of code.matchAll(CLASSNAME_$_RE)) {\n            const index = match.index!;\n            const [_, pre, post] = match;\n            const { line, column } = indexToLineAndColumn(code, index + pre.length);\n\n            const link = `${path.slice(inCodebase.index + IN_CODEBASE_SLICE)}:${line}:${column}`;\n            let dataAttrs = `data-loc=${JSON.stringify(link)}`;\n            if (pre.startsWith(\"<\")) {\n              dataAttrs = `${dataAttrs} data-name=${JSON.stringify(pre.split(\" \")[0].slice(1).trim())}`;\n            }\n\n            if (post === \"=\") {\n              string.overwrite(index + pre.length, index + _.length - post.length, `${dataAttrs} className`);\n            } else {\n              string.overwrite(index + pre.length, index + _.length - post.length, dataAttrs);\n            }\n          }\n        }
\n
\n
\n
  // Input:\n  <div $="card">Content</div>\n\n  // Output (at build):\n  <div data-loc="components/Card.tsx:26:7" className="card">Content</div>\n
\n

Runtime handler walks React fiber tree and opens the file:

\n
\n \n
\n
const getPath = (fiber: Fiber, element: HTMLElement | undefined): string | undefined => {\n  // First check for data-loc attribute if element is provided\n  if (element?.dataset.loc) {\n    return element.dataset.loc;\n  }\n\n  const source = fiber._debugSource ?? fiber._debugInfo ?? fiber._source;\n\n  if (!source) return undefined;\n\n  const { fileName, lineNumber = 1, columnNumber = 1 } = source;\n  return `${fileName}:${lineNumber}:${columnNumber}`;\n};\n\nconst getLayersForElement = (element: HTMLElement, root: string): ComponentLayer[] => {\n  let instance = getReactInstanceForElement(element);\n  const layers: ComponentLayer[] = [];\n\n  while (instance) {\n    // Try to find the DOM element for this fiber to check for data-loc\n    const fiberElement = instance.stateNode instanceof HTMLElement ? instance.stateNode : undefined;\n    const path = getPath(instance, fiberElement);\n    if (path) {\n      const name =\n        typeof instance.type === \"string\"\n          ? instance.type\n          : (instance.type.displayName ?? instance.type.name ?? instance.type.render?.name ?? \"undefined\");\n      layers.push({ name, path: path.replace(`${root}/`, \"\") });\n    }\n    instance = instance._debugOwner ?? undefined;\n  }\n  return layers;\n};
\n
\n
\n

DevString Locations

\n

Tagged templates automatically capture call-site locations:

\n
\n \n
\n
        if (enableDevLoc) {\n          for (const match of code.matchAll(DEV_RE)) {\n            const index = match.index!;\n            const { line, column } = indexToLineAndColumn(code, index);\n            const [_, fn, message] = match;\n            const link = `${path.slice(inCodebase.index + IN_CODEBASE_SLICE)}:${line}:${column}`;\n            string.overwrite(index, index + _.length, `${fn}\\`${message}\\`.ctx({ loc: ${JSON.stringify(link)} })`);\n          }\n        }
\n
\n
\n
// Input:\nhandler(dev`User pressed X`);\n\n// Output (at build):\nhandler(dev`User pressed X`.ctx({ loc: "Card.tsx:83:12" }));\n
\n

Usage:

\n
function deleteCard(reason: DevString) {\n  console.log("Called from:", reason.toJSON().context.loc);\n}\n\ndeleteCard(dev`User clicked delete`);\n// Automatically knows source location\n
\n

DevStrings compose with .because() to build audit trails:

\n
const rootEvent = dev`keydown from root`;\nhandler(rootEvent.because(dev`Looking for action handler`));\n// Creates chain: "keydown from root → Looking for action handler"\n
\n

Editor Integration

\n

Local HTTP endpoint opens files:

\n
\n \n
\n
let lastOpenedFile: string | null = null;\n/**\n * uses our launch-editor endpoint to open the file in the dev's editor\n * this has been set up as a vite plugin.\n */\nexport const openInDevEditor = (loc: string) => {\n  if (lastOpenedFile === loc) return;\n  lastOpenedFile = loc;\n  setTimeout(() => (lastOpenedFile = null), 500);\n  void fetch(`http://localhost:5090/__open-in-editor?file=${loc}`).catch((error) => {\n    console.error(\"Failed to open in editor\", error);\n  });\n};
\n
\n
\n
openInDevEditor("Card.tsx:26:7");\n  ↓\nfetch("http://localhost:5090/__open-in-editor?file=Card.tsx:26:7");\n  ↓\n// Editor opens at that line\n
\n

Setup

\n

Build plugin:

\n
import { bunDevStringAndReact$ClassNameLoc } from "./bun-dev-and-react-$-className-loc.mts";\n\nawait Bun.build({\n  plugins: [\n    bunDevStringAndReact$ClassNameLoc({\n      enableReact$Loc: true,\n      enableDevLoc: true,\n    }),\n  ],\n});\n
\n

Runtime:

\n
import { initClickToSource } from "./click-to-source.client.ts";\n\nif (import.meta.env.DEV) {\n  initClickToSource();\n}\n
\n", "permalink": "/click-to-source/", "slug": "click-to-source", "ancestors": [ "_index.md" ], "title": "Click to Source: Embedding Runtime Locations", "description": null, "updated": null, "date": "2025-10-20", "year": 2025, "month": 10, "day": 20, "taxonomies": {}, "authors": [], "extra": { "nav_section": "Moving Quickly", "nav_order": 1 }, "path": "/click-to-source/", "components": [ "click-to-source" ], "summary": null, "toc": [ { "level": 1, "id": "click-to-source-embedding-runtime-locations", "permalink": "/click-to-source/#click-to-source-embedding-runtime-locations", "title": "Click to Source: Embedding Runtime Locations ⋅", "children": [ { "level": 2, "id": "try-it", "permalink": "/click-to-source/#try-it", "title": "Try It ⋅", "children": [] }, { "level": 2, "id": "react-component-locations", "permalink": "/click-to-source/#react-component-locations", "title": "React Component Locations ⋅", "children": [] }, { "level": 2, "id": "devstring-locations", "permalink": "/click-to-source/#devstring-locations", "title": "DevString Locations ⋅", "children": [] }, { "level": 2, "id": "editor-integration", "permalink": "/click-to-source/#editor-integration", "title": "Editor Integration ⋅", "children": [] }, { "level": 2, "id": "setup", "permalink": "/click-to-source/#setup", "title": "Setup ⋅", "children": [] } ] } ], "word_count": 255, "reading_time": 2, "assets": [], "draft": true, "lang": "en", "lower": null, "higher": null, "translations": [], "backlinks": [] }, "higher": { "relative_path": "keyboard-navigation-demo.md", "colocated_path": null, "content": "

Let's Build Composable Keyboard Navigation Together

\n
\n

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!

\n

Time to read: ~15 minutes
\nWhat we'll learn: How to build keyboard navigation using composable plugins that don't know about each other

\n
\n

The Problem We're Solving

\n

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.

\n

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.

\n

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.

\n

What We're Building

\n

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.

\n

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.

\n

Our Approach: Entities, Components, and Plugins

\n

We're borrowing a pattern from game development called Entity-Component-System (ECS):

\n
    \n
  • Entity = A unique identifier for a thing in the system, not a class or instance
  • \n
  • Component = Data attached to an entity via a component type key
  • \n
  • Plugin = Behavior that queries entities with specific component combinations and reacts to changes
  • \n
\n

The mapping to React:

\n
ReactECS\n─────────────────────────────────────\nComponent instanceEntity (just a UID)\nProps/state shapeComponent (data attached to UID)\nContext + useEffectPlugin (reactive behavior)\nuseStateAtom (Jotai reactive state)\n
\n

The key insight: Components are just data. Plugins add behavior by querying for that data. Nothing is tightly coupled.

\n

Let's see this in practice.

\n

Try It Out First

\n

Before diving into theory, let's play with what we're building:

\n\n
\n\n

Watch how the demo responds. Notice that only the focused card's shortcuts work - the others are \"dormant\" until focused.

\n

Now let's understand how we built this.

\n

Our Four Building Blocks

\n

Let's break down our keyboard system into four composable pieces.

\n

Block 1: Making Things Focusable

\n

First, we need to mark which entities can receive focus. We'll create a CFocusable component:

\n
\n \n
\n
export class CFocusable extends World.Component(\"focusable\")<\n  CFocusable,\n  {\n    handler: Handler<ExitDirection>;\n    hasDirectFocusAtom: Atom<boolean>;\n  }\n>() {\n}
\n
\n
\n

What this gives us:

\n
    \n
  • hasDirectFocusAtom: A reactive boolean that's true when this specific entity has focus
  • \n
  • handler: Called when focus enters from a direction (we'll use this later for spatial nav)
  • \n
\n

Let's use it:

\n
const buttonUID = uid(null, null, "my-button");\n\nworld.addEntity(buttonUID, ButtonEntity, {\n  focusable: CFocusable.of({\n    hasDirectFocusAtom: atom(false),\n    handler: () => handled`button focused`,\n  }),\n});\n
\n

Notice: Our component doesn't know HOW focus works, just that it CAN be focused. It's pure data.

\n

Block 2: Tracking Which Entity Has Focus

\n

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.

\n

We'll create a \"Unique\" (a singleton component):

\n
\n \n
\n
export class UCurrentFocus extends World.Unique(\"currentFocus\")<\n  UCurrentFocus,\n  { activeFocusAtom: PrimitiveAtom<UID | null> }\n>() {}
\n
\n
\n

What this gives us:

\n
    \n
  • activeFocusAtom: Holds the UID of whichever entity currently has focus (or null)
  • \n
\n

How it connects:

\n
// When we focus a card:\nconst focusUnique = world.getUniqueOrThrow(UCurrentFocus);\nworld.store.set(focusUnique.activeFocusAtom, cardUID);\n\n// Anywhere else in our app:\nconst focusedEntityUID = world.store.get(focusUnique.activeFocusAtom);\n
\n

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.

\n

Block 3: Declaring Actions

\n

Now we need entities to declare what keyboard actions they support:

\n
\n \n
\n
export type AnyAction = {\n  label: string;\n  defaultKeybinding: DefaultKeyCombo;\n  description?: string;\n  icon?: any;\n  self?: boolean;\n  hideFromLastPressed?: boolean;\n};\ntype AnyBindables = Record<string, AnyAction>;\n\nexport type ActionEvent = { target: UID };\n\nexport namespace CActions {\n  export type Bindings<T extends AnyBindables> = {\n    [P in keyof T]: Handler<ActionEvent> | Falsey;\n  };\n}\n\nexport type ActionBindings<T extends AnyBindables = AnyBindables> = {\n  bindingSource: DevString;\n  registryKey: ActionRegistryKey<T>;\n  bindingsAtom: Atom<CActions.Bindings<T>>;\n};\n\nexport class ActionRegistryKey<T extends AnyBindables = AnyBindables> {\n  constructor(\n    public readonly key: string,\n    public readonly meta: { source: DevString; sectionName: string },\n    public readonly bindables: T,\n  ) {}\n}\n\nexport class CActions extends World.Component(\"actions\")<CActions, ActionBindings[]>() {\n  static bind<T extends AnyBindables>(key: ActionBindings<T>) {\n    return CActions.of([key as ActionBindings]);\n  }\n\n  static merge(...bindings: Array<ActionBindings | ActionBindings[]>) {\n    const out: ActionBindings[] = [];\n    for (const b of bindings) {\n      if (Array.isArray(b)) {\n        out.push(...b);\n      } else {\n        out.push(b);\n      }\n    }\n    return CActions.of(out);\n  }\n\n  static defineActions<T extends AnyBindables>(\n    key: string,\n    meta: { source: DevString; sectionName: string },\n    actions: T,\n  ): ActionRegistryKey<T> {\n    return new ActionRegistryKey(key, meta, actions);\n  }\n}
\n
\n
\n

What this gives us:

\n
    \n
  • A way to define available actions (defineActions)
  • \n
  • A way to bind handlers to those actions per entity
  • \n
  • Actions are just metadata: label, key binding, description
  • \n
\n

Let's define some actions for our cards:

\n
const CardActions = CActions.defineActions(\n  "card-actions",\n  { source: dev`Card actions`, sectionName: "Card Actions" },\n  {\n    delete: {\n      label: "Delete Card",\n      defaultKeybinding: "X" as const,\n      description: "Remove this card",\n    },\n    edit: {\n      label: "Edit Card",\n      defaultKeybinding: "E" as const,\n      description: "Edit card content",\n    },\n  },\n);\n
\n

Now attach handlers to a specific card entity:

\n
world.addEntity(cardUID, CardEntity, {\n  actions: CActions.bind({\n    bindingSource: dev`Card 1 actions`,\n    registryKey: CardActions,\n    bindingsAtom: atom({\n      delete: () => {\n        alert("Deleted!");\n        return handled`delete`;\n      },\n      edit: () => {\n        alert("Editing!");\n        return handled`edit`;\n      },\n    }),\n  }),\n});\n
\n

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.

\n

Block 4: Wiring It All Together - ActionsPlugin

\n

Here's where the magic happens. We need something that:

\n
    \n
  1. Listens for keyboard events
  2. \n
  3. Finds the currently focused entity
  4. \n
  5. Matches keys to actions
  6. \n
  7. Executes the handler
  8. \n
\n

That's what our ActionsPlugin does:

\n
\n \n
\n
export const ActionsPlugin = World.definePlugin({\n  name: dev`ActionsPlugin`,\n  setup: (build) => {\n    const { store } = build;\n\n    // Track the currently focused entity\n    const currentFocusAtom = atom((get) =>\n      pipeNonNull(get(build.getUniqueAtom(UCurrentFocus)), (a) => get(a.activeFocusAtom)),\n    );\n\n    const rootUIDAtom = atom<UID | null>(null);\n    const currentDispatchSpotAtom = atom((get) => get(currentFocusAtom) ?? get(rootUIDAtom));\n\n    const handleOnce = new WeakSet<KeyboardEvent>();\n    build.addUnique(UKeydownRootHandler, {\n      handler(reason, keyboardEvent) {\n        if (handleOnce.has(keyboardEvent)) return Outcome.Passthrough;\n        handleOnce.add(keyboardEvent);\n        if (keyboardEvent.defaultPrevented) return Outcome.Passthrough;\n        const world = store.get(build.worldAtom);\n        if (!world) return Outcome.Passthrough;\n        const dispatchFromUID = store.get(currentDispatchSpotAtom);\n        if (!dispatchFromUID) return Outcome.Passthrough;\n        // Walk up the parent chain looking for keydown handlers\n        const result = CParent.dispatch(\n          dev`keydown from root`.because(reason),\n          world,\n          dispatchFromUID,\n          CKeydownHandler,\n          reason,\n          keyboardEvent,\n        );\n        // Prevent default browser behavior when we handle the key\n        if (result !== Outcome.Passthrough) {\n          keyboardEvent.preventDefault();\n        }\n        return result;\n      },\n      rootUIDAtom,\n    });
\n
\n
\n

Here's what happens when we press a key:

\n
User presses "X"\n  ↓\nActionsPlugin.UKeydownRootHandler receives event\n  ↓\nQuery: Which entity has focus? (from UCurrentFocus)\n  ↓\nWalk up parent chain: Does this entity have CKeydownHandler?\n  ↓\nMatch key "X" to action "delete"\n  ↓\nCall the handler we bound earlier\n  ↓\npreventDefault() so browser doesn't scroll\n
\n

The 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.\"

\n
\n \n
\n
    // Provide keydown handler for entities with CActions\n    build.onEntityCreated(\n      {\n        requires: [CActions],\n        provides: [CKeydownHandler],\n      },\n      (uid, { actions }) => {\n        const combinedCombosAtom = atom((get) => {\n          type ComboData = {\n            actionKey: string;\n            handler: (reason: DevString, event: ActionEvent) => Outcome;\n          } & AnyAction;\n\n          const combosMap = new Map<string, ComboData[]>();\n\n          for (const actionSet of actions) {\n            const resolvedBindings = get(actionSet.bindingsAtom);\n            for (const [actionKey, maybeHandler] of Object.entries(resolvedBindings)) {\n              if (!maybeHandler) continue;\n              const bindable = actionSet.registryKey.bindables[actionKey];\n              if (!bindable) continue;\n              const defaultKey = bindable.defaultKeybinding;\n              const combo = normalizedKeyCombo(defaultKey, ENV_KEYBOARD_KIND).normalized;\n              const comboData: ComboData = {\n                actionKey,\n                handler: maybeHandler,\n                ...bindable,\n              };\n              const list = combosMap.get(combo);\n              if (!list) {\n                combosMap.set(combo, [comboData]);\n              } else {\n                list.push(comboData);\n              }\n            }\n          }\n          return combosMap;\n        });\n\n        const keydownHandler = CKeydownHandler.of({\n          handler(reason, event) {\n            // Omit shift for letter keys so \"Shift+X\" matches \"X\"\n            const combos = addModifiersToKeyCombo(ENV_KEYBOARD_KIND, event, true);\n            if (event.defaultPrevented) return Outcome.Passthrough;\n            const combosMap = store.get(combinedCombosAtom);\n\n            for (const combo of combos) {\n              const comboDatas = combosMap.get(combo.normalized);\n              if (!comboDatas) continue;\n              for (const comboData of comboDatas) {\n                const outcome = comboData.handler(dev`Key combo pressed: ${combo.normalized}`.because(reason), {\n                  target: uid,\n                });\n                if (outcome !== Outcome.Passthrough) {\n                  return outcome;\n                }\n              }\n            }\n            return Outcome.Passthrough;\n          },\n        });\n\n        return { keydownHandler };\n      },\n    );
\n
\n
\n

This is the actual per-entity handler creation. When we add an entity with CActions, the plugin automatically:

\n
    \n
  • Reads all action definitions
  • \n
  • Normalizes key combos (so \"X\" and \"Shift-X\" both match)
  • \n
  • Creates a CKeydownHandler that matches keys to handlers
  • \n
  • Plugs it into the event system
  • \n
\n

We don't call any of this ourselves. It Just Works™.

\n

What We Learned

\n

Let's step back and appreciate what we built:

\n

✅ We Can Test Everything In Isolation

\n

Want to test if \"X\" triggers delete? No React needed:

\n
const world = createTestWorld();\nconst cardUID = addCardEntity(world, {\n  onDelete: mockFn,\n});\n\n// Simulate focus\nworld.store.set(focusAtom, cardUID);\n\n// Simulate keypress\nrootHandler.handler(dev`test`, { key: "x" });\n\nexpect(mockFn).toHaveBeenCalled();\n
\n

✅ Components Are Composable

\n

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:

\n
// Simple button\nworld.addEntity(uid, SimpleButton, {\n  focusable: CFocusable.of({...}),\n});\n\n// Rich editor\nworld.addEntity(uid, RichEditor, {\n  focusable: CFocusable.of({...}),\n  actions: CActions.merge(\n    TextFormattingActions,    // Bold, italic, etc.\n    BlockActions,             // Lists, headings\n    ClipboardActions,         // Cut, copy, paste\n  ),\n});\n
\n

✅ Everything Is Observable

\n

All state lives in Jotai atoms. DevTools can show us:

\n
    \n
  • Which entity has focus right now
  • \n
  • What actions are available
  • \n
  • When each action was last pressed
  • \n
\n

✅ Nothing Is Tightly Coupled

\n

Look at what we didn't do:

\n
    \n
  • ❌ Import KeyboardManager in every component
  • \n
  • ❌ Call registerShortcut() imperatively
  • \n
  • ❌ Have components know about each other
  • \n
  • ❌ Write glue code to connect pieces
  • \n
\n

Instead:

\n
    \n
  • ✅ Components declare data (\"I can be focused\", \"I have actions\")
  • \n
  • ✅ Plugins react to component presence (\"Oh, you have both? Let me wire you up\")
  • \n
  • ✅ Everything communicates through atoms
  • \n
  • ✅ Adding a new entity requires zero changes to existing code
  • \n
\n

When Should We Use This Approach?

\n

Let's be honest about trade-offs.

\n

This pattern shines when:

\n
    \n
  • ✅ We're already using ECS architecture in our app (like we do in Phosphor)
  • \n
  • ✅ We have complex nesting and need context-sensitive shortcuts
  • \n
  • ✅ We want every piece testable in isolation
  • \n
  • ✅ Our app has 10+ different shortcut contexts
  • \n
  • ✅ We value composition over simplicity
  • \n
\n

Consider simpler alternatives when:

\n
    \n
  • ❌ We're building a small app with <20 shortcuts
  • \n
  • ❌ We want minimal bundle size (this adds ~30KB with Jotai + ECS)
  • \n
  • ❌ Our team isn't familiar with reactive state patterns
  • \n
  • ❌ We just need basic \"hotkey → function\" mapping
  • \n
\n

Simpler Alternatives We Considered

\n\n\n\n\n\n
ApproachBundle SizeLearning CurveTest IsolationContext-Sensitive
ECS (Ours)~30KBHighExcellentExcellent
tinykeys2KBLowGoodManual
React Context0KBMediumMediumGood
Mousetrap8KBLowPoorManual
\n

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.

\n

Tracing a Keypress Together

\n

Let's walk through exactly what happens when we press \"X\" to delete a card. This demystifies the \"magic\":

\n
📍 Step 1: DOM Event (keyboard-demo.entrypoint.tsx:29)\n   document.addEventListener('keydown', ...)\n   Event fires with event.key = "x"\n\n   ↓\n\n📍 Step 2: Root Handler (ActionsPlugin.ts:33-42)\n   UKeydownRootHandler.handler() receives event\n   Check currentDispatchSpotAtom: Is anything focused?\n   Result: Card 2 has focus\n\n   ↓\n\n📍 Step 3: Parent Walk (ActionsPlugin.ts:44-55)\n   CParent.dispatch() walks up the entity tree\n   Current: Card 2 → Does it have CKeydownHandler? YES ✓\n\n   ↓\n\n📍 Step 4: Key Normalization (ActionsPlugin.ts:105-107)\n   addModifiersToKeyCombo("x", event, omitShift=true)\n   "x" → "X" (uppercase)\n   No modifiers, final combo: "X"\n\n   ↓\n\n📍 Step 5: Action Lookup (ActionsPlugin.ts:110-115)\n   combosMap.get("X") → [{action: "delete", handler: fn}]\n   Call handler(dev`Key combo`, {target: card2UID})\n\n   ↓\n\n📍 Step 6: Our Handler (createKeyboardDemo.ts:83)\n   onDelete() runs\n   alert("Deleted Card 2!")\n   Returns: handled`delete`\n\n   ↓\n\n📍 Step 7: Prevent Default (ActionsPlugin.ts:50-52)\n   outcome !== Passthrough, so:\n   event.preventDefault() ← stops browser scroll\n   Return "handled" to stop propagation\n
\n

Key insight: Notice how information flows through atoms and component queries, never through direct imports or method calls. That's the decoupling in action.

\n

What's Next?

\n

Now that we understand composable keyboard navigation, we can:

\n
    \n
  • Add spatial navigation (arrow keys navigate a 2D grid)
  • \n
  • Build focus trapping for modals
  • \n
  • Create a command palette with searchable actions
  • \n
  • Support user-customizable keybindings
  • \n
\n

The pattern scales because we're composing data, not coupling objects.

\n

Reflection

\n

We started with a problem: keyboard shortcuts without spaghetti code.

\n

We solved it by separating concerns:

\n
    \n
  • CFocusable says \"I can receive focus\" (data)
  • \n
  • CActions says \"I have these shortcuts\" (data)
  • \n
  • ActionsPlugin says \"When those exist together, wire them up\" (behavior)
  • \n
\n

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.

\n

That's the power of Entity-Component-System for UI.

\n", "permalink": "/keyboard-navigation-demo/", "slug": "keyboard-navigation-demo", "ancestors": [ "_index.md" ], "title": "Let's Build Composable Keyboard Navigation Together", "description": null, "updated": null, "date": "2025-10-20", "year": 2025, "month": 10, "day": 20, "taxonomies": {}, "authors": [], "extra": { "nav_section": "Interactive Demos", "nav_order": 1 }, "path": "/keyboard-navigation-demo/", "components": [ "keyboard-navigation-demo" ], "summary": null, "toc": [ { "level": 1, "id": "let-s-build-composable-keyboard-navigation-together", "permalink": "/keyboard-navigation-demo/#let-s-build-composable-keyboard-navigation-together", "title": "Let's Build Composable Keyboard Navigation Together ⋅", "children": [ { "level": 2, "id": "the-problem-we-re-solving", "permalink": "/keyboard-navigation-demo/#the-problem-we-re-solving", "title": "The Problem We're Solving ⋅", "children": [] }, { "level": 2, "id": "what-we-re-building", "permalink": "/keyboard-navigation-demo/#what-we-re-building", "title": "What We're Building ⋅", "children": [] }, { "level": 2, "id": "our-approach-entities-components-and-plugins", "permalink": "/keyboard-navigation-demo/#our-approach-entities-components-and-plugins", "title": "Our Approach: Entities, Components, and Plugins ⋅", "children": [] }, { "level": 2, "id": "try-it-out-first", "permalink": "/keyboard-navigation-demo/#try-it-out-first", "title": "Try It Out First ⋅", "children": [] }, { "level": 2, "id": "our-four-building-blocks", "permalink": "/keyboard-navigation-demo/#our-four-building-blocks", "title": "Our Four Building Blocks ⋅", "children": [ { "level": 3, "id": "block-1-making-things-focusable", "permalink": "/keyboard-navigation-demo/#block-1-making-things-focusable", "title": "Block 1: Making Things Focusable ⋅", "children": [] }, { "level": 3, "id": "block-2-tracking-which-entity-has-focus", "permalink": "/keyboard-navigation-demo/#block-2-tracking-which-entity-has-focus", "title": "Block 2: Tracking Which Entity Has Focus ⋅", "children": [] }, { "level": 3, "id": "block-3-declaring-actions", "permalink": "/keyboard-navigation-demo/#block-3-declaring-actions", "title": "Block 3: Declaring Actions ⋅", "children": [] }, { "level": 3, "id": "block-4-wiring-it-all-together-actionsplugin", "permalink": "/keyboard-navigation-demo/#block-4-wiring-it-all-together-actionsplugin", "title": "Block 4: Wiring It All Together - ActionsPlugin ⋅", "children": [] } ] }, { "level": 2, "id": "what-we-learned", "permalink": "/keyboard-navigation-demo/#what-we-learned", "title": "What We Learned ⋅", "children": [ { "level": 3, "id": "white-check-mark-we-can-test-everything-in-isolation", "permalink": "/keyboard-navigation-demo/#white-check-mark-we-can-test-everything-in-isolation", "title": "✅ We Can Test Everything In Isolation ⋅", "children": [] }, { "level": 3, "id": "white-check-mark-components-are-composable", "permalink": "/keyboard-navigation-demo/#white-check-mark-components-are-composable", "title": "✅ Components Are Composable ⋅", "children": [] }, { "level": 3, "id": "white-check-mark-everything-is-observable", "permalink": "/keyboard-navigation-demo/#white-check-mark-everything-is-observable", "title": "✅ Everything Is Observable ⋅", "children": [] }, { "level": 3, "id": "white-check-mark-nothing-is-tightly-coupled", "permalink": "/keyboard-navigation-demo/#white-check-mark-nothing-is-tightly-coupled", "title": "✅ Nothing Is Tightly Coupled ⋅", "children": [] } ] }, { "level": 2, "id": "when-should-we-use-this-approach", "permalink": "/keyboard-navigation-demo/#when-should-we-use-this-approach", "title": "When Should We Use This Approach? ⋅", "children": [ { "level": 3, "id": "simpler-alternatives-we-considered", "permalink": "/keyboard-navigation-demo/#simpler-alternatives-we-considered", "title": "Simpler Alternatives We Considered ⋅", "children": [] } ] }, { "level": 2, "id": "tracing-a-keypress-together", "permalink": "/keyboard-navigation-demo/#tracing-a-keypress-together", "title": "Tracing a Keypress Together ⋅", "children": [] }, { "level": 2, "id": "what-s-next", "permalink": "/keyboard-navigation-demo/#what-s-next", "title": "What's Next? ⋅", "children": [] }, { "level": 2, "id": "reflection", "permalink": "/keyboard-navigation-demo/#reflection", "title": "Reflection ⋅", "children": [] } ] } ], "word_count": 1559, "reading_time": 8, "assets": [], "draft": true, "lang": "en", "lower": null, "higher": null, "translations": [], "backlinks": [] }, "translations": [], "backlinks": [] }, "zola_version": "0.21.0" }