Files
faunosteo/scripts/visual-canvas.mjs
T

143 lines
5.9 KiB
JavaScript

// R3 visual check (plan 2026-10-14 §3 O6): screenshots of the editor canvas in a real
// Chromium, then a pixel comparison of two captures (reference vs candidate).
//
// capture: node scripts/visual-canvas.mjs capture <base-url> <out-dir>
// compare: node scripts/visual-canvas.mjs compare <reference-dir> <candidate-dir>
//
// Needs CHROME (an executable) and NODE_PATH pointing at a node_modules that holds
// playwright-core and pngjs, outside the repository (no project dependency). The base URL is
// a running dev server of the build to capture (the DEV origin, scripts/dev-env.sh).
// Each case opens the editor on a draft holding one observation of the demo report, so the
// canvas shows the states the editor shows when that observation is active.
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const DEMO = resolve(import.meta.dirname, '../apps/app/tests/fixtures/report-v3.demo.json')
const VIEWPORTS = { desktop: { width: 1280, height: 800 }, phone: { width: 390, height: 844 } }
const SETTLE_MS = 600
// A differing pixel counts as anti-aliasing when its channels move by at most this much and it
// sits next to a contrast edge of the reference; anything else is a regression.
const AA_MAX_DELTA = 96
const EDGE_CONTRAST = 48
function cases() {
const demo = JSON.parse(readFileSync(DEMO, 'utf8'))
const one = (obs) => ({ ...demo, observations: obs ? [obs] : [] })
return [
{ name: 'none', report: one(null) },
...demo.observations.map((obs) => ({ name: obs.id, report: one(obs) })),
]
}
async function openEditor(page, base, report) {
await page.goto(`${base}/`)
await page.evaluate((draft) => {
sessionStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
sessionStorage.setItem('osteo:draft', JSON.stringify(draft))
localStorage.setItem('osteo:locale', 'fr')
}, report)
await page.goto(`${base}/editor`)
await page.waitForSelector('.svg-canvas [data-anno-id="head-trigger"]')
await page.mouse.move(0, 0)
await page.waitForTimeout(SETTLE_MS)
}
async function shoot(locator, file) {
writeFileSync(file, await locator.screenshot({ animations: 'disabled' }))
}
async function capture(base, out) {
const { chromium } = require('playwright-core')
mkdirSync(out, { recursive: true })
const browser = await chromium.launch({ executablePath: process.env.CHROME })
const meta = { browser: browser.version(), base, at: new Date().toISOString() }
for (const [vp, size] of Object.entries(VIEWPORTS)) {
const page = await browser.newPage({ viewport: size, deviceScaleFactor: 1, locale: 'fr-FR' })
page.on('dialog', (d) => d.dismiss())
for (const c of cases()) {
await openEditor(page, base, c.report)
const main = page.locator('.svg-canvas').first()
await shoot(main, join(out, `${vp}.${c.name}.main.png`))
if (c.name === 'none') {
await page.locator('.svg-canvas [data-anno-id="hip"]').first().hover()
await page.waitForTimeout(SETTLE_MS)
await shoot(main, join(out, `${vp}.hover-hip.main.png`))
await page.mouse.move(0, 0)
}
await page.locator('.svg-canvas [data-anno-id="head-trigger"]').first().click({ force: true })
const head = page.locator('[role="dialog"] .svg-canvas')
await head.waitFor()
await page.waitForTimeout(SETTLE_MS)
await shoot(head, join(out, `${vp}.${c.name}.head.png`))
await page.keyboard.press('Escape')
}
await page.close()
}
await browser.close()
writeFileSync(join(out, 'meta.json'), `${JSON.stringify(meta, null, 2)}\n`)
console.log(`captured into ${out} (${meta.browser})`)
}
function pixel(png, x, y) {
const i = (png.width * y + x) << 2
return [png.data[i], png.data[i + 1], png.data[i + 2], png.data[i + 3]]
}
const delta = (a, b) => Math.max(...a.map((v, k) => Math.abs(v - b[k])))
function nearEdge(png, x, y) {
const here = pixel(png, x, y)
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -1; dx <= 1; dx++) {
const nx = x + dx
const ny = y + dy
if (nx < 0 || ny < 0 || nx >= png.width || ny >= png.height) continue
if (delta(here, pixel(png, nx, ny)) >= EDGE_CONTRAST) return true
}
}
return false
}
function comparePng(refFile, candFile) {
const { PNG } = require('pngjs')
const ref = PNG.sync.read(readFileSync(refFile))
const cand = PNG.sync.read(readFileSync(candFile))
if (ref.width !== cand.width || ref.height !== cand.height) {
return { verdict: 'regression', reason: `size ${ref.width}x${ref.height} vs ${cand.width}x${cand.height}` }
}
let diff = 0
let regressions = 0
let maxDelta = 0
for (let y = 0; y < ref.height; y++) {
for (let x = 0; x < ref.width; x++) {
const d = delta(pixel(ref, x, y), pixel(cand, x, y))
if (d === 0) continue
diff++
maxDelta = Math.max(maxDelta, d)
if (d > AA_MAX_DELTA || !nearEdge(ref, x, y)) regressions++
}
}
const verdict = diff === 0 ? 'identical' : regressions === 0 ? 'anti-aliasing' : 'regression'
return { verdict, diff, regressions, maxDelta, pixels: ref.width * ref.height }
}
function compare(refDir, candDir) {
const files = readdirSync(refDir).filter((f) => f.endsWith('.png')).sort()
const results = files.map((f) => ({ file: f, ...comparePng(join(refDir, f), join(candDir, f)) }))
for (const r of results) console.log(`${r.verdict.padEnd(13)} ${r.file} ${r.diff ?? ''} ${r.reason ?? ''}`)
const failed = results.filter((r) => r.verdict === 'regression').length
console.log(`${results.length} images, ${failed} regression(s)`)
process.exitCode = failed > 0 ? 1 : 0
}
const [mode, a, b] = process.argv.slice(2)
if (mode === 'capture' && a && b) await capture(a, b)
else if (mode === 'compare' && a && b) compare(a, b)
else {
console.error('usage: visual-canvas.mjs capture <base-url> <out-dir> | compare <ref-dir> <cand-dir>')
process.exitCode = 2
}