@@ -22,13 +22,7 @@ bun add @cel-tui/components
2222
2323 ## Core Pattern
2424
25-Every cel-tui app follows this pattern:
26-
27-1. Import primitives and `ProcessTerminal`
28-2. Initialize with `cel.init(new ProcessTerminal())`
29-3. Define state as plain variables (or any state approach)
30-4. Set render function with `cel.viewport(() => tree)`
31-5. Call `cel.render()` after state changes
25+Every cel-tui app follows this structure:
3226
3327 ```ts
3428 import {
@@ -71,163 +65,43 @@ cel.viewport(() =>
7165 );
7266 ```
7367
74-## 4 Primitives
75-
76-| Primitive | Type | Description |
77-| ------------------------- | ----------------------- | ---------------------------------------------- |
78-| `VStack(props, children)` | Container | Vertical stack — children top to bottom |
79-| `HStack(props, children)` | Container | Horizontal stack — children left to right |
80-| `Text(content, props?)` | Leaf | Styled text, no children, fills parent width |
81-| `TextInput(props)` | Container (no children) | Multi-line editable text, accepts sizing props |
82-
83-## Sizing
68+The steps: `cel.init(terminal)` → `cel.viewport(() => tree)` → mutate state + `cel.render()`.
8469
85-Containers accept 4 sizing strategies:
86-
87-```ts
88-VStack({}, []); // Intrinsic — size to fit content (default)
89-VStack({ width: 30, height: 10 }, []); // Fixed — exact cell count
90-VStack({ flex: 1 }, []); // Flex — proportional to siblings
91-VStack({ width: "50%", height: "100%" }, []); // Percentage — relative to parent
92-```
93-
94-Constraints: `minWidth`, `maxWidth`, `minHeight`, `maxHeight`.
95-
96-Text has no sizing props — parent controls the box, height is intrinsic (content + wrapping).
97-
98-TextInput accepts container sizing props (`flex`, `width`, `height`, `padding`, `maxHeight`, etc.).
99-
100-## Container Props
101-
102-```ts
103-{
104- // Sizing
105- width, height, // SizeValue (number | "50%")
106- flex, // number
107- minWidth, maxWidth, // number
108- minHeight, maxHeight, // number
109- padding, // { x?: number, y?: number }
110- gap, // number (cells between children)
111- justifyContent, // "start" | "end" | "center" | "space-between"
112- alignItems, // "start" | "end" | "center" | "stretch"
113- overflow, // "hidden" (default) | "scroll"
114- scrollbar, // boolean
115- scrollOffset, // number (controlled scroll)
116- onScroll, // (offset: number) => void
117-
118- // Styling (inherited by descendants)
119- bold, italic, underline,// boolean
120- fgColor, bgColor, // Color (ANSI 16)
121- focusStyle, // StyleProps — overrides when focused
122-
123- // Interaction
124- onClick, // () => void
125- focusable, // boolean (default true if onClick set)
126- focused, // boolean (controlled — omit for uncontrolled)
127- onFocus, // () => void
128- onBlur, // () => void
129- onKeyPress, // (key: string) => void
130-}
131-```
132-
133-## Text Props
134-
135-```ts
136-Text("content", {
137- repeat: "fill" | number, // Repeat to fill width or N times
138- wrap: "none" | "word", // Default "none", hard-clips at edge
139- bold,
140- italic,
141- underline, // boolean
142- fgColor,
143- bgColor, // ANSI 16 Color
144-});
145-```
70+## 4 Primitives
14671
147-Colors: `"black"`, `"red"`, `"green"`, `"yellow"`, `"blue"`, `"magenta"`, `"cyan"`, `"white"`, and bright variants (`"brightRed"`, etc.).
72+| Primitive | Type | Description |
73+| ------------------------- | ----------------------- | ----------------------------------------- |
74+| `VStack(props, children)` | Container | Vertical stack — children top to bottom |
75+| `HStack(props, children)` | Container | Horizontal stack — children left to right |
76+| `Text(content, props?)` | Leaf | Styled text, no children |
77+| `TextInput(props)` | Container (no children) | Multi-line editable text |
14878
149-## TextInput Props
79+Containers accept sizing (`width`, `height`, `flex`, `"50%"`, `minWidth`/`maxWidth`), layout (`padding`, `gap`, `justifyContent`, `alignItems`), scroll (`overflow: "scroll"`, `scrollbar`), styling (`fgColor`, `bgColor`, `bold`, `focusStyle`), and interaction (`onClick`, `focusable`, `focused`, `onKeyPress`).
15080
151-```ts
152-TextInput({
153- value, // string (controlled)
154- onChange, // (value: string) => void
155- onSubmit, // () => void
156- submitKey, // string (default "enter")
157- placeholder, // Text() node shown when empty
158- // + all container props (sizing, styling, focus, etc.)
159-});
160-```
81+Read [references/api.md](references/api.md) for the full props listing, sizing strategies, text props, and component reference.
16182
16283 ## Common Patterns
16384
164-### Spacer (push items apart)
165-
166-```ts
167-HStack({ height: 1 }, [
168- Text("left"),
169- VStack({ flex: 1 }, []), // spacer
170- Text("right"),
171-]);
172-```
173-
174-### Horizontal divider
85+### Spacer, divider, button
17586
17687 ```ts
88+HStack({ height: 1 }, [Text("left"), VStack({ flex: 1 }, []), Text("right")]);
17789 Text("─", { repeat: "fill", fgColor: "brightBlack" });
178-```
179-
180-### Button with focus style
181-
182-```ts
18390 HStack(
184- {
185- onClick: handleClick,
186- fgColor: "cyan",
187- focusStyle: { bgColor: "cyan", fgColor: "black" },
188- },
91+ { onClick: handleClick, focusStyle: { bgColor: "cyan", fgColor: "black" } },
18992 [Text(" Send ", { bold: true })],
19093 );
19194 ```
19295
193-### Growing text input (caps at maxHeight, then scrolls)
194-
195-```ts
196-TextInput({
197- flex: 1,
198- maxHeight: 10,
199- value,
200- onChange: (v) => {
201- value = v;
202- cel.render();
203- },
204- submitKey: "ctrl+enter",
205-});
206-```
207-
20896 ### Scrollable list
20997
21098 ```ts
211-// Uncontrolled (framework manages scroll)
21299 VStack({ overflow: "scroll", scrollbar: true }, [...items]);
213-
214-// Controlled (app manages scroll)
215-VStack(
216- {
217- overflow: "scroll",
218- scrollOffset: offset,
219- onScroll: (o) => {
220- offset = o;
221- cel.render();
222- },
223- },
224- [...items],
225-);
226100 ```
227101
228102 ### Layers (modals)
229103
230-Return an array from the render function. Layers composite bottom-to-top. Use `bgColor` for opaque modal backgrounds:
104+Return an array from the render function — layers composite bottom-to-top:
231105
232106 ```ts
233107 cel.viewport(() => [
@@ -235,15 +109,7 @@ cel.viewport(() => [
235109 ...(showModal
236110 ? [
237111 VStack(
238- {
239- height: "100%",
240- justifyContent: "center",
241- alignItems: "center",
242- onClick: () => {
243- showModal = false;
244- cel.render();
245- },
246- },
112+ { height: "100%", justifyContent: "center", alignItems: "center" },
247113 [
248114 VStack({ width: 40, height: 10, bgColor: "black" }, [
249115 ...modalContent,
@@ -255,41 +121,23 @@ cel.viewport(() => [
255121 ]);
256122 ```
257123
258-### Global key bindings
259-
260-Put `onKeyPress` on the root container — it catches all keys not consumed by focused elements:
261-
262-```ts
263-VStack({
264- height: "100%",
265- onKeyPress: (key) => {
266- if (key === "ctrl+q") { cel.stop(); process.exit(); }
267- if (key === "ctrl+s") saveFile();
268- },
269-}, [...])
270-```
271-
272124 ### Focus
273125
274-Focus is **uncontrolled by default** — Tab/Shift+Tab/Escape/click just work:
126+Focus is **uncontrolled by default** — Tab/Shift+Tab/Escape/click just work. Provide `focused` prop to opt into controlled mode:
275127
276128 ```ts
277-// Uncontrolled (default) — framework manages focus
129+// Uncontrolled — framework manages focus
278130 HStack({ onClick: handleAction }, [Text("[ OK ]")]);
279131
280-// Controlled — app owns focus state (provide `focused` prop)
132+// Controlled — app owns focus state
281133 TextInput({
282- value: text,
283- onChange: handleChange,
134+ value,
135+ onChange,
284136 focused: isFocused,
285137 onFocus: () => {
286138 isFocused = true;
287139 cel.render();
288140 },
289- onBlur: () => {
290- isFocused = false;
291- cel.render();
292- },
293141 });
294142 ```
295143
@@ -304,40 +152,7 @@ VStack({ fgColor: "white", bgColor: "blue" }, [
304152 ]);
305153 ```
306154
307-## Key Format
308-
309-All lowercase, modifiers joined by `+`: `"ctrl+s"`, `"ctrl+shift+n"`, `"escape"`, `"enter"`, `"alt+up"`, `"f1"`. Framework normalizes modifier order.
310-
311-## Key Rules
312-
313-- **State is external** — framework has no state. Call `cel.render()` after changes.
314-- **Text is a leaf** — no sizing props, no children. Parent controls the box.
315-- **TextInput is a container** — accepts sizing props but no children.
316-- **Style inheritance** — containers propagate styles (fgColor, bgColor, bold, etc.) to descendants. Explicit props on a node always override. Container `bgColor` fills the rect with opaque background.
317-- **focusStyle** — `focusStyle: { bgColor, fgColor, ... }` on containers overrides styles when focused. Participates in inheritance.
318-- **Uncontrolled focus by default** — Tab/Shift+Tab/Escape/click just work. Provide `focused` prop to opt into controlled mode.
319-- **Escape unfocuses** the current element.
320-- **Tab/Shift+Tab** traverses focusable elements in document order (wraps around). After Escape, traversal continues from the element that lost focus (not from the start).
321-- **Enter** activates a focused clickable container (fires onClick).
322-- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace, delete). Modifier combos (ctrl+s) bubble up through ancestors via onKeyPress.
323-- **Mouse click** on a focusable element fires onFocus (and onBlur on previous).
324-- **Innermost wins** — for click, scroll, and key handlers.
325-- **Differential rendering** — only changed cells are emitted after the first render.
326-- **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
327-
328-## Pre-made Components
329-
330-```ts
331-import { Spacer, Divider, Button, Select } from "@cel-tui/components";
332-
333-Spacer(); // VStack({ flex: 1 }, [])
334-Divider(); // Text("─", { repeat: "fill" })
335-Divider({ char: "═", fgColor: "brightBlack" });
336-Button("[OK]", { onClick: handleOk });
337-Button("✕", { onClick: handleClose, focusable: false });
338-```
339-
340-### Select (filterable list)
155+### Select component
341156
342157 ```ts
343158 import { Select } from "@cel-tui/components";
@@ -348,10 +163,7 @@ const mySelect = Select({
348163 chosen = value;
349164 cel.render();
350165 },
351- placeholder: "search fruits...",
352- maxVisible: 8,
353166 onKeyPress: (key) => {
354- // Receives keys the Select doesn't handle (modifiers, etc.)
355167 if (key === "ctrl+q") {
356168 cel.stop();
357169 process.exit();
@@ -359,140 +171,25 @@ const mySelect = Select({
359171 },
360172 });
361173
362-// Inside cel.viewport — call each render to get the current node tree
363-cel.viewport(() =>
364- VStack({ height: "100%" }, [Text("Pick a fruit:"), mySelect()]),
365-);
366-
367-// Reset state programmatically
368-mySelect.reset();
174+cel.viewport(() => VStack({ height: "100%" }, [mySelect()]));
175+mySelect.reset(); // clear filter/highlight programmatically
369176 ```
370177
371-Rich items with separate display label, return value, and filter text:
178+## Gotchas
372179
373-```ts
374-const modelSelect = Select({
375- items: [
376- {
377- label: "claude-sonnet-4 (free)",
378- value: "anthropic/claude-sonnet-4",
379- filterText: "claude-sonnet-4",
380- },
381- { label: "gpt-4o", value: "openai/gpt-4o", filterText: "gpt-4o" },
382- ],
383- onSelect: (value) => {
384- model = value;
385- cel.render();
386- },
387-});
388-```
180+- **State is external** — the framework has no state. Mutate variables then call `cel.render()`.
181+- **Text is a pure leaf** — no sizing props, no children. Parent controls the box.
182+- **TextInput consumes editing keys** when focused (printable chars, arrows, backspace). Modifier combos (`ctrl+s`) bubble up through ancestors via `onKeyPress`.
183+- **Escape unfocuses** the current element. Tab/Shift+Tab traverses focusable elements (wraps around). After Escape, traversal continues from where focus was lost.
184+- **Enter activates** a focused container's `onClick`. If no `onClick`, Enter reaches `onKeyPress`.
185+- **`focusable: true`** without `onClick` makes a container keyboard-focusable (receives `onKeyPress` events via Tab). Used by stateful components like `Select`.
186+- **Innermost handler wins** — for `onClick`, `onScroll`, and `onKeyPress`. Unhandled keys in a component's `onKeyPress` don't automatically bubble to parent handlers — forward them manually via an `onKeyPress` prop.
187+- **Container `bgColor`** fills the rect with opaque background before painting children.
188+- **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
189+- **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
389190
390191 ## Composing Components
391192
392-cel-tui components are plain functions that return `Node` trees. There are two patterns depending on whether the component needs internal state.
393-
394-### Stateless components
395-
396-Stateless components are simple functions that take props and return a `Node`. They're called every render cycle inside `cel.viewport()`. All existing state is external — passed in as props.
397-
398-```ts
399-import type { ContainerNode } from "@cel-tui/types";
400-import { HStack, Text } from "@cel-tui/core";
401-
402-function StatusBar(left: string, right: string): ContainerNode {
403- return HStack({ fgColor: "black", bgColor: "white" }, [
404- Text(` ${left}`),
405- VStack({ flex: 1 }, []), // spacer
406- Text(`${right} `),
407- ]);
408-}
409-
410-// Usage — called fresh each render
411-cel.viewport(() =>
412- VStack({ height: "100%" }, [
413- mainContent(),
414- StatusBar(filename, `${lines} lines`),
415- ]),
416-);
417-```
418-
419-This is the pattern used by `Button`, `Divider`, and `Spacer`. Prefer it whenever possible — it's simple, testable, and composable.
420-
421-### Stateful components (factory pattern)
422-
423-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.
424-
425-```ts
426-import type { ContainerNode, Color } from "@cel-tui/types";
427-import { cel, VStack, HStack, Text } from "@cel-tui/core";
428-
429-interface ToggleGroupProps {
430- options: string[];
431- onSelect: (value: string) => void;
432- activeColor?: Color;
433-}
434-
435-interface ToggleGroupInstance {
436- (): ContainerNode;
437- reset(): void;
438-}
439-
440-function ToggleGroup(props: ToggleGroupProps): ToggleGroupInstance {
441- const { options, onSelect, activeColor = "cyan" } = props;
442- let activeIndex = 0;
443-
444- function handleKey(key: string): void {
445- if (key === "left" && activeIndex > 0) {
446- activeIndex--;
447- cel.render();
448- } else if (key === "right" && activeIndex < options.length - 1) {
449- activeIndex++;
450- cel.render();
451- } else if (key === "enter") {
452- onSelect(options[activeIndex]!);
453- }
454- }
455-
456- function render(): ContainerNode {
457- return HStack(
458- { focusable: true, onKeyPress: handleKey, gap: 1 },
459- options.map((opt, i) =>
460- Text(` ${opt} `, {
461- fgColor: i === activeIndex ? "black" : undefined,
462- bgColor: i === activeIndex ? activeColor : undefined,
463- }),
464- ),
465- );
466- }
467-
468- render.reset = () => {
469- activeIndex = 0;
470- };
471- return render as ToggleGroupInstance;
472-}
473-
474-// Usage — create once, call each render
475-const formatToggle = ToggleGroup({
476- options: ["JSON", "YAML", "TOML"],
477- onSelect: (fmt) => {
478- format = fmt;
479- cel.render();
480- },
481-});
482-
483-cel.viewport(() =>
484- VStack({ height: "100%" }, [Text("Output format:"), formatToggle()]),
485-);
486-```
487-
488-Key points:
489-
490-- **Create once** outside `cel.viewport()`. The closure captures mutable state.
491-- **Call each render** inside `cel.viewport()` — the function builds a fresh node tree from current state.
492-- **`cel.render()`** is importable from `@cel-tui/core` — stateful components call it after internal state changes to trigger re-renders.
493-- **Key forwarding** — `findKeyPressHandler` returns the innermost handler and stops. If your component uses `onKeyPress`, accept an `onKeyPress` prop from the user and call it for keys you don't handle, so parent shortcuts still work.
494-- **`.reset()`** or other methods — attach to the render function (functions are objects in JS) to expose imperative control.
495-
496-This is the pattern used by `Select` from `@cel-tui/components`.
193+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.
497194
498-For the full specification, see the [cel-tui spec](https://raw.githubusercontent.com/sacenox/cel-tui/main/spec.md).
195+For the full framework specification, see the [cel-tui spec](https://raw.githubusercontent.com/sacenox/cel-tui/main/spec.md).