Files
coredns-web-ui/static/js/common.js
T
bryanpedini 5ac8f98f10 chore(ui): add module file and main stub
- chore(ui): add module file and main stub
- feat(ui): add layout, pages and partials
- feat(ui): add stylesheet and scripts
- feat(ui): add page renderer and static file handler
- test(ui): cover rendering, escaping and static serving
2026-11-19 15:46:12 +01:00

407 lines
13 KiB
JavaScript

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
const SVG_NS = "http://www.w3.org/2000/svg";
const ICONS = {
edit: "M4 20h4l10-10-4-4L4 16v4zM14 6l4 4",
trash: "M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13M10 11v6M14 11v6",
alert: "M12 4l9 16H3L12 4zM12 10v4M12 17v1",
chevron: "M9 6l6 6-6 6",
plus: "M12 5v14M5 12h14",
close: "M6 6l12 12M18 6L6 18",
};
export function h(tag, attrs, ...children) {
const el = document.createElement(tag);
applyAttrs(el, attrs);
append(el, children);
return el;
}
function applyAttrs(el, attrs) {
if (!attrs) return;
for (const [key, value] of Object.entries(attrs)) {
if (value === undefined || value === null || value === false) continue;
if (key === "class") {
el.className = value;
} else if (key === "text") {
el.textContent = value;
} else if (key.startsWith("on") && typeof value === "function") {
el.addEventListener(key.slice(2), value);
} else if (key === "value") {
el.value = value;
} else if (key === "checked" || key === "disabled" || key === "hidden" || key === "selected") {
el[key] = Boolean(value);
} else if (value === true) {
el.setAttribute(key, "");
} else {
el.setAttribute(key, String(value));
}
}
}
function append(el, children) {
for (const child of children.flat(Infinity)) {
if (child === undefined || child === null || child === false) continue;
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
}
export function icon(name) {
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "16");
svg.setAttribute("height", "16");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", ICONS[name] || "");
svg.append(path);
return svg;
}
export function clear(el) {
el.replaceChildren();
}
export function $(selector, root = document) {
return root.querySelector(selector);
}
export function appData() {
const app = document.getElementById("app");
return {
app,
username: app.dataset.username || "",
role: app.dataset.role || "",
zone: app.dataset.zone || "",
targetUser: app.dataset.targetUser || "",
isAdmin: app.dataset.role === "admin",
};
}
export class ApiError extends Error {
constructor(status, body) {
const message = body && typeof body.error === "string" && body.error ? body.error : defaultMessage(status);
super(message);
this.status = status;
this.body = body;
this.fields = body && body.fields && typeof body.fields === "object" ? body.fields : {};
}
}
function defaultMessage(status) {
switch (status) {
case 0: return "The server cannot be reached.";
case 403: return "You are not allowed to do this.";
case 404: return "Not found.";
case 409: return "The request conflicts with the current state.";
case 412: return "The data was changed by someone else.";
case 428: return "The request needs a current version of the data.";
case 429: return "Too many attempts. Try again later.";
case 503: return "The service is unavailable. Try again later.";
default: return "The request failed (status " + status + ").";
}
}
export async function api(method, path, options = {}) {
const headers = { Accept: "application/json" };
const init = { method, headers, credentials: "include" };
if (options.body !== undefined) {
headers["Content-Type"] = "application/json";
init.body = JSON.stringify(options.body);
}
if (options.ifMatch) headers["If-Match"] = options.ifMatch;
let url = "/api/v1" + path;
if (options.query) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.query)) {
if (value !== undefined && value !== null && value !== "") params.set(key, String(value));
}
const text = params.toString();
if (text) url += "?" + text;
}
let response;
try {
response = await fetch(url, init);
} catch (err) {
throw new ApiError(0, null);
}
if (response.status === 401) {
const next = location.pathname + location.search;
location.assign("/login?next=" + encodeURIComponent(next));
return new Promise(() => {});
}
const text = await response.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch (err) {
data = null;
}
}
if (!response.ok) throw new ApiError(response.status, data);
return { status: response.status, data, etag: response.headers.get("ETag") };
}
export const zonePath = (zone) => "/zones/" + encodeURIComponent(zone);
export const userPath = (username) => "/users/" + encodeURIComponent(username);
export function toast(message, options = {}) {
const region = document.getElementById("toasts");
const kind = options.kind || "info";
const item = h("div", { class: "toast toast-" + kind });
item.append(h("span", { class: "toast-text", text: message }));
if (options.action) {
item.append(h("button", {
type: "button",
class: "btn btn-small",
text: options.action.label,
onclick: () => {
item.remove();
options.action.run();
},
}));
}
const close = h("button", { type: "button", class: "btn btn-icon", "aria-label": "Dismiss notification", onclick: () => item.remove() });
close.append(icon("close"));
item.append(close);
region.append(item);
if (!options.action && kind !== "error") {
setTimeout(() => item.remove(), 8000);
}
return item;
}
export function flash(message) {
try {
sessionStorage.setItem("flash", message);
} catch (err) {
return;
}
}
export function showFlash() {
let message = null;
try {
message = sessionStorage.getItem("flash");
sessionStorage.removeItem("flash");
} catch (err) {
return;
}
if (message) toast(message);
}
export function clearErrors(form) {
for (const el of form.querySelectorAll(".field-error, .form-error")) el.remove();
for (const el of form.querySelectorAll("[aria-invalid]")) el.removeAttribute("aria-invalid");
}
let errorCounter = 0;
export function showFormError(form, message) {
let box = form.querySelector(".form-error");
if (!box) {
box = h("p", { class: "alert alert-error form-error", role: "alert" });
const body = form.querySelector(".dialog-body") || form;
body.prepend(box);
}
box.textContent = message;
}
export function showFieldErrors(form, fields, message) {
clearErrors(form);
const unmatched = [];
for (const [key, text] of Object.entries(fields || {})) {
const name = key.startsWith("data.") ? key.slice(5) : key;
const control = form.elements ? form.elements[name] : null;
if (control && control.nodeType === 1) {
errorCounter += 1;
const id = "field-error-" + errorCounter;
control.setAttribute("aria-invalid", "true");
control.setAttribute("aria-describedby", id);
control.insertAdjacentElement("afterend", h("p", { class: "field-error", id, text: String(text) }));
} else {
unmatched.push(key + ": " + text);
}
}
if (unmatched.length > 0 || message) {
showFormError(form, [message, ...unmatched].filter(Boolean).join(" "));
}
}
export function handleError(err, options = {}) {
if (!(err instanceof ApiError)) {
toast("Unexpected error: " + (err && err.message ? err.message : "unknown"), { kind: "error" });
return;
}
if (err.status === 422 && options.form) {
showFieldErrors(options.form, err.fields, Object.keys(err.fields).length === 0 ? err.message : "");
return;
}
if (err.status === 412) {
toast(err.message + " Reload to see the current data.", {
kind: "error",
action: { label: "Reload", run: options.reload || (() => location.reload()) },
});
return;
}
if (options.form) {
showFormError(options.form, err.message);
return;
}
toast(err.message, { kind: "error" });
}
export async function busy(button, task) {
if (button) button.disabled = true;
try {
return await task();
} finally {
if (button) button.disabled = false;
}
}
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
function trapFocus(dialog, event) {
if (event.key !== "Tab") return;
const items = [...dialog.querySelectorAll(FOCUSABLE)].filter((el) => !el.hidden && el.offsetParent !== null);
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items[items.length - 1];
if (event.shiftKey && (document.activeElement === first || !dialog.contains(document.activeElement))) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (document.activeElement === last || !dialog.contains(document.activeElement))) {
event.preventDefault();
first.focus();
}
}
export function setupDialog(dialog) {
if (dialog.dataset.ready) return;
dialog.dataset.ready = "1";
dialog.addEventListener("keydown", (event) => trapFocus(dialog, event));
dialog.addEventListener("click", (event) => {
if (event.target === dialog) dialog.close();
});
for (const button of dialog.querySelectorAll("[data-close]")) {
button.addEventListener("click", () => dialog.close());
}
}
export function setupDialogs() {
for (const dialog of document.querySelectorAll("dialog")) setupDialog(dialog);
}
export function openDialog(dialog) {
setupDialog(dialog);
const form = dialog.querySelector("form");
if (form) clearErrors(form);
dialog.showModal();
const first = dialog.querySelector("input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea");
if (first) first.focus();
}
export function confirmDialog(options) {
return new Promise((resolve) => {
const titleId = "confirm-title";
const dialog = h("dialog", { class: "dialog dialog-small", "aria-labelledby": titleId });
let result = false;
const confirmButton = h("button", {
type: "button",
class: "btn " + (options.danger === false ? "btn-primary" : "btn-danger"),
text: options.confirm || "Confirm",
onclick: () => {
result = true;
dialog.close();
},
});
dialog.append(
h("div", { class: "dialog-head" }, h("h2", { id: titleId, text: options.title })),
h("div", { class: "dialog-body" }, h("p", { text: options.message })),
h("div", { class: "dialog-actions" },
h("button", { type: "button", class: "btn", "data-close": true, text: "Cancel" }),
confirmButton),
);
dialog.addEventListener("close", () => {
dialog.remove();
resolve(result);
});
document.body.append(dialog);
setupDialog(dialog);
dialog.showModal();
confirmButton.focus();
});
}
export function formatTime(iso) {
if (!iso) return "-";
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return String(iso);
return date.toISOString().replace("T", " ").replace(/\.\d+Z$/, "").replace("Z", "");
}
export function formatTTL(ttl) {
if (ttl === null || ttl === undefined) return "missing";
if (ttl === 0) return "default (360 s)";
return String(ttl);
}
export function debounce(fn, ms) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
export function parseNumber(text) {
const value = String(text).trim();
return /^-?\d+$/.test(value) ? Number(value) : value;
}
export function option(value, label, selected) {
return h("option", { value, text: label, selected: Boolean(selected) });
}
export function plural(count, one, many) {
return count + " " + (count === 1 ? one : many);
}
export function zoneLink(name) {
return h("a", { href: "/zones/" + encodeURIComponent(name), text: name });
}
export function bindPasswordForm(form, submit) {
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
const password = form.elements.password.value;
if (password !== form.elements.repeat.value) {
showFieldErrors(form, { repeat: "The two passwords differ." });
return;
}
const button = form.querySelector("button[type=submit]");
await busy(button, async () => {
try {
await submit(form);
form.reset();
} catch (err) {
handleError(err, { form });
}
});
});
}