xonecas.io
70160
Ce

cel-tui / commit 98d11da

feat(core): replace onSubmit/submitKey with onKeyPress on TextInput

TextInput now accepts onKeyPress, which fires before built-in editing
logic. Returning false prevents the default editing action for that key
(e.g., intercept Enter to submit instead of inserting a newline).

This removes onSubmit and submitKey entirely — key interception uses
the same onKeyPress pattern as containers, with no new concepts to learn.
Enter inserts a newline by default (TextInput is naturally multi-line).

- Add onKeyPress to TextInputProps, remove onSubmit/submitKey
- Pre-editing hook in cel.ts: onKeyPress called before editing logic
- Exclude TextInput onKeyPress from ancestor bubbling (no double-call)
- Replace 2 old tests with 6 new onKeyPress tests
- Update spec, examples, docs, skill, AGENTS.md, TODO.md

xonecas2026-04-05 98d11dad2c62baa5277b1621e4f2166a454e395b parent 2acfe11

13 files changed

AGENTS.md+1−1
@@ -203,7 +203,7 @@ chore: scaffold monorepo with types, core, components packages
203203
204204 ## Architecture Notes
205205
206-- `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. Mouse input handles batched SGR events (terminals often send multiple events in a single data chunk).
206+- `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. Mouse input handles batched SGR events (terminals often send multiple events in a single data chunk). TextInput key handling: `onKeyPress` fires before built-in editing logic — returning `false` prevents the …
207207 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
208208 - `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.
209209 - `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
@@ -42,7 +42,7 @@ Remaining work, known bugs, and planned improvements.
4242
4343 - 💡 **Scrollbar styling** — Scrollbar characters (`┃`/`│` vertical, `━`/`─` horizontal) and colors are hardcoded in `paintScrollbar`. A `scrollbarStyle` prop on containers (or a global theme option) would allow customizing thumb/track characters and colors. Currently the only two visual elements the framework doesn't support styling.
4444
45-- 💡 **Textarea component** (`packages/components`) — A higher-level wrapper around TextInput that handles the autogrowing pattern out of the box. Props like `maxLines`, `minLines`, `submitKey`, and `placeholder` would cover the common chat-input / form-field use case without requiring the `HStack + flex + maxHeight` boilerplate. Could also include optional line-count display and character limit.
45+- 💡 **Textarea component** (`packages/components`) — A higher-level wrapper around TextInput that handles the autogrowing pattern out of the box. Props like `maxLines`, `minLines`, and `placeholder` would cover the common chat-input / form-field use case without requiring the `HStack + flex + maxHeight` boilerplate. Could also include optional line-count display and character limit.
4646
4747 - 💡 **Editor component** (`packages/components`) — A TextInput with a line-number gutter, built as a component. Would compose an HStack with a fixed-width line-number column (styled, right-aligned) alongside a flex TextInput, keeping scroll synchronized. Useful for code/config editing use cases like the markdown editor example.
4848
docs/skill/cel-tui/SKILL.md+1−1
@@ -214,7 +214,7 @@ mySelect.reset(); // clear filter/highlight programmatically
214214
215215 - **State is external** — the framework has no state. Mutate variables then call `cel.render()`.
216216 - **Text is a pure leaf** — no sizing props, no children. Parent controls the box.
217-- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace). Modifier combos (`ctrl+s`) bubble up through ancestors via `onKeyPress`.
217+- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace, Enter, Tab). Enter inserts a newline by default. Use `onKeyPress` on TextInput to intercept keys before editing — return `false` to prevent the default action (e.g., intercept Enter for submit). Modifier combos (`ctrl+s`) are not editing keys and bubble up through ancestors via `onKeyPress`.
218218 - **Escape unfocuses** the current element. Tab/Shift+Tab traverses focusable elements (wraps around). After Escape, traversal continues from where focus was lost.
219219 - **Enter activates** a focused container's `onClick`. If no `onClick`, Enter reaches `onKeyPress`.
220220 - **`focusable: true`** without `onClick` makes a container keyboard-focusable (receives `onKeyPress` events via Tab). Used by stateful components like `Select`.
docs/skill/cel-tui/references/api.md+17−2
@@ -85,13 +85,28 @@ Colors: 16 numbered palette slots — `"color00"` through `"color15"`. Mapped to
8585 TextInput({
8686 value, // string (controlled)
8787 onChange, // (value: string) => void
88- onSubmit, // () => void
89- submitKey, // string (default "enter")
88+ onKeyPress, // (key: string) => boolean | void — return false to prevent default editing action
9089 placeholder, // Text() node shown when empty
9190 // + all container props (sizing, styling, focus, etc.)
9291 });
9392 ```
9493
94+Enter inserts a newline by default. Use `onKeyPress` to intercept keys before editing:
95+
96+```ts
97+// Enter submits instead of inserting newline
98+TextInput({
99+ value: input,
100+ onChange: handleChange,
101+ onKeyPress: (key) => {
102+ if (key === "enter") {
103+ handleSend();
104+ return false;
105+ }
106+ },
107+});
108+```
109+
95110 ## Sizing Strategies
96111
97112 Containers accept 4 sizing strategies:
examples/chat.ts+6−1
@@ -280,7 +280,12 @@ cel.viewport(() =>
280280 value: input,
281281 onChange: handleChange,
282282 placeholder: Text("type a message...", { fgColor: "color08" }),
283- onSubmit: handleSend,
283+ onKeyPress: (key) => {
284+ if (key === "enter") {
285+ handleSend();
286+ return false;
287+ }
288+ },
284289 focused: inputFocused,
285290 onFocus: () => {
286291 inputFocused = true;
examples/markdown-editor.ts+1−1
@@ -3,7 +3,7 @@
33 *
44 * A split-pane markdown editor with live preview, showcasing:
55 * - Custom color theme (Catppuccin Mocha via true color)
6- * - Large multi-line TextInput with ctrl+enter submit
6+ * - Large multi-line TextInput editor
77 * - Live Markdown rendering (source ↔ preview)
88 * - Split-pane layout with VDivider
99 * - Scrollable preview pane
examples/pet.ts+6−4
@@ -484,10 +484,12 @@ function createView() {
484484 nameInputFocused = false;
485485 cel.render();
486486 },
487- submitKey: "enter",
488- onSubmit: () => {
489- nameInputFocused = false;
490- cel.render();
487+ onKeyPress: (key) => {
488+ if (key === "enter") {
489+ nameInputFocused = false;
490+ cel.render();
491+ return false;
492+ }
491493 },
492494 }),
493495
packages/core/src/cel.test.ts+7−5
@@ -1006,7 +1006,7 @@ describe("cel end-to-end", () => {
10061006 expect(value).toBe("he\nllo");
10071007 });
10081008
1009- test("Shift+Enter does not trigger submitKey", async () => {
1009+ test("Shift+Enter inserts newline even when onKeyPress intercepts Enter", async () => {
10101010 const term = setup(20, 5);
10111011 let value = "hello";
10121012 let submitted = false;
@@ -1018,16 +1018,18 @@ describe("cel end-to-end", () => {
10181018 onChange: (v) => {
10191019 value = v;
10201020 },
1021- onSubmit: () => {
1022- submitted = true;
1021+ onKeyPress: (key) => {
1022+ if (key === "enter") {
1023+ submitted = true;
1024+ return false;
1025+ }
10231026 },
1024- // default submitKey is "enter"
10251027 }),
10261028 ]),
10271029 );
10281030 await waitForRender();
10291031
1030- // Shift+Enter should insert newline, NOT submit
1032+ // Shift+Enter is a different key — should insert newline, not trigger onKeyPress for "enter"
10311033 term.sendInput(kittyEncode("shift+enter"));
10321034 await waitForRender();
10331035 expect(submitted).toBe(false);
packages/core/src/cel.ts+18−8
@@ -8,7 +8,7 @@ import {
88 collectKeyPressHandlers,
99 collectFocusable,
1010 } from "./hit-test.js";
11-import { parseKey, isEditingKey, normalizeKey } from "./keys.js";
11+import { parseKey, isEditingKey } from "./keys.js";
1212 import { layout, type LayoutNode } from "./layout.js";
1313 import {
1414 paint,
@@ -689,12 +689,13 @@ function handleKeyEvent(key: string, rawData?: string): void {
689689 const props = focusedInput.node
690690 .props as import("@cel-tui/types").TextInputProps;
691691
692- // Check submitKey
693- const submitKey = normalizeKey(props.submitKey ?? "enter");
694- if (key === submitKey && props.onSubmit) {
695- props.onSubmit();
696- cel.render();
697- return;
692+ // onKeyPress fires before editing — return false prevents the default action
693+ if (props.onKeyPress) {
694+ const result = props.onKeyPress(key);
695+ if (result === false) {
696+ cel.render();
697+ return;
698+ }
698699 }
699700
700701 // Editing keys are consumed by TextInput
@@ -771,7 +772,16 @@ function handleKeyEvent(key: string, rawData?: string): void {
771772 for (let i = currentLayouts.length - 1; i >= 0; i--) {
772773 const path = findPathTo(currentLayouts[i]!, focused);
773774 if (path) {
774- const handlers = collectKeyPressHandlers(path);
775+ let handlers = collectKeyPressHandlers(path);
776+ // If a TextInput's onKeyPress was already called in the pre-editing
777+ // hook above, exclude it from bubbling to avoid calling it twice.
778+ if (
779+ focusedInput &&
780+ handlers.length > 0 &&
781+ handlers[0]!.layoutNode === focusedInput
782+ ) {
783+ handlers = handlers.slice(1);
784+ }
775785 if (handlers.length > 0) {
776786 let consumed = false;
777787 for (const h of handlers) {
packages/core/src/primitives/text-input.ts+8−4
@@ -12,9 +12,12 @@ import type { TextInputNode, TextInputProps } from "@cel-tui/types";
1212 * responds to mouse wheel automatically.
1313 *
1414 * TextInput is always focusable. When focused, text-editing keys
15- * (printable characters, arrows, backspace, Tab) are consumed.
15+ * (printable characters, arrows, backspace, Enter, Tab) are consumed.
1616 * Modifier combos (e.g., `ctrl+s`) bubble up to ancestor `onKeyPress` handlers.
1717 *
18+ * Use `onKeyPress` to intercept keys before editing. Return `false` to
19+ * prevent the default editing action for that key.
20+ *
1821 * @param props - Value, callbacks, sizing, styling, and focus props.
1922 * @returns A text input node for the UI tree.
2023 *
@@ -26,14 +29,15 @@ import type { TextInputNode, TextInputProps } from "@cel-tui/types";
2629 * })
2730 *
2831 * @example
29- * // Growing input with max height
32+ * // Growing input with max height, Enter submits
3033 * TextInput({
3134 * flex: 1,
3235 * maxHeight: 10,
3336 * value: text,
3437 * onChange: handleChange,
35- * onSubmit: handleSend,
36- * submitKey: "ctrl+enter",
38+ * onKeyPress: (key) => {
39+ * if (key === "enter") { handleSend(); return false; }
40+ * },
3741 * placeholder: Text("type a message...", { fgColor: "color08" }),
3842 * })
3943 */
packages/core/src/text-input.test.ts+145−13
@@ -121,7 +121,7 @@ describe("TextInput integration", () => {
121121 expect(value).toBe("ab\n");
122122 });
123123
124- test("submitKey fires onSubmit instead of inserting", async () => {
124+ test("onKeyPress returning false prevents default editing action", async () => {
125125 const term = setup(20, 3);
126126 let submitted = false;
127127 let value = "hello";
@@ -133,10 +133,12 @@ describe("TextInput integration", () => {
133133 onChange: (v) => {
134134 value = v;
135135 },
136- onSubmit: () => {
137- submitted = true;
136+ onKeyPress: (key) => {
137+ if (key === "enter") {
138+ submitted = true;
139+ return false;
140+ }
138141 },
139- submitKey: "enter",
140142 }),
141143 ]),
142144 );
@@ -146,12 +148,12 @@ describe("TextInput integration", () => {
146148 await waitForRender();
147149
148150 expect(submitted).toBe(true);
149- expect(value).toBe("hello"); // Value should not change
151+ expect(value).toBe("hello"); // No newline inserted
150152 });
151153
152- test("ctrl+enter as submitKey with enter for newlines", async () => {
154+ test("onKeyPress not returning false allows default editing", async () => {
153155 const term = setup(20, 3);
154- let submitted = false;
156+ let keyReceived = "";
155157 let value = "hi";
156158 cel.viewport(() =>
157159 VStack({}, [
@@ -161,20 +163,150 @@ describe("TextInput integration", () => {
161163 onChange: (v) => {
162164 value = v;
163165 },
164- onSubmit: () => {
165- submitted = true;
166+ onKeyPress: (key) => {
167+ keyReceived = key;
168+ // no return false — default editing proceeds
169+ },
170+ }),
171+ ]),
172+ );
173+ await waitForRender();
174+
175+ term.sendInput(ENTER);
176+ await waitForRender();
177+
178+ expect(keyReceived).toBe("enter");
179+ expect(value).toBe("hi\n"); // Newline inserted
180+ });
181+
182+ test("onKeyPress returning false prevents character insertion", async () => {
183+ const term = setup(20, 3);
184+ let value = "abc";
185+ cel.viewport(() =>
186+ VStack({}, [
187+ TextInput({
188+ value,
189+ focused: true,
190+ onChange: (v) => {
191+ value = v;
192+ },
193+ onKeyPress: (key) => {
194+ if (key === "x") return false;
166195 },
167- submitKey: "ctrl+enter",
168196 }),
169197 ]),
170198 );
171199 await waitForRender();
172200
173- // Enter should insert newline (not submit)
201+ // "x" should be prevented
202+ term.sendInput("x");
203+ await waitForRender();
204+ expect(value).toBe("abc");
205+
206+ // "y" should go through
207+ term.sendInput("y");
208+ await waitForRender();
209+ expect(value).toBe("abcy");
210+ });
211+
212+ test("onKeyPress returning false prevents backspace", async () => {
213+ const term = setup(20, 3);
214+ let value = "abc";
215+ cel.viewport(() =>
216+ VStack({}, [
217+ TextInput({
218+ value,
219+ focused: true,
220+ onChange: (v) => {
221+ value = v;
222+ },
223+ onKeyPress: (key) => {
224+ if (key === "backspace") return false;
225+ },
226+ }),
227+ ]),
228+ );
229+ await waitForRender();
230+
231+ term.sendInput(BACKSPACE);
232+ await waitForRender();
233+
234+ expect(value).toBe("abc"); // No deletion
235+ });
236+
237+ test("onKeyPress on TextInput fires before ancestor onKeyPress", async () => {
238+ const term = setup(20, 3);
239+ let parentKey = "";
240+ let inputKey = "";
241+ let value = "hi";
242+ cel.viewport(() =>
243+ VStack(
244+ {
245+ onKeyPress: (key) => {
246+ parentKey = key;
247+ },
248+ },
249+ [
250+ TextInput({
251+ value,
252+ focused: true,
253+ onChange: (v) => {
254+ value = v;
255+ },
256+ onKeyPress: (key) => {
257+ if (key === "enter") {
258+ inputKey = key;
259+ return false; // prevent default, consume key
260+ }
261+ },
262+ }),
263+ ],
264+ ),
265+ );
266+ await waitForRender();
267+
174268 term.sendInput(ENTER);
175269 await waitForRender();
176- expect(value).toBe("hi\n");
177- expect(submitted).toBe(false);
270+
271+ expect(inputKey).toBe("enter");
272+ expect(parentKey).toBe(""); // Ancestor never sees it
273+ expect(value).toBe("hi"); // No newline
274+ });
275+
276+ test("non-editing key bubbles to ancestor when onKeyPress doesn't intercept", async () => {
277+ const term = setup(20, 3);
278+ let parentKey = "";
279+ let value = "hi";
280+ cel.viewport(() =>
281+ VStack(
282+ {
283+ onKeyPress: (key) => {
284+ parentKey = key;
285+ },
286+ },
287+ [
288+ TextInput({
289+ value,
290+ focused: true,
291+ onChange: (v) => {
292+ value = v;
293+ },
294+ onKeyPress: (key) => {
295+ // only intercept enter
296+ if (key === "enter") return false;
297+ },
298+ }),
299+ ],
300+ ),
301+ );
302+ await waitForRender();
303+
304+ // ctrl+s is not intercepted by onKeyPress, and not an editing key — bubbles up
305+ term.sendInput(CTRL_S);
306+ await waitForRender();
307+
308+ expect(parentKey).toBe("ctrl+s"); // Bubbled up
309+ expect(value).toBe("hi"); // Unchanged
178310 });
179311
180312 test("modifier keys bubble up (not consumed by TextInput)", async () => {
packages/types/src/index.ts+9−10
@@ -313,19 +313,18 @@ export interface TextInputProps extends ContainerProps {
313313 onChange: (value: string) => void;
314314
315315 /**
316- * Called when the user presses the submit key.
317- * @see {@link submitKey}
318- */
319- onSubmit?: () => void;
320-
321- /**
322- * Key combo that fires {@link onSubmit}.
323- * @default "enter"
316+ * Key handler that fires **before** the built-in editing logic.
317+ * Return `false` to prevent the default editing action for that key
318+ * (no character insertion, no cursor movement, no deletion).
319+ * Any other return (or no return) lets the default action proceed.
324320 *
325321 * @example
326- * submitKey: "ctrl+enter" // Enter inserts newline, Ctrl+Enter submits
322+ * // Enter submits instead of inserting a newline
323+ * onKeyPress: (key) => {
324+ * if (key === "enter") { handleSend(); return false; }
325+ * }
327326 */
328- submitKey?: string;
327+ onKeyPress?: (key: string) => boolean | void;
329328
330329 /**
331330 * A {@link TextNode} displayed when {@link value} is empty.
spec.md+22−12
@@ -301,7 +301,7 @@ Focus is implicit — no `focusable` prop needed for the common case:
301301
302302 **Escape** unfocuses the current element. **Tab / Shift+Tab** moves focus to the next/previous focusable element in document order (depth-first tree traversal).
303303
304-When a TextInput is focused, text-editing keys (printable characters, arrows, backspace, Tab) go to the input. Modifier combos (e.g., `ctrl+s`) are not consumed by TextInput and bubble up. Press Escape to leave the input, then Tab to traverse.
304+When a TextInput is focused, text-editing keys (printable characters, arrows, backspace, delete, Enter, Tab) go to the input. Modifier combos (e.g., `ctrl+s`) are not consumed by TextInput and bubble up. The TextInput's `onKeyPress` handler fires before editing — returning `false` prevents the default action, letting the app override any key's behavior. Press Escape to leave the input, then Tab to traverse.
305305
306306 ### Uncontrolled Focus
307307
@@ -391,7 +391,9 @@ cel-tui **requires** the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kit
391391 ### Key Event Flow
392392
393393 1. **Topmost layer** receives the key event
394-2. If a **TextInput** is focused, it consumes text-editing keys (printable characters, arrows, backspace, Tab). Modifier combos pass through.
394+2. If a **TextInput** is focused:
395+ - 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.
396+ - Otherwise, the TextInput processes editing keys (printable characters, arrows, backspace, delete, Enter, Tab). Modifier combos (e.g., `ctrl+s`) are not editing keys and pass through.
395397 3. If a **clickable container** is focused, Enter fires `onClick`. Other keys pass through.
396398 4. Unconsumed keys **bubble up** through ancestors — each `onKeyPress` handler in the ancestor chain is called from innermost to root.
397399 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).
@@ -550,13 +552,12 @@ TextInput(props: TextInputProps)
550552
551553 Container sizing props (`width`, `height`, `flex`, `min*`, `max*`, `padding`), focus props (`focused`, `onFocus`, `onBlur`, `focusStyle`), styling props, and:
552554
553-| Prop | Type | Description |
554-| ------------- | ------------------------- | -------------------------------------------------- |
555-| `value` | `string` | Current text content (controlled) |
556-| `onChange` | `(value: string) => void` | Called on text change |
557-| `onSubmit` | `() => void` | Called on submit key |
558-| `submitKey` | `string` | Key combo that fires onSubmit (default: `"enter"`) |
559-| `placeholder` | `Text` | Text node shown when value is empty |
555+| Prop | Type | Description |
556+| ------------- | ---------------------------------- | ---------------------------------------------------------------------------------------- |
557+| `value` | `string` | Current text content (controlled) |
558+| `onChange` | `(value: string) => void` | Called on text change |
559+| `onKeyPress` | `(key: string) => boolean \| void` | Key handler, fires before editing. Return `false` to prevent the default editing action. |
560+| `placeholder` | `Text` | Text node shown when value is empty |
560561
561562 Word-wrap is always on. Cursor position is framework-managed.
562563
@@ -569,8 +570,12 @@ TextInput({
569570 maxHeight: 10,
570571 value,
571572 onChange,
572- onSubmit,
573- submitKey: "ctrl+enter",
573+ onKeyPress: (key) => {
574+ if (key === "ctrl+enter") {
575+ handleSubmit();
576+ return false;
577+ }
578+ },
574579 });
575580 ```
576581
@@ -843,7 +848,12 @@ cel.viewport(() =>
843848 value: input,
844849 onChange: handleChange,
845850 placeholder: Text("type a message...", { fgColor: "color08" }),
846- onSubmit: handleSend,
851+ onKeyPress: (key) => {
852+ if (key === "enter") {
853+ handleSend();
854+ return false;
855+ }
856+ },
847857 }),
848858 HStack(
849859 {