-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDarkModer.user.js
More file actions
5295 lines (4613 loc) · 184 KB
/
DarkModer.user.js
File metadata and controls
5295 lines (4613 loc) · 184 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
// ==UserScript==
// @name DarkModer
// @namespace https://github.com/SysAdminDoc/DarkModer
// @version 3.0.0
// @description Dark mode for every website. Complete Dark Reader recreation as userscript with all features.
// @author SysAdminDoc (Based on Dark Reader by Alexander Shutau)
// @license MIT
// @match *://*/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant GM_addStyle
// @connect raw.githubusercontent.com
// @connect *
// @run-at document-start
// @noframes
// @updateURL https://github.com/SysAdminDoc/DarkModer/raw/refs/heads/main/DarkModer.user.js
// @downloadURL https://github.com/SysAdminDoc/DarkModer/raw/refs/heads/main/DarkModer.user.js
// @homepageURL https://github.com/SysAdminDoc/DarkModer
// @supportURL https://github.com/SysAdminDoc/DarkModer/issues
// ==/UserScript==
(function() {
'use strict';
// ============================================================================
// CONFIGURATION
// ============================================================================
const CONFIG = {
version: '3.0.0',
storageKey: 'darkModer',
configBaseURL: 'https://raw.githubusercontent.com/SysAdminDoc/DarkModer/refs/heads/main/',
configFiles: {
darkSites: 'dark-sites.json',
dynamicFixes: 'dynamic-theme-fixes.json',
inversionFixes: 'inversion-fixes.json',
staticThemes: 'static-themes.json'
},
cacheDuration: 60 * 60 * 1000, // 1 hour
maxInlineElements: 200,
inlineElementBatchSize: 50,
stylesheetBatchSize: 5,
observerBatchSize: 3,
maxCSSRules: 1000,
colorSamplingThreshold: 0.3,
maxColorSamples: 30
};
// ============================================================================
// COLOR SCHEME PRESETS (NEW in v3.0.0)
// ============================================================================
const COLOR_SCHEMES = {
'Default': {
background: '#181a1b',
text: '#e8e6e3',
selectionBg: '#004daa',
selectionText: '#ffffff',
link: '#3391ff',
border: '#3a3d3e'
},
'Dracula': {
background: '#282a36',
text: '#f8f8f2',
selectionBg: '#44475a',
selectionText: '#f8f8f2',
link: '#8be9fd',
border: '#44475a'
},
'Nord': {
background: '#2e3440',
text: '#eceff4',
selectionBg: '#4c566a',
selectionText: '#eceff4',
link: '#88c0d0',
border: '#3b4252'
},
'Solarized Dark': {
background: '#002b36',
text: '#839496',
selectionBg: '#073642',
selectionText: '#93a1a1',
link: '#268bd2',
border: '#073642'
},
'Monokai': {
background: '#272822',
text: '#f8f8f2',
selectionBg: '#49483e',
selectionText: '#f8f8f2',
link: '#66d9ef',
border: '#3e3d32'
},
'One Dark': {
background: '#282c34',
text: '#abb2bf',
selectionBg: '#3e4451',
selectionText: '#abb2bf',
link: '#61afef',
border: '#3b4048'
},
'Gruvbox': {
background: '#282828',
text: '#ebdbb2',
selectionBg: '#504945',
selectionText: '#ebdbb2',
link: '#83a598',
border: '#3c3836'
},
'Tokyo Night': {
background: '#1a1b26',
text: '#a9b1d6',
selectionBg: '#33467c',
selectionText: '#c0caf5',
link: '#7aa2f7',
border: '#292e42'
},
'Catppuccin Mocha': {
background: '#1e1e2e',
text: '#cdd6f4',
selectionBg: '#45475a',
selectionText: '#cdd6f4',
link: '#89b4fa',
border: '#313244'
},
'GitHub Dark': {
background: '#0d1117',
text: '#c9d1d9',
selectionBg: '#388bfd',
selectionText: '#ffffff',
link: '#58a6ff',
border: '#30363d'
},
'Amoled': {
background: '#000000',
text: '#ffffff',
selectionBg: '#1a1a1a',
selectionText: '#ffffff',
link: '#4da6ff',
border: '#1a1a1a'
},
'Sepia': {
background: '#232018',
text: '#c8b89a',
selectionBg: '#3d3426',
selectionText: '#c8b89a',
link: '#d4a574',
border: '#3d3426'
}
};
// ============================================================================
// DEFAULT THEME SETTINGS
// ============================================================================
const DEFAULT_THEME = {
mode: 1, // 0: light, 1: dark
brightness: 100,
contrast: 100,
grayscale: 0,
sepia: 0,
useFont: false,
fontFamily: '',
textStroke: 0,
engine: 'dynamic', // 'filter', 'filterPlus', 'dynamic', 'static'
stylesheet: '',
darkSchemeBackgroundColor: '#181a1b',
darkSchemeTextColor: '#e8e6e3',
lightSchemeBackgroundColor: '#dcdad7',
lightSchemeTextColor: '#181a1b',
scrollbarColor: 'auto',
selectionColor: 'auto',
selectionBgColor: '#004daa',
selectionTextColor: '#ffffff',
linkColor: '#3391ff',
visitedLinkColor: '#9e6eff',
borderColor: '#3a3d3e',
styleSystemControls: true,
colorScheme: 'Default',
immediateModify: true
};
// ============================================================================
// DEFAULT SETTINGS
// ============================================================================
const DEFAULT_SETTINGS = {
enabled: true,
fetchNews: false,
theme: { ...DEFAULT_THEME },
presets: [],
siteSettings: {},
customThemes: [],
themePresets: {},
enabledByDefault: true,
enabledFor: [],
disabledFor: [],
disabledSites: [],
siteFixesUser: {},
changeBrowserTheme: false,
syncSettings: false,
syncSitesFixes: false,
colorScheme: 'Default',
automation: {
enabled: false,
mode: 'disabled', // 'disabled', 'time', 'system', 'location'
behavior: 'OnOff',
startTime: '18:00',
endTime: '09:00',
latitude: null,
longitude: null
},
time: {
activation: '18:00',
deactivation: '09:00'
},
location: {
latitude: null,
longitude: null
},
shortcuts: {
toggle: 'Alt+Shift+D',
toggleSite: 'Alt+Shift+S',
openSettings: 'Alt+Shift+A'
},
previewNewDesign: true,
enableForPDF: true,
enableForProtectedPages: false,
enableContextMenus: false,
detectDarkTheme: true
};
// ============================================================================
// NAMED CSS COLORS (Pre-computed table - created once, not per-call)
// ============================================================================
const NAMED_COLORS = {
// Basic colors
white: [255, 255, 255],
black: [0, 0, 0],
red: [255, 0, 0],
green: [0, 128, 0],
blue: [0, 0, 255],
yellow: [255, 255, 0],
cyan: [0, 255, 255],
magenta: [255, 0, 255],
// Gray scale
silver: [192, 192, 192],
gray: [128, 128, 128],
grey: [128, 128, 128],
darkgray: [169, 169, 169],
darkgrey: [169, 169, 169],
dimgray: [105, 105, 105],
dimgrey: [105, 105, 105],
lightgray: [211, 211, 211],
lightgrey: [211, 211, 211],
gainsboro: [220, 220, 220],
whitesmoke: [245, 245, 245],
// Reds
maroon: [128, 0, 0],
darkred: [139, 0, 0],
crimson: [220, 20, 60],
firebrick: [178, 34, 34],
indianred: [205, 92, 92],
lightcoral: [240, 128, 128],
salmon: [250, 128, 114],
darksalmon: [233, 150, 122],
lightsalmon: [255, 160, 122],
coral: [255, 127, 80],
tomato: [255, 99, 71],
orangered: [255, 69, 0],
// Pinks
pink: [255, 192, 203],
lightpink: [255, 182, 193],
hotpink: [255, 105, 180],
deeppink: [255, 20, 147],
mediumvioletred: [199, 21, 133],
palevioletred: [219, 112, 147],
// Oranges
orange: [255, 165, 0],
darkorange: [255, 140, 0],
// Yellows
gold: [255, 215, 0],
lightyellow: [255, 255, 224],
lemonchiffon: [255, 250, 205],
lightgoldenrodyellow: [250, 250, 210],
papayawhip: [255, 239, 213],
moccasin: [255, 228, 181],
peachpuff: [255, 218, 185],
palegoldenrod: [238, 232, 170],
khaki: [240, 230, 140],
darkkhaki: [189, 183, 107],
// Greens
lime: [0, 255, 0],
limegreen: [50, 205, 50],
forestgreen: [34, 139, 34],
darkgreen: [0, 100, 0],
seagreen: [46, 139, 87],
mediumseagreen: [60, 179, 113],
springgreen: [0, 255, 127],
mediumspringgreen: [0, 250, 154],
lightgreen: [144, 238, 144],
palegreen: [152, 251, 152],
darkseagreen: [143, 188, 143],
mediumaquamarine: [102, 205, 170],
yellowgreen: [154, 205, 50],
olivedrab: [107, 142, 35],
olive: [128, 128, 0],
darkolivegreen: [85, 107, 47],
greenyellow: [173, 255, 47],
chartreuse: [127, 255, 0],
lawngreen: [124, 252, 0],
// Cyans
aqua: [0, 255, 255],
teal: [0, 128, 128],
darkcyan: [0, 139, 139],
lightcyan: [224, 255, 255],
paleturquoise: [175, 238, 238],
aquamarine: [127, 255, 212],
turquoise: [64, 224, 208],
mediumturquoise: [72, 209, 204],
darkturquoise: [0, 206, 209],
cadetblue: [95, 158, 160],
steelblue: [70, 130, 180],
lightsteelblue: [176, 196, 222],
// Blues
navy: [0, 0, 128],
darkblue: [0, 0, 139],
mediumblue: [0, 0, 205],
royalblue: [65, 105, 225],
cornflowerblue: [100, 149, 237],
dodgerblue: [30, 144, 255],
deepskyblue: [0, 191, 255],
lightskyblue: [135, 206, 250],
skyblue: [135, 206, 235],
lightblue: [173, 216, 230],
powderblue: [176, 224, 230],
aliceblue: [240, 248, 255],
midnightblue: [25, 25, 112],
// Purples
fuchsia: [255, 0, 255],
purple: [128, 0, 128],
indigo: [75, 0, 130],
darkmagenta: [139, 0, 139],
darkviolet: [148, 0, 211],
darkorchid: [153, 50, 204],
mediumorchid: [186, 85, 211],
orchid: [218, 112, 214],
violet: [238, 130, 238],
plum: [221, 160, 221],
thistle: [216, 191, 216],
lavender: [230, 230, 250],
rebeccapurple: [102, 51, 153],
blueviolet: [138, 43, 226],
mediumpurple: [147, 112, 219],
slateblue: [106, 90, 205],
darkslateblue: [72, 61, 139],
mediumslateblue: [123, 104, 238],
// Browns
brown: [165, 42, 42],
saddlebrown: [139, 69, 19],
sienna: [160, 82, 45],
chocolate: [210, 105, 30],
peru: [205, 133, 63],
sandybrown: [244, 164, 96],
burlywood: [222, 184, 135],
tan: [210, 180, 140],
rosybrown: [188, 143, 143],
goldenrod: [218, 165, 32],
darkgoldenrod: [184, 134, 11],
// Whites
snow: [255, 250, 250],
honeydew: [240, 255, 240],
mintcream: [245, 255, 250],
azure: [240, 255, 255],
ghostwhite: [248, 248, 255],
floralwhite: [255, 250, 240],
ivory: [255, 255, 240],
beige: [245, 245, 220],
linen: [250, 240, 230],
oldlace: [253, 245, 230],
antiquewhite: [250, 235, 215],
bisque: [255, 228, 196],
blanchedalmond: [255, 235, 205],
wheat: [245, 222, 179],
cornsilk: [255, 248, 220],
navajowhite: [255, 222, 173],
seashell: [255, 245, 238],
mistyrose: [255, 228, 225],
lavenderblush: [255, 240, 245],
// Slate colors
slategray: [112, 128, 144],
slategrey: [112, 128, 144],
lightslategray: [119, 136, 153],
lightslategrey: [119, 136, 153],
darkslategray: [47, 79, 79],
darkslategrey: [47, 79, 79],
// Transparent
transparent: [0, 0, 0, 0]
};
// ============================================================================
// BUILT-IN DARK SITES LIST
// ============================================================================
const BUILT_IN_DARK_SITES = [
'darkreader.org',
'discord.com',
'github.com',
'netflix.com',
'twitch.tv',
'youtube.com',
'music.youtube.com',
'reddit.com',
'twitter.com',
'x.com',
'spotify.com',
'slack.com',
'notion.so',
'figma.com',
'linear.app',
'vercel.com',
'vitejs.dev',
'hulu.com',
'disneyplus.com',
'primevideo.com',
'hbomax.com'
];
// ============================================================================
// BUILT-IN DYNAMIC THEME FIXES
// ============================================================================
const BUILT_IN_DYNAMIC_FIXES = {
// Example fixes structure
// 'example.com': 'INVERT\n.icon\n\nCSS\n.element { color: white !important; }'
};
// ============================================================================
// BUILT-IN INVERSION FIXES
// ============================================================================
const BUILT_IN_INVERSION_FIXES = {
// Example fixes structure
// 'example.com': 'INVERT\nimg\n\nNO INVERT\n.logo'
};
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
/**
* Throttle function execution to prevent excessive calls
* @param {Function} fn - Function to throttle
* @param {number} delay - Minimum delay between calls in ms
* @returns {Function} Throttled function
*/
function throttle(fn, delay) {
let lastCall = 0;
let lastResult;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
lastResult = fn.apply(this, args);
}
return lastResult;
};
}
/**
* Debounce function execution to prevent rapid successive calls
* @param {Function} fn - Function to debounce
* @param {number} delay - Delay in ms after last call
* @returns {Function} Debounced function
*/
function debounce(fn, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
/**
* Clamp a value between min and max
* @param {number} value - Value to clamp
* @param {number} min - Minimum value
* @param {number} max - Maximum value
* @returns {number} Clamped value
*/
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
/**
* Extract hostname from URL
* @param {string} url - URL to parse
* @returns {string} Hostname or empty string
*/
function getURLHostname(url) {
try {
return new URL(url).hostname;
} catch (e) {
return '';
}
}
/**
* Check if URL matches any pattern in the list
* Supports exact match, wildcard (*), and regex (/pattern/)
* @param {string} url - URL to check
* @param {Array} patterns - Array of patterns to match against
* @returns {boolean} True if matched
*/
function isURLMatched(url, patterns) {
if (!patterns || !Array.isArray(patterns)) {
return false;
}
const hostname = getURLHostname(url) || url;
return patterns.some(pattern => {
if (!pattern || typeof pattern !== 'string') {
return false;
}
// Regex pattern: /pattern/
if (pattern.startsWith('/') && pattern.endsWith('/')) {
try {
const regex = new RegExp(pattern.slice(1, -1));
return regex.test(url);
} catch (e) {
return false;
}
}
// Wildcard pattern: *.example.com
if (pattern.includes('*')) {
const escapedPattern = pattern
.replace(/[.+?^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*');
const regex = new RegExp('^' + escapedPattern + '$', 'i');
return regex.test(hostname) || regex.test(url);
}
// Exact match or subdomain match
return hostname === pattern || hostname.endsWith('.' + pattern);
});
}
/**
* Generate a unique identifier
* @returns {string} Unique ID
*/
function generateUID() {
return Math.random().toString(36).substring(2, 11);
}
/**
* Parse a keyboard shortcut string
* @param {string} shortcut - Shortcut string (e.g., "Alt+Shift+D")
* @returns {Object|null} Parsed shortcut object
*/
function parseShortcut(shortcut) {
if (!shortcut || typeof shortcut !== 'string') {
return null;
}
const parts = shortcut.toLowerCase().split('+').map(p => p.trim());
return {
ctrl: parts.includes('ctrl') || parts.includes('control'),
alt: parts.includes('alt'),
shift: parts.includes('shift'),
meta: parts.includes('meta') || parts.includes('cmd') || parts.includes('command'),
key: parts.find(p => !['ctrl', 'control', 'alt', 'shift', 'meta', 'cmd', 'command'].includes(p)) || ''
};
}
/**
* Check if a keyboard event matches a shortcut
* @param {KeyboardEvent} event - Keyboard event
* @param {string} shortcut - Shortcut string to match
* @returns {boolean} True if matched
*/
function matchShortcut(event, shortcut) {
const parsed = parseShortcut(shortcut);
if (!parsed) {
return false;
}
return event.ctrlKey === parsed.ctrl &&
event.altKey === parsed.alt &&
event.shiftKey === parsed.shift &&
event.metaKey === parsed.meta &&
event.key.toLowerCase() === parsed.key;
}
/**
* Escape HTML special characters
* @param {string} str - String to escape
* @returns {string} Escaped string
*/
function escapeHtml(str) {
const htmlEntities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return String(str).replace(/[&<>"']/g, char => htmlEntities[char]);
}
/**
* Deep merge two objects
* @param {Object} target - Target object
* @param {Object} source - Source object
* @returns {Object} Merged object
*/
function deepMerge(target, source) {
const result = { ...target };
for (const key of Object.keys(source)) {
if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) {
result[key] = deepMerge(result[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
return result;
}
// ============================================================================
// SUN CALCULATOR (for sunrise/sunset automation)
// Based on NOAA Solar Calculator algorithms
// ============================================================================
const SunCalc = {
/**
* Calculate sunrise and sunset times for a given date and location
* @param {Date} date - Date to calculate for
* @param {number} lat - Latitude in degrees
* @param {number} lng - Longitude in degrees
* @returns {Object} Object with sunrise and sunset Date objects
*/
calculate(date, lat, lng) {
const rad = Math.PI / 180;
const dayMs = 1000 * 60 * 60 * 24;
const J1970 = 2440588;
const J2000 = 2451545;
// Convert date to Julian
const toJulian = d => d.valueOf() / dayMs - 0.5 + J1970;
const fromJulian = j => new Date((j + 0.5 - J1970) * dayMs);
const toDays = d => toJulian(d) - J2000;
// Obliquity of the ecliptic
const e = rad * 23.4397;
/**
* Calculate right ascension
*/
const rightAscension = (l, b) => {
return Math.atan2(
Math.sin(l) * Math.cos(e) - Math.tan(b) * Math.sin(e),
Math.cos(l)
);
};
/**
* Calculate declination
*/
const declination = (l, b) => {
return Math.asin(
Math.sin(b) * Math.cos(e) +
Math.cos(b) * Math.sin(e) * Math.sin(l)
);
};
/**
* Calculate solar mean anomaly
*/
const solarMeanAnomaly = d => {
return rad * (357.5291 + 0.98560028 * d);
};
/**
* Calculate ecliptic longitude
*/
const eclipticLongitude = M => {
const C = rad * (
1.9148 * Math.sin(M) +
0.02 * Math.sin(2 * M) +
0.0003 * Math.sin(3 * M)
);
const P = rad * 102.9372;
return M + C + P + Math.PI;
};
/**
* Calculate Julian cycle
*/
const julianCycle = (d, lw) => {
return Math.round(d - 0.0009 - lw / (2 * Math.PI));
};
/**
* Calculate approximate transit
*/
const approxTransit = (Ht, lw, n) => {
return 0.0009 + (Ht + lw) / (2 * Math.PI) + n;
};
/**
* Calculate solar transit in Julian days
*/
const solarTransitJ = (ds, M, L) => {
return J2000 + ds + 0.0053 * Math.sin(M) - 0.0069 * Math.sin(2 * L);
};
/**
* Calculate hour angle
*/
const hourAngle = (h, phi, d) => {
const cosH = (Math.sin(h) - Math.sin(phi) * Math.sin(d)) /
(Math.cos(phi) * Math.cos(d));
// Clamp to valid range
if (cosH < -1) return Math.PI;
if (cosH > 1) return 0;
return Math.acos(cosH);
};
/**
* Calculate sunset time in Julian days
*/
const getSetJ = (h, lw, phi, dec, n, M, L) => {
const w = hourAngle(h, phi, dec);
const a = approxTransit(w, lw, n);
return solarTransitJ(a, M, L);
};
try {
const lw = rad * -lng;
const phi = rad * lat;
const d = toDays(date);
const n = julianCycle(d, lw);
const ds = approxTransit(0, lw, n);
const M = solarMeanAnomaly(ds);
const L = eclipticLongitude(M);
const dec = declination(L, 0);
const Jnoon = solarTransitJ(ds, M, L);
// Sun altitude at sunrise/sunset
const h0 = rad * -0.833;
const Jset = getSetJ(h0, lw, phi, dec, n, M, L);
const Jrise = Jnoon - (Jset - Jnoon);
return {
sunrise: fromJulian(Jrise),
sunset: fromJulian(Jset),
noon: fromJulian(Jnoon)
};
} catch (e) {
console.warn('SunCalc: Calculation error', e);
return {
sunrise: null,
sunset: null,
noon: null
};
}
},
/**
* Check if it's currently dark (between sunset and sunrise)
* @param {Date} now - Current time
* @param {number} lat - Latitude
* @param {number} lng - Longitude
* @returns {boolean} True if dark
*/
isDark(now, lat, lng) {
const { sunrise, sunset } = this.calculate(now, lat, lng);
if (!sunrise || !sunset) {
return true; // Default to dark if calculation fails
}
return now < sunrise || now > sunset;
}
};
// ============================================================================
// DARK THEME DETECTOR
// Two-phase detection system to prevent white flash
// ============================================================================
const DarkThemeDetector = {
/**
* CSS selectors that indicate dark mode on html element (Phase 1 - early)
*/
earlyDarkSelectors: [
'html[data-theme="dark"]',
'html[data-color-mode="dark"]',
'html[data-dark-mode="true"]',
'html[data-bs-theme="dark"]',
'html[data-color-scheme="dark"]',
'html[data-mode="dark"]',
'html.dark',
'html.dark-mode',
'html.dark-theme',
'html.theme-dark',
':root[data-theme="dark"]',
':root[data-color-mode="dark"]',
':root.dark'
],
/**
* CSS selectors that indicate dark mode on body element (Phase 2)
*/
bodyDarkSelectors: [
'body[data-theme="dark"]',
'body[data-color-mode="dark"]',
'body[data-dark-mode="true"]',
'body[data-bs-theme="dark"]',
'body.dark',
'body.dark-mode',
'body.dark-theme',
'body.theme-dark',
'body[dark]'
],
/**
* Phase 1: Early detection before body is available
* Runs at document-start to prevent white flash
* @returns {Object} Detection result {isDark: boolean, reason: string|null}
*/
detectEarly() {
// Check for meta darkreader-lock tag
if (document.querySelector('meta[name="darkreader-lock"]')) {
return {
isDark: true,
reason: 'meta-lock'
};
}
// Check color-scheme meta tag
const colorSchemeMeta = document.querySelector('meta[name="color-scheme"]');
if (colorSchemeMeta) {
const content = colorSchemeMeta.getAttribute('content') || '';
if (content.includes('dark') && !content.includes('light')) {
return {
isDark: true,
reason: 'meta-color-scheme'
};
}
}
// Check early dark selectors on html element
if (this.hasEarlyDarkSelector()) {
return {
isDark: true,
reason: 'html-selector'
};
}
return {
isDark: false,
reason: null
};
},
/**
* Phase 2: Full detection after DOM is ready
* Can optionally use color sampling (disabled by default for performance)
* @param {boolean} useColorSampling - Whether to sample page colors
* @returns {Object} Detection result
*/
detect(useColorSampling = false) {
// Check for meta darkreader-lock tag
if (document.querySelector('meta[name="darkreader-lock"]')) {
return {
isDark: true,
reason: 'meta-lock'
};
}
// Temporarily disable our provisional style if present
const provisional = document.getElementById('darkmoder-provisional');
if (provisional) {
provisional.disabled = true;
}
try {
// Check color-scheme meta tag
const colorSchemeMeta = document.querySelector('meta[name="color-scheme"]');
if (colorSchemeMeta) {
const content = colorSchemeMeta.getAttribute('content') || '';
if (content.includes('dark') && !content.includes('light')) {
return {
isDark: true,
reason: 'meta-color-scheme'
};
}
}
// Check computed color-scheme property
if (!provisional && document.documentElement) {
try {
const computedStyle = getComputedStyle(document.documentElement);
const colorScheme = computedStyle.colorScheme ||
computedStyle.getPropertyValue('color-scheme');
if (colorScheme && colorScheme.includes('dark') && !colorScheme.includes('light')) {
return {
isDark: true,
reason: 'color-scheme-property'
};
}
} catch (e) {
// Ignore getComputedStyle errors
}
}
// Check CSS class/attribute selectors
if (this.hasDarkModeSelector()) {
return {
isDark: true,
reason: 'css-selector'
};
}
// Optional: Sample page colors
if (useColorSampling && document.body) {
const avgLuminance = this.samplePageColors();
if (avgLuminance < CONFIG.colorSamplingThreshold) {
return {
isDark: true,
reason: 'color-sampling'
};
}
}
return {
isDark: false,
reason: null
};
} finally {
// Re-enable provisional style
if (provisional) {
provisional.disabled = false;
}
}
},
/**
* Check if any early dark selector matches
* @returns {boolean} True if matched
*/
hasEarlyDarkSelector() {
for (const selector of this.earlyDarkSelectors) {
try {
if (document.querySelector(selector)) {
return true;
}
} catch (e) {
// Invalid selector, skip
}
}
return false;
},