@thednp/color-picker 0.0.1-alpha3 → 0.0.2-alpha2

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,1167 @@
1
+ /*!
2
+ * Color v0.0.2alpha2 (http://thednp.github.io/color-picker)
3
+ * Copyright 2022 © thednp
4
+ * Licensed under MIT (https://github.com/thednp/color-picker/blob/master/LICENSE)
5
+ */
6
+ /**
7
+ * A global namespace for `document.head`.
8
+ */
9
+ const { head: documentHead } = document;
10
+
11
+ /**
12
+ * Shortcut for `window.getComputedStyle(element).propertyName`
13
+ * static method.
14
+ *
15
+ * * If `element` parameter is not an `HTMLElement`, `getComputedStyle`
16
+ * throws a `ReferenceError`.
17
+ *
18
+ * @param {HTMLElement | Element} element target
19
+ * @param {string} property the css property
20
+ * @return {string} the css property value
21
+ */
22
+ function getElementStyle(element, property) {
23
+ const computedStyle = getComputedStyle(element);
24
+
25
+ // @ts-ignore -- must use camelcase strings,
26
+ // or non-camelcase strings with `getPropertyValue`
27
+ return property in computedStyle ? computedStyle[property] : '';
28
+ }
29
+
30
+ /**
31
+ * Shortcut for `Object.assign()` static method.
32
+ * @param {Record<string, any>} obj a target object
33
+ * @param {Record<string, any>} source a source object
34
+ */
35
+ const ObjectAssign = (obj, source) => Object.assign(obj, source);
36
+
37
+ /**
38
+ * Shortcut for multiple uses of `HTMLElement.style.propertyName` method.
39
+ * @param {HTMLElement | Element} element target element
40
+ * @param {Partial<CSSStyleDeclaration>} styles attribute value
41
+ */
42
+ // @ts-ignore
43
+ const setElementStyle = (element, styles) => { ObjectAssign(element.style, styles); };
44
+
45
+ /**
46
+ * Shortcut for `String.toLowerCase()`.
47
+ *
48
+ * @param {string} source input string
49
+ * @returns {string} lowercase output string
50
+ */
51
+ const toLowerCase = (source) => source.toLowerCase();
52
+
53
+ /**
54
+ * A list of explicit default non-color values.
55
+ */
56
+ const nonColors = ['transparent', 'currentColor', 'inherit', 'revert', 'initial'];
57
+
58
+ /**
59
+ * Round colour components, for all formats except HEX.
60
+ * @param {number} v one of the colour components
61
+ * @returns {number} the rounded number
62
+ */
63
+ function roundPart(v) {
64
+ const floor = Math.floor(v);
65
+ return v - floor < 0.5 ? floor : Math.round(v);
66
+ }
67
+
68
+ // Color supported formats
69
+ const COLOR_FORMAT = ['rgb', 'hex', 'hsl', 'hsv', 'hwb'];
70
+
71
+ // Hue angles
72
+ const ANGLES = 'deg|rad|grad|turn';
73
+
74
+ // <http://www.w3.org/TR/css3-values/#integers>
75
+ const CSS_INTEGER = '[-\\+]?\\d+%?';
76
+
77
+ // Include CSS3 Module
78
+ // <http://www.w3.org/TR/css3-values/#number-value>
79
+ const CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?';
80
+
81
+ // Include CSS4 Module Hue degrees unit
82
+ // <https://www.w3.org/TR/css3-values/#angle-value>
83
+ const CSS_ANGLE = `[-\\+]?\\d*\\.?\\d+(?:${ANGLES})?`;
84
+
85
+ // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
86
+ const CSS_UNIT = `(?:${CSS_NUMBER})|(?:${CSS_INTEGER})`;
87
+
88
+ // Add angles to the mix
89
+ const CSS_UNIT2 = `(?:${CSS_UNIT})|(?:${CSS_ANGLE})`;
90
+
91
+ // Start & end
92
+ const START_MATCH = '(?:[\\s|\\(\\s|\\s\\(\\s]+)?';
93
+ const END_MATCH = '(?:[\\s|\\)\\s]+)?';
94
+ // Components separation
95
+ const SEP = '(?:[,|\\s]+)';
96
+ const SEP2 = '(?:[,|\\/\\s]*)?';
97
+
98
+ // Actual matching.
99
+ // Parentheses and commas are optional, but not required.
100
+ // Whitespace can take the place of commas or opening paren
101
+ const PERMISSIVE_MATCH = `${START_MATCH}(${CSS_UNIT2})${SEP}(${CSS_UNIT})${SEP}(${CSS_UNIT})${SEP2}(${CSS_UNIT})?${END_MATCH}`;
102
+
103
+ const matchers = {
104
+ CSS_UNIT: new RegExp(CSS_UNIT2),
105
+ hwb: new RegExp(`hwb${PERMISSIVE_MATCH}`),
106
+ rgb: new RegExp(`rgb(?:a)?${PERMISSIVE_MATCH}`),
107
+ hsl: new RegExp(`hsl(?:a)?${PERMISSIVE_MATCH}`),
108
+ hsv: new RegExp(`hsv(?:a)?${PERMISSIVE_MATCH}`),
109
+ hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
110
+ hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
111
+ hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
112
+ hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
113
+ };
114
+
115
+ /**
116
+ * Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
117
+ * <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
118
+ * @param {string} n testing number
119
+ * @returns {boolean} the query result
120
+ */
121
+ function isOnePointZero(n) {
122
+ return `${n}`.includes('.') && parseFloat(n) === 1;
123
+ }
124
+
125
+ /**
126
+ * Check to see if string passed in is a percentage
127
+ * @param {string} n testing number
128
+ * @returns {boolean} the query result
129
+ */
130
+ function isPercentage(n) {
131
+ return `${n}`.includes('%');
132
+ }
133
+
134
+ /**
135
+ * Check to see if string passed is a web safe colour.
136
+ * @see https://stackoverflow.com/a/16994164
137
+ * @param {string} color a colour name, EG: *red*
138
+ * @returns {boolean} the query result
139
+ */
140
+ function isColorName(color) {
141
+ if (nonColors.includes(color)
142
+ || ['#', ...COLOR_FORMAT].some((f) => color.includes(f))) return false;
143
+
144
+ if (['black', 'white'].includes(color)) return true;
145
+
146
+ return ['rgb(255, 255, 255)', 'rgb(0, 0, 0)'].every((c) => {
147
+ setElementStyle(documentHead, { color });
148
+ const computedColor = getElementStyle(documentHead, 'color');
149
+ setElementStyle(documentHead, { color: '' });
150
+ return computedColor !== c;
151
+ });
152
+ }
153
+
154
+ /**
155
+ * Check to see if it looks like a CSS unit
156
+ * (see `matchers` above for definition).
157
+ * @param {string | number} color testing value
158
+ * @returns {boolean} the query result
159
+ */
160
+ function isValidCSSUnit(color) {
161
+ return Boolean(matchers.CSS_UNIT.exec(String(color)));
162
+ }
163
+
164
+ /**
165
+ * Take input from [0, n] and return it as [0, 1]
166
+ * @param {*} N the input number
167
+ * @param {number} max the number maximum value
168
+ * @returns {number} the number in [0, 1] value range
169
+ */
170
+ function bound01(N, max) {
171
+ let n = N;
172
+
173
+ if (typeof N === 'number'
174
+ && Math.min(N, 0) === 0 // round values to 6 decimals Math.round(N * (10 ** 6)) / 10 ** 6
175
+ && Math.max(N, 1) === 1) return N;
176
+
177
+ if (isOnePointZero(N)) n = '100%';
178
+
179
+ const processPercent = isPercentage(n);
180
+ n = max === 360
181
+ ? parseFloat(n)
182
+ : Math.min(max, Math.max(0, parseFloat(n)));
183
+
184
+ // Automatically convert percentage into number
185
+ if (processPercent) n = (n * max) / 100;
186
+
187
+ // Handle floating point rounding errors
188
+ if (Math.abs(n - max) < 0.000001) {
189
+ return 1;
190
+ }
191
+ // Convert into [0, 1] range if it isn't already
192
+ if (max === 360) {
193
+ // If n is a hue given in degrees,
194
+ // wrap around out-of-range values into [0, 360] range
195
+ // then convert into [0, 1].
196
+ n = (n < 0 ? (n % max) + max : n % max) / max;
197
+ } else {
198
+ // If n not a hue given in degrees
199
+ // Convert into [0, 1] range if it isn't already.
200
+ n = (n % max) / max;
201
+ }
202
+ return n;
203
+ }
204
+
205
+ /**
206
+ * Return a valid alpha value [0,1] with all invalid values being set to 1.
207
+ * @param {string | number} a transparency value
208
+ * @returns {number} a transparency value in the [0, 1] range
209
+ */
210
+ function boundAlpha(a) {
211
+ let na = parseFloat(`${a}`);
212
+
213
+ if (Number.isNaN(na) || na < 0 || na > 1) {
214
+ na = 1;
215
+ }
216
+
217
+ return na;
218
+ }
219
+
220
+ /**
221
+ * Force a number between 0 and 1.
222
+ * @param {number} v the float number
223
+ * @returns {number} - the resulting number
224
+ */
225
+ function clamp01(v) {
226
+ return Math.min(1, Math.max(0, v));
227
+ }
228
+
229
+ /**
230
+ * Returns the hexadecimal value of a web safe colour.
231
+ * @param {string} name
232
+ * @returns {string}
233
+ */
234
+ function getRGBFromName(name) {
235
+ setElementStyle(documentHead, { color: name });
236
+ const colorName = getElementStyle(documentHead, 'color');
237
+ setElementStyle(documentHead, { color: '' });
238
+ return colorName;
239
+ }
240
+
241
+ /**
242
+ * Converts a decimal value to hexadecimal.
243
+ * @param {number} d the input number
244
+ * @returns {string} - the hexadecimal value
245
+ */
246
+ function convertDecimalToHex(d) {
247
+ return roundPart(d * 255).toString(16);
248
+ }
249
+
250
+ /**
251
+ * Converts a hexadecimal value to decimal.
252
+ * @param {string} h hexadecimal value
253
+ * @returns {number} number in decimal format
254
+ */
255
+ function convertHexToDecimal(h) {
256
+ return parseIntFromHex(h) / 255;
257
+ }
258
+
259
+ /**
260
+ * Converts a base-16 hexadecimal value into a base-10 integer.
261
+ * @param {string} val
262
+ * @returns {number}
263
+ */
264
+ function parseIntFromHex(val) {
265
+ return parseInt(val, 16);
266
+ }
267
+
268
+ /**
269
+ * Force a hexadecimal value to have 2 characters.
270
+ * @param {string} c string with [0-9A-F] ranged values
271
+ * @returns {string} 0 => 00, a => 0a
272
+ */
273
+ function pad2(c) {
274
+ return c.length === 1 ? `0${c}` : String(c);
275
+ }
276
+
277
+ /**
278
+ * Converts an RGB colour value to HSL.
279
+ *
280
+ * @param {number} r Red component [0, 1]
281
+ * @param {number} g Green component [0, 1]
282
+ * @param {number} b Blue component [0, 1]
283
+ * @returns {CP.HSL} {h,s,l} object with [0, 1] ranged values
284
+ */
285
+ function rgbToHsl(r, g, b) {
286
+ const max = Math.max(r, g, b);
287
+ const min = Math.min(r, g, b);
288
+ let h = 0;
289
+ let s = 0;
290
+ const l = (max + min) / 2;
291
+ if (max === min) {
292
+ s = 0;
293
+ h = 0; // achromatic
294
+ } else {
295
+ const d = max - min;
296
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
297
+ if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
298
+ if (max === g) h = (b - r) / d + 2;
299
+ if (max === b) h = (r - g) / d + 4;
300
+
301
+ h /= 6;
302
+ }
303
+ return { h, s, l };
304
+ }
305
+
306
+ /**
307
+ * Returns a normalized RGB component value.
308
+ * @param {number} p
309
+ * @param {number} q
310
+ * @param {number} t
311
+ * @returns {number}
312
+ */
313
+ function hueToRgb(p, q, t) {
314
+ let T = t;
315
+ if (T < 0) T += 1;
316
+ if (T > 1) T -= 1;
317
+ if (T < 1 / 6) return p + (q - p) * (6 * T);
318
+ if (T < 1 / 2) return q;
319
+ if (T < 2 / 3) return p + (q - p) * (2 / 3 - T) * 6;
320
+ return p;
321
+ }
322
+
323
+ /**
324
+ * Converts an HSL colour value to RGB.
325
+ *
326
+ * @param {number} h Hue Angle [0, 1]
327
+ * @param {number} s Saturation [0, 1]
328
+ * @param {number} l Lightness Angle [0, 1]
329
+ * @returns {CP.RGB} {r,g,b} object with [0, 1] ranged values
330
+ */
331
+ function hslToRgb(h, s, l) {
332
+ let r = 0;
333
+ let g = 0;
334
+ let b = 0;
335
+
336
+ if (s === 0) {
337
+ // achromatic
338
+ g = l;
339
+ b = l;
340
+ r = l;
341
+ } else {
342
+ const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
343
+ const p = 2 * l - q;
344
+ r = hueToRgb(p, q, h + 1 / 3);
345
+ g = hueToRgb(p, q, h);
346
+ b = hueToRgb(p, q, h - 1 / 3);
347
+ }
348
+
349
+ return { r, g, b };
350
+ }
351
+
352
+ /**
353
+ * Returns an HWB colour object from an RGB colour object.
354
+ * @link https://www.w3.org/TR/css-color-4/#hwb-to-rgb
355
+ * @link http://alvyray.com/Papers/CG/hwb2rgb.htm
356
+ *
357
+ * @param {number} r Red component [0, 1]
358
+ * @param {number} g Green [0, 1]
359
+ * @param {number} b Blue [0, 1]
360
+ * @return {CP.HWB} {h,w,b} object with [0, 1] ranged values
361
+ */
362
+ function rgbToHwb(r, g, b) {
363
+ let f = 0;
364
+ let i = 0;
365
+ const whiteness = Math.min(r, g, b);
366
+ const max = Math.max(r, g, b);
367
+ const black = 1 - max;
368
+
369
+ if (max === whiteness) return { h: 0, w: whiteness, b: black };
370
+ if (r === whiteness) {
371
+ f = g - b;
372
+ i = 3;
373
+ } else {
374
+ f = g === whiteness ? b - r : r - g;
375
+ i = g === whiteness ? 5 : 1;
376
+ }
377
+
378
+ const h = (i - f / (max - whiteness)) / 6;
379
+ return {
380
+ h: h === 1 ? 0 : h,
381
+ w: whiteness,
382
+ b: black,
383
+ };
384
+ }
385
+
386
+ /**
387
+ * Returns an RGB colour object from an HWB colour.
388
+ *
389
+ * @param {number} H Hue Angle [0, 1]
390
+ * @param {number} W Whiteness [0, 1]
391
+ * @param {number} B Blackness [0, 1]
392
+ * @return {CP.RGB} {r,g,b} object with [0, 1] ranged values
393
+ *
394
+ * @link https://www.w3.org/TR/css-color-4/#hwb-to-rgb
395
+ * @link http://alvyray.com/Papers/CG/hwb2rgb.htm
396
+ */
397
+ function hwbToRgb(H, W, B) {
398
+ if (W + B >= 1) {
399
+ const gray = W / (W + B);
400
+ return { r: gray, g: gray, b: gray };
401
+ }
402
+ let { r, g, b } = hslToRgb(H, 1, 0.5);
403
+ [r, g, b] = [r, g, b].map((v) => v * (1 - W - B) + W);
404
+
405
+ return { r, g, b };
406
+ }
407
+
408
+ /**
409
+ * Converts an RGB colour value to HSV.
410
+ *
411
+ * @param {number} r Red component [0, 1]
412
+ * @param {number} g Green [0, 1]
413
+ * @param {number} b Blue [0, 1]
414
+ * @returns {CP.HSV} {h,s,v} object with [0, 1] ranged values
415
+ */
416
+ function rgbToHsv(r, g, b) {
417
+ const max = Math.max(r, g, b);
418
+ const min = Math.min(r, g, b);
419
+ let h = 0;
420
+ const v = max;
421
+ const d = max - min;
422
+ const s = max === 0 ? 0 : d / max;
423
+ if (max === min) {
424
+ h = 0; // achromatic
425
+ } else {
426
+ if (r === max) h = (g - b) / d + (g < b ? 6 : 0);
427
+ if (g === max) h = (b - r) / d + 2;
428
+ if (b === max) h = (r - g) / d + 4;
429
+
430
+ h /= 6;
431
+ }
432
+ return { h, s, v };
433
+ }
434
+
435
+ /**
436
+ * Converts an HSV colour value to RGB.
437
+ *
438
+ * @param {number} H Hue Angle [0, 1]
439
+ * @param {number} S Saturation [0, 1]
440
+ * @param {number} V Brightness Angle [0, 1]
441
+ * @returns {CP.RGB} {r,g,b} object with [0, 1] ranged values
442
+ */
443
+ function hsvToRgb(H, S, V) {
444
+ const h = H * 6;
445
+ const s = S;
446
+ const v = V;
447
+ const i = Math.floor(h);
448
+ const f = h - i;
449
+ const p = v * (1 - s);
450
+ const q = v * (1 - f * s);
451
+ const t = v * (1 - (1 - f) * s);
452
+ const mod = i % 6;
453
+ const r = [v, q, p, p, t, v][mod];
454
+ const g = [t, v, v, q, p, p][mod];
455
+ const b = [p, p, t, v, v, q][mod];
456
+ return { r, g, b };
457
+ }
458
+
459
+ /**
460
+ * Converts an RGB colour to hex
461
+ *
462
+ * Assumes r, g, and b are contained in the set [0, 255]
463
+ * Returns a 3 or 6 character hex
464
+ * @param {number} r Red component [0, 255]
465
+ * @param {number} g Green [0, 255]
466
+ * @param {number} b Blue [0, 255]
467
+ * @param {boolean=} allow3Char
468
+ * @returns {string}
469
+ */
470
+ function rgbToHex(r, g, b, allow3Char) {
471
+ const hex = [
472
+ pad2(roundPart(r).toString(16)),
473
+ pad2(roundPart(g).toString(16)),
474
+ pad2(roundPart(b).toString(16)),
475
+ ];
476
+
477
+ // Return a 3 character hex if possible
478
+ if (allow3Char && hex[0].charAt(0) === hex[0].charAt(1)
479
+ && hex[1].charAt(0) === hex[1].charAt(1)
480
+ && hex[2].charAt(0) === hex[2].charAt(1)) {
481
+ return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
482
+ }
483
+
484
+ return hex.join('');
485
+ }
486
+
487
+ /**
488
+ * Converts an RGBA color plus alpha transparency to hex8.
489
+ *
490
+ * @param {number} r Red component [0, 255]
491
+ * @param {number} g Green [0, 255]
492
+ * @param {number} b Blue [0, 255]
493
+ * @param {number} a Alpha transparency [0, 1]
494
+ * @param {boolean=} allow4Char when *true* it will also find hex shorthand
495
+ * @returns {string} a hexadecimal value with alpha transparency
496
+ */
497
+ function rgbaToHex(r, g, b, a, allow4Char) {
498
+ const hex = [
499
+ pad2(roundPart(r).toString(16)),
500
+ pad2(roundPart(g).toString(16)),
501
+ pad2(roundPart(b).toString(16)),
502
+ pad2(convertDecimalToHex(a)),
503
+ ];
504
+
505
+ // Return a 4 character hex if possible
506
+ if (allow4Char && hex[0].charAt(0) === hex[0].charAt(1)
507
+ && hex[1].charAt(0) === hex[1].charAt(1)
508
+ && hex[2].charAt(0) === hex[2].charAt(1)
509
+ && hex[3].charAt(0) === hex[3].charAt(1)) {
510
+ return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
511
+ }
512
+ return hex.join('');
513
+ }
514
+
515
+ /**
516
+ * Permissive string parsing. Take in a number of formats, and output an object
517
+ * based on detected format. Returns {r,g,b} or {h,s,l} or {h,s,v}
518
+ * @param {string} input colour value in any format
519
+ * @returns {Record<string, (number | string | boolean)> | false} an object matching the RegExp
520
+ */
521
+ function stringInputToObject(input) {
522
+ let color = toLowerCase(input.trim());
523
+
524
+ if (color.length === 0) {
525
+ return {
526
+ r: 0, g: 0, b: 0, a: 1,
527
+ };
528
+ }
529
+
530
+ if (isColorName(color)) {
531
+ color = getRGBFromName(color);
532
+ } else if (nonColors.includes(color)) {
533
+ const a = color === 'transparent' ? 0 : 1;
534
+ return {
535
+ r: 0, g: 0, b: 0, a, format: 'rgb', ok: true,
536
+ };
537
+ }
538
+
539
+ // Try to match string input using regular expressions.
540
+ // Keep most of the number bounding out of this function,
541
+ // don't worry about [0,1] or [0,100] or [0,360]
542
+ // Just return an object and let the conversion functions handle that.
543
+ // This way the result will be the same whether Color is initialized with string or object.
544
+ let [, m1, m2, m3, m4] = matchers.rgb.exec(color) || [];
545
+ if (m1 && m2 && m3/* && m4 */) {
546
+ return {
547
+ r: m1, g: m2, b: m3, a: m4 !== undefined ? m4 : 1, format: 'rgb',
548
+ };
549
+ }
550
+
551
+ [, m1, m2, m3, m4] = matchers.hsl.exec(color) || [];
552
+ if (m1 && m2 && m3/* && m4 */) {
553
+ return {
554
+ h: m1, s: m2, l: m3, a: m4 !== undefined ? m4 : 1, format: 'hsl',
555
+ };
556
+ }
557
+
558
+ [, m1, m2, m3, m4] = matchers.hsv.exec(color) || [];
559
+ if (m1 && m2 && m3/* && m4 */) {
560
+ return {
561
+ h: m1, s: m2, v: m3, a: m4 !== undefined ? m4 : 1, format: 'hsv',
562
+ };
563
+ }
564
+
565
+ [, m1, m2, m3, m4] = matchers.hwb.exec(color) || [];
566
+ if (m1 && m2 && m3) {
567
+ return {
568
+ h: m1, w: m2, b: m3, a: m4 !== undefined ? m4 : 1, format: 'hwb',
569
+ };
570
+ }
571
+
572
+ [, m1, m2, m3, m4] = matchers.hex8.exec(color) || [];
573
+ if (m1 && m2 && m3 && m4) {
574
+ return {
575
+ r: parseIntFromHex(m1),
576
+ g: parseIntFromHex(m2),
577
+ b: parseIntFromHex(m3),
578
+ a: convertHexToDecimal(m4),
579
+ format: 'hex',
580
+ };
581
+ }
582
+
583
+ [, m1, m2, m3] = matchers.hex6.exec(color) || [];
584
+ if (m1 && m2 && m3) {
585
+ return {
586
+ r: parseIntFromHex(m1),
587
+ g: parseIntFromHex(m2),
588
+ b: parseIntFromHex(m3),
589
+ format: 'hex',
590
+ };
591
+ }
592
+
593
+ [, m1, m2, m3, m4] = matchers.hex4.exec(color) || [];
594
+ if (m1 && m2 && m3 && m4) {
595
+ return {
596
+ r: parseIntFromHex(m1 + m1),
597
+ g: parseIntFromHex(m2 + m2),
598
+ b: parseIntFromHex(m3 + m3),
599
+ a: convertHexToDecimal(m4 + m4),
600
+ format: 'hex',
601
+ };
602
+ }
603
+
604
+ [, m1, m2, m3] = matchers.hex3.exec(color) || [];
605
+ if (m1 && m2 && m3) {
606
+ return {
607
+ r: parseIntFromHex(m1 + m1),
608
+ g: parseIntFromHex(m2 + m2),
609
+ b: parseIntFromHex(m3 + m3),
610
+ format: 'hex',
611
+ };
612
+ }
613
+
614
+ return false;
615
+ }
616
+
617
+ /**
618
+ * Given a string or object, convert that input to RGB
619
+ *
620
+ * Possible string inputs:
621
+ * ```
622
+ * "red"
623
+ * "#f00" or "f00"
624
+ * "#ff0000" or "ff0000"
625
+ * "#ff000000" or "ff000000" // CSS4 Module
626
+ * "rgb 255 0 0" or "rgb (255, 0, 0)"
627
+ * "rgb 1.0 0 0" or "rgb (1, 0, 0)"
628
+ * "rgba(255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
629
+ * "rgba(1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
630
+ * "rgb(255 0 0 / 10%)" or "rgb 255 0 0 0.1" // CSS4 Module
631
+ * "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
632
+ * "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
633
+ * "hsl(0deg 100% 50% / 50%)" or "hsl 0 100 50 50" // CSS4 Module
634
+ * "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
635
+ * "hsva(0, 100%, 100%, 0.1)" or "hsva 0 100% 100% 0.1"
636
+ * "hsv(0deg 100% 100% / 10%)" or "hsv 0 100 100 0.1" // CSS4 Module
637
+ * "hwb(0deg, 100%, 100%, 100%)" or "hwb 0 100% 100% 0.1" // CSS4 Module
638
+ * ```
639
+ * @param {string | Record<string, any>} input
640
+ * @returns {CP.ColorObject}
641
+ */
642
+ function inputToRGB(input) {
643
+ let rgb = { r: 0, g: 0, b: 0 };
644
+ /** @type {*} */
645
+ let color = input;
646
+ /** @type {string | number} */
647
+ let a = 1;
648
+ let s = null;
649
+ let v = null;
650
+ let l = null;
651
+ let w = null;
652
+ let b = null;
653
+ let h = null;
654
+ let r = null;
655
+ let g = null;
656
+ let ok = false;
657
+ const inputFormat = typeof color === 'object' && color.format;
658
+ let format = inputFormat && COLOR_FORMAT.includes(inputFormat) ? inputFormat : 'rgb';
659
+
660
+ if (typeof input === 'string') {
661
+ color = stringInputToObject(input);
662
+ if (color) ok = true;
663
+ }
664
+ if (typeof color === 'object') {
665
+ if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
666
+ ({ r, g, b } = color);
667
+ // RGB values now are all in [0, 1] range
668
+ [r, g, b] = [r, g, b].map((n) => bound01(n, isPercentage(n) ? 100 : 255));
669
+ rgb = { r, g, b };
670
+ ok = true;
671
+ format = color.format || 'rgb';
672
+ }
673
+ if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
674
+ ({ h, s, v } = color);
675
+ h = bound01(h, 360); // hue can be `5deg` or a [0, 1] value
676
+ s = bound01(s, 100); // saturation can be `5%` or a [0, 1] value
677
+ v = bound01(v, 100); // brightness can be `5%` or a [0, 1] value
678
+ rgb = hsvToRgb(h, s, v);
679
+ ok = true;
680
+ format = 'hsv';
681
+ }
682
+ if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
683
+ ({ h, s, l } = color);
684
+ h = bound01(h, 360); // hue can be `5deg` or a [0, 1] value
685
+ s = bound01(s, 100); // saturation can be `5%` or a [0, 1] value
686
+ l = bound01(l, 100); // lightness can be `5%` or a [0, 1] value
687
+ rgb = hslToRgb(h, s, l);
688
+ ok = true;
689
+ format = 'hsl';
690
+ }
691
+ if (isValidCSSUnit(color.h) && isValidCSSUnit(color.w) && isValidCSSUnit(color.b)) {
692
+ ({ h, w, b } = color);
693
+ h = bound01(h, 360); // hue can be `5deg` or a [0, 1] value
694
+ w = bound01(w, 100); // whiteness can be `5%` or a [0, 1] value
695
+ b = bound01(b, 100); // blackness can be `5%` or a [0, 1] value
696
+ rgb = hwbToRgb(h, w, b);
697
+ ok = true;
698
+ format = 'hwb';
699
+ }
700
+ if (isValidCSSUnit(color.a)) {
701
+ a = color.a; // @ts-ignore -- `parseFloat` works with numbers too
702
+ a = isPercentage(`${a}`) || parseFloat(a) > 1 ? bound01(a, 100) : a;
703
+ }
704
+ }
705
+ if (typeof color === 'undefined') {
706
+ ok = true;
707
+ }
708
+
709
+ return {
710
+ ok,
711
+ format,
712
+ // r: Math.min(255, Math.max(rgb.r, 0)),
713
+ // g: Math.min(255, Math.max(rgb.g, 0)),
714
+ // b: Math.min(255, Math.max(rgb.b, 0)),
715
+ r: rgb.r,
716
+ g: rgb.g,
717
+ b: rgb.b,
718
+ a: boundAlpha(a),
719
+ };
720
+ }
721
+
722
+ /**
723
+ * @class
724
+ * Returns a new `Color` instance.
725
+ * @see https://github.com/bgrins/TinyColor
726
+ */
727
+ class Color {
728
+ /**
729
+ * @constructor
730
+ * @param {CP.ColorInput} input the given colour value
731
+ * @param {CP.ColorFormats=} config the given format
732
+ */
733
+ constructor(input, config) {
734
+ let color = input;
735
+ const configFormat = config && COLOR_FORMAT.includes(config)
736
+ ? config : '';
737
+
738
+ // If input is already a `Color`, clone its values
739
+ if (color instanceof Color) {
740
+ color = inputToRGB(color);
741
+ }
742
+
743
+ const {
744
+ r, g, b, a, ok, format,
745
+ } = inputToRGB(color);
746
+
747
+ // bind
748
+ const self = this;
749
+
750
+ /** @type {CP.ColorInput} */
751
+ self.originalInput = input;
752
+ /** @type {number} */
753
+ self.r = r;
754
+ /** @type {number} */
755
+ self.g = g;
756
+ /** @type {number} */
757
+ self.b = b;
758
+ /** @type {number} */
759
+ self.a = a;
760
+ /** @type {boolean} */
761
+ self.ok = ok;
762
+ /** @type {CP.ColorFormats} */
763
+ self.format = configFormat || format;
764
+ }
765
+
766
+ /**
767
+ * Checks if the current input value is a valid colour.
768
+ * @returns {boolean} the query result
769
+ */
770
+ get isValid() {
771
+ return this.ok;
772
+ }
773
+
774
+ /**
775
+ * Checks if the current colour requires a light text colour.
776
+ * @returns {boolean} the query result
777
+ */
778
+ get isDark() {
779
+ return this.brightness < 120;
780
+ }
781
+
782
+ /**
783
+ * Returns the perceived luminance of a colour.
784
+ * @see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
785
+ * @returns {number} a number in the [0, 1] range
786
+ */
787
+ get luminance() {
788
+ const { r, g, b } = this;
789
+ let R = 0;
790
+ let G = 0;
791
+ let B = 0;
792
+
793
+ if (r <= 0.03928) {
794
+ R = r / 12.92;
795
+ } else {
796
+ R = ((r + 0.055) / 1.055) ** 2.4;
797
+ }
798
+ if (g <= 0.03928) {
799
+ G = g / 12.92;
800
+ } else {
801
+ G = ((g + 0.055) / 1.055) ** 2.4;
802
+ }
803
+ if (b <= 0.03928) {
804
+ B = b / 12.92;
805
+ } else {
806
+ B = ((b + 0.055) / 1.055) ** 2.4;
807
+ }
808
+ return 0.2126 * R + 0.7152 * G + 0.0722 * B;
809
+ }
810
+
811
+ /**
812
+ * Returns the perceived brightness of the colour.
813
+ * @returns {number} a number in the [0, 255] range
814
+ */
815
+ get brightness() {
816
+ const { r, g, b } = this.toRgb();
817
+ return (r * 299 + g * 587 + b * 114) / 1000;
818
+ }
819
+
820
+ /**
821
+ * Returns the colour as an RGBA object.
822
+ * @returns {CP.RGBA} an {r,g,b,a} object with [0, 255] ranged values
823
+ */
824
+ toRgb() {
825
+ let {
826
+ r, g, b, a,
827
+ } = this;
828
+
829
+ [r, g, b] = [r, g, b].map((n) => roundPart(n * 255 * 100) / 100);
830
+ a = roundPart(a * 100) / 100;
831
+ return {
832
+ r, g, b, a,
833
+ };
834
+ }
835
+
836
+ /**
837
+ * Returns the RGBA values concatenated into a CSS3 Module string format.
838
+ * * rgb(255,255,255)
839
+ * * rgba(255,255,255,0.5)
840
+ * @returns {string} the CSS valid colour in RGB/RGBA format
841
+ */
842
+ toRgbString() {
843
+ const {
844
+ r, g, b, a,
845
+ } = this.toRgb();
846
+ const [R, G, B] = [r, g, b].map(roundPart);
847
+
848
+ return a === 1
849
+ ? `rgb(${R}, ${G}, ${B})`
850
+ : `rgba(${R}, ${G}, ${B}, ${a})`;
851
+ }
852
+
853
+ /**
854
+ * Returns the RGBA values concatenated into a CSS4 Module string format.
855
+ * * rgb(255 255 255)
856
+ * * rgb(255 255 255 / 50%)
857
+ * @returns {string} the CSS valid colour in CSS4 RGB format
858
+ */
859
+ toRgbCSS4String() {
860
+ const {
861
+ r, g, b, a,
862
+ } = this.toRgb();
863
+ const [R, G, B] = [r, g, b].map(roundPart);
864
+ const A = a === 1 ? '' : ` / ${roundPart(a * 100)}%`;
865
+
866
+ return `rgb(${R} ${G} ${B}${A})`;
867
+ }
868
+
869
+ /**
870
+ * Returns the hexadecimal value of the colour. When the parameter is *true*
871
+ * it will find a 3 characters shorthand of the decimal value.
872
+ *
873
+ * @param {boolean=} allow3Char when `true` returns shorthand HEX
874
+ * @returns {string} the hexadecimal colour format
875
+ */
876
+ toHex(allow3Char) {
877
+ const {
878
+ r, g, b, a,
879
+ } = this.toRgb();
880
+
881
+ return a === 1
882
+ ? rgbToHex(r, g, b, allow3Char)
883
+ : rgbaToHex(r, g, b, a, allow3Char);
884
+ }
885
+
886
+ /**
887
+ * Returns the CSS valid hexadecimal vaue of the colour. When the parameter is *true*
888
+ * it will find a 3 characters shorthand of the value.
889
+ *
890
+ * @param {boolean=} allow3Char when `true` returns shorthand HEX
891
+ * @returns {string} the CSS valid colour in hexadecimal format
892
+ */
893
+ toHexString(allow3Char) {
894
+ return `#${this.toHex(allow3Char)}`;
895
+ }
896
+
897
+ /**
898
+ * Returns the HEX8 value of the colour.
899
+ * @param {boolean=} allow4Char when `true` returns shorthand HEX
900
+ * @returns {string} the CSS valid colour in hexadecimal format
901
+ */
902
+ toHex8(allow4Char) {
903
+ const {
904
+ r, g, b, a,
905
+ } = this.toRgb();
906
+
907
+ return rgbaToHex(r, g, b, a, allow4Char);
908
+ }
909
+
910
+ /**
911
+ * Returns the HEX8 value of the colour.
912
+ * @param {boolean=} allow4Char when `true` returns shorthand HEX
913
+ * @returns {string} the CSS valid colour in hexadecimal format
914
+ */
915
+ toHex8String(allow4Char) {
916
+ return `#${this.toHex8(allow4Char)}`;
917
+ }
918
+
919
+ /**
920
+ * Returns the colour as a HSVA object.
921
+ * @returns {CP.HSVA} the `{h,s,v,a}` object with [0, 1] ranged values
922
+ */
923
+ toHsv() {
924
+ const {
925
+ r, g, b, a,
926
+ } = this;
927
+ const { h, s, v } = rgbToHsv(r, g, b);
928
+
929
+ return {
930
+ h, s, v, a,
931
+ };
932
+ }
933
+
934
+ /**
935
+ * Returns the colour as an HSLA object.
936
+ * @returns {CP.HSLA} the `{h,s,l,a}` object with [0, 1] ranged values
937
+ */
938
+ toHsl() {
939
+ const {
940
+ r, g, b, a,
941
+ } = this;
942
+ const { h, s, l } = rgbToHsl(r, g, b);
943
+
944
+ return {
945
+ h, s, l, a,
946
+ };
947
+ }
948
+
949
+ /**
950
+ * Returns the HSLA values concatenated into a CSS3 Module format string.
951
+ * * `hsl(150, 100%, 50%)`
952
+ * * `hsla(150, 100%, 50%, 0.5)`
953
+ * @returns {string} the CSS valid colour in HSL/HSLA format
954
+ */
955
+ toHslString() {
956
+ let {
957
+ h, s, l, a,
958
+ } = this.toHsl();
959
+ h = roundPart(h * 360);
960
+ s = roundPart(s * 100);
961
+ l = roundPart(l * 100);
962
+ a = roundPart(a * 100) / 100;
963
+
964
+ return a === 1
965
+ ? `hsl(${h}, ${s}%, ${l}%)`
966
+ : `hsla(${h}, ${s}%, ${l}%, ${a})`;
967
+ }
968
+
969
+ /**
970
+ * Returns the HSLA values concatenated into a CSS4 Module format string.
971
+ * * `hsl(150deg 100% 50%)`
972
+ * * `hsl(150deg 100% 50% / 50%)`
973
+ * @returns {string} the CSS valid colour in CSS4 HSL format
974
+ */
975
+ toHslCSS4String() {
976
+ let {
977
+ h, s, l, a,
978
+ } = this.toHsl();
979
+ h = roundPart(h * 360);
980
+ s = roundPart(s * 100);
981
+ l = roundPart(l * 100);
982
+ a = roundPart(a * 100);
983
+ const A = a < 100 ? ` / ${roundPart(a)}%` : '';
984
+
985
+ return `hsl(${h}deg ${s}% ${l}%${A})`;
986
+ }
987
+
988
+ /**
989
+ * Returns the colour as an HWBA object.
990
+ * @returns {CP.HWBA} the `{h,w,b,a}` object with [0, 1] ranged values
991
+ */
992
+ toHwb() {
993
+ const {
994
+ r, g, b, a,
995
+ } = this;
996
+ const { h, w, b: bl } = rgbToHwb(r, g, b);
997
+ return {
998
+ h, w, b: bl, a,
999
+ };
1000
+ }
1001
+
1002
+ /**
1003
+ * Returns the HWBA values concatenated into a string.
1004
+ * @returns {string} the CSS valid colour in HWB format
1005
+ */
1006
+ toHwbString() {
1007
+ let {
1008
+ h, w, b, a,
1009
+ } = this.toHwb();
1010
+ h = roundPart(h * 360);
1011
+ w = roundPart(w * 100);
1012
+ b = roundPart(b * 100);
1013
+ a = roundPart(a * 100);
1014
+ const A = a < 100 ? ` / ${roundPart(a)}%` : '';
1015
+
1016
+ return `hwb(${h}deg ${w}% ${b}%${A})`;
1017
+ }
1018
+
1019
+ /**
1020
+ * Sets the alpha value of the current colour.
1021
+ * @param {number} alpha a new alpha value in the [0, 1] range.
1022
+ * @returns {Color} the `Color` instance
1023
+ */
1024
+ setAlpha(alpha) {
1025
+ const self = this;
1026
+ if (typeof alpha !== 'number') return self;
1027
+ self.a = boundAlpha(alpha);
1028
+ return self;
1029
+ }
1030
+
1031
+ /**
1032
+ * Saturate the colour with a given amount.
1033
+ * @param {number=} amount a value in the [0, 100] range
1034
+ * @returns {Color} the `Color` instance
1035
+ */
1036
+ saturate(amount) {
1037
+ const self = this;
1038
+ if (typeof amount !== 'number') return self;
1039
+ const { h, s, l } = self.toHsl();
1040
+ const { r, g, b } = hslToRgb(h, clamp01(s + amount / 100), l);
1041
+
1042
+ ObjectAssign(self, { r, g, b });
1043
+ return self;
1044
+ }
1045
+
1046
+ /**
1047
+ * Desaturate the colour with a given amount.
1048
+ * @param {number=} amount a value in the [0, 100] range
1049
+ * @returns {Color} the `Color` instance
1050
+ */
1051
+ desaturate(amount) {
1052
+ return typeof amount === 'number' ? this.saturate(-amount) : this;
1053
+ }
1054
+
1055
+ /**
1056
+ * Completely desaturates a colour into greyscale.
1057
+ * Same as calling `desaturate(100)`
1058
+ * @returns {Color} the `Color` instance
1059
+ */
1060
+ greyscale() {
1061
+ return this.saturate(-100);
1062
+ }
1063
+
1064
+ /**
1065
+ * Increase the colour lightness with a given amount.
1066
+ * @param {number=} amount a value in the [0, 100] range
1067
+ * @returns {Color} the `Color` instance
1068
+ */
1069
+ lighten(amount) {
1070
+ const self = this;
1071
+ if (typeof amount !== 'number') return self;
1072
+
1073
+ const { h, s, l } = self.toHsl();
1074
+ const { r, g, b } = hslToRgb(h, s, clamp01(l + amount / 100));
1075
+
1076
+ ObjectAssign(self, { r, g, b });
1077
+ return self;
1078
+ }
1079
+
1080
+ /**
1081
+ * Decrease the colour lightness with a given amount.
1082
+ * @param {number=} amount a value in the [0, 100] range
1083
+ * @returns {Color} the `Color` instance
1084
+ */
1085
+ darken(amount) {
1086
+ return typeof amount === 'number' ? this.lighten(-amount) : this;
1087
+ }
1088
+
1089
+ /**
1090
+ * Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
1091
+ * Values outside of this range will be wrapped into this range.
1092
+ *
1093
+ * @param {number=} amount a value in the [0, 100] range
1094
+ * @returns {Color} the `Color` instance
1095
+ */
1096
+ spin(amount) {
1097
+ const self = this;
1098
+ if (typeof amount !== 'number') return self;
1099
+
1100
+ const { h, s, l } = self.toHsl();
1101
+ const { r, g, b } = hslToRgb(clamp01(((h * 360 + amount) % 360) / 360), s, l);
1102
+
1103
+ ObjectAssign(self, { r, g, b });
1104
+ return self;
1105
+ }
1106
+
1107
+ /** Returns a clone of the current `Color` instance. */
1108
+ clone() {
1109
+ return new Color(this);
1110
+ }
1111
+
1112
+ /**
1113
+ * Returns the colour value in CSS valid string format.
1114
+ * @param {boolean=} allowShort when *true*, HEX values can be shorthand
1115
+ * @returns {string} the CSS valid colour in the configured format
1116
+ */
1117
+ toString(allowShort) {
1118
+ const self = this;
1119
+ const { format } = self;
1120
+
1121
+ if (format === 'hex') return self.toHexString(allowShort);
1122
+ if (format === 'hsl') return self.toHslString();
1123
+ if (format === 'hwb') return self.toHwbString();
1124
+
1125
+ return self.toRgbString();
1126
+ }
1127
+ }
1128
+
1129
+ ObjectAssign(Color, {
1130
+ ANGLES,
1131
+ CSS_ANGLE,
1132
+ CSS_INTEGER,
1133
+ CSS_NUMBER,
1134
+ CSS_UNIT,
1135
+ CSS_UNIT2,
1136
+ PERMISSIVE_MATCH,
1137
+ matchers,
1138
+ isOnePointZero,
1139
+ isPercentage,
1140
+ isValidCSSUnit,
1141
+ isColorName,
1142
+ pad2,
1143
+ clamp01,
1144
+ bound01,
1145
+ boundAlpha,
1146
+ getRGBFromName,
1147
+ convertHexToDecimal,
1148
+ convertDecimalToHex,
1149
+ rgbToHsl,
1150
+ rgbToHex,
1151
+ rgbToHsv,
1152
+ rgbToHwb,
1153
+ rgbaToHex,
1154
+ hslToRgb,
1155
+ hsvToRgb,
1156
+ hueToRgb,
1157
+ hwbToRgb,
1158
+ parseIntFromHex,
1159
+ stringInputToObject,
1160
+ inputToRGB,
1161
+ roundPart,
1162
+ getElementStyle,
1163
+ setElementStyle,
1164
+ ObjectAssign,
1165
+ });
1166
+
1167
+ export { Color as default };