packages/core/src/lib/layout/flow.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import { withAllocationCheckpoint } from './allocation-checkpoint.js';
2 import { contentBoxStyle } from './box-sizing.js';
3 import { canvasMeasurementService } from './canvas-measurement.js';
4 import { nativeLayout, mountedLayoutRegion, type LayoutRegion, 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, type PreparedQuery } 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 { setPreNormalizedStyle } from '../style/resolve-dispatch.js';
19 import type { BoxStyle, LayoutItemStyle, ResolvedBoxStyle } from '../style/types.js';
20 import type {
21 CanvasMeasurementService,
22 PibblNodeInput,
23 IntrinsicMeasureInput,
24 IntrinsicSizesResult,
25 MeasureInput,
26 MeasureResult,
27 RenderingContext2D,
28 SystemStyle,
29 } from '../types.js';
30 import {
31 childWithUsedSize,
32 materializeLayoutChildren,
33 prepareDirectChildStyle,
34 placeDirectChildren,
35 prepareLayoutChildren,
36 resolveContainerBox,
37 resolveDirectChildBox,
38 } from './absolute.js';
39 import { pushLayoutBox, resolvePositionedContainingBox } from './context.js';
40 import { recordLayoutEvaluation } from './diagnostics.js';
41 import { assertSupportedChildPosition } from './positioning-diagnostics.js';
42 import { measureElement, measureIntrinsicElement } from './measure.js';
43 import type { Constraints, LayoutBox } from './types.js';
44
45 type FlowDirection = 'horizontal' | 'vertical';
46 type FlowAlignment = 'start' | 'center' | 'end' | 'stretch';
47
48 /**
49 * Supported geometry and presentation properties for Flow.
50 *
51 * @see {@link BoxStyle}
52 * @see {@link LayoutItemStyle}
53 * @see {@link Flow}
54 */
55 export interface FlowStyle extends BoxStyle, LayoutItemStyle {
56 /** Direction in which this operation proceeds. See {@link FlowDirection}. */
57 direction?: FlowDirection;
58 /** Whether content may wrap into additional lines. See {@link FlowStyle}. */
59 wrap?: boolean;
60 /** Spacing between adjacent items. See {@link FlowStyle}. */
61 gap?: number;
62 /** Space between wrapped flow lines. See {@link FlowStyle}. */
63 lineGap?: number;
64 /** Default alignment of children on the cross or block axis. See {@link FlowAlignment}. */
65 alignItems?: FlowAlignment;
66 }
67
68 /**
69 * Authored inputs for Flow, including the declared data and presentation options.
70 *
71 * @see {@link PibblNodeInput}
72 * @see {@link Flow}
73 */
74 export interface FlowProps extends PibblStructuralEventProps {
75 /** Descendant content or the callback that supplies it. See {@link PibblNodeInput}. */
76 children: PibblNodeInput;
77 }
78
79 // Parent input is private metadata, not a recursively validated resolved value.
80 const FLOW_CONTAINING_BOX_STYLE = Symbol('pibbl.flow-containing-box-style');
81
82 interface ResolvedFlowStyle extends SystemStyle {
83 box: ResolvedBoxStyle;
84 [FLOW_CONTAINING_BOX_STYLE]: Readonly<FlowStyle>;
85 overflow: 'visible' | 'clip';
86 direction: FlowDirection;
87 wrap: boolean;
88 gap: number;
89 lineGap: number;
90 alignItems: FlowAlignment;
91 }
92
93 interface FlowItem {
94 child: PibblElement<any>;
95 normalized: Readonly<SystemStyle>;
96 width: number;
97 height: number;
98 horizontalPadding: number;
99 verticalPadding: number;
100 alignment: FlowAlignment;
101 receiverToken: object;
102 query?: PreparedQuery;
103 }
104
105 export interface FlowMeasurementInput {
106 service: CanvasMeasurementService;
107 measureElement(
108 element: PibblElement<any>,
109 constraints: Readonly<Constraints>,
110 ): MeasureResult;
111 }
112
113 interface FlowPlacement {
114 usedWidth: number; usedHeight: number;
115 box: LayoutBox;
116 element: PibblElement<any>;
117 }
118
119 function renderFlow(
120 props: FlowProps,
121 style: Readonly<ResolvedFlowStyle>,
122 ctx: RenderingContext2D,
123 ) {
124 wireStructuralEvents(props);
125 recordLayoutEvaluation();
126 const content = style.box.contentBox;
127 ctx.translate(content.x, content.y);
128 const localContent = Object.freeze({
129 x: 0,
130 y: 0,
131 width: content.width,
132 height: content.height,
133 });
134 const releaseLayout = pushLayoutBox(localContent, {
135 logicalOffset: content,
136 containingBlock: resolvePositionedContainingBox(
137 style[FLOW_CONTAINING_BOX_STYLE],
138 localContent,
139 'Flow',
140 ),
141 });
142 GLOBAL_STATE.componentRefs!.onAfterRender = releaseLayout;
143 const prepared = nativeLayout ? claimPreparedLayoutPlan(GLOBAL_STATE.componentRefs!.element, localContent) : undefined;
144 const nativeRegion = prepared?.region ?? (nativeLayout ? mountedLayoutRegion() : undefined);
145 if (nativeLayout && !nativeRegion) throw new Error('Experimental Flow requires its mounted native region.');
146 const plan = prepared ?? prepareFlowAllocation(props, style, localContent, ctx, nativeRegion);
147 const { children, placements } = plan;
148 let index = 0;
149 return placeDirectChildren(
150 children,
151 localContent,
152 (_child, occurrence) => {
153 const placement = placements[index++];
154 if (nativeLayout && !prepared) preparePlacedKnownLayout(placement.element, occurrence);
155 return placement;
156 },
157 style.overflow,
158 );
159 }
160
161 /**
162 * Describes sequential flow layout for JSX or createElement authoring.
163 *
164 * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
165 * props and style types.
166 * @throws When called directly; Pibbl mounts this component through JSX or createElement.
167 *
168 * @see {@link FlowProps}
169 * @see {@link FlowStyle}
170 */
171 export const Flow = definePrimitive<
172 FlowProps,
173 FlowStyle,
174 FlowStyle,
175 ResolvedFlowStyle
176 >(renderFlow, {
177 childInput: 'structural',
178 resolveStyle: (style, context) => {
179 if (nativeLayout && hasPercentageBoxPadding(style)) {
180 style = resolveAllocatedInsets(style, { width: context.percentageBasis.width,
181 context: { ...context, component: 'Flow', algorithm: 'flow' } });
182 }
183 return {
184 box: resolveContainerBox(style, context, 'Flow', 'flow'),
185 [FLOW_CONTAINING_BOX_STYLE]: style,
186 overflow: style.overflow ?? 'visible',
187 ...normalizeFlowOptions(style, context.allocation),
188 };
189 },
190 measure: input => measureFlow(input),
191 measureIntrinsic: input => measureFlowIntrinsic(input),
192 });
193
194 interface IntrinsicFlowItem {
195 readonly child: PibblElement<any>;
196 readonly style: Readonly<BoxStyle & LayoutItemStyle>;
197 readonly receiver: object;
198 readonly query?: PreparedQuery;
199 readonly horizontalInsets: number;
200 readonly verticalInsets: number;
201 readonly minWidth: number;
202 readonly maxWidth: number;
203 }
204
205 /** Pure paired contributions for a declared Flow sequence. */
206 function measureFlowIntrinsic(
207 input: IntrinsicMeasureInput<FlowProps, FlowStyle>,
208 ): IntrinsicSizesResult {
209 const maximumWidth = intrinsicConstraintMaximum(input.constraints.width);
210 const maximumHeight = intrinsicConstraintMaximum(input.constraints.height);
211 const owner = { x: 0, y: 0, width: maximumWidth, height: maximumHeight };
212 const options = normalizeFlowOptions(input.style, owner);
213 const children = materializeLayoutChildren(input.props.children, 'Flow');
214 const items: IntrinsicFlowItem[] = [];
215 let maximumWidthContribution = 0;
216 let minimumWidthContribution = 0;
217
218 for (let index = 0; index < children.length; index++) {
219 const child = children[index]!;
220 const receiver = getChildPrimitiveReceiverToken(
221 GLOBAL_STATE.renderTransaction,
222 GLOBAL_STATE.primitiveReceiverToken,
223 index,
224 );
225 const prepared = prepareDirectChildStyle(child, receiver, owner);
226 let style = preparedStyleValue(prepared) as Readonly<BoxStyle & LayoutItemStyle>;
227 if (hasIntrinsicPercentageCycle(style)) {
228 return { status: 'unsupported', reason: 'Flow intrinsic percentage child sizes require a definite owner allocation' };
229 }
230 if (style.boxSizing !== undefined) {
231 style = contentBoxStyle(style, {
232 width: owner.width,
233 height: owner.height,
234 context: {
235 component: child.type.name || 'Anonymous', algorithm: 'Flow intrinsic measurement',
236 constraints: { minWidth: 0, maxWidth: owner.width, minHeight: 0, maxHeight: owner.height },
237 },
238 });
239 }
240 assertSupportedChildPosition('Flow', child, style);
241 const insets = normalizeBoxInsets(style, {
242 component: child.type.name || 'Anonymous', algorithm: 'Flow intrinsic measurement',
243 constraints: { minWidth: 0, maxWidth: owner.width, minHeight: 0, maxHeight: owner.height },
244 });
245 const horizontalInsets = insets.left + insets.right;
246 const verticalInsets = insets.top + insets.bottom;
247 let minWidth: number;
248 let maxWidth: number;
249 if (typeof style.width === 'number' && typeof style.height === 'number') {
250 minWidth = style.width + horizontalInsets;
251 maxWidth = minWidth;
252 } else {
253 const measuredChild = clonePibblElement(child);
254 setPreNormalizedStyle(measuredChild, style, child, receiver, preparedStyleQuery(prepared));
255 const measured = measureIntrinsicElement(measuredChild, {
256 minWidth: 0, maxWidth: owner.width, minHeight: 0, maxHeight: owner.height,
257 }, input.service);
258 if (measured.status !== 'measured') return measured;
259 minWidth = (typeof style.width === 'number' ? style.width : measured.minContent.width) + horizontalInsets;
260 maxWidth = (typeof style.width === 'number' ? style.width : measured.maxContent.width) + horizontalInsets;
261 }
262 if (!Number.isFinite(minWidth) || !Number.isFinite(maxWidth) || minWidth < 0 || maxWidth < minWidth) {
263 return { status: 'unsupported', reason: 'Flow intrinsic child widths must be finite and ordered' };
264 }
265 items.push({ child, style, receiver, query: preparedStyleQuery(prepared), horizontalInsets, verticalInsets, minWidth, maxWidth });
266 minimumWidthContribution = options.wrap ? Math.max(minimumWidthContribution, minWidth) : minimumWidthContribution + minWidth;
267 maximumWidthContribution += maxWidth;
268 }
269 const gaps = Math.max(0, items.length - 1) * options.gap;
270 if (!options.wrap) minimumWidthContribution += gaps;
271 maximumWidthContribution += gaps;
272 const minimumHeight = measureIntrinsicFlowHeight(items, minimumWidthContribution, false, options, input, owner);
273 if (minimumHeight.status !== 'measured') return minimumHeight;
274 const maximumHeightResult = measureIntrinsicFlowHeight(items, maximumWidthContribution, true, options, input, owner);
275 if (maximumHeightResult.status !== 'measured') return maximumHeightResult;
276 return {
277 status: 'measured',
278 minContent: { width: minimumWidthContribution, height: minimumHeight.height },
279 maxContent: { width: maximumWidthContribution, height: maximumHeightResult.height },
280 };
281 }
282
283 function intrinsicConstraintMaximum(constraint: IntrinsicMeasureInput<FlowProps, FlowStyle>['constraints']['width']): number {
284 return constraint.kind === 'bounded' ? constraint.max : Number.MAX_SAFE_INTEGER;
285 }
286
287 function hasIntrinsicPercentageCycle(style: Readonly<BoxStyle>): boolean {
288 return hasPercentageBoxPadding(style) || isPercentageLength(style.width) || isPercentageLength(style.height) ||
289 isPercentageLength(style.minWidth) || isPercentageLength(style.maxWidth) ||
290 isPercentageLength(style.minHeight) || isPercentageLength(style.maxHeight);
291 }
292
293 function isPercentageLength(value: unknown): boolean {
294 return typeof value === 'string' && value.endsWith('%');
295 }
296
297 function measureIntrinsicFlowHeight(
298 items: readonly IntrinsicFlowItem[],
299 width: number,
300 maximumWidths: boolean,
301 options: ReturnType<typeof normalizeFlowOptions>,
302 input: IntrinsicMeasureInput<FlowProps, FlowStyle>,
303 owner: Readonly<LayoutBox>,
304 ): Readonly<{ status: 'measured'; height: number }> | Readonly<{ status: 'unsupported'; reason: string }> {
305 const placements: FlowItem[] = [];
306 for (const item of items) {
307 const selectedWidth = maximumWidths ? item.maxWidth : item.minWidth;
308 const contentWidth = Math.max(0, (width === 0 ? 0 : options.wrap ? Math.min(width, selectedWidth) : selectedWidth) - item.horizontalInsets);
309 let contentHeight: number;
310 if (typeof item.style.height === 'number') {
311 contentHeight = item.style.height;
312 } else {
313 const measuredChild = clonePibblElement(item.child);
314 setPreNormalizedStyle(measuredChild, { ...item.style, width: contentWidth } as Readonly<BoxStyle & LayoutItemStyle>, item.child, item.receiver, item.query);
315 const measured = measureElement(measuredChild, {
316 minWidth: contentWidth, maxWidth: contentWidth,
317 minHeight: 0, maxHeight: owner.height,
318 }, input.service);
319 if (measured.status !== 'measured') return measured;
320 contentHeight = measured.size.height;
321 }
322 if (!Number.isFinite(contentHeight) || contentHeight < 0) {
323 return { status: 'unsupported', reason: 'Flow intrinsic child heights must be finite and nonnegative' };
324 }
325 placements.push({
326 child: item.child, normalized: item.style, width: contentWidth + item.horizontalInsets,
327 height: contentHeight + item.verticalInsets, horizontalPadding: item.horizontalInsets,
328 verticalPadding: item.verticalInsets, alignment: options.alignItems, receiverToken: item.receiver,
329 query: item.query,
330 });
331 }
332 const boxes = arrangeFlowItems({ x: 0, y: 0, width, height: owner.height }, placements, options);
333 let height = 0;
334 for (const box of boxes) height = Math.max(height, box.y + box.height);
335 return { status: 'measured', height };
336 }
337
338 function prepareFlowAllocation(props: FlowProps, style: Readonly<FlowStyle>, content: Readonly<LayoutBox>, ctx: RenderingContext2D, region?: LayoutRegion): { children: readonly PibblElement<any>[]; placements: FlowPlacement[] } {
339 const children = prepareLayoutChildren(props.children, 'Flow');
340 const service = canvasMeasurementService(ctx);
341 const placements = withAllocationCheckpoint(region, { children, content, settings: style, onHit: recordWasmAllocationCacheHit, calculate: () => resolveFlowPlacements(content, children, style, { service, measureElement: (child, constraints) => measureElement(child, constraints, service) }, region) });
342 return { children, placements };
343 }
344 if (nativeLayout) registerKnownLayoutPreflight(Flow, (element, style, content, receiver, slot) => {
345 const previous = GLOBAL_STATE.primitiveReceiverToken;
346 GLOBAL_STATE.primitiveReceiverToken = receiver;
347 const releaseLayout = pushLayoutBox(content, {
348 containingBlock: resolvePositionedContainingBox(
349 style as Readonly<FlowStyle>,
350 content,
351 'Flow',
352 ),
353 });
354 try {
355 const options = normalizeFlowOptions(style as Readonly<FlowStyle>, content);
356 const ctx = GLOBAL_STATE.renderContext;
357 if (!ctx) throw new Error('Known Flow preparation requires a Canvas measurement context.');
358 const region = slot.acquire();
359 const allocation = prepareFlowAllocation(element.props as FlowProps, options, content, ctx, region);
360 const plan: PreparedLayoutPlan = { region, content, ...allocation };
361 prepareKnownLayoutDescendants(plan, slot);
362 stagePreparedLayoutPlan(slot, plan);
363 } finally {
364 releaseLayout();
365 GLOBAL_STATE.primitiveReceiverToken = previous;
366 }
367 });
368
369 export function layoutFlow(
370 container: Readonly<LayoutBox>,
371 children: PibblNodeInput,
372 style: Readonly<FlowStyle>,
373 measurement: FlowMeasurementInput,
374 ): LayoutBox[] {
375 const prepared = materializeLayoutChildren(children, 'Flow');
376 return resolveFlowPlacements(container, prepared, style, measurement)
377 .map(placement => placement.box);
378 }
379
380 function resolveFlowPlacements(
381 container: Readonly<LayoutBox>,
382 children: readonly PibblElement<any>[],
383 style: Readonly<FlowStyle>,
384 measurement: FlowMeasurementInput,
385 nativeRegion?: LayoutRegion,
386 ): FlowPlacement[] {
387 if (nativeRegion) recordWasmAllocationPass();
388 assertFiniteContainer(container);
389 const options = normalizeFlowOptions(style, container);
390 const items: FlowItem[] = [];
391 for (const child of children) {
392 if (nativeRegion) recordWasmAllocationItem();
393 const receiverToken = getChildPrimitiveReceiverToken(
394 GLOBAL_STATE.renderTransaction,
395 GLOBAL_STATE.primitiveReceiverToken,
396 items.length,
397 );
398 const prepared = prepareDirectChildStyle(child, receiverToken, container);
399 let normalized = preparedStyleValue(prepared) as Readonly<
400 BoxStyle & LayoutItemStyle
401 >;
402 if (nativeLayout && GLOBAL_STATE.currentPibblInstance && getStyleMeasurementMode() === undefined && hasPercentageBoxPadding(normalized)) {
403 normalized = resolveAllocatedInsets(normalized, { width: container.width, context: { component: child.type.name || 'Anonymous', algorithm: 'flow' } });
404 }
405 if (normalized.boxSizing !== undefined) normalized = contentBoxStyle(normalized, { width: container.width, height: container.height, context: { component: child.type.name || 'Anonymous', algorithm: 'flow', constraints: { minWidth: 0, maxWidth: container.width, minHeight: 0, maxHeight: container.height } } });
406 assertSupportedChildPosition('Flow', child, normalized);
407 const needsWidth = normalized.width === undefined || normalized.width === 'auto';
408 const needsHeight = normalized.height === undefined || normalized.height === 'auto';
409 let measuredWidth: number | undefined;
410 let measuredHeight: number | undefined;
411 if (needsWidth || needsHeight) {
412 const constraints = {
413 minWidth: 0,
414 maxWidth: container.width,
415 minHeight: 0,
416 maxHeight: container.height,
417 };
418 const measurementChild = clonePibblElement(child);
419 setPreNormalizedStyle(
420 measurementChild,
421 normalized,
422 child,
423 receiverToken,
424 preparedStyleQuery(prepared),
425 );
426 const result = measurement.measureElement(measurementChild, constraints);
427 if (result.status === 'unsupported') {
428 const axis = needsWidth ? 'width' : 'height';
429 throw layoutDiagnostic({
430 component: child.type.name || 'Anonymous',
431 property: axis,
432 value: normalized[axis] ?? 'auto',
433 algorithm: 'flow',
434 constraints,
435 reason: `measurement is required but unsupported: ${result.reason}`,
436 });
437 }
438 measuredWidth = result.size.width;
439 measuredHeight = result.size.height;
440 }
441 const resolvedStyle = {
442 ...normalized,
443 width: needsWidth ? measuredWidth : normalized.width,
444 height: needsHeight ? measuredHeight : normalized.height,
445 };
446 const resolved = resolveDirectChildBox(
447 container,
448 child,
449 'flow',
450 resolvedStyle,
451 measurement.service,
452 receiverToken,
453 );
454 const box = resolved.borderBox;
455 items.push({
456 child,
457 normalized: Object.freeze(resolvedStyle),
458 width: box.width,
459 height: box.height,
460 horizontalPadding: box.width - resolved.contentBox.width,
461 verticalPadding: box.height - resolved.contentBox.height,
462 alignment: resolveItemAlignment(
463 normalized.alignSelf,
464 options.alignItems,
465 child,
466 container,
467 ),
468 receiverToken,
469 query: preparedStyleQuery(prepared),
470 });
471 }
472
473 const nativeBoxes = nativeRegion?.placeFlow(items, { horizontal: options.direction === 'horizontal', mainBound: options.direction === 'horizontal' ? container.width : container.height, gap: options.gap, lineGap: options.lineGap, wrap: options.wrap });
474 const boxes = nativeBoxes ?? arrangeFlowItems(container, items, options);
475 return boxes.map((box, index) => {
476 const usedWidth = Math.max(0, box.width - items[index].horizontalPadding);
477 const usedHeight = Math.max(0, box.height - items[index].verticalPadding);
478 return {
479 box: nativeBoxes && (container.x !== 0 || container.y !== 0) ? { x: container.x + box.x, y: container.y + box.y, width: box.width, height: box.height } : box,
480 usedWidth, usedHeight,
481 element: childWithUsedSize(items[index].child, items[index].normalized, usedWidth, usedHeight, items[index].receiverToken, items[index].query),
482 };
483 });
484 }
485
486 function measureFlow(
487 input: MeasureInput<FlowProps, FlowStyle>,
488 ): MeasureResult {
489 const children = prepareLayoutChildren(input.props.children, 'Flow');
490 const widthDefinite = input.style.width !== undefined &&
491 input.style.width !== 'auto';
492 const heightDefinite = input.style.height !== undefined &&
493 input.style.height !== 'auto';
494 const provisional = provisionalFlowBox(input.style, input.constraints);
495 if (widthDefinite && heightDefinite) {
496 return { status: 'measured', size: {
497 width: provisional.content.width,
498 height: provisional.content.height,
499 } };
500 }
501
502 const placements = resolveFlowPlacements(
503 provisional.content,
504 children,
505 input.style,
506 input,
507 );
508 let intrinsicWidth = 0;
509 let intrinsicHeight = 0;
510 for (const placement of placements) {
511 intrinsicWidth = Math.max(
512 intrinsicWidth,
513 placement.box.x - provisional.content.x + placement.box.width,
514 );
515 intrinsicHeight = Math.max(
516 intrinsicHeight,
517 placement.box.y - provisional.content.y + placement.box.height,
518 );
519 }
520 validateMeasuredExtent(intrinsicWidth, 'width', input.constraints);
521 validateMeasuredExtent(intrinsicHeight, 'height', input.constraints);
522 return { status: 'measured', size: {
523 width: widthDefinite ? provisional.content.width : intrinsicWidth,
524 height: heightDefinite ? provisional.content.height : intrinsicHeight,
525 } };
526 }
527
528 function provisionalFlowBox(
529 style: Readonly<FlowStyle>,
530 constraints: Readonly<Constraints>,
531 ): { border: LayoutBox; content: LayoutBox } {
532 const diagnosticContext = {
533 component: 'Flow',
534 algorithm: 'measurement',
535 constraints,
536 };
537 const padding = normalizeBoxInsets(style, diagnosticContext);
538 const width = finiteMeasurementBound(
539 constraints.maxWidth,
540 [style.width, style.minWidth, style.maxWidth],
541 padding.left + padding.right,
542 'width',
543 constraints,
544 );
545 const height = finiteMeasurementBound(
546 constraints.maxHeight,
547 [style.height, style.minHeight, style.maxHeight],
548 padding.top + padding.bottom,
549 'height',
550 constraints,
551 );
552 const box = resolveContainerBox(style, {
553 allocation: { x: 0, y: 0, width, height },
554 percentageBasis: { x: 0, y: 0, width, height },
555 constraints,
556 component: 'Flow',
557 algorithm: 'render-dispatch',
558 }, 'Flow', 'measurement');
559 return { border: box.borderBox, content: box.contentBox };
560 }
561
562 function finiteMeasurementBound(
563 maximum: number,
564 specified: readonly (BoxStyle['width'] | undefined)[],
565 padding: number,
566 property: 'width' | 'height',
567 constraints: Readonly<Constraints>,
568 ): number {
569 if (Number.isFinite(maximum)) return maximum;
570 const numeric = specified.filter(
571 (value): value is number => typeof value === 'number' && Number.isFinite(value),
572 );
573 if (numeric.length > 0) {
574 const bound = Math.max(...numeric) + padding;
575 if (Number.isFinite(bound)) return bound;
576 throw layoutDiagnostic({
577 component: 'Flow',
578 property,
579 value: bound,
580 algorithm: 'measurement',
581 constraints,
582 reason: 'measurement allocation arithmetic must remain finite',
583 });
584 }
585 const percentage = specified.find(
586 value => typeof value === 'string' && value.endsWith('%'),
587 );
588 if (percentage !== undefined) {
589 throw layoutDiagnostic({
590 component: 'Flow',
591 property,
592 value: percentage,
593 algorithm: 'measurement',
594 constraints,
595 reason: 'requires a definite finite percentage reference',
596 });
597 }
598 return Number.MAX_SAFE_INTEGER;
599 }
600
601 function validateMeasuredExtent(
602 value: number,
603 property: string,
604 constraints: Readonly<Constraints>,
605 ): void {
606 if (!Number.isFinite(value) || value < 0) {
607 throw layoutDiagnostic({
608 component: 'Flow',
609 property,
610 value,
611 algorithm: 'measurement',
612 constraints,
613 reason: 'intrinsic flow extent must be finite and nonnegative',
614 });
615 }
616 }
617
618 function arrangeFlowItems(
619 container: Readonly<LayoutBox>,
620 items: readonly FlowItem[],
621 options: ReturnType<typeof normalizeFlowOptions>,
622 ): LayoutBox[] {
623 const horizontal = options.direction === 'horizontal';
624 const mainBound = horizontal ? container.width : container.height;
625 const lines: FlowItem[][] = [];
626 let line: FlowItem[] = [];
627 let occupiedMain = 0;
628 for (const item of items) {
629 const mainSize = horizontal ? item.width : item.height;
630 const nextMain = line.length === 0 ?
631 mainSize :
632 occupiedMain + options.gap + mainSize;
633 if (options.wrap && line.length > 0 && nextMain > mainBound) {
634 lines.push(line);
635 line = [];
636 occupiedMain = 0;
637 }
638 occupiedMain = line.length === 0 ?
639 mainSize :
640 occupiedMain + options.gap + mainSize;
641 line.push(item);
642 }
643 if (line.length > 0) lines.push(line);
644
645 const placements: LayoutBox[] = [];
646 let crossCursor = 0;
647 for (const currentLine of lines) {
648 const lineCross = Math.max(0, ...currentLine.map(item =>
649 horizontal ? item.height : item.width,
650 ));
651 let mainCursor = 0;
652 for (const item of currentLine) {
653 const itemMain = horizontal ? item.width : item.height;
654 const itemCross = horizontal ? item.height : item.width;
655 const crossOffset = alignCross(lineCross, itemCross, item.alignment);
656 const placedCross = item.alignment === 'stretch' ?
657 Math.max(0, lineCross) :
658 itemCross;
659 placements.push(horizontal ? {
660 x: container.x + mainCursor,
661 y: container.y + crossCursor + crossOffset,
662 width: itemMain,
663 height: placedCross,
664 } : {
665 x: container.x + crossCursor + crossOffset,
666 y: container.y + mainCursor,
667 width: placedCross,
668 height: itemMain,
669 });
670 mainCursor += itemMain + options.gap;
671 }
672 crossCursor += lineCross + options.lineGap;
673 }
674 return placements;
675 }
676
677 function normalizeFlowOptions(
678 style: Readonly<FlowStyle>,
679 container: Readonly<LayoutBox>,
680 ) {
681 const direction = style.direction ?? 'horizontal';
682 if (direction !== 'horizontal' && direction !== 'vertical') {
683 throw optionDiagnostic('direction', direction, container);
684 }
685 if (style.wrap !== undefined && typeof style.wrap !== 'boolean') {
686 throw optionDiagnostic('wrap', style.wrap, container);
687 }
688 const alignItems = style.alignItems ?? 'start';
689 if (
690 alignItems !== 'start' && alignItems !== 'center' &&
691 alignItems !== 'end' && alignItems !== 'stretch'
692 ) {
693 throw optionDiagnostic('alignItems', alignItems, container);
694 }
695 return {
696 direction,
697 wrap: style.wrap ?? false,
698 gap: nonnegativeOption(style.gap ?? 0, 'gap', container),
699 lineGap: nonnegativeOption(style.lineGap ?? 0, 'lineGap', container),
700 alignItems,
701 };
702 }
703
704 function nonnegativeOption(
705 value: number,
706 property: string,
707 container: Readonly<LayoutBox>,
708 ): number {
709 if (!Number.isFinite(value) || value < 0) {
710 throw optionDiagnostic(property, value, container);
711 }
712 return value;
713 }
714
715 function resolveItemAlignment(
716 value: LayoutItemStyle['alignSelf'],
717 fallback: FlowAlignment,
718 child: PibblElement<any>,
719 container: Readonly<LayoutBox>,
720 ): FlowAlignment {
721 if (value === undefined || value === 'auto') return fallback;
722 if (value === 'start' || value === 'center' || value === 'end' || value === 'stretch') {
723 return value;
724 }
725 throw layoutDiagnostic({
726 component: child.type.name || 'Anonymous',
727 property: 'alignSelf',
728 value,
729 algorithm: 'flow',
730 constraints: constraintsFor(container),
731 reason: 'uses an unsupported flow alignment value',
732 });
733 }
734
735 function alignCross(
736 lineCross: number,
737 itemCross: number,
738 alignment: FlowAlignment,
739 ): number {
740 if (alignment === 'center') return (lineCross - itemCross) / 2;
741 if (alignment === 'end') return lineCross - itemCross;
742 return 0;
743 }
744
745 function assertFiniteContainer(container: Readonly<LayoutBox>): void {
746 for (const [property, value] of Object.entries(container)) {
747 if (!Number.isFinite(value) ||
748 ((property === 'width' || property === 'height') && value < 0)) {
749 throw optionDiagnostic(property, value, container);
750 }
751 }
752 }
753
754 function optionDiagnostic(
755 property: string,
756 value: unknown,
757 container: Readonly<LayoutBox>,
758 ) {
759 return layoutDiagnostic({
760 component: 'Flow',
761 property,
762 value,
763 algorithm: 'flow',
764 constraints: constraintsFor(container),
765 reason: 'uses an unsupported flow value',
766 });
767 }
768
769 function constraintsFor(container: Readonly<LayoutBox>) {
770 return {
771 minWidth: 0,
772 maxWidth: container.width,
773 minHeight: 0,
774 maxHeight: container.height,
775 };
776 }
777
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.