xonecas.io
70160
Ce

cel-tui / files

cel-tui / packages / core / src / layout.ts

28.0 KB
1import type { ContainerProps, Node, SizeValue } from "@cel-tui/types";
2import { measureTextLineCount } from "./text-layout.js";
3import { visibleWidth } from "./width.js";
4
5/**
6 * A rectangle in absolute screen coordinates.
7 */
8export interface Rect {
9  x: number;
10  y: number;
11  width: number;
12  height: number;
13}
14
15/**
16 * A node in the layout tree with computed position and size.
17 */
18export interface LayoutNode {
19  /** The original UI node. */
20  node: Node;
21  /** Computed absolute screen rect. */
22  rect: Rect;
23  /** Laid-out children (empty for leaf nodes). */
24  children: LayoutNode[];
25}
26
27// --- Helpers ---
28
29function resolveSizeValue(
30  value: SizeValue | undefined,
31  parentSize: number,
32): number | undefined {
33  if (value === undefined) return undefined;
34  if (typeof value === "number") return value;
35  const match = value.match(/^(\d+(?:\.\d+)?)%$/);
36  if (match) {
37    const percentage = match[1];
38    if (percentage === undefined) {
39      throw new Error(`Invalid percentage size: ${value}`);
40    }
41    return Math.floor((parentSize * parseFloat(percentage)) / 100);
42  }
43  return undefined;
44}
45
46function clamp(value: number, min: number, max: number): number {
47  return Math.max(min, Math.min(max, value));
48}
49
50function getProps(node: Node): ContainerProps | null {
51  if (node.type === "text") return null;
52  return node.props;
53}
54
55function getNodeFlex(node: Node, isVertical: boolean): number {
56  const explicitFlex = getProps(node)?.flex;
57  if (explicitFlex && explicitFlex > 0) {
58    return explicitFlex;
59  }
60  if (
61    !isVertical &&
62    node.type === "text" &&
63    node.props.repeat === "fill" &&
64    visibleWidth(node.content) > 0
65  ) {
66    return 1;
67  }
68  return 0;
69}
70
71function requiredAt<T>(
72  items: readonly T[],
73  index: number,
74  description: string,
75): T {
76  const item = items[index];
77  if (item === undefined) {
78    throw new Error(`Missing ${description} at index ${index}`);
79  }
80  return item;
81}
82
83function getMainAxisGap(
84  gap: number,
85  justify: ContainerProps["justifyContent"] | undefined,
86): number {
87  return justify === "space-between" ? 0 : gap;
88}
89
90// --- Intrinsic size computation ---
91
92/**
93 * Compute intrinsic main-axis size for a node (before layout).
94 * Used by the parent to determine how much space to allocate.
95 */
96function intrinsicMainSize(
97  node: Node,
98  isVertical: boolean,
99  crossSize: number,
100): number {
101  if (node.type === "text") {
102    if (isVertical) {
103      return measureTextLineCount(
104        node.content,
105        Math.max(1, crossSize),
106        node.props.wrap ?? "none",
107      );
108    }
109    // Width (intrinsic)
110    if (node.props.repeat === "fill") return 0;
111    const lines = node.content.split("\n");
112    let maxW = 0;
113    for (const line of lines) {
114      const w = visibleWidth(line);
115      if (w > maxW) maxW = w;
116    }
117    if (typeof node.props.repeat === "number") maxW *= node.props.repeat;
118    return maxW;
119  }
120
121  if (node.type === "textinput") {
122    const tiPadX = (node.props.padding?.x ?? 0) * 2;
123    const tiPadY = (node.props.padding?.y ?? 0) * 2;
124    if (isVertical) {
125      const val = node.props.value || "";
126      const innerCrossForTI = Math.max(1, crossSize - tiPadX);
127      return measureTextLineCount(val, innerCrossForTI, "word") + tiPadY;
128    }
129    return 0 + tiPadX;
130  }
131
132  // Container: compute intrinsic size along the requested axis.
133  // If the requested axis matches the container's main axis, sum children + gaps.
134  // If it's the cross axis, take the max of children on that axis.
135  const props = node.props;
136  const gap = props.gap ?? 0;
137  const mainAxisGap = getMainAxisGap(gap, props.justifyContent);
138  const containerIsVertical = node.type === "vstack";
139  const axisMatchesMain = isVertical === containerIsVertical;
140
141  const padMain = isVertical
142    ? (props.padding?.y ?? 0) * 2
143    : (props.padding?.x ?? 0) * 2;
144  const padCross = isVertical
145    ? (props.padding?.x ?? 0) * 2
146    : (props.padding?.y ?? 0) * 2;
147  const innerCross = Math.max(0, crossSize - padCross);
148
149  if (axisMatchesMain) {
150    // Sum children along the main axis + gaps
151    let total = 0;
152    for (let i = 0; i < node.children.length; i++) {
153      const child = requiredAt(node.children, i, "child node");
154      const cProps = getProps(child);
155
156      let childMain: number;
157      if (isVertical) {
158        childMain =
159          resolveSizeValue(cProps?.height, 0) ??
160          intrinsicMainSize(child, true, innerCross);
161      } else {
162        childMain =
163          resolveSizeValue(cProps?.width, 0) ??
164          intrinsicMainSize(child, false, innerCross);
165      }
166      if (cProps) {
167        const minMain = isVertical
168          ? (cProps.minHeight ?? 0)
169          : (cProps.minWidth ?? 0);
170        const maxMain = isVertical
171          ? (cProps.maxHeight ?? Infinity)
172          : (cProps.maxWidth ?? Infinity);
173        childMain = clamp(childMain, minMain, maxMain);
174      }
175      total += childMain;
176      if (i < node.children.length - 1) total += mainAxisGap;
177    }
178    return total + padMain;
179  }
180
181  // Special case: wrapping HStack computing intrinsic height.
182  // Instead of max-of-children, simulate the row layout and sum row heights.
183  if (
184    node.type === "hstack" &&
185    (node.props as ContainerProps).flexWrap === "wrap"
186  ) {
187    const wrapRows = measureWrapRows(node.children, {
188      availableHeight: 0,
189      availableWidth: innerCross,
190      intrinsicWidthCrossSize: innerCross,
191      itemGap: mainAxisGap,
192    });
193    let total = 0;
194    for (let ri = 0; ri < wrapRows.length; ri++) {
195      total += requiredAt(wrapRows, ri, "measured wrap row").height;
196      if (ri < wrapRows.length - 1) total += gap;
197    }
198    return total + padMain;
199  }
200
201  // Cross axis: max of children on the requested axis
202  let maxSize = 0;
203  for (const child of node.children) {
204    const cProps = getProps(child);
205
206    let childSize: number;
207    if (isVertical) {
208      childSize =
209        resolveSizeValue(cProps?.height, 0) ??
210        intrinsicMainSize(child, true, innerCross);
211    } else {
212      childSize =
213        resolveSizeValue(cProps?.width, 0) ??
214        intrinsicMainSize(child, false, innerCross);
215    }
216    // Apply child's cross-axis constraints (e.g. maxHeight on a TextInput
217    // inside an HStack) so the container's intrinsic size respects them.
218    if (cProps) {
219      const minCross = isVertical
220        ? (cProps.minHeight ?? 0)
221        : (cProps.minWidth ?? 0);
222      const maxCross = isVertical
223        ? (cProps.maxHeight ?? Infinity)
224        : (cProps.maxWidth ?? Infinity);
225      childSize = clamp(childSize, minCross, maxCross);
226    }
227    if (childSize > maxSize) maxSize = childSize;
228  }
229  return maxSize + padMain;
230}
231
232// --- Wrap row assignment ---
233
234/**
235 * Assign children to rows for a wrapping HStack.
236 * Children are placed left-to-right; when adding the next child (plus gap)
237 * would exceed availWidth, a new row begins. A child wider than the
238 * container still gets its own row.
239 */
240function assignWrapRows(
241  widths: number[],
242  availWidth: number,
243  gap: number,
244): number[][] {
245  if (widths.length === 0) return [];
246  const rows: number[][] = [];
247  let currentRow: number[] = [];
248  let rowWidth = 0;
249
250  for (let i = 0; i < widths.length; i++) {
251    const w = requiredAt(widths, i, "wrap width");
252    if (currentRow.length === 0) {
253      currentRow.push(i);
254      rowWidth = w;
255    } else {
256      const needed = rowWidth + gap + w;
257      if (needed > availWidth) {
258        rows.push(currentRow);
259        currentRow = [i];
260        rowWidth = w;
261      } else {
262        currentRow.push(i);
263        rowWidth = needed;
264      }
265    }
266  }
267  if (currentRow.length > 0) rows.push(currentRow);
268  return rows;
269}
270
271// --- Largest remainder rounding ---
272
273function largestRemainder(fractions: number[], total: number): number[] {
274  const floored = fractions.map(Math.floor);
275  let remainder = total - floored.reduce((a, b) => a + b, 0);
276
277  const indices = fractions
278    .map((v, i) => ({ i, frac: v - Math.floor(v) }))
279    .sort((a, b) => b.frac - a.frac);
280
281  for (const { i } of indices) {
282    if (remainder <= 0) break;
283    const value = requiredAt(floored, i, "rounded size");
284    floored[i] = value + 1;
285    remainder--;
286  }
287
288  return floored;
289}
290
291interface FlexAllocationItem {
292  flex: number;
293  min: number;
294  max: number;
295}
296
297function allocateFlexSizes(
298  items: readonly FlexAllocationItem[],
299  total: number,
300): number[] {
301  const sizes = Array.from({ length: items.length }, () => 0);
302  let remainingIndices = items.map((_, index) => index);
303  let remainingSpace = total;
304  let remainingFlex = items.reduce((sum, item) => sum + item.flex, 0);
305
306  while (remainingIndices.length > 0 && remainingFlex > 0) {
307    const rawSizes = remainingIndices.map((index) => {
308      const item = requiredAt(items, index, "flex allocation item");
309      return (item.flex / remainingFlex) * remainingSpace;
310    });
311
312    const minClamped = new Set<number>();
313
314    for (let i = 0; i < remainingIndices.length; i++) {
315      const index = requiredAt(remainingIndices, i, "flex allocation index");
316      const rawSize = requiredAt(rawSizes, i, "raw flex size");
317      const item = requiredAt(items, index, "flex allocation item");
318
319      if (rawSize < item.min) {
320        sizes[index] = item.min;
321        remainingSpace -= item.min;
322        remainingFlex -= item.flex;
323        minClamped.add(index);
324      }
325    }
326
327    if (minClamped.size === 0) {
328      const rounded = largestRemainder(rawSizes, remainingSpace);
329      for (let i = 0; i < remainingIndices.length; i++) {
330        const index = requiredAt(remainingIndices, i, "flex allocation index");
331        sizes[index] = requiredAt(rounded, i, "rounded flex size");
332      }
333      break;
334    }
335
336    remainingIndices = remainingIndices.filter(
337      (index) => !minClamped.has(index),
338    );
339  }
340
341  let activeIndices = items.map((_, index) => index);
342  let activeFlex = items.reduce((sum, item) => sum + item.flex, 0);
343
344  while (activeIndices.length > 0 && activeFlex > 0) {
345    let excess = 0;
346    const maxClamped = new Set<number>();
347
348    for (const index of activeIndices) {
349      const item = requiredAt(items, index, "flex allocation item");
350      const max = Math.max(item.min, item.max);
351      const size = requiredAt(sizes, index, "allocated flex size");
352
353      if (size > max) {
354        sizes[index] = max;
355        excess += size - max;
356        activeFlex -= item.flex;
357        maxClamped.add(index);
358      }
359    }
360
361    if (maxClamped.size === 0) {
362      return sizes;
363    }
364
365    activeIndices = activeIndices.filter((index) => !maxClamped.has(index));
366    if (activeIndices.length === 0 || activeFlex <= 0 || excess <= 0) {
367      return sizes;
368    }
369
370    const rawExtras = activeIndices.map((index) => {
371      const item = requiredAt(items, index, "flex allocation item");
372      return (item.flex / activeFlex) * excess;
373    });
374    const rounded = largestRemainder(rawExtras, excess);
375
376    for (let i = 0; i < activeIndices.length; i++) {
377      const index = requiredAt(activeIndices, i, "flex allocation index");
378      sizes[index] += requiredAt(rounded, i, "rounded flex size");
379    }
380  }
381
382  return sizes;
383}
384
385interface WrapMeasurementOptions {
386  availableHeight: number;
387  availableWidth: number;
388  /**
389   * Cross-size hint used only while finding a non-flex child's intrinsic width.
390   * Intrinsic-height callers do not have a definite height, so this can differ
391   * from the available height.
392   */
393  intrinsicWidthCrossSize: number;
394  itemGap: number;
395}
396
397interface MeasuredWrapRow {
398  childHeights: number[];
399  childIndices: number[];
400  childWidths: number[];
401  height: number;
402}
403
404/**
405 * Assign wrapping HStack children to rows, allocate each row's flex widths,
406 * then measure child heights at those final widths.
407 */
408function measureWrapRows(
409  children: readonly Node[],
410  options: WrapMeasurementOptions,
411): MeasuredWrapRow[] {
412  const baseWidths: number[] = [];
413  const flexValues: number[] = [];
414
415  for (const child of children) {
416    const cProps = getProps(child);
417    const flex = getNodeFlex(child, false);
418    flexValues.push(flex);
419
420    let baseWidth: number;
421    if (flex > 0) {
422      // Flex children use minWidth for row assignment (like CSS flex-basis).
423      baseWidth = cProps?.minWidth ?? 0;
424    } else {
425      baseWidth =
426        resolveSizeValue(cProps?.width, options.availableWidth) ??
427        intrinsicMainSize(child, false, options.intrinsicWidthCrossSize);
428      if (cProps) {
429        baseWidth = clamp(
430          baseWidth,
431          cProps.minWidth ?? 0,
432          cProps.maxWidth ?? Infinity,
433        );
434      }
435    }
436    baseWidths.push(baseWidth);
437  }
438
439  const rowIndices = assignWrapRows(
440    baseWidths,
441    options.availableWidth,
442    options.itemGap,
443  );
444
445  return rowIndices.map((childIndices) => {
446    const rowGapTotal = options.itemGap * (childIndices.length - 1);
447    const rowAvailableWidth = options.availableWidth - rowGapTotal;
448    let fixedWidth = 0;
449    const flexPositions: number[] = [];
450    const childWidths = childIndices.map((childIndex, position) => {
451      if (requiredAt(flexValues, childIndex, "flex value") > 0) {
452        flexPositions.push(position);
453        return 0;
454      }
455
456      const width = requiredAt(baseWidths, childIndex, "base width");
457      fixedWidth += width;
458      return width;
459    });
460
461    if (flexPositions.length > 0) {
462      const allocated = allocateFlexSizes(
463        flexPositions.map((position) => {
464          const childIndex = requiredAt(
465            childIndices,
466            position,
467            "wrap row index",
468          );
469          const cProps = getProps(
470            requiredAt(children, childIndex, "child node"),
471          );
472          return {
473            flex: requiredAt(flexValues, childIndex, "flex value"),
474            min: cProps?.minWidth ?? 0,
475            max: cProps?.maxWidth ?? Infinity,
476          };
477        }),
478        Math.max(0, rowAvailableWidth - fixedWidth),
479      );
480
481      for (let index = 0; index < flexPositions.length; index++) {
482        const position = requiredAt(flexPositions, index, "flex position");
483        childWidths[position] = requiredAt(
484          allocated,
485          index,
486          "allocated flex size",
487        );
488      }
489    }
490
491    let height = 0;
492    const childHeights = childIndices.map((childIndex, position) => {
493      const child = requiredAt(children, childIndex, "child node");
494      const cProps = getProps(child);
495      const childWidth = requiredAt(childWidths, position, "child width");
496      let childHeight =
497        resolveSizeValue(cProps?.height, options.availableHeight) ??
498        intrinsicMainSize(child, true, childWidth);
499
500      if (cProps) {
501        childHeight = clamp(
502          childHeight,
503          cProps.minHeight ?? 0,
504          cProps.maxHeight ?? Infinity,
505        );
506      }
507      height = Math.max(height, childHeight);
508      return childHeight;
509    });
510
511    return { childHeights, childIndices, childWidths, height };
512  });
513}
514
515// --- Main layout ---
516
517/**
518 * Measure a node tree's intrinsic content height at the provided width.
519 *
520 * This is a content-measurement helper, not a viewport/clipping helper.
521 * The caller-provided `width` is the authoritative wrapping width for the
522 * measured subtree. Measurement starts at the given node, ignores that
523 * node's own main-axis height constraints, and walks downward through its
524 * descendants. Descendant sizing rules still apply normally.
525 *
526 * Use this for intrinsically sized content such as scrollback/message
527 * history chunks. If a wrapper's visible height is controlled by `height`,
528 * `flex`, or percentage sizing, measure the content subtree inside that
529 * wrapper instead.
530 *
531 * @example
532 * ```ts
533 * const addedHeight = measureContentHeight(
534 *   VStack({}, olderMessages.map(renderMessage)),
535 *   { width: historyContentWidth },
536 * );
537 *
538 * scrollOffset += addedHeight;
539 * ```
540 */
541export function measureContentHeight(
542  node: Node,
543  options: { width: number },
544): number {
545  return intrinsicMainSize(node, true, options.width);
546}
547
548/**
549 * Compute the layout for a UI tree.
550 *
551 * @param root - The root UI node.
552 * @param availWidth - Available width (typically terminal columns).
553 * @param availHeight - Available height (typically terminal rows).
554 * @returns Layout tree with computed rects.
555 */
556export function layout(
557  root: Node,
558  availWidth: number,
559  availHeight: number,
560): LayoutNode {
561  // Resolve root's own size against the viewport
562  const rootProps = getProps(root);
563  const rootW = resolveSizeValue(rootProps?.width, availWidth) ?? availWidth;
564  const rootH = resolveSizeValue(rootProps?.height, availHeight) ?? availHeight;
565  return layoutNode(root, 0, 0, rootW, rootH);
566}
567
568/**
569 * Layout a wrapping HStack. Children are assigned to rows based on their
570 * base widths, then each row is laid out as an independent flex context.
571 */
572function layoutWrapHStack(
573  node: Node,
574  rect: Rect,
575  props: ContainerProps,
576  children: Node[],
577  x: number,
578  y: number,
579  width: number,
580  height: number,
581): LayoutNode {
582  const gap = props.gap ?? 0;
583  const align = props.alignItems ?? "stretch";
584  const justify = props.justifyContent ?? "start";
585  const itemGap = getMainAxisGap(gap, justify);
586
587  // Padding
588  const padX = props.padding?.x ?? 0;
589  const padY = props.padding?.y ?? 0;
590  const innerX = x + padX;
591  const innerY = y + padY;
592  const innerW = Math.max(0, width - padX * 2);
593  const innerH = Math.max(0, height - padY * 2);
594
595  const rows = measureWrapRows(children, {
596    availableHeight: innerH,
597    availableWidth: innerW,
598    intrinsicWidthCrossSize: innerH,
599    itemGap,
600  });
601
602  // Layout each measured row independently.
603  const layoutChildren: LayoutNode[] = [];
604  let rowY = 0;
605
606  for (let ri = 0; ri < rows.length; ri++) {
607    const row = requiredAt(rows, ri, "measured wrap row");
608    const rowIdx = row.childIndices;
609    const childWidths = row.childWidths;
610    const crossSizes = row.childHeights;
611    const rowHeight = row.height;
612    const rowGapTotal = itemGap * (rowIdx.length - 1);
613
614    // justifyContent: compute main-axis starting offset
615    let totalUsedWidth = rowGapTotal;
616    for (let ci = 0; ci < rowIdx.length; ci++) {
617      totalUsedWidth += requiredAt(childWidths, ci, "child width");
618    }
619    const remainingMain = Math.max(0, innerW - totalUsedWidth);
620
621    let mainStart = 0;
622    let betweenGaps: number[] | null = null;
623
624    if (justify === "end") {
625      mainStart = remainingMain;
626    } else if (justify === "center") {
627      mainStart = Math.floor(remainingMain / 2);
628    } else if (justify === "space-between" && rowIdx.length > 1) {
629      const gapCount = rowIdx.length - 1;
630      const rawGaps = Array.from(
631        { length: gapCount },
632        () => remainingMain / gapCount,
633      );
634      betweenGaps = largestRemainder(rawGaps, remainingMain);
635    }
636
637    // Position children in this row
638    let xOffset = mainStart;
639    for (let ci = 0; ci < rowIdx.length; ci++) {
640      const idx = requiredAt(rowIdx, ci, "wrap row index");
641      const childW = requiredAt(childWidths, ci, "child width");
642
643      // Cross-axis sizing: stretch fills row height, others keep their size
644      let childH: number;
645      if (align === "stretch") {
646        const cProps = getProps(requiredAt(children, idx, "child node"));
647        const explicitH = resolveSizeValue(cProps?.height, innerH);
648        childH =
649          explicitH === undefined
650            ? clamp(
651                rowHeight,
652                cProps?.minHeight ?? 0,
653                cProps?.maxHeight ?? Infinity,
654              )
655            : requiredAt(crossSizes, ci, "cross size");
656      } else {
657        childH = requiredAt(crossSizes, ci, "cross size");
658      }
659
660      // Cross-axis alignment within the row
661      let crossOffset = 0;
662      if (align === "center") {
663        crossOffset = Math.floor((rowHeight - childH) / 2);
664      } else if (align === "end") {
665        crossOffset = rowHeight - childH;
666      }
667
668      const childX = innerX + xOffset;
669      const childY = innerY + rowY + crossOffset;
670
671      layoutChildren.push(
672        layoutNode(
673          requiredAt(children, idx, "child node"),
674          childX,
675          childY,
676          childW,
677          childH,
678        ),
679      );
680
681      xOffset += childW;
682      if (ci < rowIdx.length - 1) {
683        xOffset += itemGap;
684        if (betweenGaps) {
685          xOffset += requiredAt(betweenGaps, ci, "justified gap");
686        }
687      }
688    }
689
690    rowY += rowHeight;
691    if (ri < rows.length - 1) {
692      rowY += gap;
693    }
694  }
695
696  // Intrinsic height: if no explicit height, shrink to fit all rows
697  const hasExplicitHeight =
698    props.height !== undefined || props.flex !== undefined;
699  if (!hasExplicitHeight) {
700    rect.height = rowY + padY * 2;
701  }
702
703  return { node, rect, children: layoutChildren };
704}
705
706/**
707 * Layout a node within the given available space.
708 * Resolves the node's own explicit size (if any) against available space,
709 * then lays out children within that.
710 */
711function layoutNode(
712  node: Node,
713  x: number,
714  y: number,
715  availWidth: number,
716  availHeight: number,
717): LayoutNode {
718  // Resolve own dimensions: explicit size wins, otherwise fill available.
719  // Note: for children, the parent has already resolved sizing and passes
720  // the result as availWidth/availHeight. We only re-resolve for the root
721  // node (where available space = viewport, not pre-resolved).
722  const width = availWidth;
723  const height = availHeight;
724  const rect: Rect = { x, y, width, height };
725
726  // Leaf nodes
727  if (node.type === "text" || node.type === "textinput") {
728    return { node, rect, children: [] };
729  }
730
731  // Container nodes
732  const props = node.props;
733  const isVertical = node.type === "vstack";
734  const children = node.children;
735
736  if (children.length === 0) {
737    return { node, rect, children: [] };
738  }
739
740  // Wrapping HStack: separate layout path
741  if (node.type === "hstack" && props.flexWrap === "wrap") {
742    return layoutWrapHStack(node, rect, props, children, x, y, width, height);
743  }
744
745  // Padding
746  const padX = props.padding?.x ?? 0;
747  const padY = props.padding?.y ?? 0;
748  const innerX = x + padX;
749  const innerY = y + padY;
750  const innerW = Math.max(0, width - padX * 2);
751  const innerH = Math.max(0, height - padY * 2);
752
753  // Gap
754  const gap = props.gap ?? 0;
755  const justify = props.justifyContent ?? "start";
756  const mainAxisGap = getMainAxisGap(gap, justify);
757  const totalGap = mainAxisGap * (children.length - 1);
758  const mainAvail = (isVertical ? innerH : innerW) - totalGap;
759
760  // --- Measure phase: compute each child's main-axis and cross-axis size ---
761  type ChildInfo = {
762    node: Node;
763    mainSize: number;
764    crossSize: number;
765    flex: number;
766  };
767  const infos: ChildInfo[] = [];
768  let fixedMain = 0;
769  let totalFlex = 0;
770  const align = props.alignItems ?? "stretch";
771  const useIntrinsicCross = align !== "stretch";
772
773  for (const child of children) {
774    const cProps = getProps(child);
775    const flex = getNodeFlex(child, isVertical);
776
777    if (flex > 0) {
778      totalFlex += flex;
779      // Cross-axis: explicit size, or intrinsic if not stretch, or fill
780      let cross: number;
781      if (isVertical) {
782        cross =
783          resolveSizeValue(cProps?.width, innerW) ??
784          (useIntrinsicCross
785            ? intrinsicMainSize(child, false, innerH)
786            : innerW);
787      } else {
788        cross =
789          resolveSizeValue(cProps?.height, innerH) ??
790          (useIntrinsicCross ? intrinsicMainSize(child, true, innerW) : innerH);
791      }
792      // Apply cross-axis constraints
793      if (cProps) {
794        const minCross = isVertical
795          ? (cProps.minWidth ?? 0)
796          : (cProps.minHeight ?? 0);
797        const maxCross = isVertical
798          ? (cProps.maxWidth ?? Infinity)
799          : (cProps.maxHeight ?? Infinity);
800        cross = clamp(cross, minCross, maxCross);
801      }
802      infos.push({ node: child, mainSize: 0, crossSize: cross, flex });
803    } else {
804      // Main-axis: explicit → percentage → intrinsic
805      let main: number;
806      let cross: number;
807      if (isVertical) {
808        main =
809          resolveSizeValue(cProps?.height, innerH) ??
810          intrinsicMainSize(child, true, innerW);
811        cross =
812          resolveSizeValue(cProps?.width, innerW) ??
813          (useIntrinsicCross
814            ? intrinsicMainSize(child, false, innerH)
815            : innerW);
816      } else {
817        main =
818          resolveSizeValue(cProps?.width, innerW) ??
819          intrinsicMainSize(child, false, innerH);
820        cross =
821          resolveSizeValue(cProps?.height, innerH) ??
822          (useIntrinsicCross ? intrinsicMainSize(child, true, innerW) : innerH);
823      }
824
825      // Apply main-axis constraints
826      if (cProps) {
827        const minMain = isVertical
828          ? (cProps.minHeight ?? 0)
829          : (cProps.minWidth ?? 0);
830        const maxMain = isVertical
831          ? (cProps.maxHeight ?? Infinity)
832          : (cProps.maxWidth ?? Infinity);
833        main = clamp(main, minMain, maxMain);
834      }
835      // Apply cross-axis constraints
836      if (cProps) {
837        const minCross = isVertical
838          ? (cProps.minWidth ?? 0)
839          : (cProps.minHeight ?? 0);
840        const maxCross = isVertical
841          ? (cProps.maxWidth ?? Infinity)
842          : (cProps.maxHeight ?? Infinity);
843        cross = clamp(cross, minCross, maxCross);
844      }
845
846      fixedMain += main;
847      infos.push({ node: child, mainSize: main, crossSize: cross, flex });
848    }
849  }
850
851  // --- Flex distribution ---
852  const flexSpace = Math.max(0, mainAvail - fixedMain);
853
854  if (totalFlex > 0) {
855    const flexInfos = infos.filter((c) => c.flex > 0);
856    const allocated = allocateFlexSizes(
857      flexInfos.map((info) => {
858        const cProps = getProps(info.node);
859        return {
860          flex: info.flex,
861          min: isVertical ? (cProps?.minHeight ?? 0) : (cProps?.minWidth ?? 0),
862          max: isVertical
863            ? (cProps?.maxHeight ?? Infinity)
864            : (cProps?.maxWidth ?? Infinity),
865        };
866      }),
867      flexSpace,
868    );
869
870    for (let i = 0; i < flexInfos.length; i++) {
871      requiredAt(flexInfos, i, "flex child info").mainSize = requiredAt(
872        allocated,
873        i,
874        "allocated flex size",
875      );
876    }
877  }
878
879  // --- Position phase ---
880
881  // Compute total main-axis content size (children + gaps)
882  const totalChildMain = infos.reduce((sum, c) => sum + c.mainSize, 0);
883  const totalContent = totalChildMain + totalGap;
884  const mainInner = isVertical ? innerH : innerW;
885  const crossInner = isVertical ? innerW : innerH;
886  const remainingMain = Math.max(0, mainInner - totalContent);
887
888  // justifyContent: compute main-axis starting offset and per-gap extra space
889  let mainStart = 0;
890  let betweenGaps: number[] | null = null;
891
892  if (justify === "end") {
893    mainStart = remainingMain;
894  } else if (justify === "center") {
895    mainStart = Math.floor(remainingMain / 2);
896  } else if (justify === "space-between" && infos.length > 1) {
897    // Distribute remaining space into gaps between children
898    const gapCount = infos.length - 1;
899    const rawGaps = Array.from(
900      { length: gapCount },
901      () => remainingMain / gapCount,
902    );
903    betweenGaps = largestRemainder(rawGaps, remainingMain);
904  }
905
906  const layoutChildren: LayoutNode[] = [];
907  let mainOffset = mainStart;
908
909  for (let i = 0; i < infos.length; i++) {
910    const info = requiredAt(infos, i, "child layout info");
911
912    // Cross-axis alignment
913    let crossOffset = 0;
914    if (align === "center") {
915      crossOffset = Math.floor((crossInner - info.crossSize) / 2);
916    } else if (align === "end") {
917      crossOffset = crossInner - info.crossSize;
918    }
919    // "start" and "stretch" keep crossOffset = 0
920
921    const childX = isVertical ? innerX + crossOffset : innerX + mainOffset;
922    const childY = isVertical ? innerY + mainOffset : innerY + crossOffset;
923    const childW = isVertical ? info.crossSize : info.mainSize;
924    const childH = isVertical ? info.mainSize : info.crossSize;
925
926    layoutChildren.push(layoutNode(info.node, childX, childY, childW, childH));
927
928    mainOffset += info.mainSize;
929    if (i < infos.length - 1) {
930      mainOffset += mainAxisGap;
931      if (betweenGaps) {
932        mainOffset += requiredAt(betweenGaps, i, "justified gap");
933      }
934    }
935  }
936
937  // --- Intrinsic container sizing ---
938  // If no explicit main-axis size, shrink to fit children
939  const hasExplicitMain = isVertical
940    ? props.height !== undefined || props.flex !== undefined
941    : props.width !== undefined || props.flex !== undefined;
942
943  if (!hasExplicitMain) {
944    const contentMain = mainOffset + (isVertical ? padY * 2 : padX * 2);
945    if (isVertical) {
946      rect.height = contentMain;
947    } else {
948      rect.width = contentMain;
949    }
950  }
951
952  return { node, rect, children: layoutChildren };
953}