From 478ef2f26e8b2811383d6e0e31b69efebf508148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Thu, 5 Nov 2026 19:03:31 +0000 Subject: [PATCH] fix(cli): check judges SVG gradient text by its gradient stops, not as black (#7258) --- .../src/commands/contrast-audit.browser.js | 64 +++++++++++++---- packages/cli/src/commands/contrast-fg.test.ts | 6 +- packages/cli/src/commands/contrast-fg.ts | 10 +-- .../contrast-svg-gradient.browser.test.ts | 71 +++++++++++++++++++ 4 files changed, 129 insertions(+), 22 deletions(-) create mode 100644 packages/cli/src/commands/contrast-svg-gradient.browser.test.ts diff --git a/packages/cli/src/commands/contrast-audit.browser.js b/packages/cli/src/commands/contrast-audit.browser.js index 854b0b6458..fa51384d50 100644 --- a/packages/cli/src/commands/contrast-audit.browser.js +++ b/packages/cli/src/commands/contrast-audit.browser.js @@ -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("."); @@ -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"); @@ -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, @@ -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 diff --git a/packages/cli/src/commands/contrast-fg.test.ts b/packages/cli/src/commands/contrast-fg.test.ts index 81e5bfd8fa..a45de15b2d 100644 --- a/packages/cli/src/commands/contrast-fg.test.ts +++ b/packages/cli/src/commands/contrast-fg.test.ts @@ -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", () => { diff --git a/packages/cli/src/commands/contrast-fg.ts b/packages/cli/src/commands/contrast-fg.ts index 2d55429520..6566b1063b 100644 --- a/packages/cli/src/commands/contrast-fg.ts +++ b/packages/cli/src/commands/contrast-fg.ts @@ -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; diff --git a/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts b/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts new file mode 100644 index 0000000000..b06de0db1b --- /dev/null +++ b/packages/cli/src/commands/contrast-svg-gradient.browser.test.ts @@ -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 = ` +
+ + + + + + + + Light gradient + Dim gradient + Borrowed stops + Pattern fill + +
`; +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((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);