Skip to content

PyModel/pythinker-code / .agents/skills/opentui

opentui

Verified

Build terminal UIs with OpenTUI. Covers core, components, audio, keymaps, React, Solid, plugins, testing, standalone executables, QR encoding, SSH, and Three.js WebGPU.

FileKindSize
SKILL.mdskill md5.4 KB
docs/bindings/react.mdxmarkdown11.0 KB
docs/bindings/solid.mdxmarkdown15.0 KB
docs/components/ascii-font.mdxmarkdown4.3 KB
docs/components/box.mdxmarkdown5.5 KB
docs/components/code.mdxmarkdown10.2 KB
docs/components/diff.mdxmarkdown4.2 KB
docs/components/frame-buffer.mdxmarkdown6.7 KB
docs/components/input.mdxmarkdown5.6 KB
docs/components/line-number.mdxmarkdown4.0 KB
docs/components/markdown.mdxmarkdown10.6 KB
docs/components/qr-code.mdxmarkdown4.3 KB
docs/components/scrollbar.mdxmarkdown2.3 KB
docs/components/scrollbox.mdxmarkdown7.5 KB
docs/components/select.mdxmarkdown6.2 KB
docs/components/slider.mdxmarkdown2.2 KB
docs/components/tab-select.mdxmarkdown6.0 KB
docs/components/text-table.mdxmarkdown9.0 KB
docs/components/text.mdxmarkdown4.5 KB
docs/components/textarea.mdxmarkdown7.7 KB
docs/components/time-to-first-draw.mdxmarkdown4.7 KB
docs/core-concepts/audio.mdxmarkdown32.2 KB
docs/core-concepts/colors.mdxmarkdown7.8 KB
docs/core-concepts/console.mdxmarkdown3.2 KB
docs/core-concepts/constructs.mdxmarkdown5.8 KB
docs/core-concepts/keyboard.mdxmarkdown10.4 KB
docs/core-concepts/layout.mdxmarkdown4.0 KB
docs/core-concepts/lifecycle.mdxmarkdown4.4 KB
docs/core-concepts/notifications.mdxmarkdown2.3 KB
docs/core-concepts/renderables-vs-constructs.mdxmarkdown4.5 KB
docs/core-concepts/renderables.mdxmarkdown9.9 KB
docs/core-concepts/renderer.mdxmarkdown30.9 KB
docs/core-concepts/testing.mdxmarkdown14.6 KB
docs/getting-started.mdxmarkdown3.2 KB
docs/keymap/addons.mdxmarkdown15.6 KB
docs/keymap/core.mdxmarkdown38.9 KB
docs/keymap/custom-addons.mdxmarkdown26.7 KB
docs/keymap/hosts.mdxmarkdown15.7 KB
docs/keymap/overview.mdxmarkdown18.1 KB
docs/keymap/react.mdxmarkdown4.9 KB
docs/keymap/solid.mdxmarkdown5.1 KB
docs/plugins/core.mdxmarkdown12.6 KB
docs/plugins/react.mdxmarkdown6.5 KB
docs/plugins/slots.mdxmarkdown12.7 KB
docs/plugins/solid.mdxmarkdown7.0 KB
docs/reference/color-matrix.mdxmarkdown3.8 KB
docs/reference/env-vars.mdxmarkdown6.5 KB
docs/reference/native-span-feed.mdxmarkdown6.0 KB
docs/reference/package-entrypoints.mdxmarkdown9.6 KB
docs/reference/qr-encoder.mdxmarkdown12.3 KB
docs/reference/ssh.mdxmarkdown14.8 KB
docs/reference/standalone-executables.mdxmarkdown7.1 KB
docs/reference/three.mdxmarkdown14.8 KB
docs/reference/tree-sitter.mdxmarkdown4.6 KB

docs/core-concepts/keyboard.mdx

View on GitHub
---
title: Keyboard input
description: Handling keyboard events in OpenTUI
order: 6
skill:
  entry: true
  intents: [keyboard, input, keybindings, paste, focus]
---

# Keyboard input

OpenTUI parses terminal input and provides structured key events. The `renderer.keyInput` EventEmitter emits `keypress` events plus raw `paste` events with optional metadata.

## Basic key handling

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

const renderer = await createCliRenderer()
const keyHandler = renderer.keyInput

