包文件→ .shtukbase/packages/design-a11y/checks/contrast.ts
checks/contrast.ts
101 行, 5.6 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // A11Y-R01. Text colors of the theme are readable on their backgrounds: every pair of CSS custom properties
- // `--x-foreground` on `--x` (also `--foreground` on `--background`, `--on-x` on `--x`, and the pairs named on
- // /design/a11y.md) has a WCAG 2.2 contrast ratio of at least 4.5:1, in every scheme (:root, .dark, [data-theme=…]).
- // A value that is not a plain color (a gradient, color-mix(), an unknown var) is skipped. A color with alpha is laid
- // over its background; a background with alpha over the scheme's --background (or white).
- import { contrast, hex, over, parseColor, type RGBA } from '../../design-base/lib/color.ts';
- import { resolveVars, themes } from '../../design-base/lib/css.ts';
- import { projectFiles, read, report } from '../../design-base/lib/files.ts';
- import { config } from './a11ylib.ts';
- export const RULE = { id: 'a11y-r01', title: 'Theme text contrast is at least 4.5:1' };
- /** Pairs [text, background] that a theme defines by naming. */
- export function pairsOf(vars: Map<string, string>): [string, string][] {
- const out: [string, string][] = [];
- for (const v of vars.keys()) {
- let bg: string | null = null;
- if (v === '--foreground') bg = '--background';
- else if (/-(foreground|fg)$/.test(v)) {
- const base = v.replace(/-(foreground|fg)$/, '');
- bg = [`${base}-bg`, `${base}-background`, base].find((b) => vars.has(b)) ?? null; // --x-bg beats --x
- }
- else if (/(^--|-)on-[\w-]+$/.test(v)) bg = v.replace(/(^--|-)on-([\w-]+)$/, '$1$2');
- if (bg && vars.has(bg)) out.push([v, bg]);
- }
- return out;
- }
- function color(name: string, vars: Map<string, string>): RGBA | null {
- const raw = vars.get(name);
- if (raw === undefined) return null;
- const v = resolveVars(raw, vars);
- return v === null ? null : parseColor(v);
- }
- export type Finding = { scheme: string; fg: string; bg: string; ratio: number; colors: string };
- export function measure(files: { rel: string; text: string }[], min: number, extra: [string, string][] = [], skip = new Set<string>(), ownOnly = false): { findings: Finding[]; where: Map<string, string>; checked: number } {
- const { themes: all, scopes, where } = themes(files);
- const findings: Finding[] = [];
- const baseResult = new Map<string, string>();
- let checked = 0;
- for (const [scheme, vars] of all) {
- const page = color('--background', vars) ?? (scheme === 'dark' ? parseColor('#000') : parseColor('#fff'));
- const pairs = [...pairsOf(vars), ...extra.filter(([f, b]) => vars.has(f) && vars.has(b))];
- for (const [fgName, bgName] of pairs) {
- if (skip.has(`${fgName} ${bgName}`)) continue;
- if (ownOnly && !(where.has(`${scheme} ${fgName}`) && where.has(`${scheme} ${bgName}`))) continue;
- // An alias pair (Tailwind 4 `@theme inline { --color-x: var(--x) }`) repeats a pair that is checked by itself.
- const alias = (n: string) => /^var\((--[\w-]+)\)$/.exec((vars.get(n) ?? '').trim())?.[1];
- const [fa, ba] = [alias(fgName), alias(bgName)];
- if (fa && ba && pairs.some(([f, b]) => f === fa && b === ba)) continue;
- let bg = color(bgName, vars);
- let fg = color(fgName, vars);
- if (!bg || !fg || !page) continue;
- if (bg.a < 1 && ownOnly && !color('--background', vars)) continue; // what lies under it is defined elsewhere
- if (bg.a < 1) bg = over(bg, page.a < 1 ? over(page, parseColor('#fff') as RGBA) : page);
- if (fg.a < 1) fg = over(fg, bg);
- const key = `${fgName} ${bgName}`;
- const sig = `${hex(fg)} ${hex(bg)}`;
- if (scheme === 'base') baseResult.set(key, sig);
- else if (baseResult.get(key) === sig) continue; // same colors as :root: already counted there
- checked++;
- const ratio = contrast(fg, bg);
- // A part of the page that sets its own colors (`[data-theme=x] .sidebar { … }`) and makes the pair readable
- // there: the pair is taken to be used in that part.
- const fixedInScope = (scopes.get(scheme) ?? []).some((sv) => {
- if (!sv.has(fgName) && !sv.has(bgName)) return false;
- const f2 = color(fgName, sv), b2 = color(bgName, sv);
- if (!f2 || !b2) return false;
- const b3 = b2.a < 1 ? over(b2, page) : b2;
- return contrast(f2.a < 1 ? over(f2, b3) : f2, b3) + 1e-9 >= min && `${hex(f2)} ${hex(b2)}` !== sig;
- });
- if (ratio + 1e-9 < min && !fixedInScope) findings.push({ scheme, fg: fgName, bg: bgName, ratio, colors: `${hex(fg)} on ${hex(bg)}` });
- }
- }
- return { findings, where, checked };
- }
- export function check(root = process.cwd()): string[] {
- const { minContrast, pairs, skip } = config(root);
- const files = projectFiles(['css']).map((rel) => ({ rel, text: read(rel, root) }));
- // All stylesheets together (a theme split over files), and each one alone (a later file must not hide an earlier one).
- const seen = new Set<string>();
- const found: { f: Finding; at: string }[] = [];
- // Alone, a file is judged only on pairs it defines itself in a scheme (both colors), not on inherited halves.
- for (const set of [files, ...(files.length > 1 ? files.map((f) => [f]) : [])]) {
- const { findings, where } = measure(set, minContrast, pairs, skip, set !== files);
- for (const f of findings) {
- const at = where.get(`${f.scheme} ${f.fg}`) ?? where.get(`base ${f.fg}`) ?? '?';
- const key = `${at} ${f.scheme} ${f.fg} ${f.bg} ${f.colors}`;
- if (!seen.has(key)) { seen.add(key); found.push({ f, at }); }
- }
- }
- return found.map(({ f, at }) => {
- const scheme = f.scheme === 'base' ? ':root' : f.scheme;
- return `${at}: theme ${scheme}: ${f.fg} on ${f.bg} — contrast ${f.ratio.toFixed(2)}:1, at least ${minContrast}:1 needed (${f.colors})`;
- });
- }
- if (import.meta.main) report(check());