Files
siftlode/frontend/src/lib/colorMath.ts
T
peter 36653886d5 build(frontend)!: knip drops --production; plain knip stays
The production pass (7ed2ac4e, E32) asked "is this export used by what
ships?". No real hit: its only findings were 37 exports a test imports,
answered with 36 `@internal` JSDoc tags (E34 S2) — test-only exports, not
defects. Since then it has only ever asked for another tag. The tags go
with it (36, no longer read by anything), and so do the production-only
`!…!` exclusions in knip.jsonc and their register rows. Plain knip (unused
files, exports and dependencies) keeps running in the gate.
2026-10-05 00:19:38 +02:00

44 lines
1.9 KiB
TypeScript

// WCAG contrast and OKLCH hue distance on literal hex colours. The design constitution's colour rules
// (docs/DESIGN.md, Tokens) are measured with these: theme.contract.test.ts runs them over every scheme
// in index.css, and the design lab's scheme tiles render the same numbers. OKLCH, because equal hue
// angles there look equally far apart, unlike HSL's.
const rgb = (hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);
const lin2 = (v: number) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4);
export function hexContrast(a: string, b: string): number {
const l = (h: string) => {
const [r = 0, g = 0, bl = 0] = rgb(h).map(lin2);
return 0.2126 * r + 0.7152 * g + 0.0722 * bl;
};
const x = l(a);
const y = l(b);
return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
}
function hue(hex: string): number {
const [r = 0, g = 0, b = 0] = rgb(hex).map(lin2);
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 A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
return ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;
}
/** The OKLCH hue angle between two colours, 0..180°. */
export function hueGap(a: string, b: string): number {
const d = Math.abs(hue(a) - hue(b)) % 360;
return Math.min(d, 360 - d);
}
/** `color-mix(in srgb, a w, b)` for two opaque hex colours: the channels mix gamma-encoded, as the
* browser does in the srgb space. */
export function mixHex(a: string, b: string, w: number): string {
const [x, y] = [rgb(a), rgb(b)];
return `#${x
.map((v, i) => Math.round((v * w + (y[i] ?? 0) * (1 - w)) * 255))
.map((n) => n.toString(16).padStart(2, "0"))
.join("")}`;
}