// A sequence on the panel (owner review 2, R6): its title, tags, rating and notes, its facts, its photos in pages of 500 // with lazy thumbnails, a photo viewer, deleting photos into the archive's trash, the cover, its projects (R8: listed, // renamed and deleted, projects.js), the originals and the renders to download. Nothing here edits the video: its settings, // its projects' versions and its renders are the desktop editor's. import { t, plural, applyStrings } from "../../i18n.js"; import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, escapeReverts, redraw } from "../../ui.js"; import { icons } from "../../icons.js"; import { captureText, cameraLabel, spanText, statusChips, lazyImage, watchImages, retryImages, Selection, selectableGrid, tagList, coverUrl, listed, JOB_ENDED } from "./shared.js"; import { projectsSection } from "./projects.js"; const FRAME_PAGE = 500; /** Deleting more photos than this asks for their number to be typed. */ const TYPED_ABOVE = 20; /** How long after a job ended the page reads the sequence again; one read covers every job that ended meanwhile. */ const AFTER_JOB_MS = 1500; /** FrameFlags bits the viewer and the tiles name. */ const FLAGS = [[1, "Missing"], [2, "Corrupt"], [4, "Duplicate"], [8, "Excluded"]]; const MAX_TAGS = 50; export async function renderSequence(root, { api, setMeta, actions, onEvent }, id, { back, loadUpload }) { let seq; let frames = []; let cursor = null; let renders = []; /** The renders' list as last drawn (JSON), null before the first draw. */ let rendersShown = null; let generation = 0; let timer = null; let jobTimer = null; /** Set once this page deleted the sequence, or saw it go: its deletion event then says nothing more. */ let leaving = false; const selection = new Selection(); actions.innerHTML = ` ${icons.back}`; applyStrings(actions); try { seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`); } catch (err) { root.innerHTML = err.status === 404 ? `
${emptyState("Admin.Sequence.Gone", ``)}
` : `
${escapeHtml(errorText(err))}
`; applyStrings(root); return; } actions.insertAdjacentHTML("beforeend", ` `); applyStrings(actions); actions.querySelector("#delete-sequence").addEventListener("click", deleteSequence); loadUpload().then((upload) => { const button = actions.querySelector("#add"); if (!upload || !button?.isConnected) return; button.hidden = false; button.title = t("Admin.Sequence.AddPhotos.Tip"); button.addEventListener("click", () => upload.openUpload({ api, sequence: seq, onDone: () => reload(true) })); }); root.innerHTML = `

