@labpics/colors 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +381 -282
- package/adapt-theme.d.ts +76 -74
- package/adapt-theme.js +738 -542
- package/apply-theme.d.ts +16 -16
- package/apply-theme.js +45 -44
- package/build-metadata.json +19 -0
- package/effective-bg.d.ts +51 -50
- package/effective-bg.js +501 -492
- package/index.d.ts +70 -37
- package/index.js +21 -21
- package/package.json +11 -5
- package/pkg/labcolors.d.ts +282 -37
- package/pkg/labcolors.js +65 -33
- package/pkg/labcolors_bg.wasm +0 -0
- package/pkg/labcolors_bg.wasm.d.ts +2 -1
- package/watch-theme.d.ts +57 -57
- package/watch-theme.js +144 -144
package/adapt-theme.js
CHANGED
|
@@ -1,542 +1,738 @@
|
|
|
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
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
//
|
|
46
|
-
//
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
*
|
|
110
|
-
* @property {(
|
|
111
|
-
*
|
|
112
|
-
* @property {(
|
|
113
|
-
*
|
|
114
|
-
* @property {() =>
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
*
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
* @param {
|
|
125
|
-
* @param {
|
|
126
|
-
* @param {
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
*
|
|
133
|
-
* @param {
|
|
134
|
-
* @param {
|
|
135
|
-
* @param {number} [options.
|
|
136
|
-
* @param {number} [options.
|
|
137
|
-
* @param {
|
|
138
|
-
*
|
|
139
|
-
*
|
|
140
|
-
*
|
|
141
|
-
* @param {
|
|
142
|
-
* @param {
|
|
143
|
-
* @param {
|
|
144
|
-
* @param {(el:*)=>*} [options.
|
|
145
|
-
* @
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
typeof options.colors?.
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
const
|
|
158
|
-
const
|
|
159
|
-
const
|
|
160
|
-
const
|
|
161
|
-
const
|
|
162
|
-
const
|
|
163
|
-
const
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
let
|
|
184
|
-
|
|
185
|
-
let
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
//
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
//
|
|
214
|
-
//
|
|
215
|
-
//
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
//
|
|
219
|
-
//
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
//
|
|
223
|
-
//
|
|
224
|
-
//
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
if (
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
const
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
const
|
|
472
|
-
const
|
|
473
|
-
const
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
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`): requests the legacy per-frame floor clamp. The
|
|
43
|
+
// current Oklab→clip→sRGB8 path is characterized, but is not globally
|
|
44
|
+
// monotone and therefore does not prove a least/legal blend for every frame;
|
|
45
|
+
// #287 owns the finite hard-floor-safe replacement. Roles with no declared
|
|
46
|
+
// floor (decorative) ease freely either way.
|
|
47
|
+
|
|
48
|
+
import { applyTheme } from "./apply-theme.js";
|
|
49
|
+
import {
|
|
50
|
+
effectiveBackground,
|
|
51
|
+
parseCssColor,
|
|
52
|
+
oklabLerp,
|
|
53
|
+
compileLerpPair,
|
|
54
|
+
lerpPairHex,
|
|
55
|
+
lerpPairLuminance,
|
|
56
|
+
wcagLuminanceCached,
|
|
57
|
+
} from "./effective-bg.js";
|
|
58
|
+
|
|
59
|
+
/** Cubic ease-out: fast start, gentle settle, no overshoot. A non-finite `t`
|
|
60
|
+
* (e.g. a NaN clock making `(now - easeStart) / easeMs` NaN) is treated as a
|
|
61
|
+
* completed ease (1), so the crossfade can never emit `#NANNANNAN` CSS. */
|
|
62
|
+
function easeOut(t) {
|
|
63
|
+
const clamped = Number.isFinite(t) ? Math.min(1, Math.max(0, t)) : 1;
|
|
64
|
+
const u = 1 - clamped;
|
|
65
|
+
return 1 - u * u * u;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Relative luminance of `#RRGGBB` in the frozen original WCAG 2.1 (2018)
|
|
69
|
+
* profile (0.03928 split, 2.4 exponent), so the strict floor-clamp agrees
|
|
70
|
+
* byte-for-byte with the core's versioned `legalFloor` semantics. */
|
|
71
|
+
function relativeLuminanceHex(hex) {
|
|
72
|
+
const rgb = parseCssColor(hex) ?? [0, 0, 0, 1];
|
|
73
|
+
const lin = (c) => {
|
|
74
|
+
const s = c / 255;
|
|
75
|
+
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
76
|
+
};
|
|
77
|
+
return 0.2126 * lin(rgb[0]) + 0.7152 * lin(rgb[1]) + 0.0722 * lin(rgb[2]);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** WCAG contrast ratio from two relative luminances: `(L+0.05)/(L+0.05)`. */
|
|
81
|
+
function wcagRatio(lumA, lumB) {
|
|
82
|
+
const hi = Math.max(lumA, lumB);
|
|
83
|
+
const lo = Math.min(lumA, lumB);
|
|
84
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Interpolate an ease segment at `t ∈ [0,1]` in Oklab, so the crossfade is
|
|
88
|
+
* perceptually even (no lingering-bright sRGB midpoint, no muddy chroma path).
|
|
89
|
+
* Segments carry a compiled pair (`compileLerpPair`) when both endpoints
|
|
90
|
+
* parse — the always-case in practice, both being engine-emitted `#RRGGBB` —
|
|
91
|
+
* so per-frame interpolation runs on pre-parsed Oklab coordinates instead of
|
|
92
|
+
* re-parsing both endpoint strings every frame. A `null` pair falls back to
|
|
93
|
+
* `oklabLerp`, which owns the unparseable-endpoint fallback semantics.
|
|
94
|
+
* Byte-identical either way (locked by test/hotpath-parity.test.mjs). */
|
|
95
|
+
function segHex(seg, t) {
|
|
96
|
+
return seg.pair ? lerpPairHex(seg.pair, t) : oklabLerp(seg.from, seg.to, t);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** WCAG relative luminance of `segHex(seg, t)` — numeric fast path on the
|
|
100
|
+
* compiled pair (no `#RRGGBB` round-trip), string path otherwise. Strict
|
|
101
|
+
* mode's `floorBlend` bisection calls this up to 14× per role per frame. */
|
|
102
|
+
function segLum(seg, t) {
|
|
103
|
+
return seg.pair ? lerpPairLuminance(seg.pair, t) : relativeLuminanceHex(segHex(seg, t));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* @typedef {object} AdaptController
|
|
108
|
+
* @property {(now?: number) => void} tick Drive one step (call from rAF, or let
|
|
109
|
+
* `start()` do it). Cheap: a re-check; a re-solve only on a sustained breach.
|
|
110
|
+
* @property {(theme: string) => void} setTheme Switch theme INSTANTLY (intent,
|
|
111
|
+
* not drift) — re-resolve and apply, bypassing the debounce/dwell machinery.
|
|
112
|
+
* @property {() => void} start Begin an internal requestAnimationFrame loop.
|
|
113
|
+
* @property {() => void} stop Stop the loop and disconnect.
|
|
114
|
+
* @property {() => Record<string,string>} current The currently-applied vars.
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Keep an element's `--lab-*` variables adapting to its (changing) background
|
|
119
|
+
* lazily and smoothly. Applies the resolved set immediately, then holds it while
|
|
120
|
+
* it still passes, re-solving + easing only when contrast stably degrades.
|
|
121
|
+
*
|
|
122
|
+
* @param {*} element
|
|
123
|
+
* @param {object} options
|
|
124
|
+
* @param {{ resolveTheme: (bg:string,theme:string)=>any, recheckContrast:(bg:string,fgs:string[],theme:string)=>ArrayLike<number>, isStableGlowPointNoop?:(tint:string,bg:string)=>boolean }} options.colors
|
|
125
|
+
* @param {string} options.theme
|
|
126
|
+
* @param {string | string[] | (() => string | string[])} [options.background]
|
|
127
|
+
* explicit effective background. An ARRAY (or a function returning one) is a
|
|
128
|
+
* set of worst-case samples of a varying backdrop (gradient / image): the
|
|
129
|
+
* colours are held legible against the hardest sample. The caller does the
|
|
130
|
+
* pixel sampling; this consumes the samples worst-case.
|
|
131
|
+
* @param {*} [options.target=element] element to write vars onto
|
|
132
|
+
* @param {string} [options.fallback="#FFFFFF"]
|
|
133
|
+
* @param {number} [options.dropFraction=0.2] surplus fraction lost before re-solve
|
|
134
|
+
* @param {number} [options.sustainMs=120] breach must persist this long
|
|
135
|
+
* @param {number} [options.dwellMs=250] minimum between re-solves
|
|
136
|
+
* @param {number} [options.easeMs=280] crossfade duration
|
|
137
|
+
* @param {boolean} [options.strict=false] enable the legacy characterized
|
|
138
|
+
* per-frame clamp; the current non-monotone interpolation path is not a
|
|
139
|
+
* universal floor certificate (replacement tracked by #287)
|
|
140
|
+
* @param {boolean} [options.reducedMotion] override; default reads matchMedia
|
|
141
|
+
* @param {() => number} [options.now] clock (default performance.now/Date.now)
|
|
142
|
+
* @param {*} [options.win=globalThis]
|
|
143
|
+
* @param {(el:*)=>*} [options.getStyle] effectiveBackground seam (testing)
|
|
144
|
+
* @param {(el:*)=>*} [options.parentOf] effectiveBackground seam (testing)
|
|
145
|
+
* @returns {AdaptController}
|
|
146
|
+
*/
|
|
147
|
+
export function adaptTheme(element, options) {
|
|
148
|
+
if (
|
|
149
|
+
!options ||
|
|
150
|
+
typeof options.colors?.resolveTheme !== "function" ||
|
|
151
|
+
typeof options.colors?.recheckContrast !== "function"
|
|
152
|
+
) {
|
|
153
|
+
throw new TypeError("adaptTheme: options.colors needs resolveTheme + recheckContrast");
|
|
154
|
+
}
|
|
155
|
+
const colors = options.colors;
|
|
156
|
+
const target = options.target ?? element;
|
|
157
|
+
const fallback = options.fallback ?? "#FFFFFF";
|
|
158
|
+
const dropFraction = options.dropFraction ?? 0.2;
|
|
159
|
+
const sustainMs = options.sustainMs ?? 120;
|
|
160
|
+
const dwellMs = options.dwellMs ?? 250;
|
|
161
|
+
const strict = options.strict ?? false;
|
|
162
|
+
const win = options.win ?? (typeof globalThis !== "undefined" ? globalThis : undefined);
|
|
163
|
+
const reducedMotion =
|
|
164
|
+
options.reducedMotion ??
|
|
165
|
+
(win?.matchMedia ? win.matchMedia("(prefers-reduced-motion: reduce)").matches : false);
|
|
166
|
+
// Reduced motion → a gentle SHORT fade, never a hard snap.
|
|
167
|
+
const easeMs = reducedMotion ? Math.min(options.easeMs ?? 280, 80) : (options.easeMs ?? 280);
|
|
168
|
+
const clock = options.now ?? (() => (win?.performance?.now ? win.performance.now() : Date.now()));
|
|
169
|
+
|
|
170
|
+
let theme = options.theme;
|
|
171
|
+
/** @type {{ cssVar: string, key: string, lc: number, hex: string, legalFloor: number|null }[]} stable role order */
|
|
172
|
+
let roles = [];
|
|
173
|
+
/** Stable Glow roles need an exact class recheck in addition to color
|
|
174
|
+
* contrast rechecks. The only determinate stable state is the core-certified
|
|
175
|
+
* quantised screen point no-op; every other state is typed Indeterminate and must have
|
|
176
|
+
* no halo/core/alpha vars. */
|
|
177
|
+
let stableGlows = [];
|
|
178
|
+
/** Full canonical var set from the last solve — the `result.vars` of EVERY
|
|
179
|
+
* reachable role (color AND translucent), each an oklch string. Every apply is
|
|
180
|
+
* `applyTheme(target, {...baseVars, ...easedColorOverlay})`, so translucent
|
|
181
|
+
* roles are never dropped by `applyTheme`'s clear-then-write and always carry
|
|
182
|
+
* the current theme's value. Only `kind === "color"` roles (in `roles`) ease. */
|
|
183
|
+
let baseVars = {};
|
|
184
|
+
/** @type {Map<string,{from:string,to:string,held:number,pair:object|null}>} in-flight ease per cssVar */
|
|
185
|
+
let easing = new Map();
|
|
186
|
+
let easeStart = 0;
|
|
187
|
+
let breachSince = null;
|
|
188
|
+
let lastSolveAt = -Infinity;
|
|
189
|
+
let lastKey = null;
|
|
190
|
+
|
|
191
|
+
const readBackground = () => {
|
|
192
|
+
const b = options.background;
|
|
193
|
+
if (typeof b === "function") return b();
|
|
194
|
+
if (typeof b === "string" || Array.isArray(b)) return b;
|
|
195
|
+
return effectiveBackground(element, {
|
|
196
|
+
fallback,
|
|
197
|
+
getStyle: options.getStyle,
|
|
198
|
+
parentOf: options.parentOf,
|
|
199
|
+
});
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// The background is a SET of samples. A solid surface is one sample; a varying
|
|
203
|
+
// backdrop (gradient / image / video the caller sampled) is several. Every
|
|
204
|
+
// decision is worst-case over the set: a role "passes" only if it passes
|
|
205
|
+
// against EVERY sample, and we re-solve against the HARDEST sample. With one
|
|
206
|
+
// sample this collapses to plain single-background behaviour, bit-for-bit.
|
|
207
|
+
const readSamples = () => {
|
|
208
|
+
const v = readBackground();
|
|
209
|
+
const arr = Array.isArray(v) ? v.filter((s) => typeof s === "string" && s.length > 0) : [v];
|
|
210
|
+
return arr.length > 0 ? arr : [fallback];
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
// Recheck the current colours against every sample. A role breaches if its
|
|
214
|
+
// achieved |Lc| drops below its single-threshold margin (`|lc| * (1 -
|
|
215
|
+
// dropFraction)`) against ANY sample. `worstIdx` is the sample with the least
|
|
216
|
+
// set-wide margin — the one to re-solve against, so the constraint we solve to
|
|
217
|
+
// is the same constraint we check hardest.
|
|
218
|
+
// The current foreground hexes, refreshed on adopt. Rechecks run per changed
|
|
219
|
+
// frame and previously rebuilt this identical array from `roles` each time.
|
|
220
|
+
let fgsCache = [];
|
|
221
|
+
|
|
222
|
+
// Batch path (many samples): collapse the shared per-foreground CAM16 forward
|
|
223
|
+
// across every sample into ONE engine call. `recheckContrastMulti` returns a
|
|
224
|
+
// background-major flat buffer where sample `s`, foreground `i` sits at
|
|
225
|
+
// `(s * stride + i) * 2` (Lc) — the batched analogue of the per-sample loop's
|
|
226
|
+
// `flat[2 * i]`. Byte-identical to N `recheckContrast` calls (locked by the
|
|
227
|
+
// wasm boundary parity test), so the worst-margin / breach / worstIdx decision
|
|
228
|
+
// below is bit-for-bit the same as the fallback loop.
|
|
229
|
+
const canBatch =
|
|
230
|
+
typeof colors.recheckContrastMulti === "function";
|
|
231
|
+
|
|
232
|
+
const recheckSamples = (samples) => {
|
|
233
|
+
let breached = false;
|
|
234
|
+
let worstIdx = 0;
|
|
235
|
+
let worstMargin = Infinity;
|
|
236
|
+
const stride = fgsCache.length;
|
|
237
|
+
const batch =
|
|
238
|
+
canBatch && samples.length > 1
|
|
239
|
+
? colors.recheckContrastMulti(samples, fgsCache, theme)
|
|
240
|
+
: null;
|
|
241
|
+
for (let s = 0; s < samples.length; s++) {
|
|
242
|
+
// Per-sample flat buffer, or a background-major window into the batch one.
|
|
243
|
+
const flat = batch ? null : colors.recheckContrast(samples[s], fgsCache, theme);
|
|
244
|
+
const base = s * stride;
|
|
245
|
+
let sampleMargin = Infinity;
|
|
246
|
+
for (let i = 0; i < roles.length; i++) {
|
|
247
|
+
const want = Math.abs(roles[i].lc) * (1 - dropFraction);
|
|
248
|
+
const lcNow = Math.abs(batch ? batch[(base + i) * 2] : flat[2 * i]);
|
|
249
|
+
if (lcNow < want) breached = true;
|
|
250
|
+
const margin = want > 0 ? lcNow / want : Infinity;
|
|
251
|
+
if (margin < sampleMargin) sampleMargin = margin;
|
|
252
|
+
}
|
|
253
|
+
if (sampleMargin < worstMargin) {
|
|
254
|
+
worstMargin = sampleMargin;
|
|
255
|
+
worstIdx = s;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return { breached, worstIdx };
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
const stableVarKeys = (role) => [
|
|
262
|
+
role.cssVar,
|
|
263
|
+
`${role.cssVar}-core`,
|
|
264
|
+
`${role.cssVar}-alpha`,
|
|
265
|
+
];
|
|
266
|
+
|
|
267
|
+
const hasDeterminateGlowEnvelope = (result, role, emittedKeys) =>
|
|
268
|
+
role.compositeProfile === "encoded-srgb8-screen-v1" &&
|
|
269
|
+
role.compositeGuarantee === "bit-exact" &&
|
|
270
|
+
role.layerRecipeProfile === "cam16-jprime-oklab-cusp-v1" &&
|
|
271
|
+
role.appearanceDiagnosticProfile === "cam16-ucs-jprime-li2017-v1" &&
|
|
272
|
+
role.constraintLayer === "halo" &&
|
|
273
|
+
typeof role.coreHex === "string" &&
|
|
274
|
+
typeof role.haloHex === "string" &&
|
|
275
|
+
emittedKeys.every((emittedKey) => typeof result.vars?.[emittedKey] === "string");
|
|
276
|
+
|
|
277
|
+
const validatedStableGlowsFrom = (result) => {
|
|
278
|
+
const out = [];
|
|
279
|
+
for (const [key, role] of Object.entries(result.roles ?? {})) {
|
|
280
|
+
if (!role) continue;
|
|
281
|
+
const isGlow = role.kind === "glow" || role.kind === "glow-indeterminate";
|
|
282
|
+
if (!isGlow) {
|
|
283
|
+
if (role.decisionProfile !== undefined) {
|
|
284
|
+
throw new TypeError(`adaptTheme: decision profile on non-Glow role '${key}'`);
|
|
285
|
+
}
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
const expectedCssVar = `--lab-${key}`;
|
|
289
|
+
if (role.cssVar !== expectedCssVar) {
|
|
290
|
+
throw new TypeError(
|
|
291
|
+
`adaptTheme: Glow '${key}' has non-canonical cssVar`,
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
const emittedKeys = stableVarKeys(role);
|
|
295
|
+
if (role.decisionProfile === "legacy-platform-dependent-v1") {
|
|
296
|
+
if (role.kind !== "glow") {
|
|
297
|
+
throw new TypeError(
|
|
298
|
+
`adaptTheme: legacy Glow '${key}' cannot be Indeterminate`,
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
const reached =
|
|
302
|
+
role.targetStatus === "legacy-reached" && role.degraded === false;
|
|
303
|
+
const unreachable =
|
|
304
|
+
role.targetStatus === "legacy-unreachable" && role.degraded === true;
|
|
305
|
+
if (
|
|
306
|
+
!hasDeterminateGlowEnvelope(result, role, emittedKeys) ||
|
|
307
|
+
role.decisionGuarantee?.kind !== "legacy-platform-dependent-v1" ||
|
|
308
|
+
role.selectionDiagnosticProfile !== "cam16-ucs-jprime-li2017-v1" ||
|
|
309
|
+
(!reached && !unreachable)
|
|
310
|
+
) {
|
|
311
|
+
throw new TypeError(
|
|
312
|
+
`adaptTheme: legacy Glow '${key}' lacks lawful legacy evidence`,
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (role.decisionProfile !== "stable-v1") {
|
|
318
|
+
throw new TypeError(`adaptTheme: Glow '${key}' lacks an explicit known decisionProfile`);
|
|
319
|
+
}
|
|
320
|
+
if (role.kind === "glow") {
|
|
321
|
+
if (
|
|
322
|
+
role.decisionGuarantee?.kind !== "bit-exact" ||
|
|
323
|
+
!hasDeterminateGlowEnvelope(result, role, emittedKeys) ||
|
|
324
|
+
role.selectionDiagnosticProfile !== null ||
|
|
325
|
+
role.targetStatus !== "exact-noop-unreachable" ||
|
|
326
|
+
role.degraded !== true
|
|
327
|
+
) {
|
|
328
|
+
throw new TypeError(`adaptTheme: stable Glow '${key}' lacks BitExact evidence`);
|
|
329
|
+
}
|
|
330
|
+
out.push({ key, cssVar: role.cssVar, sourceHex: role.haloHex, indeterminate: false });
|
|
331
|
+
continue;
|
|
332
|
+
}
|
|
333
|
+
if (role.kind === "glow-indeterminate") {
|
|
334
|
+
const expectedSite =
|
|
335
|
+
role.numericalSiteId === "glow-target-or-maximum-v1" &&
|
|
336
|
+
role.constraintLayer === "halo";
|
|
337
|
+
const unavailable =
|
|
338
|
+
role.reason === "sound-bound-unavailable" && role.bounds?.kind === "unavailable";
|
|
339
|
+
const soundOverlap =
|
|
340
|
+
role.reason === "interval-overlap" &&
|
|
341
|
+
role.bounds?.kind === "outward" &&
|
|
342
|
+
Number.isFinite(role.bounds.lower) &&
|
|
343
|
+
Number.isFinite(role.bounds.upper) &&
|
|
344
|
+
role.bounds.lower <= role.bounds.upper;
|
|
345
|
+
const lawfulEvidence = expectedSite && (unavailable || soundOverlap);
|
|
346
|
+
if (
|
|
347
|
+
!lawfulEvidence ||
|
|
348
|
+
typeof role.sourceHex !== "string" ||
|
|
349
|
+
emittedKeys.some((emittedKey) => Object.hasOwn(result.vars ?? {}, emittedKey))
|
|
350
|
+
) {
|
|
351
|
+
throw new TypeError(`adaptTheme: stable Glow '${key}' lacks lawful Indeterminate evidence`);
|
|
352
|
+
}
|
|
353
|
+
out.push({ key, cssVar: role.cssVar, sourceHex: role.sourceHex, indeterminate: true });
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
throw new TypeError(`adaptTheme: stable decision profile on unknown Glow role '${key}'`);
|
|
357
|
+
}
|
|
358
|
+
return out;
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
// Adopt one already-resolved set as the current colours (no ease).
|
|
362
|
+
const adoptResolved = (result, now) => {
|
|
363
|
+
const nextStableGlows = validatedStableGlowsFrom(result);
|
|
364
|
+
// Carry the FULL canonical var set (color + translucent) so no reachable
|
|
365
|
+
// role is dropped by a subsequent apply; only color roles feed the ease.
|
|
366
|
+
baseVars = result.vars && typeof result.vars === "object" ? result.vars : {};
|
|
367
|
+
roles = Object.entries(result.roles)
|
|
368
|
+
.filter(([, r]) => r && r.kind === "color")
|
|
369
|
+
.map(([key, r]) => ({
|
|
370
|
+
cssVar: r.cssVar,
|
|
371
|
+
key,
|
|
372
|
+
lc: r.lc,
|
|
373
|
+
hex: r.hex,
|
|
374
|
+
legalFloor: typeof r.legalFloor === "number" ? r.legalFloor : null,
|
|
375
|
+
}));
|
|
376
|
+
stableGlows = nextStableGlows;
|
|
377
|
+
fgsCache = roles.map((r) => r.hex);
|
|
378
|
+
// The adopt may change the var/role KEY SET — force the next write through
|
|
379
|
+
// `applyTheme`'s full clear-then-write instead of the mid-ease diff path.
|
|
380
|
+
written = null;
|
|
381
|
+
lastSolveAt = now;
|
|
382
|
+
breachSince = null;
|
|
383
|
+
return result;
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
// Resolve a fresh set and adopt it as the current colours (no ease).
|
|
387
|
+
const solveAndAdopt = (bg, now) => adoptResolved(colors.resolveTheme(bg, theme), now);
|
|
388
|
+
|
|
389
|
+
// Solve+adopt against the hardest of `samples`. With one sample this is a
|
|
390
|
+
// single solve; with several it does a provisional solve to learn the role
|
|
391
|
+
// colours, picks the worst sample for them, and re-solves against it if that
|
|
392
|
+
// is not the one already chosen — so the adopted set is the strongest the
|
|
393
|
+
// backdrop demands. Used where there is no current set to recheck (initial
|
|
394
|
+
// apply, theme switch); the tick path already knows the worst sample from its
|
|
395
|
+
// own recheck and calls `solveAndAdopt` directly.
|
|
396
|
+
const solveAndAdoptWorst = (samples, now) => {
|
|
397
|
+
solveAndAdopt(samples[0], now);
|
|
398
|
+
if (samples.length > 1) {
|
|
399
|
+
const { worstIdx } = recheckSamples(samples);
|
|
400
|
+
if (worstIdx !== 0) solveAndAdopt(samples[worstIdx], now);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
// Every write goes through the full canonical set with the (optional) eased
|
|
405
|
+
// color overlay on top — so translucent roles in `baseVars` persist through
|
|
406
|
+
// the apply, and non-eased color roles keep their canonical oklch form.
|
|
407
|
+
// `overlay` carries only in-flight color roles as hex.
|
|
408
|
+
//
|
|
409
|
+
// WRITE STRATEGY — full vs diff. `written` holds the vars of the last write;
|
|
410
|
+
// `null` forces the next write through `applyTheme`'s full clear-then-write.
|
|
411
|
+
// Between two adopts the composed key set is invariant (always `baseVars`'
|
|
412
|
+
// keys), so mid-ease frames DIFF against `written`: only values that changed
|
|
413
|
+
// this frame hit `setProperty` (≈ the roles actually easing), instead of
|
|
414
|
+
// remove+set of EVERY `--lab-*` var on every frame — the dominant DOM cost
|
|
415
|
+
// of an ease and pure churn for the style engine. The final style state is
|
|
416
|
+
// byte-identical to a full rewrite (locked by the golden fingerprints in
|
|
417
|
+
// test/hotpath-parity.test.mjs). Every adopt nulls `written`, so key-set
|
|
418
|
+
// changes and any external clobbering self-heal at the next solve — the same
|
|
419
|
+
// guarantee the always-full-rewrite gave, which also wrote nothing between
|
|
420
|
+
// eases while steady.
|
|
421
|
+
let written = null;
|
|
422
|
+
const applyHexes = (overlay) => {
|
|
423
|
+
const vars = { ...baseVars, ...overlay };
|
|
424
|
+
if (written === null) {
|
|
425
|
+
applyTheme(target, { vars });
|
|
426
|
+
} else {
|
|
427
|
+
for (const k in vars) {
|
|
428
|
+
const v = vars[k];
|
|
429
|
+
if (written[k] !== v) target.style.setProperty(k, v);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
written = vars;
|
|
433
|
+
};
|
|
434
|
+
|
|
435
|
+
// Apply the canonical set as-is (no ease in flight): color roles show their
|
|
436
|
+
// oklch form, translucent roles their tint+alpha.
|
|
437
|
+
const applyRolesDirect = () => applyHexes({});
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Recheck the background-dependent stable Glow decision class. This is not a
|
|
441
|
+
* contrast surplus and therefore never passes through sustain/dwell/easing.
|
|
442
|
+
* A stable Glow result requires the core-owned exact predicate. Missing
|
|
443
|
+
* capability is a typed integration error, never a hidden full-solve loop.
|
|
444
|
+
*/
|
|
445
|
+
const reconcileStableGlows = (samples) => {
|
|
446
|
+
if (stableGlows.length === 0) return false;
|
|
447
|
+
|
|
448
|
+
if (typeof colors.isStableGlowPointNoop !== "function") {
|
|
449
|
+
throw new TypeError(
|
|
450
|
+
"adaptTheme: stable Glow requires colors.isStableGlowPointNoop",
|
|
451
|
+
);
|
|
452
|
+
}
|
|
453
|
+
const desired = new Map();
|
|
454
|
+
for (const role of stableGlows) {
|
|
455
|
+
desired.set(
|
|
456
|
+
role.key,
|
|
457
|
+
samples.some((bg) => !colors.isStableGlowPointNoop(role.sourceHex, bg)),
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const changed = stableGlows.some(
|
|
462
|
+
(role) => desired.get(role.key) !== role.indeterminate,
|
|
463
|
+
);
|
|
464
|
+
if (!changed) return false;
|
|
465
|
+
|
|
466
|
+
// Re-resolve exactly once to refresh certificates/source metadata. Only
|
|
467
|
+
// stable Glow satellites are adopted; color/translucent roles remain under
|
|
468
|
+
// the existing adaptive contrast controller and do not snap.
|
|
469
|
+
const fresh = colors.resolveTheme(samples[0], theme);
|
|
470
|
+
const freshStable = validatedStableGlowsFrom(fresh);
|
|
471
|
+
const freshByKey = new Map(freshStable.map((role) => [role.key, role]));
|
|
472
|
+
const nextVars = { ...baseVars };
|
|
473
|
+
for (const previous of stableGlows) {
|
|
474
|
+
const current = freshByKey.get(previous.key);
|
|
475
|
+
if (!current) {
|
|
476
|
+
throw new TypeError(`adaptTheme: stable Glow role '${previous.key}' disappeared`);
|
|
477
|
+
}
|
|
478
|
+
for (const key of stableVarKeys(previous)) delete nextVars[key];
|
|
479
|
+
const indeterminate = desired.get(previous.key);
|
|
480
|
+
if (!indeterminate) {
|
|
481
|
+
for (const key of stableVarKeys(current)) {
|
|
482
|
+
if (typeof fresh.vars?.[key] !== "string") {
|
|
483
|
+
throw new TypeError(
|
|
484
|
+
`adaptTheme: determinate stable Glow '${previous.key}' lacks '${key}'`,
|
|
485
|
+
);
|
|
486
|
+
}
|
|
487
|
+
nextVars[key] = fresh.vars[key];
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
current.indeterminate = indeterminate;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const previousVars = baseVars;
|
|
494
|
+
baseVars = nextVars;
|
|
495
|
+
stableGlows = freshStable.map((role) => {
|
|
496
|
+
const state = desired.get(role.key);
|
|
497
|
+
return state === undefined ? role : { ...role, indeterminate: state };
|
|
498
|
+
});
|
|
499
|
+
if (written !== null) {
|
|
500
|
+
// A stable certificate transition may coincide with an in-flight color
|
|
501
|
+
// ease. Patch only Glow satellites so the already-painted color overlay
|
|
502
|
+
// remains continuous; resetting `written`/`easing` here would snap every
|
|
503
|
+
// color role to its canonical destination.
|
|
504
|
+
const nextWritten = { ...written };
|
|
505
|
+
const stableKeys = new Set(
|
|
506
|
+
stableGlows.flatMap((role) => stableVarKeys(role)),
|
|
507
|
+
);
|
|
508
|
+
for (const key of stableKeys) {
|
|
509
|
+
if (typeof nextVars[key] === "string") {
|
|
510
|
+
if (previousVars[key] !== nextVars[key] || written[key] !== nextVars[key]) {
|
|
511
|
+
target.style.setProperty(key, nextVars[key]);
|
|
512
|
+
}
|
|
513
|
+
nextWritten[key] = nextVars[key];
|
|
514
|
+
} else {
|
|
515
|
+
target.style.removeProperty(key);
|
|
516
|
+
delete nextWritten[key];
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
written = nextWritten;
|
|
520
|
+
}
|
|
521
|
+
return true;
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
// Begin an ease from the currently-applied colours toward the role colours.
|
|
525
|
+
// `held` latches the per-role displayed blend so it only ever advances toward
|
|
526
|
+
// the destination (strict mode) — see `stepEase`.
|
|
527
|
+
const beginEase = (fromByVar, now) => {
|
|
528
|
+
easing = new Map();
|
|
529
|
+
for (const r of roles) {
|
|
530
|
+
const from = fromByVar[r.cssVar] ?? r.hex;
|
|
531
|
+
if (from !== r.hex) {
|
|
532
|
+
easing.set(r.cssVar, { from, to: r.hex, held: 0, pair: compileLerpPair(from, r.hex) });
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
easeStart = now;
|
|
536
|
+
if (easing.size === 0) applyRolesDirect();
|
|
537
|
+
};
|
|
538
|
+
|
|
539
|
+
// Legacy strict clamp: fixed-step bisection from the natural ease value `e`
|
|
540
|
+
// toward the freshly-solved destination. Oklab→clip→sRGB8 legality is not
|
|
541
|
+
// globally monotone, so this is a characterized compatibility selector, not
|
|
542
|
+
// a proof of the least or universally legal blend. #287 owns the finite
|
|
543
|
+
// hard-floor-safe replacement. If even `to` fails after background drift, the
|
|
544
|
+
// selector returns 1 and the recheck loop requests another solve.
|
|
545
|
+
const floorBlend = (seg, e, bgLums, floor) => {
|
|
546
|
+
const legalAt = (blend) => {
|
|
547
|
+
const lum = segLum(seg, blend);
|
|
548
|
+
for (let i = 0; i < bgLums.length; i++) {
|
|
549
|
+
if (wcagRatio(lum, bgLums[i]) < floor) return false;
|
|
550
|
+
}
|
|
551
|
+
return true;
|
|
552
|
+
};
|
|
553
|
+
if (legalAt(e)) return e;
|
|
554
|
+
let lo = e;
|
|
555
|
+
let hi = 1;
|
|
556
|
+
for (let k = 0; k < 14; k++) {
|
|
557
|
+
const mid = (lo + hi) / 2;
|
|
558
|
+
if (legalAt(mid)) hi = mid;
|
|
559
|
+
else lo = mid;
|
|
560
|
+
}
|
|
561
|
+
return hi; // hi is always legal (or blend 1, the most-legal we have)
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
// Per-key memo of the samples' WCAG luminances. Strict mode reads them in
|
|
565
|
+
// both `stepEase` and `paintedNow` within a tick, and across consecutive
|
|
566
|
+
// frames of a static backdrop mid-ease; the tick already computes the
|
|
567
|
+
// samples key, so this costs one map per DISTINCT backdrop, not per call.
|
|
568
|
+
let lumsKey = null;
|
|
569
|
+
let lums = null;
|
|
570
|
+
const bgLumsFor = (samples, key) => {
|
|
571
|
+
if (key !== lumsKey) {
|
|
572
|
+
lums = samples.map(wcagLuminanceCached);
|
|
573
|
+
lumsKey = key;
|
|
574
|
+
}
|
|
575
|
+
return lums;
|
|
576
|
+
};
|
|
577
|
+
|
|
578
|
+
const stepEase = (now, samples, key) => {
|
|
579
|
+
const t = easeMs <= 0 ? 1 : (now - easeStart) / easeMs;
|
|
580
|
+
// Terminate the ease when it is done (`t >= 1`) OR when the clock went
|
|
581
|
+
// non-finite (a NaN/±∞ `now` making `t` non-finite): drop the segments and
|
|
582
|
+
// re-apply the canonical set, so the just-eased color roles snap back from
|
|
583
|
+
// their interpolated hex to their oklch form (translucent roles stay put).
|
|
584
|
+
// The non-finite guard is load-bearing for STATE, not just paint: without it
|
|
585
|
+
// a persistently bad clock would leave `easing` in flight forever, freezing
|
|
586
|
+
// color roles at their hex destination and never reverting to canonical
|
|
587
|
+
// oklch. (`easeOut` separately guards the interpolation math from
|
|
588
|
+
// `#NANNANNAN`; this guards the controller's easing state.)
|
|
589
|
+
if (t >= 1 || !Number.isFinite(t)) {
|
|
590
|
+
easing = new Map();
|
|
591
|
+
applyRolesDirect();
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
const e = easeOut(t);
|
|
595
|
+
const bgLums = strict ? bgLumsFor(samples, key) : null;
|
|
596
|
+
// Overlay carries ONLY in-flight color roles (as interpolated hex); every
|
|
597
|
+
// other role — non-eased color and all translucent — keeps its canonical
|
|
598
|
+
// `baseVars` value under the merge in `applyHexes`.
|
|
599
|
+
const overlay = {};
|
|
600
|
+
for (const r of roles) {
|
|
601
|
+
const seg = easing.get(r.cssVar);
|
|
602
|
+
if (!seg) continue;
|
|
603
|
+
let blend = e;
|
|
604
|
+
if (strict && r.legalFloor != null) {
|
|
605
|
+
// Hold the floor (against the worst sample), then LATCH: the displayed
|
|
606
|
+
// blend may only advance toward the destination, never retreat.
|
|
607
|
+
// `floorBlend` is stateless and depends on the live (drifting) samples,
|
|
608
|
+
// so on a frame where they drift favourably it could return a *lower*
|
|
609
|
+
// blend than last frame — a backwards step toward the old colour, the
|
|
610
|
+
// precise jarring reversal this mode exists to avoid. `held` clamps that
|
|
611
|
+
// out: the scalar blend parameter never retreats. This latch alone is
|
|
612
|
+
// not a proof that the quantized colour stays above every floor; #287
|
|
613
|
+
// owns that finite-path guarantee.
|
|
614
|
+
blend = Math.max(floorBlend(seg, e, bgLums, r.legalFloor), seg.held);
|
|
615
|
+
seg.held = blend;
|
|
616
|
+
}
|
|
617
|
+
overlay[r.cssVar] = segHex(seg, blend);
|
|
618
|
+
}
|
|
619
|
+
applyHexes(overlay);
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
// The full applied picture: the canonical set (color + translucent) with each
|
|
623
|
+
// in-flight color role reported at its LOGICAL target (`seg.to`), so a reader
|
|
624
|
+
// sees where the ease is going, not a mid-transition frame.
|
|
625
|
+
const currentApplied = () => {
|
|
626
|
+
const vars = { ...baseVars };
|
|
627
|
+
for (const r of roles) {
|
|
628
|
+
const seg = easing.get(r.cssVar);
|
|
629
|
+
if (seg) vars[r.cssVar] = seg.to;
|
|
630
|
+
}
|
|
631
|
+
return vars;
|
|
632
|
+
};
|
|
633
|
+
|
|
634
|
+
// The colour each role is PAINTED right now — exactly what `stepEase` writes
|
|
635
|
+
// this frame: an in-flight segment sampled at `now` (with the SAME strict
|
|
636
|
+
// floor-hold + latch against the worst sample when `strict`), else the static
|
|
637
|
+
// hex. Mirrors `stepEase`'s blend math byte-for-byte so the begin-from value
|
|
638
|
+
// equals what is on screen, including the strict-mode `held` clamp — otherwise
|
|
639
|
+
// an overlapping re-solve in strict mode would start one frame BELOW the
|
|
640
|
+
// painted (floored) colour.
|
|
641
|
+
const paintedNow = (now, samples, key) => {
|
|
642
|
+
const t = easeMs <= 0 ? 1 : (now - easeStart) / easeMs;
|
|
643
|
+
const e = easeOut(t);
|
|
644
|
+
const bgLums = strict ? bgLumsFor(samples, key) : null;
|
|
645
|
+
const vars = {};
|
|
646
|
+
for (const r of roles) {
|
|
647
|
+
const seg = easing.get(r.cssVar);
|
|
648
|
+
if (!seg) {
|
|
649
|
+
vars[r.cssVar] = r.hex;
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
const blend =
|
|
653
|
+
strict && r.legalFloor != null
|
|
654
|
+
? Math.max(floorBlend(seg, e, bgLums, r.legalFloor), seg.held)
|
|
655
|
+
: e;
|
|
656
|
+
vars[r.cssVar] = segHex(seg, blend);
|
|
657
|
+
}
|
|
658
|
+
return vars;
|
|
659
|
+
};
|
|
660
|
+
|
|
661
|
+
const tick = (nowArg) => {
|
|
662
|
+
const now = nowArg ?? clock();
|
|
663
|
+
const samples = readSamples();
|
|
664
|
+
const key = samples.join("|");
|
|
665
|
+
// Advance any in-flight ease first against the live samples. Legacy strict
|
|
666
|
+
// mode applies its characterized clamp here; it is not a universal
|
|
667
|
+
// per-frame floor certificate (#287).
|
|
668
|
+
if (easing.size > 0) stepEase(now, samples, key);
|
|
669
|
+
|
|
670
|
+
// Steady state: a static backdrop with no in-flight ease and no pending
|
|
671
|
+
// breach needs no work. A PENDING breach keeps us live even on a static
|
|
672
|
+
// backdrop, so the sustain timer can fire on one that changed once to a
|
|
673
|
+
// failing value and then held.
|
|
674
|
+
if (key === lastKey && easing.size === 0 && breachSince === null) return;
|
|
675
|
+
if (key !== lastKey) reconcileStableGlows(samples);
|
|
676
|
+
lastKey = key;
|
|
677
|
+
if (roles.length === 0) return;
|
|
678
|
+
|
|
679
|
+
// Cheap worst-case re-check: do the current colours still pass against every
|
|
680
|
+
// sample? `worstIdx` is the hardest sample, the one to re-solve against.
|
|
681
|
+
const { breached, worstIdx } = recheckSamples(samples);
|
|
682
|
+
|
|
683
|
+
if (!breached) {
|
|
684
|
+
breachSince = null;
|
|
685
|
+
return; // hold — the common case for a slowly-drifting backdrop
|
|
686
|
+
}
|
|
687
|
+
if (breachSince === null) breachSince = now;
|
|
688
|
+
if (now - breachSince < sustainMs || now - lastSolveAt < dwellMs) return; // debounce / dwell
|
|
689
|
+
|
|
690
|
+
// Sustained breach: re-solve against the worst sample and ease toward fresh,
|
|
691
|
+
// starting from the colour each role is PAINTED right now (the in-flight ease
|
|
692
|
+
// sampled at `now`) — never the in-flight TARGET. Starting from the target
|
|
693
|
+
// would SNAP the element to the old target for one frame before easing,
|
|
694
|
+
// reintroducing flicker when a re-solve overlaps a previous ease.
|
|
695
|
+
const fromByVar = paintedNow(now, samples, key);
|
|
696
|
+
solveAndAdopt(samples[worstIdx], now);
|
|
697
|
+
reconcileStableGlows(samples);
|
|
698
|
+
beginEase(fromByVar, now);
|
|
699
|
+
stepEase(now, samples, key);
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
let rafId = null;
|
|
703
|
+
const loop = () => {
|
|
704
|
+
tick();
|
|
705
|
+
if (win?.requestAnimationFrame) rafId = win.requestAnimationFrame(loop);
|
|
706
|
+
};
|
|
707
|
+
|
|
708
|
+
// Apply the initial set immediately (against the worst sample of the backdrop).
|
|
709
|
+
{
|
|
710
|
+
const samples = readSamples();
|
|
711
|
+
lastKey = samples.join("|");
|
|
712
|
+
solveAndAdoptWorst(samples, clock());
|
|
713
|
+
reconcileStableGlows(samples);
|
|
714
|
+
applyRolesDirect();
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
return {
|
|
718
|
+
tick,
|
|
719
|
+
setTheme(next) {
|
|
720
|
+
theme = next;
|
|
721
|
+
const samples = readSamples();
|
|
722
|
+
lastKey = samples.join("|");
|
|
723
|
+
easing = new Map();
|
|
724
|
+
solveAndAdoptWorst(samples, clock());
|
|
725
|
+
reconcileStableGlows(samples);
|
|
726
|
+
applyRolesDirect(); // instant — a theme switch is intent, not drift
|
|
727
|
+
},
|
|
728
|
+
start() {
|
|
729
|
+
if (rafId == null && win?.requestAnimationFrame) rafId = win.requestAnimationFrame(loop);
|
|
730
|
+
},
|
|
731
|
+
stop() {
|
|
732
|
+
if (rafId != null && win?.cancelAnimationFrame) win.cancelAnimationFrame(rafId);
|
|
733
|
+
rafId = null;
|
|
734
|
+
easing = new Map();
|
|
735
|
+
},
|
|
736
|
+
current: currentApplied,
|
|
737
|
+
};
|
|
738
|
+
}
|