An open source design system that's fully customizable and agent ready
TypeScript
chore(harness): trackBrightness reads a colour channel per frame (#10377)
Christopher Chedeau75a9c1776478
diff --git a/internal/interaction-harness/README.md b/internal/interaction-harness/README.mdindex 6d8ea4f06e..3f16c3271d 100644--- a/internal/interaction-harness/README.md+++ b/internal/interaction-harness/README.md@@ -59,6 +59,7 @@ committed: a pull request links or attaches it.| `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), `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. |+| `brightness.ts` | `trackBrightness(page, frames, {x, y})`: a colour channel's mean in a square per frame, as a scalar on `box.x`, for a busy-window proof of a fade or a dim. || `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. || `curves.ts` | `holdAnimations`, `armHold`, `seekAnimations`, `sampleCurve` (presented transform / opacity at any t), `waitForAnimation`, `watchAnimations`, `waitForRest`, `releaseAnimations`, `releaseAnimationLog` (frees what the recorder kept, before a heap or listener count). |diff --git a/internal/interaction-harness/src/brightness.ts b/internal/interaction-harness/src/brightness.tsnew file mode 100644index 0000000000..a3e1880cc5--- /dev/null+++ b/internal/interaction-harness/src/brightness.ts@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file brightness.ts+ * @input Screencast frames (`startScreencast`) and a CSS-px point on screen+ * @output `trackBrightness`: one colour channel's mean in a square, per frame,+ * as a tracked value on `box.x`+ * @position Busy-window proofs of a fade or a dim read it, and judge the+ * series with `busyWindowProof` or `pooledBusyProof` on `axis: 'x'`.+ */++import type {Page} from '@playwright/test';++import type {CastFrame, TrackedFrame} from './frames';++/**+ * One colour channel's mean at a CSS-px point in each cast frame: a square of+ * `size` bitmap px, red by default. It shows what a fade or a dim paints+ * there. The value is a scalar on `box.x`: judge it with `axis: 'x'`. The+ * proof reads its step from the series' own changes. Put the square on a flat+ * part of the element, because JPEG noise on an edge reads as change. The+ * frames are decoded in a scratch page, as `trackMarker` does.+ */+export async function trackBrightness(+ page: Page,+ castFrames: readonly CastFrame[],+ {+ x,+ y,+ size = 16,+ channel = 'r',+ }: {x: number; y: number; size?: number; channel?: 'r' | 'g' | 'b'},+): Promise<TrackedFrame[]> {+ const offset = {r: 0, g: 1, b: 2}[channel];+ const scratch = await page.context().newPage();+ try {+ const values: number[] = [];+ for (let i = 0; i < castFrames.length; i += 12) {+ const batch = castFrames.slice(i, i + 12);+ values.push(+ ...(await scratch.evaluate(+ async ({items, px, py, side, at}) => {+ const out: number[] = [];+ for (const item of items) {+ const blob = await (+ await fetch(`data:image/${item.format};base64,${item.data}`)+ ).blob();+ const bitmap = await createImageBitmap(blob);+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);+ const context = canvas.getContext('2d');+ if (context == null) {+ throw new Error('no 2d context');+ }+ context.drawImage(bitmap, 0, 0);+ const scale = bitmap.width / item.viewportWidth;+ const {data} = context.getImageData(+ Math.round(px * scale),+ Math.round(py * scale),+ side,+ side,+ );+ let sum = 0;+ for (let o = at; o < data.length; o += 4) {+ sum += data[o];+ }+ out.push(sum / (data.length / 4));+ }+ return out;+ },+ {+ items: batch.map(f => ({+ data: f.data,+ format: f.format,+ viewportWidth: f.viewportWidth,+ })),+ px: x,+ py: y,+ side: size,+ at: offset,+ },+ )),+ );+ }+ return castFrames.map((f, i) => ({+ t: f.t,+ box: {x: values[i], y: 0, width: 1, height: 1},+ pixels: 1,+ }));+ } finally {+ await scratch.close();+ }+}diff --git a/internal/interaction-harness/src/harness.interaction.browser.spec.ts b/internal/interaction-harness/src/harness.interaction.browser.spec.tsindex ba634c6e02..9913a2c410 100644--- a/internal/interaction-harness/src/harness.interaction.browser.spec.ts+++ b/internal/interaction-harness/src/harness.interaction.browser.spec.ts@@ -53,7 +53,7 @@ import {test,type Page,} from '@astryxdesign/a11y-spec/playwright';-import type {CastFrame, TrackedFrame} from './frames';+import type {CastFrame} from './frames';import {advanceFrozenPage,ANSWER_SLACK_MS,@@ -108,6 +108,7 @@ import {thawTimers,timeline,touchDriver,+ trackBrightness,TouchPageStallError,touchStoryboard,traceRendering,@@ -159,73 +160,6 @@ const BUSY_FIXTURE = `<!doctype html><meta name=viewport content="width=device-w</style><div id=box></div>`;-/**- * The red channel at a CSS-px point in each cast frame (a 16 px square's mean),- * as a tracked value on x: what a backdrop's dim shows there. Decoded in a- * scratch page, as `trackMarker` does.- */-async function brightnessAt(- page: Page,- castFrames: readonly CastFrame[],- {x, y}: {x: number; y: number},-): Promise<TrackedFrame[]> {- const scratch = await page.context().newPage();- try {- const values: number[] = [];- for (let i = 0; i < castFrames.length; i += 12) {- const batch = castFrames.slice(i, i + 12);- values.push(- ...(await scratch.evaluate(- async ({items, px, py}) => {- const out: number[] = [];- for (const item of items) {- const blob = await (- await fetch(`data:image/${item.format};base64,${item.data}`)- ).blob();- const bitmap = await createImageBitmap(blob);- const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);- const context = canvas.getContext('2d');- if (context == null) {- throw new Error('no 2d context');- }- context.drawImage(bitmap, 0, 0);- const scale = bitmap.width / item.viewportWidth;- const {data} = context.getImageData(- Math.round(px * scale),- Math.round(py * scale),- 16,- 16,- );- let sum = 0;- for (let o = 0; o < data.length; o += 4) {- sum += data[o];- }- out.push(sum / (data.length / 4));- }- return out;- },- {- items: batch.map(f => ({- data: f.data,- format: f.format,- viewportWidth: f.viewportWidth,- })),- px: x,- py: y,- },- )),- );- }- return castFrames.map((f, i) => ({- t: f.t,- box: {x: values[i], y: 0, width: 1, height: 1},- pixels: 1,- }));- } finally {- await scratch.close();- }-}-async function busyFixture(page: Page) {await page.route('http://busy.test/', route =>route.fulfill({contentType: 'text/html', body: BUSY_FIXTURE}),@@ -1119,7 +1053,7 @@ test.describe('frame evidence', () => {const controlFrames = await trackMarker(page, castFrames, {rgb: CONTROL_RGB,});- const dim = await brightnessAt(page, castFrames, {x: 40, y: 600});+ const dim = await trackBrightness(page, castFrames, {x: 40, y: 600});const proof = busyWindowProof(dim, window, {axis: 'x',control: controlFrames,@@ -1127,6 +1061,44 @@ test.describe('frame evidence', () => {expect(proof.verdict.failures, proof.summary).toEqual([]);});+ test('trackBrightness reads the channel it is given, over a square of the size it is given', async ({+ page,+ }) => {+ const lastFrame = async (html: string) => {+ await page.setContent(html);+ const cast = await startScreencast(page);+ await page.waitForTimeout(200);+ const castFrames = (await cast.stop()).slice(-1);+ expect(castFrames).toHaveLength(1);+ return castFrames;+ };+ const read = async (+ castFrames: readonly CastFrame[],+ at: {x: number; y: number; size: number; channel?: 'r' | 'g' | 'b'},+ ) => (await trackBrightness(page, castFrames, at))[0].box?.x ?? Number.NaN;+ // A flat colour: each channel reads its own value, to within the cast's+ // compression.+ const flat = await lastFrame(+ '<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:rgb(10,200,30)}</style>',+ );+ for (const [channel, value] of [+ ['r', 10],+ ['g', 200],+ ['b', 30],+ ] as const) {+ expect(+ Math.abs((await read(flat, {x: 40, y: 40, size: 16, channel})) - value),+ ).toBeLessThan(6);+ }+ // A 16 px red block on black. A small square inside it reads the block.+ // A large one reads mostly the black around it, at any device scale.+ const block = await lastFrame(+ '<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><style>html,body{margin:0;height:100%;background:#000}#block{position:absolute;left:40px;top:40px;width:16px;height:16px;background:rgb(200,0,0)}</style><div id="block"></div>',+ );+ expect(await read(block, {x: 44, y: 44, size: 4})).toBeGreaterThan(150);+ expect(await read(block, {x: 44, y: 44, size: 128})).toBeLessThan(60);+ });+test("waitForAnimation and blockMainThread's during never count the control's own animation inside a dialog", async ({page,}) => {diff --git a/internal/interaction-harness/src/index.ts b/internal/interaction-harness/src/index.tsindex 6c6b32e7e5..b8e96a5557 100644--- a/internal/interaction-harness/src/index.ts+++ b/internal/interaction-harness/src/index.ts@@ -14,6 +14,7 @@* SYNC: When a module is added, export it here and describe it in README.md.*/+export * from './brightness';export * from './busy';export * from './curves';export * from './frames';