xonecas.io
70160
Ce

cel-tui / commit ac77a43

feat: style inheritance, container bgColor, uncontrolled focus, focusStyle

- ContainerProps extends StyleProps — containers accept bold, italic,
  underline, fgColor, bgColor. bgColor fills the container rect with
  opaque background cells before painting children.

- Style inheritance — containers propagate styles to descendants.
  Resolution: node's own prop → nearest ancestor → terminal default.

- Uncontrolled focus — framework manages focus internally when the
  focused prop is omitted (mirrors uncontrolled scroll pattern).
  Tab/Shift+Tab/Escape/click just work with no app-side state.
  Controlled focus (explicit focused prop) still supported.

- focusStyle on ContainerProps — StyleProps overrides applied when
  focused. Participates in inheritance so children see focused values.

- Updated spec to reflect all new decisions, removed transient content.

- Pet example rewritten: removed focus state variable and ~60 lines of
  boilerplate. Log modal uses container bgColor instead of 11 manual
  fill workarounds.

- Bump all packages to 0.1.0.

BREAKING CHANGE: ContainerProps now extends StyleProps. TextInputProps
no longer redundantly declares focused/onFocus/onBlur (inherited from
ContainerProps).

xonecas2026-04-04 ac77a4364fd9848713a970ce49b4cd82330acef5 parent f120637

10 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.

