diff --git a/apps/web/src/components/shell/AppShell/AppShell.tsx b/apps/web/src/components/shell/AppShell/AppShell.tsx
index d426645..cb2c7c0 100644
--- a/apps/web/src/components/shell/AppShell/AppShell.tsx
+++ b/apps/web/src/components/shell/AppShell/AppShell.tsx
@@ -1,11 +1,33 @@
-import { Suspense } from 'react';
-import { Outlet } from 'react-router-dom';
+import { Suspense, useEffect, useRef } from 'react';
+import { Outlet, useLocation, useNavigationType } from 'react-router-dom';
import LoadingIndicator from '../../ui/LoadingIndicator/LoadingIndicator';
import SiteHeader from '../SiteHeader/SiteHeader';
import './AppShell.css';
function AppShell() {
+ const { pathname } = useLocation();
+ const navigationType = useNavigationType();
+ 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. Back/Forward (POP) keeps the scroll position
+ * the browser restores, so the user returns to where they were.
+ */
+ useEffect(() => {
+ if (previousPathname.current === pathname) return;
+ previousPathname.current = pathname;
+ if (document.querySelector('dialog[open], [role="dialog"]')) return;
+ if (navigationType !== 'POP')
+ window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
+ document.getElementById('main-content')?.focus({ preventScroll: true });
+ }, [pathname, navigationType]);
+
return (
{/*
diff --git a/apps/web/src/features/auth/LoginPage.tsx b/apps/web/src/features/auth/LoginPage.tsx
index 34f07ca..d6f5414 100644
--- a/apps/web/src/features/auth/LoginPage.tsx
+++ b/apps/web/src/features/auth/LoginPage.tsx
@@ -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';
@@ -15,6 +16,7 @@ interface LoginErrors {
}
function LoginPage() {
+ usePageTitle('Log in');
const navigate = useNavigate();
const location = useLocation();
const returnPath = getAuthReturnPath(location.state);
diff --git a/apps/web/src/features/auth/RegisterPage.tsx b/apps/web/src/features/auth/RegisterPage.tsx
index 928fe56..cda385e 100644
--- a/apps/web/src/features/auth/RegisterPage.tsx
+++ b/apps/web/src/features/auth/RegisterPage.tsx
@@ -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';
@@ -17,6 +18,7 @@ interface RegisterErrors {
}
function RegisterPage() {
+ usePageTitle('Register');
const navigate = useNavigate();
const location = useLocation();
const returnPath = getAuthReturnPath(location.state);
diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx
index f2687cd..5af641b 100644
--- a/apps/web/src/features/auth/RequireAuth.test.tsx
+++ b/apps/web/src/features/auth/RequireAuth.test.tsx
@@ -111,6 +111,30 @@ describe('protected routes with session restoration', () => {
await screen.findByRole('heading', { name: 'Add Recipe' }),
).toBeInTheDocument();
});
+ it('titles the session states of a protected page, then the page itself', async () => {
+ document.title = 'Creamy salmon pasta – Recipe Platform';
+ let failRestore!: (error: Error) => void;
+ vi.mocked(getCurrentUser).mockReturnValue(
+ new Promise((_resolve, reject) => {
+ failRestore = reject;
+ }),
+ );
+ renderApp('/cookbook');
+ // Not the title of whatever page was open before.
+ expect(document.title).toBe('Restoring session – Recipe Platform');
+ await act(async () => failRestore(new Error('Offline')));
+ await screen.findByRole('alert');
+ expect(document.title).toBe(
+ 'Session could not be restored – Recipe Platform',
+ );
+
+ vi.mocked(getCurrentUser).mockResolvedValue(user);
+ await userEvent
+ .setup()
+ .click(screen.getByRole('button', { name: 'Try again' }));
+ await screen.findByRole('heading', { name: 'My Cookbook' });
+ expect(document.title).toBe('My Cookbook – Recipe Platform');
+ });
it.each([false, true])(
'returns to the requested URL after authentication (register=%s)',
async (register) => {
diff --git a/apps/web/src/features/auth/RequireAuth.tsx b/apps/web/src/features/auth/RequireAuth.tsx
index b1c8dcb..4ec0e05 100644
--- a/apps/web/src/features/auth/RequireAuth.tsx
+++ b/apps/web/src/features/auth/RequireAuth.tsx
@@ -2,6 +2,7 @@ import { Navigate, Outlet, useLocation } from 'react-router-dom';
import Button from '../../components/ui/Button/Button';
import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage';
import { useAppStore } from '../../store';
+import { PageTitle } from '../../lib/usePageTitle';
export default function RequireAuth() {
const location = useLocation();
@@ -10,11 +11,17 @@ export default function RequireAuth() {
const restoreSession = useAppStore((state) => state.restoreSession);
if (sessionStatus === 'restoring') {
- return
Restoring your session...
;
+ return (
+ <>
+
+
Restoring your session...
+ >
+ );
}
if (sessionStatus === 'error') {
return (
+
Unable to restore your session. Check your connection and try again.
diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx
index 2e22b67..6e02a48 100644
--- a/apps/web/src/features/cookbook/CookbookPage.tsx
+++ b/apps/web/src/features/cookbook/CookbookPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
@@ -44,6 +45,7 @@ import RecipeQueryStatus from '../recipes/RecipeQueryStatus';
import './CookbookPage.css';
function CookbookPage() {
+ usePageTitle('My Cookbook');
const searchInputRef = useRef
(null);
const resultCountRef = useRef(null);
diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx
index 69bcbf0..c658650 100644
--- a/apps/web/src/features/explore/ExplorePage.tsx
+++ b/apps/web/src/features/explore/ExplorePage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
@@ -48,6 +49,7 @@ type SaveFeedback = {
};
function ExplorePage() {
+ usePageTitle('Explore recipes');
const searchInputRef = useRef(null);
const resultCountRef = useRef(null);
diff --git a/apps/web/src/features/not-found/NotFoundPage.tsx b/apps/web/src/features/not-found/NotFoundPage.tsx
index ce4c6d9..c0e0679 100644
--- a/apps/web/src/features/not-found/NotFoundPage.tsx
+++ b/apps/web/src/features/not-found/NotFoundPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import { useNavigate } from 'react-router-dom';
import Button from '../../components/ui/Button/Button';
@@ -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() {
diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
index f7da3b9..69da68c 100644
--- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
+++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
@@ -1,3 +1,4 @@
+import { usePageTitle } from '../../lib/usePageTitle';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
@@ -641,6 +642,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 ;
const recipe = query.data;
diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx
index 77af37b..0427409 100644
--- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx
+++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx
@@ -420,3 +420,27 @@ it('reorders ingredients and steps with the keyboard, keeping focus and announci
'Step moved to position 1 of 2.',
);
});
+
+describe('edit page titles', () => {
+ it('names the state in the tab title: editing, not editable, or unavailable', async () => {
+ mockRecipeFetch(() => ({
+ data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true } },
+ }));
+ const owned = mount('/recipes/' + apiRecipe.id + '/edit');
+ await screen.findByRole('heading', { name: 'Edit Recipe' });
+ expect(document.title).toBe(`Edit ${apiRecipe.title} – Recipe Platform`);
+ owned.unmount();
+
+ mockRecipeFetch(() => ({
+ data: { recipe: { ...apiRecipe, id: crypto.randomUUID() } },
+ }));
+ const other = mount('/recipes/' + crypto.randomUUID() + '/edit');
+ await screen.findByRole('heading', { name: 'Cannot edit recipe' });
+ expect(document.title).toBe('Cannot edit recipe – Recipe Platform');
+ other.unmount();
+
+ mount('/recipes/abc/edit');
+ await screen.findByRole('heading', { name: 'Recipe unavailable' });
+ expect(document.title).toBe('Recipe unavailable – Recipe Platform');
+ });
+});
diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx
index e9907a4..3d929bf 100644
--- a/apps/web/src/features/recipes/RecipeCreatePage.tsx
+++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx
@@ -1,3 +1,4 @@
+import { PageTitle, usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
@@ -87,6 +88,7 @@ function moveItem(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);
@@ -977,11 +979,20 @@ function RecipeEditPage({ id }: { id: string }) {
[id],
);
const query = useRecipeQuery(id, load, { refreshOnMutation: false });
+ // Each state sets its own title; RecipeEditor sets "Edit ".
if (query.loading || query.error)
- return ;
+ return (
+ <>
+
+
+ >
+ );
if (!query.data)
return (
+
Recipe unavailable
This recipe does not exist or is not available to you.
Back to My Cookbook
@@ -990,6 +1001,7 @@ function RecipeEditPage({ id }: { id: string }) {
if (!query.data.isCreatedByCurrentUser)
return (
+
Cannot edit recipe
You can only edit your own recipes.
Back to My Cookbook
diff --git a/apps/web/src/lib/usePageTitle.ts b/apps/web/src/lib/usePageTitle.ts
new file mode 100644
index 0000000..a35864b
--- /dev/null
+++ b/apps/web/src/lib/usePageTitle.ts
@@ -0,0 +1,25 @@
+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]);
+}
+
+/**
+ * Sets the title for a state that renders instead of a page, such as a
+ * loading, error or access message. Render it only in that state: a parent
+ * calling usePageTitle unconditionally would run its effect after the
+ * child page's and overwrite the page's own title.
+ */
+export function PageTitle({ title }: { title: string }) {
+ usePageTitle(title);
+ return null;
+}
diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts
index 251bcfb..a124ce5 100644
--- a/e2e/smoke.spec.ts
+++ b/e2e/smoke.spec.ts
@@ -421,6 +421,94 @@ test('skip link is the first tab stop, visible on focus, and moves focus to 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`);
+ }
+});
+
+test('Back returns to the earlier scroll position; opening a page starts at the top', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 1280, height: 600 });
+ const recipes = Array.from({ length: 6 }, (_, index) => ({
+ ...recipe,
+ id: `11111111-1111-4111-8111-11111111111${index}`,
+ title: `Scroll recipe ${index + 1}`,
+ }));
+ await page.route('**/project2/api/graphql', async (route) => {
+ const body = route.request().postDataJSON() as {
+ query?: string;
+ variables?: { id?: string };
+ };
+ await route.fulfill({
+ json: body.query?.includes('currentUser')
+ ? { data: { currentUser: null } }
+ : body.query?.includes('query Recipes')
+ ? {
+ data: {
+ recipes: {
+ items: recipes,
+ totalCount: 6,
+ totalPages: 1,
+ page: 1,
+ pageSize: 6,
+ },
+ },
+ }
+ : {
+ data: {
+ recipe:
+ recipes.find((item) => item.id === body.variables?.id) ??
+ null,
+ },
+ },
+ });
+ });
+ await page.goto('.');
+ const last = page.getByRole('link', { name: 'Scroll recipe 6' });
+ await last.scrollIntoViewIfNeeded();
+ const scrolled = await page.evaluate(() => window.scrollY);
+ expect(scrolled).toBeGreaterThan(200);
+
+ await last.click();
+ await expect(
+ page.getByRole('heading', { name: 'Scroll recipe 6', level: 1 }),
+ ).toBeVisible();
+ // A new page opens at the top, with focus on main.
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
+ await expect(page.locator('main#main-content')).toBeFocused();
+
+ await page.goBack();
+ await expect(last).toBeVisible();
+ await expect
+ .poll(() => page.evaluate(() => window.scrollY))
+ .toBeGreaterThan(scrolled - 5);
+ expect(await page.evaluate(() => window.scrollY)).toBeLessThan(scrolled + 5);
+ await expect(page.locator('main#main-content')).toBeFocused();
+});
+
test('after the skip link on a scrolled page, the next control is not under the header', async ({
page,
}) => {