-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy paththeme-color-editor.js
More file actions
2659 lines (2388 loc) · 128 KB
/
theme-color-editor.js
File metadata and controls
2659 lines (2388 loc) · 128 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
// ****************************************************
// theme color editor for wiki.gg wikis
// ****************************************************
// MIT License
//
// Copyright (c) 2025 cadaei (https://github.com/cadon)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// ****************************************************
//
// # Theme Color Editor
// Theme color editor for wiki.gg wikis.
//
// ## Features
// * Adjust color variables of wiki themes with a color picker or indirect definitions based on other colors
// * Live preview of the set colors on other wiki pages
// * Display of needed contrasts between colors
// * buttons for automatic contrast fixing
//
// ## How to use
// Run this script in the browser console of a wiki page with a specific table of defined color variables, e.g. on ...wiki.gg/wiki/MediaWiki:Common.css and add the styles of theme-color-editor.css. The variable table needs to have the following format
//
// <table>
// <tr>
// <th>Variable name</th>
// <th>Color</th>
// <th>Notes</th>
// <th>Test contrast against these variables</th>
// </tr>
// <tr>
// <td>--wiki-body-background-color
// </td>
// <td style="background-color:var(--wiki-body-background-color);"></td>
// <td>The background color behind the background image.</td>
// <td style="background-color:var(--wiki-body-background-color);">
// <p><span style="color:var(--wiki-body-dynamic-color);">--wiki-body-dynamic-color</span><br>
// <span style="color:var(--wiki-body-dynamic-color--secondary);" data-min-contrast="3">--wiki-body-dynamic-color--secondary</span>
// </p>
// </td>
// </tr>
// </table>
// ***************************************************
"use strict";
const themeColorEditor = {
/**
* Contains info about the css variables edited by the user.
* Key is the variable name, value is the variableInfo.
*/
variableInfo: undefined,
colorPicker: undefined,
/**
* Clipboard-like variable used to copy/paste colors
*/
holdVariable: undefined,
/**
* If true and a variable has an --rgb variant, it's included in the output
*/
exportIncludeRgbVariants: false,
/**
* If true the explicit color adjustment options are also exported. Used to save work on a theme and import again in a later session.
*/
exportIncludeExplicitOptions: false,
/**
* References to preview popups where the styles are applied.
* Each entry is an object with property w: window, s: style element to adjust the styles
*/
previewPopups: undefined,
/**
* collection of base css, key is name (e.g. view-light, view-dark, theme-my-theme-name)
* value is map of rules (key: var name, value: var value)
*/
baseCss: undefined,
/**
* Indicator if the current theme is based on dark view or light view.
* To also set the UI element accordingly use the function setThemeView(viewDark: boolean).
*/
themeBaseDark: false,
themeBaseSelector: undefined,
/**
* container for textarea to import/export themes.
*/
inOutStyleSheetEl: undefined,
/**
* textarea to import/export themes.
*/
inOutTextarea: undefined,
/**
* css rule for the applied page styles
*/
pageRules: undefined,
initialize: function () {
// check if page should display the color editor
let initializeColorEditor = false;
for (let table of document.querySelectorAll('table')) {
if (table.rows.length < 2 || table.rows[0].length < 3) continue;
// the color table contains "Variable name" in first cell
if (table.rows[0].cells[0].textContent.trim() !== 'Variable name') continue;
const secondRowFirstCell = table.rows[1].cells[0];
if (secondRowFirstCell.innerText.match(/^--[-\w]+$/)) {
initializeColorEditor = true;
break;
}
}
if (!initializeColorEditor) return;
this.pageRules = this.addPreviewStyleElement(document);
// define variables
this.variableInfo = new Map()
this.previewPopups = [];
this.baseCss = new Map();
this.addToolbar();
this.colorPicker = new this.ColorPicker(document.body);
this.parseVariables();
this.parseBaseThemes();
this.addThemesToSelector();
this.initializeVariables();
},
/**
* Creates a style element in the document head where the variable values are stored to be visible.
* @param {document} doc
* @returns
*/
addPreviewStyleElement: function (doc) {
//this.createElementAndAdd('style', null, doc.head, null, null, { type: 'text/css' });
const styleElement = doc.createElement('style');
styleElement.setAttribute('type', 'text/css');
styleElement.setAttribute('id', 'tcolor-editor-styles');
doc.head.appendChild(styleElement);
styleElement.sheet.insertRule(':root {}');
return styleElement.sheet.cssRules[0].style;
},
//#region color parsing
/**
* Parses a color from a string, accepts input like '#ff113a', 'rgb(24, 144, 0)', rgba(120, 20, 80, 0.5).
* @param {string} colorRepresentation
* @returns {number[] | null} color as number[], e.g. [24, 144, 0] or null if invalid.
*/
parseColor: function (colorRepresentation) {
if (!colorRepresentation) return null;
if (colorRepresentation.startsWith('#'))
return this.hexToRgb(colorRepresentation.substring(1));
// try parsing other color formats
const colorRgb = this.rgbParenthesisToRgb(colorRepresentation);
if (colorRgb) return colorRgb;
// unsupported color format, maybe dependent on other colors or vars
console.warn(`couldn't parse color ${colorRepresentation}`);
return null;
},
/**
* Parses an RGB color string in the format 'rgb(39, 34, 102)' or 'color(srgb 0.4, 1, 0.2)'.
* @param {string} rgbString
* @returns {number[] | null} RGB values as an array, or null if parsing fails.
*/
rgbParenthesisToRgb: function (rgbString) {
let rgbMatch = rgbString.match(/(?:rgba?\()?(\d+)[\s,]+(\d+)[\s,]+(\d+)(?:[\s,]+([\d.]+))?\)?/);
if (rgbMatch) {
const rgb = rgbMatch.slice(1, 4).map(Number);
rgb.push(rgbMatch[4] === undefined ? 1 : Number(rgbMatch[4]));
return rgb;
}
// parse e.g. color(srgb 0.4 1 0.2)
rgbMatch = rgbString.match(/color\(srgb\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)(?:\s+\/\s+([\d.]+))?\)?/);
if (rgbMatch) {
const rgb = rgbMatch.slice(1, 4).map(v => Math.round(parseFloat(v) * 255));
rgb.push(rgbMatch[4] === undefined ? 1 : Number(rgbMatch[4]));
return rgb;
}
console.warn(`couldn't parse color ${rgbString}`);
return null;
},
/**
* Parses a color given with 3 or 6 hex digits (without #).
* @param {string} hexString
* @param {boolean} logErrors (optional) whether to log errors.
* @returns {number[] | null} RGB values as an array, or null if invalid.
*/
hexToRgb: function (hexString, logErrors = true) {
if (!hexString) return null;
if (hexString.length == 3 || hexString.length == 4) {
// convert 3-digit hex to 6-digit hex ("rgb" -> "rrggbb")
hexString = hexString.split('').map(c => c + c).join('');
}
// ensure it's a valid hex color code
if (!/^[\dA-Fa-f]{6}(?:[\dA-Fa-f]{2})?$/.test(hexString)) {
if (logErrors)
console.warn(`Invalid hex color format: ${hexString}. Use rgb, rrggbb, rgba or rrggbbaa format.`);
return null;
}
return [
parseInt(hexString.slice(0, 2), 16),
parseInt(hexString.slice(2, 4), 16),
parseInt(hexString.slice(4, 6), 16),
hexString.length == 8 ? parseInt(hexString.slice(6, 8), 16) / 255 : 1
];
},
/**
* Converts a color byte array to the hex string representation including the hash.
* E.g. [1, 255, 8] => '#01ff08'
* @param {byte[]} rgb
* @param {boolean} prependHash if true (default) a hash char is prepended to the output string.
* @returns {string} hex string
*/
rgbToHexString: function (rgb, prependHash = true) {
if (!rgb || rgb.length < 3) return null;
const alphaPart = rgb.length == 4 && rgb[3] < 1 ? Math.round(rgb[3] * 255).toString(16).padStart(2, '0') : '';
return (prependHash ? '#' : '') + rgb.slice(0, 3).reduce((result, color) => result + color.toString(16).padStart(2, '0'), '') + alphaPart;
},
/**
* Converts an rgb array to a comma separated string, used for the --rgb variables. Ignores alpha.
* @param {byte[]} rgb
* @returns {string}
*/
rgbArrayToRgbCsvString: function (rgb) {
if (!rgb) return '';
return `${rgb[0]},${rgb[1]},${rgb[2]}`
},
hsvToRgb: function ([h, s, v], alpha = 1) {
let f = (n) => {
let k = (n + h / 60) % 6;
return Math.round(v * (1 - s * Math.max(Math.min(k, 4 - k, 1), 0)) * 255);
};
s /= 100;
v /= 100;
return [f(5), f(3), f(1), alpha];
},
/**
* h [0,360], s [0,100], l [0,100]
*/
hslToRgb: function ([h, s, l], alpha = 1) {
let f = (n) => {
let k = (n + h / 30) % 12;
return Math.round((l - s * Math.min(l, 1 - l) * Math.max(Math.min(k - 3, 9 - k, 1), -1)) * 255);
};
s /= 100;
l /= 100;
return [f(0), f(8), f(4), alpha];
},
/**
* Converts an rgb color to its hsv and hsl components, the hue is the same and ommited for hsl.
* @param {number[]} rgb rgb channels, each in range 0-255.
* @returns {number[]} color components in array: [hue, saturation_hsv, value, saturation_hsl, lightness].
*/
rgbToHsvSl: function ([r, g, b]) {
r /= 255;
g /= 255;
b /= 255;
let max = Math.max(r, g, b),
min = Math.min(r, g, b),
d = max - min,
h,
s = max === 0 ? 0 : d / max,
v = max;
switch (max) {
case min:
h = 0;
break;
case r:
h = (60 * (g - b) / d + 360) % 360;
break;
case g:
h = (60 * (b - r) / d + 120) % 360;
break;
case b:
h = (60 * (r - g) / d + 240) % 360;
break;
}
return [
Math.round(h),
Math.round(s * 100),
Math.round(v * 100),
Math.round(max == min ? 0 : 100 * d / (1 - Math.abs(max + min - 1))),
Math.round((max + min) * 50)
];
},
/**
* Mixes colors using specified relative fractions. If no fractions given, the colors are mixed with equal parts.
* @param {number[][]} rgbColors
* @param {number[]?} mixFractions
* @returns
*/
mixColors: function (rgbColors, mixFractions) {
if (!rgbColors) return [0, 0, 0];
const mixedColor = [0, 0, 0, 0];
let weightingSum = 0;
for (let i = 0; i < rgbColors.length; i++) {
const weight = (mixFractions && mixFractions.length > i) ? mixFractions[i] : 1;
if (weight <= 0) continue;
const addColorRgb = rgbColors[i];
if (!addColorRgb) continue;
weightingSum += weight;
mixedColor[0] += addColorRgb[0] * weight;
mixedColor[1] += addColorRgb[1] * weight;
mixedColor[2] += addColorRgb[2] * weight;
mixedColor[3] += addColorRgb[3] * weight;
}
if (weightingSum == 0) return [0, 0, 0];
mixedColor[0] = Math.round(mixedColor[0] / weightingSum);
mixedColor[1] = Math.round(mixedColor[1] / weightingSum);
mixedColor[2] = Math.round(mixedColor[2] / weightingSum);
mixedColor[3] = mixedColor[3] / weightingSum;
return mixedColor;
},
/**
* Inverse of the color.
* @param {number[]} rgb
*/
invertedColor: function (rgb) {
if (!rgb) return null;
return [255 - rgb[0], 255 - rgb[1], 255 - rgb[2], rgb[3]];
},
/**
* Inverts a color gradually, 1: inverse, 0: no change.
* @param {number[]} rgb
* @param {number} amount
* @returns {number[] | null} gradually inverted rgb
*/
invert: function (rgb, amount = 1) {
if (!rgb) return null;
amount = Math.max(0, Math.min(1, amount));
if (amount == 0) return rgb;
if (amount == 1) return this.invertedColor(rgb);
return [
Math.round(rgb[0] + amount * (255 - 2 * rgb[0])),
Math.round(rgb[1] + amount * (255 - 2 * rgb[1])),
Math.round(rgb[2] + amount * (255 - 2 * rgb[2])),
rgb[3]
];
},
/**
* Hue rotation of color using hsl transformation.
* @param {number[]} rgb
* @param {number} hueRotate in deg, full circle is 360.
*/
hueRotate: function (rgb, hueRotate) {
if (!rgb) return null;
if (!hueRotate) return rgb;
const hsvsl = this.rgbToHsvSl(rgb);
return this.hslToRgb([hsvsl[0] + hueRotate, hsvsl[3], hsvsl[4]], rgb[3]);
},
/**
* Change hsl parameters of color.
* @param {number[]} rgb
* @param {number} hueRotate in deg, full circle is 360
* @param {number} saturationFactor 0: no saturation, 1: no change, >1: more saturation
* @param {number} lightnessFactor 0: black, 1: no change, >1: lighter
*/
adjustHsl: function (rgb, hueRotate = 0, saturationFactor = 1, lightnessFactor = 1) {
if (!rgb) return null;
const hsvsl = this.rgbToHsvSl(rgb);
return this.hslToRgb(
[
hsvsl[0] + (hueRotate === undefined ? 0 : hueRotate),
saturationFactor === undefined ? hsvsl[3] : Math.min(100, Math.max(0, hsvsl[3] * saturationFactor)),
lightnessFactor === undefined ? hsvsl[4] : Math.min(100, Math.max(0, hsvsl[4] * lightnessFactor))
],
rgb[3]
);
},
/**
* Inverse lightness of the color.
* @param {number[]} rgb
*/
inverseLightnessOfColor: function (rgb) {
if (!rgb) return null;
const hsvsl = this.rgbToHsvSl(rgb);
return this.hslToRgb([hsvsl[0], hsvsl[3], 100 - hsvsl[4]], rgb[3]);
},
/**
* Inverse relative luminance of the color.
* @param {number[]} rgb
*/
inverseLuminanceOfColor: function (rgb) {
if (!rgb) return null;
return this.setRelativeLuminance(rgb, 1 - this.relativeLuminance(rgb));
},
/**
* Returns true if the first 4 elements of the arrays are equal.
* @param {number[]} rgb1
* @param {number[]} rgb2
*/
rgbEqual: function (rgb1, rgb2) {
if (!rgb1 && !rgb2) return true;
if (!rgb1 || !rgb2) return false;
return rgb1[0] == rgb2[0]
&& rgb1[1] == rgb2[1]
&& rgb1[2] == rgb2[2]
&& rgb1[3] == rgb2[3];
},
//#endregion
//#region theme functions
/**
* parses the base variable values for set views and themes
*/
parseBaseThemes: function () {
const stylesheets = [...document.styleSheets];
for (const sheet of stylesheets) {
try {
for (const rule of sheet.cssRules) {
if (!rule.selectorText) continue;
const selectors = rule.selectorText.split(',');
selectors.forEach((s) => {
let selectorName = s.trim();
if (!selectorName
|| (selectorName !== ':root'
&& selectorName !== 'html'
&& selectorName !== '.view-light'
&& selectorName !== '.view-dark'
&& !selectorName.startsWith('.theme-'))
) return;
if (selectorName === 'html')
selectorName = 'root';
else
selectorName = selectorName.substring(1); // remove colon or dot
if (!this.baseCss.has(selectorName))
this.baseCss.set(selectorName, new Map());
const ruleProperties = this.baseCss.get(selectorName);
const ruleCount = rule.style.length;
for (let i = 0; i < ruleCount; i++) {
const propName = rule.style[i];
const propNameWithOutRgb = propName.endsWith('--rgb') ? propName.substring(0, propName.length - 5) : undefined;
if (this.variableInfo.has(propName)
|| (propNameWithOutRgb && this.variableInfo.has(propNameWithOutRgb))) {
ruleProperties.set(propName, rule.style.getPropertyValue(propName).trim());
}
}
});
}
} catch (e) {
console.warn('cannot access stylesheet: ', e);
}
}
// use view-light and view-dark as base, apply missing root variables
const rootStyles = this.baseCss.get('root');
const viewLight = this.baseCss.get('view-light');
const viewDark = this.baseCss.get('view-dark');
rootStyles.forEach((v, k) => {
if (viewLight && !viewLight.has(k)) {
viewLight.set(k, v);
}
if (viewDark && !viewDark.has(k)) {
viewDark.set(k, v);
}
});
},
/**
* Adds an option entry to the select element for each theme.
*/
addThemesToSelector: function () {
this.baseCss.forEach((_, k) => {
const o = document.createElement('option');
o.value = o.innerHTML = k;
this.themeBaseSelector.appendChild(o);
});
},
/**
* Sets all variables to the values of a preset theme.
* @param {string} themeName
* @returns {boolean} whether the theme could be applied.
*/
applyTheme: function (themeName) {
//console.log(`applying variable values of theme or view: ${themeName}`);
// first set light or dark base values
if (themeName != 'root' && themeName != 'view-light' && themeName != 'view-dark')
this.applyTheme(this.themeBaseDark ? 'view-dark' : 'view-light');
if (!themeName) {
console.warn(`cannot apply styles, themeName was empty`);
return false;
}
const theme = this.baseCss.get(themeName);
if (!theme) {
console.warn(`no theme with name "${themeName}" found to apply.`);
return false;
}
const setAsBaseValues = themeName === 'root' || themeName === 'view-light' || themeName === 'view-dark';
theme.forEach((v, k) => {
const varInfo = this.variableInfo.get(k);
if (varInfo)
varInfo.setValue(v, setAsBaseValues);
});
this.setBackgroundImageExplicitly();
return true;
},
/**
* Applies the base values of a view, i.e. it does not change the set values, only the value a variable can be reset to. This has an effect on if a variable is saved or not, if it's equal to its base.
* @param {string} viewName view-light or view-dark
*/
applyThemeAsBase: function (viewName) {
if (viewName != 'view-light' && viewName != 'view-dark') return;
const theme = this.baseCss.get(viewName);
if (!theme) {
console.warn(`no view with name "${viewName}" found to apply.`);
return;
}
theme.forEach((v, k) => {
const varInfo = this.variableInfo.get(k);
if (varInfo)
varInfo.setBaseValue(v);
});
this.setBackgroundImageExplicitly();
},
/**
* Reads the variable values of the currently selected theme by the wiki theme-selector
* and applies the variable values to the editor variables.
*/
applyValuesOfCurrentPageTheme() {
// get styles of theme selector
const themeStyleEl = document.getElementById('mw-themetoggle-styleref');
if (!themeStyleEl) {
console.warn('theme selector style element with id mw-themetoggle-styleref not found. Cannot apply theme selector styles.');
return;
}
const sheetRules = themeStyleEl.sheet.cssRules;
if (!sheetRules) {
console.warn('theme selector styles not found in (mw-themetoggle-styleref).sheet.cssRules not found. Cannot apply theme selector styles.');
return;
}
// clear editor style element so current wiki theme styles are valid and can be read
const tceStylesElement = document.getElementById('tcolor-editor-styles');
if (tceStylesElement && tceStylesElement.sheet.length > 0)
tceStylesElement.sheet.deleteRule(0);
const sheetRulesArray = [];
for (let i = 0; i < sheetRules.length; i++) {
const sr = sheetRules[i];
if (sr.selectorText && (sr.selectorText.includes(':root') || sr.selectorText.includes('html')))
sheetRulesArray.push(sr);
}
// first collect values without updating it
const varValues = new Map();
this.variableInfo.forEach(v => {
let varValue = '';
sheetRulesArray.forEach(sr => {
const varValueRule = sr.style.getPropertyValue(v.name);
if (varValueRule) varValue = varValueRule;
});
if (varValue)
varValues.set(v.name, varValue);
});
if (varValues.length == 0) {
console.warn('the theme selector element with id mw-themetoggle-styleref did not contain any values for the used variables.');
return;
}
if (tceStylesElement) {
// When selecting a theme of an external file, a new head element may be added where the styles are loaded.
// Make sure the styles of this editor are the last style element.
document.head.appendChild(tceStylesElement);
tceStylesElement.sheet.insertRule(':root {}'); // re add previously deleted rule
this.pageRules = tceStylesElement.sheet.cssRules[0].style;
}
this.previewPopups.forEach(p => {
const styleElement = p.w.document.getElementById('tcolor-editor-styles');
if (styleElement)
styleElement.remove();
p.s = this.addPreviewStyleElement(p.w.document);
});
// update variable values
this.variableInfo.forEach(v => {
const varValue = varValues.get(v.name);
if (varValue)
v.setValue(varValue);
});
// update background if it was changed by the theme
this.setBackgroundImageExplicitly();
},
/**
* Set the background-image property of the body element explicitly to its calculated value.
* Usually the background-image is set via a variable (e.g. --wiki-body-background-image).
* Setting the value explicitly will prevent flickering of the background-image if color variables are adjusted in a high frequency and a preview window is opened.
* @param {window} win
* @param {string} backgroundStyle
*/
setBackgroundImageExplicitly: function () {
document.body.style.removeProperty('background'); // remove previously explicitly set property
const computedBodyBackground = getComputedStyle(document.body).background;
if (computedBodyBackground.includes('url')) {
document.body.style.setProperty('background', computedBodyBackground);
this.previewPopups.forEach((p) => p.w.document.body.style.setProperty('background', computedBodyBackground));
} else {
this.previewPopups.forEach((p) => p.w.document.body.style.removeProperty('background'));
}
},
invertAllLightness: function (useLuminance = false) {
if (useLuminance)
this.variableInfo.forEach((v) => {
if (!v.useIndirectDefinition)
v.setColor(this.inverseLuminanceOfColor(v.rgb));
});
else
this.variableInfo.forEach((v) => {
if (!v.useIndirectDefinition)
v.setColor(this.inverseLightnessOfColor(v.rgb));
});
// adjust view the theme is based on (view-light or view-dark)
// if variable --wiki-content-text-color is available, use that as indicator (dark text: view-light and vice versa)
// if that variable is not existing, just toggle the view
let useViewDark = undefined;
const defaultVarTextColor = this.variableInfo.get('--wiki-content-text-color');
if (defaultVarTextColor) {
useViewDark = this.rgbToHsvSl(defaultVarTextColor.rgb)[4] > 50; // use dark-view if lightness of text color is larger than 50%
} else {
useViewDark = !this.themeBaseDark;
}
this.setThemeView(useViewDark);
this.applyThemeAsBase(this.themeBaseDark ? 'view-dark' : 'view-light')
},
applyAllSuggestions: function () {
this.variableInfo.forEach((v) => {
v.setValueByDefinition();
});
},
importStyles: function (useLightView) {
const varMatches = Array.from(this.inOutTextarea.value.matchAll(/(--[-\w]+)\s*:\s*([^;]+)\s*;(?:[ \t]*\/\*[ \t]*\{([^}]+)\}[ \t]*\*\/)?/g));
if (varMatches.length == 0) {
console.warn(`couldn't import, no variable definitions found in the input\n${this.inOutTextarea.value}`);
return;
}
if (useLightView) this.applyTheme('view-light');
else this.applyTheme('view-dark');
varMatches.forEach((m) => {
const varInfo = this.variableInfo.get(m[1]);
if (!varInfo) {
if (!m[1].endsWith('--rgb'))
console.log(`var ${m[1]} not found in given variables, couldn't apply value`);
return;
}
varInfo.setValue(m[2]);
if (m[3]) {
const optionMatches = Array.from(m[3].matchAll(/(saveExplicitRgbInOutput|invert|hueRotate|saturationFactor|lightnessFactor) *: *(\d+(?:\.\d+)?)/g));
if (optionMatches.length > 0) {
// first set to default
const options = new Map();
options.set('saveExplicitRgbInOutput', false);
options.set('optionInvert', false);
options.set('optionHueRotate', 0);
options.set('optionSaturationFactor', 1);
options.set('optionLightnessFactor', 1);
optionMatches.forEach(optionMatch => {
let parsedNumber;
switch (optionMatch[1]) {
case 'saveExplicitRgbInOutput':
options.set('saveExplicitRgbInOutput', !!optionMatch[2]);
break;
case 'invert':
options.set('optionInvert', !!optionMatch[2]);
break;
case 'hueRotate':
parsedNumber = parseFloat(optionMatch[2]);
if (isNaN(parsedNumber)) parsedNumber = 0;
options.set('optionHueRotate', parsedNumber);
break;
case 'saturationFactor':
parsedNumber = parseFloat(optionMatch[2]);
if (isNaN(parsedNumber)) parsedNumber = 0;
options.set('optionSaturationFactor', parsedNumber);
break;
case 'lightnessFactor':
parsedNumber = parseFloat(optionMatch[2]);
if (isNaN(parsedNumber)) parsedNumber = 0;
options.set('optionLightnessFactor', parsedNumber);
break;
}
});
for (const [option, value] of options) {
varInfo[option] = value;
}
}
}
});
// close import textarea
this.inOutStyleSheetEl.classList.toggle('transition-hide', true);
},
/**
* Exports current styles.
* @param {boolean} returnText If true the generated style text is returned. If false, the text is displayed in a textarea.
*/
exportStyles: function (returnText = false) {
const varDefinitions = [];
const exportIncludeExplicitOptions = this.exportIncludeExplicitOptions;
this.variableInfo.forEach((v) => {
let explicitDefinition = null;
if (exportIncludeExplicitOptions) {
const options = [];
if (v.saveExplicitRgbInOutput) options.push('saveExplicitRgbInOutput: 1');
if (v.optionInvert !== undefined) options.push('invert: 1');
if (v.optionHueRotate !== undefined) options.push('hueRotate: ' + v.optionHueRotate);
if (v.optionSaturationFactor !== undefined) options.push('saturationFactor: ' + v.optionSaturationFactor);
if (v.optionLightnessFactor !== undefined) options.push('lightnessFactor: ' + v.optionLightnessFactor);
if (options.length > 0)
explicitDefinition = options.join(', ');
}
if (!explicitDefinition && !v.valueShouldGoInOutput()) {
//console.log(`skipping output for var ${v.name}, it's equal to base color`);
return;
}
if (exportIncludeExplicitOptions) {
// css output for saving theme definition
varDefinitions.push(`${v.name}: ${v.value};` + (explicitDefinition ? ` /* {${explicitDefinition}} */` : ''));
} else {
// css ouput for wiki
varDefinitions.push(`${v.name}: ${v.valueStringOutput()};`);
if (this.exportIncludeRgbVariants && v.hasFormatRgb)
varDefinitions.push(`${v.name}--rgb: ${v.valueColorAsCommaRgbString()};`);
if (v.name == '--wiki-content-link-color') {
varDefinitions.push(`--wiki-icon-to-link-filter: ${this.filterCreator.calculateFilter(v.rgb).filterString};`);
}
}
});
const styleText = varDefinitions.length == 0 ? '/* no variables where different from the base theme, nothing to export. */'
: '.theme-myThemeName {\n ' + varDefinitions.join('\n ') + '\n}\n';
if (returnText) return styleText;
this.inOutTextarea.value = styleText;
},
//#endregion
//#region general utils
roundToDigits: function (val, digits) {
const power = Math.pow(10, digits);
return Math.round(val * power) / power;
},
/**
* Throttles a function call, calls after the cooldown again if called during cooldown
* @param {function} functionToThrottle
* @param {number} delay
* @returns throttled function
*/
throttle: function (functionToThrottle, delay = 50) {
let isInCooldown = false;
let callAfterThrottle = false;
return (...args) => {
if (isInCooldown) {
callAfterThrottle = true;
return;
}
functionToThrottle(...args);
isInCooldown = true;
callAfterThrottle = false;
setTimeout(nextPossibleCall, delay);
function nextPossibleCall() {
if (callAfterThrottle) {
callAfterThrottle = false;
functionToThrottle(...args);
setTimeout(nextPossibleCall, delay);
return;
}
isInCooldown = false;
}
};
},
/**
* Debounces a function, it will only execute when the function was not called for some time.
* @param {function} functionToDebounce
* @param {number} waitFor
*/
debounce: function (functionToDebounce, waitFor = 500) {
let timerId;
return (...args) => {
clearTimeout(timerId);
timerId = setTimeout(() => functionToDebounce.apply(this, args), waitFor);
}
},
//#endregion
//#region controls
addToolbar: function () {
const toolBarElement = document.createElement('div');
toolBarElement.className = 'tcolor-editor-toolbar tcolor-editor-control';
document.body.appendChild(toolBarElement);
// global color tools
const divTools = this.createElementAndAdd('div', 'tcolor-editor-groupbox', toolBarElement);
this.createElementAndAdd('span', 'tcolor-editor-groupbox-heading', divTools, null, 'global color tools');
this.createElementAndAdd('span', 'tcolor-editor-toolbarText', divTools,
'Select on which view the theme is based on (light or dark).\nThis has an effect whether a variable will be in the output or not\n(variables equal to their base value of the view will not be included in the output).',
'theme based on');
const viewToggleEl = this.createCheckbox('view-light',
(e) => {
this.setThemeView(e.target.checked);
this.applyThemeAsBase(this.themeBaseDark ? 'view-dark' : 'view-light');
},
'view the theme is based on', true);
divTools.appendChild(viewToggleEl);
this.createElementAndAdd('div', 'tcolor-editor-separator', divTools);
this.setThemeView = (viewDark = false) => {
this.themeBaseDark = viewDark;
viewToggleEl.firstChild.checked = viewDark; // viewToggleEl is label, firstChild is the input:checkbox
viewToggleEl.lastChild.nodeValue = viewDark ? 'view-dark' : 'view-light';
};
let bt = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divTools,
'Inverts the lightness of all colors (switching dark <-> light)\nThe base view (dark or light theme) is also toggled. If that is not correct you can change that using the "rebase" button after setting the view toggle button.', 'invert all color\'s lightness');
bt.addEventListener('click', () => this.invertAllLightness());
bt = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divTools,
'Applies all suggested values to according values.\nThis affects usually black/white base colors and secondary colors dependant on other colors.\nThis can be done when starting a color theme, later it might overwrite changes you already made.',
'apply all suggestions');
bt.addEventListener('click', () => this.applyAllSuggestions());
// theme loader
const divThemeSelector = this.createElementAndAdd('div', 'tcolor-editor-groupbox', toolBarElement);
this.createElementAndAdd('span', 'tcolor-editor-groupbox-heading', divThemeSelector, null, 'themes');
this.themeBaseSelector = this.createElementAndAdd('select', null, divThemeSelector);
bt = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divThemeSelector,
'Sets all variables to the values of the selected theme or view in the select control above.', 'load theme variables');
bt.addEventListener('click', () => this.applyTheme(this.themeBaseSelector.options[this.themeBaseSelector.selectedIndex].text));
this.createElementAndAdd('div', 'tcolor-editor-separator', divThemeSelector);
bt = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divThemeSelector,
'Load all variables of the currently selected wiki theme (using the wiki theme-selector at the top of the page).\nIt is recommended to do this after loading a theme from a separate file with the theme-selector.\nThis will not reset initially indirect defined values.\nTo do this consider loading a base view (light or dark) first.',
'load wiki theme variables');
bt.addEventListener('click', () => this.applyValuesOfCurrentPageTheme());
// import export
const divImportExport = this.createElementAndAdd('div', 'tcolor-editor-groupbox', toolBarElement);
this.createElementAndAdd('span', 'tcolor-editor-groupbox-heading', divImportExport, null, 'import/export css');
divImportExport.appendChild(this.createCheckbox('include --rgb',
(e) => { this.exportIncludeRgbVariants = e.target.checked; },
'Include --rgb color variables for variables that have them.'));
this.createElementAndAdd('br', null, divImportExport);
divImportExport.appendChild(this.createCheckbox('include explicit adjustments',
(e) => { this.exportIncludeExplicitOptions = e.target.checked; },
'Include color options set for explicit color adjustments (e.g. invert, hue-rotate).\nThis should be only enabled if you want to save your work and import later.\nThis should not be enabled to export the css for use on a wiki.'));
const inOutButton = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divImportExport, null, 'input-output view toggle');
inOutButton.addEventListener('click', () => this.inOutStyleSheetEl.classList.toggle('transition-hide'));
bt = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divImportExport, null, 'copy styles to clipboard');
bt.addEventListener('click', () => navigator.clipboard.writeText(this.exportStyles(true)));
// in out element
this.inOutStyleSheetEl = this.createElementAndAdd('div', 'tcolor-editor-control tcolor-editor-center-popup transition-show transition-hide', document.body);
this.createElementAndAdd('div', null, this.inOutStyleSheetEl, null, 'css import/export');
bt = this.createElementAndAdd('div', 'tcolor-editor-close-button', this.inOutStyleSheetEl, null, '×');
bt.addEventListener('click', (e) => e.target.parentElement.classList.toggle('transition-hide', true));
this.inOutTextarea = this.createElementAndAdd('textarea', null, this.inOutStyleSheetEl, null, null, { 'rows': '20', 'cols': '106' });
const buttonContainer = this.createElementAndAdd('div', null, this.inOutStyleSheetEl);
const btImportLight = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-button-light tcolor-editor-inline', buttonContainer, null, '↷import with light-view as base');
btImportLight.addEventListener('click', () => this.importStyles(true));
const btImportDark = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-inline', buttonContainer, null, '↷import with dark-view as base');
btImportDark.addEventListener('click', () => this.importStyles(false));
const btExport = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-inline', buttonContainer, null, '⮍replace text above with current theme definitions');
btExport.addEventListener('click', () => this.exportStyles());
// live preview controls
const divPreview = this.createElementAndAdd('div', 'tcolor-editor-groupbox', toolBarElement);
this.createElementAndAdd('span', 'tcolor-editor-groupbox-heading', divPreview, null, 'live preview');
let previewPageSavedValue = localStorage.getItem('tcolor-editor-preview-page-name');
if (!previewPageSavedValue) previewPageSavedValue = '';
const previewPageEl = this.createElementAndAdd('input', null, divPreview, 'Enter the name of a wiki page for a live preview of the set colors\nE.g. "Wood", "Main Page" or "Wood?diff=prev&oldid=6699"', 'preview', {
'type': 'text', 'placeholder': 'Wiki page name', 'id': 'tcolor-editor-preview-page-name',
'value': previewPageSavedValue
});
previewPageEl.addEventListener('keyup', (e) => {
if (e.key === 'Enter') this.openPreviewWindow();
});
bt = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', divPreview, null, 'preview popup');
bt.addEventListener('click', () => this.openPreviewWindow());
bt = this.createElementAndAdd('button', 'tcolor-editor-button', divPreview, 'set default popup screen location and size', 'remember popup loc');
bt.addEventListener('click', () => this.saveDefaultPopupLocation());
// shortManual
const shortManual = this.createElementAndAdd('div', 'tcolor-editor-control tcolor-editor-center-popup transition-show transition-hide', document.body);
bt = this.createElementAndAdd('div', 'tcolor-editor-close-button', shortManual, null, '×');
bt.addEventListener('click', (e) => e.target.parentElement.classList.toggle('transition-hide', true));
const manualButton = this.createElementAndAdd('button', 'tcolor-editor-button tcolor-editor-full-width', toolBarElement, 'toggle display of short manual', ' ? ', null,
'align-self: flex-start; padding:0.1em 0.5em; background:linear-gradient(to bottom, #229, #004);');
manualButton.addEventListener('click', () => shortManual.classList.toggle('transition-hide'));
this.createElementAndAdd('div', null, shortManual, null, `
<h2>General info</h2>
<ul>
<li>This tool allows to edit theme colors, but it cannot save it directly to the wiki. To use the colors on the
wiki,
export the css code and save it manually, usually to this page (MediaWiki:common.css).</li>
<li><a href="https://support.wiki.gg/wiki/Theme_Color_Editor" target="_blank">Detailed instructions about the
Theme Color Editor (this tool)</a></li>
<li><a href="https://support.wiki.gg/wiki/Theming" target="_blank">General info about theming a wiki.gg wiki</a>
</li>
<li><a href="https://support.wiki.gg/wiki/Theming#Creating_more_than_one_theme" target="_blank">Section about
using multiple color themes on a wiki</a></li>
</ul>
<h2>Theme Color Editor short manual</h2>
<ul>
<li>In the toolbar set <span class="tcolor-editor-toggle-button" style="cursor:auto">view-light</span> or <span
class="tcolor-editor-toggle-button" style="cursor:auto">view-dark</span></li>
<li>Optionally load an existing theme as starting point</li>
<ul>
<li>If themes all saved in common.css:</li>
<ul>
<li>In the toolbar select the theme and load it with <span class="tcolor-editor-button"
style="cursor:auto; display: inline-block">load theme variables</span></li>
</ul>
<li>If themes saved in separate files:</li>
<ul>
<li>At the top right use the Appearance drop down menu to choose a theme</li>
<li>Load the theme colors via the toolbar button <span class="tcolor-editor-button"
style="cursor:auto; display: inline-block">load wiki theme variables</span></li>
</ul>
</ul>
<li>Adjust colors by clicking on them while making sure the contrasts are fulfilled</li>
<li>Make use of indirect definitions to simplify color adjustments</li>
<li>Export theme to save in common.css or theme-page</li>
<ul>
<li>If wiki styling uses --rgb variables (usually wikis created before 2025), make sure to enable this
checkbox</li>
<li>If indirect definitions should be exported, enable "include explicit adjustments"
checkbox.<br />Enable that only for saving a theme for later (e.g. in a local text file and later import
it for use as base definition for other themes).<br />This option should be disabled when exporting
for wiki styles.</li>
<li>Export themes directly to clipboard with <span class="tcolor-editor-button"
style="cursor:auto; display: inline-block">copy styles to clipboard</span> or using <span class="tcolor-editor-button"
style="cursor:auto; display: inline-block">input-output view toggle</span></li>
</ul>
</ul>
`);
},
//#endregion
/**
* Contains info about a css variable.