Skip to content

packages/core/src/lib/components/layer.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 { getLayoutDirection, hasParentLayoutAllocation } from '../layout/context.js';
2 import { registerLayoutSuspensionResource, unregisterLayoutSuspensionResource } from '../layout/participation.js';
3 import { isLayoutComponent, prepareLayoutComponent } from '../layout/define-layout-component.js';
4 import { isKnownLayoutType, registerKnownLayoutPreflight, preflightKnownLayout, attachPreparedLayoutSlot, stagePreparedBoundaryChildren, takePreparedBoundaryChildren, preparedBoundaryNeedsAllocationParent, retainPreparedBoundarySubtree } from '../layout/prepared-root.js';
5 import { prepareLayoutChildren, prepareDirectChildStyle, resolveContainerBox } from '../layout/absolute.js';
6 import { setPreNormalizedStyle } from '../style/resolve-dispatch.js';
7 import { getChildPrimitiveReceiverToken } from '../element/metadata.js';
8 import { preparedStyleValue, preparedStyleQuery } from '../style/responsive.js';
9 import { nativeLayout } from '../layout/wasm/region.js';
10 import { definePrimitive } from '../define-primitive.js';
11 import { materializeContainerChildren } from '../element/children.js';
12 import { clonePibblElement, createElement } from '../element/create-element.js';
13 import { Fragment, type FragmentProps } from '../element/fragment.js';
14 import { executeRender } from '../execute-render.js';
15 import {
16   getPibblInstance,
17   getCurrentPibblInstance,
18   GLOBAL_STATE,
19 } from '../global-state.js';
20 import { mountPibbl } from '../mount-pibbl.js';
21 import {
22   PibblNodeInput,
23   PibblInteractionLayer,
24   RenderingContext2D,
25   SystemStyle,
26 } from '../types.js';
27 import { PibblPaintEntryKind } from '../events/paint-entry.js';
28 import {
29   resolveRequiredLength,
30   stripLayoutParticipation,
31 } from '../style/resolve-built-in.js';
32 import type {
33   BoxStyle,
34   LayoutItemStyle,
35   ResolvedDrawingStyle,
36 } from '../style/types.js';
37 import {
38   getSurfaceSnapshot,
39 } from '../surface/transform.js';
40 import { getCurrentWorldTransform } from '../render-target.js';
41 import { createLayerSurface } from '../surface/resolve-surface.js';
42 import {
43   completeInstanceRenderRevision,
44   hasPendingInstanceRender,
45   setInstanceAllocationParent,
46 } from '../scheduler/realm-scheduler.js';
47 import type { PibblElement } from '../element/types.js';
48 import {
49   haveSameLayerNodeTree,
50   snapshotLayerNodeTree,
51   type LayerNodeSnapshot,
52 } from './layer-node-equality.js';
53 import {
54   type PibblStructuralEventProps,
55   wireStructuralEvents,
56 } from './structural-events.js';
57 
58 /**
59  * Authored inputs for Layer, including the declared data and presentation options.
60  *
61  * @see {@link PibblNodeInput}
62  * @see {@link Layer}
63  */
64 export interface LayerProps extends PibblStructuralEventProps {
65   /** Descendant content or the callback that supplies it. See {@link PibblNodeInput}. */
66   children: PibblNodeInput;
67 }
68 
69 /**
70  * Supported geometry and presentation properties for Layer.
71  *
72  * @see {@link SystemStyle}
73  * @see {@link BoxStyle}
74  * @see {@link LayoutItemStyle}
75  * @see {@link Layer}
76  */
77 export interface LayerStyle extends SystemStyle, BoxStyle, LayoutItemStyle {}
78 
79 type ResolvedLayerStyle = ResolvedDrawingStyle<LayerStyle> & {
80   width: number;
81   height: number;
82 };
83 
84 interface LayerSlot {
85   canvas: OffscreenCanvas;
86   interactionLayer: PibblInteractionLayer;
87   logicalWidth: number;
88   logicalHeight: number;
89   /** Direction used for the currently retained child bitmap. */
90   layoutDirection: 'ltr' | 'rtl' | undefined;
91   focusRenderRevision: number | undefined;
92   retainedTree: LayerNodeSnapshot | undefined;
93 }
94 
95 function renderLayer(
96   props: LayerProps,
97   style: Readonly<ResolvedLayerStyle>,
98   ctx: RenderingContext2D,
99 ) {
100   wireStructuralEvents(props);
101   const canvas = GLOBAL_STATE.canvas!;
102   const { width = canvas.width, height = canvas.height } = style;
103   const componentRefs = GLOBAL_STATE.componentRefs!;
104   let preparedBoundary = componentRefs.element;
105   let preparedChildren = nativeLayout ? takePreparedBoundaryChildren(preparedBoundary) : undefined;
106   if (nativeLayout && !preparedChildren) {
107     const slot = preflightKnownLayout(preparedBoundary, style, { x: 0, y: 0, width, height }, GLOBAL_STATE.primitiveReceiverToken);
108     // Keep transaction metadata off the application-owned reusable descriptor.
109     preparedBoundary = clonePibblElement(preparedBoundary);
110     attachPreparedLayoutSlot(preparedBoundary, slot);
111     preparedChildren = takePreparedBoundaryChildren(preparedBoundary);
112   }
113   const materializedChildren = preparedChildren ?? materializeContainerChildren(props.children, 'Layer');
114   const needsPreparedAllocationParent = nativeLayout && preparedBoundaryNeedsAllocationParent(preparedBoundary);
115   const nextRoot = createPrivateLayerRoot(materializedChildren);
116   const parentInstance = getCurrentPibblInstance();
117   const parentSurface = getSurfaceSnapshot(parentInstance);
118   const layerSurface = createLayerSurface(
119     width,
120     height,
121     parentSurface.backingPixelsPerLogicalUnitX,
122     parentSurface.backingPixelsPerLogicalUnitY,
123   );
124   if (GLOBAL_STATE.componentIsMounting) {
125     const offscreenCanvas = new OffscreenCanvas(
126       layerSurface.backingWidth,
127       layerSurface.backingHeight,
128     );
129     const controller = mountPibbl(offscreenCanvas, nextRoot, {
130       parent: canvas,
131       surface: layerSurface,
132     });
133     const childInstance = getPibblInstance(offscreenCanvas);
134     childInstance.eventParent = componentRefs;
135     const interactionLayer: PibblInteractionLayer = {
136       paintKind: PibblPaintEntryKind.NestedInstance,
137       instance: childInstance,
138       transform: new DOMMatrix(),
139       clippingStack: [],
140       bounds: createBounds(width, height),
141       resolveLocal: undefined,
142     };
143     componentRefs.refs[0] = {
144       canvas: offscreenCanvas,
145       interactionLayer,
146       logicalWidth: width,
147       logicalHeight: height,
148       layoutDirection: undefined,
149       focusRenderRevision: undefined,
150       retainedTree: undefined,
151     } satisfies LayerSlot;
152     const suspensionResource = {
153       suspendLayout: () => parentInstance.paintEntries.delete(interactionLayer),
154     };
155     registerLayoutSuspensionResource(componentRefs, suspensionResource);
156     componentRefs.teardowns.add(() => {
157       unregisterLayoutSuspensionResource(componentRefs, suspensionResource);
158       setInstanceAllocationParent(childInstance);
159       childInstance.eventParent = undefined;
160       parentInstance.paintEntries.delete(interactionLayer);
161       controller.dispose();
162     });
163   }
164 
165   const slot = componentRefs.refs[0] as LayerSlot;
166   const offscreenCanvas = slot.canvas;
167   const layerPibbl = getPibblInstance(offscreenCanvas);
168   if (nativeLayout) setInstanceAllocationParent(layerPibbl,
169     hasParentLayoutAllocation() || needsPreparedAllocationParent ? parentInstance : undefined);
170   const layoutDirection = getLayoutDirection();
171   const directionChanged = slot.layoutDirection !== layoutDirection;
172   const dimensionsChanged = slot.logicalWidth !== width ||
173     slot.logicalHeight !== height;
174   const surfaceChanged =
175     offscreenCanvas.width !== layerSurface.backingWidth ||
176     offscreenCanvas.height !== layerSurface.backingHeight;
177 
178   const { interactionLayer } = slot;
179   parentInstance.paintEntries.delete(interactionLayer);
180   interactionLayer.transform = getCurrentWorldTransform();
181   interactionLayer.clippingStack = Array.from(GLOBAL_STATE.clippingStack);
182   if (dimensionsChanged) {
183     interactionLayer.bounds = createBounds(width, height);
184   }
185   // Install the current bridge before entering the child render. Focus bounds
186   // collected by the child must never see the previous frame's transform.
187   parentInstance.paintEntries.add(interactionLayer);
188 
189   const focusPolicy = parentInstance.eventRoot.focusPolicy;
190   const focusRenderRevision = focusPolicy?.layerFocusRenderRevision?.(layerPibbl);
191 
192   const shouldRender =
193     GLOBAL_STATE.componentIsMounting ||
194     dimensionsChanged ||
195     directionChanged ||
196     surfaceChanged ||
197     !haveSameLayerNodeTree(slot.retainedTree, nextRoot) ||
198     slot.focusRenderRevision !== focusRenderRevision ||
199     hasPendingInstanceRender(layerPibbl);
200   if (shouldRender) {
201     if (layerPibbl.surface.kind !== 'layer') {
202       throw new Error('Pibbl layer mounted without a derived surface.');
203     }
204     layerPibbl.surface.snapshot = layerSurface;
205     layerPibbl.surface.managed = true;
206     offscreenCanvas.width = layerSurface.backingWidth;
207     offscreenCanvas.height = layerSurface.backingHeight;
208     slot.logicalWidth = width;
209     slot.logicalHeight = height;
210 
211     const renderedRevision = layerPibbl.requestedRenderRevision;
212     const previousRootLayoutDirection = layerPibbl.rootLayoutDirection;
213     layerPibbl.rootLayoutDirection = layoutDirection;
214     try {
215       executeRender(
216         offscreenCanvas,
217         getCurrentPibblInstance().renderTimestamp,
218         nextRoot,
219         false,
220       );
221       completeInstanceRenderRevision(layerPibbl, renderedRevision);
222       slot.retainedTree = snapshotLayerNodeTree(nextRoot);
223       slot.layoutDirection = layoutDirection;
224     } catch (error) {
225       layerPibbl.rootLayoutDirection = previousRootLayoutDirection;
226       throw error;
227     }
228   } else {
229     if (nativeLayout) retainPreparedBoundarySubtree(preparedBoundary);
230     parentInstance.eventRoot.focusPolicy?.replayRetainedSubtree(layerPibbl);
231   }
232   const renderedFocusPolicy = parentInstance.eventRoot.focusPolicy;
233   slot.focusRenderRevision =
234     renderedFocusPolicy?.layerFocusRenderRevision?.(layerPibbl);
235 
236   parentInstance.eventRoot.html?.recordLayer(parentInstance, layerPibbl, interactionLayer, ctx.globalAlpha, ctx.globalCompositeOperation);
237 
238   ctx.drawImage(
239     offscreenCanvas,
240     0,
241     0,
242     offscreenCanvas.width,
243     offscreenCanvas.height,
244     0,
245     0,
246     width,
247     height,
248   );
249 
250 }
251 
252 /**
253  * Describes a retained offscreen composition layer.
254  *
255  * @param props - Authored component inputs, supplied through JSX or createElement. See the linked
256  * props and style types.
257  * @throws When called directly; Pibbl mounts this component through JSX or createElement.
258  *
259  * @see {@link LayerProps}
260  * @see {@link LayerStyle}
261  */
262 export const Layer = definePrimitive<
263   LayerProps,
264   LayerStyle,
265   LayerStyle,
266   ResolvedLayerStyle
267 >(renderLayer, {
268   childInput: 'structural',
269   resolveStyle: resolveLayerStyle,
270 });
271 
272 if (nativeLayout) registerKnownLayoutPreflight(Layer, (element, _style, content, receiver, slot) => {
273   const previous = GLOBAL_STATE.primitiveReceiverToken;
274   GLOBAL_STATE.primitiveReceiverToken = receiver;
275   try {
276     const children = prepareLayoutChildren(element.props.children, 'Layer');
277     const placed = children.slice();
278     let occurrences: Map<Function, number> | undefined;
279     for (let index = 0; index < children.length; index++) {
280       const child = children[index];
281       // Layer is a raster boundary, not a layout algorithm for arbitrary children.
282       if (!isKnownLayoutType(child.type) && !isLayoutComponent(child.type)) continue;
283       let occurrence = 0;
284       if (child.key === undefined) {
285         occurrences ??= new Map(); occurrence = occurrences.get(child.type) ?? 0;
286         occurrences.set(child.type, occurrence + 1);
287       }
288       const token = getChildPrimitiveReceiverToken(GLOBAL_STATE.renderTransaction, receiver, index);
289       const root = isLayoutComponent(child.type) ? prepareLayoutComponent(child, { receiverToken: token }) : child;
290       if (!isKnownLayoutType(root.type)) continue;
291       const component = root.type.name || 'Layout';
292       const prepared = prepareDirectChildStyle(child, token, content, true);
293       const style = preparedStyleValue(prepared);
294       const context = { component, algorithm: 'render-dispatch' as const, allocation: content, percentageBasis: content, constraints: { minWidth: 0, maxWidth: content.width, minHeight: 0, maxHeight: content.height } };
295       // A nested raster boundary uses Layer's actual dimensions, not box layout.
296       let width: number, height: number;
297       if (root.type === Layer) {
298         const layerStyle = resolveLayerStyle(style, context);
299         width = layerStyle.width!; height = layerStyle.height!;
300       } else {
301         const box = resolveContainerBox(style, context, component, 'render-dispatch');
302         width = box.contentBox.width; height = box.contentBox.height;
303       }
304       const nested = preflightKnownLayout(child, style, { x: 0, y: 0, width, height }, token, occurrence, slot);
305       const clone = clonePibblElement(child);
306       setPreNormalizedStyle(clone, style, child, token, preparedStyleQuery(prepared));
307       attachPreparedLayoutSlot(clone, nested); placed[index] = clone;
308     }
309     stagePreparedBoundaryChildren(slot, placed);
310   } finally { GLOBAL_STATE.primitiveReceiverToken = previous; }
311 });
312 
313 function resolveLayerStyle(
314   style: Readonly<LayerStyle>,
315   context: Parameters<NonNullable<
316     import('../types.js').PrimitiveCapabilities<
317       LayerProps,
318       LayerStyle,
319       LayerStyle,
320       ResolvedLayerStyle
321     >['resolveStyle']
322   >>[1],
323 ): ResolvedLayerStyle {
324   return {
325     ...stripLayoutParticipation(style),
326     width: resolveRequiredLength(
327       style.width ?? context.allocation.width,
328       context.percentageBasis.width,
329       'width',
330       context,
331     ),
332     height: resolveRequiredLength(
333       style.height ?? context.allocation.height,
334       context.percentageBasis.height,
335       'height',
336       context,
337     ),
338   } as ResolvedLayerStyle;
339 }
340 
341 function createPrivateLayerRoot(
342   children: readonly PibblElement<any>[],
343 ): PibblElement<FragmentProps> {
344   return createElement(Fragment, {
345     key: 'pibbl-layer-root',
346     children,
347   });
348 }
349 
350 function createBounds(width: number, height: number): Path2D {
351   const bounds = new Path2D();
352   bounds.rect(0, 0, width, height);
353   return bounds;
354 }
355 

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