xonecas.io
70160
Ce

cel-tui / commit a594136

Merge branch 'main' into gh-pages

xonecas2026-04-04 a5941362efd130e2b0ae863d7be6a9f5fe664b2a parent 414c54dparent 684f2e9

38 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+67−6
@@ -39,10 +39,10 @@ All core systems from the spec are implemented and tested:
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
4141 - **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
42+- **Input** — Kitty keyboard protocol (level 1, required), key parsing/normalization for CSI u / CSI letter / CSI tilde formats, 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
45-- **Terminal** — crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
45+- **Terminal** — Kitty keyboard protocol enable/disable, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
4646
4747 See `TODO.md` for remaining spec violations and future work.
4848
@@ -67,7 +67,19 @@ bun run docs # generate HTML + Markdown docs into docs/
6767
6868 ## Visual Testing with tmux
6969
70-Use a tmux session to run examples and visually inspect rendered output:
70+Use a tmux session to run examples and visually inspect rendered output.
71+
72+### tmux Configuration
73+
74+cel-tui requires the Kitty keyboard protocol. tmux 3.2+ supports it via the `extended-keys` option, but it's **off by default**. The global `~/.tmux.conf` must include:
75+
76+```
77+set -s extended-keys on
78+```
79+
80+Without this, tmux intercepts the protocol negotiation and key events arrive in legacy format that the framework's parser won't recognize.
81+
82+### Usage
7183
7284 ```bash
7385 # Create a session (set size to simulate a terminal window)
@@ -91,8 +103,57 @@ tmux kill-session -t cel
91103
92104 This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
93105
106+### Sending Keys with the Kitty Protocol
107+
108+cel-tui requires the Kitty keyboard protocol. `tmux send-keys` named keys (e.g., `C-q`, `Enter`) inject **legacy** byte sequences that the framework's parser won't recognize. Use the `kittyEncode` test helper with `send-keys -H` (hex mode) instead:
109+
110+```bash
111+# Helper: convert a key name to hex bytes via kittyEncode
112+send_key() {
113+ local hex=$(cd /home/xonecas/src/cel-tui && bun -e "
114+ const {kittyEncode} = require('./packages/core/src/test-helpers.ts');
115+ const bytes = kittyEncode('$1');
116+ const hex = Array.from(bytes).map(c => c.charCodeAt(0).toString(16).padStart(2,'0')).join(' ');
117+ process.stdout.write(hex);
118+ ")
119+ tmux send-keys -t cel -H $hex
120+}
121+
122+# Usage:
123+send_key "ctrl+q" # Quit
124+send_key "tab" # Focus traversal
125+send_key "enter" # Activate
126+send_key "escape" # Unfocus
127+send_key "a" # Printable character (lowercase only)
128+send_key "ctrl+s" # Modifier combo
129+send_key "shift+tab" # Reverse focus traversal
130+```
131+
132+**Limitations:** The helper lowercases all input, so uppercase letters aren't testable this way.
133+
94134 **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.
95135
136+### Mouse Events Don't Work in tmux
137+
138+SGR mouse events (click, scroll) sent via `tmux send-keys -H` are **unreliable** and should not be used for testing. Even with correctly-formatted SGR press/release byte sequences and `mouse off` in tmux config, the injected bytes may not reach the application's stdin in a form the parser recognizes. This is a known tmux limitation with raw byte injection for mouse protocols.
139+
140+**Do not test mouse interactions (click, scroll) through tmux.** Use tmux only for:
141+
142+- Keyboard-driven testing via `send_key` helper
143+- Visual inspection of rendered output via `tmux capture-pane -p`
144+- Verifying layout, alignment, and text content
145+
146+Mouse and scroll behavior must be verified in a real interactive terminal.
147+
148+### tmux capture-pane Limitations
149+
150+`tmux capture-pane -p` captures **plain text only** — no colors or style attributes. This means:
151+
152+- You can verify text content, alignment, and layout structure
153+- You **cannot** verify `fgColor`, `bgColor`, `bold`, `focusStyle` changes, or any visual styling
154+
155+To inspect colors, use `tmux capture-pane -e -p` (includes escape sequences) or verify styling through unit tests against the cell buffer.
156+
96157 ## Spec
97158
98159 The `spec.md` file is the source of truth for all API design decisions. Always read it before making changes to core framework behavior.
@@ -144,13 +205,13 @@ chore: scaffold monorepo with types, core, components packages
144205
145206 - `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).
146207 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
147-- `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.
208+- `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, container bgColor fill, style inheritance threading, focusStyle resolution.
148209 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both wrap in CSI 2026 synchronized output.
149210 - `hit-test.ts` — `hitTest(root, x, y)` → path from root to deepest node. `findClickHandler`, `findScrollTarget`, `collectKeyPressHandlers`, `collectFocusable` walk paths.
150-- `keys.ts` — `parseKey(data)` normalizes terminal input to canonical key strings. `isEditingKey()` identifies keys consumed by TextInput. `normalizeKey()` reorders modifiers to canonical `ctrl+alt+shift+<key>` order.
211+- `keys.ts` — Kitty keyboard protocol parser. `parseKey(data)` handles CSI u sequences (special keys, modifier combos), CSI letter sequences (arrows, Home/End with modifiers), CSI tilde sequences (Delete, PageUp/Down, F-keys with modifiers), and raw printable bytes. Maps `" "` → `"space"`, `"+"` → `"plus"` as named keys. `isEditingKey()` identifies keys consumed by TextInput. `normalizeKey()` reorders modifiers to canonical `ctrl+alt+shift+<key>` order.
151212 - `text-edit.ts` — Pure text editing functions (`insertChar`, `deleteBackward`, `deleteForward`, `moveCursor`). Operates on `EditState` (value + cursor position). Used by `cel.ts` to handle TextInput key events.
152213 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
153-- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, SGR mouse, crash cleanup) and `MockTerminal` (testing).
214+- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1, SGR mouse, crash cleanup) and `MockTerminal` (testing).
154215
155216 ## Updating gh-pages
156217
README.md+1−0
@@ -66,6 +66,7 @@ cel.viewport(() =>
6666 - **Uncontrolled by default** — focus and scroll just work. Opt into controlled mode when needed.
6767 - **Style inheritance** — containers propagate styles to descendants. `bgColor` fills the rect.
6868 - **Cell buffer rendering** — styled cells, differential updates, synchronized output.
69+- **Kitty keyboard protocol** — unambiguous key input with full modifier support. Requires a [compatible terminal](https://sw.kovidgoyal.net/kitty/keyboard-protocol/#progressive-enhancement) (Kitty, WezTerm, Ghostty, foot, Alacritty, Windows Terminal).
6970
7071 ## Packages
7172
TODO.md+20−8
@@ -10,22 +10,34 @@ Remaining work, known bugs, and planned improvements.
1010
1111 ---
1212
13-## API Improvements
13+## Bugs / Spec Violations
1414
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.
15+- 🔧 **TextInput cursor movement doesn't handle multi-codepoint graphemes** — `deleteBackward`/`deleteForward` in `text-edit.ts` operate on single string indices. For multi-codepoint characters (emoji ZWJ sequences, combining marks), this leaves the cursor mid-grapheme. `moveCursor` has the same issue.
1616
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.
17+- 🔧 **Controlled-focus TextInput traps Tab traversal** — When a controlled-focus TextInput (`focused` prop provided) is the first focusable element, Tab from unfocused state always focuses it. Once focused, Tab is consumed as an editing key. Escape unfocuses it, but the next Tab re-focuses it again — the user can never Tab past it to reach subsequent focusable elements. Visible in `examples/pet.ts` on the create screen: the name TextInput prevents keyboard access to the Create Pet button. …
18+
19+- 🔧 **Scrollbar thumb position ignores padding** — `paintScrollbar` in `paint.ts` computes `maxOffset = contentHeight - rect.height` without accounting for container padding, while the scroll clamping logic uses `contentHeight + padY - rect.height`. For padded scrollable containers the thumb position is slightly off.
20+
21+- 🔧 **Duplicate max scroll offset calculation** — `getMaxScrollOffset` in `cel.ts` and `computeMaxScrollOffset` in `paint.ts` implement the same logic. Should be extracted to a shared function.
22+
23+- 🔧 **Key events leak through layers** — When no element is focused and the topmost layer's root has no `onKeyPress`, `handleKeyEvent` falls through to lower layers. Mouse input stops at the topmost layer with a node at the event position, but keyboard input doesn't follow the same rule. A modal overlay without its own root `onKeyPress` would leak keys to the base layer, breaking the "events target the topmost layer" principle.
24+
25+- 🔧 **`space-between` + `gap` double-spaces children** — When both `justifyContent: "space-between"` and `gap` are set, children get `gap` spacing plus the distributed remaining space on top. The remaining-space calculation subtracts `totalGap` first, then `space-between` distributes what's left as extra gap — so the effective gap is `gap + betweenGaps[i]`. CSS flex doesn't stack `space-between` on top of `gap` this way. The spec doesn't define this interaction.
1826
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.
27+---
28+
29+## API Improvements
30+
31+- ❌ **`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.
2032
2133 ## Not Yet Implemented
2234
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.
2535 - ❌ Bracketed paste mode support
26-- ❌ Kitty keyboard protocol detection
36+
37+- ❌ **Markdown heading inline styling** — Headings (`#`, `##`, `###`) still strip inline formatting to plain text. Since headings are short and single-line, this is low priority. Paragraphs, list items, and blockquotes now render inline formatting via wrapping HStack.
2738
2839 ## Future Enhancements
2940
30-- 💡 Additional example apps (chat UI, text editor from spec reference examples)
41+- 💡 Additional example apps (text editor from spec reference example)
3142 - 💡 `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)
43+- 💡 Higher Kitty protocol levels — key-release events (level 2), associated text (level 3), and full event types (level 4) for advanced input patterns (games, physical key layout awareness)
bun.lock+11−1
@@ -7,7 +7,6 @@
77 "devDependencies": {
88 "@biomejs/biome": "^2.4.10",
99 "@types/bun": "^1.3.11",
10- "get-east-asian-width": "^1.5.0",
1110 "lefthook": "^2.1.4",
1211 "mitata": "^1.0.34",
1312 "prettier": "^3.8.1",
@@ -22,6 +21,7 @@
2221 "dependencies": {
2322 "@cel-tui/core": "workspace:*",
2423 "@cel-tui/types": "workspace:*",
24+ "yoctomarkdown": "^0.1.0",
2525 },
2626 "peerDependencies": {
2727 "typescript": ">=5.0.0",
@@ -91,6 +91,8 @@
9191
9292 "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
9393
94+ "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
95+
9496 "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
9597
9698 "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
@@ -141,6 +143,10 @@
141143
142144 "punycode.js": ["punycode.js@2.3.1", "", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
143145
146+ "string-width": ["string-width@8.2.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw=="],
147+
148+ "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
149+
144150 "typedoc": ["typedoc@0.28.18", "", { "dependencies": { "@gerrit0/mini-shiki": "^3.23.0", "lunr": "^2.3.9", "markdown-it": "^14.1.1", "minimatch": "^10.2.4", "yaml": "^2.8.2" }, "peerDependencies": { "typescript": "5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x || 5.6.x || 5.7.x || 5.8.x || 5.9.x || 6.0.x" }, "bin": { "typedoc": "bin/typedoc" } }, "sha512-NTWTUOFRQ9+SGKKTuWKUioUkjxNwtS3JDRPVKZAXGHZy2wCA8bdv2iJiyeePn0xkmK+TCCqZFT0X7+2+FLjngA=="],
145151
146152 "typedoc-plugin-markdown": ["typedoc-plugin-markdown@4.11.0", "", { "peerDependencies": { "typedoc": "0.28.x" } }, "sha512-2iunh2ALyfyh204OF7h2u0kuQ84xB3jFZtFyUr01nThJkLvR8oGGSSDlyt2gyO4kXhvUxDcVbO0y43+qX+wFbw=="],
@@ -152,5 +158,9 @@
152158 "undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
153159
154160 "yaml": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="],
161+
162+ "yoctocolors": ["yoctocolors@2.1.2", "", {}, "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug=="],
163+
164+ "yoctomarkdown": ["yoctomarkdown@0.1.0", "", { "dependencies": { "string-width": "^8.2.0", "strip-ansi": "^7.2.0", "yoctocolors": "^2.1.2" }, "peerDependencies": { "typescript": "^5.9.3" }, "bin": { "yoctomarkdown": "src/cli.ts" } }, "sha512-N5ccZ2dQA3ZJSbImSeSxqfDHC/aBcyPWc5WI57corl4gB2Vsr4W11jswPhVNNI6R49ajFDNBNLLIqJTp5KtcQA=="],
155165 }
156166 }
docs/skill/cel-tui/SKILL.md+24−1
@@ -95,10 +95,33 @@ HStack(
9595
9696 ### Scrollable list
9797
98+Scroll is **uncontrolled by default** — the framework manages scroll position internally. Mouse wheel just works:
99+
98100 ```ts
99101 VStack({ overflow: "scroll", scrollbar: true }, [...items]);
100102 ```
101103
104+Provide `scrollOffset` + `onScroll` to opt into **controlled mode** — you own the state:
105+
106+```ts
107+let offset = 0;
108+
109+VStack(
110+ {
111+ overflow: "scroll",
112+ scrollbar: true,
113+ scrollOffset: offset,
114+ onScroll: (newOffset) => {
115+ offset = newOffset;
116+ cel.render();
117+ },
118+ },
119+ [...items],
120+);
121+```
122+
123+Controlled mode enables patterns like auto-scroll to bottom on new content.
124+
102125 ### Layers (modals)
103126
104127 Return an array from the render function — layers composite bottom-to-top:
@@ -197,7 +220,7 @@ mySelect.reset(); // clear filter/highlight programmatically
197220 - **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
198221 - **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
199222 - **Always call `cel.stop()` before `process.exit()`** — restores raw mode, mouse tracking, and alternate screen.
200-- **Alt key combos** (`alt+x`, `alt+up`) are not yet implemented in key parsing. Use `ctrl+` modifiers instead.
223+- **Kitty keyboard protocol required** — the framework requires the Kitty keyboard protocol (level 1). All modifier combos (`alt+x`, `ctrl+plus`, `shift+enter`) are fully supported. The terminal must support this protocol (Kitty, WezTerm, Ghostty, foot, Alacritty, Windows Terminal). macOS Terminal.app and older xterm are not supported.
201224 - **Button limitations** — `Button` from `@cel-tui/components` does not forward `focusStyle`, container sizing, or all style props. Use `HStack` + `Text` directly when you need full control.
202225
203226 ## Composing Components
docs/skill/cel-tui/references/api.md+27−0
@@ -35,6 +35,33 @@ All props accepted by `VStack` and `HStack`:
3535 }
3636 ```
3737
38+## Scroll
39+
40+Scroll supports **uncontrolled** (default) and **controlled** modes, mirroring the focus model:
41+
42+```ts
43+// Uncontrolled — framework manages scroll position. Mouse wheel just works.
44+VStack({ overflow: "scroll", scrollbar: true }, [...items]);
45+
46+// Controlled — app owns scroll state.
47+VStack(
48+ {
49+ overflow: "scroll",
50+ scrollbar: true,
51+ scrollOffset: offset,
52+ onScroll: (newOffset) => {
53+ offset = newOffset;
54+ cel.render();
55+ },
56+ },
57+ [...items],
58+);
59+```
60+
61+- Scroll direction follows the container’s main axis: VStack → vertical, HStack → horizontal.
62+- Scroll is pointer-driven (mouse wheel), not focus-driven. A user can type in a focused widget while scrolling a different container.
63+- In controlled mode, the UI only moves when the app passes the updated `scrollOffset` back. `onScroll` fires with the clamped new offset.
64+
3865 ## Text Props
3966
4067 ```ts
examples/chat.ts+300−0
@@ -0,0 +1,300 @@
1+/**
2+ * cel-tui: Agentic Chat UI
3+ *
4+ * A simulated agentic chat interface showcasing the full API:
5+ * - Markdown rendering in streamed agent responses
6+ * - TextInput with controlled focus
7+ * - Scrollable message history
8+ * - Button with focusStyle
9+ * - Divider, Spacer components
10+ * - Key bindings (Ctrl+Q quit, Escape/Tab focus traversal)
11+ *
12+ * The agent responses are simulated — characters stream in one by
13+ * one with a small delay, exercising the Markdown component's
14+ * streaming behavior.
15+ *
16+ * Run: bun run examples/chat.ts
17+ */
18+
19+import {
20+ cel,
21+ VStack,
22+ HStack,
23+ Text,
24+ TextInput,
25+ ProcessTerminal,
26+} from "@cel-tui/core";
27+import { Button, Divider, Markdown, Spacer } from "@cel-tui/components";
28+
29+// ─── Simulated Agent Responses ──────────────────────────────────
30+
31+const RESPONSES = [
32+ `I'll check that for you.
33+
34+\`\`\`
35+$ ls -la
36+file1.ts
37+file2.ts
38+README.md
39+\`\`\`
40+
41+Found **3 files** in the current directory.`,
42+
43+ `Here's a quick overview:
44+
45+## Project Structure
46+
47+- **file1.ts** — Main entry point
48+- **file2.ts** — Utility functions
49+- **README.md** — Project documentation
50+
51+> All files were last modified today.`,
52+
53+ `Sure, I can help with that. Here's a code snippet:
54+
55+\`\`\`ts
56+function greet(name: string): string {
57+ return \`Hello, \${name}!\`;
58+}
59+
60+console.log(greet("world"));
61+\`\`\`
62+
63+This defines a simple \`greet\` function that returns a formatted string.
64+
65+---
66+
67+Let me know if you need anything else!`,
68+
69+ `Here's what I found:
70+
71+### Summary
72+
73+1. The project uses **TypeScript** with strict mode
74+2. Dependencies are managed via \`bun\`
75+3. Tests use the built-in \`bun test\` runner
76+
77+> The codebase follows conventional commits and has pre-commit hooks.
78+
79+Everything looks good!`,
80+];
81+
82+// ─── State ──────────────────────────────────────────────────────
83+
84+interface Message {
85+ role: "user" | "agent";
86+ content: string;
87+ streaming?: boolean;
88+}
89+
90+let messages: Message[] = [];
91+let input = "";
92+let inputFocused = true;
93+let responseIndex = 0;
94+let streamTimer: ReturnType<typeof setTimeout> | null = null;
95+let streamSource = "";
96+let streamPos = 0;
97+let scrollOffset = 0;
98+let stickToBottom = true;
99+
100+// ─── Helpers ────────────────────────────────────────────────────
101+
102+const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
103+let spinnerTick = 0;
104+let spinnerTimer: ReturnType<typeof setInterval> | null = null;
105+
106+function startSpinner() {
107+ stopSpinner();
108+ spinnerTimer = setInterval(() => {
109+ spinnerTick++;
110+ cel.render();
111+ }, 80);
112+}
113+
114+function stopSpinner() {
115+ if (spinnerTimer) {
116+ clearInterval(spinnerTimer);
117+ spinnerTimer = null;
118+ }
119+}
120+
121+function isStreaming(): boolean {
122+ return streamTimer !== null;
123+}
124+
125+function streamNextChar() {
126+ const agentMsg = messages[messages.length - 1];
127+ if (!agentMsg || agentMsg.role !== "agent") return;
128+
129+ if (streamPos < streamSource.length) {
130+ // Stream a few characters at a time for speed
131+ const chunk = streamSource.slice(streamPos, streamPos + 3);
132+ streamPos += chunk.length;
133+ agentMsg.content = streamSource.slice(0, streamPos);
134+ cel.render();
135+ streamTimer = setTimeout(streamNextChar, 15);
136+ } else {
137+ // Done streaming
138+ agentMsg.streaming = false;
139+ streamTimer = null;
140+ stopSpinner();
141+ cel.render();
142+ }
143+}
144+
145+function handleSend() {
146+ const text = input.trim();
147+ if (text.length === 0 || isStreaming()) return;
148+
149+ // Add user message
150+ messages.push({ role: "user", content: text });
151+ input = "";
152+ stickToBottom = true;
153+
154+ // Pick a response and start streaming
155+ streamSource = RESPONSES[responseIndex % RESPONSES.length]!;
156+ responseIndex++;
157+ streamPos = 0;
158+ messages.push({ role: "agent", content: "", streaming: true });
159+
160+ startSpinner();
161+ streamTimer = setTimeout(streamNextChar, 300);
162+ cel.render();
163+}
164+
165+function handleChange(value: string) {
166+ input = value;
167+ cel.render();
168+}
169+
170+function quit() {
171+ stopSpinner();
172+ if (streamTimer) clearTimeout(streamTimer);
173+ cel.stop();
174+ process.exit(0);
175+}
176+
177+// ─── Message Rendering ──────────────────────────────────────────
178+
179+function renderMessage(msg: Message, idx: number) {
180+ const isUser = msg.role === "user";
181+ const icon = isUser ? "▶" : "▷";
182+ const label = isUser ? "You" : "Agent";
183+ const color = isUser ? "blue" : "green";
184+
185+ const spinner =
186+ msg.streaming && msg.content.length > 0
187+ ? ` ${spinnerFrames[spinnerTick % spinnerFrames.length]}`
188+ : "";
189+
190+ return VStack({ gap: 0 }, [
191+ // Role header
192+ HStack({ gap: 1 }, [
193+ Text(`${icon} ${label}${spinner}`, { bold: true, fgColor: color }),
194+ ]),
195+
196+ // Content
197+ ...(isUser
198+ ? [Text(` ${msg.content}`, { wrap: "word" })]
199+ : msg.content.length > 0
200+ ? Markdown(msg.content).map((node) => {
201+ // Indent agent content by wrapping in a padded container
202+ if (node.type === "text" && node.content === "") return node;
203+ return HStack({}, [Text(" "), VStack({ flex: 1 }, [node])]);
204+ })
205+ : [
206+ Text(
207+ ` ${spinnerFrames[spinnerTick % spinnerFrames.length]} thinking...`,
208+ { fgColor: "brightBlack", italic: true },
209+ ),
210+ ]),
211+ ]);
212+}
213+
214+// ─── UI ─────────────────────────────────────────────────────────
215+
216+cel.init(new ProcessTerminal());
217+
218+cel.viewport(() =>
219+ VStack(
220+ {
221+ height: "100%",
222+ fgColor: "white",
223+ onKeyPress: (key) => {
224+ if (key === "ctrl+q" || key === "ctrl+c") quit();
225+ },
226+ },
227+ [
228+ // ── Header ──
229+ HStack({ height: 1, padding: { x: 1 }, bgColor: "blue" }, [
230+ Text(" Agent ", { bold: true, fgColor: "white", bgColor: "blue" }),
231+ Spacer(),
232+ Text("model: gpt-4", { fgColor: "brightBlack" }),
233+ ]),
234+ Divider({ fgColor: "brightBlack" }),
235+
236+ // ── Message History ──
237+ VStack(
238+ {
239+ flex: 1,
240+ overflow: "scroll",
241+ scrollbar: true,
242+ padding: { x: 1 },
243+ scrollOffset: stickToBottom ? Infinity : scrollOffset,
244+ onScroll: (offset, maxOffset) => {
245+ scrollOffset = offset;
246+ stickToBottom = offset >= maxOffset;
247+ cel.render();
248+ },
249+ },
250+ messages.length > 0
251+ ? messages.flatMap((msg, i) => [
252+ ...(i > 0 ? [Text("")] : []),
253+ renderMessage(msg, i),
254+ ])
255+ : [
256+ Spacer(),
257+ VStack({ alignItems: "center" }, [
258+ Text("No messages yet.", {
259+ fgColor: "brightBlack",
260+ italic: true,
261+ }),
262+ Text("Type a message below to start.", {
263+ fgColor: "brightBlack",
264+ }),
265+ ]),
266+ Spacer(),
267+ ],
268+ ),
269+
270+ // ── Input Area ──
271+ Divider({ fgColor: "brightBlack" }),
272+ HStack({ padding: { x: 1 }, gap: 1 }, [
273+ Text(">", { fgColor: "cyan", bold: true }),
274+ TextInput({
275+ flex: 1,
276+ maxHeight: 5,
277+ value: input,
278+ onChange: handleChange,
279+ placeholder: Text("type a message...", { fgColor: "brightBlack" }),
280+ onSubmit: handleSend,
281+ focused: inputFocused,
282+ onFocus: () => {
283+ inputFocused = true;
284+ cel.render();
285+ },
286+ onBlur: () => {
287+ inputFocused = false;
288+ cel.render();
289+ },
290+ }),
291+ Button(" Send ", {
292+ onClick: handleSend,
293+ bgColor: "brightBlack",
294+ bold: true,
295+ focusStyle: { bgColor: "cyan", fgColor: "black" },
296+ }),
297+ ]),
298+ ],
299+ ),
300+);
examples/pet.ts+67−75
@@ -21,7 +21,7 @@ import {
2121 TextInput,
2222 ProcessTerminal,
2323 } from "@cel-tui/core";
24-import { Button, Divider, Spacer } from "@cel-tui/components";
24+import { Button, Divider, Spacer, VDivider } from "@cel-tui/components";
2525
2626 // ─── Pet Definitions ────────────────────────────────────────────
2727
@@ -491,32 +491,32 @@ function createView() {
491491 },
492492 }),
493493
494- // Species picker
494+ // Species picker — wrapping chips
495495 Text(""),
496496 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();
497+ HStack(
498+ { flexWrap: "wrap", gap: 1 },
499+ PETS.map((p, i) => {
500+ const sel = i === selectedKind;
501+ return HStack(
502+ {
503+ onClick: () => {
504+ selectedKind = i;
505+ cel.render();
506+ },
507+ focusable: false,
504508 },
505- focusable: false,
506- },
507- [
508- Text(sel ? " > " : " ", {
509- fgColor: sel ? "cyan" : "brightBlack",
510- bold: sel,
511- }),
512- Text(p.kind, {
513- fgColor: sel ? "cyan" : "white",
514- bold: sel,
515- }),
516- ],
517- );
518- }),
519- Text(" ↑/↓ to change", {
509+ [
510+ Text(sel ? ` ● ${p.kind} ` : ` ${p.kind} `, {
511+ fgColor: sel ? "black" : "white",
512+ bgColor: sel ? "cyan" : undefined,
513+ bold: sel,
514+ }),
515+ ],
516+ );
517+ }),
518+ ),
519+ Text(" ↑/↓ to change", {
520520 fgColor: "brightBlack",
521521 italic: true,
522522 }),
@@ -536,22 +536,24 @@ function createView() {
536536
537537 // Create button — uncontrolled focus + focusStyle
538538 HStack({ justifyContent: "center" }, [
539- HStack(
540- {
541- onClick: startGame,
542- fgColor: "green",
543- focusStyle: { bgColor: "green", fgColor: "black" },
544- },
545- [Text(" Create Pet! ", { bold: true })],
546- ),
539+ Button(" Create Pet! ", {
540+ onClick: startGame,
541+ fgColor: "green",
542+ bold: true,
543+ focusStyle: { bgColor: "green", fgColor: "black" },
544+ }),
547545 ]),
548546
549- // Hints
550- HStack({ justifyContent: "center" }, [
551- Text("Tab", { fgColor: "brightBlack", bold: true }),
552- Text(" navigate ", { fgColor: "brightBlack" }),
553- Text("Ctrl+Q", { fgColor: "brightBlack", bold: true }),
554- Text(" quit", { fgColor: "brightBlack" }),
547+ // Hints — wrapping for narrow terminals
548+ HStack({ justifyContent: "center", flexWrap: "wrap", gap: 1 }, [
549+ HStack({}, [
550+ Text("Tab", { fgColor: "brightBlack", bold: true }),
551+ Text(" navigate", { fgColor: "brightBlack" }),
552+ ]),
553+ HStack({}, [
554+ Text("Ctrl+Q", { fgColor: "brightBlack", bold: true }),
555+ Text(" quit", { fgColor: "brightBlack" }),
556+ ]),
555557 ]),
556558 ]),
557559 Spacer(),
@@ -602,22 +604,18 @@ function mainView() {
602604 ),
603605 Text(""),
604606 HStack({ gap: 3 }, [
605- HStack(
606- {
607- onClick: feed,
608- fgColor: "yellow",
609- focusStyle: { bgColor: "yellow", fgColor: "black" },
610- },
611- [Text(" Feed ", { bold: true })],
612- ),
613- HStack(
614- {
615- onClick: petIt,
616- fgColor: "magenta",
617- focusStyle: { bgColor: "magenta", fgColor: "black" },
618- },
619- [Text(" Pet ", { bold: true })],
620- ),
607+ Button(" Feed ", {
608+ onClick: feed,
609+ fgColor: "yellow",
610+ bold: true,
611+ focusStyle: { bgColor: "yellow", fgColor: "black" },
612+ }),
613+ Button(" Pet ", {
614+ onClick: petIt,
615+ fgColor: "magenta",
616+ bold: true,
617+ focusStyle: { bgColor: "magenta", fgColor: "black" },
618+ }),
621619 ]),
622620 ],
623621 );
@@ -663,9 +661,7 @@ function mainView() {
663661 // Wide: sidebar | pet side-by-side
664662 HStack({ flex: 1 }, [
665663 statsPanel,
666- VStack({ width: 1, height: "100%" }, [
667- Text("│", { repeat: "fill", fgColor: "brightBlack" }),
668- ]),
664+ VDivider({ fgColor: "brightBlack" }),
669665 petPane,
670666 ]),
671667 ]),
@@ -811,25 +807,21 @@ function deadView() {
811807 }),
812808 Text(""),
813809 HStack({ gap: 3 }, [
814- HStack(
815- {
816- onClick: restart,
817- fgColor: "green",
818- focusStyle: { bgColor: "green", fgColor: "black" },
819- },
820- [Text(" New Pet ", { bold: true })],
821- ),
822- HStack(
823- {
824- onClick: () => {
825- showLog = !showLog;
826- cel.render();
827- },
828- fgColor: "cyan",
829- focusStyle: { bgColor: "cyan", fgColor: "black" },
810+ Button(" New Pet ", {
811+ onClick: restart,
812+ fgColor: "green",
813+ bold: true,
814+ focusStyle: { bgColor: "green", fgColor: "black" },
815+ }),
816+ Button(" View Log ", {
817+ onClick: () => {
818+ showLog = !showLog;
819+ cel.render();
830820 },
831- [Text(" View Log ", { bold: true })],
832- ),
821+ fgColor: "cyan",
822+ bold: true,
823+ focusStyle: { bgColor: "cyan", fgColor: "black" },
824+ }),
833825 ]),
834826 HStack({}, [
835827 Text("Ctrl+Q", { fgColor: "brightBlack", bold: true }),
examples/simple-scroll.ts+13−18
@@ -2,9 +2,13 @@
22 * Scroll test — a large list inside a scrollable VStack.
33 * Mouse wheel should scroll the list up/down.
44 *
5- * Run: bun run examples/scroll-test.ts
5+ * Uses uncontrolled scroll — the framework manages scroll position
6+ * internally. No scrollOffset/onScroll state needed.
7+ *
8+ * Run: bun run examples/simple-scroll.ts
69 */
710 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
11+import { Divider, Spacer } from "@cel-tui/components";
812
913 const MIN_COLS = 30;
1014 const MIN_ROWS = 8;
@@ -39,8 +43,6 @@ function fake(): string {
3943 ).join(" ");
4044 }
4145
42-let scrollOffset = 0;
43-
4446 function quit() {
4547 cel.stop();
4648 process.exit();
@@ -87,22 +89,13 @@ cel.viewport(() => {
8789 [
8890 HStack({ padding: { x: 1 } }, [
8991 Text("Scroll Test", { bold: true, fgColor: "cyan" }),
90- VStack({ flex: 1 }, []),
91- Text(`offset: ${scrollOffset}`, { fgColor: "brightBlack" }),
92+ Spacer(),
93+ Text("uncontrolled", { fgColor: "brightBlack" }),
9294 ]),
93- Text("─", { repeat: "fill", fgColor: "brightBlack" }),
95+ Divider({ fgColor: "brightBlack" }),
9496
9597 VStack(
96- {
97- flex: 1,
98- overflow: "scroll",
99- scrollbar: true,
100- scrollOffset,
101- onScroll: (off) => {
102- scrollOffset = off;
103- cel.render();
104- },
105- },
98+ { flex: 1, overflow: "scroll", scrollbar: true },
10699 items.map((item, i) =>
107100 HStack({ padding: { x: 1 } }, [
108101 Text(`${String(i + 1).padStart(3)}.`, { fgColor: "yellow" }),
@@ -111,9 +104,11 @@ cel.viewport(() => {
111104 ),
112105 ),
113106
114- Text("─", { repeat: "fill", fgColor: "brightBlack" }),
107+ Divider({ fgColor: "brightBlack" }),
115108 HStack({ padding: { x: 1 } }, [
116- Text("Mouse wheel to scroll · Ctrl+Q quit", { fgColor: "brightBlack" }),
109+ Text("Mouse wheel to scroll · Ctrl+Q quit", {
110+ fgColor: "brightBlack",
111+ }),
117112 ]),
118113 ],
119114 );
examples/tags.ts+189−0
@@ -0,0 +1,189 @@
1+/**
2+ * cel-tui: Tag Cloud
3+ *
4+ * Demonstrates `flexWrap: "wrap"` on HStack — tags flow
5+ * left-to-right and wrap to the next line when they exceed
6+ * the terminal width. Resize the terminal to see tags reflow.
7+ *
8+ * Click or press Enter to toggle tags. Tab/Shift+Tab to
9+ * navigate. Ctrl+Q to quit.
10+ *
11+ * Run: bun run examples/tags.ts
12+ */
13+
14+import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
15+import { Button, Divider, Spacer } from "@cel-tui/components";
16+
17+// ─── Data ───────────────────────────────────────────────────────
18+
19+interface Tag {
20+ label: string;
21+ color: "cyan" | "magenta" | "yellow" | "green" | "blue" | "red";
22+}
23+
24+const TAGS: Tag[] = [
25+ { label: "TypeScript", color: "blue" },
26+ { label: "Rust", color: "red" },
27+ { label: "Go", color: "cyan" },
28+ { label: "Python", color: "yellow" },
29+ { label: "JavaScript", color: "yellow" },
30+ { label: "C++", color: "blue" },
31+ { label: "Zig", color: "magenta" },
32+ { label: "Haskell", color: "magenta" },
33+ { label: "Elixir", color: "magenta" },
34+ { label: "Ruby", color: "red" },
35+ { label: "Kotlin", color: "green" },
36+ { label: "Swift", color: "red" },
37+ { label: "Lua", color: "blue" },
38+ { label: "OCaml", color: "yellow" },
39+ { label: "Clojure", color: "green" },
40+ { label: "Scala", color: "red" },
41+ { label: "Nim", color: "yellow" },
42+ { label: "Julia", color: "green" },
43+ { label: "Erlang", color: "red" },
44+ { label: "Dart", color: "cyan" },
45+ { label: "C#", color: "green" },
46+ { label: "F#", color: "cyan" },
47+ { label: "Gleam", color: "magenta" },
48+ { label: "Odin", color: "blue" },
49+];
50+
51+// ─── State ──────────────────────────────────────────────────────
52+
53+const selected = new Set<string>();
54+
55+function toggle(label: string) {
56+ if (selected.has(label)) selected.delete(label);
57+ else selected.add(label);
58+ cel.render();
59+}
60+
61+function clearAll() {
62+ selected.clear();
63+ cel.render();
64+}
65+
66+function quit() {
67+ cel.stop();
68+ process.exit();
69+}
70+
71+// ─── UI ─────────────────────────────────────────────────────────
72+
73+function tagChip(tag: Tag) {
74+ const on = selected.has(tag.label);
75+ const check = on ? "✓ " : " ";
76+ return Button(` ${check}${tag.label} `, {
77+ onClick: () => toggle(tag.label),
78+ fgColor: on ? "black" : tag.color,
79+ bgColor: on ? tag.color : undefined,
80+ bold: on,
81+ focusStyle: {
82+ fgColor: "black",
83+ bgColor: tag.color,
84+ bold: true,
85+ },
86+ });
87+}
88+
89+cel.init(new ProcessTerminal());
90+
91+cel.viewport(() => {
92+ const cols = process.stdout.columns || 80;
93+ const selTags = TAGS.filter((t) => selected.has(t.label));
94+
95+ return VStack(
96+ {
97+ height: "100%",
98+ padding: { x: 2, y: 1 },
99+ fgColor: "white",
100+ onKeyPress: (key) => {
101+ if (key === "ctrl+q" || key === "ctrl+c") quit();
102+ if (key === "ctrl+r") clearAll();
103+ },
104+ },
105+ [
106+ // Header
107+ HStack({ gap: 1 }, [
108+ Text("◆", { fgColor: "cyan", bold: true }),
109+ Text("Pick your languages", { bold: true, fgColor: "white" }),
110+ Text(`(${selected.size}/${TAGS.length})`, {
111+ fgColor: "brightBlack",
112+ }),
113+ ]),
114+ Text("Tab navigate · Enter toggle · resize to reflow", {
115+ fgColor: "brightBlack",
116+ italic: true,
117+ }),
118+ Divider({ fgColor: "brightBlack" }),
119+
120+ // Tag cloud — the flexWrap showcase
121+ HStack(
122+ { flexWrap: "wrap", gap: 1, padding: { y: 1 } },
123+ TAGS.map(tagChip),
124+ ),
125+
126+ Divider({ fgColor: "brightBlack" }),
127+
128+ // Selection summary
129+ ...(selTags.length > 0
130+ ? [
131+ Text("Selected:", { bold: true, fgColor: "brightBlack" }),
132+ HStack(
133+ { flexWrap: "wrap", gap: 1 },
134+ selTags.map((t) =>
135+ Text(` ${t.label} `, {
136+ fgColor: "black",
137+ bgColor: t.color,
138+ bold: true,
139+ }),
140+ ),
141+ ),
142+ ]
143+ : [
144+ Text("No languages selected yet.", {
145+ fgColor: "brightBlack",
146+ italic: true,
147+ }),
148+ ]),
149+
150+ Spacer(),
151+
152+ // Footer hints — also wrapping
153+ HStack({ flexWrap: "wrap", gap: 1 }, [
154+ HStack({ gap: 0 }, [
155+ Text(" Tab ", {
156+ bgColor: "brightBlack",
157+ fgColor: "black",
158+ bold: true,
159+ }),
160+ Text(" navigate", { fgColor: "brightBlack" }),
Cut short: this commit's diff is over 1000 lines.
knip.json+23−0
Cut short: this commit's diff is over 1000 lines.
package.json+0−1
Cut short: this commit's diff is over 1000 lines.
packages/components/package.json+5−3
Cut short: this commit's diff is over 1000 lines.
packages/components/src/button.ts+48−14
Cut short: this commit's diff is over 1000 lines.
packages/components/src/index.ts+9−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/markdown.test.ts+337−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/markdown.ts+283−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/vdivider.ts+50−0
Cut short: this commit's diff is over 1000 lines.
packages/core/package.json+3−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.test.ts+178−49
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.ts+154−21
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.test.ts+29−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.ts+6−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/hit-test.test.ts+51−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/hit-test.ts+48−3
Cut short: this commit's diff is over 1000 lines.
packages/core/src/keys.test.ts+273−36
Cut short: this commit's diff is over 1000 lines.
packages/core/src/keys.ts+181−74
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.test.ts+441−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.ts+289−4
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+128−8
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.ts+85−40
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+12−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/test-helpers.ts+122−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-edit.ts+0−23
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-input.test.ts+70−9
Cut short: this commit's diff is over 1000 lines.
packages/types/package.json+1−1
Cut short: this commit's diff is over 1000 lines.
packages/types/src/index.ts+16−1
Cut short: this commit's diff is over 1000 lines.
spec.md+110−29
Cut short: this commit's diff is over 1000 lines.