Skip to content

packages/core/src/lib/layout/grid.ts

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import { withAllocationCheckpoint } from './allocation-checkpoint.js';
2 import { contentBoxStyle } from './box-sizing.js';
3 import { canvasMeasurementService } from './canvas-measurement.js';
4 import { nativeLayout, LayoutRegion, mountedLayoutRegion, recordWasmAllocationPass, recordWasmAllocationItem, recordWasmAllocationCacheHit } from './wasm/region.js';
5 import { prepareKnownLayoutDescendants, registerKnownLayoutPreflight, claimPreparedLayoutPlan, stagePreparedLayoutPlan, preparePlacedKnownLayout, type PreparedLayoutPlan } from './prepared-root.js';
6 import { getStyleMeasurementMode, preparedStyleValue, preparedStyleQuery } from '../style/responsive.js';
7 import { definePrimitive } from '../define-primitive.js';
8 import { clonePibblElement } from '../element/create-element.js';
9 import { getChildPrimitiveReceiverToken } from '../element/metadata.js';
10 import type { PibblElement } from '../element/types.js';
11 import { GLOBAL_STATE } from '../global-state.js';
12 import { layoutDiagnostic } from '../style/diagnostics.js';
13 import {
14   type PibblStructuralEventProps,
15   wireStructuralEvents,
16 } from '../components/structural-events.js';
17 import { normalizeBoxInsets, hasPercentageBoxPadding, resolveAllocatedInsets } from './box-insets.js';
18 import { isFitContent, resolveScalarSizingLength, type FitContent, type SizingKeyword } from '../style/sizing-length.js';
19 import { setPreNormalizedStyle, registerOpaqueStyleProperties } from '../style/resolve-dispatch.js';
20 import type {
21   BoxStyle,
22   GridItemStyle,
23   LayoutItemStyle,
24   ResolvedBoxStyle,
25 } from '../style/types.js';
26 import type {
27   CanvasMeasurementService,
28   PibblNodeInput,
29   MeasureInput,
30   MeasureResult,
31   RenderingContext2D,
32   SystemStyle,
33 } from '../types.js';
34 import {
35   childWithUsedSize,
36   prepareDirectChildStyle,
37   materializeLayoutChildren,
38   placeDirectChildren,
39   prepareLayoutChildren,
40   resolveContainerBox,
41   resolveDirectChildBox,
42 } from './absolute.js';
43 import { getLayoutDirection, pushLayoutBox, resolvePositionedContainingBox } from './context.js';
44 import { recordLayoutEvaluation } from './diagnostics.js';
45 import { assertSupportedChildPosition } from './positioning-diagnostics.js';
46 import { measureElement, measureIntrinsicElement } from './measure.js';
47 import { resolveAbsoluteFlexPlacement } from './flex.js';
48 import { GRID_V2_TRACK_STRIDE } from './grid-kernel.js';
49 import type { Constraints, LayoutBox } from './types.js';
50 const unsupportedProperties = ['gridColumnEnd', 'gridRowEnd', 'gridArea', 'order'] as const;
51 
52 
53 
54 /** A scalar, fractional, or intrinsic breadth accepted by a Grid track.
55  *
56  * @see {@link GridTrack}
57  */
58 export type GridTrackBreadth = number | `${number}%` | `${number}fr` | SizingKeyword | FitContent | 'auto';
59 
60 /** A bounded Grid track whose minimum and maximum are resolved by the Grid owner.
61  *
62  * @see {@link GridTrack}
63  */
64 export interface GridMinMaxTrack {
65   /** Identifies the bounded track definition. See {@link GridMinMaxTrack}. */
66   readonly kind: 'minmax';
67   /** Minimum track breadth. See {@link GridTrackBreadth}. */
68   readonly min: GridTrackBreadth;
69   /** Maximum track breadth. See {@link GridTrackBreadth}. */
70   readonly max: GridTrackBreadth;
71 }
72 
73 /** A repeated {@link GridTrack} list. `auto-fill` and `auto-fit` use the available axis size. */
74 export interface GridRepeatTrack {
75   /** Identifies the repetition definition. See {@link GridRepeatTrack}. */
76   readonly kind: 'repeat';
77   /** Fixed count or automatic fill/fit policy. See {@link GridRepeatTrack}. */
78   readonly count: number | 'auto-fill' | 'auto-fit';
79   /** Ordered pattern to repeat. See {@link GridTrack}. */
80   readonly tracks: readonly GridTrack[];
81 }
82 
83 /** A fixed logical size, percentage, fraction, intrinsic breadth, minmax, or repeat track. See {@link GridTrackBreadth}, {@link GridMinMaxTrack}, {@link GridRepeatTrack}. */
84 export type GridTrack = GridTrackBreadth | GridMinMaxTrack | GridRepeatTrack;
85 
86 /** Creates an immutable bounded Grid track.
87  * @param options - The minimum and maximum breadths.
88  * @returns An immutable `minmax` track definition.
89  * @see {@link GridTrack}
90  */
91 export function minmax(options: Readonly<{ min: GridTrackBreadth; max: GridTrackBreadth }>): GridMinMaxTrack {
92   return Object.freeze({ kind: 'minmax' as const, min: options.min, max: options.max });
93 }
94 
95 /** Repeats Grid tracks a fixed number of times.
96  * @param tracks - The track sequence to repeat.
97  * @param options - The repeat count.
98  * @returns An immutable repeated track definition.
99  * @see {@link GridTrack}
100  */
101 export function repeatTracks(tracks: readonly GridTrack[], options: Readonly<{ count: number }>): GridRepeatTrack {
102   return Object.freeze({ kind: 'repeat' as const, count: options.count, tracks: Object.freeze([...tracks]) });
103 }
104 
105 /** Repeats Grid tracks to fill the available axis.
106  * @param tracks - The track sequence to repeat.
107  * @returns An immutable auto-fill track definition.
108  * @see {@link GridTrack}
109  */
110 export function autoFillTracks(...tracks: readonly GridTrack[]): GridRepeatTrack {
111   return Object.freeze({ kind: 'repeat' as const, count: 'auto-fill' as const, tracks: Object.freeze([...tracks]) });
112 }
113 
114 /** Repeats Grid tracks to fit occupied cells in the available axis.
115  * @param tracks - The track sequence to repeat.
116  * @returns An immutable auto-fit track definition.
117  * @see {@link GridTrack}
118  */
119 export function autoFitTracks(...tracks: readonly GridTrack[]): GridRepeatTrack {
120   return Object.freeze({ kind: 'repeat' as const, count: 'auto-fit' as const, tracks: Object.freeze([...tracks]) });
121 }
122 
123 type GridAlignment = 'stretch' | 'start' | 'center' | 'end';
124 type ParsedGridTrack = (
125   | Readonly<{ kind: 'fixed'; value: number }>
126   | Readonly<{ kind: 'percentage'; factor: number }>
127   | Readonly<{ kind: 'fraction'; factor: number }>
128   | Readonly<{ kind: 'intrinsic'; value: 'auto' | SizingKeyword | FitContent }>
129   | Readonly<{ kind: 'minmax'; min: ParsedGridTrack; max: ParsedGridTrack }>) & { readonly autoFit?: boolean };
130 
131 /**
132  * Supported geometry and presentation properties for Grid.
133  *
134  * @see {@link BoxStyle}
135  * @see {@link LayoutItemStyle}
136  * @see {@link GridTrack}
137  * @see {@link Grid}
138  */
139 export interface GridStyle extends BoxStyle, LayoutItemStyle {
140   /** Explicit grid column track definitions. See {@link GridTrack}. */
141   gridTemplateColumns: readonly GridTrack[];
142   /** Explicit grid row track definitions. See {@link GridTrack}. */
143   gridTemplateRows: readonly GridTrack[];
144   /** Default inline-axis alignment of grid or overlay children. See {@link GridAlignment}. */
145   justifyItems?: GridAlignment;
146   /** Default alignment of children on the cross or block axis. See {@link GridAlignment}. */
147   alignItems?: GridAlignment;
148   /** Placement direction and dense-packing policy for automatically placed children. */
149   gridAutoFlow?: 'row' | 'column' | 'row dense' | 'column dense';
150   /** Track used when automatic placement creates an implicit column. */
151   gridAutoColumns?: GridTrack;
152   /** Track used when automatic placement creates an implicit row. */
153   gridAutoRows?: GridTrack;
154   /** Spacing between adjacent items. See {@link GridStyle}. */
155   gap?: number;
156   /** Space between adjacent rows or items on the row axis. See {@link GridStyle}. */
157   rowGap?: number;
158   /** Space between adjacent columns or items on the column axis. See {@link GridStyle}. */
159   columnGap?: number;
160 }
161 
162 /**
163  * Authored inputs for Grid, including the declared data and presentation options.
164  *
165  * @see {@link PibblNodeInput}
166  * @see {@link Grid}
167  */
168 export interface GridProps extends PibblStructuralEventProps {
169   /** Descendant content or the callback that supplies it. See {@link PibblNodeInput}. */
170   children: PibblNodeInput;
171 }
172 
173 export interface GridMeasurementInput {
174   service: CanvasMeasurementService;
175   measureElement(
176     element: PibblElement<any>,
177     constraints: Readonly<Constraints>,
178   ): MeasureResult;
179 }
180 
181 // Parent input is private metadata, not a recursively validated resolved value.
182 const GRID_CONTAINING_BOX_STYLE = Symbol('pibbl.grid-containing-box-style');
183 
184 interface ResolvedGridStyle extends SystemStyle {
185   box: ResolvedBoxStyle;
186   [GRID_CONTAINING_BOX_STYLE]: Readonly<GridStyle>;
187   overflow: 'visible' | 'clip';
188   columns: readonly ParsedGridTrack[];
189   rows: readonly ParsedGridTrack[];
190   justifyItems: GridAlignment;
191   alignItems: GridAlignment;
192   rowGap: number;
193   columnGap: number;
194   gridAutoFlow: NonNullable<GridStyle['gridAutoFlow']>;
195   autoColumn: ParsedGridTrack;
196   autoRow: ParsedGridTrack;
197   autoFitColumns: boolean;
198   autoFitRows: boolean;
199   layoutDirection: 'ltr' | 'rtl';
200 }
201 
202 interface GridPlacement {
203   usedWidth: number; usedHeight: number;
204   box: LayoutBox;
205   element: PibblElement<any>;
206 }
207 
208 type GridChildStyle = Readonly<
209   BoxStyle & GridItemStyle & LayoutItemStyle & Record<string, unknown>
210 >;
211 
212 interface GridCell {
213   readonly child: PibblElement<any>;
214   readonly prepared: ReturnType<typeof prepareDirectChildStyle>;
215   readonly normalized: GridChildStyle;
216   readonly receiverToken: object;
217   columnStart: number;
218   readonly columnSpan: number;
219   rowStart: number;
220   readonly rowSpan: number;
221 }
222 
223 function renderGrid(
224   props: GridProps,
225   style: Readonly<ResolvedGridStyle>,
226   ctx: RenderingContext2D,
227 ) {
228   wireStructuralEvents(props);
229   recordLayoutEvaluation();
230   const content = style.box.contentBox;
231   ctx.translate(content.x, content.y);
232   const localContent = Object.freeze({
233     x: 0,
234     y: 0,
235     width: content.width,
236     height: content.height,
237   });
238   const releaseLayout = pushLayoutBox(localContent, {
239     logicalOffset: content,
240     containingBlock: resolvePositionedContainingBox(
241       style[GRID_CONTAINING_BOX_STYLE],
242       localContent,
243       'Grid',
244     ),
245   });
246   GLOBAL_STATE.componentRefs!.onAfterRender = releaseLayout;
247   const prepared = nativeLayout ? claimPreparedLayoutPlan(GLOBAL_STATE.componentRefs!.element, localContent) : undefined;
248   const children = prepared?.children ?? prepareLayoutChildren(props.children, 'Grid');
249   const service = canvasMeasurementService(ctx);
250   const nativeRegion = prepared?.region ?? (nativeLayout ? mountedLayoutRegion() : undefined);
251   if (nativeLayout && !nativeRegion) throw new Error('Experimental Grid requires its mounted native region.');
252   const placements = prepared?.placements ?? withAllocationCheckpoint(nativeRegion, { children, content: localContent, settings: style, onHit: recordWasmAllocationCacheHit, calculate: () => resolveGridPlacements(
253     localContent,
254     children,
255     style,
256     {
257       service,
258       measureElement: (element, constraints) =>
259         measureElement(element, constraints, service),
260     },
261     nativeRegion,
262   ) });
263   let index = 0;
264   return placeDirectChildren(
265     children,
266     localContent,
267     (_child, occurrence) => {
268       const placement = placements[index++];
269       if (nativeLayout && !prepared) preparePlacedKnownLayout(placement.element, occurrence);
270       return placement;
271     },
272     style.overflow,
273   );
274 }
275 
276 /**
277  * Describes explicit Grid layout for JSX or createElement authoring.
278  *
279  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
280  * props and style types.
281  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
282  *
283  * @see {@link GridProps}
284  * @see {@link GridStyle}
285  */
286 export const Grid = definePrimitive<
287   GridProps,
288   GridStyle,
289   GridStyle,
290   ResolvedGridStyle
291 >(renderGrid, {
292   childInput: 'structural',
293   resolveStyle: (style, context) => {
294     if (nativeLayout && hasPercentageBoxPadding(style)) {
295       style = resolveAllocatedInsets(style, { width: context.percentageBasis.width,
296         context: { ...context, component: 'Grid', algorithm: 'grid' } });
297     }
298     return {
299       box: resolveContainerBox(style, context, 'Grid', 'grid'),
300       [GRID_CONTAINING_BOX_STYLE]: style,
301       overflow: style.overflow ?? 'visible',
302       ...normalizeGridOptions(style, context.allocation),
303     };
304   },
305   measure: (input) => measureGrid(input),
306   measureIntrinsic: (input) => measureGridIntrinsic(input),
307 });
308 
309 registerOpaqueStyleProperties(Grid, [
310   'columns', 'rows', 'autoColumn', 'autoRow', 'gridAutoColumns', 'gridAutoRows',
311 ]);
312 
313 if (nativeLayout) registerKnownLayoutPreflight(Grid, (element, style, content, receiver, slot) => {
314   const previous = GLOBAL_STATE.primitiveReceiverToken;
315   GLOBAL_STATE.primitiveReceiverToken = receiver;
316   const releaseLayout = pushLayoutBox(content, {
317     containingBlock: resolvePositionedContainingBox(
318       style as Readonly<GridStyle>,
319       content,
320       'Grid',
321     ),
322   });
323   try {
324     const children = prepareLayoutChildren(element.props.children, 'Grid');
325     const options = normalizeGridOptions(style as Readonly<GridStyle>, content);
326     const ctx = GLOBAL_STATE.renderContext;
327     if (!ctx) throw new Error('Known Grid preparation requires a Canvas measurement context.');
328     const service = canvasMeasurementService(ctx);
329     const region = slot.acquire();
330     const placements = withAllocationCheckpoint(region, { children, content, settings: options, onHit: recordWasmAllocationCacheHit, calculate: () => resolveGridPlacements(content, children, options, { service, measureElement: (child, constraints) => measureElement(child, constraints, service) }, region) });
331     const plan: PreparedLayoutPlan = { region, content, children, placements };
332     prepareKnownLayoutDescendants(plan, slot);
333     stagePreparedLayoutPlan(slot, plan);
334   } finally {
335     releaseLayout();
336     GLOBAL_STATE.primitiveReceiverToken = previous;
337   }
338 });
339 
340 export function layoutGrid(
341   container: Readonly<LayoutBox>,
342   children: PibblNodeInput,
343   style: Readonly<GridStyle>,
344   measurement: GridMeasurementInput,
345 ): LayoutBox[] {
346   const prepared = materializeLayoutChildren(children, 'Grid');
347   const options = normalizeGridOptions(style, container);
348   const region = nativeLayout ? new LayoutRegion() : undefined;
349   try { return resolveGridPlacements(container, prepared, options, measurement, region).map((placement) => placement.box); }
350   finally { region?.dispose(); }
351 }
352 
353 function resolveGridPlacements(
354   container: Readonly<LayoutBox>,
355   children: readonly PibblElement<any>[],
356   options: Readonly<ReturnType<typeof normalizeGridOptions>>,
357   measurement: GridMeasurementInput,
358   nativeRegion?: LayoutRegion,
359   assignedCells?: GridCell[],
360 ): GridPlacement[] {
361   if (nativeRegion) recordWasmAllocationPass();
362   assertFiniteContainer(container);
363   // Selected-width measurement can supply single-use cells already prepared
364   // and assigned for these exact children, container and options.
365   const cells = assignedCells ?? (nativeRegion ? prepareGridCells(children, container) : prepareExplicitGridCells(children, container, options.columns.length, options.rows.length));
366   const flowCells = cells.filter((cell) => cell.normalized.position !== 'absolute');
367   if (nativeRegion && !assignedCells) { const assigned = nativeRegion.gridV2Region().assign(flowCells, options.columns.length, options.rows.length, gridFlowCode(options.gridAutoFlow)).cells; for (let index = 0; index < flowCells.length; index++) { flowCells[index]!.columnStart = assigned[index]!.columnStart; flowCells[index]!.rowStart = assigned[index]!.rowStart; } }
368   let expandedColumns = appendImplicitTracks(options.columns, options.autoColumn, maxGridExtent(flowCells, 'column'));
369   let expandedRows = appendImplicitTracks(options.rows, options.autoRow, maxGridExtent(flowCells, 'row'));
370   if (nativeRegion && options.autoFitColumns) expandedColumns = collapseParsedAutoFit(expandedColumns, flowCells, 'column');
371   if (nativeRegion && options.autoFitRows) expandedRows = collapseParsedAutoFit(expandedRows, flowCells, 'row');
372   let columns = nativeRegion ? resolveNativeGridTracks(nativeRegion, expandedColumns, container.width, options.columnGap, 'columns', container) : resolveParsedGridTracks(
373     expandedColumns,
374     container.width,
375     options.columnGap,
376     'columns',
377     container,
378   );
379   if (nativeRegion) {
380     nativeRegion.applyGridV2Contributions(
381       gatherGridIntrinsicContributions(expandedColumns, cells, measurement, container, 'columns'),
382       options.columnGap,
383       0,
384     );
385     // Contributions mutate native records in place. Row measurement must use the
386     // resulting column areas, not the initial host snapshot.
387     columns = nativeRegion.snapshotGridV2Tracks(0) as number[];
388   }
389   let rows = nativeRegion ? resolveNativeGridTracks(nativeRegion, expandedRows, container.height, options.rowGap, 'rows', container) : resolveParsedGridTracks(
390     expandedRows,
391     container.height,
392     options.rowGap,
393     'rows',
394     container,
395   );
396   if (nativeRegion) {
397     nativeRegion.applyGridV2Contributions(
398       gatherGridIntrinsicContributions(
399         expandedRows,
400         cells,
401         measurement,
402         container,
403         'rows',
404         columns,
405         options.columnGap,
406       ),
407       options.rowGap,
408       1,
409     );
410     rows = nativeRegion.snapshotGridV2Tracks(1) as number[];
411   }
412   if (!nativeRegion && options.autoFitColumns) columns = collapseAutoFitTracks(columns, cells, 'column');
413   if (!nativeRegion && options.autoFitRows) rows = collapseAutoFitTracks(rows, cells, 'row');
414   const nativeItems = cells;
415   const nativeBoxes = nativeRegion ? nativeRegion.placeGridV2Cells(flowCells, gridFlowCode(options.gridAutoFlow), options.columnGap, options.rowGap) : undefined;
416   const placements: GridPlacement[] = [];
417 
418   let flowIndex = 0;
419   for (const child of children) {
420     const item = nativeItems[placements.length]!;
421     const { prepared, receiverToken, columnStart, columnSpan, rowStart, rowSpan } = item;
422     let normalized = item.normalized;
423     if (normalized.position === 'absolute') {
424       const needsNaturalMeasurement =
425         normalized.width === undefined || normalized.width === 'auto' ||
426         normalized.height === undefined || normalized.height === 'auto';
427       const absolute = resolveAbsoluteFlexPlacement(container, child, normalized, receiverToken, preparedStyleQuery(prepared), container, {
428         flexDirection: 'row', flexWrap: 'nowrap', justifyContent: 'flex-start', alignItems: options.alignItems === 'start' ? 'flex-start' : options.alignItems === 'end' ? 'flex-end' : options.alignItems, layoutDirection: options.layoutDirection,
429       }, needsNaturalMeasurement ? measurement : undefined);
430       placements.push({ usedWidth: absolute.usedWidth, usedHeight: absolute.usedHeight, box: absolute.box, element: absolute.element });
431       continue;
432     }
433     const nativeBox = nativeBoxes?.[flowIndex++];
434     const area = nativeBox ? { x: container.x + nativeBox.x, y: container.y + nativeBox.y, width: nativeBox.width, height: nativeBox.height } : {
435       x: container.x + trackOffset(columns, columnStart - 1, options.columnGap),
436       y: container.y + trackOffset(rows, rowStart - 1, options.rowGap),
437       width: trackSpan(columns, columnStart - 1, columnSpan, options.columnGap),
438       height: trackSpan(rows, rowStart - 1, rowSpan, options.rowGap),
439     };
440     if (nativeLayout && GLOBAL_STATE.currentPibblInstance && getStyleMeasurementMode() === undefined && hasPercentageBoxPadding(normalized)) {
441       normalized = resolveAllocatedInsets(normalized, { width: area.width, context: childContext(child, area) });
442     }
443     if (normalized.boxSizing !== undefined) normalized = contentBoxStyle(normalized, { width: area.width, height: area.height, context: childContext(child, area) });
444     const widthAuto =
445       normalized.width === undefined || normalized.width === 'auto';
446     const heightAuto =
447       normalized.height === undefined || normalized.height === 'auto';
448     const justify = itemAlignment(
449       normalized.justifySelf,
450       options.justifyItems,
451       'justifySelf',
452       child,
453       container,
454     );
455     const align = itemAlignment(
456       normalized.alignSelf,
457       options.alignItems,
458       'alignSelf',
459       child,
460       container,
461     );
462     let measured: MeasureResult | undefined;
463     if (
464       (widthAuto && justify !== 'stretch') ||
465       (heightAuto && align !== 'stretch')
466     ) {
467       const measurementChild = clonePibblElement(child);
468       setPreNormalizedStyle(
469         measurementChild,
470         normalized,
471         child,
472         receiverToken,
473         preparedStyleQuery(prepared),
474       );
475       measured = measurement.measureElement(measurementChild, {
476         minWidth: 0,
477         maxWidth: area.width,
478         minHeight: 0,
479         maxHeight: area.height,
480       });
481       if (measured.status === 'unsupported') {
482         throw childDiagnostic(
483           child,
484           widthAuto && justify !== 'stretch' ? 'width' : 'height',
485           'auto',
486           container,
487           `measurement is required but unsupported: ${measured.reason}`,
488         );
489       }
490     }
491     const padding = normalizeBoxInsets(normalized, childContext(child, container));
492     const usedStyle = {
493       ...normalized,
494       width: widthAuto
495         ? justify === 'stretch'
496           ? Math.max(0, area.width - padding.left - padding.right)
497           : measured!.status === 'measured'
498             ? measured!.size.width
499             : 0
500         : normalized.width,
501       height: heightAuto
502         ? align === 'stretch'
503           ? Math.max(0, area.height - padding.top - padding.bottom)
504           : measured!.status === 'measured'
505             ? measured!.size.height
506             : 0
507         : normalized.height,
508     };
509     const resolved = resolveDirectChildBox(area, child, 'grid', usedStyle, measurement.service, receiverToken);
510     const border = resolved.borderBox;
511     const box = {
512       x: area.x + alignmentOffset(area.width, border.width, justify),
513       y: area.y + alignmentOffset(area.height, border.height, align),
514       width: border.width,
515       height: border.height,
516     };
517     placements.push({
518       usedWidth: resolved.contentBox.width, usedHeight: resolved.contentBox.height,
519       box,
520       element: childWithUsedSize(
521         child,
522         normalized,
523         resolved.contentBox.width,
524         resolved.contentBox.height,
525         receiverToken,
526         preparedStyleQuery(prepared),
527       ),
528     });
529   }
530   return placements;
531 }
532 
533 export function resolveGridTracks(
534   tracks: readonly GridTrack[],
535   bound: number,
536   gap: number,
537   axis: 'columns' | 'rows',
538 ): number[] {
539   const container = {
540     x: 0,
541     y: 0,
542     width: axis === 'columns' ? bound : 0,
543     height: axis === 'rows' ? bound : 0,
544   };
545   const parsed = parseGridTracks(tracks, axis, container, gap);
546   return resolveParsedGridTracks(parsed, bound, gap, axis, container);
547 }
548 
549 
550 function assignGridCells(children: readonly PibblElement<any>[], container: Readonly<LayoutBox>, columns: number, rows: number, options: Readonly<ReturnType<typeof normalizeGridOptions>>): GridCell[] {
551   const cells = prepareGridCells(children, container);
552   const flow = cells.filter(cell => cell.normalized.position !== 'absolute');
553   const region = new LayoutRegion();
554   try {
555     const assigned = region.gridV2Region().assign(flow, columns, rows, gridFlowCode(options.gridAutoFlow)).cells;
556     for (let index = 0; index < flow.length; index++) {
557       flow[index]!.columnStart = assigned[index]!.columnStart;
558       flow[index]!.rowStart = assigned[index]!.rowStart;
559     }
560     return cells;
561   } finally { region.dispose(); }
562 }
563 
564 function prepareExplicitGridCells(children: readonly PibblElement<any>[], container: Readonly<LayoutBox>, columns: number, rows: number): GridCell[] {
565   const cells = prepareGridCells(children, container);
566   for (let index = 0; index < cells.length; index++) {
567     const cell = cells[index]!;
568     assertSupportedChildPosition('Grid', cell.child, cell.normalized);
569     cell.columnStart = placementInteger(cell.normalized.gridColumnStart, 'gridColumnStart', cell.child, container, true);
570     cell.rowStart = placementInteger(cell.normalized.gridRowStart, 'gridRowStart', cell.child, container, true);
571     if (cell.columnStart > columns) throw childDiagnostic(cell.child, 'gridColumnStart', cell.columnStart, container, `must reference one of the explicit ${columns} columns`);
572     if (cell.rowStart > rows) throw childDiagnostic(cell.child, 'gridRowStart', cell.rowStart, container, `must reference one of the explicit ${rows} rows`);
573     if (cell.columnStart + cell.columnSpan - 1 > columns) throw childDiagnostic(cell.child, 'gridColumnSpan', cell.columnSpan, container, `start ${cell.columnStart} plus span ${cell.columnSpan} must remain inside the explicit column tracks`);
574     if (cell.rowStart + cell.rowSpan - 1 > rows) throw childDiagnostic(cell.child, 'gridRowSpan', cell.rowSpan, container, `start ${cell.rowStart} plus span ${cell.rowSpan} must remain inside the explicit row tracks`);
575   }
576   return cells;
577 }
578 
579 function prepareGridCells(children: readonly PibblElement<any>[], container: Readonly<LayoutBox>): GridCell[] {
580   const result: GridCell[] = [];
581   for (let index = 0; index < children.length; index++) {
582     recordWasmAllocationItem();
583     const child = children[index]!;
584     const receiverToken = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, index);
585     const prepared = prepareDirectChildStyle(child, receiverToken, container);
586     const normalized = preparedStyleValue(prepared) as GridChildStyle;
587     if (normalized.position !== 'absolute') assertSupportedChildPosition('Grid', child, normalized); rejectUnsupportedItemFields(child, normalized, container);
588     const columnSpan = placementInteger(normalized.gridColumnSpan ?? 1, 'gridColumnSpan', child, container, false);
589     const rowSpan = placementInteger(normalized.gridRowSpan ?? 1, 'gridRowSpan', child, container, false);
590     const columnStart = normalized.gridColumnStart === undefined ? 0 : placementInteger(normalized.gridColumnStart, 'gridColumnStart', child, container, false);
591     const rowStart = normalized.gridRowStart === undefined ? 0 : placementInteger(normalized.gridRowStart, 'gridRowStart', child, container, false);
592     result.push({ child, prepared, normalized, receiverToken, columnStart, columnSpan, rowStart, rowSpan });
593   }
594   return result;
595 }
596 
597 function maxGridExtent(cells: readonly { columnStart: number; columnSpan: number; rowStart: number; rowSpan: number }[], axis: 'column' | 'row'): number {
598   let extent = 0;
599   for (let index = 0; index < cells.length; index++) {
600     const cell = cells[index]!;
601     extent = Math.max(extent, axis === 'column' ? cell.columnStart + cell.columnSpan - 1 : cell.rowStart + cell.rowSpan - 1);
602   }
603   return extent;
604 }
605 function collapseAutoFitTracks(tracks: readonly number[], cells: readonly GridCell[], axis: 'column' | 'row'): number[] { const out=tracks.slice(); for(let index=0;index<out.length;index++){let used=false;for(let cellIndex=0;cellIndex<cells.length;cellIndex++){const cell=cells[cellIndex]!;const start=axis==='column'?cell.columnStart:cell.rowStart,span=axis==='column'?cell.columnSpan:cell.rowSpan;if(start<=index+1&&index+1<start+span){used=true;break}}if(!used)out[index]=0;}return out; }
606 
607 function containsAutoFit(tracks: readonly GridTrack[]): boolean {
608   for (const track of tracks) if (typeof track === 'object' && track !== null && 'kind' in track && track.kind === 'repeat' &&
609     (track.count === 'auto-fit' || containsAutoFit(track.tracks))) return true;
610   return false;
611 }
612 
613 /** Collapse only automatic-fit tracks; fixed siblings and implicit tracks remain. */
614 function collapseParsedAutoFit(tracks: readonly ParsedGridTrack[], cells: GridCell[], axis: 'column' | 'row'): readonly ParsedGridTrack[] {
615   const occupied = new Int32Array(tracks.length + 1);
616   for (const cell of cells) {
617     const start = (axis === 'column' ? cell.columnStart : cell.rowStart) - 1;
618     const span = axis === 'column' ? cell.columnSpan : cell.rowSpan;
619     occupied[start]++; occupied[start + span]--;
620   }
621   const offsets = new Uint32Array(tracks.length + 1), kept: ParsedGridTrack[] = [];
622   let count = 0;
623   for (let index = 0; index < tracks.length; index++) {
624     count += occupied[index]!;
625     if (!tracks[index]!.autoFit || count > 0) kept.push(tracks[index]!);
626     offsets[index + 1] = kept.length;
627   }
628   for (const cell of cells) {
629     if (axis === 'column') cell.columnStart = offsets[cell.columnStart - 1]! + 1;
630     else cell.rowStart = offsets[cell.rowStart - 1]! + 1;
631   }
632   return kept;
633 }
634 
635 function appendImplicitTracks(explicit: readonly ParsedGridTrack[], automatic: ParsedGridTrack, extent: number): readonly ParsedGridTrack[] {
636   if (extent <= explicit.length) return explicit;
637   const tracks = explicit.slice();
638   while (tracks.length < extent) tracks.push(automatic);
639   return tracks;
640 }
641 
642 function gatherGridIntrinsicContributions(
643   tracks: readonly ParsedGridTrack[],
644   cells: readonly GridCell[],
645   measurement: GridMeasurementInput,
646   container: Readonly<LayoutBox>,
647   axis: 'columns' | 'rows',
648   selectedColumns?: readonly number[],
649   columnGap = 0,
650 ): number[] {
651   const records: number[] = [];
652   for (let index = 0; index < cells.length; index++) {
653     const cell = cells[index]!;
654     if (cell.normalized.position === 'absolute') continue;
655     const start = axis === 'columns' ? cell.columnStart : cell.rowStart;
656     const span = axis === 'columns' ? cell.columnSpan : cell.rowSpan;
657     if (start < 1 || start + span - 1 > tracks.length) continue;
658     let needed = false;
659     for (let track = start - 1; track < start - 1 + span; track++) {
660       if (trackNeedsIntrinsic(tracks[track]!)) needed = true;
661     }
662     if (!needed) continue;
663     if (axis === 'rows') {
664       if (!selectedColumns) throw new Error('Grid row contributions require resolved column tracks.');
665       const width = trackSpan(selectedColumns, cell.columnStart - 1, cell.columnSpan, columnGap);
666       const height = measureGridCellAtSelectedWidth(cell, width, measurement, container);
667       records.push(start, span, height, height);
668       continue;
669     }
670     const contributionChild = clonePibblElement(cell.child);
671     setPreNormalizedStyle(contributionChild, cell.normalized, cell.child, cell.receiverToken, preparedStyleQuery(cell.prepared));
672     const result = measureIntrinsicElement(
673       contributionChild,
674       {
675         minWidth: 0,
676         maxWidth: container.width,
677         minHeight: 0,
678         maxHeight: container.height,
679       },
680       measurement.service,
681     );
682     if (result.status !== 'measured') {
683       throw childDiagnostic(
684         cell.child,
685         'measureIntrinsic',
686         'unsupported',
687         container,
688         `intrinsic grid track contribution requires a declared intrinsic measurement: ${result.reason}`,
689       );
690     }
691     records.push(start, span, result.minContent.width, result.maxContent.width);
692   }
693   return records;
694 }
695 
696 /** Measures a row contribution at its selected final column span. */
697 function measureGridCellAtSelectedWidth(
698   cell: Readonly<GridCell>,
699   width: number,
700   measurement: GridMeasurementInput,
701   container: Readonly<LayoutBox>,
702 ): number {
703   const area = { x: 0, y: 0, width, height: container.height };
704   let normalized = cell.normalized;
705   if (
706     nativeLayout &&
707     GLOBAL_STATE.currentPibblInstance &&
708     getStyleMeasurementMode() === undefined &&
709     hasPercentageBoxPadding(normalized)
710   ) {
711     normalized = resolveAllocatedInsets(normalized, {
712       width,
713       context: childContext(cell.child, area),
714     });
715   }
716   if (normalized.boxSizing !== undefined) {
717     normalized = contentBoxStyle(normalized, {
718       width,
719       height: container.height,
720       context: childContext(cell.child, area),
721     });
722   }
723   const child = clonePibblElement(cell.child);
724   setPreNormalizedStyle(
725     child,
726     normalized,
727     cell.child,
728     cell.receiverToken,
729     preparedStyleQuery(cell.prepared),
730   );
731   const result = measurement.measureElement(child, {
732     minWidth: width,
733     maxWidth: width,
734     minHeight: 0,
735     maxHeight: container.height,
736   });
737   if (result.status !== 'measured') {
738     throw childDiagnostic(
739       cell.child,
740       'height',
741       'auto',
742       container,
743       `selected Grid column width requires measurement: ${result.reason}`,
744     );
745   }
746   return result.size.height;
747 }
748 
749 function trackNeedsIntrinsic(track: ParsedGridTrack): boolean { return track.kind === 'intrinsic' || track.kind === 'minmax' && (trackNeedsIntrinsic(track.min) || trackNeedsIntrinsic(track.max)); }
750 function resolveNativeGridTracks(region: LayoutRegion, tracks: readonly ParsedGridTrack[], bound: number, gap: number, axis: 'columns' | 'rows', container: Readonly<LayoutBox>): number[] {
751   try { return region.resolveGridV2Tracks(gridTrackRecords(tracks, bound), { bound, gap, axis: axis === 'columns' ? 0 : 1 }) as number[]; }
752   catch (error) { if (error instanceof RangeError) throw trackDiagnostic(tracks, axis, container); throw error; }
753 }
754 
755 function gridTrackRecords(tracks: readonly ParsedGridTrack[], bound: number): number[] {
756   const records = new Array<number>(tracks.length * GRID_V2_TRACK_STRIDE).fill(0);
757   for (let index = 0; index < tracks.length; index++) {
758     const track = tracks[index]!, offset = index * GRID_V2_TRACK_STRIDE;
759     if (track.kind === 'fixed') { records[offset] = 0; records[offset + 1] = track.value; }
760     else if (track.kind === 'percentage') { records[offset] = 1; records[offset + 1] = track.factor; }
761     else if (track.kind === 'fraction') { records[offset] = 2; records[offset + 1] = track.factor; }
762     else if (track.kind === 'intrinsic') { writeGridBreadth(records, offset, track, bound); }
763     else { records[offset] = 6; writeGridBreadth(records, offset + 2, track.min, bound); writeGridBreadth(records, offset + 4, track.max, bound); }
764   }
765   return records;
766 }
767 
768 function writeGridBreadth(records: number[], offset: number, track: ParsedGridTrack, bound: number): void {
769   if (track.kind === 'fixed') { records[offset] = 0; records[offset + 1] = track.value; }
770   else if (track.kind === 'percentage') { records[offset] = 1; records[offset + 1] = track.factor; }
771   else if (track.kind === 'fraction') { records[offset] = 2; records[offset + 1] = track.factor; }
772   else if (track.kind === 'minmax') writeGridBreadth(records, offset, track.min, bound);
773   else if (track.value === 'min-content') records[offset] = 3;
774   else if (track.value === 'max-content') records[offset] = 4;
775   else if (track.value === 'auto') records[offset] = 5;
776   else if (isFitContent(track.value)) { records[offset]=7; records[offset+1]=typeof track.value.limit==='number'?track.value.limit:bound*Number.parseFloat(track.value.limit)/100; }
777 }
778 
779 function gridFlowCode(flow: NonNullable<GridStyle['gridAutoFlow']>): 0 | 1 | 2 | 3 {
780   return flow === 'row' ? 0 : flow === 'column' ? 1 : flow === 'row dense' ? 2 : 3;
781 }
782 
783 function resolveParsedGridTracks(
784   tracks: readonly ParsedGridTrack[],
785   bound: number,
786   gap: number,
787   axis: 'columns' | 'rows',
788   container: Readonly<LayoutBox>,
789 ): number[] {
790   if (!Number.isFinite(bound) || bound < 0) {
791     throw optionDiagnostic(
792       axis,
793       bound,
794       container,
795       'requires a finite nonnegative track bound',
796     );
797   }
798   const resolved = new Array<number>(tracks.length).fill(0);
799   const fractions: { index: number; factor: number }[] = [];
800   let allocated =
801     Math.max(0, tracks.length - 1) * nonnegativeOption(gap, 'gap', container);
802   for (let index = 0; index < tracks.length; index++) {
803     const track = tracks[index];
804     if (track.kind === 'fixed') {
805       resolved[index] = track.value;
806       allocated += track.value;
807     } else if (track.kind === 'percentage') {
808       const size = (bound * track.factor) / 100;
809       if (!Number.isFinite(size)) throw trackDiagnostic(track, axis, container);
810       resolved[index] = size;
811       allocated += size;
812     } else if (track.kind === 'fraction') {
813       fractions.push({ index, factor: track.factor });
814     } else if (track.kind === 'minmax') {
815       const min = resolvedTrackMinimum(track.min, bound, axis, container);
816       const max = resolvedTrackMaximum(track.max, bound, axis, container);
817       if (max < min) throw trackDiagnostic(track, axis, container);
818       resolved[index] = min;
819       allocated += min;
820     } else {
821       /* Intrinsic tracks begin at zero; their contribution is supplied by
822        * known primitive measurement in the containing Grid pass. */
823       resolved[index] = 0;
824     }
825   }
826   const totalFr = fractions.reduce((total, track) => total + track.factor, 0);
827   if (!Number.isFinite(allocated) || !Number.isFinite(totalFr)) {
828     throw trackDiagnostic(tracks, axis, container);
829   }
830   const remaining = Math.max(0, bound - allocated);
831   const unit = remaining / Math.max(1, totalFr);
832   for (const track of fractions) resolved[track.index] = unit * track.factor;
833   if (resolved.some((value) => !Number.isFinite(value) || value < 0)) {
834     throw trackDiagnostic(tracks, axis, container);
835   }
836   return resolved;
837 }
838 
839 function parseGridTracks(
840   tracks: readonly GridTrack[],
841   axis: 'columns' | 'rows',
842   container: Readonly<LayoutBox>,
843   gap = 0,
844 ): readonly ParsedGridTrack[] {
845   if (!Array.isArray(tracks) || tracks.length === 0) {
846     throw optionDiagnostic(
847       axis === 'columns' ? 'gridTemplateColumns' : 'gridTemplateRows',
848       tracks,
849       container,
850       `requires a nonempty explicit ${axis} list`,
851     );
852   }
853   if (!nativeLayout) for (let index = 0; index < tracks.length; index++) {
854     const track = tracks[index]!;
855     if (typeof track === 'object' || track === 'auto' || track === 'min-content' || track === 'max-content') throw trackDiagnostic(track, axis, container);
856   }
857   let autoRepeatIndex = -1;
858   for (let index = 0; index < tracks.length; index++) {
859     const track = tracks[index]!;
860     if (!isAutoRepeatTrack(track)) continue;
861     if (autoRepeatIndex !== -1) throw trackDiagnostic(tracks, axis, container);
862     autoRepeatIndex = index;
863   }
864   const autoRepeatCount = autoRepeatIndex === -1
865     ? undefined
866     : resolveAutoRepeatCount(
867       tracks,
868       autoRepeatIndex,
869       axis,
870       container,
871       gap,
872     );
873   const expanded: GridTrack[] = [];
874   const autoFit = autoRepeatIndex !== -1 && (tracks[autoRepeatIndex] as GridRepeatTrack).count === 'auto-fit' ? new Set<number>() : undefined;
875   for (let index = 0; index < tracks.length; index++) {
876     expandGridTrack(
877       tracks[index]!,
878       axis,
879       container,
880       expanded,
881       index === autoRepeatIndex ? autoRepeatCount : undefined,
882       autoFit,
883     );
884   }
885   if (!expanded.length) throw trackDiagnostic(tracks, axis, container);
886   const parsed: ParsedGridTrack[] = expanded.map(track => {
887     if (typeof track === 'number') {
888       if (!Number.isFinite(track) || track < 0) {
889         throw trackDiagnostic(track, axis, container);
890       }
891       return Object.freeze({ kind: 'fixed', value: track });
892     }
893     if (isFitContent(track)) return Object.freeze({ kind: 'intrinsic' as const, value: track });
894     if (typeof track === 'object' && track !== null && 'kind' in track && track.kind === 'minmax') {
895       const min = parseSingleGridTrack((track as GridMinMaxTrack).min, axis, container);
896       const max = parseSingleGridTrack((track as GridMinMaxTrack).max, axis, container);
897       return Object.freeze({ kind: 'minmax' as const, min, max });
898     }
899     if (typeof track !== 'string') throw trackDiagnostic(track, axis, container);
900     if (track === 'auto' || track === 'min-content' || track === 'max-content') return Object.freeze({ kind: 'intrinsic' as const, value: track });
901     const match = /^(?:\d+(?:\.\d+)?|\.\d+)(%|fr)$/.exec(track);
902     if (!match) throw trackDiagnostic(track, axis, container);
903     const factor = Number.parseFloat(track);
904     if (!Number.isFinite(factor) || factor < 0) {
905       throw trackDiagnostic(track, axis, container);
906     }
907     return Object.freeze(match[1] === '%' ?
908       { kind: 'percentage', factor } :
909       { kind: 'fraction', factor });
910   });
911   return autoFit ? parsed.map((track, index) => autoFit.has(index) ? Object.freeze({ ...track, autoFit: true }) : track) : parsed;
912 }
913 
914 function parseSingleGridTrack(track: GridTrackBreadth, axis: 'columns' | 'rows', container: Readonly<LayoutBox>): ParsedGridTrack {
915   const parsed = parseGridTracks([track], axis, container);
916   return parsed[0]!;
917 }
918 
919 function expandGridTrack(
920   track: GridTrack,
921   axis: 'columns' | 'rows',
922   container: Readonly<LayoutBox>,
923   into: GridTrack[],
924   resolvedAutoRepeatCount?: number,
925   autoFit?: Set<number>,
926   inheritedAutoFit = false,
927 ): void {
928   if (typeof track === 'object' && track !== null && 'kind' in track && track.kind === 'repeat') {
929     if (!Array.isArray(track.tracks) || !track.tracks.length) throw trackDiagnostic(track, axis, container);
930     let count = track.count;
931     if (count === 'auto-fill' || count === 'auto-fit') {
932       if (resolvedAutoRepeatCount === undefined) throw trackDiagnostic(track, axis, container);
933       count = resolvedAutoRepeatCount;
934     }
935     if (!Number.isInteger(count) || count < 0) throw trackDiagnostic(track, axis, container);
936     for (let repeat = 0; repeat < count; repeat++) for (let index = 0; index < track.tracks.length; index++) expandGridTrack(track.tracks[index]!, axis, container, into, undefined, autoFit, inheritedAutoFit || track.count === 'auto-fit');
937     return;
938   }
939   if (inheritedAutoFit) autoFit?.add(into.length);
940   into.push(track);
941 }
942 
943 function isAutoRepeatTrack(track: GridTrack): track is GridRepeatTrack {
944   return typeof track === 'object' && track !== null && 'kind' in track &&
945     track.kind === 'repeat' &&
946     (track.count === 'auto-fill' || track.count === 'auto-fit');
947 }
948 
949 function resolveAutoRepeatCount(
950   tracks: readonly GridTrack[],
951   autoRepeatIndex: number,
952   axis: 'columns' | 'rows',
953   container: Readonly<LayoutBox>,
954   gap: number,
955 ): number {
956   const autoRepeat = tracks[autoRepeatIndex]! as GridRepeatTrack;
957   const repeated = trackListMetrics(autoRepeat.tracks, axis, container);
958   let fixedBreadth = 0;
959   let fixedCount = 0;
960   for (let index = 0; index < tracks.length; index++) {
961     if (index === autoRepeatIndex) continue;
962     const metrics = trackMetrics(tracks[index]!, axis, container);
963     fixedBreadth += metrics.breadth;
964     fixedCount += metrics.count;
965   }
966   const bound = axis === 'columns' ? container.width : container.height;
967   // The repeat group owns one gap per repeated track; fixed siblings own
968   // only the gaps between fixed tracks. With no fixed sibling, the leading
969   // gap is absent; with one, it is already represented by the group.
970   const available = bound - fixedBreadth - (fixedCount - 1) * gap;
971   const repeatedBreadth = repeated.breadth + repeated.count * gap;
972   return Math.max(1, Math.floor(available / Math.max(1, repeatedBreadth)));
973 }
974 
975 function trackListMetrics(
976   tracks: readonly GridTrack[],
977   axis: 'columns' | 'rows',
978   container: Readonly<LayoutBox>,
979 ): Readonly<{ breadth: number; count: number }> {
980   let breadth = 0;
981   let count = 0;
982   for (let index = 0; index < tracks.length; index++) {
983     const metrics = trackMetrics(tracks[index]!, axis, container);
984     breadth += metrics.breadth;
985     count += metrics.count;
986   }
987   return { breadth, count };
988 }
989 
990 function trackMetrics(
991   track: GridTrack,
992   axis: 'columns' | 'rows',
993   container: Readonly<LayoutBox>,
994 ): Readonly<{ breadth: number; count: number }> {
995   if (typeof track === 'object' && track !== null && 'kind' in track && track.kind === 'repeat') {
996     if (!Array.isArray(track.tracks) || !track.tracks.length || typeof track.count !== 'number' || !Number.isInteger(track.count) || track.count < 0) {
997       throw trackDiagnostic(track, axis, container);
998     }
999     let breadth = 0;
1000     let count = 0;
1001     for (let index = 0; index < track.tracks.length; index++) {
1002       const metrics = trackMetrics(track.tracks[index]!, axis, container);
1003       breadth += metrics.breadth * track.count;
1004       count += metrics.count * track.count;
1005     }
1006     return { breadth, count };
1007   }
1008   return {
1009     breadth: minimumRepeatBreadth([track], axis, container),
1010     count: 1,
1011   };
1012 }
1013 
1014 function minimumRepeatBreadth(tracks: readonly GridTrack[], axis: 'columns' | 'rows', container: Readonly<LayoutBox>): number {
1015   let size = 0;
1016   for (let index = 0; index < tracks.length; index++) {
1017     const parsed = parseSingleGridTrack(tracks[index]! as GridTrackBreadth, axis, container);
1018     size += resolvedTrackMinimum(parsed, axis === 'columns' ? container.width : container.height, axis, container);
1019   }
1020   return size;
1021 }
1022 
1023 function resolvedTrackMinimum(track: ParsedGridTrack, bound: number, axis: string, container: Readonly<LayoutBox>): number {
1024   if (track.kind === 'fixed') return track.value;
1025   if (track.kind === 'percentage') return bound * track.factor / 100;
1026   if (track.kind === 'minmax') return resolvedTrackMinimum(track.min, bound, axis, container);
1027   return 0;
1028 }
1029 
1030 function resolvedTrackMaximum(track: ParsedGridTrack, bound: number, axis: string, container: Readonly<LayoutBox>): number {
1031   if (track.kind === 'fixed') return track.value;
1032   if (track.kind === 'percentage') return bound * track.factor / 100;
1033   if (track.kind === 'fraction' || track.kind === 'intrinsic') return Number.POSITIVE_INFINITY;
1034   return resolvedTrackMaximum(track.max, bound, axis, container);
1035 }
1036 
1037 function measureGrid(input: MeasureInput<GridProps, GridStyle>): MeasureResult {
1038   prepareLayoutChildren(input.props.children, 'Grid');
1039   const diagnosticBox = {
1040     x: 0,
1041     y: 0,
1042     width: Number.isFinite(input.constraints.maxWidth)
1043       ? input.constraints.maxWidth
1044       : 0,
1045     height: Number.isFinite(input.constraints.maxHeight)
1046       ? input.constraints.maxHeight
1047       : 0,
1048   };
1049   const options = normalizeGridOptions(input.style, diagnosticBox);
1050   const widthDefinite =
1051     input.style.width !== undefined && input.style.width !== 'auto';
1052   const heightDefinite =
1053     input.style.height !== undefined && input.style.height !== 'auto';
1054   if (widthDefinite && !heightDefinite) {
1055     const width = measuredLength(
1056       input.style.width!,
1057       input.constraints.maxWidth,
1058       'width',
1059       input.constraints,
1060     );
1061     const selected = measureGridRowsAtSelectedWidth(
1062       input.props.children,
1063       input.style,
1064       input.service,
1065       (element, constraints) => input.measureElement(element, constraints),
1066       input.constraints,
1067       width,
1068     );
1069     if (selected.status === 'unsupported') return selected;
1070     return { status: 'measured', size: { width, height: selected.height } };
1071   }
1072   const intrinsic = (!widthDefinite && !fixedIntrinsicAxis(options.columns)) || (!heightDefinite && !fixedIntrinsicAxis(options.rows))
1073     ? measureGridIntrinsic({
1074       props: input.props,
1075       style: input.style,
1076       constraints: {
1077         width: { kind: 'bounded', min: input.constraints.minWidth, max: input.constraints.maxWidth },
1078         height: { kind: 'bounded', min: input.constraints.minHeight, max: input.constraints.maxHeight },
1079       },
1080       service: input.service,
1081     })
1082     : undefined;
1083   if (intrinsic?.status === 'unsupported') return intrinsic;
1084   const width = widthDefinite
1085     ? measuredLength(
1086         input.style.width!,
1087         input.constraints.maxWidth,
1088         'width',
1089         input.constraints,
1090       )
1091     : fixedIntrinsicAxis(options.columns) ? intrinsicTrackSize(options.columns, options.columnGap) : intrinsic!.maxContent.width;
1092   const height = heightDefinite
1093     ? measuredLength(
1094         input.style.height!,
1095         input.constraints.maxHeight,
1096         'height',
1097         input.constraints,
1098       )
1099     : fixedIntrinsicAxis(options.rows) ? intrinsicTrackSize(options.rows, options.rowGap) : intrinsic!.maxContent.height;
1100   return { status: 'measured', size: { width, height } };
1101 }
1102 
1103 /**
1104  * Resolves intrinsic row tracks only after their column areas are known. A
1105  * paired provider's height is defined at that selected width, so its width-pair
1106  * height cannot be used as a row contribution.
1107  */
1108 function measureGridRowsAtSelectedWidth(
1109   childInput: PibblNodeInput,
1110   style: Readonly<GridStyle>,
1111   service: CanvasMeasurementService,
1112   measure: GridMeasurementInput['measureElement'],
1113   constraints: Readonly<Constraints>,
1114   width: number,
1115 ): Readonly<{ status: 'measured'; height: number }> | Readonly<{ status: 'unsupported'; reason: string }> {
1116   if (!Number.isFinite(width) || width < 0 || !Number.isFinite(constraints.maxHeight)) {
1117     return { status: 'unsupported', reason: 'Grid selected-width row measurement requires finite owner constraints' };
1118   }
1119   const allocatedHeight = typeof style.height === 'number'
1120     ? measuredLength(style.height, constraints.maxHeight, 'height', constraints)
1121     : undefined;
1122   const container = { x: 0, y: 0, width, height: allocatedHeight ?? constraints.maxHeight };
1123   const options = normalizeGridOptions(style, container);
1124   // The width is selected, but maxHeight remains only an upper bound. Row
1125   // fractions, percentages and automatic repetition need an allocated height.
1126   if (allocatedHeight === undefined && (style.gridTemplateRows.some(isAutoRepeatTrack) || options.rows.some(trackNeedsAllocatedAxis))) {
1127     return { status: 'unsupported', reason: 'Grid intrinsic row measurement is allocation-dependent' };
1128   }
1129   const children = materializeLayoutChildren(childInput, 'Grid');
1130   const dependentImplicitRows = allocatedHeight === undefined &&
1131     (trackNeedsAllocatedAxis(options.autoRow) || style.gridAutoRows !== undefined && isAutoRepeatTrack(style.gridAutoRows));
1132   const canSumRows = fixedIntrinsicAxis(options.rows) && !options.autoFitRows;
1133   let assignedCells: GridCell[] | undefined;
1134   if (dependentImplicitRows || canSumRows) {
1135     assignedCells = assignGridCells(children, container, options.columns.length, options.rows.length, options);
1136     const extent = maxGridExtent(assignedCells.filter(cell => cell.normalized.position !== 'absolute'), 'row');
1137     if (dependentImplicitRows && extent > options.rows.length) {
1138       return { status: 'unsupported', reason: 'Grid intrinsic implicit-row measurement is allocation-dependent' };
1139     }
1140     const rows = appendImplicitTracks(options.rows, options.autoRow, extent);
1141     if (canSumRows && fixedIntrinsicAxis(rows)) {
1142       return { status: 'measured', height: intrinsicTrackSize(rows, options.rowGap) };
1143     }
1144   }
1145   const region = new LayoutRegion();
1146   try {
1147     // Measurement and rendering use one track/occupancy algorithm. In particular,
1148     // a minmax fractional maximum must settle before width-dependent row queries.
1149     resolveGridPlacements(container, children, options, { service, measureElement: measure }, region, assignedCells);
1150     const rows = region.snapshotGridV2Tracks(1);
1151     let height = Math.max(0, rows.length - 1) * options.rowGap;
1152     for (let index = 0; index < rows.length; index++) height += rows[index]!;
1153     return { status: 'measured', height };
1154   } finally { region.dispose(); }
1155 }
1156 
1157 function trackNeedsAllocatedAxis(track: ParsedGridTrack): boolean {
1158   if (track.kind === 'percentage' || track.kind === 'fraction') return true;
1159   if (track.kind === 'minmax') return trackNeedsAllocatedAxis(track.min) || trackNeedsAllocatedAxis(track.max);
1160   return track.kind === 'intrinsic' && isFitContent(track.value) && typeof track.value.limit === 'string';
1161 }
1162 
1163 function fixedIntrinsicAxis(tracks: readonly ParsedGridTrack[]): boolean {
1164   return tracks.every(track => track.kind === 'fixed');
1165 }
1166 
1167 function intrinsicTrackSize(tracks: readonly ParsedGridTrack[], gap: number): number {
1168   return tracks.reduce((total, track) => total + (track.kind === 'fixed' ? track.value : 0), Math.max(0, tracks.length - 1) * gap);
1169 }
1170 
1171 function measureGridIntrinsic(input: import('../types.js').IntrinsicMeasureInput<GridProps, GridStyle>): import('../types.js').IntrinsicSizesResult {
1172   const selected = intrinsicGridSelectedWidth(input);
1173   if (selected !== undefined) {
1174     const rows = measureGridRowsAtSelectedWidth(
1175       input.props.children,
1176       input.style,
1177       input.service,
1178       (element, constraints) => measureElement(element, constraints, input.service),
1179       selected.constraints,
1180       selected.width,
1181     );
1182     if (rows.status === 'unsupported') return rows;
1183     return {
1184       status: 'measured',
1185       minContent: { width: selected.width, height: rows.height },
1186       maxContent: { width: selected.width, height: rows.height },
1187     };
1188   }
1189   if (containsFractionTrack(input.style.gridTemplateColumns) || containsFractionTrack(input.style.gridTemplateRows)) {
1190     return { status: 'unsupported', reason: 'Grid fractional intrinsic measurement is allocation-dependent' };
1191   }
1192   const width = input.constraints.width.kind === 'bounded' ? input.constraints.width.max : Number.POSITIVE_INFINITY;
1193   const height = input.constraints.height.kind === 'bounded' ? input.constraints.height.max : Number.POSITIVE_INFINITY;
1194   if (!Number.isFinite(width) || !Number.isFinite(height)) {
1195     return { status: 'unsupported', reason: 'Grid intrinsic measurement requires finite owner constraints' };
1196   }
1197   const container = { x: 0, y: 0, width, height };
1198   const options = normalizeGridOptions(input.style, container);
1199   if (options.columns.some(track => track.kind === 'percentage') || options.rows.some(track => track.kind === 'percentage')) {
1200     return { status: 'unsupported', reason: 'Grid percentage intrinsic measurement is allocation-dependent' };
1201   }
1202   const children = materializeLayoutChildren(input.props.children, 'Grid');
1203   const cells = assignGridCells(children, container, options.columns.length, options.rows.length, options);
1204   const columns = intrinsicGridAxis(appendImplicitTracks(options.columns, options.autoColumn, maxGridExtent(cells.filter(cell => cell.normalized.position !== 'absolute'), 'column')), cells, 'columns', options.columnGap, container, input.service);
1205   if (columns.status === 'unsupported') return columns;
1206   const rows = intrinsicGridAxis(appendImplicitTracks(options.rows, options.autoRow, maxGridExtent(cells.filter(cell => cell.normalized.position !== 'absolute'), 'row')), cells, 'rows', options.rowGap, container, input.service);
1207   if (rows.status === 'unsupported') return rows;
1208   return {
1209     status: 'measured',
1210     minContent: { width: columns.min, height: rows.min },
1211     maxContent: { width: columns.max, height: rows.max },
1212   };
1213 }
1214 
1215 /** A declared finite Grid width selects the row-height query width. */
1216 function intrinsicGridSelectedWidth(
1217   input: import('../types.js').IntrinsicMeasureInput<GridProps, GridStyle>,
1218 ): Readonly<{ width: number; constraints: Constraints }> | undefined {
1219   const widthConstraint = input.constraints.width;
1220   const heightConstraint = input.constraints.height;
1221   if (
1222     input.style.width === undefined ||
1223     input.style.width === 'auto' ||
1224     widthConstraint.kind !== 'bounded' ||
1225     heightConstraint.kind !== 'bounded'
1226   ) {
1227     return undefined;
1228   }
1229   const constraints: Constraints = {
1230     minWidth: widthConstraint.min,
1231     maxWidth: widthConstraint.max,
1232     minHeight: heightConstraint.min,
1233     maxHeight: heightConstraint.max,
1234   };
1235   const width = resolveScalarSizingLength(input.style.width, widthConstraint.max, 'width', {
1236     component: 'Grid',
1237     algorithm: 'intrinsic measurement',
1238     constraints,
1239   });
1240   return width === undefined || width < 0 ? undefined : { width, constraints };
1241 }
1242 
1243 function containsFractionTrack(tracks: readonly GridTrack[]): boolean {
1244   for (const track of tracks) {
1245     if (typeof track === 'string' && track.endsWith('fr')) return true;
1246     if (typeof track === 'object' && track !== null && 'kind' in track) {
1247       if (track.kind === 'minmax' && (typeof track.min === 'string' && track.min.endsWith('fr') || typeof track.max === 'string' && track.max.endsWith('fr'))) return true;
1248       if (track.kind === 'repeat' && containsFractionTrack(track.tracks)) return true;
1249     }
1250   }
1251   return false;
1252 }
1253 
1254 function intrinsicGridAxis(
1255   tracks: readonly ParsedGridTrack[],
1256   cells: readonly GridCell[],
1257   axis: 'columns' | 'rows',
1258   gap: number,
1259   container: Readonly<LayoutBox>,
1260   service: CanvasMeasurementService,
1261 ): Readonly<{ status: 'measured'; min: number; max: number }> | Readonly<{ status: 'unsupported'; reason: string }> {
1262   const minimum = new Array<number>(tracks.length).fill(0);
1263   const maximum = new Array<number>(tracks.length).fill(0);
1264   for (let index = 0; index < tracks.length; index++) {
1265     const track = tracks[index]!;
1266     if (track.kind === 'fixed') minimum[index] = maximum[index] = track.value;
1267     else if (track.kind === 'fraction') return { status: 'unsupported', reason: `Grid fractional intrinsic measurement for ${axis} is allocation-dependent` };
1268     else if (track.kind === 'minmax' && track.max.kind === 'fraction') return { status: 'unsupported', reason: `Grid fractional intrinsic measurement for ${axis} is allocation-dependent` };
1269   }
1270   for (const cell of cells) {
1271     if (cell.normalized.position === 'absolute') continue;
1272     const start = axis === 'columns' ? cell.columnStart : cell.rowStart;
1273     const span = axis === 'columns' ? cell.columnSpan : cell.rowSpan;
1274     if (start < 1 || start + span - 1 > tracks.length) continue;
1275     const measured = measureIntrinsicElement(cell.child, { minWidth: 0, maxWidth: container.width, minHeight: 0, maxHeight: container.height }, service);
1276     if (measured.status === 'unsupported') return measured;
1277     const min = axis === 'columns' ? measured.minContent.width : measured.minContent.height;
1278     const max = axis === 'columns' ? measured.maxContent.width : measured.maxContent.height;
1279     let fixed = Math.max(0, span - 1) * gap;
1280     const eligible: number[] = [];
1281     for (let index = start - 1; index < start - 1 + span; index++) {
1282       if (trackNeedsIntrinsic(tracks[index]!)) eligible.push(index);
1283       else fixed += minimum[index]!;
1284     }
1285     if (eligible.length) {
1286       const minimumContribution = Math.max(0, min - fixed) / eligible.length;
1287       const maximumContribution = Math.max(0, max - fixed) / eligible.length;
1288       for (const index of eligible) {
1289         minimum[index] = Math.max(minimum[index]!, minimumContribution);
1290         maximum[index] = Math.max(maximum[index]!, maximumContribution);
1291       }
1292     }
1293   }
1294   const gaps = Math.max(0, tracks.length - 1) * gap;
1295   return { status: 'measured', min: minimum.reduce((total, value) => total + value, gaps), max: maximum.reduce((total, value) => total + value, gaps) };
1296 }
1297 
1298 function measuredLength(
1299   value: Exclude<BoxStyle['width'], undefined>,
1300   reference: number,
1301   property: string,
1302   constraints: Readonly<Constraints>,
1303 ): number {
1304   const resolved = resolveScalarSizingLength(value, reference, property, {
1305     component: 'Grid',
1306     algorithm: 'measurement',
1307     constraints,
1308   });
1309   if (resolved === undefined || resolved < 0) {
1310     throw layoutDiagnostic({
1311       component: 'Grid',
1312       property,
1313       value,
1314       algorithm: 'measurement',
1315       constraints,
1316       reason: 'requires a definite nonnegative container size',
1317     });
1318   }
1319   return resolved;
1320 }
1321 
1322 function normalizeGridOptions(
1323   style: Readonly<GridStyle>,
1324   container: Readonly<LayoutBox>,
1325 ) {
1326   if (
1327     !Array.isArray(style.gridTemplateColumns) ||
1328     style.gridTemplateColumns.length === 0
1329   ) {
1330     throw optionDiagnostic(
1331       'gridTemplateColumns',
1332       style.gridTemplateColumns,
1333       container,
1334       'requires a nonempty explicit columns list',
1335     );
1336   }
1337   if (
1338     !Array.isArray(style.gridTemplateRows) ||
1339     style.gridTemplateRows.length === 0
1340   ) {
1341     throw optionDiagnostic(
1342       'gridTemplateRows',
1343       style.gridTemplateRows,
1344       container,
1345       'requires a nonempty explicit rows list',
1346     );
1347   }
1348   const justifyItems = containerAlignment(
1349     style.justifyItems ?? 'stretch',
1350     'justifyItems',
1351     container,
1352   );
1353   const alignItems = containerAlignment(
1354     style.alignItems ?? 'stretch',
1355     'alignItems',
1356     container,
1357   );
1358   const gap = nonnegativeOption(style.gap ?? 0, 'gap', container);
1359   const rowGap = nonnegativeOption(style.rowGap ?? gap, 'rowGap', container);
1360   const columnGap = nonnegativeOption(
1361     style.columnGap ?? gap,
1362     'columnGap',
1363     container,
1364   );
1365   if (!nativeLayout && (style.gridAutoFlow !== undefined || style.gridAutoColumns !== undefined || style.gridAutoRows !== undefined)) throw optionDiagnostic('gridAutoFlow', style.gridAutoFlow, container, 'requires the native layout engine');
1366   const gridAutoFlow = style.gridAutoFlow ?? 'row';
1367   return {
1368     gridAutoFlow,
1369     columns: parseGridTracks(
1370       style.gridTemplateColumns,
1371       'columns',
1372       container,
1373       columnGap,
1374     ),
1375     rows: parseGridTracks(style.gridTemplateRows, 'rows', container, rowGap),
1376     autoColumn: nativeLayout ? parseGridTracks([style.gridAutoColumns ?? 'auto'], 'columns', container)[0]! : { kind: 'fixed' as const, value: 0 },
1377     autoRow: nativeLayout ? parseGridTracks([style.gridAutoRows ?? 'auto'], 'rows', container)[0]! : { kind: 'fixed' as const, value: 0 },
1378     autoFitColumns: containsAutoFit(style.gridTemplateColumns),
1379     autoFitRows: containsAutoFit(style.gridTemplateRows),
1380     layoutDirection: getLayoutDirection(),
1381     justifyItems,
1382     alignItems,
1383     rowGap,
1384     columnGap,
1385   };
1386 }
1387 
1388 function containerAlignment(
1389   value: unknown,
1390   property: string,
1391   container: Readonly<LayoutBox>,
1392 ): GridAlignment {
1393   if (
1394     value === 'stretch' ||
1395     value === 'start' ||
1396     value === 'center' ||
1397     value === 'end'
1398   )
1399     return value;
1400   throw optionDiagnostic(
1401     property,
1402     value,
1403     container,
1404     'uses an unsupported grid alignment',
1405   );
1406 }
1407 
1408 function itemAlignment(
1409   value: unknown,
1410   fallback: GridAlignment,
1411   property: string,
1412   child: PibblElement<any>,
1413   container: Readonly<LayoutBox>,
1414 ): GridAlignment {
1415   if (value === undefined || value === 'auto') return fallback;
1416   if (
1417     value === 'stretch' ||
1418     value === 'start' ||
1419     value === 'center' ||
1420     value === 'end'
1421   )
1422     return value;
1423   throw childDiagnostic(
1424     child,
1425     property,
1426     value,
1427     container,
1428     'uses an unsupported grid alignment',
1429   );
1430 }
1431 
1432 function placementInteger(
1433   value: unknown,
1434   property: string,
1435   child: PibblElement<any>,
1436   container: Readonly<LayoutBox>,
1437   required: boolean,
1438 ): number {
1439   if (value === undefined && required) {
1440     throw childDiagnostic(
1441       child,
1442       property,
1443       value,
1444       container,
1445       'is required for explicit grid placement',
1446     );
1447   }
1448   if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
1449     throw childDiagnostic(
1450       child,
1451       property,
1452       value,
1453       container,
1454       'must be a positive integer',
1455     );
1456   }
1457   return value;
1458 }
1459 
1460 function trackOffset(
1461   tracks: readonly number[],
1462   index: number,
1463   gap: number,
1464 ): number {
1465   return (
1466     tracks.slice(0, index).reduce((total, size) => total + size, 0) +
1467     index * gap
1468   );
1469 }
1470 
1471 function trackSpan(
1472   tracks: readonly number[],
1473   index: number,
1474   span: number,
1475   gap: number,
1476 ): number {
1477   return (
1478     tracks.slice(index, index + span).reduce((total, size) => total + size, 0) +
1479     Math.max(0, span - 1) * gap
1480   );
1481 }
1482 
1483 function alignmentOffset(
1484   area: number,
1485   item: number,
1486   alignment: GridAlignment,
1487 ): number {
1488   if (alignment === 'center') return (area - item) / 2;
1489   if (alignment === 'end') return area - item;
1490   return 0;
1491 }
1492 
1493 function nonnegativeOption(
1494   value: number,
1495   property: string,
1496   container: Readonly<LayoutBox>,
1497 ): number {
1498   if (!Number.isFinite(value) || value < 0) {
1499     throw optionDiagnostic(
1500       property,
1501       value,
1502       container,
1503       'requires a finite nonnegative number',
1504     );
1505   }
1506   return value;
1507 }
1508 
1509 function assertFiniteContainer(container: Readonly<LayoutBox>): void {
1510   for (const [property, value] of Object.entries(container)) {
1511     if (
1512       !Number.isFinite(value) ||
1513       ((property === 'width' || property === 'height') && value < 0)
1514     ) {
1515       throw optionDiagnostic(
1516         property,
1517         value,
1518         container,
1519         'requires finite nonnegative container geometry',
1520       );
1521     }
1522   }
1523 }
1524 
1525 function rejectUnsupportedItemFields(
1526   child: PibblElement<any>,
1527   style: Readonly<Record<string, unknown>>,
1528   container: Readonly<LayoutBox>,
1529 ): void {
1530   for (let propertyIndex = 0; propertyIndex < unsupportedProperties.length; propertyIndex++) {
1531     const property = unsupportedProperties[propertyIndex];
1532     if (style[property] !== undefined) {
1533       throw childDiagnostic(
1534         child,
1535         property,
1536         style[property],
1537         container,
1538         'is outside the explicit Grid subset',
1539       );
1540     }
1541   }
1542 }
1543 
1544 function trackDiagnostic(
1545   value: unknown,
1546   axis: string,
1547   container: Readonly<LayoutBox>,
1548 ) {
1549   return optionDiagnostic(
1550     axis === 'columns' ? 'gridTemplateColumns' : 'gridTemplateRows',
1551     value,
1552     container,
1553     'contains an unsupported track; use finite numbers, exact decimal percentages, or decimal fr units',
1554   );
1555 }
1556 
1557 function optionDiagnostic(
1558   property: string,
1559   value: unknown,
1560   container: Readonly<LayoutBox>,
1561   reason: string,
1562 ) {
1563   return layoutDiagnostic({
1564     component: 'Grid',
1565     property,
1566     value,
1567     algorithm: 'grid',
1568     constraints: constraintsFor(container),
1569     reason,
1570   });
1571 }
1572 
1573 function childDiagnostic(
1574   child: PibblElement<any>,
1575   property: string,
1576   value: unknown,
1577   container: Readonly<LayoutBox>,
1578   reason: string,
1579 ) {
1580   return layoutDiagnostic({
1581     component: child.type.name || 'Anonymous',
1582     property,
1583     value,
1584     algorithm: 'grid',
1585     constraints: constraintsFor(container),
1586     reason,
1587   });
1588 }
1589 
1590 function childContext(child: PibblElement<any>, container: Readonly<LayoutBox>) {
1591   return {
1592     component: child.type.name || 'Anonymous',
1593     algorithm: 'grid',
1594     constraints: constraintsFor(container),
1595   };
1596 }
1597 
1598 function constraintsFor(container: Readonly<LayoutBox>) {
1599   return {
1600     minWidth: 0,
1601     maxWidth: container.width,
1602     minHeight: 0,
1603     maxHeight: container.height,
1604   };
1605 }
1606 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.