Adding automatic theme change

This commit is contained in:
Fabian
2019-07-02 19:10:16 +02:00
parent c3f9529feb
commit ae5257b2b3
4 changed files with 63 additions and 18 deletions

View File

@ -1,27 +1,52 @@
const light = require("!!raw-loader!@hibas123/theme/out/light.css").default;
const dark = require("!!raw-loader!@hibas123/theme/out/dark.css").default;
let isDark = localStorage.getItem("theme") === "dark";
export enum ThemeStates {
AUTO,
LIGHT,
DARK
}
let themeConfig: ThemeStates = Number(localStorage.getItem("theme"));
if (Number.isNaN(themeConfig))
themeConfig = ThemeStates.AUTO;
let isDark = false;
let mediaIsDark = false;
if (window.matchMedia) {
const mediaq = matchMedia("(prefers-color-scheme: dark)");
mediaIsDark = mediaq.matches;
mediaq.onchange = ev => {
mediaIsDark = ev.matches;
apply();
}
console.log(mediaq);
}
let styleElm: HTMLStyleElement;
function apply() {
if (styleElm) styleElm.remove();
styleElm = document.createElement("style");
document.head.appendChild(styleElm);
styleElm.innerHTML = isDark ? dark : light;
function apply(force?: boolean) {
let shouldDark = themeConfig === ThemeStates.AUTO ? mediaIsDark : themeConfig === ThemeStates.DARK;
if (force || shouldDark !== isDark) {
if (styleElm) styleElm.remove();
styleElm = document.createElement("style");
document.head.appendChild(styleElm);
styleElm.innerHTML = shouldDark ? dark : light;
isDark = shouldDark;
}
}
apply();
apply(true);
function toggle() {
isDark = !isDark;
localStorage.setItem("theme", isDark ? "dark" : "light");
function change(state: ThemeStates) {
themeConfig = state;
localStorage.setItem("theme", String(themeConfig));
apply();
}
export default {
active: () => isDark,
toggle: () => toggle()
active: () => themeConfig,
change: (state: ThemeStates) => change(state)
}