keyHandler.on("keypress", (key: KeyEvent) => {
  console.log("Key name:", key.name)
  console.log("Input sequence:", key.sequence)
  console.log("Raw input:", key.raw)
  console.log("Ctrl pressed:", key.ctrl)
  console.log("Shift pressed:", key.shift)
  console.log("Alt pressed:", key.meta)
  console.log("Option pressed:", key.option)
})
```

## KeyEvent properties

Each `KeyEvent` contains the parsed key identity, the generated input sequence, and the original terminal input:

| Property    | Type                               | Description                                                                                          |
| ----------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `name`      | `string`                           | Canonical key identity, such as `"a"`, `"space"`, `"return"`, `"escape"`, or `"f1"`                  |
| `sequence`  | `string`                           | Decoded input sequence/text for the key. For printable keys this is the text, such as `"a"` or `" "` |
| `raw`       | `string`                           | Exact terminal input sequence for this key event, decoded as a string                                |
| `source`    | `"raw" \| "kitty"`                 | Parser path that produced the event                                                                  |
| `ctrl`      | `boolean`                          | Whether Ctrl was held                                                                                |
| `shift`     | `boolean`                          | Whether Shift was held                                                                               |
| `meta`      | `boolean`                          | Whether Alt/Meta was held                                                                            |
| `option`    | `boolean`                          | Whether Option was held (macOS Alt/Option path)                                                      |
| `super`     | `boolean?`                         | Whether Super/Cmd/Windows was held, when reported                                                    |
| `hyper`     | `boolean?`                         | Whether Hyper was held, when reported                                                                |
| `eventType` | `"press" \| "repeat" \| "release"` | Key event type. Kitty repeat events are emitted as `"press"` with `repeated: true`                   |
| `repeated`  | `boolean?`                         | `true` for Kitty repeat events                                                                       |
| `number`    | `boolean`                          | `true` when the parsed key is a digit from legacy input                                              |
| `code`      | `string?`                          | Terminal key code for recognized function-style escape sequences                                     |
| `capsLock`  | `boolean?`                         | Kitty Caps Lock modifier state, when reported                                                        |
| `numLock`   | `boolean?`                         | Kitty Num Lock modifier state, when reported                                                         |
| `baseCode`  | `number?`                          | Kitty base-layout codepoint used by layout-stable shortcut matching                                  |

`sequence` is not always the raw terminal bytes. For example, Kitty `Ctrl+Space` arrives as raw `"\x1b[32;5u"`, but emits `name: "space"`, `ctrl: true`, and `sequence: " "`. Use `raw` when you need the exact terminal sequence.

## Keybinding aliases

Some core renderables and the built-in console support aliases for configured keybindings. These aliases are applied when building a component's keybinding lookup map; they do not rewrite emitted `KeyEvent.name` values.

The default keybinding aliases are:

```ts
// enter -> return
// esc   -> escape
//
// Numpad keys are aliased to their main-keyboard equivalents:
// kp0..kp9   -> "0".."9"
// kpenter    -> enter
// kpleft/kpright/kpup/kpdown -> arrow keys
// kphome/kpend/kppageup/kppagedown/kpinsert/kpdelete -> navigation
// kpdecimal/kpdivide/kpmultiply/kpminus/kpplus/kpequal/kpseparator -> symbols
```

Aliases are one-step mappings from configured binding names to additional lookup names. For example, a component binding configured as `{ name: "enter", action: "submit" }` also matches an emitted `KeyEvent` whose `name` is `"return"`. This aliasing is component-specific; direct `renderer.keyInput` handlers receive the parser's canonical names and should compare against names such as `"return"`, `"escape"`, and `"space"`.

Editable components that accept a `keyAliasMap` option (`InputRenderable`, `TextareaRenderable`, `SelectRenderable`, etc.) merge these defaults with your own map:

```typescript
import { InputRenderable } from "@opentui/core"

