xonecas.io
70160
Ce

cel-tui / commit fbafce6

fix(core): uncontrolled container scroll now works without onScroll

The scroll handler checked 'onScroll in props' which failed when users
omitted the callback. Changed to check overflow === 'scroll' instead.

Uncontrolled scroll state is now persisted across re-renders using a
path-based key (structural tree position), stamped onto props before
paint and unstamped after — matching the focus stamp/unstamp pattern.

Added two tests: basic uncontrolled scroll and clamp at max offset.

xonecas2026-04-04 fbafce6236fe03fd63a361dc1ab1f2982817f0ca parent 4facee8

3 files changed

TODO.md+29−0
@@ -10,6 +10,28 @@ Remaining work, known bugs, and planned improvements.
1010
1111 ---
1212
13+## Bugs / Spec Violations
14+
15+- 🔧 **Uncontrolled container scroll is broken** — `VStack({ overflow: "scroll" }, [...])` without `onScroll` silently drops scroll events. In `cel.ts`, the check `"onScroll" in props` fails when the user omits the callback. The spec says uncontrolled scroll should "just work". Fix: check `props.overflow === "scroll"` instead. No existing tests cover this case.
16+
17+- 🔧 **Wide character (CJK/emoji) rendering broken in emitter** — `paintLineGraphemes` writes wide chars to the cell buffer but never writes a continuation marker to the second cell. The emitter iterates every cell sequentially, so the empty cell at position x+1 overwrites the right half of the wide char. The `CellBuffer` doc says wide chars use continuation markers, but paint never writes them and the emitter never skips them. Paint tests pass because they only check buffer contents, not em …
18+
19+- 🔧 **Hit testing ignores scroll offsets** — `hitTest()` uses original layout rects, not scroll-adjusted positions. Clicking on items in a scrolled container hits the wrong node (pre-scroll position). `shiftLayoutNode` only adjusts rects during painting, not in `currentLayouts` used by hit detection.
20+
21+- 🔧 **TextInput padding accepted but never applied** — `TextInputProps extends ContainerProps` accepts `padding`, but `layout.ts` treats TextInput as a leaf node (no padding subtraction). `paintTextInput` also ignores padding. The spec says TextInput accepts "Container sizing props (width, height, flex, min\*, max\*, padding)".
22+
23+- 🔧 **TextInput placeholder doesn't inherit styles** — `paintTextInput` passes `props.placeholder.props` directly to `paintText`, bypassing the TextInput's resolved inherited styles. A placeholder without explicit `fgColor` won't inherit from parent containers, unlike all other nodes.
24+
25+- 🔧 **Key bubbling spuriously consumes keys** — When all `onKeyPress` handlers in the bubbling chain return `false`, the key is still treated as consumed (triggers render, returns early) due to `if (consumed || handlers.length > 0)`. Per spec, `false` means not consumed. Causes unnecessary re-renders.
26+
27+- 🔧 **`getMaxScrollOffset` doesn't account for padding** — The max scroll offset calculation uses raw child rects relative to the container rect but doesn't subtract padding. Scrollable containers with padding allow scrolling past content.
28+
29+- 🔧 **TextInput cursor movement doesn't handle multi-codepoint graphemes** — `deleteBackward`/`deleteForward` in `text-edit.ts` operate on single string indices. For multi-codepoint characters (emoji ZWJ sequences, combining marks), this leaves the cursor mid-grapheme. `moveCursor` has the same issue.
30+
31+- 🔧 **Spec reference example inconsistency** — The chat example uses `msg.blocks.map(...)` but message construction only sets `content`, not `blocks`.
32+
33+---
34+
1335 ## API Improvements
1436
1537 - ❌ **Upgrade `Button` component** — `Button` from `@cel-tui/components` doesn't forward `focusStyle`, `fgColor`, `bgColor`, or other container/style props to the underlying HStack. With uncontrolled focus and focusStyle now available, Button should accept these to be useful for keyboard navigation without inline HStack wrappers.
@@ -27,3 +49,10 @@ Remaining work, known bugs, and planned improvements.
2749 - 💡 Additional example apps (chat UI, text editor from spec reference examples)
2850 - 💡 `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)
2951 - 💡 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)
52+
53+---
54+
55+## Documentation Gaps
56+
57+- 🔧 **Duplicate JSDoc** — `paintLineGraphemes` in `paint.ts` has its doc comment written twice.
58+- ❌ **No docs for uncontrolled scroll** — All examples/docs use controlled scroll (`scrollOffset` + `onScroll`). The spec's uncontrolled pattern isn't shown anywhere.
packages/core/src/cel.test.ts+62−0
@@ -276,6 +276,68 @@ describe("cel end-to-end", () => {
276276
277277 expect(scrollOffset).toBe(3);
278278 });
279+
280+ test("uncontrolled scroll works without onScroll", async () => {
281+ const term = setup(20, 5);
282+ cel.viewport(() =>
283+ VStack(
284+ {
285+ width: 20,
286+ height: 5,
287+ overflow: "scroll",
288+ },
289+ Array.from({ length: 10 }, (_, i) => Text(`line ${i + 1}`)),
290+ ),
291+ );
292+ await waitForRender();
293+
294+ // Before scroll, line 1 should be visible at row 0
295+ const buf1 = cel._getBuffer()!;
296+ expect(buf1.get(0, 0).char).toBe("l"); // "line 1"
297+
298+ // SGR scroll down at (3, 2): ESC [ < 65 ; 4 ; 3 M
299+ term.sendInput("\x1b[<65;4;3M");
300+ await waitForRender();
301+
302+ // After scroll by 1, line 2 should now be at row 0
303+ const buf2 = cel._getBuffer()!;
304+ // Read first 6 chars of row 0
305+ let row0 = "";
306+ for (let x = 0; x < 6; x++) row0 += buf2.get(x, 0).char;
307+ expect(row0).toBe("line 2");
308+ });
309+
310+ test("uncontrolled scroll clamps at max offset", async () => {
311+ const term = setup(20, 3);
312+ cel.viewport(() =>
313+ VStack(
314+ {
315+ width: 20,
316+ height: 3,
317+ overflow: "scroll",
318+ },
319+ // 5 items in 3-row viewport → max offset = 2
320+ Array.from({ length: 5 }, (_, i) => Text(`item ${i + 1}`)),
321+ ),
322+ );
323+ await waitForRender();
324+
325+ // Scroll down 10 times — should clamp at 2
326+ for (let i = 0; i < 10; i++) {
327+ term.sendInput("\x1b[<65;4;2M");
328+ await waitForRender();
329+ }
330+
331+ // Row 0 should show item 3 (offset=2), row 2 should show item 5
332+ const buf = cel._getBuffer()!;
333+ let row0 = "";
334+ for (let x = 0; x < 6; x++) row0 += buf.get(x, 0).char;
335+ expect(row0).toBe("item 3");
336+
337+ let row2 = "";
338+ for (let x = 0; x < 6; x++) row2 += buf.get(x, 2).char;
339+ expect(row2).toBe("item 5");
340+ });
279341 });
280342
281343 describe("focus system", () => {
packages/core/src/cel.ts+96−8
@@ -16,8 +16,6 @@ import {
1616 setTextInputCursor,
1717 getTextInputScroll,
1818 setTextInputScroll,
19- getContainerScroll,
20- setContainerScroll,
2119 } from "./paint.js";
2220 import {
2321 insertChar,
@@ -49,6 +47,17 @@ let frameworkFocusIndex = -1;
4947 /** The node whose props were stamped with `focused: true` during the last paint. */
5048 let stampedNode: LayoutNode | null = null;
5149
50+/**
51+ * Uncontrolled scroll offsets, keyed by structural tree path.
52+ * The path is a string like "0/2/1" representing the DFS child indices
53+ * from the layer root to the scrollable container. This survives re-renders
54+ * because the structural position is the same even with new props objects.
55+ */
56+const uncontrolledScrollOffsets = new Map<string, number>();
57+
58+/** Nodes whose props were stamped with scrollOffset during the last paint. */
59+let stampedScrollNodes: { node: Node; key: string }[] = [];
60+
5261 function doRender(): void {
5362 renderScheduled = false;
5463 if (!renderFn || !terminal) return;
@@ -81,8 +90,9 @@ function doRender(): void {
8190 currentLayouts.push(layoutTree);
8291 }
8392
84- // Stamp uncontrolled focus before painting so focusStyle and cursor work
93+ // Stamp uncontrolled focus and scroll before painting
8594 stampUncontrolledFocus();
95+ stampUncontrolledScroll();
8696
8797 // Paint each layer into the buffer
8898 for (const layoutTree of currentLayouts) {
@@ -91,6 +101,7 @@ function doRender(): void {
91101
92102 // Unstamp after paint so input handlers see clean props
93103 unstampUncontrolledFocus();
104+ unstampUncontrolledScroll();
94105
95106 // Emit to terminal — differential when possible
96107 if (prevBuffer) {
@@ -252,6 +263,75 @@ function unstampUncontrolledFocus(): void {
252263 stampedNode = null;
253264 }
254265
266+/**
267+ * Compute the structural tree path from a layer root to a target LayoutNode.
268+ * Returns a string like "0/2/1" or null if target is not in the tree.
269+ */
270+function computeTreePath(root: LayoutNode, target: LayoutNode): string | null {
271+ if (root === target) return "";
272+ for (let i = 0; i < root.children.length; i++) {
273+ const sub = computeTreePath(root.children[i]!, target);
274+ if (sub !== null) return sub === "" ? String(i) : `${i}/${sub}`;
275+ }
276+ return null;
277+}
278+
279+/**
280+ * Get the full path key for a scrollable node, prefixed by layer index.
281+ */
282+function getScrollPathKey(target: LayoutNode): string | null {
283+ for (let i = 0; i < currentLayouts.length; i++) {
284+ const path = computeTreePath(currentLayouts[i]!, target);
285+ if (path !== null) return `L${i}:${path}`;
286+ }
287+ return null;
288+}
289+
290+/**
291+ * Stamp `scrollOffset` on uncontrolled scrollable containers' props
292+ * before painting, so paint reads the correct offset.
293+ */
294+function stampUncontrolledScroll(): void {
295+ stampedScrollNodes = [];
296+ if (uncontrolledScrollOffsets.size === 0) return;
297+ for (let i = 0; i < currentLayouts.length; i++) {
298+ walkAndStampScroll(currentLayouts[i]!, `L${i}:`);
299+ }
300+}
301+
302+function walkAndStampScroll(ln: LayoutNode, pathKey: string): void {
303+ const node = ln.node;
304+ if (node.type === "vstack" || node.type === "hstack") {
305+ if (
306+ node.props.overflow === "scroll" &&
307+ node.props.scrollOffset === undefined &&
308+ !node.props.onScroll
309+ ) {
310+ const offset = uncontrolledScrollOffsets.get(pathKey);
311+ if (offset !== undefined && offset !== 0) {
312+ (node.props as any).scrollOffset = offset;
313+ stampedScrollNodes.push({ node, key: pathKey });
314+ }
315+ }
316+ }
317+ for (let i = 0; i < ln.children.length; i++) {
318+ // Keys match getScrollPathKey format: "L0:" for root, "L0:2" for child 2, "L0:2/1" for grandchild
319+ const childKey = pathKey.endsWith(":")
320+ ? `${pathKey}${i}`
321+ : `${pathKey}/${i}`;
322+ walkAndStampScroll(ln.children[i]!, childKey);
323+ }
324+}
325+
326+function unstampUncontrolledScroll(): void {
327+ for (const { node } of stampedScrollNodes) {
328+ if (node.type === "vstack" || node.type === "hstack") {
329+ delete (node.props as any).scrollOffset;
330+ }
331+ }
332+ stampedScrollNodes = [];
333+}
334+
255335 /**
256336 * Blur the currently focused element and focus a new one.
257337 * Manages both controlled (via onFocus/onBlur callbacks) and
@@ -383,7 +463,7 @@ function handleMouseEvent(event: MouseEvent): void {
383463 cel.render();
384464 } else {
385465 const props = target.node.type !== "text" ? target.node.props : null;
386- if (props && "onScroll" in props) {
466+ if (props && (props as any).overflow === "scroll") {
387467 if (props.onScroll) {
388468 // Controlled scroll: notify app.
389469 // Use batch accumulator if available (multiple events in one chunk),
@@ -399,10 +479,16 @@ function handleMouseEvent(event: MouseEvent): void {
399479 batchScrollOffsets?.set(props, newOffset);
400480 props.onScroll(newOffset);
401481 } else {
402- // Uncontrolled scroll: framework manages state
403- const current = getContainerScroll(props);
404- const clamped = Math.max(0, Math.min(maxOffset, current + delta));
405- setContainerScroll(props, clamped);
482+ // Uncontrolled scroll: framework manages state via path key
483+ const pathKey = getScrollPathKey(target);
484+ if (pathKey !== null) {
485+ const current = uncontrolledScrollOffsets.get(pathKey) ?? 0;
486+ const clamped = Math.max(
487+ 0,
488+ Math.min(maxOffset, current + delta),
489+ );
490+ uncontrolledScrollOffsets.set(pathKey, clamped);
491+ }
406492 }
407493 cel.render();
408494 }
@@ -731,6 +817,8 @@ export const cel = {
731817 lastFocusedIndex = -1;
732818 frameworkFocusIndex = -1;
733819 stampedNode = null;
820+ uncontrolledScrollOffsets.clear();
821+ stampedScrollNodes = [];
734822 },
735823
736824 /** @internal */