xonecas.io
70160
Ce

cel-tui / commit f5280a2

feat(core): onKeyPress bubbling with return false convention

Implement spec-compliant key event bubbling through ancestor handlers.
Previously, only the innermost onKeyPress handler was called and the
event stopped. Now handlers can return false to signal the key was not
consumed, allowing it to continue bubbling to parent handlers.

- Change onKeyPress signature to (key: string) => boolean | void
- Return false = not consumed (keep bubbling)
- Return void/undefined/true = consumed (stop bubbling, backward compat)
- Replace findKeyPressHandler with collectKeyPressHandlers (collects all
  handlers along the path, innermost-first)
- Update cel.ts dispatch to iterate handlers and stop on first non-false
- Select component returns false for unrecognized keys instead of
  manual onKeyPress forwarding
- Simplify select example: ctrl+q/ctrl+r now live on root onKeyPress
- Update spec Key Event Flow (steps 4-6) and prop table
- Remove onKeyPress bubbling TODO item
- Add 4 new tests, update 3 existing hit-test tests

xonecas2026-04-04 f5280a2a6538152f116ec17273dbeabaa23673f5 parent 11a74b2

9 files changed

TODO.md+0−2
@@ -18,8 +18,6 @@ Remaining work, known bugs, and planned improvements.
1818
1919 - ❌ **`VDivider` component** — Drawing a vertical divider requires `VStack({ width: 1, height: "100%" }, [Text("│", { repeat: "fill" })])`. A `VDivider({ char, fgColor })` component would match the existing horizontal `Divider` and reduce boilerplate.
2020
21-- ❌ **`onKeyPress` bubbling through component boundaries** — `findKeyPressHandler` returns the innermost handler and stops. Unhandled keys don't bubble to parent `onKeyPress` handlers. This means every stateful component with `onKeyPress` needs to manually forward unrecognized keys (e.g., `Select` accepts an `onKeyPress` prop and calls it for keys it doesn't consume). A framework-level fix — such as a "return false to keep bubbling" convention or a `consumed` return value from handlers — …
22-
2321 ## Not Yet Implemented
2422
2523 - ❌ 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.
examples/select.ts+11−11
@@ -45,17 +45,6 @@ const fruitSelect = Select({
4545 selected = value;
4646 cel.render();
4747 },
48- onKeyPress: (key) => {
49- if (key === "ctrl+q") {
50- cel.stop();
51- process.exit();
52- }
53- if (key === "ctrl+r") {
54- selected = "";
55- fruitSelect.reset();
56- cel.render();
57- }
58- },
5948 focusStyle: { fgColor: "white" },
6049 });
6150
@@ -66,6 +55,17 @@ cel.viewport(() =>
6655 height: "100%",
6756 padding: { x: 2, y: 1 },
6857 fgColor: "white",
58+ onKeyPress: (key) => {
59+ if (key === "ctrl+q") {
60+ cel.stop();
61+ process.exit();
62+ }
63+ if (key === "ctrl+r") {
64+ selected = "";
65+ fruitSelect.reset();
66+ cel.render();
67+ }
68+ },
6969 },
7070 [
7171 Text("Select Component Demo", { bold: true, fgColor: "cyan" }),
packages/components/src/select.ts+21−9
@@ -62,13 +62,12 @@ export interface SelectProps {
6262 */
6363 highlightColor?: Color;
6464 /**
65- * Called for key events not consumed by the Select
66- * (e.g., modifier combos like `"ctrl+s"`).
67- * Use this to handle application-level shortcuts when the Select is focused.
65+ * Called on key events that bubble up to the Select.
66+ * Return `false` to keep bubbling to ancestors.
6867 *
69- * @param key - The unhandled key string.
68+ * @param key - The key string.
7069 */
71- onKeyPress?: (key: string) => void;
70+ onKeyPress?: (key: string) => boolean | void;
7271 /** Fixed width in cells or percentage. */
7372 width?: SizeValue;
7473 /** Fixed height in cells or percentage. */
@@ -241,6 +240,19 @@ export function Select(props: SelectProps): SelectInstance {
241240 focusStyle,
242241 } = props;
243242
243+ // Compose user's onKeyPress with internal handler.
244+ // Internal handler runs first; if it returns false (unrecognized key),
245+ // delegate to the user's handler for component-level interception.
246+ // If the user's handler also returns false, the framework continues
247+ // bubbling to ancestors automatically.
248+ function composedKeyPress(key: string): boolean | void {
249+ const result = handleKey(key);
250+ if (result === false && userKeyPress) {
251+ return userKeyPress(key);
252+ }
253+ return result;
254+ }
255+
244256 let query = "";
245257 let highlightIndex = 0;
246258 let scrollOffset = 0;
@@ -249,7 +261,7 @@ export function Select(props: SelectProps): SelectInstance {
249261 return prefixFilter(normalizeItems(rawItems), query);
250262 }
251263
252- function handleKey(key: string): void {
264+ function handleKey(key: string): boolean | void {
253265 switch (key) {
254266 case "enter": {
255267 const filtered = getFiltered();
@@ -305,8 +317,8 @@ export function Select(props: SelectProps): SelectInstance {
305317 scrollOffset = 0;
306318 cel.render();
307319 } else {
308- // Forward unrecognized keys to user callback
309- userKeyPress?.(key);
320+ // Unrecognized key — let it bubble to ancestors
321+ return false;
310322 }
311323 return;
312324 }
@@ -375,7 +387,7 @@ export function Select(props: SelectProps): SelectInstance {
375387
376388 return VStack(
377389 {
378- onKeyPress: handleKey,
390+ onKeyPress: composedKeyPress,
379391 focusable: focusable ?? true,
380392 focused,
381393 onFocus,
packages/core/src/cel.test.ts+138−4
@@ -499,7 +499,7 @@ describe("cel end-to-end", () => {
499499 });
500500
501501 describe("onKeyPress bubbling", () => {
502- test("key bubbles from focused element up through ancestors", async () => {
502+ test("void handler consumes key — no further bubbling (backward compat)", async () => {
503503 const term = setup(20, 5);
504504 const received: string[] = [];
505505
@@ -517,6 +517,7 @@ describe("cel end-to-end", () => {
517517 {
518518 onKeyPress: (key) => {
519519 received.push("mid:" + key);
520+ // void return = consumed
520521 },
521522 },
522523 [
@@ -534,14 +535,147 @@ describe("cel end-to-end", () => {
534535 );
535536 await waitForRender();
536537
537- // Send a key — should bubble from focused btn through mid, then root
538538 term.sendInput("x");
539539 await waitForRender();
540540
541- // Nearest ancestor with onKeyPress is "mid", so it handles first
541+ // mid handler consumes (void return), root never sees the key
542542 expect(received).toEqual(["mid:x"]);
543543 });
544544
545+ test("returning false continues bubbling to parent handlers", async () => {
546+ const term = setup(20, 5);
547+ const received: string[] = [];
548+
549+ cel.viewport(() =>
550+ VStack(
551+ {
552+ width: 20,
553+ height: 5,
554+ onKeyPress: (key) => {
555+ received.push("root:" + key);
556+ },
557+ },
558+ [
559+ VStack(
560+ {
561+ onKeyPress: (key) => {
562+ received.push("mid:" + key);
563+ return false; // not consumed — keep bubbling
564+ },
565+ },
566+ [
567+ HStack(
568+ {
569+ onClick: () => {},
570+ focused: true,
571+ },
572+ [Text("Focused Btn")],
573+ ),
574+ ],
575+ ),
576+ ],
577+ ),
578+ );
579+ await waitForRender();
580+
581+ term.sendInput("x");
582+ await waitForRender();
583+
584+ // mid returns false, so key continues to root
585+ expect(received).toEqual(["mid:x", "root:x"]);
586+ });
587+
588+ test("selective bubbling — consume some keys, pass others", async () => {
589+ const term = setup(20, 5);
590+ const received: string[] = [];
591+
592+ cel.viewport(() =>
593+ VStack(
594+ {
595+ width: 20,
596+ height: 5,
597+ onKeyPress: (key) => {
598+ received.push("root:" + key);
599+ },
600+ },
601+ [
602+ VStack(
603+ {
604+ onKeyPress: (key) => {
605+ received.push("mid:" + key);
606+ // Consume "a" but pass through everything else
607+ if (key === "a") return; // consumed
608+ return false; // not consumed
609+ },
610+ },
611+ [
612+ HStack(
613+ {
614+ onClick: () => {},
615+ focused: true,
616+ },
617+ [Text("Focused Btn")],
618+ ),
619+ ],
620+ ),
621+ ],
622+ ),
623+ );
624+ await waitForRender();
625+
626+ term.sendInput("a");
627+ await waitForRender();
628+ expect(received).toEqual(["mid:a"]); // consumed by mid
629+
630+ received.length = 0;
631+ term.sendInput("b");
632+ await waitForRender();
633+ expect(received).toEqual(["mid:b", "root:b"]); // passed through to root
634+ });
635+
636+ test("all handlers return false — every handler in chain is called", async () => {
637+ const term = setup(20, 5);
638+ const received: string[] = [];
639+
640+ cel.viewport(() =>
641+ VStack(
642+ {
643+ width: 20,
644+ height: 5,
645+ onKeyPress: (key) => {
646+ received.push("root:" + key);
647+ return false;
648+ },
649+ },
650+ [
651+ VStack(
652+ {
653+ onKeyPress: (key) => {
654+ received.push("mid:" + key);
655+ return false;
656+ },
657+ },
658+ [
659+ HStack(
660+ {
661+ onClick: () => {},
662+ focused: true,
663+ },
664+ [Text("Focused Btn")],
665+ ),
666+ ],
667+ ),
668+ ],
669+ ),
670+ );
671+ await waitForRender();
672+
673+ term.sendInput("x");
674+ await waitForRender();
675+
676+ expect(received).toEqual(["mid:x", "root:x"]);
677+ });
678+
545679 test("key reaches root onKeyPress when no intermediate handlers", async () => {
546680 const term = setup(20, 5);
547681 let rootKey = "";
@@ -606,7 +740,7 @@ describe("cel end-to-end", () => {
606740 expect(parentKey).toBe("ctrl+s");
607741 });
608742
609- test("unfocused state bubbles from root only", async () => {
743+ test("unfocused state routes key to root handler", async () => {
610744 const term = setup(20, 5);
611745 let rootKey = "";
612746
packages/core/src/cel.ts+22−9
@@ -5,7 +5,7 @@ import {
55 hitTest,
66 findClickHandler,
77 findScrollTarget,
8- findKeyPressHandler,
8+ collectKeyPressHandlers,
99 collectFocusable,
1010 } from "./hit-test.js";
1111 import { parseKey, isEditingKey, normalizeKey } from "./keys.js";
@@ -577,11 +577,21 @@ function handleKeyEvent(key: string, rawData?: string): void {
577577 for (let i = currentLayouts.length - 1; i >= 0; i--) {
578578 const path = findPathTo(currentLayouts[i]!, focused);
579579 if (path) {
580- const handler = findKeyPressHandler(path);
581- if (handler) {
582- handler.handler(key);
583- cel.render();
584- return;
580+ const handlers = collectKeyPressHandlers(path);
581+ if (handlers.length > 0) {
582+ let consumed = false;
583+ for (const h of handlers) {
584+ const result = h.handler(key);
585+ if (result !== false) {
586+ consumed = true;
587+ break;
588+ }
589+ // result === false → key not consumed, keep bubbling
590+ }
591+ if (consumed || handlers.length > 0) {
592+ cel.render();
593+ return;
594+ }
585595 }
586596 }
587597 }
@@ -591,9 +601,12 @@ function handleKeyEvent(key: string, rawData?: string): void {
591601 for (let i = currentLayouts.length - 1; i >= 0; i--) {
592602 const layoutRoot = currentLayouts[i]!;
593603 const path = [layoutRoot];
594- const handler = findKeyPressHandler(path);
595- if (handler) {
596- handler.handler(key);
604+ const handlers = collectKeyPressHandlers(path);
605+ if (handlers.length > 0) {
606+ for (const h of handlers) {
607+ const result = h.handler(key);
608+ if (result !== false) break;
609+ }
597610 cel.render();
598611 return;
599612 }
packages/core/src/hit-test.test.ts+22−8
@@ -4,7 +4,7 @@ import {
44 hitTest,
55 findClickHandler,
66 findScrollTarget,
7- findKeyPressHandler,
7+ collectKeyPressHandlers,
88 collectFocusable,
99 } from "./hit-test.js";
1010 import { VStack, HStack } from "./primitives/stacks.js";
@@ -130,24 +130,38 @@ describe("findScrollTarget", () => {
130130 });
131131 });
132132
133-describe("findKeyPressHandler", () => {
134- test("finds nearest ancestor with onKeyPress", () => {
133+describe("collectKeyPressHandlers", () => {
134+ test("collects handlers from deepest to root", () => {
135+ const rootHandler = (_key: string) => {};
136+ const midHandler = (_key: string) => {};
137+ const node = VStack({ width: 20, height: 10, onKeyPress: rootHandler }, [
138+ VStack({ onKeyPress: midHandler }, [Text("hello")]),
139+ ]);
140+ const ln = layout(node, 20, 10);
141+ const path = hitTest(ln, 3, 0);
142+ const handlers = collectKeyPressHandlers(path);
143+ expect(handlers).toHaveLength(2);
144+ expect(handlers[0]!.handler).toBe(midHandler);
145+ expect(handlers[1]!.handler).toBe(rootHandler);
146+ });
147+
148+ test("returns single handler when only root has onKeyPress", () => {
135149 const handler = (_key: string) => {};
136150 const node = VStack({ width: 20, height: 10, onKeyPress: handler }, [
137151 Text("hello"),
138152 ]);
139153 const ln = layout(node, 20, 10);
140154 const path = hitTest(ln, 3, 0);
141- const result = findKeyPressHandler(path);
142- expect(result).not.toBeNull();
143- expect(result!.handler).toBe(handler);
155+ const handlers = collectKeyPressHandlers(path);
156+ expect(handlers).toHaveLength(1);
157+ expect(handlers[0]!.handler).toBe(handler);
144158 });
145159
146- test("returns null when no onKeyPress in path", () => {
160+ test("returns empty array when no onKeyPress in path", () => {
147161 const node = VStack({ width: 20, height: 10 }, [Text("hello")]);
148162 const ln = layout(node, 20, 10);
149163 const path = hitTest(ln, 3, 0);
150- expect(findKeyPressHandler(path)).toBeNull();
164+ expect(collectKeyPressHandlers(path)).toEqual([]);
151165 });
152166 });
153167
packages/core/src/hit-test.ts+11−7
@@ -95,22 +95,26 @@ export function findScrollTarget(path: LayoutNode[]): LayoutNode | null {
9595 }
9696
9797 /**
98- * Find the nearest ancestor with an `onKeyPress` handler.
99- * Walks from deepest to root (bubbling).
98+ * Collect all `onKeyPress` handlers along a path, ordered innermost-first
99+ * (deepest to root) for bubbling dispatch.
100100 *
101101 * @param path - Path from root to current node.
102- * @returns The handler and its layout node, or null.
102+ * @returns Array of handlers ordered from deepest to root.
103103 */
104-export function findKeyPressHandler(
104+export function collectKeyPressHandlers(
105105 path: LayoutNode[],
106-): { layoutNode: LayoutNode; handler: (key: string) => void } | null {
106+): { layoutNode: LayoutNode; handler: (key: string) => boolean | void }[] {
107+ const handlers: {
108+ layoutNode: LayoutNode;
109+ handler: (key: string) => boolean | void;
110+ }[] = [];
107111 for (let i = path.length - 1; i >= 0; i--) {
108112 const props = getProps(path[i]!);
109113 if (props?.onKeyPress) {
110- return { layoutNode: path[i]!, handler: props.onKeyPress };
114+ handlers.push({ layoutNode: path[i]!, handler: props.onKeyPress });
111115 }
112116 }
113- return null;
117+ return handlers;
114118 }
115119
116120 /**
packages/types/src/index.ts+8−1
@@ -198,12 +198,19 @@ export interface ContainerProps extends StyleProps {
198198 * (e.g., modifier combos like `"ctrl+s"`) bubble up through ancestors.
199199 * The root container's `onKeyPress` acts as the global key handler.
200200 *
201+ * Return `false` to indicate the key was **not consumed** — it will
202+ * continue bubbling to the next ancestor handler. Any other return
203+ * value (`undefined`, `true`, or no return) means the key was consumed
204+ * and bubbling stops. This is backward-compatible: existing `void`
205+ * handlers consume by default.
206+ *
201207 * Key format: all lowercase, modifiers joined by `+` in canonical
202208 * order `ctrl+alt+shift+<key>` (e.g., `"ctrl+s"`, `"alt+up"`, `"escape"`).
203209 *
204210 * @param key - Normalized key string.
211+ * @returns `false` to keep bubbling, anything else to consume.
205212 */
206- onKeyPress?: (key: string) => void;
213+ onKeyPress?: (key: string) => boolean | void;
207214 }
208215
209216 /**
spec.md+27−26
@@ -64,30 +64,30 @@ HStack(props, children);
6464
6565 Shared by both VStack and HStack. Containers also accept styling props (see [Styling](#styling)).
6666
67-| Prop | Type | Description |
68-| ---------------- | ---------------------------- | ----------------------------------------------- |
69-| `width` | `number \| string` | Fixed cells or percentage (`"50%"`) |
70-| `height` | `number \| string` | Fixed cells or percentage (`"100%"`) |
71-| `flex` | `number` | Flex grow factor, proportional to siblings |
72-| `minWidth` | `number` | Minimum width constraint |
73-| `maxWidth` | `number` | Maximum width constraint |
74-| `minHeight` | `number` | Minimum height constraint |
75-| `maxHeight` | `number` | Maximum height constraint |
76-| `padding` | `{ x?: number, y?: number }` | Internal padding (cells) |
77-| `gap` | `number` | Spacing between children (cells) |
78-| `justifyContent` | `string` | Distribute children along the main axis |
79-| `alignItems` | `string` | Align children along the cross axis |
80-| `overflow` | `"hidden" \| "scroll"` | Content overflow behavior (default: `"hidden"`) |
81-| `scrollbar` | `boolean` | Show scrollbar indicator |
82-| `scrollOffset` | `number` | Scroll position in cells (controlled) |
83-| `onScroll` | `(offset: number) => void` | Called on scroll input |
84-| `onClick` | `() => void` | Called on mouse click or Enter when focused |
85-| `focusable` | `boolean` | Opt out of focus (default: `true` if `onClick`) |
86-| `focused` | `boolean` | Whether this element is focused (controlled) |
87-| `onFocus` | `() => void` | Called when element receives focus |
88-| `onBlur` | `() => void` | Called when element loses focus |
89-| `focusStyle` | `StyleProps` | Style overrides applied when focused |
90-| `onKeyPress` | `(key: string) => void` | Called on key event (bubbles up from focus) |
67+| Prop | Type | Description |
68+| ---------------- | ---------------------------------- | --------------------------------------------------- |
69+| `width` | `number \| string` | Fixed cells or percentage (`"50%"`) |
70+| `height` | `number \| string` | Fixed cells or percentage (`"100%"`) |
71+| `flex` | `number` | Flex grow factor, proportional to siblings |
72+| `minWidth` | `number` | Minimum width constraint |
73+| `maxWidth` | `number` | Maximum width constraint |
74+| `minHeight` | `number` | Minimum height constraint |
75+| `maxHeight` | `number` | Maximum height constraint |
76+| `padding` | `{ x?: number, y?: number }` | Internal padding (cells) |
77+| `gap` | `number` | Spacing between children (cells) |
78+| `justifyContent` | `string` | Distribute children along the main axis |
79+| `alignItems` | `string` | Align children along the cross axis |
80+| `overflow` | `"hidden" \| "scroll"` | Content overflow behavior (default: `"hidden"`) |
81+| `scrollbar` | `boolean` | Show scrollbar indicator |
82+| `scrollOffset` | `number` | Scroll position in cells (controlled) |
83+| `onScroll` | `(offset: number) => void` | Called on scroll input |
84+| `onClick` | `() => void` | Called on mouse click or Enter when focused |
85+| `focusable` | `boolean` | Opt out of focus (default: `true` if `onClick`) |
86+| `focused` | `boolean` | Whether this element is focused (controlled) |
87+| `onFocus` | `() => void` | Called when element receives focus |
88+| `onBlur` | `() => void` | Called when element loses focus |
89+| `focusStyle` | `StyleProps` | Style overrides applied when focused |
90+| `onKeyPress` | `(key: string) => boolean \| void` | Key event handler. Return `false` to keep bubbling. |
9191
9292 ### Sizing
9393
@@ -317,8 +317,9 @@ Key events are routed through the focus and layer system, then bubble up the tre
317317 1. **Topmost layer** receives the key event
318318 2. If a **TextInput** is focused, it consumes text-editing keys (printable characters, arrows, backspace, Tab). Modifier combos pass through.
319319 3. If a **clickable container** is focused, Enter fires `onClick`. Other keys pass through.
320-4. Unconsumed keys **bubble up** through ancestors — the nearest `onKeyPress` handler in the ancestor chain handles it.
321-5. The root container's `onKeyPress` acts as the global key handler.
320+4. Unconsumed keys **bubble up** through ancestors — each `onKeyPress` handler in the ancestor chain is called from innermost to root.
321+5. A handler that returns `false` signals the key was **not consumed** — bubbling continues to the next ancestor. Any other return (`undefined`, `true`, or no return) **stops bubbling** (backward-compatible: existing `void` handlers consume by default).
322+6. The root container's `onKeyPress` acts as the global key handler — it receives keys that bubble all the way up.
322323
323324 ### Key Format