diff --git a/apps/web/src/features/auth/authNavigation.test.ts b/apps/web/src/features/auth/authNavigation.test.ts index 3203a41..61af532 100644 --- a/apps/web/src/features/auth/authNavigation.test.ts +++ b/apps/web/src/features/auth/authNavigation.test.ts @@ -12,13 +12,13 @@ describe('authentication return navigation', () => { { from: '/recipes/11111111-1111-4111-8111-111111111111/editor' }, { from: '/recipes/11111111-1111-4111-8111-111111111111/edit/../../x' }, { from: '//example.com/recipes/11111111-1111-4111-8111-111111111111/edit' }, - { from: '/recipes/11111111-1111-4111-8111-111111111111' }, ])('falls back for unsafe or unsupported state %j', (state) => { expect(getAuthReturnPath(state)).toBe('/'); }); it.each([ '/cookbook?view=saved#recipes', '/recipes/new', + '/recipes/11111111-1111-4111-8111-111111111111?view=full#ingredients', '/recipes/11111111-1111-4111-8111-111111111111/edit', ])('preserves protected destination %s', (from) => { expect(getAuthReturnPath({ from })).toBe(from); diff --git a/apps/web/src/features/auth/authNavigation.ts b/apps/web/src/features/auth/authNavigation.ts index 18e33fc..ea1ecfb 100644 --- a/apps/web/src/features/auth/authNavigation.ts +++ b/apps/web/src/features/auth/authNavigation.ts @@ -1,8 +1,8 @@ -// The recipe editor of one recipe id; nothing else under /recipes/. -const EDIT_ROUTE = - /^\/recipes\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\/edit$/; +// One recipe detail or editor route; nothing else under /recipes/. +const RECIPE_ROUTE = + /^\/recipes\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}(?:\/edit)?$/; -// Only return to known protected routes. Never navigate to a supplied origin. +// Only return to known recipe and protected routes. Never navigate to a supplied origin. export function getAuthReturnPath(state: unknown): string { if (typeof state !== 'object' || state === null || !('from' in state)) return '/'; @@ -11,7 +11,7 @@ export function getAuthReturnPath(state: unknown): string { const pathname = from.split(/[?#]/)[0] ?? ''; return pathname === '/cookbook' || pathname === '/recipes/new' || - EDIT_ROUTE.test(pathname) + RECIPE_ROUTE.test(pathname) ? from : '/'; } diff --git a/apps/web/src/features/cookbook/CookbookControls.css b/apps/web/src/features/cookbook/CookbookControls.css index e0de5fb..d526c79 100644 --- a/apps/web/src/features/cookbook/CookbookControls.css +++ b/apps/web/src/features/cookbook/CookbookControls.css @@ -15,7 +15,7 @@ .cookbook-controls__desktop { display: flex; flex-wrap: nowrap; - align-items: center; + align-items: flex-start; gap: var(--space-3); min-width: 0; @@ -61,8 +61,14 @@ width: 15.5rem; } - .cookbook-controls__custom-time-input { + .cookbook-controls__desktop-control--custom-time { + flex: 0 0 9rem; width: 9rem; + overflow-wrap: anywhere; + } + + .cookbook-controls__custom-time-input { + width: 100%; background-color: var(--color-surface-raised); border-color: var(--color-border-input); diff --git a/apps/web/src/features/cookbook/CookbookControls.tsx b/apps/web/src/features/cookbook/CookbookControls.tsx index 1f6d7bf..3992b18 100644 --- a/apps/web/src/features/cookbook/CookbookControls.tsx +++ b/apps/web/src/features/cookbook/CookbookControls.tsx @@ -1,7 +1,14 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; +import { + clampCustomTime, + customTimeError, + customTimeText, +} from '../../lib/recipeBrowse/browseValidation'; +import { useCustomTimeInput } from '../../lib/recipeBrowse/useCustomTimeInput'; import Button from '../../components/ui/Button/Button'; import Field from '../../components/ui/Field/Field'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; import FilterChip from '../../components/ui/FilterChip/FilterChip'; import { Icon } from '../../components/ui/Icon/Icon'; import Radio from '../../components/ui/Radio/Radio'; @@ -32,6 +39,7 @@ import { import './CookbookControls.css'; export type CookbookControlsProps = { + navigationKey?: string; scope: CookbookScope; browseState: CookbookBrowseState; onScopeChange: (scope: CookbookScope) => void; @@ -39,16 +47,6 @@ export type CookbookControlsProps = { onFiltersChange: (scope: CookbookScope, value: CookbookBrowseState) => void; }; -function parseCustomMaxMinutes(value: string) { - if (value.trim() === '') { - return null; - } - - const parsed = Number(value); - - return Number.isInteger(parsed) && parsed > 0 ? parsed : null; -} - function getScopeSelectLabel(scope: CookbookScope) { switch (scope) { case 'saved': @@ -65,12 +63,20 @@ function getScopeSelectLabel(scope: CookbookScope) { function CookbookControls({ scope, browseState, + navigationKey = '', onScopeChange, onBrowseStateChange, onFiltersChange, }: CookbookControlsProps) { const [filterSheetOpen, setFilterSheetOpen] = useState(false); const [sortSheetOpen, setSortSheetOpen] = useState(false); + const [focusMobileTime, setFocusMobileTime] = useState(false); + const desktopTimeRef = useRef(null); + const mobileTimeRef = useRef(null); + + useEffect(() => { + if (filterSheetOpen && focusMobileTime) mobileTimeRef.current?.focus(); + }, [filterSheetOpen, focusMobileTime]); const [scopeDraft, setScopeDraft] = useState(scope); @@ -81,7 +87,25 @@ function CookbookControls({ }); const [sortDraft, setSortDraft] = useState(browseState.sort); - const [showCustomTimeError, setShowCustomTimeError] = useState(false); + const [mobileTime, setMobileTime] = useState(''); + const resetKey = JSON.stringify([navigationKey, browseState, scope]); + const desktopTime = useCustomTimeInput( + browseState.customMaxMinutes, + resetKey, + (minutes, raw) => { + onBrowseStateChange({ + ...browseState, + cookingTime: 'custom', + customMaxMinutes: minutes, + customMaxMinutesRaw: raw, + }); + }, + browseState.customMaxMinutesRaw, + ); + const committedTimeError = + browseState.cookingTime === 'custom' + ? customTimeError(clampCustomTime(customTimeText(browseState))) + : undefined; const activeFilterCount = countActiveRecipeFilters(browseState) + (scope === 'all' ? 0 : 1); @@ -100,17 +124,13 @@ function CookbookControls({ cookingTime, customMaxMinutes: cookingTime === 'custom' ? browseState.customMaxMinutes : null, + customMaxMinutesRaw: + cookingTime === 'custom' ? browseState.customMaxMinutesRaw : undefined, }); } - function handleDesktopCustomMaxChange(rawValue: string) { - updateBrowseState({ - cookingTime: 'custom', - customMaxMinutes: parseCustomMaxMinutes(rawValue), - }); - } - - function openFilterSheet() { + function openFilterSheet(focusTime = false) { + setFocusMobileTime(focusTime); setScopeDraft(scope); setFilterDraft({ @@ -119,11 +139,13 @@ function CookbookControls({ customMaxMinutes: browseState.customMaxMinutes, }); - setShowCustomTimeError(false); + setMobileTime(customTimeText(browseState)); setFilterSheetOpen(true); } function handleDraftCookingTimeChange(cookingTime: RecipeCookingTime) { + if (cookingTime === filterDraft.cookingTime) return; + setFilterDraft((current) => ({ ...current, cookingTime, @@ -131,21 +153,26 @@ function CookbookControls({ cookingTime === 'custom' ? current.customMaxMinutes : null, })); - setShowCustomTimeError(false); + setMobileTime(''); } function handleApplyFilters() { - if ( - filterDraft.cookingTime === 'custom' && - filterDraft.customMaxMinutes === null - ) { - setShowCustomTimeError(true); + const clamped = clampCustomTime(mobileTime); + if (filterDraft.cookingTime === 'custom' && customTimeError(clamped)) { return; } onFiltersChange(scopeDraft, { ...browseState, ...filterDraft, + customMaxMinutes: + filterDraft.cookingTime === 'custom' && clamped.trim() + ? Number(clamped) + : null, + customMaxMinutesRaw: + filterDraft.cookingTime === 'custom' && customTimeError(mobileTime) + ? mobileTime + : undefined, }); setFilterSheetOpen(false); @@ -158,7 +185,15 @@ function CookbookControls({ ...DEFAULT_RECIPE_FILTER_STATE, }); - setShowCustomTimeError(false); + setMobileTime(''); + } + + function editTimeFilter() { + if (desktopTimeRef.current?.getClientRects().length) { + desktopTimeRef.current.focus(); + } else { + openFilterSheet(true); + } } function openSortSheet() { @@ -245,19 +280,25 @@ function CookbookControls({ {browseState.cookingTime === 'custom' && ( -
+
No time limit applied. + ) : undefined + } placeholder="Max minutes" onChange={(event) => - handleDesktopCustomMaxChange(event.currentTarget.value) + desktopTime.change(event.currentTarget.value) } />
@@ -290,7 +331,7 @@ function CookbookControls({
+ {committedTimeError && ( + +

+ Recipes cannot be loaded until the maximum cooking time is corrected + or cleared. +

+ +
+ )} + No time limit applied. + ) } - onChange={(event) => { - const customMaxMinutes = parseCustomMaxMinutes( - event.currentTarget.value, - ); - - setFilterDraft((current) => ({ - ...current, - cookingTime: 'custom', - customMaxMinutes, - })); - - setShowCustomTimeError(false); - }} + error={customTimeError(mobileTime)} + onChange={(event) => setMobileTime(event.currentTarget.value)} /> )} diff --git a/apps/web/src/features/cookbook/CookbookPage.css b/apps/web/src/features/cookbook/CookbookPage.css index 4ee1844..3553e5d 100644 --- a/apps/web/src/features/cookbook/CookbookPage.css +++ b/apps/web/src/features/cookbook/CookbookPage.css @@ -29,7 +29,7 @@ .cookbook-page__search-form { display: grid; grid-template-columns: minmax(0, 1fr) auto; - align-items: end; + align-items: start; gap: var(--space-3); width: min(100%, 52rem); @@ -76,7 +76,21 @@ grid-template-columns: 1fr; } + /* Keep the stacked button in place when field feedback appears. */ + .cookbook-page__search-form > .field { + display: contents; + } + + .cookbook-page__search-form .field__control { + grid-row: 1; + } + + .cookbook-page__search-form .field__error { + grid-row: 3; + } + .cookbook-page__search-button { + grid-row: 2; width: 100%; } diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx index 0180bb9..9bef7bc 100644 --- a/apps/web/src/features/cookbook/CookbookPage.test.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx @@ -1,4 +1,4 @@ -import { render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, useLocation } from 'react-router-dom'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; @@ -94,3 +94,50 @@ it('shows session-expired failures with retry', async () => { ).toBeTruthy(); expect(screen.queryByText('Your cookbook is empty')).toBeNull(); }); + +it('rejects oversized submitted searches beside the field without a request', async () => { + const fetch = mockRecipeFetch(() => ({ data: { cookbook: apiPage([]) } })); + mount(); + await screen.findByText('0 recipes found'); + const before = fetch.mock.calls.length; + const input = screen.getByRole('searchbox'); + fireEvent.change(input, { target: { value: 'a'.repeat(201) } }); + await userEvent.setup().click(screen.getByRole('button', { name: 'Search' })); + expect( + screen.getByText('Use at most 200 characters for search.'), + ).toBeTruthy(); + expect(fetch.mock.calls.length).toBe(before); + expect(screen.getByTestId('location').textContent).toBe(''); + fireEvent.change(input, { target: { value: 'a'.repeat(200) } }); + await userEvent.setup().click(screen.getByRole('button', { name: 'Search' })); + await waitFor(() => expect(fetch.mock.calls.length).toBe(before + 1)); +}); + +it.each([ + ['?q=' + 'a'.repeat(201), 'Use at most 200 characters for search.'], + ['?time=custom&maxTime=1.5', 'Enter whole minutes from 1 to 20,160.'], +])('blocks invalid bookmarked criteria %s', async (query, message) => { + const fetch = mockRecipeFetch(() => ({ data: { cookbook: apiPage([]) } })); + mount('/cookbook' + query); + await screen.findByText(message); + expect(fetch).not.toHaveBeenCalled(); + expect(screen.queryByText('0 recipes found')).toBeNull(); +}); + +it('keeps malformed bookmarked input editable and loads results after clearing', async () => { + const fetch = mockRecipeFetch(() => ({ data: { cookbook: apiPage([]) } })); + mount('/cookbook?time=custom&maxTime=abc'); + const input = screen.getByRole('textbox', { name: 'Maximum cooking time' }); + expect((input as HTMLInputElement).value).toBe('abc'); + expect(screen.getByText('Invalid time filter')).toBeTruthy(); + expect(fetch).not.toHaveBeenCalled(); + fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), { + target: { value: 'soup' }, + }); + expect(screen.getByTestId('location').textContent).toContain('maxTime=abc'); + expect(fetch).not.toHaveBeenCalled(); + fireEvent.change(input, { target: { value: '' } }); + await screen.findByText('0 recipes found'); + expect(screen.getByTestId('location').textContent).not.toContain('maxTime'); + expect(screen.queryByText('Invalid time filter')).toBeNull(); +}); diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx index 57dbcab..3b78b2f 100644 --- a/apps/web/src/features/cookbook/CookbookPage.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -7,7 +7,13 @@ import { useState, type SubmitEvent, } from 'react'; -import { useSearchParams } from 'react-router-dom'; +import { useLocation, useSearchParams } from 'react-router-dom'; +import { + clampCustomTime, + customTimeError, + customTimeText, + searchError, +} from '../../lib/recipeBrowse/browseValidation'; import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps'; @@ -50,6 +56,7 @@ function CookbookPage() { const resultCountRef = useRef(null); const [searchParams, setSearchParams] = useSearchParams(); + const location = useLocation(); const pendingSaves = useRef(new Set()); const [savingIds, setSavingIds] = useState([]); @@ -61,6 +68,10 @@ function CookbookPage() { ); const [searchInput, setSearchInput] = useState(search); + const criteriaInvalid = + !!searchError(search) || + (browseState.cookingTime === 'custom' && + !!customTimeError(clampCustomTime(customTimeText(browseState)))); const queryFilters = getCookbookQueryFilters(browseState); @@ -92,6 +103,7 @@ function CookbookPage() { scope, ]), load, + { enabled: !criteriaInvalid }, ); const result = query.data ?? { items: [], @@ -149,6 +161,10 @@ function CookbookPage() { function handleSearchSubmit(event: SubmitEvent) { event.preventDefault(); + if (searchError(searchInput)) { + searchInputRef.current?.focus(); + return; + } updateUrlState({ scope, @@ -333,6 +349,7 @@ function CookbookPage() { type="search" name="search" value={searchInput} + error={searchError(searchInput)} placeholder="Search recipes, ingredients or tags..." autoComplete="off" onChange={(event) => { @@ -369,6 +386,7 @@ function CookbookPage() { {query.loading ? ( 'Loading recipes…' - ) : query.error ? null : ( + ) : query.error || criteriaInvalid ? null : ( <> {result.totalItems}{' '} {result.totalItems === 1 ? 'recipe' : 'recipes'} found @@ -406,7 +424,7 @@ function CookbookPage() { {/* Errors and retry only; loading is shown in the line above. */} {saveError &&

