Files
Chronos/src/Chronos.Server/Admin/web/ui.js
T
Alby96 aa1d4913a3 feat(admin): Library pages on the web panel (owner review 2, R6)
The web panel now manages the library without editing it: the owner can
browse and view sequences and photos, delete sequences and photos into the
archive's trash, restore or empty the trash and run mass operations, as
R6 asks, on top of the engine endpoints of the previous commit.

- Library page right after the Dashboard: search, Year/Camera/Status/Tag
  filters fed by a new GET /api/v1/sequences/facets, sort, cards or list
  (remembered per browser), lazy cover thumbnails, Load more by cursor,
  multi-select with Shift ranges and "Select all N" of the filter, and a
  sticky bar for the selection: Analyse, Proxies, Thumbnails, Verify,
  Tags (add/remove), Export CSV (client-side) and Delete (dry run, list
  of what moves to the trash, then the move). Filters live in the address,
  so Back from a sequence finds them again.
- Sequence view (#/library?id=): inline title, tags, rating and notes,
  facts, photos in pages of 500 with content-visibility, a photo viewer
  (proxy, arrows, Esc, Exif facts), Set cover, Download original, Delete
  photos (typing the count above 20 photos), Delete sequence, renders to
  download. No video editing controls.
- Trash view (#/library?view=trash, also linked from Archive): entries,
  Restore, and Empty (dry run, list, the localised word typed, the plan's
  fingerprint sent back, the job followed to its end).
- Live updates from sequenceChanged and jobState; keyboard grid (one tab
  stop, arrows, Space, Shift+Space, Enter, Ctrl+A, Esc); RTL, dark theme.
- GET /sequences takes rendered=true|false for the Status filter.
- ui.js: confirmDialog's typed confirmation by name, word or count, with a
  list of what the action concerns; formDialog. api.js: putBytes for the
  web upload, which the Library imports on demand (upload.js, optional).
- New web icons from icons.py (Image for the Library, trash, grid/list,
  arrows, stars, cover); directional glyphs mirror in right-to-left pages.
- Strings in en and it; tests for the facets (both dialects), the rendered
  filter, the menu, the modules and the on-demand upload import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 029cf334f66cb6fa1265b96a6f8faff2964c11ea)
2026-10-27 10:51:04 +01:00

351 lines
17 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[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 ? `<span class="fingerprint" dir="ltr">${String(value).split(":").map(escapeHtml).join(":<wbr>")}</span>` : "—";
}
/** 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 `<svg class="bar${muted ? " muted" : ""}" viewBox="0 0 100 6" preserveAspectRatio="none" aria-hidden="true">` +
`<rect class="track" width="100" height="6" rx="3"/><rect class="fill" width="${width}" height="6" rx="3"/></svg>`;
}
/**
* 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 `<span class="sub" title="${attr(t("Admin.Dashboard.WriteVolume.Tip"))}">${escapeHtml(t("Admin.Dashboard.WriteVolume", formatBytes(stats.writeFreeBytes)))}</span>`;
}
/**
* 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 class="chart${sun ? " sun" : ""}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${attr(label)}">`;
svg += `<line class="axis" x1="0" y1="${base}" x2="${width}" y2="${base}"/>`;
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 += `<rect class="column" x="${x.toFixed(1)}" y="${(base - h).toFixed(1)}" width="${barWidth.toFixed(1)}" height="${h.toFixed(1)}" rx="2"><title>${escapeHtml(item.title ?? "")}</title></rect>`;
if (valueLabel) svg += `<text class="value" x="${middle}" y="${(base - h - 5).toFixed(1)}">${escapeHtml(valueLabel(item))}</text>`;
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 += `<text class="label${edge ? " " + edge : ""}" x="${at}" y="${base + 16}">${escapeHtml(item.label)}</text>`;
});
return svg + "</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 = `<span class="chip warn" data-i18n="Admin.Settings.ProxyBypassed" data-i18n-title="Admin.Settings.ProxyBypassed.Tip"></span>`;
/** An empty state: one sentence and one button (BRIEF §0.2). */
export function emptyState(sentenceKey, button = "") {
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
}
/** 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", `<strong dir="auto">${escapeHtml(typed)}</strong>`) : "";
dialog.innerHTML = `
<form method="dialog">
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${body ? `<p id="${id}-body">${escapeHtml(body)}</p>` : ""}
${list?.length ? `<ul class="dialog-list" tabindex="0" aria-label="${attr(title)}">${list.map((item) => `<li dir="auto">${escapeHtml(item)}</li>`).join("")}</ul>` : ""}
${typed ? `<label class="field-label"><span>${typedLabel}</span>
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" ${typedKind === "count" ? 'inputmode="numeric"' : ""} title="${attr(t(kind.tip))}"></label>` : ""}
<div class="buttons">
<button class="btn" value="cancel" title="${attr(cancelTip)}" autofocus>${escapeHtml(cancel)}</button>
<button class="btn destructive" value="ok" title="${attr(typed ? firstTip : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
</div>
</form>`;
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 = `
<form method="dialog" class="form" novalidate>
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${fields}
<div class="buttons">
<button class="btn" type="button" value="cancel" title="${attr(cancelTip)}">${escapeHtml(cancel)}</button>
<button class="btn primary" value="ok" title="${attr(confirmTip)}">${escapeHtml(confirm)}</button>
</div>
</form>`;
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;
}
}