visual-regression-ci 0.0.0-stage → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +953 -2
  3. package/package.json +76 -4
  4. package/src/ci/actionReport.js +340 -0
  5. package/src/ci/prComment.js +420 -0
  6. package/src/cli/capture.js +243 -0
  7. package/src/cli/compare.js +190 -0
  8. package/src/cli/config.js +287 -0
  9. package/src/cli/database.js +69 -0
  10. package/src/cli/display.js +119 -0
  11. package/src/cli/errors.js +17 -0
  12. package/src/cli/index.js +577 -0
  13. package/src/cli/installBrowsers.js +59 -0
  14. package/src/cli/invocation.js +66 -0
  15. package/src/cli/jsonTarget.js +100 -0
  16. package/src/cli/logger.js +15 -0
  17. package/src/cli/manifest.js +139 -0
  18. package/src/cli/naming.js +60 -0
  19. package/src/cli/reporter.js +172 -0
  20. package/src/cli/result.js +225 -0
  21. package/src/cli/serve.js +64 -0
  22. package/src/server/app.js +135 -0
  23. package/src/server/db.js +691 -0
  24. package/src/server/importRuns.js +837 -0
  25. package/src/server/paths.js +107 -0
  26. package/src/server/public/css/styles.css +2362 -0
  27. package/src/server/public/js/common.js +32 -0
  28. package/src/server/public/js/dashboard.js +140 -0
  29. package/src/server/public/js/import-upload.js +169 -0
  30. package/src/server/public/js/review-actions.js +379 -0
  31. package/src/server/public/js/shortcuts.js +242 -0
  32. package/src/server/public/js/slider.js +104 -0
  33. package/src/server/public/js/tabs.js +85 -0
  34. package/src/server/public/js/theme.js +83 -0
  35. package/src/server/routes/api.js +141 -0
  36. package/src/server/routes/views.js +68 -0
  37. package/src/server/security.js +79 -0
  38. package/src/server/uploadImport.js +227 -0
  39. package/src/server/urls.js +31 -0
  40. package/src/server/viewModels.js +366 -0
  41. package/src/server/views/history.ejs +111 -0
  42. package/src/server/views/index.ejs +283 -0
  43. package/src/server/views/layout.ejs +11 -0
  44. package/src/server/views/partials/footer.ejs +11 -0
  45. package/src/server/views/partials/header.ejs +93 -0
  46. package/src/server/views/run-detail.ejs +295 -0
  47. package/src/shared/packageSpec.js +49 -0
  48. package/src/shared/text.js +59 -0
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Approve / Reject buttons on the run detail page, plus "Approve all pending" in the
3
+ * run header. Loaded as a module (deferred), so the DOM is already parsed when this runs.
4
+ *
5
+ * In the static GitHub Pages build (mode 'static') there is no server: the actions are
6
+ * simulated in the page, with the same UI update as a successful request, and reset
7
+ * on reload.
8
+ *
9
+ * Results are announced through the polite live region; errors are shown in the card's (or
10
+ * run header's) role="alert" region, never with a blocking alert().
11
+ */
12
+ import { api, announce, mode } from './common.js';
13
+
14
+ const APPROVE_LABEL = '<svg aria-hidden="true" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg><span>Approve & Update Baseline</span>';
15
+ const REJECT_LABEL = '<svg aria-hidden="true" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg><span>Reject</span>';
16
+
17
+ // Run status pills, matching run-detail.ejs
18
+ const RUN_STATUS_PILLS = {
19
+ PASSED: '<span class="status-pill status-pill-passed"><svg aria-hidden="true" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg><span>PASSED</span></span>',
20
+ APPROVED: '<span class="status-pill status-pill-approved"><svg aria-hidden="true" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg><span>APPROVED</span></span>',
21
+ FAILED: '<span class="status-pill status-pill-failed"><svg aria-hidden="true" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg><span>FAILED</span></span>',
22
+ REJECTED: '<span class="status-pill status-pill-rejected"><svg aria-hidden="true" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"></circle><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"></line></svg><span>REJECTED</span></span>'
23
+ };
24
+
25
+ const PENDING_STATUSES = ['DIFF', 'MISSING_BASELINE'];
26
+
27
+ // Required by the server's CSRF check (see src/server/security.js)
28
+ const WRITE_HEADERS = { 'X-Requested-With': 'visual-ci-dashboard' };
29
+
30
+ function postAction(snapId, action) {
31
+ return fetch(api(`/snapshots/${encodeURIComponent(snapId)}/${action}`), {
32
+ method: 'POST',
33
+ headers: WRITE_HEADERS
34
+ });
35
+ }
36
+
37
+ // The API answers with JSON, errors included; anything else (e.g. a proxy error page)
38
+ // becomes a failure result instead of a JSON parse error.
39
+ async function readJson(res) {
40
+ try {
41
+ return await res.json();
42
+ } catch {
43
+ return { success: false, error: `the server responded with HTTP ${res.status}` };
44
+ }
45
+ }
46
+
47
+ const DEMO_NOTE = 'Demo: nothing is saved, resets on reload';
48
+
49
+ // Live: POST to the API and return its JSON. Static demo: a synthetic success result.
50
+ async function sendAction(snapId, action) {
51
+ if (mode === 'static') {
52
+ return {
53
+ success: true,
54
+ simulated: true,
55
+ snapshot: { id: Number(snapId), status: action === 'approve' ? 'APPROVED' : 'REJECTED' }
56
+ };
57
+ }
58
+ const res = await postAction(snapId, action);
59
+ return readJson(res);
60
+ }
61
+
62
+ function showDemoNote(card) {
63
+ const actions = card?.querySelector('.snapshot-actions');
64
+ if (!actions || actions.querySelector('.demo-note')) return;
65
+ const note = document.createElement('span');
66
+ note.className = 'demo-note';
67
+ note.textContent = DEMO_NOTE;
68
+ actions.appendChild(note);
69
+ }
70
+
71
+ function snapshotLabel(card) {
72
+ const route = card?.querySelector('.route-pill')?.textContent.trim();
73
+ const viewport = card?.querySelector('.viewport-badge')?.textContent.trim();
74
+ return [route, viewport].filter(Boolean).join(' ') || 'Snapshot';
75
+ }
76
+
77
+ const snapshotCards = () => [...document.querySelectorAll('.snapshot-card')];
78
+
79
+ /**
80
+ * Errors go to the role="alert" region (rendered empty in run-detail.ejs) of the card or
81
+ * run header the button belongs to, instead of a blocking alert(). A new paragraph is
82
+ * inserted each time so repeating the same error is announced again.
83
+ *
84
+ * @param {Element} from - The button that was used
85
+ * @param {string|Node[]} content - Text, or nodes (e.g. text plus a button)
86
+ */
87
+ function showError(from, content) {
88
+ const region = from.closest('.snapshot-card, .detail-header-card')?.querySelector('[data-action-error]');
89
+ if (!region) return;
90
+ const p = document.createElement('p');
91
+ if (typeof content === 'string') p.textContent = content;
92
+ else p.append(...content);
93
+ region.replaceChildren(p);
94
+ }
95
+
96
+ function clearError(from) {
97
+ from.closest('.snapshot-card, .detail-header-card')?.querySelector('[data-action-error]')?.replaceChildren();
98
+ }
99
+
100
+ /**
101
+ * Keeps keyboard focus on the card when the focused button is disabled or removed by a
102
+ * successful action (focus would otherwise fall back to the top of the page).
103
+ */
104
+ function keepFocusInCard(card, hadFocus) {
105
+ if (!card || !hadFocus) return;
106
+ const active = document.activeElement;
107
+ if (!active || active === document.body || !card.contains(active) || active.disabled) card.focus();
108
+ }
109
+
110
+ /** Client-side mirror of recalculateRunStatus() in src/server/db.js (static demo only). */
111
+ function runStatusFromCards() {
112
+ const statuses = snapshotCards().map((c) => c.dataset.status);
113
+ if (statuses.includes('REJECTED')) return 'REJECTED';
114
+ if (statuses.some((s) => PENDING_STATUSES.includes(s))) return 'FAILED';
115
+ if (statuses.includes('APPROVED')) return 'APPROVED';
116
+ return 'PASSED';
117
+ }
118
+
119
+ /**
120
+ * Brings the run header in line with the cards: the run status pill, and the
121
+ * "Approve all pending (N)" button (hidden once nothing is pending).
122
+ *
123
+ * @param {string} [runStatus] - From the server; computed from the cards when omitted
124
+ */
125
+ function refreshRunHeader(runStatus = runStatusFromCards()) {
126
+ const container = document.querySelector('.run-status-container');
127
+ if (container && RUN_STATUS_PILLS[runStatus] && container.dataset.runStatus !== runStatus) {
128
+ container.dataset.runStatus = runStatus;
129
+ container.innerHTML = RUN_STATUS_PILLS[runStatus];
130
+ }
131
+
132
+ const approveAll = document.querySelector('.btn-approve-all');
133
+ if (!approveAll) return;
134
+ const pendingCards = snapshotCards().filter((c) => PENDING_STATUSES.includes(c.dataset.status));
135
+ const pending = pendingCards.length;
136
+ approveAll.dataset.count = String(pending);
137
+ const label = approveAll.querySelector('.approve-all-label');
138
+ if (label) label.textContent = `Approve all pending (${pending})`;
139
+ approveAll.hidden = pending === 0;
140
+
141
+ // Imported runs: "Approve all" stays blocked while a pending snapshot has a stale local
142
+ // baseline (run-detail.ejs); rejecting those snapshots unblocks it.
143
+ const stale = pendingCards.filter((c) => c.dataset.baselineStale === 'true').length;
144
+ const note = document.querySelector('[data-approve-all-stale]');
145
+ if (note) {
146
+ note.hidden = stale === 0;
147
+ const count = note.querySelector('[data-stale-count]');
148
+ if (count) count.textContent = String(stale);
149
+ }
150
+ if (stale === 0 && approveAll.classList.contains('is-blocked')) {
151
+ approveAll.classList.remove('is-blocked');
152
+ approveAll.removeAttribute('aria-describedby');
153
+ approveAll.disabled = false;
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Shows a snapshot card as approved: badge, "Baseline Promoted" in place of the
159
+ * Approve button, Reject removed. Used by single approve and approve-all alike.
160
+ *
161
+ * @returns {HTMLElement|null} The card, if it is on the page
162
+ */
163
+ function markApproved(snapId, { simulated = false } = {}) {
164
+ const card = document.getElementById(`snapshot-${snapId}`);
165
+ if (!card) return null;
166
+ card.dataset.status = 'APPROVED';
167
+
168
+ const badge = card.querySelector('.status-badge-container');
169
+ if (badge) {
170
+ badge.innerHTML = '<span class="status-pill status-pill-approved"><svg aria-hidden="true" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg><span>APPROVED</span></span>';
171
+ }
172
+
173
+ const btn = card.querySelector('.btn-approve');
174
+ if (btn) {
175
+ btn.disabled = true;
176
+ btn.innerHTML = '<span>✓ Baseline Promoted</span>';
177
+ btn.style.backgroundColor = 'transparent';
178
+ btn.style.borderColor = 'transparent';
179
+ btn.style.color = 'var(--success-green)';
180
+ btn.style.cursor = 'default';
181
+ }
182
+
183
+ // Disable corresponding reject button
184
+ const rejectBtn = card.querySelector('.btn-reject');
185
+ if (rejectBtn) rejectBtn.remove();
186
+
187
+ if (simulated) showDemoNote(card);
188
+ return card;
189
+ }
190
+
191
+ /** Shows a snapshot card as rejected (counterpart of markApproved). */
192
+ function markRejected(snapId, { simulated = false } = {}) {
193
+ const card = document.getElementById(`snapshot-${snapId}`);
194
+ if (!card) return null;
195
+ card.dataset.status = 'REJECTED';
196
+
197
+ const badge = card.querySelector('.status-badge-container');
198
+ if (badge) {
199
+ badge.innerHTML = '<span class="status-pill status-pill-rejected"><span>REJECTED</span></span>';
200
+ }
201
+
202
+ const btn = card.querySelector('.btn-reject');
203
+ if (btn) {
204
+ btn.disabled = true;
205
+ btn.innerHTML = '<span>✗ Rejected</span>';
206
+ btn.style.backgroundColor = 'transparent';
207
+ btn.style.borderColor = 'transparent';
208
+ btn.style.color = 'var(--error-red)';
209
+ btn.style.cursor = 'default';
210
+ }
211
+
212
+ // Disable corresponding approve button
213
+ const approveBtn = card.querySelector('.btn-approve');
214
+ if (approveBtn) approveBtn.remove();
215
+
216
+ if (simulated) showDemoNote(card);
217
+ return card;
218
+ }
219
+
220
+ /**
221
+ * Wires one Approve or Reject button. Success updates the card and is announced through
222
+ * the polite live region; failure goes to the card's role="alert" region and restores the
223
+ * button. Reject asks for confirmation first (also when triggered by the "r" shortcut).
224
+ */
225
+ function wireSnapshotAction(btn, { action, busyLabel, idleLabel, confirmMessage, mark, done, failed }) {
226
+ btn.addEventListener('click', async () => {
227
+ const snapId = btn.getAttribute('data-id');
228
+ if (!snapId) return;
229
+ if (confirmMessage && !confirm(confirmMessage)) return;
230
+
231
+ const card = btn.closest('.snapshot-card');
232
+ const btnHadFocus = document.activeElement === btn;
233
+ const hadFocus = btnHadFocus || Boolean(card?.contains(document.activeElement));
234
+ clearError(btn);
235
+ btn.disabled = true;
236
+ btn.textContent = busyLabel;
237
+
238
+ const restore = () => {
239
+ btn.disabled = false;
240
+ btn.innerHTML = idleLabel;
241
+ if (btnHadFocus) btn.focus();
242
+ };
243
+
244
+ try {
245
+ const data = await sendAction(snapId, action);
246
+
247
+ if (data.success) {
248
+ mark(snapId, { simulated: data.simulated });
249
+ refreshRunHeader(data.runStatus);
250
+ keepFocusInCard(card, hadFocus);
251
+ const label = snapshotLabel(card);
252
+ announce(data.simulated ? `${label} ${done} (simulated). ${DEMO_NOTE}.` : `${label} ${done}${action === 'approve' ? '. Baseline updated.' : '.'}`);
253
+ } else {
254
+ restore();
255
+ showError(btn, `${failed}: ${data.error || 'unknown error'}`);
256
+ }
257
+ } catch (err) {
258
+ restore();
259
+ showError(btn, `Network error: ${err.message}`);
260
+ }
261
+ });
262
+ }
263
+
264
+ document.querySelectorAll('.btn-approve').forEach((btn) => wireSnapshotAction(btn, {
265
+ action: 'approve',
266
+ busyLabel: 'Approving...',
267
+ idleLabel: APPROVE_LABEL,
268
+ mark: markApproved,
269
+ done: 'approved',
270
+ failed: 'Approval failed'
271
+ }));
272
+
273
+ document.querySelectorAll('.btn-reject').forEach((btn) => wireSnapshotAction(btn, {
274
+ action: 'reject',
275
+ busyLabel: 'Rejecting...',
276
+ idleLabel: REJECT_LABEL,
277
+ confirmMessage: 'Are you sure you want to reject this visual diff?',
278
+ mark: markRejected,
279
+ done: 'rejected',
280
+ failed: 'Rejection failed'
281
+ }));
282
+
283
+ // ─── Approve all pending ─────────────────────────────────────────────────────
284
+
285
+ // Live: POST /api/runs/:id/approve-all and return its JSON. Static demo: approve every
286
+ // pending card in the page.
287
+ async function sendApproveAll(runId) {
288
+ if (mode === 'static') {
289
+ const approved = snapshotCards()
290
+ .filter((c) => PENDING_STATUSES.includes(c.dataset.status))
291
+ .map((c) => Number(c.id.replace(/^snapshot-/, '')));
292
+ return { success: true, simulated: true, approved };
293
+ }
294
+ const res = await fetch(api(`/runs/${encodeURIComponent(runId)}/approve-all`), {
295
+ method: 'POST',
296
+ headers: WRITE_HEADERS
297
+ });
298
+ return readJson(res);
299
+ }
300
+
301
+ function conflictList(conflicts) {
302
+ return conflicts.map((c) => `${c.route} @ ${c.viewport}`);
303
+ }
304
+
305
+ const approveAllBtn = document.querySelector('.btn-approve-all');
306
+ if (approveAllBtn) {
307
+ approveAllBtn.addEventListener('click', async () => {
308
+ const runId = approveAllBtn.getAttribute('data-run-id');
309
+ const count = Number(approveAllBtn.dataset.count) || 0;
310
+ if (!runId || count === 0) return;
311
+
312
+ const noun = count === 1 ? 'snapshot' : 'snapshots';
313
+ if (!confirm(`Approve all ${count} pending ${noun} in this run? Their baselines will be replaced with this run's screenshots.`)) {
314
+ return;
315
+ }
316
+
317
+ const label = approveAllBtn.querySelector('.approve-all-label');
318
+ const hadFocus = document.activeElement === approveAllBtn;
319
+ const restoreLabel = () => {
320
+ approveAllBtn.disabled = false;
321
+ if (label) label.textContent = `Approve all pending (${approveAllBtn.dataset.count})`;
322
+ if (hadFocus) approveAllBtn.focus();
323
+ };
324
+ clearError(approveAllBtn);
325
+ approveAllBtn.disabled = true;
326
+ if (label) label.textContent = 'Approving...';
327
+
328
+ try {
329
+ const data = await sendApproveAll(runId);
330
+
331
+ if (data.success && !data.simulated && data.approved.length !== count) {
332
+ // The page was out of date (e.g. approved or rejected in another tab). The snapshots
333
+ // that WERE approved must still show it, so their Approve/Reject buttons can't act on
334
+ // a baseline that was just promoted; then offer a reload for the rest.
335
+ for (const id of data.approved) markApproved(id, { simulated: false });
336
+ refreshRunHeader(data.runStatus);
337
+ const reload = document.createElement('button');
338
+ reload.type = 'button';
339
+ reload.className = 'action-error-button';
340
+ reload.textContent = 'Reload page';
341
+ reload.addEventListener('click', () => window.location.reload());
342
+ showError(approveAllBtn, [
343
+ `This run changed since the page was loaded: ${data.approved.length} of ${count} snapshots were still pending and have been approved. Reload to see its current state. `,
344
+ reload
345
+ ]);
346
+ if (label) label.textContent = 'Out of date';
347
+ if (hadFocus) reload.focus();
348
+ return;
349
+ }
350
+
351
+ if (data.success) {
352
+ for (const id of data.approved) markApproved(id, { simulated: data.simulated });
353
+ refreshRunHeader(data.runStatus);
354
+ approveAllBtn.disabled = false;
355
+ // The button is hidden once nothing is pending: keep focus at the top of the content.
356
+ if (hadFocus) (approveAllBtn.hidden ? document.getElementById('main') : approveAllBtn)?.focus();
357
+
358
+ const n = data.approved.length;
359
+ const summary = `Approved ${n} ${n === 1 ? 'snapshot' : 'snapshots'}`;
360
+ if (data.simulated) {
361
+ announce(`${summary} (simulated). ${DEMO_NOTE}.`);
362
+ } else {
363
+ announce(`${summary}. Baselines updated; run is now ${data.runStatus}.`);
364
+ }
365
+ } else if (Array.isArray(data.conflicts) && data.conflicts.length) {
366
+ const pairs = conflictList(data.conflicts);
367
+ restoreLabel();
368
+ showError(approveAllBtn, `Nothing was approved. The baseline has changed since this run for ${pairs.join(', ')}. ` +
369
+ 'Re-run the visual tests and review the new result, or approve the other snapshots one at a time.');
370
+ } else {
371
+ restoreLabel();
372
+ showError(approveAllBtn, `Approve all failed: ${data.error || 'unknown error'}`);
373
+ }
374
+ } catch (err) {
375
+ restoreLabel();
376
+ showError(approveAllBtn, `Network error: ${err.message}`);
377
+ }
378
+ });
379
+ }
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Single-key keyboard shortcuts for the run detail page:
3
+ *
4
+ * j / k next / previous snapshot card (the first press goes to the first card still
5
+ * awaiting review, then every card in page order)
6
+ * a approve the current card (same as clicking its Approve button)
7
+ * r reject the current card (same as its Reject button, so it still asks to confirm)
8
+ * 1 2 3 side-by-side, slider or diff view of the current card
9
+ * ? help dialog (native <dialog>; Esc closes it)
10
+ *
11
+ * Keys are ignored while typing in a field, with Ctrl/Meta/Alt held, on auto-repeat and while
12
+ * a dialog is open. WCAG 2.1.4 (Character Key Shortcuts): the help dialog has a switch that
13
+ * turns them all off, remembered in localStorage; the "Press ? for keyboard shortcuts"
14
+ * button still opens the dialog, so they can be turned back on.
15
+ *
16
+ * Works in the static demo too: approve/reject go through the buttons, which
17
+ * review-actions.js simulates there. Deliberately no shortcut for "Approve all pending".
18
+ *
19
+ * Loaded as a module (deferred), so the DOM is already parsed when this runs.
20
+ */
21
+ import { announce } from './common.js';
22
+
23
+ const STORAGE_KEY = 'vrt:shortcuts-enabled';
24
+ const PENDING_STATUSES = ['DIFF', 'MISSING_BASELINE'];
25
+ const VIEW_KEYS = { 1: 'side-by-side', 2: 'slider', 3: 'diff' };
26
+
27
+ const dialog = document.getElementById('shortcuts-dialog');
28
+ const toggle = document.getElementById('shortcuts-enabled');
29
+ const hintButtons = [...document.querySelectorAll('[data-shortcuts-open]')];
30
+
31
+ // Storage can be unavailable (private mode, blocked site data): default to on.
32
+ function readEnabled() {
33
+ try {
34
+ return localStorage.getItem(STORAGE_KEY) !== 'false';
35
+ } catch {
36
+ return true;
37
+ }
38
+ }
39
+
40
+ function writeEnabled(value) {
41
+ try {
42
+ localStorage.setItem(STORAGE_KEY, String(value));
43
+ } catch {
44
+ // Not persisted; the setting still applies until the page is reloaded.
45
+ }
46
+ }
47
+
48
+ let enabled = readEnabled();
49
+
50
+ function renderEnabled() {
51
+ if (toggle) toggle.checked = enabled;
52
+ for (const btn of hintButtons) {
53
+ btn.innerHTML = enabled
54
+ ? 'Press <kbd>?</kbd> for keyboard shortcuts'
55
+ : 'Keyboard shortcuts are off';
56
+ }
57
+ }
58
+
59
+ // ─── Current card ───────────────────────────────────────────────────────────
60
+
61
+ const cards = () => [...document.querySelectorAll('.snapshot-card')];
62
+ const currentCard = () => document.querySelector('.snapshot-card.is-current');
63
+ const label = (card) => card.querySelector('h2')?.textContent.trim().replace(/^Snapshot /, '') || 'snapshot';
64
+
65
+ // The card that j/k is currently scrolling into view (a smooth scroll can still be
66
+ // running when the next key arrives). Any scrolling by the reviewer cancels it.
67
+ let scrollingTo = null;
68
+ const cancelOwnScroll = () => { scrollingTo = null; };
69
+ window.addEventListener('scrollend', cancelOwnScroll);
70
+ for (const type of ['wheel', 'touchmove']) window.addEventListener(type, cancelOwnScroll, { passive: true });
71
+ window.addEventListener('keydown', (e) => {
72
+ if (['PageDown', 'PageUp', ' ', 'Home', 'End', 'ArrowDown', 'ArrowUp'].includes(e.key)) cancelOwnScroll();
73
+ }, true);
74
+
75
+ function setCurrent(card, { focus = true } = {}) {
76
+ for (const c of cards()) {
77
+ const isCurrent = c === card;
78
+ c.classList.toggle('is-current', isCurrent);
79
+ if (isCurrent) c.setAttribute('aria-current', 'true');
80
+ else c.removeAttribute('aria-current');
81
+ }
82
+ if (focus) {
83
+ card.focus({ preventScroll: true });
84
+ const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
85
+ scrollingTo = card;
86
+ card.scrollIntoView({ block: 'start', behavior: reduceMotion ? 'auto' : 'smooth' });
87
+ }
88
+ }
89
+
90
+ function move(step) {
91
+ const all = cards();
92
+ if (all.length === 0) return;
93
+ const current = currentCard();
94
+ let target;
95
+ if (!current) {
96
+ // Start where the review work is: the first (j) or last (k) pending card.
97
+ const pending = all.filter((c) => PENDING_STATUSES.includes(c.dataset.status));
98
+ const pool = pending.length ? pending : all;
99
+ target = step > 0 ? pool[0] : pool[pool.length - 1];
100
+ } else {
101
+ target = all[all.indexOf(current) + step];
102
+ if (!target) {
103
+ announce(step > 0 ? 'Last snapshot.' : 'First snapshot.');
104
+ current.focus({ preventScroll: true });
105
+ return;
106
+ }
107
+ }
108
+ setCurrent(target);
109
+ }
110
+
111
+ function requireCurrent() {
112
+ const card = currentCard();
113
+ if (!card) announce('No snapshot selected. Press j to go to the next snapshot.');
114
+ return card;
115
+ }
116
+
117
+ /**
118
+ * True when at least part of the card is inside the viewport, or j/k is still scrolling
119
+ * it into view (the reviewer asked for it and hasn't scrolled elsewhere since).
120
+ */
121
+ function isOnScreen(card) {
122
+ if (scrollingTo === card) return true;
123
+ const rect = card.getBoundingClientRect();
124
+ return rect.bottom > 0 && rect.top < window.innerHeight;
125
+ }
126
+
127
+ function clickAction(selector, verb) {
128
+ const card = requireCurrent();
129
+ if (!card) return;
130
+ if (!isOnScreen(card)) {
131
+ // The reviewer scrolled away from the current snapshot (mouse wheel, scrollbar,
132
+ // Page Down): never approve or reject something they can't see. Bring it back first.
133
+ card.scrollIntoView({ block: 'start' });
134
+ announce(`Showing ${label(card)} again. Press the key again to ${verb} it.`);
135
+ return;
136
+ }
137
+ const btn = card.querySelector(selector);
138
+ if (!btn || btn.disabled) {
139
+ announce(`Nothing to ${verb} for ${label(card)}.`);
140
+ return;
141
+ }
142
+ btn.click();
143
+ }
144
+
145
+ function showView(key) {
146
+ const card = requireCurrent();
147
+ if (!card) return;
148
+ const tab = card.querySelector(`[role="tab"][data-tab="${key}"]`);
149
+ if (!tab) {
150
+ announce(`No ${key} view for ${label(card)}.`);
151
+ return;
152
+ }
153
+ const hadFocusInside = card.contains(document.activeElement);
154
+ tab.click();
155
+ // The panel that held focus may now be hidden (focus can linger on the hidden element
156
+ // until the browser drops it to <body>): move it to the card itself.
157
+ const active = document.activeElement;
158
+ if (hadFocusInside && (!card.contains(active) || active?.closest('[hidden]'))) card.focus({ preventScroll: true });
159
+ announce(`${tab.textContent.trim()} view.`);
160
+ }
161
+
162
+ // ─── Help dialog ────────────────────────────────────────────────────────────
163
+
164
+ let returnFocusTo = null;
165
+
166
+ function openHelp() {
167
+ if (!dialog || dialog.open) return;
168
+ returnFocusTo = document.activeElement;
169
+ dialog.showModal();
170
+ dialog.querySelector('[data-shortcuts-close]')?.focus();
171
+ }
172
+
173
+ if (dialog) {
174
+ dialog.querySelector('[data-shortcuts-close]')?.addEventListener('click', () => dialog.close());
175
+ // A click on the backdrop lands on the <dialog> element itself (as do clicks on its
176
+ // padding, hence the bounds check).
177
+ dialog.addEventListener('click', (e) => {
178
+ if (e.target !== dialog) return;
179
+ const r = dialog.getBoundingClientRect();
180
+ const inside = e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom;
181
+ if (!inside) dialog.close();
182
+ });
183
+ dialog.addEventListener('close', () => {
184
+ const target = returnFocusTo && document.contains(returnFocusTo) ? returnFocusTo : null;
185
+ returnFocusTo = null;
186
+ target?.focus({ preventScroll: true });
187
+ });
188
+ }
189
+
190
+ for (const btn of hintButtons) btn.addEventListener('click', openHelp);
191
+
192
+ toggle?.addEventListener('change', () => {
193
+ enabled = toggle.checked;
194
+ writeEnabled(enabled);
195
+ renderEnabled();
196
+ announce(enabled ? 'Keyboard shortcuts on.' : 'Keyboard shortcuts off.');
197
+ });
198
+
199
+ // ─── Key handling ───────────────────────────────────────────────────────────
200
+
201
+ function isTyping(target) {
202
+ if (!(target instanceof Element)) return false;
203
+ return target.isContentEditable || Boolean(target.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])'));
204
+ }
205
+
206
+ document.addEventListener('keydown', (e) => {
207
+ if (!enabled || e.defaultPrevented || e.repeat || e.isComposing) return;
208
+ if (e.ctrlKey || e.metaKey || e.altKey) return;
209
+ if (document.querySelector('dialog[open]')) return; // Esc there is the dialog's own
210
+ if (isTyping(e.target)) return;
211
+
212
+ if (e.key === 'j') move(1);
213
+ else if (e.key === 'k') move(-1);
214
+ else if (e.key === 'a') clickAction('.btn-approve', 'approve');
215
+ else if (e.key === 'r') clickAction('.btn-reject', 'reject');
216
+ else if (Object.hasOwn(VIEW_KEYS, e.key)) showView(VIEW_KEYS[e.key]);
217
+ else if (e.key === '?') openHelp();
218
+ else return;
219
+ e.preventDefault();
220
+ });
221
+
222
+ // Clicking or tabbing into a card makes it the current one, so a/r/1-3 act on the card
223
+ // the reviewer is looking at. So does arriving from a history link (#snapshot-<id>).
224
+ document.addEventListener('focusin', (e) => {
225
+ const card = e.target instanceof Element ? e.target.closest('.snapshot-card') : null;
226
+ if (card && !card.classList.contains('is-current')) setCurrent(card, { focus: false });
227
+ });
228
+ document.addEventListener('pointerdown', (e) => {
229
+ const card = e.target instanceof Element ? e.target.closest('.snapshot-card') : null;
230
+ if (card && !card.classList.contains('is-current')) setCurrent(card, { focus: false });
231
+ });
232
+ renderEnabled();
233
+
234
+ let fromHash = null;
235
+ if (window.location.hash.startsWith('#snapshot-')) {
236
+ try {
237
+ fromHash = document.getElementById(decodeURIComponent(window.location.hash.slice(1)));
238
+ } catch {
239
+ // Malformed percent-encoding in the URL: just ignore the hash.
240
+ }
241
+ }
242
+ if (fromHash?.classList.contains('snapshot-card')) setCurrent(fromHash, { focus: false });