Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions docs/plans/2026-11-07-issue-4-keyboard-screen-reader-a11y.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Plan: Layer toggles, stress slider, and feature popup are not keyboard or screen reader accessible (issue #4)

Risk tier: Medium. Stateful UI interaction (focus management, keyboard events) that unit tests cover only in jsdom, and it alters existing behavior (popup now takes focus, Escape closes it). Changes are confined to two components, their tests, and one stylesheet, with no API or store contract change.

Domain skills:
- superpowers:test-driven-development: invoke.
- chrome-devtools-mcp:a11y-debugging: invoke for the live drive (accessibility tree, focus, Tab order).
- vercel-react-best-practices: not applicable because no data fetching, bundle, or render performance work; one small focus effect only.
- frontend-design: not applicable because no new visual design; only focus indicators matching the existing accent token.
- dataviz, django, fastapi, expo, payments, email: not applicable because none of that is touched.

## Acceptance criteria

1. Every layer toggle (Airports, Sea Ports, and Heatmap when supported), the stress slider, and the popup close button are in the Tab order and operable from the keyboard: Space toggles a layer checkbox, arrow keys move the slider, Enter and Space activate the close button.
2. Each of those controls, and the popup dialog itself, shows a visible `:focus-visible` indicator (2px solid outline in `var(--accent)`, not clipped or covered by its container) that meets WCAG 2.4.7 and 2.4.11. `.stress-slider` no longer removes the focus indicator without replacement.
3. Accessible names and roles: each layer toggle is a native checkbox named "<Label> layer" (for example "Airports layer", "Sea Ports layer", "Heatmap layer") with its checked state; the slider is named "Stress test point count" and has `aria-valuetext` like "500,000 points"; the popup has `role="dialog"` with `aria-labelledby` pointing at its title; the close button is named "Close" (capitalized) and its glyph is hidden from assistive technology.
4. When the popup opens, focus moves to the dialog. Escape closes it (via `onClose`). When it closes while focus was inside the dialog, focus returns to the element that was focused before it opened, if that element is still in the document. If the user had moved focus elsewhere (the dialog is non-modal), focus stays where it is.
5. A Lighthouse accessibility audit of the built app reports no `label`, `button-name`, `aria-*-name`, or other label/name failures. Baseline on `origin/main` (10731f7): score 0.95, one failure, `label` on the stress-test range input.
6. Visible layout is unchanged apart from focus indicators: checkboxes are visually hidden with a standard `.visually-hidden` pattern, not `display: none`.

Out of scope (documented in the PR): the optional "keyboard path to features" (searchable list or nearest-feature action) and closing the popup on empty map click; issue #5 (mobile layout) and issue #7 (contrast, 24px targets, reduced motion).

## Files that change

- `src/components/LayerPanel.jsx`: checkbox gets `className="visually-hidden"` and `aria-label={`${label} layer`}`; decorative dot and ON/OFF spans get `aria-hidden="true"` (the checkbox's checked state already conveys it). Slider gets `aria-label="Stress test point count"` and `aria-valuetext={formatValueText(stressCount)}` where `formatValueText(n)` returns `${n.toLocaleString('en-US')} points`.
- `src/components/FeaturePopup.jsx`: outer div gets `role="dialog"`, `aria-labelledby` (id from `useId()`) on the title span, `tabIndex={-1}`, and a ref. A `useEffect` keyed on whether a feature is open (`const open = feature != null`) does: on open, save `document.activeElement`, focus the dialog; register a `keydown` listener on `document` that calls `onClose()` on `Escape`; on cleanup (close or unmount) remove the listener and, only if focus was inside the dialog at close (by cleanup time React has removed the dialog node, so the check is `document.activeElement` being `document.body` or null) and the saved element is still connected and has `focus`, focus it. Keep `onClose` in a ref (updated in an effect) so a new inline `onClose` each App render does not re-run the open effect and steal focus again. Switching from one feature to another while open must not re-save the return target. Close button: `type="button"`, `aria-label="Close"`, glyph wrapped in `<span aria-hidden="true">`. Hooks run before the `if (!feature) return null` early return.
- `src/index.css`: replace `.layer-row input[type='checkbox'] { display: none; }` with a global `.visually-hidden` utility (clip-path/inset pattern: `position:absolute; width:1px; height:1px; padding:0; margin:-1px; overflow:hidden; clip:rect(0 0 0 0); clip-path:inset(50%); white-space:nowrap; border:0`). Add `.layer-row:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: -2px; }`. Replace `outline: none` on `.stress-slider` with a `.stress-slider:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }` rule. Add `.popup-close:focus-visible` and `.feature-popup:focus-visible` outlines. Use negative or small offsets so the panel's `overflow` does not clip them (check `.layer-panel` overflow in the live drive). Do not change colors, sizes, or animations (issue #7 owns those).
- `src/components/LayerPanel.test.jsx`: add tests (see Proof). Existing tests stay.
- `src/components/FeaturePopup.test.jsx`: add tests (see Proof). Existing tests stay; the close-button test queries `{ name: 'Close' }`.
- `package.json`, `package-lock.json`: add devDependency `@testing-library/user-event` (latest 14.x) for real Tab, Space, arrow, and Escape key sequences. Dev only, so `npm audit --omit=dev` is unaffected.
- `docs/plans/2026-11-07-issue-4-keyboard-screen-reader-a11y.md`: this file.

## Order of work

1. Install `@testing-library/user-event` as a devDependency (`npm install -D @testing-library/user-event@^14`).
2. Red: add the new LayerPanel and FeaturePopup tests; run `npm test` and confirm they fail for the right reasons. Commit the red tests (with the dependency) alone.
3. Green: LayerPanel changes, FeaturePopup changes. Run `npm test`.
4. CSS changes.
5. Full gate in order: `npm ci`, `npm run lint`, `npm test`, `npm run build`, `npm audit --omit=dev --audit-level=high`.
6. Lighthouse after (`npx -y lighthouse@12` against `npx vite preview`, headless Chrome, accessibility only) and the live drive.

## Risks

- Focus stealing: re-running the open effect on every App render (App passes a new inline `onClose` on every render, and App re-renders on store changes such as viewport moves) would repeatedly yank focus to the popup. Mitigated by keying the effect on `open` only and reading `onClose` from a ref. Tested by rerendering with a new `onClose` and checking focus did not move back.
- Escape listener on `document` fires even if focus is elsewhere (for example on the map); that is intended so Escape always dismisses the popup. It must be removed when closed (tested: Escape after close does not call `onClose` again).
- `:has()` needs a current browser; the app already requires WebGPU-capable Chrome/Edge/Firefox/Safari versions which all support `:has()`.
- `.layer-panel` may clip outlines if it has `overflow: hidden`; inset outlines (`outline-offset: -2px`) avoid that.
- Visually hidden checkbox must still receive the label click (native label association preserved since the input stays inside the `<label>`).
- Chose not to: switch to `role="switch"` (native checkbox already matches the AC wording "checkbox, checked"), add a focus trap (non-modal dialog; trapping would break the map), add map-feature keyboard navigation, or close on empty map click.

## Proof

- Criterion 1: LayerPanel test tabs with `user-event` through the panel and asserts focus lands on each checkbox (three with heatmap supported) and then the slider; `user.keyboard(' ')` on a focused checkbox calls `onToggle('airports', false)`; a one-step `change` on the slider sets `stressCount` to 100000 and `aria-valuetext` to "100,000 points" (arrow keys themselves are proven in the live drive; see Deviations). FeaturePopup test: Tab reaches the Close button and Enter calls `onClose`. Live drive confirms in a real browser.
- Criterion 2: CSS review plus live drive screenshots of the focus ring on a layer row, the slider, and the close button.
- Criterion 3: `getByRole('checkbox', { name: 'Airports layer' })` (and Sea Ports, Heatmap) with `toBeChecked`; `getByRole('slider', { name: 'Stress test point count' })` with `aria-valuetext` "0 points" and "500,000 points"; `getByRole('dialog', { name: 'FEATURE INTEL' })`; `getByRole('button', { name: 'Close' })`. Live drive reads the accessibility tree.
- Criterion 4: FeaturePopup tests: on open the dialog has focus; Escape calls `onClose` once; rerender from feature to null returns focus to a button that had focus before open; if focus was moved to another control outside the dialog, Escape and close leave focus on that control; rerender with a different `onClose` does not move focus back to the dialog; Escape after close does not call `onClose`.
- Criterion 5: Lighthouse JSON after the change, with no failing label/name audits.
- Criterion 6: CSS review; live drive screenshot shows the panel looks unchanged.
- Live drive: `npm run build && npx vite preview`; Tab from page start reaches Airports, Sea Ports, Heatmap (if WebGPU), the slider; focus ring visible on each; Space toggles a layer and the map updates; arrow keys move the slider; click an airport, popup takes focus, Tab to Close shows a focus ring, Escape closes, focus returns; open the popup again, focus a layer checkbox, Escape keeps focus on that checkbox.

## Deviations during implementation

- Slider arrow key test: `@testing-library/user-event` 14.6.8 has no keydown behavior for `ArrowRight` on `input[type=range]` (only radios and text selection), and jsdom does not step range inputs either, so a `{ArrowRight}` test could never go green from production code. The LayerPanel test instead dispatches the one-step `change` a browser makes on ArrowRight and asserts `stressCount` 100000 and `aria-valuetext` "100,000 points". Real arrow key stepping is verified in the live drive.
- Focus return on close (defect found in review): the first implementation always refocused the saved return target on cleanup, so with the non-modal dialog and the document-level Escape listener, pressing Escape while focus was on, for example, the stress slider or a layer checkbox yanked focus back to the element focused before opening. Focus is now restored only when focus was inside the dialog at close, detected as `document.activeElement` being `document.body` or null because React has already removed the dialog node by passive-effect cleanup time. Criterion 4, the FeaturePopup Files line, Proof, and the live drive were updated; a new frozen test covers it.
- Close button `type="button"`: added to the popup close button, which the plan did not list. It has no behavior change today (the popup is not inside a form) but prevents accidental form submission if it ever is.
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"@eslint/js": "^9.39.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^14.6.8",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.2.1",
Expand Down
56 changes: 51 additions & 5 deletions src/components/FeaturePopup.jsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,58 @@
import { useEffect, useId, useRef } from 'react'

export function FeaturePopup({ feature, onClose }) {
const open = feature != null
const titleId = useId()
const dialogRef = useRef(null)
const onCloseRef = useRef(onClose)

useEffect(() => {
onCloseRef.current = onClose
}, [onClose])

useEffect(() => {
if (!open) return undefined

const returnTarget = document.activeElement
dialogRef.current?.focus()

function handleKeyDown(e) {
if (e.key === 'Escape') onCloseRef.current?.()
}
document.addEventListener('keydown', handleKeyDown)

return () => {
document.removeEventListener('keydown', handleKeyDown)
// React has already removed the dialog node here, so focus that was
// inside it has fallen back to body. Restore only in that case; if the
// user moved focus elsewhere, leave it there.
const focusWasInDialog =
document.activeElement == null || document.activeElement === document.body
if (
focusWasInDialog &&
returnTarget &&
returnTarget.isConnected &&
typeof returnTarget.focus === 'function'
) {
returnTarget.focus()
}
}
}, [open])

if (!feature) return null

return (
<div className="feature-popup">
<div
ref={dialogRef}
className="feature-popup"
role="dialog"
aria-labelledby={titleId}
tabIndex={-1}
>
<div className="popup-header">
<span className="popup-title">FEATURE INTEL</span>
<button className="popup-close" aria-label="close" onClick={onClose}>
✕
<span id={titleId} className="popup-title">FEATURE INTEL</span>
<button type="button" className="popup-close" aria-label="Close" onClick={onClose}>
<span aria-hidden="true">✕</span>
</button>
</div>

Expand All @@ -22,4 +68,4 @@ export function FeaturePopup({ feature, onClose }) {
</table>
</div>
)
}
}
125 changes: 123 additions & 2 deletions src/components/FeaturePopup.test.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FeaturePopup } from './FeaturePopup.jsx'

const feature = {
Expand All @@ -22,7 +23,127 @@ describe('FeaturePopup', () => {
it('calls onClose when close button is clicked', () => {
const onClose = vi.fn()
render(<FeaturePopup feature={feature} onClose={onClose} />)
fireEvent.click(screen.getByRole('button', { name: /close/i }))
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
expect(onClose).toHaveBeenCalledOnce()
})
})
})

