packages/core/src/lib/layout/measure.ts
This is the source snapshot used to build these API details. View this revision on GitHub.
1 import { bindCanvasMeasurementService, sameCanvasMeasurementService } from './canvas-measurement.js';
2 import { allocationMeasurement, declineUnrecordedAllocationMeasurement, declineUntracedAllocationQuery, allocationQueryReplayRevision, allocationQueryVolatilityRevision } from './allocation-checkpoint.js';
3 import { allocationOwner, setAllocationOwner } from './allocation-revision.js';
4 import { isFitContent } from '../style/sizing-length.js';
5 import { observeReceiverInputReads, captureReceiverInputProvision, replayReceiverInputProvision, withReceiverInputProvision, type ReceiverInputProvisionReceipt } from '../signals/input-provision.js';
6 import type { BoxStyle } from '../style/types.js';
7 import { hasPercentageBoxPadding } from './box-insets.js';
8 import { contentBoxStyle } from './box-sizing.js';
9 import { isLayoutComponent, placedLayoutComponentRoot } from './define-layout-component.js';
10 import { getStyleMeasurementMode, withStyleMeasurement, rejectResponsiveMeasurement, UnsupportedResponsiveMeasurement, type PreparedQuery } from '../style/responsive.js';
11 import { layoutDiagnostic } from '../style/diagnostics.js';
12 import { GLOBAL_STATE } from '../global-state.js';
13 import { withMeasurementLayoutOwner } from './wasm/region.js';
14 import { EMPTY_STYLE } from '../style/empty-style.js';
15 import {
16 takePreNormalizedStyle,
17 peekPreNormalizedStyle,
18 withoutSystemFilter,
19 } from '../style/resolve-dispatch.js';
20 import {
21 createPrimitiveReceiverToken,
22 getPrimitiveDefinition,
23 getPrimitiveProgramProps,
24 getPrimitiveReceiverToken,
25 getElementMetadata,
26 } from '../element/metadata.js';
27 import { resolvePrimitiveInputs } from '../element/resolve-primitive-inputs.js';
28 import { recordLayoutMeasurement } from './diagnostics.js';
29 import type {
30 CanvasMeasurementService,
31 MeasureResult,
32 IntrinsicSizesResult,
33 BaselinesResult,
34 BaselineMeasureInput,
35 SystemStyle,
36 } from '../types.js';
37 import type { PibblElement } from '../element/types.js';
38 import { prepareElementPolicies } from '../element/children.js';
39 import type { Constraints, LayoutBox } from './types.js';
40 import { isSignal, trackSignalDependency, withSignalTracking, type SignalNode, withSignalDependencyRole, untracked, withSignalWriteForbidden } from '../signals/graph.js';
41
42 export type {
43 CanvasMeasurementService,
44 MeasureInput,
45 MeasureResult,
46 } from '../types.js';
47
48 /**
49 * Measures an element against logical size constraints using the supplied Canvas measurement service.
50 *
51 * @param element - Element whose declared measurement capability is used. See {@link PibblElement}.
52 * @param constraints - Available size constraints in logical units. See {@link Constraints}.
53 * @param service - Canvas text measurement service. See {@link CanvasMeasurementService}.
54 * @returns Measured dimensions, or an unsupported result with its reason. See
55 * {@link MeasureResult} .
56 *
57 * @see {@link PibblElement}
58 * @see {@link Constraints}
59 * @see {@link CanvasMeasurementService}
60 * @see {@link MeasureResult}
61 */
62 export function measureElement(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService): MeasureResult {
63 const resolveService = bindCanvasMeasurementService(service);
64 return allocationMeasurement(element, current => measureElementUncached(current, constraints, resolveService()));
65 }
66
67 function measureElementUncached(
68 element: PibblElement<any>,
69 constraints: Readonly<Constraints>,
70 service: CanvasMeasurementService,
71 ): MeasureResult {
72 const context: MeasurementContext = {
73 active: new Set(),
74 stack: [],
75 };
76 const mode = getStyleMeasurementMode() ? 'recursive' :
77 GLOBAL_STATE.componentRefs ? 'mounted-intrinsic' : 'standalone-root';
78 const owner = GLOBAL_STATE.currentPibblInstance?.interactionRoot ?? GLOBAL_STATE.currentPibblInstance;
79 const evaluate = () => withSignalWriteForbidden('Signal writes are forbidden during Pibbl measurement', () =>
80 withMeasurementLayoutOwner(owner, () => withStyleMeasurement(mode, () => withIsolatedRenderState(() =>
81 measureElementInternal(element, constraints, service, context),
82 ))),
83 );
84 const receiver = getPrimitiveReceiverToken(element);
85 return receiver ? withReceiverInputProvision(GLOBAL_STATE.renderTransaction, receiver, () => withSignalDependencyRole('measurement', evaluate)) : evaluate();
86 }
87
88 /** @internal Passive snapshot owned and released by one layout region. */
89 export interface PrimitiveMeasurementEntry {
90 readonly props: object;
91 readonly key: string;
92 readonly result: IntrinsicSizesResult | MeasureResult | BaselinesResult;
93 readonly mode: 'intrinsic' | 'finite' | 'baseline';
94 readonly dependencies: readonly SignalNode<unknown>[];
95 readonly receiverDependencies?: readonly SignalNode<unknown>[];
96 readonly dependencyVersions?: readonly number[];
97 readonly inputSnapshot: readonly unknown[] | undefined;
98 readonly receiverReceipts?: readonly ConstrainedMeasurementReceipt[];
99 }
100 function measurementDependenciesUnchanged(entry: Pick<PrimitiveMeasurementEntry, 'dependencies' | 'dependencyVersions'>): boolean {
101 const versions = entry.dependencyVersions;
102 if (!versions || versions.length !== entry.dependencies.length) return false;
103 for (let index = 0; index < versions.length; index++) {
104 const node = entry.dependencies[index]!;
105 node.validate?.();
106 if (node.version !== versions[index]) return false;
107 }
108 return true;
109 }
110 function measurementDependencyVersions(dependencies: readonly SignalNode<unknown>[]): number[] {
111 const versions: number[] = [];
112 for (let index = 0; index < dependencies.length; index++) versions.push(dependencies[index]!.version);
113 return versions;
114 }
115 interface PrimitiveMeasurementCache {
116 readPrimitiveMeasurement(token: object, key: string): PrimitiveMeasurementEntry | undefined;
117 writePrimitiveMeasurement(token: object, entry: PrimitiveMeasurementEntry): void;
118 }
119 const intrinsicTransactions = new WeakMap<object, WeakMap<object, Map<string, PrimitiveMeasurementEntry>>>();
120
121 // Conservative admission: mutable nested props or custom style records always
122 // remeasure. Scalar snapshots also detect production-mode in-place scalar writes.
123 function intrinsicInputSnapshot(element: PibblElement<any>): unknown[] | undefined {
124 const props = getPrimitiveProgramProps<Record<string, unknown>>(element);
125 const style = peekPreNormalizedStyle(element)?.style as Readonly<Record<string, unknown>> | undefined;
126 const snapshot: unknown[] = [];
127 for (const key of Object.keys(props)) {
128 const value = props[key];
129 if (value !== null && (typeof value === 'object' && !isSignal(value) || typeof value === 'function')) return;
130 snapshot.push(key, value);
131 }
132 if (style) for (const key of Object.keys(style)) {
133 const value = style[key];
134 // This module-branded sizing record is immutable; snapshot its semantic limit
135 // rather than its per-render identity. Other object-valued styles stay conservative.
136 if (isFitContent(value) && Object.isFrozen(value)) {
137 snapshot.push(key, isFitContent, value.limit);
138 continue;
139 }
140 if (value !== null && (typeof value === 'object' || typeof value === 'function')) return;
141 snapshot.push(key, value);
142 }
143 return snapshot;
144 }
145 function sameIntrinsicInputs(left: readonly unknown[] | undefined, right: readonly unknown[] | undefined): boolean {
146 if (!left || !right || left.length !== right.length) return false;
147 for (let index=0; index<left.length; index++) if (!Object.is(left[index], right[index])) return false;
148 return true;
149 }
150
151 interface PrimitiveMeasurementOptions {
152 cache: PrimitiveMeasurementCache;
153 token: object;
154 key: string;
155 recordMeasurement: () => void;
156 }
157 /** @internal Paired content contributions through the existing pure receiver transaction. */
158 export function measureIntrinsicElement(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, options?: PrimitiveMeasurementOptions): IntrinsicSizesResult {
159 const resolveService = bindCanvasMeasurementService(service);
160 return allocationMeasurement(element, current => measurePrimitiveInput(current, constraints, resolveService(), true, options));
161 }
162 /** @internal Finite custom measurement through the same receiver transaction and cache. */
163 export function measureConstrainedIntrinsicElement(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, options?: PrimitiveMeasurementOptions): MeasureResult {
164 const resolveService = bindCanvasMeasurementService(service);
165 return allocationMeasurement(element, current => measurePrimitiveInput(current, constraints, resolveService(), false, options));
166 }
167 /** @internal Parent-owned prepared row result with fresh receiver paths per query. */
168 export function measurePreparedLayoutElement(
169 element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService,
170 options: PrimitiveMeasurementOptions, snapshot: readonly unknown[], receivers: readonly object[],
171 ): MeasureResult {
172 declineUnrecordedAllocationMeasurement();
173 return measurePrimitiveInput(element, constraints, service, false, options, { snapshot, receivers });
174 }
175 interface PreparedMeasurementInput {
176 readonly snapshot: readonly unknown[];
177 readonly receivers: readonly object[];
178 }
179
180
181 interface PreparedBaselineOwner {
182 readonly transaction: object;
183 readonly receiver: object;
184 readonly query: PreparedQuery;
185 readonly width: number;
186 readonly height: number;
187 }
188 const preparedBaselineOwners = new WeakMap<PibblElement<any>, PreparedBaselineOwner>();
189 /** @internal One-shot proof of a direct child's current finite Flex selection. */
190 export function setPreparedBaselineOwner(element: PibblElement<any>, owner: Readonly<LayoutBox>): void {
191 const transaction = GLOBAL_STATE.renderTransaction;
192 const receiver = getPrimitiveReceiverToken(element);
193 const query = peekPreNormalizedStyle(element)?.query;
194 if (!transaction || !receiver || !query || !Number.isFinite(owner.width) || !Number.isFinite(owner.height) ||
195 query.basis.width !== owner.width || query.basis.height !== owner.height) return;
196 preparedBaselineOwners.set(element, { transaction, receiver, query, width: owner.width, height: owner.height });
197 }
198
199 /** @internal Cache identity for a transparent, currently prepared primitive root. */
200 export interface BaselineMeasurementOptions extends PrimitiveMeasurementOptions {
201 source?: PibblElement<any>;
202 }
203
204 /** @internal Pure first/last baseline query at one final content allocation. */
205 export function measureBaselineElement(element: PibblElement<any>, allocation: Readonly<LayoutBox>, service: CanvasMeasurementService, options?: BaselineMeasurementOptions): BaselinesResult {
206 const resolveService = bindCanvasMeasurementService(service);
207 const owner = preparedBaselineOwners.get(element);
208 const ownerValid = owner && owner.transaction === GLOBAL_STATE.renderTransaction &&
209 owner.receiver === getPrimitiveReceiverToken(element) && owner.query === peekPreNormalizedStyle(element)?.query;
210 const ownerBox = ownerValid ? { x: 0, y: 0, width: owner.width, height: owner.height } : undefined;
211 return allocationMeasurement(element, current => {
212 if (ownerBox) setPreparedBaselineOwner(current, ownerBox);
213 return measureBaselineElementUncached(current, allocation, resolveService(), options);
214 }, true);
215 }
216
217 function measureBaselineElementUncached(
218 element: PibblElement<any>,
219 allocation: Readonly<LayoutBox>,
220 service: CanvasMeasurementService,
221 options?: BaselineMeasurementOptions,
222 ): BaselinesResult {
223 // Responsive baselines require the existing current-owner proof and must
224 // never bypass its validation through direct demand reuse.
225 if (!options && !peekPreNormalizedStyle(element)?.query) {
226 const mode = getStyleMeasurementMode() ? 'recursive' : GLOBAL_STATE.componentRefs ? 'mounted-intrinsic' : 'standalone-root';
227 return exactDirectMeasurement(element, service, ['baseline', mode, allocation.width, allocation.height],
228 () => measureBaselineElementWithCache(element, allocation, service));
229 }
230 return measureBaselineElementWithCache(element, allocation, service, options);
231 }
232
233 function measureBaselineElementWithCache(
234 element: PibblElement<any>, allocation: Readonly<LayoutBox>, service: CanvasMeasurementService, options?: BaselineMeasurementOptions,
235 ): BaselinesResult {
236 const transaction = GLOBAL_STATE.renderTransaction;
237 const receiver = getPrimitiveReceiverToken(element);
238 const mode = getStyleMeasurementMode() ? 'recursive' : GLOBAL_STATE.componentRefs ? 'mounted-intrinsic' : 'standalone-root';
239 const key = `baseline:${options?.key ?? ''}`;
240 const constraints = {
241 minWidth: allocation.width, maxWidth: allocation.width,
242 minHeight: allocation.height, maxHeight: allocation.height,
243 };
244 return withSignalWriteForbidden('Signal writes are forbidden during Pibbl measurement', () => withReceiverInputProvision(transaction, receiver, () => withSignalDependencyRole('measurement', () => {
245 const source = options?.source ?? element;
246 let inputSnapshot = intrinsicInputSnapshot(element);
247 if (source !== element) {
248 const sourceSnapshot = intrinsicInputSnapshot(source);
249 if (!sourceSnapshot || !inputSnapshot) inputSnapshot = undefined;
250 else {
251 // The source props retain one wrapper occurrence; the complete scalar
252 // root snapshot permits fresh JSX descriptions without retaining roots.
253 sourceSnapshot.push(source.type, source.key, element.type, element.key, inputSnapshot.length);
254 for (let index = 0; index < inputSnapshot.length; index++) sourceSnapshot.push(inputSnapshot[index]);
255 inputSnapshot = sourceSnapshot;
256 }
257 }
258 let receivers = transaction && intrinsicTransactions.get(transaction);
259 let entries = options && receivers?.get(options.token);
260 let entry = options && (entries?.get(key) ?? options.cache.readPrimitiveMeasurement(options.token, key));
261 if (!entry || !measurementDependenciesUnchanged(entry) || entry.mode !== 'baseline' || entry.props !== source.props || !sameIntrinsicInputs(entry.inputSnapshot, inputSnapshot)) {
262 options?.recordMeasurement();
263 const dependencies: SignalNode<unknown>[] = [];
264 const addDependency = (node: SignalNode<unknown>) => { if (!dependencies.includes(node)) dependencies.push(node); };
265 const result = observeReceiverInputReads(addDependency, () => withSignalTracking({ addDependency }, () =>
266 withStyleMeasurement(mode, () => withIsolatedRenderState(() =>
267 measureBaselineInput(element, allocation, constraints, service),
268 ))));
269 entry = { props: source.props, key, result, mode: 'baseline', dependencies, dependencyVersions: measurementDependencyVersions(dependencies), inputSnapshot };
270 if (options && transaction && inputSnapshot && result.status === 'measured') {
271 if (!receivers) { receivers = new WeakMap(); intrinsicTransactions.set(transaction, receivers); }
272 if (!entries) { entries = new Map(); receivers.set(options.token, entries); }
273 entries.set(key, entry);
274 const snapshot = entry;
275 transaction.onFinish(success => { if (success) options.cache.writePrimitiveMeasurement(options.token, snapshot); });
276 }
277 }
278 for (const node of entry.dependencies) trackSignalDependency(node, 'measurement');
279 return entry.result as BaselinesResult;
280 })));
281 }
282
283 function measureBaselineInput(
284 original: PibblElement<any>,
285 allocation: Readonly<LayoutBox>,
286 constraints: Readonly<Constraints>,
287 service: CanvasMeasurementService,
288 ): BaselinesResult {
289 const element = prepareElementPolicies(original, 'measureBaselines');
290 recordLayoutMeasurement();
291 const definition = getPrimitiveDefinition(element.type);
292 const component = element.type.name || 'Anonymous';
293 if (isLayoutComponent(element.type)) {
294 return { status: 'unsupported', reason: 'baseline providers currently require a direct custom primitive' };
295 }
296 if (!definition?.measureBaselines) {
297 return { status: 'unsupported', reason: `${component} does not provide baseline measurement` };
298 }
299 const preNormalized = takePreNormalizedStyle(element);
300 const preparedOwner = preparedBaselineOwners.get(element);
301 preparedBaselineOwners.delete(element);
302 if (preNormalized?.query && getStyleMeasurementMode() !== 'standalone-root') {
303 // Only the direct Flex owner's already-selected style may cross this pure
304 // boundary. Never evaluate responsive rules against the provider allocation.
305 const query = preNormalized.query;
306 if (getStyleMeasurementMode() !== 'mounted-intrinsic' || !preparedOwner ||
307 preparedOwner.transaction !== GLOBAL_STATE.renderTransaction ||
308 preparedOwner.receiver !== getPrimitiveReceiverToken(element) || preparedOwner.query !== query ||
309 preparedOwner.width !== query.basis.width || preparedOwner.height !== query.basis.height) {
310 rejectResponsiveMeasurement(element);
311 }
312 }
313 const inputs = resolvePrimitiveInputs(element, definition, preNormalized, {
314 width: allocation.width, height: allocation.height,
315 });
316 const specifiedStyle = withoutSystemFilter(preNormalized?.style ?? inputs.style ?? EMPTY_STYLE);
317 let normalized = preNormalized ? specifiedStyle : definition.normalizeStyle ?
318 definition.normalizeStyle(specifiedStyle) : specifiedStyle;
319 if (hasPercentageBoxPadding(normalized as Readonly<BoxStyle>)) {
320 return { status: 'unsupported', reason: 'percentage padding requires an actual finite Flex owner allocation' };
321 }
322 if ('boxSizing' in normalized && normalized.boxSizing !== undefined) {
323 normalized = contentBoxStyle(normalized as Readonly<BoxStyle>, {
324 width: allocation.width, height: allocation.height,
325 context: { component, algorithm: 'baseline measurement', constraints },
326 });
327 }
328 const previousReceiverToken = GLOBAL_STATE.primitiveReceiverToken;
329 GLOBAL_STATE.primitiveReceiverToken = getPrimitiveReceiverToken(element) ?? createPrimitiveReceiverToken();
330 try {
331 const result = definition.measureBaselines({
332 props: inputs.props,
333 style: normalized,
334 allocation: { x: 0, y: 0, width: allocation.width, height: allocation.height },
335 service,
336 } as BaselineMeasureInput<Record<PropertyKey, unknown>, SystemStyle>);
337 if (result.status === 'unsupported') return result;
338 if (result.status !== 'measured' || !Number.isFinite(result.first) || !Number.isFinite(result.last) || result.first > result.last) {
339 throw layoutDiagnostic({
340 component, property: 'measureBaselines', value: result,
341 algorithm: 'baseline measurement', constraints,
342 reason: 'first and last baselines must be finite with first not after last',
343 });
344 }
345 return { status: 'measured', first: result.first, last: result.last };
346 } catch (error) {
347 if (error instanceof UnsupportedResponsiveMeasurement) return { status: 'unsupported', reason: error.message };
348 throw error;
349 } finally {
350 GLOBAL_STATE.primitiveReceiverToken = previousReceiverToken;
351 }
352 }
353 function measurePrimitiveInput(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, intrinsic: true, options?: PrimitiveMeasurementOptions): IntrinsicSizesResult;
354 function measurePrimitiveInput(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, intrinsic: false, options?: PrimitiveMeasurementOptions, prepared?: PreparedMeasurementInput): MeasureResult;
355 function measurePrimitiveInput(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, intrinsic: boolean, options?: PrimitiveMeasurementOptions, prepared?: PreparedMeasurementInput): IntrinsicSizesResult | MeasureResult {
356 const transaction = GLOBAL_STATE.renderTransaction;
357 const receiver = getPrimitiveReceiverToken(element);
358 const context: MeasurementContext = { active: new Set(), stack: [] };
359 const mode = getStyleMeasurementMode() ? 'recursive' : GLOBAL_STATE.componentRefs ? 'mounted-intrinsic' : 'standalone-root';
360 const key = `${intrinsic ? 'intrinsic' : 'finite'}:${options?.key ?? ''}`;
361 const owner = GLOBAL_STATE.currentPibblInstance?.interactionRoot ?? GLOBAL_STATE.currentPibblInstance;
362 return withSignalWriteForbidden('Signal writes are forbidden during Pibbl measurement', () => withMeasurementLayoutOwner(owner, () => withReceiverInputProvision(transaction, receiver, () => withSignalDependencyRole('measurement', () => {
363 const inputSnapshot = prepared?.snapshot ?? intrinsicInputSnapshot(element);
364 let receivers = transaction && intrinsicTransactions.get(transaction);
365 let entries = options && receivers?.get(options.token);
366 let entry = options && (entries?.get(key) ?? options.cache.readPrimitiveMeasurement(options.token, key));
367 const entryMode = intrinsic ? 'intrinsic' : 'finite';
368 if (!entry || !measurementDependenciesUnchanged(entry) || entry.mode !== entryMode || entry.props !== element.props || !sameIntrinsicInputs(entry.inputSnapshot, inputSnapshot) || prepared && entry.receiverReceipts === undefined) {
369 options?.recordMeasurement();
370 const dependencies: SignalNode<unknown>[] = [];
371 const receiverDependencies: SignalNode<unknown>[] = [];
372 let untracedReceiverReads = false;
373 const trace: ConstrainedMeasurementTrace | undefined = prepared ? {
374 cacheable: true, receipts: [], receivers: prepared.receivers,
375 } : undefined;
376 const evaluate = () => withStyleMeasurement(mode, () => withIsolatedRenderState(() => intrinsic ?
377 measureElementInternal(element, constraints, service, context, true) :
378 measureElementInternal(element, constraints, service, context, false, true),
379 ));
380 const addDependency = (node: SignalNode<unknown>) => {
381 if (!dependencies.includes(node)) dependencies.push(node);
382 if (!receiverDependencies.includes(node)) receiverDependencies.push(node);
383 };
384 const result = observeReceiverInputReads((node, _roles, inputReceiver) => {
385 if (!dependencies.includes(node)) dependencies.push(node);
386 if (inputReceiver === receiver && !receiverDependencies.includes(node)) receiverDependencies.push(node);
387 if (inputReceiver !== receiver && !trace) untracedReceiverReads = true;
388 }, () => withSignalTracking({ addDependency }, () =>
389 trace ? withConstrainedMeasurementTrace(trace, evaluate) : evaluate()));
390 entry = { props: element.props, key, result, mode: entryMode, dependencies, receiverDependencies, dependencyVersions: measurementDependencyVersions(dependencies), inputSnapshot,
391 ...(trace?.cacheable ? { receiverReceipts: trace.receipts } : {}) };
392 if (options && transaction && inputSnapshot && result.status === 'measured' && !untracedReceiverReads && (!trace || trace.cacheable)) {
393 if (!receivers) { receivers = new WeakMap(); intrinsicTransactions.set(transaction, receivers); }
394 if (!entries) { entries = new Map(); receivers.set(options.token, entries); }
395 entries.set(key, entry);
396 const snapshot = entry;
397 transaction.onFinish(success => { if (success) options.cache.writePrimitiveMeasurement(options.token, snapshot); });
398 }
399 }
400 if (prepared && entry.receiverReceipts) {
401 for (let index = 0; index < entry.receiverReceipts.length; index++) {
402 const captured = entry.receiverReceipts[index];
403 replayReceiverInputProvision(transaction, prepared.receivers[captured.childIndex], captured.receipt);
404 }
405 }
406 for (const node of entry.receiverDependencies ?? entry.dependencies) trackSignalDependency(node, 'measurement');
407 return entry.result as IntrinsicSizesResult | MeasureResult;
408 }))));
409 }
410
411 interface MeasurementContext {
412 active: Set<PibblElement<any>>;
413 stack: PibblElement<any>[];
414 }
415
416 // Present only while a primitive measurement callback is evaluating. Flex uses this
417 // continuation for its explicitly admitted paired structural child, so the child
418 // shares the caller's cycle stack and receives provider inputs with measurement
419 // dependency tracking. Ordinary `input.measureElement` remains unchanged.
420 let constrainedChildContext: MeasurementContext | undefined;
421 let constrainedChildService: CanvasMeasurementService | undefined;
422 interface ConstrainedMeasurementReceipt {
423 readonly childIndex: number;
424 readonly receipt: ReceiverInputProvisionReceipt;
425 }
426 export interface ConstrainedMeasurementTrace {
427 cacheable: boolean;
428 readonly receipts: ConstrainedMeasurementReceipt[];
429 readonly receivers: readonly object[];
430 }
431 let constrainedMeasurementTrace: ConstrainedMeasurementTrace | undefined;
432 /** @internal Binds one direct known-row provider trace without retaining receiver tokens. */
433 export function withConstrainedMeasurementTrace<T>(trace: ConstrainedMeasurementTrace, work: () => T): T {
434 const previous = constrainedMeasurementTrace;
435 constrainedMeasurementTrace = trace;
436 try { return work(); }
437 finally { constrainedMeasurementTrace = previous; }
438 }
439 interface ExactDirectDemand {
440 readonly type: Function;
441 readonly service: CanvasMeasurementService;
442 readonly key: readonly unknown[];
443 readonly inputs: readonly unknown[];
444 readonly receipt: ReceiverInputProvisionReceipt;
445 readonly dependencies: readonly SignalNode<unknown>[];
446 readonly dependencyVersions: readonly number[];
447 readonly result: MeasureResult | BaselinesResult;
448 }
449 const exactDirectDemands = new WeakMap<object, WeakMap<object, ExactDirectDemand>>();
450
451 // A failed allocation equality barrier may demand the same pure query again.
452 // Share only current transaction/receiver numeric demands, never an old program.
453 function exactDirectMeasurement<T extends MeasureResult | BaselinesResult>(
454 element: PibblElement<any>, service: CanvasMeasurementService, key: readonly unknown[], run: () => T, allowHit = true,
455 ): T {
456 const transaction = GLOBAL_STATE.renderTransaction, receiver = getPrimitiveReceiverToken(element);
457 if (!transaction || !receiver || Object.hasOwn(element.props, 'children') || isLayoutComponent(element.type)) return run();
458 const inputs = peekPreNormalizedStyle(element) ? intrinsicInputSnapshot(element) : undefined;
459 const demands = exactDirectDemands.get(transaction), prior = demands?.get(receiver);
460 if (allowHit && inputs && prior && prior.type === element.type && sameCanvasMeasurementService(prior.service, service) &&
461 sameIntrinsicInputs(prior.key, key) && sameIntrinsicInputs(prior.inputs, inputs) && measurementDependenciesUnchanged(prior)) {
462 takePreNormalizedStyle(element);
463 replayReceiverInputProvision(transaction, receiver, prior.receipt);
464 return prior.result as T;
465 }
466 let direct = true;
467 const receipt: { node: SignalNode<unknown>; roles: number }[] = [];
468 const replayRevision = allocationQueryReplayRevision(), volatility = allocationQueryVolatilityRevision();
469 const captured = observeReceiverInputReads((node, roles, owner) => {
470 if (owner !== receiver) { direct = false; return; }
471 const existing = receipt.find(entry => entry.node === node);
472 if (existing) existing.roles |= roles;
473 else receipt.push({ node, roles });
474 }, () => captureReceiverInputProvision(transaction, receiver, run));
475 if (inputs && direct && replayRevision === allocationQueryReplayRevision() && volatility === allocationQueryVolatilityRevision() && captured.receipt && captured.value.status === 'measured') {
476 let current = demands;
477 if (!current) {
478 current = new WeakMap(); exactDirectDemands.set(transaction, current);
479 transaction.onFinish(() => exactDirectDemands.delete(transaction));
480 }
481 const dependencies = receipt.map(entry => entry.node);
482 current.set(receiver, { type: element.type, service, key, inputs, receipt, dependencies,
483 dependencyVersions: measurementDependencyVersions(dependencies), result: captured.value });
484 }
485 return captured.value;
486 }
487
488 export function measureConstrainedLayoutChild(
489 element: PibblElement<any>,
490 constraints: Readonly<Constraints>,
491 childIndex?: number,
492 ): MeasureResult {
493 const context = constrainedChildContext, service = constrainedChildService;
494 if (!context || !service) throw new Error('Constrained structural measurement requires an active provider measurement.');
495 const transaction = GLOBAL_STATE.renderTransaction;
496 const receiver = getPrimitiveReceiverToken(element);
497 const trace = constrainedMeasurementTrace;
498 const run = () => withSignalDependencyRole('measurement', () =>
499 measureElementInternal(element, constraints, service, context, false, true));
500 // The structural tracer has no indexed leaf path for this native continuation.
501 if (transaction && receiver && childIndex === undefined && !Object.hasOwn(element.props, 'children') && !isLayoutComponent(element.type)) {
502 if (trace) trace.cacheable = false;
503 const metadata = getElementMetadata(element);
504 const source = metadata?.policyPreparationSource ?? metadata?.layoutDescriptionSource ?? peekPreNormalizedStyle(element)?.source ?? element;
505 return exactDirectMeasurement(element, service,
506 ['size', getStyleMeasurementMode(), constraints.minWidth, constraints.maxWidth, constraints.minHeight, constraints.maxHeight],
507 run, !context.active.has(source));
508 }
509 if (!trace) return withReceiverInputProvision(transaction, receiver, run);
510 if (childIndex === undefined || trace.receivers[childIndex] !== receiver) {
511 trace.cacheable = false;
512 return withReceiverInputProvision(transaction, receiver, run);
513 }
514 const captured = captureReceiverInputProvision(transaction, receiver, run);
515 if (captured.receipt === undefined) trace.cacheable = false;
516 else trace.receipts.push({ childIndex, receipt: captured.receipt });
517 return captured.value;
518 }
519
520 function measureElementInternal(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, context: MeasurementContext, intrinsic: true): IntrinsicSizesResult;
521 function measureElementInternal(element: PibblElement<any>, constraints: Readonly<Constraints>, service: CanvasMeasurementService, context: MeasurementContext, intrinsic?: false, providerInputs?: boolean): MeasureResult;
522 function measureElementInternal(
523 element: PibblElement<any>,
524 constraints: Readonly<Constraints>,
525 service: CanvasMeasurementService,
526 context: MeasurementContext,
527 intrinsic = false,
528 providerInputs = false,
529 ): MeasureResult | IntrinsicSizesResult {
530 element = prepareElementPolicies(element, 'measureElement');
531 recordLayoutMeasurement();
532 const type = element.type;
533 const definition = getPrimitiveDefinition(type);
534 const component = type.name || 'Anonymous';
535 const preNormalized = takePreNormalizedStyle(element);
536 const metadata = getElementMetadata(element);
537 const source = metadata?.policyPreparationSource ?? metadata?.layoutDescriptionSource ??
538 preNormalized?.source ??
539 element;
540 if (context.active.has(source)) {
541 throw layoutDiagnostic({
542 component,
543 property: 'measurement',
544 value: context.stack.map(item => item.type.name || 'Anonymous'),
545 algorithm: 'measurement',
546 constraints,
547 reason: 'cyclic measurement dependency is not supported',
548 });
549 }
550 if (isLayoutComponent(type)) {
551 context.active.add(source);
552 context.stack.push(element);
553 try {
554 // A declared layout description is the existing pure boundary. Preserve the
555 // caller's measurement mode so a paired primitive root can contribute its
556 // intrinsic result or receive provider inputs under the same transaction.
557 const root = placedLayoutComponentRoot(element, preNormalized);
558 return withReceiverInputProvision(GLOBAL_STATE.renderTransaction, getPrimitiveReceiverToken(root), () => intrinsic ?
559 measureElementInternal(root, constraints, service, context, true) :
560 measureElementInternal(root, constraints, service, context, false, providerInputs));
561 } finally {
562 context.stack.pop();
563 context.active.delete(source);
564 }
565 }
566 if (intrinsic ? !definition?.measureIntrinsic : !definition?.measure) {
567 return {
568 status: 'unsupported',
569 reason: `${component} does not provide ${intrinsic ? 'intrinsic measurement' : 'measurement'}`,
570 };
571 }
572
573 context.active.add(source);
574 context.stack.push(element);
575 try {
576 if (preNormalized?.query && getStyleMeasurementMode() !== 'standalone-root') {
577 rejectResponsiveMeasurement(element);
578 }
579 const readInputs = () => resolvePrimitiveInputs(element, definition!, preNormalized, {
580 width: constraints.maxWidth, height: constraints.maxHeight,
581 });
582 const inputs = intrinsic || providerInputs ? readInputs() : untracked(readInputs);
583 const specifiedStyle = withoutSystemFilter(
584 preNormalized?.style ?? inputs.style ?? EMPTY_STYLE,
585 );
586 let normalized = preNormalized ?
587 specifiedStyle :
588 definition!.normalizeStyle ?
589 definition!.normalizeStyle!(specifiedStyle) :
590 specifiedStyle;
591 if (hasPercentageBoxPadding(normalized as Readonly<BoxStyle>)) return { status: 'unsupported', reason: 'percentage padding requires an actual finite Flex owner allocation' };
592 if ('boxSizing' in normalized && normalized.boxSizing !== undefined) normalized = contentBoxStyle(normalized as Readonly<BoxStyle>, { width: constraints.maxWidth, height: constraints.maxHeight, context: { component, algorithm: 'measurement', constraints } });
593 const previousReceiverToken = GLOBAL_STATE.primitiveReceiverToken;
594 GLOBAL_STATE.primitiveReceiverToken =
595 getPrimitiveReceiverToken(element) ?? createPrimitiveReceiverToken();
596 let result: MeasureResult | IntrinsicSizesResult;
597 const previousConstrainedChildContext = constrainedChildContext;
598 const previousConstrainedChildService = constrainedChildService;
599 if (!intrinsic) { constrainedChildContext = context; constrainedChildService = service; }
600 try {
601 result = withStyleMeasurement('recursive', () => intrinsic ? definition!.measureIntrinsic!({
602 props: inputs.props, style: normalized, service,
603 constraints: {
604 width: Number.isFinite(constraints.maxWidth) ? { kind: 'bounded', min: constraints.minWidth, max: constraints.maxWidth } : { kind: 'unbounded', min: constraints.minWidth },
605 height: Number.isFinite(constraints.maxHeight) ? { kind: 'bounded', min: constraints.minHeight, max: constraints.maxHeight } : { kind: 'unbounded', min: constraints.minHeight },
606 },
607 }) : definition!.measure!({
608 props: inputs.props,
609 style: normalized,
610 constraints,
611 service,
612 measureElement: (child, childConstraints) => {
613 // Public recursive queries have no direct-child receipt path. Preserve
614 // their ordinary measurement behavior without caching this aggregate.
615 if (constrainedMeasurementTrace) constrainedMeasurementTrace.cacheable = false;
616 const receiver = getPrimitiveReceiverToken(child);
617 const prepared = peekPreNormalizedStyle(child);
618 // Known layout providers pass current normalized children with an
619 // owned receiver path. Their props must join that receiver's receipt.
620 // Arbitrary public descriptors have no such replayable input proof.
621 if (!receiver || !prepared) declineUntracedAllocationQuery();
622 return receiver ? withReceiverInputProvision(GLOBAL_STATE.renderTransaction, receiver, () => withSignalDependencyRole('measurement', () =>
623 measureElementInternal(child, childConstraints, service, context, false, !!prepared))) : measureElementInternal(child, childConstraints, service, context);
624 },
625 }));
626 } finally {
627 constrainedChildContext = previousConstrainedChildContext;
628 constrainedChildService = previousConstrainedChildService;
629 GLOBAL_STATE.primitiveReceiverToken = previousReceiverToken;
630 }
631 if (result.status === 'unsupported') return result;
632 if ('minContent' in result) {
633 validateMeasuredSize(result.minContent.width, 'minContent.width', component, constraints);
634 validateMeasuredSize(result.minContent.height, 'minContent.height', component, constraints);
635 validateMeasuredSize(result.maxContent.width, 'maxContent.width', component, constraints);
636 validateMeasuredSize(result.maxContent.height, 'maxContent.height', component, constraints);
637 if (result.minContent.width > result.maxContent.width) throw layoutDiagnostic({ component, property: 'measureIntrinsic', value: result, algorithm: 'measurement', constraints, reason: 'min-content width must not exceed max-content width' });
638 return result;
639 }
640 validateMeasuredSize(result.size.width, 'width', component, constraints);
641 validateMeasuredSize(result.size.height, 'height', component, constraints);
642 return result;
643 } catch (error) {
644 if (error instanceof UnsupportedResponsiveMeasurement) {
645 return { status: 'unsupported', reason: error.message };
646 }
647 throw error;
648 } finally {
649 context.stack.pop();
650 context.active.delete(source);
651 }
652 }
653
654 /** @internal Shared pure measurement preparation; never lends a mounted render context. */
655 export function withIsolatedRenderState<T>(work: () => T): T {
656 const previousAllocationOwner = setAllocationOwner(allocationOwner());
657 const snapshot = {
658 currentPibblInstance: GLOBAL_STATE.currentPibblInstance,
659 componentRefs: GLOBAL_STATE.componentRefs,
660 canvas: GLOBAL_STATE.canvas,
661 componentIsMounting: GLOBAL_STATE.componentIsMounting,
662 componentHookIndex: GLOBAL_STATE.componentHookIndex,
663 renderContext: GLOBAL_STATE.renderContext,
664 primitiveReceiverToken: GLOBAL_STATE.primitiveReceiverToken,
665 seenIds: GLOBAL_STATE.seenIds,
666 seenKeys: GLOBAL_STATE.seenKeys,
667 clippingStack: GLOBAL_STATE.clippingStack,
668 layoutStack: GLOBAL_STATE.layoutStack,
669 };
670 GLOBAL_STATE.currentPibblInstance = undefined;
671 GLOBAL_STATE.componentRefs = undefined;
672 GLOBAL_STATE.canvas = undefined;
673 GLOBAL_STATE.componentIsMounting = false;
674 GLOBAL_STATE.componentHookIndex = 0;
675 GLOBAL_STATE.renderContext = undefined;
676 GLOBAL_STATE.primitiveReceiverToken = undefined;
677 GLOBAL_STATE.seenIds = undefined;
678 GLOBAL_STATE.seenKeys = undefined;
679 GLOBAL_STATE.clippingStack = [];
680 GLOBAL_STATE.layoutStack = undefined;
681 try {
682 return work();
683 } finally {
684 Object.assign(GLOBAL_STATE, snapshot);
685 setAllocationOwner(previousAllocationOwner);
686 }
687 }
688
689 function validateMeasuredSize(
690 value: number,
691 property: string,
692 component: string,
693 constraints: Readonly<Constraints>,
694 ): void {
695 if (!Number.isFinite(value) || value < 0) {
696 throw layoutDiagnostic({
697 component,
698 property,
699 value,
700 algorithm: 'measurement',
701 constraints,
702 reason: 'measured dimensions must be finite and nonnegative',
703 });
704 }
705 }
706
Documentation version
Section titled “Documentation version”Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.