packages/core/src/lib/layout/absolute.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import { recordAllocationStyle, configureAllocationCheckpointAdapter, withAllocationCheckpoint, mountedAllocationCheckpointOwner } from './allocation-checkpoint.js';
2 import { participatingLayoutChildren, layoutParticipationPlan, type LayoutParticipationSource } from './participation.js';
3 import { allocatedContentBoxStyle, contentBoxStyle } from './box-sizing.js';
4 import { recordWasmAllocationPass, recordWasmAllocationItem, recordWasmAllocationCacheHit, nativeLayout } from './wasm/region.js';
5 import { registerKnownLayoutPreflight, isKnownLayoutType, claimPreparedLayoutPlan, stagePreparedLayoutPlan, prepareKnownLayoutDescendants, preparePlacedKnownLayout, takePreparedChildStyle, stagePreparedChildStyle, type PreparedLayoutPlan } from './prepared-root.js';
6 import { isLayoutComponent, prepareLayoutComponent } from './define-layout-component.js';
7 import { ResponsiveStylePreparation, getStyleMeasurementMode, preparedStyleValue, preparedStyleQuery, type PreparedQuery } from '../style/responsive.js';
8 import { definePrimitive } from '../define-primitive.js';
9 import { EMPTY_STYLE } from '../style/empty-style.js';
10 import { materializeContainerChildren } from '../element/children.js';
11 import { clonePibblElement } from '../element/create-element.js';
12 import {
13 getElementMetadata,
14 setElementMetadata,
15 getPrimitiveDefinition,
16 getChildPrimitiveReceiverToken,
17 setPlacementConsumed,
18 } from '../element/metadata.js';
19 import { resolvePrimitiveStyleInput } from '../element/resolve-primitive-inputs.js';
20 import type { PibblElement } from '../element/types.js';
21 import { GLOBAL_STATE } from '../global-state.js';
22 import { normalizeBoxInsets, hasPercentageBoxPadding, resolveAllocatedInsets } from './box-insets.js';
23 import { isFitContent, isIntrinsicSizingValue, resolveScalarSizingLength } from '../style/sizing-length.js';
24 import {
25 extractSystemFilter,
26 setPreNormalizedStyle, setAllocatedContentSize,
27 withoutSystemFilter,
28 } from '../style/resolve-dispatch.js';
29 import type {
30 BoxStyle,
31 LayoutItemStyle,
32 ResolvedBoxStyle,
33 } from '../style/types.js';
34 import type {
35 IntrinsicMeasureInput,
36 IntrinsicSizesResult,
37 CanvasMeasurementService,
38 PibblNodeInput,
39 PibblRenderTransaction,
40 RenderingContext2D,
41 StyleResolutionContext,
42 SystemStyle,
43 } from '../types.js';
44 import { measureElement, measureIntrinsicElement } from './measure.js';
45 import { canvasMeasurementService } from './canvas-measurement.js';
46 import { layoutDiagnostic } from '../style/diagnostics.js';
47 import {
48 type PibblStructuralEventProps,
49 wireStructuralEvents,
50 } from '../components/structural-events.js';
51 import { pushLayoutBox, resolvePositionedContainingBox } from './context.js';
52 import { recordLayoutEvaluation } from './diagnostics.js';
53 import { resolveBox } from './box.js';
54 import {
55 createPlacementIdentityHint,
56 placeChild,
57 } from './place-child.js';
58 import type { LayoutBox } from './types.js';
59 import { withReceiverInputProvision, captureReceiverInputProvision } from '../signals/input-provision.js';
60 import { assertSupportedChildPosition } from './positioning-diagnostics.js';
61
62 /**
63 * Supported geometry and presentation properties for Absolute.
64 *
65 * @see {@link BoxStyle}
66 * @see {@link LayoutItemStyle}
67 * @see {@link Absolute}
68 */
69 export type AbsoluteStyle = BoxStyle & LayoutItemStyle;
70
71 /**
72 * Authored inputs for Absolute, including the declared data and presentation options.
73 *
74 * @see {@link PibblNodeInput}
75 * @see {@link Absolute}
76 */
77 export interface AbsoluteProps extends PibblStructuralEventProps {
78 /** Descendant content or the callback that supplies it. See {@link PibblNodeInput}. */
79 children: PibblNodeInput;
80 }
81
82 // Parent input is private metadata, not a recursively validated resolved value.
83 const ABSOLUTE_CONTAINING_BOX_STYLE = Symbol('pibbl.absolute-containing-box-style');
84
85 interface ResolvedAbsoluteStyle extends SystemStyle {
86 box: ResolvedBoxStyle;
87 [ABSOLUTE_CONTAINING_BOX_STYLE]: Readonly<AbsoluteStyle>;
88 overflow: 'visible' | 'clip';
89 }
90
91 type LayoutReceiver = 'Absolute' | 'Overlay' | 'Flow' | 'Flex' | 'Grid' | 'Layer';
92
93 const preparedLayoutTransactions = new WeakMap<
94 PibblRenderTransaction,
95 WeakMap<object, readonly PibblElement<any>[]>
96 >();
97
98 function renderAbsolute(
99 props: AbsoluteProps,
100 style: Readonly<ResolvedAbsoluteStyle>,
101 ctx: RenderingContext2D,
102 ) {
103 wireStructuralEvents(props);
104 const ordinaryChildren = nativeLayout ? undefined : prepareLayoutChildren(props.children, 'Absolute');
105 recordLayoutEvaluation();
106 const content = style.box.contentBox;
107 ctx.translate(content.x, content.y);
108 const localContent = Object.freeze({
109 x: 0,
110 y: 0,
111 width: content.width,
112 height: content.height,
113 });
114 const releaseLayout = pushLayoutBox(localContent, {
115 logicalOffset: content,
116 containingBlock: resolvePositionedContainingBox(
117 style[ABSOLUTE_CONTAINING_BOX_STYLE],
118 localContent,
119 'Absolute',
120 ),
121 });
122 GLOBAL_STATE.componentRefs!.onAfterRender = releaseLayout;
123
124 const prepared = nativeLayout ? claimPreparedLayoutPlan(GLOBAL_STATE.componentRefs!.element, localContent) : undefined;
125 const children = prepared?.children ?? ordinaryChildren ?? prepareLayoutChildren(props.children, 'Absolute');
126 const placements = prepared?.placements ?? (nativeLayout ? withAllocationCheckpoint(mountedAllocationCheckpointOwner(), { children, content: localContent, settings: style, onHit: recordWasmAllocationCacheHit, calculate: () => prepareAbsolutePlacements(children, localContent) }) : undefined);
127 let placementIndex = 0;
128 let occurrence = 0;
129 return placeDirectChildren(
130 children,
131 localContent,
132 (child, childOccurrence) => {
133 const placement = placements ? placements[placementIndex++] : resolveAbsoluteChildPlacement(localContent, child, getChildPrimitiveReceiverToken(
134 GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, occurrence++,
135 ));
136 if (nativeLayout && !prepared) preparePlacedKnownLayout(placement.element, childOccurrence);
137 return placement;
138 },
139 style.overflow,
140 );
141 }
142
143 /**
144 * Describes absolute layout for JSX or createElement authoring.
145 *
146 * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
147 * props and style types.
148 * @throws When called directly; Pibbl mounts this component through JSX or createElement.
149 *
150 * @see {@link AbsoluteProps}
151 * @see {@link AbsoluteStyle}
152 */
153 export const Absolute = definePrimitive<
154 AbsoluteProps,
155 AbsoluteStyle,
156 AbsoluteStyle,
157 ResolvedAbsoluteStyle
158 >(renderAbsolute, {
159 childInput: 'structural',
160 resolveStyle: (style, context) => {
161 if (nativeLayout && hasPercentageBoxPadding(style)) {
162 style = resolveAllocatedInsets(style, { width: context.percentageBasis.width,
163 context: { ...context, component: 'Absolute', algorithm: 'absolute' } });
164 }
165 return {
166 box: resolveContainerBox(style, context, 'Absolute', 'absolute'),
167 [ABSOLUTE_CONTAINING_BOX_STYLE]: style,
168 overflow: style.overflow ?? 'visible',
169 };
170 },
171 measureIntrinsic: (input) => measureUnionIntrinsic(input, 'Absolute'),
172 });
173
174 /** Pure paired intrinsic contributions for stacking known layout owners. */
175 export function measureUnionIntrinsic<S extends SystemStyle>(
176 input: IntrinsicMeasureInput<{ readonly children: PibblNodeInput }, S>,
177 receiver: LayoutReceiver,
178 ): IntrinsicSizesResult {
179 const owner = {
180 x: 0,
181 y: 0,
182 width: intrinsicMaximum(input.constraints.width),
183 height: intrinsicMaximum(input.constraints.height),
184 };
185 const children = materializeLayoutChildren(input.props.children, receiver);
186 let minWidth = 0, minHeight = 0, maxWidth = 0, maxHeight = 0;
187 for (let index = 0; index < children.length; index++) {
188 const child = children[index]!;
189 const receiverToken = getChildPrimitiveReceiverToken(
190 GLOBAL_STATE.renderTransaction,
191 GLOBAL_STATE.primitiveReceiverToken,
192 index,
193 );
194 const prepared = prepareDirectChildStyle(child, receiverToken, owner);
195 let style = preparedStyleValue(prepared) as Readonly<BoxStyle & LayoutItemStyle>;
196 if (hasIntrinsicUnionPercentage(style)) {
197 return { status: 'unsupported', reason: `${receiver} intrinsic percentage child sizes require a definite owner allocation` };
198 }
199 if (style.boxSizing !== undefined) {
200 style = contentBoxStyle(style, {
201 width: owner.width,
202 height: owner.height,
203 context: { component: child.type.name || 'Anonymous', algorithm: `${receiver} intrinsic measurement`, constraints: {
204 minWidth: 0, maxWidth: owner.width, minHeight: 0, maxHeight: owner.height,
205 } },
206 });
207 }
208 assertSupportedChildPosition(receiver, child, style, false, false);
209 const insets = normalizeBoxInsets(style, {
210 component: child.type.name || 'Anonymous', algorithm: `${receiver} intrinsic measurement`,
211 constraints: { minWidth: 0, maxWidth: owner.width, minHeight: 0, maxHeight: owner.height },
212 });
213 let measured: IntrinsicSizesResult;
214 if (typeof style.width === 'number' && typeof style.height === 'number') {
215 measured = {
216 status: 'measured',
217 minContent: { width: style.width, height: style.height },
218 maxContent: { width: style.width, height: style.height },
219 };
220 } else {
221 const measuredChild = clonePibblElement(child);
222 setPreNormalizedStyle(measuredChild, style, child, receiverToken, preparedStyleQuery(prepared));
223 measured = measureIntrinsicElement(measuredChild, {
224 minWidth: 0, maxWidth: owner.width, minHeight: 0, maxHeight: owner.height,
225 }, input.service);
226 if (measured.status !== 'measured') return measured;
227 }
228 const minimumWidth = (typeof style.width === 'number' ? style.width : measured.minContent.width) + insets.left + insets.right;
229 const maximumWidth = (typeof style.width === 'number' ? style.width : measured.maxContent.width) + insets.left + insets.right;
230 const minimumHeight = (typeof style.height === 'number' ? style.height : measured.minContent.height) + insets.top + insets.bottom;
231 const maximumHeight = (typeof style.height === 'number' ? style.height : measured.maxContent.height) + insets.top + insets.bottom;
232 const left = intrinsicOffset(receiver === 'Absolute' ? style.left : undefined, 'left', receiver);
233 const top = intrinsicOffset(receiver === 'Absolute' ? style.top : undefined, 'top', receiver);
234 if (left.status === 'unsupported') return { status: 'unsupported', reason: left.reason };
235 if (top.status === 'unsupported') return { status: 'unsupported', reason: top.reason };
236 minWidth = Math.max(minWidth, left.value + minimumWidth);
237 minHeight = Math.max(minHeight, top.value + minimumHeight);
238 maxWidth = Math.max(maxWidth, left.value + maximumWidth);
239 maxHeight = Math.max(maxHeight, top.value + maximumHeight);
240 }
241 return { status: 'measured', minContent: { width: minWidth, height: minHeight }, maxContent: { width: maxWidth, height: maxHeight } };
242 }
243
244 function intrinsicMaximum(constraint: IntrinsicMeasureInput<{ readonly children: PibblNodeInput }>['constraints']['width']): number {
245 return constraint.kind === 'bounded' ? constraint.max : Number.MAX_SAFE_INTEGER;
246 }
247
248 function hasIntrinsicUnionPercentage(style: Readonly<BoxStyle & LayoutItemStyle>): boolean {
249 return hasPercentageBoxPadding(style) || intrinsicPercentage(style.width) || intrinsicPercentage(style.height) ||
250 intrinsicPercentage(style.minWidth) || intrinsicPercentage(style.maxWidth) ||
251 intrinsicPercentage(style.minHeight) || intrinsicPercentage(style.maxHeight) ||
252 intrinsicPercentage(style.left) || intrinsicPercentage(style.top);
253 }
254
255 function intrinsicPercentage(value: unknown): boolean {
256 return typeof value === 'string' && value.endsWith('%');
257 }
258
259 function intrinsicOffset(
260 value: LayoutItemStyle['left'] | undefined,
261 property: 'left' | 'top',
262 receiver: LayoutReceiver,
263 ): Readonly<{ status: 'measured'; value: number }> | Readonly<{ status: 'unsupported'; reason: string }> {
264 if (value === undefined) return { status: 'measured', value: 0 };
265 if (typeof value !== 'number' || !Number.isFinite(value)) {
266 return { status: 'unsupported', reason: `${receiver} intrinsic ${property} offset must be finite and numeric` };
267 }
268 return { status: 'measured', value: Math.max(0, value) };
269 }
270
271 function prepareAbsolutePlacements(children: readonly PibblElement<any>[], content: Readonly<LayoutBox>): { box: LayoutBox; element: PibblElement<any> }[] {
272 recordWasmAllocationPass();
273 const placements: { box: LayoutBox; element: PibblElement<any> }[] = [];
274 for (let index = 0; index < children.length; index++) {
275 recordWasmAllocationItem();
276 placements.push(resolveAbsoluteChildPlacement(content, children[index], getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, index)));
277 }
278 return placements;
279 }
280
281 if (nativeLayout) registerKnownLayoutPreflight(Absolute, (element, style, content, receiver, slot) => {
282 const previous = GLOBAL_STATE.primitiveReceiverToken;
283 GLOBAL_STATE.primitiveReceiverToken = receiver;
284 const releaseLayout = pushLayoutBox(content, {
285 containingBlock: resolvePositionedContainingBox(
286 style as Readonly<AbsoluteStyle>,
287 content,
288 'Absolute',
289 ),
290 });
291 try {
292 const children = prepareLayoutChildren(element.props.children, 'Absolute');
293 const placements = withAllocationCheckpoint(slot, { children, content, settings: style, onHit: recordWasmAllocationCacheHit, calculate: () => prepareAbsolutePlacements(children, content) });
294 const plan: PreparedLayoutPlan = { content, children, placements };
295 prepareKnownLayoutDescendants(plan, slot);
296 stagePreparedLayoutPlan(slot, plan);
297 } finally {
298 releaseLayout();
299 GLOBAL_STATE.primitiveReceiverToken = previous;
300 }
301 });
302
303 /** @internal Resolves a layout container without inspecting its children. */
304 export function resolveContainerBox(
305 style: Readonly<BoxStyle>,
306 context: Readonly<StyleResolutionContext>,
307 component: string,
308 algorithm: string,
309 ): ResolvedBoxStyle {
310 return resolveLayoutBox(style, context, component, algorithm, false);
311 }
312
313 export function placeAbsoluteChild(
314 container: Readonly<LayoutBox>,
315 child: PibblElement<any>,
316 ): LayoutBox {
317 return resolveAbsoluteChildPlacement(container, child).box;
318 }
319
320 function resolveAbsoluteChildPlacement(
321 container: Readonly<LayoutBox>,
322 child: PibblElement<any>,
323 receiverToken?: object,
324 ): { box: LayoutBox; element: PibblElement<any> } {
325 const prepared = prepareDirectChildStyle(child, receiverToken, container);
326 let style = preparedStyleValue(prepared) as Readonly<
327 BoxStyle & LayoutItemStyle
328 >;
329 if (nativeLayout && GLOBAL_STATE.currentPibblInstance && getStyleMeasurementMode() === undefined && hasPercentageBoxPadding(style)) {
330 style = resolveAllocatedInsets(style, { width: container.width, context: childDiagnosticContext(child, container, 'absolute') });
331 }
332 // Absolute retains legacy left/top placement but never accepts Flex's explicit mode.
333 assertSupportedChildPosition('Absolute', child, style, false, false);
334 const resolved = resolveDirectChildBox(container, child, 'absolute', style, undefined, receiverToken);
335 const context = childDiagnosticContext(child, container, 'absolute');
336 const left = resolveScalarSizingLength(style.left ?? 0, container.width, 'left', context)!;
337 const top = resolveScalarSizingLength(style.top ?? 0, container.height, 'top', context)!;
338 const box = {
339 x: finitePlacement(container.x + left, 'left', left, context),
340 y: finitePlacement(container.y + top, 'top', top, context),
341 width: resolved.borderBox.width,
342 height: resolved.borderBox.height,
343 };
344 const element = childWithUsedSize(
345 child,
346 style,
347 resolved.contentBox.width,
348 resolved.contentBox.height,
349 receiverToken,
350 preparedStyleQuery(prepared),
351 );
352 return { box, element };
353 }
354
355 /** @internal Carries normalized finite content size into the eventual render. */
356 export function childWithUsedSize(
357 child: PibblElement<any>,
358 style: Readonly<SystemStyle>,
359 width: number,
360 height: number,
361 receiverToken?: object,
362 query?: PreparedQuery,
363 ): PibblElement<any> {
364 const renderedChild = clonePibblElement(child);
365 setPlacementConsumed(renderedChild);
366 setPreNormalizedStyle(renderedChild, Object.freeze(allocatedContentBoxStyle(style, width, height)), child, receiverToken, query);
367 return renderedChild;
368 }
369
370 /** Rebinds current raw inputs while carrying only a settled content allocation. */
371 export function childWithCachedUsedSize(child: PibblElement<any>, width: number, height: number): PibblElement<any> {
372 const renderedChild = clonePibblElement(child);
373 setPlacementConsumed(renderedChild);
374 setAllocatedContentSize(renderedChild, width, height);
375 return renderedChild;
376 }
377
378 /** @internal Shared by the initial direct-child layout algorithms. */
379 export function resolveDirectChildBox(
380 container: Readonly<LayoutBox>,
381 child: PibblElement<any>,
382 algorithm: string,
383 style: Readonly<SystemStyle> = normalizeDirectChildStyle(child, undefined, container),
384 service?: CanvasMeasurementService,
385 receiverToken?: object,
386 ): ResolvedBoxStyle {
387 const boxStyle = style as Readonly<BoxStyle>;
388 if (hasIntrinsicDirectLength(boxStyle)) return resolveIntrinsicDirectChildBox(container, child, algorithm, boxStyle, service, receiverToken);
389 return resolveLayoutBox(
390 boxStyle,
391 {
392 allocation: container,
393 percentageBasis: container,
394 constraints: {
395 minWidth: 0,
396 maxWidth: container.width,
397 minHeight: 0,
398 maxHeight: container.height,
399 },
400 component: child.type.name || 'Anonymous',
401 algorithm: 'render-dispatch',
402 },
403 child.type.name || 'Anonymous',
404 algorithm,
405 true,
406 );
407 }
408
409 function hasIntrinsicDirectLength(style: Readonly<BoxStyle>): boolean {
410 return isIntrinsicSizingValue(style.width) || isIntrinsicSizingValue(style.height) ||
411 isIntrinsicSizingValue(style.minWidth) || isIntrinsicSizingValue(style.maxWidth) ||
412 isIntrinsicSizingValue(style.minHeight) || isIntrinsicSizingValue(style.maxHeight);
413 }
414
415 function resolveIntrinsicDirectChildBox(container: Readonly<LayoutBox>, child: PibblElement<any>, algorithm: string, style: Readonly<BoxStyle>, service?: CanvasMeasurementService, receiverToken?: object): ResolvedBoxStyle {
416 const context = childDiagnosticContext(child, container, algorithm);
417 const measurement = service ?? (GLOBAL_STATE.renderContext ? canvasMeasurementService(GLOBAL_STATE.renderContext) : undefined);
418 if (!measurement) throw layoutDiagnostic({ ...context, property: 'width', value: style.width, reason: 'intrinsic sizing requires a Canvas measurement service' });
419 const pairedChild = clonePibblElement(child);
420 setPreNormalizedStyle(pairedChild, style, child, receiverToken);
421 const paired = measureIntrinsicElement(pairedChild, { minWidth: 0, maxWidth: container.width, minHeight: 0, maxHeight: container.height }, measurement);
422 if (paired.status !== 'measured') throw layoutDiagnostic({ ...context, property: 'width', value: style.width, reason: `intrinsic measurement is required but unsupported: ${paired.reason}` });
423 let width = intrinsicDirectLength(style.width, paired.minContent.width, paired.maxContent.width, container.width, 'width', context);
424 const minWidth = intrinsicDirectLength(style.minWidth, paired.minContent.width, paired.maxContent.width, container.width, 'minWidth', context);
425 const maxWidth = intrinsicDirectLength(style.maxWidth, paired.minContent.width, paired.maxContent.width, container.width, 'maxWidth', context);
426 let height = intrinsicDirectLength(style.height, paired.minContent.height, paired.maxContent.height, container.height, 'height', context);
427 const minHeight = intrinsicDirectLength(style.minHeight, paired.minContent.height, paired.maxContent.height, container.height, 'minHeight', context);
428 const maxHeight = intrinsicDirectLength(style.maxHeight, paired.minContent.height, paired.maxContent.height, container.height, 'maxHeight', context);
429 if (width !== undefined) {
430 const minimum = minWidth ?? scalarDirectBound(style.minWidth, container.width, 'minWidth', context) ?? 0;
431 const maximum = maxWidth ?? scalarDirectBound(style.maxWidth, container.width, 'maxWidth', context) ?? Number.POSITIVE_INFINITY;
432 width = Math.min(maximum, Math.max(minimum, width));
433 }
434 if (height === undefined && width !== undefined) {
435 const measuredChild = clonePibblElement(child);
436 setPreNormalizedStyle(measuredChild, { ...style, boxSizing: 'content-box', width, minWidth: undefined, maxWidth: undefined } as Readonly<BoxStyle>, child, receiverToken);
437 const measured = measureElement(measuredChild, { minWidth: width, maxWidth: width, minHeight: 0, maxHeight: container.height }, measurement);
438 if (measured.status !== 'measured') throw layoutDiagnostic({ ...context, property: 'height', value: style.height ?? 'auto', reason: `constrained measurement is required but unsupported: ${measured.reason}` });
439 height = measured.size.height;
440 }
441 const insets = normalizeBoxInsets(style, context);
442 const horizontal = style.boxSizing === 'border-box' ? insets.left + insets.right : 0;
443 const vertical = style.boxSizing === 'border-box' ? insets.top + insets.bottom : 0;
444 return resolveLayoutBox({ ...style,
445 width: width === undefined ? style.width : width + horizontal,
446 height: height === undefined ? style.height : height + vertical,
447 minWidth: minWidth === undefined ? style.minWidth : minWidth + horizontal,
448 maxWidth: maxWidth === undefined ? style.maxWidth : maxWidth + horizontal,
449 minHeight: minHeight === undefined ? style.minHeight : minHeight + vertical,
450 maxHeight: maxHeight === undefined ? style.maxHeight : maxHeight + vertical,
451 }, { allocation: container, percentageBasis: container, constraints: { minWidth: 0, maxWidth: container.width, minHeight: 0, maxHeight: container.height }, component: child.type.name || 'Anonymous', algorithm: 'render-dispatch' }, child.type.name || 'Anonymous', algorithm, true);
452 }
453
454 function intrinsicDirectLength(value: BoxStyle['width'], minimum: number, maximum: number, reference: number, property: string, context: Parameters<typeof resolveScalarSizingLength>[3]): number | undefined {
455 if (value === 'min-content') return minimum;
456 if (value === 'max-content') return maximum;
457 if (isFitContent(value)) {
458 const limit = resolveScalarSizingLength(value.limit, reference, property, context)!;
459 return Math.min(maximum, Math.max(minimum, limit));
460 }
461 return undefined;
462 }
463
464 function scalarDirectBound(value: BoxStyle['width'] | undefined, reference: number, property: string, context: Parameters<typeof resolveScalarSizingLength>[3]): number | undefined {
465 return value === undefined || isIntrinsicSizingValue(value) ? undefined : resolveScalarSizingLength(value, reference, property, context);
466 }
467
468 /** @internal Normalizes a descriptor without resolving or invoking its callback. */
469 export function normalizeDirectChildStyle(
470 child: PibblElement<any>,
471 receiverToken?: object,
472 queryBasis?: Readonly<LayoutBox>,
473 ): Readonly<SystemStyle> {
474 return preparedStyleValue(prepareDirectChildStyle(child, receiverToken, queryBasis));
475 }
476
477 /** Carries responsive eligibility with this normalization, never with a token. */
478 export function prepareDirectChildStyle(
479 child: PibblElement<any>,
480 receiverToken?: object,
481 queryBasis?: Readonly<LayoutBox>,
482 flexMargins = false,
483 ): Readonly<SystemStyle> | ResponsiveStylePreparation<Readonly<SystemStyle>> {
484 configureAllocationCheckpointAdapter(prepareDirectChildStyle, childWithUsedSize, takePreparedChildStyle, stagePreparedChildStyle, isLayoutComponent, isKnownLayoutType, prepareLayoutComponent);
485 const staged = takePreparedChildStyle(child, receiverToken, queryBasis);
486 if (staged) { recordAllocationStyle(receiverToken, staged); return staged; }
487 let source = child;
488 const captured = captureReceiverInputProvision(
489 GLOBAL_STATE.renderTransaction,
490 receiverToken,
491 () => {
492 if (isLayoutComponent(child.type)) source = prepareLayoutComponent(child, { receiverToken });
493 return resolvePrimitiveStyleInput(
494 (source.props as { readonly style?: unknown }).style,
495 source, queryBasis,
496 ) ?? EMPTY_STYLE;
497 },
498 );
499 const prepared = captured.value;
500 const definition = getPrimitiveDefinition(source.type);
501 const style = preparedStyleValue(prepared);
502 if (!flexMargins) {
503 const values = style as Readonly<Record<string, unknown>>;
504 const property = values.margin !== undefined ? 'margin' : values.marginTop !== undefined ? 'marginTop' :
505 values.marginRight !== undefined ? 'marginRight' : values.marginBottom !== undefined ? 'marginBottom' :
506 values.marginLeft !== undefined ? 'marginLeft' : values.marginStart !== undefined ? 'marginStart' :
507 values.marginEnd !== undefined ? 'marginEnd' : undefined;
508 if (property) throw layoutDiagnostic({ component: child.type.name, algorithm: 'layout', property,
509 value: values[property], reason: 'margins currently require experimental Flex' });
510 }
511 const filter = extractSystemFilter(style);
512 const normalized = definition?.normalizeStyle ?
513 definition.normalizeStyle(withoutSystemFilter(style)) :
514 withoutSystemFilter(style);
515 const final = { ...normalized, ...(filter === undefined ? {} : { filter }), ...(style.transition === undefined ? {} : { transition: (style as Readonly<SystemStyle>).transition }) };
516 if (prepared instanceof ResponsiveStylePreparation) {
517 prepared.style = final;
518 recordAllocationStyle(receiverToken, prepared, captured.receipt);
519 return prepared;
520 }
521 recordAllocationStyle(receiverToken, final, captured.receipt);
522 return final;
523 }
524
525 /** @internal Converts source-order descriptors to stable placed children. */
526 export function placeDirectChildren(
527 children: readonly PibblElement<any>[],
528 contentBox: Readonly<LayoutBox>,
529 place: (child: PibblElement<any>, occurrence: number) => LayoutBox | {
530 box: LayoutBox;
531 element: PibblElement<any>;
532 },
533 overflow: 'visible' | 'clip',
534 ): PibblElement<any>[] {
535 const participation = layoutParticipationPlan(children);
536 if (participation) {
537 const renderSequence = (sequence: readonly LayoutParticipationSource[], insideContents: boolean): PibblElement<any>[] => {
538 const occurrences = new Map<Function, number>();
539 const result: PibblElement<any>[] = [];
540 for (const node of sequence) {
541 const child = node.element;
542 const occurrence = child.key === undefined ? occurrences.get(child.type) ?? 0 : 0;
543 if (child.key === undefined) occurrences.set(child.type, occurrence + 1);
544 let element: PibblElement<any>, box: LayoutBox;
545 if (node.children) {
546 element = clonePibblElement(child);
547 setElementMetadata(element, { ...getElementMetadata(element), layoutContentsChildren: renderSequence(node.children, true) });
548 box = { x: 0, y: 0, width: contentBox.width, height: contentBox.height };
549 } else if (node.hidden) {
550 element = child;
551 box = { x: 0, y: 0, width: 0, height: 0 };
552 } else {
553 const placement = place(child, occurrence);
554 box = 'box' in placement ? placement.box : placement;
555 element = 'box' in placement ? placement.element : child;
556 }
557 result.push(placeChild({ element, box,
558 clipInChildSpace: overflow === 'clip' && !insideContents ? {
559 x: contentBox.x - box.x, y: contentBox.y - box.y,
560 width: contentBox.width, height: contentBox.height,
561 } : undefined,
562 identityHint: createPlacementIdentityHint(child, occurrence),
563 }));
564 }
565 return result;
566 };
567 return renderSequence(participation, false);
568 }
569 const occurrences = new Map<Function, number>();
570 const placed: PibblElement<any>[] = [];
571 for (const child of children) {
572 const occurrence = child.key === undefined ? occurrences.get(child.type) ?? 0 : 0;
573 if (child.key === undefined) occurrences.set(child.type, occurrence + 1);
574 const placement = place(child, occurrence);
575 const box = 'box' in placement ? placement.box : placement;
576 const element = 'box' in placement ? placement.element : child;
577 placed.push(placeChild({ element, box,
578 clipInChildSpace: overflow === 'clip' ? {
579 x: contentBox.x - box.x, y: contentBox.y - box.y,
580 width: contentBox.width, height: contentBox.height,
581 } : undefined,
582 identityHint: createPlacementIdentityHint(child, occurrence),
583 }));
584 }
585 return placed;
586 }
587
588 /** @internal Prepares one finite direct-child sequence for a layout boundary. */
589 export function materializeLayoutChildren(
590 children: PibblNodeInput,
591 receiver: LayoutReceiver,
592 ): readonly PibblElement<any>[] {
593 // Placement identity owns layout sibling keys. Deferring its check preserves
594 // fail-closed teardown when a later duplicate follows an acquired child.
595 return participatingLayoutChildren(materializeContainerChildren(children, receiver, {
596 validateKeys: false,
597 }));
598 }
599
600 /** @internal Shares one direct sequence between an occurrence's measurement and paint. */
601 export function prepareLayoutChildren(
602 children: PibblNodeInput,
603 receiver: LayoutReceiver,
604 ): readonly PibblElement<any>[] {
605 const transaction = GLOBAL_STATE.renderTransaction;
606 const receiverToken = GLOBAL_STATE.primitiveReceiverToken;
607 if (!transaction || !receiverToken) {
608 return materializeLayoutChildren(children, receiver);
609 }
610
611 let receivers = preparedLayoutTransactions.get(transaction);
612 if (!receivers) {
613 receivers = new WeakMap();
614 preparedLayoutTransactions.set(transaction, receivers);
615 }
616 const prepared = receivers.get(receiverToken);
617 if (prepared) return prepared;
618 const materialized = withReceiverInputProvision(
619 transaction,
620 receiverToken,
621 () => materializeLayoutChildren(children, receiver),
622 );
623 receivers.set(receiverToken, materialized);
624 return materialized;
625 }
626
627 function resolveLayoutBox(
628 style: Readonly<BoxStyle>,
629 context: Readonly<StyleResolutionContext>,
630 component: string,
631 algorithm: string,
632 requireDefinite: boolean,
633 ): ResolvedBoxStyle {
634 if (requireDefinite && (style.width === undefined || style.width === 'auto')) {
635 throw requiredDimension(component, 'width', style.width, context, algorithm);
636 }
637 if (requireDefinite && (style.height === undefined || style.height === 'auto')) {
638 throw requiredDimension(component, 'height', style.height, context, algorithm);
639 }
640
641 const diagnosticContext = {
642 component,
643 algorithm,
644 constraints: context.constraints,
645 };
646 const width = resolveOptionalAllocationLength(
647 style.width,
648 context.percentageBasis.width,
649 'width',
650 diagnosticContext,
651 );
652 const height = resolveOptionalAllocationLength(
653 style.height,
654 context.percentageBasis.height,
655 'height',
656 diagnosticContext,
657 );
658 const minWidth = resolveOptionalAllocationLength(
659 style.minWidth,
660 context.percentageBasis.width,
661 'minWidth',
662 diagnosticContext,
663 );
664 const maxWidth = resolveOptionalAllocationLength(
665 style.maxWidth,
666 context.percentageBasis.width,
667 'maxWidth',
668 diagnosticContext,
669 );
670 const minHeight = resolveOptionalAllocationLength(
671 style.minHeight,
672 context.percentageBasis.height,
673 'minHeight',
674 diagnosticContext,
675 );
676 const maxHeight = resolveOptionalAllocationLength(
677 style.maxHeight,
678 context.percentageBasis.height,
679 'maxHeight',
680 diagnosticContext,
681 );
682 const padding = normalizeBoxInsets(style, diagnosticContext);
683 const allowOverflow = requireDefinite;
684 const maxConstraintWidth = allowOverflow ? allocationCeiling(
685 context.allocation.width,
686 [width, minWidth, maxWidth],
687 padding.left + padding.right,
688 'width',
689 diagnosticContext,
690 ) : context.allocation.width;
691 const maxConstraintHeight = allowOverflow ? allocationCeiling(
692 context.allocation.height,
693 [height, minHeight, maxHeight],
694 padding.top + padding.bottom,
695 'height',
696 diagnosticContext,
697 ) : context.allocation.height;
698
699 return resolveBox({
700 ...style,
701 width,
702 height,
703 minWidth,
704 maxWidth,
705 minHeight,
706 maxHeight,
707 }, {
708 minWidth: 0,
709 maxWidth: maxConstraintWidth,
710 minHeight: 0,
711 maxHeight: maxConstraintHeight,
712 }, diagnosticContext);
713 }
714
715 function resolveOptionalAllocationLength(
716 value: BoxStyle['width'],
717 reference: number,
718 property: string,
719 context: Parameters<typeof resolveScalarSizingLength>[3],
720 ): number | undefined {
721 if (value === undefined) return undefined;
722 return resolveScalarSizingLength(value, reference, property, context);
723 }
724
725 function allocationCeiling(
726 allocation: number,
727 values: readonly (number | undefined)[],
728 padding: number,
729 property: string,
730 context: Parameters<typeof resolveScalarSizingLength>[3],
731 ): number {
732 const ceiling = Math.max(allocation, ...values.filter(
733 (value): value is number => value !== undefined,
734 )) + padding;
735 if (!Number.isFinite(ceiling)) {
736 throw layoutDiagnostic({
737 ...context,
738 property,
739 value: ceiling,
740 reason: 'resolved allocation arithmetic must remain finite',
741 });
742 }
743 return ceiling;
744 }
745
746 function requiredDimension(
747 component: string,
748 property: 'width' | 'height',
749 value: unknown,
750 context: Readonly<StyleResolutionContext>,
751 algorithm: string,
752 ) {
753 return layoutDiagnostic({
754 component,
755 property,
756 value: value ?? 'auto',
757 algorithm,
758 constraints: context.constraints,
759 reason: 'requires a definite dimension until measurement is available',
760 });
761 }
762
763 function childDiagnosticContext(
764 child: PibblElement<any>,
765 container: Readonly<LayoutBox>,
766 algorithm: string,
767 ) {
768 return {
769 component: child.type.name || 'Anonymous',
770 algorithm,
771 constraints: {
772 minWidth: 0,
773 maxWidth: container.width,
774 minHeight: 0,
775 maxHeight: container.height,
776 },
777 };
778 }
779
780 function finitePlacement(
781 resolved: number,
782 property: string,
783 value: unknown,
784 context: ReturnType<typeof childDiagnosticContext>,
785 ): number {
786 if (!Number.isFinite(resolved)) {
787 throw layoutDiagnostic({
788 ...context,
789 property,
790 value,
791 reason: 'resolved placement arithmetic must remain finite',
792 });
793 }
794 return resolved;
795 }
796
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.