Skip to content

Commit 478ef2f

Browse files
fix(cli): check judges SVG gradient text by its gradient stops, not as black (#7258)
1 parent 7290ee6 commit 478ef2f

4 files changed

Lines changed: 129 additions & 22 deletions

File tree

‎packages/cli/src/commands/contrast-audit.browser.js‎

Lines changed: 50 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,28 @@ window.__contrastAuditPrepare = function () {
188188
return [p[0], p[1], p[2], p[3] != null ? p[3] : 1];
189189
}
190190

191+
// The colours a url(#id) fill paints (gradient stops, through href); [] when it names no gradient.
192+
function gradientStops(fill) {
193+
var ref = /^url\("?[^"#)]*#([^")]+)"?\)/.exec(fill || "");
194+
if (!ref) return null;
195+
var grad = document.getElementById(ref[1]);
196+
for (var hops = 0; grad && hops < 8; hops++) {
197+
if (!/^(linear|radial)Gradient$/.test(grad.localName)) return [];
198+
var stops = grad.querySelectorAll(":scope > stop");
199+
if (stops.length) return Array.prototype.map.call(stops, stopColor).filter(Boolean);
200+
var href = grad.getAttribute("href") || grad.getAttribute("xlink:href") || "";
201+
grad = href.charAt(0) === "#" ? document.getElementById(href.slice(1)) : null;
202+
}
203+
return [];
204+
}
205+
206+
function stopColor(stop) {
207+
var stopStyle = getComputedStyle(stop);
208+
var color = parseColor(stopStyle.stopColor);
209+
if (color) color[3] *= parseFloat(stopStyle.stopOpacity);
210+
return color && color[3] > 0.01 ? color : null;
211+
}
212+
191213
function selectorOf(el) {
192214
if (el.id) return "#" + el.id;
193215
var cls = Array.from(el.classList).slice(0, 2).join(".");
@@ -369,14 +391,16 @@ window.__contrastAuditPrepare = function () {
369391
// is actually covered; the same copy is audited normally when visible.
370392
if (isIntentionallyOccluded(el, rect)) continue;
371393

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

606-
// Composite foreground alpha over the measured background
607-
var fg = c.fg;
608-
var compR = Math.round(fg[0] * fg[3] + bgR * (1 - fg[3]));
609-
var compG = Math.round(fg[1] * fg[3] + bgG * (1 - fg[3]));
610-
var compB = Math.round(fg[2] * fg[3] + bgB * (1 - fg[3]));
611-
612-
var ratio = +wcagRatio(compR, compG, compB, bgR, bgG, bgB).toFixed(2);
631+
// Composite foreground alpha over the measured background; a gradient's weakest stop sets the ratio.
632+
var compR = 0,
633+
compG = 0,
634+
compB = 0,
635+
ratio = Infinity;
636+
var fills = c.fgStops || [c.fg];
637+
for (var pi = 0; pi < fills.length; pi++) {
638+
var fg = fills[pi];
639+
var paintR = Math.round(fg[0] * fg[3] + bgR * (1 - fg[3]));
640+
var paintG = Math.round(fg[1] * fg[3] + bgG * (1 - fg[3]));
641+
var paintB = Math.round(fg[2] * fg[3] + bgB * (1 - fg[3]));
642+
var paintRatio = +wcagRatio(paintR, paintG, paintB, bgR, bgG, bgB).toFixed(2);
643+
if (paintRatio >= ratio) continue;
644+
compR = paintR;
645+
compG = paintG;
646+
compB = paintB;
647+
ratio = paintRatio;
648+
}
613649

614650
// A solid text stroke is part of the visible glyph paint. Use whichever
615651
// of fill or stroke provides the stronger edge contrast, rather than

‎packages/cli/src/commands/contrast-fg.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,10 @@ describe("resolveForegroundColor", () => {
4747
).toEqual([0, 255, 0, 1]);
4848
});
4949

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

5656
it("never crashes on garbage fill values", () => {

‎packages/cli/src/commands/contrast-fg.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,16 @@ import { parseColorRGBA, type Rgba } from "./contrast-bg.js";
2121
*
2222
* - For ordinary HTML text, this is always the computed `color`.
2323
* - For SVG text, the rendered glyph color is `fill`, not `color`. `fill` is
24-
* only trusted when it resolves to a solid rgb()/rgba() color — SVG paint
25-
* keywords ("none", "context-fill") and gradient/pattern references
26-
* (`url(#...)`) are not colors, so those fall back to `color` instead of
27-
* fabricating black.
24+
* only trusted when it resolves to a solid rgb()/rgba() color; SVG paint
25+
* keywords ("none", "context-fill") fall back to `color`.
26+
* - A `url(#...)` fill is null: the audit judges a gradient by its stops and skips anything else.
2827
*/
2928
export function resolveForegroundColor(opts: {
3029
isSvgText: boolean;
3130
fill: string;
3231
color: string;
33-
}): Rgba {
32+
}): Rgba | null {
33+
if (opts.isSvgText && opts.fill.startsWith("url(")) return null;
3434
if (opts.isSvgText) {
3535
const solid = parseColorRGBA(opts.fill);
3636
if (solid) return solid;
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { readFileSync } from "node:fs";
2+
import { createServer, type Server } from "node:http";
3+
import type { AddressInfo } from "node:net";
4+
import { join } from "node:path";
5+
import { afterAll, beforeAll, expect, it } from "vitest";
6+
import { openSettledCompositionPage } from "../capture/captureCompositionFrame.js";
7+
8+
const TEXT = `x="20" font-family="sans-serif" font-weight="700" font-size="40"`;
9+
const HTML = `<!doctype html><html><body style="margin:0">
10+
<div data-composition-id="main" data-width="640" data-height="360" data-duration="1"
11+
style="position:relative;width:640px;height:360px;background:#0b0b14">
12+
<svg width="640" height="360" style="position:absolute;left:0;top:0">
13+
<defs>
14+
<linearGradient id="light"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#e3f6ff"/></linearGradient>
15+
<linearGradient id="dim"><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#202030"/></linearGradient>
16+
<linearGradient id="borrowed" href="#light" x1="0" x2="0" y2="1"/>
17+
<pattern id="dots" width="4" height="4" patternUnits="userSpaceOnUse"><rect width="2" height="2" fill="#fff"/></pattern>
18+
</defs>
19+
<text id="light-text" ${TEXT} y="60" fill="url(#light)">Light gradient</text>
20+
<text id="dim-text" ${TEXT} y="140" fill="url(#dim)">Dim gradient</text>
21+
<text id="borrowed-text" ${TEXT} y="220" fill="url(#borrowed)">Borrowed stops</text>
22+
<text id="pattern-text" ${TEXT} y="300" fill="url(#dots)">Pattern fill</text>
23+
</svg>
24+
</div><script>window.__renderReady = true;</script></body></html>`;
25+
const SCRIPT = readFileSync(join(import.meta.dirname, "contrast-audit.browser.js"), "utf8");
26+
27+
let server: Server;
28+
let url: string;
29+
30+
beforeAll(async () => {
31+
server = createServer((_req, res) =>
32+
res.writeHead(200, { "Content-Type": "text/html" }).end(HTML),
33+
);
34+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
35+
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
36+
});
37+
38+
afterAll(() => {
39+
server.closeAllConnections();
40+
server.close();
41+
});
42+
43+
// fails without the fix: a url(#gradient) fill was read as `color` (black), so near-white text failed at 1.07:1.
44+
it("judges SVG gradient text by its stops and skips a pattern fill", async () => {
45+
const { browser, page } = await openSettledCompositionPage(HTML, url, {
46+
renderReadyTimeoutMs: 5_000,
47+
renderReadyWarningSuffix: "test",
48+
browserGpuMode: "software",
49+
});
50+
try {
51+
await page.addScriptTag({ content: SCRIPT });
52+
const candidates = await page.evaluate("window.__contrastAuditPrepare()");
53+
const shot = await page.screenshot({ encoding: "base64", omitBackground: true });
54+
const entries = (await page.evaluate(
55+
(png: string, items: unknown) =>
56+
Reflect.apply(Reflect.get(window, "__contrastAuditFinish"), window, [png, 0, items, null]),
57+
shot,
58+
candidates,
59+
)) as { selector: string; fg: string; wcagAA: boolean }[];
60+
const bySelector = Object.fromEntries(
61+
entries.map(({ selector, fg, wcagAA }) => [selector, { fg, wcagAA }]),
62+
);
63+
expect(bySelector).toEqual({
64+
"#light-text": { fg: "rgb(227,246,255)", wcagAA: true },
65+
"#dim-text": { fg: "rgb(32,32,48)", wcagAA: false },
66+
"#borrowed-text": { fg: "rgb(227,246,255)", wcagAA: true },
67+
});
68+
} finally {
69+
await browser.close();
70+
}
71+
}, 90_000);

0 commit comments

Comments
 (0)