Merge branch 'feature/character-led-sections' into feature/music-podcast-grunge-stages

This commit is contained in:
chrnx committed 2026-08-13 00:21:36 -05:00
commit 7480f9c21e
20 files changed
+1313 -76

No files matched your search

+22 -3
View File
@@ -16,6 +16,7 @@ ALTER_EGO_ASSETS = (
"alter-ego-life.png",
"alter-ego-gaming.png",
)
ALTER_EGO_SOURCE_ASSETS = (*ALTER_EGO_ASSETS, "alter-ego-gaming-half-body.png")
CONTACT_SHEET_SCRIPT = PROJECT_ROOT / "scripts" / "build-alter-ego-contact-sheet.py"
@@ -33,9 +34,9 @@ def test_opaque_coverage_counts_near_opaque_alpha() -> None:
def test_alter_ego_asset_inventory_and_image_contract() -> None:
expected = set(ALTER_EGO_ASSETS)
expected = set(ALTER_EGO_SOURCE_ASSETS)
actual = {path.name for path in ASSET_DIRECTORY.glob("alter-ego-*.png")}
missing = [name for name in ALTER_EGO_ASSETS if name not in actual]
missing = [name for name in ALTER_EGO_SOURCE_ASSETS if name not in actual]
unexpected = sorted(actual - expected)
inventory_violations = [
*(f"missing assets/images/{name}" for name in missing),
@@ -46,7 +47,7 @@ def test_alter_ego_asset_inventory_and_image_contract() -> None:
)
violations: list[str] = []
for name in ALTER_EGO_ASSETS:
for name in ALTER_EGO_SOURCE_ASSETS:
path = ASSET_DIRECTORY / name
with Image.open(path) as image:
if image.format != "PNG":
@@ -92,6 +93,24 @@ def test_alter_ego_asset_inventory_and_image_contract() -> None:
)
def test_gaming_half_body_preserves_original_and_has_prominent_visible_alpha() -> None:
original = ASSET_DIRECTORY / "alter-ego-gaming.png"
half_body = ASSET_DIRECTORY / "alter-ego-gaming-half-body.png"
assert original.read_bytes() != half_body.read_bytes()
with Image.open(original) as original_image, Image.open(half_body) as half_body_image:
assert original_image.size == half_body_image.size == (1024, 1536)
original_box = original_image.getchannel("A").point(
lambda value: 255 if value >= 16 else 0
).getbbox()
half_body_box = half_body_image.getchannel("A").point(
lambda value: 255 if value >= 16 else 0
).getbbox()
assert original_box == (170, 54, 882, 1475)
assert half_body_box == (15, 79, 948, 1536)
assert (half_body_box[2] - half_body_box[0]) / 1024 >= 0.90
def _install_contact_sheet_script(project_root: Path) -> Path:
assert CONTACT_SHEET_SCRIPT.is_file(), (
f"Missing contact-sheet script: {CONTACT_SHEET_SCRIPT}"
+529
View File
@@ -8,6 +8,143 @@ const viewports = [
{ width: 2560, height: 1440 },
];
const characterSurfaces = [
{ name: 'home-projects', path: '/', selector: '.chrnx-home-projects .chrnx-character-stage' },
{ name: 'home-music', path: '/', selector: '.chrnx-home-music .chrnx-character-stage' },
{ name: 'projects', path: '/projects/', selector: '.chrnx-home-projects .chrnx-character-stage' },
{ name: 'music', path: '/music/', selector: '.chrnx-music-landing .chrnx-character-stage' },
{
name: 'podcasts',
path: '/podcasts/',
selector: '.chrnx-podcast-landing .chrnx-character-stage',
},
{ name: 'about', path: '/about/', selector: '.chrnx-about .chrnx-character-stage' },
{
name: 'show-silicon-ranch',
path: '/show/silicon-ranch/',
selector: '.chrnx-topic-hero .chrnx-character-stage',
},
...[ 'research', 'code', 'literature', 'music', 'podcasts', 'life', 'gaming' ].map(
( topic ) => ( {
name: `topic-${ topic }`,
path: `/topic/${ topic }/`,
selector: '.chrnx-topic-hero .chrnx-character-stage',
} ),
),
];
const characterVisibleAlphaBounds = {
'alter-ego-code': [ 1122, 1402, 87, 204, 1022, 1172 ],
'alter-ego-gaming-half-body': [ 1024, 1536, 15, 79, 948, 1536 ],
'alter-ego-life': [ 1122, 1402, 25, 81, 1078, 1402 ],
'alter-ego-literature': [ 1122, 1402, 51, 48, 1072, 1359 ],
'alter-ego-podcasts': [ 1122, 1402, 62, 110, 1101, 1338 ],
'alter-ego-research': [ 1122, 1402, 106, 52, 1074, 1402 ],
'the-no-names-musician-cutout': [ 1122, 1402, 0, 46, 1102, 1402 ],
};
async function positionStageBelowStickyHeader( page, stage ) {
await stage.scrollIntoViewIfNeeded();
await page.evaluate(
( element ) => {
const header = document.querySelector( 'header.wp-block-template-part' );
const overlap = header.getBoundingClientRect().bottom - element.getBoundingClientRect().top;
if ( overlap > 0 ) {
window.scrollBy( 0, -( overlap + 16 ) );
}
},
await stage.elementHandle(),
);
await page.evaluate(
() =>
new Promise( ( resolve ) =>
window.requestAnimationFrame( () => window.requestAnimationFrame( resolve ) ),
),
);
}
async function setExplicitTheme( page, theme ) {
await page.addInitScript( ( value ) => {
window.localStorage.setItem( 'chrnx-theme', value );
}, theme );
}
async function readCharacterGeometry( stage ) {
return stage.evaluate( ( element ) => {
const content = element.querySelector( ':scope > .chrnx-character-stage__content' );
const art = element.querySelector( ':scope > .chrnx-character-stage__art' );
const atmosphere = element.querySelector( ':scope > .chrnx-character-stage__atmosphere' );
const picture = art.querySelector( ':scope > picture' );
const image = picture?.querySelector( 'img' );
const secondary = atmosphere.querySelector( 'picture' );
const collage = element
.querySelector( '.chrnx-character-stage__collage' )
?.closest( 'picture' );
const facets = element.parentElement.querySelector( ':scope > .chrnx-character-facets' );
const stageRect = element.getBoundingClientRect();
const contentRect = content.getBoundingClientRect();
const artRect = art.getBoundingClientRect();
const pictureRect = picture?.getBoundingClientRect();
const imageStyle = image ? window.getComputedStyle( image ) : null;
const pictureStyle = picture ? window.getComputedStyle( picture ) : null;
const atmosphereStyle = window.getComputedStyle( atmosphere );
const secondaryStyle = secondary ? window.getComputedStyle( secondary ) : null;
const collageStyle = collage ? window.getComputedStyle( collage ) : null;
const facetsStyle = facets ? window.getComputedStyle( facets ) : null;
const intersects = ( first, second ) =>
first.left < second.right - 1 &&
first.right > second.left + 1 &&
first.top < second.bottom - 1 &&
first.bottom > second.top + 1;
const following = [];
let branch = element;
while ( branch && branch.tagName !== 'MAIN' ) {
let sibling = branch.nextElementSibling;
while ( sibling ) {
following.push( sibling );
sibling = sibling.nextElementSibling;
}
branch = branch.parentElement;
}
return {
stageWidth: stageRect.width,
artWidth: artRect.width,
artBottomGap: Math.abs( stageRect.bottom - artRect.bottom ),
contentTop: contentRect.top,
contentBottom: contentRect.bottom,
artTop: artRect.top,
contentArtIntersect: intersects( contentRect, artRect ),
followingIntersections: following.filter( ( candidate ) =>
intersects( stageRect, candidate.getBoundingClientRect() ),
).length,
followingCount: following.length,
stageOverflow: element.scrollWidth - element.clientWidth,
pictureVisible: Boolean(
pictureRect && pictureRect.width > 0 && pictureRect.height > 0 && image?.complete,
),
pictureContained: Boolean(
pictureRect &&
pictureRect.left >= artRect.left - 1 &&
pictureRect.right <= artRect.right + 1 &&
pictureRect.top >= artRect.top - 1 &&
pictureRect.bottom <= artRect.bottom + 1,
),
pictureZ: Number.parseInt( pictureStyle?.zIndex || '0', 10 ) || 0,
atmosphereZ: Number.parseInt( atmosphereStyle.zIndex, 10 ) || 0,
secondaryZ: Number.parseInt( secondaryStyle?.zIndex || '0', 10 ) || 0,
collageZ: Number.parseInt( collageStyle?.zIndex || '0', 10 ) || 0,
collageLoading: collage?.querySelector( 'img' )?.loading,
facetsOpacity: facetsStyle ? Number.parseFloat( facetsStyle.opacity ) : null,
facetsZ: Number.parseInt( facetsStyle?.zIndex || '0', 10 ) || 0,
effect: imageStyle
? `${ imageStyle.filter }|${ imageStyle.boxShadow }|${ imageStyle.maskImage }|${ imageStyle.webkitMaskImage }`
: '',
loading: image?.loading,
};
} );
}
async function expectNoHorizontalOverflow( page ) {
const overflow = await page.evaluate( () => ( {
document: document.documentElement.scrollWidth - window.innerWidth,
@@ -34,6 +171,20 @@ function contrastRatio( foreground, background ) {
return ( lighter + 0.05 ) / ( darker + 0.05 );
}
function conservativeOverlayContrast( foreground, overlay ) {
const channels = overlay.match( /[\d.]+/g ).map( Number );
const alpha = channels[ 3 ] ?? 1;
const composite = ( underlay ) =>
`rgb(${ channels
.slice( 0, 3 )
.map( ( channel ) => Math.round( channel * alpha + underlay * ( 1 - alpha ) ) )
.join( ', ' ) })`;
return Math.min(
contrastRatio( foreground, composite( 0 ) ),
contrastRatio( foreground, composite( 255 ) ),
);
}
test( 'home remains coherent at all approved review viewports', async ( { page } ) => {
for ( const viewport of viewports ) {
await page.setViewportSize( viewport );
@@ -672,3 +823,381 @@ test( 'key public surfaces pass automated WCAG 2.2 AA checks', async ( { page },
}
}
} );
test( 'character stage geometry, layering, effects, loading, and inspection captures', async ( {
page,
}, testInfo ) => {
test.setTimeout( 180_000 );
test.skip( testInfo.project.name !== 'chromium', 'Character geometry is reviewed in Chromium.' );
for ( const theme of [ 'dark', 'light' ] ) {
await setExplicitTheme( page, theme );
for ( const viewport of viewports ) {
await page.setViewportSize( viewport );
for ( const surface of characterSurfaces ) {
await page.goto( surface.path );
await expect( page.locator( 'html' ) ).toHaveAttribute( 'data-theme', theme );
const stage = page.locator( surface.selector ).first();
await expect( stage, `${ surface.name } stage` ).toBeVisible();
const initial = await stage.evaluate( ( element ) => ( {
top: element.getBoundingClientRect().top,
loading: element.querySelector( ':scope > .chrnx-character-stage__art picture img' )
?.loading,
priority: element.querySelector( ':scope > .chrnx-character-stage__art picture img' )
?.fetchPriority,
} ) );
await positionStageBelowStickyHeader( page, stage );
await stage
.locator( ':scope > .chrnx-character-stage__art picture img' )
.evaluate( ( image ) => image.decode() );
const geometry = await readCharacterGeometry( stage );
const mobile = viewport.width <= 768;
const ratio = geometry.artWidth / geometry.stageWidth;
expect(
ratio,
`${ surface.name } art ratio at ${ viewport.width }px ${ theme }`,
).toBeGreaterThanOrEqual( mobile ? 0.62 : 0.35 );
if ( ! mobile ) {
expect( ratio ).toBeLessThanOrEqual( 0.48 );
}
expect( geometry.artBottomGap ).toBeLessThanOrEqual( 2 );
if ( mobile ) {
expect( geometry.contentTop ).toBeLessThan( geometry.artTop );
expect( geometry.contentBottom ).toBeLessThanOrEqual( geometry.artTop + 1 );
}
expect( geometry.contentArtIntersect ).toBeFalsy();
expect( geometry.followingIntersections ).toBe( 0 );
if (
[ 'home-projects', 'home-music', 'projects', 'music', 'podcasts', 'about' ].includes(
surface.name,
)
) {
expect( geometry.followingCount, `${ surface.name } following surfaces` ).toBeGreaterThan(
0,
);
}
expect( geometry.stageOverflow ).toBeLessThanOrEqual( 1 );
expect( geometry.pictureVisible ).toBeTruthy();
expect( geometry.pictureContained ).toBeTruthy();
expect( geometry.pictureZ ).toBeGreaterThan( geometry.atmosphereZ );
expect( geometry.pictureZ ).toBeGreaterThan( geometry.secondaryZ );
expect( geometry.pictureZ ).toBeGreaterThan( geometry.collageZ );
expect( geometry.effect ).not.toBe( 'none|none|none|none' );
const painted = await stage.evaluate( ( element, boundsByAsset ) => {
const image = element.querySelector( ':scope > .chrnx-character-stage__art picture img' );
const sourceName = new URL( image.src ).pathname
.split( '/' )
.pop()
.replace( /\.png$/, '' );
const [ naturalWidth, naturalHeight, x0, y0, x1, y1 ] = boundsByAsset[ sourceName ];
const imageRect = image.getBoundingClientRect();
const stageRect = element.getBoundingClientRect();
const scale = Math.min(
imageRect.width / naturalWidth,
imageRect.height / naturalHeight,
);
const objectWidth = naturalWidth * scale;
const objectHeight = naturalHeight * scale;
const objectLeft = imageRect.left + ( imageRect.width - objectWidth ) / 2;
const objectTop = imageRect.bottom - objectHeight;
const visible = {
left: objectLeft + x0 * scale,
top: objectTop + y0 * scale,
right: objectLeft + x1 * scale,
bottom: objectTop + y1 * scale,
};
return {
sourceName,
widthRatio: ( visible.right - visible.left ) / stageRect.width,
heightRatio: ( visible.bottom - visible.top ) / stageRect.height,
contained:
visible.left >= stageRect.left - 1 &&
visible.right <= stageRect.right + 1 &&
visible.top >= stageRect.top - 1 &&
visible.bottom <= stageRect.bottom + 1,
};
}, characterVisibleAlphaBounds );
expect( painted.widthRatio, `${ surface.name } painted width` ).toBeGreaterThanOrEqual(
mobile ? 0.45 : 0.36,
);
expect( painted.heightRatio ).toBeGreaterThanOrEqual( 0.28 );
expect( painted.contained ).toBeTruthy();
if ( surface.name === 'topic-gaming' ) {
expect( painted.sourceName ).toBe( 'alter-ego-gaming-half-body' );
}
if ( surface.name === 'home-music' || surface.name === 'music' ) {
expect( geometry.collageLoading ).toBe( 'lazy' );
}
if ( surface.name === 'music' ) {
const collage = stage.locator(
'.chrnx-character-stage__content > .chrnx-responsive-portrait:has(.chrnx-character-stage__collage)',
);
const collageContract = await collage.evaluate(
( picture, stageElement ) => {
const pictureRect = picture.getBoundingClientRect();
const stageRect = stageElement.getBoundingClientRect();
return {
left: Math.abs( pictureRect.left - stageRect.left ),
right: Math.abs( pictureRect.right - stageRect.right ),
top: Math.abs( pictureRect.top - stageRect.top ),
bottom: Math.abs( pictureRect.bottom - stageRect.bottom ),
hiddenAncestor: Boolean( picture.closest( '[aria-hidden="true"]' ) ),
alt: picture.querySelector( 'img' )?.alt,
};
},
await stage.elementHandle(),
);
expect( collageContract.left ).toBeLessThanOrEqual( 2 );
expect( collageContract.right ).toBeLessThanOrEqual( 2 );
expect( collageContract.top ).toBeLessThanOrEqual( 2 );
expect( collageContract.bottom ).toBeLessThanOrEqual( 2 );
expect( collageContract.hiddenAncestor ).toBeFalsy();
expect( collageContract.alt ).toBe( 'The No Names collage' );
}
if ( surface.name === 'about' ) {
expect( geometry.facetsOpacity ).toBeLessThan( 1 );
expect( geometry.facetsZ ).toBeLessThan( geometry.pictureZ );
}
await expectNoHorizontalOverflow( page );
if ( initial.top >= viewport.height ) {
expect( initial.loading ).not.toBe( 'eager' );
expect( initial.priority ).not.toBe( 'high' );
}
const captureContract = await stage.evaluate( ( element ) => {
const header = document.querySelector( 'header.wp-block-template-part' );
const heading = element.querySelector( 'h1, h2, h3, h4, h5, h6' );
const headerRect = header.getBoundingClientRect();
const stageRect = element.getBoundingClientRect();
const headingRect = heading.getBoundingClientRect();
return {
headerIntersects:
headerRect.bottom > stageRect.top && headerRect.top < stageRect.bottom,
headingContained:
headingRect.top >= stageRect.top && headingRect.bottom <= stageRect.bottom,
};
} );
expect( captureContract.headerIntersects ).toBeFalsy();
expect( captureContract.headingContained ).toBeTruthy();
const header = page.locator( 'header.wp-block-template-part' );
await header.evaluate( ( element ) => {
element.dataset.characterCaptureVisibility = element.style.visibility;
element.style.visibility = 'hidden';
} );
try {
await testInfo.attach(
`character-stage-${ surface.name }-${ viewport.width }-${ theme }.png`,
{ body: await stage.screenshot(), contentType: 'image/png' },
);
} finally {
await header.evaluate( ( element ) => {
element.style.visibility = element.dataset.characterCaptureVisibility;
delete element.dataset.characterCaptureVisibility;
} );
}
}
}
}
} );
test( 'character stage long copy grows safely with AA contrast in both themes', async ( {
page,
}, testInfo ) => {
test.setTimeout( 120_000 );
test.skip( testInfo.project.name !== 'chromium', 'Character geometry is reviewed in Chromium.' );
for ( const theme of [ 'dark', 'light' ] ) {
await setExplicitTheme( page, theme );
for ( const width of [ 375, 1440 ] ) {
await page.setViewportSize( { width, height: width === 375 ? 812 : 900 } );
for ( const surface of characterSurfaces ) {
await page.goto( surface.path );
const stage = page.locator( surface.selector ).first();
await stage.locator( ':scope > .chrnx-character-stage__content' ).evaluate( ( content ) => {
const walker = document.createTreeWalker( content, window.NodeFilter.SHOW_TEXT );
const nodes = [];
while ( walker.nextNode() ) {
if ( walker.currentNode.textContent.trim() ) {
nodes.push( walker.currentNode );
}
}
for ( const node of nodes ) {
node.textContent = `${ node.textContent.trim() } `.repeat( 4 ).trim();
}
} );
const result = await stage.evaluate( ( element ) => {
const content = element.querySelector( ':scope > .chrnx-character-stage__content' );
const art = element.querySelector( ':scope > .chrnx-character-stage__art' );
const stageRect = element.getBoundingClientRect();
const contentRect = content.getBoundingClientRect();
const artRect = art.getBoundingClientRect();
const following = [
...element.parentElement.querySelectorAll(
'.chrnx-release-card, .chrnx-podcast-card, .chrnx-character-facets',
),
].filter( ( candidate ) => {
const rect = candidate.getBoundingClientRect();
return ! element.contains( candidate ) && rect.height > 0 && rect.top >= stageRect.top;
} );
const foregrounds = [ ...content.querySelectorAll( 'h1, h2, h3, h4, h5, h6, p, li, a' ) ]
.filter( ( candidate ) => candidate.getClientRects().length > 0 )
.map( ( candidate ) => window.getComputedStyle( candidate ).color );
const copySurfaceStyle = window.getComputedStyle( content, '::before' );
return {
stageBottom: stageRect.bottom,
contentBottom: contentRect.bottom,
artTop: artRect.top,
artBottom: artRect.bottom,
nextTop: following.length
? Math.min(
...following.map( ( candidate ) => candidate.getBoundingClientRect().top ),
)
: Number.POSITIVE_INFINITY,
foregrounds,
background: copySurfaceStyle.backgroundColor,
backgroundImage: copySurfaceStyle.backgroundImage,
copySurfaceContent: copySurfaceStyle.content,
};
} );
expect( result.stageBottom ).toBeGreaterThanOrEqual( result.contentBottom - 1 );
expect( result.stageBottom ).toBeGreaterThanOrEqual( result.artBottom - 1 );
expect( result.nextTop ).toBeGreaterThanOrEqual( result.stageBottom - 1 );
if ( width === 375 ) {
expect( result.artTop ).toBeGreaterThanOrEqual( result.contentBottom - 1 );
}
expect( result.foregrounds.length ).toBeGreaterThan( 0 );
expect( result.copySurfaceContent ).not.toBe( 'none' );
const backgroundChannels = result.background.match( /[\d.]+/g ).map( Number );
expect( backgroundChannels[ 3 ] ?? 1 ).toBeGreaterThanOrEqual( 0.85 );
expect( result.backgroundImage ).toBe( 'none' );
for ( const foreground of result.foregrounds ) {
expect(
conservativeOverlayContrast( foreground, result.background ),
`${ surface.name } ${ width }px ${ theme } contrast`,
).toBeGreaterThanOrEqual( 4.5 );
}
await expectNoHorizontalOverflow( page );
}
}
}
} );
test( 'character stage is static under reduced motion and visible without JavaScript', async ( {
browser,
}, testInfo ) => {
test.setTimeout( 60_000 );
test.skip( testInfo.project.name !== 'chromium', 'Character geometry is reviewed in Chromium.' );
const cases = characterSurfaces.filter( ( surface ) =>
[ 'home-music', 'about', 'topic-code' ].includes( surface.name ),
);
for ( const surface of cases ) {
const regularContext = await browser.newContext( {
baseURL: testInfo.project.use.baseURL,
viewport: { width: 375, height: 812 },
} );
const reducedContext = await browser.newContext( {
baseURL: testInfo.project.use.baseURL,
viewport: { width: 375, height: 812 },
reducedMotion: 'reduce',
} );
const noJavaScriptContext = await browser.newContext( {
baseURL: testInfo.project.use.baseURL,
viewport: { width: 375, height: 812 },
javaScriptEnabled: false,
} );
const [ regular, reduced, noJavaScript ] = await Promise.all( [
regularContext.newPage(),
reducedContext.newPage(),
noJavaScriptContext.newPage(),
] );
try {
for ( const page of [ regular, reduced, noJavaScript ] ) {
await page.goto( surface.path );
}
const regularStage = regular.locator( surface.selector ).first();
const reducedStage = reduced.locator( surface.selector ).first();
const noJsStage = noJavaScript.locator( surface.selector ).first();
const [ regularBox, reducedBox ] = await Promise.all( [
regularStage.boundingBox(),
reducedStage.boundingBox(),
] );
expect( Math.abs( regularBox.width - reducedBox.width ) ).toBeLessThanOrEqual( 1 );
expect( Math.abs( regularBox.height - reducedBox.height ) ).toBeLessThanOrEqual( 1 );
await expect( noJsStage ).toBeVisible();
const noJsGeometry = await readCharacterGeometry( noJsStage );
expect( noJsGeometry.pictureVisible ).toBeTruthy();
expect( noJsGeometry.stageOverflow ).toBeLessThanOrEqual( 1 );
await expectNoHorizontalOverflow( noJavaScript );
} finally {
await Promise.all( [
regularContext.close(),
reducedContext.close(),
noJavaScriptContext.close(),
] );
}
}
} );
test( 'character stage below-fold derivatives wait for approach and then load responsively', async ( {
page,
}, testInfo ) => {
test.setTimeout( 60_000 );
test.skip( testInfo.project.name !== 'chromium', 'Character loading is reviewed in Chromium.' );
await page.setViewportSize( { width: 375, height: 812 } );
const requested = [];
page.on( 'request', ( request ) => {
if ( /\/assets\/images\/(?:generated\/)?/.test( request.url() ) ) {
requested.push( request.url() );
}
} );
await page.goto( '/' );
await page.waitForTimeout( 300 );
const stages = page.locator(
'.chrnx-home-projects .chrnx-character-stage, .chrnx-home-music .chrnx-character-stage',
);
await expect( stages ).toHaveCount( 2 );
const expected = [];
for ( let stageIndex = 0; stageIndex < 2; stageIndex += 1 ) {
const stage = stages.nth( stageIndex );
const stageTop = await stage.evaluate( ( element ) => element.getBoundingClientRect().top );
expect( stageTop ).toBeGreaterThanOrEqual( 812 );
const portraits = await stage.locator( 'picture' ).evaluateAll( ( pictures ) =>
pictures
.filter(
( picture ) =>
window.getComputedStyle( picture.querySelector( 'img' ) ).display !== 'none',
)
.map( ( picture ) => {
const source = picture.querySelector( 'source[type="image/avif"]' );
return {
candidates: source.srcset
.split( ',' )
.map( ( candidate ) => new URL( candidate.trim().split( /\s+/ )[ 0 ] ).pathname ),
};
} ),
);
expected.push( ...portraits );
}
for ( const portrait of expected ) {
expect(
requested.some( ( url ) => portrait.candidates.includes( new URL( url ).pathname ) ),
).toBeFalsy();
}
for ( let stageIndex = 0; stageIndex < 2; stageIndex += 1 ) {
await stages.nth( stageIndex ).scrollIntoViewIfNeeded();
}
for ( const portrait of expected ) {
await expect
.poll(
() => requested.find( ( url ) => portrait.candidates.includes( new URL( url ).pathname ) ),
{ timeout: 10_000 },
)
.toMatch( /-384\.avif$/ );
}
} );
+57 -1
View File
@@ -367,7 +367,7 @@ class BlockRenderingTest extends WP_UnitTestCase {
'music' => 'the-no-names-musician-cutout.png',
'podcasts' => 'alter-ego-podcasts.png',
'life' => 'alter-ego-life.png',
'gaming' => 'alter-ego-gaming.png',
'gaming' => 'alter-ego-gaming-half-body.png',
);
foreach ( $expected as $slug => $filename ) {
$this->assertSame( 'assets/images/' . $filename, chrnx_get_topic_art_asset( $slug ) );
@@ -628,6 +628,9 @@ class BlockRenderingTest extends WP_UnitTestCase {
$this->assertStringContainsString( 'loading="eager"', $output );
$this->assertStringContainsString( 'fetchpriority="high"', $output );
$this->assertStringContainsString( 'decoding="async"', $output );
$this->assertStringContainsString( 'type="image/avif"', $output );
$this->assertStringContainsString( 'type="image/webp"', $output );
$this->assertStringContainsString( 'srcset="', $output );
$unsafe = render_block(
array(
@@ -651,6 +654,59 @@ class BlockRenderingTest extends WP_UnitTestCase {
);
$this->assertStringContainsString( 'width="1024"', $gaming );
$this->assertStringContainsString( 'height="1536"', $gaming );
$this->assertStringContainsString( 'alter-ego-gaming-half-body', $gaming );
}
/** Topic heroes share the three-layer stage and unknown topics retain a safe labeled fallback. */
public function test_topic_hero_uses_shared_stage_and_labels_unknown_fallbacks() {
$attributes = array(
'topic' => 'future-topic',
'headingLevel' => 2,
);
ob_start();
include get_theme_file_path( 'blocks/topic-hero/render.php' );
$output = (string) ob_get_clean();
$this->assertStringContainsString( 'chrnx-topic-hero', $output );
$this->assertStringContainsString( 'chrnx-character-stage', $output );
$this->assertStringContainsString( '>Future Topic</h2>', $output );
$this->assertMatchesRegularExpression( '/class="chrnx-topic-hero__fallback" aria-hidden="true"/', $output );
$this->assertStringNotContainsString( '<img', $output );
$dom = new DOMDocument();
$dom->loadHTML( '<?xml encoding="utf-8" ?>' . $output, LIBXML_NOERROR | LIBXML_NOWARNING );
$xpath = new DOMXPath( $dom );
$stage = $xpath->query( '//*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-stage ")]' )->item( 0 );
$children = array();
foreach ( $stage->childNodes as $child ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
if ( XML_ELEMENT_NODE === $child->nodeType ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
$children[] = $child;
}
}
$this->assertCount( 3, $children );
$this->assertStringContainsString( 'chrnx-character-stage__atmosphere', $children[0]->getAttribute( 'class' ) );
$this->assertSame( 'true', $children[0]->getAttribute( 'aria-hidden' ) );
$this->assertStringContainsString( 'chrnx-character-stage__content', $children[1]->getAttribute( 'class' ) );
$this->assertStringContainsString( 'chrnx-character-stage__art', $children[2]->getAttribute( 'class' ) );
}
/** Show archives use podcast art without replacing the visible show name. */
public function test_show_archive_uses_podcasts_art_and_keeps_silicon_ranch_title() {
$show = get_term_by( 'slug', 'silicon-ranch', 'chrnx_show' );
$this->assertInstanceOf( WP_Term::class, $show );
$this->go_to( get_term_link( $show ) );
$output = render_block(
array(
'blockName' => 'chrnx/topic-hero',
'attrs' => array(),
)
);
$this->assertStringContainsString( '>Silicon Ranch</h2>', $output );
$this->assertStringContainsString( 'alter-ego-podcasts.png', $output );
$this->assertStringNotContainsString( '>Podcasts</h2>', $output );
$this->assertSame( 1, substr_count( $output, 'class="chrnx-character-stage"' ) );
}
/** Subscribe CTA is exactly empty until a published Page is configured. */
+172 -2
View File
@@ -84,11 +84,11 @@ class PatternsTest extends WP_UnitTestCase {
$content = $this->render_pattern( get_theme_file_path( 'patterns/home-music.php' ) );
$this->assertStringContainsString( "chrnx_get_topic_portrait_markup( 'music-collage'", $source );
$this->assertStringContainsString( 'chrnx-home-music__collage-layer', $content );
$this->assertStringContainsString( 'chrnx-character-stage__atmosphere', $content );
$this->assertStringContainsString( 'the-no-names-collage-384.avif 384w', $content );
$this->assertStringContainsString( 'the-no-names-collage-768.webp 768w', $content );
$this->assertStringContainsString( 'sizes="(max-width: 599px) 100vw, 720px"', $content );
$this->assertMatchesRegularExpression( '/class="chrnx-home-music__collage"[^>]*loading="lazy"[^>]*alt=""/', $content );
$this->assertMatchesRegularExpression( '/class="chrnx-character-stage__collage"[^>]*loading="lazy"[^>]*alt=""/', $content );
$this->assertStringContainsString( 'the-no-names-musician-cutout.png', $content );
$this->assertLessThan(
strpos( $content, 'the-no-names-musician-cutout.png' ),
@@ -197,6 +197,176 @@ class PatternsTest extends WP_UnitTestCase {
}
}
/** Section openings expose one block-valid three-layer character stage. */
public function test_character_led_patterns_use_the_exact_shared_stage_api() {
$contracts = array(
'home-projects' => array(
'heading' => 'Selected work',
'order' => array( 'Selected work', 'Expressive Tea', 'Ailed', 'Published research' ),
'art' => 'alter-ego-code.png',
'art_alt' => '',
'atmosphere' => 'chrnx-character-stage__secondary-art',
),
'home-music' => array(
'heading' => 'The No Names',
'order' => array( 'The No Names', 'Grunge mexicano para cerebros que no se callan.', 'Un proyecto de banda activo hecho en Sinaloa: estudio crudo, cero live.' ),
'art' => 'the-no-names-musician-cutout.png',
'art_alt' => 'The No Names musician portrait',
'atmosphere' => 'chrnx-character-stage__collage',
),
'music-landing' => array(
'heading' => 'The No Names',
'order' => array( 'The No Names', 'Grunge mexicano para cerebros que no se callan.', 'The No Names es una banda activa', 'El proceso usa generative AI' ),
'art' => 'the-no-names-musician-cutout.png',
'art_alt' => 'The No Names musician portrait',
),
'podcast-landing' => array(
'heading' => 'Podcasts',
'order' => array( 'Podcasts' ),
'art' => 'alter-ego-podcasts.png',
'art_alt' => '',
),
'about' => array(
'heading' => 'About',
'order' => array( 'About', 'I work as Lead Developer @Expressive Tea', 'I am a published researcher.', 'I am an autistic Level 1 software developer and researcher.', 'Beyond the work', 'I am the father of three wonderful children' ),
'art' => 'alter-ego-life.png',
'art_alt' => '',
'facets' => array( 'alter-ego-literature.png', 'alter-ego-gaming-half-body.png' ),
),
);
foreach ( $contracts as $name => $contract ) {
$content = $this->render_pattern( get_theme_file_path( 'patterns/' . $name . '.php' ) );
$dom = $this->load_html_fragment( $content );
$xpath = new DOMXPath( $dom );
$stages = $xpath->query( '//*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-stage ")]' );
$this->assertCount( 1, $stages, $name );
$stage = $stages->item( 0 );
$children = array();
foreach ( $stage->childNodes as $child ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
if ( XML_ELEMENT_NODE === $child->nodeType ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
$children[] = $child;
}
}
$this->assertCount( 3, $children, $name );
$this->assert_element_has_class( $children[0], 'chrnx-character-stage__atmosphere', $name );
$this->assertSame( 'true', $children[0]->getAttribute( 'aria-hidden' ), $name );
$this->assert_element_has_class( $children[1], 'chrnx-character-stage__content', $name );
$this->assert_element_has_class( $children[2], 'chrnx-character-stage__art', $name );
$this->assertCount( 1, $xpath->query( './/picture', $children[2] ), $name );
$art_markup = $dom->saveHTML( $children[2] );
$this->assertStringContainsString( $contract['art'], $art_markup, $name );
$this->assertStringContainsString( 'type="image/avif"', $art_markup, $name );
$this->assertStringContainsString( 'type="image/webp"', $art_markup, $name );
$this->assertStringContainsString( 'srcset="', $art_markup, $name );
$this->assertStringContainsString( 'loading="lazy"', $art_markup, $name );
$this->assertStringContainsString( 'alt="' . $contract['art_alt'] . '"', $art_markup, $name );
if ( '' === $contract['art_alt'] ) {
$this->assertStringContainsString( '<picture class="chrnx-responsive-portrait" aria-hidden="true">', $art_markup, $name );
} else {
$this->assertStringNotContainsString( '<picture class="chrnx-responsive-portrait" aria-hidden=', $art_markup, $name );
}
$this->assertSame( 1, substr_count( $dom->saveHTML( $children[1] ), '>' . $contract['heading'] . '</h2>' ), $name );
$this->assertStringNotContainsString( '<h1', strtolower( $content ), $name );
$plain = wp_strip_all_tags( $dom->saveHTML( $children[1] ) );
$previous = -1;
foreach ( $contract['order'] as $copy ) {
$position = strpos( $plain, $copy );
$this->assertNotFalse( $position, $name . ':' . $copy );
$this->assertGreaterThan( $previous, $position, $name . ':' . $copy );
$previous = $position;
}
if ( isset( $contract['atmosphere'] ) ) {
$atmosphere_markup = $dom->saveHTML( $children[0] );
$this->assertStringContainsString( $contract['atmosphere'], $atmosphere_markup, $name );
$this->assertStringContainsString( 'loading="lazy"', $atmosphere_markup, $name );
$this->assertStringContainsString( 'type="image/avif"', $atmosphere_markup, $name );
$this->assertStringContainsString( 'type="image/webp"', $atmosphere_markup, $name );
$this->assertStringContainsString( 'alt="' . ( $contract['atmos_alt'] ?? '' ) . '"', $atmosphere_markup, $name );
}
$this->assertCount( 0, $xpath->query( './/*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-facets ")]', $stage ), $name );
$facets = $xpath->query( '//*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-facets ")]' );
if ( isset( $contract['facets'] ) ) {
$this->assertCount( 1, $facets, $name );
$this->assertSame( $stage->parentNode, $facets->item( 0 )->parentNode, $name ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
$following_element = $stage->nextSibling; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
while ( $following_element && XML_ELEMENT_NODE !== $following_element->nodeType ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
$following_element = $following_element->nextSibling; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- DOM API property.
}
$this->assertSame( $facets->item( 0 ), $following_element, $name );
$facets_markup = $dom->saveHTML( $facets->item( 0 ) );
foreach ( $contract['facets'] as $asset ) {
$this->assertStringContainsString( $asset, $facets_markup, $name );
}
$this->assertSame( 2, substr_count( $facets_markup, 'aria-hidden="true"' ), $name );
} else {
$this->assertCount( 0, $facets, $name );
}
}
}
/** Meaningful Music collage text remains exposed to assistive technology. */
public function test_music_landing_meaningful_collage_is_not_hidden_by_the_atmosphere_layer() {
$content = $this->render_pattern( get_theme_file_path( 'patterns/music-landing.php' ) );
$dom = $this->load_html_fragment( $content );
$xpath = new DOMXPath( $dom );
$stage = $xpath->query( '//*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-stage ")]' )->item( 0 );
$collage = $xpath->query( '//img[@alt="The No Names collage"]' )->item( 0 );
$this->assertInstanceOf( DOMElement::class, $stage );
$this->assertInstanceOf( DOMElement::class, $collage );
$this->assertCount( 3, $xpath->query( './*', $stage ) );
$this->assertCount( 0, $xpath->query( 'ancestor::*[@aria-hidden="true"]', $collage ) );
$this->assertCount( 1, $xpath->query( 'ancestor::*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-stage__content ")]', $collage ) );
$this->assertCount( 0, $xpath->query( './*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-stage__atmosphere ")]//picture', $stage ) );
$this->assertCount( 1, $xpath->query( './*[contains(concat(" ", normalize-space(@class), " "), " chrnx-character-stage__art ")]//picture', $stage ) );
}
/** Rendered pattern content survives parse/serialize without block-tree drift. */
public function test_character_led_patterns_preserve_editor_fidelity() {
foreach ( array( 'home-projects', 'home-music', 'music-landing', 'podcast-landing', 'about' ) as $name ) {
$content = $this->render_pattern( get_theme_file_path( 'patterns/' . $name . '.php' ) );
$parsed = parse_blocks( $content );
$serialized = serialize_blocks( $parsed );
$reparsed = parse_blocks( $serialized );
$initial_tree = $this->block_name_tree( $parsed, $name );
$round_trip = $this->block_name_tree( $reparsed, $name );
$this->assertSame( $initial_tree, $round_trip, $name );
$this->assertSame( 1, substr_count( strtolower( $content ), '<h2' ), $name );
$this->assertStringNotContainsString( '<h1', strtolower( $content ), $name );
}
}
/** Parse an HTML fragment for structural assertions. */
private function load_html_fragment( $content ) {
$dom = new DOMDocument();
$dom->loadHTML( '<?xml encoding="utf-8" ?><div id="chrnx-test-root">' . $content . '</div>', LIBXML_NOERROR | LIBXML_NOWARNING );
return $dom;
}
/** Assert a DOM element carries one class token. */
private function assert_element_has_class( DOMElement $element, $class_name, $message ) {
$this->assertContains( $class_name, preg_split( '/\s+/', trim( $element->getAttribute( 'class' ) ) ), $message );
}
/** Return the ordered nested block-name tree while rejecting non-whitespace freeform nodes. */
private function block_name_tree( array $blocks, $message ) {
$tree = array();
foreach ( $blocks as $block ) {
if ( null === $block['blockName'] ) {
$this->assertSame( '', trim( $block['innerHTML'] ), $message . ' has freeform corruption' );
continue;
}
$tree[] = array( $block['blockName'], $this->block_name_tree( $block['innerBlocks'], $message ) );
}
return $tree;
}
/** Render a pattern file exactly as WordPress does. */
private function render_pattern( $path ) {
ob_start();
+72 -3
View File
@@ -144,7 +144,7 @@ test( 'lower home sections preserve editorial order and define layered panel tre
}
assert.match( homeMusic, /chrnx_get_topic_portrait_markup\( 'music-collage'/ );
assert.match( homeMusic, /chrnx-home-music__collage-layer/ );
assert.match( homeMusic, /chrnx-character-stage__atmosphere/ );
assert.doesNotMatch( components, /url\([^)]*the-no-names-collage\.jpeg/ );
assert.match(
components,
@@ -181,8 +181,13 @@ test( 'all approved portraits rebuild byte-identically within payload bounds', (
assert.deepEqual( readdirSync( external ), [ 'sentinel' ] );
execFileSync( './scripts/build-responsive-images.sh', [ output ], { cwd: new URL( '../..', import.meta.url ) } );
const names = readdirSync( output ).sort();
assert.equal( names.length, 40 );
assert.equal( names.length, 45 );
for ( const name of [
'alter-ego-gaming-half-body-384.avif',
'alter-ego-gaming-half-body-384.webp',
'alter-ego-gaming-half-body-768.avif',
'alter-ego-gaming-half-body-768.webp',
'alter-ego-gaming-half-body.json',
'the-no-names-collage-384.avif',
'the-no-names-collage-384.webp',
'the-no-names-collage-768.avif',
@@ -193,6 +198,7 @@ test( 'all approved portraits rebuild byte-identically within payload bounds', (
}
let total = 0;
let collageTotal = 0;
let gamingHalfBodyTotal = 0;
for ( const name of names ) {
const generated = readFileSync( join( output, name ) );
const committed = readFileSync( new URL( `../../assets/images/generated/${ name }`, import.meta.url ) );
@@ -213,10 +219,17 @@ test( 'all approved portraits rebuild byte-identically within payload bounds', (
if ( name.startsWith( 'the-no-names-collage-' ) ) {
collageTotal += generated.length;
}
if ( name.startsWith( 'alter-ego-gaming-half-body-' ) ) {
gamingHalfBodyTotal += generated.length;
}
}
}
assert.ok( collageTotal <= 400 * 1024, `collage derivatives exceed 400 KiB: ${ collageTotal }` );
assert.ok( total <= 2.1 * 1024 * 1024, `derivatives exceed 2.1 MiB: ${ total }` );
assert.ok(
gamingHalfBodyTotal <= 340 * 1024,
`gaming half-body derivatives exceed 340 KiB: ${ gamingHalfBodyTotal }`,
);
assert.ok( total <= 2.4 * 1024 * 1024, `derivatives exceed 2.4 MiB: ${ total }` );
} finally {
rmSync( output, { recursive: true, force: true } );
rmSync( external, { recursive: true, force: true } );
@@ -241,3 +254,59 @@ test( 'front page and section pages connect the real editorial patterns', () =>
assert.match( fixtures, new RegExp( slug.replace( '/', '\\/' ) ) );
}
} );
test( 'character-led openings share the exact stage class contract', () => {
for ( const path of [
'patterns/home-projects.php',
'patterns/home-music.php',
'patterns/music-landing.php',
'patterns/podcast-landing.php',
'patterns/about.php',
'blocks/topic-hero/render.php',
] ) {
const source = read( path );
const stageDeclaration = path.startsWith( 'patterns/' )
? /className":"chrnx-character-stage"/g
: /class="chrnx-character-stage"/g;
assert.equal( ( source.match( stageDeclaration ) || [] ).length, 1, path );
for ( const className of [
'chrnx-character-stage__atmosphere',
'chrnx-character-stage__content',
'chrnx-character-stage__art',
] ) {
assert.match( source, new RegExp( className ), `${ path } missing ${ className }` );
}
}
const musicLanding = read( 'patterns/music-landing.php' );
assert.match( musicLanding, /chrnx_get_topic_portrait_markup\( 'music-collage', __\( 'The No Names collage', 'chrnx' \), 'chrnx-character-stage__collage' \)/ );
assert.doesNotMatch( musicLanding, /<img\s+src=/ );
assert.match( read( 'patterns/about.php' ), /chrnx-character-facets/ );
assert.match( read( 'blocks/topic-hero/render.php' ), /chrnx-topic-hero__fallback/ );
} );
test( 'character stages define the shared mockup effect and responsive geometry', () => {
const components = read( 'assets/css/components.css' );
const visualStates = read( 'tests/e2e/visual-states.spec.mjs' );
for ( const token of [
'--chrnx-character-accent',
'--chrnx-character-halo',
'--chrnx-character-wash',
'--chrnx-character-shadow',
] ) {
assert.match( components, new RegExp( token ), `${ token } must be shared` );
}
assert.match( components, /\.chrnx-character-stage\s*\{[\s\S]*?grid-template-columns:\s*minmax\(0,\s*55fr\)\s+minmax\(0,\s*45fr\)/ );
assert.match( components, /\.chrnx-character-stage__atmosphere::before/ );
assert.match( components, /\.chrnx-character-stage__atmosphere::after/ );
assert.match( components, /\.chrnx-character-stage__art\s*>\s*\.chrnx-responsive-portrait/ );
assert.match( components, /@media \(max-width:\s*780px\)[\s\S]*?\.chrnx-character-stage\s*\{[\s\S]*?grid-template-columns:\s*1fr/ );
assert.match( components, /@media \(prefers-reduced-motion:\s*reduce\)[\s\S]*?\.chrnx-character-stage/ );
assert.match( components, /--chrnx-character-copy-surface/ );
assert.match( components, /\.chrnx-music-landing \.chrnx-character-stage__content\s*>\s*\.chrnx-responsive-portrait:has\(\.chrnx-character-stage__collage\)[\s\S]*?inset:\s*0/ );
for ( const timeout of [ '180_000', '120_000', '60_000' ] ) {
assert.match( visualStates, new RegExp( `test\\.setTimeout\\( ${ timeout } \\)` ) );
}
assert.match( visualStates, /character stage below-fold derivatives wait for approach/ );
} );