Files
Chronos/src/Chronos.Server/Admin/web/pages/library/sequence.js
T
Alby96andClaude Opus 5.5 81c303f484
CI / Build and test (push) Successful in 9m58s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 14m8s
CI / PostgreSQL 16 integration (push) Successful in 8m55s
CI / PostgreSQL 17 integration (push) Successful in 8m50s
CI / Docker image (push) Successful in 57s
Release / Server image (push) Successful in 1m22s
feat: owner review 2 phase 5b: the server as a project home (#17)
A Chronos Server keeps its sequences' projects, as a PC's archive does: Main and named projects with versions under /api/v1/sequences/{id}/projects, the projects capability and the projectChanged event. The desktop opens a server's sequences in the workspace (proxies downloaded, hash-checked, resumable) with Save version, Sync, conflicts, History, Restore and the project actions against the server. Renders can be of a project version. The admin panel lists a sequence's projects and versions. Strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-04 14:58:11 +01:00

622 lines
31 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 = `
<a class="btn" href="${attr(back)}" data-i18n-title="Admin.Sequence.Back.Tip">${icons.back}<span data-i18n="Admin.Sequence.Back"></span></a>`;
applyStrings(actions);
try {
seq = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}`);
} catch (err) {
root.innerHTML = err.status === 404
? `<section class="panel">${emptyState("Admin.Sequence.Gone", `<a class="btn small" href="${attr(back)}" data-i18n="Admin.Sequence.Back" data-i18n-title="Admin.Sequence.Back.Tip"></a>`)}</section>`
: `<div class="panel empty">${escapeHtml(errorText(err))}</div>`;
applyStrings(root);
return;
}
actions.insertAdjacentHTML("beforeend", `
<button class="btn" id="add" hidden>${icons.upload}<span data-i18n="Admin.Sequence.AddPhotos"></span></button>
<button class="btn destructive" id="delete-sequence" data-i18n="Admin.Sequence.Delete" data-i18n-title="Admin.Sequence.Delete.Tip"></button>`);
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 = `
<section class="panel seq-detail" aria-label="${attr(t("Admin.Sequence.Details"))}">
<div class="seq-cover" id="cover"></div>
<form class="form seq-fields" novalidate>
<input class="input heading" name="title" id="seq-title" dir="auto" maxlength="200" autocomplete="off"
aria-label="${attr(t("Admin.Sequence.Title"))}" data-i18n-title="Admin.Sequence.Title.Tip">
<div class="field-label"><span id="tags-label" data-i18n="Admin.Sequence.Tags"></span>
<div class="tag-editor" role="group" aria-labelledby="tags-label"><span class="tag-list" id="tags"></span>
<input class="input small" id="tag-add" dir="auto" autocomplete="off" data-i18n-placeholder="Admin.Sequence.AddTag" data-i18n-title="Admin.Sequence.AddTag.Tip"
aria-label="${attr(t("Admin.Sequence.AddTag"))}"></div></div>
<div class="field-label"><span id="rating-label" data-i18n="Admin.Sequence.Rating"></span>
<div class="stars" role="group" aria-labelledby="rating-label" id="rating"></div></div>
<label><span data-i18n="Admin.Sequence.Notes"></span>
<textarea class="input notes" name="notes" dir="auto" rows="3" maxlength="2000" data-i18n-title="Admin.Sequence.Notes.Tip"></textarea></label>
</form>
<dl class="seq-facts" id="facts"></dl>
</section>
<section class="panel flush" aria-labelledby="photos-title">
<div class="panel-head padded wrap"><h2 id="photos-title" data-i18n="Admin.Sequence.Photos"></h2><span class="muted ellipsis" id="photos-meta"></span>
<span class="spacer"></span><span class="button-row" id="frame-actions"></span></div>
<div class="frame-grid" id="frames" dir="ltr" role="listbox" aria-multiselectable="true" aria-labelledby="photos-title"></div>
<div class="table-foot" id="frames-foot" hidden><span class="muted" id="frames-shown"></span><span class="spacer"></span>
<button class="btn small" id="frames-more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Sequence.MorePhotos.Tip"></button></div>
</section>
<section class="panel flush" aria-labelledby="projects-title">
<div class="panel-head padded"><h2 id="projects-title" data-i18n="Admin.Projects.Title"></h2><span class="muted ellipsis" id="projects-meta"></span></div>
<div id="projects" class="table-host"></div>
</section>
<section class="panel flush" aria-labelledby="renders-title">
<div class="panel-head padded"><h2 id="renders-title" data-i18n="Admin.Sequence.Renders"></h2></div>
<div id="renders"></div>
</section>`;
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) => `<span class="tag" dir="auto">${escapeHtml(tag)}<button class="btn icon subtle tiny" type="button" data-remove="${i}"
title="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}" aria-label="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}">${icons.close}</button></span>`).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) => `<button class="btn icon subtle star" type="button" id="star-${n}" data-star="${n}" aria-pressed="${n <= seq.rating}"
aria-label="${attr(plural("Admin.Sequence.Stars", n))}" title="${attr(t(n === seq.rating ? "Admin.Sequence.Unrate.Tip" : "Admin.Sequence.Rate.Tip", n))}">${n <= seq.rating ? icons.starFilled : icons.star}</button>`).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 === ""
? "" : `<div><dt data-i18n="Admin.Sequence.Fact.${key}"></dt><dd ${ltr ? 'dir="ltr" class="mono"' : 'dir="auto"'}>${html ? value : escapeHtml(value)}</dd></div>`;
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", `<span class="chips-row">${statusChips(seq)}</span>`, { 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("") ||
`<div class="frame-empty">${emptyState("Admin.Sequence.NoPhotos")}</div>`;
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 ? `<span class="frame-badge hero" title="${attr(t("Admin.Sequence.Cover.Tip"))}">${icons.hero}</span>` : "";
const flagged = flags.length > 0 ? `<span class="frame-badge warn" title="${attr(flags.join(" · "))}">${icons.warning}</span>` : "";
return `<div class="frame" role="option" data-key="${attr(f.id)}" aria-selected="false" tabindex="-1" aria-label="${attr(label)}" title="${attr(t("Admin.Sequence.Photo.Tip", f.fileName))}">
${lazyImage(`/api/v1/frames/${encodeURIComponent(f.id)}/thumb`)}
<input type="checkbox" class="seq-check" data-check tabindex="-1" aria-hidden="true" title="${attr(t("Admin.Sequence.SelectPhoto.Tip"))}">
<span class="frame-no num" aria-hidden="true">${formatNumber(f.index + 1)}</span>${hero}${flagged}
</div>`;
}
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 ? `<span class="muted nowrap" role="status">${escapeHtml(plural("Admin.Library.Selected", n))}</span>` : ""}
<button class="btn small" id="frames-all" data-frames="all" data-i18n="Admin.Sequence.SelectAll" data-i18n-title="Admin.Sequence.SelectAll.Tip" ${frames.length === 0 ? "disabled" : ""}></button>
${n > 0 ? `<button class="btn small" id="frames-clear" data-frames="clear" data-i18n="Admin.Sequence.ClearSelection" data-i18n-title="Admin.Sequence.ClearSelection.Tip"></button>` : ""}
<button class="btn small" id="frames-cover" data-frames="cover" title="${tip("Admin.Sequence.SetCover.Tip", one, "Admin.Sequence.OnePhoto.Tip")}" ${one ? "" : "disabled"}>${icons.hero}<span data-i18n="Admin.Sequence.SetCover"></span></button>
<button class="btn small" id="frames-download" data-frames="download" title="${tip("Admin.Sequence.Download.Tip", one, "Admin.Sequence.OnePhoto.Tip")}" ${one ? "" : "disabled"}>${icons.download}<span data-i18n="Admin.Sequence.Download"></span></button>
<button class="btn small destructive" id="frames-delete" data-frames="delete" title="${tip("Admin.Sequence.DeletePhotos.Tip", n > 0, "Admin.Sequence.SomePhotos.Tip")}" ${n > 0 ? "" : "disabled"}
data-i18n="Admin.Sequence.DeletePhotos"></button>`;
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") : `
<div class="table renders" role="table" aria-labelledby="renders-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Sequence.Render.Preset"></span>
<span role="columnheader" data-i18n="Admin.Sequence.Render.Video"></span><span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Length"></span>
<span role="columnheader" class="end" data-i18n="Admin.Sequence.Render.Size"></span><span role="columnheader" data-i18n="Admin.Sequence.Render.Created"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div role="rowgroup">${renders.map((r) => `
<div class="row" role="row" data-key="${attr(r.id)}">
<span class="ellipsis" role="cell" dir="auto" title="${attr(r.producedBy ?? "")}">${escapeHtml(r.presetName)}</span>
<span class="num nowrap" role="cell" dir="ltr">${escapeHtml(`${r.width} × ${r.height} · ${formatNumber(r.fps)} fps${r.codec ? ` · ${r.codec.toUpperCase()}` : ""}`)}</span>
<span class="num end nowrap" role="cell">${escapeHtml(clock(r.durationSeconds))}</span>
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(r.bytes))}</span>
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(r.created))}</span>
<span class="row-actions" role="cell"><a class="btn small" href="/api/v1/renders/${encodeURIComponent(r.id)}/file" download
data-i18n-title="Admin.Sequence.Render.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Render.Download"></span></a></span>
</div>`).join("")}</div>
</div>`;
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 = `
<div class="viewer-head"><h2 id="viewer-title" class="ellipsis" dir="ltr"></h2><span class="muted num nowrap" id="viewer-position"></span>
<span class="spacer"></span>
<span class="inline" dir="ltr"><button class="btn icon" type="button" data-go="-1" data-i18n-title="Admin.Sequence.Previous.Tip">${icons.previous}</button>
<button class="btn icon" type="button" data-go="1" data-i18n-title="Admin.Sequence.Next.Tip">${icons.next}</button></span>
<button class="btn icon" type="button" data-close data-i18n-title="Admin.Sequence.CloseViewer.Tip">${icons.close}</button></div>
<div class="viewer-stage" dir="ltr"><img alt=""><span class="placeholder" aria-hidden="true">${icons.image}</span></div>
<dl class="viewer-meta" id="viewer-meta"></dl>
<div class="buttons">
<button class="btn" type="button" data-cover data-i18n-title="Admin.Sequence.SetCover.Tip">${icons.hero}<span data-i18n="Admin.Sequence.SetCover"></span></button>
<button class="btn" type="button" data-download data-i18n-title="Admin.Sequence.Download.Tip">${icons.download}<span data-i18n="Admin.Sequence.Download"></span></button>
</div>`;
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 === ""
? "" : `<div><dt data-i18n="Admin.Sequence.Fact.${key}"></dt><dd ${ltr ? 'dir="ltr"' : 'dir="auto"'}>${escapeHtml(value)}</dd></div>`;
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}`;
}