Something went wrong. Try again.
Tools for building Offline-first Web Apps
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371#!/usr/bin/env -S deno run -A/** * @module Visual baseline capture * * Screenshots every app's static routes in light and dark, at two viewports. * The UI restructure moves ~10,000 lines of CSS across six repos; no test in * any of them would notice a rule that quietly stopped applying, so this is * the check that makes the restructure verifiable instead of eyeballed. * * ``` * deno task visual:capture --out .visual/before * # …do the work… * deno task visual:capture --out .visual/after * deno task visual:compare .visual/before .visual/after * ``` * * Apps are served as static files rather than through `civ start`. Every app * hash-routes, so `www/` plus a built `www/dist/` is the entire surface, and * serving it in-process avoids supervising an esbuild watcher per app (and the * orphaned children that come with killing one). * * Determinism is the whole point of a baseline, so before each shot the page * gets animations, transitions and the text caret disabled. What remains * nondeterministic is genuinely dynamic content — `ui-version`'s build id, * `timeAgo()` strings — which shows up as a small, obviously-localised diff * rather than a false pass. */import { launch, type Page } from '@astral/astral'import { serveDir } from '@std/http/file-server'import { fromFileUrl } from '@std/path'import { APPS, type AppSpec, SCHEMES, VIEWPORTS } from './apps.ts'
/** `apps/` — this file lives at `apps/civility/scripts/visual/capture.ts`. */const APPS_ROOT = fromFileUrl(new URL('../../../', import.meta.url))
/** Ceiling on a full-page screenshot, in CSS pixels. */const MAX_PAGE_HEIGHT = 4000
interface Clip { x: number y: number width: number height: number scale: number}
/** Kills every source of frame-to-frame jitter before a shot is taken. */const FREEZE_CSS = ` *, *::before, *::after { animation-delay: -1ms !important; animation-duration: 1ms !important; animation-iteration-count: 1 !important; transition-duration: 0ms !important; transition-delay: 0ms !important; scroll-behavior: auto !important; caret-color: transparent !important; }`
interface Options { out: string only: string[] build: boolean}
async function main(): Promise<void> { const opts = parseOptions(Deno.args) const apps = opts.only.length ? APPS.filter((a) => opts.only.includes(a.name)) : APPS
if (apps.length === 0) { console.error( `No apps matched. Known: ${APPS.map((a) => a.name).join(', ')}`, ) Deno.exit(1) }
await Deno.mkdir(opts.out, { recursive: true }) console.log(`Capturing ${apps.length} app(s) → ${opts.out}\n`)
const browser = await launch() const stalled: string[] = [] let shots = 0 try { for (const app of apps) { if (opts.build) await build(app) shots += await captureApp(browser, app, opts.out, stalled) } } finally { await browser.close() }
console.log(`\n${shots} screenshots written to ${opts.out}`)
// A route that never mounted was captured as a blank page. Banking that as // a baseline is worse than having none — every later run would "match". if (stalled.length) { const routes = [...new Set(stalled)] console.error( `\n${routes.length} route(s) never mounted; their screenshots are not ` + `a usable baseline:`, ) for (const r of routes) console.error(` ${r}`) Deno.exit(1) }}
/** * `civ build` rather than the app's own `deno task build`: maps has no build * task at all, and cook's `start` task still shells out to a `civility` binary * that no longer exists on PATH. */async function build(app: AppSpec): Promise<void> { const [cmd, ...args] = app.build?.cmd ?? ['civ', 'build'] const cwd = `${APPS_ROOT}${app.build?.cwd ?? app.name}` const { code, stderr } = await new Deno.Command(cmd, { args, cwd, stdout: 'null', stderr: 'piped', }).output() if (code !== 0) { console.error(` ${app.name}: build failed`) console.error(new TextDecoder().decode(stderr).trimEnd()) Deno.exit(1) }}
async function captureApp( browser: Awaited<ReturnType<typeof launch>>, app: AppSpec, outDir: string, stalled: string[],): Promise<number> { const root = `${APPS_ROOT}${app.root ?? `${app.name}/www`}` const server = Deno.serve( { port: 0, hostname: '127.0.0.1', onListen: () => {} }, (req) => serveDir(req, { fsRoot: root, quiet: true }), ) const base = `http://127.0.0.1:${server.addr.port}` await Deno.mkdir(`${outDir}/${app.name}`, { recursive: true })
let count = 0 try { // `''` is the app's own theme; named ones are layered on via `?theme=`. for (const theme of ['', ...(app.themes ?? [])]) { for (const [vpName, vp] of Object.entries(VIEWPORTS)) { for (const scheme of SCHEMES) { const page = await browser.newPage() try { await page.setViewportSize(vp) await page.emulateMediaFeatures([ { name: 'prefers-color-scheme', value: scheme }, ]) // One cold boot per (viewport, scheme); routes after that are hash // changes, which is how a user actually moves through the app. const query = theme ? `?theme=${theme}` : '' await page.goto(`${base}/${query}#!${app.routes[0]}`, { waitUntil: 'networkidle2', })
const routes = app.discoverRoutes ? await page.evaluate(() => (globalThis as { __ROUTES__?: string[] }).__ROUTES__ ?? [] ) : app.routes if (routes.length === 0) { throw new Error( `${app.name}: discoverRoutes found no globalThis.__ROUTES__`, ) }
for (const route of routes) { if (!await goToRoute(page, route, !!app.discoverRoutes)) { stalled.push(`${app.name} ${route}`) } const mask = app.mask?.length ? `${app.mask.join(', ')} { visibility: hidden !important; }` : '' await page.evaluate( (css: string) => { let el = document.getElementById('__freeze') if (!el) { el = document.createElement('style') el.id = '__freeze' document.head.appendChild(el) } el.textContent = css }, { args: [FREEZE_CSS + mask] }, ) // Webfonts landing after first paint reflow text metrics, which // moves every vertically-centred box by a pixel — the single // largest source of false diffs before this line existed. await page.evaluate(() => document.fonts.ready.then(() => true)) await page.waitForTimeout(250)
const suffix = theme ? `--${theme}` : '' const name = `${slug(route)}--${vpName}--${scheme}${suffix}.png` const bytes = await page.screenshot( await fullPageClip(page, vp.width), ) await Deno.writeFile(`${outDir}/${app.name}/${name}`, bytes) count++ } } finally { await page.close() } } } } } finally { await server.shutdown() }
console.log(` ${app.name.padEnd(7)} ${count} shots`) return count}
/** * Navigate by hash and wait for the router to mount the route's component. * * `goto()` is not usable here: a same-document hash change fires no navigation * event, so waiting on one would hang. The signal instead is the *mounted * component's tag name*, since the router swaps the landmark's children rather * than the landmark — each route mounts a different element (`albums-page`, * `settings-page`, …). * * Returns false if nothing mounted before the deadline, which means the shot * about to be taken is of a blank or half-booted page. */async function goToRoute( page: Page, route: string, /** * Wait for `documentElement.dataset.ready` to equal the route instead of for * the mounted tag to change. The gallery renders consecutive specimens of * the same component, so "the tag changed" is never true there. */ usesReadyStamp = false,): Promise<boolean> { if (usesReadyStamp) { await page.evaluate( (hash: string) => { delete document.documentElement.dataset.ready if (location.hash !== `#!${hash}`) location.hash = `#!${hash}` else globalThis.dispatchEvent(new HashChangeEvent('hashchange')) }, { args: [route] }, ) const readyBy = Date.now() + 10_000 while (Date.now() < readyBy) { const ok = await page.evaluate( (r: string) => document.documentElement.dataset.ready === r, { args: [route] }, ) if (ok) { await page.waitForTimeout(150) return true } await page.waitForTimeout(50) } console.warn(` ${route}: never became ready, captured as-is`) return false }
// Two different waits, because the first route of each page is the one the // browser cold-booted into: it is already mounted by the time this runs, so // waiting for the tag to *change* would deadlock. There, any mounted element // means success; everywhere else the tag has to actually change. const previous = await page.evaluate( (hash: string) => { const mounted = document.querySelector('main')?.firstElementChild const already = location.hash === `#!${hash}` if (!already) location.hash = `#!${hash}` return { already, tag: mounted?.tagName ?? '' } }, { args: [route] }, )
// Bounded poll rather than `page.waitForFunction`, which astral polls // without a deadline — a route that never settles would hang the run. const deadline = Date.now() + 10_000 while (Date.now() < deadline) { const ready = await page.evaluate( (prev: { already: boolean; tag: string }) => { const mounted = document.querySelector('main')?.firstElementChild if (!mounted) return false return prev.already || mounted.tagName !== prev.tag }, { args: [previous] }, ) if (ready) { // Let the newly mounted component finish its first render. await page.waitForTimeout(150) return true } await page.waitForTimeout(100) } console.warn(` ${route}: never mounted, captured as-is`) return false}
/** * A clip covering the whole document, not just the viewport. * * Settings pages are long, and the components this restructure touches * (`civ-store-import`, `civ-devices`, the Data section) sit near the bottom — * a viewport-sized shot showed no change at all when they were rewritten, * which is a baseline that quietly certifies work it never looked at. * * Height is capped: an infinite-scroll or runaway-layout route would otherwise * produce an image large enough to be useless to diff. */async function fullPageClip( page: Page, width: number,): Promise<{ captureBeyondViewport: boolean; clip: Clip }> { const height = await page.evaluate(() => { const d = document.documentElement const b = document.body return Math.max( d.scrollHeight, d.offsetHeight, b?.scrollHeight ?? 0, b?.offsetHeight ?? 0, ) }) return { captureBeyondViewport: true, clip: { x: 0, y: 0, width, height: Math.min(height, MAX_PAGE_HEIGHT), scale: 1, }, }}
/** `/settings/about` → `settings-about`; `/` → `index`. */function slug(route: string): string { const s = route.replace(/^\/+|\/+$/g, '').replace(/\//g, '-') return s === '' ? 'index' : s}
function parseOptions(args: string[]): Options { const opts: Options = { out: '.visual/capture', only: [], build: true } for (let i = 0; i < args.length; i++) { const arg = args[i] if (arg === '--out') opts.out = args[++i] else if (arg.startsWith('--out=')) opts.out = arg.slice(6) else if (arg === '--only') opts.only = args[++i].split(',') else if (arg.startsWith('--only=')) opts.only = arg.slice(7).split(',') else if (arg === '--no-build') opts.build = false else if (arg === '--help' || arg === '-h') { console.log( 'Usage: deno task visual:capture [--out DIR] [--only app,app] [--no-build]', ) Deno.exit(0) } else { console.error(`Unknown argument: ${arg}`) Deno.exit(1) } } return opts}
if (import.meta.main) await main()