Theme engine v3 step 4: inkOn, the contrast solver

themeInk.ts: OKLCH lightness search toward the pole with headroom, hue kept, chroma
cut only for the gamut; several fills (gradient ends, glass grounds); compositing.
reach() now runs on it (8% headroom when a colour has to move, for the site's tints
mixed from these surfaces). Property test: 5,000 random pairs reach 4.5:1 and 3:1;
the live 1.0.2 cases ("New" pill 1.19:1, HoverLabel 2.7:1, like pink 3.84:1) pass.
This commit is contained in:
CRTkafa 2026-10-02 04:56:04 +07:00
parent 0f0f51988b
commit c66d66e3a8
3 changed files with 193 additions and 11 deletions

View file

@ -0,0 +1,116 @@
// The contrast solver of theme engine v3 (.omc/plans/theme-engine-v3.md 3.3): one function for the
// derivation, the site remap, the layer guard, the shell and the Theme Builder. Pure, no DOM.
//
// inkOn(fill, preferred, target) keeps `preferred` when it reads on `fill`; otherwise it moves the
// colour in OKLCH lightness toward the pole (black or white) with more headroom on that fill, keeping
// the hue and giving up chroma only where the sRGB gamut forces it, and stops at the first lightness
// that reaches the target (binary search). Ratios are WCAG 2.x; APCA is not a gate in v3.0.
import { contrastRatio, hexToRgb } from './themeApi.ts';
export type InkResult = { ink: string; adjusted: boolean; ratio: number };
export type InkOptions = {
/** Hue and chroma are always kept where the gamut allows; the flag marks a meaning colour (like, repost) for notes. */
keepHue?: boolean;
/** A translucent `fill` (`#rrggbbaa`) is composited over this opaque colour first. */
over?: string;
};
/** WCAG targets used across the engine. */
export const TARGET = { text: 4.5, large: 3, nonText: 3, high: 7 } as const;
// ---------------------------------------------------------------------------------------------
// sRGB <-> OKLab / OKLCH
const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
const fromLinear = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
export type Oklch = { l: number; c: number; h: number };
export function hexToOklch(hex: string): Oklch {
const [r, g, b] = hexToRgb(hex).map(v => toLinear(v / 255)) as [number, number, number];
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;
const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
return { l: L, c: Math.hypot(A, B), h: Math.atan2(B, A) };
}
/** Linear sRGB of an OKLCH colour (may be out of gamut). */
function oklchToLinear({ l, c, h }: Oklch): [number, number, number] {
const A = c * Math.cos(h), B = c * Math.sin(h);
const l_ = (l + 0.3963377774 * A + 0.2158037573 * B) ** 3;
const m_ = (l - 0.1055613458 * A - 0.0638541728 * B) ** 3;
const s_ = (l - 0.0894841775 * A - 1.291485548 * B) ** 3;
return [
4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,
-1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,
-0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_,
];
}
const inGamut = (rgb: number[]) => rgb.every(v => v >= -1e-4 && v <= 1 + 1e-4);
const hex2 = (v: number) => Math.round(Math.min(1, Math.max(0, fromLinear(Math.min(1, Math.max(0, v))))) * 255).toString(16).padStart(2, '0');
/** OKLCH to `#rrggbb`, reducing chroma (never hue or lightness) until the colour is in sRGB. */
export function oklchToHex(color: Oklch): string {
let rgb = oklchToLinear(color);
if (!inGamut(rgb)) {
let lo = 0, hi = color.c;
for (let i = 0; i < 16; i++) {
const mid = (lo + hi) / 2;
if (inGamut(oklchToLinear({ ...color, c: mid }))) lo = mid; else hi = mid;
}
rgb = oklchToLinear({ ...color, c: lo });
}
return `#${rgb.map(hex2).join('')}`;
}
// ---------------------------------------------------------------------------------------------
// Compositing
/** `#rrggbbaa` over an opaque `#rrggbb` (sRGB space, as browsers composite). `#rrggbb` passes through. */
export function composite(fill: string, over: string): string {
if (!/^#[0-9a-f]{8}$/i.test(fill)) return fill.toLowerCase();
const alpha = parseInt(fill.slice(7, 9), 16) / 255;
const top = hexToRgb(fill.slice(0, 7)), bottom = hexToRgb(over);
return `#${top.map((v, i) => Math.round(v * alpha + bottom[i]! * (1 - alpha)).toString(16).padStart(2, '0')).join('')}`;
}
// ---------------------------------------------------------------------------------------------
// The solver
/** The worst ratio of `ink` over every fill. */
const worst = (ink: string, fills: string[]) => Math.min(...fills.map(fill => contrastRatio(ink, fill)));
/**
* The ink closest to `preferred` that reaches `target` on every one of `fills` (all opaque).
* Several fills: the ink has to read on each (a gradient's two ends, glass over two grounds).
*/
export function inkOnEvery(fills: string[], preferred: string, target: number, options: InkOptions = {}): InkResult {
const grounds = fills.map(fill => composite(fill, options.over ?? '#ffffff'));
const start = preferred.toLowerCase();
const startRatio = worst(start, grounds);
if (startRatio >= target) return { ink: start, adjusted: false, ratio: startRatio };
// The pole with more headroom: the one that reads better on the worst ground.
const toWhite = worst('#ffffff', grounds) >= worst('#000000', grounds);
const pole = toWhite ? '#ffffff' : '#000000';
const poleRatio = worst(pole, grounds);
if (poleRatio < target) return { ink: pole, adjusted: true, ratio: poleRatio };
const base = hexToOklch(start);
// Binary search on lightness between the colour and the pole; the ratio grows monotonically along it.
let lo = base.l, hi = toWhite ? 1 : 0, best = pole;
for (let i = 0; i < 12; i++) {
const mid = (lo + hi) / 2;
const candidate = oklchToHex({ l: mid, c: base.c, h: base.h });
if (worst(candidate, grounds) >= target) { best = candidate; hi = mid; } else lo = mid;
}
return { ink: best, adjusted: true, ratio: worst(best, grounds) };
}
/** The ink closest to `preferred` that reaches `target` on `fill`. */
export function inkOn(fill: string, preferred: string, target: number, options: InkOptions = {}): InkResult {
return inkOnEvery([fill], preferred, target, options);
}

View file

@ -16,8 +16,9 @@
// system fonts, "Geist" / "Geist Mono" (bundled and registered from bytes: `FontFace(ArrayBuffer)` is // system fonts, "Geist" / "Geist Mono" (bundled and registered from bytes: `FontFace(ArrayBuffer)` is
// not a fetch), or Google Fonts families the owner downloaded (`source: "google"`, fonts.ts). // not a fetch), or Google Fonts families the owner downloaded (`source: "google"`, fonts.ts).
import { FONT_ROLE_NAMES, MONO_FAMILIES, contrastRatio, hexToRgb, mix, relativeLuminance, type FontRoleName } from './themeApi.ts'; import { FONT_ROLE_NAMES, MONO_FAMILIES, hexToRgb, mix, type FontRoleName } from './themeApi.ts';
import { deriveColors } from './themeTokens.ts'; import { deriveColors } from './themeTokens.ts';
import { inkOnEvery } from './themeInk.ts';
import { ACTION_NAMES, sanitizeComponents, type ActionColors, type ThemeComponents } from './themeComponents.ts'; import { ACTION_NAMES, sanitizeComponents, type ActionColors, type ThemeComponents } from './themeComponents.ts';
import { sanitizeDecor, type ThemeDecor } from './themeDecor.ts'; import { sanitizeDecor, type ThemeDecor } from './themeDecor.ts';
import { sanitizeThemeIcons, type ThemeIcons } from './themeIcons.ts'; import { sanitizeThemeIcons, type ThemeIcons } from './themeIcons.ts';
@ -151,19 +152,17 @@ export const isHex = (value: unknown): value is string => typeof value === 'stri
/** `#rrggbb` + alpha as `rgba()`. */ /** `#rrggbb` + alpha as `rgba()`. */
export const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${+alpha.toFixed(3)})`; export const rgba = (hex: string, alpha: number) => `rgba(${hexToRgb(hex).join(', ')}, ${+alpha.toFixed(3)})`;
/** Moves `color` toward black or white until it reaches `ratio` against every surface. */ /**
* The colour closest to `color` (OKLCH lightness, hue kept) that reaches `ratio` against every surface
* (themeInk.ts). A colour that has to move gets 8% headroom: the site's hover and pressed tints are mixed
* from these surfaces, and an exact solver would leave the ink a hair under the target on them.
*/
export function reach(color: string, surfaces: string[], ratio: number): string { export function reach(color: string, surfaces: string[], ratio: number): string {
const worst = (c: string) => Math.min(...surfaces.map(s => contrastRatio(c, s))); const kept = inkOnEvery(surfaces, color, ratio);
if (worst(color) >= ratio) return color; return kept.adjusted ? inkOnEvery(surfaces, color, ratio * 1.08).ink : kept.ink;
const lightSurfaces = surfaces.reduce((sum, s) => sum + relativeLuminance(s), 0) / surfaces.length > 0.18;
const pole = lightSurfaces ? '#000000' : '#ffffff';
for (let t = 0.04; t <= 1; t += 0.04) {
const next = mix(color, pole, t);
if (worst(next) >= ratio) return next;
}
return pole;
} }
/** /**
* Guarantees legibility for any palette (built-in, imported or overridden): text, secondary text * Guarantees legibility for any palette (built-in, imported or overridden): text, secondary text
* and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled * and links reach WCAG AA (4.5:1) on every surface, including the page canvas, and the site's filled

View file

@ -0,0 +1,67 @@
// Theme engine v3, step 4: the contrast solver (themeInk.ts). Property test over random palettes.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { contrastRatio } from '../src/themeApi.ts';
import { composite, hexToOklch, inkOn, inkOnEvery, oklchToHex, TARGET } from '../src/themeInk.ts';
import { reach } from '../src/themeSpec.ts';
/** Deterministic PRNG (mulberry32): the property test is reproducible. */
function rng(seed: number) {
return () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
const randomHex = (r: () => number) => `#${Array.from({ length: 3 }, () => Math.floor(r() * 256).toString(16).padStart(2, '0')).join('')}`;
test('inkOn keeps an ink that already reads, unchanged', () => {
const result = inkOn('#ffffff', '#000000', TARGET.text);
assert.deepEqual([result.ink, result.adjusted], ['#000000', false]);
});
test('5,000 random fill and ink pairs reach 4.5:1 after inkOn, 3:1 for non-text', () => {
const r = rng(20261002);
for (let i = 0; i < 5000; i++) {
const fill = randomHex(r), preferred = randomHex(r);
for (const target of [TARGET.text, TARGET.nonText]) {
const { ink, ratio } = inkOn(fill, preferred, target);
assert.ok(contrastRatio(ink, fill) >= target - 1e-9, `${preferred} on ${fill}: ${ratio.toFixed(2)} < ${target} (${ink})`);
}
}
});
test('an adjusted ink keeps the hue of the preferred colour (meaning colours stay themselves)', () => {
// The live 1.0.2 failure: navy accent text on Creator Studio's indigo pill, 1.19:1.
const { ink, adjusted, ratio } = inkOn('#1e1b4b', '#0000a8', TARGET.text);
assert.ok(adjusted && ratio >= 4.5, `${ink} ${ratio}`);
const hue = (hex: string) => hexToOklch(hex).h;
assert.ok(Math.abs(hue(ink) - hue('#0000a8')) < 0.15, `hue drifted: ${ink}`);
// X's like pink on white was 3.84:1 as a count.
const pink = inkOn('#ffffff', '#f91880', TARGET.text, { keepHue: true });
assert.ok(pink.ratio >= 4.5 && Math.abs(hue(pink.ink) - hue('#f91880')) < 0.15, pink.ink);
});
test('the "More" HoverLabel: black on X grey 82 gets a readable ink', () => {
const { ratio } = inkOn('#525252', '#000000', TARGET.text);
assert.ok(ratio >= 4.5);
});
test('every fill of a gradient or glass is honoured', () => {
// The 98 title bar is bold chrome type: large-text target on both ends of its gradient.
const { ink } = inkOnEvery(['#000080', '#1084d0'], '#c0c0c0', TARGET.large);
for (const fill of ['#000080', '#1084d0']) assert.ok(contrastRatio(ink, fill) >= 3, `${ink} on ${fill}`);
// No ink reaches 4.5:1 on both: the solver says so instead of pretending (the deriver then darkens the end).
const none = inkOnEvery(['#000080', '#1084d0'], '#ffffff', TARGET.text);
assert.ok(none.adjusted && none.ratio < 4.5);
assert.equal(composite('#00000080', '#ffffff'), '#7f7f7f');
const glass = inkOn('#ffffff80', '#808080', TARGET.text, { over: '#000000' });
assert.ok(contrastRatio(glass.ink, '#808080') >= 4.5 - 0.05);
});
test('OKLCH round trip is exact for sRGB colours', () => {
const r = rng(7);
for (let i = 0; i < 500; i++) { const hex = randomHex(r); assert.equal(oklchToHex(hexToOklch(hex)), hex); }
});
test('reach runs on the solver and still guarantees every surface', () => {
const out = reach('#888888', ['#ffffff', '#f4f4f4', '#dfdfdf'], 4.5);
for (const s of ['#ffffff', '#f4f4f4', '#dfdfdf']) assert.ok(contrastRatio(out, s) >= 4.5);
assert.equal(reach('#000000', ['#ffffff'], 7), '#000000');
});