1
1
Fork 0
website/themes/meins/assets/js/index.ts

82 Zeilen
2.2 KiB
TypeScript

2022-06-26 19:55:39 +00:00
class Storage {
enabled: boolean
constructor() {
try {
if (localStorage) {
localStorage.setItem("__test", "")
localStorage.removeItem("__test")
this.enabled = true
console.debug("localstorage enabled")
}
} catch {
console.debug("Local storage not available")
}
}
set(key: string, value: any): void {
if (this.enabled) {
try {
localStorage.setItem(key, JSON.stringify(value))
} catch {
}
}
}
get(key: string, _default: any = null): any {
if (this.enabled) {
try {
let value = localStorage.getItem(key);
if (value !== null) {
return JSON.parse(value)
}
} catch {
}
}
return _default;
}
}
var storage = new Storage();
function settheme(theme: string): EventListener {
let body = document.getElementsByTagName("body")[0]
let classes = new Set(["dark", "black", "light"])
classes.delete(theme)
return function () {
console.info("Overriding theme to", theme)
body.classList.remove(...classes)
if (theme !== "auto") {
if (!body.classList.contains(theme)) {
body.classList.add(theme)
}
}
storage.set("theme", theme)
}
}
function init() {
let theme_elems = document.getElementsByClassName("theme")
let themeconfig: string = storage.get("theme", "auto")
for (let i = 0; i < theme_elems.length; i++) {
let theme_el = theme_elems.item(i) as HTMLInputElement
if (theme_el !== null) {
let theme = settheme(theme_el.id)
if (themeconfig === theme_el.id) {
theme(new Event("change"))
console.log(typeof theme_el, theme_el)
theme_el.select()
}
theme_el.addEventListener("change", theme)
console.info("added event to ", theme_el, "for theme", theme_el.id)
}
}
let body = document.getElementsByTagName("body")[0]
body.classList.add("interactive")
}
export {
init,
}