Skip to main content
Minimal terminal UI framework with differential rendering and synchronized output for flicker-free interactive CLI applications.

Features

  • Interchangeable Renderers: Shared TUI interface with main-screen and alternate-screen implementations
  • Differential Rendering: Updates only changed lines or viewport rows
  • Application-owned Scrolling: Alternate-screen viewport supports mouse, trackpad, and keyboard navigation
  • Synchronized Output: Uses CSI 2026 for atomic screen updates (no flicker)
  • Bracketed Paste Mode: Handles large pastes correctly with markers for >10 line pastes
  • Component-based: Simple Component interface with render() method
  • Theme Support: Components accept theme interfaces for customizable styling
  • Built-in Components: Text, TruncatedText, Input, Editor, Markdown, Loader, SelectList, SettingsList, MouseRegion, Spacer, Image, Box, Container, VStack, HStack, ScrollView
  • Inline Images: Renders images in terminals that support Kitty or iTerm2 graphics protocols
  • Autocomplete Support: File paths and slash commands

Quick Start

Core API

TUI interface and renderers

TUI is the shared interface for component management, focus, overlays, input, lifecycle, terminal queries, and rendering. Choose a concrete renderer only when constructing the application:
  • TuiMainScreen renders into the main terminal buffer and preserves terminal scrollback.
  • TuiAltScreen renders a fixed-height viewport in the alternate terminal buffer with application-owned scrolling. When stopped, it restores the main buffer and prints the complete final document.

Colors and terminal styles

Colors are values that can be converted or mixed before terminal rendering:
Color is an indexed ANSI color, an sRGB color, or an OKLCH color. Every color converts to sRGB, so color math such as mixColors() always works. Indices 0-15 follow the user’s terminal palette, so their sRGB values are approximations. styleText() converts colors to truecolor or 256-color output based on the requested terminal mode. parseColor() also accepts OKHSL, as in okhsl(250 60% 55%); okhslColor() builds it in code and colorToOkhsl() reads any color’s OKHSL channels. OKHSL saturation is relative to the most the sRGB gamut allows at the hue and lightness, so every value is in gamut and equal saturation looks equally colorful across hues. OKHSL colors are converted to sRGB when created. Conversions are not cached. OKLCH colors, especially ones outside the sRGB gamut, are more expensive to convert than sRGB or indexed colors. For colors used on every render, convert once and reuse the result:

Alternate-screen viewport layouts

TuiAltScreen can render an explicit terminal-height layout. VStack and HStack allocate constrained regions, while ScrollView owns scrolling for one region. These semantics are intentionally unavailable on TuiMainScreen, where the terminal owns scrollback.
Stack entries support basis, grow, shrink, minSize, maxSize, and responsive visible callbacks. Mouse-wheel input targets the scroll view under the pointer and unused delta chains to outer scroll views by default. The primary scroll view receives the alternate-screen keyboard navigation actions and wheel input over non-scrollable regions. It can also jump between OSC 133 semantic prompt markers, matching common terminal prompt-navigation shortcuts. Press Ctrl+Shift+F to open or close its bordered search panel. The panel shows the configured previous/next shortcuts and provides clickable arrow controls; by default, Enter/Ctrl+G and Shift+Enter/Ctrl+Shift+G move between matches, and Escape also closes search. TuiAltScreenOptions.searchMatchStyle and searchCurrentMatchStyle customize match highlighting, while searchNavigationButtonStyle styles each arrow button and receives its hover state. TuiAltScreenOptions.scrollToEndIndicator renders a clickable label centered on the last row of a follow: "end" primary scroll view while it is scrolled away from the end; clicking it resumes end-following. Layout geometry is rebuilt for each requested frame. Stateful components are retained, and their existing rendered-line caches remain effective. Calling render(width) directly on these layout components produces an unbounded document, which is also used when alt mode restores the main screen.

Overlays

Overlays render components on top of existing content without replacing it. Useful for dialogs, menus, and modal UI.
Anchor values: 'center', 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'top-center', 'bottom-center', 'left-center', 'right-center' Resolution order:
  1. minWidth is applied as a floor after width calculation
  2. For position: absolute row/col > percentage row/col > anchor
  3. margin clamps final position to stay within terminal bounds
  4. visible callback controls whether overlay renders (called each frame)

Component Interface

All components implement:
The TUI appends a full SGR reset and OSC 8 reset at the end of each rendered line. Styles do not carry across lines. If you emit multi-line text with styling, reapply styles per line or use wrapTextWithAnsi() so styles are preserved for each wrapped line.

Mouse Input

