xonecas.io
70160
Ce

cel-tui / commit 9a7fdab

fix(core): support kitty-first tmux-compatible input

xonecas2026-04-07 9a7fdab073dcb85abc16470ce70f6e0bedb9c627 parent 46745b4

16 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+42−29
@@ -39,10 +39,10 @@ All core systems from the spec are implemented and tested:
3939 - **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints (including cross-axis min/max), gap, padding, justifyContent, alignItems, flexWrap, largest-remainder rounding
4040 - **Rendering** — cell buffer, ANSI emitter with SGR styling, synchronized output (CSI 2026), differential rendering (emitDiff), full clear on resize
4141 - **Painting** — grapheme-aware text rendering (CJK/emoji via visibleWidth), overflow clipping via clip rect propagation, scroll content offsetting, scrollbar indicators, container bgColor fill, style inheritance, focusStyle overrides
42-- **Input** — Kitty keyboard protocol (level 1, required), key parsing/normalization for CSI u / CSI letter / CSI tilde formats, SGR mouse events (with batched event support), hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter) with uncontrolled and controlled modes, onKeyPress bubbling from focused element through ancestors
43-- **TextInput** — grapheme-aware text editing (Intl.Segmenter for emoji/ZWJ), cursor movement, cursor persistence across re-renders (keyed on onChange, clamped on external value changes), auto-scroll to keep cursor visible, inverted-cell cursor with native terminal cursor positioning (blinking), background fill, placeholder rendering
42+- **Input** — Kitty-first keyboard input (Kitty level 1 enable), mixed-stream decoding for CSI u / CSI letter / CSI tilde / recoverable legacy control bytes / ESC-prefixed Alt combos, batched SGR mouse handling, hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter) with uncontrolled and controlled modes, onKeyPress bubbling from focused element through ancestors
43+- **TextInput** — grapheme-aware text editing (Intl.Segmenter for emoji/ZWJ), cursor movement, cursor persistence across re-renders (keyed on onChange, clamped on external value changes), batched key handling with preserved edit state across stdin chunks, auto-scroll to keep cursor visible, inverted-cell cursor with native terminal cursor positioning (blinking), background fill, placeholder rendering
4444 - **Layering** — multi-layer compositing, transparency, topmost-layer input priority
45-- **Terminal** — Kitty keyboard protocol enable/disable, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
45+- **Terminal** — Kitty level 1 enable/disable, mixed keyboard stream compatibility in tmux, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
4646
4747 See `TODO.md` for remaining spec violations and future work.
4848
@@ -71,13 +71,13 @@ Use a tmux session to run examples and visually inspect rendered output.
7171
7272 ### tmux Configuration
7373
74-cel-tui requires the Kitty keyboard protocol. tmux 3.2+ supports it via the `extended-keys` option, but it's **off by default**. The global `~/.tmux.conf` must include:
74+cel-tui is **Kitty-first**, but `tmux` is a supported environment. tmux 3.2+ should have `extended-keys` enabled so it preserves as much modifier information as possible:
7575
7676 ```
7777 set -s extended-keys on
7878 ```
7979
80-Without this, tmux intercepts the protocol negotiation and key events arrive in legacy format that the framework's parser won't recognize.
80+With that setting enabled, common keyboard-driven checks work well through `tmux send-keys`. Without it, cel-tui still accepts many recoverable legacy encodings, but historically ambiguous collisions remain collapsed by the host (`ctrl+i`/`tab`, `ctrl+m`/`enter`, `ctrl+[`/`escape`).
8181
8282 ### Usage
8383
@@ -91,7 +91,8 @@ tmux send-keys -t cel "cd /home/xonecas/src/cel-tui && bun run examples/hello.ts
9191 # Wait for render, then capture the screen contents
9292 sleep 1; tmux capture-pane -t cel -p
9393
94-# Send keystrokes (e.g., Ctrl+Q to quit)
94+# Send common keystrokes directly
95+# (printable chars, Tab/BTab, Enter, Escape, arrows, many Ctrl+letter combos)
9596 tmux send-keys -t cel C-q
9697
9798 # Resize the window to test different terminal sizes
@@ -101,11 +102,25 @@ tmux resize-window -t cel -x 60 -y 20
101102 tmux kill-session -t cel
102103 ```
103104
104-This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
105+This lets you see exactly what the user sees — rendered cells, alignment, clipping, and, via `capture-pane -e -p`, style escape sequences — without needing a real interactive terminal.
105106
106-### Sending Keys with the Kitty Protocol
107+### Sending Keys in tmux
107108
108-cel-tui requires the Kitty keyboard protocol. `tmux send-keys` named keys (e.g., `C-q`, `Enter`) inject **legacy** byte sequences that the framework's parser won't recognize. Use the `kittyEncode` test helper with `send-keys -H` (hex mode) instead:
109+For most keyboard-driven manual checks, plain `tmux send-keys` is now sufficient:
110+
111+```bash
112+# Common cases that work well in tmux with extended-keys on
113+tmux send-keys -t cel a
114+tmux send-keys -t cel Enter
115+tmux send-keys -t cel Escape
116+tmux send-keys -t cel Tab
117+tmux send-keys -t cel BTab
118+tmux send-keys -t cel Up
119+tmux send-keys -t cel C-q
120+tmux send-keys -t cel C-r
121+```
122+
123+Use exact Kitty-style injection only when you need to test protocol-specific sequences or combos that tmux named keys do not express reliably (for example `shift+enter`, `ctrl+plus`, or a precise CSI-u path):
109124
110125 ```bash
111126 # Helper: convert a key name to hex bytes via kittyEncode
@@ -120,39 +135,37 @@ send_key() {
120135 }
121136
122137 # Usage:
123-send_key "ctrl+q" # Quit
124-send_key "tab" # Focus traversal
125-send_key "enter" # Activate
126-send_key "escape" # Unfocus
127-send_key "a" # Printable character (lowercase only)
128-send_key "ctrl+s" # Modifier combo
129-send_key "shift+tab" # Reverse focus traversal
138+send_key "ctrl+q"
139+send_key "shift+enter"
140+send_key "ctrl+plus"
141+send_key "shift+tab"
130142 ```
131143
132-**Limitations:** The helper lowercases all input, so uppercase letters aren't testable this way.
144+**Limitations:** the helper lowercases printable input, so uppercase-text insertion is still better tested with plain `tmux send-keys` or in a real terminal.
133145
134-**Caveat:** tmux `send-keys -H` injects raw bytes one event at a time, but real terminals batch multiple mouse events into a single stdin chunk. Always verify mouse/scroll behavior in a real terminal, not just tmux.
146+**Caveat:** `tmux send-keys -H` injects raw bytes one event at a time, while real terminals may batch multiple keyboard or mouse events into a single stdin chunk. Use hex injection to target exact encodings, not to simulate full terminal behavior.
135147
136148 ### Mouse Events Don't Work in tmux
137149
138-SGR mouse events (click, scroll) sent via `tmux send-keys -H` are **unreliable** and should not be used for testing. Even with correctly-formatted SGR press/release byte sequences and `mouse off` in tmux config, the injected bytes may not reach the application's stdin in a form the parser recognizes. This is a known tmux limitation with raw byte injection for mouse protocols.
150+SGR mouse events (click, scroll) sent through tmux remain **unreliable** and should not be used for verification. Even with correctly formatted SGR sequences and `mouse off` in tmux config, the injected bytes may not reach the application's stdin in a form the parser recognizes. This is a tmux limitation around raw mouse protocol injection.
139151
140-**Do not test mouse interactions (click, scroll) through tmux.** Use tmux only for:
152+**Do not treat tmux as authoritative for mouse interactions (click, scroll).** Use tmux for:
141153
142-- Keyboard-driven testing via `send_key` helper
143-- Visual inspection of rendered output via `tmux capture-pane -p`
144-- Verifying layout, alignment, and text content
154+- Keyboard-driven testing via plain `tmux send-keys` for common keys
155+- Exact keyboard-sequence injection via `send_key` when you need protocol precision
156+- Visual inspection via `tmux capture-pane -p` / `tmux capture-pane -e -p`
157+- Verifying layout, alignment, text content, and many keyboard flows
145158
146-Mouse and scroll behavior must be verified in a real interactive terminal.
159+Mouse and scroll behavior still need verification in a real interactive terminal.
147160
148161 ### tmux capture-pane Limitations
149162
150163 `tmux capture-pane -p` captures **plain text only** — no colors or style attributes. This means:
151164
152165 - You can verify text content, alignment, and layout structure
153-- You **cannot** verify `fgColor`, `bgColor`, `bold`, `focusStyle` changes, or any visual styling
166+- You **cannot** verify `fgColor`, `bgColor`, `bold`, or `focusStyle` changes from plain-text capture alone
154167
155-To inspect colors, use `tmux capture-pane -e -p` (includes escape sequences) or verify styling through unit tests against the cell buffer.
168+To inspect styling, use `tmux capture-pane -e -p` (includes escape sequences) or verify style output through unit tests against the cell buffer.
156169
157170 ## Spec
158171
@@ -203,15 +216,15 @@ chore: scaffold monorepo with types, core, components packages
203216
204217 ## Architecture Notes
205218
206-- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Mouse input handles batched SGR events (terminals often send multiple events in a single data chunk). TextInput key handling: `onKeyPress` fires before built-in editing logic — returning `false` prevents the …
219+- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Input handling treats stdin as a mixed stream: keyboard chunks may contain multiple decoded key events, mouse input handles batched SGR events, and TextInput batching preserves the latest value/cursor across m …
207220 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
208221 - `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets (clamped to max — apps can pass `Infinity` to mean "scroll to end"), scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state (with cursor screen position export for native cursor), TextInput background fill, container bgColor fill, style inheritance threading, focusStyle resolution.
209222 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both accept an optional `Theme` for color resolution and wrap in CSI 2026 synchronized output. Exports `defaultTheme` (ANSI 16 mapping).
210223 - `hit-test.ts` — `hitTest(root, x, y, getScrollOffset?)` → path from root to deepest node at `(x,y)`, accounting for scroll offsets. `findClickHandler`, `findScrollTarget`, `collectKeyPressHandlers`, `collectFocusable` walk paths.
211-- `keys.ts` — Kitty keyboard protocol parser. `parseKey(data)` handles CSI u sequences (special keys, modifier combos), CSI letter sequences (arrows, Home/End with modifiers), CSI tilde sequences (Delete, PageUp/Down, F-keys with modifiers), and raw printable bytes. Maps `" "` → `"space"`, `"+"` → `"plus"` as named keys. `isEditingKey()` identifies keys consumed by TextInput. `normalizeKey()` reorders modifiers to canonical `ctrl+alt+shift+<key>` order.
224+- `keys.ts` — Kitty-first input decoder. `decodeKeyEvents(data)` splits a raw chunk into ordered key events, accepting CSI u / CSI letter / CSI tilde sequences, recoverable legacy ASCII control bytes, ESC-prefixed Alt combos, and raw printable text. Key events carry a normalized semantic `key` plus optional original insertable `text`. `parseKey(data)` remains as a convenience wrapper for single-event cases. `isEditingKey()` identifies non-text editing/navigation keys consumed by TextInput, and …
212225 - `text-edit.ts` — Pure text editing functions (`insertChar`, `deleteBackward`, `deleteForward`, `moveCursor`). Operates on `EditState` (value + cursor position). Uses `Intl.Segmenter` with grapheme granularity for cursor movement and deletion (handles emoji, ZWJ sequences, combining marks). Used by `cel.ts` to handle TextInput key events.
213226 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
214-- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1, SGR mouse, crash cleanup) and `MockTerminal` (testing).
227+- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1 enable, SGR mouse, crash cleanup) and `MockTerminal` (testing). The runtime prefers Kitty semantics but the parser still accepts mixed tmux/legacy keyboard encodings.
215228
216229 ## Updating gh-pages
217230
README.md+10−2
@@ -1,6 +1,6 @@
11 # cel-tui
22
3-A TypeScript TUI framework built around a declarative functional API and ultra-fast rendering.
3+A TypeScript TUI framework built around a declarative functional API, ultra-fast rendering, and Kitty-first keyboard input that also works well in tmux.
44
55 <p align="center">
66 <picture>
@@ -67,7 +67,15 @@ cel.viewport(() =>
6767 - **Style inheritance** — containers propagate styles to descendants. `bgColor` fills the rect.
6868 - **16-color palette** — numbered slots (`"color00"`–`"color15"`) mapped to ANSI 16 by default. Custom themes can remap to different ANSI indices or 24-bit true color.
6969 - **Cell buffer rendering** — styled cells, differential updates, synchronized output.
70-- **Kitty keyboard protocol** — unambiguous key input with full modifier support. Requires a [compatible terminal](https://sw.kovidgoyal.net/kitty/keyboard-protocol/#progressive-enhancement) (Kitty, WezTerm, Ghostty, foot, Alacritty, Windows Terminal).
70+- **Kitty-first keyboard input** — cel-tui enables Kitty level 1 for full modifier fidelity, works well in `tmux` with `set -s extended-keys on`, and accepts recoverable legacy encodings when the host does not preserve a pure Kitty stream.
71+
72+## Terminal Compatibility
73+
74+- **First-class:** Kitty-compatible terminals such as Kitty, WezTerm, Ghostty, foot, Alacritty, and Windows Terminal
75+- **First-class:** `tmux` with `set -s extended-keys on`
76+- **Best effort:** legacy terminals or multiplexers that collapse some modifier distinctions
77+
78+Some historical legacy collisions remain impossible to recover once a host has already collapsed them — for example `ctrl+i` vs `tab`, `ctrl+m` vs `enter`, and `ctrl+[` vs `escape`.
7179
7280 ## Packages
7381
TODO.md+0−2
@@ -12,8 +12,6 @@ Remaining work, known bugs, and planned improvements.
1212
1313 ## Bugs / Spec Violations
1414
15-- 🔧 **Streaming wrapped Markdown with inline formatting can corrupt until rendering settles** — high priority. The risky behavior is in `packages/components/src/markdown.ts`: plain paragraphs render as a single `Text(..., { wrap: "word" })`, but formatted paragraphs/list items/blockquote content render as `HStack({ flexWrap: "wrap" })` trees built from split inline spans. During streaming, partial markdown can change shape across renders (for example plain text becoming a formatted span onc …
16-
1715 - 🔧 **Scrollbar thumb position ignores padding** — `paintScrollbar` in `paint.ts` computes `maxOffset = contentHeight - rect.height` without accounting for container padding, while the scroll clamping logic uses `contentHeight + padY - rect.height`. For padded scrollable containers the thumb position is slightly off.
1816
1917 - 🔧 **Key events leak through layers** — When no element is focused and the topmost layer's root has no `onKeyPress`, `handleKeyEvent` falls through to lower layers. Mouse input stops at the topmost layer with a node at the event position, but keyboard input doesn't follow the same rule. A modal overlay without its own root `onKeyPress` would leak keys to the base layer, breaking the "events target the topmost layer" principle.
docs/skill/cel-tui/SKILL.md+13−4
@@ -2,7 +2,7 @@
22 name: cel-tui
33 description: Build terminal user interfaces with cel-tui, a TypeScript TUI framework. Use when the user wants to create a TUI app, build a terminal UI, render text in the terminal, create a CLI with interactive elements, build a chat interface, text editor, or any interactive terminal application. Triggers include "build a TUI", "terminal UI", "interactive CLI", "text-based interface", "render to terminal", or any task requiring a programmatic terminal user interface.
44 license: MIT
5-compatibility: Requires Bun runtime and a terminal supporting the Kitty keyboard protocol and SGR mouse mode.
5+compatibility: Requires Bun runtime. Best experience on Kitty-compatible terminals and in tmux with `set -s extended-keys on`; uses SGR mouse mode and accepts recoverable legacy key encodings when hosts do not preserve a pure Kitty stream.
66 metadata:
77 author: sacenox
88 version: "0.4.0"
@@ -10,7 +10,15 @@ metadata:
1010
1111 # Building TUIs with cel-tui
1212
13-cel-tui is a TypeScript TUI framework with a declarative functional API, flexbox layout, cell-buffer rendering, and style inheritance. It has 4 primitives and external state management.
13+cel-tui is a TypeScript TUI framework with a declarative functional API, flexbox layout, cell-buffer rendering, style inheritance, and Kitty-first keyboard input. It has 4 primitives and external state management.
14+
15+## Terminal compatibility
16+
17+- **First-class:** Kitty-compatible terminals
18+- **First-class:** `tmux` with `set -s extended-keys on`
19+- **Best effort:** legacy terminals or multiplexers that collapse some modifier distinctions
20+
21+cel-tui enables Kitty level 1 for full modifier fidelity, but it also accepts recoverable legacy control bytes and ESC-prefixed Alt combinations so common keyboard flows keep working in tmux and mixed environments.
1422
1523 ## Install
1624
@@ -225,7 +233,7 @@ mySelect.reset(); // clear filter/highlight programmatically
225233
226234 - **State is external** — the framework has no state. Mutate variables then call `cel.render()`.
227235 - **Text is a pure leaf** — no sizing props, no children. Parent controls the box.
228-- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace, Enter, Tab). Enter inserts a newline by default. Use `onKeyPress` on TextInput to intercept keys before editing — return `false` to prevent the default action (e.g., intercept Enter for submit). Modifier combos (`ctrl+s`) are not editing keys and bubble up through ancestors via `onKeyPress`.
236+- **TextInput consumes insertable text and editing/navigation keys** when focused (printable text, arrows, backspace, Enter, Tab). Enter inserts a newline by default. Use `onKeyPress` on TextInput to intercept keys before editing — return `false` to prevent the default action (e.g., intercept Enter for submit). `onKeyPress` receives normalized semantic key strings, while inserted text preserves the original characters (uppercase `A` arrives as key `"a"` but inserts `"A"`). Modifier combos (`ct …
229237 - **Escape unfocuses** the current element. Tab/Shift+Tab traverses focusable elements (wraps around). After Escape, traversal continues from where focus was lost.
230238 - **Enter activates** a focused container's `onClick`. If no `onClick`, Enter reaches `onKeyPress`.
231239 - **`focusable: true`** without `onClick` makes a container keyboard-focusable (receives `onKeyPress` events via Tab). Used by stateful components like `Select`.
@@ -236,7 +244,8 @@ mySelect.reset(); // clear filter/highlight programmatically
236244 - **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
237245 - **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
238246 - **Always call `cel.stop()` before `process.exit()`** — restores raw mode, mouse tracking, and alternate screen.
239-- **Kitty keyboard protocol required** — the framework requires the Kitty keyboard protocol (level 1). All modifier combos (`alt+x`, `ctrl+plus`, `shift+enter`) are fully supported. The terminal must support this protocol (Kitty, WezTerm, Ghostty, foot, Alacritty, Windows Terminal). macOS Terminal.app and older xterm are not supported.
247+- **Kitty-first keyboard input** — the framework enables Kitty level 1 and gets full modifier fidelity when the host preserves it (`alt+x`, `ctrl+plus`, `shift+enter`, etc.). It also normalizes recoverable legacy encodings so common shortcuts keep working in tmux. For best results, use a Kitty-compatible terminal or `tmux` with `set -s extended-keys on`. On older legacy hosts, historically ambiguous collisions such as `ctrl+i` vs `tab` or `ctrl+m` vs `enter` cannot be recovered once the host c …
248+- **tmux is good for keyboard-driven manual checks** — common `tmux send-keys` paths work for printable chars, `Tab`/`BTab`, `Enter`, `Escape`, arrows, and many `Ctrl+letter` shortcuts. Use exact raw-sequence injection only when you need to target a protocol-specific encoding. Mouse input remains unreliable in tmux and should be verified in a real terminal.
240249 - **Button limitations** — `Button` from `@cel-tui/components` does not forward container sizing props (`width`, `height`, `flex`, `minWidth`, etc.). It supports styling (`fgColor`, `bgColor`, `bold`, etc.), `focusStyle`, `focused`, `onFocus`, `onBlur`, `onKeyPress`, and `padding`. For full layout control, use `HStack` + `Text` directly.
241250
242251 ## Composing Components
docs/skill/cel-tui/references/api.md+6−2
@@ -33,7 +33,7 @@ All props accepted by `VStack` and `HStack`:
3333 focused, // boolean (controlled — omit for uncontrolled)
3434 onFocus, // () => void
3535 onBlur, // () => void
36- onKeyPress, // (key: string) => boolean | void — return false to keep bubbling
36+ onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to keep bubbling
3737 }
3838 ```
3939
@@ -88,7 +88,7 @@ Colors: 16 numbered palette slots — `"color00"` through `"color15"`. Mapped to
8888 TextInput({
8989 value, // string (controlled)
9090 onChange, // (value: string) => void
91- onKeyPress, // (key: string) => boolean | void — return false to prevent default editing action
91+ onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to prevent default editing action
9292 placeholder, // Text() node shown when empty
9393 // + all container props (sizing, styling, focus, scrollStep, etc.)
9494 });
@@ -110,6 +110,8 @@ TextInput({
110110 });
111111 ```
112112
113+When focused, TextInput consumes insertable text plus editing/navigation keys. Modifier combos and non-insertable control keys bubble. Key strings are semantic identifiers for handlers, not necessarily the exact inserted text — uppercase `A` normalizes to key `"a"` while still inserting `"A"`.
114+
113115 ## Sizing Strategies
114116
115117 Containers accept 4 sizing strategies:
@@ -131,6 +133,8 @@ TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`,
131133
132134 All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`, `"enter"`, `"alt+up"`, `"f1"`. Framework normalizes modifier order.
133135
136+cel-tui is **Kitty-first** and works well in `tmux` with `set -s extended-keys on`. Recoverable legacy forms normalize to the same key strings, but historically collapsed collisions (`ctrl+i` vs `tab`, `ctrl+m` vs `enter`, `ctrl+[` vs `escape`) remain limited by what the host terminal or multiplexer reports.
137+
134138 ## Pre-made Components
135139
136140 ```ts
packages/components/src/button.ts+2−2
@@ -34,8 +34,8 @@ export interface ButtonProps extends StyleProps {
3434 */
3535 focusStyle?: StyleProps;
3636 /**
37- * Key event handler. Receives keys that bubble up to this button.
38- * Return `false` to keep bubbling.
37+ * Key event handler. Receives normalized semantic keys that bubble up
38+ * to this button. Return `false` to keep bubbling.
3939 */
4040 onKeyPress?: (key: string) => boolean | void;
4141 /** Internal padding in cells. */
packages/components/src/select.ts+1−1
@@ -65,7 +65,7 @@ export interface SelectProps {
6565 * Called on key events that bubble up to the Select.
6666 * Return `false` to keep bubbling to ancestors.
6767 *
68- * @param key - The key string.
68+ * @param key - The normalized semantic key string.
6969 */
7070 onKeyPress?: (key: string) => boolean | void;
7171 /** Fixed width in cells or percentage. */
packages/core/src/cel.test.ts+24−0
@@ -12,6 +12,7 @@ const ENTER = kittyEncode("enter");
1212 const ESCAPE = kittyEncode("escape");
1313 const SHIFT_TAB = kittyEncode("shift+tab");
1414 const CTRL_S = kittyEncode("ctrl+s");
15+const LEGACY_CTRL_R = "\x12";
1516
1617 describe("cel end-to-end", () => {
1718 let term: MockTerminal;
@@ -186,6 +187,29 @@ describe("cel end-to-end", () => {
186187 expect(receivedKey).toBe("ctrl+s");
187188 });
188189
190+ test("batched keyboard events are all processed in order", async () => {
191+ const term = setup(20, 5);
192+ const receivedKeys: string[] = [];
193+ cel.viewport(() =>
194+ VStack(
195+ {
196+ width: 20,
197+ height: 5,
198+ onKeyPress: (key) => {
199+ receivedKeys.push(key);
200+ },
201+ },
202+ [Text("hello")],
203+ ),
204+ );
205+ await waitForRender();
206+
207+ term.sendInput(`${LEGACY_CTRL_R}${CTRL_S}`);
208+ await waitForRender();
209+
210+ expect(receivedKeys).toEqual(["ctrl+r", "ctrl+s"]);
211+ });
212+
189213 test("onScroll fires on mouse wheel using the adaptive default step", async () => {
190214 const term = setup(20, 12);
191215 let scrollOffset = 0;
packages/core/src/cel.ts+67−37
@@ -1,4 +1,9 @@
1-import type { Node, Theme } from "@cel-tui/types";
1+import type {
2+ Node,
3+ TextInputNode,
4+ TextInputProps,
5+ Theme,
6+} from "@cel-tui/types";
27 import { CellBuffer } from "./cell-buffer.js";
38 import { emitBuffer, emitDiff, defaultTheme } from "./emitter.js";
49 import {
@@ -8,7 +13,7 @@ import {
813 collectKeyPressHandlers,
914 collectFocusable,
1015 } from "./hit-test.js";
11-import { parseKey, isEditingKey } from "./keys.js";
16+import { decodeKeyEvents, isEditingKey, type KeyInput } from "./keys.js";
1217 import { layout, type LayoutNode } from "./layout.js";
1318 import {
1419 paint,
@@ -195,25 +200,49 @@ const SGR_MOUSE_RE = /\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;
195200 // need to remember the offset we already dispatched via onScroll.
196201 let batchScrollOffsets: Map<object, number> | null = null;
197202
203+// Tracks the focused TextInput's latest edit state during a batched keyboard
204+// chunk. The layout tree does not re-render until the next tick, so subsequent
205+// keys in the same chunk must see the updated value/cursor immediately.
206+let batchTextInputEdits: Map<TextInputProps, EditState> | null = null;
207+
198208 function handleInput(data: string): void {
199- // Terminals may batch multiple mouse events into one data chunk.
200- // Scan for all SGR mouse sequences and handle each one.
201209 SGR_MOUSE_RE.lastIndex = 0;
202- let match = SGR_MOUSE_RE.exec(data);
203- if (match) {
204- batchScrollOffsets = new Map();
210+ batchTextInputEdits = new Map();
211+
212+ let lastIndex = 0;
213+
214+ try {
215+ let match = SGR_MOUSE_RE.exec(data);
205216 while (match) {
217+ if (match.index > lastIndex) {
218+ handleKeyChunk(data.slice(lastIndex, match.index));
219+ }
220+
221+ if (batchScrollOffsets === null) {
222+ batchScrollOffsets = new Map();
223+ }
224+
206225 const mouse = parseSgrMatch(match);
207226 if (mouse) handleMouseEvent(mouse);
227+
228+ lastIndex = match.index + match[0].length;
208229 match = SGR_MOUSE_RE.exec(data);
209230 }
231+
232+ if (lastIndex < data.length) {
233+ handleKeyChunk(data.slice(lastIndex));
234+ }
235+ } finally {
210236 batchScrollOffsets = null;
211- return;
237+ batchTextInputEdits = null;
212238 }
239+}
213240
214- // Keyboard input
215- const key = parseKey(data);
216- handleKeyEvent(key, data);
241+function handleKeyChunk(data: string): void {
242+ if (data.length === 0) return;
243+ for (const key of decodeKeyEvents(data)) {
244+ handleKeyEvent(key);
245+ }
217246 }
218247
219248 interface MouseEvent {
@@ -572,7 +601,18 @@ function findClickFocusTarget(path: LayoutNode[]): LayoutNode | null {
572601 return null;
573602 }
574603
575-function handleKeyEvent(key: string, rawData?: string): void {
604+function getTextInputEditState(props: TextInputProps): EditState {
605+ const batched = batchTextInputEdits?.get(props);
606+ if (batched) return batched;
607+ return {
608+ value: props.value,
609+ cursor: getTextInputCursor(props),
610+ };
611+}
612+
613+function handleKeyEvent(event: KeyInput): void {
614+ const { key, text } = event;
615+
576616 // --- Focus traversal keys ---
577617
578618 // Tab / Shift+Tab: cycle through focusable elements
@@ -646,12 +686,10 @@ function handleKeyEvent(key: string, rawData?: string): void {
646686 }
647687
648688 // --- TextInput key routing ---
649- // Find the focused TextInput (if any) to route editing keys
650689 const focusedInput = findFocusedTextInput();
651690
652691 if (focusedInput) {
653- const props = focusedInput.node
654- .props as import("@cel-tui/types").TextInputProps;
692+ const props = focusedInput.node.props as TextInputProps;
655693
656694 // onKeyPress fires before editing — return false prevents the default action
657695 if (props.onKeyPress) {
@@ -662,12 +700,12 @@ function handleKeyEvent(key: string, rawData?: string): void {
662700 }
663701 }
664702
665- // Editing keys are consumed by TextInput
666- if (isEditingKey(key)) {
667- const cursor = getTextInputCursor(props);
668- const editState: EditState = { value: props.value, cursor };
669- let newState: EditState | null = null;
703+ let newState: EditState | null = null;
704+ const editState = getTextInputEditState(props);
670705
706+ if (text !== undefined) {
707+ newState = insertChar(editState, text);
708+ } else if (isEditingKey(key)) {
671709 switch (key) {
672710 case "backspace":
673711 newState = deleteBackward(editState);
@@ -683,8 +721,7 @@ function handleKeyEvent(key: string, rawData?: string): void {
683721 case "end":
684722 {
685723 const tiPadX =
686- (focusedInput.node as import("@cel-tui/types").TextInputNode)
687- .props.padding?.x ?? 0;
724+ (focusedInput.node as TextInputNode).props.padding?.x ?? 0;
688725 const contentWidth = Math.max(
689726 0,
690727 focusedInput.rect.width - tiPadX * 2,
@@ -709,24 +746,17 @@ function handleKeyEvent(key: string, rawData?: string): void {
709746 case "plus":
710747 newState = insertChar(editState, "+");
711748 break;
712- default:
713- // Single printable character — use raw data to preserve case
714- if (key.length === 1 && rawData && rawData.length === 1) {
715- newState = insertChar(editState, rawData);
716- } else if (key.length === 1) {
717- newState = insertChar(editState, key);
718- }
719- break;
720749 }
750+ }
721751
722- if (newState && newState !== editState) {
723- setTextInputCursor(props, newState.cursor);
724- if (newState.value !== editState.value) {
725- props.onChange(newState.value);
726- }
727- cel.render();
728- return;
752+ if (newState && newState !== editState) {
753+ batchTextInputEdits?.set(props, newState);
754+ setTextInputCursor(props, newState.cursor);
755+ if (newState.value !== editState.value) {
756+ props.onChange(newState.value);
729757 }
758+ cel.render();
759+ return;
730760 }
731761 }
732762
packages/core/src/keys.test.ts+17−0
@@ -117,6 +117,21 @@ describe("parseKey", () => {
117117 });
118118 });
119119
120+ describe("legacy compatibility encodings", () => {
121+ test("recoverable ASCII control bytes normalize to ctrl+letter", () => {
122+ expect(parseKey("\x01")).toBe("ctrl+a");
123+ expect(parseKey("\x08")).toBe("ctrl+h");
124+ expect(parseKey("\x12")).toBe("ctrl+r");
125+ expect(parseKey("\x1a")).toBe("ctrl+z");
126+ });
127+
128+ test("ESC-prefixed Alt combinations normalize to alt+<key>", () => {
129+ expect(parseKey("\x1bx")).toBe("alt+x");
130+ expect(parseKey("\x1bX")).toBe("alt+x");
131+ expect(parseKey("\x1b+")).toBe("alt+plus");
132+ });
133+ });
134+
120135 // --- CSI u: special keys (also valid, sent by some terminals) ---
121136
122137 describe("CSI u special keys", () => {
@@ -292,7 +307,9 @@ describe("isEditingKey", () => {
292307
293308 test("modifier combos are NOT editing keys", () => {
294309 expect(isEditingKey("ctrl+s")).toBe(false);
310+ expect(isEditingKey("ctrl+r")).toBe(false);
295311 expect(isEditingKey("alt+x")).toBe(false);
312+ expect(isEditingKey("alt+plus")).toBe(false);
296313 expect(isEditingKey("ctrl+shift+n")).toBe(false);
297314 expect(isEditingKey("shift+tab")).toBe(false);
298315 });
packages/core/src/keys.ts+141−64
@@ -1,7 +1,7 @@
11 /**
2- * Key parsing for the Kitty keyboard protocol (level 1 — disambiguate).
2+ * Key parsing for Kitty-first terminal input with legacy compatibility.
33 *
4- * At level 1, the terminal sends:
4+ * The decoder accepts a mixed keyboard stream containing:
55 * - **CSI u** (`ESC [ codepoint ; modifiers u`) for modified special keys
66 * and modifier combos (Ctrl+letter, Alt+letter, Shift+Tab, Ctrl+Enter, etc.)
77 * - **CSI letter** (`ESC [ A/B/C/D/H/F` or `ESC [ 1 ; modifiers letter`) for
@@ -9,16 +9,26 @@
99 * - **CSI tilde** (`ESC [ number ~` or `ESC [ number ; modifiers ~`) for
1010 * Delete, PageUp, PageDown, and function keys
1111 * - **Legacy bytes** for unmodified special keys (Tab=0x09, Enter=0x0D,
12- * Escape=0x1B, Backspace=0x7F) — these retain their traditional encoding
13- * - **Raw bytes** for unmodified printable characters
12+ * Escape=0x1B, Backspace=0x7F)
13+ * - **Recoverable control bytes** for legacy `ctrl+letter` shortcuts
14+ * - **ESC-prefixed Alt combinations** such as `ESC x`
15+ * - **Raw printable text**
1416 *
1517 * Modifier bitmask (wire value = bitmask + 1):
16- * shift=1, alt=2, ctrl=4 → e.g., ctrl = bitmask 4, wire param = 5
18+ * shift=1, alt=2, ctrl=4 -> e.g., ctrl = bitmask 4, wire param = 5
1719 *
1820 * @module
1921 */
2022
21-// --- Codepoint → named key mappings ---
23+/** A decoded keyboard event from the terminal input stream. */
24+export interface KeyInput {
25+ /** Normalized semantic key string (e.g. `"ctrl+s"`, `"enter"`, `"a"`). */
26+ key: string;
27+ /** Original insertable text, when this key should insert text. */
28+ text?: string;
29+}
30+
31+// --- Codepoint -> named key mappings ---
2232
2333 /** Named key lookup from Unicode codepoint (for CSI u sequences). */
2434 const CODEPOINT_NAMES: Record<number, string> = {
@@ -60,7 +70,7 @@ const TILDE_NAMES: Record<number, string> = {
6070 };
6171
6272 /**
63- * Legacy byte → named key mapping for unmodified special keys.
73+ * Legacy byte -> named key mapping for unmodified special keys.
6474 *
6575 * At Kitty level 1, unmodified special keys that have well-known legacy
6676 * encodings retain those encodings. Only modified variants (e.g., Shift+Tab,
@@ -68,8 +78,8 @@ const TILDE_NAMES: Record<number, string> = {
6878 * bytes that arrive for the unmodified case.
6979 */
7080 const LEGACY_BYTE_NAMES: Record<number, string> = {
71- 9: "tab", // \t — also Ctrl+I in legacy, but at level 1 Ctrl+I → CSI u
72- 13: "enter", // \r — also Ctrl+M in legacy, but at level 1 Ctrl+M → CSI u
81+ 9: "tab", // \t — also Ctrl+I in legacy, but collapsed to tab here
82+ 13: "enter", // \r — also Ctrl+M in legacy, but collapsed to enter here
7383 27: "escape", // \x1b — bare ESC byte
7484 127: "backspace", // \x7f — DEL byte
7585 };
@@ -99,9 +109,7 @@ function decodeModifiers(param: number): string {
99109 return parts.length > 0 ? parts.join("+") + "+" : "";
100110 }
101111
102-/**
103- * Build a key string from a modifier prefix and base key name.
104- */
112+/** Build a key string from a modifier prefix and base key name. */
105113 function withModifiers(modParam: number, base: string): string {
106114 return decodeModifiers(modParam) + base;
107115 }
@@ -117,88 +125,157 @@ const CSI_LETTER_RE = /^(?:1;(\d+))?([A-H])$/;
117125 /** Match CSI tilde format: ESC [ <number> ; <modifiers> ~ */
118126 const CSI_TILDE_RE = /^(\d+)(?:;(\d+))?~$/;
119127
120-function parseCsiSequence(seq: string): string {
128+function parseCsiSequence(seq: string): KeyInput {
121129 // Legacy Shift+Tab (CSI Z) — sent by tmux and some terminals
122- if (seq === "Z") return "shift+tab";
130+ if (seq === "Z") return { key: "shift+tab" };
123131
124132 // CSI u format: codepoint [; modifiers] u
125133 let match = CSI_U_RE.exec(seq);
126134 if (match) {
127135 const codepoint = parseInt(match[1]!, 10);
128- const modParam = match[2] ? parseInt(match[2], 10) : 0;
136+ const modParam = match[2] ? parseInt(match[2]!, 10) : 0;
129137
130- // Check named keys first
131138 const name = CODEPOINT_NAMES[codepoint];
132- if (name) return withModifiers(modParam, name);
133-
134- // Printable character — convert codepoint to char, lowercase
135- const char = String.fromCodePoint(codepoint).toLowerCase();
136- return withModifiers(modParam, char);
139+ if (name) {
140+ return { key: withModifiers(modParam, name) };
141+ }
142+
143+ const char = String.fromCodePoint(codepoint);
144+ const key = withModifiers(modParam, char.toLowerCase());
145+ if (modParam <= 1) {
146+ return { key, text: char };
147+ }
148+ return { key };
137149 }
138150
139151 // CSI letter format: [1 ; modifiers] <letter>
140152 match = CSI_LETTER_RE.exec(seq);
141153 if (match) {
142- const modParam = match[1] ? parseInt(match[1], 10) : 0;
154+ const modParam = match[1] ? parseInt(match[1]!, 10) : 0;
143155 const letter = match[2]!;
144156 const name = LETTER_NAMES[letter];
145- if (name) return withModifiers(modParam, name);
157+ if (name) return { key: withModifiers(modParam, name) };
146158 }
147159
148160 // CSI tilde format: number [; modifiers] ~
149161 match = CSI_TILDE_RE.exec(seq);
150162 if (match) {
151163 const num = parseInt(match[1]!, 10);
152- const modParam = match[2] ? parseInt(match[2], 10) : 0;
164+ const modParam = match[2] ? parseInt(match[2]!, 10) : 0;
153165 const name = TILDE_NAMES[num];
154- if (name) return withModifiers(modParam, name);
166+ if (name) return { key: withModifiers(modParam, name) };
155167 }
156168
157- return `unknown:${seq}`;
169+ return { key: `unknown:${seq}` };
158170 }
159171
160-// --- Public API ---
161-
162-/**
163- * Parse raw terminal input data into a normalized key string.
164- *
165- * Handles the Kitty keyboard protocol level 1 (disambiguate) encoding:
166- * - CSI u sequences for special keys and modifier combos
167- * - CSI letter sequences for arrow keys and Home/End (with optional modifiers)
168- * - CSI tilde sequences for Delete, PageUp/Down, and function keys
169- * - Raw printable characters (unmodified, arrive as raw bytes at level 1)
170- *
171- * @param data - Raw terminal input string.
172- * @returns Normalized key string (e.g., `"ctrl+s"`, `"escape"`, `"alt+up"`).
173- */
174-export function parseKey(data: string): string {
175- // CSI sequences: ESC [ ...
176- if (data.startsWith("\x1b[")) {
177- return parseCsiSequence(data.slice(2));
172+function decodeLegacyControlByte(code: number): string | null {
173+ if (code >= 1 && code <= 26) {
174+ return `ctrl+${String.fromCharCode(code + 96)}`;
178175 }
176+ return null;
177+}
179178
180- // Single-character input
181- if (data.length === 1) {
182- const code = data.charCodeAt(0);
179+function parseRawKeyInput(data: string): KeyInput {
180+ const code = data.charCodeAt(0);
183181
184- // Legacy bytes for unmodified special keys (Kitty level 1 retains these)
185- const legacy = LEGACY_BYTE_NAMES[code];
186- if (legacy) return legacy;
182+ const legacy = LEGACY_BYTE_NAMES[code];
183+ if (legacy) return { key: legacy };
187184
188- // Named printable characters
189- const named = CHAR_NAMES[data];
190- if (named) return named;
185+ const ctrl = decodeLegacyControlByte(code);
186+ if (ctrl) return { key: ctrl };
187+
188+ const named = CHAR_NAMES[data];
189+ if (named) return { key: named, text: data };
190+
191+ return { key: data.toLowerCase(), text: data };
192+}
193+
194+function parseAltKeyInput(data: string): KeyInput {
195+ const base = parseRawKeyInput(data);
196+ return { key: normalizeKey(`alt+${base.key}`) };
197+}
191198
192- // Printable characters — return lowercase
193- return data.toLowerCase();
199+function readCodePoint(
200+ data: string,
201+ index: number,
202+): { value: string; nextIndex: number } | null {
203+ if (index >= data.length) return null;
204+ const codepoint = data.codePointAt(index);
205+ if (codepoint === undefined) return null;
206+ const value = String.fromCodePoint(codepoint);
207+ return { value, nextIndex: index + value.length };
208+}
209+
210+function readCsiSequence(
211+ data: string,
212+ index: number,
213+): { value: string; nextIndex: number } | null {
214+ if (!data.startsWith("\x1b[", index)) return null;
215+
216+ for (let i = index + 2; i < data.length; i++) {
217+ const code = data.charCodeAt(i);
218+ if (code >= 0x40 && code <= 0x7e) {
219+ return { value: data.slice(index + 2, i + 1), nextIndex: i + 1 };
220+ }
194221 }
195222
196- // Multi-byte UTF-8 (e.g., emoji, CJK) — return as-is lowercase
197- if (data.length > 1) {
198- return data.toLowerCase();
223+ return null;
224+}
225+
226+/**
227+ * Decode a raw keyboard data chunk into ordered key events.
228+ *
229+ * A single chunk may contain multiple key presses batched together.
230+ */
231+export function decodeKeyEvents(data: string): KeyInput[] {
232+ const events: KeyInput[] = [];
233+ let index = 0;
234+
235+ while (index < data.length) {
236+ const csi = readCsiSequence(data, index);
237+ if (csi) {
238+ events.push(parseCsiSequence(csi.value));
239+ index = csi.nextIndex;
240+ continue;
241+ }
242+
243+ const char = data[index]!;
244+ if (char === "\x1b") {
245+ const next = readCodePoint(data, index + 1);
246+ if (next && next.value !== "[") {
247+ events.push(parseAltKeyInput(next.value));
248+ index = next.nextIndex;
249+ } else {
250+ events.push({ key: "escape" });
251+ index += 1;
252+ }
253+ continue;
254+ }
255+
256+ const codePoint = readCodePoint(data, index);
257+ if (!codePoint) break;
258+ events.push(parseRawKeyInput(codePoint.value));
259+ index = codePoint.nextIndex;
199260 }
200261
201- return `unknown:${data}`;
262+ return events;
263+}
264+
265+// --- Public API ---
266+
267+/**
268+ * Parse a single raw key sequence into a normalized key string.
269+ *
270+ * This is a convenience wrapper around {@link decodeKeyEvents} for callers that
271+ * already know the input contains one logical key event.
272+ *
273+ * @param data - Raw terminal input string.
274+ * @returns Normalized key string (e.g., `"ctrl+s"`, `"escape"`, `"alt+up"`).
275+ */
276+export function parseKey(data: string): string {
277+ const events = decodeKeyEvents(data);
278+ return events[0]?.key ?? `unknown:${data}`;
202279 }
203280
204281 /**
@@ -217,7 +294,6 @@ export function normalizeKey(key: string): string {
217294 const base = parts[parts.length - 1]!;
218295 const mods = parts.slice(0, -1);
219296
220- // Canonical order: ctrl, alt, shift
221297 const ordered: string[] = [];
222298 if (mods.includes("ctrl")) ordered.push("ctrl");
223299 if (mods.includes("alt")) ordered.push("alt");
@@ -227,14 +303,15 @@ export function normalizeKey(key: string): string {
227303 }
228304
229305 /**
230- * Check if a parsed key is a text-editing key that TextInput should consume.
231- * Modifier combos (ctrl+s, alt+x) are NOT editing keys and should bubble.
306+ * Check whether a semantic key represents TextInput editing/navigation.
307+ *
308+ * Single-character semantic keys represent insertable text, while named keys
309+ * like `"enter"` and `"left"` represent editing/navigation actions. Modifier
310+ * combos (`ctrl+s`, `alt+x`) are NOT editing keys and should bubble.
232311 */
233312 export function isEditingKey(key: string): boolean {
234- // Single printable characters
235313 if (key.length === 1) return true;
236314
237- // Navigation and editing keys consumed by TextInput
238315 const editingKeys = new Set([
239316 "enter",
240317 "backspace",
packages/core/src/primitives/text-input.ts+7−5
@@ -11,12 +11,14 @@ import type { TextInputNode, TextInputProps } from "@cel-tui/types";
1111 * Scroll is always uncontrolled — the view follows the cursor and
1212 * responds to mouse wheel automatically.
1313 *
14- * TextInput is always focusable. When focused, text-editing keys
15- * (printable characters, arrows, backspace, Enter, Tab) are consumed.
16- * Modifier combos (e.g., `ctrl+s`) bubble up to ancestor `onKeyPress` handlers.
14+ * TextInput is always focusable. When focused, it consumes insertable text
15+ * plus editing/navigation keys (arrows, backspace, delete, Enter, Tab).
16+ * Modifier combos (e.g., `ctrl+s`) and non-insertable control keys bubble
17+ * up to ancestor `onKeyPress` handlers.
1718 *
18- * Use `onKeyPress` to intercept keys before editing. Return `false` to
19- * prevent the default editing action for that key.
19+ * Use `onKeyPress` to intercept keys before editing. The handler receives a
20+ * normalized semantic key string; inserted text preserves the original
21+ * characters. Return `false` to prevent the default editing action.
2022 *
2123 * @param props - Value, callbacks, sizing, styling, and focus props.
2224 * @returns A text input node for the UI tree.
packages/core/src/terminal.ts+11−3
@@ -11,7 +11,13 @@ export interface Terminal {
1111 get columns(): number;
1212 /** Terminal height in rows. */
1313 get rows(): number;
14- /** Enter raw mode, enable Kitty keyboard protocol, enable mouse tracking, hide cursor. */
14+ /**
15+ * Enter raw mode, enable Kitty level 1 keyboard reporting, enable mouse
16+ * tracking, and hide the cursor.
17+ *
18+ * The framework prefers Kitty semantics but its parser also accepts mixed
19+ * tmux/legacy keyboard encodings that may still arrive on stdin.
20+ */
1521 start(onInput: (data: string) => void, onResize: () => void): void;
1622 /** Restore terminal state. */
1723 stop(): void;
@@ -24,8 +30,10 @@ export interface Terminal {
2430 /**
2531 * Real terminal using process.stdin/stdout.
2632 *
27- * Enables the Kitty keyboard protocol (level 1) for unambiguous key input,
28- * SGR mouse tracking, and raw mode. All modes are restored on stop/crash.
33+ * Enables Kitty keyboard protocol level 1, SGR mouse tracking, and raw mode.
34+ * The runtime prefers Kitty semantics for full modifier fidelity, while the
35+ * parser remains compatible with mixed tmux/legacy keyboard encodings that
36+ * may still arrive on stdin. All modes are restored on stop/crash.
2937 */
3038 export class ProcessTerminal implements Terminal {
3139 private wasRaw = false;
packages/core/src/text-input.test.ts+113−0
@@ -10,6 +10,8 @@ const ENTER = kittyEncode("enter");
1010 const BACKSPACE = kittyEncode("backspace");
1111 const CTRL_S = kittyEncode("ctrl+s");
1212 const LEFT = kittyEncode("left");
13+const LEGACY_CTRL_R = "\x12";
14+const LEGACY_ALT_X = "\x1bx";
1315
1416 describe("TextInput integration", () => {
1517 let term: MockTerminal;
@@ -75,6 +77,55 @@ describe("TextInput integration", () => {
7577 expect(value).toBe("hi!");
7678 });
7779
80+ test("batched printable input inserts all characters in order", async () => {
81+ const term = setup(20, 3);
82+ let value = "hi";
83+ cel.viewport(() =>
84+ VStack({}, [
85+ TextInput({
86+ value,
87+ focused: true,
88+ onChange: (v) => {
89+ value = v;
90+ },
91+ }),
92+ ]),
93+ );
94+ await waitForRender();
95+
96+ term.sendInput("ab");
97+ await waitForRender();
98+
99+ expect(value).toBe("hiab");
100+ });
101+
102+ test("onKeyPress receives normalized keys while TextInput inserts original text", async () => {
103+ const term = setup(20, 3);
104+ let keyReceived = "";
105+ let value = "";
106+ cel.viewport(() =>
107+ VStack({}, [
108+ TextInput({
109+ value,
110+ focused: true,
111+ onChange: (v) => {
112+ value = v;
113+ },
114+ onKeyPress: (key) => {
115+ keyReceived = key;
116+ },
117+ }),
118+ ]),
119+ );
120+ await waitForRender();
121+
122+ term.sendInput("A");
123+ await waitForRender();
124+
125+ expect(keyReceived).toBe("a");
126+ expect(value).toBe("A");
127+ });
128+
78129 test("backspace deletes character", async () => {
79130 const term = setup(20, 3);
80131 let value = "abc";
@@ -341,6 +392,68 @@ describe("TextInput integration", () => {
341392 expect(value).toBe("text"); // Value unchanged
342393 });
343394
395+ test("legacy ctrl+letter from tmux bubbles to ancestor without editing", async () => {
396+ const term = setup(20, 3);
397+ let parentKey = "";
398+ let value = "text";
399+ cel.viewport(() =>
400+ VStack(
401+ {
402+ onKeyPress: (key) => {
403+ parentKey = key;
404+ },
405+ },
406+ [
407+ TextInput({
408+ value,
409+ focused: true,
410+ onChange: (v) => {
411+ value = v;
412+ },
413+ }),
414+ ],
415+ ),
416+ );
417+ await waitForRender();
418+
419+ term.sendInput(LEGACY_CTRL_R);
420+ await waitForRender();
421+
422+ expect(parentKey).toBe("ctrl+r");
423+ expect(value).toBe("text");
424+ });
425+
426+ test("ESC-prefixed Alt combos bubble to ancestor without editing", async () => {
427+ const term = setup(20, 3);
428+ let parentKey = "";
429+ let value = "text";
430+ cel.viewport(() =>
431+ VStack(
432+ {
433+ onKeyPress: (key) => {
434+ parentKey = key;
435+ },
436+ },
437+ [
438+ TextInput({
439+ value,
440+ focused: true,
441+ onChange: (v) => {
442+ value = v;
443+ },
444+ }),
445+ ],
446+ ),
447+ );
448+ await waitForRender();
449+
450+ term.sendInput(LEGACY_ALT_X);
Cut short: this commit's diff is over 1000 lines.
packages/types/src/index.ts+11−1
Cut short: this commit's diff is over 1000 lines.
spec.md+33−18
Cut short: this commit's diff is over 1000 lines.