packages/core/src/lib/layout/define-layout-component.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import type { PibblComponent, PibblElement, PibblNodeInput } from '../element/types.js';
2 import { clonePibblElement } from '../element/create-element.js';
3 import { materializeContainerChildren } from '../element/children.js';
4 import { getChildPrimitiveReceiverToken, getElementMetadata, setElementMetadata, getPrimitiveDefinition, getPrimitiveReceiverToken, setPrimitiveReceiverToken, isPlacementConsumed, setPlacementConsumed } from '../element/metadata.js';
5 import { GLOBAL_STATE } from '../global-state.js';
6 import { withHooksForbidden } from '../hooks/hook-slot.js';
7 import { withSignalWriteForbidden } from '../signals/graph.js';
8 import { adoptReceiverInputProvision, withReceiverInputProvision } from '../signals/input-provision.js';
9 import type { PibblRenderTransaction } from '../types.js';
10 import { withIsolatedRenderState } from './measure.js';
11 import { setPreNormalizedStyle, type PreparedStyleInput } from '../style/resolve-dispatch.js';
12
13 const definitions = new WeakMap<Function, (props: any) => PibblNodeInput>();
14 const transactions = new WeakMap<PibblRenderTransaction, WeakMap<object, PibblElement<any>>>();
15
16 /**
17 * Defines pure reusable structure that a parent can inspect before allocation.
18 * The description returns one drawing or layout primitive root, optionally inside
19 * transparent fragments. Forward any authored style explicitly to that root.
20 * Signal reads are supported; hooks, Canvas/allocation reads, writes and resource
21 * creation are excluded. Descriptions are shared only within one transaction.
22 *
23 * @param describe - Pure synchronous description using authored readonly props.
24 * @returns A component for JSX or createElement, preserving normal type/key identity.
25 * @throws When called directly, or when its description has no single primitive root.
26 * @see {@link PibblComponent}
27 * @see {@link PibblNodeInput}
28 */
29 export function defineLayoutComponent<P>(
30 describe: (props: Readonly<P>) => PibblNodeInput,
31 ): PibblComponent<P> {
32 if (typeof describe !== 'function') throw new TypeError('A layout description must be a function.');
33 const component: PibblComponent<P> = function LayoutComponent() {
34 throw new Error('Mount layout components through JSX or createElement; do not call them directly.');
35 };
36 definitions.set(component, describe);
37 return component;
38 }
39
40 export function isLayoutComponent(type: Function): boolean { return definitions.has(type); }
41
42 /** One prepared root per layout occurrence, never cached by mutable prop identity. */
43 export function prepareLayoutComponent(
44 element: PibblElement<any>, options?: { receiverToken?: object },
45 ): PibblElement<any> {
46 const describe = definitions.get(element.type);
47 if (!describe) throw new Error('The element has no structural layout description.');
48 const transaction = GLOBAL_STATE.renderTransaction;
49 const receiver = options?.receiverToken ?? getPrimitiveReceiverToken(element) ??
50 (GLOBAL_STATE.componentRefs?.element === element ? GLOBAL_STATE.componentRefs : element);
51 let prepared = transaction ? transactions.get(transaction) : undefined;
52 const cached = prepared?.get(receiver);
53 if (cached) return cached;
54 const root = withHooksForbidden('Hooks are forbidden in a layout description.', () =>
55 withSignalWriteForbidden('Signal writes are forbidden in a layout description.', () =>
56 withIsolatedRenderState(() => withReceiverInputProvision(transaction, receiver, () => {
57 const roots = materializeContainerChildren(describe(element.props), element);
58 if (roots.length !== 1 || !getPrimitiveDefinition(roots[0].type)) {
59 throw new Error('A layout description must return exactly one drawing or layout primitive root.');
60 }
61 const root = clonePibblElement(roots[0]);
62 setElementMetadata(root, {
63 ...getElementMetadata(root),
64 layoutDescriptionSource: getElementMetadata(roots[0])?.layoutDescriptionSource ?? roots[0],
65 });
66 return root;
67 })),
68 ),
69 );
70 const current = GLOBAL_STATE.componentRefs;
71 if (current && (getPrimitiveReceiverToken(current.element) ?? current) === receiver) {
72 adoptReceiverInputProvision(transaction, receiver);
73 }
74 setPrimitiveReceiverToken(root, getChildPrimitiveReceiverToken(transaction, receiver, 0));
75 if (transaction) {
76 if (!prepared) { prepared = new WeakMap(); transactions.set(transaction, prepared); }
77 prepared.set(receiver, root);
78 }
79 return root;
80 }
81
82 /** Carries the parent's settled content size into the same prepared root. */
83 export function placedLayoutComponentRoot(element: PibblElement<any>, style?: PreparedStyleInput): PibblElement<any> {
84 const root = prepareLayoutComponent(element);
85 const slot = getElementMetadata(element)?.preparedLayoutSlot;
86 if (!style && !slot) return root;
87 const placed = clonePibblElement(root);
88 // The description is transparent: its one actual root consumes the already
89 // allocated placement, including explicit static/relative positioning, once.
90 if (isPlacementConsumed(element)) setPlacementConsumed(placed);
91 if (style) setPreNormalizedStyle(placed, style.style, root, getPrimitiveReceiverToken(root), style.query);
92 const metadata = getElementMetadata(element);
93 if (slot || metadata?.absoluteContainingBlock) setElementMetadata(placed, {
94 ...getElementMetadata(placed),
95 ...(slot ? { preparedLayoutSlot: slot } : undefined),
96 ...(metadata?.absoluteContainingBlock ? { absoluteContainingBlock: metadata.absoluteContainingBlock } : undefined),
97 });
98 return placed;
99 }
100
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.