diff --git a/.gitignore b/.gitignore index dbd64df..55624f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ test-results/ playwright-report/ +dist/ diff --git a/README.md b/README.md index 6fd59fb..0fdc62f 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,26 @@ npm start -- --repo ~/code/ionic-framework --pr 31321 Press ? in the app for what each marker means and the keyboard shortcuts. +### Exporting a static site + +`export` writes the same review as plain files, for hosting where there is no clone to read from. + +```sh +npm run export -- --base origin/main --head my-branch +npm run export -- --base --head --out dist --label '#31321 fix(item): ...' --url +``` + +| Option | | +| ------------------------------- | ----------------------------------------------------------------------------------------- | +| `--base `, `--head ` | Required. A pull request number is not accepted. | +| `--out ` | Defaults to `dist`. An earlier export there is replaced, but any other files are refused. | +| `--label `, `--url ` | The header title and its link. Default to the refs. | +| `--repo`, `--path` | Same as above. | + +The exported page is read-only. Viewed marks stay in the browser, and a newer push is noticed when the deployment's `head.json` names a different commit. + +When `--url` is a pull request, the page loads its comments from GitHub's public API each time it opens, with no comment box. That API allows 60 requests an hour per network, one request per 100 comments, and can't say whether a thread is resolved. A range with no changed screenshots writes nothing and exits successfully. + ### Why it needs a local clone The clone is where everything is read from: diff --git a/eslint.config.js b/eslint.config.js index ace0816..2da3f7c 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -5,7 +5,7 @@ import playwright from 'eslint-plugin-playwright'; import globals from 'globals'; export default [ - { ignores: ['node_modules/**', 'playwright-report/**', 'test-results/**'] }, + { ignores: ['node_modules/**', 'playwright-report/**', 'test-results/**', 'dist/**'] }, js.configs.recommended, importPlugin.flatConfigs.recommended, diff --git a/package-lock.json b/package-lock.json index 7cc8c28..7dc362f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ "eslint-plugin-playwright": "^2.12.0", "globals": "^17.13.0", "prettier": "^3.9.9", + "sirv-cli": "^3.0.1", "stylelint": "^16.26.1", "stylelint-order": "^7.0.1", "typescript": "^7.0.2" @@ -1330,6 +1331,16 @@ "dev": true, "license": "MIT" }, + "node_modules/console-clear": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/console-clear/-/console-clear-1.1.1.tgz", + "integrity": "sha512-pMD+MVR538ipqkG5JXeOEbKWS5um1H4LUUccUQG68qpeqBYbzYy79Gh55jkd2TtPdRfUaLWdv6LPP//5Zt0aPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/cosmiconfig": { "version": "9.0.2", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz", @@ -2304,6 +2315,19 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-port": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz", + "integrity": "sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", @@ -3193,6 +3217,16 @@ "node": ">=0.10.0" } }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/known-css-properties": { "version": "0.37.0", "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.37.0.tgz", @@ -3221,6 +3255,16 @@ "dev": true, "license": "MIT" }, + "node_modules/local-access": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/local-access/-/local-access-1.1.0.tgz", + "integrity": "sha512-XfegD5pyTAfb+GY6chk283Ox5z8WexG56OvM06RWLpAc/UHozO8X6xAxEkIitZOtsSMM1Yr3DkHgW5W+onLhCw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", @@ -3339,6 +3383,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/mrmime": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/mrmime/-/mrmime-2.0.1.tgz", @@ -4035,6 +4089,19 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/safe-array-concat": { "version": "1.1.4", "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz", @@ -4090,6 +4157,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/semiver": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/semiver/-/semiver-1.1.0.tgz", + "integrity": "sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", @@ -4275,6 +4352,29 @@ "node": ">=18" } }, + "node_modules/sirv-cli": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/sirv-cli/-/sirv-cli-3.0.1.tgz", + "integrity": "sha512-ICXaF2u6IQhLZ0EXF6nqUF4YODfSQSt+mGykt4qqO5rY+oIiwdg7B8w2PVDBJlQulaS2a3J8666CUoDoAuCGvg==", + "dev": true, + "license": "MIT", + "dependencies": { + "console-clear": "^1.1.0", + "get-port": "^5.1.1", + "kleur": "^4.1.4", + "local-access": "^1.0.1", + "sade": "^1.6.0", + "semiver": "^1.0.0", + "sirv": "^3.0.0", + "tinydate": "^1.0.0" + }, + "bin": { + "sirv": "bin.js" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", @@ -4658,6 +4758,16 @@ "dev": true, "license": "MIT" }, + "node_modules/tinydate": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/tinydate/-/tinydate-1.3.0.tgz", + "integrity": "sha512-7cR8rLy2QhYHpsBDBVYnnWXm8uRTr38RoZakFSW7Bs7PzfMPNZthuMLkwqZv7MTu8lhQ91cOFYS5a7iFj2oR3w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", diff --git a/package.json b/package.json index 325a3c1..8bf41fa 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ }, "scripts": { "start": "node src/cli.mjs", + "export": "node src/cli.mjs export", "lint": "eslint . && stylelint \"src/**/*.css\" && prettier \"./**/*.{html,js,mjs,css}\" --write --cache", "lint.fix": "eslint . --fix && stylelint \"src/**/*.css\" --fix && prettier \"./**/*.{html,js,mjs,css}\" --write --cache", "test": "npm run test.spec && npm run test.e2e", @@ -35,6 +36,7 @@ "eslint-plugin-playwright": "^2.12.0", "globals": "^17.13.0", "prettier": "^3.9.9", + "sirv-cli": "^3.0.1", "stylelint": "^16.26.1", "stylelint-order": "^7.0.1", "typescript": "^7.0.2" diff --git a/src/cli.mjs b/src/cli.mjs index f4fbb18..281b1b7 100644 --- a/src/cli.mjs +++ b/src/cli.mjs @@ -1,14 +1,18 @@ #!/usr/bin/env node /* - * Entry point for npm start. Kept apart from index.mjs so tests can import the - * server's pieces without starting it. + * Entry point for npm start and npm run export. Kept apart from index.mjs so tests can + * import the server's pieces without starting it. * + * - `export` as the first argument writes a static site instead of serving. * - Any startup failure, such as no clone found or no screenshots in the range, * prints as one line and exits with code 1. */ +import { exportSite } from './export.mjs'; import { main } from './index.mjs'; -main().catch((error) => { +const run = process.argv[2] === 'export' ? () => exportSite(process.argv.slice(3)) : main; + +run().catch((error) => { process.stderr.write(`\n ${error.message}\n\n`); process.exit(1); }); diff --git a/src/client/app.js b/src/client/app.js index 01f0ab1..271c3c4 100644 --- a/src/client/app.js +++ b/src/client/app.js @@ -3,14 +3,17 @@ * * - The comment box, teammates' comments and the c shortcut appear only for a pull * request with gh signed in. Viewed marks work in every case. + * - A static export shows teammates' comments, read only, when its --url named a pull + * request. It never has a comment box. * - If a push changed screenshots since they were marked viewed, the sidebar says how * many lost their mark. * - The orphans only and encoding only checkboxes appear only when there is one. - * - A newer push is checked for on load and whenever the tab regains focus. + * - A newer push is checked for on load and whenever the tab regains focus. A static + * export also checks when an image fails to load. * - Every image is prefetched after the first render, so stepping through stays * instant. */ -import { renderPublish, wireComments } from './scripts/comments.js'; +import { loadThreads, renderPublish, wireComments } from './scripts/comments.js'; import { wireControls } from './scripts/controls.js'; import { dom } from './scripts/dom.js'; import { indexGroups, reencodedOnly } from './scripts/entries.js'; @@ -20,7 +23,7 @@ import { blobUrl } from './scripts/links.js'; import { renderList, renderProgress } from './scripts/list.js'; import { restoreMode, select } from './scripts/stage.js'; import { state } from './scripts/state.js'; -import { checkFreshness } from './scripts/sync.js'; +import { checkFreshness, restoreViewed } from './scripts/sync.js'; import { restoreTheme } from './scripts/theme.js'; /** @@ -35,16 +38,22 @@ const init = async () => { window.addEventListener('focus', checkFreshness); - const manifest = await fetch('/api/manifest').then((response) => response.json()); + const manifest = await fetch('manifest.json', { cache: 'no-cache' }).then((response) => response.json()); + + state.static = manifest.static === true; + /* A static export has no server to keep marks, so this browser keeps them, and + reports the ones a push undid the same way the server does. */ + const local = state.static ? restoreViewed(manifest.entries) : null; + const saved = local ?? manifest.state; state.head = manifest.head ?? null; state.blobBase = manifest.blobBase ?? null; state.entries = manifest.entries; - state.viewed = new Set(Object.keys(manifest.state.viewed ?? {})); - state.comments = new Map(Object.entries(manifest.state.comments ?? {})); - state.stale = new Set(manifest.state.stale ?? []); - state.unsent = new Set(manifest.state.unsent ?? []); - state.posted = new Set(manifest.state.posted ?? []); + state.viewed = new Set(Object.keys(saved.viewed ?? {})); + state.comments = new Map(Object.entries(saved.comments ?? {})); + state.stale = new Set(saved.stale ?? []); + state.unsent = new Set(saved.unsent ?? []); + state.posted = new Set(saved.posted ?? []); state.threads = manifest.threads ?? {}; state.pr = manifest.pr ?? null; state.prState = manifest.prState ?? null; @@ -55,12 +64,15 @@ const init = async () => { never leave this machine. Viewed stays either way: it is how a range is worked through, pull request or not. */ dom.commentSection.hidden = !state.pr || !state.viewer; + /* Read only, so the section shows threads and nothing to type into. renderThreads + opens it on a screenshot that has some. */ + dom.comment.hidden = state.static; renderPublish(); /* Only the screenshots that lost their tick are worth saying out loud. Carrying progress over is the expected outcome and needs no announcement; ticks vanishing without explanation does. */ - const { reset = 0 } = manifest.carriedOver ?? {}; + const { reset = 0 } = local ?? manifest.carriedOver ?? {}; if (reset) { dom.carried.hidden = false; dom.carried.textContent = `${reset} ${ @@ -97,12 +109,33 @@ const init = async () => { reported without waiting for the reviewer to mark something. */ checkFreshness(); + /* Not awaited: comments arrive whenever GitHub answers, and the prefetch below + shouldn't wait on them. */ + if (state.static && manifest.pullRequest) { + loadThreads(manifest.pullRequest); + } + + /* A deployment replaced by a newer push serves only that push's images, so one that + fails to load is often the first sign of it. An empty src fires error too, and is + only a side with nothing to show. */ + if (state.static) { + dom.stage.addEventListener( + 'error', + (event) => { + if (/** @type {HTMLImageElement} */ (event.target).getAttribute('src')) { + checkFreshness(); + } + }, + true + ); + } + /* Warm the cache so stepping through hundreds of screenshots stays instant. */ const queue = state.entries .flatMap((entry) => [ - entry.status === 'A' ? null : blobUrl('expected', entry.path), - entry.status === 'D' ? null : blobUrl('actual', entry.path), - entry.comparable ? blobUrl('diff', entry.path) : null, + entry.status === 'A' ? null : blobUrl('expected', entry), + entry.status === 'D' ? null : blobUrl('actual', entry), + entry.comparable ? blobUrl('diff', entry) : null, ]) .filter(Boolean); diff --git a/src/client/index.html b/src/client/index.html index aa6812f..4eb4f45 100644 --- a/src/client/index.html +++ b/src/client/index.html @@ -53,6 +53,7 @@ +
@@ -211,7 +212,8 @@

