70160
Ce
cel-tui / files
cel-tui / spec.md
61.0 KB
1# cel-tui Specification 2 3## Overview 4 5cel-tui is a TypeScript TUI framework built around a declarative functional API, ultra-fast rendering, and a concise developer experience. Layout is inspired by CSS Flexbox, using composable horizontal and vertical stacks as the core container primitives. 6 7--- 8 9## API Surface 10 11### Entrypoint 12 13```ts 14cel.init(terminal, options?: { 15 theme?: Theme; 16 kittyKeyboard?: KittyKeyboardOptions; 17}) 18cel.viewport(render: () => Node | Node[]) 19cel.render() 20cel.redraw() 21cel.setTheme(theme: Theme) 22cel.setTitle(title: string) 23cel.stop() 24``` 25 26`cel.init` attaches the terminal, configures terminal input/output modes, 27selects the initial theme, and optionally requests Kitty progressive keyboard 28flags. `cel.stop` detaches the terminal and restores the terminal state. 29 30`cel.viewport` sets the render function that returns the UI tree. Accepts a single layer or an array of layers. Each layer is a container with full viewport dimensions, laid out independently. When multiple layers are provided, they are composited bottom-to-top (array index = z-order). Setting the viewport triggers the first render. 31 32`cel.render` requests a re-render. Batched via `process.nextTick()` — multiple calls within the same tick produce a single render. Call this after state changes. 33 34`cel.redraw` requests a batched **full redraw**. It still re-evaluates the 35viewport, but discards the differential-render baseline and re-emits every 36cell. Use it after terminal resume or external screen corruption. 37 38`cel.setTheme(theme)` replaces the active runtime theme and automatically 39requests a full redraw. A normal cell diff cannot detect that the rendering of 40an unchanged palette slot changed, so theme replacement always invalidates the 41full frame. 42 43State is fully external to the framework. Use any state management approach — plain variables, classes, libraries. The framework just calls the render function and renders the returned tree. 44 45### Terminal Title 46 47```ts 48cel.setTitle(title: string) 49``` 50 51Sets the terminal window or tab title as an imperative side effect. This is **global terminal state**, not part of the declarative render tree, so it should be called directly when the title needs to change. 52 53The framework emits a best-effort terminal title request using an OSC title sequence. Support varies by terminal emulator, multiplexer, and remote environment — some hosts may ignore it, reinterpret it, or map it to a pane/window title instead. 54 55**Semantics:** 56 57- Later calls replace the previous title set by the app. 58- Repeating the same sanitized title is a no-op. 59- `title` is treated as plain text. Control characters are stripped before writing the sequence. 60- The framework does **not** automatically restore the previous terminal title on `cel.stop()`. 61 62### Measurement Helpers 63 64```ts 65measureContentHeight(node: Node, options: { width: number }): number 66``` 67 68Measures a node tree's **intrinsic content height** in terminal cells when wrapped within the provided width. The measurement walks downward from the given node and follows the same content rules as layout: text wrapping, padding, gap, intrinsic container sizing, fixed-size descendants, wrapping HStacks, and TextInput content height. 69 70This helper is for **content subtrees** whose height is not externally constrained. Typical use cases: scrollback/message history chunks, prepend-anchor preservation, markdown blocks, and any other intrinsically sized content. It is **not** a viewport measurement API — if a container's visible height is determined by `height`, `flex`, or percentage sizing, measure the content subtree inside that container instead. 71 72`width` should be the actual wrapping width for the node being measured. If you measure a padded container, pass its outer width so the helper can account for that container's own padding. If you measure the children inside a padded container directly, pass the inner content width. 73 74### Primitives 75 76| Category | Primitive | Description | 77| --------- | ------------------------- | -------------------------------------------------- | 78| Layout | `VStack(props, children)` | Vertical stack — children laid out top to bottom | 79| Layout | `HStack(props, children)` | Horizontal stack — children laid out left to right | 80| Content | `Text(content, props?)` | Styled text content | 81| Container | `TextInput(props)` | Editable text container | 82 83### Systems 84 85| System | Description | 86| -------------------------- | ------------------------------------------------------------ | 87| Flexbox layout engine | Sizing, alignment, gap | 88| Overflow & scrolling | `overflow: "hidden" \| "scroll"`, scrollbar | 89| Layering | Multiple viewport layers, composited bottom-to-top | 90| Mouse/scroll hit detection | Pointer-driven, topmost layer first, innermost-first routing | 91| Focus management | Keyboard-driven, for `TextInput` and clickable containers | 92| Keyboard input | Kitty-first input with tmux/legacy compatibility | 93 94--- 95 96## Layout Model 97 98### Core Containers 99 100- **VStack** — vertical stack, children laid out top to bottom (`flex-direction: column`) 101- **HStack** — horizontal stack, children laid out left to right (`flex-direction: row`) 102 103Containers are arbitrarily nestable: `HStack > VStack > HStack > ...` 104 105### API Shape 106 107Declarative and functional: 108 109```ts 110VStack(props, children); 111HStack(props, children); 112``` 113 114### Container Props 115 116Shared by both VStack and HStack. Containers also accept styling props (see [Styling](#styling)). 117 118| Prop | Type | Description | 119| ---------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | 120| `stateKey` | `string \| number` | Stable identity for framework-managed node state | 121| `width` | `SizeValue` | Fixed cells or percentage (`"50%"`) | 122| `height` | `SizeValue` | Fixed cells or percentage (`"100%"`) | 123| `flex` | `number` | Flex grow factor, proportional to siblings | 124| `minWidth` | `number` | Minimum width constraint | 125| `maxWidth` | `number` | Maximum width constraint | 126| `minHeight` | `number` | Minimum height constraint | 127| `maxHeight` | `number` | Maximum height constraint | 128| `padding` | `{ x?: number, y?: number }` | Internal padding (cells) | 129| `gap` | `number` | Spacing between children (cells) | 130| `justifyContent` | `"start" \| "end" \| "center" \| "space-between"` | Distribute children along the main axis | 131| `alignItems` | `"start" \| "end" \| "center" \| "stretch"` | Align children along the cross axis | 132| `flexWrap` | `"nowrap" \| "wrap"` | Wrap children to next line (HStack only) | 133| `overflow` | `"hidden" \| "scroll"` | Content overflow behavior (default: `"hidden"`) | 134| `scrollbar` | `boolean` | Show scrollbar indicator | 135| `scrollbarStyle` | `{ thumb?: ScrollbarPartStyle, track?: ScrollbarPartStyle }` | Customize scrollbar characters and styles | 136| `scrollStep` | `number` | Mouse wheel step in cells (default: adaptive) | 137| `scrollOffset` | `number` | Scroll position in cells (controlled) | 138| `onScroll` | `ScrollHandler` | Called on scroll input. Return `false` to keep bubbling. | 139| `onClick` | `() => void` | Called on mouse click or Enter when focused | 140| `focusable` | `boolean` | Focus traversal/click opt-out (TextInput defaults `true`; containers when `onClick`) | 141| `focused` | `boolean` | Whether this element is focused (controlled) | 142| `autoFocus` | `boolean` | Seed focus once when mounted in the active layer | 143| `onFocus` | `(event: { reason: "auto" \| "tab" \| "shift+tab" \| "click" \| "escape" }) => void` | Called when element receives focus | 144| `onBlur` | `(event: { reason: "auto" \| "tab" \| "shift+tab" \| "click" \| "escape" }) => void` | Called when element loses focus | 145| `focusStyle` | `StyleProps` | Style overrides applied when focused | 146| `onKeyPress` | `(key: string, event: KeyEvent) => boolean \| void` | Key event handler. Return `false` to keep bubbling. | 147 148`ScrollHandler` is `((offset: number, maxOffset: number) => void) | ((offset: number, maxOffset: number) => boolean)`. Only an exact `false` return continues propagation to the next scrollable ancestor; any other return value consumes the scroll event. The union preserves source compatibility for legacy void callbacks whose expression bodies incidentally return another value. 149 150### Stateful Node Identity 151 152`stateKey` gives a container or TextInput a stable identity for state owned by 153the framework: uncontrolled focus, uncontrolled container scroll, and 154TextInput cursor/scroll state. Keys are strings or numbers and must be unique 155among the stateful nodes mounted in the viewport at the same time. 156 157State follows a key when siblings are inserted, removed, or reordered and when 158the render function creates fresh props and callback objects. A key that is 159absent for a complete rendered frame is unmounted: its framework state is 160discarded, and later reuse starts a new lifecycle. Controlled props remain the 161source of truth regardless of `stateKey`. 162 163For source compatibility, an omitted `stateKey` retains the existing 164fallbacks: TextInput state follows its `onChange` function reference, 165uncontrolled scroll follows structural position, and uncontrolled focus 166follows traversal position. Dynamic/stateful collections should use explicit 167keys rather than relying on those fallbacks. 168 169### Sizing 170 171Four sizing strategies, inspired by CSS Flexbox: 172 173| Strategy | Example | Description | 174| -------------- | -------------------------------- | ----------------------------- | 175| **Intrinsic** | _(no sizing props set)_ | Size to fit content (default) | 176| **Fixed** | `width: 30, height: 10` | Exact cell count | 177| **Flex** | `flex: 1`, `flex: 2` | Proportional to siblings | 178| **Percentage** | `width: "50%"`, `height: "100%"` | Relative to parent | 179 180Constraints via `minWidth`, `maxWidth`, `minHeight`, `maxHeight`. 181 182**Intrinsic sizing:** A container with no explicit `width`/`height`/`flex`/percentage sizes to fit its children. Leaf nodes (Text) and TextInput compute intrinsic height from content and wrapping at the given width. 183 184**Sizing priority:** Intrinsic and fixed sizes are allocated first, then remaining space is distributed among flex/percentage children. 185 186### Gap 187 188Cell-based spacing between children: 189 190```ts 191HStack({ gap: 1 }, [...]) 192``` 193 194### Alignment 195 196Inspired by Flexbox: 197 198- `justifyContent` — distribute children along the main axis 199- `alignItems` — align children along the cross axis 200 201### Flex Wrap 202 203HStack supports `flexWrap: "wrap"` to flow children onto multiple rows when they exceed the container width, like CSS `flex-wrap: wrap`. 204 205```ts 206HStack({ flexWrap: "wrap", gap: 1 }, [ 207 VStack({ width: 30, height: 2 }, [Text("A")]), 208 VStack({ width: 30, height: 2 }, [Text("B")]), 209 VStack({ width: 30, height: 2 }, [Text("C")]), 210]); 211``` 212 213In an 80-column container: A and B fit on row 1 (60 ≤ 80), C wraps to row 2. 214 215**Wrapping rules:** 216 217- Children are placed left-to-right. When adding the next child (plus gap) would exceed the available width, a new row begins. 218- A child wider than the container still gets its own row (never split across rows). 219- `gap` applies between items within a row **and** between rows. 220- `flexWrap` is only meaningful on HStack. VStack ignores it. 221 222**Per-row layout:** 223 224Each row is an independent flex context: 225 226- **Row height** = tallest child in that row. 227- **Flex distribution** — flex children share remaining space within their row. 228- **`justifyContent`** — applied per row. 229- **`alignItems`** — applied per row (children aligned within their row's height). 230 231**Intrinsic sizing:** 232 233A wrapping HStack with no explicit height sizes to fit all rows: 234 235``` 236intrinsic height = sum of row heights + gap × (number of rows − 1) 237``` 238 239--- 240 241## Rounding Strategy 242 243Terminals operate on integer cell coordinates. When dividing space among flex/percentage children produces fractional values, the **Largest Remainder Method** is used: 244 2451. Floor all computed sizes 2462. Calculate the remaining cells (available space minus sum of floored values) 2473. Distribute remaining cells one-by-one to children with the largest fractional remainders 248 249Example: 80 columns, three `flex: 1` children (80 ÷ 3 = 26.667 each): 250 251- Floor: 26, 26, 26 = 78 252- Remaining: 2 cells 253- All fractional parts are equal (0.667), first two children receive +1 254- Result: 27, 27, 26 255 256This guarantees the total always sums exactly to the available space. Equal 257remainders are resolved deterministically in document order. 258 259--- 260 261## Overflow & Scrolling 262 263### Overflow Modes 264 265```ts 266VStack({ overflow: "hidden" }); // clip content (default) 267VStack({ overflow: "scroll" }); // enable scrolling 268``` 269 270### Scrollbar 271 272Optional visual scrollbar indicator: 273 274```ts 275VStack({ overflow: "scroll", scrollbar: true }); 276``` 277 278`scrollbarStyle` customizes the thumb and track independently. Each `char` 279must be exactly one terminal column; style fields use normal `StyleProps`: 280 281```ts 282VStack({ 283 overflow: "scroll", 284 scrollbar: true, 285 scrollbarStyle: { 286 thumb: { char: "█", fgColor: "color06", bold: true }, 287 track: { char: "·", fgColor: "color08" }, 288 }, 289}); 290``` 291 292### Scroll Direction 293 294Follows the container's main axis: 295 296- VStack with `overflow: "scroll"` → vertical scroll 297- HStack with `overflow: "scroll"` → horizontal scroll 298 299### Scroll Position 300 301Scroll supports both **uncontrolled** and **controlled** modes, determined by whether `scrollOffset` is provided: 302 303**Uncontrolled** (default) — the framework manages scroll position internally. Mouse wheel just works: 304 305```ts 306VStack({ overflow: "scroll" }, [...]) 307``` 308 309**Controlled** — the app owns the scroll state. Enables patterns like auto-scroll to bottom on new content: 310 311```ts 312VStack({ 313 overflow: "scroll", 314 scrollOffset: offset, 315 onScroll: (newOffset, maxOffset) => { 316 offset = newOffset; 317 }, 318}, [...]) 319``` 320 321In controlled mode, mouse wheel events fire `onScroll` with the new offset and maximum offset (total content size minus viewport size); the UI only moves when the app passes the updated `scrollOffset` back. 322 323For containers, `onScroll` may return `false` to decline handling and continue scroll propagation to the next scrollable ancestor. Any other return value (`undefined`, `true`, or no return) consumes the scroll event and stops propagation, preserving backward compatibility with existing void handlers. 324 325### Scroll Step 326 327Mouse wheel scrolling moves by a configurable **step size** measured in cells along the container's main axis. 328 329- `scrollStep` sets the step explicitly. 330- When omitted, the framework uses an adaptive default based on the viewport size of the scroll target: 331 - `floor(viewportMainAxis / 3)` 332 - clamped to the range `3..8` 333 334Examples: 335 336- height `3` viewport → step `3` 337- height `12` viewport → step `4` 338- height `30` viewport → step `8` 339 340This applies to both controlled and uncontrolled scrollable containers, and to `TextInput` mouse wheel scrolling. It affects **mouse wheel input only** — not programmatic `scrollOffset` updates or TextInput cursor-follow behavior. 341 342Values exceeding the maximum scroll offset are clamped during rendering and hit testing — passing `Infinity` means "scroll to the end". This enables patterns like sticky-bottom scroll: 343 344```ts 345let offset = 0; 346let stickToBottom = true; 347 348VStack({ 349 overflow: "scroll", 350 scrollOffset: stickToBottom ? Infinity : offset, 351 onScroll: (newOffset, maxOffset) => { 352 offset = newOffset; 353 stickToBottom = newOffset >= maxOffset; 354 }, 355}, [...]) 356``` 357 358While `stickToBottom` is true, `Infinity` is clamped to the current maximum on each render — new content automatically scrolls into view. When the user scrolls up, `stickToBottom` becomes false and the explicit offset takes over. Scrolling back to the bottom re-enables sticky mode. 359 360For prepend-style scrollback, apps can preserve the current viewport anchor by measuring the height of the newly inserted content and increasing `scrollOffset` by that amount: 361 362```ts 363const addedHeight = measureContentHeight( 364 VStack({}, olderMessages.map(renderMessage)), 365 { width: historyContentWidth }, 366); 367 368scrollOffset += addedHeight; 369``` 370 371`historyContentWidth` is the width the inserted content actually wraps at. For a padded scroll container, that usually means the container's inner content width. 372 373### Variable-height VirtualList 374 375`@cel-tui/components` provides `VirtualList` for collections that are too long 376to materialize and lay out on every render. It is a factory: create one callable 377instance per mounted list, then call that instance from the viewport render 378function with the current items and exact viewport dimensions. 379 380```ts 381const messages = VirtualList<Message>({ 382 itemKey: (message) => message.id, 383 renderItem: (message) => Text(message.body, { wrap: "word" }), 384 estimatedItemHeight: 3, 385 overscan: 8, // cells before and after the viewport 386 defaultStickToBottom: true, 387}); 388 389cel.viewport(() => 390 messages({ 391 items, 392 width: terminalWidth, 393 height: conversationHeight, 394 scrollbar: true, 395 }), 396); 397``` 398 399The component's virtualization contract is: 400 401- Item keys are `string | number`, must be unique within the list, and carry 402 measured height plus viewport anchoring across insertions, removals, and 403 reordering. 404- Cold rows use a positive cell-height estimate (optionally computed from the 405 item, index, and current width). Rows in the visible window plus cell-based overscan are rendered and measured with 406 `measureContentHeight`; top and bottom spacer nodes represent the rest. 407- `maxRenderedItems` is a hard returned-tree bound, including for zero-height 408 rows or extreme overscan. `maxCachedItems` bounds retained measurements. 409- Omitting `scrollOffset` uses instance-managed scrolling. Supplying it opts 410 into controlled scrolling. `onScroll(offset, maxOffset, reason)` receives 411 `"input"` for wheel requests and `"anchor"` when layout compensation changes 412 the effective offset. Returning exactly `false` bubbles only input events. 413- Sticky-bottom state can be instance-managed (`defaultStickToBottom`) or 414 controlled (`stickToBottom`). Wheel input away from the end disables the 415 uncontrolled sticky state; appends remain pinned while it is active. As with 416 core scroll containers, a controlled `scrollOffset: Infinity` also means 417 "pin to the current end" on every render. 418- The first visible keyed row and its screen position are retained when rows 419 are prepended, removed, reordered, or remeasured. A bounded batch of newly 420 prepended rows is measured immediately; cold rows converge from their 421 estimates as they enter the measurement window. 422- A width change clears all measured heights so wrapped content reflows. 423 Immutable item replacement invalidates the affected key by default; 424 `itemVersion` supports mutable models and `.invalidate(key?)` provides an 425 imperative escape hatch. 426- `.reset()`, `.scrollTo()`, `.scrollToEnd()`, and `.invalidate()` request a 427 render. `.dispose()` eagerly releases retained state when the view is 428 permanently removed; the callable can be reused afterward as a fresh list. 429 430--- 431 432## Scroll Input Model 433 434Scroll is **pointer-driven**, not focus-driven. Mouse wheel events are routed spatially based on cursor position. 435 436### Hit Detection 437 4381. Terminal reports mouse position via SGR mouse mode 4392. Starting from the **topmost layer**, find the deepest node at `(x, y)` 4403. If the layer has a node at that position, it handles the event. Otherwise, try the next layer down. 4414. For scroll: walk up the ancestor chain from the deepest hit node, considering scrollable nodes innermost-first (containers with `overflow: "scroll"`, or TextInput) 4425. For click: walk up to find the nearest container with `onClick` 443 444### Nested Scrollable Containers 445 446Wheel events start at the deepest scrollable ancestor of the hit target. For scrollable containers, if the container's `onScroll` returns `false`, the event continues to the next scrollable ancestor. Otherwise, that first target handles the event and propagation stops. Existing void `onScroll` handlers preserve current behavior because `undefined` consumes the event. 447 448TextInput participates as a scrollable target with framework-managed scroll, but it does not expose `onScroll`; once a TextInput is the scroll target, it handles wheel input directly. 449 450### Architecture Requirements 451 452- Each node stores its **absolute screen rect** after layout 453- The layout tree supports **bottom-up traversal** (child → parent) 454- Hit testing: given `(x, y)` → return the deepest node at that position 455 456### Click 457 458Click uses the same hit model as scroll: mouse click position is mapped to the deepest node, then walks up the ancestor chain to find the nearest container with `onClick`. **Innermost clickable container wins.** 459 460### Text Selection 461 462Native terminal text selection (click-drag to highlight/copy) is handled by the terminal emulator, not the framework. With SGR mouse mode enabled, most terminals support **Shift+click/drag** to bypass application mouse capture and use native selection. This is standard behavior across terminal applications (vim, tmux, etc.). 463 464--- 465 466## Focus Model 467 468Focus is **keyboard-driven** and separate from scroll. It supports both **uncontrolled** and **controlled** modes, determined by whether `focused` is provided. This mirrors the scroll model. 469 470- Focus is for interactive widgets (TextInput) and clickable containers (with `onClick`) 471- Scroll does not require focus 472- A user can type in a focused widget while scrolling a different container with the mouse 473 474### Focusable Elements 475 476Focus is implicit — no `focusable` prop needed for the common case: 477 478- **TextInput** — focusable by default, opt out with `focusable: false` 479- **Container with `onClick`** — focusable by default, opt out with `focusable: false` 480 481### Traversal 482 483**Escape** behaves like a normal key first: it bubbles through `onKeyPress` handlers, and if it remains unconsumed the framework unfocuses the current element. **Tab / Shift+Tab** moves focus to the next/previous focusable element in document order (depth-first tree traversal). 484 485When a TextInput is focused, insertable text and text-editing keys go to the input. This includes arrows, backspace, delete, Enter, Tab, plus readline-style shortcuts: `ctrl+a` / `ctrl+e` for start/end, `alt+b` / `alt+f` and `ctrl+left` / `ctrl+right` for whitespace-delimited word movement, and `ctrl+w` / `alt+d` for whitespace-delimited word deletion. `up` and `down` follow the input's visual wrapped lines, not just newline-separated hard lines. Other modifier combos (e.g., `ctrl+s`) are not consumed by TextInput and bubble up. The TextInput's `onKeyPress` handler fires before editing — returning `false` prevents the default action for that key, letting the app override any key's behavior, including Escape blur. Legacy control-byte encodings are normalized when possible, so recoverable shortcuts still bubble in environments like `tmux`. If no handler consumes it, press Escape to leave the input, then Tab to traverse. 486 487### Uncontrolled Focus 488 489**Uncontrolled** (default) — the framework manages focus internally. Tab, Shift+Tab, Escape, and mouse clicks just work with no app-side state: 490 491```ts 492HStack({ onClick: handleAction }, [Text("[ Action ]", { bold: true })]); 493``` 494 495The framework tracks which element is focused. `onFocus` and `onBlur` are optional notification callbacks — they fire when focus changes, include a `{ reason }` object (`"auto" | "tab" | "shift+tab" | "click" | "escape"`), and are not required for focus to work. 496 497Set `autoFocus: true` to seed uncontrolled focus once when that identity first 498mounts in the active topmost layer. If multiple elements request it, the first 499in document order wins. Covered layers do not claim focus. Escape does not let 500the hint reclaim focus on later renders; removing the identity for a complete 501rendered frame resets the hint's lifecycle. When a modal layer disappears, the 502underlying layer's previous focus is restored without firing focus callbacks: 503 504```ts 505HStack( 506 { 507 onClick: handleAction, 508 onFocus: ({ reason }) => addLog(`button focused via ${reason}`), 509 onBlur: ({ reason }) => addLog(`button blurred via ${reason}`), 510 }, 511 [Text("[ Action ]", { bold: true })], 512); 513``` 514 515### Controlled Focus 516 517**Controlled** — when `focused` is explicitly provided, the app owns the focus state. The framework calls `onFocus` and `onBlur` with a `{ reason }` object, but does not move focus until the app updates `focused`: 518 519```ts 520TextInput({ 521 value: text, 522 onChange: handleChange, 523 focused: isEditorFocused, 524 onFocus: ({ reason }) => { 525 addLog(`focused via ${reason}`); 526 isEditorFocused = true; 527 }, 528 onBlur: ({ reason }) => { 529 addLog(`blurred via ${reason}`); 530 isEditorFocused = false; 531 }, 532}); 533``` 534 535Only one element can be focused at a time. In controlled mode, the app is responsible for ensuring this — if multiple elements set `focused: true`, the first in document order wins. 536 537### Focus Style 538 539The `focusStyle` prop provides visual feedback when an element is focused. It accepts a `StyleProps` object whose values override the element's normal styles while focused: 540 541```ts 542HStack( 543 { 544 onClick: handleAction, 545 focusStyle: { bgColor: "color06", fgColor: "color00" }, 546 }, 547 [Text("[ Action ]", { bold: true })], 548); 549``` 550 551When this element receives focus, the container background becomes color06 and descendant Text nodes that don't set their own `fgColor` inherit color00. When focus leaves, the normal styles resume and text returns to the terminal default foreground. 552 553`focusStyle` works in both uncontrolled and controlled modes. 554 555--- 556 557## Key Handling 558 559Key events are routed through the focus and layer system, then bubble up the tree. 560 561### Kitty-First Keyboard Input 562 563cel-tui enables the [Kitty keyboard protocol](https://sw.kovidgoyal.net/kitty/keyboard-protocol/) and treats it as the preferred source of key identity, but it does **not** assume stdin becomes a pure Kitty-only stream. The framework must work well in both native Kitty-compatible terminals and in `tmux` with `set -s extended-keys on`, where input may arrive as a mixture of Kitty sequences and legacy encodings. 564 565**Why:** Kitty's baseline disambiguation flag fixes modifier collisions while 566its independent progressive-enhancement flags can add event phases, alternate 567keys, all-key reporting, and associated text. These are flags, not numbered 568protocol levels. Real-world hosts may still preserve only part of the protocol, 569so the decoder always accepts mixed Kitty and recoverable legacy forms. 570 571**Support targets:** 572 573- **First-class:** native Kitty-compatible terminals (Kitty, WezTerm, Ghostty, foot, Alacritty, Windows Terminal 1.25+, and others) 574- **First-class:** `tmux` with `set -s extended-keys on` 575- **Best effort:** legacy terminals or multiplexers that do not preserve Kitty distinctions 576 577**Lifecycle:** 578 5791. `cel.init()` pushes Kitty's baseline disambiguation flag (`CSI > 1 u`) and bracketed paste mode (`CSI ? 2004 h`). `kittyKeyboard` init options add progressive-enhancement bits to the pushed value 5802. The input decoder accepts a mixed stream of: 581 - Kitty `CSI key:alternate-keys ; modifiers:event-type ; text-codepoints u` 582 - legacy CSI letter / tilde sequences for arrows, Home/End, Delete, PageUp/Down, and function keys 583 - raw printable text 584 - legacy ASCII control bytes for recoverable `ctrl+letter` shortcuts 585 - recoverable ESC-prefixed Alt combinations 5863. `cel.stop()` pops the keyboard mode (`CSI < u`) and disables bracketed paste mode (`CSI ? 2004 l`), restoring the terminal's previous state 587 588```ts 589cel.init(new ProcessTerminal(), { 590 kittyKeyboard: { 591 reportEventTypes: true, 592 reportAlternateKeys: true, 593 reportAllKeys: true, 594 reportAssociatedText: true, 595 }, 596}); 597``` 598 599The options map directly to Kitty's official flags: event types (`2`), 600alternate keys (`4`), all keys as CSI-u (`8`), and associated text (`16`). 601Baseline disambiguation (`1`) is always present. Associated text is undefined 602without all-key reporting in Kitty, so cel-tui automatically enables bit `8` 603when `reportAssociatedText` is requested. 604 605`reportAllKeys` intentionally stops the terminal from sending ordinary text 606bytes. Callers that still want TextInput insertion must also request 607`reportAssociatedText`; cel-tui does not guess layout/IME output from a physical 608key code. Event phases for ordinary text keys likewise require all-key 609reporting. Flags unsupported or stripped by the host simply fall back to the 610mixed baseline/legacy decoder. 611 612**Stream model:** Terminals and multiplexers may batch multiple keyboard and mouse sequences into a single stdin chunk. The framework treats stdin as a stream and decodes all events in order. 613 614**Baseline details:** With only disambiguation enabled, unmodified special keys with well-known legacy encodings (Tab, Enter, Escape, Backspace) may still arrive as single-byte legacy input. Modified variants use structured sequences when the host preserves them. The parser handles both forms. 615 616**tmux compatibility:** In `tmux`, even with extended keys enabled, some shortcuts may still arrive in legacy form rather than Kitty-normalized form. cel-tui treats this as a supported environment, not an error case: recoverable legacy encodings should normalize to the same key strings as native Kitty input. 617 618**Unavoidable ambiguity:** Some legacy encodings are indistinguishable once a host has collapsed them. For example, `Ctrl+I` vs `Tab`, `Ctrl+M` vs `Enter`, and `Ctrl+[` vs `Escape` cannot be recovered if the terminal or multiplexer emits only the shared legacy byte. In those cases the framework uses the legacy key meaning (`tab`, `enter`, `escape`) and cannot infer the modifier combo. 619 620### Bracketed Paste Mode 621 622cel-tui enables bracketed paste mode so the terminal wraps pasted content with `CSI 200~` and `CSI 201~`. This lets the framework distinguish paste from typing and prevents pasted bytes from being mis-decoded as keyboard sequences. 623 624**Paste stream model:** The paste start marker, payload, and end marker may be split across multiple stdin chunks. The input layer must track paste state across chunks and wait for the closing marker before ending the paste. 625 626**Paste semantics:** 627 628- Inside a bracketed paste region, bytes are treated as literal pasted content until `CSI 201~` arrives. Kitty key decoding, legacy key parsing, and ESC-prefixed Alt handling do not run on the payload. 629- Newlines, tabs, spaces, and repeated characters are preserved exactly as pasted. 630- If a TextInput is focused, the full pasted payload is inserted at the cursor as a single batch edit. `onChange` fires once with the final value, then cursor-follow and scroll updates apply to the post-paste state. 631- Bracketed paste is **not** a key event. `onKeyPress` handlers are not called for the paste markers or for the pasted text itself. 632- If no TextInput is focused, pasted text is ignored by the framework. 633 634**Fallback:** If the terminal or multiplexer ignores bracketed paste mode and emits only raw text, the framework cannot distinguish paste from typing; that input falls back to the normal mixed-stream keyboard path. 635 636`onKeyPress` receives `(key, event)`. `event` exposes `eventType` 637(`"press" | "repeat" | "release"`), exact associated `text`, the main 638`codePoint`, optional `shiftedKey` / `baseLayoutKey`, and reported modifier 639state. Legacy events report `eventType: "press"`; modifier fields unavailable 640from the legacy bytes are false, and repeat phase/physical layout cannot be 641reconstructed after the host discards them. 642 643### Key Event Flow 644 6451. **Topmost layer** receives the key event 6462. A **release** event is offered to `onKeyPress` handlers but skips every 647 framework default action: no focus traversal, activation, TextInput edit, 648 cursor movement, or Escape blur 6493. If a **TextInput** is focused: 650 - If the TextInput has `onKeyPress`, call it first. If `onKeyPress` returns `false`, the key's **default TextInput action** is prevented — no character insertion, no cursor movement, and no Escape blur. The key is consumed. 651 - Otherwise, the TextInput processes insertable text, editing/navigation keys (arrows, backspace, delete, Enter, Tab), and these modifier-based editing shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and deletion use whitespace-delimited boundaries, and `up` / `down` navigate visual wrapped lines. Other modifier combos (e.g., `ctrl+s`) and non-insertable control keys are not editing keys and pass through. 6524. If a **clickable container** is focused, Enter press/repeat fires `onClick`. Other keys pass through. 6535. Unconsumed keys **bubble up** through ancestors — each `onKeyPress` handler in the ancestor chain is called from innermost to root. 6546. A handler that returns `false` signals the key was **not consumed** — bubbling continues to the next ancestor. Any other return (`undefined`, `true`, or no return) **stops bubbling** (backward-compatible: existing `void` handlers consume by default). 6557. The root container's `onKeyPress` acts as the global key handler — it receives keys that bubble all the way up. 6568. After bubbling, framework default actions run for still-unconsumed press/repeat events. Today that means: if `escape` is still unconsumed and an element is focused, the framework blurs it. 657 658### Key Format 659 660All lowercase, modifiers joined by `+` in canonical order `ctrl+alt+shift+super+hyper+meta+<key>`: 661 662``` 663"ctrl+s" 664"ctrl+shift+n" 665"escape" 666"enter" 667"alt+up" 668"f1" 669"ctrl+plus" 670"shift+enter" 671``` 672 673**Modifiers in key strings:** `ctrl`, `alt`, `shift`, `super`, `hyper`, `meta`. 674The `event.modifiers` object also reports `capsLock` and `numLock` state. 675 676**Named keys:** `escape`, `enter`, `tab`, `backspace`, `delete`, `space`, `plus`, `up`, `down`, `left`, `right`, `home`, `end`, `pageup`, `pagedown`, `f1`–`f12` 677 678**Printable characters:** lowercase letter or character itself — `"a"`, `"1"`, `"/"` 679 680The framework normalizes modifier order, so `"shift+ctrl+s"` and `"ctrl+shift+s"` both match. 681 682Key strings are semantic identifiers for handlers, not necessarily the exact text inserted into a TextInput. For example, pressing uppercase `A` normalizes to key `"a"` while still inserting `"A"` into the input. 683 684When the host preserves Kitty modifier data, all modifier combinations are fully supported — including `alt+<key>`, `ctrl+plus`, `shift+enter`, and other combos that are ambiguous or impossible in legacy terminal encoding. In compatibility paths, recoverable legacy forms normalize to the same key strings, but historically ambiguous collisions (for example `ctrl+i` vs `tab`) remain limited by what the terminal or multiplexer reports. 685 686### Activation 687 688When a clickable container is focused, **Enter** fires its `onClick`. 689 690### Mouse Interaction 691 692Clicking a focusable element also focuses it. This bridges the keyboard and mouse models — click a TextInput to start typing, click a button to focus it. 693 694--- 695 696## Layering 697 698Layering enables modals, dropdowns, and overlay UI. Each layer is an independent layout tree with full viewport dimensions. 699 700```ts 701// Single layer — most apps 702cel.viewport(() => 703 VStack({ height: "100%" }, [...]) 704) 705 706// Multiple layers — ordered bottom-to-top 707cel.viewport(() => [ 708 VStack({ height: "100%" }, [...mainUI]), 709 VStack({ height: "100%" }, [...modalUI]), 710]) 711``` 712 713**Compositing:** Layers are rendered bottom-to-top. Cells without content in a higher layer are transparent — the lower layer shows through. 714 715**Input:** Events target the topmost layer that has a node at the event position. This naturally blocks input to lower layers when a modal or overlay is present. 716 717**Modal backdrop pattern:** A full-viewport container on the top layer captures all input, preventing interaction with the base UI: 718 719```ts 720cel.viewport(() => [ 721 VStack({ height: "100%" }, [...mainUI]), 722 VStack( 723 { 724 height: "100%", 725 justifyContent: "center", 726 alignItems: "center", 727 onClick: dismissModal, 728 }, 729 [ 730 VStack({ width: 40, height: 15, bgColor: "color08" }, [ 731 Text("Are you sure?"), 732 HStack({ gap: 1 }, [ 733 HStack( 734 { 735 onClick: handleYes, 736 bgColor: "color08", 737 focusStyle: { bgColor: "color02" }, 738 }, 739 [Text(" Yes ", { bold: true })], 740 ), 741 HStack( 742 { 743 onClick: handleNo, 744 bgColor: "color08", 745 focusStyle: { bgColor: "color01" }, 746 }, 747 [Text(" No ", { bold: true })], 748 ), 749 ]), 750 ]), 751 ], 752 ), 753]); 754``` 755 756--- 757 758## Primitives 759 760### Text 761 762Styled text leaf node. No children, no sizing props — the parent container controls the box. 763 764```ts 765Text(content: string, props?: TextProps) 766``` 767 768**Sizing behavior:** 769 770- Width: always parent-assigned 771- Height: intrinsic — computed from content, newlines, and word-wrapping at the given width 772 773#### Props 774 775| Prop | Type | Description | 776| -------- | ------------------ | ------------------------------------ | 777| `repeat` | `number \| "fill"` | Repeat content N times or fill width | 778| `wrap` | `"none" \| "word"` | Wrapping mode (default: `"none"`) | 779 780Text also accepts styling props (see [Styling](#styling)). 781 782#### Repeat 783 784```ts 785Text("─", { repeat: "fill" }); // repeat to fill available width 786Text("─", { repeat: 20 }); // repeat exactly 20 times 787``` 788 789`repeat` takes a number or `"fill"`. When set, wrapping is ignored. 790 791#### Wrapping 792 793| Mode | Description | 794| -------------- | --------------------------------------------------------------- | 795| `wrap: "none"` | No wrapping (default). Content is hard-clipped at the box edge. | 796| `wrap: "word"` | Word-wrap to fit available width. Affects computed height. | 797 798Whitespace is always preserved. `\n` in content produces explicit line breaks. 799 800--- 801 802### TextInput 803 804Multi-line editable text container. Accepts the explicit `TextInputBaseProps` 805subset of container props but has no children — its content is the editable 806`value`. Scroll is always uncontrolled (framework-managed): the stored offset 807is clamped every render, mouse wheel input adjusts it, and focused inputs 808further adjust only as needed to keep the cursor visible. 809 810```ts 811TextInput(props: TextInputProps) 812``` 813 814#### Props 815 816`TextInputBaseProps` includes `stateKey`, sizing (`width`, `height`, `flex`, 817`min*`, `max*`, `padding`), styling, focus (`focusable`, `focused`, `autoFocus`, 818`onFocus`, `onBlur`, `focusStyle`), key routing (`onKeyPress`), and wheel step 819(`scrollStep`). It deliberately excludes child layout, container scroll state, 820scrollbar, and click-activation props. TextInput's behavior-specific props are: 821 822| Prop | Type | Description | 823| ---------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | 824| `value` | `string` | Current text content (controlled) | 825| `onChange` | `(value: string) => void` | Called on text change | 826| `cursor` | `number` | Controlled UTF-16 cursor offset, clamped backward to a grapheme boundary | 827| `onCursorChange` | `(cursor: number) => void` | Called when editing or navigation requests a cursor change | 828| `cursorStyle` | `"block" \| "bar" \| "underline"` | Painted and native terminal cursor shape. Defaults to `"block"` | 829| `onKeyPress` | `(key: string, event: KeyEvent) => boolean \| void` | Key handler, fires before editing. Return `false` to prevent the default TextInput action for that key. | 830| `placeholder` | `TextNode` | Text node shown when value is empty (pass a `Text()` call) | 831 832Word-wrap is always on. Cursor position is uncontrolled by default. Providing 833`cursor` switches it to controlled mode; editing and navigation call 834`onCursorChange`, and the app must update `cursor`. Offsets use JavaScript 835UTF-16 string indices but are clamped backward to grapheme boundaries so an 836emoji, ZWJ sequence, or combining sequence is never split. Programmatic value 837and cursor updates are applied together on the next render; without controlled 838`cursor`, external value changes preserve the internal cursor relative to the 839unchanged prefix/suffix. 840 841`cursorStyle` controls both cursor representations: the cell-buffer fallback 842and the native blinking terminal cursor selected with DECSCUSR. `"block"` 843inverts the current cell, `"bar"` paints a vertical bar, and `"underline"` 844underlines the current cell. Terminal cleanup restores the user's default 845cursor shape. 846 847TextInput scroll follows one rule: clamp the stored offset every render, then if the input is focused, adjust further only as needed to keep the cursor visible after edits, cursor movement, mouse wheel scrolling, or reflow/resize. Supported editing shortcuts include `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`; word movement and deletion use whitespace-delimited boundaries, and `up` / `down` navigate visual wrapped lines. In bracketed paste mode, pasted text is inserted literally at the cursor as one batch edit: one `onChange`, no `onKeyPress`, newlines and tabs preserved. 848 849#### Growing / Shrinking Pattern 850 851Without explicit height, TextInput uses intrinsic sizing (content height). Combined with `maxHeight`, this creates a naturally growing input: 852 853```ts 854TextInput({ 855 maxHeight: 10, 856 value, 857 onChange, 858 onKeyPress: (key) => { 859 if (key === "ctrl+enter") { 860 handleSubmit(); 861 return false; 862 } 863 }, 864}); 865``` 866 867- 1 line of text → height is 1 868- 5 lines → height is 5 869- 15 lines → height is 10 (capped), internal scroll kicks in 870 871--- 872 873## Styling 874 875### Color System 876 877cel-tui exposes **16 numbered color slots** — `"color00"` through `"color15"`. These are abstract palette references, not color names. The framework never uses names like "white" or "black" because those imply absolute colors and are easily confused with the terminal's default foreground and background. 878 879The **default theme** maps these slots 1:1 to the terminal's ANSI 16 palette: 880 881| Slot | Default ANSI mapping | Slot | Default ANSI mapping | 882| ----------- | -------------------- | ----------- | ------------------------ | 883| `"color00"` | ANSI 0 (black) | `"color08"` | ANSI 8 (bright black) | 884| `"color01"` | ANSI 1 (red) | `"color09"` | ANSI 9 (bright red) | 885| `"color02"` | ANSI 2 (green) | `"color10"` | ANSI 10 (bright green) | 886| `"color03"` | ANSI 3 (yellow) | `"color11"` | ANSI 11 (bright yellow) | 887| `"color04"` | ANSI 4 (blue) | `"color12"` | ANSI 12 (bright blue) | 888| `"color05"` | ANSI 5 (magenta) | `"color13"` | ANSI 13 (bright magenta) | 889| `"color06"` | ANSI 6 (cyan) | `"color14"` | ANSI 14 (bright cyan) | 890| `"color07"` | ANSI 7 (white) | `"color15"` | ANSI 15 (bright white) | 891 892With the default theme, the app automatically inherits whatever terminal color scheme the user has configured — Solarized, Gruvbox, Dracula, etc. Switch themes in the terminal, and every color in the UI updates. No application-side configuration needed. 893 894#### Theme override 895 896A **theme** is a mapping from the 16 color slots to rendering output. The default theme maps to ANSI SGR codes. A custom theme can remap any slot to different ANSI palette indices, 24-bit hex values, or a mix of both: 897 898```ts 899// Custom theme — remap slots to true color 900const myTheme: Theme = { 901 color00: "#1e1e2e", 902 color01: "#f38ba8", 903 color02: "#a6e3a1", 904 // ... remaining slots 905}; 906 907cel.init(terminal, { theme: myTheme }); 908``` 909 910Replace the active theme later with `cel.setTheme(nextTheme)`. Theme changes 911automatically perform a full redraw, including when the logical cell buffer is 912unchanged. If an application mutates a theme object in place, call 913`cel.setTheme(theme)` again or `cel.redraw()` to invalidate the terminal frame. 914 915App code uses the same `"color00"`–`"color15"` values regardless of what theme is active. The theme is a rendering concern, not an app logic concern. 916 917#### Terminal defaults 918 919The terminal's **default foreground and background are not palette colors** — they are a separate pair, chosen by the terminal theme to always contrast with each other. Omitting `fgColor` (leaving it `undefined`) emits no SGR color code, so the terminal uses its default foreground. This is the only way to guarantee readable text across both dark and light themes. The same applies to `bgColor`. 920 921**Guidelines:** 922 923- **Normal text** — don't set `fgColor` or `bgColor`. Let the terminal defaults handle contrast. 924- **Semantic accents** — use palette colors for meaning: `"color06"` for highlights, `"color01"` for errors, `"color08"` for dimmed/muted text. 925- **Badges and chips** — when setting `bgColor`, always pair it with an explicit `fgColor` so both sides are controlled (e.g., `bgColor: "color04"`, `fgColor: "color00"`). 926 927For more background on terminal color complexity, see [Terminal colours are tricky](https://jvns.ca/blog/2024/10/01/terminal-colours/) by Julia Evans. 928 929### Style Props 930 931| Prop | Type | Description | 932| ----------- | --------- | ---------------- | 933| `bold` | `boolean` | Bold weight | 934| `italic` | `boolean` | Italic style | 935| `underline` | `boolean` | Underlined text | 936| `fgColor` | `Color` | Foreground color | 937| `bgColor` | `Color` | Background color | 938 939**Colors:** 16 numbered palette slots — `"color00"` through `"color15"`. These are abstract references resolved through the active theme. With the default theme, they map to the terminal's ANSI 16 palette. Omitting a color prop means "use the terminal default." 940 941Style props are accepted by Text, TextInput, and containers (VStack, HStack). 942 943### Style Inheritance 944 945Containers propagate their styles to descendants. A child node inherits the nearest ancestor's style values, unless it sets a value explicitly. Explicit props always win. 946 947```ts 948VStack({ fgColor: "color06" }, [ 949 Text("inherits color06 on terminal default bg"), 950 Text("explicit color02", { fgColor: "color02" }), 951 VStack({ fgColor: "color01" }, [ 952 Text("inherits color01"), 953 Text("explicit color03", { fgColor: "color03" }), 954 ]), 955]); 956``` 957 958Resolution order for each style prop: **node's own prop → nearest ancestor → terminal default**. 959 960### Container Background 961 962When a container has `bgColor` (explicitly or via inheritance), the framework fills the container's rect with that color before painting children. This provides solid backgrounds for panels, modals, and sidebars without manual fill workarounds. 963 964When setting `bgColor`, always pair it with an explicit `fgColor` to ensure contrast across themes: 965 966```ts 967VStack({ bgColor: "color04", fgColor: "color07", padding: { x: 1 } }, [ 968 Text("Status bar content"), 969 Text(" ", { repeat: "fill" }), 970 Text("Right side"), 971]); 972``` 973 974### Focus Style 975 976The `focusStyle` prop on containers and TextInput overrides styles while the element is focused. Overridden values participate in inheritance — descendants see the focused values as their inherited defaults. 977 978```ts 979HStack( 980 { 981 onClick: handleSend, 982 bgColor: "color08", 983 focusStyle: { bgColor: "color06", fgColor: "color00" }, 984 }, 985 [Text(" Send ", { bold: true })], 986); 987``` 988 989When focused: background is color06, Text inherits `fgColor: "color00"`. When not focused: background is color08, Text inherits the terminal default foreground. 990 991--- 992 993## Character Width 994 995Terminal cells are monospaced, but not all characters occupy one cell. Correct width measurement is critical for layout, wrapping, truncation, and cursor positioning. 996 997### Width Rules 998 999| Category | Width | Examples | 1000| --------------------------- | ----- | -------------------------------------------------- | 1001| Printable ASCII (0x20–0x7E) | 1 | `a`, `Z`, `#`, ` ` | 1002| East Asian wide (CJK) | 2 | `世`, `界`, `!` | 1003| Emoji (RGI) | 2 | `😀`, `👨👩👧` | 1004| Zero-width | 0 | Control chars, combining marks, default ignorables | 1005| ANSI escape sequences | 0 | `\x1b[31m`, `\x1b[0m` | 1006 1007### Measurement Strategy 1008 10091. **Fast ASCII path** — if the entire string is printable ASCII, width = `string.length`. No segmentation needed. This is the hot path. 10102. **Grapheme segmentation** — `Intl.Segmenter` with `granularity: "grapheme"` to handle multi-codepoint characters (emoji with ZWJ, skin tones, combining marks). 10113. **East Asian width lookup** — per-codepoint lookup for CJK full-width characters (via `get-east-asian-width` or equivalent). 10124. **ANSI stripping** — escape sequences (CSI, OSC, APC) are stripped before measuring. 10135. **Caching** — LRU cache for non-ASCII width results. 1014 1015--- 1016 1017## Rendering 1018 1019### Cell Buffer 1020 1021The rendering pipeline uses a 2D **cell buffer** — a grid matching the terminal dimensions where each cell stores: 1022 1023- Character (grapheme cluster) 1024- Foreground color 1025- Background color 1026- Style flags (bold, italic, underline) 1027 1028The layout engine writes styled cells into the buffer. This makes clipping trivial (don't write outside the rect), and layer compositing trivial (higher layers overwrite lower layers, empty cells are transparent). 1029 1030### Pipeline 1031 10321. **Layout** — flexbox engine computes absolute screen rects for all nodes 10332. **Paint** — each node writes styled cells into the buffer within its rect 10343. **Composite** — layers are painted bottom-to-top into the final buffer 10354. **Diff** — compare new buffer against previous buffer 10365. **Emit** — generate ANSI sequences for changed cells, write in a single batched call 1037 1038### Reactive Rendering 1039 1040Rendering is **reactive**, not FPS-based. `cel.render()` batches via `process.nextTick()` — multiple calls within the same tick produce a single render. Terminal resize also triggers a re-render automatically. No fixed frame rate, no wasted renders. 1041 1042Animation is an explicit component-level lifecycle, never a permanent framework 1043loop. `createTicker({ maxFps, onTick })` schedules nothing until `.start()`, 1044requests at most one batched render per tick, skips delayed frames instead of 1045replaying a catch-up burst, and can be paused with `.stop()` or permanently 1046released with `.dispose()`. `Spinner()` builds on this scheduler and is likewise 1047inert unless `.start()` or the explicit `autoStart` option is used. 1048 1049`cel.redraw()` uses the same batching mechanism but forces the next frame to be 1050emitted in full. `cel.setTheme()` schedules this full-redraw path automatically. 1051If a differential frame has no changed cells and no cursor change, the renderer 1052emits no terminal bytes. 1053 1054### Synchronized Output 1055 1056All screen updates are wrapped in **CSI 2026** (`\x1b[?2026h` to begin, `\x1b[?2026l` to end). The terminal holds display updates until the end marker, producing atomic flicker-free screen refreshes. 1057 1058### Differential Rendering 1059 1060Three strategies, selected automatically: 1061 1062| Strategy | When | Description | 1063| ------------------ | --------------- | ---------------------------------------------- | 1064| **Full + clear** | Terminal resize | Clear the display, re-render everything | 1065| **Full, no clear** | First render | Output everything to clean screen | 1066| **Differential** | Most renders | Compare buffers, only emit changed cells/lines | 1067 1068--- 1069 1070## Reference Example: Agentic Chat UI 1071 1072``` 1073┌──────────────────────────────────────────────┐ 1074│ Agent Name model: gpt │ 1075├──────────────────────────────────────────────┤ 1076│ ▶ User: What files are in this dir? │ 1077│ │ 1078│ ▷ Agent: I'll check that for you. │ 1079│ ┌──────────────────────────────┐ │ 1080│ │ $ ls -la │ │ 1081│ │ file1.ts │ │ 1082│ │ file2.ts │ │ 1083│ │ README.md │ │ 1084│ └──────────────────────────────┘ │ 1085│ Found 3 files. │ 1086│ │ 1087│ ▶ User: Delete file2.ts │ 1088│ │ 1089│ ▷ Agent: Running... ⠋ │ 1090├──────────────────────────────────────────────┤ 1091│ > type a message... [Send]│ 1092└──────────────────────────────────────────────┘ 1093``` 1094 1095```ts 1096// State 1097let messages = []; 1098let input = ""; 1099 1100function handleChange(value) { 1101 input = value; 1102 cel.render(); 1103} 1104 1105function handleSend() { 1106 messages.push({ role: "user", content: input }); 1107 input = ""; 1108 cel.render(); 1109} 1110 1111// UI 1112cel.viewport(() => 1113 VStack( 1114 { 1115 height: "100%", 1116 onKeyPress: (key) => { 1117 if (key === "ctrl+q") process.exit(); 1118 }, 1119 }, 1120 [ 1121 // Header 1122 HStack({ height: 1, padding: { x: 1 } }, [ 1123 Text("Agent Name", { bold: true }), 1124 VStack({ flex: 1 }), 1125 Text("model: gpt", { fgColor: "color08" }), 1126 ]), 1127 1128 // Message history 1129 VStack( 1130 { flex: 1, overflow: "scroll", scrollbar: true, padding: { x: 1 } }, 1131 [ 1132 ...messages.map((msg) => 1133 VStack({ gap: 0 }, [ 1134 Text(`${msg.role === "user" ? "▶" : "▷"} ${msg.role}:`, { 1135 bold: msg.role === "user", 1136 fgColor: msg.role === "user" ? "color04" : "color02", 1137 }), 1138 Text(` ${msg.content}`), 1139 ]), 1140 ), 1141 ], 1142 ), 1143 1144 // Input area 1145 HStack({ padding: { x: 1 }, gap: 1 }, [ 1146 Text(">"), 1147 TextInput({ 1148 flex: 1, 1149 maxHeight: 10, 1150 value: input, 1151 onChange: handleChange, 1152 placeholder: Text("type a message...", { fgColor: "color08" }), 1153 onKeyPress: (key) => { 1154 if (key === "enter") { 1155 handleSend(); 1156 return false; 1157 } 1158 }, 1159 }), 1160 HStack( 1161 { 1162 onClick: handleSend, 1163 bgColor: "color08", 1164 focusStyle: { bgColor: "color06", fgColor: "color00" }, 1165 }, 1166 [Text("[Send]", { bold: true })], 1167 ), 1168 ]), 1169 ], 1170 ), 1171); 1172``` 1173 1174--- 1175 1176## Reference Example: Text Editor 1177 1178``` 1179┌──────────────┬───────────────────────────────┐ 1180│ files/ │ main.ts │ 1181│ ▸ main.ts │ │ 1182│ utils.ts │ import { foo } from "./utils";│ 1183│ test.ts │ │ 1184│ │ function main() { │ 1185│ │ console.log(foo()); │ 1186│ │ } │ 1187│ │ │ 1188│ │ │ 1189├──────────────┴───────────────────────────────┤ 1190│ main.ts Ln 3, Col 1 TypeScript ✓ │ 1191└──────────────────────────────────────────────┘ 1192``` 1193 1194```ts 1195cel.viewport(() => 1196 HStack( 1197 { 1198 height: "100%", 1199 onKeyPress: (key) => { 1200 if (key === "ctrl+q") process.exit(); 1201 if (key === "ctrl+s") saveFile(); 1202 }, 1203 }, 1204 [ 1205 // Sidebar 1206 VStack( 1207 { 1208 width: 20, 1209 overflow: "scroll", 1210 scrollOffset: sidebarScroll, 1211 onScroll: (newOffset) => { 1212 sidebarScroll = newOffset; 1213 }, 1214 }, 1215 [ 1216 Text("files/", { bold: true }), 1217 ...files.map((file) => 1218 HStack( 1219 { 1220 onClick: () => selectFile(file), 1221 focusable: false, 1222 }, 1223 [ 1224 Text( 1225 `${file === activeFile ? "▸" : " "} ${file.name}`, 1226 file === activeFile 1227 ? { fgColor: "color06", bgColor: "color08" } 1228 : {}, 1229 ), 1230 ], 1231 ), 1232 ), 1233 ], 1234 ), 1235 1236 // Main area 1237 VStack({ flex: 1 }, [ 1238 // Tab bar 1239 HStack({ height: 1 }, [ 1240 Text(` ${activeFile.name} `, { bold: true, bgColor: "color08" }), 1241 Text(" ", { repeat: "fill" }), 1242 ]), 1243 1244 // Editor — controlled focus (app manages when editor is focused) 1245 TextInput({ 1246 flex: 1, 1247 value: activeFile.content, 1248 onChange: handleEdit, 1249 focused: editorFocused, 1250 onFocus: ({ reason }) => { 1251 addLog(`editor focused via ${reason}`); 1252 editorFocused = true; 1253 }, 1254 onBlur: ({ reason }) => { 1255 addLog(`editor blurred via ${reason}`); 1256 editorFocused = false; 1257 }, 1258 }), 1259 1260 // Status bar 1261 HStack({ height: 1, bgColor: "color04" }, [ 1262 Text(` ${activeFile.name}`), 1263 Text(` Ln ${cursor.line}, Col ${cursor.col}`), 1264 Text(" ", { repeat: "fill" }), 1265 Text(`TypeScript ✓ `), 1266 ]), 1267 ]), 1268 ], 1269 ), 1270); 1271```