@@ -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",