From 3a34a9990f557cf749e15283476b0e57ade1b8aa Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Wed, 12 Aug 2026 21:54:50 -0500 Subject: [PATCH] test: verify Related Stories workflows --- assets/js/related-posts.js | 24 +- playwright.config.mjs | 16 +- scripts/seed-test-content.php | 137 +++++- scripts/seed-test-content.sh | 2 +- tests/e2e/related-stories-scenarios.spec.mjs | 104 +++++ tests/e2e/related-stories.spec.mjs | 461 +++++++++++++++---- tests/js/related-posts.test.js | 21 + tests/smoke/e2e-harness.test.mjs | 47 +- 8 files changed, 702 insertions(+), 110 deletions(-) create mode 100644 tests/e2e/related-stories-scenarios.spec.mjs diff --git a/assets/js/related-posts.js b/assets/js/related-posts.js index 4cd3da7..e4230d9 100644 --- a/assets/js/related-posts.js +++ b/assets/js/related-posts.js @@ -84,6 +84,7 @@ tabIndex: rememberAttribute( track, 'tabindex' ), }; let rail = carousel || environment.media.matches; + let clearHeadingFocus = null; const updateEdges = () => { const maximum = Math.max( 0, track.scrollWidth - track.clientWidth ); @@ -118,7 +119,17 @@ const previousTabIndex = rememberAttribute( heading, 'tabindex' ); heading.setAttribute( 'tabindex', '-1' ); focusWithoutScroll( heading ); - restoreAttribute( heading, 'tabindex', previousTabIndex ); + if ( environment.document.activeElement !== heading ) { + restoreAttribute( heading, 'tabindex', previousTabIndex ); + return; + } + const restoreHeadingTabIndex = () => { + heading.removeEventListener( 'blur', restoreHeadingTabIndex ); + restoreAttribute( heading, 'tabindex', previousTabIndex ); + clearHeadingFocus = null; + }; + heading.addEventListener( 'blur', restoreHeadingTabIndex, { once: true } ); + clearHeadingFocus = restoreHeadingTabIndex; }; const applyViewport = () => { const nextRail = carousel || environment.media.matches; @@ -142,7 +153,13 @@ const onPrevious = () => scroll( -1 ); const onNext = () => scroll( 1 ); const onMediaChange = () => applyViewport(); - const onResize = () => updateEdges(); + const onResize = () => { + if ( adaptive && rail !== environment.media.matches ) { + applyViewport(); + return; + } + updateEdges(); + }; previous.addEventListener( 'click', onPrevious ); next.addEventListener( 'click', onNext ); @@ -161,6 +178,9 @@ if ( adaptive ) { environment.media.removeEventListener( 'change', onMediaChange ); } + if ( clearHeadingFocus ) { + clearHeadingFocus(); + } controls.hidden = original.controlsHidden; previous.disabled = original.previousDisabled; next.disabled = original.nextDisabled; diff --git a/playwright.config.mjs b/playwright.config.mjs index c721e0d..68e9177 100644 --- a/playwright.config.mjs +++ b/playwright.config.mjs @@ -14,26 +14,36 @@ export default defineConfig({ projects: [ { name: 'chromium', - testIgnore: 'visual-scenarios.spec.mjs', + testIgnore: [ 'visual-scenarios.spec.mjs', 'related-stories-scenarios.spec.mjs' ], use: { ...devices['Desktop Chrome'] }, }, { name: 'firefox', - testIgnore: 'visual-scenarios.spec.mjs', + testIgnore: [ 'visual-scenarios.spec.mjs', 'related-stories-scenarios.spec.mjs' ], use: { ...devices['Desktop Firefox'] }, }, { name: 'webkit', - testIgnore: 'visual-scenarios.spec.mjs', + testIgnore: [ 'visual-scenarios.spec.mjs', 'related-stories-scenarios.spec.mjs' ], use: { ...devices['Desktop Safari'] }, }, { name: 'scenarios', testMatch: 'visual-scenarios.spec.mjs', + testIgnore: 'related-stories-scenarios.spec.mjs', dependencies: [ 'chromium', 'firefox', 'webkit' ], fullyParallel: false, workers: 1, use: { ...devices['Desktop Chrome'] }, }, + { + name: 'related-scenarios', + testMatch: 'related-stories-scenarios.spec.mjs', + testIgnore: 'visual-scenarios.spec.mjs', + dependencies: [ 'scenarios' ], + fullyParallel: false, + workers: 1, + use: { ...devices['Desktop Chrome'] }, + }, ], }); diff --git a/scripts/seed-test-content.php b/scripts/seed-test-content.php index 59be910..4c4a5af 100644 --- a/scripts/seed-test-content.php +++ b/scripts/seed-test-content.php @@ -14,7 +14,7 @@ if ( ! in_array( $chrnx_seed_host, array( 'localhost', '127.0.0.1' ), true ) ) { WP_CLI::error( 'Refusing to seed a non-local WordPress site.' ); } $chrnx_seed_scenario = isset( $args[0] ) && is_string( $args[0] ) ? $args[0] : 'default'; -$chrnx_seed_scenarios = array( 'default', 'featured-1', 'featured-2', 'featured-3', 'subscribe-unpublished', 'subscribe-unavailable', 'restore' ); +$chrnx_seed_scenarios = array( 'default', 'featured-1', 'featured-2', 'featured-3', 'subscribe-unpublished', 'subscribe-unavailable', 'related-1', 'related-2', 'related-4', 'restore' ); if ( ! in_array( $chrnx_seed_scenario, $chrnx_seed_scenarios, true ) ) { WP_CLI::error( 'Unknown local fixture scenario.' ); } @@ -81,11 +81,123 @@ function chrnx_seed_upsert_post( array $fixture, string $post_type, int $offset return absint( $result ); } +/** Return the option that stores temporary unrelated-post statuses. */ +function chrnx_seed_related_status_snapshot_name(): string { + return '_chrnx_fixture_related_unowned_status_snapshot_v1'; +} + +/** + * Capture every eligible unrelated post before a Related Stories scenario. + * + * @return array Exact records from the first scenario. + */ +function chrnx_seed_snapshot_related_unowned_statuses(): array { + $snapshot_name = chrnx_seed_related_status_snapshot_name(); + $snapshot = get_option( $snapshot_name, false ); + if ( is_array( $snapshot ) && 1 === ( $snapshot['version'] ?? null ) && is_array( $snapshot['posts'] ?? null ) ) { + return $snapshot['posts']; + } + + $candidate_ids = get_posts( + array( + 'post_type' => 'post', + 'post_status' => 'publish', + 'posts_per_page' => -1, + 'fields' => 'ids', + 'no_found_rows' => true, + 'meta_query' => array( + array( + 'key' => '_chrnx_fixture_key', + 'compare' => 'NOT EXISTS', + ), + ), + ) + ); + $records = array(); + foreach ( $candidate_ids as $candidate_id ) { + $candidate_id = absint( $candidate_id ); + if ( chrnx_is_eligible_editorial_post( $candidate_id ) ) { + $records[] = array( + 'id' => $candidate_id, + 'status' => (string) get_post_status( $candidate_id ), + ); + } + } + update_option( + $snapshot_name, + array( + 'version' => 1, + 'posts' => $records, + ), + false + ); + return $records; +} + +/** Temporarily draft the exact unrelated posts captured for a Related Stories scenario. */ +function chrnx_seed_draft_related_unowned_posts(): void { + foreach ( chrnx_seed_snapshot_related_unowned_statuses() as $record ) { + $post_id = absint( $record['id'] ?? 0 ); + if ( $post_id <= 0 || ! get_post( $post_id ) ) { + continue; + } + $result = wp_update_post( + array( + 'ID' => $post_id, + 'post_status' => 'draft', + ), + true + ); + if ( is_wp_error( $result ) ) { + WP_CLI::error( 'Could not isolate an unrelated Related Stories fixture candidate.' ); + } + } +} + +/** Restore exact unrelated-post statuses after a Related Stories scenario. */ +function chrnx_seed_restore_related_unowned_statuses(): bool { + $snapshot_name = chrnx_seed_related_status_snapshot_name(); + $snapshot = get_option( $snapshot_name, false ); + if ( ! is_array( $snapshot ) ) { + return false; + } + if ( 1 !== ( $snapshot['version'] ?? null ) || ! is_array( $snapshot['posts'] ?? null ) ) { + WP_CLI::error( 'Related Stories fixture snapshot is invalid.' ); + } + foreach ( $snapshot['posts'] as $record ) { + $post_id = absint( $record['id'] ?? 0 ); + $status = sanitize_key( $record['status'] ?? '' ); + if ( $post_id <= 0 || ! get_post( $post_id ) ) { + continue; + } + if ( ! array_key_exists( $status, get_post_stati() ) ) { + WP_CLI::error( 'Related Stories fixture snapshot contains an invalid post status.' ); + } + $result = wp_update_post( + array( + 'ID' => $post_id, + 'post_status' => $status, + ), + true + ); + if ( is_wp_error( $result ) ) { + WP_CLI::error( 'Could not restore an unrelated Related Stories fixture candidate.' ); + } + } + delete_option( $snapshot_name ); + return true; +} + if ( 'restore' === $chrnx_seed_scenario ) { + chrnx_seed_restore_related_unowned_statuses(); WP_CLI::log( chrnx_fixture_environment_restore() ? 'CHRNX_FIXTURES_RESTORE snapshot=restored' : 'CHRNX_FIXTURES_RESTORE snapshot=none' ); return; } +if ( 'default' === $chrnx_seed_scenario ) { + chrnx_seed_restore_related_unowned_statuses(); +} + chrnx_fixture_environment_snapshot(); chrnx_seed_editorial_terms(); $chrnx_seed_pages = chrnx_seed_read_fixture( 'pages.json' ); @@ -149,6 +261,29 @@ foreach ( $chrnx_seed_posts as $chrnx_seed_index => $chrnx_seed_post ) { $chrnx_seed_post_ids[ $chrnx_seed_post['fixtureKey'] ] = $chrnx_seed_post_id; } +if ( preg_match( '/^related-([124])$/', $chrnx_seed_scenario, $chrnx_seed_related_match ) ) { + chrnx_seed_draft_related_unowned_posts(); + $chrnx_seed_related_count = absint( $chrnx_seed_related_match[1] ); + $chrnx_seed_current_key = 'post-literature-long'; + $chrnx_seed_related_candidates = array_values( array_diff( array_keys( $chrnx_seed_post_ids ), array( $chrnx_seed_current_key ) ) ); + $chrnx_seed_published_keys = array_merge( + array( $chrnx_seed_current_key ), + array_slice( $chrnx_seed_related_candidates, 0, $chrnx_seed_related_count ) + ); + foreach ( $chrnx_seed_post_ids as $chrnx_seed_post_key => $chrnx_seed_owned_post_id ) { + $chrnx_seed_status_result = wp_update_post( + array( + 'ID' => $chrnx_seed_owned_post_id, + 'post_status' => in_array( $chrnx_seed_post_key, $chrnx_seed_published_keys, true ) ? 'publish' : 'draft', + ), + true + ); + if ( is_wp_error( $chrnx_seed_status_result ) ) { + WP_CLI::error( 'Could not apply Related Stories fixture status.' ); + } + } +} + $chrnx_seed_sticky_ids = array(); foreach ( $chrnx_seed_posts as $chrnx_seed_post ) { if ( ! empty( $chrnx_seed_post['featured'] ) && isset( $chrnx_seed_post_ids[ $chrnx_seed_post['fixtureKey'] ] ) ) { diff --git a/scripts/seed-test-content.sh b/scripts/seed-test-content.sh index 28630ad..d038d42 100755 --- a/scripts/seed-test-content.sh +++ b/scripts/seed-test-content.sh @@ -7,7 +7,7 @@ chrnx_docker_cli_dir=${CHRNX_DOCKER_CLI_DIR:-/opt/homebrew/opt/docker/bin} chrnx_seed_scenario=${1:-default} case "$chrnx_seed_scenario" in - default|featured-1|featured-2|featured-3|subscribe-unpublished|subscribe-unavailable|restore) ;; + default|featured-1|featured-2|featured-3|subscribe-unpublished|subscribe-unavailable|related-1|related-2|related-4|restore) ;; *) echo "Unknown local fixture scenario: $chrnx_seed_scenario" >&2 exit 2 diff --git a/tests/e2e/related-stories-scenarios.spec.mjs b/tests/e2e/related-stories-scenarios.spec.mjs new file mode 100644 index 0000000..3a7e913 --- /dev/null +++ b/tests/e2e/related-stories-scenarios.spec.mjs @@ -0,0 +1,104 @@ +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { expect, test } from '@playwright/test'; + +const projectRoot = fileURLToPath( new URL( '../..', import.meta.url ) ); +const commandEnvironment = { + ...process.env, + PATH: `/opt/homebrew/opt/docker/bin:${ process.env.PATH ?? '' }`, +}; +const seedScenario = ( scenario ) => + execFileSync( './scripts/seed-test-content.sh', [ scenario ], { + cwd: projectRoot, + env: commandEnvironment, + stdio: 'pipe', + } ); + +function readFixtureState() { + const php = String.raw` + $owned = get_posts(array('post_type'=>array('page','post'),'post_status'=>'any','posts_per_page'=>-1,'orderby'=>'ID','order'=>'ASC','meta_key'=>'_chrnx_fixture_key')); + $records = array(); + foreach ($owned as $post) { + $records[] = array('id'=>$post->ID,'key'=>get_post_meta($post->ID,'_chrnx_fixture_key',true),'type'=>$post->post_type,'status'=>$post->post_status,'slug'=>$post->post_name,'content'=>hash('sha256',$post->post_content)); + } + $unrelated = get_posts(array('post_type'=>array('page','post'),'post_status'=>'any','posts_per_page'=>-1,'orderby'=>'ID','order'=>'ASC','meta_query'=>array(array('key'=>'_chrnx_fixture_key','compare'=>'NOT EXISTS')))); + $outside = array(); + foreach ($unrelated as $post) { + $outside[] = array('id'=>$post->ID,'type'=>$post->post_type,'status'=>$post->post_status,'slug'=>$post->post_name,'content'=>hash('sha256',$post->post_content)); + } + echo 'CHRNX_STATE=' . wp_json_encode(array('owned'=>$records,'unrelated'=>$outside,'relatedSnapshot'=>get_option('_chrnx_fixture_related_unowned_status_snapshot_v1',false))); + `; + const output = execFileSync( 'npm', [ 'exec', '--', 'wp-env', 'run', 'cli', 'wp', 'eval', php ], { + cwd: projectRoot, + env: commandEnvironment, + encoding: 'utf8', + } ); + const encoded = output.match( /CHRNX_STATE=(\{.*\})/ )?.[ 1 ]; + if ( ! encoded ) { + throw new Error( 'Could not read the local fixture state.' ); + } + const state = JSON.parse( encoded ); + return { + ...state, + fingerprint: createHash( 'sha256' ).update( JSON.stringify( state ) ).digest( 'hex' ), + }; +} + +test.describe.configure( { mode: 'serial' } ); + +test.afterAll( () => { + seedScenario( 'default' ); +} ); + +test( 'related scenarios render exact partial counts and restore the identical default dataset', async ( { + page, +} ) => { + seedScenario( 'default' ); + const baseline = readFixtureState(); + const unrelatedBaseline = baseline.unrelated.find( ( post ) => post.slug === 'hello-world' ); + expect( unrelatedBaseline ).toMatchObject( { status: 'publish', slug: 'hello-world' } ); + expect( baseline.owned.filter( ( post ) => post.type === 'page' ) ).toHaveLength( 7 ); + expect( baseline.owned.filter( ( post ) => post.type === 'post' ) ).toHaveLength( 12 ); + expect( baseline.owned ).toHaveLength( 19 ); + seedScenario( 'default' ); + expect( readFixtureState() ).toEqual( baseline ); + + try { + for ( const count of [ 1, 2, 4 ] ) { + seedScenario( `related-${ count }` ); + const duringScenario = readFixtureState(); + const unrelatedDuringScenario = duringScenario.unrelated.find( + ( post ) => post.id === unrelatedBaseline.id, + ); + expect( unrelatedDuringScenario ).toEqual( { + ...unrelatedBaseline, + status: 'draft', + } ); + expect( duringScenario.relatedSnapshot.posts ).toContainEqual( { + id: unrelatedBaseline.id, + status: 'publish', + } ); + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( `/long-title-night-writing-fixture/?fixtureScenario=related-${ count }` ); + const section = page.locator( '#related-stories-5-adaptive .chrnx-related-posts' ); + const cards = section.locator( '.chrnx-related-card' ); + const buttons = section.getByRole( 'button' ); + await expect( cards ).toHaveCount( count ); + await expect( buttons ).toHaveCount( 2 ); + if ( count === 1 ) { + await expect( buttons.nth( 0 ) ).toBeDisabled(); + await expect( buttons.nth( 1 ) ).toBeDisabled(); + } + } + } finally { + seedScenario( 'default' ); + } + + const restored = readFixtureState(); + expect( restored ).toEqual( baseline ); + await page.goto( '/long-title-night-writing-fixture/?fixtureScenario=default' ); + await expect( page.locator( '#related-stories-5-adaptive .chrnx-related-card' ) ).toHaveCount( + 5, + ); +} ); diff --git a/tests/e2e/related-stories.spec.mjs b/tests/e2e/related-stories.spec.mjs index 940a0d8..0a80c36 100644 --- a/tests/e2e/related-stories.spec.mjs +++ b/tests/e2e/related-stories.spec.mjs @@ -1,11 +1,12 @@ import { expect, test } from '@playwright/test'; +import { injectAxe } from 'axe-playwright'; async function logIn( page ) { await page.goto( '/wp-login.php' ); await page.locator( '#user_login' ).fill( 'admin' ); await page.locator( '#user_pass' ).fill( 'password' ); await Promise.all( [ - page.waitForURL( /\/wp-admin\// ), + page.waitForURL( ( url ) => url.pathname.startsWith( '/wp-admin/' ) ), page.getByRole( 'button', { name: /log in/i } ).click(), ] ); } @@ -35,107 +36,137 @@ async function openSettings( page ) { } } -test( 'Related Stories is insertable and configurable in the real post editor', async ( { - page, -} ) => { - await logIn( page ); - await page.goto( '/wp-admin/post-new.php' ); - await closeWelcomeGuide( page ); - await expect( page.getByRole( 'heading', { name: 'Add Post', exact: true } ) ).toBeVisible(); - - const inserted = await page.evaluate( () => { - const type = window.wp.blocks.getBlockType( 'chrnx/related-posts' ); - if ( ! type ) { - return false; - } - const block = window.wp.blocks.createBlock( 'chrnx/related-posts' ); - window.wp.data.dispatch( 'core/block-editor' ).insertBlock( block ); - window.wp.data.dispatch( 'core/block-editor' ).selectBlock( block.clientId ); - return ( - window.wp.data.select( 'core/block-editor' ).getSelectedBlockClientId() === block.clientId - ); - } ); - expect( inserted ).toBe( true ); - - await openSettings( page ); - await expect( page.getByLabel( 'Stories to show', { exact: true } ) ).toBeVisible(); - await expect( page.getByLabel( 'Layout', { exact: true } ) ).toBeVisible(); - await expect( page.getByText( 'Related stories settings', { exact: true } ) ).toBeVisible(); -} ); - -test( 'Related Stories persists typed attributes with null saved HTML in the Site Editor', async ( { - page, -} ) => { - await logIn( page ); - await page.goto( - '/wp-admin/site-editor.php?postType=wp_template&postId=chrnx%2F%2Fsingle&canvas=edit', - ); - await closeWelcomeGuide( page ); - - await expect - .poll( () => - page.evaluate( () => { - const editor = window.wp?.data?.select( 'core/block-editor' ); - return typeof editor?.getBlocks === 'function' && editor.getBlocks().length > 0; - } ), - ) - .toBe( true ); - - const recovery = page - .locator( 'iframe' ) - .contentFrame() - .getByRole( 'button', { name: 'Attempt recovery' } ) - .first(); - if ( await recovery.isVisible() ) { - await recovery.click(); +function tabShortcut( browserName, reverse = false ) { + const modifiers = []; + if ( browserName === 'webkit' ) { + modifiers.push( 'Alt' ); } + if ( reverse ) { + modifiers.push( 'Shift' ); + } + return [ ...modifiers, 'Tab' ].join( '+' ); +} - const selected = await page.evaluate( () => { - const getNestedBlocks = ( blocks ) => - blocks.flatMap( ( block ) => [ block, ...getNestedBlocks( block.innerBlocks || [] ) ] ); - const store = window.wp.data.select( 'core/block-editor' ); - const block = getNestedBlocks( store.getBlocks() ).find( - ( candidate ) => candidate.name === 'chrnx/related-posts', +async function scrollRailNatively( page, track, browserName ) { + await track.hover(); + if ( browserName === 'webkit' ) { + await track.evaluate( ( element ) => { + const card = element.querySelector( '.chrnx-related-card' ); + const style = window.getComputedStyle( element ); + const gap = Number.parseFloat( style.columnGap || style.gap ) || 0; + element.scrollBy( { + left: card.getBoundingClientRect().width + gap, + behavior: 'auto', + } ); + } ); + return; + } + await page.mouse.wheel( 240, 0 ); +} + +test.describe.serial( 'Related Stories editor integration', () => { + test( 'Related Stories is insertable and configurable in the real post editor', async ( { + page, + } ) => { + await logIn( page ); + await page.goto( '/wp-admin/post-new.php' ); + await closeWelcomeGuide( page ); + await expect( page.getByRole( 'heading', { name: 'Add Post', exact: true } ) ).toBeVisible(); + + const inserted = await page.evaluate( () => { + const type = window.wp.blocks.getBlockType( 'chrnx/related-posts' ); + if ( ! type ) { + return false; + } + const block = window.wp.blocks.createBlock( 'chrnx/related-posts' ); + window.wp.data.dispatch( 'core/block-editor' ).insertBlock( block ); + window.wp.data.dispatch( 'core/block-editor' ).selectBlock( block.clientId ); + return ( + window.wp.data.select( 'core/block-editor' ).getSelectedBlockClientId() === block.clientId + ); + } ); + expect( inserted ).toBe( true ); + + await openSettings( page ); + await expect( page.getByLabel( 'Stories to show', { exact: true } ) ).toBeVisible(); + await expect( page.getByLabel( 'Layout', { exact: true } ) ).toBeVisible(); + await expect( page.getByText( 'Related stories settings', { exact: true } ) ).toBeVisible(); + } ); + + test( 'Related Stories persists typed attributes with null saved HTML in the Site Editor', async ( { + page, + } ) => { + await logIn( page ); + await page.goto( + '/wp-admin/site-editor.php?postType=wp_template&postId=chrnx%2F%2Fsingle&canvas=edit', ); - if ( ! block ) { - return false; + await closeWelcomeGuide( page ); + + await expect + .poll( () => + page.evaluate( () => { + const editor = window.wp?.data?.select( 'core/block-editor' ); + return typeof editor?.getBlocks === 'function' && editor.getBlocks().length > 0; + } ), + ) + .toBe( true ); + + const recovery = page + .locator( 'iframe' ) + .contentFrame() + .getByRole( 'button', { name: 'Attempt recovery' } ) + .first(); + if ( await recovery.isVisible() ) { + await recovery.click(); } - window.wp.data.dispatch( 'core/block-editor' ).selectBlock( block.clientId ); - return true; - } ); - expect( selected ).toBe( true ); - await openSettings( page ); - await page.getByLabel( 'Stories to show', { exact: true } ).selectOption( '5' ); - await page.getByLabel( 'Layout', { exact: true } ).selectOption( 'carousel' ); + const selected = await page.evaluate( () => { + const getNestedBlocks = ( blocks ) => + blocks.flatMap( ( block ) => [ block, ...getNestedBlocks( block.innerBlocks || [] ) ] ); + const store = window.wp.data.select( 'core/block-editor' ); + const block = getNestedBlocks( store.getBlocks() ).find( + ( candidate ) => candidate.name === 'chrnx/related-posts', + ); + if ( ! block ) { + return false; + } + window.wp.data.dispatch( 'core/block-editor' ).selectBlock( block.clientId ); + return true; + } ); + expect( selected ).toBe( true ); - const state = await page.evaluate( () => { - const getNestedBlocks = ( blocks ) => - blocks.flatMap( ( block ) => [ block, ...getNestedBlocks( block.innerBlocks || [] ) ] ); - const block = getNestedBlocks( window.wp.data.select( 'core/block-editor' ).getBlocks() ).find( - ( candidate ) => candidate.name === 'chrnx/related-posts', + await openSettings( page ); + await page.getByLabel( 'Stories to show', { exact: true } ).selectOption( '5' ); + await page.getByLabel( 'Layout', { exact: true } ).selectOption( 'carousel' ); + + const state = await page.evaluate( () => { + const getNestedBlocks = ( blocks ) => + blocks.flatMap( ( block ) => [ block, ...getNestedBlocks( block.innerBlocks || [] ) ] ); + const block = getNestedBlocks( + window.wp.data.select( 'core/block-editor' ).getBlocks(), + ).find( ( candidate ) => candidate.name === 'chrnx/related-posts' ); + return { + limit: block.attributes.limit, + limitType: typeof block.attributes.limit, + layout: block.attributes.layout, + editType: typeof window.wp.blocks.getBlockType( block.name )?.edit, + selectedClientId: window.wp.data.select( 'core/block-editor' ).getSelectedBlockClientId(), + clientId: block.clientId, + saveContent: window.wp.blocks.getSaveContent( block.name, block.attributes ), + serialized: window.wp.blocks.serialize( block ), + }; + } ); + + expect( state.limit ).toBe( 5 ); + expect( state.limitType ).toBe( 'number' ); + expect( state.layout ).toBe( 'carousel' ); + expect( state.editType ).toBe( 'function' ); + expect( state.selectedClientId ).toBe( state.clientId ); + expect( state.saveContent ).toBe( '' ); + expect( state.serialized ).toMatch( + /^$/, ); - return { - limit: block.attributes.limit, - limitType: typeof block.attributes.limit, - layout: block.attributes.layout, - editType: typeof window.wp.blocks.getBlockType( block.name )?.edit, - selectedClientId: window.wp.data.select( 'core/block-editor' ).getSelectedBlockClientId(), - clientId: block.clientId, - saveContent: window.wp.blocks.getSaveContent( block.name, block.attributes ), - serialized: window.wp.blocks.serialize( block ), - }; } ); - - expect( state.limit ).toBe( 5 ); - expect( state.limitType ).toBe( 'number' ); - expect( state.layout ).toBe( 'carousel' ); - expect( state.editType ).toBe( 'function' ); - expect( state.selectedClientId ).toBe( state.clientId ); - expect( state.saveContent ).toBe( '' ); - expect( state.serialized ).toMatch( - /^$/, - ); } ); const layoutCases = [ @@ -440,3 +471,245 @@ for ( const theme of [ 'light', 'dark' ] ) { await page.mouse.up(); } ); } + +test( 'interaction buttons move exactly one card and update both disabled edges', async ( { + page, +} ) => { + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + const section = page.locator( '#related-stories-3-adaptive .chrnx-related-posts' ); + const track = section.locator( '[data-chrnx-related-track]' ); + const previous = section.getByRole( 'button', { + name: 'Previous stories', + } ); + const next = section.getByRole( 'button', { name: 'Next stories' } ); + const step = await track.evaluate( ( element ) => { + const card = element.querySelector( '.chrnx-related-card' ); + const style = window.getComputedStyle( element ); + return card.getBoundingClientRect().width + Number.parseFloat( style.columnGap || style.gap ); + } ); + + await expect( previous ).toBeDisabled(); + await expect( next ).toBeEnabled(); + await next.click(); + await expect + .poll( () => track.evaluate( ( element ) => element.scrollLeft ) ) + .toBeGreaterThan( step - 3 ); + expect( await track.evaluate( ( element ) => element.scrollLeft ) ).toBeLessThanOrEqual( + step + 3, + ); + await expect( previous ).toBeEnabled(); + + await next.click(); + await expect( next ).toBeDisabled(); + await previous.click(); + await expect( next ).toBeEnabled(); +} ); + +test( 'interaction native horizontal wheel scrolling remains available', async ( { + page, + browserName, +} ) => { + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + const track = page.locator( '#related-stories-3-adaptive [data-chrnx-related-track]' ); + await expect( track ).toHaveCSS( 'overflow-x', 'auto' ); + await scrollRailNatively( page, track, browserName ); + await expect + .poll( () => track.evaluate( ( element ) => element.scrollLeft ) ) + .toBeGreaterThan( 0 ); +} ); + +test( 'interaction Tab reaches rail, cards, controls, then exits without trapping', async ( { + page, + browserName, +} ) => { + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + const section = page.locator( '#related-stories-3-adaptive .chrnx-related-posts' ); + const track = section.locator( '[data-chrnx-related-track]' ); + const links = track.locator( '.chrnx-related-card__link' ); + const previous = section.getByRole( 'button', { + name: 'Previous stories', + } ); + const next = section.getByRole( 'button', { name: 'Next stories' } ); + await next.click(); + await expect( previous ).toBeEnabled(); + await track.focus(); + + for ( let index = 0; index < ( await links.count() ); index += 1 ) { + await page.keyboard.press( tabShortcut( browserName ) ); + await expect( links.nth( index ) ).toBeFocused(); + } + await expect( previous ).toBeEnabled(); + await expect( next ).toBeDisabled(); + await page.keyboard.press( tabShortcut( browserName ) ); + await expect( previous ).toBeFocused(); + await page.keyboard.press( tabShortcut( browserName ) ); + const nextSectionTrack = page.locator( '#related-stories-5-adaptive [data-chrnx-related-track]' ); + await expect( nextSectionTrack ).toBeFocused(); + + await previous.click(); + await expect( next ).toBeEnabled(); + await nextSectionTrack.focus(); + await page.keyboard.press( tabShortcut( browserName, true ) ); + await expect( next ).toBeFocused(); + await page.keyboard.press( tabShortcut( browserName, true ) ); + await expect( previous ).toBeFocused(); +} ); + +for ( const buttonName of [ 'Previous stories', 'Next stories' ] ) { + test( `interaction resize repairs ${ buttonName } focus before adaptive controls hide`, async ( { + page, + } ) => { + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + const section = page.locator( '#related-stories-3-adaptive .chrnx-related-posts' ); + const heading = section.getByRole( 'heading', { + name: 'Related stories', + } ); + if ( buttonName === 'Previous stories' ) { + await section.getByRole( 'button', { name: 'Next stories' } ).click(); + await expect( section.getByRole( 'button', { name: 'Previous stories' } ) ).toBeEnabled(); + } + const button = section.getByRole( 'button', { name: buttonName } ); + await button.focus(); + await expect( button ).toBeFocused(); + await page.setViewportSize( { width: 901, height: 900 } ); + await expect( heading ).toBeFocused(); + await expect( section.locator( '.chrnx-related-posts__controls' ) ).toBeHidden(); + } ); +} + +test( 'interaction reduced motion avoids smooth scrolling and preserves card geometry', async ( { + page, +} ) => { + await page.emulateMedia( { reducedMotion: 'reduce' } ); + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + const section = page.locator( '#related-stories-3-adaptive .chrnx-related-posts' ); + const track = section.locator( '[data-chrnx-related-track]' ); + const card = track.locator( '.chrnx-related-card' ).first(); + const before = await card.evaluate( ( element ) => element.getBoundingClientRect().width ); + await track.evaluate( ( element ) => { + globalThis.__chrnxRelatedScrollBehaviors = []; + const nativeScrollBy = element.scrollBy.bind( element ); + element.scrollBy = ( options ) => { + globalThis.__chrnxRelatedScrollBehaviors.push( options.behavior ); + nativeScrollBy( options ); + }; + } ); + await section.getByRole( 'button', { name: 'Next stories' } ).click(); + await expect + .poll( () => track.evaluate( () => globalThis.__chrnxRelatedScrollBehaviors ) ) + .toEqual( [ 'auto' ] ); + expect( await card.evaluate( ( element ) => element.getBoundingClientRect().width ) ).toBeCloseTo( + before, + 1, + ); +} ); + +test.describe( 'no JavaScript progressive access', () => { + test.use( { javaScriptEnabled: false } ); + + test( 'no JavaScript keeps controls hidden and every rail link keyboard reachable', async ( { + page, + browserName, + } ) => { + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + for ( const anchor of [ 'related-stories-3-adaptive', 'related-stories-3-carousel' ] ) { + const section = page.locator( `#${ anchor } .chrnx-related-posts` ); + const controls = section.locator( '.chrnx-related-posts__controls' ); + const track = section.locator( '[data-chrnx-related-track]' ); + const links = track.locator( '.chrnx-related-card__link' ); + await expect( controls ).toBeHidden(); + await track.focus(); + for ( let index = 0; index < ( await links.count() ); index += 1 ) { + await page.keyboard.press( tabShortcut( browserName ) ); + const link = links.nth( index ); + await expect( link ).toBeFocused(); + await expect( link ).toHaveAttribute( 'href', /.+/ ); + expect( new URL( await link.getAttribute( 'href' ), page.url() ).origin ).toBe( + new URL( page.url() ).origin, + ); + } + } + } ); +} ); + +test( 'interaction controller failure leaves the native rail and links usable', async ( { + page, + browserName, +} ) => { + await page.route( '**/wp-content/themes/chrnx/assets/js/related-posts.js*', ( route ) => + route.abort(), + ); + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + const section = page.locator( '#related-stories-3-adaptive .chrnx-related-posts' ); + const track = section.locator( '[data-chrnx-related-track]' ); + await expect( section.locator( '.chrnx-related-posts__controls' ) ).toBeHidden(); + await expect( track ).toHaveCSS( 'overflow-x', 'auto' ); + await scrollRailNatively( page, track, browserName ); + await expect + .poll( () => track.evaluate( ( element ) => element.scrollLeft ) ) + .toBeGreaterThan( 0 ); + await track.focus(); + await page.keyboard.press( tabShortcut( browserName ) ); + await expect( track.locator( '.chrnx-related-card__link' ).first() ).toBeFocused(); +} ); + +test( 'permalink every rendered related card reaches a same-origin published HTTP 200', async ( { + page, +} ) => { + const sourcePath = '/long-title-night-writing-fixture/'; + await page.goto( sourcePath ); + const sourceOrigin = new URL( page.url() ).origin; + const hrefs = await page + .locator( '#related-stories-5-grid .chrnx-related-card__link' ) + .evaluateAll( ( links ) => links.map( ( link ) => link.href ) ); + expect( hrefs ).toHaveLength( 5 ); + expect( new Set( hrefs ).size ).toBe( hrefs.length ); + + for ( const href of hrefs ) { + expect( new URL( href ).origin ).toBe( sourceOrigin ); + await page.goto( sourcePath ); + const responsePromise = page.waitForNavigation(); + await page.locator( `#related-stories-5-grid a[href="${ href }"]` ).click(); + const response = await responsePromise; + expect( response.status() ).toBe( 200 ); + expect( await response.text() ).not.toMatch( /PHP (?:Warning|Notice)|Fatal error/i ); + await expect( page.locator( 'body' ) ).toHaveClass( /single-post/ ); + await expect( page.getByRole( 'heading', { level: 1 } ) ).toBeVisible(); + } +} ); + +test( 'accessibility grid and active carousel pass automated WCAG 2.2 AA checks', async ( { + page, +}, testInfo ) => { + test.skip( + testInfo.project.name !== 'chromium', + 'Axe is intentionally deterministic in Chromium.', + ); + await page.setViewportSize( { width: 900, height: 900 } ); + await page.goto( '/long-title-night-writing-fixture/' ); + await injectAxe( page ); + const tags = [ 'wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa' ]; + for ( const selector of [ '#related-stories-5-grid', '#related-stories-5-carousel' ] ) { + const violations = await page.evaluate( + async ( { contextSelector, runOnly } ) => { + const result = await globalThis.axe.run( document.querySelector( contextSelector ), { + runOnly: { type: 'tag', values: runOnly }, + } ); + return result.violations.map( ( violation ) => ( { + id: violation.id, + impact: violation.impact, + nodes: violation.nodes.map( ( node ) => node.target ), + } ) ); + }, + { contextSelector: selector, runOnly: tags }, + ); + expect( violations, selector ).toEqual( [] ); + } +} ); diff --git a/tests/js/related-posts.test.js b/tests/js/related-posts.test.js index 06c5f75..00bb312 100644 --- a/tests/js/related-posts.test.js +++ b/tests/js/related-posts.test.js @@ -298,11 +298,32 @@ describe( 'Related Stories progressive controllers', () => { media.change( false ); expect( focusAtHide ).toBe( fixture.heading ); expect( document.activeElement ).toBe( fixture.heading ); + expect( fixture.heading.getAttribute( 'tabindex' ) ).toBe( '-1' ); + document.querySelector( '[data-unrelated]' ).focus(); expect( fixture.heading.hasAttribute( 'tabindex' ) ).toBe( false ); expect( fixture.controls.hidden ).toBe( true ); }, ); + test( 'resize repairs focused controls before the media change event arrives', () => { + const { initialize } = require( modulePath ); + const media = createMedia( true ); + const fixture = installFixture().get( 'one' ); + initialize( options( media ) ); + fixture.next.focus(); + + media.matches = false; + fixture.geometry.clientWidth = fixture.geometry.scrollWidth; + window.dispatchEvent( new Event( 'resize' ) ); + + expect( document.activeElement ).toBe( fixture.heading ); + expect( fixture.controls.hidden ).toBe( true ); + expect( fixture.next.disabled ).toBe( false ); + expect( fixture.heading.getAttribute( 'tabindex' ) ).toBe( '-1' ); + document.querySelector( '[data-unrelated]' ).focus(); + expect( fixture.heading.hasAttribute( 'tabindex' ) ).toBe( false ); + } ); + test( 'unrelated focus remains unchanged when adaptive controls hide', () => { const { initialize } = require( modulePath ); const media = createMedia( true ); diff --git a/tests/smoke/e2e-harness.test.mjs b/tests/smoke/e2e-harness.test.mjs index 7cd90f5..1e7bcb4 100644 --- a/tests/smoke/e2e-harness.test.mjs +++ b/tests/smoke/e2e-harness.test.mjs @@ -24,23 +24,52 @@ test( 'Playwright seeds deterministic local fixtures once outside browser worker assert.doesNotMatch( spec, /wp-env|execFileSync|beforeAll/ ); } ); -test( 'database scenarios run only in a serial Chromium project after all read-only browsers', async () => { +test( 'exactly two serial mutation projects run after every read-only browser', async () => { const config = await readFile( 'playwright.config.mjs', 'utf8' ); const files = await readdir( 'tests/e2e' ); - const scenario = await readFile( 'tests/e2e/visual-scenarios.spec.mjs', 'utf8' ); + const mutationSpecs = [ 'related-stories-scenarios.spec.mjs', 'visual-scenarios.spec.mjs' ]; + const mutationSources = await Promise.all( + mutationSpecs.map( ( file ) => readFile( `tests/e2e/${ file }`, 'utf8' ) ), + ); + const detectedMutations = []; - for ( const file of files.filter( ( name ) => name.endsWith( '.spec.mjs' ) && name !== 'visual-scenarios.spec.mjs' ) ) { + for ( const file of files.filter( ( name ) => name.endsWith( '.spec.mjs' ) ) ) { const source = await readFile( `tests/e2e/${ file }`, 'utf8' ); - assert.doesNotMatch( source, /seed-test-content|wp-env|execFileSync/, `${ file } must be DB read-only` ); + if ( /seed-test-content|wp-env|execFileSync/.test( source ) ) { + detectedMutations.push( file ); + } else { + assert.doesNotMatch( + source, + /seed-test-content|wp-env|execFileSync/, + `${ file } must be DB read-only`, + ); + } } + assert.deepEqual( detectedMutations.sort(), mutationSpecs ); + assert.equal( + config.match( + /testIgnore:\s*\[\s*['"]visual-scenarios\.spec\.mjs['"],\s*['"]related-stories-scenarios\.spec\.mjs['"]\s*\]/gs, + )?.length, + 3, + ); assert.match( config, /name:\s*['"]scenarios['"]/ ); assert.match( config, /testMatch:\s*['"]visual-scenarios\.spec\.mjs['"]/ ); - assert.match( config, /dependencies:\s*\[\s*['"]chromium['"],\s*['"]firefox['"],\s*['"]webkit['"]\s*\]/s ); - assert.match( config, /fullyParallel:\s*false/ ); - assert.match( config, /workers:\s*1/ ); - assert.match( scenario, /test\.describe\.configure\(\s*\{\s*mode:\s*['"]serial['"]/s ); - assert.match( scenario, /test\.afterAll[\s\S]*seedScenario\(\s*['"]default['"]\s*\)/ ); + assert.match( config, /testIgnore:\s*['"]related-stories-scenarios\.spec\.mjs['"]/ ); + assert.match( + config, + /dependencies:\s*\[\s*['"]chromium['"],\s*['"]firefox['"],\s*['"]webkit['"]\s*\]/s, + ); + assert.match( config, /name:\s*['"]related-scenarios['"]/ ); + assert.match( config, /testMatch:\s*['"]related-stories-scenarios\.spec\.mjs['"]/ ); + assert.match( config, /testIgnore:\s*['"]visual-scenarios\.spec\.mjs['"]/ ); + assert.match( config, /dependencies:\s*\[\s*['"]scenarios['"]\s*\]/s ); + assert.equal( config.match( /fullyParallel:\s*false/g )?.length, 2 ); + assert.equal( config.match( /workers:\s*1/g )?.length, 2 ); + for ( const source of mutationSources ) { + assert.match( source, /test\.describe\.configure\(\s*\{\s*mode:\s*['"]serial['"]/s ); + assert.match( source, /test\.afterAll[\s\S]*seedScenario\(\s*['"]default['"]\s*\)/ ); + } } ); test( 'the npm integration chain finishes isolated PHP before browser workers', async () => {