diff --git a/packages/cli/src/commands/blank-span.browser.js b/packages/cli/src/commands/blank-span.browser.js index e1bd0d690ea..f322d1435f1 100644 --- a/packages/cli/src/commands/blank-span.browser.js +++ b/packages/cli/src/commands/blank-span.browser.js @@ -1,8 +1,7 @@ -// blank_span's page half (utils/blankSpan.ts): does a frame show only the bare stage, by motion-signature's framesDiffer. +// blank_span's page half (utils/blankSpan.ts): the stage's own colour while nothing on it renders, else null. (function () { const CONTENT_TAGS = new Set(["IMG", "VIDEO", "CANVAS", "SVG", "IFRAME", "OBJECT", "EMBED"]); const RENDERED_OPTIONS = { opacityProperty: true, visibilityProperty: true }; - const PNG_PREFIX = "data:image/png;base64,"; // An `rgb()` or `rgba()` colour's alpha; null for any other notation, which is never read as transparent. function alphaOf(color) { @@ -49,23 +48,19 @@ ); } - async function stageFrame(color, png) { - const image = new Image(); - image.src = PNG_PREFIX + png; - await image.decode(); + // Any CSS colour notation, as the canvas paints it. + function painted(color) { const canvas = document.createElement("canvas"); - canvas.width = image.naturalWidth; - canvas.height = image.naturalHeight; + canvas.width = canvas.height = 1; const context = canvas.getContext("2d"); context.fillStyle = color; - context.fillRect(0, 0, canvas.width, canvas.height); - return canvas.toDataURL("image/png").slice(PNG_PREFIX.length); + context.fillRect(0, 0, 1, 1); + return Array.from(context.getImageData(0, 0, 1, 1).data); } - window.__hyperframesStageIsEmpty = async function stageIsEmpty(png) { + window.__hyperframesEmptyStageColor = function emptyStageColor() { const root = window.__hyperframesMotionSignature.compositionRoot(); const color = stageColor(root); - if (color === null || rendersAnything(root)) return false; - return !(await window.__hyperframesFramesDiffer(await stageFrame(color, png), png)); + return color === null || rendersAnything(root) ? null : painted(color); }; })(); diff --git a/packages/cli/src/commands/check.test.ts b/packages/cli/src/commands/check.test.ts index 75d25b10de2..8ee02a93fcd 100644 --- a/packages/cli/src/commands/check.test.ts +++ b/packages/cli/src/commands/check.test.ts @@ -3,7 +3,6 @@ import { runCommand } from "citty"; import { mkdirSync, mkdtempSync, - readFileSync, rmSync, statSync, symlinkSync, @@ -269,10 +268,6 @@ function fixtureRect(left: number, top: number, width: number, height: number): return { left, top, right: left + width, bottom: top + height, width, height }; } -function checkBrowserSource(): string { - return readFileSync(new URL("../utils/checkBrowser.ts", import.meta.url), "utf8"); -} - async function gateCandidates( time: number, request: { text: boolean; media: boolean; tolerance: number }, @@ -4392,20 +4387,6 @@ describe("check report telemetry", () => { }); }); -describe("contrast candidate round-trip", () => { - it("passes the browser script's raw candidates back to finish, never the normalized copies", () => { - const source = checkBrowserSource(); - - // __contrastAuditFinish samples pixels via the page script's own bbox - // shape ({x, y, w, h}); sending the Node-normalized candidate - // ({width, height}) makes every sample rect NaN and the audit silently - // reports zero checked elements. The raw object must round-trip verbatim. - expect(source).toMatch(/prepared\.map\(\(entry\) => entry\.raw\)/); - expect(source).toMatch(/raw: unknown;/); - expect(source).not.toMatch(/prepared\.map\(\(entry\) => entry\.candidate\)/); - }); -}); - describe("dense motion-overlap re-sampling", () => { // Collision lives inside (3.5, 4.5), a gap the sparse base grid seeks past; only the 8fps dense pass observes it. const inBetweenGridWindow = (time: number): boolean => time >= 3.6 && time <= 4.4; diff --git a/packages/cli/src/commands/contrast-audit.browser.js b/packages/cli/src/commands/contrast-audit.browser.js index fa51384d506..a80b664e765 100644 --- a/packages/cli/src/commands/contrast-audit.browser.js +++ b/packages/cli/src/commands/contrast-audit.browser.js @@ -1,13 +1,10 @@ // Browser-side WCAG contrast audit, injected as a raw string so esbuild can't mangle it. // __contrastAuditPrepare() hides each text element's own paint (layout-neutral) and returns candidates; // the caller takes one screenshot, full frame or clipped to the candidates (collectContrast in checkBrowser.ts); -// __contrastAuditFinish(png, time, candidates, region) restores paint first, then samples inside each box. +// __contrastAuditRestoreIfPending() restores the paint, and contrast-measure.ts reads the shot in Node. // Sampling inside the box reads the exact pixels behind the glyphs; a ring outside the text misreads // neighbouring panels, rounded pills, blurred glass and partial decorations. -// __contrastAuditRestoreIfPending() restores hidden paint if the screenshot or finish() throws. - -// The "which rect to sample" decision is mirrored and unit-tested in contrast-sample.ts. /* eslint-disable */ window.__contrastAuditPrepare = function () { @@ -513,167 +510,7 @@ function __contrastAuditRestoreAll() { window.__contrastAuditRestores = null; } -// Safety net for the caller: if the screenshot or finish() call throws -// between prepare() and finish(), call this to restore any still-hidden -// paint so the next sample in the loop isn't auditing a page with stale -// invisible text. No-op if finish() already ran normally. +// Called right after the screenshot, and again if anything threw before that: a no-op once restored. window.__contrastAuditRestoreIfPending = function () { __contrastAuditRestoreAll(); }; - -window.__contrastAuditFinish = async function (imgBase64, time, candidates, region) { - function relLum(r, g, b) { - function ch(v) { - var s = v / 255; - return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4); - } - return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b); - } - - function wcagRatio(r1, g1, b1, r2, g2, b2) { - var l1 = relLum(r1, g1, b1), - l2 = relLum(r2, g2, b2); - var hi = l1 > l2 ? l1 : l2, - lo = l1 > l2 ? l2 : l1; - return (hi + 0.05) / (lo + 0.05); - } - - function median(arr) { - var s = arr.slice().sort(function (a, b) { - return a - b; - }); - return s[Math.floor(s.length / 2)]; - } - - // Restore original paint first — we already have the screenshot, and we - // never want a decode failure below to leave the page's text invisible. - __contrastAuditRestoreAll(); - - // No image when every candidate's background is known from styles. - var canvas = { width: region ? region.frameWidth : 0, height: region ? region.frameHeight : 0 }; - var px = null; - if (imgBase64) { - var img = new Image(); - await new Promise(function (resolve) { - img.onload = resolve; - img.onerror = function () { - resolve(); - }; - img.src = "data:image/png;base64," + imgBase64; - }); - if (!img.naturalWidth) return []; - canvas = document.createElement("canvas"); - canvas.width = img.naturalWidth || 1920; - canvas.height = img.naturalHeight || 1080; - var ctx = canvas.getContext("2d"); - if (!ctx) return []; - ctx.drawImage(img, 0, 0); - px = ctx.getImageData(0, 0, canvas.width, canvas.height).data; - } - // A clipped shot holds `region.clip` of the frame: clamp to the frame, read at the offset. - var w = region ? region.frameWidth : canvas.width; - var h = region ? region.frameHeight : canvas.height; - var ox = region ? region.clip.x : 0; - var oy = region ? region.clip.y : 0; - - var out = []; - for (var ci = 0; ci < candidates.length; ci++) { - var c = candidates[ci]; - var bbox = c.bbox; - - // Sample the element's OWN box (glyphs are hidden in this screenshot), - // inset 1px on each side to dodge anti-aliased edge pixels, clamped to - // the canvas. Mirrors contrast-sample.ts's computeSampleRect. - var x0 = Math.max(0, Math.round(bbox.x) + 1); - var x1 = Math.min(w - 1, Math.round(bbox.x + bbox.w) - 1); - var y0 = Math.max(0, Math.round(bbox.y) + 1); - var y1 = Math.min(h - 1, Math.round(bbox.y + bbox.h) - 1); - if (x1 <= x0 || y1 <= y0) continue; - - // Bounded grid, not a full scan — dense enough to catch a - // partially-overlapping decoration without turning a wide caption bar - // into thousands of samples. Mirrors contrast-sample.ts's - // sampleGridPoints. - var stepX = Math.max(1, Math.floor((x1 - x0) / 12)); - var stepY = Math.max(1, Math.floor((y1 - y0) / 6)); - var known = c.ownBg && c.ownBg.length >= 4 && c.ownBg[3] >= 0.99 ? c.ownBg : c.solidBg; - var rr = [], - gg = [], - bb = [], - aa = []; - for (var y = y0; !known && y <= y1; y += stepY) { - for (var x = x0; x <= x1; x += stepX) { - var idx = ((y - oy) * canvas.width + (x - ox)) * 4; - rr.push(px[idx]); - gg.push(px[idx + 1]); - bb.push(px[idx + 2]); - aa.push(px[idx + 3]); - } - } - if (!known && rr.length === 0) continue; - - var bgR, bgG, bgB; - if (known) { - bgR = known[0]; - bgG = known[1]; - bgB = known[2]; - } else { - // A transparent sampled backdrop is supplied by the downstream editor, - // not this composition. WCAG contrast cannot be inferred until that live - // video/image is known, so do not invent an opaque browser default and - // hard-fail an otherwise valid alpha overlay. - if (median(aa) < 255) continue; - bgR = median(rr); - bgG = median(gg); - bgB = median(bb); - } - - // Composite foreground alpha over the measured background; a gradient's weakest stop sets the ratio. - var compR = 0, - compG = 0, - compB = 0, - ratio = Infinity; - var fills = c.fgStops || [c.fg]; - for (var pi = 0; pi < fills.length; pi++) { - var fg = fills[pi]; - var paintR = Math.round(fg[0] * fg[3] + bgR * (1 - fg[3])); - var paintG = Math.round(fg[1] * fg[3] + bgG * (1 - fg[3])); - var paintB = Math.round(fg[2] * fg[3] + bgB * (1 - fg[3])); - var paintRatio = +wcagRatio(paintR, paintG, paintB, bgR, bgG, bgB).toFixed(2); - if (paintRatio >= ratio) continue; - compR = paintR; - compG = paintG; - compB = paintB; - ratio = paintRatio; - } - - // A solid text stroke is part of the visible glyph paint. Use whichever - // of fill or stroke provides the stronger edge contrast, rather than - // failing readable outlined captions based on fill alone. - if (c.stroke) { - var stroke = c.stroke; - var strokeR = Math.round(stroke[0] * stroke[3] + bgR * (1 - stroke[3])); - var strokeG = Math.round(stroke[1] * stroke[3] + bgG * (1 - stroke[3])); - var strokeB = Math.round(stroke[2] * stroke[3] + bgB * (1 - stroke[3])); - var strokeRatio = +wcagRatio(strokeR, strokeG, strokeB, bgR, bgG, bgB).toFixed(2); - if (strokeRatio > ratio) { - compR = strokeR; - compG = strokeG; - compB = strokeB; - ratio = strokeRatio; - } - } - - out.push({ - time: time, - selector: c.selector, - text: c.text, - ratio: ratio, - wcagAA: c.large ? ratio >= 3 : ratio >= 4.5, - large: c.large, - fg: "rgb(" + compR + "," + compG + "," + compB + ")", - bg: "rgb(" + bgR + "," + bgG + "," + bgB + ")", - }); - } - return out; -}; diff --git a/packages/cli/src/commands/contrast-bg.ts b/packages/cli/src/commands/contrast-bg.ts index 778a9e64ae3..d8999b0a4db 100644 --- a/packages/cli/src/commands/contrast-bg.ts +++ b/packages/cli/src/commands/contrast-bg.ts @@ -1,26 +1,9 @@ -// Pure background-resolution logic for the WCAG contrast audit. -// -// HISTORICAL NOTE: contrast-audit.browser.js used to sample a 4px pixel ring -// just OUTSIDE an element's bounding box to estimate its background, with -// pickOpaqueBackground() below as a pre-check: prefer an element's own opaque -// background-color over the ring for solid CTA/pill/card cases. The audit has -// since moved to sampling the ACTUAL composited pixels directly inside each -// element's own bbox (hiding the glyphs first) — see contrast-sample.ts — which -// gets pill/card backgrounds right AND fixes the ring's blind spots (rounded -// corners, backdrop-filter blur, cross-component bleed, partially-overlapping -// translucent decoration). pickOpaqueBackground()/parseColorRGBA() are no -// longer called by the live audit but are kept here — still correct, still -// unit-tested, and contrast-fg.ts imports parseColorRGBA from this module. -// -// This module hosts pure decisions so they can be unit-tested without a -// browser. Historically the same logic was inlined into -// contrast-audit.browser.js (which is injected as a raw string and cannot -// import) — see contrast-sample.ts for what's actually mirrored today. +// Pure colour decisions for the WCAG contrast audit, unit-testable without a browser. export type Rgb = [number, number, number]; export type Rgba = [number, number, number, number]; -/** WCAG relative luminance for an sRGB color. Mirrors contrast-audit.browser.js. */ +/** WCAG relative luminance for an sRGB color. */ export function relativeLuminance(color: Rgb): number { const channel = (value: number) => { const srgb = value / 255; diff --git a/packages/cli/src/commands/contrast-clip.browser.test.ts b/packages/cli/src/commands/contrast-clip.browser.test.ts index f0c4299d3d6..801a91b7abc 100644 --- a/packages/cli/src/commands/contrast-clip.browser.test.ts +++ b/packages/cli/src/commands/contrast-clip.browser.test.ts @@ -4,6 +4,8 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { afterAll, beforeAll, expect, it } from "vitest"; import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js"; +import { framePixels } from "../utils/framePixels.js"; +import { measureContrast, parseContrastCandidate, type TextRegion } from "./contrast-measure.js"; // Text over a two-tone backdrop, away from the origin: reading a clipped shot at the wrong offset picks the other tone. const HTML = ` @@ -54,17 +56,17 @@ it("measures the same contrast from a shot clipped to the text as from the full omitBackground: true, ...(clipped ? { clip, captureBeyondViewport: false } : {}), }); - const region = clipped ? { clip, frameWidth: 640, frameHeight: 360 } : null; - return page.evaluate( - (png: string, items: unknown[], at: unknown) => - Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [png, 0, items, at]), - shot, - candidates, - region, - ); + await page.evaluate("window.__contrastAuditRestoreIfPending()"); + const region: TextRegion | undefined = clipped + ? { clip, frameWidth: 640, frameHeight: 360 } + : undefined; + return candidates.map((value) => { + const candidate = parseContrastCandidate(value); + return candidate && measureContrast(candidate, framePixels(shot), region); + }); }; - const full = (await measure(false)) as { bg: number[] }[]; + const full = await measure(false); expect(full).toHaveLength(2); expect(full[0]?.bg).not.toEqual(full[1]?.bg); expect(await measure(true)).toEqual(full); diff --git a/packages/cli/src/commands/contrast-measure.test.ts b/packages/cli/src/commands/contrast-measure.test.ts new file mode 100644 index 00000000000..c7657c23fb1 --- /dev/null +++ b/packages/cli/src/commands/contrast-measure.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "vitest"; +import { measureContrast, parseContrastCandidate } from "./contrast-measure.js"; + +const prepared = { + selector: "#a", + text: "Words", + fg: [255, 255, 255, 1], + fgStops: null, + stroke: null, + large: false, + ownBg: null, + solidBg: null, + bbox: { x: 0, y: 0, w: 8, h: 8 }, +}; +const frame = (...pixel: number[]) => ({ + width: 10, + height: 10, + data: Uint8Array.from({ length: 400 }, (_, i) => pixel[i % 4] ?? 0), +}); +const measure = (value: object, pixels: ReturnType | null) => { + const candidate = parseContrastCandidate({ ...prepared, ...value }); + return candidate && measureContrast(candidate, pixels, undefined); +}; + +describe("measureContrast", () => { + it("judges text by the pixels behind it", () => { + expect(measure({}, frame(0, 0, 0, 255))).toMatchObject({ ratio: 21, wcagAA: true }); + expect(measure({}, frame(255, 255, 255, 255))).toMatchObject({ ratio: 1, wcagAA: false }); + }); + + it("judges a gradient fill by its weakest stop, and an outline that reads better instead", () => { + const fgStops = [ + [255, 255, 255, 1], + [0, 0, 0, 1], + ]; + expect(measure({ fgStops }, frame(0, 0, 0, 255))?.fg).toBe("rgb(0,0,0)"); + expect(measure({ fgStops, stroke: [255, 255, 0, 1] }, frame(0, 0, 0, 255))?.fg).toBe( + "rgb(255,255,0)", + ); + }); + + it("leaves text over a transparent backdrop alone", () => { + expect(measure({}, frame(0, 0, 0, 0))).toBeNull(); + }); + + it("reads no pixel where styles prove the backdrop", () => { + const region = { clip: { x: 0, y: 0, width: 10, height: 10 }, frameWidth: 10, frameHeight: 10 }; + const candidate = parseContrastCandidate({ ...prepared, solidBg: [0, 0, 0] }); + expect(candidate && measureContrast(candidate, null, region)).toMatchObject({ ratio: 21 }); + }); +}); + +describe("parseContrastCandidate", () => { + it.each([ + ["no selector", { selector: "" }], + ["a colour that is not numbers", { fg: ["x", 0, 0, 1] }], + ["a gradient stop that is not a colour", { fgStops: [[0, 0, 0, 1], {}] }], + ["a box without a height", { bbox: { x: 0, y: 0, w: 8 } }], + ["a box that is not finite", { bbox: { x: 0, y: 0, w: Number.POSITIVE_INFINITY, h: 8 } }], + ])("drops a candidate with %s", (_, value) => { + expect(parseContrastCandidate({ ...prepared, ...value })).toBeNull(); + }); +}); diff --git a/packages/cli/src/commands/contrast-measure.ts b/packages/cli/src/commands/contrast-measure.ts new file mode 100644 index 00000000000..74ca8c9308b --- /dev/null +++ b/packages/cli/src/commands/contrast-measure.ts @@ -0,0 +1,140 @@ +import type { FramePixels } from "../utils/framePixels.js"; +import { contrastRatio, requiredContrastRatio, type Rgb, type Rgba } from "./contrast-bg.js"; +import { + computeSampleRect, + sampleGridPoints, + type PixelRect, + type Rect, +} from "./contrast-sample.js"; + +/** One text __contrastAuditPrepare hid: what the page knows about it before any pixel is read. */ +export interface ContrastCandidate { + selector: string; + text: string; + /** The fill, or each stop of a gradient fill: the weakest sets the ratio. */ + fills: Rgba[]; + stroke: Rgba | null; + /** The backdrop where styles alone prove it, so no pixel is read. */ + knownBackdrop: Rgb | null; + large: boolean; + bbox: Rect; +} + +/** Where a clipped shot sits in the frame. */ +export interface TextRegion { + clip: { x: number; y: number; width: number; height: number }; + frameWidth: number; + frameHeight: number; +} + +export interface ContrastMeasurement { + ratio: number; + wcagAA: boolean; + large: boolean; + fg: string; + bg: string; +} + +export function parseContrastCandidate(value: unknown): ContrastCandidate | null { + if (typeof value !== "object" || value === null) return null; + const { selector, text, fg, fgStops, stroke, ownBg, solidBg, large, bbox } = value as Record< + string, + unknown + >; + const fills = (Array.isArray(fgStops) ? fgStops : [fg]).map(rgba); + const box = rect(bbox); + if (typeof selector !== "string" || !selector || typeof text !== "string") return null; + if (typeof large !== "boolean" || !box || !fills.every((fill) => fill !== null)) return null; + return { + selector, + text, + fills, + stroke: rgba(stroke), + knownBackdrop: opaque(rgba(ownBg)) ?? rgb(solidBg), + large, + bbox: box, + }; +} + +/** The contrast of one text against what is behind its glyphs; null where that cannot be known. */ +export function measureContrast( + candidate: ContrastCandidate, + pixels: FramePixels | null, + region?: TextRegion, +): ContrastMeasurement | null { + const bg = backdrop(candidate, pixels, region); + if (!bg) return null; + const { stroke, large } = candidate; + const paints = candidate.fills.map((fill) => over(fill, bg)); + const [weakest] = paints.sort((a, b) => a.ratio - b.ratio); + if (!weakest) return null; + // A solid text stroke is visible glyph paint too: the stronger of fill and stroke decides. + const outline = stroke && over(stroke, bg); + const { color, ratio } = outline && outline.ratio > weakest.ratio ? outline : weakest; + if (!Number.isFinite(ratio)) return null; + return { + ratio, + wcagAA: ratio >= requiredContrastRatio(large), + large, + fg: `rgb(${color.join(",")})`, + bg: `rgb(${bg.join(",")})`, + }; +} + +function backdrop( + { bbox, knownBackdrop }: ContrastCandidate, + pixels: FramePixels | null, + region: TextRegion | undefined, +): Rgb | null { + const { clip, frameWidth, frameHeight } = region ?? wholeFrame(pixels); + const box = computeSampleRect(bbox, frameWidth, frameHeight); + if (!box || knownBackdrop) return box && knownBackdrop; + return pixels && sampledColor(pixels, box, clip); +} + +function wholeFrame(pixels: FramePixels | null): TextRegion { + const { width, height } = pixels ?? { width: 0, height: 0 }; + return { clip: { x: 0, y: 0, width, height }, frameWidth: width, frameHeight: height }; +} + +function sampledColor( + { data, width }: FramePixels, + box: PixelRect, + clip: TextRegion["clip"], +): Rgb | null { + const offsets = sampleGridPoints(box).map(([x, y]) => ((y - clip.y) * width + (x - clip.x)) * 4); + const channel = (index: number) => median(offsets.map((at) => data[at + index] ?? 0)); + // The editor supplies what a transparent backdrop shows, so its contrast cannot be known here. + return channel(3) < 255 ? null : [channel(0), channel(1), channel(2)]; +} + +function over([r, g, b, alpha]: Rgba, bg: Rgb): { color: Rgb; ratio: number } { + const mix = (paint: number, under: number) => Math.round(paint * alpha + under * (1 - alpha)); + const color: Rgb = [mix(r, bg[0]), mix(g, bg[1]), mix(b, bg[2])]; + return { color, ratio: +contrastRatio(color, bg).toFixed(2) }; +} + +function median(values: number[]): number { + const sorted = [...values].sort((a, b) => a - b); + return sorted[Math.floor(sorted.length / 2)] ?? 0; +} + +function numbers(value: unknown, count: number): number[] | null { + if (!Array.isArray(value) || value.length < count) return null; + const read: unknown[] = value.slice(0, count); + return read.every((entry) => typeof entry === "number" && Number.isFinite(entry)) + ? (read as number[]) + : null; +} + +const rgba = (value: unknown) => numbers(value, 4) as Rgba | null; +const rgb = (value: unknown) => numbers(value, 3) as Rgb | null; +const opaque = (color: Rgba | null): Rgb | null => + color && color[3] >= 0.99 ? [color[0], color[1], color[2]] : null; + +function rect(value: unknown): Rect | null { + if (typeof value !== "object" || value === null) return null; + const { x, y, w, h } = value as Record; + const read = numbers([x, y, w, h], 4); + return read ? { x: read[0]!, y: read[1]!, w: read[2]!, h: read[3]! } : null; +} diff --git a/packages/cli/src/commands/contrast-occlusion.browser.test.ts b/packages/cli/src/commands/contrast-occlusion.browser.test.ts index 521c95abe6a..d69cbb825fd 100644 --- a/packages/cli/src/commands/contrast-occlusion.browser.test.ts +++ b/packages/cli/src/commands/contrast-occlusion.browser.test.ts @@ -71,7 +71,6 @@ afterEach(() => { Reflect.deleteProperty(document, "elementsFromPoint"); for (const name of [ "__contrastAuditPrepare", - "__contrastAuditFinish", "__contrastAuditRestoreIfPending", "__contrastAuditRestores", ]) diff --git a/packages/cli/src/commands/contrast-sample.ts b/packages/cli/src/commands/contrast-sample.ts index 7df00457350..07ae2a02251 100644 --- a/packages/cli/src/commands/contrast-sample.ts +++ b/packages/cli/src/commands/contrast-sample.ts @@ -8,9 +8,7 @@ // invisible, and samples the composited pixels INSIDE the element's own bbox. // This module hosts the pure "which rect do we sample" decision (inset to // dodge anti-aliased edge pixels, clamp to canvas bounds, and reject a rect -// that's too small to sample) so it's unit-testable without a browser. The -// same logic is inlined into contrast-audit.browser.js (which is injected as -// a raw string and cannot import) — keep both in sync. +// that's too small to sample) so it's unit-testable without a browser. export interface Rect { x: number; diff --git a/packages/cli/src/commands/contrast-solid.browser.test.ts b/packages/cli/src/commands/contrast-solid.browser.test.ts index 04ae5b215b5..9abea589a71 100644 --- a/packages/cli/src/commands/contrast-solid.browser.test.ts +++ b/packages/cli/src/commands/contrast-solid.browser.test.ts @@ -4,6 +4,8 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { afterAll, beforeAll, expect, it } from "vitest"; import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js"; +import { framePixels } from "../utils/framePixels.js"; +import { measureContrast, parseContrastCandidate } from "./contrast-measure.js"; const P = "position:absolute;margin:0;font:28px sans-serif;color:#9ab"; const HTML = ` @@ -52,17 +54,12 @@ it("reads a backdrop from styles only where pixels would give the same contrast" const prepared = (await page.evaluate("window.__contrastAuditPrepare()")) as Candidate[]; const shot = await page.screenshot({ encoding: "base64", omitBackground: true }); const candidates = dropSolid ? prepared.map((c) => ({ ...c, solidBg: null })) : prepared; - const entries = await page.evaluate( - (png: string, items: unknown[]) => - Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [ - png, - 0, - items, - null, - ]), - shot, - candidates, - ); + await page.evaluate("window.__contrastAuditRestoreIfPending()"); + const entries = candidates.map((value) => { + const candidate = parseContrastCandidate(value); + return candidate && measureContrast(candidate, framePixels(shot)); + }); + expect(entries).not.toContain(null); return { prepared, entries }; }; diff --git a/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts b/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts index b06de0db1b8..4c2187f2588 100644 --- a/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts +++ b/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts @@ -4,6 +4,8 @@ import type { AddressInfo } from "node:net"; import { join } from "node:path"; import { afterAll, beforeAll, expect, it } from "vitest"; import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js"; +import { framePixels } from "../utils/framePixels.js"; +import { measureContrast, parseContrastCandidate } from "./contrast-measure.js"; const TEXT = `x="20" font-family="sans-serif" font-weight="700" font-size="40"`; const HTML = ` @@ -49,14 +51,13 @@ it("judges SVG gradient text by its stops and skips a pattern fill", async () => }); try { await page.addScriptTag({ content: SCRIPT }); - const candidates = await page.evaluate("window.__contrastAuditPrepare()"); + const candidates = (await page.evaluate("window.__contrastAuditPrepare()")) as unknown[]; const shot = await page.screenshot({ encoding: "base64", omitBackground: true }); - const entries = (await page.evaluate( - (png: string, items: unknown) => - Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [png, 0, items, null]), - shot, - candidates, - )) as { selector: string; fg: string; wcagAA: boolean }[]; + const entries = candidates.flatMap((value) => { + const candidate = parseContrastCandidate(value); + const measured = candidate && measureContrast(candidate, framePixels(shot)); + return measured ? [{ selector: candidate.selector, ...measured }] : []; + }); const bySelector = Object.fromEntries( entries.map(({ selector, fg, wcagAA }) => [selector, { fg, wcagAA }]), ); diff --git a/packages/cli/src/commands/layout-audit.browser.test.ts b/packages/cli/src/commands/layout-audit.browser.test.ts index 53523fbef56..d42a5411599 100644 --- a/packages/cli/src/commands/layout-audit.browser.test.ts +++ b/packages/cli/src/commands/layout-audit.browser.test.ts @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; +import { measureContrast, parseContrastCandidate } from "./contrast-measure.js"; const __dirname = dirname(fileURLToPath(import.meta.url)); const script = readFileSync(join(__dirname, "layout-audit.browser.js"), "utf-8"); @@ -2623,12 +2624,10 @@ describe("contrast-audit.browser clip-path visibility", () => { delete ( window as unknown as { __contrastAuditPrepare?: unknown; - __contrastAuditFinish?: unknown; __contrastAuditRestoreIfPending?: unknown; __contrastAuditRestores?: unknown; } ).__contrastAuditPrepare; - delete (window as unknown as { __contrastAuditFinish?: unknown }).__contrastAuditFinish; delete (window as unknown as { __contrastAuditRestoreIfPending?: unknown }) .__contrastAuditRestoreIfPending; delete (window as unknown as { __contrastAuditRestores?: unknown }).__contrastAuditRestores; @@ -2813,23 +2812,12 @@ describe("contrast-audit.browser background sampling", () => { document.body.innerHTML = ""; delete (document as unknown as { elementFromPoint?: unknown }).elementFromPoint; delete (window as unknown as { __contrastAuditPrepare?: unknown }).__contrastAuditPrepare; - delete (window as unknown as { __contrastAuditFinish?: unknown }).__contrastAuditFinish; delete (window as unknown as { __contrastAuditRestoreIfPending?: unknown }) .__contrastAuditRestoreIfPending; delete (window as unknown as { __contrastAuditRestores?: unknown }).__contrastAuditRestores; }); - // Locks in the "already correct" finding from investigating the - // solid-fill-pill/button false-positive report: a rounded pill/button - // with its own solid background, sitting on a busy/bright page - // background, must NOT be flagged even though the two-phase - // prepare()/finish() path (hide text, sample the real pixels directly - // inside the element's own bbox) replaced the ring+own-background-walk - // heuristic this used to rely on. The pixel buffer here is real per-pixel - // data (not the flat-white default), with a dark region standing in for - // the pill sitting inside a bright page background, so this exercises the - // actual bbox-sampling logic in __contrastAuditFinish rather than a fixed - // stub value. + // A dark pill with its own solid fill on a bright, busy page: only the pixels inside the text's box count. it("does not flag a solid-fill pill/button with adequate contrast", async () => { document.body.innerHTML = `
@@ -4032,27 +4020,7 @@ function installAuditScript(): void { // position (e.g. a solid-fill pill sitting on a busy page background) so the // two-phase prepare/finish sampling has something real to distinguish. function installContrastScript(pixels?: Uint8ClampedArray): void { - class MockImage { - onload: (() => void) | null = null; - onerror: (() => void) | null = null; - naturalWidth = 640; - naturalHeight = 360; - - set src(_value: string) { - this.onload?.(); - } - } - - vi.stubGlobal("Image", MockImage); - const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as { - mockReturnValue(value: CanvasRenderingContext2D): void; - }; - getContextSpy.mockReturnValue({ - drawImage() {}, - getImageData() { - return { data: pixels ?? new Uint8ClampedArray(640 * 360 * 4).fill(255) }; - }, - } as unknown as CanvasRenderingContext2D); + contrastPixels = pixels ?? new Uint8ClampedArray(640 * 360 * 4).fill(255); window.eval(contrastScript); } @@ -4087,17 +4055,16 @@ function pixelsWithRegion( return data; } +let contrastPixels: Uint8ClampedArray = new Uint8ClampedArray(); + async function runContrastAudit(): Promise>> { - const w = window as unknown as { - __contrastAuditPrepare: () => Array>; - __contrastAuditFinish: ( - imgBase64: string, - time: number, - candidates: Array>, - ) => Promise>>; - }; - const candidates = w.__contrastAuditPrepare(); - return w.__contrastAuditFinish("stub", 0, candidates); + const candidates: unknown[] = Reflect.get(window, "__contrastAuditPrepare")(); + const pixels = { width: 640, height: 360, data: new Uint8Array(contrastPixels) }; + return candidates.flatMap((value) => { + const candidate = parseContrastCandidate(value); + const measured = candidate && measureContrast(candidate, pixels); + return measured ? [{ selector: candidate.selector, text: candidate.text, ...measured }] : []; + }); } interface AuditIssue { diff --git a/packages/cli/src/commands/motion-signature.browser.js b/packages/cli/src/commands/motion-signature.browser.js index f69647b387f..fcb287152cc 100644 --- a/packages/cli/src/commands/motion-signature.browser.js +++ b/packages/cli/src/commands/motion-signature.browser.js @@ -1,7 +1,7 @@ // Shared "what counts as motion" classifier, injected before layout-audit.browser.js and motion-sample.browser.js. // The frozen-sweep guard (sweep_static) and keepsMoving liveness (motion_frozen) meet in one decision, so both // must count the same channels as motion; only quantization differs (liveness buckets 2px and 0.08 opacity). -// Where both read still, check asks framesDiffer below, which compares the rendered frames. +// Where both read still, check compares the rendered frames (utils/framePixels.ts). // A channel reader returns a string equal across samples iff it did not visibly change, "" when it does not apply. (function () { const IGNORE_TAGS = new Set(["SCRIPT", "STYLE", "TEMPLATE", "NOSCRIPT", "META", "LINK"]); @@ -429,57 +429,6 @@ return parts.join("|"); } - // --- Rendered frames: the last word where DOM channels cannot see paint ------ - // A frame moved when enough pixels changed by more than render noise (antialiasing, dither) on some channel. - // ponytail: fewer than FRAME_MIN_CHANGED_PIXELS changed pixels reads as still; lower it for tinier motion. - const FRAME_CHANNEL_NOISE = 24; - const FRAME_MIN_CHANGED_PIXELS = 16; - let reference = { png: "", pixels: null }; - - // Decoded in the page like the contrast pass, so no image library is needed. - async function framePixels(png) { - const image = new Image(); - image.src = "data:image/png;base64," + png; - await image.decode(); - const canvas = document.createElement("canvas"); - canvas.width = image.naturalWidth; - canvas.height = image.naturalHeight; - const ctx2d = canvas.getContext("2d", { willReadFrequently: true }); - ctx2d.drawImage(image, 0, 0); - return ctx2d.getImageData(0, 0, canvas.width, canvas.height); - } - - function pixelChanged(a, b, i) { - return ( - Math.abs(a[i] - b[i]) > FRAME_CHANNEL_NOISE || - Math.abs(a[i + 1] - b[i + 1]) > FRAME_CHANNEL_NOISE || - Math.abs(a[i + 2] - b[i + 2]) > FRAME_CHANNEL_NOISE || - Math.abs(a[i + 3] - b[i + 3]) > FRAME_CHANNEL_NOISE - ); - } - - // Base64 PNG screenshots in, "did anything visible change" out. The first frame is usually a run's - // reference compared against many, so its decode is kept. - // fallow-ignore-next-line complexity - async function framesDiffer(first, second) { - if (first === second) return false; - if (!first || !second) return true; - if (reference.png !== first) reference = { png: first, pixels: await framePixels(first) }; - return pixelsDiffer(reference.pixels, await framePixels(second)); - } - - // fallow-ignore-next-line complexity - function pixelsDiffer(a, b) { - if (a.width !== b.width || a.height !== b.height) return true; - let changed = 0; - for (let i = 0; i < a.data.length; i += 4) { - if (pixelChanged(a.data, b.data, i) && ++changed >= FRAME_MIN_CHANGED_PIXELS) return true; - } - return false; - } - - window.__hyperframesFramesDiffer = framesDiffer; - window.__hyperframesMotionSignature = { compositionRoot, isVisibleElement, diff --git a/packages/cli/src/commands/motionShot.ts b/packages/cli/src/commands/motionShot.ts index c6ae302d857..da9864e8a00 100644 --- a/packages/cli/src/commands/motionShot.ts +++ b/packages/cli/src/commands/motionShot.ts @@ -19,6 +19,7 @@ import { dirname, resolve } from "node:path"; import { pageNavigationTimeoutMs } from "../utils/renderArgs.js"; import { gotoWhenSent } from "../capture/navigateForCapture.js"; import { resolveCompositionViewportFromHtml } from "../utils/compositionViewport.js"; +import { screenshotOnBlankPage } from "../utils/blankPageShot.js"; import { waitForRuntimeReady } from "../capture/captureCompositionFrame.js"; import { assertWebGpuAdapterAvailable, @@ -731,11 +732,9 @@ async function captureRenderedSvgStrip( height: size.height, label: `${cameraLabel(camera)} · filmstrip · ${times.length} frames${windowStr}`, }); - await page.evaluate((svg: string) => document.body.insertAdjacentHTML("beforeend", svg), markup); - await new Promise((resolveWait) => setTimeout(resolveWait, 60)); - const output = await page.screenshot({ type: "png" }); + const output = await screenshotOnBlankPage(page, (blank) => blank.setContent(markup)); if (!output) throw new Error("screenshot returned no data"); - replaceFileAtomically(outPath, output as Uint8Array); + replaceFileAtomically(outPath, Buffer.from(output, "base64")); return outPath; } diff --git a/packages/cli/src/commands/validate.ts b/packages/cli/src/commands/validate.ts index 90939456079..ee0bafd1005 100644 --- a/packages/cli/src/commands/validate.ts +++ b/packages/cli/src/commands/validate.ts @@ -31,6 +31,8 @@ import { waitForRuntimeReady, } from "../capture/captureCompositionFrame.js"; import { failureMessage, jsonFailure } from "../utils/jsonError.js"; +import { framePixels } from "../utils/framePixels.js"; +import { measureContrast, parseContrastCandidate } from "./contrast-measure.js"; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -286,17 +288,9 @@ export async function auditClipDurations( return warnings; } -interface ContrastCandidate { - selector: string; - text: string; - fg: [number, number, number, number]; - fontSize: number; - fontWeight: number; - large: boolean; - bbox: { x: number; y: number; w: number; h: number }; -} - -async function runContrastAudit(page: import("puppeteer-core").Page): Promise { +export async function runContrastAudit( + page: import("puppeteer-core").Page, +): Promise { const duration = await getCompositionDuration(page); if (duration <= 0) return []; @@ -313,54 +307,29 @@ async function runContrastAudit(page: import("puppeteer-core").Page): Promise - typeof (window as unknown as Record).__contrastAuditPrepare === "function" - ? ( - (window as unknown as Record).__contrastAuditPrepare as () => unknown - )() - : [], - )) as ContrastCandidate[]; - - const screenshot = (await page.screenshot({ + // First inside the try: if it throws partway through hiding text, the finally still restores it. + const prepared = await page.evaluate(() => { + const prepare = Reflect.get(window, "__contrastAuditPrepare"); + return typeof prepare === "function" ? Reflect.apply(prepare, window, []) : []; + }); + const candidates = (Array.isArray(prepared) ? prepared : []).flatMap( + (value) => parseContrastCandidate(value) ?? [], + ); + const screenshot = await page.screenshot({ encoding: "base64", type: "png", omitBackground: true, - })) as string; - const entries = await page.evaluate( - (b64: string, time: number, cands: ContrastCandidate[]) => - typeof (window as unknown as Record).__contrastAuditFinish === "function" - ? ((window as unknown as Record).__contrastAuditFinish as Function)( - b64, - time, - cands, - ) - : [], - screenshot, - t, - candidates, - ); - results.push(...(entries as ContrastEntry[])); + }); + const pixels = framePixels(screenshot); + for (const candidate of candidates) { + const measured = measureContrast(candidate, pixels); + const { selector, text } = candidate; + if (measured) results.push({ time: t, selector, text, ...measured }); + } } finally { - // If prepare(), the screenshot, or finish() above throws, this restores - // any still-hidden text paint so the NEXT sample in the loop doesn't - // audit a page with stale invisible elements. No-op after a normal - // finish() call. await page.evaluate(() => { - const restore = (window as unknown as Record) - .__contrastAuditRestoreIfPending; - if (typeof restore === "function") (restore as () => void)(); + const restore = Reflect.get(window, "__contrastAuditRestoreIfPending"); + if (typeof restore === "function") Reflect.apply(restore, window, []); }); } } diff --git a/packages/cli/src/utils/blankPageShot.ts b/packages/cli/src/utils/blankPageShot.ts new file mode 100644 index 00000000000..ebd6556f35d --- /dev/null +++ b/packages/cli/src/utils/blankPageShot.ts @@ -0,0 +1,17 @@ +import type { Page } from "puppeteer-core"; + +/** A screenshot of what `build` draws on a blank page of the same size, which shares nothing with `page`. */ +export async function screenshotOnBlankPage( + page: Page, + build: (blank: Page) => Promise, +): Promise { + const blank = await page.browser().newPage(); + try { + const viewport = page.viewport(); + if (viewport) await blank.setViewport(viewport); + await build(blank); + return await blank.screenshot({ encoding: "base64", type: "png" }); + } finally { + await blank.close(); + } +} diff --git a/packages/cli/src/utils/checkBrowser.test.ts b/packages/cli/src/utils/checkBrowser.test.ts index 338c1e42748..d9fb1d9b6f8 100644 --- a/packages/cli/src/utils/checkBrowser.test.ts +++ b/packages/cli/src/utils/checkBrowser.test.ts @@ -2,6 +2,7 @@ // fallow-ignore-file code-duplication import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { DEFAULT_CONFIG } from "@hyperframes/engine"; +import { encodePng } from "@hyperframes/engine/alpha-blit"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { execFileSync } from "node:child_process"; import os, { tmpdir } from "node:os"; @@ -34,6 +35,16 @@ import { closeManagedBrowser } from "../browser/launch.js"; import { serveStaticProjectHtml } from "./staticProjectServer.js"; import type { ProjectDir } from "./project.js"; +const solidPng = (channel: number) => + encodePng( + 640, + 360, + new Uint8Array(640 * 360 * 4).map((_, i) => (i % 4 === 3 ? 255 : channel)), + ).toString("base64"); +const WHITE_PNG = solidPng(255); +const BLACK_PNG = solidPng(0); +const GRAY_PNG = solidPng(128); + const mocks = vi.hoisted(() => ({ stopListeners: new Set<() => void>(), proxyProgress: { @@ -188,7 +199,6 @@ afterEach(() => { Reflect.deleteProperty(window, "__hyperframesGeometryCandidates"); Reflect.deleteProperty(window, "__hyperframesLayoutAudit"); Reflect.deleteProperty(window, "__contrastAuditPrepare"); - Reflect.deleteProperty(window, "__contrastAuditFinish"); Reflect.deleteProperty(window, "__contrastAuditRestores"); Reflect.deleteProperty(window, "__contrastAuditRestoreIfPending"); mocks.scanProjectMediaCodecMap.mockResolvedValue({}); @@ -555,12 +565,7 @@ it("fails at once when the page crashes, instead of waiting out the deadline", a } }); -it("round-trips the browser script's raw contrast candidates back into finish", async () => { - // The U2 regression class: Node parses prepare's candidates for reporting, - // but must hand the UNTOUCHED objects back to __contrastAuditFinish — the - // page script samples pixels via its own bbox shape (w/h). A normalized - // candidate (width/height) makes every sample rect NaN and the audit - // silently reports zero checked elements as green. +it("measures the contrast of the browser script's own candidates", async () => { vi.spyOn(Date, "now").mockReturnValue(100); mountCanvasFixture(`
Readable copy
@@ -585,74 +590,24 @@ it("round-trips the browser script's raw contrast candidates back into finish", }) as unknown as CSSStyleDeclaration, ); - // happy-dom can't decode PNGs: stub Image (sync onload) and the canvas 2D - // context the way layout-audit.browser.test.ts's contrast harness does, so - // the REAL __contrastAuditFinish runs its sampling path end to end. - class MockImage { - onload: (() => void) | null = null; - onerror: (() => void) | null = null; - naturalWidth = 640; - naturalHeight = 360; - - set src(_value: string) { - this.onload?.(); - } - } - vi.stubGlobal("Image", MockImage); - const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as { - mockReturnValue(value: CanvasRenderingContext2D): void; - }; - getContextSpy.mockReturnValue({ - drawImage() {}, - getImageData() { - return { data: new Uint8ClampedArray(640 * 360 * 4).fill(255) }; - }, - } as unknown as CanvasRenderingContext2D); - - const received: Array> = []; const page = fakePage(); - const injectScript = page.addScriptTag; - page.addScriptTag = vi.fn(async (arg: { content: string }) => { - await injectScript(arg); - const w = window as unknown as { - __contrastAuditFinish?: ((...args: unknown[]) => Promise) & { wrapped?: boolean }; - }; - const finish = w.__contrastAuditFinish; - if (finish && !finish.wrapped) { - const wrapper = Object.assign( - async (...args: unknown[]) => { - const candidates = args[2]; - if (Array.isArray(candidates)) { - received.push(...(candidates as Array>)); - } - return finish(...args); - }, - { wrapped: true }, - ); - w.__contrastAuditFinish = wrapper; - } - }); - page.screenshot = vi.fn(async () => "c3R1Yg=="); + page.screenshot = vi.fn(async () => WHITE_PNG); installSessionMock(page); - await runBrowserCheck( + const result = await runBrowserCheck( PROJECT, { ...DEFAULT_CHECK_OPTIONS, samples: 1, contrast: true }, { kind: "none" }, runAuditGrid, ); - expect(received.length).toBeGreaterThan(0); - for (const candidate of received) { - const bbox = candidate.bbox as Record; - // The page script's own shape (w/h), not Node's envelope shape (width/height): - expect(typeof bbox.w).toBe("number"); - expect(typeof bbox.h).toBe("number"); - } + expect(result.contrastFindings).toEqual([ + expect.objectContaining({ selector: "#headline", ratio: 1, bg: "rgb(255,255,255)" }), + ]); }); it.each([ - { snapshots: true, shots: 2, saved: ["text-visible-base64"] }, + { snapshots: true, shots: 2, saved: [GRAY_PNG] }, { snapshots: false, shots: 1, saved: [] }, ])( "takes $shots contrast screenshot(s) when snapshots is $snapshots, overview after text restores", @@ -679,24 +634,8 @@ it.each([ ); const page = fakePage(); - const injectScript = page.addScriptTag; - page.addScriptTag = vi.fn(async (arg: { content: string }) => { - await injectScript(arg); - const w = window as unknown as { - __contrastAuditFinish?: (...args: unknown[]) => Promise; - __contrastAuditRestoreIfPending?: () => void; - }; - if (w.__contrastAuditFinish) { - w.__contrastAuditFinish = async () => { - w.__contrastAuditRestoreIfPending?.(); - return []; - }; - } - }); page.screenshot = vi.fn(async () => - headline.style.getPropertyValue("color") === "transparent" - ? "text-hidden-base64" - : "text-visible-base64", + headline.style.getPropertyValue("color") === "transparent" ? BLACK_PNG : GRAY_PNG, ); installSessionMock(page); @@ -720,6 +659,33 @@ it.each([ }, ); +it("shows the text again when its contrast screenshot fails", async () => { + vi.spyOn(Date, "now").mockReturnValue(100); + mountCanvasFixture(`
Readable copy
`); + const headline = document.querySelector("#headline"); + if (!headline) throw new Error("Contrast fixture failed to mount"); + vi.spyOn(headline, "getBoundingClientRect").mockReturnValue(new DOMRect(50, 50, 300, 40)); + const page = fakePage(); + let hidden = ""; + page.screenshot = vi.fn(async () => { + hidden = headline.style.color; + throw new Error("screenshot failed"); + }); + installSessionMock(page); + + await expect( + runBrowserCheck( + PROJECT, + { ...DEFAULT_CHECK_OPTIONS, samples: 1, contrast: true }, + { kind: "none" }, + runAuditGrid, + ), + ).rejects.toThrow("screenshot failed"); + + expect(hidden).toBe("transparent"); + expect(headline.style.color).toBe("rgb(1, 2, 3)"); +}); + describe("skipContrastInMotion", () => { type Tween = { target: string; start: number; duration: number; repeat?: number }; @@ -749,24 +715,6 @@ describe("skipContrastInMotion", () => { fontWeight: "700", }) as unknown as CSSStyleDeclaration, ); - class MockImage { - onload: (() => void) | null = null; - naturalWidth = 640; - naturalHeight = 360; - set src(_value: string) { - this.onload?.(); - } - } - vi.stubGlobal("Image", MockImage); - const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext") as unknown as { - mockReturnValue(value: CanvasRenderingContext2D): void; - }; - getContextSpy.mockReturnValue({ - drawImage() {}, - getImageData() { - return { data: new Uint8ClampedArray(640 * 360 * 4).fill(255) }; - }, - } as unknown as CanvasRenderingContext2D); const main = { time: () => 5, repeat: () => 0, @@ -792,10 +740,8 @@ describe("skipContrastInMotion", () => { } const page = fakePage(); const annotations: string[] = []; - page.screenshot = vi.fn(async () => { - annotations.push(document.getElementById("__hyperframesCheckAnnotations")?.textContent ?? ""); - return "c3R1Yg=="; - }); + page.screenshot = vi.fn(async () => WHITE_PNG); + page.browser = () => fakeBrowser((boxes) => annotations.push(...boxes.map((box) => box.label))); installSessionMock(page); try { const result = await runBrowserCheck( @@ -2019,17 +1965,10 @@ describe("preResolveHostileMediaProxies", () => { }); describe("captureOverviewShot", () => { - it("injects the annotation overlay before the overview shot and removes it right after", async () => { - const calls: string[] = []; - const evaluate = vi.fn(async (fn: unknown, ...args: unknown[]) => { - calls.push("evaluate"); - return typeof fn === "function" ? Reflect.apply(fn, undefined, args) : undefined; - }); - const screenshot = vi.fn(async () => { - calls.push("screenshot"); - return "annotated-base64"; - }); - const page = Object.assign(Object.create(null), { evaluate, screenshot }); + it("draws the boxes over the overview shot on a page of their own, then closes it", async () => { + const drawn: string[] = []; + const browser = fakeBrowser((boxes) => drawn.push(...boxes.map((box) => box.label))); + const page = { ...fakePage(), browser: () => browser }; const result = await captureOverviewShot( page, @@ -2037,10 +1976,12 @@ describe("captureOverviewShot", () => { "measurement-base64", ); - // inject overlay -> take the shot -> remove overlay, in that order — - // never present while any audit (which runs before this is called) collects. - expect(calls).toEqual(["evaluate", "screenshot", "evaluate"]); + expect(browser.blank.setViewport).toHaveBeenCalledWith({ width: 640, height: 360 }); + expect(browser.blank.setContent.mock.calls[0]?.[0]).toContain("measurement-base64"); + expect(drawn).toEqual(["1 clipped_text"]); expect(result).toBe("annotated-base64"); + expect(browser.blank.close).toHaveBeenCalled(); + expect(page.evaluate).not.toHaveBeenCalled(); }); it("skips the overlay entirely and returns the plain screenshot when there's nothing to annotate", async () => { @@ -2072,6 +2013,17 @@ function fakeConsoleMessage(type: string, text: string) { }; } +function fakeBrowser(onBoxes: (boxes: { label: string }[]) => void) { + const blank = { + setViewport: vi.fn(async () => undefined), + setContent: vi.fn(async (_html: string) => undefined), + evaluate: vi.fn(async (_draw: unknown, boxes: { label: string }[]) => onBoxes(boxes)), + screenshot: vi.fn(async () => "annotated-base64"), + close: vi.fn(async () => undefined), + }; + return { blank, newPage: async () => blank }; +} + function fakePage() { return Object.assign(Object.create(null), { on: vi.fn(), diff --git a/packages/cli/src/utils/checkBrowser.ts b/packages/cli/src/utils/checkBrowser.ts index 6a06d84e510..3e476b1f5b7 100644 --- a/packages/cli/src/utils/checkBrowser.ts +++ b/packages/cli/src/utils/checkBrowser.ts @@ -30,6 +30,14 @@ import { shouldIgnoreRequestFailure, } from "../commands/validate.js"; import { loadBrowserScript } from "../commands/browserScript.js"; +import { + measureContrast, + parseContrastCandidate, + type ContrastCandidate, + type TextRegion, +} from "../commands/contrast-measure.js"; +import { screenshotOnBlankPage } from "./blankPageShot.js"; +import { createFrameComparer, framePixels, isOneColor, type FramePixels } from "./framePixels.js"; import { projectLocalFile } from "../commands/snapshotHeldVideos.js"; import { normalizeErrorMessage } from "./errorMessage.js"; import { ambiguousIssue, type MotionFrame } from "./motionAudit.js"; @@ -129,36 +137,12 @@ interface AnchorRequest { bbox: CheckBbox; } -interface ContrastCandidate { - selector: string; - text: string; - fg: [number, number, number, number]; - large: boolean; - bbox: CheckBbox; -} - interface PreparedContrast { - // The untouched candidate object from __contrastAuditPrepare. It round-trips - // back into __contrastAuditFinish verbatim — the browser script owns its - // shape (e.g. bbox uses w/h, not width/height), so Node must not normalize - // what it sends back. `candidate` is the parsed copy for Node-side reporting. - raw: unknown; candidate: ContrastCandidate; - knownBackdrop: boolean; anchor: CheckAnchor; motion: ContrastMotionSample | null; } -interface FinishedContrast { - selector: string; - text: string; - ratio: number; - wcagAA: boolean; - large: boolean; - fg: string; - bg: string; -} - const COPY_HEARTBEAT_MS = 10_000; function elapsedText(ms: number): string { @@ -1099,6 +1083,7 @@ export function createPageDriver( sampleLog?: SampleWindow, projectDir?: string, ): CheckAuditDriver { + const framesDiffer = createFrameComparer(); return failWhenPageDies(page, { initialize: (contrast) => injectAuditScripts(page, contrast), markSamples: (phase) => { @@ -1107,7 +1092,13 @@ export function createPageDriver( else sampleLog[phase] = sampleLog.drafts.length; }, matchComponents: (components, findings) => - page.evaluate(matchComponentFindings, { components, findings }), + page.evaluate(matchComponentFindings, { + components, + findings: findings.map(({ selector, containerSelector }: ComponentFinding) => ({ + selector, + containerSelector, + })), + }), getDuration: () => getCompositionDuration(page), hasNoTimelineDeclaration: () => hasNoTimelineDeclaration(page), getTransitionBoundaries: () => collectTweenBoundaries(page), @@ -1140,14 +1131,7 @@ export function createPageDriver( }, collectLayoutGeometry: () => collectLayoutGeometry(page), captureFrame: (scope) => captureFrame(page, scope), - framesDiffer: (first, second) => - page - .evaluate( - (a, b) => Reflect.apply(Reflect.get(window, "__hyperframesFramesDiffer"), window, [a, b]), - first, - second, - ) - .then((differ) => differ === true), + framesDiffer: async (first, second) => framesDiffer(first, second), collectSeekClock: () => collectSeekClock(page), collectRotationSample: (time) => collectRotationSample(page, time), collectOffPivotRotationSample: (time) => collectOffPivotRotationSample(page, time), @@ -1162,13 +1146,14 @@ export function createPageDriver( collectContrast(page, time, annotations, skipInMotion), collectCraftFrame: (time) => collectCraftFrame(page, time), collectCraftFilm: () => collectCraftFilm(page), - stageIsEmpty: (frame) => - page - .evaluate( - (png) => Reflect.apply(Reflect.get(window, "__hyperframesStageIsEmpty"), window, [png]), - frame, - ) - .then((empty) => empty === true), + stageIsEmpty: async (frame) => { + const color = rgbaValue( + await page.evaluate(() => + Reflect.apply(Reflect.get(window, "__hyperframesEmptyStageColor"), window, []), + ), + ); + return color !== null && isOneColor(framePixels(frame), color); + }, }); } @@ -1853,24 +1838,12 @@ async function collectContrast( const motion = skipInMotion ? await page.evaluate(readContrastMotion).catch(() => []) : []; prepared = parsePreparedContrast(candidates, motion); if (prepared.length === 0 && !snapshotAnnotations) return { entries: [] }; - // This screenshot is the one contrast math is sampled from below — it must - // stay untouched by the annotation overlay (finishContrast reads real - // painted pixels), so annotation only ever happens on a SECOND shot. + // Measured with the glyphs hidden, so the annotated overview below is always a second shot. const { shot, region } = await measurementShot(page, prepared); - const raw = await finishContrast( - page, - shot, - time, - prepared.map((entry) => entry.raw), - region, - ); - const finished = raw.flatMap(parseFinishedContrast); - const entries = joinContrastEntries(finished, prepared); + await restoreContrastPaint(page); + const pixels = shot === null ? null : framePixels(shot); + const entries = prepared.flatMap((entry) => contrastEntry(entry, pixels, region)); if (!snapshotAnnotations) return { entries }; - // __contrastAuditFinish restores the text paint hidden by prepare. The - // measurement screenshot intentionally has glyphs removed so contrast - // can sample the pixels behind them; never persist that image as visual - // QA evidence. Capture the restored page for the overview instead. const overviewShot = await page.screenshot({ encoding: "base64", type: "png" }); if (typeof overviewShot !== "string") throw new Error("Overview screenshot was not base64"); // Contrast failures are only known once measurement above completes, so @@ -1883,21 +1856,33 @@ async function collectContrast( const pngBase64 = await captureOverviewShot(page, annotations, overviewShot); return { entries, pngBase64 }; } finally { - await page - .evaluate(() => { - const restore = Reflect.get(window, "__contrastAuditRestoreIfPending"); - if (typeof restore === "function") Reflect.apply(restore, window, []); - }) - .catch(() => undefined); + await restoreContrastPaint(page).catch(() => undefined); } } +async function restoreContrastPaint(page: Page): Promise { + await page.evaluate(() => { + const restore = Reflect.get(window, "__contrastAuditRestoreIfPending"); + if (typeof restore === "function") Reflect.apply(restore, window, []); + }); +} + +function contrastEntry( + { candidate, anchor, motion }: PreparedContrast, + pixels: FramePixels | null, + region: TextRegion | undefined, +): ContrastAuditEntry[] { + const measured = measureContrast(candidate, pixels, region); + if (!measured || (!measured.wcagAA && motion && measuredInMotion(motion))) return []; + return [{ text: candidate.text, ...measured, ...anchor }]; +} + async function measurementShot( page: Page, prepared: PreparedContrast[], ): Promise<{ shot: string | null; region: TextRegion | undefined }> { const frame = plainFrame(page.viewport()); - const sampled = prepared.filter((entry) => !entry.knownBackdrop); + const sampled = prepared.filter((entry) => !entry.candidate.knownBackdrop); if (frame && sampled.length === 0) { const clip = { x: 0, y: 0, ...frame }; return { shot: null, region: { clip, frameWidth: frame.width, frameHeight: frame.height } }; @@ -1925,62 +1910,39 @@ function contrastFailureAnnotations( })); } -const ANNOTATION_OVERLAY_ID = "__hyperframesCheckAnnotations"; - -/** - * `check --snapshots`'s overview-frame annotation: every audit for this - * sample time has already run (layout/geometry findings arrive via - * `annotations`; contrast failures were just measured above), so it's safe - * to draw labeled boxes and take one more shot without perturbing anything - * audits read. No-op (returns the plain screenshot) when there's nothing to - * annotate — the common case stays exactly as before this feature existed. - */ +/** The overview frame with each finding's box drawn on it, on a page of its own: which texts failed + * contrast is read from pixels, so the boxes never enter the composition's page. */ export async function captureOverviewShot( page: Page, annotations: CheckAnnotationBox[], - fallbackScreenshot: string, + overviewShot: string, ): Promise { - if (annotations.length === 0) return fallbackScreenshot; - await injectAnnotationOverlay(page, annotations); - try { - const shot = await page.screenshot({ encoding: "base64", type: "png" }); - return typeof shot === "string" ? shot : fallbackScreenshot; - } finally { - await removeAnnotationOverlay(page); - } + if (annotations.length === 0) return overviewShot; + return screenshotOnBlankPage(page, async (blank) => { + await blank.setContent( + ``, + ); + await injectAnnotationOverlay(blank, annotations); + }); } -/** One small, self-contained DOM overlay: fixed-position labeled boxes over - * each finding's bbox. Injected immediately before the annotated overview - * shot and torn down immediately after (see `captureOverviewShot`), so it - * never leaks into any audit's DOM reads. */ +/** Fixed-position labeled boxes over each finding's bbox. */ async function injectAnnotationOverlay(page: Page, boxes: CheckAnnotationBox[]): Promise { - await page.evaluate( - (items: CheckAnnotationBox[], overlayId: string) => { - const root = document.createElement("div"); - root.id = overlayId; - root.style.cssText = "position:fixed;inset:0;z-index:2147483647;pointer-events:none;"; - for (const item of items) { - const box = document.createElement("div"); - box.style.cssText = `position:fixed;left:${item.bbox.x}px;top:${item.bbox.y}px;width:${item.bbox.width}px;height:${item.bbox.height}px;border:2px solid #ff2d55;box-sizing:border-box;`; - const label = document.createElement("div"); - label.textContent = item.label; - label.style.cssText = - "position:absolute;top:-18px;left:0;background:#ff2d55;color:#fff;font:11px/16px monospace;padding:0 4px;white-space:nowrap;"; - box.appendChild(label); - root.appendChild(box); - } - document.body.appendChild(root); - }, - boxes, - ANNOTATION_OVERLAY_ID, - ); -} - -async function removeAnnotationOverlay(page: Page): Promise { - await page.evaluate((overlayId: string) => { - document.getElementById(overlayId)?.remove(); - }, ANNOTATION_OVERLAY_ID); + await page.evaluate((items: CheckAnnotationBox[]) => { + const root = document.createElement("div"); + root.style.cssText = "position:fixed;inset:0;z-index:2147483647;pointer-events:none;"; + for (const item of items) { + const box = document.createElement("div"); + box.style.cssText = `position:fixed;left:${item.bbox.x}px;top:${item.bbox.y}px;width:${item.bbox.width}px;height:${item.bbox.height}px;border:2px solid #ff2d55;box-sizing:border-box;`; + const label = document.createElement("div"); + label.textContent = item.label; + label.style.cssText = + "position:absolute;top:-18px;left:0;background:#ff2d55;color:#fff;font:11px/16px monospace;padding:0 4px;white-space:nowrap;"; + box.appendChild(label); + root.appendChild(box); + } + document.body.appendChild(root); + }, boxes); } async function prepareContrast(page: Page, time: number): Promise { @@ -2051,12 +2013,6 @@ async function prepareContrast(page: Page, time: number): Promise { }, time); } -interface TextRegion { - clip: { x: number; y: number; width: number; height: number }; - frameWidth: number; - frameHeight: number; -} - // The smallest whole-pixel rect holding every box contrast samples; undefined means the full frame. function plainFrame( viewport: { width: number; height: number; deviceScaleFactor?: number } | null, @@ -2073,120 +2029,22 @@ function textRegion( const boxes = prepared.map((entry) => entry.candidate.bbox); const x = Math.max(0, Math.floor(Math.min(...boxes.map((box) => box.x)))); const y = Math.max(0, Math.floor(Math.min(...boxes.map((box) => box.y)))); - const right = Math.min(viewport.width, Math.ceil(Math.max(...boxes.map((b) => b.x + b.width)))); - const bottom = Math.min( - viewport.height, - Math.ceil(Math.max(...boxes.map((b) => b.y + b.height))), - ); + const right = Math.min(viewport.width, Math.ceil(Math.max(...boxes.map((b) => b.x + b.w)))); + const bottom = Math.min(viewport.height, Math.ceil(Math.max(...boxes.map((b) => b.y + b.h)))); if (right <= x || bottom <= y) return undefined; const clip = { x, y, width: right - x, height: bottom - y }; return { clip, frameWidth: viewport.width, frameHeight: viewport.height }; } -async function finishContrast( - page: Page, - screenshot: string | null, - time: number, - candidates: unknown[], - region: TextRegion | undefined, -): Promise { - return page.evaluate( - async (payload: { - screenshot: string | null; - time: number; - candidates: unknown[]; - region: TextRegion | null; - }) => { - const finish = Reflect.get(window, "__contrastAuditFinish"); - if (typeof finish !== "function") return []; - const result = await Reflect.apply(finish, window, [ - payload.screenshot, - payload.time, - payload.candidates, - payload.region, - ]); - return Array.isArray(result) ? result : []; - }, - { screenshot, time, candidates, region: region ?? null }, - ); -} - function parsePreparedContrast( raw: unknown[], motion: (ContrastMotionSample | null)[], ): PreparedContrast[] { return raw.flatMap((value, index) => { if (!isRecord(value)) return []; - const raw = Reflect.get(value, "candidate"); - const candidate = parseContrastCandidate(raw); + const candidate = parseContrastCandidate(Reflect.get(value, "candidate")); const anchor = parseAnchor(Reflect.get(value, "anchor")); - return candidate && anchor - ? [ - { - raw, - candidate, - anchor, - knownBackdrop: knownBackdrop(raw), - motion: motion[index] ?? null, - }, - ] - : []; - }); -} - -function knownBackdrop(raw: unknown): boolean { - if (!isRecord(raw)) return false; - const own = Reflect.get(raw, "ownBg"); - const solid = Reflect.get(raw, "solidBg"); - return Array.isArray(solid) || (Array.isArray(own) && own.length >= 4 && own[3] >= 0.99); -} - -function parseContrastCandidate(value: unknown): ContrastCandidate | null { - if (!isRecord(value)) return null; - const selector = stringValue(value, "selector"); - const text = stringValue(value, "text"); - const fg = rgbaValue(Reflect.get(value, "fg")); - const large = booleanValue(value, "large"); - const bbox = parseBbox(Reflect.get(value, "bbox")); - return selector && text !== null && fg && large !== null && bbox - ? { selector, text, fg, large, bbox } - : null; -} - -function parseFinishedContrast(value: unknown): FinishedContrast[] { - if (!isRecord(value)) return []; - const selector = stringValue(value, "selector"); - const text = stringValue(value, "text"); - const ratio = numberValue(value, "ratio"); - const wcagAA = booleanValue(value, "wcagAA"); - const large = booleanValue(value, "large"); - const fg = stringValue(value, "fg"); - const bg = stringValue(value, "bg"); - return selector && - text !== null && - ratio !== null && - wcagAA !== null && - large !== null && - fg && - bg - ? [{ selector, text, ratio, wcagAA, large, fg, bg }] - : []; -} - -function joinContrastEntries( - finished: FinishedContrast[], - prepared: PreparedContrast[], -): ContrastAuditEntry[] { - const remaining = [...prepared]; - return finished.flatMap((entry) => { - const index = remaining.findIndex( - (candidate) => - candidate.candidate.selector === entry.selector && candidate.candidate.text === entry.text, - ); - const match = index >= 0 ? remaining.splice(index, 1)[0] : undefined; - if (!match) return []; - if (!entry.wcagAA && match.motion && measuredInMotion(match.motion)) return []; - return [{ ...entry, ...match.anchor }]; + return candidate && anchor ? [{ candidate, anchor, motion: motion[index] ?? null }] : []; }); } @@ -2474,12 +2332,15 @@ function urlPath(url: string): string { } } +/** All of a finding the page is handed. */ +export type ComponentFinding = Pick & { containerSelector?: string }; + export function matchComponentFindings({ components, findings, }: { components: string[]; - findings: CheckFinding[]; + findings: ComponentFinding[]; }): boolean[] { const roots = components.flatMap((selector) => { const matches = [...document.querySelectorAll(selector)]; @@ -2497,7 +2358,7 @@ export function matchComponentFindings({ } return findings.map((finding) => { if (!finding.selector || finding.selector === "[data-composition-id]") return true; - const container = Reflect.get(finding, "containerSelector"); + const container = finding.containerSelector; return ( matchesSelector(finding.selector) !== false || (typeof container === "string" && matchesSelector(container) !== false) diff --git a/packages/cli/src/utils/framePixels.test.ts b/packages/cli/src/utils/framePixels.test.ts new file mode 100644 index 00000000000..2cf039ba9e2 --- /dev/null +++ b/packages/cli/src/utils/framePixels.test.ts @@ -0,0 +1,48 @@ +import { encodePng } from "@hyperframes/engine/alpha-blit"; +import { describe, expect, it } from "vitest"; +import type { Rgba } from "../commands/contrast-bg.js"; +import { createFrameComparer, framePixels, isOneColor } from "./framePixels.js"; + +// A 20x20 frame of one colour, its first `marked` pixels another. +function frame(color: Rgba, marked = 0, mark: Rgba = [255, 255, 255, 255], width = 20): string { + const data = Uint8Array.from({ length: width * 20 * 4 }, (_, i) => + Math.floor(i / 4) < marked ? (mark[i % 4] ?? 0) : (color[i % 4] ?? 0), + ); + return encodePng(width, 20, data).toString("base64"); +} + +const BLACK: Rgba = [0, 0, 0, 255]; + +describe("createFrameComparer", () => { + it.each([ + ["the same frame", frame(BLACK), frame(BLACK), false], + ["15 changed pixels, as render noise", frame(BLACK), frame(BLACK, 15), false], + ["16 changed pixels", frame(BLACK), frame(BLACK, 16), true], + ["a change of 24, as render noise", frame(BLACK), frame([24, 24, 24, 255]), false], + ["a change of 25", frame(BLACK), frame([0, 25, 0, 255]), true], + ["paint told from the cleared page only by alpha", frame(BLACK), frame([0, 0, 0, 0]), true], + ["a frame of another size", frame(BLACK), frame(BLACK, 0, BLACK, 21), true], + ["nothing captured, then a frame", "", frame(BLACK), true], + ["nothing captured twice", "", "", false], + ])("reads %s", (_, first, second, differ) => { + expect(createFrameComparer()(first, second)).toBe(differ); + }); + + it("compares each frame with the reference it is given", () => { + const differ = createFrameComparer(); + const white = frame([255, 255, 255, 255]); + expect(differ(frame(BLACK), white)).toBe(true); + expect(differ(white, frame(BLACK))).toBe(true); + expect(differ(white, frame([250, 250, 250, 255]))).toBe(false); + }); +}); + +describe("isOneColor", () => { + it.each([ + ["the stage's own colour", frame([10, 20, 30, 255]), true], + ["another colour", frame([10, 80, 30, 255]), false], + ["something on the stage", frame([10, 20, 30, 255], 16), false], + ])("reads %s", (_, png, empty) => { + expect(isOneColor(framePixels(png), [10, 20, 30, 255])).toBe(empty); + }); +}); diff --git a/packages/cli/src/utils/framePixels.ts b/packages/cli/src/utils/framePixels.ts new file mode 100644 index 00000000000..4a0b99d5ef1 --- /dev/null +++ b/packages/cli/src/utils/framePixels.ts @@ -0,0 +1,60 @@ +import { decodePng } from "@hyperframes/engine/alpha-blit"; +import type { Rgba } from "../commands/contrast-bg.js"; + +// Screenshots are measured here, in Node: nothing read from one goes back into the composition's page. + +export interface FramePixels { + width: number; + height: number; + data: Uint8Array; +} + +export function framePixels(pngBase64: string): FramePixels { + return decodePng(Buffer.from(pngBase64, "base64")); +} + +// A frame moved when enough pixels changed by more than render noise (antialiasing, dither) on some channel. +// ponytail: fewer than FRAME_MIN_CHANGED_PIXELS changed pixels reads as still; lower it for tinier motion. +const FRAME_CHANNEL_NOISE = 24; +const FRAME_MIN_CHANGED_PIXELS = 16; + +/** Base64 PNG screenshots in, "did anything visible change" out. */ +export function createFrameComparer(): (first: string, second: string) => boolean { + // The first frame is usually a run's reference compared against many, so its decode is kept. + let reference: { png: string; pixels: FramePixels } | undefined; + return (first, second) => { + if (first === second) return false; + if (!first || !second) return true; + if (reference?.png !== first) reference = { png: first, pixels: framePixels(first) }; + return pixelsDiffer(reference.pixels, framePixels(second)); + }; +} + +function pixelsDiffer(first: FramePixels, second: FramePixels): boolean { + if (first.width !== second.width || first.height !== second.height) return true; + return differsFrom(first, (offset) => second.data[offset] ?? 0); +} + +export function isOneColor(frame: FramePixels, color: Rgba): boolean { + return !differsFrom(frame, (offset) => color[offset % 4] ?? 0); +} + +function differsFrom(frame: FramePixels, expected: (offset: number) => number): boolean { + const { data } = frame; + let changed = 0; + for (let i = 0; i < data.length; i += 4) { + if (pixelChanged(data, expected, i) && ++changed >= FRAME_MIN_CHANGED_PIXELS) return true; + } + return false; +} + +function pixelChanged( + data: Uint8Array, + expected: (offset: number) => number, + start: number, +): boolean { + for (let i = start; i < start + 4; i++) { + if (Math.abs((data[i] ?? 0) - expected(i)) > FRAME_CHANNEL_NOISE) return true; + } + return false; +} diff --git a/packages/cli/src/utils/screenshotsOutsidePage.chromium.test.ts b/packages/cli/src/utils/screenshotsOutsidePage.chromium.test.ts new file mode 100644 index 00000000000..f8992c30e8f --- /dev/null +++ b/packages/cli/src/utils/screenshotsOutsidePage.chromium.test.ts @@ -0,0 +1,285 @@ +// Real-Chromium pins: what a command measures from its screenshots is measured outside the composition's page. +// The film records every PNG, and every result read from one, that its page is handed. +// Skipped without a local Chrome; opt-in on Windows (HYPERFRAMES_BROWSER_TESTS=1), like the other Chromium suites. +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Browser, Page } from "puppeteer-core"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { findSystemBrowser } from "../browser/manager.js"; +import { captureMotionPathShot } from "../commands/motionShot.js"; +import { runContrastAudit } from "../commands/validate.js"; +import { createPageDriver } from "./checkBrowser.js"; +import { DEFAULT_CHECK_OPTIONS, runAuditGrid } from "./checkPipeline.js"; +import type { CheckOptions, MotionSpecResolution } from "./checkTypes.js"; + +function resolveExecutable(): string | undefined { + for (const name of ["HYPERFRAMES_BROWSER_PATH", "PUPPETEER_EXECUTABLE_PATH"]) { + const candidate = process.env[name]; + if (candidate && existsSync(candidate)) return candidate; + } + return findSystemBrowser()?.executablePath; +} + +const executablePath = resolveExecutable(); +const RUNS_CHROMIUM = + !!executablePath && + (process.platform !== "win32" || process.env.HYPERFRAMES_BROWSER_TESTS === "1"); +const BROWSER_LAUNCH_TIMEOUT_MS = 120_000; +const CASE_TIMEOUT_MS = 90_000; + +// Runs in the page before anything else, and again at every seek, so a receiver installed later is hooked too. +function recordHandedResults(report: string): void { + const pngStart = "iVBORw0KGgo"; + const seen = new Set(); + const note = (where: string) => { + if (seen.has(where)) return; + seen.add(where); + const request = new XMLHttpRequest(); + request.open("POST", report, false); + request.send(where); + }; + const holds = (value: unknown, depth = 0): boolean => { + if (typeof value === "string") + return value.includes(pngStart) || value.includes("contrast_aa_failure"); + if (typeof value !== "object" || value === null || depth > 4) return false; + if (value === window || value instanceof Node) return false; + if (typeof Reflect.get(value, "bg") === "string") return true; + return Object.values(value).some((entry) => holds(entry, depth + 1)); + }; + const hooked = new WeakSet(); + const hook = (owner: object, key: string, readsThis = false) => { + const original = Reflect.get(owner, key); + if (typeof original !== "function" || hooked.has(original)) return; + const wrapper = function (this: unknown, ...args: unknown[]) { + if (holds(args) || (readsThis && holds(this))) note(key); + return apply(original, this, args); + }; + hooked.add(wrapper); + Reflect.set(owner, key, wrapper); + }; + const apply = Reflect.apply; + const receivers = ["StageIsEmpty", "FramesDiffer"].map((name) => `__hyperframes${name}`); + receivers.push("__contrastAuditFinish"); + const hookReceivers = () => receivers.forEach((name) => hook(window, name)); + Reflect.set(window, "hookReceivers", hookReceivers); + hook(Reflect, "apply"); + hook(Array.prototype, "map", true); + hook(Element.prototype, "setAttribute"); + hook(Element.prototype, "insertAdjacentHTML"); + hook(CanvasRenderingContext2D.prototype, "putImageData"); + const source = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src"); + Object.defineProperty(HTMLImageElement.prototype, "src", { + ...source, + set(value: string) { + if (holds(value)) note("Image.src"); + source?.set?.call(this, value); + }, + }); + new MutationObserver((records) => { + for (const record of records) + for (const node of record.addedNodes) + if (node instanceof Element && node.localName !== "script" && holds(node.outerHTML)) + note("DOM"); + }).observe(document, { childList: true, subtree: true }); +} + +const TITLE = "position:absolute;left:80px;top:140px;margin:0;color:#fff;font:600 48px sans-serif"; + +// A 6 s film whose state at each seek is what `draw(t)` sets; `window.__hf` is the seek target the commands drive. +function film(report: string, body: string, draw: string): string { + return ` + + + +
${body}
+ + `; +} + +const CUTS = `show("a", t < 2); show("b", t >= 4);`; +const TWO_TITLES = `