{saveError}

} - {!query.loading && !query.error && ( + {!criteriaInvalid && !query.loading && !query.error && ( <> {result.totalItems > 0 ? ( <> diff --git a/apps/web/src/features/cookbook/cookbookUrlState.test.ts b/apps/web/src/features/cookbook/cookbookUrlState.test.ts index a1897f4..cafb56f 100644 --- a/apps/web/src/features/cookbook/cookbookUrlState.test.ts +++ b/apps/web/src/features/cookbook/cookbookUrlState.test.ts @@ -97,3 +97,27 @@ describe('Cookbook URL state', () => { }); }); }); + +it.each(['abc', '1.5', 'x'.repeat(300)])( + 'preserves invalid custom time %s without NaN', + (raw) => { + const state = readCookbookUrlState( + new URLSearchParams({ time: 'custom', maxTime: raw }), + ); + expect(state.browseState.customMaxMinutes).toBeNull(); + expect(state.browseState.customMaxMinutesRaw).toBe(raw); + expect(createCookbookSearchParams(state).get('maxTime')).toBe(raw); + }, +); + +it.each([ + ['20161', 20160], + ['-1', 1], + ['0', 1], +])('clamps bookmarked time %s to %s', (raw, expected) => { + const state = readCookbookUrlState( + new URLSearchParams({ time: 'custom', maxTime: raw }), + ); + expect(state.browseState.customMaxMinutes).toBe(expected); + expect(state.browseState.customMaxMinutesRaw).toBe(raw); +}); diff --git a/apps/web/src/features/cookbook/cookbookUrlState.ts b/apps/web/src/features/cookbook/cookbookUrlState.ts index 59026a8..269dd9d 100644 --- a/apps/web/src/features/cookbook/cookbookUrlState.ts +++ b/apps/web/src/features/cookbook/cookbookUrlState.ts @@ -1,3 +1,4 @@ +import { readCustomTime } from '../../lib/recipeBrowse/browseValidation'; import { isRecipeCategory, isRecipeCookingTime, @@ -50,10 +51,10 @@ export function readCookbookUrlState( ? sortParam : DEFAULT_COOKBOOK_BROWSE_STATE.sort; - const customMaxMinutes = + const customTime = cookingTime === 'custom' - ? parsePositiveInteger(searchParams.get('maxTime')) - : null; + ? readCustomTime(searchParams.get('maxTime')) + : { customMaxMinutes: null }; return { scope, @@ -63,7 +64,7 @@ export function readCookbookUrlState( browseState: { category, cookingTime, - customMaxMinutes, + ...customTime, sort, }, @@ -98,9 +99,13 @@ export function createCookbookSearchParams({ if ( browseState.cookingTime === 'custom' && - browseState.customMaxMinutes !== null + (browseState.customMaxMinutesRaw !== undefined || + browseState.customMaxMinutes !== null) ) { - searchParams.set('maxTime', String(browseState.customMaxMinutes)); + searchParams.set( + 'maxTime', + browseState.customMaxMinutesRaw ?? String(browseState.customMaxMinutes), + ); } } diff --git a/apps/web/src/features/explore/ExploreControls.css b/apps/web/src/features/explore/ExploreControls.css index e7ab09d..a91a366 100644 --- a/apps/web/src/features/explore/ExploreControls.css +++ b/apps/web/src/features/explore/ExploreControls.css @@ -11,7 +11,7 @@ .explore-controls__desktop { display: flex; flex-wrap: nowrap; - align-items: center; + align-items: flex-start; gap: var(--space-3); min-width: 0; @@ -49,8 +49,14 @@ width: 18rem; } - .explore-controls__custom-time-input { + .explore-controls__desktop-control--custom-time { + flex: 0 0 9rem; width: 9rem; + overflow-wrap: anywhere; + } + + .explore-controls__custom-time-input { + width: 100%; background-color: var(--color-surface-raised); border-color: var(--color-border-input); diff --git a/apps/web/src/features/explore/ExploreControls.test.tsx b/apps/web/src/features/explore/ExploreControls.test.tsx index 7c6faff..bc04864 100644 --- a/apps/web/src/features/explore/ExploreControls.test.tsx +++ b/apps/web/src/features/explore/ExploreControls.test.tsx @@ -128,7 +128,7 @@ describe('ExploreControls', () => { ).toBe('lte60'); }); - it('requires a positive custom maximum before applying mobile filters', async () => { + it('requires a valid nonempty custom maximum before applying mobile filters', async () => { const user = userEvent.setup(); render(); @@ -146,20 +146,24 @@ describe('ExploreControls', () => { }), ); - await user.click( - screen.getByRole('button', { - name: 'Apply filters', + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', }), + { target: { value: 'abc' } }, ); + await user.click(screen.getByRole('button', { name: 'Apply filters' })); + expect( - screen.getByText('Enter a maximum cooking time before applying filters.'), + screen.getByText('Enter whole minutes from 1 to 20,160.'), ).toBeTruthy(); - const customMaximum = screen.getByRole('spinbutton', { + const customMaximum = screen.getByRole('textbox', { name: 'Maximum cooking time in minutes', }); + await user.clear(customMaximum); await user.type(customMaximum, '45'); await user.click( @@ -185,7 +189,7 @@ describe('ExploreControls', () => { expect( ( - screen.getByRole('spinbutton', { + screen.getByRole('textbox', { name: 'Maximum cooking time', }) as HTMLInputElement ).value, diff --git a/apps/web/src/features/explore/ExploreControls.tsx b/apps/web/src/features/explore/ExploreControls.tsx index 63bdb04..f2a8164 100644 --- a/apps/web/src/features/explore/ExploreControls.tsx +++ b/apps/web/src/features/explore/ExploreControls.tsx @@ -1,7 +1,14 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; +import { + clampCustomTime, + customTimeError, + customTimeText, +} from '../../lib/recipeBrowse/browseValidation'; +import { useCustomTimeInput } from '../../lib/recipeBrowse/useCustomTimeInput'; import Button from '../../components/ui/Button/Button'; import Field from '../../components/ui/Field/Field'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; import FilterChip from '../../components/ui/FilterChip/FilterChip'; import { Icon } from '../../components/ui/Icon/Icon'; import Radio from '../../components/ui/Radio/Radio'; @@ -27,23 +34,25 @@ import { import './ExploreControls.css'; export type ExploreControlsProps = { + navigationKey?: string; value: ExploreBrowseState; onChange: (value: ExploreBrowseState) => void; }; -function parseCustomMaxMinutes(value: string) { - if (value.trim() === '') { - return null; - } - - const parsed = Number(value); - - return Number.isInteger(parsed) && parsed > 0 ? parsed : null; -} - -function ExploreControls({ value, onChange }: ExploreControlsProps) { +function ExploreControls({ + value, + onChange, + navigationKey = '', +}: ExploreControlsProps) { const [filterSheetOpen, setFilterSheetOpen] = useState(false); const [sortSheetOpen, setSortSheetOpen] = useState(false); + const [focusMobileTime, setFocusMobileTime] = useState(false); + const desktopTimeRef = useRef(null); + const mobileTimeRef = useRef(null); + + useEffect(() => { + if (filterSheetOpen && focusMobileTime) mobileTimeRef.current?.focus(); + }, [filterSheetOpen, focusMobileTime]); const [filterDraft, setFilterDraft] = useState({ category: value.category, @@ -52,7 +61,25 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) { }); const [sortDraft, setSortDraft] = useState(value.sort); - const [showCustomTimeError, setShowCustomTimeError] = useState(false); + const [mobileTime, setMobileTime] = useState(''); + const resetKey = JSON.stringify([navigationKey, value]); + const desktopTime = useCustomTimeInput( + value.customMaxMinutes, + resetKey, + (minutes, raw) => { + onChange({ + ...value, + cookingTime: 'custom', + customMaxMinutes: minutes, + customMaxMinutesRaw: raw, + }); + }, + value.customMaxMinutesRaw, + ); + const committedTimeError = + value.cookingTime === 'custom' + ? customTimeError(clampCustomTime(customTimeText(value))) + : undefined; const activeFilterCount = countActiveExploreFilters(value); const currentSortLabel = getExploreSortLabel(value.sort); @@ -69,28 +96,26 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) { cookingTime, customMaxMinutes: cookingTime === 'custom' ? value.customMaxMinutes : null, + customMaxMinutesRaw: + cookingTime === 'custom' ? value.customMaxMinutesRaw : undefined, }); } - function handleDesktopCustomMaxChange(rawValue: string) { - updateValue({ - cookingTime: 'custom', - customMaxMinutes: parseCustomMaxMinutes(rawValue), - }); - } - - function openFilterSheet() { + function openFilterSheet(focusTime = false) { + setFocusMobileTime(focusTime); setFilterDraft({ category: value.category, cookingTime: value.cookingTime, customMaxMinutes: value.customMaxMinutes, }); - setShowCustomTimeError(false); + setMobileTime(customTimeText(value)); setFilterSheetOpen(true); } function handleDraftCookingTimeChange(cookingTime: ExploreCookingTime) { + if (cookingTime === filterDraft.cookingTime) return; + setFilterDraft((current) => ({ ...current, cookingTime, @@ -98,26 +123,39 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) { cookingTime === 'custom' ? current.customMaxMinutes : null, })); - setShowCustomTimeError(false); + setMobileTime(''); } function handleApplyFilters() { - if ( - filterDraft.cookingTime === 'custom' && - filterDraft.customMaxMinutes === null - ) { - setShowCustomTimeError(true); + const clamped = clampCustomTime(mobileTime); + if (filterDraft.cookingTime === 'custom' && customTimeError(clamped)) { return; } onChange({ ...value, ...filterDraft, + customMaxMinutes: + filterDraft.cookingTime === 'custom' && clamped.trim() + ? Number(clamped) + : null, + customMaxMinutesRaw: + filterDraft.cookingTime === 'custom' && customTimeError(mobileTime) + ? mobileTime + : undefined, }); setFilterSheetOpen(false); } + function editTimeFilter() { + if (desktopTimeRef.current?.getClientRects().length) { + desktopTimeRef.current.focus(); + } else { + openFilterSheet(true); + } + } + function openSortSheet() { setSortDraft(value.sort); setSortSheetOpen(true); @@ -182,19 +220,25 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) { {value.cookingTime === 'custom' && ( -
+
No time limit applied. + ) : undefined + } placeholder="Max minutes" onChange={(event) => - handleDesktopCustomMaxChange(event.currentTarget.value) + desktopTime.change(event.currentTarget.value) } />
@@ -227,7 +271,7 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) {
+ {committedTimeError && ( + +

+ Recipes cannot be loaded until the maximum cooking time is corrected + or cleared. +

+ +
+ )} + { setFilterDraft(DEFAULT_EXPLORE_FILTER_STATE); - setShowCustomTimeError(false); + setMobileTime(''); }} > Clear filters @@ -319,32 +375,21 @@ function ExploreControls({ value, onChange }: ExploreControlsProps) { {filterDraft.cookingTime === 'custom' && (
No time limit applied. + ) } - onChange={(event) => { - const customMaxMinutes = parseCustomMaxMinutes( - event.currentTarget.value, - ); - - setFilterDraft((current) => ({ - ...current, - cookingTime: 'custom', - customMaxMinutes, - })); - - setShowCustomTimeError(false); - }} + error={customTimeError(mobileTime)} + onChange={(event) => setMobileTime(event.currentTarget.value)} />
)} diff --git a/apps/web/src/features/explore/ExplorePage.css b/apps/web/src/features/explore/ExplorePage.css index 048100b..e50df97 100644 --- a/apps/web/src/features/explore/ExplorePage.css +++ b/apps/web/src/features/explore/ExplorePage.css @@ -29,7 +29,7 @@ .explore-page__search-form { display: grid; grid-template-columns: minmax(0, 1fr) auto; - align-items: end; + align-items: start; gap: var(--space-3); width: min(100%, 52rem); @@ -85,7 +85,21 @@ grid-template-columns: 1fr; } + /* Keep the stacked button in place when field feedback appears. */ + .explore-page__search-form > .field { + display: contents; + } + + .explore-page__search-form .field__control { + grid-row: 1; + } + + .explore-page__search-form .field__error { + grid-row: 3; + } + .explore-page__search-button { + grid-row: 2; width: 100%; } diff --git a/apps/web/src/features/explore/ExplorePage.test.tsx b/apps/web/src/features/explore/ExplorePage.test.tsx index 7e4d156..0f3d7b7 100644 --- a/apps/web/src/features/explore/ExplorePage.test.tsx +++ b/apps/web/src/features/explore/ExplorePage.test.tsx @@ -1,4 +1,10 @@ -import { act, render, screen, waitFor } from '@testing-library/react'; +import { + act, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, useLocation } from 'react-router-dom'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -210,3 +216,50 @@ describe('Explore API integration', () => { ).toBeTruthy(); }); }); + +it('rejects oversized submitted searches beside the field without a request', async () => { + const fetch = mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } })); + mount(); + await screen.findByText('0 recipes found'); + const before = fetch.mock.calls.length; + const input = screen.getByRole('searchbox'); + fireEvent.change(input, { target: { value: 'a'.repeat(201) } }); + await userEvent.setup().click(screen.getByRole('button', { name: 'Search' })); + expect( + screen.getByText('Use at most 200 characters for search.'), + ).toBeTruthy(); + expect(fetch.mock.calls.length).toBe(before); + expect(screen.getByTestId('location').textContent).toBe(''); + fireEvent.change(input, { target: { value: 'a'.repeat(200) } }); + await userEvent.setup().click(screen.getByRole('button', { name: 'Search' })); + await waitFor(() => expect(fetch.mock.calls.length).toBe(before + 1)); +}); + +it.each([ + ['?q=' + 'a'.repeat(201), 'Use at most 200 characters for search.'], + ['?time=custom&maxTime=1.5', 'Enter whole minutes from 1 to 20,160.'], +])('blocks invalid bookmarked criteria %s', async (query, message) => { + const fetch = mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } })); + mount('/' + query); + await screen.findByText(message); + expect(fetch).not.toHaveBeenCalled(); + expect(screen.queryByText('0 recipes found')).toBeNull(); +}); + +it('keeps malformed bookmarked input editable and loads results after clearing', async () => { + const fetch = mockRecipeFetch(() => ({ data: { recipes: apiPage([]) } })); + mount('/?time=custom&maxTime=abc'); + const input = screen.getByRole('textbox', { name: 'Maximum cooking time' }); + expect((input as HTMLInputElement).value).toBe('abc'); + expect(screen.getByText('Invalid time filter')).toBeTruthy(); + expect(fetch).not.toHaveBeenCalled(); + fireEvent.change(screen.getByRole('combobox', { name: 'Category' }), { + target: { value: 'soup' }, + }); + expect(screen.getByTestId('location').textContent).toContain('maxTime=abc'); + expect(fetch).not.toHaveBeenCalled(); + fireEvent.change(input, { target: { value: '' } }); + await screen.findByText('0 recipes found'); + expect(screen.getByTestId('location').textContent).not.toContain('maxTime'); + expect(screen.queryByText('Invalid time filter')).toBeNull(); +}); diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx index 1c89072..638d43b 100644 --- a/apps/web/src/features/explore/ExplorePage.tsx +++ b/apps/web/src/features/explore/ExplorePage.tsx @@ -7,7 +7,13 @@ import { useState, type SubmitEvent, } from 'react'; -import { useSearchParams } from 'react-router-dom'; +import { useLocation, useSearchParams } from 'react-router-dom'; +import { + clampCustomTime, + customTimeError, + customTimeText, + searchError, +} from '../../lib/recipeBrowse/browseValidation'; import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps'; @@ -54,6 +60,7 @@ function ExplorePage() { const resultCountRef = useRef(null); const [searchParams, setSearchParams] = useSearchParams(); + const location = useLocation(); const currentUser = useAppStore((state) => state.currentUser); @@ -74,6 +81,10 @@ function ExplorePage() { * sorting, and pagination. */ const [searchInput, setSearchInput] = useState(search); + const criteriaInvalid = + !!searchError(search) || + (browseState.cookingTime === 'custom' && + !!customTimeError(clampCustomTime(customTimeText(browseState)))); const queryFilters = getExploreQueryFilters(browseState); @@ -104,6 +115,7 @@ function ExplorePage() { page, ]), load, + { enabled: !criteriaInvalid }, ); const result = query.data ?? { items: [], @@ -158,6 +170,10 @@ function ExplorePage() { function handleSearchSubmit(event: SubmitEvent) { event.preventDefault(); + if (searchError(searchInput)) { + searchInputRef.current?.focus(); + return; + } updateUrlState({ search: searchInput, @@ -305,6 +321,7 @@ function ExplorePage() { type="search" name="search" value={searchInput} + error={searchError(searchInput)} placeholder="Search recipes, ingredients or tags..." autoComplete="off" onChange={(event) => { @@ -340,6 +357,7 @@ function ExplorePage() { @@ -357,7 +375,7 @@ function ExplorePage() { > {query.loading ? ( 'Loading recipes…' - ) : query.error ? null : ( + ) : query.error || criteriaInvalid ? null : ( <> {result.totalItems}{' '} {result.totalItems === 1 ? 'recipe' : 'recipes'} found @@ -373,7 +391,7 @@ function ExplorePage() {

