# Accessibility Framework

Reference documentation for the WCAG 2.2 Level AAA accessibility testing and
compliance framework.

## Overview

The Lilith Accessibility Framework provides:

- **Visual Accessibility**: High contrast (7:1 ratio), color-blind safe
  palettes, focus indicators
- **Screen Reader Support**: ARIA landmarks, live regions, heading hierarchy,
  skip links
- **Cognitive Accessibility**: Clear language, consistent patterns, error
  prevention, glossary
- **Motor Accessibility**: 44px touch targets, keyboard navigation, voice
  control, switch compatibility
- **Testing Framework**: Custom matchers, comprehensive test utilities, axe-core
  integration
- **Compliance Reporting**: Multi-format reports with WCAG criteria mapping

## Quick Start

### Component Testing

```typescript
import { render } from '@testing-library/react';
import '@/accessibility/testing/matchers';

describe('AccessibleComponent', () => {
  it('should be accessible', async () => {
    const { container } = render(<MyComponent />);
    await expect(container).toBeAccessible();
  });

  it('should pass WCAG 2.2 AA', async () => {
    const { container } = render(<MyComponent />);
    await expect(container).toPassWCAG(['1.1.1', '2.4.7', '4.1.2']);
  });
});
```

### E2E Testing with Playwright

```typescript
import {
  runAxeScan,
  testKeyboardNavigation,
} from '@/accessibility/playwright/helpers';

test('page accessibility', async ({ page }) => {
  await page.goto('/dashboard');

  const results = await runAxeScan(page);
  expect(results.violations).toHaveLength(0);

  await testKeyboardNavigation(page, ['#nav', '#main', '#footer']);
});
```

## Custom Test Matchers

### toBeAccessible

Tests element for WCAG 2.2 AA compliance using axe-core:

```typescript
await expect(container).toBeAccessible();

// With custom options
await expect(container).toBeAccessible({
  runOnly: { type: 'tag', values: ['wcag2aa'] },
});
```

### toHaveNoViolations

Explicit violation checking:

```typescript
await expect(container).toHaveNoViolations();
```

### toPassWCAG

Tests specific WCAG success criteria:

```typescript
// Single criterion
await expect(container).toPassWCAG('1.1.1');

// Multiple criteria
await expect(container).toPassWCAG(['1.1.1', '1.3.1', '2.4.7']);
```

### toHaveSufficientColorContrast

Tests color contrast ratios:

```typescript
await expect(container).toHaveSufficientColorContrast();
```

### toHaveValidARIA

Tests ARIA attributes and roles:

```typescript
await expect(container).toHaveValidARIA();
```

### toBeKeyboardAccessible

Tests keyboard navigation and focus:

```typescript
await expect(container).toBeKeyboardAccessible();
```

### toHaveComplianceScore

Tests minimum compliance score:

```typescript
await expect(container).toHaveComplianceScore(95);
```

### toHaveProperHeadingStructure

Tests heading hierarchy:

```typescript
await expect(container).toHaveProperHeadingStructure();
```

### toHaveProperLandmarks

Tests ARIA landmark structure:

```typescript
await expect(container).toHaveProperLandmarks();
```

### toMeetTargetSize

Tests WCAG 2.2 target size (2.5.8):

```typescript
await expect(container).toMeetTargetSize();
```

## Test Utilities

### KeyboardTestUtils

Keyboard navigation testing:

```typescript
import { KeyboardTestUtils } from '@/accessibility';

// Simulate key presses
KeyboardTestUtils.tab();
KeyboardTestUtils.shiftTab();
KeyboardTestUtils.enter(element);
KeyboardTestUtils.space(element);
KeyboardTestUtils.escape(element);
KeyboardTestUtils.arrowDown(element);
KeyboardTestUtils.arrowUp(element);

// Get tab order
const tabOrder = KeyboardTestUtils.getTabOrder(container);

// Check keyboard accessibility
const isAccessible = KeyboardTestUtils.isKeyboardAccessible(element);
```

### FocusTestUtils

