/** * WCAG 2.1 contrast check of the built-in themes * (https://www.w3.org/TR/WCAG21/#contrast-minimum). Every token pair the * UI draws text with reaches AA: 4.5:1 for body text, 3:1 for non-text * marks (cursor, modified dot; WCAG 1.4.11). The themes come from * `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current` * keeps equal to `lutra_engine::theme`. */ import { describe, expect, it } from "vitest"; import themes from "./themes.json"; /** Minimum ratio for normal-size text (AA). */ const TEXT = 4.5; /** Minimum ratio for large text and non-text marks (AA). */ const LARGE = 3; /** * Foreground token, background token and minimum ratio, for every * combination the components use (see `ui/src/**` `color`/`background`). */ const PAIRS: [string, string, number][] = [ ["fg", "bg", TEXT], ["fg", "editor-bg", TEXT], ["fg", "tab-active-bg", TEXT], ["fg", "notice-bg", TEXT], ["fg", "editor-active-line-bg", TEXT], ["fg", "editor-selection-bg", TEXT], ["fg", "editor-match-bg", TEXT], ["fg-muted", "bg", TEXT], ["fg-muted", "editor-bg", TEXT], ["accent", "bg", TEXT], ["error", "bg", TEXT], ["error", "statusbar-bg", TEXT], ["statusbar-fg", "statusbar-bg", TEXT], ["editor-gutter-fg", "editor-gutter-bg", TEXT], ["editor-gutter-fg", "editor-active-line-bg", TEXT], ["editor-cursor", "editor-bg", LARGE], ["editor-cursor", "editor-active-line-bg", LARGE], ["tab-modified", "bg", LARGE], ["tab-modified", "tab-active-bg", LARGE], ]; /** * Relative luminance of a `#rrggbb` colour (WCAG 2.1 definition). * * @param hex - the colour. * @returns the luminance, 0 (black) to 1 (white). */ export function luminance(hex: string): number { const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex); if (!match) { throw new Error(`not a #rrggbb colour: ${hex}`); } const [r, g, b] = match.slice(1).map((part) => { const c = parseInt(part, 16) / 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }) as [number, number, number]; return 0.2126 * r + 0.7152 * g + 0.0722 * b; } /** * Contrast ratio of two colours. * * @param a - one `#rrggbb` colour. * @param b - the other. * @returns the ratio, 1 to 21. */ export function contrast(a: string, b: string): number { const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number]; return (hi + 0.05) / (lo + 0.05); } describe("contrast helper", () => { it("matches the WCAG extremes", () => { expect(contrast("#000000", "#ffffff")).toBeCloseTo(21, 5); expect(contrast("#777777", "#777777")).toBe(1); expect(contrast("#767676", "#ffffff")).toBeGreaterThanOrEqual(4.5); }); }); describe.each(themes)("theme $id", (theme) => { const tokens: Record = theme.tokens; const token = (name: string): string => { const value = tokens[`--lt-${name}`]; if (value === undefined) { throw new Error(`${theme.id} has no --lt-${name}`); } return value; }; it.each(PAIRS)("%s on %s reaches %d:1", (fg, bg, min) => { expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min); }); });