-
Notifications
You must be signed in to change notification settings - Fork 58
/
coloris.js
1269 lines (1083 loc) · 37.7 KB
/
coloris.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* Copyright (c) 2021 Momo Bassit.
* Licensed under the MIT License (MIT)
* https://github.com/mdbassit/Coloris
*/
((window, document, Math, undefined) => {
const ctx = document.createElement('canvas').getContext('2d');
const currentColor = { r: 0, g: 0, b: 0, h: 0, s: 0, v: 0, a: 1 };
let container, picker, colorArea, colorMarker, colorPreview, colorValue, clearButton, closeButton,
hueSlider, hueMarker, alphaSlider, alphaMarker, currentEl, currentFormat, oldColor, keyboardNav,
colorAreaDims = {};
// Default settings
const settings = {
el: '[data-coloris]',
parent: 'body',
theme: 'default',
themeMode: 'light',
rtl: false,
wrap: true,
margin: 2,
format: 'hex',
formatToggle : false,
swatches: [],
swatchesOnly: false,
alpha: true,
forceAlpha: false,
focusInput: true,
selectInput: false,
inline: false,
defaultColor: '#000000',
clearButton: false,
clearLabel: 'Clear',
closeButton: false,
closeLabel: 'Close',
onChange: () => undefined,
a11y: {
open: 'Open color picker',
close: 'Close color picker',
clear: 'Clear the selected color',
marker: 'Saturation: {s}. Brightness: {v}.',
hueSlider: 'Hue slider',
alphaSlider: 'Opacity slider',
input: 'Color value field',
format: 'Color format',
swatch: 'Color swatch',
instruction: 'Saturation and brightness selector. Use up, down, left and right arrow keys to select.'
}
};
// Virtual instances cache
const instances = {};
let currentInstanceId = '';
let defaultInstance = {};
let hasInstance = false;
/**
* Configure the color picker.
* @param {object} options Configuration options.
*/
function configure(options) {
if (typeof options !== 'object') {
return;
}
for (const key in options) {
switch (key) {
case 'el':
bindFields(options.el);
if (options.wrap !== false) {
wrapFields(options.el);
}
break;
case 'parent':
container = options.parent instanceof HTMLElement ? options.parent : document.querySelector(options.parent);
if (container) {
container.appendChild(picker);
settings.parent = options.parent;
// document.body is special
if (container === document.body) {
container = undefined;
}
}
break;
case 'themeMode':
settings.themeMode = options.themeMode;
if (options.themeMode === 'auto' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
settings.themeMode = 'dark';
}
// The lack of a break statement is intentional
case 'theme':
if (options.theme) {
settings.theme = options.theme;
}
// Set the theme and color scheme
picker.className = `clr-picker clr-${settings.theme} clr-${settings.themeMode}`;
// Update the color picker's position if inline mode is in use
if (settings.inline) {
updatePickerPosition();
}
break;
case 'rtl':
settings.rtl = !!options.rtl;
Array.from(document.getElementsByClassName('clr-field')).forEach(field => field.classList.toggle('clr-rtl', settings.rtl));
break;
case 'margin':
options.margin *= 1;
settings.margin = !isNaN(options.margin) ? options.margin : settings.margin;
break;
case 'wrap':
if (options.el && options.wrap) {
wrapFields(options.el);
}
break;
case 'formatToggle':
settings.formatToggle = !!options.formatToggle;
getEl('clr-format').style.display = settings.formatToggle ? 'block' : 'none';
if (settings.formatToggle) {
settings.format = 'auto';
}
break;
case 'swatches':
if (Array.isArray(options.swatches)) {
const swatchesContainer = getEl('clr-swatches');
const swatches = document.createElement('div');
// Clear current swatches
swatchesContainer.textContent = '';
// Build new swatches
options.swatches.forEach((swatch, i) => {
const button = document.createElement('button');
button.setAttribute('type', `button`);
button.setAttribute('id', `clr-swatch-${i}`);
button.setAttribute('aria-labelledby', `clr-swatch-label clr-swatch-${i}`);
button.style.color = swatch;
button.textContent = swatch;
swatches.appendChild(button);
});
// Append new swatches if any
if (options.swatches.length) {
swatchesContainer.appendChild(swatches);
}
settings.swatches = options.swatches.slice();
}
break;
case 'swatchesOnly':
settings.swatchesOnly = !!options.swatchesOnly;
picker.setAttribute('data-minimal', settings.swatchesOnly);
break;
case 'alpha':
settings.alpha = !!options.alpha;
picker.setAttribute('data-alpha', settings.alpha);
break;
case 'inline':
settings.inline = !!options.inline;
picker.setAttribute('data-inline', settings.inline);
if (settings.inline) {
const defaultColor = options.defaultColor || settings.defaultColor;
currentFormat = getColorFormatFromStr(defaultColor);
updatePickerPosition();
setColorFromStr(defaultColor);
}
break;
case 'clearButton':
// Backward compatibility
if (typeof options.clearButton === 'object') {
if (options.clearButton.label) {
settings.clearLabel = options.clearButton.label;
clearButton.innerHTML = settings.clearLabel;
}
options.clearButton = options.clearButton.show;
}
settings.clearButton = !!options.clearButton;
clearButton.style.display = settings.clearButton ? 'block' : 'none';
break;
case 'clearLabel':
settings.clearLabel = options.clearLabel;
clearButton.innerHTML = settings.clearLabel;
break;
case 'closeButton':
settings.closeButton = !!options.closeButton;
if (settings.closeButton) {
picker.insertBefore(closeButton, colorPreview);
} else {
colorPreview.appendChild(closeButton);
}
break;
case 'closeLabel':
settings.closeLabel = options.closeLabel;
closeButton.innerHTML = settings.closeLabel;
break;
case 'a11y':
const labels = options.a11y;
let update = false;
if (typeof labels === 'object') {
for (const label in labels) {
if (labels[label] && settings.a11y[label]) {
settings.a11y[label] = labels[label];
update = true;
}
}
}
if (update) {
const openLabel = getEl('clr-open-label');
const swatchLabel = getEl('clr-swatch-label');
openLabel.innerHTML = settings.a11y.open;
swatchLabel.innerHTML = settings.a11y.swatch;
closeButton.setAttribute('aria-label', settings.a11y.close);
clearButton.setAttribute('aria-label', settings.a11y.clear);
hueSlider.setAttribute('aria-label', settings.a11y.hueSlider);
alphaSlider.setAttribute('aria-label', settings.a11y.alphaSlider);
colorValue.setAttribute('aria-label', settings.a11y.input);
colorArea.setAttribute('aria-label', settings.a11y.instruction);
}
break;
default:
settings[key] = options[key];
}
}
}
/**
* Add or update a virtual instance.
* @param {String} selector The CSS selector of the elements to which the instance is attached.
* @param {Object} options Per-instance options to apply.
*/
function setVirtualInstance(selector, options) {
if (typeof selector === 'string' && typeof options === 'object') {
instances[selector] = options;
hasInstance = true;
}
}
/**
* Remove a virtual instance.
* @param {String} selector The CSS selector of the elements to which the instance is attached.
*/
function removeVirtualInstance(selector) {
delete instances[selector];
if (Object.keys(instances).length === 0) {
hasInstance = false;
if (selector === currentInstanceId) {
resetVirtualInstance();
}
}
}
/**
* Attach a virtual instance to an element if it matches a selector.
* @param {Object} element Target element that will receive a virtual instance if applicable.
*/
function attachVirtualInstance(element) {
if (hasInstance) {
// These options can only be set globally, not per instance
const unsupportedOptions = ['el', 'wrap', 'rtl', 'inline', 'defaultColor', 'a11y'];
for (let selector in instances) {
const options = instances[selector];
// If the element matches an instance's CSS selector
if (element.matches(selector)) {
currentInstanceId = selector;
defaultInstance = {};
// Delete unsupported options
unsupportedOptions.forEach(option => delete options[option]);
// Back up the default options so we can restore them later
for (let option in options) {
defaultInstance[option] = Array.isArray(settings[option]) ? settings[option].slice() : settings[option];
}
// Set the instance's options
configure(options);
break;
}
}
}
}
/**
* Revert any per-instance options that were previously applied.
*/
function resetVirtualInstance() {
if (Object.keys(defaultInstance).length > 0) {
configure(defaultInstance);
currentInstanceId = '';
defaultInstance = {};
}
}
/**
* Bind the color picker to input fields that match the selector.
* @param {(string|HTMLElement|HTMLElement[])} selector A CSS selector string, a DOM element or a list of DOM elements.
*/
function bindFields(selector) {
if (selector instanceof HTMLElement) {
selector = [selector];
}
if (Array.isArray(selector)) {
selector.forEach(field => {
addListener(field, 'click', openPicker);
addListener(field, 'input', updateColorPreview);
});
} else {
addListener(document, 'click', selector, openPicker);
addListener(document, 'input', selector, updateColorPreview);
}
}
/**
* Open the color picker.
* @param {object} event The event that opens the color picker.
*/
function openPicker(event) {
// Skip if inline mode is in use
if (settings.inline) {
return;
}
// Apply any per-instance options first
attachVirtualInstance(event.target);
currentEl = event.target;
oldColor = currentEl.value;
currentFormat = getColorFormatFromStr(oldColor);
picker.classList.add('clr-open');
updatePickerPosition();
setColorFromStr(oldColor);
if (settings.focusInput || settings.selectInput) {
colorValue.focus({ preventScroll: true });
colorValue.setSelectionRange(currentEl.selectionStart, currentEl.selectionEnd);
}
if (settings.selectInput) {
colorValue.select();
}
// Always focus the first element when using keyboard navigation
if (keyboardNav || settings.swatchesOnly) {
getFocusableElements().shift().focus();
}
// Trigger an "open" event
currentEl.dispatchEvent(new Event('open', { bubbles: true }));
}
/**
* Update the color picker's position and the color gradient's offset
*/
function updatePickerPosition() {
const parent = container;
const scrollY = window.scrollY;
const pickerWidth = picker.offsetWidth;
const pickerHeight = picker.offsetHeight;
const reposition = { left: false, top: false };
let parentStyle, parentMarginTop, parentBorderTop;
let offset = { x: 0, y: 0 };
if (parent) {
parentStyle = window.getComputedStyle(parent);
parentMarginTop = parseFloat(parentStyle.marginTop);
parentBorderTop = parseFloat(parentStyle.borderTopWidth);
offset = parent.getBoundingClientRect();
offset.y += parentBorderTop + scrollY;
}
if (!settings.inline) {
const coords = currentEl.getBoundingClientRect();
let left = coords.x;
let top = scrollY + coords.y + coords.height + settings.margin;
// If the color picker is inside a custom container
// set the position relative to it
if (parent) {
left -= offset.x;
top -= offset.y;
if (left + pickerWidth > parent.clientWidth) {
left += coords.width - pickerWidth;
reposition.left = true;
}
if (top + pickerHeight > parent.clientHeight - parentMarginTop) {
if (pickerHeight + settings.margin <= coords.top - (offset.y - scrollY)) {
top -= coords.height + pickerHeight + settings.margin * 2;
reposition.top = true;
}
}
top += parent.scrollTop;
// Otherwise set the position relative to the whole document
} else {
if (left + pickerWidth > document.documentElement.clientWidth) {
left += coords.width - pickerWidth;
reposition.left = true;
}
if (top + pickerHeight - scrollY > document.documentElement.clientHeight) {
if (pickerHeight + settings.margin <= coords.top) {
top = scrollY + coords.y - pickerHeight - settings.margin;
reposition.top = true;
}
}
}
picker.classList.toggle('clr-left', reposition.left);
picker.classList.toggle('clr-top', reposition.top);
picker.style.left = `${left}px`;
picker.style.top = `${top}px`;
offset.x += picker.offsetLeft;
offset.y += picker.offsetTop;
}
colorAreaDims = {
width: colorArea.offsetWidth,
height: colorArea.offsetHeight,
x: colorArea.offsetLeft + offset.x,
y: colorArea.offsetTop + offset.y
};
}
/**
* Wrap the linked input fields in a div that adds a color preview.
* @param {(string|HTMLElement|HTMLElement[])} selector A CSS selector string, a DOM element or a list of DOM elements.
*/
function wrapFields(selector) {
if (selector instanceof HTMLElement) {
wrapColorField(selector);
} else if (Array.isArray(selector)) {
selector.forEach(wrapColorField);
} else {
document.querySelectorAll(selector).forEach(wrapColorField);
}
}
/**
* Wrap an input field in a div that adds a color preview.
* @param {object} field The input field.
*/
function wrapColorField(field) {
const parentNode = field.parentNode;
if (!parentNode.classList.contains('clr-field')) {
const wrapper = document.createElement('div');
let classes = 'clr-field';
if (settings.rtl || field.classList.contains('clr-rtl')) {
classes += ' clr-rtl';
}
wrapper.innerHTML = '<button type="button" aria-labelledby="clr-open-label"></button>';
parentNode.insertBefore(wrapper, field);
wrapper.className = classes;
wrapper.style.color = field.value;
wrapper.appendChild(field);
}
}
/**
* Update the color preview of an input field
* @param {object} event The "input" event that triggers the color change.
*/
function updateColorPreview(event) {
const parent = event.target.parentNode;
// Only update the preview if the field has been previously wrapped
if (parent.classList.contains('clr-field')) {
parent.style.color = event.target.value;
}
}
/**
* Close the color picker.
* @param {boolean} [revert] If true, revert the color to the original value.
*/
function closePicker(revert) {
if (currentEl && !settings.inline) {
const prevEl = currentEl;
// Revert the color to the original value if needed
if (revert) {
// This will prevent the "change" event on the colorValue input to execute its handler
currentEl = undefined;
if (oldColor !== prevEl.value) {
prevEl.value = oldColor;
// Trigger an "input" event to force update the thumbnail next to the input field
prevEl.dispatchEvent(new Event('input', { bubbles: true }));
}
}
// Trigger a "change" event if needed
setTimeout(() => { // Add this to the end of the event loop
if (oldColor !== prevEl.value) {
prevEl.dispatchEvent(new Event('change', { bubbles: true }));
}
});
// Hide the picker dialog
picker.classList.remove('clr-open');
// Reset any previously set per-instance options
if (hasInstance) {
resetVirtualInstance();
}
// Trigger a "close" event
prevEl.dispatchEvent(new Event('close', { bubbles: true }));
if (settings.focusInput) {
prevEl.focus({ preventScroll: true });
}
// This essentially marks the picker as closed
currentEl = undefined;
}
}
/**
* Set the active color from a string.
* @param {string} str String representing a color.
*/
function setColorFromStr(str) {
const rgba = strToRGBA(str);
const hsva = RGBAtoHSVA(rgba);
updateMarkerA11yLabel(hsva.s, hsva.v);
updateColor(rgba, hsva);
// Update the UI
hueSlider.value = hsva.h;
picker.style.color = `hsl(${hsva.h}, 100%, 50%)`;
hueMarker.style.left = `${hsva.h / 360 * 100}%`;
colorMarker.style.left = `${colorAreaDims.width * hsva.s / 100}px`;
colorMarker.style.top = `${colorAreaDims.height - (colorAreaDims.height * hsva.v / 100)}px`;
alphaSlider.value = hsva.a * 100;
alphaMarker.style.left = `${hsva.a * 100}%`;
}
/**
* Guess the color format from a string.
* @param {string} str String representing a color.
* @return {string} The color format.
*/
function getColorFormatFromStr(str) {
const format = str.substring(0, 3).toLowerCase();
if (format === 'rgb' || format === 'hsl' ) {
return format;
}
return 'hex';
}
/**
* Copy the active color to the linked input field.
* @param {number} [color] Color value to override the active color.
*/
function pickColor(color) {
color = color !== undefined ? color : colorValue.value;
if (currentEl) {
currentEl.value = color;
currentEl.dispatchEvent(new Event('input', { bubbles: true }));
}
if (settings.onChange) {
settings.onChange.call(window, color, currentEl);
}
document.dispatchEvent(new CustomEvent('coloris:pick', { detail: { color, currentEl } }));
}
/**
* Set the active color based on a specific point in the color gradient.
* @param {number} x Left position.
* @param {number} y Top position.
*/
function setColorAtPosition(x, y) {
const hsva = {
h: hueSlider.value * 1,
s: x / colorAreaDims.width * 100,
v: 100 - (y / colorAreaDims.height * 100),
a: alphaSlider.value / 100
};
const rgba = HSVAtoRGBA(hsva);
updateMarkerA11yLabel(hsva.s, hsva.v);
updateColor(rgba, hsva);
pickColor();
}
/**
* Update the color marker's accessibility label.
* @param {number} saturation
* @param {number} value
*/
function updateMarkerA11yLabel(saturation, value) {
let label = settings.a11y.marker;
saturation = saturation.toFixed(1) * 1;
value = value.toFixed(1) * 1;
label = label.replace('{s}', saturation);
label = label.replace('{v}', value);
colorMarker.setAttribute('aria-label', label);
}
//
/**
* Get the pageX and pageY positions of the pointer.
* @param {object} event The MouseEvent or TouchEvent object.
* @return {object} The pageX and pageY positions.
*/
function getPointerPosition(event) {
return {
pageX: event.changedTouches ? event.changedTouches[0].pageX : event.pageX,
pageY: event.changedTouches ? event.changedTouches[0].pageY : event.pageY
};
}
/**
* Move the color marker when dragged.
* @param {object} event The MouseEvent object.
*/
function moveMarker(event) {
const pointer = getPointerPosition(event);
let x = pointer.pageX - colorAreaDims.x;
let y = pointer.pageY - colorAreaDims.y;
if (container) {
y += container.scrollTop;
}
setMarkerPosition(x, y);
// Prevent scrolling while dragging the marker
event.preventDefault();
event.stopPropagation();
}
/**
* Move the color marker when the arrow keys are pressed.
* @param {number} offsetX The horizontal amount to move.
* @param {number} offsetY The vertical amount to move.
*/
function moveMarkerOnKeydown(offsetX, offsetY) {
let x = colorMarker.style.left.replace('px', '') * 1 + offsetX;
let y = colorMarker.style.top.replace('px', '') * 1 + offsetY;
setMarkerPosition(x, y);
}
/**
* Set the color marker's position.
* @param {number} x Left position.
* @param {number} y Top position.
*/
function setMarkerPosition(x, y) {
// Make sure the marker doesn't go out of bounds
x = (x < 0) ? 0 : (x > colorAreaDims.width) ? colorAreaDims.width : x;
y = (y < 0) ? 0 : (y > colorAreaDims.height) ? colorAreaDims.height : y;
// Set the position
colorMarker.style.left = `${x}px`;
colorMarker.style.top = `${y}px`;
// Update the color
setColorAtPosition(x, y);
// Make sure the marker is focused
colorMarker.focus();
}
/**
* Update the color picker's input field and preview thumb.
* @param {Object} rgba Red, green, blue and alpha values.
* @param {Object} [hsva] Hue, saturation, value and alpha values.
*/
function updateColor(rgba = {}, hsva = {}) {
let format = settings.format;
for (const key in rgba) {
currentColor[key] = rgba[key];
}
for (const key in hsva) {
currentColor[key] = hsva[key];
}
const hex = RGBAToHex(currentColor);
const opaqueHex = hex.substring(0, 7);
colorMarker.style.color = opaqueHex;
alphaMarker.parentNode.style.color = opaqueHex;
alphaMarker.style.color = hex;
colorPreview.style.color = hex;
// Force repaint the color and alpha gradients as a workaround for a Google Chrome bug
colorArea.style.display = 'none';
colorArea.offsetHeight;
colorArea.style.display = '';
alphaMarker.nextElementSibling.style.display = 'none';
alphaMarker.nextElementSibling.offsetHeight;
alphaMarker.nextElementSibling.style.display = '';
if (format === 'mixed') {
format = currentColor.a === 1 ? 'hex' : 'rgb';
} else if (format === 'auto') {
format = currentFormat;
}
switch (format) {
case 'hex':
colorValue.value = hex;
break;
case 'rgb':
colorValue.value = RGBAToStr(currentColor);
break;
case 'hsl':
colorValue.value = HSLAToStr(HSVAtoHSLA(currentColor));
break;
}
// Select the current format in the format switcher
document.querySelector(`.clr-format [value="${format}"]`).checked = true;
}
/**
* Set the hue when its slider is moved.
*/
function setHue() {
const hue = hueSlider.value * 1;
const x = colorMarker.style.left.replace('px', '') * 1;
const y = colorMarker.style.top.replace('px', '') * 1;
picker.style.color = `hsl(${hue}, 100%, 50%)`;
hueMarker.style.left = `${hue / 360 * 100}%`;
setColorAtPosition(x, y);
}
/**
* Set the alpha when its slider is moved.
*/
function setAlpha() {
const alpha = alphaSlider.value / 100;
alphaMarker.style.left = `${alpha * 100}%`;
updateColor({ a: alpha });
pickColor();
}
/**
* Convert HSVA to RGBA.
* @param {object} hsva Hue, saturation, value and alpha values.
* @return {object} Red, green, blue and alpha values.
*/
function HSVAtoRGBA(hsva) {
const saturation = hsva.s / 100;
const value = hsva.v / 100;
let chroma = saturation * value;
let hueBy60 = hsva.h / 60;
let x = chroma * (1 - Math.abs(hueBy60 % 2 - 1));
let m = value - chroma;
chroma = (chroma + m);
x = (x + m);
const index = Math.floor(hueBy60) % 6;
const red = [chroma, x, m, m, x, chroma][index];
const green = [x, chroma, chroma, x, m, m][index];
const blue = [m, m, x, chroma, chroma, x][index];
return {
r: Math.round(red * 255),
g: Math.round(green * 255),
b: Math.round(blue * 255),
a: hsva.a
};
}
/**
* Convert HSVA to HSLA.
* @param {object} hsva Hue, saturation, value and alpha values.
* @return {object} Hue, saturation, lightness and alpha values.
*/
function HSVAtoHSLA(hsva) {
const value = hsva.v / 100;
const lightness = value * (1 - (hsva.s / 100) / 2);
let saturation;
if (lightness > 0 && lightness < 1) {
saturation = Math.round((value - lightness) / Math.min(lightness, 1 - lightness) * 100);
}
return {
h: hsva.h,
s: saturation || 0,
l: Math.round(lightness * 100),
a: hsva.a
};
}
/**
* Convert RGBA to HSVA.
* @param {object} rgba Red, green, blue and alpha values.
* @return {object} Hue, saturation, value and alpha values.
*/
function RGBAtoHSVA(rgba) {
const red = rgba.r / 255;
const green = rgba.g / 255;
const blue = rgba.b / 255;
const xmax = Math.max(red, green, blue);
const xmin = Math.min(red, green, blue);
const chroma = xmax - xmin;
const value = xmax;
let hue = 0;
let saturation = 0;
if (chroma) {
if (xmax === red ) { hue = ((green - blue) / chroma); }
if (xmax === green ) { hue = 2 + (blue - red) / chroma; }
if (xmax === blue ) { hue = 4 + (red - green) / chroma; }
if (xmax) { saturation = chroma / xmax; }
}
hue = Math.floor(hue * 60);
return {
h: hue < 0 ? hue + 360 : hue,
s: Math.round(saturation * 100),
v: Math.round(value * 100),
a: rgba.a
};
}
/**
* Parse a string to RGBA.
* @param {string} str String representing a color.
* @return {object} Red, green, blue and alpha values.
*/
function strToRGBA(str) {
const regex = /^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i;
let match, rgba;
// Default to black for invalid color strings
ctx.fillStyle = '#000';
// Use canvas to convert the string to a valid color string
ctx.fillStyle = str;
match = regex.exec(ctx.fillStyle);
if (match) {
rgba = {
r: match[3] * 1,
g: match[4] * 1,
b: match[5] * 1,
a: match[6] * 1
};
} else {
match = ctx.fillStyle.replace('#', '').match(/.{2}/g).map(h => parseInt(h, 16));
rgba = {
r: match[0],
g: match[1],
b: match[2],
a: 1
};
}
return rgba;
}
/**
* Convert RGBA to Hex.
* @param {object} rgba Red, green, blue and alpha values.
* @return {string} Hex color string.
*/
function RGBAToHex(rgba) {
let R = rgba.r.toString(16);
let G = rgba.g.toString(16);
let B = rgba.b.toString(16);
let A = '';
if (rgba.r < 16) {
R = '0' + R;
}
if (rgba.g < 16) {
G = '0' + G;
}
if (rgba.b < 16) {
B = '0' + B;
}
if (settings.alpha && (rgba.a < 1 || settings.forceAlpha)) {
const alpha = rgba.a * 255 | 0;
A = alpha.toString(16);
if (alpha < 16) {
A = '0' + A;
}
}
return '#' + R + G + B + A;
}
/**
* Convert RGBA values to a CSS rgb/rgba string.
* @param {object} rgba Red, green, blue and alpha values.
* @return {string} CSS color string.
*/
function RGBAToStr(rgba) {
if (!settings.alpha || (rgba.a === 1 && !settings.forceAlpha)) {
return `rgb(${rgba.r}, ${rgba.g}, ${rgba.b})`;
} else {
return `rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${rgba.a})`;
}
}
/**
* Convert HSLA values to a CSS hsl/hsla string.
* @param {object} hsla Hue, saturation, lightness and alpha values.
* @return {string} CSS color string.
*/
function HSLAToStr(hsla) {
if (!settings.alpha || (hsla.a === 1 && !settings.forceAlpha)) {
return `hsl(${hsla.h}, ${hsla.s}%, ${hsla.l}%)`;
} else {
return `hsla(${hsla.h}, ${hsla.s}%, ${hsla.l}%, ${hsla.a})`;
}
}
/**
* Init the color picker.
*/
function init() {
// Render the UI
container = undefined;
picker = document.createElement('div');
picker.setAttribute('id', 'clr-picker');
picker.className = 'clr-picker';
picker.innerHTML =
`<input id="clr-color-value" name="clr-color-value" class="clr-color" type="text" value="" spellcheck="false" aria-label="${settings.a11y.input}">`+
`<div id="clr-color-area" class="clr-gradient" role="application" aria-label="${settings.a11y.instruction}">`+
'<div id="clr-color-marker" class="clr-marker" tabindex="0"></div>'+
'</div>'+
'<div class="clr-hue">'+
`<input id="clr-hue-slider" name="clr-hue-slider" type="range" min="0" max="360" step="1" aria-label="${settings.a11y.hueSlider}">`+
'<div id="clr-hue-marker"></div>'+
'</div>'+
'<div class="clr-alpha">'+
`<input id="clr-alpha-slider" name="clr-alpha-slider" type="range" min="0" max="100" step="1" aria-label="${settings.a11y.alphaSlider}">`+
'<div id="clr-alpha-marker"></div>'+
'<span></span>'+
'</div>'+
'<div id="clr-format" class="clr-format">'+
'<fieldset class="clr-segmented">'+
`<legend>${settings.a11y.format}</legend>`+
'<input id="clr-f1" type="radio" name="clr-format" value="hex">'+
'<label for="clr-f1">Hex</label>'+
'<input id="clr-f2" type="radio" name="clr-format" value="rgb">'+
'<label for="clr-f2">RGB</label>'+
'<input id="clr-f3" type="radio" name="clr-format" value="hsl">'+
'<label for="clr-f3">HSL</label>'+
'<span></span>'+
'</fieldset>'+
'</div>'+
'<div id="clr-swatches" class="clr-swatches"></div>'+
`<button type="button" id="clr-clear" class="clr-clear" aria-label="${settings.a11y.clear}">${settings.clearLabel}</button>`+