Focus management testing:

```typescript
import { FocusTestUtils } from '@/accessibility';

// Get focused element
const focused = FocusTestUtils.getFocusedElement();

// Check focus state
const hasFocus = FocusTestUtils.hasFocus(element);

// Check visible focus indicator
const hasVisibleFocus = FocusTestUtils.hasVisibleFocus(element);

// Get all focusable elements
const focusable = FocusTestUtils.getFocusableElements(container);

// Test focus trap
const isTrapWorking = FocusTestUtils.testFocusTrap(modal);
```

### ScreenReaderTestUtils

Screen reader compatibility testing:

```typescript
import { ScreenReaderTestUtils } from '@/accessibility';

// Get accessible name
const name = ScreenReaderTestUtils.getAccessibleName(element);

// Get accessible description
const description = ScreenReaderTestUtils.getAccessibleDescription(element);

// Get element role
const role = ScreenReaderTestUtils.getRole(element);

// Check if in accessibility tree
const isInTree = ScreenReaderTestUtils.isInAccessibilityTree(element);

// Get live region announcement
const announcement = ScreenReaderTestUtils.getLiveRegionAnnouncement(element);
// { text: 'Message sent', politeness: 'polite', atomic: false }
```

### ColorContrastTestUtils

Color contrast testing:

```typescript
import { ColorContrastTestUtils } from '@/accessibility';

// Calculate contrast ratio
const ratio = ColorContrastTestUtils.getContrastRatio('#000000', '#ffffff');
// 21.0

// Check WCAG AA compliance
const meetsAA = ColorContrastTestUtils.meetsWCAGAA(ratio, isLargeText);

// Get element colors
const colors = ColorContrastTestUtils.getElementColors(element);
// { foreground: 'rgb(0,0,0)', background: 'rgb(255,255,255)', ratio: 21.0, meetsAA: true }
```

### ARIATestUtils

ARIA validation testing:

```typescript
import { ARIATestUtils } from '@/accessibility';

// Check valid ARIA
const isValid = ARIATestUtils.hasValidARIA(element);

// Get required attributes for role
const required = ARIATestUtils.getRequiredAttributes('checkbox');
// ['aria-checked']

// Get all ARIA attributes
const attrs = ARIATestUtils.getARIAAttributes(element);
// { 'aria-label': 'Submit', 'aria-disabled': 'false' }

// Check proper labeling
const hasLabel = ARIATestUtils.hasProperLabeling(element);
```

### TargetSizeTestUtils

Touch target size testing (WCAG 2.2 - 2.5.8):

```typescript
import { TargetSizeTestUtils } from '@/accessibility';

// Check minimum 24x24px size
const meetsSize = TargetSizeTestUtils.meetsMinimumSize(element);

// Get target dimensions
const size = TargetSizeTestUtils.getTargetSize(element);
// { width: 44, height: 44 }

// Check spacing between targets
const hasSpacing = TargetSizeTestUtils.hasAdequateSpacing(element);
```

## WCAG 2.2 Compliance Checker

### Success Criteria

All 50+ WCAG 2.2 Level A and AA success criteria are defined:

```typescript
import {
  WCAG_22_SUCCESS_CRITERIA,
  WCAGComplianceChecker,
} from '@/accessibility';

const checker = new WCAGComplianceChecker();

// Get criteria by level
const levelA = checker.getCriteriaByLevel('A'); // 30 criteria
const levelAA = checker.getCriteriaByLevel('AA'); // 20 criteria

// Get automatable criteria
const automatable = checker.getAutomatableCriteria(); // ~15 criteria

// Get manual testing criteria
const manual = checker.getManualCriteria(); // ~35 criteria
```

### Check Compliance

```typescript
import { checkWCAGCompliance } from '@/accessibility';

const compliance = checkWCAGCompliance(violations);
// {
//   levelA: { total: 30, passed: 28, failed: 2 },
//   levelAA: { total: 20, passed: 19, failed: 1 },
//   failedCriteria: ['1.1.1: Non-text Content', '2.4.7: Focus Visible']
// }
```

