diff --git a/docs/theme-contrast.md b/docs/theme-contrast.md new file mode 100644 index 0000000..617078e --- /dev/null +++ b/docs/theme-contrast.md @@ -0,0 +1,214 @@ +# Theme contrast measurements + +Measured contrast ratios for the theme token contract, in the light theme and in the dark theme. Every number in the table below was produced by the harness in this repository, not estimated by hand. + +- **Harness:** `scripts/check-contrast.mjs` +- **Pair list:** `scripts/contrast-pairs.json` +- **Token source:** `public/src/main.css` (`:root` block for light, `.dark` block for dark) +- **Measured at:** the token values of commit `552d8474bf68e3fe37950fb7a97196daf33f84c0`, 2026-11-02. The token file is unchanged between that commit and this one (`git diff 552d847 HEAD -- public/src/main.css public/tailwind.config.js` is empty), so the table still holds at the branch head. +- **Result:** 16 pairs measured in 2 themes = 32 measurements, 32 pass, 0 fail + +Reproduce with: + +``` +node scripts/check-contrast.mjs +``` + +The harness exits `0` when every pair meets its threshold, `1` when at least one pair is below its threshold (naming each failing pair with its token names, values, measured ratio and required threshold), and `2` on a usage or I/O error. + +## Which stylesheet holds the tokens + +Two stylesheets are imported by `public/src/main.js`. The contrast is measured against the one the browser actually receives. + +- `public/src/assets/styles/main.css` is the legacy Tailwind stylesheet. It contains no `:root` block, no `.dark` block and no `--color-*` declaration, so it holds no theme token values. +- `public/src/main.css` is the token stylesheet. It holds the only `:root` block and the only `.dark` block, with the nine semantic colour tokens. + +The built bundle confirms this. After `npm run build` in `public/`, the token blocks are the last rules of the built stylesheet `public/dist/assets/index-WwvGP2s-.css`, and `public/dist/index.html` links that file. The hashed file name is the one from the build at the measured commit, so it changes if the stylesheet changes: + +``` +$ grep -cE '(^|[^-\w])\:root\s*\{' public/src/assets/styles/main.css +0 +$ grep -cE '\.dark\s*\{' public/src/assets/styles/main.css +0 +$ grep -c -- '--color-' public/src/assets/styles/main.css +0 +$ grep -cE '(^|[^-\w])\:root\s*\{' public/src/main.css +1 +$ grep -cE '\.dark\s*\{' public/src/main.css +1 +$ grep -c -- '--color-' public/src/main.css +27 +$ grep -oE 'href="\./assets/index-[^"]*\.css"' public/dist/index.html +href="./assets/index-WwvGP2s-.css" +$ tail -c 400 public/dist/assets/index-WwvGP2s-.css +...d-foreground:#475569;--color-border:#64748b;--color-accent:#1d4ed8;--color-accent-foreground:#fff;--color-text-body:#374151;--color-text-large:#1f2937}.dark{--color-background:#0f172a;--color-foreground:#f8fafc;--color-muted:#1e293b;--color-muted-foreground:#94a3b8;--color-border:#7c8ca3;--color-accent:#60a5fa;--color-accent-foreground:#0f172a;--color-text-body:#cbd5e1;--color-text-large:#e2e8f0} +``` + +The start of the tail is elided with `...`; the token blocks are the two rules at the end of the file. + +Running the harness against the built bundle gives the same ratios as the table below, which confirms the token file is what the browser sees: + +``` +$ node scripts/check-contrast.mjs --tokens public/dist/assets/index-WwvGP2s-.css --json +... "pairs": 16, "failures": 0 ... +``` + +## Thresholds + +The threshold for each pair comes from its own `threshold` field in `scripts/contrast-pairs.json`, and the harness checks it against the category default, so a threshold that disagrees with its category is rejected: + +- `body-text` — 4.5:1 (WCAG 2.2 SC 1.4.3 Contrast Minimum). +- `large-text` — 3:1 (WCAG 2.2 SC 1.4.3, large-scale text). +- `ui-component` — 3:1 (WCAG 2.2 SC 1.4.11 Non-text Contrast, for component boundaries such as borders and focus outlines). + +## Measured table + +Ratios are computed with the WCAG 2.2 relative-luminance formula, `(L1 + 0.05) / (L2 + 0.05)`, and rounded to two decimals for display. The harness compares the unrounded ratio against the threshold. + +| Pair | Category | Light foreground | Light background | Light ratio | Dark foreground | Dark background | Dark ratio | Threshold | Result | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `body-text-on-background` | body-text | `--color-text-body` #374151 | `--color-background` #ffffff | 10.31:1 | `--color-text-body` #cbd5e1 | `--color-background` #0f172a | 12.02:1 | 4.5:1 | pass | +| `body-text-on-muted` | body-text | `--color-text-body` #374151 | `--color-muted` #f1f5f9 | 9.41:1 | `--color-text-body` #cbd5e1 | `--color-muted` #1e293b | 9.85:1 | 4.5:1 | pass | +| `foreground-on-background` | body-text | `--color-foreground` #111827 | `--color-background` #ffffff | 17.74:1 | `--color-foreground` #f8fafc | `--color-background` #0f172a | 17.06:1 | 4.5:1 | pass | +| `foreground-on-muted` | body-text | `--color-foreground` #111827 | `--color-muted` #f1f5f9 | 16.19:1 | `--color-foreground` #f8fafc | `--color-muted` #1e293b | 13.98:1 | 4.5:1 | pass | +| `muted-foreground-on-background` | body-text | `--color-muted-foreground` #475569 | `--color-background` #ffffff | 7.58:1 | `--color-muted-foreground` #94a3b8 | `--color-background` #0f172a | 6.96:1 | 4.5:1 | pass | +| `muted-foreground-on-muted` | body-text | `--color-muted-foreground` #475569 | `--color-muted` #f1f5f9 | 6.92:1 | `--color-muted-foreground` #94a3b8 | `--color-muted` #1e293b | 5.71:1 | 4.5:1 | pass | +| `accent-text-on-background` | body-text | `--color-accent` #1d4ed8 | `--color-background` #ffffff | 6.70:1 | `--color-accent` #60a5fa | `--color-background` #0f172a | 7.02:1 | 4.5:1 | pass | +| `accent-text-on-muted` | body-text | `--color-accent` #1d4ed8 | `--color-muted` #f1f5f9 | 6.12:1 | `--color-accent` #60a5fa | `--color-muted` #1e293b | 5.75:1 | 4.5:1 | pass | +| `accent-foreground-on-accent` | body-text | `--color-accent-foreground` #ffffff | `--color-accent` #1d4ed8 | 6.70:1 | `--color-accent-foreground` #0f172a | `--color-accent` #60a5fa | 7.02:1 | 4.5:1 | pass | +| `large-text-on-background` | large-text | `--color-text-large` #1f2937 | `--color-background` #ffffff | 14.68:1 | `--color-text-large` #e2e8f0 | `--color-background` #0f172a | 14.48:1 | 3.0:1 | pass | +| `large-text-on-muted` | large-text | `--color-text-large` #1f2937 | `--color-muted` #f1f5f9 | 13.40:1 | `--color-text-large` #e2e8f0 | `--color-muted` #1e293b | 11.87:1 | 3.0:1 | pass | +| `border-on-background` | ui-component | `--color-border` #64748b | `--color-background` #ffffff | 4.76:1 | `--color-border` #7c8ca3 | `--color-background` #0f172a | 5.22:1 | 3.0:1 | pass | +| `border-on-muted` | ui-component | `--color-border` #64748b | `--color-muted` #f1f5f9 | 4.34:1 | `--color-border` #7c8ca3 | `--color-muted` #1e293b | 4.28:1 | 3.0:1 | pass | +| `accent-boundary-on-background` | ui-component | `--color-accent` #1d4ed8 | `--color-background` #ffffff | 6.70:1 | `--color-accent` #60a5fa | `--color-background` #0f172a | 7.02:1 | 3.0:1 | pass | +| `accent-boundary-on-muted` | ui-component | `--color-accent` #1d4ed8 | `--color-muted` #f1f5f9 | 6.12:1 | `--color-accent` #60a5fa | `--color-muted` #1e293b | 5.75:1 | 3.0:1 | pass | +| `foreground-boundary-on-background` | ui-component | `--color-foreground` #111827 | `--color-background` #ffffff | 17.74:1 | `--color-foreground` #f8fafc | `--color-background` #0f172a | 17.06:1 | 3.0:1 | pass | + +No pair is below its threshold in either theme, so there are no failing pairs to report at this commit. + +## Full harness output at this commit + +``` +$ node scripts/check-contrast.mjs +check-contrast: token file public/src/main.css +check-contrast: pair list scripts/contrast-pairs.json +check-contrast: 16 pair(s) measured in 2 theme(s) + +theme: light + pass body-text-on-background (--color-text-body #374151 on --color-background #ffffff) ratio 10.31:1, required 4.5:1 + pass body-text-on-muted (--color-text-body #374151 on --color-muted #f1f5f9) ratio 9.41:1, required 4.5:1 + pass foreground-on-background (--color-foreground #111827 on --color-background #ffffff) ratio 17.74:1, required 4.5:1 + pass foreground-on-muted (--color-foreground #111827 on --color-muted #f1f5f9) ratio 16.19:1, required 4.5:1 + pass muted-foreground-on-background (--color-muted-foreground #475569 on --color-background #ffffff) ratio 7.58:1, required 4.5:1 + pass muted-foreground-on-muted (--color-muted-foreground #475569 on --color-muted #f1f5f9) ratio 6.92:1, required 4.5:1 + pass accent-text-on-background (--color-accent #1d4ed8 on --color-background #ffffff) ratio 6.70:1, required 4.5:1 + pass accent-text-on-muted (--color-accent #1d4ed8 on --color-muted #f1f5f9) ratio 6.12:1, required 4.5:1 + pass accent-foreground-on-accent (--color-accent-foreground #ffffff on --color-accent #1d4ed8) ratio 6.70:1, required 4.5:1 + pass large-text-on-background (--color-text-large #1f2937 on --color-background #ffffff) ratio 14.68:1, required 3.0:1 + pass large-text-on-muted (--color-text-large #1f2937 on --color-muted #f1f5f9) ratio 13.40:1, required 3.0:1 + pass border-on-background (--color-border #64748b on --color-background #ffffff) ratio 4.76:1, required 3.0:1 + pass border-on-muted (--color-border #64748b on --color-muted #f1f5f9) ratio 4.34:1, required 3.0:1 + pass accent-boundary-on-background (--color-accent #1d4ed8 on --color-background #ffffff) ratio 6.70:1, required 3.0:1 + pass accent-boundary-on-muted (--color-accent #1d4ed8 on --color-muted #f1f5f9) ratio 6.12:1, required 3.0:1 + pass foreground-boundary-on-background (--color-foreground #111827 on --color-background #ffffff) ratio 17.74:1, required 3.0:1 + +theme: dark + pass body-text-on-background (--color-text-body #cbd5e1 on --color-background #0f172a) ratio 12.02:1, required 4.5:1 + pass body-text-on-muted (--color-text-body #cbd5e1 on --color-muted #1e293b) ratio 9.85:1, required 4.5:1 + pass foreground-on-background (--color-foreground #f8fafc on --color-background #0f172a) ratio 17.06:1, required 4.5:1 + pass foreground-on-muted (--color-foreground #f8fafc on --color-muted #1e293b) ratio 13.98:1, required 4.5:1 + pass muted-foreground-on-background (--color-muted-foreground #94a3b8 on --color-background #0f172a) ratio 6.96:1, required 4.5:1 + pass muted-foreground-on-muted (--color-muted-foreground #94a3b8 on --color-muted #1e293b) ratio 5.71:1, required 4.5:1 + pass accent-text-on-background (--color-accent #60a5fa on --color-background #0f172a) ratio 7.02:1, required 4.5:1 + pass accent-text-on-muted (--color-accent #60a5fa on --color-muted #1e293b) ratio 5.75:1, required 4.5:1 + pass accent-foreground-on-accent (--color-accent-foreground #0f172a on --color-accent #60a5fa) ratio 7.02:1, required 4.5:1 + pass large-text-on-background (--color-text-large #e2e8f0 on --color-background #0f172a) ratio 14.48:1, required 3.0:1 + pass large-text-on-muted (--color-text-large #e2e8f0 on --color-muted #1e293b) ratio 11.87:1, required 3.0:1 + pass border-on-background (--color-border #7c8ca3 on --color-background #0f172a) ratio 5.22:1, required 3.0:1 + pass border-on-muted (--color-border #7c8ca3 on --color-muted #1e293b) ratio 4.28:1, required 3.0:1 + pass accent-boundary-on-background (--color-accent #60a5fa on --color-background #0f172a) ratio 7.02:1, required 3.0:1 + pass accent-boundary-on-muted (--color-accent #60a5fa on --color-muted #1e293b) ratio 5.75:1, required 3.0:1 + pass foreground-boundary-on-background (--color-foreground #f8fafc on --color-background #0f172a) ratio 17.06:1, required 3.0:1 + +check-contrast: 16 pair(s), 32 measurement(s), 32 pass, 0 fail +$ echo $? +0 +``` + +## Harness self-test + +The harness was checked against fixtures that break the token contract on purpose, to confirm it fails loudly instead of passing silently. The fixtures are scratch copies of the token file; the token file in the repository is unchanged. + +One foreground changed so that exactly one pair fails — light `--color-accent-foreground` moved from `#ffffff` to `#93c5fd`: + +``` +$ diff public/src/main.css "$LOCUST_SCRATCH_DIR/fixture-single-pair.css" +35c35 +< --color-accent-foreground: #ffffff; +--- +> --color-accent-foreground: #93c5fd; +$ node scripts/check-contrast.mjs --tokens "$LOCUST_SCRATCH_DIR/fixture-single-pair.css" +... +check-contrast: 16 pair(s), 32 measurement(s), 31 pass, 1 fail + +failing pairs: + accent-foreground-on-accent [light] --color-accent-foreground #93c5fd on --color-accent #1d4ed8: ratio 3.72:1, required 4.5:1 - contrast ratio below the required threshold +$ echo $? +1 +``` + +One foreground changed so that several pairs fail — light `--color-text-body` moved from `#374151` to `#9ca3af`: + +``` +$ node scripts/check-contrast.mjs --tokens "$LOCUST_SCRATCH_DIR/fixture-failing-tokens.css" +... +check-contrast: 16 pair(s), 32 measurement(s), 30 pass, 2 fail + +failing pairs: + body-text-on-background [light] --color-text-body #9ca3af on --color-background #ffffff: ratio 2.54:1, required 4.5:1 - contrast ratio below the required threshold + body-text-on-muted [light] --color-text-body #9ca3af on --color-muted #f1f5f9: ratio 2.32:1, required 4.5:1 - contrast ratio below the required threshold +$ echo $? +1 +``` + +A token removed from the dark theme is reported as a failure, not skipped: + +``` +$ node scripts/check-contrast.mjs --tokens "$LOCUST_SCRATCH_DIR/fixture-missing-token.css" +... +check-contrast: 16 pair(s), 32 measurement(s), 30 pass, 2 fail + +failing pairs: + border-on-background [dark] --color-border n/a on --color-background #0f172a: ratio n/a, required 3.0:1 - token not defined in the dark theme: --color-border + border-on-muted [dark] --color-border n/a on --color-muted #1e293b: ratio n/a, required 3.0:1 - token not defined in the dark theme: --color-border +$ echo $? +1 +``` + +A bad invocation exits `2` rather than reporting a pass: + +``` +$ node scripts/check-contrast.mjs --tokens /nonexistent.css +check-contrast: cannot read token file: /nonexistent.css +Usage: node scripts/check-contrast.mjs [options] +... +$ echo $? +2 +``` + +A pair whose threshold disagrees with its category is rejected instead of being measured against a threshold the reviewer did not write: + +``` +$ node scripts/check-contrast.mjs --pairs "$LOCUST_SCRATCH_DIR/pairs-bad-threshold.json" +check-contrast: pair "body-text-on-background" has threshold 3, but category "body-text" requires 4.5 +Usage: node scripts/check-contrast.mjs [options] +... +$ echo $? +2 +``` + +## Scope + +This harness measures the token contract: the values declared in `public/src/main.css` and the pairs listed in `scripts/contrast-pairs.json`. It does not audit how the components consume the tokens. At this commit the components still use the legacy hard-coded Tailwind palette classes (`text-gray-100`, `bg-gray-900`, `text-blue-600` and similar), so no component references the new token utilities yet; adopting them is the work of the redesign card. When a component adopts a token, the pair that governs that surface must exist in `scripts/contrast-pairs.json`. + +The pair list is data, not code, so adding a governed surface is a one-line JSON change. The harness rejects a pair with an unknown category, a missing field or a duplicate id, so a malformed list fails loudly instead of silently measuring less than intended. diff --git a/scripts/check-contrast.mjs b/scripts/check-contrast.mjs new file mode 100755 index 0000000..e79f69b --- /dev/null +++ b/scripts/check-contrast.mjs @@ -0,0 +1,392 @@ +#!/usr/bin/env node +/** + * check-contrast.mjs + * + * Plain Node script (no runtime dependency, no test framework) that measures + * the WCAG 2.2 contrast ratio of every foreground/background pair of the + * theme token contract, in the light theme and in the dark theme. + * + * The token values come from the token stylesheet: the `:root` block holds + * the light values and the `.dark` block holds the dark values. The pairs + * come from a separate data file (scripts/contrast-pairs.json by default), + * so the list of measured pairs is reviewable on its own. + * + * The thresholds follow WCAG 2.2: + * body text 4.5:1 (SC 1.4.3 Contrast Minimum) + * large text 3:1 (SC 1.4.3, large-scale text) + * UI component 3:1 (SC 1.4.11 Non-text Contrast) + * + * Usage: + * node scripts/check-contrast.mjs [--tokens ] [--pairs ] + * [--json] [--help] + * + * Exit codes: 0 = every pair meets its threshold, 1 = at least one pair is + * below its threshold, 2 = bad usage or I/O error. + */ + +import { readFileSync } from 'node:fs' +import { dirname, join, relative, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = resolve(SCRIPT_DIR, '..') +const DEFAULT_TOKENS = join(REPO_ROOT, 'public', 'src', 'main.css') +const DEFAULT_PAIRS = join(SCRIPT_DIR, 'contrast-pairs.json') + +/** The WCAG 2.2 minimum for each pair category. */ +const THRESHOLDS = { + 'body-text': 4.5, + 'large-text': 3, + 'ui-component': 3, +} + +const THEMES = ['light', 'dark'] + +const usage = `Usage: node scripts/check-contrast.mjs [options] + + --tokens token stylesheet to read (default: public/src/main.css) + --pairs pair list to read (default: scripts/contrast-pairs.json) + --json print the measurements as JSON instead of a table + --help print this text +Exit codes: 0 = all pairs pass, 1 = at least one pair fails, 2 = usage or I/O error.` + +/* ------------------------------------------------------------------ colours */ + +/** + * Parse a CSS colour into its sRGB channels. + * + * Hex colours (#rgb, #rrggbb, #rrggbbaa) and the rgb()/rgba() function are + * supported, which covers every form a token value can take. + */ +function parseColor (value) { + const text = String(value).trim() + + const hex = /^#([0-9a-f]{3,8})$/i.exec(text) + if (hex) { + const digits = hex[1] + const expand = digits.length <= 4 + ? digits.split('').map((d) => d + d).join('') + : digits + if (expand.length !== 6 && expand.length !== 8) { + throw new Error(`unsupported hex colour: ${text}`) + } + return { + r: parseInt(expand.slice(0, 2), 16), + g: parseInt(expand.slice(2, 4), 16), + b: parseInt(expand.slice(4, 6), 16), + a: expand.length === 8 ? parseInt(expand.slice(6, 8), 16) / 255 : 1, + } + } + + const rgb = /^rgba?\(\s*([^)]+)\)$/i.exec(text) + if (rgb) { + const parts = rgb[1].split(/[\s,/]+/).filter(Boolean) + if (parts.length < 3) throw new Error(`unsupported rgb colour: ${text}`) + const channel = (part) => (part.endsWith('%') + ? Math.round((parseFloat(part) / 100) * 255) + : parseInt(part, 10)) + const alpha = parts[3] === undefined + ? 1 + : (parts[3].endsWith('%') ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])) + return { + r: channel(parts[0]), + g: channel(parts[1]), + b: channel(parts[2]), + a: alpha, + } + } + + throw new Error(`unsupported colour value: ${text}`) +} + +/** Composite a translucent colour over an opaque one. */ +function flatten (top, bottom) { + const alpha = top.a + if (alpha >= 1) return { r: top.r, g: top.g, b: top.b } + return { + r: Math.round(top.r * alpha + bottom.r * (1 - alpha)), + g: Math.round(top.g * alpha + bottom.g * (1 - alpha)), + b: Math.round(top.b * alpha + bottom.b * (1 - alpha)), + } +} + +/** The relative luminance of a colour, per WCAG 2.2. */ +function relativeLuminance ({ r, g, b }) { + const channel = (value) => { + const srgb = value / 255 + return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4 + } + return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b) +} + +/** + * The contrast ratio between two colours, per WCAG 2.2. + * + * A translucent foreground is composited over the background first, because + * that is what the reader sees. + */ +function contrastRatio (foreground, background) { + const fg = flatten(foreground, background) + const bg = { r: background.r, g: background.g, b: background.b } + const lighter = Math.max(relativeLuminance(fg), relativeLuminance(bg)) + const darker = Math.min(relativeLuminance(fg), relativeLuminance(bg)) + return (lighter + 0.05) / (darker + 0.05) +} + +/* ------------------------------------------------------------- token file */ + +/** + * Read the custom properties of one block of a stylesheet. + * + * The block is selected by its selector, so the same reader finds the light + * values in `:root` and the dark values in `.dark`. + */ +function readBlock (css, selector) { + const pattern = new RegExp(`(^|[}\\s,])${selector.replace('.', '\\.')}\\s*\\{`, 'm') + const match = pattern.exec(css) + if (!match) throw new Error(`no "${selector}" block in the token file`) + + const start = match.index + match[0].length + const end = css.indexOf('}', start) + if (end === -1) throw new Error(`unterminated "${selector}" block in the token file`) + + const values = new Map() + for (const entry of css.slice(start, end).split(';')) { + const declaration = entry.trim() + if (declaration === '' || declaration.startsWith('/*')) continue + const colon = declaration.indexOf(':') + if (colon === -1) continue + values.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).trim()) + } + return values +} + +/** The token values of both themes, read from the token stylesheet. */ +function readTokens (tokenPath) { + let css + try { + css = readFileSync(tokenPath, 'utf8') + } catch { + throw new Error(`cannot read token file: ${tokenPath}`) + } + const light = readBlock(css, ':root') + const dark = readBlock(css, '.dark') + return { light, dark } +} + +/* -------------------------------------------------------------- pair list */ + +/** Read and validate the pair list. */ +function readPairs (pairsPath) { + let data + try { + data = JSON.parse(readFileSync(pairsPath, 'utf8')) + } catch (error) { + throw new Error(`cannot read pair list: ${pairsPath} (${error.message})`) + } + if (!data || !Array.isArray(data.pairs) || data.pairs.length === 0) { + throw new Error(`pair list has no pairs: ${pairsPath}`) + } + + const ids = new Set() + return data.pairs.map((pair) => { + for (const field of ['id', 'category', 'foreground', 'background']) { + if (typeof pair[field] !== 'string' || pair[field].trim() === '') { + throw new Error(`pair is missing "${field}": ${JSON.stringify(pair)}`) + } + } + if (!Object.hasOwn(THRESHOLDS, pair.category)) { + throw new Error( + `pair "${pair.id}" has unknown category "${pair.category}"; ` + + `known categories: ${Object.keys(THRESHOLDS).join(', ')}` + ) + } + if (ids.has(pair.id)) throw new Error(`duplicate pair id: ${pair.id}`) + ids.add(pair.id) + + // The pair list states the threshold it needs. The category default + // must agree with it, so a wrong threshold cannot slip in unnoticed. + const categoryThreshold = THRESHOLDS[pair.category] + let threshold = categoryThreshold + if (pair.threshold !== undefined) { + if (typeof pair.threshold !== 'number' || !Number.isFinite(pair.threshold)) { + throw new Error(`pair "${pair.id}" has a non-numeric threshold: ${pair.threshold}`) + } + if (Math.abs(pair.threshold - categoryThreshold) > 1e-9) { + throw new Error( + `pair "${pair.id}" has threshold ${pair.threshold}, but category ` + + `"${pair.category}" requires ${categoryThreshold}` + ) + } + threshold = pair.threshold + } + + return { + id: pair.id, + category: pair.category, + foreground: pair.foreground, + background: pair.background, + surface: typeof pair.surface === 'string' ? pair.surface : '', + threshold, + } + }) +} + +/* ------------------------------------------------------------ measurement */ + +/** + * Measure every pair in both themes. + * + * A pair whose tokens are missing from a theme is reported as an error + * rather than skipped: a missing token is a contrast failure the site + * cannot recover from. + */ +function measure (pairs, tokens) { + const results = [] + for (const pair of pairs) { + const themes = {} + for (const theme of THEMES) { + const foregroundValue = tokens[theme].get(pair.foreground) + const backgroundValue = tokens[theme].get(pair.background) + if (foregroundValue === undefined || backgroundValue === undefined) { + const missing = [ + foregroundValue === undefined ? pair.foreground : null, + backgroundValue === undefined ? pair.background : null, + ].filter(Boolean).join(', ') + themes[theme] = { + error: `token not defined in the ${theme} theme: ${missing}`, + foregroundValue: foregroundValue ?? null, + backgroundValue: backgroundValue ?? null, + ratio: null, + pass: false, + } + continue + } + const foreground = parseColor(foregroundValue) + const background = parseColor(backgroundValue) + const ratio = contrastRatio(foreground, background) + themes[theme] = { + error: null, + foregroundValue, + backgroundValue, + ratio: Number(ratio.toFixed(2)), + pass: ratio >= pair.threshold - 1e-9, + } + } + results.push({ ...pair, themes }) + } + return results +} + +/* ----------------------------------------------------------------- output */ + +/** Format a ratio for the report: two decimals, or a placeholder. */ +const formatRatio = (ratio) => (ratio === null ? 'n/a' : `${ratio.toFixed(2)}:1`) + +function printTable (results, tokenPath, pairsPath) { + const shown = (file) => relative(process.cwd(), file) || file + console.log(`check-contrast: token file ${shown(tokenPath)}`) + console.log(`check-contrast: pair list ${shown(pairsPath)}`) + console.log(`check-contrast: ${results.length} pair(s) measured in ${THEMES.length} theme(s)`) + console.log('') + + for (const theme of THEMES) { + console.log(`theme: ${theme}`) + for (const result of results) { + const measurement = result.themes[theme] + const status = measurement.error + ? 'ERROR' + : (measurement.pass ? 'pass' : 'FAIL') + console.log( + ` ${status.padEnd(5)} ${result.id} ` + + `(${result.foreground} ${measurement.foregroundValue ?? 'n/a'} on ` + + `${result.background} ${measurement.backgroundValue ?? 'n/a'}) ` + + `ratio ${formatRatio(measurement.ratio)}, ` + + `required ${result.threshold.toFixed(1)}:1` + + (measurement.error ? ` - ${measurement.error}` : '') + ) + } + console.log('') + } +} + +/** The failing measurements, in a stable order. */ +function failures (results) { + const failing = [] + for (const result of results) { + for (const theme of THEMES) { + const measurement = result.themes[theme] + if (!measurement.pass) failing.push({ result, theme, measurement }) + } + } + return failing +} + +/* -------------------------------------------------------------------- main */ + +function main (argv) { + if (argv.includes('--help') || argv.includes('-h')) { + console.log(usage) + return 0 + } + const known = new Set(['--tokens', '--pairs', '--json', '--help', '-h']) + const unknown = argv.filter((argument) => argument.startsWith('-') && !known.has(argument)) + if (unknown.length > 0) throw new Error(`unknown option: ${unknown[0]}`) + + const optionValue = (name) => { + const index = argv.indexOf(name) + return index === -1 ? null : (argv[index + 1] ?? null) + } + const tokenOption = optionValue('--tokens') + const pairsOption = optionValue('--pairs') + if (argv.includes('--tokens') && tokenOption === null) throw new Error('--tokens needs a file path') + if (argv.includes('--pairs') && pairsOption === null) throw new Error('--pairs needs a file path') + + const tokenPath = tokenOption === null ? DEFAULT_TOKENS : resolve(process.cwd(), tokenOption) + const pairsPath = pairsOption === null ? DEFAULT_PAIRS : resolve(process.cwd(), pairsOption) + + const tokens = readTokens(tokenPath) + const pairs = readPairs(pairsPath) + const results = measure(pairs, tokens) + const failing = failures(results) + + if (argv.includes('--json')) { + console.log(JSON.stringify({ + tokenFile: tokenPath, + pairFile: pairsPath, + pairs: results.length, + failures: failing.length, + results, + }, null, 2)) + return failing.length > 0 ? 1 : 0 + } + + printTable(results, tokenPath, pairsPath) + + const measurements = results.length * THEMES.length + console.log( + `check-contrast: ${results.length} pair(s), ${measurements} measurement(s), ` + + `${measurements - failing.length} pass, ${failing.length} fail` + ) + if (failing.length > 0) { + console.log('') + console.log('failing pairs:') + for (const { result, theme, measurement } of failing) { + const reason = measurement.error ?? 'contrast ratio below the required threshold' + console.log( + ` ${result.id} [${theme}] ${result.foreground} ${measurement.foregroundValue ?? 'n/a'} on ` + + `${result.background} ${measurement.backgroundValue ?? 'n/a'}: ` + + `ratio ${formatRatio(measurement.ratio)}, required ${result.threshold.toFixed(1)}:1 - ${reason}` + ) + } + } + return failing.length > 0 ? 1 : 0 +} + +try { + process.exit(main(process.argv.slice(2))) +} catch (error) { + console.error(`check-contrast: ${error.message}`) + console.error(usage) + process.exit(2) +} diff --git a/scripts/contrast-pairs.json b/scripts/contrast-pairs.json new file mode 100644 index 0000000..7420a48 --- /dev/null +++ b/scripts/contrast-pairs.json @@ -0,0 +1,150 @@ +{ + "comment": [ + "The foreground/background pairs of the theme token contract that the", + "contrast harness measures. Every pair names the CSS custom properties", + "it reads, so a reviewer can check the list against the token file", + "without running anything.", + "", + "The category fixes the WCAG 2.2 threshold the harness applies:", + " body-text 4.5:1 (WCAG 1.4.3, normal-size text)", + " large-text 3:1 (WCAG 1.4.3, large-scale text)", + " ui-component 3:1 (WCAG 1.4.11, component boundaries)", + "", + "Every pair also states its own threshold, so the list carries the", + "requirement in full and can be reviewed without the harness. The", + "harness rejects a pair whose threshold disagrees with its category.", + "", + "A pair is checked in both themes: the light values come from the :root", + "block and the dark values from the .dark block of the token file." + ], + "pairs": [ + { + "id": "body-text-on-background", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-text-body", + "background": "--color-background", + "surface": "Body copy on the page background" + }, + { + "id": "body-text-on-muted", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-text-body", + "background": "--color-muted", + "surface": "Body copy on a muted surface (card, code block, inset panel)" + }, + { + "id": "foreground-on-background", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-foreground", + "background": "--color-background", + "surface": "Primary text and headings on the page background" + }, + { + "id": "foreground-on-muted", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-foreground", + "background": "--color-muted", + "surface": "Primary text and headings on a muted surface" + }, + { + "id": "muted-foreground-on-background", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-muted-foreground", + "background": "--color-background", + "surface": "Secondary text (captions, metadata, helper text) on the page background" + }, + { + "id": "muted-foreground-on-muted", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-muted-foreground", + "background": "--color-muted", + "surface": "Secondary text on a muted surface" + }, + { + "id": "accent-text-on-background", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-accent", + "background": "--color-background", + "surface": "Link and emphasis text on the page background" + }, + { + "id": "accent-text-on-muted", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-accent", + "background": "--color-muted", + "surface": "Link and emphasis text on a muted surface" + }, + { + "id": "accent-foreground-on-accent", + "category": "body-text", + "threshold": 4.5, + "foreground": "--color-accent-foreground", + "background": "--color-accent", + "surface": "Label text on an accent-filled button or badge" + }, + { + "id": "large-text-on-background", + "category": "large-text", + "threshold": 3, + "foreground": "--color-text-large", + "background": "--color-background", + "surface": "Large headings on the page background" + }, + { + "id": "large-text-on-muted", + "category": "large-text", + "threshold": 3, + "foreground": "--color-text-large", + "background": "--color-muted", + "surface": "Large headings on a muted surface" + }, + { + "id": "border-on-background", + "category": "ui-component", + "threshold": 3, + "foreground": "--color-border", + "background": "--color-background", + "surface": "Control and card boundary on the page background" + }, + { + "id": "border-on-muted", + "category": "ui-component", + "threshold": 3, + "foreground": "--color-border", + "background": "--color-muted", + "surface": "Control and card boundary on a muted surface" + }, + { + "id": "accent-boundary-on-background", + "category": "ui-component", + "threshold": 3, + "foreground": "--color-accent", + "background": "--color-background", + "surface": "Accent control edge and focus indicator on the page background" + }, + { + "id": "accent-boundary-on-muted", + "category": "ui-component", + "threshold": 3, + "foreground": "--color-accent", + "background": "--color-muted", + "surface": "Accent control edge on a muted surface" + }, + { + "id": "foreground-boundary-on-background", + "category": "ui-component", + "threshold": 3, + "foreground": "--color-foreground", + "background": "--color-background", + "surface": "Strong control edge (input outline, toggle track) on the page background" + } + ] +}