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