xonecas.io
70160
Ce

cel-tui / commit ad4be61

fix(core): handle batched mouse events, Tab in TextInput, and TextInput scroll

- Fix batched SGR mouse events: real terminals send multiple mouse events
  in a single stdin chunk. The parser now scans for all events and processes
  each one, with scroll offset accumulation for controlled scroll.
- Fix Tab key in TextInput: Tab/Shift+Tab no longer trigger focus traversal
  when a TextInput is focused. Tab inserts \t as an editing key per spec.
  Press Escape first, then Tab to traverse.
- Fix mouse wheel scroll on TextInput: scroll events targeting a TextInput
  now update its framework-managed scroll offset directly.
- Add simple-scroll example demonstrating scrollable lists.
- Add tmux caveat and destructive actions guidance to AGENTS.md.
- Update test count and docs across README, AGENTS, TODO.

xonecas2026-04-04 ad4be616fb526f47999955563f390f1ed37a9c98 parent 0c69554

6 files changed

AGENTS.md+11−3
@@ -34,12 +34,12 @@ Dependency chain: `components → core → types`
3434
3535 ## Implementation Status
3636
37-All core systems from the spec are implemented and tested (232 tests):
37+All core systems from the spec are implemented and tested (240 tests):
3838
3939 - **Layout engine** — flexbox sizing (fixed, intrinsic, flex, percentage), constraints, gap, padding, justifyContent, alignItems, largest-remainder rounding
4040 - **Rendering** — cell buffer, ANSI emitter with SGR styling, synchronized output (CSI 2026), differential rendering (emitDiff), full clear on resize
4141 - **Painting** — grapheme-aware text rendering (CJK/emoji via visibleWidth), overflow clipping via clip rect propagation, scroll content offsetting, scrollbar indicators
42-- **Input** — key parsing/normalization, SGR mouse events, hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter), onKeyPress bubbling from focused element through ancestors
42+- **Input** — key parsing/normalization, SGR mouse events (with batched event support), hit detection, click/scroll routing, focus traversal (Tab/Shift+Tab/Escape/Enter), onKeyPress bubbling from focused element through ancestors
4343 - **TextInput** — text editing, cursor movement, cursor persistence across re-renders (keyed on onChange), auto-scroll to keep cursor visible, placeholder rendering
4444 - **Layering** — multi-layer compositing, transparency, topmost-layer input priority
4545 - **Terminal** — crash cleanup (SIGINT/SIGTERM/uncaughtException), resize clear
@@ -90,6 +90,8 @@ tmux kill-session -t cel
9090
9191 This lets you see exactly what the user sees — rendered cells, alignment, clipping, colors — without needing a real interactive terminal.
9292
93+**Caveat:** tmux `send-keys -H` injects raw bytes one event at a time, but real terminals batch multiple mouse events into a single stdin chunk. Always verify mouse/scroll behavior in a real terminal, not just tmux.
94+
9395 ## Spec
9496
9597 The `spec.md` file is the source of truth for all API design decisions. Always read it before making changes to core framework behavior. The open questions at the bottom track what's been decided vs. still in progress.
@@ -139,7 +141,7 @@ chore: scaffold monorepo with types, core, components packages
139141
140142 ## Architecture Notes
141143
142-- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal)` starts, `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal.
144+- `cel.ts` — Framework entrypoint. Owns render loop, input dispatch, focus management. `cel.init(terminal)` starts, `cel.viewport(fn)` sets render function, `cel.render()` requests re-render, `cel.stop()` restores terminal. Mouse input handles batched SGR events (terminals often send multiple events in a single data chunk).
143145 - `layout.ts` — Flexbox engine. `layout(root, width, height)` → `LayoutNode` tree with absolute screen rects.
144146 - `paint.ts` — Paints `LayoutNode` tree into `CellBuffer`. Handles clip rects, scroll offsets, scrollbars, grapheme-aware text rendering, TextInput cursor/scroll state.
145147 - `emitter.ts` — `emitBuffer()` for full renders, `emitDiff()` for differential. Both wrap in CSI 2026 synchronized output.
@@ -167,6 +169,12 @@ git checkout main
167169 - `.gitignore` does **not** exclude `docs/html/` or `docs/md/` (they're committed)
168170 - `.prettierignore` includes `docs/html` and `docs/md` (generated files fail format checks otherwise)
169171
172+## Destructive Actions
173+
174+**Never use `git checkout` or `git restore` on files you have modified.** A single `git checkout <file>` will silently discard all uncommitted changes in that file — including unrelated work. If you need to revert a specific edit, use `edit` to undo just that change. If you must use git to undo something, `git stash` first so the work can be recovered.
175+
176+More generally: before running any command that could destroy uncommitted work (`git checkout`, `git reset --hard`, `git clean`, `rm` on source files), stop and consider whether there are unsaved changes at risk. If in doubt, `git stash` or `git diff --stat` first.
177+
170178 ## Conventions
171179
172180 - All code is TypeScript with strict mode
README.md+1−1
@@ -81,7 +81,7 @@ cel.viewport(() =>
8181
8282 ```bash
8383 bun install # install dependencies
84-bun test # run tests (230+)
84+bun test # run tests (240+)
8585 bun run check # biome lint
8686 bun run format # prettier check
8787 bun run typecheck # tsc --noEmit
TODO.md+4−2
@@ -12,9 +12,11 @@ Remaining work, known bugs, and planned improvements.
1212
1313 ## Bugs & Spec Violations
1414
15-- 🔧 **Tab key consumed by TextInput when focused** — The spec says Tab is an editing key consumed by TextInput (inserts `\t`). Currently Tab always triggers focus traversal. The spec requires Escape to leave the input first, then Tab to traverse. Fix: skip Tab/Shift+Tab focus traversal when a TextInput is focused.
15+- ✅ **Tab key consumed by TextInput when focused** — Fixed. Tab/Shift+Tab focus traversal is now skipped when a TextInput is focused. Tab inserts `\t` as an editing key. Press Escape first, then Tab to traverse.
1616
17-- 🔧 **Mouse wheel scroll inside TextInput** — `findScrollTarget` correctly identifies TextInput as a scroll target, but `cel.ts` scroll handling only updates containers with `overflow: "scroll"`. It should also update TextInput's framework-managed scroll offset when the mouse wheel targets a TextInput.
17+- ✅ **Mouse wheel scroll inside TextInput** — Fixed. Scroll events targeting a TextInput now update its framework-managed scroll offset directly, instead of requiring `onScroll`/`overflow: "scroll"` container props.
18+
19+- ✅ **Batched mouse events dropped** — Fixed. Real terminals send multiple SGR mouse events in a single stdin data chunk (e.g., 3 scroll events concatenated). The parser expected one event per chunk and silently dropped batched input. Now scans for all events in the chunk and processes each one, with scroll offset accumulation for controlled scroll.
1820
1921 ## API Improvements
2022
examples/simple-scroll.ts+86−0
@@ -0,0 +1,86 @@
1+/**
2+ * Scroll test — a large list inside a scrollable VStack.
3+ * Mouse wheel should scroll the list up/down.
4+ *
5+ * Run: bun run examples/scroll-test.ts
6+ */
7+import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
8+
9+const items = Array.from({ length: 50 }, (_, i) => `Item ${i + 1} — ${fake()}`);
10+
11+function fake(): string {
12+ const words = [
13+ "apple",
14+ "banana",
15+ "cherry",
16+ "dragonfruit",
17+ "elderberry",
18+ "fig",
19+ "grape",
20+ "honeydew",
21+ "kiwi",
22+ "lemon",
23+ "mango",
24+ "nectarine",
25+ "orange",
26+ "papaya",
27+ "quince",
28+ "raspberry",
29+ "strawberry",
30+ "tangerine",
31+ ];
32+ const n = 2 + Math.floor(Math.random() * 4);
33+ return Array.from(
34+ { length: n },
35+ () => words[Math.floor(Math.random() * words.length)],
36+ ).join(" ");
37+}
38+
39+let scrollOffset = 0;
40+
41+cel.init(new ProcessTerminal());
42+cel.viewport(() =>
43+ VStack(
44+ {
45+ height: "100%",
46+ onKeyPress: (key) => {
47+ if (key === "ctrl+q" || key === "ctrl+c") {
48+ cel.stop();
49+ process.exit();
50+ }
51+ },
52+ },
53+ [
54+ HStack({ padding: { x: 1 } }, [
55+ Text("Scroll Test", { bold: true, fgColor: "cyan" }),
56+ VStack({ flex: 1 }, []),
57+ Text(`offset: ${scrollOffset}`, { fgColor: "brightBlack" }),
58+ ]),
59+ Text("─", { repeat: "fill", fgColor: "brightBlack" }),
60+
61+ VStack(
62+ {
63+ flex: 1,
64+ overflow: "scroll",
65+ scrollbar: true,
66+ scrollOffset,
67+ onScroll: (off) => {
68+ scrollOffset = off;
69+ cel.render();
70+ },
71+ },
72+ items.map((item, i) =>
73+ HStack({ padding: { x: 1 } }, [
74+ Text(`${String(i + 1).padStart(3)}.`, { fgColor: "yellow" }),
75+ Text(` ${item}`),
76+ ]),
77+ ),
78+ ),
79+
80+ Text("─", { repeat: "fill", fgColor: "brightBlack" }),
81+ HStack({ padding: { x: 1 } }, [
82+ Text("Mouse wheel to scroll · Ctrl+Q quit", { fgColor: "brightBlack" }),
83+ ]),
84+ ],
85+ ),
86+);
packages/core/src/cel.test.ts+268−0
@@ -203,6 +203,41 @@ describe("cel end-to-end", () => {
203203
204204 expect(scrollOffset).toBe(1);
205205 });
206+
207+ test("batched mouse scroll events are all processed", async () => {
208+ const term = setup(20, 5);
209+ let scrollOffset = 0;
210+ cel.viewport(() =>
211+ VStack(
212+ {
213+ width: 20,
214+ height: 5,
215+ overflow: "scroll",
216+ scrollOffset: scrollOffset,
217+ onScroll: (offset) => {
218+ scrollOffset = offset;
219+ },
220+ },
221+ [
222+ Text("line1"),
223+ Text("line2"),
224+ Text("line3"),
225+ Text("line4"),
226+ Text("line5"),
227+ Text("line6"),
228+ Text("line7"),
229+ Text("line8"),
230+ ],
231+ ),
232+ );
233+ await waitForRender();
234+
235+ // 3 scroll-down events batched in one data chunk (as real terminals do)
236+ term.sendInput("\x1b[<65;4;3M\x1b[<65;4;3M\x1b[<65;4;3M");
237+ await waitForRender();
238+
239+ expect(scrollOffset).toBe(3);
240+ });
206241 });
207242
208243 describe("focus system", () => {
@@ -564,4 +599,237 @@ describe("cel end-to-end", () => {
564599 expect(rootKey).toBe("z");
565600 });
566601 });
602+
603+ describe("TextInput Tab handling", () => {
604+ test("Tab inserts \\t when TextInput is focused", async () => {
605+ const term = setup(20, 5);
606+ let value = "hello";
607+ cel.viewport(() =>
608+ VStack({ width: 20, height: 5 }, [
609+ TextInput({
610+ value,
611+ focused: true,
612+ onChange: (v) => {
613+ value = v;
614+ },
615+ }),
616+ ]),
617+ );
618+ await waitForRender();
619+
620+ // Tab should insert \t, not traverse focus
621+ term.sendInput("\t");
622+ await waitForRender();
623+ expect(value).toBe("hello\t");
624+ });
625+
626+ test("Shift+Tab does not traverse focus when TextInput is focused", async () => {
627+ const term = setup(20, 5);
628+ let value = "hello";
629+ let btnFocused = false;
630+
631+ cel.viewport(() =>
632+ VStack({ width: 20, height: 5 }, [
633+ HStack(
634+ {
635+ onClick: () => {},
636+ focused: btnFocused,
637+ onFocus: () => {
638+ btnFocused = true;
639+ },
640+ },
641+ [Text("Btn")],
642+ ),
643+ TextInput({
644+ value,
645+ focused: true,
646+ onChange: (v) => {
647+ value = v;
648+ },
649+ }),
650+ ]),
651+ );
652+ await waitForRender();
653+
654+ // Shift+Tab should not move focus away from TextInput
655+ term.sendInput("\x1b[Z");
656+ await waitForRender();
657+ expect(btnFocused).toBe(false);
658+ });
659+
660+ test("Tab traverses focus when TextInput is NOT focused", async () => {
661+ const term = setup(20, 5);
662+ let tiFocused = false;
663+
664+ cel.viewport(() =>
665+ VStack({ width: 20, height: 5 }, [
666+ TextInput({
667+ value: "text",
668+ focused: tiFocused,
669+ onChange: () => {},
670+ onFocus: () => {
671+ tiFocused = true;
672+ },
673+ }),
674+ ]),
675+ );
676+ await waitForRender();
677+
678+ // Tab should traverse to the TextInput (it's not focused yet)
679+ term.sendInput("\t");
680+ await waitForRender();
681+ expect(tiFocused).toBe(true);
682+ });
683+
684+ test("Escape then Tab leaves TextInput and traverses", async () => {
685+ const term = setup(20, 5);
686+ let tiFocused = true;
687+ let btnFocused = false;
688+
689+ cel.viewport(() =>
690+ VStack({ width: 20, height: 5 }, [
691+ HStack(
692+ {
693+ onClick: () => {},
694+ focused: btnFocused,
695+ onFocus: () => {
696+ btnFocused = true;
697+ tiFocused = false;
698+ },
699+ },
700+ [Text("Btn")],
701+ ),
702+ TextInput({
703+ value: "text",
704+ focused: tiFocused,
705+ onChange: () => {},
706+ onBlur: () => {
707+ tiFocused = false;
708+ },
709+ }),
710+ ]),
711+ );
712+ await waitForRender();
713+
714+ // Escape to leave TextInput
715+ term.sendInput("\x1b");
716+ await waitForRender();
717+ expect(tiFocused).toBe(false);
718+
719+ // Tab should now traverse to the button
720+ term.sendInput("\t");
721+ await waitForRender();
722+ expect(btnFocused).toBe(true);
723+ });
724+ });
725+
726+ describe("TextInput mouse wheel scroll", () => {
727+ test("mouse wheel scrolls TextInput content", async () => {
728+ const term = setup(20, 3);
729+ let value = "line1\nline2\nline3\nline4\nline5";
730+ // Stable onChange ref so TextInput scroll state persists across re-renders
731+ const onChange = (v: string) => {
732+ value = v;
733+ };
734+
735+ cel.viewport(() =>
736+ VStack({ width: 20, height: 3 }, [
737+ TextInput({
738+ value,
739+ height: 3,
740+ onChange,
741+ }),
742+ ]),
743+ );
744+ await waitForRender();
745+
746+ // Initially line1 should be visible
747+ const buf1 = cel._getBuffer()!;
748+ let row0 = "";
749+ for (let x = 0; x < 5; x++) row0 += buf1.get(x, 0).char;
750+ expect(row0).toBe("line1");
751+
752+ // Scroll down at (5, 1)
753+ term.sendInput("\x1b[<65;6;2M");
754+ await waitForRender();
755+
756+ // After scrolling down, line1 should no longer be at row 0
757+ const buf2 = cel._getBuffer()!;
758+ let row0After = "";
759+ for (let x = 0; x < 5; x++) row0After += buf2.get(x, 0).char;
760+ expect(row0After).toBe("line2");
761+ });
762+
763+ test("mouse wheel scroll up clamps at 0", async () => {
764+ const term = setup(20, 3);
765+ let value = "line1\nline2\nline3\nline4";
766+ const onChange = (v: string) => {
767+ value = v;
768+ };
769+
770+ cel.viewport(() =>
771+ VStack({ width: 20, height: 3 }, [
772+ TextInput({
773+ value,
774+ height: 3,
775+ onChange,
776+ }),
777+ ]),
778+ );
779+ await waitForRender();
780+
781+ // Scroll up (already at top, should clamp to 0)
782+ term.sendInput("\x1b[<64;6;2M");
783+ await waitForRender();
784+
785+ // line1 should still be at row 0
786+ const buf = cel._getBuffer()!;
787+ let row0 = "";
788+ for (let x = 0; x < 5; x++) row0 += buf.get(x, 0).char;
789+ expect(row0).toBe("line1");
790+ });
791+
792+ test("mouse wheel prefers innermost TextInput over outer scrollable", async () => {
793+ const term = setup(20, 3);
794+ let outerScrolled = false;
795+ let value = "line1\nline2\nline3\nline4";
796+ const onChange = (v: string) => {
797+ value = v;
798+ };
799+
800+ cel.viewport(() =>
801+ VStack(
802+ {
803+ width: 20,
804+ height: 3,
805+ overflow: "scroll",
806+ scrollOffset: 0,
807+ onScroll: () => {
808+ outerScrolled = true;
809+ },
810+ },
811+ [
812+ TextInput({
813+ value,
814+ height: 3,
815+ onChange,
816+ }),
817+ ],
818+ ),
819+ );
820+ await waitForRender();
821+
822+ // Scroll down — should target TextInput, not outer VStack
823+ term.sendInput("\x1b[<65;6;2M");
824+ await waitForRender();
825+
826+ expect(outerScrolled).toBe(false);
827+
828+ // Verify TextInput scrolled
829+ const buf = cel._getBuffer()!;
830+ let row0 = "";
831+ for (let x = 0; x < 5; x++) row0 += buf.get(x, 0).char;
832+ expect(row0).toBe("line2");
833+ });
834+ });
567835 });
packages/core/src/cel.ts+84−43
@@ -14,6 +14,7 @@ import {
1414 paint,
1515 getTextInputCursor,
1616 setTextInputCursor,
17+ getTextInputScroll,
1718 setTextInputScroll,
1819 getContainerScroll,
1920 setContainerScroll,
@@ -81,11 +82,28 @@ function doRender(): void {
8182
8283 // --- Input handling ---
8384
85+// Regex for a single SGR mouse event (non-anchored, for scanning batched input)
86+const SGR_MOUSE_RE = /\x1b\[<(\d+);(\d+);(\d+)([Mm])/g;
87+
88+// Tracks accumulated scroll offsets during a batch of mouse events.
89+// Controlled scroll reads scrollOffset from props, which doesn't update until
90+// re-render. Within a single data chunk containing multiple scroll events, we
91+// need to remember the offset we already dispatched via onScroll.
92+let batchScrollOffsets: Map<object, number> | null = null;
93+
8494 function handleInput(data: string): void {
85- // Try to parse as mouse event
86- const mouse = parseMouseEvent(data);
87- if (mouse) {
88- handleMouseEvent(mouse);
95+ // Terminals may batch multiple mouse events into one data chunk.
96+ // Scan for all SGR mouse sequences and handle each one.
97+ SGR_MOUSE_RE.lastIndex = 0;
98+ let match = SGR_MOUSE_RE.exec(data);
99+ if (match) {
100+ batchScrollOffsets = new Map();
101+ while (match) {
102+ const mouse = parseSgrMatch(match);
103+ if (mouse) handleMouseEvent(mouse);
104+ match = SGR_MOUSE_RE.exec(data);
105+ }
106+ batchScrollOffsets = null;
89107 return;
90108 }
91109
@@ -100,11 +118,11 @@ interface MouseEvent {
100118 y: number;
101119 }
102120
103-function parseMouseEvent(data: string): MouseEvent | null {
104- // SGR mouse mode: ESC [ < Cb ; Cx ; Cy M (press) or m (release)
105- const match = data.match(/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/);
106- if (!match) return null;
107-
121+/**
122+ * Parse a single SGR mouse event from a RegExp match.
123+ * Returns a MouseEvent for scroll and click events, null for unhandled buttons.
124+ */
125+function parseSgrMatch(match: RegExpExecArray): MouseEvent | null {
108126 const cb = parseInt(match[1]!, 10);
109127 const x = parseInt(match[2]!, 10) - 1; // 1-indexed → 0-indexed
110128 const y = parseInt(match[3]!, 10) - 1;
@@ -190,19 +208,35 @@ function handleMouseEvent(event: MouseEvent): void {
190208 if (event.type === "scroll-up" || event.type === "scroll-down") {
191209 const target = findScrollTarget(path);
192210 if (target) {
193- const props = target.node.type !== "text" ? target.node.props : null;
194- if (props && "onScroll" in props) {
195- const delta = event.type === "scroll-up" ? -1 : 1;
196- if (props.onScroll) {
197- // Controlled scroll: notify app
198- const offset = (props as any).scrollOffset ?? 0;
199- props.onScroll(Math.max(0, offset + delta));
200- } else {
201- // Uncontrolled scroll: framework manages state
202- const current = getContainerScroll(props);
203- setContainerScroll(props, Math.max(0, current + delta));
204- }
211+ const delta = event.type === "scroll-up" ? -1 : 1;
212+
213+ if (target.node.type === "textinput") {
214+ // TextInput scroll is always framework-managed
215+ const tiProps = target.node.props;
216+ const current = getTextInputScroll(tiProps);
217+ setTextInputScroll(tiProps, Math.max(0, current + delta));
205218 cel.render();
219+ } else {
220+ const props = target.node.type !== "text" ? target.node.props : null;
221+ if (props && "onScroll" in props) {
222+ if (props.onScroll) {
223+ // Controlled scroll: notify app.
224+ // Use batch accumulator if available (multiple events in one chunk),
225+ // otherwise read from props.
226+ const baseOffset =
227+ batchScrollOffsets?.get(props) ??
228+ (props as any).scrollOffset ??
229+ 0;
230+ const newOffset = Math.max(0, baseOffset + delta);
231+ batchScrollOffsets?.set(props, newOffset);
232+ props.onScroll(newOffset);
233+ } else {
234+ // Uncontrolled scroll: framework manages state
235+ const current = getContainerScroll(props);
236+ setContainerScroll(props, Math.max(0, current + delta));
237+ }
238+ cel.render();
239+ }
206240 }
207241 }
208242 return;
@@ -232,33 +266,40 @@ function handleKeyEvent(key: string, rawData?: string): void {
232266 // --- Focus traversal keys ---
233267
234268 // Tab / Shift+Tab: cycle through focusable elements
269+ // Skip focus traversal when a TextInput is focused — Tab is an editing key
270+ // that inserts \t. The user must Escape first, then Tab to traverse.
235271 if (key === "tab" || key === "shift+tab") {
236- const topLayer = currentLayouts[currentLayouts.length - 1];
237- if (!topLayer) return;
238- const focusables = collectFocusable(topLayer);
239- if (focusables.length === 0) return;
272+ const focusedTI = findFocusedTextInput();
273+ if (focusedTI) {
274+ // Fall through to TextInput key routing below
275+ } else {
276+ const topLayer = currentLayouts[currentLayouts.length - 1];
277+ if (!topLayer) return;
278+ const focusables = collectFocusable(topLayer);
279+ if (focusables.length === 0) return;
240280
241- const current = findFocusedElement();
242- let currentIdx = current ? focusables.indexOf(current) : -1;
281+ const current = findFocusedElement();
282+ let currentIdx = current ? focusables.indexOf(current) : -1;
243283
244- // If current not found in focusables list, search by identity
245- if (currentIdx === -1 && current) {
246- currentIdx = focusables.findIndex((f) => f.node === current.node);
247- }
284+ // If current not found in focusables list, search by identity
285+ if (currentIdx === -1 && current) {
286+ currentIdx = focusables.findIndex((f) => f.node === current.node);
287+ }
248288
249- let nextIdx: number;
250- if (key === "tab") {
251- nextIdx = currentIdx === -1 ? 0 : (currentIdx + 1) % focusables.length;
252- } else {
253- nextIdx =
254- currentIdx === -1
255- ? focusables.length - 1
256- : (currentIdx - 1 + focusables.length) % focusables.length;
257- }
289+ let nextIdx: number;
290+ if (key === "tab") {
291+ nextIdx = currentIdx === -1 ? 0 : (currentIdx + 1) % focusables.length;
292+ } else {
293+ nextIdx =
294+ currentIdx === -1
295+ ? focusables.length - 1
296+ : (currentIdx - 1 + focusables.length) % focusables.length;
297+ }
258298
259- changeFocus(focusables[nextIdx]!);
260- cel.render();
261- return;
299+ changeFocus(focusables[nextIdx]!);
300+ cel.render();
301+ return;
302+ } // end: not a focused TextInput
262303 }
263304
264305 // Escape: unfocus current element