| 1 | // Compat check for generated widgets (corpus/generated/**, see |
| 2 | // scripts/generate-corpus.ts) and, with CORPUS_GROUP=htmlbubbles-ported, for the |
| 3 | // ported Telegram demos (pnpm test:htmlbubbles). No per-widget script: each widget is loaded in |
| 4 | // sandbox and reference mode, every visible button is clicked once (up to 4), |
| 5 |
| 6 | // TW_RENDERER=blitz|litehtml runs the sandbox side on a native wasm renderer instead of |
| 7 | // the iframe (pnpm build:blitz-web first): a canvas, so no buttons are clicked, |
| 8 | // and the report goes to docs/compat-report-<group>-blitz.md — the pixel |
| 9 | // threshold is not a pass criterion there (another rasterizer, see |
| 10 | // docs/blitz-experiment.md), the gallery is. TW_RENDERER=shadow runs it on the |
| 11 | // Shadow DOM renderer (no iframe, docs/shadow-dom-renderer.md): the same engine, |
| 12 | // so clicks and the pixel threshold apply as for the iframe; report |
| 13 | // docs/compat-report-<group>-shadow.md. CORPUS_GROUP=safe-area (pnpm test:safe-area-corpus) draws both sides as a client |
| 14 | // without a caption: the dev app's time control (?time=corner: the reference band and the time over both columns) and, |
| 15 | // for the reference frame, Chromium's own env(safe-area-inset-*) through its safe-area override. |
| 16 |
| 17 | import { expect, test, type FrameLocator, type Locator, type Page } from '@playwright/test'; |
| 18 | import fs from 'node:fs'; |
| 19 | import path from 'node:path'; |
| 20 | import { fileURLToPath } from 'node:url'; |
| 21 | import pixelmatch from 'pixelmatch'; |
| 22 | import { PNG } from 'pngjs'; |
| 23 | import { REFERENCE_TIME_CORNER } from '../packages/core/src/shared/reference.ts'; |
| 24 |
| 25 | const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); |
| 26 | const GROUP = process.env.CORPUS_GROUP ?? 'generated'; |
| 27 | /** 'blitz' | 'litehtml' | 'shadow': the renderer the sandbox side runs on instead of the iframe (wasm: pnpm build:<name>-web first), '' for the iframe. */ |
| 28 | const NATIVE = ['blitz', 'litehtml', 'shadow'].includes(process.env.TW_RENDERER ?? '') ? process.env.TW_RENDERER! : ''; |
| 29 | /** A canvas renderer: no clicks, pixel diff informational. The shadow renderer is DOM like the iframe. */ |
| 30 | const BLITZ = NATIVE === 'blitz' || NATIVE === 'litehtml'; |
| 31 | const SHADOW = NATIVE === 'shadow'; |
| 32 | const SUFFIX = NATIVE ? `-${NATIVE}` : ''; |
| 33 | /** corpus/safe-area: the client's time over the corner (docs/sdk-v1.md §2.17), on both sides. */ |
| 34 | const SAFE_AREA = GROUP === 'safe-area'; |
| 35 | const genDir = path.join(root, 'corpus', GROUP); |
| 36 | const outDir = path.join(root, 'reports', GROUP + SUFFIX); // outside test-results/, see compat.spec.ts |
| 37 | fs.mkdirSync(outDir, { recursive: true }); |
| 38 |
| 39 | const files: string[] = []; |
| 40 | if (fs.existsSync(genDir)) { |
| 41 | for (const batch of fs.readdirSync(genDir).sort()) { |
| 42 | const dir = path.join(genDir, batch); |
| 43 | if (!fs.statSync(dir).isDirectory()) continue; |
| 44 | for (const f of fs.readdirSync(dir).sort()) if (f.endsWith('.html')) files.push(`${batch}/${f}`); |
| 45 | } |
| 46 | } |
| 47 |
| 48 | const TOLERANCE = 0.03; |
| 49 |
| 50 | interface Result { file: string; batch: string; loaded: boolean; errors: string[]; diags: string[]; diff: number; clicks: number; pass: boolean; unsupported: string[] } |
| 51 | const resultFile = (file: string) => path.join(outDir, file.replace(/[^\w.-]+/g, '_') + '.result.json'); |
| 52 |
| 53 | async function waitReady(page: Page) { |
| 54 | await page.waitForFunction(() => { const s = (window as any).__tw?.state; return s && (s.loaded || s.dead); }, null, { timeout: 60_000 }); |
| 55 | await page.waitForTimeout(600); |
| 56 | } |
| 57 |
| 58 | async function poke(frame: FrameLocator | Locator, page: Page): Promise<number> { |
| 59 | const buttons = frame.locator('button:visible, [role=button]:visible, input[type=button]:visible, input[type=submit]:visible'); |
| 60 | const n = Math.min(await buttons.count().catch(() => 0), 4); |
| 61 | for (let i = 0; i < n; i++) { |
| 62 | try { await buttons.nth(i).click({ timeout: 2000, force: true }); } catch {} |
| 63 | await page.waitForTimeout(150); |
| 64 | } |
| 65 | return n; |
| 66 | } |
| 67 |
| 68 | async function run(page: Page, file: string, mode: 'sandbox' | 'reference') { |
| 69 | const blitz = BLITZ && mode === 'sandbox'; |
| 70 | const shadow = SHADOW && mode === 'sandbox'; |
| 71 | if (SAFE_AREA) { |
| 72 | // The reference frame is the browser's own: its env() gets the band from Chromium (the sandbox's is rewritten to the host's variables). |
| 73 | const cdp = await page.context().newCDPSession(page); |
| 74 | await cdp.send('Emulation.setSafeAreaInsetsOverride' as any, { insets: { top: 0, right: 0, bottom: REFERENCE_TIME_CORNER.bottom, left: 0 } }); |
| 75 | } |
| 76 | await page.goto(`/?file=${GROUP}/${file}${mode === 'reference' ? '&reference=1' : ''}${blitz || shadow ? `&${NATIVE}=1` : ''}${SAFE_AREA ? '&time=corner' : ''}`); |
| 77 | await waitReady(page); |
| 78 | if (mode === 'reference') await page.waitForTimeout(800); |
| 79 | if (blitz) { |
| 80 | // The wasm renderer paints on its own rAF clock; its first raster follows `loaded` closely, the Playwright click cannot see into a canvas. |
| 81 | await page.waitForFunction((name) => ((window as any).__tw[name]?.paints ?? 0) > 0, NATIVE, { timeout: 30_000 }).catch(() => {}); |
| 82 | await page.waitForTimeout(300); |
| 83 | } |
| 84 | const sel = blitz ? '#sandbox-wrap canvas' : shadow ? '#sandbox-wrap .widget-shadow' : mode === 'sandbox' ? '#sandbox-wrap iframe' : '#reference-wrap iframe'; |
| 85 | // Playwright's CSS engine pierces open shadow roots: the host element locator reaches the widget's buttons. |
| 86 | const clicks = blitz ? 0 : await poke(shadow ? page.locator(sel) : page.frameLocator(sel), page); |
| 87 | await page.waitForTimeout(500); |
| 88 | const buf = await page.locator(sel).screenshot({ animations: 'disabled', caret: 'hide' }); |
| 89 | fs.writeFileSync(path.join(outDir, `${file.replace('/', '__')}.${mode}.png`), buf); |
| 90 | const state = await page.evaluate(() => { const st = (window as any).__tw.state; return { loaded: st.loaded, dead: st.dead, diags: st.diags, logs: st.logs }; }); |
| 91 | return { png: PNG.sync.read(buf), clicks, state }; |
| 92 | } |
| 93 |
| 94 | function diffImages(a: PNG, b: PNG, file: string): number { |
| 95 | const w = Math.max(a.width, b.width), h = Math.max(a.height, b.height); |
| 96 | const pad = (img: PNG) => { if (img.width === w && img.height === h) return img; const o = new PNG({ width: w, height: h }); o.data.fill(255); PNG.bitblt(img, o, 0, 0, img.width, img.height, 0, 0); return o; }; |
| 97 | const out = new PNG({ width: w, height: h }); |
| 98 | const n = pixelmatch(pad(a).data, pad(b).data, out.data, w, h, { threshold: 0.15, includeAA: true }); |
| 99 | fs.writeFileSync(path.join(outDir, `${file.replace('/', '__')}.diff.png`), PNG.sync.write(out)); |
| 100 | return n / (w * h); |
| 101 | } |
| 102 |
| 103 | test.skip(files.length === 0, `no corpus/${GROUP} — run pnpm generate-corpus (or extract + port the Telegram demos) first`); |
| 104 |
| 105 | for (const file of files) { |
| 106 | test(`${GROUP} ${file}`, async ({ page }) => { |
| 107 | test.setTimeout(120_000); |
| 108 | const sb = await run(page, file, 'sandbox'); |
| 109 | const ref = await run(page, file, 'reference'); |
| 110 | const diff = diffImages(sb.png, ref.png, file); |
| 111 | const errors = (sb.state.logs as any[]).filter((l) => l.level === 'error').map((l) => String(l.text).split('\n')[0].slice(0, 160)); |
| 112 | const diagEntries = Object.entries(sb.state.diags as Record<string, { count: number; details: string[] }>); |
| 113 | const unsupported = diagEntries.filter(([k]) => ['unsupported', 'script-skipped', 'network-blocked', 'url-blocked', 'tag-dropped'].includes(k)).map(([k, v]) => `${k}: ${v.details.slice(0, 2).join('; ')}`); |
| 114 | const pass = !!sb.state.loaded && !sb.state.dead && errors.length === 0 && (BLITZ || diff <= TOLERANCE); |
| 115 | const result: Result = { file, batch: file.split('/')[0], loaded: !!sb.state.loaded && !sb.state.dead, errors, diags: diagEntries.filter(([k]) => k !== 'boot' && k !== 'library').map(([k, v]) => `${k}×${v.count}`), diff, clicks: sb.clicks, pass, unsupported }; |
| 116 | fs.writeFileSync(resultFile(file), JSON.stringify(result)); |
| 117 | expect.soft(sb.state.dead, 'sandbox died').toBeNull(); |
| 118 | expect.soft(errors, 'sandbox JS errors').toHaveLength(0); |
| 119 | if (!BLITZ) expect.soft(diff, 'pixel diff').toBeLessThanOrEqual(TOLERANCE); |
| 120 | else expect.soft(sb.state.diags['renderer'], `${NATIVE} renderer diag`).toBeUndefined(); |
| 121 | }); |
| 122 | } |
| 123 |
| 124 | test.afterAll(() => { |
| 125 | const results: Result[] = fs.readdirSync(outDir).filter((f) => f.endsWith('.result.json')).map((f) => JSON.parse(fs.readFileSync(path.join(outDir, f), 'utf8')) as Result).sort((a, b) => a.file.localeCompare(b.file)); |
| 126 | if (!results.length) return; |
| 127 | const batches = [...new Set(results.map((r) => r.batch))]; |
| 128 | const cmd = (NATIVE ? `TW_RENDERER=${NATIVE} ` : '') + (GROUP === 'generated' ? 'pnpm test:generated' : `CORPUS_GROUP=${GROUP} pnpm test:generated`); |
| 129 | const lines = [`# Compat report — ${GROUP === 'generated' ? 'generated widgets' : GROUP}${BLITZ ? ` on the ${NATIVE} wasm renderer` : SHADOW ? ' on the Shadow DOM renderer (no iframe)' : ''}`, '', |
| 130 | BLITZ ? `Generated ${new Date().toISOString()} by \`${cmd}\`. Pass = loaded without JS errors on the ${NATIVE} renderer (no clicks: a canvas). The pixel diff against the native reference is informational — another rasterizer, see docs/blitz-experiment.md and docs/litehtml-renderer.md; judge by reports/${GROUP}${SUFFIX}/.` |
| 131 | : `Generated ${new Date().toISOString()} by \`${cmd}\`. Pass = loaded without JS errors and screenshot within ${TOLERANCE * 100}% of the native reference after clicking up to 4 buttons.`, '', |
| 132 | ...(SAFE_AREA ? [`Both sides are drawn as a client without a caption draws them: a ${REFERENCE_TIME_CORNER.bottom} px band with the time over a ${REFERENCE_TIME_CORNER.corner} px right corner (the dev app's \`?time=corner\`; Chromium's env() override for the reference frame).`, ''] : [])]; |
| 133 | for (const b of batches) { |
| 134 | const rs = results.filter((r) => r.batch === b); |
| 135 | const passed = rs.filter((r) => r.pass).length; |
| 136 | lines.push(`## ${b}: ${passed} / ${rs.length} pass (${Math.round((passed / rs.length) * 100)}%)`, '', '| Widget | Pass | Pixel diff | Clicks | Errors | Unsupported / blocked | Other diagnostics |', '|---|---|---|---|---|---|---|'); |
| 137 | for (const r of rs) lines.push(`| ${r.file.split('/')[1]} | ${r.pass ? '✅' : '❌'} | ${(r.diff * 100).toFixed(2)}% | ${r.clicks} | ${r.errors.join('<br>').replace(/\|/g, '\\|')} | ${r.unsupported.join('<br>').replace(/\|/g, '\\|')} | ${r.diags.join(', ')} |`); |
| 138 | lines.push(''); |
| 139 | } |
| 140 | fs.writeFileSync(path.join(root, 'docs', `compat-report-${GROUP}${SUFFIX}.md`), lines.join('\n')); |
| 141 | }); |
| 142 |