{/* Errors and retry only; loading is shown in the line above. */} - {!query.loading && !query.error && ( + {!criteriaInvalid && !query.loading && !query.error && ( <> {result.totalItems > 0 ? ( <> diff --git a/apps/web/src/features/explore/exploreUrlState.test.ts b/apps/web/src/features/explore/exploreUrlState.test.ts index 366e66d..dde606b 100644 --- a/apps/web/src/features/explore/exploreUrlState.test.ts +++ b/apps/web/src/features/explore/exploreUrlState.test.ts @@ -116,3 +116,27 @@ describe('Explore URL state', () => { }); }); }); + +it.each(['abc', '1.5', 'x'.repeat(300)])( + 'preserves invalid custom time %s without NaN', + (raw) => { + const state = readExploreUrlState( + new URLSearchParams({ time: 'custom', maxTime: raw }), + ); + expect(state.browseState.customMaxMinutes).toBeNull(); + expect(state.browseState.customMaxMinutesRaw).toBe(raw); + expect(createExploreSearchParams(state).get('maxTime')).toBe(raw); + }, +); + +it.each([ + ['20161', 20160], + ['-1', 1], + ['0', 1], +])('clamps bookmarked time %s to %s', (raw, expected) => { + const state = readExploreUrlState( + new URLSearchParams({ time: 'custom', maxTime: raw }), + ); + expect(state.browseState.customMaxMinutes).toBe(expected); + expect(state.browseState.customMaxMinutesRaw).toBe(raw); +}); diff --git a/apps/web/src/features/explore/exploreUrlState.ts b/apps/web/src/features/explore/exploreUrlState.ts index c76d85a..432b27e 100644 --- a/apps/web/src/features/explore/exploreUrlState.ts +++ b/apps/web/src/features/explore/exploreUrlState.ts @@ -1,3 +1,4 @@ +import { readCustomTime } from '../../lib/recipeBrowse/browseValidation'; import { DEFAULT_EXPLORE_BROWSE_STATE, isExploreCategory, @@ -41,10 +42,10 @@ export function readExploreUrlState( ? sortParam : DEFAULT_EXPLORE_BROWSE_STATE.sort; - const customMaxMinutes = + const customTime = cookingTime === 'custom' - ? parsePositiveInteger(searchParams.get('maxTime')) - : null; + ? readCustomTime(searchParams.get('maxTime')) + : { customMaxMinutes: null }; return { search: (searchParams.get('q') ?? '').trim(), @@ -52,7 +53,7 @@ export function readExploreUrlState( browseState: { category, cookingTime, - customMaxMinutes, + ...customTime, sort, }, @@ -82,9 +83,13 @@ export function createExploreSearchParams({ if ( browseState.cookingTime === 'custom' && - browseState.customMaxMinutes !== null + (browseState.customMaxMinutesRaw !== undefined || + browseState.customMaxMinutes !== null) ) { - searchParams.set('maxTime', String(browseState.customMaxMinutes)); + searchParams.set( + 'maxTime', + browseState.customMaxMinutesRaw ?? String(browseState.customMaxMinutes), + ); } } diff --git a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx index 7d25909..8cf5f7f 100644 --- a/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx +++ b/apps/web/src/features/recipe-detail/RecipeDetailPage.tsx @@ -669,6 +669,8 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) { function RecipeDetailPage() { const { id } = useParams(); + const location = useLocation(); + const currentUser = useAppStore((state) => state.currentUser); const load = useCallback( (signal: AbortSignal) => getRecipe(id ?? '', signal), @@ -690,8 +692,31 @@ function RecipeDetailPage() { icon={EmptyStateIcon} headingLevel={1} title="Recipe not found" - description="This recipe does not exist or is not available to you." - action={Back to Explore} + description={ + currentUser + ? 'This recipe does not exist or is not available to you.' + : 'This recipe does not exist or is not available to you. If it is private, log in to the account that owns it.' + } + action={ + <> + {!currentUser && ( + + Log in + + )} + + Back to Explore + + + } /> ); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css index f1d8bf4..bd90bca 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.css +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -1,4 +1,17 @@ @layer components { + .recipe-create-page__toast-region { + position: fixed; + right: var(--space-6); + bottom: var(--space-6); + z-index: var(--z-overlay); + width: min(24rem, calc(100% - (2 * var(--space-6)))); + } + + .recipe-create-page__form + :is(.field, .textarea, .select, .radio-group, [data-form-error]) { + scroll-margin-top: calc(var(--site-header-height) + var(--space-4)); + } + .recipe-create-page { padding-block: var(--space-10) var(--space-16); } diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index 719634c..c024cfb 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -1,5 +1,11 @@ import '@testing-library/jest-dom/vitest'; -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { useAppStore } from '../../store'; @@ -51,7 +57,11 @@ describe('RecipeCreatePage', () => { expect(screen.getByLabelText(/Recipe title/)).toBeInTheDocument(); expect(screen.getByLabelText(/Short description/)).toBeInTheDocument(); expect(screen.getByLabelText(/Cooking time/)).toBeInTheDocument(); - expect(screen.getByLabelText(/Servings/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Servings/)).toHaveAttribute( + 'placeholder', + 'e.g. 4', + ); + expect(screen.getByLabelText(/Servings/)).toHaveValue(null); expect(screen.getByLabelText(/Category/)).toBeInTheDocument(); expect(screen.getByLabelText(/Tags/)).toBeInTheDocument(); expect( @@ -458,6 +468,11 @@ describe('recipe drafts', () => { mount(); await user.click(screen.getByRole('button', { name: 'Discard draft' })); + await user.click( + within( + screen.getByRole('dialog', { name: 'Discard saved draft?' }), + ).getByRole('button', { name: 'Discard draft' }), + ); expect(screen.queryByText('Saved draft found')).not.toBeInTheDocument(); expect(localStorage.length).toBe(0); }); @@ -652,6 +667,11 @@ describe('recipe draft edge cases', () => { const newer = storedDraft({ title: 'Newer' }, '2026-10-01T11:00:00Z'); localStorage.setItem(draftKey('new'), newer); await user.click(screen.getByRole('button', { name: 'Discard draft' })); + await user.click( + within( + screen.getByRole('dialog', { name: 'Discard saved draft?' }), + ).getByRole('button', { name: 'Discard draft' }), + ); expect(localStorage.getItem(draftKey('new'))).toBe(newer); expect( screen.getByText(/A newer draft was saved in another tab/), @@ -968,10 +988,22 @@ describe('recipe size limits and error focus', () => { fireEvent.change(screen.getByLabelText('Ingredient 2'), { target: { value: 'Salt' }, }); + const scroll = vi.fn(); + const field = screen + .getByLabelText('Ingredient 2 amount') + .closest('.field')!; + Object.defineProperty(field, 'scrollIntoView', { + configurable: true, + value: scroll, + }); // Ingredient 2 has no amount: focus goes there, not to the title. await publish(); await tick(); expect(screen.getByLabelText('Ingredient 2 amount')).toHaveFocus(); + expect(scroll).toHaveBeenCalledWith({ + block: 'start', + behavior: 'instant', + }); fireEvent.change(screen.getByLabelText('Ingredient 2 amount'), { target: { value: '2' }, @@ -987,3 +1019,90 @@ describe('recipe size limits and error focus', () => { expect(screen.getByLabelText('Step 3')).toHaveFocus(); }); }); + +it('keeps a draft and the form when discarding is cancelled', async () => { + localStorage.clear(); + const user = userEvent.setup(); + const first = mount(); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Saved title' }, + }); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + first.unmount(); + mount(); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Current form' }, + }); + await user.click(screen.getByRole('button', { name: 'Discard draft' })); + expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Saved title'); + await user.click(screen.getByRole('button', { name: 'Keep draft' })); + expect(loadDraft(apiUser.id, 'new')?.fields.title).toBe('Saved title'); + expect(screen.getByLabelText(/Recipe title/)).toHaveValue('Current form'); + expect(screen.getByText('Saved draft found')).toBeInTheDocument(); +}); + +it('restarts success notifications for each save and allows dismissal', async () => { + localStorage.clear(); + const user = userEvent.setup(); + mount(); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + const first = screen.getByText('Draft saved').closest('.toast'); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + expect(screen.getByText('Draft saved').closest('.toast')).not.toBe(first); + await user.click( + screen.getByRole('button', { name: 'Dismiss notification' }), + ); + expect(screen.queryByText('Draft saved')).not.toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Save draft' })); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Changed' }, + }); + expect(screen.queryByText('Draft saved')).not.toBeInTheDocument(); +}); + +it('expires success feedback but keeps a failed save visible until corrected', () => { + localStorage.clear(); + vi.useFakeTimers(); + let storage: ReturnType | undefined; + try { + mount(); + fireEvent.click(screen.getByRole('button', { name: 'Save draft' })); + act(() => vi.advanceTimersByTime(4000)); + fireEvent.click(screen.getByRole('button', { name: 'Save draft' })); + act(() => vi.advanceTimersByTime(1001)); + expect(screen.getByText('Draft saved')).toBeInTheDocument(); + act(() => vi.advanceTimersByTime(4000)); + expect(screen.queryByText('Draft saved')).not.toBeInTheDocument(); + storage = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { + throw new Error('Storage full'); + }); + fireEvent.click(screen.getByRole('button', { name: 'Save draft' })); + act(() => vi.advanceTimersByTime(10000)); + expect(screen.getByText('Draft not saved')).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText(/Recipe title/), { + target: { value: 'Corrected' }, + }); + expect(screen.queryByText('Draft not saved')).not.toBeInTheDocument(); + } finally { + storage?.mockRestore(); + vi.useRealTimers(); + } +}); + +it('does not restart draft feedback when publishing triggers validation', () => { + localStorage.clear(); + vi.useFakeTimers(); + try { + mount(); + fireEvent.click(screen.getByRole('button', { name: 'Save draft' })); + act(() => vi.advanceTimersByTime(3500)); + fireEvent.click(screen.getByRole('button', { name: 'Publish recipe' })); + expect(screen.getByText('Enter a recipe title.')).toBeInTheDocument(); + act(() => vi.advanceTimersByTime(1499)); + expect(screen.getByText('Draft saved')).toBeInTheDocument(); + act(() => vi.advanceTimersByTime(1)); + expect(screen.queryByText('Draft saved')).not.toBeInTheDocument(); + } finally { + vi.useRealTimers(); + } +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index faf3d13..88b2467 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -13,6 +13,7 @@ import { ChevronDownIcon, ChevronUpIcon } from '../../icons/navigation'; import Button from '../../components/ui/Button/Button'; import Field from '../../components/ui/Field/Field'; import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; +import Toast from '../../components/ui/Toast/Toast'; import IconButton from '../../components/ui/IconButton/IconButton'; import { Icon } from '../../components/ui/Icon/Icon'; import Radio from '../../components/ui/Radio/Radio'; @@ -283,6 +284,8 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ); const [confirmReplaceDraft, setConfirmReplaceDraft] = useState(false); + const [confirmDiscardDraft, setConfirmDiscardDraft] = useState(false); + const [draftNotification, setDraftNotification] = useState(0); function handleSaveDraft() { if (!userId || imageRestoring) return; // Do not silently replace a draft this tab has not restored or written: @@ -313,6 +316,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { setDraftNotice(''); setSavedSnapshot(formSnapshot); setStatus(saved ? 'draft' : 'draft-failed'); + setDraftNotification((current) => current + 1); } function restoreDraft() { @@ -371,6 +375,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function discardDraft() { + setConfirmDiscardDraft(false); const removed = userId && clearDraft(userId, draftRecipeId, knownDrafts.current); setOfferedDraft(null); @@ -386,6 +391,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { >(); const [errors, setErrors] = useState({}); const [status, setStatus] = useState('idle'); + const closeDraftNotification = useCallback(() => setStatus('idle'), []); const pointerDragRef = useRef< { type: 'ingredient' | 'instruction'; index: number } | undefined >(undefined); @@ -722,7 +728,11 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { const firstInvalid = formRef.current?.querySelector( '[aria-invalid="true"], [data-form-error]', ); - (firstInvalid ?? document.getElementById('recipe-title'))?.focus(); + const target = firstInvalid ?? document.getElementById('recipe-title'); + target?.focus({ preventScroll: true }); + const field = + target?.closest('.field, .textarea, .select, .radio-group') ?? target; + field?.scrollIntoView?.({ block: 'start', behavior: 'instant' }); }, 0); return; } @@ -823,7 +833,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { type="button" size="sm" variant="secondary" - onClick={discardDraft} + onClick={() => setConfirmDiscardDraft(true)} > Discard draft @@ -833,18 +843,6 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { {draftNotice && ( {draftNotice} )} - {status === 'draft' && draftMessageIsCurrent && ( - - Saved in this browser. It will be offered when you open this form - again, also after reloading the page. - - )} - {status === 'draft-failed' && draftMessageIsCurrent && ( - - Your browser did not allow saving the draft. Your changes are - still in the form. - - )}
{ @@ -1314,6 +1313,32 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { + {status !== 'idle' && draftMessageIsCurrent && ( +
+ + {status === 'draft' + ? 'Saved in this browser. It will be offered when you open this form again.' + : 'Saving the draft failed. Your changes are still in the form.'} + +
+ )} + setConfirmDiscardDraft(false)} + /> { + const load = vi.fn().mockResolvedValue('valid results'); + const { result, rerender } = renderHook( + ({ enabled }) => useRecipeQuery('guarded', load, { enabled }), + { initialProps: { enabled: false } }, + ); + expect(load).not.toHaveBeenCalled(); + expect(result.current.loading).toBe(false); + rerender({ enabled: true }); + await waitFor(() => expect(result.current.data).toBe('valid results')); + expect(load).toHaveBeenCalledTimes(1); +}); diff --git a/apps/web/src/features/recipes/useRecipeQuery.ts b/apps/web/src/features/recipes/useRecipeQuery.ts index b99c671..2dc87df 100644 --- a/apps/web/src/features/recipes/useRecipeQuery.ts +++ b/apps/web/src/features/recipes/useRecipeQuery.ts @@ -26,6 +26,7 @@ export function useRecipeQuery( key: string, load: (signal: AbortSignal) => Promise, { + enabled = true, refreshOnMutation = true, // Refetch stale data when the user comes back to a long-open page. // Off for forms (the editor), which must never replace typed input. @@ -62,7 +63,7 @@ export function useRecipeQuery( error?: string; }>({ identity: '', key: '', hasData: false }); useEffect(() => { - if (waiting) return; + if (waiting || !enabled) return; const cached = attempt === 0 ? readRecipeCache(identity) : undefined; const generation = recipeCacheGeneration(); const controller = new AbortController(); @@ -90,8 +91,9 @@ export function useRecipeQuery( }, ); return () => controller.abort(); - }, [identity, requestKey, load, waiting, attempt]); - const current = !waiting && state.identity === identity ? state : undefined; + }, [identity, requestKey, load, waiting, attempt, enabled]); + const current = + enabled && !waiting && state.identity === identity ? state : undefined; const hasData = current?.hasData ?? false; /* @@ -122,8 +124,8 @@ export function useRecipeQuery( error: !hasData && current?.key === requestKey ? current.error : undefined, refreshError: hasData && current?.key === requestKey ? current.error : undefined, - loading: waiting || (!hasData && current?.key !== requestKey), - refreshing: hasData && current?.key !== requestKey, + loading: enabled && (waiting || (!hasData && current?.key !== requestKey)), + refreshing: enabled && hasData && current?.key !== requestKey, retry: () => setAttempt((value) => value + 1), }; } diff --git a/apps/web/src/lib/recipeBrowse/browseControls.test.tsx b/apps/web/src/lib/recipeBrowse/browseControls.test.tsx new file mode 100644 index 0000000..a69313c --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/browseControls.test.tsx @@ -0,0 +1,280 @@ +import '@testing-library/jest-dom/vitest'; +import { useState } from 'react'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import ExploreControls from '../../features/explore/ExploreControls'; +import CookbookControls from '../../features/cookbook/CookbookControls'; +import { + DEFAULT_EXPLORE_BROWSE_STATE, + type ExploreBrowseState, +} from '../../features/explore/exploreBrowseState'; +import { + DEFAULT_COOKBOOK_BROWSE_STATE, + type CookbookBrowseState, +} from '../../features/cookbook/cookbookBrowseState'; + +// Exercise both consumers so their desktop/mobile behavior cannot drift. +for (const kind of ['explore', 'cookbook'] as const) { + describe(`${kind} custom time controls`, () => { + afterEach(() => vi.useRealTimers()); + + function Harness({ navigationKey = 'first' }: { navigationKey?: string }) { + const [explore, setExplore] = useState({ + ...DEFAULT_EXPLORE_BROWSE_STATE, + cookingTime: 'custom' as const, + customMaxMinutes: 30, + }); + const [cookbook, setCookbook] = useState({ + ...DEFAULT_COOKBOOK_BROWSE_STATE, + cookingTime: 'custom' as const, + customMaxMinutes: 30, + }); + return ( + <> + {kind === 'explore' ? ( + + ) : ( + {}} + onBrowseStateChange={setCookbook} + onFiltersChange={(_, next) => setCookbook(next)} + /> + )} + + {(kind === 'explore' ? explore : cookbook).customMaxMinutes ?? + 'none'} + + + ); + } + + it('debounces typing, preserves the prior limit, and clears immediately', () => { + vi.useFakeTimers(); + render(); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: '4' } }); + act(() => vi.advanceTimersByTime(200)); + fireEvent.change(input, { target: { value: '45' } }); + act(() => vi.advanceTimersByTime(299)); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + act(() => vi.advanceTimersByTime(1)); + expect(screen.getByTestId('applied')).toHaveTextContent('45'); + fireEvent.change(input, { target: { value: '90' } }); + fireEvent.change(input, { target: { value: '' } }); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + expect( + screen.getAllByText('No time limit applied.')[0], + ).toBeInTheDocument(); + expect( + screen.getByRole('combobox', { name: 'Cooking time' }), + ).toHaveValue('custom'); + expect( + screen.getByRole('button', { name: 'Filters', hidden: true }), + ).toBeInTheDocument(); + }); + + it.each(['abc', '1.5'])( + 'keeps invalid input %s editable without applying it', + (text) => { + vi.useFakeTimers(); + render(); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: text } }); + act(() => vi.advanceTimersByTime(500)); + expect(input).toHaveValue(text); + expect(input).toHaveAttribute('aria-invalid', 'true'); + expect( + screen.getByText('Enter whole minutes from 1 to 20,160.'), + ).toBeInTheDocument(); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + }, + ); + + it.each([ + ['0', '1'], + ['-5', '1'], + ['20161', '20160'], + ])( + 'uses %s as %s while keeping the typed value and error', + (text, expected) => { + vi.useFakeTimers(); + render(); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: text } }); + expect(input).toHaveValue(text); + act(() => vi.advanceTimersByTime(300)); + expect(input).toHaveValue(text); + expect(input).toHaveAttribute('aria-invalid', 'true'); + expect(screen.getByTestId('applied')).toHaveTextContent(expected); + }, + ); + + it('clamps on blur even when the applied value is already the maximum', () => { + vi.useFakeTimers(); + render(); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time', + }); + fireEvent.change(input, { target: { value: '99999' } }); + fireEvent.blur(input); + expect(input).toHaveValue('99999'); + fireEvent.change(input, { target: { value: '999999' } }); + act(() => vi.advanceTimersByTime(300)); + expect(input).toHaveValue('999999'); + expect(screen.getByTestId('applied')).toHaveTextContent('20160'); + }); + + it('preserves the custom maximum when reselected and applied on mobile', () => { + render(); + const openFilters = () => + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + openFilters(); + fireEvent.click(screen.getByRole('button', { name: 'Close filters' })); + openFilters(); + fireEvent.click(screen.getByRole('button', { name: 'Custom maximum' })); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + ).toHaveValue('30'); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + openFilters(); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + ).toHaveValue('30'); + }); + + it.each([ + ['0', '1'], + ['99999', '20160'], + ])('clamps mobile input %s on Apply', (text, expected) => { + render(); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }); + fireEvent.change(input, { target: { value: text } }); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent(expected); + expect( + screen.getByRole('textbox', { name: 'Maximum cooking time' }), + ).toHaveValue(text); + }); + + it.each(['1', '20160'])('accepts boundary %s', (text) => { + vi.useFakeTimers(); + render(); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + { target: { value: text } }, + ); + act(() => vi.advanceTimersByTime(300)); + expect(screen.getByTestId('applied')).toHaveTextContent(text); + }); + + it('cancels pending changes on navigation and preset changes', () => { + vi.useFakeTimers(); + const { rerender } = render(); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + { target: { value: '45' } }, + ); + rerender(); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + ).toHaveValue('30'); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time', + }), + { target: { value: '45' } }, + ); + fireEvent.change(screen.getByRole('combobox', { name: 'Cooking time' }), { + target: { value: 'any' }, + }); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + expect( + screen.getByRole('combobox', { name: 'Cooking time' }), + ).toHaveValue('any'); + }); + + it('blocks invalid mobile values, then applies empty time as no limit', () => { + render(); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + const input = screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }); + fireEvent.change(input, { target: { value: 'abc' } }); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect( + screen.getByRole('dialog', { name: 'Filter recipes' }), + ).toBeInTheDocument(); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + fireEvent.change(input, { target: { value: '' } }); + fireEvent.click(screen.getByRole('button', { name: 'Apply filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent('none'); + expect( + screen.queryByRole('dialog', { name: 'Filter recipes' }), + ).not.toBeInTheDocument(); + expect( + screen.getAllByText('No time limit applied.')[0], + ).toBeInTheDocument(); + }); + + it('discards mobile edits when closed', () => { + render(); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + fireEvent.change( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + { target: { value: '45' } }, + ); + fireEvent.click(screen.getByRole('button', { name: 'Close filters' })); + expect(screen.getByTestId('applied')).toHaveTextContent('30'); + fireEvent.click( + screen.getByRole('button', { name: 'Filters (1)', hidden: true }), + ); + expect( + screen.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }), + ).toHaveValue('30'); + }); + }); +} diff --git a/apps/web/src/lib/recipeBrowse/browseValidation.ts b/apps/web/src/lib/recipeBrowse/browseValidation.ts new file mode 100644 index 0000000..9b67474 --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/browseValidation.ts @@ -0,0 +1,50 @@ +export const MAX_SEARCH_LENGTH = 200; +export const MAX_FILTER_MINUTES = 20160; + +export function searchError(value: string) { + return value.trim().length > MAX_SEARCH_LENGTH + ? 'Use at most 200 characters for search.' + : undefined; +} + +/** Clamp finite numeric input on commit; leave empty or malformed input editable. */ +export function clampCustomTime(value: string) { + if (!value.trim()) return value; + const minutes = Number(value); + if (!Number.isFinite(minutes)) return value; + if (minutes < 1) return '1'; + if (minutes > MAX_FILTER_MINUTES) return String(MAX_FILTER_MINUTES); + return value; +} + +export function customTimeError(value: string) { + if (!value.trim()) return undefined; + const minutes = Number(value); + return Number.isInteger(minutes) && + minutes >= 1 && + minutes <= MAX_FILTER_MINUTES + ? undefined + : 'Enter whole minutes from 1 to 20,160.'; +} + +// Preserve invalid URL input separately from the validated numeric query value. +export function readCustomTime(value: string | null): { + customMaxMinutes: number | null; + customMaxMinutesRaw?: string; +} { + if (value === null || value.trim() === '') return { customMaxMinutes: null }; + const clamped = clampCustomTime(value); + if (customTimeError(clamped)) + return { customMaxMinutes: null, customMaxMinutesRaw: value }; + return { + customMaxMinutes: Number(clamped), + ...(customTimeError(value) ? { customMaxMinutesRaw: value } : {}), + }; +} + +export function customTimeText(state: { + customMaxMinutes: number | null; + customMaxMinutesRaw?: string; +}) { + return state.customMaxMinutesRaw ?? String(state.customMaxMinutes ?? ''); +} diff --git a/apps/web/src/lib/recipeBrowse/recipeBrowse.ts b/apps/web/src/lib/recipeBrowse/recipeBrowse.ts index db14a47..384fd4f 100644 --- a/apps/web/src/lib/recipeBrowse/recipeBrowse.ts +++ b/apps/web/src/lib/recipeBrowse/recipeBrowse.ts @@ -33,6 +33,8 @@ export type RecipeFilterState = { category: RecipeCategory; cookingTime: RecipeCookingTime; customMaxMinutes: number | null; + // Invalid bookmarked input stays editable without putting NaN in query state. + customMaxMinutesRaw?: string; }; /** @@ -109,7 +111,9 @@ export function countActiveRecipeFilters(state: RecipeFilterState) { if ( state.cookingTime !== 'any' && - (state.cookingTime !== 'custom' || state.customMaxMinutes !== null) + (state.cookingTime !== 'custom' || + state.customMaxMinutes !== null || + state.customMaxMinutesRaw !== undefined) ) { count += 1; } diff --git a/apps/web/src/lib/recipeBrowse/useCustomTimeInput.ts b/apps/web/src/lib/recipeBrowse/useCustomTimeInput.ts new file mode 100644 index 0000000..a922569 --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/useCustomTimeInput.ts @@ -0,0 +1,66 @@ +import { useEffect, useEffectEvent, useState } from 'react'; +import { clampCustomTime, customTimeError } from './browseValidation'; + +/** Keep typed input separate from the URL until it is valid and typing pauses. */ +export function useCustomTimeInput( + committed: number | null, + resetKey: string, + onCommit: (minutes: number | null, raw?: string) => void, + raw?: string, +) { + const [draft, setDraft] = useState({ + key: resetKey, + text: raw ?? String(committed ?? ''), + }); + const text = + draft.key === resetKey ? draft.text : (raw ?? String(committed ?? '')); + const clamped = clampCustomTime(text); + const error = customTimeError(text); + const effectiveError = customTimeError(clamped); + const nextRaw = error ? text : undefined; + const commit = useEffectEvent(onCommit); + + useEffect(() => { + if ( + draft.key !== resetKey || + !text.trim() || + effectiveError || + (Number(clamped) === committed && nextRaw === raw) + ) + return; + const timer = window.setTimeout(() => { + commit(Number(clamped), nextRaw); + }, 300); + return () => window.clearTimeout(timer); + }, [ + draft.key, + resetKey, + text, + clamped, + effectiveError, + committed, + raw, + nextRaw, + ]); + + function change(text: string) { + setDraft({ key: resetKey, text }); + // Clearing is immediate, even if an earlier value was waiting to be committed. + if (!text.trim() && (committed !== null || raw !== undefined)) + onCommit(null); + } + + function apply() { + if (effectiveError || !clamped.trim()) return; + if (Number(clamped) !== committed || nextRaw !== raw) + onCommit(Number(clamped), nextRaw); + } + + return { + text, + error, + change, + apply, + noLimit: committed === null && raw === undefined, + }; +} diff --git a/e2e/recipe-usability.spec.ts b/e2e/recipe-usability.spec.ts new file mode 100644 index 0000000..4d18b47 --- /dev/null +++ b/e2e/recipe-usability.spec.ts @@ -0,0 +1,432 @@ +import { expect, test, type Page, type Locator } from '@playwright/test'; +import type { RecipeFieldsFragment } from '../contracts/generated'; + +const id = '11111111-1111-4111-8111-111111111111'; +const user = { + id: '22222222-2222-4222-8222-222222222222', + name: 'Chef', + email: 'chef@example.com', +}; +const recipe: RecipeFieldsFragment = { + id, + title: 'Usability soup', + description: 'A simple soup', + category: 'soup', + cuisine: null, + difficulty: 'easy', + visibility: 'private', + imageUrl: null, + sourceRecipeId: null, + prepMinutes: 5, + cookMinutes: 10, + servings: 2, + createdAt: '2026-10-22T12:00:00Z', + updatedAt: '2026-10-22T12:00:00Z', + author: user, + ingredients: Array.from({ length: 8 }, (_, i) => ({ + id: `ingredient-${i}`, + name: `Ingredient ${i + 1}`, + amount: 1, + unit: 'g', + note: null, + })), + instructions: Array.from({ length: 8 }, (_, i) => ({ + step: i + 1, + text: `Prepare step ${i + 1}.`, + })), + tags: [], + rating: { average: 0, count: 0 }, + userRating: null, + saveCount: 0, + isSaved: false, + isCreatedByCurrentUser: true, +}; + +async function mockApi(page: Page, signedIn = true) { + let authenticated = signedIn; + const limits: Array = []; + await page.route('**/project2/api/graphql', async (route) => { + const { query, variables } = route.request().postDataJSON() as { + query: string; + variables: { input?: { maxCookingMinutes?: number | null } }; + }; + let data; + if (query.includes('mutation Login')) { + authenticated = true; + data = { login: { user } }; + } else if (query.includes('currentUser')) + data = { currentUser: authenticated ? user : null }; + else if ( + query.includes('query Recipes') || + query.includes('query Cookbook') + ) { + limits.push(variables.input?.maxCookingMinutes ?? null); + const list = { + items: [ + { + ...recipe, + title: + variables.input?.maxCookingMinutes == null + ? 'All time recipes' + : 'Time filtered recipes', + }, + ], + totalCount: 1, + totalPages: 1, + page: 1, + pageSize: 6, + }; + data = { recipes: list, cookbook: list }; + } else data = { recipe: authenticated ? recipe : null }; + await route.fulfill({ json: { data } }); + }); + return limits; +} + +async function expectFieldVisibleBelowHeader(page: Page, input: Locator) { + await expect(input).toBeFocused(); + const bounds = await input.locator('..').boundingBox(); + const headerBottom = await page + .locator('.site-header') + .evaluate((el) => el.getBoundingClientRect().bottom); + expect(bounds).not.toBeNull(); + expect(bounds!.y).toBeGreaterThanOrEqual(headerBottom); + expect(bounds!.y + bounds!.height).toBeLessThanOrEqual( + page.viewportSize()!.height, + ); +} + +for (const viewport of [ + { width: 1280, height: 800 }, + { width: 390, height: 844 }, +]) { + test(`editor feedback and later ingredient validation are visible at ${viewport.width}px`, async ({ + page, + }) => { + await page.setViewportSize(viewport); + await mockApi(page); + await page.goto(`recipes/${id}/edit`); + const amount = page.getByRole('spinbutton', { + name: 'Ingredient 7 amount', + exact: true, + }); + await amount.fill('0'); + await page.getByRole('button', { name: 'Save changes' }).click(); + await expectFieldVisibleBelowHeader(page, amount); + await page.getByRole('button', { name: 'Save changes' }).click(); + await expectFieldVisibleBelowHeader(page, amount); + await page.getByRole('button', { name: 'Save draft', exact: true }).click(); + const toast = page.locator('.recipe-create-page__toast-region'); + await expect(toast.getByText('Draft saved', { exact: true })).toBeVisible(); + await expect(toast).toBeInViewport(); + await page.reload(); + await page + .getByRole('button', { name: 'Discard draft', exact: true }) + .click(); + const dialog = page.getByRole('dialog', { name: 'Discard saved draft?' }); + await expect(dialog).toBeVisible(); + await page.keyboard.press('Escape'); + await expect(dialog).not.toBeVisible(); + await expect(page.getByText('Saved draft found')).toBeVisible(); + await page + .getByRole('button', { name: 'Discard draft', exact: true }) + .click(); + await dialog.getByRole('button', { name: 'Discard draft' }).click(); + await expect(page.getByText('Draft discarded.')).toBeVisible(); + }); +} + +for (const path of ['.', 'cookbook']) { + test(`desktop custom time validates, debounces, and clears on ${path}`, async ({ + page, + }) => { + await page.setViewportSize({ width: 1600, height: 1000 }); + const limits = await mockApi(page); + await page.goto(path); + await expect( + page.getByText('1 recipe found', { exact: false }), + ).toBeVisible(); + await page + .getByRole('combobox', { name: 'Cooking time', exact: true }) + .selectOption('custom'); + const input = page.getByRole('textbox', { + name: 'Maximum cooking time', + exact: true, + }); + await input.fill('abc'); + await expect( + page.getByText('Enter whole minutes from 1 to 20,160.'), + ).toBeVisible(); + expect(limits).not.toContain(20161); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= window.innerWidth, + ), + ).toBe(true); + await input.fill('20161'); + await expect(page).toHaveURL(/maxTime=20161/); + await expect.poll(() => limits).toContain(20160); + await expect(input).toHaveValue('20161'); + await expect(input).toHaveAttribute('aria-invalid', 'true'); + await input.fill(''); + await expect(page.getByText('No time limit applied.')).toHaveClass( + 'sr-only', + ); + await expect(page).not.toHaveURL(/maxTime=/); + // Clearing can reuse the cached unfiltered query without another request. + await expect( + page.getByRole('heading', { name: 'All time recipes', exact: true }), + ).toBeVisible(); + const search = page.getByRole('searchbox'); + await search.fill('a'.repeat(201)); + await page.getByRole('button', { name: 'Search', exact: true }).click(); + await expect( + page.getByText('Use at most 200 characters for search.'), + ).toBeVisible(); + await expect(page).not.toHaveURL(/q=/); + }); + + test(`mobile empty custom maximum removes the limit on ${path}`, async ({ + page, + }) => { + await page.setViewportSize({ width: 390, height: 844 }); + const limits = await mockApi(page); + await page.goto(path); + await page.getByRole('button', { name: 'Filters', exact: true }).click(); + await page + .getByRole('button', { name: 'Custom maximum', exact: true }) + .click(); + const input = page.getByRole('textbox', { + name: 'Maximum cooking time in minutes', + }); + await input.fill('abc'); + await page.getByRole('button', { name: 'Apply filters' }).click(); + await expect( + page.getByRole('dialog', { name: 'Filter recipes' }), + ).toBeVisible(); + await expect( + page.getByText('Enter whole minutes from 1 to 20,160.'), + ).toBeVisible(); + await input.fill(''); + await page.getByRole('button', { name: 'Apply filters' }).click(); + await expect( + page.getByRole('dialog', { name: 'Filter recipes' }), + ).not.toBeVisible(); + expect(limits).not.toContain(20161); + await expect( + page.getByRole('button', { name: 'Filters', exact: true }), + ).toBeVisible(); + }); +} + +test('a logged-out private recipe bookmark returns to the recipe after login', async ({ + page, +}) => { + await mockApi(page, false); + await page.goto(`recipes/${id}?view=full#ingredients`); + await expect( + page.getByRole('heading', { name: 'Recipe not found' }), + ).toBeVisible(); + await page + .getByRole('main') + .getByRole('link', { name: 'Log in', exact: true }) + .click(); + await page.getByRole('textbox', { name: 'Email' }).fill(user.email); + await page.getByLabel('Password', { exact: false }).fill('secret123'); + await page.getByRole('button', { name: 'Log in', exact: true }).click(); + await expect(page).toHaveURL( + new RegExp(`recipes/${id}\\?view=full#ingredients$`), + ); + await expect( + page.getByRole('heading', { name: 'Usability soup', exact: true }), + ).toBeVisible(); +}); + +for (const path of ['.', 'cookbook']) { + const breakpointWidths = path === '.' ? [961, 1000] : [1153, 1200]; + for (const width of breakpointWidths) { + test(`invalid time feedback fits ${path} at ${width}px`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 900 }); + await mockApi(page); + await page.goto(path); + await page + .getByRole('combobox', { name: 'Cooking time', exact: true }) + .selectOption('custom'); + const input = page.getByRole('textbox', { + name: 'Maximum cooking time', + exact: true, + }); + await input.fill('abc'); + await expect( + page.getByText('Enter whole minutes from 1 to 20,160.'), + ).toBeVisible(); + expect( + await page.evaluate(() => document.documentElement.scrollWidth), + ).toBeLessThanOrEqual(width); + const fieldTop = (await input.boundingBox())!.y; + for (const name of ['Category', 'Cooking time', 'Sort by']) { + const bounds = await page + .getByRole('combobox', { name, exact: true }) + .boundingBox(); + expect(Math.abs(bounds!.y - fieldTop)).toBeLessThan(1); + } + await input.fill('x'.repeat(300)); + expect( + await page.evaluate(() => document.documentElement.scrollWidth), + ).toBeLessThanOrEqual(width); + }); + } + + for (const width of [390, 1280]) { + test(`search validation keeps its button aligned on ${path} at ${width}px`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 900 }); + await mockApi(page); + await page.goto(path); + const button = page.getByRole('button', { name: 'Search', exact: true }); + const before = await button.evaluate( + (el) => el.getBoundingClientRect().top + window.scrollY, + ); + await page.getByRole('searchbox').fill('a'.repeat(201)); + await expect( + page.getByText('Use at most 200 characters for search.'), + ).toBeVisible(); + const after = await button.evaluate( + (el) => el.getBoundingClientRect().top + window.scrollY, + ); + expect(Math.abs(after - before)).toBeLessThan(1); + const input = await page.getByRole('searchbox').boundingBox(); + if (width > 704) { + const bounds = await button.boundingBox(); + expect(Math.abs(bounds!.y - input!.y)).toBeLessThan(1); + } + }); + + for (const raw of ['abc', '1.5']) { + test(`bookmarked ${raw} is visible and recoverable on ${path} at ${width}px`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 900 }); + const limits = await mockApi(page); + await page.goto(`${path}?time=custom&maxTime=${raw}`); + await expect( + page.getByText('Invalid time filter', { exact: true }), + ).toBeVisible(); + expect(limits).toEqual([]); + // Changing another filter must not silently discard the invalid bookmark. + if (width > 1000 && path === '.') { + await page + .getByRole('combobox', { name: 'Category', exact: true }) + .selectOption('soup'); + await expect(page).toHaveURL(new RegExp(`maxTime=${raw}`)); + } + await page + .getByRole('button', { name: 'Edit time filter', exact: true }) + .click(); + const input = page.getByRole('textbox', { + name: + width === 390 + ? 'Maximum cooking time in minutes' + : 'Maximum cooking time', + exact: true, + }); + await expect(input).toBeFocused(); + await expect(input).toHaveValue(raw); + await input.fill(''); + if (width === 390) + await page.getByRole('button', { name: 'Apply filters' }).click(); + await expect(page).not.toHaveURL(/maxTime=/); + await expect( + page.getByText('Invalid time filter', { exact: true }), + ).not.toBeVisible(); + await expect( + page.getByRole('heading', { name: 'All time recipes', exact: true }), + ).toBeVisible(); + expect(limits).toEqual([null]); + if (width !== 390) { + const help = page + .getByRole('group', { + name: + path === '.' + ? 'Explore filters and sorting' + : 'Cookbook filters and sorting', + }) + .getByText('No time limit applied.', { exact: true }); + await expect(help).toHaveClass('sr-only'); + const bounds = await help.boundingBox(); + expect(bounds!.width).toBeLessThanOrEqual(1); + expect(bounds!.height).toBeLessThanOrEqual(1); + } + }); + } + } + + test(`malformed limit can be replaced with valid minutes on ${path}`, async ({ + page, + }) => { + await page.setViewportSize({ width: 1280, height: 900 }); + const limits = await mockApi(page); + await page.goto(`${path}?time=custom&maxTime=abc`); + await page + .getByRole('textbox', { name: 'Maximum cooking time', exact: true }) + .fill('30'); + await expect(page).toHaveURL(/maxTime=30/); + await expect( + page.getByText('Invalid time filter', { exact: true }), + ).not.toBeVisible(); + await expect.poll(() => limits).toEqual([30]); + }); +} + +for (const path of ['.', 'cookbook']) { + for (const width of [390, 1280]) { + test(`numeric limits clamp to bounds on ${path} at ${width}px`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 900 }); + const limits = await mockApi(page); + await page.goto(`${path}?time=custom&maxTime=99999`); + await expect(page).toHaveURL(/maxTime=99999/); + await expect.poll(() => limits).toEqual([20160]); + if (width === 390) + await page + .getByRole('button', { name: 'Filters (1)', exact: true }) + .click(); + const input = page.getByRole('textbox', { + name: + width === 390 + ? 'Maximum cooking time in minutes' + : 'Maximum cooking time', + exact: true, + }); + await expect(input).toHaveValue('99999'); + await expect(input).toHaveAttribute('aria-invalid', 'true'); + await input.fill('-5'); + if (width === 390) + await page + .getByRole('button', { name: 'Apply filters', exact: true }) + .click(); + else await input.blur(); + await expect(page).toHaveURL(/maxTime=-5(?:&|$)/); + await expect.poll(() => limits).toEqual([20160, 1]); + if (width === 390) + await page + .getByRole('button', { name: 'Filters (1)', exact: true }) + .click(); + await expect(input).toHaveValue('-5'); + await expect(input).toHaveAttribute('aria-invalid', 'true'); + await expect( + input + .locator('..') + .getByText('Enter whole minutes from 1 to 20,160.', { exact: true }), + ).toBeVisible(); + + await expect( + page.getByText('Invalid time filter', { exact: true }), + ).not.toBeVisible(); + }); + } +}