// retoor <retoor@molodetz.nl>
import { Toast } from "./Toast.js";
export class DomUtils {
constructor() {
this.initClipboardCopy();
this.initShareButtons();
this.initTogglers();
this.initStopPropagation();
this.initReload();
this.initCardNav();
}
static onDataAttr(attr, event, handler) {
document.querySelectorAll(`[data-${attr}]`).forEach((el) => {
el.addEventListener(event, (e) => handler(el, e));
});
}
static show(el) {
el.style.display = "block";
}
static hide(el) {
el.style.display = "none";
}
static toggle(el) {
el.style.display = el.style.display === "none" ? "block" : "none";
}
static isShown(el) {
return el.style.display === "block";
}
initClipboardCopy() {
DomUtils.onDataAttr("copy", "click", async (btn) => {
const source = document.getElementById(btn.dataset.copy);
if (!source) return;
try {
await navigator.clipboard.writeText(source.textContent);
Toast.flash(btn, "Copied!", 2000);
} catch {
// silently fail
}
});
}
initShareButtons() {
DomUtils.onDataAttr("share", "click", async (btn, e) => {
e.preventDefault();
e.stopPropagation();
const url = new URL(btn.dataset.share || window.location.href, window.location.href).href;
try {
await navigator.clipboard.writeText(url);
Toast.flash(btn, "Copied!", 1000);
} catch {
// silently fail
}
});
}
initTogglers() {
DomUtils.onDataAttr("toggle", "click", (btn) => {
const target = document.getElementById(btn.dataset.toggle);
if (target) target.classList.toggle("hidden");
});
}
initStopPropagation() {
DomUtils.onDataAttr("stop-propagation", "click", (el, e) => e.stopPropagation());
}
initReload() {
DomUtils.onDataAttr("reload", "click", () => window.location.reload());
}
initCardNav() {
DomUtils.onDataAttr("card-href", "click", (el, e) => {
if (e.target.closest("a, button")) {
return;
}
window.location.href = el.dataset.cardHref;
});
}
}