xonecas.io
70160
Ce

cel-tui / commit 4736c2d

feat(core): implement focus system with Tab traversal, Escape, Enter, and click focusing

Focus traversal:
- Tab/Shift+Tab cycles through focusable elements (TextInput and
  containers with onClick) in document order, wrapping around
- collectFocusable() provides the ordered list from hit-test.ts

Focus management:
- changeFocus() fires onBlur on current, onFocus on target
- findFocusedElement() finds any focused node (TextInput or container)
- findFocusedInTree() now checks both TextInput and container focused prop

Key handling:
- Escape unfocuses current element (fires onBlur)
- Enter activates focused clickable container (fires onClick)
- Tab/Shift+Tab handled before TextInput key routing

Mouse:
- Clicking a focusable element fires onFocus via findClickFocusTarget()
- Focus change happens before onClick handler

xonecas2026-04-03 4736c2d75c979c23c81e0f604cda8dc338368e97 parent 1896195

3 files changed

TODO.md+5−5
@@ -54,11 +54,11 @@ What's implemented, what's missing, and what needs hardening. Reference `spec.md
5454 - ✅ Key routing to `onKeyPress` handlers
5555 - ✅ TextInput key consumption (editing keys consumed, modifiers bubble)
5656 - 🔧 `onKeyPress` bubbling — currently only checks the root container, should walk up from focused element through all ancestors
57-- ❌ Focus traversal (Tab/Shift+Tab cycling through focusable elements)
58-- ❌ Escape to unfocus
59-- ❌ Enter to activate focused clickable container
60-- ❌ Mouse click focusing (clicking a focusable element should fire `onFocus`)
61-- ❌ `onFocus`/`onBlur` callbacks not fired by framework
57+- ✅ Focus traversal (Tab/Shift+Tab cycling through focusable elements)
58+- ✅ Escape to unfocus
59+- ✅ Enter to activate focused clickable container
60+- ✅ Mouse click focusing (clicking a focusable element fires `onFocus`)
61+- ✅ `onFocus`/`onBlur` callbacks fired by framework
6262
6363 ## Layer Compositing
6464
packages/core/src/cel.test.ts+230−2
@@ -2,8 +2,8 @@ import { afterEach, describe, expect, test } from "bun:test";
22 import { cel } from "./cel.js";
33 import { MockTerminal } from "./terminal.js";
44 import { Text } from "./primitives/text.js";
5-import { VStack } from "./primitives/stacks.js";
6-import { HStack } from "./primitives/stacks.js";
5+import { TextInput } from "./primitives/text-input.js";
6+import { VStack, HStack } from "./primitives/stacks.js";
77
88 describe("cel end-to-end", () => {
99 let term: MockTerminal;
@@ -204,4 +204,232 @@ describe("cel end-to-end", () => {
204204 expect(scrollOffset).toBe(1);
205205 });
206206 });
207+
208+ describe("focus system", () => {
209+ test("Tab moves focus to next focusable element", async () => {
210+ const term = setup(20, 5);
211+ const focused: string[] = [];
212+ let focus1 = false;
213+ let focus2 = false;
214+
215+ cel.viewport(() =>
216+ VStack({ width: 20, height: 5 }, [
217+ HStack(
218+ {
219+ onClick: () => {},
220+ focused: focus1,
221+ onFocus: () => {
222+ focus1 = true;
223+ focus2 = false;
224+ focused.push("btn1");
225+ },
226+ onBlur: () => {
227+ focus1 = false;
228+ },
229+ },
230+ [Text("Btn1")],
231+ ),
232+ HStack(
233+ {
234+ onClick: () => {},
235+ focused: focus2,
236+ onFocus: () => {
237+ focus2 = true;
238+ focus1 = false;
239+ focused.push("btn2");
240+ },
241+ onBlur: () => {
242+ focus2 = false;
243+ },
244+ },
245+ [Text("Btn2")],
246+ ),
247+ ]),
248+ );
249+ await waitForRender();
250+
251+ // Tab to focus first element
252+ term.sendInput("\t");
253+ await waitForRender();
254+ expect(focused).toEqual(["btn1"]);
255+
256+ // Tab to focus second element
257+ term.sendInput("\t");
258+ await waitForRender();
259+ expect(focused).toEqual(["btn1", "btn2"]);
260+ });
261+
262+ test("Shift+Tab moves focus backwards", async () => {
263+ const term = setup(20, 5);
264+ let focus1 = false;
265+ let focus2 = true;
266+ const focused: string[] = [];
267+
268+ cel.viewport(() =>
269+ VStack({ width: 20, height: 5 }, [
270+ HStack(
271+ {
272+ onClick: () => {},
273+ focused: focus1,
274+ onFocus: () => {
275+ focus1 = true;
276+ focus2 = false;
277+ focused.push("btn1");
278+ },
279+ onBlur: () => {
280+ focus1 = false;
281+ },
282+ },
283+ [Text("Btn1")],
284+ ),
285+ HStack(
286+ {
287+ onClick: () => {},
288+ focused: focus2,
289+ onFocus: () => {
290+ focus2 = true;
291+ focus1 = false;
292+ focused.push("btn2");
293+ },
294+ onBlur: () => {
295+ focus2 = false;
296+ },
297+ },
298+ [Text("Btn2")],
299+ ),
300+ ]),
301+ );
302+ await waitForRender();
303+
304+ // Shift+Tab from btn2 should focus btn1
305+ term.sendInput("\x1b[Z");
306+ await waitForRender();
307+ expect(focused).toEqual(["btn1"]);
308+ });
309+
310+ test("Escape unfocuses the current element", async () => {
311+ const term = setup(20, 5);
312+ let blurred = false;
313+ let btnFocused = true;
314+
315+ cel.viewport(() =>
316+ VStack({ width: 20, height: 5 }, [
317+ HStack(
318+ {
319+ onClick: () => {},
320+ focused: btnFocused,
321+ onBlur: () => {
322+ blurred = true;
323+ btnFocused = false;
324+ },
325+ },
326+ [Text("Btn")],
327+ ),
328+ ]),
329+ );
330+ await waitForRender();
331+
332+ term.sendInput("\x1b");
333+ await waitForRender();
334+ expect(blurred).toBe(true);
335+ });
336+
337+ test("Enter activates focused clickable container", async () => {
338+ const term = setup(20, 5);
339+ let clicked = false;
340+
341+ cel.viewport(() =>
342+ VStack({ width: 20, height: 5 }, [
343+ HStack(
344+ {
345+ onClick: () => {
346+ clicked = true;
347+ },
348+ focused: true,
349+ },
350+ [Text("Btn")],
351+ ),
352+ ]),
353+ );
354+ await waitForRender();
355+
356+ term.sendInput("\r");
357+ await waitForRender();
358+ expect(clicked).toBe(true);
359+ });
360+
361+ test("mouse click on focusable element fires onFocus", async () => {
362+ const term = setup(20, 5);
363+ let btnFocused = false;
364+
365+ cel.viewport(() =>
366+ VStack({ width: 20, height: 5 }, [
367+ HStack(
368+ {
369+ onClick: () => {},
370+ focused: btnFocused,
371+ onFocus: () => {
372+ btnFocused = true;
373+ },
374+ },
375+ [Text("Btn")],
376+ ),
377+ ]),
378+ );
379+ await waitForRender();
380+
381+ // Click on the button at (1, 0)
382+ term.sendInput("\x1b[<0;2;1m");
383+ await waitForRender();
384+ expect(btnFocused).toBe(true);
385+ });
386+
387+ test("Tab wraps around to first element", async () => {
388+ const term = setup(20, 5);
389+ let focus1 = false;
390+ let focus2 = true;
391+ const focused: string[] = [];
392+
393+ cel.viewport(() =>
394+ VStack({ width: 20, height: 5 }, [
395+ HStack(
396+ {
397+ onClick: () => {},
398+ focused: focus1,
399+ onFocus: () => {
400+ focus1 = true;
401+ focus2 = false;
402+ focused.push("btn1");
403+ },
404+ onBlur: () => {
405+ focus1 = false;
406+ },
407+ },
408+ [Text("Btn1")],
409+ ),
410+ HStack(
411+ {
412+ onClick: () => {},
413+ focused: focus2,
414+ onFocus: () => {
415+ focus2 = true;
416+ focus1 = false;
417+ focused.push("btn2");
418+ },
419+ onBlur: () => {
420+ focus2 = false;
421+ },
422+ },
423+ [Text("Btn2")],
424+ ),
425+ ]),
426+ );
427+ await waitForRender();
428+
429+ // Tab from btn2 (last) should wrap to btn1
430+ term.sendInput("\t");
431+ await waitForRender();
432+ expect(focused).toEqual(["btn1"]);
433+ });
434+ });
207435 });
packages/core/src/cel.ts+132−2
@@ -120,6 +120,51 @@ function parseMouseEvent(data: string): MouseEvent | null {
120120 return null;
121121 }
122122
123+/**
124+ * Find the currently focused element across all layers.
125+ * Checks both TextInput (focused prop) and containers (focused prop).
126+ */
127+function findFocusedElement(): LayoutNode | null {
128+ for (let i = currentLayouts.length - 1; i >= 0; i--) {
129+ const found = findFocusedInTree(currentLayouts[i]!);
130+ if (found) return found;
131+ }
132+ return null;
133+}
134+
135+/**
136+ * Blur the currently focused element and focus a new one.
137+ */
138+function changeFocus(target: LayoutNode | null): void {
139+ const current = findFocusedElement();
140+
141+ // Blur current
142+ if (current && current !== target) {
143+ const props =
144+ current.node.type === "textinput"
145+ ? current.node.props
146+ : current.node.type !== "text"
147+ ? current.node.props
148+ : null;
149+ if (props && "onBlur" in props && props.onBlur) {
150+ props.onBlur();
151+ }
152+ }
153+
154+ // Focus new target
155+ if (target && target !== current) {
156+ const props =
157+ target.node.type === "textinput"
158+ ? target.node.props
159+ : target.node.type !== "text"
160+ ? target.node.props
161+ : null;
162+ if (props && "onFocus" in props && props.onFocus) {
163+ props.onFocus();
164+ }
165+ }
166+}
167+
123168 function handleMouseEvent(event: MouseEvent): void {
124169 // Hit test on topmost layer first
125170 for (let i = currentLayouts.length - 1; i >= 0; i--) {
@@ -128,12 +173,17 @@ function handleMouseEvent(event: MouseEvent): void {
128173 if (path.length === 0) continue;
129174
130175 if (event.type === "click") {
176+ // Find and focus the focusable element at click position
177+ const focusable = findClickFocusTarget(path);
178+ if (focusable) {
179+ changeFocus(focusable);
180+ }
181+
131182 const click = findClickHandler(path);
132183 if (click) {
133184 click.handler();
134- cel.render();
135185 }
136- // Clicking a focusable element — fire onFocus/onBlur via props
186+ cel.render();
137187 return;
138188 }
139189
@@ -160,7 +210,81 @@ function handleMouseEvent(event: MouseEvent): void {
160210 }
161211 }
162212
213+/**
214+ * Find the nearest focusable element in a hit path (for mouse click focusing).
215+ */
216+function findClickFocusTarget(path: LayoutNode[]): LayoutNode | null {
217+ for (let i = path.length - 1; i >= 0; i--) {
218+ const node = path[i]!.node;
219+ if (node.type === "textinput") return path[i]!;
220+ if (
221+ (node.type === "vstack" || node.type === "hstack") &&
222+ node.props.onClick &&
223+ node.props.focusable !== false
224+ ) {
225+ return path[i]!;
226+ }
227+ }
228+ return null;
229+}
230+
163231 function handleKeyEvent(key: string): void {
232+ // --- Focus traversal keys ---
233+
234+ // Tab / Shift+Tab: cycle through focusable elements
235+ 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;
240+
241+ const current = findFocusedElement();
242+ let currentIdx = current ? focusables.indexOf(current) : -1;
243+
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+ }
248+
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+ }
258+
259+ changeFocus(focusables[nextIdx]!);
260+ cel.render();
261+ return;
262+ }
263+
264+ // Escape: unfocus current element
265+ if (key === "escape") {
266+ const current = findFocusedElement();
267+ if (current) {
268+ changeFocus(null);
269+ cel.render();
270+ return;
271+ }
272+ }
273+
274+ // Enter: activate focused clickable container
275+ if (key === "enter") {
276+ const current = findFocusedElement();
277+ if (current && current.node.type !== "textinput") {
278+ const props = current.node.type !== "text" ? current.node.props : null;
279+ if (props?.onClick) {
280+ props.onClick();
281+ cel.render();
282+ return;
283+ }
284+ }
285+ }
286+
287+ // --- TextInput key routing ---
164288 // Find the focused TextInput (if any) to route editing keys
165289 const focusedInput = findFocusedTextInput();
166290
@@ -251,6 +375,12 @@ function findFocusedInTree(ln: LayoutNode): LayoutNode | null {
251375 if (ln.node.type === "textinput" && ln.node.props.focused) {
252376 return ln;
253377 }
378+ if (
379+ (ln.node.type === "vstack" || ln.node.type === "hstack") &&
380+ ln.node.props.focused
381+ ) {
382+ return ln;
383+ }
254384 for (const child of ln.children) {
255385 const found = findFocusedInTree(child);
256386 if (found) return found;