-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathZenGradientGenerator.mjs
More file actions
1995 lines (1798 loc) · 63.3 KB
/
ZenGradientGenerator.mjs
File metadata and controls
1995 lines (1798 loc) · 63.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import { nsZenMultiWindowFeature } from "chrome://browser/content/zen-components/ZenCommonUtils.mjs";
function parseSinePath(pathStr) {
const points = [];
const commands = pathStr.match(/[MCL]\s*[\d\s.\-,]+/g);
if (!commands) {
return points;
}
commands.forEach(command => {
const type = command.charAt(0);
const coordsStr = command.slice(1).trim();
const coords = coordsStr.split(/[\s,]+/).map(Number);
switch (type) {
case "M":
points.push({ x: coords[0], y: coords[1], type: "M" });
break;
case "C":
if (coords.length >= 6 && coords.length % 6 === 0) {
for (let i = 0; i < coords.length; i += 6) {
points.push({
x1: coords[i],
y1: coords[i + 1],
x2: coords[i + 2],
y2: coords[i + 3],
x: coords[i + 4],
y: coords[i + 5],
type: "C",
});
}
}
break;
case "L":
points.push({ x: coords[0], y: coords[1], type: "L" });
break;
}
});
return points;
}
const lazy = {};
ChromeUtils.defineLazyGetter(lazy, "MAX_OPACITY", () => {
return parseFloat(
document.getElementById("PanelUI-zen-gradient-generator-opacity").max
);
});
ChromeUtils.defineLazyGetter(lazy, "MIN_OPACITY", () => {
return parseFloat(
document.getElementById("PanelUI-zen-gradient-generator-opacity").min
);
});
ChromeUtils.defineLazyGetter(lazy, "browserBackgroundElement", () => {
return document.getElementById("zen-browser-background");
});
ChromeUtils.defineLazyGetter(lazy, "toolbarBackgroundElement", () => {
return document.getElementById("zen-toolbar-background");
});
const EXPLICIT_LIGHTNESS_TYPE = "explicit-lightness";
const EXPLICIT_BLACKWHITE_TYPE = "explicit-black-white";
/**
* A class that manages the theme picker for Zen Workspaces.
* It allows users to create and customize gradients for their workspace themes.
*/
export class nsZenThemePicker extends nsZenMultiWindowFeature {
static MAX_DOTS = 3;
currentOpacity = 0.5;
dots = [];
useAlgo = "";
#currentLightness = 50;
#allowTransparencyOnSidebar = Services.prefs.getBoolPref(
"zen.theme.acrylic-elements",
false
);
#linePath = `M 51.373 27.395 L 367.037 27.395`;
#sinePath = `M 51.373 27.395 C 60.14 -8.503 68.906 -8.503 77.671 27.395 C 86.438 63.293 95.205 63.293 103.971 27.395 C 112.738 -8.503 121.504 -8.503 130.271 27.395 C 139.037 63.293 147.803 63.293 156.57 27.395 C 165.335 -8.503 174.101 -8.503 182.868 27.395 C 191.634 63.293 200.4 63.293 209.167 27.395 C 217.933 -8.503 226.7 -8.503 235.467 27.395 C 244.233 63.293 252.999 63.293 261.765 27.395 C 270.531 -8.503 279.297 -8.503 288.064 27.395 C 296.83 63.293 305.596 63.293 314.363 27.395 C 323.13 -8.503 331.896 -8.503 340.662 27.395 M 314.438 27.395 C 323.204 -8.503 331.97 -8.503 340.737 27.395 C 349.503 63.293 358.27 63.293 367.037 27.395`;
#sinePoints = parseSinePath(this.#sinePath);
#colorPage = 0;
#gradientsCache = new Map();
constructor() {
super();
if (
!gZenWorkspaces.shouldHaveWorkspaces ||
gZenWorkspaces.privateWindowOrDisabled
) {
return;
}
this.promiseInitialized = new Promise(resolve => {
this._resolveInitialized = resolve;
});
this.dragStartPosition = null;
this.isLegacyVersion =
Services.prefs.getIntPref("zen.theme.gradient-legacy-version", 1) === 0;
ChromeUtils.defineLazyGetter(this, "panel", () =>
document.getElementById("PanelUI-zen-gradient-generator")
);
ChromeUtils.defineLazyGetter(this, "toolbox", () =>
document.getElementById("TabsToolbar")
);
ChromeUtils.defineLazyGetter(this, "customColorInput", () =>
document.getElementById("PanelUI-zen-gradient-generator-custom-input")
);
ChromeUtils.defineLazyGetter(this, "customColorList", () =>
document.getElementById("PanelUI-zen-gradient-generator-custom-list")
);
ChromeUtils.defineLazyGetter(this, "sliderWavePath", () =>
document
.getElementById("PanelUI-zen-gradient-slider-wave")
.querySelector("path")
);
this.panel.addEventListener(
"popupshowing",
this.handlePanelOpen.bind(this)
);
this.panel.addEventListener(
"popuphidden",
this.handlePanelClose.bind(this)
);
this.panel.addEventListener("command", this.handlePanelCommand.bind(this));
document
.getElementById("PanelUI-zen-gradient-generator-opacity")
.addEventListener("input", this.onOpacityChange.bind(this));
// Call the rest of the initialization
this.initContextMenu();
this.initPredefinedColors();
this._resolveInitialized();
delete this._resolveInitialized;
this.initCustomColorInput();
this.initTextureInput();
this.initSchemeButtons();
this.initColorPages();
const darkModeChange = this.handleDarkModeChange.bind(this);
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", darkModeChange);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"windowSchemeType",
"zen.view.window.scheme",
2,
darkModeChange
);
XPCOMUtils.defineLazyPreferenceGetter(
this,
"darkModeBias",
"zen.theme.dark-mode-bias",
"0.5"
);
}
handleDarkModeChange() {
this.updateCurrentWorkspace();
}
get isDarkMode() {
if (PrivateBrowsingUtils.isWindowPrivate(window)) {
return true;
}
switch (this.windowSchemeType) {
case 0:
return true;
case 1:
return false;
default:
}
return window.matchMedia("(prefers-color-scheme: dark)").matches;
}
get colorHarmonies() {
return [
{ type: "complementary", angles: [180] },
{ type: "singleAnalogous", angles: [310] },
{ type: "splitComplementary", angles: [150, 210] },
{ type: "analogous", angles: [50, 310] },
{ type: "triadic", angles: [120, 240] },
{ type: "floating", angles: [] },
];
}
initContextMenu() {
const menu = window.MozXULElement.parseXULToFragment(`
<menuitem id="zenToolbarThemePicker"
data-lazy-l10n-id="zen-workspaces-change-theme"
command="cmd_zenOpenZenThemePicker"/>
`);
document.getElementById("toolbar-context-customize").before(menu);
}
openThemePicker(event) {
const fromForm = event.explicitOriginalTarget?.classList?.contains(
"zen-workspace-creation-edit-theme-button"
);
const isRightSide = window.gZenVerticalTabsManager._prefsRightSide;
PanelMultiView.openPopup(this.panel, this.toolbox, {
position: isRightSide ? "topleft topright" : "topright topleft",
triggerEvent: event,
y: fromForm ? -160 : 0,
x: -10,
});
}
initCustomColorInput() {
this.customColorInput.addEventListener("change", event => {
// Prevent the popup from closing when the input is focused
this.openThemePicker(event);
});
}
initPredefinedColors() {
document
.getElementById("PanelUI-zen-gradient-generator-color-pages")
.addEventListener("click", async event => {
const target = event.target;
const rawPosition = target.getAttribute("data-position");
if (!rawPosition) {
return;
}
const algo = target.getAttribute("data-algo");
const lightness = target.getAttribute("data-lightness");
const numDots = parseInt(target.getAttribute("data-num-dots"));
if (numDots < this.dots.length) {
for (let i = numDots; i < this.dots.length; i++) {
this.dots[i].element.remove();
}
this.dots = this.dots.slice(0, numDots);
}
const type =
target.getAttribute("data-type") || EXPLICIT_LIGHTNESS_TYPE;
// Generate new gradient from the single color given
const [x, y] = rawPosition.split(",").map(pos => parseInt(pos));
let dots = [
{
ID: 0,
position: { x, y },
isPrimary: true,
type,
},
];
for (let i = 1; i < numDots; i++) {
dots.push({
ID: i,
position: { x: 0, y: 0 },
type,
});
}
this.useAlgo = algo;
if (lightness !== null) {
this.#currentLightness = lightness;
}
dots = this.calculateCompliments(dots, "update", this.useAlgo);
this.handleColorPositions(dots, true);
this.updateCurrentWorkspace();
});
}
initColorPages() {
const leftButton = document.getElementById(
"PanelUI-zen-gradient-generator-color-page-left"
);
const rightButton = document.getElementById(
"PanelUI-zen-gradient-generator-color-page-right"
);
const pagesWrapper = document.getElementById(
"PanelUI-zen-gradient-generator-color-pages"
);
const pages = pagesWrapper.children;
pagesWrapper.addEventListener("wheel", event => {
event.preventDefault();
event.stopPropagation();
});
leftButton.addEventListener("command", () => {
this.#colorPage = (this.#colorPage - 1 + pages.length) % pages.length;
// Scroll to the next page, by using scrollLeft
pagesWrapper.scrollLeft =
(this.#colorPage * pagesWrapper.scrollWidth) / pages.length;
rightButton.disabled = false;
leftButton.disabled = this.#colorPage === 0;
});
rightButton.addEventListener("command", () => {
this.#colorPage = (this.#colorPage + 1) % pages.length;
// Scroll to the next page, by using scrollLeft
pagesWrapper.scrollLeft =
(this.#colorPage * pagesWrapper.scrollWidth) / pages.length;
leftButton.disabled = false;
rightButton.disabled = this.#colorPage === pages.length - 1;
});
}
initSchemeButtons() {
const buttons = document.getElementById(
"PanelUI-zen-gradient-generator-scheme"
);
buttons.addEventListener("click", event => {
const target = event.target.closest(".subviewbutton");
if (!target) {
return;
}
event.preventDefault();
event.stopPropagation();
const scheme = target.id.replace(
"PanelUI-zen-gradient-generator-scheme-",
""
);
if (!scheme) {
return;
}
const themeInt = {
auto: 2,
light: 1,
dark: 0,
}[scheme];
if (themeInt === undefined) {
return;
}
Services.prefs.setIntPref("zen.view.window.scheme", themeInt);
});
}
initTextureInput() {
const wrapper = document.getElementById(
"PanelUI-zen-gradient-generator-texture-wrapper"
);
const wrapperWidth =
window.windowUtils.getBoundsWithoutFlushing(wrapper).width;
// Add elements in a circular pattern, where the center is the center of the wrapper
for (let i = 0; i < 16; i++) {
const dot = document.createElement("div");
dot.classList.add("zen-theme-picker-texture-dot");
const position = (i / 16) * Math.PI * 2 + wrapperWidth;
dot.style.left = `${Math.cos(position) * 50 + 50}%`;
dot.style.top = `${Math.sin(position) * 50 + 50}%`;
wrapper.appendChild(dot);
}
this._textureHandler = document.createElement("div");
this._textureHandler.id = "PanelUI-zen-gradient-generator-texture-handler";
this._textureHandler.addEventListener(
"mousedown",
this.onTextureHandlerMouseDown.bind(this)
);
wrapper.appendChild(this._textureHandler);
}
onTextureHandlerMouseDown(event) {
event.preventDefault();
this._onTextureMouseMove = this.onTextureMouseMove.bind(this);
this._onTextureMouseUp = this.onTextureMouseUp.bind(this);
document.addEventListener("mousemove", this._onTextureMouseMove);
document.addEventListener("mouseup", this._onTextureMouseUp);
}
onTextureMouseMove(event) {
event.preventDefault();
const wrapper = document.getElementById(
"PanelUI-zen-gradient-generator-texture-wrapper"
);
const wrapperRect = window.windowUtils.getBoundsWithoutFlushing(wrapper);
// Determine how much rotation there is based on the mouse position and the center of the wrapper
const rotation = Math.atan2(
event.clientY - wrapperRect.top - wrapperRect.height / 2,
event.clientX - wrapperRect.left - wrapperRect.width / 2
);
const previousTexture = this.currentTexture;
this.currentTexture = (rotation * 180) / Math.PI + 90;
// if it's negative, add 360 to make it positive
if (this.currentTexture < 0) {
this.currentTexture += 360;
}
// make it go from 1 to 0 instead of being in degrees
this.currentTexture /= 360;
// We clip it to the closest button out of 16 possible buttons
this.currentTexture = Math.round(this.currentTexture * 16) / 16;
if (this.currentTexture === 1) {
this.currentTexture = 0;
}
if (previousTexture !== this.currentTexture) {
this.updateCurrentWorkspace();
/* eslint-disable mozilla/valid-services */
Services.zen.playHapticFeedback();
}
}
onTextureMouseUp(event) {
event.preventDefault();
document.removeEventListener("mousemove", this._onTextureMouseMove);
document.removeEventListener("mouseup", this._onTextureMouseUp);
this._onTextureMouseMove = null;
this._onTextureMouseUp = null;
}
initThemePicker() {
const themePicker = this.panel.querySelector(".zen-theme-picker-gradient");
this._onDotMouseMove = this.onDotMouseMove.bind(this);
this._onDotMouseUp = this.onDotMouseUp.bind(this);
this._onDotMouseDown = this.onDotMouseDown.bind(this);
this._onThemePickerClick = this.onThemePickerClick.bind(this);
document.addEventListener("mousemove", this._onDotMouseMove);
document.addEventListener("mouseup", this._onDotMouseUp);
themePicker.addEventListener("mousedown", this._onDotMouseDown);
themePicker.addEventListener("click", this._onThemePickerClick);
}
uninitThemePicker() {
const themePicker = this.panel.querySelector(".zen-theme-picker-gradient");
document.removeEventListener("mousemove", this._onDotMouseMove);
document.removeEventListener("mouseup", this._onDotMouseUp);
themePicker.removeEventListener("mousedown", this._onDotMouseDown);
themePicker.removeEventListener("click", this._onThemePickerClick);
this._onDotMouseMove = null;
this._onDotMouseUp = null;
this._onDotMouseDown = null;
this._onThemePickerClick = null;
}
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from https://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param {number} h The hue
* @param {number} s The saturation
* @param {number} l The lightness
* @returns {Array} The RGB representation
*/
hslToRgb(h, s, l) {
const { round } = Math;
let r, g, b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = this.hueToRgb(p, q, h + 1 / 3);
g = this.hueToRgb(p, q, h);
b = this.hueToRgb(p, q, h - 1 / 3);
}
return [round(r * 255), round(g * 255), round(b * 255)];
}
rgbToHsl(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
let max = Math.max(r, g, b);
let min = Math.min(r, g, b);
let d = max - min;
let h;
if (d === 0) {
h = 0;
} else if (max === r) {
h = ((g - b) / d) % 6;
} else if (max === g) {
h = (b - r) / d + 2;
} else if (max === b) {
h = (r - g) / d + 4;
}
let l = (min + max) / 2;
let s = d === 0 ? 0 : d / (1 - Math.abs(2 * l - 1));
return [h * 60, s, l];
}
hueToRgb(p, q, t) {
if (t < 0) {
t += 1;
}
if (t > 1) {
t -= 1;
}
if (t < 1 / 6) {
return p + (q - p) * 6 * t;
}
if (t < 1 / 2) {
return q;
}
if (t < 2 / 3) {
return p + (q - p) * (2 / 3 - t) * 6;
}
return p;
}
calculateInitialPosition([r, g, b]) {
// This function is called before the picker is even rendered, so we hard code the dimensions
// important: If any sort of sizing is changed, make sure changes are reflected here
const padding = 0;
const rect = {
width: 380 + padding * 2,
height: 380 + padding * 2,
};
const centerX = rect.width / 2;
const centerY = rect.height / 2;
const radius = (rect.width - padding) / 2;
const [hue, saturation] = this.rgbToHsl(r, g, b);
const angle = (hue / 360) * 2 * Math.PI; // Convert to radians
const normalizedSaturation = saturation / 100; // Convert to [0, 1]
const x =
centerX + radius * normalizedSaturation * Math.cos(angle) - padding;
const y =
centerY + radius * normalizedSaturation * Math.sin(angle) - padding;
return { x, y };
}
getColorFromPosition(x, y, type = undefined) {
// Return a color as hsl based on the position in the gradient
const gradient = this.panel.querySelector(".zen-theme-picker-gradient");
const rect = window.windowUtils.getBoundsWithoutFlushing(gradient);
const padding = 30; // each side
const dotHalfSize = 29; // half the size of the dot. -11 for correct centering
x += dotHalfSize;
y += dotHalfSize;
rect.width += padding * 2; // Adjust width and height for padding
rect.height += padding * 2; // Adjust width and height for padding
const centerX = rect.width / 2;
const centerY = rect.height / 2;
const radius = (rect.width - padding) / 2;
const distance = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
let angle = Math.atan2(y - centerY, x - centerX);
angle = (angle * 180) / Math.PI; // Convert to degrees
if (angle < 0) {
angle += 360; // Normalize to [0, 360)
}
const normalizedDistance = 1 - Math.min(distance / radius, 1); // Normalize distance to [0, 1]
let hue = (angle / 360) * 360; // Normalize angle to [0, 360)
let saturation = normalizedDistance * 100; // stays high even in center
if (type !== EXPLICIT_LIGHTNESS_TYPE) {
saturation = 90 + (1 - normalizedDistance) * 10;
// Set the current lightness to how far we are from the center of the circle
// For example, moving the dot outside will have higher lightness, while moving it inside will have lower lightness
this.#currentLightness = Math.round((1 - normalizedDistance) * 100);
}
let lightness = this.#currentLightness; // Fixed lightness for simplicity
if (type === EXPLICIT_BLACKWHITE_TYPE) {
// We can only get grayscales from white to black
saturation = 0;
lightness = Math.round((1 - normalizedDistance) * 100);
}
const [r, g, b] = this.hslToRgb(
hue / 360,
saturation / 100,
lightness / 100
);
return [
Math.min(255, Math.max(0, r)),
Math.min(255, Math.max(0, g)),
Math.min(255, Math.max(0, b)),
];
}
getJSONPos(x, y) {
// Return a JSON string with the position
return JSON.stringify({ x: Math.round(x), y: Math.round(y) });
}
createDot(color, fromWorkspace = false) {
const [r, g, b] = color.c;
const dot = document.createElement("div");
if (color.isPrimary) {
dot.classList.add("primary");
}
if (color.isCustom) {
if (!color.c) {
return;
}
dot.classList.add("custom");
dot.style.opacity = 0;
dot.style.setProperty("--zen-theme-picker-dot-color", color.c);
} else {
const { x, y } =
color.position || this.calculateInitialPosition([r, g, b]);
const dotPad = this.panel.querySelector(".zen-theme-picker-gradient");
dot.classList.add("zen-theme-picker-dot");
dot.style.left = `${x}px`;
dot.style.top = `${y}px`;
if (this.dots.length < 1) {
dot.classList.add("primary");
}
dotPad.appendChild(dot);
let id = this.dots.length;
dot.style.setProperty(
"--zen-theme-picker-dot-color",
`rgb(${r}, ${g}, ${b})`
);
dot.setAttribute("data-position", this.getJSONPos(x, y));
dot.setAttribute("data-type", color.type);
this.dots.push({
ID: id,
element: dot,
position: { x, y },
type: color.type,
lightness: color.lightness,
});
}
if (!fromWorkspace) {
this.updateCurrentWorkspace(true);
}
}
addColorToCustomList(color) {
const listItems = window.MozXULElement.parseXULToFragment(`
<hbox class="zen-theme-picker-custom-list-item">
<html:div class="zen-theme-picker-dot custom"></html:div>
<label class="zen-theme-picker-custom-list-item-label"></label>
<toolbarbutton class="zen-theme-picker-custom-list-item-remove toolbarbutton-1"></toolbarbutton>
</hbox>
`);
listItems
.querySelector(".zen-theme-picker-custom-list-item")
.setAttribute("data-color", color);
listItems
.querySelector(".zen-theme-picker-dot")
.style.setProperty("--zen-theme-picker-dot-color", color);
listItems.querySelector(
".zen-theme-picker-custom-list-item-label"
).textContent = color;
listItems
.querySelector(".zen-theme-picker-custom-list-item-remove")
.addEventListener("command", this.removeCustomColor.bind(this));
this.customColorList.appendChild(listItems);
}
async addCustomColor() {
let color = this.customColorInput.value;
if (!color) {
return;
}
let colorOpacity =
document.getElementById("PanelUI-zen-gradient-generator-custom-opacity")
?.value ?? 1;
// Convert the opacity into a hex value if it's not already
if (colorOpacity < 1) {
// e.g. if opacity is 1, we add to the color FF, if it's 0.5 we add 80, etc.
const hexOpacity = Math.round(colorOpacity * 255)
.toString(16)
.padStart(2, "0")
.toUpperCase();
// If the color is in hex format
if (color.startsWith("#")) {
// If the color is already in hex format, we just append the opacity
if (color.length === 7) {
color += hexOpacity;
}
}
}
// Add '#' prefix if it's missing and the input appears to be a hex color
if (!color.startsWith("#") && /^[0-9A-Fa-f]{3,6}$/.test(color)) {
color = "#" + color;
}
// can be any color format, we just add it to the list as a dot, but hidden
const dot = document.createElement("div");
dot.classList.add("zen-theme-picker-dot", "hidden", "custom");
dot.style.opacity = 0;
dot.style.setProperty("--zen-theme-picker-dot-color", color);
this.panel
.querySelector("#PanelUI-zen-gradient-generator-custom-list")
.prepend(dot);
this.customColorInput.value = "";
document.getElementById(
"PanelUI-zen-gradient-generator-custom-opacity"
).value = 1;
this.updateCurrentWorkspace();
}
handlePanelCommand(event) {
const target = event.target.closest("toolbarbutton");
if (!target) {
return;
}
switch (target.id) {
case "PanelUI-zen-gradient-generator-color-custom-add":
this.addCustomColor();
break;
}
}
spawnDot(dotData, primary = false) {
const dotPad = this.panel.querySelector(".zen-theme-picker-gradient");
const relativePosition = {
x: dotData.x,
y: dotData.y,
};
const dot = document.createElement("div");
dot.classList.add("zen-theme-picker-dot");
dot.style.left = `${dotData.x}px`;
dot.style.top = `${dotData.y}px`;
dotPad.appendChild(dot);
let id = this.dots.length;
if (primary) {
id = 0;
dot.classList.add("primary");
const existingPrimaryDot = this.dots.find(d => d.ID === 0);
if (existingPrimaryDot) {
existingPrimaryDot.ID = this.dots.length;
existingPrimaryDot.element.classList.remove("primary");
}
}
const colorFromPos = this.getColorFromPosition(
relativePosition.x,
relativePosition.y,
dotData.type
);
dot.style.setProperty(
"--zen-theme-picker-dot-color",
`rgb(${colorFromPos[0]}, ${colorFromPos[1]}, ${colorFromPos[2]})`
);
dot.setAttribute(
"data-position",
this.getJSONPos(relativePosition.x, relativePosition.y)
);
dot.setAttribute("data-type", dotData.type);
this.dots.push({
ID: id,
element: dot,
position: { x: relativePosition.x, y: relativePosition.y },
lightness: this.#currentLightness,
type: dotData.type,
});
}
calculateCompliments(dots, action = "update", useHarmony = "") {
const colorHarmonies = this.colorHarmonies;
if (dots.length === 0) {
return [];
}
/* eslint-disable no-shadow */
function getColorHarmonyType(numDots, dots) {
if (useHarmony !== "") {
const selectedHarmony = colorHarmonies.find(
harmony => harmony.type === useHarmony
);
if (selectedHarmony) {
if (action === "remove") {
if (dots.length !== 0) {
return colorHarmonies.find(
harmony =>
harmony.angles.length === selectedHarmony.angles.length - 1
);
}
return { type: "floating", angles: [] };
}
if (action === "add") {
return colorHarmonies.find(
harmony =>
harmony.angles.length === selectedHarmony.angles.length + 1
);
}
if (action === "update") {
return selectedHarmony;
}
}
}
if (action === "remove") {
let harmony = colorHarmonies.find(h => h.angles.length === numDots);
// If we are coming from 3 analogous dots, we should now go to singleAnalogous if
// there are 2 dots left
if (harmony.type === "analogous" && numDots === 1) {
harmony = colorHarmonies.find(h => h.type === "singleAnalogous");
}
return harmony;
}
if (action === "add") {
return colorHarmonies.find(h => h.angles.length + 1 === numDots);
}
if (action === "update") {
return colorHarmonies.find(h => h.angles.length + 1 === numDots);
}
return null;
}
function getAngleFromPosition(position, centerPosition) {
let deltaX = position.x - centerPosition.x;
let deltaY = position.y - centerPosition.y;
let angle = Math.atan2(deltaY, deltaX) * (180 / Math.PI);
return (angle + 360) % 360;
}
function getDistanceFromCenter(position, centerPosition) {
const deltaX = position.x - centerPosition.x;
const deltaY = position.y - centerPosition.y;
return Math.sqrt(deltaX * deltaX + deltaY * deltaY);
}
const dotPad = this.panel.querySelector(".zen-theme-picker-gradient");
const rect = window.windowUtils.getBoundsWithoutFlushing(dotPad);
const padding = 0;
let updatedDots = [...dots];
const centerPosition = { x: rect.width / 2, y: rect.height / 2 };
const harmonyAngles = getColorHarmonyType(
/* eslint-disable no-nested-ternary */
dots.length + (action === "add" ? 1 : action === "remove" ? -1 : 0),
this.dots
);
this.useAlgo = harmonyAngles.type;
if (!harmonyAngles || harmonyAngles.angles.length === 0) {
return dots;
}
let primaryDot = dots.find(dot => dot.ID === 0);
if (!primaryDot) {
return [];
}
if (action === "add" && this.dots.length) {
updatedDots.push({ ID: this.dots.length, position: centerPosition });
}
const baseAngle = getAngleFromPosition(primaryDot.position, centerPosition);
let distance = getDistanceFromCenter(primaryDot.position, centerPosition);
const radius = (rect.width - padding) / 2;
if (distance > radius) {
distance = radius;
}
if (this.dots.length) {
updatedDots = [
{
ID: 0,
position: primaryDot.position,
type: primaryDot.type,
},
];
}
harmonyAngles.angles.forEach((angleOffset, index) => {
let newAngle = (baseAngle + angleOffset) % 360;
let radian = (newAngle * Math.PI) / 180;
let newPosition = {
x: centerPosition.x + distance * Math.cos(radian),
y: centerPosition.y + distance * Math.sin(radian),
};
updatedDots.push({
ID: index + 1,
position: newPosition,
type: primaryDot.type,
});
});
return updatedDots;
}
handleColorPositions(colorPositions, ignoreLegacy = false) {
colorPositions.sort((a, b) => a.ID - b.ID);
if (this.isLegacyVersion && !ignoreLegacy) {
this.isLegacyVersion = false;
Services.prefs.setIntPref("zen.theme.gradient-legacy-version", 1);
}
colorPositions.forEach(dotPosition => {
const existingDot = this.dots.find(dot => dot.ID === dotPosition.ID);
if (existingDot) {
existingDot.type = dotPosition.type;
existingDot.position = dotPosition.position;
const colorFromPos = this.getColorFromPosition(
dotPosition.position.x,
dotPosition.position.y,
dotPosition.type
);
existingDot.lightness = this.#currentLightness;
existingDot.element.style.setProperty(
"--zen-theme-picker-dot-color",
`rgb(${colorFromPos[0]}, ${colorFromPos[1]}, ${colorFromPos[2]})`
);
existingDot.element.setAttribute(
"data-position",
this.getJSONPos(dotPosition.position.x, dotPosition.position.y)
);
existingDot.element.setAttribute("data-type", dotPosition.type);
if (!this.dragging) {
gZenUIManager.motion.animate(
existingDot.element,
{
left: existingDot.element.style.left
? [
existingDot.element.style.left,
`${dotPosition.position.x}px`,
]
: `${dotPosition.position.x}px`,
top: existingDot.element.style.top
? [existingDot.element.style.top, `${dotPosition.position.y}px`]
: `${dotPosition.position.y}px`,
},
{
duration: 0.4,
type: "spring",
bounce: 0.3,
}
);
} else {
existingDot.element.style.left = `${dotPosition.position.x}px`;
existingDot.element.style.top = `${dotPosition.position.y}px`;
}
} else {
this.spawnDot({
type: dotPosition.type,
...dotPosition.position,
});
}
});
}
onThemePickerClick(event) {
if (this._rotating) {
return;
}
if (event.target.closest("#PanelUI-zen-gradient-generator-scheme")) {
return;
}
event.preventDefault();
const target = event.target;
if (target.id === "PanelUI-zen-gradient-generator-color-add") {
if (this.dots.length >= nsZenThemePicker.MAX_DOTS) {
return;
}
let colorPositions = this.calculateCompliments(
this.dots,
"add",
this.useAlgo
);
this.handleColorPositions(colorPositions);
this.updateCurrentWorkspace();
return;
} else if (target.id === "PanelUI-zen-gradient-generator-color-remove") {
this.dots.sort((a, b) => a.ID - b.ID);
if (this.dots.length === 0) {
return;
}
const lastDot = this.dots.pop();
lastDot.element.remove();
this.dots.forEach((dot, index) => {
dot.ID = index;
if (index === 0) {
dot.element.classList.add("primary");
} else {
dot.element.classList.remove("primary");
}
});
let colorPositions = this.calculateCompliments(this.dots, "remove");
this.handleColorPositions(colorPositions);
this.updateCurrentWorkspace();
return;
} else if (