aboutsummaryrefslogtreecommitdiff
path: root/public/js/schemeSwap.js
blob: e048f6a72018406aff86243eb87112c775ef2019 (plain)
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
/**
 * Retrieves a cookies value
 * @param {string} cname Cookie name
 * @returns {string}     Cookie value
 */
function getCookie(cname) {
    let name = cname + "=";
    let decodedCookie = decodeURIComponent(document.cookie);
    let ca = decodedCookie.split(';');
    for(let i = 0; i <ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

/**
 * Sets/creates a cookie
 * @param {string} cname  Cookie name
 * @param {string} cvalue Cookie value
 * @param {number} exdays Cookie lifespan (days)
 */
function setCookie(cname, cvalue, exdays) {
    const d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    let expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

/**
 * Checks if a cookie exists
 * @param {string} cname Cookie name
 * @returns {boolean}    If cookie exists or not
 */
function cookieExists(cname) {
    const cvalue = getCookie(cname);
    return cvalue !== "";
}

/**
 * Swaps the colorscheme
 * @param {string} scheme Color scheme ID
 */
function swapScheme(scheme) {
    setCookie("colorscheme", scheme, 90);
    document.getElementById("css-colorscheme").href = `/css/colorschemes/${scheme}.css`;
    console.log(`Set colorscheme to ${getCookie("colorscheme")}`)
}

function setSchemeSelector() {
    if (!cookieExists("colorscheme")) {
        setCookie("colorscheme", "catppuccin-macchiato", 90);
    } else {
        const scheme = getCookie("colorscheme");
        const schemeselector = document.getElementById("scheme-selector");
        if (scheme && schemeselector) {
            for (let option of schemeselector.options) {
                if (option.value == scheme) {
                    option.selected = true;
                    break;
                }
            }
        }
    }
}