// Shooting one element of a live page FROM THE WINDOW, never with Chromium's // beyond-viewport capture. // // WHY. `page.screenshot({ fullPage: true, clip })` on a page taller than the // window makes Playwright ask Chromium for `captureBeyondViewport`, which // resizes the page's frame for the capture and back. The page sees that // resize. Measured on x.com (2026-10-27) in the X session profile: the page's // resize handler read the window as 1×1, X's responsive layout reflowed for // it mid-capture (its nav laid over the post, the column shifted ~100 px left, // the focal post moved down below its parent), and the pixels captured came // from that layout, not from the one the clip was measured in. Whether a shot // lands in the bad layout is a race, which is why the same post came out // offset on one capture and fine on the next. Re-measuring afterwards cannot // catch it: by then the page has laid itself out again. // // So the element is made to fit the window first — scrolled into it, and the // window grown (its height only, so no width breakpoint moves) when the element // is taller — the layout is let settle and measured again, and the shot is a // plain viewport clip: no resize during the capture, nothing for the page to // react to. The box is measured once more after the shot; a box that moved // means the page was still laying out, and the shot is taken again. // // A page that cannot grow its window (the tests' fakes), or an element taller // than the window may grow, gets `null`: the caller falls back to its // full-page clip. import type { PageLike } from "./playwrightRuntime"; // The element's box in VIEWPORT coordinates, and the window it is in. export type ElementView = { x: number; y: number; width: number; height: number; vw: number; vh: number; }; export type ViewportShotOptions = { // The element, as a selector the page can query (a marker attribute the // caller set) -- or several, shot as ONE box: their union (a reply's thread // shot, its parent's article over its own). Every one must be on the page. selector: string | ReadonlyArray; // Shoot at most this much of the element's height, from its top. maxHeight?: number; // The tallest window it will grow to (default 16 384 px). growLimit?: number; // How long a scroll or a resize is let settle before the box is read again. settleMs?: number; onLog?: (line: string) => void; }; export type ViewportShotResult = | { png: Uint8Array; trimmed: boolean } | { error: string }; // Room left above an element scrolled into the window: X's sticky column // header (53 px) would otherwise lie over the element's top. export const TOP_ROOM = 64; const BOTTOM_ROOM = 16; const DEFAULT_GROW_LIMIT = 16_384; const DEFAULT_SETTLE_MS = 750; // A box that moved by more than this between the measure and the check after // the shot was shot mid-layout. const MOVED_PX = 1; export const VIEW_SCRIPT_MARKER = "__archilyzerElementView"; // The smallest box holding every one of `boxes` (null for none): what a // selector list is shot as. The page runs the same arithmetic (viewScript). export function unionBox( boxes: ReadonlyArray<{ x: number; y: number; width: number; height: number }>, ): { x: number; y: number; width: number; height: number } | null { if (boxes.length === 0) return null; const left = Math.min(...boxes.map((b) => b.x)); const top = Math.min(...boxes.map((b) => b.y)); const right = Math.max(...boxes.map((b) => b.x + b.width)); const bottom = Math.max(...boxes.map((b) => b.y + b.height)); return { x: left, y: top, width: right - left, height: bottom - top }; } export const viewScript = (selector: string | ReadonlyArray) => `(() => { const ${VIEW_SCRIPT_MARKER} = true; const sels = ${JSON.stringify(typeof selector === "string" ? [selector] : [...selector])}; const rs = []; for (const s of sels) { const el = document.querySelector(s); if (!el) return null; rs.push(el.getBoundingClientRect()); } if (!rs.length) return null; const left = Math.min(...rs.map((r) => r.left)); const top = Math.min(...rs.map((r) => r.top)); const right = Math.max(...rs.map((r) => r.right)); const bottom = Math.max(...rs.map((r) => r.bottom)); return { x: left, y: top, width: right - left, height: bottom - top, vw: window.innerWidth, vh: window.innerHeight }; })()`; const scrollScript = (dy: number) => `window.scrollBy(0, ${Math.round(dy)})`; function asView(v: unknown): ElementView | null { const o = v as Partial | null; if (!o || typeof o !== "object") return null; for (const k of ["x", "y", "width", "height", "vw", "vh"] as const) { if (typeof o[k] !== "number" || !Number.isFinite(o[k])) return null; } return o as ElementView; } const fits = (v: ElementView, h: number) => v.x >= 0 && v.y >= 0 && v.x + v.width <= v.vw + 0.5 && v.y + h <= v.vh + 0.5; const moved = (a: ElementView, b: ElementView) => Math.abs(a.x - b.x) > MOVED_PX || Math.abs(a.y - b.y) > MOVED_PX || Math.abs(a.width - b.width) > MOVED_PX || Math.abs(a.height - b.height) > MOVED_PX || a.vw !== b.vw || a.vh !== b.vh; // null: this page cannot be shot from the window (the caller falls back). export async function shootFromViewport( page: PageLike, opts: ViewportShotOptions, ): Promise { const settleMs = opts.settleMs ?? DEFAULT_SETTLE_MS; const growLimit = opts.growLimit ?? DEFAULT_GROW_LIMIT; const measure = async () => asView(await page.evaluate(viewScript(opts.selector)).catch(() => null)); const first = await measure(); if (!first) return null; if (first.width < 1 || first.height < 1) return { error: "The element has no size to shoot." }; // Wider than the window: growing the width would move the page's // breakpoints, which is the very thing this avoids. if (first.width > first.vw) return null; const original = { width: first.vw, height: first.vh }; let grown = false; try { for (let attempt = 0; attempt < 2; attempt++) { let v = await measure(); if (!v) return { error: "The element vanished before its shot." }; const want = Math.ceil(Math.min(v.height, opts.maxHeight ?? Infinity)); // Into the window: its top below the sticky header. if (v.y < 0 || (v.y + want > v.vh && v.y > TOP_ROOM)) { await page.evaluate(scrollScript(v.y - TOP_ROOM)).catch(() => {}); await page.waitForTimeout(settleMs); v = (await measure()) ?? v; } // Taller than the window: grow the window to hold it. if (!fits(v, want)) { const height = Math.ceil(Math.max(v.y, 0) + want + BOTTOM_ROOM); if (!page.setViewportSize || height > growLimit) return null; await page.setViewportSize({ width: original.width, height }); grown = true; await page.waitForTimeout(settleMs); v = (await measure()) ?? v; } if (!fits(v, want)) { opts.onLog?.("The element did not stay inside the window; measuring it again."); continue; } const clip = { x: Math.max(0, Math.floor(v.x)), y: Math.max(0, Math.floor(v.y)), width: Math.ceil(v.width), height: want, }; const png = await page.screenshot({ type: "png", clip }); const after = await measure(); if (after && !moved(v, after)) return { png, trimmed: v.height > want }; opts.onLog?.("The element moved while it was being shot; shooting it again."); await page.waitForTimeout(settleMs); } return { error: "The element kept moving; no steady shot of it." }; } finally { if (grown) await page.setViewportSize?.(original).catch(() => {}); } }