# Accessibility (a11y) Guide

This document provides comprehensive accessibility guidelines for the Yemaya
platform. Our goal is to meet WCAG 2.1 Level AA compliance and ensure an
inclusive experience for all users.

## Table of Contents

1. [Overview](#overview)
2. [Standards & Compliance](#standards--compliance)
3. [Keyboard Navigation](#keyboard-navigation)
4. [Screen Reader Support](#screen-reader-support)
5. [Focus Management](#focus-management)
6. [Color & Contrast](#color--contrast)
7. [Motion & Animation](#motion--animation)
8. [ARIA Patterns](#aria-patterns)
9. [Component Guidelines](#component-guidelines)
10. [Testing](#testing)
11. [Development Checklist](#development-checklist)

---

## Overview

Accessibility is a core value of the Yemaya platform. We design and develop with
accessibility in mind from the start, not as an afterthought.

### Key Principles

- **Perceivable**: Information must be presentable in ways users can perceive
- **Operable**: UI components must be operable via keyboard and assistive
  technologies
- **Understandable**: Information and operation must be understandable
- **Robust**: Content must be robust enough for various assistive technologies

---

## Standards & Compliance

### WCAG 2.1 Level AA

We target WCAG 2.1 Level AA compliance, which includes:

- All Level A requirements
- Color contrast ratios of at least 4.5:1 for normal text, 3:1 for large text
- Keyboard focus visibility
- Consistent navigation
- Multiple ways to find content
- Error identification and suggestions

### Screen Reader Testing

Test with at least two screen readers:

- **NVDA** (Windows) - Free, open source
- **VoiceOver** (macOS/iOS) - Built into Apple devices
- **JAWS** (Windows) - Industry standard
- **TalkBack** (Android) - Built into Android

---

## Keyboard Navigation

All interactive elements must be keyboard accessible.

### Keyboard Patterns

Located in: `packages/ui/src/accessibility/keyboard.ts`

```typescript
import { Keys, navigateWithKeyboard, formatShortcut } from '@yemaya/ui';

// Key constants for consistent handling
Keys.Enter; // Enter key
Keys.Space; // Space bar
Keys.Escape; // Escape key
Keys.Tab; // Tab key
Keys.ArrowUp; // Up arrow
Keys.ArrowDown; // Down arrow
Keys.ArrowLeft; // Left arrow
Keys.ArrowRight; // Right arrow
Keys.Home; // Home key
Keys.End; // End key
```

### Focus Order

- Ensure logical tab order (left-to-right, top-to-bottom)
- Group related elements together
- Provide skip links for repetitive content

```typescript
import { SkipToMain, SkipLinks } from '@yemaya/ui';

// Add skip links at the top of your layout
<SkipLinks>
  <SkipToMain />
</SkipLinks>
```

### Keyboard Shortcuts

Document all keyboard shortcuts and provide alternatives:

```typescript
import { formatShortcut } from '@yemaya/ui';

// Display platform-appropriate shortcuts
formatShortcut(['ctrl', 's']); // "Ctrl + S" on Windows, "Cmd + S" on Mac
```

---

## Screen Reader Support

### Live Regions

Use live regions for dynamic content updates:

```typescript
import { announce, announcePolite, announceAssertive } from '@yemaya/ui';

// Polite announcement (waits for screen reader to finish)
announcePolite('Item added to cart');

// Assertive announcement (interrupts current speech)
announceAssertive('Error: Invalid input');

// General announcement with custom politeness
announce('5 results found', 'polite');
```

### Descriptive Labels

Every interactive element needs an accessible name:

```tsx
// Good - explicit label
<button aria-label="Close dialog">
  <CloseIcon />
</button>

// Good - visible text
<button>Close</button>

// Good - associated label
<label htmlFor="email">Email</label>
<input id="email" type="email" />
```

---

## Focus Management

### Focus Trapping

Use focus traps for modals and dialogs:

```typescript
import { focusTrap, getFocusableElements } from '@yemaya/ui';

// Create a focus trap in a modal
const { activate, deactivate } = focusTrap(modalElement);

// Activate when modal opens
activate();

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

### Roving TabIndex

For composite widgets (menus, toolbars, tab lists):

```typescript
import { useRovingTabIndex } from '@yemaya/ui';

function Toolbar() {
  const { getItemProps, setActiveIndex } = useRovingTabIndex({
    items: toolbarItems,
    orientation: 'horizontal',
  });

  return (
    <div role="toolbar">
      {toolbarItems.map((item, index) => (
        <button key={item.id} {...getItemProps(index)}>
          {item.label}
        </button>
      ))}
    </div>
  );
}
```

### Restore Focus

Return focus to trigger element when closing modals:

```typescript
import { useFocusReturn } from '@yemaya/ui';

function Modal({ isOpen, onClose }) {
  useFocusReturn(isOpen);

  // Focus returns to trigger when modal closes
}
```

---

## Color & Contrast

### Contrast Requirements

| Text Type                        | Minimum Ratio | Example           |
| -------------------------------- | ------------- | ----------------- |
| Normal text (<18px)              | 4.5:1         | Body text, labels |
| Large text (>=18px bold, >=24px) | 3:1           | Headings          |
| UI components                    | 3:1           | Buttons, inputs   |
| Graphical objects                | 3:1           | Icons, charts     |

### Checking Contrast

```typescript
import {
  checkContrast,
  suggestBetterContrast,
  getContrastingTextColor,
} from '@yemaya/ui';

// Check if contrast meets WCAG AA
const result = checkContrast('#ffffff', '#767676');
// { ratio: 4.54, passes: { aa: true, aaa: false } }

// Get a better contrasting color suggestion
const betterColor = suggestBetterContrast('#ffffff', '#aaaaaa', 'AA');

// Get contrasting text color for a background
const textColor = getContrastingTextColor('#3b82f6');
// Returns black or white based on background
```

### High Contrast Mode

Support Windows High Contrast Mode and provide a high contrast theme:

```typescript
import { ThemeProvider } from '@yemaya/ui';

// High contrast themes available
<ThemeProvider theme="high-contrast-light">
  <App />
</ThemeProvider>

<ThemeProvider theme="high-contrast-dark">
  <App />
</ThemeProvider>
```

---

## Motion & Animation

### Respecting User Preferences

Always respect `prefers-reduced-motion`:

```typescript
import {
  prefersReducedMotion,
  subscribeToMotionPreference,
  motionStyles,
} from '@yemaya/ui';

// Check current preference
if (prefersReducedMotion()) {
  // Use instant transitions
}

// Subscribe to preference changes
const unsubscribe = subscribeToMotionPreference((reduced) => {
  if (reduced) {
    // Disable animations
  }
});

// CSS helper
const styles = motionStyles({
  normal: { transition: 'transform 0.3s ease' },
  reduced: { transition: 'none' },
});
```

### CSS Implementation

```css
/* Prefer reduced motion */
@media (prefers-reduced-motion: reduce) {
  *,
  *::before,
  *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}
```

---

## ARIA Patterns

### Roles

Common ARIA roles used in Yemaya:

| Role                           | Usage                                     |
| ------------------------------ | ----------------------------------------- |
| `button`                       | Clickable elements that aren't `<button>` |
| `dialog`                       | Modal dialogs                             |
| `alertdialog`                  | Confirmation dialogs                      |
| `menu`                         | Dropdown menus                            |
| `menuitem`                     | Items within menus                        |
| `tab` / `tablist` / `tabpanel` | Tab interfaces                            |
| `tree` / `treeitem`            | Hierarchical lists                        |
| `toolbar`                      | Groups of related buttons                 |
| `tooltip`                      | Tooltip content                           |

### Properties

```tsx
// Required for screen readers
aria-label="Description"        // Provides accessible name
aria-labelledby="heading-id"    // References visible text
aria-describedby="help-text-id" // References descriptive text
aria-hidden="true"              // Hides from screen readers

// State indicators
aria-expanded="true"            // Expandable sections
aria-selected="true"            // Selected items
aria-checked="true"             // Checkboxes
aria-pressed="true"             // Toggle buttons
aria-disabled="true"            // Disabled elements
aria-busy="true"                // Loading states

// Live regions
aria-live="polite"              // Announces when idle
aria-live="assertive"           // Announces immediately
aria-atomic="true"              // Reads entire region
```

---

## Component Guidelines

### Buttons

```tsx
// Icon-only buttons need labels
<Button aria-label="Close" icon={<CloseIcon />} />

// Loading state
<Button aria-busy={isLoading} disabled={isLoading}>
  {isLoading ? 'Saving...' : 'Save'}
</Button>

// Toggle buttons
<Button aria-pressed={isActive} onClick={toggle}>
  Bold
</Button>
```

### Forms

```tsx
// Always associate labels
<div>
  <Label htmlFor="username">Username</Label>
  <Input
    id="username"
    aria-describedby="username-help username-error"
    aria-invalid={hasError}
    aria-required="true"
  />
  <p id="username-help">Choose a unique username</p>
  {hasError && (
    <p id="username-error" role="alert">
      Username is already taken
    </p>
  )}
</div>
```

### Modals

```tsx
<Dialog
  role="dialog"
  aria-modal="true"
  aria-labelledby="dialog-title"
  aria-describedby="dialog-description"
>
  <h2 id="dialog-title">Confirm Delete</h2>
  <p id="dialog-description">Are you sure you want to delete this item?</p>
  <Button>Cancel</Button>
  <Button>Delete</Button>
</Dialog>
```

### Tables

```tsx
<table>
  <caption>User list</caption>
  <thead>
    <tr>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
      <th scope="col">Role</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John Doe</td>
      <td>john@example.com</td>
      <td>Admin</td>
    </tr>
  </tbody>
</table>
```

---

## Testing

### Automated Testing

We use multiple tools for accessibility testing:

1. **vitest-axe** - Unit tests with axe-core
2. **pa11y** - CLI and CI testing
3. **@axe-core/playwright** - E2E accessibility testing
4. **Lighthouse** - Performance and accessibility audits

### Running Tests

```bash
# Run accessibility unit tests
pnpm --filter @yemaya/ui test:a11y

# Run full test suite (includes a11y)
pnpm test
```

### CI Pipeline

The accessibility audit workflow runs on:

- Every PR that modifies UI code
- Weekly scheduled runs
- Manual trigger

Results are posted as PR comments with:

- Violation counts
- WCAG rule references
- Impact levels (critical, serious, moderate, minor)

### Manual Testing Checklist

1. [ ] Navigate entire page using only keyboard
2. [ ] Test with screen reader (VoiceOver/NVDA)
3. [ ] Check with browser zoom at 200%
4. [ ] Test with Windows High Contrast Mode
5. [ ] Verify with prefers-reduced-motion enabled
6. [ ] Test all interactive elements are reachable
7. [ ] Verify focus indicators are visible
8. [ ] Check form error messages are announced

---

## Development Checklist

Use this checklist when developing new components:

### Structure

- [ ] Semantic HTML elements used (`<button>`, `<nav>`, `<main>`, etc.)
- [ ] Heading hierarchy is logical (h1 > h2 > h3)
- [ ] Lists use `<ul>`, `<ol>`, or `<dl>` appropriately
- [ ] Tables have proper structure with `<th>`, `scope`, `<caption>`

### Interactive Elements

- [ ] All interactive elements are keyboard accessible
- [ ] Focus order is logical
- [ ] Focus indicator is visible and sufficient contrast
- [ ] Custom controls have appropriate ARIA roles
- [ ] States are communicated (expanded, selected, disabled)

### Visual Design

- [ ] Color contrast meets requirements (4.5:1 / 3:1)
- [ ] Information is not conveyed by color alone
- [ ] Text can be resized to 200% without loss of content
- [ ] Touch targets are at least 44x44 pixels

### Screen Readers

- [ ] All images have alt text (or `alt=""` for decorative)
- [ ] Form inputs have associated labels
- [ ] Error messages are announced
- [ ] Dynamic content updates use live regions
- [ ] Icons have accessible names

### Motion

- [ ] Animations respect prefers-reduced-motion
- [ ] Auto-playing content can be paused
- [ ] No content flashes more than 3 times per second

---

## Resources

### Tools

- [axe DevTools](https://www.deque.com/axe/devtools/) - Browser extension
- [WAVE](https://wave.webaim.org/) - Web accessibility evaluation
- [Contrast Checker](https://webaim.org/resources/contrastchecker/) - Color
  contrast
- [Accessibility Insights](https://accessibilityinsights.io/) - Microsoft's a11y
  tool

### References

- [WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)
- [WAI-ARIA Authoring Practices](https://www.w3.org/WAI/ARIA/apg/)
- [MDN Accessibility](https://developer.mozilla.org/en-US/docs/Web/Accessibility)
- [A11y Project Checklist](https://www.a11yproject.com/checklist/)

### Internal Resources

- UI Components: `packages/ui/src/components/`
- Accessibility Utilities: `packages/ui/src/accessibility/`
- Component Tests: `packages/ui/src/components/__tests__/`

---

## Getting Help

If you have questions about accessibility:

1. Check this documentation first
2. Review the WAI-ARIA Authoring Practices
3. Ask in the #accessibility Slack channel
4. Open an issue with the `accessibility` label

Remember: Accessibility benefits everyone, not just users with disabilities!
