-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbackground.js
1818 lines (1581 loc) · 79.9 KB
/
background.js
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
class Common {
static appCompat(res) {
if (uDark.browserInfo.version < 105 && uDark.browserInfo.name == "Firefox") {
res.disable_image_edition = true;
console.warn("UltimaDark", "Image edition is disabled on Firefox versions below 105, as it is not supported");
globalThis.browser.storage.local.set(res);
}
}
static install() {
}
};
class uDarkC extends uDarkExtended {
exportFunction= f => f; // Emulate the exportFunction function of the content script to avoid many ternary operators
logPrefix = "UltimaDark:";
log(...args) {
console.log("%c"+this.logPrefix, "color:white;font-weight:bolder",...args);
};
warn(...args) {
console.warn("%c"+this.logPrefix, "color:yellow;font-weight:bolder",...args);
}
error(text,...args) {
console.error("%c"+this.logPrefix, "color:red;font-weight:bolder",...args,new Error(text));
}
info(...args) {
console.info("%c"+this.logPrefix, "color:lightblue;font-weight:bolder",...args);
}
success(...args) {
console.log("%c"+this.logPrefix, "color:lightgreen;font-weight:bolder",...args);
}
keypoint(...args) {
console.info("%c"+this.logPrefix, "color:lime;font-weight:bolder;font-size:14px",...args);
}
static CSS_COLOR_NAMES = [
//"currentcolor",
"AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "RebeccaPurple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"]
static SHORTHANDS = ["all", "animation", "animation-range", "background", "border", "border-block", "border-block-end", "border-block-start", "border-bottom", "border-color", "border-image", "border-inline", "border-inline-end", "border-inline-start", "border-left", "border-radius", "border-right", "border-style", "border-top", "border-width", "column-rule", "columns", "contain-intrinsic-size", "container", "flex", "flex-flow", "font", "font-synthesis", "font-variant", "gap", "grid", "grid-area", "grid-column", "grid-row", "grid-template", "inset", "inset-block", "inset-inline", "list-style", "margin", "margin-block", "margin-inline", "mask", "mask-border", "offset", "outline", "overflow", "overscroll-behavior", "padding", "padding-block", "padding-inline", "place-content", "place-items", "place-self", "position-try", "scroll-margin", "scroll-margin-block", "scroll-margin-inline", "scroll-padding", "scroll-padding-block", "scroll-padding-inline", "scroll-timeline", "text-decoration", "text-emphasis", "text-wrap", "transition"]
static TAGS_TO_PROTECT = ["head", "html", "body", "frameset", "frame"]
static CSS_COLOR_FUNCTIONS = ["rgb", "rgba", "hsl", "hsla", "hwb", "lab", "lch", "color", "color-mix", "oklch", "oklab"]
shortHandRegex = new RegExp(`(?<![\\w-])(${uDarkC.SHORTHANDS.join("|")})([\s\t]*:)`, "gi") // The \t is probably not needed, as \s includes it
tagsToProtectRegex = new RegExp(`(?<![\\w-])(${uDarkC.TAGS_TO_PROTECT.join("|")})(?![\\w-])`, "gi")
// How much the color syntax can be complex: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#formal_syntax
fastColorRegex = new RegExp(`(?<![\\w-])(${uDarkC.CSS_COLOR_FUNCTIONS.join("|")})\\(.*?\\)`, "gi")
static colorWorkSource = {
canvasWidth: 5,
canvasHeight: 3,
}
colorWork = {
canvasContext: (() => {
let canvas = document.createElement("canvas");
canvas.width = 5;
canvas.height = 3;
return canvas.getContext("2d");
})()
}
attributes_function_map = {
"color": (r, g, b, a, render, elem) => {
elem.style.p_ud_setProperty("--ud-html4-color", uDark.revert_rgba(r, g, b, a, render));
elem.setAttribute("ud-html4-support", true);
elem.removeAttribute("color");
},
"text": "color",
"bgcolor": this.rgba
}
colorRegex = new RegExp(`(?<![\\w-])(?:${uDarkC.CSS_COLOR_FUNCTIONS.join("|")})` + uDarkC.generateNestedParenthesisRegexNC(10), "gi")
hexadecimalColorsRegex = /#[0-9a-f]{3,4}(?:[0-9a-f]{2})?(?:[0-9a-f]{2})?/gi // hexadecimal colors
// Cant't use \b because of the possibility of a - next to the identifier, it's a word character
namedColorsRegex = (new RegExp(`(?<![\\w-])(${uDarkC.CSS_COLOR_NAMES.join("|")})(?![\\w-])`, "gi"))
regex_search_for_url = /url\("(.+?)(?<!\\)("\))/g
regex_search_for_url_raw = /url\(\s*?(('.+?(?<!\\)'|(".+?(?<!\\)")|[^\)'"]*)\s*?)\)/gsi
background_match = /background|sprite|(?<![a-z])(bg|box|panel|fond|fundo|bck)(?![a-z])/i
logo_match = /nav|avatar|logo|icon|alert|notif|cart|menu|tooltip|dropdown|control/i
background_color_css_properties_regex = /color|fill|(?:box|text)-shadow|border|^background(?:-image|-color)?$|^--ud-ptd-background/ // Background images can contain colors // css properties that are background colors
exactAtRuleProtect = true
matchAllCssCommentsRegex = /\/\*[^*]*\*+([^/*][^*]*\*+)*\/|\/\*[^*]*\*+([^/*][^*]*\*+)*|\/\*[^*]*(\*+[^/*][^*]*)*/g
// At-rules : https://developer.mozilla.org/fr/docs/Web/CSS/At-rule
// @charset, @import or @namespace, followed by some space or \n, followed by some content, followed by a code block a semicolon; or end of STRING
// Surpisingly and fortunately end of LINE does not delimits the end of the at-rule and forces devs & minifers either to add a ; or end of STRING
// which and fortunately simplifies a LOT the handling
// See https://www.w3.org/TR/css-syntax-3/#block-at-rule ( Block at-rules )
// 'm' flag is not set on purpose to avoid matching $ as a line end, and keeping it at end of STRING
// Content must not be interupted while between quotes or parenthesis.
// It wont break on string ("te\"st") or this one('te\'st') or @import ('abc\)d;s'); thanks to
// priority matches (\\\)) and (\\') and (\\")
//-------------------v-Rule name----space or-CR--v-----v--Protected values-v----v-the content dot
cssAtRulesRegex = /@(charset|import|namespace)(\n|\s)+((\((\\\)|.)+?\))|("(\\"|.)+?")|('(\\'|.)+?')|.)+?({.+?}|;|$)/gs
direct_window_export = true
general_cache = new Map()
userSettings = {}
imageSrcInfoMarker = "_uDark"
imageWorkerJsFile = "imageWorker.js"
min_bright_fg = 0.65 // Text with luminance under this value will be brightened
max_bright_fg = 1 // Text over this value will be darkened
brightness_peak_editor_fg = 0.5 // Reduce the brightness of texts with intermediate luminace, tying to achieve better saturation
hueShiftfg = 0 // Hue shift for text, 0 is fno shift, 360 is full shift
min_bright_bg_trigger = 0.2 // backgrounds with luminace under this value will remain as is
min_bright_bg = 0.1 // background with value over min_bright_bg_trigger will be darkened from this value up to max_bright_bg
max_bright_bg = 0.4 // background with value over min_bright_bg_trigger will be darkened from min_bright_bg up to this value
foreground_color_css_properties = ["color"] // css properties that are foreground colors
// Gradients can be set in background-image
static generateNestedParenthesisRegex(depth) { // Generates a regex that matches nested parenthesis
if (depth === 1) {
return "\\((.)*?\\)";
}
return `\\((${uDarkC.generateNestedParenthesisRegex(depth - 1)}|.)*?\\)`;
}
static generateNestedParenthesisRegexNC(depth) { // Generates a regex that matches nested parenthesis, non-capturing
if (depth === 1) {
return "\\(.*?\\)";
}
return `\\((?:${uDarkC.generateNestedParenthesisRegexNC(depth - 1)}|.)*?\\)`;
}
css_properties_wording_action_dict = {
"mix-blend-mode": {
replace: ["multiply", "normal"]
},
"scrollbar-color": {
remove: 1
},
"color-scheme": {
replace: ["light", "dark"]
},
"fill": {
// TODO: Needs rework since we replaced prefix_fg_vars by prefix_vars
callBacks: [(cssStyle, cssRule, details, options) => {
let value = cssStyle.getPropertyValue("fill");
this.edit_all_cssRule_colors_cb(cssRule, "color", value, options, {
key_prefix:"--ud-fg--fill-",
l_var: "--uDark_transform_lighten",
fastValue0:true
})
}]
},
"mask-image": {
stickConcatToPropery: {
sValue: "url(",
rKey: "filter",
stick: "brightness(10)"
}
},
"background-image": {
callBacks: [this.edit_css_urls]
},
"background": {
callBacks: [this.edit_css_urls]
},
"--ud-ptd-background": {
variables: {
property: "--ud-ptd-background",
regex: this.regex_search_for_url_raw,
use_other_property: "background-image",
originalProperty: "background"
},
callBacks: [this.edit_css_urls]
},
// Not good for wayback machine time selector
// "color":{ stickConcatToPropery: {sValue:"(",rKey:"mix-blend-mode", stick:"difference"}}, // Not good for wayback machine time selector
// "position":{ stickConcatToPropery: {sValue:"fixed",rKey:"filter", stick:"contrast(110%)"}}, // Not good for wayback machine time selector
}
/*
Took comments from w3.org/csswg-drafts/css-syntax-3/#comments
First part: \/\*[^*]*\*+([^/*][^*]*\*+)*\/ — This matches valid CSS comments.
Second part: \/\*[^*]*\*+([^/*][^*]*\*+)* — This matches incomplete comments that look like they are improperly closed (badcomment1).
Third part: \/\*[^*]*(\*+[^/*][^*]*)* — This also matches another form of incomplete comments (badcomment2).
*/
edit_css(cssStyleSheet, details, options = {}) {
if (!details) {
details = {};
}
if (!details.transientCache) {
details.transientCache = new Map();
}
uDark.edit_cssRules(cssStyleSheet.cssRules, details, options);
}
str_protect(str, regexSearch, protectWith) {
// sore values into an array:
var values = str.match(regexSearch);
if (values) {
str = str.replace(regexSearch, protectWith);
}
return {
str,
values,
protectWith
};
}
str_unprotect(str, protection) {
if (protection.values) {
protection.values.forEach((value, index) => {
// I've learnt the hard way to care about some $' or $1 the protected value:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement
// This is why we use a function to replace the protected value
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement
str = str.replace(protection.protectWith, () => value);
})
}
return str;
}
str_protect_numbered(str, regexSearch, protectWith, condition = true) {
// sore values into an array:
if (!condition) {
return false;
}
var values = str.match(regexSearch);
if (values) {
let index = 0;
str = str.replace(regexSearch, function(match, g1) {
return protectWith.replace("{index}", index++);
});
}
return {
str,
values,
protectWith
};
}
str_unprotect_numbered(str, protection, condition = true) {
if (protection.values && condition) {
protection.values.forEach((value, index) => {
// I've learnt the hard way tto care about some $' or $1 the protected value:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_the_replacement
// This is why we use a function to replace the protected value
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_function_as_the_replacement
str = str.replace(protection.protectWith.replace("{index}", index), () => value);
})
}
return str;
}
sRGBtoLin(colorChannel) {
// Send this function a decimal sRGB gamma encoded color value
// between 0.0 and 1.0, and it returns a linearized value.
if (colorChannel <= 0.04045) {
return colorChannel / 12.92;
} else {
return Math.pow(((colorChannel + 0.055) / 1.055), 2.4);
}
}
getLuminance(r, g, b) {
return (0.2126 * uDark.sRGBtoLin(r / 255) + 0.7152 * uDark.sRGBtoLin(g / 255) + 0.0722 * uDark.sRGBtoLin(b / 255));
}
getPerceivedLigtness(r, g, b) {
return uDark.YtoLstar(uDark.getLuminance(r, g, b));
}
YtoLstar(Y) {
// Send this function a luminance value between 0.0 and 1.0,
// and it returns L* which is "perceptual lightness"
if (Y <= (216 / 24389)) { // The CIE standard states 0.008856 but 216/24389 is the intent for 0.008856451679036
return Y * (24389 / 27); // The CIE standard states 903.3, but 24389/27 is the intent, making 903.296296296296296
} else {
return Math.pow(Y, (1 / 3)) * 116 - 16;
}
}
search_container_logo(element, notableInfos) {
let parent = (element.parentNode || element)
parent = (parent.parentNode || parent)
return uDark.logo_match.test(parent.outerHTML + notableInfos.uDark_cssClass)
}
search_clickable_parent(documentElement, selectorText) {
return documentElement.querySelector(`a ${selectorText},button ${selectorText}`);
}
image_element_prepare_href(image, documentElement, src_override, options = {}) // Adds notable infos to the image element href, used by the image edition feature
{
// Do not parse url preventing adding context to it or interpreting it as a relative url or correcting its content by any way
let imageTrueSrc = src_override || image.getAttribute("src")
if (uDark.userSettings.disable_image_edition || !imageTrueSrc) {
return imageTrueSrc;
}
if (!image.hasAttribute("data-ud-selector")) {
image.setAttribute("data-ud-selector", Math.random());
}
let selectorText = image.tagName + `[data-ud-selector='${image.getAttribute("data-ud-selector")}']`;
let notableInfos = {};
for (const attribute of image.attributes) {
if (attribute.value.length > 0 && !(/[.\/]/i).test(attribute.value) && !(["src", "data", "data-ud-selector"]).includes(attribute.name)) {
notableInfos[attribute.name] = attribute.value;
}
}
if (imageTrueSrc.includes(uDark.imageSrcInfoMarker)) {
return imageTrueSrc;
}
if (uDark.search_clickable_parent(documentElement, selectorText)) {
notableInfos.inside_clickable = true;
}
if (uDark.search_container_logo(image, notableInfos)) {
notableInfos.logo_match = true;
}
let usedChar = uDark.imageSrcInfoMarker;
if (!imageTrueSrc.includes("#")) {
usedChar = "#" + usedChar;
}
imageTrueSrc = uDark.send_data_image_to_parser(imageTrueSrc, false, {
...options,
notableInfos,
image
});
return imageTrueSrc + usedChar + new URLSearchParams(notableInfos).toString();
}
valuePrototypeEditor(leType, atName, setter = false, conditon = false, aftermath = false, getter = false) {
uDark.info("Editing property :", leType, atName)
if (leType.concat) {
return leType.forEach(aType => uDark.valuePrototypeEditor(aType, atName, setter, conditon, aftermath, getter))
}
if (leType.wrappedJSObject) { // Cross compatibilty with content script
leType = leType.wrappedJSObject;
}
var originalProperty = Object.getOwnPropertyDescriptor(leType.prototype, atName);
if (!originalProperty) {
console.error("No existing property for '", atName, "'", leType, leType.name, leType.prototype)
return;
}
Object.defineProperty(leType.prototype, "o_ud_" + atName, originalProperty);
let override_get_set = {};
if (setter) {
override_get_set.set = uDark.exportFunction(function(value) { // getters must be exported like regular functions
var new_value = (!conditon || conditon(this, value) === true) ? setter(this, value) : value;
let call_result = originalProperty.set.call(this, new_value || value);
aftermath && aftermath(this, value, new_value);
return call_result;
}, window);
}
if (getter) {
override_get_set.get = uDark.exportFunction(function() { // getters must be exported like regular functions
let call_result = originalProperty.get.call(this);
return getter(this, call_result);
}, window);
}
// uDark.general_cache["o_ud_"+atName]=originalSet
Object.defineProperty(leType.prototype, atName, override_get_set);
}
functionWrapper(leType, laFonction, fName, watcher = x => x, conditon = true, result_editor = x => x) {
uDark.info("Wrapping function :", leType, laFonction, fName)
let originalFunction = leType.prototype["o_ud_wrap_" + fName] = laFonction;
leType.prototype[fName] = function(...args) {
if (conditon === true || conditon(this, arguments) === true) {
let watcher_result = watcher(this, arguments);
let result = originalFunction.apply(...watcher_result)
return result_editor(result, this, watcher_result);
} else {
return (originalFunction.apply(this, arguments));
}
}
}
functionPrototypeEditor(leType, laFonction, watcher = x => x, conditon = x => x, result_editor = x => x) {
if (laFonction.concat) {
return laFonction.forEach(aFonction => {
uDark.functionPrototypeEditor(leType, aFonction, watcher, conditon, result_editor)
})
}
if (leType.wrappedJSObject) { // Cross compatibilty with content script
leType = leType.wrappedJSObject;
}
uDark.info("Editing function :", leType, laFonction)
leType.prototype.count = (leType.prototype.count || 0) + 1;
if (!Object.getOwnPropertyDescriptor(leType.prototype, laFonction.name)) {
uDark.error("No getter for '", leType, laFonction, new Error(), leType.prototype.count, document.location.href)
return;
}
let originalFunctionKey = "o_ud_" + laFonction.name
var originalFunction = uDark.exportFunction(Object.getOwnPropertyDescriptor(leType.prototype, laFonction.name).value, window);
Object.defineProperty(leType.prototype, originalFunctionKey, {
value: originalFunction,
writable: true
});
Object.defineProperty(leType.prototype, laFonction.name, {
value: {
[laFonction.name]: uDark.exportFunction(function() {
if (conditon === true || conditon.apply(this, arguments)) { // if a standard function is provided, it will will be able to use the 'this' keyword
let watcher_result = watcher(this, arguments);
let result = originalFunction.apply(this, watcher_result) // if a standard function is provided, it will will be able to use the 'this' keyword
return result_editor(result, this, arguments, watcher_result);
} else {
return (originalFunction.apply(this, arguments));
}
}, window)
} [laFonction.name]
});
}
edit_str_restore_imports_all_way(str, rules) {
// This regexp seems a bit complex
// because @import url("") can includes ";" which is also the css instruction separator like in following example
// @charset "UTF-8";@import url("https://use.typekit.net/lls1fmf.css");
// @import url("https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap");
// .primary-1{ color: rgb(133, 175, 255); }
// This code is sensible to some edge cases, like @rules put in a comment, or in a string, and this is why i now use the protect system
// It was breaking https://www.pascalgamedevelopment.com/content.php .
// It would be possible to fix this by adding a condition to the regex to avoid matching @rules in comments or strings, but it would be a bit more complex
// Or even protecting the @rules individually wit a numbered css class, but it would be a bit more complex too regarding the occurences of the @rules in strings or comments
let imports = str.match(uDark.cssAtRulesRegex) || [];
rules.unshift(...imports);
}
send_data_image_to_parser(str, details, options) {
// uDark.disable_data_image_edition=true;
if (str.trim().toLowerCase().startsWith('data:') && !uDark.userSettings.disable_image_edition && !uDark.disable_data_image_edition) {
let {
b64,
dataHeader,
data,
failure
} = options.cut || uDark.decodeBase64DataURIifIsDataURI(str);
let imageData = data;
options.changed = true; // We have changed the image, notify calle, like edit_css_url action
options.is_data_image = true;
if (!failure && dataHeader.includes('svg')) // Synchronous edit for data SVGs images, we have some nice context and functions to work with
{ // This avoids loosing svg data including the size of the image, and the tags in the image
uDark.disable_svg_data_url_edition = false;
options.svgImage = true;
options.svgDataImage = true;
if (uDark.disable_svg_data_url_edition) {
return str;
}
options.get_document = true;
if (!b64) {
// This replaces searches for unencoded % in image data, and replaces them by the equivalent %25.
// Some websites uses % in their svg data eg for percentage value, while not encoding them.
// This results in a probalby broken image, since we are in a dataURL image.
// I dont care too much about this,but it can lead to decodeURI errors. and therefore to a broken page.
imageData = imageData.replace(/%(?![0-9a-z]{2})/gi, "%25")
imageData = decodeURIComponent(imageData);
}
imageData = uDark.frontEditHTML(false, imageData, details, options).innerHTML;
let encoded = undefined;
// uDark.disable_reencode_data_svg_to_base64=true;
if (uDark.disable_reencode_data_svg_to_base64) {
if (b64) {
dataHeader = dataHeader.replace("base64", "")
};
encoded = dataHeader + encodeURIComponent(imageData)
} else if (uDark.respect_site_svgs_dataurls) {
if (!b64) {
imageData = encodeURIComponent(imageData);
}
let encoded = uDark.rencodeToURI(imageData, dataHeader, b64);
if (encoded.message) {
console.warn(encoded)
encoded = encodeURIComponent(imageData);
}
str = encoded;
} else {
if (!b64) {
encoded = uDark.rencodeToURI(imageData, dataHeader.split(",").join(";base64,"), true);
} else {
encoded = uDark.rencodeToURI(imageData, dataHeader, true);
}
if (encoded.message) {
console.warn(encoded)
encoded = encodeURIComponent(imageData);
encoded = uDark.rencodeToURI(encoded, dataHeader.replace("base64", ""), false);
}
}
str = encoded;
} else {
str = "https://data-image?base64IMG=" + str; // Sending other images to the parser via the worker,
if (options.image) {
options.image.removeAttribute("crossorigin"); // data images are not CORS with this domain, so we remove the attribute to avoid CORS errors
}
}
}
return str;
}
get_fill_for_svg_elem(fillElem, override_value = false, options = {}, class_name = "udark-fill", transform = true) {
let fillValue = override_value || fillElem.getAttribute("fill");
if (override_value == "none" || !uDark.is_color(fillValue)) {
fillValue = "#000000";
}
if (["animate"].includes(fillElem.tagName)) {
return fillValue
} // fill has another meaning for animate
let is_text = options.notableInfos.guessed_type == "logo" || ["text", "tspan"].includes(fillElem.tagName);
if (!is_text && ["path"].includes(fillElem.tagName)) {
let draw_path = fillElem.getAttribute("d");
// Lot of stop path in in path, it's probably a text
is_text = draw_path && ([...draw_path.matchAll(/Z/ig)].length >= 2 || draw_path.length > 170)
}
fillElem.setAttribute("udark-edit", true);
fillElem.setAttribute(class_name, `${options.notableInfos.guessed_type}${is_text?"-text":""}`);
if (transform) {
// Wont work with new mthod, will need to be updated
let edit_result = uDark.eget_color(fillValue, is_text ? uDark.revert_rgba_rgb_raw : uDark.rgba_rgb_raw,false,true)
return edit_result;
}
return "Not implemented";
}
frontEditSVG(svg, documentElement, details, options = {}) {
if (uDark.userSettings.disable_image_edition) {
return;
}
uDark.edit_styles_attributes(svg, details, options);
uDark.edit_styles_elements(svg, details, "ud-edited-background", options);
options = {
...options, // Do not edit the original object, it may be used by other functions by reference
notableInfos: options.notableInfos || {},
lighten: uDark.revert_rgba_rgb_raw,
darken: uDark.rgba_rgb_raw,
}
svg.setAttribute("udark-fill", true);
svg.setAttribute("udark-id", Math.random());
let svgUdarkId = svg.getAttribute("udark-id");
if (!options.notableInfos.inside_clickable) {
if (uDark.search_clickable_parent(documentElement, `svg[udark-id='${svgUdarkId}']`)) {
options.notableInfos.inside_clickable = true;
}
}
if (!options.notableInfos.logo_match) {
if (uDark.search_container_logo(svg, options.notableInfos)) {
options.notableInfos.logo_match = true;
}
}
if (options.notableInfos.logo_match || options.notableInfos.inside_clickable) {
options.notableInfos.guessed_type = "logo";
}
if (options.notableInfos.guessed_type == "logo") {
svg.setAttribute("fill", "white");
// svg.removeAttribute("fill");
// svg.setAttribute("fill", "currentColor");
if (options.remoteSVG || options.svgDataImage) // If there is no style element, we don't need to create one
{
let styleElem = document.createElement("style");
styleElem.id = "udark-styled";
styleElem.append(document.createTextNode(uDark.inject_css_override))
styleElem.append(document.createTextNode("svg{color:white}")) // Allows "currentColor" to take effect
svg.append(styleElem);
}
}
svg.querySelectorAll("[fill]:not([udark-fill])").forEach(fillElem => {
fillElem.setAttribute("fill", uDark.get_fill_for_svg_elem(fillElem, false, options))
})
svg.querySelectorAll("[stroke]:not([udark-stroke])").forEach(fillElem => {
fillElem.setAttribute("stroke", uDark.get_fill_for_svg_elem(fillElem, fillElem.getAttribute("stroke"), options).replace(/currentColor/i, "white"), "udark-stroke")
})
svg.setAttribute("udark-guess", options.notableInfos.guessed_type);
svg.setAttribute("udark-infos", new URLSearchParams(options.notableInfos).toString());
}
edit_styles_elements(parentElement, details, add_class = "ud-edited-background", options = {}) {
parentElement.querySelectorAll(`style:not(.${add_class})`).forEach(astyle => {
astyle.p_ud_innerHTML = uDark.edit_str(astyle.innerHTML, false, false, details, false, options);
// astyle.innerHTML='*{fill:red!important;}'
// According to https://stackoverflow.com/questions/55895361/how-do-i-change-the-innerhtml-of-a-global-style-element-with-cssrule ,
// it is not possible to edit a style element innerHTML with its cssStyleSheet alone
// As long as we are returing a STR, we have to edit the style element innerHTML;
astyle.classList.add(add_class)
});
}
parseAndEditHtmlContentBackend4(strO, details) {
let str = strO;
if (!str || !str.trim().length) {
return str;
}
str = str.protect_simple(uDark.tagsToProtectRegex, "ud-tag-ptd-$1"
// use word boundaries to avoid matching tags like "headings" or tbody or texts like innerHTML
// Frame and frameset are obsolete, but there were meant to be in head, and will be removed from body, they need to be protected
);
let parsedDocument = uDark.createDocumentFromHtml("<body>" + str + "</body>"
/* Re encapsulate str into a <body> is not an overkill : Exists something called unsafeHTML clid binding. I did not understood what it is, but it needs a body tag for proper parsing*/
);
const aDocument = parsedDocument.body;
if (details.unspecifiedCharset) {
// As we seen document.characterSet will default <meta http-equiv> we need to account the meta tag charset and re decode the document properly
// It Falbacks from http header charset to meta tag charset, then to http-equiv charset then to OS charset.
// We can use queryselector safely as it takes the first meta tag it finds
let metaContentType = aDocument.querySelector("meta[charset],meta[http-equiv='Content-Type']");
// If both charset and http-equiv attributes are set in the same tag , charset wins
if (metaContentType) {
let usedContentType = metaContentType.getAttribute("content");
if (metaContentType.hasAttribute("charset")) {
let usedCharset = metaContentType.getAttribute("charset");
usedContentType = `text/html;charset=${usedCharset}`;
}
let metaDetails = {
responseHeaders: [{
name: "Content-Type",
value: usedContentType
}]
}
uDark.extractCharsetFromHeaders(metaDetails);
if (metaDetails.charset != "utf-8") {
details.metaContentType = usedContentType;
details.unspecifiedCharset = false;
details.charset = metaDetails.charset;
const redDecoded = uDarkDecode(metaDetails.charset, details.writeEnd, {
stream: true
});
return uDark.parseAndEditHtmlContentBackend4(redDecoded, details);
}
}
}
aDocument.querySelectorAll("meta[http-equiv=content-security-policy]").forEach(m => m.remove());
if (!details.debugParsing) {
// 4. Temporarily replace all SVG elements to avoid accidental style modifications
const svgElements = uDark.processSvgElements(aDocument, details);
// 5. Edit styles and attributes inline for background elements
uDark.edit_styles_attributes(aDocument, details);
uDark.edit_styles_elements(aDocument, details, "ud-edited-background");
// 8. Add a custom identifier to favicon links to manage cache
uDark.processLinks(aDocument);
// 9. Process image sources and prepare them for custom modifications
uDark.processImages(aDocument);
// 10. Recursively process iframes using the "srcdoc" attribute by applying the same editing logic
uDark.processIframes(aDocument, details, {});
// 11. Handle elements with color attributes (color, bgcolor) and ensure proper color handling
uDark.processColoredItems(aDocument);
// 12. Inject custom CSS and dark color scheme if required (only for the first data load)
uDark.injectStylesIfNeeded(aDocument, details); // Only benefit of this ; avoids page being white on uDark refresh
// 13. Restore the original SVG elements that were temporarily replaced
uDark.restoreSvgElements(svgElements);
}
// 15. Remove the integrity attribute from elements and replace it with a custom attribute
uDark.restoreIntegrityAttributes(aDocument);
// 16. Return the final edited HTML
const outerEdited = aDocument.innerHTML.trim().unprotect_simple("ud-tag-ptd-");
return "<!doctype html>" + outerEdited; // Once i tried to be funny and personalized the doctype, but it was a bad idea, it broke everything ! Doctype is a serious thing, very sensitive to any change outside of the standard
}
frontEditHTML(elem, strO, details, options = {}) {
// 0. Return the original value if it's not a string
if(!(strO instanceof String || typeof strO === "string")){
return strO;
}
// 1. Ignore <script> elements to prevent unintended modifications to JavaScript
let str = strO;
if (elem instanceof HTMLScriptElement) {
return strO;
}
// 2. Special handling for <style> and <svg> style elements (returns edited value directly)
if (elem instanceof HTMLStyleElement || elem instanceof SVGStyleElement) {
return uDark.edit_str(str, false, false, undefined, false, options);
}
// Cant use \b because of the possibility of a - next to the identifier, it's a word character
str = str.protect_simple(uDark.tagsToProtectRegex, "ud-tag-ptd-$1");
let parsedDocument = uDark.createDocumentFromHtml("<body>" + str + "</body>"
/* Re encapsulate str into a <body> is not an overkill : Exists something called unsafeHTML clid binding. I did not understood what it is, but it needs a body tag for proper parsing*/
);
const aDocument = parsedDocument.body;
// 4. Temporarily replace all SVG elements to avoid accidental style modifications
const svgElements = uDark.processSvgElements(aDocument, details);
// 5. Edit styles and attributes inline for background elements
uDark.edit_styles_attributes(aDocument, details);
uDark.edit_styles_elements(aDocument, details, "ud-edited-background");
// 8. Add a custom identifier to favicon links to manage cache
uDark.processLinks(aDocument);
// 9. Process image sources and prepare them for custom modifications
uDark.processImages(aDocument);
// 10. Recursively process iframes using the "srcdoc" attribute by applying the same editing logic
uDark.processIframes(aDocument, details, options);
// 11. Handle elements with color attributes (color, bgcolor) and ensure proper color handling
uDark.processColoredItems(aDocument);
// 13. Restore the original SVG elements that were temporarily replaced
uDark.restoreSvgElements(svgElements);
// 15. Remove the integrity attribute from elements and replace it with a custom attribute
uDark.restoreIntegrityAttributes(aDocument);
// 18. After all the edits, return the final HTML output
if (options.get_document) {
return aDocument;
}
let resultEdited = aDocument.innerHTML.unprotect_simple("ud-tag-ptd-");
return resultEdited;
}
createDocumentFromHtml(html) {
// Use DOMParser to convert the HTML string into a DOM document
const parser = new DOMParser();
return parser.p_ud_parseFromString(html, "text/html");
}
processSvgElements(documentElement, details) {
let svgElements = [];
// Temporarily replace all SVG elements to avoid accidental style modifications
documentElement.querySelectorAll("svg").forEach(svg => {
const tempReplace = document.createElement("svg_secured");
svgElements.push([svg, tempReplace]);
svg.replaceWith(tempReplace);
// Edit SVG styles separately, before main style editing
uDark.frontEditSVG(svg, documentElement, details);
});
return svgElements;
}
processMetaTags(documentElement) {
// Ensure that content-type meta tags are properly set to avoid charset issues
documentElement.querySelectorAll("meta[http-equiv]").forEach(m => {
if (m.httpEquiv && m.httpEquiv.toLowerCase().trim() === "content-type" && m.content.includes("charset")) {
m.content = "text/html; charset=utf-8";
}
});
}
edit_styles_attributes(parentElement, details, options = {}) {
parentElement.querySelectorAll("[style]").forEach(astyle => {
astyle.setAttribute("style", uDark.edit_str(astyle.getAttribute("style"), false, false, details, false, {
...options,
nochunk: true
}));
});
}
processLinks(documentElement) {
// Append a custom identifier to favicon links to manage cache more effectively
documentElement.querySelectorAll("link[rel*='icon' i][href]").forEach(link => {
link.setAttribute("href", link.getAttribute("href") + "#ud_favicon");
});
}
decodeBase64DataURIifIsDataURI(maybeBase64DataURI) {
maybeBase64DataURI = maybeBase64DataURI.trim();
if (!maybeBase64DataURI.startsWith("data:")) {
return {
b64: false,
dataHeader: false,
data: maybeBase64DataURI
};
}
let commaIndex = maybeBase64DataURI.indexOf(","); // String.split is broken: It limits the number of elems in returned array instead of limiting the number of splits
let [dataHeader, data] = [maybeBase64DataURI.substring(0, commaIndex + 1).toLowerCase().trim(), maybeBase64DataURI.substring(commaIndex + 1)]
if (!dataHeader.includes("base64")) {
return {
b64: false,
dataHeader,
data
}
}
try {
return {
b64: true,
dataHeader,
data: atob(data)
}
} catch {
console.warn("Error decoding base64 data URI", maybeBase64DataURI)
return {
b64: true,
dataHeader: false,
data: false,
failure: true
}
}
}
rencodeToURI(data, dataHeader, base64 = false) {
if (!dataHeader) {
return data;
}
if (base64) {
try {
return dataHeader + btoa(data);
} catch {
return new Error("Error encoding base64 data URI", data)
}
}
return dataHeader + data;
}
processImages(documentElement) {
// Process image sources to prepare them for custom modifications
documentElement.querySelectorAll("img[src]").forEach(image => {
image.setAttribute("src", uDark.image_element_prepare_href(image, documentElement));
});
}
frontEditHTMLPossibleDataURL(elem, value, details, options, documentElement) {
let {
b64,
dataHeader,
data,
failure
} = uDark.decodeBase64DataURIifIsDataURI(value || ""); // Value can be null
if (!failure && dataHeader) {
if (dataHeader.includes("image")) {
return uDark.image_element_prepare_href(elem, documentElement || document, value, {
...options,
cut: {
b64,
dataHeader,
data
}
});
} else if (dataHeader.includes("html")) {
data = uDark.frontEditHTML(elem, data, details, options)
return uDark.rencodeToURI(data, dataHeader, b64);
}
}
return value;
}
processIframes(documentElement, details, options) {
// Recursively process iframes that use the "srcdoc" attribute by applying the same HTML processing function
documentElement.querySelectorAll("iframe[srcdoc]").forEach(iframe => {
iframe.setAttribute("srcdoc", uDark.frontEditHTML(false, iframe.srcdoc, details));
});
documentElement.querySelectorAll("object[data],embed[src],iframe[src]").forEach(object => {
// Use GetAttribute to get the original value, as the src attribute may be changed by the context
let src = object.getAttribute("src");
let usedData = src ? src : object.getAttribute("data");
object.setAttribute(src ? "src" : "data", uDark.frontEditHTMLPossibleDataURL(object, usedData, details, options, documentElement));
});
}
processColoredItems(documentElement) {
// Process elements with color or bgcolor attributes and ensure proper color handling
documentElement.querySelectorAll("[color],[bgcolor]").forEach(coloredItem => {
for (let [key, afunction] of Object.entries(uDark.attributes_function_map)) {
if (typeof afunction === "string") {
afunction = uDark.attributes_function_map[afunction];
}
let attributeValue = coloredItem.getAttribute(key);
if (attributeValue && attributeValue.startsWith("#") && attributeValue.length === 6) {
attributeValue += "0"; // Ensure colors are properly formatted
}
const possibleColor = uDark.is_color(attributeValue, true, true);
if (possibleColor) {
let callResult = afunction(...possibleColor, uDark.hex_val /* this kind of html4 attributes does not fully supports rgba vals, prefer use hex vals */ , coloredItem);
if (callResult) {
coloredItem.setAttribute(key, callResult);
}
}
}
});
}
injectStylesIfNeeded(aDocument, details) {
// Inject custom CSS and the dark color scheme meta tag if this is the first data load
if (details.dataCount === 1) {
// Stopped using inject_css_suggested, as it was causing issues with some websites, like react ones that stats with a minimal body
const udMetaDark = aDocument.querySelector("meta[name='color-scheme']") || document.createElement("meta");
udMetaDark.id = "ud-meta-dark";
udMetaDark.name = "color-scheme";
udMetaDark.content = "dark";
let headElem = aDocument.head || aDocument.querySelector("ud-tag-ptd-head") || aDocument;
headElem.prepend(udMetaDark);
}
}
restoreSvgElements(svgElements) {
// Restore the original SVG elements that were temporarily replaced
svgElements.forEach(([svg, tempReplace]) => {
tempReplace.replaceWith(svg);
});
}
restoreNoscriptElements(aDocument) {
// Restore <noscript> elements that were converted to <script>
aDocument.querySelectorAll("script[secnoscript]").forEach(script => {
let noScript = document.createElement("noscript");
for (let node of script.attributes) {
noScript.setAttribute(node.name, node.value)
}
let template = aDocument.createElement('template');
template.innerHTML = script.innerHTML;
noScript.append(template.content); // We cant put innerHTML directly in a noscript element, it would be html encoded. The template element is used to avoid this, it parse elements for us.
script.replaceWith(noScript);
});
}
restoreTemplateElements(aDocument) {
// Restore <noscript> elements that were converted to <template>
// Using replaceWith() instead of innerHTML to avoid issues with nested elements wich were HTMLencoded
aDocument.querySelectorAll("template[secnoscript]").forEach(template => {
let noScript = document.createElement("noscript");
for (let node of template.attributes) {
noScript.setAttribute(node.name, node.value)
}
noScript.append(template.content);
template.replaceWith(noScript);
});
}
restoreIntegrityAttributes(aDocument) {
// Remove the integrity attribute from elements and store it as a custom attribute
aDocument.querySelectorAll("[integrity]").forEach(integrityElem => {
integrityElem.setAttribute("data-no-integ", integrityElem.getAttribute("integrity"));
integrityElem.removeAttribute("integrity");
integrityElem.setAttribute("onerror", "uDark.linkIntegrityErrorEvent(this)"); // Fix for reloading the resource if it fails to load, happened on graphene.org
});
}
str_protect_simple(str, regex, protectWith, condition = true) {
if (condition) {
str = str.replaceAll(regex, protectWith)
}
return str;
}
str_unprotect_simple(str, protectedWith, condition = true) {
if (condition) {
str = str.replaceAll(protectedWith, "")
}
return str;
}
edit_str_nochunk(strO) {
if (strO.join) {
strO = strO.join("");
}
return uDark.edit_str(strO, false, false, undefined, false, {
nochunk: true
});
}
edit_str(strO, cssStyleSheet, verifyIntegrity = false, details, options = {}) {
if(!( typeof strO === "string" || strO instanceof String)){
return strO; // Do not edit non string values to avoid errors, web is wide and wild
}
let str = strO;
if (false && strO.includes("/*!sc*/")) { // TODO: Fix thins in abetter way; this is a temporary and specific fix;
console.warn("React incompatible css detectd", uDark.edit_str);
uDark.edit_str.last_debugged = {
strO,
cssStyleSheet,