File size: 1,433 Bytes
6bc2e5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
(function () {
    var KEY = 'qv-theme';
    var root = document.documentElement;
    var btn = document.getElementById('theme-toggle');
    var meta = document.querySelector('meta[name="theme-color"]');

    function current() {
        return root.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
    }

    function apply(theme) {
        if (theme === 'light') root.setAttribute('data-theme', 'light');
        else root.removeAttribute('data-theme');
        if (meta) meta.setAttribute('content', getComputedStyle(root).getPropertyValue('--bg-dark').trim());
        if (!btn) return;
        var next = theme === 'light' ? 'dark' : 'light';
        btn.setAttribute('aria-pressed', String(theme === 'light'));
        btn.setAttribute('aria-label', 'Switch to ' + next + ' theme');
        btn.setAttribute('title', 'Switch to ' + next + ' theme');
    }

    function save(theme) {
        try {
            if (theme === 'light') localStorage.setItem(KEY, 'light');
            else localStorage.removeItem(KEY);
        } catch (e) {}
    }

    apply(current());

    if (btn) {
        btn.addEventListener('click', function () {
            var theme = current() === 'light' ? 'dark' : 'light';
            apply(theme);
            save(theme);
        });
    }

    window.addEventListener('storage', function (e) {
        if (e.key === KEY) apply(e.newValue === 'light' ? 'light' : 'dark');
    });
})();