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
64 changes: 50 additions & 14 deletions packages/cli/src/commands/contrast-audit.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,28 @@ window.__contrastAuditPrepare = function () {
return [p[0], p[1], p[2], p[3] != null ? p[3] : 1];
}

// The colours a url(#id) fill paints (gradient stops, through href); [] when it names no gradient.
function gradientStops(fill) {
var ref = /^url\("?[^"#)]*#([^")]+)"?\)/.exec(fill || "");
if (!ref) return null;
var grad = document.getElementById(ref[1]);
for (var hops = 0; grad && hops < 8; hops++) {
if (!/^(linear|radial)Gradient$/.test(grad.localName)) return [];
var stops = grad.querySelectorAll(":scope > stop");
if (stops.length) return Array.prototype.map.call(stops, stopColor).filter(Boolean);
var href = grad.getAttribute("href") || grad.getAttribute("xlink:href") || "";
grad = href.charAt(0) === "#" ? document.getElementById(href.slice(1)) : null;
}
return [];
}

function stopColor(stop) {
var stopStyle = getComputedStyle(stop);
var color = parseColor(stopStyle.stopColor);
if (color) color[3] *= parseFloat(stopStyle.stopOpacity);
return color && color[3] > 0.01 ? color : null;
}

function selectorOf(el) {
if (el.id) return "#" + el.id;
var cls = Array.from(el.classList).slice(0, 2).join(".");
Expand Down Expand Up @@ -369,14 +391,16 @@ window.__contrastAuditPrepare = function () {
// is actually covered; the same copy is audited normally when visible.
if (isIntentionallyOccluded(el, rect)) continue;

// For SVG text, `fill` is the paint that's actually rendered; `color` is
// frequently just the inherited/initial value and unrelated to what's on
// screen. Only trust `fill` when it resolves to a solid color — "none",
// "context-fill", and gradient/pattern refs (url(#...)) fall back to
// `color` rather than crashing parseColor or reporting a fabricated
// black.
// SVG text paints `fill`, not `color`. A gradient fill is judged by its weakest stop; a pattern
// or a missing reference has no colour to judge, so the text is skipped.
var isSvgText = isSvgTextElement(el);
var fg = isSvgText ? parseColor(cs.fill) || parseColor(cs.color) : parseColor(cs.color);
var fgStops = isSvgText ? gradientStops(cs.fill) : null;
if (fgStops && !fgStops.length) continue;
var fg = fgStops
? fgStops[0]
: isSvgText
? parseColor(cs.fill) || parseColor(cs.color)
: parseColor(cs.color);
if (!fg) continue;
if (fg[3] <= 0.01) continue;
var strokeWidth = parseFloat(cs.webkitTextStrokeWidth || "0");
Expand Down Expand Up @@ -448,6 +472,7 @@ window.__contrastAuditPrepare = function () {
selector: selectorOf(el),
text: (el.textContent || "").trim().slice(0, 50),
fg: fg,
fgStops: fgStops,
stroke: stroke,
fontSize: fontSize,
fontWeight: fontWeight,
Expand Down Expand Up @@ -603,13 +628,24 @@ window.__contrastAuditFinish = async function (imgBase64, time, candidates, regi
bgB = median(bb);
}

// Composite foreground alpha over the measured background
var fg = c.fg;
var compR = Math.round(fg[0] * fg[3] + bgR * (1 - fg[3]));
var compG = Math.round(fg[1] * fg[3] + bgG * (1 - fg[3]));
var compB = Math.round(fg[2] * fg[3] + bgB * (1 - fg[3]));

var ratio = +wcagRatio(compR, compG, compB, bgR, bgG, bgB).toFixed(2);
// 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
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/src/commands/contrast-fg.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ describe("resolveForegroundColor", () => {
).toEqual([0, 255, 0, 1]);
});

it("falls back to `color` when fill is a gradient/pattern reference", () => {
it("never reads `color` for a gradient/pattern fill: the glyphs are not painted with it", () => {
expect(
resolveForegroundColor({ isSvgText: true, fill: 'url("#grad")', color: "rgb(0, 255, 0)" }),
).toEqual([0, 255, 0, 1]);
resolveForegroundColor({ isSvgText: true, fill: 'url("#grad")', color: "rgb(0, 0, 0)" }),
).toBeNull();
});

it("never crashes on garbage fill values", () => {
Expand Down
10 changes: 5 additions & 5 deletions packages/cli/src/commands/contrast-fg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ import { parseColorRGBA, type Rgba } from "./contrast-bg.js";
*
* - For ordinary HTML text, this is always the computed `color`.
* - For SVG text, the rendered glyph color is `fill`, not `color`. `fill` is
* only trusted when it resolves to a solid rgb()/rgba() color — SVG paint
* keywords ("none", "context-fill") and gradient/pattern references
* (`url(#...)`) are not colors, so those fall back to `color` instead of
* fabricating black.
* only trusted when it resolves to a solid rgb()/rgba() color; SVG paint
* keywords ("none", "context-fill") fall back to `color`.
* - A `url(#...)` fill is null: the audit judges a gradient by its stops and skips anything else.
*/
export function resolveForegroundColor(opts: {
isSvgText: boolean;
fill: string;
color: string;
}): Rgba {
}): Rgba | null {
if (opts.isSvgText && opts.fill.startsWith("url(")) return null;
if (opts.isSvgText) {
const solid = parseColorRGBA(opts.fill);
if (solid) return solid;
Expand Down
71 changes: 71 additions & 0 deletions packages/cli/src/commands/contrast-svg-gradient.browser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { readFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
import { afterAll, beforeAll, expect, it } from "vitest";
import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js";

const TEXT = `x="20" font-family="sans-serif" font-weight="700" font-size="40"`;
const HTML = `<!doctype html><html><body style="margin:0">
<div data-composition-id="main" data-width="640" data-height="360" data-duration="1"
style="position:relative;width:640px;height:360px;background:#0b0b14">
<svg width="640" height="360" style="position:absolute;left:0;top:0">
<defs>
<linearGradient id="light"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#e3f6ff"/></linearGradient>
<linearGradient id="dim"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#202030"/></linearGradient>
<linearGradient id="borrowed" href="#light" x1="0" x2="0" y2="1"/>
<pattern id="dots" width="4" height="4" patternUnits="userSpaceOnUse"><rect width="2" height="2" fill="#fff"/></pattern>
</defs>
<text id="light-text" ${TEXT} y="60" fill="url(#light)">Light gradient</text>
<text id="dim-text" ${TEXT} y="140" fill="url(#dim)">Dim gradient</text>
<text id="borrowed-text" ${TEXT} y="220" fill="url(#borrowed)">Borrowed stops</text>
<text id="pattern-text" ${TEXT} y="300" fill="url(#dots)">Pattern fill</text>
</svg>
</div><script>window.__renderReady = true;</script></body></html>`;
const SCRIPT = readFileSync(join(import.meta.dirname, "contrast-audit.browser.js"), "utf8");

let server: Server;
let url: string;

beforeAll(async () => {
server = createServer((_req, res) =>
res.writeHead(200, { "Content-Type": "text/html" }).end(HTML),
);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
});

afterAll(() => {
server.closeAllConnections();
server.close();
});

// fails without the fix: a url(#gradient) fill was read as `color` (black), so near-white text failed at 1.07:1.
it("judges SVG gradient text by its stops and skips a pattern fill", async () => {
const { browser, page } = await openSettledCompositionPage(HTML, url, {
renderReadyTimeoutMs: 5_000,
renderReadyWarningSuffix: "test",
browserGpuMode: "software",
});
try {
await page.addScriptTag({ content: SCRIPT });
const candidates = await page.evaluate("window.__contrastAuditPrepare()");
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 bySelector = Object.fromEntries(
entries.map(({ selector, fg, wcagAA }) => [selector, { fg, wcagAA }]),
);
expect(bySelector).toEqual({
"#light-text": { fg: "rgb(227,246,255)", wcagAA: true },
"#dim-text": { fg: "rgb(32,32,48)", wcagAA: false },
"#borrowed-text": { fg: "rgb(227,246,255)", wcagAA: true },
});
} finally {
await browser.close();
}
}, 90_000);
Loading