const input = new InputRenderable(renderer, {
  id: "field",
  keyAliasMap: {
    // Treat the numpad decimal key as forward-delete
    kpdecimal: "delete",
  },
})
```

## Common key patterns

### Single keys

```typescript
keyHandler.on("keypress", (key: KeyEvent) => {
  if (key.name === "escape") {
    console.log("Escape pressed!")
  }

  if (key.name === "return") {
    console.log("Enter pressed!")
  }

  if (key.name === "space") {
    console.log("Space pressed!")
  }
})
```

### Modifier combinations

```typescript
keyHandler.on("keypress", (key: KeyEvent) => {
  // Ctrl+C
  if (key.ctrl && key.name === "c") {
    console.log("Ctrl+C pressed!")
  }

  // Ctrl+S
  if (key.ctrl && key.name === "s") {
    console.log("Save shortcut!")
  }

  // Shift+F1
  if (key.shift && key.name === "f1") {
    console.log("Shift+F1 pressed!")
  }

  // Alt+Enter
  if (key.meta && key.name === "return") {
    console.log("Alt+Enter pressed!")
  }
})
```

### Function keys

```typescript
keyHandler.on("keypress", (key: KeyEvent) => {
  // F1-F12
  if (key.name === "f1") {
    showHelp()
  }

  if (key.name === "f5") {
    refresh()
  }
})
```

### Arrow keys

```typescript
keyHandler.on("keypress", (key: KeyEvent) => {
  switch (key.name) {
    case "up":
      moveCursorUp()
      break
    case "down":
      moveCursorDown()
      break
    case "left":
      moveCursorLeft()
      break
    case "right":
      moveCursorRight()
      break
  }
})
```

## Paste events

Handle pasted bytes separately from individual keypresses. Decode them explicitly when you expect text:

```typescript
import { type PasteEvent } from "@opentui/core"

const textDecoder = new TextDecoder()

keyHandler.on("paste", (event: PasteEvent) => {
  console.log("Pasted bytes:", event.bytes)
  console.log("Decoded text:", textDecoder.decode(event.bytes))
  console.log("Metadata:", event.metadata)
})
```

## Exit on Ctrl+C

Configure the renderer to automatically exit on Ctrl+C:

```typescript
const renderer = await createCliRenderer({
  exitOnCtrlC: true, // Default behavior
})

// Or handle it manually
const renderer = await createCliRenderer({
  exitOnCtrlC: false,
})

renderer.keyInput.on("keypress", (key: KeyEvent) => {
  if (key.ctrl && key.name === "c") {
    // Custom cleanup before shutdown
    cleanup()
    renderer.destroy()
  }
})
```

## Kitty keyboard protocol

OpenTUI opts into the [kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/keyboard-protocol/) when the terminal supports it. The protocol gives more reliable key names and modifier state than legacy input encoding, including release events, disambiguated escape, alt+key sequences, and alternate keys for cross-layout shortcuts. Configure it with the `useKittyKeyboard` option:

```typescript
const renderer = await createCliRenderer({
  useKittyKeyboard: {
    disambiguate: true,
    alternateKeys: true,
    events: true, // press/repeat/release
    allKeysAsEscapes: false,
    reportText: false,
  },
})

// Disable entirely:
await createCliRenderer({ useKittyKeyboard: null })
```

| Option             | Default | Flag                              | Description                                                                    |
| ------------------ | ------- | --------------------------------- | ------------------------------------------------------------------------------ |
| `disambiguate`     | `true`  | `DISAMBIGUATE_ESCAPE_CODES`       | Fixes ESC timing and alt+key ambiguity; reports `ctrl+c` as a proper key event |
| `alternateKeys`    | `true`  | `REPORT_ALTERNATE_KEYS`           | Reports shifted/base-layout keys for cross-layout shortcuts                    |
| `events`           | `false` | `REPORT_EVENT_TYPES`              | Report press, repeat, and release events                                       |
| `allKeysAsEscapes` | `false` | `REPORT_ALL_KEYS_AS_ESCAPE_CODES` | Encode every key as an escape sequence                                         |
| `reportText`       | `false` | `REPORT_ASSOCIATED_TEXT`          | Include the text a key press generates                                         |

`events: true` enables the `keyrelease` event on `renderer.keyInput` as well as `eventType` on `KeyEvent`.

`useKittyKeyboard: {}` applies the defaults (`disambiguate` + `alternateKeys`). Passing `null` disables the protocol entirely.

Kitty escape sequences still emit the same canonical key names as legacy input where possible. For example, Kitty `Ctrl+Space` emits `name: "space"` with `ctrl: true`; the literal typed text remains available as `sequence: " "`, and the original escape sequence remains available as `raw`.

## Focus and key routing

Focus components to receive keyboard input. OpenTUI routes events to the focused component:

```typescript
import { InputRenderable } from "@opentui/core"

const input = new InputRenderable(renderer, {
  id: "my-input",
  placeholder: "Type here...",
})

// Focus the input to receive key events
input.focus()

// Or with constructs
import { Input } from "@opentui/core"

const inputNode = Input({ placeholder: "Type here..." })
inputNode.focus() // Queued for when instantiated

renderer.root.add(inputNode)
```
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 319kUpdated Claude CodeCodexVerifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 319kUpdated Claude CodeCodexVerifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 319kUpdated Claude CodeCodexVerifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 196kUpdated Claude CodeCodexVerifiedInstall