@labpics/colors 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/effective-bg.js CHANGED
@@ -1,492 +1,501 @@
1
- // Effective background resolution — zero dependencies.
2
- //
3
- // `labcolors` resolves roles against a *solid* background. A real UI surface is
4
- // often translucent (a panel at `rgba(…, .8)` over its parents) or has no
5
- // background of its own (inheriting whatever is behind it). To resolve such a
6
- // surface honestly you need the **effective** background: the opaque colour a
7
- // viewer actually sees behind the element's own content.
8
- //
9
- // This module computes it by walking the ancestor chain and **alpha-compositing**
10
- // each element's `background-color` (front-to-back) until the stack is opaque,
11
- // over an opaque fallback (white by default). It is the bridge from the DOM's
12
- // layered, translucent reality to the single solid hex the WASM core consumes.
13
- //
14
- // HONEST LIMIT: this composites solid/translucent `background-color` layers only.
15
- // It does NOT sample `background-image`s, gradients, blurred backdrops, video, or
16
- // content showing through — those have no single colour to read from computed
17
- // style. For those, the caller supplies the effective background explicitly (the
18
- // `background` option of `watchTheme`, or a sampled average). What it does cover —
19
- // translucent panels over solid parents — is the common case and is composited
20
- // *correctly* (true source-over alpha), not approximated.
21
- //
22
- // COLOUR FORMS: `parseCssColor` reads the forms this package actually meets —
23
- // `#hex`, `rgb()/rgba()` (legacy comma and modern space/slash), `transparent`,
24
- // and `oklch()` (the engine's OWN emission form since 0.4.0, and what a browser
25
- // serialises `background-color` back to for an oklch-painted surface). Other
26
- // modern forms — `lab()`, `lch()`, `color(srgb …)`, `color-mix()`, `hsl()`,
27
- // named colours beyond `transparent` — are NOT parsed and return `null` (a
28
- // dropped layer). If a surface's background is authored in one of those, pass the
29
- // effective background explicitly via the `background` option.
30
-
31
- /** @typedef {[number, number, number, number]} Rgba r,g,b in 0..255, a in 0..1 */
32
-
33
- /**
34
- * Parse a CSS colour string into `[r, g, b, a]`, or `null` if unrecognised.
35
- *
36
- * Handles the forms computed style actually yields:
37
- * - `rgb(r, g, b)` / `rgba(r, g, b, a)` and the modern `rgb(r g b / a)`;
38
- * - `#rgb` / `#rgba` / `#rrggbb` / `#rrggbbaa`;
39
- * - the `transparent` keyword;
40
- * - `oklch(L C H)` / `oklch(L C H / A)` — the engine's own emission form and
41
- * what a browser serialises an oklch-painted `background-color` back to.
42
- * `L` accepts both a `0..1` number (Chrome's computed form) and a percentage
43
- * (the engine's literal form); `C` a number or a `%` (100% = 0.4 per CSS
44
- * Color 4); `H` degrees (bare or `deg`-suffixed); a missing component
45
- * (`none`) is 0. Conversion to sRGB bytes reuses the file's Oklab↔sRGB
46
- * transform and is byte-exact to the core's round-trip proof.
47
- *
48
- * Any other form — `lab()`, `lch()`, `color(srgb …)`, `color-mix()`, `hsl()`,
49
- * named colours other than `transparent` — returns `null` (treated as "no
50
- * layer"); supply such backgrounds explicitly via the `background` option.
51
- *
52
- * @param {string} css
53
- * @returns {Rgba | null}
54
- */
55
- export function parseCssColor(css) {
56
- if (typeof css !== "string") return null;
57
- const s = css.trim().toLowerCase();
58
- if (s === "transparent") return [0, 0, 0, 0];
59
-
60
- if (s.startsWith("oklch(") && s.endsWith(")")) return parseOklch(s.slice(6, -1));
61
-
62
- if (s[0] === "#") {
63
- const h = s.slice(1);
64
- if (h.length === 3 || h.length === 4) {
65
- const r = parseInt(h[0] + h[0], 16);
66
- const g = parseInt(h[1] + h[1], 16);
67
- const b = parseInt(h[2] + h[2], 16);
68
- const a = h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1;
69
- return [r, g, b, a].some(Number.isNaN) ? null : [r, g, b, a];
70
- }
71
- if (h.length === 6 || h.length === 8) {
72
- const r = parseInt(h.slice(0, 2), 16);
73
- const g = parseInt(h.slice(2, 4), 16);
74
- const b = parseInt(h.slice(4, 6), 16);
75
- const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
76
- return [r, g, b, a].some(Number.isNaN) ? null : [r, g, b, a];
77
- }
78
- return null;
79
- }
80
-
81
- const m = s.match(/^rgba?\(([^)]+)\)$/);
82
- if (!m) return null;
83
- // Split on commas or whitespace and an optional "/" alpha separator.
84
- const parts = m[1].split(/[,\s/]+/).filter((p) => p.length > 0);
85
- if (parts.length < 3) return null;
86
- const chan = (p) => (p.endsWith("%") ? (parseFloat(p) / 100) * 255 : parseFloat(p));
87
- const r = chan(parts[0]);
88
- const g = chan(parts[1]);
89
- const b = chan(parts[2]);
90
- const a = parts.length >= 4 ? (parts[3].endsWith("%") ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])) : 1;
91
- if ([r, g, b, a].some((v) => Number.isNaN(v))) return null;
92
- return [clamp255(r), clamp255(g), clamp255(b), Math.min(1, Math.max(0, a))];
93
- }
94
-
95
- function clamp255(v) {
96
- return Math.min(255, Math.max(0, v));
97
- }
98
-
99
- /**
100
- * Parse the inside of an `oklch(...)` (the part between the parens) into sRGB
101
- * `[r, g, b, a]`, or `null` on any malformed component.
102
- *
103
- * The engine emits `oklch(L% C H)` / `oklch(L% C H / A)`; a browser's computed
104
- * form is `oklch(<L 0..1> C H [/ A])`. Components are whitespace-separated with
105
- * an optional `/`-separated alpha, exactly like `rgb()`'s modern syntax.
106
- * oklch → Oklab is `a = C·cos(H)`, `b = C·sin(H)`; then the file's own
107
- * `oklabToLinearRgb` + `linearToSrgb` land it in sRGB — the SAME transform (and
108
- * the SAME clamp-then-round the core uses in `hex_from_srgb`) that carries the
109
- * emitter's byte-exact round-trip, so an emitted string decodes to its source
110
- * bytes. Out-of-gamut channels clamp per channel, matching `oklabLerp`/`toHex`.
111
- *
112
- * @param {string} inner the text between `oklch(` and `)`
113
- * @returns {Rgba | null}
114
- */
115
- function parseOklch(inner) {
116
- const slash = inner.indexOf("/");
117
- const lch = (slash >= 0 ? inner.slice(0, slash) : inner).trim();
118
- const alphaTok = slash >= 0 ? inner.slice(slash + 1).trim() : null;
119
- const comps = lch.split(/\s+/).filter((p) => p.length > 0);
120
- if (comps.length !== 3) return null;
121
-
122
- const L = oklchLightness(comps[0]);
123
- const C = oklchChroma(comps[1]);
124
- const H = oklchHue(comps[2]);
125
- const a = alphaTok === null ? 1 : oklchAlpha(alphaTok);
126
- if (L === null || C === null || H === null || a === null) return null;
127
-
128
- const hRad = (H * Math.PI) / 180;
129
- const lin = oklabToLinearRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
130
- const byte = (i) => Math.round(clamp255(linearToSrgb(lin[i]) * 255));
131
- return [byte(0), byte(1), byte(2), a];
132
- }
133
-
134
- /** Strict CSS `<number>` (no trailing junk, unlike `parseFloat`), else `null`. */
135
- function cssNumber(tok) {
136
- return /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(tok) ? parseFloat(tok) : null;
137
- }
138
-
139
- /** L: a percentage → `/100` into `0..1`; a bare number is already `0..1`; `none`
140
- * → 0. Lightness clamps to `[0, 1]` (CSS Color 4) — a byte-level clamp alone
141
- * masks out-of-range L only at low chroma, not high, so clamp L explicitly. */
142
- function oklchLightness(tok) {
143
- if (tok === "none") return 0;
144
- const pct = tok.endsWith("%");
145
- const n = cssNumber(pct ? tok.slice(0, -1) : tok);
146
- if (n === null) return null;
147
- return Math.min(1, Math.max(0, pct ? n / 100 : n));
148
- }
149
-
150
- /** C: a bare number is absolute chroma; a percentage is a fraction of 0.4
151
- * (CSS Color 4: 100% = 0.4); `none` → 0. Negative chroma clamps to 0. */
152
- function oklchChroma(tok) {
153
- if (tok === "none") return 0;
154
- const pct = tok.endsWith("%");
155
- const n = cssNumber(pct ? tok.slice(0, -1) : tok);
156
- if (n === null) return null;
157
- return Math.max(0, pct ? (n / 100) * 0.4 : n);
158
- }
159
-
160
- /** H: degrees, bare or `deg`-suffixed; `none` → 0. (grad/rad/turn are out of
161
- * scope — the engine and browsers emit bare degrees.) */
162
- function oklchHue(tok) {
163
- if (tok === "none") return 0;
164
- return cssNumber(tok.endsWith("deg") ? tok.slice(0, -3) : tok);
165
- }
166
-
167
- /** Alpha: a number `0..1` or a percentage; `none` → 0; clamped to `[0, 1]`. */
168
- function oklchAlpha(tok) {
169
- if (tok === "none") return 0;
170
- const pct = tok.endsWith("%");
171
- const n = cssNumber(pct ? tok.slice(0, -1) : tok);
172
- if (n === null) return null;
173
- return Math.min(1, Math.max(0, pct ? n / 100 : n));
174
- }
175
-
176
- /**
177
- * Source-over composite of `top` onto `bottom` (Porter-Duff "over").
178
- *
179
- * @param {Rgba} top
180
- * @param {Rgba} bottom
181
- * @returns {Rgba}
182
- */
183
- export function compositeOver(top, bottom) {
184
- const at = top[3];
185
- const ab = bottom[3];
186
- const a = at + ab * (1 - at);
187
- if (a === 0) return [0, 0, 0, 0];
188
- const c = (i) => (top[i] * at + bottom[i] * ab * (1 - at)) / a;
189
- return [c(0), c(1), c(2), a];
190
- }
191
-
192
- /**
193
- * `[r, g, b]` (0..255) → `#RRGGBB`, channels rounded and clamped.
194
- *
195
- * @param {Rgba | [number, number, number]} rgb
196
- * @returns {string}
197
- */
198
- export function toHex(rgb) {
199
- // Coerce non-finite channels (NaN/±Infinity, e.g. from a malformed `Rgba`
200
- // passed by a caller) to 0, so a bad input yields a valid `#RRGGBB` rather
201
- // than an invalid CSS string like `"#NAN0000"`.
202
- const h = (v) => {
203
- const n = Math.round(clamp255(Number.isFinite(v) ? v : 0));
204
- return n.toString(16).padStart(2, "0");
205
- };
206
- return `#${h(rgb[0])}${h(rgb[1])}${h(rgb[2])}`.toUpperCase();
207
- }
208
-
209
- // --- Perceptual interpolation (Oklab) -------------------------------------
210
- //
211
- // A crossfade should feel even: equal progress should be equal *perceived*
212
- // change. A straight sRGB-channel blend is not that — it lingers in the brighter
213
- // half (black→white at t=0.5 is #808080, but the perceived midpoint grey is
214
- // ~#606060). Interpolating in Oklab — a perceptually-uniform space — fixes the
215
- // timing and, for chromatic endpoints, avoids the muddy desaturated midpoint a
216
- // raw RGB blend produces. Björn Ottosson's sRGB↔Oklab transform, self-contained.
217
-
218
- /** sRGB gamma transfer (IEC 61966-2-1): encoded channel 0..1 → linear 0..1. */
219
- function srgbToLinear(c) {
220
- return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
221
- }
222
-
223
- /** Inverse sRGB transfer: linear 0..1 → encoded 0..1. */
224
- function linearToSrgb(c) {
225
- return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
226
- }
227
-
228
- /** Linear-light sRGB `[r,g,b]` (0..1) → Oklab `[L, a, b]`. */
229
- function linearRgbToOklab(r, g, b) {
230
- const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
231
- const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
232
- const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
233
- const l_ = Math.cbrt(l);
234
- const m_ = Math.cbrt(m);
235
- const s_ = Math.cbrt(s);
236
- return [
237
- 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
238
- 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
239
- 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,
240
- ];
241
- }
242
-
243
- /** Oklab `[L, a, b]` → linear-light sRGB `[r,g,b]` (0..1, may be out of gamut). */
244
- function oklabToLinearRgb(L, A, B) {
245
- const l_ = L + 0.3963377774 * A + 0.2158037573 * B;
246
- const m_ = L - 0.1055613458 * A - 0.0638541728 * B;
247
- const s_ = L - 0.0894841775 * A - 1.291485548 * B;
248
- const l = l_ * l_ * l_;
249
- const m = m_ * m_ * m_;
250
- const s = s_ * s_ * s_;
251
- return [
252
- 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
253
- -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
254
- -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
255
- ];
256
- }
257
-
258
- /**
259
- * Interpolate two colours in Oklab at `t ∈ [0,1]`, returning `#RRGGBB`.
260
- *
261
- * `from`/`to` may be ANY string `parseCssColor` accepts (`#rgb`/`#rrggbb`,
262
- * `rgb()`/`rgba()`, `oklch()`, `transparent`) — not only `#RRGGBB`. Perceptually
263
- * uniform: equal steps in `t` are equal steps in perceived lightness (and a
264
- * straight, non-muddy path in hue/chroma), so a crossfade feels even rather than
265
- * lingering bright. Endpoints are returned exactly (`t ≤ 0` → `from`, `t ≥ 1` →
266
- * `to`), always normalised to `#RRGGBB` through `toHex`; out-of-gamut
267
- * intermediates are clamped per channel. Unparseable input falls back to the
268
- * nearer parseable endpoint.
269
- *
270
- * @param {string} from any colour string `parseCssColor` accepts
271
- * @param {string} to any colour string `parseCssColor` accepts
272
- * @param {number} t
273
- * @returns {string} a `#RRGGBB` string
274
- */
275
- export function oklabLerp(from, to, t) {
276
- const a = parseCssColor(from);
277
- const b = parseCssColor(to);
278
- if (!a || !b) return (b && t >= 0.5) || !a ? (b ? toHex(b) : "#000000") : toHex(a);
279
- if (t <= 0) return toHex(a);
280
- if (t >= 1) return toHex(b);
281
- const la = linearRgbToOklab(srgbToLinear(a[0] / 255), srgbToLinear(a[1] / 255), srgbToLinear(a[2] / 255));
282
- const lb = linearRgbToOklab(srgbToLinear(b[0] / 255), srgbToLinear(b[1] / 255), srgbToLinear(b[2] / 255));
283
- const lin = oklabToLinearRgb(
284
- la[0] + (lb[0] - la[0]) * t,
285
- la[1] + (lb[1] - la[1]) * t,
286
- la[2] + (lb[2] - la[2]) * t,
287
- );
288
- return toHex([linearToSrgb(lin[0]) * 255, linearToSrgb(lin[1]) * 255, linearToSrgb(lin[2]) * 255]);
289
- }
290
-
291
- // --- Compiled hot-path forms (package-internal) -----------------------------
292
- //
293
- // `adaptTheme` interpolates the SAME from/to pair on every frame of an ease,
294
- // and strict mode re-derives WCAG luminance from the interpolated colour up to
295
- // 14× per floored role per frame (`floorBlend`'s bisection). Doing that
296
- // through the string API means re-parsing both endpoints and round-tripping
297
- // through `#RRGGBB` text on every call — measured at ~85-90% of the ease-frame
298
- // budget (bench/hotpath.bench.mjs). These helpers compile a pair once and then
299
- // produce results BYTE-IDENTICAL to their string-path equivalents:
300
- //
301
- // · `lerpPairHex(pair, t)` ≡ `oklabLerp(from, to, t)`
302
- // · `lerpPairLuminance(pair, t)` ≡ WCAG luminance of `oklabLerp(from, to, t)`
303
- // · `wcagLuminanceCached(css)` ≡ luminance of `parseCssColor(css) ?? black`
304
- //
305
- // (locked by test/hotpath-parity.test.mjs on randomised inputs). They are
306
- // consumed by `adapt-theme.js` and are NOT part of the public package surface
307
- // (`index.js` does not re-export them).
308
-
309
- const PARSE_CACHE_CAP = 256;
310
- const parseCache = new Map();
311
-
312
- /** `parseCssColor` behind a small bounded memo, for per-frame callers feeding
313
- * it recurring strings (computed-style values, backdrop samples, ease
314
- * endpoints). The cap is a blunt bound, not an LRU: a full cache is simply
315
- * cleared and refills within a frame — cheaper than eviction bookkeeping for
316
- * a working set that is a handful of strings. The cached arrays are SHARED —
317
- * package-internal callers must treat them as immutable. (The public
318
- * `parseCssColor` stays unmemoized and returns a fresh array per call.) */
319
- export function parseCssColorCached(css) {
320
- let hit = parseCache.get(css);
321
- if (hit === undefined) {
322
- hit = parseCssColor(css);
323
- if (parseCache.size >= PARSE_CACHE_CAP) parseCache.clear();
324
- parseCache.set(css, hit);
325
- }
326
- return hit;
327
- }
328
-
329
- /** WCAG 2.1 relative luminance of r,g,b channels (0..255) — the normative
330
- * 0.03928 / 12.92 / 2.4 constants, matching `adapt-theme`'s floor semantics. */
331
- function wcagLumChannels(r, g, b) {
332
- const lin = (c) => {
333
- const s = c / 255;
334
- return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
335
- };
336
- return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
337
- }
338
-
339
- const LUM_CACHE_CAP = 256;
340
- const lumCache = new Map();
341
-
342
- /** WCAG relative luminance of any colour string, memoised. Byte-equal to the
343
- * string path `adapt-theme` used per sample per frame: luminance of
344
- * `parseCssColor(css) ?? [0,0,0,1]` — i.e. unparseable input yields the
345
- * luminance of black, preserving the historical fallback. */
346
- export function wcagLuminanceCached(css) {
347
- let lum = lumCache.get(css);
348
- if (lum === undefined) {
349
- const c = parseCssColorCached(css) ?? [0, 0, 0, 1];
350
- lum = wcagLumChannels(c[0], c[1], c[2]);
351
- if (lumCache.size >= LUM_CACHE_CAP) lumCache.clear();
352
- lumCache.set(css, lum);
353
- }
354
- return lum;
355
- }
356
-
357
- /** Round a channel to the exact byte `toHex` would emit (non-finite → 0,
358
- * clamp, round) — keeps the numeric luminance path quantisation-identical to
359
- * the `#RRGGBB` round-trip it replaces. */
360
- function hexByte(v) {
361
- return Math.round(clamp255(Number.isFinite(v) ? v : 0));
362
- }
363
-
364
- /**
365
- * Compile a from/to colour pair for repeated interpolation. Returns `null`
366
- * when either endpoint fails to parse — callers fall back to `oklabLerp`,
367
- * which owns the unparseable-endpoint fallback semantics. The pair carries
368
- * both endpoints' Oklab coordinates plus their exact `toHex` forms, so the
369
- * per-frame work is one Oklab lerp + gamut map — no string parsing at all.
370
- *
371
- * @param {string} from any colour string `parseCssColor` accepts
372
- * @param {string} to any colour string `parseCssColor` accepts
373
- * @returns {{la:number[],lb:number[],aHex:string,bHex:string,aBytes:number[],bBytes:number[]} | null}
374
- */
375
- export function compileLerpPair(from, to) {
376
- const a = parseCssColorCached(from);
377
- const b = parseCssColorCached(to);
378
- if (!a || !b) return null;
379
- return {
380
- la: linearRgbToOklab(srgbToLinear(a[0] / 255), srgbToLinear(a[1] / 255), srgbToLinear(a[2] / 255)),
381
- lb: linearRgbToOklab(srgbToLinear(b[0] / 255), srgbToLinear(b[1] / 255), srgbToLinear(b[2] / 255)),
382
- aHex: toHex(a),
383
- bHex: toHex(b),
384
- aBytes: [hexByte(a[0]), hexByte(a[1]), hexByte(a[2])],
385
- bBytes: [hexByte(b[0]), hexByte(b[1]), hexByte(b[2])],
386
- };
387
- }
388
-
389
- /** Byte-identical to `oklabLerp(from, to, t)` for the pair's endpoints — the
390
- * same double-precision Oklab lerp on the same parsed channels, minus the
391
- * per-call re-parse. */
392
- export function lerpPairHex(pair, t) {
393
- if (t <= 0) return pair.aHex;
394
- if (t >= 1) return pair.bHex;
395
- const la = pair.la;
396
- const lb = pair.lb;
397
- const lin = oklabToLinearRgb(
398
- la[0] + (lb[0] - la[0]) * t,
399
- la[1] + (lb[1] - la[1]) * t,
400
- la[2] + (lb[2] - la[2]) * t,
401
- );
402
- return toHex([linearToSrgb(lin[0]) * 255, linearToSrgb(lin[1]) * 255, linearToSrgb(lin[2]) * 255]);
403
- }
404
-
405
- /** WCAG relative luminance of `lerpPairHex(pair, t)` WITHOUT the `#RRGGBB`
406
- * round-trip: channels are quantised to the exact bytes `toHex` would emit,
407
- * then fed to the normative formula — so strict-mode bisection over `t` is
408
- * ~20 flops instead of serialise + re-parse, at identical results. */
409
- export function lerpPairLuminance(pair, t) {
410
- if (t <= 0) return wcagLumChannels(pair.aBytes[0], pair.aBytes[1], pair.aBytes[2]);
411
- if (t >= 1) return wcagLumChannels(pair.bBytes[0], pair.bBytes[1], pair.bBytes[2]);
412
- const la = pair.la;
413
- const lb = pair.lb;
414
- const lin = oklabToLinearRgb(
415
- la[0] + (lb[0] - la[0]) * t,
416
- la[1] + (lb[1] - la[1]) * t,
417
- la[2] + (lb[2] - la[2]) * t,
418
- );
419
- return wcagLumChannels(
420
- hexByte(linearToSrgb(lin[0]) * 255),
421
- hexByte(linearToSrgb(lin[1]) * 255),
422
- hexByte(linearToSrgb(lin[2]) * 255),
423
- );
424
- }
425
-
426
- /**
427
- * Compose an ordered stack of colour layers (front-to-back) over an opaque base
428
- * into a single opaque `#RRGGBB`. Pure — no DOM. Exposed for testing and for
429
- * callers that sample their own layers.
430
- *
431
- * @param {Rgba[]} layersFrontToBack index 0 is the topmost layer
432
- * @param {Rgba} opaqueBase must have alpha 1
433
- * @returns {string}
434
- */
435
- export function compositeStackToHex(layersFrontToBack, opaqueBase) {
436
- let result = opaqueBase;
437
- // Apply from the back (closest to base) forward, so index 0 lands on top.
438
- for (let i = layersFrontToBack.length - 1; i >= 0; i--) {
439
- result = compositeOver(layersFrontToBack[i], result);
440
- }
441
- return toHex(result);
442
- }
443
-
444
- /**
445
- * The opaque effective background `#RRGGBB` visible behind `element`'s own
446
- * content, by walking ancestors and compositing their `background-color`s.
447
- *
448
- * Walks from `element` upward, collecting each `background-color` layer, and
449
- * stops at the first fully-opaque layer (which becomes the base). If the chain
450
- * reaches the root without an opaque layer, `fallback` (default white) is the
451
- * base — matching how a browser shows the page's default canvas.
452
- *
453
- * Pure and injectable: pass `getStyle` and `parentOf` to test without a DOM; in
454
- * the browser they default to `getComputedStyle` and `el.parentElement`.
455
- *
456
- * @param {*} element
457
- * @param {object} [opts]
458
- * @param {string} [opts.fallback="#FFFFFF"] base when the chain is fully translucent
459
- * @param {(el: *) => { getPropertyValue: (p: string) => string }} [opts.getStyle]
460
- * @param {(el: *) => *} [opts.parentOf]
461
- * @param {number} [opts.maxDepth=64] guard against detached/cyclic chains
462
- * @returns {string}
463
- */
464
- export function effectiveBackground(element, opts = {}) {
465
- const fallback = opts.fallback ?? "#FFFFFF";
466
- const getStyle =
467
- opts.getStyle ?? ((el) => (typeof getComputedStyle === "function" ? getComputedStyle(el) : { getPropertyValue: () => "" }));
468
- const parentOf = opts.parentOf ?? ((el) => el.parentElement);
469
- const maxDepth = opts.maxDepth ?? 64;
470
-
471
- /** @type {Rgba[]} */
472
- const layers = [];
473
- let el = element;
474
- let depth = 0;
475
- let base = parseCssColor(fallback) ?? [255, 255, 255, 1];
476
-
477
- while (el && depth < maxDepth) {
478
- const css = getStyle(el).getPropertyValue("background-color");
479
- const c = parseCssColor(css);
480
- if (c && c[3] > 0) {
481
- if (c[3] >= 1) {
482
- base = c; // first opaque layer is the base; nothing behind it shows
483
- break;
484
- }
485
- layers.push(c);
486
- }
487
- el = parentOf(el);
488
- depth++;
489
- }
490
-
491
- return compositeStackToHex(layers, base);
492
- }
1
+ // Effective background resolution — zero dependencies.
2
+ //
3
+ // `labcolors` resolves roles against a *solid* background. A real UI surface is
4
+ // often translucent (a panel at `rgba(…, .8)` over its parents) or has no
5
+ // background of its own (inheriting whatever is behind it). To resolve such a
6
+ // surface you need a background observation. This legacy helper produces a
7
+ // reference estimate for the subset it understands; it is not a browser pixel
8
+ // capture or a claim about what a viewer actually sees.
9
+ //
10
+ // This module computes it by walking the ancestor chain and **alpha-compositing**
11
+ // each element's `background-color` (front-to-back) until the stack is opaque,
12
+ // over an opaque fallback (white by default), yielding one solid reference hex
13
+ // the WASM core can consume.
14
+ //
15
+ // HONEST LIMIT: this composites solid/translucent `background-color` layers only.
16
+ // It does NOT sample `background-image`s, gradients, blurred backdrops, video, or
17
+ // content showing through — those have no single colour to read from computed
18
+ // style. For those, the caller supplies the effective background explicitly (the
19
+ // `background` option of `watchTheme`, or a sampled average). What it does cover —
20
+ // translucent panels over solid parents — is the common case and is composited
21
+ // *correctly* (true source-over alpha), not approximated.
22
+ //
23
+ // COLOUR FORMS: `parseCssColor` reads the forms this package actually meets —
24
+ // `#hex`, `rgb()/rgba()` (legacy comma and modern space/slash), `transparent`,
25
+ // and `oklch()` (the engine's OWN emission form since 0.4.0, and what a browser
26
+ // serialises `background-color` back to for an oklch-painted surface). Other
27
+ // modern forms — `lab()`, `lch()`, `color(srgb …)`, `color-mix()`, `hsl()`,
28
+ // named colours beyond `transparent` — are NOT parsed and currently become a
29
+ // dropped layer for compatibility. That is not safe evidence: pass the
30
+ // background explicitly. Issue #283 owns the typed `Unknown` replacement for
31
+ // unsupported syntax, missing opaque bases and incomplete traversal.
32
+
33
+ /** @typedef {[number, number, number, number]} Rgba r,g,b in 0..255, a in 0..1 */
34
+
35
+ /**
36
+ * Parse a CSS colour string into `[r, g, b, a]`, or `null` if unrecognised.
37
+ *
38
+ * Handles the forms computed style actually yields:
39
+ * - `rgb(r, g, b)` / `rgba(r, g, b, a)` and the modern `rgb(r g b / a)`;
40
+ * - `#rgb` / `#rgba` / `#rrggbb` / `#rrggbbaa`;
41
+ * - the `transparent` keyword;
42
+ * - `oklch(L C H)` / `oklch(L C H / A)` — the engine's own emission form and
43
+ * what a browser serialises an oklch-painted `background-color` back to.
44
+ * `L` accepts both a `0..1` number (Chrome's computed form) and a percentage
45
+ * (the engine's literal form); `C` a number or a `%` (100% = 0.4 per CSS
46
+ * Color 4); `H` degrees (bare or `deg`-suffixed); a missing component
47
+ * (`none`) is 0. Conversion to sRGB bytes reuses the file's Oklab↔sRGB
48
+ * transform and is byte-exact to the core's round-trip proof.
49
+ *
50
+ * Any other form — `lab()`, `lch()`, `color(srgb …)`, `color-mix()`, `hsl()`,
51
+ * named colours other than `transparent` — returns `null` (treated as "no
52
+ * layer"); supply such backgrounds explicitly via the `background` option.
53
+ *
54
+ * @param {string} css
55
+ * @returns {Rgba | null}
56
+ */
57
+ export function parseCssColor(css) {
58
+ if (typeof css !== "string") return null;
59
+ const s = css.trim().toLowerCase();
60
+ if (s === "transparent") return [0, 0, 0, 0];
61
+
62
+ if (s.startsWith("oklch(") && s.endsWith(")")) return parseOklch(s.slice(6, -1));
63
+
64
+ if (s[0] === "#") {
65
+ const h = s.slice(1);
66
+ if (h.length === 3 || h.length === 4) {
67
+ const r = parseInt(h[0] + h[0], 16);
68
+ const g = parseInt(h[1] + h[1], 16);
69
+ const b = parseInt(h[2] + h[2], 16);
70
+ const a = h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1;
71
+ return [r, g, b, a].some(Number.isNaN) ? null : [r, g, b, a];
72
+ }
73
+ if (h.length === 6 || h.length === 8) {
74
+ const r = parseInt(h.slice(0, 2), 16);
75
+ const g = parseInt(h.slice(2, 4), 16);
76
+ const b = parseInt(h.slice(4, 6), 16);
77
+ const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
78
+ return [r, g, b, a].some(Number.isNaN) ? null : [r, g, b, a];
79
+ }
80
+ return null;
81
+ }
82
+
83
+ const m = s.match(/^rgba?\(([^)]+)\)$/);
84
+ if (!m) return null;
85
+ // Split on commas or whitespace and an optional "/" alpha separator.
86
+ const parts = m[1].split(/[,\s/]+/).filter((p) => p.length > 0);
87
+ if (parts.length < 3) return null;
88
+ const chan = (p) => (p.endsWith("%") ? (parseFloat(p) / 100) * 255 : parseFloat(p));
89
+ const r = chan(parts[0]);
90
+ const g = chan(parts[1]);
91
+ const b = chan(parts[2]);
92
+ const a = parts.length >= 4 ? (parts[3].endsWith("%") ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])) : 1;
93
+ if ([r, g, b, a].some((v) => Number.isNaN(v))) return null;
94
+ return [clamp255(r), clamp255(g), clamp255(b), Math.min(1, Math.max(0, a))];
95
+ }
96
+
97
+ function clamp255(v) {
98
+ return Math.min(255, Math.max(0, v));
99
+ }
100
+
101
+ /**
102
+ * Parse the inside of an `oklch(...)` (the part between the parens) into sRGB
103
+ * `[r, g, b, a]`, or `null` on any malformed component.
104
+ *
105
+ * The engine emits `oklch(L% C H)` / `oklch(L% C H / A)`; a browser's computed
106
+ * form is `oklch(<L 0..1> C H [/ A])`. Components are whitespace-separated with
107
+ * an optional `/`-separated alpha, exactly like `rgb()`'s modern syntax.
108
+ * oklch → Oklab is `a = C·cos(H)`, `b = C·sin(H)`; then the file's own
109
+ * `oklabToLinearRgb` + `linearToSrgb` land it in sRGB — the SAME transform (and
110
+ * the SAME clamp-then-round the core uses in `hex_from_srgb`) that carries the
111
+ * emitter's byte-exact round-trip, so an emitted string decodes to its source
112
+ * bytes. Out-of-gamut channels clamp per channel, matching `oklabLerp`/`toHex`.
113
+ *
114
+ * @param {string} inner the text between `oklch(` and `)`
115
+ * @returns {Rgba | null}
116
+ */
117
+ function parseOklch(inner) {
118
+ const slash = inner.indexOf("/");
119
+ const lch = (slash >= 0 ? inner.slice(0, slash) : inner).trim();
120
+ const alphaTok = slash >= 0 ? inner.slice(slash + 1).trim() : null;
121
+ const comps = lch.split(/\s+/).filter((p) => p.length > 0);
122
+ if (comps.length !== 3) return null;
123
+
124
+ const L = oklchLightness(comps[0]);
125
+ const C = oklchChroma(comps[1]);
126
+ const H = oklchHue(comps[2]);
127
+ const a = alphaTok === null ? 1 : oklchAlpha(alphaTok);
128
+ if (L === null || C === null || H === null || a === null) return null;
129
+
130
+ const hRad = (H * Math.PI) / 180;
131
+ const lin = oklabToLinearRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
132
+ const byte = (i) => Math.round(clamp255(linearToSrgb(lin[i]) * 255));
133
+ return [byte(0), byte(1), byte(2), a];
134
+ }
135
+
136
+ /** Strict CSS `<number>` (no trailing junk, unlike `parseFloat`), else `null`. */
137
+ function cssNumber(tok) {
138
+ return /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(tok) ? parseFloat(tok) : null;
139
+ }
140
+
141
+ /** L: a percentage → `/100` into `0..1`; a bare number is already `0..1`; `none`
142
+ * → 0. Lightness clamps to `[0, 1]` (CSS Color 4) — a byte-level clamp alone
143
+ * masks out-of-range L only at low chroma, not high, so clamp L explicitly. */
144
+ function oklchLightness(tok) {
145
+ if (tok === "none") return 0;
146
+ const pct = tok.endsWith("%");
147
+ const n = cssNumber(pct ? tok.slice(0, -1) : tok);
148
+ if (n === null) return null;
149
+ return Math.min(1, Math.max(0, pct ? n / 100 : n));
150
+ }
151
+
152
+ /** C: a bare number is absolute chroma; a percentage is a fraction of 0.4
153
+ * (CSS Color 4: 100% = 0.4); `none` → 0. Negative chroma clamps to 0. */
154
+ function oklchChroma(tok) {
155
+ if (tok === "none") return 0;
156
+ const pct = tok.endsWith("%");
157
+ const n = cssNumber(pct ? tok.slice(0, -1) : tok);
158
+ if (n === null) return null;
159
+ return Math.max(0, pct ? (n / 100) * 0.4 : n);
160
+ }
161
+
162
+ /** H: degrees, bare or `deg`-suffixed; `none` → 0. (grad/rad/turn are out of
163
+ * scope — the engine and browsers emit bare degrees.) */
164
+ function oklchHue(tok) {
165
+ if (tok === "none") return 0;
166
+ return cssNumber(tok.endsWith("deg") ? tok.slice(0, -3) : tok);
167
+ }
168
+
169
+ /** Alpha: a number `0..1` or a percentage; `none` → 0; clamped to `[0, 1]`. */
170
+ function oklchAlpha(tok) {
171
+ if (tok === "none") return 0;
172
+ const pct = tok.endsWith("%");
173
+ const n = cssNumber(pct ? tok.slice(0, -1) : tok);
174
+ if (n === null) return null;
175
+ return Math.min(1, Math.max(0, pct ? n / 100 : n));
176
+ }
177
+
178
+ /**
179
+ * Source-over composite of `top` onto `bottom` (Porter-Duff "over").
180
+ *
181
+ * @param {Rgba} top
182
+ * @param {Rgba} bottom
183
+ * @returns {Rgba}
184
+ */
185
+ export function compositeOver(top, bottom) {
186
+ const at = top[3];
187
+ const ab = bottom[3];
188
+ // Affine-форма математически равна expanded source-over и фиксирует
189
+ // объявленный byte-scale binary64 operation order. Это numerical profile,
190
+ // не утверждение глобальной монотонности: округление может менять локальный
191
+ // порядок соседних значений, а legacy WCAG EOTF дополнительно имеет seam.
192
+ const a = ab + at * (1 - ab);
193
+ if (a === 0) return [0, 0, 0, 0];
194
+ const c = (i) => {
195
+ const bottomPremultiplied = bottom[i] * ab;
196
+ return (bottomPremultiplied + at * (top[i] - bottomPremultiplied)) / a;
197
+ };
198
+ return [c(0), c(1), c(2), a];
199
+ }
200
+
201
+ /**
202
+ * `[r, g, b]` (0..255) → `#RRGGBB`, channels rounded and clamped.
203
+ *
204
+ * @param {Rgba | [number, number, number]} rgb
205
+ * @returns {string}
206
+ */
207
+ export function toHex(rgb) {
208
+ // Coerce non-finite channels (NaN/±Infinity, e.g. from a malformed `Rgba`
209
+ // passed by a caller) to 0, so a bad input yields a valid `#RRGGBB` rather
210
+ // than an invalid CSS string like `"#NAN0000"`.
211
+ const h = (v) => {
212
+ const n = Math.round(clamp255(Number.isFinite(v) ? v : 0));
213
+ return n.toString(16).padStart(2, "0");
214
+ };
215
+ return `#${h(rgb[0])}${h(rgb[1])}${h(rgb[2])}`.toUpperCase();
216
+ }
217
+
218
+ // --- Perceptual interpolation (Oklab) -------------------------------------
219
+ //
220
+ // A crossfade should feel even: equal progress should be equal *perceived*
221
+ // change. A straight sRGB-channel blend is not that — it lingers in the brighter
222
+ // half (black→white at t=0.5 is #808080, but the perceived midpoint grey is
223
+ // ~#606060). Interpolating in Oklab — a perceptually-uniform space — fixes the
224
+ // timing and, for chromatic endpoints, avoids the muddy desaturated midpoint a
225
+ // raw RGB blend produces. Björn Ottosson's sRGB↔Oklab transform, self-contained.
226
+
227
+ /** sRGB gamma transfer (IEC 61966-2-1): encoded channel 0..1 → linear 0..1. */
228
+ function srgbToLinear(c) {
229
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
230
+ }
231
+
232
+ /** Inverse sRGB transfer: linear 0..1 → encoded 0..1. */
233
+ function linearToSrgb(c) {
234
+ return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
235
+ }
236
+
237
+ /** Linear-light sRGB `[r,g,b]` (0..1) → Oklab `[L, a, b]`. */
238
+ function linearRgbToOklab(r, g, b) {
239
+ const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
240
+ const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
241
+ const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
242
+ const l_ = Math.cbrt(l);
243
+ const m_ = Math.cbrt(m);
244
+ const s_ = Math.cbrt(s);
245
+ return [
246
+ 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
247
+ 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
248
+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,
249
+ ];
250
+ }
251
+
252
+ /** Oklab `[L, a, b]` → linear-light sRGB `[r,g,b]` (0..1, may be out of gamut). */
253
+ function oklabToLinearRgb(L, A, B) {
254
+ const l_ = L + 0.3963377774 * A + 0.2158037573 * B;
255
+ const m_ = L - 0.1055613458 * A - 0.0638541728 * B;
256
+ const s_ = L - 0.0894841775 * A - 1.291485548 * B;
257
+ const l = l_ * l_ * l_;
258
+ const m = m_ * m_ * m_;
259
+ const s = s_ * s_ * s_;
260
+ return [
261
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
262
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
263
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
264
+ ];
265
+ }
266
+
267
+ /**
268
+ * Interpolate two colours in Oklab at `t ∈ [0,1]`, returning `#RRGGBB`.
269
+ *
270
+ * `from`/`to` may be ANY string `parseCssColor` accepts (`#rgb`/`#rrggbb`,
271
+ * `rgb()`/`rgba()`, `oklch()`, `transparent`) — not only `#RRGGBB`. Perceptually
272
+ * uniform: equal steps in `t` are equal steps in perceived lightness (and a
273
+ * straight, non-muddy path in hue/chroma), so a crossfade feels even rather than
274
+ * lingering bright. Endpoints are returned exactly (`t ≤ 0` → `from`, `t ≥ 1` →
275
+ * `to`), always normalised to `#RRGGBB` through `toHex`; out-of-gamut
276
+ * intermediates are clamped per channel. Unparseable input falls back to the
277
+ * nearer parseable endpoint.
278
+ *
279
+ * @param {string} from any colour string `parseCssColor` accepts
280
+ * @param {string} to any colour string `parseCssColor` accepts
281
+ * @param {number} t
282
+ * @returns {string} a `#RRGGBB` string
283
+ */
284
+ export function oklabLerp(from, to, t) {
285
+ const a = parseCssColor(from);
286
+ const b = parseCssColor(to);
287
+ if (!a || !b) return (b && t >= 0.5) || !a ? (b ? toHex(b) : "#000000") : toHex(a);
288
+ if (t <= 0) return toHex(a);
289
+ if (t >= 1) return toHex(b);
290
+ const la = linearRgbToOklab(srgbToLinear(a[0] / 255), srgbToLinear(a[1] / 255), srgbToLinear(a[2] / 255));
291
+ const lb = linearRgbToOklab(srgbToLinear(b[0] / 255), srgbToLinear(b[1] / 255), srgbToLinear(b[2] / 255));
292
+ const lin = oklabToLinearRgb(
293
+ la[0] + (lb[0] - la[0]) * t,
294
+ la[1] + (lb[1] - la[1]) * t,
295
+ la[2] + (lb[2] - la[2]) * t,
296
+ );
297
+ return toHex([linearToSrgb(lin[0]) * 255, linearToSrgb(lin[1]) * 255, linearToSrgb(lin[2]) * 255]);
298
+ }
299
+
300
+ // --- Compiled hot-path forms (package-internal) -----------------------------
301
+ //
302
+ // `adaptTheme` interpolates the SAME from/to pair on every frame of an ease,
303
+ // and strict mode re-derives WCAG luminance from the interpolated colour up to
304
+ // 14× per floored role per frame (`floorBlend`'s bisection). Doing that
305
+ // through the string API means re-parsing both endpoints and round-tripping
306
+ // through `#RRGGBB` text on every call — measured at ~85-90% of the ease-frame
307
+ // budget (bench/hotpath.bench.mjs). These helpers compile a pair once and then
308
+ // produce results BYTE-IDENTICAL to their string-path equivalents:
309
+ //
310
+ // · `lerpPairHex(pair, t)` ≡ `oklabLerp(from, to, t)`
311
+ // · `lerpPairLuminance(pair, t)` ≡ WCAG luminance of `oklabLerp(from, to, t)`
312
+ // · `wcagLuminanceCached(css)` ≡ luminance of `parseCssColor(css) ?? black`
313
+ //
314
+ // (locked by test/hotpath-parity.test.mjs on randomised inputs). They are
315
+ // consumed by `adapt-theme.js` and are NOT part of the public package surface
316
+ // (`index.js` does not re-export them).
317
+
318
+ const PARSE_CACHE_CAP = 256;
319
+ const parseCache = new Map();
320
+
321
+ /** `parseCssColor` behind a small bounded memo, for per-frame callers feeding
322
+ * it recurring strings (computed-style values, backdrop samples, ease
323
+ * endpoints). The cap is a blunt bound, not an LRU: a full cache is simply
324
+ * cleared and refills within a frame — cheaper than eviction bookkeeping for
325
+ * a working set that is a handful of strings. The cached arrays are SHARED —
326
+ * package-internal callers must treat them as immutable. (The public
327
+ * `parseCssColor` stays unmemoized and returns a fresh array per call.) */
328
+ export function parseCssColorCached(css) {
329
+ let hit = parseCache.get(css);
330
+ if (hit === undefined) {
331
+ hit = parseCssColor(css);
332
+ if (parseCache.size >= PARSE_CACHE_CAP) parseCache.clear();
333
+ parseCache.set(css, hit);
334
+ }
335
+ return hit;
336
+ }
337
+
338
+ /** Relative luminance of r,g,b channels (0..255) in the frozen original WCAG
339
+ * 2.1 (2018) profile: 0.03928 / 12.92 / 2.4, matching `adapt-theme`. */
340
+ function wcagLumChannels(r, g, b) {
341
+ const lin = (c) => {
342
+ const s = c / 255;
343
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
344
+ };
345
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
346
+ }
347
+
348
+ const LUM_CACHE_CAP = 256;
349
+ const lumCache = new Map();
350
+
351
+ /** WCAG relative luminance of any colour string, memoised. Byte-equal to the
352
+ * string path `adapt-theme` used per sample per frame: luminance of
353
+ * `parseCssColor(css) ?? [0,0,0,1]` — i.e. unparseable input yields the
354
+ * luminance of black, preserving the historical fallback. */
355
+ export function wcagLuminanceCached(css) {
356
+ let lum = lumCache.get(css);
357
+ if (lum === undefined) {
358
+ const c = parseCssColorCached(css) ?? [0, 0, 0, 1];
359
+ lum = wcagLumChannels(c[0], c[1], c[2]);
360
+ if (lumCache.size >= LUM_CACHE_CAP) lumCache.clear();
361
+ lumCache.set(css, lum);
362
+ }
363
+ return lum;
364
+ }
365
+
366
+ /** Round a channel to the exact byte `toHex` would emit (non-finite → 0,
367
+ * clamp, round) — keeps the numeric luminance path quantisation-identical to
368
+ * the `#RRGGBB` round-trip it replaces. */
369
+ function hexByte(v) {
370
+ return Math.round(clamp255(Number.isFinite(v) ? v : 0));
371
+ }
372
+
373
+ /**
374
+ * Compile a from/to colour pair for repeated interpolation. Returns `null`
375
+ * when either endpoint fails to parse — callers fall back to `oklabLerp`,
376
+ * which owns the unparseable-endpoint fallback semantics. The pair carries
377
+ * both endpoints' Oklab coordinates plus their exact `toHex` forms, so the
378
+ * per-frame work is one Oklab lerp + gamut map — no string parsing at all.
379
+ *
380
+ * @param {string} from any colour string `parseCssColor` accepts
381
+ * @param {string} to any colour string `parseCssColor` accepts
382
+ * @returns {{la:number[],lb:number[],aHex:string,bHex:string,aBytes:number[],bBytes:number[]} | null}
383
+ */
384
+ export function compileLerpPair(from, to) {
385
+ const a = parseCssColorCached(from);
386
+ const b = parseCssColorCached(to);
387
+ if (!a || !b) return null;
388
+ return {
389
+ la: linearRgbToOklab(srgbToLinear(a[0] / 255), srgbToLinear(a[1] / 255), srgbToLinear(a[2] / 255)),
390
+ lb: linearRgbToOklab(srgbToLinear(b[0] / 255), srgbToLinear(b[1] / 255), srgbToLinear(b[2] / 255)),
391
+ aHex: toHex(a),
392
+ bHex: toHex(b),
393
+ aBytes: [hexByte(a[0]), hexByte(a[1]), hexByte(a[2])],
394
+ bBytes: [hexByte(b[0]), hexByte(b[1]), hexByte(b[2])],
395
+ };
396
+ }
397
+
398
+ /** Byte-identical to `oklabLerp(from, to, t)` for the pair's endpoints — the
399
+ * same double-precision Oklab lerp on the same parsed channels, minus the
400
+ * per-call re-parse. */
401
+ export function lerpPairHex(pair, t) {
402
+ if (t <= 0) return pair.aHex;
403
+ if (t >= 1) return pair.bHex;
404
+ const la = pair.la;
405
+ const lb = pair.lb;
406
+ const lin = oklabToLinearRgb(
407
+ la[0] + (lb[0] - la[0]) * t,
408
+ la[1] + (lb[1] - la[1]) * t,
409
+ la[2] + (lb[2] - la[2]) * t,
410
+ );
411
+ return toHex([linearToSrgb(lin[0]) * 255, linearToSrgb(lin[1]) * 255, linearToSrgb(lin[2]) * 255]);
412
+ }
413
+
414
+ /** Relative luminance of `lerpPairHex(pair, t)` in the frozen legacy WCAG 2.1
415
+ * (2018) profile, WITHOUT the `#RRGGBB` round-trip: channels are quantised to
416
+ * the exact bytes `toHex` would emit, then fed to the same profile formula.
417
+ * This preserves value parity; it does not prove bisection monotonicity. */
418
+ export function lerpPairLuminance(pair, t) {
419
+ if (t <= 0) return wcagLumChannels(pair.aBytes[0], pair.aBytes[1], pair.aBytes[2]);
420
+ if (t >= 1) return wcagLumChannels(pair.bBytes[0], pair.bBytes[1], pair.bBytes[2]);
421
+ const la = pair.la;
422
+ const lb = pair.lb;
423
+ const lin = oklabToLinearRgb(
424
+ la[0] + (lb[0] - la[0]) * t,
425
+ la[1] + (lb[1] - la[1]) * t,
426
+ la[2] + (lb[2] - la[2]) * t,
427
+ );
428
+ return wcagLumChannels(
429
+ hexByte(linearToSrgb(lin[0]) * 255),
430
+ hexByte(linearToSrgb(lin[1]) * 255),
431
+ hexByte(linearToSrgb(lin[2]) * 255),
432
+ );
433
+ }
434
+
435
+ /**
436
+ * Compose an ordered stack of colour layers (front-to-back) over an opaque base
437
+ * into a single opaque `#RRGGBB`. Pure — no DOM. Exposed for testing and for
438
+ * callers that sample their own layers.
439
+ *
440
+ * @param {Rgba[]} layersFrontToBack index 0 is the topmost layer
441
+ * @param {Rgba} opaqueBase must have alpha 1
442
+ * @returns {string}
443
+ */
444
+ export function compositeStackToHex(layersFrontToBack, opaqueBase) {
445
+ let result = opaqueBase;
446
+ // Apply from the back (closest to base) forward, so index 0 lands on top.
447
+ for (let i = layersFrontToBack.length - 1; i >= 0; i--) {
448
+ result = compositeOver(layersFrontToBack[i], result);
449
+ }
450
+ return toHex(result);
451
+ }
452
+
453
+ /**
454
+ * Legacy opaque reference-background estimate for the supported
455
+ * `background-color` subset. This is not a browser pixel observation.
456
+ *
457
+ * Walks from `element` upward, collecting each `background-color` layer, and
458
+ * stops at the first fully-opaque layer (which becomes the base). If the chain
459
+ * reaches the root without an opaque layer, `fallback` (default white) is used
460
+ * as an explicit compatibility assumption; it is not evidence of the canvas.
461
+ *
462
+ * Pure and injectable: pass `getStyle` and `parentOf` to test without a DOM; in
463
+ * the browser they default to `getComputedStyle` and `el.parentElement`.
464
+ *
465
+ * @param {*} element
466
+ * @param {object} [opts]
467
+ * @param {string} [opts.fallback="#FFFFFF"] base when the chain is fully translucent
468
+ * @param {(el: *) => { getPropertyValue: (p: string) => string }} [opts.getStyle]
469
+ * @param {(el: *) => *} [opts.parentOf]
470
+ * @param {number} [opts.maxDepth=64] guard against detached/cyclic chains
471
+ * @returns {string}
472
+ */
473
+ export function effectiveBackground(element, opts = {}) {
474
+ const fallback = opts.fallback ?? "#FFFFFF";
475
+ const getStyle =
476
+ opts.getStyle ?? ((el) => (typeof getComputedStyle === "function" ? getComputedStyle(el) : { getPropertyValue: () => "" }));
477
+ const parentOf = opts.parentOf ?? ((el) => el.parentElement);
478
+ const maxDepth = opts.maxDepth ?? 64;
479
+
480
+ /** @type {Rgba[]} */
481
+ const layers = [];
482
+ let el = element;
483
+ let depth = 0;
484
+ let base = parseCssColor(fallback) ?? [255, 255, 255, 1];
485
+
486
+ while (el && depth < maxDepth) {
487
+ const css = getStyle(el).getPropertyValue("background-color");
488
+ const c = parseCssColor(css);
489
+ if (c && c[3] > 0) {
490
+ if (c[3] >= 1) {
491
+ base = c; // first opaque layer is the base; nothing behind it shows
492
+ break;
493
+ }
494
+ layers.push(c);
495
+ }
496
+ el = parentOf(el);
497
+ depth++;
498
+ }
499
+
500
+ return compositeStackToHex(layers, base);
501
+ }