-
Notifications
You must be signed in to change notification settings - Fork 37
/
uui-color-picker.element.ts
702 lines (614 loc) · 18.8 KB
/
uui-color-picker.element.ts
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
import { LitElement, html, css, nothing } from 'lit';
import { Colord, colord, extend, HslaColor } from 'colord';
import namesPlugin from 'colord/plugins/names';
extend([namesPlugin]);
import { defineElement } from '@umbraco-ui/uui-base/lib/registration';
import { property, query, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { live } from 'lit/directives/live.js';
import { clamp, demandCustomElement } from '@umbraco-ui/uui-base/lib/utils';
import { styleMap } from 'lit/directives/style-map.js';
import {
UUIColorAreaElement,
UUIColorAreaEvent,
} from '@umbraco-ui/uui-color-area/lib';
import {
UUIColorSliderElement,
UUIColorSliderEvent,
} from '@umbraco-ui/uui-color-slider/lib';
import {
UUIColorSwatchesElement,
UUIColorSwatchesEvent,
} from '@umbraco-ui/uui-color-swatches/lib';
import { UUIColorSwatchElement } from '@umbraco-ui/uui-color-swatch/lib';
import { UUIPopoverElement } from '@umbraco-ui/uui-popover/lib';
import { UUIInputElement } from '@umbraco-ui/uui-input/lib';
import { UUIColorPickerChangeEvent } from './UUIColorPickerEvent';
import { LabelMixin } from '@umbraco-ui/uui-base/lib/mixins';
const hasEyeDropper = 'EyeDropper' in window;
interface EyeDropperConstructor {
new (): EyeDropperInterface;
}
interface EyeDropperInterface {
open: () => Promise<{ sRGBHex: string }>;
}
export type UUIColorPickerFormat = 'hex' | 'rgb' | 'hsl';
export type UUIColorPickerFormatWithAlpha =
| UUIColorPickerFormat
| 'hexa'
| 'rgba'
| 'hsla';
declare const EyeDropper: EyeDropperConstructor;
type UUIColorPickerSize = 'small' | 'medium' | 'large';
/**
* @element uui-color-picker
* @cssprop --uui-color-picker-width - The width of the color picker
* @description
* @fires {UUIColorPickerChangeEvent} change - Fired when the color changes
*/
@defineElement('uui-color-picker')
export class UUIColorPickerElement extends LabelMixin('label', LitElement) {
static styles = [
css`
:host {
--uui-look-outline-border: #ddd;
--uui-look-outline-border-hover: #aaa;
font-size: 0.8rem;
display: block;
width: var(--uui-color-picker-width, 280px);
}
.color-picker {
width: 100%;
background-color: #fff;
user-select: none;
border: solid 1px #e4e4e7;
}
.color-picker__user-input {
display: flex;
padding: 0 0.75rem 0.75rem 0.75rem;
}
.color-picker__user-input uui-button {
border: var(--uui-input-border-width, 1px) solid
var(--uui-input-border-color, var(--uui-color-border));
border-left: none;
}
.color-picker__preview,
.color-picker__trigger {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
justify-content: center;
position: relative;
width: 2.25rem;
height: 2.25rem;
border: none;
border-radius: 50%;
background: none;
}
.color-picker__preview {
cursor: copy;
margin-left: 0.75rem;
border-radius: 50%;
}
.color-picker__trigger[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
.color-picker__preview::before,
.color-picker__trigger::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: inherit;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
/* We use a custom property in lieu of currentColor because of https://bugs.webkit.org/show_bug.cgi?id=216780 */
background-color: var(--preview-color);
}
.color-dropdown__trigger--empty::before {
background-color: transparent;
}
.color-picker__transparent-bg {
background-image: linear-gradient(
45deg,
var(--uui-palette-grey) 25%,
transparent 25%
),
linear-gradient(45deg, transparent 75%, var(--uui-palette-grey) 75%),
linear-gradient(45deg, transparent 75%, var(--uui-palette-grey) 75%),
linear-gradient(45deg, var(--uui-palette-grey) 25%, transparent 25%);
background-size: 10px 10px;
background-position: 0 0, 0 0, -5px -5px, 5px 5px;
}
.color-picker__preview-color--copied {
animation: pulse 0.75s;
}
@keyframes pulse {
0% {
box-shadow: 0 0 0 0 var(--uui-palette-space-cadet-light);
}
70% {
box-shadow: 0 0 0 0.5rem transparent;
}
100% {
box-shadow: 0 0 0 0 transparent;
}
}
.color-picker__controls {
padding: 0.75rem;
display: flex;
align-items: center;
}
.color-picker__sliders {
flex: 1 1 auto;
}
uui-color-slider:not(:last-of-type) {
margin-bottom: 1rem;
}
.color-picker__toggle-format {
min-width: 45px;
--uui-button-font-size: 0.8rem;
}
.color-picker__toggle-format > span {
text-transform: uppercase;
}
uui-color-swatches {
border-top: solid 1px #d4d4d8;
padding: 0.75rem;
}
button[slot='trigger'] {
border-radius: 50%;
cursor: pointer;
width: 36px;
height: 36px;
}
uui-popover {
display: block;
width: 100%;
margin: 5px 0;
}
uui-input {
/* lower the font size to avoid overflow with hlsa format */
font-size: 0.85rem;
box-sizing: content-box;
flex: 1;
}
uui-color-area {
width: 100%;
}
`,
];
@query('[part="input"]') _input!: UUIInputElement;
@query('.color-picker__preview') _previewButton!: HTMLButtonElement;
@query('#swatches') _swatches!: UUIColorSwatchesElement;
@state() private inputValue = '';
@state() private hue = 0;
@state() private saturation = 0;
@state() private lightness = 0;
@state() private alpha = 100;
@state() private _colord: Colord = colord('hsl(0, 0%, 0%)');
/**
* The current color.
* @attr
* @type {string}
* @default ''
**/
@property() value = '';
/**
* The format to use for the display value. If opacity is enabled, these will translate to HEXA, RGBA, and HSLA
* respectively. The color picker will always accept user input in any format (including CSS color names) and convert
* it to the desired format.
* @attr
* @type {UUIColorPickerFormat}
* @default 'hex'
*/
@property() format: UUIColorPickerFormat = 'hex';
/**
* The input's name attribute.
* @attr
* @type {string}
* @default ''
**/
@property() name = '';
/**
* Determines the size of the color picker's trigger. This has no effect on inline color pickers.
* @attr
* @type {UUIColorPickerSize}
* @default 'medium'
**/
@property() size: UUIColorPickerSize = 'medium';
/**
* Removes the format toggle.
* @attr
* @type {boolean}
* @default false
**/
@property({ attribute: 'no-format-toggle', type: Boolean }) noFormatToggle =
false;
/**
* Renders the color picker inline rather than inside a dropdown.
* @attr
* @type {boolean}
* @default false
**/
@property({ type: Boolean, reflect: true }) inline = false;
/**
* Disables the color picker.
* @attr
* @type {boolean}
* @default false
**/
@property({ type: Boolean, reflect: true }) disabled = false;
/**
* Whether to show the opacity slider.
* @attr
* @type {boolean}
* @default false
**/
@property({ type: Boolean }) opacity = false;
/**
* By default, the value will be set in lowercase. Set this to true to set it in uppercase instead.
* @attr
* @type {boolean}
* @default false
**/
@property({ type: Boolean }) uppercase = false;
/**
* An array of predefined color swatches to display. Can include any format the color picker can parse, including
* HEX(A), RGB(A), HSL(A), and CSS color names.
*/
@property({ attribute: false }) swatches: string[] = [
'#d0021b',
'#f5a623',
'#f8e71c',
'#8b572a',
'#7ed321',
'#417505',
'#bd10e0',
'#9013fe',
'#4a90e2',
'#50e3c2',
'#b8e986',
'#000',
'#444',
'#888',
'#ccc',
'#fff',
];
connectedCallback(): void {
super.connectedCallback();
if (this.value) {
this.setColor(this.value);
} else {
this.setColor('#000');
}
demandCustomElement(this, 'uui-icon');
demandCustomElement(this, 'uui-icon-registry-essential');
demandCustomElement(this, 'uui-input');
demandCustomElement(this, 'uui-button');
demandCustomElement(this, 'uui-button-group');
demandCustomElement(this, 'uui-popover');
demandCustomElement(this, 'uui-color-swatches');
demandCustomElement(this, 'uui-color-swatch');
demandCustomElement(this, 'uui-color-area');
demandCustomElement(this, 'uui-color-slider');
}
/** Returns the current value as a string in the specified format. */
getFormattedValue(format: UUIColorPickerFormat) {
const formatToUse = this.opacity ? `${format}a` : format;
const { h, l, s } = this._colord.toHsl();
const { r, g, b } = this._colord.toRgb();
const hexa = this.setLetterCase(this._colord.toHex());
const hex = this.setLetterCase(
hexa.length > 7 ? hexa.substring(0, hexa.length - 2) : hexa
);
switch (formatToUse) {
case 'hex':
return hex;
case 'hexa':
return hexa;
case 'rgb':
return `rgb(${r} ${g} ${b})`;
case 'rgba':
return this._colord.toRgbString();
case 'hsl':
return `hsl(${h} ${s} ${l})`;
case 'hsla':
return this._colord.toHslString();
default:
return '';
}
}
getBrightness(lightness: number) {
return clamp(-1 * ((200 * lightness) / (this.saturation - 200)), 0, 100);
}
getLightness(brightness: number) {
return clamp(
((((200 - this.saturation) * brightness) / 100) * 5) / 10,
0,
100
);
}
handleFormatToggle() {
const formats = ['hex', 'rgb', 'hsl'];
const nextIndex = (formats.indexOf(this.format) + 1) % formats.length;
this.format = formats[nextIndex] as 'hex' | 'rgb' | 'hsl';
this._syncValues();
}
handleAlphaChange(event: UUIColorSliderEvent) {
event.stopPropagation();
this._swatches?.resetSelection();
const element = event.target as UUIColorSliderElement;
const newColor: HslaColor = {
h: this.hue,
s: this.saturation,
l: this.lightness,
a: Math.round(element.value) / 100,
};
this.setColor(newColor);
}
handleHueChange(event: UUIColorSliderEvent) {
event.stopPropagation();
this._swatches?.resetSelection();
const element = event.target as UUIColorSliderElement;
const newColor: HslaColor = {
h: element.value,
s: this.saturation,
l: this.lightness,
a: this.alpha / 100,
};
this.setColor(newColor);
}
handleGridChange(event: UUIColorAreaEvent) {
event.stopPropagation();
this._swatches?.resetSelection();
const element = event.target as UUIColorAreaElement;
const newColor: HslaColor = {
h: this.hue,
s: element.saturation,
l: element.lightness,
a: this.alpha / 100,
};
this.setColor(newColor);
}
handleInputChange(event: CustomEvent) {
this._swatches?.resetSelection();
const target = event.target as HTMLInputElement;
if (target.value) {
this.setColor(target.value);
target.value = this.value;
} else {
this.setColor('#000');
}
event.stopPropagation();
}
handleInputKeyDown(event: KeyboardEvent) {
if (event.key === 'Enter') {
if (this.inputValue) {
this.setColor(this.inputValue);
this._swatches?.resetSelection();
this.inputValue = this.value;
setTimeout(() => this._input.select());
} else {
this.setColor('#000');
}
}
}
handleColorSwatchChange(event: UUIColorSwatchesEvent) {
event.stopImmediatePropagation();
const target = event.target as UUIColorSwatchElement;
if (target.value) {
this.setColor(target.value);
} else {
//reset to black
this.setColor('#000');
}
}
handleCopy() {
navigator.clipboard.writeText(this._input.value as string).then(() => {
// Show copied animation
this._previewButton.classList.add('color-picker__preview-color--copied');
this._previewButton.addEventListener('animationend', () => {
this._previewButton.classList.remove(
'color-picker__preview-color--copied'
);
});
});
}
openColorPicker(event: Event) {
event.stopImmediatePropagation();
const target = event.target as HTMLElement;
const popover = target.parentElement as UUIPopoverElement;
popover.open = !popover?.open;
target.setAttribute('aria-expanded', popover.open.toString());
}
closeColorPicker(event: Event) {
const target = event.target as UUIPopoverElement;
const trigger = target.querySelector("button[part=trigger]");
if (trigger) {
trigger.setAttribute('aria-expanded', 'false');
}
}
handleEyeDropper() {
if (!hasEyeDropper) {
return;
}
const eyeDropper = new EyeDropper();
eyeDropper
.open()
.then(result => this.setColor(result.sRGBHex))
.catch(() => {
// The user canceled, do nothing
});
}
setColor(colorString: string | HslaColor) {
this._colord = new Colord(colorString);
const { h, l, s, a } = this._colord.toHsl();
this.hue = h;
this.saturation = s;
this.lightness = l;
this.alpha = this.opacity ? a * 100 : 100;
this._syncValues();
this.dispatchEvent(
new UUIColorPickerChangeEvent(UUIColorPickerChangeEvent.CHANGE)
);
return true;
}
setLetterCase(string: string) {
if (typeof string !== 'string') {
return '';
}
return this.uppercase ? string.toUpperCase() : string.toLowerCase();
}
private _syncValues() {
this.inputValue = this.getFormattedValue(this.format);
this.value = this.inputValue;
}
private _renderColorPicker() {
return html`
<div
class=${classMap({
'color-picker': true,
'color-picker--inline': this.inline,
'color-picker--disabled': this.disabled,
})}
aria-disabled=${this.disabled ? 'true' : 'false'}>
<uui-color-area
.value="${this.value}"
?disabled=${this.disabled}
@change=${this.handleGridChange}>
</uui-color-area>
<div class="color-picker__controls">
<div class="color-picker__sliders">
<uui-color-slider
label="hue"
class="hue-slider"
.value=${Math.round(this.hue)}
?disabled=${this.disabled}
@change=${this.handleHueChange}>
</uui-color-slider>
${this.opacity
? html`
<uui-color-slider
label="alpha"
class="opacity-slider"
.value=${Math.round(this.alpha)}
type="opacity"
.color=${this.value}
?disabled=${this.disabled}
@change=${this.handleAlphaChange}>
</uui-color-slider>
`
: ''}
</div>
<button
type="button"
part="preview"
class="color-picker__preview color-picker__transparent-bg"
title="Copy"
aria-label="Copy"
style=${styleMap({
'--preview-color': `hsla(${this.hue}deg, ${this.saturation}%, ${
this.lightness
}%, ${this.alpha / 100})`,
})}
@click=${this.handleCopy}></button>
</div>
<div class="color-picker__user-input" aria-live="polite">
<uui-input
label="label"
type="text"
part="input"
name=${this.name}
autocomplete="off"
autocapitalize="off"
spellcheck="false"
.value=${live(this.inputValue)}
?disabled=${this.disabled}
@keydown=${this.handleInputKeyDown}
@change=${this.handleInputChange}>
</uui-input>
<uui-button-group>
${!this.noFormatToggle
? html`<uui-button
label="Toggle color format"
@click=${this.handleFormatToggle}
class="color-picker__toggle-format"
?disabled=${this.disabled}
compact>
<span>${this.format}</span>
</uui-button>`
: ''}
${hasEyeDropper
? html`<uui-button
label="Select a color"
?disabled=${this.disabled}
@click=${this.handleEyeDropper}
compact>
<uui-icon-registry-essential>
<uui-icon name="colorpicker"></uui-icon>
</uui-icon-registry-essential>
</uui-button>`
: ''}
</uui-button-group>
</div>
${this._renderSwatches()}
</div>
`;
}
private _renderSwatches() {
if (!this.swatches) return nothing;
return html`<uui-color-swatches
id="swatches"
class="color-picker__swatches"
?disabled=${this.disabled}
@change=${this.handleColorSwatchChange}>
${this.swatches.map(
swatch =>
html`<uui-color-swatch
label="${swatch}"
.value=${swatch}>
</uui-color-swatch>`
)}
</uui-color-swatches>`;
}
private _renderPreviewButton() {
return html`<uui-popover placement="bottom-start" @close=${this.closeColorPicker}>
<button
type="button"
part="trigger"
slot="trigger"
aria-label="${this.label || 'Open Color picker'}"
class=${classMap({
'color-picker__trigger': true,
'color-dropdown__trigger--disabled': this.disabled,
'color-dropdown__trigger--small': this.size === 'small',
'color-dropdown__trigger--medium': this.size === 'medium',
'color-dropdown__trigger--large': this.size === 'large',
'color-picker__transparent-bg': true,
})}
style=${styleMap({
'--preview-color': `hsla(${this.hue}deg, ${this.saturation}%, ${
this.lightness
}%, ${this.alpha / 100})`,
})}
?disabled=${this.disabled}
@click=${this.openColorPicker}
aria-haspopup="true"
aria-expanded="false"></button>
<div slot="popover">${this._renderColorPicker()}</div>
</uui-popover>`;
}
render() {
return this.inline
? this._renderColorPicker()
: this._renderPreviewButton();
}
}
declare global {
interface HTMLElementTagNameMap {
'uui-color-picker': UUIColorPickerElement;
}
}