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