TuiAltScreen normalizes SGR mouse input and hit-tests components and overlays. Events contain component-local x/y, absolute screenX/screenY, bounds, button, modifiers, click count, and wheel delta. TuiMainScreen does not capture mouse input because the terminal owns its scrollback.
Returning handled suppresses renderer-level fallback behavior. capture keeps subsequent drag and release events routed to the same component. focus requests keyboard focus. The optional render flag controls repainting: press, click, drag, and wheel default to rendering; move and release do not. Set render: true for a hover state that visibly changed, or render: false for a handled no-op. Render requests are coalesced and terminal output remains differential. A click carries clickCount (1, 2 or 3). When a single click should do something a double-click must not, such as expanding a block whose text a double-click would select, return its action as whenSingleClick instead of running it: { handled: true, whenSingleClick: () => toggle() }. TuiAltScreen runs it once MULTI_CLICK_INTERVAL_MS (500 ms) has passed since the press with no second press on the same spot, then repaints. A second press there makes the click part of a double- or triple-click and drops the action. Read the state the action changes when it runs, not when the click arrives: two quick clicks on different rows are two single clicks, and the first one’s action may run just before the second’s. Unhandled gestures retain alternate-screen defaults: wheel input scrolls the nearest ScrollView and chains unused delta, primary-button drags select text, OSC 8 links open before parent click handlers, and unhandled right-click preserves configured paste behavior. A click is emitted only when press/release completes without a drag. Use MouseRegion to add mouse behavior without changing a component’s rendering:
Container and Box route events to nested children using geometry recorded by the last rendered frame, so pointer motion does not rerender children merely to hit-test them. Explicit VStack, HStack, and ScrollView layouts use the alternate-screen layout frame directly.

Focusable Interface (IME Support)

Components that display a text cursor and need IME (Input Method Editor) support should implement the Focusable interface:
When a Focusable component has focus, TUI:
  1. Sets focused = true on the component
  2. Scans rendered output for CURSOR_MARKER (a zero-width APC escape sequence)
  3. Positions the hardware terminal cursor at that location
  4. Shows the hardware cursor only when showHardwareCursor is enabled
renderFakeCursor() wraps the cursor cell in zero-width markers. TUI renders them as reverse video. When showHardwareCursor is enabled, TUI removes the fake cursor that directly follows CURSOR_MARKER, so the focused component shows only the terminal cursor. Fake cursors without a preceding CURSOR_MARKER stay visible. The hardware cursor remains hidden by default. This keeps the fake cursor rendering, while still positioning the hardware cursor for terminals that track IME candidate windows with hidden cursors. Some terminals require a visible hardware cursor for IME positioning; enable it with the renderer constructor’s showHardwareCursor argument or setShowHardwareCursor(true). The Editor and Input built-in components already implement this interface. Container components with embedded inputs: When a container component (dialog, selector, etc.) contains an Input or Editor child, the container must implement Focusable and propagate the focus state to the child:
Without this propagation, typing with an IME (Chinese, Japanese, Korean, etc.) will show the candidate window in the wrong position.

Built-in Components

Container

Groups child components.

Box

Container that applies padding and background color to all children.

Text

Displays multi-line text with word wrapping and padding.

TruncatedText

Single-line text that truncates to fit viewport width. Useful for status lines and headers.

Input

Single-line text input with horizontal scrolling.
Clicking positions the cursor and gives the input keyboard focus in alternate-screen mode. Key Bindings:
  • Enter - Submit
  • Ctrl+A / Ctrl+E - Line start/end
  • Ctrl+W or Alt+Backspace - Delete word backwards
  • Ctrl+U - Delete to start of line
  • Ctrl+K - Delete to end of line
  • Ctrl+Left / Ctrl+Right - Word navigation
  • Alt+Left / Alt+Right - Word navigation
  • Arrow keys, Backspace, Delete work as expected

Editor

Multi-line text editor with autocomplete, file completion, paste handling, and vertical scrolling when content exceeds terminal height.
getHistory() returns past prompts, newest first. autocompleteHint draws one line below an open completion menu. Its entries name the available actions and their labels, with essential marking actions to keep on narrow terminals. Resolve actions through the active keybindings. When resolvedKeys is present, use those keys instead, including an empty array: CustomEditor supplies only keys that reach the menu after app shortcuts. Without autocompleteHint, the editor draws no menu hint. Features:
  • Click-to-position cursor and clickable autocomplete rows in alternate-screen mode
  • Multi-line editing with word wrap
  • Slash command autocomplete (type /)
  • File path autocomplete (press Tab)
  • Large paste handling (>10 lines creates [paste #1 +50 lines] marker)
  • Horizontal lines above/below editor
  • Fake cursor rendering (hidden real cursor)
Key Bindings:
  • Enter - Submit
  • Shift+Enter, Ctrl+Enter, or Alt+Enter - New line (terminal-dependent, Alt+Enter most reliable)
  • Tab - Autocomplete
  • Ctrl+K - Delete to end of line
  • Ctrl+U - Delete to start of line
  • Ctrl+W or Alt+Backspace - Delete word backwards
  • Alt+D or Alt+Delete - Delete word forwards
  • Ctrl+A / Ctrl+E - Line start/end
  • Ctrl+] - Jump forward to character (awaits next keypress, then moves cursor to first occurrence)
  • Ctrl+Alt+] - Jump backward to character
  • Arrow keys, Backspace, Delete work as expected

Markdown

Renders markdown with syntax highlighting and theming support.
Features:
  • Headings, bold, italic, code blocks, lists, links, blockquotes
  • HTML tags rendered as plain text
  • Optional syntax highlighting via highlightCode
  • Padding support
  • Render caching for performance

