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
3 changes: 3 additions & 0 deletions apps/web/src/features/recipe-detail/RecipeDetailPage.css
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
59 changes: 58 additions & 1 deletion apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down
43 changes: 38 additions & 5 deletions apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLElement>(null);
const desktopServingsRef = useRef<HTMLElement>(null);
const [confirmUnsaveOpen, setConfirmUnsaveOpen] = useState(false);
const [feedback, setFeedback] = useState<DetailFeedback | null>(null);
const [showAllTags, setShowAllTags] = useState(false);
Expand Down Expand Up @@ -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<HTMLElement>('h2') ??
document.getElementById('recipe-detail-ingredients-title')
)?.focus({ preventScroll: true });
}

function openRating() {
Expand Down Expand Up @@ -430,11 +455,14 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
</div>

<section
ref={mobileServingsRef}
className="recipe-detail-page__servings-control recipe-detail-page__servings-control--mobile"
aria-labelledby="recipe-detail-servings-title-mobile"
>
<div>
<h2 id="recipe-detail-servings-title-mobile">Adjust Servings</h2>
<h2 id="recipe-detail-servings-title-mobile" tabIndex={-1}>
Adjust Servings
</h2>

<p>Ingredient amounts update automatically.</p>
</div>
Expand All @@ -458,11 +486,14 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
</section>

<section
ref={desktopServingsRef}
className="recipe-detail-page__servings-control recipe-detail-page__servings-control--desktop"
aria-labelledby="recipe-detail-servings-title-desktop"
>
<div>
<h2 id="recipe-detail-servings-title-desktop">Adjust Servings</h2>
<h2 id="recipe-detail-servings-title-desktop" tabIndex={-1}>
Adjust Servings
</h2>

<p>Ingredient amounts update automatically.</p>
</div>
Expand All @@ -483,7 +514,9 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
aria-labelledby="recipe-detail-ingredients-title"
>
<div className="recipe-detail-page__section-heading">
<h2 id="recipe-detail-ingredients-title">Ingredients</h2>
<h2 id="recipe-detail-ingredients-title" tabIndex={-1}>
Ingredients
</h2>

<span>
{selectedServings}{' '}
Expand Down
69 changes: 69 additions & 0 deletions e2e/smoke.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}) => {
Expand Down