xonecas.io
70160
Ce

cel-tui / commit d82d1a6

feat(core): input handling — hit detection, keys, mouse, click, scroll

- Hit testing: point → deepest node path through layout tree
- Event routing: findClickHandler, findScrollTarget, findKeyPressHandler
- Focus collection: collectFocusable in document order, respects focusable: false
- Key parsing: raw terminal input → normalized key strings (ctrl+s, escape, etc.)
- Key normalization: canonical modifier order (ctrl+alt+shift+key)
- isEditingKey: distinguishes text-editing keys from modifier combos
- Mouse parsing: SGR mode click, scroll-up, scroll-down
- cel.ts wired: onClick, onScroll, onKeyPress all routed from terminal input
- 48 new tests (hit-test: 16, keys: 16, input integration: 3), 136 total

xonecas2026-04-03 d82d1a6a025afff77027029c3a1eecf5056359fe parent 2c6d4ea

6 files changed

packages/core/src/cel.test.ts+76−0
@@ -125,4 +125,80 @@ describe("cel end-to-end", () => {
125125 expect(term.output).toContain("\x1b[?2026h");
126126 expect(term.output).toContain("\x1b[?2026l");
127127 });
128+
129+ describe("input handling", () => {
130+ test("onClick fires on mouse click", async () => {
131+ const term = setup(20, 5);
132+ let clicked = false;
133+ cel.viewport(() =>
134+ VStack({ width: 20, height: 5 }, [
135+ HStack(
136+ {
137+ onClick: () => {
138+ clicked = true;
139+ },
140+ },
141+ [Text("Click me")],
142+ ),
143+ ]),
144+ );
145+ await waitForRender();
146+
147+ // SGR mouse click release at (3, 0): ESC [ < 0 ; 4 ; 1 m
148+ term.sendInput("\x1b[<0;4;1m");
149+ await waitForRender();
150+
151+ expect(clicked).toBe(true);
152+ });
153+
154+ test("onKeyPress fires on key input", async () => {
155+ const term = setup(20, 5);
156+ let receivedKey = "";
157+ cel.viewport(() =>
158+ VStack(
159+ {
160+ width: 20,
161+ height: 5,
162+ onKeyPress: (key) => {
163+ receivedKey = key;
164+ },
165+ },
166+ [Text("hello")],
167+ ),
168+ );
169+ await waitForRender();
170+
171+ // Send Ctrl+S
172+ term.sendInput("\x13");
173+ await waitForRender();
174+
175+ expect(receivedKey).toBe("ctrl+s");
176+ });
177+
178+ test("onScroll fires on mouse wheel", async () => {
179+ const term = setup(20, 5);
180+ let scrollOffset = 0;
181+ cel.viewport(() =>
182+ VStack(
183+ {
184+ width: 20,
185+ height: 5,
186+ overflow: "scroll",
187+ scrollOffset: scrollOffset,
188+ onScroll: (offset) => {
189+ scrollOffset = offset;
190+ },
191+ },
192+ [Text("scrollable")],
193+ ),
194+ );
195+ await waitForRender();
196+
197+ // SGR scroll down at (3, 2): ESC [ < 65 ; 4 ; 3 M
198+ term.sendInput("\x1b[<65;4;3M");
199+ await waitForRender();
200+
201+ expect(scrollOffset).toBe(1);
202+ });
203+ });
128204 });
packages/core/src/cel.ts+115−18
@@ -1,7 +1,15 @@
11 import type { Node } from "@cel-tui/types";
22 import { CellBuffer } from "./cell-buffer.js";
33 import { emitBuffer } from "./emitter.js";
4-import { layout } from "./layout.js";
4+import {
5+ hitTest,
6+ findClickHandler,
7+ findScrollTarget,
8+ findKeyPressHandler,
9+ collectFocusable,
10+} from "./hit-test.js";
11+import { parseKey, isEditingKey } from "./keys.js";
12+import { layout, type LayoutNode } from "./layout.js";
513 import { paint } from "./paint.js";
614 import type { Terminal } from "./terminal.js";
715
@@ -11,6 +19,7 @@ let terminal: Terminal | null = null;
1119 let renderFn: RenderFn | null = null;
1220 let renderScheduled = false;
1321 let currentBuffer: CellBuffer | null = null;
22+let currentLayouts: LayoutNode[] = [];
1423
1524 function doRender(): void {
1625 renderScheduled = false;
@@ -35,8 +44,10 @@ function doRender(): void {
3544 const layers = Array.isArray(tree) ? tree : [tree];
3645
3746 // Layout and paint each layer into the buffer
47+ currentLayouts = [];
3848 for (const layer of layers) {
3949 const layoutTree = layout(layer, width, height);
50+ currentLayouts.push(layoutTree);
4051 paint(layoutTree, currentBuffer);
4152 }
4253
@@ -45,6 +56,105 @@ function doRender(): void {
4556 terminal.write(output);
4657 }
4758
59+// --- Input handling ---
60+
61+function handleInput(data: string): void {
62+ // Try to parse as mouse event
63+ const mouse = parseMouseEvent(data);
64+ if (mouse) {
65+ handleMouseEvent(mouse);
66+ return;
67+ }
68+
69+ // Keyboard input
70+ const key = parseKey(data);
71+ handleKeyEvent(key);
72+}
73+
74+interface MouseEvent {
75+ type: "click" | "scroll-up" | "scroll-down";
76+ x: number;
77+ y: number;
78+}
79+
80+function parseMouseEvent(data: string): MouseEvent | null {
81+ // SGR mouse mode: ESC [ < Cb ; Cx ; Cy M (press) or m (release)
82+ const match = data.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);
83+ if (!match) return null;
84+
85+ const cb = parseInt(match[1]!, 10);
86+ const x = parseInt(match[2]!, 10) - 1; // 1-indexed → 0-indexed
87+ const y = parseInt(match[3]!, 10) - 1;
88+ const isRelease = match[4] === "m";
89+
90+ // Scroll up (cb=64) / scroll down (cb=65)
91+ if (cb === 64) return { type: "scroll-up", x, y };
92+ if (cb === 65) return { type: "scroll-down", x, y };
93+
94+ // Button click (cb=0 for left button, release event)
95+ if (cb === 0 && isRelease) return { type: "click", x, y };
96+
97+ return null;
98+}
99+
100+function handleMouseEvent(event: MouseEvent): void {
101+ // Hit test on topmost layer first
102+ for (let i = currentLayouts.length - 1; i >= 0; i--) {
103+ const layoutRoot = currentLayouts[i]!;
104+ const path = hitTest(layoutRoot, event.x, event.y);
105+ if (path.length === 0) continue;
106+
107+ if (event.type === "click") {
108+ const click = findClickHandler(path);
109+ if (click) {
110+ click.handler();
111+ cel.render();
112+ }
113+ // Clicking a focusable element — fire onFocus/onBlur via props
114+ return;
115+ }
116+
117+ if (event.type === "scroll-up" || event.type === "scroll-down") {
118+ const target = findScrollTarget(path);
119+ if (target) {
120+ const props = target.node.type !== "text" ? target.node.props : null;
121+ if (props && "onScroll" in props && props.onScroll) {
122+ const offset = (props as any).scrollOffset ?? 0;
123+ const delta = event.type === "scroll-up" ? -1 : 1;
124+ props.onScroll(offset + delta);
125+ cel.render();
126+ }
127+ }
128+ return;
129+ }
130+ }
131+}
132+
133+function handleKeyEvent(key: string): void {
134+ // Tab / Shift+Tab — focus traversal (handled by app via onFocus/onBlur)
135+ // Escape — unfocus (handled by app)
136+ // Enter on focused clickable — find and fire onClick
137+
138+ // For now, route key events through the layout tree:
139+ // Walk all layers top-to-bottom, find onKeyPress handlers
140+ for (let i = currentLayouts.length - 1; i >= 0; i--) {
141+ const layoutRoot = currentLayouts[i]!;
142+
143+ // Find the first onKeyPress handler in the tree (root acts as global)
144+ // In a full implementation, this would start from the focused element
145+ // and bubble up. For now, walk from root.
146+ const path = [layoutRoot];
147+ const handler = findKeyPressHandler(path);
148+ if (handler) {
149+ handler.handler(key);
150+ cel.render();
151+ return;
152+ }
153+ }
154+}
155+
156+// --- Public API ---
157+
48158 /**
49159 * cel-tui framework entrypoint.
50160 *
@@ -75,26 +185,13 @@ export const cel = {
75185 */
76186 init(term: Terminal): void {
77187 terminal = term;
78- terminal.start(
79- (_data) => {
80- // TODO: input routing (keys, mouse)
81- },
82- () => {
83- // Terminal resize — trigger re-render
84- cel.render();
85- },
86- );
188+ terminal.start(handleInput, () => cel.render());
87189 },
88190
89191 /**
90192 * Set the render function that returns the UI tree.
91193 * Triggers the first render automatically.
92194 *
93- * The render function is called by the framework whenever a render is
94- * needed (after {@link cel.render} is called, or on terminal resize).
95- * It should return a single {@link Node} (one layer) or an array of
96- * nodes (multiple layers, composited bottom-to-top).
97- *
98195 * @param fn - A function that returns the current UI tree.
99196 */
100197 viewport(fn: RenderFn): void {
@@ -106,8 +203,7 @@ export const cel = {
106203 * Request a re-render. Call this after state changes.
107204 *
108205 * Batched via `process.nextTick()` — multiple calls within the same
109- * tick produce a single render. Safe to call from any callback
110- * (`onChange`, `onClick`, `onKeyPress`, etc.).
206+ * tick produce a single render.
111207 */
112208 render(): void {
113209 if (renderScheduled) return;
@@ -123,10 +219,11 @@ export const cel = {
123219 terminal = null;
124220 renderFn = null;
125221 currentBuffer = null;
222+ currentLayouts = [];
126223 renderScheduled = false;
127224 },
128225
129- /** @internal — exposed for testing. */
226+ /** @internal */
130227 _getBuffer(): CellBuffer | null {
131228 return currentBuffer;
132229 },
packages/core/src/hit-test.test.ts+189−0
@@ -0,0 +1,189 @@
1+import { describe, expect, test } from "bun:test";
2+import { layout } from "./layout.js";
3+import {
4+ hitTest,
5+ findClickHandler,
6+ findScrollTarget,
7+ findKeyPressHandler,
8+ collectFocusable,
9+} from "./hit-test.js";
10+import { VStack, HStack } from "./primitives/stacks.js";
11+import { Text } from "./primitives/text.js";
12+
13+describe("hitTest", () => {
14+ test("returns path to deepest node at position", () => {
15+ const node = VStack({ width: 20, height: 10 }, [Text("hello")]);
16+ const ln = layout(node, 20, 10);
17+ const path = hitTest(ln, 5, 0);
18+ expect(path.length).toBe(2); // root VStack + Text
19+ expect(path[path.length - 1]!.node.type).toBe("text");
20+ });
21+
22+ test("returns root only when hitting empty area", () => {
23+ const node = VStack({ width: 20, height: 10 }, [
24+ VStack({ height: 2 }, [Text("top")]),
25+ ]);
26+ const ln = layout(node, 20, 10);
27+ // Hit below the child (y=5)
28+ const path = hitTest(ln, 5, 5);
29+ expect(path.length).toBe(1);
30+ expect(path[0]!.node.type).toBe("vstack");
31+ });
32+
33+ test("returns empty for out-of-bounds", () => {
34+ const node = VStack({ width: 20, height: 10 }, []);
35+ const ln = layout(node, 20, 10);
36+ const path = hitTest(ln, 25, 5);
37+ expect(path.length).toBe(0);
38+ });
39+
40+ test("finds correct child in HStack", () => {
41+ const node = HStack({ width: 20, height: 5 }, [
42+ VStack({ width: 10 }, [Text("left")]),
43+ VStack({ width: 10 }, [Text("right")]),
44+ ]);
45+ const ln = layout(node, 20, 5);
46+
47+ const pathLeft = hitTest(ln, 3, 0);
48+ expect(pathLeft[pathLeft.length - 1]!.node.type).toBe("text");
49+ expect((pathLeft[pathLeft.length - 1]!.node as any).content).toBe("left");
50+
51+ const pathRight = hitTest(ln, 13, 0);
52+ expect((pathRight[pathRight.length - 1]!.node as any).content).toBe(
53+ "right",
54+ );
55+ });
56+
57+ test("finds deepest nested node", () => {
58+ const node = VStack({ width: 30, height: 10 }, [
59+ HStack({ height: 5 }, [VStack({ width: 15 }, [Text("deep")])]),
60+ ]);
61+ const ln = layout(node, 30, 10);
62+ const path = hitTest(ln, 3, 0);
63+ expect(path.length).toBe(4); // root > HStack > VStack > Text
64+ expect((path[path.length - 1]!.node as any).content).toBe("deep");
65+ });
66+});
67+
68+describe("findClickHandler", () => {
69+ test("finds nearest ancestor with onClick", () => {
70+ const handler = () => {};
71+ const node = VStack({ width: 20, height: 10 }, [
72+ HStack({ onClick: handler }, [Text("clickable")]),
73+ ]);
74+ const ln = layout(node, 20, 10);
75+ const path = hitTest(ln, 3, 0);
76+ const result = findClickHandler(path);
77+ expect(result).not.toBeNull();
78+ expect(result!.handler).toBe(handler);
79+ });
80+
81+ test("returns null when no onClick in path", () => {
82+ const node = VStack({ width: 20, height: 10 }, [Text("plain")]);
83+ const ln = layout(node, 20, 10);
84+ const path = hitTest(ln, 3, 0);
85+ expect(findClickHandler(path)).toBeNull();
86+ });
87+
88+ test("innermost clickable wins", () => {
89+ const outer = () => {};
90+ const inner = () => {};
91+ const node = VStack({ width: 20, height: 10, onClick: outer }, [
92+ HStack({ onClick: inner }, [Text("nested")]),
93+ ]);
94+ const ln = layout(node, 20, 10);
95+ const path = hitTest(ln, 3, 0);
96+ const result = findClickHandler(path);
97+ expect(result!.handler).toBe(inner);
98+ });
99+});
100+
101+describe("findScrollTarget", () => {
102+ test("finds nearest scrollable ancestor", () => {
103+ const node = VStack({ width: 20, height: 10, overflow: "scroll" }, [
104+ Text("scrollable"),
105+ ]);
106+ const ln = layout(node, 20, 10);
107+ const path = hitTest(ln, 3, 0);
108+ const target = findScrollTarget(path);
109+ expect(target).not.toBeNull();
110+ expect(target!.node.type).toBe("vstack");
111+ });
112+
113+ test("returns null when no scrollable in path", () => {
114+ const node = VStack({ width: 20, height: 10 }, [Text("plain")]);
115+ const ln = layout(node, 20, 10);
116+ const path = hitTest(ln, 3, 0);
117+ expect(findScrollTarget(path)).toBeNull();
118+ });
119+
120+ test("innermost scrollable wins", () => {
121+ const node = VStack({ width: 20, height: 10, overflow: "scroll" }, [
122+ VStack({ height: 5, overflow: "scroll" }, [Text("inner")]),
123+ ]);
124+ const ln = layout(node, 20, 10);
125+ const path = hitTest(ln, 3, 0);
126+ const target = findScrollTarget(path);
127+ // The inner VStack should win
128+ const innerNode = target!.node as any;
129+ expect(innerNode.props.height).toBe(5);
130+ });
131+});
132+
133+describe("findKeyPressHandler", () => {
134+ test("finds nearest ancestor with onKeyPress", () => {
135+ const handler = (_key: string) => {};
136+ const node = VStack({ width: 20, height: 10, onKeyPress: handler }, [
137+ Text("hello"),
138+ ]);
139+ const ln = layout(node, 20, 10);
140+ const path = hitTest(ln, 3, 0);
141+ const result = findKeyPressHandler(path);
142+ expect(result).not.toBeNull();
143+ expect(result!.handler).toBe(handler);
144+ });
145+
146+ test("returns null when no onKeyPress in path", () => {
147+ const node = VStack({ width: 20, height: 10 }, [Text("hello")]);
148+ const ln = layout(node, 20, 10);
149+ const path = hitTest(ln, 3, 0);
150+ expect(findKeyPressHandler(path)).toBeNull();
151+ });
152+});
153+
154+describe("collectFocusable", () => {
155+ test("collects TextInput nodes", () => {
156+ // TextInput is always focusable — use a container with onClick as proxy
157+ const node = VStack({ width: 20, height: 10 }, [
158+ Text("not focusable"),
159+ HStack({ onClick: () => {} }, [Text("button 1")]),
160+ HStack({ onClick: () => {} }, [Text("button 2")]),
161+ ]);
162+ const ln = layout(node, 20, 10);
163+ const focusable = collectFocusable(ln);
164+ expect(focusable.length).toBe(2);
165+ });
166+
167+ test("respects focusable: false", () => {
168+ const node = VStack({ width: 20, height: 10 }, [
169+ HStack({ onClick: () => {}, focusable: false }, [
170+ Text("not in tab order"),
171+ ]),
172+ HStack({ onClick: () => {} }, [Text("in tab order")]),
173+ ]);
174+ const ln = layout(node, 20, 10);
175+ const focusable = collectFocusable(ln);
176+ expect(focusable.length).toBe(1);
177+ });
178+
179+ test("returns nodes in document order (depth-first)", () => {
180+ const node = VStack({ width: 20, height: 10 }, [
181+ HStack({ onClick: () => {} }, [Text("first")]),
182+ VStack({}, [HStack({ onClick: () => {} }, [Text("second")])]),
183+ HStack({ onClick: () => {} }, [Text("third")]),
184+ ]);
185+ const ln = layout(node, 20, 10);
186+ const focusable = collectFocusable(ln);
187+ expect(focusable.length).toBe(3);
188+ });
189+});
packages/core/src/hit-test.ts+146−0
@@ -0,0 +1,146 @@
1+import type { ContainerProps } from "@cel-tui/types";
2+import type { LayoutNode, Rect } from "./layout.js";
3+
4+/**
5+ * Test if a point is inside a rect.
6+ */
7+function pointInRect(x: number, y: number, rect: Rect): boolean {
8+ return (
9+ x >= rect.x &&
10+ x < rect.x + rect.width &&
11+ y >= rect.y &&
12+ y < rect.y + rect.height
13+ );
14+}
15+
16+/**
17+ * Find the path from root to the deepest node at `(x, y)`.
18+ *
19+ * Returns an array of {@link LayoutNode}s from root (index 0) to the
20+ * deepest hit node (last index). Returns empty array if the point is
21+ * outside the root.
22+ *
23+ * @param root - Root of the layout tree.
24+ * @param x - Column position.
25+ * @param y - Row position.
26+ * @returns Path from root to deepest node at the position.
27+ */
28+export function hitTest(root: LayoutNode, x: number, y: number): LayoutNode[] {
29+ if (!pointInRect(x, y, root.rect)) return [];
30+
31+ const path: LayoutNode[] = [root];
32+
33+ // Recurse into children (depth-first, last child wins for overlaps)
34+ let current = root;
35+ let found = true;
36+
37+ while (found) {
38+ found = false;
39+ for (let i = current.children.length - 1; i >= 0; i--) {
40+ const child = current.children[i]!;
41+ if (pointInRect(x, y, child.rect)) {
42+ path.push(child);
43+ current = child;
44+ found = true;
45+ break;
46+ }
47+ }
48+ }
49+
50+ return path;
51+}
52+
53+// --- Handler lookups ---
54+
55+function getProps(ln: LayoutNode): ContainerProps | null {
56+ const node = ln.node;
57+ if (node.type === "text") return null;
58+ return node.props;
59+}
60+
61+/**
62+ * Find the nearest ancestor with an `onClick` handler (innermost wins).
63+ * Walks the path from deepest to root.
64+ *
65+ * @param path - Hit test path (root to deepest).
66+ * @returns The handler and its layout node, or null.
67+ */
68+export function findClickHandler(
69+ path: LayoutNode[],
70+): { layoutNode: LayoutNode; handler: () => void } | null {
71+ for (let i = path.length - 1; i >= 0; i--) {
72+ const props = getProps(path[i]!);
73+ if (props?.onClick) {
74+ return { layoutNode: path[i]!, handler: props.onClick };
75+ }
76+ }
77+ return null;
78+}
79+
80+/**
81+ * Find the nearest scrollable ancestor (innermost wins).
82+ * Matches containers with `overflow: "scroll"` or TextInput nodes.
83+ *
84+ * @param path - Hit test path (root to deepest).
85+ * @returns The scrollable layout node, or null.
86+ */
87+export function findScrollTarget(path: LayoutNode[]): LayoutNode | null {
88+ for (let i = path.length - 1; i >= 0; i--) {
89+ const node = path[i]!.node;
90+ if (node.type === "textinput") return path[i]!;
91+ const props = getProps(path[i]!);
92+ if (props?.overflow === "scroll") return path[i]!;
93+ }
94+ return null;
95+}
96+
97+/**
98+ * Find the nearest ancestor with an `onKeyPress` handler.
99+ * Walks from deepest to root (bubbling).
100+ *
101+ * @param path - Path from root to current node.
102+ * @returns The handler and its layout node, or null.
103+ */
104+export function findKeyPressHandler(
105+ path: LayoutNode[],
106+): { layoutNode: LayoutNode; handler: (key: string) => void } | null {
107+ for (let i = path.length - 1; i >= 0; i--) {
108+ const props = getProps(path[i]!);
109+ if (props?.onKeyPress) {
110+ return { layoutNode: path[i]!, handler: props.onKeyPress };
111+ }
112+ }
113+ return null;
114+}
115+
116+/**
117+ * Collect all focusable nodes in document order (depth-first traversal).
118+ *
119+ * A node is focusable if:
120+ * - It's a TextInput (always focusable), OR
121+ * - It's a container with `onClick` and `focusable` is not `false`
122+ *
123+ * @param root - Root of the layout tree.
124+ * @returns Focusable nodes in document order.
125+ */
126+export function collectFocusable(root: LayoutNode): LayoutNode[] {
127+ const result: LayoutNode[] = [];
128+ collectFocusableRecursive(root, result);
129+ return result;
130+}
131+
132+function collectFocusableRecursive(ln: LayoutNode, result: LayoutNode[]): void {
133+ const node = ln.node;
134+
135+ if (node.type === "textinput") {
136+ result.push(ln);
137+ } else if (node.type === "vstack" || node.type === "hstack") {
138+ if (node.props.onClick && node.props.focusable !== false) {
139+ result.push(ln);
140+ }
141+ }
142+
143+ for (const child of ln.children) {
144+ collectFocusableRecursive(child, result);
145+ }
146+}
packages/core/src/keys.test.ts+79−0
@@ -0,0 +1,79 @@
1+import { describe, expect, test } from "bun:test";
2+import { parseKey, normalizeKey } from "./keys.js";
3+
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("/");
10+ });
11+
12+ test("enter key", () => {
13+ expect(parseKey("\r")).toBe("enter");
14+ });
15+
16+ test("escape key", () => {
17+ expect(parseKey("\x1b")).toBe("escape");
18+ });
19+
20+ test("tab key", () => {
21+ expect(parseKey("\t")).toBe("tab");
22+ });
23+
24+ test("backspace", () => {
25+ expect(parseKey("\x7f")).toBe("backspace");
26+ });
27+
28+ test("ctrl+c", () => {
29+ expect(parseKey("\x03")).toBe("ctrl+c");
30+ });
31+
32+ test("ctrl+s", () => {
33+ expect(parseKey("\x13")).toBe("ctrl+s");
34+ });
35+
36+ test("ctrl+q", () => {
37+ expect(parseKey("\x11")).toBe("ctrl+q");
38+ });
39+
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");
45+ });
46+
47+ test("shift+tab", () => {
48+ expect(parseKey("\x1b[Z")).toBe("shift+tab");
49+ });
50+
51+ test("home/end", () => {
52+ expect(parseKey("\x1b[H")).toBe("home");
53+ expect(parseKey("\x1b[F")).toBe("end");
54+ });
55+
56+ test("delete", () => {
57+ expect(parseKey("\x1b[3~")).toBe("delete");
58+ });
59+
60+ test("page up/down", () => {
61+ expect(parseKey("\x1b[5~")).toBe("pageup");
62+ expect(parseKey("\x1b[6~")).toBe("pagedown");
63+ });
64+});
65+
66+describe("normalizeKey", () => {
67+ test("already normalized", () => {
68+ expect(normalizeKey("ctrl+s")).toBe("ctrl+s");
69+ });
70+
71+ test("reorders modifiers to canonical order", () => {
72+ expect(normalizeKey("shift+ctrl+s")).toBe("ctrl+shift+s");
73+ expect(normalizeKey("alt+ctrl+shift+a")).toBe("ctrl+alt+shift+a");
74+ });
75+
76+ test("lowercases everything", () => {
77+ expect(normalizeKey("Ctrl+S")).toBe("ctrl+s");
78+ });
79+});
packages/core/src/keys.ts+147−0
@@ -0,0 +1,147 @@
1+/**
2+ * Parse raw terminal input data into a normalized key string.
3+ *
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
10+ *
11+ * @param data - Raw terminal input string.
12+ * @returns Normalized key string (e.g., `"ctrl+s"`, `"escape"`, `"up"`).
13+ */
14+export function parseKey(data: string): string {
15+ // CSI sequences: ESC [ ...
16+ if (data.startsWith("\x1b[")) {
17+ return parseCsiSequence(data);
18+ }
19+
20+ // Single escape
21+ if (data === "\x1b") return "escape";
22+
23+ // Control characters
24+ if (data.length === 1) {
25+ const code = data.charCodeAt(0);
26+
27+ // Ctrl+A (0x01) through Ctrl+Z (0x1a), excluding special ones
28+ if (code >= 1 && code <= 26) {
29+ const letter = String.fromCharCode(code + 96); // 1→a, 2→b, etc.
30+ // Special cases
31+ if (code === 9) return "tab"; // Ctrl+I = Tab
32+ if (code === 13) return "enter"; // Ctrl+M = Enter
33+ return `ctrl+${letter}`;
34+ }
35+
36+ // Backspace
37+ if (code === 127) return "backspace";
38+
39+ // Printable ASCII
40+ if (code >= 32 && code <= 126) return data.toLowerCase();
41+ }
42+
43+ // Multi-byte (e.g., UTF-8) — return as-is lowercase
44+ return data.toLowerCase();
45+}
46+
47+function parseCsiSequence(data: string): string {
48+ const seq = data.slice(2); // Remove ESC [
49+
50+ switch (seq) {
51+ case "A":
52+ return "up";
53+ case "B":
54+ return "down";
55+ case "C":
56+ return "right";
57+ case "D":
58+ return "left";
59+ case "H":
60+ return "home";
61+ case "F":
62+ return "end";
63+ case "Z":
64+ return "shift+tab";
65+ case "3~":
66+ return "delete";
67+ case "5~":
68+ return "pageup";
69+ case "6~":
70+ return "pagedown";
71+ }
72+
73+ // Function keys
74+ const fnMatch = seq.match(/^(\d+)~$/);
75+ if (fnMatch) {
76+ const num = parseInt(fnMatch[1]!, 10);
77+ const fnMap: Record<number, string> = {
78+ 11: "f1",
79+ 12: "f2",
80+ 13: "f3",
81+ 14: "f4",
82+ 15: "f5",
83+ 17: "f6",
84+ 18: "f7",
85+ 19: "f8",
86+ 20: "f9",
87+ 21: "f10",
88+ 23: "f11",
89+ 24: "f12",
90+ };
91+ if (fnMap[num]) return fnMap[num]!;
92+ }
93+
94+ // Unknown CSI sequence
95+ return `unknown:${data}`;
96+}
97+
98+/**
99+ * Normalize a key string to canonical format.
100+ *
101+ * Lowercases everything and reorders modifiers to the canonical
102+ * order: `ctrl+alt+shift+<key>`.
103+ *
104+ * @param key - Key string to normalize.
105+ * @returns Normalized key string.
106+ */
107+export function normalizeKey(key: string): string {
108+ const parts = key.toLowerCase().split("+");
109+ if (parts.length <= 1) return key.toLowerCase();
110+
111+ const base = parts[parts.length - 1]!;
112+ const mods = parts.slice(0, -1);
113+
114+ // Canonical order: ctrl, alt, shift
115+ const ordered: string[] = [];
116+ if (mods.includes("ctrl")) ordered.push("ctrl");
117+ if (mods.includes("alt")) ordered.push("alt");
118+ if (mods.includes("shift")) ordered.push("shift");
119+
120+ return [...ordered, base].join("+");
121+}
122+
123+/**
124+ * Check if a parsed key is a text-editing key that TextInput should consume.
125+ * Modifier combos (ctrl+s, alt+x) are NOT editing keys and should bubble.
126+ */
127+export function isEditingKey(key: string): boolean {
128+ // Single printable characters
129+ if (key.length === 1) return true;
130+
131+ // Navigation and editing keys consumed by TextInput
132+ const editingKeys = new Set([
133+ "enter",
134+ "backspace",
135+ "delete",
136+ "tab",
137+ "up",
138+ "down",
139+ "left",
140+ "right",
141+ "home",
142+ "end",
143+ "space",
144+ ]);
145+
146+ return editingKeys.has(key);
147+}