@labpics/colors 0.8.0 → 0.9.1
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/README.md +282 -271
- package/adapt-theme.d.ts +74 -67
- package/adapt-theme.js +542 -525
- package/apply-theme.d.ts +16 -16
- package/apply-theme.js +44 -44
- package/effective-bg.d.ts +50 -50
- package/effective-bg.js +492 -492
- package/index.d.ts +37 -37
- package/index.js +21 -21
- package/package.json +16 -2
- package/pkg/labcolors_bg.wasm +0 -0
- package/watch-theme.d.ts +57 -57
- package/watch-theme.js +144 -144
package/effective-bg.js
CHANGED
|
@@ -1,492 +1,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 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 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
|
+
}
|