fix(admin): complete web uploads, hold Esc during a run, keep focus and restores across job refreshes

The upload dialog's completion helper called `api`, which only exists inside
openUpload, so every web upload failed with a ReferenceError at its last step.
complete() now takes the dialog's api. A new test lexes every admin module and
fails when a top-level function uses api without taking it; it flags the old
upload.js.

During a run Esc is now stopped on the document in the capture phase. The old
listener sat on the dialog, so with the focus on the body (Start disables
itself, a click on the dialog's text) a second Esc closed the dialog and threw
the uploads away. The listener is added when a run starts and removed when it
ends or the dialog closes.

A sequence page refreshes after any ended job, because jobState names no
sequence. That refresh now redraws the header only when the sequence changed,
and the renders only when their list did. Stars, tags and renders are redrawn
through redraw(), so the keyboard focus stays put. restoreFocus finds an
unnamed control by its place, not as the first unnamed one. Failed thumbnails
are retried with a doubling wait and at most 8 tries, counted again once the
sequence changes.

The trash page reads the emptying it follows from /api/v1/jobs/{id} on every
load and after the event socket reconnects (api.events now emits
"reconnected"), so Empty no longer stays disabled when the job's end was lost.
A Restore in flight stays disabled across redraws.

The Library list counts cancelled jobs as ended (shared JOB_ENDED). Comments
are corrected in shared.js and library.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 641b9cd96b95d523990d1414c2bdead4138c5f4d)
This commit is contained in:
Alby96 committed 2026-10-27 13:53:41 +01:00
1 parent 4518ffe655
commit 81cf58227d
9 files changed
+379 -52

No files matched your search

+14 -1
View File
@@ -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 {
@@ -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();
}
@@ -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) => `<span class="tag" dir="auto">${escapeHtml(tag)}<button class="btn icon subtle tiny" type="button" data-remove="${i}"
title="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}" aria-label="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}">${icons.close}</button></span>`).join("");
redraw(tags, () => {
tags.innerHTML = seq.tags.map((tag, i) => `<span class="tag" dir="auto">${escapeHtml(tag)}<button class="btn icon subtle tiny" type="button" data-remove="${i}"
title="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}" aria-label="${attr(t("Admin.Sequence.RemoveTag.Tip", tag))}">${icons.close}</button></span>`).join("");
});
tags.querySelectorAll("[data-remove]").forEach((b) => b.addEventListener("click", () =>
patch({ tags: seq.tags.filter((_, i) => i !== Number(b.dataset.remove)) }, "tag-add")));
const rating = root.querySelector("#rating");
rating.innerHTML = [1, 2, 3, 4, 5].map((n) => `<button class="btn icon subtle star" type="button" id="star-${n}" data-star="${n}" aria-pressed="${n <= seq.rating}"
aria-label="${attr(plural("Admin.Sequence.Stars", n))}" title="${attr(t(n === seq.rating ? "Admin.Sequence.Unrate.Tip" : "Admin.Sequence.Rate.Tip", n))}">${n <= seq.rating ? icons.starFilled : icons.star}</button>`).join("");
redraw(rating, () => {
rating.innerHTML = [1, 2, 3, 4, 5].map((n) => `<button class="btn icon subtle star" type="button" id="star-${n}" data-star="${n}" aria-pressed="${n <= seq.rating}"
aria-label="${attr(plural("Admin.Sequence.Stars", n))}" title="${attr(t(n === seq.rating ? "Admin.Sequence.Unrate.Tip" : "Admin.Sequence.Rate.Tip", n))}">${n <= seq.rating ? icons.starFilled : icons.star}</button>`).join("");
});
rating.querySelectorAll("[data-star]").forEach((b) => b.addEventListener("click", () => {
const n = Number(b.dataset.star);
patch({ rating: n === seq.rating ? 0 : n }, `star-${n}`);
@@ -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") : `
<div class="table renders" role="table" aria-labelledby="renders-title">
<div class="thead" role="row"><span role="columnheader" data-i18n="Admin.Sequence.Render.Preset"></span>
@@ -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;
}
@@ -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;
@@ -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
<span class="col-by ellipsis" role="cell" dir="auto">${escapeHtml(e.deletedBy ?? "—")}</span>
<span class="muted nowrap" role="cell">${escapeHtml(formatDateTime(e.deletedAt))}</span>
<span class="row-actions" role="cell"><button class="btn small" data-restore="${attr(e.name)}" data-i18n="Admin.Trash.Restore"
data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}"></button></span>
data-i18n-title="${e.kind === "sequence" ? "Admin.Trash.RestoreSequence.Tip" : "Admin.Trash.RestorePhotos.Tip"}" ${restoring.has(e.name) ? "disabled" : ""}></button></span>
</div>`).join("")
|| `<div class="row" role="row"><div class="wide" role="cell">${emptyState("Admin.Trash.IsEmpty",
`<a class="btn small" href="${attr(back)}" data-i18n="Admin.Trash.Back" data-i18n-title="Admin.Trash.Back.Tip"></a>`)}</div></div>`;
@@ -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();
+4 -2
View File
@@ -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. */
+15 -11
View File
@@ -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 {
@@ -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);
}
/// <summary>
/// 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.
/// </summary>
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<int>();
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);
}
/// <summary>Whether the slash at <paramref name="at"/> starts a regular expression (after an operator or a keyword), not a division.</summary>
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";
}
/// <summary>
/// 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.
/// </summary>
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();
/// <summary>The name api, not a member (x.api) nor part of a longer name.</summary>
[GeneratedRegex(@"(?<![\w$.])api(?![\w$])")]
private static partial Regex ApiName();
/// <summary>A module that imports api or declares it at its top level.</summary>
[GeneratedRegex(@"^(?:import \{[^}]*(?<![\w$])api(?![\w$])[^}]*\} from|(?:export )?(?:const|let|var) api(?![\w$]))", RegexOptions.Multiline)]
private static partial Regex HasApi();
[Test]
public async Task TheTrashsRestoreTooltipsSayWhatIsChecked()
{
@@ -325,11 +325,21 @@ public sealed class BrowserUploadTests(TestContext context)
public async Task TheDialogKeepsItselfOpenAndSettlesWhatAnotherCompletionFiles()
{
// Owner review 2, R3 (upload.js): Esc is stopped at its keydown during a run, since Chromium lets a dialog's cancel be
// prevented only once per user activation; a completion refused while another one files the upload (409
// upload_state) waits for it instead of failing the photo; the same photo picked twice waits for its first copy.
// prevented only once per user activation, and on the document in the capture phase, since the focus may be on the
// body (a click on the dialog's text), where the dialog never sees the key; a completion refused while another one
// files the upload (409 upload_state) waits for it instead of failing the photo; the same photo picked twice waits
// for its first copy.
await using var server = await TestServer.StartAsync(context);
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.True(Regex.IsMatch(upload, @"addEventListener\(""keydown"", \(e\) => \{\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);