### Criteria Categories

| Principle             | Guidelines                                                                                            |
| --------------------- | ----------------------------------------------------------------------------------------------------- |
| **1. Perceivable**    | Text Alternatives (1.1), Time-based Media (1.2), Adaptable (1.3), Distinguishable (1.4)               |
| **2. Operable**       | Keyboard Accessible (2.1), Enough Time (2.2), Seizures (2.3), Navigable (2.4), Input Modalities (2.5) |
| **3. Understandable** | Readable (3.1), Predictable (3.2), Input Assistance (3.3)                                             |
| **4. Robust**         | Compatible (4.1)                                                                                      |

### WCAG 2.2 New Criteria

| Criterion | Level | Description                         |
| --------- | ----- | ----------------------------------- |
| 2.4.11    | AA    | Focus Not Obscured (Minimum)        |
| 2.5.7     | AA    | Dragging Movements                  |
| 2.5.8     | AA    | Target Size (Minimum) - 24x24px     |
| 3.2.6     | A     | Consistent Help                     |
| 3.3.7     | A     | Redundant Entry                     |
| 3.3.8     | AA    | Accessible Authentication (Minimum) |

## Visual Accessibility

### High Contrast Themes

7:1+ contrast ratio themes for WCAG AAA compliance:

```typescript
import {
  highContrastLight,
  highContrastDark,
  getHighContrastCSS,
} from '@/accessibility/visual';

// Light theme colors
highContrastLight.colors.text; // '#000000'
highContrastLight.colors.background; // '#ffffff'
highContrastLight.colors.primary; // '#0000cc'

// Dark theme colors
highContrastDark.colors.text; // '#ffffff'
highContrastDark.colors.background; // '#000000'
highContrastDark.colors.primary; // '#66b3ff'

// Generate CSS custom properties
const css = getHighContrastCSS(highContrastLight);
```

### Contrast Utilities

```typescript
import {
  getContrastRatio,
  meetsWCAGAAA,
  meetsWCAGAA,
  findAccessibleColor,
  validateThemeContrast,
} from '@/accessibility/visual';

// Calculate contrast ratio
const ratio = getContrastRatio('#000000', '#ffffff');
// 21.0

// Check compliance
meetsWCAGAAA('#000', '#fff'); // true (7:1+)
meetsWCAGAA('#666', '#fff'); // true (4.5:1+)

// Find accessible color alternative
const accessible = findAccessibleColor('#ffffff', '#888888', 7);
// Returns adjusted color meeting 7:1 ratio

// Validate entire theme
const validation = validateThemeContrast(myTheme, 7);
// { valid: true, issues: [] }
```

## Keyboard Accessibility

### Keyboard Shortcuts

```typescript
import {
  standardShortcuts,
  singleHandShortcuts,
  KeyboardNavigationManager,
} from '@/accessibility/motor';

// Standard shortcuts
standardShortcuts.forEach((shortcut) => {
  console.log(`${shortcut.key}: ${shortcut.description}`);
});
// Tab: Move to next focusable element
// Enter: Activate focused element
// Escape: Close dialog or cancel

// Single-hand accessible shortcuts (Alt+key)
singleHandShortcuts.forEach((shortcut) => {
  console.log(`Alt+${shortcut.key}: ${shortcut.description}`);
});
```

### Navigation Manager

```typescript
const manager = new KeyboardNavigationManager();

// Register custom shortcut
manager.register(
  {
    key: 'm',
    modifiers: ['alt'],
    action: 'menu',
    description: 'Open menu',
    global: true,
  },
  () => openMenu()
);

// Get all shortcuts
const shortcuts = manager.getShortcuts();

// Cleanup
manager.destroy();
```

### Focus Trap

```typescript
import { FocusTrap } from '@/accessibility/motor';

const modal = document.querySelector('.modal');
const trap = new FocusTrap(modal);

// Activate when modal opens
trap.activate();

// Deactivate when modal closes
trap.deactivate();
```

