xonecas.io
70160
Ce

cel-tui / commit 3f42b8f

Merge branch 'main' into gh-pages

xonecas2026-04-04 3f42b8f9f04e894bda687c40d5c606614db01a42 parent d56b3cbparent 6a47e37

19 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+80−9
@@ -21,11 +21,11 @@ Dependency chain: `components → core → types`
2121
2222 - **4 primitives only:** VStack, HStack (layout), Text (content leaf), TextInput (editable container)
2323 - **State is external:** The framework has no state management. `cel.viewport(() => tree)` sets a render function, `cel.render()` requests re-evaluation. Apps use whatever state approach they want.
24-- **Controlled props pattern:** Focus (`focused`/`onFocus`/`onBlur`), scroll (`scrollOffset`/`onScroll`), and value (`value`/`onChange`) are app-controlled. The app owns the state, the framework renders it.
25-- **Uncontrolled scroll default:** `overflow: "scroll"` without `scrollOffset` is framework-managed. Adding `scrollOffset` makes it controlled.
24+- **Uncontrolled by default, controlled opt-in:** Focus and scroll are framework-managed by default. Providing `focused` or `scrollOffset` explicitly switches to controlled mode (app owns the state). Value (`value`/`onChange`) on TextInput is always controlled.
25+- **Style inheritance:** Containers propagate style props (fgColor, bgColor, bold, italic, underline) to descendants. Explicit props on a node always override inherited values. Container `bgColor` fills the rect with opaque background before painting children.
26+- **focusStyle:** Containers accept `focusStyle: StyleProps` — style overrides applied when focused, participating in inheritance.
2627 - **TextInput is a container:** Accepts sizing props (flex, width, height, padding, min/max constraints) but has no children — its content is the `value` prop. Scroll is always framework-managed (follows cursor + responds to mouse wheel).
2728 - **Text is a pure leaf:** No sizing props, no children. Parent controls the box. Height is intrinsic (from content + wrapping).
28-- **No style inheritance:** Every Text/TextInput sets its own styles explicitly. No cascading. Verbose but predictable.
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.
@@ -34,12 +34,12 @@ Dependency chain: `components → core → types`
3434
3535 ## Implementation Status
3636
37-All core systems from the spec are implemented and tested (232 tests):
37+All core systems from the spec are implemented and tested:
3838
3939 - **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints, gap, padding, justifyContent, alignItems, largest-remainder rounding
4040 - **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
41+- **Painting** — grapheme-aware text rendering (CJK/emoji via visibleWidth), overflow clipping via clip rect propagation, scroll content offsetting, scrollbar indicators, container bgColor fill, style inheritance, focusStyle overrides
42+- **Input** — key parsing/normalization, SGR mouse events (with batched event support), hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter) with uncontrolled and controlled modes, onKeyPress bubbling from focused element through ancestors
4343 - **TextInput** — text editing, cursor movement, cursor persistence across re-renders (keyed on onChange), auto-scroll to keep cursor visible, placeholder rendering
4444 - **Layering** — multi-layer compositing, transparency, topmost-layer input priority
4545 - **Terminal** — crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
@@ -90,9 +90,11 @@ tmux kill-session -t cel
9090
9191 This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
9292
93+**Caveat:** tmux `send-keys -H` injects raw bytes one event at a time, but real terminals batch multiple mouse events into a single stdin chunk. Always verify mouse/scroll behavior in a real terminal, not just tmux.
94+
9395 ## Spec
9496
95-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+The `spec.md` file is the source of truth for all API design decisions. Always read it before making changes to core framework behavior.
9698
9799 ## Testing Strategy
98100
@@ -139,15 +141,84 @@ chore: scaffold monorepo with types, core, components packages
139141
140142 ## Architecture Notes
141143
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.
144+- `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. Mouse input handles batched SGR events (terminals often send multiple events in a single data chunk).
143145 - `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.
146+- `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets, scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state, container bgColor fill, style inheritance threading, focusStyle resolution.
145147 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both wrap in CSI 2026 synchronized output.
146148 - `hit-test.ts` — `hitTest(root, x, y)` → path from root to deepest node. `findClickHandler`, `findScrollTarget`, `findKeyPressHandler`, `collectFocusable` walk paths.
147149 - `keys.ts` — `parseKey(data)` normalizes terminal input to canonical key strings. `isEditingKey()` identifies keys consumed by TextInput.
148150 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
149151 - `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, SGR mouse, crash cleanup) and `MockTerminal` (testing).
150152
153+## Updating gh-pages
154+
155+The `gh-pages` branch tracks generated API docs (`docs/html/`, `docs/md/`) and an `index.html` for GitHub Pages. To update it after changes land on `main`:
156+
157+```bash
158+git checkout gh-pages
159+git merge main # resolve any conflicts, keeping docs tracked
160+bun run docs # regenerate API docs
161+git add -A
162+git commit -m "docs: regenerate API docs from latest main"
163+git push
164+git checkout main
165+```
166+
167+**Key differences on gh-pages:**
168+
169+- `.gitignore` does **not** exclude `docs/html/` or `docs/md/` (they're committed)
170+- `.prettierignore` includes `docs/html` and `docs/md` (generated files fail format checks otherwise)
171+
172+## Publishing to npm
173+
174+Packages are published to the `@cel-tui` npm org (owner: `xonecas`). They ship TypeScript source directly — no build step.
175+
176+### Version bump
177+
178+All three packages share the same version. Bump all together:
179+
180+```bash
181+# In packages/types/package.json, packages/core/package.json, packages/components/package.json
182+# Update "version" to the new value
183+```
184+
185+Follow [semver](https://semver.org/): patch for fixes, minor for features, major for breaking changes. While `0.x`, minor = breaking is acceptable.
186+
187+### Publish order
188+
189+Must publish in dependency order — types first, then core, then components:
190+
191+```bash
192+cd packages/types && bun publish --access public
193+cd ../core && bun publish --access public
194+cd ../components && bun publish --access public
195+```
196+
197+If 2FA is enabled, add `--otp <code>` to each command.
198+
199+### Pre-publish checklist
200+
201+1. All tests pass: `bun test`
202+2. Types clean: `bun run typecheck`
203+3. Lint/format clean: `bun run check && bun run format`
204+4. Version bumped in all three `package.json` files
205+5. Changes committed and pushed
206+6. Dry run looks correct: `cd packages/core && bun publish --dry-run --access public`
207+
208+### How it works
209+
210+- `"files"` in each `package.json` whitelists what ships (source only, no tests)
211+- `"exports"` map provides proper module resolution for Bun and bundlers
212+- `workspace:*` dependencies are resolved to actual versions by `bun publish`
213+- `get-east-asian-width` is a real dependency of `@cel-tui/core` (installs for consumers)
214+- `typescript` is a peer dependency (consumers bring their own)
215+
216+## Destructive Actions
217+
218+**Never use `git checkout` or `git restore` on files you have modified.** A single `git checkout <file>` will silently discard all uncommitted changes in that file — including unrelated work. If you need to revert a specific edit, use `edit` to undo just that change. If you must use git to undo something, `git stash` first so the work can be recovered.
219+
220+More generally: before running any command that could destroy uncommitted work (`git checkout`, `git reset --hard`, `git clean`, `rm` on source files), stop and consider whether there are unsaved changes at risk. If in doubt, `git stash` or `git diff --stat` first.
221+
151222 ## Conventions
152223
153224 - All code is TypeScript with strict mode
README.md+4−3
@@ -24,6 +24,7 @@ cel.viewport(() =>
2424 VStack(
2525 {
2626 height: "100%",
27+ fgColor: "white",
2728 onKeyPress: (key) => {
2829 if (key === "ctrl+q") process.exit();
2930 },
@@ -34,7 +35,6 @@ cel.viewport(() =>
3435 TextInput({
3536 flex: 1,
3637 value: input,
37- focused: true,
3838 onChange: (v) => {
3939 input = v;
4040 cel.render();
@@ -60,7 +60,8 @@ cel.viewport(() =>
6060 - **`cel.viewport(() => tree)`** sets the render function, **`cel.render()`** triggers re-renders.
6161 - **Flexbox layout** — fixed, flex, percentage, and intrinsic sizing with gap, padding, alignment.
6262 - **Layers** — return an array for multi-layer compositing (modals, overlays).
63-- **Controlled props** — focus, scroll, and text value are app-owned.
63+- **Uncontrolled by default** — focus and scroll just work. Opt into controlled mode when needed.
64+- **Style inheritance** — containers propagate styles to descendants. `bgColor` fills the rect.
6465 - **Cell buffer rendering** — styled cells, differential updates, synchronized output.
6566
6667 ## Packages
@@ -81,7 +82,7 @@ cel.viewport(() =>
8182
8283 ```bash
8384 bun install # install dependencies
84-bun test # run tests (230+)
85+bun test # run tests
8586 bun run check # biome lint
8687 bun run format # prettier check
8788 bun run typecheck # tsc --noEmit
TODO.md+10−6
@@ -1,23 +1,27 @@
11 # cel-tui — TODO
22
3-Remaining work and known discrepancies vs `spec.md`.
3+Remaining work, known bugs, and planned improvements.
44
55 ## Legend
66
7-- 🔧 Needs fix (spec violation or bug)
7+- 🔧 Bug / spec violation
88 - ❌ Not yet implemented
9-- 💡 Nice-to-have / future enhancement
9+- 💡 Future enhancement
1010
1111 ---
1212
13-## Spec Violations
13+## API Improvements
1414
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.
15+- ❌ **Upgrade `Button` component** — `Button` from `@cel-tui/components` doesn't forward `focusStyle`, `fgColor`, `bgColor`, or other container/style props to the underlying HStack. With uncontrolled focus and focusStyle now available, Button should accept these to be useful for keyboard navigation without inline HStack wrappers.
1616
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.
17+- ❌ **`repeat: "fill"` should claim flex space in HStack** — `Text(" ", { repeat: "fill" })` inside an HStack gets width 0 because its intrinsic width is 0 and no flex distributes remaining space. The workaround is `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`, which is non-obvious. Fix: either make `repeat: "fill"` imply flex behavior in the layout engine, or document the workaround prominently. The former is preferred.
18+
19+- ❌ **`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.
1820
1921 ## Not Yet Implemented
2022
23+- ❌ 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.
24+- ❌ `"plus"` as a named key — the spec mentions `"ctrl+plus"` but `+` is the modifier separator and needs special handling.
2125 - ❌ Bracketed paste mode support
2226 - ❌ Kitty keyboard protocol detection
2327
bun.lock+13−3
@@ -17,22 +17,32 @@
1717 },
1818 "packages/components": {
1919 "name": "@cel-tui/components",
20- "version": "0.0.1",
20+ "version": "0.1.0",
2121 "dependencies": {
2222 "@cel-tui/core": "workspace:*",
2323 "@cel-tui/types": "workspace:*",
2424 },
25+ "peerDependencies": {
26+ "typescript": ">=5.0.0",
27+ },
2528 },
2629 "packages/core": {
2730 "name": "@cel-tui/core",
28- "version": "0.0.1",
31+ "version": "0.1.0",
2932 "dependencies": {
3033 "@cel-tui/types": "workspace:*",
34+ "get-east-asian-width": "^1.5.0",
35+ },
36+ "peerDependencies": {
37+ "typescript": ">=5.0.0",
3138 },
3239 },
3340 "packages/types": {
3441 "name": "@cel-tui/types",
35- "version": "0.0.1",
42+ "version": "0.1.0",
43+ "peerDependencies": {
44+ "typescript": ">=5.0.0",
45+ },
3646 },
3747 },
3848 "packages": {
docs/skill/cel-tui/SKILL.md+50−18
@@ -5,12 +5,12 @@ license: MIT
55 compatibility: Requires Bun runtime and a terminal with SGR mouse mode support.
66 metadata:
77 author: sacenox
8- version: "0.0.1"
8+ version: "0.1.0"
99 ---
1010
1111 # Building TUIs with cel-tui
1212
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.
13+cel-tui is a TypeScript TUI framework with a declarative functional API, flexbox layout, cell-buffer rendering, and style inheritance. It has 4 primitives and external state management.
1414
1515 ## Install
1616
@@ -47,6 +47,7 @@ cel.viewport(() =>
4747 VStack(
4848 {
4949 height: "100%",
50+ fgColor: "white",
5051 onKeyPress: (key) => {
5152 if (key === "ctrl+q") {
5253 cel.stop();
@@ -60,7 +61,6 @@ cel.viewport(() =>
6061 TextInput({
6162 flex: 1,
6263 value,
63- focused: true,
6464 onChange: (v) => {
6565 value = v;
6666 cel.render();
@@ -101,6 +101,7 @@ TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`,
101101
102102 ```ts
103103 {
104+ // Sizing
104105 width, height, // SizeValue (number | "50%")
105106 flex, // number
106107 minWidth, maxWidth, // number
@@ -113,9 +114,16 @@ TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`,
113114 scrollbar, // boolean
114115 scrollOffset, // number (controlled scroll)
115116 onScroll, // (offset: number) => void
117+
118+ // Styling (inherited by descendants)
119+ bold, italic, underline,// boolean
120+ fgColor, bgColor, // Color (ANSI 16)
121+ focusStyle, // StyleProps — overrides when focused
122+
123+ // Interaction
116124 onClick, // () => void
117125 focusable, // boolean (default true if onClick set)
118- focused, // boolean (controlled)
126+ focused, // boolean (controlled — omit for uncontrolled)
119127 onFocus, // () => void
120128 onBlur, // () => void
121129 onKeyPress, // (key: string) => void
@@ -147,11 +155,7 @@ TextInput({
147155 onSubmit, // () => void
148156 submitKey, // string (default "enter")
149157 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.)
158+ // + all container props (sizing, styling, focus, etc.)
155159 });
156160 ```
157161
@@ -173,12 +177,17 @@ HStack({ height: 1 }, [
173177 Text("─", { repeat: "fill", fgColor: "brightBlack" });
174178 ```
175179
176-### Button
180+### Button with focus style
177181
178182 ```ts
179-HStack({ onClick: handleClick }, [
180- Text("[Send]", { bold: true, fgColor: "cyan" }),
181-]);
183+HStack(
184+ {
185+ onClick: handleClick,
186+ fgColor: "cyan",
187+ focusStyle: { bgColor: "cyan", fgColor: "black" },
188+ },
189+ [Text(" Send ", { bold: true })],
190+);
182191 ```
183192
184193 ### Growing text input (caps at maxHeight, then scrolls)
@@ -218,7 +227,7 @@ VStack(
218227
219228 ### Layers (modals)
220229
221-Return an array from the render function. Layers composite bottom-to-top:
230+Return an array from the render function. Layers composite bottom-to-top. Use `bgColor` for opaque modal backgrounds:
222231
223232 ```ts
224233 cel.viewport(() => [
@@ -235,7 +244,11 @@ cel.viewport(() => [
235244 cel.render();
236245 },
237246 },
238- [VStack({ width: 40, height: 10 }, [...modalContent])],
247+ [
248+ VStack({ width: 40, height: 10, bgColor: "black" }, [
249+ ...modalContent,
250+ ]),
251+ ],
239252 ),
240253 ]
241254 : []),
@@ -256,9 +269,15 @@ VStack({
256269 }, [...])
257270 ```
258271
259-### Focus (controlled)
272+### Focus
273+
274+Focus is **uncontrolled by default** — Tab/Shift+Tab/Escape/click just work:
260275
261276 ```ts
277+// Uncontrolled (default) — framework manages focus
278+HStack({ onClick: handleAction }, [Text("[ OK ]")]);
279+
280+// Controlled — app owns focus state (provide `focused` prop)
262281 TextInput({
263282 value: text,
264283 onChange: handleChange,
@@ -274,6 +293,17 @@ TextInput({
274293 });
275294 ```
276295
296+### Style inheritance
297+
298+Containers propagate styles to descendants. Explicit props always win:
299+
300+```ts
301+VStack({ fgColor: "white", bgColor: "blue" }, [
302+ Text("inherits white on blue"),
303+ Text("explicit green on blue", { fgColor: "green" }),
304+]);
305+```
306+
277307 ## Key Format
278308
279309 All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`, `"enter"`, `"alt+up"`, `"f1"`. Framework normalizes modifier order.
@@ -283,9 +313,11 @@ All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`
283313 - **State is external** — framework has no state. Call `cel.render()` after changes.
284314 - **Text is a leaf** — no sizing props, no children. Parent controls the box.
285315 - **TextInput is a container** — accepts sizing props but no children.
286-- **No style inheritance** — every node sets its own styles explicitly.
316+- **Style inheritance** — containers propagate styles (fgColor, bgColor, bold, etc.) to descendants. Explicit props on a node always override. Container `bgColor` fills the rect with opaque background.
317+- **focusStyle** — `focusStyle: { bgColor, fgColor, ... }` on containers overrides styles when focused. Participates in inheritance.
318+- **Uncontrolled focus by default** — Tab/Shift+Tab/Escape/click just work. Provide `focused` prop to opt into controlled mode.
287319 - **Escape unfocuses** the current element.
288-- **Tab/Shift+Tab** traverses focusable elements in document order (wraps around).
320+- **Tab/Shift+Tab** traverses focusable elements in document order (wraps around). After Escape, traversal continues from the element that lost focus (not from the start).
289321 - **Enter** activates a focused clickable container (fires onClick).
290322 - **TextInput consumes editing keys** when focused (printable chars, arrows, backspace, delete). Modifier combos (ctrl+s) bubble up through ancestors via onKeyPress.
291323 - **Mouse click** on a focusable element fires onFocus (and onBlur on previous).
examples/hello.ts+42−5
@@ -9,6 +9,7 @@
99 */
1010
1111 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
12+import { Spacer } from "@cel-tui/components";
1213
1314 const logo = [
1415 "╭─────────────────────╮",
@@ -27,6 +28,9 @@ const palette: Array<"cyan" | "magenta" | "yellow" | "green" | "blue" | "red"> =
2728 let colorIndex = 0;
2829 let tick = 0;
2930
31+const MIN_COLS = 38;
32+const MIN_ROWS = 14;
33+
3034 const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
3135
3236 function clock(): string {
@@ -40,26 +44,58 @@ setInterval(() => {
4044 cel.render();
4145 }, 80);
4246
47+function quit() {
48+ cel.stop();
49+ process.exit();
50+}
51+
4352 cel.init(new ProcessTerminal());
4453 cel.viewport(() => {
54+ const cols = process.stdout.columns || 80;
55+ const rows = process.stdout.rows || 24;
56+
57+ if (cols < MIN_COLS || rows < MIN_ROWS) {
58+ return VStack(
59+ {
60+ height: "100%",
61+ justifyContent: "center",
62+ alignItems: "center",
63+ onKeyPress: (key) => {
64+ if (key === "ctrl+q" || key === "ctrl+c") quit();
65+ },
66+ },
67+ [
68+ Text("┌─────────────────────────┐", { fgColor: "yellow" }),
69+ Text("│ Terminal too small :( │", { fgColor: "yellow" }),
70+ Text("│ │", { fgColor: "yellow" }),
71+ Text("│ Please resize to at │", { fgColor: "yellow" }),
72+ Text(
73+ `│ least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars. │`,
74+ { fgColor: "yellow" },
75+ ),
76+ Text("│ │", { fgColor: "yellow" }),
77+ Text("│ Ctrl+Q to quit │", { fgColor: "yellow" }),
78+ Text("└─────────────────────────┘", { fgColor: "yellow" }),
79+ ],
80+ );
81+ }
82+
4583 const color = palette[colorIndex % palette.length]!;
4684 const spinner = spinnerFrames[tick % spinnerFrames.length]!;
4785
4886 return VStack(
4987 {
5088 height: "100%",
51- justifyContent: "center",
5289 alignItems: "center",
90+ overflow: "scroll",
5391 onKeyPress: (key) => {
54- if (key === "ctrl+q" || key === "ctrl+c") {
55- cel.stop();
56- process.exit();
57- }
92+ if (key === "ctrl+q" || key === "ctrl+c") quit();
5893 colorIndex++;
5994 cel.render();
6095 },
6196 },
6297 [
98+ Spacer(),
6399 // Logo
64100 ...logo.map((line) => Text(line, { fgColor: color, bold: true })),
65101
@@ -93,6 +129,7 @@ cel.viewport(() => {
93129 Text(" ctrl+q ", { bgColor: color, fgColor: "black", bold: true }),
94130 Text("quit", { fgColor: "brightBlack" }),
95131 ]),
132+ Spacer(),
96133 ],
97134 );
98135 });
examples/pet.ts+858−0
@@ -0,0 +1,858 @@
1+/**
2+ * cel-tui: Virtual Pet (Tamagotchi)
3+ *
4+ * A feature-rich example exercising the full API surface:
5+ * - Layers (creation modal, log modal, death screen overlay)
6+ * - TextInput (pet name)
7+ * - Focus traversal (Tab/Shift+Tab/Enter/Escape)
8+ * - Controlled scroll (activity log)
9+ * - Timers & animation frames
10+ * - Buttons, key bindings, click handlers
11+ * - External state management
12+ *
13+ * Run: bun run examples/pet.ts
14+ */
15+
16+import {
17+ cel,
18+ VStack,
19+ HStack,
20+ Text,
21+ TextInput,
22+ ProcessTerminal,
23+} from "@cel-tui/core";
24+import { Button, Divider, Spacer } from "@cel-tui/components";
25+
26+// ─── Pet Definitions ────────────────────────────────────────────
27+
28+interface PetDef {
29+ kind: string;
30+ idle: { happy: string[][]; hungry: string[][] };
31+ excited: string[][];
32+ dead: string[];
33+}
34+
35+const PETS: PetDef[] = [
36+ {
37+ kind: "Cat",
38+ idle: {
39+ happy: [
40+ [
41+ " /\\_/\\ ",
42+ " ( ^.^ ) ",
43+ " > ^ < ",
44+ " /| |\\ ",
45+ " (_| |_) ",
46+ ],
47+ [
48+ " /\\_/\\ ",
49+ " ( ^.^ ) ",
50+ " > ^ < ",
51+ " /| |\\ ",
52+ " (_| |_) ",
53+ " ~ ~ ",
54+ ],
55+ ],
56+ hungry: [
57+ [
58+ " /\\_/\\ ",
59+ " ( T.T ) ",
60+ " > o < ",
61+ " /| |\\ ",
62+ " (_| |_) ",
63+ ],
64+ [
65+ " /\\_/\\ ",
66+ " ( T.T ) ",
67+ " > o < ",
68+ " | | ",
69+ " _| |_ ",
70+ ],
71+ ],
72+ },
73+ excited: [
74+ [
75+ " /\\_/\\ ",
76+ " ( >.< ) ",
77+ " >\\^/< ",
78+ " \\| |/ ",
79+ " (_\\_/_) ",
80+ " \\ / ",
81+ ],
82+ [
83+ " /\\_/\\ ",
84+ " \\( ^o^ )/ ",
85+ " > ^ < ",
86+ " | | ",
87+ " (_\\_/_) ",
88+ " / \\ ",
89+ ],
90+ ],
91+ dead: [
92+ " /\\_/\\ ",
93+ " ( x.x ) ",
94+ " > - < ",
95+ " | | ",
96+ " |___| ",
97+ ],
98+ },
99+ {
100+ kind: "Dog",
101+ idle: {
102+ happy: [
103+ [
104+ " |\\_/| ",
105+ " | @ @ ",
106+ " | <> _ ",
107+ " |_/| |// ",
108+ " |/ / ",
109+ " / / ",
110+ ],
111+ [
112+ " |\\_/| ",
113+ " | @ @ ",
114+ " | <> _ ",
115+ " |_/| |// ",
116+ " |/ / ",
117+ " / |_/ ",
118+ ],
119+ ],
120+ hungry: [
121+ [
122+ " |\\_/| ",
123+ " | ; ; ",
124+ " | .. _ ",
125+ " |_/| |// ",
126+ " |/ / ",
127+ " / / ",
128+ ],
129+ [
130+ " |\\_/| ",
131+ " | ; ; ",
132+ " | .. ",
133+ " |_/| | ",
134+ " |/ | ",
135+ " / / ",
136+ ],
137+ ],
138+ },
139+ excited: [
140+ [
141+ " |\\_/| ",
142+ " | O O ",
143+ " | D> _ ",
144+ " |_/| |// ",
145+ " /|/ _/ ",
146+ " / |__/ ",
147+ ],
148+ [
149+ " |\\_/| ",
150+ " | O O ",
151+ " | D> ",
152+ " __|_/|\\__ ",
153+ " / |/ \\ ",
154+ " / | / ",
155+ ],
156+ ],
157+ dead: [
158+ " |\\_/| ",
159+ " | x x ",
160+ " | -- _ ",
161+ " |_/| |// ",
162+ " |/ / ",
163+ " /____/ ",
164+ ],
165+ },
166+ {
167+ kind: "Bunny",
168+ idle: {
169+ happy: [
170+ [" (\\(\\ ", " ( -.-) ", ' o_(")(") '],
171+ [" (\\(\\ ", " ( -.-) ", ' o_(")(") ', " * "],
172+ ],
173+ hungry: [
174+ [" (\\(\\ ", " ( ;.;) ", ' c_(")(") '],
175+ [" (\\(\\ ", " ( ;.;) ", ' c_(")(") ', " ... "],
176+ ],
177+ },
178+ excited: [
179+ [" (\\(\\ ", " ( ^.^) ", ' (")(")_o ', " \\|/ "],
180+ [" (\\(\\ ", " \\( ^o^)/ ", ' (")(") ', " /|\\ "],
181+ ],
182+ dead: [
183+ " (\\(\\ ",
184+ " ( x.x) ",
185+ ' c_(")(") ',
186+ " R.I.P ",
187+ ],
188+ },
189+];
190+
191+// ─── App State ──────────────────────────────────────────────────
192+
193+type Screen = "create" | "main" | "dead";
194+let screen: Screen = "create";
195+
196+// -- Creation state --
197+let petName = "";
198+let selectedKind = 0;
199+let nameInputFocused = false; // only TextInput needs controlled focus (arrow key routing)
200+
201+// -- Pet state --
202+let pet: PetDef | null = null;
203+let health = 100;
204+let hunger = 0; // 0 = full, 100 = starving
205+let happiness = 100;
206+
207+// -- Animation --
208+let frame = 0;
209+let anim: "idle" | "excited" = "idle";
210+let excitedTimer: ReturnType<typeof setTimeout> | null = null;
211+
212+// -- Timers --
213+let tickTimer: ReturnType<typeof setInterval> | null = null;
214+let decayTimer: ReturnType<typeof setInterval> | null = null;
215+
216+// -- Activity log --
217+let log: string[] = [];
218+let showLog = false;
219+let logScroll = 0;
220+
221+// ─── Helpers ────────────────────────────────────────────────────
222+
223+function ts(): string {
224+ return new Date().toLocaleTimeString("en-US", { hour12: false });
225+}
226+
227+function addLog(msg: string) {
228+ log.push(`[${ts()}] ${msg}`);
229+ logScroll = Math.max(0, log.length - 12);
230+}
231+
232+function startGame() {
233+ pet = PETS[selectedKind]!;
234+ if (!petName.trim()) petName = pet.kind;
235+ health = 100;
236+ hunger = 0;
237+ happiness = 100;
238+ anim = "idle";
239+ frame = 0;
240+ log = [];
241+ screen = "main";
242+
243+ addLog(`${petName} the ${pet.kind} was born!`);
244+ addLog("Press [F] feed · [P] pet · [L] log");
245+ startTimers();
246+ cel.render();
247+}
248+
249+function startTimers() {
250+ stopTimers();
251+ tickTimer = setInterval(() => {
252+ frame++;
253+ cel.render();
254+ }, 600);
255+
256+ decayTimer = setInterval(() => {
257+ if (screen !== "main") return;
258+ hunger = Math.min(100, hunger + 3);
259+ happiness = Math.max(0, happiness - 2);
260+ if (hunger >= 80) happiness = Math.max(0, happiness - 2);
261+ if (hunger >= 90 && happiness <= 20) health = Math.max(0, health - 5);
262+ if (health <= 0) return die();
263+ if (hunger >= 70) addLog(`${petName} is hungry...`);
264+ if (happiness <= 25) addLog(`${petName} feels lonely...`);
265+ if (health <= 30) addLog(`${petName} doesn't look well!`);
266+ cel.render();
267+ }, 3000);
268+}
269+
270+function stopTimers() {
271+ if (tickTimer) clearInterval(tickTimer);
272+ if (decayTimer) clearInterval(decayTimer);
273+ if (excitedTimer) clearTimeout(excitedTimer);
274+ tickTimer = decayTimer = excitedTimer = null;
275+}
276+
277+function feed() {
278+ if (screen !== "main") return;
279+ hunger = Math.max(0, hunger - 30);
280+ health = Math.min(100, health + 5);
281+ addLog(`You fed ${petName}! Hunger -30`);
282+ playExcited();
283+}
284+
285+function petIt() {
286+ if (screen !== "main") return;
287+ happiness = Math.min(100, happiness + 25);
288+ addLog(`You pet ${petName}! Happy +25`);
289+ playExcited();
290+}
291+
292+function playExcited() {
293+ anim = "excited";
294+ frame = 0;
295+ if (excitedTimer) clearTimeout(excitedTimer);
296+ excitedTimer = setTimeout(() => {
297+ anim = "idle";
298+ cel.render();
299+ }, 2400);
300+ cel.render();
301+}
302+
303+function die() {
304+ addLog(`${petName} has passed away...`);
305+ screen = "dead";
306+ stopTimers();
307+ cel.render();
308+}
309+
310+function restart() {
311+ stopTimers();
312+ pet = null;
313+ petName = "";
314+ selectedKind = 0;
315+ screen = "create";
316+ log = [];
317+ showLog = false;
318+ cel.render();
319+}
320+
321+function quit() {
322+ stopTimers();
323+ cel.stop();
324+ process.exit(0);
325+}
326+
327+// ─── Terminal Size ──────────────────────────────────────────────
328+
329+const MIN_COLS = 40;
330+const MIN_ROWS = 15;
331+
332+function termSize(): { cols: number; rows: number } {
333+ return {
334+ cols: process.stdout.columns || 80,
335+ rows: process.stdout.rows || 24,
336+ };
337+}
338+
339+function tooSmallView() {
340+ return VStack(
341+ {
342+ height: "100%",
343+ justifyContent: "center",
344+ alignItems: "center",
345+ onKeyPress: (key) => {
346+ if (key === "ctrl+q" || key === "ctrl+c") quit();
347+ },
348+ },
349+ [
350+ Text("┌─────────────────────────┐", { fgColor: "yellow" }),
351+ Text("│ Terminal too small :( │", { fgColor: "yellow" }),
352+ Text("│ │", { fgColor: "yellow" }),
353+ Text("│ Please resize to at │", { fgColor: "yellow" }),
354+ Text(
355+ `│ least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars. │`,
356+ { fgColor: "yellow" },
357+ ),
358+ Text("│ │", { fgColor: "yellow" }),
359+ Text("│ Ctrl+Q to quit │", { fgColor: "yellow" }),
360+ Text("└─────────────────────────┘", { fgColor: "yellow" }),
361+ ],
362+ );
363+}
364+
365+// ─── Art Helpers ────────────────────────────────────────────────
366+
367+function maxArtHeight(def: PetDef): number {
368+ const frames = [
369+ ...def.idle.happy,
370+ ...def.idle.hungry,
371+ ...def.excited,
372+ def.dead,
373+ ];
374+ return Math.max(...frames.map((f) => f.length));
375+}
376+
377+function currentArt(): string[] {
378+ if (!pet) return [];
379+ let lines: string[];
380+ if (anim === "excited") {
381+ lines = pet.excited[frame % pet.excited.length]!;
382+ } else {
383+ const mood = hunger > 60 || happiness < 30 ? "hungry" : "happy";
384+ const frames = pet.idle[mood];
385+ lines = frames[frame % frames.length]!;
386+ }
387+ // Pad to consistent height so buttons don't bounce
388+ const target = maxArtHeight(pet);
389+ while (lines.length < target) lines = [...lines, ""];
390+ return lines;
391+}
392+
393+function artColor(): "cyan" | "yellow" | "magenta" {
394+ if (anim === "excited") return "magenta";
395+ if (hunger > 60 || happiness < 30) return "yellow";
396+ return "cyan";
397+}
398+
399+// ─── Reusable Widgets ───────────────────────────────────────────
400+
401+function StatBar(
402+ label: string,
403+ value: number,
404+ color: "green" | "yellow" | "red" | "cyan",
405+) {
406+ const w = 12;
407+ const filled = Math.round((value / 100) * w);
408+ return VStack({}, [
409+ Text(label, { bold: true, fgColor: "white" }),
410+ HStack({}, [
411+ Text("█", { repeat: Math.max(filled, 0), fgColor: color }),
412+ Text("░", { repeat: Math.max(w - filled, 0), fgColor: "brightBlack" }),
413+ Text(` ${value}`, { fgColor: "brightBlack" }),
414+ ]),
415+ ]);
416+}
417+
418+function barColor(val: number, invert = false): "green" | "yellow" | "red" {
419+ const v = invert ? 100 - val : val;
420+ if (v > 60) return "green";
421+ if (v > 30) return "yellow";
422+ return "red";
423+}
424+
425+// ─── Create Screen ──────────────────────────────────────────────
426+
427+function createView() {
428+ const { rows } = termSize();
429+ const preview = PETS[selectedKind]!;
430+ const previewArt = preview.idle.happy[frame % preview.idle.happy.length]!;
431+ // Compact mode: drop art preview when height is tight
432+ const showPreview = rows >= 22;
433+
434+ return VStack(
435+ {
436+ height: "100%",
437+ alignItems: "center",
438+ overflow: "scroll",
439+ onKeyPress: (key) => {
440+ if (key === "ctrl+q" || key === "ctrl+c") quit();
441+ // Arrow keys to pick species (only when name input is NOT focused)
442+ if (!nameInputFocused) {
443+ if (key === "up") {
444+ selectedKind = (selectedKind - 1 + PETS.length) % PETS.length;
445+ cel.render();
446+ } else if (key === "down") {
447+ selectedKind = (selectedKind + 1) % PETS.length;
448+ cel.render();
449+ }
450+ }
451+ },
452+ },
453+ [
454+ Spacer(),
455+ VStack({ width: 40, padding: { x: 2 }, gap: 0 }, [
456+ // Title
457+ HStack({ justifyContent: "center" }, [
458+ Text("~ New Pet ~", { bold: true, fgColor: "cyan" }),
459+ ]),
460+ Divider({ fgColor: "brightBlack" }),
461+
462+ // Name
463+ Text("Name:", { bold: true, fgColor: "white" }),
464+ TextInput({
465+ value: petName,
466+ onChange: (v) => {
467+ petName = v;
468+ cel.render();
469+ },
470+ height: 1,
471+ fgColor: "brightWhite",
472+ bgColor: "black",
473+ placeholder: Text("enter a name...", {
474+ fgColor: "brightBlack",
475+ bgColor: "black",
476+ }),
477+ // Controlled focus: needed to gate arrow key routing above
478+ focused: nameInputFocused,
479+ onFocus: () => {
480+ nameInputFocused = true;
481+ cel.render();
482+ },
483+ onBlur: () => {
484+ nameInputFocused = false;
485+ cel.render();
486+ },
487+ submitKey: "enter",
488+ onSubmit: () => {
489+ nameInputFocused = false;
490+ cel.render();
491+ },
492+ }),
493+
494+ // Species picker
495+ Text(""),
496+ Text("Species:", { bold: true, fgColor: "white" }),
497+ ...PETS.map((p, i) => {
498+ const sel = i === selectedKind;
499+ return HStack(
500+ {
501+ onClick: () => {
502+ selectedKind = i;
503+ cel.render();
504+ },
505+ focusable: false,
506+ },
507+ [
508+ Text(sel ? " > " : " ", {
509+ fgColor: sel ? "cyan" : "brightBlack",
510+ bold: sel,
Cut short: this commit's diff is over 1000 lines.
examples/simple-scroll.ts+120−0
Cut short: this commit's diff is over 1000 lines.
packages/components/package.json+30−3
Cut short: this commit's diff is over 1000 lines.
packages/core/package.json+35−4
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.test.ts+842−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.ts+272−63
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+301−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.ts+119−11
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+4−4
Cut short: this commit's diff is over 1000 lines.
packages/types/package.json+30−4
Cut short: this commit's diff is over 1000 lines.
packages/types/src/index.ts+37−21
Cut short: this commit's diff is over 1000 lines.
spec.md+150−58
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+3−2
Cut short: this commit's diff is over 1000 lines.