@thednp/color-picker 1.0.0 → 2.0.0-alpha1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (88) hide show
  1. package/.eslintrc.cjs +199 -0
  2. package/.lgtm.yml +9 -0
  3. package/.prettierrc.json +15 -0
  4. package/.stylelintrc.json +236 -0
  5. package/LICENSE +0 -0
  6. package/README.md +63 -80
  7. package/compile.js +48 -0
  8. package/cypress/downloads/downloads.htm +0 -0
  9. package/cypress/e2e/color-palette.cy.ts +128 -0
  10. package/cypress/e2e/color-picker.cy.ts +920 -0
  11. package/cypress/fixtures/colorNamesFrench.js +3 -0
  12. package/cypress/fixtures/componentLabelsFrench.js +21 -0
  13. package/cypress/fixtures/format.js +3 -0
  14. package/cypress/fixtures/getCEMarkup.js +29 -0
  15. package/cypress/fixtures/getMarkup.js +28 -0
  16. package/cypress/fixtures/getRandomInt.js +6 -0
  17. package/cypress/fixtures/sampleWebcolors.js +18 -0
  18. package/cypress/fixtures/testSample.js +8 -0
  19. package/cypress/plugins/esbuild-istanbul.ts +50 -0
  20. package/cypress/plugins/tsCompile.ts +34 -0
  21. package/cypress/support/commands.ts +0 -0
  22. package/cypress/support/e2e.ts +21 -0
  23. package/cypress/test.html +23 -0
  24. package/cypress.config.ts +29 -0
  25. package/dist/css/color-picker.css +15 -39
  26. package/dist/css/color-picker.min.css +2 -2
  27. package/dist/css/color-picker.rtl.css +15 -39
  28. package/dist/css/color-picker.rtl.min.css +2 -2
  29. package/dist/js/color-picker.cjs +8 -0
  30. package/dist/js/color-picker.cjs.map +1 -0
  31. package/dist/js/color-picker.d.ts +278 -0
  32. package/dist/js/color-picker.js +5 -3583
  33. package/dist/js/color-picker.js.map +1 -0
  34. package/dist/js/color-picker.mjs +2631 -0
  35. package/dist/js/color-picker.mjs.map +1 -0
  36. package/dts.config.ts +15 -0
  37. package/package.json +64 -74
  38. package/src/scss/_variables.scss +0 -1
  39. package/src/scss/color-picker.rtl.scss +4 -0
  40. package/src/scss/color-picker.scss +75 -39
  41. package/src/ts/colorPalette.ts +89 -0
  42. package/src/{js/color-picker.js → ts/index.ts} +492 -502
  43. package/src/ts/interface/colorPickerLabels.ts +20 -0
  44. package/src/ts/interface/colorPickerOptions.ts +11 -0
  45. package/src/ts/interface/paletteOptions.ts +6 -0
  46. package/src/ts/util/colorNames.ts +21 -0
  47. package/src/{js/util/colorPickerLabels.js → ts/util/colorPickerLabels.ts} +4 -2
  48. package/src/ts/util/getColorControls.ts +90 -0
  49. package/src/{js/util/getColorForm.js → ts/util/getColorForm.ts} +28 -18
  50. package/src/{js/util/getColorMenu.js → ts/util/getColorMenu.ts} +21 -30
  51. package/src/ts/util/isValidJSON.ts +19 -0
  52. package/src/{js/util/setMarkup.js → ts/util/setMarkup.ts} +57 -48
  53. package/src/{js/util/vHidden.js → ts/util/vHidden.ts} +0 -0
  54. package/tsconfig.json +29 -0
  55. package/vite.config.ts +34 -0
  56. package/dist/js/color-esm.js +0 -1167
  57. package/dist/js/color-esm.min.js +0 -2
  58. package/dist/js/color-palette-esm.js +0 -1238
  59. package/dist/js/color-palette-esm.min.js +0 -2
  60. package/dist/js/color-palette.js +0 -1246
  61. package/dist/js/color-palette.min.js +0 -2
  62. package/dist/js/color-picker-element-esm.js +0 -3739
  63. package/dist/js/color-picker-element-esm.min.js +0 -2
  64. package/dist/js/color-picker-element.js +0 -3747
  65. package/dist/js/color-picker-element.min.js +0 -2
  66. package/dist/js/color-picker-esm.js +0 -3578
  67. package/dist/js/color-picker-esm.min.js +0 -2
  68. package/dist/js/color-picker.min.js +0 -2
  69. package/dist/js/color.js +0 -1175
  70. package/dist/js/color.min.js +0 -2
  71. package/src/js/color-palette.js +0 -75
  72. package/src/js/color-picker-element.js +0 -110
  73. package/src/js/color.js +0 -1107
  74. package/src/js/index.js +0 -3
  75. package/src/js/util/colorNames.js +0 -6
  76. package/src/js/util/getColorControls.js +0 -103
  77. package/src/js/util/isValidJSON.js +0 -13
  78. package/src/js/util/nonColors.js +0 -5
  79. package/src/js/util/roundPart.js +0 -9
  80. package/src/js/util/setCSSProperties.js +0 -12
  81. package/src/js/util/tabindex.js +0 -3
  82. package/src/js/util/toggleCEAttr.js +0 -70
  83. package/src/js/util/version.js +0 -6
  84. package/src/js/version.js +0 -6
  85. package/types/cp.d.ts +0 -544
  86. package/types/index.d.ts +0 -48
  87. package/types/source/source.ts +0 -5
  88. package/types/source/types.d.ts +0 -92
