From d3e1e950ffccefe53e38d10ac98f089fc05764d3 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Mon, 16 Nov 2026 22:53:23 +0100 Subject: [PATCH 1/4] Progress on screen reader testing --- frontend/src/components/layout/AppLayout.tsx | 10 ++--- frontend/src/components/ui/Chip.tsx | 10 ++++- frontend/src/features/auth/AccountPage.tsx | 18 ++++++-- .../auth/components/AuthForm.module.css | 2 +- .../src/features/auth/components/AuthForm.tsx | 8 +++- frontend/src/features/search/SearchView.tsx | 18 +++++++- .../search/components/ActiveFilters.tsx | 23 ++++++++++- frontend/src/features/wine/WineView.tsx | 6 ++- .../wine/components/StudentReviews.tsx | 32 +++++++++++---- frontend/src/lib/focus.test.ts | 41 +++++++++++++++++++ frontend/src/lib/focus.ts | 20 +++++++++ 11 files changed, 163 insertions(+), 25 deletions(-) create mode 100644 frontend/src/lib/focus.test.ts diff --git a/frontend/src/components/layout/AppLayout.tsx b/frontend/src/components/layout/AppLayout.tsx index 7f4b993..0c94d9c 100644 --- a/frontend/src/components/layout/AppLayout.tsx +++ b/frontend/src/components/layout/AppLayout.tsx @@ -14,15 +14,15 @@ import styles from './AppLayout.module.css'; */ export function AppLayout() { const { pathname } = useLocation(); - const isFirstRender = useRef(true); + // Compared with the previous path instead of counting renders. StrictMode runs effects + // twice in development, and a counter would then move focus on the very first load. + const previousPathname = useRef(pathname); const mainRef = useRef(null); useEffect(() => { - if (isFirstRender.current) { - isFirstRender.current = false; - return; - } + if (previousPathname.current === pathname) return; + previousPathname.current = pathname; const main = mainRef.current; if (!main) return; return focusHeadingWhenReady(main); diff --git a/frontend/src/components/ui/Chip.tsx b/frontend/src/components/ui/Chip.tsx index ed0eb8c..4a44653 100644 --- a/frontend/src/components/ui/Chip.tsx +++ b/frontend/src/components/ui/Chip.tsx @@ -9,15 +9,21 @@ interface ChipLinkProps { tone?: 'default' | 'onBrand'; /** Replaces the visible text for screen readers when it says too little on its own. */ label?: string; + onClick?: () => void; } /** * Chip som navigerer (forslag, kategorier, aktive filtre som lenker). * Det er en lenke – ikke en knapp – fordi den endrer side/URL. */ -export function ChipLink({ to, children, tone = 'default', label }: ChipLinkProps) { +export function ChipLink({ to, children, tone = 'default', label, onClick }: ChipLinkProps) { return ( - + {children} ); diff --git a/frontend/src/features/auth/AccountPage.tsx b/frontend/src/features/auth/AccountPage.tsx index 6cb7dbe..25b72e4 100644 --- a/frontend/src/features/auth/AccountPage.tsx +++ b/frontend/src/features/auth/AccountPage.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useNavigate, useLocation, Link } from 'react-router'; import { useDocumentTitle } from '../../hooks/useDocumentTitle'; import { AuthForm } from './components/AuthForm'; @@ -17,10 +17,22 @@ function nextPage(state: unknown): string { export default function AccountPage() { const [logoutError, setLogoutError] = useState(''); const [mode, setMode] = useState<'login' | 'register'>('login'); + const headingRef = useRef(null); + const previousMode = useRef(mode); const { user, loading, login, register, logout } = useAuth(); const navigate = useNavigate(); const location = useLocation(); - useDocumentTitle(user ? 'Min konto' : 'Logg inn'); + useDocumentTitle(user ? 'Min konto' : mode === 'login' ? 'Logg inn' : 'Lag bruker'); + + // Switching between logging in and creating a user replaces the form, like a new page. + // Focus moves to the new heading, so screen reader users hear which form they are in. + useEffect(() => { + if (previousMode.current === mode) return; + previousMode.current = mode; + const heading = headingRef.current; + heading?.setAttribute('tabindex', '-1'); + heading?.focus(); + }, [mode]); async function handleSubmit(credentials: Credentials): Promise { const message = await (mode === 'login' ? login : register)(credentials); @@ -63,7 +75,7 @@ export default function AccountPage() { return (
-

{mode === 'login' ? 'Logg inn' : 'Lag bruker'}

+

{mode === 'login' ? 'Logg inn' : 'Lag bruker'}

{mode === 'login' ? 'Logg inn for å ta vare på dommene og listene dine.' diff --git a/frontend/src/features/auth/components/AuthForm.module.css b/frontend/src/features/auth/components/AuthForm.module.css index fa7daac..abafe22 100644 --- a/frontend/src/features/auth/components/AuthForm.module.css +++ b/frontend/src/features/auth/components/AuthForm.module.css @@ -54,7 +54,7 @@ cursor: pointer; } -.submit:disabled { +.submit[aria-disabled='true'] { opacity: 0.6; cursor: progress; } diff --git a/frontend/src/features/auth/components/AuthForm.tsx b/frontend/src/features/auth/components/AuthForm.tsx index dd75fb8..304b6e9 100644 --- a/frontend/src/features/auth/components/AuthForm.tsx +++ b/frontend/src/features/auth/components/AuthForm.tsx @@ -26,6 +26,7 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) { async function handleSubmit(event: FormEvent) { event.preventDefault(); + if (working) return; setError(''); setWorking(true); const message = await onSubmit({ username: username.trim().toLowerCase(), password }); @@ -78,7 +79,12 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) { {error}

- diff --git a/frontend/src/features/search/SearchView.tsx b/frontend/src/features/search/SearchView.tsx index 16f1525..e6be315 100644 --- a/frontend/src/features/search/SearchView.tsx +++ b/frontend/src/features/search/SearchView.tsx @@ -1,9 +1,11 @@ import { useEffect, useRef, useId } from 'react'; +import { useLocation } from 'react-router'; import { ErrorNotice } from '../../components/ui/ErrorNotice'; import { SearchForm } from '../../components/ui/SearchForm'; import { Skeleton } from '../../components/ui/Skeleton'; import { WineList } from '../../components/ui/WineList'; import { useMediaQuery } from '../../hooks/useMediaQuery'; +import { focusIfLost } from '../../lib/focus'; import { formatCount, pluralize } from '../../lib/format'; import { activeFilterCount, type SearchState, type SortOption } from '../../lib/searchParams'; import type { FilterGroup } from './api/toFilterGroups'; @@ -62,6 +64,18 @@ export function SearchView(props: SearchViewProps) { const listRef = useRef(null); const firstNewWine = useRef(null); + const headingRef = useRef(null); + const { search } = useLocation(); + const previousSearch = useRef(search); + + // Links on this page change the URL and are often gone afterwards: a removed filter, + // «Nullstill filtre», a suggestion when nothing matched. The route stays the same, so + // the layout does not move focus. The h1 takes it, and the live region reads the result. + useEffect(() => { + if (previousSearch.current === search) return; + previousSearch.current = search; + focusIfLost(headingRef.current); + }, [search]); // The button can disappear after the last page, so keyboard and screen // reader users continue from the first new wine instead of losing their place. @@ -90,7 +104,9 @@ export function SearchView(props: SearchViewProps) { return (
-

Utforsk viner

+

+ Utforsk viner +

(null); + const removedIndex = useRef(null); + + // The removed chip is gone, so focus moves to the one that took its place, or to the + // one before it. With no chips left, the search page moves focus to its h1. + useEffect(() => { + const index = removedIndex.current; + if (index === null) return; + removedIndex.current = null; + const links = listRef.current?.querySelectorAll('a'); + if (!links?.length || !isFocusLost()) return; + links[Math.min(index, links.length - 1)].focus(); + }); + if (chips.length === 0) return null; return (
-
    - {chips.map(({ label, without }) => ( +
      + {chips.map(({ label, without }, index) => (
    • { + removedIndex.current = index; + }} > {label} diff --git a/frontend/src/features/wine/WineView.tsx b/frontend/src/features/wine/WineView.tsx index 7642ab9..ced290b 100644 --- a/frontend/src/features/wine/WineView.tsx +++ b/frontend/src/features/wine/WineView.tsx @@ -37,6 +37,8 @@ function backLink(state: unknown) { export function WineView({ wine, loading, error, refetch, notFound }: WineViewProps) { const location = useLocation(); const back = backLink(location.state); + // Saving a review fetches the wine again. Only the first load is shown and announced. + const firstLoad = loading && !wine; return (
      @@ -45,10 +47,10 @@ export function WineView({ wine, loading, error, refetch, notFound }: WineViewPr

      - {loading ? 'Laster vin …' : ''} + {firstLoad ? 'Laster vin …' : ''}

      - {loading && } + {firstLoad && } {error && ( <> diff --git a/frontend/src/features/wine/components/StudentReviews.tsx b/frontend/src/features/wine/components/StudentReviews.tsx index a26053f..73765ec 100644 --- a/frontend/src/features/wine/components/StudentReviews.tsx +++ b/frontend/src/features/wine/components/StudentReviews.tsx @@ -1,8 +1,9 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Stars } from '../../../components/ui/Stars'; import { ErrorNotice } from '../../../components/ui/ErrorNotice'; import { Skeleton } from '../../../components/ui/Skeleton'; import { classifyError, ERROR_DETAILS } from '../../../lib/errors'; +import { focusIfLost } from '../../../lib/focus'; import { formatRatingSummary, formatRelativeTime } from '../../../lib/format'; import { useWineReviews, type ReviewChange, type ReviewDraft } from '../api/useWineReviews'; import { RatingDistribution } from './RatingDistribution'; @@ -36,8 +37,20 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) { saving, } = useWineReviews(wineId); const [message, setMessage] = useState(''); + const formArea = useRef(null); + const changed = useRef(false); + + // The buttons are disabled while saving, and the form is built again after the first + // save and after a delete. Both drop the focus, so it goes back to the submit button + // once the result is in the live region. + useEffect(() => { + if (saving || !message || !changed.current) return; + changed.current = false; + focusIfLost(formArea.current?.querySelector('button[type="submit"]')); + }, [saving, message]); async function handleSave(draft: ReviewDraft) { + changed.current = true; setMessage(''); setMessage( describeChange(await save(draft), 'Dommen er lagret.', 'Vi fikk ikke lagret dommen.'), @@ -45,6 +58,7 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) { } async function handleDelete() { + changed.current = true; setMessage(''); setMessage( describeChange(await remove(), 'Dommen er slettet.', 'Vi fikk ikke slettet dommen.'), @@ -90,13 +104,15 @@ export function StudentReviews({ wineId, now }: StudentReviewsProps) {

      {/* A new key resets the form when the review is first saved or deleted. */} - +
      + +
      {reviews.length > 0 ? (
        diff --git a/frontend/src/lib/focus.test.ts b/frontend/src/lib/focus.test.ts new file mode 100644 index 0000000..cd9ed96 --- /dev/null +++ b/frontend/src/lib/focus.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { focusIfLost } from './focus'; + +describe('focusIfLost', () => { + afterEach(() => { + document.body.innerHTML = ''; + }); + + it('flytter fokus når det fokuserte elementet er fjernet', () => { + document.body.innerHTML = '

        Tittel

        '; + const heading = document.querySelector('h1')!; + const button = document.querySelector('button')!; + button.focus(); + button.remove(); + + focusIfLost(heading); + + expect(heading).toHaveFocus(); + expect(heading).toHaveAttribute('tabindex', '-1'); + }); + + it('lar fokus være der brukeren er', () => { + document.body.innerHTML = '

        Tittel

        '; + const input = document.querySelector('input')!; + input.focus(); + + focusIfLost(document.querySelector('h1')); + + expect(input).toHaveFocus(); + }); + + it('gir ikke tabindex til elementer som kan fokuseres fra før', () => { + document.body.innerHTML = ''; + const button = document.querySelector('button')!; + + focusIfLost(button); + + expect(button).toHaveFocus(); + expect(button).not.toHaveAttribute('tabindex'); + }); +}); diff --git a/frontend/src/lib/focus.ts b/frontend/src/lib/focus.ts index 2c0b604..51f548e 100644 --- a/frontend/src/lib/focus.ts +++ b/frontend/src/lib/focus.ts @@ -25,3 +25,23 @@ export function focusHeadingWhenReady(container: HTMLElement, timeoutMs = 5000): observer.observe(container, { childList: true, subtree: true }); return stop; } + +/** True when nothing has focus, which is what happens when the focused element is removed. */ +export function isFocusLost(): boolean { + const active = document.activeElement; + return !active || active === document.body || !active.isConnected; +} + +/** + * Moves focus to `target` if the focused element has just been removed from the page, + * for example a link that disappears when the user clicks it. Without this the focus + * falls back to ``, and screen reader and keyboard users lose their place. + * Does nothing if the user is still focused on something that exists. + */ +export function focusIfLost(target: HTMLElement | null | undefined): void { + if (!target || !isFocusLost()) return; + if (!target.hasAttribute('tabindex') && !target.matches('a[href], button, input, select, textarea')) { + target.setAttribute('tabindex', '-1'); + } + target.focus(); +} From 435779e313a321c2fa780a4e4533d1b264e3555f Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Mon, 16 Nov 2026 22:56:15 +0100 Subject: [PATCH 2/4] Screenreader work and bug fixes --- frontend/src/components/ui/Chip.tsx | 7 +------ .../src/features/auth/AccountPage.test.tsx | 11 ++++++++++ frontend/src/features/my/MyPage.test.tsx | 4 ++++ .../features/search/SearchFilters.test.tsx | 20 +++++++++++++++++++ .../src/features/search/SearchPage.test.tsx | 15 ++++++++++++++ .../wine/components/StudentReviews.test.tsx | 7 +++++++ frontend/src/lib/focus.ts | 5 ++++- 7 files changed, 62 insertions(+), 7 deletions(-) diff --git a/frontend/src/components/ui/Chip.tsx b/frontend/src/components/ui/Chip.tsx index 4a44653..95d4594 100644 --- a/frontend/src/components/ui/Chip.tsx +++ b/frontend/src/components/ui/Chip.tsx @@ -18,12 +18,7 @@ interface ChipLinkProps { */ export function ChipLink({ to, children, tone = 'default', label, onClick }: ChipLinkProps) { return ( - + {children} ); diff --git a/frontend/src/features/auth/AccountPage.test.tsx b/frontend/src/features/auth/AccountPage.test.tsx index 296c483..ed765c0 100644 --- a/frontend/src/features/auth/AccountPage.test.tsx +++ b/frontend/src/features/auth/AccountPage.test.tsx @@ -82,6 +82,17 @@ describe('AccountPage', () => { await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Feil brukernavn eller passord.'), ); + // The button is never disabled, so the user is still in the form and can try again. + expect(screen.getByRole('button', { name: 'Logg inn' })).toHaveFocus(); + }); + + it('moves focus to the new heading when switching to «Lag bruker»', async () => { + const { user } = renderPage([me(null)]); + + await user.click(await screen.findByRole('button', { name: 'Lag bruker' })); + + expect(screen.getByRole('heading', { level: 1, name: 'Lag bruker' })).toHaveFocus(); + expect(document.title).toBe('Lag bruker – Kork & Krone'); }); it('explains which rule the username broke', async () => { diff --git a/frontend/src/features/my/MyPage.test.tsx b/frontend/src/features/my/MyPage.test.tsx index b620865..b4eb6ee 100644 --- a/frontend/src/features/my/MyPage.test.tsx +++ b/frontend/src/features/my/MyPage.test.tsx @@ -88,6 +88,10 @@ describe('MyPage', () => { await user.click(await screen.findByRole('button', { name: 'Vil prøve Origem Merlot' })); expect(screen.getByText(/Du har ikke lagret noen viner ennå/)).toBeInTheDocument(); + // The button the user clicked is gone. The live region says what happened, + // and focus moves to the heading of the list instead of the top of the page. + expect(screen.getByRole('status')).toHaveTextContent('Fjernet fra listen. Listen er tom.'); + expect(screen.getByRole('heading', { level: 2, name: 'Vil prøve' })).toHaveFocus(); }); it('offers a new attempt when the wines cannot be fetched', async () => { diff --git a/frontend/src/features/search/SearchFilters.test.tsx b/frontend/src/features/search/SearchFilters.test.tsx index f22ac27..e581ec4 100644 --- a/frontend/src/features/search/SearchFilters.test.tsx +++ b/frontend/src/features/search/SearchFilters.test.tsx @@ -210,6 +210,26 @@ describe('Aktive filtre', () => { ); }); + it('flytter fokus til neste filter når et filter fjernes', async () => { + const { user } = renderPage( + [searchMock(() => 3).mock, filterOptionsMock().mock], + '/sok?q=pinot&type=rodvin&land=IT', + ); + await user.click(await screen.findByRole('link', { name: 'Fjern filteret Rødvin' })); + await waitFor(() => expect(location()).toHaveTextContent('/sok?q=pinot&land=IT')); + expect(screen.getByRole('link', { name: 'Fjern filteret Italia' })).toHaveFocus(); + }); + + it('flytter fokus til h1 når det siste filteret fjernes', async () => { + const { user } = renderPage( + [searchMock(() => 3).mock, filterOptionsMock().mock], + '/sok?q=pinot&type=rodvin&land=IT', + ); + await user.click(await screen.findByRole('link', { name: 'Nullstill filtre' })); + await waitFor(() => expect(location()).toHaveTextContent('/sok?q=pinot')); + expect(screen.getByRole('heading', { level: 1, name: 'Utforsk viner' })).toHaveFocus(); + }); + it('vises ikke uten filtre', async () => { renderPage([searchMock(() => 3).mock, filterOptionsMock().mock], '/sok?q=pinot'); await screen.findByRole('list', { name: 'Søkeresultater' }); diff --git a/frontend/src/features/search/SearchPage.test.tsx b/frontend/src/features/search/SearchPage.test.tsx index 54f43d5..225ab99 100644 --- a/frontend/src/features/search/SearchPage.test.tsx +++ b/frontend/src/features/search/SearchPage.test.tsx @@ -262,6 +262,21 @@ describe('SearchPage – tilstander', () => { expect(screen.getByRole('link', { name: 'Se alle viner' })).toHaveAttribute('href', '/sok'); }); + it('flytter fokus til h1 når en lenke uten treff blir borte etter klikket', async () => { + const { user } = renderPage([searchMock(({ search }) => (search ? 0 : 3)).mock], '/sok?q=zzz'); + await user.click(await screen.findByRole('link', { name: 'Se alle viner' })); + expect(await results()).toBeInTheDocument(); + expect(screen.getByRole('heading', { level: 1, name: 'Utforsk viner' })).toHaveFocus(); + }); + + it('lar fokus bli i søkefeltet mens brukeren skriver', async () => { + const { user } = renderPage([searchMock(() => 3).mock]); + await results(); + await user.type(searchbox(), 'pinot'); + await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('q=pinot')); + expect(searchbox()).toHaveFocus(); + }); + it('viser en egen tekst når filtre uten søkeord ikke gir treff', async () => { renderPage([searchMock(() => 0).mock], '/sok?type=rodvin'); expect(await screen.findByText('Ingen viner passer til valgene dine.')).toBeInTheDocument(); diff --git a/frontend/src/features/wine/components/StudentReviews.test.tsx b/frontend/src/features/wine/components/StudentReviews.test.tsx index b7e1e45..772d32d 100644 --- a/frontend/src/features/wine/components/StudentReviews.test.tsx +++ b/frontend/src/features/wine/components/StudentReviews.test.tsx @@ -112,6 +112,10 @@ describe('StudentReviews', () => { expect(await screen.findByRole('button', { name: 'Oppdater dommen' })).toBeInTheDocument(); expect(screen.getByRole('status')).toHaveTextContent('Dommen er lagret.'); + // The form is built again after the first save. Focus must not fall back to the page. + await waitFor(() => + expect(screen.getByRole('button', { name: 'Oppdater dommen' })).toHaveFocus(), + ); }); it('tells the user when saving fails', async () => { @@ -134,6 +138,7 @@ describe('StudentReviews', () => { 'Vi fikk ikke lagret dommen. Vi fikk ikke kontakt med serveren.', ), ); + await waitFor(() => expect(screen.getByRole('button', { name: 'Lagre dommen' })).toHaveFocus()); }); it('deletes the user\u2019s own review', async () => { @@ -149,6 +154,8 @@ describe('StudentReviews', () => { await user.click(await screen.findByRole('button', { name: 'Slett dommen' })); await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('Dommen er slettet.')); + // The delete button is gone, so focus goes to the button that starts a new review. + await waitFor(() => expect(screen.getByRole('button', { name: 'Lagre dommen' })).toHaveFocus()); }); it('offers a new attempt when the reviews cannot be fetched', async () => { diff --git a/frontend/src/lib/focus.ts b/frontend/src/lib/focus.ts index 51f548e..d6227b8 100644 --- a/frontend/src/lib/focus.ts +++ b/frontend/src/lib/focus.ts @@ -40,7 +40,10 @@ export function isFocusLost(): boolean { */ export function focusIfLost(target: HTMLElement | null | undefined): void { if (!target || !isFocusLost()) return; - if (!target.hasAttribute('tabindex') && !target.matches('a[href], button, input, select, textarea')) { + if ( + !target.hasAttribute('tabindex') && + !target.matches('a[href], button, input, select, textarea') + ) { target.setAttribute('tabindex', '-1'); } target.focus(); From 2804a4fe0947d67d8bfd1fe5704ab590932bb19b Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Mon, 16 Nov 2026 23:02:59 +0100 Subject: [PATCH 3/4] Automated tests and 3 more test files --- README.md | 4 +- docs/screen-reader.md | 65 ++++++++ frontend/e2e/screenreader.spec.ts | 156 ++++++++++++++++++ .../src/features/auth/AccountPage.test.tsx | 5 + .../src/features/auth/components/AuthForm.tsx | 8 +- frontend/src/features/my/MyView.tsx | 31 +++- 6 files changed, 265 insertions(+), 4 deletions(-) create mode 100644 docs/screen-reader.md create mode 100644 frontend/e2e/screenreader.spec.ts diff --git a/README.md b/README.md index ff425db..ba50433 100644 --- a/README.md +++ b/README.md @@ -226,10 +226,11 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, - Playwright with axe-core against WCAG 2.1 A and AA, on desktop and mobile. - An automated test for reflow at 320 px. - Manual testing with only the keyboard. +- Screen reader flows: Playwright steps through the flows and checks where focus goes and what the live regions say, for example after removing a filter, a failed login or saving a review. See [screen reader testing](docs/screen-reader.md) for what we found and fixed, and the script for testing by hand with VoiceOver. ### Some known gaps -- We have not tested with a screen reader yet. +- The manual test with VoiceOver has not been run yet. The script is in [screen reader testing](docs/screen-reader.md). - eslint-plugin-jsx-a11y is not set up yet. ## Sustainability @@ -403,5 +404,6 @@ Remove known issues as they are fixed. - [Database](docs/database.md): PostgreSQL on macOS, Windows and Ubuntu - [VM](docs/vm.md): deployment, Apache and running the backend with `nohup` - [API](docs/api.md): GraphQL queries, user accounts and the X-Wines citation +- [Screen reader testing](docs/screen-reader.md): what we found, what we fixed and the VoiceOver script - [Workflow](docs/workflow.md): branches, reviews and checks - [Tasks](docs/tasks.md): requirements and sketches \ No newline at end of file diff --git a/docs/screen-reader.md b/docs/screen-reader.md new file mode 100644 index 0000000..9d41c11 --- /dev/null +++ b/docs/screen-reader.md @@ -0,0 +1,65 @@ +# Screen reader testing + +How we test Kork & Krone with a screen reader, what we found, and what is still left to check. Issue #47. + +## How we test + +Two parts, because neither is enough on its own. + +1. **The accessibility tree, automated.** A screen reader reads the accessibility tree that the browser builds from the page, not the page itself. We read that tree for every page and step through each flow in Chromium (Playwright), and record after every action where focus is and what the live regions say. The flows that matter are in `frontend/e2e/screenreader.spec.ts`, so they stay fixed. +2. **A real screen reader, by hand.** The automated checks cannot tell how a screen reader phrases things, or whether it reads something twice. That needs a person with VoiceOver, using the script below. + +## What we found and fixed + +Found by stepping through the flows. Each one has a test that fails without the fix. + +| Where | Problem | Fix | +| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | +| Search: active filters | Removing a filter removed the link the user was on. Focus fell back to the top of the page, so the screen reader started from the top again. | Focus moves to the next filter, or to the h1 when none are left. | +| Search: «Nullstill filtre» and the links when nothing matched | Same: the link disappears with the click. | Focus moves to the h1, and the live region reads the new result. | +| Wine page: saving or deleting a review | The buttons are disabled while saving, and the form is rebuilt after the first save. Focus was lost both times. | Focus goes back to the submit button once the result has been announced. | +| Wine page: saving a review | The page announced «Laster vin …» while it refreshed, and showed a skeleton above the wine. | Only the first load is announced and shown. | +| Login | The button was disabled while logging in, so focus was lost when the login failed. | `aria-disabled` instead of `disabled`, so focus stays on the button. Double clicks are still ignored. | +| Login: «Lag bruker» / «Logg inn» | The form changed, but focus stayed on the switch button, so nothing told the user which form they were in. | Focus moves to the new h1, and the page title changes with it. | +| Lag bruker: the password field | «Minst 8 tegn.» was shown under the field but not read with it. Only the username had its hint linked. | `aria-describedby` on the password field too. | +| Mine anmeldelser: removing a wine from «Vil prøve» | The card disappeared with the button, focus was lost, and nothing was announced. | The live region says «Fjernet fra listen. 1 vin igjen.», and focus moves to the list heading. | +| All pages, in development only | React StrictMode runs effects twice, so focus jumped to the h1 on the very first load. Production did not do this, so testing on the dev server gave a different result. | The layout compares with the previous path instead of counting renders. | + +Checked and fine: landmarks, one h1 per page, focus on the h1 after navigation, page titles, names on all buttons and form fields, «Vil prøve» as a toggle button (`aria-pressed`), the star rating as ten radio buttons, star ratings as text, the filter dialog (focus inside, Escape closes, focus back to the button), «Last inn flere» (focus on the first new wine), and the live regions for search results, loading and errors. + +## Manual test with VoiceOver + +Use VoiceOver on macOS with **Safari**, the combination most VoiceOver users have. Test against the production build (`npm run build && npm run preview` in `frontend/`) or the VM. + +- Turn VoiceOver on and off: Cmd + F5. +- VO is Ctrl + Option. VO + arrow keys read the next or previous item. +- VO + U opens the rotor, with lists of headings, links, landmarks and form controls. +- Tab moves between controls. Space or Enter uses them. + +For each step, write down what VoiceOver says if it differs from the expected result. + +| # | Step | Expected | +| --- | ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Open the front page. Open the rotor and look at landmarks and headings. | Banner, «Hovedmeny», main and footer. One h1, then h2 for each section. | +| 2 | Tab once from the top. | «Hopp til hovedinnhold, lenke». Enter goes to the main content. | +| 3 | Type «pinot» in the search field and press Enter. | The new page is announced with its h1, «Utforsk viner». Then «Viser … viner for «pinot»». | +| 4 | Go to the first wine card with VO + arrows. | Type and country, the name as a heading and link, the winery, «Fellesskapet 4,9 av 5 · 8 vurderinger», and «Vil prøve …, toggle button». | +| 5 | Tick «Rødvin» in the filters with Space. | «Rødvin, 11 viner, checked» (not «unchecked»), then the new number of hits. | +| 6 | Tab to «Fjern filteret Rødvin» and press Enter. | Focus on the next filter, or on «Utforsk viner» if it was the last. Then the new number of hits. | +| 7 | Search for «finnesikke». | «Ingen treff», and the text that explains why, with the suggestions. | +| 8 | Open a wine. Find «Gi din dom» and use the arrow keys in the stars. | «0,5 av 5 stjerner, radio button, 1 of 10», and so on up to 5. | +| 9 | Choose 4 stars, write a comment, press «Lagre dommen». | «Dommen er lagret.» Focus on «Oppdater dommen». | +| 10 | Press «Slett dommen». | «Dommen er slettet.» Focus on «Lagre dommen». | +| 11 | Press «Vil prøve» on the wine page, then go to «Mine anmeldelser» and press it again on the card. | «Fjernet fra listen. Listen er tom.» Focus on «Vil prøve, heading level 2». | +| 12 | Go to «Logg inn», log in with a wrong password. | «Feil brukernavn eller passord.» Focus still on «Logg inn». | +| 13 | Press «Lag bruker». | «Lag bruker, heading level 1». The field hints are read with the fields. | +| 14 | On a phone-sized window: open «Filtrer», choose a filter, close with «Vis … viner». | The dialog is announced with its heading, and focus goes back to «Filtrer (1 valgt)». | +| 15 | Turn off the network (Wi-Fi) and search. | «Du er frakoblet …», and the error message says what is wrong. | + +### Results + +| Date | Who | Browser and screen reader | Result | +| ---- | --- | -------------------------- | ----------- | +| | | Safari + VoiceOver (macOS) | Not run yet | + +If there is time, also test with NVDA and Firefox on Windows, and VoiceOver on an iPhone. diff --git a/frontend/e2e/screenreader.spec.ts b/frontend/e2e/screenreader.spec.ts new file mode 100644 index 0000000..39d59ae --- /dev/null +++ b/frontend/e2e/screenreader.spec.ts @@ -0,0 +1,156 @@ +import AxeBuilder from '@axe-core/playwright'; +import { expect, test, type Page } from '@playwright/test'; + +/* + * E2E for what a screen reader user depends on beyond the markup: where focus goes when the + * element the user was on disappears, and what the live regions say. jsdom keeps focus on + * a disabled button, so these flows are only tested properly in a real browser. + * Runs against `vite preview` with a stubbed GraphQL API. + */ +interface Variables { + filter?: { types?: string[] }; +} + +const wine = (id: number, type: string) => ({ + __typename: 'Wine', + id: String(id), + name: `${type} ${id}`, + type, + grapes: ['Merlot'], + country: 'Italy', + countryCode: 'IT', + wineryName: 'Testprodusent', + communityRating: 4, + communityRatingCount: 10, +}); + +function winesResponse({ filter }: Variables, search?: string) { + const types = search === 'finnesikke' ? [] : (filter?.types ?? ['Red', 'White']); + const wines = types.map((type, index) => wine(index + 1, type)); + return { + data: { + wines: { + __typename: 'WineConnection', + totalCount: wines.length, + edges: wines.map((node) => ({ __typename: 'WineEdge', cursor: node.id, node })), + pageInfo: { __typename: 'PageInfo', hasNextPage: false, endCursor: null }, + }, + }, + }; +} + +const option = (value: string, count: number) => ({ + __typename: 'FilterOption', + value, + label: value, + count, +}); + +const filterResponse = { + data: { + filterOptions: { + __typename: 'FilterOptions', + types: [option('Red', 53), option('White', 19)], + countries: [option('IT', 25)], + grapes: [option('Merlot', 9)], + harmonize: [option('Beef', 53)], + }, + }, +}; + +async function stubApi(page: Page) { + await page.route('**/project2/graphql', (route) => { + const { operationName, variables } = route.request().postDataJSON() as { + operationName: string; + variables: Variables & { search?: string }; + }; + switch (operationName) { + case 'Me': + return route.fulfill({ json: { data: { me: null } } }); + case 'Login': + return route.fulfill({ + json: { + errors: [ + { message: 'Invalid credentials', extensions: { code: 'INVALID_CREDENTIALS' } }, + ], + }, + }); + case 'FilterOptions': + return route.fulfill({ json: filterResponse }); + case 'SearchWines': + return route.fulfill({ json: winesResponse(variables, variables.search) }); + default: + return route.abort(); + } + }); +} + +const heading = (page: Page) => page.getByRole('heading', { level: 1 }); +// Scoped to
        : the layout has its own live region for the connection banner. +const mainStatus = (page: Page) => page.getByRole('main').getByRole('status'); + +async function expectNoAxeViolations(page: Page) { + const axe = await new AxeBuilder({ page }) + .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']) + .analyze(); + expect(axe.violations).toEqual([]); +} + +test.describe('Skjermleser og fokus', () => { + test.beforeEach(async ({ page }) => { + await stubApi(page); + }); + + test('fokus går til neste filter når et filter fjernes, og til h1 når alle er borte', async ({ + page, + }) => { + await page.goto('./sok?type=rodvin&type=hvitvin'); + const removeRed = page.getByRole('link', { name: 'Fjern filteret Rødvin' }); + await removeRed.focus(); + await page.keyboard.press('Enter'); + + await expect(page).toHaveURL(/\/sok\?type=hvitvin$/); + const removeWhite = page.getByRole('link', { name: 'Fjern filteret Hvitvin' }); + await expect(removeWhite).toBeFocused(); + await expect(mainStatus(page)).toHaveText('Viser 1 av 1 vin'); + + await page.keyboard.press('Enter'); + await expect(page).toHaveURL(/\/sok$/); + await expect(heading(page)).toBeFocused(); + await expect(mainStatus(page)).toHaveText('Viser 2 av 2 viner'); + }); + + test('fokus blir på knappen når innloggingen feiler, og feilen leses opp', async ({ page }) => { + await page.goto('./konto'); + await page.getByRole('textbox', { name: 'Brukernavn' }).fill('ola'); + await page.getByLabel('Passord').fill('feilpassord'); + const submit = page.getByRole('main').getByRole('button', { name: 'Logg inn' }); + await submit.focus(); + await page.keyboard.press('Enter'); + + await expect(page.getByRole('alert')).toHaveText('Feil brukernavn eller passord.'); + await expect(submit).toBeFocused(); + }); + + test('fokus går til overskriften når skjemaet byttes til «Lag bruker»', async ({ page }) => { + await page.goto('./konto'); + await page.getByRole('button', { name: 'Lag bruker' }).click(); + + await expect(heading(page)).toHaveText('Lag bruker'); + await expect(heading(page)).toBeFocused(); + await expect(page).toHaveTitle('Lag bruker – Kork & Krone'); + }); + + for (const [name, path, title] of [ + ['innlogging', './konto', 'Logg inn'], + ['Mine anmeldelser uten lagrede viner', './mine', 'Mine anmeldelser'], + ['søk uten treff', './sok?q=finnesikke', 'Utforsk viner'], + ['siden som ikke finnes', './finnesikke', 'Fant ikke siden'], + ]) { + test(`har ingen axe-brudd: ${name}`, async ({ page }) => { + await page.goto(path); + await expect(heading(page)).toHaveText(title); + await expectNoAxeViolations(page); + }); + } +}); diff --git a/frontend/src/features/auth/AccountPage.test.tsx b/frontend/src/features/auth/AccountPage.test.tsx index ed765c0..8dc961f 100644 --- a/frontend/src/features/auth/AccountPage.test.tsx +++ b/frontend/src/features/auth/AccountPage.test.tsx @@ -93,6 +93,11 @@ describe('AccountPage', () => { expect(screen.getByRole('heading', { level: 1, name: 'Lag bruker' })).toHaveFocus(); expect(document.title).toBe('Lag bruker – Kork & Krone'); + // The rules are read together with the fields, not only seen under them. + expect(screen.getByLabelText('Brukernavn')).toHaveAccessibleDescription( + '3–30 tegn: små bokstaver, tall og understrek.', + ); + expect(screen.getByLabelText('Passord')).toHaveAccessibleDescription('Minst 8 tegn.'); }); it('explains which rule the username broke', async () => { diff --git a/frontend/src/features/auth/components/AuthForm.tsx b/frontend/src/features/auth/components/AuthForm.tsx index 304b6e9..2a178ff 100644 --- a/frontend/src/features/auth/components/AuthForm.tsx +++ b/frontend/src/features/auth/components/AuthForm.tsx @@ -23,6 +23,7 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) { const usernameId = useId(); const passwordId = useId(); const helpId = useId(); + const passwordHelpId = useId(); async function handleSubmit(event: FormEvent) { event.preventDefault(); @@ -69,9 +70,14 @@ export function AuthForm({ mode, onSubmit }: AuthFormProps) { autoComplete={mode === 'login' ? 'current-password' : 'new-password'} minLength={mode === 'register' ? PASSWORD_MIN_LENGTH : undefined} maxLength={PASSWORD_MAX_LENGTH} + aria-describedby={mode === 'register' ? passwordHelpId : undefined} required /> - {mode === 'register' &&

        Minst {PASSWORD_MIN_LENGTH} tegn.

        } + {mode === 'register' && ( +

        + Minst {PASSWORD_MIN_LENGTH} tegn. +

        + )}
      {/* Always in the DOM, so screen readers announce the message when it appears. */} diff --git a/frontend/src/features/my/MyView.tsx b/frontend/src/features/my/MyView.tsx index ac1f5f4..360906b 100644 --- a/frontend/src/features/my/MyView.tsx +++ b/frontend/src/features/my/MyView.tsx @@ -1,7 +1,9 @@ +import { useEffect, useRef, useState } from 'react'; import { Link } from 'react-router'; import { ErrorNotice } from '../../components/ui/ErrorNotice'; import { Skeleton } from '../../components/ui/Skeleton'; import { WineList } from '../../components/ui/WineList'; +import { focusIfLost } from '../../lib/focus'; import { pluralize } from '../../lib/format'; import { buildSearchUrl } from '../../lib/searchParams'; import type { WishlistResult } from './api/useWishlistWines'; @@ -9,15 +11,40 @@ import styles from './MyView.module.css'; /** Presentation of «Mine anmeldelser». The list lives in the browser until we have login. */ export function MyView({ wines, savedCount, loading, error, refetch }: WishlistResult) { + const headingRef = useRef(null); + const [previousCount, setPreviousCount] = useState(savedCount); + const [message, setMessage] = useState(''); + + // A wine removed with its heart disappears from the list, and the button with it. + // Saying so in the live region tells screen reader users that the click worked. + if (savedCount !== previousCount) { + setPreviousCount(savedCount); + setMessage( + savedCount < previousCount + ? `Fjernet fra listen. ${savedCount === 0 ? 'Listen er tom.' : `${pluralize(savedCount, 'vin', 'viner')} igjen.`}` + : '', + ); + } + + // The removed card had focus, so it moves to the heading of the list. + const countBefore = useRef(savedCount); + useEffect(() => { + const removed = savedCount < countBefore.current; + countBefore.current = savedCount; + if (removed) focusIfLost(headingRef.current); + }, [savedCount]); + return (

      Mine anmeldelser

      -

      Vil prøve

      +

      + Vil prøve +

      - {loading ? 'Laster viner …' : ''} + {loading ? 'Laster viner …' : message}

      {savedCount === 0 ? ( From cc81c93d2d8f563b3aab993576a57ef7949122b9 Mon Sep 17 00:00:00 2001 From: William Mikal Ruud Schmidt Date: Mon, 16 Nov 2026 23:49:55 +0100 Subject: [PATCH 4/4] Final voiceover report --- README.md | 2 +- docs/screen-reader.md | 53 ++- docs/voiceover-report.md | 233 +++++++++++ frontend/package-lock.json | 97 +++++ frontend/package.json | 4 +- frontend/scripts/voiceover.mjs | 387 ++++++++++++++++++ frontend/src/components/ui/WineList.tsx | 10 +- .../landing/components/CategoryList.tsx | 2 +- .../src/features/landing/components/Hero.tsx | 2 +- .../landing/components/HowItWorks.tsx | 2 +- .../landing/components/RecentReviews.tsx | 2 +- .../search/components/ActiveFilters.tsx | 2 +- .../search/components/FilterPanel.tsx | 2 +- .../features/search/components/NoResults.tsx | 2 +- frontend/src/features/wine/WineView.tsx | 2 +- .../wine/components/RatingDistribution.tsx | 2 +- .../wine/components/StudentReviews.tsx | 2 +- frontend/src/test/listRoles.test.ts | 29 ++ 18 files changed, 815 insertions(+), 20 deletions(-) create mode 100644 docs/voiceover-report.md create mode 100644 frontend/scripts/voiceover.mjs create mode 100644 frontend/src/test/listRoles.test.ts diff --git a/README.md b/README.md index ba50433..ea331e7 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,7 @@ Our goal is WCAG 2.1 level AA. We design for users with reduced vision, hearing, ### Some known gaps -- The manual test with VoiceOver has not been run yet. The script is in [screen reader testing](docs/screen-reader.md). +- VoiceOver has been run automated (11 of 15 steps passed, see the [VoiceOver report](docs/voiceover-report.md)), but not yet by hand. Empty required fields are read as «invalid data» before the user has done anything. See [screen reader testing](docs/screen-reader.md). - eslint-plugin-jsx-a11y is not set up yet. ## Sustainability diff --git a/docs/screen-reader.md b/docs/screen-reader.md index 9d41c11..ec73deb 100644 --- a/docs/screen-reader.md +++ b/docs/screen-reader.md @@ -4,10 +4,11 @@ How we test Kork & Krone with a screen reader, what we found, and what is still ## How we test -Two parts, because neither is enough on its own. +Three parts, because none is enough on its own. 1. **The accessibility tree, automated.** A screen reader reads the accessibility tree that the browser builds from the page, not the page itself. We read that tree for every page and step through each flow in Chromium (Playwright), and record after every action where focus is and what the live regions say. The flows that matter are in `frontend/e2e/screenreader.spec.ts`, so they stay fixed. -2. **A real screen reader, by hand.** The automated checks cannot tell how a screen reader phrases things, or whether it reads something twice. That needs a person with VoiceOver, using the script below. +2. **The real VoiceOver, automated.** `npm run voiceover` runs the script below with VoiceOver and records what it says. The result is in the [VoiceOver report](voiceover-report.md). This shows how VoiceOver phrases things and whether live regions are announced, which the accessibility tree cannot. +3. **A person with VoiceOver.** The automated run cannot judge whether something is understandable, too long or annoying. Someone in the group goes through the script by hand before each submission. ## What we found and fixed @@ -27,9 +28,27 @@ Found by stepping through the flows. Each one has a test that fails without the Checked and fine: landmarks, one h1 per page, focus on the h1 after navigation, page titles, names on all buttons and form fields, «Vil prøve» as a toggle button (`aria-pressed`), the star rating as ten radio buttons, star ratings as text, the filter dialog (focus inside, Escape closes, focus back to the button), «Last inn flere» (focus on the first new wine), and the live regions for search results, loading and errors. +## Automated test with VoiceOver + +[Guidepup](https://www.guidepup.dev/) controls VoiceOver and records every phrase it says. Playwright opens the app in WebKit, the engine in Safari, and moves focus and presses keys like a keyboard user. Each step in the script below has the phrases we expect, and the report marks the steps that did not say them. Only on macOS. + +Once per machine, in your own terminal, from `frontend/` after `npm install`: + + npx @guidepup/setup setup + npx @guidepup/setup install voiceover + +The first command lets VoiceOver be controlled with AppleScript, and asks for Accessibility and Automation permission for the terminal (or the app that runs the command). The second downloads the VoiceOver settings that Guidepup uses during the run, and only works where `@guidepup/guidepup` is installed, which is why it runs from `frontend/`. Your own VoiceOver settings are put back afterwards. + +Then start the backend and the dev server, and run from `frontend/`: + + npm run voiceover # all steps + npm run voiceover -- 5,9 # only steps 5 and 9 + +VoiceOver talks while it runs, and the keyboard and mouse should be left alone until it is done. The report is written to [docs/voiceover-report.md](voiceover-report.md). Commit it, so the latest result is in the repository. + ## Manual test with VoiceOver -Use VoiceOver on macOS with **Safari**, the combination most VoiceOver users have. Test against the production build (`npm run build && npm run preview` in `frontend/`) or the VM. +Use VoiceOver on macOS with **Safari**, the combination most VoiceOver users have. Test against the dev server with the backend running, or against the VM. `npm run preview` has no API proxy, so the data does not load there. - Turn VoiceOver on and off: Cmd + F5. - VO is Ctrl + Option. VO + arrow keys read the next or previous item. @@ -58,8 +77,30 @@ For each step, write down what VoiceOver says if it differs from the expected re ### Results -| Date | Who | Browser and screen reader | Result | -| ---- | --- | -------------------------- | ----------- | -| | | Safari + VoiceOver (macOS) | Not run yet | +| Date | How | Browser and screen reader | Result | +| ----------- | ------------------------------ | ----------------------------------- | ------------------------------------------------------------- | +| 16 Nov 2026 | Automated, `npm run voiceover` | WebKit 27.2 + VoiceOver, macOS 26.6 | 11 of 15 steps passed. See the [report](voiceover-report.md). | +| | By hand | Safari + VoiceOver (macOS) | Not run yet | + +## What the VoiceOver run found + +Fixed: + +- **Lists were not read as lists.** Safari and VoiceOver ignore the list role on a `
        ` or `
          ` without bullets (`list-style: none`), unless it is inside `