// 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= opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js). // Reorganize (R7) applies new folder, file and title templates to the selection (reorganize.js), Convert (R7) converts its // photos to JPEG, TIFF-16 or linear DNG (convert.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, listed, JOB_ENDED } from "./library/shared.js"; import { renderSequence } from "./library/sequence.js"; import { renderTrash } from "./library/trash.js"; import { openReorganize } from "../reorganize.js"; import { openConvert } from "../convert.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 = ` ${icons.trash} `; 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 = `
`; 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: () => { // "Select all" holds while sequences beyond the loaded rows stay selected (unticking cards keeps those); once none // does (Esc, Ctrl+A) the selection is the loaded rows' again: Select all comes back and a refresh drops sequences gone. if (matching) { const loaded = new Set(rows.map((r) => r.id)); if ([...selection.ids].every((id) => loaded.has(id))) matching = null; } 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), a thousand per request; the selection and the keyboard * place stay. */ async function refreshVisible() { const mine = ++generation; const wanted = Math.max(rows.length, PAGE); try { const facetsRead = api.get("/api/v1/sequences/facets").catch(() => facets); const first = await api.get(listQuery(Math.min(wanted, BULK_LIMIT), null)); let items = first.items; let after = first.nextCursor; while (after && items.length < wanted) { if (mine !== generation || !root.isConnected) return; const page = await api.get(listQuery(Math.min(wanted - items.length, BULK_LIMIT), after)); items = items.concat(page.items); after = page.nextCursor; } const f = await facetsRead; if (mine !== generation || !root.isConnected) return; total = first.total ?? total; facets = f; drawFilters(); rows = items; cursor = after; 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) => ``; // 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"); itemsHost.innerHTML = isFiltered() ? emptyState("Admin.Library.NoMatch", ``) : emptyState("Admin.Library.Empty", ``); applyStrings(itemsHost); itemsHost.querySelector("#clear")?.addEventListener("click", clearFilters); itemsHost.querySelector("#scan")?.addEventListener("click", scan); syncSelection(); return; } const head = view === "list" ? `` : ""; 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 = ``; if (view === "list") { return `
${check}${thumb} ${escapeHtml(s.displayTitle)}${statusChips(s)} ${escapeHtml(cameraLabel(s.cameraMake, s.cameraModel) || "—")} ${formatNumber(s.frameCount)} ${escapeHtml(formatBytes(s.totalBytes))} ${escapeHtml(captureText(s.firstCapture, false))}
`; } return `
${thumb}${check} ${escapeHtml(s.displayTitle)} ${escapeHtml(facts || "—")} ${statusChips(s)}
`; } 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 ? `` : ""; const job = (kind) => ``; mass.hidden = false; // Drawn again at every change of the selection: the keyboard focus stays on its button. redraw(mass, () => { mass.innerHTML = ` ${escapeHtml(plural("Admin.Library.Selected", selection.size))}${selectAll} ${JOBS.map(job).join("")} `; 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(); // Modal dialogs: the button stays enabled, so the focus comes back to it when the dialog closes. if (action === "reorganize") return reorganize(); if (action === "convert") return convert(); 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); } /** One job per thousand sequences (a bulk request's limit); the toast counts them, and says those queued before a failure. */ async function queueJobs(kind) { let queued = 0; let skipped = 0; let failure = null; 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) { failure = errorText(err); } const done = queued > 0 ? plural("Admin.Library.JobsQueued", queued) : failure ? "" : t("Admin.Library.NothingQueued"); toast([done, skipped > 0 ? plural("Admin.Library.Skipped", skipped) : "", failure ?? ""].filter(Boolean).join(" · "), failure !== null); } /** Whether a filter narrows the list (the sort order does not). */ function isFiltered() { return FILTERS.some((f) => f !== "sort" && filters[f]); } /** * What a plan-first mass operation (owner review 2, R7: Reorganize, Convert) works on: the selected sequences' ids, at * most a bulk request's thousand (one plan, one job). Beyond that, every sequence of the archive, but only while the * selection is exactly what Select all fetched without a filter and the archive has not grown since: a sequence unticked * or added later is never included. Null, with tooMany's toast, otherwise. */ function planTarget(tooMany) { const ids = [...selection.ids]; const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length && ids.length === matching.length && matching.every((s) => selection.has(s.id)); if (!everything && ids.length > BULK_LIMIT) { toast(t(tooMany, formatNumber(BULK_LIMIT)), true); return null; } return everything ? { all: true } : { sequenceIds: ids }; } /** Reorganize of the selected sequences: new folder, file and title templates, with a dry run. */ async function reorganize() { const target = planTarget("Admin.Reorganize.TooMany"); if (!target) return; const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle])); await openReorganize({ api, target, names }); } /** Convert of the selected sequences' photos: the format and, at every run, Replace or New sequence, with a dry run. */ async function convert() { const target = planTarget("Admin.Convert.TooMany"); if (!target) return; const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle])); await openConvert({ api, target, names }); } async function retag() { const datalist = facets.tags.map((f) => ``).join(""); const data = await formDialog({ title: plural("Admin.Library.RetagTitle", selection.size), fields: ` ${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(" "); // Those that stay first, with their reasons; the title and the body count them all. const confirmed = await confirmDialog({ title: plural("Admin.Library.DeleteTitle", going.length), body, list: listed([...blocked.map((i) => t("Admin.Library.BlockedItem", titles.get(i.id) ?? i.id, i.message ?? i.reason)), ...going.map((i) => titles.get(i.id) ?? i.id)]), 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); selection.clear(); matching = null; 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" && JOB_ENDED.has(e.state)) 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(""); }