// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP. import { t, culture, applyStrings } from "./i18n.js"; export function escapeHtml(s) { return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); } /** Escaped attribute value for title="…" tooltips. */ export const attr = escapeHtml; export function formatNumber(n) { return new Intl.NumberFormat(culture()).format(n ?? 0); } /** 9.4 TB, 610 GB … (decimal units, like disk vendors and the desktop client). */ export function formatBytes(bytes) { const units = ["B", "KB", "MB", "GB", "TB", "PB"]; let value = Number(bytes ?? 0); let unit = 0; while (value >= 1000 && unit < units.length - 1) { value /= 1000; unit++; } const digits = value >= 100 || unit === 0 ? 0 : 1; return `${new Intl.NumberFormat(culture(), { maximumFractionDigits: digits }).format(value)} ${units[unit]}`; } export function formatTime(iso) { if (!iso) return "—"; const date = new Date(iso); const sameDay = new Date().toDateString() === date.toDateString(); return new Intl.DateTimeFormat(culture(), sameDay ? { timeStyle: "short" } : { dateStyle: "medium" }).format(date); } export function formatDateTime(iso) { return iso ? new Intl.DateTimeFormat(culture(), { dateStyle: "short", timeStyle: "medium" }).format(new Date(iso)) : "—"; } export function formatDuration(seconds) { const s = Math.max(0, Math.round(seconds ?? 0)); if (s >= 86400) return t("Common.Duration.Days", Math.floor(s / 86400), Math.floor((s % 86400) / 3600)); if (s >= 3600) return t("Common.Duration.Hours", Math.floor(s / 3600), Math.floor((s % 3600) / 60)); if (s >= 60) return t("Common.Duration.Minutes", Math.floor(s / 60)); return t("Common.Duration.Seconds", s); } /** A certificate fingerprint that wraps only between its byte pairs, always left to right. */ export function fingerprint(value) { return value ? `${String(value).split(":").map(escapeHtml).join(":")}` : "—"; } /** 6 px progress bar drawn as SVG (attributes, not inline styles). */ export function bar(fraction, muted = false) { const width = Math.max(0, Math.min(100, Math.round((fraction ?? 0) * 100))); return ``; } /** * Tooltip of a storage tile's figures (archive stats): the volume they measure and its file system; on an Unraid share * without a space volume, that they are the share's primary storage. */ export function storageTip(stats) { const lines = [stats.usesSpacePath ? t("Admin.Dashboard.SpaceVolume.Tip") : t("Admin.Dashboard.Storage.Tip")]; if (stats.fileSystem) lines.push(t("Admin.Dashboard.FileSystem", stats.fileSystem)); if (stats.fileSystem === "fuse.shfs" && !stats.usesSpacePath) lines.push(t("Admin.Dashboard.UnraidShare.Tip")); return lines.join("\n"); } /** The write volume's free space as one more line of a storage tile, when the stats have it apart; "" otherwise. */ export function writeVolumeLine(stats) { if (stats.writeFreeBytes == null) return ""; return `${escapeHtml(t("Admin.Dashboard.WriteVolume", formatBytes(stats.writeFreeBytes)))}`; } /** * Column chart named by label: values with labels under the bars and, when given, the value above each bar. Bars use * the accent colour, or the sun colour for upload activity. With edgeLabels the first and last labels align with the * chart edges (a time axis labelled only at its ends). Charts keep their left-to-right axis in right-to-left pages. */ export function columns(items, { label, sun = false, valueLabel = null, edgeLabels = false, height = 190 } = {}) { const width = 400; const base = height - 30; const max = Math.max(1, ...items.map((i) => i.value)); const step = width / Math.max(1, items.length); const barWidth = Math.max(2, Math.min(32, step * 0.65)); let svg = ``; svg += ``; items.forEach((item, i) => { const h = item.value > 0 ? Math.max(2, (item.value / max) * (base - 18)) : 0; const x = i * step + (step - barWidth) / 2; const middle = (x + barWidth / 2).toFixed(1); svg += `${escapeHtml(item.title ?? "")}`; if (valueLabel) svg += `${escapeHtml(valueLabel(item))}`; if (!item.label) return; const edge = !edgeLabels ? "" : i === 0 ? "start" : i === items.length - 1 ? "end" : ""; const at = edge === "start" ? 0 : edge === "end" ? width : middle; svg += `${escapeHtml(item.label)}`; }); return svg + ""; } /** * Hides a table's secondary columns level by level (fit-1 … fit-n in admin.css, n = data-levels) until its rows fit * the panel: the widths depend on the language and on the side panel, so they are measured rather than guessed. */ export function fitColumns(table) { const levels = Number(table.dataset.levels); for (let level = 0; level <= levels; level++) { for (let i = 1; i <= levels; i++) table.classList.toggle(`fit-${i}`, i <= level); if (table.scrollWidth <= table.clientWidth) return; } } window.addEventListener("resize", () => document.querySelectorAll(".table[data-levels]").forEach(fitColumns)); /** Chip of the Dashboard and Settings: TLS mode is proxy, but this page did not come through a trusted proxy over HTTPS (BRIEF §14.2). */ export const PROXY_WARNING = ``; /** An empty state: one sentence and one button (BRIEF §0.2). */ export function emptyState(sentenceKey, button = "") { return `
${button}
`; } /** Shows a toast at the bottom (inline end) for 8 s (hover pauses). */ export function toast(message, isError = false) { const host = document.getElementById("toasts") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "toasts" })); const item = document.createElement("div"); item.className = `toast${isError ? " error" : ""}`; item.setAttribute("role", isError ? "alert" : "status"); item.textContent = message; host.appendChild(item); let remaining = 8000; let started = Date.now(); let timer = setTimeout(() => item.remove(), remaining); item.addEventListener("mouseenter", () => { clearTimeout(timer); remaining -= Date.now() - started; }); item.addEventListener("mouseleave", () => { started = Date.now(); timer = setTimeout(() => item.remove(), remaining); }); } let dialogs = 0; /** What a typed confirmation asks for: its field's tooltip, the confirm button's while it waits, and how a value matches. */ const TYPED = { // A name (an account), exactly as shown. name: { tip: "Admin.Common.TypeToConfirm.Tip", first: "Admin.Common.TypeFirst.Tip", matches: (value, typed) => value === typed }, // A word of the interface (the localised "empty"), whatever its case. word: { tip: "Admin.Common.TypeWord.Tip", first: "Admin.Common.TypeWordFirst.Tip", matches: (value, typed) => value.trim().toLocaleLowerCase() === typed.toLocaleLowerCase() }, // A count (the photos a deletion moves), its digits whatever the separators typed between them. count: { tip: "Admin.Common.TypeCount.Tip", first: "Admin.Common.TypeCountFirst.Tip", matches: (value, typed) => value.replace(/[\s.,'’  ]/g, "") === typed }, }; /** * Two-button confirmation dialog (safe action left and default, Esc keeps). Resolves true when the destructive action * is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field, as `typedKind` * says: a name exactly, a word whatever its case, or a count. `list` adds the items the action concerns (titles, * entries) under the body, in a scrolling box; user text, so each keeps its own direction. */ export function confirmDialog({ title, body, list, confirm, confirmTip, cancel, cancelTip, typed, typedKind = "name" }) { return new Promise((resolve) => { const id = `dialog-${++dialogs}`; const dialog = document.createElement("dialog"); dialog.className = "dialog"; dialog.setAttribute("aria-labelledby", `${id}-title`); if (body) dialog.setAttribute("aria-describedby", `${id}-body`); const kind = TYPED[typedKind] ?? TYPED.name; const firstTip = t(kind.first); const matches = (value) => kind.matches(value, String(typed)); // The text to type stands out of its sentence, and keeps its own direction. const typedLabel = typed ? escapeHtml(t("Admin.Common.TypeToConfirm", "\u0001")).replace("\u0001", `${escapeHtml(typed)}`) : ""; dialog.innerHTML = `

