diff --git a/src/Chronos.Server/Admin/web/api.js b/src/Chronos.Server/Admin/web/api.js
index de496323..6537c4bc 100644
--- a/src/Chronos.Server/Admin/web/api.js
+++ b/src/Chronos.Server/Admin/web/api.js
@@ -88,16 +88,29 @@ export const api = {
currentUser = null;
},
- /** Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. */
+ /**
+ * Server events over WebSocket (cookie session), reconnecting with back-off until stop() is called. The events sent
+ * while it was not connected are lost, so once it is connected again onEvent gets { type: "reconnected" } (the
+ * panel's own, never the server's): a page then reads again what it follows.
+ */
events(onEvent) {
let socket = null;
let stopped = false;
+ let opened = false;
let delay = 1000;
const connect = () => {
if (stopped) return;
socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/v1/events`);
socket.onopen = () => {
delay = 1000;
+ if (opened) {
+ try {
+ onEvent({ type: "reconnected" });
+ } catch {
+ // A listener that throws does not stop the events.
+ }
+ }
+ opened = true;
};
socket.onmessage = (m) => {
try {
diff --git a/src/Chronos.Server/Admin/web/pages/library.js b/src/Chronos.Server/Admin/web/pages/library.js
index 17e65404..573b0286 100644
--- a/src/Chronos.Server/Admin/web/pages/library.js
+++ b/src/Chronos.Server/Admin/web/pages/library.js
@@ -4,7 +4,7 @@
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 } from "./library/shared.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";
@@ -138,8 +138,8 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
location.hash = `#/library?id=${encodeURIComponent(key)}`;
},
onChange: () => {
- // "Select all" holds while sequences beyond the loaded rows stay selected; once none does (Esc, Ctrl+A, every card
- // unticked) the selection is the loaded rows' again: Select all comes back and a refresh drops sequences gone.
+ // "Select all" holds while sequences beyond the loaded rows stay selected (unticking cards keeps those); once none
+ // does (Esc, Ctrl+A) the selection is the loaded rows' again: Select all comes back and a refresh drops sequences gone.
if (matching) {
const loaded = new Set(rows.map((r) => r.id));
if ([...selection.ids].every((id) => loaded.has(id))) matching = null;
@@ -556,7 +556,7 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
// 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);
+ else if (e.type === "jobState" && JOB_ENDED.has(e.state)) refreshSoon(1500);
});
await load();
}
diff --git a/src/Chronos.Server/Admin/web/pages/library/sequence.js b/src/Chronos.Server/Admin/web/pages/library/sequence.js
index 87235077..944b82d9 100644
--- a/src/Chronos.Server/Admin/web/pages/library/sequence.js
+++ b/src/Chronos.Server/Admin/web/pages/library/sequence.js
@@ -20,6 +20,8 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
let frames = [];
let cursor = null;
let renders = [];
+ /** The renders' list as last drawn (JSON), null before the first draw. */
+ let rendersShown = null;
let generation = 0;
let timer = null;
let jobTimer = null;
@@ -135,15 +137,20 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
watchImages(cover);
}
+ // Tags and stars are buttons: a redraw keeps the keyboard focus on the same one (a star by its id, a tag by its place).
const tags = root.querySelector("#tags");
- tags.innerHTML = seq.tags.map((tag, i) => `${escapeHtml(tag)}`).join("");
+ redraw(tags, () => {
+ tags.innerHTML = seq.tags.map((tag, i) => `${escapeHtml(tag)}`).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) => ``).join("");
+ redraw(rating, () => {
+ rating.innerHTML = [1, 2, 3, 4, 5].map((n) => ``).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}`);
@@ -399,13 +406,25 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
location.hash = back;
}
+ /** The renders, drawn again only when their list changed (a refresh after every job must not move the focus). */
async function loadRenders() {
+ let list;
try {
- renders = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/renders`);
+ list = await api.get(`/api/v1/sequences/${encodeURIComponent(id)}/renders`);
} catch {
- renders = [];
+ // A failed refresh leaves the list shown; a first read that failed shows none.
+ if (rendersShown !== null) return;
+ list = [];
}
+ const key = JSON.stringify(list);
+ if (key === rendersShown || !root.isConnected) return;
+ rendersShown = key;
+ renders = list;
const host = root.querySelector("#renders");
+ redraw(host, () => drawRenders(host));
+ }
+
+ function drawRenders(host) {
host.innerHTML = renders.length === 0 ? emptyState("Admin.Sequence.NoRenders") : `
@@ -517,16 +536,21 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
].join("");
}
- /** Everything again after a change elsewhere; with frames, the photos too. */
+ /**
+ * Everything again after a change elsewhere; with frames, the photos too. Only what changed is drawn again (the header
+ * when the sequence read differs from the one shown), so a refresh that finds nothing new leaves the page and the
+ * keyboard focus as they were. True when the sequence changed.
+ */
async function reload(withFrames) {
- const before = seq.framesVersion;
- const hero = seq.heroFrameId;
+ const shown = seq;
await reloadSequence();
- if (!root.isConnected || leaving) return;
- drawHeader();
- if (withFrames || seq.framesVersion !== before) await reloadFrames();
- else if (seq.heroFrameId !== hero) drawFrames();
+ if (!root.isConnected || leaving) return false;
+ const changed = JSON.stringify(seq) !== JSON.stringify(shown);
+ if (changed) drawHeader();
+ if (withFrames || seq.framesVersion !== shown.framesVersion) await reloadFrames();
+ else if (seq.heroFrameId !== shown.heroFrameId) drawFrames();
await loadRenders();
+ return changed;
}
function gone() {
@@ -538,19 +562,21 @@ export async function renderSequence(root, { api, setMeta, actions, onEvent }, i
/**
* After a job ended: thumbnail, proxy, verify and analysis jobs send no sequenceChanged, so the facts and status chips
- * are read again and the cover and photos that had no thumbnail yet are asked for again.
+ * are read again and the cover and photos that had no thumbnail yet are asked for again, each less often and up to a
+ * limit, from the start again once the sequence changed.
*/
async function afterJob() {
jobTimer = null;
if (!root.isConnected || leaving) return;
- await reload(false);
- if (root.isConnected && !leaving) retryImages(root);
+ const changed = await reload(false);
+ if (root.isConnected && !leaving) retryImages(root, changed);
}
onEvent((e) => {
if (e.type === "jobState") {
- // The event names no sequence: any job that ended may have worked on this one. The timer is not pushed back by the
- // next one, so a busy queue still refreshes the page every AFTER_JOB_MS.
+ // The event names neither the job's kind nor its targets: any job that ended may have worked on this one. The timer
+ // is not pushed back by the next one, so a busy queue still refreshes the page every AFTER_JOB_MS; a refresh that
+ // finds the sequence and its renders as shown draws nothing.
if (JOB_ENDED.has(e.state) && jobTimer === null) jobTimer = setTimeout(afterJob, AFTER_JOB_MS);
return;
}
diff --git a/src/Chronos.Server/Admin/web/pages/library/shared.js b/src/Chronos.Server/Admin/web/pages/library/shared.js
index d659acdc..b9039814 100644
--- a/src/Chronos.Server/Admin/web/pages/library/shared.js
+++ b/src/Chronos.Server/Admin/web/pages/library/shared.js
@@ -1,5 +1,6 @@
// 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.
+// thumbnails and their retries after a job ended, the job states that end a job, delete lists cut to LISTED names, a
+// selection with Shift ranges, the keyboard of a grid of selectable items, chunked bulk calls and file downloads.
import { t, plural, culture } from "../../i18n.js";
import { escapeHtml, attr, formatNumber, formatDuration } from "../../ui.js";
import { icons } from "../../icons.js";
@@ -93,14 +94,26 @@ export function watchImages(root) {
});
}
+/** Retries of an image that had nothing to show, the first after RETRY_FIRST_MS and each next one after twice the wait, up to RETRY_LONGEST_MS. */
+const RETRY_TRIES = 8;
+const RETRY_FIRST_MS = 2000;
+const RETRY_LONGEST_MS = 60000;
+
/**
* The images under root that had nothing to show (a thumbnail not built yet) asked for again, once a job that may have
- * built them ended: under an address the browser has not tried, so its first answer is not reused.
+ * built them ended: under an address the browser has not tried, so its first answer is not reused. Each image waits
+ * longer before every retry and stops after RETRY_TRIES, since some never get one (a photo whose original is missing);
+ * fresh (the sequence itself changed, a pass may have built them) starts every image's count again.
*/
-export function retryImages(root) {
+export function retryImages(root, fresh = false) {
+ const now = Date.now();
root.querySelectorAll("img.failed").forEach((img) => {
+ const tries = fresh ? 0 : Number(img.dataset.tries ?? 0);
+ if (tries >= RETRY_TRIES || (!fresh && now < Number(img.dataset.retryAt ?? 0))) return;
+ img.dataset.tries = String(tries + 1);
+ img.dataset.retryAt = String(now + Math.min(RETRY_FIRST_MS * 2 ** tries, RETRY_LONGEST_MS));
const url = new URL(img.getAttribute("src"), location.href);
- url.searchParams.set("retry", String(Date.now()));
+ url.searchParams.set("retry", String(now));
img.classList.remove("failed");
img.setAttribute("data-fallback", "");
img.src = url.pathname + url.search;
diff --git a/src/Chronos.Server/Admin/web/pages/library/trash.js b/src/Chronos.Server/Admin/web/pages/library/trash.js
index 6225e0a0..658858a8 100644
--- a/src/Chronos.Server/Admin/web/pages/library/trash.js
+++ b/src/Chronos.Server/Admin/web/pages/library/trash.js
@@ -20,6 +20,8 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
* the POST that queued it has answered, so the page looks the job up here once it has its id.
*/
const ended = new Map();
+ /** Entries whose restore was sent and has not answered: their buttons stay disabled through every redraw. */
+ const restoring = new Set();
let timer = null;
let jobTimer = null;
@@ -45,6 +47,7 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
const table = root.querySelector(".table");
async function load() {
+ if (emptyJob !== null) await checkEmptyJob();
try {
const list = await api.get("/api/v1/archive/trash");
entries = list.entries;
@@ -75,7 +78,7 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
${escapeHtml(e.deletedBy ?? "—")}${escapeHtml(formatDateTime(e.deletedAt))}
+ data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}" ${restoring.has(e.name) ? "disabled" : ""}>
`).join("")
|| `
${emptyState("Admin.Trash.IsEmpty",
``)}
`;
@@ -86,16 +89,19 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
}
async function restore(entry, button) {
- if (!entry) return;
+ if (!entry || restoring.has(entry.name)) return;
+ restoring.add(entry.name);
button.disabled = true;
let result;
try {
result = await api.post(`/api/v1/archive/trash/${encodeURIComponent(entry.name)}/restore`);
} catch (err) {
+ restoring.delete(entry.name);
toast(errorText(err), true);
- if (button.isConnected) button.disabled = false;
- // The entry is gone (emptied or restored elsewhere): the list shows the trash as it is now.
+ // The entry is gone (emptied or restored elsewhere): the list shows the trash as it is now; else its button, maybe
+ // drawn again meanwhile, can be used again.
if (err.status === 404) await load();
+ else draw();
return;
}
const lines = [result.kind === "sequence" ? t("Admin.Trash.RestoredSequence", entry.title)
@@ -103,7 +109,9 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
// The server says, in the page's language, how many photos stayed in the trash and why (one sentence per reason).
if (result.kept.length > 0 && result.message) lines.push(result.message);
toast(lines.join(" "), result.kept.length > 0);
+ // Until the list without the entry is drawn: a read that started before the restore answered still shows it.
await load();
+ restoring.delete(entry.name);
}
/** Measure (dry run), name what goes, have "empty" typed, then queue the erase with the plan's fingerprint. */
@@ -152,13 +160,29 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
}
}
- /** The emptying this page queued ended: its toast; the caller shows the trash again. */
+ /** The emptying this page queued ended (its jobState event, or the job read): its toast; the caller shows the trash again. */
function emptyEnded(e) {
emptyJob = null;
if (e.state === "done") toast(t("Admin.Trash.Emptied"));
else toast(e.error || t("Admin.Trash.EmptyFailed"), true);
}
+ /**
+ * The emptying this page follows, read from the queue: its end may have come while the events were not connected,
+ * and nothing sends it again. A job no longer listed is followed no more, so Empty never stays disabled.
+ */
+ async function checkEmptyJob() {
+ const id = emptyJob;
+ let job;
+ try {
+ job = await api.get(`/api/v1/jobs/${encodeURIComponent(id)}`);
+ } catch (err) {
+ if (err.status === 404 && emptyJob === id) emptyJob = null;
+ return;
+ }
+ if (emptyJob === id && JOB_ENDED.has(job.state)) emptyEnded(job);
+ }
+
onEvent((e) => {
if (e.type === "jobState" && JOB_ENDED.has(e.state)) {
ended.set(e.jobId, e);
@@ -180,6 +204,9 @@ export async function renderTrash(root, { api, setMeta, actions, onEvent }, { ba
timer = setTimeout(() => {
if (root.isConnected) load();
}, 800);
+ } else if (e.type === "reconnected") {
+ // Events sent while the socket was down are lost: the trash, and the emptying it follows, are read again.
+ if (root.isConnected) load();
}
});
await load();
diff --git a/src/Chronos.Server/Admin/web/ui.js b/src/Chronos.Server/Admin/web/ui.js
index 2edb1902..39f6629d 100644
--- a/src/Chronos.Server/Admin/web/ui.js
+++ b/src/Chronos.Server/Admin/web/ui.js
@@ -307,7 +307,8 @@ export function focusPlace(root) {
/**
* Focuses the same control after a re-render, else the control at the same place in the same (or same-position) row,
- * else the first control left (an empty state's button).
+ * else the first control left (an empty state's button). A control without a name (a tag's remove button) is found by
+ * its place alone: matching its empty name would pick the first unnamed control instead.
*/
export function restoreFocus(root, place) {
if (!place) return;
@@ -320,7 +321,8 @@ export function restoreFocus(root, place) {
else index = 0;
}
const controls = [...scope.querySelectorAll(FOCUSABLE)];
- (controls.find((c) => controlKey(c) === place.control) ?? controls[Math.min(Math.max(index, 0), controls.length - 1)])?.focus();
+ const same = place.control ? controls.find((c) => controlKey(c) === place.control) : undefined;
+ (same ?? controls[Math.min(Math.max(index, 0), controls.length - 1)])?.focus();
}
/** Redraws with draw() and puts the keyboard focus back where it was. */
diff --git a/src/Chronos.Server/Admin/web/upload.js b/src/Chronos.Server/Admin/web/upload.js
index 31323142..c7ec62b0 100644
--- a/src/Chronos.Server/Admin/web/upload.js
+++ b/src/Chronos.Server/Admin/web/upload.js
@@ -152,11 +152,12 @@ export function openUpload({ api, sequence, onDone } = {}) {
});
// Esc closes only while nothing is being sent; Cancel stops a run. Chromium lets a dialog's cancel be prevented only
- // once per user activation, so during a run Esc is stopped at its keydown; the cancel handler stays for close requests
- // that do not come from the keyboard (a back gesture).
- dialog.addEventListener("keydown", (e) => {
- if (running && e.key === "Escape") e.preventDefault();
- });
+ // once per user activation, so during a run Esc is stopped at its keydown, on the document in the capture phase: a
+ // click on the dialog's text moves the focus to the body, and Esc from there would pass the dialog by. The cancel
+ // handler stays for close requests that do not come from the keyboard (a back gesture).
+ const stopEscape = (e) => {
+ if (e.key === "Escape") e.preventDefault();
+ };
dialog.addEventListener("cancel", (e) => {
if (running) e.preventDefault();
});
@@ -176,6 +177,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
clearTimeout(searchTimer);
cancelAnimationFrame(frame);
window.removeEventListener("beforeunload", guard);
+ document.removeEventListener("keydown", stopEscape, true);
window.removeEventListener("chronos:signed-out", signedOut);
dialog.remove();
resolve();
@@ -456,6 +458,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
sameContent = new Map();
const signal = controller.signal;
window.addEventListener("beforeunload", guard);
+ document.addEventListener("keydown", stopEscape, true);
drawButtons();
let changed = false;
try {
@@ -496,6 +499,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
running = false;
controller = null;
window.removeEventListener("beforeunload", guard);
+ document.removeEventListener("keydown", stopEscape, true);
todo.filter((i) => ACTIVE.has(i.state)).forEach((i) => setState(i, "cancelled"));
drawButtons();
drawTotal();
@@ -629,7 +633,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
if (failure !== null && !filing(failure)) throw failure;
setState(item, "verifying");
try {
- await complete(item.uploadId, restore, signal);
+ await complete(api, item.uploadId, restore, signal);
} catch (err) {
if (!(err instanceof ApiFailure && err.status === 409 && err.code === "photo_removed")) throw err;
// Deleted from the sequence while it was on its way: not filed, and the server dropped the upload (R6).
@@ -656,12 +660,12 @@ function filing(err) {
}
/**
- * Completes an upload (with restore, a photo deleted from the sequence meanwhile is filed anyway). A completion refused
- * while another one is filing the upload (the same photo started twice, a retry after a lost answer) waits for it: once
- * the upload is committed, completing again answers its frame. Only an upload that failed or was cancelled, or one that
- * stays busy for about a minute, fails the photo.
+ * Completes an upload through api, the dialog's (with restore, a photo deleted from the sequence meanwhile is filed
+ * anyway). A completion refused while another one is filing the upload (the same photo started twice, a retry after a
+ * lost answer) waits for it: once the upload is committed, completing again answers its frame. Only an upload that
+ * failed or was cancelled, or one that stays busy for about a minute, fails the photo.
*/
-async function complete(uploadId, restore, signal) {
+async function complete(api, uploadId, restore, signal) {
const url = `/api/v1/uploads/${uploadId}/complete${restore ? "?restore=true" : ""}`;
for (let check = 0; ; check++) {
try {
diff --git a/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs b/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs
index bb393a18..f818b65b 100644
--- a/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs
+++ b/tests/Chronos.Server.Tests/Hosting/SystemEndpointTests.cs
@@ -250,13 +250,245 @@ public sealed partial class SystemEndpointTests(TestContext context)
var shared = await server.Client.GetStringAsync("/admin/pages/library/shared.js");
Assert.True(Regex.IsMatch(sequence, @"e\.type === ""jobState""\) \{\s+(//[^\n]*\s+)*if \(JOB_ENDED\.has\(e\.state\) && jobTimer === null\) jobTimer = setTimeout\(afterJob"),
"an ended job schedules one refresh, not pushed back by the next");
- Assert.True(Regex.IsMatch(sequence, @"async function afterJob\(\) \{[^}]*await reload\(false\);[^}]*retryImages\(root\);", RegexOptions.Singleline),
- "the refresh reads the sequence again, then retries the cover and the photos");
+ Assert.True(Regex.IsMatch(sequence, @"async function afterJob\(\) \{[^}]*const changed = await reload\(false\);[^}]*retryImages\(root, changed\);", RegexOptions.Singleline),
+ "the refresh reads the sequence again, then retries the cover and the photos, all of them again once the sequence changed");
Assert.Contains(@"export const JOB_ENDED = new Set([""done"", ""failed"", ""cancelled""]);", shared);
- Assert.True(Regex.IsMatch(shared, @"export function retryImages\(root\) \{\s+root\.querySelectorAll\(""img\.failed""\)[^}]*searchParams\.set\(""retry"",", RegexOptions.Singleline),
- "a retried image gets an address the browser has not tried");
+ // A thumbnail that never comes (its original is missing) is not asked for after every job for as long as the page
+ // stays open: each retry waits twice as long as the last, and an image stops after RETRY_TRIES.
+ Assert.True(Regex.IsMatch(shared, @"export function retryImages\(root, fresh = false\) \{[^}]*root\.querySelectorAll\(""img\.failed""\)[^}]*" +
+ @"if \(tries >= RETRY_TRIES \|\| \(!fresh && now < Number\(img\.dataset\.retryAt \?\? 0\)\)\) return;[^}]*" +
+ @"Math\.min\(RETRY_FIRST_MS \* 2 \*\* tries, RETRY_LONGEST_MS\)[^}]*searchParams\.set\(""retry"",", RegexOptions.Singleline),
+ "a retried image waits longer each time, stops, and gets an address the browser has not tried");
+ Assert.True(Regex.IsMatch(shared, @"const RETRY_TRIES = \d+;"), "RETRY_TRIES");
+ // The Library list also counts a cancelled job as ended.
+ var library = await server.Client.GetStringAsync("/admin/pages/library.js");
+ Assert.Contains(@"e.type === ""jobState"" && JOB_ENDED.has(e.state)", library);
}
+ [Test]
+ public async Task ASequencePageRefreshDrawsOnlyWhatChangedAndKeepsTheFocus()
+ {
+ // The refresh after every ended job must not drop a keyboard user on the body: the header is drawn again only when
+ // the sequence read differs from the one shown, the renders only when their list does, and every redraw of the
+ // stars, the tags and the renders puts the focus back on the same control.
+ await using var server = await TestServer.StartAsync(context);
+ var sequence = await server.Client.GetStringAsync("/admin/pages/library/sequence.js");
+ Assert.True(Regex.IsMatch(sequence, @"async function reload\(withFrames\) \{[^}]*const changed = JSON\.stringify\(seq\) !== JSON\.stringify\(shown\);\s+if \(changed\) drawHeader\(\);", RegexOptions.Singleline),
+ "the header is drawn again only when the sequence changed");
+ foreach (var host in new[] { "tags", "rating" })
+ {
+ Assert.True(Regex.IsMatch(sequence, $@"redraw\({host}, \(\) => \{{\s+{host}\.innerHTML = "), $"#{host} is drawn keeping the focus");
+ Assert.Count(1, Regex.Matches(sequence, $@"\b{host}\.innerHTML = "));
+ }
+ Assert.True(Regex.IsMatch(sequence, @"if \(key === rendersShown \|\| !root\.isConnected\) return;\s+rendersShown = key;\s+renders = list;\s+const host = root\.querySelector\(""#renders""\);\s+redraw\(host, \(\) => drawRenders\(host\)\);"),
+ "the renders are drawn again only when they changed, keeping the focus");
+ Assert.Count(2, Regex.Matches(sequence, @"\bdrawRenders\("));
+ // A control without a name (a tag's remove button) is found again by its place, not as the first unnamed one.
+ var ui = await server.Client.GetStringAsync("/admin/ui.js");
+ Assert.Contains("const same = place.control ? controls.find((c) => controlKey(c) === place.control) : undefined;", ui);
+ }
+
+ [Test]
+ public async Task TheTrashPageReadsItsEmptyingAgainAndKeepsARestoreDisabledUntilItAnswers()
+ {
+ // The end of an emptying can be lost while the events are not connected: whenever the page reads the trash (and
+ // after the socket connects again) it reads the job it follows, so Empty never stays disabled.
+ await using var server = await TestServer.StartAsync(context);
+ var trash = await server.Client.GetStringAsync("/admin/pages/library/trash.js");
+ Assert.True(Regex.IsMatch(trash, @"async function load\(\) \{\s+if \(emptyJob !== null\) await checkEmptyJob\(\);"), "load reads the emptying first");
+ Assert.True(Regex.IsMatch(trash, @"async function checkEmptyJob\(\) \{[^}]*api\.get\(`/api/v1/jobs/\$\{encodeURIComponent\(id\)\}`\);.*?if \(err\.status === 404 && emptyJob === id\) emptyJob = null;.*?" +
+ @"if \(emptyJob === id && JOB_ENDED\.has\(job\.state\)\) emptyEnded\(job\);", RegexOptions.Singleline), "the job read ends the emptying, and a job gone too");
+ Assert.True(Regex.IsMatch(trash, @"e\.type === ""reconnected""\) \{\s+(//[^\n]*\s+)*if \(root\.isConnected\) load\(\);"), "a reconnect reads the trash again");
+ var api = await server.Client.GetStringAsync("/admin/api.js");
+ Assert.True(Regex.IsMatch(api, @"socket\.onopen = \(\) => \{\s+delay = 1000;\s+if \(opened\) \{\s+try \{\s+onEvent\(\{ type: ""reconnected"" \}\);"), "the socket says when it connected again");
+ // A redraw while a restore is on its way (a job ended, a sequence changed) keeps its button disabled, so the same
+ // entry is not sent twice.
+ Assert.Contains(@"${restoring.has(e.name) ? ""disabled"" : """"}", trash);
+ Assert.True(Regex.IsMatch(trash, @"if \(!entry \|\| restoring\.has\(entry\.name\)\) return;\s+restoring\.add\(entry\.name\);"), "a restore marks its entry");
+ Assert.True(Regex.IsMatch(trash, @"catch \(err\) \{\s+restoring\.delete\(entry\.name\);"), "a refused restore frees its button");
+ Assert.True(Regex.IsMatch(trash, @"await load\(\);\s+restoring\.delete\(entry\.name\);\s+\}"), "a restore frees its entry once the trash is read again");
+ }
+
+ [Test]
+ public async Task AdminModulesCallTheApiOnlyWhereTheyHaveIt()
+ {
+ // upload.js once called api from a top-level helper while api was only openUpload's parameter: every completion
+ // threw a ReferenceError that string checks never saw. A module that neither declares api (api.js) nor imports it
+ // (app.js) takes it as a parameter in each top-level function that uses it, and uses it nowhere else.
+ await using var server = await TestServer.StartAsync(context);
+ var modules = await ModulesAsync(server);
+ var checkedUses = 0;
+ foreach (var (module, source) in modules)
+ {
+ var code = JsCode(source);
+ if (HasApi().IsMatch(code)) continue;
+ foreach (var (name, parameters, body) in TopLevel(code))
+ {
+ if (!ApiName().IsMatch(body)) continue;
+ checkedUses++;
+ Assert.True(ApiName().IsMatch(parameters), $"{module}: {name} uses api but does not take it");
+ }
+ }
+ Assert.Greater(checkedUses, 5);
+ Assert.Contains("complete(api, item.uploadId, restore, signal)", modules["upload.js"]);
+
+ // The check sees the mistake it is here for, and is not fooled by strings, comments, templates or regular expressions.
+ const string broken = """
+ import { ApiFailure } from "./api.js";
+ // api.get in a comment
+ export function openUpload({ api, sequence } = {}) {
+ return complete(1, /api\//.test("x"));
+ }
+ async function complete(id) {
+ const url = `/api/v1/uploads/${id}/complete${id ? `?api=${"api"}` : ""}`;
+ return api.post(url);
+ }
+ function retry(call) {
+ return call("api");
+ }
+ """;
+ var flagged = TopLevel(JsCode(broken)).Where(s => ApiName().IsMatch(s.Body) && !ApiName().IsMatch(s.Parameters)).Select(s => s.Name);
+ Assert.SequenceEqual(["complete"], flagged);
+ }
+
+ ///
+ /// A module's code with its comments, string and regular expression literals and the text of its template literals
+ /// blanked (their expressions kept), each character where it was: what is left are names, keywords and punctuation.
+ ///
+ private static string JsCode(string source)
+ {
+ var code = source.ToCharArray();
+ // The brace depth at which each template expression open ends and its template's text goes on.
+ var templates = new Stack();
+ var depth = 0;
+ var i = 0;
+ void Blank(int from, int to)
+ {
+ for (var k = from; k < Math.Min(to, code.Length); k++)
+ if (code[k] != '\n') code[k] = ' ';
+ }
+ // From the text of a template literal: true at its closing backtick, false at an expression; i past either.
+ bool TemplateText()
+ {
+ var start = i;
+ while (i < code.Length)
+ {
+ if (code[i] == '\\') i += 2;
+ else if (code[i] == '`')
+ {
+ Blank(start, i++);
+ return true;
+ }
+ else if (code[i] == '$' && i + 1 < code.Length && code[i + 1] == '{')
+ {
+ Blank(start, i);
+ i += 2;
+ return false;
+ }
+ else i++;
+ }
+ Blank(start, i);
+ return true;
+ }
+ while (i < code.Length)
+ {
+ var c = code[i];
+ var next = i + 1 < code.Length ? code[i + 1] : '\0';
+ if (c == '/' && next is '/' or '*')
+ {
+ var end = next == '/' ? source.IndexOf('\n', i) : source.IndexOf("*/", i + 2, StringComparison.Ordinal);
+ end = end < 0 ? code.Length : next == '/' ? end : end + 2;
+ Blank(i, end);
+ i = end;
+ }
+ else if (c is '"' or '\'' || (c == '/' && RegexMayStart(code, i)))
+ {
+ var start = i++;
+ var inClass = false;
+ while (i < code.Length && code[i] != '\n' && (code[i] != c || inClass))
+ {
+ if (code[i] == '\\') i++;
+ else if (c == '/' && code[i] == '[') inClass = true;
+ else if (c == '/' && code[i] == ']') inClass = false;
+ i++;
+ }
+ Blank(start + 1, i++);
+ }
+ else if (c == '`')
+ {
+ i++;
+ if (!TemplateText()) templates.Push(++depth);
+ }
+ else if (c == '}' && templates.Count > 0 && templates.Peek() == depth)
+ {
+ templates.Pop();
+ depth--;
+ i++;
+ if (!TemplateText()) templates.Push(++depth);
+ }
+ else
+ {
+ if (c == '{') depth++;
+ else if (c == '}') depth--;
+ i++;
+ }
+ }
+ return new string(code);
+ }
+
+ /// Whether the slash at starts a regular expression (after an operator or a keyword), not a division.
+ private static bool RegexMayStart(char[] code, int at)
+ {
+ var p = at - 1;
+ while (p >= 0 && char.IsWhiteSpace(code[p])) p--;
+ if (p < 0 || "(,=:[!&|?{};+-*%<>~^".Contains(code[p], StringComparison.Ordinal)) return true;
+ if (!(char.IsLetterOrDigit(code[p]) || code[p] is '_' or '$')) return false;
+ var end = p + 1;
+ while (p >= 0 && (char.IsLetterOrDigit(code[p]) || code[p] is '_' or '$')) p--;
+ return new string(code, p + 1, end - p - 1) is "return" or "typeof" or "case" or "in" or "of" or "delete" or "void" or "throw" or "new";
+ }
+
+ ///
+ /// The top-level statements of blanked code (each starts at the beginning of a line): a function's name, parameters and
+ /// body, or another statement's first line, no parameters and its text.
+ ///
+ private static IEnumerable<(string Name, string Parameters, string Body)> TopLevel(string code)
+ {
+ var starts = TopLevelStart().Matches(code).Select(m => m.Index).Append(code.Length).ToList();
+ for (var s = 0; s + 1 < starts.Count; s++)
+ {
+ var text = code[starts[s]..starts[s + 1]];
+ var head = FunctionHead().Match(text);
+ if (!head.Success)
+ {
+ yield return (text.Split('\n')[0].Trim(), string.Empty, text);
+ continue;
+ }
+ var open = head.Index + head.Length - 1;
+ var close = open;
+ for (var level = 0; close < text.Length; close++)
+ {
+ if (text[close] == '(') level++;
+ else if (text[close] == ')' && --level == 0) break;
+ }
+ yield return (head.Groups[1].Value, text[(open + 1)..close], text[(close + 1)..]);
+ }
+ }
+
+ [GeneratedRegex(@"^[A-Za-z_$]", RegexOptions.Multiline)]
+ private static partial Regex TopLevelStart();
+
+ [GeneratedRegex(@"^(?:export\s+)?(?:async\s+)?function\s*\*?\s*([\w$]*)\s*\(")]
+ private static partial Regex FunctionHead();
+
+ /// The name api, not a member (x.api) nor part of a longer name.
+ [GeneratedRegex(@"(?A module that imports api or declares it at its top level.
+ [GeneratedRegex(@"^(?:import \{[^}]*(? \{\s*if \(running && e\.key === ""Escape""\) e\.preventDefault\(\);"), "Esc at keydown");
+ Assert.True(Regex.IsMatch(upload, @"const stopEscape = \(e\) => \{\s*if \(e\.key === ""Escape""\) e\.preventDefault\(\);"), "Esc at keydown");
+ var run = upload[upload.IndexOf("async function run()", StringComparison.Ordinal)..upload.IndexOf("function cancel()", StringComparison.Ordinal)];
+ Assert.True(Regex.IsMatch(run, @"running = true;(?:(?!finally).)*document\.addEventListener\(""keydown"", stopEscape, true\);", RegexOptions.Singleline),
+ "a run stops Esc on the document, in the capture phase");
+ Assert.True(Regex.IsMatch(run, @"finally \{(?:(?!\n \}).)*document\.removeEventListener\(""keydown"", stopEscape, true\);", RegexOptions.Singleline),
+ "the end of a run lets Esc close the dialog again");
+ Assert.True(Regex.IsMatch(upload, @"dialog\.addEventListener\(""close"", \(\) => \{(?:(?!\n \}\);).)*document\.removeEventListener\(""keydown"", stopEscape, true\);", RegexOptions.Singleline),
+ "closing the dialog takes its listener off the document");
+ Assert.False(upload.Contains(@"dialog.addEventListener(""keydown""", StringComparison.Ordinal), "Esc stopped only on the dialog");
Assert.Contains(@"err.code === ""upload_state""", upload);
Assert.Contains(@"api.get(`/api/v1/uploads/${uploadId}`)", upload);
Assert.Contains("sameContent.get(sha256)", upload);