hosts.mdx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. ---
  2. title: Hosts
  3. description: Built-in OpenTUI and HTML adapters plus the KeymapHost contract
  4. order: 2
  5. navTitle: Hosts
  6. ---
  7. # Keymap hosts
  8. OpenTUI Keymap is host-agnostic. A host adapts a runtime's focus model, hierarchy, key events and lifecycle into `KeymapHost<TTarget, TEvent>` so the shared engine can work against it.
  9. The package ships two built-in hosts:
  10. - `@opentui/keymap/opentui` for terminal apps built on `CliRenderer` and `Renderable`
  11. - `@opentui/keymap/html` for browser UIs rooted in an `HTMLElement`
  12. If you have not read the shared model yet, start with [Keymap overview](/docs/keymap/overview).
  13. ## What a host does
  14. The keymap core does not know about DOM nodes, terminal renderables or any other UI tree. It only knows about host targets and host events.
  15. - `target` on a local layer is a host target object.
  16. - `focus` and `focus-within` activation come from the host's focused target and parent traversal.
  17. - key press and key release events come from the host event stream.
  18. - local layers are cleaned up when the host reports that their target was destroyed or removed.
  19. - host metadata describes platform shortcut conventions and modifier support for addons.
  20. - `runCommand()` and `dispatchCommand()` need the host to create a synthetic event for programmatic execution.
  21. - raw input interception only exists when the host implements the optional raw-input hook.
  22. ## `KeymapHost`
  23. | Member | Required | Purpose |
  24. | ----------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
  25. | `metadata` | yes | Platform, primary shortcut modifier and modifier capability metadata |
  26. | `rootTarget` | yes | Root target for the host hierarchy |
  27. | `isDestroyed` | yes | Host lifetime flag |
  28. | `getFocusedTarget()` | yes | Returns the currently focused target or `null` |
  29. | `getParentTarget(target)` | yes | Parent traversal used for `focus-within` matching |
  30. | `isTargetDestroyed(target)` | yes | Target liveness check |
  31. | `onKeyPress(listener)` | yes | Subscribes to press events |
  32. | `onKeyRelease(listener)` | yes | Subscribes to release events |
  33. | `onFocusChange(listener)` | yes | Subscribes to focus changes |
  34. | `onTargetDestroy(target, listener)` | yes | Notifies when a local layer target is destroyed or removed |
  35. | `createCommandEvent()` | yes | Creates the synthetic event used by `runCommand()` and `dispatchCommand()` |
  36. | `onDestroy(listener)` | no | Optional host-destroy notification |
  37. | `onRawInput(listener)` | no | Optional raw input hook used before key parsing. The listener returns `true` when it consumed the sequence |
  38. If you are building your own runtime adapter, implement this contract and pass it to `new Keymap(host)`.
  39. Host metadata is available through `keymap.getHostMetadata()`. `primaryModifier` is the modifier that addon syntax such as `mod+s` should resolve to. Capability values are `supported`, `unsupported` or `unknown`; terminal hosts use `unknown` when the event type can represent a modifier but actual terminal delivery depends on protocol support.
  40. | Metadata field | Meaning |
  41. | ----------------- | ---------------------------------------------------------------- |
  42. | `platform` | `macos`, `windows`, `linux` or `unknown` |
  43. | `primaryModifier` | `super` on macOS, `ctrl` on Windows/Linux, or `unknown` |
  44. | `modifiers` | Host capability for `ctrl`, `shift`, `meta`, `super` and `hyper` |
  45. Host key events must satisfy `KeymapEvent`:
  46. | Member | Purpose |
  47. | ------------------------- | --------------------------------------------------------------------------------- |
  48. | `name` | Normalized key name |
  49. | `ctrl` / `shift` / `meta` | Modifier state |
  50. | `super` / `hyper` | Optional extra modifier state |
  51. | `preventDefault()` | Prevent the matched event from reaching the host target |
  52. | `stopPropagation()` | Stop later listeners from seeing the event and set `propagationStopped` to `true` |
  53. | `propagationStopped` | `true` after `stopPropagation()` was called |
  54. If your host implements `onRawInput()`, it must call each listener before key parsing and stop when a listener returns `true`.
  55. ## Built-in host helpers
  56. Both built-in host packages export adapter-specific helpers. Import the shared `Keymap`, stringifiers and core types from `@opentui/keymap`.
  57. | Package | Host adapter | Bare keymap helper | Default helper |
  58. | ------------------------- | ----------------------------------- | ------------------------------- | -------------------------------------- |
  59. | `@opentui/keymap/opentui` | `createOpenTuiKeymapHost(renderer)` | `createOpenTuiKeymap(renderer)` | `createDefaultOpenTuiKeymap(renderer)` |
  60. | `@opentui/keymap/html` | `createHtmlKeymapHost(root)` | `createHtmlKeymap(root)` | `createDefaultHtmlKeymap(root)` |
  61. - The host adapter returns a `KeymapHost` implementation.
  62. - The bare helper creates a `new Keymap(host)` with only the host installed; parser and addon stages remain opt-in.
  63. - The default helper starts from the bare helper and installs the small default addon set for that host.
  64. ## OpenTUI host
  65. `@opentui/keymap/opentui` is the host package for terminal apps built on `@opentui/core`.
  66. ### What it adds
  67. - `createOpenTuiKeymapHost(renderer)` - adapts `CliRenderer` and `Renderable` to `KeymapHost`
  68. - `createOpenTuiKeymap(renderer)` - creates a bare `Keymap<Renderable, KeyEvent>`
  69. - `createDefaultOpenTuiKeymap(renderer)` - creates an OpenTUI keymap with default keys, enabled fields and metadata fields installed
  70. ### Basic usage
  71. ```ts
  72. import { createCliRenderer } from "@opentui/core"
  73. import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
  74. const renderer = await createCliRenderer()
  75. const keymap = createDefaultOpenTuiKeymap(renderer)
  76. keymap.registerLayer({
  77. commands: [
  78. {
  79. name: "quit",
  80. run() {
  81. renderer.destroy()
  82. },
  83. },
  84. ],
  85. bindings: [{ key: "q", cmd: "quit" }],
  86. })
  87. ```
  88. If you want to control the installed addons yourself, start from `createOpenTuiKeymap(renderer)` and register addons manually.
  89. ### Host behavior
  90. | Behavior | OpenTUI adapter |
  91. | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
  92. | Root target | `renderer.root` |
  93. | Focused target | `renderer.currentFocusedRenderable` when still focused and not destroyed |
  94. | Parent traversal | `Renderable.parent` |
  95. | Target destroy tracking | `RenderableEvents.DESTROYED` |
  96. | Host destroy tracking | `CliRenderEvents.DESTROY` |
  97. | Press/release events | `renderer.keyInput` `keypress` and `keyrelease` |
  98. | Raw input interception | `renderer.prependInputHandler(...)` |
  99. | Synthetic command event | New `KeyEvent` with `name: "command"` |
  100. | Host metadata | Runtime platform; `ctrl`, `shift` and `meta` supported; `super`/`hyper` supported when terminal capabilities report Kitty keyboard, otherwise unknown |
  101. `createOpenTuiKeymap(renderer)` throws if the renderer is already destroyed.
  102. ### Default helper
  103. `createDefaultOpenTuiKeymap(renderer)` installs:
  104. - `registerDefaultKeys()`
  105. - `registerEnabledFields()`
  106. - `registerMetadataFields()`
  107. It does not install leader tokens, ex commands, disambiguation addons, warning analyzers, base-layout fallback or textarea helpers. Call `registerBaseLayoutFallback()` from `@opentui/keymap/addons/opentui` if you want bindings to ignore active keyboard-layout changes.
  108. ### Event notes
  109. - Press and release events come directly from the renderer's key input stream.
  110. - Programmatic `runCommand()` and `dispatchCommand()` calls receive the synthetic `KeyEvent` created by `createCommandEvent()`.
  111. - Kitty-specific fields on `KeyEvent`, such as `baseCode`, stay available to addons like `registerBaseLayoutFallback()`.
  112. ### OpenTUI-specific addons
  113. `@opentui/keymap/addons/opentui` adds helpers on top of the shared addon set:
  114. - `registerBaseLayoutFallback()` - match against Kitty base-layout codepoints
  115. - `createTextareaBindings()` - generate textarea bindings from the shared edit-buffer command set
  116. - `registerEditBufferCommands()` - register the edit-buffer command layer against `renderer.currentFocusedEditor`
  117. - `registerTextareaMappingSuspension()` - suspend a focused `TextareaRenderable`'s built-in mapped shortcuts
  118. - `registerManagedTextareaLayer()` - high-level textarea integration combining the helpers above
  119. Example: `packages/examples/src/keymap-demo.ts`
  120. See [Built-in Addons](/docs/keymap/addons) for the rest of the shipped addon surface and [Custom Addons](/docs/keymap/custom-addons) for addon authoring.
  121. ## HTML host
  122. `@opentui/keymap/html` is the host package for browser UIs rooted in an `HTMLElement` subtree.
  123. Live demo: [HTML keymap demo](/demos/keymap-html/)
  124. ### What it adds
  125. - `HtmlKeymapEvent` - shared keymap event plus optional `originalEvent: KeyboardEvent`
  126. - `normalizeHtmlKeyName(key)` - normalizes browser `event.key` values to keymap names
  127. - `createHtmlKeymapEvent(event?)` - wraps a `KeyboardEvent` in `HtmlKeymapEvent`
  128. - `createHtmlKeymapHost(root)` - adapts an `HTMLElement` subtree to `KeymapHost`
  129. - `htmlEventMatchResolver` - HTML-specific event matcher for browser key events
  130. - `createHtmlKeymap(root)` - creates a bare `Keymap<HTMLElement, HtmlKeymapEvent>`
  131. - `createDefaultHtmlKeymap(root)` - creates an HTML keymap with default keys, enabled fields, metadata fields and HTML event matching installed
  132. ### Basic usage
  133. ```ts
  134. import { createDefaultHtmlKeymap } from "@opentui/keymap/html"
  135. const root = document.getElementById("app")!
  136. const keymap = createDefaultHtmlKeymap(root)
  137. keymap.registerLayer({
  138. commands: [
  139. {
  140. name: "toggle-help",
  141. run() {
  142. document.body.classList.toggle("help-open")
  143. },
  144. },
  145. ],
  146. bindings: [{ key: "?", cmd: "toggle-help" }],
  147. })
  148. ```
  149. If you want to control parser or event-matching stages yourself, start from `createHtmlKeymap(root)` and install the pieces manually.
  150. ### Key normalization
  151. | Browser input | Keymap result | Notes |
  152. | ------------- | ------------- | --------------------------------------------------------------------- |
  153. | `ArrowLeft` | `left` | Navigation keys are normalized to the shared canonical names |
  154. | `Enter` | `return` | Canonical name is `return`; display stringifiers render it as `enter` |
  155. | `A` | `a` | Printable names are lowercased |
  156. | `F12` | `f12` | Function keys are normalized to lowercase |
  157. | `altKey` | `meta` | Keymap uses `meta` for Alt/Option |
  158. | `metaKey` | `super` | Keymap uses `super` for the platform Meta key |
  159. The HTML matcher also adds an unshifted match candidate for shifted printable punctuation, so bindings such as `":"` and `"?"` work as literal keys instead of forcing `shift+semicolon`-style spellings.
  160. ### Host behavior
  161. | Behavior | HTML adapter |
  162. | ----------------------- | ------------------------------------------------------------------------------------ |
  163. | Root target | The `HTMLElement` passed to `createHtmlKeymapHost()` / `createHtmlKeymap()` |
  164. | Focused target | `document.activeElement` when it is the root or a descendant |
  165. | Parent traversal | `HTMLElement.parentElement` |
  166. | Target destroy tracking | `MutationObserver` over the root subtree when available |
  167. | Host destroy tracking | None; root reachability is the lifetime model |
  168. | Press/release events | `keydown` and `keyup` listeners on the root in capture phase |
  169. | Raw input interception | Not provided by the HTML host |
  170. | Synthetic command event | `createHtmlKeymapEvent()` with no DOM event |
  171. | Host metadata | Browser platform; `ctrl`, `shift`, `meta` and `super` supported; `hyper` unsupported |
  172. When a target element disconnects from the rooted subtree, local layers registered against it are removed.
  173. ### Default helper
  174. `createDefaultHtmlKeymap(root)` installs:
  175. - `registerDefaultKeys()`
  176. - `registerEnabledFields()`
  177. - `registerMetadataFields()`
  178. - `htmlEventMatchResolver` via `prependEventMatchResolver(...)` so HTML-specific matching runs before the canonical matcher
  179. Call `prependEventMatchResolver(...)` for any custom resolver that must run before the HTML matcher.
  180. ## Custom hosts
  181. If neither built-in host fits your runtime, implement `KeymapHost` yourself and construct the engine directly:
  182. ```ts
  183. import { Keymap, type KeymapHost } from "@opentui/keymap"
  184. const keymap = new Keymap(host as KeymapHost<object>)
  185. ```
  186. Custom hosts must provide conservative metadata. Use `unknown` when the host cannot prove a platform or modifier capability.
  187. Use [Core](/docs/keymap/core) for the bare engine APIs and extension points.