@@ -373,19 +373,77 @@ const maskTree = (tree: string, dotted: RegExp) =>
373373 } )
374374 . join ( "\n" ) ;
375375
376+ /** Chromium sizes the capture, so the reported size is read from the PNG header. */
377+ const pngSize = ( base64 : string ) => {
378+ const header = Buffer . from ( base64 . slice ( 0 , 32 ) , "base64" ) ;
379+ return { width : header . readUInt32BE ( 16 ) , height : header . readUInt32BE ( 20 ) } ;
380+ } ;
381+
382+ type Viewport = { readonly width : number ; readonly height : number } ;
383+
384+ /**
385+ * A page's display ratio and CSS viewport, read in an isolated world since page script can
386+ * reassign `devicePixelRatio`, `innerWidth`, and `innerHeight` in its own, and its page zoom.
387+ */
388+ export const readPageMetrics = async ( cdp : CDPSession ) => {
389+ const { frameTree } = await cdp . send ( "Page.getFrameTree" ) ;
390+ const { executionContextId } = await cdp . send ( "Page.createIsolatedWorld" , {
391+ frameId : frameTree . frame . id ,
392+ worldName : "t3-preview-metrics" ,
393+ } ) ;
394+ let { cssVisualViewport } = await cdp . send ( "Page.getLayoutMetrics" ) ;
395+ // Desktop zoom applies asynchronously; bracket the CSS metrics to reject a torn read.
396+ for ( let attempt = 0 ; attempt < 3 ; attempt += 1 ) {
397+ const zoom = cssVisualViewport . zoom ?? 1 ;
398+ const { result } = await cdp . send ( "Runtime.evaluate" , {
399+ expression : "({ ratio: devicePixelRatio, width: innerWidth, height: innerHeight })" ,
400+ contextId : executionContextId ,
401+ returnByValue : true ,
402+ } ) ;
403+ ( { cssVisualViewport } = await cdp . send ( "Page.getLayoutMetrics" ) ) ;
404+ if ( ( cssVisualViewport . zoom ?? 1 ) === zoom ) {
405+ const { ratio, width, height } = result . value as {
406+ readonly ratio : number ;
407+ readonly width : number ;
408+ readonly height : number ;
409+ } ;
410+ return {
411+ ratio,
412+ width,
413+ height,
414+ zoom,
415+ offset : { x : cssVisualViewport . pageX * zoom , y : cssVisualViewport . pageY * zoom } ,
416+ } ;
417+ }
418+ }
419+ throw new Error (
420+ "The page's zoom kept changing while the snapshot read its size. Try the snapshot again." ,
421+ ) ;
422+ } ;
423+
376424// Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets.
377425export const captureViewport = async (
378426 page : Page ,
379427 cdp : CDPSession ,
380- options : { readonly format : "png" | "jpeg" ; readonly quality ?: number ; readonly scale : number } ,
428+ options : {
429+ readonly format : "png" | "jpeg" ;
430+ readonly quality ?: number ;
431+ readonly scale : number ;
432+ readonly viewport ?: Viewport ;
433+ readonly offset ?: { readonly x : number ; readonly y : number } | undefined ;
434+ } ,
381435) => {
382436 let clip ;
383437 if ( options . scale < 1 ) {
384- const viewport = page . viewportSize ( ) ?? { width : 1280 , height : 800 } ;
385- const { cssVisualViewport } = await cdp . send ( "Page.getLayoutMetrics" ) ;
438+ const viewport = options . viewport ?? page . viewportSize ( ) ?? { width : 1280 , height : 800 } ;
439+ let offset = options . offset ;
440+ if ( ! offset ) {
441+ const { cssVisualViewport } = await cdp . send ( "Page.getLayoutMetrics" ) ;
442+ const zoom = cssVisualViewport . zoom ?? 1 ;
443+ offset = { x : cssVisualViewport . pageX * zoom , y : cssVisualViewport . pageY * zoom } ;
444+ }
386445 clip = {
387- x : cssVisualViewport . pageX ,
388- y : cssVisualViewport . pageY ,
446+ ...offset ,
389447 ...viewport ,
390448 scale : options . scale ,
391449 } ;
@@ -401,18 +459,39 @@ export const captureViewport = async (
401459type SnapshotInput = {
402460 readonly page : Page ;
403461 readonly cdp : CDPSession ;
404- readonly renderScale : number ;
462+ /** Headless pages render at the scale the server set; a desktop page at its display's. */
463+ readonly renderScale : number | "display" ;
405464 readonly consoleEntries : ReadonlyArray < PreviewAutomationConsoleEntry > ;
406465 readonly networkEntries : ReadonlyArray < PreviewAutomationNetworkEntry > ;
407466 readonly actionTimeline : PreviewAutomationSnapshot [ "actionTimeline" ] ;
408467} ;
409468
469+ /** The scale a page renders at and its viewport in device-independent pixels, a clip's units. */
470+ const renderingOf = async ( input : SnapshotInput ) => {
471+ if ( input . renderScale !== "display" ) {
472+ const viewport = input . page . viewportSize ( ) ?? { width : 1280 , height : 800 } ;
473+ return { renderScale : input . renderScale , viewport, offset : undefined } ;
474+ }
475+ // The display ratio a desktop page reports includes its page zoom, and its sizes are CSS pixels.
476+ const page = await readPageMetrics ( input . cdp ) ;
477+ return {
478+ renderScale : page . ratio / page . zoom ,
479+ offset : page . offset ,
480+ viewport : {
481+ width : Math . round ( page . width * page . zoom ) ,
482+ height : Math . round ( page . height * page . zoom ) ,
483+ } ,
484+ } ;
485+ } ;
486+
410487const capture = async (
411488 input : SnapshotInput ,
412489 deadline : number ,
413490) : Promise < PreviewAutomationSnapshot > => {
414- const viewport = input . page . viewportSize ( ) ?? { width : 1280 , height : 800 } ;
415- const scale = Math . min ( 1 , MAX_SCREENSHOT_WIDTH / ( viewport . width * input . renderScale ) ) ;
491+ const { renderScale, viewport, offset } = await renderingOf ( input ) ;
492+ // A late metrics reply must not begin a capture after viewers have resumed.
493+ if ( Date . now ( ) >= deadline ) throw tooBusy ( ) ;
494+ const scale = Math . min ( 1 , MAX_SCREENSHOT_WIDTH / ( viewport . width * renderScale ) ) ;
416495 const state = refsFor ( input . page ) ;
417496 invalidateRefs ( input . page ) ;
418497 const generation = state . generation ;
@@ -427,7 +506,7 @@ const capture = async (
427506 "url" | "title" | "loading" | "visibleText" | "interactiveElements"
428507 >
429508 > ,
430- captureViewport ( input . page , input . cdp , { format : "png" , scale } ) ,
509+ captureViewport ( input . page , input . cdp , { format : "png" , scale, viewport , offset } ) ,
431510 ] ) ;
432511 void pageAndScreenshot . catch ( constVoid ) ;
433512 // Leaves time for the second read; a frame that never loads holds the tree until then.
@@ -474,8 +553,7 @@ const capture = async (
474553 screenshot : {
475554 mimeType : "image/png" ,
476555 data,
477- width : Math . round ( viewport . width * input . renderScale * scale ) ,
478- height : Math . round ( viewport . height * input . renderScale * scale ) ,
556+ ...pngSize ( data ) ,
479557 } ,
480558 } ;
481559} ;
0 commit comments