diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ca94a3ca..534059ee 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -88,7 +88,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job), API errors, the WebSocket `EventHub` |
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step), render store; `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability |
-| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time) |
+| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files (`EmbeddedStaticFiles`: `no-cache` and a content ETag, so an upgrade never mixes old and new modules), Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection, grid keyboard and the retry of thumbnails a finished job may have built; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use, and sending the capture time `capture-time.js` reads: the Exif DateTimeOriginal of a JPEG or TIFF-based file, else the file's time; `reorganize.js` the Reorganize dialog of the Library's selection and of the Archive page's save toast: template switches and fields, a live dry run of `POST /archive/reorganize` one request at a time, Apply that sends the shown plan's fingerprint back) |
### 2.5 Hosts
diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx
index 3dfd7e8c..ff9dd9ae 100644
--- a/i18n/en/Admin.resx
+++ b/i18n/en/Admin.resx
@@ -9,6 +9,7 @@
Chronos ServerRunning forVersion
+ {0} reorganized the archive · {1}long{0} changed the archive layoutlong{0} deleted {1}long{0} started {1}long
@@ -343,6 +344,7 @@
Sign in to administer this serverUserYour user name on this server
+ Archive reorganizedArchive layoutPhotos deletedJob started
@@ -427,6 +429,57 @@
Change passwordReplace the password and continue to the panelChoose a new password
+ Reorganize…
+ Apply folder, file and title templates to the selected sequences; a preview shows every change first
+ After:
+ Apply…
+ Reorganize as the preview shows; a confirmation comes first
+ Before:
+ Write a template, or switch this part off.long
+ Close without changing anything
+ Carried
+ Moves only because a folder it is inside moves
+ Renamed files
+ Folder
+ Sequence
+ Reorganize
+ Queue the job that moves and renames the originals, each one verified; nothing is overwritten or deleted
+ {0} photo gets a new name.long
+ {0} photos get new names.long
+ {0} folder moves.long
+ {0} folders move.long
+ {0} sequence changes.long
+ {0} sequences change.long
+ Reorganize now?
+ Name of each photo as an import gives it, e.g. {date}_{time}_{n:0000}; the files beside a photo follow it
+ Files
+ Rename the photos of each sequence; off keeps every file name
+ {0} file renamedlong
+ {0} files renamedlong
+ Folder of each sequence in the archive, e.g. {year}/{date} {camera}; {title} is the new title
+ Folders
+ Move each sequence to the folder its template gives; off keeps every folder where it is
+ A selected sequence is no longer in the archive; close and select again.long
+ {0}: {1}long: a photo count, then why those photos keep their names
+ Switch on at least one part to change.long
+ Nothing to change: these sequences already follow the templates.long
+ Reorganize…
+ Apply the new templates to the sequences already in the archive; a preview shows every change first
+ Open job
+ Show the job and its log on the Jobs page
+ Planning…
+ Preview
+ What each sequence becomes, in the order the changes apply; nothing has changed yet
+ Reorganize queued.
+ This folder stays where it is
+ Reorganize {0} sequence
+ Reorganize {0} sequences
+ Reorganize all sequences
+ New title of each sequence, e.g. {date} {camera}; {title} is the current title
+ Titles
+ Give each sequence the title its template makes; off keeps every title
+ Reorganize takes at most {0} sequences at once, or every sequence: clear the filters and select all.long
+ Sequences changed: {0} · files renamed: {1} · names kept: {2}longAdministratorEditorUploader
diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx
index 59c94477..89c0ddaf 100644
--- a/i18n/it/Admin.it.resx
+++ b/i18n/it/Admin.it.resx
@@ -9,6 +9,7 @@
Chronos ServerIn esecuzione daVersione
+ {0} ha riorganizzato l'archivio · {1}{0} ha modificato l'organizzazione dell'archivio{0} ha eliminato {1}long{0} ha avviato {1}
@@ -343,6 +344,7 @@
Accedi per amministrare questo serverUtenteIl tuo nome utente su questo server
+ Archivio riorganizzatoOrganizzazione archivioFoto eliminateJob avviato
@@ -426,6 +428,57 @@
Cambia passwordSostituisci la password e continua nel pannelloScegli una nuova password
+ Riorganizza…
+ Applica modelli di cartelle, file e titoli alle sequenze selezionate; un'anteprima mostra prima ogni modifica
+ Dopo:
+ Applica…
+ Riorganizza come mostra l'anteprima; prima chiede conferma
+ Prima:
+ Scrivi un modello, o disattiva questa parte.
+ Chiudi senza cambiare niente
+ Trasportata
+ Si sposta solo perché si sposta una cartella che la contiene
+ File rinominati
+ Cartella
+ Sequenza
+ Riorganizza
+ Metti in coda il job che sposta e rinomina gli originali, verificandoli uno per uno; niente viene sovrascritto o eliminato
+ {0} foto riceve un nuovo nome.
+ {0} foto ricevono un nuovo nome.
+ Si sposta {0} cartella.
+ Si spostano {0} cartelle.
+ Cambia {0} sequenza.
+ Cambiano {0} sequenze.
+ Riorganizzare ora?
+ Nome di ogni foto come lo dà un'importazione, es. {date}_{time}_{n:0000}; i file accanto a una foto la seguono
+ File
+ Rinomina le foto di ogni sequenza; spento mantiene ogni nome di file
+ {0} file rinominato
+ {0} file rinominati
+ Cartella di ogni sequenza nell'archivio, es. {year}/{date} {camera}; {title} è il nuovo titolo
+ Cartelle
+ Sposta ogni sequenza nella cartella data dal modello; spento lascia ogni cartella dov'è
+ Una sequenza selezionata non è più nell'archivio; chiudi e seleziona di nuovo.
+ {0}: {1}
+ Attiva almeno una parte da cambiare.
+ Niente da cambiare: queste sequenze seguono già i modelli.
+ Riorganizza…
+ Applica i nuovi modelli alle sequenze già nell'archivio; un'anteprima mostra prima ogni modifica
+ Apri job
+ Mostra il job e il suo log nella pagina Job
+ Pianificazione…
+ Anteprima
+ Cosa diventa ogni sequenza, nell'ordine in cui si applicano le modifiche; ancora non è cambiato niente
+ Riorganizzazione in coda.
+ Questa cartella resta dov'è
+ Riorganizza {0} sequenza
+ Riorganizza {0} sequenze
+ Riorganizza tutte le sequenze
+ Nuovo titolo di ogni sequenza, es. {date} {camera}; {title} è il titolo attuale
+ Titoli
+ Dai a ogni sequenza il titolo fatto dal modello; spento mantiene ogni titolo
+ Riorganizza al massimo {0} sequenze alla volta, o tutte: togli i filtri e seleziona tutto.
+ Sequenze cambiate: {0} · file rinominati: {1} · nomi mantenuti: {2}AmministratoreEditorCaricamento
diff --git a/src/Chronos.Server/Admin/web/admin.css b/src/Chronos.Server/Admin/web/admin.css
index e23338a1..2a5a8ac9 100644
--- a/src/Chronos.Server/Admin/web/admin.css
+++ b/src/Chronos.Server/Admin/web/admin.css
@@ -294,6 +294,10 @@ dialog.dialog p { margin: 0; color: var(--text-muted); }
#toasts { position: fixed; inset-inline-end: 24px; bottom: 24px; display: grid; gap: 8px; z-index: 10; }
.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); }
+/* A toast with an action (Open job, Reorganize…): the message, then its link or button at the inline end. */
+.toast.with-action { display: flex; align-items: center; gap: 12px; }
+.toast.with-action > span { flex: 1 1 auto; min-width: 0; }
+.toast.with-action > .btn { flex: none; }
/* 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); }
@@ -422,6 +426,35 @@ dialog.upload.dragging .drop { border-color: var(--accent); background: var(--ac
.upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; }
.upload-total .progress-cell { flex: 1 1 0; }
+/* Reorganize dialog (owner review 2, R7, reorganize.js): a switch and a field per template, the dry run's totals and its
+ steps (title, folder and renamed files, the old value struck through above the new one); paths stay left to right. */
+dialog.dialog.reorganize { width: 960px; }
+.reorg-fields { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 6px 14px; align-items: center; }
+.reorg-fields .field-error { grid-column: 2; color: var(--error); font-size: 12px; overflow-wrap: anywhere; }
+.reorg-fields .field-error:empty { display: none; }
+.reorg-totals { min-height: 18px; color: var(--text-muted); }
+.reorg-preview { max-height: 46vh; overflow: auto; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--bg); }
+.reorg-preview:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+.reorg-preview.stale .table { opacity: .55; }
+.table.reorg { grid-template-columns: minmax(120px, 1fr) minmax(160px, 1.3fr) minmax(160px, 1.3fr); font-size: 12px; }
+.table.reorg .thead { position: sticky; top: 0; z-index: 1; padding: 8px 12px; background: var(--bg); }
+.table.reorg .row { min-height: 0; padding: 8px 12px; align-items: start; }
+.table.reorg .row:hover { background: none; }
+.table.reorg .row:last-child { border-bottom: 0; }
+.table.reorg .pill { align-self: flex-start; margin-block-start: 4px; }
+.change { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.change .was { color: var(--text-muted); text-decoration: line-through; }
+.path { font-family: var(--mono); overflow-wrap: anywhere; }
+.reorg-samples, .reorg-kept { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 2px; }
+.reorg-samples { color: var(--text-muted); }
+.reorg-kept { color: var(--warning); }
+.reorg-preview .table-foot { padding: 8px 12px; border-top: 1px solid var(--stroke); }
+/* Narrow windows: each step's cells one under the other; the column names stay for screen readers. */
+@media (max-width: 700px) {
+ .table.reorg { grid-template-columns: minmax(0, 1fr); }
+ .table.reorg .thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
+}
+
/* 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; }
diff --git a/src/Chronos.Server/Admin/web/audit.js b/src/Chronos.Server/Admin/web/audit.js
index b803569e..f7b8d8fa 100644
--- a/src/Chronos.Server/Admin/web/audit.js
+++ b/src/Chronos.Server/Admin/web/audit.js
@@ -74,6 +74,12 @@ export function detailText(entry) {
const [count, size] = details.split(" · ");
return /^\d+$/.test(count) && /^\d+$/.test(size ?? "") ? `${plural("Admin.Trash.EntryCount", Number(count))} · ${formatBytes(Number(size))}` : details;
}
+ // Owner review 2, R7: "sequences · files · folder template · file template · title template", a template empty when kept.
+ case "archive_reorganized": {
+ const [sequences, files, ...templates] = details.split(" · ");
+ if (!/^\d+$/.test(sequences) || !/^\d+$/.test(files ?? "")) return details;
+ return [plural("Admin.Library.Count", Number(sequences)), plural("Admin.Reorganize.FilesRenamed", Number(files)), ...templates.filter(Boolean)].join(" · ");
+ }
default:
return details;
}
diff --git a/src/Chronos.Server/Admin/web/pages/archive.js b/src/Chronos.Server/Admin/web/pages/archive.js
index a85593ed..dcb77e65 100644
--- a/src/Chronos.Server/Admin/web/pages/archive.js
+++ b/src/Chronos.Server/Admin/web/pages/archive.js
@@ -1,7 +1,9 @@
// 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).
+// archive's trash (the Library's trash view, owner review 2, R6). New folder or file templates apply to new sequences; the
+// toast of their save offers Reorganize (R7) to apply them to the sequences already in the archive.
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";
+import { openReorganize } from "../reorganize.js";
const PROXY_SIZES = [-1, 1280, 1920, 2560, 3840, 0];
const ACTIONS = ["scan", "rebuild", "verify", "maintenance"];
@@ -71,6 +73,7 @@ export async function render(root, { api, setMeta }) {
e.preventDefault();
form.querySelectorAll("[aria-invalid]").forEach(clearInvalid);
const data = new FormData(form);
+ const before = settings;
try {
settings = await api.put("/api/v1/archive/settings", {
...settings,
@@ -86,7 +89,7 @@ export async function render(root, { api, setMeta }) {
form.querySelectorAll("option").forEach((option) => {
option.defaultSelected = option.selected;
});
- toast(t("Admin.Common.Saved"));
+ savedToast(before, settings);
} catch (err) {
// Errors name the field in details; the field gets the error border and the message as its tooltip.
const field = err.details && form.elements[err.details];
@@ -98,6 +101,28 @@ export async function render(root, { api, setMeta }) {
toast(message, true);
}
});
+ /**
+ * Saved; when the folder or file template changed and the archive has sequences, the toast offers Reorganize for all of
+ * them with the saved templates, the changed ones switched on.
+ */
+ function savedToast(before, saved) {
+ const changed = [["folder", "folderTemplate"], ["file", "fileTemplate"]].filter(([, field]) => before[field] !== saved[field]).map(([part]) => part);
+ if (changed.length === 0 || stats.sequences === 0) {
+ toast(t("Admin.Common.Saved"));
+ return;
+ }
+ toast(t("Admin.Common.Saved"), false, {
+ label: t("Admin.Reorganize.Offer"),
+ tip: t("Admin.Reorganize.Offer.Tip"),
+ run: () => openReorganize({
+ api,
+ target: { all: true },
+ templates: { folderTemplate: saved.folderTemplate, fileTemplate: saved.fileTemplate, titleTemplate: saved.titleTemplate ?? "" },
+ use: changed,
+ }),
+ });
+ }
+
root.querySelectorAll("[data-action]").forEach((button) => button.addEventListener("click", async () => {
button.disabled = true;
try {
diff --git a/src/Chronos.Server/Admin/web/pages/library.js b/src/Chronos.Server/Admin/web/pages/library.js
index 573b0286..1fccce80 100644
--- a/src/Chronos.Server/Admin/web/pages/library.js
+++ b/src/Chronos.Server/Admin/web/pages/library.js
@@ -1,12 +1,14 @@
// 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= opens one (library/sequence.js), #/library?view=trash the archive's trash (library/trash.js).
+// Reorganize (R7) applies new folder, file and title templates to the selection (reorganize.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, listed, JOB_ENDED } from "./library/shared.js";
import { renderSequence } from "./library/sequence.js";
import { renderTrash } from "./library/trash.js";
+import { openReorganize } from "../reorganize.js";
const VIEW_KEY = "chronos.admin.library.view";
const PAGE = 100;
@@ -256,8 +258,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
if (rows.length === 0) {
itemsHost.removeAttribute("role");
itemsHost.removeAttribute("aria-multiselectable");
- const filtered = FILTERS.some((f) => f !== "sort" && filters[f]);
- itemsHost.innerHTML = filtered
+ itemsHost.innerHTML = isFiltered()
? emptyState("Admin.Library.NoMatch", ``)
: emptyState("Admin.Library.Empty", ``);
applyStrings(itemsHost);
@@ -343,6 +344,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
${escapeHtml(plural("Admin.Library.Selected", selection.size))}${selectAll}
${JOBS.map(job).join("")}
+
@@ -362,6 +364,8 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
}
if (action === "all") return selectAll();
if (action === "csv") return exportCsv();
+ // A modal dialog: the button stays enabled, so the focus comes back to it when the dialog closes.
+ if (action === "reorganize") return reorganize();
button.disabled = true;
try {
if (action === "job") await queueJobs(button.dataset.kind);
@@ -415,6 +419,25 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
toast([done, skipped > 0 ? plural("Admin.Library.Skipped", skipped) : "", failure ?? ""].filter(Boolean).join(" · "), failure !== null);
}
+ /** Whether a filter narrows the list (the sort order does not). */
+ function isFiltered() {
+ return FILTERS.some((f) => f !== "sort" && filters[f]);
+ }
+
+ /**
+ * Reorganize (owner review 2, R7) of the selected sequences: every sequence of the archive after Select all without a
+ * filter, else their ids, at most a bulk request's thousand (one plan, one job).
+ */
+ async function reorganize() {
+ const everything = matching !== null && !isFiltered() && selection.size === matching.length;
+ if (!everything && selection.size > BULK_LIMIT) {
+ toast(t("Admin.Reorganize.TooMany", formatNumber(BULK_LIMIT)), true);
+ return;
+ }
+ const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
+ await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }, names });
+ }
+
async function retag() {
const datalist = facets.tags.map((f) => ``).join("");
const data = await formDialog({
diff --git a/src/Chronos.Server/Admin/web/reorganize.js b/src/Chronos.Server/Admin/web/reorganize.js
new file mode 100644
index 00000000..0b05e6a2
--- /dev/null
+++ b/src/Chronos.Server/Admin/web/reorganize.js
@@ -0,0 +1,365 @@
+// Reorganize dialog of the admin panel (owner review 2, R7; BRIEF §12.5, §14.8): folder, file and title templates applied
+// to sequences already in the archive, the Library's selection or every sequence. Each change of a template asks the
+// server for a dry run (nothing is touched) and the table shows what every sequence becomes, in the order the changes
+// apply. Apply confirms that very plan by its fingerprint, and the server runs it as a job (kind "move") that moves and
+// renames the originals, verified, never overwriting or deleting one.
+import { t, plural, applyStrings } from "./i18n.js";
+import { escapeHtml, attr, formatNumber, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js";
+
+const ENDPOINT = "/api/v1/archive/reorganize";
+/** Wait after the last keystroke before the dry run, and the steps the table draws at a time. */
+const PLAN_DELAY = 400;
+const PAGE = 200;
+/** The parts a Reorganize changes: the template's request field, its switch and its field, with their strings. */
+const PARTS = [
+ { key: "folder", field: "folderTemplate", label: "Admin.Reorganize.Folders", use: "Admin.Reorganize.Folders.Tip", tip: "Admin.Reorganize.FolderTemplate.Tip" },
+ { key: "file", field: "fileTemplate", label: "Admin.Reorganize.Files", use: "Admin.Reorganize.Files.Tip", tip: "Admin.Reorganize.FileTemplate.Tip" },
+ { key: "title", field: "titleTemplate", label: "Admin.Reorganize.Titles", use: "Admin.Reorganize.Titles.Tip", tip: "Admin.Reorganize.TitleTemplate.Tip" },
+];
+
+let dialogs = 0;
+
+/**
+ * Opens the Reorganize dialog. target is { all: true } (every sequence of the archive) or { sequenceIds } (at most a
+ * bulk request's thousand); names maps sequence ids to the titles the page shows. templates ({ folderTemplate,
+ * fileTemplate, titleTemplate }) fills the fields, else the archive's settings do; use lists the parts switched on
+ * ("folder", "file", "title"), else those with a template. Resolves when the dialog closes: the queued job, or null.
+ */
+export function openReorganize({ api, target, names = new Map(), templates = null, use = null } = {}) {
+ return new Promise((resolve) => {
+ const id = `reorganize-${++dialogs}`;
+ /** The last dry run, with key: the request it answers. */
+ let plan = null;
+ let shown = PAGE;
+ let timer = null;
+ let planning = false;
+ let again = false;
+ let loaded = false;
+ let busy = false;
+ let queued = null;
+ /** A message the next plan shows (why the plan was made again). */
+ let notice = "";
+ const title = target.all ? t("Admin.Reorganize.TitleAll") : plural("Admin.Reorganize.Title", target.sequenceIds.length);
+
+ const dialog = document.createElement("dialog");
+ dialog.className = "dialog reorganize";
+ dialog.setAttribute("aria-labelledby", `${id}-title`);
+ dialog.innerHTML = `
+ `;
+ document.body.appendChild(dialog);
+ applyStrings(dialog);
+ const form = dialog.querySelector("form");
+ const totals = dialog.querySelector(".reorg-totals");
+ const preview = dialog.querySelector(".reorg-preview");
+ const rows = dialog.querySelector(".reorg-rows");
+ const foot = dialog.querySelector(".table-foot");
+ const shownText = dialog.querySelector(".reorg-shown");
+ const errorLine = dialog.querySelector(".error");
+ const closeButton = dialog.querySelector('[data-act="close"]');
+ const applyButton = dialog.querySelector('[data-act="apply"]');
+ const check = (p) => dialog.querySelector(`[data-part="${p.key}"]`);
+ const input = (p) => form.elements[p.field];
+ const errorHost = (p) => dialog.querySelector(`[data-error="${p.key}"]`);
+
+ for (const p of PARTS) {
+ check(p).addEventListener("change", () => {
+ clearField(p);
+ showError("");
+ drawButtons();
+ // A part switched on without a template: its field is where the next step is.
+ if (check(p).checked && input(p).value.trim() === "") {
+ input(p).focus();
+ clearTimeout(timer);
+ preview.classList.add("stale");
+ return;
+ }
+ schedule(0);
+ });
+ input(p).addEventListener("input", () => {
+ clearField(p);
+ showError("");
+ schedule(PLAN_DELAY);
+ });
+ }
+ // Enter in a field plans at once; only the Apply button changes anything.
+ form.addEventListener("submit", (e) => {
+ e.preventDefault();
+ if (loaded && !busy) schedule(0);
+ });
+ closeButton.addEventListener("click", () => {
+ if (!busy) dialog.close();
+ });
+ applyButton.addEventListener("click", apply);
+ dialog.querySelector('[data-act="more"]').addEventListener("click", () => {
+ shown += PAGE;
+ drawRows();
+ if (foot.hidden) preview.focus();
+ });
+ // Esc closes, except while the change is being sent.
+ dialog.addEventListener("cancel", (e) => {
+ if (busy) e.preventDefault();
+ });
+ const signedOut = () => dialog.close();
+ window.addEventListener("chronos:signed-out", signedOut);
+ dialog.addEventListener("close", () => {
+ clearTimeout(timer);
+ window.removeEventListener("chronos:signed-out", signedOut);
+ dialog.remove();
+ resolve(queued);
+ });
+ dialog.showModal();
+ start();
+
+ /** The templates to start from: given, or the archive's settings (and its title template when it has one). */
+ async function start() {
+ let values = templates;
+ if (!values) {
+ try {
+ const settings = await api.get("/api/v1/archive/settings");
+ values = { folderTemplate: settings.folderTemplate, fileTemplate: settings.fileTemplate, titleTemplate: settings.titleTemplate ?? "" };
+ } catch (err) {
+ showError(errorText(err));
+ values = {};
+ }
+ }
+ if (!dialog.open) return;
+ const on = new Set(use ?? PARTS.filter((p) => String(values[p.field] ?? "").trim() !== "").map((p) => p.key));
+ for (const p of PARTS) {
+ input(p).value = values[p.field] ?? "";
+ check(p).checked = on.has(p.key);
+ }
+ loaded = true;
+ drawButtons();
+ (PARTS.map(input).find((field) => !field.disabled) ?? check(PARTS[0])).focus();
+ schedule(0);
+ }
+
+ /** The request the fields make (without dryRun); null when no part is switched on. */
+ function request() {
+ const body = target.all ? { all: true } : { all: false, sequenceIds: target.sequenceIds };
+ let any = false;
+ for (const p of PARTS) {
+ if (!check(p).checked) continue;
+ body[p.field] = input(p).value.trim();
+ any = true;
+ }
+ return any ? body : null;
+ }
+
+ function keyNow() {
+ return JSON.stringify(request());
+ }
+
+ /** Plans again after delay ms; what the table shows until then no longer matches the fields. */
+ function schedule(delay) {
+ clearTimeout(timer);
+ preview.classList.add("stale");
+ drawButtons();
+ timer = setTimeout(runPlan, delay);
+ }
+
+ /** One dry run at a time: a change made while one is answered plans again right after it. */
+ async function runPlan() {
+ if (!loaded || !dialog.open) return;
+ if (planning) {
+ again = true;
+ return;
+ }
+ const body = request();
+ const blank = PARTS.find((p) => check(p).checked && input(p).value.trim() === "");
+ if (!body || blank) {
+ plan = null;
+ if (blank) fieldError(blank, t("Admin.Reorganize.Blank"));
+ drawPlan();
+ return;
+ }
+ const key = JSON.stringify(body);
+ planning = true;
+ totals.textContent = t("Admin.Reorganize.Planning");
+ drawButtons();
+ try {
+ const answer = await api.post(ENDPOINT, { ...body, dryRun: true });
+ if (!dialog.open) return;
+ plan = { ...answer, key };
+ shown = PAGE;
+ PARTS.forEach(clearField);
+ showError(notice);
+ notice = "";
+ } catch (err) {
+ if (!dialog.open) return;
+ plan = null;
+ // A refusal of an older request is not shown: the fields changed since, and the next plan tells.
+ if (key === keyNow()) showProblem(err);
+ } finally {
+ planning = false;
+ }
+ if (again) {
+ again = false;
+ drawPlan();
+ runPlan();
+ return;
+ }
+ drawPlan();
+ }
+
+ function drawPlan() {
+ const current = plan !== null && plan.key === keyNow();
+ preview.classList.toggle("stale", !current);
+ if (!request()) {
+ totals.textContent = t("Admin.Reorganize.NothingChosen");
+ preview.hidden = true;
+ } else if (!plan) {
+ totals.textContent = "";
+ preview.hidden = true;
+ } else if (plan.steps.length === 0) {
+ totals.textContent = t("Admin.Reorganize.NothingToChange");
+ preview.hidden = true;
+ } else {
+ totals.textContent = t("Admin.Reorganize.Totals", formatNumber(plan.sequences), formatNumber(plan.files), formatNumber(plan.kept));
+ preview.hidden = false;
+ drawRows();
+ }
+ drawButtons();
+ }
+
+ function drawRows() {
+ const steps = plan.steps;
+ rows.innerHTML = steps.slice(0, shown).map(rowHtml).join("");
+ foot.hidden = steps.length <= shown;
+ shownText.textContent = t("Admin.Library.Shown", formatNumber(Math.min(shown, steps.length)), formatNumber(steps.length));
+ }
+
+ /** One step: the sequence's title, its folder and its renamed files, before and after, with the photos that keep their names. */
+ function rowHtml(s) {
+ const fromTitle = s.fromTitle ?? null;
+ const toTitle = s.toTitle ?? null;
+ const name = names.get(s.sequenceId) ?? toTitle ?? fromTitle ?? folderName(s.fromFolder);
+ const sequence = fromTitle !== toTitle ? change(fromTitle ?? name, toTitle ?? name, "auto")
+ : `${escapeHtml(name)}`;
+ const folder = s.fromFolder !== s.toFolder ? change(s.fromFolder || "/", s.toFolder || "/", "ltr", "path")
+ : `${escapeHtml(s.fromFolder || "/")}`;
+ const carried = s.carried
+ ? `${escapeHtml(t("Admin.Reorganize.Carried"))}` : "";
+ const samples = (s.fileSamples ?? []).map((f) => `