Webdev-Bench / tasks /c28 /repo /scripts /screenshot.mjs
Roy-DOU's picture
Add files using upload-large-folder tool
d77bae9 verified
Raw History Blame Contribute Delete
2.8 kB
import { chromium } from 'playwright'
import { spawn } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const PORT = 4173
const URL = `http://localhost:${PORT}/`
const OUT = path.join(repoRoot, 'screenshots', 'full-page.png')
function waitForServer(url, timeoutMs = 30000) {
const started = Date.now()
return new Promise((resolve, reject) => {
const tick = async () => {
try {
const res = await fetch(url)
if (res.ok) return resolve()
} catch {
/* not up yet */
}
if (Date.now() - started > timeoutMs) return reject(new Error('preview server timeout'))
setTimeout(tick, 300)
}
tick()
})
}
const preview = spawn('npx', ['vite', 'preview', '--port', String(PORT), '--strictPort'], {
cwd: repoRoot,
stdio: ['ignore', 'pipe', 'pipe'],
})
preview.stdout.on('data', (d) => process.stdout.write(`[preview] ${d}`))
preview.stderr.on('data', (d) => process.stderr.write(`[preview] ${d}`))
const meta = {
url: URL,
screenshot: OUT,
ok: false,
pageHeightPx: null,
consoleErrors: [],
pageErrors: [],
}
try {
await waitForServer(URL)
const browser = await chromium.launch()
const page = await browser.newPage({
viewport: { width: 1920, height: 1080 },
deviceScaleFactor: 1,
})
page.on('console', (msg) => {
if (msg.type() === 'error') meta.consoleErrors.push(msg.text())
})
page.on('pageerror', (err) => meta.pageErrors.push(String(err)))
await page.goto(URL, { waitUntil: 'networkidle' })
// Scroll through the page so the IntersectionObserver reveals fire,
// then return to the top before capturing.
await page.evaluate(async () => {
const step = 700
const bottom = document.body.scrollHeight
for (let y = 0; y <= bottom; y += step) {
window.scrollTo({ top: y, behavior: 'instant' })
await new Promise((r) => setTimeout(r, 60))
}
window.scrollTo({ top: 0, behavior: 'instant' })
})
await page.waitForTimeout(900)
meta.pageHeightPx = await page.evaluate(() => document.body.scrollHeight)
mkdirSync(path.dirname(OUT), { recursive: true })
// Clip to the layout width so the capture is exactly 1920px wide.
await page.screenshot({
path: OUT,
fullPage: true,
clip: { x: 0, y: 0, width: 1920, height: meta.pageHeightPx },
})
meta.ok = true
await browser.close()
console.log(JSON.stringify(meta, null, 2))
} catch (err) {
meta.error = String(err)
console.error(err)
} finally {
writeFileSync(path.join(repoRoot, 'screenshots', 'meta.json'), JSON.stringify(meta, null, 2))
preview.kill('SIGTERM')
process.exit(meta.ok ? 0 : 1)
}