Loader

Animated loading spinner.

CancellableLoader

Extends Loader with Escape key handling and an AbortSignal for cancelling async operations.
Properties:
  • signal: AbortSignal - Aborted when user presses Escape
  • aborted: boolean - Whether the loader was aborted
  • onAbort?: () => void - Callback when user presses Escape

SelectList

Interactive selection list with keyboard navigation.
Controls:
  • Mouse move/wheel: Highlight rows in alternate-screen mode
  • Click: Select a row
  • Arrow keys: Navigate
  • Enter: Select
  • Escape: Cancel

SettingsList

Settings panel with value cycling and submenus.
Controls:
  • Mouse move/wheel: Highlight rows in alternate-screen mode
  • Click: Activate a row
  • Arrow keys: Navigate
  • Enter/Space: Activate (cycle value or open submenu)
  • Escape: Cancel

Spacer

Empty lines for vertical spacing.

Image

Renders images inline for terminals that support the Kitty graphics protocol (Kitty, Ghostty, WezTerm) or iTerm2 inline images. Falls back to a text placeholder on unsupported terminals.
Supported formats: PNG, JPEG, GIF, WebP. Dimensions are parsed from the image headers automatically.

Alternate-screen image compatibility

TuiAltScreen supports inline images and partial viewport cropping in terminals that implement the Kitty graphics protocol, including Kitty and Ghostty. iTerm2’s inline-image protocol does not provide operations to delete an existing placement or crop its source while scrolling. To prevent stale images from remaining over repainted content, TuiAltScreen renders image components as text placeholders in iTerm2. TuiMainScreen continues to render iTerm2 inline images normally.

Autocomplete

CombinedAutocompleteProvider

Supports both slash commands and file paths.
Features:
  • Type / to see slash commands
  • Press Tab for file path completion
  • Works with ~/, ./, ../, and @ prefix
  • Filters to attachable files for @ prefix

Key Detection

Use matchesKey() with the Key helper for detecting keyboard input (supports Kitty keyboard protocol):
Key identifiers (use Key.* for autocomplete, or string literals):
  • Basic keys: Key.enter, Key.escape, Key.tab, Key.space, Key.backspace, Key.delete, Key.home, Key.end
  • Arrow keys: Key.up, Key.down, Key.left, Key.right
  • With modifiers: Key.ctrl("c"), Key.shift("tab"), Key.alt("left"), Key.ctrlShift("p")
  • String format also works: "enter", "ctrl+c", "shift+tab", "ctrl+shift+p"

Rendering modes

TuiMainScreen uses three rendering strategies:
  1. First Render: Output all lines without clearing scrollback
  2. Width Changed or Change Above Viewport: Clear screen and fully re-render
  3. Normal Update: Move the cursor to the first changed line, clear to the end, and render changed lines
TuiAltScreen owns a terminal-height viewport. Without an explicit layout root it preserves the legacy single-document scrolling behavior. With setLayoutRoot(), VStack, HStack, and nested ScrollView components can reserve fixed regions and independently scroll constrained regions. It updates changed viewport rows in place, follows streaming output while at the bottom, and preserves a manually selected scroll position while content grows. Mouse-wheel and configurable keyboard navigation scroll without modifying terminal scrollback, including jumps between OSC 133 semantic prompt markers. Scrollbars support hover expansion, thumb dragging, and track-click jumping. Clicking an OSC 8 hyperlink opens it with the configured URL handler. Dragging with the primary mouse button selects text and, unless TuiAltScreenOptions.copyOnSelect is false, copies it to the clipboard with OSC 52; holding the drag at a scroll view’s top or bottom edge auto-scrolls and extends the selection into off-screen content. Kitty images support vertical viewport cropping; iTerm2 inline images fall back to text because the iTerm2 protocol cannot delete or crop placements during viewport repainting. Both renderers wrap updates in synchronized output (\x1b[?2026h … \x1b[?2026l) for atomic, flicker-free rendering.

Terminal Interface

The TUI works with any object implementing the Terminal interface:
Built-in implementations:
  • ProcessTerminal - Uses process.stdin/stdout
  • VirtualTerminal - For testing (uses @xterm/headless)

Utilities

Creating Custom Components

When creating custom components, each line returned by render() must not exceed the width parameter. The TUI will error if any line is wider than the terminal.

Handling Input

Use matchesKey() with the Key helper for keyboard input:

Handling Line Width

Use the provided utilities to ensure lines fit:

ANSI Code Considerations

Both visibleWidth() and truncateToWidth() correctly handle ANSI escape codes:
  • visibleWidth() ignores ANSI codes when calculating width
  • truncateToWidth() preserves ANSI codes and properly closes them when truncating

Caching

For performance, components should cache their rendered output and only re-render when necessary:

Example

See test/chat-simple.ts for a complete chat interface example with:
  • Markdown messages with custom background colors
  • Loading spinner during responses
  • Editor with autocomplete and slash commands
  • Spacers between messages
Run it: