@labpics/colors 0.9.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/LICENSES/CC-BY-4.0.txt +396 -0
- package/LICENSES/CC-BY-SA-4.0.txt +428 -0
- package/NOTICE.md +65 -0
- package/README.md +351 -282
- package/build-metadata.json +23 -0
- package/evidence/point-support-reference-surplus-q55-bps-proof-v1.json +1 -0
- package/evidence/wcag22-srgb8-q55-proof-v1.json +1 -0
- package/evidence/wcag22-srgb8-q55-v1.bin +0 -0
- package/evidence/wcag22-srgb8-v1.json +1 -0
- package/index.d.ts +211 -37
- package/index.js +499 -21
- package/package.json +40 -36
- package/pkg/labcolors.d.ts +230 -249
- package/pkg/labcolors.js +955 -157
- package/pkg/labcolors_bg.wasm +0 -0
- package/pkg/labcolors_bg.wasm.d.ts +61 -11
- package/pkg/snippets/labcolors-wasm-9fb8b927594c3d6f/inline0.js +98 -0
- package/program-wire/abi-v1.d.ts +84 -0
- package/program-wire/abi-v1.js +332 -0
- package/program-wire/abi-v2.d.ts +17 -0
- package/program-wire/abi-v2.js +61 -0
- package/program-wire/encoding.js +218 -0
- package/wcag22.d.ts +6 -0
- package/adapt-theme.d.ts +0 -74
- package/adapt-theme.js +0 -542
- package/apply-theme.d.ts +0 -16
- package/apply-theme.js +0 -44
- package/effective-bg.d.ts +0 -50
- package/effective-bg.js +0 -492
- package/watch-theme.d.ts +0 -57
- package/watch-theme.js +0 -144
package/adapt-theme.js
DELETED
|
@@ -1,542 +0,0 @@
|
|
|
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
|
-
}
|
package/apply-theme.d.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { ResolvedTheme } from "./pkg/labcolors.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Apply a resolved theme's CSS variables to an element.
|
|
5
|
-
*
|
|
6
|
-
* Writes every reachable role from `result.vars` onto `element.style` via
|
|
7
|
-
* `setProperty`. Unreachable and zero-token roles are absent from `vars` and
|
|
8
|
-
* are not written, so the caller's CSS fallbacks stay in effect for them.
|
|
9
|
-
*
|
|
10
|
-
* @param element The target element (e.g. `document.documentElement`).
|
|
11
|
-
* @param result A `LabColors.resolveTheme(...)` result.
|
|
12
|
-
*/
|
|
13
|
-
export declare function applyTheme(
|
|
14
|
-
element: HTMLElement,
|
|
15
|
-
result: Pick<ResolvedTheme, "vars">,
|
|
16
|
-
): void;
|
package/apply-theme.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
// Vanilla DOM helper — zero dependencies.
|
|
2
|
-
//
|
|
3
|
-
// The WASM core returns data and never touches the DOM (that separation is
|
|
4
|
-
// deliberate; full reactive injection is the css-injection-runtime chapter).
|
|
5
|
-
// This helper is the minimal, framework-free bridge: write a resolved theme's
|
|
6
|
-
// reachable colours onto an element as `--lab-*` custom properties.
|
|
7
|
-
|
|
8
|
-
const LAB_VAR_PREFIX = "--lab-";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Apply a resolved theme's CSS variables to an element.
|
|
12
|
-
*
|
|
13
|
-
* First clears every inline `--lab-*` custom property a previous call set on
|
|
14
|
-
* this element, then writes every reachable role from `result.vars` via
|
|
15
|
-
* `setProperty`. Unreachable and zero-token (`none`) roles carry no colour, so
|
|
16
|
-
* they are absent from `vars` and are not written — the caller's CSS fallbacks
|
|
17
|
-
* stay in effect for those, including across theme re-application (a role
|
|
18
|
-
* reachable in the previous theme but not in the new one does not linger).
|
|
19
|
-
*
|
|
20
|
-
* @param {HTMLElement} element - The target element (e.g. `document.documentElement`).
|
|
21
|
-
* @param {{ vars: Record<string, string> }} result - A `resolveTheme(...)` result.
|
|
22
|
-
* @returns {void}
|
|
23
|
-
*/
|
|
24
|
-
export function applyTheme(element, result) {
|
|
25
|
-
if (!element || typeof element.style?.setProperty !== "function") {
|
|
26
|
-
throw new TypeError("applyTheme: first argument must be an element with a style");
|
|
27
|
-
}
|
|
28
|
-
if (!result || typeof result.vars !== "object" || result.vars === null) {
|
|
29
|
-
throw new TypeError("applyTheme: second argument must be a resolveTheme result");
|
|
30
|
-
}
|
|
31
|
-
// Inline style is a live list; collect names first, then remove, so the
|
|
32
|
-
// iteration is not invalidated mid-walk.
|
|
33
|
-
const stale = [];
|
|
34
|
-
for (let i = 0; i < element.style.length; i++) {
|
|
35
|
-
const name = element.style.item(i);
|
|
36
|
-
if (name.startsWith(LAB_VAR_PREFIX)) stale.push(name);
|
|
37
|
-
}
|
|
38
|
-
for (const name of stale) {
|
|
39
|
-
element.style.removeProperty(name);
|
|
40
|
-
}
|
|
41
|
-
for (const [name, value] of Object.entries(result.vars)) {
|
|
42
|
-
element.style.setProperty(name, value);
|
|
43
|
-
}
|
|
44
|
-
}
|
package/effective-bg.d.ts
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
// Public types for the effective-background resolver.
|
|
2
|
-
|
|
3
|
-
/** `[r, g, b, a]` — r,g,b in 0..255, a in 0..1. */
|
|
4
|
-
export type Rgba = [number, number, number, number];
|
|
5
|
-
|
|
6
|
-
/** A computed-style-like accessor: only `getPropertyValue` is used. */
|
|
7
|
-
export interface StyleLike {
|
|
8
|
-
getPropertyValue(property: string): string;
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export interface EffectiveBackgroundOptions {
|
|
12
|
-
/** Base colour when the ancestor chain never reaches an opaque layer. Default `"#FFFFFF"`. */
|
|
13
|
-
fallback?: string;
|
|
14
|
-
/** Injection seam for the computed style of an element. Defaults to `getComputedStyle`. */
|
|
15
|
-
getStyle?: (element: unknown) => StyleLike;
|
|
16
|
-
/** Injection seam for an element's parent. Defaults to `el.parentElement`. */
|
|
17
|
-
parentOf?: (element: unknown) => unknown;
|
|
18
|
-
/** Guard against detached/cyclic chains. Default `64`. */
|
|
19
|
-
maxDepth?: number;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Parse a CSS colour string into `[r,g,b,a]`, or `null` if unrecognised. */
|
|
23
|
-
export declare function parseCssColor(css: string): Rgba | null;
|
|
24
|
-
|
|
25
|
-
/** Porter-Duff source-over composite of `top` onto `bottom`. */
|
|
26
|
-
export declare function compositeOver(top: Rgba, bottom: Rgba): Rgba;
|
|
27
|
-
|
|
28
|
-
/** `[r,g,b]` (0..255) → `#RRGGBB`. */
|
|
29
|
-
export declare function toHex(rgb: Rgba | [number, number, number]): string;
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Interpolate two colours in Oklab at `t ∈ [0,1]` → `#RRGGBB`. `from`/`to` may be
|
|
33
|
-
* any string `parseCssColor` accepts (`#hex`, `rgb()`/`rgba()`, `oklch()`,
|
|
34
|
-
* `transparent`), not only `#RRGGBB`. Perceptually uniform (even crossfade timing,
|
|
35
|
-
* non-muddy chroma path); endpoints are exact and out-of-gamut intermediates are
|
|
36
|
-
* clamped per channel.
|
|
37
|
-
*/
|
|
38
|
-
export declare function oklabLerp(from: string, to: string, t: number): string;
|
|
39
|
-
|
|
40
|
-
/** Composite an ordered front-to-back layer stack over an opaque base → `#RRGGBB`. */
|
|
41
|
-
export declare function compositeStackToHex(layersFrontToBack: Rgba[], opaqueBase: Rgba): string;
|
|
42
|
-
|
|
43
|
-
/**
|
|
44
|
-
* The opaque effective background `#RRGGBB` visible behind `element`'s content,
|
|
45
|
-
* by walking ancestors and alpha-compositing their `background-color`s.
|
|
46
|
-
*/
|
|
47
|
-
export declare function effectiveBackground(
|
|
48
|
-
element: unknown,
|
|
49
|
-
opts?: EffectiveBackgroundOptions,
|
|
50
|
-
): string;
|