docs: update skill documentation with upstream repo

This commit is contained in:
msmps
2026-08-27 20:45:21 +01:00
parent c9492e03a6
commit 0d61d6d89e
23 changed files with 654 additions and 796 deletions
+4 -4
View File
@@ -84,13 +84,13 @@ The main `SKILL.md` contains decision trees for:
**Frameworks**: Core (imperative), React (declarative), Solid (fine-grained reactivity)
**Components**: text, box, scrollbox, scrollbar, input, textarea, select, tab-select, slider, ascii-font, code, line-number, diff, markdown, qr-code
**Components**: text, box, scrollbox, scrollbar, input, textarea, select, tab-select, slider, ascii-font, image, embedded-terminal, time-to-first-draw, code, line-number, diff, markdown, qr-code
**Cross-cutting**: Layout (Yoga/Flexbox), Keyboard handling, Keymap, Animations, Testing
**Additional packages**: `@opentui/keymap`, `@opentui/qrcode`, `@opentui/ssh`, native Audio, OSC notifications
**Additional capabilities**: `@opentui/keymap`, `@opentui/qrcode`, `@opentui/ssh`, loaded/streaming/captured audio, host and terminal clipboards, native images, OSC notifications
**Runtime**: Bun (reference) or Node.js 26.3.0 (`--experimental-ffi` for the native renderer)
**Runtime**: Bun (reference) or Node.js 26.4.0+ (`--experimental-ffi` for the native renderer)
## Credits & Inspiration
@@ -106,4 +106,4 @@ MIT - see [LICENSE](LICENSE)
---
**Upstream**: `anomalyco/opentui` | **Last synced commit**: `cea1dae` | **Date**: 2026-06-26
**Upstream**: `anomalyco/opentui` | **Last synced commit**: `fbd584b2` | **Date**: 2026-08-27
+12 -6
View File
@@ -87,7 +87,10 @@ Display content?
├─ Scrollable content area -> components/containers.md (scrollbox)
├─ Standalone scrollbar -> components/containers.md (scrollbar)
├─ ASCII art banner/title -> components/text-display.md (ascii-font)
├─ PNG/JPEG/WebP/GIF image -> components/text-display.md (image)
├─ First-draw diagnostic -> components/text-display.md (time-to-first-draw)
├─ QR code -> components/text-display.md (qr-code, @opentui/qrcode)
├─ Embedded child terminal/VT output -> components/containers.md (Core only)
├─ Data table with borders/wrapping -> components/code-diff.md (TextTable)
├─ Code with syntax highlighting -> components/code-diff.md
├─ Diff viewer (unified/split, hunk nav) -> components/code-diff.md
@@ -139,7 +142,7 @@ Input handling?
├─ Paste events -> keyboard/REFERENCE.md
├─ Mouse events -> components/containers.md
├─ Text selection & copy-on-select -> keyboard/REFERENCE.md (selection)
└─ Clipboard (OSC 52) -> keyboard/REFERENCE.md (clipboard)
└─ Host/terminal clipboard service or OSC 52 -> keyboard/REFERENCE.md (clipboard)
```
### "I need to test my TUI"
@@ -152,11 +155,14 @@ Testing?
└─ Debugging tests -> testing/REFERENCE.md
```
### "I need platform capabilities (audio, notifications, SSH)"
### "I need platform capabilities (audio, images, clipboard, notifications, SSH)"
```
Platform capability?
├─ Play sound / native audio -> core/api.md (Audio)
├─ Play loaded sound or MP3/FLAC stream -> core/api.md (Audio)
├─ Capture microphone PCM / record WAV -> core/api.md (Audio)
├─ Decode, transform, or display images -> components/text-display.md (image)
├─ Read/write host or terminal clipboard -> keyboard/REFERENCE.md (clipboard)
├─ Desktop notifications (OSC 9/777/99) -> core/api.md (triggerNotification)
├─ Custom stdin/stdout (PTY, xterm.js) -> core/api.md (createCliRenderer)
└─ Serve a TUI over SSH -> core/REFERENCE.md (@opentui/ssh)
@@ -204,8 +210,8 @@ For component naming differences and text modifiers, see `components/REFERENCE.m
### Component Categories
| Category | Entry File | Components |
|----------|------------|------------|
| Text & Display | `./references/components/text-display.md` | text, ascii-font, styled text, qr-code |
| Containers | `./references/components/containers.md` | box, scrollbox, scrollbar, borders |
| Text & Display | `./references/components/text-display.md` | text, ascii-font, image, time-to-first-draw, styled text, qr-code |
| Containers | `./references/components/containers.md` | box, scrollbox, scrollbar, embedded-terminal, borders |
| Inputs | `./references/components/inputs.md` | input, textarea, select, tab-select, slider |
| Code & Diff | `./references/components/code-diff.md` | code, line-number, diff, markdown, text-table |
@@ -218,7 +224,7 @@ For component naming differences and text modifiers, see `components/REFERENCE.m
| `@opentui/three` | Three.js WebGPU renderer (formerly `core/src/3d`) | upstream `packages/three` |
| `@opentui/examples` | Runnable examples (formerly `core/src/examples`) | upstream `packages/examples` |
Core also ships a native **Audio** engine and OSC desktop **notifications** — see `./references/core/api.md`.
Core also ships loaded/streaming/captured **Audio**, native **images**, host and terminal **clipboard** services, and OSC desktop **notifications**.
## Resources
+21 -66
View File
@@ -34,7 +34,7 @@ function AnimatedBox() {
{
width: 50,
duration: 2000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setWidth(Math.round(anim.targets[0].width))
},
@@ -71,7 +71,7 @@ function AnimatedBox() {
{
width: 50,
duration: 2000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setWidth(Math.round(anim.targets[0].width))
},
@@ -107,14 +107,14 @@ timeline.add(
{
x: 50,
duration: 2000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
box.setLeft(Math.round(anim.targets[0].x))
box.left = Math.round(anim.targets[0].x)
},
}
)
engine.addTimeline(timeline)
engine.register(timeline)
```
## Timeline Options
@@ -141,7 +141,7 @@ timeline.pause() // Pause
timeline.restart() // Restart from beginning
// State
timeline.progress // Current progress (0-1)
timeline.currentTime // Current position in milliseconds
timeline.duration // Total duration
```
@@ -154,7 +154,6 @@ timeline.add(
value: 100, // Final value
duration: 1000, // Animation duration in ms
ease: "linear", // Easing function
delay: 0, // Delay before starting
onUpdate: (anim) => {
// Called each frame
const current = anim.targets[0].value
@@ -163,7 +162,7 @@ timeline.add(
// Called when this animation completes
},
},
0 // Start time in timeline (optional)
0 // Start time in timeline; use this instead of delay
)
```
@@ -177,61 +176,17 @@ Available easing functions:
|------|-------------|
| `linear` | Constant speed |
### Quad (Power of 2)
### Curves
| Name | Description |
|------|-------------|
| `easeInQuad` | Slow start |
| `easeOutQuad` | Slow end |
| `easeInOutQuad` | Slow start and end |
### Cubic (Power of 3)
| Name | Description |
|------|-------------|
| `easeInCubic` | Slower start |
| `easeOutCubic` | Slower end |
| `easeInOutCubic` | Slower start and end |
### Quart (Power of 4)
| Name | Description |
|------|-------------|
| `easeInQuart` | Even slower start |
| `easeOutQuart` | Even slower end |
| `easeInOutQuart` | Even slower start and end |
### Expo (Exponential)
| Name | Description |
|------|-------------|
| `easeInExpo` | Exponential start |
| `easeOutExpo` | Exponential end |
| `easeInOutExpo` | Exponential start and end |
### Back (Overshoot)
| Name | Description |
|------|-------------|
| `easeInBack` | Pull back, then forward |
| `easeOutBack` | Overshoot, then settle |
| `easeInOutBack` | Both |
### Elastic
| Name | Description |
|------|-------------|
| `easeInElastic` | Elastic start |
| `easeOutElastic` | Elastic end (bouncy) |
| `easeInOutElastic` | Both |
### Bounce
| Name | Description |
|------|-------------|
| `easeInBounce` | Bounce at start |
| `easeOutBounce` | Bounce at end |
| `easeInOutBounce` | Both |
| Family | Names |
|--------|-------|
| Quad | `inQuad`, `outQuad`, `inOutQuad` |
| Expo | `inExpo`, `outExpo` |
| Sine | `inOutSine` |
| Circular | `inCirc`, `outCirc`, `inOutCirc` |
| Back | `inBack`, `outBack`, `inOutBack` |
| Bounce | `inBounce`, `outBounce` |
| Elastic | `outElastic` |
## Patterns
@@ -250,7 +205,7 @@ function ProgressBar({ progress }: { progress: number }) {
{
value: (progress / 100) * maxWidth,
duration: 300,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setWidth(Math.round(anim.targets[0].value))
},
@@ -283,7 +238,7 @@ function FadeIn({ children }) {
{
opacity: 1,
duration: 500,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setOpacity(anim.targets[0].opacity)
},
@@ -361,7 +316,7 @@ function SlideIn({ children, from = "left" }) {
{
offset: 0,
duration: 300,
ease: "easeOutCubic",
ease: "outQuad",
onUpdate: (anim) => {
setOffset(Math.round(anim.targets[0].offset))
},
@@ -399,7 +354,7 @@ Hooks automatically clean up, but for core:
```typescript
// When done with timeline
engine.removeTimeline(timeline)
engine.unregister(timeline)
```
## Gotchas
@@ -10,8 +10,8 @@ Use this reference when you need to find the right component category or compare
| Category | Components | File |
|----------|------------|------|
| Text & Display | text, ascii-font, styled text, qr-code | [text-display.md](./text-display.md) |
| Containers | box, scrollbox, scrollbar, borders | [containers.md](./containers.md) |
| Text & Display | text, ascii-font, image, time-to-first-draw, styled text, qr-code | [text-display.md](./text-display.md) |
| Containers | box, scrollbox, scrollbar, embedded-terminal, borders | [containers.md](./containers.md) |
| Inputs | input, textarea, select, tab-select, slider | [inputs.md](./inputs.md) |
| Code & Diff | code, line-number, diff, markdown, text-table | [code-diff.md](./code-diff.md) |
@@ -19,8 +19,8 @@ Use this reference when you need to find the right component category or compare
```
Need a component?
├─ Styled text, ASCII art, or QR code -> text-display.md
├─ Containers, borders, scrolling, scrollbar -> containers.md
├─ Styled text, images, diagnostics, ASCII art, or QR code -> text-display.md
├─ Containers, borders, scrolling, scrollbar, embedded terminal -> containers.md
├─ Forms, input controls, sliders -> inputs.md
└─ Code blocks, diffs, line numbers, markdown -> code-diff.md
```
@@ -39,6 +39,8 @@ Components have different names across frameworks:
| Select | `SelectRenderable` | `<select>` | `<select>` |
| Tab Select | `TabSelectRenderable` | `<tab-select>` | `<tab_select>` |
| ASCII Font | `ASCIIFontRenderable` | `<ascii-font>` | `<ascii_font>` |
| Image | `ImageRenderable` | `<image>` | `<image>` |
| Time to First Draw | `TimeToFirstDrawRenderable` | `<time-to-first-draw>` / `TimeToFirstDraw` | `<time_to_first_draw>` / `TimeToFirstDraw` |
| Code | `CodeRenderable` | `<code>` | `<code>` |
| Line Number | `LineNumberRenderable` | `<line-number>` | `<line_number>` |
| Diff | `DiffRenderable` | `<diff>` | `<diff>` |
@@ -47,9 +49,10 @@ Components have different names across frameworks:
| Slider | `SliderRenderable` | N/A (Core only) | N/A (Core only) |
| ScrollBar | `ScrollBarRenderable` | N/A (Core only) | N/A (Core only) |
| FrameBuffer | `FrameBufferRenderable` | N/A (Core + construct) | N/A (Core + construct) |
| Embedded Terminal | `EmbeddedTerminalRenderable` | N/A (Core only) | N/A (Core only) |
| QR Code | `QRCodeRenderable` | `<qr-code>` * | `<qr_code>` * |
**Note**: Solid uses underscores (`tab_select`) while React uses hyphens (`tab-select`). `TextTableRenderable` is used internally by `MarkdownRenderable` for table rendering and is also available as a standalone Core component. `SliderRenderable` and `ScrollBarRenderable` do not yet expose a construct/JSX API — use the Core class. `FrameBufferRenderable` is Core-only with a `FrameBuffer({...})` construct wrapper (no reconciler JSX element). `* QRCodeRenderable` ships in the separate `@opentui/qrcode` package and requires `registerQRCode()` before the JSX element is available (see [text-display.md](./text-display.md)).
**Note**: Solid uses underscores (`tab_select`) while React uses hyphens (`tab-select`). `TextTableRenderable` is used internally by `MarkdownRenderable` for table rendering and is also available as a standalone Core component. `SliderRenderable`, `ScrollBarRenderable`, and `EmbeddedTerminalRenderable` do not expose built-in reconciler elements — use Core (or explicitly register a custom catalogue entry). `FrameBufferRenderable` is Core-only with a `FrameBuffer({...})` construct wrapper. `* QRCodeRenderable` ships in the separate `@opentui/qrcode` package and requires `registerQRCode()` before the JSX element is available (see [text-display.md](./text-display.md)).
## Common Properties
@@ -75,8 +78,8 @@ paddingX, paddingY // Axis shorthand (horizontal/vertical)
margin, marginTop, marginRight, marginBottom, marginLeft
marginX, marginY // Axis shorthand (horizontal/vertical)
// Display
display="flex" | "none"
// Visibility
visible
overflow="visible" | "hidden" | "scroll"
zIndex
```
+187 -615
View File
@@ -1,733 +1,305 @@
# Code & Diff Components
Components for displaying code with syntax highlighting and diffs in OpenTUI.
Components for source code, line-number gutters, unified diffs, Markdown, and
text tables.
## Code Component
Display syntax-highlighted code blocks.
`CodeRenderable` displays plain text immediately and applies asynchronous
Tree-sitter highlighting when `filetype` and a parser are available.
### Basic Usage
```tsx
// React
<code
code={`function hello() {
console.log("Hello, World!");
}`}
language="typescript"
/>
// Solid
<code
code={sourceCode}
language="javascript"
/>
// React / Solid
<code content={sourceCode} filetype="typescript" syntaxStyle={syntaxStyle} />
// Core
const codeBlock = new CodeRenderable(renderer, {
id: "code",
code: sourceCode,
language: "typescript",
const code = new CodeRenderable(renderer, {
content: sourceCode,
filetype: "typescript",
syntaxStyle,
wrapMode: "none", // "none" | "char" | "word"
})
```
### Supported Languages
OpenTUI bundles parsers for JavaScript/JSX, TypeScript/TSX, Markdown,
Markdown-inline, and Zig. Other grammars require Tree-sitter asset
configuration. Without `filetype`, Code renders unhighlighted text.
OpenTUI uses Tree-sitter for syntax highlighting. Common languages:
- `typescript`, `javascript`
- `python`
- `rust`
- `go`
- `json`
- `html`, `css`
- `markdown`
- `bash`, `shell`
### Highlight Hooks
### Styling
`onHighlight` can replace the syntax ranges before styling. It receives
`SimpleHighlight[]` tuples and `{ content, filetype, syntaxStyle }`; return an
array or `undefined`, synchronously or asynchronously.
```tsx
<code
code={sourceCode}
language="typescript"
backgroundColor="#1a1a2e"
showLineNumbers
content={sourceCode}
filetype="typescript"
syntaxStyle={syntaxStyle}
onHighlight={(highlights, context) =>
highlights.filter((highlight) => highlight[2] !== "comment")
}
/>
```
### onHighlight Callback
Intercept and modify syntax highlights before rendering:
`onChunks` runs afterward and can replace the resolved `TextChunk[]`. Its
context also includes `highlights`.
```tsx
// Core
const codeBlock = new CodeRenderable(renderer, {
id: "code",
code: sourceCode,
language: "typescript",
onHighlight: (highlights, context) => {
// Add custom highlights
highlights.push([10, 20, "custom.error", {}])
return highlights
},
})
// React/Solid
<code
code={sourceCode}
language="typescript"
onHighlight={(highlights, context) => {
// context: { content, filetype, syntaxStyle }
// Modify and return highlights array
return highlights.filter(h => h[2] !== "comment")
}}
/>
```
**Callback signature:**
- `highlights: SimpleHighlight[]` - Array of `[start, end, scope, metadata]`
- `context: { content, filetype, syntaxStyle }` - Highlighting context
- Return modified highlights array or `undefined` to use original
Supports async callbacks for fetching additional highlight data.
### onChunks Callback
Post-process rendered text chunks after syntax highlighting. Runs after `onHighlight` and receives fully resolved chunks:
```tsx
// Core
const codeBlock = new CodeRenderable(renderer, {
id: "code",
code: sourceCode,
language: "typescript",
onChunks: (chunks, context) => {
// Transform chunks (e.g., add link detection)
return chunks
},
})
// React/Solid
<code
code={sourceCode}
language="typescript"
onChunks={(chunks, context) => {
// context: { content, filetype, syntaxStyle, highlights }
return chunks
}}
/>
```
### Link Detection Utility
Auto-detect URLs in code and add clickable hyperlinks:
```typescript
import { detectLinks } from "@opentui/core"
<code
code={sourceCode}
language="typescript"
content={markdown}
filetype="markdown"
syntaxStyle={syntaxStyle}
onChunks={(chunks, context) => detectLinks(chunks, context)}
/>
```
`detectLinks` examines Tree-sitter highlights to find URL tokens and sets `chunk.link` on matching chunks. Supports async usage.
`detectLinks` applies links for recognized Markdown/URL highlight scopes.
## TextTable Component
Render data tables with borders, word wrapping, and selection support.
### Basic Usage
`TextTableRenderable` is Core-only. It displays styled chunk cells with borders,
wrapping, width fitting, and selection.
```typescript
// Core
import { TextTableRenderable, type TextTableContent } from "@opentui/core"
import {
TextTableRenderable,
bold,
fg,
type TextChunk,
type TextTableContent,
} from "@opentui/core"
const cell = (text: string): TextChunk[] => [{ __isChunk: true, text }]
const content: TextTableContent = [
[[ { text: "Name" } ], [ { text: "Age" } ], [ { text: "Role" } ]],
[[ { text: "Alice" } ], [ { text: "30" } ], [ { text: "Engineer" } ]],
[[ { text: "Bob" } ], [ { text: "25" } ], [ { text: "Designer" } ]],
[[bold("Service")], [bold("Status")], [bold("Notes")]],
[cell("api"), [fg("#00d4aa")("OK")], cell("latency 28ms")],
]
const table = new TextTableRenderable(renderer, {
id: "table",
content,
wrapMode: "word", // "none" | "char" | "word"
columnWidthMode: "content", // "content" | "fill"
cellPadding: 0,
wrapMode: "word",
columnWidthMode: "full", // "content" | "full"
columnFitter: "balanced", // "proportional" | "balanced"
cellPadding: 1,
border: true,
outerBorder: true,
borderStyle: "single", // single | double | rounded | bold
selectable: true, // Allow text selection
columnFitter: "balanced", // "proportional" | "balanced"
borderStyle: "rounded",
selectable: true,
})
```
### Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `content` | `TextTableContent` | - | 2D array of cell content |
| `wrapMode` | `"none" \| "char" \| "word"` | `"none"` | Text wrapping in cells |
| `columnWidthMode` | `"content" \| "fill"` | `"content"` | Column sizing strategy |
| `cellPadding` | `number` | `0` | Padding inside cells |
| `border` | `boolean` | `true` | Show inner borders |
| `outerBorder` | `boolean` | `true` | Show outer borders |
| `borderStyle` | `string` | `"single"` | Border style |
| `borderColor` | `string \| RGBA` | - | Border color |
| `selectable` | `boolean` | `false` | Allow text selection |
| `columnFitter` | `"proportional" \| "balanced"` | `"proportional"` | Column width distribution |
| `content` | `TextTableContent` | - | Rows of styled chunk cells |
| `wrapMode` | `none \| char \| word` | `none` | Cell wrapping |
| `columnWidthMode` | `content \| full` | `full` | Natural or available-width sizing |
| `columnFitter` | `proportional \| balanced` | `proportional` | Distribute constrained width |
| `cellPadding` | `number` | `0` | Horizontal cell padding |
| `border`, `outerBorder` | `boolean` | `true` | Inner and outer borders |
| `borderStyle` | `single \| double \| rounded \| heavy` | `single` | Border glyph set |
| `borderColor` | `ColorInput` | - | Border color |
| `selectable` | `boolean` | `false` | Participate in text selection |
### Cell Content Format
Each cell is an array of styled text chunks:
```typescript
type TextTableCellContent = { text: string; fg?: RGBA; bg?: RGBA }[]
type TextTableContent = TextTableCellContent[][] // rows -> cells -> chunks
```
### Selection
```typescript
table.getSelectedText() // Get selected text
table.hasSelection() // Check if text is selected
```
Columnar selection is supported: dragging vertically within a single column selects only that column's content.
`TextTableCellContent` is `TextChunk[] | null | undefined`. Each literal chunk
needs `__isChunk: true`; styled-text helpers such as `bold()` and `fg()` already
return valid chunks. `getSelectedText()` and `hasSelection()` expose selection;
vertical drags within one column retain columnar selection.
## Line Number Component
Code display with line numbers, highlighting, and diagnostics.
### Basic Usage
`LineNumberRenderable` is a gutter for another renderable that implements
`LineInfoProvider`; it does not accept source code itself.
```tsx
// React
// React (use <line_number> in Solid)
<line-number
code={sourceCode}
language="typescript"
/>
// Solid (note underscore)
<line_number
code={sourceCode}
language="typescript"
/>
ref={lineNumbersRef}
fg="#6b7280"
bg="#161b22"
minWidth={3}
paddingRight={1}
lineNumberOffset={0}
>
<code content={sourceCode} filetype="typescript" syntaxStyle={syntaxStyle} />
</line-number>
```
```typescript
// Core
const codeView = new LineNumberRenderable(renderer, {
id: "code-view",
code: sourceCode,
language: "typescript",
const code = new CodeRenderable(renderer, {
content: sourceCode,
filetype: "typescript",
syntaxStyle,
})
const lineNumbers = new LineNumberRenderable(renderer, {
target: code,
minWidth: 3,
paddingRight: 1,
})
```
### Line Number Options
Use methods rather than nonexistent `diagnostics`, `addedLines`,
`removedLines`, or `highlightedLines` props:
```tsx
// React
<line-number
code={sourceCode}
language="typescript"
startLine={1} // Starting line number
showLineNumbers={true} // Display line numbers
/>
// Solid
<line_number
code={sourceCode}
language="typescript"
startLine={1}
showLineNumbers={true}
/>
```typescript
lineNumbers.setLineColor(4, "#1a4d1a")
lineNumbers.setLineSign(4, { after: " +", afterColor: "#22c55e" })
lineNumbers.highlightLines(9, 11, "#4d1a1a")
lineNumbers.clearHighlightLines(9, 11)
```
### Line Highlighting
Highlight specific lines:
```tsx
// React
<line-number
code={sourceCode}
language="typescript"
highlightedLines={[5, 10, 15]} // Highlight these lines
/>
// Solid
<line_number
code={sourceCode}
language="typescript"
highlightedLines={[5, 10, 15]}
/>
```
### Diagnostics
Show errors, warnings, and info on specific lines:
```tsx
// React
<line-number
code={sourceCode}
language="typescript"
diagnostics={[
{ line: 3, severity: "error", message: "Unexpected token" },
{ line: 7, severity: "warning", message: "Unused variable" },
{ line: 12, severity: "info", message: "Consider using const" },
]}
/>
// Solid
<line_number
code={sourceCode}
language="typescript"
diagnostics={[
{ line: 3, severity: "error", message: "Unexpected token" },
]}
/>
```
**Diagnostic severity levels:**
- `error` - Red indicator
- `warning` - Yellow indicator
- `info` - Blue indicator
- `hint` - Gray indicator
### Diff Highlighting
Show added/removed lines:
```tsx
<line-number
code={sourceCode}
language="typescript"
addedLines={[5, 6, 7]} // Green background
removedLines={[10, 11]} // Red background
/>
```
Other methods include `clearLineColor()`, `setLineColors()`,
`clearAllLineColors()`, `clearLineSign()`, `setLineSigns()`, and
`clearAllLineSigns()`. `lineNumberOffset` changes displayed numbering.
## Diff Component
Unified or split diff viewer with syntax highlighting.
### Basic Usage
`DiffRenderable` accepts a unified diff string. It does not compute a diff from
old and new source strings.
```tsx
// React
// React / Solid
<diff
oldCode={originalCode}
newCode={modifiedCode}
language="typescript"
/>
// Solid
<diff
oldCode={originalCode}
newCode={modifiedCode}
language="typescript"
diff={unifiedPatch}
filetype="typescript"
syntaxStyle={syntaxStyle}
view="split"
syncScroll
showLineNumbers
/>
// Core
const diffView = new DiffRenderable(renderer, {
id: "diff",
oldCode: originalCode,
newCode: modifiedCode,
language: "typescript",
const diff = new DiffRenderable(renderer, {
diff: unifiedPatch,
filetype: "typescript",
syntaxStyle,
view: "unified",
})
```
### Display Modes
```tsx
// Unified diff (default)
<diff
oldCode={old}
newCode={new}
mode="unified"
/>
// Split/side-by-side diff
<diff
oldCode={old}
newCode={new}
mode="split"
/>
```
### Synchronized Scrolling (Split View)
In split view, enable synchronized scrolling between left and right panes:
```tsx
// React/Solid
<diff
oldCode={old}
newCode={new}
mode="split"
syncScroll // Scrolling one pane syncs the other
/>
// Core
const diffView = new DiffRenderable(renderer, {
id: "diff",
diff: unifiedDiff,
view: "split",
syncScroll: true,
})
// Toggle at runtime
diffView.syncScroll = true
diffView.syncScroll = false
```
### Options
```tsx
<diff
oldCode={originalCode}
newCode={modifiedCode}
language="typescript"
mode="unified"
showLineNumbers
context={3} // Lines of context around changes
/>
```
| Option | Type / Default | Description |
|--------|----------------|-------------|
| `diff` | `string` | Unified patch input |
| `view` | `unified \| split` / `unified` | Display mode |
| `syncScroll` | `boolean` / `false` | Keep split panes aligned |
| `filetype` | `string` | Tree-sitter language |
| `syntaxStyle` | `SyntaxStyle` | Highlight style |
| `wrapMode` | `word \| char \| none` | Source wrapping |
| `conceal` | `boolean` / `false` | Conceal syntax tokens |
| `showLineNumbers` | `boolean` / `true` | Show line-number gutters |
| `addedBg`, `removedBg`, `contextBg` | `ColorInput` | Whole-line backgrounds |
| `addedContentBg`, `removedContentBg`, `contextContentBg` | `ColorInput` | Changed-content backgrounds |
| `addedLineNumberBg`, `removedLineNumberBg`, `lineNumberBg` | `ColorInput` | Gutter backgrounds |
| `addedSignColor`, `removedSignColor` | `ColorInput` | `+` and `-` colors |
### Styling
Use `view`, not `mode`; use `addedBg`/`removedBg`/`contextBg`, not
`addedLineColor`/`removedLineColor`/`unchangedLineColor`. Context lines are
already encoded in the patch, so there is no `context` option. For multi-file
input, Diff currently displays only the first parsed file patch.
```tsx
<diff
oldCode={old}
newCode={new}
addedLineColor="#2d4f2d" // Background for added lines
removedLineColor="#4f2d2d" // Background for removed lines
unchangedLineColor="transparent"
/>
```
### Line Highlighting API (Core)
Programmatically highlight specific lines in a diff:
### Programmatic Line Highlighting
```typescript
// Set a single line's color
diffView.setLineColor(5, "#2d4f2d")
diffView.setLineColor(5, { gutter: "#333", content: "#2d4f2d" })
// Clear a single line's color
diffView.clearLineColor(5)
// Set multiple lines at once
diffView.setLineColors(new Map([
[1, "#2d4f2d"],
[2, "#4f2d2d"],
diff.setLineColor(10, "#FFFF0030")
diff.clearLineColor(10)
diff.setLineColors(new Map([
[5, "#FF000030"],
[10, { bg: "#00FF0030", fg: "#FFFFFF" }],
]))
// Highlight a range
diffView.highlightLines(10, 20, "#2d4f2d")
diffView.clearHighlightLines(10, 20)
// Clear all line colors
diffView.clearAllLineColors()
diff.highlightLines(20, 25, "#0000FF30")
diff.clearHighlightLines(20, 25)
diff.clearAllLineColors()
```
The `LineNumberRenderable` also supports programmatic highlighting:
```typescript
lineNumberView.highlightLines(5, 10, "#2d4f2d")
lineNumberView.clearHighlightLines(5, 10)
```
### Hunk Navigation (Core)
`getHunkRowOffsets()` returns the visual row offset (0-based, accounting for
wrapping and concealed lines) where each diff hunk begins, in hunk order. Works
in both `"unified"` and `"split"` views.
```typescript
const offsets = diffView.getHunkRowOffsets() // number[]
// Jump to the next hunk below the current scroll position
const next = offsets.find((row) => row > diffView.scrollTop)
if (next !== undefined) diffView.scrollTop = next
// Jump to the previous hunk
const prev = [...offsets].reverse().find((row) => row < diffView.scrollTop)
if (prev !== undefined) diffView.scrollTop = prev
```
The result is cached and invalidated when the view rebuilds, `wrapMode` changes,
or line info changes.
`getHunkRowOffsets()` returns display-row offsets for parsed hunks. Re-read it
after changing the patch, view, wrapping, or dimensions.
## Markdown Component
Render markdown content with syntax highlighting for code blocks.
### Basic Usage
```tsx
// React
<markdown
content={markdownText}
syntaxStyle={mySyntaxStyle}
/>
// Solid
<markdown
content={markdownText}
syntaxStyle={mySyntaxStyle}
/>
// Core
import { MarkdownRenderable } from "@opentui/core"
const md = new MarkdownRenderable(renderer, {
id: "markdown",
content: "# Hello\n\nThis is **markdown**.",
syntaxStyle: mySyntaxStyle,
})
```
### Options
`MarkdownRenderable` parses Markdown into styled renderables. Pass a
`SyntaxStyle` for fenced code highlighting.
```tsx
<markdown
content={markdownText}
syntaxStyle={syntaxStyle} // Required
treeSitterClient={client} // Optional: custom tree-sitter client
conceal={true} // Hide markdown syntax characters (default true)
concealCode={false} // Conceal code fences too (default false)
streaming={true} // Enable streaming mode for incremental updates
internalBlockMode="coalesced" // "coalesced" (default) | "top-level"
tableOptions={{ // Customize markdown table rendering
style: "columns", // "grid" | "columns"
widthMode: "full", // "content" | "full"
wrapMode: "word", // "none" | "char" | "word"
cellPadding: 0,
borders: true,
outerBorder: true,
borderStyle: "single",
borderColor: "#555",
selectable: true, // Tables are selectable by default
}}
syntaxStyle={syntaxStyle}
conceal
concealCode={false}
streaming={false}
internalBlockMode="coalesced"
/>
```
**`internalBlockMode`**: `"top-level"` keeps each top-level block (heading,
paragraph, list, table, fenced code) as its own child renderable — required for
row-by-row committing of streamed output and for stable-block tracking. The
default `"coalesced"` folds siblings together (historical layout). When set to
`"top-level"`, `markdown._stableBlockCount` reports how many head-of-stream
blocks are currently stable.
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `content` | `string` | `""` | Markdown source |
| `syntaxStyle` | `SyntaxStyle` | - | Syntax colors |
| `treeSitterClient` | `TreeSitterClient` | shared | Parser client |
| `conceal` | `boolean` | `true` | Hide Markdown markers |
| `concealCode` | `boolean` | `false` | Hide fenced-code markers |
| `streaming` | `boolean` | `false` | Optimize append-only content |
| `internalBlockMode` | `coalesced \| top-level` | `coalesced` | Internal block grouping |
| `tableOptions` | `MarkdownTableOptions` | - | Table layout and border options |
### Custom Node Rendering
```tsx
// Core
const md = new MarkdownRenderable(renderer, {
id: "markdown",
`renderNode` receives `(token, context)`. Return a custom renderable,
`context.defaultRender()` for the built-in representation, or `null`/
`undefined` as appropriate.
```typescript
const markdown = new MarkdownRenderable(renderer, {
content: "# Custom Heading",
syntaxStyle,
renderNode: (node, ctx, defaultRender) => {
if (node.type === "heading") {
// Return custom renderable for headings
return new TextRenderable(ctx, {
content: `>> ${node.content} <<`,
})
renderNode(token, context) {
if (token.type === "heading") {
return new TextRenderable(renderer, { content: `>> ${token.text} <<` })
}
return null // Use default rendering
return context.defaultRender()
},
})
```
### Custom Code Block Renderers
For fenced-code specialization, use `createMarkdownCodeBlockRenderer()` to
dispatch normalized filetypes to custom renderers while retaining the default
renderer for unmatched tokens.
`createMarkdownCodeBlockRenderer` builds a `renderNode` that only overrides
fenced code blocks, keyed by the **normalized** fence info string (e.g. `tsx` →
`typescriptreact`; custom names like `taskflow` match directly):
```typescript
import { createMarkdownCodeBlockRenderer, MarkdownRenderable } from "@opentui/core"
const renderNode = createMarkdownCodeBlockRenderer({
mermaid: (token, ctx) => renderMermaidDiagram(ctx, token.text),
taskflow: (token, ctx) => renderTaskflow(ctx, token.text),
})
const md = new MarkdownRenderable(renderer, {
id: "markdown",
content,
syntaxStyle,
renderNode, // Only the matched fences are replaced; others render normally
})
```
Each renderer receives `(token: Tokens.Code, context: RenderNodeContext)` and
returns a `Renderable`, or `undefined`/`null` to fall back to default rendering.
### Streaming Mode
For real-time content like LLM output:
### Streaming Markdown
```tsx
const [content, setContent] = useState("")
// Append text as it arrives
useEffect(() => {
llmStream.on("token", (token) => {
setContent(c => c + token)
})
}, [])
<markdown
content={content}
content={streamedContent}
syntaxStyle={syntaxStyle}
streaming={true} // Optimizes for incremental updates
streaming={isStreaming}
internalBlockMode="top-level"
/>
```
In Core, set `markdown.streaming = true` while appending chunks (assign or `+=`
to `markdown.content`; each change reparses incrementally). Set
`markdown.streaming = false` when the stream completes to finalize trailing
block parsing. Use `internalBlockMode: "top-level"` if you need per-block commit
boundaries (`markdown._stableBlockCount`).
## Use Cases
### Code Editor
```tsx
function CodeEditor() {
const [code, setCode] = useState(`function hello() {
console.log("Hello!");
}`)
return (
<box flexDirection="column" height="100%">
<box height={1}>
<text>editor.ts</text>
</box>
<textarea
value={code}
onChange={setCode}
language="typescript"
showLineNumbers
flexGrow={1}
focused
/>
</box>
)
}
```
### Code Review
```tsx
function CodeReview({ oldCode, newCode }) {
return (
<box flexDirection="column" height="100%">
<box height={1} backgroundColor="#333">
<text>Changes in src/utils.ts</text>
</box>
<diff
oldCode={oldCode}
newCode={newCode}
language="typescript"
mode="split"
showLineNumbers
/>
</box>
)
}
```
### Syntax-Highlighted Preview
```tsx
function MarkdownPreview({ content }) {
// Extract code blocks from markdown
const codeBlocks = extractCodeBlocks(content)
return (
<scrollbox height={20}>
{codeBlocks.map((block, i) => (
<box key={i} marginBottom={1}>
<code
code={block.code}
language={block.language}
/>
</box>
))}
</scrollbox>
)
}
```
### Error Display
```tsx
function ErrorView({ errors, code }) {
const diagnostics = errors.map(err => ({
line: err.line,
severity: "error",
message: err.message,
}))
return (
<line-number
code={code}
language="typescript"
diagnostics={diagnostics}
highlightedLines={errors.map(e => e.line)}
/>
)
}
```
Keep `streaming` true while appending and set it false when complete so the
final parse can settle. `top-level` mode exposes stable top-level blocks, which
is useful for LLM output and incremental views.
## Gotchas
### Solid Uses Underscores
- React uses `<line-number>`; Solid uses `<line_number>`.
- Code uses `content` and `filetype`, not `code` and `language`.
- Diff uses one unified `diff` string and `view`, not old/new strings and
`mode`.
- Line Number wraps a target; it does not render source code by itself.
- Tree-sitter loading is asynchronous. Use `OTUI_TREE_SITTER_WORKER_PATH` when
packaging requires a custom worker path.
- Put large Code/Line Number views inside a height-constrained ScrollBox.
```tsx
// React
<line-number />
## See Also
// Solid
<line_number />
```
### Language Required for Highlighting
```tsx
// No highlighting (plain text)
<code code={text} />
// With highlighting
<code code={text} language="typescript" />
```
### Large Files
For very large files, consider:
- Pagination or virtual scrolling
- Loading only visible portion
- Using `scrollbox` wrapper
```tsx
<scrollbox height={30}>
<line-number
code={largeFile}
language="typescript"
/>
</scrollbox>
```
### Tree-sitter Loading
Syntax highlighting requires Tree-sitter grammars. If highlighting isn't working:
1. Check the language is supported
2. Verify grammars are installed
3. Check `OTUI_TREE_SITTER_WORKER_PATH` if using custom path
- [Text & Display](./text-display.md) - Styled text and image rendering
- [Containers](./containers.md) - ScrollBox for large content
- [Core API](../core/api.md) - Imperative renderables
- [Testing](../testing/REFERENCE.md) - Frame and snapshot tests
@@ -30,19 +30,14 @@ box.add(child)
<box
border
borderStyle="single" // single | double | rounded | bold | none
borderStyle="single" // single | double | rounded | heavy
borderColor="#FFFFFF"
>
Styled border
</box>
// Individual borders
<box
borderTop
borderBottom
borderLeft={false}
borderRight={false}
>
// Selected sides
<box border={["top", "bottom"]}>
Top and bottom only
</box>
```
@@ -54,7 +49,7 @@ box.add(child)
| `single` | `┌─┐│ │└─┘` |
| `double` | `╔═╗║ ║╚═╝` |
| `rounded` | `╭─╮│ │╰─╯` |
| `bold` | `┏━┓┃ ┃┗━┛` |
| `heavy` | `┏━┓┃ ┃┗━┛` |
### Title
@@ -317,6 +312,42 @@ When focused: arrows / `hjkl`, `PageUp`/`PageDown`, `Home`/`End`.
> `ScrollBarRenderable` only when you need a scrollbar decoupled from a
> `scrollbox` viewport.
## Embedded Terminal Component
`EmbeddedTerminalRenderable` is a Core-only Ghostty VT parser and screen. It is
not a process or PTY: write child output into it and send `onData` bytes back to
the child.
```typescript
import { EmbeddedTerminalRenderable } from "@opentui/core"
const terminal = new EmbeddedTerminalRenderable(renderer, {
width: 80,
height: 24,
maxScrollback: 10_000, // Bytes, not lines
onData(data, source) {
child.write(data) // source is "input" or "response"
},
onTerminalResize(cols, rows) {
child.resize(cols, rows)
},
})
renderer.root.add(terminal)
terminal.write(childOutput) // string | Uint8Array
terminal.focus()
```
Key methods are `write()`, `encodeKey()`, `encodePaste()`, `screen()`,
`invalidate()`, `focus()`, and `blur()`. The renderable handles focused key,
paste, mouse, cursor, scrollback, and selection behavior. `selectable` defaults
to `true`; `cols`/`rows` default to numeric layout dimensions or `80x24`.
Destroy the child and renderable together.
React and Solid do not register an element for this component. Use Core or
register an adapter with `extend()`; catalogue registration alone cannot supply
non-default constructor-only `cols`, `rows`, or `maxScrollback` in Solid.
## Composition Patterns
### Card Component
@@ -331,9 +362,7 @@ function Card({ title, children }) {
marginBottom={1}
>
{title && (
<text fg="#00FFFF" bold>
{title}
</text>
<text fg="#00FFFF"><strong>{title}</strong></text>
)}
<box marginTop={title ? 1 : 0}>
{children}
@@ -356,11 +385,11 @@ function Panel({ title, children, width = 40 }) {
>
{title && (
<box
borderBottom
border={["bottom"]}
padding={1}
backgroundColor="#2a2a4e"
>
<text bold>{title}</text>
<text><strong>{title}</strong></text>
</box>
)}
<box padding={2}>
+28 -26
View File
@@ -108,20 +108,9 @@ Multi-line text input field.
### Basic Usage
```tsx
// React
// React / Solid (Textarea is imperative, not a controlled input)
<textarea
value={text}
onChange={(newText) => setText(newText)}
placeholder="Enter multiple lines..."
width={40}
height={10}
focused
/>
// Solid
<textarea
value={text()}
onInput={(newText) => setText(newText)}
initialValue="Draft text"
placeholder="Enter multiple lines..."
width={40}
height={10}
@@ -141,23 +130,36 @@ const textarea = new TextareaRenderable(renderer, {
```tsx
<textarea
showLineNumbers // Display line numbers
wrapText // Wrap long lines
readOnly // Disable editing
tabSize={2} // Tab character width
initialValue="Draft"
wrapMode="word" // "none" | "char" | "word"
selectionOccupancy="boundary" // Half-open insert-style selection
cursorStyle={{ style: "line" }}
/>
```
### Syntax Highlighting
Textarea does not expose controlled `value`/`onChange`, `language`,
`showLineNumbers`, `readOnly`, `wrapText`, or `tabSize` props. Keep a renderable
ref, use `plainText`/`setText()`, and listen with `onContentChange`. For syntax
highlighting, create and pass a `SyntaxStyle`; compose a
`LineNumberRenderable` when line numbers are needed.
```tsx
<textarea
language="typescript"
value={code}
onChange={setCode}
/>
### Cursor, Selection, and Tab Width
```typescript
textarea.gotoVisualLineEnd({ select: true })
textarea.setSelection(start, end) // Half-open [start, end)
textarea.setSelectionInclusive(start, end) // Includes end grapheme in cell mode
textarea.clearSelection()
textarea.editBuffer.setTabWidth(4)
console.log(textarea.editBuffer.getTabWidth())
```
`selectionOccupancy` is `"cell"` (default, both endpoint cells) or
`"boundary"` (half-open insertion range). Cursor style only changes paint; use
boundary occupancy with a line/bar cursor when insert-style selection is
desired.
## Select Component
List selection for choosing from options.
@@ -224,7 +226,6 @@ interface SelectOption {
showSelectionIndicator={true} // Show "▶ " marker + gutter (default true)
selectedBackgroundColor="#333"
selectedTextColor="#fff"
highlightBackgroundColor="#444"
/>
```
@@ -237,6 +238,7 @@ interface SelectOption {
Default keybindings:
- `Up` / `k` - Move up
- `Down` / `j` - Move down
- `Shift+Up` / `Shift+Down` - Move by `fastScrollStep` (default 5)
- `Enter` - Select item
### Events
@@ -433,7 +435,7 @@ function Form() {
```typescript
input.focus() // Give focus
input.blur() // Remove focus
input.isFocused() // Check focus state
input.focused // Check focus state
```
## Form Patterns
@@ -200,6 +200,9 @@ const title = new ASCIIFontRenderable(renderer, {
| `block` | Block-style letters |
| `slick` | Sleek modern style |
| `shade` | Shaded 3D effect |
| `huge` | Large font |
| `grid` | Grid-style font |
| `pallet` | Pallet-style font |
### Styling
@@ -235,6 +238,98 @@ Font: block
▀▀▀▀ ▀ ▀▀▀ ▀ ▀
```
## Image Component
Display PNG, JPEG, WebP, GIF, or raw image data. OpenTUI chooses Kitty,
Sixel, or Unicode block rendering based on terminal capabilities.
```tsx
// React and Solid
<image source="./cover.webp" fit="cover" protocol="auto" width={40} height={15} />
// Core
const image = new ImageRenderable(renderer, {
source: "./cover.webp",
width: 40,
height: 15,
fit: "cover",
protocol: "auto",
onError: console.error,
})
renderer.root.add(image)
await image.loadPromise
```
`source` accepts a path, supported URL, `URL`, `Blob`, `Response`,
`Uint8Array`, `ArrayBuffer`, or `NativeImage`. Replacing `source` keeps the
current image visible until the replacement succeeds.
| Option | Values | Description |
|--------|--------|-------------|
| `fit` | `fit`, `cover`, `fill` | Contain (default), crop, or stretch |
| `protocol` | `auto`, `kitty`, `sixel`, `blocks` | Requested terminal rendering protocol |
| `onLoad` | `(image: NativeImage) => void` | Current source loaded |
| `onError` | `(error: unknown) => void` | Current source failed |
State includes `image`, `loading`, `loadError`, `loadPromise`,
`effectiveProtocol`, and `getFittedSize()`. Set
`OPENTUI_IMAGE_PROTOCOL=auto|kitty|sixel|blocks` for a global default;
`OPENTUI_GRAPHICS=false` disables Kitty and Sixel detection.
### NativeImage
Use `NativeImage` when you need to inspect, transform, or share decoded pixels:
```typescript
import { NativeImage, imageInfo } from "@opentui/core"
const source = await NativeImage.load("photo.jpg")
const thumbnail = source.resize({ width: 320 })
const shared = thumbnail.retain() // Independent handle, no pixel copy
try {
console.log(imageInfo(await Bun.file("photo.jpg").arrayBuffer()))
const rgba = thumbnail.raw("rgba8")
} finally {
shared.dispose()
thumbnail.dispose()
source.dispose()
}
```
Creation methods are `load()`, `decode()`, and `fromRgba()`. Pixel methods are
`raw()`, `copyTo()`, and ownership-transferring `takeRaw()`. Transform methods
include `resize()`, `extract()`, `extend()`, `rotate()`, `flip()`, `flop()`, and
`composite()`. `retain()` shares storage, `clone()` copies it, and every returned
native handle must be disposed separately. `ensureEncodedPng()` prepares an
encoded PNG for low-level native consumers. `ImageRenderable` retains a supplied
`NativeImage`, so the caller still owns and must dispose its source reference.
## Time to First Draw
`TimeToFirstDrawRenderable` is a rendering diagnostic. It captures
`performance.now()` on its first draw; this is a runtime-relative timestamp,
not elapsed application startup time.
```tsx
// React
<time-to-first-draw label="First draw timestamp" precision={1} />
// Solid
<time_to_first_draw label="First draw timestamp" precision={1} />
// Core
const firstDraw = new TimeToFirstDrawRenderable(renderer, {
label: "First draw timestamp",
precision: 1,
})
renderer.root.add(firstDraw)
```
React and Solid also export a `TimeToFirstDraw` wrapper. `runtimeMs` is `null`
before the first draw; call `reset()` to capture again. Keep `precision` an
integer from 0 through 100.
## QR Code Component
Render a QR code in the terminal. Ships as a **separate package**,
+4 -2
View File
@@ -113,7 +113,7 @@ bun test # Run tests
## Runtime Requirements
OpenTUI runs on **Bun (reference runtime)** and uses Zig for native builds.
**Node.js 26.3.0** is also supported for the native renderer when launched with
**Node.js 26.4.0 or later** is also supported for the native renderer when launched with
`--experimental-ffi`; importing core/keymap without a native renderer works on
Node without FFI. See [Gotchas](./gotchas.md) for the full Node.js notes.
@@ -133,7 +133,9 @@ bun run build
## Additional Capabilities
- **Audio** — native audio engine via `Audio` from `@opentui/core`. See [API](./api.md#audio).
- **Audio** — loaded sounds, MP3/FLAC streams, input capture, and WAV recording via `Audio`. See [API](./api.md#audio).
- **Images** — decode and display PNG, JPEG, WebP, and GIF content. See [Text & Display](../components/text-display.md#image-component).
- **Clipboard** — combine native host reads/writes with terminal OSC 52. See [Keyboard](../keyboard/REFERENCE.md#clipboard-services).
- **Notifications** — `renderer.triggerNotification(message, title?)` (OSC 9/777/99). See [API](./api.md).
- **SSH** — serve a TUI over SSH with the `@opentui/ssh` package:
+108 -8
View File
@@ -10,7 +10,8 @@ Creates and initializes the CLI renderer.
import { createCliRenderer, type CliRendererConfig } from "@opentui/core"
const renderer = await createCliRenderer({
targetFPS: 60, // Target frames per second
targetFps: 30, // Continuous rendering target (default: 30)
maxFps: 60, // Cap immediate re-renders (default: 60)
exitOnCtrlC: true, // Exit process on Ctrl+C
consoleOptions: { // Debug console overlay
position: ConsolePosition.BOTTOM,
@@ -34,6 +35,7 @@ const renderer = await createCliRenderer({
width: cols, // Fallback columns for non-TTY / custom stdout
height: rows, // Fallback rows for non-TTY / custom stdout
remote: true, // Treat output as a remote terminal (auto-detects SSH/mosh for process.stdout)
forwardEnvKeys: [], // Local env names forwarded to remote capability detection
exitOnCtrlC: false,
})
@@ -52,6 +54,10 @@ Size resolution order: `stdout.columns/rows` → `config.width/height` → `80x2
Env overrides: `OTUI_OVERRIDE_STDOUT` (force stdout routing),
`OTUI_USE_ALTERNATE_SCREEN`.
A feed-backed custom `stdout` defaults to `remote: true` and forwards no local
environment values. Pass only terminal-related names that genuinely describe
the remote terminal in `forwardEnvKeys`.
### CliRenderer Instance
```typescript
@@ -103,8 +109,14 @@ renderer.on("memory:snapshot", (snapshot) => {}) // Memory snapshot
renderer.on("debugOverlay:toggle", () => {}) // Debug overlay toggled
renderer.on("frame", ({ frameId }) => {}) // A frame was committed
renderer.on("focused_renderable", (current, previous) => {}) // Focus moved
renderer.on("render:error", ({ error, renderable }) => {}) // Render pass threw
renderer.on("handler:error", ({ error, event }) => {}) // Mouse handler threw
```
If neither error event has a listener, OpenTUI logs the error. During a render
error, `renderable` identifies the node that was executing when available.
Mouse events expose both their original `target` and bubbling `currentTarget`.
### Scheduler & Idle
```typescript
@@ -130,7 +142,10 @@ tmux requires `set -g allow-passthrough on`; Zellij uses OSC 99. Env overrides:
### Audio
Native audio engine exported from `@opentui/core`.
Native playback, streaming, capture, and recording exported from
`@opentui/core`.
#### Loaded Sounds
```typescript
import { Audio } from "@opentui/core"
@@ -142,7 +157,11 @@ const sound = await audio.loadSoundFile("click.wav")
if (sound != null && audio.start()) {
audio.play(sound, { volume: 0.8, pan: 0, loop: false })
}
audio.dispose()
// Keep the engine alive while playback is active. Stop/dispose it during
// application cleanup, not immediately after play().
// audio.stop()
// audio.dispose()
```
Key methods: `start()`, `stop()`, `loadSound(data)`, `loadSoundFile(path)`,
@@ -150,6 +169,76 @@ Key methods: `start()`, `stop()`, `loadSound(data)`, `loadSoundFile(path)`,
`setMasterVolume()`, `listPlaybackDevices()`, `getStats()`, `dispose()`.
`AudioPlayOptions`: `{ volume?, pan?, loop?, groupId? }` (32 voice slots).
#### Streaming MP3 or FLAC
Start playback before creating a stream. Setup errors reject the entry method;
later errors are `AudioStream` events, so attach an error listener immediately.
```typescript
import { Audio, type AudioStream } from "@opentui/core"
const audio = Audio.create({ autoStart: false })
const abortController = new AbortController()
audio.on("error", (error, context) => console.error(context.action, error))
if (!audio.start()) throw new Error("No playback device")
const stream: AudioStream = await audio.playStreamUrl("https://example.com/radio.mp3", {
format: "mp3", // "mp3" | "flac"
buffer: { capacityMs: 2000, startupMs: 1000, resumeMs: 1000 },
reconnect: { maxRetries: 5 },
signal: abortController.signal,
})
stream.on("error", (error, context) => console.error(context.action, error))
stream.on("metadata", (metadata) => console.log(metadata)) // ICY metadata for URL streams
await stream.closed
```
Choose the source API by ownership:
| Method | Source policy |
|--------|---------------|
| `playStream(source, options?)` | One `ReadableStream<Uint8Array>` or `AsyncIterable<Uint8Array>` to EOF |
| `playStreamUrl(url, options?)` | Fetch, content-type validation, ICY metadata, optional reconnect |
| `playStreamSource(connector, options?)` | Custom connection and per-connection demuxer |
`AudioStream` exposes `state`, `closed`, `getStats()`, `getMetadata()`,
`setVolume()`, `setPan()`, `setGroup()`, and `dispose()`. Use
`createIcyStreamDemuxer()` for ICY framing on custom transports. Streaming does
not support WAV, AAC, Ogg, Opus, HLS, seeking, or pause.
#### Input Capture and WAV Recording
Capture is independent of playback. One `Audio` engine permits one capture
owner at a time.
```typescript
const capture = await audio.openCapture({ channels: 1, chunkFrames: 2048 })
capture.on("error", (error, context) => console.error(context.action, error))
const consumption = (async () => {
for await (const pcm of capture.readable) {
processFloat32Pcm(pcm, capture.channels)
}
})()
await new Promise((resolve) => setTimeout(resolve, 1000))
capture.stop() // Gracefully drains unread PCM
await consumption
await capture.closed
const recorder = await audio.recordToFile("recording.wav", { channels: 1 })
recorder.on("error", (error, context) => console.error(context.action, error))
await new Promise((resolve) => setTimeout(resolve, 1000))
recorder.stop() // Finalizes and publishes PCM16 WAV
await recorder.closed
```
`openCapture()` returns an `AudioCaptureStream` with `readable`, `state`,
`getStats()`, `stop()`, `dispose()`, and `closed`. `recordToFile()` returns an
`AudioRecorder` with the same lifecycle plus `filePath` and `format: "wav"`.
For polling, use `startCapture()`, `readCaptureFrames()`, `getCaptureStats()`,
and `stopCapture()`. Device APIs are `listCaptureDevices()`,
`selectCaptureDevice()`, and `clearCaptureDeviceSelection()`. Microphone
permissions and device availability are platform-dependent.
### Console Overlay
```typescript
@@ -167,7 +256,7 @@ All renderables extend the base `Renderable` class and share common properties.
```typescript
interface CommonProps {
id?: string // Unique identifier
id?: string // Identifier; duplicate IDs are allowed
// Positioning
position?: "relative" | "absolute"
@@ -209,7 +298,7 @@ interface CommonProps {
gap?: number
// Display
display?: "flex" | "none"
visible?: boolean
overflow?: "visible" | "hidden" | "scroll"
zIndex?: number
}
@@ -262,6 +351,10 @@ const styled = new TextRenderable(renderer, {
- `TextAttributes.HIDDEN`
- `TextAttributes.STRIKETHROUGH`
`createTextAttributes({ bold, italic, underline, dim, blink, inverse, reverse,
hidden, strikethrough })` builds the bit mask. `reverse` is an alias for
`inverse`.
### Box, Input, Select, Tab Select, ScrollBox, ASCII Font
Every component is `new <Name>Renderable(renderer, options)`, composed with
@@ -317,8 +410,12 @@ const canvas = new FrameBufferRenderable(renderer, {
canvas.frameBuffer.fillRect(10, 5, 20, 8, RGBA.fromHex("#FF0000"))
canvas.frameBuffer.drawText("Custom", 12, 7, RGBA.fromHex("#FFFFFF"))
canvas.frameBuffer.setCell(x, y, char, fg, bg)
canvas.frameBuffer.drawImage(nativeImage, x, y, width, height)
```
See [Image Component](../components/text-display.md#image-component) for
`NativeImage` ownership and terminal graphics protocols.
## Constructs (VNode API)
Declarative wrappers that create VNodes instead of direct instances.
@@ -467,15 +564,15 @@ timeline.add(
{
width: 50,
duration: 1000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
box.setWidth(anim.targets[0].width)
box.width = anim.targets[0].width
},
},
)
engine.attach(renderer)
engine.addTimeline(timeline)
engine.register(timeline)
```
## Type Exports
@@ -487,6 +584,9 @@ import type {
RenderContext,
KeyEvent,
Renderable,
WidthMethod, // "wcwidth" | "unicode" | "unicode-wide"
SelectionOccupancy, // "cell" | "boundary"
SelectionBehavior, // "cell" | "word" | "line"
// ... and more
} from "@opentui/core"
```
+38 -5
View File
@@ -9,10 +9,15 @@ import { createCliRenderer, ConsolePosition } from "@opentui/core"
const renderer = await createCliRenderer({
// Rendering
targetFPS: 60, // Target frames per second (default: 60)
targetFps: 30, // Continuous rendering target (default: 30)
maxFps: 60, // Immediate render cap (default: 60)
// Behavior
exitOnCtrlC: true, // Exit on Ctrl+C (default: true)
useMouse: true, // Enable mouse input (default: true)
autoFocus: true, // Focus nearest focusable node on click
screenMode: "alternate-screen", // "alternate-screen" | "main-screen" | "split-footer"
externalOutputMode: "passthrough", // Or "capture-stdout" in split-footer mode
// Console overlay
consoleOptions: {
@@ -45,12 +50,14 @@ OpenTUI respects several environment variables for configuration and debugging.
| `OTUI_TRACE_FFI` | boolean | false | Tracing for FFI bindings |
| `OTUI_SHOW_STATS` | boolean | false | Show debug overlay at startup |
| `OTUI_DUMP_CAPTURES` | boolean | false | Dump captured output on exit |
| `OTUI_STDIN_LOG` | string | "" | Write raw stdin bytes to a file (may contain secrets) |
| `OTUI_GHOSTTY_LOG_LEVEL` | string | "" | Ghostty logs: `error`, `warn`, `info`, or `debug` |
### Console
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `OTUI_USE_CONSOLE` | boolean | true | Enable console capture |
| `OTUI_USE_CONSOLE` | boolean | true | Enable global `console.*` capture and activation |
| `SHOW_CONSOLE` | boolean | false | Show console at startup |
### Rendering
@@ -65,7 +72,8 @@ OpenTUI respects several environment variables for configuration and debugging.
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `OPENTUI_NO_GRAPHICS` | boolean | false | Disable Kitty graphics protocol |
| `OPENTUI_GRAPHICS` | string | automatic | `false`/`0` disables Kitty and Sixel detection; `true`/`1` keeps auto-detection |
| `OPENTUI_IMAGE_PROTOCOL` | string | `auto` | `auto`, `kitty`, `sixel`, or `blocks` |
| `OPENTUI_FORCE_UNICODE` | boolean | false | Force Mode 2026 Unicode support |
| `OPENTUI_FORCE_WCWIDTH` | boolean | false | Use wcwidth for character width |
| `OPENTUI_FORCE_NOZWJ` | boolean | false | Disable ZWJ emoji joining |
@@ -78,6 +86,13 @@ OpenTUI respects several environment variables for configuration and debugging.
| `OTUI_TS_STYLE_WARN` | boolean | false | Warn on missing syntax styles |
| `OTUI_TREE_SITTER_WORKER_PATH` | string | "" | Custom tree-sitter worker path |
### Runtime Assets
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `OPENTUI_LIBC` | string | `glibc` | Select `glibc` or `musl` on Linux before the first Core import |
| `OTUI_ASSET_ROOT` | string | "" | Absolute root for relocated native, worker, grammar, and WASM assets |
### XDG Paths
| Variable | Type | Default | Description |
@@ -106,8 +121,8 @@ OTUI_NO_NATIVE_RENDER=true bun run src/index.ts
# Force wcwidth for problematic terminals
OPENTUI_FORCE_WCWIDTH=true bun run src/index.ts
# Disable graphics for SSH sessions
OPENTUI_NO_GRAPHICS=true bun run src/index.ts
# Disable Kitty and Sixel detection for a remote session
OPENTUI_GRAPHICS=false bun run src/index.ts
```
## Project Setup
@@ -166,3 +181,21 @@ bun run build
```
**Note**: TypeScript changes do NOT require building. Bun runs TypeScript directly.
## Standalone Executables
Bun embeds OpenTUI runtime assets directly:
```bash
bun build --compile ./src/index.ts --outfile app
```
For a Linux musl target, define `process.env.OPENTUI_LIBC` as `"musl"` at
build time so Bun retains only that native-package branch.
Node SEA builds require Node.js 26.4.0+, ESM, and `--experimental-ffi`. At
build time import `getNodeAssets()` from `@opentui/core/node-assets`, embed every
returned `{ key, source }`, extract those exact keys at startup, and set the
absolute `OTUI_ASSET_ROOT` before bundled Core code executes. Do not call
`getNodeAssets()` from the finished executable. The root export
`resolveBundledFilePath()` resolves runtime assets for custom packaging.
+8 -8
View File
@@ -2,7 +2,7 @@
## Runtime Environment
### Bun (reference runtime) or Node.js 26.3.0
### Bun (reference runtime) or Node.js 26.4.0+
Bun is the reference runtime and the smoothest path — prefer it for new projects:
@@ -18,7 +18,7 @@ bun test
- Importing `@opentui/core` (and `@opentui/keymap`) works in Node.js **without
FFI** as long as you don't create a native renderer.
- Creating a **native renderer** (`createCliRenderer()`) requires FFI: **Node.js
26.3.0** launched with `--experimental-ffi` (and, under Node's permission
26.4.0 or later** launched with `--experimental-ffi` (and, under Node's permission
model, `--allow-ffi` plus filesystem permissions). OpenTUI does not install
Node for you.
- The Node path is lower-level than Bun; the `packages/*/package.json` `engines`
@@ -243,7 +243,7 @@ Yoga layout is calculated lazily. Force a recalculation:
```typescript
// After changing layout properties
box.setWidth(newWidth)
box.width = newWidth
renderer.requestRender()
```
@@ -311,14 +311,14 @@ Box({}, Box({}, Box({}, Text({ content: "Hello" }))))
Box({}, Text({ content: "Hello" }))
```
### Use display: none
### Toggle visibility
Hide elements instead of removing/re-adding:
```typescript
// For toggling visibility
element.setDisplay("none") // Hidden
element.setDisplay("flex") // Visible
element.visible = false // Hidden and removed from layout
element.visible = true // Visible
// Instead of
parent.remove(element)
@@ -356,8 +356,8 @@ bun run test:native
### Filter Tests
```bash
# Bun test filter
bun test --filter "component name"
# Bun test-name filter
bun test --test-name-pattern "component name"
# Native test filter
bun run test:native -Dtest-filter="test name"
+57 -10
View File
@@ -430,12 +430,12 @@ renderer.keyInput.on("paste", (event: PasteEvent) => {
})
```
### Solid
### React and Solid
Solid provides a dedicated `usePaste` hook:
Both reconciler packages provide a dedicated `usePaste` hook:
```tsx
import { usePaste } from "@opentui/solid"
import { usePaste } from "@opentui/react" // or @opentui/solid
import { decodePasteBytes } from "@opentui/core"
function App() {
@@ -448,12 +448,17 @@ function App() {
}
```
> **Note**: `usePaste` is **Solid-only**. React does not have this hook - handle paste via the Core event emitter or input component's `onChange`.
## Text Selection
Text selection is renderer-managed. The renderer owns a single `Selection` object, walks the renderable tree to find selectable children, and emits a `"selection"` event when the user finishes selecting (mouse-up). The `Selection` object aggregates text from all selected renderables automatically.
Text-buffer renderables use repeated left-button presses: a first press/drag
selects cells, a second press selects a word, and a third press selects a
logical line (including soft wraps). Repeated presses must hit the same
renderable within 500 ms and within one cell. Dragging after the second or third
press extends by words or lines. ASCII Font, TextTable, and Embedded Terminal
keep component-specific cell selection.
### Making Renderables Selectable
A renderable must have `selectable` set to `true` to participate in selection. Text-based renderables (`TextRenderable`, `TextareaRenderable`, `ASCIIFontRenderable`, `TextTableRenderable`) support this:
@@ -487,10 +492,10 @@ renderer.on("selection", (selection: Selection) => {
> **Important**: Call `selection.getSelectedText()` on the `Selection` object from the event -- not `renderer.root.getSelectedText()`. Individual renderables only return their own selected text. The `Selection` object aggregates across the tree.
### Copy-on-Selection (Solid)
### Copy-on-Selection (React or Solid)
```tsx
import { useSelectionHandler } from "@opentui/solid"
import { useSelectionHandler } from "@opentui/react" // or @opentui/solid
function App() {
useSelectionHandler((selection) => {
@@ -504,8 +509,6 @@ function App() {
}
```
> **Note**: `useSelectionHandler` is **Solid-only**. React does not have this hook -- use the Core `renderer.on("selection", ...)` event.
### Selection Object
The `Selection` object passed to the event callback:
@@ -515,8 +518,15 @@ selection.getSelectedText() // Aggregated text from all selected renderabl
selection.bounds // { startX, startY, endX, endY } bounding rect
selection.selectedRenderables // Renderable[] with active selections
selection.isActive // Whether selection is still active
selection.behavior // "cell" | "word" | "line"
selection.anchor // Global anchor cell
selection.focus // Global focus cell
```
For text-buffer renderables, `getSelection()` returns a half-open
`{ start, end }` range measured in terminal display columns; line breaks add
one unit. These offsets are not JavaScript UTF-16 string indexes.
Individual renderables also expose:
```typescript
@@ -534,7 +544,44 @@ When the user drags to select, the renderer:
This means selection works across multiple renderables. Dragging across two `<text selectable>` elements selects text in both, and `selection.getSelectedText()` joins them with newlines.
## Clipboard API (OSC 52)
## Clipboard Services
Use the composed clipboard service when an application needs host reads/writes
or needs to choose safely between the host and terminal clipboard:
```typescript
import {
createClipboard,
createHostClipboard,
createRendererClipboardAdapter,
} from "@opentui/core"
const clipboard = createClipboard({
host: createHostClipboard(),
terminal: createRendererClipboardAdapter(renderer),
})
await clipboard.writeText("Hello", { destination: "best-available" })
const result = await clipboard.read({ preferredTypes: ["text/plain"] })
if (result.status === "read") {
console.log(new TextDecoder().decode(result.representation.bytes))
}
await clipboard.dispose()
```
Write/clear destinations are `terminal-only`, `host-only`, `best-available`,
and `all-available`. In a remote session, the host clipboard belongs to the
server; host operations are skipped unless `allowRemoteHost: true`, while the
terminal adapter sends OSC 52 to the remote client. Reads always use the process
host. `ClipboardService` owns its host service, and `renderer.destroy()` does
not dispose a clipboard service created by the application.
Use `createHostClipboard()` by itself when no renderer is available. Host reads
accept ordered MIME preferences and can return text or platform-supported image
data. Operations support `AbortSignal`, timeouts, size limits, and `clipboard`
or Linux `primary` selection.
### Low-level OSC 52
Copy text to the system clipboard using OSC 52 escape sequences. Works over SSH and in most modern terminal emulators.
+5 -3
View File
@@ -161,10 +161,12 @@ Initial size before growing/shrinking:
```tsx
<box flexDirection="row">
<box flexBasis={20} flexGrow={1}>Starts at 20, can grow</box>
<box flexBasis="50%">Half of parent</box>
<box flexBasis="auto">Use measured content as the basis</box>
</box>
```
`flexBasis` accepts a cell count or `"auto"`; it does not accept percentages.
### alignSelf
Override parent's alignItems for this child:
@@ -298,10 +300,10 @@ Element positioned relative to nearest positioned ancestor:
```tsx
// Visible (default)
<box display="flex">Visible</box>
<box visible>Visible</box>
// Hidden (removed from layout)
<box display="none">Hidden</box>
<box visible={false}>Hidden</box>
```
## Overflow
+4 -4
View File
@@ -25,7 +25,7 @@ function AppLayout() {
return (
<box flexDirection="column" width="100%" height="100%">
{/* Header - fixed height */}
<box height={3} borderStyle="single" borderBottom>
<box height={3} borderStyle="single" border={["bottom"]}>
<text>Header</text>
</box>
@@ -50,7 +50,7 @@ function SidebarLayout() {
return (
<box flexDirection="row" width="100%" height="100%">
{/* Sidebar - fixed width */}
<box width={25} borderStyle="single" borderRight>
<box width={25} borderStyle="single" border={["right"]}>
<text>Sidebar</text>
</box>
@@ -140,7 +140,7 @@ function Modal({ children, visible }) {
height="100%"
justifyContent="center"
alignItems="center"
backgroundColor="rgba(0,0,0,0.5)"
backgroundColor="#00000080"
>
<box
width={50}
@@ -255,7 +255,7 @@ function LoginForm() {
```tsx
function TabBar({ tabs, activeIndex, onSelect }) {
return (
<box flexDirection="row" borderBottom>
<box flexDirection="row" border={["bottom"]}>
{tabs.map((tab, i) => (
<box
key={i}
@@ -123,6 +123,8 @@ Two approaches to styling:
- `<box>` - Container with borders and layout
- `<scrollbox>` - Scrollable container
- `<ascii-font>` - ASCII art text
- `<image>` - PNG, JPEG, WebP, or GIF image
- `<time-to-first-draw>` / `TimeToFirstDraw` - First-draw diagnostic
### Input
- `<input>` - Single-line text input
@@ -134,6 +136,7 @@ Two approaches to styling:
- `<code>` - Syntax-highlighted code
- `<line-number>` - Code with line numbers
- `<diff>` - Unified or split diff viewer
- `<markdown>` - Markdown content
### Text Modifiers (inside `<text>`)
- `<span>` - Inline styled text
+6 -5
View File
@@ -188,7 +188,7 @@ function AnimatedBox() {
{
width: 50,
duration: 2000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setWidth(Math.round(anim.targets[0].width))
},
@@ -270,7 +270,7 @@ React uses **hyphenated** tag names. Full props are in the linked file:
| Element | Full props |
|---------|-----------|
| `<text>`, `<span>`, `<strong>`, `<em>`, `<u>`, `<a>`, `<br>` | [text-display.md](../components/text-display.md) |
| `<text>`, `<span>`, `<strong>`, `<em>`, `<u>`, `<a>`, `<br>`, `<image>`, `<time-to-first-draw>` | [text-display.md](../components/text-display.md) |
| `<box>`, `<scrollbox>` | [containers.md](../components/containers.md) |
| `<input>`, `<textarea>`, `<select>`, `<tab-select>` | [inputs.md](../components/inputs.md) |
| `<code>`, `<line-number>`, `<diff>`, `<markdown>` | [code-diff.md](../components/code-diff.md) |
@@ -293,12 +293,13 @@ Style text with **nested modifier elements**, not props:
### Controlled Inputs (React-specific)
Inputs are controlled with `value` + `onChange` (single value), and use the
`focused` prop to receive keyboard input:
Single-line inputs are controlled with `value` + `onChange`, and use the
`focused` prop to receive keyboard input. Textarea is imperative: use
`initialValue`, keep a ref, and read `plainText` from `onContentChange`.
```tsx
<input value={value} onChange={setValue} focused />
<textarea value={text} onChange={setText} focused width={40} height={10} />
<textarea initialValue={text} ref={textareaRef} onContentChange={() => setText(textareaRef.current!.plainText)} />
// Select/tab-select: onChange fires on navigation, onSelect on Enter
<select options={opts} onChange={(i, opt) => setSel(opt)} focused />
@@ -143,7 +143,7 @@ import { createCliRenderer, ConsolePosition } from "@opentui/core"
const renderer = await createCliRenderer({
// Rendering
targetFPS: 60,
targetFps: 30,
// Behavior
exitOnCtrlC: true, // Set false to handle Ctrl+C yourself
@@ -127,6 +127,8 @@ Inside `<text>`, use modifier elements:
- `<box>` - Container with borders and layout
- `<scrollbox>` - Scrollable container
- `<ascii_font>` - ASCII art text (note underscore)
- `<image>` - PNG, JPEG, WebP, or GIF image
- `<time_to_first_draw>` / `TimeToFirstDraw` - First-draw diagnostic
### Input
- `<input>` - Single-line text input
@@ -138,6 +140,7 @@ Inside `<text>`, use modifier elements:
- `<code>` - Syntax-highlighted code
- `<line_number>` - Code with line numbers (note underscore)
- `<diff>` - Unified or split diff viewer
- `<markdown>` - Markdown content
### Text Modifiers (inside `<text>`)
- `<span>` - Inline styled text
+12 -7
View File
@@ -15,7 +15,7 @@ render(() => <App />)
// With config
render(() => <App />, {
exitOnCtrlC: false,
targetFPS: 60,
targetFps: 30,
})
// With existing renderer
@@ -212,7 +212,8 @@ function ResponsiveLayout() {
### onFocus(callback) / onBlur(callback)
Handle terminal window focus and blur events. Solid-only hooks.
Handle terminal window focus and blur events. React exposes equivalent
`useFocus` and `useBlur` hooks.
```tsx
import { onFocus, onBlur } from "@opentui/solid"
@@ -234,7 +235,8 @@ These hooks fire when the terminal emulator window gains or loses operating syst
### useSelectionHandler(handler)
Handle text selection events. Fires when the user finishes a mouse selection (mouse-up). Solid-only hook - React does not have this.
Handle text selection events. Fires when the user finishes a mouse selection
(mouse-up). React exposes an equivalent `useSelectionHandler` hook.
```tsx
import { useSelectionHandler } from "@opentui/solid"
@@ -285,7 +287,7 @@ function AnimatedBox() {
{
width: 50,
duration: 2000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setWidth(Math.round(anim.targets[0].width))
},
@@ -309,7 +311,7 @@ Multi-word elements use **underscores** (not hyphens like React):
| Element | Full props |
|---------|-----------|
| `<text>`, `<span>`, `<strong>`, `<em>`, `<u>`, `<a>`, `<br>` | [text-display.md](../components/text-display.md) |
| `<text>`, `<span>`, `<strong>`, `<em>`, `<u>`, `<a>`, `<br>`, `<image>`, `<time_to_first_draw>` | [text-display.md](../components/text-display.md) |
| `<box>`, `<scrollbox>` | [containers.md](../components/containers.md) |
| `<input>`, `<textarea>`, `<select>`, `<tab_select>` | [inputs.md](../components/inputs.md) |
| `<code>`, `<line_number>`, `<diff>`, `<markdown>` | [code-diff.md](../components/code-diff.md) |
@@ -328,12 +330,15 @@ Multi-word elements use **underscores** (not hyphens like React):
### Reactive Values + `onInput` (Solid-specific)
Solid uses **`onInput`** (not React's `onChange`) for text inputs, and values are
Solid uses **`onInput`** (not React's `onChange`) for single-line inputs, and values are
signals. Use `<For>` inside `<scrollbox>` for lists:
```tsx
<input value={value()} onInput={setValue} focused />
<textarea value={text()} onInput={setText} focused width={40} height={10} />
// Textarea is not a controlled input. Seed it with initialValue and use a ref
// plus onContentChange to read textarea.plainText.
<textarea initialValue={text()} ref={setTextarea} onContentChange={() => setText(textarea.plainText)} />
// select/tab_select still use onChange (navigate) / onSelect (Enter)
<select options={opts} onChange={(i, opt) => setSelected(opt)} focused />
@@ -147,7 +147,7 @@ import { ConsolePosition } from "@opentui/core"
render(() => <App />, {
// Rendering
targetFPS: 60,
targetFps: 30,
// Behavior
exitOnCtrlC: true,
+1 -1
View File
@@ -522,7 +522,7 @@ function AnimatedProgress() {
{
value: 50,
duration: 2000,
ease: "easeOutQuad",
ease: "outQuad",
onUpdate: (anim) => {
setWidth(Math.round(anim.targets[0].value))
},
@@ -142,7 +142,7 @@ const commits = t.externalOutput.take()
`@opentui/core/testing`: `createMockKeys`, `KeyCodes`, `createMockMouse`,
`MouseButtons`, `createSpy`, `TestRecorder`, `ManualClock`,
`createTerminalCapabilities`, `setRendererCapabilities`,
`createMockTreeSitterClient`.
`MockTreeSitterClient`.
## React Testing
@@ -452,7 +452,7 @@ test("input receives focus", async () => {
input.focus()
expect(input.isFocused()).toBe(true)
expect(input.focused).toBe(true)
})
```
@@ -481,7 +481,7 @@ bun test
bun test src/components/Button.test.tsx
# Run with filter
bun test --filter "Button"
bun test --test-name-pattern "Button"
# Watch mode
bun test --watch