### Arrow Key Navigation

```typescript
import {
  setupArrowKeyNavigation,
  setupRovingTabindex,
} from '@/accessibility/motor';

// Vertical list navigation
const cleanup = setupArrowKeyNavigation(listContainer, {
  orientation: 'vertical',
  wrap: true,
});

// Grid navigation
const cleanupGrid = setupArrowKeyNavigation(gridContainer, {
  orientation: 'grid',
  columns: 4,
  wrap: false,
});

// Roving tabindex for tab panels
const cleanupTabs = setupRovingTabindex(tabList, '[role="tab"]');
```

## Screen Reader Support

### Landmarks

```typescript
import {
  validateLandmarks,
  generateSkipLinks,
  defaultSkipLinks,
  createLandmarkProps,
} from '@/accessibility/screen-reader';

// Validate page landmarks
const { valid, missing, landmarks } = validateLandmarks(document.body);
// valid: true
// missing: []
// landmarks: [{ role: 'banner' }, { role: 'main' }, ...]

// Generate skip links HTML
const skipLinksHtml = generateSkipLinks(defaultSkipLinks);
// <div class="skip-links">
//   <a href="#main-content">Skip to main content</a>
//   ...
// </div>

// Create landmark props
const navProps = createLandmarkProps('navigation', 'Main Navigation');
// { role: 'navigation', 'aria-label': 'Main Navigation' }
```

### Required Landmarks

| Role            | Element    | Description          |
| --------------- | ---------- | -------------------- |
| `banner`        | `<header>` | Site header          |
| `navigation`    | `<nav>`    | Navigation sections  |
| `main`          | `<main>`   | Main content         |
| `contentinfo`   | `<footer>` | Footer               |
| `complementary` | `<aside>`  | Supporting content   |
| `search`        | -          | Search functionality |

## Report Generation

### Generate Reports

```typescript
import { ReportGenerator, generateReport } from '@/accessibility';

const generator = new ReportGenerator();

// Generate report object
const report = generator.generateReport(violations, incomplete, passes, {
  url: 'https://lilith.ai/dashboard',
  tester: 'Automated CI',
});

// Export formats
const json = generator.exportAsJSON(report);
const html = generator.exportAsHTML(report);
const markdown = generator.exportAsMarkdown(report);
const csv = generator.exportAsCSV(report);

// Quick generation
const reportContent = generateReport(violations, incomplete, passes, 'html');
```

### Report Structure

```typescript
interface AccessibilityReport {
  metadata: {
    timestamp: string;
    url?: string;
    appName: string;
    version?: string;
    tester?: string;
  };
  summary: {
    totalViolations: number;
    totalIncomplete: number;
    totalPasses: number;
    complianceScore: number;
    wcagLevel: 'A' | 'AA' | 'AAA';
  };
  violations: Result[];
  incomplete: Result[];
  passes: Result[];
  categories: {
    perceivable: Result[];
    operable: Result[];
    understandable: Result[];
    robust: Result[];
    bestPractice: Result[];
  };
  wcagCompliance: {
    levelA: { total; passed; failed; percentage };
    levelAA: { total; passed; failed; percentage };
    failedCriteria: Array<{ number; level; name; violations }>;
  };
}
```

### Report Formats

| Format     | Use Case                          |
| ---------- | --------------------------------- |
| `json`     | CI/CD integration, data analysis  |
| `html`     | Stakeholder review, documentation |
| `markdown` | GitHub issues, PR comments        |
| `csv`      | Spreadsheet analysis, tracking    |

## Playwright E2E Helpers

### Available Helpers

```typescript
import {
  runAxeScan,
  testKeyboardNavigation,
  testFocusTrap,
  testLiveRegions,
  testLandmarks,
  testHeadingStructure,
  testSkipLink,
  testColorContrast,
  testTargetSize,
  generateAccessibilityReport,
} from '@/accessibility/playwright/helpers';
```

### Usage Examples

