An open source design system that's fully customizable and agent ready
TypeScript
fix(core): guarantee WCAG contrast for generated color token pairs (#4354)
Baraa Hamodif81527af3c21
diff --git a/.changeset/a11y-token-contrast-assertions.md b/.changeset/a11y-token-contrast-assertions.mdnew file mode 100644index 0000000000..5dba6c0e25--- /dev/null+++ b/.changeset/a11y-token-contrast-assertions.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] theme: guarantee WCAG contrast for generated color token pairs — text-on-surface pairs are asserted at >= 4.5:1 and non-text UI pairs at >= 3:1 (WCAG 1.4.3/1.4.11), with `--color-border-emphasized` tone-bumped in generation until it clears 3:1 against the generated surface+@bhamodidiff --git a/packages/core/src/theme/contrast.test.ts b/packages/core/src/theme/contrast.test.tsnew file mode 100644index 0000000000..3fbd80c02d--- /dev/null+++ b/packages/core/src/theme/contrast.test.ts@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {relativeLuminance, compositeOver, contrastRatio} from './contrast';+import {parseColor} from '../utils/color';++describe('relativeLuminance', () => {+ it('is 0 for black and 1 for white', () => {+ expect(relativeLuminance({r: 0, g: 0, b: 0, a: 1})).toBe(0);+ expect(relativeLuminance({r: 255, g: 255, b: 255, a: 1})).toBeCloseTo(+ 1,+ 10,+ );+ });++ it('weights channels per WCAG (green brightest, blue darkest)', () => {+ const red = relativeLuminance({r: 255, g: 0, b: 0, a: 1});+ const green = relativeLuminance({r: 0, g: 255, b: 0, a: 1});+ const blue = relativeLuminance({r: 0, g: 0, b: 255, a: 1});+ expect(red).toBeCloseTo(0.2126, 4);+ expect(green).toBeCloseTo(0.7152, 4);+ expect(blue).toBeCloseTo(0.0722, 4);+ });+});++describe('contrastRatio', () => {+ it('is 21 for black on white and 1 for identical colors', () => {+ expect(contrastRatio('#000000', '#FFFFFF')).toBeCloseTo(21, 5);+ expect(contrastRatio('#3B82F6', '#3B82F6')).toBe(1);+ });++ it('is symmetric in fg/bg for opaque colors', () => {+ expect(contrastRatio('#0064E0', '#FCFDFE')).toBeCloseTo(+ contrastRatio('#FCFDFE', '#0064E0'),+ 10,+ );+ });++ it('matches the canonical 4.5:1 boundary gray (#767676 on white)', () => {+ const ratio = contrastRatio('#767676', '#FFFFFF');+ expect(ratio).toBeGreaterThanOrEqual(4.5);+ expect(ratio).toBeLessThan(4.6);+ });++ it('composites a translucent foreground over the background', () => {+ // 50% black over white paints as mid-gray, not black.+ const composited = contrastRatio('rgba(0, 0, 0, 0.5)', '#FFFFFF');+ expect(composited).toBeLessThan(contrastRatio('#000000', '#FFFFFF'));+ expect(composited).toBeCloseTo(+ contrastRatio('rgb(127.5, 127.5, 127.5)', '#FFFFFF'),+ 10,+ );+ });++ it('rejects a translucent background', () => {+ expect(() => contrastRatio('#000000', '#FFFFFF80')).toThrow(+ /background must be opaque/,+ );+ });++ it('rejects unparseable colors', () => {+ expect(() => contrastRatio('var(--color-accent)', '#FFFFFF')).toThrow(+ /could not parse foreground/,+ );+ expect(() => contrastRatio('#000000', 'oklch(0.5 0.1 200)')).toThrow(+ /could not parse background/,+ );+ });+});++describe('compositeOver', () => {+ it('returns the foreground when opaque and the backdrop at alpha 0', () => {+ const fg = parseColor('#123456');+ const bg = parseColor('#FFFFFF');+ if (fg === null || bg === null) {+ throw new Error('fixture colors must parse');+ }+ expect(compositeOver(fg, bg)).toEqual({...fg, a: 1});+ expect(compositeOver({...fg, a: 0}, bg)).toEqual({...bg, a: 1});+ });++ it('blends in gamma-encoded sRGB space like CSS', () => {+ const fg = parseColor('rgba(0, 0, 0, 0.5)');+ const bg = parseColor('#FFFFFF');+ if (fg === null || bg === null) {+ throw new Error('fixture colors must parse');+ }+ const out = compositeOver(fg, bg);+ expect(out.r).toBeCloseTo(127.5, 5);+ expect(out.g).toBeCloseTo(127.5, 5);+ expect(out.b).toBeCloseTo(127.5, 5);+ expect(out.a).toBe(1);+ });+});diff --git a/packages/core/src/theme/contrast.ts b/packages/core/src/theme/contrast.tsnew file mode 100644index 0000000000..ab6c658f60--- /dev/null+++ b/packages/core/src/theme/contrast.ts@@ -0,0 +1,99 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file contrast.ts+ * @input CSS color strings (hex, rgb()/rgba()) or parsed RGBA values+ * @output WCAG 2.x relative luminance and contrast ratios+ * @position Theme utility; consumed by expandColorScale.ts and theme tests+ *+ * Dependency-free WCAG 2.x contrast math. Backs the contrast guarantees+ * for generated color tokens (WCAG 1.4.3 text contrast >= 4.5:1,+ * WCAG 1.4.11 non-text contrast >= 3:1).+ *+ * Semi-transparent foregrounds are composited over their backdrop in+ * gamma-encoded sRGB space (matching CSS alpha compositing) before the+ * ratio is measured — a translucent token has no contrast of its own,+ * only against what it renders on.+ */++import type {RGBA} from '../utils/color';+import {parseColor} from '../utils/color';++/**+ * WCAG 2.x relative luminance of an sRGB color (alpha ignored).+ * 0 = black, 1 = white.+ *+ * https://www.w3.org/WAI/WCAG22/Techniques/general/G18+ */+export function relativeLuminance(color: RGBA): number {+ const channel = (c: number): number => {+ const s = c / 255;+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);+ };+ return (+ 0.2126 * channel(color.r) ++ 0.7152 * channel(color.g) ++ 0.0722 * channel(color.b)+ );+}++/**+ * Composite a (possibly translucent) foreground over an opaque backdrop+ * using standard source-over alpha blending in gamma-encoded sRGB space,+ * matching how CSS paints translucent tokens. Returns an opaque color.+ */+export function compositeOver(foreground: RGBA, backdrop: RGBA): RGBA {+ const a = foreground.a;+ return {+ r: foreground.r * a + backdrop.r * (1 - a),+ g: foreground.g * a + backdrop.g * (1 - a),+ b: foreground.b * a + backdrop.b * (1 - a),+ a: 1,+ };+}++function resolve(value: string | RGBA, label: string): RGBA {+ if (typeof value !== 'string') {+ return value;+ }+ const parsed = parseColor(value);+ if (parsed === null) {+ throw new TypeError(`contrastRatio: could not parse ${label} "${value}"`);+ }+ return parsed;+}++/**+ * WCAG 2.x contrast ratio between a foreground and an opaque background.+ * Returns a value in [1, 21].+ *+ * A translucent foreground is composited over the background first.+ * A translucent background is rejected — composite it over its own+ * backdrop before calling, since its rendered color is unknowable here.+ *+ * @example+ * ```+ * contrastRatio('#000000', '#FFFFFF'); // 21+ * contrastRatio('#0D131A', '#FCFDFE') >= 4.5; // text-on-surface check+ * ```+ */+export function contrastRatio(+ foreground: string | RGBA,+ background: string | RGBA,+): number {+ const bg = resolve(background, 'background');+ if (bg.a < 1) {+ throw new TypeError(+ 'contrastRatio: background must be opaque — composite it over its backdrop first',+ );+ }+ let fg = resolve(foreground, 'foreground');+ if (fg.a < 1) {+ fg = compositeOver(fg, bg);+ }+ const lumA = relativeLuminance(fg);+ const lumB = relativeLuminance(bg);+ const lighter = Math.max(lumA, lumB);+ const darker = Math.min(lumA, lumB);+ return (lighter + 0.05) / (darker + 0.05);+}diff --git a/packages/core/src/theme/expandColorScale.test.ts b/packages/core/src/theme/expandColorScale.test.tsindex 607ef81815..02254b490b 100644--- a/packages/core/src/theme/expandColorScale.test.ts+++ b/packages/core/src/theme/expandColorScale.test.ts@@ -1,11 +1,14 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, it, expect} from 'vitest';-import {expandColorScale} from './expandColorScale';+import {expandColorScale, ensureContrastTone} from './expandColorScale';+import {contrastRatio, compositeOver} from './contrast';+import {hexToHct, tonalPalette} from './hct';import {defineTheme} from './defineTheme';import {generateThemeRules} from './generateThemeRules';import {resolveThemeTokens} from './tokens';import {colorDefaults} from './tokens.stylex';+import {parseColor, formatColor} from '../utils/color';/** Light-mode half of colorDefaults['--color-accent'] — the hue an accent-less config seeds from. */const DEFAULT_ACCENT = '#0064E0';@@ -255,3 +258,242 @@ describe('expandColorScale + defineTheme integration', () => {expect(css).toContain('--color-text-accent: var(--color-accent);');});});++// =============================================================================+// WCAG contrast guarantees (WCAG 1.4.3 text >= 4.5:1, 1.4.11 non-text >= 3:1)+// =============================================================================++/** Split a light-dark(a, b) token into its [light, dark] halves. */+function splitLightDark(value: string): [light: string, dark: string] {+ const match = value.match(/^light-dark\((.+?),\s*(.+)\)$/);+ if (!match) {+ // Single-value tokens apply to both modes.+ return [value, value];+ }+ return [match[1], match[2]];+}++type Mode = 0 | 1; // 0 = light, 1 = dark++/** Resolve one mode of a token to a concrete color string. */+function resolveToken(+ tokens: Record<string, string>,+ name: string,+ mode: Mode,+): string {+ return splitLightDark(tokens[name])[mode];+}++/** Resolve one mode of an alpha token, composited over its backdrop. */+function resolveComposited(+ tokens: Record<string, string>,+ name: string,+ backdrop: string,+ mode: Mode,+): string {+ const fg = parseColor(resolveToken(tokens, name, mode));+ const bg = parseColor(backdrop);+ if (fg === null || bg === null) {+ throw new Error(`could not parse ${name} or its backdrop`);+ }+ return formatColor(compositeOver(fg, bg));+}++describe('expandColorScale WCAG contrast guarantees', () => {+ // Representative configs: the docs' default accent, both contrast levels,+ // every neutralStyle, saturated custom brand accents across the hue wheel,+ // a low-chroma (gray) seed, and degenerate black/white seeds.+ const configs = [+ {accent: '#0064E0'},+ {accent: '#0064E0', contrast: 'high'},+ {accent: '#DC2626', neutralStyle: 'warm'},+ {accent: '#B7410E', neutralStyle: 'warm', contrast: 'high'},+ {accent: '#12B76A', neutralStyle: 'neutral'},+ {accent: '#D9006E', neutralStyle: 'warm'},+ {accent: '#657100', neutralStyle: 'cool'},+ {accent: '#6B7280'},+ {accent: '#000000'},+ {accent: '#FFFFFF', neutralStyle: 'neutral', contrast: 'high'},+ ] as const;++ const modes: [label: string, mode: Mode][] = [+ ['light', 0],+ ['dark', 1],+ ];++ describe.each(configs)('config %o', config => {+ const tokens = expandColorScale(config);++ it.each(modes)(+ 'text tokens meet 4.5:1 on the surfaces the system pairs them with (%s)',+ (_label, mode) => {+ const surface = resolveToken(+ tokens,+ '--color-background-surface',+ mode,+ );+ const body = resolveToken(tokens, '--color-background-body', mode);+ const card = resolveToken(tokens, '--color-background-card', mode);+ const popover = resolveToken(+ tokens,+ '--color-background-popover',+ mode,+ );+ // Alpha tokens paint over the surface — composite before measuring.+ const muted = resolveComposited(+ tokens,+ '--color-background-muted',+ surface,+ mode,+ );+ const neutral = resolveComposited(+ tokens,+ '--color-neutral',+ surface,+ mode,+ );++ const textPrimary = resolveToken(tokens, '--color-text-primary', mode);+ const textSecondary = resolveToken(+ tokens,+ '--color-text-secondary',+ mode,+ );+ const accent = resolveToken(tokens, '--color-accent', mode);+ const onAccent = resolveToken(tokens, '--color-on-accent', mode);++ // Primary text on every generated background it renders on.+ for (const bg of [surface, body, card, popover, muted, neutral]) {+ expect(contrastRatio(textPrimary, bg)).toBeGreaterThanOrEqual(4.5);+ }+ // Secondary/muted text on the main content surfaces.+ for (const bg of [surface, body, card, popover]) {+ expect(contrastRatio(textSecondary, bg)).toBeGreaterThanOrEqual(4.5);+ }+ // Accent-colored text (--color-text-accent references --color-accent).+ expect(contrastRatio(accent, surface)).toBeGreaterThanOrEqual(4.5);+ // Label text on accent-filled controls (primary buttons).+ expect(contrastRatio(onAccent, accent)).toBeGreaterThanOrEqual(4.5);+ },+ );++ it.each(modes)(+ 'non-text UI tokens meet 3:1 against the surface (%s)',+ (_label, mode) => {+ const surface = resolveToken(+ tokens,+ '--color-background-surface',+ mode,+ );+ // Accent-filled controls and focus indicators.+ expect(+ contrastRatio(resolveToken(tokens, '--color-accent', mode), surface),+ ).toBeGreaterThanOrEqual(3);+ // Meaningful icons alongside text.+ expect(+ contrastRatio(+ resolveToken(tokens, '--color-icon-primary', mode),+ surface,+ ),+ ).toBeGreaterThanOrEqual(3);+ expect(+ contrastRatio(+ resolveToken(tokens, '--color-icon-secondary', mode),+ surface,+ ),+ ).toBeGreaterThanOrEqual(3);+ // Form-control boundaries (CheckboxInput, Selector borders).+ expect(+ contrastRatio(+ resolveToken(tokens, '--color-border-emphasized', mode),+ surface,+ ),+ ).toBeGreaterThanOrEqual(3);+ },+ );+ });++ it('documents the intentionally decorative tokens excluded from 3:1', () => {+ // These tokens are decorative or redundant cues, not WCAG 1.4.11+ // boundaries, and are deliberately NOT held to 3:1:+ // - --color-border: hairline separator (~1.1:1 by design). Components+ // that rely on it as their only boundary are tracked separately.+ // - --color-skeleton: loading placeholder; conveys no information.+ // - --color-track: rail behind a >= 3:1 thumb/fill (Slider, Switch,+ // ProgressBar) — the indicator, not the rail, carries state.+ // - --color-text-disabled / --color-icon-disabled: disabled controls+ // are explicitly exempt from WCAG 1.4.3/1.4.11.+ // Lock in the decorative alpha form of --color-border so a future+ // change that starts relying on it for contrast shows up here.+ const tokens = expandColorScale({accent: '#0064E0'});+ const [light, dark] = splitLightDark(tokens['--color-border']);+ for (const half of [light, dark]) {+ const parsed = parseColor(half);+ expect(parsed).not.toBeNull();+ expect(parsed !== null && parsed.a).toBeLessThanOrEqual(0.2);+ }+ });+});++describe('ensureContrastTone', () => {+ it('returns the starting tone when it already meets the ratio', () => {+ // Tone 10 on a near-white background is far past 4.5:1 already.+ const hex = ensureContrastTone(282, 8, 10, -1, '#FCFDFE', 4.5);+ expect(hex).toBe(ensureContrastTone(282, 8, 10, 1, '#FCFDFE', 1));+ });++ it('bumps the tone until the ratio passes', () => {+ // Tone 70 sits around 2.2:1 on a near-white surface — below 3:1.+ const before = ensureContrastTone(282, 8, 70, -1, '#FCFDFE', 1);+ expect(contrastRatio(before, '#FCFDFE')).toBeLessThan(3);+ const after = ensureContrastTone(282, 8, 70, -1, '#FCFDFE', 3);+ expect(contrastRatio(after, '#FCFDFE')).toBeGreaterThanOrEqual(3);+ });++ it('terminates at the tone floor/ceiling for impossible ratios', () => {+ // 22:1 is unreachable; the loop must stop at pure black.+ expect(ensureContrastTone(282, 8, 70, -1, '#FFFFFF', 22)).toBe('#000000');+ expect(ensureContrastTone(282, 8, 30, 1, '#000000', 22)).toBe('#FFFFFF');+ });+});++// =============================================================================+// --color-border-emphasized: concrete before/after delta+// =============================================================================+//+// This is the one generated token whose emitted VALUE changes. Every other+// token is byte-identical to the pre-change output; they only gained the+// assertions above. Before this change the token was emitted directly as the+// neutral-variant palette's tone 70 (light) / 30 (dark) — `ld(NV[70], NV[30])`.+// Those preferred tones land BELOW the WCAG 1.4.11 3:1 floor against the+// generated surface, so the generator now tone-bumps them until they clear+// 3:1. These tests reconstruct the exact old output and lock in the delta so+// the correction can't silently regress to the sub-3:1 value.+describe('--color-border-emphasized WCAG 1.4.11 correction (before/after)', () => {+ const config = {accent: '#0064E0'} as const; // docs default, cool neutrals+ const NEUTRAL_VARIANT_CHROMA_COOL = 8; // NEUTRAL_VARIANT_CHROMA.cool+ const {hue} = hexToHct(config.accent);+ // Exactly what the pre-change generator emitted: NV[70] light / NV[30] dark.+ const nv = tonalPalette(hue, NEUTRAL_VARIANT_CHROMA_COOL);+ const tokens = expandColorScale(config);++ it('light: old NV[70] (~2.24:1) is corrected to >= 3:1', () => {+ const surface = resolveToken(tokens, '--color-background-surface', 0);+ const oldValue = nv[70];+ const newValue = resolveToken(tokens, '--color-border-emphasized', 0);+ expect(contrastRatio(oldValue, surface)).toBeCloseTo(2.24, 1);+ expect(contrastRatio(oldValue, surface)).toBeLessThan(3);+ expect(newValue).not.toBe(oldValue);+ expect(contrastRatio(newValue, surface)).toBeGreaterThanOrEqual(3);+ });++ it('dark: old NV[30] (~1.84:1) is corrected to >= 3:1', () => {+ const surface = resolveToken(tokens, '--color-background-surface', 1);+ const oldValue = nv[30];+ const newValue = resolveToken(tokens, '--color-border-emphasized', 1);+ expect(contrastRatio(oldValue, surface)).toBeCloseTo(1.84, 1);+ expect(contrastRatio(oldValue, surface)).toBeLessThan(3);+ expect(newValue).not.toBe(oldValue);+ expect(contrastRatio(newValue, surface)).toBeGreaterThanOrEqual(3);+ });+});diff --git a/packages/core/src/theme/expandColorScale.ts b/packages/core/src/theme/expandColorScale.tsindex 2795786bd6..f6b996ac31 100644--- a/packages/core/src/theme/expandColorScale.ts+++ b/packages/core/src/theme/expandColorScale.ts@@ -15,11 +15,23 @@* ramp (seeded from the default accent's hue) while the accent tokens* themselves fall through to colorDefaults, same as the tokens above.*+ * WCAG contrast guarantees (asserted in expandColorScale.test.ts):+ * - Text tones are guaranteed >= 4.5:1 against their surfaces by tone+ * spacing alone — HCT tone is CIE L*, which fixes relative luminance+ * regardless of hue/chroma, so the fixed tone assignments hold for any+ * accent/neutralStyle (WCAG 1.4.3).+ * - --color-border-emphasized (form-control boundaries) is tone-bumped+ * until it reaches >= 3:1 against the generated surface (WCAG 1.4.11).+ * - --color-border, --color-skeleton, and --color-track are intentionally+ * decorative/redundant cues and are NOT held to 3:1 — see the test file+ * for the rationale.+ ** SYNC: When modified, update:* - /packages/core/src/theme/defineTheme.ts*/-import {hexToHct, tonalPalette, hexWithAlpha} from './hct';+import {contrastRatio} from './contrast';+import {hexToHct, hctToHex, tonalPalette, hexWithAlpha} from './hct';// =============================================================================// Types@@ -103,6 +115,39 @@ function accentWithAlpha(alpha: number): string {return `color-mix(in srgb, var(--color-accent) ${alpha * 100}%, transparent)`;}+/** WCAG 1.4.11 minimum contrast for non-text UI boundaries. */+const NON_TEXT_MIN_CONTRAST = 3;++/**+ * Walk tone in `step` increments from `startTone` until the color reaches+ * `minRatio` against `background`, and return the resulting hex.+ *+ * Used for tokens whose preferred tone is not guaranteed by tone spacing+ * alone (e.g. --color-border-emphasized). Because HCT tone is CIE L*,+ * each step moves luminance monotonically, so the loop always terminates —+ * at worst at pure black/white (21:1 against anything mid-range).+ */+export function ensureContrastTone(+ hue: number,+ chroma: number,+ startTone: number,+ step: -1 | 1,+ background: string,+ minRatio: number,+): string {+ let tone = startTone;+ let hex = hctToHex({hue, chroma, tone});+ while (+ contrastRatio(hex, background) < minRatio &&+ tone + step >= 0 &&+ tone + step <= 100+ ) {+ tone += step;+ hex = hctToHex({hue, chroma, tone});+ }+ return hex;+}+/*** Expand a color scale config into Astryx color token overrides.*@@ -145,6 +190,31 @@ export function expandColorScale(config: ColorScaleConfig): ColorScaleTokens {const textSecondaryLightTone = isHigh ? 20 : 30;const textSecondaryDarkTone = isHigh ? 80 : 70;+ // Emphasized borders outline form controls (CheckboxInput, Selector), so+ // they are non-text UI boundaries under WCAG 1.4.11 and must reach 3:1+ // against the surface they sit on. The preferred tones (70 light /+ // 30 dark) land around 2.2:1 / 1.8:1, so bump the tone toward the+ // opposing extreme until the ratio passes. Text tones need no such loop:+ // their spacing guarantees >= 4.5:1 for any hue/chroma (see file header).+ const borderEmphasized = ld(+ ensureContrastTone(+ seedHue,+ neutralVariantChroma,+ 70,+ -1,+ N[99],+ NON_TEXT_MIN_CONTRAST,+ ),+ ensureContrastTone(+ seedHue,+ neutralVariantChroma,+ 30,+ 1,+ N[10],+ NON_TEXT_MIN_CONTRAST,+ ),+ );+return {// Core semantic — only with a seed accent. Without one these fall through// to colorDefaults, whose --color-accent is NOT what the default seed@@ -206,8 +276,9 @@ export function expandColorScale(config: ColorScaleConfig): ColorScaleTokens {'--color-background-inverted': ld(N[10], N[99]),// Border+ // Decorative hairline (~1.1:1 by design) — not a WCAG 1.4.11 boundary.'--color-border': ld(hexWithAlpha(N[10], 0.1), hexWithAlpha(N[95], 0.1)),- '--color-border-emphasized': ld(NV[70], NV[30]),+ '--color-border-emphasized': borderEmphasized,// Effects'--color-skeleton': ld(NV[70], NV[30]),