70160
Ce
cel-tui / files
cel-tui / AGENTS.md
23.2 KB
1# cel-tui — Agent Guide 2 3## What is this? 4 5cel-tui is a TypeScript TUI framework built around a declarative functional API, ultra-fast rendering, and a concise developer experience. Read `spec.md` for the full specification. 6 7## Project Structure 8 9Bun monorepo with four packages: 10 11``` 12packages/ 13 types/ — Shared type definitions (Color, ContainerProps, TextProps, Node, etc.) 14 core/ — Framework engine (primitives, layout, rendering, input handling) 15 clew/ — Stream-first syntax tokenization library 16 components/ — Pre-made components built with core + clew (Button, Spacer, Divider, etc.) 17``` 18 19Dependency graph: `core → types`, `components → core`, `components → types`, `components → @cel-tui/clew` 20 21## Key Design Decisions 22 23- **4 primitives only:** VStack, HStack (layout), Text (content leaf), TextInput (editable container) 24- **State is external:** The framework has no state management. `cel.viewport(() => tree)` sets a render function, `cel.render()` requests re-evaluation. Apps use whatever state approach they want. 25- **Uncontrolled by default, controlled opt-in:** Focus and scroll are framework-managed by default. Providing `focused` or `scrollOffset` explicitly switches to controlled mode (app owns the state). Value (`value`/`onChange`) on TextInput is always controlled; `cursor`/`onCursorChange` optionally controls its grapheme-safe caret. 26- **Stable identity:** `stateKey` attaches framework focus, scroll, and TextInput state to a continuously mounted identity across reordering. Keys are viewport-global, and absence for one successful frame ends the lifecycle. Per-layer focus is suspended/restored as overlays mount/unmount; `autoFocus` seeds only the active layer once. 27- **Style inheritance:** Containers propagate style props (fgColor, bgColor, bold, italic, underline) to descendants. Explicit props on a node always override inherited values. Container `bgColor` fills the rect with opaque background before painting children. 28- **focusStyle:** Containers accept `focusStyle: StyleProps` — style overrides applied when focused, participating in inheritance. 29- **TextInput is a container:** Accepts sizing props (flex, width, height, padding, min/max constraints) but has no children — its content is the `value` prop. Scroll is always framework-managed: the stored offset is clamped every render, mouse wheel input adjusts it, and focused inputs further adjust only as needed to keep the cursor visible. 30- **Text is a pure leaf:** No sizing props, no children. Parent controls the box. Height is intrinsic (from content + wrapping). 31- **Cell buffer rendering:** Layout writes to a 2D grid of styled cells, not raw strings. Clipping and layer compositing are cell writes. Diff against previous buffer for minimal terminal output. 32- **Reactive rendering:** `cel.render()` batches via `process.nextTick()`. No fixed FPS. 33- **Animation is opt-in:** `Spinner` and `createTicker` provide bounded cadence with explicit start/stop/dispose; the core renderer never starts a permanent frame loop. 34- **Layers:** `cel.viewport(() => [layer1, layer2])` — array of independent viewport-sized trees, composited bottom-to-top. Conditional inclusion = show/hide. 35- **Key bubbling:** Unconsumed keys bubble up from focused element through ancestors. Root `onKeyPress` = global handler. Escape blur is a fallback default action after bubbling — consuming `escape` prevents blur. 36- **Hit detection:** Topmost layer first, deepest node at (x,y), walk up to find handler. Scroll targets propagate innermost-first when a container `onScroll` returns exactly `false`; TextInput consumes wheel input directly. Click uses the nearest handler; key bubbling is focused-element based. 37 38## Implementation Status 39 40All core systems from the spec are implemented and tested: 41 42- **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints (including cross-axis min/max), gap, padding, justifyContent, alignItems, flexWrap, largest-remainder rounding 43- **Rendering** — cell buffer, ANSI emitter with SGR styling, synchronized output (CSI 2026), differential rendering (emitDiff), full clear on resize 44- **Painting** — grapheme-aware text rendering (CJK/emoji via visibleWidth), overflow clipping via clip rect propagation, scroll content offsetting, scrollbar indicators, container bgColor fill, style inheritance, focusStyle overrides 45- **Input** — Kitty-first keyboard input with baseline disambiguation plus opt-in progressive flags, structured press/repeat/release metadata, alternate/layout keys and associated text, mixed-stream decoding for CSI u / CSI letter / CSI tilde / recoverable legacy control bytes / ESC-prefixed Alt combos, batched SGR mouse handling, hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter) with uncontrolled and controlled modes, onKeyPress bubbling from focused element through ancestors 46- **TextInput** — grapheme-aware text editing (Intl.Segmenter for emoji/ZWJ), controlled or framework-managed cursor movement, stable `stateKey` identity with compatible `onChange` fallback, batched key handling with preserved edit state across stdin chunks, auto-scroll to keep cursor visible, inverted-cell cursor with native terminal cursor positioning (blinking), background fill, placeholder rendering 47- **Layering** — multi-layer compositing, transparency, topmost-layer input priority 48- **Terminal** — Kitty keyboard flag push/pop, mixed keyboard stream compatibility in tmux, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear 49- **Long lists** — callable `VirtualList` component with keyed variable-height measurement, bounded cell-based windowing/overscan, controlled or internal scrolling, sticky bottom, anchor compensation, and resize invalidation 50 51`TODO.md` records the completed quality-pass backlog and is the place to add 52newly reproduced issues or measured opportunities. 53 54## Runtime 55 56- **Bun** for package management and running TypeScript 57- **TypeScript** with strict mode, ESNext target, bundler module resolution 58 59## Commands 60 61```bash 62bun install # install workspace dependencies 63bun run <file.ts> # run any TypeScript file directly 64bun run check # biome lint + import sorting 65bun run check:fix # biome auto-fix 66bun run format # prettier format check 67bun run format:fix # prettier auto-fix 68bun run typecheck # tsc --noEmit type checking 69bun run bench # run benchmark suite (benchmarks/) 70bun run docs # generate HTML + Markdown docs into docs/ 71``` 72 73## Visual Testing with tmux 74 75Use a tmux session to run examples and visually inspect rendered output. 76 77### tmux Configuration 78 79cel-tui is **Kitty-first**, but `tmux` is a supported environment. tmux 3.2+ should have `extended-keys` enabled so it preserves as much modifier information as possible: 80 81``` 82set -s extended-keys on 83``` 84 85With that setting enabled, common keyboard-driven checks work well through `tmux send-keys`. Without it, cel-tui still accepts many recoverable legacy encodings, but historically ambiguous collisions remain collapsed by the host (`ctrl+i`/`tab`, `ctrl+m`/`enter`, `ctrl+[`/`escape`). 86 87### Usage 88 89```bash 90# Create a session (set size to simulate a terminal window) 91tmux new-session -d -s cel -x 80 -y 24 92 93# Run an example 94tmux send-keys -t cel "cd /home/xonecas/src/cel-tui && bun run examples/hello.ts" Enter 95 96# Wait for render, then capture the screen contents 97sleep 1; tmux capture-pane -t cel -p 98 99# Send common keystrokes directly 100# (printable chars, Tab/BTab, Enter, Escape, arrows, many Ctrl+letter combos) 101tmux send-keys -t cel C-q 102 103# Resize the window to test different terminal sizes 104tmux resize-window -t cel -x 60 -y 20 105 106# Kill the session when done 107tmux kill-session -t cel 108``` 109 110This lets you see exactly what the user sees — rendered cells, alignment, clipping, and, via `capture-pane -e -p`, style escape sequences — without needing a real interactive terminal. 111 112### Sending Keys in tmux 113 114For most keyboard-driven manual checks, plain `tmux send-keys` is now sufficient: 115 116```bash 117# Common cases that work well in tmux with extended-keys on 118tmux send-keys -t cel a 119tmux send-keys -t cel Enter 120tmux send-keys -t cel Escape 121tmux send-keys -t cel Tab 122tmux send-keys -t cel BTab 123tmux send-keys -t cel Up 124tmux send-keys -t cel C-q 125tmux send-keys -t cel C-r 126``` 127 128Use exact Kitty-style injection only when you need to test protocol-specific sequences or combos that tmux named keys do not express reliably (for example `shift+enter`, `ctrl+plus`, or a precise CSI-u path): 129 130```bash 131# Helper: convert a key name to hex bytes via kittyEncode 132send_key() { 133 local hex=$(cd /home/xonecas/src/cel-tui && bun -e " 134 const {kittyEncode} = require('./packages/core/src/test-helpers.ts'); 135 const bytes = kittyEncode('$1'); 136 const hex = Array.from(bytes).map(c => c.charCodeAt(0).toString(16).padStart(2,'0')).join(' '); 137 process.stdout.write(hex); 138 ") 139 tmux send-keys -t cel -H $hex 140} 141 142# Usage: 143send_key "ctrl+q" 144send_key "shift+enter" 145send_key "ctrl+plus" 146send_key "shift+tab" 147``` 148 149**Limitations:** the helper lowercases printable input, so uppercase-text insertion is still better tested with plain `tmux send-keys` or in a real terminal. 150 151**Caveat:** `tmux send-keys -H` injects raw bytes one event at a time, while real terminals may batch multiple keyboard or mouse events into a single stdin chunk. Use hex injection to target exact encodings, not to simulate full terminal behavior. 152 153### Mouse Events Don't Work in tmux 154 155SGR mouse events (click, scroll) sent through tmux remain **unreliable** and should not be used for verification. Even with correctly formatted SGR sequences and `mouse off` in tmux config, the injected bytes may not reach the application's stdin in a form the parser recognizes. This is a tmux limitation around raw mouse protocol injection. 156 157**Do not treat tmux as authoritative for mouse interactions (click, scroll).** Use tmux for: 158 159- Keyboard-driven testing via plain `tmux send-keys` for common keys 160- Exact keyboard-sequence injection via `send_key` when you need protocol precision 161- Visual inspection via `tmux capture-pane -p` / `tmux capture-pane -e -p` 162- Verifying layout, alignment, text content, and many keyboard flows 163 164Mouse and scroll behavior still need verification in a real interactive terminal. 165 166### tmux capture-pane Limitations 167 168`tmux capture-pane -p` captures **plain text only** — no colors or style attributes. This means: 169 170- You can verify text content, alignment, and layout structure 171- You **cannot** verify `fgColor`, `bgColor`, `bold`, or `focusStyle` changes from plain-text capture alone 172 173To inspect styling, use `tmux capture-pane -e -p` (includes escape sequences) or verify style output through unit tests against the cell buffer. 174 175## Spec 176 177The `spec.md` file is the source of truth for all API design decisions. Always read it before making changes to core framework behavior. 178 179## Testing Strategy 180 181Use `bun test` (built-in test runner, no extra deps). Test files live next to source as `*.test.ts`. 182 183**TDD for pure logic** — write tests first for: 184 185- Character width (`visibleWidth`, grapheme segmentation, ANSI stripping) 186- Cell buffer (write, read, diff) 187- Layout engine (input tree + available space → output rects) 188- Painting/clipping (node + rect → cell buffer contents) 189- Hit detection (position → node lookup) 190- Focus/key routing (key events → correct handler) 191 192**Integration tests with mock terminal** for: 193 194- Terminal I/O (assert emitted ANSI sequences against an in-memory buffer) 195- End-to-end pipeline (`cel.viewport` → rendered output) 196 197## Commit Format 198 199Use [Conventional Commits](https://www.conventionalcommits.org/): 200 201``` 202<type>(<scope>): <description> 203``` 204 205**Types:** `feat`, `fix`, `test`, `refactor`, `docs`, `chore`, `style` 206 207**Scopes:** `types`, `core`, `components`, `spec`, or omit for repo-wide changes. 208 209**Examples:** 210 211``` 212feat(core): implement visibleWidth with grapheme segmentation 213test(core): add character width tests for CJK, emoji, ANSI 214docs(spec): define Text primitive styling and wrapping 215chore: scaffold monorepo with types, core, components packages 216``` 217 218## Runtime 219 220**Always use `bun` and `bunx` instead of `node`, `npm`, `npx`, or `yarn`.** This is a Bun monorepo — all scripts, package management, and execution should go through Bun. 221 222## Architecture Notes 223 224- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme, kittyKeyboard }` for custom palettes and Kitty progressive-enhancement flags), `cel.viewport(fn)` sets the render function, `cel.render()` requests a differential re-render, `cel.redraw()` forces a full-frame invalidation, `cel.setTheme(theme)` replaces the runtime theme and redraws, and `cel.stop()` restores the terminal. Input handling treats stdin as a mixed stream: keyboard chunks may contain multiple decoded key events, mouse input handles batched SGR events, and TextInput batching preserves the latest value/cursor across multiple keys in one chunk. TextInput `onKeyPress` fires before built-in editing logic — returning `false` prevents the default TextInput action for that key (for example, intercept Enter instead of inserting a newline, or intercept Escape instead of blurring). The TextInput's `onKeyPress` is excluded from ancestor bubbling to avoid double-calling. Escape blur itself runs only after `onKeyPress` bubbling leaves the key unconsumed. 225- `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects. 226- `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets (clamped to max — apps can pass `Infinity` to mean "scroll to end"), scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state (with cursor screen position export for native cursor), TextInput background fill, container bgColor fill, style inheritance threading, focusStyle resolution. 227- `state-identity.ts` — Validates viewport-global `stateKey` values across layers and snapshots mounted state lifecycles. Identity kind changes remount; cleanup is committed only after a successful frame. 228- `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both accept an optional `Theme` plus typed cursor `EmitOptions` and wrap in CSI 2026 synchronized output. The public barrel exports `emitBuffer`, `EmitOptions`, `TerminalCursorState`, and `defaultTheme` (ANSI 16 mapping); differential emission remains a runtime-internal implementation detail. 229- `hit-test.ts` — `hitTest(root, x, y, getScrollOffset?)` → path from root to deepest node at `(x,y)`, accounting for scroll offsets. `findClickHandler`, `findScrollTarget`, `collectKeyPressHandlers`, `collectFocusable` walk paths. 230- `keys.ts` — Kitty-first input decoder. `decodeKeyEvents(data)` splits a raw chunk into ordered structured events, accepting enhanced CSI u (alternate keys, event phase, associated text), CSI letter / CSI tilde, recoverable legacy ASCII control bytes, ESC-prefixed Alt combos, and raw printable text. Events carry semantic `key`, exact optional `text`, phase, key codes, and reported modifiers. `parseKey(data)` remains the single-event semantic convenience wrapper; `normalizeKey()` uses canonical `ctrl+alt+shift+super+hyper+meta+<key>` order. 231- `text-edit.ts` — Pure text editing functions (`insertChar`, `deleteBackward`, `deleteForward`, `moveCursor`). Operates on `EditState` (value + cursor position). Uses `Intl.Segmenter` with grapheme granularity for cursor movement and deletion (handles emoji, ZWJ sequences, combining marks). Used by `cel.ts` to handle TextInput key events. 232- `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache. 233- `terminal.ts` — `ProcessTerminal` (real I/O, Kitty baseline/optional flag push and pop, raw mode, SGR mouse, crash cleanup) and `MockTerminal` (testing). The runtime prefers Kitty semantics but the parser still accepts mixed tmux/legacy keyboard encodings. 234- `packages/components/src/virtual-list.ts` — Callable variable-height list instance. Measures only the active keyed window, uses prefix sums plus spacer nodes for cold rows, preserves the first visible anchor across structural edits, and bounds/release its height cache explicitly. 235 236## Updating gh-pages 237 238The `gh-pages` branch tracks generated API docs (`docs/html/`, `docs/md/`) and an `index.html` for GitHub Pages. To update it after changes land on `main`: 239 240```bash 241git checkout gh-pages 242git merge main # resolve any conflicts, keeping docs tracked 243bun run docs # regenerate API docs 244git add -A 245git commit -m "docs: regenerate API docs from latest main" 246git push 247git checkout main 248``` 249 250**Key differences on gh-pages:** 251 252- `.gitignore` does **not** exclude `docs/html/` or `docs/md/` (they're committed) 253- `.prettierignore` includes `docs/html` and `docs/md` (generated files fail format checks otherwise) 254 255## Publishing to npm 256 257Packages are published to the `@cel-tui` npm org (owner: `xonecas`). They ship TypeScript source directly — no build step. 258 259### Version bump 260 261All four packages share the same version. Bump all together: 262 263```bash 264# In packages/types/package.json, packages/core/package.json, packages/clew/package.json, packages/components/package.json 265# Update "version" to the new value 266``` 267 268Follow [semver](https://semver.org/): patch for fixes, minor for features, major for breaking changes. While `0.x`, minor = breaking is acceptable. 269 270**⚠️ Critical: After bumping versions, regenerate the lockfile:** 271 272```bash 273rm bun.lock && bun install 274``` 275 276`bun publish` resolves `workspace:*` from `bun.lock`, **not** from `package.json`. If you skip this step, the published packages will depend on the old version. `bun install` alone does NOT update workspace versions in an existing lockfile — you must delete and regenerate it. 277 278### Publish order 279 280Must publish in dependency order — types first, then core, then `@cel-tui/clew`, then components: 281 282```bash 283cd packages/types && bun publish --access public 284cd ../core && bun publish --access public 285cd ../clew && bun publish --access public 286cd ../components && bun publish --access public 287``` 288 289If 2FA is enabled, add `--otp <code>` to each command. 290 291### Pre-release documentation audit 292 293Before every release, run a full alignment audit across all documentation surfaces. The goal is to catch stale versions, false capability claims, signature mismatches, and terminology drift between the spec, code, JSDocs, agent docs, and skill files. 294 295**What to read** (in this order — each layer should agree with the ones before it): 296 2971. `packages/types/src/index.ts` — the canonical type definitions and their JSDocs 2982. `packages/core/src/*.ts` — implementation (public function signatures, behavior, exports) 2993. `packages/core/src/index.ts` — what's actually exported to consumers 3004. `packages/clew/src/*.ts` — tokenizer implementation, streaming behavior, exports, and JSDocs 3015. `packages/clew/src/index.ts` — what's actually exported from `@cel-tui/clew` 3026. `packages/components/src/*.ts` — component implementations and JSDocs 3037. `spec.md` — design spec (API tables, prop types, behavior descriptions) 3048. `AGENTS.md` — architecture notes, module descriptions, conventions 3059. `README.md` — user-facing overview and feature claims 30610. `docs/skill/cel-tui/SKILL.md` — agent skill (version, compatibility, patterns, gotchas) 30711. `docs/skill/cel-tui/references/*.md` — API reference and composing guide 30812. `TODO.md` — verify listed bugs/violations are still present or mark resolved 30913. `package.json` files — versions, descriptions, dependency declarations 310 311**What to check at each layer:** 312 313- **Versions** — skill metadata, package.json files, and any version references all match 314- **Capability claims** — if docs say "supports X", verify the code actually implements X (e.g., color spaces, protocol levels, sizing strategies) 315- **Function signatures** — parameter names, types, optional params, return types match between code and docs 316- **Prop tables** — every prop in the type definition appears in the spec table with the correct type and description 317- **Terminology** — consistent naming across all surfaces (e.g., `TextNode` vs `Text`, "uncontrolled" vs "framework-managed") 318- **Behavior descriptions** — bubbling semantics, controlled/uncontrolled modes, default values all match the implementation 319- **Exports** — what `index.ts` exports matches what docs say is available 320- **Compatibility/requirements** — terminal requirements, runtime requirements are stated accurately 321- **TODO.md currency** — bugs listed as open are still present in code; any that were fixed should be removed 322 323**After making fixes**, always verify nothing broke: 324 325```bash 326bun run typecheck && bun test && bun run check && bun run format 327``` 328 329### Pre-publish checklist 330 3311. **Documentation audit passes** (see above) 3322. All tests pass: `bun test` 3333. Types clean: `bun run typecheck` 3344. Lint/format clean: `bun run check && bun run format` 3355. Version bumped in all four `package.json` files 3366. Lockfile regenerated: `rm bun.lock && bun install` 3377. **Pre-publish check passes: `bun run prepublish-check`** (verifies lockfile versions match package.json) 3388. Changes committed and pushed 3399. After publishing, **verify on npm**: `npm view @cel-tui/clew@<version> dependencies --json` and `npm view @cel-tui/components@<version> dependencies --json` 340 341### How it works 342 343- `"files"` in each `package.json` whitelists what ships (source only, no tests) 344- `"exports"` map provides proper module resolution for Bun and bundlers 345- `workspace:*` dependencies are resolved to actual versions by `bun publish` **using versions from `bun.lock`** (not package.json — the lockfile must be regenerated after version bumps) 346- `get-east-asian-width` is a real dependency of `@cel-tui/core` (installs for consumers) 347- `typescript` is a peer dependency (consumers bring their own) 348 349## Non-interactive Commands 350 351Avoid commands that open an interactive editor or prompt from the agent shell. They can hang the tool. 352 353- Always pass messages explicitly for git commands that might invoke `$EDITOR`. 354- Use `git commit -m "..."` and `git tag -a <tag> -m "..."`. 355- Do not run bare `git tag <tag>` during release work. 356 357## Destructive Actions 358 359**Never use `git checkout` or `git restore` on files you have modified.** A single `git checkout <file>` will silently discard all uncommitted changes in that file — including unrelated work. If you need to revert a specific edit, use `edit` to undo just that change. If you must use git to undo something, `git stash` first so the work can be recovered. 360 361More generally: before running any command that could destroy uncommitted work (`git checkout`, `git reset --hard`, `git clean`, `rm` on source files), stop and consider whether there are unsaved changes at risk. If in doubt, `git stash` or `git diff --stat` first. 362 363## Conventions 364 365- All code is TypeScript with strict mode 366- Primitives are functions that return typed Node objects (not classes) 367- Components in `packages/components/` are plain functions using core primitives 368- Key format: all lowercase, modifiers joined by `+` (e.g., `"ctrl+shift+s"`) 369- Colors: 16 numbered palette slots (`"color00"`–`"color15"`), mapped to ANSI 16 by default via `defaultTheme`. Custom themes can remap slots to different ANSI indices or 24-bit true color. Omit `fgColor`/`bgColor` for terminal defaults. Always pair `bgColor` with `fgColor` for contrast.