From 025f1ff9471eb433e199d22b34adf6a9eb655201 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 15:15:25 +0100 Subject: [PATCH 1/3] feat(a11y): add a skip-to-content link Keyboard users had to tab through the whole header on every page. A "Skip to main content" link is now the first tab stop: hidden until focused, then shown top left in white on the dark text colour. It moves focus to
without adding a hash to the URL. Browser test covers focus order, visibility, colours and the focus move. Closes #102 --- .../components/shell/AppShell/AppShell.css | 29 +++++++++++++++++++ .../components/shell/AppShell/AppShell.tsx | 18 +++++++++++- e2e/smoke.spec.ts | 26 +++++++++++++++++ 3 files changed, 72 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/shell/AppShell/AppShell.css b/apps/web/src/components/shell/AppShell/AppShell.css index e945a95..f2f2600 100644 --- a/apps/web/src/components/shell/AppShell/AppShell.css +++ b/apps/web/src/components/shell/AppShell/AppShell.css @@ -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; + } } diff --git a/apps/web/src/components/shell/AppShell/AppShell.tsx b/apps/web/src/components/shell/AppShell/AppShell.tsx index 195600a..f4cd171 100644 --- a/apps/web/src/components/shell/AppShell/AppShell.tsx +++ b/apps/web/src/components/shell/AppShell/AppShell.tsx @@ -6,8 +6,24 @@ import './AppShell.css'; function AppShell() { return (
+ {/* + * 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. + */} + { + // Focus main directly instead of adding #main-content to the URL. + event.preventDefault(); + document.getElementById('main-content')?.focus(); + }} + > + Skip to main content + -
+
diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 6b2ba23..68af88c 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -356,3 +356,29 @@ 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); +}); From 1bcfc3afea3f5040ad1b0069148b54d109e83d06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Mon, 16 Nov 2026 15:17:38 +0100 Subject: [PATCH 2/3] feat(a11y): set page titles and move focus to main on navigation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every page now sets a document title ("My Cookbook – Recipe Platform", the recipe's name on detail pages). When the pathname changes, AppShell scrolls to the top and moves focus to main, as a full page load would, so screen readers start on the new page. Not on first load, not for query string changes (search, filters, paging) and not while a dialog is open. Closes #103 --- .../components/shell/AppShell/AppShell.tsx | 22 ++++++++++++++- apps/web/src/features/auth/LoginPage.tsx | 2 ++ apps/web/src/features/auth/RegisterPage.tsx | 2 ++ .../src/features/cookbook/CookbookPage.tsx | 2 ++ apps/web/src/features/explore/ExplorePage.tsx | 2 ++ .../src/features/not-found/NotFoundPage.tsx | 2 ++ .../recipe-detail/RecipeDetailPage.tsx | 5 ++++ .../src/features/recipes/RecipeCreatePage.tsx | 4 +++ apps/web/src/lib/usePageTitle.ts | 14 ++++++++++ e2e/smoke.spec.ts | 27 +++++++++++++++++++ 10 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/lib/usePageTitle.ts diff --git a/apps/web/src/components/shell/AppShell/AppShell.tsx b/apps/web/src/components/shell/AppShell/AppShell.tsx index f4cd171..6a55de0 100644 --- a/apps/web/src/components/shell/AppShell/AppShell.tsx +++ b/apps/web/src/components/shell/AppShell/AppShell.tsx @@ -1,9 +1,29 @@ -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 (
{/* 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/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx index bf753b4..13b5a6b 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 [searchParams, setSearchParams] = useSearchParams(); diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx index f5e486c..be5e3bd 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 [searchParams, setSearchParams] = useSearchParams(); 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 384750d..d98ae8b 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'; @@ -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 ; const recipe = query.data; diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 625399f..67f26d2 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -1,3 +1,4 @@ +import { usePageTitle } from '../../lib/usePageTitle'; import { useCallback, useEffect, @@ -70,6 +71,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); @@ -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 ; if (!query.data) diff --git a/apps/web/src/lib/usePageTitle.ts b/apps/web/src/lib/usePageTitle.ts new file mode 100644 index 0000000..4200fe2 --- /dev/null +++ b/apps/web/src/lib/usePageTitle.ts @@ -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]); +} diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index 68af88c..bb6026b 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -382,3 +382,30 @@ test('skip link is the first tab stop, visible on focus, and moves focus to main 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`); + } +}); From 177a8ae89686cb61816b97105ae33cb1da4c2048 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 01:03:23 +0100 Subject: [PATCH 3/3] fix(a11y): keep Back/Forward scroll position; title auth and edit error states - AppShell no longer scrolls to the top on Back/Forward (POP), so the browser's restored position is kept; focus still moves to main. - RequireAuth titles its own states ("Restoring session", "Session could not be restored"), so a protected page that cannot render no longer keeps the previous page's title. - The edit page titles each state: "Recipe could not be loaded", "Recipe unavailable", "Cannot edit recipe"; "Edit " only when editing. A PageTitle component sets titles from such branches, since a parent's unconditional usePageTitle would override the child page's. --- .../components/shell/AppShell/AppShell.tsx | 11 ++-- .../src/features/auth/RequireAuth.test.tsx | 24 ++++++++ apps/web/src/features/auth/RequireAuth.tsx | 9 ++- .../recipes/RecipeCreatePage.test.tsx | 24 ++++++++ .../src/features/recipes/RecipeCreatePage.tsx | 16 +++-- apps/web/src/lib/usePageTitle.ts | 11 ++++ e2e/smoke.spec.ts | 61 +++++++++++++++++++ 7 files changed, 147 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/shell/AppShell/AppShell.tsx b/apps/web/src/components/shell/AppShell/AppShell.tsx index 6a55de0..f7d6143 100644 --- a/apps/web/src/components/shell/AppShell/AppShell.tsx +++ b/apps/web/src/components/shell/AppShell/AppShell.tsx @@ -1,11 +1,12 @@ import { useEffect, useRef } from 'react'; -import { Outlet, useLocation } from 'react-router-dom'; +import { Outlet, useLocation, useNavigationType } from 'react-router-dom'; import SiteHeader from '../SiteHeader/SiteHeader'; import './AppShell.css'; function AppShell() { const { pathname } = useLocation(); + const navigationType = useNavigationType(); const previousPathname = useRef(pathname); /* @@ -14,15 +15,17 @@ function AppShell() { * 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. + * 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; - window.scrollTo({ top: 0, left: 0, behavior: 'auto' }); + if (navigationType !== 'POP') + window.scrollTo({ top: 0, left: 0, behavior: 'auto' }); document.getElementById('main-content')?.focus({ preventScroll: true }); - }, [pathname]); + }, [pathname, navigationType]); return ( <div className="app-shell"> diff --git a/apps/web/src/features/auth/RequireAuth.test.tsx b/apps/web/src/features/auth/RequireAuth.test.tsx index a1d760b..c5235d1 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 <p role="status">Restoring your session...</p>; + return ( + <> + <PageTitle title="Restoring session" /> + <p role="status">Restoring your session...</p> + </> + ); } if (sessionStatus === 'error') { return ( <div> + <PageTitle title="Session could not be restored" /> <FeedbackMessage tone="error"> Unable to restore your session. Check your connection and try again. </FeedbackMessage> diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index b05c11c..43f5d8f 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -346,3 +346,27 @@ it('does not fetch or reset the new recipe form after list invalidation', () => expect(title).toHaveValue('New draft'); expect(fetch).not.toHaveBeenCalled(); }); + +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 67f26d2..a54289b 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -1,4 +1,4 @@ -import { usePageTitle } from '../../lib/usePageTitle'; +import { PageTitle, usePageTitle } from '../../lib/usePageTitle'; import { useCallback, useEffect, @@ -873,13 +873,20 @@ 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'); + // Each state sets its own title; RecipeEditor sets "Edit <title>". if (query.loading || query.error) - return <RecipeQueryStatus {...query} label="Loading recipe for editing…" />; + return ( + <> + <PageTitle + title={query.error ? 'Recipe could not be loaded' : 'Edit recipe'} + /> + <RecipeQueryStatus {...query} label="Loading recipe for editing…" /> + </> + ); if (!query.data) return ( <section> + <PageTitle title="Recipe unavailable" /> <h1>Recipe unavailable</h1> <p>This recipe does not exist or is not available to you.</p> <LinkButton to="/cookbook">Back to My Cookbook</LinkButton> @@ -888,6 +895,7 @@ function RecipeEditPage({ id }: { id: string }) { if (!query.data.isCreatedByCurrentUser) return ( <section> + <PageTitle title="Cannot edit recipe" /> <h1>Cannot edit recipe</h1> <p>You can only edit your own recipes.</p> <LinkButton to="/cookbook">Back to My Cookbook</LinkButton> diff --git a/apps/web/src/lib/usePageTitle.ts b/apps/web/src/lib/usePageTitle.ts index 4200fe2..a35864b 100644 --- a/apps/web/src/lib/usePageTitle.ts +++ b/apps/web/src/lib/usePageTitle.ts @@ -12,3 +12,14 @@ export function usePageTitle(title: string | null) { 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 bb6026b..3fafc45 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -409,3 +409,64 @@ test('sets page titles and moves focus to main only when the page changes', asyn 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(); +});