-
Notifications
You must be signed in to change notification settings - Fork 209
/
Copy pathColorSlider.ts
350 lines (305 loc) · 10.8 KB
/
ColorSlider.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
/*
Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
import {
CSSResultArray,
html,
PropertyValues,
TemplateResult,
} from '@spectrum-web-components/base';
import { ifDefined } from '@spectrum-web-components/base/src/directives.js';
import {
property,
query,
} from '@spectrum-web-components/base/src/decorators.js';
import { streamingListener } from '@spectrum-web-components/base/src/streaming-listener.js';
import { Focusable } from '@spectrum-web-components/shared/src/focusable.js';
import type { ColorHandle } from '@spectrum-web-components/color-handle';
import '@spectrum-web-components/color-handle/sp-color-handle.js';
import {
ColorController,
ColorValue,
HSL,
} from '@spectrum-web-components/reactive-controllers/src/Color.js';
import styles from './color-slider.css.js';
/**
* @element sp-color-slider
* @slot gradient - a custom gradient visually outlining the available color values
* @fires input - The value of the Color Slider has changed.
* @fires change - An alteration to the value of the Color Slider has been committed by the user.
*/
export class ColorSlider extends Focusable {
public static override get styles(): CSSResultArray {
return [styles];
}
@property({ type: Boolean, reflect: true })
public override disabled = false;
@property({ type: Boolean, reflect: true })
public focused = false;
@query('.handle')
private handle!: ColorHandle;
@property({ type: String })
public label = 'hue';
@property({ type: Boolean, reflect: true })
public vertical = false;
private colorController = new ColorController(this, {
/* c8 ignore next 3 */
applyColorToState: () => {
this.sliderHandlePosition = 100 * (this.colorController.hue / 360);
},
extractColorFromState: (controller) => ({
...(controller.getColor('hsl') as HSL),
h: this.value,
}),
maintains: 'saturation',
});
@property({ type: Number })
public get value(): number {
return this.colorController.hue;
}
public set value(hue: number) {
this.colorController.hue = hue;
}
@property({ type: Number, reflect: true })
public sliderHandlePosition = 0;
@property({ type: String })
public get color(): ColorValue {
return this.colorController.color;
}
public set color(color: ColorValue) {
this.colorController.color = color;
}
@property({ type: Number })
public step = 1;
private get altered(): number {
return this._altered;
}
private set altered(altered: number) {
this._altered = altered;
this.step = Math.max(1, this.altered * 10);
}
private _altered = 0;
@query('input')
public input!: HTMLInputElement;
public override get focusElement(): HTMLInputElement {
return this.input;
}
private handleKeydown(event: KeyboardEvent): void {
const { key } = event;
this.focused = true;
this.altered = [event.shiftKey, event.ctrlKey, event.altKey].filter(
(key) => !!key
).length;
let delta = 0;
switch (key) {
case 'ArrowUp':
delta = this.step;
break;
case 'ArrowDown':
delta = -this.step;
break;
case 'ArrowLeft':
delta = this.step * (this.isLTR ? -1 : 1);
break;
case 'ArrowRight':
delta = this.step * (this.isLTR ? 1 : -1);
break;
default:
return;
}
event.preventDefault();
this.sliderHandlePosition = Math.min(
100,
Math.max(0, this.sliderHandlePosition + delta)
);
this.value = 360 * (this.sliderHandlePosition / 100);
this.colorController.applyColorFromState();
if (delta != 0) {
this.dispatchEvent(
new Event('input', {
bubbles: true,
composed: true,
})
);
this.dispatchEvent(
new Event('change', {
bubbles: true,
composed: true,
})
);
}
}
private handleInput(event: Event & { target: HTMLInputElement }): void {
const { valueAsNumber } = event.target;
this.value = valueAsNumber;
this.sliderHandlePosition = 100 * (this.value / 360);
this.colorController.applyColorFromState();
}
private handleChange(event: Event & { target: HTMLInputElement }): void {
this.handleInput(event);
this.dispatchEvent(
new Event('change', {
bubbles: true,
composed: true,
})
);
}
public override focus(focusOptions: FocusOptions = {}): void {
super.focus(focusOptions);
this.forwardFocus();
}
private forwardFocus(): void {
this.focused = this.hasVisibleFocusInTree();
this.input.focus();
}
private handleFocusin(): void {
this.focused = true;
}
private handleFocusout(): void {
if (this._pointerDown) {
return;
}
this.altered = 0;
this.focused = false;
}
private boundingClientRect!: DOMRect;
private _pointerDown = false;
private handlePointerdown(event: PointerEvent): void {
if (event.button !== 0) {
event.preventDefault();
return;
}
this._pointerDown = true;
this.colorController.savePreviousColor();
this.boundingClientRect = this.getBoundingClientRect();
(event.target as HTMLElement).setPointerCapture(event.pointerId);
if (event.pointerType === 'mouse') {
this.focused = true;
}
}
private handlePointermove(event: PointerEvent): void {
this.sliderHandlePosition = this.calculateHandlePosition(event);
this.value = 360 * (this.sliderHandlePosition / 100);
this.colorController.applyColorFromState();
this.dispatchEvent(
new Event('input', {
bubbles: true,
composed: true,
cancelable: true,
})
);
}
private handlePointerup(event: PointerEvent): void {
this._pointerDown = false;
(event.target as HTMLElement).releasePointerCapture(event.pointerId);
const applyDefault = this.dispatchEvent(
new Event('change', {
bubbles: true,
composed: true,
cancelable: true,
})
);
if (!applyDefault) {
this.colorController.restorePreviousColor();
}
// Retain focus on input element after mouse up to enable keyboard interactions
this.focus();
if (event.pointerType === 'mouse') {
this.focused = false;
}
}
/**
* Returns the value under the cursor
* @param: PointerEvent on slider
* @return: Slider value that correlates to the position under the pointer
*/
private calculateHandlePosition(event: PointerEvent): number {
/* c8 ignore next 3 */
if (!this.boundingClientRect) {
return this.sliderHandlePosition;
}
const rect = this.boundingClientRect;
const minOffset = this.vertical ? rect.top : rect.left;
const offset = this.vertical ? event.clientY : event.clientX;
const size = this.vertical ? rect.height : rect.width;
const percent = Math.max(0, Math.min(1, (offset - minOffset) / size));
const sliderHandlePosition =
this.vertical || !this.isLTR ? 100 - 100 * percent : 100 * percent;
return sliderHandlePosition;
}
private handleGradientPointerdown(event: PointerEvent): void {
if (event.button !== 0) {
return;
}
event.stopPropagation();
event.preventDefault();
this.handle.dispatchEvent(new PointerEvent('pointerdown', event));
this.handlePointermove(event);
}
private get handlePositionStyles(): string {
return `${this.vertical ? 'inset-block-end' : 'inset-inline-start'}: ${
this.sliderHandlePosition
}%`;
}
protected override render(): TemplateResult {
return html`
<div
class="checkerboard"
role="presentation"
@pointerdown=${this.handleGradientPointerdown}
>
<div
class="gradient"
role="presentation"
style="background: linear-gradient(to ${this.vertical
? 'top'
: 'right'}, var(--sp-color-slider-gradient, var(--sp-color-slider-gradient-fallback)));"
>
<slot name="gradient"></slot>
</div>
</div>
<sp-color-handle
tabindex=${ifDefined(this.focused ? undefined : '0')}
@focus=${this.forwardFocus}
?focused=${this.focused}
class="handle"
color="hsl(${this.value}, 100%, 50%)"
?disabled=${this.disabled}
style=${this.handlePositionStyles}
${streamingListener({
start: ['pointerdown', this.handlePointerdown],
streamInside: ['pointermove', this.handlePointermove],
end: [
['pointerup', 'pointercancel', 'pointerleave'],
this.handlePointerup,
],
})}
></sp-color-handle>
<input
type="range"
class="slider"
min="0"
max="360"
step=${this.step}
aria-label=${this.label}
.value=${String(this.value)}
@input=${this.handleInput}
@change=${this.handleChange}
@keydown=${this.handleKeydown}
/>
`;
}
protected override firstUpdated(changed: PropertyValues): void {
super.firstUpdated(changed);
this.boundingClientRect = this.getBoundingClientRect();
this.addEventListener('focusin', this.handleFocusin);
this.addEventListener('focusout', this.handleFocusout);
}
}