@sardine/colour 2.4.0 → 4.0.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/dist/index.cjs CHANGED
@@ -1,646 +1,1081 @@
1
- "use strict";
2
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/util/namedCSSColours.ts
3
+ /**
4
+ * Named list from https://developer.mozilla.org/en-US/docs/Web/CSS/named-color
5
+ */
6
+ var namedCSSColours = new Map([
7
+ ["aliceblue", "#f0f8ff"],
8
+ ["antiquewhite", "#faebd7"],
9
+ ["aqua", "#00ffff"],
10
+ ["aquamarine", "#7fffd4"],
11
+ ["azure", "#f0ffff"],
12
+ ["beige", "#f5f5dc"],
13
+ ["bisque", "#ffe4c4"],
14
+ ["black", "#000000"],
15
+ ["blanchedalmond", "#ffebcd"],
16
+ ["blue", "#0000ff"],
17
+ ["blueviolet", "#8a2be2"],
18
+ ["brown", "#a52a2a"],
19
+ ["burlywood", "#deb887"],
20
+ ["cadetblue", "#5f9ea0"],
21
+ ["chartreuse", "#7fff00"],
22
+ ["chocolate", "#d2691e"],
23
+ ["coral", "#ff7f50"],
24
+ ["cornflowerblue", "#6495ed"],
25
+ ["cornsilk", "#fff8dc"],
26
+ ["crimson", "#dc143c"],
27
+ ["cyan", "#00ffff"],
28
+ ["darkblue", "#00008b"],
29
+ ["darkcyan", "#008b8b"],
30
+ ["darkgoldenrod", "#b8860b"],
31
+ ["darkgray", "#a9a9a9"],
32
+ ["darkgreen", "#006400"],
33
+ ["darkgrey", "#a9a9a9"],
34
+ ["darkkhaki", "#bdb76b"],
35
+ ["darkmagenta", "#8b008b"],
36
+ ["darkolivegreen", "#556b2f"],
37
+ ["darkorange", "#ff8c00"],
38
+ ["darkorchid", "#9932cc"],
39
+ ["darkred", "#8b0000"],
40
+ ["darksalmon", "#e9967a"],
41
+ ["darkseagreen", "#8fbc8f"],
42
+ ["darkslateblue", "#483d8b"],
43
+ ["darkslategray", "#2f4f4f"],
44
+ ["darkslategrey", "#2f4f4f"],
45
+ ["darkturquoise", "#00ced1"],
46
+ ["darkviolet", "#9400d3"],
47
+ ["deeppink", "#ff1493"],
48
+ ["deepskyblue", "#00bfff"],
49
+ ["dimgray", "#696969"],
50
+ ["dimgrey", "#696969"],
51
+ ["dodgerblue", "#1e90ff"],
52
+ ["firebrick", "#b22222"],
53
+ ["floralwhite", "#fffaf0"],
54
+ ["forestgreen", "#228b22"],
55
+ ["fuchsia", "#ff00ff"],
56
+ ["gainsboro", "#dcdcdc"],
57
+ ["ghostwhite", "#f8f8ff"],
58
+ ["gold", "#ffd700"],
59
+ ["goldenrod", "#daa520"],
60
+ ["gray", "#808080"],
61
+ ["green", "#008000"],
62
+ ["greenyellow", "#adff2f"],
63
+ ["grey", "#808080"],
64
+ ["honeydew", "#f0fff0"],
65
+ ["hotpink", "#ff69b4"],
66
+ ["indianred", "#cd5c5c"],
67
+ ["indigo", "#4b0082"],
68
+ ["ivory", "#fffff0"],
69
+ ["khaki", "#f0e68c"],
70
+ ["lavender", "#e6e6fa"],
71
+ ["lavenderblush", "#fff0f5"],
72
+ ["lawngreen", "#7cfc00"],
73
+ ["lemonchiffon", "#fffacd"],
74
+ ["lightblue", "#add8e6"],
75
+ ["lightcoral", "#f08080"],
76
+ ["lightcyan", "#e0ffff"],
77
+ ["lightgoldenrodyellow", "#fafad2"],
78
+ ["lightgray", "#d3d3d3"],
79
+ ["lightgreen", "#90ee90"],
80
+ ["lightgrey", "#d3d3d3"],
81
+ ["lightpink", "#ffb6c1"],
82
+ ["lightsalmon", "#ffa07a"],
83
+ ["lightseagreen", "#20b2aa"],
84
+ ["lightskyblue", "#87cefa"],
85
+ ["lightslategray", "#778899"],
86
+ ["lightslategrey", "#778899"],
87
+ ["lightsteelblue", "#b0c4de"],
88
+ ["lightyellow", "#ffffe0"],
89
+ ["lime", "#00ff00"],
90
+ ["limegreen", "#32cd32"],
91
+ ["linen", "#faf0e6"],
92
+ ["magenta", "#ff00ff"],
93
+ ["maroon", "#800000"],
94
+ ["mediumaquamarine", "#66cdaa"],
95
+ ["mediumblue", "#0000cd"],
96
+ ["mediumorchid", "#ba55d3"],
97
+ ["mediumpurple", "#9370db"],
98
+ ["mediumseagreen", "#3cb371"],
99
+ ["mediumslateblue", "#7b68ee"],
100
+ ["mediumspringgreen", "#00fa9a"],
101
+ ["mediumturquoise", "#48d1cc"],
102
+ ["mediumvioletred", "#c71585"],
103
+ ["midnightblue", "#191970"],
104
+ ["mintcream", "#f5fffa"],
105
+ ["mistyrose", "#ffe4e1"],
106
+ ["moccasin", "#ffe4b5"],
107
+ ["navajowhite", "#ffdead"],
108
+ ["navy", "#000080"],
109
+ ["oldlace", "#fdf5e6"],
110
+ ["olive", "#808000"],
111
+ ["olivedrab", "#6b8e23"],
112
+ ["orange", "#ffa500"],
113
+ ["orangered", "#ff4500"],
114
+ ["orchid", "#da70d6"],
115
+ ["palegoldenrod", "#eee8aa"],
116
+ ["palegreen", "#98fb98"],
117
+ ["paleturquoise", "#afeeee"],
118
+ ["palevioletred", "#db7093"],
119
+ ["papayawhip", "#ffefd5"],
120
+ ["peachpuff", "#ffdab9"],
121
+ ["peru", "#cd853f"],
122
+ ["pink", "#ffc0cb"],
123
+ ["plum", "#dda0dd"],
124
+ ["powderblue", "#b0e0e6"],
125
+ ["purple", "#800080"],
126
+ ["rebeccapurple", "#663399"],
127
+ ["red", "#ff0000"],
128
+ ["rosybrown", "#bc8f8f"],
129
+ ["royalblue", "#4169e1"],
130
+ ["saddlebrown", "#8b4513"],
131
+ ["salmon", "#fa8072"],
132
+ ["sandybrown", "#f4a460"],
133
+ ["seagreen", "#2e8b57"],
134
+ ["seashell", "#fff5ee"],
135
+ ["sienna", "#a0522d"],
136
+ ["silver", "#c0c0c0"],
137
+ ["skyblue", "#87ceeb"],
138
+ ["slateblue", "#6a5acd"],
139
+ ["slategray", "#708090"],
140
+ ["slategrey", "#708090"],
141
+ ["snow", "#fffafa"],
142
+ ["springgreen", "#00ff7f"],
143
+ ["steelblue", "#4682b4"],
144
+ ["tan", "#d2b48c"],
145
+ ["teal", "#008080"],
146
+ ["thistle", "#d8bfd8"],
147
+ ["tomato", "#ff6347"],
148
+ ["transparent", "#00000000"],
149
+ ["turquoise", "#40e0d0"],
150
+ ["violet", "#ee82ee"],
151
+ ["wheat", "#f5deb3"],
152
+ ["white", "#ffffff"],
153
+ ["whitesmoke", "#f5f5f5"],
154
+ ["yellow", "#ffff00"],
155
+ ["yellowgreen", "#9acd32"]
156
+ ]);
157
+ //#endregion
158
+ //#region src/util/regexers.ts
159
+ /** Any valid hexadecimal colour: 3, 4, 6, or 8 hex digits after `#` */
160
+ var hexAnyRegex = /^#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{4}|[0-9a-fA-F]{3})$/;
161
+ /**
162
+ * Captures the following CSS RGB formats:
163
+ * - `rgb(0,0,0)`
164
+ * - `rgba(0, 0, 0, 0.4)`
165
+ * - `rgba(0,0,0,50%)`
166
+ * - `rgb(0 0 0)`
167
+ * - `rgba(0 0 0 / 0.4)`
168
+ * - `rgb(0 0 0 / 0.5)`
169
+ * - `rgb(0 0 0 / 50%)`
170
+ * - `rgb(50%, 25%, 100%)`
171
+ * - `rgba(50%, 25%, 100%, 0.8)`
172
+ * - `rgba(50%, 25%, 100%, 80%)`
173
+ */
174
+ var cssRGBARegex = /^rgba?\(\s*([-+]?\d*\.?\d+%?)\s*[,\s]\s*([-+]?\d*\.?\d+%?)\s*[,\s]\s*([-+]?\d*\.?\d+%?)\s*(?:[,/]\s*([-+]?\d*\.?\d+%?))?\s*\)$/i;
175
+ //#endregion
176
+ //#region src/assertions.ts
177
+ /**
178
+ * Determines whether a string represents a valid CSS RGB or RGBA colour value.
179
+ *
180
+ * Captures the following CSS RGB formats:
181
+ * - `rgb(0,0,0)`
182
+ * - `rgba(0, 0, 0, 0.4)`
183
+ * - `rgba(0,0,0,50%)`
184
+ * - `rgb(0 0 0)`
185
+ * - `rgba(0 0 0 / 0.4)`
186
+ * - `rgb(0 0 0 / 0.5)`
187
+ * - `rgb(0 0 0 / 50%)`
188
+ * - `rgb(50%, 25%, 100%)`
189
+ * - `rgba(50%, 25%, 100%, 0.8)`
190
+ * - `rgba(50%, 25%, 100%, 80%)`
191
+ *
192
+ * @param {string} colour - The string to test.
193
+ * @returns {boolean} `true` if the string represents a valid CSS RGB or RGBA colour value, `false` otherwise.
194
+ */
195
+ function isCSSRGBColour(colour) {
196
+ return cssRGBARegex.test(colour);
197
+ }
198
+ /**
199
+ * Determines whether a string represents a valid hexadecimal colour value.
200
+ *
201
+ * @param {string} colour - The string to test.
202
+ * @returns {boolean} True if the string represents a valid hexadecimal colour value, false otherwise.
203
+ */
204
+ function isHexColour(colour) {
205
+ return hexAnyRegex.test(colour);
206
+ }
207
+ /**
208
+ * Determines whether a string represents a valid named CSS colour.
209
+ *
210
+ * @param {NamedCSSColour} colour - The string to test.
211
+ * @returns {boolean} `true` if the string represents a valid named CSS colour, `false` otherwise.
212
+ */
213
+ function isNamedCSSColour(colour) {
214
+ return namedCSSColours.has(colour);
215
+ }
216
+ //#endregion
217
+ //#region src/util/index.ts
218
+ /**
219
+ * Calculates the Hue derivative
220
+ * @param x A numeric expression representing the cartesian x-coordinate.
221
+ * @param y A numeric expression representing the cartesian y-coordinate.
222
+ */
3
223
  function hue_d(x, y) {
4
- if (x === 0 && y === 0) {
5
- return 0;
6
- }
7
- const angle = Math.atan2(x, y) * (180 / Math.PI);
8
- if (angle >= 0) {
9
- return angle;
10
- }
11
- return angle + 360;
224
+ if (x === 0 && y === 0) return 0;
225
+ /** The angle in degrees */
226
+ const angle = Math.atan2(x, y) * (180 / Math.PI);
227
+ if (angle >= 0) return angle;
228
+ return angle + 360;
12
229
  }