describe('FeaturePopup keyboard and screen reader access', () => {
it('is a dialog named by its title', () => {
render(<FeaturePopup feature={feature} onClose={vi.fn()} />)
expect(screen.getByRole('dialog', { name: 'FEATURE INTEL' })).toBeInTheDocument()
})

it('names the close button Close and hides its glyph', () => {
render(<FeaturePopup feature={feature} onClose={vi.fn()} />)
const button = screen.getByRole('button', { name: 'Close' })
expect(button.querySelector('[aria-hidden="true"]')).not.toBeNull()
})

it('moves focus to the dialog when it opens', () => {
render(<FeaturePopup feature={feature} onClose={vi.fn()} />)
expect(screen.getByRole('dialog', { name: 'FEATURE INTEL' })).toHaveFocus()
})

it('reaches the close button with Tab and activates it with Enter', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
render(<FeaturePopup feature={feature} onClose={onClose} />)
await user.tab()
expect(screen.getByRole('button', { name: 'Close' })).toHaveFocus()
await user.keyboard('{Enter}')
expect(onClose).toHaveBeenCalledOnce()
})

it('calls onClose once on Escape', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
render(<FeaturePopup feature={feature} onClose={onClose} />)
await user.keyboard('{Escape}')
expect(onClose).toHaveBeenCalledOnce()
})

