@labpics/colors 0.10.0 → 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 +1 -1
- 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 +303 -333
- package/build-metadata.json +16 -12
- 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 +204 -63
- package/index.js +495 -17
- package/package.json +32 -34
- package/pkg/labcolors.d.ts +227 -491
- package/pkg/labcolors.js +943 -177
- package/pkg/labcolors_bg.wasm +0 -0
- package/pkg/labcolors_bg.wasm.d.ts +61 -12
- 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 -76
- package/adapt-theme.js +0 -738
- package/apply-theme.d.ts +0 -16
- package/apply-theme.js +0 -45
- package/effective-bg.d.ts +0 -51
- package/effective-bg.js +0 -501
- package/watch-theme.d.ts +0 -57
- package/watch-theme.js +0 -144
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,45 +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, zero-token (`none`), and stable
|
|
16
|
-
* `glow-indeterminate` roles carry no selected CSS value, so they are absent
|
|
17
|
-
* from `vars` and are not written — the caller's CSS fallbacks stay in effect
|
|
18
|
-
* for those, including across theme re-application (a role reachable in the
|
|
19
|
-
* previous theme but not in the new one does not linger).
|
|
20
|
-
*
|
|
21
|
-
* @param {HTMLElement} element - The target element (e.g. `document.documentElement`).
|
|
22
|
-
* @param {{ vars: Record<string, string> }} result - A `resolveTheme(...)` result.
|
|
23
|
-
* @returns {void}
|
|
24
|
-
*/
|
|
25
|
-
export function applyTheme(element, result) {
|
|
26
|
-
if (!element || typeof element.style?.setProperty !== "function") {
|
|
27
|
-
throw new TypeError("applyTheme: first argument must be an element with a style");
|
|
28
|
-
}
|
|
29
|
-
if (!result || typeof result.vars !== "object" || result.vars === null) {
|
|
30
|
-
throw new TypeError("applyTheme: second argument must be a resolveTheme result");
|
|
31
|
-
}
|
|
32
|
-
// Inline style is a live list; collect names first, then remove, so the
|
|
33
|
-
// iteration is not invalidated mid-walk.
|
|
34
|
-
const stale = [];
|
|
35
|
-
for (let i = 0; i < element.style.length; i++) {
|
|
36
|
-
const name = element.style.item(i);
|
|
37
|
-
if (name.startsWith(LAB_VAR_PREFIX)) stale.push(name);
|
|
38
|
-
}
|
|
39
|
-
for (const name of stale) {
|
|
40
|
-
element.style.removeProperty(name);
|
|
41
|
-
}
|
|
42
|
-
for (const [name, value] of Object.entries(result.vars)) {
|
|
43
|
-
element.style.setProperty(name, value);
|
|
44
|
-
}
|
|
45
|
-
}
|
package/effective-bg.d.ts
DELETED
|
@@ -1,51 +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
|
-
* Legacy opaque reference-background estimate for the supported
|
|
45
|
-
* `background-color` subset. This is not a browser pixel observation; use an
|
|
46
|
-
* explicit sampled background when correctness depends on unsupported layers.
|
|
47
|
-
*/
|
|
48
|
-
export declare function effectiveBackground(
|
|
49
|
-
element: unknown,
|
|
50
|
-
opts?: EffectiveBackgroundOptions,
|
|
51
|
-
): string;
|
package/effective-bg.js
DELETED
|
@@ -1,501 +0,0 @@
|
|
|
1
|
-
// Effective background resolution — zero dependencies.
|
|
2
|
-
//
|
|
3
|
-
// `labcolors` resolves roles against a *solid* background. A real UI surface is
|
|
4
|
-
// often translucent (a panel at `rgba(…, .8)` over its parents) or has no
|
|
5
|
-
// background of its own (inheriting whatever is behind it). To resolve such a
|
|
6
|
-
// surface you need a background observation. This legacy helper produces a
|
|
7
|
-
// reference estimate for the subset it understands; it is not a browser pixel
|
|
8
|
-
// capture or a claim about what a viewer actually sees.
|
|
9
|
-
//
|
|
10
|
-
// This module computes it by walking the ancestor chain and **alpha-compositing**
|
|
11
|
-
// each element's `background-color` (front-to-back) until the stack is opaque,
|
|
12
|
-
// over an opaque fallback (white by default), yielding one solid reference hex
|
|
13
|
-
// the WASM core can consume.
|
|
14
|
-
//
|
|
15
|
-
// HONEST LIMIT: this composites solid/translucent `background-color` layers only.
|
|
16
|
-
// It does NOT sample `background-image`s, gradients, blurred backdrops, video, or
|
|
17
|
-
// content showing through — those have no single colour to read from computed
|
|
18
|
-
// style. For those, the caller supplies the effective background explicitly (the
|
|
19
|
-
// `background` option of `watchTheme`, or a sampled average). What it does cover —
|
|
20
|
-
// translucent panels over solid parents — is the common case and is composited
|
|
21
|
-
// *correctly* (true source-over alpha), not approximated.
|
|
22
|
-
//
|
|
23
|
-
// COLOUR FORMS: `parseCssColor` reads the forms this package actually meets —
|
|
24
|
-
// `#hex`, `rgb()/rgba()` (legacy comma and modern space/slash), `transparent`,
|
|
25
|
-
// and `oklch()` (the engine's OWN emission form since 0.4.0, and what a browser
|
|
26
|
-
// serialises `background-color` back to for an oklch-painted surface). Other
|
|
27
|
-
// modern forms — `lab()`, `lch()`, `color(srgb …)`, `color-mix()`, `hsl()`,
|
|
28
|
-
// named colours beyond `transparent` — are NOT parsed and currently become a
|
|
29
|
-
// dropped layer for compatibility. That is not safe evidence: pass the
|
|
30
|
-
// background explicitly. Issue #283 owns the typed `Unknown` replacement for
|
|
31
|
-
// unsupported syntax, missing opaque bases and incomplete traversal.
|
|
32
|
-
|
|
33
|
-
/** @typedef {[number, number, number, number]} Rgba r,g,b in 0..255, a in 0..1 */
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* Parse a CSS colour string into `[r, g, b, a]`, or `null` if unrecognised.
|
|
37
|
-
*
|
|
38
|
-
* Handles the forms computed style actually yields:
|
|
39
|
-
* - `rgb(r, g, b)` / `rgba(r, g, b, a)` and the modern `rgb(r g b / a)`;
|
|
40
|
-
* - `#rgb` / `#rgba` / `#rrggbb` / `#rrggbbaa`;
|
|
41
|
-
* - the `transparent` keyword;
|
|
42
|
-
* - `oklch(L C H)` / `oklch(L C H / A)` — the engine's own emission form and
|
|
43
|
-
* what a browser serialises an oklch-painted `background-color` back to.
|
|
44
|
-
* `L` accepts both a `0..1` number (Chrome's computed form) and a percentage
|
|
45
|
-
* (the engine's literal form); `C` a number or a `%` (100% = 0.4 per CSS
|
|
46
|
-
* Color 4); `H` degrees (bare or `deg`-suffixed); a missing component
|
|
47
|
-
* (`none`) is 0. Conversion to sRGB bytes reuses the file's Oklab↔sRGB
|
|
48
|
-
* transform and is byte-exact to the core's round-trip proof.
|
|
49
|
-
*
|
|
50
|
-
* Any other form — `lab()`, `lch()`, `color(srgb …)`, `color-mix()`, `hsl()`,
|
|
51
|
-
* named colours other than `transparent` — returns `null` (treated as "no
|
|
52
|
-
* layer"); supply such backgrounds explicitly via the `background` option.
|
|
53
|
-
*
|
|
54
|
-
* @param {string} css
|
|
55
|
-
* @returns {Rgba | null}
|
|
56
|
-
*/
|
|
57
|
-
export function parseCssColor(css) {
|
|
58
|
-
if (typeof css !== "string") return null;
|
|
59
|
-
const s = css.trim().toLowerCase();
|
|
60
|
-
if (s === "transparent") return [0, 0, 0, 0];
|
|
61
|
-
|
|
62
|
-
if (s.startsWith("oklch(") && s.endsWith(")")) return parseOklch(s.slice(6, -1));
|
|
63
|
-
|
|
64
|
-
if (s[0] === "#") {
|
|
65
|
-
const h = s.slice(1);
|
|
66
|
-
if (h.length === 3 || h.length === 4) {
|
|
67
|
-
const r = parseInt(h[0] + h[0], 16);
|
|
68
|
-
const g = parseInt(h[1] + h[1], 16);
|
|
69
|
-
const b = parseInt(h[2] + h[2], 16);
|
|
70
|
-
const a = h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1;
|
|
71
|
-
return [r, g, b, a].some(Number.isNaN) ? null : [r, g, b, a];
|
|
72
|
-
}
|
|
73
|
-
if (h.length === 6 || h.length === 8) {
|
|
74
|
-
const r = parseInt(h.slice(0, 2), 16);
|
|
75
|
-
const g = parseInt(h.slice(2, 4), 16);
|
|
76
|
-
const b = parseInt(h.slice(4, 6), 16);
|
|
77
|
-
const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
|
|
78
|
-
return [r, g, b, a].some(Number.isNaN) ? null : [r, g, b, a];
|
|
79
|
-
}
|
|
80
|
-
return null;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
const m = s.match(/^rgba?\(([^)]+)\)$/);
|
|
84
|
-
if (!m) return null;
|
|
85
|
-
// Split on commas or whitespace and an optional "/" alpha separator.
|
|
86
|
-
const parts = m[1].split(/[,\s/]+/).filter((p) => p.length > 0);
|
|
87
|
-
if (parts.length < 3) return null;
|
|
88
|
-
const chan = (p) => (p.endsWith("%") ? (parseFloat(p) / 100) * 255 : parseFloat(p));
|
|
89
|
-
const r = chan(parts[0]);
|
|
90
|
-
const g = chan(parts[1]);
|
|
91
|
-
const b = chan(parts[2]);
|
|
92
|
-
const a = parts.length >= 4 ? (parts[3].endsWith("%") ? parseFloat(parts[3]) / 100 : parseFloat(parts[3])) : 1;
|
|
93
|
-
if ([r, g, b, a].some((v) => Number.isNaN(v))) return null;
|
|
94
|
-
return [clamp255(r), clamp255(g), clamp255(b), Math.min(1, Math.max(0, a))];
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
function clamp255(v) {
|
|
98
|
-
return Math.min(255, Math.max(0, v));
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/**
|
|
102
|
-
* Parse the inside of an `oklch(...)` (the part between the parens) into sRGB
|
|
103
|
-
* `[r, g, b, a]`, or `null` on any malformed component.
|
|
104
|
-
*
|
|
105
|
-
* The engine emits `oklch(L% C H)` / `oklch(L% C H / A)`; a browser's computed
|
|
106
|
-
* form is `oklch(<L 0..1> C H [/ A])`. Components are whitespace-separated with
|
|
107
|
-
* an optional `/`-separated alpha, exactly like `rgb()`'s modern syntax.
|
|
108
|
-
* oklch → Oklab is `a = C·cos(H)`, `b = C·sin(H)`; then the file's own
|
|
109
|
-
* `oklabToLinearRgb` + `linearToSrgb` land it in sRGB — the SAME transform (and
|
|
110
|
-
* the SAME clamp-then-round the core uses in `hex_from_srgb`) that carries the
|
|
111
|
-
* emitter's byte-exact round-trip, so an emitted string decodes to its source
|
|
112
|
-
* bytes. Out-of-gamut channels clamp per channel, matching `oklabLerp`/`toHex`.
|
|
113
|
-
*
|
|
114
|
-
* @param {string} inner the text between `oklch(` and `)`
|
|
115
|
-
* @returns {Rgba | null}
|
|
116
|
-
*/
|
|
117
|
-
function parseOklch(inner) {
|
|
118
|
-
const slash = inner.indexOf("/");
|
|
119
|
-
const lch = (slash >= 0 ? inner.slice(0, slash) : inner).trim();
|
|
120
|
-
const alphaTok = slash >= 0 ? inner.slice(slash + 1).trim() : null;
|
|
121
|
-
const comps = lch.split(/\s+/).filter((p) => p.length > 0);
|
|
122
|
-
if (comps.length !== 3) return null;
|
|
123
|
-
|
|
124
|
-
const L = oklchLightness(comps[0]);
|
|
125
|
-
const C = oklchChroma(comps[1]);
|
|
126
|
-
const H = oklchHue(comps[2]);
|
|
127
|
-
const a = alphaTok === null ? 1 : oklchAlpha(alphaTok);
|
|
128
|
-
if (L === null || C === null || H === null || a === null) return null;
|
|
129
|
-
|
|
130
|
-
const hRad = (H * Math.PI) / 180;
|
|
131
|
-
const lin = oklabToLinearRgb(L, C * Math.cos(hRad), C * Math.sin(hRad));
|
|
132
|
-
const byte = (i) => Math.round(clamp255(linearToSrgb(lin[i]) * 255));
|
|
133
|
-
return [byte(0), byte(1), byte(2), a];
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Strict CSS `<number>` (no trailing junk, unlike `parseFloat`), else `null`. */
|
|
137
|
-
function cssNumber(tok) {
|
|
138
|
-
return /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i.test(tok) ? parseFloat(tok) : null;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
/** L: a percentage → `/100` into `0..1`; a bare number is already `0..1`; `none`
|
|
142
|
-
* → 0. Lightness clamps to `[0, 1]` (CSS Color 4) — a byte-level clamp alone
|
|
143
|
-
* masks out-of-range L only at low chroma, not high, so clamp L explicitly. */
|
|
144
|
-
function oklchLightness(tok) {
|
|
145
|
-
if (tok === "none") return 0;
|
|
146
|
-
const pct = tok.endsWith("%");
|
|
147
|
-
const n = cssNumber(pct ? tok.slice(0, -1) : tok);
|
|
148
|
-
if (n === null) return null;
|
|
149
|
-
return Math.min(1, Math.max(0, pct ? n / 100 : n));
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** C: a bare number is absolute chroma; a percentage is a fraction of 0.4
|
|
153
|
-
* (CSS Color 4: 100% = 0.4); `none` → 0. Negative chroma clamps to 0. */
|
|
154
|
-
function oklchChroma(tok) {
|
|
155
|
-
if (tok === "none") return 0;
|
|
156
|
-
const pct = tok.endsWith("%");
|
|
157
|
-
const n = cssNumber(pct ? tok.slice(0, -1) : tok);
|
|
158
|
-
if (n === null) return null;
|
|
159
|
-
return Math.max(0, pct ? (n / 100) * 0.4 : n);
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/** H: degrees, bare or `deg`-suffixed; `none` → 0. (grad/rad/turn are out of
|
|
163
|
-
* scope — the engine and browsers emit bare degrees.) */
|
|
164
|
-
function oklchHue(tok) {
|
|
165
|
-
if (tok === "none") return 0;
|
|
166
|
-
return cssNumber(tok.endsWith("deg") ? tok.slice(0, -3) : tok);
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/** Alpha: a number `0..1` or a percentage; `none` → 0; clamped to `[0, 1]`. */
|
|
170
|
-
function oklchAlpha(tok) {
|
|
171
|
-
if (tok === "none") return 0;
|
|
172
|
-
const pct = tok.endsWith("%");
|
|
173
|
-
const n = cssNumber(pct ? tok.slice(0, -1) : tok);
|
|
174
|
-
if (n === null) return null;
|
|
175
|
-
return Math.min(1, Math.max(0, pct ? n / 100 : n));
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
/**
|
|
179
|
-
* Source-over composite of `top` onto `bottom` (Porter-Duff "over").
|
|
180
|
-
*
|
|
181
|
-
* @param {Rgba} top
|
|
182
|
-
* @param {Rgba} bottom
|
|
183
|
-
* @returns {Rgba}
|
|
184
|
-
*/
|
|
185
|
-
export function compositeOver(top, bottom) {
|
|
186
|
-
const at = top[3];
|
|
187
|
-
const ab = bottom[3];
|
|
188
|
-
// Affine-форма математически равна expanded source-over и фиксирует
|
|
189
|
-
// объявленный byte-scale binary64 operation order. Это numerical profile,
|
|
190
|
-
// не утверждение глобальной монотонности: округление может менять локальный
|
|
191
|
-
// порядок соседних значений, а legacy WCAG EOTF дополнительно имеет seam.
|
|
192
|
-
const a = ab + at * (1 - ab);
|
|
193
|
-
if (a === 0) return [0, 0, 0, 0];
|
|
194
|
-
const c = (i) => {
|
|
195
|
-
const bottomPremultiplied = bottom[i] * ab;
|
|
196
|
-
return (bottomPremultiplied + at * (top[i] - bottomPremultiplied)) / a;
|
|
197
|
-
};
|
|
198
|
-
return [c(0), c(1), c(2), a];
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
/**
|
|
202
|
-
* `[r, g, b]` (0..255) → `#RRGGBB`, channels rounded and clamped.
|
|
203
|
-
*
|
|
204
|
-
* @param {Rgba | [number, number, number]} rgb
|
|
205
|
-
* @returns {string}
|
|
206
|
-
*/
|
|
207
|
-
export function toHex(rgb) {
|
|
208
|
-
// Coerce non-finite channels (NaN/±Infinity, e.g. from a malformed `Rgba`
|
|
209
|
-
// passed by a caller) to 0, so a bad input yields a valid `#RRGGBB` rather
|
|
210
|
-
// than an invalid CSS string like `"#NAN0000"`.
|
|
211
|
-
const h = (v) => {
|
|
212
|
-
const n = Math.round(clamp255(Number.isFinite(v) ? v : 0));
|
|
213
|
-
return n.toString(16).padStart(2, "0");
|
|
214
|
-
};
|
|
215
|
-
return `#${h(rgb[0])}${h(rgb[1])}${h(rgb[2])}`.toUpperCase();
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
// --- Perceptual interpolation (Oklab) -------------------------------------
|
|
219
|
-
//
|
|
220
|
-
// A crossfade should feel even: equal progress should be equal *perceived*
|
|
221
|
-
// change. A straight sRGB-channel blend is not that — it lingers in the brighter
|
|
222
|
-
// half (black→white at t=0.5 is #808080, but the perceived midpoint grey is
|
|
223
|
-
// ~#606060). Interpolating in Oklab — a perceptually-uniform space — fixes the
|
|
224
|
-
// timing and, for chromatic endpoints, avoids the muddy desaturated midpoint a
|
|
225
|
-
// raw RGB blend produces. Björn Ottosson's sRGB↔Oklab transform, self-contained.
|
|
226
|
-
|
|
227
|
-
/** sRGB gamma transfer (IEC 61966-2-1): encoded channel 0..1 → linear 0..1. */
|
|
228
|
-
function srgbToLinear(c) {
|
|
229
|
-
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
/** Inverse sRGB transfer: linear 0..1 → encoded 0..1. */
|
|
233
|
-
function linearToSrgb(c) {
|
|
234
|
-
return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** Linear-light sRGB `[r,g,b]` (0..1) → Oklab `[L, a, b]`. */
|
|
238
|
-
function linearRgbToOklab(r, g, b) {
|
|
239
|
-
const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;
|
|
240
|
-
const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;
|
|
241
|
-
const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;
|
|
242
|
-
const l_ = Math.cbrt(l);
|
|
243
|
-
const m_ = Math.cbrt(m);
|
|
244
|
-
const s_ = Math.cbrt(s);
|
|
245
|
-
return [
|
|
246
|
-
0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,
|
|
247
|
-
1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,
|
|
248
|
-
0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,
|
|
249
|
-
];
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/** Oklab `[L, a, b]` → linear-light sRGB `[r,g,b]` (0..1, may be out of gamut). */
|
|
253
|
-
function oklabToLinearRgb(L, A, B) {
|
|
254
|
-
const l_ = L + 0.3963377774 * A + 0.2158037573 * B;
|
|
255
|
-
const m_ = L - 0.1055613458 * A - 0.0638541728 * B;
|
|
256
|
-
const s_ = L - 0.0894841775 * A - 1.291485548 * B;
|
|
257
|
-
const l = l_ * l_ * l_;
|
|
258
|
-
const m = m_ * m_ * m_;
|
|
259
|
-
const s = s_ * s_ * s_;
|
|
260
|
-
return [
|
|
261
|
-
4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
|
|
262
|
-
-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
|
|
263
|
-
-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,
|
|
264
|
-
];
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/**
|
|
268
|
-
* Interpolate two colours in Oklab at `t ∈ [0,1]`, returning `#RRGGBB`.
|
|
269
|
-
*
|
|
270
|
-
* `from`/`to` may be ANY string `parseCssColor` accepts (`#rgb`/`#rrggbb`,
|
|
271
|
-
* `rgb()`/`rgba()`, `oklch()`, `transparent`) — not only `#RRGGBB`. Perceptually
|
|
272
|
-
* uniform: equal steps in `t` are equal steps in perceived lightness (and a
|
|
273
|
-
* straight, non-muddy path in hue/chroma), so a crossfade feels even rather than
|
|
274
|
-
* lingering bright. Endpoints are returned exactly (`t ≤ 0` → `from`, `t ≥ 1` →
|
|
275
|
-
* `to`), always normalised to `#RRGGBB` through `toHex`; out-of-gamut
|
|
276
|
-
* intermediates are clamped per channel. Unparseable input falls back to the
|
|
277
|
-
* nearer parseable endpoint.
|
|
278
|
-
*
|
|
279
|
-
* @param {string} from any colour string `parseCssColor` accepts
|
|
280
|
-
* @param {string} to any colour string `parseCssColor` accepts
|
|
281
|
-
* @param {number} t
|
|
282
|
-
* @returns {string} a `#RRGGBB` string
|
|
283
|
-
*/
|
|
284
|
-
export function oklabLerp(from, to, t) {
|
|
285
|
-
const a = parseCssColor(from);
|
|
286
|
-
const b = parseCssColor(to);
|
|
287
|
-
if (!a || !b) return (b && t >= 0.5) || !a ? (b ? toHex(b) : "#000000") : toHex(a);
|
|
288
|
-
if (t <= 0) return toHex(a);
|
|
289
|
-
if (t >= 1) return toHex(b);
|
|
290
|
-
const la = linearRgbToOklab(srgbToLinear(a[0] / 255), srgbToLinear(a[1] / 255), srgbToLinear(a[2] / 255));
|
|
291
|
-
const lb = linearRgbToOklab(srgbToLinear(b[0] / 255), srgbToLinear(b[1] / 255), srgbToLinear(b[2] / 255));
|
|
292
|
-
const lin = oklabToLinearRgb(
|
|
293
|
-
la[0] + (lb[0] - la[0]) * t,
|
|
294
|
-
la[1] + (lb[1] - la[1]) * t,
|
|
295
|
-
la[2] + (lb[2] - la[2]) * t,
|
|
296
|
-
);
|
|
297
|
-
return toHex([linearToSrgb(lin[0]) * 255, linearToSrgb(lin[1]) * 255, linearToSrgb(lin[2]) * 255]);
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
// --- Compiled hot-path forms (package-internal) -----------------------------
|
|
301
|
-
//
|
|
302
|
-
// `adaptTheme` interpolates the SAME from/to pair on every frame of an ease,
|
|
303
|
-
// and strict mode re-derives WCAG luminance from the interpolated colour up to
|
|
304
|
-
// 14× per floored role per frame (`floorBlend`'s bisection). Doing that
|
|
305
|
-
// through the string API means re-parsing both endpoints and round-tripping
|
|
306
|
-
// through `#RRGGBB` text on every call — measured at ~85-90% of the ease-frame
|
|
307
|
-
// budget (bench/hotpath.bench.mjs). These helpers compile a pair once and then
|
|
308
|
-
// produce results BYTE-IDENTICAL to their string-path equivalents:
|
|
309
|
-
//
|
|
310
|
-
// · `lerpPairHex(pair, t)` ≡ `oklabLerp(from, to, t)`
|
|
311
|
-
// · `lerpPairLuminance(pair, t)` ≡ WCAG luminance of `oklabLerp(from, to, t)`
|
|
312
|
-
// · `wcagLuminanceCached(css)` ≡ luminance of `parseCssColor(css) ?? black`
|
|
313
|
-
//
|
|
314
|
-
// (locked by test/hotpath-parity.test.mjs on randomised inputs). They are
|
|
315
|
-
// consumed by `adapt-theme.js` and are NOT part of the public package surface
|
|
316
|
-
// (`index.js` does not re-export them).
|
|
317
|
-
|
|
318
|
-
const PARSE_CACHE_CAP = 256;
|
|
319
|
-
const parseCache = new Map();
|
|
320
|
-
|
|
321
|
-
/** `parseCssColor` behind a small bounded memo, for per-frame callers feeding
|
|
322
|
-
* it recurring strings (computed-style values, backdrop samples, ease
|
|
323
|
-
* endpoints). The cap is a blunt bound, not an LRU: a full cache is simply
|
|
324
|
-
* cleared and refills within a frame — cheaper than eviction bookkeeping for
|
|
325
|
-
* a working set that is a handful of strings. The cached arrays are SHARED —
|
|
326
|
-
* package-internal callers must treat them as immutable. (The public
|
|
327
|
-
* `parseCssColor` stays unmemoized and returns a fresh array per call.) */
|
|
328
|
-
export function parseCssColorCached(css) {
|
|
329
|
-
let hit = parseCache.get(css);
|
|
330
|
-
if (hit === undefined) {
|
|
331
|
-
hit = parseCssColor(css);
|
|
332
|
-
if (parseCache.size >= PARSE_CACHE_CAP) parseCache.clear();
|
|
333
|
-
parseCache.set(css, hit);
|
|
334
|
-
}
|
|
335
|
-
return hit;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
/** Relative luminance of r,g,b channels (0..255) in the frozen original WCAG
|
|
339
|
-
* 2.1 (2018) profile: 0.03928 / 12.92 / 2.4, matching `adapt-theme`. */
|
|
340
|
-
function wcagLumChannels(r, g, b) {
|
|
341
|
-
const lin = (c) => {
|
|
342
|
-
const s = c / 255;
|
|
343
|
-
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
|
344
|
-
};
|
|
345
|
-
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
const LUM_CACHE_CAP = 256;
|
|
349
|
-
const lumCache = new Map();
|
|
350
|
-
|
|
351
|
-
/** WCAG relative luminance of any colour string, memoised. Byte-equal to the
|
|
352
|
-
* string path `adapt-theme` used per sample per frame: luminance of
|
|
353
|
-
* `parseCssColor(css) ?? [0,0,0,1]` — i.e. unparseable input yields the
|
|
354
|
-
* luminance of black, preserving the historical fallback. */
|
|
355
|
-
export function wcagLuminanceCached(css) {
|
|
356
|
-
let lum = lumCache.get(css);
|
|
357
|
-
if (lum === undefined) {
|
|
358
|
-
const c = parseCssColorCached(css) ?? [0, 0, 0, 1];
|
|
359
|
-
lum = wcagLumChannels(c[0], c[1], c[2]);
|
|
360
|
-
if (lumCache.size >= LUM_CACHE_CAP) lumCache.clear();
|
|
361
|
-
lumCache.set(css, lum);
|
|
362
|
-
}
|
|
363
|
-
return lum;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
/** Round a channel to the exact byte `toHex` would emit (non-finite → 0,
|
|
367
|
-
* clamp, round) — keeps the numeric luminance path quantisation-identical to
|
|
368
|
-
* the `#RRGGBB` round-trip it replaces. */
|
|
369
|
-
function hexByte(v) {
|
|
370
|
-
return Math.round(clamp255(Number.isFinite(v) ? v : 0));
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
/**
|
|
374
|
-
* Compile a from/to colour pair for repeated interpolation. Returns `null`
|
|
375
|
-
* when either endpoint fails to parse — callers fall back to `oklabLerp`,
|
|
376
|
-
* which owns the unparseable-endpoint fallback semantics. The pair carries
|
|
377
|
-
* both endpoints' Oklab coordinates plus their exact `toHex` forms, so the
|
|
378
|
-
* per-frame work is one Oklab lerp + gamut map — no string parsing at all.
|
|
379
|
-
*
|
|
380
|
-
* @param {string} from any colour string `parseCssColor` accepts
|
|
381
|
-
* @param {string} to any colour string `parseCssColor` accepts
|
|
382
|
-
* @returns {{la:number[],lb:number[],aHex:string,bHex:string,aBytes:number[],bBytes:number[]} | null}
|
|
383
|
-
*/
|
|
384
|
-
export function compileLerpPair(from, to) {
|
|
385
|
-
const a = parseCssColorCached(from);
|
|
386
|
-
const b = parseCssColorCached(to);
|
|
387
|
-
if (!a || !b) return null;
|
|
388
|
-
return {
|
|
389
|
-
la: linearRgbToOklab(srgbToLinear(a[0] / 255), srgbToLinear(a[1] / 255), srgbToLinear(a[2] / 255)),
|
|
390
|
-
lb: linearRgbToOklab(srgbToLinear(b[0] / 255), srgbToLinear(b[1] / 255), srgbToLinear(b[2] / 255)),
|
|
391
|
-
aHex: toHex(a),
|
|
392
|
-
bHex: toHex(b),
|
|
393
|
-
aBytes: [hexByte(a[0]), hexByte(a[1]), hexByte(a[2])],
|
|
394
|
-
bBytes: [hexByte(b[0]), hexByte(b[1]), hexByte(b[2])],
|
|
395
|
-
};
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
/** Byte-identical to `oklabLerp(from, to, t)` for the pair's endpoints — the
|
|
399
|
-
* same double-precision Oklab lerp on the same parsed channels, minus the
|
|
400
|
-
* per-call re-parse. */
|
|
401
|
-
export function lerpPairHex(pair, t) {
|
|
402
|
-
if (t <= 0) return pair.aHex;
|
|
403
|
-
if (t >= 1) return pair.bHex;
|
|
404
|
-
const la = pair.la;
|
|
405
|
-
const lb = pair.lb;
|
|
406
|
-
const lin = oklabToLinearRgb(
|
|
407
|
-
la[0] + (lb[0] - la[0]) * t,
|
|
408
|
-
la[1] + (lb[1] - la[1]) * t,
|
|
409
|
-
la[2] + (lb[2] - la[2]) * t,
|
|
410
|
-
);
|
|
411
|
-
return toHex([linearToSrgb(lin[0]) * 255, linearToSrgb(lin[1]) * 255, linearToSrgb(lin[2]) * 255]);
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
/** Relative luminance of `lerpPairHex(pair, t)` in the frozen legacy WCAG 2.1
|
|
415
|
-
* (2018) profile, WITHOUT the `#RRGGBB` round-trip: channels are quantised to
|
|
416
|
-
* the exact bytes `toHex` would emit, then fed to the same profile formula.
|
|
417
|
-
* This preserves value parity; it does not prove bisection monotonicity. */
|
|
418
|
-
export function lerpPairLuminance(pair, t) {
|
|
419
|
-
if (t <= 0) return wcagLumChannels(pair.aBytes[0], pair.aBytes[1], pair.aBytes[2]);
|
|
420
|
-
if (t >= 1) return wcagLumChannels(pair.bBytes[0], pair.bBytes[1], pair.bBytes[2]);
|
|
421
|
-
const la = pair.la;
|
|
422
|
-
const lb = pair.lb;
|
|
423
|
-
const lin = oklabToLinearRgb(
|
|
424
|
-
la[0] + (lb[0] - la[0]) * t,
|
|
425
|
-
la[1] + (lb[1] - la[1]) * t,
|
|
426
|
-
la[2] + (lb[2] - la[2]) * t,
|
|
427
|
-
);
|
|
428
|
-
return wcagLumChannels(
|
|
429
|
-
hexByte(linearToSrgb(lin[0]) * 255),
|
|
430
|
-
hexByte(linearToSrgb(lin[1]) * 255),
|
|
431
|
-
hexByte(linearToSrgb(lin[2]) * 255),
|
|
432
|
-
);
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/**
|
|
436
|
-
* Compose an ordered stack of colour layers (front-to-back) over an opaque base
|
|
437
|
-
* into a single opaque `#RRGGBB`. Pure — no DOM. Exposed for testing and for
|
|
438
|
-
* callers that sample their own layers.
|
|
439
|
-
*
|
|
440
|
-
* @param {Rgba[]} layersFrontToBack index 0 is the topmost layer
|
|
441
|
-
* @param {Rgba} opaqueBase must have alpha 1
|
|
442
|
-
* @returns {string}
|
|
443
|
-
*/
|
|
444
|
-
export function compositeStackToHex(layersFrontToBack, opaqueBase) {
|
|
445
|
-
let result = opaqueBase;
|
|
446
|
-
// Apply from the back (closest to base) forward, so index 0 lands on top.
|
|
447
|
-
for (let i = layersFrontToBack.length - 1; i >= 0; i--) {
|
|
448
|
-
result = compositeOver(layersFrontToBack[i], result);
|
|
449
|
-
}
|
|
450
|
-
return toHex(result);
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
/**
|
|
454
|
-
* Legacy opaque reference-background estimate for the supported
|
|
455
|
-
* `background-color` subset. This is not a browser pixel observation.
|
|
456
|
-
*
|
|
457
|
-
* Walks from `element` upward, collecting each `background-color` layer, and
|
|
458
|
-
* stops at the first fully-opaque layer (which becomes the base). If the chain
|
|
459
|
-
* reaches the root without an opaque layer, `fallback` (default white) is used
|
|
460
|
-
* as an explicit compatibility assumption; it is not evidence of the canvas.
|
|
461
|
-
*
|
|
462
|
-
* Pure and injectable: pass `getStyle` and `parentOf` to test without a DOM; in
|
|
463
|
-
* the browser they default to `getComputedStyle` and `el.parentElement`.
|
|
464
|
-
*
|
|
465
|
-
* @param {*} element
|
|
466
|
-
* @param {object} [opts]
|
|
467
|
-
* @param {string} [opts.fallback="#FFFFFF"] base when the chain is fully translucent
|
|
468
|
-
* @param {(el: *) => { getPropertyValue: (p: string) => string }} [opts.getStyle]
|
|
469
|
-
* @param {(el: *) => *} [opts.parentOf]
|
|
470
|
-
* @param {number} [opts.maxDepth=64] guard against detached/cyclic chains
|
|
471
|
-
* @returns {string}
|
|
472
|
-
*/
|
|
473
|
-
export function effectiveBackground(element, opts = {}) {
|
|
474
|
-
const fallback = opts.fallback ?? "#FFFFFF";
|
|
475
|
-
const getStyle =
|
|
476
|
-
opts.getStyle ?? ((el) => (typeof getComputedStyle === "function" ? getComputedStyle(el) : { getPropertyValue: () => "" }));
|
|
477
|
-
const parentOf = opts.parentOf ?? ((el) => el.parentElement);
|
|
478
|
-
const maxDepth = opts.maxDepth ?? 64;
|
|
479
|
-
|
|
480
|
-
/** @type {Rgba[]} */
|
|
481
|
-
const layers = [];
|
|
482
|
-
let el = element;
|
|
483
|
-
let depth = 0;
|
|
484
|
-
let base = parseCssColor(fallback) ?? [255, 255, 255, 1];
|
|
485
|
-
|
|
486
|
-
while (el && depth < maxDepth) {
|
|
487
|
-
const css = getStyle(el).getPropertyValue("background-color");
|
|
488
|
-
const c = parseCssColor(css);
|
|
489
|
-
if (c && c[3] > 0) {
|
|
490
|
-
if (c[3] >= 1) {
|
|
491
|
-
base = c; // first opaque layer is the base; nothing behind it shows
|
|
492
|
-
break;
|
|
493
|
-
}
|
|
494
|
-
layers.push(c);
|
|
495
|
-
}
|
|
496
|
-
el = parentOf(el);
|
|
497
|
-
depth++;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
return compositeStackToHex(layers, base);
|
|
501
|
-
}
|
package/watch-theme.d.ts
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
// Public types for the reactive theme runtime.
|
|
2
|
-
|
|
3
|
-
import type { LabColors, ResolvedTheme, ThemeName } from "./pkg/labcolors.js";
|
|
4
|
-
|
|
5
|
-
export interface WatchThemeOptions {
|
|
6
|
-
/** An initialised `LabColors` engine (after `await init()`). */
|
|
7
|
-
colors: Pick<LabColors, "resolveTheme">;
|
|
8
|
-
/** Theme name. */
|
|
9
|
-
theme: ThemeName;
|
|
10
|
-
/**
|
|
11
|
-
* Explicit effective background, overriding the ancestor-composite. Use a hex
|
|
12
|
-
* string or a `() => hex` you sample yourself for image/gradient/blur surfaces
|
|
13
|
-
* that have no single readable `background-color`.
|
|
14
|
-
*/
|
|
15
|
-
background?: string | (() => string);
|
|
16
|
-
/** Element to write the `--lab-*` variables onto. Defaults to the watched element. */
|
|
17
|
-
target?: HTMLElement;
|
|
18
|
-
/** Base colour when the ancestor chain is fully translucent. Default `"#FFFFFF"`. */
|
|
19
|
-
fallback?: string;
|
|
20
|
-
/** Auto-refresh on DOM attribute mutations. Default `true`. */
|
|
21
|
-
observe?: boolean;
|
|
22
|
-
/** Mutation-observer root. Defaults to the document element. */
|
|
23
|
-
root?: Node;
|
|
24
|
-
/** Window-like host (for `MutationObserver`). Defaults to `globalThis`. */
|
|
25
|
-
win?: Window;
|
|
26
|
-
/** Injection seam for the computed style of an element (testing). */
|
|
27
|
-
getStyle?: (element: unknown) => { getPropertyValue(property: string): string };
|
|
28
|
-
/** Injection seam for an element's parent (testing). */
|
|
29
|
-
parentOf?: (element: unknown) => unknown;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export interface WatchController {
|
|
33
|
-
/**
|
|
34
|
-
* Re-resolve and re-apply if the effective background (or theme) changed;
|
|
35
|
-
* `force` re-applies unconditionally. Returns the now-applied result, or the
|
|
36
|
-
* cached one when nothing changed.
|
|
37
|
-
*/
|
|
38
|
-
refresh(force?: boolean): ResolvedTheme | null;
|
|
39
|
-
/** Switch theme and re-apply. */
|
|
40
|
-
setTheme(theme: ThemeName): void;
|
|
41
|
-
/** The effective background hex last resolved. */
|
|
42
|
-
background(): string;
|
|
43
|
-
/** Disconnect observers and stop watching. */
|
|
44
|
-
stop(): void;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Keep an element's `--lab-*` variables in sync with its (effective) background.
|
|
49
|
-
*
|
|
50
|
-
* Discrete background/theme changes are caught by a `MutationObserver`;
|
|
51
|
-
* continuous (animated) backgrounds are driven by calling `refresh()` from a
|
|
52
|
-
* `requestAnimationFrame` loop (cheap — re-resolves only on real change).
|
|
53
|
-
*/
|
|
54
|
-
export declare function watchTheme(
|
|
55
|
-
element: HTMLElement,
|
|
56
|
-
options: WatchThemeOptions,
|
|
57
|
-
): WatchController;
|