| 1 | // The posted pictures against the pipeline: every widget of the visual set drawn through the sandbox on the web |
| 2 | // dev app (apps/web: QuickJS worker → validator → the shadow renderer, the web product renderer) at the reference |
| 3 | // width and DPR, before any input, and compared with its reference picture (refs/visual/<widget>[.dark].png, drawn |
| 4 | // natively by Chromium in reference mode). A picture must show what widget profile 1 draws: a feature that Chromium |
| // draws and the profile removes (a canvas pattern, a popover's top layer) is neutralised in reference mode, by the |
| 6 | // stage's <template data-ref> or by the widget itself (T.mode == 'ref'), or the two differ here. A difference is |
| 7 | // either such a reference or a bug of the pipeline; the pixel diff points at the rows. Stages marked |
| 8 | // data-illustration (motion, a state after input) are left out of both. The client-SDK group is not compared: its |
| 9 | // pictures show the SDK stand-in's state (a fixed clock, the chat type, the cap), not the dev app's. |
| 10 | // build.ts runs it after drawing the pictures, on the dev server it starts for the height gate. |
| 11 | // |
| 12 | // Needs the dev server of this checkout: corepack pnpm dev --port 5175 |
| 13 | // corepack pnpm tsx scripts/conformance/picture-check.ts --origin http://127.0.0.1:5175 [--only 13-out] [--renderer shadow|iframe] |
| 14 |
| 15 | import fs from 'node:fs'; |
| 16 | import path from 'node:path'; |
| 17 | import { pathToFileURL } from 'node:url'; |
| 18 | import { chromium, type Page } from '@playwright/test'; |
| 19 | import { PNG } from 'pngjs'; |
| 20 | import { ROOT, listWidgets, picturePath, type Widget } from './lib'; |
| 21 | import { diffStats } from '../../packages/conformance/tools/diff.mjs'; |
| 22 | import { checkContentSafeArea } from '../../packages/core/src/shared/sdk-policy.ts'; |
| 23 |
| 24 | /** At most this share of the ink may differ (the pipeline and the reference agree to under 0.1 % today), and the heights by this many CSS px. */ |
| 25 | export const PICTURE_CHECK = { maxDiff: 0.005, height: 2 }; |
| 26 | const WIDTH = 390; |
| 27 | const DPR = 2; |
| 28 | const OUT = path.join(ROOT, 'reports', 'conformance', 'pictures'); |
| 29 |
| 30 | const isChecked = (w: Widget) => w.set === 'visual' && !w.id.startsWith('visual/sdk/'); |
| 31 |
| 32 | /** Loads the widget at the reference width and returns its picture and the stage rects it published, once it ran its checks (or waits for input). */ |
| 33 | async function draw(page: Page, w: Widget): Promise<{ png: PNG; stages: Record<string, number[]> }> { |
| 34 | await page.evaluate(({ html, name, width, safeArea }) => { |
| 35 | const wrap = document.querySelector('#sandbox-wrap') as HTMLElement; |
| 36 | (wrap.closest('.chat') as HTMLElement).style.width = width + 'px'; |
| 37 | const bubble = wrap.closest('.bubble') as HTMLElement; |
| 38 | bubble.style.padding = '0'; |
| 39 | bubble.style.borderRadius = '0'; |
| 40 | bubble.style.boxShadow = 'none'; |
| 41 | const tw = (window as any).__tw; |
| 42 | const m: any = ((window as any).__pictures = { attr: null, html: null }); |
| 43 | // The client's time over the corner (the header's safeArea): the dev app passes the band and draws the time over the bubble. |
| 44 | tw.setSafeArea(safeArea); |
| 45 | tw.load(html, name); |
| 46 | tw.host.element.setAttribute('data-conf-el', ''); |
| 47 | const r = tw.host.renderer; |
| 48 | const send = r.send.bind(r); |
| 49 | r.send = (msg: any) => { |
| 50 | if (msg?.type === 'ops') { |
| 51 | for (const op of msg.ops) { |
| 52 | if (op.op === 'el' && op.adopt === 'html') { |
| 53 | m.html = op.id; |
| 54 | for (const [n, v] of op.attrs) if (n === 'data-conformance') m.attr = v; |
| 55 | } else if (op.op === 'attr' && op.id === m.html && op.name === 'data-conformance') m.attr = op.value; |
| 56 | } |
| 57 | } |
| 58 | return send(msg); |
| 59 | }; |
| 60 | }, { html: w.html, name: `conformance/${w.id}.html`, width: WIDTH, safeArea: w.meta.safeArea ?? null }); |
| 61 | let pub: any = null; |
| 62 | const t0 = Date.now(); |
| 63 | while (Date.now() - t0 < 15_000) { |
| 64 | pub = await page.evaluate(() => { try { return JSON.parse((window as any).__pictures.attr); } catch { return null; } }); |
| 65 | if (pub && (pub.status === 'done' || pub.status === 'awaiting')) break; |
| 66 | if (await page.evaluate(() => (window as any).__tw.state.dead)) break; |
| 67 | await page.waitForTimeout(100); |
| 68 | } |
| 69 | // As long as build.ts waits before its picture. |
| 70 | await page.waitForTimeout(300); |
| 71 | // The renderer element can sit at a fractional CSS position: clip at the snapped origin, as run-web.ts crops. |
| 72 | const box = (await page.locator('[data-conf-el]').boundingBox())!; |
| 73 | const shot = await page.screenshot({ clip: { x: Math.round(box.x), y: Math.round(box.y), width: WIDTH, height: Math.max(Math.ceil(box.height), 40) }, animations: 'allow', caret: 'hide' }); |
| 74 | return { png: PNG.sync.read(shot), stages: pub?.stages ?? {} }; |
| 75 | } |
| 76 |
| 77 | /** The corner box the client's time takes over the bottom of a picture `height` CSS px tall (the header's safeArea), as [x, y, w, h]. */ |
| 78 | function timeCorner(w: Widget, height: number): number[] | null { |
| 79 | const a = checkContentSafeArea(w.meta.safeArea ?? null); |
| 80 | const corner = a.cornerRight || a.cornerLeft; |
| 81 | if (!a.bottom || !corner) return null; |
| 82 | return [a.cornerRight ? WIDTH - corner : 0, height - a.bottom, corner, a.bottom]; |
| 83 | } |
| 84 |
| 85 | /** The top `h` device rows of `png`, with the rects (CSS px) painted white. */ |
| 86 | function prepare(png: PNG, h: number, masks: number[][]): PNG { |
| 87 | const out = new PNG({ width: png.width, height: h }); |
| 88 | PNG.bitblt(png, out, 0, 0, png.width, h, 0, 0); |
| 89 | for (const [x, y, w, hh] of masks) { |
| 90 | const x0 = Math.max(0, Math.floor(x * DPR) - 2), y0 = Math.max(0, Math.floor(y * DPR) - 2); |
| 91 | const x1 = Math.min(out.width, Math.ceil((x + w) * DPR) + 2), y1 = Math.min(h, Math.ceil((y + hh) * DPR) + 2); |
| 92 | for (let yy = y0; yy < y1; yy++) out.data.fill(255, (yy * out.width + x0) * 4, (yy * out.width + x1) * 4); |
| 93 | } |
| 94 | return out; |
| 95 | } |
| 96 |
| 97 | /** The CSS-px rows that hold differing pixels (red in the diff image), a few per device row at least: single ones are glyph noise. */ |
| 98 | function diffRows(img: { width: number; height: number; data: Uint8Array }): [number, number] | null { |
| 99 | let top = -1, bottom = -1; |
| 100 | for (let y = 0; y < img.height; y++) { |
| 101 | let n = 0; |
| 102 | for (let x = 0; x < img.width; x++) { |
| 103 | const p = (y * img.width + x) * 4; |
| 104 | if (img.data[p] === 255 && img.data[p + 1] === 0 && img.data[p + 2] === 0) n++; |
| 105 | } |
| 106 | if (n >= 4) { if (top < 0) top = y; bottom = y; } |
| 107 | } |
| 108 | return top < 0 ? null : [Math.floor(top / DPR), Math.ceil(bottom / DPR)]; |
| 109 | } |
| 110 |
| 111 | /** |
| 112 | * Draws `widgets` (the visual set among them) through the dev app at `origin` and returns the ones whose reference |
| 113 | * picture differs from the pipeline's, as "<id>[ (dark)]: what differs". The pipeline's pictures and the diffs go to |
| 114 | * reports/conformance/pictures. |
| 115 | */ |
| 116 | export async function checkPictures(widgets: Widget[], origin: string, renderer = 'shadow', log = console.log): Promise<string[]> { |
| 117 | const list = widgets.filter(isChecked); |
| 118 | if (!list.length) return []; |
| 119 | const browser = await chromium.launch(); |
| 120 | const page = await (await browser.newContext({ viewport: { width: 1400, height: 2400 }, deviceScaleFactor: DPR })).newPage(); |
| 121 | const bad: string[] = []; |
| 122 | fs.mkdirSync(OUT, { recursive: true }); |
| 123 | log(`${renderer}, ${WIDTH} px; at most ${PICTURE_CHECK.maxDiff * 100} % of the ink and ${PICTURE_CHECK.height} px of height may differ`); |
| 124 | try { |
| 125 | for (const theme of ['light', 'dark'] as const) { |
| 126 | const todo = list.filter((w) => fs.existsSync(picturePath(w, theme))); |
| 127 | if (!todo.length) continue; |
| 128 | const q = new URLSearchParams({ theme, features: 'webAnimations', policy: 'strict' }); |
| 129 | if (renderer !== 'iframe') q.set(renderer, '1'); |
| 130 | await page.goto(`${origin}/?${q}`); |
| 131 | await page.waitForFunction(() => !!(window as any).__tw, null, { timeout: 60_000 }); |
| 132 | for (const w of todo) { |
| 133 | const label = `${w.id}${theme === 'dark' ? ' (dark)' : ''}`; |
| 134 | const ref = PNG.sync.read(fs.readFileSync(picturePath(w, theme))); |
| 135 | const got = await draw(page, w); |
| 136 | const masks = w.stages.filter((s) => s.illustration && got.stages[s.name]).map((s) => got.stages[s.name]); |
| 137 | const h = Math.min(ref.height, got.png.height); |
| 138 | // The client's time over the corner is the client's drawing (the dev app's and the build's agree, but it is no part of the widget). |
| 139 | const corner = timeCorner(w, h / DPR); |
| 140 | if (corner) masks.push(corner); |
| 141 | const d = diffStats(prepare(got.png, h, masks), prepare(ref, h, masks)); |
| 142 | const tall = Math.abs(ref.height - got.png.height) / DPR; |
| 143 | const rows = diffRows(d.image); |
| 144 | const problems = [ |
| 145 | tall > PICTURE_CHECK.height ? `the picture is ${ref.height / DPR} px tall, the pipeline draws ${got.png.height / DPR} px` : '', |
| 146 | d.ink > PICTURE_CHECK.maxDiff ? `${(d.ink * 100).toFixed(1)} % of the ink differs${rows ? `, rows ${rows[0]}–${rows[1]} px` : ''}` : '', |
| 147 | ].filter(Boolean); |
| 148 | if (problems.length) bad.push(`${label}: ${problems.join('; ')}`); |
| 149 | const file = path.join(OUT, `${w.stem}${theme === 'dark' ? '.dark' : ''}`); |
| 150 | fs.writeFileSync(`${file}.png`, PNG.sync.write(got.png)); |
| 151 | fs.writeFileSync(`${file}.diff.png`, PNG.sync.write(Object.assign(new PNG({ width: d.image.width, height: d.image.height }), { data: d.image.data }))); |
| 152 | log(`${label.padEnd(40)} ${(d.ink * 100).toFixed(2).padStart(6)} % ${String(got.png.height / DPR).padStart(4)} / ${String(ref.height / DPR).padStart(4)} px${masks.length ? ` (${masks.length} illustrated)` : ''}${problems.length ? ' DIFFERS' : ''}`); |
| 153 | } |
| 154 | } |
| 155 | } finally { |
| 156 | await browser.close(); |
| 157 | } |
| 158 | return bad; |
| 159 | } |
| 160 |
| 161 | async function main() { |
| 162 | const args = process.argv.slice(2); |
| 163 | const opt = (name: string) => (args.includes('--' + name) ? args[args.indexOf('--' + name) + 1] : undefined); |
| 164 | const bad = await checkPictures(listWidgets(opt('only')), opt('origin') ?? 'http://127.0.0.1:5175', opt('renderer') ?? 'shadow'); |
| 165 | if (bad.length) { |
| 166 | console.log(`\nreference pictures that differ from the widget drawn through the sandbox (diffs in ${path.relative(process.cwd(), OUT)}):`); |
| 167 | for (const b of bad) console.log(' ' + b); |
| 168 | process.exitCode = 1; |
| 169 | } |
| 170 | } |
| 171 |
| 172 | if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main().catch((e) => { console.error(e); process.exit(1); }); |
| 173 |