Skip to content

packages/core/src/lib/layout/overlay.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, mountedAllocationCheckpointOwner } from './allocation-checkpoint.js';
2 import { hasPercentageBoxPadding, resolveAllocatedInsets } from './box-insets.js';
3 import { recordWasmAllocationPass, recordWasmAllocationItem, recordWasmAllocationCacheHit, nativeLayout } from './wasm/region.js';
4 import { registerKnownLayoutPreflight, claimPreparedLayoutPlan, stagePreparedLayoutPlan, prepareKnownLayoutDescendants, preparePlacedKnownLayout, type PreparedLayoutPlan } from './prepared-root.js';
5 import { getStyleMeasurementMode, preparedStyleValue, preparedStyleQuery } from '../style/responsive.js';
6 import { definePrimitive } from '../define-primitive.js';
7 import { GLOBAL_STATE } from '../global-state.js';
8 import { layoutDiagnostic } from '../style/diagnostics.js';
9 import {
10   type PibblStructuralEventProps,
11   wireStructuralEvents,
12 } from '../components/structural-events.js';
13 import type { BoxStyle, LayoutItemStyle, ResolvedBoxStyle } from '../style/types.js';
14 import type {
15   PibblNodeInput,
16   RenderingContext2D,
17   SystemStyle,
18 } from '../types.js';
19 import type { PibblElement } from '../element/types.js';
20 import { getChildPrimitiveReceiverToken } from '../element/metadata.js';
21 import {
22   childWithUsedSize,
23   prepareLayoutChildren,
24   prepareDirectChildStyle,
25   placeDirectChildren,
26   resolveContainerBox,
27   resolveDirectChildBox,
28   measureUnionIntrinsic,
29 } from './absolute.js';
30 import { pushLayoutBox, resolvePositionedContainingBox } from './context.js';
31 import { recordLayoutEvaluation } from './diagnostics.js';
32 import { assertSupportedChildPosition } from './positioning-diagnostics.js';
33 import type { LayoutBox } from './types.js';
34 
35 type OverlayAlignment = 'start' | 'center' | 'end' | 'stretch';
36 
37 /**
38  * Supported geometry and presentation properties for Overlay.
39  *
40  * @see {@link BoxStyle}
41  * @see {@link LayoutItemStyle}
42  * @see {@link Overlay}
43  */
44 export interface OverlayStyle extends BoxStyle, LayoutItemStyle {
45   /** Default alignment of children on the cross or block axis. See {@link OverlayAlignment}. */
46   alignItems?: OverlayAlignment;
47   /** Default inline-axis alignment of grid or overlay children. See {@link OverlayAlignment}. */
48   justifyItems?: OverlayAlignment;
49 }
50 
51 /**
52  * Authored inputs for Overlay, including the declared data and presentation options.
53  *
54  * @see {@link PibblNodeInput}
55  * @see {@link Overlay}
56  */
57 export interface OverlayProps extends PibblStructuralEventProps {
58   /** Descendant content or the callback that supplies it. See {@link PibblNodeInput}. */
59   children: PibblNodeInput;
60 }
61 
62 // Parent input is private metadata, not a recursively validated resolved value.
63 const OVERLAY_CONTAINING_BOX_STYLE = Symbol('pibbl.overlay-containing-box-style');
64 
65 interface ResolvedOverlayStyle extends SystemStyle {
66   box: ResolvedBoxStyle;
67   [OVERLAY_CONTAINING_BOX_STYLE]: Readonly<OverlayStyle>;
68   overflow: 'visible' | 'clip';
69   alignItems: OverlayAlignment;
70   justifyItems: OverlayAlignment;
71 }
72 
73 function renderOverlay(
74   props: OverlayProps,
75   style: Readonly<ResolvedOverlayStyle>,
76   ctx: RenderingContext2D,
77 ) {
78   wireStructuralEvents(props);
79   const ordinaryChildren = nativeLayout ? undefined : prepareLayoutChildren(props.children, 'Overlay');
80   recordLayoutEvaluation();
81   const content = style.box.contentBox;
82   ctx.translate(content.x, content.y);
83   const localContent = Object.freeze({
84     x: 0,
85     y: 0,
86     width: content.width,
87     height: content.height,
88   });
89   const releaseLayout = pushLayoutBox(localContent, {
90     logicalOffset: content,
91     containingBlock: resolvePositionedContainingBox(
92       style[OVERLAY_CONTAINING_BOX_STYLE],
93       localContent,
94       'Overlay',
95     ),
96   });
97   GLOBAL_STATE.componentRefs!.onAfterRender = releaseLayout;
98 
99   const prepared = nativeLayout ? claimPreparedLayoutPlan(GLOBAL_STATE.componentRefs!.element, localContent) : undefined;
100   const children = prepared?.children ?? ordinaryChildren ?? prepareLayoutChildren(props.children, 'Overlay');
101   const placements = prepared?.placements ?? (nativeLayout ? withAllocationCheckpoint(mountedAllocationCheckpointOwner(), { children, content: localContent, settings: style, onHit: recordWasmAllocationCacheHit, calculate: () => prepareOverlayPlacements(children, localContent, style) }) : undefined);
102   let placementIndex = 0;
103   let occurrence = 0;
104   return placeDirectChildren(
105     children,
106     localContent,
107     (child, childOccurrence) => {
108       const placement = placements ? placements[placementIndex++] : resolveOverlayChildPlacement(localContent, child, style, getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, occurrence++));
109       if (nativeLayout && !prepared) preparePlacedKnownLayout(placement.element, childOccurrence);
110       return placement;
111     },
112     style.overflow,
113   );
114 }
115 
116 /**
117  * Describes overlay layout for JSX or createElement authoring.
118  *
119  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
120  * props and style types.
121  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
122  *
123  * @see {@link OverlayProps}
124  * @see {@link OverlayStyle}
125  */
126 export const Overlay = definePrimitive<
127   OverlayProps,
128   OverlayStyle,
129   OverlayStyle,
130   ResolvedOverlayStyle
131 >(renderOverlay, {
132   childInput: 'structural',
133   resolveStyle: (style, context) => {
134     if (nativeLayout && hasPercentageBoxPadding(style)) {
135       style = resolveAllocatedInsets(style, { width: context.percentageBasis.width,
136         context: { ...context, component: 'Overlay', algorithm: 'overlay' } });
137     }
138     return {
139       box: resolveContainerBox(style, context, 'Overlay', 'overlay'),
140       [OVERLAY_CONTAINING_BOX_STYLE]: style,
141       overflow: style.overflow ?? 'visible',
142       alignItems: style.alignItems ?? 'stretch',
143       justifyItems: style.justifyItems ?? 'stretch',
144     };
145   },
146   measureIntrinsic: (input) => measureUnionIntrinsic(input, 'Overlay'),
147 });
148 
149 function prepareOverlayPlacements(children: readonly PibblElement<any>[], content: Readonly<LayoutBox>, alignment: Readonly<Pick<OverlayStyle, 'alignItems' | 'justifyItems'>>): { box: LayoutBox; element: PibblElement<any> }[] {
150   recordWasmAllocationPass();
151   const placements = new Array<{ box: LayoutBox; element: PibblElement<any> }>(children.length);
152   for (let index = 0; index < children.length; index++) {
153     recordWasmAllocationItem();
154     placements[index] = resolveOverlayChildPlacement(content, children[index], alignment, getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, GLOBAL_STATE.primitiveReceiverToken, index));
155   }
156   return placements;
157 }
158 if (nativeLayout) registerKnownLayoutPreflight(Overlay, (element, style, content, receiver, slot) => {
159   // The registry owns this structural slot; Overlay needs no numeric arena.
160   const previous = GLOBAL_STATE.primitiveReceiverToken;
161   GLOBAL_STATE.primitiveReceiverToken = receiver;
162   const releaseLayout = pushLayoutBox(content, {
163     containingBlock: resolvePositionedContainingBox(
164       style as Readonly<OverlayStyle>,
165       content,
166       'Overlay',
167     ),
168   });
169   try {
170     const children = prepareLayoutChildren(element.props.children, 'Overlay');
171     const plan: PreparedLayoutPlan = { content, children, placements: withAllocationCheckpoint(slot, { children, content, settings: style, onHit: recordWasmAllocationCacheHit, calculate: () => prepareOverlayPlacements(children, content, style as Readonly<OverlayStyle>) }) };
172     prepareKnownLayoutDescendants(plan, slot);
173     stagePreparedLayoutPlan(slot, plan);
174   } finally {
175     releaseLayout();
176     GLOBAL_STATE.primitiveReceiverToken = previous;
177   }
178 });
179 
180 export function placeOverlayChild(
181   container: Readonly<LayoutBox>,
182   child: PibblElement<any>,
183   alignment: Readonly<Pick<OverlayStyle, 'alignItems' | 'justifyItems'>> = {},
184 ): LayoutBox {
185   return resolveOverlayChildPlacement(container, child, alignment).box;
186 }
187 
188 function resolveOverlayChildPlacement(
189   container: Readonly<LayoutBox>,
190   child: PibblElement<any>,
191   alignment: Readonly<Pick<OverlayStyle, 'alignItems' | 'justifyItems'>> = {},
192   receiverToken?: object,
193 ): { box: LayoutBox; element: PibblElement<any> } {
194   const prepared = prepareDirectChildStyle(child, receiverToken, container);
195   let item = preparedStyleValue(prepared) as Readonly<
196     BoxStyle & LayoutItemStyle
197   >;
198   if (nativeLayout && GLOBAL_STATE.currentPibblInstance && getStyleMeasurementMode() === undefined && hasPercentageBoxPadding(item)) {
199     item = resolveAllocatedInsets(item, { width: container.width, context: { component: child.type.name || 'Anonymous', algorithm: 'overlay' } });
200   }
201   assertSupportedChildPosition('Overlay', child, item, false, false);
202   const resolved = resolveDirectChildBox(
203     container,
204     child,
205     'overlay',
206     item,
207     undefined,
208     receiverToken,
209   );
210   const declaredBox = resolved.borderBox;
211   const horizontal = resolveItemAlignment(
212     item.justifySelf,
213     alignment.justifyItems ?? 'stretch',
214     child,
215     container,
216     'justifySelf',
217   );
218   const vertical = resolveItemAlignment(
219     item.alignSelf,
220     alignment.alignItems ?? 'stretch',
221     child,
222     container,
223     'alignSelf',
224   );
225   const x = alignAxis(
226     container.x,
227     container.width,
228     declaredBox.width,
229     horizontal,
230   );
231   const y = alignAxis(
232     container.y,
233     container.height,
234     declaredBox.height,
235     vertical,
236   );
237   const box = {
238     x,
239     y,
240     width: horizontal === 'stretch' ?
241         Math.max(0, container.width) :
242         declaredBox.width,
243     height: vertical === 'stretch' ?
244         Math.max(0, container.height) :
245         declaredBox.height,
246   };
247   const horizontalPadding = declaredBox.width - resolved.contentBox.width;
248   const verticalPadding = declaredBox.height - resolved.contentBox.height;
249   return {
250     box,
251     element: childWithUsedSize(
252       child,
253       item,
254       Math.max(0, box.width - horizontalPadding),
255       Math.max(0, box.height - verticalPadding),
256       receiverToken,
257       preparedStyleQuery(prepared),
258     ),
259   };
260 }
261 
262 function resolveItemAlignment(
263   item: LayoutItemStyle['alignSelf'] | LayoutItemStyle['justifySelf'],
264   fallback: OverlayAlignment,
265   child: PibblElement<any>,
266   container: Readonly<LayoutBox>,
267   property: 'alignSelf' | 'justifySelf',
268 ): OverlayAlignment {
269   if (item === undefined || item === 'auto') return fallback;
270   if (item === 'start' || item === 'center' || item === 'end' || item === 'stretch') {
271     return item;
272   }
273   throw layoutDiagnostic({
274     component: child.type.name || 'Anonymous',
275     property,
276     value: item,
277     algorithm: 'overlay',
278     constraints: {
279       minWidth: 0,
280       maxWidth: container.width,
281       minHeight: 0,
282       maxHeight: container.height,
283     },
284     reason: 'uses an unsupported overlay alignment value',
285   });
286 }
287 
288 function alignAxis(
289   start: number,
290   available: number,
291   size: number,
292   alignment: OverlayAlignment,
293 ): number {
294   switch (alignment) {
295     case 'center': return start + (available - size) / 2;
296     case 'end': return start + available - size;
297     default: return start;
298   }
299 }
300 

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