@solid-primitives/utils 6.4.0 → 7.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +71 -0
- package/README.md +276 -0
- package/dist/colors/helpers.d.ts +46 -0
- package/dist/colors/helpers.js +895 -0
- package/dist/colors/index.d.ts +4 -0
- package/dist/colors/index.js +4 -0
- package/dist/colors/intl.d.ts +54 -0
- package/dist/colors/intl.js +68 -0
- package/dist/colors/manipulation.d.ts +144 -0
- package/dist/colors/manipulation.js +278 -0
- package/dist/colors/types.d.ts +77 -0
- package/dist/colors/types.js +14 -0
- package/dist/index.d.ts +104 -21
- package/dist/index.js +106 -18
- package/dist/types.d.ts +4 -2
- package/package.json +84 -3
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Portions of this file are based on code from Kobalte.
|
|
3
|
+
* MIT License, Copyright Fabien Marie-Louise.
|
|
4
|
+
*
|
|
5
|
+
* Credits to the Kobalte team:
|
|
6
|
+
* https://github.com/kobaltedev/kobalte/tree/main/packages/core/src/colors
|
|
7
|
+
*
|
|
8
|
+
* Which in turn is based on code from React Spectrum.
|
|
9
|
+
* Apache License Version 2.0, Copyright 2020 Adobe.
|
|
10
|
+
*
|
|
11
|
+
* Credits to the React Spectrum team:
|
|
12
|
+
* https://github.com/adobe/react-spectrum/blob/68e305768cb829bab7b9836dded593bd731259f3/packages/%40react-stately/color/src/Color.ts
|
|
13
|
+
*/
|
|
14
|
+
import { clamp } from "../index.js";
|
|
15
|
+
/**
|
|
16
|
+
* Parses a color string into a {@link Color} object.
|
|
17
|
+
*
|
|
18
|
+
* Supported formats:
|
|
19
|
+
* - **Hex**: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`
|
|
20
|
+
* - **RGB**: `rgb(r g b)`, `rgb(r, g, b)`, `rgb(r g b / a)`, `rgba(r, g, b, a)`
|
|
21
|
+
* - **HSL**: `hsl(h, s%, l%)`, `hsla(h, s%, l%, a)`
|
|
22
|
+
* - **HSB**: `hsb(h, s%, b%)`, `hsba(h, s%, b%, a)`
|
|
23
|
+
*
|
|
24
|
+
* @throws if the string does not match any supported format.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* const color = parseColor("#3264C8");
|
|
29
|
+
* color.toString("hsl"); // "hsl(220 60% 49.02%)"
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export function parseColor(value) {
|
|
33
|
+
const res = RGBColor.parse(value) || HSBColor.parse(value) || HSLColor.parse(value);
|
|
34
|
+
if (res)
|
|
35
|
+
return res;
|
|
36
|
+
throw new Error(`Invalid color value: ${value}`);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Accepts either a color string or an existing {@link Color} and always returns a `Color`.
|
|
40
|
+
* Useful for normalizing props that accept both forms.
|
|
41
|
+
*/
|
|
42
|
+
export function normalizeColor(v) {
|
|
43
|
+
return typeof v === "string" ? parseColor(v) : v;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Returns the ordered channel triple for a given color space.
|
|
47
|
+
*
|
|
48
|
+
* - `"rgb"` → `["red", "green", "blue"]`
|
|
49
|
+
* - `"hsl"` → `["hue", "saturation", "lightness"]`
|
|
50
|
+
* - `"hsb"` → `["hue", "saturation", "brightness"]`
|
|
51
|
+
*/
|
|
52
|
+
export function getColorChannels(colorSpace) {
|
|
53
|
+
switch (colorSpace) {
|
|
54
|
+
case "rgb":
|
|
55
|
+
return RGBColor.colorChannels;
|
|
56
|
+
case "hsl":
|
|
57
|
+
return HSLColor.colorChannels;
|
|
58
|
+
case "hsb":
|
|
59
|
+
return HSBColor.colorChannels;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Normalizes a hue angle to the range `[0, 360]`.
|
|
64
|
+
* Exactly `360` is kept as-is so that a full-circle endpoint stays distinct from `0`.
|
|
65
|
+
*/
|
|
66
|
+
export function normalizeHue(hue) {
|
|
67
|
+
if (hue === 360)
|
|
68
|
+
return hue;
|
|
69
|
+
return ((hue % 360) + 360) % 360;
|
|
70
|
+
}
|
|
71
|
+
// Lightness threshold separating orange (L ≥ 0.68) from brown (L < 0.68) in OKLCH.
|
|
72
|
+
const ORANGE_LIGHTNESS_THRESHOLD = 0.68;
|
|
73
|
+
// Below this OKLCH lightness, yellow hues are labelled "yellow green" instead of "yellow".
|
|
74
|
+
const YELLOW_GREEN_LIGHTNESS_THRESHOLD = 0.85;
|
|
75
|
+
// OKLCH L ≤ this value is considered "dark" for the lightness descriptor.
|
|
76
|
+
const MAX_DARK_LIGHTNESS = 0.55;
|
|
77
|
+
// OKLCH chroma below this threshold is treated as achromatic (gray).
|
|
78
|
+
const GRAY_THRESHOLD = 0.001;
|
|
79
|
+
/**
|
|
80
|
+
* Ordered hue-segment table for `getOklchHue`. Each entry is `[startDegrees, hueName]`.
|
|
81
|
+
* A hue angle H belongs to segment i when `OKLCH_HUES[i][0] <= H < OKLCH_HUES[i+1][0]`.
|
|
82
|
+
* The list wraps: angles ≥ 349° fall back to `"pink"` (the implicit 360° endpoint).
|
|
83
|
+
*/
|
|
84
|
+
const OKLCH_HUES = [
|
|
85
|
+
[0, "pink"],
|
|
86
|
+
[15, "red"],
|
|
87
|
+
[48, "orange"],
|
|
88
|
+
[94, "yellow"],
|
|
89
|
+
[135, "green"],
|
|
90
|
+
[175, "cyan"],
|
|
91
|
+
[264, "blue"],
|
|
92
|
+
[284, "purple"],
|
|
93
|
+
[320, "magenta"],
|
|
94
|
+
[349, "pink"],
|
|
95
|
+
];
|
|
96
|
+
/** Formats `value` with the runtime locale (`undefined` = user's system locale). */
|
|
97
|
+
function formatNumber(value, options) {
|
|
98
|
+
return new Intl.NumberFormat(undefined, options).format(value);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Shared base providing concrete implementations of the channel-read/write, naming,
|
|
102
|
+
* and axis-resolution methods declared on {@link IColor}. Subclasses (`RGBColor`,
|
|
103
|
+
* `HSBColor`, `HSLColor`) supply format conversion and the channel-range /
|
|
104
|
+
* format-options API.
|
|
105
|
+
*
|
|
106
|
+
* Channel names are used directly as private field names on each subclass so that
|
|
107
|
+
* `getChannelValue` / `withChannelValue` can read and write them via string keying
|
|
108
|
+
* without a per-subclass switch statement.
|
|
109
|
+
*/
|
|
110
|
+
class Color {
|
|
111
|
+
/** Delegates to RGB since only `RGBColor` can pack channels directly into a 24-bit int. */
|
|
112
|
+
toHexInt() {
|
|
113
|
+
return this.toFormat("rgb").toHexInt();
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Reads a channel value by name. Channel name strings correspond directly to
|
|
117
|
+
* the private field names on each concrete subclass (e.g. `"red"` → `this.red`).
|
|
118
|
+
* The `@ts-expect-error` suppresses the untyped index-access warning.
|
|
119
|
+
*/
|
|
120
|
+
getChannelValue(channel) {
|
|
121
|
+
if (channel in this) {
|
|
122
|
+
// @ts-expect-error — channel names map to private fields (see class-level doc)
|
|
123
|
+
return this[channel];
|
|
124
|
+
}
|
|
125
|
+
throw new Error(`Unsupported color channel: ${channel}`);
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Returns a shallow clone of this color with one channel replaced.
|
|
129
|
+
* Clones first to preserve immutability, then writes via the same string-keyed
|
|
130
|
+
* approach as `getChannelValue`.
|
|
131
|
+
*/
|
|
132
|
+
withChannelValue(channel, value) {
|
|
133
|
+
if (channel in this) {
|
|
134
|
+
const x = this.clone();
|
|
135
|
+
// @ts-expect-error — see getChannelValue
|
|
136
|
+
x[channel] = value;
|
|
137
|
+
return x;
|
|
138
|
+
}
|
|
139
|
+
throw new Error(`Unsupported color channel: ${channel}`);
|
|
140
|
+
}
|
|
141
|
+
/** Returns the translation string for `channel` (e.g. `"Hue"`, `"Saturation"`). */
|
|
142
|
+
getChannelName(channel, translations) {
|
|
143
|
+
return translations[channel];
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Resolves the three channel axes used by a 2D color-area picker.
|
|
147
|
+
* `xChannel` and `yChannel` are caller-supplied (either may be omitted).
|
|
148
|
+
* `zChannel` is the remaining channel not already assigned to x or y.
|
|
149
|
+
* Omitted channels are filled in order from the color space's channel list.
|
|
150
|
+
*/
|
|
151
|
+
getColorSpaceAxes(xyChannels) {
|
|
152
|
+
const { xChannel, yChannel } = xyChannels;
|
|
153
|
+
const xCh = xChannel || this.getColorChannels().find(c => c !== yChannel);
|
|
154
|
+
const yCh = yChannel || this.getColorChannels().find(c => c !== xCh);
|
|
155
|
+
const zCh = this.getColorChannels().find(c => c !== xCh && c !== yCh);
|
|
156
|
+
return { xChannel: xCh, yChannel: yCh, zChannel: zCh };
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Produces a human-readable color description (e.g. `"dark vibrant blue"`) suitable
|
|
160
|
+
* for `aria-label` attributes. Uses OKLCH — a perceptually uniform space — so that
|
|
161
|
+
* lightness and chroma descriptors correspond to what the eye perceives.
|
|
162
|
+
*
|
|
163
|
+
* Pipeline:
|
|
164
|
+
* 1. Convert to OKLCH (L = perceived lightness 0–1, C = chroma, H = hue angle).
|
|
165
|
+
* 2. Short-circuit for near-white (L > 0.999) and near-black (L < 0.001).
|
|
166
|
+
* 3. Map hue angle to a named hue family via `getOklchHue` (handles orange/brown split,
|
|
167
|
+
* hue blending at segment midpoints, etc.).
|
|
168
|
+
* 4. Choose a chroma descriptor: `"pale"` or `"grayish"` for low-C, `"vibrant"` for high-C.
|
|
169
|
+
* 5. Choose a lightness descriptor: `"very dark"` / `"dark"` / `"light"` / `"very light"`.
|
|
170
|
+
* 6. Compose via `translations.colorName`. If alpha < 1, append the transparency percentage.
|
|
171
|
+
*/
|
|
172
|
+
getColorName(translations) {
|
|
173
|
+
const [initialL, c, h] = colorToOKLCH(this);
|
|
174
|
+
let l = initialL;
|
|
175
|
+
if (l > 0.999)
|
|
176
|
+
return translations.white;
|
|
177
|
+
if (l < 0.001)
|
|
178
|
+
return translations.black;
|
|
179
|
+
const [hue, newL] = this.getOklchHue(l, c, h, translations);
|
|
180
|
+
l = newL;
|
|
181
|
+
let lightness = "";
|
|
182
|
+
let chroma = "";
|
|
183
|
+
if (c <= 0.1 && c >= GRAY_THRESHOLD) {
|
|
184
|
+
chroma = l >= 0.7 ? "pale" : "grayish";
|
|
185
|
+
}
|
|
186
|
+
else if (c >= 0.15) {
|
|
187
|
+
chroma = "vibrant";
|
|
188
|
+
}
|
|
189
|
+
if (l < 0.3) {
|
|
190
|
+
lightness = "very dark";
|
|
191
|
+
}
|
|
192
|
+
else if (l < MAX_DARK_LIGHTNESS) {
|
|
193
|
+
lightness = "dark";
|
|
194
|
+
}
|
|
195
|
+
else if (l < 0.7) {
|
|
196
|
+
// no descriptor for mid-range lightness
|
|
197
|
+
}
|
|
198
|
+
else if (l < 0.85) {
|
|
199
|
+
lightness = "light";
|
|
200
|
+
}
|
|
201
|
+
else {
|
|
202
|
+
lightness = "very light";
|
|
203
|
+
}
|
|
204
|
+
// @ts-expect-error
|
|
205
|
+
if (chroma)
|
|
206
|
+
chroma = translations[chroma];
|
|
207
|
+
// @ts-expect-error
|
|
208
|
+
if (lightness)
|
|
209
|
+
lightness = translations[lightness];
|
|
210
|
+
const alpha = this.getChannelValue("alpha");
|
|
211
|
+
if (alpha < 1) {
|
|
212
|
+
const percentTransparent = formatNumber(1 - alpha, { style: "percent" });
|
|
213
|
+
return translations
|
|
214
|
+
.transparentColorName(lightness, chroma, hue, percentTransparent)
|
|
215
|
+
.replace(/\s+/g, " ")
|
|
216
|
+
.trim();
|
|
217
|
+
}
|
|
218
|
+
return translations.colorName(lightness, chroma, hue).replace(/\s+/g, " ").trim();
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Maps OKLCH `(L, C, H)` to a named hue family and optionally adjusts `L`.
|
|
222
|
+
*
|
|
223
|
+
* Special cases:
|
|
224
|
+
* - **Orange vs brown**: Hues in the orange segment (48–94°) are classified as
|
|
225
|
+
* `"brown"` when L < `ORANGE_LIGHTNESS_THRESHOLD`. For true orange, L is shifted
|
|
226
|
+
* down by the threshold so that the lightness descriptor still reads naturally.
|
|
227
|
+
* - **Yellow green**: Yellow (94–135°) reads as `"yellow green"` when L is below
|
|
228
|
+
* `YELLOW_GREEN_LIGHTNESS_THRESHOLD`.
|
|
229
|
+
* - **Hue blending**: When H falls in the upper half of a segment (past the midpoint
|
|
230
|
+
* toward the next hue), the name becomes a compound `"<current> <next>"` (e.g.
|
|
231
|
+
* `"blue purple"`), unless the two adjacent segment names are already the same
|
|
232
|
+
* (the pink wrap-around case).
|
|
233
|
+
* - **Achromatic fallback**: Returns `"gray"` immediately when C < `GRAY_THRESHOLD`.
|
|
234
|
+
*/
|
|
235
|
+
getOklchHue(l, c, h, translations) {
|
|
236
|
+
if (c < GRAY_THRESHOLD)
|
|
237
|
+
return [translations.gray, l];
|
|
238
|
+
for (let i = 0; i < OKLCH_HUES.length; i++) {
|
|
239
|
+
const [hue] = OKLCH_HUES[i];
|
|
240
|
+
let hueName = OKLCH_HUES[i][1];
|
|
241
|
+
const [nextHue, nextHueName] = OKLCH_HUES[i + 1] || [360, "pink"];
|
|
242
|
+
if (h >= hue && h < nextHue) {
|
|
243
|
+
if (hueName === "orange") {
|
|
244
|
+
if (l < ORANGE_LIGHTNESS_THRESHOLD) {
|
|
245
|
+
hueName = "brown";
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
// Shift L so mid-lightness orange doesn't get a "light" descriptor.
|
|
249
|
+
l = l - ORANGE_LIGHTNESS_THRESHOLD + MAX_DARK_LIGHTNESS;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (h > hue + (nextHue - hue) / 2 && hueName !== nextHueName) {
|
|
253
|
+
// Past the midpoint of the segment — blend toward the next hue.
|
|
254
|
+
hueName = `${hueName} ${nextHueName}`;
|
|
255
|
+
}
|
|
256
|
+
else if (hueName === "yellow" && l < YELLOW_GREEN_LIGHTNESS_THRESHOLD) {
|
|
257
|
+
hueName = "yellow green";
|
|
258
|
+
}
|
|
259
|
+
// @ts-expect-error — hueName is a dynamic key into translations
|
|
260
|
+
return [translations[hueName], l];
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
throw new Error("Unexpected hue");
|
|
264
|
+
}
|
|
265
|
+
/** Returns only the hue family name (e.g. `"blue"`) without lightness/chroma descriptors. */
|
|
266
|
+
getHueName(translations) {
|
|
267
|
+
const [l, c, h] = colorToOKLCH(this);
|
|
268
|
+
const [name] = this.getOklchHue(l, c, h, translations);
|
|
269
|
+
return name;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* RGB color with red/green/blue stored as integers in `[0, 255]` and alpha as a
|
|
274
|
+
* float in `[0, 1]`. This is the canonical representation — hex strings and `rgb()`
|
|
275
|
+
* strings parse directly into this class, and all other spaces delegate `toHexInt()`
|
|
276
|
+
* through an RGB conversion.
|
|
277
|
+
*/
|
|
278
|
+
class RGBColor extends Color {
|
|
279
|
+
red;
|
|
280
|
+
green;
|
|
281
|
+
blue;
|
|
282
|
+
alpha;
|
|
283
|
+
constructor(red, green, blue, alpha) {
|
|
284
|
+
super();
|
|
285
|
+
this.red = red;
|
|
286
|
+
this.green = green;
|
|
287
|
+
this.blue = blue;
|
|
288
|
+
this.alpha = alpha;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Parses hex (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`) and `rgb()`/`rgba()` strings.
|
|
292
|
+
* Returns `undefined` for non-matching input.
|
|
293
|
+
*
|
|
294
|
+
* Hex shorthand is expanded by doubling each nibble (`#abc` → `#aabbcc`).
|
|
295
|
+
* The alpha byte (if present in hex) is normalized from the `[0, 255]` range to `[0, 1]`.
|
|
296
|
+
* Both space-separated (`rgb(r g b / a)`) and comma-separated (`rgb(r, g, b)`) syntaxes
|
|
297
|
+
* are accepted. Tokens with a `%` suffix are converted: RGB channels to 0–255,
|
|
298
|
+
* alpha to a 0–1 fraction. Non-numeric or non-finite tokens reject the whole match.
|
|
299
|
+
*/
|
|
300
|
+
static parse(value) {
|
|
301
|
+
let colors = [];
|
|
302
|
+
if (/^#[\da-f]+$/i.test(value) && [4, 5, 7, 9].includes(value.length)) {
|
|
303
|
+
// Expand 3/4-digit shorthand by doubling each hex nibble.
|
|
304
|
+
const values = (value.length < 6 ? value.replace(/[^#]/gi, "$&$&") : value)
|
|
305
|
+
.slice(1)
|
|
306
|
+
.split("");
|
|
307
|
+
while (values.length > 0) {
|
|
308
|
+
colors.push(Number.parseInt(values.splice(0, 2).join(""), 16));
|
|
309
|
+
}
|
|
310
|
+
// Hex alpha is 0–255; normalize to 0–1.
|
|
311
|
+
colors[3] = colors[3] !== undefined ? colors[3] / 255 : undefined;
|
|
312
|
+
}
|
|
313
|
+
const match = value.match(/^rgba?\((.*)\)$/);
|
|
314
|
+
if (match?.[1]) {
|
|
315
|
+
// Normalize separators (comma, slash) to spaces, trim, then split on any
|
|
316
|
+
// run of whitespace so leading/trailing spaces don't produce empty tokens.
|
|
317
|
+
const tokens = match[1]
|
|
318
|
+
.replaceAll(/,|\//gu, " ")
|
|
319
|
+
.trim()
|
|
320
|
+
.split(/\s+/);
|
|
321
|
+
// Require exactly 3 (rgb) or 4 (rgba) tokens.
|
|
322
|
+
if (tokens.length !== 3 && tokens.length !== 4)
|
|
323
|
+
return undefined;
|
|
324
|
+
const parsed = [];
|
|
325
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
326
|
+
const token = tokens[i];
|
|
327
|
+
let num;
|
|
328
|
+
if (token.endsWith("%")) {
|
|
329
|
+
const pct = Number(token.slice(0, -1));
|
|
330
|
+
if (!Number.isFinite(pct))
|
|
331
|
+
return undefined;
|
|
332
|
+
// RGB channels: % of 255; alpha channel: % as 0–1 fraction.
|
|
333
|
+
num = i < 3 ? (pct / 100) * 255 : pct / 100;
|
|
334
|
+
}
|
|
335
|
+
else {
|
|
336
|
+
num = Number(token);
|
|
337
|
+
if (!Number.isFinite(num))
|
|
338
|
+
return undefined;
|
|
339
|
+
}
|
|
340
|
+
parsed.push(clamp(num, 0, i < 3 ? 255 : 1));
|
|
341
|
+
}
|
|
342
|
+
colors = parsed;
|
|
343
|
+
}
|
|
344
|
+
if (colors[0] === undefined || colors[1] === undefined || colors[2] === undefined) {
|
|
345
|
+
return undefined;
|
|
346
|
+
}
|
|
347
|
+
return colors.length < 3
|
|
348
|
+
? undefined
|
|
349
|
+
: new RGBColor(colors[0], colors[1], colors[2], colors[3] ?? 1);
|
|
350
|
+
}
|
|
351
|
+
toString(format = "css") {
|
|
352
|
+
switch (format) {
|
|
353
|
+
case "hex":
|
|
354
|
+
return `#${(this.red.toString(16).padStart(2, "0") +
|
|
355
|
+
this.green.toString(16).padStart(2, "0") +
|
|
356
|
+
this.blue.toString(16).padStart(2, "0")).toUpperCase()}`;
|
|
357
|
+
case "hexa":
|
|
358
|
+
return `#${(this.red.toString(16).padStart(2, "0") +
|
|
359
|
+
this.green.toString(16).padStart(2, "0") +
|
|
360
|
+
this.blue.toString(16).padStart(2, "0") +
|
|
361
|
+
Math.round(this.alpha * 255)
|
|
362
|
+
.toString(16)
|
|
363
|
+
.padStart(2, "0")).toUpperCase()}`;
|
|
364
|
+
case "css":
|
|
365
|
+
case "rgb":
|
|
366
|
+
return `rgb(${this.red}, ${this.green}, ${this.blue}${this.alpha !== 1 && this.alpha !== 100 ? ` / ${this.alpha}` : ""})`;
|
|
367
|
+
case "rgba":
|
|
368
|
+
return `rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`;
|
|
369
|
+
default:
|
|
370
|
+
return this.toFormat(format).toString(format);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
toFormat(format) {
|
|
374
|
+
switch (format) {
|
|
375
|
+
case "hex":
|
|
376
|
+
case "hexa":
|
|
377
|
+
case "rgb":
|
|
378
|
+
case "rgba":
|
|
379
|
+
return this;
|
|
380
|
+
case "hsb":
|
|
381
|
+
case "hsba":
|
|
382
|
+
return this.toHSB();
|
|
383
|
+
case "hsl":
|
|
384
|
+
case "hsla":
|
|
385
|
+
return this.toHSL();
|
|
386
|
+
default:
|
|
387
|
+
throw new Error(`Unsupported color conversion: rgb -> ${format}`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/** Packs red/green/blue into a 24-bit integer via bitwise shifts (alpha is not included). */
|
|
391
|
+
toHexInt() {
|
|
392
|
+
return (this.red << 16) | (this.green << 8) | this.blue;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Standard RGB → HSB conversion.
|
|
396
|
+
* brightness = max(r, g, b); saturation = chroma / brightness;
|
|
397
|
+
* hue is derived from which primary sits at the maximum.
|
|
398
|
+
*/
|
|
399
|
+
toHSB() {
|
|
400
|
+
const red = this.red / 255;
|
|
401
|
+
const green = this.green / 255;
|
|
402
|
+
const blue = this.blue / 255;
|
|
403
|
+
const min = Math.min(red, green, blue);
|
|
404
|
+
const brightness = Math.max(red, green, blue);
|
|
405
|
+
const chroma = brightness - min;
|
|
406
|
+
const saturation = brightness === 0 ? 0 : chroma / brightness;
|
|
407
|
+
let hue = 0;
|
|
408
|
+
if (chroma !== 0) {
|
|
409
|
+
switch (brightness) {
|
|
410
|
+
case red:
|
|
411
|
+
hue = (green - blue) / chroma + (green < blue ? 6 : 0);
|
|
412
|
+
break;
|
|
413
|
+
case green:
|
|
414
|
+
hue = (blue - red) / chroma + 2;
|
|
415
|
+
break;
|
|
416
|
+
case blue:
|
|
417
|
+
hue = (red - green) / chroma + 4;
|
|
418
|
+
break;
|
|
419
|
+
}
|
|
420
|
+
hue /= 6;
|
|
421
|
+
}
|
|
422
|
+
return new HSBColor(toFixedNumber(hue * 360, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(brightness * 100, 2), this.alpha);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Standard RGB → HSL conversion.
|
|
426
|
+
* lightness = (max + min) / 2;
|
|
427
|
+
* saturation = chroma / (1 − |2L − 1|);
|
|
428
|
+
* hue uses the same sector formula as `toHSB`.
|
|
429
|
+
*/
|
|
430
|
+
toHSL() {
|
|
431
|
+
const red = this.red / 255;
|
|
432
|
+
const green = this.green / 255;
|
|
433
|
+
const blue = this.blue / 255;
|
|
434
|
+
const min = Math.min(red, green, blue);
|
|
435
|
+
const max = Math.max(red, green, blue);
|
|
436
|
+
const lightness = (max + min) / 2;
|
|
437
|
+
const chroma = max - min;
|
|
438
|
+
let hue;
|
|
439
|
+
let saturation;
|
|
440
|
+
if (chroma === 0) {
|
|
441
|
+
hue = saturation = 0;
|
|
442
|
+
}
|
|
443
|
+
else {
|
|
444
|
+
saturation = chroma / (lightness < 0.5 ? max + min : 2 - max - min);
|
|
445
|
+
switch (max) {
|
|
446
|
+
case red:
|
|
447
|
+
hue = (green - blue) / chroma + (green < blue ? 6 : 0);
|
|
448
|
+
break;
|
|
449
|
+
case green:
|
|
450
|
+
hue = (blue - red) / chroma + 2;
|
|
451
|
+
break;
|
|
452
|
+
default:
|
|
453
|
+
hue = (red - green) / chroma + 4;
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
hue /= 6;
|
|
457
|
+
}
|
|
458
|
+
return new HSLColor(toFixedNumber(hue * 360, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(lightness * 100, 2), this.alpha);
|
|
459
|
+
}
|
|
460
|
+
clone() {
|
|
461
|
+
return new RGBColor(this.red, this.green, this.blue, this.alpha);
|
|
462
|
+
}
|
|
463
|
+
getChannelRange(channel) {
|
|
464
|
+
switch (channel) {
|
|
465
|
+
case "red":
|
|
466
|
+
case "green":
|
|
467
|
+
case "blue":
|
|
468
|
+
return { minValue: 0x0, maxValue: 0xff, step: 0x1, pageSize: 0x11 };
|
|
469
|
+
case "alpha":
|
|
470
|
+
return { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 };
|
|
471
|
+
default:
|
|
472
|
+
throw new Error(`Unknown color channel: ${channel}`);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
getChannelFormatOptions(channel) {
|
|
476
|
+
switch (channel) {
|
|
477
|
+
case "red":
|
|
478
|
+
case "green":
|
|
479
|
+
case "blue":
|
|
480
|
+
return { style: "decimal" };
|
|
481
|
+
case "alpha":
|
|
482
|
+
return { style: "percent", maximumFractionDigits: 2 };
|
|
483
|
+
default:
|
|
484
|
+
throw new Error(`Unknown color channel: ${channel}`);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
formatChannelValue(channel) {
|
|
488
|
+
return formatNumber(this.getChannelValue(channel), this.getChannelFormatOptions(channel));
|
|
489
|
+
}
|
|
490
|
+
getColorSpace() {
|
|
491
|
+
return "rgb";
|
|
492
|
+
}
|
|
493
|
+
static colorChannels = ["red", "green", "blue"];
|
|
494
|
+
getColorChannels() {
|
|
495
|
+
return RGBColor.colorChannels;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
// Matches `hsb(h, s%, b%)` and `hsba(h, s%, b%, a)`.
|
|
499
|
+
// Components may be comma- or space-separated; values may be signed or decimal.
|
|
500
|
+
const HSB_REGEX = /hsb\(([-+]?\d+(?:\.\d+)?(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%)\)|hsba\(([-+]?\d+(?:\.\d+)?(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?)\)/;
|
|
501
|
+
/**
|
|
502
|
+
* HSB (Hue–Saturation–Brightness) color, also known as HSV (Hue–Saturation–Value).
|
|
503
|
+
* Hue is in degrees `[0, 360]`; saturation and brightness are percentages `[0, 100]`;
|
|
504
|
+
* alpha is a float `[0, 1]`.
|
|
505
|
+
*/
|
|
506
|
+
class HSBColor extends Color {
|
|
507
|
+
hue;
|
|
508
|
+
saturation;
|
|
509
|
+
brightness;
|
|
510
|
+
alpha;
|
|
511
|
+
constructor(hue, saturation, brightness, alpha) {
|
|
512
|
+
super();
|
|
513
|
+
this.hue = hue;
|
|
514
|
+
this.saturation = saturation;
|
|
515
|
+
this.brightness = brightness;
|
|
516
|
+
this.alpha = alpha;
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Parses `hsb(h, s%, b%)` and `hsba(h, s%, b%, a)` strings via `HSB_REGEX`.
|
|
520
|
+
* Returns `undefined` for non-matching input.
|
|
521
|
+
* Hue is normalised with `normalizeHue`; saturation/brightness are clamped to 0–100;
|
|
522
|
+
* alpha defaults to 1 when absent.
|
|
523
|
+
*/
|
|
524
|
+
static parse(value) {
|
|
525
|
+
let m;
|
|
526
|
+
if ((m = value.match(HSB_REGEX))) {
|
|
527
|
+
const [h, s, b, a] = (m[1] ?? m[2])
|
|
528
|
+
.split(/[,\s]+/)
|
|
529
|
+
.filter(Boolean)
|
|
530
|
+
.map(n => Number(n.trim().replace("%", "")));
|
|
531
|
+
if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(b))
|
|
532
|
+
return undefined;
|
|
533
|
+
if (a !== undefined && !Number.isFinite(a))
|
|
534
|
+
return undefined;
|
|
535
|
+
return new HSBColor(normalizeHue(h), clamp(s, 0, 100), clamp(b, 0, 100), clamp(a ?? 1, 0, 1));
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
toString(format = "css") {
|
|
539
|
+
switch (format) {
|
|
540
|
+
case "css":
|
|
541
|
+
// HSB is not a native CSS format; fall back to HSL for browser compatibility.
|
|
542
|
+
return this.toHSL().toString("css");
|
|
543
|
+
case "hex":
|
|
544
|
+
return this.toRGB().toString("hex");
|
|
545
|
+
case "hexa":
|
|
546
|
+
return this.toRGB().toString("hexa");
|
|
547
|
+
case "hsb":
|
|
548
|
+
return `hsb(${this.hue} ${toFixedNumber(this.saturation, 2)}% ${toFixedNumber(this.brightness, 2)}%)`;
|
|
549
|
+
case "hsba":
|
|
550
|
+
return `hsba(${this.hue} ${toFixedNumber(this.saturation, 2)}% ${toFixedNumber(this.brightness, 2)}% ${this.alpha})`;
|
|
551
|
+
default:
|
|
552
|
+
return this.toFormat(format).toString(format);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
toFormat(format) {
|
|
556
|
+
switch (format) {
|
|
557
|
+
case "hsb":
|
|
558
|
+
case "hsba":
|
|
559
|
+
return this;
|
|
560
|
+
case "hsl":
|
|
561
|
+
case "hsla":
|
|
562
|
+
return this.toHSL();
|
|
563
|
+
case "rgb":
|
|
564
|
+
case "rgba":
|
|
565
|
+
return this.toRGB();
|
|
566
|
+
default:
|
|
567
|
+
throw new Error(`Unsupported color conversion: hsb -> ${format}`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* HSB → HSL conversion:
|
|
572
|
+
* L = B × (1 − S/2);
|
|
573
|
+
* S_hsl = (B − L) / min(L, 1 − L) (0 at achromatic extremes)
|
|
574
|
+
*/
|
|
575
|
+
toHSL() {
|
|
576
|
+
let saturation = this.saturation / 100;
|
|
577
|
+
const brightness = this.brightness / 100;
|
|
578
|
+
const lightness = brightness * (1 - saturation / 2);
|
|
579
|
+
saturation =
|
|
580
|
+
lightness === 0 || lightness === 1
|
|
581
|
+
? 0
|
|
582
|
+
: (brightness - lightness) / Math.min(lightness, 1 - lightness);
|
|
583
|
+
return new HSLColor(toFixedNumber(this.hue, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(lightness * 100, 2), this.alpha);
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* HSB → RGB using the compact HSV formula.
|
|
587
|
+
* `fn(n)` evaluates one channel:
|
|
588
|
+
* channel = B − S·B · clamp((n + H/60) mod 6, 0, 1)
|
|
589
|
+
* where n=5 → red, n=3 → green, n=1 → blue.
|
|
590
|
+
*/
|
|
591
|
+
toRGB() {
|
|
592
|
+
const hue = this.hue;
|
|
593
|
+
const saturation = this.saturation / 100;
|
|
594
|
+
const brightness = this.brightness / 100;
|
|
595
|
+
const fn = (n, k = (n + hue / 60) % 6) => brightness - saturation * brightness * Math.max(Math.min(k, 4 - k, 1), 0);
|
|
596
|
+
return new RGBColor(Math.round(fn(5) * 255), Math.round(fn(3) * 255), Math.round(fn(1) * 255), this.alpha);
|
|
597
|
+
}
|
|
598
|
+
clone() {
|
|
599
|
+
return new HSBColor(this.hue, this.saturation, this.brightness, this.alpha);
|
|
600
|
+
}
|
|
601
|
+
getChannelRange(channel) {
|
|
602
|
+
switch (channel) {
|
|
603
|
+
case "hue":
|
|
604
|
+
return { minValue: 0, maxValue: 360, step: 1, pageSize: 15 };
|
|
605
|
+
case "saturation":
|
|
606
|
+
case "brightness":
|
|
607
|
+
return { minValue: 0, maxValue: 100, step: 1, pageSize: 10 };
|
|
608
|
+
case "alpha":
|
|
609
|
+
return { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 };
|
|
610
|
+
default:
|
|
611
|
+
throw new Error(`Unknown color channel: ${channel}`);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
getChannelFormatOptions(channel) {
|
|
615
|
+
switch (channel) {
|
|
616
|
+
case "hue":
|
|
617
|
+
return { style: "unit", unit: "degree", unitDisplay: "narrow" };
|
|
618
|
+
case "saturation":
|
|
619
|
+
case "brightness":
|
|
620
|
+
case "alpha":
|
|
621
|
+
return { style: "percent", maximumFractionDigits: 2 };
|
|
622
|
+
default:
|
|
623
|
+
throw new Error(`Unknown color channel: ${channel}`);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
formatChannelValue(channel) {
|
|
627
|
+
let value = this.getChannelValue(channel);
|
|
628
|
+
// saturation/brightness are stored as 0–100 but formatted as 0–1 percentages
|
|
629
|
+
if (channel === "saturation" || channel === "brightness")
|
|
630
|
+
value /= 100;
|
|
631
|
+
return formatNumber(value, this.getChannelFormatOptions(channel));
|
|
632
|
+
}
|
|
633
|
+
getColorSpace() {
|
|
634
|
+
return "hsb";
|
|
635
|
+
}
|
|
636
|
+
static colorChannels = [
|
|
637
|
+
"hue",
|
|
638
|
+
"saturation",
|
|
639
|
+
"brightness",
|
|
640
|
+
];
|
|
641
|
+
getColorChannels() {
|
|
642
|
+
return HSBColor.colorChannels;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
// Matches `hsl(h, s%, l%)` / `hsl(h s% l% / a)` and `hsla(h, s%, l%, a)` / `hsla(h s% l% / a)`.
|
|
646
|
+
// Components may be comma- or space-separated; the alpha separator also accepts `/` (CSS Color 4).
|
|
647
|
+
const HSL_REGEX = /hsl\(([-+]?\d+(?:\.\d+)?(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:(?:\s*[,/]\s*|\s+)[-+]?\d+(?:\.\d+)?)?)\)|hsla\(([-+]?\d+(?:\.\d+)?(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?%(?:\s*[,/]\s*|\s+)[-+]?\d+(?:\.\d+)?)\)/;
|
|
648
|
+
/**
|
|
649
|
+
* HSL (Hue–Saturation–Lightness) color — the native CSS color notation.
|
|
650
|
+
* Hue is in degrees `[0, 360]`; saturation and lightness are percentages `[0, 100]`;
|
|
651
|
+
* alpha is a float `[0, 1]`.
|
|
652
|
+
*/
|
|
653
|
+
class HSLColor extends Color {
|
|
654
|
+
hue;
|
|
655
|
+
saturation;
|
|
656
|
+
lightness;
|
|
657
|
+
alpha;
|
|
658
|
+
constructor(hue, saturation, lightness, alpha) {
|
|
659
|
+
super();
|
|
660
|
+
this.hue = hue;
|
|
661
|
+
this.saturation = saturation;
|
|
662
|
+
this.lightness = lightness;
|
|
663
|
+
this.alpha = alpha;
|
|
664
|
+
}
|
|
665
|
+
/**
|
|
666
|
+
* Parses `hsl(h, s%, l%)` and `hsla(h, s%, l%, a)` strings via `HSL_REGEX`.
|
|
667
|
+
* Returns `undefined` for non-matching input.
|
|
668
|
+
* Hue is normalised with `normalizeHue`; saturation/lightness are clamped to 0–100;
|
|
669
|
+
* alpha defaults to 1 when absent.
|
|
670
|
+
*/
|
|
671
|
+
static parse(value) {
|
|
672
|
+
let m;
|
|
673
|
+
if ((m = value.match(HSL_REGEX))) {
|
|
674
|
+
// Replace `/` (CSS Color 4 alpha separator) with a space before splitting.
|
|
675
|
+
const [h, s, l, a] = (m[1] ?? m[2])
|
|
676
|
+
.replace(/\//g, " ")
|
|
677
|
+
.split(/[,\s]+/)
|
|
678
|
+
.filter(Boolean)
|
|
679
|
+
.map(n => Number(n.trim().replace("%", "")));
|
|
680
|
+
if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l))
|
|
681
|
+
return undefined;
|
|
682
|
+
if (a !== undefined && !Number.isFinite(a))
|
|
683
|
+
return undefined;
|
|
684
|
+
return new HSLColor(normalizeHue(h), clamp(s, 0, 100), clamp(l, 0, 100), clamp(a ?? 1, 0, 1));
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
toString(format = "css") {
|
|
688
|
+
switch (format) {
|
|
689
|
+
case "hex":
|
|
690
|
+
return this.toRGB().toString("hex");
|
|
691
|
+
case "hexa":
|
|
692
|
+
return this.toRGB().toString("hexa");
|
|
693
|
+
case "hsl":
|
|
694
|
+
return `hsl(${this.hue} ${toFixedNumber(this.saturation, 2)}% ${toFixedNumber(this.lightness, 2)}%${this.alpha !== 1 && this.alpha !== 100 ? ` / ${this.alpha}` : ""})`;
|
|
695
|
+
case "css":
|
|
696
|
+
case "hsla":
|
|
697
|
+
return `hsla(${this.hue} ${toFixedNumber(this.saturation, 2)}% ${toFixedNumber(this.lightness, 2)}% / ${this.alpha})`;
|
|
698
|
+
default:
|
|
699
|
+
return this.toFormat(format).toString(format);
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
toFormat(format) {
|
|
703
|
+
switch (format) {
|
|
704
|
+
case "hsl":
|
|
705
|
+
case "hsla":
|
|
706
|
+
return this;
|
|
707
|
+
case "hsb":
|
|
708
|
+
case "hsba":
|
|
709
|
+
return this.toHSB();
|
|
710
|
+
case "rgb":
|
|
711
|
+
case "rgba":
|
|
712
|
+
return this.toRGB();
|
|
713
|
+
default:
|
|
714
|
+
throw new Error(`Unsupported color conversion: hsl -> ${format}`);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* HSL → HSB conversion:
|
|
719
|
+
* B = L + S·min(L, 1 − L);
|
|
720
|
+
* S_hsb = 2·(1 − L/B) (0 when B = 0)
|
|
721
|
+
*/
|
|
722
|
+
toHSB() {
|
|
723
|
+
let saturation = this.saturation / 100;
|
|
724
|
+
const lightness = this.lightness / 100;
|
|
725
|
+
const brightness = lightness + saturation * Math.min(lightness, 1 - lightness);
|
|
726
|
+
saturation = brightness === 0 ? 0 : 2 * (1 - lightness / brightness);
|
|
727
|
+
return new HSBColor(toFixedNumber(this.hue, 2), toFixedNumber(saturation * 100, 2), toFixedNumber(brightness * 100, 2), this.alpha);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* HSL → RGB using the smooth HSL formula.
|
|
731
|
+
* `a = S·min(L, 1−L)` is the chroma amplitude.
|
|
732
|
+
* `fn(n)` evaluates one channel:
|
|
733
|
+
* channel = L − a·clamp((n + H/30) mod 12 − 3, −1, 1)
|
|
734
|
+
* where n=0 → red, n=8 → green, n=4 → blue.
|
|
735
|
+
*/
|
|
736
|
+
toRGB() {
|
|
737
|
+
const hue = this.hue;
|
|
738
|
+
const saturation = this.saturation / 100;
|
|
739
|
+
const lightness = this.lightness / 100;
|
|
740
|
+
const a = saturation * Math.min(lightness, 1 - lightness);
|
|
741
|
+
const fn = (n, k = (n + hue / 30) % 12) => lightness - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
|
|
742
|
+
return new RGBColor(Math.round(fn(0) * 255), Math.round(fn(8) * 255), Math.round(fn(4) * 255), this.alpha);
|
|
743
|
+
}
|
|
744
|
+
clone() {
|
|
745
|
+
return new HSLColor(this.hue, this.saturation, this.lightness, this.alpha);
|
|
746
|
+
}
|
|
747
|
+
getChannelRange(channel) {
|
|
748
|
+
switch (channel) {
|
|
749
|
+
case "hue":
|
|
750
|
+
return { minValue: 0, maxValue: 360, step: 1, pageSize: 15 };
|
|
751
|
+
case "saturation":
|
|
752
|
+
case "lightness":
|
|
753
|
+
return { minValue: 0, maxValue: 100, step: 1, pageSize: 10 };
|
|
754
|
+
case "alpha":
|
|
755
|
+
return { minValue: 0, maxValue: 1, step: 0.01, pageSize: 0.1 };
|
|
756
|
+
default:
|
|
757
|
+
throw new Error(`Unknown color channel: ${channel}`);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
getChannelFormatOptions(channel) {
|
|
761
|
+
switch (channel) {
|
|
762
|
+
case "hue":
|
|
763
|
+
return { style: "unit", unit: "degree", unitDisplay: "narrow" };
|
|
764
|
+
case "saturation":
|
|
765
|
+
case "lightness":
|
|
766
|
+
case "alpha":
|
|
767
|
+
return { style: "percent", maximumFractionDigits: 2 };
|
|
768
|
+
default:
|
|
769
|
+
throw new Error(`Unknown color channel: ${channel}`);
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
formatChannelValue(channel) {
|
|
773
|
+
let value = this.getChannelValue(channel);
|
|
774
|
+
// saturation/lightness are stored as 0–100 but formatted as 0–1 percentages
|
|
775
|
+
if (channel === "saturation" || channel === "lightness")
|
|
776
|
+
value /= 100;
|
|
777
|
+
return formatNumber(value, this.getChannelFormatOptions(channel));
|
|
778
|
+
}
|
|
779
|
+
getColorSpace() {
|
|
780
|
+
return "hsl";
|
|
781
|
+
}
|
|
782
|
+
static colorChannels = [
|
|
783
|
+
"hue",
|
|
784
|
+
"saturation",
|
|
785
|
+
"lightness",
|
|
786
|
+
];
|
|
787
|
+
getColorChannels() {
|
|
788
|
+
return HSLColor.colorChannels;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Converts any {@link Color} to OKLCH `[L, C, H]` — a perceptually uniform space
|
|
793
|
+
* where L is perceived lightness (0–1), C is chroma (≥ 0), and H is a hue angle (0–360).
|
|
794
|
+
*
|
|
795
|
+
* Full pipeline: sRGB bytes → linear sRGB (gamma-expand) → CIE XYZ D65 → OKLab → OKLCH.
|
|
796
|
+
*
|
|
797
|
+
* @see https://www.w3.org/TR/css-color-4/#color-conversion-code
|
|
798
|
+
*/
|
|
799
|
+
export function colorToOKLCH(color) {
|
|
800
|
+
const rgb = color.toFormat("rgb");
|
|
801
|
+
let red = rgb.getChannelValue("red") / 255;
|
|
802
|
+
let green = rgb.getChannelValue("green") / 255;
|
|
803
|
+
let blue = rgb.getChannelValue("blue") / 255;
|
|
804
|
+
[red, green, blue] = lin_sRGB(red, green, blue);
|
|
805
|
+
const [x, y, z] = lin_sRGB_to_XYZ(red, green, blue);
|
|
806
|
+
const [l, a, b] = XYZ_to_OKLab(x, y, z);
|
|
807
|
+
return OKLab_to_OKLCH(l, a, b);
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Converts OKLab `(L, a, b)` to cylindrical OKLCH `(L, C, H)`.
|
|
811
|
+
* C = sqrt(a² + b²); H = atan2(b, a) in degrees, normalised to [0, 360).
|
|
812
|
+
*/
|
|
813
|
+
function OKLab_to_OKLCH(l, a, b) {
|
|
814
|
+
const hue = (Math.atan2(b, a) * 180) / Math.PI;
|
|
815
|
+
return [l, Math.sqrt(a ** 2 + b ** 2), hue >= 0 ? hue : hue + 360];
|
|
816
|
+
}
|
|
817
|
+
/** Applies sRGB gamma expansion component-wise, converting display-encoded sRGB to linear light. */
|
|
818
|
+
function lin_sRGB(r, g, b) {
|
|
819
|
+
return [lin_sRGB_component(r), lin_sRGB_component(g), lin_sRGB_component(b)];
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* IEC 61966-2-1 sRGB gamma expansion (the inverse EOTF).
|
|
823
|
+
* Values in the linear region (|v| ≤ 0.04045) are divided by 12.92.
|
|
824
|
+
* Larger values follow the power curve: sign(v) · ((|v| + 0.055) / 1.055)^2.4.
|
|
825
|
+
*/
|
|
826
|
+
function lin_sRGB_component(val) {
|
|
827
|
+
const sign = val < 0 ? -1 : 1;
|
|
828
|
+
const abs = Math.abs(val);
|
|
829
|
+
if (abs <= 0.04045)
|
|
830
|
+
return val / 12.92;
|
|
831
|
+
return sign * ((abs + 0.055) / 1.055) ** 2.4;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Transforms linear sRGB to CIE XYZ adapted to the D65 white point.
|
|
835
|
+
* The matrix coefficients are expressed as exact rational fractions (as in the CSS Color 4
|
|
836
|
+
* spec) to avoid floating-point rounding accumulation that can occur with decimal literals.
|
|
837
|
+
*/
|
|
838
|
+
function lin_sRGB_to_XYZ(r, g, b) {
|
|
839
|
+
const M = [
|
|
840
|
+
506752 / 1228815,
|
|
841
|
+
87881 / 245763,
|
|
842
|
+
12673 / 70218,
|
|
843
|
+
87098 / 409605,
|
|
844
|
+
175762 / 245763,
|
|
845
|
+
12673 / 175545,
|
|
846
|
+
7918 / 409605,
|
|
847
|
+
87881 / 737289,
|
|
848
|
+
1001167 / 1053270,
|
|
849
|
+
];
|
|
850
|
+
return multiplyMatrix(M, r, g, b);
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Converts CIE XYZ to OKLab via Björn Ottosson's two-step LMS approach:
|
|
854
|
+
* 1. XYZ → LMS using a linear matrix (XYZtoLMS).
|
|
855
|
+
* 2. Cube-root each LMS component (perceptual non-linearity).
|
|
856
|
+
* 3. LMS^(1/3) → OKLab using a second linear matrix (LMStoOKLab).
|
|
857
|
+
*
|
|
858
|
+
* The result is a perceptually uniform Lab space where equal Euclidean distances
|
|
859
|
+
* correspond to equal perceived color differences.
|
|
860
|
+
*
|
|
861
|
+
* @see https://bottosson.github.io/posts/oklab/
|
|
862
|
+
*/
|
|
863
|
+
function XYZ_to_OKLab(x, y, z) {
|
|
864
|
+
const XYZtoLMS = [
|
|
865
|
+
0.819022437996703, 0.3619062600528904, -0.1288737815209879, 0.0329836539323885,
|
|
866
|
+
0.9292868615863434, 0.0361446663506424, 0.0481771893596242, 0.2642395317527308,
|
|
867
|
+
0.6335478284694309,
|
|
868
|
+
];
|
|
869
|
+
const LMStoOKLab = [
|
|
870
|
+
0.210454268309314, 0.7936177747023054, -0.0040720430116193, 1.9779985324311684,
|
|
871
|
+
-2.4285922420485799, 0.450593709617411, 0.0259040424655478, 0.7827717124575296,
|
|
872
|
+
-0.8086757549230774,
|
|
873
|
+
];
|
|
874
|
+
const [a, b, c] = multiplyMatrix(XYZtoLMS, x, y, z);
|
|
875
|
+
return multiplyMatrix(LMStoOKLab, Math.cbrt(a), Math.cbrt(b), Math.cbrt(c));
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Multiplies a flat row-major 3×3 matrix `m` by the column vector `[x, y, z]`.
|
|
879
|
+
* Layout: `m = [m00, m01, m02, m10, m11, m12, m20, m21, m22]`.
|
|
880
|
+
*/
|
|
881
|
+
function multiplyMatrix(m, x, y, z) {
|
|
882
|
+
return [
|
|
883
|
+
m[0] * x + m[1] * y + m[2] * z,
|
|
884
|
+
m[3] * x + m[4] * y + m[5] * z,
|
|
885
|
+
m[6] * x + m[7] * y + m[8] * z,
|
|
886
|
+
];
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* Rounds `value` to `digits` decimal places in `base`.
|
|
890
|
+
* Uses integer scaling instead of `toFixed` to avoid floating-point string round-trips.
|
|
891
|
+
*/
|
|
892
|
+
function toFixedNumber(value, digits, base = 10) {
|
|
893
|
+
const pow = base ** digits;
|
|
894
|
+
return Math.round(value * pow) / pow;
|
|
895
|
+
}
|