Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
29 changes: 29 additions & 0 deletions apps/web/src/components/shell/AppShell/AppShell.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,33 @@
),
var(--color-bg-page);
}

/* Off-screen until it receives keyboard focus, then shown top left. */
.app-shell__skip-link {
position: absolute;
z-index: var(--z-modal);
top: var(--space-2);
left: var(--space-2);

padding: var(--space-2) var(--space-4);

border-radius: var(--radius-md);

color: var(--color-text-inverse);
background-color: var(--color-text-primary);

font-weight: var(--font-weight-semibold);
text-decoration: none;

transform: translateY(calc(-100% - var(--space-4)));
}

.app-shell__skip-link:focus {
transform: none;
}

/* Main is only focused as a skip-link or navigation target, not typed in. */
.app-shell main:focus {
outline: none;
}
}
40 changes: 38 additions & 2 deletions apps/web/src/components/shell/AppShell/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,49 @@
import { Outlet } from 'react-router-dom';
import { useEffect, useRef } from 'react';
import { Outlet, useLocation } from 'react-router-dom';

import SiteHeader from '../SiteHeader/SiteHeader';
import './AppShell.css';

function AppShell() {
const { pathname } = useLocation();
const previousPathname = useRef(pathname);

/*
* After client-side navigation to another page, move focus to the main
* content (and the view to the top), as a full page load would. Screen
* readers then start reading the new page instead of staying on the link
* that was activated. Skipped on the first load, for changes that only
* touch the query string (search, filters, paging keep their own focus),
* and while a dialog is open.
*/
useEffect(() => {
if (previousPathname.current === pathname) return;
previousPathname.current = pathname;
if (document.querySelector('dialog[open], [role="dialog"]')) return;
window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
document.getElementById('main-content')?.focus({ preventScroll: true });
}, [pathname]);

return (
<div className="app-shell">
{/*
* First focusable element: lets keyboard users skip the header.
* Hidden until focused (AppShell.css). Main is focusable (tabIndex -1)
* so focus actually moves there, not only the scroll position.
*/}
<a
className="app-shell__skip-link"
href="#main-content"
onClick={(event) => {
// Focus main directly instead of adding #main-content to the URL.
event.preventDefault();
document.getElementById('main-content')?.focus();
}}
>
Skip to main content
</a>
<SiteHeader />
<main className="container">
<main id="main-content" className="container" tabIndex={-1}>
<Outlet />
</main>
</div>
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/features/auth/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import { loginSchema, fieldErrors } from '@t31/validation';
import { useState, type FormEvent } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
Expand All @@ -15,6 +16,7 @@ interface LoginErrors {
}

function LoginPage() {
usePageTitle('Log in');
const navigate = useNavigate();
const location = useLocation();
const returnPath = getAuthReturnPath(location.state);
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/features/auth/RegisterPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import { registerFormSchema, fieldErrors } from '@t31/validation';
import { useState, type FormEvent } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
Expand All @@ -17,6 +18,7 @@ interface RegisterErrors {
}

function RegisterPage() {
usePageTitle('Register');
const navigate = useNavigate();
const location = useLocation();
const returnPath = getAuthReturnPath(location.state);
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/features/cookbook/CookbookPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
Expand Down Expand Up @@ -44,6 +45,7 @@ import RecipeQueryStatus from '../recipes/RecipeQueryStatus';
import './CookbookPage.css';

function CookbookPage() {
usePageTitle('My Cookbook');
const searchInputRef = useRef<HTMLInputElement>(null);

const [searchParams, setSearchParams] = useSearchParams();
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/features/explore/ExplorePage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
Expand Down Expand Up @@ -48,6 +49,7 @@ type SaveFeedback = {
};

function ExplorePage() {
usePageTitle('Explore recipes');
const searchInputRef = useRef<HTMLInputElement>(null);

const [searchParams, setSearchParams] = useSearchParams();
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/features/not-found/NotFoundPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import { useNavigate } from 'react-router-dom';

import Button from '../../components/ui/Button/Button';
Expand All @@ -7,6 +8,7 @@ import chefHatIllustration from '../../assets/illustrations/not-found-chef-hat.w
import './NotFoundPage.css';

function NotFoundPage() {
usePageTitle('Page not found');
const navigate = useNavigate();

function handleGoBack() {
Expand Down
5 changes: 5 additions & 0 deletions apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import { useCallback, useEffect, useRef, useState } from 'react';

import { useLocation, useNavigate, useParams } from 'react-router-dom';
Expand Down Expand Up @@ -711,6 +712,10 @@ function RecipeDetailPage() {
[id],
);
const query = useRecipeQuery(id ?? '', load);
usePageTitle(
query.data?.title ??
(query.loading || query.error ? 'Recipe' : 'Recipe not found'),
);
if (query.loading || query.error)
return <RecipeQueryStatus {...query} label="Loading recipe…" />;
const recipe = query.data;
Expand Down
4 changes: 4 additions & 0 deletions apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
Expand Down Expand Up @@ -70,6 +71,7 @@ function moveItem<T>(items: T[], fromIndex: number, toIndex: number) {
}

function RecipeEditor({ recipe }: { recipe?: Recipe }) {
usePageTitle(recipe ? `Edit ${recipe.title}` : 'Add recipe');
const navigate = useNavigate();
const busyRef = useRef(false);
const [pending, setPending] = useState(false);
Expand Down Expand Up @@ -871,6 +873,8 @@ function RecipeEditPage({ id }: { id: string }) {
[id],
);
const query = useRecipeQuery(id, load, { refreshOnMutation: false });
// RecipeEditor sets the specific title once the recipe has loaded.
usePageTitle('Edit recipe');
if (query.loading || query.error)
return <RecipeQueryStatus {...query} label="Loading recipe for editing…" />;
if (!query.data)
Expand Down
14 changes: 14 additions & 0 deletions apps/web/src/lib/usePageTitle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { useEffect } from 'react';

const APP_NAME = 'Recipe Platform';

/**
* Sets the browser tab title for the current page, e.g.
* "My Cookbook – Recipe Platform". Screen readers announce the title after
* navigation, so every route should call this (WCAG 2.4.2 Page Titled).
*/
export function usePageTitle(title: string | null) {
useEffect(() => {
document.title = title ? `${title} – ${APP_NAME}` : APP_NAME;
}, [title]);
}
53 changes: 53 additions & 0 deletions e2e/smoke.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,56 @@ test('keeps recipe-specific not-found handling separate from the global 404', as
page.getByRole('heading', { name: 'Page not found' }),
).not.toBeVisible();
});

test('skip link is the first tab stop, visible on focus, and moves focus to main', async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto('.');
await expect(
page.getByRole('heading', { name: 'Explore Recipes' }),
).toBeVisible();
const skip = page.getByRole('link', { name: 'Skip to main content' });
await expect(skip).not.toBeInViewport();
await page.keyboard.press('Tab');
await expect(skip).toBeFocused();
await expect(skip).toBeInViewport();
// Light text on the dark text colour: well above the 4.5:1 AA minimum.
await expect(skip).toHaveCSS('color', 'rgb(255, 255, 255)');
await expect(skip).toHaveCSS('background-color', 'rgb(15, 23, 42)');
await page.keyboard.press('Enter');
await expect(page.locator('main#main-content')).toBeFocused();
await expect(page).not.toHaveURL(/#main-content/);
// The next Tab continues inside the page content, not in the header.
await page.keyboard.press('Tab');
expect(
await page.evaluate(() => Boolean(document.activeElement?.closest('main'))),
).toBe(true);
});

test('sets page titles and moves focus to main only when the page changes', async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto('.');
await expect(page).toHaveTitle('Explore recipes – Recipe Platform');
// Searching only changes the query string: focus stays in the search box.
const search = page.getByRole('searchbox');
await search.fill('pasta');
await search.press('Enter');
await expect(page).toHaveURL(/q=pasta/);
await expect(search).toBeFocused();
// Opening a recipe is a new page: title and focus follow.
await page.getByRole('link', { name: 'Creamy salmon pasta' }).click();
await expect(page).toHaveTitle('Creamy salmon pasta – Recipe Platform');
await expect(page.locator('main#main-content')).toBeFocused();
for (const [path, title] of [
['login', 'Log in'],
['register', 'Register'],
['recipes/42', 'Recipe not found'],
['no-such-page', 'Page not found'],
]) {
await page.goto(path);
await expect(page).toHaveTitle(`${title} – Recipe Platform`);
}
});