test(tests): R3 freeze O1 canvas trees and the visual comparison script

This commit is contained in:
bchanot committed 2026-10-14 23:26:20 +02:00
1 parent fbc9526e57
commit 47c5f49014
7 files changed
+40542

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+63
View File
@@ -0,0 +1,63 @@
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { expect } from 'vitest'
import { FIXTURES_DIR } from './goldens'
/**
* R3 freeze (plan 2026-10-14 §3 O1): a DOM tree as structure and semantic
* properties, never bytes. Elements by namespace + local name, attributes as
* a map keyed by qualified name (their order is not part of the contract),
* children in document order with text nodes kept (the canvas imports the
* drawing's whitespace), comments and processing instructions named.
*/
export type TreeNode =
| {
ns: string | null
name: string
attrs: Record<string, string>
children: TreeNode[]
}
| { text: string }
| { comment: string }
| { pi: string }
const ELEMENT = 1
const TEXT = 3
const CDATA = 4
const PI = 7
const COMMENT = 8
export function treeOf(node: Node): TreeNode {
if (node.nodeType === TEXT || node.nodeType === CDATA) {
return { text: node.nodeValue ?? '' }
}
if (node.nodeType === COMMENT) return { comment: node.nodeValue ?? '' }
if (node.nodeType === PI) return { pi: node.nodeName }
if (node.nodeType !== ELEMENT) throw new Error(`node type ${node.nodeType}`)
const el = node as Element
const attrs: Record<string, string> = {}
for (const name of Array.from(el.attributes, (a) => a.name).sort()) {
attrs[name] = el.getAttribute(name) ?? ''
}
return {
ns: el.namespaceURI,
name: el.localName,
attrs,
children: Array.from(el.childNodes, treeOf),
}
}
export const R3_GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/r3')
/** `MAKE_R3_GOLDEN=1` writes the R3 freeze; never set it without the owner's decision once frozen. */
export const MAKE_R3_GOLDEN = process.env.MAKE_R3_GOLDEN === '1'
export function checkR3Golden(name: string, actual: unknown): void {
const file = resolve(R3_GOLDEN_DIR, name)
if (MAKE_R3_GOLDEN) {
mkdirSync(R3_GOLDEN_DIR, { recursive: true })
writeFileSync(file, `${JSON.stringify(actual, null, 1)}\n`)
return
}
expect(actual, name).toEqual(JSON.parse(readFileSync(file, 'utf8')))
}
+71
View File
@@ -0,0 +1,71 @@
/**
* R3 freeze O1 (plan 2026-10-14 §3): the editor canvas as the TypeScript
* built it before the anatomy core moved to Rust. For each view, the whole
* tree with no state (root attributes, the drawing's nodes, the layer), and
* for every state set the editor can produce from the three reference
* reports (each observation active, zones of every view, as EditorRoute
* builds them) plus "every annotation", the annotation layer. After the
* switch the same assertions hold on the Rust composition: trees compared by
* structure and semantic properties, never by bytes or attribute order.
*/
import { beforeAll, describe, expect, it } from 'vitest'
import { buildViewSvg, type ViewStates } from '@/anatomy/drawing'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadTestSheet } from '../helpers/sheet'
import {
buildGoldenReports,
GOLDEN_REPORTS,
type GoldenReports,
} from '../helpers/goldenReports'
import { checkR3Golden, treeOf, type TreeNode } from '../helpers/svgTree'
let sheet: SheetIndex
let golden: GoldenReports
beforeAll(async () => {
sheet = await loadTestSheet()
golden = buildGoldenReports(sheet)
})
const VIEWS = ['main', 'head'] as const
/** The state sets of the editor: no selection, every observation of the three reports, all. */
function stateCases(): Array<[string, ViewStates]> {
const cases: Array<[string, ViewStates]> = [['none', new Map()]]
for (const name of GOLDEN_REPORTS) {
for (const obs of golden.reports[name].observations) {
const states = new Map<string, 'current'>()
obs.zones.forEach((z) => states.set(z.annotationId, 'current'))
cases.push([`${name}:${obs.id}`, states])
}
}
const all = new Map<string, 'current'>()
sheet.sheet.document.annotations.forEach((a) => all.set(a.id, 'current'))
cases.push(['all', all])
return cases
}
/** The layer is the last element child of the root; everything before it is the drawing. */
function layerOf(tree: TreeNode): TreeNode {
if (!('children' in tree)) throw new Error('not an element')
const last = tree.children.at(-1)
if (!last || !('attrs' in last) || last.attrs['data-layer'] !== 'annotations') {
throw new Error('the layer is not the last child')
}
return last
}
describe.each(VIEWS)('the %s canvas', (viewId) => {
it('builds the frozen tree with no state', () => {
const tree = treeOf(buildViewSvg(sheet, viewId, new Map()))
checkR3Golden(`canvas.${viewId}.json`, tree)
})
it('builds the frozen layer for every state set of the reference reports', () => {
const layers: Record<string, TreeNode> = {}
for (const [name, states] of stateCases()) {
layers[name] = layerOf(treeOf(buildViewSvg(sheet, viewId, states)))
}
expect(Object.keys(layers).length).toBeGreaterThan(8)
checkR3Golden(`canvas.${viewId}.layers.json`, layers)
})
})
+142
View File
@@ -0,0 +1,142 @@
// 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
}