First version with CCNA 2 questions and answers
This commit is contained in:
72
src/helper/theme.ts
Normal file
72
src/helper/theme.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import "@hibas123/theme/out/base.css";
|
||||
|
||||
// const baseElm = document.createElement("style")
|
||||
// baseElm.innerHTML = base;
|
||||
// document.head.appendChild(baseElm);
|
||||
|
||||
import { readFileSync } from "fs";
|
||||
|
||||
const light = readFileSync("./node_modules/@hibas123/theme/out/light.css", "utf8")
|
||||
const dark = readFileSync("./node_modules/@hibas123/theme/out/dark.css", "utf8")
|
||||
|
||||
// import light from "@hibas123/theme/out/light.css";
|
||||
// import dark from "@hibas123/theme/out/dark.css";
|
||||
import { Observable } from "@hibas123/utils";
|
||||
import { readable } from "svelte/store";
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
const isDarkObs = new Observable<boolean>();
|
||||
export const DarkStore = readable(isDark, (set) => {
|
||||
const cb = val => set(val);
|
||||
isDarkObs.getPublicApi().subscribe(cb);
|
||||
return () => isDarkObs.getPublicApi().unsubscribe(cb);
|
||||
});
|
||||
|
||||
let styleElm: HTMLStyleElement;
|
||||
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;
|
||||
isDarkObs.send(isDark)
|
||||
}
|
||||
}
|
||||
apply(true);
|
||||
|
||||
function change(state: ThemeStates) {
|
||||
themeConfig = state;
|
||||
localStorage.setItem("theme", String(themeConfig));
|
||||
apply();
|
||||
}
|
||||
|
||||
export default {
|
||||
active: () => themeConfig,
|
||||
change: (state: ThemeStates) => change(state),
|
||||
isDark: () => isDark,
|
||||
isDarkObservable: isDarkObs.getPublicApi()
|
||||
}
|
||||
|
Reference in New Issue
Block a user