// What the Library's views share (owner review 2, R6): sequence facts and status chips as the desktop cards show them,
// thumbnails and their retries after a job ended, the job states that end a job, delete lists cut to LISTED names, a
// selection with Shift ranges, the keyboard of a grid of selectable items, chunked bulk calls and file downloads.
import { t, plural, culture } from "../../i18n.js";
import { escapeHtml, attr, formatNumber, formatDuration } from "../../ui.js";
import { icons } from "../../icons.js";
/** SequenceStatus bits (Chronos.Core.Model). */
export const STATUS = { analysed: 1, deep: 2, proxies: 4, thumbs: 8, verified: 16, warnings: 32, errors: 64 };
/** Ids one bulk request may name (LibraryEndpoints.MaxBulkIds). */
export const BULK_LIMIT = 1000;
/** Names a delete dialog lists; the count in its title says how many there are in all. */
export const LISTED = 500;
/** The jobState states after which a job does nothing more. */
export const JOB_ENDED = new Set(["done", "failed", "cancelled"]);
/** A dialog's list cut to LISTED lines and "…", so a delete of thousands never builds thousands of nodes. */
export function listed(lines) {
return lines.length > LISTED ? [...lines.slice(0, LISTED), "…"] : lines;
}
/**
* A camera's name as the desktop and the server's facets give it (PathTemplate.CameraName): the make's brand once,
* "Canon EOS R5" (Canon + Canon EOS R5), "Nikon Z 8" (NIKON CORPORATION + NIKON Z 8), "SONY ILCE-7M4".
*/
export function cameraLabel(make, model) {
make = make?.trim();
model = model?.trim();
if (!model) return make ?? "";
if (!make) return model;
let brand = make.split(" ").find(Boolean);
if (brand.toUpperCase() === "NIKON") brand = "Nikon";
return model.toLowerCase().startsWith(brand.toLowerCase()) ? brand + model.slice(brand.length) : `${brand} ${model}`;
}
/** How long the sequence lasts, from its first capture to its last ("2 h 0 m"); "" without captures. */
export function spanText(s) {
if (!s.firstCapture || !s.lastCapture) return "";
return formatDuration((new Date(s.lastCapture) - new Date(s.firstCapture)) / 1000);
}
/** A capture time as the camera recorded it (stored without zone, so read and shown as it was taken). */
export function captureText(iso, withTime = true) {
if (!iso) return "—";
const options = withTime ? { dateStyle: "medium", timeStyle: "short" } : { dateStyle: "medium" };
return new Intl.DateTimeFormat(culture(), options).format(new Date(iso));
}
/** The line under a card's title: "3,600 · Canon EOS R5 · 2 h 0 m". */
export function factsLine(s) {
return [formatNumber(s.frameCount), cameraLabel(s.cameraMake, s.cameraModel), spanText(s)].filter(Boolean).join(" · ");
}
/**
* Status glyphs as DESIGN §4 draws them: ● analysed (○ not yet), ● proxies (○ none), ▶ n renders, ▲ n warnings, ✕ errors,
* ✓ verified. Each chip has its words for screen readers and its tooltip; the glyph alone is decoration.
*/
export function statusChips(s) {
const chip = (cls, glyph, key, text, tipKey) =>
`${glyph} ${escapeHtml(text ?? t(key))}`;
const on = (bit) => (s.status & bit) !== 0;
const chips = [
on(STATUS.analysed) ? chip("ok", "●", "Admin.Library.Status.Analysed", null, "Admin.Library.Status.Analysed.Tip")
: chip("off", "○", "Admin.Library.Status.NotAnalysed", null, "Admin.Library.Status.NotAnalysed.Tip"),
on(STATUS.proxies) ? chip("", "●", "Admin.Library.Status.Proxies", null, "Admin.Library.Status.Proxies.Tip")
: chip("off", "○", "Admin.Library.Status.NoProxies", null, "Admin.Library.Status.NoProxies.Tip"),
];
if (on(STATUS.verified)) chips.push(chip("ok", "✓", "Admin.Library.Status.Verified", null, "Admin.Library.Status.Verified.Tip"));
if (s.renderedCount > 0) chips.push(chip("", "▶", null, plural("Admin.Library.Status.Renders", s.renderedCount), "Admin.Library.Status.Renders.Tip"));
if (s.warningCount > 0 || on(STATUS.warnings))
chips.push(chip("warn", "▲", null, plural("Admin.Library.Status.Warnings", Math.max(1, s.warningCount)), "Admin.Library.Status.Warnings.Tip"));
if (on(STATUS.errors)) chips.push(chip("err", "✕", "Admin.Library.Status.Errors", null, "Admin.Library.Status.Errors.Tip"));
return chips.join("");
}
/**
* An image the browser loads when it nears the view, with the photo icon in its place while it has none: before it
* arrives, when the thumbnail is not built yet (404) or cannot be read. watchImages() hooks the error up (no inline
* handlers under the panel's policy).
*/
export function lazyImage(src, cls = "") {
return `${icons.image}` +
`
`;
}
export function watchImages(root) {
root.querySelectorAll("img[data-fallback]").forEach((img) => {
img.removeAttribute("data-fallback");
img.addEventListener("error", () => img.classList.add("failed"), { once: true });
img.addEventListener("load", () => img.classList.add("loaded"), { once: true });
});
}
/** Retries of an image that had nothing to show, the first after RETRY_FIRST_MS and each next one after twice the wait, up to RETRY_LONGEST_MS. */
const RETRY_TRIES = 8;
const RETRY_FIRST_MS = 2000;
const RETRY_LONGEST_MS = 60000;
/**
* The images under root that had nothing to show (a thumbnail not built yet) asked for again, once a job that may have
* built them ended: under an address the browser has not tried, so its first answer is not reused. Each image waits
* longer before every retry and stops after RETRY_TRIES, since some never get one (a photo whose original is missing);
* fresh (the sequence itself changed, a pass may have built them) starts every image's count again.
*/
export function retryImages(root, fresh = false) {
const now = Date.now();
root.querySelectorAll("img.failed").forEach((img) => {
const tries = fresh ? 0 : Number(img.dataset.tries ?? 0);
if (tries >= RETRY_TRIES || (!fresh && now < Number(img.dataset.retryAt ?? 0))) return;
img.dataset.tries = String(tries + 1);
img.dataset.retryAt = String(now + Math.min(RETRY_FIRST_MS * 2 ** tries, RETRY_LONGEST_MS));
const url = new URL(img.getAttribute("src"), location.href);
url.searchParams.set("retry", String(now));
img.classList.remove("failed");
img.setAttribute("data-fallback", "");
img.src = url.pathname + url.search;
});
watchImages(root);
}
/** A sequence's cover thumbnail; its address changes with the cover and the photos, so a browser's copy never shows an old one. */
export function coverUrl(s) {
return `/api/v1/sequences/${encodeURIComponent(s.id)}/thumb?v=${s.heroFrameId ?? "first"}-${s.framesVersion}`;
}
/** Items picked by click, Space and Shift ranges over the order shown; the anchor is where the next range starts. */
export class Selection {
constructor() {
this.ids = new Set();
this.anchor = null;
}
get size() {
return this.ids.size;
}
has(id) {
return this.ids.has(id);
}
toggle(id) {
if (!this.ids.delete(id)) this.ids.add(id);
this.anchor = id;
}
/** Selects every item from the anchor to id in order (the anchor stays), or id alone without an anchor in view. */
range(id, order) {
const from = order.indexOf(this.anchor);
const to = order.indexOf(id);
if (from < 0 || to < 0) return this.toggle(id);
const [a, b] = from < to ? [from, to] : [to, from];
for (let i = a; i <= b; i++) this.ids.add(order[i]);
}
set(ids) {
this.ids = new Set(ids);
}
clear() {
this.ids.clear();
this.anchor = null;
}
}
/**
* The keyboard and pointer of a grid of selectable items (role="option" with data-key, in a role="listbox"): one tab
* stop (the current item), arrows move along the reading direction and between rows, Home and End, Space selects
* (Shift+Space: the range from the last one picked), Enter opens, Ctrl+A selects everything shown, Esc clears the
* selection. A click on an item's check box selects (with Shift, a range), Ctrl+click too; a plain click opens.
* The caller redraws through onChange after the selection changed.
*/
export function selectableGrid(host, { selection, order, open, onChange }) {
let current = null;
const items = () => [...host.querySelectorAll('[role="option"]')];
const focusItem = (el) => {
if (!el) return;
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
current = el.dataset.key;
el.focus();
};
const pick = (key, shift) => {
if (shift) selection.range(key, order());
else selection.toggle(key);
onChange();
};
host.addEventListener("focusin", (e) => {
const el = e.target.closest?.('[role="option"]');
if (el && host.contains(el)) {
current = el.dataset.key;
items().forEach((i) => (i.tabIndex = i === el ? 0 : -1));
}
});
host.addEventListener("click", (e) => {
const el = e.target.closest('[role="option"]');
if (!el || !host.contains(el)) return;
if (e.target.closest("[data-check]") || e.ctrlKey || e.metaKey || e.shiftKey) {
// A check box keeps its own click (a cancelled one would put its old state back after onChange drew the new one).
if (!e.target.matches("input[data-check]")) e.preventDefault();
pick(el.dataset.key, e.shiftKey);
return;
}
if (e.target.closest("a, button")) return;
open(el.dataset.key);
});
host.addEventListener("keydown", (e) => {
const el = e.target.closest?.('[role="option"]');
if (!el || e.altKey) return;
const list = items();
const index = list.indexOf(el);
const rtl = getComputedStyle(host).direction === "rtl";
let next = null;
switch (e.key) {
case "ArrowRight": next = list[index + (rtl ? -1 : 1)]; break;
case "ArrowLeft": next = list[index + (rtl ? 1 : -1)]; break;
case "ArrowDown": next = list[index + columns(list)]; break;
case "ArrowUp": next = list[index - columns(list)]; break;
case "Home": next = list[0]; break;
case "End": next = list[list.length - 1]; break;
case " ":
e.preventDefault();
pick(el.dataset.key, e.shiftKey);
return;
case "Enter":
e.preventDefault();
open(el.dataset.key);
return;
case "Escape":
if (selection.size === 0) return;
e.preventDefault();
selection.clear();
onChange();
return;
case "a":
case "A":
if (!(e.ctrlKey || e.metaKey)) return;
e.preventDefault();
selection.set(list.map((i) => i.dataset.key));
onChange();
return;
default:
return;
}
e.preventDefault();
focusItem(next);
});
return {
/** After a redraw: the current item keeps the tab stop (the first one when it is gone). */
restore(focus = false) {
const list = items();
const el = list.find((i) => i.dataset.key === current) ?? list[0];
list.forEach((i) => (i.tabIndex = i === el ? 0 : -1));
if (focus && el) el.focus();
},
};
}
/** Items per row of a wrapping grid: those on the first item's line. */
function columns(list) {
const top = list[0]?.offsetTop;
const n = list.findIndex((i) => i.offsetTop !== top);
return n < 0 ? list.length || 1 : n;
}
/** Tags typed as "night, roof; sky": trimmed, once each (case-insensitive), none empty. */
export function tagList(text) {
const seen = new Set();
return String(text ?? "").split(/[,;]/).map((s) => s.trim()).filter((s) => {
const key = s.toLocaleLowerCase();
if (!s || seen.has(key)) return false;
seen.add(key);
return true;
});
}
/** The ids in requests of at most BULK_LIMIT, in their order. */
export function chunks(ids, size = BULK_LIMIT) {
const out = [];
for (let i = 0; i < ids.length; i += size) out.push(ids.slice(i, i + size));
return out;
}
/** Hands the browser a file to save (a Blob made here; nothing leaves the page). */
export function saveFile(name, blob) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
/**
* Sequences as CSV (comma separated, UTF-8 with a byte-order mark for spreadsheets): title, camera, photos, size in
* bytes, first and last capture (ISO, as the camera recorded them) and tags. A cell a spreadsheet would run as a formula
* starts with an apostrophe.
*/
export function sequencesCsv(sequences) {
const cell = (value) => {
let text = String(value ?? "");
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
return /[",\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
};
const head = ["Admin.Library.Csv.Title", "Admin.Library.Csv.Camera", "Admin.Library.Csv.Photos", "Admin.Library.Csv.Bytes",
"Admin.Library.Csv.First", "Admin.Library.Csv.Last", "Admin.Library.Csv.Tags"].map((key) => cell(t(key)));
const rows = sequences.map((s) => [s.displayTitle, cameraLabel(s.cameraMake, s.cameraModel), s.frameCount, s.totalBytes,
s.firstCapture ?? "", s.lastCapture ?? "", (s.tags ?? []).join("; ")].map(cell).join(","));
return new Blob(["" + [head.join(","), ...rows].join("\r\n") + "\r\n"], { type: "text/csv;charset=utf-8" });
}
/** "2026-10-27" in the file names of exports. */
export function today() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}