@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/adapt-theme.js CHANGED
@@ -1,525 +1,542 @@
1
- // Adaptive theme controller — the lazy debounced-re-solve runtime. Zero dependencies.
2
- //
3
- // `watchTheme` re-resolves the whole set whenever the background changes. For a
4
- // CONTINUOUSLY changing background (animation/scroll/blur) that is both expensive
5
- // (a full solve every frame) and jittery (colours twitch frame to frame).
6
- //
7
- // `adaptTheme` is the elegant alternative, and the way real systems behave: it
8
- // does NOT re-solve per frame. Each frame it cheaply RE-CHECKS whether the
9
- // current colours still pass their contrast against the (new) background — one
10
- // perceptual-model forward for the background plus one per role, no solve. While they pass
11
- // it does nothing (no churn, no jitter). Only when a role's perceptual contrast
12
- // stays below target for a sustained moment does it re-solve and **ease** to the
13
- // fresh colours over a short transition. The result: fewer computations, no
14
- // flicker, and a smooth, calm adaptation.
15
- //
16
- // Control law (principled defaults; all tunable):
17
- // * Margin threshold — re-solve only when a role's achieved |Lc| falls below
18
- // `(1 - dropFraction)` of its target |Lc| (a `dropFraction` margin under the
19
- // target), not merely when it touches the line. This is a SINGLE-threshold
20
- // detector: the same level gates entering and leaving the breach state — NOT a
21
- // Schmitt trigger, which would need two distinct levels. The margin keeps a
22
- // background sitting right at the target from counting as a breach, but it
23
- // does NOT by itself stop chatter for values straddling the threshold.
24
- // * Debounce — the breach must persist `sustainMs` before acting, so a dark
25
- // object scrolling past for a couple of frames never triggers. Together with
26
- // min-dwell this is what actually prevents oscillation near the threshold.
27
- // * Min dwell — at least `dwellMs` between re-solves, capping the effective
28
- // transition rate well under the flash threshold.
29
- // * Ease — a non-overshooting ease-out crossfade of `easeMs`; under
30
- // `prefers-reduced-motion` a gentle short fade (NOT a jarring snap — an
31
- // instant state change is more stressful than a soft one, and a colour
32
- // crossfade is not "motion").
33
- // * Theme switches are a deliberate INTENT, not a drift: applied instantly
34
- // (a single quick crossfade), never run through the debounce/dwell machinery.
35
- //
36
- // Floor-clamp modes:
37
- // * Default (free ease): the crossfade does not floor-clamp each frame.
38
- // Reading comprehension is far slower than a ~300ms transition and surfaces
39
- // usually sit on a substrate, so a brief dip of the aesthetic *surplus*
40
- // during the ease is imperceptible while the freshly-solved destination is
41
- // always legal.
42
- // * Strict (`strict: true`): the WCAG legal floor is HELD every frame. For
43
- // text directly on animated content or under `prefers-contrast`, an
44
- // intermediate colour is only shown while it still clears the role's
45
- // `legalFloor` against the live background; a role whose eased intermediate
46
- // would dip below its floor is advanced (monotonically) to the least blend
47
- // that stays legal — never below the line, never a backwards flicker. Roles
48
- // with no legal floor (decorative) ease freely either way.
49
-
50
- import { applyTheme } from "./apply-theme.js";
51
- import {
52
- effectiveBackground,
53
- parseCssColor,
54
- oklabLerp,
55
- compileLerpPair,
56
- lerpPairHex,
57
- lerpPairLuminance,
58
- wcagLuminanceCached,
59
- } from "./effective-bg.js";
60
-
61
- /** Cubic ease-out: fast start, gentle settle, no overshoot. A non-finite `t`
62
- * (e.g. a NaN clock making `(now - easeStart) / easeMs` NaN) is treated as a
63
- * completed ease (1), so the crossfade can never emit `#NANNANNAN` CSS. */
64
- function easeOut(t) {
65
- const clamped = Number.isFinite(t) ? Math.min(1, Math.max(0, t)) : 1;
66
- const u = 1 - clamped;
67
- return 1 - u * u * u;
68
- }
69
-
70
- /** WCAG 2.1 relative luminance of `#RRGGBB` — a faithful transcription of the
71
- * normative definition (0.03928 split, 2.4 exponent), so the strict floor-clamp
72
- * agrees byte-for-byte with the core's `legalFloor` semantics. */
73
- function relativeLuminanceHex(hex) {
74
- const rgb = parseCssColor(hex) ?? [0, 0, 0, 1];
75
- const lin = (c) => {
76
- const s = c / 255;
77
- return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
78
- };
79
- return 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]);
80
- }
81
-
82
- /** WCAG contrast ratio from two relative luminances: `(L+0.05)/(L+0.05)`. */
83
- function wcagRatio(lumA, lumB) {
84
- const hi = Math.max(lumA, lumB);
85
- const lo = Math.min(lumA, lumB);
86
- return (hi + 0.05) / (lo + 0.05);
87
- }
88
-
89
- /** Interpolate an ease segment at `t ∈ [0,1]` in Oklab, so the crossfade is
90
- * perceptually even (no lingering-bright sRGB midpoint, no muddy chroma path).
91
- * Segments carry a compiled pair (`compileLerpPair`) when both endpoints
92
- * parse — the always-case in practice, both being engine-emitted `#RRGGBB` —
93
- * so per-frame interpolation runs on pre-parsed Oklab coordinates instead of
94
- * re-parsing both endpoint strings every frame. A `null` pair falls back to
95
- * `oklabLerp`, which owns the unparseable-endpoint fallback semantics.
96
- * Byte-identical either way (locked by test/hotpath-parity.test.mjs). */
97
- function segHex(seg, t) {
98
- return seg.pair ? lerpPairHex(seg.pair, t) : oklabLerp(seg.from, seg.to, t);
99
- }
100
-
101
- /** WCAG relative luminance of `segHex(seg, t)` — numeric fast path on the
102
- * compiled pair (no `#RRGGBB` round-trip), string path otherwise. Strict
103
- * mode's `floorBlend` bisection calls this up to 14× per role per frame. */
104
- function segLum(seg, t) {
105
- return seg.pair ? lerpPairLuminance(seg.pair, t) : relativeLuminanceHex(segHex(seg, t));
106
- }
107
-
108
- /**
109
- * @typedef {object} AdaptController
110
- * @property {(now?: number) => void} tick Drive one step (call from rAF, or let
111
- * `start()` do it). Cheap: a re-check; a re-solve only on a sustained breach.
112
- * @property {(theme: string) => void} setTheme Switch theme INSTANTLY (intent,
113
- * not drift) — re-resolve and apply, bypassing the debounce/dwell machinery.
114
- * @property {() => void} start Begin an internal requestAnimationFrame loop.
115
- * @property {() => void} stop Stop the loop and disconnect.
116
- * @property {() => Record<string,string>} current The currently-applied vars.
117
- */
118
-
119
- /**
120
- * Keep an element's `--lab-*` variables adapting to its (changing) background
121
- * lazily and smoothly. Applies the resolved set immediately, then holds it while
122
- * it still passes, re-solving + easing only when contrast stably degrades.
123
- *
124
- * @param {*} element
125
- * @param {object} options
126
- * @param {{ resolveTheme: (bg:string,theme:string)=>any, recheckContrast:(bg:string,fgs:string[],theme:string)=>ArrayLike<number> }} options.colors
127
- * @param {string} options.theme
128
- * @param {string | string[] | (() => string | string[])} [options.background]
129
- * explicit effective background. An ARRAY (or a function returning one) is a
130
- * set of worst-case samples of a varying backdrop (gradient / image): the
131
- * colours are held legible against the hardest sample. The caller does the
132
- * pixel sampling; this consumes the samples worst-case.
133
- * @param {*} [options.target=element] element to write vars onto
134
- * @param {string} [options.fallback="#FFFFFF"]
135
- * @param {number} [options.dropFraction=0.2] surplus fraction lost before re-solve
136
- * @param {number} [options.sustainMs=120] breach must persist this long
137
- * @param {number} [options.dwellMs=250] minimum between re-solves
138
- * @param {number} [options.easeMs=280] crossfade duration
139
- * @param {boolean} [options.strict=false] hold each role's WCAG legal floor
140
- * every frame of the ease (for text on animated content / `prefers-contrast`)
141
- * @param {boolean} [options.reducedMotion] override; default reads matchMedia
142
- * @param {() => number} [options.now] clock (default performance.now/Date.now)
143
- * @param {*} [options.win=globalThis]
144
- * @param {(el:*)=>*} [options.getStyle] effectiveBackground seam (testing)
145
- * @param {(el:*)=>*} [options.parentOf] effectiveBackground seam (testing)
146
- * @returns {AdaptController}
147
- */
148
- export function adaptTheme(element, options) {
149
- if (
150
- !options ||
151
- typeof options.colors?.resolveTheme !== "function" ||
152
- typeof options.colors?.recheckContrast !== "function"
153
- ) {
154
- throw new TypeError("adaptTheme: options.colors needs resolveTheme + recheckContrast");
155
- }
156
- const colors = options.colors;
157
- const target = options.target ?? element;
158
- const fallback = options.fallback ?? "#FFFFFF";
159
- const dropFraction = options.dropFraction ?? 0.2;
160
- const sustainMs = options.sustainMs ?? 120;
161
- const dwellMs = options.dwellMs ?? 250;
162
- const strict = options.strict ?? false;
163
- const win = options.win ?? (typeof globalThis !== "undefined" ? globalThis : undefined);
164
- const reducedMotion =
165
- options.reducedMotion ??
166
- (win?.matchMedia ? win.matchMedia("(prefers-reduced-motion: reduce)").matches : false);
167
- // Reduced motion → a gentle SHORT fade, never a hard snap.
168
- const easeMs = reducedMotion ? Math.min(options.easeMs ?? 280, 80) : (options.easeMs ?? 280);
169
- const clock = options.now ?? (() => (win?.performance?.now ? win.performance.now() : Date.now()));
170
-
171
- let theme = options.theme;
172
- /** @type {{ cssVar: string, key: string, lc: number, hex: string, legalFloor: number|null }[]} stable role order */
173
- let roles = [];
174
- /** Full canonical var set from the last solve — the `result.vars` of EVERY
175
- * reachable role (color AND translucent), each an oklch string. Every apply is
176
- * `applyTheme(target, {...baseVars, ...easedColorOverlay})`, so translucent
177
- * roles are never dropped by `applyTheme`'s clear-then-write and always carry
178
- * the current theme's value. Only `kind === "color"` roles (in `roles`) ease. */
179
- let baseVars = {};
180
- /** @type {Map<string,{from:string,to:string,held:number,pair:object|null}>} in-flight ease per cssVar */
181
- let easing = new Map();
182
- let easeStart = 0;
183
- let breachSince = null;
184
- let lastSolveAt = -Infinity;
185
- let lastKey = null;
186
-
187
- const readBackground = () => {
188
- const b = options.background;
189
- if (typeof b === "function") return b();
190
- if (typeof b === "string" || Array.isArray(b)) return b;
191
- return effectiveBackground(element, {
192
- fallback,
193
- getStyle: options.getStyle,
194
- parentOf: options.parentOf,
195
- });
196
- };
197
-
198
- // The background is a SET of samples. A solid surface is one sample; a varying
199
- // backdrop (gradient / image / video the caller sampled) is several. Every
200
- // decision is worst-case over the set: a role "passes" only if it passes
201
- // against EVERY sample, and we re-solve against the HARDEST sample. With one
202
- // sample this collapses to plain single-background behaviour, bit-for-bit.
203
- const readSamples = () => {
204
- const v = readBackground();
205
- const arr = Array.isArray(v) ? v.filter((s) => typeof s === "string" && s.length > 0) : [v];
206
- return arr.length > 0 ? arr : [fallback];
207
- };
208
-
209
- // Recheck the current colours against every sample. A role breaches if its
210
- // achieved |Lc| drops below its single-threshold margin (`|lc| * (1 -
211
- // dropFraction)`) against ANY sample. `worstIdx` is the sample with the least
212
- // set-wide margin — the one to re-solve against, so the constraint we solve to
213
- // is the same constraint we check hardest.
214
- // The current foreground hexes, refreshed on adopt. Rechecks run per changed
215
- // frame and previously rebuilt this identical array from `roles` each time.
216
- let fgsCache = [];
217
-
218
- const recheckSamples = (samples) => {
219
- let breached = false;
220
- let worstIdx = 0;
221
- let worstMargin = Infinity;
222
- for (let s = 0; s < samples.length; s++) {
223
- const flat = colors.recheckContrast(samples[s], fgsCache, theme);
224
- let sampleMargin = Infinity;
225
- for (let i = 0; i < roles.length; i++) {
226
- const want = Math.abs(roles[i].lc) * (1 - dropFraction);
227
- const lcNow = Math.abs(flat[2 * i]);
228
- if (lcNow < want) breached = true;
229
- const margin = want > 0 ? lcNow / want : Infinity;
230
- if (margin < sampleMargin) sampleMargin = margin;
231
- }
232
- if (sampleMargin < worstMargin) {
233
- worstMargin = sampleMargin;
234
- worstIdx = s;
235
- }
236
- }
237
- return { breached, worstIdx };
238
- };
239
-
240
- // Resolve a fresh set and adopt it as the current colours (no ease).
241
- const solveAndAdopt = (bg, now) => {
242
- const result = colors.resolveTheme(bg, theme);
243
- // Carry the FULL canonical var set (color + translucent) so no reachable
244
- // role is dropped by a subsequent apply; only color roles feed the ease.
245
- baseVars = result.vars && typeof result.vars === "object" ? result.vars : {};
246
- roles = Object.entries(result.roles)
247
- .filter(([, r]) => r && r.kind === "color")
248
- .map(([key, r]) => ({
249
- cssVar: r.cssVar,
250
- key,
251
- lc: r.lc,
252
- hex: r.hex,
253
- legalFloor: typeof r.legalFloor === "number" ? r.legalFloor : null,
254
- }));
255
- fgsCache = roles.map((r) => r.hex);
256
- // The adopt may change the var/role KEY SET — force the next write through
257
- // `applyTheme`'s full clear-then-write instead of the mid-ease diff path.
258
- written = null;
259
- lastSolveAt = now;
260
- breachSince = null;
261
- return result;
262
- };
263
-
264
- // Solve+adopt against the hardest of `samples`. With one sample this is a
265
- // single solve; with several it does a provisional solve to learn the role
266
- // colours, picks the worst sample for them, and re-solves against it if that
267
- // is not the one already chosen — so the adopted set is the strongest the
268
- // backdrop demands. Used where there is no current set to recheck (initial
269
- // apply, theme switch); the tick path already knows the worst sample from its
270
- // own recheck and calls `solveAndAdopt` directly.
271
- const solveAndAdoptWorst = (samples, now) => {
272
- solveAndAdopt(samples[0], now);
273
- if (samples.length > 1) {
274
- const { worstIdx } = recheckSamples(samples);
275
- if (worstIdx !== 0) solveAndAdopt(samples[worstIdx], now);
276
- }
277
- };
278
-
279
- // Every write goes through the full canonical set with the (optional) eased
280
- // color overlay on top — so translucent roles in `baseVars` persist through
281
- // the apply, and non-eased color roles keep their canonical oklch form.
282
- // `overlay` carries only in-flight color roles as hex.
283
- //
284
- // WRITE STRATEGY — full vs diff. `written` holds the vars of the last write;
285
- // `null` forces the next write through `applyTheme`'s full clear-then-write.
286
- // Between two adopts the composed key set is invariant (always `baseVars`'
287
- // keys), so mid-ease frames DIFF against `written`: only values that changed
288
- // this frame hit `setProperty` (≈ the roles actually easing), instead of
289
- // remove+set of EVERY `--lab-*` var on every frame — the dominant DOM cost
290
- // of an ease and pure churn for the style engine. The final style state is
291
- // byte-identical to a full rewrite (locked by the golden fingerprints in
292
- // test/hotpath-parity.test.mjs). Every adopt nulls `written`, so key-set
293
- // changes and any external clobbering self-heal at the next solve — the same
294
- // guarantee the always-full-rewrite gave, which also wrote nothing between
295
- // eases while steady.
296
- let written = null;
297
- const applyHexes = (overlay) => {
298
- const vars = { ...baseVars, ...overlay };
299
- if (written === null) {
300
- applyTheme(target, { vars });
301
- } else {
302
- for (const k in vars) {
303
- const v = vars[k];
304
- if (written[k] !== v) target.style.setProperty(k, v);
305
- }
306
- }
307
- written = vars;
308
- };
309
-
310
- // Apply the canonical set as-is (no ease in flight): color roles show their
311
- // oklch form, translucent roles their tint+alpha.
312
- const applyRolesDirect = () => applyHexes({});
313
-
314
- // Begin an ease from the currently-applied colours toward the role colours.
315
- // `held` latches the per-role displayed blend so it only ever advances toward
316
- // the destination (strict mode) — see `stepEase`.
317
- const beginEase = (fromByVar, now) => {
318
- easing = new Map();
319
- for (const r of roles) {
320
- const from = fromByVar[r.cssVar] ?? r.hex;
321
- if (from !== r.hex) {
322
- easing.set(r.cssVar, { from, to: r.hex, held: 0, pair: compileLerpPair(from, r.hex) });
323
- }
324
- }
325
- easeStart = now;
326
- if (easing.size === 0) applyRolesDirect();
327
- };
328
-
329
- // Strict mode: the least blend in [e, 1] whose interpolated colour clears
330
- // `floor` against EVERY background sample in `bgLums`. The destination (`to`,
331
- // blend 1) is a freshly-solved legal colour, so it anchors the search; we
332
- // bisect toward it from the natural ease value `e`. Returns `e` unchanged when
333
- // the eased colour is already legal everywhere (the common case — no
334
- // intervention). The returned blend is always floor-legal against the worst
335
- // sample, except in the unavoidable case where even `to` is illegal against a
336
- // sample that drifted further this frame — then it returns 1 (the most-legal
337
- // colour we have) and the recheck loop re-solves.
338
- const floorBlend = (seg, e, bgLums, floor) => {
339
- const legalAt = (blend) => {
340
- const lum = segLum(seg, blend);
341
- for (let i = 0; i < bgLums.length; i++) {
342
- if (wcagRatio(lum, bgLums[i]) < floor) return false;
343
- }
344
- return true;
345
- };
346
- if (legalAt(e)) return e;
347
- let lo = e;
348
- let hi = 1;
349
- for (let k = 0; k < 14; k++) {
350
- const mid = (lo + hi) / 2;
351
- if (legalAt(mid)) hi = mid;
352
- else lo = mid;
353
- }
354
- return hi; // hi is always legal (or blend 1, the most-legal we have)
355
- };
356
-
357
- // Per-key memo of the samples' WCAG luminances. Strict mode reads them in
358
- // both `stepEase` and `paintedNow` within a tick, and across consecutive
359
- // frames of a static backdrop mid-ease; the tick already computes the
360
- // samples key, so this costs one map per DISTINCT backdrop, not per call.
361
- let lumsKey = null;
362
- let lums = null;
363
- const bgLumsFor = (samples, key) => {
364
- if (key !== lumsKey) {
365
- lums = samples.map(wcagLuminanceCached);
366
- lumsKey = key;
367
- }
368
- return lums;
369
- };
370
-
371
- const stepEase = (now, samples, key) => {
372
- const t = easeMs <= 0 ? 1 : (now - easeStart) / easeMs;
373
- // Terminate the ease when it is done (`t >= 1`) OR when the clock went
374
- // non-finite (a NaN/±∞ `now` making `t` non-finite): drop the segments and
375
- // re-apply the canonical set, so the just-eased color roles snap back from
376
- // their interpolated hex to their oklch form (translucent roles stay put).
377
- // The non-finite guard is load-bearing for STATE, not just paint: without it
378
- // a persistently bad clock would leave `easing` in flight forever, freezing
379
- // color roles at their hex destination and never reverting to canonical
380
- // oklch. (`easeOut` separately guards the interpolation math from
381
- // `#NANNANNAN`; this guards the controller's easing state.)
382
- if (t >= 1 || !Number.isFinite(t)) {
383
- easing = new Map();
384
- applyRolesDirect();
385
- return;
386
- }
387
- const e = easeOut(t);
388
- const bgLums = strict ? bgLumsFor(samples, key) : null;
389
- // Overlay carries ONLY in-flight color roles (as interpolated hex); every
390
- // other role — non-eased color and all translucent — keeps its canonical
391
- // `baseVars` value under the merge in `applyHexes`.
392
- const overlay = {};
393
- for (const r of roles) {
394
- const seg = easing.get(r.cssVar);
395
- if (!seg) continue;
396
- let blend = e;
397
- if (strict && r.legalFloor != null) {
398
- // Hold the floor (against the worst sample), then LATCH: the displayed
399
- // blend may only advance toward the destination, never retreat.
400
- // `floorBlend` is stateless and depends on the live (drifting) samples,
401
- // so on a frame where they drift favourably it could return a *lower*
402
- // blend than last frame — a backwards step toward the old colour, the
403
- // precise jarring reversal this mode exists to avoid. `held` clamps that
404
- // out: the colour progresses monotonically from→to and never below the
405
- // legal line on any sample.
406
- blend = Math.max(floorBlend(seg, e, bgLums, r.legalFloor), seg.held);
407
- seg.held = blend;
408
- }
409
- overlay[r.cssVar] = segHex(seg, blend);
410
- }
411
- applyHexes(overlay);
412
- };
413
-
414
- // The full applied picture: the canonical set (color + translucent) with each
415
- // in-flight color role reported at its LOGICAL target (`seg.to`), so a reader
416
- // sees where the ease is going, not a mid-transition frame.
417
- const currentApplied = () => {
418
- const vars = { ...baseVars };
419
- for (const r of roles) {
420
- const seg = easing.get(r.cssVar);
421
- if (seg) vars[r.cssVar] = seg.to;
422
- }
423
- return vars;
424
- };
425
-
426
- // The colour each role is PAINTED right now — exactly what `stepEase` writes
427
- // this frame: an in-flight segment sampled at `now` (with the SAME strict
428
- // floor-hold + latch against the worst sample when `strict`), else the static
429
- // hex. Mirrors `stepEase`'s blend math byte-for-byte so the begin-from value
430
- // equals what is on screen, including the strict-mode `held` clamp — otherwise
431
- // an overlapping re-solve in strict mode would start one frame BELOW the
432
- // painted (floored) colour.
433
- const paintedNow = (now, samples, key) => {
434
- const t = easeMs <= 0 ? 1 : (now - easeStart) / easeMs;
435
- const e = easeOut(t);
436
- const bgLums = strict ? bgLumsFor(samples, key) : null;
437
- const vars = {};
438
- for (const r of roles) {
439
- const seg = easing.get(r.cssVar);
440
- if (!seg) {
441
- vars[r.cssVar] = r.hex;
442
- continue;
443
- }
444
- const blend =
445
- strict && r.legalFloor != null
446
- ? Math.max(floorBlend(seg, e, bgLums, r.legalFloor), seg.held)
447
- : e;
448
- vars[r.cssVar] = segHex(seg, blend);
449
- }
450
- return vars;
451
- };
452
-
453
- const tick = (nowArg) => {
454
- const now = nowArg ?? clock();
455
- const samples = readSamples();
456
- const key = samples.join("|");
457
- // Advance any in-flight ease first (against the live samples, so strict mode
458
- // holds the legal floor every frame as the backdrop keeps drifting under it).
459
- if (easing.size > 0) stepEase(now, samples, key);
460
-
461
- // Steady state: a static backdrop with no in-flight ease and no pending
462
- // breach needs no work. A PENDING breach keeps us live even on a static
463
- // backdrop, so the sustain timer can fire on one that changed once to a
464
- // failing value and then held.
465
- if (key === lastKey && easing.size === 0 && breachSince === null) return;
466
- lastKey = key;
467
- if (roles.length === 0) return;
468
-
469
- // Cheap worst-case re-check: do the current colours still pass against every
470
- // sample? `worstIdx` is the hardest sample, the one to re-solve against.
471
- const { breached, worstIdx } = recheckSamples(samples);
472
-
473
- if (!breached) {
474
- breachSince = null;
475
- return; // hold — the common case for a slowly-drifting backdrop
476
- }
477
- if (breachSince === null) breachSince = now;
478
- if (now - breachSince < sustainMs || now - lastSolveAt < dwellMs) return; // debounce / dwell
479
-
480
- // Sustained breach: re-solve against the worst sample and ease toward fresh,
481
- // starting from the colour each role is PAINTED right now (the in-flight ease
482
- // sampled at `now`) — never the in-flight TARGET. Starting from the target
483
- // would SNAP the element to the old target for one frame before easing,
484
- // reintroducing flicker when a re-solve overlaps a previous ease.
485
- const fromByVar = paintedNow(now, samples, key);
486
- solveAndAdopt(samples[worstIdx], now);
487
- beginEase(fromByVar, now);
488
- stepEase(now, samples, key);
489
- };
490
-
491
- let rafId = null;
492
- const loop = () => {
493
- tick();
494
- if (win?.requestAnimationFrame) rafId = win.requestAnimationFrame(loop);
495
- };
496
-
497
- // Apply the initial set immediately (against the worst sample of the backdrop).
498
- {
499
- const samples = readSamples();
500
- lastKey = samples.join("|");
501
- solveAndAdoptWorst(samples, clock());
502
- applyRolesDirect();
503
- }
504
-
505
- return {
506
- tick,
507
- setTheme(next) {
508
- theme = next;
509
- const samples = readSamples();
510
- lastKey = samples.join("|");
511
- easing = new Map();
512
- solveAndAdoptWorst(samples, clock());
513
- applyRolesDirect(); // instant — a theme switch is intent, not drift
514
- },
515
- start() {
516
- if (rafId == null && win?.requestAnimationFrame) rafId = win.requestAnimationFrame(loop);
517
- },
518
- stop() {
519
- if (rafId != null && win?.cancelAnimationFrame) win.cancelAnimationFrame(rafId);
520
- rafId = null;
521
- easing = new Map();
522
- },
523
- current: currentApplied,
524
- };
525
- }
1
+ // Adaptive theme controller — the lazy debounced-re-solve runtime. Zero dependencies.
2
+ //
3
+ // `watchTheme` re-resolves the whole set whenever the background changes. For a
4
+ // CONTINUOUSLY changing background (animation/scroll/blur) that is both expensive
5
+ // (a full solve every frame) and jittery (colours twitch frame to frame).
6
+ //
7
+ // `adaptTheme` is the elegant alternative, and the way real systems behave: it
8
+ // does NOT re-solve per frame. Each frame it cheaply RE-CHECKS whether the
9
+ // current colours still pass their contrast against the (new) background — one
10
+ // perceptual-model forward for the background plus one per role, no solve. While they pass
11
+ // it does nothing (no churn, no jitter). Only when a role's perceptual contrast
12
+ // stays below target for a sustained moment does it re-solve and **ease** to the
13
+ // fresh colours over a short transition. The result: fewer computations, no
14
+ // flicker, and a smooth, calm adaptation.
15
+ //
16
+ // Control law (principled defaults; all tunable):
17
+ // * Margin threshold — re-solve only when a role's achieved |Lc| falls below
18
+ // `(1 - dropFraction)` of its target |Lc| (a `dropFraction` margin under the
19
+ // target), not merely when it touches the line. This is a SINGLE-threshold
20
+ // detector: the same level gates entering and leaving the breach state — NOT a
21
+ // Schmitt trigger, which would need two distinct levels. The margin keeps a
22
+ // background sitting right at the target from counting as a breach, but it
23
+ // does NOT by itself stop chatter for values straddling the threshold.
24
+ // * Debounce — the breach must persist `sustainMs` before acting, so a dark
25
+ // object scrolling past for a couple of frames never triggers. Together with
26
+ // min-dwell this is what actually prevents oscillation near the threshold.
27
+ // * Min dwell — at least `dwellMs` between re-solves, capping the effective
28
+ // transition rate well under the flash threshold.
29
+ // * Ease — a non-overshooting ease-out crossfade of `easeMs`; under
30
+ // `prefers-reduced-motion` a gentle short fade (NOT a jarring snap — an
31
+ // instant state change is more stressful than a soft one, and a colour
32
+ // crossfade is not "motion").
33
+ // * Theme switches are a deliberate INTENT, not a drift: applied instantly
34
+ // (a single quick crossfade), never run through the debounce/dwell machinery.
35
+ //
36
+ // Floor-clamp modes:
37
+ // * Default (free ease): the crossfade does not floor-clamp each frame.
38
+ // Reading comprehension is far slower than a ~300ms transition and surfaces
39
+ // usually sit on a substrate, so a brief dip of the aesthetic *surplus*
40
+ // during the ease is imperceptible while the freshly-solved destination is
41
+ // always legal.
42
+ // * Strict (`strict: true`): the WCAG legal floor is HELD every frame. For
43
+ // text directly on animated content or under `prefers-contrast`, an
44
+ // intermediate colour is only shown while it still clears the role's
45
+ // `legalFloor` against the live background; a role whose eased intermediate
46
+ // would dip below its floor is advanced (monotonically) to the least blend
47
+ // that stays legal — never below the line, never a backwards flicker. Roles
48
+ // with no legal floor (decorative) ease freely either way.
49
+
50
+ import { applyTheme } from "./apply-theme.js";
51
+ import {
52
+ effectiveBackground,
53
+ parseCssColor,
54
+ oklabLerp,
55
+ compileLerpPair,
56
+ lerpPairHex,
57
+ lerpPairLuminance,
58
+ wcagLuminanceCached,
59
+ } from "./effective-bg.js";
60
+
61
+ /** Cubic ease-out: fast start, gentle settle, no overshoot. A non-finite `t`
62
+ * (e.g. a NaN clock making `(now - easeStart) / easeMs` NaN) is treated as a
63
+ * completed ease (1), so the crossfade can never emit `#NANNANNAN` CSS. */
64
+ function easeOut(t) {
65
+ const clamped = Number.isFinite(t) ? Math.min(1, Math.max(0, t)) : 1;
66
+ const u = 1 - clamped;
67
+ return 1 - u * u * u;
68
+ }
69
+
70
+ /** WCAG 2.1 relative luminance of `#RRGGBB` — a faithful transcription of the
71
+ * normative definition (0.03928 split, 2.4 exponent), so the strict floor-clamp
72
+ * agrees byte-for-byte with the core's `legalFloor` semantics. */
73
+ function relativeLuminanceHex(hex) {
74
+ const rgb = parseCssColor(hex) ?? [0, 0, 0, 1];
75
+ const lin = (c) => {
76
+ const s = c / 255;
77
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
78
+ };
79
+ return 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]);
80
+ }
81
+
82
+ /** WCAG contrast ratio from two relative luminances: `(L+0.05)/(L+0.05)`. */
83
+ function wcagRatio(lumA, lumB) {
84
+ const hi = Math.max(lumA, lumB);
85
+ const lo = Math.min(lumA, lumB);
86
+ return (hi + 0.05) / (lo + 0.05);
87
+ }
88
+
89
+ /** Interpolate an ease segment at `t ∈ [0,1]` in Oklab, so the crossfade is
90
+ * perceptually even (no lingering-bright sRGB midpoint, no muddy chroma path).
91
+ * Segments carry a compiled pair (`compileLerpPair`) when both endpoints
92
+ * parse — the always-case in practice, both being engine-emitted `#RRGGBB` —
93
+ * so per-frame interpolation runs on pre-parsed Oklab coordinates instead of
94
+ * re-parsing both endpoint strings every frame. A `null` pair falls back to
95
+ * `oklabLerp`, which owns the unparseable-endpoint fallback semantics.
96
+ * Byte-identical either way (locked by test/hotpath-parity.test.mjs). */
97
+ function segHex(seg, t) {
98
+ return seg.pair ? lerpPairHex(seg.pair, t) : oklabLerp(seg.from, seg.to, t);
99
+ }
100
+
101
+ /** WCAG relative luminance of `segHex(seg, t)` — numeric fast path on the
102
+ * compiled pair (no `#RRGGBB` round-trip), string path otherwise. Strict
103
+ * mode's `floorBlend` bisection calls this up to 14× per role per frame. */
104
+ function segLum(seg, t) {
105
+ return seg.pair ? lerpPairLuminance(seg.pair, t) : relativeLuminanceHex(segHex(seg, t));
106
+ }
107
+
108
+ /**
109
+ * @typedef {object} AdaptController
110
+ * @property {(now?: number) => void} tick Drive one step (call from rAF, or let
111
+ * `start()` do it). Cheap: a re-check; a re-solve only on a sustained breach.
112
+ * @property {(theme: string) => void} setTheme Switch theme INSTANTLY (intent,
113
+ * not drift) — re-resolve and apply, bypassing the debounce/dwell machinery.
114
+ * @property {() => void} start Begin an internal requestAnimationFrame loop.
115
+ * @property {() => void} stop Stop the loop and disconnect.
116
+ * @property {() => Record<string,string>} current The currently-applied vars.
117
+ */
118
+
119
+ /**
120
+ * Keep an element's `--lab-*` variables adapting to its (changing) background
121
+ * lazily and smoothly. Applies the resolved set immediately, then holds it while
122
+ * it still passes, re-solving + easing only when contrast stably degrades.
123
+ *
124
+ * @param {*} element
125
+ * @param {object} options
126
+ * @param {{ resolveTheme: (bg:string,theme:string)=>any, recheckContrast:(bg:string,fgs:string[],theme:string)=>ArrayLike<number> }} options.colors
127
+ * @param {string} options.theme
128
+ * @param {string | string[] | (() => string | string[])} [options.background]
129
+ * explicit effective background. An ARRAY (or a function returning one) is a
130
+ * set of worst-case samples of a varying backdrop (gradient / image): the
131
+ * colours are held legible against the hardest sample. The caller does the
132
+ * pixel sampling; this consumes the samples worst-case.
133
+ * @param {*} [options.target=element] element to write vars onto
134
+ * @param {string} [options.fallback="#FFFFFF"]
135
+ * @param {number} [options.dropFraction=0.2] surplus fraction lost before re-solve
136
+ * @param {number} [options.sustainMs=120] breach must persist this long
137
+ * @param {number} [options.dwellMs=250] minimum between re-solves
138
+ * @param {number} [options.easeMs=280] crossfade duration
139
+ * @param {boolean} [options.strict=false] hold each role's WCAG legal floor
140
+ * every frame of the ease (for text on animated content / `prefers-contrast`)
141
+ * @param {boolean} [options.reducedMotion] override; default reads matchMedia
142
+ * @param {() => number} [options.now] clock (default performance.now/Date.now)
143
+ * @param {*} [options.win=globalThis]
144
+ * @param {(el:*)=>*} [options.getStyle] effectiveBackground seam (testing)
145
+ * @param {(el:*)=>*} [options.parentOf] effectiveBackground seam (testing)
146
+ * @returns {AdaptController}
147
+ */
148
+ export function adaptTheme(element, options) {
149
+ if (
150
+ !options ||
151
+ typeof options.colors?.resolveTheme !== "function" ||
152
+ typeof options.colors?.recheckContrast !== "function"
153
+ ) {
154
+ throw new TypeError("adaptTheme: options.colors needs resolveTheme + recheckContrast");
155
+ }
156
+ const colors = options.colors;
157
+ const target = options.target ?? element;
158
+ const fallback = options.fallback ?? "#FFFFFF";
159
+ const dropFraction = options.dropFraction ?? 0.2;
160
+ const sustainMs = options.sustainMs ?? 120;
161
+ const dwellMs = options.dwellMs ?? 250;
162
+ const strict = options.strict ?? false;
163
+ const win = options.win ?? (typeof globalThis !== "undefined" ? globalThis : undefined);
164
+ const reducedMotion =
165
+ options.reducedMotion ??
166
+ (win?.matchMedia ? win.matchMedia("(prefers-reduced-motion: reduce)").matches : false);
167
+ // Reduced motion → a gentle SHORT fade, never a hard snap.
168
+ const easeMs = reducedMotion ? Math.min(options.easeMs ?? 280, 80) : (options.easeMs ?? 280);
169
+ const clock = options.now ?? (() => (win?.performance?.now ? win.performance.now() : Date.now()));
170
+
171
+ let theme = options.theme;
172
+ /** @type {{ cssVar: string, key: string, lc: number, hex: string, legalFloor: number|null }[]} stable role order */
173
+ let roles = [];
174
+ /** Full canonical var set from the last solve — the `result.vars` of EVERY
175
+ * reachable role (color AND translucent), each an oklch string. Every apply is
176
+ * `applyTheme(target, {...baseVars, ...easedColorOverlay})`, so translucent
177
+ * roles are never dropped by `applyTheme`'s clear-then-write and always carry
178
+ * the current theme's value. Only `kind === "color"` roles (in `roles`) ease. */
179
+ let baseVars = {};
180
+ /** @type {Map<string,{from:string,to:string,held:number,pair:object|null}>} in-flight ease per cssVar */
181
+ let easing = new Map();
182
+ let easeStart = 0;
183
+ let breachSince = null;
184
+ let lastSolveAt = -Infinity;
185
+ let lastKey = null;
186
+
187
+ const readBackground = () => {
188
+ const b = options.background;
189
+ if (typeof b === "function") return b();
190
+ if (typeof b === "string" || Array.isArray(b)) return b;
191
+ return effectiveBackground(element, {
192
+ fallback,
193
+ getStyle: options.getStyle,
194
+ parentOf: options.parentOf,
195
+ });
196
+ };
197
+
198
+ // The background is a SET of samples. A solid surface is one sample; a varying
199
+ // backdrop (gradient / image / video the caller sampled) is several. Every
200
+ // decision is worst-case over the set: a role "passes" only if it passes
201
+ // against EVERY sample, and we re-solve against the HARDEST sample. With one
202
+ // sample this collapses to plain single-background behaviour, bit-for-bit.
203
+ const readSamples = () => {
204
+ const v = readBackground();
205
+ const arr = Array.isArray(v) ? v.filter((s) => typeof s === "string" && s.length > 0) : [v];
206
+ return arr.length > 0 ? arr : [fallback];
207
+ };
208
+
209
+ // Recheck the current colours against every sample. A role breaches if its
210
+ // achieved |Lc| drops below its single-threshold margin (`|lc| * (1 -
211
+ // dropFraction)`) against ANY sample. `worstIdx` is the sample with the least
212
+ // set-wide margin — the one to re-solve against, so the constraint we solve to
213
+ // is the same constraint we check hardest.
214
+ // The current foreground hexes, refreshed on adopt. Rechecks run per changed
215
+ // frame and previously rebuilt this identical array from `roles` each time.
216
+ let fgsCache = [];
217
+
218
+ // Batch path (many samples): collapse the shared per-foreground CAM16 forward
219
+ // across every sample into ONE engine call. `recheckContrastMulti` returns a
220
+ // background-major flat buffer where sample `s`, foreground `i` sits at
221
+ // `(s * stride + i) * 2` (Lc) — the batched analogue of the per-sample loop's
222
+ // `flat[2 * i]`. Byte-identical to N `recheckContrast` calls (locked by the
223
+ // wasm boundary parity test), so the worst-margin / breach / worstIdx decision
224
+ // below is bit-for-bit the same as the fallback loop.
225
+ const canBatch =
226
+ typeof colors.recheckContrastMulti === "function";
227
+
228
+ const recheckSamples = (samples) => {
229
+ let breached = false;
230
+ let worstIdx = 0;
231
+ let worstMargin = Infinity;
232
+ const stride = fgsCache.length;
233
+ const batch =
234
+ canBatch && samples.length > 1
235
+ ? colors.recheckContrastMulti(samples, fgsCache, theme)
236
+ : null;
237
+ for (let s = 0; s < samples.length; s++) {
238
+ // Per-sample flat buffer, or a background-major window into the batch one.
239
+ const flat = batch ? null : colors.recheckContrast(samples[s], fgsCache, theme);
240
+ const base = s * stride;
241
+ let sampleMargin = Infinity;
242
+ for (let i = 0; i < roles.length; i++) {
243
+ const want = Math.abs(roles[i].lc) * (1 - dropFraction);
244
+ const lcNow = Math.abs(batch ? batch[(base + i) * 2] : flat[2 * i]);
245
+ if (lcNow < want) breached = true;
246
+ const margin = want > 0 ? lcNow / want : Infinity;
247
+ if (margin < sampleMargin) sampleMargin = margin;
248
+ }
249
+ if (sampleMargin < worstMargin) {
250
+ worstMargin = sampleMargin;
251
+ worstIdx = s;
252
+ }
253
+ }
254
+ return { breached, worstIdx };
255
+ };
256
+
257
+ // Resolve a fresh set and adopt it as the current colours (no ease).
258
+ const solveAndAdopt = (bg, now) => {
259
+ const result = colors.resolveTheme(bg, theme);
260
+ // Carry the FULL canonical var set (color + translucent) so no reachable
261
+ // role is dropped by a subsequent apply; only color roles feed the ease.
262
+ baseVars = result.vars && typeof result.vars === "object" ? result.vars : {};
263
+ roles = Object.entries(result.roles)
264
+ .filter(([, r]) => r && r.kind === "color")
265
+ .map(([key, r]) => ({
266
+ cssVar: r.cssVar,
267
+ key,
268
+ lc: r.lc,
269
+ hex: r.hex,
270
+ legalFloor: typeof r.legalFloor === "number" ? r.legalFloor : null,
271
+ }));
272
+ fgsCache = roles.map((r) => r.hex);
273
+ // The adopt may change the var/role KEY SET — force the next write through
274
+ // `applyTheme`'s full clear-then-write instead of the mid-ease diff path.
275
+ written = null;
276
+ lastSolveAt = now;
277
+ breachSince = null;
278
+ return result;
279
+ };
280
+
281
+ // Solve+adopt against the hardest of `samples`. With one sample this is a
282
+ // single solve; with several it does a provisional solve to learn the role
283
+ // colours, picks the worst sample for them, and re-solves against it if that
284
+ // is not the one already chosen — so the adopted set is the strongest the
285
+ // backdrop demands. Used where there is no current set to recheck (initial
286
+ // apply, theme switch); the tick path already knows the worst sample from its
287
+ // own recheck and calls `solveAndAdopt` directly.
288
+ const solveAndAdoptWorst = (samples, now) => {
289
+ solveAndAdopt(samples[0], now);
290
+ if (samples.length > 1) {
291
+ const { worstIdx } = recheckSamples(samples);
292
+ if (worstIdx !== 0) solveAndAdopt(samples[worstIdx], now);
293
+ }
294
+ };
295
+
296
+ // Every write goes through the full canonical set with the (optional) eased
297
+ // color overlay on top — so translucent roles in `baseVars` persist through
298
+ // the apply, and non-eased color roles keep their canonical oklch form.
299
+ // `overlay` carries only in-flight color roles as hex.
300
+ //
301
+ // WRITE STRATEGY — full vs diff. `written` holds the vars of the last write;
302
+ // `null` forces the next write through `applyTheme`'s full clear-then-write.
303
+ // Between two adopts the composed key set is invariant (always `baseVars`'
304
+ // keys), so mid-ease frames DIFF against `written`: only values that changed
305
+ // this frame hit `setProperty` (≈ the roles actually easing), instead of
306
+ // remove+set of EVERY `--lab-*` var on every frame — the dominant DOM cost
307
+ // of an ease and pure churn for the style engine. The final style state is
308
+ // byte-identical to a full rewrite (locked by the golden fingerprints in
309
+ // test/hotpath-parity.test.mjs). Every adopt nulls `written`, so key-set
310
+ // changes and any external clobbering self-heal at the next solve — the same
311
+ // guarantee the always-full-rewrite gave, which also wrote nothing between
312
+ // eases while steady.
313
+ let written = null;
314
+ const applyHexes = (overlay) => {
315
+ const vars = { ...baseVars, ...overlay };
316
+ if (written === null) {
317
+ applyTheme(target, { vars });
318
+ } else {
319
+ for (const k in vars) {
320
+ const v = vars[k];
321
+ if (written[k] !== v) target.style.setProperty(k, v);
322
+ }
323
+ }
324
+ written = vars;
325
+ };
326
+
327
+ // Apply the canonical set as-is (no ease in flight): color roles show their
328
+ // oklch form, translucent roles their tint+alpha.
329
+ const applyRolesDirect = () => applyHexes({});
330
+
331
+ // Begin an ease from the currently-applied colours toward the role colours.
332
+ // `held` latches the per-role displayed blend so it only ever advances toward
333
+ // the destination (strict mode) — see `stepEase`.
334
+ const beginEase = (fromByVar, now) => {
335
+ easing = new Map();
336
+ for (const r of roles) {
337
+ const from = fromByVar[r.cssVar] ?? r.hex;
338
+ if (from !== r.hex) {
339
+ easing.set(r.cssVar, { from, to: r.hex, held: 0, pair: compileLerpPair(from, r.hex) });
340
+ }
341
+ }
342
+ easeStart = now;
343
+ if (easing.size === 0) applyRolesDirect();
344
+ };
345
+
346
+ // Strict mode: the least blend in [e, 1] whose interpolated colour clears
347
+ // `floor` against EVERY background sample in `bgLums`. The destination (`to`,
348
+ // blend 1) is a freshly-solved legal colour, so it anchors the search; we
349
+ // bisect toward it from the natural ease value `e`. Returns `e` unchanged when
350
+ // the eased colour is already legal everywhere (the common case — no
351
+ // intervention). The returned blend is always floor-legal against the worst
352
+ // sample, except in the unavoidable case where even `to` is illegal against a
353
+ // sample that drifted further this frame — then it returns 1 (the most-legal
354
+ // colour we have) and the recheck loop re-solves.
355
+ const floorBlend = (seg, e, bgLums, floor) => {
356
+ const legalAt = (blend) => {
357
+ const lum = segLum(seg, blend);
358
+ for (let i = 0; i < bgLums.length; i++) {
359
+ if (wcagRatio(lum, bgLums[i]) < floor) return false;
360
+ }
361
+ return true;
362
+ };
363
+ if (legalAt(e)) return e;
364
+ let lo = e;
365
+ let hi = 1;
366
+ for (let k = 0; k < 14; k++) {
367
+ const mid = (lo + hi) / 2;
368
+ if (legalAt(mid)) hi = mid;
369
+ else lo = mid;
370
+ }
371
+ return hi; // hi is always legal (or blend 1, the most-legal we have)
372
+ };
373
+
374
+ // Per-key memo of the samples' WCAG luminances. Strict mode reads them in
375
+ // both `stepEase` and `paintedNow` within a tick, and across consecutive
376
+ // frames of a static backdrop mid-ease; the tick already computes the
377
+ // samples key, so this costs one map per DISTINCT backdrop, not per call.
378
+ let lumsKey = null;
379
+ let lums = null;
380
+ const bgLumsFor = (samples, key) => {
381
+ if (key !== lumsKey) {
382
+ lums = samples.map(wcagLuminanceCached);
383
+ lumsKey = key;
384
+ }
385
+ return lums;
386
+ };
387
+
388
+ const stepEase = (now, samples, key) => {
389
+ const t = easeMs <= 0 ? 1 : (now - easeStart) / easeMs;
390
+ // Terminate the ease when it is done (`t >= 1`) OR when the clock went
391
+ // non-finite (a NaN/±∞ `now` making `t` non-finite): drop the segments and
392
+ // re-apply the canonical set, so the just-eased color roles snap back from
393
+ // their interpolated hex to their oklch form (translucent roles stay put).
394
+ // The non-finite guard is load-bearing for STATE, not just paint: without it
395
+ // a persistently bad clock would leave `easing` in flight forever, freezing
396
+ // color roles at their hex destination and never reverting to canonical
397
+ // oklch. (`easeOut` separately guards the interpolation math from
398
+ // `#NANNANNAN`; this guards the controller's easing state.)
399
+ if (t >= 1 || !Number.isFinite(t)) {
400
+ easing = new Map();
401
+ applyRolesDirect();
402
+ return;
403
+ }
404
+ const e = easeOut(t);
405
+ const bgLums = strict ? bgLumsFor(samples, key) : null;
406
+ // Overlay carries ONLY in-flight color roles (as interpolated hex); every
407
+ // other role — non-eased color and all translucent — keeps its canonical
408
+ // `baseVars` value under the merge in `applyHexes`.
409
+ const overlay = {};
410
+ for (const r of roles) {
411
+ const seg = easing.get(r.cssVar);
412
+ if (!seg) continue;
413
+ let blend = e;
414
+ if (strict && r.legalFloor != null) {
415
+ // Hold the floor (against the worst sample), then LATCH: the displayed
416
+ // blend may only advance toward the destination, never retreat.
417
+ // `floorBlend` is stateless and depends on the live (drifting) samples,
418
+ // so on a frame where they drift favourably it could return a *lower*
419
+ // blend than last frame — a backwards step toward the old colour, the
420
+ // precise jarring reversal this mode exists to avoid. `held` clamps that
421
+ // out: the colour progresses monotonically from→to and never below the
422
+ // legal line on any sample.
423
+ blend = Math.max(floorBlend(seg, e, bgLums, r.legalFloor), seg.held);
424
+ seg.held = blend;
425
+ }
426
+ overlay[r.cssVar] = segHex(seg, blend);
427
+ }
428
+ applyHexes(overlay);
429
+ };
430
+
431
+ // The full applied picture: the canonical set (color + translucent) with each
432
+ // in-flight color role reported at its LOGICAL target (`seg.to`), so a reader
433
+ // sees where the ease is going, not a mid-transition frame.
434
+ const currentApplied = () => {
435
+ const vars = { ...baseVars };
436
+ for (const r of roles) {
437
+ const seg = easing.get(r.cssVar);
438
+ if (seg) vars[r.cssVar] = seg.to;
439
+ }
440
+ return vars;
441
+ };
442
+
443
+ // The colour each role is PAINTED right now — exactly what `stepEase` writes
444
+ // this frame: an in-flight segment sampled at `now` (with the SAME strict
445
+ // floor-hold + latch against the worst sample when `strict`), else the static
446
+ // hex. Mirrors `stepEase`'s blend math byte-for-byte so the begin-from value
447
+ // equals what is on screen, including the strict-mode `held` clamp — otherwise
448
+ // an overlapping re-solve in strict mode would start one frame BELOW the
449
+ // painted (floored) colour.
450
+ const paintedNow = (now, samples, key) => {
451
+ const t = easeMs <= 0 ? 1 : (now - easeStart) / easeMs;
452
+ const e = easeOut(t);
453
+ const bgLums = strict ? bgLumsFor(samples, key) : null;
454
+ const vars = {};
455
+ for (const r of roles) {
456
+ const seg = easing.get(r.cssVar);
457
+ if (!seg) {
458
+ vars[r.cssVar] = r.hex;
459
+ continue;
460
+ }
461
+ const blend =
462
+ strict && r.legalFloor != null
463
+ ? Math.max(floorBlend(seg, e, bgLums, r.legalFloor), seg.held)
464
+ : e;
465
+ vars[r.cssVar] = segHex(seg, blend);
466
+ }
467
+ return vars;
468
+ };
469
+
470
+ const tick = (nowArg) => {
471
+ const now = nowArg ?? clock();
472
+ const samples = readSamples();
473
+ const key = samples.join("|");
474
+ // Advance any in-flight ease first (against the live samples, so strict mode
475
+ // holds the legal floor every frame as the backdrop keeps drifting under it).
476
+ if (easing.size > 0) stepEase(now, samples, key);
477
+
478
+ // Steady state: a static backdrop with no in-flight ease and no pending
479
+ // breach needs no work. A PENDING breach keeps us live even on a static
480
+ // backdrop, so the sustain timer can fire on one that changed once to a
481
+ // failing value and then held.
482
+ if (key === lastKey && easing.size === 0 && breachSince === null) return;
483
+ lastKey = key;
484
+ if (roles.length === 0) return;
485
+
486
+ // Cheap worst-case re-check: do the current colours still pass against every
487
+ // sample? `worstIdx` is the hardest sample, the one to re-solve against.
488
+ const { breached, worstIdx } = recheckSamples(samples);
489
+
490
+ if (!breached) {
491
+ breachSince = null;
492
+ return; // hold — the common case for a slowly-drifting backdrop
493
+ }
494
+ if (breachSince === null) breachSince = now;
495
+ if (now - breachSince < sustainMs || now - lastSolveAt < dwellMs) return; // debounce / dwell
496
+
497
+ // Sustained breach: re-solve against the worst sample and ease toward fresh,
498
+ // starting from the colour each role is PAINTED right now (the in-flight ease
499
+ // sampled at `now`) — never the in-flight TARGET. Starting from the target
500
+ // would SNAP the element to the old target for one frame before easing,
501
+ // reintroducing flicker when a re-solve overlaps a previous ease.
502
+ const fromByVar = paintedNow(now, samples, key);
503
+ solveAndAdopt(samples[worstIdx], now);
504
+ beginEase(fromByVar, now);
505
+ stepEase(now, samples, key);
506
+ };
507
+
508
+ let rafId = null;
509
+ const loop = () => {
510
+ tick();
511
+ if (win?.requestAnimationFrame) rafId = win.requestAnimationFrame(loop);
512
+ };
513
+
514
+ // Apply the initial set immediately (against the worst sample of the backdrop).
515
+ {
516
+ const samples = readSamples();
517
+ lastKey = samples.join("|");
518
+ solveAndAdoptWorst(samples, clock());
519
+ applyRolesDirect();
520
+ }
521
+
522
+ return {
523
+ tick,
524
+ setTheme(next) {
525
+ theme = next;
526
+ const samples = readSamples();
527
+ lastKey = samples.join("|");
528
+ easing = new Map();
529
+ solveAndAdoptWorst(samples, clock());
530
+ applyRolesDirect(); // instant — a theme switch is intent, not drift
531
+ },
532
+ start() {
533
+ if (rafId == null && win?.requestAnimationFrame) rafId = win.requestAnimationFrame(loop);
534
+ },
535
+ stop() {
536
+ if (rafId != null && win?.cancelAnimationFrame) win.cancelAnimationFrame(rafId);
537
+ rafId = null;
538
+ easing = new Map();
539
+ },
540
+ current: currentApplied,
541
+ };
542
+ }