diff --git a/README.md b/README.md index 6e805f7..f9bc965 100644 --- a/README.md +++ b/README.md @@ -93,11 +93,18 @@ WebP sources, with the original source as a fallback. Capture the approved local review routes with Chromium: ```sh -node scripts/capture-visual-review.mjs +CHRNX_REVIEW_URL=http://localhost:8908 node scripts/capture-visual-review.mjs ``` The capture script rejects public hosts and writes its screenshots to -`tmp/imagegen/`, which Git ignores. +`tmp/imagegen/`, which Git ignores. It captures the rendered Music and Podcasts +pages at 375, 768, 1440, and 2560 px in light and dark themes. The long-copy +Podcast state changes only the rendered latest-card title and excerpt; it does +not write to the database. Source masters remain authoritative, and responsive +media must be rebuilt with `scripts/build-responsive-images.sh` after any +approved source change. Treat these screenshots as disposable review evidence: +keep them uncommitted, obtain visual approval before committing this stage, and +do not begin the next visual task until that approval is recorded. PHPUnit always runs through wp-env's isolated `tests-cli` database. The browser suite uses the separate development `cli` database; its serial scenario project diff --git a/scripts/capture-visual-review.mjs b/scripts/capture-visual-review.mjs index 09117d3..57939ed 100644 --- a/scripts/capture-visual-review.mjs +++ b/scripts/capture-visual-review.mjs @@ -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 ); + } } } diff --git a/tests/smoke/visual-integration.test.mjs b/tests/smoke/visual-integration.test.mjs index f0c0e4e..405e73e 100644 --- a/tests/smoke/visual-integration.test.mjs +++ b/tests/smoke/visual-integration.test.mjs @@ -92,27 +92,26 @@ test( 'the visual layer is separately enqueued and covers responsive accessible assert.match( components, /html\[data-theme="light"\]/ ); } ); -test( 'editorial review capture stays bounded to approved pages, variants, and filenames', () => { +test( 'grunge stage capture stays bounded to approved routes, widths, themes, and filenames', () => { const capture = read( 'scripts/capture-visual-review.mjs' ); - for ( const target of [ 'home', 'music', 'post', 'footer' ] ) { + for ( const target of [ 'music', 'podcasts', 'podcasts-long-copy' ] ) { assert.match( capture, new RegExp( `name: '${ target }'` ) ); } - assert.match( capture, /path: '\/'/ ); assert.match( capture, /path: '\/music\/'/ ); - assert.match( capture, /path: '\/una-cuerda-rota-tambien-puede-decidir-el-arreglo\/'/ ); - assert.match( capture, /selector: 'footer\.wp-block-template-part'/ ); - for ( const variant of [ 'desktop-dark', 'desktop-light', 'mobile-dark', 'mobile-light' ] ) { - assert.match( capture, new RegExp( `name: '${ variant }'` ) ); + assert.equal( capture.match( /path: '\/podcasts\/'/g )?.length, 2 ); + for ( const width of [ 375, 768, 1440, 2560 ] ) { + assert.match( capture, new RegExp( `width: ${ width }` ) ); } + assert.match( capture, /const THEMES = \[ 'light', 'dark' \]/ ); assert.match( capture, - /`editorial-polish-\$\{\s*target\.name\s*\}-\$\{\s*variant\.name\s*\}\.png`/, + /`grunge-stage-\$\{\s*target\.name\s*\}-\$\{\s*viewport\.width\s*\}-\$\{\s*theme\s*\}\.png`/, ); - assert.doesNotMatch( capture, /name: 'topic-|name: 'podcasts'|name: 'about'/ ); + assert.doesNotMatch( capture, /name: 'home'|name: 'post'|name: 'footer'|editorial-polish/ ); } ); -test( 'editorial review capture isolates browser compositing between theme variants', () => { +test( 'grunge stage capture isolates every image and waits for stable rendered assets', () => { const capture = read( 'scripts/capture-visual-review.mjs' ); assert.ok( @@ -122,9 +121,35 @@ test( 'editorial review capture isolates browser compositing between theme varia ); assert.match( capture, - /const browser = await chromium\.launch\(\);[\s\S]*?try \{[\s\S]*?finally \{\s*await browser\.close\(\);\s*\}/, - 'Every isolated browser must close even when navigation or capture fails', + /const browser = await chromium\.launch\(\);[\s\S]*?try \{[\s\S]*?finally \{\s*try \{\s*await context\?\.close\(\);\s*\} finally \{\s*await browser\.close\(\);\s*\}\s*\}/, + 'Every isolated browser must close even when navigation, capture, or context cleanup fails', ); + assert.match( capture, /await document\.fonts\.ready/ ); + assert.match( capture, /image\.complete/ ); + assert.match( capture, /image\.naturalWidth/ ); + assert.match( capture, /image\.decode\(\)/ ); + assert.match( capture, /reducedMotion: 'reduce'/ ); + assert.match( capture, /page\.setDefaultTimeout\( 5_000 \)/ ); + assert.match( capture, /page\.setDefaultNavigationTimeout\( 15_000 \)/ ); + assert.match( capture, /LOCAL_HOSTS/ ); + assert.match( capture, /route\.abort\( 'blockedbyclient' \)/ ); + assert.equal( capture.match( /const browser = await chromium\.launch\(\)/g )?.length, 1 ); + assert.match( + capture, + /for \( const target[\s\S]*for \( const viewport[\s\S]*for \( const theme[\s\S]*await capture\( baseURL, target, viewport, theme \)/, + ); +} ); + +test( 'long-copy review mutates only the rendered latest podcast title and excerpt', () => { + const capture = read( 'scripts/capture-visual-review.mjs' ); + const titleSelector = '.chrnx-latest-podcast .chrnx-podcast-card__title'; + const excerptSelector = '.chrnx-latest-podcast .chrnx-podcast-card__excerpt'; + + assert.ok( capture.includes( `titleSelector: '${ titleSelector }'` ) ); + assert.ok( capture.includes( `excerptSelector: '${ excerptSelector }'` ) ); + assert.match( capture, /target\.longCopy[\s\S]*locator\( target\.longCopy\.titleSelector \)[\s\S]*locator\( target\.longCopy\.excerptSelector \)/ ); + assert.match( capture, /element\.textContent = value/ ); + assert.doesNotMatch( capture, /wp-json|fetch\(|XMLHttpRequest|wp eval|seed-test-content/ ); } ); test( 'the page canvas is atmospheric rather than a repeating grid', () => {