xonecas.io
70160
Ce

cel-tui / commit edf13b5

feat(core): implement flexWrap: "wrap" for HStack

Add flexWrap?: "nowrap" | "wrap" to ContainerProps. When set to
"wrap", HStack children that exceed the container width flow to
the next row, like CSS flex-wrap: wrap.

Layout engine changes:
- assignWrapRows() groups children into rows by accumulated width
- layoutWrapHStack() lays out each row as an independent flex
  context with its own flex distribution, justifyContent, and
  alignItems
- intrinsicMainSize() computes wrap-aware height (sum of row
  heights + gaps) for wrapping HStacks
- Flex children use minWidth for row assignment (like flex-basis)
- Gap applies between items within a row and between rows

New example: examples/tags.ts — a tag cloud / chip picker that
showcases wrapping and dynamic reflow on terminal resize.

Updated examples/pet.ts — species picker converted from vertical
list to horizontal wrapping chips.

25 layout tests + 4 paint tests covering: basic wrap, row height,
gap, flex distribution per row, padding, alignItems (stretch/
center/end), justifyContent (center/end/space-between), intrinsic
height, nested wrapping, constraints, and VStack ignoring flexWrap.

xonecas2026-04-04 edf13b52e30265de2f0827388c67fa9b2bad82bb parent a750598

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

