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