@labpics/colors 0.9.1 → 1.0.2

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 DELETED
@@ -1,492 +0,0 @@
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
- }
package/watch-theme.d.ts DELETED
@@ -1,57 +0,0 @@
1
- // Public types for the reactive theme runtime.
2
-
3
- import type { LabColors, ResolvedTheme, ThemeName } from "./pkg/labcolors.js";
4
-
5
- export interface WatchThemeOptions {
6
- /** An initialised `LabColors` engine (after `await init()`). */
7
- colors: Pick<LabColors, "resolveTheme">;
8
- /** Theme name. */
9
- theme: ThemeName;
10
- /**
11
- * Explicit effective background, overriding the ancestor-composite. Use a hex
12
- * string or a `() => hex` you sample yourself for image/gradient/blur surfaces
13
- * that have no single readable `background-color`.
14
- */
15
- background?: string | (() => string);
16
- /** Element to write the `--lab-*` variables onto. Defaults to the watched element. */
17
- target?: HTMLElement;
18
- /** Base colour when the ancestor chain is fully translucent. Default `"#FFFFFF"`. */
19
- fallback?: string;
20
- /** Auto-refresh on DOM attribute mutations. Default `true`. */
21
- observe?: boolean;
22
- /** Mutation-observer root. Defaults to the document element. */
23
- root?: Node;
24
- /** Window-like host (for `MutationObserver`). Defaults to `globalThis`. */
25
- win?: Window;
26
- /** Injection seam for the computed style of an element (testing). */
27
- getStyle?: (element: unknown) => { getPropertyValue(property: string): string };
28
- /** Injection seam for an element's parent (testing). */
29
- parentOf?: (element: unknown) => unknown;
30
- }
31
-
32
- export interface WatchController {
33
- /**
34
- * Re-resolve and re-apply if the effective background (or theme) changed;
35
- * `force` re-applies unconditionally. Returns the now-applied result, or the
36
- * cached one when nothing changed.
37
- */
38
- refresh(force?: boolean): ResolvedTheme | null;
39
- /** Switch theme and re-apply. */
40
- setTheme(theme: ThemeName): void;
41
- /** The effective background hex last resolved. */
42
- background(): string;
43
- /** Disconnect observers and stop watching. */
44
- stop(): void;
45
- }
46
-
47
- /**
48
- * Keep an element's `--lab-*` variables in sync with its (effective) background.
49
- *
50
- * Discrete background/theme changes are caught by a `MutationObserver`;
51
- * continuous (animated) backgrounds are driven by calling `refresh()` from a
52
- * `requestAnimationFrame` loop (cheap — re-resolves only on real change).
53
- */
54
- export declare function watchTheme(
55
- element: HTMLElement,
56
- options: WatchThemeOptions,
57
- ): WatchController;
package/watch-theme.js DELETED
@@ -1,144 +0,0 @@
1
- // Reactive theme runtime — zero dependencies.
2
- //
3
- // `applyTheme` writes a resolved theme's `--lab-*` variables onto an element
4
- // once. `watchTheme` closes the loop the css-injection-runtime chapter left
5
- // open: it keeps an element's variables *in sync* with its background. Point it
6
- // at a surface and theming follows the background — the seamless drop-in for a
7
- // design system that re-resolves against a changing background.
8
- //
9
- // It serves both regimes:
10
- // * DISCRETE changes (theme switch, a class/style toggle, DOM reflow) are
11
- // caught automatically by a `MutationObserver` — call once, forget.
12
- // * CONTINUOUS changes (a CSS-animated or per-frame-scripted background that
13
- // never mutates inline style) are driven by the caller calling `refresh()`
14
- // inside its own `requestAnimationFrame` loop. `refresh()` is cheap: it
15
- // re-resolves only when the effective background actually changed, so a
16
- // steady background costs one string compare per frame, not a WASM solve.
17
- //
18
- // The effective background is computed by alpha-compositing ancestors
19
- // (`effective-bg.js`); for surfaces over images/gradients/blur — which have no
20
- // single readable colour — pass an explicit `background` (a hex string or a
21
- // `() => hex` you sample yourself).
22
-
23
- import { applyTheme } from "./apply-theme.js";
24
- import { effectiveBackground } from "./effective-bg.js";
25
-
26
- /**
27
- * @typedef {object} WatchController
28
- * @property {(force?: boolean) => (object | null)} refresh Re-resolve+apply if the
29
- * background (or theme) changed; `force` re-applies unconditionally. Returns the
30
- * `resolveTheme` result that is now applied, or `null` if nothing was applied.
31
- * @property {(theme: string) => void} setTheme Switch theme and re-apply.
32
- * @property {() => string} background The effective background hex last resolved.
33
- * @property {() => void} stop Disconnect observers and stop watching.
34
- */
35
-
36
- /**
37
- * Keep `element`'s `--lab-*` variables in sync with its (effective) background.
38
- *
39
- * @param {*} element The surface to read the background from and (by default)
40
- * write the variables onto.
41
- * @param {object} options
42
- * @param {{ resolveTheme: (bgHex: string, theme: string) => object }} options.colors
43
- * An initialised `LabColors` engine (already `await init()`-ed).
44
- * @param {string} options.theme Theme name (`"light" | "dark" | …`).
45
- * @param {string | (() => string)} [options.background] Explicit effective
46
- * background, overriding the ancestor-composite (use for image/gradient/blur
47
- * surfaces you sample yourself).
48
- * @param {*} [options.target=element] Element to write the variables onto.
49
- * @param {string} [options.fallback="#FFFFFF"] Base for a fully-translucent chain.
50
- * @param {boolean} [options.observe=true] Auto-refresh on DOM attribute mutations.
51
- * @param {*} [options.root] Mutation-observer root (default: the document element).
52
- * @param {*} [options.win=globalThis] Window-like host (for MutationObserver).
53
- * @param {(el:*)=>*} [options.getStyle] Injection seam for `effectiveBackground`.
54
- * @param {(el:*)=>*} [options.parentOf] Injection seam for `effectiveBackground`.
55
- * @returns {WatchController}
56
- */
57
- export function watchTheme(element, options) {
58
- if (!options || typeof options.colors?.resolveTheme !== "function") {
59
- throw new TypeError("watchTheme: options.colors must be an initialised LabColors engine");
60
- }
61
- if (typeof options.theme !== "string") {
62
- throw new TypeError("watchTheme: options.theme must be a theme name string");
63
- }
64
-
65
- const target = options.target ?? element;
66
- const fallback = options.fallback ?? "#FFFFFF";
67
- const win = options.win ?? (typeof globalThis !== "undefined" ? globalThis : undefined);
68
- let theme = options.theme;
69
- let lastBg = null;
70
- let lastTheme = null;
71
- let lastResult = null;
72
-
73
- const readBackground = () => {
74
- const b = options.background;
75
- if (typeof b === "function") return b();
76
- if (typeof b === "string") return b;
77
- return effectiveBackground(element, {
78
- fallback,
79
- getStyle: options.getStyle,
80
- parentOf: options.parentOf,
81
- });
82
- };
83
-
84
- const refresh = (force = false) => {
85
- const bg = readBackground();
86
- if (!force && bg === lastBg && theme === lastTheme) return lastResult;
87
- const result = options.colors.resolveTheme(bg, theme);
88
- applyTheme(target, result);
89
- lastBg = bg;
90
- lastTheme = theme;
91
- lastResult = result;
92
- return result;
93
- };
94
-
95
- // Coalesce a burst of mutations into a single refresh on the next microtask.
96
- let scheduled = false;
97
- let stopped = false;
98
- const schedule = () => {
99
- if (scheduled || stopped) return;
100
- scheduled = true;
101
- Promise.resolve().then(() => {
102
- scheduled = false;
103
- // A `stop()` between scheduling and this microtask must cancel the refresh
104
- // — the watcher is done, no late writes.
105
- if (!stopped) refresh();
106
- });
107
- };
108
-
109
- let observer = null;
110
- if (options.observe !== false && win && typeof win.MutationObserver === "function") {
111
- const root =
112
- options.root ??
113
- (typeof win.document !== "undefined" ? win.document.documentElement : null);
114
- if (root) {
115
- observer = new win.MutationObserver(schedule);
116
- // A background can change on the element OR any ancestor, via inline style
117
- // or a class swap — so watch attribute changes across the subtree.
118
- observer.observe(root, {
119
- subtree: true,
120
- attributes: true,
121
- attributeFilter: ["style", "class"],
122
- });
123
- }
124
- }
125
-
126
- // Apply immediately so the surface is correct on creation.
127
- refresh(true);
128
-
129
- return {
130
- refresh,
131
- setTheme(next) {
132
- theme = next;
133
- refresh();
134
- },
135
- background() {
136
- return lastBg;
137
- },
138
- stop() {
139
- stopped = true;
140
- if (observer) observer.disconnect();
141
- observer = null;
142
- },
143
- };
144
- }