xonecas.io
70160
Ce

cel-tui / commit 21afdb5

feat!: release v0.9.0

Complete the measured runtime, layout, input, component, tokenizer, documentation, and benchmark quality pass.

BREAKING CHANGE: TextInput exposes only supported base props; Cell values are readonly; keyboard, Select, focus, terminal, and syntax-theme behavior follows the updated 0.9.0 contract.

xonecas2026-07-09 21afdb5f2a5add5d94f30ce559e105285c8a3d17 parent 3e49b22

94 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+15−9
@@ -22,13 +22,15 @@ Dependency graph: `core → types`, `components → core`, `components → types
2222
2323 - **4 primitives only:** VStack, HStack (layout), Text (content leaf), TextInput (editable container)
2424 - **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.
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.
2627 - **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.
2728 - **focusStyle:** Containers accept `focusStyle: StyleProps` — style overrides applied when focused, participating in inheritance.
2829 - **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.
2930 - **Text is a pure leaf:** No sizing props, no children. Parent controls the box. Height is intrinsic (from content + wrapping).
3031 - **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.
3132 - **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.
3234 - **Layers:** `cel.viewport(() => [layer1, layer2])` — array of independent viewport-sized trees, composited bottom-to-top. Conditional inclusion = show/hide.
3335 - **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.
3436 - **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.
@@ -40,12 +42,14 @@ All core systems from the spec are implemented and tested:
4042 - **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints (including cross-axis min/max), gap, padding, justifyContent, alignItems, flexWrap, largest-remainder rounding
4143 - **Rendering** — cell buffer, ANSI emitter with SGR styling, synchronized output (CSI 2026), differential rendering (emitDiff), full clear on resize
4244 - **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
43-- **Input** — Kitty-first keyboard input (Kitty level 1 enable), 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
44-- **TextInput** — grapheme-aware text editing (Intl.Segmenter for emoji/ZWJ), cursor movement, cursor persistence across re-renders (keyed on onChange, clamped on external value changes), 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
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 th …
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
4547 - **Layering** — multi-layer compositing, transparency, topmost-layer input priority
46-- **Terminal** — Kitty level 1 enable/disable, mixed keyboard stream compatibility in tmux, crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
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
4750
48-See `TODO.md` for remaining spec violations and future work.
51+`TODO.md` records the completed quality-pass backlog and is the place to add
52+newly reproduced issues or measured opportunities.
4953
5054 ## Runtime
5155
@@ -217,15 +221,17 @@ chore: scaffold monorepo with types, core, components packages
217221
218222 ## Architecture Notes
219223
220-- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal, options?)` starts (accepts optional `{ theme }` for custom color themes), `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores 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 m …
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 treat …
221225 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
222226 - `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.
223-- `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both accept an optional `Theme` for color resolution and wrap in CSI 2026 synchronized output. Exports `defaultTheme` (ANSI 16 mapping).
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.
224229 - `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.
225-- `keys.ts` — Kitty-first input decoder. `decodeKeyEvents(data)` splits a raw chunk into ordered key events, accepting CSI u / CSI letter / CSI tilde sequences, recoverable legacy ASCII control bytes, ESC-prefixed Alt combos, and raw printable text. Key events carry a normalized semantic `key` plus optional original insertable `text`. `parseKey(data)` remains as a convenience wrapper for single-event cases. `isEditingKey()` identifies non-text editing/navigation keys consumed by TextInput, and …
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 canonica …
226231 - `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.
227232 - `width.ts` — `visibleWidth(str)` measures terminal column width. Fast ASCII path, grapheme segmentation, East Asian width, ANSI stripping, LRU cache.
228-- `terminal.ts` — `ProcessTerminal` (real I/O, raw mode, Kitty keyboard protocol level 1 enable, SGR mouse, crash cleanup) and `MockTerminal` (testing). The runtime prefers Kitty semantics but the parser still accepts mixed tmux/legacy keyboard encodings.
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.
229235
230236 ## Updating gh-pages
231237
README.md+19−10
@@ -60,21 +60,29 @@ cel.viewport(() =>
6060
6161 - **State is external** — the framework renders what you give it. Use any state approach.
6262 - **`cel.viewport(() => tree)`** sets the render function, **`cel.render()`** triggers re-renders.
63+- **Explicit invalidation** — `cel.redraw()` repairs externally corrupted screens; `cel.setTheme(theme)` replaces the runtime palette and redraws automatically.
6364 - **Flexbox layout** — fixed, flex, percentage, and intrinsic sizing with gap, padding, alignment.
6465 - **Layers** — return an array for multi-layer compositing (modals, overlays).
6566 - **Uncontrolled by default** — focus and scroll just work. Opt into controlled mode when needed.
67+- **Stable state identity** — `stateKey` keeps focus, scroll, and TextInput state attached through reordering; `autoFocus` seeds the active layer once.
68+- **Controlled caret when needed** — TextInput `cursor` / `onCursorChange` enables grapheme-safe completion and range-replacement workflows.
69+- **Cursor shape control** — TextInput `cursorStyle` keeps block, bar, or underline painted/native cursors aligned.
6670 - **Adaptive wheel scrolling** — scrollables and TextInput use an adaptive mouse-wheel step by default; override it with `scrollStep` when needed.
6771 - **Content measurement helper** — `measureContentHeight(node, { width })` lets apps preserve scroll anchors when prepending intrinsically sized content.
72+- **Bounded long lists** — callable `VirtualList()` instances measure variable-height keyed rows, window by cell offset with overscan, preserve scroll anchors, and support controlled or sticky-bottom scrolling.
6873 - **Terminal title helper** — `cel.setTitle("My App")` updates the window/tab title when the host honors OSC titles.
6974 - **Style inheritance** — containers propagate styles to descendants. `bgColor` fills the rect.
75+- **Custom scrollbars** — `scrollbarStyle` controls thumb/track characters and terminal styles.
7076 - **16-color palette** — numbered slots (`"color00"`–`"color15"`) mapped to ANSI 16 by default. Custom themes can remap to different ANSI indices or 24-bit true color.
7177 - **Cell buffer rendering** — styled cells, differential updates, synchronized output.
72-- **Kitty-first keyboard input** — cel-tui enables Kitty level 1 for full modifier fidelity, works well in `tmux` with `set -s extended-keys on`, and accepts recoverable legacy encodings when the host does not preserve a pure Kitty stream.
78+- **Opt-in managed animation** — `Spinner()` and `createTicker()` cap render cadence and expose explicit start/stop/dispose lifecycles; the default renderer remains timer-free.
79+- **Kitty-first keyboard input** — baseline disambiguation is enabled by default; optional `kittyKeyboard` flags expose repeat/release phases, alternate-layout keys, all-key events, and associated text. Mixed tmux/legacy input remains supported.
7380 - **TextInput editing shortcuts** — focused inputs support familiar readline-style editing (`ctrl+a/e`, `alt+b/f`, `ctrl+left/right`, `ctrl+w`, `alt+d`), and `up` / `down` follow visual wrapped lines.
81+- **TextInput-backed Select** — filterable lists share exact text, grapheme-safe cursor editing, and bracketed paste behavior with TextInput, with optional controlled query/highlight models for async overlays.
7482
7583 ## Terminal Compatibility
7684
77-- **First-class:** Kitty-compatible terminals such as Kitty, WezTerm, Ghostty, foot, Alacritty, and Windows Terminal
85+- **First-class:** Kitty-compatible terminals such as Kitty, WezTerm, Ghostty, foot, Alacritty, and Windows Terminal 1.25+
7886 - **First-class:** `tmux` with `set -s extended-keys on`
7987 - **Best effort:** legacy terminals or multiplexers that collapse some modifier distinctions
8088
@@ -82,12 +90,12 @@ Some historical legacy collisions remain impossible to recover once a host has a
8290
8391 ## Packages
8492
85-| Package | Description |
86-| --------------------- | ------------------------------------------------------------------------------------------ |
87-| `@cel-tui/types` | Shared type definitions |
88-| `@cel-tui/core` | Framework engine and primitives |
89-| `@cel-tui/clew` | Stream-first syntax tokenization library |
90-| `@cel-tui/components` | Pre-made components (Button, Spacer, Divider, VDivider, Select, Markdown, SyntaxHighlight) |
93+| Package | Description |
94+| --------------------- | ---------------------------------------------------------------------------------------------------------------- |
95+| `@cel-tui/types` | Shared type definitions |
96+| `@cel-tui/core` | Framework engine and primitives |
97+| `@cel-tui/clew` | Stream-first syntax tokenization library |
98+| `@cel-tui/components` | Pre-made components (Button, Spacer, Divider, VDivider, Select, VirtualList, Spinner, Markdown, SyntaxHighlight) |
9199
92100 ## Documentation
93101
@@ -97,10 +105,11 @@ Some historical legacy collisions remain impossible to recover once a host has a
97105
98106 ## Performance
99107
100-cel-tui ships a benchmark suite 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.
108+cel-tui ships a benchmark suite covering every pipeline stage (layout, paint, cell buffer, ANSI emission, hit testing, key parsing). See [benchmarks/RESULTS.md](benchmarks/RESULTS.md) for historical measurements and the benchmark methodology. For before/after work, compare repeated runs on the same machine, Bun version, and power profile.
101109
102110 ```bash
103-bun run bench # run all benchmarks
111+bun run bench # detailed exploratory suite
112+bun run bench:regression # fixed-work JSON for before/after comparisons
104113 ```
105114
106115 ## Development
TODO.md+82−17
@@ -1,30 +1,95 @@
11 # cel-tui — TODO
22
3-Open work that remains after the stability pass.
3+There are currently no known open items. The mini-coder integration findings
4+and former future enhancements were completed in the 2026-07-09 quality pass.
5+Add newly reproduced issues or measured opportunities here rather than relying
6+on undocumented workarounds.
47
5-## Current state
8+## Completed quality pass
69
7-- Core systems from the spec are implemented.
8-- The current repo state is green: `bun run typecheck`, `bun test`, `bun run check`, and `bun run format` pass.
9-- The previous stability blockers have been addressed: flex redistribution now respects constraints, scroll hit testing clamps like paint, ProcessTerminal cleans up crash listeners, focus callbacks include reasons, TextInput scroll behavior is specified and aligned, `repeat: "fill"` claims horizontal flex space, and the known docs/capability overclaims were removed.
10-- There are no known blockers left for honestly calling the framework stable.
10+### Core runtime and interaction
1111
12-## Legend
12+- ✅ **Runtime theme replacement and explicit full redraw** — `cel.setTheme()`
13+ replaces the palette and schedules a full frame; `cel.redraw()` repairs
14+ terminal resume/external corruption without private buffer access. Full
15+ redraws also restore the SGR baseline and native cursor state.
16+- ✅ **Stable identity for stateful nodes** — viewport-global `stateKey`
17+ identities retain TextInput cursor/scroll, uncontrolled container scroll,
18+ and per-layer focus through callback recreation, insertion, and reordering.
19+ Duplicate keys fail deterministically, node-kind changes remount, and absence
20+ for one successful frame releases keyed state. Legacy callback/path/index
21+ fallbacks remain available.
22+- ✅ **Layer-aware initial focus** — `autoFocus` seeds the active topmost layer
23+ once per mounted identity with reason `"auto"`, does not reclaim after
24+ Escape, and allows underlying focus to resume after a modal disappears.
25+- ✅ **Observable and controllable TextInput cursor** — `cursor` and
26+ `onCursorChange` expose controlled UTF-16 offsets, clamp backward to grapheme
27+ boundaries, preserve batched editing, and honor programmatic value/cursor
28+ updates together on the next render.
29+- ✅ **True no-op terminal output** — identical buffers and cursor state emit
30+ no bytes, while cursor-only changes still emit. `cel.setTitle()` suppresses
31+ duplicate sanitized titles and resets its cache across runtime lifecycles.
1332
14-- ❌ Not yet implemented
15-- 💡 Future enhancement
33+### Long-lived and streaming views
1634
17----
35+- ✅ **Variable-height VirtualList** — the callable keyed component measures
36+ visible variable-height rows, uses prefix sums/binary search and bounded
37+ overscan, supports controlled or internal scrolling, sticky bottom,
38+ first-visible anchor compensation, width/version invalidation, imperative
39+ navigation, and eager bounded-cache release. A 5,000-row same-process
40+ regression measured 134.39 ms unvirtualized versus 2.170 ms virtualized
41+ (98.4% reduction, 61.9× speedup), with the returned row tree hard-bounded.
42+- ✅ **SyntaxHighlight identity and cache scaling** —
43+ `createSyntaxHighlight()` owns one isolated append stream and exposes
44+ `.dispose()`. Direct calls use a bounded exact-render LRU with no content-
45+ prefix identity guessing; custom theme/color caches are bounded. Crossing
46+ the former four-entry cliff at five snippets improved from 1.7105 ms to
47+ 0.0082 ms per frame (99.5%).
1848
19-## Open, but not blocking stability
49+### Components
2050
21-- ❌ **Markdown heading inline styling** — Headings (`#`, `##`, `###`) still strip inline formatting to plain text. Paragraphs, list items, and blockquotes already render inline formatting via wrapping HStack. This is real missing functionality, but not a stability blocker.
51+- ✅ **Markdown heading inline styling** — `#`, `##`, and `###` headings retain
52+ their heading style while composing bold, italic, inline-code, and link
53+ spans in wrapping rows; plain headings retain the compact Text path.
54+- ✅ **Native palette-slot syntax themes** — compatible TextMate registrations
55+ remain supported, while native `baseStyle` / `scopeStyles` preserve
56+ `color00`–`color15` references and explicit false style values. Runtime
57+ palette replacement changes emitted RGB without re-highlighting.
58+- ✅ **TextInput-backed Select / Combobox** — Select now uses exact TextInput
59+ text and cursor behavior (case, spaces, grapheme deletion, readline editing,
60+ batched input, bracketed paste), plus initial/controlled query, cursor, and
61+ highlight state, updateable items, cancel handling, custom filtering/rows,
62+ and the compatible callable static-list API.
63+- ✅ **Spinner and managed animation** — configurable `Spinner()` instances and
64+ `createTicker()` provide explicit maximum cadence, drift-safe skipped frames,
65+ start/stop/reset/dispose lifecycles, stable frame width, and no permanent
66+ framework FPS loop. The hello/chat examples no longer duplicate spinner
67+ arrays, intervals, render calls, or cleanup.
2268
23-## Future enhancements
69+### Former future enhancements
2470
25-- 💡 **Cursor style/shape customization** — TextInput currently renders the cursor as an inverted cell (block cursor). There's no way to choose bar (`│` between characters), underline, or custom cursor characters. A `cursorStyle` prop on TextInput (`"block" | "bar" | "underline"`) would cover the common cases. The native terminal cursor shape could also be set via DECSCUSR (`CSI q`) sequences to match.
71+- ✅ **Cursor shape customization** — TextInput `cursorStyle` supports
72+ `"block"`, `"bar"`, and `"underline"` in both the painted fallback and
73+ native DECSCUSR cursor; shape-only diffs and terminal cleanup are covered.
74+- ✅ **Scrollbar styling** — `scrollbarStyle` customizes single-cell thumb and
75+ track characters plus normal terminal style props, with width validation.
76+- ✅ **Explicit hidden overflow** — `overflow: "hidden"` is specified as the
77+ default clipping mode and has a deterministic explicit-prop regression test.
78+- ✅ **Advanced Kitty keyboard reporting** — the API uses Kitty's actual
79+ independent progressive-enhancement flags (not fictional numbered levels)
80+ for event phases, alternate/layout keys, all-key reporting, and associated
81+ text. `onKeyPress(key, event)` exposes typed metadata; release events never
82+ edit, activate, traverse, or blur; mixed tmux/legacy streams remain accepted.
2683
27-- 💡 **Scrollbar styling** — Scrollbar characters (`┃`/`│` vertical, `━`/`─` horizontal) and colors are hardcoded in `paintScrollbar`. A `scrollbarStyle` prop on containers (or a global theme option) would allow customizing thumb/track characters and colors.
84+## Verification snapshot
2885
29-- 💡 `overflow: "hidden"` as explicit prop (currently all containers clip by default, which matches the spec's default behavior, but the prop value is not checked)
30-- 💡 Higher Kitty protocol levels — key-release events (level 2), associated text (level 3), and full event types (level 4) for advanced input patterns (games, physical key layout awareness)
86+- `bun test`: 720 tests, 16,441 assertions
87+- `bun run typecheck`
88+- `bun run check`
89+- `bun run format`
90+- `bun run prepublish-check`
91+- `bun run docs`: clean HTML and Markdown generation, no warnings
92+- `bun run bench:regression`: all fixed-work cases complete with raw JSON
93+- `examples/hello.ts`: visually smoke-tested in an 80×24 tmux pane
94+
95+Detailed benchmark methodology and snapshots live in `benchmarks/RESULTS.md`.
benchmarks/RESULTS.md+99−12
@@ -1,5 +1,89 @@
11 # cel-tui Benchmark Results
22
3+> These are historical snapshots, not universal performance claims. For
4+> before/after work, run `bun run bench:regression` on the same machine, Bun
5+> version, and power profile; it emits environment metadata and raw fixed-work
6+> samples as JSON.
7+
8+## 2026-07-09 quality-pass comparison
9+
10+Same-machine, same-runtime (`Bun 1.3.13`) fixed-work medians recorded before
11+and after the rendering quality pass:
12+
13+| Case | Before | After | Change |
14+| ----------------------------------------- | ------- | ------- | ------ |
15+| Allocate `CellBuffer(120, 40)` | 92.8 µs | 3.4 µs | -96.3% |
16+| Allocate + paint 1,000 messages at top | 1.33 ms | 0.44 ms | -67.1% |
17+| Allocate + paint 1,000 messages at bottom | 8.61 ms | 0.45 ms | -94.8% |
18+
19+The bottom-scroll gain comes from translating and clipping during traversal
20+instead of cloning every layout node in a scrolled subtree. The allocation
21+gain comes from sharing an immutable empty-cell sentinel. The checked-in
22+`bench:regression` harness now makes equivalent future comparisons
23+repeatable and records its raw samples and environment as JSON.
24+
25+Two mid-pass checkpoints isolate the later ASCII painting fast path: the
26+Ink-shaped end-to-end case moved from 0.663 ms to 0.198 ms (-70.1%), and the
27+20-message app case from 4.29 ms to 0.466 ms (-89.1%). These are not the
28+original repository baseline, so they are intentionally separate from the
29+table above.
30+
31+The full test suite also moved from 561 tests in 4.77 s to 608 tests in
32+0.40 s after replacing fixed timer sleeps with a deterministic render-flush
33+seam. Line coverage increased from 93.20% to 93.52%.
34+
35+### SyntaxHighlight cache scaling
36+
37+The same quality pass replaced the global four-state content-prefix heuristic
38+with a bounded exact-render cache plus explicit `createSyntaxHighlight()`
39+instances. The fixed workload below renders 24-line TypeScript snippets for 30
40+frames after three warmup frames on the same Bun 1.3.13 process shape:
41+
42+| Static snippets per frame | Before | After |
43+| ------------------------- | --------- | --------- |
44+| 4 | 0.0058 ms | 0.0067 ms |
45+| 5 | 1.7105 ms | 0.0082 ms |
46+| 5 / 4 scaling ratio | 297.3x | 1.22x |
47+
48+Crossing the old four-entry boundary made every lookup miss. At five snippets,
49+the new cache removes 99.5% of that frame cost while scaling close to the ideal
50+1.25x increase in work. `bench:regression` now includes fixed-work 4-snippet,
51+5-snippet, and 32-isolated-instance cases; one recorded run measured medians of
52+3.40 µs, 4.17 µs, and 0.93 µs per frame respectively.
53+
54+### Variable-height VirtualList
55+
56+The first-class `VirtualList` regression case uses 5,000 keyed, variable-height
57+mini-coder message rows at 120×40. It includes callable component rendering,
58+visible-row measurement, prefix/window calculation, spacer construction, and
59+layout. A same-process steady-state run on Bun 1.3.13 measured:
60+
61+| Case | Median |
62+| ----------------------------------- | ------------- |
63+| Build + layout all 5,000 rows | 134.39 ms |
64+| VirtualList + layout visible window | 2.170 ms |
65+| Relative reduction / speedup | 98.4% / 61.9× |
66+
67+The virtual result retains cell-accurate measured heights for active rows and
68+uses bounded estimates for cold rows; only the viewport plus configured
69+overscan appears in the returned node tree. Both cases remain in
70+`bench:regression` so future changes can be compared with the same fixed-work
71+harness and raw samples.
72+
73+### Editing-key lookup
74+
75+The exploratory key benchmark exposed an immutable `Set` being rebuilt for
76+every named key event. Hoisting that lookup removed the hot-path allocation on
77+the same machine and similar measured clock (~1.7 GHz):
78+
79+| Case | Before | After | Change |
80+| ------------------------ | ------- | ------- | ------------- |
81+| `isEditingKey("enter")` | 1.39 µs | 3.94 ns | -99.7% / 353× |
82+| `isEditingKey("ctrl+s")` | 1.26 µs | 6.03 ns | -99.5% / 209× |
83+
84+`bench:regression` now includes the combined named-key/shortcut lookup; one
85+recorded fixed-work median was 11.09 ns for both calls together.
86+
387 **Machine:** 12th Gen Intel Core i9-12900, ~4.4 GHz
488 **Runtime:** Bun 1.3.9 (x64-linux)
589 **Date:** 2026-04-05 (updated from 2026-04-04 baseline)
@@ -100,18 +184,21 @@ Paint is O(cells), not O(nodes) — 100 vs 1,000 children produce similar times
100184
101185 ### CellBuffer & ANSI Emission
102186
103-| Operation | Time |
104-| ---------------------------- | -------- |
105-| Buffer creation 80×24 | 24.7 µs |
106-| Buffer creation 120×40 | 58.2 µs |
107-| Buffer creation 200×50 | 117.0 µs |
108-| emitBuffer 80×24 (full) | 21.4 µs |
109-| emitBuffer 120×40 (full) | 46.4 µs |
110-| emitDiff 80×24 (no changes) | 11.8 µs |
111-| emitDiff 80×24 (partial) | 11.1 µs |
112-| emitDiff 80×24 (full change) | 11.2 µs |
113-
114-Differential rendering has near-constant cost regardless of change amount — dominated by the comparison scan over all cells.
187+| Operation | Time |
188+| ---------------------------- | -------------------------- |
189+| Buffer creation 80×24 | 24.7 µs |
190+| Buffer creation 120×40 | 58.2 µs |
191+| Buffer creation 200×50 | 117.0 µs |
192+| emitBuffer 80×24 (full) | 21.4 µs |
193+| emitBuffer 120×40 (full) | 46.4 µs |
194+| emitDiff 80×24 (no changes) | 11.8 µs |
195+| emitDiff 80×24 (partial) | invalid historical fixture |
196+| emitDiff 80×24 (full change) | invalid historical fixture |
197+
198+The original partial/full-change fixtures accidentally produced identical
199+visible buffers, so their published timings did not measure the named cases.
200+The fixtures now assert that exactly one or every cell changes, respectively;
201+use `bun run benchmarks/cell-buffer.bench.ts` for corrected measurements.
115202
116203 ### Hit Test & Focus
117204
benchmarks/cell-buffer.bench.ts+22−13
@@ -5,12 +5,12 @@
55 * and differential rendering (the key to fast re-renders).
66 */
77
8-import { bench, group, run } from "mitata";
98 import { CellBuffer, emitBuffer } from "@cel-tui/core";
9+import { bench, group, run } from "mitata";
1010 import { emitDiff } from "../packages/core/src/emitter.js";
1111 import { layout } from "../packages/core/src/layout.js";
1212 import { paint } from "../packages/core/src/paint.js";
13-import { appTree, flatTree, inkComparableTree } from "./helpers.js";
13+import { appTree } from "./helpers.js";
1414
1515 // --- Buffer creation ---
1616
@@ -65,29 +65,38 @@ group("emitDiff: no changes", () => {
6565 });
6666
6767 group("emitDiff: partial changes", () => {
68- // Base buffer
6968 const tree1 = layout(appTree(20), 80, 24);
7069 const buf1 = new CellBuffer(80, 24);
7170 paint(tree1, buf1);
7271
73- // Changed buffer — different message count changes bottom portion
74- const tree2 = layout(appTree(21), 80, 24);
7572 const buf2 = new CellBuffer(80, 24);
76- paint(tree2, buf2);
77-
78- bench("80×24 one message added", () => {
73+ paint(tree1, buf2);
74+ const changed = buf2.get(10, 5);
75+ buf2.set(10, 5, { ...changed, char: changed.char === "X" ? "Y" : "X" });
76+ if (buf1.diff(buf2).length !== 1) {
77+ throw new Error("Partial-diff benchmark must change exactly one cell");
78+ }
79+
80+ bench("80×24 one cell changed", () => {
7981 emitDiff(buf1, buf2);
8082 });
8183 });
8284
8385 group("emitDiff: full change", () => {
84- const tree1 = layout(flatTree(24), 80, 24);
8586 const buf1 = new CellBuffer(80, 24);
86- paint(tree1, buf1);
87-
88- const tree2 = layout(flatTree(100), 80, 24);
8987 const buf2 = new CellBuffer(80, 24);
90- paint(tree2, buf2);
88+ const baseCell = {
89+ fgColor: null,
90+ bgColor: null,
91+ bold: false,
92+ italic: false,
93+ underline: false,
94+ } as const;
95+ buf1.fill(0, 0, 80, 24, { ...baseCell, char: "A" });
96+ buf2.fill(0, 0, 80, 24, { ...baseCell, char: "B" });
97+ if (buf1.diff(buf2).length !== 80 * 24) {
98+ throw new Error("Full-diff benchmark must change every cell");
99+ }
91100
92101 bench("80×24 completely different", () => {
93102 emitDiff(buf1, buf2);
benchmarks/e2e.bench.ts+2−2
@@ -9,12 +9,12 @@
99 * benchmark/simple) for direct comparison.
1010 */
1111
12-import { bench, group, run } from "mitata";
1312 import { CellBuffer, emitBuffer } from "@cel-tui/core";
13+import { bench, group, run } from "mitata";
1414 import { emitDiff } from "../packages/core/src/emitter.js";
1515 import { layout } from "../packages/core/src/layout.js";
1616 import { paint } from "../packages/core/src/paint.js";
17-import { flatTree, inkComparableTree, appTree } from "./helpers.js";
17+import { appTree, flatTree, inkComparableTree } from "./helpers.js";
1818
1919 // --- Full pipeline: tree → layout → paint → emit ---
2020
benchmarks/helpers.ts+3−2
@@ -2,8 +2,8 @@
22 * Shared helpers for benchmark tree construction.
33 */
44
5-import type { ContainerNode, Node, StyleProps } from "@cel-tui/types";
65 import { HStack, Text, TextInput, VStack } from "@cel-tui/core";
6+import type { ContainerNode, Node, StyleProps } from "@cel-tui/types";
77
88 /** Build a flat VStack with N Text children. */
99 export function flatTree(n: number): ContainerNode {
@@ -219,7 +219,8 @@ export function syntaxLikeBlock(
219219 return VStack({ gap: 0 }, children);
220220 }
221221
222-function miniCoderMessage(index: number): ContainerNode {
222+/** Build one representative variable-height mini-coder conversation row. */
223+export function miniCoderMessage(index: number): ContainerNode {
223224 const kind = MESSAGE_KINDS[index % MESSAGE_KINDS.length];
224225 const isUser = kind === "user";
225226 const isTool = kind === "tool";
benchmarks/hit-test.bench.ts+4−4
@@ -5,12 +5,12 @@
55 * routing and keyboard focus traversal.
66 */
77
8+import { HStack, Text, VStack } from "@cel-tui/core";
9+import type { Node } from "@cel-tui/types";
810 import { bench, group, run } from "mitata";
11+import { collectFocusable, hitTest } from "../packages/core/src/hit-test.js";
912 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";
13+import { appTree, flatTree, nestedTree } from "./helpers.js";
1414
1515 const W = 120;
1616 const H = 40;
benchmarks/keys.bench.ts+2−2
@@ -7,9 +7,9 @@
77
88 import { bench, group, run } from "mitata";
99 import {
10- parseKey,
11- normalizeKey,
1210 isEditingKey,
11+ normalizeKey,
12+ parseKey,
1313 } from "../packages/core/src/keys.js";
1414
1515 group("parseKey", () => {
benchmarks/layout.bench.ts+2−2
@@ -8,12 +8,12 @@
88 import { bench, group, run } from "mitata";
99 import { layout } from "../packages/core/src/layout.js";
1010 import {
11+ appTree,
1112 flatTree,
13+ inkComparableTree,
1214 nestedTree,
1315 styledTree,
1416 wrappedTextTree,
15- inkComparableTree,
16- appTree,
1717 } from "./helpers.js";
1818
1919 const W = 120;
benchmarks/paint.bench.ts+4−4
@@ -5,18 +5,18 @@
55 * including text rendering, style inheritance, clipping, and scrollbars.
66 */
77
8-import { bench, group, run } from "mitata";
98 import { CellBuffer } from "@cel-tui/core";
9+import { bench, group, run } from "mitata";
1010 import { layout } from "../packages/core/src/layout.js";
1111 import { paint } from "../packages/core/src/paint.js";
1212 import {
13+ appTree,
1314 flatTree,
15+ inkComparableTree,
1416 nestedTree,
15- styledTree,
1617 scrollableTree,
18+ styledTree,
1719 wrappedTextTree,
18- inkComparableTree,
19- appTree,
2020 } from "./helpers.js";
2121
2222 const W = 120;
benchmarks/real-world.bench.ts+1−1
@@ -6,8 +6,8 @@
66 * windows, syntax-highlight-like blocks, and wide wrapping token rows.
77 */
88
9-import { bench, group, run } from "mitata";
109 import { CellBuffer, emitBuffer, measureContentHeight } from "@cel-tui/core";
10+import { bench, group, run } from "mitata";
1111 import { emitDiff } from "../packages/core/src/emitter.js";
1212 import { layout } from "../packages/core/src/layout.js";
1313 import { paint } from "../packages/core/src/paint.js";
benchmarks/regression.ts+349−0
@@ -0,0 +1,349 @@
1+/**
2+ * Deterministic regression benchmark harness.
3+ *
4+ * Each case runs a fixed number of operations for two warmup samples and seven
5+ * measured samples. Results are emitted as JSON so commits and machines can be
6+ * compared without parsing human-oriented benchmark output.
7+ */
8+
9+import { cpus } from "node:os";
10+import { CellBuffer, emitBuffer, VStack } from "@cel-tui/core";
11+import {
12+ createSyntaxHighlight,
13+ SyntaxHighlight,
14+} from "../packages/components/src/syntax-highlight.js";
15+import { VirtualList } from "../packages/components/src/virtual-list.js";
16+import { emitDiff } from "../packages/core/src/emitter.js";
17+import { isEditingKey } from "../packages/core/src/keys.js";
18+import { layout } from "../packages/core/src/layout.js";
19+import { paint } from "../packages/core/src/paint.js";
20+import { layoutText } from "../packages/core/src/text-layout.js";
21+import {
22+ appTree,
23+ inkComparableTree,
24+ miniCoderMessage,
25+ miniCoderNextConversationTree,
26+} from "./helpers.js";
27+
28+const WIDTH = 120;
29+const HEIGHT = 40;
30+const WARMUP_SAMPLES = 2;
31+const MEASURED_SAMPLES = 7;
32+const LONG_WRAPPED_PARAGRAPH =
33+ "The quick brown fox jumps over the lazy dog while terminal cells wrap predictably. ".repeat(
34+ 110,
35+ );
36+const SYNTAX_SOURCES = Array.from({ length: 32 }, (_, snippet) =>
37+ Array.from(
38+ { length: 24 },
39+ (_, line) => `const value${snippet}_${line}: number = ${snippet + line};`,
40+ ).join("\n"),
41+);
42+const FOUR_SYNTAX_SOURCES = SYNTAX_SOURCES.slice(0, 4);
43+const FIVE_SYNTAX_SOURCES = SYNTAX_SOURCES.slice(0, 5);
44+const BENCHMARK_SYNTAX_THEME = {
45+ name: "regression-benchmark",
46+ fg: "#e5e5e5",
47+ tokenColors: [
48+ { scope: "keyword", settings: { foreground: "#2472c8" } },
49+ { scope: "string", settings: { foreground: "#0dbc79" } },
50+ ],
51+} as const;
52+const VIRTUAL_MESSAGE_ITEMS = Array.from(
53+ { length: 5_000 },
54+ (_, index) => index,
55+);
56+
57+interface BenchmarkDefinition {
58+ name: string;
59+ iterationsPerSample: number;
60+ operation: () => number;
61+}
62+
63+interface BenchmarkResult {
64+ name: string;
65+ iterationsPerSample: number;
66+ medianNsPerOperation: number;
67+ rawSamplesNs: number[];
68+}
69+
70+let benchmarkSink = 0;
71+
72+function fixedWorkSample(definition: BenchmarkDefinition): number {
73+ const start = Bun.nanoseconds();
74+ for (let i = 0; i < definition.iterationsPerSample; i++) {
75+ benchmarkSink = (benchmarkSink + definition.operation()) | 0;
76+ }
77+ return Bun.nanoseconds() - start;
78+}
79+
80+function median(values: readonly number[]): number {
81+ const sorted = [...values].sort((a, b) => a - b);
82+ const middle = Math.floor(sorted.length / 2);
83+ const value = sorted[middle];
84+ if (value === undefined) {
85+ throw new Error("Cannot calculate the median of an empty sample set");
86+ }
87+ return value;
88+}
89+
90+function measure(definition: BenchmarkDefinition): BenchmarkResult {
91+ for (let i = 0; i < WARMUP_SAMPLES; i++) {
92+ fixedWorkSample(definition);
93+ }
94+
95+ const rawSamplesNs: number[] = [];
96+ for (let i = 0; i < MEASURED_SAMPLES; i++) {
97+ rawSamplesNs.push(fixedWorkSample(definition));
98+ }
99+
100+ return {
101+ name: definition.name,
102+ iterationsPerSample: definition.iterationsPerSample,
103+ medianNsPerOperation: median(rawSamplesNs) / definition.iterationsPerSample,
104+ rawSamplesNs,
105+ };
106+}
107+
108+function fullRender(
109+ treeFactory: typeof inkComparableTree | (() => ReturnType<typeof appTree>),
110+ width: number,
111+ height: number,
112+): number {
113+ const tree = treeFactory();
114+ const layoutTree = layout(tree, width, height);
115+ const buffer = new CellBuffer(width, height);
116+ paint(layoutTree, buffer);
117+ return emitBuffer(buffer).length;
118+}
119+
120+function renderSyntaxFrame(sources: readonly string[]): number {
121+ let lineCount = 0;
122+ for (const source of sources) {
123+ lineCount += SyntaxHighlight(source, "typescript").children.length;
124+ }
125+ return lineCount;
126+}
127+
128+function renderCustomThemeSyntaxFrame(sources: readonly string[]): number {
129+ let lineCount = 0;
130+ for (const source of sources) {
131+ lineCount += SyntaxHighlight(source, "typescript", {
132+ theme: BENCHMARK_SYNTAX_THEME,
133+ }).children.length;
134+ }
135+ return lineCount;
136+}
137+
138+function setConversationScroll(
139+ tree: ReturnType<typeof miniCoderNextConversationTree>,
140+ scrollOffset: number,
141+): void {
142+ const conversation = tree.children[0];
143+ if (conversation?.type !== "vstack" && conversation?.type !== "hstack") {
144+ throw new Error("Expected the benchmark conversation to be a container");
145+ }
146+ conversation.props.scrollOffset = scrollOffset;
147+}
148+
149+function commitSha(): string {
150+ const result = Bun.spawnSync(["git", "rev-parse", "HEAD"], {
151+ cwd: process.cwd(),
152+ stderr: "pipe",
153+ stdout: "pipe",
154+ });
155+ if (result.exitCode !== 0) return "unknown";
156+ return result.stdout.toString().trim() || "unknown";
157+}
158+
159+function workingTreeDirty(): boolean {
160+ const result = Bun.spawnSync(["git", "status", "--porcelain"], {
161+ cwd: process.cwd(),
162+ stderr: "pipe",
163+ stdout: "pipe",
164+ });
165+ return result.exitCode === 0 && result.stdout.length > 0;
166+}
167+
168+const topTree = miniCoderNextConversationTree(1_000);
169+setConversationScroll(topTree, 0);
170+const topLayout = layout(topTree, WIDTH, HEIGHT);
171+
172+const bottomTree = miniCoderNextConversationTree(1_000);
173+setConversationScroll(bottomTree, Infinity);
174+const bottomLayout = layout(bottomTree, WIDTH, HEIGHT);
175+
176+const identicalLayout = layout(inkComparableTree(), 80, 24);
177+const identicalPrevious = new CellBuffer(80, 24);
178+const identicalNext = new CellBuffer(80, 24);
179+paint(identicalLayout, identicalPrevious);
180+paint(identicalLayout, identicalNext);
181+
182+const syntaxInstances = SYNTAX_SOURCES.map(() => createSyntaxHighlight());
183+for (let index = 0; index < syntaxInstances.length; index++) {
184+ syntaxInstances[index]?.(SYNTAX_SOURCES[index] ?? "", "typescript");
185+}
186+
187+// Prime direct-call entries so these cases measure steady-state frames. The
188+// historical four-entry prefix cache was fast at four snippets and thrashed at
189+// five; keeping both cases makes that cliff visible in regression output.
190+renderSyntaxFrame(FIVE_SYNTAX_SOURCES);
191+renderCustomThemeSyntaxFrame(FIVE_SYNTAX_SOURCES);
192+
193+const virtualConversation = VirtualList<number>({
194+ itemKey: (index) => index,
195+ renderItem: miniCoderMessage,
196+ estimatedItemHeight: 8,
197+ gap: 1,
198+ overscan: HEIGHT,
199+ defaultStickToBottom: true,
200+});
201+
202+function renderVirtualConversation(): number {
203+ const tree = virtualConversation({
204+ items: VIRTUAL_MESSAGE_ITEMS,
205+ width: WIDTH,
206+ height: HEIGHT,
207+ });
208+ const layoutTree = layout(tree, WIDTH, HEIGHT);
209+ return (
210+ virtualConversation.getState().renderedItems + layoutTree.children.length
211+ );
212+}
213+
214+// Prime measured row heights so the regression case represents a steady-state
215+// interactive frame rather than first-mount cache population.
216+renderVirtualConversation();
217+
218+const definitions: BenchmarkDefinition[] = [
219+ {
220+ name: "cell_buffer_create_120x40",
221+ iterationsPerSample: 400,
222+ operation: () => {
223+ const buffer = new CellBuffer(WIDTH, HEIGHT);
224+ return buffer.width + buffer.height + buffer.get(0, 0).char.length;
225+ },
226+ },
227+ {
228+ name: "e2e_ink_comparable_80x24",
229+ iterationsPerSample: 200,
230+ operation: () => fullRender(inkComparableTree, 80, 24),
231+ },
232+ {
233+ name: "e2e_app_tree_20_120x40",
234+ iterationsPerSample: 100,
235+ operation: () => fullRender(() => appTree(20), WIDTH, HEIGHT),
236+ },
237+ {
238+ name: "allocate_and_paint_1000_messages_top_120x40",
239+ iterationsPerSample: 8,
240+ operation: () => {
241+ const buffer = new CellBuffer(WIDTH, HEIGHT);
242+ paint(topLayout, buffer);
243+ return buffer.get(0, 0).char.length + buffer.get(10, 10).char.length;
244+ },
245+ },
246+ {
247+ name: "build_and_layout_5000_messages_unvirtualized_120x40",
248+ iterationsPerSample: 1,
249+ operation: () => {
250+ const tree = VStack(
251+ {
252+ width: WIDTH,
253+ height: HEIGHT,
254+ gap: 1,
255+ overflow: "scroll",
256+ scrollOffset: Infinity,
257+ },
258+ VIRTUAL_MESSAGE_ITEMS.map(miniCoderMessage),
259+ );
260+ return layout(tree, WIDTH, HEIGHT).children.length;
261+ },
262+ },
263+ {
264+ name: "virtual_list_5000_variable_messages_120x40",
265+ iterationsPerSample: 20,
266+ operation: renderVirtualConversation,
267+ },
268+ {
269+ name: "layout_text_ascii_9130_chars_width_80",
270+ iterationsPerSample: 10,
271+ operation: () => {
272+ const result = layoutText(LONG_WRAPPED_PARAGRAPH, 80, "word");
273+ return result.lineCount + (result.lines.at(-1)?.endOffset ?? 0);
274+ },
275+ },
276+ {
277+ name: "allocate_and_paint_1000_messages_bottom_120x40",
278+ iterationsPerSample: 8,
279+ operation: () => {
280+ const buffer = new CellBuffer(WIDTH, HEIGHT);
281+ paint(bottomLayout, buffer);
282+ return buffer.get(0, 0).char.length + buffer.get(10, 10).char.length;
283+ },
284+ },
285+ {
286+ name: "emit_diff_identical_80x24",
287+ iterationsPerSample: 400,
288+ operation: () =>
289+ emitDiff(identicalPrevious, identicalNext).length + identicalNext.width,
290+ },
291+ {
292+ name: "editing_key_lookup_named_and_shortcut",
293+ iterationsPerSample: 20_000,
294+ operation: () =>
295+ Number(isEditingKey("enter")) + Number(isEditingKey("ctrl+s")),
296+ },
297+ {
298+ name: "syntax_highlight_direct_4_static_snippets_frame",
299+ iterationsPerSample: 200,
300+ operation: () => renderSyntaxFrame(FOUR_SYNTAX_SOURCES),
301+ },
302+ {
303+ name: "syntax_highlight_direct_5_static_snippets_frame",
304+ iterationsPerSample: 200,
305+ operation: () => renderSyntaxFrame(FIVE_SYNTAX_SOURCES),
306+ },
307+ {
308+ name: "syntax_highlight_32_isolated_instances_frame",
309+ iterationsPerSample: 100,
310+ operation: () => {
311+ let lineCount = 0;
312+ for (let index = 0; index < syntaxInstances.length; index++) {
313+ lineCount +=
314+ syntaxInstances[index]?.(SYNTAX_SOURCES[index] ?? "", "typescript")
315+ .children.length ?? 0;
316+ }
317+ return lineCount;
318+ },
319+ },
320+ {
321+ name: "syntax_highlight_cached_custom_theme_5_snippets_frame",
322+ iterationsPerSample: 200,
323+ operation: () => renderCustomThemeSyntaxFrame(FIVE_SYNTAX_SOURCES),
324+ },
325+];
326+
327+const output = {
328+ schemaVersion: 1,
329+ environment: {
330+ bunVersion: Bun.version,
331+ platform: process.platform,
332+ arch: process.arch,
333+ cpuModel: cpus()[0]?.model ?? "unknown",
334+ commitSha: commitSha(),
335+ workingTreeDirty: workingTreeDirty(),
336+ },
337+ methodology: {
338+ clock: "Bun.nanoseconds",
339+ unit: "nanoseconds",
340+ statistic: "median",
341+ warmupSamples: WARMUP_SAMPLES,
342+ measuredSamples: MEASURED_SAMPLES,
343+ fixedIterationsPerSample: true,
344+ },
345+ cases: definitions.map(measure),
346+ checksum: benchmarkSink,
347+};
348+
349+process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
benchmarks/run-all.ts+2−0
@@ -43,3 +43,5 @@ for (const name of benchmarks) {
4343 },
4444 );
4545 }
46+
47+console.log("\nAll benchmark groups completed successfully.");
benchmarks/width.bench.ts+1−1
@@ -5,8 +5,8 @@
55 * word-wrap calculation, every cursor position calls visibleWidth().
66 */
77
8-import { bench, group, run } from "mitata";
98 import { visibleWidth } from "@cel-tui/core";
9+import { bench, group, run } from "mitata";
1010 import { ASCII_STRING, CJK_EMOJI_STRING, MIXED_STRING } from "./helpers.js";
1111
1212 // --- Benchmarks ---
biome.json+30−3
@@ -1,5 +1,5 @@
11 {
2- "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
2+ "$schema": "https://biomejs.dev/schemas/2.5.3/schema.json",
33 "assist": {
44 "actions": {
55 "source": {
@@ -13,10 +13,37 @@
1313 "linter": {
1414 "enabled": true,
1515 "rules": {
16- "recommended": true
16+ "preset": "recommended"
1717 }
1818 },
19+ "overrides": [
20+ {
21+ "includes": ["examples/**/*.ts"],
22+ "linter": {
23+ "rules": {
24+ "style": {
25+ "noNonNullAssertion": "off"
26+ }
27+ }
28+ }
29+ },
30+ {
31+ "includes": ["examples/syntax-highlight.ts"],
32+ "linter": {
33+ "rules": {
34+ "suspicious": {
35+ "noTemplateCurlyInString": "off"
36+ }
37+ }
38+ }
39+ }
40+ ],
1941 "files": {
20- "includes": ["packages/*/src/**/*.ts"]
42+ "includes": [
43+ "packages/*/src/**/*.ts",
44+ "examples/**/*.ts",
45+ "benchmarks/**/*.ts",
46+ "scripts/**/*.ts"
47+ ]
2148 }
2249 }
bun.lock+38−38
@@ -17,14 +17,14 @@
1717 },
1818 "packages/clew": {
1919 "name": "@cel-tui/clew",
20- "version": "0.8.3",
20+ "version": "0.9.0",
2121 "peerDependencies": {
2222 "typescript": ">=5.0.0",
2323 },
2424 },
2525 "packages/components": {
2626 "name": "@cel-tui/components",
27- "version": "0.8.3",
27+ "version": "0.9.0",
2828 "dependencies": {
2929 "@cel-tui/clew": "workspace:*",
3030 "@cel-tui/core": "workspace:*",
@@ -37,7 +37,7 @@
3737 },
3838 "packages/core": {
3939 "name": "@cel-tui/core",
40- "version": "0.8.3",
40+ "version": "0.9.0",
4141 "dependencies": {
4242 "@cel-tui/types": "workspace:*",
4343 "get-east-asian-width": "^1.5.0",
@@ -48,30 +48,30 @@
4848 },
4949 "packages/types": {
5050 "name": "@cel-tui/types",
51- "version": "0.8.3",
51+ "version": "0.9.0",
5252 "peerDependencies": {
5353 "typescript": ">=5.0.0",
5454 },
5555 },
5656 },
5757 "packages": {
58- "@biomejs/biome": ["@biomejs/biome@2.4.13", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.13", "@biomejs/cli-darwin-x64": "2.4.13", "@biomejs/cli-linux-arm64": "2.4.13", "@biomejs/cli-linux-arm64-musl": "2.4.13", "@biomejs/cli-linux-x64": "2.4.13", "@biomejs/cli-linux-x64-musl": "2.4.13", "@biomejs/cli-win32-arm64": "2.4.13", "@biomejs/cli-win32-x64": "2.4.13" }, "bin": { "biome": "bin/biome" } }, "sha512-gLXOwkOBBg0tr7bDsqlkIh4uFeKuMjxvqsrb1Tukww1iDmHcfr4Uu8MoQxp0Rcte+69 …
58+ "@biomejs/biome": ["@biomejs/biome@2.5.3", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.3", "@biomejs/cli-darwin-x64": "2.5.3", "@biomejs/cli-linux-arm64": "2.5.3", "@biomejs/cli-linux-arm64-musl": "2.5.3", "@biomejs/cli-linux-x64": "2.5.3", "@biomejs/cli-linux-x64-musl": "2.5.3", "@biomejs/cli-win32-arm64": "2.5.3", "@biomejs/cli-win32-x64": "2.5.3" }, "bin": { "biome": "bin/biome" } }, "sha512-MrJswFdei9EfDwwUy2tQrPDpK0AO+RmMFvBoaaJ6ayBc3sUbHdCE+XG5N8vp+5So41ZupZJQm0ro …
5959
60- "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2KImO1jhNFBa2oWConyr0x6flxbQpGKv6902uGXpYM62Xyem8U80j441SyUJ8KyngsmKbQjeIv1q2CQfDkNnYg=="],
60+ "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.5.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QhYP9muVQ0nUO5zztFuPbEwi4+94sJWVjaZds9aMi1l/KNZBiUjdiSUrGHsTaMGDXrYl+r4AS2sUKfgH3w+V3g=="],
6161
62- "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-BKrJklbaFN4p1Ts4kPBczo+PkbsHQg57kmJ+vON9u2t6uN5okYHaSr7h/MutPCWQgg2lglaWoSmm+zhYW+oOkg=="],
62+ "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.5.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-NC1Ss13UaW7QZX+y8j44bF7AP0jSJdBl6iRhe0MAkvaSqZy+mWg3GaXsrb+eSoHoGDBtaXWEbMVV0iVN2cZ7cQ=="],
6363
64- "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-NzkUDSqfvMBrPplKgVr3aXLHZ2NEELvvF4vZxXulEylKWIGqlvNEcwUcj9OLrn75TD3lJ/GIqCVlBwd1MZCuYQ=="],
64+ "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.5.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-ksx1KWeyYW18ILL04msF/J4ZBtBDN33znYK8Z/aNv/vlBVxL9/g3mGP+omgHJKy4+KWbK87vcmmpmurfNjSgiA=="],
6565
Cut short: this commit's diff is over 1000 lines.
docs/skill/cel-tui/SKILL.md+120−10
Cut short: this commit's diff is over 1000 lines.
docs/skill/cel-tui/references/api.md+256−13
Cut short: this commit's diff is over 1000 lines.
docs/skill/cel-tui/references/composing-components.md+12−3
Cut short: this commit's diff is over 1000 lines.
examples/chat.ts+16−17
Cut short: this commit's diff is over 1000 lines.
examples/diff-highlight.ts+17−42
Cut short: this commit's diff is over 1000 lines.
examples/hello.ts+6−12
Cut short: this commit's diff is over 1000 lines.
examples/markdown-editor.ts+8−9
Cut short: this commit's diff is over 1000 lines.
examples/pet.ts+6−5
Cut short: this commit's diff is over 1000 lines.
examples/select.ts+48−15
Cut short: this commit's diff is over 1000 lines.
examples/simple-scroll.ts+1−1
Cut short: this commit's diff is over 1000 lines.
examples/syntax-highlight.ts+11−13
Cut short: this commit's diff is over 1000 lines.
examples/tags.ts+1−2
Cut short: this commit's diff is over 1000 lines.
package.json+3−1
Cut short: this commit's diff is over 1000 lines.
packages/clew/LICENSE+21−0
Cut short: this commit's diff is over 1000 lines.
packages/clew/README.md+3−2
Cut short: this commit's diff is over 1000 lines.
packages/clew/package.json+1−1
Cut short: this commit's diff is over 1000 lines.
packages/clew/src/index.test.ts+154−1
Cut short: this commit's diff is over 1000 lines.
packages/clew/src/languages/bash.ts+0−1
Cut short: this commit's diff is over 1000 lines.
packages/clew/src/model.ts+2−1
Cut short: this commit's diff is over 1000 lines.
packages/clew/src/shared.ts+5−0
Cut short: this commit's diff is over 1000 lines.
packages/clew/src/stream.ts+10−7
Cut short: this commit's diff is over 1000 lines.
packages/components/LICENSE+21−0
Cut short: this commit's diff is over 1000 lines.
packages/components/README.md+32−0
Cut short: this commit's diff is over 1000 lines.
packages/components/package.json+2−2
Cut short: this commit's diff is over 1000 lines.
packages/components/src/index.ts+34−1
Cut short: this commit's diff is over 1000 lines.
packages/components/src/markdown.test.ts+82−4
Cut short: this commit's diff is over 1000 lines.
packages/components/src/markdown.ts+20−12
Cut short: this commit's diff is over 1000 lines.
packages/components/src/select.test.ts+398−3
Cut short: this commit's diff is over 1000 lines.
packages/components/src/select.ts+468−281
Cut short: this commit's diff is over 1000 lines.
packages/components/src/spinner.test.ts+139−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/spinner.ts+162−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/syntax-highlight.test.ts+218−10
Cut short: this commit's diff is over 1000 lines.
packages/components/src/syntax-highlight.ts+219−106
Cut short: this commit's diff is over 1000 lines.
packages/components/src/ticker.test.ts+138−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/ticker.ts+166−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/virtual-list.test.ts+462−0
Cut short: this commit's diff is over 1000 lines.
packages/components/src/virtual-list.ts+897−0
Cut short: this commit's diff is over 1000 lines.
packages/core/LICENSE+21−0
Cut short: this commit's diff is over 1000 lines.
packages/core/README.md+30−0
Cut short: this commit's diff is over 1000 lines.
packages/core/package.json+1−1
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.test.ts+557−4
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cel.ts+540−175
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cell-buffer.test.ts+125−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/cell-buffer.ts+81−16
Cut short: this commit's diff is over 1000 lines.
packages/core/src/composite.test.ts+164−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.test.ts+93−3
Cut short: this commit's diff is over 1000 lines.
packages/core/src/emitter.ts+76−13
Cut short: this commit's diff is over 1000 lines.
packages/core/src/hit-test.test.ts+24−4
Cut short: this commit's diff is over 1000 lines.
packages/core/src/hit-test.ts+2−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/index.test.ts+73−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/index.ts+24−3
Cut short: this commit's diff is over 1000 lines.
packages/core/src/keys.test.ts+147−4
Cut short: this commit's diff is over 1000 lines.
packages/core/src/keys.ts+370−103
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.test.ts+68−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/layout.ts+158−133
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+254−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.ts+226−102
Cut short: this commit's diff is over 1000 lines.
packages/core/src/primitives/text-input.ts+10−4
Cut short: this commit's diff is over 1000 lines.
packages/core/src/state-identity.test.ts+51−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/state-identity.ts+96−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.test.ts+140−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+66−14
Cut short: this commit's diff is over 1000 lines.
packages/core/src/test-helpers.ts+11−2
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-edit.test.ts+12−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-edit.ts+18−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-input.test.ts+312−29
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-layout.test.ts+40−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/text-layout.ts+85−93
Cut short: this commit's diff is over 1000 lines.
packages/core/src/width.test.ts+5−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/width.ts+3−1
Cut short: this commit's diff is over 1000 lines.
packages/types/LICENSE+21−0
Cut short: this commit's diff is over 1000 lines.
packages/types/README.md+19−0
Cut short: this commit's diff is over 1000 lines.
packages/types/package.json+1−1
Cut short: this commit's diff is over 1000 lines.
packages/types/src/index.ts+174−17
Cut short: this commit's diff is over 1000 lines.
scripts/prepublish-check.ts+2−2
Cut short: this commit's diff is over 1000 lines.
spec.md+257−55
Cut short: this commit's diff is over 1000 lines.
tsconfig.json+6−1
Cut short: this commit's diff is over 1000 lines.