feat(admin): Library pages on the web panel (owner review 2, R6)

The web panel now manages the library without editing it: the owner can
browse and view sequences and photos, delete sequences and photos into the
archive's trash, restore or empty the trash and run mass operations, as
R6 asks, on top of the engine endpoints of the previous commit.

- Library page right after the Dashboard: search, Year/Camera/Status/Tag
  filters fed by a new GET /api/v1/sequences/facets, sort, cards or list
  (remembered per browser), lazy cover thumbnails, Load more by cursor,
  multi-select with Shift ranges and "Select all N" of the filter, and a
  sticky bar for the selection: Analyse, Proxies, Thumbnails, Verify,
  Tags (add/remove), Export CSV (client-side) and Delete (dry run, list
  of what moves to the trash, then the move). Filters live in the address,
  so Back from a sequence finds them again.
- Sequence view (#/library?id=): inline title, tags, rating and notes,
  facts, photos in pages of 500 with content-visibility, a photo viewer
  (proxy, arrows, Esc, Exif facts), Set cover, Download original, Delete
  photos (typing the count above 20 photos), Delete sequence, renders to
  download. No video editing controls.
- Trash view (#/library?view=trash, also linked from Archive): entries,
  Restore, and Empty (dry run, list, the localised word typed, the plan's
  fingerprint sent back, the job followed to its end).
- Live updates from sequenceChanged and jobState; keyboard grid (one tab
  stop, arrows, Space, Shift+Space, Enter, Ctrl+A, Esc); RTL, dark theme.
- GET /sequences takes rendered=true|false for the Status filter.
- ui.js: confirmDialog's typed confirmation by name, word or count, with a
  list of what the action concerns; formDialog. api.js: putBytes for the
  web upload, which the Library imports on demand (upload.js, optional).
- New web icons from icons.py (Image for the Library, trash, grid/list,
  arrows, stars, cover); directional glyphs mirror in right-to-left pages.
- Strings in en and it; tests for the facets (both dialects), the rendered
  filter, the menu, the modules and the on-demand upload import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 029cf334f66cb6fa1265b96a6f8faff2964c11ea)
This commit is contained in:
Alby96 committed 2026-10-27 10:51:04 +01:00
1 parent 51782a3ada
commit aa1d4913a3
23 files changed
+2540 -31

No files matched your search

+111
View File
@@ -25,6 +25,8 @@
--error: light-dark(#c42b1c, #f0625d);
--shadow: light-dark(rgba(0, 0, 0, .18), rgba(0, 0, 0, .4));
--scrim: light-dark(rgba(0, 0, 0, .25), rgba(0, 0, 0, .6));
/* Badges drawn over photos (counts, numbers, the cover mark) read the same on light and dark pages. */
--on-photo: rgba(0, 0, 0, .6);
--radius: 6px;
--radius-card: 8px;
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
@@ -293,6 +295,115 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
.toast { width: 420px; max-width: calc(100vw - 48px); padding: 12px 14px; color: var(--text); background: var(--card); border: 1px solid var(--stroke); border-inline-start: 3px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
.toast.error { border-inline-start-color: var(--error); }
/* Directional glyphs (icons.js) point along the reading direction; inside a left-to-right island (photos, time) they do not turn. */
svg.directional:dir(rtl) { transform: scaleX(-1); }
.btn svg, .tag svg { flex: none; }
dialog.dialog .dialog-list { margin: 0; padding-block: 8px; padding-inline: 28px 12px; max-height: 200px; overflow: auto; border: 1px solid var(--stroke);
border-radius: var(--radius); background: var(--bg); font-size: 12px; overflow-wrap: anywhere; }
dialog.dialog .dialog-list:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
dialog.dialog .field-label strong { color: var(--text); }
/* Library (owner review 2, R6): toolbar, cards (DESIGN §4: 16:9 thumbnail, count badge, check box on hover or selection,
selected = accent border and glow), list rows, the selection's bar, a sequence's photos and the photo viewer. */
.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.toolbar .input.small { height: 32px; max-width: 200px; }
.toolbar select.active { border-color: var(--accent); color: var(--accent); }
.seq-items { min-width: 0; }
.seq-items.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(220px, 100%), 1fr)); gap: 16px; padding: 16px; }
.seq-items > .empty { grid-column: 1 / -1; }
/* Shift+click picks a range: it selects no text. */
.seq-card, .seq-row, .frame { position: relative; cursor: pointer; outline: none; user-select: none; }
.seq-card { display: flex; flex-direction: column; min-width: 0; background: var(--card); border: 1px solid var(--stroke); border-radius: var(--radius-card); overflow: hidden; }
.seq-card:hover { border-color: var(--stroke-strong); }
.seq-card:focus-visible, .seq-row:focus-visible, .frame:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.seq-card[aria-selected="true"], .frame[aria-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-selected); }
.thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: var(--card-pressed); overflow: hidden; }
.thumb .placeholder { position: absolute; inset: 0; display: grid; place-items: center; color: var(--text-faint); }
.thumb .placeholder svg { width: 28px; height: 28px; }
.thumb img { position: relative; display: block; width: 100%; height: 100%; object-fit: cover; }
.thumb img.failed { visibility: hidden; }
.seq-check { position: absolute; top: 8px; inset-inline-start: 8px; width: 18px; height: 18px; z-index: 1; opacity: 0; cursor: pointer; }
.seq-card:hover .seq-check, .seq-card:focus-visible .seq-check, .frame:hover .seq-check, .frame:focus-visible .seq-check,
.selecting .seq-check, [aria-selected="true"] > .seq-check { opacity: 1; }
.seq-card .count { position: absolute; top: 8px; inset-inline-end: 8px; padding: 0 6px; border-radius: 8px; background: var(--on-photo); color: #fff; font-size: 11px; }
.seq-card .info { display: flex; flex-direction: column; gap: 4px; padding: 8px 10px 10px; min-width: 0; }
.seq-card .facts { font-size: 12px; color: var(--text-muted); }
.chips-row { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 11px; color: var(--text-muted); }
.st { white-space: nowrap; }
.st.ok { color: var(--success); }
.st.off { color: var(--text-faint); }
.st.warn { color: var(--warning); }
.st.err { color: var(--error); }
/* List: the rows are one grid's subgrids, so every column fits its widest cell (as .table). */
.seq-items.rows { display: grid; grid-template-columns: max-content 64px minmax(160px, 2fr) minmax(80px, 1fr) max-content max-content max-content; column-gap: 12px; }
.seq-items.rows > .seq-head, .seq-items.rows > .seq-row { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; padding: 0 18px; }
.seq-items.rows > .seq-head { font-size: 11px; color: var(--text-muted); padding-block: 10px; border-bottom: 1px solid var(--stroke); white-space: nowrap; }
.seq-items.rows > .empty { grid-column: 1 / -1; }
.seq-row { min-height: 52px; border-bottom: 1px solid var(--stroke); }
.seq-row:hover { background: var(--card-hover); }
.seq-row[aria-selected="true"] { background: var(--accent-selected); }
.seq-row .seq-check { position: static; opacity: 1; }
.seq-row .thumb { width: 64px; border-radius: 4px; }
.seq-row .thumb .placeholder svg { width: 16px; height: 16px; }
@media (max-width: 900px) {
.seq-items.rows { grid-template-columns: max-content 64px minmax(120px, 1fr) max-content; }
.seq-items.rows .col-camera, .seq-items.rows .col-size, .seq-items.rows .col-date { display: none; }
}
/* The selection's actions stay in view at the foot of the window while the list scrolls. */
.mass-bar { position: sticky; bottom: 16px; z-index: 4; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 12px;
background: var(--surface); border: 1px solid var(--accent); border-radius: var(--radius-card); box-shadow: 0 4px 16px var(--shadow); }
/* A sequence: cover, editable fields and facts side by side, stacked on narrow screens. */
.seq-detail { grid-template-columns: minmax(180px, 280px) minmax(0, 1fr) minmax(220px, 320px); gap: 20px; align-items: start; }
.seq-cover .thumb { border-radius: var(--radius); }
.input.heading { height: 38px; font-size: 18px; font-weight: 600; border-color: transparent; background: transparent; padding-inline: 8px; margin-inline-start: -8px; }
.input.heading:hover { border-color: var(--stroke); }
.input.heading:focus { background: var(--card); }
textarea.input.notes { height: auto; min-height: 64px; padding: 6px 10px; resize: vertical; font: inherit; }
.tag-editor { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
.tag-list { display: contents; }
.tag { display: inline-flex; align-items: center; gap: 2px; height: 24px; padding-inline: 10px 2px; border: 1px solid var(--stroke); border-radius: 12px; background: var(--card); color: var(--text); font-size: 12px; }
.tag-editor .input.small { width: 140px; }
.btn.tiny { width: 20px; min-width: 20px; height: 20px; border-radius: 10px; }
.btn.tiny svg { width: 12px; height: 12px; }
.stars { display: flex; gap: 2px; }
.btn.star { color: var(--text-faint); }
.btn.star[aria-pressed="true"] { color: var(--sun); border-color: transparent; box-shadow: none; }
.seq-facts, .viewer-meta { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 14px; margin: 0; font-size: 12px; }
.seq-facts > div, .viewer-meta > div { display: contents; }
.seq-facts dt, .viewer-meta dt { color: var(--text-muted); }
.seq-facts dd, .viewer-meta dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
.panel-head.wrap { flex-wrap: wrap; }
.frame-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 8px; padding: 12px 18px; }
.frame-grid > .frame-empty { grid-column: 1 / -1; }
/* Thousands of photos: the browser lays out and paints only those near the view. */
.frame { content-visibility: auto; contain-intrinsic-size: auto 90px; border: 1px solid var(--stroke); border-radius: var(--radius); overflow: hidden; background: var(--card); }
.frame .thumb { aspect-ratio: 3 / 2; }
.frame-no { position: absolute; bottom: 4px; inset-inline-end: 4px; padding: 0 5px; border-radius: 6px; background: var(--on-photo); color: #fff; font-size: 10px; }
.frame-badge { position: absolute; top: 4px; inset-inline-end: 4px; display: grid; place-items: center; width: 22px; height: 22px; border-radius: 11px; background: var(--on-photo); color: #fff; }
.frame-badge.hero { color: var(--sun); }
.frame-badge.warn { top: auto; bottom: 4px; inset-inline: 4px auto; color: var(--warning); }
.table.renders { grid-template-columns: minmax(100px, 1.4fr) max-content max-content max-content max-content max-content; }
.table.trash { grid-template-columns: max-content minmax(140px, 2fr) max-content max-content minmax(60px, 1fr) max-content max-content; }
.table.trash.fit-1 { grid-template-columns: max-content minmax(120px, 2fr) max-content max-content max-content max-content; }
.table.trash.fit-1 .col-by { display: none; }
dialog.viewer { width: min(1100px, calc(100vw - 32px)); padding: 16px 18px; }
dialog.viewer[open] { display: grid; grid-template-columns: minmax(0, 1fr) 240px; grid-template-rows: auto minmax(0, 1fr) auto; gap: 12px 16px; }
.viewer-head { grid-column: 1 / -1; display: flex; align-items: center; gap: 10px; min-width: 0; }
.viewer-stage { position: relative; display: grid; place-items: center; min-height: 240px; max-height: 72vh; background: #000; border-radius: var(--radius); overflow: hidden; }
.viewer-stage img { max-width: 100%; max-height: 72vh; object-fit: contain; display: block; }
.viewer-stage img.failed { display: none; }
.viewer-stage .placeholder { position: absolute; color: var(--text-faint); }
.viewer-stage img:not(.failed) + .placeholder { display: none; }
.viewer-meta { align-content: start; }
dialog.viewer .buttons { grid-column: 1 / -1; }
@media (max-width: 900px) {
.seq-detail { grid-template-columns: minmax(0, 1fr); }
dialog.viewer[open] { grid-template-columns: minmax(0, 1fr); }
}
@media (forced-colors: active) {
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
}
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
.about { scroll-margin-block-start: 84px; }
.about h2:focus { outline: none; }
+12 -4
View File
@@ -17,14 +17,20 @@ function csrfToken() {
return m ? decodeURIComponent(m[1]) : "";
}
async function request(method, url, body) {
/**
* One API call. The body is JSON (any value), raw bytes (a Blob, sent as application/octet-stream) or nothing. A call
* aborted through signal rejects with the browser's AbortError, which callers tell apart from an ApiFailure.
*/
async function request(method, url, body, signal) {
const headers = { Accept: "application/json", "Accept-Language": culture() };
if (body !== undefined) headers["Content-Type"] = "application/json";
const raw = body instanceof Blob;
if (body !== undefined) headers["Content-Type"] = raw ? "application/octet-stream" : "application/json";
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
let res;
try {
res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
} catch {
res = await fetch(url, { method, headers, credentials: "same-origin", signal, body: body === undefined ? undefined : raw ? body : JSON.stringify(body) });
} catch (err) {
if (err?.name === "AbortError") throw err;
throw new ApiFailure(0, "unreachable", "");
}
if (res.status === 401 && url !== "/api/v1/auth/login") {
@@ -49,6 +55,8 @@ export const api = {
put: (url, body) => request("PUT", url, body),
patch: (url, body) => request("PATCH", url, body),
del: (url) => request("DELETE", url),
/** PUT of raw bytes (an upload chunk) with the session's CSRF header, like every other call; abortable through signal. */
putBytes: (url, blob, signal) => request("PUT", url, blob, signal),
user: () => currentUser,
/** Restores the session from the cookie; null when signed out. */
+3 -2
View File
@@ -5,8 +5,9 @@ import { icons } from "./icons.js";
import { escapeHtml, attr, errorText, nativeName, formatNumber, fitColumns } from "./ui.js";
const app = document.getElementById("app");
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2).
const topPages = ["dashboard", "users", "archive", "jobs", "logs"];
// The menu: its pages from the top, then the ones docked at its foot above the account (owner review 2). The Library
// manages sequences and photos without editing them (owner review 2, R6).
const topPages = ["dashboard", "library", "users", "archive", "jobs", "logs"];
const bottomPages = ["settings"];
const pages = [...topPages, ...bottomPages];
/** Routes of old bookmarks and where they open now: About is the last group of Settings (owner review 2). */
+13
View File
@@ -61,6 +61,19 @@ export function detailText(entry) {
const shown = [scheduleNameIn(parts), scheduleAction(action), recurrence ? recurrenceText(recurrence) : code];
return (off ? [...shown, t("Admin.Schedules.Off")] : shown).join(" · ");
}
// Owner review 2, R6: "3 · photos-<entry>", "<entry> · Harbour sunset", "2 · 1048576 · <entries>".
case "frames_deleted": {
const [count] = details.split(" · ");
return /^\d+$/.test(count) ? plural("Admin.Dashboard.PhotoCount", Number(count)) : details;
}
case "trash_restored": {
const [, ...title] = details.split(" · ");
return title.length > 0 ? title.join(" · ") : details;
}
case "trash_emptied": {
const [count, size] = details.split(" · ");
return /^\d+$/.test(count) && /^\d+$/.test(size ?? "") ? `${plural("Admin.Trash.EntryCount", Number(count))} · ${formatBytes(Number(size))}` : details;
}
default:
return details;
}
+17 -2
View File
@@ -1,11 +1,13 @@
// Generated by branding/ui-icons/icons.py (same 16-px set as the desktop apps). Do not edit by hand.
// Glyphs that point along the reading direction carry class="directional" (mirrored in right-to-left pages, admin.css).
export const icons = {
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
library: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
jobs: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M7.15 3.48 L7.4 1.53 A6.5 6.5 0 0 1 8.6 1.53 L8.85 3.48 A4.6 4.6 0 0 1 10.6 4.2 L12.15 3 A6.5 6.5 0 0 1 13 3.85 L11.8 5.4 A4.6 4.6 0 0 1 12.52 7.15 L14.47 7.4 A6.5 6.5 0 0 1 14.47 8.6 L12.52 8.85 A4.6 4.6 0 0 1 11.8 10.6 L13 12.15 A6.5 6.5 0 0 1 12.15 13 L10.6 11.8 A4.6 4.6 0 0 1 8.85 12.52 L8.6 14.47 A6.5 6.5 0 0 1 7.4 14.47 L7.15 12.52 A4.6 4.6 0 0 1 5.4 11.8 L3.85 13 A6.5 6.5 0 0 1 3 12.15 L4.2 10.6 A4.6 4.6 0 0 1 3.48 8.85 L1.53 8.6 A6.5 6.5 0 0 1 1.53 7.4 L3.48 7.15 A4.6 4.6 0 0 1 4.2 5.4 L3 3.85 A6.5 6.5 0 0 1 3.85 3 L5.4 4.2 A4.6 4.6 0 0 1 7.15 3.48 Z M6.3 8 A1.7 1.7 0 1 0 9.7 8 A1.7 1.7 0 1 0 6.3 8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
logs: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
menu: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M2.5 8 H13.5 M2.5 12 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
@@ -14,4 +16,17 @@ export const icons = {
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
copy: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6.5 5 H13.0 A1.5 1.5 0 0 1 14.5 6.5 V13.0 A1.5 1.5 0 0 1 13.0 14.5 H6.5 A1.5 1.5 0 0 1 5 13.0 V6.5 A1.5 1.5 0 0 1 6.5 5 Z M11 5 V2.5 A1 1 0 0 0 10 1.5 H2.5 A1 1 0 0 0 1.5 2.5 V10 A1 1 0 0 0 2.5 11 H5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
grid: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
list: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.5 4 H13.5 M5.5 8 H13.5 M5.5 12 H13.5 M2.5 4 H2.6 M2.5 8 H2.6 M2.5 12 H2.6" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
trash: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 4 H13.5 M6 4 V2.5 H10 V4 M3.8 4 L4.6 14 H11.4 L12.2 4 M6.6 6.8 V11.2 M9.4 6.8 V11.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
upload: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 10.5 V2.5 M4.5 6 L8 2.5 L11.5 6 M2.5 13.5 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
download: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 2 V10 M4.5 6.5 L8 10 L11.5 6.5 M2.5 13.5 H13.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
back: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M13 8 H3 M7 4 L3 8 L7 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
previous: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10 4 L6 8 L10 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
next: `<svg class="directional" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M6 4 L10 8 L6 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
star: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
starFilled: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L9.9 5.8 L14.2 6.3 L11 9.3 L11.9 13.6 L8 11.4 L4.1 13.6 L5 9.3 L1.8 6.3 L6.1 5.8 Z" fill="currentColor"/></svg>`,
hero: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 4.8 L8.9 6.9 L11.1 7.1 L9.4 8.5 L9.9 10.7 L8 9.5 L6.1 10.7 L6.6 8.5 L4.9 7.1 L7.1 6.9 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
image: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.600000000000001 5.6 A1.2 1.2 0 1 0 12.0 5.6 A1.2 1.2 0 1 0 9.600000000000001 5.6 Z" fill="currentColor"/><path d="M3.0 2.5 H13.0 A1.5 1.5 0 0 1 14.5 4.0 V12.0 A1.5 1.5 0 0 1 13.0 13.5 H3.0 A1.5 1.5 0 0 1 1.5 12.0 V4.0 A1.5 1.5 0 0 1 3.0 2.5 Z M1.5 11 L5.5 7 L9 10.5 L11 8.5 L14.5 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
warning: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 L14.8 13.8 H1.2 Z M8 6.2 V9.6 M8 11.7 V11.8" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
};
@@ -1,4 +1,5 @@
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics.
// Archive (BRIEF §14.8): naming templates, proxy policy, scan/rebuild/verify/maintenance, statistics, and the way to the
// archive's trash (the Library's trash view, owner review 2, R6).
import { t, plural, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, bar, storageTip, writeVolumeLine, columns, toast, errorText, emptyState, markInvalid, clearInvalid, invalidText, escapeReverts } from "../ui.js";
@@ -46,7 +47,8 @@ export async function render(root, { api, setMeta }) {
</form>
<section class="panel" aria-labelledby="maintenance-title">
<h2 id="maintenance-title" data-i18n="Admin.Archive.Maintenance"></h2>
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}</div>
<div class="button-row">${ACTIONS.map((a) => `<button class="btn" data-action="${a}" data-i18n="Admin.Archive.${cap(a)}" data-i18n-title="Admin.Archive.${cap(a)}.Tip"></button>`).join("")}
<a class="btn" href="#/library?view=trash" data-i18n="Admin.Archive.Trash" data-i18n-title="Admin.Archive.Trash.Tip"></a></div>
<h2 id="cameras-title" data-i18n="Admin.Archive.ByCamera"></h2>
${statsTable(stats.byCamera.slice(0, 8).map((c) => ({ label: c.key || "—", count: c.count, bytes: c.bytes })), "cameras-title")
|| `<p class="muted" data-i18n="Admin.Dashboard.NoData"></p>`}
@@ -0,0 +1,555 @@
// 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).
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 } from "./library/shared.js";
import { renderSequence } from "./library/sequence.js";
import { renderTrash } from "./library/trash.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: 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); the selection and the keyboard place stay. */
async function refreshVisible() {
const mine = ++generation;
try {
const [page, f] = await Promise.all([
api.get(listQuery(Math.min(Math.max(rows.length, PAGE), BULK_LIMIT), null)),
api.get("/api/v1/sequences/facets").catch(() => facets),
]);
if (mine !== generation || !root.isConnected) return;
total = page.total ?? total;
facets = f;
drawFilters();
rows = page.items;
cursor = page.nextCursor;
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");
const filtered = FILTERS.some((f) => f !== "sort" && filters[f]);
itemsHost.innerHTML = filtered
? 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-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();
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);
}
async function queueJobs(kind) {
let queued = 0;
let skipped = 0;
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) {
toast(errorText(err), true);
return;
}
toast([queued > 0 ? t("Admin.Library.JobQueued") : t("Admin.Library.NothingQueued"), skipped > 0 ? plural("Admin.Library.Skipped", skipped) : ""]
.filter(Boolean).join(" · "));
}
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(" ");
const confirmed = await confirmDialog({
title: plural("Admin.Library.DeleteTitle", going.length),
body,
list: [...going.map((i) => titles.get(i.id) ?? i.id), ...blocked.map((i) => t("Admin.Library.BlockedItem", titles.get(i.id) ?? i.id, i.message ?? i.reason))],
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);
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" && (e.state === "done" || e.state === "failed")) 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("");
}
@@ -0,0 +1,569 @@
// 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, the originals and the renders
// to download. Nothing here edits the video: its settings 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, Selection, selectableGrid, tagList, coverUrl } from "./shared.js";
const FRAME_PAGE = 500;
/** Deleting more photos than this asks for their number to be typed. */
const TYPED_ABOVE = 20;
/** Names a delete dialog lists; the count in its title says how many there are in all. */
const LISTED = 500;
/** 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 = [];
let generation = 0;
let timer = 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="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 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);
}
const tags = root.querySelector("#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");
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: names.length > LISTED ? [...names.slice(0, 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;
}
async function loadRenders() {
try {
renders = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/renders`);
} catch {
renders = [];
}
const host = root.querySelector("#renders");
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. */
async function reload(withFrames) {
const before = seq.framesVersion;
const hero = seq.heroFrameId;
await reloadSequence();
if (!root.isConnected || leaving) return;
drawHeader();
if (withFrames || seq.framesVersion !== before) await reloadFrames();
else if (seq.heroFrameId !== hero) drawFrames();
await loadRenders();
}
function gone() {
if (leaving) return;
leaving = true;
toast(t("Admin.Sequence.Gone"), true);
location.hash = back;
}
onEvent((e) => {
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}`;
}
@@ -0,0 +1,283 @@
// What the Library's views share (owner review 2, R6): sequence facts and status chips as the desktop cards show them,
// 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;
/**
* 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) =>
`<span class="st ${cls}" title="${attr(t(tipKey))}"><span aria-hidden="true">${glyph}</span> ${escapeHtml(text ?? t(key))}</span>`;
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 `<span class="thumb ${cls}"><span class="placeholder" aria-hidden="true">${icons.image}</span>` +
`<img loading="lazy" decoding="async" alt="" src="${attr(src)}" data-fallback></span>`;
}
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 });
});
}
/** 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")}`;
}
@@ -0,0 +1,156 @@
// The archive's trash on the panel (owner review 2, R6; #/library?view=trash, reached from the Library and the Archive):
// deleted sequences and photos deleted from sequences, each restorable; emptying it is the panel's only erase of user
// files, so it measures the trash first (dry run), names what goes, asks for the word "empty" to be typed and sends the
// plan's fingerprint, which the server's job checks again before it erases anything.
import { t, plural, applyStrings } from "../../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatDateTime, toast, errorText, confirmDialog, emptyState, redraw, fitColumns } from "../../ui.js";
import { icons } from "../../icons.js";
export async function renderTrash(root, { api, setMeta, actions, onEvent }, { back }) {
let entries = [];
let bytes = 0;
/** The empty-trash job this page queued, followed until it ends. */
let emptyJob = null;
let timer = null;
actions.innerHTML = `
<a class="btn" href="${attr(back)}" data-i18n-title="Admin.Trash.Back.Tip">${icons.back}<span data-i18n="Admin.Trash.Back"></span></a>
<button class="btn destructive" id="empty" data-i18n="Admin.Trash.Empty" data-i18n-title="Admin.Trash.Empty.Tip"></button>`;
applyStrings(actions);
const emptyButton = actions.querySelector("#empty");
emptyButton.addEventListener("click", emptyTrash);
root.innerHTML = `
<section class="panel flush" aria-labelledby="trash-title">
<div class="panel-head padded"><h2 id="trash-title" data-i18n="Admin.Trash.Title"></h2><span class="muted ellipsis" id="trash-meta"></span></div>
<div class="table trash" data-levels="1" role="table" aria-labelledby="trash-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Trash.Kind"></span><span role="columnheader" data-i18n="Admin.Trash.Sequence"></span>
<span role="columnheader" class="end" data-i18n="Admin.Trash.Photos"></span><span role="columnheader" class="end" data-i18n="Admin.Trash.Size"></span>
<span role="columnheader" class="col-by" data-i18n="Admin.Trash.DeletedBy"></span><span role="columnheader" data-i18n="Admin.Trash.DeletedAt"></span>
<span role="columnheader"><span class="sr-only" data-i18n="Admin.Common.Actions"></span></span></div>
<div id="rows" role="rowgroup"></div>
</div>
</section>`;
applyStrings(root);
const table = root.querySelector(".table");
async function load() {
try {
const list = await api.get("/api/v1/archive/trash");
entries = list.entries;
bytes = list.bytes;
} catch (err) {
toast(errorText(err), true);
return;
}
if (!root.isConnected) return;
const summary = entries.length === 0 ? "" : `${plural("Admin.Trash.EntryCount", entries.length)} · ${formatBytes(bytes)}`;
setMeta(t("Admin.Trash.Title"));
root.querySelector("#trash-meta").textContent = summary;
emptyButton.disabled = entries.length === 0 || emptyJob !== null;
emptyButton.title = t(entries.length === 0 ? "Admin.Trash.NothingToEmpty.Tip" : emptyJob ? "Admin.Trash.Emptying.Tip" : "Admin.Trash.Empty.Tip");
draw();
}
function draw() {
const host = root.querySelector("#rows");
redraw(host, () => {
host.innerHTML = entries.map((e) => `
<div class="row" role="row" data-key="${attr(e.name)}">
<span class="nowrap" role="cell">${escapeHtml(kindLabel(e.kind))}</span>
<span class="stack" role="cell"><strong class="ellipsis" dir="auto" title="${attr(e.title)}">${escapeHtml(e.title)}</strong>
<small dir="ltr" class="mono" title="${attr(e.folder)}">${escapeHtml(e.folder)}</small></span>
<span class="num end" role="cell">${formatNumber(e.photos)}</span>
<span class="num end nowrap" role="cell">${escapeHtml(formatBytes(e.bytes))}</span>
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
<span class="row-actions" role="cell"><button class="btn small" data-restore="${attr(e.name)}" data-i18n="Admin.Trash.Restore"
data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}"></button></span>
</div>`).join("")
|| `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Trash.IsEmpty",
`<a class="btn small" href="${attr(back)}" data-i18n="Admin.Trash.Back" data-i18n-title="Admin.Trash.Back.Tip"></a>`)}</div></div>`;
applyStrings(host);
});
host.querySelectorAll("[data-restore]").forEach((b) => b.addEventListener("click", () => restore(entries.find((e) => e.name === b.dataset.restore), b)));
fitColumns(table);
}
async function restore(entry, button) {
if (!entry) return;
button.disabled = true;
let result;
try {
result = await api.post(`/api/v1/archive/trash/${encodeURIComponent(entry.name)}/restore`);
} catch (err) {
toast(errorText(err), true);
if (button.isConnected) button.disabled = false;
return;
}
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
: result.newSequence ? plural("Admin.Trash.RestoredNew", result.photos) : plural("Admin.Trash.RestoredPhotos", result.photos, entry.title)];
if (result.kept.length > 0) lines.push(plural("Admin.Trash.Kept", result.kept.length));
toast(lines.join(" "), result.kept.length > 0);
await load();
}
/** Measure (dry run), name what goes, have "empty" typed, then queue the erase with the plan's fingerprint. */
async function emptyTrash() {
emptyButton.disabled = true;
try {
let plan;
try {
plan = await api.post("/api/v1/archive/trash/empty", { names: null, dryRun: true, fingerprint: null });
} catch (err) {
toast(errorText(err), true);
return;
}
if (plan.entries.length === 0) {
toast(t("Admin.Trash.IsEmpty"));
await load();
return;
}
const confirmed = await confirmDialog({
title: t("Admin.Trash.EmptyTitle"),
body: [plural("Admin.Trash.EmptyBody", plan.files, formatBytes(plan.bytes)), t("Admin.Trash.EmptyFinal")].join(" "),
list: plan.entries.map((e) => t("Admin.Trash.PlanItem", kindLabel(e.kind), e.title, formatBytes(e.bytes))),
confirm: t("Admin.Trash.EmptyConfirm"),
confirmTip: t("Admin.Trash.EmptyConfirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: t("Admin.Trash.EmptyWord"),
typedKind: "word",
});
if (!confirmed) return;
try {
const job = await api.post("/api/v1/archive/trash/empty", { names: null, dryRun: false, fingerprint: plan.fingerprint });
emptyJob = job.id;
toast(t("Admin.Trash.EmptyQueued"));
} catch (err) {
// trash_changed: something entered or left the trash since it was measured; it is shown as it is now.
toast(errorText(err), true);
}
} finally {
await load();
}
}
onEvent((e) => {
if (e.type === "jobState" && e.jobId === emptyJob && (e.state === "done" || e.state === "failed" || e.state === "cancelled")) {
emptyJob = null;
if (e.state === "done") toast(t("Admin.Trash.Emptied"));
else toast(e.error || t("Admin.Trash.EmptyFailed"), true);
load();
} else if (e.type === "sequenceChanged") {
// A deletion or a restore elsewhere changes what the trash holds.
clearTimeout(timer);
timer = setTimeout(() => {
if (root.isConnected) load();
}, 800);
}
});
await load();
}
function kindLabel(kind) {
return t(kind === "sequence" ? "Admin.Trash.Kind.Sequence" : kind === "replaced" ? "Admin.Trash.Kind.Replaced" : "Admin.Trash.Kind.Photos");
}
+69 -8
View File
@@ -1,5 +1,5 @@
// Small DOM and formatting helpers shared by the admin pages. No inline styles: the panel runs under a strict CSP.
import { t, culture } from "./i18n.js";
import { t, culture, applyStrings } from "./i18n.js";
export function escapeHtml(s) {
return String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
@@ -145,33 +145,53 @@ export function toast(message, isError = false) {
let dialogs = 0;
/** What a typed confirmation asks for: its field's tooltip, the confirm button's while it waits, and how a value matches. */
const TYPED = {
// A name (an account), exactly as shown.
name: { tip: "Admin.Common.TypeToConfirm.Tip", first: "Admin.Common.TypeFirst.Tip", matches: (value, typed) => value === typed },
// A word of the interface (the localised "empty"), whatever its case.
word: { tip: "Admin.Common.TypeWord.Tip", first: "Admin.Common.TypeWordFirst.Tip",
matches: (value, typed) => value.trim().toLocaleLowerCase() === typed.toLocaleLowerCase() },
// A count (the photos a deletion moves), its digits whatever the separators typed between them.
count: { tip: "Admin.Common.TypeCount.Tip", first: "Admin.Common.TypeCountFirst.Tip",
matches: (value, typed) => value.replace(/[\s.,'’  ]/g, "") === typed },
};
/**
* Two-button confirmation dialog (safe action left and default, Esc keeps). Resolves true when the destructive action
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field.
* is chosen; with `typed`, that button stays disabled until the text is typed into the labelled field, as `typedKind`
* says: a name exactly, a word whatever its case, or a count. `list` adds the items the action concerns (titles,
* entries) under the body, in a scrolling box; user text, so each keeps its own direction.
*/
export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancelTip, typed }) {
export function confirmDialog({ title, body, list, confirm, confirmTip, cancel, cancelTip, typed, typedKind = "name" }) {
return new Promise((resolve) => {
const id = `dialog-${++dialogs}`;
const dialog = document.createElement("dialog");
dialog.className = "dialog";
dialog.setAttribute("aria-labelledby", `${id}-title`);
if (body) dialog.setAttribute("aria-describedby", `${id}-body`);
const kind = TYPED[typedKind] ?? TYPED.name;
const firstTip = t(kind.first);
const matches = (value) => kind.matches(value, String(typed));
// The text to type stands out of its sentence, and keeps its own direction.
const typedLabel = typed ? escapeHtml(t("Admin.Common.TypeToConfirm", "\u0001")).replace("\u0001", `<strong dir="auto">${escapeHtml(typed)}</strong>`) : "";
dialog.innerHTML = `
<form method="dialog">
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${body ? `<p id="${id}-body">${escapeHtml(body)}</p>` : ""}
${typed ? `<label class="field-label"><span>${escapeHtml(t("Admin.Common.TypeToConfirm", typed))}</span>
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" title="${attr(t("Admin.Common.TypeToConfirm.Tip"))}"></label>` : ""}
${list?.length ? `<ul class="dialog-list" tabindex="0" aria-label="${attr(title)}">${list.map((item) => `<li dir="auto">${escapeHtml(item)}</li>`).join("")}</ul>` : ""}
${typed ? `<label class="field-label"><span>${typedLabel}</span>
<input class="input" name="typed" autocomplete="off" spellcheck="false" dir="auto" ${typedKind === "count" ? 'inputmode="numeric"' : ""} title="${attr(t(kind.tip))}"></label>` : ""}
<div class="buttons">
<button class="btn" value="cancel" title="${attr(cancelTip)}" autofocus>${escapeHtml(cancel)}</button>
<button class="btn destructive" value="ok" title="${attr(typed ? t("Admin.Common.TypeFirst.Tip") : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
<button class="btn destructive" value="ok" title="${attr(typed ? firstTip : confirmTip)}" ${typed ? "disabled" : ""}>${escapeHtml(confirm)}</button>
</div>
</form>`;
document.body.appendChild(dialog);
const ok = dialog.querySelector('button[value="ok"]');
dialog.querySelector('input[name="typed"]')?.addEventListener("input", (e) => {
ok.disabled = e.target.value !== typed;
ok.title = ok.disabled ? t("Admin.Common.TypeFirst.Tip") : confirmTip;
ok.disabled = !matches(e.target.value);
ok.title = ok.disabled ? firstTip : confirmTip;
});
dialog.addEventListener("close", () => {
resolve(dialog.returnValue === "ok");
@@ -181,6 +201,47 @@ export function confirmDialog({ title, body, confirm, confirmTip, cancel, cancel
});
}
/**
* A dialog of form fields (fields: HTML whose data-i18n attributes are filled here) with the action on the right, which
* Enter in a field chooses too; Esc or the safe button cancels. Resolves the FormData once confirmed, null when cancelled.
* check(form) may refuse the values: it marks the field (markInvalid) and returns false, and the dialog stays open.
*/
export function formDialog({ title, fields, confirm, confirmTip, cancel, cancelTip, check }) {
return new Promise((resolve) => {
const id = `dialog-${++dialogs}`;
const dialog = document.createElement("dialog");
dialog.className = "dialog";
dialog.setAttribute("aria-labelledby", `${id}-title`);
dialog.innerHTML = `
<form method="dialog" class="form" novalidate>
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
${fields}
<div class="buttons">
<button class="btn" type="button" value="cancel" title="${attr(cancelTip)}">${escapeHtml(cancel)}</button>
<button class="btn primary" value="ok" title="${attr(confirmTip)}">${escapeHtml(confirm)}</button>
</div>
</form>`;
applyStrings(dialog);
document.body.appendChild(dialog);
const form = dialog.querySelector("form");
let result = null;
form.addEventListener("submit", (e) => {
if (check && !check(form)) {
e.preventDefault();
return;
}
result = new FormData(form);
});
dialog.querySelector('button[value="cancel"]').addEventListener("click", () => dialog.close());
dialog.addEventListener("close", () => {
resolve(result);
dialog.remove();
});
dialog.showModal();
form.querySelector("input, select, textarea")?.focus();
});
}
/** The localised message of an API failure, or the generic one when the server was not reached. */
export function errorText(err) {
return err?.message && err.status ? err.message : t("Admin.Error.Unreachable");
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Chronos.Core.Archiving;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
@@ -38,6 +39,7 @@ public static class LibraryEndpoints
public static void Map(RouteGroupBuilder api)
{
var sequences = api.MapGroup("/sequences");
sequences.MapGet("/facets", FacetsAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/thumb", ThumbAsync).Requires(Permissions.Read);
sequences.MapPost("/{id:guid}/frames/delete", DeleteFramesAsync).Requires(Permissions.Delete);
sequences.MapPost("/bulk/delete", BulkDeleteAsync).Requires(Permissions.Delete);
@@ -49,6 +51,20 @@ public static class LibraryEndpoints
internal static ArchiveService Engine(ArchiveService? archives, ChronosDatabase db) =>
archives ?? new ArchiveService(db, new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, ImagesAfterScan = true });
/// <summary>
/// What the Library's filters offer (the panel's Year, Camera and Tag menus): the years of first capture, the camera
/// models and the tags of this archive's sequences, each with its count. A camera's label is the name the desktop
/// shows (<see cref="PathTemplate.CameraName"/>: brand and model, the brand once).
/// </summary>
private static async Task<IResult> FacetsAsync(HttpContext context, ChronosDatabase db, ServerArchive archive)
{
var facets = await db.Sequences.GetFacetsAsync(archive.Id, context.RequestAborted);
return Results.Json(new LibraryFacetsDto(
[.. facets.Years.Select(y => new FacetDto(y.Value, y.Sequences))],
[.. facets.Cameras.Select(c => new FacetDto(c.Value, c.Sequences, PathTemplate.CameraName(c.Make, c.Value)))],
[.. facets.Tags.Select(t => new FacetDto(t.Value, t.Sequences))]), ProtocolJson.Default.LibraryFacetsDto);
}
/// <summary>
/// The thumbnail of the sequence's hero frame, else of its first frame, streamed like <c>/frames/{id}/thumb</c> with an
/// ETag (304 when unchanged); 404 <c>not_found</c> (<c>thumbnail</c>) when the sequence has no frame or that thumbnail
+7 -1
View File
@@ -58,8 +58,13 @@ public static class SequenceEndpoints
.Requires(Permissions.Edit);
}
/// <summary>
/// One page of the library. Filters: <c>year</c>, <c>camera</c> (the exact model), <c>status</c> (flags, <c>-</c> for
/// cleared ones), <c>rendered</c> (<c>true</c>: with a render, <c>false</c>: without; the admin panel's Library), <c>tag</c>,
/// <c>q</c> (title, camera or tag), <c>owner</c> (<c>me</c> or an id); <c>sort</c>, <c>cursor</c>, <c>limit</c>.
/// </summary>
private static async Task<IResult> ListAsync(HttpContext context, ChronosDatabase db, ServerArchive archive, int? year, string? camera, string? status,
string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
bool? rendered, string? tag, string? q, string? owner, string? sort, string? cursor, int? limit, Caller caller)
{
if (!TryParseStatus(status, out var with, out var without)) return ApiErrors.BadRequest(context, "invalid_filter", "status");
if (!TryParseSort(sort, out var order)) return ApiErrors.BadRequest(context, "invalid_filter", "sort");
@@ -75,6 +80,7 @@ public static class SequenceEndpoints
Camera = string.IsNullOrWhiteSpace(camera) ? null : camera,
WithStatus = with,
WithoutStatus = without,
Rendered = rendered,
Tag = string.IsNullOrWhiteSpace(tag) ? null : tag,
Text = string.IsNullOrWhiteSpace(q) ? null : q,
OwnerUserId = ownerId,