mirror of https://github.com/lxndrblz/anatole.git

Alexander Bilz
07.07.2021 2003b9b2c26edad359bc5c4bd0d6457ec426b5b6
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
// initialize default value
function getTheme() {
    return localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
}
 
function setTheme(style) {
    document.documentElement.setAttribute('data-theme', style);
    localStorage.setItem('theme', style);
}
 
// Check if a theme was set manually
function getMode()  {
    return localStorage.getItem('mode') ? localStorage.getItem('mode') : null;
}
 
function setMode(mode)  {
    localStorage.setItem('mode', mode);
}
 
function init() {
    // initialize default value
    const theme = getTheme();
    const mode = getMode();
 
    // check if a preferred color theme is set for users that have never been to our site
    const userPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
    const userPrefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
    if (theme === null) {
        if (userPrefersDark) {
            setTheme('dark');
            setMode('auto');
        } else if (userPrefersLight){
            setTheme('light');
            setMode('auto');
        } else if (!document.documentElement.getAttribute('data-theme')) {
            setTheme('light');
        } else {
            setTheme(document.documentElement.getAttribute('data-theme'));
        }
    } else {
 
        if (mode === 'auto') {
            if (userPrefersDark) {
                document.documentElement.setAttribute('data-theme', 'dark');
            } else if (userPrefersLight){
                document.documentElement.setAttribute('data-theme', 'light');
            } 
        }
        else {
            // load a user set theme theme
            if (theme === 'light') {
                document.documentElement.setAttribute('data-theme', 'light');
            } else {
                document.documentElement.setAttribute('data-theme', 'dark');
            }
        }
    }
}
 
 
// switch themes
function switchTheme() {
    const theme = getTheme();
    if (theme === 'light') {
        setTheme('dark');
    } else {
        setTheme('light');
    }
    setMode('user');
}
 
document.addEventListener('DOMContentLoaded', function () {
    const themeSwitcher = document.querySelector('.theme-switch');
    themeSwitcher.addEventListener('click', switchTheme, false);
}, false);
 
init();