test: capture CHRNX grunge stage review
This commit is contained in:
3 files changed
+216
-76
No files matched your search
@@ -1,86 +1,194 @@
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium } from '@playwright/test';
|
||||
|
||||
const baseURL = process.env.CHRNX_REVIEW_URL || 'http://localhost:8888';
|
||||
const host = new URL(baseURL).hostname;
|
||||
if (!['localhost', '127.0.0.1'].includes(host)) {
|
||||
throw new Error('Visual review capture is restricted to local WordPress.');
|
||||
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;
|
||||
}
|
||||
|
||||
const output = new URL('../tmp/imagegen/', import.meta.url);
|
||||
await mkdir(output, { recursive: true });
|
||||
function getPngDimensions( buffer ) {
|
||||
if (
|
||||
buffer.length < 24 ||
|
||||
buffer.subarray( 0, 8 ).toString( 'hex' ) !== '89504e470d0a1a0a'
|
||||
) {
|
||||
throw new Error( 'Screenshot did not produce a valid PNG.' );
|
||||
}
|
||||
|
||||
async function capture(target, variant) {
|
||||
const { path, selector } = target;
|
||||
const { theme, viewport } = variant;
|
||||
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 {
|
||||
const context = await browser.newContext({
|
||||
context = await browser.newContext( {
|
||||
viewport,
|
||||
colorScheme: theme,
|
||||
reducedMotion: 'reduce',
|
||||
});
|
||||
} );
|
||||
await context.addInitScript(
|
||||
(preference) => localStorage.setItem('chrnx-theme', preference),
|
||||
theme,
|
||||
( [ key, preference ] ) => {
|
||||
localStorage.clear();
|
||||
localStorage.setItem( key, preference );
|
||||
},
|
||||
[ STORAGE_KEY, theme ],
|
||||
);
|
||||
const page = await context.newPage();
|
||||
const response = await page.goto(new URL(path, baseURL).href, { waitUntil: 'networkidle' });
|
||||
if (!response?.ok()) {
|
||||
throw new Error(`Capture target ${path} returned HTTP ${response?.status() ?? 'unknown'}.`);
|
||||
}
|
||||
await page.addStyleTag({
|
||||
content: '*,*::before,*::after{animation:none!important;transition:none!important}',
|
||||
});
|
||||
await page.evaluate(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)));
|
||||
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' );
|
||||
}
|
||||
await Promise.race([
|
||||
Promise.all(
|
||||
[...document.images].map((image) =>
|
||||
image.complete ? Promise.resolve() : image.decode().catch(() => {}),
|
||||
),
|
||||
),
|
||||
new Promise((resolve) => setTimeout(resolve, 3000)),
|
||||
]);
|
||||
window.scrollTo(0, 0);
|
||||
});
|
||||
const outputName = `editorial-polish-${target.name}-${variant.name}.png`;
|
||||
const outputPath = new URL(outputName, output).pathname;
|
||||
if (selector) {
|
||||
await page.locator(selector).screenshot({ path: outputPath });
|
||||
} else {
|
||||
await page.screenshot({ path: outputPath, fullPage: true });
|
||||
} );
|
||||
|
||||
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' }.`,
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`${outputName} ${await page.evaluate(
|
||||
() => `${document.documentElement.scrollWidth}x${document.documentElement.scrollHeight}`,
|
||||
)}`,
|
||||
await page.waitForFunction(
|
||||
( expectedTheme ) => document.documentElement.dataset.theme === expectedTheme,
|
||||
theme,
|
||||
{ timeout: 5_000 },
|
||||
);
|
||||
await context.close();
|
||||
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 {
|
||||
await browser.close();
|
||||
try {
|
||||
await context?.close();
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const reviewTargets = [
|
||||
{ name: 'home', path: '/' },
|
||||
{ name: 'music', path: '/music/' },
|
||||
{ name: 'post', path: '/una-cuerda-rota-tambien-puede-decidir-el-arreglo/' },
|
||||
{ name: 'footer', path: '/', selector: 'footer.wp-block-template-part' },
|
||||
];
|
||||
const reviewVariants = [
|
||||
{ name: 'desktop-dark', theme: 'dark', viewport: { width: 1440, height: 900 } },
|
||||
{ name: 'desktop-light', theme: 'light', viewport: { width: 1440, height: 900 } },
|
||||
{ name: 'mobile-dark', theme: 'dark', viewport: { width: 375, height: 812 } },
|
||||
{ name: 'mobile-light', theme: 'light', viewport: { width: 375, height: 812 } },
|
||||
];
|
||||
const baseURL = getBaseURL();
|
||||
await mkdir( OUTPUT_DIRECTORY, { recursive: true } );
|
||||
|
||||
for (const target of reviewTargets) {
|
||||
for (const variant of reviewVariants) {
|
||||
await capture(target, variant);
|
||||
for ( const target of TARGETS ) {
|
||||
for ( const viewport of VIEWPORTS ) {
|
||||
for ( const theme of THEMES ) {
|
||||
await capture( baseURL, target, viewport, theme );
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user