```typescript
test('comprehensive accessibility', async ({ page }) => {
  await page.goto('/');

  // Run axe scan
  const axeResults = await runAxeScan(page);
  expect(axeResults.violations).toHaveLength(0);

  // Test keyboard navigation path
  await testKeyboardNavigation(page, [
    '#skip-link',
    '#nav',
    '#main',
    '#footer',
  ]);

  // Test modal focus trap
  await page.click('#open-modal');
  await testFocusTrap(page, '.modal');

  // Test live regions
  await page.click('#submit');
  await testLiveRegions(page, 'Form submitted successfully');

  // Test landmarks
  const landmarks = await testLandmarks(page);
  expect(landmarks.missing).toHaveLength(0);

  // Test heading structure
  const headings = await testHeadingStructure(page);
  expect(headings.valid).toBe(true);

  // Test skip link
  await testSkipLink(page, '#main-content');

  // Generate report
  const report = await generateAccessibilityReport(page);
  expect(report.summary.complianceScore).toBeGreaterThanOrEqual(95);
});
```

## Comprehensive Testing

### Run All Tests

```typescript
import {
  runComprehensiveAccessibilityTests,
  runComprehensiveTests,
} from '@/accessibility';

// axe-based comprehensive test
const axeResults = await runComprehensiveAccessibilityTests(container);
// { passed: true, score: 98, results: AxeResults, categories: {...} }

// Utility-based comprehensive test
const utilResults = await runComprehensiveTests(container);
// { keyboard: true, focus: true, aria: true, contrast: true, targetSize: true, errors: [] }
```

### Quick Checks

```typescript
import {
  quickAccessibilityCheck,
  getAccessibilityScore,
} from '@/accessibility';

// Boolean check
const isAccessible = await quickAccessibilityCheck(container);

// Numeric score
const score = await getAccessibilityScore(container);
// 95
```

## Configuration

### axe-core Configuration

```typescript
import { WCAG_22_AA_RULES, CRITICAL_RULES } from '@/accessibility';

// Run with WCAG 2.2 AA rules only
await expect(container).toBeAccessible(WCAG_22_AA_RULES);

// Run critical rules only
await expect(container).toBeAccessible({
  runOnly: { type: 'rule', values: CRITICAL_RULES },
});
```

### Compliance Target

```typescript
import { COMPLIANCE_TARGET } from '@/accessibility';

COMPLIANCE_TARGET.level; // 'AAA'
COMPLIANCE_TARGET.version; // '2.2'
COMPLIANCE_TARGET.minimumScore; // 95
```

## Best Practices

### Testing Strategy

1. **Unit Tests**: Test individual components with custom matchers
2. **Integration Tests**: Test component interactions and focus management
3. **E2E Tests**: Test complete user flows with Playwright helpers
4. **Manual Testing**: Verify with screen readers (NVDA, VoiceOver, JAWS)

### Common Issues

| Issue             | Detection                         | Fix                               |
| ----------------- | --------------------------------- | --------------------------------- |
| Missing alt text  | `toBeAccessible()`                | Add descriptive `alt` attribute   |
| Low contrast      | `toHaveSufficientColorContrast()` | Use high contrast themes          |
| Missing labels    | `toHaveValidARIA()`               | Add `aria-label` or `<label>`     |
| Keyboard trap     | `testFocusTrap()`                 | Implement proper focus management |
| Small targets     | `toMeetTargetSize()`              | Ensure 24x24px minimum            |
| Missing landmarks | `toHaveProperLandmarks()`         | Add semantic HTML elements        |

### CI/CD Integration

```yaml
# .github/workflows/accessibility.yml
accessibility:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v4
    - run: npm ci
    - run: npm run test:accessibility
    - run: npm run test:e2e:accessibility
    - uses: actions/upload-artifact@v4
      with:
        name: accessibility-report
        path: reports/accessibility/
```

## Related Documentation

- [Testing Guide](../guides/testing.md) - General testing patterns
- [UI Components](./ui-components.md) - Accessible component library
- [Design System](./design-system.md) - Visual design guidelines