examples/pet.ts+83−172
@@ -196,7 +196,7 @@ let screen: Screen = "create";
196196 // -- Creation state --
197197 let petName = "";
198198 let selectedKind = 0;
199-let focused: string | null = "name"; // tracks which element has focus
199+let nameInputFocused = false; // only TextInput needs controlled focus (arrow key routing)
200200
201201 // -- Pet state --
202202 let pet: PetDef | null = null;
@@ -239,7 +239,6 @@ function startGame() {
239239 frame = 0;
240240 log = [];
241241 screen = "main";
242- focused = null;
243242
244243 addLog(`${petName} the ${pet.kind} was born!`);
245244 addLog("Press [F] feed · [P] pet · [L] log");
@@ -304,7 +303,6 @@ function playExcited() {
304303 function die() {
305304 addLog(`${petName} has passed away...`);
306305 screen = "dead";
307- focused = null;
308306 stopTimers();
309307 cel.render();
310308 }
@@ -314,7 +312,6 @@ function restart() {
314312 pet = null;
315313 petName = "";
316314 selectedKind = 0;
317- focused = "name";
318315 screen = "create";
319316 log = [];
320317 showLog = false;
@@ -442,7 +439,7 @@ function createView() {
442439 onKeyPress: (key) => {
443440 if (key === "ctrl+q" || key === "ctrl+c") quit();
444441 // Arrow keys to pick species (only when name input is NOT focused)
445- if (focused !== "name") {
442+ if (!nameInputFocused) {
446443 if (key === "up") {
447444 selectedKind = (selectedKind - 1 + PETS.length) % PETS.length;
448445 cel.render();
@@ -477,18 +474,19 @@ function createView() {
477474 fgColor: "brightBlack",
478475 bgColor: "black",
479476 }),
480- focused: focused === "name",
477+ // Controlled focus: needed to gate arrow key routing above
478+ focused: nameInputFocused,
481479 onFocus: () => {
482- focused = "name";
480+ nameInputFocused = true;
483481 cel.render();
484482 },
485483 onBlur: () => {
486- if (focused === "name") focused = null;
484+ nameInputFocused = false;
487485 cel.render();
488486 },
489487 submitKey: "enter",
490488 onSubmit: () => {
491- focused = null;
489+ nameInputFocused = false;
492490 cel.render();
493491 },
494492 }),
@@ -536,27 +534,15 @@ function createView() {
536534
537535 Divider({ fgColor: "brightBlack" }),
538536
539- // Create button
537+ // Create button — uncontrolled focus + focusStyle
540538 HStack({ justifyContent: "center" }, [
541539 HStack(
542540 {
543541 onClick: startGame,
544- focused: focused === "create",
545- onFocus: () => {
546- focused = "create";
547- cel.render();
548- },
549- onBlur: () => {
550- if (focused === "create") focused = null;
551- cel.render();
552- },
542+ fgColor: "green",
543+ focusStyle: { bgColor: "green", fgColor: "black" },
553544 },
554- [
555- Text(
556- focused === "create" ? ">> Create Pet! <<" : "[ Create Pet! ]",
557- { bold: true, fgColor: "green" },
558- ),
559- ],
545+ [Text(" Create Pet! ", { bold: true })],
560546 ),
561547 ]),
562548
@@ -619,42 +605,18 @@ function mainView() {
619605 HStack(
620606 {
621607 onClick: feed,
622- focused: focused === "feed",
623- onFocus: () => {
624- focused = "feed";
625- cel.render();
626- },
627- onBlur: () => {
628- if (focused === "feed") focused = null;
629- cel.render();
630- },
608+ fgColor: "yellow",
609+ focusStyle: { bgColor: "yellow", fgColor: "black" },
631610 },
632- [
633- Text(focused === "feed" ? ">> Feed <<" : "[ Feed ]", {
634- bold: true,
635- fgColor: "yellow",
636- }),
637- ],
611+ [Text(" Feed ", { bold: true })],
638612 ),
639613 HStack(
640614 {
641615 onClick: petIt,
642- focused: focused === "pet",
643- onFocus: () => {
644- focused = "pet";
645- cel.render();
646- },
647- onBlur: () => {
648- if (focused === "pet") focused = null;
649- cel.render();
650- },
616+ fgColor: "magenta",
617+ focusStyle: { bgColor: "magenta", fgColor: "black" },
651618 },
652- [
653- Text(focused === "pet" ? ">> Pet <<" : "[ Pet ]", {
654- bold: true,
655- fgColor: "magenta",
656- }),
657- ],
619+ [Text(" Pet ", { bold: true })],
658620 ),
659621 ]),
660622 ],
@@ -671,7 +633,6 @@ function mainView() {
671633 showLog = !showLog;
672634 if (showLog) {
673635 logScroll = Math.max(0, log.length - 12);
674- focused = null;
675636 }
676637 cel.render();
677638 }
@@ -716,7 +677,6 @@ function mainView() {
716677
717678 function logView() {
718679 const { cols, rows } = termSize();
719- const bg = "black" as const;
720680 const closeLog = () => {
721681 showLog = false;
722682 cel.render();
@@ -725,7 +685,7 @@ function logView() {
725685 // Adapt modal size to terminal
726686 const modalW = Math.min(60, cols - 4);
727687 const modalH = Math.min(14, rows - 4);
728- const borderW = modalW - 2; // inner repeat count for ═ chars
688+ const borderW = modalW - 2;
729689
730690 return VStack(
731691 {
@@ -738,104 +698,81 @@ function logView() {
738698 },
739699 [
740700 // Top border
741- HStack({}, [
742- Text("╔", { fgColor: "brightBlack", bgColor: bg }),
743- Text("═", { repeat: borderW, fgColor: "brightBlack", bgColor: bg }),
744- Text("╗", { fgColor: "brightBlack", bgColor: bg }),
701+ HStack({ bgColor: "black" }, [
702+ Text("╔", { fgColor: "brightBlack" }),
703+ Text("═", { repeat: borderW, fgColor: "brightBlack" }),
704+ Text("╗", { fgColor: "brightBlack" }),
745705 ]),
746706
747- VStack({ width: modalW, height: modalH, padding: { x: 1 } }, [
748- // Header row
749- HStack({}, [
750- Text(" Activity Log ", { bold: true, fgColor: "cyan", bgColor: bg }),
751- VStack({ flex: 1 }, [Text(" ", { repeat: "fill", bgColor: bg })]),
752- HStack({ onClick: closeLog, focusable: false }, [
753- Text(" [x] ", { fgColor: "red", bold: true, bgColor: bg }),
707+ VStack(
708+ { width: modalW, height: modalH, padding: { x: 1 }, bgColor: "black" },
709+ [
710+ // Header row
711+ HStack({}, [
712+ Text(" Activity Log ", { bold: true, fgColor: "cyan" }),
713+ VStack({ flex: 1 }, [Text(" ", { repeat: "fill" })]),
714+ HStack({ onClick: closeLog, focusable: false }, [
715+ Text(" [x] ", { fgColor: "red", bold: true }),
716+ ]),
754717 ]),
755- ]),
756- Text("─", { repeat: "fill", fgColor: "brightBlack", bgColor: bg }),
718+ Text("─", { repeat: "fill", fgColor: "brightBlack" }),
757719
758- // Scrollable entries
759- VStack(
760- {
761- flex: 1,
762- overflow: "scroll",
763- scrollbar: true,
764- scrollOffset: logScroll,
765- onScroll: (off) => {
766- logScroll = off;
767- cel.render();
720+ // Scrollable entries
721+ VStack(
722+ {
723+ flex: 1,
724+ overflow: "scroll",
725+ scrollbar: true,
726+ scrollOffset: logScroll,
727+ onScroll: (off) => {
728+ logScroll = off;
729+ cel.render();
730+ },
768731 },
769- },
770- (() => {
771- const blank = () =>
772- HStack({}, [
773- VStack({ flex: 1 }, [
774- Text(" ", { repeat: "fill", bgColor: bg }),
775- ]),
776- ]);
777- if (log.length === 0) {
778- return [
779- HStack({}, [
732+ (() => {
733+ if (log.length === 0) {
734+ return [
780735 Text(" No activity yet.", {
781736 fgColor: "brightBlack",
782737 italic: true,
783- bgColor: bg,
784738 }),
785- VStack({ flex: 1 }, [
786- Text(" ", { repeat: "fill", bgColor: bg }),
787- ]),
788- ]),
789- ...Array.from({ length: Math.max(0, modalH - 5) }, blank),
790- ];
791- }
792- const rows = log.map((entry) => {
793- let fg:
794- | "yellow"
795- | "magenta"
796- | "red"
797- | "green"
798- | "white"
799- | "brightRed" = "white";
800- if (entry.includes("born")) fg = "green";
801- else if (entry.includes("fed") || entry.includes("Feed"))
802- fg = "yellow";
803- else if (entry.includes("pet ") || entry.includes("Happy"))
804- fg = "magenta";
805- else if (entry.includes("hungry") || entry.includes("lonely"))
806- fg = "brightRed";
807- else if (entry.includes("passed") || entry.includes("well"))
808- fg = "red";
809- return HStack({}, [
810- Text(entry, { fgColor: fg, bgColor: bg }),
811- VStack({ flex: 1 }, [
812- Text(" ", { repeat: "fill", bgColor: bg }),
813- ]),
814- ]);
815- });
816- // Pad with blank rows so empty space has background
817- const visibleRows = Math.max(0, modalH - 4);
818- const pad = Math.max(0, visibleRows - rows.length);
819- return [...rows, ...Array.from({ length: pad }, blank)];
820- })(),
821- ),
739+ ];
740+ }
741+ return log.map((entry) => {
742+ let fg:
743+ | "yellow"
744+ | "magenta"
745+ | "red"
746+ | "green"
747+ | "white"
748+ | "brightRed" = "white";
749+ if (entry.includes("born")) fg = "green";
750+ else if (entry.includes("fed") || entry.includes("Feed"))
751+ fg = "yellow";
752+ else if (entry.includes("pet ") || entry.includes("Happy"))
753+ fg = "magenta";
754+ else if (entry.includes("hungry") || entry.includes("lonely"))
755+ fg = "brightRed";
756+ else if (entry.includes("passed") || entry.includes("well"))
757+ fg = "red";
758+ return Text(entry, { fgColor: fg });
759+ });
760+ })(),
761+ ),
822762
823- Text("─", { repeat: "fill", fgColor: "brightBlack", bgColor: bg }),
824- HStack({}, [
763+ Text("─", { repeat: "fill", fgColor: "brightBlack" }),
825764 Text(" Scroll: mouse wheel Close: [L] or Esc", {
826765 fgColor: "brightBlack",
827766 italic: true,
828- bgColor: bg,
829767 }),
830- VStack({ flex: 1 }, [Text(" ", { repeat: "fill", bgColor: bg })]),
831- ]),
832- ]),
768+ ],
769+ ),
833770
834771 // Bottom border
835- HStack({}, [
836- Text("╚", { fgColor: "brightBlack", bgColor: bg }),
837- Text("═", { repeat: borderW, fgColor: "brightBlack", bgColor: bg }),
838- Text("╝", { fgColor: "brightBlack", bgColor: bg }),
772+ HStack({ bgColor: "black" }, [
773+ Text("╚", { fgColor: "brightBlack" }),
774+ Text("═", { repeat: borderW, fgColor: "brightBlack" }),
775+ Text("╝", { fgColor: "brightBlack" }),
839776 ]),
840777 ],
841778 );
@@ -854,7 +791,6 @@ function deadView() {
854791 if (key === "ctrl+q" || key === "ctrl+c") quit();
855792 if (key === "l") {
856793 showLog = !showLog;
857- if (showLog) focused = null;
858794 cel.render();
859795 }
860796 },
@@ -878,46 +814,21 @@ function deadView() {
878814 HStack(
879815 {
880816 onClick: restart,
881- focused: focused === "restart",
882- onFocus: () => {
883- focused = "restart";
884- cel.render();
885- },
886- onBlur: () => {
887- if (focused === "restart") focused = null;
888- cel.render();
889- },
817+ fgColor: "green",
818+ focusStyle: { bgColor: "green", fgColor: "black" },
890819 },
891- [
892- Text(focused === "restart" ? ">> New Pet <<" : "[ New Pet ]", {
893- bold: true,
894- fgColor: "green",
895- }),
896- ],
820+ [Text(" New Pet ", { bold: true })],
897821 ),
898822 HStack(
899823 {
900824 onClick: () => {
901825 showLog = !showLog;
902- focused = null;
903- cel.render();
904- },
905- focused: focused === "viewlog",
906- onFocus: () => {
907- focused = "viewlog";
908- cel.render();
909- },
910- onBlur: () => {
911- if (focused === "viewlog") focused = null;
912826 cel.render();
913827 },
828+ fgColor: "cyan",
829+ focusStyle: { bgColor: "cyan", fgColor: "black" },
914830 },
915- [
916- Text(focused === "viewlog" ? ">> View Log <<" : "[ View Log ]", {
917- bold: true,
918- fgColor: "cyan",
919- }),
920- ],
831+ [Text(" View Log ", { bold: true })],
921832 ),
922833 ]),
923834 HStack({}, [
packages/components/package.json+1−1
@@ -1,6 +1,6 @@
11 {
22 "name": "@cel-tui/components",
3- "version": "0.0.1",
3+ "version": "0.1.0",
44 "type": "module",
55 "main": "src/index.ts",
66 "types": "src/index.ts",
packages/core/package.json+1−1
@@ -1,6 +1,6 @@
11 {
22 "name": "@cel-tui/core",
3- "version": "0.0.1",
3+ "version": "0.1.0",
44 "type": "module",
55 "main": "src/index.ts",
66 "types": "src/index.ts",
packages/core/src/cel.test.ts+430−0
@@ -975,4 +975,434 @@ describe("cel end-to-end", () => {
975975 expect(row0).toBe("line2");
976976 });
977977 });
978+
979+ describe("uncontrolled focus", () => {
980+ test("Tab focuses first clickable element and Enter activates it", async () => {
981+ const term = setup(20, 5);
982+ let clicked = false;
983+
984+ cel.viewport(() =>
985+ VStack({ width: 20, height: 5 }, [
986+ HStack(
987+ {
988+ onClick: () => {
989+ clicked = true;
990+ },
991+ },
992+ [Text("Btn")],
993+ ),
994+ ]),
995+ );
996+ await waitForRender();
997+
998+ // Tab to focus the button
999+ term.sendInput("\t");
1000+ await waitForRender();
1001+
1002+ // Enter to activate
1003+ term.sendInput("\r");
1004+ await waitForRender();
1005+
1006+ expect(clicked).toBe(true);
1007+ });
1008+
1009+ test("Tab cycles through focusable elements in order", async () => {
1010+ const term = setup(20, 5);
1011+ const clicks: string[] = [];
1012+
1013+ cel.viewport(() =>
1014+ VStack({ width: 20, height: 5 }, [
1015+ HStack({ onClick: () => clicks.push("btn1") }, [Text("Btn1")]),
1016+ HStack({ onClick: () => clicks.push("btn2") }, [Text("Btn2")]),
1017+ ]),
1018+ );
1019+ await waitForRender();
1020+
1021+ // Tab to first, activate
1022+ term.sendInput("\t");
1023+ await waitForRender();
1024+ term.sendInput("\r");
1025+ await waitForRender();
1026+ expect(clicks).toEqual(["btn1"]);
1027+
1028+ // Tab to second, activate
1029+ term.sendInput("\t");
1030+ await waitForRender();
1031+ term.sendInput("\r");
1032+ await waitForRender();
1033+ expect(clicks).toEqual(["btn1", "btn2"]);
1034+ });
1035+
1036+ test("Shift+Tab moves focus backwards", async () => {
1037+ const term = setup(20, 5);
1038+ const clicks: string[] = [];
1039+
1040+ cel.viewport(() =>
1041+ VStack({ width: 20, height: 5 }, [
1042+ HStack({ onClick: () => clicks.push("btn1") }, [Text("Btn1")]),
1043+ HStack({ onClick: () => clicks.push("btn2") }, [Text("Btn2")]),
1044+ ]),
1045+ );
1046+ await waitForRender();
1047+
1048+ // Shift+Tab to focus last element
1049+ term.sendInput("\x1b[Z");
1050+ await waitForRender();
1051+ term.sendInput("\r");
1052+ await waitForRender();
1053+ expect(clicks).toEqual(["btn2"]);
1054+
1055+ // Shift+Tab to go backward to first
1056+ term.sendInput("\x1b[Z");
1057+ await waitForRender();
1058+ term.sendInput("\r");
1059+ await waitForRender();
1060+ expect(clicks).toEqual(["btn2", "btn1"]);
1061+ });
1062+
1063+ test("Escape unfocuses and Enter does nothing", async () => {
1064+ const term = setup(20, 5);
1065+ let clicked = false;
1066+
1067+ cel.viewport(() =>
1068+ VStack({ width: 20, height: 5 }, [
1069+ HStack(
1070+ {
1071+ onClick: () => {
1072+ clicked = true;
1073+ },
1074+ },
1075+ [Text("Btn")],
1076+ ),
1077+ ]),
1078+ );
1079+ await waitForRender();
1080+
1081+ // Tab to focus, then Escape to unfocus
1082+ term.sendInput("\t");
1083+ await waitForRender();
1084+ term.sendInput("\x1b");
1085+ await waitForRender();
1086+
1087+ // Enter should do nothing — no element is focused
1088+ term.sendInput("\r");
1089+ await waitForRender();
1090+ expect(clicked).toBe(false);
1091+ });
1092+
1093+ test("mouse click focuses element and Enter activates it", async () => {
1094+ const term = setup(20, 5);
1095+ let clicked = false;
1096+
1097+ cel.viewport(() =>
1098+ VStack({ width: 20, height: 5 }, [
1099+ HStack({}, [Text("not clickable")]),
1100+ HStack(
1101+ {
1102+ onClick: () => {
1103+ clicked = true;
1104+ },
1105+ },
1106+ [Text("Clickable")],
1107+ ),
1108+ ]),
1109+ );
1110+ await waitForRender();
1111+
1112+ // Click on the second element (row 1)
1113+ term.sendInput("\x1b[<0;2;2m");
1114+ await waitForRender();
1115+
1116+ // Enter should activate the clicked element
1117+ term.sendInput("\r");
1118+ await waitForRender();
1119+ expect(clicked).toBe(true);
1120+ });
1121+
1122+ test("onFocus fires as notification in uncontrolled mode", async () => {
1123+ const term = setup(20, 5);
1124+ const events: string[] = [];
1125+
1126+ cel.viewport(() =>
1127+ VStack({ width: 20, height: 5 }, [
1128+ HStack(
1129+ {
1130+ onClick: () => {},
1131+ onFocus: () => events.push("focus"),
1132+ },
1133+ [Text("Btn")],
1134+ ),
1135+ ]),
1136+ );
1137+ await waitForRender();
1138+
1139+ term.sendInput("\t");
1140+ await waitForRender();
1141+ expect(events).toEqual(["focus"]);
1142+ });
1143+
1144+ test("onBlur fires as notification in uncontrolled mode", async () => {
1145+ const term = setup(20, 5);
1146+ const events: string[] = [];
1147+
1148+ cel.viewport(() =>
1149+ VStack({ width: 20, height: 5 }, [
1150+ HStack(
1151+ {
1152+ onClick: () => {},
1153+ onFocus: () => events.push("focus1"),
1154+ onBlur: () => events.push("blur1"),
1155+ },
1156+ [Text("Btn1")],
1157+ ),
1158+ HStack(
1159+ {
1160+ onClick: () => {},
1161+ onFocus: () => events.push("focus2"),
1162+ },
1163+ [Text("Btn2")],
1164+ ),
1165+ ]),
1166+ );
1167+ await waitForRender();
1168+
1169+ // Tab to first
1170+ term.sendInput("\t");
1171+ await waitForRender();
1172+ expect(events).toEqual(["focus1"]);
1173+
1174+ // Tab to second — first should get onBlur
1175+ term.sendInput("\t");
1176+ await waitForRender();
1177+ expect(events).toEqual(["focus1", "blur1", "focus2"]);
1178+ });
1179+
1180+ test("Tab focuses uncontrolled TextInput and typing works", async () => {
1181+ const term = setup(20, 5);
1182+ let value = "";
1183+
1184+ cel.viewport(() =>
1185+ VStack({ width: 20, height: 5 }, [
1186+ TextInput({
1187+ value,
1188+ onChange: (v) => {
1189+ value = v;
1190+ },
1191+ }),
1192+ ]),
1193+ );
1194+ await waitForRender();
1195+
1196+ // Tab to focus the TextInput
1197+ term.sendInput("\t");
1198+ await waitForRender();
1199+
1200+ // Type a character
1201+ term.sendInput("x");
1202+ await waitForRender();
1203+ expect(value).toBe("x");
1204+ });
1205+
1206+ test("Tab wraps from last to first element", async () => {
1207+ const term = setup(20, 5);
1208+ const clicks: string[] = [];
1209+
1210+ cel.viewport(() =>
1211+ VStack({ width: 20, height: 5 }, [
1212+ HStack({ onClick: () => clicks.push("btn1") }, [Text("Btn1")]),
1213+ HStack({ onClick: () => clicks.push("btn2") }, [Text("Btn2")]),
1214+ ]),
1215+ );
1216+ await waitForRender();
1217+
1218+ // Tab to first, Tab to second, Tab wraps to first
1219+ term.sendInput("\t");
1220+ await waitForRender();
1221+ term.sendInput("\t");
1222+ await waitForRender();
1223+ term.sendInput("\t");
1224+ await waitForRender();
1225+ term.sendInput("\r");
1226+ await waitForRender();
1227+ expect(clicks).toEqual(["btn1"]);
1228+ });
1229+
1230+ test("mixed controlled and uncontrolled elements", async () => {
1231+ const term = setup(20, 5);
1232+ const clicks: string[] = [];
1233+ let controlledFocused = false;
1234+
1235+ cel.viewport(() =>
1236+ VStack({ width: 20, height: 5 }, [
1237+ HStack(
1238+ {
1239+ onClick: () => clicks.push("controlled"),
1240+ focused: controlledFocused,
1241+ onFocus: () => {
1242+ controlledFocused = true;
1243+ },
1244+ onBlur: () => {
1245+ controlledFocused = false;
1246+ },
1247+ },
1248+ [Text("Controlled")],
1249+ ),
1250+ HStack({ onClick: () => clicks.push("uncontrolled") }, [
1251+ Text("Uncontrolled"),
1252+ ]),
1253+ ]),
1254+ );
1255+ await waitForRender();
1256+
1257+ // Tab to first (controlled)
1258+ term.sendInput("\t");
1259+ await waitForRender();
1260+ expect(controlledFocused).toBe(true);
1261+
1262+ // Tab to second (uncontrolled), Enter to activate
1263+ term.sendInput("\t");
1264+ await waitForRender();
1265+ expect(controlledFocused).toBe(false);
1266+ term.sendInput("\r");
1267+ await waitForRender();
1268+ expect(clicks).toEqual(["uncontrolled"]);
1269+ });
1270+ });
1271+
1272+ describe("focusStyle rendering", () => {
1273+ test("focusStyle bgColor applied when element is focused via Tab", async () => {
1274+ const term = setup(20, 3);
1275+
1276+ cel.viewport(() =>
1277+ VStack({ width: 20, height: 3 }, [
1278+ HStack(
1279+ {
1280+ onClick: () => {},
1281+ bgColor: "black",
1282+ focusStyle: { bgColor: "cyan" },
1283+ },
1284+ [Text("Btn")],
1285+ ),
1286+ ]),
1287+ );
1288+ await waitForRender();
1289+
1290+ // Before focus — normal bgColor
1291+ let buf = cel._getBuffer()!;
1292+ expect(buf.get(0, 0).bgColor).toBe("black");
1293+
1294+ // Tab to focus
1295+ term.sendInput("\t");
1296+ await waitForRender();
1297+
1298+ // After focus — focusStyle bgColor
1299+ buf = cel._getBuffer()!;
1300+ expect(buf.get(0, 0).bgColor).toBe("cyan");
1301+ });
1302+
1303+ test("focusStyle removed when focus moves to another element", async () => {
1304+ const term = setup(20, 3);
1305+
1306+ cel.viewport(() =>
1307+ VStack({ width: 20, height: 3 }, [
1308+ HStack(
1309+ {
1310+ onClick: () => {},
1311+ bgColor: "black",
1312+ focusStyle: { bgColor: "cyan" },
1313+ },
1314+ [Text("Btn1")],
1315+ ),
1316+ HStack(
1317+ {
1318+ onClick: () => {},
1319+ bgColor: "black",
1320+ focusStyle: { bgColor: "yellow" },
1321+ },
1322+ [Text("Btn2")],
1323+ ),
1324+ ]),
1325+ );
1326+ await waitForRender();
1327+
1328+ // Tab to first
1329+ term.sendInput("\t");
1330+ await waitForRender();
1331+ let buf = cel._getBuffer()!;
1332+ expect(buf.get(0, 0).bgColor).toBe("cyan");
1333+ expect(buf.get(0, 1).bgColor).toBe("black");
1334+
1335+ // Tab to second — first loses focusStyle, second gains it
1336+ term.sendInput("\t");
1337+ await waitForRender();
1338+ buf = cel._getBuffer()!;
1339+ expect(buf.get(0, 0).bgColor).toBe("black");
1340+ expect(buf.get(0, 1).bgColor).toBe("yellow");
1341+ });
1342+
1343+ test("focusStyle fgColor inherited by child Text when focused", async () => {
1344+ const term = setup(20, 3);
1345+
1346+ cel.viewport(() =>
1347+ VStack({ width: 20, height: 3 }, [
1348+ HStack(
1349+ {
1350+ onClick: () => {},
1351+ fgColor: "white",
1352+ focusStyle: { fgColor: "black", bgColor: "cyan" },
1353+ },
1354+ [Text("Btn")],
1355+ ),
1356+ ]),
1357+ );
1358+ await waitForRender();
1359+
1360+ // Before focus — Text inherits white
1361+ let buf = cel._getBuffer()!;
1362+ expect(buf.get(0, 0).fgColor).toBe("white");
1363+
1364+ // Tab to focus
1365+ term.sendInput("\t");
1366+ await waitForRender();
1367+
1368+ // After focus — Text inherits black from focusStyle
1369+ buf = cel._getBuffer()!;
1370+ expect(buf.get(0, 0).fgColor).toBe("black");
1371+ });
1372+
1373+ test("focusStyle with controlled focus", async () => {
1374+ const term = setup(20, 3);
1375+ let isFocused = true;
1376+
1377+ cel.viewport(() =>
1378+ VStack({ width: 20, height: 3 }, [
1379+ HStack(
1380+ {
1381+ onClick: () => {},
1382+ focused: isFocused,
1383+ bgColor: "black",
1384+ focusStyle: { bgColor: "cyan" },
1385+ onBlur: () => {
1386+ isFocused = false;
1387+ },
1388+ },
1389+ [Text("Btn")],
1390+ ),
1391+ ]),
1392+ );
1393+ await waitForRender();
1394+
1395+ // Controlled focused=true — focusStyle applies
1396+ let buf = cel._getBuffer()!;
1397+ expect(buf.get(0, 0).bgColor).toBe("cyan");
1398+
1399+ // Escape to blur
1400+ term.sendInput("\x1b");
1401+ await waitForRender();
1402+
1403+ // focused=false — normal style
1404+ buf = cel._getBuffer()!;
1405+ expect(buf.get(0, 0).bgColor).toBe("black");
1406+ });
1407+ });
9781408 });
packages/core/src/cel.ts+120−18
@@ -39,6 +39,16 @@ let currentBuffer: CellBuffer | null = null;
3939 let currentLayouts: LayoutNode[] = [];
4040 let lastFocusedIndex = -1;
4141
42+/**
43+ * Framework-tracked focus index for uncontrolled focus.
44+ * Points into the `collectFocusable()` list of the topmost layer.
45+ * -1 means no uncontrolled element is focused.
46+ */
47+let frameworkFocusIndex = -1;
48+
49+/** The node whose props were stamped with `focused: true` during the last paint. */
50+let stampedNode: LayoutNode | null = null;
51+
4252 function doRender(): void {
4353 renderScheduled = false;
4454 if (!renderFn || !terminal) return;
@@ -64,14 +74,24 @@ function doRender(): void {
6474 const tree = renderFn();
6575 const layers = Array.isArray(tree) ? tree : [tree];
6676
67- // Layout and paint each layer into the buffer
77+ // Layout each layer
6878 currentLayouts = [];
6979 for (const layer of layers) {
7080 const layoutTree = layout(layer, width, height);
7181 currentLayouts.push(layoutTree);
82+ }
83+
84+ // Stamp uncontrolled focus before painting so focusStyle and cursor work
85+ stampUncontrolledFocus();
86+
87+ // Paint each layer into the buffer
88+ for (const layoutTree of currentLayouts) {
7289 paint(layoutTree, currentBuffer);
7390 }
7491
92+ // Unstamp after paint so input handlers see clean props
93+ unstampUncontrolledFocus();
94+
7595 // Emit to terminal — differential when possible
7696 if (prevBuffer) {
7797 const output = emitDiff(prevBuffer, currentBuffer);
@@ -140,20 +160,102 @@ function parseSgrMatch(match: RegExpExecArray): MouseEvent | null {
140160 return null;
141161 }
142162
163+/**
164+ * Check if a focusable element uses controlled focus (explicit `focused` prop).
165+ */
166+function isControlledFocus(ln: LayoutNode): boolean {
167+ const node = ln.node;
168+ if (node.type === "textinput") return node.props.focused !== undefined;
169+ if (node.type === "vstack" || node.type === "hstack")
170+ return node.props.focused !== undefined;
171+ return false;
172+}
173+
143174 /**
144175 * Find the currently focused element across all layers.
145- * Checks both TextInput (focused prop) and containers (focused prop).
176+ * Checks controlled focus (`focused: true` in props) first,
177+ * then falls back to framework-tracked uncontrolled focus.
146178 */
147179 function findFocusedElement(): LayoutNode | null {
180+ // Controlled: scan tree for focused: true
148181 for (let i = currentLayouts.length - 1; i >= 0; i--) {
149182 const found = findFocusedInTree(currentLayouts[i]!);
150183 if (found) return found;
151184 }
185+ // Uncontrolled: check framework-tracked index
186+ if (frameworkFocusIndex >= 0) {
187+ const topLayer = currentLayouts[currentLayouts.length - 1];
188+ if (topLayer) {
189+ const focusables = collectFocusable(topLayer);
190+ if (frameworkFocusIndex < focusables.length) {
191+ return focusables[frameworkFocusIndex]!;
192+ }
193+ }
194+ // Index out of bounds (tree changed) — clear
195+ frameworkFocusIndex = -1;
196+ }
152197 return null;
153198 }
154199
200+/**
201+ * Stamp `focused: true` on the framework-tracked focused node's props
202+ * before painting, so that paint/focusStyle/cursor rendering picks it up.
203+ * Only stamps if no controlled element is already focused.
204+ * Must be followed by {@link unstampUncontrolledFocus} after paint.
205+ */
206+function stampUncontrolledFocus(): void {
207+ stampedNode = null;
208+ if (frameworkFocusIndex < 0) return;
209+
210+ // Don't stamp if a controlled element owns focus
211+ for (let i = currentLayouts.length - 1; i >= 0; i--) {
212+ if (findFocusedInTree(currentLayouts[i]!)) {
213+ frameworkFocusIndex = -1;
214+ return;
215+ }
216+ }
217+
218+ const topLayer = currentLayouts[currentLayouts.length - 1];
219+ if (!topLayer) return;
220+ const focusables = collectFocusable(topLayer);
221+ if (frameworkFocusIndex >= focusables.length) {
222+ frameworkFocusIndex = -1;
223+ return;
224+ }
225+ const target = focusables[frameworkFocusIndex]!;
226+ const node = target.node;
227+ if (
228+ node.type === "textinput" ||
229+ node.type === "vstack" ||
230+ node.type === "hstack"
231+ ) {
232+ (node.props as any).focused = true;
233+ stampedNode = target;
234+ }
235+}
236+
237+/**
238+ * Remove the `focused: true` stamp set by {@link stampUncontrolledFocus}.
239+ * Called after paint so input handlers see the original props and can
240+ * correctly distinguish controlled from uncontrolled elements.
241+ */
242+function unstampUncontrolledFocus(): void {
243+ if (!stampedNode) return;
244+ const node = stampedNode.node;
245+ if (
246+ node.type === "textinput" ||
247+ node.type === "vstack" ||
248+ node.type === "hstack"
249+ ) {
250+ delete (node.props as any).focused;
251+ }
252+ stampedNode = null;
253+}
254+
155255 /**
156256 * Blur the currently focused element and focus a new one.
257+ * Manages both controlled (via onFocus/onBlur callbacks) and
258+ * uncontrolled (via frameworkFocusIndex) focus.
157259 */
158260 function changeFocus(target: LayoutNode | null): void {
159261 const current = findFocusedElement();
@@ -168,6 +270,8 @@ function changeFocus(target: LayoutNode | null): void {
168270 idx = focusables.findIndex((f) => f.node === current.node);
169271 lastFocusedIndex = idx;
170272 }
273+ // Always clear framework tracking on blur
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+301−0
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.ts+119−11
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+37−21
Cut short: this commit's diff is over 1000 lines.
spec.md+150−58
Cut short: this commit's diff is over 1000 lines.