Files
chrnx-dev-wp/scripts/capture-mobile-header-review.mjs
T

188 lines
5.8 KiB
JavaScript

import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from '@playwright/test';
const LOCAL_HOSTS = new Set( [ 'localhost', '127.0.0.1' ] );
const VIEWPORT = { width: 375, height: 844 };
const HEADER_CLIP = { x: 0, y: 0, width: 375, height: 500 };
const OUTPUT_DIRECTORY = fileURLToPath( new URL( '../tmp/imagegen/', import.meta.url ) );
const STORAGE_KEY = 'chrnx-theme';
function getBaseURL() {
let url;
try {
url = new URL( process.env.CHRNX_REVIEW_URL || 'http://localhost:8888' );
} catch {
throw new Error( 'Capture URL must be a valid local HTTP URL.' );
}
if (
url.protocol !== 'http:' ||
! LOCAL_HOSTS.has( url.hostname ) ||
url.username ||
url.password
) {
throw new Error( 'Capture URL must be credential-free HTTP on localhost or 127.0.0.1.' );
}
return url;
}
function getPngDimensions( buffer ) {
const signature = '89504e470d0a1a0a';
if ( buffer.length < 24 || buffer.subarray( 0, 8 ).toString( 'hex' ) !== signature ) {
throw new Error( 'Screenshot did not produce a valid PNG.' );
}
return {
width: buffer.readUInt32BE( 16 ),
height: buffer.readUInt32BE( 20 ),
};
}
const baseURL = getBaseURL();
const homeURL = new URL( '/', baseURL ).href;
await mkdir( OUTPUT_DIRECTORY, { recursive: true } );
const captures = [];
const browser = await chromium.launch( { timeout: 15_000 } );
async function waitForExpanded( page, selector, expanded ) {
await page.waitForFunction(
( [ target, expected ] ) =>
document.querySelector( target )?.getAttribute( 'aria-expanded' ) === expected,
[ selector, String( expanded ) ],
{ timeout: 5_000 },
);
}
async function resetHeader( page, theme ) {
await page.reload( { waitUntil: 'domcontentloaded', timeout: 15_000 } );
await page.waitForFunction(
( expectedTheme ) =>
localStorage.getItem( 'chrnx-theme' ) === expectedTheme &&
document.documentElement.dataset.theme === expectedTheme,
theme,
{ timeout: 5_000 },
);
const selectors = [
'[data-chrnx-search-button]',
'[data-chrnx-theme-button]',
'[data-chrnx-menu-toggle]',
];
for ( const selector of selectors ) {
await page.locator( selector ).waitFor( { state: 'visible', timeout: 5_000 } );
await waitForExpanded( page, selector, false );
}
await page.locator( '.chrnx-site-brand img' ).waitFor( { state: 'visible', timeout: 5_000 } );
await page.waitForFunction( () => document.fonts.status === 'loaded', null, { timeout: 5_000 } );
await page.evaluate( async () => {
for ( let y = 0; y <= document.documentElement.scrollHeight; y += window.innerHeight ) {
window.scrollTo( 0, y );
await new Promise( ( resolve ) =>
window.requestAnimationFrame( () => window.requestAnimationFrame( resolve ) ),
);
}
await Promise.race( [
Promise.all(
[ ...document.images ].map( ( image ) =>
image.complete ? Promise.resolve() : image.decode().catch( () => {} ),
),
),
new Promise( ( resolve ) => setTimeout( resolve, 3_000 ) ),
] );
window.scrollTo( 0, 0 );
} );
}
async function saveScreenshot( page, filename, options ) {
const path = join( OUTPUT_DIRECTORY, filename );
const buffer = await page.screenshot( {
path,
animations: 'disabled',
caret: 'hide',
...options,
} );
const dimensions = getPngDimensions( buffer );
if ( dimensions.width !== VIEWPORT.width ) {
throw new Error( 'Screenshot width did not match the mobile review viewport.' );
}
if ( options.clip && dimensions.height !== HEADER_CLIP.height ) {
throw new Error( 'Header screenshot height did not match the review crop.' );
}
captures.push( { path, ...dimensions } );
}
async function captureTheme( theme ) {
const context = await browser.newContext( {
viewport: VIEWPORT,
colorScheme: theme,
reducedMotion: 'reduce',
} );
const page = await context.newPage();
page.setDefaultTimeout( 5_000 );
page.setDefaultNavigationTimeout( 15_000 );
await page.route( '**/*', async ( route ) => {
const requestURL = new URL( route.request().url() );
if ( requestURL.protocol === 'http:' && LOCAL_HOSTS.has( requestURL.hostname ) ) {
await route.continue();
} else {
await route.abort( 'blockedbyclient' );
}
} );
try {
await page.goto( homeURL, { waitUntil: 'domcontentloaded', timeout: 15_000 } );
await page.evaluate(
( [ key, preference ] ) => {
localStorage.clear();
localStorage.setItem( key, preference );
},
[ STORAGE_KEY, theme ],
);
await resetHeader( page, theme );
await saveScreenshot( page, `home-mobile-${ theme }-v2.png`, { fullPage: true } );
for ( const state of [ 'search', 'theme', 'menu' ] ) {
await resetHeader( page, theme );
const triggerSelector = {
search: '[data-chrnx-search-button]',
theme: '[data-chrnx-theme-button]',
menu: '[data-chrnx-menu-toggle]',
}[ state ];
await page.locator( triggerSelector ).click( { timeout: 5_000 } );
await waitForExpanded( page, triggerSelector, true );
for ( const otherSelector of [
'[data-chrnx-search-button]',
'[data-chrnx-theme-button]',
'[data-chrnx-menu-toggle]',
] ) {
if ( otherSelector !== triggerSelector ) {
await waitForExpanded( page, otherSelector, false );
}
}
await saveScreenshot( page, `header-mobile-${ theme }-${ state }.png`, {
clip: HEADER_CLIP,
} );
}
} finally {
await context.close();
}
}
try {
await captureTheme( 'dark' );
await captureTheme( 'light' );
} finally {
await browser.close();
}
for ( const capture of captures ) {
process.stdout.write( `${ capture.path } ${ capture.width }x${ capture.height }\n` );
}