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)
This commit is contained in:
Alby96 committed 2026-10-27 10:51:04 +01:00
1 parent 51782a3ada
commit aa1d4913a3
23 files changed
+2540 -31

No files matched your search

@@ -0,0 +1,555 @@
// Library (owner review 2, R6; BRIEF §14.8): the panel browses, views and deletes sequences and photos and runs mass
// operations on them, but never edits a video (no settings, no render). #/library lists the sequences with filters in the
// address, #/library?id=<sequence> opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, toast, errorText, confirmDialog, formDialog, markInvalid, emptyState, routeParams, redraw } from "../ui.js";
import { icons } from "../icons.js";
import { BULK_LIMIT, factsLine, captureText, cameraLabel, statusChips, lazyImage, watchImages, Selection, selectableGrid, chunks, saveFile, sequencesCsv, today, tagList, coverUrl } from "./library/shared.js";
import { renderSequence } from "./library/sequence.js";
import { renderTrash } from "./library/trash.js";
const VIEW_KEY = "chronos.admin.library.view";
const PAGE = 100;
/** The Status menu: its value in the address and the listing's query parameters. */
const STATUS_FILTERS = {
analysed: "status=analyzedLight",
"not-analysed": "status=-analyzedLight",
proxies: "status=proxiesBuilt",
"no-proxies": "status=-proxiesBuilt",
rendered: "rendered=true",
"not-rendered": "rendered=false",
verified: "status=verified",
"not-verified": "status=-verified",
warnings: "status=hasWarnings",
errors: "status=hasErrors",
};
const SORTS = ["newest", "oldest", "title", "frameCount", "size"];
const JOBS = ["analyse", "proxies", "thumbnails", "verify"];
const FILTERS = ["q", "year", "camera", "status", "tag", "sort"];
/** The list's address the last time it was shown, so a sequence's Back returns to the same filters. */
let listHash = "#/library";
/** upload.js of the web upload, once asked for: the module, or null when this server has none. */
let uploadModule;
/**
* The web upload (owner review 2, R3) lives in its own module; the Library offers it only when that module loads, so
* the page works on a panel without it.
*/
export async function loadUpload() {
if (uploadModule === undefined) {
try {
const m = await import("../upload.js");
uploadModule = typeof m.openUpload === "function" ? m : null;
} catch {
uploadModule = null;
}
}
return uploadModule;
}
export async function render(root, context) {
const params = routeParams();
if (params.get("view") === "trash") return renderTrash(root, context, { back: listHash });
const id = params.get("id");
if (id) return renderSequence(root, context, id, { back: listHash, loadUpload });
listHash = location.hash || "#/library";
return renderList(root, context, params);
}
async function renderList(root, { api, setMeta, actions, onEvent }, params) {
const filters = Object.fromEntries(FILTERS.map((f) => [f, params.get(f) ?? ""]));
if (!SORTS.includes(filters.sort)) filters.sort = "newest";
if (!Object.hasOwn(STATUS_FILTERS, filters.status)) filters.status = "";
let view = storedView();
let rows = [];
let cursor = null;
let total = 0;
let facets = { years: [], cameras: [], tags: [] };
/** Every sequence of the filter, once "Select all" fetched them; null otherwise. */
let matching = null;
let generation = 0;
const selection = new Selection();
let refreshTimer = null;
actions.innerHTML = `
<button class="btn" id="upload" hidden>${icons.upload}<span data-i18n="Admin.Library.Upload"></span></button>
<a class="btn" href="#/library?view=trash" data-i18n-title="Admin.Library.Trash.Tip">${icons.trash}<span data-i18n="Admin.Library.Trash"></span></a>
<button class="btn icon" id="refresh" data-i18n-title="Admin.Library.Refresh.Tip">${icons.refresh}</button>`;
applyStrings(actions);
actions.querySelector("#refresh").addEventListener("click", () => load());
loadUpload().then((upload) => {
const button = actions.querySelector("#upload");
if (!upload || !button.isConnected) return;
button.hidden = false;
button.title = t("Admin.Library.Upload.Tip");
button.addEventListener("click", () => upload.openUpload({ api, onDone: () => load() }));
});
root.innerHTML = `
<div class="toolbar" role="search">
<input class="input search" type="search" id="q" dir="auto" value="${attr(filters.q)}" data-i18n-placeholder="Admin.Library.Search"
data-i18n-title="Admin.Library.Search.Tip" aria-label="${attr(t("Admin.Library.Search"))}">
<select class="input small" id="year" data-i18n-title="Admin.Library.Year.Tip"></select>
<select class="input small" id="camera" data-i18n-title="Admin.Library.Camera.Tip"></select>
<select class="input small" id="status" data-i18n-title="Admin.Library.Status.Tip"></select>
<select class="input small" id="tag" data-i18n-title="Admin.Library.Tag.Tip"></select>
<select class="input small" id="sort" data-i18n-title="Admin.Library.Sort.Tip">${SORTS.map((s) =>
`<option value="${s}" ${s === filters.sort ? "selected" : ""}>${escapeHtml(t(`Admin.Library.Sort.${cap(s)}`))}</option>`).join("")}</select>
<span class="spacer"></span>
<div class="segmented" role="group" aria-label="${attr(t("Admin.Library.View"))}">
<button class="btn icon" data-view="grid" aria-pressed="${view === "grid"}" data-i18n-title="Admin.Library.View.Grid.Tip">${icons.grid}</button>
<button class="btn icon" data-view="list" aria-pressed="${view === "list"}" data-i18n-title="Admin.Library.View.List.Tip">${icons.list}</button>
</div>
</div>
<section class="panel flush library" aria-label="${attr(t("Admin.Nav.Library"))}">
<div id="items"></div>
<div class="table-foot" id="foot" hidden><span class="muted" id="shown"></span><span class="spacer"></span>
<button class="btn small" id="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
</section>
<div class="mass-bar" id="mass" role="toolbar" aria-label="${attr(t("Admin.Library.Selection"))}" hidden></div>`;
applyStrings(root);
const itemsHost = root.querySelector("#items");
const mass = root.querySelector("#mass");
let searchTimer = null;
root.querySelector("#q").addEventListener("input", (e) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => setFilter("q", e.target.value.trim()), 300);
});
for (const f of ["year", "camera", "status", "tag", "sort"]) root.querySelector(`#${f}`).addEventListener("change", (e) => setFilter(f, e.target.value));
root.querySelectorAll("[data-view]").forEach((b) => b.addEventListener("click", () => {
view = b.dataset.view;
root.querySelectorAll("[data-view]").forEach((x) => x.setAttribute("aria-pressed", String(x === b)));
try {
localStorage.setItem(VIEW_KEY, view);
} catch {
// Only this page keeps the view then.
}
draw();
}));
root.querySelector("#more").addEventListener("click", () => load(true));
// One grid object for the page: the host stays, its items are redrawn.
const grid = selectableGrid(itemsHost, {
selection,
order: () => rows.map((r) => r.id),
open: (key) => {
location.hash = `#/library?id=${encodeURIComponent(key)}`;
},
onChange: syncSelection,
});
function setFilter(name, value) {
if (filters[name] === value) return;
filters[name] = value;
// The address keeps the filters (no hashchange: the page stays), so Back from a sequence finds them again.
const query = new URLSearchParams(Object.entries(filters).filter(([k, v]) => v && !(k === "sort" && v === "newest")));
listHash = `#/library${query.size ? `?${query}` : ""}`;
history.replaceState(null, "", listHash);
selection.clear();
matching = null;
load();
}
function listQuery(limit, after) {
const p = new URLSearchParams({ limit: String(limit), sort: filters.sort });
for (const f of ["q", "year", "camera", "tag"]) if (filters[f]) p.set(f, filters[f]);
if (after) p.set("cursor", after);
const status = STATUS_FILTERS[filters.status];
return `/api/v1/sequences?${p}${status ? `&${status}` : ""}`;
}
async function load(more = false) {
const mine = ++generation;
try {
const [page, f] = await Promise.all([
api.get(listQuery(PAGE, more ? cursor : null)),
more ? Promise.resolve(facets) : api.get("/api/v1/sequences/facets").catch(() => facets),
]);
if (mine !== generation || !root.isConnected) return;
facets = f;
if (!more) total = page.total ?? page.items.length;
cursor = page.nextCursor;
if (more) {
rows = rows.concat(page.items);
appendItems(page.items);
} else {
rows = page.items;
drawFilters();
draw();
}
} catch (err) {
toast(errorText(err), true);
return;
}
setMeta(plural("Admin.Library.Count", total));
drawFoot();
}
/** The loaded rows again, as many as are shown (live updates); the selection and the keyboard place stay. */
async function refreshVisible() {
const mine = ++generation;
try {
const [page, f] = await Promise.all([
api.get(listQuery(Math.min(Math.max(rows.length, PAGE), BULK_LIMIT), null)),
api.get("/api/v1/sequences/facets").catch(() => facets),
]);
if (mine !== generation || !root.isConnected) return;
total = page.total ?? total;
facets = f;
drawFilters();
rows = page.items;
cursor = page.nextCursor;
const known = new Set(rows.map((r) => r.id));
if (!matching) selection.set([...selection.ids].filter((id) => known.has(id)));
const focused = itemsHost.contains(document.activeElement);
draw();
grid.restore(focused);
setMeta(plural("Admin.Library.Count", total));
drawFoot();
} catch {
// The next event or Refresh tries again.
}
}
function drawFilters() {
const option = (value, label, chosen) => `<option value="${attr(value)}" ${value === chosen ? "selected" : ""}>${escapeHtml(label)}</option>`;
// A value of the address the archive no longer has stays in its menu, so the filter shows what the list does.
const withChosen = (list, chosen) => (chosen && !list.some((f) => f.value === chosen) ? [{ value: chosen, sequences: 0 }, ...list] : list);
const counted = (f, label) => `${label ?? f.label ?? f.value} (${formatNumber(f.sequences)})`;
root.querySelector("#year").innerHTML = option("", t("Admin.Library.AnyYear"), filters.year) +
withChosen(facets.years, filters.year).map((f) => option(f.value, counted(f), filters.year)).join("");
root.querySelector("#camera").innerHTML = option("", t("Admin.Library.AnyCamera"), filters.camera) +
withChosen(facets.cameras, filters.camera).map((f) => option(f.value, counted(f), filters.camera)).join("");
root.querySelector("#tag").innerHTML = option("", t("Admin.Library.AnyTag"), filters.tag) +
withChosen(facets.tags, filters.tag).map((f) => option(f.value, counted(f), filters.tag)).join("");
root.querySelector("#status").innerHTML = option("", t("Admin.Library.AnyStatus"), filters.status) +
Object.keys(STATUS_FILTERS).map((s) => option(s, t(`Admin.Library.Filter.${pascal(s)}`), filters.status)).join("");
root.querySelectorAll(".toolbar select").forEach((s) => s.classList.toggle("active", s.id !== "sort" && s.value !== ""));
}
function draw() {
itemsHost.className = `seq-items ${view === "list" ? "rows" : "cards"}`;
itemsHost.setAttribute("role", "listbox");
itemsHost.setAttribute("aria-multiselectable", "true");
itemsHost.setAttribute("aria-label", t("Admin.Library.Sequences"));
if (rows.length === 0) {
itemsHost.removeAttribute("role");
itemsHost.removeAttribute("aria-multiselectable");
const filtered = FILTERS.some((f) => f !== "sort" && filters[f]);
itemsHost.innerHTML = filtered
? emptyState("Admin.Library.NoMatch", `<button class="btn small" id="clear" data-i18n="Admin.Library.ClearFilters" data-i18n-title="Admin.Library.ClearFilters.Tip"></button>`)
: emptyState("Admin.Library.Empty", `<button class="btn small" id="scan" data-i18n="Admin.Archive.Scan" data-i18n-title="Admin.Archive.Scan.Tip"></button>`);
applyStrings(itemsHost);
itemsHost.querySelector("#clear")?.addEventListener("click", clearFilters);
itemsHost.querySelector("#scan")?.addEventListener("click", scan);
syncSelection();
return;
}
const head = view === "list" ? `<div class="seq-head" aria-hidden="true"><span></span><span></span>
<span data-i18n="Admin.Library.Column.Sequence"></span><span class="col-camera" data-i18n="Admin.Library.Column.Camera"></span>
<span class="end" data-i18n="Admin.Library.Column.Photos"></span><span class="end col-size" data-i18n="Admin.Library.Column.Size"></span>
<span class="col-date" data-i18n="Admin.Library.Column.Date"></span></div>` : "";
itemsHost.innerHTML = head + rows.map(itemHtml).join("");
applyStrings(itemsHost);
watchImages(itemsHost);
grid.restore();
syncSelection();
}
function appendItems(items) {
if (rows.length === items.length) return draw();
itemsHost.insertAdjacentHTML("beforeend", items.map(itemHtml).join(""));
watchImages(itemsHost);
grid.restore();
syncSelection();
}
function itemHtml(s) {
const facts = factsLine(s);
const thumb = lazyImage(coverUrl(s));
const label = [s.displayTitle, facts].filter(Boolean).join(" · ");
const check = `<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Library.Select.Tip"))}">`;
if (view === "list") {
return `<div class="seq-row" role="option" data-key="${attr(s.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Library.Open.Tip"))}">
${check}${thumb}
<span class="stack"><strong class="ellipsis" dir="auto">${escapeHtml(s.displayTitle)}</strong><span class="chips-row">${statusChips(s)}</span></span>
<span class="ellipsis col-camera" dir="auto">${escapeHtml(cameraLabel(s.cameraMake, s.cameraModel) || "—")}</span>
<span class="num end">${formatNumber(s.frameCount)}</span>
<span class="num end col-size">${escapeHtml(formatBytes(s.totalBytes))}</span>
<span class="muted nowrap col-date">${escapeHtml(captureText(s.firstCapture, false))}</span>
</div>`;
}
return `<div class="seq-card" role="option" data-key="${attr(s.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Library.Open.Tip"))}">
${thumb}${check}
<span class="count num" aria-hidden="true">${formatNumber(s.frameCount)}</span>
<span class="info"><strong class="ellipsis" dir="auto">${escapeHtml(s.displayTitle)}</strong>
<span class="facts ellipsis" dir="auto">${escapeHtml(facts || "—")}</span>
<span class="chips-row">${statusChips(s)}</span></span>
</div>`;
}
function drawFoot() {
root.querySelector("#foot").hidden = rows.length === 0 || (!cursor && rows.length >= total);
root.querySelector("#more").hidden = !cursor;
root.querySelector("#shown").textContent = t("Admin.Library.Shown", formatNumber(rows.length), formatNumber(total));
}
/** Check boxes, item states and the mass bar for the selection; the items themselves are not drawn again. */
function syncSelection() {
itemsHost.querySelectorAll('[role="option"]').forEach((el) => {
const on = selection.has(el.dataset.key);
el.setAttribute("aria-selected", String(on));
const box = el.querySelector("[data-check]");
if (box) box.checked = on;
});
itemsHost.classList.toggle("selecting", selection.size > 0);
drawMass();
}
function drawMass() {
if (selection.size === 0) {
mass.hidden = true;
mass.innerHTML = "";
return;
}
const selectAll = !matching && total > selection.size
? `<button class="btn small subtle" id="mass-all" data-mass="all" data-i18n-title="Admin.Library.SelectAll.Tip">${escapeHtml(t("Admin.Library.SelectAll", formatNumber(total)))}</button>` : "";
const job = (kind) => `<button class="btn small" id="mass-${kind}" data-mass="job" data-kind="${kind}" data-i18n="Admin.Library.Job.${cap(kind)}" data-i18n-title="Admin.Library.Job.${cap(kind)}.Tip"></button>`;
mass.hidden = false;
// Drawn again at every change of the selection: the keyboard focus stays on its button.
redraw(mass, () => {
mass.innerHTML = `
<strong class="nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", selection.size))}</strong>${selectAll}
<span class="spacer"></span>
${JOBS.map(job).join("")}
<button class="btn small" id="mass-retag" data-mass="retag" data-i18n="Admin.Library.Retag" data-i18n-title="Admin.Library.Retag.Tip"></button>
<button class="btn small" id="mass-csv" data-mass="csv" data-i18n="Admin.Library.ExportCsv" data-i18n-title="Admin.Library.ExportCsv.Tip"></button>
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Library.Delete" data-i18n-title="Admin.Library.Delete.Tip"></button>
<button class="btn small icon subtle" id="mass-clear" data-mass="clear" data-i18n-title="Admin.Library.ClearSelection.Tip">${icons.close}</button>`;
applyStrings(mass);
});
mass.querySelectorAll("[data-mass]").forEach((b) => b.addEventListener("click", () => massAction(b.dataset.mass, b)));
}
async function massAction(action, button) {
if (action === "clear") {
selection.clear();
matching = null;
syncSelection();
grid.restore(true);
return;
}
if (action === "all") return selectAll();
if (action === "csv") return exportCsv();
button.disabled = true;
try {
if (action === "job") await queueJobs(button.dataset.kind);
else if (action === "retag") await retag();
else if (action === "delete") await deleteSequences();
} finally {
if (button.isConnected) button.disabled = false;
}
}
/** Every sequence of the filter, a thousand per request: they all count as selected. */
async function selectAll() {
const all = [];
let after = null;
try {
do {
const page = await api.get(listQuery(BULK_LIMIT, after));
all.push(...page.items);
after = page.nextCursor;
} while (after);
} catch (err) {
toast(errorText(err), true);
return;
}
matching = all;
selection.set(all.map((s) => s.id));
syncSelection();
}
/** The selected sequences as far as this page knows them (all of them after Select all). */
function selectedRows() {
const known = new Map([...(matching ?? []), ...rows].map((s) => [s.id, s]));
return [...selection.ids].map((id) => known.get(id)).filter(Boolean);
}
async function queueJobs(kind) {
let queued = 0;
let skipped = 0;
try {
for (const ids of chunks([...selection.ids])) {
const result = await api.post("/api/v1/sequences/bulk/jobs", { ids, kind });
if (result.job) queued++;
skipped += result.skipped;
}
} catch (err) {
toast(errorText(err), true);
return;
}
toast([queued > 0 ? t("Admin.Library.JobQueued") : t("Admin.Library.NothingQueued"), skipped > 0 ? plural("Admin.Library.Skipped", skipped) : ""]
.filter(Boolean).join(" · "));
}
async function retag() {
const datalist = facets.tags.map((f) => `<option value="${attr(f.value)}"></option>`).join("");
const data = await formDialog({
title: plural("Admin.Library.RetagTitle", selection.size),
fields: `
<label><span data-i18n="Admin.Library.AddTags"></span><input class="input" name="add" dir="auto" list="retag-tags" autocomplete="off" data-i18n-title="Admin.Library.AddTags.Tip"></label>
<label><span data-i18n="Admin.Library.RemoveTags"></span><input class="input" name="remove" dir="auto" list="retag-tags" autocomplete="off" data-i18n-title="Admin.Library.RemoveTags.Tip"></label>
<datalist id="retag-tags">${datalist}</datalist>`,
confirm: t("Admin.Library.Apply"),
confirmTip: t("Admin.Library.Apply.Tip"),
cancel: t("Admin.Common.Cancel"),
cancelTip: t("Admin.Common.Cancel.Tip"),
check: (form) => {
const add = tagList(form.elements.add.value);
const remove = tagList(form.elements.remove.value);
const long = [form.elements.add, form.elements.remove].find((f) => tagList(f.value).some((tag) => tag.length > 64));
if (long) {
markInvalid(long, t("Admin.Library.TagTooLong"));
long.focus();
return false;
}
if (add.length + remove.length === 0) {
markInvalid(form.elements.add, t("Admin.Library.NoTags"));
form.elements.add.focus();
return false;
}
return true;
},
});
if (!data) return;
const add = tagList(String(data.get("add")));
const remove = tagList(String(data.get("remove")));
let ok = 0;
const skipped = [];
try {
for (const ids of chunks([...selection.ids])) {
const result = await api.post("/api/v1/sequences/bulk/retag", { ids, add, remove });
ok += result.ok;
skipped.push(...result.items.filter((i) => i.outcome !== "ok"));
}
} catch (err) {
toast(errorText(err), true);
return;
}
toast([plural("Admin.Library.Retagged", ok), skipped.length > 0 ? plural("Admin.Library.Skipped", skipped.length) : ""].filter(Boolean).join(" · "),
skipped.length > 0 && ok === 0);
refreshSoon();
}
/** Dry run, the list of what moves to the trash, then the move; each sequence goes whole or not at all. */
async function deleteSequences() {
const ids = [...selection.ids];
const plan = { items: [], ok: 0, photos: 0, bytes: 0 };
try {
for (const part of chunks(ids)) {
const result = await api.post("/api/v1/sequences/bulk/delete", { ids: part, dryRun: true });
plan.items.push(...result.items);
plan.ok += result.ok;
plan.photos += result.photos;
plan.bytes += result.bytes;
}
} catch (err) {
toast(errorText(err), true);
return;
}
const titles = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
const going = plan.items.filter((i) => i.outcome === "ok");
const blocked = plan.items.filter((i) => i.outcome !== "ok");
if (going.length === 0) {
toast(blocked[0]?.message || t("Admin.Library.NothingToDelete"), true);
return;
}
const body = [plural("Admin.Library.DeleteBody", going.length, plural("Admin.Dashboard.PhotoCount", plan.photos), formatBytes(plan.bytes)),
blocked.length > 0 ? plural("Admin.Library.DeleteBlocked", blocked.length) : ""].filter(Boolean).join(" ");
const confirmed = await confirmDialog({
title: plural("Admin.Library.DeleteTitle", going.length),
body,
list: [...going.map((i) => titles.get(i.id) ?? i.id), ...blocked.map((i) => t("Admin.Library.BlockedItem", titles.get(i.id) ?? i.id, i.message ?? i.reason))],
confirm: t("Admin.Library.DeleteConfirm"),
confirmTip: t("Admin.Library.DeleteConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed) return;
let moved = 0;
let photos = 0;
const failed = [];
try {
for (const part of chunks(going.map((i) => i.id))) {
const result = await api.post("/api/v1/sequences/bulk/delete", { ids: part, dryRun: false });
moved += result.ok;
photos += result.photos;
failed.push(...result.items.filter((i) => i.outcome !== "ok"));
}
} catch (err) {
toast(errorText(err), true);
}
toast([plural("Admin.Library.Deleted", moved, plural("Admin.Dashboard.PhotoCount", photos)), failed.length > 0 ? plural("Admin.Library.Skipped", failed.length) : ""]
.filter(Boolean).join(" · "), moved === 0);
selection.clear();
matching = null;
await load();
}
function exportCsv() {
const chosen = selectedRows();
saveFile(`chronos-library-${today()}.csv`, sequencesCsv(chosen));
toast(plural("Admin.Library.Exported", chosen.length));
}
function clearFilters() {
for (const f of FILTERS) filters[f] = f === "sort" ? filters.sort : "";
root.querySelector("#q").value = "";
listHash = filters.sort === "newest" ? "#/library" : `#/library?sort=${filters.sort}`;
history.replaceState(null, "", listHash);
load();
root.querySelector("#q").focus();
}
async function scan() {
try {
await api.post("/api/v1/archive/scan");
toast(t("Admin.Archive.Queued"));
} catch (err) {
toast(errorText(err), true);
}
}
function refreshSoon(delay = 800) {
clearTimeout(refreshTimer);
refreshTimer = setTimeout(() => {
if (root.isConnected) refreshVisible();
}, delay);
}
// Sequences that change (a job finished, an upload landed, someone deleted or retagged) show their new state.
onEvent((e) => {
if (e.type === "sequenceChanged") refreshSoon(800);
else if (e.type === "jobState" && (e.state === "done" || e.state === "failed")) refreshSoon(1500);
});
await load();
}
function storedView() {
try {
return localStorage.getItem(VIEW_KEY) === "list" ? "list" : "grid";
} catch {
return "grid";
}
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
function pascal(s) {
return s.split("-").map(cap).join("");
}