xonecas.io
70160
Ce

cel-tui / commit 0b562f7

Merge branch 'main' into gh-pages

xonecas2026-04-11 0b562f7e6ef4714e6324d16018cd997c4e9e5d95 parent 744a926parent 34b6b7e

57 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−30
@@ -29,7 +29,7 @@ Dependency chain: `components → core → types`
2929 - **Cell buffer rendering:** Layout writes to a 2D grid of styled cells, not raw strings. Clipping and layer compositing are cell writes. Diff against previous buffer for minimal terminal output.
3030 - **Reactive rendering:** `cel.render()` batches via `process.nextTick()`. No fixed FPS.
3131 - **Layers:** `cel.viewport(() => [layer1, layer2])` — array of independent viewport-sized trees, composited bottom-to-top. Conditional inclusion = show/hide.
32-- **Key bubbling:** Unconsumed keys bubble up from focused element through ancestors. Root `onKeyPress` = global handler.
32+- **Key bubbling:** Unconsumed keys bubble up from focused element through ancestors. Root `onKeyPress` = global handler. Escape blur is a fallback default action after bubbling — consuming `escape` prevents blur.
3333 - **Hit detection:** Topmost layer first, deepest node at (x,y), walk up to find handler. Innermost wins for scroll, click, keys.
3434
3535 ## Implementation Status
@@ -39,10 +39,10 @@ All core systems from the spec are implemented and tested:
3939 - **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints (including cross-axis min/max), gap, padding, justifyContent, alignItems, flexWrap, 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** — 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
43-- **TextInput** — grapheme-aware text editing (Intl.Segmenter for emoji/ZWJ), cursor movement, cursor persistence across re-renders (keyed on onChange, clamped on external value changes), auto-scroll to keep cursor visible, inverted-cell cursor with native terminal cursor positioning (blinking), background fill, placeholder rendering
42+- **Input** — Kitty-first keyboard input (Kitty level 1 enable), mixed-stream decoding for CSI u / CSI letter / CSI tilde / recoverable legacy control bytes / ESC-prefixed Alt combos, batched SGR mouse handling, hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter) with uncontrolled and controlled modes, onKeyPress bubbling from focused element through ancestors
43+- **TextInput** — grapheme-aware text editing (Intl.Segmenter for emoji/ZWJ), cursor movement, cursor persistence across re-renders (keyed on onChange, clamped on external value changes), batched key handling with preserved edit state across stdin chunks, auto-scroll to keep cursor visible, inverted-cell cursor with native terminal cursor positioning (blinking), background fill, placeholder rendering
4444 - **Layering** — multi-layer compositing, transparency, topmost-layer input priority
45-- **Terminal** — Kitty keyboard protocol enable/disable, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
45+- **Terminal** — Kitty level 1 enable/disable, mixed keyboard stream compatibility in tmux, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
4646
4747 See `TODO.md` for remaining spec violations and future work.
4848
@@ -71,13 +71,13 @@ Use a tmux session to run examples and visually inspect rendered output.
7171
7272 ### tmux Configuration
7373
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:
74+cel-tui is **Kitty-first**, but `tmux` is a supported environment. tmux 3.2+ should have `extended-keys` enabled so it preserves as much modifier information as possible:
7575
7676 ```
7777 set -s extended-keys on
7878 ```
7979
80-Without this, tmux intercepts the protocol negotiation and key events arrive in legacy format that the framework's parser won't recognize.
80+With that setting enabled, common keyboard-driven checks work well through `tmux send-keys`. Without it, cel-tui still accepts many recoverable legacy encodings, but historically ambiguous collisions remain collapsed by the host (`ctrl+i`/`tab`, `ctrl+m`/`enter`, `ctrl+[`/`escape`).
8181
8282 ### Usage
8383
@@ -91,7 +91,8 @@ tmux send-keys -t cel "cd /home/xonecas/src/cel-tui && bun run examples/hello.ts
9191 # Wait for render, then capture the screen contents
9292 sleep 1; tmux capture-pane -t cel -p
9393
94-# Send keystrokes (e.g., Ctrl+Q to quit)
94+# Send common keystrokes directly
95+# (printable chars, Tab/BTab, Enter, Escape, arrows, many Ctrl+letter combos)
9596 tmux send-keys -t cel C-q
9697
9798 # Resize the window to test different terminal sizes
@@ -101,11 +102,25 @@ tmux resize-window -t cel -x 60 -y 20
101102 tmux kill-session -t cel
102103 ```
103104
104-This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
105+This lets you see exactly what the user sees — rendered cells, alignment, clipping, and, via `capture-pane -e -p`, style escape sequences — without needing a real interactive terminal.
105106
106-### Sending Keys with the Kitty Protocol
107+### Sending Keys in tmux
107108
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+For most keyboard-driven manual checks, plain `tmux send-keys` is now sufficient:
110+
111+```bash
112+# Common cases that work well in tmux with extended-keys on
113+tmux send-keys -t cel a
114+tmux send-keys -t cel Enter
115+tmux send-keys -t cel Escape
116+tmux send-keys -t cel Tab
117+tmux send-keys -t cel BTab
118+tmux send-keys -t cel Up
119+tmux send-keys -t cel C-q
120+tmux send-keys -t cel C-r
121+```
122+
123+Use exact Kitty-style injection only when you need to test protocol-specific sequences or combos that tmux named keys do not express reliably (for example `shift+enter`, `ctrl+plus`, or a precise CSI-u path):
109124
110125 ```bash
111126 # Helper: convert a key name to hex bytes via kittyEncode
@@ -120,39 +135,37 @@ send_key() {
120135 }
121136
122137 # 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
138+send_key "ctrl+q"
139+send_key "shift+enter"
140+send_key "ctrl+plus"
141+send_key "shift+tab"
130142 ```
131143
132-**Limitations:** The helper lowercases all input, so uppercase letters aren't testable this way.
144+**Limitations:** the helper lowercases printable input, so uppercase-text insertion is still better tested with plain `tmux send-keys` or in a real terminal.
133145
134-**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.
146+**Caveat:** `tmux send-keys -H` injects raw bytes one event at a time, while real terminals may batch multiple keyboard or mouse events into a single stdin chunk. Use hex injection to target exact encodings, not to simulate full terminal behavior.
135147
136148 ### Mouse Events Don't Work in tmux
137149
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.
150+SGR mouse events (click, scroll) sent through tmux remain **unreliable** and should not be used for verification. Even with correctly formatted SGR 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 tmux limitation around raw mouse protocol injection.
139151
140-**Do not test mouse interactions (click, scroll) through tmux.** Use tmux only for:
152+**Do not treat tmux as authoritative for mouse interactions (click, scroll).** Use tmux for:
141153
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
154+- Keyboard-driven testing via plain `tmux send-keys` for common keys
155+- Exact keyboard-sequence injection via `send_key` when you need protocol precision
156+- Visual inspection via `tmux capture-pane -p` / `tmux capture-pane -e -p`
157+- Verifying layout, alignment, text content, and many keyboard flows
145158
146-Mouse and scroll behavior must be verified in a real interactive terminal.
159+Mouse and scroll behavior still need verification in a real interactive terminal.
147160
148161 ### tmux capture-pane Limitations
149162
150163 `tmux capture-pane -p` captures **plain text only** — no colors or style attributes. This means:
151164
152165 - You can verify text content, alignment, and layout structure
153-- You **cannot** verify `fgColor`, `bgColor`, `bold`, `focusStyle` changes, or any visual styling
166+- You **cannot** verify `fgColor`, `bgColor`, `bold`, or `focusStyle` changes from plain-text capture alone
154167
155-To inspect colors, use `tmux capture-pane -e -p` (includes escape sequences) or verify styling through unit tests against the cell buffer.
168+To inspect styling, use `tmux capture-pane -e -p` (includes escape sequences) or verify style output through unit tests against the cell buffer.
156169
157170 ## Spec
158171
@@ -203,15 +216,15 @@ chore: scaffold monorepo with types, core, components packages
203216
204217 ## Architecture Notes
205218
206-- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Mouse input handles batched SGR events (terminals often send multiple events in a single data chunk). TextInput key handling: `onKeyPress` fires before built-in editing logic — returning `false` prevents the …
219+- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Input handling treats stdin as a mixed stream: keyboard chunks may contain multiple decoded key events, mouse input handles batched SGR events, and TextInput batching preserves the latest value/cursor across m …
207220 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
208221 - `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets (clamped to max — apps can pass `Infinity` to mean "scroll to end"), scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state (with cursor screen position export for native cursor), TextInput background fill, container bgColor fill, style inheritance threading, focusStyle resolution.
209222 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both accept an optional `Theme` for color resolution and wrap in CSI 2026 synchronized output. Exports `defaultTheme` (ANSI 16 mapping).
210223 - `hit-test.ts` — `hitTest(root, x, y, getScrollOffset?)` → path from root to deepest node at `(x,y)`, accounting for scroll offsets. `findClickHandler`, `findScrollTarget`, `collectKeyPressHandlers`, `collectFocusable` walk paths.
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.
224+- `keys.ts` — Kitty-first input decoder. `decodeKeyEvents(data)` splits a raw chunk into ordered key events, accepting CSI u / CSI letter / CSI tilde sequences, recoverable legacy ASCII control bytes, ESC-prefixed Alt combos, and raw printable text. Key events carry a normalized semantic `key` plus optional original insertable `text`. `parseKey(data)` remains as a convenience wrapper for single-event cases. `isEditingKey()` identifies non-text editing/navigation keys consumed by TextInput, and …
212225 - `text-edit.ts` — Pure text editing functions (`insertChar`, `deleteBackward`, `deleteForward`, `moveCursor`). Operates on `EditState` (value + cursor position). Uses `Intl.Segmenter` with grapheme granularity for cursor movement and deletion (handles emoji, ZWJ sequences, combining marks). Used by `cel.ts` to handle TextInput key events.
213226 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
214-- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1, SGR mouse, crash cleanup) and `MockTerminal` (testing).
227+- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1 enable, SGR mouse, crash cleanup) and `MockTerminal` (testing). The runtime prefers Kitty semantics but the parser still accepts mixed tmux/legacy keyboard encodings.
215228
216229 ## Updating gh-pages
217230
@@ -323,6 +336,14 @@ bun run typecheck && bun test && bun run check && bun run format
323336 - `get-east-asian-width` is a real dependency of `@cel-tui/core` (installs for consumers)
324337 - `typescript` is a peer dependency (consumers bring their own)
325338
339+## Non-interactive Commands
340+
341+Avoid commands that open an interactive editor or prompt from the agent shell. They can hang the tool.
342+
343+- Always pass messages explicitly for git commands that might invoke `$EDITOR`.
344+- Use `git commit -m "..."` and `git tag -a <tag> -m "..."`.
345+- Do not run bare `git tag <tag>` during release work.
346+
326347 ## Destructive Actions
327348
328349 **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.
README.md+19−8
@@ -1,6 +1,6 @@
11 # cel-tui
22
3-A TypeScript TUI framework built around a declarative functional API and ultra-fast rendering.
3+A TypeScript TUI framework built around a declarative functional API, ultra-fast rendering, and Kitty-first keyboard input that also works well in tmux.
44
55 <p align="center">
66 <picture>
@@ -64,18 +64,29 @@ cel.viewport(() =>
6464 - **Layers** — return an array for multi-layer compositing (modals, overlays).
6565 - **Uncontrolled by default** — focus and scroll just work. Opt into controlled mode when needed.
6666 - **Adaptive wheel scrolling** — scrollables and TextInput use an adaptive mouse-wheel step by default; override it with `scrollStep` when needed.
67+- **Content measurement helper** — `measureContentHeight(node, { width })` lets apps preserve scroll anchors when prepending intrinsically sized content.
68+- **Terminal title helper** — `cel.setTitle("My App")` updates the window/tab title when the host honors OSC titles.
6769 - **Style inheritance** — containers propagate styles to descendants. `bgColor` fills the rect.
6870 - **16-color palette** — numbered slots (`"color00"`–`"color15"`) mapped to ANSI 16 by default. Custom themes can remap to different ANSI indices or 24-bit true color.
6971 - **Cell buffer rendering** — styled cells, differential updates, synchronized output.
70-- **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).
72+- **Kitty-first keyboard input** — cel-tui enables Kitty level 1 for full modifier fidelity, works well in `tmux` with `set -s extended-keys on`, and accepts recoverable legacy encodings when the host does not preserve a pure Kitty stream.
73+- **TextInput editing shortcuts** — focused inputs support familiar readline-style editing (`ctrl+a/e`, `alt+b/f`, `ctrl+left/right`, `ctrl+w`, `alt+d`), and `up` / `down` follow visual wrapped lines.
74+
75+## Terminal Compatibility
76+
77+- **First-class:** Kitty-compatible terminals such as Kitty, WezTerm, Ghostty, foot, Alacritty, and Windows Terminal
78+- **First-class:** `tmux` with `set -s extended-keys on`
79+- **Best effort:** legacy terminals or multiplexers that collapse some modifier distinctions
80+
81+Some historical legacy collisions remain impossible to recover once a host has already collapsed them — for example `ctrl+i` vs `tab`, `ctrl+m` vs `enter`, and `ctrl+[` vs `escape`.
7182
7283 ## Packages
7384
74-| Package | Description |
75-| --------------------- | ------------------------------------------------------------------------- |
76-| `@cel-tui/types` | Shared type definitions |
77-| `@cel-tui/core` | Framework engine and primitives |
78-| `@cel-tui/components` | Pre-made components (Button, Spacer, Divider, VDivider, Select, Markdown) |
85+| Package | Description |
86+| --------------------- | ------------------------------------------------------------------------------------------ |
87+| `@cel-tui/types` | Shared type definitions |
88+| `@cel-tui/core` | Framework engine and primitives |
89+| `@cel-tui/components` | Pre-made components (Button, Spacer, Divider, VDivider, Select, Markdown, SyntaxHighlight) |
7990
8091 ## Documentation
8192
@@ -85,7 +96,7 @@ cel.viewport(() =>
8596
8697 ## Performance
8798
88-cel-tui ships a [benchmark suite](benchmarks/) covering every pipeline stage (layout, paint, cell buffer, ANSI emission, hit testing, key parsing). On a comparable tree, the full end-to-end render completes in **~65 µs** — around 15,000 renders/sec. See [benchmarks/RESULTS.md](benchmarks/RESULTS.md) for detailed numbers and an Ink comparison.
99+cel-tui ships a benchmark suite covering every pipeline stage (layout, paint, cell buffer, ANSI emission, hit testing, key parsing). On a comparable tree, the full end-to-end render completes in **~65 µs** — around 15,000 renders/sec. See [benchmarks/RESULTS.md](benchmarks/RESULTS.md) for detailed numbers and an Ink comparison.
89100
90101 ```bash
91102 bun run bench # run all benchmarks
TODO.md+2−23
@@ -10,44 +10,23 @@ Remaining work, known bugs, and planned improvements.
1010
1111 ---
1212
13-## Bugs / Spec Violations
14-
15-- 🔧 **Streaming wrapped Markdown with inline formatting can corrupt until rendering settles** — high priority. The risky behavior is in `packages/components/src/markdown.ts`: plain paragraphs render as a single `Text(..., { wrap: "word" })`, but formatted paragraphs/list items/blockquote content render as `HStack({ flexWrap: "wrap" })` trees built from split inline spans. During streaming, partial markdown can change shape across renders (for example plain text becoming a formatted span onc …
16-
17-- 🔧 **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.
18-
19-- 🔧 **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.
20-
21-- 🔧 **`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.
22-
23----
24-
2513 ## API Improvements
2614
15+- ❌ **Focus callbacks need reason metadata** — `onFocus`/`onBlur` currently expose only that focus changed, not why. Controlled-focus apps can't distinguish blur caused by `Escape` from blur caused by Tab traversal, mouse clicks, overlay changes, or other focus transitions, which still makes blur-specific behavior awkward.
16+
2717 - ❌ **Define TextInput scroll semantics for cursor-follow and resize** — After the text layout refactor, the framework now has one canonical visual wrapping model, but the behavior contract around TextInput scrolling still needs to be specified. In particular: when a user has manually scrolled away from the cursor, what actions should re-enable automatic cursor-follow (typing, cursor movement, focus changes, programmatic value changes)? And when a TextInput changes height because of intrinsi …
2818
2919 - ❌ **`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.
3020
3121 ## Not Yet Implemented
3222
33-- ❌ Bracketed paste mode support
34-
3523 - ❌ **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.
3624
37-## Toolchain
38-
39-- 🔧 **Biome formatter clashes with Prettier on generic type arguments** — When a chained `.method<TypeArgs>(longString)` call exceeds `lineWidth`, biome's formatter breaks at the function args `(` while prettier breaks at the type args `<`. They never converge. Current config has biome formatter enabled (`indentStyle: "space"`), which means both formatters fight on this pattern. Fix: either disable biome's formatter (set `formatter.enabled: false` — `organizeImports` still works as an err …
40-
4125 ## Future Enhancements
4226
4327 - 💡 **Cursor style/shape customization** — TextInput currently renders the cursor as an inverted cell (block cursor). There's no way to choose bar (`│` between characters), underline, or custom cursor characters. A `cursorStyle` prop on TextInput (`"block" | "bar" | "underline"`) would cover the common cases. The native terminal cursor shape could also be set via DECSCUSR (`CSI q`) sequences to match.
4428
4529 - 💡 **Scrollbar styling** — Scrollbar characters (`┃`/`│` vertical, `━`/`─` horizontal) and colors are hardcoded in `paintScrollbar`. A `scrollbarStyle` prop on containers (or a global theme option) would allow customizing thumb/track characters and colors. Currently the only two visual elements the framework doesn't support styling.
4630
47-- 💡 **Textarea component** (`packages/components`) — A higher-level wrapper around TextInput that handles the autogrowing pattern out of the box. Props like `maxLines`, `minLines`, and `placeholder` would cover the common chat-input / form-field use case without requiring the `HStack + flex + maxHeight` boilerplate. Could also include optional line-count display and character limit.
48-
49-- 💡 **Editor component** (`packages/components`) — A TextInput with a line-number gutter, built as a component. Would compose an HStack with a fixed-width line-number column (styled, right-aligned) alongside a flex TextInput, keeping scroll synchronized. Useful for code/config editing use cases like the markdown editor example.
50-
51-- 💡 Additional example apps (text editor from spec reference example)
5231 - 💡 `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)
5332 - 💡 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)
biome.json+2−2
@@ -1,5 +1,5 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/2.4.10/schema.json",
2+ "$schema": "https://biomejs.dev/schemas/2.4.11/schema.json",
33 "assist": {
44 "actions": {
55 "source": {
@@ -8,7 +8,7 @@
88 }
99 },
1010 "formatter": {
11- "indentStyle": "space"
11+ "enabled": false
1212 },
1313 "linter": {
1414 "enabled": true,
bun.lock+24−21
@@ -5,11 +5,11 @@
55 "": {
66 "name": "cel-tui",
77 "devDependencies": {
8- "@biomejs/biome": "^2.4.10",
9- "@types/bun": "^1.3.11",
10- "lefthook": "^2.1.4",
8+ "@biomejs/biome": "^2.4.11",
9+ "@types/bun": "^1.3.12",
10+ "lefthook": "^2.1.5",
1111 "mitata": "^1.0.34",
12- "prettier": "^3.8.1",
12+ "prettier": "^3.8.2",
1313 "typedoc": "^0.28.18",
1414 "typedoc-plugin-markdown": "^4.11.0",
1515 "typescript": "^6.0.2",
@@ -17,10 +17,11 @@
1717 },
1818 "packages/components": {
1919 "name": "@cel-tui/components",
20- "version": "0.4.0",
20+ "version": "0.7.0",
2121 "dependencies": {
2222 "@cel-tui/core": "workspace:*",
2323 "@cel-tui/types": "workspace:*",
24+ "lextide": "^0.2.0",
2425 "yoctomarkdown": "^0.1.0",
2526 },
2627 "peerDependencies": {
@@ -29,7 +30,7 @@
2930 },
3031 "packages/core": {
3132 "name": "@cel-tui/core",
32- "version": "0.4.0",
33+ "version": "0.7.0",
3334 "dependencies": {
3435 "@cel-tui/types": "workspace:*",
3536 "get-east-asian-width": "^1.5.0",
@@ -40,30 +41,30 @@
4041 },
4142 "packages/types": {
4243 "name": "@cel-tui/types",
43- "version": "0.4.0",
44+ "version": "0.7.0",
4445 "peerDependencies": {
4546 "typescript": ">=5.0.0",
4647 },
4748 },
4849 },
4950 "packages": {
50- "@biomejs/biome": ["@biomejs/biome@2.4.10", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.10", "@biomejs/cli-darwin-x64": "2.4.10", "@biomejs/cli-linux-arm64": "2.4.10", "@biomejs/cli-linux-arm64-musl": "2.4.10", "@biomejs/cli-linux-x64": "2.4.10", "@biomejs/cli-linux-x64-musl": "2.4.10", "@biomejs/cli-win32-arm64": "2.4.10", "@biomejs/cli-win32-x64": "2.4.10" }, "bin": { "biome": "bin/biome" } }, "sha512-xxA3AphFQ1geij4JTHXv4EeSTda1IFn22ye9LdyVPoJU19fNVl0uzfEuhsfQ4Yue/0F …
51+ "@biomejs/biome": ["@biomejs/biome@2.4.11", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.11", "@biomejs/cli-darwin-x64": "2.4.11", "@biomejs/cli-linux-arm64": "2.4.11", "@biomejs/cli-linux-arm64-musl": "2.4.11", "@biomejs/cli-linux-x64": "2.4.11", "@biomejs/cli-linux-x64-musl": "2.4.11", "@biomejs/cli-win32-arm64": "2.4.11", "@biomejs/cli-win32-x64": "2.4.11" }, "bin": { "biome": "bin/biome" } }, "sha512-nWxHX8tf3Opb/qRgZpBbsTOqOodkbrkJ7S+JxJAruxOReaDPPmPuLBAGQ8vigyUgo0Q …
5152
52- "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-vuzzI1cWqDVzOMIkYyHbKqp+AkQq4K7k+UCXWpkYcY/HDn1UxdsbsfgtVpa40shem8Kax4TLDLlx8kMAecgqiw=="],
53+ "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.11", "", { "os": "darwin", "cpu": "arm64" }, "sha512-wOt+ed+L2dgZanWyL6i29qlXMc088N11optzpo10peayObBaAshbTcxKUchzEMp9QSY8rh5h6VfAFE3WTS1rqg=="],
5354
54- "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-14fzASRo+BPotwp7nWULy2W5xeUyFnTaq1V13Etrrxkrih+ez/2QfgFm5Ehtf5vSjtgx/IJycMMpn5kPd5ZNaA=="],
55+ "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.11", "", { "os": "darwin", "cpu": "x64" }, "sha512-gZ6zR8XmZlExfi/Pz/PffmdpWOQ8Qhy7oBztgkR8/ylSRyLwfRPSadmiVCV8WQ8PoJ2MWUy2fgID9zmtgUUJmw=="],
5556
56- "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-7MH1CMW5uuxQ/s7FLST63qF8B3Hgu2HRdZ7tA1X1+mk+St4JOuIrqdhIBnnyqeyWJNI+Bww7Es5QZ0wIc1Cmkw=="],
57+ "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.11", "", { "os": "linux", "cpu": "arm64" }, "sha512-avdJaEElXrKceK0va9FkJ4P5ci3N01TGkc6ni3P8l3BElqbOz42Wg2IyX3gbh0ZLEd4HVKEIrmuVu/AMuSeFFA=="],
5758
58- "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-WrJY6UuiSD/Dh+nwK2qOTu8kdMDlLV3dLMmychIghHPAysWFq1/DGC1pVZx8POE3ZkzKR3PUUnVrtZfMfaJjyQ=="],
59+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.11", "", { "os": "linux", "cpu": "arm64" }, "sha512-+Sbo1OAmlegtdwqFE8iOxFIWLh1B3OEgsuZfBpyyN/kWuqZ8dx9ZEes6zVnDMo+zRHF2wLynRVhoQmV7ohxl2Q=="],
5960
60- "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.10", "", { "os": "linux", "cpu": "x64" }, "sha512-tZLvEEi2u9Xu1zAqRjTcpIDGVtldigVvzug2fTuPG0ME/g8/mXpRPcNgLB22bGn6FvLJpHHnqLnwliOu8xjYrg=="],
61+ "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.11", "", { "os": "linux", "cpu": "x64" }, "sha512-TagWV0iomp5LnEnxWFg4nQO+e52Fow349vaX0Q/PIcX6Zhk4GGBgp3qqZ8PVkpC+cuehRctMf3+6+FgQ8jCEFQ=="],
6162
62- "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.10", "", { "os": "linux", "cpu": "x64" }, "sha512-kDTi3pI6PBN6CiczsWYOyP2zk0IJI08EWEQyDMQWW221rPaaEz6FvjLhnU07KMzLv8q3qSuoB93ua6inSQ55Tw=="],
63+ "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.11", "", { "os": "linux", "cpu": "x64" }, "sha512-bexd2IklK7ZgPhrz6jXzpIL6dEAH9MlJU1xGTrypx+FICxrXUp4CqtwfiuoDKse+UlgAlWtzML3jrMqeEAHEhA=="],
6364
64- "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-umwQU6qPzH+ISTf/eHyJ/QoQnJs3V9Vpjz2OjZXe9MVBZ7prgGafMy7yYeRGnlmDAn87AKTF3Q6weLoMGpeqdQ=="],
65+ "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.11", "", { "os": "win32", "cpu": "arm64" }, "sha512-RJhaTnY8byzxDt4bDVb7AFPHkPcjOPK3xBip4ZRTrN3TEfyhjLRm3r3mqknqydgVTB74XG8l4jMLwEACEeihVg=="],
6566
66- "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.10", "", { "os": "win32", "cpu": "x64" }, "sha512-aW/JU5GuyH4uxMrNYpoC2kjaHlyJGLgIa3XkhPEZI0uKhZhJZU8BuEyJmvgzSPQNGozBwWjC972RaNdcJ9KyJg=="],
67+ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.11", "", { "os": "win32", "cpu": "x64" }, "sha512-A8D3JM/00C2KQgUV3oj8Ba15EHEYwebAGCy5Sf9GAjr5Y3+kJIYOiESoqRDeuRZueuMdCsbLZIUqmPhpYXJE9A=="],
6768
6869 "@cel-tui/components": ["@cel-tui/components@workspace:packages/components"],
6970
@@ -83,11 +84,11 @@
8384
8485 "@shikijs/vscode-textmate": ["@shikijs/vscode-textmate@10.0.2", "", {}, "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg=="],
8586
86- "@types/bun": ["@types/bun@1.3.11", "", { "dependencies": { "bun-types": "1.3.11" } }, "sha512-5vPne5QvtpjGpsGYXiFyycfpDF2ECyPcTSsFBMa0fraoxiQyMJ3SmuQIGhzPg2WJuWxVBoxWJ2kClYTcw/4fAg=="],
87+ "@types/bun": ["@types/bun@1.3.12", "", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
8788
8889 "@types/hast": ["@types/hast@3.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ=="],
8990
90- "@types/node": ["@types/node@25.5.2", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-tO4ZIRKNC+MDWV4qKVZe3Ql/woTnmHDr5JD8UI5hn2pwBrHEwOEMZK7WlNb5RKB6EoJ02gwmQS9OrjuFnZYdpg=="],
91+ "@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
9192
9293 "@types/unist": ["@types/unist@3.0.3", "", {}, "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q=="],
9394
@@ -99,7 +100,7 @@
99100
100101 "brace-expansion": ["brace-expansion@5.0.5", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ=="],
101102
102- "bun-types": ["bun-types@1.3.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="],
103+ "bun-types": ["bun-types@1.3.12", "", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="],
103104
104105 "entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
105106
@@ -127,6 +128,8 @@
127128
128129 "lefthook-windows-x64": ["lefthook-windows-x64@2.1.5", "", { "os": "win32", "cpu": "x64" }, "sha512-yiAh8qxml6uqy10jDxOdN9fOQpyLxBFY1fgCEAhn7sVJYmJKRhjqSBwZX6LG5MQjzr29KStrIdw7TR3lf3rT7Q=="],
129130
131+ "lextide": ["lextide@0.2.0", "", {}, "sha512-EGORriYc1h2xHVcIpLdfETIVOp4impZ+X2nnm5EJOt3L55Jf/U9zFLxONfl3kWiB5WhyzUJLHL1m/7Rv17lb0g=="],
132+
130133 "linkify-it": ["linkify-it@5.0.0", "", { "dependencies": { "uc.micro": "^2.0.0" } }, "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ=="],
131134
132135 "lunr": ["lunr@2.3.9", "", {}, "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow=="],
@@ -139,7 +142,7 @@
139142
140143 "mitata": ["mitata@1.0.34", "", {}, "sha512-Mc3zrtNBKIMeHSCQ0XqRLo1vbdIx1wvFV9c8NJAiyho6AjNfMY8bVhbS12bwciUdd1t4rj8099CH3N3NFahaUA=="],
141144
142- "prettier": ["prettier@3.8.1", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg=="],
145+ "prettier": ["prettier@3.8.2", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-8c3mgTe0ASwWAJK+78dpviD+A8EqhndQPUBpNUIPt6+xWlIigCwfN01lWr9MAede4uqXGTEKeQWTvzb3vjia0Q=="],
143146
144147 "punycode.js": ["punycode.js@2.3.1", "", {}, "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA=="],
145148
@@ -155,7 +158,7 @@
155158
156159 "uc.micro": ["uc.micro@2.1.0", "", {}, "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A=="],
157160
158- "undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
161+ "undici-types": ["undici-types@7.19.2", "", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="],
159162
160163 "yaml": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="],
161164
docs/skill/cel-tui/SKILL.md+48−5
@@ -2,15 +2,23 @@
22 name: cel-tui
33 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.
44 license: MIT
5-compatibility: Requires Bun runtime and a terminal supporting the Kitty keyboard protocol and SGR mouse mode.
5+compatibility: Requires Bun runtime. Best experience on Kitty-compatible terminals and in tmux with `set -s extended-keys on`; uses SGR mouse mode and accepts recoverable legacy key encodings when hosts do not preserve a pure Kitty stream.
66 metadata:
77 author: sacenox
8- version: "0.4.0"
8+ version: "0.7.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, cell-buffer rendering, and style inheritance. 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, style inheritance, and Kitty-first keyboard input. It has 4 primitives and external state management.
14+
15+## Terminal compatibility
16+
17+- **First-class:** Kitty-compatible terminals
18+- **First-class:** `tmux` with `set -s extended-keys on`
19+- **Best effort:** legacy terminals or multiplexers that collapse some modifier distinctions
20+
21+cel-tui enables Kitty level 1 for full modifier fidelity, but it also accepts recoverable legacy control bytes and ESC-prefixed Alt combinations so common keyboard flows keep working in tmux and mixed environments.
1422
1523 ## Install
1624
@@ -66,6 +74,8 @@ cel.viewport(() =>
6674
6775 The steps: `cel.init(terminal)` → `cel.viewport(() => tree)` → mutate state + `cel.render()`.
6876
77+Use `cel.setTitle("My App")` when you want to update the terminal window or tab title. It is imperative terminal state, not part of the render tree, and the previous title is not restored automatically on `cel.stop()`.
78+
6979 ## 4 Primitives
7080
7181 | Primitive | Type | Description |
@@ -135,6 +145,23 @@ VStack(
135145
136146 Controlled mode enables patterns like auto-scroll to bottom on new content. `scrollStep` affects mouse wheel input only — not programmatic `scrollOffset` updates.
137147
148+### Measuring content height
149+
150+Use `measureContentHeight(node, { width })` when your app knows the wrapping width but needs to know how tall a content subtree will be.
151+
152+```ts
153+import { measureContentHeight, VStack } from "@cel-tui/core";
154+
155+const addedHeight = measureContentHeight(
156+ VStack({}, olderMessages.map(renderMessage)),
157+ { width: historyContentWidth },
158+);
159+
160+scrollOffset += addedHeight;
161+```
162+
163+This is for **intrinsic content measurement**, not viewport/clipping measurement. The provided `width` is authoritative. Measure the content subtree you are adding or anchoring around — not a wrapper whose visible height is controlled by `height`, `flex`, or percentage sizing. If you measure a padded container, pass its outer width; if you measure the children inside a padded container directly, pass the inner content width.
164+
138165 ### Layers (modals)
139166
140167 Return an array from the render function — layers composite bottom-to-top:
@@ -221,11 +248,25 @@ cel.viewport(() =>
221248 mySelect.reset(); // clear filter/highlight programmatically
222249 ```
223250
251+### SyntaxHighlight component
252+
253+```ts
254+import { SyntaxHighlight } from "@cel-tui/components";
255+
256+VStack({ flex: 1, overflow: "scroll", padding: { x: 1 } }, [
257+ SyntaxHighlight(source, "typescript"),
258+]);
259+
260+SyntaxHighlight(source, "javascript", { theme: "dark-plus" });
261+```
262+
263+`SyntaxHighlight(content, language, props?)` renders registered lextide languages and aliases into cel-tui primitives. The component stays synchronous to call, but append-only updates reuse lextide's streaming parser state. Unknown language ids render plain text. The optional `theme` accepts the small built-in presets (`"default"`, `"dark-plus"`) or a best-effort token-color registration object.
264+
224265 ## Gotchas
225266
226267 - **State is external** — the framework has no state. Mutate variables then call `cel.render()`.
227268 - **Text is a pure leaf** — no sizing props, no children. Parent controls the box.
228-- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace, Enter, Tab). Enter inserts a newline by default. Use `onKeyPress` on TextInput to intercept keys before editing — return `false` to prevent the default action (e.g., intercept Enter for submit). Modifier combos (`ctrl+s`) are not editing keys and bubble up through ancestors via `onKeyPress`.
269+- **TextInput consumes insertable text and editing/navigation keys** when focused (printable text, arrows, backspace, Enter, Tab), plus readline-style shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and deletion are whitespace-delimited, and `up` / `down` follow visual wrapped lines. Enter inserts a newline by default. Use `onKeyPress` on TextInput to intercept keys before editing — return `false` to prevent the default action …
229270 - **Escape unfocuses** the current element. Tab/Shift+Tab traverses focusable elements (wraps around). After Escape, traversal continues from where focus was lost.
230271 - **Enter activates** a focused container's `onClick`. If no `onClick`, Enter reaches `onKeyPress`.
231272 - **`focusable: true`** without `onClick` makes a container keyboard-focusable (receives `onKeyPress` events via Tab). Used by stateful components like `Select`.
@@ -236,8 +277,10 @@ mySelect.reset(); // clear filter/highlight programmatically
236277 - **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
237278 - **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
238279 - **Always call `cel.stop()` before `process.exit()`** — restores raw mode, mouse tracking, and alternate screen.
239-- **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.
280+- **Kitty-first keyboard input** — the framework enables Kitty level 1 and gets full modifier fidelity when the host preserves it (`alt+x`, `ctrl+plus`, `shift+enter`, etc.). It also normalizes recoverable legacy encodings so common shortcuts keep working in tmux. For best results, use a Kitty-compatible terminal or `tmux` with `set -s extended-keys on`. On older legacy hosts, historically ambiguous collisions such as `ctrl+i` vs `tab` or `ctrl+m` vs `enter` cannot be recovered once the host c …
281+- **tmux is good for keyboard-driven manual checks** — common `tmux send-keys` paths work for printable chars, `Tab`/`BTab`, `Enter`, `Escape`, arrows, and many `Ctrl+letter` shortcuts. Use exact raw-sequence injection only when you need to target a protocol-specific encoding. Mouse input remains unreliable in tmux and should be verified in a real terminal.
240282 - **Button limitations** — `Button` from `@cel-tui/components` does not forward container sizing props (`width`, `height`, `flex`, `minWidth`, etc.). It supports styling (`fgColor`, `bgColor`, `bold`, etc.), `focusStyle`, `focused`, `onFocus`, `onBlur`, `onKeyPress`, and `padding`. For full layout control, use `HStack` + `Text` directly.
283+- **SyntaxHighlight keeps streaming parser state only for append-only growth** — appended content reuses lextide's stream state, but non-append edits still reset and replay the full snippet. Unknown language ids render plain text.
241284
242285 ## Composing Components
243286
docs/skill/cel-tui/references/api.md+73−3
@@ -1,5 +1,20 @@
11 # cel-tui API Reference
22
3+## Framework lifecycle
4+
5+```ts
6+cel.init(new ProcessTerminal(), { theme?: Theme });
7+cel.viewport(() => tree); // or () => [layer1, layer2]
8+cel.render();
9+cel.setTitle("My App");
10+cel.stop();
11+```
12+
13+- `cel.viewport` sets the render function and triggers the first render.
14+- `cel.render()` requests a batched re-render after external state changes.
15+- `cel.setTitle(title)` writes a best-effort terminal title request. Control characters are stripped from `title`, and `cel.stop()` does not restore the previous title automatically.
16+- `cel.stop()` restores terminal state (raw mode, keyboard protocol, mouse tracking, alternate screen).
17+
318 ## Container Props
419
520 All props accepted by `VStack` and `HStack`:
@@ -33,10 +48,32 @@ All props accepted by `VStack` and `HStack`:
3348 focused, // boolean (controlled — omit for uncontrolled)
3449 onFocus, // () => void
3550 onBlur, // () => void
36- onKeyPress, // (key: string) => boolean | void — return false to keep bubbling
51+ onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to keep bubbling
3752 }
3853 ```
3954
55+## Measurement Helpers
56+
57+```ts
58+measureContentHeight(node, { width }); // number
59+```
60+
61+- Measures a node tree's **intrinsic content height** at the provided wrapping width.
62+- This is a content-measurement helper, not a viewport/clipping helper.
63+- The provided `width` is authoritative — use the actual width the subtree wraps at.
64+- Main use case: prepend-style scrollback, where older content is inserted above the current viewport and the app needs to preserve the viewport anchor.
65+
66+```ts
67+const addedHeight = measureContentHeight(
68+ VStack({}, olderMessages.map(renderMessage)),
69+ { width: historyContentWidth },
70+);
71+
72+scrollOffset += addedHeight;
73+```
74+
75+Measure the content subtree you are adding. If a wrapper's visible height is controlled by `height`, `flex`, or percentage sizing, measure the content inside that wrapper instead. For padded content, pass the outer width when measuring the padded container itself, or the inner content width when measuring its children directly.
76+
4077 ## Scroll
4178
4279 Scroll supports **uncontrolled** (default) and **controlled** modes, mirroring the focus model:
@@ -88,7 +125,7 @@ Colors: 16 numbered palette slots — `"color00"` through `"color15"`. Mapped to
88125 TextInput({
89126 value, // string (controlled)
90127 onChange, // (value: string) => void
91- onKeyPress, // (key: string) => boolean | void — return false to prevent default editing action
128+ onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to prevent default editing action
92129 placeholder, // Text() node shown when empty
93130 // + all container props (sizing, styling, focus, scrollStep, etc.)
94131 });
@@ -110,6 +147,8 @@ TextInput({
110147 });
111148 ```
112149
150+When focused, TextInput consumes insertable text plus editing/navigation keys, including readline-style shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and deletion are whitespace-delimited, and `up` / `down` navigate visual wrapped lines. Other modifier combos and non-insertable control keys bubble. Key strings are semantic identifiers for handlers, not necessarily the exact inserted text — uppercase `A` normalizes to key `"a …
151+
113152 ## Sizing Strategies
114153
115154 Containers accept 4 sizing strategies:
@@ -131,10 +170,20 @@ TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`,
131170
132171 All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`, `"enter"`, `"alt+up"`, `"f1"`. Framework normalizes modifier order.
133172
173+cel-tui is **Kitty-first** and works well in `tmux` with `set -s extended-keys on`. Recoverable legacy forms normalize to the same key strings, but historically collapsed collisions (`ctrl+i` vs `tab`, `ctrl+m` vs `enter`, `ctrl+[` vs `escape`) remain limited by what the host terminal or multiplexer reports.
174+
134175 ## Pre-made Components
135176
136177 ```ts
137-import { Spacer, Divider, Button, Select } from "@cel-tui/components";
178+import {
179+ Spacer,
180+ Divider,
181+ Button,
182+ Select,
183+ VDivider,
184+ Markdown,
185+ SyntaxHighlight,
186+} from "@cel-tui/components";
138187
139188 Spacer(); // VStack({ flex: 1 }, [])
140189 Divider(); // Text("─", { repeat: "fill" })
@@ -244,6 +293,27 @@ Markdown(content, {
244293
245294 Streaming works naturally — append chunks and call `cel.render()`. Unclosed blocks are handled gracefully.
246295
296+### SyntaxHighlight (rendered code)
297+
298+Returns a `VStack` — place it directly in a container's children:
299+
300+```ts
301+import { SyntaxHighlight } from "@cel-tui/components";
302+
303+VStack({ flex: 1, overflow: "scroll", padding: { x: 1 } }, [
304+ SyntaxHighlight(code, "typescript"),
305+]);
306+
307+SyntaxHighlight(code, "javascript", { theme: "dark-plus" });
308+```
309+
310+- Signature: `SyntaxHighlight(content, language, props?)`
311+- `language` accepts registered lextide language ids and aliases
312+- `props.theme` accepts the built-in presets (`"default"`, `"dark-plus"`) or a best-effort token theme registration object
313+- Uses a terminal-friendly ANSI 16 fallback theme by default
314+- Highlighting is synchronous at the component boundary; unsupported languages render plain text
315+- Append-only updates reuse lextide stream state, while non-append edits reset and replay the full snippet
316+
247317 ## Theme
248318
249319 The default theme maps 16 color slots to ANSI palette indices. Custom themes remap to different ANSI indices or 24-bit hex:
docs/skill/cel-tui/references/composing-components.md+1−1
@@ -27,7 +27,7 @@ cel.viewport(() =>
2727 );
2828 ```
2929
30-This is the pattern used by `Button`, `Divider`, and `Spacer`. Prefer it whenever possible — it's simple, testable, and composable.
30+This is the pattern used by `Button`, `Divider`, `Spacer`, `VDivider`, `Markdown`, and `SyntaxHighlight` — stateless functions that derive output from current inputs. Prefer it whenever possible — it's simple, testable, and composable.
3131
3232 ## Stateful components (factory pattern)
3333
examples/hello.ts+9−11
@@ -10,6 +10,7 @@
1010
1111 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
1212 import { Spacer } from "@cel-tui/components";
13+import { warningBox } from "./warning-box";
1314
1415 const logo = [
1516 "╭─────────────────────╮",
@@ -66,17 +67,14 @@ cel.viewport(() => {
6667 },
6768 },
6869 [
69- Text("┌─────────────────────────┐", { fgColor: "color03" }),
70- Text("│ Terminal too small :( │", { fgColor: "color03" }),
71- Text("│ │", { fgColor: "color03" }),
72- Text("│ Please resize to at │", { fgColor: "color03" }),
73- Text(
74- `│ least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars. │`,
75- { fgColor: "color03" },
76- ),
77- Text("│ │", { fgColor: "color03" }),
78- Text("│ Ctrl+Q to quit │", { fgColor: "color03" }),
79- Text("└─────────────────────────┘", { fgColor: "color03" }),
70+ ...warningBox([
71+ " Terminal too small :(",
72+ "",
73+ " Please resize to at",
74+ ` least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`,
75+ "",
76+ " Ctrl+Q to quit",
77+ ]),
8078 ],
8179 );
8280 }
examples/pet.ts+9−11
@@ -22,6 +22,7 @@ import {
2222 ProcessTerminal,
2323 } from "@cel-tui/core";
2424 import { Button, Divider, Spacer, VDivider } from "@cel-tui/components";
25+import { warningBox } from "./warning-box";
2526
2627 // ─── Pet Definitions ────────────────────────────────────────────
2728
@@ -347,17 +348,14 @@ function tooSmallView() {
347348 },
348349 },
349350 [
350- Text("┌─────────────────────────┐", { fgColor: "color03" }),
351- Text("│ Terminal too small :( │", { fgColor: "color03" }),
352- Text("│ │", { fgColor: "color03" }),
353- Text("│ Please resize to at │", { fgColor: "color03" }),
354- Text(
355- `│ least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars. │`,
356- { fgColor: "color03" },
357- ),
358- Text("│ │", { fgColor: "color03" }),
359- Text("│ Ctrl+Q to quit │", { fgColor: "color03" }),
360- Text("└─────────────────────────┘", { fgColor: "color03" }),
351+ ...warningBox([
352+ " Terminal too small :(",
353+ "",
354+ " Please resize to at",
355+ ` least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`,
356+ "",
357+ " Ctrl+Q to quit",
358+ ]),
361359 ],
362360 );
363361 }
examples/simple-scroll.ts+9−11
@@ -9,6 +9,7 @@
99 */
1010 import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
1111 import { Divider, Spacer } from "@cel-tui/components";
12+import { warningBox } from "./warning-box";
1213
1314 const MIN_COLS = 30;
1415 const MIN_ROWS = 8;
@@ -64,17 +65,14 @@ cel.viewport(() => {
6465 },
6566 },
6667 [
67- Text("┌─────────────────────────┐", { fgColor: "color03" }),
68- Text("│ Terminal too small :( │", { fgColor: "color03" }),
69- Text("│ │", { fgColor: "color03" }),
70- Text("│ Please resize to at │", { fgColor: "color03" }),
71- Text(
72- `│ least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars. │`,
73- { fgColor: "color03" },
74- ),
75- Text("│ │", { fgColor: "color03" }),
76- Text("│ Ctrl+Q to quit │", { fgColor: "color03" }),
77- Text("└─────────────────────────┘", { fgColor: "color03" }),
68+ ...warningBox([
69+ " Terminal too small :(",
70+ "",
71+ " Please resize to at",
72+ ` least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`,
73+ "",
74+ " Ctrl+Q to quit",
75+ ]),
7876 ],
7977 );
8078 }
examples/syntax-highlight.ts+371−0
@@ -0,0 +1,371 @@
1+/**
2+ * cel-tui: SyntaxHighlight demo
3+ *
4+ * Streams TypeScript and Bash code into SyntaxHighlight.
5+ * Shows lextide-backed highlighting with append-only incremental updates.
6+ *
7+ * Run: bun run examples/syntax-highlight.ts
8+ */
9+
10+import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
11+import {
12+ Divider,
13+ Spacer,
14+ SyntaxHighlight,
15+ VDivider,
16+ type SyntaxHighlightTheme,
17+} from "@cel-tui/components";
18+import { warningBox } from "./warning-box";
19+
20+const LANGUAGE = "typescript";
21+const BASH_LANGUAGE = "bash";
22+const MIN_COLS = 52;
23+const MIN_ROWS = 16;
24+const STACKED_MIN_ROWS = 20;
25+const SIDE_BY_SIDE_MIN_COLS = 100;
26+const CHUNK_SIZE = 3;
27+const TICK_MS = 18;
28+
29+const CUSTOM_THEME: SyntaxHighlightTheme = {
30+ name: "cel-demo-sunset",
31+ type: "dark",
32+ fg: "#f8f8f2",
33+ bg: "#1f2335",
34+ tokenColors: [
35+ { settings: { foreground: "#f8f8f2" } },
36+ {
37+ scope: ["comment", "string.quoted.docstring.multi"],
38+ settings: { foreground: "#7f849c", fontStyle: "italic" },
39+ },
40+ {
41+ scope: ["keyword", "storage", "entity.name.operator"],
42+ settings: { foreground: "#ff79c6" },
43+ },
44+ {
45+ scope: ["string", "markup.inline"],
46+ settings: { foreground: "#f1fa8c" },
47+ },
48+ {
49+ scope: ["constant.numeric", "constant.language", "constant.character"],
50+ settings: { foreground: "#ffb86c" },
51+ },
52+ {
53+ scope: ["entity.name.function", "support.function", "meta.function-call"],
54+ settings: { foreground: "#50fa7b" },
55+ },
56+ {
57+ scope: [
58+ "entity.name.type",
59+ "support.type",
60+ "support.class",
61+ "entity.other.inherited-class",
62+ ],
63+ settings: { foreground: "#8be9fd" },
64+ },
65+ {
66+ scope: [
67+ "variable.parameter",
68+ "meta.object-literal.key",
69+ "meta.property-name",
70+ ],
71+ settings: { foreground: "#bd93f9" },
72+ },
73+ ],
74+};
75+
76+const THEME_OPTIONS: ReadonlyArray<{
77+ label: string;
78+ help: string;
79+ theme?: SyntaxHighlightTheme;
80+}> = [
81+ {
82+ label: "terminal ansi16",
83+ help: "Default theme follows terminal defaults plus ANSI slots.",
84+ },
85+ {
86+ label: "custom sunset",
87+ help: "Custom token theme remapped onto cel ANSI slots.",
88+ theme: CUSTOM_THEME,
89+ },
90+];
91+
92+const FULL_CODE = [
93+ "/**",
94+ " * Streaming syntax highlight demo.",
95+ " */",
96+ "interface User {",
97+ " id: number;",
98+ " name: string;",
99+ "}",
100+ "",
101+ "const users: User[] = [",
102+ ' { id: 1, name: "Ada" },',
103+ ' { id: 2, name: "Linus" },',
104+ "];",
105+ "",
106+ "function greet(user: User): string {",
107+ " return `Hello, ${user.name}!`;",
108+ "}",
109+ "",
110+ "/* Multi-line comment to test streamed grammar state */",
111+ "for (const user of users) {",
112+ " console.log(greet(user));",
113+ "}",
114+ "Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.Long ass line to see the wrapping behaviuour on the example.",
115+].join("\n");
116+
117+const BASH_CODE = [
118+ "#!/usr/bin/env bash",
119+ "set -euo pipefail",
120+ "",
121+ "readonly script_path=${BASH_SOURCE[0]}",
122+ "script_dir=${script_path%/*}",
123+ "targets=(debug release)",
124+ "count=0",
125+ "",
126+ "build() {",
127+ " local target=${1:-debug}",
128+ ' printf \'==> building %s from %s\\n\' "$target" "$script_dir"',
129+ " ((count += 1))",
130+ " bun run typecheck",
131+ " bun test",
132+ "}",
133+ "",
134+ 'for target in "${targets[@]}"; do',
135+ ' case "$target" in',
136+ ' release) build "$target" ;;',
137+ " esac",
138+ "done",
139+].join("\n");
140+
141+let content = "";
142+let bashContent = "";
143+let paused = false;
144+let themeIndex = 0;
145+let streamTimer: ReturnType<typeof setTimeout> | null = null;
146+
147+function quit() {
148+ stopStreaming();
149+ cel.stop();
150+ process.exit(0);
151+}
152+
153+function stopStreaming() {
154+ if (streamTimer) {
155+ clearTimeout(streamTimer);
156+ streamTimer = null;
157+ }
158+}
159+
160+function isDone(): boolean {
161+ return (
162+ content.length >= FULL_CODE.length && bashContent.length >= BASH_CODE.length
163+ );
164+}
165+
166+function startStreaming() {
167+ stopStreaming();
168+ if (isDone() || paused) return;
169+ streamTimer = setTimeout(streamNext, TICK_MS);
170+}
171+
172+function streamNext() {
173+ if (paused || isDone()) {
174+ streamTimer = null;
175+ cel.render();
176+ return;
177+ }
178+
179+ const nextContentLength = Math.min(
180+ FULL_CODE.length,
181+ content.length + CHUNK_SIZE,
182+ );
183+ const nextBashLength = Math.min(
184+ BASH_CODE.length,
185+ Math.round((nextContentLength / FULL_CODE.length) * BASH_CODE.length),
186+ );
187+
188+ content = FULL_CODE.slice(0, nextContentLength);
189+ bashContent = BASH_CODE.slice(0, nextBashLength);
190+ cel.render();
191+
192+ if (isDone()) {
193+ streamTimer = null;
194+ return;
195+ }
196+
197+ streamTimer = setTimeout(streamNext, TICK_MS);
198+}
199+
200+function restart() {
201+ content = "";
202+ bashContent = "";
203+ paused = false;
204+ startStreaming();
205+ cel.render();
206+}
207+
208+function togglePause() {
209+ if (isDone()) return;
210+ paused = !paused;
211+ if (!paused) startStreaming();
212+ else stopStreaming();
213+ cel.render();
214+}
215+
216+function toggleTheme() {
217+ themeIndex = (themeIndex + 1) % THEME_OPTIONS.length;
218+ cel.render();
219+}
220+
221+function codePane(
222+ title: string,
223+ status: string,
224+ content: string,
225+ language: string,
226+ theme?: SyntaxHighlightTheme,
227+) {
228+ return VStack({ flex: 1 }, [
229+ HStack(
230+ {
231+ height: 1,
232+ padding: { x: 1 },
233+ bgColor: "color08",
234+ },
235+ [
236+ Text(title, { bold: true, fgColor: "color06" }),
237+ Spacer(),
238+ Text(status, { fgColor: "color15" }),
239+ ],
240+ ),
241+ VStack(
242+ {
243+ flex: 1,
244+ overflow: "scroll",
245+ scrollbar: true,
246+ padding: { x: 1 },
247+ },
248+ [SyntaxHighlight(content, language, { theme })],
249+ ),
250+ ]);
251+}
252+
253+startStreaming();
254+
Cut short: this commit's diff is over 1000 lines.
examples/warning-box.ts+14−0
Cut short: this commit's diff is over 1000 lines.
package.json+6−6
Cut short: this commit's diff is over 1000 lines.
packages/components/package.json+4−3
Cut short: this commit's diff is over 1000 lines.
packages/components/src/button.ts+4−4
Cut short: this commit's diff is over 1000 lines.
packages/components/src/divider.ts+1−1
Cut short: this commit's diff is over 1000 lines.
packages/components/src/index.ts+18−13
Cut short: this commit's diff is over 1000 lines.
packages/components/src/markdown.test.ts+68−59
Cut short: this commit's diff is over 1000 lines.
packages/components/src/markdown.ts+3−3
Cut short: this commit's diff is over 1000 lines.
packages/components/src/select.test.ts+15−6
Cut short: this commit's diff is over 1000 lines.
packages/components/src/select.ts+12−6
Cut short: this commit's diff is over 1000 lines.
packages/components/src/spacer.ts+1−1
Cut short: this commit's diff is over 1000 lines.
packages/components/src/syntax-highlight.test.ts+223−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/syntax-highlight.ts+755−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/vdivider.ts+1−1
Cut short: this commit's diff is over 1000 lines.
packages/core/package.json+1−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.test.ts+325−25
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.ts+405−115
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cell-buffer.test.ts+1−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cell-buffer.ts+7−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/composite.test.ts+16−7
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.test.ts+2−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.ts+1−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/hit-test.test.ts+57−28
Cut short: this commit's diff is over 1000 lines.
packages/core/src/hit-test.ts+30−15
Cut short: this commit's diff is over 1000 lines.
packages/core/src/index.ts+18−17
Cut short: this commit's diff is over 1000 lines.
packages/core/src/keys.test.ts+30−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/keys.ts+176−69
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.test.ts+266−126
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.ts+132−41
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+22−11
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.ts+26−15
Cut short: this commit's diff is over 1000 lines.
packages/core/src/primitives/text-input.ts+11−5
Cut short: this commit's diff is over 1000 lines.
packages/core/src/scroll.test.ts+11−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/scroll.ts+10−6
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+16−3
Cut short: this commit's diff is over 1000 lines.
packages/core/src/test-helpers.ts+25−6
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-edit.test.ts+91−8
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-edit.ts+99−41
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-input.test.ts+493−5
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-layout.test.ts+5−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-layout.ts+65−8
Cut short: this commit's diff is over 1000 lines.
packages/core/src/width.ts+9−4
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+29−12
Cut short: this commit's diff is over 1000 lines.
spec.md+96−22
Cut short: this commit's diff is over 1000 lines.