xonecas.io
725
Ds

diff-scope / commit a4cb69d

feat: bootstrap initial diff viewer

xonecas2026-04-16 a4cb69d5bdc01b24475e23c0ea029855b3f7fe1f

10 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/skills/cel-tui/SKILL.md+289−0
@@ -0,0 +1,289 @@
1+---
2+name: cel-tui
3+description: Build terminal user interfaces with cel-tui, a TypeScript TUI framework. Use when the user wants to create a TUI app, build a terminal UI, render text in the terminal, create a CLI with interactive elements, build a chat interface, text editor, or any interactive terminal application. Triggers include "build a TUI", "terminal UI", "interactive CLI", "text-based interface", "render to terminal", or any task requiring a programmatic terminal user interface.
4+license: MIT
5+compatibility: Requires Bun runtime. 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.
6+metadata:
7+ author: sacenox
8+ version: "0.7.2"
9+---
10+
11+# Building TUIs with cel-tui
12+
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.
22+
23+## Install
24+
25+```bash
26+bun add @cel-tui/core
27+# Optional pre-made components
28+bun add @cel-tui/components
29+```
30+
31+## Core Pattern
32+
33+Every cel-tui app follows this structure:
34+
35+```ts
36+import {
37+ cel,
38+ VStack,
39+ HStack,
40+ Text,
41+ TextInput,
42+ ProcessTerminal,
43+} from "@cel-tui/core";
44+
45+let value = "";
46+
47+cel.init(new ProcessTerminal());
48+cel.viewport(() =>
49+ VStack(
50+ {
51+ height: "100%",
52+ onKeyPress: (key) => {
53+ if (key === "ctrl+q") {
54+ cel.stop();
55+ process.exit();
56+ }
57+ },
58+ },
59+ [
60+ Text("My App", { bold: true, fgColor: "color06" }),
61+ Text("─", { repeat: "fill" }),
62+ TextInput({
63+ flex: 1,
64+ value,
65+ onChange: (v) => {
66+ value = v;
67+ cel.render();
68+ },
69+ }),
70+ ],
71+ ),
72+);
73+```
74+
75+The steps: `cel.init(terminal)` → `cel.viewport(() => tree)` → mutate state + `cel.render()`.
76+
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+
79+## 4 Primitives
80+
81+| Primitive | Type | Description |
82+| ------------------------- | ----------------------- | ----------------------------------------- |
83+| `VStack(props, children)` | Container | Vertical stack — children top to bottom |
84+| `HStack(props, children)` | Container | Horizontal stack — children left to right |
85+| `Text(content, props?)` | Leaf | Styled text, no children |
86+| `TextInput(props)` | Container (no children) | Multi-line editable text |
87+
88+Containers accept sizing (`width`, `height`, `flex`, `"50%"`, `minWidth`/`maxWidth`), layout (`padding`, `gap`, `justifyContent`, `alignItems`, `flexWrap`), scroll (`overflow: "scroll"`, `scrollbar`, `scrollStep`, `scrollOffset`, `onScroll`), styling (`fgColor`, `bgColor`, `bold`, `focusStyle`), and interaction (`onClick`, `focusable`, `focused`, `onKeyPress`). Colors are numbered palette slots (`"color00"`–`"color15"`), mapped to ANSI 16 by default. Custom themes can remap slots to different …
89+
90+Read [references/api.md](references/api.md) for the full props listing, sizing strategies, text props, and component reference.
91+
92+## Common Patterns
93+
94+### Spacer, divider, button
95+
96+```ts
97+HStack({ height: 1 }, [Text("left"), VStack({ flex: 1 }, []), Text("right")]);
98+Text("─", { repeat: "fill", fgColor: "color08" });
99+HStack(
100+ {
101+ onClick: handleClick,
102+ focusStyle: { bgColor: "color06", fgColor: "color00" },
103+ },
104+ [Text(" Send ", { bold: true })],
105+);
106+```
107+
108+### Scrollable list
109+
110+Scroll is **uncontrolled by default** — the framework manages scroll position internally. Mouse wheel just works:
111+
112+```ts
113+VStack({ overflow: "scroll", scrollbar: true }, [...items]);
114+```
115+
116+Mouse wheel scrolling uses an **adaptive step** by default based on the scroll target's visible main-axis viewport size:
117+
118+- `floor(viewportMainAxis / 3)`
119+- clamped to `3..8`
120+
121+Override it with `scrollStep` when a view should scroll faster or slower:
122+
123+```ts
124+VStack({ overflow: "scroll", scrollbar: true, scrollStep: 6 }, [...items]);
125+```
126+
127+Provide `scrollOffset` + `onScroll` to opt into **controlled mode** — you own the state:
128+
129+```ts
130+let offset = 0;
131+
132+VStack(
133+ {
134+ overflow: "scroll",
135+ scrollbar: true,
136+ scrollOffset: offset,
137+ onScroll: (newOffset, maxOffset) => {
138+ offset = newOffset;
139+ cel.render();
140+ },
141+ },
142+ [...items],
143+);
144+```
145+
146+Controlled mode enables patterns like auto-scroll to bottom on new content. `scrollStep` affects mouse wheel input only — not programmatic `scrollOffset` updates.
147+
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+
165+### Layers (modals)
166+
167+Return an array from the render function — layers composite bottom-to-top:
168+
169+```ts
170+cel.viewport(() => [
171+ VStack({ height: "100%" }, [...mainUI]),
172+ ...(showModal
173+ ? [
174+ VStack(
175+ { height: "100%", justifyContent: "center", alignItems: "center" },
176+ [
177+ VStack(
178+ { width: 40, height: 10, bgColor: "color08", fgColor: "color07" },
179+ [...modalContent],
180+ ),
181+ ],
182+ ),
183+ ]
184+ : []),
185+]);
186+```
187+
188+### Focus
189+
190+Focus is **uncontrolled by default** — Tab/Shift+Tab/Escape/click just work. Provide `focused` prop to opt into controlled mode:
191+
192+```ts
193+// Uncontrolled — framework manages focus
194+HStack({ onClick: handleAction }, [Text("[ OK ]")]);
195+
196+// Controlled — app owns focus state
197+TextInput({
198+ value,
199+ onChange,
200+ focused: isFocused,
201+ onFocus: () => {
202+ isFocused = true;
203+ cel.render();
204+ },
205+});
206+```
207+
208+### Style inheritance
209+
210+Containers propagate styles to descendants. Explicit props always win:
211+
212+```ts
213+VStack({ fgColor: "color07", bgColor: "color04" }, [
214+ Text("inherits color07 on color04"),
215+ Text("explicit color02", { fgColor: "color02" }),
216+]);
217+```
218+
219+### Select component
220+
221+```ts
222+import { Select } from "@cel-tui/components";
223+
224+const mySelect = Select({
225+ items: ["apple", "banana", "cherry"],
226+ onSelect: (value) => {
227+ chosen = value;
228+ cel.render();
229+ },
230+});
231+
232+// ctrl+q lives on the root — Select returns false for unrecognized
233+// keys, so they bubble up automatically.
234+cel.viewport(() =>
235+ VStack(
236+ {
237+ height: "100%",
238+ onKeyPress: (key) => {
239+ if (key === "ctrl+q") {
240+ cel.stop();
241+ process.exit();
242+ }
243+ },
244+ },
245+ [mySelect()],
246+ ),
247+);
248+mySelect.reset(); // clear filter/highlight programmatically
249+```
250+
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 and re-highlights the full snippet whenever content changes, so final output stays stable across streamed chunk boundaries. 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+
265+## Gotchas
266+
267+- **State is external** — the framework has no state. Mutate variables then call `cel.render()`.
268+- **Text is a pure leaf** — no sizing props, no children. Parent controls the box.
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 …
270+- **Escape unfocuses** the current element. Tab/Shift+Tab traverses focusable elements (wraps around). After Escape, traversal continues from where focus was lost.
271+- **Enter activates** a focused container's `onClick`. If no `onClick`, Enter reaches `onKeyPress`.
272+- **`focusable: true`** without `onClick` makes a container keyboard-focusable (receives `onKeyPress` events via Tab). Used by stateful components like `Select`.
273+- **Innermost handler wins** — for `onClick` and `onScroll`. For `onKeyPress`, keys **bubble up** through ancestors: return `false` from a handler to let the key continue to the next ancestor. Returning `void`/`undefined` consumes the key (stops bubbling). This is backward-compatible.
274+- **Mouse wheel step is adaptive by default** — scrollable containers and `TextInput` use `floor(viewportMainAxis / 3)`, clamped to `3..8`. Set `scrollStep` to override it for a specific view.
275+- **Container `bgColor`** fills the rect with opaque background before painting children. Always pair `bgColor` with `fgColor` for contrast — terminal default fg is designed for the terminal default bg, not for arbitrary palette backgrounds.
276+- **Colors are numbered slots** (`"color00"`–`"color15"`), not names. The default theme maps to ANSI 16. Omit `fgColor`/`bgColor` for terminal defaults (guaranteed readable across themes).
277+- **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
278+- **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
279+- **Always call `cel.stop()` before `process.exit()`** — restores raw mode, mouse tracking, and alternate screen.
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.
282+- **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 re-highlights on content changes** — the component favors deterministic final output over incremental parser reuse, so streamed chunk boundaries do not change the final highlighting. Unknown language ids render plain text.
284+
285+## Composing Components
286+
287+Stateless components are plain functions returning `Node` trees — prefer this pattern. When a component needs internal state across renders, use a factory function that returns a callable instance. Read [references/composing-components.md](references/composing-components.md) for full patterns and examples.
288+
289+For the full framework specification, see the [cel-tui spec](https://raw.githubusercontent.com/sacenox/cel-tui/main/spec.md).
.agents/skills/cel-tui/references/api.md+346−0
@@ -0,0 +1,346 @@
1+# cel-tui API Reference
2+
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+
18+## Container Props
19+
20+All props accepted by `VStack` and `HStack`:
21+
22+```ts
23+{
24+ // Sizing
25+ width, height, // SizeValue (number | "50%")
26+ flex, // number
27+ minWidth, maxWidth, // number
28+ minHeight, maxHeight, // number
29+ padding, // { x?: number, y?: number }
30+ gap, // number (cells between children)
31+ justifyContent, // "start" | "end" | "center" | "space-between"
32+ alignItems, // "start" | "end" | "center" | "stretch"
33+ overflow, // "hidden" (default) | "scroll"
34+ scrollbar, // boolean
35+ scrollStep, // number (mouse wheel step in cells; default adaptive)
36+ scrollOffset, // number (controlled scroll)
37+ onScroll, // (offset: number, maxOffset: number) => void
38+ flexWrap, // "nowrap" (default) | "wrap" (HStack only)
39+
40+ // Styling (inherited by descendants)
41+ bold, italic, underline,// boolean
42+ fgColor, bgColor, // Color ("color00"–"color15")
43+ focusStyle, // StyleProps — overrides when focused
44+
45+ // Interaction
46+ onClick, // () => void
47+ focusable, // boolean (default true if onClick set, or set true explicitly)
48+ focused, // boolean (controlled — omit for uncontrolled)
49+ onFocus, // () => void
50+ onBlur, // () => void
51+ onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to keep bubbling
52+}
53+```
54+
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+
77+## Scroll
78+
79+Scroll supports **uncontrolled** (default) and **controlled** modes, mirroring the focus model:
80+
81+```ts
82+// Uncontrolled — framework manages scroll position. Mouse wheel just works.
83+VStack({ overflow: "scroll", scrollbar: true }, [...items]);
84+
85+// Controlled — app owns scroll state.
86+VStack(
87+ {
88+ overflow: "scroll",
89+ scrollbar: true,
90+ scrollOffset: offset,
91+ onScroll: (newOffset, maxOffset) => {
92+ offset = newOffset;
93+ cel.render();
94+ },
95+ },
96+ [...items],
97+);
98+```
99+
100+- Scroll direction follows the container’s main axis: VStack → vertical, HStack → horizontal.
101+- Scroll is pointer-driven (mouse wheel), not focus-driven. A user can type in a focused widget while scrolling a different container.
102+- Mouse wheel scrolling uses an adaptive default step based on the scroll target's visible main-axis viewport size: `floor(viewportMainAxis / 3)`, clamped to `3..8`.
103+- Set `scrollStep` to override the mouse wheel step for a specific scrollable or `TextInput`.
104+- In controlled mode, the UI only moves when the app passes the updated `scrollOffset` back. `onScroll` fires with the clamped new offset and the maximum offset (content size minus viewport size). Pass `Infinity` as `scrollOffset` to mean "scroll to end" (clamped during rendering). `scrollStep` affects mouse wheel input only.
105+
106+## Text Props
107+
108+```ts
109+Text("content", {
110+ repeat: "fill" | number, // Repeat to fill width or N times
111+ wrap: "none" | "word", // Default "none", hard-clips at edge
112+ bold,
113+ italic,
114+ underline, // boolean
115+ fgColor,
116+ bgColor, // Color ("color00"–"color15")
117+});
118+```
119+
120+Colors: 16 numbered palette slots — `"color00"` through `"color15"`. Mapped to ANSI 16 by default; custom themes can remap to different ANSI indices or 24-bit true color. Omit a color prop for the terminal default.
121+
122+## TextInput Props
123+
124+```ts
125+TextInput({
126+ value, // string (controlled)
127+ onChange, // (value: string) => void
128+ onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to prevent default editing action
129+ placeholder, // Text() node shown when empty
130+ // + all container props (sizing, styling, focus, scrollStep, etc.)
131+});
132+```
133+
134+Enter inserts a newline by default. Use `onKeyPress` to intercept keys before editing:
135+
136+```ts
137+// Enter submits instead of inserting newline
138+TextInput({
139+ value: input,
140+ onChange: handleChange,
141+ onKeyPress: (key) => {
142+ if (key === "enter") {
143+ handleSend();
144+ return false;
145+ }
146+ },
147+});
148+```
149+
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+
152+## Sizing Strategies
153+
154+Containers accept 4 sizing strategies:
155+
156+```ts
157+VStack({}, []); // Intrinsic — size to fit content (default)
158+VStack({ width: 30, height: 10 }, []); // Fixed — exact cell count
159+VStack({ flex: 1 }, []); // Flex — proportional to siblings
160+VStack({ width: "50%", height: "100%" }, []); // Percentage — relative to parent
161+```
162+
163+Constraints: `minWidth`, `maxWidth`, `minHeight`, `maxHeight`.
164+
165+Text has no sizing props — parent controls the box, height is intrinsic (content + wrapping).
166+
167+TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`, `maxHeight`, etc.) plus container scroll props like `scrollStep` for mouse wheel behavior.
168+
169+## Key Format
170+
171+All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`, `"enter"`, `"alt+up"`, `"f1"`. Framework normalizes modifier order.
172+
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+
175+## Pre-made Components
176+
177+```ts
178+import {
179+ Spacer,
180+ Divider,
181+ Button,
182+ Select,
183+ VDivider,
184+ Markdown,
185+ SyntaxHighlight,
186+} from "@cel-tui/components";
187+
188+Spacer(); // VStack({ flex: 1 }, [])
189+Divider(); // Text("─", { repeat: "fill" })
190+Divider({ char: "═", fgColor: "color08" });
191+Button("[OK]", { onClick: handleOk });
192+Button("✕", { onClick: handleClose, focusable: false });
193+// Button accepts: onClick, focusable, focused, onFocus, onBlur, focusStyle,
194+// onKeyPress, padding, bold, fgColor, bgColor, italic, underline.
195+// Note: Button does not forward container sizing props (width, height, flex).
196+// For full layout control, use HStack + Text directly.
197+```
198+
199+### Select (filterable list)
200+
201+Select props: `items`, `onSelect`, `placeholder` (default `"type to filter..."`), `maxVisible` (default `10`), `indicator` (default `"›"`), `highlightColor` (default `"color06"`), `onKeyPress` (composed with internal handler), plus container/style props: `width`, `height`, `flex`, `fgColor`, `bgColor`, `focused`, `focusable`, `onFocus`, `onBlur`, `focusStyle`.
202+
203+```ts
204+const mySelect = Select({
205+ items: ["apple", "banana", "cherry"],
206+ onSelect: (value) => {
207+ chosen = value;
208+ cel.render();
209+ },
210+ placeholder: "search fruits...",
211+ maxVisible: 8,
212+});
213+
214+// Select returns false for unrecognized keys, so they bubble to root.
215+cel.viewport(() =>
216+ VStack(
217+ {
218+ height: "100%",
219+ onKeyPress: (key) => {
220+ if (key === "ctrl+q") {
221+ cel.stop();
222+ process.exit();
223+ }
224+ },
225+ },
226+ [Text("Pick a fruit:"), mySelect()],
227+ ),
228+);
229+
230+// Reset state programmatically
231+mySelect.reset();
232+```
233+
234+Rich items with separate display label, return value, and filter text:
235+
236+```ts
237+const modelSelect = Select({
238+ items: [
239+ {
240+ label: "claude-sonnet-4 (free)",
241+ value: "anthropic/claude-sonnet-4",
242+ filterText: "claude-sonnet-4",
243+ },
244+ { label: "gpt-4o", value: "openai/gpt-4o", filterText: "gpt-4o" },
245+ ],
246+ onSelect: (value) => {
247+ model = value;
248+ cel.render();
249+ },
250+});
251+```
252+
253+### VDivider (vertical divider)
254+
255+```ts
256+import { VDivider } from "@cel-tui/components";
257+
258+// Separate columns in an HStack
259+HStack({ height: "100%" }, [
260+ VStack({ flex: 1 }, [Text("left pane")]),
261+ VDivider({ fgColor: "color08" }),
262+ VStack({ flex: 1 }, [Text("right pane")]),
263+]);
264+
265+// Custom character
266+VDivider({ char: "║", fgColor: "color08" });
267+```
268+
269+### Markdown (rendered markdown)
270+
271+Returns an array of nodes — spread into a container's children:
272+
273+````ts
274+import { Markdown } from "@cel-tui/components";
275+
276+VStack(
277+ { flex: 1, overflow: "scroll", padding: { x: 1 } },
278+ Markdown("# Hello\n\nSome **bold** text.\n\n```js\nconst x = 1;\n```"),
279+);
280+````
281+
282+Custom theme for markdown styling:
283+
284+```ts
285+Markdown(content, {
286+ theme: {
287+ heading1: { bold: true, fgColor: "color05" },
288+ codeBlock: { bgColor: "color08" },
289+ bold: { bold: true, fgColor: "color03" },
290+ },
291+});
292+```
293+
294+Streaming works naturally — append chunks and call `cel.render()`. Unclosed blocks are handled gracefully.
295+
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+- Content changes re-highlight the full snippet so final output stays stable across streamed chunk boundaries
316+
317+## Theme
318+
319+The default theme maps 16 color slots to ANSI palette indices. Custom themes remap to different ANSI indices or 24-bit hex:
320+
321+```ts
322+import { cel, ProcessTerminal, type Theme } from "@cel-tui/core";
323+
324+const mocha: Theme = {
325+ color00: "#1e1e2e",
326+ color01: "#f38ba8",
327+ color02: "#a6e3a1",
328+ color03: "#f9e2af",
329+ color04: "#89b4fa",
330+ color05: "#cba6f7",
331+ color06: "#94e2d5",
332+ color07: "#cdd6f4",
333+ color08: "#45475a",
334+ color09: "#f38ba8",
335+ color10: "#a6e3a1",
336+ color11: "#f9e2af",
337+ color12: "#89b4fa",
338+ color13: "#cba6f7",
339+ color14: "#94e2d5",
340+ color15: "#bac2de",
341+};
342+
343+cel.init(new ProcessTerminal(), { theme: mocha });
344+```
345+
346+App code uses `"color00"`–`"color15"` regardless of theme. The mapping is a rendering concern.
.agents/skills/cel-tui/references/composing-components.md+109−0
@@ -0,0 +1,109 @@
1+# Composing Components
2+
3+cel-tui components are plain functions that return `Node` trees. There are two patterns depending on whether the component needs internal state.
4+
5+## Stateless components
6+
7+Simple functions that take props and return a `Node`. Called every render cycle inside `cel.viewport()`. All state is external — passed in as props.
8+
9+```ts
10+import type { ContainerNode } from "@cel-tui/types";
11+import { HStack, VStack, Text } from "@cel-tui/core";
12+
13+function StatusBar(left: string, right: string): ContainerNode {
14+ return HStack({ fgColor: "color00", bgColor: "color07" }, [
15+ Text(` ${left}`),
16+ VStack({ flex: 1 }, []), // spacer
17+ Text(`${right} `),
18+ ]);
19+}
20+
21+// Usage — called fresh each render
22+cel.viewport(() =>
23+ VStack({ height: "100%" }, [
24+ mainContent(),
25+ StatusBar(filename, `${lines} lines`),
26+ ]),
27+);
28+```
29+
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.
31+
32+## Stateful components (factory pattern)
33+
34+When a component needs internal state that persists across renders (e.g., a search query, cursor position, scroll offset), use a **factory function** that returns a callable instance. State lives in the closure. The user calls the instance each render to get a fresh `Node` tree.
35+
36+```ts
37+import type { ContainerNode, Color } from "@cel-tui/types";
38+import { cel, VStack, HStack, Text } from "@cel-tui/core";
39+
40+interface ToggleGroupProps {
41+ options: string[];
42+ onSelect: (value: string) => void;
43+ activeColor?: Color;
44+}
45+
46+interface ToggleGroupInstance {
47+ (): ContainerNode;
48+ reset(): void;
49+}
50+
51+function ToggleGroup(props: ToggleGroupProps): ToggleGroupInstance {
52+ const { options, onSelect, activeColor = "color06" } = props;
53+ let activeIndex = 0;
54+
55+ function handleKey(key: string): boolean | void {
56+ if (key === "left" && activeIndex > 0) {
57+ activeIndex--;
58+ cel.render();
59+ } else if (key === "right" && activeIndex < options.length - 1) {
60+ activeIndex++;
61+ cel.render();
62+ } else if (key === "enter") {
63+ onSelect(options[activeIndex]!);
64+ } else {
65+ return false; // unrecognized key — let it bubble to ancestors
66+ }
67+ }
68+
69+ function render(): ContainerNode {
70+ return HStack(
71+ { focusable: true, onKeyPress: handleKey, gap: 1 },
72+ options.map((opt, i) =>
73+ Text(` ${opt} `, {
74+ fgColor: i === activeIndex ? "color00" : undefined,
75+ bgColor: i === activeIndex ? activeColor : undefined,
76+ }),
77+ ),
78+ );
79+ }
80+
81+ render.reset = () => {
82+ activeIndex = 0;
83+ };
84+ return render as ToggleGroupInstance;
85+}
86+
87+// Usage — create once, call each render
88+const formatToggle = ToggleGroup({
89+ options: ["JSON", "YAML", "TOML"],
90+ onSelect: (fmt) => {
91+ format = fmt;
92+ cel.render();
93+ },
94+});
95+
96+cel.viewport(() =>
97+ VStack({ height: "100%" }, [Text("Output format:"), formatToggle()]),
98+);
99+```
100+
101+## Key points
102+
103+- **Create once** outside `cel.viewport()`. The closure captures mutable state.
104+- **Call each render** inside `cel.viewport()` — the function builds a fresh node tree from current state.
105+- **`cel.render()`** is importable from `@cel-tui/core` — stateful components call it after internal state changes to trigger re-renders.
106+- **Key bubbling** — `onKeyPress` handlers bubble from innermost to root. Return `false` from a handler to signal the key was not consumed and let it continue to the next ancestor. Return `void`/`undefined` to consume (backward-compatible). Components like `Select` return `false` for unrecognized keys, so app-level shortcuts on parent containers work automatically.
107+- **`.reset()`** or other methods — attach to the render function (functions are objects in JS) to expose imperative control.
108+
109+This is the pattern used by `Select` from `@cel-tui/components`.
.gitignore+1−0
@@ -0,0 +1 @@
1+node_modules
AGENTS.md+52−0
@@ -0,0 +1,52 @@
1+# diff-scope — Agent Guide
2+
3+## Project
4+
5+Build a live git diff viewer as a terminal app with `cel-tui`.
6+
7+## Stack
8+
9+- Runtime, package management, and script execution: `bun`
10+- One-off tools like Prettier or Biome: `bunx`
11+- Language: TypeScript
12+- TUI framework: `cel-tui`
13+
14+## Current Repo Layout
15+
16+- `src/index.ts` — current app entrypoint and TUI
17+- `package.json` — Bun scripts and dependencies
18+- `.agents/skills/cel-tui/` — local cel-tui skill and references
19+
20+## Current App Status
21+
22+The current app already has:
23+
24+- a scrollable git diff view
25+- staged and unstaged diff rendering in one snapshot
26+- diff highlighting and wrapped long lines
27+- a bottom status bar with cwd, branch, and git status summary
28+- pending-change detection every 5 seconds
29+- manual refresh with `r`
30+- a help/about modal toggled with `?` and closed with `?` or `Esc`
31+
32+Not implemented yet:
33+
34+- auto-refresh toggle
35+- adjustable auto-refresh interval controls
36+
37+## Commands
38+
39+```bash
40+bun install
41+bun run start
42+bun run dev
43+bun run typecheck
44+```
45+
46+## Working Rules
47+
48+- Use `bun` and `bunx` instead of `node`, `npm`, `npx`, or `yarn`.
49+- Use `cel-tui` for the UI. Do not introduce another TUI framework unless the user asks for it.
50+- Keep the app focused on the git diff live viewer; avoid side systems the user did not request.
51+- Prefer simple shelling out to `git` over adding a git library unless the user asks for one.
52+- When making `cel-tui` implementation decisions or checking framework behavior, load `.agents/skills/cel-tui/SKILL.md` first.
README.md+35−0
@@ -0,0 +1,35 @@
1+# diff-scope
2+
3+A small terminal git diff viewer built with `cel-tui` and Bun.
4+
5+## Current features
6+
7+- scrollable diff view
8+- staged and unstaged diff snapshots
9+- diff highlighting
10+- wrapped long lines
11+- status bar with current directory, branch, and git status summary
12+- pending-change detection every 5 seconds
13+- manual refresh with `r`
14+- help/about modal with `?`
15+
16+## Run
17+
18+```bash
19+bun install
20+bun run start
21+```
22+
23+## Development
24+
25+```bash
26+bun run dev
27+bun run typecheck
28+```
29+
30+## Current keybinds
31+
32+- `r` — refresh snapshot
33+- `?` — open or close help
34+- `Esc` — close help
35+- `Ctrl+Q` / `Ctrl+C` — quit
bun.lock+48−0
@@ -0,0 +1,48 @@
1+{
2+ "lockfileVersion": 1,
3+ "configVersion": 1,
4+ "workspaces": {
5+ "": {
6+ "name": "diff-scope",
7+ "dependencies": {
8+ "@cel-tui/components": "^0.7.2",
9+ "@cel-tui/core": "^0.7.2",
10+ },
11+ "devDependencies": {
12+ "@types/bun": "latest",
13+ "typescript": "^5",
14+ },
15+ },
16+ },
17+ "packages": {
18+ "@cel-tui/components": ["@cel-tui/components@0.7.2", "", { "dependencies": { "@cel-tui/core": "0.7.2", "@cel-tui/types": "0.7.2", "lextide": "^0.2.1", "yoctomarkdown": "^0.1.0" }, "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-RHq7G/lS6A733l534cSStQp+cJECkxZZWrLghbPHwGBsSeDdJ2MkrQm+02roh6EH/N40ZAYjQqplq8acRrnFFQ=="],
19+
20+ "@cel-tui/core": ["@cel-tui/core@0.7.2", "", { "dependencies": { "@cel-tui/types": "0.7.2", "get-east-asian-width": "^1.5.0" }, "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-Y5qdI9Zoa77Olq/LD+vqf3j0hyCRJYkkTkIdUfQplSDSUJS5NM+VSnxcQ8RCUNmrIsHeLmmAPHYsBsS1WMWk1w=="],
21+
22+ "@cel-tui/types": ["@cel-tui/types@0.7.2", "", { "peerDependencies": { "typescript": ">=5.0.0" } }, "sha512-XEmYkGqtBMOXI/DKLopv5OL7d5/8ybkj1OpJO4weWPyx4Y6VY9pYFaj8zYhVaFSQZcB23/yoA+DPYi0kOgoZhQ=="],
23+
24+ "@types/bun": ["@types/bun@1.3.12", "", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
25+
26+ "@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
27+
28+ "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
29+
30+ "bun-types": ["bun-types@1.3.12", "", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="],
31+
32+ "get-east-asian-width": ["get-east-asian-width@1.5.0", "", {}, "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA=="],
33+
34+ "lextide": ["lextide@0.2.1", "", {}, "sha512-fP7liS0LoNJz2EF6G7+K21yvB58bJEjaTrsDcPi4Qv7xZynB9NzjY44N6tFK6SJaECHIUqF2kcWbWQ84hPfmlg=="],
35+
36+ "string-width": ["string-width@8.2.0", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw=="],
37+
38+ "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
39+
40+ "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
41+
42+ "undici-types": ["undici-types@7.19.2", "", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="],
43+
44+ "yoctocolors": ["yoctocolors@2.1.2", "", {}, "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug=="],
45+
46+ "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=="],
47+ }
48+}
package.json+20−0
@@ -0,0 +1,20 @@
1+{
2+ "name": "diff-scope",
3+ "version": "0.1.0",
4+ "private": true,
5+ "type": "module",
6+ "module": "src/index.ts",
7+ "scripts": {
8+ "dev": "bun --watch src/index.ts",
9+ "start": "bun run src/index.ts",
10+ "typecheck": "tsc --noEmit"
11+ },
12+ "dependencies": {
13+ "@cel-tui/components": "^0.7.2",
14+ "@cel-tui/core": "^0.7.2"
15+ },
16+ "devDependencies": {
17+ "@types/bun": "latest",
18+ "typescript": "^5"
19+ }
20+}
src/index.ts+413−0
@@ -0,0 +1,413 @@
1+import { Divider, Spacer } from "@cel-tui/components";
2+import { HStack, ProcessTerminal, Text, VStack, cel } from "@cel-tui/core";
3+import packageJson from "../package.json";
4+
5+type GitCommandResult = {
6+ ok: boolean;
7+ stdout: string;
8+ stderr: string;
9+};
10+
11+type RepoSnapshot = {
12+ cwd: string;
13+ branch: string;
14+ statusSummary: string;
15+ diffLines: string[];
16+};
17+
18+type RepoState = {
19+ snapshot: RepoSnapshot;
20+ fingerprint: string;
21+};
22+
23+const APP_NAME = packageJson.name;
24+const APP_VERSION = packageJson.version;
25+const CHANGE_DETECTION_INTERVAL_MS = 5_000;
26+const textDecoder = new TextDecoder();
27+
28+let helpOpen = false;
29+let displayedState = readRepoState();
30+let snapshot = displayedState.snapshot;
31+let displayedFingerprint = displayedState.fingerprint;
32+let hasPendingChanges = false;
33+
34+function decode(buffer: Uint8Array<ArrayBufferLike>): string {
35+ return textDecoder.decode(buffer).replace(/\r\n/g, "\n").trimEnd();
36+}
37+
38+function runGit(args: string[]): GitCommandResult {
39+ const result = Bun.spawnSync({
40+ cmd: ["git", ...args],
41+ cwd: process.cwd(),
42+ stdout: "pipe",
43+ stderr: "pipe",
44+ });
45+
46+ return {
47+ ok: result.exitCode === 0,
48+ stdout: decode(result.stdout),
49+ stderr: decode(result.stderr),
50+ };
51+}
52+
53+function shortenPath(path: string): string {
54+ const home = process.env.HOME;
55+
56+ if (!home || !path.startsWith(home)) {
57+ return path;
58+ }
59+
60+ const suffix = path.slice(home.length);
61+ return suffix ? `~${suffix}` : "~";
62+}
63+
64+function summarizeStatus(shortStatus: string): string {
65+ if (!shortStatus) {
66+ return "clean";
67+ }
68+
69+ let staged = 0;
70+ let modified = 0;
71+ let untracked = 0;
72+
73+ for (const line of shortStatus.split("\n")) {
74+ if (!line) {
75+ continue;
76+ }
77+
78+ if (line.startsWith("??")) {
79+ untracked += 1;
80+ continue;
81+ }
82+
83+ const indexStatus = line[0] ?? " ";
84+ const worktreeStatus = line[1] ?? " ";
85+
86+ if (indexStatus !== " ") {
87+ staged += 1;
88+ }
89+
90+ if (worktreeStatus !== " ") {
91+ modified += 1;
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+20−0
Cut short: this commit's diff is over 1000 lines.