`; applyStrings(root); const projects = projectsSection(root.querySelector("#projects"), root.querySelector("#projects-meta"), { api, sequenceId: id }); const form = root.querySelector("form"); const framesHost = root.querySelector("#frames"); escapeReverts(form); form.addEventListener("submit", (e) => e.preventDefault()); form.elements.title.addEventListener("change", () => { const title = form.elements.title.value.trim(); if (title !== (seq.title ?? "")) patch({ title }); }); form.elements.title.addEventListener("keydown", (e) => { if (e.key === "Enter") form.elements.title.blur(); }); form.elements.notes.addEventListener("change", () => { const notes = form.elements.notes.value; if (notes !== (seq.notes ?? "")) patch({ notes }); }); const tagInput = root.querySelector("#tag-add"); tagInput.addEventListener("keydown", (e) => { if (e.key !== "Enter") return; e.preventDefault(); const added = tagList(tagInput.value).filter((tag) => !seq.tags.some((s) => s.toLocaleLowerCase() === tag.toLocaleLowerCase())); if (added.some((tag) => tag.length > 64)) return toast(t("Admin.Library.TagTooLong"), true); if (seq.tags.length + added.length > MAX_TAGS) return toast(t("Admin.Sequence.TooManyTags"), true); tagInput.value = ""; if (added.length > 0) patch({ tags: [...seq.tags, ...added] }, "tag-add"); }); root.querySelector("#frames-more").addEventListener("click", () => loadFrames(true)); const grid = selectableGrid(framesHost, { selection, order: () => frames.map((f) => f.id), open: (key) => openViewer(key), onChange: syncSelection, }); function drawHeader() { setMeta(seq.displayTitle); document.title = `${seq.displayTitle} · Chronos Server`; const titleField = form.elements.title; if (document.activeElement !== titleField) titleField.value = titleField.defaultValue = seq.title ?? ""; titleField.placeholder = seq.displayTitle; const notes = form.elements.notes; if (document.activeElement !== notes) notes.value = notes.defaultValue = seq.notes ?? ""; // The cover is drawn again only when it changes (another photo, other photos), not at every edit. const cover = root.querySelector("#cover"); if (cover.dataset.src !== coverUrl(seq)) { cover.dataset.src = coverUrl(seq); cover.innerHTML = lazyImage(coverUrl(seq), "cover"); watchImages(cover); } // Tags and stars are buttons: a redraw keeps the keyboard focus on the same one (a star by its id, a tag by its place). const tags = root.querySelector("#tags"); redraw(tags, () => { tags.innerHTML = seq.tags.map((tag, i) => `${escapeHtml(tag)}`).join(""); }); tags.querySelectorAll("[data-remove]").forEach((b) => b.addEventListener("click", () => patch({ tags: seq.tags.filter((_, i) => i !== Number(b.dataset.remove)) }, "tag-add"))); const rating = root.querySelector("#rating"); redraw(rating, () => { rating.innerHTML = [1, 2, 3, 4, 5].map((n) => ``).join(""); }); rating.querySelectorAll("[data-star]").forEach((b) => b.addEventListener("click", () => { const n = Number(b.dataset.star); patch({ rating: n === seq.rating ? 0 : n }, `star-${n}`); })); const fact = (key, value, { ltr = false, html = false } = {}) => value === null || value === undefined || value === "" ? "" : `
${html ? value : escapeHtml(value)}
`; const captured = seq.firstCapture ? `${captureText(seq.firstCapture)} – ${captureText(seq.lastCapture)}` : ""; root.querySelector("#facts").innerHTML = [ fact("Camera", cameraLabel(seq.cameraMake, seq.cameraModel)), fact("Lens", seq.lens), fact("Captured", captured), fact("Span", spanText(seq)), fact("Photos", formatNumber(seq.frameCount)), fact("Size", formatBytes(seq.totalBytes)), fact("Interval", seq.medianInterval ? t("Common.Duration.Seconds", formatNumber(Math.round(seq.medianInterval * 10) / 10)) : ""), fact("Folder", seq.folder, { ltr: true }), fact("Status", `${statusChips(seq)}`, { html: true }), fact("Updated", formatDateTime(seq.updatedAt)), ].join(""); applyStrings(root.querySelector("#facts")); } /** One field of the sequence changed (the same edit as the desktop's Library makes); a conflict reloads it. */ async function patch(change, focusId = null) { const hero = seq.heroFrameId; try { seq = await api.patch(`/api/v1/sequences/${encodeURIComponent(id)}`, { ...change, expectedSettingsVersion: seq.settingsVersion }); toast(t("Admin.Common.Saved")); } catch (err) { toast(errorText(err), true); if (err.status === 409) await reloadSequence(); } drawHeader(); // The cover's mark moves to its new photo. if (seq.heroFrameId !== hero) drawFrames(); if (focusId) root.querySelector(`#${focusId}`)?.focus(); } async function reloadSequence() { try { seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`); } catch (err) { if (err.status === 404) gone(); } } async function loadFrames(more = false) { const mine = ++generation; try { const page = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/frames?limit=${FRAME_PAGE}${more && cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}`); if (mine !== generation || !root.isConnected) return; cursor = page.nextCursor; if (more) { frames = frames.concat(page.items); framesHost.insertAdjacentHTML("beforeend", page.items.map(frameHtml).join("")); watchImages(framesHost); grid.restore(); syncSelection(); } else { frames = page.items; drawFrames(); } } catch (err) { toast(errorText(err), true); } drawFramesFoot(); } /** The photos again after they changed, as many as were shown; the selection keeps the photos still there. */ async function reloadFrames() { const want = Math.max(frames.length, FRAME_PAGE); const mine = ++generation; let list = []; let after = null; try { do { const page = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/frames?limit=${FRAME_PAGE}${after ? `&cursor=${encodeURIComponent(after)}` : ""}`); list = list.concat(page.items); after = page.nextCursor; } while (after && list.length < want); } catch (err) { toast(errorText(err), true); return; } if (mine !== generation || !root.isConnected) return; frames = list; cursor = after; const known = new Set(frames.map((f) => f.id)); selection.set([...selection.ids].filter((f) => known.has(f))); const focused = framesHost.contains(document.activeElement); drawFrames(); grid.restore(focused); drawFramesFoot(); } function drawFrames() { framesHost.innerHTML = frames.map(frameHtml).join("") || `
${emptyState("Admin.Sequence.NoPhotos")}
`; applyStrings(framesHost); watchImages(framesHost); grid.restore(); syncSelection(); } function frameHtml(f) { const flags = FLAGS.filter(([bit]) => (f.flags & bit) !== 0).map(([, name]) => t(`Admin.Sequence.Flag.${name}`)); const label = [f.fileName, captureText(f.capturedAt), ...flags].join(" · "); const hero = f.id === seq.heroFrameId ? `${icons.hero}` : ""; const flagged = flags.length > 0 ? `${icons.warning}` : ""; return `
${lazyImage(`/api/v1/frames/${encodeURIComponent(f.id)}/thumb`)} ${hero}${flagged}
`; } function drawFramesFoot() { root.querySelector("#photos-meta").textContent = plural("Admin.Dashboard.PhotoCount", seq.frameCount); root.querySelector("#frames-foot").hidden = !cursor; root.querySelector("#frames-shown").textContent = t("Admin.Library.Shown", formatNumber(frames.length), formatNumber(seq.frameCount)); } function syncSelection() { framesHost.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; }); framesHost.classList.toggle("selecting", selection.size > 0); drawFrameActions(); } function drawFrameActions() { const host = root.querySelector("#frame-actions"); const n = selection.size; const one = n === 1; const tip = (key, enabled, why) => attr(t(enabled ? key : why)); redraw(host, () => { host.innerHTML = ` ${n > 0 ? `${escapeHtml(plural("Admin.Library.Selected", n))}` : ""} ${n > 0 ? `` : ""} `; applyStrings(host); }); host.querySelectorAll("[data-frames]").forEach((b) => b.addEventListener("click", () => frameAction(b.dataset.frames))); } function frameAction(action) { const [only] = selection.ids; switch (action) { case "all": selection.set(frames.map((f) => f.id)); return syncSelection(); case "clear": selection.clear(); syncSelection(); return grid.restore(true); case "cover": return setCover(only); case "download": return download(only); case "delete": return deletePhotos(); } } function setCover(frameId) { return patch({ heroFrameId: frameId }); } function download(frameId) { const frame = frames.find((f) => f.id === frameId); const a = document.createElement("a"); a.href = `/api/v1/frames/${encodeURIComponent(frameId)}/original`; a.download = frame?.fileName ?? ""; document.body.appendChild(a); a.click(); a.remove(); } /** Dry run, the confirmation (typing the count when many go), then the move into the archive's trash. */ async function deletePhotos() { const ids = [...selection.ids]; const url = `/api/v1/sequences/${encodeURIComponent(id)}/frames/delete`; let plan; try { plan = await api.post(url, { frameIds: ids, expectedFramesVersion: seq.framesVersion, dryRun: true }); } catch (err) { return refused(err); } const names = frames.filter((f) => selection.has(f.id)).map((f) => f.fileName); const confirmed = await confirmDialog({ title: plural("Admin.Sequence.DeletePhotosTitle", plan.photos), body: plural("Admin.Sequence.DeletePhotosBody", plan.photos, formatBytes(plan.bytes)), list: listed(names), confirm: t("Admin.Sequence.DeletePhotosConfirm"), confirmTip: t("Admin.Sequence.DeletePhotosConfirm.Tip"), cancel: t("Admin.Common.Keep"), cancelTip: t("Admin.Common.Keep.Tip"), typed: plan.photos > TYPED_ABOVE ? String(plan.photos) : undefined, typedKind: "count", }); if (!confirmed) return; let result; try { result = await api.post(url, { frameIds: ids, expectedFramesVersion: plan.framesVersion, dryRun: false }); } catch (err) { return refused(err); } toast(plural("Admin.Sequence.PhotosDeleted", result.photos)); selection.clear(); await reload(true); } /** A deletion the server refused: its sentence; photos that changed meanwhile are shown again. */ async function refused(err) { toast(errorText(err), true); if (err.code === "frames_conflict") await reload(true); if (err.status === 404) gone(); } async function deleteSequence() { const url = `/api/v1/sequences/${encodeURIComponent(id)}`; let plan; try { plan = await api.del(`${url}?dryRun=true`); } catch (err) { return toast(errorText(err), true); } const confirmed = await confirmDialog({ title: t("Admin.Sequence.DeleteTitle", seq.displayTitle), body: plural("Admin.Sequence.DeleteBody", plan.frameCount, formatBytes(plan.totalBytes)), confirm: t("Admin.Library.DeleteConfirm"), confirmTip: t("Admin.Sequence.DeleteConfirm.Tip"), cancel: t("Admin.Common.Keep"), cancelTip: t("Admin.Common.Keep.Tip"), }); if (!confirmed) return; leaving = true; try { await api.del(url); } catch (err) { leaving = false; return toast(errorText(err), true); } toast(t("Admin.Sequence.Deleted", seq.displayTitle)); location.hash = back; } /** The renders, drawn again only when their list changed (a refresh after every job must not move the focus). */ async function loadRenders() { let list; try { list = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/renders`); } catch { // A failed refresh leaves the list shown; a first read that failed shows none. if (rendersShown !== null) return; list = []; } const key = JSON.stringify(list); if (key === rendersShown || !root.isConnected) return; rendersShown = key; renders = list; const host = root.querySelector("#renders"); redraw(host, () => drawRenders(host)); } function drawRenders(host) { host.innerHTML = renders.length === 0 ? emptyState("Admin.Sequence.NoRenders") : `
${renders.map((r) => `
${escapeHtml(r.presetName)} ${escapeHtml(`${r.width} × ${r.height} · ${formatNumber(r.fps)} fps${r.codec ? ` · ${r.codec.toUpperCase()}` : ""}`)} ${escapeHtml(clock(r.durationSeconds))} ${escapeHtml(formatBytes(r.bytes))} ${escapeHtml(formatDateTime(r.created))} ${icons.download}
`).join("")}
`; applyStrings(host); } /** The photo viewer: the proxy (the thumbnail when there is none), its facts, ← and → through the photos, Esc closes. */ function openViewer(frameId) { let index = frames.findIndex((f) => f.id === frameId); if (index < 0) return; const opener = document.activeElement; const dialog = document.createElement("dialog"); dialog.className = "dialog viewer"; dialog.setAttribute("aria-labelledby", "viewer-title"); dialog.innerHTML = `

`; applyStrings(dialog); document.body.appendChild(dialog); const img = dialog.querySelector("img"); img.addEventListener("error", () => { // No proxy (proxies off, or not built yet): the thumbnail, then the placeholder. const thumb = `/api/v1/frames/${encodeURIComponent(frames[index].id)}/thumb`; if (!img.src.endsWith(thumb)) img.src = thumb; else img.classList.add("failed"); }); img.addEventListener("load", () => img.classList.remove("failed")); const show = async (to) => { if (to >= frames.length && cursor) await loadFrames(true); if (to < 0 || to >= frames.length) return; index = to; const f = frames[index]; img.classList.remove("failed"); img.src = `/api/v1/frames/${encodeURIComponent(f.id)}/proxy`; dialog.querySelector("#viewer-title").textContent = f.fileName; dialog.querySelector("#viewer-position").textContent = t("Admin.Sequence.Position", formatNumber(f.index + 1), formatNumber(seq.frameCount)); dialog.querySelector("#viewer-meta").innerHTML = frameFacts(f); applyStrings(dialog.querySelector("#viewer-meta")); dialog.querySelector('[data-go="-1"]').disabled = index === 0; dialog.querySelector('[data-go="1"]').disabled = index === frames.length - 1 && !cursor; dialog.querySelector("[data-cover]").disabled = f.id === seq.heroFrameId; }; dialog.addEventListener("keydown", (e) => { if (e.key === "ArrowLeft" || e.key === "ArrowRight") { e.preventDefault(); show(index + (e.key === "ArrowRight" ? 1 : -1)); } }); dialog.querySelectorAll("[data-go]").forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.go)))); dialog.querySelector("[data-close]").addEventListener("click", () => dialog.close()); dialog.querySelector("[data-cover]").addEventListener("click", async () => { await setCover(frames[index].id); show(index); }); dialog.querySelector("[data-download]").addEventListener("click", () => download(frames[index].id)); dialog.addEventListener("close", () => { const at = frames[index]?.id; dialog.remove(); // Back on the photo the viewer ended on. const tile = at && framesHost.querySelector(`[data-key="${CSS.escape(at)}"]`); (tile ?? opener)?.focus?.(); }); dialog.showModal(); show(index); } function frameFacts(f) { const fact = (key, value, ltr = false) => value === null || value === undefined || value === "" ? "" : `
${escapeHtml(value)}
`; const swapped = f.orientation >= 5 && f.orientation <= 8; const [w, h] = swapped ? [f.height, f.width] : [f.width, f.height]; const offset = f.utcOffsetMinutes == null ? "" : ` UTC${f.utcOffsetMinutes < 0 ? "−" : "+"}${String(Math.floor(Math.abs(f.utcOffsetMinutes) / 60)).padStart(2, "0")}:${String(Math.abs(f.utcOffsetMinutes) % 60).padStart(2, "0")}`; const flags = FLAGS.filter(([bit]) => (f.flags & bit) !== 0).map(([, name]) => t(`Admin.Sequence.Flag.${name}`)).join(" · "); return [ fact("Time", f.capturedAt ? captureText(f.capturedAt) + offset : ""), fact("Exposure", exposure(f.exposureTime), true), fact("Aperture", f.fNumber ? `f/${formatNumber(f.fNumber)}` : "", true), fact("Iso", f.iso ? formatNumber(f.iso) : "", true), fact("Focal", f.focalLength ? `${formatNumber(f.focalLength)} mm` : "", true), fact("Dimensions", w > 0 && h > 0 ? `${w} × ${h}` : "", true), fact("Size", formatBytes(f.size)), fact("Format", f.format.toUpperCase(), true), fact("Flags", flags), fact("Sha256", f.sha256 ?? "", true), ].join(""); } /** * Everything again after a change elsewhere; with frames, the photos too. Only what changed is drawn again (the header * when the sequence read differs from the one shown), so a refresh that finds nothing new leaves the page and the * keyboard focus as they were. True when the sequence changed. */ async function reload(withFrames) { const shown = seq; await reloadSequence(); if (!root.isConnected || leaving) return false; const changed = JSON.stringify(seq) !== JSON.stringify(shown); if (changed) drawHeader(); if (withFrames || seq.framesVersion !== shown.framesVersion) await reloadFrames(); else if (seq.heroFrameId !== shown.heroFrameId) drawFrames(); await loadRenders(); return changed; } function gone() { if (leaving) return; leaving = true; toast(t("Admin.Sequence.Gone"), true); location.hash = back; } /** * After a job ended: thumbnail, proxy, verify and analysis jobs send no sequenceChanged, so the facts and status chips * are read again and the cover and photos that had no thumbnail yet are asked for again, each less often and up to a * limit, from the start again once the sequence changed. */ async function afterJob() { jobTimer = null; if (!root.isConnected || leaving) return; const changed = await reload(false); if (root.isConnected && !leaving) retryImages(root, changed); } onEvent((e) => { projects.onEvent(e); if (e.type === "jobState") { // The event names neither the job's kind nor its targets: any job that ended may have worked on this one. The timer // is not pushed back by the next one, so a busy queue still refreshes the page every AFTER_JOB_MS; a refresh that // finds the sequence and its renders as shown draws nothing. if (JOB_ENDED.has(e.state) && jobTimer === null) jobTimer = setTimeout(afterJob, AFTER_JOB_MS); return; } if (e.type !== "sequenceChanged" || e.sequenceId !== id) return; if (e.change === "deleted") { gone(); return; } clearTimeout(timer); timer = setTimeout(() => { if (root.isConnected) reload(false); }, 800); }); drawHeader(); await Promise.all([loadFrames(), loadRenders()]); drawFrameActions(); } /** 1/250 s, 0.5 s, 30 s. */ function exposure(seconds) { if (!seconds || seconds <= 0) return ""; if (seconds < 0.5) return `1/${Math.round(1 / seconds)} s`; return `${Math.round(seconds * 10) / 10} s`; } /** A video length as 1:05 or 1:02:05. */ function clock(seconds) { const s = Math.max(0, Math.round(seconds ?? 0)); const hh = Math.floor(s / 3600); const mm = Math.floor((s % 3600) / 60); const ss = String(s % 60).padStart(2, "0"); return hh > 0 ? `${hh}:${String(mm).padStart(2, "0")}:${ss}` : `${mm}:${ss}`; }