slots.mdx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. ---
  2. title: Plugin Slots
  3. description: Shared slot registry API used by core, React, and Solid
  4. order: 1
  5. navTitle: Overview
  6. skill:
  7. entry: true
  8. intents: [plugins, plugin, slots, registry, extensions]
  9. ---
  10. # Plugin slots
  11. Most TUI apps start as one codebase. As features and teams grow, you may want extension points without asking users to fork the app.
  12. Plugin slots give you that. The host application defines named places in the layout (for example, a status bar, sidebar, or panel), and plugins contribute UI for those places at runtime.
  13. The host stays in control of layout, rendering mode, and type contracts. Plugins only receive the context and slot props the host intentionally exposes.
  14. This page describes the **shared registry API** that the core, React, and Solid bindings are built on. If you are building an app, start with the page for the binding you use:
  15. - [Core slots](/docs/plugins/core) — framework-free, `BaseRenderable` nodes
  16. - [React slots](/docs/plugins/react) — `ReactNode`
  17. - [Solid slots](/docs/plugins/solid) — `JSX.Element`
  18. If you load plugin modules from disk at runtime, see the runtime support notes on the [React slots page](/docs/plugins/react#runtime-loaded-external-plugins) and [Solid slots page](/docs/plugins/solid#runtime-loaded-external-plugins). For custom hosts, use `@opentui/core/runtime-plugin-support` or `createRuntimePlugin` from `@opentui/core/runtime-plugin`.
  19. Read on if you need to understand the underlying model, want to build a custom binding for another framework, or need direct access to the registry API.
  20. ## Concepts
  21. - **Host**: defines slot names and slot prop types.
  22. - **Plugin**: contributes one or more slot renderer callbacks. May include lifecycle hooks.
  23. - **Registry**: registers plugins and resolves contributions for a slot.
  24. - **Slot mode**: controls how plugin output and fallback UI combine (`append`, `replace`, or `single_winner`).
  25. ## Define slots and host context
  26. Slot names map to the props each slot receives. The host context is a shared object passed to every plugin renderer.
  27. ```typescript
  28. import type { PluginContext } from "@opentui/core"
  29. type AppSlots = {
  30. statusbar: { user: string }
  31. sidebar: { section: "left" | "right" }
  32. }
  33. interface AppContext extends PluginContext {
  34. appName: string
  35. version: string
  36. }
  37. ```
  38. The context can be any object. `PluginContext` is a type alias for `object` — extending it is not required but gives your plugins a named type to reference.
  39. ## Create a registry
  40. ```typescript
  41. import { createSlotRegistry } from "@opentui/core"
  42. type AppSlots = {
  43. statusbar: { user: string }
  44. sidebar: { section: "left" | "right" }
  45. }
  46. const context = { appName: "my-app", version: "1.0.0" }
  47. const registry = createSlotRegistry<string, AppSlots, typeof context>(renderer, "my-app:plugins", context)
  48. ```
  49. The first type parameter (`TNode`) is the node type your framework returns — `BaseRenderable` for core, `ReactNode` for React, `JSX.Element` for Solid. The framework-specific helpers fill this in for you.
  50. `createSlotRegistry` is renderer-scoped. For a given `(renderer, key)` pair, you always get the same registry instance. The `key` parameter namespaces registries within a renderer so multiple independent registries can coexist.
  51. Calling `createSlotRegistry` again with the same `(renderer, key)` pair returns the existing registry and applies the new `options` via `configure()`. The `context` argument **must** be the same object reference — passing a different context object throws an error. This means you should create the context object once and reuse it:
  52. ```typescript
  53. // correct — same object reference
  54. const context = { appName: "my-app" }
  55. const reg1 = createSlotRegistry(renderer, "my-key", context)
  56. const reg2 = createSlotRegistry(renderer, "my-key", context) // returns reg1
  57. // throws — different object even if structurally identical
  58. const reg3 = createSlotRegistry(renderer, "my-key", { appName: "my-app" })
  59. ```
  60. When the renderer is destroyed, all registries scoped to it are automatically cleared and disposed.
  61. The framework-specific helpers (`createCoreSlotRegistry`, `createReactSlotRegistry`, `createSolidSlotRegistry`) call `createSlotRegistry` internally with a fixed key. Use `createSlotRegistry` directly only if you need multiple independent registries per renderer.
  62. ### Registry options
  63. All `create*SlotRegistry` functions accept an optional `SlotRegistryOptions` object:
  64. | Option | Type | Default | Description |
  65. | ------------------- | ----------------------------------- | ------- | ----------------------------------------------------------- |
  66. | `onPluginError` | `(event: PluginErrorEvent) => void` | — | Callback invoked on every plugin error |
  67. | `debugPluginErrors` | `boolean` | `false` | When `true`, errors are also logged via `console.debug` |
  68. | `maxPluginErrors` | `number` | `100` | Maximum number of buffered errors before oldest are dropped |
  69. ## Register plugins
  70. ```typescript
  71. const unregister = registry.register({
  72. id: "clock-plugin",
  73. order: 0,
  74. setup(ctx, renderer) {
  75. // called once on registration — initialize resources here
  76. },
  77. dispose() {
  78. // called when the plugin is unregistered — clean up resources here
  79. },
  80. slots: {
  81. statusbar(ctx, props) {
  82. return `${ctx.appName}:${props.user}`
  83. },
  84. },
  85. })
  86. // later: remove this plugin
  87. unregister()
  88. ```
  89. `register()` returns an unregister function. Calling it removes the plugin and invokes its `dispose` hook.
  90. ### Plugin interface
  91. | Field | Type | Required | Description |
  92. | --------- | --------------------------------------- | -------- | -------------------------------------------------------------------------------- |
  93. | `id` | `string` | yes | Unique identifier. Duplicate ids throw. |
  94. | `order` | `number` | no | Sort priority (ascending). Defaults to `0`. |
  95. | `setup` | `(ctx, renderer) => void` | no | Called once at registration time. If it throws, the plugin is not registered. |
  96. | `dispose` | `() => void` | no | Called when the plugin is unregistered or the registry is cleared. |
  97. | `slots` | `{ [slotName]: (ctx, props) => TNode }` | yes | Slot renderer callbacks. Each receives the host context and slot-specific props. |
  98. The core binding extends this with [managed slot objects](/docs/plugins/core#managed-slot-contributions) that add lifecycle hooks.
  99. ### Ordering
  100. Plugins are resolved in this order:
  101. 1. `order` ascending (lower numbers first)
  102. 2. Registration order (earlier registrations first)
  103. 3. `id` lexicographic (tie-breaker)
  104. ## Slot modes
  105. Every slot mount or `<Slot>` component accepts a `mode`. The mode controls how plugin output and fallback UI combine.
  106. | Mode | Behavior |
  107. | --------------- | -------------------------------------------------------------------------- |
  108. | `append` | Fallback first, then all plugin output (default) |
  109. | `replace` | Plugin output only; fallback shown only when no plugins produce output |
  110. | `single_winner` | Only the first plugin by resolved order; fallback if it produces no output |
  111. ## Resolve contributions
  112. ```typescript
  113. const entries = registry.resolveEntries("statusbar")
  114. // Array<{ id: string, renderer: (ctx, props) => TNode }>
  115. const slotRenderers = registry.resolve("statusbar")
  116. // Array<(ctx, props) => TNode>
  117. ```
  118. `renderer` here means the plugin's **slot renderer callback**, not the `CliRenderer` instance.
  119. Use `resolveEntries` when you need plugin ids alongside the callbacks. Use `resolve` when you only need the callbacks.
  120. ## Registry methods
  121. | Method | Description |
  122. | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
  123. | `register(plugin)` | Add a plugin. Returns an unregister function. |
  124. | `unregister(id)` | Remove a plugin by id. Returns `true` if found. |
  125. | `updateOrder(id, order)` | Change a plugin's sort order. Returns `true` if found. |
  126. | `clear()` | Remove and dispose all plugins. |
  127. | `resolve(slot)` | Return ordered slot renderer callbacks. |
  128. | `resolveEntries(slot)` | Return ordered `{ id, renderer }` entries. |
  129. | `subscribe(listener)` | Listen for registration changes. Returns an unsubscribe function. Used internally by React and Solid to trigger re-renders. |
  130. | `configure(options)` | Update `SlotRegistryOptions` after creation. |
  131. | `onPluginError(listener)` | Listen for plugin errors. Returns an unsubscribe function. |
  132. | `getPluginErrors()` | Return buffered `PluginErrorEvent` array. |
  133. | `clearPluginErrors()` | Clear the error buffer. |
  134. | `reportPluginError(report)` | Manually report a plugin error. Used by framework integrations. |
  135. | `renderer` | Getter — the `CliRenderer` this registry is scoped to. |
  136. | `context` | Getter — the host context object. |
  137. ## Error handling
  138. Registries expose plugin error events:
  139. ```typescript
  140. registry.onPluginError((event) => {
  141. console.error(event.pluginId, event.phase, event.source, event.error.message)
  142. })
  143. ```
  144. You can also read and clear buffered errors:
  145. ```typescript
  146. const history = registry.getPluginErrors()
  147. registry.clearPluginErrors()
  148. ```
  149. ### PluginErrorReport
  150. The `reportPluginError` method accepts a `PluginErrorReport`:
  151. | Field | Type | Required | Description |
  152. | ---------- | --------------------- | -------- | ------------------------------------------------------------ |
  153. | `pluginId` | `string` | yes | The plugin that caused the error |
  154. | `slot` | `string \| undefined` | no | The slot name, if the error is slot-specific |
  155. | `phase` | `PluginErrorPhase` | yes | `"setup"`, `"render"`, `"dispose"`, or `"error_placeholder"` |
  156. | `source` | `PluginErrorSource` | no | Defaults to `"registry"` if omitted |
  157. | `error` | `unknown` | yes | The raw error — normalized to `Error` internally |
  158. ### PluginErrorEvent
  159. | Field | Type | Description |
  160. | ----------- | --------------------- | ------------------------------------------------------------ |
  161. | `pluginId` | `string` | The plugin that caused the error |
  162. | `slot` | `string \| undefined` | The slot name, if the error is slot-specific |
  163. | `phase` | `PluginErrorPhase` | `"setup"`, `"render"`, `"dispose"`, or `"error_placeholder"` |
  164. | `source` | `PluginErrorSource` | `"registry"`, `"core"`, or a framework-defined source string |
  165. | `error` | `Error` | The normalized error object |
  166. | `timestamp` | `number` | `Date.now()` at the time of the error |
  167. ## Next: concrete host APIs
  168. Use the shared model above with one of these host integrations:
  169. - [Core slots](/docs/plugins/core) — framework-free, returns `BaseRenderable` nodes
  170. - [React slots](/docs/plugins/react) — returns `ReactNode`
  171. - [Solid slots](/docs/plugins/solid) — returns `JSX.Element`