|
| 1 | +import type { DevToolsLogLevel } from '@vitejs/devtools-kit' |
| 2 | +import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client' |
| 3 | +import axe from 'axe-core' |
| 4 | + |
| 5 | +const SOURCE = 'a11y-checker' |
| 6 | + |
| 7 | +function impactToLevel(impact: string | undefined | null): DevToolsLogLevel { |
| 8 | + switch (impact) { |
| 9 | + case 'critical': |
| 10 | + case 'serious': |
| 11 | + return 'error' |
| 12 | + case 'moderate': |
| 13 | + return 'warn' |
| 14 | + case 'minor': |
| 15 | + default: |
| 16 | + return 'info' |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +async function runA11yCheck(): Promise<void> { |
| 21 | + const rpc = await getDevToolsRpcClient() |
| 22 | + |
| 23 | + try { |
| 24 | + const results = await axe.run(document) |
| 25 | + |
| 26 | + for (const violation of results.violations) { |
| 27 | + const level = impactToLevel(violation.impact) |
| 28 | + const firstNode = violation.nodes[0] |
| 29 | + |
| 30 | + await rpc.call('devtoolskit:internal:logs:add', { |
| 31 | + message: violation.description, |
| 32 | + level, |
| 33 | + description: `${violation.help}\n\n${violation.helpUrl}`, |
| 34 | + category: 'a11y', |
| 35 | + labels: violation.tags.filter(t => t.startsWith('wcag') || t.startsWith('best-practice')), |
| 36 | + elementPosition: firstNode |
| 37 | + ? { |
| 38 | + selector: firstNode.target.join(' '), |
| 39 | + description: firstNode.html, |
| 40 | + } |
| 41 | + : undefined, |
| 42 | + }, SOURCE) |
| 43 | + } |
| 44 | + |
| 45 | + const violationCount = results.violations.length |
| 46 | + const passCount = results.passes.length |
| 47 | + |
| 48 | + await rpc.call('devtoolskit:internal:logs:add', { |
| 49 | + message: violationCount > 0 |
| 50 | + ? `Found ${violationCount} violation${violationCount > 1 ? 's' : ''}, ${passCount} passed` |
| 51 | + : `All ${passCount} checks passed`, |
| 52 | + level: (violationCount > 0 ? 'warn' : 'success') as DevToolsLogLevel, |
| 53 | + category: 'a11y', |
| 54 | + notify: true, |
| 55 | + autoDismiss: 4000, |
| 56 | + }, SOURCE) |
| 57 | + } |
| 58 | + catch (err) { |
| 59 | + await rpc.call('devtoolskit:internal:logs:add', { |
| 60 | + message: 'A11y audit failed', |
| 61 | + level: 'error' as DevToolsLogLevel, |
| 62 | + description: String(err), |
| 63 | + category: 'a11y', |
| 64 | + notify: true, |
| 65 | + }, SOURCE) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// Auto-execute after page load |
| 70 | +if (document.readyState === 'complete') { |
| 71 | + runA11yCheck() |
| 72 | +} |
| 73 | +else { |
| 74 | + window.addEventListener('load', () => runA11yCheck()) |
| 75 | +} |
0 commit comments