Molodetz blogrol volgens DPP-template
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import "./components/index.js";
|
||||
import { ContentEnhancer } from "./utils/ContentEnhancer.js";
|
||||
import { FormManager } from "./utils/FormManager.js";
|
||||
import { Http } from "./utils/Http.js";
|
||||
import { LocalTime } from "./utils/LocalTime.js";
|
||||
import { MobileNav } from "./utils/MobileNav.js";
|
||||
import { ModalManager } from "./utils/ModalManager.js";
|
||||
import { PresenceManager } from "./utils/PresenceManager.js";
|
||||
import { ScrollMemory } from "./utils/ScrollMemory.js";
|
||||
import { Tabs } from "./utils/Tabs.js";
|
||||
import { TermsGate } from "./utils/TermsGate.js";
|
||||
import { Toast } from "./utils/Toast.js";
|
||||
|
||||
export class Application {
|
||||
constructor() {
|
||||
this.dialog = document.querySelector("dp-dialog") || document.body.appendChild(document.createElement("dp-dialog"));
|
||||
this.toastHost = document.querySelector("dp-toast");
|
||||
this.http = Http;
|
||||
this.termsGate = new TermsGate(this.dialog);
|
||||
Http.termsGate = this.termsGate;
|
||||
this.forms = new FormManager(this.dialog);
|
||||
this.modals = new ModalManager();
|
||||
this.time = new LocalTime();
|
||||
this.nav = new MobileNav();
|
||||
this.tabs = new Tabs();
|
||||
this.scroll = new ScrollMemory();
|
||||
this.presence = new PresenceManager();
|
||||
this.enhancer = new ContentEnhancer();
|
||||
this.wireCopy();
|
||||
}
|
||||
|
||||
toast(message, kind = "info") {
|
||||
if (this.toastHost?.show) {
|
||||
this.toastHost.show(message, kind);
|
||||
}
|
||||
}
|
||||
|
||||
wireCopy() {
|
||||
document.querySelectorAll("[data-copy]").forEach((node) => {
|
||||
node.title = "Klik om te kopi\u00ebren";
|
||||
node.addEventListener("click", async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(node.textContent.trim());
|
||||
this.toast("Gekopieerd");
|
||||
} catch {
|
||||
Toast.flash(node, "Kopi\u00ebren mislukt", 1500);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
window.app = new Application();
|
||||
document.documentElement.dataset.app = "ready";
|
||||
@@ -0,0 +1,35 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class Avatar extends Component {
|
||||
static tag = "dp-avatar";
|
||||
static observedAttributes = ["seed", "uid", "size", "online"];
|
||||
|
||||
setup() {
|
||||
this.render();
|
||||
}
|
||||
|
||||
attributeChangedCallback() {
|
||||
if (this.dataset.ready) {
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const uid = this.getAttribute("uid") || "";
|
||||
const size = Number(this.getAttribute("size") || 32);
|
||||
this.replaceChildren();
|
||||
const img = document.createElement("img");
|
||||
img.className = "avatar";
|
||||
img.alt = "";
|
||||
img.width = size;
|
||||
img.height = size;
|
||||
const seed = this.getAttribute("seed") || uid;
|
||||
img.src = `/avatar/svg/${encodeURIComponent(seed)}?size=${size}`;
|
||||
const dot = document.createElement("span");
|
||||
dot.className = "presence-dot";
|
||||
dot.dataset.presenceUid = uid;
|
||||
dot.classList.toggle("online", this.hasAttribute("online"));
|
||||
this.append(img, dot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class Chat extends Component {
|
||||
static tag = "dp-chat";
|
||||
|
||||
setup() {
|
||||
this.log = document.createElement("div");
|
||||
this.log.className = "chat-log";
|
||||
this.log.setAttribute("aria-live", "polite");
|
||||
const form = document.createElement("form");
|
||||
form.className = "chat-form";
|
||||
this.input = document.createElement("textarea");
|
||||
this.input.rows = 2;
|
||||
this.input.setAttribute("aria-label", "Bericht");
|
||||
const send = document.createElement("button");
|
||||
send.type = "submit";
|
||||
send.className = "button small";
|
||||
send.textContent = "Verstuur";
|
||||
form.append(this.input, send);
|
||||
form.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
const text = this.input.value.trim();
|
||||
if (text) {
|
||||
this.emit("dp-chat-send", { text });
|
||||
this.input.value = "";
|
||||
}
|
||||
});
|
||||
this.append(this.log, form);
|
||||
}
|
||||
|
||||
addMessage(author, text) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "chat-line";
|
||||
const who = document.createElement("strong");
|
||||
who.textContent = author;
|
||||
const body = document.createElement("span");
|
||||
body.textContent = ` ${text}`;
|
||||
item.append(who, body);
|
||||
this.log.append(item);
|
||||
this.log.scrollTop = this.log.scrollHeight;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import hljs from "../../vendor/highlight.es.min.js";
|
||||
import { Component } from "./Component.js";
|
||||
import { Toast } from "../utils/Toast.js";
|
||||
|
||||
export class Code extends Component {
|
||||
static tag = "dp-code";
|
||||
|
||||
setup() {
|
||||
requestAnimationFrame(() => this.enhance());
|
||||
}
|
||||
|
||||
enhance() {
|
||||
const code = this.querySelector("pre > code");
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
hljs.highlightElement(code);
|
||||
} catch (error) {
|
||||
console.debug("highlight failed", error);
|
||||
}
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "copy-button";
|
||||
button.textContent = "Kopieer";
|
||||
button.addEventListener("click", async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(code.textContent);
|
||||
Toast.flash(button, "Gekopieerd", 1500, "Kopieer");
|
||||
} catch {
|
||||
Toast.flash(button, "Mislukt", 1500, "Kopieer");
|
||||
}
|
||||
});
|
||||
this.prepend(button);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class Component extends HTMLElement {
|
||||
static tag = "";
|
||||
|
||||
static define() {
|
||||
if (this.tag && !customElements.get(this.tag)) {
|
||||
customElements.define(this.tag, this);
|
||||
}
|
||||
}
|
||||
|
||||
emit(name, detail = {}) {
|
||||
this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
if (!this.dataset.ready) {
|
||||
this.dataset.ready = "1";
|
||||
this.setup();
|
||||
}
|
||||
}
|
||||
|
||||
setup() {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
import { ContentRenderer } from "../utils/ContentRenderer.js";
|
||||
|
||||
export class Content extends Component {
|
||||
static tag = "dp-content";
|
||||
|
||||
setup() {
|
||||
const source = this.querySelector('script[type="text/markdown"]');
|
||||
if (source) {
|
||||
this.markdown = source.textContent;
|
||||
}
|
||||
}
|
||||
|
||||
set markdown(text) {
|
||||
this.innerHTML = ContentRenderer.render(text);
|
||||
this.querySelectorAll("pre > code").forEach((code) => {
|
||||
const host = document.createElement("dp-code");
|
||||
code.parentElement.replaceWith(host);
|
||||
host.appendChild(code.parentElement);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class ContextMenu extends Component {
|
||||
static tag = "dp-context-menu";
|
||||
|
||||
setup() {
|
||||
this.hidden = true;
|
||||
document.addEventListener("click", (event) => {
|
||||
if (!this.contains(event.target)) {
|
||||
this.close();
|
||||
}
|
||||
});
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
this.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
open(x, y, items) {
|
||||
this.replaceChildren();
|
||||
items.forEach((item) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = item.label;
|
||||
button.addEventListener("click", () => {
|
||||
this.close();
|
||||
item.action();
|
||||
});
|
||||
this.append(button);
|
||||
});
|
||||
this.style.left = `${Math.min(x, window.innerWidth - 220)}px`;
|
||||
this.style.top = `${y}px`;
|
||||
this.hidden = false;
|
||||
}
|
||||
|
||||
close() {
|
||||
this.hidden = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class Dialog extends Component {
|
||||
static tag = "dp-dialog";
|
||||
|
||||
setup() {
|
||||
this.className = "modal-overlay";
|
||||
this.setAttribute("role", "alertdialog");
|
||||
this.setAttribute("aria-modal", "true");
|
||||
}
|
||||
|
||||
confirm(message, { okLabel = "Ja", cancelLabel = "Annuleren" } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
this.replaceChildren();
|
||||
const box = document.createElement("div");
|
||||
box.className = "modal";
|
||||
const text = document.createElement("p");
|
||||
text.textContent = message;
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "actions";
|
||||
const ok = document.createElement("button");
|
||||
ok.type = "button";
|
||||
ok.className = "button";
|
||||
ok.textContent = okLabel;
|
||||
const cancel = document.createElement("button");
|
||||
cancel.type = "button";
|
||||
cancel.className = "button ghost";
|
||||
cancel.textContent = cancelLabel;
|
||||
actions.append(cancel, ok);
|
||||
box.append(text, actions);
|
||||
this.append(box);
|
||||
this.classList.add("visible");
|
||||
const finish = (value) => {
|
||||
this.classList.remove("visible");
|
||||
document.removeEventListener("keydown", onKey);
|
||||
resolve(value);
|
||||
};
|
||||
const onKey = (event) => {
|
||||
if (event.key === "Escape") {
|
||||
finish(false);
|
||||
}
|
||||
};
|
||||
document.addEventListener("keydown", onKey);
|
||||
ok.addEventListener("click", () => finish(true));
|
||||
cancel.addEventListener("click", () => finish(false));
|
||||
ok.focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class Lightbox extends Component {
|
||||
static tag = "dp-lightbox";
|
||||
|
||||
setup() {
|
||||
this.setAttribute("role", "dialog");
|
||||
this.setAttribute("aria-modal", "true");
|
||||
this.setAttribute("aria-label", "Afbeelding");
|
||||
this.hidden = true;
|
||||
this.image = document.createElement("img");
|
||||
this.image.alt = "";
|
||||
this.caption = document.createElement("p");
|
||||
this.caption.className = "caption";
|
||||
this.closeButton = document.createElement("button");
|
||||
this.closeButton.type = "button";
|
||||
this.closeButton.className = "modal-close lightbox-close";
|
||||
this.closeButton.setAttribute("aria-label", "Sluiten");
|
||||
this.closeButton.textContent = "\u00d7";
|
||||
this.append(this.closeButton, this.image, this.caption);
|
||||
this.items = [];
|
||||
this.index = 0;
|
||||
document.addEventListener("click", (event) => this.onDocumentClick(event));
|
||||
this.addEventListener("click", (event) => {
|
||||
if (event.target === this || event.target === this.closeButton) {
|
||||
this.close();
|
||||
}
|
||||
});
|
||||
document.addEventListener("keydown", (event) => this.onKey(event));
|
||||
}
|
||||
|
||||
onDocumentClick(event) {
|
||||
const link = event.target.closest("[data-lightbox]");
|
||||
if (!link || event.metaKey || event.ctrlKey) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
this.items = [...document.querySelectorAll("[data-lightbox]")];
|
||||
this.show(this.items.indexOf(link));
|
||||
}
|
||||
|
||||
show(index) {
|
||||
this.index = (index + this.items.length) % this.items.length;
|
||||
const link = this.items[this.index];
|
||||
this.image.src = link.getAttribute("href");
|
||||
this.image.alt = link.dataset.caption || "";
|
||||
this.caption.textContent = link.dataset.caption || "";
|
||||
this.hidden = false;
|
||||
this.classList.add("visible");
|
||||
this.closeButton.focus();
|
||||
}
|
||||
|
||||
close() {
|
||||
this.hidden = true;
|
||||
this.classList.remove("visible");
|
||||
this.image.removeAttribute("src");
|
||||
}
|
||||
|
||||
onKey(event) {
|
||||
if (this.hidden) {
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
this.close();
|
||||
} else if (event.key === "ArrowRight") {
|
||||
this.show(this.index + 1);
|
||||
} else if (event.key === "ArrowLeft") {
|
||||
this.show(this.index - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
import { ContentRenderer } from "../utils/ContentRenderer.js";
|
||||
|
||||
export class Title extends Component {
|
||||
static tag = "dp-title";
|
||||
|
||||
setup() {
|
||||
const text = this.textContent;
|
||||
this.innerHTML = ContentRenderer.render(text, { inline: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class ToastHost extends Component {
|
||||
static tag = "dp-toast";
|
||||
|
||||
setup() {
|
||||
this.setAttribute("role", "status");
|
||||
this.setAttribute("aria-live", "polite");
|
||||
}
|
||||
|
||||
show(message, kind = "info", ms = 3500) {
|
||||
const item = document.createElement("div");
|
||||
item.className = `toast ${kind}`;
|
||||
item.textContent = message;
|
||||
this.append(item);
|
||||
setTimeout(() => item.remove(), ms);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Component } from "./Component.js";
|
||||
|
||||
export class Upload extends Component {
|
||||
static tag = "dp-upload";
|
||||
|
||||
setup() {
|
||||
this.input = document.createElement("input");
|
||||
this.input.type = "file";
|
||||
this.input.multiple = this.hasAttribute("multiple");
|
||||
this.input.accept = this.getAttribute("accept") || "image/*";
|
||||
this.input.className = "sr-only";
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "button ghost small";
|
||||
button.textContent = this.getAttribute("label") || "Bestand kiezen";
|
||||
button.addEventListener("click", () => this.input.click());
|
||||
this.input.addEventListener("change", () => this.emit("dp-files", { files: [...this.input.files] }));
|
||||
this.addEventListener("dragover", (event) => {
|
||||
event.preventDefault();
|
||||
this.classList.add("dragging");
|
||||
});
|
||||
this.addEventListener("dragleave", () => this.classList.remove("dragging"));
|
||||
this.addEventListener("drop", (event) => {
|
||||
event.preventDefault();
|
||||
this.classList.remove("dragging");
|
||||
this.emit("dp-files", { files: [...event.dataTransfer.files] });
|
||||
});
|
||||
this.append(this.input, button);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Avatar } from "./Avatar.js";
|
||||
import { Chat } from "./Chat.js";
|
||||
import { Code } from "./Code.js";
|
||||
import { Content } from "./Content.js";
|
||||
import { ContextMenu } from "./ContextMenu.js";
|
||||
import { Dialog } from "./Dialog.js";
|
||||
import { Lightbox } from "./Lightbox.js";
|
||||
import { Title } from "./Title.js";
|
||||
import { ToastHost } from "./ToastHost.js";
|
||||
import { Upload } from "./Upload.js";
|
||||
|
||||
[Avatar, Chat, Code, Content, ContextMenu, Dialog, Lightbox, Title, ToastHost, Upload].forEach((component) => component.define());
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,63 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { LoadingButton } from "./LoadingButton.js";
|
||||
|
||||
export class ApiTester {
|
||||
constructor() {
|
||||
document.querySelectorAll("[data-endpoint] [data-send]").forEach((button) => {
|
||||
button.addEventListener("click", () => this.send(button));
|
||||
});
|
||||
}
|
||||
|
||||
async send(button) {
|
||||
const section = button.closest("[data-endpoint]");
|
||||
const output = section.querySelector("[data-response]");
|
||||
if (section.dataset.destructive === "1") {
|
||||
const accepted = await window.app.dialog.confirm("Dit verzoek wijzigt echte data. Doorgaan?");
|
||||
if (!accepted) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let path = section.dataset.path;
|
||||
const query = new URLSearchParams();
|
||||
const body = {};
|
||||
section.querySelectorAll("[data-param]").forEach((input) => {
|
||||
const name = input.dataset.param;
|
||||
const value = input.value;
|
||||
if (input.dataset.location === "path") {
|
||||
path = path.replace(`{${name}}`, encodeURIComponent(value));
|
||||
} else if (input.dataset.location === "query") {
|
||||
if (value !== "") {
|
||||
query.set(name, value);
|
||||
}
|
||||
} else {
|
||||
body[name] = value;
|
||||
}
|
||||
});
|
||||
const method = section.dataset.method;
|
||||
const url = query.toString() ? `${path}?${query}` : path;
|
||||
const options = { method, credentials: "same-origin", headers: { Accept: "application/json" } };
|
||||
if (method !== "GET") {
|
||||
options.headers["Content-Type"] = "application/json";
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
LoadingButton.setLoading(button, true);
|
||||
const started = performance.now();
|
||||
try {
|
||||
const response = await fetch(url, options);
|
||||
const text = await response.text();
|
||||
let pretty = text;
|
||||
try {
|
||||
pretty = JSON.stringify(JSON.parse(text), null, 2);
|
||||
} catch {
|
||||
pretty = text.slice(0, 4000);
|
||||
}
|
||||
output.textContent = `${response.status} ${response.statusText} (${Math.round(performance.now() - started)} ms)\n\n${pretty}`;
|
||||
} catch (error) {
|
||||
output.textContent = `Fout: ${error.message}`;
|
||||
} finally {
|
||||
LoadingButton.setLoading(button, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.apiTester = new ApiTester();
|
||||
@@ -0,0 +1,16 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class AssetUrl {
|
||||
static version() {
|
||||
const meta = document.querySelector('meta[name="asset-version"]');
|
||||
return meta ? meta.content : "";
|
||||
}
|
||||
|
||||
static resolve(path) {
|
||||
if (!path.startsWith("/static/") || path.startsWith("/static/uploads/")) {
|
||||
return path;
|
||||
}
|
||||
return `/static/v${AssetUrl.version()}/${path.slice("/static/".length)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const assetUrl = (path) => AssetUrl.resolve(path);
|
||||
@@ -0,0 +1,10 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class ContentEnhancer {
|
||||
constructor() {
|
||||
document.querySelectorAll("[data-enhance] pre > code, [data-docs-content] pre > code").forEach((code) => {
|
||||
const host = document.createElement("dp-code");
|
||||
code.parentElement.replaceWith(host);
|
||||
host.appendChild(code.parentElement);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { marked } from "../../vendor/marked.esm.js";
|
||||
import DOMPurify from "../../vendor/purify.es.mjs";
|
||||
import { EMOJI_MAP } from "../generated/EmojiMap.js";
|
||||
|
||||
export class ContentRenderer {
|
||||
static ALLOWED_URI = /^(?:(?:https?|mailto|tel):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
|
||||
|
||||
static normalize(text) {
|
||||
return (text || "").replace(/[\u2013\u2014]/g, "-").replace(/:([a-z0-9_+-]+):/g, (match, name) => EMOJI_MAP[name] || match);
|
||||
}
|
||||
|
||||
static render(text, { inline = false } = {}) {
|
||||
try {
|
||||
const source = ContentRenderer.normalize(text);
|
||||
const html = inline ? marked.parseInline(source) : marked.parse(source, { gfm: true, breaks: true });
|
||||
return DOMPurify.sanitize(html, { ALLOWED_URI_REGEXP: ContentRenderer.ALLOWED_URI });
|
||||
} catch (error) {
|
||||
console.error("render failed", error);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class EditorPreview {
|
||||
constructor() {
|
||||
this.source = document.querySelector("[data-preview-source]");
|
||||
this.target = document.querySelector("[data-preview-target]");
|
||||
if (!this.source || !this.target) {
|
||||
return;
|
||||
}
|
||||
this.timer = null;
|
||||
this.source.addEventListener("input", () => this.schedule());
|
||||
customElements.whenDefined("dp-content").then(() => this.update());
|
||||
}
|
||||
|
||||
schedule() {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.update(), 150);
|
||||
}
|
||||
|
||||
update() {
|
||||
this.target.markdown = this.source.value;
|
||||
}
|
||||
}
|
||||
|
||||
window.editorPreview = new EditorPreview();
|
||||
@@ -0,0 +1,30 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { LoadingButton } from "./LoadingButton.js";
|
||||
|
||||
export class FormManager {
|
||||
constructor(dialog) {
|
||||
this.dialog = dialog;
|
||||
document.addEventListener("submit", (event) => this.onSubmit(event), true);
|
||||
}
|
||||
|
||||
async onSubmit(event) {
|
||||
const form = event.target;
|
||||
if (!(form instanceof HTMLFormElement)) {
|
||||
return;
|
||||
}
|
||||
if (form.dataset.confirm && form.dataset.confirmed !== "1") {
|
||||
event.preventDefault();
|
||||
const accepted = await this.dialog.confirm(form.dataset.confirm);
|
||||
if (accepted) {
|
||||
form.dataset.confirmed = "1";
|
||||
form.requestSubmit(event.submitter || undefined);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const button = event.submitter || form.querySelector("[data-loading]");
|
||||
if (button && button.hasAttribute("data-loading")) {
|
||||
LoadingButton.setLoading(button, true);
|
||||
window.addEventListener("pageshow", () => LoadingButton.setLoading(button, false), { once: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class Http {
|
||||
static termsGate = null;
|
||||
|
||||
static suspend() {
|
||||
return new Promise(() => {});
|
||||
}
|
||||
|
||||
static async getJson(url) {
|
||||
const response = await fetch(url, { headers: { Accept: "application/json" }, credentials: "same-origin" });
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status} ${response.statusText}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
static async #post(url, body, headers) {
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
body,
|
||||
credentials: "same-origin",
|
||||
headers: { Accept: "application/json", ...headers },
|
||||
});
|
||||
if (response.status === 403 && Http.termsGate) {
|
||||
const handled = await Http.termsGate.intercept(response.clone());
|
||||
if (handled) {
|
||||
return Http.#post(url, body, headers);
|
||||
}
|
||||
}
|
||||
if (response.redirected && response.url.includes("/auth/login")) {
|
||||
window.location.href = response.url;
|
||||
return Http.suspend();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
static async send(url, data = {}) {
|
||||
const response = await Http.#post(url, JSON.stringify(data), { "Content-Type": "application/json" });
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok || payload.ok === false) {
|
||||
const message = payload.error?.message || (payload.messages || []).join(", ") || response.statusText;
|
||||
throw new Error(message);
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
static async sendForm(url, form) {
|
||||
const body = new URLSearchParams(new FormData(form));
|
||||
const response = await Http.#post(url, body, { "Content-Type": "application/x-www-form-urlencoded" });
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
throw new Error(`${response.status} ${payload.error?.message || (payload.messages || []).join(", ") || ""}`.trim());
|
||||
}
|
||||
return response.json().catch(() => ({ ok: true }));
|
||||
}
|
||||
|
||||
static postJson(url, data) {
|
||||
return Http.send(url, data);
|
||||
}
|
||||
|
||||
static postForm(url, form) {
|
||||
return Http.sendForm(url, form);
|
||||
}
|
||||
|
||||
static async sendDelete(url) {
|
||||
const response = await fetch(url, { method: "DELETE", credentials: "same-origin", headers: { Accept: "application/json" } });
|
||||
if (!response.ok) {
|
||||
throw new Error(`${response.status}`);
|
||||
}
|
||||
return response.json().catch(() => ({ ok: true }));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class LoadingButton {
|
||||
static setLoading(button, on) {
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
button.classList.toggle("is-loading", on);
|
||||
button.disabled = on;
|
||||
button.setAttribute("aria-busy", on ? "true" : "false");
|
||||
const existing = button.querySelector(".spinner");
|
||||
if (on && !existing) {
|
||||
const spinner = document.createElement("span");
|
||||
spinner.className = "spinner";
|
||||
spinner.setAttribute("aria-hidden", "true");
|
||||
button.prepend(spinner);
|
||||
} else if (!on && existing) {
|
||||
existing.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Poller } from "./Poller.js";
|
||||
|
||||
export class LocalTime {
|
||||
constructor() {
|
||||
this.dateFormat = new Intl.DateTimeFormat("nl-NL", { day: "2-digit", month: "2-digit", year: "numeric" });
|
||||
this.timeFormat = new Intl.DateTimeFormat("nl-NL", { hour: "2-digit", minute: "2-digit" });
|
||||
this.fullFormat = new Intl.DateTimeFormat("nl-NL", { dateStyle: "full", timeStyle: "long" });
|
||||
this.relative = new Intl.RelativeTimeFormat("nl-NL", { numeric: "auto" });
|
||||
this.renderAll(document);
|
||||
this.observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => mutation.addedNodes.forEach((node) => node.nodeType === 1 && this.renderAll(node)));
|
||||
});
|
||||
this.observer.observe(document.body, { childList: true, subtree: true });
|
||||
this.poller = new Poller(() => this.renderAll(document, "ago"), 60000, { pauseHidden: true }).start();
|
||||
}
|
||||
|
||||
renderAll(root, onlyMode = null) {
|
||||
const nodes = root.matches?.("time[data-dt]") ? [root] : root.querySelectorAll("time[data-dt]");
|
||||
nodes.forEach((node) => {
|
||||
if (!onlyMode || node.dataset.mode === onlyMode) {
|
||||
this.render(node);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
render(node) {
|
||||
const date = new Date(node.dataset.dt);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return;
|
||||
}
|
||||
const mode = node.dataset.mode || "datetime";
|
||||
node.title = this.fullFormat.format(date);
|
||||
if (mode === "date") {
|
||||
node.textContent = this.dateFormat.format(date).replaceAll("-", "/");
|
||||
} else if (mode === "time") {
|
||||
node.textContent = this.timeFormat.format(date);
|
||||
} else if (mode === "ago") {
|
||||
node.textContent = this.ago(date);
|
||||
} else {
|
||||
node.textContent = `${this.dateFormat.format(date).replaceAll("-", "/")} ${this.timeFormat.format(date)}`;
|
||||
}
|
||||
}
|
||||
|
||||
ago(date) {
|
||||
const seconds = Math.round((date.getTime() - Date.now()) / 1000);
|
||||
const steps = [["year", 31536000], ["month", 2592000], ["day", 86400], ["hour", 3600], ["minute", 60]];
|
||||
for (const [unit, size] of steps) {
|
||||
if (Math.abs(seconds) >= size) {
|
||||
return this.relative.format(Math.round(seconds / size), unit);
|
||||
}
|
||||
}
|
||||
return this.relative.format(seconds, "second");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class MobileNav {
|
||||
constructor() {
|
||||
this.toggle = document.querySelector("[data-nav-toggle]");
|
||||
this.panel = document.getElementById("nav-links");
|
||||
if (!this.toggle || !this.panel) {
|
||||
return;
|
||||
}
|
||||
this.toggle.addEventListener("click", () => {
|
||||
const open = this.panel.classList.toggle("open");
|
||||
this.toggle.setAttribute("aria-expanded", open ? "true" : "false");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class ModalManager {
|
||||
constructor() {
|
||||
this.stack = [];
|
||||
document.addEventListener("click", (event) => this.onClick(event));
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape" && this.stack.length) {
|
||||
this.close(this.stack[this.stack.length - 1]);
|
||||
}
|
||||
});
|
||||
window.addEventListener("popstate", () => {
|
||||
if (this.stack.length) {
|
||||
this.close(this.stack[this.stack.length - 1], false);
|
||||
}
|
||||
});
|
||||
new MutationObserver(() => this.wire()).observe(document.body, { childList: true, subtree: true });
|
||||
this.wire();
|
||||
}
|
||||
|
||||
wire() {
|
||||
document.querySelectorAll(".modal-overlay:not([data-wired])").forEach((overlay) => {
|
||||
overlay.dataset.wired = "1";
|
||||
overlay.setAttribute("role", overlay.getAttribute("role") || "dialog");
|
||||
overlay.setAttribute("aria-modal", "true");
|
||||
overlay.addEventListener("keydown", (event) => this.trap(event, overlay));
|
||||
});
|
||||
}
|
||||
|
||||
onClick(event) {
|
||||
const trigger = event.target.closest("[data-modal]");
|
||||
if (trigger) {
|
||||
event.preventDefault();
|
||||
this.open(document.getElementById(trigger.dataset.modal));
|
||||
return;
|
||||
}
|
||||
if (event.target.closest(".modal-close")) {
|
||||
this.close(event.target.closest(".modal-overlay"));
|
||||
return;
|
||||
}
|
||||
if (event.target.classList?.contains("modal-overlay")) {
|
||||
this.close(event.target);
|
||||
}
|
||||
}
|
||||
|
||||
open(overlay) {
|
||||
if (!overlay) {
|
||||
return;
|
||||
}
|
||||
overlay.classList.add("visible");
|
||||
this.stack.push(overlay);
|
||||
history.pushState({ modal: overlay.id }, "");
|
||||
overlay.querySelector("button, a, input, select, textarea")?.focus();
|
||||
}
|
||||
|
||||
close(overlay, popHistory = true) {
|
||||
if (!overlay) {
|
||||
return;
|
||||
}
|
||||
overlay.classList.remove("visible");
|
||||
this.stack = this.stack.filter((item) => item !== overlay);
|
||||
if (popHistory && history.state?.modal === overlay.id) {
|
||||
history.back();
|
||||
}
|
||||
}
|
||||
|
||||
trap(event, overlay) {
|
||||
if (event.key !== "Tab") {
|
||||
return;
|
||||
}
|
||||
const focusable = [...overlay.querySelectorAll("button, a[href], input, select, textarea")].filter((el) => !el.disabled);
|
||||
if (!focusable.length) {
|
||||
return;
|
||||
}
|
||||
const first = focusable[0];
|
||||
const last = focusable[focusable.length - 1];
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class Poller {
|
||||
constructor(fn, intervalMs, { immediate = false, pauseHidden = true } = {}) {
|
||||
this.fn = fn;
|
||||
this.intervalMs = intervalMs;
|
||||
this.immediate = immediate;
|
||||
this.pauseHidden = pauseHidden;
|
||||
this.timer = null;
|
||||
this.busy = false;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.timer) {
|
||||
return this;
|
||||
}
|
||||
if (this.immediate) {
|
||||
this.tick();
|
||||
}
|
||||
this.timer = setInterval(() => this.tick(), this.intervalMs);
|
||||
return this;
|
||||
}
|
||||
|
||||
stop() {
|
||||
clearInterval(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
|
||||
async tick() {
|
||||
if (this.busy || (this.pauseHidden && document.hidden)) {
|
||||
return;
|
||||
}
|
||||
this.busy = true;
|
||||
try {
|
||||
await this.fn();
|
||||
} catch (error) {
|
||||
console.debug("poller tick failed", error);
|
||||
} finally {
|
||||
this.busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
|
||||
export class PresenceManager {
|
||||
constructor() {
|
||||
this.online = new Set();
|
||||
this.poller = null;
|
||||
if (document.querySelector("[data-presence-uid]")) {
|
||||
this.poller = new Poller(() => this.refresh(), 20000, { immediate: false }).start();
|
||||
}
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
const roster = await Http.getJson("/presence/roster");
|
||||
this.online = new Set(roster.online || []);
|
||||
this.render();
|
||||
}
|
||||
|
||||
render() {
|
||||
document.querySelectorAll("[data-presence-uid]").forEach((dot) => {
|
||||
dot.classList.toggle("online", this.online.has(dot.dataset.presenceUid));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class ScrollMemory {
|
||||
static KEY = "molodetz-scroll";
|
||||
static MAX_ENTRIES = 50;
|
||||
static MAX_AGE_MS = 60 * 60 * 1000;
|
||||
|
||||
constructor() {
|
||||
history.scrollRestoration = "manual";
|
||||
this.key = location.pathname + location.search;
|
||||
window.addEventListener("pagehide", () => this.save());
|
||||
const navigation = performance.getEntriesByType("navigation")[0];
|
||||
const type = navigation ? navigation.type : "navigate";
|
||||
if (type === "back_forward" || type === "reload" || sessionStorage.getItem("molodetz-restore") === this.key) {
|
||||
sessionStorage.removeItem("molodetz-restore");
|
||||
this.restore();
|
||||
}
|
||||
document.addEventListener("click", (event) => {
|
||||
const link = event.target.closest(".breadcrumbs a, a[data-back]");
|
||||
if (link) {
|
||||
sessionStorage.setItem("molodetz-restore", new URL(link.href).pathname);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
read() {
|
||||
try {
|
||||
return JSON.parse(sessionStorage.getItem(ScrollMemory.KEY) || "{}");
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
save() {
|
||||
const entries = this.read();
|
||||
entries[this.key] = { y: window.scrollY, at: Date.now() };
|
||||
const now = Date.now();
|
||||
const kept = Object.entries(entries)
|
||||
.filter(([, value]) => now - value.at < ScrollMemory.MAX_AGE_MS)
|
||||
.sort((a, b) => b[1].at - a[1].at)
|
||||
.slice(0, ScrollMemory.MAX_ENTRIES);
|
||||
sessionStorage.setItem(ScrollMemory.KEY, JSON.stringify(Object.fromEntries(kept)));
|
||||
}
|
||||
|
||||
restore() {
|
||||
const entry = this.read()[this.key];
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
const deadline = performance.now() + 1500;
|
||||
let aborted = false;
|
||||
const abort = () => { aborted = true; };
|
||||
["wheel", "touchstart", "keydown"].forEach((name) => window.addEventListener(name, abort, { once: true, passive: true }));
|
||||
const apply = () => {
|
||||
if (aborted) {
|
||||
return;
|
||||
}
|
||||
window.scrollTo(0, entry.y);
|
||||
if (Math.abs(window.scrollY - entry.y) > 2 && performance.now() < deadline) {
|
||||
requestAnimationFrame(apply);
|
||||
}
|
||||
};
|
||||
requestAnimationFrame(apply);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
import { Http } from "./Http.js";
|
||||
import { Poller } from "./Poller.js";
|
||||
|
||||
export class ServiceMonitor {
|
||||
constructor() {
|
||||
this.root = document.querySelector("[data-service-monitor]");
|
||||
if (!this.root) {
|
||||
return;
|
||||
}
|
||||
this.mode = this.root.dataset.serviceMonitor;
|
||||
this.poller = new Poller(() => this.refresh(), 3000).start();
|
||||
}
|
||||
|
||||
async refresh() {
|
||||
if (this.mode === "detail") {
|
||||
const payload = await Http.getJson(`/admin/services/${encodeURIComponent(this.root.dataset.service)}`);
|
||||
this.renderDetail(payload.service || {});
|
||||
} else {
|
||||
const payload = await Http.getJson("/admin/services");
|
||||
(payload.services || []).forEach((service) => this.renderRow(service));
|
||||
}
|
||||
}
|
||||
|
||||
setStatus(node, status) {
|
||||
if (node) {
|
||||
node.className = `status ${status}`;
|
||||
node.textContent = status;
|
||||
}
|
||||
}
|
||||
|
||||
setTime(node, iso) {
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
node.replaceChildren();
|
||||
if (iso) {
|
||||
const time = document.createElement("time");
|
||||
time.dataset.dt = iso;
|
||||
time.dataset.mode = "datetime";
|
||||
time.dateTime = iso;
|
||||
time.textContent = iso;
|
||||
node.append(time);
|
||||
}
|
||||
}
|
||||
|
||||
renderRow(service) {
|
||||
const row = this.root.querySelector(`[data-service="${CSS.escape(service.name)}"]`);
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
this.setStatus(row.querySelector('[data-field="status"]'), service.status);
|
||||
this.setTime(row.querySelector('[data-field="last_run"]'), service.last_run);
|
||||
this.setTime(row.querySelector('[data-field="next_run"]'), service.next_run);
|
||||
}
|
||||
|
||||
renderDetail(service) {
|
||||
this.setStatus(this.root.querySelector('[data-field="status"]'), service.status);
|
||||
const logs = this.root.querySelector('[data-field="logs"]');
|
||||
if (logs) {
|
||||
logs.textContent = (service.logs || []).join("\n");
|
||||
}
|
||||
const cards = this.root.querySelector('[data-field="cards"]');
|
||||
if (cards && service.metrics?.cards) {
|
||||
cards.replaceChildren(...service.metrics.cards.map((card) => {
|
||||
const box = document.createElement("div");
|
||||
box.className = "stat-card";
|
||||
const value = document.createElement("span");
|
||||
value.className = "value";
|
||||
value.textContent = card.value;
|
||||
const name = document.createElement("span");
|
||||
name.className = "name";
|
||||
name.textContent = card.label;
|
||||
box.append(value, name);
|
||||
return box;
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.serviceMonitor = new ServiceMonitor();
|
||||
@@ -0,0 +1,20 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class Tabs {
|
||||
constructor() {
|
||||
document.addEventListener("click", (event) => {
|
||||
const button = event.target.closest("[data-tabs] [data-tab]");
|
||||
if (button) {
|
||||
this.select(button);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
select(button) {
|
||||
const bar = button.closest("[data-tabs]");
|
||||
const scope = bar.parentElement;
|
||||
bar.querySelectorAll("[data-tab]").forEach((item) => item.classList.toggle("active", item === button));
|
||||
scope.querySelectorAll(":scope > [data-panel]").forEach((panel) => {
|
||||
panel.hidden = panel.dataset.panel !== button.dataset.tab;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class TermsGate {
|
||||
constructor(dialog) {
|
||||
this.dialog = dialog;
|
||||
this.pending = null;
|
||||
}
|
||||
|
||||
async intercept(response) {
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (payload.error?.code !== "terms_required") {
|
||||
return false;
|
||||
}
|
||||
if (!this.pending) {
|
||||
this.pending = this.dialog
|
||||
.confirm(`De voorwaarden zijn gewijzigd (versie ${payload.error.terms_version}). Accepteren en doorgaan?`)
|
||||
.then(async (accepted) => {
|
||||
if (!accepted) {
|
||||
return false;
|
||||
}
|
||||
const result = await fetch("/voorwaarden/accept", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
||||
body: "{}",
|
||||
});
|
||||
return result.ok;
|
||||
})
|
||||
.finally(() => {
|
||||
setTimeout(() => { this.pending = null; }, 0);
|
||||
});
|
||||
}
|
||||
return this.pending;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// retoor <retoor@molodetz.nl>
|
||||
export class Toast {
|
||||
static flash(el, message, ms = 2000, revertTo = null) {
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
const original = revertTo ?? el.textContent;
|
||||
el.textContent = message;
|
||||
setTimeout(() => { el.textContent = original; }, ms);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user