xonecas.io
70160
Ce

cel-tui / commit 12bff6c

fix(core): let escape bubble before blur

xonecas2026-04-11 12bff6c39caf8f9ba7cc0c694c57040a0aebc08b parent 43a6f24

5 files changed

AGENTS.md+2−2
@@ -29,7 +29,7 @@ Dependency chain: `components → core → types`
2929 - **Cell buffer rendering:** Layout writes to a 2D grid of styled cells, not raw strings. Clipping and layer compositing are cell writes. Diff against previous buffer for minimal terminal output.
3030 - **Reactive rendering:** `cel.render()` batches via `process.nextTick()`. No fixed FPS.
3131 - **Layers:** `cel.viewport(() => [layer1, layer2])` — array of independent viewport-sized trees, composited bottom-to-top. Conditional inclusion = show/hide.
32-- **Key bubbling:** Unconsumed keys bubble up from focused element through ancestors. Root `onKeyPress` = global handler.
32+- **Key bubbling:** Unconsumed keys bubble up from focused element through ancestors. Root `onKeyPress` = global handler. Escape blur is a fallback default action after bubbling — consuming `escape` prevents blur.
3333 - **Hit detection:** Topmost layer first, deepest node at (x,y), walk up to find handler. Innermost wins for scroll, click, keys.
3434
3535 ## Implementation Status
@@ -216,7 +216,7 @@ chore: scaffold monorepo with types, core, components packages
216216
217217 ## Architecture Notes
218218
219-- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Input handling treats stdin as a mixed stream: keyboard chunks may contain multiple decoded key events, mouse input handles batched SGR events, and TextInput batching preserves the latest value/cursor across m …
219+- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Input handling treats stdin as a mixed stream: keyboard chunks may contain multiple decoded key events, mouse input handles batched SGR events, and TextInput batching preserves the latest value/cursor across m …
220220 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
221221 - `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets (clamped to max — apps can pass `Infinity` to mean "scroll to end"), scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state (with cursor screen position export for native cursor), TextInput background fill, container bgColor fill, style inheritance threading, focusStyle resolution.
222222 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both accept an optional `Theme` for color resolution and wrap in CSI 2026 synchronized output. Exports `defaultTheme` (ANSI 16 mapping).
TODO.md+1−1
@@ -12,7 +12,7 @@ Remaining work, known bugs, and planned improvements.
1212
1313 ## API Improvements
1414
15-- ❌ **Focus callbacks need reason metadata** — `onFocus`/`onBlur` currently expose only that focus changed, not why. Controlled-focus apps can't distinguish blur caused by `Escape` from blur caused by Tab traversal, mouse clicks, overlay changes, or other focus transitions, which forces awkward workarounds for behaviors like "Escape blurs first, second Escape triggers a global action".
15+- ❌ **Focus callbacks need reason metadata** — `onFocus`/`onBlur` currently expose only that focus changed, not why. Controlled-focus apps can't distinguish blur caused by `Escape` from blur caused by Tab traversal, mouse clicks, overlay changes, or other focus transitions, which still makes blur-specific behavior awkward.
1616
1717 - ❌ **Define TextInput scroll semantics for cursor-follow and resize** — After the text layout refactor, the framework now has one canonical visual wrapping model, but the behavior contract around TextInput scrolling still needs to be specified. In particular: when a user has manually scrolled away from the cursor, what actions should re-enable automatic cursor-follow (typing, cursor movement, focus changes, programmatic value changes)? And when a TextInput changes height because of intrinsi …
1818
packages/core/src/cel.test.ts+126−0
@@ -941,6 +941,87 @@ describe("cel end-to-end", () => {
941941 expect(received).toEqual(["mid:x", "root:x"]);
942942 });
943943
944+ test("ancestor onKeyPress can consume Escape before blur", async () => {
945+ const term = setup(20, 5);
946+ const received: string[] = [];
947+ let btnFocused = true;
948+ let blurred = false;
949+
950+ cel.viewport(() =>
951+ VStack(
952+ {
953+ width: 20,
954+ height: 5,
955+ onKeyPress: (key) => {
956+ received.push(key);
957+ },
958+ },
959+ [
960+ HStack(
961+ {
962+ onClick: () => {},
963+ focused: btnFocused,
964+ onBlur: () => {
965+ blurred = true;
966+ btnFocused = false;
967+ },
968+ },
969+ [Text("Btn")],
970+ ),
971+ ],
972+ ),
973+ );
974+ await waitForRender();
975+
976+ term.sendInput(ESCAPE);
977+ await waitForRender();
978+
979+ expect(received).toEqual(["escape"]);
980+ expect(blurred).toBe(false);
981+ expect(btnFocused).toBe(true);
982+ });
983+
984+ test("Escape blurs after bubbling when ancestor handlers return false", async () => {
985+ const term = setup(20, 5);
986+ const received: string[] = [];
987+ let btnFocused = true;
988+ let blurred = false;
989+
990+ cel.viewport(() =>
991+ VStack(
992+ {
993+ width: 20,
994+ height: 5,
995+ onKeyPress: (key) => {
996+ received.push(key);
997+ return false;
998+ },
999+ },
1000+ [
1001+ HStack(
1002+ {
1003+ onClick: () => {},
1004+ focused: btnFocused,
1005+ onBlur: () => {
1006+ blurred = true;
1007+ btnFocused = false;
1008+ },
1009+ },
1010+ [Text("Btn")],
1011+ ),
1012+ ],
1013+ ),
1014+ );
1015+ await waitForRender();
1016+
1017+ term.sendInput(ESCAPE);
1018+ await waitForRender();
1019+
1020+ expect(received).toEqual(["escape"]);
1021+ expect(blurred).toBe(true);
1022+ expect(btnFocused).toBe(false);
1023+ });
1024+
9441025 test("key reaches root onKeyPress when no intermediate handlers", async () => {
9451026 const term = setup(20, 5);
9461027 let rootKey = "";
@@ -1005,6 +1086,51 @@ describe("cel end-to-end", () => {
10051086 expect(parentKey).toBe("ctrl+s");
10061087 });
10071088
1089+ test("TextInput onKeyPress returning false prevents Escape blur", async () => {
1090+ const term = setup(20, 5);
1091+ let parentKey = "";
1092+ let inputKey = "";
1093+ let inputValue = "hello";
1094+ let inputFocused = true;
1095+
1096+ cel.viewport(() =>
1097+ VStack(
1098+ {
1099+ width: 20,
1100+ height: 5,
1101+ onKeyPress: (key) => {
1102+ parentKey = key;
1103+ },
1104+ },
1105+ [
1106+ TextInput({
1107+ value: inputValue,
1108+ onChange: (v) => {
1109+ inputValue = v;
1110+ },
1111+ focused: inputFocused,
1112+ onBlur: () => {
1113+ inputFocused = false;
1114+ },
1115+ onKeyPress: (key) => {
1116+ inputKey = key;
1117+ if (key === "escape") return false;
1118+ },
1119+ }),
1120+ ],
1121+ ),
1122+ );
1123+ await waitForRender();
1124+
1125+ term.sendInput(ESCAPE);
1126+ await waitForRender();
1127+
1128+ expect(inputKey).toBe("escape");
1129+ expect(parentKey).toBe("");
1130+ expect(inputFocused).toBe(true);
1131+ expect(inputValue).toBe("hello");
1132+ });
1133+
10081134 test("unfocused state routes key to root handler", async () => {
10091135 const term = setup(20, 5);
10101136 let rootKey = "";
packages/core/src/cel.ts+37−19
@@ -822,6 +822,15 @@ function handleBracketedPaste(text: string): void {
822822 commitTextInputEdit(props, editState, nextState);
823823 }
824824
825+function blurFocusedElement(): boolean {
826+ const current = findFocusedElement();
827+ if (!current) return false;
828+
829+ changeFocus(null);
830+ cel.render();
831+ return true;
832+}
833+
825834 function handleKeyEvent(event: KeyInput): void {
826835 const { key, text } = event;
827836
@@ -874,16 +883,6 @@ function handleKeyEvent(event: KeyInput): void {
874883 } // end: not a focused TextInput
875884 }
876885
877- // Escape: unfocus current element
878- if (key === "escape") {
879- const current = findFocusedElement();
880- if (current) {
881- changeFocus(null);
882- cel.render();
883- return;
884- }
885- }
886-
887886 // Enter: activate focused clickable container
888887 if (key === "enter") {
889888 const current = findFocusedElement();
@@ -1016,25 +1015,44 @@ function handleKeyEvent(event: KeyInput): void {
10161015 }
10171016 // Always return — the key was offered to every handler in the
10181017 // focused element's path (including root). Even if all returned
1019- // false, we don't retry via the unfocused fallback path.
1020- if (consumed) cel.render();
1018+ // false, we don't retry via the top-layer fallback path.
1019+ if (consumed) {
1020+ cel.render();
1021+ return;
1022+ }
1023+ if (key === "escape" && blurFocusedElement()) return;
10211024 return;
10221025 }
10231026 }
10241027 }
10251028 }
10261029
1027- // No focused element — only the topmost layer's root can receive the key.
1030+ // Fallback: offer the key to the topmost layer's root when it was not
1031+ // already handled on the focused path.
10281032 const topLayer = currentLayouts[currentLayouts.length - 1];
1029- if (!topLayer) return;
1033+ if (!topLayer) {
1034+ if (key === "escape") blurFocusedElement();
1035+ return;
1036+ }
10301037
10311038 const handlers = collectKeyPressHandlers([topLayer]);
1032- if (handlers.length === 0) return;
1033-
1034- for (const h of handlers) {
1035- const result = h.handler(key);
1036- if (result !== false) break;
1039+ if (handlers.length > 0) {
1040+ let consumed = false;
1041+ for (const h of handlers) {
1042+ const result = h.handler(key);
1043+ if (result !== false) {
1044+ consumed = true;
1045+ break;
1046+ }
1047+ }
1048+ if (consumed) {
1049+ cel.render();
1050+ return;
1051+ }
10371052 }
1053+
1054+ if (key === "escape" && blurFocusedElement()) return;
1055+ if (handlers.length === 0) return;
10381056 cel.render();
10391057 }
10401058
spec.md+10−9
@@ -359,9 +359,9 @@ Focus is implicit — no `focusable` prop needed for the common case:
359359
360360 ### Traversal
361361
362-**Escape** unfocuses the current element. **Tab / Shift+Tab** moves focus to the next/previous focusable element in document order (depth-first tree traversal).
362+**Escape** behaves like a normal key first: it bubbles through `onKeyPress` handlers, and if it remains unconsumed the framework unfocuses the current element. **Tab / Shift+Tab** moves focus to the next/previous focusable element in document order (depth-first tree traversal).
363363
364-When a TextInput is focused, insertable text and text-editing keys go to the input. This includes arrows, backspace, delete, Enter, Tab, plus readline-style shortcuts: `ctrl+a` / `ctrl+e` for start/end, `alt+b` / `alt+f` and `ctrl+left` / `ctrl+right` for whitespace-delimited word movement, and `ctrl+w` / `alt+d` for whitespace-delimited word deletion. `up` and `down` follow the input's visual wrapped lines, not just newline-separated hard lines. Other modifier combos (e.g., `ctrl+s`) are not co …
364+When a TextInput is focused, insertable text and text-editing keys go to the input. This includes arrows, backspace, delete, Enter, Tab, plus readline-style shortcuts: `ctrl+a` / `ctrl+e` for start/end, `alt+b` / `alt+f` and `ctrl+left` / `ctrl+right` for whitespace-delimited word movement, and `ctrl+w` / `alt+d` for whitespace-delimited word deletion. `up` and `down` follow the input's visual wrapped lines, not just newline-separated hard lines. Other modifier combos (e.g., `ctrl+s`) are not co …
365365
366366 ### Uncontrolled Focus
367367
@@ -481,12 +481,13 @@ cel-tui enables bracketed paste mode so the terminal wraps pasted content with `
481481
482482 1. **Topmost layer** receives the key event
483483 2. If a **TextInput** is focused:
484- - If the TextInput has `onKeyPress`, call it first. If `onKeyPress` returns `false`, the key's **default editing action is prevented** — no character insertion, no cursor movement, nothing. The key is consumed.
484+ - If the TextInput has `onKeyPress`, call it first. If `onKeyPress` returns `false`, the key's **default TextInput action** is prevented — no character insertion, no cursor movement, and no Escape blur. The key is consumed.
485485 - Otherwise, the TextInput processes insertable text, editing/navigation keys (arrows, backspace, delete, Enter, Tab), and these modifier-based editing shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and deletion use whitespace-delimited boundaries, and `up` / `down` navigate visual wrapped lines. Other modifier combos (e.g., `ctrl+s`) and non-insertable control keys are not editing keys and pass through.
486486 3. If a **clickable container** is focused, Enter fires `onClick`. Other keys pass through.
487487 4. Unconsumed keys **bubble up** through ancestors — each `onKeyPress` handler in the ancestor chain is called from innermost to root.
488488 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).
489489 6. The root container's `onKeyPress` acts as the global key handler — it receives keys that bubble all the way up.
490+7. After bubbling, framework default actions run for still-unconsumed keys. Today that means: if `escape` is still unconsumed and an element is focused, the framework blurs it.
490491
491492 ### Key Format
492493
@@ -643,12 +644,12 @@ TextInput(props: TextInputProps)
643644
644645 Container sizing props (`width`, `height`, `flex`, `min*`, `max*`, `padding`), focus props (`focused`, `onFocus`, `onBlur`, `focusStyle`), styling props, wheel scroll prop (`scrollStep`), and:
645646
646-| Prop | Type | Description |
647-| ------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
648-| `value` | `string` | Current text content (controlled) |
649-| `onChange` | `(value: string) => void` | Called on text change |
650-| `onKeyPress` | `(key: string) => boolean \| void` | Key handler, fires before editing. Receives normalized semantic key strings. Return `false` to prevent the default editing action. |
651-| `placeholder` | `TextNode` | Text node shown when value is empty (pass a `Text()` call) |
647+| Prop | Type | Description |
648+| ------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
649+| `value` | `string` | Current text content (controlled) |
650+| `onChange` | `(value: string) => void` | Called on text change |
651+| `onKeyPress` | `(key: string) => boolean \| void` | Key handler, fires before editing. Receives normalized semantic key strings. Return `false` to prevent the default TextInput action for that key. |
652+| `placeholder` | `TextNode` | Text node shown when value is empty (pass a `Text()` call) |
652653
653654 Word-wrap is always on. Cursor position is framework-managed. Supported editing shortcuts include `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`; word movement and deletion use whitespace-delimited boundaries, and `up` / `down` navigate visual wrapped lines. In bracketed paste mode, pasted text is inserted literally at the cursor as one batch edit: one `onChange`, no `onKeyPress`, newlines and tabs preserved.