TODO.md+1−3
@@ -30,9 +30,7 @@ Remaining work, known bugs, and planned improvements.
3030
3131 - ❌ Bracketed paste mode support
3232
33-- ❌ **`flexWrap: "wrap"` for HStack** — Add `flexWrap?: "nowrap" | "wrap"` to `ContainerProps`. When set to `"wrap"`, children that exceed the container width flow to the next line (like CSS `flex-wrap: wrap`). This is a general layout feature useful for tags, chips, and inline elements — but the primary motivation is enabling Markdown inline styling.
34-
35-- ❌ **Markdown inline styling** — The `Markdown` component strips inline formatting (`**bold**`, `*italic*`, `` `code` ``, `[links](url)`) to plain text. With `flexWrap: "wrap"` on HStack, the component can split inline spans at word boundaries into individual `Text` nodes and wrap them in `HStack({ flexWrap: "wrap" })`. The framework handles line wrapping; the component handles word splitting. Depends on `flexWrap` above.
33+- ❌ **Markdown inline styling** — The `Markdown` component strips inline formatting (`**bold**`, `*italic*`, `` `code` ``, `[links](url)`) to plain text. With `flexWrap: "wrap"` on HStack (now implemented), the component can split inline spans at word boundaries into individual `Text` nodes and wrap them in `HStack({ flexWrap: "wrap" })`. The framework handles line wrapping; the component handles word splitting.
3634
3735 ## Future Enhancements
3836
examples/pet.ts+33−29
@@ -491,32 +491,32 @@ function createView() {
491491 },
492492 }),
493493
494- // Species picker
494+ // Species picker — wrapping chips
495495 Text(""),
496496 Text("Species:", { bold: true, fgColor: "white" }),
497- ...PETS.map((p, i) => {
498- const sel = i === selectedKind;
499- return HStack(
500- {
501- onClick: () => {
502- selectedKind = i;
503- cel.render();
497+ HStack(
498+ { flexWrap: "wrap", gap: 1 },
499+ PETS.map((p, i) => {
500+ const sel = i === selectedKind;
501+ return HStack(
502+ {
503+ onClick: () => {
504+ selectedKind = i;
505+ cel.render();
506+ },
507+ focusable: false,
504508 },
505- focusable: false,
506- },
507- [
508- Text(sel ? " > " : " ", {
509- fgColor: sel ? "cyan" : "brightBlack",
510- bold: sel,
511- }),
512- Text(p.kind, {
513- fgColor: sel ? "cyan" : "white",
514- bold: sel,
515- }),
516- ],
517- );
518- }),
519- Text(" ↑/↓ to change", {
509+ [
510+ Text(sel ? ` ● ${p.kind} ` : ` ${p.kind} `, {
511+ fgColor: sel ? "black" : "white",
512+ bgColor: sel ? "cyan" : undefined,
513+ bold: sel,
514+ }),
515+ ],
516+ );
517+ }),
518+ ),
519+ Text(" ↑/↓ to change", {
520520 fgColor: "brightBlack",
521521 italic: true,
522522 }),
@@ -544,12 +544,16 @@ function createView() {
544544 }),
545545 ]),
546546
547- // Hints
548- HStack({ justifyContent: "center" }, [
549- Text("Tab", { fgColor: "brightBlack", bold: true }),
550- Text(" navigate ", { fgColor: "brightBlack" }),
551- Text("Ctrl+Q", { fgColor: "brightBlack", bold: true }),
552- Text(" quit", { fgColor: "brightBlack" }),
547+ // Hints — wrapping for narrow terminals
548+ HStack({ justifyContent: "center", flexWrap: "wrap", gap: 1 }, [
549+ HStack({}, [
550+ Text("Tab", { fgColor: "brightBlack", bold: true }),
551+ Text(" navigate", { fgColor: "brightBlack" }),
552+ ]),
553+ HStack({}, [
554+ Text("Ctrl+Q", { fgColor: "brightBlack", bold: true }),
555+ Text(" quit", { fgColor: "brightBlack" }),
556+ ]),
553557 ]),
554558 ]),
555559 Spacer(),
examples/tags.ts+189−0
@@ -0,0 +1,189 @@
1+/**
2+ * cel-tui: Tag Cloud
3+ *
4+ * Demonstrates `flexWrap: "wrap"` on HStack — tags flow
5+ * left-to-right and wrap to the next line when they exceed
6+ * the terminal width. Resize the terminal to see tags reflow.
7+ *
8+ * Click or press Enter to toggle tags. Tab/Shift+Tab to
9+ * navigate. Ctrl+Q to quit.
10+ *
11+ * Run: bun run examples/tags.ts
12+ */
13+
14+import { cel, VStack, HStack, Text, ProcessTerminal } from "@cel-tui/core";
15+import { Button, Divider, Spacer } from "@cel-tui/components";
16+
17+// ─── Data ───────────────────────────────────────────────────────
18+
19+interface Tag {
20+ label: string;
21+ color: "cyan" | "magenta" | "yellow" | "green" | "blue" | "red";
22+}
23+
24+const TAGS: Tag[] = [
25+ { label: "TypeScript", color: "blue" },
26+ { label: "Rust", color: "red" },
27+ { label: "Go", color: "cyan" },
28+ { label: "Python", color: "yellow" },
29+ { label: "JavaScript", color: "yellow" },
30+ { label: "C++", color: "blue" },
31+ { label: "Zig", color: "magenta" },
32+ { label: "Haskell", color: "magenta" },
33+ { label: "Elixir", color: "magenta" },
34+ { label: "Ruby", color: "red" },
35+ { label: "Kotlin", color: "green" },
36+ { label: "Swift", color: "red" },
37+ { label: "Lua", color: "blue" },
38+ { label: "OCaml", color: "yellow" },
39+ { label: "Clojure", color: "green" },
40+ { label: "Scala", color: "red" },
41+ { label: "Nim", color: "yellow" },
42+ { label: "Julia", color: "green" },
43+ { label: "Erlang", color: "red" },
44+ { label: "Dart", color: "cyan" },
45+ { label: "C#", color: "green" },
46+ { label: "F#", color: "cyan" },
47+ { label: "Gleam", color: "magenta" },
48+ { label: "Odin", color: "blue" },
49+];
50+
51+// ─── State ──────────────────────────────────────────────────────
52+
53+const selected = new Set<string>();
54+
55+function toggle(label: string) {
56+ if (selected.has(label)) selected.delete(label);
57+ else selected.add(label);
58+ cel.render();
59+}
60+
61+function clearAll() {
62+ selected.clear();
63+ cel.render();
64+}
65+
66+function quit() {
67+ cel.stop();
68+ process.exit();
69+}
70+
71+// ─── UI ─────────────────────────────────────────────────────────
72+
73+function tagChip(tag: Tag) {
74+ const on = selected.has(tag.label);
75+ const check = on ? "✓ " : " ";
76+ return Button(` ${check}${tag.label} `, {
77+ onClick: () => toggle(tag.label),
78+ fgColor: on ? "black" : tag.color,
79+ bgColor: on ? tag.color : undefined,
80+ bold: on,
81+ focusStyle: {
82+ fgColor: "black",
83+ bgColor: tag.color,
84+ bold: true,
85+ },
86+ });
87+}
88+
89+cel.init(new ProcessTerminal());
90+
91+cel.viewport(() => {
92+ const cols = process.stdout.columns || 80;
93+ const selTags = TAGS.filter((t) => selected.has(t.label));
94+
95+ return VStack(
96+ {
97+ height: "100%",
98+ padding: { x: 2, y: 1 },
99+ fgColor: "white",
100+ onKeyPress: (key) => {
101+ if (key === "ctrl+q" || key === "ctrl+c") quit();
102+ if (key === "ctrl+r") clearAll();
103+ },
104+ },
105+ [
106+ // Header
107+ HStack({ gap: 1 }, [
108+ Text("◆", { fgColor: "cyan", bold: true }),
109+ Text("Pick your languages", { bold: true, fgColor: "white" }),
110+ Text(`(${selected.size}/${TAGS.length})`, {
111+ fgColor: "brightBlack",
112+ }),
113+ ]),
114+ Text("Tab navigate · Enter toggle · resize to reflow", {
115+ fgColor: "brightBlack",
116+ italic: true,
117+ }),
118+ Divider({ fgColor: "brightBlack" }),
119+
120+ // Tag cloud — the flexWrap showcase
121+ HStack(
122+ { flexWrap: "wrap", gap: 1, padding: { y: 1 } },
123+ TAGS.map(tagChip),
124+ ),
125+
126+ Divider({ fgColor: "brightBlack" }),
127+
128+ // Selection summary
129+ ...(selTags.length > 0
130+ ? [
131+ Text("Selected:", { bold: true, fgColor: "brightBlack" }),
132+ HStack(
133+ { flexWrap: "wrap", gap: 1 },
134+ selTags.map((t) =>
135+ Text(` ${t.label} `, {
136+ fgColor: "black",
137+ bgColor: t.color,
138+ bold: true,
139+ }),
140+ ),
141+ ),
142+ ]
143+ : [
144+ Text("No languages selected yet.", {
145+ fgColor: "brightBlack",
146+ italic: true,
147+ }),
148+ ]),
149+
150+ Spacer(),
151+
152+ // Footer hints — also wrapping
153+ HStack({ flexWrap: "wrap", gap: 1 }, [
154+ HStack({ gap: 0 }, [
155+ Text(" Tab ", {
156+ bgColor: "brightBlack",
157+ fgColor: "black",
158+ bold: true,
159+ }),
160+ Text(" navigate", { fgColor: "brightBlack" }),
161+ ]),
162+ HStack({ gap: 0 }, [
163+ Text(" Enter ", {
164+ bgColor: "brightBlack",
165+ fgColor: "black",
166+ bold: true,
167+ }),
168+ Text(" toggle", { fgColor: "brightBlack" }),
169+ ]),
170+ HStack({ gap: 0 }, [
171+ Text(" Ctrl+R ", {
172+ bgColor: "brightBlack",
173+ fgColor: "black",
174+ bold: true,
175+ }),
176+ Text(" clear", { fgColor: "brightBlack" }),
177+ ]),
178+ HStack({ gap: 0 }, [
179+ Text(" Ctrl+Q ", {
180+ bgColor: "brightBlack",
181+ fgColor: "black",
182+ bold: true,
183+ }),
184+ Text(" quit", { fgColor: "brightBlack" }),
185+ ]),
186+ ]),
187+ ],
188+ );
189+});
packages/core/src/layout.test.ts+441−0
@@ -648,6 +648,447 @@ describe("layout", () => {
648648 });
649649 });
650650
651+ describe("flexWrap", () => {
652+ test("nowrap is the default — children stay on one line", () => {
653+ // Three 30-wide children in an 80-wide HStack: total 90, no wrapping
654+ const node = HStack({ width: 80, height: 24 }, [
655+ VStack({ width: 30, height: 5 }, []),
656+ VStack({ width: 30, height: 5 }, []),
657+ VStack({ width: 30, height: 5 }, []),
658+ ]);
659+ const result = layout(node, 80, 24);
660+ const rects = childRects(result);
661+ // All on same row (y=0), positioned left-to-right
662+ expect(rects[0]!.y).toBe(0);
663+ expect(rects[1]!.y).toBe(0);
664+ expect(rects[2]!.y).toBe(0);
665+ expect(rects[0]!.x).toBe(0);
666+ expect(rects[1]!.x).toBe(30);
667+ expect(rects[2]!.x).toBe(60);
668+ });
669+
670+ test("wrap splits children into rows when they exceed width", () => {
671+ // Three 30-wide children in an 80-wide HStack with wrap
672+ // Row 1: child0 (30) + child1 (30) = 60 ≤ 80 ✓
673+ // Row 2: child2 (30) — adding to row 1 would be 90 > 80
674+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
675+ VStack({ width: 30, height: 5 }, []),
676+ VStack({ width: 30, height: 5 }, []),
677+ VStack({ width: 30, height: 5 }, []),
678+ ]);
679+ const result = layout(node, 80, 24);
680+ const rects = childRects(result);
681+ // Row 1: child0 at (0,0), child1 at (30,0)
682+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 30, height: 5 });
683+ expect(rects[1]).toEqual({ x: 30, y: 0, width: 30, height: 5 });
684+ // Row 2: child2 at (0,5)
685+ expect(rects[2]).toEqual({ x: 0, y: 5, width: 30, height: 5 });
686+ });
687+
688+ test("all children fit on one row — no wrapping", () => {
689+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
690+ VStack({ width: 20, height: 3 }, []),
691+ VStack({ width: 20, height: 3 }, []),
692+ VStack({ width: 20, height: 3 }, []),
693+ ]);
694+ const result = layout(node, 80, 24);
695+ const rects = childRects(result);
696+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 20, height: 3 });
697+ expect(rects[1]).toEqual({ x: 20, y: 0, width: 20, height: 3 });
698+ expect(rects[2]).toEqual({ x: 40, y: 0, width: 20, height: 3 });
699+ });
700+
701+ test("each child on its own row when each exceeds half the width", () => {
702+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
703+ VStack({ width: 50, height: 2 }, []),
704+ VStack({ width: 50, height: 3 }, []),
705+ VStack({ width: 50, height: 4 }, []),
706+ ]);
707+ const result = layout(node, 80, 24);
708+ const rects = childRects(result);
709+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 50, height: 2 });
710+ expect(rects[1]).toEqual({ x: 0, y: 2, width: 50, height: 3 });
711+ expect(rects[2]).toEqual({ x: 0, y: 5, width: 50, height: 4 });
712+ });
713+
714+ test("row height is the max cross-size of children in that row", () => {
715+ // Row 1: height-2 and height-5 → row height 5
716+ // Row 2: height-3 → row height 3
717+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
718+ VStack({ width: 50, height: 2 }, []),
719+ VStack({ width: 20, height: 5 }, []),
720+ VStack({ width: 50, height: 3 }, []),
721+ ]);
722+ const result = layout(node, 80, 24);
723+ const rects = childRects(result);
724+ // Row 1: both at y=0, row height = max(2,5) = 5
725+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 50, height: 2 });
726+ expect(rects[1]).toEqual({ x: 50, y: 0, width: 20, height: 5 });
727+ // Row 2: starts at y=5
728+ expect(rects[2]).toEqual({ x: 0, y: 5, width: 50, height: 3 });
729+ });
730+
731+ test("gap between items within a row", () => {
732+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap", gap: 2 }, [
733+ VStack({ width: 30, height: 3 }, []),
734+ VStack({ width: 30, height: 3 }, []),
735+ VStack({ width: 30, height: 3 }, []),
736+ ]);
737+ const result = layout(node, 80, 24);
738+ const rects = childRects(result);
739+ // Row 1: child0(30) + gap(2) + child1(30) = 62 ≤ 80 ✓
740+ // + gap(2) + child2(30) = 94 > 80 ✗
741+ // Row 2: child2
742+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 30, height: 3 });
743+ expect(rects[1]).toEqual({ x: 32, y: 0, width: 30, height: 3 });
744+ // Row 2 starts at y = row1Height(3) + gap(2) = 5
745+ expect(rects[2]).toEqual({ x: 0, y: 5, width: 30, height: 3 });
746+ });
747+
748+ test("gap between rows", () => {
749+ // Every child gets its own row, gap between rows
750+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap", gap: 1 }, [
751+ VStack({ width: 80, height: 2 }, []),
752+ VStack({ width: 80, height: 3 }, []),
753+ ]);
754+ const result = layout(node, 80, 24);
755+ const rects = childRects(result);
756+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 80, height: 2 });
757+ // gap between rows = 1
758+ expect(rects[1]).toEqual({ x: 0, y: 3, width: 80, height: 3 });
759+ });
760+
761+ test("flex children distribute remaining space within their row", () => {
762+ // Row 1: fixed(20) + flex(1) → flex gets 80-20 = 60
763+ // Row 2: flex(1) → flex gets 80
764+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
765+ VStack({ width: 20, height: 3 }, []),
766+ VStack({ flex: 1, height: 3 }, []),
767+ VStack({ width: 90, height: 4 }, []), // wider than container, own row
768+ ]);
769+ const result = layout(node, 80, 24);
770+ const rects = childRects(result);
771+ // Row 1: fixed + flex
772+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 20, height: 3 });
773+ expect(rects[1]).toEqual({ x: 20, y: 0, width: 60, height: 3 });
774+ // Row 2: child wider than container
775+ expect(rects[2]!.y).toBe(3);
776+ });
777+
778+ test("multiple flex children in one row share space", () => {
779+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
780+ VStack({ width: 20, height: 3 }, []),
781+ VStack({ flex: 1, height: 3 }, []),
782+ VStack({ flex: 1, height: 3 }, []),
783+ ]);
784+ const result = layout(node, 80, 24);
785+ const rects = childRects(result);
786+ // All fit in one row. Remaining = 80 - 20 = 60, split 30/30
787+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 20, height: 3 });
788+ expect(rects[1]).toEqual({ x: 20, y: 0, width: 30, height: 3 });
789+ expect(rects[2]).toEqual({ x: 50, y: 0, width: 30, height: 3 });
790+ });
791+
792+ test("padding reduces available width for wrapping", () => {
793+ // Inner width = 80 - 2*5 = 70
794+ // Row 1: 40 ≤ 70 ✓, 40+40=80 > 70 ✗
795+ // Row 2: 40
796+ const node = HStack(
797+ { width: 80, height: 24, flexWrap: "wrap", padding: { x: 5, y: 2 } },
798+ [
799+ VStack({ width: 40, height: 3 }, []),
800+ VStack({ width: 40, height: 3 }, []),
801+ ],
802+ );
803+ const result = layout(node, 80, 24);
804+ const rects = childRects(result);
805+ // Row 1 at padded origin
806+ expect(rects[0]).toEqual({ x: 5, y: 2, width: 40, height: 3 });
807+ // Row 2
808+ expect(rects[1]).toEqual({ x: 5, y: 5, width: 40, height: 3 });
809+ });
810+
811+ test("alignItems stretch makes children fill row height", () => {
812+ // Default alignItems is stretch. Children should fill their row's height.
813+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
814+ VStack({ width: 50, height: 2 }, []),
815+ VStack({ width: 20 }, []), // no explicit height
816+ VStack({ width: 50, height: 3 }, []),
817+ ]);
818+ const result = layout(node, 80, 24);
819+ const rects = childRects(result);
820+ // Row 1: max height = 2 (first child), second child stretches to 2
821+ // But wait — when the second child has no explicit height, under stretch
822+ // it should fill the row height, which is determined by the tallest child.
823+ // The tallest in row 1 is 2, so stretched child gets 2.
824+ expect(rects[0]!.height).toBe(2);
825+ expect(rects[1]!.height).toBe(2);
826+ // Row 2
827+ expect(rects[2]!.height).toBe(3);
828+ });
829+
830+ test("alignItems center centers children vertically within row", () => {
831+ const node = HStack(
832+ { width: 80, height: 24, flexWrap: "wrap", alignItems: "center" },
833+ [
834+ VStack({ width: 50, height: 6 }, []),
835+ VStack({ width: 20, height: 2 }, []),
836+ ],
837+ );
838+ const result = layout(node, 80, 24);
839+ const rects = childRects(result);
840+ // Single row, row height = 6
841+ // First child: y=0, height=6 (fills row)
842+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 50, height: 6 });
843+ // Second child: centered in 6-high row → (6-2)/2 = 2
844+ expect(rects[1]).toEqual({ x: 50, y: 2, width: 20, height: 2 });
845+ });
846+
847+ test("alignItems end aligns children to bottom of row", () => {
848+ const node = HStack(
849+ { width: 80, height: 24, flexWrap: "wrap", alignItems: "end" },
850+ [
851+ VStack({ width: 50, height: 6 }, []),
852+ VStack({ width: 20, height: 2 }, []),
853+ ],
854+ );
855+ const result = layout(node, 80, 24);
856+ const rects = childRects(result);
857+ // Row height = 6. Second child at bottom: y = 6-2 = 4
858+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 50, height: 6 });
859+ expect(rects[1]).toEqual({ x: 50, y: 4, width: 20, height: 2 });
860+ });
861+
862+ test("justifyContent center centers items within each row", () => {
863+ const node = HStack(
864+ { width: 80, height: 24, flexWrap: "wrap", justifyContent: "center" },
865+ [
866+ VStack({ width: 30, height: 3 }, []),
867+ VStack({ width: 30, height: 3 }, []),
868+ VStack({ width: 30, height: 3 }, []),
869+ ],
870+ );
871+ const result = layout(node, 80, 24);
872+ const rects = childRects(result);
873+ // Row 1: child0+child1 = 60, remaining = 20, offset = 10
874+ expect(rects[0]).toEqual({ x: 10, y: 0, width: 30, height: 3 });
875+ expect(rects[1]).toEqual({ x: 40, y: 0, width: 30, height: 3 });
876+ // Row 2: child2 = 30, remaining = 50, offset = 25
877+ expect(rects[2]).toEqual({ x: 25, y: 3, width: 30, height: 3 });
878+ });
879+
880+ test("justifyContent end pushes items to end of each row", () => {
881+ const node = HStack(
882+ { width: 80, height: 24, flexWrap: "wrap", justifyContent: "end" },
883+ [
884+ VStack({ width: 30, height: 3 }, []),
885+ VStack({ width: 30, height: 3 }, []),
886+ VStack({ width: 30, height: 3 }, []),
887+ ],
888+ );
889+ const result = layout(node, 80, 24);
890+ const rects = childRects(result);
891+ // Row 1: 30+30 = 60, remaining = 20, offset = 20
892+ expect(rects[0]).toEqual({ x: 20, y: 0, width: 30, height: 3 });
893+ expect(rects[1]).toEqual({ x: 50, y: 0, width: 30, height: 3 });
894+ // Row 2: 30, remaining = 50, offset = 50
895+ expect(rects[2]).toEqual({ x: 50, y: 3, width: 30, height: 3 });
896+ });
897+
898+ test("justifyContent space-between distributes within each row", () => {
899+ const node = HStack(
900+ {
901+ width: 80,
902+ height: 24,
903+ flexWrap: "wrap",
904+ justifyContent: "space-between",
905+ },
906+ [
907+ VStack({ width: 20, height: 3 }, []),
908+ VStack({ width: 20, height: 3 }, []),
909+ VStack({ width: 20, height: 3 }, []),
910+ VStack({ width: 20, height: 3 }, []),
911+ ],
912+ );
913+ const result = layout(node, 80, 24);
914+ const rects = childRects(result);
915+ // All 4 fit: 20*4 = 80 — no wrapping needed
916+ // Remaining = 0 with space-between
917+ expect(rects[0]!.x).toBe(0);
918+ expect(rects[1]!.x).toBe(20);
919+ expect(rects[2]!.x).toBe(40);
920+ expect(rects[3]!.x).toBe(60);
921+ });
922+
923+ test("intrinsic height of wrapping HStack equals sum of row heights", () => {
924+ // HStack with no explicit height should size to fit all rows
925+ const node = VStack({ width: 80, height: 24 }, [
926+ HStack({ flexWrap: "wrap" }, [
927+ VStack({ width: 50, height: 3 }, []),
928+ VStack({ width: 50, height: 4 }, []),
929+ ]),
930+ Text("below"),
931+ ]);
932+ const result = layout(node, 80, 24);
933+ const rects = childRects(result);
934+ // HStack: row1 height=3, row2 height=4, total = 7
935+ expect(rects[0]!.height).toBe(7);
936+ // Text below starts at y=7
937+ expect(rects[1]!.y).toBe(7);
938+ });
939+
940+ test("intrinsic height with gap includes gaps between rows", () => {
941+ const node = VStack({ width: 80, height: 24 }, [
942+ HStack({ flexWrap: "wrap", gap: 1 }, [
943+ VStack({ width: 80, height: 2 }, []),
944+ VStack({ width: 80, height: 3 }, []),
945+ ]),
946+ Text("below"),
947+ ]);
948+ const result = layout(node, 80, 24);
949+ const rects = childRects(result);
950+ // Two rows: 2 + gap(1) + 3 = 6
951+ expect(rects[0]!.height).toBe(6);
952+ expect(rects[1]!.y).toBe(6);
953+ });
954+
955+ test("Text children wrap based on intrinsic width", () => {
956+ // Text nodes have intrinsic width. They should wrap like other nodes.
957+ const node = HStack({ width: 20, height: 10, flexWrap: "wrap" }, [
958+ Text("hello"), // width 5
959+ Text("world"), // width 5
960+ Text("this is long text"), // width 17
961+ ]);
962+ const result = layout(node, 20, 10);
963+ const rects = childRects(result);
964+ // Row 1: "hello"(5) + "world"(5) = 10 ≤ 20 ✓
965+ // + "this is long text"(17) = 27 > 20 ✗
966+ // Row 2: "this is long text"
967+ expect(rects[0]!.y).toBe(0);
968+ expect(rects[1]!.y).toBe(0);
969+ expect(rects[2]!.y).toBe(1); // second row
970+ expect(rects[0]!.x).toBe(0);
971+ expect(rects[1]!.x).toBe(5);
972+ expect(rects[2]!.x).toBe(0);
973+ });
974+
975+ test("single child wider than container gets its own row", () => {
976+ const node = HStack({ width: 40, height: 24, flexWrap: "wrap" }, [
977+ VStack({ width: 20, height: 3 }, []),
978+ VStack({ width: 50, height: 4 }, []), // wider than container
979+ VStack({ width: 20, height: 2 }, []),
980+ ]);
981+ const result = layout(node, 40, 24);
982+ const rects = childRects(result);
983+ // Row 1: child0 (20 ≤ 40)
984+ // child1 (20+50 > 40, starts new row)
985+ // Row 2: child1 (50 > 40, but it's the first item so it goes on this row)
986+ // Row 3: child2 (50+20 > 40, new row)
987+ expect(rects[0]!.y).toBe(0);
988+ expect(rects[1]!.y).toBe(3); // after row 1 (height 3)
989+ expect(rects[2]!.y).toBe(7); // after row 2 (height 4)
990+ });
991+
992+ test("empty HStack with flexWrap produces no children", () => {
993+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, []);
994+ const result = layout(node, 80, 24);
995+ expect(result.children).toEqual([]);
996+ });
997+
998+ test("single child in wrapping HStack", () => {
999+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
1000+ VStack({ width: 30, height: 5 }, []),
1001+ ]);
1002+ const result = layout(node, 80, 24);
1003+ const rects = childRects(result);
1004+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 30, height: 5 });
1005+ });
1006+
1007+ test("flexWrap on VStack is ignored (treated as nowrap)", () => {
1008+ // flexWrap is only meaningful on HStack per the spec
1009+ const node = VStack({ width: 80, height: 10, flexWrap: "wrap" as any }, [
1010+ VStack({ height: 4 }, []),
1011+ VStack({ height: 4 }, []),
1012+ VStack({ height: 4 }, []),
1013+ ]);
1014+ const result = layout(node, 80, 10);
1015+ const rects = childRects(result);
1016+ // Normal VStack behavior — children stack vertically, overflow
1017+ expect(rects[0]!.y).toBe(0);
1018+ expect(rects[1]!.y).toBe(4);
1019+ expect(rects[2]!.y).toBe(8);
1020+ });
1021+
1022+ test("nested wrapping HStack inside VStack", () => {
1023+ const node = VStack({ width: 60, height: 24 }, [
1024+ Text("Title"),
1025+ HStack({ flexWrap: "wrap", gap: 1 }, [
1026+ VStack({ width: 25, height: 2 }, []),
1027+ VStack({ width: 25, height: 2 }, []),
1028+ VStack({ width: 25, height: 2 }, []),
1029+ ]),
1030+ Text("Footer"),
1031+ ]);
1032+ const result = layout(node, 60, 24);
1033+ const rects = childRects(result);
1034+
1035+ // Title at y=0, height=1
1036+ expect(rects[0]!.y).toBe(0);
1037+ expect(rects[0]!.height).toBe(1);
1038+
1039+ // HStack at y=1
1040+ // Row 1: 25 + 1 + 25 = 51 ≤ 60, + 1 + 25 = 77 > 60
1041+ // Row 2: 25
1042+ // HStack height = 2 + 1 + 2 = 5
1043+ expect(rects[1]!.y).toBe(1);
1044+ expect(rects[1]!.height).toBe(5);
1045+
1046+ // Footer at y=6
1047+ expect(rects[2]!.y).toBe(6);
1048+
1049+ // Verify HStack's children
1050+ const hstackChildren = result.children[1]!.children;
1051+ expect(hstackChildren[0]!.rect).toEqual({
1052+ x: 0,
1053+ y: 1,
1054+ width: 25,
1055+ height: 2,
1056+ });
1057+ expect(hstackChildren[1]!.rect).toEqual({
1058+ x: 26,
1059+ y: 1,
1060+ width: 25,
1061+ height: 2,
1062+ });
1063+ expect(hstackChildren[2]!.rect).toEqual({
1064+ x: 0,
1065+ y: 4,
1066+ width: 25,
1067+ height: 2,
1068+ });
1069+ });
1070+
1071+ test("constraints apply to children in wrapped rows", () => {
1072+ const node = HStack({ width: 80, height: 24, flexWrap: "wrap" }, [
1073+ VStack({ flex: 1, minWidth: 30, height: 3 }, []),
1074+ VStack({ flex: 1, minWidth: 30, height: 3 }, []),
1075+ VStack({ flex: 1, minWidth: 30, height: 3 }, []),
1076+ ]);
1077+ const result = layout(node, 80, 24);
1078+ const rects = childRects(result);
1079+ // Flex children: need to decide row membership based on min sizes
1080+ // Each has minWidth 30. Three at 30 = 90 > 80, so wrapping occurs.
1081+ // Row 1: child0 + child1 at minWidth 30 each = 60 ≤ 80
1082+ // Remaining = 80 - 0 (no fixed) = 80, shared between 2 flex → 40 each
1083+ // Both ≥ 30 ✓
1084+ // Row 2: child2 → gets full 80
1085+ expect(rects[0]!.width).toBe(40);
1086+ expect(rects[1]!.width).toBe(40);
1087+ expect(rects[2]!.y).toBe(3);
1088+ expect(rects[2]!.width).toBe(80);
1089+ });
1090+ });
1091+
6511092 describe("nested layout", () => {
6521093 test("editor-like layout: sidebar + main area", () => {
6531094 const node = HStack({ width: 80, height: 24 }, [
packages/core/src/layout.ts+282−0
@@ -144,6 +144,47 @@ function intrinsicMainSize(
144144 return total + padMain;
145145 }
146146
147+ // Special case: wrapping HStack computing intrinsic height.
148+ // Instead of max-of-children, simulate the row layout and sum row heights.
149+ if (
150+ node.type === "hstack" &&
151+ (node.props as ContainerProps).flexWrap === "wrap"
152+ ) {
153+ const wrapWidths: number[] = [];
154+ const wrapHeights: number[] = [];
155+ for (const child of node.children) {
156+ const cProps = getProps(child);
157+ const flex = cProps?.flex ?? 0;
158+ let w: number;
159+ if (flex > 0) {
160+ w = cProps?.minWidth ?? 0;
161+ } else {
162+ w =
163+ resolveSizeValue(cProps?.width, innerCross) ??
164+ intrinsicMainSize(child, false, innerCross);
165+ if (cProps) {
166+ w = clamp(w, cProps.minWidth ?? 0, cProps.maxWidth ?? Infinity);
167+ }
168+ }
169+ wrapWidths.push(w);
170+ const h =
171+ resolveSizeValue(cProps?.height, 0) ??
172+ intrinsicMainSize(child, true, innerCross);
173+ wrapHeights.push(h);
174+ }
175+ const wrapRows = assignWrapRows(wrapWidths, innerCross, gap);
176+ let total = 0;
177+ for (let ri = 0; ri < wrapRows.length; ri++) {
178+ let maxH = 0;
179+ for (const idx of wrapRows[ri]!) {
180+ if (wrapHeights[idx]! > maxH) maxH = wrapHeights[idx]!;
181+ }
182+ total += maxH;
183+ if (ri < wrapRows.length - 1) total += gap;
184+ }
185+ return total + padMain;
186+ }
187+
147188 // Cross axis: max of children on the requested axis
148189 let maxSize = 0;
149190 for (const child of node.children) {
@@ -164,6 +205,45 @@ function intrinsicMainSize(
164205 return maxSize + padMain;
165206 }
166207
208+// --- Wrap row assignment ---
209+
210+/**
211+ * Assign children to rows for a wrapping HStack.
212+ * Children are placed left-to-right; when adding the next child (plus gap)
213+ * would exceed availWidth, a new row begins. A child wider than the
214+ * container still gets its own row.
215+ */
216+function assignWrapRows(
217+ widths: number[],
218+ availWidth: number,
219+ gap: number,
220+): number[][] {
221+ if (widths.length === 0) return [];
222+ const rows: number[][] = [];
223+ let currentRow: number[] = [];
224+ let rowWidth = 0;
225+
226+ for (let i = 0; i < widths.length; i++) {
227+ const w = widths[i]!;
228+ if (currentRow.length === 0) {
229+ currentRow.push(i);
230+ rowWidth = w;
231+ } else {
232+ const needed = rowWidth + gap + w;
233+ if (needed > availWidth) {
234+ rows.push(currentRow);
235+ currentRow = [i];
236+ rowWidth = w;
237+ } else {
238+ currentRow.push(i);
239+ rowWidth = needed;
240+ }
241+ }
242+ }
243+ if (currentRow.length > 0) rows.push(currentRow);
244+ return rows;
245+}
246+
167247 // --- Largest remainder rounding ---
168248
169249 function largestRemainder(fractions: number[], total: number): number[] {
@@ -205,6 +285,203 @@ export function layout(
205285 return layoutNode(root, 0, 0, rootW, rootH);
206286 }
207287
288+/**
289+ * Layout a wrapping HStack. Children are assigned to rows based on their
290+ * base widths, then each row is laid out as an independent flex context.
291+ */
292+function layoutWrapHStack(
293+ node: Node,
294+ rect: Rect,
295+ props: ContainerProps,
296+ children: Node[],
297+ x: number,
298+ y: number,
299+ width: number,
300+ height: number,
301+): LayoutNode {
302+ const gap = props.gap ?? 0;
303+ const align = props.alignItems ?? "stretch";
304+ const justify = props.justifyContent ?? "start";
305+
306+ // Padding
307+ const padX = props.padding?.x ?? 0;
308+ const padY = props.padding?.y ?? 0;
309+ const innerX = x + padX;
310+ const innerY = y + padY;
311+ const innerW = Math.max(0, width - padX * 2);
312+ const innerH = Math.max(0, height - padY * 2);
313+
314+ // Phase 1: Measure each child's base width and cross (height) size
315+ const baseWidths: number[] = [];
316+ const crossSizes: number[] = [];
317+ const flexValues: number[] = [];
318+
319+ for (const child of children) {
320+ const cProps = getProps(child);
321+ const flex = cProps?.flex ?? 0;
322+ flexValues.push(flex);
323+
324+ let baseW: number;
325+ if (flex > 0) {
326+ // Flex children use minWidth for row assignment (like CSS flex-basis)
327+ baseW = cProps?.minWidth ?? 0;
328+ } else {
329+ baseW =
330+ resolveSizeValue(cProps?.width, innerW) ??
331+ intrinsicMainSize(child, false, innerH);
332+ if (cProps) {
333+ baseW = clamp(baseW, cProps.minWidth ?? 0, cProps.maxWidth ?? Infinity);
334+ }
335+ }
336+ baseWidths.push(baseW);
337+
338+ // Always compute real cross size (explicit or intrinsic) for row height
339+ const cross =
340+ resolveSizeValue(cProps?.height, innerH) ??
341+ intrinsicMainSize(child, true, innerW);
342+ crossSizes.push(cross);
343+ }
344+
345+ // Phase 2: Assign children to rows
346+ const rows = assignWrapRows(baseWidths, innerW, gap);
347+
348+ // Phase 3: Layout each row independently
349+ const layoutChildren: LayoutNode[] = [];
350+ let rowY = 0;
351+
352+ for (let ri = 0; ri < rows.length; ri++) {
353+ const rowIdx = rows[ri]!;
354+ const rowGapTotal = gap * (rowIdx.length - 1);
355+ const rowAvail = innerW - rowGapTotal;
356+
357+ // Compute fixed and flex totals for this row
358+ let fixedMain = 0;
359+ let totalFlex = 0;
360+ for (const idx of rowIdx) {
361+ if (flexValues[idx]! > 0) {
362+ totalFlex += flexValues[idx]!;
363+ } else {
364+ fixedMain += baseWidths[idx]!;
365+ }
366+ }
367+
368+ // Distribute flex space within this row
369+ const flexSpace = Math.max(0, rowAvail - fixedMain);
370+ const childWidths: number[] = new Array(rowIdx.length);
371+
372+ if (totalFlex > 0) {
373+ const flexPositions: number[] = [];
374+ for (let ci = 0; ci < rowIdx.length; ci++) {
375+ if (flexValues[rowIdx[ci]!]! > 0) flexPositions.push(ci);
376+ }
377+ const rawSizes = flexPositions.map(
378+ (ci) => (flexValues[rowIdx[ci]!]! / totalFlex) * flexSpace,
379+ );
380+ const rounded = largestRemainder(rawSizes, flexSpace);
381+
382+ for (let fi = 0; fi < flexPositions.length; fi++) {
383+ const ci = flexPositions[fi]!;
384+ let size = rounded[fi]!;
385+ const cProps = getProps(children[rowIdx[ci]!]!);
386+ if (cProps) {
387+ size = clamp(size, cProps.minWidth ?? 0, cProps.maxWidth ?? Infinity);
388+ }
389+ childWidths[ci] = size;
390+ }
391+ }
392+
393+ // Non-flex children keep their base width
394+ for (let ci = 0; ci < rowIdx.length; ci++) {
395+ if (childWidths[ci] === undefined) {
396+ childWidths[ci] = baseWidths[rowIdx[ci]!]!;
397+ }
398+ }
399+
400+ // Row height = max cross size of children in this row
401+ let rowHeight = 0;
402+ for (const idx of rowIdx) {
403+ if (crossSizes[idx]! > rowHeight) rowHeight = crossSizes[idx]!;
404+ }
405+
406+ // justifyContent: compute main-axis starting offset
407+ let totalUsedWidth = rowGapTotal;
408+ for (let ci = 0; ci < rowIdx.length; ci++) {
409+ totalUsedWidth += childWidths[ci]!;
410+ }
411+ const remainingMain = Math.max(0, innerW - totalUsedWidth);
412+
413+ let mainStart = 0;
414+ let betweenGaps: number[] | null = null;
415+
416+ if (justify === "end") {
417+ mainStart = remainingMain;
418+ } else if (justify === "center") {
419+ mainStart = Math.floor(remainingMain / 2);
420+ } else if (justify === "space-between" && rowIdx.length > 1) {
421+ const gapCount = rowIdx.length - 1;
422+ const rawGaps = Array.from(
423+ { length: gapCount },
424+ () => remainingMain / gapCount,
425+ );
426+ betweenGaps = largestRemainder(rawGaps, remainingMain);
427+ }
428+
429+ // Position children in this row
430+ let xOffset = mainStart;
431+ for (let ci = 0; ci < rowIdx.length; ci++) {
432+ const idx = rowIdx[ci]!;
433+ const childW = childWidths[ci]!;
434+
435+ // Cross-axis sizing: stretch fills row height, others keep their size
436+ let childH: number;
437+ if (align === "stretch") {
438+ const cProps = getProps(children[idx]!);
439+ const explicitH = resolveSizeValue(cProps?.height, innerH);
440+ childH = explicitH ?? rowHeight;
441+ } else {
442+ childH = crossSizes[idx]!;
443+ }
444+
445+ // Cross-axis alignment within the row
446+ let crossOffset = 0;
447+ if (align === "center") {
448+ crossOffset = Math.floor((rowHeight - childH) / 2);
449+ } else if (align === "end") {
450+ crossOffset = rowHeight - childH;
451+ }
452+
453+ const childX = innerX + xOffset;
454+ const childY = innerY + rowY + crossOffset;
455+
456+ layoutChildren.push(
457+ layoutNode(children[idx]!, childX, childY, childW, childH),
458+ );
459+
460+ xOffset += childW;
461+ if (ci < rowIdx.length - 1) {
Cut short: this commit's diff is over 1000 lines.
packages/core/src/paint.test.ts+68−0
Cut short: this commit's diff is over 1000 lines.
packages/types/src/index.ts+14−0
Cut short: this commit's diff is over 1000 lines.
spec.md+39−0
Cut short: this commit's diff is over 1000 lines.