brass/web/static/utils.js

58 lines
2.3 KiB
JavaScript

// delete confirmation dialog and attachment to elements
const fireConfirmModal = (event) => {
Swal.fire({ title: 'Wirklich löschen?', showCancelButton: true, cancelButtonText: 'Abbrechen', icon: 'warning', confirmButtonText: "Löschen", showCloseButton: true })
.then((result) => { if (result.isConfirmed) { htmx.trigger(event.target, 'confirmed'); } });
}
document.querySelectorAll("button[hx-trigger='confirmed']").forEach((value) => value.addEventListener("click", fireConfirmModal));
document.addEventListener("htmx:afterSwap", () => {
document.querySelectorAll("button[hx-trigger='confirmed']").forEach((value) => value.addEventListener("click", fireConfirmModal));
});
// light / dark mode interpretation for first load and switch behaviour respecting localStorage and CSS prefers-color-scheme
const getCurrentTheme = () => {
let current = localStorage.getItem("theme");
if (current === null) {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
current = "dark";
} else {
current = "light";
}
}
return current;
}
const setThemeSwitcherIconTo = (name) =>
document.querySelector("#theme-switcher use")?.setAttribute("href", `/static/feather-sprite.svg#${name}`)
const switchTheme = () => {
const currentTheme = getCurrentTheme();
const newTheme = currentTheme === "light" ? "dark" : "light";
const newIcon = currentTheme === "light" ? "sun" : "moon";
document.documentElement.setAttribute("data-theme", newTheme);
setThemeSwitcherIconTo(newIcon);
localStorage.setItem("theme", newTheme);
}
const observer = new MutationObserver((mutationList) => {
const foundNavbar = mutationList.flatMap((record) => Array.from(record.addedNodes))
.some((node) => node.className?.includes("navbar"));
if (foundNavbar) {
document.getElementById("theme-switcher")?.addEventListener("click", switchTheme);
setThemeSwitcherIconTo(getCurrentTheme() === "light" ? "moon" : "sun");
}
});
observer.observe(document, { childList: true, subtree: true });
const isCurrentlyLight = getCurrentTheme() === "light";
document.documentElement.setAttribute("data-theme", isCurrentlyLight ? "light" : "dark");
document.getElementById("theme-switcher")?.addEventListener("click", switchTheme);
setThemeSwitcherIconTo(isCurrentlyLight ? "moon" : "sun");