This repository has been archived on 2023-10-15. You can view files and clone it, but cannot push or open issues or pull requests.

81 lines
2.5 KiB
JavaScript

// Set theme on load.
function init() {
// Default to light theme.
let theme = 'light'
// Check media query prefer and set it as dark.
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme = 'dark';
}
// Add event handler so if they change media query it'll update. overkill? yes.
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
let theme = event.matches ? "dark" : "light";
applyTheme(theme);
});
// If they have manually changed it use that theme instead.
theme = localStorage.getItem("theme") ?? theme
// Set it on body.
document.body.dataset.theme = theme;
// If dark-mode was toggle above we need to fix the icon.
let toggle = document.getElementsByName("dark-mode-toggle")[0];
// if it's already dark check it.
toggle.checked = theme === 'dark';
applyTheme(theme);
}
// Toggle the theme.
function darkLight() {
// Get current theme.
let element = document.body;
// Invert it.
switch (element.dataset.theme) {
case "light":
element.dataset.theme = "dark";
break;
case "dark":
element.dataset.theme = "light";
break;
}
localStorage.setItem("theme", element.dataset.theme);
applyTheme(element.dataset.theme);
}
// Apply theme
function applyTheme(theme) {
let primaryElements
// Find elements and update class.
switch (theme) {
case 'dark':
test = Array('.is-primary-invert|is-primary', '.sel-button|sel-button-dark' , '.innercontainer|innercontainer-dark')
test.forEach((t) => {
let c = t.split('|')
primaryElements = Array.from(document.querySelectorAll(c[0]));
primaryElements.forEach((element) => {
element.classList.remove(c[0].split('.')[1]);
element.classList.add(c[1]);
});
})
break;
case 'light':
test = Array('.is-primary|is-primary-invert', '.sel-button-dark|sel-button' , '.innercontainer-dark|innercontainer')
test.forEach((t) => {
let c = t.split('|')
primaryElements = Array.from(document.querySelectorAll(c[0]));
primaryElements.forEach((element) => {
element.classList.remove(c[0].split('.')[1]);
element.classList.add(c[1]);
});
})
break;
}
}