diff --git a/package-lock.json b/package-lock.json index 698701f594f8e..eb00f3e7f91fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,6 +42,7 @@ }, "devDependencies": { "@343dev/gifsicle": "1.2.0", + "@axe-core/playwright": "4.13.0", "@lodder/grunt-postcss": "^3.1.1", "@napi-rs/image": "1.14.0", "@playwright/test": "1.61.1", @@ -134,6 +135,19 @@ "dev": true, "license": "ISC" }, + "node_modules/@axe-core/playwright": { + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.13.0.tgz", + "integrity": "sha512-6YLx+kxXu5GJceG4ozFg+33a2EMTdjYwWGloJ3sb9Kta5pp+ZNS53uxGVog5JetIY8s++P5UrtX+cri+u0VAVg==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "axe-core": "~4.13.0" + }, + "peerDependencies": { + "playwright-core": ">= 1.0.0" + } + }, "node_modules/@babel/code-frame": { "version": "7.29.7", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", @@ -9406,10 +9420,11 @@ "dev": true }, "node_modules/axe-core": { - "version": "4.10.2", - "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.10.2.tgz", - "integrity": "sha512-RE3mdQ7P3FRSe7eqCWoeQ/Z9QXrtniSjp1wUjt5nRC3WIpz5rSCve6o3fsZ2aCpJtrZjSZgjwXAoTO5k4tEI0w==", + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.13.0.tgz", + "integrity": "sha512-UzGt8zg7Ny8djbYMhxl2zuEevVa7r2gJjYY5Lwr1xM7+XU2nd6CkIWFTVcCIbAP63vSz71NaVyyuSk9lHKcy0A==", "dev": true, + "license": "MPL-2.0", "engines": { "node": ">=4" } diff --git a/package.json b/package.json index eb165bda5b0f0..b5203a4cfa985 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ ], "devDependencies": { "@343dev/gifsicle": "1.2.0", + "@axe-core/playwright": "4.13.0", "@lodder/grunt-postcss": "^3.1.1", "@napi-rs/image": "1.14.0", "@playwright/test": "1.61.1", @@ -153,6 +154,7 @@ "test:php": "node ./tools/local-env/scripts/docker.js run --rm php ./vendor/bin/phpunit", "test:coverage": "npm run test:php -- --coverage-html ./coverage/html/ --coverage-php ./coverage/php/report.php --coverage-text=./coverage/text/report.txt", "test:e2e": "wp-scripts test-playwright --config tests/e2e/playwright.config.js", + "test:e2e:a11y": "npm run test:e2e -- tests/e2e/specs/accessibility.spec.js", "test:visual": "wp-scripts test-playwright --config tests/visual-regression/playwright.config.js", "typecheck:php": "node ./tools/local-env/scripts/docker.js run --rm php composer phpstan --", "typecheck:php:baselines": "node ./tools/local-env/scripts/docker.js run --rm php composer phpstan:baselines --", diff --git a/tests/e2e/assets/sample.png b/tests/e2e/assets/sample.png new file mode 100644 index 0000000000000..108d87fd5b652 Binary files /dev/null and b/tests/e2e/assets/sample.png differ diff --git a/tests/e2e/specs/accessibility.spec.js b/tests/e2e/specs/accessibility.spec.js new file mode 100644 index 0000000000000..c4ac17ac1f13e --- /dev/null +++ b/tests/e2e/specs/accessibility.spec.js @@ -0,0 +1,165 @@ +import path from 'path'; +import { test, expect } from '@wordpress/e2e-test-utils-playwright'; +const AxeScanner = require( '../utils/accessibility-axe-scanner' ); +const { pages } = require( '../utils/accessibility-pages-matrix' ); +const ignoresAndFalsePositives = require( '../utils/accessibility-ignores-and-false-positives' ); + +/** + * Global accessibility scan rules. + * Applied to all pages defined in utils/accessibility-pages-matrix. + * + * See the Axe Options parameter documentation. + * See: https://github.com/dequelabs/axe-core/blob/master/doc/API.md#options-parameter + */ +const globalRules = { + runOnly: [ 'wcag2a', 'wcag2aa', 'best-practice' ], + absolutePaths: true, // Report the absolute CSS target selector for better exclusions mechanism. +}; + +/** + * Filters violations to remove violations we want to intentionally ignore and known false positives. + * Only returns violations for nodes that don't match excluded selectors. + * + * See more details in tests/e2e/utils/accessibility-ignores-and-false-positives.js. + * + * @param {Object} results Axe results object. + * @param {Object} exclusions Explicit exclusions and known false positives config (rule ID → selectors[]). + * @return {Object} Filtered results. + */ +function filterIgnoresAndFalsePositives( results, exclusions ) { + results.violations = results.violations.map( ( violation ) => { + const excludedSelectors = exclusions[ violation.id ] || []; + + if ( excludedSelectors.length === 0 ) { + return violation; + } + + // Filter out nodes matching excluded selectors. + violation.nodes = violation.nodes.filter( ( node ) => { + const targetSelector = node.target[ 0 ]; + + /* + * Normalize the received Axe-core Target Selector: remove combinators, + * attributes, and collapse spaces. This allows us to match patterns + * against the normalized selector using token-based matching. For example: + * - Raw Target Selector: "html > body > #__wp-uploader > .attachments-browser > .attachments-wrapper > li[aria-label="image-1"]" + * - After normalization: "html body #__wp-uploader .attachments-browser .attachments-wrapper li" + * + * Then it checks if all pattern tokens appear in order in the normalized selector. + * Intermediate selectors can be skipped. + */ + const normalizedTargetSelector = targetSelector + .replace( /[>+~]/g, ' ' ) // Replace combinators with spaces. + .replace( /\[[^\]]*\]/g, ' ' ) // Remove attributes (anything in brackets). + .replace( /\s+/g, ' ' ) // Collapse multiple spaces. + .trim(); + + // Check if target selector matches any excluded selector pattern. + const isExcluded = excludedSelectors.some( ( excluded ) => { + const selectors = excluded.trim().split( ' ' ).filter( s => s.length > 0 ); + return selectors.every( selector => { + // Escape regex special chars (periods, brackets, etc.) to match literals. + const escaped = selector.replace( /[.*+?^${}()|[\]\\]/g, '\\$&' ); + // Replace escaped asterisks with .* to enable wildcard matching. + const wildcard = escaped.replace( /\\\*/g, '.*' ); + // Regex checks for token at start/end or bounded by spaces. + const pattern = `(?:^|\\s)${ wildcard }(?=\\s|$)`; + return new RegExp( pattern ).test( normalizedTargetSelector ); + } ); + } ); + + return ! isExcluded; + } ); + + return violation; + } ).filter( ( violation ) => violation.nodes.length > 0 ); + + return results; +} + +/** + * Scans a page for accessibility violations and asserts no violations found. + * + * @param {Object} page Playwright page object. + * @param {Object} pageSpec Page specification object. + * @param {Object} [variant] Optional state variant spec. + * @return {Promise} + */ +async function scanAndAssert( page, pageSpec, variant = null ) { + // Merge rules: global < page < variant. + const mergedRules = { + ...globalRules, + ...( pageSpec.rules || {} ), + ...( variant?.rules || {} ), + }; + + // Scan and assert. + const scanner = new AxeScanner( { page, globalRules: mergedRules } ); + let results = await scanner.scan(); + + // Filter out known ignores and false positives. + results = filterIgnoresAndFalsePositives( results, ignoresAndFalsePositives ); + + scanner.formatResults( results ); + + // Use expect for cleaner error reporting at test location. + expect( scanner.getViolationsCount( results ) ).toBe( 0 ); +} + +test.describe( 'Admin Pages Accessibility', () => { + let mediaAttachmentId = null; + + test.beforeAll( async ( { requestUtils } ) => { + // Upload sample image to media library for testing. + const imagePath = path.resolve( __dirname, '../assets/sample.png' ) + const response = await requestUtils.uploadMedia( + imagePath + ); + + // Store the sample image ID for later cleanup. + mediaAttachmentId = response.id; + } ); + + test.afterAll( async ( { requestUtils } ) => { + // Delete the uploaded sample image. + if ( mediaAttachmentId ) { + await requestUtils.deleteMedia( mediaAttachmentId ); + } + + // Delete all posts of type 'post' and all associated comments. + await requestUtils.deleteAllPosts(); + } ); + + pages.forEach( ( pageSpec ) => { + // Normalize: pages without stateVariants get a default variant. + const variants = pageSpec.stateVariants || [ { name: 'default' } ]; + + variants.forEach( ( variant ) => { + // Generate test name: omit [variant.name] if default. + const variantName = variant.name === 'default' ? '' : ` [${ variant.name }]`; + const testName = `${ pageSpec.name }${ variantName } should not have violations`; + + test( testName, async ( { admin, editor, page, requestUtils } ) => { + // Navigate to page. + await admin.visitAdminPage( pageSpec.path ); + + // Wait for any async content to render. Some pages load content + // dynamically after the DOM is ready. This is particularly important + // for pages rendered via React components like the Settings > Connectors + // page or the Fonts page. Without this wait, the scan may run before all + // content is fully rendered. + if ( pageSpec.waitInterval ) { + await page.waitForTimeout( 500 ); + } + + // Run state setup if provided. + if ( variant.setup ) { + await variant.setup( { admin, editor, page, requestUtils, expect } ); + } + + // Scan and assert. + await scanAndAssert( page, pageSpec, variant ); + } ); + } ); + } ); +} ); diff --git a/tests/e2e/utils/accessibility-axe-scanner.js b/tests/e2e/utils/accessibility-axe-scanner.js new file mode 100644 index 0000000000000..7c3ec2b7115d0 --- /dev/null +++ b/tests/e2e/utils/accessibility-axe-scanner.js @@ -0,0 +1,135 @@ +/** + * AxeScanner utility for accessibility scanning with axe-core. + * + * Encapsulates axe-core scanning logic, result formatting, and assertions. + * Can be configured with global rules and logger functions. + * + * @example + * const scanner = new AxeScanner({ page, globalRules: { runOnly: ['wcag2a', 'wcag2aa'] } }); + * const results = await scanner.scan(); + * scanner.formatResults(results); + * scanner.assertNoViolations(results); + */ + +const AxeBuilder = require( '@axe-core/playwright' ).default; + +class AxeScanner { + /** + * Create an AxeScanner instance. + * + * @param {Object} options + * @param {Object} options.page Playwright page object. + * @param {Object} [options.globalRules] Rules config passed to axe (e.g., { runOnly: ['wcag2a', 'wcag2aa'], rules: {...} }). + * @param {Function} [options.logger] Custom logger function (defaults to console.log). + */ + constructor( { page, globalRules = {}, logger = console.log } ) { + this.page = page; + this.globalRules = globalRules; + this.logger = logger; + } + + /** + * Runs axe-core scan on the current page. + * + * @param {Object} [overrideOptions] Additional options to merge with globalRules (useful for per-page overrides). + * @returns {Promise} Axe results object (violations, passes, incomplete, inapplicable). + */ + async scan( overrideOptions = {} ) { + const options = this._mergeRulesOptions( this.globalRules, overrideOptions ); + + const results = await new AxeBuilder( { page: this.page } ) + .options( options ) + .analyze(); + + return results; + } + + /** + * Formats and logs scan results to console. + * Outputs violation details, element selectors, and HTML snippets. + * + * @param {Object} results Axe results object. + */ + formatResults( results ) { + const violationsAmount = results.violations.length; + + if ( violationsAmount === 0 ) { + this.logger( 'No accessibility violations found!' ); + return; + } + + this.logger( `\nFound ${ violationsAmount } accessibility violation(s):\n` ); + + /* + * Result Object documentation: https://github.com/dequelabs/axe-core/blob/master/doc/API.md#results-object + * This object has four components: + * - a `passes` array: keeps track of all the passed tests, + * along with detailed information on each one. + * - a `violations` array: keeps track of all the failed tests, + * along with detailed information on each one. + * - an `incomplete` array: indicates which nodes could neither be + * determined to definitively pass or definitively + * fail. They are separated out in order that + * a user interface can display these to the + * user for manual review + * - an `inapplicable` array: lists all the rules for which no matching + * elements were found on the page. + */ + results.violations.forEach( ( violation, index ) => { + this.logger( `--- Violation #${ index + 1 } ---` ); + this.logger( `Rule ID: ${ violation.id }` ); + this.logger( `Impact: ${ violation.impact.toUpperCase() }` ); + this.logger( `Failure: ${ violation.description }` ); + this.logger( `Help: ${ violation.help }` ); + this.logger( `Help link: ${ violation.helpUrl }` ); + + // List every specific HTML element failing a failing rule. + this.logger( 'Failing elements:' ); + violation.nodes.forEach( ( node ) => { + this.logger( ` - Target Selector: ${ node.target.join( ', ' ) }` ); + this.logger( ` - HTML Snippet:\n${ node.html }` ); + } ); + this.logger( '\n' ); + } ); + } + + /** + * Asserts that there are no accessibility violations. + * Returns the violations amount; let the test use expect() for cleaner error reporting. + * + * @param {Object} results Axe results object. + * @returns {number} Number of violations found. + */ + getViolationsCount( results ) { + return results.violations.length; + } + + /** + * Merges rules options, with overrides taking precedence over global rules.. + * + * @private + * @param {Object} globalRules Global rules config. + * @param {Object} overrideRules Override rules config. + * @returns {Object} Merged rules object. + */ + _mergeRulesOptions( globalRules, overrideRules ) { + // Deep merge rules object to allow per-rule overrides + if ( globalRules.rules && overrideRules.rules ) { + return { + ...globalRules, + ...overrideRules, + rules: { + ...globalRules.rules, + ...overrideRules.rules, + }, + }; + } + + return { + ...globalRules, + ...overrideRules, + }; + } +} + +module.exports = AxeScanner; diff --git a/tests/e2e/utils/accessibility-ignores-and-false-positives.js b/tests/e2e/utils/accessibility-ignores-and-false-positives.js new file mode 100644 index 0000000000000..efdc4f4bebf25 --- /dev/null +++ b/tests/e2e/utils/accessibility-ignores-and-false-positives.js @@ -0,0 +1,64 @@ +/** + * Explicit exclusions and known false positives after human inspection. + * + * Maps rule IDs to CSS selectors that should be excluded from the reported violations. + * These are instances where axe-core flags a violation, but after human review, + * the pattern is acceptable or represents a known limitation of the automated check. + * + * MATCHING ALGORITHM: + * 1. Normalize target selector: remove combinators (>, +, ~) and collapse spaces. + * 2. Split pattern into space-separated tokens. + * 3. Check if all tokens appear in order in the normalized selector (not necessarily consecutive). + * 4. Supports wildcard matching with asterisks (*) in patterns. + * + * Then it checks if all pattern tokens appear in order in the normalized selector. + * Intermediate selectors can be skipped, and attributes are automatically removed. + * + * For example: + * - Raw Target Selector: "html > body > #__wp-uploader > .attachments-browser > .attachments-wrapper > li[aria-label="image-1"]" + * - After Normalization: "html body #__wp-uploader .attachments-browser .attachments-wrapper li" + * - Pattern ".attachments-browser li" MATCHES (skips .attachments-wrapper; all tokens found in order). + * - Pattern ".attachments-browser .attachments-wrapper" MATCHES (all tokens found). + * - Pattern ".attachments-browserxyz" does NOT match (token boundary prevents partial matches). + * - Attributes are removed during normalization, so patterns never need to include them. + * + * WILDCARD SUPPORT: + * Use an asterisk * to match any characters in a selector token. For example: + * - Pattern "#wp-admin-bar-*" matches "#wp-admin-bar-site-name", "#wp-admin-bar-updates", etc. + * - Pattern "#wpadminbar #wp-toolbar #wp-admin-bar-*" matches full descendant chains with variable final selectors. + * + * CONSTRAINTS: + * Exclusion patterns must be space-separated tokens only (e.g., '#id .class li'). + * Do not use attribute selectors, pseudo-classes, or explicit combinators (>, +, ~) in patterns. + * Spaces implicitly represent descendant relationships (any number of intermediate selectors). + * + * NOTE: + * The passed pattern isn't meant to be a meaningful CSS selector. It's only used + * to match the Axe-core target selector of a violation. Just use a space-separated + * list of tokens that appear in the 'Target Selector' entry of the reported violation. + */ + +module.exports = { + 'link-in-text-block': [ + // Post title links in list tables may have surrounding text and are only distinguished by color. + // We consider this acceptable as these links can be distinguished by the context. + '.wp-list-table strong .row-title', + // Same for the Media Library list mode. + '#posts-filter #the-list #post-* .has-media-icon a', + // Em dashes for the pages hierarchy and other text e.g. post status are considered 'surrounding text'. + '.wp-list-table #the-list #post-* th strong a', + ], + 'aria-allowed-role': [ + // The "group" role for the admin bar list items is flagged as invalid by axe-core. + // This is a known false positive in axe-core and can be ignored. Note + // that the 'aria-allowed-role' rule is part of the 'best-practice' rules group. + // Related axe-core issue https://github.com/dequelabs/axe-core/issues/3439 on the 'aria-allowed-role' rule. + '#wp-toolbar #wp-admin-bar-*', + // Same known false positive in axe-core for the media attachments list browser. + '.attachments-browser .attachments-wrapper #__attachments-view-* .attachment', + ], + 'region': [ + // Visually hidden text that clarifies what the ARIA live regions are about. + '#a11y-speak-intro-text', + ], +}; diff --git a/tests/e2e/utils/accessibility-pages-matrix.js b/tests/e2e/utils/accessibility-pages-matrix.js new file mode 100644 index 0000000000000..fbcb772d9e83e --- /dev/null +++ b/tests/e2e/utils/accessibility-pages-matrix.js @@ -0,0 +1,384 @@ +/** + * Accessibility test pages matrix. + * + * Defines WordPress admin pages to scan for accessibility violations. + * Each page spec can have multiple state variants for testing different UI states. + * + * OVERVIEW: + * - `id`: Unique identifier for the page (used for logging and filtering) + * - `path`: WordPress admin path relative to /wp-admin/ (e.g., '/upload.php?mode=grid') + * - `name`: Human-readable name (shown in test output) + * - `rules`: (optional) Per-page axe rules override. Merged with global rules. + * - `waitInterval`: (optional) Boolean indicating if the test should wait for a + * short interval before scanning. This is particularly important + * for pages rendered via React components like the Settings > Connectors + * page or the Fonts page. Without this wait, the scan may run before all + * content is fully rendered. + * - `stateVariants`: (optional) Array of UI states to test. Each variant has: + * - `name`: State identifier (shown in test name) + * - `setup`: (optional) Async function to set up the state. Receives (page, requestUtils) objects. + * - `rules`: (optional) State-specific rule override. Merged with page and global rules. + * + * HOW TO ADD A PAGE: + * + * 1. Simple page (single state): + * { + * id: 'my-page', + * path: '/my-page.php', + * name: 'My Page Name', + * } + * + * 2. Page with multiple states: + * { + * id: 'my-page-multi', + * path: '/my-page.php', + * name: 'My Page with Multiple States', + * stateVariants: [ + * { name: 'default' }, + * { + * name: 'with-filter', + * setup: async ( { admin, editor, page, requestUtils } ) => { + // Create test data if needed. + await requestUtils.createPost({ title: 'Test', status: 'draft' }); + // Apply UI state. + * await page.getByRole('link', { name: 'Draft' }).click(); + * await page.waitForLoadState('networkidle'); + * } + * }, + * ] + * } + * + * HOW TO MODIFY: + * - To disable a page from scanning, remove or comment out its entry. + * - To add a new state variant, add another object to stateVariants. + * - To change rule config per-page, modify the `rules` property. + * + * IMPORT IN TESTS: + * const { pages } = require( './accessibility-pages-matrix' ); + * pages.forEach( (pageSpec) => { ... } ); + */ + +const { filterByStatus } = require( './admin-interactions' ); + +const pages = [ + // Dashboard. + { + id: 'dashboard', + path: '/', + name: 'Dashboard', + }, + { + id: 'updates', + path: '/update-core.php', + name: 'Updates', + }, + + // Posts & Pages. + { + id: 'posts-list', + path: '/edit.php?post_type=post', + name: 'Posts', + stateVariants: [ + { + name: 'default', + setup: async ( { page, requestUtils } ) => { + // Create a published post. + await requestUtils.createPost( { + title: 'Test Published Post', + status: 'publish', + } ); + // Create a pending review post so there's something to filter. + await requestUtils.createPost( { + title: 'Test Pending Review Post', + status: 'pending', + } ); + // Reload the page to show the draft. + await page.reload(); + }, + }, + { + name: 'draft-filter', + setup: async ( { page, requestUtils, expect } ) => { + // Create a draft post so there's something to filter. + await requestUtils.createPost( { + title: 'Test Draft Post', + status: 'draft', + } ); + // Reload the page to show the draft. + await page.reload(); + // Ensure table is visible before filtering. + const draftPostsTable = page.locator( 'table.wp-list-table' ); + await expect( draftPostsTable ).toBeVisible(); + await filterByStatus( page, 'draft' ); + }, + }, + ], + }, + { + id: 'post-categories-list', + path: '/edit-tags.php?taxonomy=category', + name: 'Categories', + }, + { + id: 'post-tags-list', + path: '/edit-tags.php?taxonomy=post_tag', + name: 'Tags', + }, + { + id: 'pages-list', + path: '/edit.php?post_type=page', + name: 'Pages', + }, + + // Media. + { + id: 'media-library-grid', + path: '/upload.php?mode=grid', + name: 'Media Library (Grid View)', + stateVariants: [ + { + name: 'default', + }, + { + name: 'image-modal-open', + setup: async ( { page } ) => { + // Click the image to open the attachment modal. + const imageLink = page.locator( '.attachment' ).first(); + await imageLink.click(); + // Wait for modal to appear. + await page.waitForSelector( '.media-modal' ); + }, + }, + ], + }, + { + id: 'media-library-list', + path: '/upload.php?mode=list', + name: 'Media Library (List View)', + }, + + // Comments. + { + id: 'comments', + path: '/edit-comments.php', + name: 'Comments', + stateVariants: [ + { + name: 'default', + setup: async ( { page, requestUtils } ) => { + // Create a post to attach comments to. + const { id: postId } = await requestUtils.createPost( { + title: 'Post for comments', + status: 'publish', + } ); + + // Create an approved comment. + await requestUtils.createComment( { + content: 'Test Approved Comment', + status: 'approve', + post: postId, + } ); + // Create a comment awaiting moderation. + await requestUtils.createComment( { + content: 'Test Comment Awaiting Moderation', + status: 'hold', + post: postId, + } ); + + // Reload the page to show the comments. + await page.reload(); + }, + }, + ], + }, + + // Appearance. + { + id: 'themes', + path: '/themes.php', + name: 'Themes', + }, + { + id: 'add-themes', + path: '/theme-install.php?browse=popular', + name: 'Add Themes', + }, + { + id: 'fonts-list', + path: '/font-library.php?p=%2Ffont-list', + name: 'Fonts', + waitInterval: true, + stateVariants: [ + { + name: 'default', + }, + { + name: 'fonts-upload-tab', + setup: async ( { page, expect } ) => { + const uploadTab = page.getByRole( 'tab', { name: 'Upload' } ); + await uploadTab.click(); + const uploadTabPanel = page.getByRole( 'tabpanel', { name: 'Upload' } ); + await expect( uploadTabPanel ).toBeVisible(); + }, + }, + { + name: 'fonts-install-fonts-tab', + setup: async ( { page, expect } ) => { + const installFontsTab = page.getByRole( 'tab', { name: 'Install Fonts' } ); + await installFontsTab.click(); + const installFontsTabPanel = page.getByRole( 'tabpanel', { name: 'Install Fonts' } ); + await expect( installFontsTabPanel ).toBeVisible(); + }, + }, + ], + }, + + // Plugins. + { + id: 'installed-plugins', + path: '/plugins.php', + name: 'Plugins', + }, + { + id: 'add-plugins', + path: '/plugin-install.php', + name: 'Add Plugins', + }, + + // Users. + { + id: 'users-list', + path: '/users.php', + name: 'Users', + }, + { + id: 'add-user', + path: '/user-new.php', + name: 'Add User', + }, + + // Admin profile. + { + id: 'profile', + path: '/profile.php', + name: 'Profile', + }, + + // Tools. + { + id: 'tools', + path: '/tools.php', + name: 'Tools', + }, + { + id: 'tools-import', + path: '/import.php', + name: 'Tools - Import', + }, + { + id: 'tools-export', + path: '/export.php', + name: 'Tools - Export', + }, + { + id: 'site-health-status', + path: '/site-health.php', + name: 'Tools - Site Health Status', + }, + { + id: 'site-health-info-wp-section', + path: '/site-health.php?tab=debug#health-check-section-wp-core', + name: 'Tools - Site Health Info WP section open', + }, + { + id: 'export-personal-data', + path: '/export-personal-data.php', + name: 'Tools - Export Personal Data', + }, + { + id: 'erase-personal-data', + path: '/erase-personal-data.php', + name: 'Tools - Erase Personal Data', + }, + + // Settings. + { + id: 'settings-general', + path: '/options-general.php', + name: 'Settings - General', + }, + + { + id: 'settings-connectors', + path: '/options-connectors.php', + name: 'Settings - Connectors', + waitInterval: true, + }, + + { + id: 'settings-writing', + path: '/options-writing.php', + name: 'Settings - Writing', + }, + + { + id: 'settings-reading', + path: '/options-reading.php', + name: 'Settings - Reading', + }, + + { + id: 'settings-discussion', + path: '/options-discussion.php', + name: 'Settings - Discussion', + }, + + { + id: 'settings-media', + path: '/options-media.php', + name: 'Settings - Media', + }, + + { + id: 'settings-permalinks', + path: '/options-permalink.php', + name: 'Settings - Permalinks', + }, + + { + id: 'settings-privacy', + path: '/options-privacy.php', + name: 'Settings - Privacy', + }, + + // About. + { + id: 'about', + path: '/about.php', + name: 'About', + }, + { + id: 'credits', + path: '/credits.php', + name: 'Credits', + }, + { + id: 'freedoms', + path: '/freedoms.php', + name: 'Freedoms', + }, + { + id: 'privacy', + path: '/privacy.php', + name: 'Privacy', + }, + { + id: 'contribute', + path: '/contribute.php', + name: 'Get involved', + } +]; + +module.exports = { + pages, +}; diff --git a/tests/e2e/utils/admin-interactions.js b/tests/e2e/utils/admin-interactions.js new file mode 100644 index 0000000000000..d57c8eb48468c --- /dev/null +++ b/tests/e2e/utils/admin-interactions.js @@ -0,0 +1,211 @@ +/** + * Common WordPress admin interaction patterns. + * + * Reusable utilities for UI interactions used in state variants. + * Can be called directly or composed inside page object state setup functions. + * + * @example + * const { filterByStatus, toggleListGridView } = require( './admin-interactions' ); + * + * const variant = { + * name: 'filtered-draft', + * setup: async (page) => { await filterByStatus(page, 'draft'); } + * }; + */ + +/** + * Filter posts by status using the view switcher links. + * + * @param {Object} page - Playwright page object + * @param {string} status - Status to filter by (e.g., 'all', 'published', 'draft', 'scheduled', 'pending') + * @returns {Promise} + */ +async function filterByStatus( page, status ) { + const statusMap = { + all: 'All', + published: 'Published', + draft: 'Draft', + scheduled: 'Scheduled', + pending: 'Pending review', + trash: 'Trash', + }; + + const label = statusMap[ status ]; + if ( ! label ) { + throw new Error( `Unknown status filter: ${ status }. Expected one of: ${ Object.keys( statusMap ).join( ', ' ) }` ); + } + + // Match the label with optional count suffix (e.g., "Draft" or "Draft (1)") + const link = page.getByRole( 'link', { name: new RegExp( `^${ label }( \\(\\d+\\))?$` ) } ); + await link.click(); + + // Brief wait for filter to apply + await page.waitForLoadState( 'networkidle' ); +} + +/** + * Toggle between list and grid view modes. + * + * @param {Object} page - Playwright page object + * @param {string} viewMode - View mode ('list' or 'grid') + * @returns {Promise} + */ +async function toggleListGridView( page, viewMode ) { + const viewMap = { + list: 'List View', + grid: 'Grid View', + }; + + const label = viewMap[ viewMode ]; + if ( ! label ) { + throw new Error( `Unknown view mode: ${ viewMode }. Expected one of: list, grid` ); + } + + const button = page.getByRole( 'button', { name: label } ); + await button.click(); + + // Brief wait for view to change + await page.waitForLoadState( 'networkidle' ); +} + +/** + * Expand a collapsible section or panel. + * Works for common WordPress patterns like meta boxes or panels with toggle buttons. + * + * @param {Object} page - Playwright page object + * @param {string} sectionName - Name or label of the section to expand + * @returns {Promise} + */ +async function expandCollapsibleSection( page, sectionName ) { + const button = page.getByRole( 'button', { name: sectionName } ); + const isExpanded = await button.getAttribute( 'aria-expanded' ); + + if ( isExpanded === 'false' ) { + await button.click(); + // Brief wait for expansion animation + await page.waitForTimeout( 300 ); + } +} + +/** + * Close a collapsible section or panel. + * + * @param {Object} page - Playwright page object + * @param {string} sectionName - Name or label of the section to collapse + * @returns {Promise} + */ +async function collapseCollapsibleSection( page, sectionName ) { + const button = page.getByRole( 'button', { name: sectionName } ); + const isExpanded = await button.getAttribute( 'aria-expanded' ); + + if ( isExpanded === 'true' ) { + await button.click(); + // Brief wait for collapse animation + await page.waitForTimeout( 300 ); + } +} + +/** + * Open a modal dialog by clicking its trigger button. + * + * @param {Object} page - Playwright page object + * @param {string} triggerLabel - Label or text of the button that opens the modal + * @returns {Promise} + */ +async function openModal( page, triggerLabel ) { + const button = page.getByRole( 'button', { name: triggerLabel } ); + await button.click(); + + // Wait for modal to appear + const modal = page.getByRole( 'dialog' ).first(); + await modal.waitFor( { state: 'visible' } ); +} + +/** + * Close the current modal dialog (e.g., by clicking close button or Escape). + * + * @param {Object} page - Playwright page object + * @param {string} [method='button'] - How to close: 'button' (click close button) or 'escape' (press Escape key) + * @returns {Promise} + */ +async function closeModal( page, method = 'button' ) { + if ( method === 'escape' ) { + await page.keyboard.press( 'Escape' ); + } else { + // Try to find close button (common patterns: aria-label="Close", text "Close") + const closeButton = page + .getByRole( 'button', { name: /close/i } ) + .first(); + if ( await closeButton.isVisible() ) { + await closeButton.click(); + } else { + throw new Error( 'Could not find close button for modal' ); + } + } + + // Wait for modal to disappear + const modal = page.getByRole( 'dialog' ).first(); + await modal.waitFor( { state: 'hidden' } ); +} + +/** + * Hover over an element to trigger hover state (e.g., reveal action buttons). + * + * @param {Object} page - Playwright page object + * @param {string} selector - CSS selector or Playwright locator of element to hover + * @returns {Promise} + */ +async function hoverElement( page, selector ) { + const locator = typeof selector === 'string' ? page.locator( selector ) : selector; + await locator.hover(); + + // Brief wait for hover state to render + await page.waitForTimeout( 100 ); +} + +/** + * Wait for a table to be fully rendered. + * Useful for pages that load data dynamically. + * + * @param {Object} page - Playwright page object + * @param {string} [tableSelector='table'] - CSS selector for the table + * @returns {Promise} + */ +async function waitForTableReady( page, tableSelector = 'table' ) { + const table = page.locator( tableSelector ); + await table.waitFor( { state: 'visible' } ); + + // Wait for rows to be present + const rows = page.locator( `${ tableSelector } tbody tr` ); + await rows.first().waitFor( { state: 'visible' } ); + + await page.waitForLoadState( 'networkidle' ); +} + +/** + * Search or filter using a search input. + * + * @param {Object} page - Playwright page object + * @param {string} searchText - Text to search for + * @param {string} [searchSelector='input[type="search"]'] - Selector for search input + * @returns {Promise} + */ +async function search( page, searchText, searchSelector = 'input[type="search"]' ) { + const input = page.locator( searchSelector ); + await input.fill( searchText ); + + // Wait for search results to update + await page.waitForLoadState( 'networkidle' ); +} + +module.exports = { + filterByStatus, + toggleListGridView, + expandCollapsibleSection, + collapseCollapsibleSection, + openModal, + closeModal, + hoverElement, + waitForTableReady, + search, +};