xonecas.io
70160
Ce

cel-tui / commit b74f539

fix: complete stability pass

xonecas2026-04-18 b74f539389732654422a93d7e9cd67900ddaa16d parent 1c5bec7

24 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+1−1
@@ -25,7 +25,7 @@ Dependency graph: `core → types`, `components → core`, `components → types
2525 - **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.
2626 - **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.
2727 - **focusStyle:** Containers accept `focusStyle: StyleProps` — style overrides applied when focused, participating in inheritance.
28-- **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 (follows cursor + responds to mouse wheel).
28+- **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.
2929 - **Text is a pure leaf:** No sizing props, no children. Parent controls the box. Height is intrinsic (from content + wrapping).
3030 - **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.
3131 - **Reactive rendering:** `cel.render()` batches via `process.nextTick()`. No fixed FPS.
TODO.md+6−30
@@ -1,50 +1,26 @@
11 # cel-tui — TODO
22
3-What remains before cel-tui can honestly be called complete and stable.
3+Open work that remains after the stability pass.
44
55 ## Current state
66
77 - Core systems from the spec are implemented.
8-- The repo is currently green: `bun run typecheck`, `bun test`, `bun run check`, and `bun run format` pass.
9-- Remaining work is no longer broad feature work. The open gaps are a short list of correctness bugs, behavior-contract gaps, and docs/capability mismatches.
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.
1011
1112 ## Legend
1213
13-- 🔧 Bug / spec violation
1414 - ❌ Not yet implemented
1515 - 💡 Future enhancement
1616
1717 ---
1818
19-## Blockers to calling the framework complete and stable
20-
21-### Correctness / stability bugs
22-
23-- 🔧 **Flex sizing can overflow or underfill after min/max clamping** — Flex children are sized once, then clamped, but leftover or overflow space is not redistributed. This can produce rows whose child widths sum larger or smaller than the container. Fix in both the normal and wrapping HStack layout paths, with regression tests for overflow and underfill cases.
24-
25-- 🔧 **Hit testing does not clamp controlled scroll offsets** — Painting clamps `scrollOffset` to the valid max, but hit testing currently reads raw values. A container rendered at `scrollOffset: Infinity` or any over-max offset can paint the right content while clicks and scroll targeting miss it. Fix by clamping in the hit-test scroll resolver path and add tests for sticky-bottom / over-max controlled offsets.
26-
27-- 🔧 **`ProcessTerminal` leaks process-level crash handlers across start/stop cycles** — `uncaughtException` and `unhandledRejection` handlers are registered with inline callbacks and never removed. Fix by storing/removing bound handlers so repeated `cel.init()` / `cel.stop()` cycles stay clean.
28-
29-### API / behavior contract gaps
30-
31-- ❌ **Focus callbacks need reason metadata** — `onFocus`/`onBlur` currently expose only that focus changed, not why. Controlled-focus apps still can't distinguish blur caused by `Escape` from blur caused by Tab traversal, mouse clicks, overlay changes, or other focus transitions.
32-
33-- ❌ **Define TextInput scroll semantics for cursor-follow and resize** — After the text layout refactor, the framework now has one canonical visual wrapping model, but the behavior contract around TextInput scrolling is still implicit. In particular: when a user has manually scrolled away from the cursor, what actions should re-enable automatic cursor-follow? And when a TextInput changes height because of intrinsic growth/shrink or `maxHeight` clamping, should the existing scroll offset be p …
34-
35-- ❌ **`repeat: "fill"` should claim flex space in HStack** — `Text(" ", { repeat: "fill" })` inside an HStack gets width 0 because its intrinsic width is 0 and no flex distributes remaining space. The workaround is `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`, which is non-obvious. Fix: either make `repeat: "fill"` imply flex behavior in the layout engine, or document the workaround prominently. The former is preferred.
36-
37-### Capability / docs mismatches to clean up before calling it stable
38-
39-- 🔧 **`clew` over-claims `tsx` / `jsx` support** — `tsx` and `jsx` are currently listed as supported TypeScript-family ids, but JSX tokenization is still wrong in real cases (for example, tag boundaries and closing tags get misclassified as operators / regexp-like tokens). Fix: make the TypeScript tokenizer variant-aware for JSX/TSX, or remove those ids until the support is real.
40-
41-- 🔧 **`Select` over-claims ANSI-styled labels** — The component docs say item labels can include ANSI styling, but the current text pipeline treats those bytes as visible content rather than styling. Fix: either remove the claim or add real ANSI-aware rendering for Select labels.
42-
43-## Open, but not blocking “stable”
19+## Open, but not blocking stability
4420
4521 - ❌ **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.
4622
47-## Post-stability enhancements
23+## Future enhancements
4824
4925 - 💡 **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.
5026
docs/skill/cel-tui/SKILL.md+2−2
@@ -198,7 +198,8 @@ TextInput({
198198 value,
199199 onChange,
200200 focused: isFocused,
201- onFocus: () => {
201+ onFocus: ({ reason }) => {
202+ addLog(`focused via ${reason}`);
202203 isFocused = true;
203204 cel.render();
204205 },
@@ -274,7 +275,6 @@ SyntaxHighlight(source, "javascript", { theme: "dark-plus" });
274275 - **Mouse wheel step is adaptive by default** — scrollable containers and `TextInput` use `floor(viewportMainAxis / 3)`, clamped to `3..8`. Set `scrollStep` to override it for a specific view.
275276 - **Container `bgColor`** fills the rect with opaque background before painting children. Always pair `bgColor` with `fgColor` for contrast — terminal default fg is designed for the terminal default bg, not for arbitrary palette backgrounds.
276277 - **Colors are numbered slots** (`"color00"`–`"color15"`), not names. The default theme maps to ANSI 16. Omit `fgColor`/`bgColor` for terminal defaults (guaranteed readable across themes).
277-- **`repeat: "fill"` in HStack** gets width 0 (intrinsic width is 0). Workaround: wrap in `VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })])`.
278278 - **Crash cleanup** — terminal state is restored on SIGINT, SIGTERM, uncaughtException.
279279 - **Always call `cel.stop()` before `process.exit()`** — restores raw mode, mouse tracking, and alternate screen.
280280 - **Kitty-first keyboard input** — the framework enables Kitty level 1 and gets full modifier fidelity when the host preserves it (`alt+x`, `ctrl+plus`, `shift+enter`, etc.). It also normalizes recoverable legacy encodings so common shortcuts keep working in tmux. For best results, use a Kitty-compatible terminal or `tmux` with `set -s extended-keys on`. On older legacy hosts, historically ambiguous collisions such as `ctrl+i` vs `tab` or `ctrl+m` vs `enter` cannot be recovered once the host c …
docs/skill/cel-tui/references/api.md+4−4
@@ -46,8 +46,8 @@ All props accepted by `VStack` and `HStack`:
4646 onClick, // () => void
4747 focusable, // boolean (default true if onClick set, or set true explicitly)
4848 focused, // boolean (controlled — omit for uncontrolled)
49- onFocus, // () => void
50- onBlur, // () => void
49+ onFocus, // ({ reason }) => void — reason is "tab" | "shift+tab" | "click" | "escape"
50+ onBlur, // ({ reason }) => void — reason is "tab" | "shift+tab" | "click" | "escape"
5151 onKeyPress, // (key: string) => boolean | void — normalized semantic key string; return false to keep bubbling
5252 }
5353 ```
@@ -101,7 +101,7 @@ VStack(
101101 - Scroll is pointer-driven (mouse wheel), not focus-driven. A user can type in a focused widget while scrolling a different container.
102102 - Mouse wheel scrolling uses an adaptive default step based on the scroll target's visible main-axis viewport size: `floor(viewportMainAxis / 3)`, clamped to `3..8`.
103103 - Set `scrollStep` to override the mouse wheel step for a specific scrollable or `TextInput`.
104-- In controlled mode, the UI only moves when the app passes the updated `scrollOffset` back. `onScroll` fires with the clamped new offset and the maximum offset (content size minus viewport size). Pass `Infinity` as `scrollOffset` to mean "scroll to end" (clamped during rendering). `scrollStep` affects mouse wheel input only.
104+- In controlled mode, the UI only moves when the app passes the updated `scrollOffset` back. `onScroll` fires with the clamped new offset and the maximum offset (content size minus viewport size). Pass `Infinity` as `scrollOffset` to mean "scroll to end" (clamped during rendering and hit testing). `scrollStep` affects mouse wheel input only.
105105
106106 ## Text Props
107107
@@ -147,7 +147,7 @@ TextInput({
147147 });
148148 ```
149149
150-When focused, TextInput consumes insertable text plus editing/navigation keys, including readline-style shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and deletion are whitespace-delimited, and `up` / `down` navigate visual wrapped lines. Other modifier combos and non-insertable control keys bubble. Key strings are semantic identifiers for handlers, not necessarily the exact inserted text — uppercase `A` normalizes to key `"a …
150+When focused, TextInput consumes insertable text plus editing/navigation keys, including readline-style shortcuts: `ctrl+a` / `ctrl+e`, `alt+b` / `alt+f`, `ctrl+left` / `ctrl+right`, `ctrl+w`, and `alt+d`. Word movement and deletion are whitespace-delimited, and `up` / `down` navigate visual wrapped lines. The stored scroll offset is clamped every render; when focused, the viewport adjusts further only as needed to keep the cursor visible after edits, cursor movement, mouse wheel scrolling, or r …
151151
152152 ## Sizing Strategies
153153
examples/syntax-highlight.ts+2−2
@@ -103,7 +103,7 @@ const SAMPLES: readonly DemoSample[] = [
103103 {
104104 title: "TypeScript",
105105 language: "typescript",
106- aliases: ["ts", "tsx", "mts", "cts"],
106+ aliases: ["ts", "mts", "cts"],
107107 description:
108108 "Shows the current clew-backed path: keywords, strings, comments, and append-only updates.",
109109 chunkSize: 4,
@@ -129,7 +129,7 @@ const SAMPLES: readonly DemoSample[] = [
129129 {
130130 title: "JavaScript",
131131 language: "javascript",
132- aliases: ["js", "jsx", "mjs", "cjs"],
132+ aliases: ["js", "mjs", "cjs"],
133133 description: "Async code, destructuring, and a template literal.",
134134 chunkSize: 5,
135135 source: [
packages/clew/README.md+2−2
@@ -122,8 +122,8 @@ const output = clew(content, {
122122 The current implementation ships a small internal language registry with:
123123
124124 - **TypeScript / JavaScript ids**
125- - `typescript`, `ts`, `tsx`, `mts`, `cts`
126- - `javascript`, `js`, `jsx`, `mjs`, `cjs`
125+ - `typescript`, `ts`, `mts`, `cts`
126+ - `javascript`, `js`, `mjs`, `cjs`
127127 - **Python**
128128 - `python`, `py`
129129 - **Bash**
packages/clew/src/index.test.ts+2−0
@@ -72,6 +72,8 @@ describe("clew", () => {
7272 expect(clewSupportsLanguage("bash")).toBe(true);
7373 expect(clewSupportsLanguage("json")).toBe(true);
7474 expect(clewSupportsLanguage("markdown")).toBe(true);
75+ expect(clewSupportsLanguage("tsx")).toBe(false);
76+ expect(clewSupportsLanguage("jsx")).toBe(false);
7577 expect(clewSupportsLanguage("shell")).toBe(false);
7678 expect(clewSupportsLanguage("zsh")).toBe(false);
7779 expect(clewSupportsLanguage("md")).toBe(false);
packages/clew/src/languages/typescript.ts+1−12
@@ -659,18 +659,7 @@ function tokenizeTypescript(content: string): ClewOutput {
659659 }
660660
661661 export const typescriptLanguageSupport: ClewLanguageSupport = {
662- ids: [
663- "typescript",
664- "ts",
665- "tsx",
666- "mts",
667- "cts",
668- "javascript",
669- "js",
670- "jsx",
671- "mjs",
672- "cjs",
673- ],
662+ ids: ["typescript", "ts", "mts", "cts", "javascript", "js", "mjs", "cjs"],
674663 stableBoundary: stableLineBoundary,
675664 tokenize: tokenizeTypescript,
676665 };
packages/components/src/button.ts+2−2
@@ -24,9 +24,9 @@ export interface ButtonProps extends StyleProps {
2424 */
2525 focused?: boolean;
2626 /** Called when the button receives focus. */
27- onFocus?: () => void;
27+ onFocus?: ContainerProps["onFocus"];
2828 /** Called when the button loses focus. */
29- onBlur?: () => void;
29+ onBlur?: ContainerProps["onBlur"];
3030 /**
3131 * Style overrides applied when focused. Overridden values
3232 * participate in inheritance — the label text sees the
packages/components/src/select.ts+4−4
@@ -18,13 +18,13 @@ import type {
1818 * // Simple string item
1919 * "apple"
2020 *
21- * // Rich item with ANSI-colored label
21+ * // Rich item with explicit display and filter text
2222 * { label: "claude-sonnet-4 (free)", value: "anthropic/claude-sonnet-4", filterText: "claude-sonnet-4" }
2323 */
2424 export type SelectItem =
2525 | string
2626 | {
27- /** Displayed text (can include ANSI styling). */
27+ /** Displayed text. */
2828 label: string;
2929 /** Value returned on selection. */
3030 value: string;
@@ -92,9 +92,9 @@ export interface SelectProps {
9292 */
9393 focusable?: boolean;
9494 /** Called when the select receives focus. */
95- onFocus?: () => void;
95+ onFocus?: ContainerProps["onFocus"];
9696 /** Called when the select loses focus. */
97- onBlur?: () => void;
97+ onBlur?: ContainerProps["onBlur"];
9898 /** Style overrides applied when focused. */
9999 focusStyle?: StyleProps;
100100 }
packages/core/src/cel.test.ts+55−20
@@ -539,6 +539,7 @@ describe("cel end-to-end", () => {
539539 test("Tab moves focus to next focusable element", async () => {
540540 const term = setup(20, 5);
541541 const focused: string[] = [];
542+ const blurred: string[] = [];
542543 let focus1 = false;
543544 let focus2 = false;
544545
@@ -548,13 +549,14 @@ describe("cel end-to-end", () => {
548549 {
549550 onClick: () => {},
550551 focused: focus1,
551- onFocus: () => {
552+ onFocus: (event) => {
552553 focus1 = true;
553554 focus2 = false;
554- focused.push("btn1");
555+ focused.push(`btn1:${event.reason}`);
555556 },
556- onBlur: () => {
557+ onBlur: (event) => {
557558 focus1 = false;
559+ blurred.push(`btn1:${event.reason}`);
558560 },
559561 },
560562 [Text("Btn1")],
@@ -563,13 +565,14 @@ describe("cel end-to-end", () => {
563565 {
564566 onClick: () => {},
565567 focused: focus2,
566- onFocus: () => {
568+ onFocus: (event) => {
567569 focus2 = true;
568570 focus1 = false;
569- focused.push("btn2");
571+ focused.push(`btn2:${event.reason}`);
570572 },
571- onBlur: () => {
573+ onBlur: (event) => {
572574 focus2 = false;
575+ blurred.push(`btn2:${event.reason}`);
573576 },
574577 },
575578 [Text("Btn2")],
@@ -581,12 +584,14 @@ describe("cel end-to-end", () => {
581584 // Tab to focus first element
582585 term.sendInput(TAB);
583586 await waitForRender();
584- expect(focused).toEqual(["btn1"]);
587+ expect(focused).toEqual(["btn1:tab"]);
588+ expect(blurred).toEqual([]);
585589
586590 // Tab to focus second element
587591 term.sendInput(TAB);
588592 await waitForRender();
589- expect(focused).toEqual(["btn1", "btn2"]);
593+ expect(focused).toEqual(["btn1:tab", "btn2:tab"]);
594+ expect(blurred).toEqual(["btn1:tab"]);
590595 });
591596
592597 test("Shift+Tab moves focus backwards", async () => {
@@ -594,6 +599,7 @@ describe("cel end-to-end", () => {
594599 let focus1 = false;
595600 let focus2 = true;
596601 const focused: string[] = [];
602+ const blurred: string[] = [];
597603
598604 cel.viewport(() =>
599605 VStack({ width: 20, height: 5 }, [
@@ -601,13 +607,14 @@ describe("cel end-to-end", () => {
601607 {
602608 onClick: () => {},
603609 focused: focus1,
604- onFocus: () => {
610+ onFocus: (event) => {
605611 focus1 = true;
606612 focus2 = false;
607- focused.push("btn1");
613+ focused.push(`btn1:${event.reason}`);
608614 },
609- onBlur: () => {
615+ onBlur: (event) => {
610616 focus1 = false;
617+ blurred.push(`btn1:${event.reason}`);
611618 },
612619 },
613620 [Text("Btn1")],
@@ -616,13 +623,14 @@ describe("cel end-to-end", () => {
616623 {
617624 onClick: () => {},
618625 focused: focus2,
619- onFocus: () => {
626+ onFocus: (event) => {
620627 focus2 = true;
621628 focus1 = false;
622- focused.push("btn2");
629+ focused.push(`btn2:${event.reason}`);
623630 },
624- onBlur: () => {
631+ onBlur: (event) => {
625632 focus2 = false;
633+ blurred.push(`btn2:${event.reason}`);
626634 },
627635 },
628636 [Text("Btn2")],
@@ -634,12 +642,13 @@ describe("cel end-to-end", () => {
634642 // Shift+Tab from btn2 should focus btn1
635643 term.sendInput(SHIFT_TAB);
636644 await waitForRender();
637- expect(focused).toEqual(["btn1"]);
645+ expect(focused).toEqual(["btn1:shift+tab"]);
646+ expect(blurred).toEqual(["btn2:shift+tab"]);
638647 });
639648
640649 test("Escape unfocuses the current element", async () => {
641650 const term = setup(20, 5);
642- let blurred = false;
651+ let blurReason = "";
643652 let btnFocused = true;
644653
645654 cel.viewport(() =>
@@ -648,8 +657,8 @@ describe("cel end-to-end", () => {
648657 {
649658 onClick: () => {},
650659 focused: btnFocused,
651- onBlur: () => {
652- blurred = true;
660+ onBlur: (event) => {
661+ blurReason = event.reason;
653662 btnFocused = false;
654663 },
655664 },
@@ -661,7 +670,7 @@ describe("cel end-to-end", () => {
661670
662671 term.sendInput(ESCAPE);
663672 await waitForRender();
664- expect(blurred).toBe(true);
673+ expect(blurReason).toBe("escape");
665674 });
666675
667676 test("Enter activates focused clickable container", async () => {
@@ -691,6 +700,7 @@ describe("cel end-to-end", () => {
691700 test("mouse click on focusable element fires onFocus", async () => {
692701 const term = setup(20, 5);
693702 let btnFocused = false;
703+ let focusReason = "";
694704
695705 cel.viewport(() =>
696706 VStack({ width: 20, height: 5 }, [
@@ -698,8 +708,9 @@ describe("cel end-to-end", () => {
698708 {
699709 onClick: () => {},
700710 focused: btnFocused,
701- onFocus: () => {
711+ onFocus: (event) => {
702712 btnFocused = true;
713+ focusReason = event.reason;
703714 },
704715 },
705716 [Text("Btn")],
@@ -712,6 +723,7 @@ describe("cel end-to-end", () => {
712723 term.sendInput("\x1b[<0;2;1m");
713724 await waitForRender();
714725 expect(btnFocused).toBe(true);
726+ expect(focusReason).toBe("click");
715727 });
716728
717729 test("Tab wraps around to first element", async () => {
@@ -1839,6 +1851,29 @@ describe("cel end-to-end", () => {
18391851 expect(value).toBe("x");
18401852 });
18411853
1854+ test("Tab focusing an uncontrolled TextInput shows the native cursor", async () => {
1855+ const term = setup(20, 5);
1856+ let value = "";
1857+
1858+ cel.viewport(() =>
1859+ VStack({ width: 20, height: 5 }, [
1860+ TextInput({
1861+ value,
1862+ onChange: (v) => {
1863+ value = v;
1864+ },
1865+ }),
1866+ ]),
1867+ );
1868+ await waitForRender();
1869+
1870+ term.clearOutput();
1871+ term.sendInput(TAB);
1872+ await waitForRender();
1873+
1874+ expect(term.output).toContain("\x1b[?25h");
1875+ });
1876+
18421877 test("Tab wraps from last to first element", async () => {
18431878 const term = setup(20, 5);
18441879 const clicks: string[] = [];
packages/core/src/cel.ts+26−12
@@ -1,4 +1,5 @@
11 import type {
2+ FocusChangeReason,
23 Node,
34 TextInputNode,
45 TextInputProps,
@@ -23,7 +24,11 @@ import {
2324 setTextInputCursor,
2425 setTextInputScroll,
2526 } from "./paint.js";
26-import { getMaxScrollOffset, getScrollStep } from "./scroll.js";
27+import {
28+ clampScrollOffset,
29+ getMaxScrollOffset,
30+ getScrollStep,
31+} from "./scroll.js";
2732 import type { Terminal } from "./terminal.js";
2833 import {
2934 deleteBackward,
@@ -134,12 +139,12 @@ function doRender(): void {
134139 paint(layoutTree, currentBuffer);
135140 }
136141
142+ const nextCursor = getDesiredTerminalCursor();
143+
137144 // Unstamp after paint so input handlers see clean props
138145 unstampUncontrolledFocus();
139146 unstampUncontrolledScroll();
140147
141- const nextCursor = getDesiredTerminalCursor();
142-
143148 // Emit to terminal — differential when possible
144149 if (prevBuffer) {
145150 const output = emitDiff(prevBuffer, currentBuffer, activeTheme, {
@@ -623,8 +628,12 @@ function unstampUncontrolledScroll(): void {
623628 * Manages both controlled (via onFocus/onBlur callbacks) and
624629 * uncontrolled (via frameworkFocusIndex) focus.
625630 */
626-function changeFocus(target: LayoutNode | null): void {
631+function changeFocus(
632+ target: LayoutNode | null,
633+ reason: FocusChangeReason,
634+): void {
627635 const current = findFocusedElement();
636+ const event = { reason };
628637
629638 // Blur current — save position for Tab/Shift+Tab continuity
630639 if (current && current !== target) {
@@ -645,7 +654,7 @@ function changeFocus(target: LayoutNode | null): void {
645654 ? current.node.props
646655 : null;
647656 if (props && "onBlur" in props && props.onBlur) {
648- props.onBlur();
657+ props.onBlur(event);
649658 }
650659 }
651660
@@ -669,7 +678,7 @@ function changeFocus(target: LayoutNode | null): void {
669678 ? target.node.props
670679 : null;
671680 if (props && "onFocus" in props && props.onFocus) {
672- props.onFocus();
681+ props.onFocus(event);
673682 }
674683 }
675684 }
@@ -682,11 +691,13 @@ function resolveScrollOffset(ln: import("./layout.js").LayoutNode): number {
682691 const node = ln.node;
683692 if (node.type === "text") return 0;
684693 const props = node.props;
685- if (props.scrollOffset !== undefined) return props.scrollOffset;
694+ if (props.scrollOffset !== undefined) {
695+ return clampScrollOffset(ln, props.scrollOffset);
696+ }
686697 // Check uncontrolled map
687698 const pathKey = getScrollPathKey(ln);
688699 if (pathKey !== null) {
689- return uncontrolledScrollOffsets.get(pathKey) ?? 0;
700+ return clampScrollOffset(ln, uncontrolledScrollOffsets.get(pathKey) ?? 0);
690701 }
691702 return 0;
692703 }
@@ -702,7 +713,7 @@ function handleMouseEvent(event: MouseEvent): void {
702713 // Find and focus the focusable element at click position
703714 const focusable = findClickFocusTarget(path);
704715 if (focusable) {
705- changeFocus(focusable);
716+ changeFocus(focusable, "click");
706717 }
707718
708719 const click = findClickHandler(path);
@@ -822,11 +833,11 @@ function handleBracketedPaste(text: string): void {
822833 commitTextInputEdit(props, editState, nextState);
823834 }
824835
825-function blurFocusedElement(): boolean {
836+function blurFocusedElement(reason: FocusChangeReason = "escape"): boolean {
826837 const current = findFocusedElement();
827838 if (!current) return false;
828839
829- changeFocus(null);
840+ changeFocus(null, reason);
830841 cel.render();
831842 return true;
832843 }
@@ -877,7 +888,10 @@ function handleKeyEvent(event: KeyInput): void {
877888 : (currentIdx - 1 + focusables.length) % focusables.length;
878889 }
879890
880- changeFocus(requiredAt(focusables, nextIdx, "focusable node"));
891+ changeFocus(
892+ requiredAt(focusables, nextIdx, "focusable node"),
893+ key === "tab" ? "tab" : "shift+tab",
894+ );
881895 cel.render();
882896 return;
883897 } // end: not a focused TextInput
packages/core/src/hit-test.test.ts+35−0
@@ -132,6 +132,41 @@ describe("hitTest", () => {
132132 expect(textContent(last(path))).toBe("b");
133133 });
134134
135+ test("clamps vertical scroll offset before hit testing", () => {
136+ const node = VStack(
137+ { width: 20, height: 3, overflow: "scroll", scrollOffset: Infinity },
138+ [
139+ Text("line 0"),
140+ Text("line 1"),
141+ Text("line 2"),
142+ Text("line 3"),
143+ Text("line 4"),
144+ ],
145+ );
146+ const ln = layout(node, 20, 3);
147+
148+ const topPath = hitTest(ln, 3, 0);
149+ expect(textContent(last(topPath))).toBe("line 2");
150+
151+ const bottomPath = hitTest(ln, 3, 2);
152+ expect(textContent(last(bottomPath))).toBe("line 4");
153+ });
154+
155+ test("clamps horizontal over-max scroll offset before hit testing", () => {
156+ const node = HStack(
157+ { width: 10, height: 3, overflow: "scroll", scrollOffset: 999 },
158+ [
159+ VStack({ width: 5 }, [Text("a")]),
160+ VStack({ width: 5 }, [Text("b")]),
161+ VStack({ width: 5 }, [Text("c")]),
162+ ],
163+ );
164+ const ln = layout(node, 10, 3);
165+
166+ const path = hitTest(ln, 0, 0);
167+ expect(textContent(last(path))).toBe("b");
168+ });
169+
135170 test("no scroll adjustment without overflow scroll", () => {
136171 const node = VStack({ width: 20, height: 3 }, [
137172 Text("line 0"),
packages/core/src/hit-test.ts+2−1
@@ -1,5 +1,6 @@
11 import type { ContainerProps } from "@cel-tui/types";
22 import type { LayoutNode, Rect } from "./layout.js";
3+import { clampScrollOffset } from "./scroll.js";
34
45 /**
56 * Test if a point is inside a rect.
@@ -77,7 +78,7 @@ export function hitTest(
7778 // Check if current node is scrollable — if so, adjust coordinates
7879 const props = getProps(current);
7980 if (props?.overflow === "scroll" || current.node.type === "textinput") {
80- const offset = resolver(current);
81+ const offset = clampScrollOffset(current, resolver(current));
8182 if (offset !== 0) {
8283 const isVertical =
8384 current.node.type === "vstack" || current.node.type === "textinput";
packages/core/src/index.ts+3−0
@@ -31,6 +31,9 @@ export type {
3131 Color,
3232 ContainerNode,
3333 ContainerProps,
34+ FocusChangeEvent,
35+ FocusChangeHandler,
36+ FocusChangeReason,
3437 Node,
3538 SizeValue,
3639 StyleProps,
packages/core/src/layout.test.ts+69−5
@@ -190,6 +190,20 @@ describe("layout", () => {
190190 { x: 0, y: 23, width: 80, height: 1 },
191191 ]);
192192 });
193+
194+ test("repeat fill claims remaining width in HStack", () => {
195+ const node = HStack({ width: 10, height: 1 }, [
196+ Text("A"),
197+ Text("-", { repeat: "fill" }),
198+ Text("B"),
199+ ]);
200+ const result = layout(node, 10, 1);
201+ expect(childRects(result)).toEqual([
202+ { x: 0, y: 0, width: 1, height: 1 },
203+ { x: 1, y: 0, width: 8, height: 1 },
204+ { x: 9, y: 0, width: 1, height: 1 },
205+ ]);
206+ });
193207 });
194208
195209 describe("percentage sizing", () => {
@@ -226,22 +240,37 @@ describe("layout", () => {
226240 });
227241
228242 describe("constraints", () => {
229- test("minWidth prevents shrinking below minimum", () => {
243+ test("minWidth redistributes the remaining flex width", () => {
230244 const node = HStack({ width: 80, height: 24 }, [
231- VStack({ flex: 1, minWidth: 30 }, []),
245+ VStack({ flex: 1, minWidth: 60 }, []),
232246 VStack({ flex: 1 }, []),
233247 ]);
234248 const result = layout(node, 80, 24);
235- expect(item(childRects(result), 0).width).toBeGreaterThanOrEqual(30);
249+ const widths = childRects(result).map((child) => child.width);
250+ expect(widths).toEqual([60, 20]);
251+ expect(widths.reduce((sum, width) => sum + width, 0)).toBe(80);
236252 });
237253
238- test("maxHeight caps growth", () => {
254+ test("maxHeight redistributes the remaining flex height", () => {
239255 const node = VStack({ width: 80, height: 24 }, [
240256 VStack({ flex: 1, maxHeight: 10 }, []),
241257 VStack({ flex: 1 }, []),
242258 ]);
243259 const result = layout(node, 80, 24);
244- expect(item(childRects(result), 0).height).toBeLessThanOrEqual(10);
260+ const heights = childRects(result).map((child) => child.height);
261+ expect(heights).toEqual([10, 14]);
262+ expect(heights.reduce((sum, height) => sum + height, 0)).toBe(24);
263+ });
264+
265+ test("mixed minWidth and maxWidth constraints keep redistributing flex width", () => {
266+ const node = HStack({ width: 100, height: 24 }, [
267+ VStack({ flex: 1, minWidth: 80 }, []),
268+ VStack({ flex: 1, maxWidth: 10 }, []),
269+ ]);
270+ const result = layout(node, 100, 24);
271+ const widths = childRects(result).map((child) => child.width);
272+ expect(widths).toEqual([90, 10]);
273+ expect(widths.reduce((sum, width) => sum + width, 0)).toBe(100);
245274 });
246275 });
247276
@@ -838,6 +867,41 @@ describe("layout", () => {
838867 expect(rects[2]).toEqual({ x: 50, y: 0, width: 30, height: 3 });
839868 });
840869
870+ test("row flex redistribution honors minWidth after clamping", () => {
871+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
872+ VStack({ width: 20, height: 3 }, []),
873+ VStack({ flex: 1, minWidth: 40, height: 3 }, []),
874+ VStack({ flex: 1, height: 3 }, []),
875+ ]);
876+ const result = layout(node, 80, 24);
877+ const widths = childRects(result).map((child) => child.width);
878+ expect(widths).toEqual([20, 40, 20]);
879+ expect(widths.reduce((sum, width) => sum + width, 0)).toBe(80);
880+ });
881+
882+ test("row flex redistribution honors maxWidth after clamping", () => {
883+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
884+ VStack({ width: 20, height: 3 }, []),
885+ VStack({ flex: 1, maxWidth: 10, height: 3 }, []),
886+ VStack({ flex: 1, height: 3 }, []),
887+ ]);
888+ const result = layout(node, 80, 24);
889+ const widths = childRects(result).map((child) => child.width);
890+ expect(widths).toEqual([20, 10, 50]);
891+ expect(widths.reduce((sum, width) => sum + width, 0)).toBe(80);
892+ });
893+
894+ test("row flex redistribution keeps going after mixed minWidth and maxWidth clamps", () => {
895+ const node = HStack({ width: 100, height: 24, flexWrap: "wrap" }, [
896+ VStack({ flex: 1, minWidth: 80, height: 3 }, []),
897+ VStack({ flex: 1, maxWidth: 10, height: 3 }, []),
898+ ]);
899+ const result = layout(node, 100, 24);
900+ const widths = childRects(result).map((child) => child.width);
901+ expect(widths).toEqual([90, 10]);
902+ expect(widths.reduce((sum, width) => sum + width, 0)).toBe(100);
903+ });
904+
841905 test("padding reduces available width for wrapping", () => {
842906 // Inner width = 80 - 2*5 = 70
843907 // Row 1: 40 ≤ 70 ✓, 40+40=80 > 70 ✗
packages/core/src/layout.ts+144−32
@@ -52,6 +52,22 @@ function getProps(node: Node): ContainerProps | null {
5252 return node.props;
5353 }
5454
55+function getNodeFlex(node: Node, isVertical: boolean): number {
56+ const explicitFlex = getProps(node)?.flex;
57+ if (explicitFlex && explicitFlex > 0) {
58+ return explicitFlex;
59+ }
60+ if (
61+ !isVertical &&
62+ node.type === "text" &&
63+ node.props.repeat === "fill" &&
64+ visibleWidth(node.content) > 0
65+ ) {
66+ return 1;
67+ }
68+ return 0;
69+}
70+
5571 function requiredAt<T>(
5672 items: readonly T[],
5773 index: number,
@@ -297,6 +313,100 @@ function largestRemainder(fractions: number[], total: number): number[] {
297313 return floored;
298314 }
299315
316+interface FlexAllocationItem {
317+ flex: number;
318+ min: number;
319+ max: number;
320+}
321+
322+function allocateFlexSizes(
323+ items: readonly FlexAllocationItem[],
324+ total: number,
325+): number[] {
326+ const sizes = Array.from({ length: items.length }, () => 0);
327+ let remainingIndices = items.map((_, index) => index);
328+ let remainingSpace = total;
329+ let remainingFlex = items.reduce((sum, item) => sum + item.flex, 0);
330+
331+ while (remainingIndices.length > 0 && remainingFlex > 0) {
332+ const rawSizes = remainingIndices.map((index) => {
333+ const item = requiredAt(items, index, "flex allocation item");
334+ return (item.flex / remainingFlex) * remainingSpace;
335+ });
336+
337+ const minClamped = new Set<number>();
338+
339+ for (let i = 0; i < remainingIndices.length; i++) {
340+ const index = requiredAt(remainingIndices, i, "flex allocation index");
341+ const rawSize = requiredAt(rawSizes, i, "raw flex size");
342+ const item = requiredAt(items, index, "flex allocation item");
343+
344+ if (rawSize < item.min) {
345+ sizes[index] = item.min;
346+ remainingSpace -= item.min;
347+ remainingFlex -= item.flex;
348+ minClamped.add(index);
349+ }
350+ }
351+
352+ if (minClamped.size === 0) {
353+ const rounded = largestRemainder(rawSizes, remainingSpace);
354+ for (let i = 0; i < remainingIndices.length; i++) {
355+ const index = requiredAt(remainingIndices, i, "flex allocation index");
356+ sizes[index] = requiredAt(rounded, i, "rounded flex size");
357+ }
358+ break;
359+ }
360+
361+ remainingIndices = remainingIndices.filter(
362+ (index) => !minClamped.has(index),
363+ );
364+ }
365+
366+ let activeIndices = items.map((_, index) => index);
367+ let activeFlex = items.reduce((sum, item) => sum + item.flex, 0);
368+
369+ while (activeIndices.length > 0 && activeFlex > 0) {
370+ let excess = 0;
371+ const maxClamped = new Set<number>();
372+
373+ for (const index of activeIndices) {
374+ const item = requiredAt(items, index, "flex allocation item");
375+ const max = Math.max(item.min, item.max);
376+ const size = requiredAt(sizes, index, "allocated flex size");
377+
378+ if (size > max) {
379+ sizes[index] = max;
380+ excess += size - max;
381+ activeFlex -= item.flex;
382+ maxClamped.add(index);
383+ }
384+ }
385+
386+ if (maxClamped.size === 0) {
387+ return sizes;
388+ }
389+
390+ activeIndices = activeIndices.filter((index) => !maxClamped.has(index));
391+ if (activeIndices.length === 0 || activeFlex <= 0 || excess <= 0) {
392+ return sizes;
393+ }
394+
395+ const rawExtras = activeIndices.map((index) => {
396+ const item = requiredAt(items, index, "flex allocation item");
397+ return (item.flex / activeFlex) * excess;
398+ });
399+ const rounded = largestRemainder(rawExtras, excess);
400+
401+ for (let i = 0; i < activeIndices.length; i++) {
402+ const index = requiredAt(activeIndices, i, "flex allocation index");
403+ sizes[index] += requiredAt(rounded, i, "rounded flex size");
404+ }
405+ }
406+
407+ return sizes;
408+}
409+
300410 // --- Main layout ---
301411
302412 /**
@@ -384,7 +494,7 @@ function layoutWrapHStack(
384494
385495 for (const child of children) {
386496 const cProps = getProps(child);
387- const flex = cProps?.flex ?? 0;
497+ const flex = getNodeFlex(child, false);
388498 flexValues.push(flex);
389499
390500 let baseW: number;
@@ -448,24 +558,23 @@ function layoutWrapHStack(
448558 flexPositions.push(ci);
449559 }
450560 }
451- const rawSizes = flexPositions.map((ci) => {
452- const rowIndex = requiredAt(rowIdx, ci, "wrap row index");
453- return (
454- (requiredAt(flexValues, rowIndex, "flex value") / totalFlex) *
455- flexSpace
456- );
457- });
458- const rounded = largestRemainder(rawSizes, flexSpace);
561+
562+ const allocated = allocateFlexSizes(
563+ flexPositions.map((ci) => {
564+ const rowIndex = requiredAt(rowIdx, ci, "wrap row index");
565+ const cProps = getProps(requiredAt(children, rowIndex, "child node"));
566+ return {
567+ flex: requiredAt(flexValues, rowIndex, "flex value"),
568+ min: cProps?.minWidth ?? 0,
569+ max: cProps?.maxWidth ?? Infinity,
570+ };
571+ }),
572+ flexSpace,
573+ );
459574
460575 for (let fi = 0; fi < flexPositions.length; fi++) {
461576 const ci = requiredAt(flexPositions, fi, "flex position");
462- let size = requiredAt(rounded, fi, "rounded flex size");
463- const rowIndex = requiredAt(rowIdx, ci, "wrap row index");
464- const cProps = getProps(requiredAt(children, rowIndex, "child node"));
465- if (cProps) {
466- size = clamp(size, cProps.minWidth ?? 0, cProps.maxWidth ?? Infinity);
467- }
468- childWidths[ci] = size;
577+ childWidths[ci] = requiredAt(allocated, fi, "allocated flex size");
469578 }
470579 }
471580
@@ -638,7 +747,7 @@ function layoutNode(
638747
639748 for (const child of children) {
640749 const cProps = getProps(child);
641- const flex = cProps?.flex ?? 0;
750+ const flex = getNodeFlex(child, isVertical);
642751
643752 if (flex > 0) {
644753 totalFlex += flex;
@@ -719,23 +828,26 @@ function layoutNode(
719828
720829 if (totalFlex > 0) {
721830 const flexInfos = infos.filter((c) => c.flex > 0);
722- const rawSizes = flexInfos.map((c) => (c.flex / totalFlex) * flexSpace);
723- const rounded = largestRemainder(rawSizes, flexSpace);
831+ const allocated = allocateFlexSizes(
832+ flexInfos.map((info) => {
833+ const cProps = getProps(info.node);
834+ return {
835+ flex: info.flex,
836+ min: isVertical ? (cProps?.minHeight ?? 0) : (cProps?.minWidth ?? 0),
837+ max: isVertical
838+ ? (cProps?.maxHeight ?? Infinity)
839+ : (cProps?.maxWidth ?? Infinity),
840+ };
841+ }),
842+ flexSpace,
843+ );
724844
725845 for (let i = 0; i < flexInfos.length; i++) {
726- let size = requiredAt(rounded, i, "rounded flex size");
727- const flexInfo = requiredAt(flexInfos, i, "flex child info");
728- const cProps = getProps(flexInfo.node);
729- if (cProps) {
730- const minMain = isVertical
731- ? (cProps.minHeight ?? 0)
732- : (cProps.minWidth ?? 0);
733- const maxMain = isVertical
734- ? (cProps.maxHeight ?? Infinity)
735- : (cProps.maxWidth ?? Infinity);
736- size = clamp(size, minMain, maxMain);
737- }
738- flexInfo.mainSize = size;
846+ requiredAt(flexInfos, i, "flex child info").mainSize = requiredAt(
847+ allocated,
848+ i,
849+ "allocated flex size",
850+ );
739851 }
740852 }
741853
packages/core/src/paint.test.ts+48−0
@@ -3,8 +3,10 @@ import { CellBuffer } from "./cell-buffer.js";
33 import { layout } from "./layout.js";
44 import {
55 getTextInputCursorScreenPos,
6+ getTextInputScroll,
67 paint,
78 setTextInputCursor,
9+ setTextInputScroll,
810 } from "./paint.js";
911 import { HStack, VStack } from "./primitives/stacks.js";
1012 import { Text } from "./primitives/text.js";
@@ -139,6 +141,40 @@ describe("paint", () => {
139141 getTextInputCursorScreenPos(props, { x: 0, y: 0, width: 6, height: 3 }),
140142 ).toEqual({ x: 1, y: 1 });
141143 });
144+
145+ test("focused TextInput clamps stale scroll before projecting the cursor", () => {
146+ const onChange = () => {};
147+ const props = {
148+ value: "foo bar baz",
149+ onChange,
150+ focused: true,
151+ };
152+
153+ setTextInputCursor(props, 5);
154+ setTextInputScroll(props, 99);
155+
156+ expect(
157+ getTextInputCursorScreenPos(props, { x: 0, y: 0, width: 6, height: 3 }),
158+ ).toEqual({ x: 1, y: 1 });
159+ expect(getTextInputScroll(props)).toBe(0);
160+ });
161+
162+ test("unfocused TextInput clamps stale scroll during paint", () => {
163+ const onChange = () => {};
164+ const props = {
165+ value: "line1\nline2",
166+ onChange,
167+ height: 2,
168+ };
169+ setTextInputScroll(props, 99);
170+
171+ const node = VStack({ width: 6, height: 2 }, [TextInput(props)]);
172+ const ln = layout(node, 6, 2);
173+ const buf = new CellBuffer(6, 2);
174+ paint(ln, buf);
175+
176+ expect(getTextInputScroll(props)).toBe(0);
177+ });
142178 });
143179
144180 describe("layout-driven positioning", () => {
@@ -177,6 +213,18 @@ describe("paint", () => {
177213 expect(buf.get(5, 0).char).toBe("B");
178214 });
179215
216+ test("repeat fill renders inside HStack", () => {
217+ const node = HStack({ width: 10, height: 1 }, [
218+ Text("A"),
219+ Text("-", { repeat: "fill" }),
220+ Text("B"),
221+ ]);
222+ const ln = layout(node, 10, 1);
223+ const buf = new CellBuffer(10, 1);
224+ paint(ln, buf);
225+ expect(readRawRow(buf, 0)).toBe("A--------B");
226+ });
227+
180228 test("padding offsets children", () => {
181229 const node = VStack({ width: 20, height: 5, padding: { x: 2, y: 1 } }, [
182230 Text("Hi"),
packages/core/src/paint.ts+44−23
@@ -429,6 +429,31 @@ function paintText(
429429 }
430430 }
431431
432+function resolveTextInputScrollOffset(
433+ props: TextInputProps,
Cut short: this commit's diff is over 1000 lines.
packages/core/src/scroll.ts+11−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.test.ts+103−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/terminal.ts+24−7
Cut short: this commit's diff is over 1000 lines.
packages/types/src/index.ts+20−4
Cut short: this commit's diff is over 1000 lines.
spec.md+41−37
Cut short: this commit's diff is over 1000 lines.