| 6 | // replaced by their bitmap, form state baked into attributes, scripts/links |
| 7 | // removed), <name>.meta.json (frame width/height). |
| 8 | import { chromium, type FrameLocator, type Page } from '@playwright/test'; |
| 9 | import fs from 'node:fs'; |
| 10 | import path from 'node:path'; |
| 11 | import { fileURLToPath } from 'node:url'; |
| 12 |
| 13 | const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..'); |
| 14 | const genDir = path.join(root, 'corpus', 'generated'); |
| 15 | const outDir = process.argv[2]; |
| 16 | if (!outDir) throw new Error('usage: corepack pnpm tsx scripts/blitz-experiment/dump-dom.mts <outDir> [filter] (dev server on 127.0.0.1:5173 must be running)'); |
| 17 | const filter = process.argv[3] ?? ''; |
| 18 | fs.mkdirSync(outDir, { recursive: true }); |
| 19 |
| 20 | const files: string[] = []; |
| 21 | for (const batch of fs.readdirSync(genDir).sort()) { |
| 22 | const dir = path.join(genDir, batch); |
| 23 | if (!fs.statSync(dir).isDirectory()) continue; |
| 24 | for (const f of fs.readdirSync(dir).sort()) if (f.endsWith('.html') && f.includes(filter)) files.push(`${batch}/${f}`); |
| 25 | } |
| 26 |
| 27 | async function waitReady(page: Page) { |
| 28 | await page.waitForFunction('(() => { const s = window.__tw && window.__tw.state; return !!(s && (s.loaded || s.dead)); })()', null, { timeout: 60_000 }); |
| 29 | await page.waitForTimeout(600); |
| 30 | } |
| 31 |
| 32 | async function poke(frame: FrameLocator, page: Page): Promise<number> { |
| 33 | const buttons = frame.locator('button:visible, [role=button]:visible, input[type=button]:visible, input[type=submit]:visible'); |
| 34 | const n = Math.min(await buttons.count().catch(() => 0), 4); |
| 35 | for (let i = 0; i < n; i++) { |
| 36 | try { await buttons.nth(i).click({ timeout: 2000, force: true }); } catch {} |
| 37 | await page.waitForTimeout(150); |
| 38 | } |
| 39 | return n; |
| 40 | } |
| 41 |
| 42 | // Browser-side code as plain JS strings (tsx's keepNames would inject __name |
| 43 | // helpers into functions passed to page.evaluate). |
| 44 | const BLUR = `(() => { try { const d = document.querySelector('#reference-wrap iframe').contentDocument; if (d && d.activeElement && d.activeElement.blur) d.activeElement.blur(); } catch (e) {} })()`; |
| 45 | const DUMP = `(() => { |
| 46 | const f = document.querySelector('#reference-wrap iframe'); |
| 47 | const d = f.contentDocument; |
| 48 | const clone = d.documentElement.cloneNode(true); |
| 49 | const copyAttrs = (from, to) => { for (const a of Array.from(from.attributes)) if (a.name !== 'width' && a.name !== 'height') to.setAttribute(a.name, a.value); }; |
| 50 | // Canvas -> its bitmap. If Blitz were the renderer, canvas would be our own |
| 51 | // command-stream backend anyway; the bitmap stands in for it. |
| 52 | const origC = d.querySelectorAll('canvas'), cloneC = clone.querySelectorAll('canvas'); |
| 53 | cloneC.forEach((c, i) => { |
| 54 | const o = origC[i]; |
| 55 | const img = d.createElement('img'); |
| 56 | copyAttrs(o, img); |
| 57 | try { img.setAttribute('src', o.toDataURL('image/png')); } catch (e) {} |
| 58 | img.style.width = o.clientWidth + 'px'; |
| 59 | img.style.height = o.clientHeight + 'px'; |
| 60 | c.replaceWith(img); |
| 61 | }); |
| 62 | // Form state -> attributes. |
| 63 | const origF = d.querySelectorAll('input,textarea,select'), cloneF = clone.querySelectorAll('input,textarea,select'); |
| 64 | cloneF.forEach((el, i) => { |
| 65 | const o = origF[i]; |
| 66 | if (o.tagName === 'INPUT') { |
| 67 | if (o.type === 'checkbox' || o.type === 'radio') { if (o.checked) el.setAttribute('checked', ''); else el.removeAttribute('checked'); } |
| 68 | else el.setAttribute('value', o.value); |
| 69 | } else if (o.tagName === 'TEXTAREA') el.textContent = o.value; |
| 70 | else if (o.tagName === 'SELECT') { |
| 71 | const oo = o.options, co = el.options; |
| 72 | for (let k = 0; k < co.length; k++) { if (oo[k] && oo[k].selected) co[k].setAttribute('selected', ''); else co[k].removeAttribute('selected'); } |
| 73 | } |
| 74 | }); |
| 75 | clone.querySelectorAll('script,link,noscript').forEach((s) => s.remove()); |
| 76 | // Only data: images reach either renderer: Chromium's CSP blocks the rest, |
| 77 | // so take the src away rather than let a static renderer fetch it. |
| 78 | clone.querySelectorAll('img,source,video,audio').forEach((el) => { const v = el.getAttribute('src') || ''; if (v && !v.startsWith('data:')) el.removeAttribute('src'); el.removeAttribute('srcset'); }); |
| 79 | return { |
| 80 | html: '<!DOCTYPE html>\\n' + clone.outerHTML, |
| 81 | width: f.clientWidth, |
| 82 | height: f.clientHeight, |
| 83 | docHeight: Math.ceil(d.documentElement.getBoundingClientRect().height), |
| 84 | bodyBg: getComputedStyle(d.body).backgroundColor, |
| 85 | canvases: origC.length, |
| 86 | svgs: d.querySelectorAll('svg').length, |
| 87 | inputs: origF.length, |
| 88 | }; |
| 89 | })()`; |
| 90 |
| 91 | const browser = await chromium.launch(); |
| 92 | const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, deviceScaleFactor: 1 }); |
| 93 | const page = await context.newPage(); |
| 94 | for (const file of files) { |
| 95 | const name = file.replace('/', '__'); |
| 96 | await page.goto(`http://127.0.0.1:5173/?file=generated/${file}&reference=1`); |
| 97 | await waitReady(page); |
| 98 | await page.waitForTimeout(800); |
| 99 | const sel = '#reference-wrap iframe'; |
| 100 | const clicks = await poke(page.frameLocator(sel), page); |
| 101 | // No :hover / :focus in the snapshot: a static renderer has neither. |
| 102 | await page.mouse.move(0, 0); |
| 103 | await page.evaluate(BLUR); |
| 104 | await page.waitForTimeout(500); |
| 105 | const buf = await page.locator(sel).screenshot({ animations: 'disabled', caret: 'hide' }); |
| 106 | fs.writeFileSync(path.join(outDir, `${name}.reference.png`), buf); |
| 107 | const dump: any = await page.evaluate(DUMP); |
| 108 | fs.writeFileSync(path.join(outDir, `${name}.html`), dump.html); |
| 109 | fs.writeFileSync(path.join(outDir, `${name}.meta.json`), JSON.stringify({ ...dump, html: undefined, clicks, file }, null, 2)); |
| 110 | console.log(`${file}: ${dump.width}x${dump.height} (doc ${dump.docHeight}) clicks=${clicks} canvas=${dump.canvases} svg=${dump.svgs} inputs=${dump.inputs}`); |
| 111 | } |
| 112 | await browser.close(); |
| 113 |