diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.css b/apps/web/src/features/recipe-detail/RecipeDetailPage.css index f990c2a..04b5ab5 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.css +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.css @@ -230,6 +230,9 @@ display: flex; align-items: center; justify-content: space-between; + + /* "Jump to recipe" scrolls here; keep it clear of the sticky header. */ + scroll-margin-top: var(--space-16); gap: var(--space-4); padding: var(--space-4); diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx index 79fbba2..ea1bbd8 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx @@ -2,7 +2,7 @@ import '@testing-library/jest-dom/vitest'; import { render, screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; -import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest'; import { apiRecipe, apiUser, @@ -140,6 +140,63 @@ it('keeps a failed rating editable and refreshes the persisted rating after retr await screen.findByRole('button', { name: 'Rate Recipe' }), ).toBeTruthy(); }); +function mockJumpScrolling() { + // jsdom has no scrollIntoView; provide one for this test only. + const originalScroll = Element.prototype.scrollIntoView; + const scrollIntoView = vi.fn(); + Element.prototype.scrollIntoView = scrollIntoView; + onTestFinished(() => { + Element.prototype.scrollIntoView = originalScroll; + }); + vi.stubGlobal( + 'matchMedia', + vi.fn((query: string) => ({ + matches: query === '(prefers-reduced-motion: reduce)', + })), + ); + return scrollIntoView; +} +it('jumps to the visible servings control, and Tab continues to its buttons', async () => { + const scrollIntoView = mockJumpScrolling(); + mockRecipeFetch(() => ({ data: { recipe: apiRecipe } })); + mount(); + await screen.findByRole('heading', { name: 'API soup' }); + // jsdom applies no CSS; mark the desktop copy as the rendered one. + const [mobile, desktop] = screen.getAllByRole('region', { + name: 'Adjust Servings', + }); + vi.spyOn(desktop!, 'getClientRects').mockReturnValue([ + new DOMRect(0, 0, 100, 100), + ] as unknown as DOMRectList); + const user = userEvent.setup(); + await user.click(screen.getByRole('button', { name: 'Jump to recipe' })); + expect(scrollIntoView).toHaveBeenCalledWith({ + behavior: 'auto', + block: 'start', + }); + expect(scrollIntoView.mock.contexts[0]).toBe(desktop); + expect(document.activeElement).toBe( + within(desktop!).getByRole('heading', { name: 'Adjust Servings' }), + ); + expect(mobile!.contains(document.activeElement)).toBe(false); + // Tab stays in the recipe: next come the servings buttons. + await user.tab(); + expect(document.activeElement).toBe( + within(desktop!).getByRole('button', { name: 'Decrease servings' }), + ); +}); +it('falls back to the ingredients heading when no servings control is rendered', async () => { + mockJumpScrolling(); + mockRecipeFetch(() => ({ data: { recipe: apiRecipe } })); + mount(); + await screen.findByRole('heading', { name: 'API soup' }); + await userEvent + .setup() + .click(screen.getByRole('button', { name: 'Jump to recipe' })); + expect(document.activeElement).toBe( + screen.getByRole('heading', { name: 'Ingredients' }), + ); +}); it('scales beyond 20 servings and accepts a typed number within the API limits', async () => { mockRecipeFetch(() => ({ data: { recipe: { ...apiRecipe, servings: 40 } } })); mount(); diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx index 69da68c..7d25909 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -93,6 +93,8 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { const [busy, setBusy] = useState(false); const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false); const [selectedServings, setSelectedServings] = useState(recipe.servings); + const mobileServingsRef = useRef(null); + const desktopServingsRef = useRef(null); const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false); const [feedback, setFeedback] = useState(null); const [showAllTags, setShowAllTags] = useState(false); @@ -151,11 +153,34 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { navigate(fallbackPath); } + /* + * The recipe starts at "Adjust Servings": it is directly above the + * ingredients and is the one control that acts on them. Jumping scrolls + * there and moves keyboard focus to its heading, so screen readers + * announce where the user landed and Tab continues to the servings + * buttons instead of leaving the recipe (the ingredient and step lists + * are text, read rather than tabbed through). The control exists twice, + * one copy per layout, and CSS hides the other; focusing a hidden element + * does nothing, so the rendered copy is picked. Smooth scrolling is + * skipped when the user prefers less motion. + */ function handleJumpToRecipe() { - document.getElementById('recipe-detail-recipe')?.scrollIntoView({ - behavior: 'smooth', + const reduceMotion = window.matchMedia?.( + '(prefers-reduced-motion: reduce)', + ).matches; + const servings = [ + mobileServingsRef.current, + desktopServingsRef.current, + ].find((section) => section && section.getClientRects().length > 0); + const target = servings ?? document.getElementById('recipe-detail-recipe'); + target?.scrollIntoView({ + behavior: reduceMotion ? 'auto' : 'smooth', block: 'start', }); + ( + servings?.querySelector('h2') ?? + document.getElementById('recipe-detail-ingredients-title') + )?.focus({ preventScroll: true }); } function openRating() { @@ -430,11 +455,14 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
-

Adjust Servings

+

+ Adjust Servings +

Ingredient amounts update automatically.

@@ -458,11 +486,14 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
-

Adjust Servings

+

+ Adjust Servings +

Ingredient amounts update automatically.

@@ -483,7 +514,9 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { aria-labelledby="recipe-detail-ingredients-title" >
-

Ingredients

+

+ Ingredients +

{selectedServings}{' '} diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index a124ce5..c02514d 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -395,6 +395,75 @@ test('keeps recipe-specific not-found handling separate from the global 404', as ).not.toBeVisible(); }); +for (const viewport of [ + { name: 'desktop', width: 1280, height: 800 }, + { name: 'mobile', width: 390, height: 844 }, +]) { + test(`Jump to recipe keeps keyboard focus in the recipe (${viewport.name})`, async ({ + page, + }) => { + await page.setViewportSize(viewport); + // A recipe long enough that jumping has to scroll. + const longRecipe: RecipeFieldsFragment = { + ...recipe, + description: 'A long description. '.repeat(30), + ingredients: Array.from({ length: 12 }, (_, index) => ({ + id: `ingredient-${index}`, + name: `Ingredient ${index + 1}`, + amount: index + 1, + unit: 'g', + note: null, + })), + instructions: Array.from({ length: 8 }, (_, index) => ({ + step: index + 1, + text: 'Stir and simmer for a while. '.repeat(6), + })), + }; + await page.route('**/project2/api/graphql', async (route) => { + const body = route.request().postDataJSON() as { query?: string }; + await route.fulfill({ + json: body.query?.includes('currentUser') + ? { data: { currentUser: null } } + : { data: { recipe: longRecipe } }, + }); + }); + await page.goto(`recipes/${recipe.id}`); + const jump = page.getByRole('button', { name: 'Jump to recipe' }); + await jump.focus(); + await page.keyboard.press('Enter'); + + // Focus lands on the visible "Adjust Servings" heading, just above the + // ingredients, in view and not hidden behind the sticky header. + const heading = page + .getByRole('heading', { name: 'Adjust Servings' }) + .locator('visible=true'); + await expect(heading).toBeFocused(); + await expect(heading).toBeInViewport(); + const header = await page.locator('header').first().boundingBox(); + await expect + .poll(async () => (await heading.boundingBox())!.y) + .toBeGreaterThanOrEqual(header!.y + header!.height); + + // Tab continues inside the recipe, through the servings control. + await page.keyboard.press('Tab'); + await expect( + page + .getByRole('button', { name: 'Decrease servings' }) + .locator('visible=true'), + ).toBeFocused(); + await page.keyboard.press('Tab'); + await expect( + page.getByLabel(/^Servings/).locator('visible=true'), + ).toBeFocused(); + await page.keyboard.press('Tab'); + await expect( + page + .getByRole('button', { name: 'Increase servings' }) + .locator('visible=true'), + ).toBeFocused(); + }); +} + test('skip link is the first tab stop, visible on focus, and moves focus to main', async ({ page, }) => {