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/apps/docs/README.md b/apps/docs/README.md index 840ca32e..70cb1f67 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -637,7 +637,9 @@ 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 same pages are scanned with Color vision on Tritanopia, as `vision-tritan-light`, `vision-tritan-dark`, `vision-tritan-more-light` and `vision-tritan-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 eight 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..f8506e3a 100644 --- a/apps/docs/scripts/a11y-axe-helpers.mjs +++ b/apps/docs/scripts/a11y-axe-helpers.mjs @@ -47,6 +47,19 @@ 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 same, for Tritanopia. +export const VISION_TRITAN_MODES = MODES.map((mode) => `vision-tritan-${mode}`); +export const VISION_TRITAN_MORE_MODES = MODES.map((mode) => `vision-tritan-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 +104,22 @@ 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-tritan-more-|vision-tritan-|vision-more-|vision-)/, ""); + +export const contrastOf = (mode) => + MORE_MODES.includes(mode) || + VISION_MORE_MODES.includes(mode) || + VISION_TRITAN_MORE_MODES.includes(mode) + ? "more" + : undefined; -export const contrastOf = (mode) => (MORE_MODES.includes(mode) ? "more" : undefined); +export function colorVisionOf(mode) { + if (VISION_MODES.includes(mode) || VISION_MORE_MODES.includes(mode)) return "protan-deuter"; + if (VISION_TRITAN_MODES.includes(mode) || VISION_TRITAN_MORE_MODES.includes(mode)) + return "tritan"; + return undefined; +} export function axeOptions(mode) { return { diff --git a/apps/docs/scripts/a11y-axe.mjs b/apps/docs/scripts/a11y-axe.mjs index 9cbffadb..41712e28 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,14 @@ import { SETTINGS_LABEL, SWITCHER_DOCUMENT, SWITCHER_LABEL, + VISION_MODES, + VISION_MORE_MODES, + VISION_TRITAN_MODES, + VISION_TRITAN_MORE_MODES, applyAllowlist, axeOptions, colorSchemeOf, + colorVisionOf, contrastOf, parseArgs, splitBestPractice, @@ -77,6 +83,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 +91,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 +106,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 +156,26 @@ async function main() { executablePath: options.chromium ?? process.env.A11Y_CHROMIUM ?? undefined, }); const desktopModes = [...MODES, ...MORE_MODES]; + const visionModes = [ + ...VISION_MODES, + ...VISION_MORE_MODES, + ...VISION_TRITAN_MODES, + ...VISION_TRITAN_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 +204,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..d8cb58f4 100644 --- a/apps/docs/scripts/a11y-axe.test.mjs +++ b/apps/docs/scripts/a11y-axe.test.mjs @@ -6,7 +6,12 @@ import { test } from "node:test"; import { DEFAULT_MOBILE_PAGES, DEFAULT_PAGES, + COLOR_VISION_PAGES, MORE_MODES, + VISION_MODES, + VISION_MORE_MODES, + VISION_TRITAN_MODES, + VISION_TRITAN_MORE_MODES, SEARCH_LABEL, SEARCH_PAGE, SEARCH_QUERY, @@ -15,6 +20,7 @@ import { applyAllowlist, axeOptions, colorSchemeOf, + colorVisionOf, contrastOf, idOf, parseArgs, @@ -169,6 +175,55 @@ 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("tritan modes scan both color schemes, standard and More", () => { + assert.deepEqual(VISION_TRITAN_MODES, ["vision-tritan-light", "vision-tritan-dark"]); + assert.deepEqual(VISION_TRITAN_MORE_MODES, [ + "vision-tritan-more-light", + "vision-tritan-more-dark", + ]); + const all = [...VISION_TRITAN_MODES, ...VISION_TRITAN_MORE_MODES]; + for (const mode of all) assert.equal(colorVisionOf(mode), "tritan", mode); + assert.deepEqual(all.map(colorSchemeOf), ["light", "dark", "light", "dark"]); + assert.deepEqual(all.map(contrastOf), [undefined, undefined, "more", "more"]); + assert.equal(colorVisionOf("vision-dark"), "protan-deuter"); + assert.deepEqual(axeOptions("vision-tritan-more-dark").rules, { + "color-contrast-enhanced": { enabled: true }, + }); + assert.equal(axeOptions("vision-tritan-dark").rules, undefined); +}); + 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..1f31c958 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,26 @@ 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"); + localStorage.setItem("docs-color-vision", "tritan"); + assert.equal(runRenderedScript().getAttribute("data-color-vision"), "tritan"); + document.documentElement.removeAttribute("data-color-vision"); + for (const stored of ["tritanopia", "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..0bccb789 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", "tritan"], + }, 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","tritan"]],["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..5fecb0d6 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,10 @@ 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", "Tritanopia"], + }, { legend: "Motion", options: ["System", "Full", "Reduced"] }, ], ); @@ -119,7 +124,65 @@ 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 its hint describes the selected choice", 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); + const hint = () => document.getElementById(hintId)?.textContent; + assert.equal(hint(), "The default colors."); + await choose(radio(dialog, "Color vision", "Protanopia and deuteranopia")); + assert.equal(hint(), "For people who find reds and greens hard to tell apart."); + await choose(radio(dialog, "Color vision", "Tritanopia")); + assert.equal( + hint(), + "For people who find blues and greens, or yellows and purples, hard to tell apart.", + ); +}); + +test("choosing Tritanopia sets the attribute and storage, switches between all three, and Standard clears them", async (t) => { + const { dialog } = await open(t); + await choose(radio(dialog, "Color vision", "Tritanopia")); + assert.equal(html.getAttribute("data-color-vision"), "tritan"); + assert.equal(localStorage.getItem("docs-color-vision"), "tritan"); + assert.equal(checkedLabel(dialog, "Color vision"), "Tritanopia"); + 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"); + await choose(radio(dialog, "Color vision", "Tritanopia")); + await choose(radio(dialog, "Color vision", "Standard")); + assert.equal(html.hasAttribute("data-color-vision"), false); + assert.equal(localStorage.getItem("docs-color-vision"), null); +}); + +test("the panel opens on a stored Tritanopia choice", async (t) => { + localStorage.setItem("docs-color-vision", "tritan"); + html.setAttribute("data-color-vision", "tritan"); + const { dialog } = await open(t); + assert.equal(checkedLabel(dialog, "Color vision"), "Tritanopia"); +}); + +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..ef8fe220 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,18 @@ const CONTRAST_OPTIONS: Option>[] = [ { value: "more", label: "More" }, ]; +const COLOR_VISION_OPTIONS: Option[] = [ + { value: "standard", label: "Standard" }, + { value: "protan-deuter", label: "Protanopia and deuteranopia" }, + { value: "tritan", label: "Tritanopia" }, +]; + +const COLOR_VISION_HINTS: Record = { + standard: "The default colors.", + "protan-deuter": "For people who find reds and greens hard to tell apart.", + tritan: "For people who find blues and greens, or yellows and purples, hard to tell apart.", +}; + const MOTION_OPTIONS: Option>[] = [ { value: "system", label: "System" }, { value: "full", label: "Full" }, @@ -49,19 +62,23 @@ function SegmentedGroup({ value, onChange, hint, + stacked, + hintLines, }: { legend: string; options: Option[]; value: V; onChange: (value: V) => void; hint?: ReactNode; + stacked?: boolean; + hintLines?: number; }): ReactElement { const name = useId(); const hintId = useId(); return (
{legend} -
+
{options.map((option) => (
{hint ? ( -

+

{hint}

) : null} @@ -99,6 +116,7 @@ function usePreference(key: K) { function DisplaySettingsPanel(): ReactElement { const { theme, systemTheme, setTheme } = useTheme(); const [contrast, setContrast] = usePreference("contrast"); + const [colorVision, setColorVision] = usePreference("colorVision"); const [motion, setMotion] = usePreference("motion"); const themeChoice = THEME_OPTIONS.find((o) => o.value === theme)?.value ?? "system"; return ( @@ -120,6 +138,15 @@ function DisplaySettingsPanel(): ReactElement { value={contrast} onChange={setContrast} /> + setColorVision(next === "standard" ? "system" : next)} + hint={COLOR_VISION_HINTS[colorVision === "system" ? "standard" : colorVision]} + hintLines={3} + stacked + /> `. 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"` or `"tritan"` on `` applies `src/color-vision.css`, which recolors the callout and state pill tokens for readers with protanopia or deuteranopia, or tritanopia; the protanopia and deuteranopia palette also recolors the green code colors. + 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"]` or `html:root[data-color-vision="tritan"]`, 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, and in the tritan palette under simulated tritanopia. - **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`, `color-vision more`, `tritan` and `tritan 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..61b7cfd7 --- /dev/null +++ b/packages/docs-theme/scripts/color-vision.test.mjs @@ -0,0 +1,246 @@ +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, + cvSelector, + parseColorVisionPalettes, + parsePalettes, + resultId, + runContrastCheck, +} from "./contrast.mjs"; +import { RED_GREEN, TRITAN, 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 = cvSelector("protan-deuter"); +const TR = cvSelector("tritan"); + +const css = await loadThemeCss(); +const { standard, more } = parsePalettes(css); +const vision = parseColorVisionPalettes(css); +const tritan = parseColorVisionPalettes(css, TR); + +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, "achromatopsia"), /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) => { + const sel = s.replace(/\s+/g, " "); + return sel.startsWith(CV) || sel.startsWith(TR); + }), + 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 !== "standard" && r.palette !== "more", + ); + for (const palette of ["color-vision", "color-vision-more", "tritan", "tritan-more"]) + assert.ok( + results.some((r) => r.palette === palette), + palette, + ); + const { failures } = applyAllowlist(results, await loadAllowlist()); + assert.deepEqual( + failures.map((r) => `${resultId(r)} ${r.ratio.toFixed(2)} < ${r.min}`), + [], + ); +}); + +for (const mode of ["light", "dark"]) { + test(`every ${mode} tritan callout color is ${MIN_DISTANCE} CIEDE2000 from every other under tritanopia`, () => { + for (const [a, b] of pairs(CALLOUTS)) { + const d = simulatedDistance( + parseColor(tritan.standard[mode][a]), + parseColor(tritan.standard[mode][b]), + TRITAN, + ); + assert.ok(d >= MIN_DISTANCE, `${mode} ${a} vs ${b}: ${d.toFixed(1)}`); + } + }); + + test(`every ${mode} tritan state pill background is ${MIN_DISTANCE} CIEDE2000 from every other under tritanopia`, () => { + for (const [a, b] of pairs(TONES)) { + const d = simulatedDistance( + parseColor(tritan.standard[mode][`state-${a}-bg`]), + parseColor(tritan.standard[mode][`state-${b}-bg`]), + TRITAN, + ); + assert.ok(d >= MIN_DISTANCE, `${mode} ${a} vs ${b} pill: ${d.toFixed(1)}`); + } + }); + + test(`${mode} diff additions and deletions stay ${MIN_DISTANCE} apart under tritanopia`, async () => { + const theme = await loadShikiTheme(mode); + const scoped = (scope) => + theme.tokenColors.find((t) => [].concat(t.scope).includes(scope)).settings.foreground; + const overrides = parseCodeOverrides(css, TR)[mode]; + const shown = (color) => overrides[color.toLowerCase()] ?? color; + const d = simulatedDistance( + parseColor(shown(scoped("markup.inserted"))), + parseColor(shown(scoped("markup.deleted"))), + TRITAN, + ); + assert.ok(d >= MIN_DISTANCE, `${mode} inserted vs deleted: ${d.toFixed(1)}`); + }); + + test(`More contrast keeps the ${mode} tritan callouts and pills`, () => { + for (const token of [...CALLOUTS, ...TONES.flatMap((t) => [`state-${t}-bg`, `state-${t}-fg`])]) + assert.equal(tritan.more[mode][token], tritan.standard[mode][token], token); + }); +} + +test("the tritan palette changes callouts and pills and nothing else", () => { + for (const mode of ["light", "dark"]) { + const changed = Object.keys(tritan.standard[mode]).filter( + (k) => tritan.standard[mode][k] !== standard[mode][k], + ); + assert.deepEqual( + changed.filter((k) => !CALLOUTS.includes(k) && !k.startsWith("state-")), + [], + ); + assert.ok(changed.length >= CALLOUTS.length + TONES.length * 2, mode); + } +}); + +test("a tritan 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${TR} .x { --color-fd-success: #00f; }`; + assert.throws(() => parseColorVisionPalettes(sheet, TR), /sets theme tokens/); +}); + +test("the protan-deuter and tritan selectors never match each other's rules", () => { + const sheet = `:root { --color-fd-success: #111; }\n.dark { --color-fd-success: #eee; }\n${CV} { --color-fd-success: #00f; }`; + assert.equal(parseColorVisionPalettes(sheet, TR).standard.light.success, "#111"); + assert.equal(RED_GREEN.length, 2); +}); diff --git a/packages/docs-theme/scripts/contrast.mjs b/packages/docs-theme/scripts/contrast.mjs index 442ba6dc..4837fb53 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,21 @@ 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, {}])); +export const cvSelector = (value) => `html:root[data-color-vision="${value}"]`; +const CV = cvSelector("protan-deuter"); +const TRITAN = cvSelector("tritan"); + +// Same cascade order as More: a plain block applies to both modes, and the mode-scoped blocks beat it. +const cvLayers = (root) => [ + [root, ["light", "dark"]], + [`${root}:not(.dark)`, ["light"]], + [`${root}.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 +140,41 @@ 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, root = CV) { + const { standard, more } = parsePalettes(css); + const layerDefs = cvLayers(root); + const layers = collectLayers(css, root, layerDefs); + const on = (base) => { + const apply = applyLayers(base, layerDefs, 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 +197,24 @@ function verdicts(ratio, kind) { return { ratio, min: aa, pass: ratio >= aa, aaaMin: aaa, aaaPass: ratio >= aaa }; } +export const isMorePalette = (palette) => palette?.endsWith("more") ?? false; + 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 +254,20 @@ 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 ", + tritan: "tritan ", + "tritan-more": "tritan 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 +306,35 @@ 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 tritan = parseColorVisionPalettes(css, TRITAN); + const merged = (own) => ({ + light: { ...moreCode.light, ...own.light }, + dark: { ...moreCode.dark, ...own.dark }, + }); + const visionCode = parseCodeOverrides(css, CV); + const tritanCode = parseCodeOverrides(css, TRITAN); 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, merged(visionCode), "color-vision-more"), + ...checkPairs(tritan.standard, PAIRS, "tritan"), + ...checkCodeTokens(tritan.standard, shiki, tritanCode, "tritan"), + ...checkPairs(tritan.more, PAIRS, "tritan-more"), + ...checkCodeTokens(tritan.more, shiki, merged(tritanCode), "tritan-more"), ]; } @@ -283,7 +359,14 @@ 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 ", + tritan: "tritan ", + "tritan-more": "tritan 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 +393,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", "tritan", "tritan-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..a84035f8 --- /dev/null +++ b/packages/docs-theme/scripts/cvd.mjs @@ -0,0 +1,102 @@ +// 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], + ], + tritanopia: [ + [1.255528, -0.076749, -0.178779], + [-0.078411, 0.930809, 0.147602], + [0.004733, 0.691367, 0.3039], + ], + deuteranopia: [ + [0.367322, 0.860646, -0.227968], + [0.280085, 0.672501, 0.047413], + [-0.01182, 0.04294, 0.968881], + ], +}; + +export const RED_GREEN = ["protanopia", "deuteranopia"]; +export const TRITAN = ["tritanopia"]; + +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 given simulations (red-green by default). */ +export function simulatedDistance(rgb1, rgb2, kinds = RED_GREEN) { + return Math.min(...kinds.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..0161d83b --- /dev/null +++ b/packages/docs-theme/src/color-vision.css @@ -0,0 +1,101 @@ +/* Color vision (protanopia and deuteranopia, and tritanopia); 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; +} + +/* Tritanopia: success moves to blue and warning to magenta, as in the dashboard, with red kept for errors. */ +html:root[data-color-vision="tritan"]:not(.dark) { + --color-fd-info: #120f5b; + --color-fd-success: #0f5991; + --color-fd-idea: #5a18a0; + --color-fd-warning: #5a1b40; + --color-fd-error: #aa1c10; + --docs-state-purple-bg: #ba95f1; + --docs-state-purple-fg: #210d3f; + --docs-state-sky-bg: #e3eff6; + --docs-state-sky-fg: #0f3a52; + --docs-state-orange-bg: #fde5c5; + --docs-state-orange-fg: #2f2519; + --docs-state-red-bg: #f39782; + --docs-state-red-fg: #361912; + --docs-state-teal-bg: #8ffaf9; + --docs-state-teal-fg: #072525; +} + +html:root[data-color-vision="tritan"].dark { + --color-fd-info: #a8aee0; + --color-fd-success: #5dc0e8; + --color-fd-idea: #ba86f9; + --color-fd-warning: #f958da; + --color-fd-error: #dca99c; + --docs-state-purple-bg: #410f8c; + --docs-state-purple-fg: #e2d8f3; + --docs-state-sky-bg: #0f2639; + --docs-state-sky-fg: #d8edff; + --docs-state-orange-bg: #4e3019; + --docs-state-orange-fg: #fbf0e8; + --docs-state-red-bg: #981614; + --docs-state-red-fg: #ffefee; + --docs-state-teal-bg: #245b4a; + --docs-state-teal-fg: #f3f9f8; +} + +/* 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; +} + +/* Reserve the room for the longest hint, so choosing an option never resizes the panel. */ +.docs-segmented-hint[data-lines="3"] { + min-height: 3lh; +} 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