xonecas.io
725
Ds

diff-scope / files

diff-scope / .agents / skills / cel-tui / SKILL.md

12.9 KB
1---
2name: cel-tui
3description: 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.
4license: MIT
5compatibility: 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.
6metadata:
7  author: sacenox
8  version: "0.7.2"
9---
10
11# Building TUIs with cel-tui
12
13cel-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
21cel-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
26bun add @cel-tui/core
27# Optional pre-made components
28bun add @cel-tui/components
29```
30
31## Core Pattern
32
33Every cel-tui app follows this structure:
34
35```ts
36import {
37  cel,
38  VStack,
39  HStack,
40  Text,
41  TextInput,
42  ProcessTerminal,
43} from "@cel-tui/core";
44
45let value = "";
46
47cel.init(new ProcessTerminal());
48cel.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
75The steps: `cel.init(terminal)` → `cel.viewport(() => tree)` → mutate state + `cel.render()`.
76
77Use `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
88Containers 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 ANSI indices or 24-bit true color via `cel.init(terminal, { theme })`.
89
90Read [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
97HStack({ height: 1 }, [Text("left"), VStack({ flex: 1 }, []), Text("right")]);
98Text("─", { repeat: "fill", fgColor: "color08" });
99HStack(
100  {
101    onClick: handleClick,
102    focusStyle: { bgColor: "color06", fgColor: "color00" },
103  },
104  [Text(" Send ", { bold: true })],
105);
106```
107
108### Scrollable list
109
110Scroll is **uncontrolled by default** — the framework manages scroll position internally. Mouse wheel just works:
111
112```ts
113VStack({ overflow: "scroll", scrollbar: true }, [...items]);
114```
115
116Mouse 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
121Override it with `scrollStep` when a view should scroll faster or slower:
122
123```ts
124VStack({ overflow: "scroll", scrollbar: true, scrollStep: 6 }, [...items]);
125```
126
127Provide `scrollOffset` + `onScroll` to opt into **controlled mode** — you own the state:
128
129```ts
130let offset = 0;
131
132VStack(
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
146Controlled 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
150Use `measureContentHeight(node, { width })` when your app knows the wrapping width but needs to know how tall a content subtree will be.
151
152```ts
153import { measureContentHeight, VStack } from "@cel-tui/core";
154
155const addedHeight = measureContentHeight(
156  VStack({}, olderMessages.map(renderMessage)),
157  { width: historyContentWidth },
158);
159
160scrollOffset += addedHeight;
161```
162
163This 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
167Return an array from the render function — layers composite bottom-to-top:
168
169```ts
170cel.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
190Focus 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
194HStack({ onClick: handleAction }, [Text("[ OK ]")]);
195
196// Controlled — app owns focus state
197TextInput({
198  value,
199  onChange,
200  focused: isFocused,
201  onFocus: () => {
202    isFocused = true;
203    cel.render();
204  },
205});
206```
207
208### Style inheritance
209
210Containers propagate styles to descendants. Explicit props always win:
211
212```ts
213VStack({ 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
222import { Select } from "@cel-tui/components";
223
224const 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.
234cel.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);
248mySelect.reset(); // clear filter/highlight programmatically
249```
250
251### SyntaxHighlight component
252
253```ts
254import { SyntaxHighlight } from "@cel-tui/components";
255
256VStack({ flex: 1, overflow: "scroll", padding: { x: 1 } }, [
257  SyntaxHighlight(source, "typescript"),
258]);
259
260SyntaxHighlight(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 (e.g., intercept Enter for submit). `onKeyPress` receives normalized semantic key strings, while inserted text preserves the original characters (uppercase `A` arrives as key `"a"` but inserts `"A"`). Other modifier combos (`ctrl+s`) and non-insertable control keys bubble up through ancestors via `onKeyPress`.
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 collapses them.
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
287Stateless 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
289For the full framework specification, see the [cel-tui spec](https://raw.githubusercontent.com/sacenox/cel-tui/main/spec.md).