Features
- Interchangeable Renderers: Shared
TUIinterface 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:
TuiMainScreenrenders into the main terminal buffer and preserves terminal scrollback.TuiAltScreenrenders 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.
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.'center', 'top-left', 'top-right', 'bottom-left', 'bottom-right', 'top-center', 'bottom-center', 'left-center', 'right-center'
Resolution order:
minWidthis applied as a floor after width calculation- For position: absolute
row/col> percentagerow/col>anchor marginclamps final position to stay within terminal boundsvisiblecallback 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.
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 theFocusable interface:
Focusable component has focus, TUI:
- Sets
focused = trueon the component - Scans rendered output for
CURSOR_MARKER(a zero-width APC escape sequence) - Positions the hardware terminal cursor at that location
- Shows the hardware cursor only when
showHardwareCursoris 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:
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.Enter- SubmitCtrl+A/Ctrl+E- Line start/endCtrl+WorAlt+Backspace- Delete word backwardsCtrl+U- Delete to start of lineCtrl+K- Delete to end of lineCtrl+Left/Ctrl+Right- Word navigationAlt+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)
Enter- SubmitShift+Enter,Ctrl+Enter, orAlt+Enter- New line (terminal-dependent, Alt+Enter most reliable)Tab- AutocompleteCtrl+K- Delete to end of lineCtrl+U- Delete to start of lineCtrl+WorAlt+Backspace- Delete word backwardsAlt+DorAlt+Delete- Delete word forwardsCtrl+A/Ctrl+E- Line start/endCtrl+]- 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.- 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.signal: AbortSignal- Aborted when user presses Escapeaborted: boolean- Whether the loader was abortedonAbort?: () => void- Callback when user presses Escape
SelectList
Interactive selection list with keyboard navigation.- 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.- 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.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.- Type
/to see slash commands - Press
Tabfor file path completion - Works with
~/,./,../, and@prefix - Filters to attachable files for
@prefix
Key Detection
UsematchesKey() with the Key helper for detecting keyboard input (supports Kitty keyboard protocol):
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:
- First Render: Output all lines without clearing scrollback
- Width Changed or Change Above Viewport: Clear screen and fully re-render
- 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 theTerminal interface:
ProcessTerminal- Usesprocess.stdin/stdoutVirtualTerminal- For testing (uses@xterm/headless)
Utilities
Creating Custom Components
When creating custom components, each line returned byrender() must not exceed the width parameter. The TUI will error if any line is wider than the terminal.
Handling Input
UsematchesKey() with the Key helper for keyboard input:
Handling Line Width
Use the provided utilities to ensure lines fit:ANSI Code Considerations
BothvisibleWidth() and truncateToWidth() correctly handle ANSI escape codes:
visibleWidth()ignores ANSI codes when calculating widthtruncateToWidth()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
Seetest/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