-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-color-picker.js
More file actions
305 lines (282 loc) · 11.3 KB
/
simple-color-picker.js
File metadata and controls
305 lines (282 loc) · 11.3 KB
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
/**
* simple-color-picker.js
* A compact, dependency-free web component that exposes a small color picker UI.
* - Shows a clickable swatch that opens the native <input type="color"> dialog
* - Provides a text input for arbitrary CSS color strings
* - Dispatches `input` when the native chooser changes, and `change` when the text input is applied
* - Exposes a `value` property and reflects the `value` attribute
*/
export class SimpleColorPicker extends HTMLElement {
static get observedAttributes() { return ['value']; }
constructor() {
super();
this._value = this.getAttribute('value') || '#ff0000';
this.attachShadow({ mode: 'open' });
// parse initial value into HSL components (fallback defaults)
const initialHsl = this._parseCssColorToHsl(this._value) || [0, 100, 50];
this._h = Math.round(initialHsl[0]);
this._s = Math.round(initialHsl[1]);
this._l = Math.round(initialHsl[2]);
this.shadowRoot.innerHTML = `
<style>
:host{display:block;font-family:system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial}
.container{display:flex;gap:1rem;align-items:center}
.controls{display:flex;flex-direction:column;gap:.5rem}
.control{display:flex;align-items:center;gap:.5rem}
.control label{width:32px;font-size:.9rem}
input[type='range']{
width:200px;
-webkit-appearance:none;
appearance:none;
height:8px;
border-radius:6px;
background:transparent;
--track: transparent;
--thumb-color: #ffffff;
}
input[type='range']::-webkit-slider-runnable-track {
height:8px;
border-radius:6px;
background: var(--track);
}
input[type='range']::-webkit-slider-thumb {
-webkit-appearance:none;
appearance:none;
width:16px;
height:16px;
border-radius:50%;
border:1px solid rgba(0,0,0,0.15);
background: var(--thumb-color);
margin-top: -4px;
}
input[type='range']::-moz-range-track {
height:8px;
border-radius:6px;
background: var(--track);
}
input[type='range']::-moz-range-thumb {
width:16px;
height:16px;
border-radius:50%;
border:1px solid rgba(0,0,0,0.15);
background: var(--thumb-color);
}
.swatch{width:48px;height:48px;border-radius:6px;border:1px solid #bdbdbd;flex:0 0 48px}
input[type='text']{font:inherit;padding:.25rem .5rem;border-radius:4px;border:1px solid #ccc}
</style>
<div class="container">
<div class="controls">
<div class="control"><label>H</label><input id="h" type="range" min="0" max="360" value="${this._h}"><input id="hVal" type="number" min="0" max="360" value="${this._h}" style="width:64px"></div>
<div class="control"><label>S</label><input id="s" type="range" min="0" max="100" value="${this._s}"><input id="sVal" type="number" min="0" max="100" value="${this._s}" style="width:64px"></div>
<div class="control"><label>L</label><input id="l" type="range" min="0" max="100" value="${this._l}"><input id="lVal" type="number" min="0" max="100" value="${this._l}" style="width:64px"></div>
</div>
<div class="swatch" id="swatch" title="Current color"></div>
</div>
`;
this._swatch = this.shadowRoot.getElementById('swatch');
this._hInput = this.shadowRoot.getElementById('h');
this._sInput = this.shadowRoot.getElementById('s');
this._lInput = this.shadowRoot.getElementById('l');
this._hVal = this.shadowRoot.getElementById('hVal');
this._sVal = this.shadowRoot.getElementById('sVal');
this._lVal = this.shadowRoot.getElementById('lVal');
// initialize UI values
this._applyHslToUI();
this._updateSwatch();
this._updateSliderBackgrounds();
// HSL updates are handled by instance methods _clamp and _setHsl
// wire slider inputs (live input -> input event; change -> commit)
const readHsl = () => [this._hInput.value, this._sInput.value, this._lInput.value];
this._hInput.addEventListener('input', () => this._setHsl(...readHsl(), false));
this._sInput.addEventListener('input', () => this._setHsl(...readHsl(), false));
this._lInput.addEventListener('input', () => this._setHsl(...readHsl(), false));
this._hInput.addEventListener('change', () => this._setHsl(...readHsl(), true));
this._sInput.addEventListener('change', () => this._setHsl(...readHsl(), true));
this._lInput.addEventListener('change', () => this._setHsl(...readHsl(), true));
// wire numeric inputs to update sliders and HSL
this._hVal.addEventListener('input', () => {
const v = this._clamp(this._hVal.value, 0, 360);
this._hInput.value = v;
this._setHsl(v, this._sInput.value, this._lInput.value, false);
});
this._sVal.addEventListener('input', () => {
const v = this._clamp(this._sVal.value, 0, 100);
this._sInput.value = v;
this._setHsl(this._hInput.value, v, this._lInput.value, false);
});
this._lVal.addEventListener('input', () => {
const v = this._clamp(this._lVal.value, 0, 100);
this._lInput.value = v;
this._setHsl(this._hInput.value, this._sInput.value, v, false);
});
this._hVal.addEventListener('change', () => {
const v = this._clamp(this._hVal.value, 0, 360);
this._hInput.value = v;
this._setHsl(v, this._sInput.value, this._lInput.value, true);
});
this._sVal.addEventListener('change', () => {
const v = this._clamp(this._sVal.value, 0, 100);
this._sInput.value = v;
this._setHsl(this._hInput.value, v, this._lInput.value, true);
});
this._lVal.addEventListener('change', () => {
const v = this._clamp(this._lVal.value, 0, 100);
this._lInput.value = v;
this._setHsl(this._hInput.value, this._sInput.value, v, true);
});
// No free-form text input in this simplified picker; user edits are via sliders and number inputs
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'value' && oldValue !== newValue) {
this._value = newValue || '';
// no text input to update
// if we can parse the new value into HSL, update sliders to reflect it
const parsed = this._parseCssColorToHsl(this._value);
if (parsed) {
this._h = Math.round(parsed[0]);
this._s = Math.round(parsed[1]);
this._l = Math.round(parsed[2]);
if (this._hInput) {
this._applyHslToUI();
}
}
this._updateSwatch();
}
}
get value() {
return this._value;
}
set value(v) {
const newVal = String(v);
this._value = newVal;
this.setAttribute('value', newVal);
// no text input to update
this._updateSwatch();
}
_updateSwatch() {
this._swatch.style.background = this._value || 'transparent';
}
// Update the slider backgrounds so they visually represent the color ranges
_updateSliderBackgrounds() {
const h = this._h, s = this._s, l = this._l;
// Hue: multi-stop gradient across hues, respecting current S/L
const hueStops = [0,60,120,180,240,300,360].map(d => `hsl(${d}, ${s}%, ${l}%)`).join(', ');
const currentCss = this._hslToCss(h, s, l);
this._hInput.style.setProperty('--thumb-color', currentCss);
this._hInput.style.setProperty('--track', `linear-gradient(to right, ${hueStops})`);
// Saturation: from desaturated to fully saturated for current H/L
this._sInput.style.setProperty('--thumb-color', currentCss);
this._sInput.style.setProperty('--track', `linear-gradient(to right, hsl(${h}, 0%, ${l}%), hsl(${h}, 100%, ${l}%))`);
// Lightness: from dark through mid to light for current H/S
this._lInput.style.setProperty('--thumb-color', currentCss);
this._lInput.style.setProperty('--track', `linear-gradient(to right, hsl(${h}, ${s}%, 0%), hsl(${h}, ${s}%, 50%), hsl(${h}, ${s}%, 100%))`);
}
// Convert HSL components into a CSS hsl() string
_hslToCss(h, s, l) {
return `hsl(${h}, ${s}%, ${l}%)`;
}
// Apply current _h/_s/_l values to UI elements
_applyHslToUI() {
this._hInput.value = this._h;
this._sInput.value = this._s;
this._lInput.value = this._l;
this._hVal.value = this._h;
this._sVal.value = this._s;
this._lVal.value = this._l;
// no text input to update
this._updateSliderBackgrounds();
}
// Parse an arbitrary CSS color string into [h, s, l] numbers (h:0-360, s/l:0-100)
_parseCssColorToHsl(str) {
if (!str) {
return null;
}
// Use canvas to normalize the color string without touching the DOM
const ctx = SimpleColorPicker._ctx || (SimpleColorPicker._ctx = document.createElement('canvas').getContext('2d'));
try {
ctx.fillStyle = str;
} catch (e) {
return null;
}
let computed = ctx.fillStyle; // could be '#rrggbb' or 'rgba(...)' or 'rgb(...)'
let r, g, b;
if (computed.startsWith('#')) {
const hex = computed.slice(1);
if (hex.length === 3) {
r = parseInt(hex[0]+hex[0],16);
g = parseInt(hex[1]+hex[1],16);
b = parseInt(hex[2]+hex[2],16);
} else {
r = parseInt(hex.slice(0,2),16);
g = parseInt(hex.slice(2,4),16);
b = parseInt(hex.slice(4,6),16);
}
} else {
const m = computed.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
if (!m) return null;
r = Number(m[1]); g = Number(m[2]); b = Number(m[3]);
}
return this._rgbToHsl(r, g, b);
}
// Convert rgb(0-255) to hsl([0-360, 0-100, 0-100])
_rgbToHsl(r, g, b) {
r /= 255; g /= 255; b /= 255;
const max = Math.max(r,g,b), min = Math.min(r,g,b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [Math.round(h * 360), Math.round(s * 100), Math.round(l * 100)];
}
// Programmatically focus the hue slider (no native picker in this implementation)
openNativePicker() {
if (this._hInput) {
this._hInput.focus();
}
}
// Helper to clamp numeric inputs to allowed ranges
_clamp(v, min, max) {
v = Number(v);
if (Number.isNaN(v)) {
return min;
}
v = Math.round(v);
if (v < min) {
return min;
}
if (v > max) {
return max;
}
return v;
}
// Set H/S/L programmatically; when commit=true the value attribute is updated and a 'change' event is emitted.
_setHsl(h, s, l, commit = false) {
this._h = this._clamp(h, 0, 360);
this._s = this._clamp(s, 0, 100);
this._l = this._clamp(l, 0, 100);
const css = this._hslToCss(this._h, this._s, this._l);
if (commit) {
this.value = css; // reflects attribute and updates UI
} else {
this._value = css;
this._applyHslToUI();
this._updateSwatch();
}
this._updateSliderBackgrounds();
this.dispatchEvent(new CustomEvent(commit ? 'change' : 'input', { detail: { value: this._value } }));
}
}
// Register the element if it hasn't been registered by another module
if (!customElements.get('simple-color-picker')) {
customElements.define('simple-color-picker', SimpleColorPicker);
}
export default SimpleColorPicker;