solid.mdx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. ---
  2. title: Solid.js
  3. description: Build terminal UIs with Solid.js and OpenTUI
  4. order: 1
  5. skill:
  6. entry: true
  7. intents: [solid, jsx, signals, hooks, keyboard, animation, testing]
  8. ---
  9. # Solid.js bindings
  10. Build terminal user interfaces with Solid.js's fine-grained reactivity and OpenTUI.
  11. ## Installation
  12. ```bash
  13. bun install solid-js @opentui/solid
  14. ```
  15. ## Setup
  16. ### 1. Configure TypeScript
  17. Add JSX config to `tsconfig.json`:
  18. ```json
  19. {
  20. "compilerOptions": {
  21. "jsx": "preserve",
  22. "jsxImportSource": "@opentui/solid"
  23. }
  24. }
  25. ```
  26. ### 2. Configure Bun
  27. Add preload script to `bunfig.toml`:
  28. ```toml
  29. preload = ["@opentui/solid/preload"]
  30. ```
  31. ### 3. Enable runtime-loaded plugin support (if needed)
  32. If your app loads external TS/TSX modules at runtime (for example a file-based plugin system), import this once in your entry file before dynamic imports:
  33. ```ts
  34. import "@opentui/solid/runtime-plugin-support"
  35. ```
  36. ### 4. Create your app
  37. ```tsx
  38. import { render } from "@opentui/solid"
  39. const App = () => <text>Hello, World!</text>
  40. render(App)
  41. ```
  42. Run with `bun index.tsx`.
  43. ## Components
  44. OpenTUI Solid provides JSX intrinsic elements that map to core renderables.
  45. **Note:** Solid uses snake_case for multi-word component names (e.g., `ascii_font`, `tab_select`).
  46. ### Layout & display
  47. - `<text>` - Styled text container
  48. - `<box>` - Layout container with borders
  49. - `<scrollbox>` - Scrollable container
  50. - `<ascii_font>` - ASCII art text
  51. - `<markdown>` - Render Markdown content
  52. QR code support is available from `@opentui/qrcode/solid` and must be registered explicitly with `registerQRCode()`.
  53. ### Input
  54. - `<input>` - Single-line text input
  55. - `<textarea>` - Multi-line text input
  56. - `<select>` - List selection
  57. - `<tab_select>` - Tab-based selection
  58. ### Code & diff
  59. - `<code>` - Syntax-highlighted code
  60. - `<line_number>` - Line numbers with diff/diagnostic support
  61. - `<diff>` - Unified or split diff viewer
  62. ### Text modifiers
  63. Use inside `<text>` components:
  64. - `<span>` - Inline styled text
  65. - `<strong>`, `<b>` - Bold text
  66. - `<em>`, `<i>` - Italic text
  67. - `<u>` - Underlined text
  68. - `<br>` - Line break
  69. - `<a>` - Link text with href
  70. ## API reference
  71. ### `render(node, rendererOrConfig?)`
  72. Render a Solid component tree into a CLI renderer.
  73. ```tsx
  74. import { render } from "@opentui/solid"
  75. // Simple usage
  76. render(() => <App />)
  77. // With renderer config
  78. render(() => <App />, {
  79. targetFps: 30,
  80. exitOnCtrlC: false,
  81. })
  82. ```
  83. **Parameters:**
  84. - `node` - Function returning a JSX element
  85. - `rendererOrConfig` - Optional `CliRenderer` instance or `CliRendererConfig`
  86. ### `testRender(node, options?)`
  87. Create a test renderer for snapshots and interaction tests.
  88. ```tsx
  89. import { testRender } from "@opentui/solid"
  90. const testSetup = await testRender(() => <App />, { width: 40, height: 10 })
  91. ```
  92. ### `extend(components)`
  93. Register custom renderables as JSX intrinsic elements.
  94. ```tsx
  95. import { extend } from "@opentui/solid"
  96. extend({ custom_box: CustomBoxRenderable })
  97. ```
  98. ### `getComponentCatalogue()`
  99. Returns the current component catalogue that powers JSX tag lookup.
  100. For plugin slots, see [Plugin Slots overview](/docs/plugins/slots) and [Solid slots](/docs/plugins/solid).
  101. ## Scrollback writers
  102. In [`split-footer`](/docs/core-concepts/renderer#split-footer) mode with `externalOutputMode: "capture-stdout"`, the Solid binding provides helpers that append JSX-rendered output above the footer. They wrap [`renderer.writeToScrollback`](/docs/core-concepts/renderer#writing-to-scrollback) so you can write scrollback content with signals and components.
  103. ### `writeSolidToScrollback(renderer, node, options?)`
  104. Render a JSX node once and append it as a scrollback commit.
  105. ```tsx
  106. import { writeSolidToScrollback } from "@opentui/solid"
  107. writeSolidToScrollback(renderer, () => <text fg="#8BD5CA">api responded in 12ms</text>)
  108. ```
  109. ### `createScrollbackWriter(node, options?)`
  110. If you need to pass the same JSX rendering to multiple `writeToScrollback` calls (or hold onto the writer inside your own code), use the lower-level factory:
  111. ```tsx
  112. import { createScrollbackWriter } from "@opentui/solid"
  113. const writer = createScrollbackWriter(() => <text>logged at {new Date().toISOString()}</text>, { startOnNewLine: true })
  114. renderer.writeToScrollback(writer)
  115. ```
  116. ### Options
  117. | Option | Type | Default | Description |
  118. | ----------------- | --------- | -------------- | ------------------------------------------------------------------------ |
  119. | `width` | `number` | renderer width | Override the snapshot width in columns |
  120. | `height` | `number` | measured auto | Override the snapshot height in rows (otherwise measured from layout) |
  121. | `rowColumns` | `number` | snapshot width | Explicit last-row column count for tail tracking |
  122. | `startOnNewLine` | `boolean` | `true` | Insert a newline before this commit if the previous commit ended mid-row |
  123. | `trailingNewline` | `boolean` | - | Append a newline after the final row |
  124. The writer returns a `ScrollbackSnapshot` whose teardown disposes the inner Solid subtree after the snapshot renders. Use the core [`ScrollbackSurface`](/docs/core-concepts/renderer#writing-to-scrollback) APIs directly if you need streaming commits that re-render the same tree over time.
  125. ## Hooks
  126. ### `useRenderer()`
  127. Access the OpenTUI renderer instance.
  128. ```tsx
  129. import { useRenderer } from "@opentui/solid"
  130. import { onMount } from "solid-js"
  131. const App = () => {
  132. const renderer = useRenderer()
  133. onMount(() => {
  134. renderer.console.show()
  135. console.log("Hello from console!")
  136. })
  137. return <box />
  138. }
  139. ```
  140. ### `useKeyboard(handler, options?)`
  141. Subscribe to keyboard events.
  142. ```tsx
  143. import { useKeyboard, useRenderer } from "@opentui/solid"
  144. const App = () => {
  145. const renderer = useRenderer()
  146. useKeyboard((key) => {
  147. if (key.name === "escape") {
  148. renderer.destroy()
  149. }
  150. })
  151. return <text>Press ESC to close</text>
  152. }
  153. ```
  154. With release events:
  155. ```tsx
  156. import { createSignal } from "solid-js"
  157. const App = () => {
  158. const [pressedKeys, setPressedKeys] = createSignal(new Set<string>())
  159. useKeyboard(
  160. (event) => {
  161. setPressedKeys((keys) => {
  162. const newKeys = new Set(keys)
  163. if (event.eventType === "release") {
  164. newKeys.delete(event.name)
  165. } else {
  166. newKeys.add(event.name)
  167. }
  168. return newKeys
  169. })
  170. },
  171. { release: true },
  172. )
  173. return <text>Pressed: {Array.from(pressedKeys()).join(", ") || "none"}</text>
  174. }
  175. ```
  176. ### `onResize(callback)`
  177. Handle terminal resize events.
  178. ```tsx
  179. import { onResize } from "@opentui/solid"
  180. const App = () => {
  181. onResize((width, height) => {
  182. console.log(`Resized to ${width}x${height}`)
  183. })
  184. return <text>Resize-aware component</text>
  185. }
  186. ```
  187. ### `onFocus(callback)`
  188. Run side effects when the terminal window gains focus.
  189. ```tsx
  190. import { onFocus } from "@opentui/solid"
  191. const App = () => {
  192. onFocus(() => {
  193. console.log("Terminal focused")
  194. })
  195. return <text>Switch away and back to trigger focus events</text>
  196. }
  197. ```
  198. ### `onBlur(callback)`
  199. Run side effects when the terminal window loses focus.
  200. ```tsx
  201. import { onBlur } from "@opentui/solid"
  202. const App = () => {
  203. onBlur(() => {
  204. console.log("Terminal blurred")
  205. })
  206. return <text>Switch away and back to trigger blur events</text>
  207. }
  208. ```
  209. These hooks listen for terminal focus-in/focus-out events when the terminal emulator supports them.
  210. ### `useTerminalDimensions()`
  211. Get reactive terminal dimensions (returns a Solid signal).
  212. ```tsx
  213. import { useTerminalDimensions } from "@opentui/solid"
  214. const App = () => {
  215. const dimensions = useTerminalDimensions()
  216. return (
  217. <text>
  218. Terminal: {dimensions().width}x{dimensions().height}
  219. </text>
  220. )
  221. }
  222. ```
  223. ### `usePaste(handler)`
  224. Subscribe to paste events.
  225. ```tsx
  226. import { usePaste } from "@opentui/solid"
  227. const textDecoder = new TextDecoder()
  228. const App = () => {
  229. usePaste((event) => {
  230. console.log("Pasted:", textDecoder.decode(event.bytes))
  231. })
  232. return <text>Paste something!</text>
  233. }
  234. ```
  235. ### `useSelectionHandler(callback)`
  236. Handle text selection events.
  237. ```tsx
  238. import { useSelectionHandler } from "@opentui/solid"
  239. const App = () => {
  240. useSelectionHandler((selection) => {
  241. console.log("Selected:", selection)
  242. })
  243. return <text selectable>Select me!</text>
  244. }
  245. ```
  246. ### `useTimeline(options?)`
  247. Create and manage animations.
  248. ```tsx
  249. import { useTimeline } from "@opentui/solid"
  250. import { createSignal, onMount } from "solid-js"
  251. const App = () => {
  252. const [width, setWidth] = createSignal(0)
  253. const timeline = useTimeline({
  254. duration: 2000,
  255. loop: false,
  256. })
  257. onMount(() => {
  258. timeline.add(
  259. { width: width() },
  260. {
  261. width: 50,
  262. duration: 2000,
  263. ease: "linear",
  264. onUpdate: (animation) => {
  265. setWidth(animation.targets[0].width)
  266. },
  267. },
  268. )
  269. })
  270. return <box style={{ width: width(), backgroundColor: "#6a5acd" }} />
  271. }
  272. ```
  273. ## Special components
  274. ### `Portal`
  275. Render children into a different mount point (useful for modals and overlays).
  276. ```tsx
  277. import { Portal, useRenderer } from "@opentui/solid"
  278. const App = () => {
  279. const renderer = useRenderer()
  280. return (
  281. <box>
  282. <text>Main content</text>
  283. <Portal mount={renderer.root}>
  284. <box border>Overlay</box>
  285. </Portal>
  286. </box>
  287. )
  288. }
  289. ```
  290. ### `Dynamic`
  291. Render arbitrary intrinsic elements or components dynamically.
  292. ```tsx
  293. import { Dynamic } from "@opentui/solid"
  294. import { createSignal } from "solid-js"
  295. const App = () => {
  296. const [isMultiline, setIsMultiline] = createSignal(false)
  297. return <Dynamic component={isMultiline() ? "textarea" : "input"} />
  298. }
  299. ```
  300. ## Building for production
  301. Use [Bun.build](https://bun.sh/docs/bundler) with the Solid plugin:
  302. ```ts
  303. import solidPlugin from "@opentui/solid/bun-plugin"
  304. await Bun.build({
  305. entrypoints: ["./index.tsx"],
  306. target: "bun",
  307. outdir: "./build",
  308. plugins: [solidPlugin],
  309. })
  310. ```
  311. To compile to a standalone executable:
  312. ```ts
  313. await Bun.build({
  314. entrypoints: ["./index.tsx"],
  315. plugins: [solidPlugin],
  316. compile: {
  317. target: "bun-darwin-arm64",
  318. outfile: "./app-macos",
  319. },
  320. })
  321. ```
  322. If that executable loads external plugins/modules at runtime, keep `import "@opentui/solid/runtime-plugin-support"` in your app entry.
  323. ## Example: counter
  324. ```tsx
  325. import { render, useKeyboard, useRenderer } from "@opentui/solid"
  326. import { createSignal } from "solid-js"
  327. const App = () => {
  328. const [count, setCount] = createSignal(0)
  329. const renderer = useRenderer()
  330. useKeyboard((key) => {
  331. if (key.name === "up") setCount((c) => c + 1)
  332. if (key.name === "down") setCount((c) => c - 1)
  333. if (key.name === "escape") renderer.destroy()
  334. })
  335. return (
  336. <box border padding={2}>
  337. <text>Count: {count()}</text>
  338. <text fg="#888">Up/Down to change, ESC to close</text>
  339. </box>
  340. )
  341. }
  342. render(App)
  343. ```
  344. ## Differences from React bindings
  345. | Aspect | Solid | React |
  346. | ------------------ | ------------------------------------------------------ | -------------------------------------- |
  347. | Render function | `render(() => <App />)` | `createRoot(renderer).render(<App />)` |
  348. | Component naming | snake_case (`ascii_font`) | kebab-case (`ascii-font`) |
  349. | State | `createSignal` | `useState` |
  350. | Effects | `onMount`, `onCleanup` | `useEffect` |
  351. | Resize hook | `onResize(callback)` | `useOnResize(callback)` |
  352. | Dimensions | Returns signal: `dimensions().width` | Returns object: `dimensions.width` |
  353. | Extra hooks | `onFocus`, `onBlur`, `usePaste`, `useSelectionHandler` | - |
  354. | Special components | `Portal`, `Dynamic` | - |