feat(admin): Reorganize dialog in the Library and after the archive templates change

Owner review 2, R7 asks to rename and move sequences after import, on the web panel too.
The Library's mass bar gets Reorganize… for the selection (every sequence after Select all
without a filter, else at most a thousand ids), and saving a changed folder or file template
on the Archive page offers it for all sequences in the save toast.

The dialog (reorganize.js) has a switch and a field for the folder, file and title templates,
prefilled from the archive settings; each change asks POST /archive/reorganize for a dry run,
one request at a time, and the table shows every step before and after (title, folder, renamed
files with samples, photos that keep their names and why). Apply confirms with the counts of
sequences, folders and photos, sends the shown plan's fingerprint back, and the toast links to
the queued job; a plan_changed refusal plans again. Server refusals land on the field they name.
Toasts can carry an action; the audit entry archive_reorganized reads as a sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 13939dff9a1e8a23ce7802ac38f2ded7fdbc2a74)
This commit is contained in:
Alby96 committed 2026-10-27 14:04:34 +01:00
1 parent eb2395d9b0
commit 17efb50e11
11 files changed
+802 -17

No files matched your search

+33
View File
@@ -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; }
+6
View File
@@ -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;
}
+27 -2
View File
@@ -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 {
+25 -2
View File
@@ -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=<sequence> 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", `<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);
@@ -343,6 +344,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
<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-reorganize" data-mass="reorganize" data-i18n="Admin.Reorganize.Action" data-i18n-title="Admin.Reorganize.Action.Tip"></button>
<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>
@@ -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) => `<option value="${attr(f.value)}"></option>`).join("");
const data = await formDialog({
+365
View File
@@ -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 = `
<form novalidate>
<h2 id="${id}-title" dir="auto">${escapeHtml(title)}</h2>
<div class="reorg-fields">${PARTS.map((p) => `
<label class="check"><input type="checkbox" data-part="${p.key}" disabled title="${attr(t(p.use))}"><span>${escapeHtml(t(p.label))}</span></label>
<input class="input mono" name="${p.field}" dir="ltr" spellcheck="false" autocomplete="off" disabled
aria-label="${attr(t(p.label))}" aria-describedby="${id}-${p.key}-error" title="${attr(t(p.tip))}">
<span class="field-error" id="${id}-${p.key}-error" data-error="${p.key}"></span>`).join("")}
</div>
<div class="reorg-totals" role="status"></div>
<div class="reorg-preview" role="region" tabindex="0" aria-label="${attr(t("Admin.Reorganize.Preview"))}" title="${attr(t("Admin.Reorganize.Preview.Tip"))}" hidden>
<div class="table reorg" role="table" aria-label="${attr(t("Admin.Reorganize.Preview"))}">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Reorganize.Column.Sequence"></span>
<span role="columnheader" data-i18n="Admin.Reorganize.Column.Folder"></span><span role="columnheader" data-i18n="Admin.Reorganize.Column.Files"></span></div>
<div role="rowgroup" class="reorg-rows"></div>
</div>
<div class="table-foot" hidden><span class="muted reorg-shown"></span><span class="spacer"></span>
<button class="btn small" type="button" data-act="more" data-i18n="Admin.Common.More" data-i18n-title="Admin.Common.More.Tip"></button></div>
</div>
<div class="error" role="alert"></div>
<div class="buttons">
<button class="btn" type="button" data-act="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Reorganize.Cancel.Tip"></button>
<button class="btn primary" type="button" data-act="apply" disabled data-i18n="Admin.Reorganize.Apply" data-i18n-title="Admin.Reorganize.Apply.Tip"></button>
</div>
</form>`;
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")
: `<span class="ellipsis" dir="auto" title="${attr(name)}">${escapeHtml(name)}</span>`;
const folder = s.fromFolder !== s.toFolder ? change(s.fromFolder || "/", s.toFolder || "/", "ltr", "path")
: `<span class="path muted" dir="ltr" title="${attr(t("Admin.Reorganize.SameFolder.Tip"))}">${escapeHtml(s.fromFolder || "/")}</span>`;
const carried = s.carried
? `<span class="pill" title="${attr(t("Admin.Reorganize.Carried.Tip"))}">${escapeHtml(t("Admin.Reorganize.Carried"))}</span>` : "";
const samples = (s.fileSamples ?? []).map((f) => `<li dir="ltr">${escapeHtml(f.from)} → ${escapeHtml(f.to)}</li>`).join("");
const files = s.fileChanges > 0
? `<strong class="num">${escapeHtml(formatNumber(s.fileChanges))}</strong>${samples ? `<ul class="reorg-samples path">${samples}</ul>` : ""}`
: `<span class="muted">—</span>`;
const kept = (s.blocked ?? []).map((b) => `<li><span aria-hidden="true">▲</span> ${escapeHtml(b.photos > 0
? t("Admin.Reorganize.KeptPhotos", plural("Admin.Dashboard.PhotoCount", b.photos), b.message) : b.message)}</li>`).join("");
return `<div class="row" role="row" data-key="${attr(s.sequenceId)}">
<span role="cell" class="stack">${sequence}${carried}</span>
<span role="cell" class="stack">${folder}</span>
<span role="cell" class="stack">${files}${kept ? `<ul class="reorg-kept">${kept}</ul>` : ""}</span>
</div>`;
}
function drawButtons() {
for (const p of PARTS) {
check(p).disabled = busy || !loaded;
input(p).disabled = busy || !loaded || !check(p).checked;
}
applyButton.disabled = busy || planning || plan === null || plan.key !== keyNow() || plan.sequences === 0;
closeButton.disabled = busy;
}
/** The confirmation names what moves; the plan sent back is the one the table shows (the fields cannot change meanwhile). */
async function apply() {
if (applyButton.disabled) return;
const chosen = plan;
const moves = chosen.steps.filter((s) => s.fromFolder !== s.toFolder).length;
const body = [plural("Admin.Reorganize.ConfirmSequences", chosen.sequences),
moves > 0 ? plural("Admin.Reorganize.ConfirmFolders", moves) : "",
chosen.files > 0 ? plural("Admin.Reorganize.ConfirmFiles", chosen.files) : ""].filter(Boolean).join(" ");
const confirmed = await confirmDialog({
title: t("Admin.Reorganize.ConfirmTitle"),
body,
confirm: t("Admin.Reorganize.Confirm"),
confirmTip: t("Admin.Reorganize.Confirm.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
if (!confirmed || !dialog.open || plan !== chosen) return;
busy = true;
showError("");
drawButtons();
try {
const job = await api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint });
queued = job;
busy = false;
dialog.close();
toast(t("Admin.Reorganize.Queued"), false,
{ label: t("Admin.Reorganize.OpenJob"), tip: t("Admin.Reorganize.OpenJob.Tip"), href: `#/jobs?job=${encodeURIComponent(job.id)}` });
} catch (err) {
busy = false;
if (!dialog.open) return;
if (err?.code === "plan_changed") {
// The archive changed since the dry run: the new plan is shown, and Apply waits for it.
notice = err.message || t("Admin.Error.Unreachable");
plan = null;
schedule(0);
} else {
showProblem(err);
}
drawButtons();
(applyButton.disabled ? closeButton : applyButton).focus();
}
}
/** A refusal on the field it names (a template, or the folders for a nested target), else under the table. */
function showProblem(err) {
const part = PARTS.find((p) => p.field === err?.details);
if (err?.code === "invalid_template" && part) fieldError(part, err.message);
else if (err?.code === "nested_target") fieldError(PARTS[0], err.message, err.details);
else if (err?.code === "not_found") showError(t("Admin.Reorganize.Gone"));
else showError(errorText(err));
}
function fieldError(part, message, path = "") {
markInvalid(input(part), path ? `${message} ${path}` : message);
errorHost(part).innerHTML = escapeHtml(message) + (path ? ` <span class="path" dir="ltr">${escapeHtml(path)}</span>` : "");
}
function clearField(part) {
clearInvalid(input(part));
errorHost(part).textContent = "";
}
function showError(message) {
errorLine.textContent = message;
}
});
}
/** Old and new value, one above the other; screen readers hear which is which. */
function change(was, now, dir, cls = "") {
return `<span class="change ${cls}"><span class="was" dir="${dir}"><span class="sr-only">${escapeHtml(t("Admin.Reorganize.Before"))} </span>${escapeHtml(was)}</span>` +
`<span class="now" dir="${dir}"><span class="sr-only">${escapeHtml(t("Admin.Reorganize.After"))} </span>${escapeHtml(now)}</span></span>`;
}
/** The last part of a sequence folder ("2026/2026-09-28 Roof" → "2026-09-28 Roof"), its name when it has no title. */
function folderName(folder) {
return String(folder ?? "").split("/").filter(Boolean).pop() ?? "—";
}
+34 -10
View File
@@ -122,25 +122,49 @@ export function emptyState(sentenceKey, button = "") {
return `<div class="empty"><span data-i18n="${attr(sentenceKey)}"></span>${button}</div>`;
}
/** Shows a toast at the bottom (inline end) for 8 s (hover pauses). */
export function toast(message, isError = false) {
/**
* Shows a toast at the bottom (inline end) for 8 s, 15 s with an action (the pointer over it or the keyboard focus in it
* pauses). action ({ label, tip, href } or { label, tip, run }) adds a link or a button after the message, which closes
* the toast.
*/
export function toast(message, isError = false, action = null) {
const host = document.getElementById("toasts") ?? document.body.appendChild(Object.assign(document.createElement("div"), { id: "toasts" }));
const item = document.createElement("div");
item.className = `toast${isError ? " error" : ""}`;
item.className = `toast${isError ? " error" : ""}${action ? " with-action" : ""}`;
item.setAttribute("role", isError ? "alert" : "status");
item.textContent = message;
item.appendChild(Object.assign(document.createElement("span"), { textContent: message }));
if (action) {
const control = document.createElement(action.href ? "a" : "button");
control.className = "btn small";
if (action.href) control.href = action.href;
else control.type = "button";
control.textContent = action.label;
control.title = action.tip;
control.addEventListener("click", () => {
item.remove();
action.run?.();
});
item.appendChild(control);
}
host.appendChild(item);
let remaining = 8000;
let remaining = action ? 15000 : 8000;
let started = Date.now();
let timer = setTimeout(() => item.remove(), remaining);
item.addEventListener("mouseenter", () => {
let held = 0;
const pause = () => {
if (held++ > 0) return;
clearTimeout(timer);
remaining -= Date.now() - started;
});
item.addEventListener("mouseleave", () => {
};
const resume = () => {
if (--held > 0) return;
started = Date.now();
timer = setTimeout(() => item.remove(), remaining);
});
timer = setTimeout(() => item.remove(), Math.max(remaining, 2000));
};
item.addEventListener("mouseenter", pause);
item.addEventListener("mouseleave", resume);
item.addEventListener("focusin", pause);
item.addEventListener("focusout", resume);
}
let dialogs = 0;