-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcolorpicker.js
More file actions
859 lines (786 loc) · 27.2 KB
/
Copy pathcolorpicker.js
File metadata and controls
859 lines (786 loc) · 27.2 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
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
// ==================== Color picker plugin ====================
// Encoding: UTF-8 without BOM (auto-detect: °°°°°) for built-in message texts
const colorPickerClass = "ff-color-picker";
// "en" is the fallback and must be complete.
const dictionary = {
de: {
background: "Hintergrund",
foreground: "Vordergrund",
generic: "Allgemein",
details: "Details",
red: "Rot",
green: "Grün",
blue: "Blau",
hue: "Farbton",
saturation: "Sättigung",
lightness: "Helligkeit",
opacity: "Deckkraft",
preview: "Vorschau",
"select color": "Farbe auswählen",
accept: "Übernehmen",
"no color": "Keine Farbe",
cancel: "Abbrechen",
"separate dark": "Separate Farbe im dunklen Design verwenden",
},
en: {
background: "Background",
foreground: "Foreground",
generic: "Generic",
details: "Details",
red: "Red",
green: "Green",
blue: "Blue",
hue: "Hue",
saturation: "Saturation",
lightness: "Lightness",
opacity: "Opacity",
preview: "Preview",
"select color": "Select colour",
accept: "Accept",
"no color": "No colour",
cancel: "Cancel",
"separate dark": "Use separate colour for dark theme",
},
"en-ca": {
"select color": "Select color",
"no color": "No color",
"separate dark": "Use separate color for dark theme",
},
"en-us": {
"select color": "Select color",
"no color": "No color",
"separate dark": "Use separate color for dark theme",
},
};
// Defines default options for the color picker plugin.
let colorPickerDefaults = {
// The initially selected color.
color: undefined,
// The type of use for the color (foreground, background).
colorUse: undefined,
// Indicates whether the alpha channel is displayed and editable.
withAlpha: false,
// Indicates whether the preview panel shows the currently selected color in HTML hex notation.
previewHex: true,
// The language to use for text labels.
language: undefined
};
// Shows a color picker on the element.
function colorPicker(options) {
return this.forEach(container => {
if (!container) return; // Nothing to do
if (container.classList.contains(colorPickerClass)) return container.F.colorPicker; // Already created
let opt = F.initOptions("colorPicker", container, {}, options);
opt._setColor = setColor;
let isEmpty = !opt.color;
if (!isEmpty)
setColorInternal(opt.color);
else
opt.color = new Color();
let language = opt.language || document.documentElement.lang;
let translate = F.getTranslator(dictionary, language);
let detailsSliders = {};
let detailsInputs = {};
let alphaSlider;
let previewPanel, previewHex;
let updatingPreview;
let selectingDataColor;
let foundMatchInTab;
let quickUpdateCount = 0, quickUpdateTimeout;
let isInitialized;
container.classList.add(colorPickerClass);
container.style.width = "420px";
container.style.maxWidth = "100%";
let tabs = F.c("div");
tabs.classList.add("tabs", "same-height");
container.append(tabs);
let grid;
let dataPaletteTab;
switch (opt.colorUse) {
case "background":
case "foreground":
dataPaletteTab = F.c("div");
dataPaletteTab.title = translate(opt.colorUse);
tabs.append(dataPaletteTab);
let colorIds = DataColor.getColorIds();
grid = F.c("div");
grid.F.style = {
display: "grid",
gridTemplateColumns: "repeat(" + colorIds.length + ", 1fr)",
gridTemplateRows: "auto",
gridGap: "6px"
};
dataPaletteTab.append(grid);
let isDark = container.F.dark;
const colorTypes = opt.colorUse === "background" ? ["b0", "b1", "b2"] : ["f0", "f1", "f2"];
colorTypes.forEach(type => {
colorIds.forEach(colorId => {
const dataColor = DataColor.getColor(colorId, type, isDark);
const swatch = F.c("a");
swatch.classList.add("swatch");
swatch.dataset.colorId = colorId;
swatch.dataset.type = type;
swatch.F.style = {
height: "29px",
backgroundColor: dataColor,
outline: "solid 0px " + (Color(dataColor).gray().r < 100 ? "#eee" : "#000"),
outlineOffset: "-2px"
};
swatch.href = "#";
grid.append(swatch);
swatch.F.on("click", event => {
event.preventDefault();
const a = opt.color.a;
let dataColorWasNull = !opt.dataColor;
opt.color = new Color(swatch.style.backgroundColor);
opt.dataColor = colorId + "-" + type.substring(1, 2);
if (a) {
opt.color.a = a;
if (a !== 1)
opt.dataColor = null;
}
selectingDataColor = true;
updateView(undefined, undefined, dataColorWasNull);
selectingDataColor = false;
if (event.detail === 2) {
// Double-click: apply color picker
container.F.trigger("apply", { bubbles: true });
}
});
});
});
break;
}
let genericPaletteTab = F.c("div");
genericPaletteTab.title = translate("generic");
tabs.append(genericPaletteTab);
// Add grey tones explicitly
let colors = [0xffffff, 0xf0f0f0, 0xd0d0d0, 0xa0a0a0, 0x707070, 0x404040, 0x000000];
// Add colors with shades
[
0xff0000, // red
0xff8000, // orange
0xffc000, // orangeyellow
0xffe000, // gold
0xffff00, // yellow
0xc0ff00, // greenyellow
0x00ff00, // green
0x00ffc0, // greencyan
0x00ffff, // cyan
0x00c0ff, // bluecyan
0x0080ff, // lightblue
0x0000ff, // blue
0x8000ff, // purple
0xc000ff, // violet
0xff00ff // magenta
].forEach(baseColor => {
baseColor = new Color(baseColor);
[0.875, 0.75, 0.5].forEach(factor => colors.push(baseColor.blendWith(0xffffff, factor)));
colors.push(baseColor.toHTML());
[0.25, 0.5, 0.75].forEach(factor => colors.push(baseColor.blendWith(0x000000, factor)));
});
grid = F.c("div");
grid.F.style = {
display: "grid",
gridTemplateColumns: "repeat(16, 1fr)",
gridTemplateRows: "auto",
gridGap: "1px",
height: "100%"
};
genericPaletteTab.append(grid);
const x1 = 7;
const x2 = colors.length / x1;
for (let i = 0; i < colors.length; i++) {
// Transpose columns to rows
const j = (i - Math.floor(i / x2) * x2) * x1 + Math.floor(i / x2);
const c = new Color(colors[j]);
c.format = "HTML";
const swatch = F.c("a");
swatch.F.style = {
backgroundColor: String(c),
outline: "solid 0px " + (c.gray().r < 100 ? "#eee" : "#000"),
outlineOffset: "-2px"
};
swatch.href = "#";
grid.append(swatch);
swatch.F.on("click", event => {
event.preventDefault();
const a = opt.color.a;
opt.color = new Color(c);
opt.dataColor = null;
if (a) opt.color.a = a;
updateView();
// Return to the current tab when the selected color also appears on a previous tab
tabs.F.tabs.activeTab = genericPaletteTab;
if (event.detail === 2) {
// Double-click: apply color picker
container.F.trigger("apply", { bubbles: true });
}
});
}
let detailsTab = F.c("div");
detailsTab.title = translate("details");
tabs.append(detailsTab);
grid = F.c("div");
grid.F.style = {
display: "grid",
gridTemplateColumns: "auto 1fr 3em",
gridTemplateRows: "auto"
};
detailsTab.append(grid);
const makeSlider = (label, colorProp, max) => {
const marginTop = colorProp === "h" ? "10px" : "0";
const factor = colorProp === "s" || colorProp === "l" ? 100 : 1;
let labelElement = F.c("div");
labelElement.style.marginTop = marginTop;
labelElement.style.paddingTop = "2px";
labelElement.style.marginRight = "6px";
labelElement.textContent = label;
grid.append(labelElement);
let updatingSlider = false;
let updatingInput = false;
let slider = detailsSliders[colorProp] = F.c("div");
slider.style.marginTop = marginTop;
grid.append(slider);
slider.F.slider({
min: 0,
max: max,
largeStep: max > 1 ? 10 : 0.1,
smallStep: max > 1 ? 1 : 0.01,
largeTicks: false,
largeTickLabels: false
})
// Make the slider untabbable, the text input next to it is already tabbable
slider.removeAttribute("tabindex");
slider.F.on("change", event => {
if (!updatingInput)
detailsInputs[colorProp].value = Math.round(event.value * factor);
if (updatingSlider) return; // Already updating this slider
updatingSlider = true;
opt.color[colorProp] = event.value;
if (!selectingDataColor)
opt.dataColor = null;
let isHSL = ["h", "s", "l"].includes(colorProp);
updateView(undefined, isHSL, !isHSL);
updatingSlider = false;
});
const onInputEvent = () => {
if (updatingInput) return; // Already updating this input
let value = +detailsInputs[colorProp].value;
if (isNaN(value)) return; // Ignore this input event
updatingInput = true;
slider.F.slider.value = value / factor;
updatingInput = false;
};
let input = detailsInputs[colorProp] = F.c("input");
input.type = "text";
input.classList.add("no-border");
input.style.marginTop = marginTop;
input.style.marginLeft = "6px";
input.value = "0";
grid.append(input);
input.F.on("input", event => onInputEvent());
input.F.on("keydown", event => {
if (event.key === "ArrowUp") {
event.preventDefault();
let value = +input.value;
if (!isNaN(value) && (value < max * factor || colorProp === "h")) {
value++;
if (colorProp === "h") while (value > max * factor) value -= 360;
input.value = value;
onInputEvent();
}
}
if (event.key === "ArrowDown") {
event.preventDefault();
let value = +input.value;
if (!isNaN(value) && (value > 0 || colorProp === "h")) {
value--;
if (colorProp === "h") while (value < 0) value += 360;
input.value = value;
onInputEvent();
}
}
});
input.F.on("blur", event => {
// Read clean value from slider
let sliderValue = slider.F.slider.value;
input.value = Math.round(sliderValue * factor);
});
};
makeSlider(translate("red"), "r", 255);
makeSlider(translate("green"), "g", 255);
makeSlider(translate("blue"), "b", 255);
makeSlider(translate("hue"), "h", 359);
makeSlider(translate("saturation"), "s", 1);
makeSlider(translate("lightness"), "l", 1);
// Future tab: tools like blending or secondary colour selection
tabs.F.tabs();
if (opt.withAlpha) {
let labelElement = F.c("div");
labelElement.style.marginTop = "10px";
labelElement.textContent = translate("opacity");
container.append(labelElement);
alphaSlider = F.c("div");
alphaSlider.style.marginTop = "20px";
container.append(alphaSlider);
alphaSlider.F.slider({
min: 0,
max: 100,
largeStep: 10,
smallStep: 1
});
alphaSlider.F.on("change", event => {
opt.color.a = event.value / 100;
updateView(undefined, undefined, true);
});
}
else {
opt.color.a = 1;
}
let previewLabel = F.c("div");
previewLabel.style.marginTop = "10px";
previewLabel.textContent = translate("preview");
container.append(previewLabel);
previewPanel = F.c("div");
previewPanel.F.style = {
marginTop: "4px",
height: "60px",
border: "solid 1px var(--textbox-border)",
padding: "2px 6px",
transition: "background-color var(--animation-duration) var(--animation-function)"
};
container.append(previewPanel);
if (opt.previewHex) {
previewHex = F.c("input");
previewHex.type = "text";
previewHex.classList.add("no-border", "transparent");
previewHex.style.width = "100%";
previewHex.value = String(opt.color);
previewPanel.append(previewHex);
previewHex.F.on("input", event => {
const val = previewHex.value;
if (val.trim().match(/^#[0-9A-Za-z]{6}$/)) {
const c = new Color(val);
opt.color = c;
opt.dataColor = null;
updateView(false, undefined, true);
}
});
}
document.documentElement.F.forwardEvent("darkthemechanging", container);
document.documentElement.F.forwardEvent("darkthemechange", container);
container.F.on("darkthemechanging", () => {
let isDark = container.F.dark;
dataPaletteTab?.querySelectorAll("a.swatch").forEach(swatch => {
const dataColor = DataColor.getColor(swatch.dataset.colorId, swatch.dataset.type, isDark);
swatch.F.style = {
backgroundColor: dataColor,
outline: "solid 0px " + (Color(dataColor).gray().r < 100 ? "#eee" : "#000")
};
if (opt.dataColor === swatch.dataset.colorId + "-" + swatch.dataset.type.substring(1, 2)) {
// Update view and color property
swatch.click();
}
});
});
container.F.on("darkthemechange", () => {
// Update preview text colour for the changed modal background, now that the theme
// colours have settled
updateView();
});
selectingDataColor = !!opt.dataColor;
updateView();
selectingDataColor = false;
isInitialized = true;
function updateView(withText, fromSlidersHSL, changed) {
if (updatingPreview) return; // Already in here
updatingPreview = true;
if (fromSlidersHSL === true)
opt.color.updateRGB();
else
opt.color.updateHSL();
if (opt.withAlpha) {
alphaSlider.F.slider.value = opt.color.a * 100;
alphaSlider.querySelector(".ff-range").style.background = "transparent";
const pattern =
container.F.dark ?
"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKAQMAAAC3/F3+AAAABlBMVEUvLy9PT08CGcynAAAAEElEQVR4XmNgP4CCfjAgIwB8gwi88/AFZQAAAABJRU5ErkJggg" :
"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKAQMAAAC3/F3+AAAABlBMVEXQ0NDw8PAEPQNRAAAAEElEQVR4XmNgP4CCfjAgIwB8gwi88/AFZQAAAABJRU5ErkJggg";
alphaSlider.querySelector(".ff-background").style.background = "linear-gradient(to right, transparent, " + opt.color.alpha(1).toHTML() + "), url(data:image/png;base64," + pattern + ") left center";
// The image is a transparent background chessboard pattern that lies behind the gradually transparent color
}
previewPanel.style.backgroundColor = opt.color.toCSS();
if (opt.previewHex) {
let bgColor = previewPanel.parentElement.F.effectiveBackgroundColor;
let previewColor = bgColor.blendWith(opt.color, opt.color.a);
previewHex.style.color = previewColor.text().toHTML();
if (withText !== false)
previewHex.value = opt.color.toHTML().toUpperCase();
}
// Indicate currently selected swatches in tab 1 and 2
foundMatchInTab = -1;
let opaqueColor = new Color(opt.color);
opaqueColor.a = 1;
F([dataPaletteTab, genericPaletteTab]).querySelectorAll("a").forEach(a => {
let match = opt.color.a > 0 && a.style.backgroundColor === opaqueColor.toCSS();
a.style.outlineWidth = match ? "2px" : "0";
if (foundMatchInTab === -1 && match) {
if (dataPaletteTab?.contains(a))
foundMatchInTab = dataPaletteTab.F.index;
else if (genericPaletteTab.contains(a))
foundMatchInTab = genericPaletteTab.F.index;
}
});
const updateSliderColor = (colorProp, max) => {
let slider = detailsSliders[colorProp];
let isHSL = ["h", "s", "l"].includes(colorProp);
slider.querySelector(".ff-range").style.background = "transparent";
let colorLeft = new Color(opt.color);
colorLeft[colorProp] = 0;
if (isHSL)
colorLeft.updateRGB();
let colorRight = new Color(opt.color);
colorRight[colorProp] = max;
if (isHSL)
colorRight.updateRGB();
let background = "linear-gradient(to right, " + colorLeft.toHTML();
if (isHSL) {
// First (0) and last (12) gradient stop already exist, add those in between
for (let x = 1; x <= 11; x++) {
let colorMid = new Color(opt.color);
colorMid[colorProp] = x / 12 * max;
colorMid.updateRGB();
background += ", " + colorMid.toHTML();
}
}
background += ", " + colorRight.toHTML() + ")";
slider.querySelector(".ff-background").style.background = background;
};
updateSliderColor("r", 255);
updateSliderColor("g", 255);
updateSliderColor("b", 255);
updateSliderColor("h", 359);
updateSliderColor("s", 1);
updateSliderColor("l", 1);
changed |=
opt.color.r !== detailsSliders.r.F.slider.value ||
opt.color.g !== detailsSliders.g.F.slider.value ||
opt.color.b !== detailsSliders.b.F.slider.value;
if (opt.withAlpha)
changed |= opt.color.a !== alphaSlider.F.slider.value / 100;
if (fromSlidersHSL !== true) {
detailsSliders.h.F.slider.value = opt.color.h;
detailsSliders.s.F.slider.value = opt.color.s;
detailsSliders.l.F.slider.value = opt.color.l;
}
if (fromSlidersHSL !== false) {
detailsSliders.r.F.slider.value = opt.color.r;
detailsSliders.g.F.slider.value = opt.color.g;
detailsSliders.b.F.slider.value = opt.color.b;
}
// Disable preview color transition during quick updates because it'll cause flicker
if (quickUpdateTimeout)
clearTimeout(quickUpdateTimeout);
quickUpdateTimeout = setTimeout(() => {
quickUpdateCount = 0;
previewPanel.style.transition = "background-color var(--animation-duration) var(--animation-function)";
}, 50);
quickUpdateCount++;
if (quickUpdateCount > 1)
previewPanel.style.transition = "background-color 0s";
updatingPreview = false;
// Select the tab that contains the selected color, otherwise the details tab
let isBeforeDetailsTab = tabs.F.tabs.activeTabIndex < detailsTab.F.index;
if (isEmpty && isBeforeDetailsTab)
tabs.F.tabs.activeTabIndex = 0;
else if (foundMatchInTab !== -1 && isBeforeDetailsTab)
tabs.F.tabs.activeTabIndex = foundMatchInTab;
else
tabs.F.tabs.activeTab = detailsTab;
if (changed && isInitialized)
container.F.trigger("change", { bubbles: true });
}
// Public function, not used internally
function setColor(newColor) {
setColorInternal(newColor);
updateView();
}
function setColorInternal(newColor) {
isEmpty = !newColor;
switch (opt.colorUse) {
case "background":
case "foreground":
let typePrefix = opt.colorUse.substring(0, 1);
let dc = DataColor.parseGetColor(newColor, typePrefix, container.F.dark);
if (dc) {
opt.color = new Color(dc);
opt.dataColor = newColor;
}
else {
opt.color = new Color(newColor);
opt.dataColor = null;
}
break;
default:
opt.color = new Color(newColor);
opt.dataColor = null;
break;
}
}
});
}
// Gets the selected color of the color picker.
function getColor() {
let container = this.first;
if (!container) return this; // Nothing to do
let opt = F.loadOptions("colorPicker", container);
if (opt?.color && opt.color.a === 1) {
return opt.color.toHTML();
}
return String(opt?.color);
}
// Sets the selected color of the color picker.
function setColor(newColor) {
return this.forEach(container => {
let opt = F.loadOptions("colorPicker", container);
opt && opt._setColor(newColor);
});
}
// Gets the selected data color of the color picker, or null if another color was selected.
function getDataColor() {
let container = this.first;
if (!container) return this; // Nothing to do
let opt = F.loadOptions("colorPicker", container);
return opt?.dataColor;
}
// Deinitializes the plugin.
function deinit() {
return this.forEach(elem => {
if (!elem.classList.contains(colorPickerClass)) return;
elem.classList.remove(colorPickerClass);
elem.replaceChildren();
elem.style.width = "";
elem.style.maxWidth = "";
F.deleteOptions("colorPicker", elem);
document.documentElement.F.unforwardEvent("darkthemechanging", elem);
document.documentElement.F.unforwardEvent("darkthemechange", elem);
});
}
F.registerPlugin("colorPicker", colorPicker, {
defaultOptions: colorPickerDefaults,
methods: {
color: {
get: getColor,
set: setColor
},
dataColor: {
get: getDataColor
},
deinit: deinit
},
selectors: ["div.color-picker"]
});
// ========== Static color picker modal ==========
// Opens a modal with a color picker.
// Returns a Promise that is resolved to the selected color when the modal is confirmed, or "" if
// the "no color" button was clicked, or undefined if the modal was cancelled or otherwise closed.
//
// options.color: The initially selected color.
// options.colorUse: The color use for the color picker. Default: None. If set, the returned value may be a DataColor specification.
// options.withAlpha: Indicates whether the alpha slider is displayed. Default: false.
// options.allowEmpty: Indicates whether the "no color" button is available. Default: false.
// options.separateDark: Shows a checkbox to select whether a separate colour is used for the dark theme.
// This has no effect on the colour picker itself and needs to be interpreted by the application.
// When true, the modal's result is an object with the properties "color" and "separateDark" instead of just the selected colour string.
// options.separateDarkChecked: Checks the "separateDark" checkbox.
// options.language: The language to use for text labels. Default: Auto.
F.colorPickerModal = options => {
let language = options.language || document.documentElement.lang;
let translate = F.getTranslator(dictionary, language);
let div = F.c("div");
div.classList.add("modal");
document.body.append(div); // some calculations require the element to be in the document
let heading = F.c("h3");
heading.style.marginTop = "0";
heading.textContent = translate("select color");
div.append(heading);
let separateDarkCheckBox;
if (options.separateDark) {
let checkBoxDiv = F.c("div");
checkBoxDiv.style.margin = "1em 0";
let label = F.c("label");
label.textContent = " " + translate("separate dark");
separateDarkCheckBox = F.c("input");
separateDarkCheckBox.type = "checkbox";
separateDarkCheckBox.checked = !!options.separateDarkChecked;
label.prepend(separateDarkCheckBox);
checkBoxDiv.append(label);
div.append(checkBoxDiv);
checkBoxDiv.F.frontfire();
}
let colorDiv = F.c("div");
div.append(colorDiv);
colorDiv.F.colorPicker(options);
let colorPicker = colorDiv.F.colorPicker;
let buttonsDiv = F.c("div");
buttonsDiv.classList.add("buttons");
div.append(buttonsDiv);
let acceptButton = F.c("button");
acceptButton.classList.add("button", "default");
acceptButton.textContent = translate("accept");
buttonsDiv.append(acceptButton);
let emptyButton;
if (options.allowEmpty) {
emptyButton = F.c("button");
emptyButton.classList.add("button");
emptyButton.textContent = translate("no color");
buttonsDiv.append(emptyButton);
}
let cancelButton = F.c("button");
cancelButton.classList.add("button", "transparent");
cancelButton.textContent = translate("cancel");
buttonsDiv.append(cancelButton);
let modal = div.F.modal();
var promise = new Promise((resolve, reject) => {
const resolveInternal = result => {
if (options.separateDark) {
resolve({
color: result,
separateDark: separateDarkCheckBox.checked
});
}
else {
resolve(result);
}
};
colorDiv.F.on("apply", () => {
if (options.colorUse)
resolveInternal(colorPicker.dataColor ?? colorPicker.color);
else
resolveInternal(colorPicker.color);
modal.close();
});
acceptButton.F.on("click", () => {
if (options.colorUse)
resolveInternal(colorPicker.dataColor ?? colorPicker.color);
else
resolveInternal(colorPicker.color);
modal.close();
});
if (emptyButton) {
emptyButton.F.on("click", () => {
resolveInternal("");
modal.close();
});
}
cancelButton.F.on("click", () => {
modal.close();
});
div.F.on("close", () => {
div.remove();
// Resolve without result if not already resolved
resolveInternal();
});
setTimeout(() => {
promise.cancel = () => {
modal.close();
};
}, 0);
});
return promise;
};
// ==================== Color input plugin ====================
const inputWrapperClass = "ff-input-wrapper";
// Defines default options for the color input plugin.
let colorInputDefaults = {
};
// Converts each selected input element into a text field with color picker button.
function colorInput(options) {
return this.forEach(input => {
if (input.parentElement?.classList.contains(inputWrapperClass)) return; // Already done
let opt = F.initOptions("colorInput", input, {}, options);
// Put a wrapper between the input and its parent
let wrapper = F.c("div");
wrapper.classList.add(inputWrapperClass);
let styleAttr = input.getAttribute("style");
if (styleAttr)
wrapper.setAttribute("style", styleAttr);
input.before(wrapper);
wrapper.append(input);
input.setAttribute("autocomplete", "off");
// Add control buttons
let buttons = F.c("span");
buttons.classList.add("group");
wrapper.append(buttons);
let updateButtons;
let pickButton = F.c("button");
pickButton.type = "button";
pickButton.classList.add("ff-colorpicker");
buttons.append(pickButton);
pickButton.setAttribute("tabindex", "-1");
pickButton.disabled = input.disabled;
pickButton.innerHTML = `<svg style="width: 18px; height: 18px;"><path class="back" d="M0,0h18v18h-18Z"/><path class="dots" d="M4,8h2v2h-2Z M8,8h2v2h-2Z M12,8h2v2h-2Z"/></svg>`;
// Selecting by class name is an easy way to get SVG children
let rect = pickButton.getElementsByClassName("back")[0];
let dots = pickButton.getElementsByClassName("dots")[0];
pickButton.F.on("click", async () => {
if (input.disabled) return;
let result = await F.colorPickerModal(Object.assign({}, opt, { color: input.value }));
if (result !== undefined) {
if (result !== "") {
input.value = result;
}
else {
input.value = "";
}
input.F.trigger("input change");
updateButtons();
}
});
document.documentElement.F.forwardEvent("darkthemechanging", pickButton);
pickButton.F.on("darkthemechanging", () => {
updateButtons();
});
updateButtons = () => {
pickButton.disabled = input.disabled;
if (input.value) {
let color = input.value;
switch (opt.colorUse) {
case "background":
case "foreground":
let typePrefix = opt.colorUse.substring(0, 1);
let dc = DataColor.parseGetColor(color, typePrefix, input.F.dark);
if (dc) {
color = new Color(dc);
}
break;
}
rect.setAttribute("fill", new Color(color).toCSS());
// Style overrides CSS which overrides SVG attributes
dots.style.fill = new Color(color).text();
}
else {
rect.setAttribute("fill", "none");
dots.style.fill = "";
}
};
updateButtons();
// Enable or disable the buttons when the input is enabled or disabled
input.F.observeDisabled(disabled => updateButtons());
// The value property cannot be observed, require the change event
input.F.on("change", () => updateButtons());
input.F.on("keydown", event => {
if (event.key === " ") {
event.preventDefault();
pickButton.click();
}
});
// Show or hide the wrapper instead whenever the input should be shown or hidden
F.internalData.set(input, "visible.replacement", wrapper);
});
}
F.registerPlugin("colorInput", colorInput, {
defaultOptions: colorInputDefaults,
selectors: ["input.color-picker"]
});