Keyboard input

Use direct renderer KeyEvent listeners for simple app-wide input. Use component key bindings for local behavior. Use @opentui/keymap for layers, commands, discovery, and key sequences.

These levels can coexist, but they have different ownership and cleanup rules.

Handle app-wide keys#

renderer.keyInput emits parsed keypress, keyrelease, and paste events.

import { type KeyEvent, createCliRenderer } from "@opentui/core"

const renderer = await createCliRenderer()

const onKeyPress = (key: KeyEvent) => {
  if (key.name === "escape") {
    renderer.destroy()
  }
}

renderer.keyInput.on("keypress", onKeyPress)

renderer.once("destroy", () => {
  renderer.keyInput.off("keypress", onKeyPress)
})

Direct listeners run before the focused renderable. They are suitable for a global exit key, a small shortcut set, or input diagnostics.

Use prependListener() when listener order matters. Remove listeners when their owner stops, as described in Lifecycle and cleanup.

Read KeyEvent#

Property Type Meaning
name string Canonical key identity, such as "a", "space", "return", or "escape".
sequence string Decoded text or sequence associated with the key.
raw string The original terminal sequence decoded as a string.
source "raw" | "kitty" The parser path.
ctrl, shift, meta, option boolean Reported common modifiers. meta includes the Alt path.
super, hyper boolean | undefined Extended modifiers when the terminal reports them.
eventType "press" | "repeat" | "release" Parsed event type. Kitty repeats use "press" with repeated: true.
repeated boolean | undefined Whether Kitty reported a repeat.
number boolean Whether legacy parsing identified a digit.
code string | undefined A recognized terminal key code.
capsLock, numLock boolean | undefined Kitty lock state when reported.
baseCode number | undefined Kitty base-layout code point: the US QWERTY key at the same position.

sequence is not always equal to raw. For example, a Kitty control sequence can produce name: "space" and sequence: " ".

Compare direct events with canonical names such as "return", "escape", and "space". Component alias maps do not rewrite direct KeyEvent.name values.

Core’s key bindings (exitOnCtrlC and component key bindings) fall back to baseCode when the typed key is one non-ASCII character, or when the base-layout key is a digit. The fallback is for layouts whose keys cannot type the binding’s character: Korean Ctrl+ㅊ matches Ctrl+C, and AZERTY Ctrl+& matches Ctrl+1. Any other ASCII key matches as typed, so Dvorak Ctrl+J stays Ctrl+J. Some punctuation on non-Latin layouts therefore does not fall back, for example Hebrew ' on the W key, Greek ; on the Q key, or Russian . on the / key.

Control propagation#

Global listeners run in registration order before the focused renderable’s handler.

key.stopPropagation() stops later global listeners and prevents delivery to the focused renderable. It does not set defaultPrevented.

key.preventDefault() lets later global listeners run, but it prevents focused renderable handlers from receiving the event.

A focused renderable’s onKeyDown runs before its built-in handleKeyPress(). Calling preventDefault() there skips the built-in action.

Component handleKeyPress() return values describe local handling, but they do not change the event’s propagation flags.

See Interaction, focus, and selection for focus ownership and the lack of automatic Tab traversal.

Configure component key bindings#

Input, Textarea, Select, and TabSelect expose keyBindings for local actions. These four components also accept keyAliasMap.

import { TextareaRenderable, createCliRenderer } from "@opentui/core"

const renderer = await createCliRenderer()
const editor = new TextareaRenderable(renderer, {
  width: 40,
  height: 8,
  keyBindings: [{ name: "s", ctrl: true, action: "submit" }],
  onSubmit() {
    console.log("Submit", editor.plainText)
  },
})

renderer.root.add(editor)
editor.focus()

A key binding contains name, optional ctrl, shift, meta, and super, plus a component-specific action.

Custom bindings replace default bindings with the same key and modifiers. Other default bindings remain active.

Core aliases configured binding names such as enter to return and esc to escape. It also maps keypad names to their main-keyboard equivalents.

Read Input and Textarea for their action sets. Other components document their own actions.

Use Keymap for commands#

Direct listeners become difficult to manage when shortcuts depend on focus, mode, priority, or a sequence prefix.

