@sdxc/color 0.0.0-pre.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +21 -0
- package/README.md +223 -0
- package/dist/color-parse-error.d.ts +18 -0
- package/dist/color-parse-error.js +22 -0
- package/dist/color.d.ts +182 -0
- package/dist/color.js +346 -0
- package/dist/contrast-unreachable-error.d.ts +24 -0
- package/dist/contrast-unreachable-error.js +21 -0
- package/dist/contrast.d.ts +35 -0
- package/dist/contrast.js +15 -0
- package/dist/gamut.d.ts +19 -0
- package/dist/gamut.js +68 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +3 -0
- package/dist/interpolate.d.ts +29 -0
- package/dist/interpolate.js +79 -0
- package/dist/named.d.ts +10 -0
- package/dist/named.js +159 -0
- package/dist/parse.d.ts +20 -0
- package/dist/parse.js +272 -0
- package/dist/spaces.d.ts +65 -0
- package/dist/spaces.js +254 -0
- package/package.json +31 -0
package/dist/color.js
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import { failure, isFailure, success } from "@sdxc/result";
|
|
2
|
+
import { ContrastUnreachableError } from "./contrast-unreachable-error.js";
|
|
3
|
+
import { relativeLuminance, wcagContrast } from "./contrast.js";
|
|
4
|
+
import { isInSrgbGamut, mapToSrgbGamut } from "./gamut.js";
|
|
5
|
+
import { interpolate } from "./interpolate.js";
|
|
6
|
+
import { parseColor } from "./parse.js";
|
|
7
|
+
import { hslToSrgb, hwbToSrgb, normalizeHue, oklabToOklch, oklabToSrgb, oklchToOklab, srgbToHsl, srgbToOklab, } from "./spaces.js";
|
|
8
|
+
/** The default tolerance of `Color#equals`, wide enough to absorb float noise from conversion. */
|
|
9
|
+
const EQUALS_EPSILON = 1e-6;
|
|
10
|
+
/** Bisection rounds `ensureContrast` runs on lightness, far below any visible step. */
|
|
11
|
+
const LIGHTNESS_ITERATIONS = 40;
|
|
12
|
+
/**
|
|
13
|
+
* An immutable CSS color. Build one with `Color.parse` or a numeric constructor; every
|
|
14
|
+
* operation answers a new `Color`. An authored hue on a gray and `none` components are not
|
|
15
|
+
* kept: a gray reads back with hue 0, and `none` reads as 0.
|
|
16
|
+
*/
|
|
17
|
+
export class Color {
|
|
18
|
+
#r;
|
|
19
|
+
#g;
|
|
20
|
+
#b;
|
|
21
|
+
#alpha;
|
|
22
|
+
/** Stores the channels, reading a non-finite one as 0 and clamping alpha to 0–1. */
|
|
23
|
+
constructor(r, g, b, alpha) {
|
|
24
|
+
this.#r = finite(r);
|
|
25
|
+
this.#g = finite(g);
|
|
26
|
+
this.#b = finite(b);
|
|
27
|
+
this.#alpha = clamp(finite(alpha), 0, 1);
|
|
28
|
+
Object.freeze(this);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Reads any CSS color: hex, named colors and `transparent`, `rgb()`, `hsl()`, `hwb()`,
|
|
32
|
+
* `lab()`, `lch()`, `oklab()`, `oklch()` and `color()` in its predefined spaces, both
|
|
33
|
+
* as authored and as `getComputedStyle` serializes them.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* Color.parse("oklch(0.24 0.008 70)"); // Success<Color>
|
|
37
|
+
* @example
|
|
38
|
+
* Color.parse("currentcolor"); // Failure<ColorParseError>
|
|
39
|
+
*/
|
|
40
|
+
static parse(input) {
|
|
41
|
+
let parsed = parseColor(input);
|
|
42
|
+
if (isFailure(parsed))
|
|
43
|
+
return parsed;
|
|
44
|
+
let { r, g, b, alpha } = parsed.data;
|
|
45
|
+
return success(new Color(r, g, b, alpha));
|
|
46
|
+
}
|
|
47
|
+
/** A color from sRGB channels 0–1, kept unclamped so values outside describe wide gamut. */
|
|
48
|
+
static rgb(r, g, b, alpha = 1) {
|
|
49
|
+
return new Color(r, g, b, alpha);
|
|
50
|
+
}
|
|
51
|
+
/** A color from HSL: hue in degrees, saturation and lightness 0–1. */
|
|
52
|
+
static hsl(hue, saturation, lightness, alpha = 1) {
|
|
53
|
+
let [r, g, b] = hslToSrgb(finite(hue), finite(saturation), finite(lightness));
|
|
54
|
+
return new Color(r, g, b, alpha);
|
|
55
|
+
}
|
|
56
|
+
/** A color from HWB: hue in degrees, whiteness and blackness 0–1. */
|
|
57
|
+
static hwb(hue, whiteness, blackness, alpha = 1) {
|
|
58
|
+
let [r, g, b] = hwbToSrgb(finite(hue), finite(whiteness), finite(blackness));
|
|
59
|
+
return new Color(r, g, b, alpha);
|
|
60
|
+
}
|
|
61
|
+
/** A color from Oklab: lightness 0–1 and a, b roughly ±0.4. */
|
|
62
|
+
static oklab(lightness, a, b, alpha = 1) {
|
|
63
|
+
return Color.#fromVector(oklabToSrgb([finite(lightness), finite(a), finite(b)]), alpha);
|
|
64
|
+
}
|
|
65
|
+
/** A color from OKLCH: lightness 0–1, chroma from 0 and hue in degrees. */
|
|
66
|
+
static oklch(lightness, chroma, hue, alpha = 1) {
|
|
67
|
+
let lab = oklchToOklab([finite(lightness), finite(chroma), finite(hue)]);
|
|
68
|
+
return Color.#fromVector(oklabToSrgb(lab), alpha);
|
|
69
|
+
}
|
|
70
|
+
/** The contrast of `foreground` painted on `background`; see `Color#contrast`. */
|
|
71
|
+
static contrast(foreground, background, algorithm = "WCAG21") {
|
|
72
|
+
return foreground.contrast(background, algorithm);
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A gradient through `colors`, evenly spaced, as a function from `t` in 0–1 to a color.
|
|
76
|
+
* `t` is clamped, and each segment interpolates as `mix` does.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* let heat = Color.scale([blue, yellow, red]); heat(0.5); // yellow
|
|
80
|
+
*/
|
|
81
|
+
static scale(colors, options = {}) {
|
|
82
|
+
let [first] = colors;
|
|
83
|
+
let segments = colors.length - 1;
|
|
84
|
+
if (segments === 0)
|
|
85
|
+
return () => first;
|
|
86
|
+
return (t) => {
|
|
87
|
+
let position = clamp(finite(t), 0, 1) * segments;
|
|
88
|
+
let index = Math.min(Math.floor(position), segments - 1);
|
|
89
|
+
let from = colors[index] ?? first;
|
|
90
|
+
let to = colors[index + 1] ?? first;
|
|
91
|
+
return from.mix(to, position - index, options);
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* `count` evenly spaced colors along `Color.scale(colors, options)`, both ends included.
|
|
96
|
+
* One step answers the first color, and fewer than one answers none.
|
|
97
|
+
*/
|
|
98
|
+
static steps(colors, count, options = {}) {
|
|
99
|
+
let scale = Color.scale(colors, options);
|
|
100
|
+
if (count < 1)
|
|
101
|
+
return [];
|
|
102
|
+
if (count < 2)
|
|
103
|
+
return [scale(0)];
|
|
104
|
+
return Array.from({ length: Math.floor(count) }, (_, index) => scale(index / (count - 1)));
|
|
105
|
+
}
|
|
106
|
+
/** A color from gamma-encoded sRGB channels. */
|
|
107
|
+
static #fromVector(rgb, alpha) {
|
|
108
|
+
return new Color(rgb[0], rgb[1], rgb[2], alpha);
|
|
109
|
+
}
|
|
110
|
+
/** Opacity from 0 (transparent) to 1 (opaque). */
|
|
111
|
+
get alpha() {
|
|
112
|
+
return this.#alpha;
|
|
113
|
+
}
|
|
114
|
+
/** The stored channels, unclamped, so a wide-gamut color reads below 0 or above 1. */
|
|
115
|
+
toRgb() {
|
|
116
|
+
return { r: this.#r, g: this.#g, b: this.#b, alpha: this.#alpha };
|
|
117
|
+
}
|
|
118
|
+
/** The color as HSL, gamut-mapped first because HSL cannot describe anything outside sRGB. */
|
|
119
|
+
toHsl() {
|
|
120
|
+
let [h, s, l] = srgbToHsl(mapToSrgbGamut(this.#vector()));
|
|
121
|
+
return { h, s, l, alpha: this.#alpha };
|
|
122
|
+
}
|
|
123
|
+
/** The color in Oklab, unclamped. */
|
|
124
|
+
toOklab() {
|
|
125
|
+
let [l, a, b] = srgbToOklab(this.#vector());
|
|
126
|
+
return { l, a, b, alpha: this.#alpha };
|
|
127
|
+
}
|
|
128
|
+
/** The color in OKLCH, unclamped; an achromatic color answers a hue of 0. */
|
|
129
|
+
toOklch() {
|
|
130
|
+
let [l, c, h] = oklabToOklch(srgbToOklab(this.#vector()));
|
|
131
|
+
return { l, c, h, alpha: this.#alpha };
|
|
132
|
+
}
|
|
133
|
+
/** Whether every sRGB channel and alpha differs from `other`'s by at most `epsilon`. */
|
|
134
|
+
equals(other, epsilon = EQUALS_EPSILON) {
|
|
135
|
+
let mine = this.toRgb();
|
|
136
|
+
let theirs = other.toRgb();
|
|
137
|
+
return (Math.abs(mine.r - theirs.r) <= epsilon &&
|
|
138
|
+
Math.abs(mine.g - theirs.g) <= epsilon &&
|
|
139
|
+
Math.abs(mine.b - theirs.b) <= epsilon &&
|
|
140
|
+
Math.abs(mine.alpha - theirs.alpha) <= epsilon);
|
|
141
|
+
}
|
|
142
|
+
/** Whether the color fits in sRGB, so every display can show it as is. */
|
|
143
|
+
inGamut() {
|
|
144
|
+
return isInSrgbGamut(this.#vector());
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The color mapped into sRGB by the CSS Color 4 algorithm, which lowers OKLCH chroma and
|
|
148
|
+
* keeps lightness and hue. A color already inside answers itself.
|
|
149
|
+
*/
|
|
150
|
+
toGamut() {
|
|
151
|
+
let vector = this.#vector();
|
|
152
|
+
let mapped = mapToSrgbGamut(vector);
|
|
153
|
+
return mapped === vector ? this : Color.#fromVector(mapped, this.#alpha);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Valid CSS for the color, so `${color}` works anywhere CSS does. Without a format it is
|
|
157
|
+
* `rgb(r g b / a)` inside sRGB and `oklch()` outside, which no display clips.
|
|
158
|
+
*/
|
|
159
|
+
toString(format) {
|
|
160
|
+
let chosen = format ?? (this.inGamut() ? "rgb" : "oklch");
|
|
161
|
+
let alpha = this.#alpha < 1 ? ` / ${formatNumber(this.#alpha, 4)}` : "";
|
|
162
|
+
switch (chosen) {
|
|
163
|
+
case "hex":
|
|
164
|
+
return this.#hex();
|
|
165
|
+
case "rgb": {
|
|
166
|
+
let [r, g, b] = mapToSrgbGamut(this.#vector()).map((channel) => formatNumber(clamp(channel, 0, 1) * 255, 2));
|
|
167
|
+
return `rgb(${r} ${g} ${b}${alpha})`;
|
|
168
|
+
}
|
|
169
|
+
case "hsl": {
|
|
170
|
+
let { h, s, l } = this.toHsl();
|
|
171
|
+
return `hsl(${formatNumber(h, 2)} ${formatNumber(s * 100, 2)}% ${formatNumber(l * 100, 2)}%${alpha})`;
|
|
172
|
+
}
|
|
173
|
+
case "oklch": {
|
|
174
|
+
let { l, c, h } = this.toOklch();
|
|
175
|
+
return `oklch(${formatNumber(l, 6)} ${formatNumber(c, 6)} ${formatNumber(h, 4)}${alpha})`;
|
|
176
|
+
}
|
|
177
|
+
case "oklab": {
|
|
178
|
+
let { l, a, b } = this.toOklab();
|
|
179
|
+
return `oklab(${formatNumber(l, 6)} ${formatNumber(a, 6)} ${formatNumber(b, 6)}${alpha})`;
|
|
180
|
+
}
|
|
181
|
+
case "srgb":
|
|
182
|
+
return `color(srgb ${formatNumber(this.#r, 6)} ${formatNumber(this.#g, 6)} ${formatNumber(this.#b, 6)}${alpha})`;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* This color painted over `background` with source-over compositing in gamma-encoded
|
|
187
|
+
* sRGB, the way browsers paint a translucent layer.
|
|
188
|
+
*/
|
|
189
|
+
over(background) {
|
|
190
|
+
let alpha = this.#alpha + background.#alpha * (1 - this.#alpha);
|
|
191
|
+
if (alpha === 0)
|
|
192
|
+
return new Color(0, 0, 0, 0);
|
|
193
|
+
let channel = (source, backdrop) => (source * this.#alpha + backdrop * background.#alpha * (1 - this.#alpha)) / alpha;
|
|
194
|
+
return new Color(channel(this.#r, background.#r), channel(this.#g, background.#g), channel(this.#b, background.#b), alpha);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* This color mixed with `other` by CSS color-mix() rules, premultiplied alpha included.
|
|
198
|
+
* `amount` is the share of `other`: 0 answers this color and 1 answers `other`.
|
|
199
|
+
*
|
|
200
|
+
* @example
|
|
201
|
+
* red.mix(blue, 0.25, { space: "oklch", hue: "longer" });
|
|
202
|
+
*/
|
|
203
|
+
mix(other, amount = 0.5, options = {}) {
|
|
204
|
+
let { r, g, b, alpha } = interpolate(this.toRgb(), other.toRgb(), finite(amount), options);
|
|
205
|
+
return new Color(r, g, b, alpha);
|
|
206
|
+
}
|
|
207
|
+
/** The same color at opacity `alpha`, clamped to 0–1. */
|
|
208
|
+
withAlpha(alpha) {
|
|
209
|
+
return new Color(this.#r, this.#g, this.#b, alpha);
|
|
210
|
+
}
|
|
211
|
+
/** The same color with its alpha multiplied by `factor`. */
|
|
212
|
+
fade(factor) {
|
|
213
|
+
return this.withAlpha(this.#alpha * factor);
|
|
214
|
+
}
|
|
215
|
+
/** OKLCH lightness multiplied by `1 + amount`, clamped to 1: `lighten(0.1)` is 10% lighter. */
|
|
216
|
+
lighten(amount) {
|
|
217
|
+
return this.with({ lightness: clamp(this.toOklch().l * (1 + amount), 0, 1) });
|
|
218
|
+
}
|
|
219
|
+
/** OKLCH lightness multiplied by `1 - amount`, clamped to 0: `darken(0.1)` is 10% darker. */
|
|
220
|
+
darken(amount) {
|
|
221
|
+
return this.with({ lightness: clamp(this.toOklch().l * (1 - amount), 0, 1) });
|
|
222
|
+
}
|
|
223
|
+
/** OKLCH chroma multiplied by `1 + amount`; the result may leave sRGB, see `toGamut`. */
|
|
224
|
+
saturate(amount) {
|
|
225
|
+
return this.with({ chroma: Math.max(this.toOklch().c * (1 + amount), 0) });
|
|
226
|
+
}
|
|
227
|
+
/** OKLCH chroma multiplied by `1 - amount`, never below 0. */
|
|
228
|
+
desaturate(amount) {
|
|
229
|
+
return this.with({ chroma: Math.max(this.toOklch().c * (1 - amount), 0) });
|
|
230
|
+
}
|
|
231
|
+
/** The OKLCH hue turned by `degrees`, either way round. */
|
|
232
|
+
rotate(degrees) {
|
|
233
|
+
return this.with({ hue: normalizeHue(this.toOklch().h + finite(degrees)) });
|
|
234
|
+
}
|
|
235
|
+
/** The gray with the same OKLCH lightness. */
|
|
236
|
+
grayscale() {
|
|
237
|
+
return this.with({ chroma: 0 });
|
|
238
|
+
}
|
|
239
|
+
/** The color opposite on the OKLCH hue circle, at the same lightness and chroma. */
|
|
240
|
+
complement() {
|
|
241
|
+
return this.rotate(180);
|
|
242
|
+
}
|
|
243
|
+
/** Each sRGB channel inverted (`1 - channel`), alpha kept. */
|
|
244
|
+
invert() {
|
|
245
|
+
return new Color(1 - this.#r, 1 - this.#g, 1 - this.#b, this.#alpha);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The color with exact OKLCH values set. A gray starts from hue 0, so giving it chroma
|
|
249
|
+
* without a hue turns it pink.
|
|
250
|
+
*/
|
|
251
|
+
with(changes) {
|
|
252
|
+
let current = this.toOklch();
|
|
253
|
+
return Color.oklch(changes.lightness ?? current.l, changes.chroma ?? current.c, changes.hue ?? current.h, changes.alpha ?? current.alpha);
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* The contrast of this color as text or a UI part on `background`. A translucent
|
|
257
|
+
* background is painted over white first and this color is painted over that, so the
|
|
258
|
+
* ratio is what a reader sees; both are gamut-mapped to sRGB before measuring.
|
|
259
|
+
* Order matters only for translucent colors; two opaque colors measure the same either way.
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* Color.rgb(0, 0, 0).contrast(Color.rgb(1, 1, 1)).aa.text; // true, 21:1
|
|
263
|
+
*/
|
|
264
|
+
contrast(background, _algorithm = "WCAG21") {
|
|
265
|
+
let backdrop = background.#alpha < 1 ? background.over(opaqueWhite()) : background;
|
|
266
|
+
let painted = this.#alpha < 1 ? this.over(backdrop) : this;
|
|
267
|
+
return wcagContrast(relativeLuminance(mapToSrgbGamut(painted.#vector())), relativeLuminance(mapToSrgbGamut(backdrop.#vector())));
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* The color closest to this one that reaches `ratio` against `background`, changing only
|
|
271
|
+
* OKLCH lightness, in whichever direction gets there with the smaller change. The answer
|
|
272
|
+
* is gamut-mapped, since that is the color contrast was measured on.
|
|
273
|
+
*
|
|
274
|
+
* @returns This color when it already passes, or a `ContrastUnreachableError` holding the
|
|
275
|
+
* best lightness extreme when neither black-ward nor white-ward reaches `ratio`.
|
|
276
|
+
*/
|
|
277
|
+
ensureContrast(background, ratio) {
|
|
278
|
+
if (this.contrast(background).ratio >= ratio)
|
|
279
|
+
return success(this);
|
|
280
|
+
let lightness = this.toOklch().l;
|
|
281
|
+
let candidate = (value) => this.with({ lightness: value }).toGamut();
|
|
282
|
+
let measure = (value) => candidate(value).contrast(background).ratio;
|
|
283
|
+
let reachable = [];
|
|
284
|
+
for (let end of [0, 1]) {
|
|
285
|
+
if (measure(end) < ratio)
|
|
286
|
+
continue;
|
|
287
|
+
let failing = lightness;
|
|
288
|
+
let passing = end;
|
|
289
|
+
for (let round = 0; round < LIGHTNESS_ITERATIONS; round++) {
|
|
290
|
+
let middle = (failing + passing) / 2;
|
|
291
|
+
if (measure(middle) >= ratio)
|
|
292
|
+
passing = middle;
|
|
293
|
+
else
|
|
294
|
+
failing = middle;
|
|
295
|
+
}
|
|
296
|
+
reachable.push(passing);
|
|
297
|
+
}
|
|
298
|
+
let closest = null;
|
|
299
|
+
for (let value of reachable) {
|
|
300
|
+
if (closest === null || Math.abs(value - lightness) < Math.abs(closest - lightness)) {
|
|
301
|
+
closest = value;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
if (closest !== null)
|
|
305
|
+
return success(candidate(closest));
|
|
306
|
+
let best = measure(0) >= measure(1) ? 0 : 1;
|
|
307
|
+
return failure(new ContrastUnreachableError(ratio, measure(best), candidate(best)));
|
|
308
|
+
}
|
|
309
|
+
/** Black or white, whichever contrasts more as text on this color; black wins a tie. */
|
|
310
|
+
contrastingText() {
|
|
311
|
+
let black = new Color(0, 0, 0, 1);
|
|
312
|
+
let white = opaqueWhite();
|
|
313
|
+
return black.contrast(this).ratio >= white.contrast(this).ratio ? black : white;
|
|
314
|
+
}
|
|
315
|
+
/** The stored channels as a vector for the space math. */
|
|
316
|
+
#vector() {
|
|
317
|
+
return [this.#r, this.#g, this.#b];
|
|
318
|
+
}
|
|
319
|
+
/** `#rrggbb`, or `#rrggbbaa` below full opacity, from the gamut-mapped color. */
|
|
320
|
+
#hex() {
|
|
321
|
+
let [r, g, b] = mapToSrgbGamut(this.#vector());
|
|
322
|
+
let bytes = [r, g, b, ...(this.#alpha < 1 ? [this.#alpha] : [])];
|
|
323
|
+
return `#${bytes.map((channel) => toByte(channel).toString(16).padStart(2, "0")).join("")}`;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/** Opaque white, the backdrop a translucent background is painted over before measuring. */
|
|
327
|
+
function opaqueWhite() {
|
|
328
|
+
return Color.rgb(1, 1, 1);
|
|
329
|
+
}
|
|
330
|
+
/** `value`, or 0 for `NaN` and the infinities, the way CSS reads `none`. */
|
|
331
|
+
function finite(value) {
|
|
332
|
+
return Number.isFinite(value) ? value : 0;
|
|
333
|
+
}
|
|
334
|
+
/** `value` limited to `[min, max]`. */
|
|
335
|
+
function clamp(value, min, max) {
|
|
336
|
+
return Math.min(Math.max(value, min), max);
|
|
337
|
+
}
|
|
338
|
+
/** A 0–1 channel as a rounded byte for hex output. */
|
|
339
|
+
function toByte(channel) {
|
|
340
|
+
return Math.round(clamp(channel, 0, 1) * 255);
|
|
341
|
+
}
|
|
342
|
+
/** `value` rounded to at most `digits` decimals, trailing zeros and negative zero dropped. */
|
|
343
|
+
function formatNumber(value, digits) {
|
|
344
|
+
let rounded = Number(value.toFixed(digits));
|
|
345
|
+
return String(Object.is(rounded, -0) ? 0 : rounded);
|
|
346
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The failure `Color#ensureContrast` reports when no lightness reaches the target ratio.
|
|
3
|
+
* It carries the closest color it found, so a caller that must show something still has
|
|
4
|
+
* the best available choice.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { Color } from "./color.js";
|
|
10
|
+
/** No OKLCH lightness of the color reaches `target` against the background. */
|
|
11
|
+
export declare class ContrastUnreachableError extends Error {
|
|
12
|
+
/** The ratio that was asked for. */
|
|
13
|
+
readonly target: number;
|
|
14
|
+
/** The highest ratio any lightness reached, which `best` has. */
|
|
15
|
+
readonly ratio: number;
|
|
16
|
+
/** The color at the lightness extreme with the highest ratio, ready to use as a fallback. */
|
|
17
|
+
readonly best: Color;
|
|
18
|
+
/**
|
|
19
|
+
* @param target - The ratio that was asked for.
|
|
20
|
+
* @param ratio - The highest ratio reached.
|
|
21
|
+
* @param best - The color that reached it.
|
|
22
|
+
*/
|
|
23
|
+
constructor(target: number, ratio: number, best: Color);
|
|
24
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** No OKLCH lightness of the color reaches `target` against the background. */
|
|
2
|
+
export class ContrastUnreachableError extends Error {
|
|
3
|
+
/** The ratio that was asked for. */
|
|
4
|
+
target;
|
|
5
|
+
/** The highest ratio any lightness reached, which `best` has. */
|
|
6
|
+
ratio;
|
|
7
|
+
/** The color at the lightness extreme with the highest ratio, ready to use as a fallback. */
|
|
8
|
+
best;
|
|
9
|
+
/**
|
|
10
|
+
* @param target - The ratio that was asked for.
|
|
11
|
+
* @param ratio - The highest ratio reached.
|
|
12
|
+
* @param best - The color that reached it.
|
|
13
|
+
*/
|
|
14
|
+
constructor(target, ratio, best) {
|
|
15
|
+
super(`No lightness reaches a contrast of ${target}:1; the best is ${ratio.toFixed(2)}:1`);
|
|
16
|
+
this.name = "ContrastUnreachableError";
|
|
17
|
+
this.target = target;
|
|
18
|
+
this.ratio = ratio;
|
|
19
|
+
this.best = best;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WCAG 2.1 contrast math: relative luminance on linear sRGB and the pass flags at each
|
|
3
|
+
* conformance level. The result names its algorithm, so a second one such as APCA can be
|
|
4
|
+
* added beside it without changing what WCAG callers read.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { Vector } from "./spaces.js";
|
|
10
|
+
/** The contrast algorithms `Color#contrast` implements. */
|
|
11
|
+
export type ContrastAlgorithm = "WCAG21";
|
|
12
|
+
/**
|
|
13
|
+
* A WCAG 2.1 contrast measurement. Every flag compares the unrounded ratio, as WCAG
|
|
14
|
+
* requires, so 4.499:1 fails a 4.5:1 threshold.
|
|
15
|
+
*/
|
|
16
|
+
export interface WcagContrast {
|
|
17
|
+
algorithm: "WCAG21";
|
|
18
|
+
/** From 1 (identical luminance) to 21 (black on white). */
|
|
19
|
+
ratio: number;
|
|
20
|
+
/** Level AA: text at 4.5:1, large text at 3:1 and non-text UI (1.4.11) at 3:1. */
|
|
21
|
+
aa: {
|
|
22
|
+
text: boolean;
|
|
23
|
+
largeText: boolean;
|
|
24
|
+
nonText: boolean;
|
|
25
|
+
};
|
|
26
|
+
/** Level AAA: text at 7:1 and large text at 4.5:1. */
|
|
27
|
+
aaa: {
|
|
28
|
+
text: boolean;
|
|
29
|
+
largeText: boolean;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** The WCAG 2.1 relative luminance of gamma-encoded sRGB, from 0 for black to 1 for white. */
|
|
33
|
+
export declare function relativeLuminance(rgb: Vector): number;
|
|
34
|
+
/** The WCAG 2.1 contrast between two relative luminances, in either order. */
|
|
35
|
+
export declare function wcagContrast(first: number, second: number): WcagContrast;
|
package/dist/contrast.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { srgbToLinear } from "./spaces.js";
|
|
2
|
+
/** The WCAG 2.1 relative luminance of gamma-encoded sRGB, from 0 for black to 1 for white. */
|
|
3
|
+
export function relativeLuminance(rgb) {
|
|
4
|
+
return (0.2126 * srgbToLinear(rgb[0]) + 0.7152 * srgbToLinear(rgb[1]) + 0.0722 * srgbToLinear(rgb[2]));
|
|
5
|
+
}
|
|
6
|
+
/** The WCAG 2.1 contrast between two relative luminances, in either order. */
|
|
7
|
+
export function wcagContrast(first, second) {
|
|
8
|
+
let ratio = (Math.max(first, second) + 0.05) / (Math.min(first, second) + 0.05);
|
|
9
|
+
return {
|
|
10
|
+
algorithm: "WCAG21",
|
|
11
|
+
ratio,
|
|
12
|
+
aa: { text: ratio >= 4.5, largeText: ratio >= 3, nonText: ratio >= 3 },
|
|
13
|
+
aaa: { text: ratio >= 7, largeText: ratio >= 4.5 },
|
|
14
|
+
};
|
|
15
|
+
}
|
package/dist/gamut.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sRGB gamut checks and the CSS Color 4 gamut-mapping algorithm. Mapping lowers OKLCH
|
|
3
|
+
* chroma until the color fits, keeping lightness and hue, so a wide-gamut color lands on
|
|
4
|
+
* the nearest displayable shade of itself instead of a per-channel clip.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { Vector } from "./spaces.js";
|
|
10
|
+
/** Whether every channel of gamma-encoded sRGB sits inside `[0, 1]`, within float noise. */
|
|
11
|
+
export declare function isInSrgbGamut(rgb: Vector): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Maps gamma-encoded sRGB into the sRGB gamut by the CSS Color 4 algorithm: a lightness at
|
|
14
|
+
* or past 1 is white and at or below 0 is black; otherwise chroma is binary-searched down
|
|
15
|
+
* until clipping the result moves it by less than a just-noticeable difference.
|
|
16
|
+
*
|
|
17
|
+
* @returns The input itself when it already fits, so callers can compare by identity.
|
|
18
|
+
*/
|
|
19
|
+
export declare function mapToSrgbGamut(rgb: Vector): Vector;
|
package/dist/gamut.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { oklabToOklch, oklabToSrgb, oklchToOklab, srgbToOklab } from "./spaces.js";
|
|
2
|
+
/**
|
|
3
|
+
* How far past 0 or 1 a channel may sit and still count as in gamut, so float noise from a
|
|
4
|
+
* conversion never flips a displayable color to out-of-gamut.
|
|
5
|
+
*/
|
|
6
|
+
const GAMUT_EPSILON = 1e-6;
|
|
7
|
+
/** The color difference CSS treats as just noticeable, in ΔEOK. */
|
|
8
|
+
const JUST_NOTICEABLE = 0.02;
|
|
9
|
+
/** The chroma precision at which the binary search stops. */
|
|
10
|
+
const CHROMA_PRECISION = 1e-4;
|
|
11
|
+
/** Whether every channel of gamma-encoded sRGB sits inside `[0, 1]`, within float noise. */
|
|
12
|
+
export function isInSrgbGamut(rgb) {
|
|
13
|
+
return rgb.every((channel) => channel >= -GAMUT_EPSILON && channel <= 1 + GAMUT_EPSILON);
|
|
14
|
+
}
|
|
15
|
+
/** Each channel clamped to `[0, 1]`. */
|
|
16
|
+
function clip(rgb) {
|
|
17
|
+
return [
|
|
18
|
+
Math.min(Math.max(rgb[0], 0), 1),
|
|
19
|
+
Math.min(Math.max(rgb[1], 0), 1),
|
|
20
|
+
Math.min(Math.max(rgb[2], 0), 1),
|
|
21
|
+
];
|
|
22
|
+
}
|
|
23
|
+
/** The Euclidean distance between two colors in Oklab, CSS's ΔEOK. */
|
|
24
|
+
function deltaEOK(first, second) {
|
|
25
|
+
return Math.hypot(first[0] - second[0], first[1] - second[1], first[2] - second[2]);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Maps gamma-encoded sRGB into the sRGB gamut by the CSS Color 4 algorithm: a lightness at
|
|
29
|
+
* or past 1 is white and at or below 0 is black; otherwise chroma is binary-searched down
|
|
30
|
+
* until clipping the result moves it by less than a just-noticeable difference.
|
|
31
|
+
*
|
|
32
|
+
* @returns The input itself when it already fits, so callers can compare by identity.
|
|
33
|
+
*/
|
|
34
|
+
export function mapToSrgbGamut(rgb) {
|
|
35
|
+
if (isInSrgbGamut(rgb))
|
|
36
|
+
return rgb;
|
|
37
|
+
let origin = oklabToOklch(srgbToOklab(rgb));
|
|
38
|
+
if (origin[0] >= 1)
|
|
39
|
+
return [1, 1, 1];
|
|
40
|
+
if (origin[0] <= 0)
|
|
41
|
+
return [0, 0, 0];
|
|
42
|
+
let toSrgb = (chroma) => oklabToSrgb(oklchToOklab([origin[0], chroma, origin[2]]));
|
|
43
|
+
let clipped = clip(rgb);
|
|
44
|
+
if (deltaEOK(srgbToOklab(clipped), srgbToOklab(rgb)) < JUST_NOTICEABLE)
|
|
45
|
+
return clipped;
|
|
46
|
+
let min = 0;
|
|
47
|
+
let max = origin[1];
|
|
48
|
+
let minInGamut = true;
|
|
49
|
+
while (max - min > CHROMA_PRECISION) {
|
|
50
|
+
let chroma = (min + max) / 2;
|
|
51
|
+
let current = toSrgb(chroma);
|
|
52
|
+
if (minInGamut && isInSrgbGamut(current)) {
|
|
53
|
+
min = chroma;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
clipped = clip(current);
|
|
57
|
+
let error = deltaEOK(srgbToOklab(clipped), srgbToOklab(current));
|
|
58
|
+
if (error >= JUST_NOTICEABLE) {
|
|
59
|
+
max = chroma;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (JUST_NOTICEABLE - error < CHROMA_PRECISION)
|
|
63
|
+
return clipped;
|
|
64
|
+
minInGamut = false;
|
|
65
|
+
min = chroma;
|
|
66
|
+
}
|
|
67
|
+
return clipped;
|
|
68
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The package entrypoint: the immutable `Color` value, the errors its fallible operations
|
|
3
|
+
* report, and the plain shapes it converts to and takes options as.
|
|
4
|
+
*
|
|
5
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
6
|
+
* @copyright Sergio Xalambrí 2026
|
|
7
|
+
*/
|
|
8
|
+
export type { ColorFormat, Hsl, Oklab, Oklch, OklchChanges, Rgb } from "./color.js";
|
|
9
|
+
export type { ContrastAlgorithm, WcagContrast } from "./contrast.js";
|
|
10
|
+
export type { HueInterpolation, InterpolationOptions, InterpolationSpace } from "./interpolate.js";
|
|
11
|
+
export { Color } from "./color.js";
|
|
12
|
+
export { ColorParseError } from "./color-parse-error.js";
|
|
13
|
+
export { ContrastUnreachableError } from "./contrast-unreachable-error.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interpolation between two colors by the CSS color-mix() and gradient rules: premultiplied
|
|
3
|
+
* alpha, a powerless hue taking the other color's hue, and the four hue arcs. `Color#mix`,
|
|
4
|
+
* `Color.scale` and `Color.steps` all go through it, so they agree at every point.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
import type { Rgb } from "./color.js";
|
|
10
|
+
/** The spaces colors interpolate in; `"oklab"` is CSS's default. */
|
|
11
|
+
export type InterpolationSpace = "oklab" | "oklch" | "srgb";
|
|
12
|
+
/** Which way round the hue circle an OKLCH interpolation travels; `"shorter"` is the default. */
|
|
13
|
+
export type HueInterpolation = "shorter" | "longer" | "increasing" | "decreasing";
|
|
14
|
+
/** How `mix`, `scale` and `steps` interpolate. */
|
|
15
|
+
export interface InterpolationOptions {
|
|
16
|
+
/** @default "oklab" */
|
|
17
|
+
space?: InterpolationSpace;
|
|
18
|
+
/**
|
|
19
|
+
* The hue arc, read only when `space` is `"oklch"`.
|
|
20
|
+
*
|
|
21
|
+
* @default "shorter"
|
|
22
|
+
*/
|
|
23
|
+
hue?: HueInterpolation;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* The color `t` of the way from `from` to `to`, interpolated with premultiplied alpha so a
|
|
27
|
+
* transparent end contributes no color of its own.
|
|
28
|
+
*/
|
|
29
|
+
export declare function interpolate(from: Rgb, to: Rgb, t: number, { space, hue }: InterpolationOptions): Rgb;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { ACHROMATIC_CHROMA, normalizeHue, oklabToOklch, oklabToSrgb, oklchToOklab, srgbToOklab, } from "./spaces.js";
|
|
2
|
+
/**
|
|
3
|
+
* The color `t` of the way from `from` to `to`, interpolated with premultiplied alpha so a
|
|
4
|
+
* transparent end contributes no color of its own.
|
|
5
|
+
*/
|
|
6
|
+
export function interpolate(from, to, t, { space = "oklab", hue = "shorter" }) {
|
|
7
|
+
let alpha = lerp(from.alpha, to.alpha, t);
|
|
8
|
+
let start = [from.r, from.g, from.b];
|
|
9
|
+
let end = [to.r, to.g, to.b];
|
|
10
|
+
if (space === "srgb")
|
|
11
|
+
return withAlpha(lerpPremultiplied(start, from.alpha, end, to.alpha, t, alpha, 3), alpha);
|
|
12
|
+
if (space === "oklab") {
|
|
13
|
+
let lab = lerpPremultiplied(srgbToOklab(start), from.alpha, srgbToOklab(end), to.alpha, t, alpha, 3);
|
|
14
|
+
return withAlpha(oklabToSrgb(lab), alpha);
|
|
15
|
+
}
|
|
16
|
+
let startLch = oklabToOklch(srgbToOklab(start));
|
|
17
|
+
let endLch = oklabToOklch(srgbToOklab(end));
|
|
18
|
+
let lc = lerpPremultiplied(startLch, from.alpha, endLch, to.alpha, t, alpha, 2);
|
|
19
|
+
let h = interpolateHue(hueOf(startLch, endLch), hueOf(endLch, startLch), t, hue);
|
|
20
|
+
return withAlpha(oklabToSrgb(oklchToOklab([lc[0], lc[1], h])), alpha);
|
|
21
|
+
}
|
|
22
|
+
/** `start + (end - start) × t`, exact at both ends. */
|
|
23
|
+
function lerp(start, end, t) {
|
|
24
|
+
return start + (end - start) * t;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Interpolates the first `count` components premultiplied by alpha and divides the result
|
|
28
|
+
* by the interpolated alpha. When that alpha is 0 the components interpolate as they are,
|
|
29
|
+
* since a fully transparent color has no premultiplied value to recover.
|
|
30
|
+
*/
|
|
31
|
+
function lerpPremultiplied(start, startAlpha, end, endAlpha, t, alpha, count) {
|
|
32
|
+
let result = [start[0], start[1], start[2]];
|
|
33
|
+
for (let index = 0; index < count; index++) {
|
|
34
|
+
result[index] =
|
|
35
|
+
alpha === 0
|
|
36
|
+
? lerp(start[index] ?? 0, end[index] ?? 0, t)
|
|
37
|
+
: lerp((start[index] ?? 0) * startAlpha, (end[index] ?? 0) * endAlpha, t) / alpha;
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
/** Rebuilds an `Rgb` from interpolated channels. */
|
|
42
|
+
function withAlpha(rgb, alpha) {
|
|
43
|
+
return { r: rgb[0], g: rgb[1], b: rgb[2], alpha };
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The hue to interpolate from for `lch`. An achromatic color's hue is powerless, so it
|
|
47
|
+
* takes the other color's hue, and two grays share a hue of 0.
|
|
48
|
+
*/
|
|
49
|
+
function hueOf(lch, other) {
|
|
50
|
+
if (lch[1] >= ACHROMATIC_CHROMA)
|
|
51
|
+
return lch[2];
|
|
52
|
+
return other[1] >= ACHROMATIC_CHROMA ? other[2] : 0;
|
|
53
|
+
}
|
|
54
|
+
/** Interpolates two hues along the arc `method` picks, as CSS Color 4 defines each one. */
|
|
55
|
+
function interpolateHue(start, end, t, method) {
|
|
56
|
+
let from = start;
|
|
57
|
+
let to = end;
|
|
58
|
+
let delta = to - from;
|
|
59
|
+
if (method === "shorter") {
|
|
60
|
+
if (delta > 180)
|
|
61
|
+
from += 360;
|
|
62
|
+
else if (delta < -180)
|
|
63
|
+
to += 360;
|
|
64
|
+
}
|
|
65
|
+
else if (method === "longer") {
|
|
66
|
+
if (delta > 0 && delta < 180)
|
|
67
|
+
from += 360;
|
|
68
|
+
else if (delta > -180 && delta <= 0)
|
|
69
|
+
to += 360;
|
|
70
|
+
}
|
|
71
|
+
else if (method === "increasing") {
|
|
72
|
+
if (delta < 0)
|
|
73
|
+
to += 360;
|
|
74
|
+
}
|
|
75
|
+
else if (delta > 0) {
|
|
76
|
+
from += 360;
|
|
77
|
+
}
|
|
78
|
+
return normalizeHue(lerp(from, to, t));
|
|
79
|
+
}
|
package/dist/named.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The CSS Color 4 named colors as packed `0xRRGGBB` numbers, the table `Color.parse`
|
|
3
|
+
* reads a keyword from. `transparent` is absent because it alone carries alpha, so the
|
|
4
|
+
* parser answers it directly.
|
|
5
|
+
*
|
|
6
|
+
* @author [Sergio Xalambrí](https://sergiodxa.com)
|
|
7
|
+
* @copyright Sergio Xalambrí 2026
|
|
8
|
+
*/
|
|
9
|
+
/** Every CSS named color, lower-cased, mapped to its sRGB value packed as `0xRRGGBB`. */
|
|
10
|
+
export declare const NAMED_COLORS: Readonly<Record<string, number>>;
|