Files
Chronos/src/Chronos.Server/Admin/web/pages/library/shared.js
T
Alby96andClaude Opus 5.5 9aa818ed47
CI / Build and test (push) Successful in 7m25s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
CI / PostgreSQL 16 integration (push) Successful in 5m20s
CI / PostgreSQL 17 integration (push) Successful in 5m22s
CI / Docker image (push) Successful in 50s
Release / Build, test and publish (push) Successful in 12m1s
Release / Server image (push) Successful in 1m26s
feat: owner review 2 phase 3: Library on the web panel, photo trash and web upload (#11)
- Web panel Library: browse, view, delete sequences and photos, mass operations (analyse, proxies, thumbnails, verify, retag, delete, CSV). It never edits the video.
- Photo trash with tombstones (migration 0008): crash-safe delete and restore, hash-checked restore with reasons, and emptying only by an explicit fingerprinted job. Sync and uploads keep deleted photos deleted; an explicit "Upload again" brings one back.
- Upload from the web panel: in-house SHA-256 in a worker with a fail-closed self-test, capture time from EXIF, chunked, resumable; no folders.
- Desktop trash dialog with photo entries and Empty.
- Admin files are revalidated (no-cache + ETag).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-27 15:08:39 +01:00

323 lines
13 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.
// What the Library's views share (owner review 2, R6): sequence facts and status chips as the desktop cards show them,
// thumbnails and their retries after a job ended, the job states that end a job, delete lists cut to LISTED names, a
// selection with Shift ranges, the keyboard of a grid of selectable items, chunked bulk calls and file downloads.
import { t, plural, culture } from "../../i18n.js";
import { escapeHtml, attr, formatNumber, formatDuration } from "../../ui.js";
import { icons } from "../../icons.js";
/** SequenceStatus bits (Chronos.Core.Model). */
export const STATUS = { analysed: 1, deep: 2, proxies: 4, thumbs: 8, verified: 16, warnings: 32, errors: 64 };
/** Ids one bulk request may name (LibraryEndpoints.MaxBulkIds). */
export const BULK_LIMIT = 1000;
/** Names a delete dialog lists; the count in its title says how many there are in all. */
export const LISTED = 500;
/** The jobState states after which a job does nothing more. */
export const JOB_ENDED = new Set(["done", "failed", "cancelled"]);
/** A dialog's list cut to LISTED lines and "…", so a delete of thousands never builds thousands of nodes. */
export function listed(lines) {
return lines.length > LISTED ? [...lines.slice(0, LISTED), "…"] : lines;
}
/**
* A camera's name as the desktop and the server's facets give it (PathTemplate.CameraName): the make's brand once,
* "Canon EOS R5" (Canon + Canon EOS R5), "Nikon Z 8" (NIKON CORPORATION + NIKON Z 8), "SONY ILCE-7M4".
*/
export function cameraLabel(make, model) {
make = make?.trim();
model = model?.trim();
if (!model) return make ?? "";
if (!make) return model;
let brand = make.split(" ").find(Boolean);
if (brand.toUpperCase() === "NIKON") brand = "Nikon";
return model.toLowerCase().startsWith(brand.toLowerCase()) ? brand + model.slice(brand.length) : `${brand} ${model}`;
}
/** How long the sequence lasts, from its first capture to its last ("2 h 0 m"); "" without captures. */
export function spanText(s) {
if (!s.firstCapture || !s.lastCapture) return "";
return formatDuration((new Date(s.lastCapture) - new Date(s.firstCapture)) / 1000);
}
/** A capture time as the camera recorded it (stored without zone, so read and shown as it was taken). */
export function captureText(iso, withTime = true) {
if (!iso) return "—";
const options = withTime ? { dateStyle: "medium", timeStyle: "short" } : { dateStyle: "medium" };
return new Intl.DateTimeFormat(culture(), options).format(new Date(iso));
}
/** The line under a card's title: "3,600 · Canon EOS R5 · 2 h 0 m". */
export function factsLine(s) {
return [formatNumber(s.frameCount), cameraLabel(s.cameraMake, s.cameraModel), spanText(s)].filter(Boolean).join(" · ");
}
/**
* Status glyphs as DESIGN §4 draws them: ● analysed (○ not yet), ● proxies (○ none), ▶ n renders, ▲ n warnings, ✕ errors,
* ✓ verified. Each chip has its words for screen readers and its tooltip; the glyph alone is decoration.
*/
export function statusChips(s) {
const chip = (cls, glyph, key, text, tipKey) =>
`<span class="st ${cls}" title="${attr(t(tipKey))}"><span aria-hidden="true">${glyph}</span> ${escapeHtml(text ?? t(key))}</span>`;
const on = (bit) => (s.status & bit) !== 0;
const chips = [
on(STATUS.analysed) ? chip("ok", "●", "Admin.Library.Status.Analysed", null, "Admin.Library.Status.Analysed.Tip")
: chip("off", "○", "Admin.Library.Status.NotAnalysed", null, "Admin.Library.Status.NotAnalysed.Tip"),
on(STATUS.proxies) ? chip("", "●", "Admin.Library.Status.Proxies", null, "Admin.Library.Status.Proxies.Tip")
: chip("off", "○", "Admin.Library.Status.NoProxies", null, "Admin.Library.Status.NoProxies.Tip"),
];
if (on(STATUS.verified)) chips.push(chip("ok", "✓", "Admin.Library.Status.Verified", null, "Admin.Library.Status.Verified.Tip"));
if (s.renderedCount > 0) chips.push(chip("", "▶", null, plural("Admin.Library.Status.Renders", s.renderedCount), "Admin.Library.Status.Renders.Tip"));
if (s.warningCount > 0 || on(STATUS.warnings))
chips.push(chip("warn", "▲", null, plural("Admin.Library.Status.Warnings", Math.max(1, s.warningCount)), "Admin.Library.Status.Warnings.Tip"));
if (on(STATUS.errors)) chips.push(chip("err", "✕", "Admin.Library.Status.Errors", null, "Admin.Library.Status.Errors.Tip"));
return chips.join("");
}
/**
* An image the browser loads when it nears the view, with the photo icon in its place while it has none: before it
* arrives, when the thumbnail is not built yet (404) or cannot be read. watchImages() hooks the error up (no inline
* handlers under the panel's policy).
*/
export function lazyImage(src, cls = "") {
return `<span class="thumb ${cls}"><span class="placeholder" aria-hidden="true">${icons.image}</span>` +
`<img loading="lazy" decoding="async" alt="" src="${attr(src)}" data-fallback></span>`;
}
export function watchImages(root) {
root.querySelectorAll("img[data-fallback]").forEach((img) => {
img.removeAttribute("data-fallback");
img.addEventListener("error", () => img.classList.add("failed"), { once: true });
img.addEventListener("load", () => img.classList.add("loaded"), { once: true });
});
}
/** Retries of an image that had nothing to show, the first after RETRY_FIRST_MS and each next one after twice the wait, up to RETRY_LONGEST_MS. */
const RETRY_TRIES = 8;
const RETRY_FIRST_MS = 2000;
const RETRY_LONGEST_MS = 60000;
/**
* The images under root that had nothing to show (a thumbnail not built yet) asked for again, once a job that may have
* built them ended: under an address the browser has not tried, so its first answer is not reused. Each image waits
* longer before every retry and stops after RETRY_TRIES, since some never get one (a photo whose original is missing);
* fresh (the sequence itself changed, a pass may have built them) starts every image's count again.
*/
export function retryImages(root, fresh = false) {
const now = Date.now();
root.querySelectorAll("img.failed").forEach((img) => {
const tries = fresh ? 0 : Number(img.dataset.tries ?? 0);
if (tries >= RETRY_TRIES || (!fresh && now < Number(img.dataset.retryAt ?? 0))) return;
img.dataset.tries = String(tries + 1);
img.dataset.retryAt = String(now + Math.min(RETRY_FIRST_MS * 2 ** tries, RETRY_LONGEST_MS));
const url = new URL(img.getAttribute("src"), location.href);
url.searchParams.set("retry", String(now));
img.classList.remove("failed");
img.setAttribute("data-fallback", "");
img.src = url.pathname + url.search;
});
watchImages(root);
}
/** A sequence's cover thumbnail; its address changes with the cover and the photos, so a browser's copy never shows an old one. */
export function coverUrl(s) {
return `/api/v1/sequences/${encodeURIComponent(s.id)}/thumb?v=${s.heroFrameId ?? "first"}-${s.framesVersion}`;
}
/** Items picked by click, Space and Shift ranges over the order shown; the anchor is where the next range starts. */
export class Selection {
constructor() {
this.ids = new Set();
this.anchor = null;
}
get size() {
return this.ids.size;
}
has(id) {
return this.ids.has(id);
}
toggle(id) {
if (!this.ids.delete(id)) this.ids.add(id);
this.anchor = id;
}
/** Selects every item from the anchor to id in order (the anchor stays), or id alone without an anchor in view. */
range(id, order) {
const from = order.indexOf(this.anchor);
const to = order.indexOf(id);
if (from < 0 || to < 0) return this.toggle(id);
const [a, b] = from < to ? [from, to] : [to, from];
for (let i = a; i <= b; i++) this.ids.add(order[i]);
}
set(ids) {
this.ids = new Set(ids);
}
clear() {
this.ids.clear();
this.anchor = null;
}
}
/**
* The keyboard and pointer of a grid of selectable items (role="option" with data-key, in a role="listbox"): one tab
* stop (the current item), arrows move along the reading direction and between rows, Home and End, Space selects
* (Shift+Space: the range from the last one picked), Enter opens, Ctrl+A selects everything shown, Esc clears the
* selection. A click on an item's check box selects (with Shift, a range), Ctrl+click too; a plain click opens.
* The caller redraws through onChange after the selection changed.
*/
export function selectableGrid(host, { selection, order, open, onChange }) {
let current = null;
const items = () => [...host.querySelectorAll('[role="option"]')];
const focusItem = (el) => {
if (!el) return;
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
current = el.dataset.key;
el.focus();
};
const pick = (key, shift) => {
if (shift) selection.range(key, order());
else selection.toggle(key);
onChange();
};
host.addEventListener("focusin", (e) => {
const el = e.target.closest?.('[role="option"]');
if (el && host.contains(el)) {
current = el.dataset.key;
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
}
});
host.addEventListener("click", (e) => {
const el = e.target.closest('[role="option"]');
if (!el || !host.contains(el)) return;
if (e.target.closest("[data-check]") || e.ctrlKey || e.metaKey || e.shiftKey) {
// A check box keeps its own click (a cancelled one would put its old state back after onChange drew the new one).
if (!e.target.matches("input[data-check]")) e.preventDefault();
pick(el.dataset.key, e.shiftKey);
return;
}
if (e.target.closest("a, button")) return;
open(el.dataset.key);
});
host.addEventListener("keydown", (e) => {
const el = e.target.closest?.('[role="option"]');
if (!el || e.altKey) return;
const list = items();
const index = list.indexOf(el);
const rtl = getComputedStyle(host).direction === "rtl";
let next = null;
switch (e.key) {
case "ArrowRight": next = list[index + (rtl ? -1 : 1)]; break;
case "ArrowLeft": next = list[index + (rtl ? 1 : -1)]; break;
case "ArrowDown": next = list[index + columns(list)]; break;
case "ArrowUp": next = list[index - columns(list)]; break;
case "Home": next = list[0]; break;
case "End": next = list[list.length - 1]; break;
case " ":
e.preventDefault();
pick(el.dataset.key, e.shiftKey);
return;
case "Enter":
e.preventDefault();
open(el.dataset.key);
return;
case "Escape":
if (selection.size === 0) return;
e.preventDefault();
selection.clear();
onChange();
return;
case "a":
case "A":
if (!(e.ctrlKey || e.metaKey)) return;
e.preventDefault();
selection.set(list.map((i) => i.dataset.key));
onChange();
return;
default:
return;
}
e.preventDefault();
focusItem(next);
});
return {
/** After a redraw: the current item keeps the tab stop (the first one when it is gone). */
restore(focus = false) {
const list = items();
const el = list.find((i) => i.dataset.key === current) ?? list[0];
list.forEach((i) => (i.tabIndex = i === el ? 0 : -1));
if (focus && el) el.focus();
},
};
}
/** Items per row of a wrapping grid: those on the first item's line. */
function columns(list) {
const top = list[0]?.offsetTop;
const n = list.findIndex((i) => i.offsetTop !== top);
return n < 0 ? list.length || 1 : n;
}
/** Tags typed as "night, roof; sky": trimmed, once each (case-insensitive), none empty. */
export function tagList(text) {
const seen = new Set();
return String(text ?? "").split(/[,;]/).map((s) => s.trim()).filter((s) => {
const key = s.toLocaleLowerCase();
if (!s || seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** The ids in requests of at most BULK_LIMIT, in their order. */
export function chunks(ids, size = BULK_LIMIT) {
const out = [];
for (let i = 0; i < ids.length; i += size) out.push(ids.slice(i, i + size));
return out;
}
/** Hands the browser a file to save (a Blob made here; nothing leaves the page). */
export function saveFile(name, blob) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/**
* Sequences as CSV (comma separated, UTF-8 with a byte-order mark for spreadsheets): title, camera, photos, size in
* bytes, first and last capture (ISO, as the camera recorded them) and tags. A cell a spreadsheet would run as a formula
* starts with an apostrophe.
*/
export function sequencesCsv(sequences) {
const cell = (value) => {
let text = String(value ?? "");
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
return /[",\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
};
const head = ["Admin.Library.Csv.Title", "Admin.Library.Csv.Camera", "Admin.Library.Csv.Photos", "Admin.Library.Csv.Bytes",
"Admin.Library.Csv.First", "Admin.Library.Csv.Last", "Admin.Library.Csv.Tags"].map((key) => cell(t(key)));
const rows = sequences.map((s) => [s.displayTitle, cameraLabel(s.cameraMake, s.cameraModel), s.frameCount, s.totalBytes,
s.firstCapture ?? "", s.lastCapture ?? "", (s.tags ?? []).join("; ")].map(cell).join(","));
return new Blob(["" + [head.join(","), ...rows].join("\r\n") + "\r\n"], { type: "text/csv;charset=utf-8" });
}
/** "2026-10-27" in the file names of exports. */
export function today() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}