Filters

What needs GitHub

  • - Marking viewed always works. It is kept in a local file, so the directory ticks, the progress bar, + Marking viewed always works. It is kept in a local file, or in this browser on a hosted review, so the + directory ticks, the progress bar, Hide viewed, v and V behave the same however the review was started.
  • @@ -231,6 +233,10 @@

    What needs GitHub

    Signed out, a new push is noticed more slowly, because GitHub allows far fewer anonymous requests and the check is spaced out to stay within them.
  • +
  • + A hosted review shows the pull request's comments, read anonymously from GitHub when the page opens, but has + no comment box. It can't tell which threads are resolved, so none is marked resolved. +

Keyboard

diff --git a/src/client/scripts/comments.js b/src/client/scripts/comments.js index 6ed889e..4015efd 100644 --- a/src/client/scripts/comments.js +++ b/src/client/scripts/comments.js @@ -16,6 +16,11 @@ * after confirming, and stays here if GitHub refuses. * - Teammates' comments are read only, with resolved and outdated threads marked. * Their HTML is rebuilt from an allowlist: no images, and only http(s) links. + * - A static export has no comment box. It loads the pull request's comments from + * GitHub's public API when the page opens, one request per 100 comments, and shows + * the section only on a screenshot that has some. That API can't say whether a + * thread is resolved, so none is marked resolved. If GitHub refuses, the sidebar + * says so. */ import { dom } from './dom.js'; import { refreshRow } from './list.js'; @@ -112,6 +117,10 @@ const sanitize = (html) => { export const renderThreads = () => { const threads = state.threads[state.current] ?? []; dom.threads.hidden = threads.length === 0; + /* With no comment box, the section is only these threads. */ + if (state.static) { + dom.commentSection.hidden = threads.length === 0; + } if (threads.length === 0) { return; @@ -169,6 +178,85 @@ export const renderThreads = () => { dom.threads.replaceChildren(...nodes); }; +/* Anonymous reads allow 60 an hour per network, which an office can share. */ +const LIMITED = 'GitHub is limiting requests from this network, so comments are not shown. Reload later to try again.'; +const UNAVAILABLE = 'Comments could not be loaded from GitHub. Reload to try again.'; + +/** + * Loads a pull request's review comments for a static export, from GitHub's public API, + * and shows them on the screenshots in this review. + * @param {{ repo: string, number: number }} pullRequest + * @returns {Promise} + */ +export const loadThreads = async ({ repo, number }) => { + const inReview = new Set(state.entries.map((entry) => entry.path)); + /* Each thread by the id of its first comment, which is what a reply names. */ + const roots = new Map(); + + try { + /* A guard rather than a limit anyone should reach: 20 pages is 2,000 comments. */ + for (let page = 1; page <= 20; page++) { + const response = await fetch( + `https://api.github.com/repos/${repo}/pulls/${number}/comments?per_page=100&page=${page}`, + { headers: { accept: 'application/vnd.github.html+json' } } + ); + if (!response.ok) { + throw new Error(response.status === 403 || response.status === 429 ? LIMITED : UNAVAILABLE); + } + + const comments = await response.json(); + + /* Oldest first, and a reply always names its thread's first comment, so the + thread exists by the time its replies arrive. */ + for (const comment of comments) { + const root = roots.get(comment.in_reply_to_id); + if (!root && !inReview.has(comment.path)) { + continue; + } + + const item = { + author: comment.user?.login ?? 'unknown', + body: comment.body_html, + url: comment.html_url, + createdAt: comment.created_at, + mine: false, + }; + + if (root) { + root.thread.comments.push(item); + } else { + /* GitHub moves a comment to each new push until the file changes under it, + so one left on an earlier commit is outdated. */ + roots.set(comment.id, { + path: comment.path, + thread: { resolved: false, outdated: comment.commit_id !== state.head, comments: [item] }, + }); + } + } + + if (comments.length < 100) { + break; + } + } + } catch (error) { + /* Anything but the rate limit, offline included, gets the plain sentence. */ + dom.threadsFailed.hidden = false; + dom.threadsFailed.textContent = error.message === LIMITED ? LIMITED : UNAVAILABLE; + return; + } + + const threads = {}; + for (const { path, thread } of roots.values()) { + (threads[path] ??= []).push(thread); + } + state.threads = threads; + + for (const path of Object.keys(threads)) { + refreshRow(path); + } + renderThreads(); +}; + /** * Shows Delete when there is a comment, labelled for the pull request when it is posted * there. diff --git a/src/client/scripts/dom.js b/src/client/scripts/dom.js index 6f2745a..2cac443 100644 --- a/src/client/scripts/dom.js +++ b/src/client/scripts/dom.js @@ -68,6 +68,7 @@ const IDS = /** @type {const} */ ([ 'commentState', 'deleteComment', 'threads', + 'threadsFailed', ]); /** diff --git a/src/client/scripts/links.js b/src/client/scripts/links.js index cc71dd1..67d61ca 100644 --- a/src/client/scripts/links.js +++ b/src/client/scripts/links.js @@ -5,8 +5,9 @@ * gets plain captions and no test link. * - The test link opens the spec at the line that took the screenshot, or the whole * spec when the line can't be found. It is hidden when the spec is gone. - * - Image URLs carry the head commit, so after Refresh the browser never shows an - * image cached from the previous push. + * - Image URLs are named by content, the same on the server and in a static export. + * A push that changes a screenshot gives it a new URL, so after Refresh the browser + * never shows an image cached from the previous push. */ import { dom } from './dom.js'; import { state } from './state.js'; @@ -77,10 +78,13 @@ export const setCaptionLink = (label, side, path, status) => { }; /** - * This server's URL for one side of a screenshot. The commit is in the query, so a - * refresh never serves an image cached from the previous push. + * The URL for one side of a screenshot: expected and actual by blob id, the diff by + * the pair. * @param {'expected' | 'actual' | 'diff'} side - * @param {string} path + * @param {Entry} entry * @returns {string} */ -export const blobUrl = (side, path) => `/blob?side=${side}&path=${encodeURIComponent(path)}&v=${state.head ?? ''}`; +export const blobUrl = (side, entry) => + side === 'diff' + ? `diffs/${entry.expectedSha}-${entry.actualSha}.png` + : `images/${side === 'expected' ? entry.expectedSha : entry.actualSha}.png`; diff --git a/src/client/scripts/stage.js b/src/client/scripts/stage.js index 0a1dde9..f528f0e 100644 --- a/src/client/scripts/stage.js +++ b/src/client/scripts/stage.js @@ -144,8 +144,8 @@ export const select = (path, { scroll = true } = {}) => { : `was ${entry.oldStem}`; dom.crumbRenamed.title = entry.oldPath ?? ''; - const expected = entry.status === 'A' ? null : blobUrl('expected', entry.path); - const actual = entry.status === 'D' ? null : blobUrl('actual', entry.path); + const expected = entry.status === 'A' ? null : blobUrl('expected', entry); + const actual = entry.status === 'D' ? null : blobUrl('actual', entry); /* The baseline is hidden when it would be the same picture twice. */ dom.figExpected.hidden = !expected || (entry.comparable && entry.ratio === 0); @@ -167,7 +167,7 @@ export const select = (path, { scroll = true } = {}) => { dom.onionSizer.src = (entry.actualSize?.height ?? 0) >= (entry.expectedSize?.height ?? 0) ? actual : expected; dom.onionExpected.src = expected; dom.onionActual.src = actual; - dom.diffImage.src = blobUrl('diff', entry.path); + dom.diffImage.src = blobUrl('diff', entry); dom.diffCount.textContent = entry.changed === null ? '' : `${entry.changed.toLocaleString()} pixels`; dom.notice.classList.remove('show'); } else { diff --git a/src/client/scripts/state.js b/src/client/scripts/state.js index 58ebac3..86f88d4 100644 --- a/src/client/scripts/state.js +++ b/src/client/scripts/state.js @@ -3,7 +3,8 @@ * * - Filled from the manifest on load, and again after Refresh reloads the page. * - Nothing here is saved by itself. Viewed marks and comments persist through the - * server, and preferences through localStorage in their own scripts. + * server, or in this browser for a static export, and preferences through + * localStorage in their own scripts. */ /** @@ -78,7 +79,10 @@ export const state = { palette: new Set(), }, current: null, - /* The commit this page is showing, used to version image URLs. */ + /* Read from a static export: no server behind the page, so marks stay in this + browser and there are no comments. */ + static: false, + /* The commit this page is showing, so a static export can tell a newer push. */ head: null, /* Repo and the two commits, when they are pushed and can be linked to. */ blobBase: null, diff --git a/src/client/scripts/sync.js b/src/client/scripts/sync.js index 4213bf5..877c7a1 100644 --- a/src/client/scripts/sync.js +++ b/src/client/scripts/sync.js @@ -9,20 +9,100 @@ * something just marked, naming the file if it was one, and quiet otherwise. * - Refresh rebuilds the review on the newer push and reloads. If that fails, the * button says so and the current review stays. + * - A static export has no server. Viewed marks are kept in this browser under the + * same rule the server applies: a mark survives only while its screenshot is + * unchanged. A newer push is noticed when head.json names another commit, and + * Refresh only reloads. */ import { fileOf } from './comments.js'; import { dom } from './dom.js'; +import { entryFor } from './entries.js'; import { select } from './stage.js'; import { state } from './state.js'; +/** @typedef {import('./state.js').Entry} Entry */ + +const VIEWED_KEY = 'snapshot-review-viewed'; + +/** + * A static export's viewed marks, each with the blobs it was marked against. + * @type {Record} + */ +let marks = {}; + +/** Writes the marks back. A browser that refuses storage keeps them for this visit only. */ +const saveMarks = () => { + try { + localStorage.setItem(VIEWED_KEY, JSON.stringify(marks)); + } catch { + /* Private mode, or storage blocked. */ + } +}; + +/** + * Reads a static export's viewed marks from this browser, keeping each only while its + * screenshot is unchanged, and drops the rest. + * @param {Entry[]} entries + * @returns {{ viewed: Record, reset: number }} `reset` counts the marks a push undid. + */ +export const restoreViewed = (entries) => { + let stored = {}; + try { + stored = JSON.parse(localStorage.getItem(VIEWED_KEY) ?? '{}') ?? {}; + } catch { + stored = {}; + } + + const viewed = {}; + let reset = 0; + marks = {}; + + for (const entry of entries) { + const record = stored[entry.path]; + if (!record) { + continue; + } + + if (record.expectedSha === entry.expectedSha && record.actualSha === entry.actualSha) { + viewed[entry.path] = true; + marks[entry.path] = record; + } else { + reset++; + } + } + + /* Rewritten from the survivors, so marks on screenshots that left the review do not + accumulate. */ + saveMarks(); + return { viewed, reset }; +}; + /** * Saves a viewed or comment change, then reports a newer push or a failed GitHub sync - * from the reply. + * from the reply. A static export saves viewed marks in this browser instead. * @param {{ path?: string, paths?: string[], viewed?: boolean, comment?: string }} patch * @returns {Promise} */ -export const persist = (patch) => - fetch('/api/state', { +export const persist = (patch) => { + if (state.static) { + const paths = patch.paths ?? (patch.path ? [patch.path] : []); + + if (patch.viewed !== undefined) { + for (const path of paths) { + const entry = entryFor(path); + if (patch.viewed && entry) { + marks[path] = { expectedSha: entry.expectedSha, actualSha: entry.actualSha }; + } else { + delete marks[path]; + } + } + saveMarks(); + } + + return checkHead(paths); + } + + return fetch('/api/state', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(patch), @@ -54,6 +134,32 @@ export const persist = (patch) => } }) .catch(() => {}); +}; + +/** + * Asks a static export whether a newer push has replaced it and shows the banner if + * one has. Not throttled, since head.json is a few bytes. The full manifest is read + * only once the head has moved, to tell which of `paths` the push changed. + * @param {string[]} paths + * @returns {Promise} + */ +const checkHead = async (paths) => { + try { + const { head } = await fetch('head.json', { cache: 'no-store' }).then((response) => response.json()); + if (!head || head === state.head) { + return; + } + + const manifest = await fetch('manifest.json', { cache: 'no-store' }).then((response) => response.json()); + /* A path missing from the newer list is back to its baseline, so it changed too. */ + const latest = new Map(manifest.entries.map((entry) => [entry.path, entry.actualSha])); + const changed = paths.filter((path) => latest.get(path) !== entryFor(path)?.actualSha); + + notePush({ head, changed }); + } catch { + /* Offline, or mid-deploy. The next check will ask again. */ + } +}; /** * Asks whether a newer push has landed and shows the banner if it has. Called on load @@ -61,14 +167,16 @@ export const persist = (patch) => * @returns {Promise} */ export const checkFreshness = () => - fetch('/api/freshness') - .then((response) => response.json()) - .then((result) => { - if (result?.moved) { - notePush(result); - } - }) - .catch(() => {}); + state.static + ? checkHead([]) + : fetch('/api/freshness') + .then((response) => response.json()) + .then((result) => { + if (result?.moved) { + notePush(result); + } + }) + .catch(() => {}); /** * Shows the push banner: urgent when the push changed something just marked, quiet @@ -107,6 +215,12 @@ const refreshButton = () => { button.textContent = 'Refresh'; button.addEventListener('click', async () => { + /* The newer export is already deployed, so there is nothing to rebuild. */ + if (state.static) { + window.location.reload(); + return; + } + button.disabled = true; button.textContent = 'Refreshing…'; diff --git a/src/client/styles/sidebar.css b/src/client/styles/sidebar.css index 88d8d82..55057fb 100644 --- a/src/client/styles/sidebar.css +++ b/src/client/styles/sidebar.css @@ -1,4 +1,4 @@ -/* Sidebar: filter, checkboxes, facets, and the push and carried-over banners. */ +/* Sidebar: filter, checkboxes, facets, and the push, carried-over and comments banners. */ .sidebar { display: flex; @@ -116,7 +116,8 @@ } .carried, -.pushed { +.pushed, +.threads-failed { margin: 0; padding: 7px 12px; @@ -130,7 +131,8 @@ } .carried[hidden], -.pushed[hidden] { +.pushed[hidden], +.threads-failed[hidden] { display: none; } diff --git a/src/export.mjs b/src/export.mjs new file mode 100644 index 0000000..3787aae --- /dev/null +++ b/src/export.mjs @@ -0,0 +1,190 @@ +/** + * Writes a review as a static site, for hosting where there is no clone to read from. + * + * The page is the same one the server sends. What it loses is everything that needs + * the server: viewed marks stay in the browser, comments are read only, and a newer + * push is noticed by reading head.json again. + * + * - Takes a range, never a pull request. Whoever runs it already knows both commits, + * and the export never contacts GitHub. + * - A --url naming a pull request is where the page loads comments from, through + * GitHub's public API when it opens. Any other --url is only the header link. + * - Images are named by blob id and diffs by the pair, so two screenshots with the + * same bytes are written once. + * - Replaces an earlier export in --out, but refuses a folder holding anything else, + * since --out can be any path. + * - A range with no changed screenshots writes nothing and still succeeds, so a + * workflow can run it on every push and skip the deploy when the folder is missing. + * + * Usage: + * npm run export -- --base origin/main --head my-branch + * npm run export -- --repo ~/code/ionic-framework --base --head --out dist + * npm run export -- --base --head --label '#31321 fix(item): ...' --url + */ +import { copyFile, cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'; +import { join, relative, resolve } from 'node:path'; +import { parseArgs } from 'node:util'; + +import { BlobReader, DEFAULT_PATHSPEC } from './git.mjs'; +import { CLIENT_DIR, SLIDER_PKG, buildSnapshots, findRepo, resolveRange } from './index.mjs'; + +const usage = ` +Write a review as a static site. + + --repo The ionic-framework checkout to read. Defaults to + ../ionic-framework next to the reviewer. + --base Compare from this ref. Required. + --head Compare to this ref. Required. + --path Narrow the set with a git pathspec. + --out Where to write the site. Defaults to dist. + --label The header title. Defaults to the two refs. + --url Where the header title links to. A pull request's URL + also shows its comments. +`; + +/** + * A folder as typed when it is under the current directory, and in full otherwise. + * @param {string} dir + * @returns {string} + */ +const shown = (dir) => { + const path = relative(process.cwd(), dir); + return path && !path.startsWith('..') ? path : dir; +}; + +/** + * The pull request a --url points at, for the page to load comments from. + * @param {string | undefined} url + * @returns {{ repo: string, number: number } | null} Null for any other URL. + */ +const pullRequestOf = (url) => { + const match = url?.match(/^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)\/?$/); + return match ? { repo: match[1], number: Number(match[2]) } : null; +}; + +/** + * Whether a folder holds an earlier export, the only thing replaced without asking. + * @param {string} dir + * @returns {Promise} + */ +const isExport = async (dir) => { + try { + return JSON.parse(await readFile(join(dir, 'manifest.json'), 'utf8')).static === true; + } catch { + return false; + } +}; + +/** + * Parses the command line after `export`. + * @param {string[]} argv + */ +const readArgs = (argv) => + parseArgs({ + args: argv, + options: { + repo: { type: 'string' }, + base: { type: 'string' }, + head: { type: 'string' }, + path: { type: 'string' }, + out: { type: 'string', default: 'dist' }, + label: { type: 'string' }, + url: { type: 'string' }, + help: { type: 'boolean', short: 'h', default: false }, + }, + }).values; + +/** + * Builds the review for a range and writes it to `--out` as a static site. + * @param {string[]} argv The arguments after `export`. + * @returns {Promise} + */ +export const exportSite = async (argv) => { + const args = readArgs(argv); + if (args.help) { + process.stdout.write(usage); + return; + } + + if (!args.base || !args.head) { + throw new Error('Pass both --base and --head .'); + } + + const out = resolve(args.out); + const replacing = (await readdir(out).catch(() => [])).length > 0; + if (replacing && !(await isExport(out))) { + throw new Error(`${shown(out)} has files that are not an export. Pass an empty --out.`); + } + + const cwd = await findRepo(args); + const range = await resolveRange({ base: args.base, head: args.head }, cwd); + const pathspec = args.path ?? DEFAULT_PATHSPEC; + + /* Cleared before building, so a range with nothing to show leaves no folder instead + of the last review. */ + if (replacing) { + await rm(out, { recursive: true, force: true }); + } + + const reader = new BlobReader(cwd); + + try { + const snapshots = await buildSnapshots({ range, pathspec, cwd, reader }); + + if (!snapshots) { + process.stdout.write(`\n No screenshots changed between ${range.base} and ${range.head}. Nothing written.\n\n`); + return; + } + + await mkdir(join(out, 'images'), { recursive: true }); + await mkdir(join(out, 'diffs'), { recursive: true }); + await mkdir(join(out, 'vendor'), { recursive: true }); + + await cp(CLIENT_DIR, out, { recursive: true }); + /* Only what the page loads, not the package's type declarations and source maps. */ + for (const file of ['index.js', 'styles.css']) { + await copyFile(join(SLIDER_PKG, file), join(out, 'vendor', file)); + } + + for (const sha of snapshots.shas) { + await writeFile(join(out, 'images', `${sha}.png`), await reader.readSha(sha)); + } + for (const [key, file] of snapshots.diffs) { + await copyFile(file, join(out, 'diffs', `${key}.png`)); + } + + await writeFile( + join(out, 'manifest.json'), + JSON.stringify({ + static: true, + range: { + ...range, + label: args.label ?? range.label, + url: args.url ?? null, + mergeBase: snapshots.mergeBase, + pathspec, + }, + blobBase: snapshots.blobBase, + pullRequest: pullRequestOf(args.url), + head: snapshots.headSha, + counts: snapshots.counts, + entries: snapshots.entries, + }) + ); + /* Polled for a newer push. Kept apart from the manifest so that question costs a + few bytes instead of the whole list. */ + await writeFile(join(out, 'head.json'), JSON.stringify({ head: snapshots.headSha })); + + process.stdout.write( + [ + ``, + ` Exported ${snapshots.entries.length} screenshots to ${shown(out)}`, + ` ${snapshots.shas.size} images, ${snapshots.diffs.size} diffs`, + ``, + ``, + ].join('\n') + ); + } finally { + reader.close(); + } +}; diff --git a/src/git.mjs b/src/git.mjs index 564e4e1..70096b1 100644 --- a/src/git.mjs +++ b/src/git.mjs @@ -953,9 +953,27 @@ export class BlobReader { * @returns {Promise} Null when the path is absent at `ref`. */ read(ref, path) { + return this.#request(`${ref}:${path}`); + } + + /** + * Reads one blob by its id. + * @param {string} sha + * @returns {Promise} Null when there is no such object. + */ + readSha(sha) { + return this.#request(sha); + } + + /** + * Queues one object name for cat-file. + * @param {string} name + * @returns {Promise} + */ + #request(name) { return new Promise((resolve, reject) => { this.queue.push({ resolve, reject }); - this.proc.stdin.write(`${ref}:${path}\n`); + this.proc.stdin.write(`${name}\n`); }); } diff --git a/src/index.mjs b/src/index.mjs index 54f76a9..8f9d2a9 100644 --- a/src/index.mjs +++ b/src/index.mjs @@ -141,8 +141,8 @@ import { */ /** - * @typedef {object} Review - * @property {Record} threads Teammates' comments, by path. + * The screenshots in a range, compared: everything the server and an export share. + * @typedef {object} Snapshots * @property {{ repo: string, expected: string | null, actual: string | null } | null} blobBase For GitHub links. * @property {number} pruned * @property {number} computed @@ -150,18 +150,29 @@ import { * @property {string} headSha * @property {string} mergeBase * @property {ReviewEntry[]} entries - * @property {Map} diffs - * @property {Store} store + * @property {Map} diffs Cached diff images, by `diffKey`. + * @property {Set} shas Every image in the range, by blob id. * @property {Record} counts By status. - * @property {Map} baselinePaths Where a renamed screenshot's baseline lives. * @property {Map} byPath + */ + +/** + * What only the server needs on top: marks, teammates' comments and push watching. + * @typedef {object} Session + * @property {Record} threads Teammates' comments, by path. + * @property {Store} store * @property {ReturnType} pushWatch */ +/** @typedef {Snapshots & Session} Review */ + const HERE = dirname(fileURLToPath(import.meta.url)); -const CLIENT_DIR = join(HERE, 'client'); +export const CLIENT_DIR = join(HERE, 'client'); /* Resolved rather than walked to, so it is found wherever npm put node_modules. */ -const SLIDER_PKG = join(dirname(createRequire(import.meta.url).resolve('img-comparison-slider/package.json')), 'dist'); +export const SLIDER_PKG = join( + dirname(createRequire(import.meta.url).resolve('img-comparison-slider/package.json')), + 'dist' +); const DEFAULT_PORT = 4300; /* Yellow only on a terminal, since styleText checks stdout before coloring. */ @@ -211,11 +222,11 @@ const readArgs = () => { /** * Resolves the arguments to the range under review: a pull request, or `--base` and * `--head`. Given with `--pr`, `--base` and `--head` override the pull request's own ends. - * @param {Args} args + * @param {Pick} args * @param {string} cwd * @returns {Promise} */ -const resolveRange = async (args, cwd) => { +export const resolveRange = async (args, cwd) => { if (args.pr) { const { base, head, pr } = await resolvePullRequest(args.pr, cwd); return { @@ -541,6 +552,14 @@ const createFreshness = ({ args, viewer, range, cwd, reviewedAt }) => { */ const DIFF_CACHE = 'diffs'; +/** + * Names a pair's diff by its two blob ids, in the cache and in image URLs alike. + * @param {string} expectedSha + * @param {string} actualSha + * @returns {string} + */ +export const diffKey = (expectedSha, actualSha) => `${expectedSha}-${actualSha}`; + /** * Where a pair's diff image and metrics are cached, keyed by the two blob ids. * @param {string} root From `stateDir`. @@ -550,7 +569,7 @@ const DIFF_CACHE = 'diffs'; */ const diffCachePaths = (root, expectedSha, actualSha) => { const dir = join(root, DIFF_CACHE, expectedSha.slice(0, 2)); - const stem = join(dir, `${expectedSha}-${actualSha}`); + const stem = join(dir, diffKey(expectedSha, actualSha)); return { dir, png: `${stem}.png`, meta: `${stem}.json` }; }; @@ -564,7 +583,7 @@ const diffCachePaths = (root, expectedSha, actualSha) => { * @param {string} options.head * @param {string} options.cacheRoot * @returns {Promise<{ entries: ReviewEntry[], diffs: Map, computed: number, reused: number }>} - * `diffs` maps a path to its cached diff image. + * `diffs` maps a `diffKey` to its cached diff image. */ const buildDiffs = async ({ entries, reader, mergeBase, head, cacheRoot }) => { const results = {}; @@ -611,7 +630,7 @@ const buildDiffs = async ({ entries, reader, mergeBase, head, cacheRoot }) => { computed++; } - diffs.set(entry.path, paths.png); + diffs.set(diffKey(entry.expectedSha, entry.actualSha), paths.png); } results[entry.path] = { @@ -752,15 +771,15 @@ const pruneCache = async (root) => { }; /** - * Builds everything the server answers from, as one value that refresh swaps whole. + * Lists and compares the screenshots in a range: what the server and an export share. * Every blob is read at the resolved head, so a moving branch cannot mix two commits. - * @param {{ args: Args, viewer: string | null, range: Range, pathspec: string, cwd: string, reader: BlobReader }} options - * @returns {Promise} + * @param {{ range: Range, pathspec: string, cwd: string, reader: BlobReader }} options + * @returns {Promise} Null when no screenshot changed. */ -const buildReview = async ({ args, viewer, range, pathspec, cwd, reader }) => { +export const buildSnapshots = async ({ range, pathspec, cwd, reader }) => { const manifest = await buildManifest({ base: range.base, head: range.head, pathspec, cwd }); if (manifest.entries.length === 0) { - throw new Error(`No screenshots changed between ${range.base} and ${range.head}`); + return null; } const headSha = await resolveRef(range.head, cwd); @@ -778,17 +797,8 @@ const buildReview = async ({ args, viewer, range, pathspec, cwd, reader }) => { cacheRoot: root, }); - const store = await createStore(cwd, reviewKey(args, range), entries); const pruned = await pruneCache(root); - /* What teammates have already said, so their notes sit beside the screenshot they - are about. A failure here is not worth refusing to start over. - Narrowed to this range: a pull request collects comments on source files too, and - those have nowhere to appear here. */ - const allThreads = args.pr ? await fetchReviewThreads({ number: args.pr, cwd }).catch(() => ({})) : {}; - const inRange = new Set(entries.map((entry) => entry.path)); - const threads = Object.fromEntries(Object.entries(allThreads).filter(([path]) => inRange.has(path))); - /* Links are only offered for commits GitHub can actually serve. */ const slug = await remoteSlug(cwd); const blobBase = slug @@ -800,7 +810,6 @@ const buildReview = async ({ args, viewer, range, pathspec, cwd, reader }) => { : null; return { - threads, blobBase, pruned, computed, @@ -809,23 +818,47 @@ const buildReview = async ({ args, viewer, range, pathspec, cwd, reader }) => { mergeBase: manifest.mergeBase, entries, diffs, - store, + shas: new Set(entries.flatMap((entry) => [entry.expectedSha, entry.actualSha]).filter(Boolean)), counts: entries.reduce((acc, entry) => ({ ...acc, [entry.status]: (acc[entry.status] ?? 0) + 1 }), {}), - /* The client only ever knows a screenshot by its current path, so the server - keeps the mapping back to where a renamed one's baseline lives. */ - baselinePaths: new Map(entries.filter((entry) => entry.oldPath).map((entry) => [entry.path, entry.oldPath])), byPath: new Map(entries.map((entry) => [entry.path, entry])), - pushWatch: createFreshness({ args, viewer, range, cwd, reviewedAt: headSha }), + }; +}; + +/** + * Builds everything the server answers from, as one value that refresh swaps whole. + * @param {{ args: Args, viewer: string | null, range: Range, pathspec: string, cwd: string, reader: BlobReader }} options + * @returns {Promise} + */ +const buildReview = async ({ args, viewer, range, pathspec, cwd, reader }) => { + const snapshots = await buildSnapshots({ range, pathspec, cwd, reader }); + if (!snapshots) { + throw new Error(`No screenshots changed between ${range.base} and ${range.head}`); + } + + const store = await createStore(cwd, reviewKey(args, range), snapshots.entries); + + /* What teammates have already said, so their notes sit beside the screenshot they + are about. A failure here is not worth refusing to start over. + Narrowed to this range: a pull request collects comments on source files too, and + those have nowhere to appear here. */ + const allThreads = args.pr ? await fetchReviewThreads({ number: args.pr, cwd }).catch(() => ({})) : {}; + const threads = Object.fromEntries(Object.entries(allThreads).filter(([path]) => snapshots.byPath.has(path))); + + return { + ...snapshots, + threads, + store, + pushWatch: createFreshness({ args, viewer, range, cwd, reviewedAt: snapshots.headSha }), }; }; /** * Finds the checkout to review: `--repo`, else ionic-framework cloned next to the * reviewer, else whatever path the developer types in. - * @param {Args} args + * @param {Pick} args * @returns {Promise} The checkout's root. */ -const findRepo = async (args) => { +export const findRepo = async (args) => { const reviewer = await repoRoot(HERE).catch(() => null); /** @param {string} path */ const check = async (path) => { @@ -1048,7 +1081,9 @@ export const main = async () => { }); } - if (url.pathname === '/api/manifest') { + /* The same path an export writes it to, so the page reads it the same way from + either. */ + if (url.pathname === '/manifest.json') { return send( res, 200, @@ -1070,29 +1105,26 @@ export const main = async () => { ); } - if (url.pathname === '/blob') { - const path = url.searchParams.get('path'); - const side = url.searchParams.get('side'); + /* + * Images are named by content, the same way an export lays them out: expected and + * actual by blob id, a diff by the pair. Only ids in this review are served. Any + * other name, one with a newline in particular, would go straight into cat-file + * and misalign every read after it. + */ + const image = url.pathname.match(/^\/(images|diffs)\/([0-9a-f-]+)\.png$/); - /* Only screenshots in this review are served. Any other path, one with a - newline in particular, would go straight into cat-file and misalign every - read after it. */ - if (!review.byPath.has(path)) { - return send(res, 404, 'not found'); - } + if (image) { + const [, kind, name] = image; /* The diff is generated, so it comes off disk. Expected and actual are the originals, read straight out of the object store. */ const blob = - side === 'diff' - ? review.diffs.has(path) - ? await readFile(review.diffs.get(path)) + kind === 'diffs' + ? review.diffs.has(name) + ? await readFile(review.diffs.get(name)) : null - : path - ? await reader.read( - side === 'expected' ? review.mergeBase : review.headSha, - side === 'expected' ? (review.baselinePaths.get(path) ?? path) : path - ) + : review.shas.has(name) + ? await reader.readSha(name) : null; if (!blob) { diff --git a/test/e2e/review.e2e.js b/test/e2e/review.e2e.js index 72d4c86..f5bb7c0 100644 --- a/test/e2e/review.e2e.js +++ b/test/e2e/review.e2e.js @@ -52,6 +52,14 @@ test('should list every changed snapshot under its directory', async ({ page }) await expect(page.locator('.group-head .group-name')).toHaveText(['badge/test/basic', 'chip/test/hint']); }); +test('should load both sides and the diff of a modified snapshot', async ({ page }) => { + await page.locator(`.row[data-path="${FIXTURE.modified}"]`).click(); + + await expect(page.locator('#sxsExpected')).toHaveJSProperty('naturalWidth', 40); + await expect(page.locator('#sxsActual')).toHaveJSProperty('naturalWidth', 40); + await expect(page.locator('#diffImage')).toHaveJSProperty('naturalWidth', 40); +}); + test('should flag the snapshot whose spec was deleted', async ({ page }) => { await page.getByLabel('Missing test only').check(); diff --git a/test/e2e/static.e2e.js b/test/e2e/static.e2e.js new file mode 100644 index 0000000..127837a --- /dev/null +++ b/test/e2e/static.e2e.js @@ -0,0 +1,148 @@ +import { expect, test } from '@playwright/test'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import sirv from 'sirv'; + +import { exportSite } from '../../src/export.mjs'; +import { FIXTURE, createFixtureRepo } from '../fixtures/repo.js'; + +/* One export for the file, served as plain files the way a static host would. */ +test.describe.configure({ mode: 'serial' }); + +let fixture; +let root; +let out; +let server; +let address; + +test.beforeAll(async () => { + fixture = createFixtureRepo(); + root = mkdtempSync(join(tmpdir(), 'visual-review-static-')); + out = join(root, 'site'); + await exportSite([ + '--repo', + fixture.dir, + '--base', + 'main', + '--head', + 'feature', + '--out', + out, + '--url', + 'https://github.com/ionic-team/ionic-framework/pull/1', + ]); + + const serve = sirv(out, { dev: true }); + server = createServer((req, res) => + serve(req, res, () => { + res.writeHead(404).end(); + }) + ); + await new Promise((resolve) => server.listen(4411, '127.0.0.1', resolve)); + address = 'http://127.0.0.1:4411'; +}); + +test.afterAll(() => { + server?.close(); + fixture?.cleanup(); + rmSync(root, { recursive: true, force: true }); +}); + +/** + * A review comment as GitHub's REST API returns it, trimmed to what the page reads. + * @param {{ id: number, replyTo?: number, commit: string, author: string, body: string }} comment + */ +const restComment = ({ id, replyTo, commit, author, body }) => ({ + id, + in_reply_to_id: replyTo ?? null, + path: FIXTURE.modified, + commit_id: commit, + user: { login: author }, + body_html: `

${body}

`, + html_url: `https://github.com/ionic-team/ionic-framework/pull/1#discussion_r${id}`, + created_at: '2026-10-28T00:00:00Z', +}); + +test.beforeEach(async ({ page }) => { + /* The page reads comments from GitHub itself. No pull request has any unless a test + says so, and none of these requests leaves the machine. */ + await page.route('https://api.github.com/**', (route) => route.fulfill({ json: [] })); + await page.goto(address); + await expect(page.locator('.row').first()).toBeVisible(); +}); + +test('should list every changed snapshot without a comment box', async ({ page }) => { + await expect(page.locator('.row')).toHaveCount(6); + await expect(page.locator('#commentSection')).toBeHidden(); +}); + +test('should load both sides and the diff of a modified snapshot', async ({ page }) => { + await page.locator(`.row[data-path="${FIXTURE.modified}"]`).click(); + + await expect(page.locator('#sxsExpected')).toHaveJSProperty('naturalWidth', 40); + await expect(page.locator('#sxsActual')).toHaveJSProperty('naturalWidth', 40); + await expect(page.locator('#diffImage')).toHaveJSProperty('naturalWidth', 40); +}); + +test('should keep a viewed mark in the browser across a reload', async ({ page }) => { + await page.locator('.row').first().click(); + await page.keyboard.press('v'); + await expect(page.locator('#progressLabel')).toHaveText('1 / 6 viewed'); + + await page.reload(); + await expect(page.locator('#progressLabel')).toHaveText('1 / 6 viewed'); +}); + +test('should show the pull request comments without a comment box', async ({ page }) => { + const { head } = JSON.parse(readFileSync(join(out, 'head.json'), 'utf8')); + await page.route('https://api.github.com/**', (route) => + route.fulfill({ + json: [ + restComment({ id: 1, commit: head, author: 'teammate', body: 'Is the band meant to be green?' }), + restComment({ id: 2, replyTo: 1, commit: head, author: 'author', body: 'Yes.' }), + restComment({ id: 3, commit: 'a'.repeat(40), author: 'teammate', body: 'On an earlier push.' }), + ], + }) + ); + await page.reload(); + + const row = page.locator(`.row[data-path="${FIXTURE.modified}"]`); + await expect(row.locator('.note')).toHaveClass(/theirs/); + await row.click(); + + await expect(page.locator('#threads .thread-comment')).toHaveText([ + /teammate.*green/, + /author.*Yes/, + /teammate.*earlier/, + ]); + await expect(page.locator('#threads .thread-tag')).toHaveText(['outdated']); + await expect(page.locator('#comment')).toBeHidden(); +}); + +test('should say when GitHub refuses to send the comments', async ({ page }) => { + await page.route('https://api.github.com/**', (route) => route.fulfill({ status: 403, json: {} })); + await page.reload(); + + await expect(page.locator('#threadsFailed')).toContainText('limiting requests'); +}); + +test('should say a newer push changed the snapshot just marked', async ({ page }) => { + /* What a deploy of the next push looks like from here: a new head, and the modified + snapshot rewritten. */ + const manifest = JSON.parse(readFileSync(join(out, 'manifest.json'), 'utf8')); + for (const entry of manifest.entries) { + if (entry.path === FIXTURE.modified) { + entry.actualSha = 'f'.repeat(40); + } + } + writeFileSync(join(out, 'manifest.json'), JSON.stringify(manifest)); + writeFileSync(join(out, 'head.json'), JSON.stringify({ head: 'e'.repeat(40) })); + + await page.locator(`.row[data-path="${FIXTURE.modified}"]`).click(); + await page.keyboard.press('v'); + + await expect(page.locator('#pushed')).toContainText('changed in a newer push'); + await expect(page.locator('#pushed')).toHaveClass(/urgent/); +}); diff --git a/test/integration/export.test.js b/test/integration/export.test.js new file mode 100644 index 0000000..212db96 --- /dev/null +++ b/test/integration/export.test.js @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, describe, test } from 'node:test'; + +import { exportSite } from '../../src/export.mjs'; +import { FIXTURE, createFixtureRepo } from '../fixtures/repo.js'; + +describe('export: static site', () => { + let fixture; + let root; + const range = () => ['--repo', fixture.dir, '--base', 'main', '--head', 'feature']; + + before(() => { + fixture = createFixtureRepo(); + root = mkdtempSync(join(tmpdir(), 'visual-review-export-')); + }); + + after(() => { + fixture.cleanup(); + rmSync(root, { recursive: true, force: true }); + }); + + test('should write the page with every image the manifest points to', async () => { + const out = join(root, 'site'); + await exportSite([ + ...range(), + '--out', + out, + '--label', + '#1 badge', + '--url', + 'https://github.com/ionic-team/ionic-framework/pull/1', + ]); + + const manifest = JSON.parse(readFileSync(join(out, 'manifest.json'), 'utf8')); + const head = execFileSync('git', ['rev-parse', 'feature'], { cwd: fixture.dir }).toString().trim(); + + assert.equal(manifest.static, true); + assert.equal(manifest.head, head); + assert.equal(manifest.range.label, '#1 badge'); + assert.deepEqual(manifest.pullRequest, { repo: 'ionic-team/ionic-framework', number: 1 }); + assert.equal(manifest.entries.length, 6); + assert.deepEqual(JSON.parse(readFileSync(join(out, 'head.json'), 'utf8')), { head }); + + for (const file of ['index.html', 'app.js', 'vendor/index.js', 'vendor/styles.css']) { + assert.ok(existsSync(join(out, file)), file); + } + + for (const entry of manifest.entries) { + for (const sha of [entry.expectedSha, entry.actualSha].filter(Boolean)) { + assert.ok(existsSync(join(out, 'images', `${sha}.png`)), `${entry.path} ${sha}`); + } + if (entry.comparable) { + assert.ok(existsSync(join(out, 'diffs', `${entry.expectedSha}-${entry.actualSha}.png`)), entry.path); + } + } + + /* A rename is compared against its old path, which the image name already covers. */ + const renamed = manifest.entries.find((entry) => entry.path === FIXTURE.renamedTo); + assert.equal(renamed.expectedSha, renamed.actualSha); + }); + + test('should replace an earlier export', async () => { + const out = join(root, 'again'); + await exportSite([...range(), '--out', out]); + writeFileSync(join(out, 'stale.txt'), 'left over'); + + await exportSite([...range(), '--out', out]); + + assert.equal(existsSync(join(out, 'stale.txt')), false); + /* No --url, so no pull request to read comments from. */ + assert.equal(JSON.parse(readFileSync(join(out, 'manifest.json'), 'utf8')).pullRequest, null); + assert.equal(JSON.parse(readFileSync(join(out, 'manifest.json'), 'utf8')).entries.length, 6); + }); + + test('should refuse a folder that holds anything but an export', async () => { + const out = join(root, 'taken'); + mkdirSync(out); + writeFileSync(join(out, 'keep.txt'), 'mine'); + + await assert.rejects(exportSite([...range(), '--out', out]), /not an export/); + assert.equal(readFileSync(join(out, 'keep.txt'), 'utf8'), 'mine'); + }); + + test('should write nothing when no screenshot changed', async () => { + const out = join(root, 'empty'); + await exportSite(['--repo', fixture.dir, '--base', 'feature', '--head', 'feature', '--out', out]); + + assert.equal(existsSync(out), false); + }); +});