Files
opentui-skill/skill/opentui/references/components/code-diff.md
T
Matt Simpson 87c512939f docs: update skill documentation with upstream repo (#3)
* fix(patterns): replace process.exit() with renderer.destroy() in react patterns

process.exit() violates Critical Rule #2 which states you must never call
it directly. Instead, use renderer.destroy() to properly clean up the
renderer and exit gracefully.

* docs(containers): add focusable prop and auto-focus behavior to Box

Documents the focusable prop on Box which allows boxes to receive focus
via mouse click. Includes controlled focus state example and notes about
focus bubbling and preventDefault behavior.

* docs(react/api): add focusable, themeMode, and theme_mode event

- Documents renderer.themeMode property for detecting terminal theme
- Adds theme_mode event listener example for reactive theme changes
- Adds focusable and focused props to Box component
- Adds paddingX/Y and marginX/Y axis shorthand props to Box

* docs(solid/api): add focusable, themeMode, and enhance useSelectionHandler

- Documents renderer.themeMode property and theme_mode event
- Adds focusable and focused props to Box component
- Adds paddingX/Y and marginX/Y axis shorthand props
- Expands useSelectionHandler docs with Selection API details
- Notes that useSelectionHandler is Solid-only

* docs(components): add markdown component and axis shorthand props

- Adds markdown component to component table and chooser
- Documents paddingX/Y and marginX/Y axis shorthand properties
- Updates Code & Diff category to include markdown

* docs(config): add autoFocus renderer option to react configuration

Documents the autoFocus option that controls whether clicking on a
focusable element automatically focuses it. Default is true.

* docs(config): add autoFocus renderer option to solid configuration

Documents the autoFocus option that controls whether clicking on a
focusable element automatically focuses it. Default is true.

* docs(keyboard): clarify usePaste is Solid-only, add OSC 52 clipboard API

- Notes that usePaste hook is only available in Solid, not React
- Documents copyToClipboardOSC52, clearClipboardOSC52, isOsc52Supported
- Adds ClipboardTarget enum usage for X11 clipboard targets
- Shows Selection.copyToClipboard() convenience method

* docs(code-diff): add onHighlight callback and markdown component

- Documents onHighlight callback for intercepting/modifying highlights
- Adds full Markdown component section with Core/React/Solid examples
- Includes renderNode custom rendering and streaming mode docs

* docs(skill): add markdown to decision tree and product index

Updates the display content decision tree and component categories
to include the markdown component.

* docs(layout): add axis shorthand spacing examples

Documents paddingX/Y and marginX/Y shorthand props with examples
showing horizontal and vertical spacing patterns.

* docs(containers): add axis shorthand to Box spacing section

Adds paddingX/Y and marginX/Y to the spacing props example to
show the axis shorthand options alongside individual side props.

* docs(gotchas): document expanded signal handling

Lists all signals handled by OpenTUI for automatic cleanup including
SIGPIPE, SIGBUS, SIGFPE, SIGHUP, and SIGBREAK.

* docs: add See Also sections to keyboard, animation, and testing references

These three cross-cutting REFERENCE.md files were navigation dead-ends
with no outbound links to related content. Adds cross-references so
agents can discover related APIs, components, and patterns.

* docs(skill): add keyboard and animation to Reading Order section

These two reference areas were only discoverable via the decision trees
further down. Adding them to the Reading Order ensures agents following
the prescribed path don't miss them.
2026-02-15 19:20:08 +00:00

8.5 KiB

Code & Diff Components

Components for displaying code with syntax highlighting and diffs in OpenTUI.

Code Component

Display syntax-highlighted code blocks.

Basic Usage

// React
<code
  code={`function hello() {
  console.log("Hello, World!");
}`}
  language="typescript"
/>

// Solid
<code
  code={sourceCode}
  language="javascript"
/>

// Core
const codeBlock = new CodeRenderable(renderer, {
  id: "code",
  code: sourceCode,
  language: "typescript",
})

Supported Languages

OpenTUI uses Tree-sitter for syntax highlighting. Common languages:

  • typescript, javascript
  • python
  • rust
  • go
  • json
  • html, css
  • markdown
  • bash, shell

Styling

<code
  code={sourceCode}
  language="typescript"
  backgroundColor="#1a1a2e"
  showLineNumbers
/>

onHighlight Callback

Intercept and modify syntax highlights before rendering:

// 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.

Line Number Component

Code display with line numbers, highlighting, and diagnostics.

Basic Usage

// React
<line-number
  code={sourceCode}
  language="typescript"
/>

// Solid (note underscore)
<line_number
  code={sourceCode}
  language="typescript"
/>

// Core
const codeView = new LineNumberRenderable(renderer, {
  id: "code-view",
  code: sourceCode,
  language: "typescript",
})

Line Number Options

// 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}
/>

Line Highlighting

Highlight specific lines:

// 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:

// 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:

<line-number
  code={sourceCode}
  language="typescript"
  addedLines={[5, 6, 7]}      // Green background
  removedLines={[10, 11]}     // Red background
/>

Diff Component

Unified or split diff viewer with syntax highlighting.

Basic Usage

// React
<diff
  oldCode={originalCode}
  newCode={modifiedCode}
  language="typescript"
/>

// Solid
<diff
  oldCode={originalCode}
  newCode={modifiedCode}
  language="typescript"
/>

// Core
const diffView = new DiffRenderable(renderer, {
  id: "diff",
  oldCode: originalCode,
  newCode: modifiedCode,
  language: "typescript",
})

Display Modes

// Unified diff (default)
<diff
  oldCode={old}
  newCode={new}
  mode="unified"
/>

// Split/side-by-side diff
<diff
  oldCode={old}
  newCode={new}
  mode="split"
/>

Options

<diff
  oldCode={originalCode}
  newCode={modifiedCode}
  language="typescript"
  mode="unified"
  showLineNumbers
  context={3}                // Lines of context around changes
/>

Styling

<diff
  oldCode={old}
  newCode={new}
  addedLineColor="#2d4f2d"   // Background for added lines
  removedLineColor="#4f2d2d" // Background for removed lines
  unchangedLineColor="transparent"
/>

Markdown Component

Render markdown content with syntax highlighting for code blocks.

Basic Usage

// 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

<markdown
  content={markdownText}
  syntaxStyle={syntaxStyle}
  treeSitterClient={client}  // Optional: custom tree-sitter client
  conceal={true}             // Hide markdown syntax characters
  streaming={true}           // Enable streaming mode for incremental updates
/>

Custom Node Rendering

// Core
const md = new MarkdownRenderable(renderer, {
  id: "markdown",
  content: "# Custom Heading",
  syntaxStyle,
  renderNode: (node, ctx, defaultRender) => {
    if (node.type === "heading") {
      // Return custom renderable for headings
      return new TextRenderable(ctx, {
        content: `>> ${node.content} <<`,
      })
    }
    return null // Use default rendering
  },
})

Streaming Mode

For real-time content like LLM output:

const [content, setContent] = useState("")

// Append text as it arrives
useEffect(() => {
  llmStream.on("token", (token) => {
    setContent(c => c + token)
  })
}, [])

<markdown
  content={content}
  syntaxStyle={syntaxStyle}
  streaming={true}  // Optimizes for incremental updates
/>

Use Cases

Code Editor

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

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

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

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)}
    />
  )
}

Gotchas

Solid Uses Underscores

// React
<line-number />

// Solid
<line_number />

Language Required for Highlighting

// 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
<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