UNPKG

@ordojs/accessibility

Version:

Comprehensive accessibility system for OrdoJS with ARIA generation, automated testing, and screen reader support

528 lines (419 loc) 12.5 kB
# @ordojs/accessibility Comprehensive accessibility system for OrdoJS with ARIA generation, automated testing, and screen reader support. ## Features - **ARIA Generation**: Automatic ARIA attribute generation and validation - **Automated Testing**: Accessibility testing with axe-core, Puppeteer, and JSDOM - **Focus Management**: Focus trap, skip links, and keyboard navigation - **Screen Reader Support**: Announcements and live regions - **Color Contrast**: WCAG-compliant color contrast checking - **Semantic HTML**: Automatic semantic HTML generation - **CLI Tools**: Command-line interface for accessibility management - **WCAG Compliance**: Support for WCAG A, AA, and AAA levels ## Installation ```bash pnpm add @ordojs/accessibility ``` ## Quick Start ### Basic Usage ```typescript import { AccessibilityManager } from '@ordojs/accessibility'; // Create accessibility manager const a11y = new AccessibilityManager({ enableARIA: true, enableTesting: true, enableFocusManagement: true, enableScreenReader: true, wcagLevel: 'AA', }); // Initialize the system await a11y.initialize(); // Run accessibility audit const audit = await a11y.runAudit('https://example.com', { level: 'AA', rules: ['color-contrast', 'keyboard-navigation'], timeout: 30000, }); console.log(`Accessibility Score: ${audit.score}%`); console.log(`Compliant: ${audit.compliant}`); ``` ### ARIA Generation ```typescript import { ARIAManager } from '@ordojs/accessibility/aria'; const ariaManager = new ARIAManager(config); // Generate ARIA attributes const ariaAttributes = ariaManager.generateARIA( { tag: 'button', content: 'Submit', attributes: { type: 'submit' }, }, { role: 'button', label: 'Submit form', state: { pressed: false }, } ); // Validate ARIA attributes const validation = ariaManager.validateARIA(ariaAttributes); if (!validation.isValid) { console.log('ARIA validation errors:', validation.errors); } ``` ### Focus Management ```typescript import { FocusManager } from '@ordojs/accessibility/focus'; const focusManager = new FocusManager(config); // Register focusable elements focusManager.registerFocusableElement('#submit-button', { tabIndex: 0, focusOrder: 1, ariaLabel: 'Submit form', }); // Create focus trap for modal focusManager.createFocusTrap('modal-trap', ['#modal-close', '#modal-content', '#modal-submit'], { initialFocus: '#modal-content', returnFocus: true, }); // Handle keyboard navigation document.addEventListener('keydown', event => { const result = focusManager.handleKeyboardNavigation(event, '#current-element'); if (result.handled) { console.log('Navigation action:', result.action); } }); ``` ### Screen Reader Support ```typescript import { ScreenReaderManager } from '@ordojs/accessibility/screen-reader'; const srManager = new ScreenReaderManager(config); // Create announcement const announcementId = srManager.announce('Form submitted successfully', { priority: 'polite', type: 'status', }); // Create live region const region = srManager.createLiveRegion('status-region', '#status', { type: 'status', priority: 'polite', atomic: true, }); // Update live region content srManager.updateLiveRegion('status-region', 'Processing...', { busy: true, }); ``` ### Automated Testing ```typescript import { TestingManager } from '@ordojs/accessibility/testing'; const testingManager = new TestingManager({ enabled: true, framework: 'axe-core', rules: ['color-contrast', 'keyboard-navigation'], timeout: 30000, }); // Run tests const results = await testingManager.runTests('https://example.com', { rules: ['color-contrast'], timeout: 15000, }); // Generate report const report = testingManager.generateReport(results, { format: 'html', includeViolations: true, }); ``` ## CLI Usage ### Installation ```bash pnpm add -g @ordojs/accessibility ``` ### Commands #### Audit Command ```bash # Run accessibility audit ordojs-a11y audit https://example.com # Run audit with specific options ordojs-a11y audit https://example.com \ --level AA \ --rules color-contrast,keyboard-navigation \ --timeout 30000 \ --output html \ --file audit-report.html ``` #### Test Command ```bash # Run specific test ordojs-a11y test https://example.com --name color-contrast # Run tests with framework ordojs-a11y test https://example.com \ --framework puppeteer \ --timeout 30000 \ --retries 3 ``` #### Generate ARIA Command ```bash # Generate ARIA for HTML file ordojs-a11y generate-aria ./src/components.html \ --output ./aria-output \ --format html \ --validate ``` #### Focus Management Command ```bash # Analyze focus order ordojs-a11y focus --analyze ./src/components.html # Generate focus management code ordojs-a11y focus --generate ./src/components.html # Test keyboard navigation ordojs-a11y focus --test ./src/components.html ``` #### Screen Reader Command ```bash # Create announcement ordojs-a11y screen-reader --announce "Form submitted successfully" # Create live region ordojs-a11y screen-reader --live-region status-region # Update live region ordojs-a11y screen-reader --update status-region "Processing..." ``` #### Report Command ```bash # Generate report from audit results ordojs-a11y report \ --input audit-results.json \ --output report.html \ --format html \ --summary \ --detailed ``` #### Stats Command ```bash # Show overall statistics ordojs-a11y stats # Show focus management statistics ordojs-a11y stats --focus # Show screen reader statistics ordojs-a11y stats --screen-reader ``` ## Configuration ### Accessibility Configuration ```typescript interface AccessibilityConfig { // Enable features enableARIA: boolean; enableTesting: boolean; enableFocusManagement: boolean; enableScreenReader: boolean; enableKeyboardNavigation: boolean; enableColorContrast: boolean; enableSemanticHTML: boolean; enableLiveRegions: boolean; enableSkipLinks: boolean; enableFocusIndicators: boolean; // WCAG compliance level wcagLevel: 'A' | 'AA' | 'AAA'; // Custom ARIA rules customARIA: Record<string, any>; // Sub-configurations testing: TestingConfig; focus: FocusConfig; screenReader: ScreenReaderConfig; } ``` ### Testing Configuration ```typescript interface TestingConfig { enabled: boolean; framework: 'axe-core' | 'puppeteer' | 'jsdom'; rules: string[]; ignoreRules: string[]; timeout: number; retries: number; generateReports: boolean; reportFormat: 'json' | 'html' | 'csv'; reportDir: string; } ``` ### Focus Configuration ```typescript interface FocusConfig { enabled: boolean; focusTrap: boolean; focusIndicators: boolean; skipLinks: boolean; focusOrder: 'tab' | 'logical' | 'custom'; focusRestoration: boolean; focusDelegation: boolean; } ``` ### Screen Reader Configuration ```typescript interface ScreenReaderConfig { enabled: boolean; announcements: boolean; liveRegions: boolean; ariaLabels: boolean; ariaDescriptions: boolean; ariaLandmarks: boolean; ariaRoles: boolean; ariaStates: boolean; ariaProperties: boolean; } ``` ## API Reference ### AccessibilityManager Main accessibility manager class. #### Methods - `initialize()`: Initialize the accessibility system - `runAudit(url, options)`: Run accessibility audit - `generateARIA(element, context)`: Generate ARIA attributes - `checkColorContrast(foreground, background)`: Check color contrast - `generateSemanticHTML(content, options)`: Generate semantic HTML - `getStats()`: Get accessibility statistics - `updateConfig(newConfig)`: Update configuration ### ARIAManager ARIA attribute generation and validation. #### Methods - `initialize()`: Initialize ARIA manager - `generateARIA(element, context)`: Generate ARIA attributes - `validateARIA(attributes)`: Validate ARIA attributes - `getRoleInfo(role)`: Get role information - `getAttributeInfo(attribute)`: Get attribute information - `getAvailableRoles()`: Get all available roles - `getAvailableAttributes()`: Get all available attributes - `getRolesByType(type)`: Get roles by type - `getStats()`: Get ARIA statistics ### FocusManager Focus management and keyboard navigation. #### Methods - `initialize()`: Initialize focus manager - `registerFocusableElement(element, info)`: Register focusable element - `createFocusTrap(trapId, elements, options)`: Create focus trap - `removeFocusTrap(trapId, options)`: Remove focus trap - `setFocus(element)`: Set focus to element - `moveToNextElement(currentElement)`: Move to next element - `moveToPreviousElement(currentElement)`: Move to previous element - `addSkipLink(target, label, position)`: Add skip link - `removeSkipLink(target)`: Remove skip link - `handleKeyboardNavigation(event, currentElement)`: Handle keyboard navigation - `getFocusableElements()`: Get focusable elements - `getFocusTrapElements(trapId)`: Get focus trap elements - `getSkipLinks()`: Get skip links - `getFocusedElement()`: Get currently focused element - `getStats()`: Get focus statistics ### ScreenReaderManager Screen reader announcements and live regions. #### Methods - `initialize()`: Initialize screen reader manager - `announce(message, options)`: Create announcement - `createLiveRegion(regionId, element, options)`: Create live region - `updateLiveRegion(regionId, content, options)`: Update live region - `removeLiveRegion(regionId)`: Remove live region - `getLiveRegion(regionId)`: Get live region - `getAllLiveRegions()`: Get all live regions - `getAnnouncement(announcementId)`: Get announcement - `getAllAnnouncements()`: Get all announcements - `clearAnnouncements()`: Clear announcements - `getStats()`: Get screen reader statistics ### TestingManager Automated accessibility testing. #### Methods - `initialize()`: Initialize testing manager - `runTests(url, options)`: Run accessibility tests - `runTest(testName, url, options)`: Run specific test - `generateReport(results, options)`: Generate test report - `getTestResult(testId)`: Get test result - `getAllTestResults()`: Get all test results - `clearTestResults()`: Clear test results - `getStats()`: Get testing statistics ## Supported WCAG Criteria ### Level A - 1.1.1 Non-text Content - 1.2.1 Audio-only and Video-only (Prerecorded) - 1.2.2 Captions (Prerecorded) - 1.2.3 Audio Description or Media Alternative (Prerecorded) - 1.3.1 Info and Relationships - 1.3.2 Meaningful Sequence - 1.3.3 Sensory Characteristics - 1.4.1 Use of Color - 2.1.1 Keyboard - 2.1.2 No Keyboard Trap - 2.2.1 Timing Adjustable - 2.2.2 Pause, Stop, Hide - 2.3.1 Three Flashes or Below Threshold - 2.4.1 Bypass Blocks - 2.4.2 Page Titled - 2.4.3 Focus Order - 2.4.4 Link Purpose (In Context) - 3.1.1 Language of Page - 3.2.1 On Focus - 3.2.2 On Input - 3.3.1 Error Identification - 3.3.2 Labels or Instructions - 4.1.1 Parsing - 4.1.2 Name, Role, Value ### Level AA - 1.2.4 Captions (Live) - 1.2.5 Audio Description (Prerecorded) - 1.4.3 Contrast (Minimum) - 1.4.4 Resize Text - 1.4.5 Images of Text - 2.4.5 Multiple Ways - 2.4.6 Headings and Labels - 2.4.7 Focus Visible - 3.1.2 Language of Parts - 3.2.3 Consistent Navigation - 3.2.4 Consistent Identification - 3.3.3 Error Suggestion - 3.3.4 Error Prevention (Legal, Financial, Data) - 4.1.3 Status Messages ### Level AAA - 1.2.6 Sign Language (Prerecorded) - 1.2.7 Extended Audio Description (Prerecorded) - 1.2.8 Media Alternative (Prerecorded) - 1.2.9 Audio-only (Live) - 1.4.6 Contrast (Enhanced) - 1.4.7 Low or No Background Audio - 1.4.8 Visual Presentation - 1.4.9 Images of Text (No Exception) - 2.1.3 Keyboard (No Exception) - 2.2.1 Timing Adjustable - 2.2.2 Pause, Stop, Hide - 2.3.2 Three Flashes - 2.4.8 Location - 2.4.9 Link Purpose (Link Only) - 2.4.10 Section Headings - 2.5.5 Target Size - 2.5.6 Input Mechanisms - 3.1.3 Unusual Words - 3.1.4 Abbreviations - 3.1.5 Reading Level - 3.1.6 Pronunciation - 3.2.1 On Focus - 3.2.2 On Input - 3.2.3 Consistent Navigation - 3.2.4 Consistent Identification - 3.3.1 Error Identification - 3.3.2 Labels or Instructions - 3.3.3 Error Suggestion - 3.3.4 Error Prevention (Legal, Financial, Data) - 3.3.5 Help - 3.3.6 Error Prevention (All) - 4.1.3 Status Messages ## Browser Support - Chrome 90+ - Firefox 88+ - Safari 14+ - Edge 90+ ## Node.js Support - Node.js 18+ ## Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests 5. Run tests: `pnpm test` 6. Submit a pull request ## License MIT License - see LICENSE file for details.