@@ -1,3739 +0,0 @@
1
- /*!
2
- * ColorPickerElement v1.0.0 (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
- * Returns the `document` or the `#document` element.
8
- * @see https://github.com/floating-ui/floating-ui
9
- * @param {(Node | HTMLElement | Element | globalThis)=} node
10
- * @returns {Document}
11
- */
12
- function getDocument(node) {
13
- if (node instanceof HTMLElement) return node.ownerDocument;
14
- if (node instanceof Window) return node.document;
15
- return window.document;
16
- }
17
-
18
- /**
19
- * Shortcut for `Object.assign()` static method.
20
- * @param {Record<string, any>} obj a target object
21
- * @param {Record<string, any>} source a source object
22
- */
23
- const ObjectAssign = (obj, source) => Object.assign(obj, source);
24
-
25
- /**
26
- * This is a shortie for `document.createElement` method
27
- * which allows you to create a new `HTMLElement` for a given `tagName`
28
- * or based on an object with specific non-readonly attributes:
29
- * `id`, `className`, `textContent`, `style`, etc.
30
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
31
- *
32
- * @param {Record<string, string> | string} param `tagName` or object
33
- * @return {HTMLElement | Element} a new `HTMLElement` or `Element`
34
- */
35
- function createElement(param) {
36
- if (typeof param === 'string') {
37
- return getDocument().createElement(param);
38
- }
39
-
40
- const { tagName } = param;
41
- const attr = { ...param };
42
- const newElement = createElement(tagName);
43
- delete attr.tagName;
44
- ObjectAssign(newElement, attr);
45
- return newElement;
46
- }
47
-
48
- /**
49
- * Shortcut for `HTMLElement.setAttribute()` method.
50
- * @param {HTMLElement | Element} element target element
51
- * @param {string} attribute attribute name
52
- * @param {string} value attribute value
53
- * @returns {void}
54
- */
55
- const setAttribute = (element, attribute, value) => element.setAttribute(attribute, value);
56
-
57
- /**
58
- * Shortcut for `HTMLElement.getAttribute()` method.
59
- * @param {HTMLElement | Element} element target element
60
- * @param {string} attribute attribute name
61
- * @returns {string?} attribute value
62
- */
63
- const getAttribute = (element, attribute) => element.getAttribute(attribute);
64
-
65
- /**
66
- * A global namespace for `document.head`.
67
- */
68
- const { head: documentHead } = document;
69
-
70
- /**
71
- * Shortcut for `window.getComputedStyle(element).propertyName`
72
- * static method.
73
- *
74
- * * If `element` parameter is not an `HTMLElement`, `getComputedStyle`
75
- * throws a `ReferenceError`.
76
- *
77
- * @param {HTMLElement | Element} element target
78
- * @param {string} property the css property
79
- * @return {string} the css property value
80
- */
81
- function getElementStyle(element, property) {
82
- const computedStyle = getComputedStyle(element);
83
-
84
- // @ts-ignore -- must use camelcase strings,
85
- // or non-camelcase strings with `getPropertyValue`
86
- return property in computedStyle ? computedStyle[property] : '';
87
- }
88
-
89
- /**
90
- * Shortcut for multiple uses of `HTMLElement.style.propertyName` method.
91
- * @param {HTMLElement | Element} element target element
92
- * @param {Partial<CSSStyleDeclaration>} styles attribute value
93
- */
94
- // @ts-ignore
95
- const setElementStyle = (element, styles) => { ObjectAssign(element.style, styles); };
96
-
97
- /**
98
- * Shortcut for `String.toLowerCase()`.
99
- *
100
- * @param {string} source input string
101
- * @returns {string} lowercase output string
102
- */
103
- const toLowerCase = (source) => source.toLowerCase();
104
-
105
- /**
106
- * A list of explicit default non-color values.
107
- */
108
- const nonColors = ['transparent', 'currentColor', 'inherit', 'revert', 'initial'];
109
-
110
- /**
111
- * Round colour components, for all formats except HEX.
112
- * @param {number} v one of the colour components
113
- * @returns {number} the rounded number
114
- */
115
- function roundPart(v) {
116
- const floor = Math.floor(v);
117
- return v - floor < 0.5 ? floor : Math.round(v);
118
- }
119
-
120
- // Color supported formats
121
- const COLOR_FORMAT = ['rgb', 'hex', 'hsl', 'hsv', 'hwb'];
122
-
123
- // Hue angles
124
- const ANGLES = 'deg|rad|grad|turn';
125
-
126
- // <http://www.w3.org/TR/css3-values/#integers>
127
- const CSS_INTEGER = '[-\\+]?\\d+%?';
128
-
129
- // Include CSS3 Module
130
- // <http://www.w3.org/TR/css3-values/#number-value>
131
- const CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?';
132
-
133
- // Include CSS4 Module Hue degrees unit
134
- // <https://www.w3.org/TR/css3-values/#angle-value>
135
- const CSS_ANGLE = `[-\\+]?\\d*\\.?\\d+(?:${ANGLES})?`;
136
-
137
- // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
138
- const CSS_UNIT = `(?:${CSS_NUMBER})|(?:${CSS_INTEGER})`;
139
-
140
- // Add angles to the mix
141
- const CSS_UNIT2 = `(?:${CSS_UNIT})|(?:${CSS_ANGLE})`;
142
-
143
- // Start & end
144
- const START_MATCH = '(?:[\\s|\\(\\s|\\s\\(\\s]+)?';
145
- const END_MATCH = '(?:[\\s|\\)\\s]+)?';
146
- // Components separation
147
- const SEP = '(?:[,|\\s]+)';
148
- const SEP2 = '(?:[,|\\/\\s]*)?';
149
-
150
- // Actual matching.
151
- // Parentheses and commas are optional, but not required.
152
- // Whitespace can take the place of commas or opening paren
153
- const PERMISSIVE_MATCH = `${START_MATCH}(${CSS_UNIT2})${SEP}(${CSS_UNIT})${SEP}(${CSS_UNIT})${SEP2}(${CSS_UNIT})?${END_MATCH}`;
154
-
155
- const matchers = {
156
- CSS_UNIT: new RegExp(CSS_UNIT2),
157
- hwb: new RegExp(`hwb${PERMISSIVE_MATCH}`),
158
- rgb: new RegExp(`rgb(?:a)?${PERMISSIVE_MATCH}`),
159
- hsl: new RegExp(`hsl(?:a)?${PERMISSIVE_MATCH}`),
160
- hsv: new RegExp(`hsv(?:a)?${PERMISSIVE_MATCH}`),
161
- hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
162
- hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
163
- hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
164
- hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
165
- };
166
-
167
- /**
168
- * Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
169
- * <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
170
- * @param {string} n testing number
171
- * @returns {boolean} the query result
172
- */
173
- function isOnePointZero(n) {
174
- return `${n}`.includes('.') && parseFloat(n) === 1;
175
- }
176
-
177
- /**
178
- * Check to see if string passed in is a percentage
179
- * @param {string} n testing number
180
- * @returns {boolean} the query result
181
- */
182
- function isPercentage(n) {
183
- return `${n}`.includes('%');
184
- }
185
-
186
- /**
187
- * Check to see if string passed is a web safe colour.
188
- * @see https://stackoverflow.com/a/16994164
189
- * @param {string} color a colour name, EG: *red*
190
- * @returns {boolean} the query result
191
- */
192
- function isColorName(color) {
193
- if (nonColors.includes(color)
194
- || ['#', ...COLOR_FORMAT].some((f) => color.includes(f))) return false;
195
-
196
- if (['black', 'white'].includes(color)) return true;
197
-
198
- return ['rgb(255, 255, 255)', 'rgb(0, 0, 0)'].every((c) => {
199
- setElementStyle(documentHead, { color });
200
- const computedColor = getElementStyle(documentHead, 'color');
201
- setElementStyle(documentHead, { color: '' });
202
- return computedColor !== c;
203
- });
204
- }
205
-
206
- /**
207
- * Check to see if it looks like a CSS unit
208
- * (see `matchers` above for definition).
209
- * @param {string | number} color testing value
210
- * @returns {boolean} the query result
211
- */
212
- function isValidCSSUnit(color) {
213
- return Boolean(matchers.CSS_UNIT.exec(String(color)));
214
- }
215
-
216
- /**
217
- * Take input from [0, n] and return it as [0, 1]
218
- * @param {*} N the input number
219
- * @param {number} max the number maximum value
220
- * @returns {number} the number in [0, 1] value range
221
- */
222
- function bound01(N, max) {
223
- let n = N;
224
-
225
- if (typeof N === 'number'
226
- && Math.min(N, 0) === 0 // round values to 6 decimals Math.round(N * (10 ** 6)) / 10 ** 6
227
- && Math.max(N, 1) === 1) return N;
228
-
229
- if (isOnePointZero(N)) n = '100%';
230
-
231
- const processPercent = isPercentage(n);
232
- n = max === 360
233
- ? parseFloat(n)
234
- : Math.min(max, Math.max(0, parseFloat(n)));
235
-
236
- // Automatically convert percentage into number
237
- if (processPercent) n = (n * max) / 100;
238
-
239
- // Handle floating point rounding errors
240
- if (Math.abs(n - max) < 0.000001) {
241
- return 1;
242
- }
243
- // Convert into [0, 1] range if it isn't already
244
- if (max === 360) {
245
- // If n is a hue given in degrees,
246
- // wrap around out-of-range values into [0, 360] range
247
- // then convert into [0, 1].
248
- n = (n < 0 ? (n % max) + max : n % max) / max;
249
- } else {
250
- // If n not a hue given in degrees
251
- // Convert into [0, 1] range if it isn't already.
252
- n = (n % max) / max;
253
- }
254
- return n;
255
- }
256
-
257
- /**
258
- * Return a valid alpha value [0,1] with all invalid values being set to 1.
259
- * @param {string | number} a transparency value
260
- * @returns {number} a transparency value in the [0, 1] range
261
- */
262
- function boundAlpha(a) {
263
- let na = parseFloat(`${a}`);
264
-
265
- if (Number.isNaN(na) || na < 0 || na > 1) {
266
- na = 1;
267
- }
268
-
269
- return na;
270
- }
271
-
272
- /**
273
- * Force a number between 0 and 1.
274
- * @param {number} v the float number
275
- * @returns {number} - the resulting number
276
- */
277
- function clamp01(v) {
278
- return Math.min(1, Math.max(0, v));
279
- }
280
-
281
- /**
282
- * Returns the hexadecimal value of a web safe colour.
283
- * @param {string} name
284
- * @returns {string}
285
- */
286
- function getRGBFromName(name) {
287
- setElementStyle(documentHead, { color: name });
288
- const colorName = getElementStyle(documentHead, 'color');
289
- setElementStyle(documentHead, { color: '' });
290
- return colorName;
291
- }
292
-
293
- /**
294
- * Converts a decimal value to hexadecimal.
295
- * @param {number} d the input number
296
- * @returns {string} - the hexadecimal value
297
- */
298
- function convertDecimalToHex(d) {
299
- return roundPart(d * 255).toString(16);
300
- }
301
-
302
- /**
303
- * Converts a hexadecimal value to decimal.
304
- * @param {string} h hexadecimal value
305
- * @returns {number} number in decimal format
306
- */
307
- function convertHexToDecimal(h) {
308
- return parseIntFromHex(h) / 255;
309
- }
310
-
311
- /**
312
- * Converts a base-16 hexadecimal value into a base-10 integer.
313
- * @param {string} val
314
- * @returns {number}
315
- */
316
- function parseIntFromHex(val) {
317
- return parseInt(val, 16);
318
- }
319
-
320
- /**
321
- * Force a hexadecimal value to have 2 characters.
322
- * @param {string} c string with [0-9A-F] ranged values
323
- * @returns {string} 0 => 00, a => 0a
324
- */
325
- function pad2(c) {
326
- return c.length === 1 ? `0${c}` : String(c);
327
- }
328
-
329
- /**
330
- * Converts an RGB colour value to HSL.
331
- *
332
- * @param {number} r Red component [0, 1]
333
- * @param {number} g Green component [0, 1]
334
- * @param {number} b Blue component [0, 1]
335
- * @returns {CP.HSL} {h,s,l} object with [0, 1] ranged values
336
- */
337
- function rgbToHsl(r, g, b) {
338
- const max = Math.max(r, g, b);
339
- const min = Math.min(r, g, b);
340
- let h = 0;
341
- let s = 0;
342
- const l = (max + min) / 2;
343
- if (max === min) {
344
- s = 0;
345
- h = 0; // achromatic
346
- } else {
347
- const d = max - min;
348
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
349
- if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
350
- if (max === g) h = (b - r) / d + 2;
351
- if (max === b) h = (r - g) / d + 4;
352
-
353
- h /= 6;
354
- }
355
- return { h, s, l };
356
- }
357
-
358
- /**
359
- * Returns a normalized RGB component value.
360
- * @param {number} p
361
- * @param {number} q
362
- * @param {number} t
363
- * @returns {number}
364
- */
365
- function hueToRgb(p, q, t) {
366
- let T = t;
367
- if (T < 0) T += 1;
368
- if (T > 1) T -= 1;
369
- if (T < 1 / 6) return p + (q - p) * (6 * T);
370
- if (T < 1 / 2) return q;
371
- if (T < 2 / 3) return p + (q - p) * (2 / 3 - T) * 6;
372
- return p;
373
- }
374
-
375
- /**
376
- * Converts an HSL colour value to RGB.
377
- *
378
- * @param {number} h Hue Angle [0, 1]
379
- * @param {number} s Saturation [0, 1]
380
- * @param {number} l Lightness Angle [0, 1]
381
- * @returns {CP.RGB} {r,g,b} object with [0, 1] ranged values
382
- */
383
- function hslToRgb(h, s, l) {
384
- let r = 0;
385
- let g = 0;
386
- let b = 0;
387
-
388
- if (s === 0) {
389
- // achromatic
390
- g = l;
391
- b = l;
392
- r = l;
393
- } else {
394
- const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
395
- const p = 2 * l - q;
396
- r = hueToRgb(p, q, h + 1 / 3);
397
- g = hueToRgb(p, q, h);
398
- b = hueToRgb(p, q, h - 1 / 3);
399
- }
400
-
401
- return { r, g, b };
402
- }
403
-
404
- /**
405
- * Returns an HWB colour object from an RGB colour object.
406
- * @link https://www.w3.org/TR/css-color-4/#hwb-to-rgb
407
- * @link http://alvyray.com/Papers/CG/hwb2rgb.htm
408
- *
409
- * @param {number} r Red component [0, 1]
410
- * @param {number} g Green [0, 1]
411
- * @param {number} b Blue [0, 1]
412
- * @return {CP.HWB} {h,w,b} object with [0, 1] ranged values
413
- */
414
- function rgbToHwb(r, g, b) {
415
- let f = 0;
416
- let i = 0;
417
- const whiteness = Math.min(r, g, b);
418
- const max = Math.max(r, g, b);
419
- const black = 1 - max;
420
-
421
- if (max === whiteness) return { h: 0, w: whiteness, b: black };
422
- if (r === whiteness) {
423
- f = g - b;
424
- i = 3;
425
- } else {
426
- f = g === whiteness ? b - r : r - g;
427
- i = g === whiteness ? 5 : 1;
428
- }
429
-
430
- const h = (i - f / (max - whiteness)) / 6;
431
- return {
432
- h: h === 1 ? 0 : h,
433
- w: whiteness,
434
- b: black,
435
- };
436
- }
437
-
438
- /**
439
- * Returns an RGB colour object from an HWB colour.
440
- *
441
- * @param {number} H Hue Angle [0, 1]
442
- * @param {number} W Whiteness [0, 1]
443
- * @param {number} B Blackness [0, 1]
444
- * @return {CP.RGB} {r,g,b} object with [0, 1] ranged values
445
- *
446
- * @link https://www.w3.org/TR/css-color-4/#hwb-to-rgb
447
- * @link http://alvyray.com/Papers/CG/hwb2rgb.htm
448
- */
449
- function hwbToRgb(H, W, B) {
450
- if (W + B >= 1) {
451
- const gray = W / (W + B);
452
- return { r: gray, g: gray, b: gray };
453
- }
454
- let { r, g, b } = hslToRgb(H, 1, 0.5);
455
- [r, g, b] = [r, g, b].map((v) => v * (1 - W - B) + W);
456
-
457
- return { r, g, b };
458
- }
459
-
460
- /**
461
- * Converts an RGB colour value to HSV.
462
- *
463
- * @param {number} r Red component [0, 1]
464
- * @param {number} g Green [0, 1]
465
- * @param {number} b Blue [0, 1]
466
- * @returns {CP.HSV} {h,s,v} object with [0, 1] ranged values
467
- */
468
- function rgbToHsv(r, g, b) {
469
- const max = Math.max(r, g, b);
470
- const min = Math.min(r, g, b);
471
- let h = 0;
472
- const v = max;
473
- const d = max - min;
474
- const s = max === 0 ? 0 : d / max;
475
- if (max === min) {
476
- h = 0; // achromatic
477
- } else {
478
- if (r === max) h = (g - b) / d + (g < b ? 6 : 0);
479
- if (g === max) h = (b - r) / d + 2;
480
- if (b === max) h = (r - g) / d + 4;
481
-
482
- h /= 6;
483
- }
484
- return { h, s, v };
485
- }
486
-
487
- /**
488
- * Converts an HSV colour value to RGB.
489
- *
490
- * @param {number} H Hue Angle [0, 1]
491
- * @param {number} S Saturation [0, 1]
492
- * @param {number} V Brightness Angle [0, 1]
493
- * @returns {CP.RGB} {r,g,b} object with [0, 1] ranged values
494
- */
495
- function hsvToRgb(H, S, V) {
496
- const h = H * 6;
497
- const s = S;
498
- const v = V;
499
- const i = Math.floor(h);
500
- const f = h - i;
501
- const p = v * (1 - s);
502
- const q = v * (1 - f * s);
503
- const t = v * (1 - (1 - f) * s);
504
- const mod = i % 6;
505
- const r = [v, q, p, p, t, v][mod];
506
- const g = [t, v, v, q, p, p][mod];
507
- const b = [p, p, t, v, v, q][mod];
508
- return { r, g, b };
509
- }
510
-
511
- /**
512
- * Converts an RGB colour to hex
513
- *
514
- * Assumes r, g, and b are contained in the set [0, 255]
515
- * Returns a 3 or 6 character hex
516
- * @param {number} r Red component [0, 255]
517
- * @param {number} g Green [0, 255]
518
- * @param {number} b Blue [0, 255]
519
- * @param {boolean=} allow3Char
520
- * @returns {string}
521
- */
522
- function rgbToHex(r, g, b, allow3Char) {
523
- const hex = [
524
- pad2(roundPart(r).toString(16)),
525
- pad2(roundPart(g).toString(16)),
526
- pad2(roundPart(b).toString(16)),
527
- ];
528
-
529
- // Return a 3 character hex if possible
530
- if (allow3Char && hex[0].charAt(0) === hex[0].charAt(1)
531
- && hex[1].charAt(0) === hex[1].charAt(1)
532
- && hex[2].charAt(0) === hex[2].charAt(1)) {
533
- return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
534
- }
535
-
536
- return hex.join('');
537
- }
538
-
539
- /**
540
- * Converts an RGBA color plus alpha transparency to hex8.
541
- *
542
- * @param {number} r Red component [0, 255]
543
- * @param {number} g Green [0, 255]
544
- * @param {number} b Blue [0, 255]
545
- * @param {number} a Alpha transparency [0, 1]
546
- * @param {boolean=} allow4Char when *true* it will also find hex shorthand
547
- * @returns {string} a hexadecimal value with alpha transparency
548
- */
549
- function rgbaToHex(r, g, b, a, allow4Char) {
550
- const hex = [
551
- pad2(roundPart(r).toString(16)),
552
- pad2(roundPart(g).toString(16)),
553
- pad2(roundPart(b).toString(16)),
554
- pad2(convertDecimalToHex(a)),
555
- ];
556
-
557
- // Return a 4 character hex if possible
558
- if (allow4Char && hex[0].charAt(0) === hex[0].charAt(1)
559
- && hex[1].charAt(0) === hex[1].charAt(1)
560
- && hex[2].charAt(0) === hex[2].charAt(1)
561
- && hex[3].charAt(0) === hex[3].charAt(1)) {
562
- return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
563
- }
564
- return hex.join('');
565
- }
566
-
567
- /**
568
- * Permissive string parsing. Take in a number of formats, and output an object
569
- * based on detected format. Returns {r,g,b} or {h,s,l} or {h,s,v}
570
- * @param {string} input colour value in any format
571
- * @returns {Record<string, (number | string | boolean)> | false} an object matching the RegExp
572
- */
573
- function stringInputToObject(input) {
574
- let color = toLowerCase(input.trim());
575
-
576
- if (color.length === 0) {
577
- return {
578
- r: 0, g: 0, b: 0, a: 1,
579
- };
580
- }
581
-
582
- if (isColorName(color)) {
583
- color = getRGBFromName(color);
584
- } else if (nonColors.includes(color)) {
585
- const a = color === 'transparent' ? 0 : 1;
586
- return {
587
- r: 0, g: 0, b: 0, a, format: 'rgb', ok: true,
588
- };
589
- }
590
-
591
- // Try to match string input using regular expressions.
592
- // Keep most of the number bounding out of this function,
593
- // don't worry about [0,1] or [0,100] or [0,360]
594
- // Just return an object and let the conversion functions handle that.
595
- // This way the result will be the same whether Color is initialized with string or object.
596
- let [, m1, m2, m3, m4] = matchers.rgb.exec(color) || [];
597
- if (m1 && m2 && m3/* && m4 */) {
598
- return {
599
- r: m1, g: m2, b: m3, a: m4 !== undefined ? m4 : 1, format: 'rgb',
600
- };
601
- }
602
-
603
- [, m1, m2, m3, m4] = matchers.hsl.exec(color) || [];
604
- if (m1 && m2 && m3/* && m4 */) {
605
- return {
606
- h: m1, s: m2, l: m3, a: m4 !== undefined ? m4 : 1, format: 'hsl',
607
- };
608
- }
609
-
610
- [, m1, m2, m3, m4] = matchers.hsv.exec(color) || [];
611
- if (m1 && m2 && m3/* && m4 */) {
612
- return {
613
- h: m1, s: m2, v: m3, a: m4 !== undefined ? m4 : 1, format: 'hsv',
614
- };
615
- }
616
-
617
- [, m1, m2, m3, m4] = matchers.hwb.exec(color) || [];
618
- if (m1 && m2 && m3) {
619
- return {
620
- h: m1, w: m2, b: m3, a: m4 !== undefined ? m4 : 1, format: 'hwb',
621
- };
622
- }
623
-
624
- [, m1, m2, m3, m4] = matchers.hex8.exec(color) || [];
625
- if (m1 && m2 && m3 && m4) {
626
- return {
627
- r: parseIntFromHex(m1),
628
- g: parseIntFromHex(m2),
629
- b: parseIntFromHex(m3),
630
- a: convertHexToDecimal(m4),
631
- format: 'hex',
632
- };
633
- }
634
-
635
- [, m1, m2, m3] = matchers.hex6.exec(color) || [];
636
- if (m1 && m2 && m3) {
637
- return {
638
- r: parseIntFromHex(m1),
639
- g: parseIntFromHex(m2),
640
- b: parseIntFromHex(m3),
641
- format: 'hex',
642
- };
643
- }
644
-
645
- [, m1, m2, m3, m4] = matchers.hex4.exec(color) || [];
646
- if (m1 && m2 && m3 && m4) {
647
- return {
648
- r: parseIntFromHex(m1 + m1),
649
- g: parseIntFromHex(m2 + m2),
650
- b: parseIntFromHex(m3 + m3),
651
- a: convertHexToDecimal(m4 + m4),
652
- format: 'hex',
653
- };
654
- }
655
-
656
- [, m1, m2, m3] = matchers.hex3.exec(color) || [];
657
- if (m1 && m2 && m3) {
658
- return {
659
- r: parseIntFromHex(m1 + m1),
660
- g: parseIntFromHex(m2 + m2),
661
- b: parseIntFromHex(m3 + m3),
662
- format: 'hex',
663
- };
664
- }
665
-
666
- return false;
667
- }
668
-
669
- /**
670
- * Given a string or object, convert that input to RGB
671
- *
672
- * Possible string inputs:
673
- * ```
674
- * "red"
675
- * "#f00" or "f00"
676
- * "#ff0000" or "ff0000"
677
- * "#ff000000" or "ff000000" // CSS4 Module
678
- * "rgb 255 0 0" or "rgb (255, 0, 0)"
679
- * "rgb 1.0 0 0" or "rgb (1, 0, 0)"
680
- * "rgba(255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
681
- * "rgba(1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
682
- * "rgb(255 0 0 / 10%)" or "rgb 255 0 0 0.1" // CSS4 Module
683
- * "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
684
- * "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
685
- * "hsl(0deg 100% 50% / 50%)" or "hsl 0 100 50 50" // CSS4 Module
686
- * "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
687
- * "hsva(0, 100%, 100%, 0.1)" or "hsva 0 100% 100% 0.1"
688
- * "hsv(0deg 100% 100% / 10%)" or "hsv 0 100 100 0.1" // CSS4 Module
689
- * "hwb(0deg, 100%, 100%, 100%)" or "hwb 0 100% 100% 0.1" // CSS4 Module
690
- * ```
691
- * @param {string | Record<string, any>} input
692
- * @returns {CP.ColorObject}
693
- */
694
- function inputToRGB(input) {
695
- let rgb = { r: 0, g: 0, b: 0 };
696
- /** @type {*} */
697
- let color = input;
698
- /** @type {string | number} */
699
- let a = 1;
700
- let s = null;
701
- let v = null;
702
- let l = null;
703
- let w = null;
704
- let b = null;
705
- let h = null;
706
- let r = null;
707
- let g = null;
708
- let ok = false;
709
- const inputFormat = typeof color === 'object' && color.format;
710
- let format = inputFormat && COLOR_FORMAT.includes(inputFormat) ? inputFormat : 'rgb';
711
-
712
- if (typeof input === 'string') {
713
- color = stringInputToObject(input);
714
- if (color) ok = true;
715
- }
716
- if (typeof color === 'object') {
717
- if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
718
- ({ r, g, b } = color);
719
- // RGB values now are all in [0, 1] range
720
- [r, g, b] = [r, g, b].map((n) => bound01(n, isPercentage(n) ? 100 : 255));
721
- rgb = { r, g, b };
722
- ok = true;
723
- format = color.format || 'rgb';
724
- }
725
- if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
726
- ({ h, s, v } = color);
727
- h = bound01(h, 360); // hue can be `5deg` or a [0, 1] value
728
- s = bound01(s, 100); // saturation can be `5%` or a [0, 1] value
729
- v = bound01(v, 100); // brightness can be `5%` or a [0, 1] value
730
- rgb = hsvToRgb(h, s, v);
731
- ok = true;
732
- format = 'hsv';
733
- }
734
- if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
735
- ({ h, s, l } = color);
736
- h = bound01(h, 360); // hue can be `5deg` or a [0, 1] value
737
- s = bound01(s, 100); // saturation can be `5%` or a [0, 1] value
738
- l = bound01(l, 100); // lightness can be `5%` or a [0, 1] value
739
- rgb = hslToRgb(h, s, l);
740
- ok = true;
741
- format = 'hsl';
742
- }
743
- if (isValidCSSUnit(color.h) && isValidCSSUnit(color.w) && isValidCSSUnit(color.b)) {
744
- ({ h, w, b } = color);
745
- h = bound01(h, 360); // hue can be `5deg` or a [0, 1] value
746
- w = bound01(w, 100); // whiteness can be `5%` or a [0, 1] value
747
- b = bound01(b, 100); // blackness can be `5%` or a [0, 1] value
748
- rgb = hwbToRgb(h, w, b);
749
- ok = true;
750
- format = 'hwb';
751
- }
752
- if (isValidCSSUnit(color.a)) {
753
- a = color.a; // @ts-ignore -- `parseFloat` works with numbers too
754
- a = isPercentage(`${a}`) || parseFloat(a) > 1 ? bound01(a, 100) : a;
755
- }
756
- }
757
- if (typeof color === 'undefined') {
758
- ok = true;
759
- }
760
-
761
- return {
762
- ok,
763
- format,
764
- // r: Math.min(255, Math.max(rgb.r, 0)),
765
- // g: Math.min(255, Math.max(rgb.g, 0)),
766
- // b: Math.min(255, Math.max(rgb.b, 0)),
767
- r: rgb.r,
768
- g: rgb.g,
769
- b: rgb.b,
770
- a: boundAlpha(a),
771
- };
772
- }
773
-
774
- /**
775
- * @class
776
- * Returns a new `Color` instance.
777
- * @see https://github.com/bgrins/TinyColor
778
- */
779
- class Color {
780
- /**
781
- * @constructor
782
- * @param {CP.ColorInput} input the given colour value
783
- * @param {CP.ColorFormats=} config the given format
784
- */
785
- constructor(input, config) {
786
- let color = input;
787
- const configFormat = config && COLOR_FORMAT.includes(config)
788
- ? config : '';
789
-
790
- // If input is already a `Color`, clone its values
791
- if (color instanceof Color) {
792
- color = inputToRGB(color);
793
- }
794
-
795
- const {
796
- r, g, b, a, ok, format,
797
- } = inputToRGB(color);
798
-
799
- // bind
800
- const self = this;
801
-
802
- /** @type {CP.ColorInput} */
803
- self.originalInput = input;
804
- /** @type {number} */
805
- self.r = r;
806
- /** @type {number} */
807
- self.g = g;
808
- /** @type {number} */
809
- self.b = b;
810
- /** @type {number} */
811
- self.a = a;
812
- /** @type {boolean} */
813
- self.ok = ok;
814
- /** @type {CP.ColorFormats} */
815
- self.format = configFormat || format;
816
- }
817
-
818
- /**
819
- * Checks if the current input value is a valid colour.
820
- * @returns {boolean} the query result
821
- */
822
- get isValid() {
823
- return this.ok;
824
- }
825
-
826
- /**
827
- * Checks if the current colour requires a light text colour.
828
- * @returns {boolean} the query result
829
- */
830
- get isDark() {
831
- return this.brightness < 120;
832
- }
833
-
834
- /**
835
- * Returns the perceived luminance of a colour.
836
- * @see http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
837
- * @returns {number} a number in the [0, 1] range
838
- */
839
- get luminance() {
840
- const { r, g, b } = this;
841
- let R = 0;
842
- let G = 0;
843
- let B = 0;
844
-
845
- if (r <= 0.03928) {
846
- R = r / 12.92;
847
- } else {
848
- R = ((r + 0.055) / 1.055) ** 2.4;
849
- }
850
- if (g <= 0.03928) {
851
- G = g / 12.92;
852
- } else {
853
- G = ((g + 0.055) / 1.055) ** 2.4;
854
- }
855
- if (b <= 0.03928) {
856
- B = b / 12.92;
857
- } else {
858
- B = ((b + 0.055) / 1.055) ** 2.4;
859
- }
860
- return 0.2126 * R + 0.7152 * G + 0.0722 * B;
861
- }
862
-
863
- /**
864
- * Returns the perceived brightness of the colour.
865
- * @returns {number} a number in the [0, 255] range
866
- */
867
- get brightness() {
868
- const { r, g, b } = this.toRgb();
869
- return (r * 299 + g * 587 + b * 114) / 1000;
870
- }
871
-
872
- /**
873
- * Returns the colour as an RGBA object.
874
- * @returns {CP.RGBA} an {r,g,b,a} object with [0, 255] ranged values
875
- */
876
- toRgb() {
877
- let {
878
- r, g, b, a,
879
- } = this;
880
-
881
- [r, g, b] = [r, g, b].map((n) => roundPart(n * 255 * 100) / 100);
882
- a = roundPart(a * 100) / 100;
883
- return {
884
- r, g, b, a,
885
- };
886
- }
887
-
888
- /**
889
- * Returns the RGBA values concatenated into a CSS3 Module string format.
890
- * * rgb(255,255,255)
891
- * * rgba(255,255,255,0.5)
892
- * @returns {string} the CSS valid colour in RGB/RGBA format
893
- */
894
- toRgbString() {
895
- const {
896
- r, g, b, a,
897
- } = this.toRgb();
898
- const [R, G, B] = [r, g, b].map(roundPart);
899
-
900
- return a === 1
901
- ? `rgb(${R}, ${G}, ${B})`
902
- : `rgba(${R}, ${G}, ${B}, ${a})`;
903
- }
904
-
905
- /**
906
- * Returns the RGBA values concatenated into a CSS4 Module string format.
907
- * * rgb(255 255 255)
908
- * * rgb(255 255 255 / 50%)
909
- * @returns {string} the CSS valid colour in CSS4 RGB format
910
- */
911
- toRgbCSS4String() {
912
- const {
913
- r, g, b, a,
914
- } = this.toRgb();
915
- const [R, G, B] = [r, g, b].map(roundPart);
916
- const A = a === 1 ? '' : ` / ${roundPart(a * 100)}%`;
917
-
918
- return `rgb(${R} ${G} ${B}${A})`;
919
- }
920
-
921
- /**
922
- * Returns the hexadecimal value of the colour. When the parameter is *true*
923
- * it will find a 3 characters shorthand of the decimal value.
924
- *
925
- * @param {boolean=} allow3Char when `true` returns shorthand HEX
926
- * @returns {string} the hexadecimal colour format
927
- */
928
- toHex(allow3Char) {
929
- const {
930
- r, g, b, a,
931
- } = this.toRgb();
932
-
933
- return a === 1
934
- ? rgbToHex(r, g, b, allow3Char)
935
- : rgbaToHex(r, g, b, a, allow3Char);
936
- }
937
-
938
- /**
939
- * Returns the CSS valid hexadecimal vaue of the colour. When the parameter is *true*
940
- * it will find a 3 characters shorthand of the value.
941
- *
942
- * @param {boolean=} allow3Char when `true` returns shorthand HEX
943
- * @returns {string} the CSS valid colour in hexadecimal format
944
- */
945
- toHexString(allow3Char) {
946
- return `#${this.toHex(allow3Char)}`;
947
- }
948
-
949
- /**
950
- * Returns the HEX8 value of the colour.
951
- * @param {boolean=} allow4Char when `true` returns shorthand HEX
952
- * @returns {string} the CSS valid colour in hexadecimal format
953
- */
954
- toHex8(allow4Char) {
955
- const {
956
- r, g, b, a,
957
- } = this.toRgb();
958
-
959
- return rgbaToHex(r, g, b, a, allow4Char);
960
- }
961
-
962
- /**
963
- * Returns the HEX8 value of the colour.
964
- * @param {boolean=} allow4Char when `true` returns shorthand HEX
965
- * @returns {string} the CSS valid colour in hexadecimal format
966
- */
967
- toHex8String(allow4Char) {
968
- return `#${this.toHex8(allow4Char)}`;
969
- }
970
-
971
- /**
972
- * Returns the colour as a HSVA object.
973
- * @returns {CP.HSVA} the `{h,s,v,a}` object with [0, 1] ranged values
974
- */
975
- toHsv() {
976
- const {
977
- r, g, b, a,
978
- } = this;
979
- const { h, s, v } = rgbToHsv(r, g, b);
980
-
981
- return {
982
- h, s, v, a,
983
- };
984
- }
985
-
986
- /**
987
- * Returns the colour as an HSLA object.
988
- * @returns {CP.HSLA} the `{h,s,l,a}` object with [0, 1] ranged values
989
- */
990
- toHsl() {
991
- const {
992
- r, g, b, a,
993
- } = this;
994
- const { h, s, l } = rgbToHsl(r, g, b);
995
-
996
- return {
997
- h, s, l, a,
998
- };
999
- }
1000
-
1001
- /**
1002
- * Returns the HSLA values concatenated into a CSS3 Module format string.
1003
- * * `hsl(150, 100%, 50%)`
1004
- * * `hsla(150, 100%, 50%, 0.5)`
1005
- * @returns {string} the CSS valid colour in HSL/HSLA format
1006
- */
1007
- toHslString() {
1008
- let {
1009
- h, s, l, a,
1010
- } = this.toHsl();
1011
- h = roundPart(h * 360);
1012
- s = roundPart(s * 100);
1013
- l = roundPart(l * 100);
1014
- a = roundPart(a * 100) / 100;
1015
-
1016
- return a === 1
1017
- ? `hsl(${h}, ${s}%, ${l}%)`
1018
- : `hsla(${h}, ${s}%, ${l}%, ${a})`;
1019
- }
1020
-
1021
- /**
1022
- * Returns the HSLA values concatenated into a CSS4 Module format string.
1023
- * * `hsl(150deg 100% 50%)`
1024
- * * `hsl(150deg 100% 50% / 50%)`
1025
- * @returns {string} the CSS valid colour in CSS4 HSL format
1026
- */
1027
- toHslCSS4String() {
1028
- let {
1029
- h, s, l, a,
1030
- } = this.toHsl();
1031
- h = roundPart(h * 360);
1032
- s = roundPart(s * 100);
1033
- l = roundPart(l * 100);
1034
- a = roundPart(a * 100);
1035
- const A = a < 100 ? ` / ${roundPart(a)}%` : '';
1036
-
1037
- return `hsl(${h}deg ${s}% ${l}%${A})`;
1038
- }
1039
-
1040
- /**
1041
- * Returns the colour as an HWBA object.
1042
- * @returns {CP.HWBA} the `{h,w,b,a}` object with [0, 1] ranged values
1043
- */
1044
- toHwb() {
1045
- const {
1046
- r, g, b, a,
1047
- } = this;
1048
- const { h, w, b: bl } = rgbToHwb(r, g, b);
1049
- return {
1050
- h, w, b: bl, a,
1051
- };
1052
- }
1053
-
1054
- /**
1055
- * Returns the HWBA values concatenated into a string.
1056
- * @returns {string} the CSS valid colour in HWB format
1057
- */
1058
- toHwbString() {
1059
- let {
1060
- h, w, b, a,
1061
- } = this.toHwb();
1062
- h = roundPart(h * 360);
1063
- w = roundPart(w * 100);
1064
- b = roundPart(b * 100);
1065
- a = roundPart(a * 100);
1066
- const A = a < 100 ? ` / ${roundPart(a)}%` : '';
1067
-
1068
- return `hwb(${h}deg ${w}% ${b}%${A})`;
1069
- }
1070
-
1071
- /**
1072
- * Sets the alpha value of the current colour.
1073
- * @param {number} alpha a new alpha value in the [0, 1] range.
1074
- * @returns {Color} the `Color` instance
1075
- */
1076
- setAlpha(alpha) {
1077
- const self = this;
1078
- if (typeof alpha !== 'number') return self;
1079
- self.a = boundAlpha(alpha);
1080
- return self;
1081
- }
1082
-
1083
- /**
1084
- * Saturate the colour with a given amount.
1085
- * @param {number=} amount a value in the [0, 100] range
1086
- * @returns {Color} the `Color` instance
1087
- */
1088
- saturate(amount) {
1089
- const self = this;
1090
- if (typeof amount !== 'number') return self;
1091
- const { h, s, l } = self.toHsl();
1092
- const { r, g, b } = hslToRgb(h, clamp01(s + amount / 100), l);
1093
-
1094
- ObjectAssign(self, { r, g, b });
1095
- return self;
1096
- }
1097
-
1098
- /**
1099
- * Desaturate the colour with a given amount.
1100
- * @param {number=} amount a value in the [0, 100] range
1101
- * @returns {Color} the `Color` instance
1102
- */
1103
- desaturate(amount) {
1104
- return typeof amount === 'number' ? this.saturate(-amount) : this;
1105
- }
1106
-
1107
- /**
1108
- * Completely desaturates a colour into greyscale.
1109
- * Same as calling `desaturate(100)`
1110
- * @returns {Color} the `Color` instance
1111
- */
1112
- greyscale() {
1113
- return this.saturate(-100);
1114
- }
1115
-
1116
- /**
1117
- * Increase the colour lightness with a given amount.
1118
- * @param {number=} amount a value in the [0, 100] range
1119
- * @returns {Color} the `Color` instance
1120
- */
1121
- lighten(amount) {
1122
- const self = this;
1123
- if (typeof amount !== 'number') return self;
1124
-
1125
- const { h, s, l } = self.toHsl();
1126
- const { r, g, b } = hslToRgb(h, s, clamp01(l + amount / 100));
1127
-
1128
- ObjectAssign(self, { r, g, b });
1129
- return self;
1130
- }
1131
-
1132
- /**
1133
- * Decrease the colour lightness with a given amount.
1134
- * @param {number=} amount a value in the [0, 100] range
1135
- * @returns {Color} the `Color` instance
1136
- */
1137
- darken(amount) {
1138
- return typeof amount === 'number' ? this.lighten(-amount) : this;
1139
- }
1140
-
1141
- /**
1142
- * Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
1143
- * Values outside of this range will be wrapped into this range.
1144
- *
1145
- * @param {number=} amount a value in the [0, 100] range
1146
- * @returns {Color} the `Color` instance
1147
- */
1148
- spin(amount) {
1149
- const self = this;
1150
- if (typeof amount !== 'number') return self;
1151
-
1152
- const { h, s, l } = self.toHsl();
1153
- const { r, g, b } = hslToRgb(clamp01(((h * 360 + amount) % 360) / 360), s, l);
1154
-
1155
- ObjectAssign(self, { r, g, b });
1156
- return self;
1157
- }
1158
-
1159
- /** Returns a clone of the current `Color` instance. */
1160
- clone() {
1161
- return new Color(this);
1162
- }
1163
-
1164
- /**
1165
- * Returns the colour value in CSS valid string format.
1166
- * @param {boolean=} allowShort when *true*, HEX values can be shorthand
1167
- * @returns {string} the CSS valid colour in the configured format
1168
- */
1169
- toString(allowShort) {
1170
- const self = this;
1171
- const { format } = self;
1172
-
1173
- if (format === 'hex') return self.toHexString(allowShort);
1174
- if (format === 'hsl') return self.toHslString();
1175
- if (format === 'hwb') return self.toHwbString();
1176
-
1177
- return self.toRgbString();
1178
- }
1179
- }
1180
-
1181
- ObjectAssign(Color, {
1182
- ANGLES,
1183
- CSS_ANGLE,
1184
- CSS_INTEGER,
1185
- CSS_NUMBER,
1186
- CSS_UNIT,
1187
- CSS_UNIT2,
1188
- PERMISSIVE_MATCH,
1189
- matchers,
1190
- isOnePointZero,
1191
- isPercentage,
1192
- isValidCSSUnit,
1193
- isColorName,
1194
- pad2,
1195
- clamp01,
1196
- bound01,
1197
- boundAlpha,
1198
- getRGBFromName,
1199
- convertHexToDecimal,
1200
- convertDecimalToHex,
1201
- rgbToHsl,
1202
- rgbToHex,
1203
- rgbToHsv,
1204
- rgbToHwb,
1205
- rgbaToHex,
1206
- hslToRgb,
1207
- hsvToRgb,
1208
- hueToRgb,
1209
- hwbToRgb,
1210
- parseIntFromHex,
1211
- stringInputToObject,
1212
- inputToRGB,
1213
- roundPart,
1214
- getElementStyle,
1215
- setElementStyle,
1216
- ObjectAssign,
1217
- });
1218
-
1219
- /** @type {Record<string, any>} */
1220
- const EventRegistry = {};
1221
-
1222
- /**
1223
- * The global event listener.
1224
- *
1225
- * @type {EventListener}
1226
- * @this {EventTarget}
1227
- */
1228
- function globalListener(e) {
1229
- const that = this;
1230
- const { type, target } = e;
1231
-
1232
- [...EventRegistry[type]].forEach((elementsMap) => {
1233
- const [element, listenersMap] = elementsMap;
1234
- /* istanbul ignore else */
1235
- if ([target, that].some((el) => element === el)) {
1236
- [...listenersMap].forEach((listenerMap) => {
1237
- const [listener, options] = listenerMap;
1238
- listener.apply(element, [e]);
1239
-
1240
- if (options && options.once) {
1241
- removeListener(element, type, listener, options);
1242
- }
1243
- });
1244
- }
1245
- });
1246
- }
1247
-
1248
- /**
1249
- * Register a new listener with its options and attach the `globalListener`
1250
- * to the target if this is the first listener.
1251
- *
1252
- * @type {Listener.ListenerAction<EventTarget>}
1253
- */
1254
- const addListener = (element, eventType, listener, options) => {
1255
- // get element listeners first
1256
- if (!EventRegistry[eventType]) {
1257
- EventRegistry[eventType] = new Map();
1258
- }
1259
- const oneEventMap = EventRegistry[eventType];
1260
-
1261
- if (!oneEventMap.has(element)) {
1262
- oneEventMap.set(element, new Map());
1263
- }
1264
- const oneElementMap = oneEventMap.get(element);
1265
-
1266
- // get listeners size
1267
- const { size } = oneElementMap;
1268
-
1269
- // register listener with its options
1270
- oneElementMap.set(listener, options);
1271
-
1272
- // add listener last
1273
- if (!size) {
1274
- element.addEventListener(eventType, globalListener, options);
1275
- }
1276
- };
1277
-
1278
- /**
1279
- * Remove a listener from registry and detach the `globalListener`
1280
- * if no listeners are found in the registry.
1281
- *
1282
- * @type {Listener.ListenerAction<EventTarget>}
1283
- */
1284
- const removeListener = (element, eventType, listener, options) => {
1285
- // get listener first
1286
- const oneEventMap = EventRegistry[eventType];
1287
- const oneElementMap = oneEventMap && oneEventMap.get(element);
1288
- const savedOptions = oneElementMap && oneElementMap.get(listener);
1289
-
1290
- // also recover initial options
1291
- const { options: eventOptions } = savedOptions !== undefined
1292
- ? savedOptions
1293
- : { options };
1294
-
1295
- // unsubscribe second, remove from registry
1296
- if (oneElementMap && oneElementMap.has(listener)) oneElementMap.delete(listener);
1297
- if (oneEventMap && (!oneElementMap || !oneElementMap.size)) oneEventMap.delete(element);
1298
- if (!oneEventMap || !oneEventMap.size) delete EventRegistry[eventType];
1299
-
1300
- // remove listener last
1301
- /* istanbul ignore else */
1302
- if (!oneElementMap || !oneElementMap.size) {
1303
- element.removeEventListener(eventType, globalListener, eventOptions);
1304
- }
1305
- };
1306
-
1307
- /**
1308
- * A global namespace for aria-description.
1309
- * @type {string}
1310
- */
1311
- const ariaDescription = 'aria-description';
1312
-
1313
- /**
1314
- * A global namespace for aria-selected.
1315
- * @type {string}
1316
- */
1317
- const ariaSelected = 'aria-selected';
1318
-
1319
- /**
1320
- * A global namespace for aria-expanded.
1321
- * @type {string}
1322
- */
1323
- const ariaExpanded = 'aria-expanded';
1324
-
1325
- /**
1326
- * A global namespace for aria-valuetext.
1327
- * @type {string}
1328
- */
1329
- const ariaValueText = 'aria-valuetext';
1330
-
1331
- /**
1332
- * A global namespace for aria-valuenow.
1333
- * @type {string}
1334
- */
1335
- const ariaValueNow = 'aria-valuenow';
1336
-
1337
- /**
1338
- * A global namespace for `ArrowDown` key.
1339
- * @type {string} e.which = 40 equivalent
1340
- */
1341
- const keyArrowDown = 'ArrowDown';
1342
-
1343
- /**
1344
- * A global namespace for `ArrowUp` key.
1345
- * @type {string} e.which = 38 equivalent
1346
- */
1347
- const keyArrowUp = 'ArrowUp';
1348
-
1349
- /**
1350
- * A global namespace for `ArrowLeft` key.
1351
- * @type {string} e.which = 37 equivalent
1352
- */
1353
- const keyArrowLeft = 'ArrowLeft';
1354
-
1355
- /**
1356
- * A global namespace for `ArrowRight` key.
1357
- * @type {string} e.which = 39 equivalent
1358
- */
1359
- const keyArrowRight = 'ArrowRight';
1360
-
1361
- /**
1362
- * A global namespace for `Enter` key.
1363
- * @type {string} e.which = 13 equivalent
1364
- */
1365
- const keyEnter = 'Enter';
1366
-
1367
- /**
1368
- * A global namespace for `Space` key.
1369
- * @type {string} e.which = 32 equivalent
1370
- */
1371
- const keySpace = 'Space';
1372
-
1373
- /**
1374
- * A global namespace for `Escape` key.
1375
- * @type {string} e.which = 27 equivalent
1376
- */
1377
- const keyEscape = 'Escape';
1378
-
1379
- /**
1380
- * A global namespace for `focusin` event.
1381
- * @type {string}
1382
- */
1383
- const focusinEvent = 'focusin';
1384
-
1385
- /**
1386
- * A global namespace for `click` event.
1387
- * @type {string}
1388
- */
1389
- const mouseclickEvent = 'click';
1390
-
1391
- /**
1392
- * A global namespace for `keydown` event.
1393
- * @type {string}
1394
- */
1395
- const keydownEvent = 'keydown';
1396
-
1397
- /**
1398
- * A global namespace for `change` event.
1399
- * @type {string}
1400
- */
1401
- const changeEvent = 'change';
1402
-
1403
- /**
1404
- * A global namespace for `touchmove` event.
1405
- * @type {string}
1406
- */
1407
- const touchmoveEvent = 'touchmove';
1408
-
1409
- /**
1410
- * A global namespace for `pointerdown` event.
1411
- * @type {string}
1412
- */
1413
- const pointerdownEvent = 'pointerdown';
1414
-
1415
- /**
1416
- * A global namespace for `pointermove` event.
1417
- * @type {string}
1418
- */
1419
- const pointermoveEvent = 'pointermove';
1420
-
1421
- /**
1422
- * A global namespace for `pointerup` event.
1423
- * @type {string}
1424
- */
1425
- const pointerupEvent = 'pointerup';
1426
-
1427
- /**
1428
- * A global namespace for `scroll` event.
1429
- * @type {string}
1430
- */
1431
- const scrollEvent = 'scroll';
1432
-
1433
- /**
1434
- * A global namespace for `keyup` event.
1435
- * @type {string}
1436
- */
1437
- const keyupEvent = 'keyup';
1438
-
1439
- /**
1440
- * A global namespace for `resize` event.
1441
- * @type {string}
1442
- */
1443
- const resizeEvent = 'resize';
1444
-
1445
- /**
1446
- * A global namespace for `focusout` event.
1447
- * @type {string}
1448
- */
1449
- const focusoutEvent = 'focusout';
1450
-
1451
- /**
1452
- * Returns the `document.documentElement` or the `<html>` element.
1453
- *
1454
- * @param {(Node | HTMLElement | Element | globalThis)=} node
1455
- * @returns {HTMLElement | HTMLHtmlElement}
1456
- */
1457
- function getDocumentElement(node) {
1458
- return getDocument(node).documentElement;
1459
- }
1460
-
1461
- let elementUID = 0;
1462
- let elementMapUID = 0;
1463
- const elementIDMap = new Map();
1464
-
1465
- /**
1466
- * Returns a unique identifier for popover, tooltip, scrollspy.
1467
- *
1468
- * @param {HTMLElement | Element} element target element
1469
- * @param {string=} key predefined key
1470
- * @returns {number} an existing or new unique ID
1471
- */
1472
- function getUID(element, key) {
1473
- let result = key ? elementUID : elementMapUID;
1474
-
1475
- if (key) {
1476
- const elID = getUID(element);
1477
- const elMap = elementIDMap.get(elID) || new Map();
1478
- if (!elementIDMap.has(elID)) {
1479
- elementIDMap.set(elID, elMap);
1480
- }
1481
- if (!elMap.has(key)) {
1482
- elMap.set(key, result);
1483
- elementUID += 1;
1484
- } else result = elMap.get(key);
1485
- } else {
1486
- const elkey = element.id || element;
1487
-
1488
- if (!elementIDMap.has(elkey)) {
1489
- elementIDMap.set(elkey, result);
1490
- elementMapUID += 1;
1491
- } else result = elementIDMap.get(elkey);
1492
- }
1493
- return result;
1494
- }
1495
-
1496
- /**
1497
- * Returns the bounding client rect of a target `HTMLElement`.
1498
- *
1499
- * @see https://github.com/floating-ui/floating-ui
1500
- *
1501
- * @param {HTMLElement | Element} element event.target
1502
- * @param {boolean=} includeScale when *true*, the target scale is also computed
1503
- * @returns {SHORTER.BoundingClientRect} the bounding client rect object
1504
- */
1505
- function getBoundingClientRect(element, includeScale) {
1506
- const {
1507
- width, height, top, right, bottom, left,
1508
- } = element.getBoundingClientRect();
1509
- let scaleX = 1;
1510
- let scaleY = 1;
1511
-
1512
- if (includeScale && element instanceof HTMLElement) {
1513
- const { offsetWidth, offsetHeight } = element;
1514
- scaleX = offsetWidth > 0 ? Math.round(width) / offsetWidth || 1 : 1;
1515
- scaleY = offsetHeight > 0 ? Math.round(height) / offsetHeight || 1 : 1;
1516
- }
1517
-
1518
- return {
1519
- width: width / scaleX,
1520
- height: height / scaleY,
1521
- top: top / scaleY,
1522
- right: right / scaleX,
1523
- bottom: bottom / scaleY,
1524
- left: left / scaleX,
1525
- x: left / scaleX,
1526
- y: top / scaleY,
1527
- };
1528
- }
1529
-
1530
- /**
1531
- * A global namespace for 'transitionDuration' string.
1532
- * @type {string}
1533
- */
1534
- const transitionDuration = 'transitionDuration';
1535
-
1536
- /**
1537
- * A global namespace for `transitionProperty` string for modern browsers.
1538
- *
1539
- * @type {string}
1540
- */
1541
- const transitionProperty = 'transitionProperty';
1542
-
1543
- /**
1544
- * Utility to get the computed `transitionDuration`
1545
- * from Element in miliseconds.
1546
- *
1547
- * @param {HTMLElement | Element} element target
1548
- * @return {number} the value in miliseconds
1549
- */
1550
- function getElementTransitionDuration(element) {
1551
- const propertyValue = getElementStyle(element, transitionProperty);
1552
- const durationValue = getElementStyle(element, transitionDuration);
1553
- const durationScale = durationValue.includes('ms') ? 1 : 1000;
1554
- const duration = propertyValue && propertyValue !== 'none'
1555
- ? parseFloat(durationValue) * durationScale : 0;
1556
-
1557
- return !Number.isNaN(duration) ? duration : 0;
1558
- }
1559
-
1560
- /**
1561
- * A global array of possible `ParentNode`.
1562
- */
1563
- const parentNodes = [Document, Element, HTMLElement];
1564
-
1565
- /**
1566
- * A global array with `Element` | `HTMLElement`.
1567
- */
1568
- const elementNodes = [Element, HTMLElement];
1569
-
1570
- /**
1571
- * Utility to check if target is typeof `HTMLElement`, `Element`, `Node`
1572
- * or find one that matches a selector.
1573
- *
1574
- * @param {HTMLElement | Element | string} selector the input selector or target element
1575
- * @param {(HTMLElement | Element | Document)=} parent optional node to look into
1576
- * @return {(HTMLElement | Element)?} the `HTMLElement` or `querySelector` result
1577
- */
1578
- function querySelector(selector, parent) {
1579
- const lookUp = parentNodes.some((x) => parent instanceof x)
1580
- ? parent : getDocument();
1581
-
1582
- // @ts-ignore
1583
- return elementNodes.some((x) => selector instanceof x)
1584
- // @ts-ignore
1585
- ? selector : lookUp.querySelector(selector);
1586
- }
1587
-
1588
- /**
1589
- * Shortcut for `HTMLElement.closest` method which also works
1590
- * with children of `ShadowRoot`. The order of the parameters
1591
- * is intentional since they're both required.
1592
- *
1593
- * @see https://stackoverflow.com/q/54520554/803358
1594
- *
1595
- * @param {HTMLElement | Element} element Element to look into
1596
- * @param {string} selector the selector name
1597
- * @return {(HTMLElement | Element)?} the query result
1598
- */
1599
- function closest(element, selector) {
1600
- return element ? (element.closest(selector)
1601
- // @ts-ignore -- break out of `ShadowRoot`
1602
- || closest(element.getRootNode().host, selector)) : null;
1603
- }
1604
-
1605
- /**
1606
- * Shortcut for `HTMLElement.getElementsByClassName` method. Some `Node` elements
1607
- * like `ShadowRoot` do not support `getElementsByClassName`.
1608
- *
1609
- * @param {string} selector the class name
1610
- * @param {(HTMLElement | Element | Document)=} parent optional Element to look into
1611
- * @return {HTMLCollectionOf<HTMLElement | Element>} the 'HTMLCollection'
1612
- */
1613
- function getElementsByClassName(selector, parent) {
1614
- const lookUp = parent && parentNodes.some((x) => parent instanceof x)
1615
- ? parent : getDocument();
1616
- return lookUp.getElementsByClassName(selector);
1617
- }
1618
-
1619
- /**
1620
- * Shortcut for the `Element.dispatchEvent(Event)` method.
1621
- *
1622
- * @param {HTMLElement | Element} element is the target
1623
- * @param {Event} event is the `Event` object
1624
- */
1625
- const dispatchEvent = (element, event) => element.dispatchEvent(event);
1626
-
1627
- /** @type {Map<string, Map<HTMLElement | Element, Record<string, any>>>} */
1628
- const componentData = new Map();
1629
- /**
1630
- * An interface for web components background data.
1631
- * @see https://github.com/thednp/bootstrap.native/blob/master/src/components/base-component.js
1632
- */
1633
- const Data = {
1634
- /**
1635
- * Sets web components data.
1636
- * @param {HTMLElement | Element | string} target target element
1637
- * @param {string} component the component's name or a unique key
1638
- * @param {Record<string, any>} instance the component instance
1639
- */
1640
- set: (target, component, instance) => {
1641
- const element = querySelector(target);
1642
- if (!element) return;
1643
-
1644
- if (!componentData.has(component)) {
1645
- componentData.set(component, new Map());
1646
- }
1647
-
1648
- const instanceMap = componentData.get(component);
1649
- // @ts-ignore - not undefined, but defined right above
1650
- instanceMap.set(element, instance);
1651
- },
1652
-
1653
- /**
1654
- * Returns all instances for specified component.
1655
- * @param {string} component the component's name or a unique key
1656
- * @returns {Map<HTMLElement | Element, Record<string, any>>?} all the component instances
1657
- */
1658
- getAllFor: (component) => {
1659
- const instanceMap = componentData.get(component);
1660
-
1661
- return instanceMap || null;
1662
- },
1663
-
1664
- /**
1665
- * Returns the instance associated with the target.
1666
- * @param {HTMLElement | Element | string} target target element
1667
- * @param {string} component the component's name or a unique key
1668
- * @returns {Record<string, any>?} the instance
1669
- */
1670
- get: (target, component) => {
1671
- const element = querySelector(target);
1672
- const allForC = Data.getAllFor(component);
1673
- const instance = element && allForC && allForC.get(element);
1674
-
1675
- return instance || null;
1676
- },
1677
-
1678
- /**
1679
- * Removes web components data.
1680
- * @param {HTMLElement | Element | string} target target element
1681
- * @param {string} component the component's name or a unique key
1682
- */
1683
- remove: (target, component) => {
1684
- const element = querySelector(target);
1685
- const instanceMap = componentData.get(component);
1686
- if (!instanceMap || !element) return;
1687
-
1688
- instanceMap.delete(element);
1689
-
1690
- if (instanceMap.size === 0) {
1691
- componentData.delete(component);
1692
- }
1693
- },
1694
- };
1695
-
1696
- /**
1697
- * An alias for `Data.get()`.
1698
- * @type {SHORTER.getInstance<any>}
1699
- */
1700
- const getInstance = (target, component) => Data.get(target, component);
1701
-
1702
- /**
1703
- * The raw value or a given component option.
1704
- *
1705
- * @typedef {string | HTMLElement | Function | number | boolean | null} niceValue
1706
- */
1707
-
1708
- /**
1709
- * Utility to normalize component options
1710
- *
1711
- * @param {any} value the input value
1712
- * @return {niceValue} the normalized value
1713
- */
1714
- function normalizeValue(value) {
1715
- if (value === 'true') { // boolean
1716
- return true;
1717
- }
1718
-
1719
- if (value === 'false') { // boolean
1720
- return false;
1721
- }
1722
-
1723
- if (!Number.isNaN(+value)) { // number
1724
- return +value;
1725
- }
1726
-
1727
- if (value === '' || value === 'null') { // null
1728
- return null;
1729
- }
1730
-
1731
- // string / function / HTMLElement / object
1732
- return value;
1733
- }
1734
-
1735
- /**
1736
- * Shortcut for `Object.keys()` static method.
1737
- * @param {Record<string, any>} obj a target object
1738
- * @returns {string[]}
1739
- */
1740
- const ObjectKeys = (obj) => Object.keys(obj);
1741
-
1742
- /**
1743
- * Utility to normalize component options.
1744
- *
1745
- * @param {HTMLElement | Element} element target
1746
- * @param {Record<string, any>} defaultOps component default options
1747
- * @param {Record<string, any>} inputOps component instance options
1748
- * @param {string=} ns component namespace
1749
- * @return {Record<string, any>} normalized component options object
1750
- */
1751
- function normalizeOptions(element, defaultOps, inputOps, ns) {
1752
- // @ts-ignore -- our targets are always `HTMLElement`
1753
- const data = { ...element.dataset };
1754
- /** @type {Record<string, any>} */
1755
- const normalOps = {};
1756
- /** @type {Record<string, any>} */
1757
- const dataOps = {};
1758
- const title = 'title';
1759
-
1760
- ObjectKeys(data).forEach((k) => {
1761
- const key = ns && k.includes(ns)
1762
- ? k.replace(ns, '').replace(/[A-Z]/, (match) => toLowerCase(match))
1763
- : k;
1764
-
1765
- dataOps[key] = normalizeValue(data[k]);
1766
- });
1767
-
1768
- ObjectKeys(inputOps).forEach((k) => {
1769
- inputOps[k] = normalizeValue(inputOps[k]);
1770
- });
1771
-
1772
- ObjectKeys(defaultOps).forEach((k) => {
1773
- if (k in inputOps) {
1774
- normalOps[k] = inputOps[k];
1775
- } else if (k in dataOps) {
1776
- normalOps[k] = dataOps[k];
1777
- } else {
1778
- normalOps[k] = k === title
1779
- ? getAttribute(element, title)
1780
- : defaultOps[k];
1781
- }
1782
- });
1783
-
1784
- return normalOps;
1785
- }
1786
-
1787
- /**
1788
- * Utility to force re-paint of an `HTMLElement` target.
1789
- *
1790
- * @param {HTMLElement | Element} element is the target
1791
- * @return {number} the `Element.offsetHeight` value
1792
- */
1793
- // @ts-ignore
1794
- const reflow = (element) => element.offsetHeight;
1795
-
1796
- /**
1797
- * Utility to focus an `HTMLElement` target.
1798
- *
1799
- * @param {HTMLElement | Element} element is the target
1800
- */
1801
- // @ts-ignore -- `Element`s resulted from querySelector can focus too
1802
- const focus = (element) => element.focus();
1803
-
1804
- /**
1805
- * Check class in `HTMLElement.classList`.
1806
- *
1807
- * @param {HTMLElement | Element} element target
1808
- * @param {string} classNAME to check
1809
- * @returns {boolean}
1810
- */
1811
- function hasClass(element, classNAME) {
1812
- return element.classList.contains(classNAME);
1813
- }
1814
-
1815
- /**
1816
- * Add class to `HTMLElement.classList`.
1817
- *
1818
- * @param {HTMLElement | Element} element target
1819
- * @param {string} classNAME to add
1820
- * @returns {void}
1821
- */
1822
- function addClass(element, classNAME) {
1823
- element.classList.add(classNAME);
1824
- }
1825
-
1826
- /**
1827
- * Remove class from `HTMLElement.classList`.
1828
- *
1829
- * @param {HTMLElement | Element} element target
1830
- * @param {string} classNAME to remove
1831
- * @returns {void}
1832
- */
1833
- function removeClass(element, classNAME) {
1834
- element.classList.remove(classNAME);
1835
- }
1836
-
1837
- /**
1838
- * Shortcut for `HTMLElement.removeAttribute()` method.
1839
- * @param {HTMLElement | Element} element target element
1840
- * @param {string} attribute attribute name
1841
- * @returns {void}
1842
- */
1843
- const removeAttribute = (element, attribute) => element.removeAttribute(attribute);
1844
-
1845
- /**
1846
- * @class
1847
- * Returns a color palette with a given set of parameters.
1848
- * @example
1849
- * new ColorPalette(0, 12, 10);
1850
- * // => { hue: 0, hueSteps: 12, lightSteps: 10, colors: Array<Color> }
1851
- */
1852
- class ColorPalette {
1853
- /**
1854
- * The `hue` parameter is optional, which would be set to 0.
1855
- * @param {number[]} args represeinting hue, hueSteps, lightSteps
1856
- * * `args.hue` the starting Hue [0, 360]
1857
- * * `args.hueSteps` Hue Steps Count [5, 24]
1858
- * * `args.lightSteps` Lightness Steps Count [5, 12]
1859
- */
1860
- constructor(...args) {
1861
- let hue = 0;
1862
- let hueSteps = 12;
1863
- let lightSteps = 10;
1864
- let lightnessArray = [0.5];
1865
-
1866
- if (args.length === 3) {
1867
- [hue, hueSteps, lightSteps] = args;
1868
- } else if (args.length === 2) {
1869
- [hueSteps, lightSteps] = args;
1870
- if ([hueSteps, lightSteps].some((n) => n < 1)) {
1871
- throw TypeError('ColorPalette: both arguments must be higher than 0.');
1872
- }
1873
- }
1874
-
1875
- /** @type {*} */
1876
- const colors = [];
1877
- const hueStep = 360 / hueSteps;
1878
- const half = roundPart((lightSteps - (lightSteps % 2 ? 1 : 0)) / 2);
1879
- const steps1To13 = [0.25, 0.2, 0.15, 0.11, 0.09, 0.075];
1880
- const lightSets = [[1, 2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13]];
1881
- const closestSet = lightSets.find((set) => set.includes(lightSteps));
1882
-
1883
- // find a lightStep that won't go beyond black and white
1884
- // something within the [10-90] range of lightness
1885
- const lightStep = closestSet
1886
- ? steps1To13[lightSets.indexOf(closestSet)]
1887
- : (100 / (lightSteps + (lightSteps % 2 ? 0 : 1)) / 100);
1888
-
1889
- // light tints
1890
- for (let i = 1; i < half + 1; i += 1) {
1891
- lightnessArray = [...lightnessArray, (0.5 + lightStep * (i))];
1892
- }
1893
-
1894
- // dark tints
1895
- for (let i = 1; i < lightSteps - half; i += 1) {
1896
- lightnessArray = [(0.5 - lightStep * (i)), ...lightnessArray];
1897
- }
1898
-
1899
- // feed `colors` Array
1900
- for (let i = 0; i < hueSteps; i += 1) {
1901
- const currentHue = ((hue + i * hueStep) % 360) / 360;
1902
- lightnessArray.forEach((l) => {
1903
- colors.push(new Color({ h: currentHue, s: 1, l }));
1904
- });
1905
- }
1906
-
1907
- this.hue = hue;
1908
- this.hueSteps = hueSteps;
1909
- this.lightSteps = lightSteps;
1910
- this.colors = colors;
1911
- }
1912
- }
1913
-
1914
- ObjectAssign(ColorPalette, { Color });
1915
-
1916
- /** @type {Record<string, string>} */
1917
- const colorPickerLabels = {
1918
- pickerLabel: 'Colour Picker',
1919
- appearanceLabel: 'Colour Appearance',
1920
- valueLabel: 'Colour Value',
1921
- toggleLabel: 'Select Colour',
1922
- presetsLabel: 'Colour Presets',
1923
- defaultsLabel: 'Colour Defaults',
1924
- formatLabel: 'Format',
1925
- alphaLabel: 'Alpha',
1926
- hexLabel: 'Hexadecimal',
1927
- hueLabel: 'Hue',
1928
- whitenessLabel: 'Whiteness',
1929
- blacknessLabel: 'Blackness',
1930
- saturationLabel: 'Saturation',
1931
- lightnessLabel: 'Lightness',
1932
- redLabel: 'Red',
1933
- greenLabel: 'Green',
1934
- blueLabel: 'Blue',
1935
- };
1936
-
1937
- /**
1938
- * A list of 17 color names used for WAI-ARIA compliance.
1939
- * @type {string[]}
1940
- */
1941
- const colorNames = ['white', 'black', 'grey', 'red', 'orange', 'brown', 'gold', 'olive', 'yellow', 'lime', 'green', 'teal', 'cyan', 'blue', 'violet', 'magenta', 'pink'];
1942
-
1943
- const tabIndex = 'tabindex';
1944
-
1945
- /**
1946
- * Check if a string is valid JSON string.
1947
- * @param {string} str the string input
1948
- * @returns {boolean} the query result
1949
- */
1950
- function isValidJSON(str) {
1951
- try {
1952
- JSON.parse(str);
1953
- } catch (e) {
1954
- return false;
1955
- }
1956
- return true;
1957
- }
1958
-
1959
- /**
1960
- * Shortcut for `String.toUpperCase()`.
1961
- *
1962
- * @param {string} source input string
1963
- * @returns {string} uppercase output string
1964
- */
1965
- const toUpperCase = (source) => source.toUpperCase();
1966
-
1967
- /**
1968
- * A global namespace for aria-haspopup.
1969
- * @type {string}
1970
- */
1971
- const ariaHasPopup = 'aria-haspopup';
1972
-
1973
- /**
1974
- * A global namespace for aria-hidden.
1975
- * @type {string}
1976
- */
1977
- const ariaHidden = 'aria-hidden';
1978
-
1979
- /**
1980
- * A global namespace for aria-labelledby.
1981
- * @type {string}
1982
- */
1983
- const ariaLabelledBy = 'aria-labelledby';
1984
-
1985
- /**
1986
- * This is a shortie for `document.createElementNS` method
1987
- * which allows you to create a new `HTMLElement` for a given `tagName`
1988
- * or based on an object with specific non-readonly attributes:
1989
- * `id`, `className`, `textContent`, `style`, etc.
1990
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS
1991
- *
1992
- * @param {string} namespace `namespaceURI` to associate with the new `HTMLElement`
1993
- * @param {Record<string, string> | string} param `tagName` or object
1994
- * @return {HTMLElement | Element} a new `HTMLElement` or `Element`
1995
- */
1996
- function createElementNS(namespace, param) {
1997
- if (typeof param === 'string') {
1998
- return getDocument().createElementNS(namespace, param);
1999
- }
2000
-
2001
- const { tagName } = param;
2002
- const attr = { ...param };
2003
- const newElement = createElementNS(namespace, tagName);
2004
- delete attr.tagName;
2005
- ObjectAssign(newElement, attr);
2006
- return newElement;
2007
- }
2008
-
2009
- const vHidden = 'v-hidden';
2010
-
2011
- /**
2012
- * Returns the color form for `ColorPicker`.
2013
- *
2014
- * @param {CP.ColorPicker} self the `ColorPicker` instance
2015
- * @returns {HTMLElement | Element} a new `<div>` element with color component `<input>`
2016
- */
2017
- function getColorForm(self) {
2018
- const { format, id, componentLabels } = self;
2019
- const colorForm = createElement({
2020
- tagName: 'div',
2021
- className: `color-form ${format}`,
2022
- });
2023
-
2024
- let components = ['hex'];
2025
- if (format === 'rgb') components = ['red', 'green', 'blue', 'alpha'];
2026
- else if (format === 'hsl') components = ['hue', 'saturation', 'lightness', 'alpha'];
2027
- else if (format === 'hwb') components = ['hue', 'whiteness', 'blackness', 'alpha'];
2028
-
2029
- components.forEach((c) => {
2030
- const [C] = format === 'hex' ? ['#'] : toUpperCase(c).split('');
2031
- const cID = `color_${format}_${c}_${id}`;
2032
- const formatLabel = componentLabels[`${c}Label`];
2033
- const cInputLabel = createElement({ tagName: 'label' });
2034
- setAttribute(cInputLabel, 'for', cID);
2035
- cInputLabel.append(
2036
- createElement({ tagName: 'span', ariaHidden: 'true', innerText: `${C}:` }),
2037
- createElement({ tagName: 'span', className: vHidden, innerText: formatLabel }),
2038
- );
2039
- const cInput = createElement({
2040
- tagName: 'input',
2041
- id: cID,
2042
- // name: cID, - prevent saving the value to a form
2043
- type: format === 'hex' ? 'text' : 'number',
2044
- value: c === 'alpha' ? '100' : '0',
2045
- className: `color-input ${c}`,
2046
- });
2047
- setAttribute(cInput, 'autocomplete', 'off');
2048
- setAttribute(cInput, 'spellcheck', 'false');
2049
-
2050
- // alpha
2051
- let max = '100';
2052
- let step = '1';
2053
- if (c !== 'alpha') {
2054
- if (format === 'rgb') {
2055
- max = '255'; step = '1';
2056
- } else if (c === 'hue') {
2057
- max = '360'; step = '1';
2058
- }
2059
- }
2060
- ObjectAssign(cInput, {
2061
- min: '0',
2062
- max,
2063
- step,
2064
- });
2065
- colorForm.append(cInputLabel, cInput);
2066
- });
2067
- return colorForm;
2068
- }
2069
-
2070
- /**
2071
- * A global namespace for aria-label.
2072
- * @type {string}
2073
- */
2074
- const ariaLabel = 'aria-label';
2075
-
2076
- /**
2077
- * A global namespace for aria-valuemin.
2078
- * @type {string}
2079
- */
2080
- const ariaValueMin = 'aria-valuemin';
2081
-
2082
- /**
2083
- * A global namespace for aria-valuemax.
2084
- * @type {string}
2085
- */
2086
- const ariaValueMax = 'aria-valuemax';
2087
-
2088
- /**
2089
- * Returns all color controls for `ColorPicker`.
2090
- *
2091
- * @param {CP.ColorPicker} self the `ColorPicker` instance
2092
- * @returns {HTMLElement | Element} color controls
2093
- */
2094
- function getColorControls(self) {
2095
- const { format, componentLabels } = self;
2096
- const {
2097
- hueLabel, alphaLabel, lightnessLabel, saturationLabel,
2098
- whitenessLabel, blacknessLabel,
2099
- } = componentLabels;
2100
-
2101
- const max1 = format === 'hsl' ? 360 : 100;
2102
- const max2 = format === 'hsl' ? 100 : 360;
2103
- const max3 = 100;
2104
-
2105
- let ctrl1Label = format === 'hsl'
2106
- ? `${hueLabel} & ${lightnessLabel}`
2107
- : `${lightnessLabel} & ${saturationLabel}`;
2108
-
2109
- ctrl1Label = format === 'hwb'
2110
- ? `${whitenessLabel} & ${blacknessLabel}`
2111
- : ctrl1Label;
2112
-
2113
- const ctrl2Label = format === 'hsl'
2114
- ? `${saturationLabel}`
2115
- : `${hueLabel}`;
2116
-
2117
- const colorControls = createElement({
2118
- tagName: 'div',
2119
- className: `color-controls ${format}`,
2120
- });
2121
-
2122
- const colorPointer = 'color-pointer';
2123
- const colorSlider = 'color-slider';
2124
-
2125
- const controls = [
2126
- {
2127
- i: 1,
2128
- c: colorPointer,
2129
- l: ctrl1Label,
2130
- min: 0,
2131
- max: max1,
2132
- },
2133
- {
2134
- i: 2,
2135
- c: colorSlider,
2136
- l: ctrl2Label,
2137
- min: 0,
2138
- max: max2,
2139
- },
2140
- {
2141
- i: 3,
2142
- c: colorSlider,
2143
- l: alphaLabel,
2144
- min: 0,
2145
- max: max3,
2146
- },
2147
- ];
2148
-
2149
- controls.forEach((template) => {
2150
- const {
2151
- i, c, l, min, max,
2152
- } = template;
2153
- const control = createElement({
2154
- tagName: 'div',
2155
- className: 'color-control',
2156
- });
2157
- setAttribute(control, 'role', 'presentation');
2158
-
2159
- control.append(
2160
- createElement({
2161
- tagName: 'div',
2162
- className: `visual-control visual-control${i}`,
2163
- }),
2164
- );
2165
-
2166
- const knob = createElement({
2167
- tagName: 'div',
2168
- className: `${c} knob`,
2169
- ariaLive: 'polite',
2170
- });
2171
-
2172
- setAttribute(knob, ariaLabel, l);
2173
- setAttribute(knob, 'role', 'slider');
2174
- setAttribute(knob, tabIndex, '0');
2175
- setAttribute(knob, ariaValueMin, `${min}`);
2176
- setAttribute(knob, ariaValueMax, `${max}`);
2177
- control.append(knob);
2178
- colorControls.append(control);
2179
- });
2180
-
2181
- return colorControls;
2182
- }
2183
-
2184
- /**
2185
- * Helps setting CSS variables to the color-menu.
2186
- * @param {HTMLElement} element
2187
- * @param {Record<string,any>} props
2188
- */
2189
- function setCSSProperties(element, props) {
2190
- ObjectKeys(props).forEach((prop) => {
2191
- element.style.setProperty(prop, props[prop]);
2192
- });
2193
- }
2194
-
2195
- /**
2196
- * Returns a color-defaults with given values and class.
2197
- * @param {CP.ColorPicker} self
2198
- * @param {CP.ColorPalette | string[]} colorsSource
2199
- * @param {string} menuClass
2200
- * @returns {HTMLElement | Element}
2201
- */
2202
- function getColorMenu(self, colorsSource, menuClass) {
2203
- const { input, format, componentLabels } = self;
2204
- const { defaultsLabel, presetsLabel } = componentLabels;
2205
- const isOptionsMenu = menuClass === 'color-options';
2206
- const isPalette = colorsSource instanceof ColorPalette;
2207
- const menuLabel = isOptionsMenu ? presetsLabel : defaultsLabel;
2208
- const colorsArray = isPalette ? colorsSource.colors : colorsSource;
2209
- const colorsCount = colorsArray.length;
2210
- const { lightSteps } = isPalette ? colorsSource : { lightSteps: null };
2211
- const fit = lightSteps || [9, 10].find((x) => colorsCount >= x * 2 && !(colorsCount % x)) || 5;
2212
- const isMultiLine = isOptionsMenu && colorsCount > fit;
2213
- let rowCountHover = 2;
2214
- rowCountHover = isMultiLine && colorsCount > fit * 2 ? 3 : rowCountHover;
2215
- rowCountHover = isMultiLine && colorsCount > fit * 3 ? 4 : rowCountHover;
2216
- rowCountHover = isMultiLine && colorsCount > fit * 4 ? 5 : rowCountHover;
2217
- const rowCount = rowCountHover - (colorsCount <= fit * 3 ? 1 : 2);
2218
- const isScrollable = isMultiLine && colorsCount > rowCount * fit;
2219
- let finalClass = menuClass;
2220
- finalClass += isScrollable ? ' scrollable' : '';
2221
- finalClass += isMultiLine ? ' multiline' : '';
2222
- const gap = isMultiLine ? '1px' : '0.25rem';
2223
- let optionSize = isMultiLine ? 1.75 : 2;
2224
- optionSize = fit > 5 && isMultiLine ? 1.5 : optionSize;
2225
- const menuHeight = `${rowCount * optionSize}rem`;
2226
- const menuHeightHover = `calc(${rowCountHover} * ${optionSize}rem + ${rowCountHover - 1} * ${gap})`;
2227
- /** @type {HTMLUListElement} */
2228
- // @ts-ignore -- <UL> is an `HTMLElement`
2229
- const menu = createElement({
2230
- tagName: 'ul',
2231
- className: finalClass,
2232
- });
2233
- setAttribute(menu, 'role', 'listbox');
2234
- setAttribute(menu, ariaLabel, menuLabel);
2235
-
2236
- if (isScrollable) {
2237
- setCSSProperties(menu, {
2238
- '--grid-item-size': `${optionSize}rem`,
2239
- '--grid-fit': fit,
2240
- '--grid-gap': gap,
2241
- '--grid-height': menuHeight,
2242
- '--grid-hover-height': menuHeightHover,
2243
- });
2244
- }
2245
-
2246
- colorsArray.forEach((x) => {
2247
- let [value, label] = typeof x === 'string' ? x.trim().split(':') : [];
2248
- if (x instanceof Color) {
2249
- value = x.toHexString();
2250
- label = value;
2251
- }
2252
- const color = new Color(x instanceof Color ? x : value, format);
2253
- const isActive = color.toString() === getAttribute(input, 'value');
2254
- const active = isActive ? ' active' : '';
2255
-
2256
- const option = createElement({
2257
- tagName: 'li',
2258
- className: `color-option${active}`,
2259
- innerText: `${label || value}`,
2260
- });
2261
-
2262
- setAttribute(option, tabIndex, '0');
2263
- setAttribute(option, 'data-value', `${value}`);
2264
- setAttribute(option, 'role', 'option');
2265
- setAttribute(option, ariaSelected, isActive ? 'true' : 'false');
2266
-
2267
- if (isOptionsMenu) {
2268
- setElementStyle(option, { backgroundColor: value });
2269
- }
2270
-
2271
- menu.append(option);
2272
- });
2273
- return menu;
2274
- }
2275
-
2276
- /**
2277
- * Generate HTML markup and update instance properties.
2278
- * @param {CP.ColorPicker} self
2279
- */
2280
- function setMarkup(self) {
2281
- const {
2282
- input, parent, format, id, componentLabels, colorKeywords, colorPresets,
2283
- } = self;
2284
- const colorValue = getAttribute(input, 'value') || '#fff';
2285
-
2286
- const {
2287
- toggleLabel, pickerLabel, formatLabel, hexLabel,
2288
- } = componentLabels;
2289
-
2290
- // update color
2291
- const color = nonColors.includes(colorValue) ? '#fff' : colorValue;
2292
- self.color = new Color(color, format);
2293
-
2294
- // set initial controls dimensions
2295
- const formatString = format === 'hex' ? hexLabel : toUpperCase(format);
2296
-
2297
- const pickerBtn = createElement({
2298
- id: `picker-btn-${id}`,
2299
- tagName: 'button',
2300
- className: 'picker-toggle btn-appearance',
2301
- });
2302
- setAttribute(pickerBtn, ariaExpanded, 'false');
2303
- setAttribute(pickerBtn, ariaHasPopup, 'true');
2304
- pickerBtn.append(createElement({
2305
- tagName: 'span',
2306
- className: vHidden,
2307
- innerText: `${pickerLabel}. ${formatLabel}: ${formatString}`,
2308
- }));
2309
-
2310
- const pickerDropdown = createElement({
2311
- tagName: 'div',
2312
- className: 'color-dropdown picker',
2313
- });
2314
- setAttribute(pickerDropdown, ariaLabelledBy, `picker-btn-${id}`);
2315
- setAttribute(pickerDropdown, 'role', 'group');
2316
-
2317
- const colorControls = getColorControls(self);
2318
- const colorForm = getColorForm(self);
2319
-
2320
- pickerDropdown.append(colorControls, colorForm);
2321
- input.before(pickerBtn);
2322
- parent.append(pickerDropdown);
2323
-
2324
- // set colour key menu template
2325
- if (colorKeywords || colorPresets) {
2326
- const presetsDropdown = createElement({
2327
- tagName: 'div',
2328
- className: 'color-dropdown scrollable menu',
2329
- });
2330
-
2331
- // color presets
2332
- if (colorPresets) {
2333
- presetsDropdown.append(getColorMenu(self, colorPresets, 'color-options'));
2334
- }
2335
-
2336
- // explicit defaults [reset, initial, inherit, transparent, currentColor]
2337
- // also custom defaults [default: #069, complementary: #930]
2338
- if (colorKeywords && colorKeywords.length) {
2339
- presetsDropdown.append(getColorMenu(self, colorKeywords, 'color-defaults'));
2340
- }
2341
-
2342
- const presetsBtn = createElement({
2343
- tagName: 'button',
2344
- className: 'menu-toggle btn-appearance',
2345
- });
2346
- setAttribute(presetsBtn, tabIndex, '-1');
2347
- setAttribute(presetsBtn, ariaExpanded, 'false');
2348
- setAttribute(presetsBtn, ariaHasPopup, 'true');
2349
-
2350
- const xmlns = encodeURI('http://www.w3.org/2000/svg');
2351
- const presetsIcon = createElementNS(xmlns, { tagName: 'svg' });
2352
- setAttribute(presetsIcon, 'xmlns', xmlns);
2353
- setAttribute(presetsIcon, 'viewBox', '0 0 512 512');
2354
- setAttribute(presetsIcon, ariaHidden, 'true');
2355
-
2356
- const path = createElementNS(xmlns, { tagName: 'path' });
2357
- setAttribute(path, 'd', 'M98,158l157,156L411,158l27,27L255,368L71,185L98,158z');
2358
- setAttribute(path, 'fill', '#fff');
2359
- presetsIcon.append(path);
2360
- presetsBtn.append(createElement({
2361
- tagName: 'span',
2362
- className: vHidden,
2363
- innerText: `${toggleLabel}`,
2364
- }), presetsIcon);
2365
-
2366
- parent.append(presetsBtn, presetsDropdown);
2367
- }
2368
-
2369
- // solve non-colors after settings save
2370
- if (colorKeywords && nonColors.includes(colorValue)) {
2371
- self.value = colorValue;
2372
- }
2373
- setAttribute(input, tabIndex, '-1');
2374
- }
2375
-
2376
- var version = "1.0.0";
2377
-
2378
- // @ts-ignore
2379
-
2380
- const Version = version;
2381
-
2382
- // ColorPicker GC
2383
- // ==============
2384
- const colorPickerString = 'color-picker';
2385
- const colorPickerSelector = `[data-function="${colorPickerString}"]`;
2386
- const colorPickerParentSelector = `.${colorPickerString},${colorPickerString}`;
2387
- const colorPickerDefaults = {
2388
- componentLabels: colorPickerLabels,
2389
- colorLabels: colorNames,
2390
- format: 'rgb',
2391
- colorPresets: false,
2392
- colorKeywords: false,
2393
- };
2394
-
2395
- // ColorPicker Static Methods
2396
- // ==========================
2397
-
2398
- /** @type {CP.GetInstance<ColorPicker, HTMLInputElement>} */
2399
- const getColorPickerInstance = (element) => getInstance(element, colorPickerString);
2400
-
2401
- /** @type {CP.InitCallback<ColorPicker>} */
2402
- const initColorPicker = (element) => new ColorPicker(element);
2403
-
2404
- // ColorPicker Private Methods
2405
- // ===========================
2406
-
2407
- /**
2408
- * Add / remove `ColorPicker` main event listeners.
2409
- * @param {ColorPicker} self
2410
- * @param {boolean=} action
2411
- */
2412
- function toggleEvents(self, action) {
2413
- const fn = action ? addListener : removeListener;
2414
- const { input, pickerToggle, menuToggle } = self;
2415
-
2416
- fn(input, focusinEvent, self.showPicker);
2417
- fn(pickerToggle, mouseclickEvent, self.togglePicker);
2418
-
2419
- if (menuToggle) {
2420
- fn(menuToggle, mouseclickEvent, self.toggleMenu);
2421
- }
2422
- }
2423
-
2424
- /**
2425
- * Add / remove `ColorPicker` event listeners active only when open.
2426
- * @param {ColorPicker} self
2427
- * @param {boolean=} action
2428
- */
2429
- function toggleEventsOnShown(self, action) {
2430
- const fn = action ? addListener : removeListener;
2431
- const { input, colorMenu, parent } = self;
2432
- const doc = getDocument(input);
2433
- // const win = getWindow(input);
2434
- const win = doc.defaultView;
2435
-
2436
- fn(self.controls, pointerdownEvent, self.pointerDown);
2437
- self.controlKnobs.forEach((x) => fn(x, keydownEvent, self.handleKnobs));
2438
-
2439
- // @ts-ignore -- this is `Window`
2440
- fn(win, scrollEvent, self.handleScroll);
2441
- // @ts-ignore -- this is `Window`
2442
- fn(win, resizeEvent, self.update);
2443
-
2444
- [input, ...self.inputs].forEach((x) => fn(x, changeEvent, self.changeHandler));
2445
-
2446
- if (colorMenu) {
2447
- fn(colorMenu, mouseclickEvent, self.menuClickHandler);
2448
- fn(colorMenu, keydownEvent, self.menuKeyHandler);
2449
- }
2450
-
2451
- fn(doc, pointermoveEvent, self.pointerMove);
2452
- fn(doc, pointerupEvent, self.pointerUp);
2453
- fn(parent, focusoutEvent, self.handleFocusOut);
2454
- fn(doc, keyupEvent, self.handleDismiss);
2455
- }
2456
-
2457
- /**
2458
- * Triggers the `ColorPicker` original event.
2459
- * @param {ColorPicker} self
2460
- */
2461
- function firePickerChange(self) {
2462
- dispatchEvent(self.input, new CustomEvent('colorpicker.change'));
2463
- }
2464
-
2465
- /**
2466
- * Hides a visible dropdown.
2467
- * @param {HTMLElement} element
2468
- * @returns {void}
2469
- */
2470
- function removePosition(element) {
2471
- /* istanbul ignore else */
2472
- if (element) {
2473
- ['bottom', 'top'].forEach((x) => removeClass(element, x));
2474
- }
2475
- }
2476
-
2477
- /**
2478
- * Shows a `ColorPicker` dropdown and close the curent open dropdown.
2479
- * @param {ColorPicker} self
2480
- * @param {HTMLElement | Element} dropdown
2481
- */
2482
- function showDropdown(self, dropdown) {
2483
- const {
2484
- colorPicker, colorMenu, menuToggle, pickerToggle, parent,
2485
- } = self;
2486
- const isPicker = dropdown === colorPicker;
2487
- const openDropdown = isPicker ? colorMenu : colorPicker;
2488
- const activeBtn = isPicker ? menuToggle : pickerToggle;
2489
- const nextBtn = !isPicker ? menuToggle : pickerToggle;
2490
-
2491
- if (!hasClass(parent, 'open')) {
2492
- addClass(parent, 'open');
2493
- }
2494
- if (openDropdown) {
2495
- removeClass(openDropdown, 'show');
2496
- removePosition(openDropdown);
2497
- }
2498
- addClass(dropdown, 'bottom');
2499
- reflow(dropdown);
2500
- addClass(dropdown, 'show');
2501
-
2502
- if (isPicker) self.update();
2503
-
2504
- if (!self.isOpen) {
2505
- toggleEventsOnShown(self, true);
2506
- self.updateDropdownPosition();
2507
- self.isOpen = true;
2508
- setAttribute(self.input, tabIndex, '0');
2509
- if (menuToggle) {
2510
- setAttribute(menuToggle, tabIndex, '0');
2511
- }
2512
- }
2513
-
2514
- setAttribute(nextBtn, ariaExpanded, 'true');
2515
- if (activeBtn) {
2516
- setAttribute(activeBtn, ariaExpanded, 'false');
2517
- }
2518
- }
2519
-
2520
- /**
2521
- * Color Picker Web Component
2522
- * @see http://thednp.github.io/color-picker
2523
- */
2524
- class ColorPicker {
2525
- /**
2526
- * Returns a new `ColorPicker` instance. The target of this constructor
2527
- * must be an `HTMLInputElement`.
2528
- *
2529
- * @param {HTMLInputElement | string} target the target `<input>` element
2530
- * @param {CP.ColorPickerOptions=} config instance options
2531
- */
2532
- constructor(target, config) {
2533
- const self = this;
2534
- /** @type {HTMLInputElement} */
2535
- // @ts-ignore
2536
- const input = querySelector(target);
2537
-
2538
- // invalidate
2539
- if (!input) throw new TypeError(`ColorPicker target "${target}" cannot be found.`);
2540
- self.input = input;
2541
-
2542
- const parent = closest(input, colorPickerParentSelector);
2543
- if (!parent) throw new TypeError('ColorPicker requires a specific markup to work.');
2544
-
2545
- /** @type {HTMLElement} */
2546
- // @ts-ignore
2547
- self.parent = parent;
2548
-
2549
- /** @type {number} */
2550
- self.id = getUID(input, colorPickerString);
2551
-
2552
- // set initial state
2553
- /** @type {HTMLElement?} */
2554
- self.dragElement = null;
2555
- /** @type {boolean} */
2556
- self.isOpen = false;
2557
- /** @type {Record<string, number>} */
2558
- self.controlPositions = {
2559
- c1x: 0, c1y: 0, c2y: 0, c3y: 0,
2560
- };
2561
- /** @type {Record<string, string>} */
2562
- self.colorLabels = {};
2563
- /** @type {string[]=} */
2564
- self.colorKeywords = undefined;
2565
- /** @type {(ColorPalette | string[])=} */
2566
- self.colorPresets = undefined;
2567
-
2568
- // process options
2569
- const {
2570
- format, componentLabels, colorLabels, colorKeywords, colorPresets,
2571
- } = normalizeOptions(this.isCE ? parent : input, colorPickerDefaults, config || {});
2572
-
2573
- let translatedColorLabels = colorNames;
2574
- /* istanbul ignore else */
2575
- if (colorLabels instanceof Array && colorLabels.length === 17) {
2576
- translatedColorLabels = colorLabels;
2577
- } else if (colorLabels && colorLabels.split(',').length === 17) {
2578
- translatedColorLabels = colorLabels.split(',');
2579
- }
2580
-
2581
- // expose colour labels to all methods
2582
- colorNames.forEach((c, i) => {
2583
- self.colorLabels[c] = translatedColorLabels[i].trim();
2584
- });
2585
-
2586
- // update and expose component labels
2587
- const tempComponentLabels = componentLabels && isValidJSON(componentLabels)
2588
- ? JSON.parse(componentLabels) : componentLabels;
2589
-
2590
- /** @type {Record<string, string>} */
2591
- self.componentLabels = ObjectAssign({ ...colorPickerLabels }, tempComponentLabels);
2592
-
2593
- /** @type {Color} */
2594
- self.color = new Color(input.value || '#fff', format);
2595
-
2596
- /** @type {CP.ColorFormats} */
2597
- self.format = format;
2598
-
2599
- // set colour defaults
2600
- if (colorKeywords instanceof Array && colorKeywords.length) {
2601
- self.colorKeywords = colorKeywords;
2602
- } else if (typeof colorKeywords === 'string' && colorKeywords.length) {
2603
- self.colorKeywords = colorKeywords.split(',').map((x) => x.trim());
2604
- }
2605
-
2606
- // set colour presets
2607
- if (colorPresets instanceof Array && colorPresets.length) {
2608
- self.colorPresets = colorPresets;
2609
- } else if (typeof colorPresets === 'string' && colorPresets.length) {
2610
- if (isValidJSON(colorPresets)) {
2611
- const { hue, hueSteps, lightSteps } = JSON.parse(colorPresets);
2612
- self.colorPresets = new ColorPalette(hue, hueSteps, lightSteps);
2613
- } else {
2614
- self.colorPresets = colorPresets.split(',').map((x) => x.trim());
2615
- }
2616
- }
2617
-
2618
- // bind events
2619
- self.showPicker = self.showPicker.bind(self);
2620
- self.togglePicker = self.togglePicker.bind(self);
2621
- self.toggleMenu = self.toggleMenu.bind(self);
2622
- self.menuClickHandler = self.menuClickHandler.bind(self);
2623
- self.menuKeyHandler = self.menuKeyHandler.bind(self);
2624
- self.pointerDown = self.pointerDown.bind(self);
2625
- self.pointerMove = self.pointerMove.bind(self);
2626
- self.pointerUp = self.pointerUp.bind(self);
2627
- self.update = self.update.bind(self);
2628
- self.handleScroll = self.handleScroll.bind(self);
2629
- self.handleFocusOut = self.handleFocusOut.bind(self);
2630
- self.changeHandler = self.changeHandler.bind(self);
2631
- self.handleDismiss = self.handleDismiss.bind(self);
2632
- self.handleKnobs = self.handleKnobs.bind(self);
2633
-
2634
- // generate markup
2635
- setMarkup(self);
2636
-
2637
- const [colorPicker, colorMenu] = getElementsByClassName('color-dropdown', parent);
2638
- // set main elements
2639
- /** @type {HTMLElement} */
2640
- // @ts-ignore
2641
- self.pickerToggle = querySelector('.picker-toggle', parent);
2642
- /** @type {HTMLElement} */
2643
- // @ts-ignore
2644
- self.menuToggle = querySelector('.menu-toggle', parent);
2645
- /** @type {HTMLElement} */
2646
- // @ts-ignore
2647
- self.colorPicker = colorPicker;
2648
- /** @type {HTMLElement} */
2649
- // @ts-ignore
2650
- self.colorMenu = colorMenu;
2651
- /** @type {HTMLInputElement[]} */
2652
- // @ts-ignore
2653
- self.inputs = [...getElementsByClassName('color-input', parent)];
2654
- const [controls] = getElementsByClassName('color-controls', parent);
2655
- self.controls = controls;
2656
- /** @type {(HTMLElement | Element)[]} */
2657
- self.controlKnobs = [...getElementsByClassName('knob', controls)];
2658
- /** @type {(HTMLElement)[]} */
2659
- // @ts-ignore
2660
- self.visuals = [...getElementsByClassName('visual-control', controls)];
2661
-
2662
- // update colour picker controls, inputs and visuals
2663
- self.update();
2664
-
2665
- // add main events listeners
2666
- toggleEvents(self, true);
2667
-
2668
- // set component data
2669
- Data.set(input, colorPickerString, self);
2670
- }
2671
-
2672
- /** Returns the current colour value */
2673
- get value() { return this.input.value; }
2674
-
2675
- /**
2676
- * Sets a new colour value.
2677
- * @param {string} v new colour value
2678
- */
2679
- set value(v) { this.input.value = v; }
2680
-
2681
- /** Check if the colour presets include any non-colour. */
2682
- get hasNonColor() {
2683
- return this.colorKeywords instanceof Array
2684
- && this.colorKeywords.some((x) => nonColors.includes(x));
2685
- }
2686
-
2687
- /** Check if the parent of the target is a `ColorPickerElement` instance. */
2688
- get isCE() { return this.parent.localName === colorPickerString; }
2689
-
2690
- /** Returns hexadecimal value of the current colour. */
2691
- get hex() { return this.color.toHex(true); }
2692
-
2693
- /** Returns the current colour value in {h,s,v,a} object format. */
2694
- get hsv() { return this.color.toHsv(); }
2695
-
2696
- /** Returns the current colour value in {h,s,l,a} object format. */
2697
- get hsl() { return this.color.toHsl(); }
2698
-
2699
- /** Returns the current colour value in {h,w,b,a} object format. */
2700
- get hwb() { return this.color.toHwb(); }
2701
-
2702
- /** Returns the current colour value in {r,g,b,a} object format. */
2703
- get rgb() { return this.color.toRgb(); }
2704
-
2705
- /** Returns the current colour brightness. */
2706
- get brightness() { return this.color.brightness; }
2707
-
2708
- /** Returns the current colour luminance. */
2709
- get luminance() { return this.color.luminance; }
2710
-
2711
- /** Checks if the current colour requires a light text colour. */
2712
- get isDark() {
2713
- const { color, brightness } = this;
2714
- return brightness < 120 && color.a > 0.33;
2715
- }
2716
-
2717
- /** Checks if the current input value is a valid colour. */
2718
- get isValid() {
2719
- const inputValue = this.input.value;
2720
- return inputValue !== '' && new Color(inputValue).isValid;
2721
- }
2722
-
2723
- /** Returns the colour appearance, usually the closest colour name for the current value. */
2724
- get appearance() {
2725
- const {
2726
- colorLabels, hsl, hsv, format,
2727
- } = this;
2728
-
2729
- const hue = roundPart(hsl.h * 360);
2730
- const saturationSource = format === 'hsl' ? hsl.s : hsv.s;
2731
- const saturation = roundPart(saturationSource * 100);
2732
- const lightness = roundPart(hsl.l * 100);
2733
- const hsvl = hsv.v * 100;
2734
-
2735
- let colorName;
2736
-
2737
- // determine color appearance
2738
- /* istanbul ignore else */
2739
- if (lightness === 100 && saturation === 0) {
2740
- colorName = colorLabels.white;
2741
- } else if (lightness === 0) {
2742
- colorName = colorLabels.black;
2743
- } else if (saturation === 0) {
2744
- colorName = colorLabels.grey;
2745
- } else if (hue < 15 || hue >= 345) {
2746
- colorName = colorLabels.red;
2747
- } else if (hue >= 15 && hue < 45) {
2748
- colorName = hsvl > 80 && saturation > 80 ? colorLabels.orange : colorLabels.brown;
2749
- } else if (hue >= 45 && hue < 75) {
2750
- const isGold = hue > 46 && hue < 54 && hsvl < 80 && saturation > 90;
2751
- const isOlive = hue >= 54 && hue < 75 && hsvl < 80;
2752
- colorName = isGold ? colorLabels.gold : colorLabels.yellow;
2753
- colorName = isOlive ? colorLabels.olive : colorName;
2754
- } else if (hue >= 75 && hue < 155) {
2755
- colorName = hsvl < 68 ? colorLabels.green : colorLabels.lime;
2756
- } else if (hue >= 155 && hue < 175) {
2757
- colorName = colorLabels.teal;
2758
- } else if (hue >= 175 && hue < 195) {
2759
- colorName = colorLabels.cyan;
2760
- } else if (hue >= 195 && hue < 255) {
2761
- colorName = colorLabels.blue;
2762
- } else if (hue >= 255 && hue < 270) {
2763
- colorName = colorLabels.violet;
2764
- } else if (hue >= 270 && hue < 295) {
2765
- colorName = colorLabels.magenta;
2766
- } else if (hue >= 295 && hue < 345) {
2767
- colorName = colorLabels.pink;
2768
- }
2769
- return colorName;
2770
- }
2771
-
2772
- /** Updates `ColorPicker` visuals. */
2773
- updateVisuals() {
2774
- const self = this;
2775
- const {
2776
- controlPositions, visuals,
2777
- } = self;
2778
- const [v1, v2, v3] = visuals;
2779
- const { offsetHeight } = v1;
2780
- const hue = controlPositions.c2y / offsetHeight;
2781
- const { r, g, b } = new Color({ h: hue, s: 1, l: 0.5 }).toRgb();
2782
- const whiteGrad = 'linear-gradient(rgb(255,255,255) 0%, rgb(255,255,255) 100%)';
2783
- const alpha = 1 - controlPositions.c3y / offsetHeight;
2784
- const roundA = roundPart((alpha * 100)) / 100;
2785
-
2786
- const fill = new Color({
2787
- h: hue, s: 1, l: 0.5, a: alpha,
2788
- }).toRgbString();
2789
- const hueGradient = `linear-gradient(
2790
- rgb(255,0,0) 0%, rgb(255,255,0) 16.67%,
2791
- rgb(0,255,0) 33.33%, rgb(0,255,255) 50%,
2792
- rgb(0,0,255) 66.67%, rgb(255,0,255) 83.33%,
2793
- rgb(255,0,0) 100%)`;
2794
- setElementStyle(v1, {
2795
- background: `linear-gradient(rgba(0,0,0,0) 0%, rgba(0,0,0,${roundA}) 100%),
2796
- linear-gradient(to right, rgba(255,255,255,${roundA}) 0%, ${fill} 100%),
2797
- ${whiteGrad}`,
2798
- });
2799
- setElementStyle(v2, { background: hueGradient });
2800
-
2801
- setElementStyle(v3, {
2802
- background: `linear-gradient(rgba(${r},${g},${b},1) 0%,rgba(${r},${g},${b},0) 100%)`,
2803
- });
2804
- }
2805
-
2806
- /**
2807
- * The `ColorPicker` *focusout* event listener when open.
2808
- * @param {FocusEvent} e
2809
- * @this {ColorPicker}
2810
- */
2811
- handleFocusOut({ relatedTarget }) {
2812
- // @ts-ignore
2813
- if (relatedTarget && !this.parent.contains(relatedTarget)) {
2814
- this.hide(true);
2815
- }
2816
- }
2817
-
2818
- /**
2819
- * The `ColorPicker` *keyup* event listener when open.
2820
- * @param {KeyboardEvent} e
2821
- * @this {ColorPicker}
2822
- */
2823
- handleDismiss({ code }) {
2824
- const self = this;
2825
- if (self.isOpen && code === keyEscape) {
2826
- self.hide();
2827
- }
2828
- }
2829
-
2830
- /**
2831
- * The `ColorPicker` *scroll* event listener when open.
2832
- * @param {Event} e
2833
- * @this {ColorPicker}
2834
- */
2835
- handleScroll(e) {
2836
- const self = this;
2837
- const { activeElement } = getDocument(self.input);
2838
-
2839
- self.updateDropdownPosition();
2840
-
2841
- /* istanbul ignore next */
2842
- if (([pointermoveEvent, touchmoveEvent].includes(e.type) && self.dragElement)
2843
- || (activeElement && self.controlKnobs.includes(activeElement))) {
2844
- e.stopPropagation();
2845
- e.preventDefault();
2846
- }
2847
- }
2848
-
2849
- /**
2850
- * The `ColorPicker` keyboard event listener for menu navigation.
2851
- * @param {KeyboardEvent} e
2852
- * @this {ColorPicker}
2853
- */
2854
- menuKeyHandler(e) {
2855
- const { target, code } = e;
2856
- // @ts-ignore
2857
- const { previousElementSibling, nextElementSibling, parentElement } = target;
2858
- const isColorOptionsMenu = parentElement && hasClass(parentElement, 'color-options');
2859
- const allSiblings = [...parentElement.children];
2860
- const columnsCount = isColorOptionsMenu
2861
- && getElementStyle(parentElement, 'grid-template-columns').split(' ').length;
2862
- const currentIndex = allSiblings.indexOf(target);
2863
- const previousElement = currentIndex > -1
2864
- && columnsCount && allSiblings[currentIndex - columnsCount];
2865
- const nextElement = currentIndex > -1
2866
- && columnsCount && allSiblings[currentIndex + columnsCount];
2867
-
2868
- if ([keyArrowDown, keyArrowUp, keySpace].includes(code)) {
2869
- // prevent scroll when navigating the menu via arrow keys / Space
2870
- e.preventDefault();
2871
- }
2872
- if (isColorOptionsMenu) {
2873
- if (previousElement && code === keyArrowUp) {
2874
- focus(previousElement);
2875
- } else if (nextElement && code === keyArrowDown) {
2876
- focus(nextElement);
2877
- } else if (previousElementSibling && code === keyArrowLeft) {
2878
- focus(previousElementSibling);
2879
- } else if (nextElementSibling && code === keyArrowRight) {
2880
- focus(nextElementSibling);
2881
- }
2882
- } else if (previousElementSibling && [keyArrowLeft, keyArrowUp].includes(code)) {
2883
- focus(previousElementSibling);
2884
- } else if (nextElementSibling && [keyArrowRight, keyArrowDown].includes(code)) {
2885
- focus(nextElementSibling);
2886
- }
2887
-
2888
- if ([keyEnter, keySpace].includes(code)) {
2889
- this.menuClickHandler({ target });
2890
- }
2891
- }
2892
-
2893
- /**
2894
- * The `ColorPicker` click event listener for the colour menu presets / defaults.
2895
- * @param {Partial<Event>} e
2896
- * @this {ColorPicker}
2897
- */
2898
- menuClickHandler(e) {
2899
- const self = this;
2900
- /** @type {*} */
2901
- const { target } = e;
2902
- const { colorMenu } = self;
2903
- const newOption = (getAttribute(target, 'data-value') || '').trim();
2904
- // invalidate for targets other than color options
2905
- if (!newOption.length) return;
2906
- const currentActive = querySelector('li.active', colorMenu);
2907
- let newColor = nonColors.includes(newOption) ? 'white' : newOption;
2908
- newColor = newOption === 'transparent' ? 'rgba(0,0,0,0)' : newOption;
2909
-
2910
- const {
2911
- r, g, b, a,
2912
- } = new Color(newColor);
2913
-
2914
- ObjectAssign(self.color, {
2915
- r, g, b, a,
2916
- });
2917
-
2918
- self.update();
2919
-
2920
- /* istanbul ignore else */
2921
- if (currentActive !== target) {
2922
- /* istanbul ignore else */
2923
- if (currentActive) {
2924
- removeClass(currentActive, 'active');
2925
- removeAttribute(currentActive, ariaSelected);
2926
- }
2927
-
2928
- addClass(target, 'active');
2929
- setAttribute(target, ariaSelected, 'true');
2930
-
2931
- if (nonColors.includes(newOption)) {
2932
- self.value = newOption;
2933
- }
2934
- firePickerChange(self);
2935
- }
2936
- }
2937
-
2938
- /**
2939
- * The `ColorPicker` *touchstart* / *mousedown* events listener for control knobs.
2940
- * @param {PointerEvent} e
2941
- * @this {ColorPicker}
2942
- */
2943
- pointerDown(e) {
2944
- const self = this;
2945
- /** @type {*} */
2946
- const { target, pageX, pageY } = e;
2947
- const { colorMenu, visuals, controlKnobs } = self;
2948
- const [v1, v2, v3] = visuals;
2949
- const [c1, c2, c3] = controlKnobs;
2950
- /** @type {HTMLElement} */
2951
- const visual = controlKnobs.includes(target) ? target.previousElementSibling : target;
2952
- const visualRect = getBoundingClientRect(visual);
2953
- const html = getDocumentElement(v1);
2954
- const offsetX = pageX - html.scrollLeft - visualRect.left;
2955
- const offsetY = pageY - html.scrollTop - visualRect.top;
2956
-
2957
- /* istanbul ignore else */
2958
- if (target === v1 || target === c1) {
2959
- self.dragElement = visual;
2960
- self.changeControl1(offsetX, offsetY);
2961
- } else if (target === v2 || target === c2) {
2962
- self.dragElement = visual;
2963
- self.changeControl2(offsetY);
2964
- } else if (target === v3 || target === c3) {
2965
- self.dragElement = visual;
2966
- self.changeAlpha(offsetY);
2967
- }
2968
-
2969
- if (colorMenu) {
2970
- const currentActive = querySelector('li.active', colorMenu);
2971
- if (currentActive) {
2972
- removeClass(currentActive, 'active');
2973
- removeAttribute(currentActive, ariaSelected);
2974
- }
2975
- }
2976
- e.preventDefault();
2977
- }
2978
-
2979
- /**
2980
- * The `ColorPicker` *touchend* / *mouseup* events listener for control knobs.
2981
- * @param {PointerEvent} e
2982
- * @this {ColorPicker}
2983
- */
2984
- pointerUp({ target }) {
2985
- const self = this;
2986
- const { parent } = self;
2987
- const doc = getDocument(parent);
2988
- const currentOpen = querySelector(`${colorPickerParentSelector}.open`, doc) !== null;
2989
- const selection = doc.getSelection();
2990
-
2991
- if (!self.dragElement && !selection.toString().length
2992
- && !parent.contains(target)) {
2993
- self.hide(currentOpen);
2994
- }
2995
-
2996
- self.dragElement = null;
2997
- }
2998
-
2999
- /**
3000
- * The `ColorPicker` *touchmove* / *mousemove* events listener for control knobs.
3001
- * @param {PointerEvent} e
3002
- */
3003
- pointerMove(e) {
3004
- const self = this;
3005
- const { dragElement, visuals } = self;
3006
- const [v1, v2, v3] = visuals;
3007
- const { pageX, pageY } = e;
3008
-
3009
- if (!dragElement) return;
3010
-
3011
- const controlRect = getBoundingClientRect(dragElement);
3012
- const win = getDocumentElement(v1);
3013
- const offsetX = pageX - win.scrollLeft - controlRect.left;
3014
- const offsetY = pageY - win.scrollTop - controlRect.top;
3015
-
3016
- if (dragElement === v1) {
3017
- self.changeControl1(offsetX, offsetY);
3018
- }
3019
-
3020
- if (dragElement === v2) {
3021
- self.changeControl2(offsetY);
3022
- }
3023
-
3024
- if (dragElement === v3) {
3025
- self.changeAlpha(offsetY);
3026
- }
3027
- }
3028
-
3029
- /**
3030
- * The `ColorPicker` *keydown* event listener for control knobs.
3031
- * @param {KeyboardEvent} e
3032
- */
3033
- handleKnobs(e) {
3034
- const { target, code } = e;
3035
- const self = this;
3036
-
3037
- // only react to arrow buttons
3038
- if (![keyArrowUp, keyArrowDown, keyArrowLeft, keyArrowRight].includes(code)) return;
3039
- e.preventDefault();
3040
-
3041
- const { controlKnobs, visuals } = self;
3042
- const { offsetWidth, offsetHeight } = visuals[0];
3043
- const [c1, c2, c3] = controlKnobs;
3044
- const { activeElement } = getDocument(c1);
3045
- const currentKnob = controlKnobs.find((x) => x === activeElement);
3046
- const yRatio = offsetHeight / 360;
3047
-
3048
- /* istanbul ignore else */
3049
- if (currentKnob) {
3050
- let offsetX = 0;
3051
- let offsetY = 0;
3052
-
3053
- /* istanbul ignore else */
3054
- if (target === c1) {
3055
- const xRatio = offsetWidth / 100;
3056
-
3057
- /* istanbul ignore else */
3058
- if ([keyArrowLeft, keyArrowRight].includes(code)) {
3059
- self.controlPositions.c1x += code === keyArrowRight ? xRatio : -xRatio;
3060
- } else if ([keyArrowUp, keyArrowDown].includes(code)) {
3061
- self.controlPositions.c1y += code === keyArrowDown ? yRatio : -yRatio;
3062
- }
3063
-
3064
- offsetX = self.controlPositions.c1x;
3065
- offsetY = self.controlPositions.c1y;
3066
- self.changeControl1(offsetX, offsetY);
3067
- } else if (target === c2) {
3068
- self.controlPositions.c2y += [keyArrowDown, keyArrowRight].includes(code)
3069
- ? yRatio
3070
- : -yRatio;
3071
-
3072
- offsetY = self.controlPositions.c2y;
3073
- self.changeControl2(offsetY);
3074
- } else if (target === c3) {
3075
- self.controlPositions.c3y += [keyArrowDown, keyArrowRight].includes(code)
3076
- ? yRatio
3077
- : -yRatio;
3078
-
3079
- offsetY = self.controlPositions.c3y;
3080
- self.changeAlpha(offsetY);
3081
- }
3082
- self.handleScroll(e);
3083
- }
3084
- }
3085
-
3086
- /** The event listener of the colour form inputs. */
3087
- changeHandler() {
3088
- const self = this;
3089
- let colorSource;
3090
- const {
3091
- inputs, format, value: currentValue, input, controlPositions, visuals,
3092
- } = self;
3093
- /** @type {*} */
3094
- const { activeElement } = getDocument(input);
3095
- const { offsetHeight } = visuals[0];
3096
- const [i1,,, i4] = inputs;
3097
- const [v1, v2, v3, v4] = format === 'rgb'
3098
- ? inputs.map((i) => parseFloat(i.value) / (i === i4 ? 100 : 1))
3099
- : inputs.map((i) => parseFloat(i.value) / (i !== i1 ? 100 : 360));
3100
- const isNonColorValue = self.hasNonColor && nonColors.includes(currentValue);
3101
- const alpha = i4 ? v4 : (1 - controlPositions.c3y / offsetHeight);
3102
-
3103
- /* istanbul ignore else */
3104
- if (activeElement === input || (activeElement && inputs.includes(activeElement))) {
3105
- if (activeElement === input) {
3106
- if (isNonColorValue) {
3107
- colorSource = currentValue === 'transparent' ? 'rgba(0,0,0,0)' : 'rgb(0,0,0)';
3108
- } else {
3109
- colorSource = currentValue;
3110
- }
3111
- } else if (format === 'hex') {
3112
- colorSource = i1.value;
3113
- } else if (format === 'hsl') {
3114
- colorSource = {
3115
- h: v1, s: v2, l: v3, a: alpha,
3116
- };
3117
- } else if (format === 'hwb') {
3118
- colorSource = {
3119
- h: v1, w: v2, b: v3, a: alpha,
3120
- };
3121
- } else {
3122
- colorSource = {
3123
- r: v1, g: v2, b: v3, a: alpha,
3124
- };
3125
- }
3126
-
3127
- const {
3128
- r, g, b, a,
3129
- } = new Color(colorSource);
3130
-
3131
- ObjectAssign(self.color, {
3132
- r, g, b, a,
3133
- });
3134
- self.setControlPositions();
3135
- self.updateAppearance();
3136
- self.updateInputs();
3137
- self.updateControls();
3138
- self.updateVisuals();
3139
-
3140
- // set non-color keyword
3141
- if (activeElement === input && isNonColorValue) {
3142
- self.value = currentValue;
3143
- }
3144
- }
3145
- }
3146
-
3147
- /**
3148
- * Updates `ColorPicker` first control:
3149
- * * `lightness` and `saturation` for HEX/RGB;
3150
- * * `lightness` and `hue` for HSL.
3151
- *
3152
- * @param {number} X the X component of the offset
3153
- * @param {number} Y the Y component of the offset
3154
- */
3155
- changeControl1(X, Y) {
3156
- const self = this;
3157
- let [offsetX, offsetY] = [0, 0];
3158
- const { controlPositions, visuals } = self;
3159
- const { offsetHeight, offsetWidth } = visuals[0];
3160
-
3161
- if (X > offsetWidth) offsetX = offsetWidth;
3162
- else if (X >= 0) offsetX = X;
3163
-
3164
- if (Y > offsetHeight) offsetY = offsetHeight;
3165
- else if (Y >= 0) offsetY = Y;
3166
-
3167
- const hue = controlPositions.c2y / offsetHeight;
3168
-
3169
- const saturation = offsetX / offsetWidth;
3170
-
3171
- const lightness = 1 - offsetY / offsetHeight;
3172
- const alpha = 1 - controlPositions.c3y / offsetHeight;
3173
-
3174
- // new color
3175
- const {
3176
- r, g, b, a,
3177
- } = new Color({
3178
- h: hue, s: saturation, v: lightness, a: alpha,
3179
- });
3180
-
3181
- ObjectAssign(self.color, {
3182
- r, g, b, a,
3183
- });
3184
-
3185
- // new positions
3186
- self.controlPositions.c1x = offsetX;
3187
- self.controlPositions.c1y = offsetY;
3188
-
3189
- // update color picker
3190
- self.updateAppearance();
3191
- self.updateInputs();
3192
- self.updateControls();
3193
- self.updateVisuals();
3194
- }
3195
-
3196
- /**
3197
- * Updates `ColorPicker` second control:
3198
- * * `hue` for HEX/RGB/HWB;
3199
- * * `saturation` for HSL.
3200
- *
3201
- * @param {number} Y the Y offset
3202
- */
3203
- changeControl2(Y) {
3204
- const self = this;
3205
- const {
3206
- controlPositions, visuals,
3207
- } = self;
3208
- const { offsetHeight, offsetWidth } = visuals[0];
3209
-
3210
- let offsetY = 0;
3211
-
3212
- if (Y > offsetHeight) offsetY = offsetHeight;
3213
- else if (Y >= 0) offsetY = Y;
3214
-
3215
- const hue = offsetY / offsetHeight;
3216
- const saturation = controlPositions.c1x / offsetWidth;
3217
- const lightness = 1 - controlPositions.c1y / offsetHeight;
3218
- const alpha = 1 - controlPositions.c3y / offsetHeight;
3219
-
3220
- // new color
3221
- const {
3222
- r, g, b, a,
3223
- } = new Color({
3224
- h: hue, s: saturation, v: lightness, a: alpha,
3225
- });
3226
-
3227
- ObjectAssign(self.color, {
3228
- r, g, b, a,
3229
- });
3230
-
3231
- // new position
3232
- self.controlPositions.c2y = offsetY;
3233
- // update color picker
3234
- self.updateAppearance();
3235
- self.updateInputs();
3236
- self.updateControls();
3237
- self.updateVisuals();
3238
- }
3239
-
3240
- /**
3241
- * Updates `ColorPicker` last control,
3242
- * the `alpha` channel.
3243
- *
3244
- * @param {number} Y
3245
- */
3246
- changeAlpha(Y) {
3247
- const self = this;
3248
- const { visuals } = self;
3249
- const { offsetHeight } = visuals[0];
3250
- let offsetY = 0;
3251
-
3252
- if (Y > offsetHeight) offsetY = offsetHeight;
3253
- else if (Y >= 0) offsetY = Y;
3254
-
3255
- // update color alpha
3256
- const alpha = 1 - offsetY / offsetHeight;
3257
- self.color.setAlpha(alpha);
3258
- // update position
3259
- self.controlPositions.c3y = offsetY;
3260
- // update color picker
3261
- self.updateAppearance();
3262
- self.updateInputs();
3263
- self.updateControls();
3264
- self.updateVisuals();
3265
- }
3266
-
3267
- /**
3268
- * Updates `ColorPicker` control positions on:
3269
- * * initialization
3270
- * * window resize
3271
- */
3272
- update() {
3273
- const self = this;
3274
- self.updateDropdownPosition();
3275
- self.updateAppearance();
3276
- self.setControlPositions();
3277
- self.updateInputs(true);
3278
- self.updateControls();
3279
- self.updateVisuals();
3280
- }
3281
-
3282
- /** Updates the open dropdown position on *scroll* event. */
3283
- updateDropdownPosition() {
3284
- const self = this;
3285
- const { input, colorPicker, colorMenu } = self;
3286
- const elRect = getBoundingClientRect(input);
3287
- const { top, bottom } = elRect;
3288
- const { offsetHeight: elHeight } = input;
3289
- const windowHeight = getDocumentElement(input).clientHeight;
3290
- const isPicker = hasClass(colorPicker, 'show');
3291
- const dropdown = isPicker ? colorPicker : colorMenu;
3292
- if (!dropdown) return;
3293
- const { offsetHeight: dropHeight } = dropdown;
3294
- const distanceBottom = windowHeight - bottom;
3295
- const distanceTop = top;
3296
- const bottomExceed = top + dropHeight + elHeight > windowHeight; // show
3297
- const topExceed = top - dropHeight < 0; // show-top
3298
-
3299
- if ((hasClass(dropdown, 'bottom') || !topExceed) && distanceBottom < distanceTop && bottomExceed) {
3300
- removeClass(dropdown, 'bottom');
3301
- addClass(dropdown, 'top');
3302
- } else {
3303
- removeClass(dropdown, 'top');
3304
- addClass(dropdown, 'bottom');
3305
- }
3306
- }
3307
-
3308
- /** Updates control knobs' positions. */
3309
- setControlPositions() {
3310
- const self = this;
3311
- const {
3312
- visuals, color, hsv,
3313
- } = self;
3314
- const { offsetHeight, offsetWidth } = visuals[0];
3315
- const alpha = color.a;
3316
- const hue = hsv.h;
3317
-
3318
- const saturation = hsv.s;
3319
- const lightness = hsv.v;
3320
-
3321
- self.controlPositions.c1x = saturation * offsetWidth;
3322
- self.controlPositions.c1y = (1 - lightness) * offsetHeight;
3323
- self.controlPositions.c2y = hue * offsetHeight;
3324
- self.controlPositions.c3y = (1 - alpha) * offsetHeight;
3325
- }
3326
-
3327
- /** Update the visual appearance label and control knob labels. */
3328
- updateAppearance() {
3329
- const self = this;
3330
- const {
3331
- componentLabels, color, parent,
3332
- hsv, hex, format, controlKnobs,
3333
- } = self;
3334
- const {
3335
- appearanceLabel, hexLabel, valueLabel,
3336
- } = componentLabels;
3337
- let { r, g, b } = color.toRgb();
3338
- const [knob1, knob2, knob3] = controlKnobs;
3339
- const hue = roundPart(hsv.h * 360);
3340
- const alpha = color.a;
3341
- const saturation = roundPart(hsv.s * 100);
3342
- const lightness = roundPart(hsv.v * 100);
3343
- const colorName = self.appearance;
3344
-
3345
- let colorLabel = `${hexLabel} ${hex.split('').join(' ')}`;
3346
-
3347
- if (format === 'hwb') {
3348
- const { hwb } = self;
3349
- const whiteness = roundPart(hwb.w * 100);
3350
- const blackness = roundPart(hwb.b * 100);
3351
- colorLabel = `HWB: ${hue}°, ${whiteness}%, ${blackness}%`;
3352
- setAttribute(knob1, ariaValueText, `${whiteness}% & ${blackness}%`);
3353
- setAttribute(knob1, ariaValueNow, `${whiteness}`);
3354
- setAttribute(knob2, ariaDescription, `${valueLabel}: ${colorLabel}. ${appearanceLabel}: ${colorName}.`);
3355
- setAttribute(knob2, ariaValueText, `${hue}%`);
3356
- setAttribute(knob2, ariaValueNow, `${hue}`);
3357
- } else {
3358
- [r, g, b] = [r, g, b].map(roundPart);
3359
- colorLabel = format === 'hsl' ? `HSL: ${hue}°, ${saturation}%, ${lightness}%` : colorLabel;
3360
- colorLabel = format === 'rgb' ? `RGB: ${r}, ${g}, ${b}` : colorLabel;
3361
-
3362
- setAttribute(knob1, ariaValueText, `${lightness}% & ${saturation}%`);
3363
- setAttribute(knob1, ariaValueNow, `${lightness}`);
3364
- setAttribute(knob2, ariaDescription, `${valueLabel}: ${colorLabel}. ${appearanceLabel}: ${colorName}.`);
3365
- setAttribute(knob2, ariaValueText, `${hue}°`);
3366
- setAttribute(knob2, ariaValueNow, `${hue}`);
3367
- }
3368
-
3369
- const alphaValue = roundPart(alpha * 100);
3370
- setAttribute(knob3, ariaValueText, `${alphaValue}%`);
3371
- setAttribute(knob3, ariaValueNow, `${alphaValue}`);
3372
-
3373
- // update the input backgroundColor
3374
- const newColor = color.toString();
3375
- setElementStyle(self.input, { backgroundColor: newColor });
3376
-
3377
- // toggle dark/light classes will also style the placeholder
3378
- // dark sets color white, light sets color black
3379
- // isDark ? '#000' : '#fff'
3380
- if (!self.isDark) {
3381
- if (hasClass(parent, 'txt-dark')) removeClass(parent, 'txt-dark');
3382
- if (!hasClass(parent, 'txt-light')) addClass(parent, 'txt-light');
3383
- } else {
3384
- if (hasClass(parent, 'txt-light')) removeClass(parent, 'txt-light');
3385
- if (!hasClass(parent, 'txt-dark')) addClass(parent, 'txt-dark');
3386
- }
3387
- }
3388
-
3389
- /** Updates the control knobs actual positions. */
3390
- updateControls() {
3391
- const { controlKnobs, controlPositions } = this;
3392
- let {
3393
- c1x, c1y, c2y, c3y,
3394
- } = controlPositions;
3395
- const [control1, control2, control3] = controlKnobs;
3396
- // round control positions
3397
- [c1x, c1y, c2y, c3y] = [c1x, c1y, c2y, c3y].map(roundPart);
3398
-
3399
- setElementStyle(control1, { transform: `translate3d(${c1x - 4}px,${c1y - 4}px,0)` });
3400
- setElementStyle(control2, { transform: `translate3d(0,${c2y - 4}px,0)` });
3401
- setElementStyle(control3, { transform: `translate3d(0,${c3y - 4}px,0)` });
3402
- }
3403
-
3404
- /**
3405
- * Updates all color form inputs.
3406
- * @param {boolean=} isPrevented when `true`, the component original event is prevented
3407
- */
3408
- updateInputs(isPrevented) {
3409
- const self = this;
3410
- const {
3411
- value: oldColor, format, inputs, color, hsl,
3412
- } = self;
3413
- const [i1, i2, i3, i4] = inputs;
3414
- const alpha = roundPart(color.a * 100);
3415
- const hue = roundPart(hsl.h * 360);
3416
- let newColor;
3417
-
3418
- /* istanbul ignore else */
3419
- if (format === 'hex') {
3420
- newColor = self.color.toHexString(true);
3421
- i1.value = self.hex;
3422
- } else if (format === 'hsl') {
3423
- const lightness = roundPart(hsl.l * 100);
3424
- const saturation = roundPart(hsl.s * 100);
3425
- newColor = self.color.toHslString();
3426
- i1.value = `${hue}`;
3427
- i2.value = `${saturation}`;
3428
- i3.value = `${lightness}`;
3429
- i4.value = `${alpha}`;
3430
- } else if (format === 'hwb') {
3431
- const { w, b } = self.hwb;
3432
- const whiteness = roundPart(w * 100);
3433
- const blackness = roundPart(b * 100);
3434
-
3435
- newColor = self.color.toHwbString();
3436
- i1.value = `${hue}`;
3437
- i2.value = `${whiteness}`;
3438
- i3.value = `${blackness}`;
3439
- i4.value = `${alpha}`;
3440
- } else if (format === 'rgb') {
3441
- let { r, g, b } = self.rgb;
3442
- [r, g, b] = [r, g, b].map(roundPart);
3443
-
3444
- newColor = self.color.toRgbString();
3445
- i1.value = `${r}`;
3446
- i2.value = `${g}`;
3447
- i3.value = `${b}`;
3448
- i4.value = `${alpha}`;
3449
- }
3450
-
3451
- // update the color value
3452
- self.value = `${newColor}`;
3453
-
3454
- // don't trigger the custom event unless it's really changed
3455
- if (!isPrevented && newColor !== oldColor) {
3456
- firePickerChange(self);
3457
- }
3458
- }
3459
-
3460
- /**
3461
- * Toggle the `ColorPicker` dropdown visibility.
3462
- * @param {Event=} e
3463
- * @this {ColorPicker}
3464
- */
3465
- togglePicker(e) {
3466
- if (e) e.preventDefault();
3467
- const self = this;
3468
- const { colorPicker } = self;
3469
-
3470
- if (self.isOpen && hasClass(colorPicker, 'show')) {
3471
- self.hide(true);
3472
- } else {
3473
- showDropdown(self, colorPicker);
3474
- }
3475
- }
3476
-
3477
- /** Shows the `ColorPicker` dropdown. */
3478
- showPicker() {
3479
- const self = this;
3480
- const { colorPicker } = self;
3481
-
3482
- if (!['top', 'bottom'].some((c) => hasClass(colorPicker, c))) {
3483
- showDropdown(self, colorPicker);
3484
- }
3485
- }
3486
-
3487
- /**
3488
- * Toggles the visibility of the `ColorPicker` presets menu.
3489
- * @param {Event=} e
3490
- * @this {ColorPicker}
3491
- */
3492
- toggleMenu(e) {
3493
- if (e) e.preventDefault();
3494
- const self = this;
3495
- const { colorMenu } = self;
3496
-
3497
- if (self.isOpen && hasClass(colorMenu, 'show')) {
3498
- self.hide(true);
3499
- } else {
3500
- showDropdown(self, colorMenu);
3501
- }
3502
- }
3503
-
3504
- /**
3505
- * Hides the currently open `ColorPicker` dropdown.
3506
- * @param {boolean=} focusPrevented
3507
- */
3508
- hide(focusPrevented) {
3509
- const self = this;
3510
- if (self.isOpen) {
3511
- const {
3512
- pickerToggle, menuToggle, colorPicker, colorMenu, parent, input,
3513
- } = self;
3514
- const openPicker = hasClass(colorPicker, 'show');
3515
- const openDropdown = openPicker ? colorPicker : colorMenu;
3516
- const relatedBtn = openPicker ? pickerToggle : menuToggle;
3517
- const animationDuration = openDropdown && getElementTransitionDuration(openDropdown);
3518
-
3519
- self.value = self.color.toString(true);
3520
-
3521
- /* istanbul ignore else */
3522
- if (openDropdown) {
3523
- removeClass(openDropdown, 'show');
3524
- setAttribute(relatedBtn, ariaExpanded, 'false');
3525
- setTimeout(() => {
3526
- removePosition(openDropdown);
3527
- /* istanbul ignore else */
3528
- if (!querySelector('.show', parent)) {
3529
- removeClass(parent, 'open');
3530
- toggleEventsOnShown(self);
3531
- self.isOpen = false;
3532
- }
3533
- }, animationDuration);
3534
- }
3535
-
3536
- if (!focusPrevented) {
3537
- focus(pickerToggle);
3538
- }
3539
- setAttribute(input, tabIndex, '-1');
3540
- if (relatedBtn === menuToggle) {
3541
- setAttribute(menuToggle, tabIndex, '-1');
3542
- }
3543
- }
3544
- }
3545
-
3546
- /** Removes `ColorPicker` from target `<input>`. */
3547
- dispose() {
3548
- const self = this;
3549
- const { input, parent } = self;
3550
- self.hide(true);
3551
- toggleEvents(self);
3552
- [...parent.children].forEach((el) => {
3553
- if (el !== input) el.remove();
3554
- });
3555
-
3556
- removeAttribute(input, tabIndex);
3557
- setElementStyle(input, { backgroundColor: '' });
3558
-
3559
- ['txt-light', 'txt-dark'].forEach((c) => removeClass(parent, c));
3560
- Data.remove(input, colorPickerString);
3561
- }
3562
- }
3563
-
3564
- ObjectAssign(ColorPicker, {
3565
- Color,
3566
- ColorPalette,
3567
- Version,
3568
- getInstance: getColorPickerInstance,
3569
- init: initColorPicker,
3570
- selector: colorPickerSelector,
3571
- // utils important for render
3572
- roundPart,
3573
- setElementStyle,
3574
- setAttribute,
3575
- getBoundingClientRect,
3576
- });
3577
-
3578
- /**
3579
- * A small utility to toggle `ColorPickerElement` attributes
3580
- * when `connectedCallback` or `disconnectedCallback` methods
3581
- * are called and helps the instance keep its value and settings instact.
3582
- *
3583
- * @param {CP.ColorPickerElement} self ColorPickerElement instance
3584
- * @param {Function=} callback when `true`, attributes are added
3585
- *
3586
- * @example
3587
- * const attributes = [
3588
- * // essentials
3589
- * 'value', 'format',
3590
- * // presets menus
3591
- * 'color-presets', 'color-keywords',
3592
- * // labels
3593
- * 'color-labels', 'component-labels',
3594
- * ];
3595
- */
3596
- function toggleCEAttr(self, callback) {
3597
- if (callback) {
3598
- const { input, colorPicker } = self;
3599
-
3600
- const {
3601
- value, format, colorPresets, colorKeywords, componentLabels, colorLabels,
3602
- } = colorPicker;
3603
-
3604
- const { id, placeholder } = input;
3605
-
3606
- setAttribute(self, 'data-id', id);
3607
- setAttribute(self, 'data-value', value);
3608
- setAttribute(self, 'data-format', format);
3609
- setAttribute(self, 'data-placeholder', placeholder);
3610
-
3611
- if (ObjectKeys(colorPickerLabels).some((l) => colorPickerLabels[l] !== componentLabels[l])) {
3612
- setAttribute(self, 'data-component-labels', JSON.stringify(componentLabels));
3613
- }
3614
- if (!colorNames.every((c) => c === colorLabels[c])) {
3615
- setAttribute(self, 'data-color-labels', colorNames.map((n) => colorLabels[n]).join(','));
3616
- }
3617
- if (colorPresets instanceof ColorPalette) {
3618
- const { hue, hueSteps, lightSteps } = colorPresets;
3619
- setAttribute(self, 'data-color-presets', JSON.stringify({ hue, hueSteps, lightSteps }));
3620
- }
3621
- if (Array.isArray(colorPresets) && colorPresets.length) {
3622
- setAttribute(self, 'data-color-presets', colorPresets.join(','));
3623
- }
3624
- if (colorKeywords) {
3625
- setAttribute(self, 'data-color-keywords', colorKeywords.join(','));
3626
- }
3627
- setTimeout(callback, 0);
3628
- } else {
3629
- // keep id
3630
- // removeAttribute(self, 'data-id');
3631
- removeAttribute(self, 'data-value');
3632
- removeAttribute(self, 'data-format');
3633
- removeAttribute(self, 'data-placeholder');
3634
- removeAttribute(self, 'data-component-labels');
3635
- removeAttribute(self, 'data-color-labels');
3636
- removeAttribute(self, 'data-color-presets');
3637
- removeAttribute(self, 'data-color-keywords');
3638
- }
3639
- }
3640
-
3641
- let CPID = 0;
3642
-
3643
- /**
3644
- * `ColorPickerElement` Web Component.
3645
- * @example
3646
- * <label for="UNIQUE_ID">Label</label>
3647
- * <color-picker data-id="UNIQUE_ID" data-value="red" data-format="hex">
3648
- * </color-picker>
3649
- * // or
3650
- * <label for="UNIQUE_ID">Label</label>
3651
- * <color-picker data-id="UNIQUE_ID" data-value="red" data-format="hex"></color-picker>
3652
- */
3653
- class ColorPickerElement extends HTMLElement {
3654
- constructor() {
3655
- super();
3656
- this.attachShadow({ mode: 'open' });
3657
- }
3658
-
3659
- /**
3660
- * Returns the current color value.
3661
- * @returns {string | undefined}
3662
- */
3663
- get value() { return this.input && this.input.value; }
3664
-
3665
- connectedCallback() {
3666
- const self = this;
3667
- if (self.input) return;
3668
-
3669
- let id = getAttribute(self, 'data-id');
3670
- const value = getAttribute(self, 'data-value') || '#fff';
3671
- const format = getAttribute(self, 'data-format') || 'rgb';
3672
- const placeholder = getAttribute(self, 'data-placeholder') || '';
3673
-
3674
- if (!id) {
3675
- id = `color-picker-${format}-${CPID}`;
3676
- CPID += 1;
3677
- }
3678
-
3679
- const input = createElement({
3680
- tagName: 'input',
3681
- type: 'text',
3682
- className: 'color-preview btn-appearance',
3683
- });
3684
-
3685
- setAttribute(input, 'id', id);
3686
- setAttribute(input, 'name', id);
3687
- setAttribute(input, 'autocomplete', 'off');
3688
- setAttribute(input, 'spellcheck', 'false');
3689
- setAttribute(input, 'value', value);
3690
- setAttribute(input, 'placeholder', placeholder);
3691
- self.append(input);
3692
-
3693
- /** @type {HTMLInputElement} */
3694
- // @ts-ignore - `HTMLInputElement` is `HTMLElement`
3695
- self.input = input;
3696
-
3697
- // @ts-ignore - `HTMLInputElement` is `HTMLElement`
3698
- self.colorPicker = new ColorPicker(input);
3699
-
3700
- // @ts-ignore - `shadowRoot` is defined in the constructor
3701
- self.shadowRoot.append(createElement('slot'));
3702
-
3703
- // remove Attributes
3704
- toggleCEAttr(self);
3705
- }
3706
-
3707
- /** @this {ColorPickerElement} */
3708
- disconnectedCallback() {
3709
- const self = this;
3710
- const { input, colorPicker, shadowRoot } = self;
3711
-
3712
- const callback = () => {
3713
- // remove markup
3714
- input.remove();
3715
- colorPicker.dispose();
3716
- shadowRoot.innerHTML = '';
3717
-
3718
- ObjectAssign(self, {
3719
- colorPicker: undefined,
3720
- input: undefined,
3721
- });
3722
- };
3723
-
3724
- // re-add Attributes
3725
- toggleCEAttr(self, callback);
3726
- }
3727
- }
3728
-
3729
- ObjectAssign(ColorPickerElement, {
3730
- Color,
3731
- ColorPicker,
3732
- ColorPalette, // @ts-ignore
3733
- getInstance: ColorPicker.getInstance,
3734
- Version,
3735
- });
3736
-
3737
- customElements.define('color-picker', ColorPickerElement);
3738
-
3739
- export { ColorPickerElement as default };