@opentui/keymap adds scoped layers, named commands, multi-stroke sequences, active-key queries, and command metadata. Its OpenTUI host reads the renderer’s focused renderable.

Keymap can consume a matched event before the focused component receives it. Read the Keymap guide for dispatch and disposal.

Paste events#

Paste is terminal input. It is not a read from the host clipboard.

import { type PasteEvent, createCliRenderer } from "@opentui/core"

const renderer = await createCliRenderer()
const decoder = new TextDecoder()

const onPaste = (event: PasteEvent) => {
  console.log(decoder.decode(event.bytes))
  console.log(event.metadata?.mimeType, event.metadata?.kind)
}

renderer.keyInput.on("paste", onPaste)

PasteEvent.bytes preserves the terminal payload. Optional metadata contains mimeType and kind, where kind is "text", "binary", or "unknown".

PasteEvent supports the same preventDefault() and stopPropagation() flow as KeyEvent. Focused Input and Textarea components decode, sanitize, and insert paste bytes.

Use Clipboard when the application must read or write host clipboard data.

Handle raw sequences#

addInputHandler(handler) and prependInputHandler(handler) receive a parsed input event’s raw terminal sequence before KeyEvent delivery.

Return true to consume that sequence. Return false to continue through remaining handlers and, for keys, KeyEvent delivery.

The renderer consumes terminal replies to its own queries, such as capability and theme color replies, before handlers added with addInputHandler run. Use prependInputHandler to observe them.

Raw terminal encodings vary. Prefer KeyEvent unless you must integrate an unsupported terminal protocol.

The Kitty keyboard protocol improves modifier and release reporting when supported. Read Terminal capabilities before depending on those fields.

Test keyboard input#

createTestRenderer() returns mockInput. It can press keys, type text, send modifiers, and emit bracketed paste.

Use Kitty test mode when you need release, repeat, super, hyper, or baseCode behavior. See Testing for the exact helpers.

Next#

Read Keymap when local listeners no longer describe your command model. Read Interaction, focus, and selection when a component does not receive input.

Changes0.9.0, 0.8.3, 0.8.0
0.9.0
core: Input always uses the native parser. The experimental_nativeInput and stdinParserMaxBufferBytes options, the OTUI_NATIVE_INPUT_PARSER and OTUI_NATIVE_INPUT_SHADOW variables, and StdinParser with its types are removed. Use renderer.keyInput, prependInputHandler, or subscribeOsc instead. This fixes the F3 bugs that @FasterPHP reported. (#1981)
core: MouseParser and nonAlphanumericKeys are removed. parseKeypress() decodes with the native parser, needs --experimental-ffi under Node, and returns null for empty input. Use renderable mouse events or createMockMouse instead of MouseParser, and terminalNamedSingleStrokeKeys instead of nonAlphanumericKeys. (#2016)
core: When a terminal confirms the Kitty keyboard protocol, Escape arrives at once instead of after 20 ms. Kitty, Ghostty, foot, and Alacritty confirm it, but WezTerm by default and tmux do not. (#1948, #1971)
core: Under the Kitty protocol, text typed quickly after Escape, such as OA or [TODO], arrives as typed. A bracketed paste arrives whole even when a pause splits its start marker. (#2046, #1971)
core: With reportText, Kitty key text longer than 8 characters arrives whole, up to about 42 CJK characters. (#1972)
Added parseKeypress.
Removed parseKeypress.
0.8.3
native: The OT_INPUT_KEY_TYPED key flag marks a key whose code is a printable character that the terminal sent as text or as a CSI 27 code. (#1919)
core: With the native input parser, a typed character from U+E000 to U+E06E, such as a Nerd Fonts glyph, gives a key with that character instead of Escape, Return, or Backspace. A Textarea now inserts the glyph. (#1919)
core: With the native input parser, a typed U+FEFF keeps its character in raw and sequence, so a Textarea no longer drops it. (#1915)
0.8.0
core: With the native input parser, a UTF-8 character that a pause splits waits for its other bytes, and so does a mouse report cut after ESC [. Before, ✓ arrived as Alt keys and a wheel notch typed <64;87;26M. 8-bit Meta input now reads as UTF-8. (#1791, #1794)