Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat: replace hand-rolled a11y checks with real axe-core (#324)

Cindy Zhang1ae6c1389983
diff --git a/.github/scripts/accessibility-audit.js b/.github/scripts/accessibility-audit.js
index eab0d3bba4..eab7221266 100644
--- a/.github/scripts/accessibility-audit.js
+++ b/.github/scripts/accessibility-audit.js
@@ -7,6 +7,7 @@
*/
const { chromium } = require('playwright');
+const { AxeBuilder } = require('@axe-core/playwright');
const fs = require('fs');
const path = require('path');
const http = require('http');
@@ -22,6 +23,15 @@ const outputFile = getArg('output') || 'a11y-report.json';
const componentsArg = getArg('components') || '';
const components = componentsArg.split(',').filter(Boolean);
+// Rules to disable — these are Storybook-context false positives, not component issues
+const DISABLED_RULES = [
+ 'html-has-lang', // Storybook controls <html>, not the component
+ 'document-title', // iframe has no <title>, irrelevant for components
+ 'landmark-one-main', // component stories are fragments, not full pages
+ 'page-has-heading-one', // same — not a full page
+ 'region', // content doesn't need to be in landmarks in story isolation
+];
+
// Simple static file server
function createServer(dir, port) {
return new Promise((resolve) => {
@@ -29,6 +39,14 @@ function createServer(dir, port) {
let filePath = path.join(dir, req.url === '/' ? 'index.html' : req.url);
filePath = filePath.split('?')[0];
+ // Prevent path traversal — ensure resolved path stays within served directory
+ const resolved = path.resolve(filePath);
+ if (!resolved.startsWith(path.resolve(dir))) {
+ res.writeHead(403);
+ res.end('Forbidden');
+ return;
+ }
+
const ext = path.extname(filePath);
const contentTypes = {
'.html': 'text/html',
@@ -71,109 +89,6 @@ async function getStories(storybookPath) {
}
}
-// axe-core script to inject
-const AXE_SCRIPT = `
-// Minimal axe-core implementation for accessibility testing
-window.runAxe = async function() {
- const violations = [];
-
- // Check for images without alt text
- document.querySelectorAll('img:not([alt])').forEach(el => {
- violations.push({
- id: 'image-alt',
- impact: 'critical',
- description: 'Images must have alternate text',
- nodes: [{ html: el.outerHTML.substring(0, 100) }]
- });
- });
-
- // Check for buttons without accessible names
- document.querySelectorAll('button').forEach(el => {
- const hasText = el.textContent.trim();
- const hasAriaLabel = el.getAttribute('aria-label');
- const hasAriaLabelledBy = el.getAttribute('aria-labelledby');
- const hasTitle = el.getAttribute('title');
-
- if (!hasText && !hasAriaLabel && !hasAriaLabelledBy && !hasTitle) {
- violations.push({
- id: 'button-name',
- impact: 'critical',
- description: 'Buttons must have discernible text',
- nodes: [{ html: el.outerHTML.substring(0, 100) }]
- });
- }
- });
-
- // Check for form inputs without labels
- document.querySelectorAll('input:not([type="hidden"]):not([type="submit"]):not([type="button"])').forEach(el => {
- const id = el.getAttribute('id');
- const hasLabel = id && document.querySelector(\`label[for="\${id}"]\`);
- const hasAriaLabel = el.getAttribute('aria-label');
- const hasAriaLabelledBy = el.getAttribute('aria-labelledby');
- const hasTitle = el.getAttribute('title');
- const hasPlaceholder = el.getAttribute('placeholder');
-
- if (!hasLabel && !hasAriaLabel && !hasAriaLabelledBy && !hasTitle && !hasPlaceholder) {
- violations.push({
- id: 'label',
- impact: 'critical',
- description: 'Form elements must have labels',
- nodes: [{ html: el.outerHTML.substring(0, 100) }]
- });
- }
- });
-
- // Check for low color contrast (basic check)
- // This is a simplified check - real axe-core does much more
-
- // Check for missing lang attribute
- if (!document.documentElement.getAttribute('lang')) {
- violations.push({
- id: 'html-has-lang',
- impact: 'serious',
- description: '<html> element must have a lang attribute',
- nodes: [{ html: '<html>' }]
- });
- }
-
- // Check for missing main landmark
- if (!document.querySelector('main, [role="main"]')) {
- // Don't flag this for component stories - they're fragments
- }
-
- // Check for empty links
- document.querySelectorAll('a').forEach(el => {
- const hasText = el.textContent.trim();
- const hasAriaLabel = el.getAttribute('aria-label');
- const hasImage = el.querySelector('img[alt]');
-
- if (!hasText && !hasAriaLabel && !hasImage) {
- violations.push({
- id: 'link-name',
- impact: 'serious',
- description: 'Links must have discernible text',
- nodes: [{ html: el.outerHTML.substring(0, 100) }]
- });
- }
- });
-
- // Check for positive tabindex
- document.querySelectorAll('[tabindex]').forEach(el => {
- const tabindex = parseInt(el.getAttribute('tabindex'), 10);
- if (tabindex > 0) {
- violations.push({
- id: 'tabindex',
- impact: 'serious',
- description: 'Elements should not have tabindex greater than zero',
- nodes: [{ html: el.outerHTML.substring(0, 100) }]
- });
- }
- });
-
- return { violations };
-};
-`;
-
async function runAccessibilityAudit() {
console.log('Starting accessibility audit...');
console.log(`Components to audit: ${components.length > 0 ? components.join(', ') : 'all affected'}`);
@@ -185,7 +100,7 @@ async function runAccessibilityAudit() {
const report = {
error: 'Storybook not built',
components: {},
- summary: { total: 0, violations: 0 }
+ summary: { total: 0, violations: 0 },
};
fs.writeFileSync(outputFile, JSON.stringify(report, null, 2));
return;
@@ -202,7 +117,7 @@ async function runAccessibilityAudit() {
console.log(`Found ${storyIds.length} stories`);
// Filter stories for relevant components
- const relevantStories = storyIds.filter(id => {
+ const relevantStories = storyIds.filter((id) => {
// Skip docs pages
if (id.endsWith('--docs')) return false;
@@ -215,7 +130,9 @@ async function runAccessibilityAudit() {
const componentPart = titleParts.length > 1 ? titleParts[1] : titleParts[0];
const normalizedComponent = componentPart.replace(/^XDS/i, '').toLowerCase();
- return components.some(comp => normalizedComponent === comp.toLowerCase());
+ return components.some(
+ (comp) => normalizedComponent === comp.toLowerCase()
+ );
});
// Group stories by component
@@ -232,67 +149,102 @@ async function runAccessibilityAudit() {
console.log(`Auditing ${Object.keys(storyGroups).length} components`);
const browser = await chromium.launch();
- const context = await browser.newContext({
- viewport: { width: 1280, height: 720 },
- });
-
const componentResults = {};
let totalViolations = 0;
- for (const [component, componentStories] of Object.entries(storyGroups)) {
- const componentViolations = [];
-
- for (const story of componentStories) {
- const page = await context.newPage();
-
- try {
- const url = `http://localhost:${port}/iframe.html?id=${story.id}&viewMode=story`;
- await page.goto(url, { waitUntil: 'networkidle', timeout: 10000 });
- await page.waitForTimeout(300);
-
- // Inject and run accessibility check
- await page.addScriptTag({ content: AXE_SCRIPT });
- const results = await page.evaluate(() => window.runAxe());
+ try {
+ const context = await browser.newContext({
+ viewport: { width: 1280, height: 720 },
+ });
- if (results.violations.length > 0) {
+ for (const [component, componentStories] of Object.entries(storyGroups)) {
+ const componentViolations = [];
+
+ for (const story of componentStories) {
+ const page = await context.newPage();
+
+ try {
+ const url = `http://localhost:${port}/iframe.html?id=${story.id}&viewMode=story`;
+ // Higher timeout to accommodate axe-core's heavier DOM analysis
+ await page.goto(url, { waitUntil: 'networkidle', timeout: 15000 });
+ // Brief wait for any post-load rendering before axe-core scans the DOM
+ await page.waitForTimeout(500);
+
+ // Run axe-core accessibility analysis
+ const results = await new AxeBuilder({ page })
+ .disableRules(DISABLED_RULES)
+ .analyze();
+
+ if (results.violations.length > 0) {
+ componentViolations.push({
+ story: story.name || story.id,
+ violations: results.violations,
+ });
+ totalViolations += results.violations.length;
+ }
+
+ console.log(
+ `✓ Audited: ${component} / ${story.name} - ${results.violations.length} issues`
+ );
+ } catch (e) {
+ console.error(`✗ Failed: ${story.id} - ${e.message}`);
+ // Record the failure but continue
componentViolations.push({
story: story.name || story.id,
- violations: results.violations,
+ error: e.message,
+ violations: [],
});
- totalViolations += results.violations.length;
+ } finally {
+ await page.close();
}
-
- console.log(`✓ Audited: ${component} / ${story.name} - ${results.violations.length} issues`);
- } catch (e) {
- console.error(`✗ Failed: ${story.id} - ${e.message}`);
- } finally {
- await page.close();
}
- }
-
- // Aggregate violations for component
- const uniqueViolations = [];
- const seenIds = new Set();
- for (const storyResult of componentViolations) {
- for (const violation of storyResult.violations) {
- if (!seenIds.has(violation.id)) {
- seenIds.add(violation.id);
- uniqueViolations.push(violation);
+ // Aggregate violations for component — preserve counts and story context
+ const violationMap = new Map();
+
+ for (const storyResult of componentViolations) {
+ for (const violation of storyResult.violations) {
+ if (!violationMap.has(violation.id)) {
+ violationMap.set(violation.id, {
+ id: violation.id,
+ impact: violation.impact,
+ description: violation.description,
+ help: violation.help,
+ helpUrl: violation.helpUrl,
+ tags: violation.tags,
+ storyCount: 0,
+ totalNodes: 0,
+ stories: [],
+ nodes: [],
+ });
+ }
+ const agg = violationMap.get(violation.id);
+ agg.storyCount++;
+ agg.totalNodes += violation.nodes.length;
+ agg.stories.push(storyResult.story);
+ // Keep first 3 nodes for display (cap to avoid bloat)
+ if (agg.nodes.length < 3) {
+ agg.nodes.push(
+ ...violation.nodes.slice(0, 3 - agg.nodes.length).map((n) => ({
+ html: n.html.substring(0, 200),
+ target: n.target,
+ }))
+ );
+ }
}
}
- }
- componentResults[component] = {
- storiesAudited: componentStories.length,
- violations: uniqueViolations,
- storyDetails: componentViolations,
- };
+ componentResults[component] = {
+ storiesAudited: componentStories.length,
+ violations: Array.from(violationMap.values()),
+ storyDetails: componentViolations,
+ };
+ }
+ } finally {
+ await browser.close();
+ server.close();
}
- await browser.close();
- server.close();
-
const report = {
components: componentResults,
summary: {
@@ -307,7 +259,7 @@ async function runAccessibilityAudit() {
console.log(`Report written to ${outputFile}`);
}
-runAccessibilityAudit().catch(e => {
+runAccessibilityAudit().catch((e) => {
console.error('Accessibility audit failed:', e);
process.exit(1);
});
diff --git a/.github/scripts/generate-pr-comment.js b/.github/scripts/generate-pr-comment.js
index 99e80e1271..93ea93e772 100644
--- a/.github/scripts/generate-pr-comment.js
+++ b/.github/scripts/generate-pr-comment.js
@@ -7,6 +7,7 @@
*/
const fs = require('fs');
+const { buildA11ySection } = require('./lib/a11y-format');
const args = process.argv.slice(2);
const getArg = (name) => {
@@ -114,26 +115,8 @@ if (analysis.modifiedComponents && analysis.modifiedComponents.length > 0) {
}
}
-// Build accessibility section
-let a11ySection = '### Accessibility Audit\n\n';
-const totalViolations = Object.values(a11yReport.components || {})
- .reduce((sum, comp) => sum + (comp.violations?.length || 0), 0);
-
-if (totalViolations === 0) {
- a11ySection += '**Status:** No accessibility violations detected.\n\n';
-} else {
- a11ySection += `**Status:** ${totalViolations} accessibility violation(s) found.\n\n`;
- for (const [compName, compReport] of Object.entries(a11yReport.components || {})) {
- if (compReport.violations?.length > 0) {
- a11ySection += `<details>\n<summary><strong>${compName}</strong> - ${compReport.violations.length} issue(s)</summary>\n\n`;
- for (const violation of compReport.violations) {
- a11ySection += `- **${violation.impact}**: ${violation.description}\n`;
- a11ySection += ` - Rule: \`${violation.id}\`\n`;
- }
- a11ySection += `\n</details>\n\n`;
- }
- }
-}
+// Build accessibility section using shared module
+const a11ySection = buildA11ySection(a11yReport);
// Build bundle size section
let bundleSection = '### Bundle Size Summary\n\n';
diff --git a/.github/scripts/lib/a11y-format.js b/.github/scripts/lib/a11y-format.js
new file mode 100644
index 0000000000..2776cb4687
--- /dev/null
+++ b/.github/scripts/lib/a11y-format.js
@@ -0,0 +1,106 @@
+/**
+ * Shared a11y formatting utilities for PR enrichment.
+ * Used by generate-pr-comment.js and test-pr-enrichment.js.
+ */
+
+// Impact emoji badges
+const impactEmoji = {
+ critical: '🔴',
+ serious: '🟠',
+ moderate: '🟡',
+ minor: '⚪',
+};
+
+/**
+ * Extract WCAG success criteria from axe tags (e.g., 'wcag412' → '4.1.2', 'wcag1411' → '1.4.11')
+ * WCAG criteria follow X.Y.Z format where Z can be multi-digit.
+ */
+function formatWcagTags(tags) {
+ if (!tags || !Array.isArray(tags)) return '';
+ const wcagCriteria = tags
+ .filter((t) => /^wcag\d{3,4}$/.test(t))
+ .map((t) => {
+ const nums = t.replace('wcag', '');
+ return `${nums[0]}.${nums[1]}.${nums.slice(2)}`;
+ });
+ const level = tags.find((t) => ['wcag2a', 'wcag2aa', 'wcag2aaa'].includes(t));
+ const levelStr = level
+ ? ` (Level ${level.replace('wcag2', '').toUpperCase()})`
+ : '';
+ return wcagCriteria.length > 0
+ ? `WCAG: ${wcagCriteria.join(', ')}${levelStr}`
+ : '';
+}
+
+/**
+ * Build the full accessibility section markdown from an a11y report.
+ * @param {object} a11yReport - The a11y report object with .components
+ * @param {object} [storiesAuditedByComponent] - Optional map of component name → storiesAudited count
+ * @returns {string} Markdown string for the a11y section
+ */
+function buildA11ySection(a11yReport, storiesAuditedByComponent) {
+ let a11ySection = '### Accessibility Audit\n\n';
+ const totalViolations = Object.values(a11yReport.components || {})
+ .reduce((sum, comp) => sum + (comp.violations?.length || 0), 0);
+
+ if (totalViolations === 0) {
+ a11ySection += '**Status:** No accessibility violations detected.\n\n';
+ return a11ySection;
+ }
+
+ // Build impact breakdown for summary line
+ const impactCounts = {};
+ for (const compReport of Object.values(a11yReport.components || {})) {
+ for (const v of compReport.violations || []) {
+ if (v.impact) {
+ impactCounts[v.impact] = (impactCounts[v.impact] || 0) + 1;
+ }
+ }
+ }
+ const impactBreakdown = ['critical', 'serious', 'moderate', 'minor']
+ .filter((level) => impactCounts[level])
+ .map((level) => `${impactCounts[level]} ${level}`)
+ .join(', ');
+ const breakdownStr = impactBreakdown ? ` — ${impactBreakdown}` : '';
+
+ a11ySection += `**Status:** ${totalViolations} accessibility violation(s) found${breakdownStr}.\n\n`;
+
+ for (const [compName, compReport] of Object.entries(a11yReport.components || {})) {
+ if (compReport.violations?.length > 0) {
+ a11ySection += `<details>\n<summary><strong>${compName}</strong> - ${compReport.violations.length} issue(s)</summary>\n\n`;
+ for (const violation of compReport.violations) {
+ const emoji = impactEmoji[violation.impact] || '';
+ const prefix = emoji ? `${emoji} ` : '';
+ a11ySection += `- ${prefix}**${violation.impact}**: ${violation.description}\n`;
+
+ // Build detail line: Rule · story count · learn more
+ const detailParts = [`Rule: \`${violation.id}\``];
+
+ if (violation.storyCount != null && compReport.storiesAudited) {
+ detailParts.push(
+ `Affects ${violation.storyCount}/${compReport.storiesAudited} stories`
+ );
+ }
+
+ if (violation.helpUrl) {
+ detailParts.push(
+ `[Learn more](${violation.helpUrl})`
+ );
+ }
+
+ a11ySection += ` - ${detailParts.join(' · ')}\n`;
+
+ // Show WCAG tags if available
+ const wcagStr = formatWcagTags(violation.tags);
+ if (wcagStr) {
+ a11ySection += ` - ${wcagStr}\n`;
+ }
+ }
+ a11ySection += `\n</details>\n\n`;
+ }
+ }
+
+ return a11ySection;
+}
+
+module.exports = { impactEmoji, formatWcagTags, buildA11ySection };
diff --git a/.github/scripts/test-pr-enrichment.js b/.github/scripts/test-pr-enrichment.js
index cb80fed1b3..b3d8610323 100644
--- a/.github/scripts/test-pr-enrichment.js
+++ b/.github/scripts/test-pr-enrichment.js
@@ -6,6 +6,7 @@
const fs = require('fs');
const path = require('path');
+const { buildA11ySection } = require('./lib/a11y-format');
// Mock analysis data
const mockAnalysis = {
@@ -74,7 +75,7 @@ const mockAnalysis = {
analyzedAt: new Date().toISOString(),
};
-// Mock a11y report
+// Mock a11y report — includes new axe-core fields (helpUrl, tags, storyCount, etc.)
const mockA11y = {
components: {
DatePicker: {
@@ -89,14 +90,57 @@ const mockA11y = {
id: 'label',
impact: 'critical',
description: 'Form elements must have labels',
+ help: 'Form elements must have labels',
+ helpUrl: 'https://dequeuniversity.com/rules/axe/4.10/label',
+ tags: ['cat.forms', 'wcag2a', 'wcag412', 'TTv5', 'TT6.a'],
+ storyCount: 2,
+ totalNodes: 3,
+ stories: ['Default', 'WithSeconds'],
+ nodes: [
+ { html: '<input type="text" class="xds-time-input">', target: ['.xds-time-input'] },
+ ],
+ },
+ {
+ id: 'color-contrast',
+ impact: 'serious',
+ description: 'Elements must meet minimum color contrast ratio thresholds',
+ help: 'Elements must have sufficient color contrast',
+ helpUrl: 'https://dequeuniversity.com/rules/axe/4.10/color-contrast',
+ tags: ['cat.color', 'wcag2aa', 'wcag143'],
+ storyCount: 1,
+ totalNodes: 2,
+ stories: ['Disabled'],
+ nodes: [
+ { html: '<span class="xds-time-label">Hours</span>', target: ['.xds-time-label'] },
+ ],
+ },
+ ],
+ storyDetails: [],
+ },
+ Button: {
+ storiesAudited: 5,
+ violations: [
+ {
+ id: 'button-name',
+ impact: 'critical',
+ description: 'Buttons must have discernible text',
+ help: 'Buttons must have discernible text',
+ helpUrl: 'https://dequeuniversity.com/rules/axe/4.10/button-name',
+ tags: ['cat.name-role-value', 'wcag2a', 'wcag412'],
+ storyCount: 3,
+ totalNodes: 5,
+ stories: ['IconOnly', 'Loading', 'Minimal'],
+ nodes: [
+ { html: '<button class="xds-button">', target: ['.xds-button'] },
+ ],
},
],
storyDetails: [],
},
},
summary: {
- componentsAudited: 2,
- totalViolations: 1,
+ componentsAudited: 3,
+ totalViolations: 4,
auditedAt: new Date().toISOString(),
},
};
@@ -166,26 +210,8 @@ if (analysis.modifiedComponents && analysis.modifiedComponents.length > 0) {
}
}
-// Build accessibility section
-let a11ySection = '### Accessibility Audit\n\n';
-const totalViolations = Object.values(a11yReport.components || {})
- .reduce((sum, comp) => sum + (comp.violations?.length || 0), 0);
-
-if (totalViolations === 0) {
- a11ySection += '**Status:** No accessibility violations detected.\n\n';
-} else {
- a11ySection += `**Status:** ${totalViolations} accessibility violation(s) found.\n\n`;
- for (const [compName, compReport] of Object.entries(a11yReport.components || {})) {
- if (compReport.violations?.length > 0) {
- a11ySection += `<details>\n<summary><strong>${compName}</strong> - ${compReport.violations.length} issue(s)</summary>\n\n`;
- for (const violation of compReport.violations) {
- a11ySection += `- **${violation.impact}**: ${violation.description}\n`;
- a11ySection += ` - Rule: \`${violation.id}\`\n`;
- }
- a11ySection += `\n</details>\n\n`;
- }
- }
-}
+// Build accessibility section using shared module
+const a11ySection = buildA11ySection(a11yReport);
// Build bundle size section
let bundleSection = '### Bundle Size Summary\n\n';
diff --git a/package.json b/package.json
index 197e280d9d..5da21c9c42 100644
--- a/package.json
+++ b/package.json
@@ -30,6 +30,7 @@
"prepare": "husky install"
},
"devDependencies": {
+ "@axe-core/playwright": "^4.11.1",
"@changesets/cli": "^2.27.0",
"@eslint/js": "^9.39.2",
"@playwright/test": "^1.48.0",
diff --git a/yarn.lock b/yarn.lock
index 6c52b23271..6421b69e20 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -52,6 +52,13 @@
resolved "https://registry.yarnpkg.com/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz#ad5549322dfe9d153d4b4dd6f7ff2ae234b06e24"
integrity sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==
+"@axe-core/playwright@^4.11.1":
+ version "4.11.1"
+ resolved "https://registry.yarnpkg.com/@axe-core/playwright/-/playwright-4.11.1.tgz#d6e2b06ddb1b8ff460ca0f6f0bc96f2f03f6d91b"
+ integrity sha512-mKEfoUIB1MkVTht0BGZFXtSAEKXMJoDkyV5YZ9jbBmZCcWDz71tegNsdTkIN8zc/yMi5Gm2kx7Z5YQ9PfWNAWw==
+ dependencies:
+ axe-core "~4.11.1"
+
"@babel/code-frame@^7.10.4", "@babel/code-frame@^7.28.6":
version "7.28.6"
resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.28.6.tgz#72499312ec58b1e2245ba4a4f550c132be4982f7"
@@ -2537,6 +2544,11 @@ available-typed-arrays@^1.0.7:
dependencies:
possible-typed-array-names "^1.0.0"
+axe-core@~4.11.1:
+ version "4.11.1"
+ resolved "https://registry.yarnpkg.com/axe-core/-/axe-core-4.11.1.tgz#052ff9b2cbf543f5595028b583e4763b40c78ea7"
+ integrity sha512-BASOg+YwO2C+346x3LZOeoovTIoTrRqEsqMa6fmfAV0P+U9mFr9NsyOEpiYvFjbc64NMrSswhV50WdXzdb/Z5A==
+
babel-plugin-syntax-hermes-parser@^0.26.0:
version "0.26.0"
resolved "https://registry.yarnpkg.com/babel-plugin-syntax-hermes-parser/-/babel-plugin-syntax-hermes-parser-0.26.0.tgz#eecd9455fbb003dcc1abd28c5ca0b343efd4abac"