xonecas.io
70160
Ce

cel-tui / commit c22a459

Merge branch 'main' into gh-pages

# Conflicts:
#	.gitignore

xonecas2026-04-04 c22a4594bf50c6f4704e9f084926eb0b2ffdc459 parent cfa40abparent 77fd978

18 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+51−0
@@ -32,6 +32,20 @@ Dependency chain: `components → core → types`
3232 - **Key bubbling:** Unconsumed keys bubble up from focused element through ancestors. Root `onKeyPress` = global handler.
3333 - **Hit detection:** Topmost layer first, deepest node at (x,y), walk up to find handler. Innermost wins for scroll, click, keys.
3434
35+## Implementation Status
36+
37+All core systems from the spec are implemented and tested (232 tests):
38+
39+- **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints, gap, padding, justifyContent, alignItems, largest-remainder rounding
40+- **Rendering** — cell buffer, ANSI emitter with SGR styling, synchronized output (CSI 2026), differential rendering (emitDiff), full clear on resize
41+- **Painting** — grapheme-aware text rendering (CJK/emoji via visibleWidth), overflow clipping via clip rect propagation, scroll content offsetting, scrollbar indicators
42+- **Input** — key parsing/normalization, SGR mouse events, hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter), onKeyPress bubbling from focused element through ancestors
43+- **TextInput** — text editing, cursor movement, cursor persistence across re-renders (keyed on onChange), auto-scroll to keep cursor visible, placeholder rendering
44+- **Layering** — multi-layer compositing, transparency, topmost-layer input priority
45+- **Terminal** — crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
46+
47+See `TODO.md` for remaining spec violations and future work.
48+
3549 ## Runtime
3650
3751 - **Bun** for package management and running TypeScript
@@ -50,6 +64,32 @@ bun run typecheck # tsc --noEmit type checking
5064 bun run docs # generate HTML + Markdown docs into docs/
5165 ```
5266
67+## Visual Testing with tmux
68+
69+Use a tmux session to run examples and visually inspect rendered output:
70+
71+```bash
72+# Create a session (set size to simulate a terminal window)
73+tmux new-session -d -s cel -x 80 -y 24
74+
75+# Run an example
76+tmux send-keys -t cel "cd /home/xonecas/src/cel-tui && bun run examples/hello.ts" Enter
77+
78+# Wait for render, then capture the screen contents
79+sleep 1; tmux capture-pane -t cel -p
80+
81+# Send keystrokes (e.g., Ctrl+Q to quit)
82+tmux send-keys -t cel C-q
83+
84+# Resize the window to test different terminal sizes
85+tmux resize-window -t cel -x 60 -y 20
86+
87+# Kill the session when done
88+tmux kill-session -t cel
89+```
90+
91+This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
92+
5393 ## Spec
5494
5595 The `spec.md` file is the source of truth for all API design decisions. Always read it before making changes to core framework behavior. The open questions at the bottom track what's been decided vs. still in progress.
@@ -97,6 +137,17 @@ chore: scaffold monorepo with types, core, components packages
97137
98138 **Always use `bun` and `bunx` instead of `node`, `npm`, `npx`, or `yarn`.** This is a Bun monorepo — all scripts, package management, and execution should go through Bun.
99139
140+## Architecture Notes
141+
142+- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal)` starts, `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal.
143+- `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
144+- `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets, scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state.
145+- `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both wrap in CSI 2026 synchronized output.
146+- `hit-test.ts` — `hitTest(root, x, y)` → path from root to deepest node. `findClickHandler`, `findScrollTarget`, `findKeyPressHandler`, `collectFocusable` walk paths.
147+- `keys.ts` — `parseKey(data)` normalizes terminal input to canonical key strings. `isEditingKey()` identifies keys consumed by TextInput.
148+- `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
149+- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, SGR mouse, crash cleanup) and `MockTerminal` (testing).
150+
100151 ## Conventions
101152
102153 - All code is TypeScript with strict mode
README.md+13−1
@@ -2,6 +2,12 @@
22
33 A TypeScript TUI framework built around a declarative functional API and ultra-fast rendering.
44
5+<p align="center">
6+ <picture>
7+ <img src="assets/demo.gif" alt="cel-tui demo" width="539" style="border-radius: 8px; box-shadow: 0 4px 16px rgba(0,0,0,0.3);" />
8+ </picture>
9+</p>
10+
511 ## Why "cel"?
612
713 A **cel** is the smallest unit of a terminal display — a single character cell. Start from the smallest meaningful unit and build up, with nothing wasted.
@@ -65,11 +71,17 @@ cel.viewport(() =>
6571 | `@cel-tui/core` | Framework engine and primitives |
6672 | `@cel-tui/components` | Pre-made components (Button, Spacer, Divider) |
6773
74+## Documentation
75+
76+- **[API Reference](https://sacenox.github.io/cel-tui/)** — full TypeDoc-generated docs on GitHub Pages
77+- **[Specification](spec.md)** — complete design spec covering layout, rendering, input, and focus
78+- **[Agent Skill](docs/skill/cel-tui/SKILL.md)** — structured guide for AI coding agents to build apps with cel-tui
79+
6880 ## Development
6981
7082 ```bash
7183 bun install # install dependencies
72-bun test # run tests (170+)
84+bun test # run tests (230+)
7385 bun run check # biome lint
7486 bun run format # prettier check
7587 bun run typecheck # tsc --noEmit
TODO.md+27−0
@@ -0,0 +1,27 @@
1+# cel-tui — TODO
2+
3+Remaining work and known discrepancies vs `spec.md`.
4+
5+## Legend
6+
7+- 🔧 Needs fix (spec violation or bug)
8+- ❌ Not yet implemented
9+- 💡 Nice-to-have / future enhancement
10+
11+---
12+
13+## Spec Violations
14+
15+- 🔧 **Tab key consumed by TextInput when focused** — The spec says Tab is an editing key consumed by TextInput (inserts `\t`). Currently Tab always triggers focus traversal. The spec requires Escape to leave the input first, then Tab to traverse. Fix: skip Tab/Shift+Tab focus traversal when a TextInput is focused.
16+
17+- 🔧 **Mouse wheel scroll inside TextInput** — `findScrollTarget` correctly identifies TextInput as a scroll target, but `cel.ts` scroll handling only updates containers with `overflow: "scroll"`. It should also update TextInput's framework-managed scroll offset when the mouse wheel targets a TextInput.
18+
19+## Not Yet Implemented
20+
21+- ❌ Bracketed paste mode support
22+- ❌ Kitty keyboard protocol detection
23+
24+## Future Enhancements
25+
26+- 💡 Additional example apps (chat UI, text editor from spec reference examples)
27+- 💡 `overflow: "hidden"` as explicit prop (currently all containers clip by default, which matches the spec's default behavior, but the prop value is not checked)
assets/demo.gif+0−0
Binary file, not shown.
docs/skill/cel-tui/SKILL.md+308−0
@@ -0,0 +1,308 @@
1+---
2+name: cel-tui
3+description: Build terminal user interfaces with cel-tui, a TypeScript TUI framework. Use when the user wants to create a TUI app, build a terminal UI, render text in the terminal, create a CLI with interactive elements, build a chat interface, text editor, or any interactive terminal application. Triggers include "build a TUI", "terminal UI", "interactive CLI", "text-based interface", "render to terminal", or any task requiring a programmatic terminal user interface.
4+license: MIT
5+compatibility: Requires Bun runtime and a terminal with SGR mouse mode support.
6+metadata:
7+ author: sacenox
8+ version: "0.0.1"
9+---
10+
11+# Building TUIs with cel-tui
12+
13+cel-tui is a TypeScript TUI framework with a declarative functional API, flexbox layout, and cell-buffer rendering. It has 4 primitives and external state management.
14+
15+## Install
16+
17+```bash
18+bun add @cel-tui/core
19+# Optional pre-made components
20+bun add @cel-tui/components
21+```
22+
23+## Core Pattern
24+
25+Every cel-tui app follows this pattern:
26+
27+1. Import primitives and `ProcessTerminal`
28+2. Initialize with `cel.init(new ProcessTerminal())`
29+3. Define state as plain variables (or any state approach)
30+4. Set render function with `cel.viewport(() => tree)`
31+5. Call `cel.render()` after state changes
32+
33+```ts
34+import {
35+ cel,
36+ VStack,
37+ HStack,
38+ Text,
39+ TextInput,
40+ ProcessTerminal,
41+} from "@cel-tui/core";
42+
43+let value = "";
44+
45+cel.init(new ProcessTerminal());
46+cel.viewport(() =>
47+ VStack(
48+ {
49+ height: "100%",
50+ onKeyPress: (key) => {
51+ if (key === "ctrl+q") {
52+ cel.stop();
53+ process.exit();
54+ }
55+ },
56+ },
57+ [
58+ Text("My App", { bold: true, fgColor: "cyan" }),
59+ Text("─", { repeat: "fill" }),
60+ TextInput({
61+ flex: 1,
62+ value,
63+ focused: true,
64+ onChange: (v) => {
65+ value = v;
66+ cel.render();
67+ },
68+ }),
69+ ],
70+ ),
71+);
72+```
73+
74+## 4 Primitives
75+
76+| Primitive | Type | Description |
77+| ------------------------- | ----------------------- | ---------------------------------------------- |
78+| `VStack(props, children)` | Container | Vertical stack — children top to bottom |
79+| `HStack(props, children)` | Container | Horizontal stack — children left to right |
80+| `Text(content, props?)` | Leaf | Styled text, no children, fills parent width |
81+| `TextInput(props)` | Container (no children) | Multi-line editable text, accepts sizing props |
82+
83+## Sizing
84+
85+Containers accept 4 sizing strategies:
86+
87+```ts
88+VStack({}, []); // Intrinsic — size to fit content (default)
89+VStack({ width: 30, height: 10 }, []); // Fixed — exact cell count
90+VStack({ flex: 1 }, []); // Flex — proportional to siblings
91+VStack({ width: "50%", height: "100%" }, []); // Percentage — relative to parent
92+```
93+
94+Constraints: `minWidth`, `maxWidth`, `minHeight`, `maxHeight`.
95+
96+Text has no sizing props — parent controls the box, height is intrinsic (content + wrapping).
97+
98+TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`, `maxHeight`, etc.).
99+
100+## Container Props
101+
102+```ts
103+{
104+ width, height, // SizeValue (number | "50%")
105+ flex, // number
106+ minWidth, maxWidth, // number
107+ minHeight, maxHeight, // number
108+ padding, // { x?: number, y?: number }
109+ gap, // number (cells between children)
110+ justifyContent, // "start" | "end" | "center" | "space-between"
111+ alignItems, // "start" | "end" | "center" | "stretch"
112+ overflow, // "hidden" (default) | "scroll"
113+ scrollbar, // boolean
114+ scrollOffset, // number (controlled scroll)
115+ onScroll, // (offset: number) => void
116+ onClick, // () => void
117+ focusable, // boolean (default true if onClick set)
118+ focused, // boolean (controlled)
119+ onFocus, // () => void
120+ onBlur, // () => void
121+ onKeyPress, // (key: string) => void
122+}
123+```
124+
125+## Text Props
126+
127+```ts
128+Text("content", {
129+ repeat: "fill" | number, // Repeat to fill width or N times
130+ wrap: "none" | "word", // Default "none", hard-clips at edge
131+ bold,
132+ italic,
133+ underline, // boolean
134+ fgColor,
135+ bgColor, // ANSI 16 Color
136+});
137+```
138+
139+Colors: `"black"`, `"red"`, `"green"`, `"yellow"`, `"blue"`, `"magenta"`, `"cyan"`, `"white"`, and bright variants (`"brightRed"`, etc.).
140+
141+## TextInput Props
142+
143+```ts
144+TextInput({
145+ value, // string (controlled)
146+ onChange, // (value: string) => void
147+ onSubmit, // () => void
148+ submitKey, // string (default "enter")
149+ placeholder, // Text() node shown when empty
150+ focused, // boolean (controlled)
151+ onFocus,
152+ onBlur, // () => void
153+ // + all container sizing props
154+ // + all styling props (bold, fgColor, etc.)
155+});
156+```
157+
158+## Common Patterns
159+
160+### Spacer (push items apart)
161+
162+```ts
163+HStack({ height: 1 }, [
164+ Text("left"),
165+ VStack({ flex: 1 }, []), // spacer
166+ Text("right"),
167+]);
168+```
169+
170+### Horizontal divider
171+
172+```ts
173+Text("─", { repeat: "fill", fgColor: "brightBlack" });
174+```
175+
176+### Button
177+
178+```ts
179+HStack({ onClick: handleClick }, [
180+ Text("[Send]", { bold: true, fgColor: "cyan" }),
181+]);
182+```
183+
184+### Growing text input (caps at maxHeight, then scrolls)
185+
186+```ts
187+TextInput({
188+ flex: 1,
189+ maxHeight: 10,
190+ value,
191+ onChange: (v) => {
192+ value = v;
193+ cel.render();
194+ },
195+ submitKey: "ctrl+enter",
196+});
197+```
198+
199+### Scrollable list
200+
201+```ts
202+// Uncontrolled (framework manages scroll)
203+VStack({ overflow: "scroll", scrollbar: true }, [...items]);
204+
205+// Controlled (app manages scroll)
206+VStack(
207+ {
208+ overflow: "scroll",
209+ scrollOffset: offset,
210+ onScroll: (o) => {
211+ offset = o;
212+ cel.render();
213+ },
214+ },
215+ [...items],
216+);
217+```
218+
219+### Layers (modals)
220+
221+Return an array from the render function. Layers composite bottom-to-top:
222+
223+```ts
224+cel.viewport(() => [
225+ VStack({ height: "100%" }, [...mainUI]),
226+ ...(showModal
227+ ? [
228+ VStack(
229+ {
230+ height: "100%",
231+ justifyContent: "center",
232+ alignItems: "center",
233+ onClick: () => {
234+ showModal = false;
235+ cel.render();
236+ },
237+ },
238+ [VStack({ width: 40, height: 10 }, [...modalContent])],
239+ ),
240+ ]
241+ : []),
242+]);
243+```
244+
245+### Global key bindings
246+
247+Put `onKeyPress` on the root container — it catches all keys not consumed by focused elements:
248+
249+```ts
250+VStack({
251+ height: "100%",
252+ onKeyPress: (key) => {
253+ if (key === "ctrl+q") { cel.stop(); process.exit(); }
254+ if (key === "ctrl+s") saveFile();
255+ },
256+}, [...])
257+```
258+
259+### Focus (controlled)
260+
261+```ts
262+TextInput({
263+ value: text,
264+ onChange: handleChange,
265+ focused: isFocused,
266+ onFocus: () => {
267+ isFocused = true;
268+ cel.render();
269+ },
270+ onBlur: () => {
271+ isFocused = false;
272+ cel.render();
273+ },
274+});
275+```
276+
277+## Key Format
278+
279+All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`, `"enter"`, `"alt+up"`, `"f1"`. Framework normalizes modifier order.
280+
281+## Key Rules
282+
283+- **State is external** — framework has no state. Call `cel.render()` after changes.
284+- **Text is a leaf** — no sizing props, no children. Parent controls the box.
285+- **TextInput is a container** — accepts sizing props but no children.
286+- **No style inheritance** — every node sets its own styles explicitly.
287+- **Escape unfocuses** the current element.
288+- **Tab/Shift+Tab** traverses focusable elements in document order (wraps around).
289+- **Enter** activates a focused clickable container (fires onClick).
290+- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace, delete). Modifier combos (ctrl+s) bubble up through ancestors via onKeyPress.
291+- **Mouse click** on a focusable element fires onFocus (and onBlur on previous).
292+- **Innermost wins** — for click, scroll, and key handlers.
293+- **Differential rendering** — only changed cells are emitted after the first render.
294+- **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
295+
296+## Pre-made Components
297+
298+```ts
299+import { Spacer, Divider, Button } from "@cel-tui/components";
300+
301+Spacer(); // VStack({ flex: 1 }, [])
302+Divider(); // Text("─", { repeat: "fill" })
303+Divider({ char: "═", fgColor: "brightBlack" });
304+Button("[OK]", { onClick: handleOk });
305+Button("✕", { onClick: handleClose, focusable: false });
306+```
307+
308+For the full specification, see the [cel-tui spec](https://raw.githubusercontent.com/sacenox/cel-tui/main/spec.md).
examples/hello.ts+98−0
@@ -0,0 +1,98 @@
1+/**
2+ * cel-tui: Hello World
3+ *
4+ * A stylish first impression — centered ASCII art logo with a
5+ * reactive clock and keyboard hints. Press any key to cycle
6+ * colors, Ctrl+Q to quit.
7+ *
8+ * Run: bun run examples/hello.ts
9+ */
10+
11+import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
12+
13+const logo = [
14+ "╭─────────────────────╮",
15+ "│ ██████╗███████╗██╗ │",
16+ "│ ██╔════╝██╔════╝██║ │",
17+ "│ ██║ █████╗ ██║ │",
18+ "│ ██║ ██╔══╝ ██║ │",
19+ "│ ╚██████╗███████╗██║ │",
20+ "│ ╚═════╝╚══════╝╚═╝ │",
21+ "╰─────────────────────╯",
22+];
23+
24+const palette: Array<"cyan" | "magenta" | "yellow" | "green" | "blue" | "red"> =
25+ ["cyan", "magenta", "yellow", "green", "blue", "red"];
26+
27+let colorIndex = 0;
28+let tick = 0;
29+
30+const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
31+
32+function clock(): string {
33+ const now = new Date();
34+ return now.toLocaleTimeString("en-US", { hour12: false });
35+}
36+
37+// Animate spinner
38+setInterval(() => {
39+ tick++;
40+ cel.render();
41+}, 80);
42+
43+cel.init(new ProcessTerminal());
44+cel.viewport(() => {
45+ const color = palette[colorIndex % palette.length]!;
46+ const spinner = spinnerFrames[tick % spinnerFrames.length]!;
47+
48+ return VStack(
49+ {
50+ height: "100%",
51+ justifyContent: "center",
52+ alignItems: "center",
53+ onKeyPress: (key) => {
54+ if (key === "ctrl+q" || key === "ctrl+c") {
55+ cel.stop();
56+ process.exit();
57+ }
58+ colorIndex++;
59+ cel.render();
60+ },
61+ },
62+ [
63+ // Logo
64+ ...logo.map((line) => Text(line, { fgColor: color, bold: true })),
65+
66+ // Tagline
67+ Text(""),
68+ Text("terminal UIs, cell by cell", {
69+ italic: true,
70+ fgColor: "brightBlack",
71+ }),
72+
73+ // Divider
74+ Text(""),
75+ HStack({}, [
76+ Text(" "),
77+ Text("─", { repeat: 34, fgColor: color }),
78+ Text(" "),
79+ ]),
80+ Text(""),
81+
82+ // Live info row
83+ HStack({ gap: 2 }, [
84+ Text(`${spinner}`, { fgColor: color, bold: true }),
85+ Text(clock(), { fgColor: "white" }),
86+ Text("│", { fgColor: "brightBlack" }),
87+ Text("press any key to change color", { fgColor: "brightBlack" }),
88+ ]),
89+
90+ // Quit hint
91+ Text(""),
92+ HStack({ gap: 1 }, [
93+ Text(" ctrl+q ", { bgColor: color, fgColor: "black", bold: true }),
94+ Text("quit", { fgColor: "brightBlack" }),
95+ ]),
96+ ],
97+ );
98+});
packages/core/src/cel.test.ts+366−3
@@ -2,8 +2,8 @@ import { afterEach, describe, expect, test } from "bun:test";
22 import { cel } from "./cel.js";
33 import { MockTerminal } from "./terminal.js";
44 import { Text } from "./primitives/text.js";
5-import { VStack } from "./primitives/stacks.js";
6-import { HStack } from "./primitives/stacks.js";
5+import { TextInput } from "./primitives/text-input.js";
6+import { VStack, HStack } from "./primitives/stacks.js";
77
88 describe("cel end-to-end", () => {
99 let term: MockTerminal;
@@ -114,7 +114,10 @@ describe("cel end-to-end", () => {
114114 await waitForRender();
115115
116116 expect(renderCount).toBe(2);
117- expect(term.output).toContain("Count: 3");
117+ // Differential rendering: initial full render has "Count: 0",
118+ // subsequent render emits only the changed character "3"
119+ expect(term.output).toContain("Count: 0");
120+ expect(term.output).toContain("3");
118121 });
119122
120123 test("wraps output in synchronized output markers", async () => {
@@ -201,4 +204,364 @@ describe("cel end-to-end", () => {
201204 expect(scrollOffset).toBe(1);
202205 });
203206 });
207+
208+ describe("focus system", () => {
209+ test("Tab moves focus to next focusable element", async () => {
210+ const term = setup(20, 5);
211+ const focused: string[] = [];
212+ let focus1 = false;
213+ let focus2 = false;
214+
215+ cel.viewport(() =>
216+ VStack({ width: 20, height: 5 }, [
217+ HStack(
218+ {
219+ onClick: () => {},
220+ focused: focus1,
221+ onFocus: () => {
222+ focus1 = true;
223+ focus2 = false;
224+ focused.push("btn1");
225+ },
226+ onBlur: () => {
227+ focus1 = false;
228+ },
229+ },
230+ [Text("Btn1")],
231+ ),
232+ HStack(
233+ {
234+ onClick: () => {},
235+ focused: focus2,
236+ onFocus: () => {
237+ focus2 = true;
238+ focus1 = false;
239+ focused.push("btn2");
240+ },
241+ onBlur: () => {
242+ focus2 = false;
243+ },
244+ },
245+ [Text("Btn2")],
246+ ),
247+ ]),
248+ );
249+ await waitForRender();
250+
251+ // Tab to focus first element
252+ term.sendInput("\t");
253+ await waitForRender();
254+ expect(focused).toEqual(["btn1"]);
255+
256+ // Tab to focus second element
257+ term.sendInput("\t");
258+ await waitForRender();
259+ expect(focused).toEqual(["btn1", "btn2"]);
260+ });
261+
262+ test("Shift+Tab moves focus backwards", async () => {
263+ const term = setup(20, 5);
264+ let focus1 = false;
265+ let focus2 = true;
266+ const focused: string[] = [];
267+
268+ cel.viewport(() =>
269+ VStack({ width: 20, height: 5 }, [
270+ HStack(
271+ {
272+ onClick: () => {},
273+ focused: focus1,
274+ onFocus: () => {
275+ focus1 = true;
276+ focus2 = false;
277+ focused.push("btn1");
278+ },
279+ onBlur: () => {
280+ focus1 = false;
281+ },
282+ },
283+ [Text("Btn1")],
284+ ),
285+ HStack(
286+ {
287+ onClick: () => {},
288+ focused: focus2,
289+ onFocus: () => {
290+ focus2 = true;
291+ focus1 = false;
292+ focused.push("btn2");
293+ },
294+ onBlur: () => {
295+ focus2 = false;
296+ },
297+ },
298+ [Text("Btn2")],
299+ ),
300+ ]),
301+ );
302+ await waitForRender();
303+
304+ // Shift+Tab from btn2 should focus btn1
305+ term.sendInput("\x1b[Z");
306+ await waitForRender();
307+ expect(focused).toEqual(["btn1"]);
308+ });
309+
310+ test("Escape unfocuses the current element", async () => {
311+ const term = setup(20, 5);
312+ let blurred = false;
313+ let btnFocused = true;
314+
315+ cel.viewport(() =>
316+ VStack({ width: 20, height: 5 }, [
317+ HStack(
318+ {
319+ onClick: () => {},
320+ focused: btnFocused,
321+ onBlur: () => {
322+ blurred = true;
323+ btnFocused = false;
324+ },
325+ },
326+ [Text("Btn")],
327+ ),
328+ ]),
329+ );
330+ await waitForRender();
331+
332+ term.sendInput("\x1b");
333+ await waitForRender();
334+ expect(blurred).toBe(true);
335+ });
336+
337+ test("Enter activates focused clickable container", async () => {
338+ const term = setup(20, 5);
339+ let clicked = false;
340+
341+ cel.viewport(() =>
342+ VStack({ width: 20, height: 5 }, [
343+ HStack(
344+ {
345+ onClick: () => {
346+ clicked = true;
347+ },
348+ focused: true,
349+ },
350+ [Text("Btn")],
351+ ),
352+ ]),
353+ );
354+ await waitForRender();
355+
356+ term.sendInput("\r");
357+ await waitForRender();
358+ expect(clicked).toBe(true);
359+ });
360+
361+ test("mouse click on focusable element fires onFocus", async () => {
362+ const term = setup(20, 5);
363+ let btnFocused = false;
364+
365+ cel.viewport(() =>
366+ VStack({ width: 20, height: 5 }, [
367+ HStack(
368+ {
369+ onClick: () => {},
370+ focused: btnFocused,
371+ onFocus: () => {
372+ btnFocused = true;
373+ },
374+ },
375+ [Text("Btn")],
376+ ),
377+ ]),
378+ );
379+ await waitForRender();
380+
381+ // Click on the button at (1, 0)
382+ term.sendInput("\x1b[<0;2;1m");
383+ await waitForRender();
384+ expect(btnFocused).toBe(true);
385+ });
386+
387+ test("Tab wraps around to first element", async () => {
388+ const term = setup(20, 5);
389+ let focus1 = false;
390+ let focus2 = true;
391+ const focused: string[] = [];
392+
393+ cel.viewport(() =>
394+ VStack({ width: 20, height: 5 }, [
395+ HStack(
396+ {
397+ onClick: () => {},
398+ focused: focus1,
399+ onFocus: () => {
400+ focus1 = true;
401+ focus2 = false;
402+ focused.push("btn1");
403+ },
404+ onBlur: () => {
405+ focus1 = false;
406+ },
407+ },
408+ [Text("Btn1")],
409+ ),
410+ HStack(
411+ {
412+ onClick: () => {},
413+ focused: focus2,
414+ onFocus: () => {
415+ focus2 = true;
416+ focus1 = false;
417+ focused.push("btn2");
418+ },
419+ onBlur: () => {
420+ focus2 = false;
421+ },
422+ },
423+ [Text("Btn2")],
424+ ),
425+ ]),
426+ );
427+ await waitForRender();
428+
429+ // Tab from btn2 (last) should wrap to btn1
430+ term.sendInput("\t");
431+ await waitForRender();
432+ expect(focused).toEqual(["btn1"]);
433+ });
434+ });
435+
436+ describe("onKeyPress bubbling", () => {
437+ test("key bubbles from focused element up through ancestors", async () => {
438+ const term = setup(20, 5);
439+ const received: string[] = [];
440+
441+ cel.viewport(() =>
442+ VStack(
443+ {
444+ width: 20,
445+ height: 5,
446+ onKeyPress: (key) => {
447+ received.push("root:" + key);
448+ },
449+ },
450+ [
451+ VStack(
452+ {
453+ onKeyPress: (key) => {
454+ received.push("mid:" + key);
455+ },
456+ },
457+ [
458+ HStack(
459+ {
460+ onClick: () => {},
461+ focused: true,
462+ },
463+ [Text("Focused Btn")],
464+ ),
465+ ],
466+ ),
467+ ],
468+ ),
469+ );
470+ await waitForRender();
471+
472+ // Send a key — should bubble from focused btn through mid, then root
473+ term.sendInput("x");
474+ await waitForRender();
475+
476+ // Nearest ancestor with onKeyPress is "mid", so it handles first
477+ expect(received).toEqual(["mid:x"]);
478+ });
479+
480+ test("key reaches root onKeyPress when no intermediate handlers", async () => {
481+ const term = setup(20, 5);
482+ let rootKey = "";
483+
484+ cel.viewport(() =>
485+ VStack(
486+ {
487+ width: 20,
488+ height: 5,
489+ onKeyPress: (key) => {
490+ rootKey = key;
491+ },
492+ },
493+ [
494+ HStack(
495+ {
496+ onClick: () => {},
497+ focused: true,
498+ },
499+ [Text("Btn")],
500+ ),
501+ ],
502+ ),
503+ );
504+ await waitForRender();
505+
506+ term.sendInput("y");
507+ await waitForRender();
508+ expect(rootKey).toBe("y");
509+ });
510+
511+ test("modifier key from focused TextInput bubbles to ancestors", async () => {
512+ const term = setup(20, 5);
513+ let parentKey = "";
514+ let inputValue = "hello";
515+
516+ cel.viewport(() =>
517+ VStack(
518+ {
519+ width: 20,
520+ height: 5,
521+ onKeyPress: (key) => {
522+ parentKey = key;
523+ },
524+ },
525+ [
526+ TextInput({
527+ value: inputValue,
528+ onChange: (v) => {
529+ inputValue = v;
530+ },
531+ focused: true,
532+ }),
533+ ],
534+ ),
535+ );
536+ await waitForRender();
537+
538+ // Ctrl+S is not an editing key — should bubble up
539+ term.sendInput("\x13");
540+ await waitForRender();
541+ expect(parentKey).toBe("ctrl+s");
542+ });
543+
544+ test("unfocused state bubbles from root only", async () => {
545+ const term = setup(20, 5);
546+ let rootKey = "";
547+
548+ cel.viewport(() =>
549+ VStack(
550+ {
551+ width: 20,
552+ height: 5,
553+ onKeyPress: (key) => {
554+ rootKey = key;
555+ },
556+ },
557+ [Text("no focus")],
558+ ),
559+ );
560+ await waitForRender();
561+
562+ term.sendInput("z");
563+ await waitForRender();
564+ expect(rootKey).toBe("z");
565+ });
566+ });
204567 });
packages/core/src/cel.ts+213−23
@@ -1,6 +1,6 @@
11 import type { Node } from "@cel-tui/types";
22 import { CellBuffer } from "./cell-buffer.js";
3-import { emitBuffer } from "./emitter.js";
3+import { emitBuffer, emitDiff } from "./emitter.js";
44 import {
55 hitTest,
66 findClickHandler,
@@ -15,6 +15,8 @@ import {
1515 getTextInputCursor,
1616 setTextInputCursor,
1717 setTextInputScroll,
18+ getContainerScroll,
19+ setContainerScroll,
1820 } from "./paint.js";
1921 import {
2022 insertChar,
@@ -30,6 +32,7 @@ type RenderFn = () => Node | Node[];
3032 let terminal: Terminal | null = null;
3133 let renderFn: RenderFn | null = null;
3234 let renderScheduled = false;
35+let prevBuffer: CellBuffer | null = null;
3336 let currentBuffer: CellBuffer | null = null;
3437 let currentLayouts: LayoutNode[] = [];
3538
@@ -41,14 +44,17 @@ function doRender(): void {
4144 const height = terminal.rows;
4245
4346 // Create or resize buffer
44- if (
45- !currentBuffer ||
46- currentBuffer.width !== width ||
47- currentBuffer.height !== height
48- ) {
47+ const isResize =
48+ currentBuffer !== null &&
49+ (currentBuffer.width !== width || currentBuffer.height !== height);
50+ const isFirstRender = currentBuffer === null;
51+
52+ if (isFirstRender || isResize) {
53+ prevBuffer = null;
4954 currentBuffer = new CellBuffer(width, height);
5055 } else {
51- currentBuffer.clear();
56+ prevBuffer = currentBuffer;
57+ currentBuffer = new CellBuffer(width, height);
5258 }
5359
5460 // Get the tree from the render function
@@ -63,9 +69,14 @@ function doRender(): void {
6369 paint(layoutTree, currentBuffer);
6470 }
6571
66- // Emit to terminal
67- const output = emitBuffer(currentBuffer);
68- terminal.write(output);
72+ // Emit to terminal — differential when possible
73+ if (prevBuffer) {
74+ const output = emitDiff(prevBuffer, currentBuffer);
75+ if (output.length > 0) terminal.write(output);
76+ } else {
77+ const output = emitBuffer(currentBuffer);
78+ terminal.write(output);
79+ }
6980 }
7081
7182 // --- Input handling ---
@@ -80,7 +91,7 @@ function handleInput(data: string): void {
8091
8192 // Keyboard input
8293 const key = parseKey(data);
83- handleKeyEvent(key);
Cut short: this commit's diff is over 1000 lines.
packages/core/src/composite.test.ts+7−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.test.ts+59−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.ts+61−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/index.ts+2−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.test.ts+370−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.ts+118−27
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+223−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.ts+309−37
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+47−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-input.test.ts+80−0
Cut short: this commit's diff is over 1000 lines.