230
+ /**
231
+ * Calculates the difference between two Hue derivatives
232
+ * @param HueHelper param
233
+ */
13
234
  function deltaHue_d({ C1, C2, h1_d, h2_d }) {
14
- if (C1 * C2 === 0) {
15
- return 0;
16
- }
17
- const delta = h2_d - h1_d;
18
- if (Math.abs(delta) <= 180) {
19
- return delta;
20
- }
21
- if (delta > 180) {
22
- return delta - 360;
23
- }
24
- return delta + 360;
235
+ if (C1 * C2 === 0) return 0;
236
+ const delta = h2_d - h1_d;
237
+ if (Math.abs(delta) <= 180) return delta;
238
+ if (delta > 180) return delta - 360;
239
+ return delta + 360;
25
240
  }
241
+ /**
242
+ * Calculates the mean between two Hue derivatives
243
+ * @param HueHelper param
244
+ */
26
245
  function meanHue_d({ C1, C2, h1_d, h2_d }) {
27
- if (C1 * C2 === 0) {
28
- return h2_d + h1_d;
29
- }
30
- const delta = Math.abs(h1_d - h2_d);
31
- if (delta <= 180) {
32
- return (h2_d + h1_d) / 2;
33
- }
34
- if (delta > 180 && h1_d + h2_d < 360) {
35
- return (h2_d + h1_d + 360) / 2;
36
- }
37
- return (h2_d + h1_d - 360) / 2;
38
- }
39
- const toRadians = (n) => n * (Math.PI / 180);
40
- const bigSquare = (n) => Math.sqrt(n ** 7 / (n ** 7 + 25 ** 7));
246
+ if (C1 * C2 === 0) return h2_d + h1_d;
247
+ const delta = Math.abs(h1_d - h2_d);
248
+ if (delta <= 180) return (h2_d + h1_d) / 2;
249
+ if (delta > 180 && h1_d + h2_d < 360) return (h2_d + h1_d + 360) / 2;
250
+ return (h2_d + h1_d - 360) / 2;
251
+ }
252
+ /**
253
+ * Converts a number in degrees to radians
254
+ * @param n Number in degrees to be converted
255
+ */
256
+ var DEG_TO_RAD = Math.PI / 180;
257
+ var toRadians = (n) => n * DEG_TO_RAD;
258
+ /**
259
+ * Calculates a recurring square root
260
+ * @param n Input number
261
+ */
262
+ var POW_25_7 = 25 ** 7;
263
+ var bigSquare = (n) => Math.sqrt(n ** 7 / (n ** 7 + POW_25_7));
264
+ /**
265
+ * Normalise black and white colorimetry as specified in IEC 61966-2-1
266
+ * It takes a RGB channel in the range [0 - 255] and returns a value between 0 and 1
267
+ * @param rgbValue number to be normalised
268
+ */
41
269
  function linearRGB(rgbValue, WCAG21) {
42
- const rgbRatio = rgbValue / 255;
43
- const threshold = WCAG21 ? 0.03928 : 0.04045;
44
- let linearValue;
45
- if (rgbRatio > threshold) {
46
- linearValue = ((rgbRatio + 0.055) / 1.055) ** 2.4;
47
- } else {
48
- linearValue = rgbRatio / 12.92;
49
- }
50
- return linearValue;
270
+ const rgbRatio = rgbValue / 255;
271
+ const threshold = WCAG21 ? .03928 : .04045;
272
+ let linearValue;
273
+ if (rgbRatio > threshold) linearValue = ((rgbRatio + .055) / 1.055) ** 2.4;
274
+ else linearValue = rgbRatio / 12.92;
275
+ return linearValue;
51
276
  }
277
+ /**
278
+ * The division of the f function domain into two parts was done to prevent an infinite slope at n = 0
279
+ * @param n Number to be constrained
280
+ */
281
+ var LAB_DELTA = 6 / 29;
282
+ var LAB_DELTA_CUBE = LAB_DELTA ** 3;
283
+ var LAB_DELTA_SQ_3 = 3 * LAB_DELTA ** 2;
52
284
  function constrainLab(n) {
53
- const delta = 6 / 29;
54
- const deltaCube = delta ** 3;
55
- let t;
56
- if (n > deltaCube) {
57
- t = Math.cbrt(n);
58
- } else {
59
- t = n / (3 * delta ** 2) + 4 / 29;
60
- }
61
- return t;
285
+ if (n > LAB_DELTA_CUBE) return Math.cbrt(n);
286
+ return n / LAB_DELTA_SQ_3 + 4 / 29;
62
287
  }
288
+ /**
289
+ * Clamps a number between two values
290
+ * @param {number} value - The value to be clamped
291
+ * @param {number} min - The minimum value
292
+ * @param {number} max - The maximum value
293
+ * @returns {number} - A clamped value
294
+ */
63
295
  function clamp(value, min, max) {
64
- return Math.min(Math.max(value, min), max);
296
+ return Math.min(Math.max(value, min), max);
65
297
  }
298
+ /** MDN reference for CSS named colours — shared to avoid duplicating the URL string in the bundle */
299
+ var NAMED_CSS_COLOUR_URL = "https://developer.mozilla.org/en-US/docs/Web/CSS/named-color";
300
+ //#endregion
301
+ //#region src/CIEDE2000.ts
302
+ /**
303
+ * Measures the colour difference between two colours in the Lab space
304
+ *
305
+ * Math taken from:
306
+ *
307
+ * https://en.wikipedia.org/wiki/Color_difference#CIEDE2000
308
+ * http://www2.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf
309
+ * @param colour1 First colour to be compared
310
+ * @param colour2 First colour to be compared
311
+ */
66
312
  function ciede2000(colour1, colour2) {
67
- const lightness1 = colour1.L;
68
- const greenRed1 = colour1.a;
69
- const blueYellow1 = colour1.b;
70
- const lightness2 = colour2.L;
71
- const greenRed2 = colour2.a;
72
- const blueYellow2 = colour2.b;
73
- const luminanceWeight = 1;
74
- const chromaWeight = 1;
75
- const hueWeight = 1;
76
- const chroma1 = Math.sqrt(greenRed1 ** 2 + blueYellow1 ** 2);
77
- const chroma2 = Math.sqrt(greenRed2 ** 2 + blueYellow2 ** 2);
78
- const deltaLightness = lightness2 - lightness1;
79
- const meanChroma = (chroma1 + chroma2) / 2;
80
- const G = 0.5 * (1 - bigSquare(meanChroma));
81
- const greenRed1Prime = greenRed1 * (1 + G);
82
- const greenRed2Prime = greenRed2 * (1 + G);
83
- const chroma1Prime = Math.sqrt(greenRed1Prime ** 2 + blueYellow1 ** 2);
84
- const chroma2Prime = Math.sqrt(greenRed2Prime ** 2 + blueYellow2 ** 2);
85
- const meanChromaPrime = (chroma1Prime + chroma2Prime) / 2;
86
- const deltaChromaPrime = chroma2Prime - chroma1Prime;
87
- const hue1Prime = hue_d(blueYellow1, greenRed1Prime);
88
- const hue2Prime = hue_d(blueYellow2, greenRed2Prime);
89
- const deltaHuePrime = deltaHue_d({
90
- C1: chroma1,
91
- C2: chroma2,
92
- h1_d: hue1Prime,
93
- h2_d: hue2Prime
94
- });
95
- const deltaHue = 2 * Math.sqrt(chroma1Prime * chroma2Prime) * Math.sin(toRadians(deltaHuePrime) / 2);
96
- const meanHuePrime = meanHue_d({
97
- C1: chroma1,
98
- C2: chroma2,
99
- h1_d: hue1Prime,
100
- h2_d: hue2Prime
101
- });
102
- const meanLightness = (lightness1 + lightness2) / 2;
103
- const T = 1 - 0.17 * Math.cos(toRadians(meanHuePrime - 30)) + 0.24 * Math.cos(toRadians(2 * meanHuePrime)) + 0.32 * Math.cos(toRadians(3 * meanHuePrime + 6)) - 0.2 * Math.cos(toRadians(4 * meanHuePrime - 63));
104
- const SL = 1 + 0.015 * (meanLightness - 50) ** 2 / Math.sqrt(20 + (meanLightness - 50) ** 2);
105
- const SC = 0.045 * meanChromaPrime + 1;
106
- const SH = 1 + 0.015 * meanChromaPrime * T;
107
- const rotation = 30 * Math.exp(-(((meanHuePrime - 275) / 25) ** 2));
108
- const RT = -2 * bigSquare(meanChromaPrime) * Math.sin(toRadians(rotation * 2));
109
- const deltaE = Math.sqrt(
110
- (deltaLightness / (luminanceWeight * SL)) ** 2 + (deltaChromaPrime / (chromaWeight * SC)) ** 2 + (deltaHue / (hueWeight * SH)) ** 2 + RT * (deltaChromaPrime / (chromaWeight * SC)) * (deltaHue / (hueWeight * SH))
111
- );
112
- return deltaE;
313
+ /** Lightness for colour 1 */
314
+ const lightness1 = colour1.L;
315
+ /** green–red colour opponent for colour 1 */
316
+ const greenRed1 = colour1.a;
317
+ /** blue–yellow colour opponent for colour 1 */
318
+ const blueYellow1 = colour1.b;
319
+ /** Lightness for colour 2 */
320
+ const lightness2 = colour2.L;
321
+ /** green–red colour opponent for colour 2 */
322
+ const greenRed2 = colour2.a;
323
+ /** blue–yellow colour opponent for colour 2 */
324
+ const blueYellow2 = colour2.b;
325
+ /** Weighting factor for Luminance */
326
+ const luminanceWeight = 1;
327
+ /** Weighting factor for Chroma */
328
+ const chromaWeight = 1;
329
+ /** Weighting factor for Hue */
330
+ const hueWeight = 1;
331
+ /** Chroma for colour 1 */
332
+ const chroma1 = Math.sqrt(greenRed1 ** 2 + blueYellow1 ** 2);
333
+ /** Chroma for colour 2 */
334
+ const chroma2 = Math.sqrt(greenRed2 ** 2 + blueYellow2 ** 2);
335
+ /** Derivative of the Lightness difference */
336
+ const deltaLightness = lightness2 - lightness1;
337
+ const G = .5 * (1 - bigSquare((chroma1 + chroma2) / 2));
338
+ /** Derivative of greenRed1 */
339
+ const greenRed1Prime = greenRed1 * (1 + G);
340
+ /** Derivative of greenRed2 */
341
+ const greenRed2Prime = greenRed2 * (1 + G);
342
+ /** Derivative of chroma1 */
343
+ const chroma1Prime = Math.sqrt(greenRed1Prime ** 2 + blueYellow1 ** 2);
344
+ /** Derivative of chroma2 */
345
+ const chroma2Prime = Math.sqrt(greenRed2Prime ** 2 + blueYellow2 ** 2);
346
+ /** Derivative of Chroma mean */
347
+ const meanChromaPrime = (chroma1Prime + chroma2Prime) / 2;
348
+ /** Derivative of the mean difference of Chroma */
349
+ const deltaChromaPrime = chroma2Prime - chroma1Prime;
350
+ /** Derivative of colour 1 Hue */
351
+ const hue1Prime = hue_d(blueYellow1, greenRed1Prime);
352
+ /** Derivative of colour 2 Hue */
353
+ const hue2Prime = hue_d(blueYellow2, greenRed2Prime);
354
+ /** Hue difference */
355
+ const deltaHuePrime = deltaHue_d({
356
+ C1: chroma1,
357
+ C2: chroma2,
358
+ h1_d: hue1Prime,
359
+ h2_d: hue2Prime
360
+ });
361
+ const deltaHue = 2 * Math.sqrt(chroma1Prime * chroma2Prime) * Math.sin(toRadians(deltaHuePrime) / 2);
362
+ /** Derivative of mean hue */
363
+ const meanHuePrime = meanHue_d({
364
+ C1: chroma1,
365
+ C2: chroma2,
366
+ h1_d: hue1Prime,
367
+ h2_d: hue2Prime
368
+ });
369
+ /** Lightness Mean value*/
370
+ const meanLightness = (lightness1 + lightness2) / 2;
371
+ /** Compensation for neutral colours (the primed values in the L*C*h differences) */
372
+ const T = 1 - .17 * Math.cos(toRadians(meanHuePrime - 30)) + .24 * Math.cos(toRadians(2 * meanHuePrime)) + .32 * Math.cos(toRadians(3 * meanHuePrime + 6)) - .2 * Math.cos(toRadians(4 * meanHuePrime - 63));
373
+ /** Compensation for lightness */
374
+ const SL = 1 + .015 * (meanLightness - 50) ** 2 / Math.sqrt(20 + (meanLightness - 50) ** 2);
375
+ /** Compensation for chroma */
376
+ const SC = .045 * meanChromaPrime + 1;
377
+ /** Compensation for hue */
378
+ const SH = 1 + .015 * meanChromaPrime * T;
379
+ const rotation = 30 * Math.exp(-(((meanHuePrime - 275) / 25) ** 2));
380
+ /** A hue rotation term, to deal with the problematic blue region (hue angles in the neighborhood of 275°) */
381
+ const RT = -2 * bigSquare(meanChromaPrime) * Math.sin(toRadians(rotation * 2));
382
+ return Math.sqrt((deltaLightness / (luminanceWeight * SL)) ** 2 + (deltaChromaPrime / (chromaWeight * SC)) ** 2 + (deltaHue / (hueWeight * SH)) ** 2 + RT * (deltaChromaPrime / (chromaWeight * SC)) * (deltaHue / (hueWeight * SH)));
113
383
  }