function Harness({ feature: f, onClose }) {
return (
<>
<button type="button">Opener</button>
<FeaturePopup feature={f} onClose={onClose} />
</>
)
}

it('returns focus to the previously focused element when it closes', () => {
const { rerender } = render(<Harness feature={null} onClose={vi.fn()} />)
const opener = screen.getByRole('button', { name: 'Opener' })
opener.focus()
rerender(<Harness feature={feature} onClose={vi.fn()} />)
expect(screen.getByRole('dialog', { name: 'FEATURE INTEL' })).toHaveFocus()
rerender(<Harness feature={null} onClose={vi.fn()} />)
expect(opener).toHaveFocus()
})

it('does not take focus back when rerendered with a new onClose', () => {
const { rerender } = render(<Harness feature={feature} onClose={vi.fn()} />)
const opener = screen.getByRole('button', { name: 'Opener' })
opener.focus()
rerender(<Harness feature={feature} onClose={vi.fn()} />)
expect(opener).toHaveFocus()
})

it('does not take focus back when switching to another feature', () => {
const other = { properties: { name: 'Other Site' } }
const { rerender } = render(<Harness feature={feature} onClose={vi.fn()} />)
const opener = screen.getByRole('button', { name: 'Opener' })
opener.focus()
rerender(<Harness feature={other} onClose={vi.fn()} />)
expect(opener).toHaveFocus()
})

