Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions packages/cli/src/commands/blank-span.browser.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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);
};
})();
19 changes: 0 additions & 19 deletions packages/cli/src/commands/check.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { runCommand } from "citty";
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
Expand Down Expand Up @@ -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 },
Expand Down Expand Up @@ -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;
Expand Down
167 changes: 2 additions & 165 deletions packages/cli/src/commands/contrast-audit.browser.js
Original file line number Diff line number Diff line change
@@ -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 () {
Expand Down Expand Up @@ -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;
};
21 changes: 2 additions & 19 deletions packages/cli/src/commands/contrast-bg.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down
20 changes: 11 additions & 9 deletions packages/cli/src/commands/contrast-clip.browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `<!doctype html><html><body style="margin:0">
Expand Down Expand Up @@ -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);
Expand Down
63 changes: 63 additions & 0 deletions packages/cli/src/commands/contrast-measure.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof frame> | 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();
});
});
Loading
Loading