114
- function convertRGBtoXYZ(colour) {
115
- const { R, G, B } = colour;
116
- const _R = linearRGB(R) * 100;
117
- const _G = linearRGB(G) * 100;
118
- const _B = linearRGB(B) * 100;
119
- const X = _R * 0.4124 + _G * 0.3576 + _B * 0.1805;
120
- const Y = _R * 0.2126 + _G * 0.7152 + _B * 0.0722;
121
- const Z = _R * 0.0193 + _G * 0.1192 + _B * 0.9505;
122
- return { X, Y, Z };
384
+ //#endregion
385
+ //#region src/convertCSSRGBtoRGB.ts
386
+ /**
387
+ * Converts a CSS RGB/Alpha value to its numeric equivalent
388
+ * @param value - The value string (e.g., "50%", "127", "0.5")
389
+ * @param isAlpha - Whether this is an alpha channel value
390
+ * @returns The numeric value
391
+ */
392
+ function convertCssValueToNumber(value, isAlpha = false) {
393
+ if (value.endsWith("%")) {
394
+ const percentage = Number.parseFloat(value.slice(0, -1));
395
+ if (isAlpha) return percentage / 100;
396
+ return Math.round(percentage / 100 * 255);
397
+ }
398
+ return Number.parseFloat(value);
123
399
  }
124
- function convertXYZtoLab(colour) {
125
- const { X, Y, Z } = colour;
126
- const _X = X / 95.047;
127
- const _Y = Y / 100;
128
- const _Z = Z / 108.883;
129
- const fX = constrainLab(_X);
130
- const fY = constrainLab(_Y);
131
- const fZ = constrainLab(_Z);
132
- const L = 116 * fY - 16;
133
- const a = 500 * (fX - fY);
134
- const b = 200 * (fY - fZ);
135
- return { L, a, b };
400
+ function convertCssRgbChannelValue(value) {
401
+ if (!value) return void 0;
402
+ return convertCssValueToNumber(value);
136
403
  }
137
- function convertRGBtoLab(colour) {
138
- const XYZColour = convertRGBtoXYZ(colour);
139
- return convertXYZtoLab(XYZColour);
404
+ function convertCssAlphaChannelValue(value) {
405
+ if (!value) return void 0;
406
+ return convertCssValueToNumber(value, true);
140
407
  }
141
- const RGBdistance = (colour1, colour2) => {
142
- const c1 = convertRGBtoLab(colour1);
143
- const c2 = convertRGBtoLab(colour2);
144
- return ciede2000(c1, c2);
145
- };
146
- const hexRegex = /^#[a-fA-F0-9]{6}$/;
147
- const hexAlphaRegex = /^#[a-fA-F0-9]{8}$/;
148
- const shortHexRegex = /^#[a-fA-F0-9]{3}$/;
149
- const shortAlphaHexRegex = /^#[a-fA-F0-9]{4}$/;
150
- const cssRGBARegex = /^rgba*\(\s*([-+]?\d+)\s*(?:,)?\s*([-+]?\d+)\s*(?:,)?\s*([-+]?\d+)\s*(?:,*|\/*)\s*([-+]?\d*[.]?\d+[%]?)*\)$/i;
408
+ /**
409
+ * Converts CSS RGB colour format into RGB colour object.
410
+ * @param {string} colour - A CSS RGB colour in the format:
411
+ *
412
+ * - `rgb(0,0,0)`
413
+ * - `rgba(0,0,0,0.4)`
414
+ * - `rgb(0 0 0)`
415
+ * - `rgba(0 0 0 / 0.4)`
416
+ * - `rgb(50%, 25%, 100%)`
417
+ * - `rgba(50%, 25%, 100%, 0.8)`
418
+ * - `rgba(50%, 25%, 100%, 80%)`
419
+ *
420
+ * @returns {RGBColour} - RGB colour object.
421
+ */
151
422
  function convertCSSRGBtoRGB(colour) {
152
- const match = colour.match(cssRGBARegex);
153
- if (!match) {
154
- throw new Error(
155
- `convertCSSRGBtoHex expects a valid CSS RGB string but got ${colour}`
156
- );
157
- }
158
- const rgbNumber = (n) => n ? Number.parseFloat(n) : void 0;
159
- return {
160
- R: rgbNumber(match[1]),
161
- G: rgbNumber(match[2]),
162
- B: rgbNumber(match[3]),
163
- A: rgbNumber(match[4])
164
- };
423
+ const match = colour.match(cssRGBARegex);
424
+ if (!match) throw new Error(`convertCSSRGBtoRGB expects a valid CSS RGB string but got ${colour}`);
425
+ return {
426
+ R: convertCssRgbChannelValue(match[1]),
427
+ G: convertCssRgbChannelValue(match[2]),
428
+ B: convertCssRgbChannelValue(match[3]),
429
+ A: convertCssAlphaChannelValue(match[4])
430
+ };
165
431
  }
432
+ //#endregion
433
+ //#region src/convertRGBtoHex.ts
434
+ /**
435
+ * Converts a colour in the RGB format to Hexadecimal.
436
+ * It accepts an option Alpha channel `A`
437
+ * @param {RGBColour} colour - An object representing RGB Colour.
438
+ * @param {number} colour.R - A number between 0 and 255 to describe the Red colour channel
439
+ * @param {number} colour.G - A number between 0 and 255 to describe the Green colour channel
440
+ * @param {number} colour.B - A number between 0 and 255 to describe the Blue colour channel
441
+ * @param {number} colour.A - An optional number between 0 and 1 to describe the Alpha colour channel
442
+ * @returns - An hexadecimal string
443
+ */
166
444
  function convertRGBtoHex({ R, G, B, A }) {
167
- const hex = (n) => {
168
- const value = clamp(n, 0, 255);
169
- return value.toString(16).padStart(2, "0");
170
- };
171
- return `#${hex(R)}${hex(G)}${hex(B)}${A ? hex(Math.round(A * 255)) : ""}`;
445
+ const hex = (n) => {
446
+ return clamp(n, 0, 255).toString(16).padStart(2, "0");
447
+ };
448
+ return `#${hex(R)}${hex(G)}${hex(B)}${A ? hex(Math.round(A * 255)) : ""}`;
172
449
  }
450
+ //#endregion
451
+ //#region src/convertCSSRGBtoHex.ts
452
+ /**
453
+ * Converts CSS RGB colour format into Hexadecimal.
454
+ * @param {string} colour - A CSS RGB colour in the format:
455
+ *
456
+ * - `rgb(0,0,0)`
457
+ * - `rgba(0,0,0,0.4)`
458
+ * - `rgb(0 0 0)`
459
+ * - `rgba(0 0 0 / 0.4)`
460
+ * - `rgb(50%, 25%, 100%)`
461
+ * - `rgba(50%, 25%, 100%, 0.8)`
462
+ * - `rgba(50%, 25%, 100%, 80%)`
463
+ *
464
+ * @returns {string} - An hexadecimal string
465
+ */
173
466
  function convertCSSRGBtoHex(colour) {
174
- const rgb = convertCSSRGBtoRGB(colour);
175
- return convertRGBtoHex(rgb);
467
+ return convertRGBtoHex(convertCSSRGBtoRGB(colour));
176
468
  }
469
+ //#endregion
470
+ //#region src/convertHextoRGB.ts
471
+ /**
472
+ * Converts an hexadecimal colour into RGB colour object.
473
+ * @param {string} hex - An hexadecimal colour in the format:
474
+ *
475
+ * - `#000`
476
+ * - `#102030`
477
+ * - `#ffff`
478
+ * - `#102030ff`
479
+ *
480
+ * @returns {RGBColour | null} RGB colour object, or `null` if the input is not a valid hexadecimal colour.
481
+ */
177
482
  function convertHextoRGB(hex) {
178
- if (typeof hex !== "string") {
179
- throw new Error(`convertHextoRGB expects a string but got a ${typeof hex}`);
180
- }
181
- if (hex.match(hexRegex)) {
182
- return {
183
- R: Number.parseInt(`${hex[1]}${hex[2]}`, 16),
184
- G: Number.parseInt(`${hex[3]}${hex[4]}`, 16),
185
- B: Number.parseInt(`${hex[5]}${hex[6]}`, 16)
186
- };
187
- }
188
- if (hex.match(shortHexRegex)) {
189
- return {
190
- R: Number.parseInt(`${hex[1]}${hex[1]}`, 16),
191
- G: Number.parseInt(`${hex[2]}${hex[2]}`, 16),
192
- B: Number.parseInt(`${hex[3]}${hex[3]}`, 16)
193
- };
194
- }
195
- if (hex.match(hexAlphaRegex)) {
196
- return {
197
- R: Number.parseInt(`${hex[1]}${hex[2]}`, 16),
198
- G: Number.parseInt(`${hex[3]}${hex[4]}`, 16),
199
- B: Number.parseInt(`${hex[5]}${hex[6]}`, 16),
200
- A: Math.round(Number.parseInt(`${hex[7]}${hex[8]}`, 16) / 255 * 100) / 100
201
- };
202
- }
203
- if (hex.match(shortAlphaHexRegex)) {
204
- return {
205
- R: Number.parseInt(`${hex[1]}${hex[1]}`, 16),
206
- G: Number.parseInt(`${hex[2]}${hex[2]}`, 16),
207
- B: Number.parseInt(`${hex[3]}${hex[3]}`, 16),
208
- A: Math.round(Number.parseInt(`${hex[4]}${hex[4]}`, 16) / 255 * 100) / 100
209
- };
210
- }
211
- throw new Error(
212
- `convertHextoRGB expects an valid hexadecimal colour value but got ${hex}`
213
- );
483
+ if (typeof hex !== "string" || !hexAnyRegex.test(hex)) return null;
484
+ switch (hex.length) {
485
+ case 7: return {
486
+ R: parseInt(hex.slice(1, 3), 16),
487
+ G: parseInt(hex.slice(3, 5), 16),
488
+ B: parseInt(hex.slice(5, 7), 16)
489
+ };
490
+ case 4: return {
491
+ R: parseInt(hex.slice(1, 2).repeat(2), 16),
492
+ G: parseInt(hex.slice(2, 3).repeat(2), 16),
493
+ B: parseInt(hex.slice(3, 4).repeat(2), 16)
494
+ };
495
+ case 9: return {
496
+ R: parseInt(hex.slice(1, 3), 16),
497
+ G: parseInt(hex.slice(3, 5), 16),
498
+ B: parseInt(hex.slice(5, 7), 16),
499
+ A: Math.round(parseInt(hex.slice(7, 9), 16) / 255 * 100) / 100
500
+ };
501
+ default: return {
502
+ R: parseInt(hex.slice(1, 2).repeat(2), 16),
503
+ G: parseInt(hex.slice(2, 3).repeat(2), 16),
504
+ B: parseInt(hex.slice(3, 4).repeat(2), 16),
505
+ A: Math.round(parseInt(hex.slice(4, 5).repeat(2), 16) / 255 * 100) / 100
506
+ };
507
+ }
214
508
  }
509
+ //#endregion
510
+ //#region src/convertHextoCSSRGB.ts
511
+ /**
512
+ * Converts an hexadecimal colour into CSS RGB/A colour.
513
+ * @param {string} hex - An hexadecimal colour in the format:
514
+ *
515
+ * - `#000`
516
+ * - `#102030`
517
+ * - `#ffff`
518
+ * - `#102030ff`
519
+ *
520
+ * @returns {string} either a CSS RGB or CSS RGBA string.
521
+ */
215
522
  function convertHextoCSSRGB(hex) {
216
- const rgb = convertHextoRGB(hex);
217
- if (rgb.A) {
218
- return `rgba(${rgb.R},${rgb.G},${rgb.B},${rgb.A})`;
219
- }
220
- return `rgb(${rgb.R},${rgb.G},${rgb.B})`;
221
- }
222
- const namedCSSColours = /* @__PURE__ */ new Map([
223
- ["aliceblue", "#f0f8ff"],
224
- ["antiquewhite", "#faebd7"],
225
- ["aqua", "#00ffff"],
226
- ["aquamarine", "#7fffd4"],
227
- ["azure", "#f0ffff"],
228
- ["beige", "#f5f5dc"],
229
- ["bisque", "#ffe4c4"],
230
- ["black", "#000000"],
231
- ["blanchedalmond", "#ffebcd"],
232
- ["blue", "#0000ff"],
233
- ["blueviolet", "#8a2be2"],
234
- ["brown", "#a52a2a"],
235
- ["burlywood", "#deb887"],
236
- ["cadetblue", "#5f9ea0"],
237
- ["chartreuse", "#7fff00"],
238
- ["chocolate", "#d2691e"],
239
- ["coral", "#ff7f50"],
240
- ["cornflowerblue", "#6495ed"],
241
- ["cornsilk", "#fff8dc"],
242
- ["crimson", "#dc143c"],
243
- ["cyan", "#00ffff"],
244
- ["darkblue", "#00008b"],
245
- ["darkcyan", "#008b8b"],
246
- ["darkgoldenrod", "#b8860b"],
247
- ["darkgray", "#a9a9a9"],
248
- ["darkgreen", "#006400"],
249
- ["darkgrey", "#a9a9a9"],
250
- ["darkkhaki", "#bdb76b"],
251
- ["darkmagenta", "#8b008b"],
252
- ["darkolivegreen", "#556b2f"],
253
- ["darkorange", "#ff8c00"],
254
- ["darkorchid", "#9932cc"],
255
- ["darkred", "#8b0000"],
256
- ["darksalmon", "#e9967a"],
257
- ["darkseagreen", "#8fbc8f"],
258
- ["darkslateblue", "#483d8b"],
259
- ["darkslategray", "#2f4f4f"],
260
- ["darkslategrey", "#2f4f4f"],
261
- ["darkturquoise", "#00ced1"],
262
- ["darkviolet", "#9400d3"],
263
- ["deeppink", "#ff1493"],
264
- ["deepskyblue", "#00bfff"],
265
- ["dimgray", "#696969"],
266
- ["dimgrey", "#696969"],
267
- ["dodgerblue", "#1e90ff"],
268
- ["firebrick", "#b22222"],
269
- ["floralwhite", "#fffaf0"],
270
- ["forestgreen", "#228b22"],
271
- ["fuchsia", "#ff00ff"],
272
- ["gainsboro", "#dcdcdc"],
273
- ["ghostwhite", "#f8f8ff"],
274
- ["gold", "#ffd700"],
275
- ["goldenrod", "#daa520"],
276
- ["gray", "#808080"],
277
- ["green", "#008000"],
278
- ["greenyellow", "#adff2f"],
279
- ["grey", "#808080"],
280
- ["honeydew", "#f0fff0"],
281
- ["hotpink", "#ff69b4"],
282
- ["indianred", "#cd5c5c"],
283
- ["indigo", "#4b0082"],
284
- ["ivory", "#fffff0"],
285
- ["khaki", "#f0e68c"],
286
- ["lavender", "#e6e6fa"],
287
- ["lavenderblush", "#fff0f5"],
288
- ["lawngreen", "#7cfc00"],
289
- ["lemonchiffon", "#fffacd"],
290
- ["lightblue", "#add8e6"],
291
- ["lightcoral", "#f08080"],
292
- ["lightcyan", "#e0ffff"],
293
- ["lightgoldenrodyellow", "#fafad2"],
294
- ["lightgray", "#d3d3d3"],
295
- ["lightgreen", "#90ee90"],
296
- ["lightgrey", "#d3d3d3"],
297
- ["lightpink", "#ffb6c1"],
298
- ["lightsalmon", "#ffa07a"],
299
- ["lightseagreen", "#20b2aa"],
300
- ["lightskyblue", "#87cefa"],
301
- ["lightslategray", "#778899"],
302
- ["lightslategrey", "#778899"],
303
- ["lightsteelblue", "#b0c4de"],
304
- ["lightyellow", "#ffffe0"],
305
- ["lime", "#00ff00"],
306
- ["limegreen", "#32cd32"],
307
- ["linen", "#faf0e6"],
308
- ["magenta", "#ff00ff"],
309
- ["maroon", "#800000"],
310
- ["mediumaquamarine", "#66cdaa"],
311
- ["mediumblue", "#0000cd"],
312
- ["mediumorchid", "#ba55d3"],
313
- ["mediumpurple", "#9370db"],
314
- ["mediumseagreen", "#3cb371"],
315
- ["mediumslateblue", "#7b68ee"],
316
- ["mediumspringgreen", "#00fa9a"],
317
- ["mediumturquoise", "#48d1cc"],
318
- ["mediumvioletred", "#c71585"],
319
- ["midnightblue", "#191970"],
320
- ["mintcream", "#f5fffa"],
321
- ["mistyrose", "#ffe4e1"],
322
- ["moccasin", "#ffe4b5"],
323
- ["navajowhite", "#ffdead"],
324
- ["navy", "#000080"],
325
- ["oldlace", "#fdf5e6"],
326
- ["olive", "#808000"],
327
- ["olivedrab", "#6b8e23"],
328
- ["orangered", "#ff4500"],
329
- ["orchid", "#da70d6"],
330
- ["palegoldenrod", "#eee8aa"],
331
- ["palegreen", "#98fb98"],
332
- ["paleturquoise", "#afeeee"],
333
- ["palevioletred", "#db7093"],
334
- ["papayawhip", "#ffefd5"],
335
- ["peachpuff", "#ffdab9"],
336
- ["peru", "#cd853f"],
337
- ["pink", "#ffc0cb"],
338
- ["plum", "#dda0dd"],
339
- ["powderblue", "#b0e0e6"],
340
- ["purple", "#800080"],
341
- ["red", "#ff0000"],
342
- ["rosybrown", "#bc8f8f"],
343
- ["royalblue", "#4169e1"],
344
- ["saddlebrown", "#8b4513"],
345
- ["salmon", "#fa8072"],
346
- ["sandybrown", "#f4a460"],
347
- ["seagreen", "#2e8b57"],
348
- ["seashell", "#fff5ee"],
349
- ["sienna", "#a0522d"],
350
- ["silver", "#c0c0c0"],
351
- ["skyblue", "#87ceeb"],
352
- ["slateblue", "#6a5acd"],
353
- ["slategray", "#708090"],
354
- ["slategrey", "#708090"],
355
- ["snow", "#fffafa"],
356
- ["springgreen", "#00ff7f"],
357
- ["steelblue", "#4682b4"],
358
- ["tan", "#d2b48c"],
359
- ["teal", "#008080"],
360
- ["thistle", "#d8bfd8"],
361
- ["tomato", "#ff6347"],
362
- ["transparent", "#00000000"],
363
- ["turquoise", "#40e0d0"],
364
- ["violet", "#ee82ee"],
365
- ["wheat", "#f5deb3"],
366
- ["white", "#ffffff"],
367
- ["whitesmoke", "#f5f5f5"],
368
- ["yellow", "#ffff00"],
369
- ["yellowgreen", "#9acd32"]
370
- ]);
523
+ const rgb = convertHextoRGB(hex);
524
+ if (!rgb) return null;
525
+ if (rgb.A) return `rgba(${rgb.R},${rgb.G},${rgb.B},${rgb.A})`;
526
+ return `rgb(${rgb.R},${rgb.G},${rgb.B})`;
527
+ }
528
+ //#endregion
529
+ //#region src/convertHextoNamedCSSColour.ts
530
+ /**
531
+ * Converts a hexadecimal colour value to a named CSS colour.
532
+ *
533
+ * @param {string} colour - The hexadecimal colour value to convert.
534
+ * @returns {NamedCSSColour | undefined} The named CSS colour that corresponds to the given hexadecimal colour value, or undefined if no named CSS colour matches the given value.
535
+ */
371
536
  function convertHextoNamedCSSColour(colour) {
372
- for (const [name, hex] of namedCSSColours.entries()) {
373
- if (hex === colour) {
374
- return name;
375
- }
376
- }
377
- return void 0;
537
+ for (const [name, hex] of namedCSSColours.entries()) if (hex === colour) return name;
378
538
  }
539
+ //#endregion
540
+ //#region src/convertNamedCSSColourtoHex.ts
541
+ /**
542
+ * Converts a named CSS Colour in an hexadecimal one.
543
+ *
544
+ * List of colours sourced here:
545
+ * https://developer.mozilla.org/en-US/docs/Web/CSS/named-color
546
+ * @param {NamedCSSColour} name - A named CSS colour
547
+ * @returns {string} - An hexadecimal string
548
+ */
379
549
  function convertNamedCSSColourtoHex(name) {
380
- return namedCSSColours.get(name);
550
+ return namedCSSColours.get(name);
381
551
  }
552
+ //#endregion
553
+ //#region src/convertNamedCSSColourtoRGB.ts
554
+ /**
555
+ * Converts a named CSS colour to an RGB colour object.
556
+ *
557
+ * @param {NamedCSSColour} colour - The named CSS colour to convert.
558
+ * @returns {RGBColour | undefined} An RGB colour object representing the named CSS colour, or undefined if the named CSS colour is not recognized.
559
+ */
382
560
  function convertNamedCSSColourtoRGB(colour) {
383
- const hex = convertNamedCSSColourtoHex(colour);
384
- if (!hex) {
385
- return void 0;
386
- }
387
- return convertHextoRGB(hex);
561
+ const hex = convertNamedCSSColourtoHex(colour);
562
+ if (!hex) return;
563
+ return convertHextoRGB(hex) || void 0;
388
564
  }
565
+ //#endregion
566
+ //#region src/convertRGBtoCSSRGB.ts
567
+ /**
568
+ * Converts an RGB colour object to a CSS RGB colour string.
569
+ *
570
+ * @param {RGBColour} colour - The RGB colour object to convert.
571
+ * @returns {string} The CSS RGB colour string in the format `rgb(R G B)` or `rgb(R G B / A)` if the alpha channel is present.
572
+ */
389
573
  function convertRGBtoCSSRGB({ R, G, B, A }) {
390
- return `rgb(${R} ${G} ${B}${A ? ` / ${A}` : ""})`;
391
- }
392
- function convertRGBtoNamedCSSColour(colour) {
393
- const hex = convertRGBtoHex(colour);
394
- return convertHextoNamedCSSColour(hex);
574
+ return `rgb(${R} ${G} ${B}${A ? ` / ${A}` : ""})`;
395
575
  }
396
- function findNearestRGBColour(colour, palette) {
397
- if (!palette || palette.length < 2) {
398
- return colour;
399
- }
400
- const map = [];
401
- for (const paletteColour of palette) {
402
- const distance = RGBdistance(colour, paletteColour);
403
- map.push([paletteColour, distance]);
404
- }
405
- const closest = map.sort((a, b) => a[1] - b[1]);
406
- return closest[0][0];
576
+ //#endregion
577
+ //#region src/convertRGBtoXYZ.ts
578
+ /**
579
+ * Converts sRGB colour space to XYZ.
580
+ * Math comes from https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation
581
+ * @param {RGBColour} colour sRGB colour
582
+ * @return {XYZColour} XYZ colour
583
+ */
584
+ function convertRGBtoXYZ(colour) {
585
+ const { R, G, B } = colour;
586
+ const _R = linearRGB(R) * 100;
587
+ const _G = linearRGB(G) * 100;
588
+ const _B = linearRGB(B) * 100;
589
+ return {
590
+ X: _R * .4124 + _G * .3576 + _B * .1805,
591
+ Y: _R * .2126 + _G * .7152 + _B * .0722,
592
+ Z: _R * .0193 + _G * .1192 + _B * .9505
593
+ };
407
594
  }
408
- function findNearestCSSRGBColour(colour, palette) {
409
- if (!palette || palette.length < 2) {
410
- return colour;
411
- }
412
- const baseRGBColour = convertCSSRGBtoRGB(colour);
413
- const paletteRGBColours = palette.map(
414
- (hexColour) => convertCSSRGBtoRGB(hexColour)
415
- );
416
- const nearestRGBColour = findNearestRGBColour(
417
- baseRGBColour,
418
- paletteRGBColours
419
- );
420
- return convertRGBtoCSSRGB(nearestRGBColour);
595
+ //#endregion
596
+ //#region src/convertXYZtoLab.ts
597
+ /**
598
+ * Converts XYZ colour space to Lab
599
+ * Math comes from https://en.wikipedia.org/wiki/CIELAB_color_space#From_CIEXYZ_to_CIELAB[11]
600
+ * @param colour XYZ colour
601
+ * @return {LabColour} Lab colour
602
+ */
603
+ function convertXYZtoLab(colour) {
604
+ const { X, Y, Z } = colour;
605
+ const _X = X / 95.047;
606
+ const _Y = Y / 100;
607
+ const _Z = Z / 108.883;
608
+ const fX = constrainLab(_X);
609
+ const fY = constrainLab(_Y);
610
+ const fZ = constrainLab(_Z);
611
+ return {
612
+ L: 116 * fY - 16,
613
+ a: 500 * (fX - fY),
614
+ b: 200 * (fY - fZ)
615
+ };
421
616
  }
422
- function isCSSRGBColour(colour) {
423
- return !!colour.match(cssRGBARegex);
617
+ //#endregion
618
+ //#region src/convertRGBtoLab.ts
619
+ /**
620
+ * Indirectly converts RGB to Lab.
621
+ * First converts RGB to XYZ, then converts XYZ to Lab.
622
+ * @param {RGBColour} colour sRGB colour
623
+ * @return {LabColour} Lab colour
624
+ */
625
+ function convertRGBtoLab(colour) {
626
+ return convertXYZtoLab(convertRGBtoXYZ(colour));
424
627
  }
425
- function isHexColour(colour) {
426
- return !!colour.match(hexRegex) || !!colour.match(hexAlphaRegex) || !!colour.match(shortAlphaHexRegex) || !!colour.match(shortHexRegex);
628
+ //#endregion
629
+ //#region src/convertRGBtoNamedCSSColour.ts
630
+ /**
631
+ * Converts an RGB colour object to a named CSS colour.
632
+ *
633
+ * @param {RGBColour} colour - The RGB colour object to convert.
634
+ * @returns {NamedCSSColour | undefined} The named CSS colour that corresponds to the given RGB colour, or undefined if no named CSS colour matches the given colour.
635
+ */
636
+ function convertRGBtoNamedCSSColour(colour) {
637
+ return convertHextoNamedCSSColour(convertRGBtoHex(colour));
427
638
  }
428
- function isNamedCSSColour(colour) {
429
- return namedCSSColours.has(colour);
639
+ //#endregion
640
+ //#region src/RGBdistance.ts
641
+ /**
642
+ * Calculate the distance between two RGB colours using the CIEDE2000 colour-difference formula.
643
+ *
644
+ * The CIEDE2000 colour-difference formula is a standard method for calculating the perceptual difference
645
+ * between two colours in the CIELAB colour space. It takes into account human visual perception and the
646
+ * non-linearities in how we perceive colour differences.
647
+ *
648
+ * @param colour1 - The first colour to compare.
649
+ * @param colour2 - The second colour to compare.
650
+ * @returns The distance between the two colours. Smaller numbers (minimum 0) mean the colours are more similar,
651
+ * larger numbers (typically not exceeding 100 for visible colours) indicate more dissimilar colours.
652
+ */
653
+ var RGBdistance = (colour1, colour2) => {
654
+ return ciede2000(convertRGBtoLab(colour1), convertRGBtoLab(colour2));
655
+ };
656
+ //#endregion
657
+ //#region src/findNearestRGBColour.ts
658
+ /**
659
+ * Finds the nearest RGB colour in a palette to the given RGB colour.
660
+ *
661
+ * @param {RGBColour} colour - The RGB colour to find the nearest match for.
662
+ * @param {RGBColour[]} palette - An array of RGB colours to search for the nearest match in.
663
+ * @returns {RGBColour} The RGB colour in the palette that is closest to the given colour.
664
+ * If the palette has fewer than 2 colours, or if it is undefined or null, the original colour is returned.
665
+ */
666
+ function findNearestRGBColour(colour, palette) {
667
+ if (!palette || palette.length < 2) return colour;
668
+ let nearest = colour;
669
+ let minDistance = Number.POSITIVE_INFINITY;
670
+ for (const paletteColour of palette) {
671
+ const distance = RGBdistance(colour, paletteColour);
672
+ if (distance < minDistance) {
673
+ minDistance = distance;
674
+ nearest = paletteColour;
675
+ }
676
+ }
677
+ return nearest;
430
678
  }
679
+ //#endregion
680
+ //#region src/findNearestColour.ts
681
+ /**
682
+ * Finds the nearest colour in a palette to a given colour.
683
+ *
684
+ * @param {string | NamedCSSColour} colour - The colour to match. It can be a hexadecimal colour, a CSS RGB colour, or a named CSS colour.
685
+ * @param {string[] | NamedCSSColour[]} palette - The palette of colours to search.
686
+ * @returns {string} The nearest colour in the palette to the given colour.
687
+ */
431
688
  function findNearestColour(colour, palette) {
432
- if (!palette || palette.length < 2) {
433
- return colour;
434
- }
435
- let baseColour;
436
- let colourType;
437
- const paletteRGB = [];
438
- if (isHexColour(colour)) {
439
- baseColour = convertHextoRGB(colour);
440
- colourType = "hex";
441
- }
442
- if (isCSSRGBColour(colour)) {
443
- baseColour = convertCSSRGBtoRGB(colour);
444
- colourType = "cssRGB";
445
- }
446
- if (isNamedCSSColour(colour)) {
447
- baseColour = convertNamedCSSColourtoRGB(colour);
448
- colourType = "namedCSS";
449
- }
450
- if (!baseColour) {
451
- return void 0;
452
- }
453
- for (const paletteColour of palette) {
454
- if (isHexColour(paletteColour)) {
455
- paletteRGB.push(convertHextoRGB(paletteColour));
456
- }
457
- if (isCSSRGBColour(paletteColour)) {
458
- paletteRGB.push(convertCSSRGBtoRGB(paletteColour));
459
- }
460
- if (isNamedCSSColour(paletteColour)) {
461
- paletteRGB.push(convertNamedCSSColourtoRGB(paletteColour));
462
- }
463
- }
464
- if (paletteRGB.length < 2) {
465
- return colour;
466
- }
467
- const nearest = findNearestRGBColour(baseColour, paletteRGB);
468
- if (colourType === "hex") {
469
- return convertRGBtoHex(nearest);
470
- }
471
- if (colourType === "cssRGB") {
472
- return convertRGBtoCSSRGB(nearest);
473
- }
474
- return convertRGBtoNamedCSSColour(nearest);
689
+ if (!palette || palette.length < 2) return colour;
690
+ let baseColour;
691
+ let colourType;
692
+ const paletteRGB = [];
693
+ if (isHexColour(colour)) {
694
+ baseColour = convertHextoRGB(colour);
695
+ colourType = "hex";
696
+ } else if (isCSSRGBColour(colour)) {
697
+ baseColour = convertCSSRGBtoRGB(colour);
698
+ colourType = "cssRGB";
699
+ } else if (isNamedCSSColour(colour)) {
700
+ baseColour = convertNamedCSSColourtoRGB(colour);
701
+ colourType = "namedCSS";
702
+ }
703
+ if (!baseColour) return;
704
+ for (const paletteColour of palette) if (isHexColour(paletteColour)) {
705
+ const rgb = convertHextoRGB(paletteColour);
706
+ if (rgb) paletteRGB.push(rgb);
707
+ } else if (isCSSRGBColour(paletteColour)) paletteRGB.push(convertCSSRGBtoRGB(paletteColour));
708
+ else if (isNamedCSSColour(paletteColour)) {
709
+ const rgb = convertNamedCSSColourtoRGB(paletteColour);
710
+ if (rgb) paletteRGB.push(rgb);
711
+ }
712
+ if (paletteRGB.length < 2) return colour;
713
+ const nearest = findNearestRGBColour(baseColour, paletteRGB);
714
+ if (colourType === "hex") return convertRGBtoHex(nearest);
715
+ if (colourType === "cssRGB") return convertRGBtoCSSRGB(nearest);
716
+ return convertRGBtoNamedCSSColour(nearest);
717
+ }
718
+ //#endregion
719
+ //#region src/findNearestCSSRGBColour.ts
720
+ /**
721
+ * Finds the nearest CSS RGB colour in a palette to a given CSS RGB colour.
722
+ *
723
+ * @param {string} colour - The CSS RGB colour to find the nearest match for. Alpha channel is ignored.
724
+ * @param {string[]} palette - An array of CSS RGB colours to search for the nearest match.
725
+ * @returns {string} The CSS RGB colour in the palette that is closest to the given colour.
726
+ * If the palette has fewer than 2 colours, or if it is undefined or null, the original colour is returned.
727
+ * The CSS RGB colour string is in the format `rgb(R G B)`.
728
+ */
729
+ function findNearestCSSRGBColour(colour, palette) {
730
+ if (!palette || palette.length < 2) return colour;
731
+ return convertRGBtoCSSRGB(findNearestRGBColour(convertCSSRGBtoRGB(colour), palette.map((hexColour) => convertCSSRGBtoRGB(hexColour))));
475
732
  }
733
+ //#endregion
734
+ //#region src/findNearestHexColour.ts
735
+ /**
736
+ * Finds the nearest hexadecimal colour in a palette to the given hex colour.
737
+ *
738
+ * @param {string} colour - The hexadecimal colour to find the nearest match for.
739
+ * @param {string[]} palette - An array of hexadecimal colours to search for the nearest match in.
740
+ * @returns {string} The hexadecimal colour in the palette that is closest to the given colour.
741
+ * If the palette has fewer than 2 colours, or if it is undefined or null, the original colour is returned.
742
+ */
476
743
  function findNearestHexColour(colour, palette) {
477
- if (!palette || palette.length < 2) {
478
- return colour;
479
- }
480
- const baseRGBColour = convertHextoRGB(colour);
481
- const paletteRGBColours = palette.map(
482
- (hexColour) => convertHextoRGB(hexColour)
483
- );
484
- const nearestRGBColour = findNearestRGBColour(
485
- baseRGBColour,
486
- paletteRGBColours
487
- );
488
- return convertRGBtoHex(nearestRGBColour);
744
+ if (!palette || palette.length < 2) return colour;
745
+ const baseRGBColour = convertHextoRGB(colour);
746
+ if (!baseRGBColour) return colour;
747
+ return convertRGBtoHex(findNearestRGBColour(baseRGBColour, palette.map((hexColour) => convertHextoRGB(hexColour)).filter((rgb) => rgb !== null)));
489
748
  }
749
+ //#endregion
750
+ //#region src/findNearestNamedCSSColour.ts
490
751
  function findNearestNamedCSSColour(colour, palette) {
491
- if (!palette || palette.length < 2) {
492
- return colour;
493
- }
494
- const baseRGBColour = convertNamedCSSColourtoRGB(colour);
495
- const paletteRGBColours = palette.map(
496
- (hexColour) => convertNamedCSSColourtoRGB(hexColour)
497
- );
498
- const filteredPaletteRGBColours = paletteRGBColours.filter(
499
- (paletteRGBColour) => paletteRGBColour !== void 0
500
- );
501
- if (!baseRGBColour || filteredPaletteRGBColours.length < 2) {
502
- return colour;
503
- }
504
- const nearestRGBColour = findNearestRGBColour(
505
- baseRGBColour,
506
- filteredPaletteRGBColours
507
- );
508
- return convertRGBtoNamedCSSColour(nearestRGBColour);
752
+ if (!palette || palette.length < 2) return colour;
753
+ const baseRGBColour = convertNamedCSSColourtoRGB(colour);
754
+ const filteredPaletteRGBColours = palette.map((hexColour) => convertNamedCSSColourtoRGB(hexColour)).filter((paletteRGBColour) => paletteRGBColour !== void 0);
755
+ if (!baseRGBColour || filteredPaletteRGBColours.length < 2) return colour;
756
+ return convertRGBtoNamedCSSColour(findNearestRGBColour(baseRGBColour, filteredPaletteRGBColours));
509
757
  }
758
+ //#endregion
759
+ //#region src/getSRGBLuminanceFromRGB.ts
760
+ /**
761
+ * Returns the relative luminance of a colour in the sRGB space.
762
+ *
763
+ * The calculations are compatible with WCAG 3.0 as it aligns with the sRGB spec
764
+ * and difference to WCAG 2.1 is minimal in a 8 bit channel.
765
+ *
766
+ * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
767
+ *
768
+ * https://www.w3.org/WAI/GL/wiki/Relative_luminance
769
+ * @param colour an hexadecimal colour
770
+ */
510
771
  function getSRGBLuminanceFromRGB({ R, G, B }, standard) {
511
- const isWCAG21 = standard === "WCAG2.1";
512
- const r = linearRGB(R, isWCAG21);
513
- const g = linearRGB(G, isWCAG21);
514
- const b = linearRGB(B, isWCAG21);
515
- return 0.2126 * r + 0.7152 * g + 0.0722 * b;
772
+ const isWCAG21 = standard === "WCAG2.1";
773
+ const r = linearRGB(R, isWCAG21);
774
+ const g = linearRGB(G, isWCAG21);
775
+ const b = linearRGB(B, isWCAG21);
776
+ return .2126 * r + .7152 * g + .0722 * b;
516
777
  }
778
+ //#endregion
779
+ //#region src/getSRGBLuminanceFromHex.ts
780
+ /**
781
+ * Returns the relative luminance of a colour in the sRGB space.
782
+ *
783
+ * The calculations are compatible with WCAG 3.0 as it aligns with the sRGB spec
784
+ * and difference to WCAG 2.1 is minimal in a 8 bit channel.
785
+ *
786
+ * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
787
+ *
788
+ * https://www.w3.org/WAI/GL/wiki/Relative_luminance
789
+ * @param colour an hexadecimal colour
790
+ */
517
791
  function getSRGBLuminanceFromHex(colour, standard) {
518
- const rgbColor = convertHextoRGB(colour);
519
- return getSRGBLuminanceFromRGB(rgbColor, standard);
792
+ const rgbColor = convertHextoRGB(colour);
793
+ if (!rgbColor) return null;
794
+ return getSRGBLuminanceFromRGB(rgbColor, standard);
520
795
  }
796
+ //#endregion
797
+ //#region src/util/calculateContrastRatio.ts
798
+ /**
799
+ * Calculate the contrast ratio between two colours
800
+ * @param luminance1 The luminance of the first colour
801
+ * @param luminance2 The luminance of the second colour
802
+ * @returns The contrast ratio between the two colours truncated to 3 decimal places
803
+ */
521
804
  function calculateContrastRatio(luminance1, luminance2) {
522
- const lighter = Math.max(luminance1, luminance2);
523
- const darker = Math.min(luminance1, luminance2);
524
- const ratio = (lighter + 0.05) / (darker + 0.05);
525
- return Math.floor(ratio * 1e3) / 1e3;
805
+ const lighter = Math.max(luminance1, luminance2);
806
+ const darker = Math.min(luminance1, luminance2);
807
+ const ratio = (lighter + .05) / (darker + .05);
808
+ return Math.floor(ratio * 1e3) / 1e3;
526
809
  }
810
+ //#endregion
811
+ //#region src/getContrastRatioFromHex.ts
812
+ /**
813
+ * Calculates the contrast ratio between two colours in hexadecimal format.
814
+ * @param colour1 The first colour in hexadecimal format
815
+ * @param colour2 The second colour in hexadecimal format
816
+ * @param standard The standard to evaluate the contrast ratio against, defaults to WCAG2.1
817
+ * @returns The contrast ratio between the two colours truncated to 3 decimal places
818
+ */
527
819
  function getContrastRatioFromHex(colour1, colour2, standard) {
528
- const luminance1 = getSRGBLuminanceFromHex(colour1, standard);
529
- const luminance2 = getSRGBLuminanceFromHex(colour2, standard);
530
- return calculateContrastRatio(luminance1, luminance2);
820
+ const luminance1 = getSRGBLuminanceFromHex(colour1, standard);
821
+ const luminance2 = getSRGBLuminanceFromHex(colour2, standard);
822
+ if (luminance1 === null || luminance2 === null) return null;
823
+ return calculateContrastRatio(luminance1, luminance2);
531
824
  }
825
+ //#endregion
826
+ //#region src/getContrastRatio.ts
827
+ /**
828
+ * Calculates the contrast ratio between two colours.
829
+ * Accepts CSS RGB colours (including percentage values), named CSS colours, or hexadecimal colours.
830
+ * @param colour1 The first colour (e.g., `#ff0000`, `rgb(255,0,0)`, `rgb(100%, 0%, 0%)`, or `red`)
831
+ * @param colour2 The second colour (e.g., `#00ff00`, `rgb(0,255,0)`, `rgb(0%, 100%, 0%)`, or `lime`)
832
+ * @param standard The standard to evaluate the contrast ratio against, defaults to WCAG2.1
833
+ * @returns The contrast ratio between the two colours truncated to 3 decimal places
834
+ */
532
835
  function getContrastRatio(colour1, colour2, standard) {
533
- let hexColour1;
534
- let hexColour2;
535
- if (colour1.startsWith("#")) {
536
- hexColour1 = colour1;
537
- } else if (colour1.startsWith("rgb")) {
538
- hexColour1 = convertCSSRGBtoHex(colour1);
539
- } else {
540
- const _hexColour1 = convertNamedCSSColourtoHex(colour1);
541
- if (_hexColour1 === void 0) {
542
- throw new Error(
543
- `getContrastRatio expects valid CSS named colours.
544
- ${colour1} is not a valid CSS named colour.
545
- See https://developer.mozilla.org/en-US/docs/Web/CSS/named-color`
546
- );
547
- }
548
- hexColour1 = _hexColour1;
549
- }
550
- if (colour2.startsWith("#")) {
551
- hexColour2 = colour2;
552
- } else if (colour2.startsWith("rgb")) {
553
- hexColour2 = convertCSSRGBtoHex(colour2);
554
- } else {
555
- const _hexColour2 = convertNamedCSSColourtoHex(colour2);
556
- if (_hexColour2 === void 0) {
557
- throw new Error(`getContrastRatio expects valid CSS named colours.
558
- ${colour2} is not a valid CSS named colour.
559
- See https://developer.mozilla.org/en-US/docs/Web/CSS/named-color`);
560
- }
561
- hexColour2 = _hexColour2;
562
- }
563
- return getContrastRatioFromHex(hexColour1, hexColour2, standard);
836
+ let hexColour1;
837
+ let hexColour2;
838
+ if (colour1.startsWith("#")) hexColour1 = colour1;
839
+ else if (colour1.startsWith("rgb")) hexColour1 = convertCSSRGBtoHex(colour1);
840
+ else {
841
+ const _hexColour1 = convertNamedCSSColourtoHex(colour1);
842
+ if (_hexColour1 === void 0) throw new Error(`getContrastRatio expects valid CSS named colours. ${colour1} is not a valid CSS named colour. See ${NAMED_CSS_COLOUR_URL}`);
843
+ hexColour1 = _hexColour1;
844
+ }
845
+ if (colour2.startsWith("#")) hexColour2 = colour2;
846
+ else if (colour2.startsWith("rgb")) hexColour2 = convertCSSRGBtoHex(colour2);
847
+ else {
848
+ const _hexColour2 = convertNamedCSSColourtoHex(colour2);
849
+ if (_hexColour2 === void 0) throw new Error(`getContrastRatio expects valid CSS named colours. ${colour2} is not a valid CSS named colour. See ${NAMED_CSS_COLOUR_URL}`);
850
+ hexColour2 = _hexColour2;
851
+ }
852
+ const result = getContrastRatioFromHex(hexColour1, hexColour2, standard);
853
+ if (result === null) throw new Error(`getContrastRatio expects valid hexadecimal colours but received ${hexColour1} or ${hexColour2}.`);
854
+ return result;
564
855
  }
856
+ //#endregion
857
+ //#region src/getContrastRatioFromCSSRGB.ts
858
+ /**
859
+ * Calculates the contrast ratio between two colours in CSSRGB format.
860
+ * @param colour1 The first colour in CSSRGB format
861
+ * @param colour2 The second colour in CSSRGB format
862
+ * @param standard The standard to evaluate the contrast ratio against, defaults to WCAG2.1
863
+ * @returns The contrast ratio between the two colours truncated to 3 decimal places
864
+ */
565
865
  function getContrastRatioFromCSSRGB(colour1, colour2, standard) {
566
- const rgbColour1 = convertCSSRGBtoRGB(colour1);
567
- const rgbColour2 = convertCSSRGBtoRGB(colour2);
568
- const luminance1 = getSRGBLuminanceFromRGB(rgbColour1, standard);
569
- const luminance2 = getSRGBLuminanceFromRGB(rgbColour2, standard);
570
- return calculateContrastRatio(luminance1, luminance2);
866
+ const rgbColour1 = convertCSSRGBtoRGB(colour1);
867
+ const rgbColour2 = convertCSSRGBtoRGB(colour2);
868
+ return calculateContrastRatio(getSRGBLuminanceFromRGB(rgbColour1, standard), getSRGBLuminanceFromRGB(rgbColour2, standard));
571
869
  }
870
+ //#endregion
871
+ //#region src/getContrastRatioFromNamedCSSColour.ts
872
+ /**
873
+ * Calculates the contrast ratio between two named CSS colours in.
874
+ *
875
+ * See list here https://developer.mozilla.org/en-US/docs/Web/CSS/named-color
876
+ * @param colour1 The first named CSS colour
877
+ * @param colour2 The second named CSS colour
878
+ * @param standard The standard to evaluate the contrast ratio against, defaults to WCAG2.1
879
+ * @returns The contrast ratio between the two colours truncated to 3 decimal places
880
+ */
572
881
  function getContrastRatioFromNamedCSSColour(colour1, colour2, standard) {
573
- const hexColour1 = convertNamedCSSColourtoHex(colour1);
574
- const hexColour2 = convertNamedCSSColourtoHex(colour2);
575
- if (hexColour1 === void 0 || hexColour2 === void 0) {
576
- throw new Error(
577
- `getContrastRatioFromNamedCSSColour expects valid CSS named colours.
578
- ${colour1} or ${colour2} are not valid CSS named colours.
579
- See https://developer.mozilla.org/en-US/docs/Web/CSS/named-color`
580
- );
581
- }
582
- return getContrastRatioFromHex(hexColour1, hexColour2, standard);
882
+ const hexColour1 = convertNamedCSSColourtoHex(colour1);
883
+ const hexColour2 = convertNamedCSSColourtoHex(colour2);
884
+ if (hexColour1 === void 0 || hexColour2 === void 0) throw new Error(`getContrastRatioFromNamedCSSColour expects valid CSS named colours. ${colour1} or ${colour2} are not valid CSS named colours. See ${NAMED_CSS_COLOUR_URL}`);
885
+ return getContrastRatioFromHex(hexColour1, hexColour2, standard);
583
886
  }
887
+ //#endregion
888
+ //#region src/isHexDarkColour.ts
889
+ /**
890
+ * Evaluates if a colour is dark by measuring the contrast ratio against black and white
891
+ * @param {string} colour - A colour in the hexadecimal format
892
+ * @param {"WCAG2.1" | "WCAG3.0"} standard - Evaluate agains "WCAG2.1" or "WCAG3.0"
893
+ * @returns {boolean} Returns either `true` or `false`
894
+ */
584
895
  function isHexDarkColour(colour, standard) {
585
- const colourLuminance = getSRGBLuminanceFromHex(colour, standard) + 0.05;
586
- const whiteContrast = 1.05 / colourLuminance;
587
- const blackContrast = colourLuminance / 0.05;
588
- return whiteContrast > blackContrast;
896
+ const lum = getSRGBLuminanceFromHex(colour, standard);
897
+ if (lum === null) return false;
898
+ const colourLuminance = lum + .05;
899
+ return 1.05 / colourLuminance > colourLuminance / .05;
589
900
  }
901
+ //#endregion
902
+ //#region src/isCSSNameDarkColour.ts
903
+ /**
904
+ * Evaluates if a named CSS colour is dark by measuring the contrast ratio against black and white
905
+ * @param {string} name - A named CSS colour, ie: `hotpink`
906
+ * @param {"WCAG2.1" | "WCAG3.0"} standard - Evaluate agains "WCAG2.1" or "WCAG3.0"
907
+ * @returns { boolean } Returns `true`, `false` or `undefined` if name is not a valid CSS named colour
908
+ */
590
909
  function isCSSNamedDarkColour(name, standard) {
591
- const hex = convertNamedCSSColourtoHex(name);
592
- if (hex) {
593
- return isHexDarkColour(hex, standard);
594
- }
595
- throw new Error(
596
- `${name} is not a valid colour format. isCSSNamedDarkColour only accepts CSS named colours. Check more details here https://developer.mozilla.org/en-US/docs/Web/CSS/named-color`
597
- );
910
+ const hex = convertNamedCSSColourtoHex(name);
911
+ if (hex) return isHexDarkColour(hex, standard);
912
+ throw new Error(`${name} is not a valid colour format. isCSSNamedDarkColour only accepts CSS named colours. See ${NAMED_CSS_COLOUR_URL}`);
598
913
  }
914
+ //#endregion
915
+ //#region src/isCSSRGBDarkColour.ts
599
916
  function isCSSRGBDarkColour(colour, standard) {
600
- const rgb = convertCSSRGBtoRGB(colour);
601
- const colourLuminance = getSRGBLuminanceFromRGB(rgb, standard);
602
- const whiteContrast = 1.05 / colourLuminance;
603
- const blackContrast = colourLuminance / 0.05;
604
- return whiteContrast > blackContrast;
917
+ const colourLuminance = getSRGBLuminanceFromRGB(convertCSSRGBtoRGB(colour), standard);
918
+ return 1.05 / colourLuminance > colourLuminance / .05;
605
919
  }
920
+ //#endregion
921
+ //#region src/isDarkColour.ts
922
+ /**
923
+ * Evaluates if a colour is dark by measuring the contrast ratio against black and white.
924
+ * It accepts CSS RGB colours (including percentage values), named CSS or hexadecimal.
925
+ *
926
+ * If you know in advance the type of colour you want to evaluate consider using `isCSSNamedDarkColour`, `isCSSRGBDarkColour` or `isHexDarkColour` as they are smaller functions
927
+ * @param {string | NamedCSSColour} colour - A colour value, ie: `hotpink`, `#333222`, `rgb(12,34,45)`, or `rgb(50%, 25%, 100%)`
928
+ * @param {"WCAG2.1" | "WCAG3.0"} standard - Evaluate agains "WCAG2.1" or "WCAG3.0"
929
+ * @returns {boolean} Returns `true`, `false` or `undefined` if name is not a valid CSS named colour
930
+ */
606
931
  function isDarkColour(colour, standard) {
607
- try {
608
- if (colour.startsWith("#")) {
609
- return isHexDarkColour(colour, standard);
610
- }
611
- if (colour.startsWith("rgb")) {
612
- return isCSSRGBDarkColour(colour, standard);
613
- }
614
- return isCSSNamedDarkColour(colour, standard);
615
- } catch (error) {
616
- throw new Error(
617
- `${colour} is not a valid colour format. isDarkColour accepts CSS RGB formats, ie rgb(0,0,0) and rgba(255, 255, 255, 0.4), hexadecimal and CSS named colours.`
618
- );
619
- }
620
- }
621
- const relativeContrast = (firstColour, secondColour) => {
622
- if (firstColour > secondColour) {
623
- return firstColour / secondColour;
624
- }
625
- return secondColour / firstColour;
932
+ try {
933
+ if (colour.startsWith("#")) return isHexDarkColour(colour, standard);
934
+ if (colour.startsWith("rgb")) return isCSSRGBDarkColour(colour, standard);
935
+ return isCSSNamedDarkColour(colour, standard);
936
+ } catch (_error) {
937
+ throw new Error(`${colour} is not a valid colour format. isDarkColour accepts CSS RGB formats, ie rgb(0,0,0), rgba(255, 255, 255, 0.4), rgb(50%, 25%, 100%), and rgba(50%, 25%, 100%, 80%), hexadecimal and CSS named colours.`);
938
+ }
939
+ }
940
+ //#endregion
941
+ //#region src/pickHexColourContrast.ts
942
+ var relativeContrast = (firstColour, secondColour) => {
943
+ if (firstColour > secondColour) return firstColour / secondColour;
944
+ return secondColour / firstColour;
626
945
  };
627
- const pickHexColourContrast = ({ backgroundColour, optionOneColour, optionTwoColour }, standard) => {
628
- const backgroundColourLuminance = getSRGBLuminanceFromHex(backgroundColour, standard) + 0.05;
629
- const optionOneColourLuminance = getSRGBLuminanceFromHex(optionOneColour, standard) + 0.05;
630
- const optionTwoColourLuminance = getSRGBLuminanceFromHex(optionTwoColour, standard) + 0.05;
631
- const optionOneContrast = relativeContrast(
632
- optionOneColourLuminance,
633
- backgroundColourLuminance
634
- );
635
- const optionTwoContrast = relativeContrast(
636
- optionTwoColourLuminance,
637
- backgroundColourLuminance
638
- );
639
- if (optionOneContrast > optionTwoContrast) {
640
- return optionOneColour;
641
- }
642
- return optionTwoColour;
946
+ var pickHexColourContrast = ({ backgroundColour, optionOneColour, optionTwoColour }, standard) => {
947
+ const bgLum = getSRGBLuminanceFromHex(backgroundColour, standard);
948
+ const opt1Lum = getSRGBLuminanceFromHex(optionOneColour, standard);
949
+ const opt2Lum = getSRGBLuminanceFromHex(optionTwoColour, standard);
950
+ if (bgLum === null || opt1Lum === null || opt2Lum === null) return null;
951
+ const backgroundColourLuminance = bgLum + .05;
952
+ const optionOneColourLuminance = opt1Lum + .05;
953
+ const optionTwoColourLuminance = opt2Lum + .05;
954
+ if (relativeContrast(optionOneColourLuminance, backgroundColourLuminance) > relativeContrast(optionTwoColourLuminance, backgroundColourLuminance)) return optionOneColour;
955
+ return optionTwoColour;
643
956
  };
957
+ //#endregion
958
+ //#region src/convertRGBtoHSV.ts
959
+ /**
960
+ * Converts an RGB colour to HSV.
961
+ * Conversion formula is based on the RGB to HSV conversion algorithm:
962
+ * https://en.wikipedia.org/wiki/HSL_and_HSV#From_RGB
963
+ *
964
+ * https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
965
+ * - Hue (h) is calculated based on the maximum RGB value.
966
+ * - Saturation (s) is the chroma divided by the maximum RGB value.
967
+ * - Value (v) is the maximum RGB value.
968
+ * @param r Red channel (0-255)
969
+ * @param g Green channel (0-255)
970
+ * @param b Blue channel (0-255)
971
+ * @returns HSVColour object with h (hue), s (saturation), v (value)
972
+ */
973
+ function convertRGBtoHSV(r, g, b) {
974
+ const red = r / 255;
975
+ const green = g / 255;
976
+ const blue = b / 255;
977
+ const max = Math.max(red, green, blue);
978
+ const min = Math.min(red, green, blue);
979
+ let hue = 0;
980
+ let saturation = 0;
981
+ const value = max;
982
+ const delta = max - min;
983
+ if (max === 0) saturation = 0;
984
+ else saturation = delta / max;
985
+ if (delta !== 0) {
986
+ if (max === red) hue = (green - blue) / delta % 6;
987
+ else if (max === green) hue = (blue - red) / delta + 2;
988
+ else if (max === blue) hue = (red - green) / delta + 4;
989
+ hue = hue * 60;
990
+ if (hue < 0) hue = hue + 360;
991
+ }
992
+ return {
993
+ h: hue,
994
+ s: saturation,
995
+ v: value
996
+ };
997
+ }
998
+ //#endregion
999
+ //#region src/sortHexColours.ts
1000
+ /**
1001
+ * Helper to parse hex and get HSV + alpha
1002
+ * @param hex Hex color string
1003
+ * @returns Object with hue, saturation, value, and alpha
1004
+ */
1005
+ function getColorInfo(hex) {
1006
+ const rgb = convertHextoRGB(hex);
1007
+ if (!rgb) return null;
1008
+ const { R, G, B, A } = rgb;
1009
+ const a = typeof A === "number" ? A : 1;
1010
+ const { h, s, v } = convertRGBtoHSV(R, G, B);
1011
+ return {
1012
+ h,
1013
+ s,
1014
+ v,
1015
+ a
1016
+ };
1017
+ }
1018
+ /**
1019
+ * Helper to get custom order for greyscale values
1020
+ * @param v HSV value (brightness) from 0 to 1
1021
+ * @returns Order priority: 0 for grey/other, 1 for black, 2 for white
1022
+ */
1023
+ function getGreyscaleOrder(v) {
1024
+ if (v === 0) return 1;
1025
+ if (v === 1) return 2;
1026
+ return 0;
1027
+ }
1028
+ /**
1029
+ * Sorts an array of hex colours by hue, then by saturation.
1030
+ * Colours with 0% saturation (greyscale) are shifted to the end.
1031
+ * Fully transparent colours (alpha = 0) are placed at the very end.
1032
+ * Accepts hex colours in #RRGGBB or #RRGGBBAA format.
1033
+ * @param hexColours Array of hex colour strings
1034
+ * @returns Sorted array of hex colour strings
1035
+ */
1036
+ function sortHexColours(hexColours) {
1037
+ const cache = /* @__PURE__ */ new Map();
1038
+ for (const hex of hexColours) if (!cache.has(hex)) {
1039
+ const info = getColorInfo(hex);
1040
+ if (info) cache.set(hex, info);
1041
+ }
1042
+ const normal = [];
1043
+ const greyscale = [];
1044
+ const transparent = [];
1045
+ for (const hex of hexColours) {
1046
+ const info = cache.get(hex);
1047
+ if (!info) continue;
1048
+ const { s, a } = info;
1049
+ if (a === 0) transparent.push(hex);
1050
+ else if (s === 0) greyscale.push(hex);
1051
+ else normal.push(hex);
1052
+ }
1053
+ normal.sort((a, b) => {
1054
+ const ca = cache.get(a);
1055
+ const cb = cache.get(b);
1056
+ if (ca.h !== cb.h) return ca.h - cb.h;
1057
+ return cb.s - ca.s;
1058
+ });
1059
+ greyscale.sort((a, b) => {
1060
+ const ca = cache.get(a);
1061
+ const cb = cache.get(b);
1062
+ const orderA = getGreyscaleOrder(ca.v);
1063
+ const orderB = getGreyscaleOrder(cb.v);
1064
+ if (orderA !== orderB) return orderA - orderB;
1065
+ return ca.v - cb.v;
1066
+ });
1067
+ transparent.sort((a, b) => {
1068
+ const ca = cache.get(a);
1069
+ const cb = cache.get(b);
1070
+ return ca.v - cb.v;
1071
+ });
1072
+ return [
1073
+ ...normal,
1074
+ ...greyscale,
1075
+ ...transparent
1076
+ ];
1077
+ }
1078
+ //#endregion
644
1079
  exports.RGBdistance = RGBdistance;
645
1080
  exports.ciede2000 = ciede2000;
646
1081
  exports.convertCSSRGBtoHex = convertCSSRGBtoHex;
@@ -675,3 +1110,4 @@ exports.isHexColour = isHexColour;
675
1110
  exports.isHexDarkColour = isHexDarkColour;
676
1111
  exports.isNamedCSSColour = isNamedCSSColour;
677
1112
  exports.pickHexColourContrast = pickHexColourContrast;
1113
+ exports.sortHexColours = sortHexColours;