/** * The numeric-twin accessibility gates and the cap recomputation for the * derived OKLCH color system, over the resolution core in `theme_resolver.ts`: * * - `check_theme` evaluates the gamut, ramp-monotonicity, and contrast gates * against an arbitrary theme (the base theme's defaults included), reusing * the `ramps.ts` numeric twin, `oklch.ts` conversions, and `wcag.ts` * ratios. It is report-only and never throws. * - `compute_theme_caps` recomputes the per-stop worst-hue chroma caps for a * theme's own hues and the palette lightness each stop resolves to, * returning `_palette_chroma_NN` caps where the baked ones no longer fit. * `compile_theme` in `theme_compile.ts` pairs them with the re-check and * the lint. * * @module */ import { clamp } from '@fuzdev/fuz_util/maths.ts'; import { clamp_oklch, oklab_to_srgb, oklch_to_srgb, srgb_to_oklab, type RgbUnit } from '@fuzdev/fuz_util/oklch.ts'; import type { StyleVariable, Theme } from './variable.ts'; import { to_theme_stance } from './theme.ts'; import { default_variables } from './variables.ts'; import { PALETTE_CHROMA_CAPS, BORDER_COLOR_ALPHAS, BORDER_CONTRAST_STOPS, CONTRAST_NAME, HIGH_CONTRAST, border_contrast_share, render_border_color_css, ramp_color_oklch, neutral_color_oklch, neutral_ground_chroma_weight, SHADE_GROUND_CHROMA_NAME, compute_worst_hue_chroma_cap, render_chroma_stop_css, to_chroma_shape_name, to_lightness_stop_name, to_palette_chroma_name, CSS_NUMBER_PATTERN, type RampFamily } from './ramps.ts'; import { numeric_scale_variants, palette_variants, intent_variants, color_scheme_variants, type NumericScaleVariant, type ColorScheme, type PaletteVariant } from './variable_data.ts'; import { wcag_contrast_ratio } from './wcag.ts'; import { NUMERIC_EPSILON, STOPS_PATTERN, ThemeResolver, VAR_MATCHER } from './theme_resolver.ts'; // // Gate thresholds - the WCAG levels the derived palette is designed to clear. // /** AAA body text: `--text_color` (`text_80` by default) on `shade_00`/`05`/`10`. */ export const GATE_BODY_TEXT = 7; /** Disabled/secondary floor: `--text_disabled` (`text_50` by default) on `shade_00`. */ export const GATE_SUBTLE_TEXT = 3; /** * AA links: `--link_color` (the accent at stop 60 by default) on `shade_00`, * plus that stop itself when a theme repoints the role, since * `label.selected` paints it directly, and an authored `--link_color_selected`. */ export const GATE_LINK = 4.5; /** * WCAG 1.4.11 non-text: every hue at stop 50 vs `shade_00`, and an authored * `--outline_color` (the focus ring, the accent at stop 50 by default). */ export const GATE_UI = 3; /** Large-text floor: `text_max` on every stop-50 fill. */ export const GATE_FILL_TEXT = 3; /** * AA selected-control inverse text: `text_00` on `shade_70` and on every * stop-60 fill - the selected-button pairings in `style.css` (`.selected` * fills with `shade_70`, `.palette_X.selected` with `palette_X_60`). The * endpoint stop is immune to `text_lightness_curve` bends, so this gate moves * only when a theme moves the endpoints, the fill ramps, or the hues. */ export const GATE_SELECTED_TEXT = 4.5; /** * AA colored labels: every palette hue at stop 60 on `shade_00` (colored * text) and on its own stop-10 tint (the chip), and the `.palette_X` button * label - the hue at stop 70 - on each of the button's fills. The * fills follow the `style.css` recipe: the hue at stop 60 at 8% alpha at * rest (and focused), 16% hovered, and 24% pressed, composited over * `shade_00` in gamma-encoded sRGB. A hovered label mixes 10% toward * `shade_max` in oklab, so a mouse press pairs that label with the pressed * fill, and a keyboard press, which doesn't hover, pairs the plain label with * it. An 8-bit raster quantizes both colors, so a rendered measurement lands * within about 0.15 of the ratio, and the gate reads it low more often than * high. */ export const GATE_PALETTE_TEXT = 4.5; /** * Control borders: `--border_color` (by default `shade_30` mixed a little * toward `shade_50`, all the way with contrast - `BORDER_CONTRAST_STOPS`, * `BORDER_CONTRAST_REST_SHARE`) vs `shade_00`, below * `HIGH_CONTRAST`. A regression floor for the shipped design, not a WCAG * level - 1.4.11's 3:1 applies to required component boundaries, and fuz * borders sit deliberately softer - so a theme can't silently wash control * borders out. */ export const GATE_BORDER = 1.5; /** * Control borders at an effective contrast of `HIGH_CONTRAST` or more: * WCAG 1.4.11's 3:1, the floor a theme that asks for contrast (or that the OS * preference raises) holds its control boundaries to, replacing * `GATE_BORDER` - against `shade_00` and, only then, against `shade_10`, the * first raised surface a control sits on. */ export const GATE_BORDER_HIGH_CONTRAST = 3; /** * Divider borders: the `border_color_30` alpha color composited over * `shade_00` (the `hr` pairing in `style.css`). A regression floor like * `GATE_BORDER`. */ export const GATE_BORDER_DIVIDER = 1.3; /** * Gamut gate: how far outside sRGB (the largest channel excess) a stop may sit and * still pass - float noise, not visible clipping. */ export const GATE_GAMUT_TOLERANCE = 1e-4; // // Report types. // /** Which accessibility gate an entry belongs to. */ export type ThemeGateId = 'gamut' | 'monotonicity' | 'contrast'; /** * A single gate measurement against a theme. The `value`/`threshold` * comparison direction depends on the gate: `contrast` passes at * `value >= threshold` (a WCAG ratio floor), `monotonicity` at * `value > threshold` (the minimum ramp step must exceed 0), and `gamut` at * `value <= threshold` (sRGB channel excess stays within tolerance). `pass` * is authoritative; renderers formatting the comparison switch on `gate`. */ export interface ThemeGateEntry { gate: ThemeGateId; scheme: ColorScheme; subject: string; value: number; threshold: number; pass: boolean; } /** * A gate input the checker couldn't evaluate, so the gates reading it were * skipped: a knob or derived stop that doesn't resolve to a number, or a * pinned color in a form the gates don't read. */ export interface ThemeUncheckedEntry { variable: string; value: string; reason: string; } /** * The result of `check_theme`. The two verdicts are separate questions: * whether what was measured holds, and whether everything was measured - a * theme that passes every gate it could evaluate may still have inputs the * gates couldn't read. */ export interface ThemeCheckReport { /** Every evaluated entry passes - vacuously true when there are none. */ passed: boolean; /** Nothing was left unchecked, so `entries` covers every gate input. */ complete: boolean; entries: Array; unchecked: Array; } // // check_theme - the numeric-twin accessibility gates. // const clamp_rgb = (rgb: RgbUnit): RgbUnit => [ clamp(rgb[0], 0, 1), clamp(rgb[1], 0, 1), clamp(rgb[2], 0, 1) ]; // max sRGB channel excess outside [0, 1] - 0 when in gamut const gamut_excess = ([r, g, b]: RgbUnit): number => Math.max(0, -r, r - 1, -g, g - 1, -b, b - 1); // source-over compositing of a translucent color on an opaque backdrop, in // gamma-encoded sRGB - how browsers stack backgrounds and borders const composite_over = (color: RgbUnit, alpha: number, backdrop: RgbUnit): RgbUnit => [ alpha * color[0] + (1 - alpha) * backdrop[0], alpha * color[1] + (1 - alpha) * backdrop[1], alpha * color[2] + (1 - alpha) * backdrop[2] ]; // the fills of a `.palette_X` button in `style.css`, each // `color-mix(in oklab, var(--fill) N%, transparent)` - the fill color at this // alpha - for `--button_fill`, `--button_fill_hover`, and `--button_fill_active` const BUTTON_FILL_ALPHAS = { rest: 0.08, hover: 0.16, active: 0.24 } as const; // a hovered button's label in `style.css`: // `color-mix(in oklab, var(--text_color) 90%, var(--shade_max))` const BUTTON_HOVER_LABEL_WEIGHT = 0.9; // the stops a `.palette_X` button in `style.css` paints: the label // (`--text_color`) and the color its fills tint with (`--fill`) const PALETTE_BUTTON_LABEL_STOP = '70'; const PALETTE_BUTTON_FILL_STOP = '60'; // mixes two opaque colors in oklab, as `color-mix(in oklab, a W%, b)` does const mix_oklab = (a: RgbUnit, weight: number, b: RgbUnit): RgbUnit => { const [al, aa, ab] = srgb_to_oklab(a); const [bl, ba, bb] = srgb_to_oklab(b); return clamp_rgb( oklab_to_srgb([ weight * al + (1 - weight) * bl, weight * aa + (1 - weight) * ba, weight * ab + (1 - weight) * bb ]) ); }; /** A color a gate reads: unclamped gamma-encoded sRGB and alpha in [0, 1]. */ interface GateColor { rgb: RgbUnit; alpha: number; } // the color literal the gates evaluate: `oklch(L C H)` with plain numeric // components and an optional `/ alpha` (a number or a percentage) const OKLCH_LITERAL_MATCHER = new RegExp( String.raw`^oklch\(\s*(${CSS_NUMBER_PATTERN})\s+(${CSS_NUMBER_PATTERN})\s+(${CSS_NUMBER_PATTERN})\s*(?:\/\s*(${CSS_NUMBER_PATTERN})(%?)\s*)?\)$`, 'iu' ); // parses an authored color literal, clamping lightness, chroma, and alpha the // way the browser clamps a parsed `oklch()`; `null` for every other form const parse_color_literal = (value: string): GateColor | null => { const m = OKLCH_LITERAL_MATCHER.exec(value); if (!m) return null; const alpha = m[4] === undefined ? 1 : Number(m[4]) / (m[5] ? 100 : 1); return { rgb: oklch_to_srgb(clamp_oklch([Number(m[1]), Number(m[2]), Number(m[3])])), alpha: clamp(alpha, 0, 1) }; }; const REASON_COLOR_FORM = 'authored color is neither an oklch(L C H) numeric literal nor an exact var() reference, so the gates reading it are skipped'; const REASON_COLOR_REFERENCE = 'authored color references a variable the gates cannot evaluate, so the gates reading it are skipped'; const REASON_COLOR_ALPHA = 'authored color is translucent where the gates read an opaque color, so they are skipped'; // the names of the color variables the gates can evaluate, beyond the aliases const PALETTE_STOP_MATCHER = new RegExp(`^palette_([a-j])_(${STOPS_PATTERN})$`, 'u'); const INTENT_STOP_MATCHER = new RegExp(`^(${intent_variants.join('|')})_(${STOPS_PATTERN})$`, 'u'); const NEUTRAL_STOP_MATCHER = new RegExp(`^(shade|text)_(${STOPS_PATTERN})$`, 'u'); const BORDER_COLOR_STOP_MATCHER = new RegExp(`^border_color_(${STOPS_PATTERN})$`, 'u'); const EXTREME_MATCHER = /^(?:shade|text)_(min|max)$/u; // the control border role, whose default is the one derived role: a mix of // two shade stops by the effective contrast (`render_border_color_css`) // rather than a plain alias const BORDER_ROLE = 'border_color'; const BORDER_ROLE_DEFAULT = render_border_color_css(); // the aliases the declared defaults carry - a variable whose default is // exactly `var(--x)`, like the roles `text_color` → `text_80` and // `link_color_selected` → `text_color`. Read from the declarations, so what a // role falls back to can't drift from what ships const ALIAS_DEFAULTS: Map = new Map( default_variables.flatMap((v): Array<[string, string]> => { const m = v.base !== undefined && v.dark === undefined ? VAR_MATCHER.exec(v.base) : null; return m ? [[v.name, m[1]!]] : []; }) ); /** * A contrast gate over one painted color and the shade stops it sits on. * `color` names what `style.css` paints: a role variable (`text_color`), * which the gate follows through whatever the theme points it at, or a stop * painted directly (`text_00`). */ interface PairingGate { color: string; /** How the subject reads: ` on|vs|over shade_NN`. */ relation: 'on' | 'vs' | 'over'; grounds: ReadonlyArray; threshold: number; /** * The threshold in place of `threshold` at an effective contrast of * `HIGH_CONTRAST` or more. */ high_contrast_threshold?: number; /** * The grounds in place of `grounds` at an effective contrast of * `HIGH_CONTRAST` or more - a pairing the design holds only once contrast * is asked for. */ high_contrast_grounds?: ReadonlyArray; /** * The role's default pairing is another gate's entry, so it gets its own * only when the theme authors it. */ when_authored?: boolean; /** * `style.css` also paints the role's default stop directly, so that stop * stays gated when the theme repoints the role. */ default_painted?: boolean; } // the single-color pairings, in report order. A role is gated here and // nowhere else: its default comes from `ALIAS_DEFAULTS` - except the control // border's, a contrast-driven mix of two shade stops that `check_theme` // derives - and `check_theme` measures whatever the theme points it at const PAIRING_GATES: ReadonlyArray = [ // body text on the page and the first raised surfaces { color: 'text_color', relation: 'on', grounds: ['00', '05', '10'], threshold: GATE_BODY_TEXT }, // selected-control inverse text on the neutral selected fill { color: 'text_00', relation: 'on', grounds: ['70'], threshold: GATE_SELECTED_TEXT }, { color: 'text_disabled', relation: 'on', grounds: ['00'], threshold: GATE_SUBTLE_TEXT }, { color: BORDER_ROLE, relation: 'vs', grounds: ['00'], threshold: GATE_BORDER, high_contrast_threshold: GATE_BORDER_HIGH_CONTRAST, // a control on the first raised surface holds the floor too, once // contrast is asked for - at no contrast the soft default sits just // above `GATE_BORDER` there, so the pairing isn't held then high_contrast_grounds: ['00', '10'] }, // the `hr` divider, the one translucent default { color: 'border_color_30', relation: 'over', grounds: ['00'], threshold: GATE_BORDER_DIVIDER }, // `label.selected` paints the link's default stop itself { color: 'link_color', relation: 'on', grounds: ['00'], threshold: GATE_LINK, default_painted: true }, // a selected link reads as body text by default, which the first gate covers { color: 'link_color_selected', relation: 'on', grounds: ['00'], threshold: GATE_LINK, when_authored: true }, // the focus ring is the accent at stop 50 by default, which the fill gate covers { color: 'outline_color', relation: 'vs', grounds: ['00'], threshold: GATE_UI, when_authored: true } ]; /** * The role variables the contrast gates follow - each aliases a color stop or * another role by default (`text_color` is `var(--text_80)`), except the * control border, which mixes two shade stops by the effective contrast - and * `check_theme` measures whatever a theme points it at instead of the * default it left. */ export const theme_gate_role_names: ReadonlyArray = PAIRING_GATES.map( (gate) => gate.color ).filter((name) => name === BORDER_ROLE || ALIAS_DEFAULTS.has(name)); const NO_VISITS: ReadonlySet = new Set(); /** * Options for `check_theme`. The stance mirror needs no passing, since the * gates derive it from the theme's stance. */ export interface CheckThemeOptions { /** * The compiled caps to check the theme with, as `compute_theme_caps` * returns them - without them the gates measure the baked caps, which a * theme with moved hues or lightness can exceed. */ caps?: Array; } /** * Runs the gamut, monotonicity, and contrast gates against a theme, resolving * its authored CSS back to numbers through the resolution core. Report-only: * failures land in `entries` (with `pass: false`), inputs that can't be * evaluated land in `unchecked`; `passed` says every entry passes and * `complete` that nothing is unchecked. Never throws. * * Every color a gate reads is looked up by its variable name, so a theme that * authors one directly - a stop (`palette_a_50`, `shade_00`, `text_max`, * `border_color_30`) or a role (`text_color`, `link_color`, `border_color`) - * is measured at the authored color when it is an `oklch(L C H)` numeric * literal or an exact `var()` reference to another color the gates evaluate, * and recorded in `unchecked` otherwise. An authored color a gate depends on * never passes unread, and one no gate reads stays out of the report. * * A contrast subject names what was measured: the default stop while a role * is at its default (`text_80 on shade_00`), the role once the theme authors * it (`text_color on shade_00`). * * An intent stop that renders the same color as a palette letter's (the * default for every intent) folds into that letter's gamut entry rather than * duplicating it, so reports for letter-bound themes list fewer subjects than * the full letters × intents grid. * * @param theme - the theme to check * @param options - the derived data to check the theme with */ export const check_theme = (theme: Theme, options: CheckThemeOptions = {}): ThemeCheckReport => { const resolver = new ThemeResolver(theme, options); const stance = to_theme_stance(theme.scheme); const entries: Array = []; const unchecked: Array = []; const seen_unchecked: Set = new Set(); const record = (r: ThemeUncheckedEntry): null => { const key = `${r.variable}|${r.value}|${r.reason}`; if (!seen_unchecked.has(key)) { seen_unchecked.add(key); unchecked.push({ variable: r.variable, value: r.value, reason: r.reason }); } return null; }; const num = (name: string, scheme: ColorScheme): number | null => { const r = resolver.resolve(name, scheme); return r.ok ? r.value : record(r); }; // the theme's own value for a color variable, evaluated: `undefined` when // it authors none for the slot, `null` (recorded) when the value isn't a // form the gates evaluate. Every gate color comes through here by name, // which is what makes the set of authored colors the report answers for // exactly the gates' own inputs const authored_color = ( name: string, scheme: ColorScheme, visited: ReadonlySet ): GateColor | null | undefined => { const authored = resolver.authored(name, scheme); if (authored === undefined) return undefined; const value = authored.trim(); const literal = parse_color_literal(value); if (literal) return literal; const reference = VAR_MATCHER.exec(value); if (!reference) return record({ variable: name, value, reason: REASON_COLOR_FORM }); const color = color_of(reference[1]!, scheme, new Set(visited).add(name)); return color === undefined ? record({ variable: name, value, reason: REASON_COLOR_REFERENCE }) : color; }; // an opaque color variable: the theme's authored color when it has one, // else the value derived from the resolved knobs const opaque_color = ( name: string, scheme: ColorScheme, derive: () => RgbUnit | null, visited: ReadonlySet = NO_VISITS ): RgbUnit | null => { const authored = authored_color(name, scheme, visited); if (authored === undefined) return derive(); if (authored === null) return null; if (authored.alpha < 1) { const value = resolver.authored(name, scheme)!.trim(); return record({ variable: name, value, reason: REASON_COLOR_ALPHA }); } return authored.rgb; }; // a palette letter's or intent's color at a stop (`palette_a_50`, // `accent_60`), derived from the slot's hue angle and chroma multiplier const slot_color = ( slot: string, hue: number, multiplier: number, stop: NumericScaleVariant, scheme: ColorScheme, visited?: ReadonlySet ): RgbUnit | null => opaque_color( `${slot}_${stop}`, scheme, () => { const lightness = num(to_lightness_stop_name('palette', stop), scheme); const chroma_stop = num(to_palette_chroma_name(stop), scheme); const chroma_scale = num('chroma_scale', scheme); if (lightness === null || chroma_stop === null || chroma_scale === null) { return null; } return oklch_to_srgb( ramp_color_oklch(lightness, chroma_stop, hue, chroma_scale, multiplier) ); }, visited ); // a neutral (shade/text) ramp color at a stop const neutral_color = ( family: 'shade' | 'text', stop: NumericScaleVariant, scheme: ColorScheme, visited?: ReadonlySet ): RgbUnit | null => opaque_color( `${family}_${stop}`, scheme, () => { const lightness = num(to_lightness_stop_name(family, stop), scheme); const neutral_c = num('neutral_chroma', scheme); const shape = num(to_chroma_shape_name(stop), scheme); const neutral_hue = num('hue_neutral', scheme); // the near-ground shade stops carry their share of the ground's own // tint, held to sRGB at the ground's lightness const ground_weight = neutral_ground_chroma_weight(family, stop); const ground_c = ground_weight === 0 ? 0 : num(SHADE_GROUND_CHROMA_NAME, scheme); if ( lightness === null || neutral_c === null || shape === null || neutral_hue === null || ground_c === null ) { return null; } return oklch_to_srgb( neutral_color_oklch(lightness, neutral_c, shape, neutral_hue, ground_c * ground_weight) ); }, visited ); const opaque = (rgb: RgbUnit | null): GateColor | null => rgb && { rgb, alpha: 1 }; // evaluates a color variable by name - a stop, an untinted extreme, or an // alias followed through to what it points at. `undefined` when the name // isn't a color the gates evaluate const color_of = ( name: string, scheme: ColorScheme, visited: ReadonlySet = NO_VISITS ): GateColor | null | undefined => { if (visited.has(name)) { return record({ variable: name, value: `var(--${name})`, reason: 'cyclic var() reference' }); } const slot_match = PALETTE_STOP_MATCHER.exec(name) ?? INTENT_STOP_MATCHER.exec(name); if (slot_match) { const letter = name.startsWith('palette_'); const slot = letter ? `palette_${slot_match[1]}` : slot_match[1]!; const hue = num(`hue_${slot_match[1]}`, scheme); const multiplier = num(`${slot}_chroma_scale`, scheme); if (hue === null || multiplier === null) return null; const stop = slot_match[2] as NumericScaleVariant; return opaque(slot_color(slot, hue, multiplier, stop, scheme, visited)); } const neutral_match = NEUTRAL_STOP_MATCHER.exec(name); if (neutral_match) { const family = neutral_match[1] as 'shade' | 'text'; const stop = neutral_match[2] as NumericScaleVariant; return opaque(neutral_color(family, stop, scheme, visited)); } const extreme_match = EXTREME_MATCHER.exec(name); if (extreme_match) { // `max` is the far end from the ground - black in light - and a stance // renders its scheme's appearance in both const black = (extreme_match[1] === 'max') === ((stance ?? scheme) === 'light'); return opaque(opaque_color(name, scheme, () => (black ? [0, 0, 0] : [1, 1, 1]), visited)); } const border_match = BORDER_COLOR_STOP_MATCHER.exec(name); if (border_match) { const authored = authored_color(name, scheme, visited); if (authored !== undefined) return authored; const border_l = num('border_color_lightness', scheme); const border_c = num('border_color_chroma', scheme); const border_h = num('hue_neutral', scheme); if (border_l === null || border_c === null || border_h === null) return null; // the alpha is baked into the stop's rendered CSS, which a stance // mirrors into both schemes - so it follows the stance const stop = border_match[1] as NumericScaleVariant; const alpha = BORDER_COLOR_ALPHAS[stance ?? scheme][stop] / 100; return { rgb: oklch_to_srgb(clamp_oklch([border_l, border_c, border_h])), alpha }; } if (name === BORDER_ROLE) { // the derived default, or the theme's own value written the same way const value = resolver.authored(name, scheme)?.trim(); if (value !== undefined && value !== BORDER_ROLE_DEFAULT) { return authored_color(name, scheme, visited); } const next = new Set(visited).add(name); const rest = color_of(`shade_${BORDER_CONTRAST_STOPS.rest}`, scheme, next); const reach = color_of(`shade_${BORDER_CONTRAST_STOPS.reach}`, scheme, next); const c = num(CONTRAST_NAME, scheme); if (!rest || !reach || c === null) return null; return { rgb: mix_oklab(rest.rgb, 1 - border_contrast_share(c), reach.rgb), alpha: 1 }; } const alias = ALIAS_DEFAULTS.get(name); if (alias !== undefined) { const authored = authored_color(name, scheme, visited); if (authored !== undefined) return authored; return color_of(alias, scheme, new Set(visited).add(name)); } return undefined; }; const contrast = (a: RgbUnit, b: RgbUnit): number => wcag_contrast_ratio(clamp_rgb(a), clamp_rgb(b)); const push_gamut = (subject: string, color: RgbUnit, scheme: ColorScheme): void => { const value = gamut_excess(color); entries.push({ gate: 'gamut', scheme, subject, value, threshold: GATE_GAMUT_TOLERANCE, pass: value <= GATE_GAMUT_TOLERANCE }); }; const push_contrast = ( subject: string, value: number, threshold: number, scheme: ColorScheme ): void => { entries.push({ gate: 'contrast', scheme, subject, value, threshold, pass: value >= threshold }); }; const push_monotonicity = (family: RampFamily, scheme: ColorScheme): void => { const lightnesses: Array = []; for (const stop of numeric_scale_variants) { const l = num(to_lightness_stop_name(family, stop), scheme); if (l === null) return; // input unchecked; skip this family+scheme // clamped as the browser clamps `oklch()`, so overshot stops that // render the same lightness read as a flat step lightnesses.push(Math.min(Math.max(l, 0), 1)); } const direction = Math.sign(lightnesses[lightnesses.length - 1]! - lightnesses[0]!); let min_step = Infinity; for (let i = 1; i < lightnesses.length; i++) { min_step = Math.min(min_step, (lightnesses[i]! - lightnesses[i - 1]!) * direction); } // direction 0 (degenerate ramp) yields min_step 0 and fails, as it should const value = direction === 0 ? 0 : min_step; entries.push({ gate: 'monotonicity', scheme, subject: `${family}_lightness`, value, threshold: 0, pass: value > 0 }); }; for (const scheme of color_scheme_variants) { const authored = (name: string): boolean => resolver.authored(name, scheme) !== undefined; // a contrast the gates can't resolve leaves the lower floors in place, // and the resolver records it const high_contrast = (num(CONTRAST_NAME, scheme) ?? 0) >= HIGH_CONTRAST; // what a subject calls a painted color: the role once the theme authors // it, the stop it defaults to until then const label_of = (name: string): string => { const alias = ALIAS_DEFAULTS.get(name); return alias === undefined || authored(name) ? name : label_of(alias); }; // one painted color against each of a gate's grounds, a translucent // color composited over the ground first const push_pairing = (gate: PairingGate, name: string): void => { const color = color_of(name, scheme); const threshold = gate.high_contrast_threshold !== undefined && high_contrast ? gate.high_contrast_threshold : gate.threshold; const grounds = gate.high_contrast_grounds !== undefined && high_contrast ? gate.high_contrast_grounds : gate.grounds; for (const stop of grounds) { const ground = neutral_color('shade', stop, scheme); if (!color || !ground) continue; const ground_rgb = clamp_rgb(ground); const color_rgb = clamp_rgb(color.rgb); const ratio = wcag_contrast_ratio( color.alpha < 1 ? composite_over(color_rgb, color.alpha, ground_rgb) : color_rgb, ground_rgb ); const subject = `${label_of(name)} ${gate.relation} shade_${stop}`; push_contrast(subject, ratio, threshold, scheme); } }; // gamut: palette letters × stops const letter_slots: Array<[letter: PaletteVariant, hue: number, multiplier: number]> = []; for (const letter of palette_variants) { const hue = num(`hue_${letter}`, scheme); const multiplier = num(`palette_${letter}_chroma_scale`, scheme); if (hue === null || multiplier === null) continue; letter_slots.push([letter, hue, multiplier]); for (const stop of numeric_scale_variants) { const color = slot_color(`palette_${letter}`, hue, multiplier, stop, scheme); if (color) push_gamut(`palette_${letter}_${stop}`, color, scheme); } } // gamut: each intent stop that renders differently from every letter's - // it folds into a letter's entry only when hue AND multiplier match and // neither stop is authored as its own color for (const intent of intent_variants) { const hue = num(`hue_${intent}`, scheme); const multiplier = num(`${intent}_chroma_scale`, scheme); if (hue === null || multiplier === null) continue; const twins = letter_slots.filter( ([, h, m]) => Math.abs(h - hue) < NUMERIC_EPSILON && Math.abs(m - multiplier) < NUMERIC_EPSILON ); for (const stop of numeric_scale_variants) { if ( !authored(`${intent}_${stop}`) && twins.some(([letter]) => !authored(`palette_${letter}_${stop}`)) ) { continue; } const color = slot_color(intent, hue, multiplier, stop, scheme); if (color) push_gamut(`${intent}_${stop}`, color, scheme); } } // gamut: the neutral (shade/text) scales for (const family of ['shade', 'text'] as const) { for (const stop of numeric_scale_variants) { const color = neutral_color(family, stop, scheme); if (color) push_gamut(`${family}_${stop}`, color, scheme); } } // monotonicity: each lightness family for (const family of ['palette', 'shade', 'text'] as const) { push_monotonicity(family, scheme); } // contrast: the single-color pairings - body, selected, and subtle text, // borders, links, and the focus ring for (const gate of PAIRING_GATES) { const role_authored = authored(gate.color); if (gate.when_authored && !role_authored) continue; push_pairing(gate, gate.color); const alias = ALIAS_DEFAULTS.get(gate.color); if (gate.default_painted && role_authored && alias !== undefined) { push_pairing(gate, alias); } } // contrast: UI affordances - every letter and intent at stop 50, the // fill stop 60 selected buttons use, and the palette letters as label text const shade_00 = neutral_color('shade', '00', scheme); const text_00 = neutral_color('text', '00', scheme); const text_max = color_of('text_max', scheme)?.rgb ?? null; const shade_max = color_of('shade_max', scheme)?.rgb ?? null; const fills: Array<[label: string, hue: number, multiplier: number, is_letter?: boolean]> = []; for (const letter of palette_variants) { const hue = num(`hue_${letter}`, scheme); const multiplier = num(`palette_${letter}_chroma_scale`, scheme); if (hue !== null && multiplier !== null) { fills.push([`palette_${letter}`, hue, multiplier, true]); } } for (const intent of intent_variants) { const hue = num(`hue_${intent}`, scheme); const multiplier = num(`${intent}_chroma_scale`, scheme); if (hue !== null && multiplier !== null) fills.push([intent, hue, multiplier]); } if (shade_00) { for (const [label, hue, multiplier, is_letter] of fills) { const fill = slot_color(label, hue, multiplier, '50', scheme); if (fill) { const ui = contrast(fill, shade_00); push_contrast(`${label}_50 vs shade_00`, ui, GATE_UI, scheme); if (text_max) { const on_fill = contrast(text_max, fill); push_contrast(`text_max on ${label}_50`, on_fill, GATE_FILL_TEXT, scheme); } } const stop_60 = slot_color(label, hue, multiplier, '60', scheme); if (!stop_60) continue; if (text_00) { const selected = contrast(text_00, stop_60); push_contrast(`text_00 on ${label}_60`, selected, GATE_SELECTED_TEXT, scheme); } if (!is_letter) continue; // the colored label on the page itself (colored text) and on // the chip's stop-10 tint const on_page = contrast(stop_60, shade_00); push_contrast(`${label}_60 on shade_00`, on_page, GATE_PALETTE_TEXT, scheme); const tint = slot_color(label, hue, multiplier, '10', scheme); if (tint) { const on_tint = contrast(stop_60, tint); push_contrast(`${label}_60 on ${label}_10`, on_tint, GATE_PALETTE_TEXT, scheme); } // the `.palette_X` button label on its fills - faint tints of the // fill stop over the page - at rest (focus keeps the rest fill), // hovered (with the hovered label), and pressed by mouse (hovered // too) and by keyboard (not hovered, so the plain label) const label_color = slot_color(label, hue, multiplier, PALETTE_BUTTON_LABEL_STOP, scheme); const fill_color = slot_color(label, hue, multiplier, PALETTE_BUTTON_FILL_STOP, scheme); if (!label_color || !fill_color) continue; const button_label = clamp_rgb(label_color); const ground = clamp_rgb(shade_00); const button_fill = (alpha: number): RgbUnit => composite_over(clamp_rgb(fill_color), alpha, ground); const stop = `${label}_${PALETTE_BUTTON_LABEL_STOP}`; const push_button = (subject: string, color: RgbUnit, alpha: number): void => { const ratio = wcag_contrast_ratio(color, button_fill(alpha)); push_contrast(subject, ratio, GATE_PALETTE_TEXT, scheme); }; push_button(`${stop} on ${label} button fill`, button_label, BUTTON_FILL_ALPHAS.rest); push_button(`${stop} on ${label} active fill`, button_label, BUTTON_FILL_ALPHAS.active); if (shade_max) { const hovered = mix_oklab(button_label, BUTTON_HOVER_LABEL_WEIGHT, clamp_rgb(shade_max)); const hovered_label = `${stop} hovered`; push_button(`${hovered_label} on ${label} hover fill`, hovered, BUTTON_FILL_ALPHAS.hover); push_button( `${hovered_label} on ${label} active fill`, hovered, BUTTON_FILL_ALPHAS.active ); } } } } return { passed: entries.every((e) => e.pass), complete: unchecked.length === 0, entries, unchecked }; }; // // compute_theme_caps - recompute worst-hue caps for the theme's own hues. // // how far a recomputed cap must sit above the baked one to be worth emitting - // reclaiming sub-JND chroma headroom isn't worth an override. A cap that // tightens always emits: the gamut gate's tolerance is far finer than this, // so any stop the baked table overshoots is a stop the gate reports const CAP_EMIT_EPSILON = 0.002; // the theme's effective hue set for cap recomputation: the palette letters // plus any intent that resolves to a literal angle distinct from every letter. // `null` when any hue fails to resolve - caps computed without it would claim // headroom the missing hue may not have, so the compile step emits nothing // (the re-check still reports the unresolvable pins) const collect_hues = (resolver: ThemeResolver, scheme: ColorScheme): Array | null => { const hues: Array = []; for (const letter of palette_variants) { const r = resolver.resolve(`hue_${letter}`, scheme); if (!r.ok) return null; hues.push(r.value); } for (const intent of intent_variants) { const r = resolver.resolve(`hue_${intent}`, scheme); if (!r.ok) return null; if (!hues.some((h) => Math.abs(h - r.value) < NUMERIC_EPSILON)) hues.push(r.value); } return hues; }; /** * Recomputes a theme's per-stop worst-hue chroma caps from its own hues and * the palette lightness each stop resolves to, then returns * `_palette_chroma_NN` caps wherever the baked ones no longer fit - the fix * for a theme (rotated hues, a monochrome collapse, a moved lightness ramp) * whose gamut headroom the baked worst-hue table misjudges. The caps are * derived data beside the theme, never in it: a theme can't set an internal * variable, so they render through `render_theme_style`'s `caps` option and * recomputing them for the same theme gives the same caps. * * Each stop's cap is computed at the lightness the resolution core resolves * for the stop in that scheme - the theme's endpoint-and-curve ramp - so the * caps describe the same colors `check_theme` gates. * * A stop is emitted when either scheme's recomputed cap is tighter than the * baked value, or looser by more than the emit epsilon. Nothing is emitted * when a hue fails to resolve to a number, since caps computed without it * could overshoot its gamut, and a stop whose lightness fails to resolve is * skipped. An override emits both slots together, so a * one-scheme override can't silently kill the base default's other slot by * cascade-layer order, collapsing to a single slot in the base position when * the two rendered values coincide. * * A stanced theme's two schemes resolve to the stanced appearance through the * mirror, so its caps are baselined against the stanced scheme's baked table - * the values the mirror already re-slots - and a stance alone (hues and * lightness unmoved) emits nothing. Its overrides coincide across schemes and * emit single-slot unless the theme authors a dark slot that splits them. * * The caps bound the requested chroma only: `chroma_scale` and the per-slot * `*_chroma_scale` multipliers apply above the clamp. A theme that raises one * past 1 clips by design - its gamut failures survive the compile, and a cap * the compile loosens can add to them, since the multiplier then pushes more * stops past the looser cap. Gate the theme with them through * `check_theme(theme, {caps})`. * * @param theme - the theme to recompute caps for * @returns the `_palette_chroma_NN` caps that moved, empty when the baked ones all still fit */ export const compute_theme_caps = (theme: Theme): Array => { const resolver = new ThemeResolver(theme); const stance = to_theme_stance(theme.scheme); const hues: Record | null> = { light: collect_hues(resolver, 'light'), dark: collect_hues(resolver, 'dark') }; // the gamut search is the expensive part, and a stanced theme resolves both // schemes to the same hues and lightness - so memoize by the search inputs const cap_memo: Map = new Map(); const recompute = (stop: NumericScaleVariant, scheme: ColorScheme): number | null => { const scheme_hues = hues[scheme]; const lightness = resolver.resolve(to_lightness_stop_name('palette', stop), scheme); if (!scheme_hues || !lightness.ok) return null; const key = `${lightness.value}|${scheme_hues.join(',')}`; let cap = cap_memo.get(key); if (cap === undefined) { // at the lightness the browser renders, which clamps an overshoot cap = compute_worst_hue_chroma_cap(scheme_hues, clamp(lightness.value, 0, 1)); cap_memo.set(key, cap); } return cap; }; // a stance baselines both schemes against the stanced scheme's baked caps: // those are what the mirror re-slots into the base position, so comparing // against the light table would emit no-op overrides duplicating the mirror // for every dark stance const baked: Record> = { light: PALETTE_CHROMA_CAPS[stance ?? 'light'], dark: PALETTE_CHROMA_CAPS[stance ?? 'dark'] }; // tightening always emits, loosening only past the epsilon const cap_moved = (cap: number, baked_cap: number): boolean => cap < baked_cap - NUMERIC_EPSILON || cap - baked_cap > CAP_EMIT_EPSILON; const caps: Array = []; for (const stop of hues.light && hues.dark ? numeric_scale_variants : []) { const light_cap = recompute(stop, 'light'); const dark_cap = recompute(stop, 'dark'); if (light_cap === null || dark_cap === null) continue; if (cap_moved(light_cap, baked.light[stop]) || cap_moved(dark_cap, baked.dark[stop])) { const light_value = render_chroma_stop_css(stop, light_cap); const dark_value = render_chroma_stop_css(stop, dark_cap); caps.push( light_value === dark_value ? { name: to_palette_chroma_name(stop), base: light_value } : { name: to_palette_chroma_name(stop), base: light_value, dark: dark_value } ); } } return caps; };