This repository has been archived on 2020-10-30. You can view files and clone it, but cannot push or open issues or pull requests.
hugo-blog/blog/js/script.js

75 lines
2.7 KiB
JavaScript

// TODO move this file into assets and use hugo pipes and babel
(function(){
var STATES = ["colorscheme-dark", "colorscheme-light", "colorscheme-auto"];
var LABELS = ["On", "Off", "Auto"]; // display text of dark mode setting - corresponds with STATES array
var CS_BTN_CLASS = 'cs-mode-button';
var CS_BTN_CONTAINER_CLASS = 'cs-mode-container';
var CS_BTN_TEXT_CLASS = 'cs-mode-button-state';
var CS_MODE_COOKIE_NAME = "cs_mode"; // name of cookie that stores dark mode setting
var MODE_BTN_TEXT_ELEMENT = document.getElementById(CS_BTN_TEXT_CLASS);
var activeState = -1; // the active index of the STATES array
var cookieMode; // dark mode setting value retrieved from cookie
// toggles the color scheme between the states specified in the array STATES
function toggleColorscheme() {
for(var i = 0; i < STATES.length; i++) {
if (document.body.classList.contains(STATES[i])) {
document.body.classList.remove(STATES[activeState]);
activeState = activeState < STATES.length - 1 ? activeState + 1 : 0;
document.body.classList.add(STATES[activeState]);
MODE_BTN_TEXT_ELEMENT.innerText = LABELS[activeState];
document.cookie = CS_MODE_COOKIE_NAME + "=" + STATES[activeState] + "; path=/;max-age=315360000";
break;
}
}
}
// returns the value fo the cookie named name
// or null if not present.
function getCookie(name) {
var cookieList = document.cookie.split(";")
var value = null;
for (var i = 0; i < cookieList.length; i++) {
if (cookieList[i].indexOf(CS_MODE_COOKIE_NAME + "=") > -1) {
value = cookieList[i].substring(cookieList[i].indexOf('=') + 1);
}
}
return value;
}
cookieMode = getCookie(CS_MODE_COOKIE_NAME);
if (cookieMode !== null) {
for(var i = 0; i < STATES.length; i++) {
document.body.classList.remove(STATES[i]);
}
document.body.classList.add(cookieMode);
// cannot set activeState directly in here, in case cookie is not present
// (in which case, document.body will already have the class which was
// specified in /layouts/_default/baseof.html, which we will use later).
}
// now we can use document.body.classlist to set activeState.
for(var i = 0; i < STATES.length; i++) {
if (document.body.classList.contains(STATES[i])) {
activeState = i;
}
}
MODE_BTN_TEXT_ELEMENT.innerText = LABELS[activeState];
// if activeState is valid, add button's event listener,
// otherwise hide the toggle button.
if (activeState > -1) {
document.getElementById(CS_BTN_CLASS).addEventListener('click', function() {
toggleColorscheme();
})
} else {
document.getElementById(CS_BTN_CONTAINER_CLASS).style.display = "none";
}
})();