xonecas.io
70160
Ce

cel-tui / commit bcc6f88

feat(core): implement flexbox layout engine

- Fixed, intrinsic, flex, and percentage sizing strategies
- Largest remainder rounding for fractional flex distribution
- min/max constraints on all axes
- Gap spacing between children
- Padding (x/y) reducing available space
- VStack (vertical) and HStack (horizontal) child positioning
- Intrinsic container sizing (shrink to fit children)
- Text/TextInput intrinsic height from content + wrapping
- Nested layout support (editor-like sidebar + main area test)
- 25 layout tests covering all sizing strategies and combinations

xonecas2026-04-03 bcc6f883d7c91ae5fbbaabe1f3e44aefe91b62d9 parent 092c158

2 files changed

packages/core/src/layout.test.ts+321−0
@@ -0,0 +1,321 @@
1+import { describe, expect, test } from "bun:test";
2+import { layout, type LayoutNode, type Rect } from "./layout.js";
3+import { VStack, HStack } from "./primitives/stacks.js";
4+import { Text } from "./primitives/text.js";
5+
6+/** Helper to extract just the rect from a layout result. */
7+function rect(ln: LayoutNode): Rect {
8+ return ln.rect;
9+}
10+
11+/** Helper to get child rects. */
12+function childRects(ln: LayoutNode): Rect[] {
13+ return ln.children.map((c) => c.rect);
14+}
15+
16+describe("layout", () => {
17+ describe("fixed sizing", () => {
18+ test("container with fixed width and height", () => {
19+ const node = VStack({ width: 30, height: 10 }, []);
20+ const result = layout(node, 80, 24);
21+ expect(rect(result)).toEqual({ x: 0, y: 0, width: 30, height: 10 });
22+ });
23+
24+ test("child with fixed size inside a container", () => {
25+ const node = VStack({ width: 80, height: 24 }, [
26+ VStack({ width: 20, height: 5 }, []),
27+ ]);
28+ const result = layout(node, 80, 24);
29+ expect(childRects(result)).toEqual([
30+ { x: 0, y: 0, width: 20, height: 5 },
31+ ]);
32+ });
33+
34+ test("root without sizing fills available space", () => {
35+ const node = VStack({}, []);
36+ const result = layout(node, 80, 24);
37+ expect(rect(result)).toEqual({ x: 0, y: 0, width: 80, height: 24 });
38+ });
39+ });
40+
41+ describe("intrinsic sizing", () => {
42+ test("Text height is 1 for single line", () => {
43+ const node = VStack({ width: 80, height: 24 }, [Text("hello")]);
44+ const result = layout(node, 80, 24);
45+ expect(childRects(result)[0]!.height).toBe(1);
46+ });
47+
48+ test("Text height follows newlines", () => {
49+ const node = VStack({ width: 80, height: 24 }, [
50+ Text("line1\nline2\nline3"),
51+ ]);
52+ const result = layout(node, 80, 24);
53+ expect(childRects(result)[0]!.height).toBe(3);
54+ });
55+
56+ test("Text width fills parent in VStack", () => {
57+ const node = VStack({ width: 40, height: 10 }, [Text("hi")]);
58+ const result = layout(node, 80, 24);
59+ expect(childRects(result)[0]!.width).toBe(40);
60+ });
61+
62+ test("VStack without height sizes to children", () => {
63+ const node = VStack({ width: 80 }, [
64+ VStack({ height: 3 }, []),
65+ VStack({ height: 5 }, []),
66+ ]);
67+ const result = layout(node, 80, 24);
68+ expect(rect(result).height).toBe(8);
69+ });
70+
71+ test("HStack without width sizes to children", () => {
72+ const node = HStack({ height: 10 }, [
73+ VStack({ width: 15 }, []),
74+ VStack({ width: 25 }, []),
75+ ]);
76+ const result = layout(node, 80, 24);
77+ expect(rect(result).width).toBe(40);
78+ });
79+ });
80+
81+ describe("flex sizing", () => {
82+ test("single flex child fills remaining space in VStack", () => {
83+ const node = VStack({ width: 80, height: 24 }, [
84+ VStack({ height: 4 }, []),
85+ VStack({ flex: 1 }, []),
86+ ]);
87+ const result = layout(node, 80, 24);
88+ expect(childRects(result)).toEqual([
89+ { x: 0, y: 0, width: 80, height: 4 },
90+ { x: 0, y: 4, width: 80, height: 20 },
91+ ]);
92+ });
93+
94+ test("multiple flex children share space proportionally", () => {
95+ const node = VStack({ width: 80, height: 24 }, [
96+ VStack({ flex: 1 }, []),
97+ VStack({ flex: 2 }, []),
98+ ]);
99+ const result = layout(node, 80, 24);
100+ expect(childRects(result)).toEqual([
101+ { x: 0, y: 0, width: 80, height: 8 },
102+ { x: 0, y: 8, width: 80, height: 16 },
103+ ]);
104+ });
105+
106+ test("flex in HStack divides width", () => {
107+ const node = HStack({ width: 80, height: 24 }, [
108+ VStack({ flex: 1 }, []),
109+ VStack({ flex: 3 }, []),
110+ ]);
111+ const result = layout(node, 80, 24);
112+ expect(childRects(result)).toEqual([
113+ { x: 0, y: 0, width: 20, height: 24 },
114+ { x: 20, y: 0, width: 60, height: 24 },
115+ ]);
116+ });
117+
118+ test("fixed + flex children", () => {
119+ const node = VStack({ width: 80, height: 24 }, [
120+ VStack({ height: 1 }, []),
121+ VStack({ flex: 1 }, []),
122+ VStack({ height: 1 }, []),
123+ ]);
124+ const result = layout(node, 80, 24);
125+ expect(childRects(result)).toEqual([
126+ { x: 0, y: 0, width: 80, height: 1 },
127+ { x: 0, y: 1, width: 80, height: 22 },
128+ { x: 0, y: 23, width: 80, height: 1 },
129+ ]);
130+ });
131+ });
132+
133+ describe("percentage sizing", () => {
134+ test("percentage width relative to parent", () => {
135+ const node = VStack({ width: 80, height: 24 }, [
136+ VStack({ width: "50%", height: 10 }, []),
137+ ]);
138+ const result = layout(node, 80, 24);
139+ expect(childRects(result)[0]!.width).toBe(40);
140+ });
141+
142+ test("percentage height relative to parent", () => {
143+ const node = VStack({ width: 80, height: 24 }, [
144+ VStack({ width: 80, height: "50%" }, []),
145+ ]);
146+ const result = layout(node, 80, 24);
147+ expect(childRects(result)[0]!.height).toBe(12);
148+ });
149+ });
150+
151+ describe("rounding (largest remainder)", () => {
152+ test("distributes remainder to children with largest fractional parts", () => {
153+ // 80 / 3 = 26.667 each → 27, 27, 26
154+ const node = HStack({ width: 80, height: 24 }, [
155+ VStack({ flex: 1 }, []),
156+ VStack({ flex: 1 }, []),
157+ VStack({ flex: 1 }, []),
158+ ]);
159+ const result = layout(node, 80, 24);
160+ const widths = childRects(result).map((r) => r.width);
161+ expect(widths).toEqual([27, 27, 26]);
162+ expect(widths.reduce((a, b) => a + b)).toBe(80);
163+ });
164+ });
165+
166+ describe("constraints", () => {
167+ test("minWidth prevents shrinking below minimum", () => {
168+ const node = HStack({ width: 80, height: 24 }, [
169+ VStack({ flex: 1, minWidth: 30 }, []),
170+ VStack({ flex: 1 }, []),
171+ ]);
172+ const result = layout(node, 80, 24);
173+ expect(childRects(result)[0]!.width).toBeGreaterThanOrEqual(30);
174+ });
175+
176+ test("maxHeight caps growth", () => {
177+ const node = VStack({ width: 80, height: 24 }, [
178+ VStack({ flex: 1, maxHeight: 10 }, []),
179+ VStack({ flex: 1 }, []),
180+ ]);
181+ const result = layout(node, 80, 24);
182+ expect(childRects(result)[0]!.height).toBeLessThanOrEqual(10);
183+ });
184+ });
185+
186+ describe("gap", () => {
187+ test("VStack gap adds spacing between children", () => {
188+ const node = VStack({ width: 80, height: 24, gap: 1 }, [
189+ VStack({ height: 3 }, []),
190+ VStack({ height: 3 }, []),
191+ VStack({ height: 3 }, []),
192+ ]);
193+ const result = layout(node, 80, 24);
194+ const rects = childRects(result);
195+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 80, height: 3 });
196+ expect(rects[1]).toEqual({ x: 0, y: 4, width: 80, height: 3 });
197+ expect(rects[2]).toEqual({ x: 0, y: 8, width: 80, height: 3 });
198+ });
199+
200+ test("HStack gap adds spacing between children", () => {
201+ const node = HStack({ width: 80, height: 24, gap: 2 }, [
202+ VStack({ width: 20 }, []),
203+ VStack({ width: 20 }, []),
204+ ]);
205+ const result = layout(node, 80, 24);
206+ const rects = childRects(result);
207+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 20, height: 24 });
208+ expect(rects[1]).toEqual({ x: 22, y: 0, width: 20, height: 24 });
209+ });
210+
211+ test("gap is subtracted before flex distribution", () => {
212+ const node = VStack({ width: 80, height: 24, gap: 1 }, [
213+ VStack({ height: 4 }, []),
214+ VStack({ flex: 1 }, []),
215+ ]);
216+ const result = layout(node, 80, 24);
217+ const rects = childRects(result);
218+ // 24 - 4 (fixed) - 1 (gap) = 19 for flex
219+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 80, height: 4 });
220+ expect(rects[1]).toEqual({ x: 0, y: 5, width: 80, height: 19 });
221+ });
222+ });
223+
224+ describe("padding", () => {
225+ test("padding reduces available space for children", () => {
226+ const node = VStack({ width: 80, height: 24, padding: { x: 2, y: 1 } }, [
227+ VStack({ flex: 1 }, []),
228+ ]);
229+ const result = layout(node, 80, 24);
230+ // Children start at (2, 1) with reduced size
231+ expect(childRects(result)[0]).toEqual({
232+ x: 2,
233+ y: 1,
234+ width: 76,
235+ height: 22,
236+ });
237+ });
238+
239+ test("padding with gap", () => {
240+ const node = VStack(
241+ { width: 80, height: 24, padding: { x: 1 }, gap: 1 },
242+ [VStack({ height: 3 }, []), VStack({ height: 3 }, [])],
243+ );
244+ const result = layout(node, 80, 24);
245+ const rects = childRects(result);
246+ expect(rects[0]).toEqual({ x: 1, y: 0, width: 78, height: 3 });
247+ expect(rects[1]).toEqual({ x: 1, y: 4, width: 78, height: 3 });
248+ });
249+ });
250+
251+ describe("VStack child positioning", () => {
252+ test("children stack top to bottom", () => {
253+ const node = VStack({ width: 80, height: 24 }, [
254+ VStack({ height: 5 }, []),
255+ VStack({ height: 3 }, []),
256+ VStack({ height: 7 }, []),
257+ ]);
258+ const result = layout(node, 80, 24);
259+ const rects = childRects(result);
260+ expect(rects[0]!.y).toBe(0);
261+ expect(rects[1]!.y).toBe(5);
262+ expect(rects[2]!.y).toBe(8);
263+ });
264+ });
265+
266+ describe("HStack child positioning", () => {
267+ test("children stack left to right", () => {
268+ const node = HStack({ width: 80, height: 24 }, [
269+ VStack({ width: 20 }, []),
270+ VStack({ width: 15 }, []),
271+ VStack({ width: 30 }, []),
272+ ]);
273+ const result = layout(node, 80, 24);
274+ const rects = childRects(result);
275+ expect(rects[0]!.x).toBe(0);
276+ expect(rects[1]!.x).toBe(20);
277+ expect(rects[2]!.x).toBe(35);
278+ });
279+ });
280+
281+ describe("nested layout", () => {
282+ test("editor-like layout: sidebar + main area", () => {
283+ const node = HStack({ width: 80, height: 24 }, [
284+ VStack({ width: 20 }, []),
285+ VStack({ flex: 1 }, [
286+ VStack({ height: 1 }, []),
287+ VStack({ flex: 1 }, []),
288+ VStack({ height: 1 }, []),
289+ ]),
290+ ]);
291+ const result = layout(node, 80, 24);
292+ const rects = childRects(result);
293+
294+ // Sidebar
295+ expect(rects[0]).toEqual({ x: 0, y: 0, width: 20, height: 24 });
296+ // Main area
297+ expect(rects[1]).toEqual({ x: 20, y: 0, width: 60, height: 24 });
298+
299+ // Main area children
300+ const mainChildren = result.children[1]!.children;
301+ expect(mainChildren[0]!.rect).toEqual({
302+ x: 20,
303+ y: 0,
304+ width: 60,
305+ height: 1,
306+ });
307+ expect(mainChildren[1]!.rect).toEqual({
308+ x: 20,
309+ y: 1,
310+ width: 60,
311+ height: 22,
312+ });
313+ expect(mainChildren[2]!.rect).toEqual({
314+ x: 20,
315+ y: 23,
316+ width: 60,
317+ height: 1,
318+ });
319+ });
320+ });
321+});
packages/core/src/layout.ts+331−0
@@ -0,0 +1,331 @@
1+import type { Node, ContainerProps, SizeValue } from "@cel-tui/types";
2+
3+/**
4+ * A rectangle in absolute screen coordinates.
5+ */
6+export interface Rect {
7+ x: number;
8+ y: number;
9+ width: number;
10+ height: number;
11+}
12+
13+/**
14+ * A node in the layout tree with computed position and size.
15+ */
16+export interface LayoutNode {
17+ /** The original UI node. */
18+ node: Node;
19+ /** Computed absolute screen rect. */
20+ rect: Rect;
21+ /** Laid-out children (empty for leaf nodes). */
22+ children: LayoutNode[];
23+}
24+
25+// --- Helpers ---
26+
27+function resolveSizeValue(
28+ value: SizeValue | undefined,
29+ parentSize: number,
30+): number | undefined {
31+ if (value === undefined) return undefined;
32+ if (typeof value === "number") return value;
33+ const match = value.match(/^(\d+(?:\.\d+)?)%$/);
34+ if (match) return Math.floor((parentSize * parseFloat(match[1]!)) / 100);
35+ return undefined;
36+}
37+
38+function clamp(value: number, min: number, max: number): number {
39+ return Math.max(min, Math.min(max, value));
40+}
41+
42+function getProps(node: Node): ContainerProps | null {
43+ if (node.type === "text") return null;
44+ return node.props;
45+}
46+
47+// --- Intrinsic size computation ---
48+
49+/**
50+ * Compute intrinsic main-axis size for a node (before layout).
51+ * Used by the parent to determine how much space to allocate.
52+ */
53+function intrinsicMainSize(
54+ node: Node,
55+ isVertical: boolean,
56+ crossSize: number,
57+): number {
58+ if (node.type === "text") {
59+ if (isVertical) {
60+ // Height = number of lines
61+ if (node.content.length === 0) return 1;
62+ const lines = node.content.split("\n");
63+ if (node.props.wrap === "word") {
64+ let total = 0;
65+ for (const line of lines) {
66+ total += Math.max(1, Math.ceil(line.length / Math.max(1, crossSize)));
67+ }
68+ return total;
69+ }
70+ return lines.length;
71+ }
72+ // Width (intrinsic)
73+ if (node.props.repeat === "fill") return 0;
74+ const lines = node.content.split("\n");
75+ let maxW = 0;
76+ for (const line of lines) {
77+ if (line.length > maxW) maxW = line.length;
78+ }
79+ if (typeof node.props.repeat === "number") maxW *= node.props.repeat;
80+ return maxW;
81+ }
82+
83+ if (node.type === "textinput") {
84+ if (isVertical) {
85+ const val = node.props.value || "";
86+ if (val.length === 0) return 1;
87+ const lines = val.split("\n");
88+ let total = 0;
89+ for (const line of lines) {
90+ total += Math.max(1, Math.ceil(line.length / Math.max(1, crossSize)));
91+ }
92+ return total;
93+ }
94+ return 0;
95+ }
96+
97+ // Container: sum children along main axis + gaps
98+ const props = node.props;
99+ const gap = props.gap ?? 0;
100+ const padMain = isVertical
101+ ? (props.padding?.y ?? 0) * 2
102+ : (props.padding?.x ?? 0) * 2;
103+ const padCross = isVertical
104+ ? (props.padding?.x ?? 0) * 2
105+ : (props.padding?.y ?? 0) * 2;
106+ const innerCross = Math.max(0, crossSize - padCross);
107+ const childIsVertical = node.type === "vstack";
108+
109+ let total = 0;
110+ for (let i = 0; i < node.children.length; i++) {
111+ const child = node.children[i]!;
112+ const cProps = getProps(child);
113+
114+ // Use child's explicit main size, or recurse for intrinsic
115+ let childMain: number;
116+ if (childIsVertical) {
117+ childMain =
118+ resolveSizeValue(cProps?.height, 0) ??
119+ intrinsicMainSize(child, true, innerCross);
120+ } else {
121+ childMain =
122+ resolveSizeValue(cProps?.width, 0) ??
123+ intrinsicMainSize(child, false, innerCross);
124+ }
125+ total += childMain;
126+ if (i < node.children.length - 1) total += gap;
127+ }
128+
129+ return total + padMain;
130+}
131+
132+// --- Largest remainder rounding ---
133+
134+function largestRemainder(fractions: number[], total: number): number[] {
135+ const floored = fractions.map(Math.floor);
136+ let remainder = total - floored.reduce((a, b) => a + b, 0);
137+
138+ const indices = fractions
139+ .map((v, i) => ({ i, frac: v - Math.floor(v) }))
140+ .sort((a, b) => b.frac - a.frac);
141+
142+ for (const { i } of indices) {
143+ if (remainder <= 0) break;
144+ floored[i]!++;
145+ remainder--;
146+ }
147+
148+ return floored;
149+}
150+
151+// --- Main layout ---
152+
153+/**
154+ * Compute the layout for a UI tree.
155+ *
156+ * @param root - The root UI node.
157+ * @param availWidth - Available width (typically terminal columns).
158+ * @param availHeight - Available height (typically terminal rows).
159+ * @returns Layout tree with computed rects.
160+ */
161+export function layout(
162+ root: Node,
163+ availWidth: number,
164+ availHeight: number,
165+): LayoutNode {
166+ // Resolve root's own size against the viewport
167+ const rootProps = getProps(root);
168+ const rootW = resolveSizeValue(rootProps?.width, availWidth) ?? availWidth;
169+ const rootH = resolveSizeValue(rootProps?.height, availHeight) ?? availHeight;
170+ return layoutNode(root, 0, 0, rootW, rootH);
171+}
172+
173+/**
174+ * Layout a node within the given available space.
175+ * Resolves the node's own explicit size (if any) against available space,
176+ * then lays out children within that.
177+ */
178+function layoutNode(
179+ node: Node,
180+ x: number,
181+ y: number,
182+ availWidth: number,
183+ availHeight: number,
184+): LayoutNode {
185+ // Resolve own dimensions: explicit size wins, otherwise fill available.
186+ // Note: for children, the parent has already resolved sizing and passes
187+ // the result as availWidth/availHeight. We only re-resolve for the root
188+ // node (where available space = viewport, not pre-resolved).
189+ const width = availWidth;
190+ const height = availHeight;
191+ const rect: Rect = { x, y, width, height };
192+
193+ // Leaf nodes
194+ if (node.type === "text" || node.type === "textinput") {
195+ return { node, rect, children: [] };
196+ }
197+
198+ // Container nodes
199+ const props = node.props;
200+ const isVertical = node.type === "vstack";
201+ const children = node.children;
202+
203+ if (children.length === 0) {
204+ return { node, rect, children: [] };
205+ }
206+
207+ // Padding
208+ const padX = props.padding?.x ?? 0;
209+ const padY = props.padding?.y ?? 0;
210+ const innerX = x + padX;
211+ const innerY = y + padY;
212+ const innerW = Math.max(0, width - padX * 2);
213+ const innerH = Math.max(0, height - padY * 2);
214+
215+ // Gap
216+ const gap = props.gap ?? 0;
217+ const totalGap = gap * (children.length - 1);
218+ const mainAvail = (isVertical ? innerH : innerW) - totalGap;
219+
220+ // --- Measure phase: compute each child's main-axis and cross-axis size ---
221+ type ChildInfo = {
222+ node: Node;
223+ mainSize: number;
224+ crossSize: number;
225+ flex: number;
226+ };
227+ const infos: ChildInfo[] = [];
228+ let fixedMain = 0;
229+ let totalFlex = 0;
230+
231+ for (const child of children) {
232+ const cProps = getProps(child);
233+ const flex = cProps?.flex ?? 0;
234+
235+ if (flex > 0) {
236+ totalFlex += flex;
237+ // Cross-axis
238+ const cross = isVertical
239+ ? (resolveSizeValue(cProps?.width, innerW) ?? innerW)
240+ : (resolveSizeValue(cProps?.height, innerH) ?? innerH);
241+ infos.push({ node: child, mainSize: 0, crossSize: cross, flex });
242+ } else {
243+ // Main-axis: explicit → percentage → intrinsic
244+ let main: number;
245+ let cross: number;
246+ if (isVertical) {
247+ main =
248+ resolveSizeValue(cProps?.height, innerH) ??
249+ intrinsicMainSize(child, true, innerW);
250+ cross = resolveSizeValue(cProps?.width, innerW) ?? innerW;
251+ } else {
252+ main =
253+ resolveSizeValue(cProps?.width, innerW) ??
254+ intrinsicMainSize(child, false, innerH);
255+ cross = resolveSizeValue(cProps?.height, innerH) ?? innerH;
256+ }
257+
258+ // Apply constraints
259+ if (cProps) {
260+ const minMain = isVertical
261+ ? (cProps.minHeight ?? 0)
262+ : (cProps.minWidth ?? 0);
263+ const maxMain = isVertical
264+ ? (cProps.maxHeight ?? Infinity)
265+ : (cProps.maxWidth ?? Infinity);
266+ main = clamp(main, minMain, maxMain);
267+ }
268+
269+ fixedMain += main;
270+ infos.push({ node: child, mainSize: main, crossSize: cross, flex });
271+ }
272+ }
273+
274+ // --- Flex distribution ---
275+ const flexSpace = Math.max(0, mainAvail - fixedMain);
276+
277+ if (totalFlex > 0) {
278+ const flexInfos = infos.filter((c) => c.flex > 0);
279+ const rawSizes = flexInfos.map((c) => (c.flex / totalFlex) * flexSpace);
280+ const rounded = largestRemainder(rawSizes, flexSpace);
281+
282+ for (let i = 0; i < flexInfos.length; i++) {
283+ let size = rounded[i]!;
284+ const cProps = getProps(flexInfos[i]!.node);
285+ if (cProps) {
286+ const minMain = isVertical
287+ ? (cProps.minHeight ?? 0)
288+ : (cProps.minWidth ?? 0);
289+ const maxMain = isVertical
290+ ? (cProps.maxHeight ?? Infinity)
291+ : (cProps.maxWidth ?? Infinity);
292+ size = clamp(size, minMain, maxMain);
293+ }
294+ flexInfos[i]!.mainSize = size;
295+ }
296+ }
297+
298+ // --- Position phase ---
299+ const layoutChildren: LayoutNode[] = [];
300+ let mainOffset = 0;
301+
302+ for (let i = 0; i < infos.length; i++) {
303+ const info = infos[i]!;
304+ const childX = isVertical ? innerX : innerX + mainOffset;
305+ const childY = isVertical ? innerY + mainOffset : innerY;
306+ const childW = isVertical ? info.crossSize : info.mainSize;
307+ const childH = isVertical ? info.mainSize : info.crossSize;
308+
309+ layoutChildren.push(layoutNode(info.node, childX, childY, childW, childH));
310+
311+ mainOffset += info.mainSize;
312+ if (i < infos.length - 1) mainOffset += gap;
313+ }
314+
315+ // --- Intrinsic container sizing ---
316+ // If no explicit main-axis size, shrink to fit children
317+ const hasExplicitMain = isVertical
318+ ? props.height !== undefined || props.flex !== undefined
319+ : props.width !== undefined || props.flex !== undefined;
320+
321+ if (!hasExplicitMain) {
322+ const contentMain = mainOffset + (isVertical ? padY * 2 : padX * 2);
323+ if (isVertical) {
324+ rect.height = contentMain;
325+ } else {
326+ rect.width = contentMain;
327+ }
328+ }
329+
330+ return { node, rect, children: layoutChildren };
331+}