195 lines
6.1 KiB
JavaScript
195 lines
6.1 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 OUTPUT_DIRECTORY = fileURLToPath( new URL( '../tmp/imagegen/', import.meta.url ) );
|
|
const STORAGE_KEY = 'chrnx-theme';
|
|
const THEMES = [ 'light', 'dark' ];
|
|
const VIEWPORTS = [
|
|
{ width: 375, height: 812 },
|
|
{ width: 768, height: 1024 },
|
|
{ width: 1440, height: 900 },
|
|
{ width: 2560, height: 1080 },
|
|
];
|
|
const TARGETS = [
|
|
{ name: 'music', path: '/music/' },
|
|
{ name: 'podcasts', path: '/podcasts/' },
|
|
{
|
|
name: 'podcasts-long-copy',
|
|
path: '/podcasts/',
|
|
longCopy: {
|
|
titleSelector: '.chrnx-latest-podcast .chrnx-podcast-card__title',
|
|
excerptSelector: '.chrnx-latest-podcast .chrnx-podcast-card__excerpt',
|
|
title:
|
|
'Cuando la conversación se alarga: arquitectura, cultura digital y las decisiones incómodas que sostienen un podcast independiente',
|
|
excerpt:
|
|
'Una descripción deliberadamente extensa para revisar el comportamiento real de la tarjeta más reciente cuando el título y el resumen ocupan varias líneas, sin modificar WordPress ni fabricar una segunda tarjeta.',
|
|
},
|
|
},
|
|
];
|
|
|
|
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 ) {
|
|
if (
|
|
buffer.length < 24 ||
|
|
buffer.subarray( 0, 8 ).toString( 'hex' ) !== '89504e470d0a1a0a'
|
|
) {
|
|
throw new Error( 'Screenshot did not produce a valid PNG.' );
|
|
}
|
|
|
|
return {
|
|
width: buffer.readUInt32BE( 16 ),
|
|
height: buffer.readUInt32BE( 20 ),
|
|
};
|
|
}
|
|
|
|
async function waitForStablePage( page ) {
|
|
await page.addStyleTag( {
|
|
content: '*,*::before,*::after{animation:none!important;transition:none!important}',
|
|
} );
|
|
await page.evaluate( async () => {
|
|
const timeout = new Promise( ( _, reject ) =>
|
|
setTimeout( () => reject( new Error( 'Timed out waiting for fonts and images.' ) ), 5_000 ),
|
|
);
|
|
const ready = ( async () => {
|
|
await document.fonts.ready;
|
|
for ( let y = 0; y <= document.documentElement.scrollHeight; y += window.innerHeight ) {
|
|
window.scrollTo( 0, y );
|
|
await new Promise( ( resolve ) =>
|
|
requestAnimationFrame( () => requestAnimationFrame( resolve ) ),
|
|
);
|
|
}
|
|
await Promise.all(
|
|
[ ...document.images ].map( async ( image ) => {
|
|
await image.decode();
|
|
if ( ! image.complete || image.naturalWidth === 0 ) {
|
|
throw new Error( `Image failed to decode: ${ image.currentSrc || image.src }` );
|
|
}
|
|
} ),
|
|
);
|
|
window.scrollTo( 0, 0 );
|
|
} )();
|
|
|
|
await Promise.race( [ ready, timeout ] );
|
|
} );
|
|
}
|
|
|
|
async function replaceLongCopy( page, target ) {
|
|
if ( ! target.longCopy ) {
|
|
return;
|
|
}
|
|
|
|
const title = page.locator( target.longCopy.titleSelector );
|
|
const excerpt = page.locator( target.longCopy.excerptSelector );
|
|
await title.waitFor( { state: 'visible', timeout: 5_000 } );
|
|
await excerpt.waitFor( { state: 'visible', timeout: 5_000 } );
|
|
await title.evaluate( ( element, value ) => {
|
|
element.textContent = value;
|
|
}, target.longCopy.title );
|
|
await excerpt.evaluate( ( element, value ) => {
|
|
element.textContent = value;
|
|
}, target.longCopy.excerpt );
|
|
}
|
|
|
|
async function capture( baseURL, target, viewport, theme ) {
|
|
const browser = await chromium.launch();
|
|
let context;
|
|
try {
|
|
context = await browser.newContext( {
|
|
viewport,
|
|
colorScheme: theme,
|
|
reducedMotion: 'reduce',
|
|
} );
|
|
await context.addInitScript(
|
|
( [ key, preference ] ) => {
|
|
localStorage.clear();
|
|
localStorage.setItem( key, preference );
|
|
},
|
|
[ STORAGE_KEY, theme ],
|
|
);
|
|
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' );
|
|
}
|
|
} );
|
|
|
|
const response = await page.goto( new URL( target.path, baseURL ).href, {
|
|
waitUntil: 'domcontentloaded',
|
|
timeout: 15_000,
|
|
} );
|
|
if ( ! response?.ok() ) {
|
|
throw new Error(
|
|
`Capture target ${ target.path } returned HTTP ${ response?.status() ?? 'unknown' }.`,
|
|
);
|
|
}
|
|
await page.waitForFunction(
|
|
( expectedTheme ) => document.documentElement.dataset.theme === expectedTheme,
|
|
theme,
|
|
{ timeout: 5_000 },
|
|
);
|
|
await page.locator( 'main' ).waitFor( { state: 'visible', timeout: 5_000 } );
|
|
await replaceLongCopy( page, target );
|
|
await waitForStablePage( page );
|
|
|
|
const outputName = `grunge-stage-${ target.name }-${ viewport.width }-${ theme }.png`;
|
|
const outputPath = join( OUTPUT_DIRECTORY, outputName );
|
|
const buffer = await page.screenshot( {
|
|
path: outputPath,
|
|
fullPage: true,
|
|
animations: 'disabled',
|
|
caret: 'hide',
|
|
} );
|
|
const dimensions = getPngDimensions( buffer );
|
|
if ( dimensions.width !== viewport.width ) {
|
|
throw new Error(
|
|
`${ outputName } width ${ dimensions.width } did not match ${ viewport.width }.`,
|
|
);
|
|
}
|
|
console.log( `${ outputName } ${ dimensions.width }x${ dimensions.height }` );
|
|
} finally {
|
|
try {
|
|
await context?.close();
|
|
} finally {
|
|
await browser.close();
|
|
}
|
|
}
|
|
}
|
|
|
|
const baseURL = getBaseURL();
|
|
await mkdir( OUTPUT_DIRECTORY, { recursive: true } );
|
|
|
|
for ( const target of TARGETS ) {
|
|
for ( const viewport of VIEWPORTS ) {
|
|
for ( const theme of THEMES ) {
|
|
await capture( baseURL, target, viewport, theme );
|
|
}
|
|
}
|
|
}
|