// WCAG contrast for design tokens written as oklch(). The conversion is // OKLab -> linear sRGB (Björn Ottosson's matrices) with a plain clip to the // sRGB gamut, which is what the browser draws for every token we ship. export interface Oklch { readonly l: number; readonly c: number; readonly h: number; } export function parseOklch(value: string): Oklch | null { const match = /^oklch\(\s*([\d.]+)(%?)\s+([\d.]+)\s+([\d.]+|none)\s*\)$/.exec( value.trim(), ); if (!match) return null; return { l: Number(match[1]) / (match[2] === "%" ? 100 : 1), c: Number(match[3]), h: match[4] === "none" ? 0 : Number(match[4]), }; } export function relativeLuminance({ l, c, h }: Oklch): number { const hue = (h * Math.PI) / 180; const a = c * Math.cos(hue); const b = c * Math.sin(hue); const long = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3; const medium = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3; const short = (l - 0.0894841775 * a - 1.291485548 * b) ** 3; const clip = (channel: number) => Math.min(1, Math.max(0, channel)); const red = clip(4.0767416621 * long - 3.3077115913 * medium + 0.2309699292 * short); const green = clip(-1.2684380046 * long + 2.6097574011 * medium - 0.3413193965 * short); const blue = clip(-0.0041960863 * long - 0.7034186147 * medium + 1.707614701 * short); return 0.2126 * red + 0.7152 * green + 0.0722 * blue; } export function contrastRatio(first: Oklch, second: Oklch): number { const [lighter, darker] = [relativeLuminance(first), relativeLuminance(second)] .sort((x, y) => y - x); return (lighter + 0.05) / (darker + 0.05); } export function readCustomProperties(css: string): Map { return new Map( [...css.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/g)].map( (match) => [match[1], match[2].trim()] as const, ), ); } // Follows var(--x) chains. Returns null for anything that is not a plain // oklch() at the end of the chain (color-mix, keywords), so callers fail // loudly instead of guessing. export function resolveColor( token: string, properties: ReadonlyMap, ): Oklch | null { let value = properties.get(token); for (let depth = 0; value !== undefined && depth < 8; depth += 1) { const reference = /^var\((--[a-z0-9-]+)\)$/.exec(value); if (!reference) return parseOklch(value); value = properties.get(reference[1]); } return null; }