Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

test(Layer): the entrance layout proof names the source of a layout (#10684)

Christopher Chedeauf9981429b48f
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.md
index 274c61ba57..2fbc3c3d9f 100644
--- a/internal/interaction-harness/README.md
+++ b/internal/interaction-harness/README.md
@@ -386,7 +386,10 @@ interaction; `countBetween` counts the steady middle of an animation (its
first and last frames may commit). A transform/opacity animation does no
Layout or Paint there; a layout-property animation does one per frame. Each
counted `Paint` names the node it painted (`node`), and each `UpdateLayoutTree`
-counts the elements it restyled (`elements`). The
+counts the elements it restyled (`elements`). A proof that expects no Layout
+can explain one: `traceRendering(page, body, {keepEvents: true})` keeps the
+window's main-thread events, and `layoutSources` names the task that ran each
+Layout and each invalidation before it. The
harness's own animation recorder stands down while the trace runs, since its
frame loop would make every frame a main-thread one, restyling each running
animation's target and laying out an anchored one: it reads only the element a
diff --git a/internal/interaction-harness/src/trace.layoutSources.test.ts b/internal/interaction-harness/src/trace.layoutSources.test.ts
new file mode 100644
index 0000000000..f2d3763f95
--- /dev/null
+++ b/internal/interaction-harness/src/trace.layoutSources.test.ts
@@ -0,0 +1,142 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file trace.layoutSources.test.ts
+ * @input Synthetic main-thread trace events (no browser)
+ * @output A counted Layout gets the steps of the task that ran it. It also
+ * gets every invalidation since the previous Layout, each with the steps of
+ * its task.
+ * A Layout outside the window is not explained. No step ends in a line and
+ * a column. A trace that kept no events fails by name.
+ * @position Unit test of ./trace's layoutSources
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ layoutSources,
+ type RenderingTrace,
+ type TimedTraceEvent,
+} from './trace';
+
+/** A main-thread event at `ms` (epoch ms equals trace ms here). */
+function at(
+ ms: number,
+ name: string,
+ {durMs, data}: {durMs?: number; data?: Record<string, unknown>} = {},
+): TimedTraceEvent {
+ return {
+ name,
+ cat: 'devtools.timeline',
+ ph: 'X',
+ ts: ms * 1000,
+ ...(durMs == null ? {} : {dur: durMs * 1000}),
+ pid: 1,
+ tid: 1,
+ ...(data == null ? {} : {args: {data}}),
+ t: ms,
+ };
+}
+
+function traceOf(mainThread?: TimedTraceEvent[]): RenderingTrace {
+ return {
+ counts: {},
+ layout: 0,
+ paint: 0,
+ styleRecalc: 0,
+ prePaint: 0,
+ durationMs: 0,
+ longTasks: [],
+ stretchedTasks: [],
+ devtoolsTasks: [],
+ events: [],
+ window: {from: 0, to: 1000},
+ ...(mainThread == null ? {} : {mainThread}),
+ };
+}
+
+describe('layoutSources', () => {
+ // A timer writes a style; the next frame lays out.
+ const timer = [
+ at(100, 'RunTask', {durMs: 2}),
+ at(100.1, 'TimerFire'),
+ at(100.2, 'FunctionCall', {
+ data: {
+ functionName: 'move',
+ url: 'https://x/a.js',
+ lineNumber: 4,
+ columnNumber: 2,
+ },
+ }),
+ at(100.3, 'ScheduleStyleRecalculation'),
+ ];
+ const frame = [
+ at(116, 'RunTask', {durMs: 3}),
+ at(116.1, 'BeginMainThreadFrame'),
+ at(116.2, 'UpdateLayoutTree'),
+ at(116.3, 'InvalidateLayout'),
+ at(116.4, 'Layout'),
+ ];
+
+ it('names the task that ran the Layout and each invalidation before it', () => {
+ const sources = layoutSources(traceOf([...timer, ...frame]), 110, 120);
+ expect(sources).toEqual([
+ {
+ t: 116.4,
+ task: ['BeginMainThreadFrame', 'UpdateLayoutTree'],
+ invalidations: [
+ {
+ t: 100.3,
+ what: 'ScheduleStyleRecalculation',
+ task: ['TimerFire', 'FunctionCall[move a.js:4:2]'],
+ },
+ {
+ t: 116.3,
+ what: 'InvalidateLayout',
+ task: ['BeginMainThreadFrame', 'UpdateLayoutTree'],
+ },
+ ],
+ },
+ ]);
+ });
+
+ it('starts the invalidations after the previous Layout, and explains only the window', () => {
+ const earlier = [
+ at(50, 'RunTask', {durMs: 2}),
+ at(50.1, 'InvalidateLayout', {
+ data: {reason: 'Style changed', nodeName: 'DIV'},
+ }),
+ at(50.2, 'Layout'),
+ ];
+ const sources = layoutSources(
+ traceOf([...earlier, ...timer, ...frame]),
+ 110,
+ 120,
+ );
+ expect(sources.map(s => s.invalidations.map(i => i.t))).toEqual([
+ [100.3, 116.3],
+ ]);
+ expect(layoutSources(traceOf([...earlier]), 0, 60)).toEqual([
+ {
+ t: 50.2,
+ task: [],
+ invalidations: [
+ {t: 50.1, what: 'InvalidateLayout[Style changed DIV]', task: []},
+ ],
+ },
+ ]);
+ });
+
+ it('writes no step that ends in a line and a column, which reads as a stack frame', () => {
+ const steps = layoutSources(traceOf([...timer, ...frame]), 110, 120)
+ .flatMap(s => [...s.task, ...s.invalidations.flatMap(i => i.task)])
+ .filter(step => step.includes('a.js'));
+ expect(steps).toEqual(['FunctionCall[move a.js:4:2]']);
+ expect(steps.some(step => /:\d+:\d+\)?$/.test(step))).toBe(false);
+ });
+
+ it('fails by name when the trace kept no events', () => {
+ expect(() => layoutSources(traceOf(), 0, 1)).toThrow(
+ 'layoutSources: the trace kept no events',
+ );
+ });
+});
diff --git a/internal/interaction-harness/src/trace.ts b/internal/interaction-harness/src/trace.ts
index a77ee7d411..a343ece4b2 100644
--- a/internal/interaction-harness/src/trace.ts
+++ b/internal/interaction-harness/src/trace.ts
@@ -7,7 +7,8 @@
* @output `traceRendering` — counts of the main thread's rendering work
* (Layout, Paint, UpdateLayoutTree, PrePaint, …) between two marks — and
* `installLongTaskLog` / `readLongTasks`. `longTasksOf` gives each long task
- * its wall and thread time.
+ * its wall and thread time. `layoutSources` names what ran each counted
+ * Layout and what invalidated layout before it.
* @position The "no Layout/Paint during a transform/opacity animation" proof.
* A compositor animation costs the main thread nothing per frame; one that
* animates a layout property, or writes styles from JavaScript each frame,
@@ -116,6 +117,17 @@ export interface RenderingTrace {
readonly events: readonly RenderingEvent[];
/** The window, epoch ms on the page's clock. */
readonly window: {readonly from: number; readonly to: number};
+ /**
+ * Every main-thread trace event inside the window, in time order, when the
+ * trace keeps them (`keepEvents`). A proof reads them only to explain a
+ * failure.
+ */
+ readonly mainThread?: readonly TimedTraceEvent[];
+}
+
+/** A main-thread trace event with its epoch-ms time. */
+export interface TimedTraceEvent extends TraceEvent {
+ readonly t: number;
}
/** Counts rendering events by name inside `[from, to]` (epoch ms). */
@@ -133,6 +145,117 @@ export function countBetween(
return counts;
}
+/** What ran a counted Layout, and what invalidated layout before it. */
+export interface LayoutSource {
+ /** The Layout's time, epoch ms. */
+ readonly t: number;
+ /** The task that ran the Layout: its dispatches and calls, in order. */
+ readonly task: readonly string[];
+ /**
+ * Each layout or style invalidation since the previous Layout, with the
+ * task it ran in. The trace names the reason and the node only when it
+ * tracks invalidations.
+ */
+ readonly invalidations: ReadonlyArray<{
+ readonly t: number;
+ readonly what: string;
+ readonly task: readonly string[];
+ }>;
+}
+
+const TASK_STEPS = new Set([
+ ...PAGE_SCRIPT_EVENTS,
+ 'BeginMainThreadFrame',
+ 'EvaluateScript',
+ 'HitTest',
+ 'IntersectionObserverController::computeIntersections',
+ 'ParseHTML',
+ 'UpdateLayoutTree',
+ 'Layout',
+]);
+
+const INVALIDATIONS = new Set([
+ 'InvalidateLayout',
+ 'ScheduleStyleRecalculation',
+ 'LayoutInvalidationTracking',
+ 'StyleRecalcInvalidationTracking',
+]);
+
+/** One trace event as text: its name and what its data says about it. */
+function describeEvent(e: TraceEvent): string {
+ const data = (e.args?.data ?? {}) as Record<string, unknown>;
+ const text = (value: unknown) =>
+ typeof value === 'string' || typeof value === 'number'
+ ? String(value)
+ : null;
+ const url = text(data.url);
+ const parts = [
+ text(data.type),
+ text(data.functionName),
+ url == null
+ ? null
+ : `${url.split('/').pop()}:${text(data.lineNumber) ?? '?'}:${text(data.columnNumber) ?? '?'}`,
+ text(data.reason),
+ text(data.nodeName),
+ ].filter(part => part != null && part !== '');
+ // Square brackets: a message line that ends in `:line:column` or
+ // `:line:column)` reads as a stack frame to Playwright, which then reports
+ // that line as the failure's location.
+ return parts.length === 0 ? e.name : `${e.name}[${parts.join(' ')}]`;
+}
+
+/**
+ * Names the source of each Layout in `[from, to]` (epoch ms) from a trace that
+ * kept its events (`traceRendering(page, body, {keepEvents: true})`). For a
+ * Layout it gives the steps of the task that ran it. It also gives every
+ * invalidation since the previous Layout, with the steps of its own task.
+ */
+export function layoutSources(
+ trace: RenderingTrace,
+ from: number,
+ to: number,
+): LayoutSource[] {
+ const main = trace.mainThread;
+ if (main == null) {
+ throw new Error(
+ 'layoutSources: the trace kept no events; trace with {keepEvents: true}',
+ );
+ }
+ const tasks = main.filter(e => e.name === 'RunTask' && e.ph === 'X');
+ const stepsBefore = (e: TimedTraceEvent): string[] => {
+ const task = tasks.find(t => t.ts <= e.ts && t.ts + (t.dur ?? 0) >= e.ts);
+ if (task == null) {
+ return [];
+ }
+ return main
+ .filter(
+ x =>
+ x !== e && x.ts >= task.ts && x.ts <= e.ts && TASK_STEPS.has(x.name),
+ )
+ .map(describeEvent)
+ .slice(-8);
+ };
+ const layouts = main.filter(e => e.name === 'Layout');
+ return layouts
+ .filter(e => e.t >= from && e.t <= to)
+ .map(layout => {
+ const previous = layouts.filter(e => e.ts < layout.ts).at(-1);
+ return {
+ t: layout.t,
+ task: stepsBefore(layout),
+ invalidations: main
+ .filter(
+ e =>
+ INVALIDATIONS.has(e.name) &&
+ e.ts > (previous?.ts ?? -Infinity) &&
+ e.ts <= layout.ts,
+ )
+ .slice(-12)
+ .map(e => ({t: e.t, what: describeEvent(e), task: stepsBefore(e)})),
+ };
+ });
+}
+
export interface TraceEvent {
name: string;
cat: string;
@@ -162,6 +285,7 @@ export interface TraceEvent {
export async function traceRendering(
page: Page,
body: () => Promise<unknown>,
+ {keepEvents = false}: {keepEvents?: boolean} = {},
): Promise<RenderingTrace> {
const cdp: CDPSession = await page.context().newCDPSession(page);
const events: TraceEvent[] = [];
@@ -272,6 +396,14 @@ export async function traceRendering(
devtoolsTasks,
events: counted,
window: {from: fromEpoch, to: toEpoch},
+ ...(keepEvents
+ ? {
+ mainThread: events
+ .filter(e => onMain(e) && e.ph !== 'E')
+ .sort((a, b) => a.ts - b.ts)
+ .map(e => ({...e, t: toEpochMs(e.ts)})),
+ }
+ : {}),
};
}
diff --git a/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.ts b/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.ts
index ef993cab35..b7f4847c89 100644
--- a/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.ts
+++ b/packages/core/src/Layer/__tests__/LayerEntranceLayout.interaction.browser.spec.ts
@@ -8,7 +8,9 @@
* on a page with a callback on every frame. Chromium lays an anchored
* element out again each time its own style changes, so the entrance runs
* on the surface inside the layer. The surface is the layer's only child
- * and fills its box, so it scales about the same center
+ * and fills its box, so it scales about the same center. A failure names
+ * the task that ran each counted layout and each invalidation before it,
+ * and saves that entrance's trace
* @position Interaction proofs for layerAnimations.stylex.ts, run in
* Chromium, the engine with a rendering trace
*/
@@ -21,10 +23,13 @@ import {
} from '@astryxdesign/a11y-spec/playwright';
import {
countBetween,
+ layoutSources,
openStory,
traceRendering,
waitForRest,
withStorybook,
+ writeEvidence,
+ type RenderingTrace,
} from '@astryxdesign/interaction-harness';
const storybook = withStorybook(test);
@@ -41,6 +46,8 @@ const OPENS = 3;
interface EntranceWindow {
__entrance: {start: number; end: number};
+ // The page's events during an entrance, to explain a counted layout.
+ __events: {type: string; t: number; target: string; name: string}[];
}
interface EntranceRoute {
@@ -102,11 +109,63 @@ async function watchEntrances(page: Page): Promise<void> {
await page.evaluate(() => {
const w = window as unknown as EntranceWindow;
w.__entrance = {start: 0, end: 0};
+ w.__events = [];
const tick = () => requestAnimationFrame(tick);
requestAnimationFrame(tick);
const inLayer = (target: EventTarget | null) =>
target instanceof Element &&
target.closest('[data-layer-anchored]') != null;
+ // Names a target without a layout read.
+ const nameOf = (target: EventTarget | null) => {
+ if (!(target instanceof Element)) {
+ return target === window ? 'window' : 'document';
+ }
+ const role = target.getAttribute('role');
+ const layer = target.closest('[data-layer-anchored]');
+ const tag = `${target.tagName.toLowerCase()}${role == null ? '' : `[${role}]`}`;
+ if (layer == null) {
+ return `page ${tag}`;
+ }
+ if (target === layer) {
+ return 'layer';
+ }
+ return target === layer.firstElementChild ? 'surface' : `layer ${tag}`;
+ };
+ for (const type of [
+ 'animationstart',
+ 'animationend',
+ 'animationcancel',
+ 'transitionrun',
+ 'transitionend',
+ 'transitioncancel',
+ 'beforetoggle',
+ 'toggle',
+ 'focusin',
+ 'focusout',
+ 'pointerover',
+ 'scroll',
+ 'resize',
+ ]) {
+ addEventListener(
+ type,
+ event => {
+ w.__events.push({
+ type,
+ t: performance.timeOrigin + event.timeStamp,
+ target: nameOf(event.target),
+ name:
+ (event as AnimationEvent).animationName ??
+ (event as TransitionEvent).propertyName ??
+ (event as ToggleEvent).newState ??
+ '',
+ });
+ if (w.__events.length > 200) {
+ w.__events.shift();
+ }
+ },
+ true,
+ );
+ }
addEventListener(
'animationstart',
event => {
@@ -136,48 +195,105 @@ async function closeAll(page: Page): Promise<void> {
await expect(open).toHaveCount(0);
}
-// The rendering work inside one entrance's window.
+interface TracedEntrance {
+ readonly counts: Record<string, number>;
+ readonly start: number;
+ readonly end: number;
+ readonly trace: RenderingTrace;
+ readonly events: EntranceWindow['__events'];
+}
+
+// The rendering work inside one entrance's window. The trace keeps its
+// events, so a counted layout can be explained.
async function traceEntrance(
page: Page,
route: EntranceRoute,
-): Promise<Record<string, number>> {
+): Promise<TracedEntrance> {
await route.prepare?.(page);
await page.evaluate(() => {
- (window as unknown as EntranceWindow).__entrance = {start: 0, end: 0};
- });
- const trace = await traceRendering(page, async () => {
- await route.open(page);
- await expect(route.shown(page)).toBeVisible();
- await page.waitForFunction(
- () => (window as unknown as EntranceWindow).__entrance.end > 0,
- );
+ const w = window as unknown as EntranceWindow;
+ w.__entrance = {start: 0, end: 0};
+ w.__events = [];
});
- const {start, end} = await page.evaluate(
- () => (window as unknown as EntranceWindow).__entrance,
+ const trace = await traceRendering(
+ page,
+ async () => {
+ await route.open(page);
+ await expect(route.shown(page)).toBeVisible();
+ await page.waitForFunction(
+ () => (window as unknown as EntranceWindow).__entrance.end > 0,
+ );
+ },
+ {keepEvents: true},
);
+ const {
+ __entrance: {start, end},
+ __events: events,
+ } = await page.evaluate(() => {
+ const w = window as unknown as EntranceWindow;
+ return {__entrance: w.__entrance, __events: w.__events};
+ });
expect(start).toBeGreaterThan(0);
- return countBetween(trace, start, end);
+ return {counts: countBetween(trace, start, end), start, end, trace, events};
+}
+
+// Each counted layout of an entrance, with the task that ran it and the
+// invalidations before it. Times are ms from the entrance's start.
+function explainLayouts(entrance: TracedEntrance, open: number): string {
+ const {start, end, trace, events} = entrance;
+ const rel = (t: number) => `${(t - start).toFixed(1)} ms`;
+ const lines = [`Entrance ${open + 1} (${rel(end)} long):`];
+ for (const source of layoutSources(trace, start, end)) {
+ lines.push(` Layout at ${rel(source.t)}, in: ${source.task.join(' > ')}`);
+ for (const invalidation of source.invalidations) {
+ lines.push(
+ ` after ${invalidation.what} at ${rel(invalidation.t)}, in: ${invalidation.task.join(' > ')}`,
+ );
+ }
+ }
+ lines.push(
+ ` Page events: ${events
+ .filter(event => event.t >= start - 50 && event.t <= end)
+ .map(e => `${rel(e.t)} ${e.type} ${e.target} ${e.name}`.trim())
+ .join('; ')}`,
+ );
+ return lines.join('\n');
}
for (const route of routes.filter(route => !route.hasOwnTransition)) {
test(`${route.name}: the entrance runs no layout while it plays`, async ({
page,
browserName,
- }) => {
+ }, testInfo) => {
test.skip(browserName !== 'chromium', 'rendering traces are Chromium-only');
await openStory(page, storybook(), route.story);
await watchEntrances(page);
const layouts: number[] = [];
const restyles: number[] = [];
+ const explanations: string[] = [];
for (let open = 0; open < OPENS; open++) {
const during = await traceEntrance(page, route);
- layouts.push(during.Layout ?? 0);
- restyles.push(during.UpdateLayoutTree ?? 0);
+ layouts.push(during.counts.Layout ?? 0);
+ restyles.push(during.counts.UpdateLayoutTree ?? 0);
+ if ((during.counts.Layout ?? 0) > 0) {
+ explanations.push(explainLayouts(during, open));
+ await writeEvidence(
+ `layer-entrance-layout/${route.story}`,
+ {
+ [`entrance-${open + 1}.json`]: JSON.stringify({
+ window: {start: during.start, end: during.end},
+ events: during.events,
+ mainThread: during.trace.mainThread,
+ }),
+ },
+ testInfo,
+ );
+ }
await closeAll(page);
}
// The entrance played across frames: its element restyled on several.
expect(Math.min(...restyles)).toBeGreaterThanOrEqual(3);
- expect(layouts).toEqual(Array(OPENS).fill(0));
+ expect(layouts, explanations.join('\n')).toEqual(Array(OPENS).fill(0));
});
}