Before

After

`; +const STILL_TITLE = `

Still

`; +// Low contrast over a gradient: only pixels tell its backdrop. +const DIM_TITLE = `
+

Dim words

`; +const MOVING_SVG = ``; + +describe.skipIf(!RUNS_CHROMIUM)("screenshots stay outside the composition's page", () => { + let browser: Browser; + let server: Server; + let report: string; + let handed: string[] = []; + + beforeAll(async () => { + const puppeteer = await import("puppeteer-core"); + browser = await puppeteer.default.launch({ + headless: true, + executablePath, + args: ["--no-sandbox", "--disable-dev-shm-usage", "--disable-gpu"], + }); + server = createServer((request, response) => { + let body = ""; + request.on("data", (chunk: Buffer) => (body += chunk.toString())); + request.on("end", () => { + handed.push(body); + response.writeHead(200, { "Access-Control-Allow-Origin": "*" }).end(); + }); + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + report = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; + }, BROWSER_LAUNCH_TIMEOUT_MS); + + afterAll(async () => { + await browser?.close(); + server?.closeAllConnections(); + server?.close(); + }); + + beforeEach(() => { + handed = []; + }); + + async function onPage(html: string, run: (page: Page) => Promise): Promise { + const page = await browser.newPage(); + try { + await page.setViewport({ width: 640, height: 360 }); + await page.setContent(html); + return await run(page); + } finally { + await page.close(); + } + } + + const audit = ( + html: string, + options: Partial, + motion: MotionSpecResolution = { kind: "none" }, + ) => + onPage(html, (page) => + runAuditGrid(createPageDriver(page), { ...DEFAULT_CHECK_OPTIONS, ...options }, motion), + ); + + it("records a PNG and a measured result its page is handed", async () => { + await onPage(film(report, STILL_TITLE, ""), async (page) => { + await page.evaluate(() => { + new Image().src = "data:image/png;base64,iVBORw0KGgo"; + Reflect.set(window, "__hyperframesFramesDiffer", () => false); + Reflect.get(window, "hookReceivers")(); + Reflect.get(window, "__hyperframesFramesDiffer")("iVBORw0KGgo", "iVBORw0KGgo"); + [{ bg: "rgb(1,2,3)" }].map(() => true); + }); + }); + expect(handed).toEqual(["Image.src", "__hyperframesFramesDiffer", "map"]); + }); + + it.each([true, false])( + "asks whether the stage is empty (contrast %s)", + async (contrast) => { + const result = await audit(film(report, TWO_TITLES, CUTS), { contrast }); + expect(result.craft.findings.map((finding) => finding.code)).toContain("blank_span"); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it( + "compares the frames of a film that never moves", + async () => { + const result = await audit(film(report, STILL_TITLE, ""), { contrast: false }); + expect(result.layoutIssues.map((issue) => issue.code)).toContain("sweep_static"); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it.each([undefined, "#root"])( + "compares the frames keepsMoving asks about (within %s)", + async (withinSelector) => { + const result = await audit( + film(report, STILL_TITLE, ""), + { contrast: false }, + { + kind: "valid", + path: "motion.json", + spec: { assertions: [{ kind: "keepsMoving", withinSelector, maxStaticSec: 1 }] }, + }, + ); + expect(result.motionIssues.map((issue) => issue.code)).toContain("motion_frozen"); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it( + "measures contrast under check's default flags", + async () => { + const result = await audit(film(report, DIM_TITLE, ""), {}); + expect(result.contrastFindings.map((finding) => finding.selector)).toContain("#a"); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it( + "marks contrast failures on the overview frame", + async () => { + const result = await audit(film(report, DIM_TITLE, ""), { snapshots: true }); + expect(result.contrastFindings).not.toEqual([]); + expect(result.screenshots).not.toEqual([]); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it( + "asks which findings belong to a component", + async () => { + const result = await audit(film(report, DIM_TITLE, ""), { components: ["#root"] }); + expect(result.contrastFindings.map((finding) => finding.componentMatch)).toContain(true); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it( + "measures contrast in validate", + async () => { + const entries = await onPage(film(report, DIM_TITLE, ""), runContrastAudit); + expect(entries.map((entry) => entry.selector)).toContain("#a"); + expect(handed).toEqual([]); + }, + CASE_TIMEOUT_MS, + ); + + it( + "lays out the keyframes filmstrip", + async () => { + const project = mkdtempSync(join(tmpdir(), "hf-strip-")); + try { + writeFileSync( + join(project, "index.html"), + film(report, MOVING_SVG, `document.getElementById("dot").setAttribute("x", t * 60);`), + ); + const out = join(project, "strip.png"); + await captureMotionPathShot(project, [{ selector: "#dot" }], out, { + layout: "strip", + samples: 3, + }); + expect(existsSync(out)).toBe(true); + expect(handed).toEqual([]); + } finally { + rmSync(project, { recursive: true, force: true }); + } + }, + CASE_TIMEOUT_MS, + ); +}); diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts index 8dcc1e8ae91..2d770edb3d4 100644 --- a/packages/cli/tsup.config.ts +++ b/packages/cli/tsup.config.ts @@ -106,6 +106,7 @@ var __dirname = __hf_dirname(__filename);`, ...sourceAliases(resolve(__dirname, "../producer"), [".", "./distributed"]), ...sourceAliases(resolve(__dirname, "../engine"), [ ".", + "./alpha-blit", "./chrome-host-ceiling", "./chrome-startup", "./network-policy",