xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / core / src / keys.ts

16.8 KB
1/**
2 * Key parsing for Kitty-first terminal input with legacy compatibility.
3 *
4 * The decoder accepts a mixed keyboard stream containing:
5 * - **CSI u** (`ESC [ key:alternates ; modifiers:event ; text u`) for the
6 *   baseline protocol and every Kitty progressive enhancement
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 * - **Legacy bytes** for unmodified special keys (Tab=0x09, Enter=0x0D,
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**
16 *
17 * Modifier bitmask (wire value = bitmask + 1): shift=1, alt=2, ctrl=4,
18 * super=8, hyper=16, meta=32, caps-lock=64, num-lock=128.
19 *
20 * @module
21 */
22
23import type { KeyEvent, KeyEventType, KeyModifiers } from "@cel-tui/types";
24
25/** A decoded keyboard event from the terminal input stream. */
26export type KeyInput = KeyEvent;
27
28// --- Codepoint -> named key mappings ---
29
30/** Named key lookup from Unicode codepoint (for CSI u sequences). */
31const CODEPOINT_NAMES: Record<number, string> = {
32  27: "escape",
33  13: "enter",
34  9: "tab",
35  127: "backspace",
36  32: "space",
37  43: "plus",
38};
39
40/** Kitty private-use functional key names that are not formulaic ranges. */
41const FUNCTIONAL_CODEPOINT_NAMES: Record<number, string> = {
42  57358: "caps-lock",
43  57359: "scroll-lock",
44  57360: "num-lock",
45  57361: "print-screen",
46  57362: "pause",
47  57363: "menu",
48  57409: "kp-decimal",
49  57410: "kp-divide",
50  57411: "kp-multiply",
51  57412: "kp-subtract",
52  57413: "kp-add",
53  57414: "kp-enter",
54  57415: "kp-equal",
55  57416: "kp-separator",
56  57417: "kp-left",
57  57418: "kp-right",
58  57419: "kp-up",
59  57420: "kp-down",
60  57421: "kp-pageup",
61  57422: "kp-pagedown",
62  57423: "kp-home",
63  57424: "kp-end",
64  57425: "kp-insert",
65  57426: "kp-delete",
66  57427: "kp-begin",
67  57428: "media-play",
68  57429: "media-pause",
69  57430: "media-play-pause",
70  57431: "media-reverse",
71  57432: "media-stop",
72  57433: "media-fast-forward",
73  57434: "media-rewind",
74  57435: "media-track-next",
75  57436: "media-track-previous",
76  57437: "media-record",
77  57438: "lower-volume",
78  57439: "raise-volume",
79  57440: "mute-volume",
80  57441: "left-shift",
81  57442: "left-control",
82  57443: "left-alt",
83  57444: "left-super",
84  57445: "left-hyper",
85  57446: "left-meta",
86  57447: "right-shift",
87  57448: "right-control",
88  57449: "right-alt",
89  57450: "right-super",
90  57451: "right-hyper",
91  57452: "right-meta",
92  57453: "iso-level3-shift",
93  57454: "iso-level5-shift",
94};
95
96/** Named key lookup from CSI letter suffix (arrows, Home, End). */
97const LETTER_NAMES: Record<string, string> = {
98  A: "up",
99  B: "down",
100  C: "right",
101  D: "left",
102  H: "home",
103  F: "end",
104  P: "f1",
105  Q: "f2",
106  S: "f4",
107};
108
109/** Named key lookup from CSI tilde number (Delete, PageUp/Down, F-keys). */
110const TILDE_NAMES: Record<number, string> = {
111  2: "insert",
112  3: "delete",
113  5: "pageup",
114  6: "pagedown",
115  7: "home",
116  8: "end",
117  11: "f1",
118  12: "f2",
119  13: "f3",
120  14: "f4",
121  15: "f5",
122  17: "f6",
123  18: "f7",
124  19: "f8",
125  20: "f9",
126  21: "f10",
127  23: "f11",
128  24: "f12",
129};
130
131/**
132 * Legacy byte -> named key mapping for unmodified special keys.
133 *
134 * With Kitty's baseline disambiguation flag, unmodified special keys that
135 * have well-known legacy encodings retain those encodings. Only modified
136 * variants (e.g., Shift+Tab, Ctrl+Enter) get the CSI-u treatment unless
137 * all-key reporting is requested. These mappings handle the legacy bytes.
138 */
139const LEGACY_BYTE_NAMES: Record<number, string> = {
140  9: "tab", // \t — also Ctrl+I in legacy, but collapsed to tab here
141  13: "enter", // \r — also Ctrl+M in legacy, but collapsed to enter here
142  27: "escape", // \x1b — bare ESC byte
143  127: "backspace", // \x7f — DEL byte
144};
145
146/** Raw printable characters that map to named keys. */
147const CHAR_NAMES: Record<string, string> = {
148  " ": "space",
149  "+": "plus",
150};
151
152const EDITING_KEYS = new Set([
153  "enter",
154  "backspace",
155  "delete",
156  "tab",
157  "up",
158  "down",
159  "left",
160  "right",
161  "home",
162  "end",
163  "space",
164  "plus",
165  "shift+enter",
166  "ctrl+a",
167  "ctrl+e",
168  "alt+b",
169  "alt+f",
170  "ctrl+left",
171  "ctrl+right",
172  "ctrl+w",
173  "alt+d",
174]);
175
176// --- Modifier decoding ---
177
178const NO_MODIFIERS: KeyModifiers = Object.freeze({
179  shift: false,
180  alt: false,
181  ctrl: false,
182  super: false,
183  hyper: false,
184  meta: false,
185  capsLock: false,
186  numLock: false,
187});
188
189/** Decode Kitty's `1 + bitmask` modifier parameter. */
190function decodeModifiers(param: number): KeyModifiers {
191  const bits = Math.max(0, param - 1);
192  if (bits === 0) return NO_MODIFIERS;
193  return {
194    shift: (bits & 1) !== 0,
195    alt: (bits & 2) !== 0,
196    ctrl: (bits & 4) !== 0,
197    super: (bits & 8) !== 0,
198    hyper: (bits & 16) !== 0,
199    meta: (bits & 32) !== 0,
200    capsLock: (bits & 64) !== 0,
201    numLock: (bits & 128) !== 0,
202  };
203}
204
205function modifierPrefix(modifiers: KeyModifiers): string {
206  const parts: string[] = [];
207  if (modifiers.ctrl) parts.push("ctrl");
208  if (modifiers.alt) parts.push("alt");
209  if (modifiers.shift) parts.push("shift");
210  if (modifiers.super) parts.push("super");
211  if (modifiers.hyper) parts.push("hyper");
212  if (modifiers.meta) parts.push("meta");
213  return parts.length > 0 ? `${parts.join("+")}+` : "";
214}
215
216/** Build a key string from a modifier prefix and base key name. */
217function withModifiers(modifiers: KeyModifiers, base: string): string {
218  return modifierPrefix(modifiers) + base;
219}
220
221// --- CSI sequence parsing ---
222
223/** Match CSI letter format: ESC [ <default> ; <modifiers> <letter> */
224const CSI_LETTER_RE = /^(?:1;(\d+)(?::([123]))?)?([A-HPSQ])$/;
225
226/** Match CSI tilde format: ESC [ <number> ; <modifiers> ~ */
227const CSI_TILDE_RE = /^(\d+)(?:;(\d+)(?::([123]))?)?~$/;
228
229function parseDecimal(value: string | undefined): number | null {
230  if (value === undefined || !/^\d+$/.test(value)) return null;
231  const parsed = Number(value);
232  return Number.isSafeInteger(parsed) ? parsed : null;
233}
234
235function parseCodePoint(value: string | undefined): number | null {
236  const parsed = parseDecimal(value);
237  return parsed !== null &&
238    parsed >= 0 &&
239    parsed <= 0x10ffff &&
240    !(parsed >= 0xd800 && parsed <= 0xdfff)
241    ? parsed
242    : null;
243}
244
245function parseEventType(value: string | undefined): KeyEventType | null {
246  switch (value ?? "1") {
247    case "1":
248      return "press";
249    case "2":
250      return "repeat";
251    case "3":
252      return "release";
253    default:
254      return null;
255  }
256}
257
258function functionalCodepointName(codePoint: number): string | undefined {
259  const direct = FUNCTIONAL_CODEPOINT_NAMES[codePoint];
260  if (direct) return direct;
261  if (codePoint >= 57376 && codePoint <= 57398) {
262    return `f${codePoint - 57363}`;
263  }
264  if (codePoint >= 57399 && codePoint <= 57408) {
265    return `kp${codePoint - 57399}`;
266  }
267  return undefined;
268}
269
270function codePointText(codePoint: number): string | null {
271  if (codePoint === 0 || codePoint > 0x10ffff) return null;
272  try {
273    return String.fromCodePoint(codePoint);
274  } catch {
275    return null;
276  }
277}
278
279function semanticCodePointName(
280  codePoint: number,
281  associatedText?: string,
282): string {
283  const named =
284    CODEPOINT_NAMES[codePoint] ?? functionalCodepointName(codePoint);
285  if (named) return named;
286  if (codePoint === 0 && associatedText) {
287    return CHAR_NAMES[associatedText] ?? associatedText.toLowerCase();
288  }
289  if (codePoint >= 57344 && codePoint <= 63743) {
290    return `unknown-codepoint:${codePoint}`;
291  }
292  const char = codePointText(codePoint);
293  return char === null
294    ? `unknown-codepoint:${codePoint}`
295    : (CHAR_NAMES[char] ?? char.toLowerCase());
296}
297
298function alternateKeyName(codePoint: number | null): string | undefined {
299  if (codePoint === null) return undefined;
300  return (
301    CODEPOINT_NAMES[codePoint] ??
302    functionalCodepointName(codePoint) ??
303    codePointText(codePoint) ??
304    undefined
305  );
306}
307
308function isAssociatedTextCodePoint(codePoint: number): boolean {
309  return !(codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f));
310}
311
312function parseAssociatedText(value: string | undefined): string | undefined {
313  if (value === undefined || value.length === 0) return undefined;
314  const codePoints = value.split(":").map(parseCodePoint);
315  if (
316    codePoints.some(
317      (codePoint) =>
318        codePoint === null || !isAssociatedTextCodePoint(codePoint),
319    )
320  ) {
321    return undefined;
322  }
323  return codePoints
324    .map((codePoint) => String.fromCodePoint(codePoint as number))
325    .join("");
326}
327
328function makeKeyInput(
329  key: string,
330  options: {
331    text?: string;
332    eventType?: KeyEventType;
333    codePoint?: number;
334    shiftedKey?: string;
335    baseLayoutKey?: string;
336    modifiers?: KeyModifiers;
337  } = {},
338): KeyInput {
339  return {
340    key,
341    text: options.text,
342    eventType: options.eventType ?? "press",
343    codePoint: options.codePoint,
344    shiftedKey: options.shiftedKey,
345    baseLayoutKey: options.baseLayoutKey,
346    modifiers: options.modifiers ?? NO_MODIFIERS,
347  };
348}
349
350function parseCsiUSequence(seq: string): KeyInput | null {
351  if (!seq.endsWith("u")) return null;
352  const fields = seq.slice(0, -1).split(";");
353  if (fields.length > 3) return null;
354
355  const keyParts = (fields[0] ?? "").split(":");
356  if (keyParts.length > 3) return null;
357  const codePoint = parseCodePoint(keyParts[0]);
358  if (codePoint === null) return null;
359
360  const shiftedCodePoint =
361    keyParts[1] === undefined || keyParts[1] === ""
362      ? null
363      : parseCodePoint(keyParts[1]);
364  const baseLayoutCodePoint =
365    keyParts[2] === undefined || keyParts[2] === ""
366      ? null
367      : parseCodePoint(keyParts[2]);
368  if (
369    (keyParts[1] !== undefined &&
370      keyParts[1] !== "" &&
371      shiftedCodePoint === null) ||
372    (keyParts[2] !== undefined &&
373      keyParts[2] !== "" &&
374      baseLayoutCodePoint === null)
375  ) {
376    return null;
377  }
378
379  const modifierParts = (fields[1] ?? "").split(":");
380  if (modifierParts.length > 2) return null;
381  const modifierParam =
382    modifierParts[0] === "" ? 1 : parseDecimal(modifierParts[0]);
383  const eventType = parseEventType(modifierParts[1]);
384  // Kitty encodes modifiers as `1 + bitmask`; zero is never a valid wire
385  // value. Unknown future high bits are ignored while all currently defined
386  // modifier and lock bits remain observable.
387  if (modifierParam === null || modifierParam < 1 || eventType === null) {
388    return null;
389  }
390
391  const modifiers = decodeModifiers(modifierParam);
392  const text = parseAssociatedText(fields[2]);
393  const base = semanticCodePointName(codePoint, text);
394  return makeKeyInput(withModifiers(modifiers, base), {
395    text,
396    eventType,
397    codePoint,
398    shiftedKey: alternateKeyName(shiftedCodePoint),
399    baseLayoutKey: alternateKeyName(baseLayoutCodePoint),
400    modifiers,
401  });
402}
403
404function parseCsiSequence(seq: string): KeyInput {
405  // Legacy Shift+Tab (CSI Z) — sent by tmux and some terminals
406  if (seq === "Z") {
407    return makeKeyInput("shift+tab", {
408      modifiers: { ...NO_MODIFIERS, shift: true },
409    });
410  }
411
412  const csiU = parseCsiUSequence(seq);
413  if (csiU) return csiU;
414
415  // CSI letter format: [1 ; modifiers] <letter>
416  let match = CSI_LETTER_RE.exec(seq);
417  if (match) {
418    const modParam = match[1] ? parseDecimal(match[1]) : 1;
419    const eventType = parseEventType(match[2]);
420    const letter = match[3];
421    if (
422      modParam === null ||
423      modParam < 1 ||
424      eventType === null ||
425      letter === undefined
426    ) {
427      return makeKeyInput(`unknown:${seq}`);
428    }
429    const name = LETTER_NAMES[letter];
430    const modifiers = decodeModifiers(modParam);
431    if (name) {
432      return makeKeyInput(withModifiers(modifiers, name), {
433        eventType,
434        modifiers,
435      });
436    }
437  }
438
439  // CSI tilde format: number [; modifiers] ~
440  match = CSI_TILDE_RE.exec(seq);
441  if (match) {
442    const num = parseDecimal(match[1]);
443    const modParam = match[2] ? parseDecimal(match[2]) : 1;
444    const eventType = parseEventType(match[3]);
445    if (
446      num === null ||
447      modParam === null ||
448      modParam < 1 ||
449      eventType === null
450    ) {
451      return makeKeyInput(`unknown:${seq}`);
452    }
453    const name = TILDE_NAMES[num];
454    const modifiers = decodeModifiers(modParam);
455    if (name) {
456      return makeKeyInput(withModifiers(modifiers, name), {
457        eventType,
458        modifiers,
459      });
460    }
461  }
462
463  return makeKeyInput(`unknown:${seq}`);
464}
465
466function decodeLegacyControlByte(code: number): string | null {
467  if (code >= 1 && code <= 26) {
468    return `ctrl+${String.fromCharCode(code + 96)}`;
469  }
470  return null;
471}
472
473function parseRawKeyInput(data: string): KeyInput {
474  const code = data.charCodeAt(0);
475
476  const legacy = LEGACY_BYTE_NAMES[code];
477  if (legacy) return makeKeyInput(legacy, { codePoint: code });
478
479  const ctrl = decodeLegacyControlByte(code);
480  if (ctrl) {
481    return makeKeyInput(ctrl, {
482      codePoint: code,
483      modifiers: { ...NO_MODIFIERS, ctrl: true },
484    });
485  }
486
487  const named = CHAR_NAMES[data];
488  const codePoint = data.codePointAt(0);
489  if (named) return makeKeyInput(named, { text: data, codePoint });
490
491  return makeKeyInput(data.toLowerCase(), { text: data, codePoint });
492}
493
494function parseAltKeyInput(data: string): KeyInput {
495  const base = parseRawKeyInput(data);
496  return makeKeyInput(normalizeKey(`alt+${base.key}`), {
497    codePoint: base.codePoint,
498    modifiers: { ...base.modifiers, alt: true },
499  });
500}
501
502function readCodePoint(
503  data: string,
504  index: number,
505): { value: string; nextIndex: number } | null {
506  if (index >= data.length) return null;
507  const codepoint = data.codePointAt(index);
508  if (codepoint === undefined) return null;
509  const value = String.fromCodePoint(codepoint);
510  return { value, nextIndex: index + value.length };
511}
512
513function readCsiSequence(
514  data: string,
515  index: number,
516): { value: string; nextIndex: number } | null {
517  if (!data.startsWith("\x1b[", index)) return null;
518
519  for (let i = index + 2; i < data.length; i++) {
520    const code = data.charCodeAt(i);
521    if (code >= 0x40 && code <= 0x7e) {
522      return { value: data.slice(index + 2, i + 1), nextIndex: i + 1 };
523    }
524  }
525
526  return null;
527}
528
529/**
530 * Decode a raw keyboard data chunk into ordered key events.
531 *
532 * A single chunk may contain multiple key presses batched together.
533 */
534export function decodeKeyEvents(data: string): KeyInput[] {
535  const events: KeyInput[] = [];
536  let index = 0;
537
538  while (index < data.length) {
539    const csi = readCsiSequence(data, index);
540    if (csi) {
541      events.push(parseCsiSequence(csi.value));
542      index = csi.nextIndex;
543      continue;
544    }
545
546    const char = data[index];
547    if (char === undefined) {
548      break;
549    }
550    if (char === "\x1b") {
551      const next = readCodePoint(data, index + 1);
552      if (next && next.value !== "[") {
553        events.push(parseAltKeyInput(next.value));
554        index = next.nextIndex;
555      } else {
556        events.push(makeKeyInput("escape", { codePoint: 27 }));
557        index += 1;
558      }
559      continue;
560    }
561
562    const codePoint = readCodePoint(data, index);
563    if (!codePoint) break;
564    events.push(parseRawKeyInput(codePoint.value));
565    index = codePoint.nextIndex;
566  }
567
568  return events;
569}
570
571// --- Public API ---
572
573/**
574 * Parse a single raw key sequence into a normalized key string.
575 *
576 * This is a convenience wrapper around {@link decodeKeyEvents} for callers that
577 * already know the input contains one logical key event.
578 *
579 * @param data - Raw terminal input string.
580 * @returns Normalized key string (e.g., `"ctrl+s"`, `"escape"`, `"alt+up"`).
581 */
582export function parseKey(data: string): string {
583  const events = decodeKeyEvents(data);
584  return events[0]?.key ?? `unknown:${data}`;
585}
586
587/**
588 * Normalize a key string to canonical format.
589 *
590 * Lowercases everything and reorders modifiers to the canonical
591 * order: `ctrl+alt+shift+super+hyper+meta+<key>`.
592 *
593 * @param key - Key string to normalize.
594 * @returns Normalized key string.
595 */
596export function normalizeKey(key: string): string {
597  const parts = key.toLowerCase().split("+");
598  if (parts.length <= 1) return key.toLowerCase();
599
600  const base = parts.at(-1);
601  if (!base) {
602    return key.toLowerCase();
603  }
604  const mods = parts.slice(0, -1);
605
606  const ordered: string[] = [];
607  if (mods.includes("ctrl")) ordered.push("ctrl");
608  if (mods.includes("alt")) ordered.push("alt");
609  if (mods.includes("shift")) ordered.push("shift");
610  if (mods.includes("super")) ordered.push("super");
611  if (mods.includes("hyper")) ordered.push("hyper");
612  if (mods.includes("meta")) ordered.push("meta");
613
614  return [...ordered, base].join("+");
615}
616
617/**
618 * Check whether a semantic key represents TextInput editing/navigation.
619 *
620 * Single-character semantic keys represent insertable text, while named keys
621 * like `"enter"` and `"left"` represent editing/navigation actions. Most
622 * modifier combos (`ctrl+s`, `alt+x`) are NOT editing keys and should bubble,
623 * but TextInput consumes a small set of readline-style shortcuts for cursor
624 * movement and word deletion.
625 */
626export function isEditingKey(key: string): boolean {
627  if (key.length === 1) return true;
628  return EDITING_KEYS.has(key);
629}