xonecas.io
70160
Ce

cel-tui / commit 251df02

feat(core): require Kitty keyboard protocol for key input

Replace the legacy terminal key parser with Kitty keyboard protocol
level 1 (disambiguate escape codes). This is a hard dependency — the
framework no longer handles legacy control character encodings.

Key changes:
- Rewrite parseKey() for CSI u, CSI letter, and CSI tilde formats
- Map space and plus to named keys per spec
- Add isEditingKey support for 'plus' named key
- Add space/plus character insertion cases in TextInput handling
- Enable protocol (CSI > 1 u) in ProcessTerminal.start()
- Pop protocol (CSI < u) in ProcessTerminal.cleanup()
- Add kittyEncode() test helper for generating Kitty byte sequences
- Update all integration tests to use Kitty-encoded input
- Update spec, docs, README, SKILL, AGENTS, and TODO

All modifier combos now work correctly: alt+key, ctrl+plus,
shift+enter, ctrl+shift+n, and any other combination that was
ambiguous or impossible in legacy terminal encoding.

xonecas2026-04-04 251df0240db229a9d44c9ff7fa569800bf74eba8 parent 36bc1c0

13 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+45−5
@@ -39,10 +39,10 @@ All core systems from the spec are implemented and tested:
3939 - **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints, gap, padding, justifyContent, alignItems, 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** — key parsing/normalization, 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
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
4343 - **TextInput** — text editing, cursor movement, cursor persistence across re-renders (keyed on onChange), auto-scroll to keep cursor visible, placeholder rendering
4444 - **Layering** — multi-layer compositing, transparency, topmost-layer input priority
45-- **Terminal** — crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
45+- **Terminal** — Kitty keyboard protocol enable/disable, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
4646
4747 See `TODO.md` for remaining spec violations and future work.
4848
@@ -67,7 +67,19 @@ bun run docs # generate HTML + Markdown docs into docs/
6767
6868 ## Visual Testing with tmux
6969
70-Use a tmux session to run examples and visually inspect rendered output:
70+Use a tmux session to run examples and visually inspect rendered output.
71+
72+### tmux Configuration
73+
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:
75+
76+```
77+set -s extended-keys on
78+```
79+
80+Without this, tmux intercepts the protocol negotiation and key events arrive in legacy format that the framework's parser won't recognize.
81+
82+### Usage
7183
7284 ```bash
7385 # Create a session (set size to simulate a terminal window)
@@ -91,6 +103,34 @@ tmux kill-session -t cel
91103
92104 This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
93105
106+### Sending Keys with the Kitty Protocol
107+
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+
110+```bash
111+# Helper: convert a key name to hex bytes via kittyEncode
112+send_key() {
113+ local hex=$(cd /home/xonecas/src/cel-tui && bun -e "
114+ const {kittyEncode} = require('./packages/core/src/test-helpers.ts');
115+ const bytes = kittyEncode('$1');
116+ const hex = Array.from(bytes).map(c => c.charCodeAt(0).toString(16).padStart(2,'0')).join(' ');
117+ process.stdout.write(hex);
118+ ")
119+ tmux send-keys -t cel -H $hex
120+}
121+
122+# 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
130+```
131+
132+**Limitations:** The helper lowercases all input, so uppercase letters aren't testable this way. Mouse events (SGR format) are unaffected — use `send-keys -H` with raw SGR hex as before.
133+
94134 **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.
95135
96136 ## Spec
@@ -147,10 +187,10 @@ chore: scaffold monorepo with types, core, components packages
147187 - `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets, scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state, container bgColor fill, style inheritance threading, focusStyle resolution.
148188 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both wrap in CSI 2026 synchronized output.
149189 - `hit-test.ts` — `hitTest(root, x, y)` → path from root to deepest node. `findClickHandler`, `findScrollTarget`, `collectKeyPressHandlers`, `collectFocusable` walk paths.
150-- `keys.ts` — `parseKey(data)` normalizes terminal input to canonical key strings. `isEditingKey()` identifies keys consumed by TextInput. `normalizeKey()` reorders modifiers to canonical `ctrl+alt+shift+<key>` order.
190+- `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.
151191 - `text-edit.ts` — Pure text editing functions (`insertChar`, `deleteBackward`, `deleteForward`, `moveCursor`). Operates on `EditState` (value + cursor position). Used by `cel.ts` to handle TextInput key events.
152192 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
153-- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, SGR mouse, crash cleanup) and `MockTerminal` (testing).
193+- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1, SGR mouse, crash cleanup) and `MockTerminal` (testing).
154194
155195 ## Updating gh-pages
156196
README.md+1−0
@@ -66,6 +66,7 @@ cel.viewport(() =>
6666 - **Uncontrolled by default** — focus and scroll just work. Opt into controlled mode when needed.
6767 - **Style inheritance** — containers propagate styles to descendants. `bgColor` fills the rect.
6868 - **Cell buffer rendering** — styled cells, differential updates, synchronized output.
69+- **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).
6970
7071 ## Packages
7172
TODO.md+1−3
@@ -20,12 +20,10 @@ Remaining work, known bugs, and planned improvements.
2020
2121 ## Not Yet Implemented
2222
23-- ❌ Alt key combos (`alt+x`) — `parseKey` doesn't handle ESC-prefixed sequences as alt modifiers. The spec lists `"alt+up"` as a valid key format.
24-- ❌ `"plus"` as a named key — the spec mentions `"ctrl+plus"` but `+` is the modifier separator and needs special handling.
2523 - ❌ Bracketed paste mode support
26-- ❌ Kitty keyboard protocol detection
2724
2825 ## Future Enhancements
2926
3027 - 💡 Additional example apps (chat UI, text editor from spec reference examples)
3128 - 💡 `overflow: "hidden"` as explicit prop (currently all containers clip by default, which matches the spec's default behavior, but the prop value is not checked)
29+- 💡 Higher Kitty protocol levels — key-release events (level 2), associated text (level 3), and full event types (level 4) for advanced input patterns (games, physical key layout awareness)
docs/skill/cel-tui/SKILL.md+1−1
@@ -197,7 +197,7 @@ mySelect.reset(); // clear filter/highlight programmatically
197197 - **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
198198 - **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
199199 - **Always call `cel.stop()` before `process.exit()`** — restores raw mode, mouse tracking, and alternate screen.
200-- **Alt key combos** (`alt+x`, `alt+up`) are not yet implemented in key parsing. Use `ctrl+` modifiers instead.
200+- **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.
201201 - **Button limitations** — `Button` from `@cel-tui/components` does not forward `focusStyle`, container sizing, or all style props. Use `HStack` + `Text` directly when you need full control.
202202
203203 ## Composing Components
packages/core/package.json+2−1
@@ -14,7 +14,8 @@
1414 },
1515 "files": [
1616 "src/**/*.ts",
17- "!src/**/*.test.ts"
17+ "!src/**/*.test.ts",
18+ "!src/test-helpers.ts"
1819 ],
1920 "license": "MIT",
2021 "repository": {
packages/core/src/cel.test.ts+57−49
@@ -4,6 +4,14 @@ import { MockTerminal } from "./terminal.js";
44 import { Text } from "./primitives/text.js";
55 import { TextInput } from "./primitives/text-input.js";
66 import { VStack, HStack } from "./primitives/stacks.js";
7+import { kittyEncode } from "./test-helpers.js";
8+
9+// Kitty protocol byte sequences for commonly used keys
10+const TAB = kittyEncode("tab");
11+const ENTER = kittyEncode("enter");
12+const ESCAPE = kittyEncode("escape");
13+const SHIFT_TAB = kittyEncode("shift+tab");
14+const CTRL_S = kittyEncode("ctrl+s");
715
816 describe("cel end-to-end", () => {
917 let term: MockTerminal;
@@ -172,7 +180,7 @@ describe("cel end-to-end", () => {
172180 await waitForRender();
173181
174182 // Send Ctrl+S
175- term.sendInput("\x13");
183+ term.sendInput(CTRL_S);
176184 await waitForRender();
177185
178186 expect(receivedKey).toBe("ctrl+s");
@@ -314,12 +322,12 @@ describe("cel end-to-end", () => {
314322 await waitForRender();
315323
316324 // Tab to focus first element
317- term.sendInput("\t");
325+ term.sendInput(TAB);
318326 await waitForRender();
319327 expect(focused).toEqual(["btn1"]);
320328
321329 // Tab to focus second element
322- term.sendInput("\t");
330+ term.sendInput(TAB);
323331 await waitForRender();
324332 expect(focused).toEqual(["btn1", "btn2"]);
325333 });
@@ -367,7 +375,7 @@ describe("cel end-to-end", () => {
367375 await waitForRender();
368376
369377 // Shift+Tab from btn2 should focus btn1
370- term.sendInput("\x1b[Z");
378+ term.sendInput(SHIFT_TAB);
371379 await waitForRender();
372380 expect(focused).toEqual(["btn1"]);
373381 });
@@ -394,7 +402,7 @@ describe("cel end-to-end", () => {
394402 );
395403 await waitForRender();
396404
397- term.sendInput("\x1b");
405+ term.sendInput(ESCAPE);
398406 await waitForRender();
399407 expect(blurred).toBe(true);
400408 });
@@ -418,7 +426,7 @@ describe("cel end-to-end", () => {
418426 );
419427 await waitForRender();
420428
421- term.sendInput("\r");
429+ term.sendInput(ENTER);
422430 await waitForRender();
423431 expect(clicked).toBe(true);
424432 });
@@ -492,7 +500,7 @@ describe("cel end-to-end", () => {
492500 await waitForRender();
493501
494502 // Tab from btn2 (last) should wrap to btn1
495- term.sendInput("\t");
503+ term.sendInput(TAB);
496504 await waitForRender();
497505 expect(focused).toEqual(["btn1"]);
498506 });
@@ -735,7 +743,7 @@ describe("cel end-to-end", () => {
735743 await waitForRender();
736744
737745 // Ctrl+S is not an editing key — should bubble up
738- term.sendInput("\x13");
746+ term.sendInput(CTRL_S);
739747 await waitForRender();
740748 expect(parentKey).toBe("ctrl+s");
741749 });
@@ -782,7 +790,7 @@ describe("cel end-to-end", () => {
782790 await waitForRender();
783791
784792 // Tab should insert \t, not traverse focus
785- term.sendInput("\t");
793+ term.sendInput(TAB);
786794 await waitForRender();
787795 expect(value).toBe("hello\t");
788796 });
@@ -816,7 +824,7 @@ describe("cel end-to-end", () => {
816824 await waitForRender();
817825
818826 // Shift+Tab should not move focus away from TextInput
819- term.sendInput("\x1b[Z");
827+ term.sendInput(SHIFT_TAB);
820828 await waitForRender();
821829 expect(btnFocused).toBe(false);
822830 });
@@ -840,7 +848,7 @@ describe("cel end-to-end", () => {
840848 await waitForRender();
841849
842850 // Tab should traverse to the TextInput (it's not focused yet)
843- term.sendInput("\t");
851+ term.sendInput(TAB);
844852 await waitForRender();
845853 expect(tiFocused).toBe(true);
846854 });
@@ -876,12 +884,12 @@ describe("cel end-to-end", () => {
876884 await waitForRender();
877885
878886 // Escape to leave TextInput
879- term.sendInput("\x1b");
887+ term.sendInput(ESCAPE);
880888 await waitForRender();
881889 expect(tiFocused).toBe(false);
882890
883891 // Tab should now traverse to the button
884- term.sendInput("\t");
892+ term.sendInput(TAB);
885893 await waitForRender();
886894 expect(btnFocused).toBe(true);
887895 });
@@ -922,13 +930,13 @@ describe("cel end-to-end", () => {
922930 expect(focused as string | null).toBe("ti");
923931
924932 // Escape to unfocus TextInput
925- term.sendInput("\x1b");
933+ term.sendInput(ESCAPE);
926934 await waitForRender();
927935 expect(focused as string | null).toBe(null);
928936
929937 // Tab should go FORWARD to the button (next after TextInput),
930938 // not back to the TextInput
931- term.sendInput("\t");
939+ term.sendInput(TAB);
932940 await waitForRender();
933941 expect(focused as string | null).toBe("btn");
934942 });
@@ -983,18 +991,18 @@ describe("cel end-to-end", () => {
983991 await waitForRender();
984992
985993 // Tab to B
986- term.sendInput("\t"); // → A
994+ term.sendInput(TAB); // → A
987995 await waitForRender();
988- term.sendInput("\t"); // → B
996+ term.sendInput(TAB); // → B
989997 await waitForRender();
990998 expect(focused as string | null).toBe("b");
991999
9921000 // Escape, then Shift+Tab should go backward to A
993- term.sendInput("\x1b");
1001+ term.sendInput(ESCAPE);
9941002 await waitForRender();
9951003 expect(focused as string | null).toBe(null);
9961004
997- term.sendInput("\x1b[Z"); // Shift+Tab
1005+ term.sendInput(SHIFT_TAB); // Shift+Tab
9981006 await waitForRender();
9991007 expect(focused as string | null).toBe("a");
10001008 });
@@ -1130,11 +1138,11 @@ describe("cel end-to-end", () => {
11301138 await waitForRender();
11311139
11321140 // Tab to focus the button
1133- term.sendInput("\t");
1141+ term.sendInput(TAB);
11341142 await waitForRender();
11351143
11361144 // Enter to activate
1137- term.sendInput("\r");
1145+ term.sendInput(ENTER);
11381146 await waitForRender();
11391147
11401148 expect(clicked).toBe(true);
@@ -1153,16 +1161,16 @@ describe("cel end-to-end", () => {
11531161 await waitForRender();
11541162
11551163 // Tab to first, activate
1156- term.sendInput("\t");
1164+ term.sendInput(TAB);
11571165 await waitForRender();
1158- term.sendInput("\r");
1166+ term.sendInput(ENTER);
11591167 await waitForRender();
11601168 expect(clicks).toEqual(["btn1"]);
11611169
11621170 // Tab to second, activate
1163- term.sendInput("\t");
1171+ term.sendInput(TAB);
11641172 await waitForRender();
1165- term.sendInput("\r");
1173+ term.sendInput(ENTER);
11661174 await waitForRender();
11671175 expect(clicks).toEqual(["btn1", "btn2"]);
11681176 });
@@ -1180,16 +1188,16 @@ describe("cel end-to-end", () => {
11801188 await waitForRender();
11811189
11821190 // Shift+Tab to focus last element
1183- term.sendInput("\x1b[Z");
1191+ term.sendInput(SHIFT_TAB);
11841192 await waitForRender();
1185- term.sendInput("\r");
1193+ term.sendInput(ENTER);
11861194 await waitForRender();
11871195 expect(clicks).toEqual(["btn2"]);
11881196
11891197 // Shift+Tab to go backward to first
1190- term.sendInput("\x1b[Z");
1198+ term.sendInput(SHIFT_TAB);
11911199 await waitForRender();
1192- term.sendInput("\r");
1200+ term.sendInput(ENTER);
11931201 await waitForRender();
11941202 expect(clicks).toEqual(["btn2", "btn1"]);
11951203 });
@@ -1213,13 +1221,13 @@ describe("cel end-to-end", () => {
12131221 await waitForRender();
12141222
12151223 // Tab to focus, then Escape to unfocus
1216- term.sendInput("\t");
1224+ term.sendInput(TAB);
12171225 await waitForRender();
1218- term.sendInput("\x1b");
1226+ term.sendInput(ESCAPE);
12191227 await waitForRender();
12201228
12211229 // Enter should do nothing — no element is focused
1222- term.sendInput("\r");
1230+ term.sendInput(ENTER);
12231231 await waitForRender();
12241232 expect(clicked).toBe(false);
12251233 });
@@ -1248,7 +1256,7 @@ describe("cel end-to-end", () => {
12481256 await waitForRender();
12491257
12501258 // Enter should activate the clicked element
1251- term.sendInput("\r");
1259+ term.sendInput(ENTER);
12521260 await waitForRender();
12531261 expect(clicked).toBe(true);
12541262 });
@@ -1270,7 +1278,7 @@ describe("cel end-to-end", () => {
12701278 );
12711279 await waitForRender();
12721280
1273- term.sendInput("\t");
1281+ term.sendInput(TAB);
12741282 await waitForRender();
12751283 expect(events).toEqual(["focus"]);
12761284 });
@@ -1301,12 +1309,12 @@ describe("cel end-to-end", () => {
13011309 await waitForRender();
13021310
13031311 // Tab to first
1304- term.sendInput("\t");
1312+ term.sendInput(TAB);
13051313 await waitForRender();
13061314 expect(events).toEqual(["focus1"]);
13071315
13081316 // Tab to second — first should get onBlur
1309- term.sendInput("\t");
1317+ term.sendInput(TAB);
13101318 await waitForRender();
13111319 expect(events).toEqual(["focus1", "blur1", "focus2"]);
13121320 });
@@ -1328,7 +1336,7 @@ describe("cel end-to-end", () => {
13281336 await waitForRender();
13291337
13301338 // Tab to focus the TextInput
1331- term.sendInput("\t");
1339+ term.sendInput(TAB);
13321340 await waitForRender();
13331341
13341342 // Type a character
@@ -1350,13 +1358,13 @@ describe("cel end-to-end", () => {
13501358 await waitForRender();
13511359
13521360 // Tab to first, Tab to second, Tab wraps to first
1353- term.sendInput("\t");
1361+ term.sendInput(TAB);
13541362 await waitForRender();
1355- term.sendInput("\t");
1363+ term.sendInput(TAB);
13561364 await waitForRender();
1357- term.sendInput("\t");
1365+ term.sendInput(TAB);
13581366 await waitForRender();
1359- term.sendInput("\r");
1367+ term.sendInput(ENTER);
13601368 await waitForRender();
13611369 expect(clicks).toEqual(["btn1"]);
13621370 });
@@ -1389,15 +1397,15 @@ describe("cel end-to-end", () => {
13891397 await waitForRender();
13901398
13911399 // Tab to first (controlled)
1392- term.sendInput("\t");
1400+ term.sendInput(TAB);
13931401 await waitForRender();
13941402 expect(controlledFocused).toBe(true);
13951403
13961404 // Tab to second (uncontrolled), Enter to activate
1397- term.sendInput("\t");
1405+ term.sendInput(TAB);
13981406 await waitForRender();
13991407 expect(controlledFocused).toBe(false);
1400- term.sendInput("\r");
1408+ term.sendInput(ENTER);
14011409 await waitForRender();
14021410 expect(clicks).toEqual(["uncontrolled"]);
14031411 });
@@ -1426,7 +1434,7 @@ describe("cel end-to-end", () => {
14261434 expect(buf.get(0, 0).bgColor).toBe("black");
14271435
14281436 // Tab to focus
1429- term.sendInput("\t");
1437+ term.sendInput(TAB);
14301438 await waitForRender();
14311439
14321440 // After focus — focusStyle bgColor
@@ -1460,14 +1468,14 @@ describe("cel end-to-end", () => {
14601468 await waitForRender();
14611469
14621470 // Tab to first
1463- term.sendInput("\t");
1471+ term.sendInput(TAB);
14641472 await waitForRender();
14651473 let buf = cel._getBuffer()!;
14661474 expect(buf.get(0, 0).bgColor).toBe("cyan");
14671475 expect(buf.get(0, 1).bgColor).toBe("black");
14681476
14691477 // Tab to second — first loses focusStyle, second gains it
1470- term.sendInput("\t");
1478+ term.sendInput(TAB);
14711479 await waitForRender();
14721480 buf = cel._getBuffer()!;
14731481 expect(buf.get(0, 0).bgColor).toBe("black");
@@ -1496,7 +1504,7 @@ describe("cel end-to-end", () => {
14961504 expect(buf.get(0, 0).fgColor).toBe("white");
14971505
14981506 // Tab to focus
1499- term.sendInput("\t");
1507+ term.sendInput(TAB);
15001508 await waitForRender();
15011509
15021510 // After focus — Text inherits black from focusStyle
@@ -1531,7 +1539,7 @@ describe("cel end-to-end", () => {
15311539 expect(buf.get(0, 0).bgColor).toBe("cyan");
15321540
15331541 // Escape to blur
1534- term.sendInput("\x1b");
1542+ term.sendInput(ESCAPE);
15351543 await waitForRender();
15361544
15371545 // focused=false — normal style
packages/core/src/cel.ts+12−0
@@ -550,6 +550,12 @@ function handleKeyEvent(key: string, rawData?: string): void {
550550 case "tab":
551551 newState = insertChar(editState, "\t");
552552 break;
553+ case "space":
554+ newState = insertChar(editState, " ");
555+ break;
556+ case "plus":
557+ newState = insertChar(editState, "+");
558+ break;
553559 default:
554560 // Single printable character — use raw data to preserve case
555561 if (key.length === 1 && rawData && rawData.length === 1) {
@@ -675,6 +681,9 @@ export const cel = {
675681 * Initialize the framework with a terminal implementation.
676682 * Must be called before {@link cel.viewport}.
677683 *
684+ * Enables the Kitty keyboard protocol (level 1) via the terminal,
685+ * enters raw mode, and starts mouse tracking.
686+ *
678687 * @param term - Terminal to render to (ProcessTerminal or MockTerminal).
679688 */
680689 init(term: Terminal): void {
@@ -707,6 +716,9 @@ export const cel = {
707716
708717 /**
709718 * Stop the framework and restore terminal state.
719+ *
720+ * Pops the Kitty keyboard protocol mode, disables mouse tracking,
721+ * and restores the terminal to its previous state.
710722 */
711723 stop(): void {
712724 terminal?.stop();
packages/core/src/keys.test.ts+246−36
@@ -1,68 +1,278 @@
11 import { describe, expect, test } from "bun:test";
2-import { parseKey, normalizeKey } from "./keys.js";
2+import { parseKey, normalizeKey, isEditingKey } from "./keys.js";
3+import { kittyEncode } from "./test-helpers.js";
34
4-describe("parseKey", () => {
5- test("printable ASCII character", () => {
6- expect(parseKey("a")).toBe("a");
7- expect(parseKey("z")).toBe("z");
8- expect(parseKey("1")).toBe("1");
9- expect(parseKey("/")).toBe("/");
5+// ── kittyEncode helper sanity checks ────────────────────────────────────────
6+
7+describe("kittyEncode helper", () => {
8+ test("unmodified printable → raw byte", () => {
9+ expect(kittyEncode("a")).toBe("a");
10+ expect(kittyEncode("1")).toBe("1");
11+ expect(kittyEncode("/")).toBe("/");
12+ });
13+
14+ test("named printable keys → raw byte when unmodified", () => {
15+ expect(kittyEncode("space")).toBe(" ");
16+ expect(kittyEncode("plus")).toBe("+");
17+ });
18+
19+ test("special keys → CSI u", () => {
20+ expect(kittyEncode("escape")).toBe("\x1b[27u");
21+ expect(kittyEncode("enter")).toBe("\x1b[13u");
22+ expect(kittyEncode("tab")).toBe("\x1b[9u");
23+ expect(kittyEncode("backspace")).toBe("\x1b[127u");
24+ });
25+
26+ test("modifier combos → CSI u with modifier param", () => {
27+ // Modifier bitmask: shift=1, alt=2, ctrl=4. Param = bitmask + 1.
28+ expect(kittyEncode("ctrl+c")).toBe("\x1b[99;5u"); // ctrl=4 → 5
29+ expect(kittyEncode("alt+x")).toBe("\x1b[120;3u"); // alt=2 → 3
30+ expect(kittyEncode("shift+enter")).toBe("\x1b[13;2u"); // shift=1 → 2
31+ expect(kittyEncode("ctrl+shift+n")).toBe("\x1b[110;6u"); // ctrl+shift=5 → 6
32+ expect(kittyEncode("ctrl+alt+shift+a")).toBe("\x1b[97;8u"); // all=7 → 8
33+ });
34+
35+ test("arrow keys → CSI letter", () => {
36+ expect(kittyEncode("up")).toBe("\x1b[A");
37+ expect(kittyEncode("ctrl+up")).toBe("\x1b[1;5A");
38+ });
39+
40+ test("tilde keys", () => {
41+ expect(kittyEncode("delete")).toBe("\x1b[3~");
42+ expect(kittyEncode("shift+delete")).toBe("\x1b[3;2~");
1043 });
1144
12- test("enter key", () => {
13- expect(parseKey("\r")).toBe("enter");
45+ test("function keys", () => {
46+ expect(kittyEncode("f1")).toBe("\x1b[11~");
47+ expect(kittyEncode("ctrl+f5")).toBe("\x1b[15;5~");
1448 });
1549
16- test("escape key", () => {
17- expect(parseKey("\x1b")).toBe("escape");
50+ test("named printable keys with modifiers → CSI u", () => {
51+ expect(kittyEncode("ctrl+space")).toBe("\x1b[32;5u");
52+ expect(kittyEncode("ctrl+plus")).toBe("\x1b[43;5u");
53+ });
54+});
55+
56+// ── parseKey ────────────────────────────────────────────────────────────────
57+
58+describe("parseKey", () => {
59+ // --- Raw printable characters (arrive as raw bytes at level 1) ---
60+
61+ describe("raw printable characters", () => {
62+ test("lowercase letters", () => {
63+ expect(parseKey("a")).toBe("a");
64+ expect(parseKey("z")).toBe("z");
65+ });
66+
67+ test("uppercase letters lowercased", () => {
68+ expect(parseKey("A")).toBe("a");
69+ expect(parseKey("Z")).toBe("z");
70+ });
71+
72+ test("digits", () => {
73+ expect(parseKey("1")).toBe("1");
74+ expect(parseKey("0")).toBe("0");
75+ });
76+
77+ test("symbols", () => {
78+ expect(parseKey("/")).toBe("/");
79+ expect(parseKey("-")).toBe("-");
80+ expect(parseKey("=")).toBe("=");
81+ expect(parseKey("[")).toBe("[");
82+ });
83+
84+ test("space maps to named key", () => {
85+ expect(parseKey(" ")).toBe("space");
86+ });
87+
88+ test("plus maps to named key", () => {
89+ expect(parseKey("+")).toBe("plus");
90+ });
91+
92+ test("multi-byte UTF-8 passed through", () => {
93+ expect(parseKey("世")).toBe("世");
94+ expect(parseKey("é")).toBe("é");
95+ });
1896 });
1997
20- test("tab key", () => {
21- expect(parseKey("\t")).toBe("tab");
98+ // --- CSI u: special keys without modifiers ---
99+
100+ describe("CSI u special keys", () => {
101+ test("escape", () => {
102+ expect(parseKey("\x1b[27u")).toBe("escape");
103+ });
104+
105+ test("enter", () => {
106+ expect(parseKey("\x1b[13u")).toBe("enter");
107+ });
108+
109+ test("tab", () => {
110+ expect(parseKey("\x1b[9u")).toBe("tab");
111+ });
112+
113+ test("backspace", () => {
114+ expect(parseKey("\x1b[127u")).toBe("backspace");
115+ });
116+
117+ test("space via CSI u", () => {
118+ expect(parseKey("\x1b[32u")).toBe("space");
119+ });
120+
121+ test("plus via CSI u", () => {
122+ expect(parseKey("\x1b[43u")).toBe("plus");
123+ });
124+
125+ test("explicit modifier=1 means no modifiers", () => {
126+ expect(parseKey("\x1b[27;1u")).toBe("escape");
127+ expect(parseKey("\x1b[13;1u")).toBe("enter");
128+ });
129+
130+ test("printable codepoint via CSI u (robustness)", () => {
131+ // At level 1 unmodified printable chars arrive as raw bytes,
132+ // but the parser should handle CSI u for them gracefully
133+ expect(parseKey("\x1b[97u")).toBe("a");
134+ expect(parseKey("\x1b[65u")).toBe("a"); // uppercase A codepoint → lowercase
135+ });
22136 });
23137
24- test("backspace", () => {
25- expect(parseKey("\x7f")).toBe("backspace");
138+ // --- CSI u: modifier combos ---
139+
140+ describe("CSI u modifier combos", () => {
141+ test("ctrl+letter", () => {
142+ expect(parseKey(kittyEncode("ctrl+c"))).toBe("ctrl+c");
143+ expect(parseKey(kittyEncode("ctrl+s"))).toBe("ctrl+s");
144+ expect(parseKey(kittyEncode("ctrl+q"))).toBe("ctrl+q");
145+ expect(parseKey(kittyEncode("ctrl+a"))).toBe("ctrl+a");
146+ });
147+
148+ test("alt+letter", () => {
149+ expect(parseKey(kittyEncode("alt+x"))).toBe("alt+x");
150+ expect(parseKey(kittyEncode("alt+a"))).toBe("alt+a");
151+ });
152+
153+ test("shift+special", () => {
154+ expect(parseKey(kittyEncode("shift+enter"))).toBe("shift+enter");
155+ expect(parseKey(kittyEncode("shift+tab"))).toBe("shift+tab");
156+ });
157+
158+ test("ctrl+special", () => {
159+ expect(parseKey(kittyEncode("ctrl+enter"))).toBe("ctrl+enter");
160+ expect(parseKey(kittyEncode("ctrl+space"))).toBe("ctrl+space");
161+ expect(parseKey(kittyEncode("ctrl+plus"))).toBe("ctrl+plus");
162+ });
163+
164+ test("multi-modifier combos", () => {
165+ expect(parseKey(kittyEncode("ctrl+shift+n"))).toBe("ctrl+shift+n");
166+ expect(parseKey(kittyEncode("ctrl+alt+shift+a"))).toBe(
167+ "ctrl+alt+shift+a",
168+ );
169+ expect(parseKey(kittyEncode("ctrl+alt+x"))).toBe("ctrl+alt+x");
170+ });
26171 });
27172
28- test("ctrl+c", () => {
29- expect(parseKey("\x03")).toBe("ctrl+c");
173+ // --- Arrow keys ---
174+
175+ describe("arrow keys", () => {
176+ test("unmodified arrows", () => {
177+ expect(parseKey(kittyEncode("up"))).toBe("up");
178+ expect(parseKey(kittyEncode("down"))).toBe("down");
179+ expect(parseKey(kittyEncode("right"))).toBe("right");
180+ expect(parseKey(kittyEncode("left"))).toBe("left");
181+ });
182+
183+ test("modified arrows", () => {
184+ expect(parseKey(kittyEncode("ctrl+up"))).toBe("ctrl+up");
185+ expect(parseKey(kittyEncode("shift+left"))).toBe("shift+left");
186+ expect(parseKey(kittyEncode("alt+down"))).toBe("alt+down");
187+ expect(parseKey(kittyEncode("ctrl+shift+right"))).toBe(
188+ "ctrl+shift+right",
189+ );
190+ });
30191 });
31192
32- test("ctrl+s", () => {
33- expect(parseKey("\x13")).toBe("ctrl+s");
193+ // --- Home/End ---
194+
195+ describe("home/end", () => {
196+ test("unmodified", () => {
197+ expect(parseKey(kittyEncode("home"))).toBe("home");
198+ expect(parseKey(kittyEncode("end"))).toBe("end");
199+ });
200+
201+ test("modified", () => {
202+ expect(parseKey(kittyEncode("ctrl+home"))).toBe("ctrl+home");
203+ expect(parseKey(kittyEncode("shift+end"))).toBe("shift+end");
204+ });
34205 });
35206
36- test("ctrl+q", () => {
37- expect(parseKey("\x11")).toBe("ctrl+q");
207+ // --- Tilde keys (Delete, PageUp, PageDown) ---
208+
209+ describe("tilde keys", () => {
210+ test("unmodified", () => {
211+ expect(parseKey(kittyEncode("delete"))).toBe("delete");
212+ expect(parseKey(kittyEncode("pageup"))).toBe("pageup");
213+ expect(parseKey(kittyEncode("pagedown"))).toBe("pagedown");
214+ });
215+
216+ test("modified", () => {
217+ expect(parseKey(kittyEncode("shift+delete"))).toBe("shift+delete");
218+ expect(parseKey(kittyEncode("ctrl+pageup"))).toBe("ctrl+pageup");
219+ });
38220 });
39221
40- test("arrow keys", () => {
41- expect(parseKey("\x1b[A")).toBe("up");
42- expect(parseKey("\x1b[B")).toBe("down");
43- expect(parseKey("\x1b[C")).toBe("right");
44- expect(parseKey("\x1b[D")).toBe("left");
222+ // --- Function keys ---
223+
224+ describe("function keys", () => {
225+ test("unmodified", () => {
226+ expect(parseKey(kittyEncode("f1"))).toBe("f1");
227+ expect(parseKey(kittyEncode("f5"))).toBe("f5");
228+ expect(parseKey(kittyEncode("f12"))).toBe("f12");
229+ });
230+
231+ test("modified", () => {
232+ expect(parseKey(kittyEncode("ctrl+f5"))).toBe("ctrl+f5");
233+ expect(parseKey(kittyEncode("shift+f1"))).toBe("shift+f1");
234+ });
45235 });
236+});
237+
238+// ── isEditingKey ────────────────────────────────────────────────────────────
46239
47- test("shift+tab", () => {
48- expect(parseKey("\x1b[Z")).toBe("shift+tab");
240+describe("isEditingKey", () => {
241+ test("single printable characters are editing keys", () => {
242+ expect(isEditingKey("a")).toBe(true);
243+ expect(isEditingKey("1")).toBe(true);
244+ expect(isEditingKey("/")).toBe(true);
49245 });
50246
51- test("home/end", () => {
52- expect(parseKey("\x1b[H")).toBe("home");
53- expect(parseKey("\x1b[F")).toBe("end");
247+ test("named editing keys", () => {
248+ expect(isEditingKey("enter")).toBe(true);
249+ expect(isEditingKey("backspace")).toBe(true);
250+ expect(isEditingKey("delete")).toBe(true);
251+ expect(isEditingKey("tab")).toBe(true);
252+ expect(isEditingKey("space")).toBe(true);
253+ expect(isEditingKey("plus")).toBe(true);
254+ expect(isEditingKey("up")).toBe(true);
255+ expect(isEditingKey("down")).toBe(true);
256+ expect(isEditingKey("left")).toBe(true);
257+ expect(isEditingKey("right")).toBe(true);
258+ expect(isEditingKey("home")).toBe(true);
259+ expect(isEditingKey("end")).toBe(true);
54260 });
55261
56- test("delete", () => {
57- expect(parseKey("\x1b[3~")).toBe("delete");
262+ test("modifier combos are NOT editing keys", () => {
263+ expect(isEditingKey("ctrl+s")).toBe(false);
264+ expect(isEditingKey("alt+x")).toBe(false);
265+ expect(isEditingKey("ctrl+shift+n")).toBe(false);
266+ expect(isEditingKey("shift+tab")).toBe(false);
58267 });
59268
60- test("page up/down", () => {
61- expect(parseKey("\x1b[5~")).toBe("pageup");
62- expect(parseKey("\x1b[6~")).toBe("pagedown");
269+ test("escape is NOT an editing key", () => {
270+ expect(isEditingKey("escape")).toBe(false);
63271 });
64272 });
65273
274+// ── normalizeKey ────────────────────────────────────────────────────────────
275+
66276 describe("normalizeKey", () => {
67277 test("already normalized", () => {
68278 expect(normalizeKey("ctrl+s")).toBe("ctrl+s");
packages/core/src/keys.ts+156−78
@@ -1,97 +1,174 @@
1+/**
2+ * Key parsing for the Kitty keyboard protocol (level 1 — disambiguate).
3+ *
4+ * At level 1, the terminal sends:
5+ * - **CSI u** (`ESC [ codepoint ; modifiers u`) for keys that were ambiguous
6+ * in legacy encoding (Escape, Enter, Tab, Backspace, Ctrl+letter, Alt+letter, etc.)
7+ * - **CSI letter** (`ESC [ A/B/C/D/H/F` or `ESC [ 1 ; modifiers letter`) for
8+ * arrow keys and Home/End
9+ * - **CSI tilde** (`ESC [ number ~` or `ESC [ number ; modifiers ~`) for
10+ * Delete, PageUp, PageDown, and function keys
11+ * - **Raw bytes** for unmodified printable characters
12+ *
13+ * Modifier bitmask (wire value = bitmask + 1):
14+ * shift=1, alt=2, ctrl=4 → e.g., ctrl = bitmask 4, wire param = 5
15+ *
16+ * @module
17+ */
18+
19+// --- Codepoint → named key mappings ---
20+
21+/** Named key lookup from Unicode codepoint (for CSI u sequences). */
22+const CODEPOINT_NAMES: Record<number, string> = {
23+ 27: "escape",
24+ 13: "enter",
25+ 9: "tab",
26+ 127: "backspace",
27+ 32: "space",
28+ 43: "plus",
29+};
30+
31+/** Named key lookup from CSI letter suffix (arrows, Home, End). */
32+const LETTER_NAMES: Record<string, string> = {
33+ A: "up",
34+ B: "down",
35+ C: "right",
36+ D: "left",
37+ H: "home",
38+ F: "end",
39+};
40+
41+/** Named key lookup from CSI tilde number (Delete, PageUp/Down, F-keys). */
42+const TILDE_NAMES: Record<number, string> = {
43+ 3: "delete",
44+ 5: "pageup",
45+ 6: "pagedown",
46+ 11: "f1",
47+ 12: "f2",
48+ 13: "f3",
49+ 14: "f4",
50+ 15: "f5",
51+ 17: "f6",
52+ 18: "f7",
53+ 19: "f8",
54+ 20: "f9",
55+ 21: "f10",
56+ 23: "f11",
57+ 24: "f12",
58+};
59+
60+/** Raw printable characters that map to named keys. */
61+const CHAR_NAMES: Record<string, string> = {
62+ " ": "space",
63+ "+": "plus",
64+};
65+
66+// --- Modifier decoding ---
67+
68+/**
69+ * Decode a Kitty modifier parameter to an ordered modifier prefix string.
70+ * Canonical order: ctrl+alt+shift. Returns empty string if no modifiers.
71+ *
72+ * @param param - The modifier parameter from the CSI sequence (bitmask + 1).
73+ * Value 0 or 1 means no modifiers.
74+ */
75+function decodeModifiers(param: number): string {
76+ if (param <= 1) return "";
77+ const bits = param - 1;
78+ const parts: string[] = [];
79+ if (bits & 4) parts.push("ctrl");
80+ if (bits & 2) parts.push("alt");
81+ if (bits & 1) parts.push("shift");
82+ return parts.length > 0 ? parts.join("+") + "+" : "";
83+}
84+
85+/**
86+ * Build a key string from a modifier prefix and base key name.
87+ */
88+function withModifiers(modParam: number, base: string): string {
89+ return decodeModifiers(modParam) + base;
90+}
91+
92+// --- CSI sequence parsing ---
93+
94+/** Match CSI u format: ESC [ <codepoint> ; <modifiers> u */
95+const CSI_U_RE = /^(\d+)(?:;(\d+))?u$/;
96+
97+/** Match CSI letter format: ESC [ <default> ; <modifiers> <letter> */
98+const CSI_LETTER_RE = /^(?:1;(\d+))?([A-H])$/;
99+
100+/** Match CSI tilde format: ESC [ <number> ; <modifiers> ~ */
101+const CSI_TILDE_RE = /^(\d+)(?:;(\d+))?~$/;
102+
103+function parseCsiSequence(seq: string): string {
104+ // CSI u format: codepoint [; modifiers] u
105+ let match = CSI_U_RE.exec(seq);
106+ if (match) {
107+ const codepoint = parseInt(match[1]!, 10);
108+ const modParam = match[2] ? parseInt(match[2], 10) : 0;
109+
110+ // Check named keys first
111+ const name = CODEPOINT_NAMES[codepoint];
112+ if (name) return withModifiers(modParam, name);
113+
114+ // Printable character — convert codepoint to char, lowercase
115+ const char = String.fromCodePoint(codepoint).toLowerCase();
116+ return withModifiers(modParam, char);
117+ }
118+
119+ // CSI letter format: [1 ; modifiers] <letter>
120+ match = CSI_LETTER_RE.exec(seq);
121+ if (match) {
122+ const modParam = match[1] ? parseInt(match[1], 10) : 0;
123+ const letter = match[2]!;
124+ const name = LETTER_NAMES[letter];
125+ if (name) return withModifiers(modParam, name);
126+ }
127+
128+ // CSI tilde format: number [; modifiers] ~
129+ match = CSI_TILDE_RE.exec(seq);
130+ if (match) {
131+ const num = parseInt(match[1]!, 10);
132+ const modParam = match[2] ? parseInt(match[2], 10) : 0;
133+ const name = TILDE_NAMES[num];
134+ if (name) return withModifiers(modParam, name);
135+ }
136+
137+ return `unknown:${seq}`;
138+}
139+
140+// --- Public API ---
141+
1142 /**
2143 * Parse raw terminal input data into a normalized key string.
3144 *
4- * Handles:
5- * - Printable ASCII characters
6- * - Control characters (Ctrl+A through Ctrl+Z)
7- * - Special keys (Enter, Escape, Tab, Backspace, Delete)
8- * - Arrow keys, Home, End, Page Up/Down
9- * - CSI sequences
145+ * Handles the Kitty keyboard protocol level 1 (disambiguate) encoding:
146+ * - CSI u sequences for special keys and modifier combos
147+ * - CSI letter sequences for arrow keys and Home/End (with optional modifiers)
148+ * - CSI tilde sequences for Delete, PageUp/Down, and function keys
149+ * - Raw printable characters (unmodified, arrive as raw bytes at level 1)
10150 *
11151 * @param data - Raw terminal input string.
12- * @returns Normalized key string (e.g., `"ctrl+s"`, `"escape"`, `"up"`).
152+ * @returns Normalized key string (e.g., `"ctrl+s"`, `"escape"`, `"alt+up"`).
13153 */
14154 export function parseKey(data: string): string {
15155 // CSI sequences: ESC [ ...
16156 if (data.startsWith("\x1b[")) {
17- return parseCsiSequence(data);
157+ return parseCsiSequence(data.slice(2));
18158 }
19159
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+8−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/test-helpers.ts+122−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-input.test.ts+15−9
Cut short: this commit's diff is over 1000 lines.
spec.md+22−0
Cut short: this commit's diff is over 1000 lines.