xonecas.io
70160
Ce

cel-tui / commit 11a74b2

feat: add benchmark suite with Ink comparison

- 7 benchmark files covering every pipeline stage: visibleWidth,
  layout, paint, cell-buffer/emitter, hit-test, keys, end-to-end
- Shared helpers for tree construction (flat, nested, styled,
  scrollable, word-wrap, ink-comparable, app-like)
- Runner script (bun run bench) and documented results
- Ink v6.8.0 comparison: ~65 µs/render vs ~632 µs (renderToString),
  with caveats about different architectures clearly noted
- Add mitata dev dependency for micro-benchmarks
- Update README with Performance section and bench command
- Update AGENTS.md commands, architecture notes (text-edit.ts, keys.ts)
- Update skill docs: Button limitations, alt key gaps, cel.stop() gotcha
- Update api.md: full Select props listing, Button limitation note
- Fix README: cel.stop() in quick example, Select in packages table

xonecas2026-04-04 11a74b2aa9a94dde4c868483174a306ce6bf6b0e parent 9c59431

16 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

AGENTS.md+3−1
@@ -61,6 +61,7 @@ bun run check:fix # biome auto-fix
6161 bun run format # prettier format check
6262 bun run format:fix # prettier auto-fix
6363 bun run typecheck # tsc --noEmit type checking
64+bun run bench # run benchmark suite (benchmarks/)
6465 bun run docs # generate HTML + Markdown docs into docs/
6566 ```
6667
@@ -146,7 +147,8 @@ chore: scaffold monorepo with types, core, components packages
146147 - `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets, scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state, container bgColor fill, style inheritance threading, focusStyle resolution.
147148 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both wrap in CSI 2026 synchronized output.
148149 - `hit-test.ts` — `hitTest(root, x, y)` → path from root to deepest node. `findClickHandler`, `findScrollTarget`, `findKeyPressHandler`, `collectFocusable` walk paths.
149-- `keys.ts` — `parseKey(data)` normalizes terminal input to canonical key strings. `isEditingKey()` identifies keys consumed by TextInput.
150+- `keys.ts` — `parseKey(data)` normalizes terminal input to canonical key strings. `isEditingKey()` identifies keys consumed by TextInput. `normalizeKey()` reorders modifiers to canonical `ctrl+alt+shift+<key>` order.
151+- `text-edit.ts` — Pure text editing functions (`insertChar`, `deleteBackward`, `deleteForward`, `moveCursor`). Operates on `EditState` (value + cursor position). Used by `cel.ts` to handle TextInput key events.
150152 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
151153 - `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, SGR mouse, crash cleanup) and `MockTerminal` (testing).
152154
README.md+18−6
@@ -26,7 +26,10 @@ cel.viewport(() =>
2626 height: "100%",
2727 fgColor: "white",
2828 onKeyPress: (key) => {
29- if (key === "ctrl+q") process.exit();
29+ if (key === "ctrl+q") {
30+ cel.stop();
31+ process.exit();
32+ }
3033 },
3134 },
3235 [
@@ -66,11 +69,11 @@ cel.viewport(() =>
6669
6770 ## Packages
6871
69-| Package | Description |
70-| --------------------- | --------------------------------------------- |
71-| `@cel-tui/types` | Shared type definitions |
72-| `@cel-tui/core` | Framework engine and primitives |
73-| `@cel-tui/components` | Pre-made components (Button, Spacer, Divider) |
72+| Package | Description |
73+| --------------------- | ----------------------------------------------------- |
74+| `@cel-tui/types` | Shared type definitions |
75+| `@cel-tui/core` | Framework engine and primitives |
76+| `@cel-tui/components` | Pre-made components (Button, Spacer, Divider, Select) |
7477
7578 ## Documentation
7679
@@ -78,11 +81,20 @@ cel.viewport(() =>
7881 - **[Specification](spec.md)** — complete design spec covering layout, rendering, input, and focus
7982 - **[Agent Skill](docs/skill/cel-tui/SKILL.md)** — structured guide for AI coding agents to build apps with cel-tui
8083
84+## Performance
85+
86+cel-tui ships a [benchmark suite](benchmarks/) covering every pipeline stage (layout, paint, cell buffer, ANSI emission, hit testing, key parsing). On a comparable tree, the full end-to-end render completes in **~65 µs** — around 15,000 renders/sec. See [benchmarks/RESULTS.md](benchmarks/RESULTS.md) for detailed numbers and an Ink comparison.
87+
88+```bash
89+bun run bench # run all benchmarks
90+```
91+
8192 ## Development
8293
8394 ```bash
8495 bun install # install dependencies
8596 bun test # run tests
97+bun run bench # run benchmarks
8698 bun run check # biome lint
8799 bun run format # prettier check
88100 bun run typecheck # tsc --noEmit
benchmarks/RESULTS.md+224−0
@@ -0,0 +1,224 @@
1+# cel-tui Benchmark Results
2+
3+**Machine:** 12th Gen Intel Core i9-12900, ~4.4 GHz
4+**Runtime:** Bun 1.3.9 (x64-linux)
5+**Date:** 2026-04-04
6+
7+## Ink Comparison (caveat emptor)
8+
9+These numbers compare cel-tui's end-to-end pipeline against Ink using a
10+visually similar tree (styled text, flexbox columns, word-wrap, nested
11+containers with colors — the same shape as Ink's own `benchmark/simple`).
12+
13+**This is not an apples-to-apples comparison.** Ink is a React-based
14+framework that does significantly more work per render: JSX → React
15+reconciliation → Yoga layout (C++ via NAPI) → segment compositing →
16+ANSI output. It supports React hooks, component lifecycle, concurrent
17+mode, and a rich ecosystem of composable components. cel-tui is a
18+minimal stateless framework that builds plain JS objects and writes
19+cells into a flat buffer — it's a fundamentally different (and much
20+simpler) architecture.
21+
22+The comparison is included as a rough reference point, not a claim of
23+superiority. Ink solves a broader set of problems; cel-tui trades
24+features for raw throughput.
25+
26+| What | cel-tui | Ink 6.8.0 | Ratio |
27+| ------------------------------------------ | ---------- | ------------------------------------------------- | ---------- |
28+| **Single render (comparable tree, 80×24)** | **65 µs** | 632 µs (`renderToString`) | **~10×** |
29+| **1,000 re-renders** | **64 ms** | 632 ms (`renderToString`) / 1,462 ms (`rerender`) | **10–23×** |
30+| **Projected 100k re-renders** | **~6.4 s** | ~63 s (`renderToString`) / ~146 s (`rerender`) | **10–23×** |
31+
32+The Ink benchmark script we used is a custom `renderToString` loop (see
33+[How to Reproduce](#how-to-reproduce)), not Ink's own shipped benchmark,
34+which does 100k `rerender()` calls that also write to stdout. Both
35+numbers are included above.
36+
37+### What each framework does per render
38+
39+| Step | cel-tui | Ink |
40+| -------------------- | -------------------------------- | ------------------------------- |
41+| Tree construction | Plain JS objects (~0 cost) | React.createElement + JSX |
42+| Layout | Custom flexbox (TypeScript) | Yoga (C++ via NAPI) |
43+| Painting | Cell buffer (typed array writes) | Segment compositor (string ops) |
44+| Output | ANSI emitter (string concat) | ANSI string builder (chalk) |
45+| State reconciliation | None (stateless) | React reconciler |
46+
47+## cel-tui Pipeline Breakdown
48+
49+### visibleWidth (character measurement)
50+
51+| Input | Time |
52+| ---------------------------- | -------- |
53+| ASCII short (5 chars) | 4.1 ns |
54+| ASCII (64 chars) | 40.3 ns |
55+| ASCII long (640 chars) | 398.6 ns |
56+| CJK + emoji (26 graphemes) | 26.8 ns |
57+| Mixed ASCII + CJK (60 chars) | 5.1 ns |
58+| ANSI escape sequences | 2.9 ns |
59+| Empty string | 0.1 ns |
60+
61+The fast ASCII path dominates — pure ASCII strings bypass grapheme segmentation entirely.
62+
63+### Layout Engine
64+
65+| Tree | Time |
66+| ----------------------------- | -------- |
67+| 10 children (flat) | 1.5 µs |
68+| 100 children (flat) | 11.9 µs |
69+| 1,000 children (flat) | 124.5 µs |
70+| depth=3 breadth=3 (40 nodes) | 3.0 µs |
71+| depth=4 breadth=3 (121 nodes) | 15.3 µs |
72+| depth=3 breadth=5 (156 nodes) | 9.5 µs |
73+| 50 styled groups (200 nodes) | 49.9 µs |
74+| 10 word-wrap paragraphs | 2.6 µs |
75+| 50 word-wrap paragraphs | 12.3 µs |
76+| Ink-comparable tree | 1.6 µs |
77+| App tree (20 messages) | 9.9 µs |
78+| App tree (100 messages) | 37.9 µs |
79+
80+Layout scales linearly with node count (~120 ns/node for flat trees).
81+
82+### Paint (cell buffer writing)
83+
84+| Scenario | Time |
85+| ----------------------------- | ------ |
86+| 10 children (flat, 120×40) | 95 µs |
87+| 100 children (flat, 120×40) | 195 µs |
88+| 1,000 children (flat, 120×40) | 198 µs |
89+| Nested 121 nodes (120×40) | 185 µs |
90+| 50 styled groups (120×40) | 220 µs |
91+| 200 lines scrollable (120×40) | 198 µs |
92+| 50 word-wrapped paragraphs | 283 µs |
93+| Ink-comparable (80×24) | 46 µs |
94+| App tree 20 msgs (120×40) | 187 µs |
95+| 80×24 (small terminal) | 110 µs |
96+| 120×40 (medium terminal) | 209 µs |
97+| 200×50 (large terminal) | 312 µs |
98+
99+Paint is O(cells), not O(nodes) — 100 vs 1,000 children produce similar times because only visible cells are painted. Cost scales with terminal size.
100+
101+### CellBuffer & ANSI Emission
102+
103+| Operation | Time |
104+| ---------------------------- | -------- |
105+| Buffer creation 80×24 | 24.2 µs |
106+| Buffer creation 120×40 | 58.6 µs |
107+| Buffer creation 200×50 | 122.2 µs |
108+| emitBuffer 80×24 (full) | 19.3 µs |
109+| emitBuffer 120×40 (full) | 46.8 µs |
110+| emitDiff 80×24 (no changes) | 11.6 µs |
111+| emitDiff 80×24 (partial) | 11.9 µs |
112+| emitDiff 80×24 (full change) | 10.7 µs |
113+
114+Differential rendering has near-constant cost regardless of change amount — dominated by the comparison scan over all cells.
115+
116+### Hit Test & Focus
117+
118+| Operation | Time |
119+| ---------------------------- | ------- |
120+| hitTest flat 100, center | 135 ns |
121+| hitTest nested 121, center | 35 ns |
122+| hitTest app 50 msgs, center | 102 ns |
123+| hitTest miss (out of bounds) | 1.5 ns |
124+| collectFocusable 100 buttons | 1.15 µs |
125+| collectFocusable app tree | 1.03 µs |
126+
127+### Key Parsing
128+
129+| Input | Time |
130+| --------------------- | ------ |
131+| Printable char 'a' | <1 ns |
132+| Ctrl+C (0x03) | <1 ns |
133+| Escape | <1 ns |
134+| Arrow up (CSI) | 2.7 ns |
135+| Shift+Tab (CSI Z) | 7.6 ns |
136+| F5 (CSI 15~) | 163 ns |
137+| Backspace (0x7F) | 6.8 ns |
138+| normalizeKey "ctrl+s" | 90 ns |
139+
140+### End-to-End Pipeline
141+
142+| Scenario | Time | Renders/sec |
143+| ------------------------- | ------ | ----------- |
144+| Ink-comparable (80×24) | 65 µs | **15,400** |
145+| Flat 100 lines (80×24) | 153 µs | 6,500 |
146+| App tree 20 msgs (120×40) | 267 µs | 3,700 |
147+| Re-render no-change diff | 61 µs | 16,400 |
148+| Re-render +1 message diff | 252 µs | 3,970 |
149+| 1,000 re-renders batch | 64 ms | 15,600 |
150+
151+## Ink Raw Numbers
152+
153+Ink v6.8.0, visually similar tree to cel-tui's "ink-comparable"
154+scenario. Run with Bun 1.3.9 on the same machine. Note: the
155+`renderToString` benchmark was written by us (not shipped by Ink) to
156+isolate the render pipeline from terminal I/O.
157+
158+### `renderToString` (pure pipeline, no I/O)
159+
160+```
161+Run 1: 1,000 renders: 632.75 ms — 632 µs/render
162+Run 2: 1,000 renders: 632.66 ms — 633 µs/render
163+Run 3: 1,000 renders: 630.99 ms — 631 µs/render
164+```
165+
166+### `rerender` (full render with React reconciler + stdout)
167+
168+```
169+Run 1: 1,000 re-renders: 1473.63 ms — 1,474 µs/render
170+Run 2: 1,000 re-renders: 1461.48 ms — 1,461 µs/render
171+Run 3: 1,000 re-renders: 1450.79 ms — 1,451 µs/render
172+```
173+
174+## How to Reproduce
175+
176+```bash
177+# cel-tui benchmarks
178+cd cel-tui
179+bun install
180+bun run benchmarks/run-all.ts # full suite
181+bun run benchmarks/e2e.bench.ts # just the headline numbers
182+
183+# Ink benchmarks
184+git clone https://github.com/vadimdemedes/ink.git /tmp/ink-bench
185+cd /tmp/ink-bench
186+npm install && npm run build
187+
188+# Create a renderToString benchmark (Ink ships rerender-to-stdout only)
189+cat > benchmark/simple/bench-rts.tsx << 'BENCH'
190+import React from "react";
191+import { renderToString, Box, Text } from "../../src/index.js";
192+
193+function App() {
194+ return (
195+ <Box flexDirection="column" padding={1}>
196+ <Text underline bold color="red">{"Hello World"}</Text>
197+ <Box marginTop={1} width={60}>
198+ <Text>
199+ Cupcake ipsum dolor sit amet candy candy. Sesame snaps cookie
200+ I love tootsie roll apple pie bonbon wafer. Caramels sesame
201+ snaps icing cotton candy I love cookie sweet roll.
202+ </Text>
203+ </Box>
204+ <Box marginTop={1} flexDirection="column">
205+ <Text backgroundColor="white" color="black">Colors:</Text>
206+ <Box flexDirection="column" paddingLeft={1}>
207+ <Text>- <Text color="red">Red</Text></Text>
208+ <Text>- <Text color="blue">Blue</Text></Text>
209+ <Text>- <Text color="green">Green</Text></Text>
210+ </Box>
211+ </Box>
212+ </Box>
213+ );
214+}
215+
216+renderToString(<App />, { columns: 80 }); // warmup
217+const start = performance.now();
218+for (let i = 0; i < 1_000; i++) renderToString(<App />, { columns: 80 });
219+const elapsed = performance.now() - start;
220+console.log(`1,000 renders: ${elapsed.toFixed(2)} ms (${(elapsed / 1000).toFixed(3)} ms/render)`);
221+BENCH
222+
223+bun run benchmark/simple/bench-rts.tsx
224+```
benchmarks/cell-buffer.bench.ts+97−0
@@ -0,0 +1,97 @@
1+/**
2+ * Benchmark: CellBuffer — creation, writing, and ANSI emission.
3+ *
4+ * Measures the cost of buffer allocation, full ANSI output generation,
5+ * and differential rendering (the key to fast re-renders).
6+ */
7+
8+import { bench, group, run } from "mitata";
9+import { CellBuffer, emitBuffer } from "@cel-tui/core";
10+import { emitDiff } from "../packages/core/src/emitter.js";
11+import { layout } from "../packages/core/src/layout.js";
12+import { paint } from "../packages/core/src/paint.js";
13+import { appTree, flatTree, inkComparableTree } from "./helpers.js";
14+
15+// --- Buffer creation ---
16+
17+group("CellBuffer: creation", () => {
18+ bench("80×24", () => {
19+ new CellBuffer(80, 24);
20+ });
21+
22+ bench("120×40", () => {
23+ new CellBuffer(120, 40);
24+ });
25+
26+ bench("200×50", () => {
27+ new CellBuffer(200, 50);
28+ });
29+});
30+
31+// --- emitBuffer (full render) ---
32+
33+group("emitBuffer: full render", () => {
34+ // Prepare a painted buffer
35+ const tree80 = layout(appTree(20), 80, 24);
36+ const buf80 = new CellBuffer(80, 24);
37+ paint(tree80, buf80);
38+
39+ const tree120 = layout(appTree(50), 120, 40);
40+ const buf120 = new CellBuffer(120, 40);
41+ paint(tree120, buf120);
42+
43+ bench("80×24 app tree", () => {
44+ emitBuffer(buf80);
45+ });
46+
47+ bench("120×40 app tree", () => {
48+ emitBuffer(buf120);
49+ });
50+});
51+
52+// --- emitDiff (differential render) ---
53+
54+group("emitDiff: no changes", () => {
55+ const tree = layout(appTree(20), 80, 24);
56+ const buf = new CellBuffer(80, 24);
57+ paint(tree, buf);
58+ // Clone the buffer by creating identical content
59+ const buf2 = new CellBuffer(80, 24);
60+ paint(tree, buf2);
61+
62+ bench("80×24 identical buffers", () => {
63+ emitDiff(buf, buf2);
64+ });
65+});
66+
67+group("emitDiff: partial changes", () => {
68+ // Base buffer
69+ const tree1 = layout(appTree(20), 80, 24);
70+ const buf1 = new CellBuffer(80, 24);
71+ paint(tree1, buf1);
72+
73+ // Changed buffer — different message count changes bottom portion
74+ const tree2 = layout(appTree(21), 80, 24);
75+ const buf2 = new CellBuffer(80, 24);
76+ paint(tree2, buf2);
77+
78+ bench("80×24 one message added", () => {
79+ emitDiff(buf1, buf2);
80+ });
81+});
82+
83+group("emitDiff: full change", () => {
84+ const tree1 = layout(flatTree(24), 80, 24);
85+ const buf1 = new CellBuffer(80, 24);
86+ paint(tree1, buf1);
87+
88+ const tree2 = layout(flatTree(100), 80, 24);
89+ const buf2 = new CellBuffer(80, 24);
90+ paint(tree2, buf2);
91+
92+ bench("80×24 completely different", () => {
93+ emitDiff(buf1, buf2);
94+ });
95+});
96+
97+await run();
benchmarks/e2e.bench.ts+105−0
@@ -0,0 +1,105 @@
1+/**
2+ * Benchmark: end-to-end render pipeline.
3+ *
4+ * Tree construction → layout → paint → emit.
5+ * This is the headline number — how fast can we go from state change
6+ * to terminal output?
7+ *
8+ * Also includes the Ink-comparable scenario (same tree shape as Ink's
9+ * benchmark/simple) for direct comparison.
10+ */
11+
12+import { bench, group, run } from "mitata";
13+import { CellBuffer, emitBuffer } from "@cel-tui/core";
14+import { emitDiff } from "../packages/core/src/emitter.js";
15+import { layout } from "../packages/core/src/layout.js";
16+import { paint } from "../packages/core/src/paint.js";
17+import { flatTree, inkComparableTree, appTree } from "./helpers.js";
18+
19+// --- Full pipeline: tree → layout → paint → emit ---
20+
21+group("e2e: full pipeline", () => {
22+ bench("ink-comparable (80×24)", () => {
23+ const tree = inkComparableTree();
24+ const l = layout(tree, 80, 24);
25+ const buf = new CellBuffer(80, 24);
26+ paint(l, buf);
27+ emitBuffer(buf);
28+ });
29+
30+ bench("app tree 20 msgs (120×40)", () => {
31+ const tree = appTree(20);
32+ const l = layout(tree, 120, 40);
33+ const buf = new CellBuffer(120, 40);
34+ paint(l, buf);
35+ emitBuffer(buf);
36+ });
37+
38+ bench("flat 100 lines (80×24)", () => {
39+ const tree = flatTree(100);
40+ const l = layout(tree, 80, 24);
41+ const buf = new CellBuffer(80, 24);
42+ paint(l, buf);
43+ emitBuffer(buf);
44+ });
45+});
46+
47+// --- Re-render with diff (the common case) ---
48+
49+group("e2e: re-render with diff", () => {
50+ // Simulate: first render, then re-render identical tree (no changes)
51+ const tree = inkComparableTree();
52+ const l = layout(tree, 80, 24);
53+ const prevBuf = new CellBuffer(80, 24);
54+ paint(l, prevBuf);
55+
56+ bench("ink-comparable no-change diff", () => {
57+ const tree2 = inkComparableTree();
58+ const l2 = layout(tree2, 80, 24);
59+ const buf = new CellBuffer(80, 24);
60+ paint(l2, buf);
61+ emitDiff(prevBuf, buf);
62+ });
63+});
64+
65+group("e2e: re-render with partial change", () => {
66+ const tree1 = appTree(20);
67+ const l1 = layout(tree1, 120, 40);
68+ const prevBuf = new CellBuffer(120, 40);
69+ paint(l1, prevBuf);
70+
71+ bench("app tree +1 message diff", () => {
72+ const tree2 = appTree(21);
73+ const l2 = layout(tree2, 120, 40);
74+ const buf = new CellBuffer(120, 40);
75+ paint(l2, buf);
76+ emitDiff(prevBuf, buf);
77+ });
78+});
79+
80+// --- Ink comparison: 100k re-renders ---
81+// Ink's benchmark does 100,000 rerender() calls of the same tree.
82+// We measure a single re-render and also the total for 100k.
83+
84+group("e2e: ink comparison — re-render throughput", () => {
85+ bench("single re-render (ink-comparable tree)", () => {
86+ const tree = inkComparableTree();
87+ const l = layout(tree, 80, 24);
88+ const buf = new CellBuffer(80, 24);
89+ paint(l, buf);
90+ emitBuffer(buf);
91+ });
92+
93+ // Measure 1000 iterations as a batch to get a total time
94+ bench("1000 re-renders (ink-comparable tree)", () => {
95+ for (let i = 0; i < 1000; i++) {
96+ const tree = inkComparableTree();
97+ const l = layout(tree, 80, 24);
98+ const buf = new CellBuffer(80, 24);
99+ paint(l, buf);
100+ emitBuffer(buf);
101+ }
102+ });
103+});
104+
105+await run();
benchmarks/helpers.ts+141−0
@@ -0,0 +1,141 @@
1+/**
2+ * Shared helpers for benchmark tree construction.
3+ */
4+
5+import type { Node, ContainerNode } from "@cel-tui/types";
6+import { VStack, HStack, Text, TextInput } from "@cel-tui/core";
7+
8+/** Build a flat VStack with N Text children. */
9+export function flatTree(n: number): ContainerNode {
10+ const children: Node[] = [];
11+ for (let i = 0; i < n; i++) {
12+ children.push(
13+ Text(`Line ${i}: The quick brown fox jumps over the lazy dog`),
14+ );
15+ }
16+ return VStack({ height: "100%" }, children);
17+}
18+
19+/** Build a nested tree: depth levels of alternating VStack/HStack, `breadth` children per level. */
20+export function nestedTree(depth: number, breadth: number): ContainerNode {
21+ function build(d: number, isV: boolean): Node {
22+ if (d === 0) {
23+ return Text("leaf content here");
24+ }
25+ const children: Node[] = [];
26+ for (let i = 0; i < breadth; i++) {
27+ children.push(build(d - 1, !isV));
28+ }
29+ return isV ? VStack({ flex: 1 }, children) : HStack({ flex: 1 }, children);
30+ }
31+ return build(depth, true) as ContainerNode;
32+}
33+
34+/** Build a styled tree with bgColor, fgColor, bold, focusStyle — stress inheritance. */
35+export function styledTree(n: number): ContainerNode {
36+ const children: Node[] = [];
37+ for (let i = 0; i < n; i++) {
38+ children.push(
39+ VStack({ fgColor: "cyan", bgColor: "black", padding: { x: 1 } }, [
40+ Text(`Styled line ${i}`, { bold: true, fgColor: "yellow" }),
41+ HStack({ fgColor: "white" }, [
42+ Text("left "),
43+ Text("right", { fgColor: "green" }),
44+ ]),
45+ ]),
46+ );
47+ }
48+ return VStack(
49+ { height: "100%", fgColor: "white", bgColor: "blue" },
50+ children,
51+ );
52+}
53+
54+/** Build a scrollable tree with more content than fits. */
55+export function scrollableTree(lines: number): ContainerNode {
56+ const children: Node[] = [];
57+ for (let i = 0; i < lines; i++) {
58+ children.push(Text(`Scrollable line ${i}: lorem ipsum dolor sit amet`));
59+ }
60+ return VStack(
61+ { height: "100%", overflow: "scroll", scrollbar: true },
62+ children,
63+ );
64+}
65+
66+/** Build a word-wrap heavy tree. */
67+export function wrappedTextTree(paragraphs: number): ContainerNode {
68+ const lorem =
69+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.";
70+ const children: Node[] = [];
71+ for (let i = 0; i < paragraphs; i++) {
72+ children.push(Text(lorem, { wrap: "word" }));
73+ }
74+ return VStack({ height: "100%" }, children);
75+}
76+
77+/** Build a tree resembling the Ink benchmark: styled text, flex layout, word-wrap. */
78+export function inkComparableTree(): ContainerNode {
79+ return VStack({ padding: { y: 1, x: 1 } }, [
80+ Text("Hello World", { underline: true, bold: true, fgColor: "red" }),
81+ VStack({ width: 60 }, [
82+ Text(
83+ "Cupcake ipsum dolor sit amet candy candy. Sesame snaps cookie I love tootsie roll apple pie bonbon wafer. Caramels sesame snaps icing cotton candy I love cookie sweet roll. I love bonbon sweet.",
84+ { wrap: "word" },
85+ ),
86+ ]),
87+ VStack({}, [
88+ Text("Colors:", { fgColor: "black", bgColor: "white" }),
89+ VStack({ padding: { x: 1 } }, [
90+ Text("- Red", { fgColor: "red" }),
91+ Text("- Blue", { fgColor: "blue" }),
92+ Text("- Green", { fgColor: "green" }),
93+ ]),
94+ ]),
95+ ]);
96+}
97+
98+/** Build a complex app-like tree (header, scrollable body, input bar). */
99+export function appTree(messageCount: number): ContainerNode {
100+ const messages: Node[] = [];
101+ for (let i = 0; i < messageCount; i++) {
102+ messages.push(
103+ VStack({}, [
104+ Text(`▶ User message ${i}`, { bold: true, fgColor: "blue" }),
105+ Text(
106+ ` This is the content of message ${i}. It can be quite long and detailed.`,
107+ ),
108+ ]),
109+ );
110+ }
111+ return VStack({ height: "100%", fgColor: "white" }, [
112+ // Header
113+ HStack({ height: 1, padding: { x: 1 } }, [
114+ Text("Agent Chat", { bold: true }),
115+ VStack({ flex: 1 }, []),
116+ Text("model: gpt", { fgColor: "brightBlack" }),
117+ ]),
118+ // Body
119+ VStack(
120+ { flex: 1, overflow: "scroll", scrollbar: true, padding: { x: 1 } },
121+ messages,
122+ ),
123+ // Input bar
124+ HStack({ height: 1, padding: { x: 1 }, gap: 1 }, [
125+ Text("> "),
126+ Text("type a message...", { fgColor: "brightBlack" }),
127+ HStack({ bgColor: "brightBlack" }, [Text("[Send]", { bold: true })]),
128+ ]),
129+ ]);
130+}
131+
132+/** Pure ASCII string for width benchmarking. */
133+export const ASCII_STRING =
134+ "The quick brown fox jumps over the lazy dog. 0123456789!@#$%^&*()";
135+
136+/** CJK + emoji string for width benchmarking. */
137+export const CJK_EMOJI_STRING = "世界你好 🌍🎉 東京タワー 한국어 テスト 😀👨‍👩‍👧";
138+
139+/** Mixed content string. */
140+export const MIXED_STRING =
141+ "Hello 世界! Testing 🎉 mixed content with ASCII and CJK 東京.";
benchmarks/hit-test.bench.ts+66−0
@@ -0,0 +1,66 @@
1+/**
2+ * Benchmark: hit testing and focus collection.
3+ *
4+ * Measures the cost of spatial lookups used for mouse click/scroll
5+ * routing and keyboard focus traversal.
6+ */
7+
8+import { bench, group, run } from "mitata";
9+import { layout } from "../packages/core/src/layout.js";
10+import { hitTest, collectFocusable } from "../packages/core/src/hit-test.js";
11+import { flatTree, nestedTree, appTree } from "./helpers.js";
12+import { VStack, HStack, Text } from "@cel-tui/core";
13+import type { Node } from "@cel-tui/types";
14+
15+const W = 120;
16+const H = 40;
17+
18+// --- hitTest ---
19+
20+group("hitTest", () => {
21+ const flatL = layout(flatTree(100), W, H);
22+ bench("flat tree (100 children), center", () => {
23+ hitTest(flatL, 60, 20);
24+ });
25+
26+ const nestedL = layout(nestedTree(4, 3), W, H);
27+ bench("nested tree (121 nodes), center", () => {
28+ hitTest(nestedL, 60, 20);
29+ });
30+
31+ const appL = layout(appTree(50), W, H);
32+ bench("app tree (50 messages), corner", () => {
33+ hitTest(appL, 0, 0);
34+ });
35+
36+ bench("app tree (50 messages), center", () => {
37+ hitTest(appL, 60, 20);
38+ });
39+
40+ bench("app tree (50 messages), miss", () => {
41+ hitTest(appL, 200, 200);
42+ });
43+});
44+
45+// --- collectFocusable ---
46+
47+group("collectFocusable", () => {
48+ // Build a tree with many focusable elements
49+ const buttons: Node[] = [];
50+ for (let i = 0; i < 100; i++) {
51+ buttons.push(HStack({ onClick: () => {} }, [Text(`Button ${i}`)]));
52+ }
53+ const focusableTree = VStack({ height: "100%" }, buttons);
54+ const focusableL = layout(focusableTree, W, H);
55+
56+ bench("100 focusable buttons", () => {
57+ collectFocusable(focusableL);
58+ });
59+
60+ const appL = layout(appTree(50), W, H);
61+ bench("app tree (few focusables)", () => {
62+ collectFocusable(appL);
63+ });
64+});
65+
66+await run();
benchmarks/keys.bench.ts+77−0
@@ -0,0 +1,77 @@
1+/**
2+ * Benchmark: key parsing and normalization.
3+ *
4+ * Measures the cost of parsing raw terminal input into canonical
5+ * key strings. Called on every keystroke.
6+ */
7+
8+import { bench, group, run } from "mitata";
9+import {
10+ parseKey,
11+ normalizeKey,
12+ isEditingKey,
13+} from "../packages/core/src/keys.js";
14+
15+group("parseKey", () => {
16+ bench("printable char 'a'", () => {
17+ parseKey("a");
18+ });
19+
20+ bench("ctrl+c (0x03)", () => {
21+ parseKey("\x03");
22+ });
23+
24+ bench("escape", () => {
25+ parseKey("\x1b");
26+ });
27+
28+ bench("arrow up (CSI A)", () => {
29+ parseKey("\x1b[A");
30+ });
31+
32+ bench("shift+tab (CSI Z)", () => {
33+ parseKey("\x1b[Z");
34+ });
35+
36+ bench("F5 (CSI 15~)", () => {
37+ parseKey("\x1b[15~");
38+ });
39+
40+ bench("backspace (0x7F)", () => {
41+ parseKey("\x7f");
42+ });
43+});
44+
45+group("normalizeKey", () => {
46+ bench("simple key 'a'", () => {
47+ normalizeKey("a");
48+ });
49+
50+ bench("ctrl+s", () => {
51+ normalizeKey("ctrl+s");
52+ });
53+
54+ bench("shift+ctrl+s (reorder)", () => {
55+ normalizeKey("shift+ctrl+s");
56+ });
57+
58+ bench("ctrl+alt+shift+x", () => {
59+ normalizeKey("ctrl+alt+shift+x");
60+ });
61+});
62+
63+group("isEditingKey", () => {
64+ bench("'a' (editing)", () => {
65+ isEditingKey("a");
66+ });
67+
68+ bench("'enter' (editing)", () => {
69+ isEditingKey("enter");
70+ });
71+
72+ bench("'ctrl+s' (not editing)", () => {
73+ isEditingKey("ctrl+s");
74+ });
75+});
76+
77+await run();
benchmarks/layout.bench.ts+110−0
@@ -0,0 +1,110 @@
1+/**
2+ * Benchmark: layout engine — flexbox sizing and positioning.
3+ *
4+ * Measures the cost of computing absolute screen rects for various
5+ * tree shapes and sizes.
6+ */
7+
8+import { bench, group, run } from "mitata";
9+import { layout } from "../packages/core/src/layout.js";
10+import {
11+ flatTree,
12+ nestedTree,
13+ styledTree,
14+ wrappedTextTree,
15+ inkComparableTree,
16+ appTree,
17+} from "./helpers.js";
18+
19+const W = 120;
20+const H = 40;
21+
22+// --- Flat trees (varying child count) ---
23+
24+group("layout: flat tree", () => {
25+ const t10 = flatTree(10);
26+ const t100 = flatTree(100);
27+ const t1000 = flatTree(1000);
28+
29+ bench("10 children", () => {
30+ layout(t10, W, H);
31+ });
32+
33+ bench("100 children", () => {
34+ layout(t100, W, H);
35+ });
36+
37+ bench("1000 children", () => {
38+ layout(t1000, W, H);
39+ });
40+});
41+
42+// --- Nested trees (depth × breadth) ---
43+
44+group("layout: nested tree", () => {
45+ const d3b3 = nestedTree(3, 3); // 3^3 = 27 leaves
46+ const d4b3 = nestedTree(4, 3); // 3^4 = 81 leaves
47+ const d3b5 = nestedTree(3, 5); // 5^3 = 125 leaves
48+
49+ bench("depth=3 breadth=3 (40 nodes)", () => {
50+ layout(d3b3, W, H);
51+ });
52+
53+ bench("depth=4 breadth=3 (121 nodes)", () => {
54+ layout(d4b3, W, H);
55+ });
56+
57+ bench("depth=3 breadth=5 (156 nodes)", () => {
58+ layout(d3b5, W, H);
59+ });
60+});
61+
62+// --- Styled tree (inheritance overhead) ---
63+
64+group("layout: styled tree", () => {
65+ const s50 = styledTree(50);
66+ bench("50 styled groups", () => {
67+ layout(s50, W, H);
68+ });
69+});
70+
71+// --- Word-wrap text ---
72+
73+group("layout: word-wrap", () => {
74+ const w10 = wrappedTextTree(10);
75+ const w50 = wrappedTextTree(50);
76+
77+ bench("10 paragraphs", () => {
78+ layout(w10, W, H);
79+ });
80+
81+ bench("50 paragraphs", () => {
82+ layout(w50, W, H);
83+ });
84+});
85+
86+// --- Ink-comparable tree ---
87+
88+group("layout: ink-comparable", () => {
89+ const tree = inkComparableTree();
90+ bench("styled flex + word-wrap", () => {
91+ layout(tree, 80, 24);
92+ });
93+});
94+
95+// --- App-like tree ---
96+
97+group("layout: app tree", () => {
98+ const a20 = appTree(20);
99+ const a100 = appTree(100);
100+
101+ bench("20 messages", () => {
102+ layout(a20, W, H);
103+ });
104+
105+ bench("100 messages", () => {
106+ layout(a100, W, H);
107+ });
108+});
109+
110+await run();
benchmarks/paint.bench.ts+140−0
@@ -0,0 +1,140 @@
1+/**
2+ * Benchmark: paint — writing styled cells into the cell buffer.
3+ *
4+ * Measures the cost of painting laid-out trees into a CellBuffer,
5+ * including text rendering, style inheritance, clipping, and scrollbars.
6+ */
7+
8+import { bench, group, run } from "mitata";
9+import { CellBuffer } from "@cel-tui/core";
10+import { layout } from "../packages/core/src/layout.js";
11+import { paint } from "../packages/core/src/paint.js";
12+import {
13+ flatTree,
14+ nestedTree,
15+ styledTree,
16+ scrollableTree,
17+ wrappedTextTree,
18+ inkComparableTree,
19+ appTree,
20+} from "./helpers.js";
21+
22+const W = 120;
23+const H = 40;
24+
25+// --- Flat tree paint ---
26+
27+group("paint: flat tree", () => {
28+ const l10 = layout(flatTree(10), W, H);
29+ const l100 = layout(flatTree(100), W, H);
30+ const l1000 = layout(flatTree(1000), W, H);
31+
32+ bench("10 children", () => {
33+ const buf = new CellBuffer(W, H);
34+ paint(l10, buf);
35+ });
36+
37+ bench("100 children", () => {
38+ const buf = new CellBuffer(W, H);
39+ paint(l100, buf);
40+ });
41+
42+ bench("1000 children", () => {
43+ const buf = new CellBuffer(W, H);
44+ paint(l1000, buf);
45+ });
46+});
47+
48+// --- Nested tree paint ---
49+
50+group("paint: nested tree", () => {
51+ const l = layout(nestedTree(4, 3), W, H);
52+ bench("depth=4 breadth=3 (121 nodes)", () => {
53+ const buf = new CellBuffer(W, H);
54+ paint(l, buf);
55+ });
56+});
57+
58+// --- Styled tree (inheritance + bgColor fill) ---
59+
60+group("paint: styled tree", () => {
61+ const l = layout(styledTree(50), W, H);
62+ bench("50 styled groups", () => {
63+ const buf = new CellBuffer(W, H);
64+ paint(l, buf);
65+ });
66+});
67+
68+// --- Scrollable (clipping + scrollbar) ---
69+
70+group("paint: scrollable", () => {
71+ const l = layout(scrollableTree(200), W, H);
72+ bench("200 lines scrollable", () => {
73+ const buf = new CellBuffer(W, H);
74+ paint(l, buf);
75+ });
76+});
77+
78+// --- Word-wrap ---
79+
80+group("paint: word-wrap", () => {
81+ const l = layout(wrappedTextTree(50), W, H);
82+ bench("50 word-wrapped paragraphs", () => {
83+ const buf = new CellBuffer(W, H);
84+ paint(l, buf);
85+ });
86+});
87+
88+// --- Ink-comparable ---
89+
90+group("paint: ink-comparable", () => {
91+ const l = layout(inkComparableTree(), 80, 24);
92+ bench("styled flex + word-wrap", () => {
93+ const buf = new CellBuffer(80, 24);
94+ paint(l, buf);
95+ });
96+});
97+
98+// --- App tree ---
99+
100+group("paint: app tree", () => {
101+ const l20 = layout(appTree(20), W, H);
102+ const l100 = layout(appTree(100), W, H);
103+
104+ bench("20 messages", () => {
Cut short: this commit's diff is over 1000 lines.
benchmarks/run-all.ts+43−0
Cut short: this commit's diff is over 1000 lines.
benchmarks/width.bench.ts+46−0
Cut short: this commit's diff is over 1000 lines.
bun.lock+3−0
Cut short: this commit's diff is over 1000 lines.
docs/skill/cel-tui/SKILL.md+3−0
Cut short: this commit's diff is over 1000 lines.
docs/skill/cel-tui/references/api.md+5−0
Cut short: this commit's diff is over 1000 lines.
package.json+2−0
Cut short: this commit's diff is over 1000 lines.