${escapeHtml(title)}

${body ? `

${escapeHtml(body)}

` : ""} ${list?.length ? `` : ""} ${typed ? `` : ""}
`; document.body.appendChild(dialog); const ok = dialog.querySelector('button[value="ok"]'); dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => { ok.disabled = !matches(e.target.value); ok.title = ok.disabled ? firstTip : confirmTip; }); dialog.addEventListener("close", () => { resolve(dialog.returnValue === "ok"); dialog.remove(); }); dialog.showModal(); }); } /** * A dialog of form fields (fields: HTML whose data-i18n attributes are filled here) with the action on the right, which * Enter in a field chooses too; Esc or the safe button cancels. Resolves the FormData once confirmed, null when cancelled. * check(form) may refuse the values: it marks the field (markInvalid) and returns false, and the dialog stays open. */ export function formDialog({ title, fields, confirm, confirmTip, cancel, cancelTip, check }) { return new Promise((resolve) => { const id = `dialog-${++dialogs}`; const dialog = document.createElement("dialog"); dialog.className = "dialog"; dialog.setAttribute("aria-labelledby", `${id}-title`); dialog.innerHTML = `

${escapeHtml(title)}

${fields}
`; applyStrings(dialog); document.body.appendChild(dialog); const form = dialog.querySelector("form"); let result = null; form.addEventListener("submit", (e) => { if (check && !check(form)) { e.preventDefault(); return; } result = new FormData(form); }); dialog.querySelector('button[value="cancel"]').addEventListener("click", () => dialog.close()); dialog.addEventListener("close", () => { resolve(result); dialog.remove(); }); dialog.showModal(); form.querySelector("input, select, textarea")?.focus(); }); } /** The localised message of an API failure, or the generic one when the server was not reached. */ export function errorText(err) { return err?.message && err.status ? err.message : t("Admin.Error.Unreachable"); } /** * Marks a form field invalid (DESIGN §4): error border and the message as its tooltip, until the value changes and * the field's own tooltip comes back. */ export function markInvalid(field, message) { if (field.getAttribute("aria-invalid") !== "true") field.dataset.tip = field.title; field.setAttribute("aria-invalid", "true"); field.title = message; field.addEventListener("input", () => clearInvalid(field), { once: true }); } /** "The value of Folder template is not valid; …": a field the server refused, named by its label. */ export function invalidText(field) { return t("Admin.Common.Invalid", field.closest("label")?.querySelector("span")?.textContent ?? field.name); } export function clearInvalid(field) { if (field.getAttribute("aria-invalid") !== "true") return; field.removeAttribute("aria-invalid"); field.title = field.dataset.tip ?? ""; } /** Esc in a field of the form puts back the value the page was drawn with (DESIGN §4: Esc reverts). */ export function escapeReverts(form) { form.addEventListener("keydown", (e) => { const field = e.target; if (e.key !== "Escape" || !(field instanceof HTMLInputElement || field instanceof HTMLSelectElement) || field.type === "search") return; const checkable = field.type === "checkbox" || field.type === "radio"; const before = checkable ? field.checked : field.value; if (field instanceof HTMLSelectElement) { [...field.options].forEach((o) => { o.selected = o.defaultSelected; }); } else if (field.type === "checkbox" || field.type === "radio") { field.checked = field.defaultChecked; } else { field.value = field.defaultValue; } clearInvalid(field); // What follows the value (the certificate files of a TLS mode, the levels of the priority queue) follows it back. if ((checkable ? field.checked : field.value) !== before) field.dispatchEvent(new Event("change", { bubbles: true })); }); } const FOCUSABLE = "a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex='-1'])"; /** * Where the keyboard focus is inside root, in terms that survive a re-render: the row (data-key), the control * (data-act, data-toggle, id or name) and positions as fallbacks. */ export function focusPlace(root) { const el = document.activeElement; if (!el || el === document.body || !root.contains(el)) return null; const row = el.closest("[data-key]"); const rows = [...root.querySelectorAll("[data-key]")]; return { row: row?.dataset.key ?? null, rowIndex: rows.indexOf(row), control: controlKey(el), index: [...(row ?? root).querySelectorAll(FOCUSABLE)].indexOf(el) }; } /** * Focuses the same control after a re-render, else the control at the same place in the same (or same-position) row, * else the first control left (an empty state's button). */ export function restoreFocus(root, place) { if (!place) return; let scope = root; let index = place.index; if (place.row !== null) { const rows = [...root.querySelectorAll("[data-key]")]; const row = rows.find((r) => r.dataset.key === place.row) ?? rows[Math.min(place.rowIndex, rows.length - 1)]; if (row) scope = row; else index = 0; } const controls = [...scope.querySelectorAll(FOCUSABLE)]; (controls.find((c) => controlKey(c) === place.control) ?? controls[Math.min(Math.max(index, 0), controls.length - 1)])?.focus(); } /** Redraws with draw() and puts the keyboard focus back where it was. */ export function redraw(root, draw) { const place = focusPlace(root); draw(); restoreFocus(root, place); } function controlKey(el) { return el.dataset.act ?? el.dataset.toggle ?? el.dataset.cancel ?? el.dataset.forget ?? (el.id || el.name || ""); } /** Query parameters of the hash route (#/logs?view=signins). */ export function routeParams() { return new URLSearchParams(location.hash.split("?")[1] ?? ""); } /** A language's own name ("Italiano"), for language menus. */ export function nativeName(code) { try { const name = new Intl.DisplayNames([code], { type: "language" }).of(code) ?? code; return name.charAt(0).toLocaleUpperCase(code) + name.slice(1); } catch { return code; } }