From 8d3339b0c01820d9b08c33e911411c40f08014b9 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Mon, 2 Nov 2026 21:13:35 +0000 Subject: [PATCH 1/4] feat(docs-theme): add a protanopia and deuteranopia palette Red-green color vision deficiency pulls the tip, warning and caution callouts, and the Early Access and Deprecated pills, close together under simulation. The labels and icons still carry the meaning, but the hues should not mislead. `data-color-vision="protan-deuter"` on now recolors the callout and state pill tokens and the green code colors, using the hues of the Coder dashboard's protan-deuter themes (teal and sky for success, orange for error, magenta for warning) re-tuned to 7:1 text contrast, so the palette also holds with More contrast on. The html prefix lets the overrides beat the More pill rules without depending on source order. contrast:check gains the callout colors, a color-vision palette, and a color-vision over More palette, and still fails on a rule it cannot place. A Machado 2009 simulation with CIEDE2000 pins every callout, pill background and diff color at least 10 apart under both deficiencies. Assisted-by: AI --- apps/dist-release/src/config.mjs | 2 +- apps/dist-release/src/contents.test.mjs | 1 + packages/docs-theme/README.md | 8 + .../docs-theme/scripts/color-vision.test.mjs | 168 ++++++++++++++++++ packages/docs-theme/scripts/contrast.mjs | 123 ++++++++++--- packages/docs-theme/scripts/cvd.mjs | 96 ++++++++++ packages/docs-theme/src/color-vision.css | 59 ++++++ packages/docs-theme/src/index.css | 1 + 8 files changed, 434 insertions(+), 24 deletions(-) create mode 100644 packages/docs-theme/scripts/color-vision.test.mjs create mode 100644 packages/docs-theme/scripts/cvd.mjs create mode 100644 packages/docs-theme/src/color-vision.css diff --git a/apps/dist-release/src/config.mjs b/apps/dist-release/src/config.mjs index ac0ba25c..70862688 100644 --- a/apps/dist-release/src/config.mjs +++ b/apps/dist-release/src/config.mjs @@ -22,7 +22,7 @@ export const LICENSE = { // What each tarball may hold besides package.json, README.md and LICENSE, whatever its `files` says. export const PACKAGE_ALLOW = { default: ["dist/"], - "docs-theme": ["src/index.css", "src/brand.css", "assets/"], + "docs-theme": ["src/index.css", "src/brand.css", "src/color-vision.css", "assets/"], }; export const KIT_NAME = "coder-docs-builder"; diff --git a/apps/dist-release/src/contents.test.mjs b/apps/dist-release/src/contents.test.mjs index 1736a934..6b0fb0bc 100644 --- a/apps/dist-release/src/contents.test.mjs +++ b/apps/dist-release/src/contents.test.mjs @@ -85,6 +85,7 @@ test("the allowlist comes from config, not from the package's files field", () = checkPackageEntries("docs-theme", [ "package/src/index.css", "package/src/brand.css", + "package/src/color-vision.css", "package/assets/favicons/favicon-dark.svg", "package/src/tokens.ts", ]), diff --git a/packages/docs-theme/README.md b/packages/docs-theme/README.md index 9d03e442..8ca61aec 100644 --- a/packages/docs-theme/README.md +++ b/packages/docs-theme/README.md @@ -29,6 +29,10 @@ The theme references host-owned resources it deliberately does not ship: `data-contrast="more"` or `data-motion="reduced"` forces the rule on, and `data-contrast="standard"` or `data-motion="full"` forces it off. The host sets the attributes before first paint by rendering `DisplayPreferencesScript` from `@coder/docs-next` in its root layout's ``. Write every new preference rule in both forms; `scripts/preference-overrides.test.mjs` fails when one is missing. +- **Color vision.** `data-color-vision="protan-deuter"` on `` applies `src/color-vision.css`, which recolors the callout and state pill tokens and the green code colors for readers with protanopia or deuteranopia. + No browser setting reports this, so the preference has no media query and no "follow the system" state: a missing attribute is the standard palette. + Every rule in that file starts with `html:root[data-color-vision="protan-deuter"]`, which out-ranks the More contrast rules, so the palette also holds with More contrast on. + `scripts/color-vision.test.mjs` keeps every callout color, state pill background, and diff color at least 10 CIEDE2000 apart under simulated protanopia and deuteranopia. - **Fonts.** The stack is `Geist Variable` / `Geist Mono Variable` with a system fallback. The theme ships no font files, so the app must load the faces or the fallback applies. `apps/docs` and `apps/offlinedocs` import `@fontsource-variable/geist` and `@fontsource-variable/geist-mono` in their `global.css`. @@ -54,8 +58,12 @@ pnpm test # the contrast checker's tests and the preference-rule che `scripts/contrast.mjs` reads the light (`:root`) and dark (`.dark`) `--color-fd-*` and `--docs-state-*` tokens from `src/brand.css` and `src/index.css` and measures the WCAG contrast ratio of each critical pair: body, muted, link, button, card, popover, hover-row and state-pill text at 4.5:1, and the focus ring at 3:1. It also measures every foreground color of the Shiki themes named in `@coder/docs-transforms` against the code-block surfaces (`card` and `secondary`) at 4.5:1. +It checks each callout type color on the page and on its 9% tint, both at 4.5:1. + It checks the More palette too: the same pairs and code colors with the `:root[data-contrast="more"]:not(.dark)` and `:root[data-contrast="more"].dark` overrides applied, at WCAG AAA. More mode keeps the Shiki themes and recolors only the code tokens below 7:1, with `[style*="--shiki-light:#..."]` rules that set the token's variable; the checker reads those rules and measures the replacement colors. +The color-vision palette is checked the same way, once on its own at AA and once layered over More at AAA (`color-vision` and `color-vision more` in the output), with the code-color replacements in `color-vision.css` measured too. +A rule in `color-vision.css` that sets theme tokens under any selector other than the three the checker reads fails the run, as a More rule does. CI runs it on every pull request and fails on any standard pair below AA or More pair below AAA that is not in `.github/a11y-allowlist.json`. Every line prints the pair's AA and AAA verdicts beside its ratio. diff --git a/packages/docs-theme/scripts/color-vision.test.mjs b/packages/docs-theme/scripts/color-vision.test.mjs new file mode 100644 index 00000000..50dc197c --- /dev/null +++ b/packages/docs-theme/scripts/color-vision.test.mjs @@ -0,0 +1,168 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; +import postcss from "postcss"; +import { + applyAllowlist, + loadAllowlist, + loadShikiTheme, + loadThemeCss, + parseCodeOverrides, + parseColor, + parseColorVisionPalettes, + parsePalettes, + resultId, + runContrastCheck, +} from "./contrast.mjs"; +import { deltaE2000, simulate, simulatedDistance } from "./cvd.mjs"; + +const MIN_DISTANCE = 10; +const CALLOUTS = ["info", "success", "idea", "warning", "error"]; +const TONES = ["purple", "sky", "orange", "red", "teal"]; +const CV = 'html:root[data-color-vision="protan-deuter"]'; + +const css = await loadThemeCss(); +const { standard, more } = parsePalettes(css); +const vision = parseColorVisionPalettes(css); + +function pairs(names) { + return names.flatMap((a, i) => names.slice(i + 1).map((b) => [a, b])); +} + +test("simulation leaves greys alone and pulls red and green together", () => { + const grey = simulate([128, 128, 128], "deuteranopia"); + for (const c of grey) assert.ok(Math.abs(c - 128) < 1, `grey stays grey: ${grey}`); + const red = [200, 30, 30]; + const green = [30, 140, 60]; + assert.ok(deltaE2000(red, green) > 50); + assert.ok(simulatedDistance(red, green) < 20); + assert.throws(() => simulate(red, "tritanopia"), /Unknown/); +}); + +test("CIEDE2000 is zero for one color and about 100 between black and white", () => { + assert.equal(deltaE2000([10, 20, 30], [10, 20, 30]), 0); + const d = deltaE2000([0, 0, 0], [255, 255, 255]); + assert.ok(d > 99 && d < 101, String(d)); +}); + +for (const mode of ["light", "dark"]) { + test(`every ${mode} callout color is ${MIN_DISTANCE} CIEDE2000 from every other under protanopia and deuteranopia`, () => { + for (const [a, b] of pairs(CALLOUTS)) { + const d = simulatedDistance( + parseColor(vision.standard[mode][a]), + parseColor(vision.standard[mode][b]), + ); + assert.ok(d >= MIN_DISTANCE, `${mode} ${a} vs ${b}: ${d.toFixed(1)}`); + } + }); + + test(`every ${mode} state pill background is ${MIN_DISTANCE} CIEDE2000 from every other under protanopia and deuteranopia`, () => { + for (const [a, b] of pairs(TONES)) { + const d = simulatedDistance( + parseColor(vision.standard[mode][`state-${a}-bg`]), + parseColor(vision.standard[mode][`state-${b}-bg`]), + ); + assert.ok(d >= MIN_DISTANCE, `${mode} ${a} vs ${b} pill: ${d.toFixed(1)}`); + } + }); + + test(`More contrast keeps the ${mode} color-vision callouts and pills`, () => { + for (const token of [...CALLOUTS, ...TONES.flatMap((t) => [`state-${t}-bg`, `state-${t}-fg`])]) + assert.equal(vision.more[mode][token], vision.standard[mode][token], token); + }); +} + +test("the color-vision palette changes callouts and pills and nothing else", () => { + for (const mode of ["light", "dark"]) { + const changed = Object.keys(vision.standard[mode]).filter( + (k) => vision.standard[mode][k] !== standard[mode][k], + ); + assert.deepEqual( + changed.filter((k) => !CALLOUTS.includes(k) && !k.startsWith("state-")), + [], + `${mode} overrides only callout and pill tokens`, + ); + assert.ok(changed.length >= CALLOUTS.length + TONES.length * 2, mode); + } +}); + +test("the color-vision More palette starts from the More palette", () => { + for (const mode of ["light", "dark"]) + assert.equal( + vision.more[mode]["muted-foreground"], + more[mode]["muted-foreground"], + `${mode} keeps the More muted text`, + ); +}); + +test("color-vision layers apply plain, then mode-scoped, over a base palette", () => { + const sheet = `:root { --color-fd-success: #111; --color-fd-error: #111; } +.dark { --color-fd-success: #eee; --color-fd-error: #eee; } +${CV} { --color-fd-success: #00f; --color-fd-error: #00f; } +${CV}:not(.dark) { --color-fd-error: #01f; } +${CV}.dark { --color-fd-error: #99f; }`; + const { standard: s } = parseColorVisionPalettes(sheet); + assert.deepEqual(s.light, { success: "#00f", error: "#01f" }); + assert.deepEqual(s.dark, { success: "#00f", error: "#99f" }); +}); + +test("a color-vision rule that sets tokens under a selector the check can't place throws", () => { + const sheet = `:root { --color-fd-success: #111; }\n.dark { --color-fd-success: #eee; }\n${CV} .x { --color-fd-success: #00f; }`; + assert.throws(() => parseColorVisionPalettes(sheet), /sets theme tokens/); +}); + +test("every theme-token and code-color rule in color-vision.css is scoped to the color-vision attribute", () => { + let checked = 0; + const own = postcss.parse( + readFileSync(new URL("../src/color-vision.css", import.meta.url), "utf8"), + ); + own.walkRules((rule) => { + const setsColour = rule.nodes.some( + (n) => n.type === "decl" && /^--(color-fd-|docs-state-|shiki-)/.test(n.prop), + ); + if (!setsColour) return; + assert.ok( + rule.selectors.every((s) => s.replace(/\s+/g, " ").startsWith(CV)), + rule.selector, + ); + checked++; + }); + assert.ok(checked > 0); +}); + +test("color-vision rules out-rank the More contrast pill rules by specificity, not source order", () => { + assert.match(CV, /^html:root/); +}); + +for (const mode of ["light", "dark"]) { + test(`${mode} diff additions and deletions in code stay ${MIN_DISTANCE} apart under protanopia and deuteranopia`, async () => { + const theme = await loadShikiTheme(mode); + const scoped = (scope) => + theme.tokenColors.find((t) => [].concat(t.scope).includes(scope)).settings.foreground; + const overrides = parseCodeOverrides(css, CV)[mode]; + const shown = (color) => overrides[color.toLowerCase()] ?? color; + const inserted = shown(scoped("markup.inserted")); + const deleted = shown(scoped("markup.deleted")); + assert.notEqual(inserted.toLowerCase(), scoped("markup.inserted").toLowerCase()); + const d = simulatedDistance(parseColor(inserted), parseColor(deleted)); + assert.ok( + d >= MIN_DISTANCE, + `${mode} inserted ${inserted} vs deleted ${deleted}: ${d.toFixed(1)}`, + ); + const keyword = shown(scoped("keyword")); + const tag = shown(scoped("entity.name.tag")); + const k = simulatedDistance(parseColor(keyword), parseColor(tag)); + assert.ok(k >= MIN_DISTANCE, `${mode} keyword ${keyword} vs tag ${tag}: ${k.toFixed(1)}`); + }); +} + +test("the color-vision palettes meet AA, and AAA with More contrast, on every pair and code token", async () => { + const results = (await runContrastCheck()).filter((r) => r.palette.startsWith("color-vision")); + assert.ok(results.some((r) => r.palette === "color-vision")); + assert.ok(results.some((r) => r.palette === "color-vision-more")); + const { failures } = applyAllowlist(results, await loadAllowlist()); + assert.deepEqual( + failures.map((r) => `${resultId(r)} ${r.ratio.toFixed(2)} < ${r.min}`), + [], + ); +}); diff --git a/packages/docs-theme/scripts/contrast.mjs b/packages/docs-theme/scripts/contrast.mjs index 442ba6dc..d286c047 100644 --- a/packages/docs-theme/scripts/contrast.mjs +++ b/packages/docs-theme/scripts/contrast.mjs @@ -27,6 +27,11 @@ export const PAIRS = [ { name: "focus ring on card", fg: "ring", bg: "card", kind: "ui" }, { name: "social icon", fg: "foreground", bg: "muted", kind: "ui" }, { name: "social icon on hover", fg: "background", bg: "foreground", kind: "ui" }, + ...["info", "success", "idea", "warning", "error"].flatMap((type) => [ + { name: `${type} callout title`, fg: type, bg: "background", kind: "text" }, + // The callout paints a 9% tint of its type color; More contrast draws it on the page instead. + { name: `${type} callout title on tint`, fg: type, bg: "background", tint: 0.09, kind: "text" }, + ]), ...["purple", "sky", "orange", "red", "teal"].map((tone) => ({ name: `${tone} state pill`, fg: `state-${tone}-fg`, @@ -72,6 +77,11 @@ export function contrastRatio(a, b) { return (hi + 0.05) / (lo + 0.05); } +// color-mix(in srgb, , ) +export function tintOver(fg, bg, amount) { + return fg.map((c, i) => Math.round(c * amount + bg[i] * (1 - amount))); +} + function blockTokens(css, selector) { const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const blocks = [...css.matchAll(new RegExp(`(?:^|\\n)${escaped}\\s*\\{([^}]*)\\}`, "g"))]; @@ -103,12 +113,19 @@ const MORE_LAYERS = [ [`${MORE}.dark`, ["dark"]], ]; -// The More palette is the standard one with the forced More overrides on top; the media twins must match them. -export function parsePalettes(css) { - const standard = parseThemeTokens(css); - const layers = new Map(MORE_LAYERS.map(([selector]) => [selector, {}])); +const CV = 'html:root[data-color-vision="protan-deuter"]'; + +// Same cascade order as More: a plain block applies to both modes, and the mode-scoped blocks beat it. +const CV_LAYERS = [ + [CV, ["light", "dark"]], + [`${CV}:not(.dark)`, ["light"]], + [`${CV}.dark`, ["dark"]], +]; + +function collectLayers(css, root, layerDefs) { + const layers = new Map(layerDefs.map(([selector]) => [selector, {}])); postcss.parse(css).walkRules((rule) => { - if (rule.parent.type !== "root" || !rule.selector.startsWith(MORE)) return; + if (rule.parent.type !== "root" || !rule.selector.startsWith(root)) return; const tokens = {}; rule.walkDecls(TOKEN, (decl) => { tokens[decl.prop.match(TOKEN)[1]] = decl.value.trim(); @@ -121,19 +138,40 @@ export function parsePalettes(css) { ); Object.assign(layer, tokens); }); - const more = (mode) => + return layers; +} + +function applyLayers(base, layerDefs, layers) { + return (mode) => Object.assign( - { ...standard[mode] }, - ...MORE_LAYERS.filter(([, modes]) => modes.includes(mode)).map(([s]) => layers.get(s)), + { ...base[mode] }, + ...layerDefs.filter(([, modes]) => modes.includes(mode)).map(([s]) => layers.get(s)), ); +} + +// The More palette is the standard one with the forced More overrides on top; the media twins must match them. +export function parsePalettes(css) { + const standard = parseThemeTokens(css); + const more = applyLayers(standard, MORE_LAYERS, collectLayers(css, MORE, MORE_LAYERS)); return { standard, more: { light: more("light"), dark: more("dark") } }; } +// The color-vision overrides sit on top of both the standard and the More palette. +export function parseColorVisionPalettes(css) { + const { standard, more } = parsePalettes(css); + const layers = collectLayers(css, CV, CV_LAYERS); + const on = (base) => { + const apply = applyLayers(base, CV_LAYERS, layers); + return { light: apply("light"), dark: apply("dark") }; + }; + return { standard: on(standard), more: on(more) }; +} + // Shiki writes `--shiki-light:#abc` on the server and `--shiki-light: #abc` after client navigation. -export function parseCodeOverrides(css) { +export function parseCodeOverrides(css, root = MORE) { const overrides = { light: {}, dark: {} }; postcss.parse(css).walkRules((rule) => { - if (rule.parent.type !== "root" || !rule.selector.startsWith(MORE)) return; + if (rule.parent.type !== "root" || !rule.selector.startsWith(root)) return; rule.walkDecls(/^--shiki-(light|dark)$/, (decl) => { const mode = decl.prop.slice("--shiki-".length); const found = [ @@ -156,16 +194,24 @@ function verdicts(ratio, kind) { return { ratio, min: aa, pass: ratio >= aa, aaaMin: aaa, aaaPass: ratio >= aaa }; } +export const isMorePalette = (palette) => palette === "more" || palette === "color-vision-more"; + export function checkPairs(tokens, pairs, palette = "standard") { + const drawn = pairs.filter((pair) => !(pair.tint && isMorePalette(palette))); return Object.entries(tokens).flatMap(([mode, values]) => - pairs.map(({ name, fg, bg, kind }) => ({ - palette, - mode, - name, - fg: values[fg], - bg: values[bg], - ...verdicts(contrastRatio(parseColor(values[fg]), parseColor(values[bg])), kind), - })), + drawn.map(({ name, fg, bg, kind, tint }) => { + const bgColor = tint + ? tintOver(parseColor(values[fg]), parseColor(values[bg]), tint) + : parseColor(values[bg]); + return { + palette, + mode, + name, + fg: values[fg], + bg: tint ? `${tint * 100}% ${values[fg]} over ${values[bg]}` : values[bg], + ...verdicts(contrastRatio(parseColor(values[fg]), bgColor), kind), + }; + }), ); } @@ -205,10 +251,18 @@ export function checkCodeTokens(tokens, shikiThemes, overrides = {}, palette = " }); } -export const resultId = (r) => `contrast ${r.palette === "more" ? "more " : ""}${r.mode} ${r.name}`; +const PALETTE_IDS = { + standard: "", + more: "more ", + "color-vision": "color-vision ", + "color-vision-more": "color-vision more ", +}; + +export const resultId = (r) => + `contrast ${PALETTE_IDS[r.palette ?? "standard"]}${r.mode} ${r.name}`; // Standard contrast must meet AA; More contrast must meet AAA. -export const meetsTarget = (r) => (r.palette === "more" ? r.aaaPass : r.pass); +export const meetsTarget = (r) => (isMorePalette(r.palette) ? r.aaaPass : r.pass); export function applyAllowlist(results, entries) { const allowed = new Set(entries.map((entry) => entry.replace(/^pr-\d+ /, ""))); @@ -247,18 +301,29 @@ export async function loadShikiTheme(mode) { export async function loadThemeCss() { const read = (file) => readFile(new URL(`../src/${file}`, import.meta.url), "utf8"); - return (await Promise.all(["brand.css", "index.css"].map(read))).join("\n"); + return (await Promise.all(["brand.css", "index.css", "color-vision.css"].map(read))).join("\n"); } export async function runContrastCheck() { const css = await loadThemeCss(); const { standard, more } = parsePalettes(css); + const colorVision = parseColorVisionPalettes(css); const shiki = { light: await loadShikiTheme("light"), dark: await loadShikiTheme("dark") }; + const moreCode = parseCodeOverrides(css); + const visionCode = parseCodeOverrides(css, CV); + const visionMoreCode = { + light: { ...moreCode.light, ...visionCode.light }, + dark: { ...moreCode.dark, ...visionCode.dark }, + }; return [ ...checkPairs(standard, PAIRS), ...checkCodeTokens(standard, shiki), ...checkPairs(more, PAIRS, "more"), - ...checkCodeTokens(more, shiki, parseCodeOverrides(css), "more"), + ...checkCodeTokens(more, shiki, moreCode, "more"), + ...checkPairs(colorVision.standard, PAIRS, "color-vision"), + ...checkCodeTokens(colorVision.standard, shiki, visionCode, "color-vision"), + ...checkPairs(colorVision.more, PAIRS, "color-vision-more"), + ...checkCodeTokens(colorVision.more, shiki, visionMoreCode, "color-vision-more"), ]; } @@ -283,7 +348,12 @@ export function formatResult(r, { level, known }) { // --level aaa --enforce fails on every AAA miss, allowlisted or not, so nothing is "known" there. const mark = ok ? "ok " : known && level === "aa" ? "known" : "FAIL "; const detail = r.scopes ? ` (${r.scopes.slice(0, 3).join(", ")})` : ` [${r.fg} on ${r.bg}]`; - const mode = r.palette === "more" ? `more ${r.mode}` : r.mode; + const mode = { + standard: "", + more: "more ", + "color-vision": "cv ", + "color-vision-more": "cv more ", + }[r.palette ?? "standard"].concat(r.mode); return `${mark} ${mode.padEnd(10)} ${r.ratio.toFixed(2).padStart(5)}:1 AA ${aa} (${r.min}) AAA ${aaa} (${r.aaaMin}) ${r.name}${detail}`; } @@ -310,6 +380,13 @@ async function main() { `\nStandard: ${aa}/${standard.length} pairs meet WCAG AA; ${aaa}/${standard.length} meet AAA${options.level === "aaa" && !options.enforce ? " (report only; add --enforce to fail on it)" : ""}.`, ); console.log(`More: ${moreAaa}/${more.length} pairs meet WCAG AAA.`); + for (const palette of ["color-vision", "color-vision-more"]) { + const set = results.filter((r) => r.palette === palette); + const met = set.filter(meetsTarget).length; + console.log( + `${palette}: ${met}/${set.length} pairs meet WCAG ${isMorePalette(palette) ? "AAA" : "AA"}.`, + ); + } console.log(`${allowed.length} known failures allowlisted, ${failures.length} new.`); process.exitCode = exitCode({ newFailures: failures.length, results }, options); } diff --git a/packages/docs-theme/scripts/cvd.mjs b/packages/docs-theme/scripts/cvd.mjs new file mode 100644 index 00000000..5af5b366 --- /dev/null +++ b/packages/docs-theme/scripts/cvd.mjs @@ -0,0 +1,96 @@ +// Color-vision simulation (Machado et al. 2009, severity 1.0, in linear sRGB) and CIEDE2000. +const MATRICES = { + protanopia: [ + [0.152286, 1.052583, -0.204868], + [0.114503, 0.786281, 0.099216], + [-0.003882, -0.048116, 1.051998], + ], + deuteranopia: [ + [0.367322, 0.860646, -0.227968], + [0.280085, 0.672501, 0.047413], + [-0.01182, 0.04294, 0.968881], + ], +}; + +export const SIMULATIONS = Object.keys(MATRICES); + +const toLinear = (c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4); + +function fromLinear(c) { + const v = Math.min(1, Math.max(0, c)); + return (v <= 0.0031308 ? 12.92 * v : 1.055 * v ** (1 / 2.4) - 0.055) * 255; +} + +/** The sRGB triple a reader with the given deficiency sees for `rgb` (0-255 channels). */ +export function simulate(rgb, kind) { + const matrix = MATRICES[kind]; + if (!matrix) throw new Error(`Unknown color-vision simulation: ${kind}`); + const lin = rgb.map((c) => toLinear(c / 255)); + return matrix.map((row) => fromLinear(row[0] * lin[0] + row[1] * lin[1] + row[2] * lin[2])); +} + +function toLab(rgb) { + const [r, g, b] = rgb.map((c) => toLinear(c / 255)); + const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047; + const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b; + const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883; + const f = (t) => (t > 216 / 24389 ? Math.cbrt(t) : ((24389 / 27) * t + 16) / 116); + const [fx, fy, fz] = [f(x), f(y), f(z)]; + return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)]; +} + +/** CIEDE2000 color difference between two sRGB triples. */ +export function deltaE2000(rgb1, rgb2) { + const [l1, a1, b1] = toLab(rgb1); + const [l2, a2, b2] = toLab(rgb2); + const rad = Math.PI / 180; + const deg = 180 / Math.PI; + const cMean = (Math.hypot(a1, b1) + Math.hypot(a2, b2)) / 2; + const g = 0.5 * (1 - Math.sqrt(cMean ** 7 / (cMean ** 7 + 25 ** 7))); + const a1p = (1 + g) * a1; + const a2p = (1 + g) * a2; + const c1p = Math.hypot(a1p, b1); + const c2p = Math.hypot(a2p, b2); + const hue = (b, a) => { + const h = Math.atan2(b, a) * deg; + return h >= 0 ? h : h + 360; + }; + const h1p = c1p === 0 ? 0 : hue(b1, a1p); + const h2p = c2p === 0 ? 0 : hue(b2, a2p); + let dh = 0; + if (c1p * c2p !== 0) { + dh = h2p - h1p; + if (dh > 180) dh -= 360; + else if (dh < -180) dh += 360; + } + const dL = l2 - l1; + const dC = c2p - c1p; + const dH = 2 * Math.sqrt(c1p * c2p) * Math.sin((dh * rad) / 2); + const lMean = (l1 + l2) / 2; + const cpMean = (c1p + c2p) / 2; + let hMean = h1p + h2p; + if (c1p * c2p !== 0) { + hMean = + Math.abs(h1p - h2p) > 180 + ? (h1p + h2p + (h1p + h2p < 360 ? 360 : -360)) / 2 + : (h1p + h2p) / 2; + } + const t = + 1 - + 0.17 * Math.cos((hMean - 30) * rad) + + 0.24 * Math.cos(2 * hMean * rad) + + 0.32 * Math.cos((3 * hMean + 6) * rad) - + 0.2 * Math.cos((4 * hMean - 63) * rad); + const dTheta = 30 * Math.exp(-(((hMean - 275) / 25) ** 2)); + const rc = 2 * Math.sqrt(cpMean ** 7 / (cpMean ** 7 + 25 ** 7)); + const sl = 1 + (0.015 * (lMean - 50) ** 2) / Math.sqrt(20 + (lMean - 50) ** 2); + const sc = 1 + 0.045 * cpMean; + const sh = 1 + 0.015 * cpMean * t; + const rt = -Math.sin(2 * dTheta * rad) * rc; + return Math.sqrt((dL / sl) ** 2 + (dC / sc) ** 2 + (dH / sh) ** 2 + rt * (dC / sc) * (dH / sh)); +} + +/** The smaller CIEDE2000 distance between two colors across the red-green simulations. */ +export function simulatedDistance(rgb1, rgb2) { + return Math.min(...SIMULATIONS.map((k) => deltaE2000(simulate(rgb1, k), simulate(rgb2, k)))); +} diff --git a/packages/docs-theme/src/color-vision.css b/packages/docs-theme/src/color-vision.css new file mode 100644 index 00000000..20a25c86 --- /dev/null +++ b/packages/docs-theme/src/color-vision.css @@ -0,0 +1,59 @@ +/* Color vision (protanopia and deuteranopia); the `html` prefix out-ranks the More contrast pill rules in index.css. */ + +/* Callout type colors and state pills. */ +html:root[data-color-vision="protan-deuter"]:not(.dark) { + --color-fd-info: #272a5c; + --color-fd-success: #06607e; + --color-fd-idea: #480ab0; + --color-fd-warning: #621035; + --color-fd-error: #76370c; + --docs-state-purple-bg: #bf9df8; + --docs-state-purple-fg: #2b1949; + --docs-state-sky-bg: #acd3e3; + --docs-state-sky-fg: #0a2531; + --docs-state-orange-bg: #fbe1b7; + --docs-state-orange-fg: #48320e; + --docs-state-red-bg: #e3afad; + --docs-state-red-fg: #421e1d; + --docs-state-teal-bg: #d0f9ef; + --docs-state-teal-fg: #145345; +} + +html:root[data-color-vision="protan-deuter"].dark { + --color-fd-info: #a1bff3; + --color-fd-success: #32d6cc; + --color-fd-idea: #b882ec; + --color-fd-warning: #d981a6; + --color-fd-error: #fd8660; + --docs-state-purple-bg: #530ba4; + --docs-state-purple-fg: #e1c8fd; + --docs-state-sky-bg: #122d3f; + --docs-state-sky-fg: #d4ebfb; + --docs-state-orange-bg: #6e3f0b; + --docs-state-orange-fg: #fbe9d5; + --docs-state-red-bg: #460b09; + --docs-state-red-fg: #e8c5c3; + --docs-state-teal-bg: #0a5344; + --docs-state-teal-fg: #cffdf3; +} + +/* Code: green becomes blue, so diff additions and tags differ from deletions and keywords. */ +html:root[data-color-vision="protan-deuter"] + :is([style*="--shiki-light:#024c1a" i], [style*="--shiki-light: #024c1a" i]) { + --shiki-light: #0a5670 !important; +} + +html:root[data-color-vision="protan-deuter"] + :is([style*="--shiki-dark:#7ee787" i], [style*="--shiki-dark: #7ee787" i]) { + --shiki-dark: #a5f3fc !important; +} + +/* Display settings: this row's long label gets one full-width option per line. */ +.docs-segmented[data-layout="stacked"] { + grid-template-columns: minmax(0, 1fr); +} + +.docs-segmented[data-layout="stacked"] .docs-segment { + justify-content: flex-start; + padding-inline: 0.5rem; +} diff --git a/packages/docs-theme/src/index.css b/packages/docs-theme/src/index.css index be22c0c3..12134516 100644 --- a/packages/docs-theme/src/index.css +++ b/packages/docs-theme/src/index.css @@ -15,6 +15,7 @@ */ @import "./brand.css"; +@import "./color-vision.css"; /* * Reserve the scrollbar gutter so the page width does not shift when a route From f59c1de33e1f62a18d9d95338e0822b19b8d7af6 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Mon, 2 Nov 2026 21:13:35 +0000 Subject: [PATCH 2/4] feat: add a color vision setting to the display settings The panel gets a Color vision row, Standard or Protanopia and deuteranopia, stored as docs-color-vision and mirrored onto as data-color-vision by the same inline head script that carries contrast and motion, so it applies before first paint on the docs site and the offline export. There is no system option, because browsers expose no signal for it; a missing attribute is the standard palette. The axe pass scans the pages with callouts, state pills, check and cross icons and a diff in the new mode, with and without More contrast, and the open panel in it. The states fixture now carries a pill of every tone and the code fixture a diff block. Assisted-by: AI --- apps/docs/README.md | 3 +- apps/docs/fixtures/docs/authoring/code.md | 8 ++++ apps/docs/fixtures/docs/authoring/states.md | 2 +- apps/docs/fixtures/docs/manifest.json | 2 +- apps/docs/scripts/a11y-axe-helpers.mjs | 18 ++++++++- apps/docs/scripts/a11y-axe.mjs | 28 ++++++++++++-- apps/docs/scripts/a11y-axe.test.mjs | 36 ++++++++++++++++++ .../src/display-preferences.test.tsx | 18 +++++++++ .../docs-next/src/display-preferences.tsx | 8 +++- .../docs-next/src/display-settings.test.tsx | 37 ++++++++++++++++++- packages/docs-next/src/display-settings.tsx | 21 ++++++++++- packages/docs-next/src/index.ts | 1 + 12 files changed, 169 insertions(+), 13 deletions(-) diff --git a/apps/docs/README.md b/apps/docs/README.md index 840ca32e..79ff89f4 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -637,7 +637,8 @@ Unpause the project only after that setting is on `main`, or the next push to `m The pages are `/`, `/admin/users`, `/admin/reference`, `/@0.1/admin`, and the `/authoring` section, whose pages carry tabs (with labels of several words), fenced code in several languages with comments, wide tables (two of them under one heading), a table with an empty header cell and a ✅/❌ support matrix, every callout type with inline code in it (some highlighted), feature-state pills, a GFM task list, and an image with alt text. Two of them, `/` and `/authoring/tables`, are also scanned at a 390px mobile viewport with touch, in both modes, as `mobile-light` and `mobile-dark`. Every desktop page is also scanned with the Contrast setting on More, as `more-light` and `more-dark`, with axe's `color-contrast-enhanced` rule on, so More is held to WCAG AAA contrast (7:1 for text). -The open search dialog is scanned in every mode, and the open display settings popover in the four desktop modes, as `/#search` and `/#settings`. +The pages with callouts, state pills, ✅/❌ and a diff (`/authoring/callouts`, `/authoring/states`, `/authoring/code`, `/authoring/tables`) are scanned again with Color vision on Protanopia and deuteranopia, as `vision-light` and `vision-dark`, and with More contrast on top, as `vision-more-light` and `vision-more-dark`. +The open search dialog is scanned in every desktop and mobile mode, and the open display settings popover in the four desktop modes and the four color vision modes, as `/#search` and `/#settings`. It fails on any WCAG violation not listed in `.github/a11y-allowlist.json`. Each entry is ` axe `, where the owner is `pr-` for the open pull request that fixes it, or `tracked-` for a known failure whose fix has no pull request yet. diff --git a/apps/docs/fixtures/docs/authoring/code.md b/apps/docs/fixtures/docs/authoring/code.md index ad6c0e71..1dce9b54 100644 --- a/apps/docs/fixtures/docs/authoring/code.md +++ b/apps/docs/fixtures/docs/authoring/code.md @@ -76,3 +76,11 @@ No highlighting here. ``` Inline code such as `coder server --help` sits in running text. + +## Diff + +```diff +- replicaCount: 1 ++ replicaCount: 2 + image: codercom/coder +``` diff --git a/apps/docs/fixtures/docs/authoring/states.md b/apps/docs/fixtures/docs/authoring/states.md index 49a7994e..ba594356 100644 --- a/apps/docs/fixtures/docs/authoring/states.md +++ b/apps/docs/fixtures/docs/authoring/states.md @@ -2,4 +2,4 @@ A page tagged with feature states in the manifest, so its title carries the state pills. -The feature is in early access and beta at once, which exercises two pill tones side by side. +The page carries a pill of every tone, early access, beta, deprecated, enterprise, and premium, side by side. diff --git a/apps/docs/fixtures/docs/manifest.json b/apps/docs/fixtures/docs/manifest.json index 31d05b83..0ca94d3e 100644 --- a/apps/docs/fixtures/docs/manifest.json +++ b/apps/docs/fixtures/docs/manifest.json @@ -29,7 +29,7 @@ { "title": "Feature states", "path": "./authoring/states.md", - "state": ["early access", "beta"] + "state": ["early access", "beta", "deprecated", "enterprise", "premium"] } ] } diff --git a/apps/docs/scripts/a11y-axe-helpers.mjs b/apps/docs/scripts/a11y-axe-helpers.mjs index ae25d4dc..1a9822e2 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -47,6 +47,16 @@ export const MODES = ["light", "dark"]; export const MOBILE_MODES = MODES.map((mode) => `mobile-${mode}`); // The More contrast setting, held to WCAG AAA contrast. export const MORE_MODES = MODES.map((mode) => `more-${mode}`); +// The color vision setting (protanopia and deuteranopia), alone and with More contrast. +export const VISION_MODES = MODES.map((mode) => `vision-${mode}`); +export const VISION_MORE_MODES = MODES.map((mode) => `vision-more-${mode}`); +// The pages with callouts, state pills, ✅/❌ and a diff, where the setting recolors content. +export const COLOR_VISION_PAGES = [ + "/authoring/callouts", + "/authoring/states", + "/authoring/code", + "/authoring/tables", +]; const AAA_CONTRAST_RULE = "color-contrast-enhanced"; export const MOBILE_VIEWPORT = { width: 390, height: 844 }; @@ -91,9 +101,13 @@ export const violationId = (mode, page, rule) => `axe ${mode} ${page} ${rule}`; export const idOf = (v) => violationId(v.mode, v.page, v.rule); -export const colorSchemeOf = (mode) => mode.replace(/^(?:mobile|more)-/, ""); +export const colorSchemeOf = (mode) => mode.replace(/^(?:mobile-|more-|vision-more-|vision-)/, ""); + +export const contrastOf = (mode) => + MORE_MODES.includes(mode) || VISION_MORE_MODES.includes(mode) ? "more" : undefined; -export const contrastOf = (mode) => (MORE_MODES.includes(mode) ? "more" : undefined); +export const colorVisionOf = (mode) => + VISION_MODES.includes(mode) || VISION_MORE_MODES.includes(mode) ? "protan-deuter" : undefined; export function axeOptions(mode) { return { diff --git a/apps/docs/scripts/a11y-axe.mjs b/apps/docs/scripts/a11y-axe.mjs index 9cbffadb..84c8bfc1 100644 --- a/apps/docs/scripts/a11y-axe.mjs +++ b/apps/docs/scripts/a11y-axe.mjs @@ -5,6 +5,7 @@ import { DEFAULT_MOBILE_PAGES, MOBILE_MODES, MOBILE_VIEWPORT, + COLOR_VISION_PAGES, MODES, MORE_MODES, SEARCH_LABEL, @@ -13,9 +14,12 @@ import { SETTINGS_LABEL, SWITCHER_DOCUMENT, SWITCHER_LABEL, + VISION_MODES, + VISION_MORE_MODES, applyAllowlist, axeOptions, colorSchemeOf, + colorVisionOf, contrastOf, parseArgs, splitBestPractice, @@ -77,6 +81,7 @@ async function scan({ }) { const scheme = colorSchemeOf(mode); const contrast = contrastOf(mode); + const colorVision = colorVisionOf(mode); const mobile = MOBILE_MODES.includes(mode) ? { viewport: MOBILE_VIEWPORT, isMobile: true, hasTouch: true, deviceScaleFactor: 3 } : {}; @@ -84,6 +89,12 @@ async function scan({ // The key is DISPLAY_PREFERENCES.contrast.storageKey in docs-next; the data-contrast check below catches a drift. if (contrast) await context.addInitScript((value) => localStorage.setItem("docs-contrast", value), contrast); + // Likewise DISPLAY_PREFERENCES.colorVision.storageKey, with the data-color-vision check below. + if (colorVision) + await context.addInitScript( + (value) => localStorage.setItem("docs-color-vision", value), + colorVision, + ); try { const page = await context.newPage(); if (switcher) @@ -93,8 +104,13 @@ async function scan({ const rendered = await page.evaluate(() => ({ dark: document.documentElement.classList.contains("dark"), contrast: document.documentElement.getAttribute("data-contrast") ?? undefined, + colorVision: document.documentElement.getAttribute("data-color-vision") ?? undefined, })); - if (rendered.dark !== (scheme === "dark") || rendered.contrast !== contrast) + if ( + rendered.dark !== (scheme === "dark") || + rendered.contrast !== contrast || + rendered.colorVision !== colorVision + ) throw new Error(`${pagePath} did not render in ${mode} mode`); await page.addScriptTag({ content: axeSource }); if (search) await openSearchWithMatch(page); @@ -138,15 +154,21 @@ async function main() { executablePath: options.chromium ?? process.env.A11Y_CHROMIUM ?? undefined, }); const desktopModes = [...MODES, ...MORE_MODES]; + const visionModes = [...VISION_MODES, ...VISION_MORE_MODES]; const runs = [ ...options.pages.flatMap((page) => desktopModes.map((mode) => ({ page, mode }))), + ...COLOR_VISION_PAGES.flatMap((page) => visionModes.map((mode) => ({ page, mode }))), ...mobilePages.flatMap((page) => MOBILE_MODES.map((mode) => ({ page, mode }))), ...[...desktopModes, ...MOBILE_MODES].map((mode) => ({ page: SEARCH_PAGE, mode, search: true, })), - ...desktopModes.map((mode) => ({ page: SEARCH_PAGE, mode, settings: true })), + ...[...desktopModes, ...visionModes].map((mode) => ({ + page: SEARCH_PAGE, + mode, + settings: true, + })), ...desktopModes.map((mode) => ({ page: SEARCH_PAGE, mode, switcher: true })), ]; const found = []; @@ -175,7 +197,7 @@ async function main() { } for (const entry of stale) console.log(`stale allowlist entry, remove it: ${entry}`); console.log( - `\n${runs.length} scans (${options.pages.length} pages x ${desktopModes.length} modes, ${mobilePages.length} x ${MOBILE_MODES.length} at ${MOBILE_VIEWPORT.width}px, the open search dialog in all ${desktopModes.length + MOBILE_MODES.length}, and the open display settings and version switcher in ${desktopModes.length} each): ` + + `\n${runs.length} scans (${options.pages.length} pages x ${desktopModes.length} modes, ${COLOR_VISION_PAGES.length} x ${visionModes.length} with color vision on, ${mobilePages.length} x ${MOBILE_MODES.length} at ${MOBILE_VIEWPORT.width}px, the open search dialog in all ${desktopModes.length + MOBILE_MODES.length}, and the open display settings in all ${desktopModes.length + visionModes.length}, and the open version switcher in ${desktopModes.length}): ` + `${violations.length} WCAG rule violations, ${allowed.length} allowlisted, ${failures.length} new; ` + `${bestPractice.length} best-practice findings (reported, not failing).`, ); diff --git a/apps/docs/scripts/a11y-axe.test.mjs b/apps/docs/scripts/a11y-axe.test.mjs index 6b9b721e..171b2ba7 100644 --- a/apps/docs/scripts/a11y-axe.test.mjs +++ b/apps/docs/scripts/a11y-axe.test.mjs @@ -6,7 +6,10 @@ import { test } from "node:test"; import { DEFAULT_MOBILE_PAGES, DEFAULT_PAGES, + COLOR_VISION_PAGES, MORE_MODES, + VISION_MODES, + VISION_MORE_MODES, SEARCH_LABEL, SEARCH_PAGE, SEARCH_QUERY, @@ -15,6 +18,7 @@ import { applyAllowlist, axeOptions, colorSchemeOf, + colorVisionOf, contrastOf, idOf, parseArgs, @@ -169,6 +173,38 @@ test("More contrast modes scan both color schemes with the AAA contrast rule ena assert.deepEqual(axeOptions("light").runOnly, axeOptions("more-light").runOnly); }); +test("color vision modes scan both color schemes, standard and More, on the pages that carry color", () => { + assert.deepEqual(VISION_MODES, ["vision-light", "vision-dark"]); + assert.deepEqual(VISION_MORE_MODES, ["vision-more-light", "vision-more-dark"]); + for (const mode of [...VISION_MODES, ...VISION_MORE_MODES]) + assert.equal(colorVisionOf(mode), "protan-deuter", mode); + assert.deepEqual([...VISION_MODES, ...VISION_MORE_MODES].map(colorSchemeOf), [ + "light", + "dark", + "light", + "dark", + ]); + assert.deepEqual(VISION_MORE_MODES.map(contrastOf), ["more", "more"]); + assert.equal(contrastOf("vision-light"), undefined); + assert.equal(colorVisionOf("more-dark"), undefined); + assert.equal(colorVisionOf("light"), undefined); + assert.deepEqual(axeOptions("vision-more-dark").rules, { + "color-contrast-enhanced": { enabled: true }, + }); + assert.equal(axeOptions("vision-dark").rules, undefined); + for (const page of COLOR_VISION_PAGES) assert.ok(DEFAULT_PAGES.includes(page), page); + for (const page of [ + "/authoring/callouts", + "/authoring/states", + "/authoring/code", + "/authoring/tables", + ]) + assert.ok( + COLOR_VISION_PAGES.includes(page), + `${page} carries callouts, pills, a diff or ✅/❌`, + ); +}); + test("splitBestPractice fails the AAA contrast rule", () => { const { wcag } = splitBestPractice([ { rule: "color-contrast-enhanced", tags: ["cat.color", "wcag2aaa", "wcag146"] }, diff --git a/packages/docs-next/src/display-preferences.test.tsx b/packages/docs-next/src/display-preferences.test.tsx index 87f91ff5..f339cb95 100644 --- a/packages/docs-next/src/display-preferences.test.tsx +++ b/packages/docs-next/src/display-preferences.test.tsx @@ -13,6 +13,7 @@ afterEach(() => { if (storageDescriptor) Object.defineProperty(globalThis, "localStorage", storageDescriptor); localStorage.clear(); document.documentElement.removeAttribute("data-contrast"); + document.documentElement.removeAttribute("data-color-vision"); document.documentElement.removeAttribute("data-motion"); document.documentElement.removeAttribute("class"); }); @@ -62,6 +63,23 @@ test("an unknown stored value is ignored", () => { assert.equal(html.hasAttribute("data-motion"), false); }); +test("a stored color-vision choice is copied onto , and anything else is ignored", () => { + localStorage.setItem("docs-color-vision", "protan-deuter"); + assert.equal(runRenderedScript().getAttribute("data-color-vision"), "protan-deuter"); + document.documentElement.removeAttribute("data-color-vision"); + for (const stored of ["tritan", "Protan-Deuter", "", "system"]) { + localStorage.setItem("docs-color-vision", stored); + assert.equal(runRenderedScript().hasAttribute("data-color-vision"), false, stored); + } +}); + +test("color vision uses its own key and leaves contrast and motion alone", () => { + localStorage.setItem("docs-color-vision", "protan-deuter"); + const html = runRenderedScript(); + assert.equal(html.hasAttribute("data-contrast"), false); + assert.equal(html.hasAttribute("data-motion"), false); +}); + test("one preference set leaves the other off", () => { localStorage.setItem("docs-motion", "reduced"); const html = runRenderedScript(); diff --git a/packages/docs-next/src/display-preferences.tsx b/packages/docs-next/src/display-preferences.tsx index f34deb49..9efc3dee 100644 --- a/packages/docs-next/src/display-preferences.tsx +++ b/packages/docs-next/src/display-preferences.tsx @@ -8,11 +8,17 @@ export const DISPLAY_PREFERENCES = { attribute: "data-contrast", values: ["standard", "more"], }, + colorVision: { + storageKey: "docs-color-vision", + attribute: "data-color-vision", + values: ["standard", "protan-deuter"], + }, motion: MOTION_PREFERENCE, } as const; export type DisplayPreference = keyof typeof DISPLAY_PREFERENCES; export type ContrastPreference = (typeof DISPLAY_PREFERENCES.contrast.values)[number]; +export type ColorVisionPreference = (typeof DISPLAY_PREFERENCES.colorVision.values)[number]; export type MotionPreference = (typeof DISPLAY_PREFERENCES.motion.values)[number]; /** The next-themes key and the only values the theme layer accepts; anything else is cleared before it can reach ``. */ @@ -22,7 +28,7 @@ export const THEME_PREFERENCE = { } as const; /** Clears an unrecognised stored theme, then copies the stored preferences onto `` before first paint; a storage error means follow the system. */ -export const DISPLAY_PREFERENCES_SCRIPT = `(function(){var d=document.documentElement;var t=["theme",["system","light","dark"]];try{var s=localStorage.getItem(t[0]);if(s!==null&&t[1].indexOf(s)<0)localStorage.removeItem(t[0])}catch(e){}[["docs-contrast","data-contrast",["standard","more"]],["docs-motion","data-motion",["full","reduced"]]].forEach(function(p){try{var v=localStorage.getItem(p[0]);if(p[2].indexOf(v)>=0)d.setAttribute(p[1],v)}catch(e){}})})()`; +export const DISPLAY_PREFERENCES_SCRIPT = `(function(){var d=document.documentElement;var t=["theme",["system","light","dark"]];try{var s=localStorage.getItem(t[0]);if(s!==null&&t[1].indexOf(s)<0)localStorage.removeItem(t[0])}catch(e){}[["docs-contrast","data-contrast",["standard","more"]],["docs-color-vision","data-color-vision",["standard","protan-deuter"]],["docs-motion","data-motion",["full","reduced"]]].forEach(function(p){try{var v=localStorage.getItem(p[0]);if(p[2].indexOf(v)>=0)d.setAttribute(p[1],v)}catch(e){}})})()`; /** The inline script above, for a root layout's ``. */ export function DisplayPreferencesScript(): ReactElement { diff --git a/packages/docs-next/src/display-settings.test.tsx b/packages/docs-next/src/display-settings.test.tsx index 7ee709fa..aaa9f109 100644 --- a/packages/docs-next/src/display-settings.test.tsx +++ b/packages/docs-next/src/display-settings.test.tsx @@ -13,6 +13,7 @@ function reset(): void { if (storageDescriptor) Object.defineProperty(globalThis, "localStorage", storageDescriptor); localStorage.clear(); html.removeAttribute("data-contrast"); + html.removeAttribute("data-color-vision"); html.removeAttribute("data-motion"); html.removeAttribute("class"); html.removeAttribute("style"); @@ -92,7 +93,7 @@ test("the server render is the trigger alone, with no panel and no inline script assert.equal(fragment.querySelector("script"), null); }); -test("the panel is a dialog named by its title, with three radio groups of three", async (t) => { +test("the panel is a dialog named by its title, with four radio groups", async (t) => { const { dialog } = await open(t); const titleId = dialog.getAttribute("aria-labelledby"); assert.ok(titleId); @@ -108,6 +109,7 @@ test("the panel is a dialog named by its title, with three radio groups of three [ { legend: "Theme", options: ["System", "Light", "Dark"] }, { legend: "Contrast", options: ["System", "Standard", "More"] }, + { legend: "Color vision", options: ["Standard", "Protanopia and deuteranopia"] }, { legend: "Motion", options: ["System", "Full", "Reduced"] }, ], ); @@ -119,7 +121,38 @@ test("the panel is a dialog named by its title, with three radio groups of three `${row.legend} options share one name, so arrows move between them`, ); } - assert.equal(new Set(rows.flatMap((r) => [...r.names])).size, 3, "each group has its own name"); + assert.equal(new Set(rows.flatMap((r) => [...r.names])).size, 4, "each group has its own name"); +}); + +test("the color vision row starts on Standard and describes what the other choice is for", async (t) => { + const { dialog } = await open(t); + assert.equal(checkedLabel(dialog, "Color vision"), "Standard"); + const hintId = group(dialog, "Color vision").getAttribute("aria-describedby"); + assert.ok(hintId); + assert.equal( + document.getElementById(hintId)?.textContent, + "For people who find reds and greens hard to tell apart.", + ); +}); + +test("choosing protanopia and deuteranopia sets the attribute and storage, and Standard clears them", async (t) => { + const { dialog } = await open(t); + await choose(radio(dialog, "Color vision", "Protanopia and deuteranopia")); + assert.equal(html.getAttribute("data-color-vision"), "protan-deuter"); + assert.equal(localStorage.getItem("docs-color-vision"), "protan-deuter"); + assert.equal(checkedLabel(dialog, "Color vision"), "Protanopia and deuteranopia"); + assert.equal(html.hasAttribute("data-contrast"), false, "contrast is untouched"); + await choose(radio(dialog, "Color vision", "Standard")); + assert.equal(html.hasAttribute("data-color-vision"), false); + assert.equal(localStorage.getItem("docs-color-vision"), null); + assert.equal(checkedLabel(dialog, "Color vision"), "Standard"); +}); + +test("the panel opens on the applied color vision choice", async (t) => { + localStorage.setItem("docs-color-vision", "protan-deuter"); + html.setAttribute("data-color-vision", "protan-deuter"); + const { dialog } = await open(t); + assert.equal(checkedLabel(dialog, "Color vision"), "Protanopia and deuteranopia"); }); test("every row starts on System, and the theme row says what the system resolves to", async (t) => { diff --git a/packages/docs-next/src/display-settings.tsx b/packages/docs-next/src/display-settings.tsx index 77d125f9..c5ae44c6 100644 --- a/packages/docs-next/src/display-settings.tsx +++ b/packages/docs-next/src/display-settings.tsx @@ -6,6 +6,7 @@ import { useTheme } from "fumadocs-ui/provider/base"; import { type LucideIcon, Monitor, Moon, SlidersHorizontal, Sun } from "lucide-react"; import { type ReactElement, type ReactNode, useId, useState } from "react"; import { + type ColorVisionPreference, type DisplayPreference, type DisplayPreferenceChoice, THEME_PREFERENCE, @@ -33,6 +34,11 @@ const CONTRAST_OPTIONS: Option>[] = [ { value: "more", label: "More" }, ]; +const COLOR_VISION_OPTIONS: Option[] = [ + { value: "standard", label: "Standard" }, + { value: "protan-deuter", label: "Protanopia and deuteranopia" }, +]; + const MOTION_OPTIONS: Option>[] = [ { value: "system", label: "System" }, { value: "full", label: "Full" }, @@ -49,19 +55,21 @@ function SegmentedGroup({ value, onChange, hint, + stacked, }: { legend: string; options: Option[]; value: V; onChange: (value: V) => void; hint?: ReactNode; + stacked?: boolean; }): ReactElement { const name = useId(); const hintId = useId(); return (
{legend} -
+
{options.map((option) => (
{hint ? ( -

+

{hint}

) : null} @@ -132,9 +141,10 @@ function DisplaySettingsPanel(): ReactElement { setColorVision(next === "standard" ? "system" : next)} - hint="For people who find reds and greens hard to tell apart." + hint={COLOR_VISION_HINTS[colorVision === "system" ? "standard" : colorVision]} + hintLines={3} stacked />