An open source design system that's fully customizable and agent ready
TypeScript
test(core): the glide keeps advancing through a blocked main thread (#10229)
Christopher Chedeaub07a832284d7
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.mdindex 2329aa5654..42f9d76a13 100644--- a/docs/specs/AST-094-touch-presentations/spec.md+++ b/docs/specs/AST-094-touch-presentations/spec.md@@ -19,6 +19,10 @@ affects_architecture:affects_families: [family:buttons]affects_contributing: []affects_consumer_docs: []+verified_by:+ [+ packages/core/src/motion/__tests__/animatedLayoutBusy.interaction.browser.spec.ts,+ ]---# Touch presentations feel native system spec@@ -1025,6 +1029,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li| FR4 | Role unit tests over every touch motion | each role at its table value; a theme that writes `motion` | a literal played in place of a role (other than a measured gesture-driven exit spring its component's motion table lists with its platform source), a value that differs from the table at `tempo` 1 and `'standard'`, or a theme that changes a role other than through its motion knobs fails || FR4 | Role unit tests over gesture-driven exits | a gesture-driven exit (a release that closes or dismisses) playing a spring measured from the platform reference with no named role; the same unnamed spring played by a program-started motion or by a gesture-driven motion that is not an exit, such as a settle | a gesture-driven exit playing a measured table spring passes; a program-started motion, or a non-exit gesture motion, playing an unnamed spring fails || FR5 | Browser proof: an animation keeps advancing frame by frame through a 1 s main-thread block, with no layout or paint per frame | Chromium phone emulation; WebKit | a script-driven or layout-animating implementation freezes or lays out |+| FR5 glide | Browser proof: the animated-layout glide keeps moving through a 700 ms main-thread block, on every frame a compositor control moves | the content after a Collapsible, a TreeList branch and a Table row; verified in Chromium; WebKit by an iOS Simulator spot-check (38/39 frames), not an automated run (evidence gap) | a glide stepped from the main thread freezes || FR6 | Unit and browser tests catching an animation mid-flight and retargeting it | catch at peak velocity; retarget with a new spring; a retarget before the browser reports the call's start | a layout read, a jump, or a lost velocity fails || FR6 pager | Unit and browser tests of a pager's settle start | releases just under and over 225 pt/s; a catch mid-settle; a programmatic page change mid-settle | a release under the floor whose settle starts moving, a release over it whose settle starts from rest, a catch that loses the on-screen velocity, or a programmatic page change mid-settle that starts from rest fails; a page change during a drag starts from rest || FR6 starved | Switch frame proofs on a starved main thread (4 workers on 2 cores); a unit test of a retarget on a settle tail | a second tap mid-travel, with frames read late or its lift handled 100 ms late; a first frame committed late; a retarget once the thumb is still | a jump out of a thumb that is still fails; a mid-travel step within the browser's commit delay is the known limit |diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex efbc2e580f..6d8ea4f06e 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -57,7 +57,7 @@ committed: a pull request links or attaches it.| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `scripts.ts` | Touch scripts as data: `tap`, `drag` (hold, rest), `flick` (exact final-move speed, velocity profiles), `holdThenDrag`, `pinch`, `rotate`, `path`, `merge` (a second finger mid-gesture), `releaseVelocity`, `toTouchEvents`. || `touch.ts` | `touchDriver(page).play(script)`: the script as real engine input. `installInputLog` / `readInputLog`: what the page received. |-| `frames.ts` | `startScreencast` (timestamped composited frames), `markElement` (a marker chip or outline), `trackMarker` (marker box per frame), `sampleRects` (per-rAF rects), `frameStats`. |+| `frames.ts` | `startScreencast` (timestamped composited frames), `markElement` (a marker chip or outline), `trackMarker` (marker box per frame), `trackMarkers` (several colors from one decode of each frame), `sampleRects` (per-rAF rects), `frameStats`. || `busy.ts` | `blockMainThread(page, ms)`, which returns the window it held and the span its loop measured, and `busyWindowProof(tracked, window)`: frames presented, frames that moved, longest stall, a verdict; `presented` adds the compositor's own frames. || `webInput.ts` | `webInputDriver(page)`: `wheel({x, y, dx, dy, ctrl})` and `pen(points)` as real engine input, for proofs across pointers (`spec:AST-100` FR4); `wheel` resolves once the page has the step; read back through the input log. || `trace.ts` | `traceRendering(page, body)`: main-thread counts of UpdateLayoutTree / Layout / PrePaint / Paint / Layerize / UpdateLayer / ScrollLayer / HitTest, `countBetween`, long tasks; `installLongTaskLog` / `readLongTasks`; `startCompositorTrace`: when the compositor presents. |@@ -244,7 +244,11 @@ a dialog they still wait for the backdrop's. Track a top-layer control fromthe same screencast with `trackControl(page, frames)` (`trackMarker` with`CONTROL_RGB`, searching only the top strip it crosses). A control mounted`within` a dialog moves with it, so track that one with `trackMarker(page,-frames, {rgb: CONTROL_RGB})`. Pass either as `control`: the component passes when it moved on every frame the control+frames, {rgb: CONTROL_RGB})`, or track the marker and the control together+with `trackMarkers(page, frames, {colors: [MARKER_RGB, CONTROL_RGB]})`, which+decodes each frame once. A proof reads frames up to+`BUSY_PROOF_LOOKAROUND_MS` (250 ms) around its judged part, so a spec may+decode only those. Pass either as `control`: the component passes when it moved on every frame the controlmoved and its longest stall is no longer than the control's. Both are read fromthe same screencast frames, so a compositor animation misses none. A window inwhich the control moved on fewer than four frames fails, since the machinediff --git a/internal/interaction-harness/src/busy.ts b/internal/interaction-harness/src/busy.tsindex 55f3f423a4..c6c0f72734 100644--- a/internal/interaction-harness/src/busy.ts+++ b/internal/interaction-harness/src/busy.ts@@ -11,6 +11,8 @@* read from its frames, `pooledBusyProof`, which judges several short* blocks as one, and `BusyWindowTooLateError`, for a block that began* after the motion it was meant to catch had ended.+ * `BUSY_PROOF_LOOKAROUND_MS` is how far around its judged part a proof+ * reads frames.* `trackControl` and `controlClock` read the control's box and its own* clock from the screencast, a second control's too (`ahead`).* @position The busy-main-thread proof: an animation that runs on the@@ -864,6 +866,13 @@ function motionStepPx(values: readonly number[]): number {* `maxMedianFrameMs`, when given, still applies; `minMovedFraction` and the* absolute stall, frame and motion limits do not.*/+/**+ * How far around its judged part a busy proof reads frames, ms: the rest+ * before it and the frame cadence on both sides. A proof that decodes only+ * part of a cast keeps the frames this far after the window.+ */+export const BUSY_PROOF_LOOKAROUND_MS = 250;+export function busyWindowProof(tracked: readonly TrackedFrame[],window: BusyWindow,@@ -1047,7 +1056,7 @@ export function busyWindowProof(const prior = tracked.filter(f => f.box != null && f.t < inner.from);let leadFrom = 0;prior.forEach((f, i) => {- if (f.t < inner.from - 250) {+ if (f.t < inner.from - BUSY_PROOF_LOOKAROUND_MS) {leadFrom = i;}});@@ -1104,7 +1113,11 @@ export function busyWindowProof(const changes = inWindow.filter(t => t > judged.from || onScreenFrom == null);const edges = [judged.from, ...changes, judged.to];const around = tracked- .filter(f => f.t >= inner.from - 250 && f.t <= inner.to + 250)+ .filter(+ f =>+ f.t >= inner.from - BUSY_PROOF_LOOKAROUND_MS &&+ f.t <= inner.to + BUSY_PROOF_LOOKAROUND_MS,+ ).map(f => f.t);const intervals = around.slice(1)@@ -1121,7 +1134,11 @@ export function busyWindowProof(// The compositor's own frames, when recorded: its interval, from the frames// around the judged part.const draws = [...(presented ?? [])]- .filter(t => t >= judged.from - 250 && t <= judged.to + 250)+ .filter(+ t =>+ t >= judged.from - BUSY_PROOF_LOOKAROUND_MS &&+ t <= judged.to + BUSY_PROOF_LOOKAROUND_MS,+ ).sort((a, b) => a - b);const drawIntervals = draws.slice(1)diff --git a/internal/interaction-harness/src/frames.ts b/internal/interaction-harness/src/frames.tsindex bf61f337f8..2569f02ef0 100644--- a/internal/interaction-harness/src/frames.ts+++ b/internal/interaction-harness/src/frames.ts@@ -7,7 +7,8 @@* `Screencast` domain)* @output `startScreencast` (timestamped composited frames), `markElement`* (a marker outline the frames can find), `trackMarker` (per-frame marker- * box and the cast's position step), `colorBlockPx` (a frame's color+ * box and the cast's position step), `trackMarkers` (several colors from+ * one decode of each frame), `colorBlockPx` (a frame's color* resolution), `sampleRects` (per-rAF rect sampling), `frameStats`.* @position Frame evidence for motion proofs. The screencast is captured off* the page's main thread, from what the compositor presents, so it keeps@@ -369,18 +370,51 @@ export async function trackMarker(region?: Box;} = {},): Promise<TrackedFrame[]> {- const isDefaultMarker = rgb.every((value, i) => value === MARKER_RGB[i]);+ const [tracked] = await trackMarkers(page, frames, {+ colors: [rgb],+ tolerance,+ region,+ });+ return tracked;+}++/**+ * `trackMarker` for several colors at once: each frame is decoded once and+ * searched for every color, so a proof that tracks a marker and a control+ * decodes each frame once. Returns one track per color, in order.+ */+export async function trackMarkers(+ page: Page,+ frames: readonly CastFrame[],+ {+ colors,+ tolerance = 40,+ region,+ }: {+ colors: readonly (readonly [number, number, number])[];+ tolerance?: number;+ region?: Box;+ },+): Promise<TrackedFrame[][]> {+ const isDefaultMarker = colors.map(rgb =>+ rgb.every((value, i) => value === MARKER_RGB[i]),+ );const scratch = await page.context().newPage();try {- const out: TrackedFrame[] = [];+ const out: TrackedFrame[][] = colors.map(() => []);// Batches keep each evaluate payload moderate.for (let i = 0; i < frames.length; i += 12) {const batch = frames.slice(i, i + 12);- const boxes = await scratch.evaluate(- async ({batch: items, color, tol, area}) => {- const results: {- box: {x: number; y: number; width: number; height: number} | null;- pixels: number;+ const results = await scratch.evaluate(+ async ({batch: items, palette, tol, area}) => {+ const found: {+ boxes: ({+ x: number;+ y: number;+ width: number;+ height: number;+ } | null)[];+ pixels: number[];scale: number;}[] = [];for (const item of items) {@@ -417,50 +451,54 @@ export async function trackMarker(right - left,bottom - top,);- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;- let pixels = 0;+ const minX = palette.map(() => Infinity);+ const minY = palette.map(() => Infinity);+ const maxX = palette.map(() => -Infinity);+ const maxY = palette.map(() => -Infinity);+ const pixels = palette.map(() => 0);for (let y = 0; y < height; y += 1) {for (let x = 0; x < width; x += 1) {const o = (y * width + x) * 4;- if (- Math.abs(data[o] - color[0]) <= tol &&- Math.abs(data[o + 1] - color[1]) <= tol &&- Math.abs(data[o + 2] - color[2]) <= tol- ) {- pixels += 1;- if (x < minX) {- minX = x;- }- if (x > maxX) {- maxX = x;- }- if (y < minY) {- minY = y;- }- if (y > maxY) {- maxY = y;+ for (let c = 0; c < palette.length; c += 1) {+ const color = palette[c];+ if (+ Math.abs(data[o] - color[0]) <= tol &&+ Math.abs(data[o + 1] - color[1]) <= tol &&+ Math.abs(data[o + 2] - color[2]) <= tol+ ) {+ pixels[c] += 1;+ if (x < minX[c]) {+ minX[c] = x;+ }+ if (x > maxX[c]) {+ maxX[c] = x;+ }+ if (y < minY[c]) {+ minY[c] = y;+ }+ if (y > maxY[c]) {+ maxY[c] = y;+ }}}}}- results.push({- box:- pixels === 0+ found.push({+ boxes: palette.map((_, c) =>+ pixels[c] === 0? null: {- x: (left + minX) / scale,- y: (top + minY) / scale,- width: (maxX - minX + 1) / scale,- height: (maxY - minY + 1) / scale,+ x: (left + minX[c]) / scale,+ y: (top + minY[c]) / scale,+ width: (maxX[c] - minX[c] + 1) / scale,+ height: (maxY[c] - minY[c] + 1) / scale,},+ ),pixels,scale,});}- return results;+ return found;},{batch: batch.map(f => ({@@ -468,22 +506,30 @@ export async function trackMarker(format: f.format,viewportWidth: f.viewportWidth,})),- color: [...rgb],+ palette: colors.map(rgb => [...rgb]),tol: tolerance,area: region ?? null,},);- boxes.forEach((result, k) => {- if (!isDefaultMarker) {- out.push({t: batch[k].t, box: result.box, pixels: result.pixels});- return;- }- const block = colorBlockPx(batch[k].data, batch[k].format);- out.push({- t: batch[k].t,- box: result.box,- pixels: result.pixels,- step: {x: block.x / result.scale, y: block.y / result.scale},+ results.forEach((result, k) => {+ const block = isDefaultMarker.some(Boolean)+ ? colorBlockPx(batch[k].data, batch[k].format)+ : null;+ colors.forEach((_, c) => {+ out[c].push(+ isDefaultMarker[c] && block != null+ ? {+ t: batch[k].t,+ box: result.boxes[c],+ pixels: result.pixels[c],+ step: {x: block.x / result.scale, y: block.y / result.scale},+ }+ : {+ t: batch[k].t,+ box: result.boxes[c],+ pixels: result.pixels[c],+ },+ );});});}diff --git a/packages/core/src/motion/__tests__/animatedLayoutBusy.interaction.browser.spec.ts b/packages/core/src/motion/__tests__/animatedLayoutBusy.interaction.browser.spec.tsnew file mode 100644index 0000000000..4185f1b5f4--- /dev/null+++ b/packages/core/src/motion/__tests__/animatedLayoutBusy.interaction.browser.spec.ts@@ -0,0 +1,404 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file animatedLayoutBusy.interaction.browser.spec.ts+ * @input The built Storybook's `Core/Animated layout` and Table row+ * expansion stories, real clicks, and the interaction harness's+ * screencast, compositor control and main-thread block+ * @output Proof that the animated-layout glide runs on the compositor.+ * While the page's main thread is blocked for 700 ms, three followers keep+ * moving with the harness's compositor control. They are the content after+ * a Collapsible, after a TreeList branch and after a Table row. The+ * judgment reads the block while the glide's keyframes move a follower by+ * a cast step or more per frame. Chromium only: Linux WebKit starts the+ * glide on its compositor late+ * @position Browser proof for animatedLayout.ts and its adopters, run by+ * `pnpm test:interaction`; the module's own proofs are+ * animatedLayout.interaction.browser.spec.ts+ */++import {+ type BlockedWindow,+ BUSY_PROOF_LOOKAROUND_MS,+ busyWindowProof,+ castStep,+ CONTROL_RGB,+ MARKER_RGB,+ markElement,+ startBusyControl,+ startScreencast,+ trackMarkers,+ writeEvidence,+} from '@astryxdesign/interaction-harness';+import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++// Linux WebKit hands the glide to its compositor late. Nothing moves for the+// first 30 to 100 ms of the block, so too little of the curve is left to judge.+// Apple's WebKit (the iOS 26.2 Simulator) moves on every frame from the start.+test.skip(+ ({browserName}) => browserName === 'webkit',+ 'Linux WebKit starts the glide on its compositor 30\u2013100 ms late; Apple\u2019s WebKit does not',+);++let storybook: StaticServer | undefined;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++/** How long the page's main thread is blocked, ms. */+const BLOCK_MS = 700;++/**+ * The glide's length here, ms. `--duration-medium-min` and `--duration-medium`+ * are both set to it, whichever the module plays. It is longer than the+ * theme's, so the judged part spans about 20 frames. The length changes+ * nothing the proof judges.+ */+const GLIDE_MS = 1000;++/** The fewest frame intervals the judged part of the block must span. */+const MIN_JUDGED_FRAMES = 8;++/** One frame at 60 Hz, ms. */+const FRAME_MS = 1000 / 60;++/** One translate animation that carries the follower, as the page read it. */+interface GlideRead {+ /** Each keyframe's offset and translate on the judged axis, px. */+ frames: [number, number][];+ durationMs: number;+ delayMs: number;+ /** The animation's own time, ms, at `at`. */+ local: number;+ /** Epoch ms on the page clock when `local` was read. */+ at: number;+}++/** Loads a story and waits for its first render, its fonts and two frames. */+async function openStory(page: Page, story: string): Promise<void> {+ await page.goto(+ `${storybook?.origin ?? ''}/iframe.html?id=${story}&viewMode=story`,+ );+ await page+ .locator('#storybook-root > *')+ .first()+ .waitFor({state: 'attached'});+ await page.addStyleTag({+ content: `* { --duration-medium-min: ${GLIDE_MS}ms !important; --duration-medium: ${GLIDE_MS}ms !important; }`,+ });+ await page.evaluate(async () => {+ await document.fonts.ready;+ await new Promise<void>(resolve => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ });+ });+}++/**+ * Clicks `trigger`, and the page blocks its own main thread for BLOCK_MS from+ * a task queued in the first frame after the click. The glide starts in the+ * click's own task, so it is under way when the block starts, however the+ * glide is driven. A round trip from the test could miss most of it. Just+ * before the block, the page reads the translate animations that carry+ * `follower`, for the judgment's expected positions.+ */+async function clickThenBlock(+ page: Page,+ trigger: Locator,+ follower: Locator,+ axis: 'x' | 'y',+): Promise<{busy: BlockedWindow; glides: GlideRead[]}> {+ const handle = await follower.elementHandle();+ await trigger.evaluate(+ (element, {duration, carried, along}) => {+ const offsetOf = (value: unknown) => {+ const match = /^(-?[\d.e+-]+)px(?:\s+(-?[\d.e+-]+)px)?/.exec(+ String(value),+ );+ if (match == null) {+ return 0;+ }+ return along === 'x' ? Number(match[1]) : Number(match[2] ?? 0);+ };+ element.addEventListener(+ 'click',+ () => {+ requestAnimationFrame(() => {+ const glides: GlideRead[] = [];+ for (+ let node: Element | null = carried;+ node != null;+ node = node.parentElement+ ) {+ for (const animation of node.getAnimations()) {+ const effect = animation.effect as KeyframeEffect;+ const frames = effect+ .getKeyframes()+ .filter(frame => typeof frame.translate === 'string');+ if (frames.length < 2) {+ continue;+ }+ glides.push({+ frames: frames.map((frame): [number, number] => [+ frame.computedOffset,+ offsetOf(frame.translate),+ ]),+ durationMs: Number(effect.getComputedTiming().duration),+ delayMs: effect.getTiming().delay ?? 0,+ local: Number(animation.currentTime ?? 0),+ at: performance.timeOrigin + performance.now(),+ });+ }+ }+ setTimeout(() => {+ const from = performance.now();+ let now = from;+ while (now - from < duration) {+ now = performance.now();+ }+ (window as unknown as {busy: unknown}).busy = {+ busy: {+ from: performance.timeOrigin + from,+ to: performance.timeOrigin + now,+ spanMs: now - from,+ },+ glides,+ };+ }, 0);+ });+ },+ {capture: true, once: true},+ );+ },+ {duration: BLOCK_MS, carried: handle, along: axis},+ );+ await trigger.click();+ const signal = await page.waitForFunction(+ () =>+ (window as unknown as {busy?: {busy: BlockedWindow; glides: GlideRead[]}})+ .busy,+ undefined,+ {polling: 50, timeout: 0},+ );+ return (await signal.jsonValue()) as {+ busy: BlockedWindow;+ glides: GlideRead[];+ };+}++/**+ * The follower's translate at epoch ms `t`, from the glides' own keyframes,+ * each running at the page's pace from where the page read it.+ */+function expectedOffset(glides: ReadonlyArray<GlideRead>, t: number): number {+ let sum = 0;+ for (const glide of glides) {+ const time = glide.local + (t - glide.at) - glide.delayMs;+ const offset = Math.min(1, Math.max(0, time / glide.durationMs));+ const after = glide.frames.findIndex(([at]) => at >= offset);+ if (after <= 0) {+ sum += glide.frames[Math.max(0, after)][1];+ continue;+ }+ const [o0, y0] = glide.frames[after - 1];+ const [o1, y1] = glide.frames[after];+ sum += y0 + ((y1 - y0) * (offset - o0)) / Math.max(1e-9, o1 - o0);+ }+ return sum;+}++/**+ * Marks `follower`, clicks `trigger` with the main thread blocked across the+ * glide, and judges the follower's frames against the compositor control's.+ * The judgment stops where the glide's own keyframes move the follower by+ * less than one step of the screencast per frame. That step is 1 px in+ * Chromium's cast and 2 px in WebKit's. An easing tail moves under what the+ * cast can show there.+ */+async function busyGlide(+ page: Page,+ name: string,+ {+ trigger,+ follower,+ axis = 'y',+ }: {trigger: Locator; follower: Locator; axis?: 'x' | 'y'},+) {+ await markElement(follower);+ // Before the glide, so the control is on the compositor first.+ await startBusyControl(page);+ const cast = await startScreencast(page);+ const {busy, glides} = await clickThenBlock(page, trigger, follower, axis);+ // Until every animation but the control's has ended.+ await expect+ .poll(async () =>+ page.evaluate(+ () =>+ document+ .getAnimations()+ .filter(+ a =>+ !(+ (a.effect as KeyframeEffect | null)?.target?.closest(+ '[data-harness-control]',+ ) ?? false+ ),+ ).length,+ ),+ )+ .toBe(0);+ // Where the marker rests, read from the page. A glide frozen through the+ // block stays far from it, and a frame after the block can still be stale.+ const settledAt = await follower.evaluate((el, along) => {+ const chip = el.querySelector('[data-harness-marker-chip]');+ if (chip == null) {+ throw new Error('the follower lost its marker chip');+ }+ const box = chip.getBoundingClientRect();+ return along === 'x' ? box.x : box.y;+ }, axis);+ const frames = await cast.stop();+ // The cast's step, from one frame in the block.+ const [probe] = await trackMarkers(+ page,+ [frames.find(f => f.t >= busy.from) ?? frames[frames.length - 1]],+ {colors: [MARKER_RGB]},+ );+ const step = castStep(probe, axis);+ // Where the glide's keyframes first move the follower by less than a cast+ // step in a frame, from the block's start on.+ let readable = busy.from;+ while (+ readable < busy.to &&+ Math.abs(+ expectedOffset(glides, readable + FRAME_MS) -+ expectedOffset(glides, readable),+ ) >= step+ ) {+ readable += 1;+ }+ // The part of the block the judgment reads ends there.+ const judgedWindow = {...busy, to: Math.min(busy.to, readable)};+ // Only the frames the proof reads are decoded, each once for both colors.+ // On a loaded machine every decode counts.+ const [tracked, control] = await trackMarkers(+ page,+ frames.filter(f => f.t <= judgedWindow.to + BUSY_PROOF_LOOKAROUND_MS),+ {colors: [MARKER_RGB, CONTROL_RGB]},+ );+ const proof = busyWindowProof(tracked, judgedWindow, {+ axis,+ settledWithinSteps: 2,+ settledAt,+ minJudgedFrames: MIN_JUDGED_FRAMES,+ control,+ });+ const at = (box: (typeof tracked)[number]['box']) =>+ box == null ? null : axis === 'x' ? box.x : box.y;+ await writeEvidence(+ `busy-main-thread/animated-layout-${name}`,+ {+ [`${test.info().project.name}.json`]: JSON.stringify(+ {+ busy,+ step,+ settledAt,+ readableUntil: +(readable - busy.from).toFixed(1),+ glides,+ proof,+ frames: tracked.map((f, i) => ({+ t: +(f.t - busy.from).toFixed(1),+ at: at(f.box),+ control: control[i].box?.x ?? null,+ })),+ },+ null,+ 1,+ ),+ },+ test.info(),+ );+ const summary = `judged until +${(readable - busy.from).toFixed(0)} ms (${step} px cast step): ${proof.summary}`;+ test+ .info()+ .annotations.push({type: 'busy-main-thread', description: summary});+ return {busy, proof, summary, glides, readableMs: readable - busy.from};+}++/** Marks the app div whose text starts with `text` for a test to find. */+async function markAppDiv(page: Page, text: string): Promise<Locator> {+ await page.evaluate(t => {+ const element = [...document.querySelectorAll('div')].find(el =>+ el.firstChild?.textContent?.trim().startsWith(t),+ );+ element?.setAttribute('data-test-id', 'follower');+ }, text);+ return page.locator('[data-test-id="follower"]');+}++function expectKeptAdvancing(run: Awaited<ReturnType<typeof busyGlide>>) {+ expect(run.busy.spanMs).toBeGreaterThanOrEqual(BLOCK_MS);+ expect(run.glides.length, 'a glide carries the follower').toBeGreaterThan(0);+ expect(run.proof.verdict.failures, run.summary).toEqual([]);+ expect(run.proof.monotonic, run.summary).toBe(true);+}++test.describe('spec:AST-094 FR5: the shared glide keeps advancing through a blocked main thread', () => {+ test('the content after a Collapsible keeps moving on the frames the compositor control moves', async ({+ page,+ }) => {+ await openStory(page, 'core-animated-layout--animated-layout');+ const follower = await markAppDiv(page, 'A plain app div');+ expectKeptAdvancing(+ await busyGlide(page, 'collapsible', {+ trigger: page.getByRole('button', {name: 'Shipping details'}),+ follower,+ }),+ );+ });++ test('the rows after a TreeList branch keep moving on the frames the compositor control moves', async ({+ page,+ }) => {+ await openStory(page, 'core-animated-layout--animated-layout');+ expectKeptAdvancing(+ await busyGlide(page, 'treelist', {+ trigger: page.locator('[data-tree-id="docs"] [data-tree-toggle]'),+ follower: page.locator('[data-tree-id="notes"]'),+ }),+ );+ });++ test('the rows after a Table row keep moving on the frames the compositor control moves', async ({+ page,+ }) => {+ await openStory(page, 'core-tablerowexpansion--gliding-rows');+ // A row takes no child, so its first cell, which rides its glide, carries+ // the marker.+ expectKeptAdvancing(+ await busyGlide(page, 'table-row', {+ trigger: page.locator('[data-expansion-toggle]').first(),+ follower: page+ .locator('tr[data-expansion-key]')+ .nth(1)+ .locator('td')+ .first(),+ }),+ );+ });+});