Owner review 2, R7 asks for mass conversion after import on the web panel too, with what happens to the originals chosen at every run. The Library's mass bar gets Convert… for the selection (every sequence after Select all without a filter, else at most a thousand ids, the same rule as Reorganize, now one helper). The dialog (convert.js) offers the format (linear DNG, the archival choice, first), the JPEG quality (shown for JPEG only, 1-100, checked on the field) and the mode, Replace or New sequence, never preselected, each tooltip saying what happens to the originals. Every change asks POST /archive/convert for a dry run, one request at a time and debounced while typing; the table shows per sequence the photos converted, the photos left as they are with why (what blocks the whole sequence first), and the size before and after, then the totals and the server's space line. While no mode is chosen the table is planned as New sequence (what converts does not depend on the mode) and Apply waits; choosing Replace plans again, since the fingerprint names the mode. Apply confirms Replace by typing the localised word, New sequence with a plain confirmation, sends the shown plan's fingerprint back and links the queued job; plan_changed, not_enough_space and nothing_to_convert plan again. Server refusals land on the field they name. The trash says what Restore does to a replaced entry (the originals swap back while their conversions are unchanged) and toasts it; the audit entry archive_converted reads as a sentence. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 2a09572e3e67ef95a931333c35cd3bb1e818db71) (cherry picked from commit 1d71a18fa112a7cb39e3e7ced7d7234230eb4453)
625 lines
29 KiB
JavaScript
625 lines
29 KiB
JavaScript
// 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).
|
|
// 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 = `
|
|
<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: () => {
|
|
// "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) => `<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");
|
|
itemsHost.innerHTML = isFiltered()
|
|
? 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-reorganize" data-mass="reorganize" data-i18n="Admin.Reorganize.Action" data-i18n-title="Admin.Reorganize.Action.Tip"></button>
|
|
<button class="btn small" id="mass-convert" data-mass="convert" data-i18n="Admin.Convert.Action" data-i18n-title="Admin.Convert.Action.Tip"></button>
|
|
<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();
|
|
// 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) => `<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(" ");
|
|
// 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("");
|
|
}
|