it('calls the latest onClose on Escape', async () => {
const user = userEvent.setup()
const first = vi.fn()
const second = vi.fn()
const { rerender } = render(<Harness feature={feature} onClose={first} />)
rerender(<Harness feature={feature} onClose={second} />)
await user.keyboard('{Escape}')
expect(first).not.toHaveBeenCalled()
expect(second).toHaveBeenCalledOnce()
})

it('does not call onClose on Escape after it has closed', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
const { rerender } = render(<Harness feature={feature} onClose={onClose} />)
rerender(<Harness feature={null} onClose={onClose} />)
await user.keyboard('{Escape}')
expect(onClose).not.toHaveBeenCalled()
})
})

describe('FeaturePopup focus return when focus has moved elsewhere', () => {
function TwoButtonHarness({ feature: f, onClose }) {
return (
<>
<button type="button">Opener</button>
<button type="button">Elsewhere</button>
<FeaturePopup feature={f} onClose={onClose} />
</>
)
}

it('leaves focus on a control outside the dialog when Escape closes it', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
const { rerender } = render(<TwoButtonHarness feature={null} onClose={onClose} />)
const opener = screen.getByRole('button', { name: 'Opener' })
const elsewhere = screen.getByRole('button', { name: 'Elsewhere' })
opener.focus()
rerender(<TwoButtonHarness feature={feature} onClose={onClose} />)
expect(screen.getByRole('dialog', { name: 'FEATURE INTEL' })).toHaveFocus()
elsewhere.focus()
await user.keyboard('{Escape}')
expect(onClose).toHaveBeenCalledOnce()
rerender(<TwoButtonHarness feature={null} onClose={onClose} />)
expect(elsewhere).toHaveFocus()
})
})
Loading
Loading