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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions apps/web/src/components/shell/AppShell/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<div className="app-shell">
{/*
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
24 changes: 24 additions & 0 deletions apps/web/src/features/auth/RequireAuth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
9 changes: 8 additions & 1 deletion apps/web/src/features/auth/RequireAuth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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>
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 resultCountRef = useRef<HTMLParagraphElement>(null);

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 resultCountRef = useRef<HTMLParagraphElement>(null);

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 @@ -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 <RecipeQueryStatus {...query} label="Loading recipe…" />;
const recipe = query.data;
Expand Down
24 changes: 24 additions & 0 deletions apps/web/src/features/recipes/RecipeCreatePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
14 changes: 13 additions & 1 deletion apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { PageTitle, usePageTitle } from '../../lib/usePageTitle';
import {
useCallback,
useEffect,
Expand Down Expand Up @@ -87,6 +88,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 @@ -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 <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>
Expand All @@ -990,6 +1001,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>
Expand Down
25 changes: 25 additions & 0 deletions apps/web/src/lib/usePageTitle.ts
Original file line number Diff line number Diff line change
@@ -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;
}
88 changes: 88 additions & 0 deletions e2e/smoke.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}) => {
Expand Down