// 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", ``)}`
: `
`;
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 = `
${icons.image}
`;
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}`;
}