From c2324f53f69cd4797e51cc2aa6bbe01d75de69ad Mon Sep 17 00:00:00 2001 From: olestang Date: Fri, 9 Oct 2026 11:07:46 +0200 Subject: [PATCH 1/4] feat: implement cookbook browsing with shared recipe logic --- apps/web/src/App.tsx | 6 +- .../features/cookbook/CookbookControls.css | 182 +++++++ .../features/cookbook/CookbookControls.tsx | 469 ++++++++++++++++++ .../src/features/cookbook/CookbookPage.css | 87 ++++ .../features/cookbook/CookbookPage.test.tsx | 236 +++++++++ .../src/features/cookbook/CookbookPage.tsx | 328 ++++++++++++ .../features/cookbook/cookbookBrowseState.ts | 64 +++ .../cookbook/cookbookUrlState.test.ts | 93 ++++ .../src/features/cookbook/cookbookUrlState.ts | 116 +++++ .../cookbook/mockCookbookQuery.test.ts | 182 +++++++ .../features/cookbook/mockCookbookQuery.ts | 101 ++++ .../src/features/explore/ExploreControls.css | 2 +- apps/web/src/features/explore/ExplorePage.tsx | 5 +- .../features/explore/exploreBrowseState.ts | 107 +--- .../src/features/explore/mockExploreQuery.ts | 54 +- apps/web/src/lib/recipeBrowse/recipeBrowse.ts | 174 +++++++ 16 files changed, 2072 insertions(+), 134 deletions(-) create mode 100644 apps/web/src/features/cookbook/CookbookControls.css create mode 100644 apps/web/src/features/cookbook/CookbookControls.tsx create mode 100644 apps/web/src/features/cookbook/CookbookPage.css create mode 100644 apps/web/src/features/cookbook/CookbookPage.test.tsx create mode 100644 apps/web/src/features/cookbook/CookbookPage.tsx create mode 100644 apps/web/src/features/cookbook/cookbookBrowseState.ts create mode 100644 apps/web/src/features/cookbook/cookbookUrlState.test.ts create mode 100644 apps/web/src/features/cookbook/cookbookUrlState.ts create mode 100644 apps/web/src/features/cookbook/mockCookbookQuery.test.ts create mode 100644 apps/web/src/features/cookbook/mockCookbookQuery.ts create mode 100644 apps/web/src/lib/recipeBrowse/recipeBrowse.ts diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index fd1846a..41be448 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -7,6 +7,7 @@ import LoginPage from './features/auth/LoginPage'; import RegisterPage from './features/auth/RegisterPage'; import ExplorePage from './features/explore/ExplorePage'; +import CookbookPage from './features/cookbook/CookbookPage'; import RecipeCreatePage from './features/recipes/RecipeCreatePage'; export function App() { @@ -15,10 +16,7 @@ export function App() { }> } /> - } - /> + } /> } /> void; + onBrowseStateChange: (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': + return 'Recipes: Saved'; + + case 'created': + return 'Recipes: Created'; + + case 'all': + return 'Recipes: All'; + } +} + +function CookbookControls({ + scope, + browseState, + onScopeChange, + onBrowseStateChange, +}: CookbookControlsProps) { + const [filterSheetOpen, setFilterSheetOpen] = useState(false); + const [sortSheetOpen, setSortSheetOpen] = useState(false); + + const [filterDraft, setFilterDraft] = useState({ + category: browseState.category, + cookingTime: browseState.cookingTime, + customMaxMinutes: browseState.customMaxMinutes, + }); + + const [sortDraft, setSortDraft] = useState(browseState.sort); + const [showCustomTimeError, setShowCustomTimeError] = useState(false); + + /* + * On mobile, Saved / Created lives inside the filter sheet. + * Count a non-default scope as an active filter so the Filters button + * communicates that the Cookbook has been narrowed. + */ + const activeFilterCount = + countActiveRecipeFilters(browseState) + (scope === 'all' ? 0 : 1); + + const currentSortLabel = getCookbookSortLabel(browseState.sort); + + function updateBrowseState(patch: Partial) { + onBrowseStateChange({ + ...browseState, + ...patch, + }); + } + + function handleDesktopCookingTimeChange(cookingTime: RecipeCookingTime) { + updateBrowseState({ + cookingTime, + customMaxMinutes: + cookingTime === 'custom' ? browseState.customMaxMinutes : null, + }); + } + + function handleDesktopCustomMaxChange(rawValue: string) { + updateBrowseState({ + cookingTime: 'custom', + customMaxMinutes: parseCustomMaxMinutes(rawValue), + }); + } + + function openFilterSheet() { + setFilterDraft({ + category: browseState.category, + cookingTime: browseState.cookingTime, + customMaxMinutes: browseState.customMaxMinutes, + }); + + setShowCustomTimeError(false); + setFilterSheetOpen(true); + } + + function handleDraftCookingTimeChange(cookingTime: RecipeCookingTime) { + setFilterDraft((current) => ({ + ...current, + cookingTime, + customMaxMinutes: + cookingTime === 'custom' ? current.customMaxMinutes : null, + })); + + setShowCustomTimeError(false); + } + + function handleApplyFilters() { + if ( + filterDraft.cookingTime === 'custom' && + filterDraft.customMaxMinutes === null + ) { + setShowCustomTimeError(true); + return; + } + + onBrowseStateChange({ + ...browseState, + ...filterDraft, + }); + + setFilterSheetOpen(false); + } + + function handleClearFilters() { + /* + * Scope is applied immediately in the mobile sheet, so reset it + * immediately as well. Category/time remain draft values until Apply. + */ + onScopeChange('all'); + + setFilterDraft({ + ...DEFAULT_RECIPE_FILTER_STATE, + }); + + setShowCustomTimeError(false); + } + + function openSortSheet() { + setSortDraft(browseState.sort); + setSortSheetOpen(true); + } + + function handleApplySort() { + updateBrowseState({ + sort: sortDraft, + }); + + setSortSheetOpen(false); + } + + return ( + <> +
+
+ Cookbook filters and sorting + +
+ +
+ +
+ +
+ +
+ +
+ + {browseState.cookingTime === 'custom' && ( +
+ + handleDesktopCustomMaxChange(event.currentTarget.value) + } + /> +
+ )} + +
+ +
+
+ +
+ + + +
+
+ + setFilterSheetOpen(false)} + footer={ +
+ + + +
+ } + > +
+
+ + Recipes + + +
+ {COOKBOOK_SCOPE_OPTIONS.map((option) => ( + onScopeChange(option.value)} + > + {option.label} + + ))} +
+
+ +
+ + Category + + +
+ {RECIPE_CATEGORY_OPTIONS.map((option) => ( + + setFilterDraft((current) => ({ + ...current, + category: option.value, + })) + } + > + {option.label} + + ))} +
+
+ +
+ + Cooking time + + +
+ {RECIPE_COOKING_TIME_OPTIONS.map((option) => ( + handleDraftCookingTimeChange(option.value)} + > + {option.label} + + ))} +
+ + {filterDraft.cookingTime === 'custom' && ( +
+ { + const customMaxMinutes = parseCustomMaxMinutes( + event.currentTarget.value, + ); + + setFilterDraft((current) => ({ + ...current, + cookingTime: 'custom', + customMaxMinutes, + })); + + setShowCustomTimeError(false); + }} + /> +
+ )} +
+
+
+ + setSortSheetOpen(false)} + footer={ +
+ +
+ } + > + + {COOKBOOK_SORT_OPTIONS.map((option) => ( + setSortDraft(option.value)} + /> + ))} + +
+ + ); +} + +export default CookbookControls; diff --git a/apps/web/src/features/cookbook/CookbookPage.css b/apps/web/src/features/cookbook/CookbookPage.css new file mode 100644 index 0000000..4ee1844 --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookPage.css @@ -0,0 +1,87 @@ +@layer components { + .cookbook-page { + display: flex; + flex-direction: column; + gap: var(--space-8); + + padding-block: var(--space-10) var(--space-16); + } + + .cookbook-page__header { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-2); + + max-width: 48rem; + margin-inline: auto; + + text-align: center; + } + + .cookbook-page__subtitle { + color: var(--color-text-secondary); + + font-size: var(--font-size-lg); + line-height: var(--line-height-relaxed); + } + + .cookbook-page__search-form { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: end; + gap: var(--space-3); + + width: min(100%, 52rem); + margin-inline: auto; + } + + .cookbook-page__results { + display: flex; + flex-direction: column; + gap: var(--space-6); + } + + .cookbook-page__result-count { + color: var(--color-text-secondary); + + font-size: var(--font-size-sm); + font-weight: var(--font-weight-medium); + } + + .cookbook-page__grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-6); + } + + .cookbook-page__pagination { + margin-block-start: var(--space-2); + } + + @media (max-width: 65rem) { + .cookbook-page__grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + } + + @media (max-width: 44rem) { + .cookbook-page { + gap: var(--space-6); + + padding-block: var(--space-8) var(--space-12); + } + + .cookbook-page__search-form { + grid-template-columns: 1fr; + } + + .cookbook-page__search-button { + width: 100%; + } + + .cookbook-page__grid { + grid-template-columns: 1fr; + } + } +} diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx new file mode 100644 index 0000000..370494e --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx @@ -0,0 +1,236 @@ +import { render, screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, useLocation } from 'react-router-dom'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { INITIAL_SAVED_RECIPE_IDS, useAppStore } from '../../store'; + +import CookbookPage from './CookbookPage'; + +const scrollToMock = vi.fn(); + +function LocationProbe() { + const location = useLocation(); + + return {location.search}; +} + +function renderCookbookPage(initialEntry = '/cookbook') { + return render( + + + + , + ); +} + +describe('CookbookPage', () => { + beforeEach(() => { + scrollToMock.mockClear(); + + useAppStore.setState({ + savedRecipeIds: [...INITIAL_SAVED_RECIPE_IDS], + }); + + Object.defineProperty(window, 'scrollTo', { + value: scrollToMock, + writable: true, + }); + }); + + it('shows All by default', () => { + renderCookbookPage(); + + expect( + screen.getByRole('heading', { + name: 'My Cookbook', + }), + ).toBeTruthy(); + + expect(screen.getByText('8 recipes found')).toBeTruthy(); + + expect( + ( + screen.getByRole('combobox', { + name: 'Recipe source', + }) as HTMLSelectElement + ).value, + ).toBe('all'); + }); + + it('switches to Saved and writes the scope to the URL', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Recipe source', + }), + 'saved', + ); + + expect(screen.getByText('4 recipes found')).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?view=saved', + ); + }); + + it('shows private owned recipes in Created', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.selectOptions( + screen.getByRole('combobox', { + name: 'Recipe source', + }), + 'created', + ); + + expect( + screen.getByRole('link', { + name: 'Simple tomato soup', + }), + ).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Slow-cooked lamb and vegetable stew', + }), + ).toBeTruthy(); + }); + + it('searches Cookbook and writes search to the URL', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + const searchInput = screen.getByRole('searchbox', { + name: 'Search cookbook recipes', + }); + + await user.type(searchInput, 'lentils'); + + await user.click( + screen.getByRole('button', { + name: 'Search', + }), + ); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Red lentil soup', + }), + ).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?q=lentils', + ); + }); + + it('restores scope, filters, and sort from the URL', () => { + renderCookbookPage( + '/cookbook?view=created&category=dinner&sort=alphabetical', + ); + + expect( + ( + screen.getByRole('combobox', { + name: 'Recipe source', + }) as HTMLSelectElement + ).value, + ).toBe('created'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Category', + }) as HTMLSelectElement + ).value, + ).toBe('dinner'); + + expect( + ( + screen.getByRole('combobox', { + name: 'Sort by', + }) as HTMLSelectElement + ).value, + ).toBe('alphabetical'); + }); + + it('does not add Save, Unsave, or Edit actions to cookbook cards', () => { + renderCookbookPage(); + + const firstCard = screen.getAllByRole('article')[0]; + + expect(firstCard).toBeTruthy(); + + if (!firstCard) { + return; + } + + expect( + within(firstCard).queryByRole('button', { + name: /Save .* to My Cookbook/i, + }), + ).toBeNull(); + + expect( + within(firstCard).queryByRole('button', { + name: /Remove .* from My Cookbook/i, + }), + ).toBeNull(); + + expect( + within(firstCard).queryByRole('button', { + name: /Edit/i, + }), + ).toBeNull(); + }); + + it('shows recipe source choices inside the filter sheet', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + expect( + screen.getByRole('button', { + name: 'All', + }), + ).toBeTruthy(); + + expect( + screen.getByRole('button', { + name: 'Saved', + }), + ).toBeTruthy(); + + expect( + screen.getByRole('button', { + name: 'Created', + }), + ).toBeTruthy(); + }); + + it('counts a non-default recipe source as an active filter', () => { + renderCookbookPage('/cookbook?view=saved'); + + expect( + screen.getByRole('button', { + name: 'Filters (1)', + hidden: true, + }), + ).toBeTruthy(); + }); +}); diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx new file mode 100644 index 0000000..d478604 --- /dev/null +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -0,0 +1,328 @@ +import { useEffect, useMemo, useRef, useState, type SubmitEvent } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; + +import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; +import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps'; +import Button from '../../components/ui/Button/Button'; +import EmptyState from '../../components/ui/EmptyState/EmptyState'; +import Field from '../../components/ui/Field/Field'; +import Pagination from '../../components/ui/Pagination/Pagination'; +import { CookbookIcon, SearchIcon } from '../../icons/navigation'; +import { + DEFAULT_RECIPE_FILTER_STATE, + RECIPE_PAGE_SIZE, +} from '../../lib/recipeBrowse/recipeBrowse'; +import { useAppStore } from '../../store'; + +import CookbookControls from './CookbookControls'; +import { + countActiveCookbookFilters, + getCookbookQueryFilters, + type CookbookBrowseState, + type CookbookScope, +} from './cookbookBrowseState'; +import { + createCookbookSearchParams, + readCookbookUrlState, + type CookbookUrlState, +} from './cookbookUrlState'; +import { getMockCookbookResult } from './mockCookbookQuery'; +import './CookbookPage.css'; + +function CookbookPage() { + const searchInputRef = useRef(null); + + const navigate = useNavigate(); + const [searchParams, setSearchParams] = useSearchParams(); + + const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); + + const { scope, search, browseState, page } = useMemo( + () => readCookbookUrlState(searchParams), + [searchParams], + ); + + const [searchInput, setSearchInput] = useState(search); + + const queryFilters = getCookbookQueryFilters(browseState); + + const result = getMockCookbookResult({ + scope, + search, + savedRecipeIds, + ...queryFilters, + page, + pageSize: RECIPE_PAGE_SIZE, + }); + + const activeFilterCount = countActiveCookbookFilters(browseState); + + const hasSearch = search.length > 0; + const hasActiveFilters = activeFilterCount > 0; + const hasSearchOrFilters = hasSearch || hasActiveFilters; + + useEffect(() => { + setSearchInput(search); + }, [search]); + + /** + * paginate() normalizes invalid/out-of-range pages. + * Keep the URL synchronized with that normalized result. + */ + useEffect(() => { + if (result.page === page) { + return; + } + + setSearchParams( + createCookbookSearchParams({ + scope, + search, + browseState, + page: result.page, + }), + { + replace: true, + }, + ); + }, [browseState, page, result.page, scope, search, setSearchParams]); + + function updateUrlState(nextState: CookbookUrlState, replace = false) { + setSearchParams(createCookbookSearchParams(nextState), { + replace, + }); + } + + function handleSearchSubmit(event: SubmitEvent) { + event.preventDefault(); + + updateUrlState({ + scope, + search: searchInput, + browseState, + page: 1, + }); + } + + function handleScopeChange(nextScope: CookbookScope) { + updateUrlState({ + scope: nextScope, + search, + browseState, + page: 1, + }); + } + + function handleBrowseStateChange(nextBrowseState: CookbookBrowseState) { + const replaceCurrentEntry = + browseState.cookingTime === 'custom' && + nextBrowseState.cookingTime === 'custom'; + + updateUrlState( + { + scope, + search, + browseState: nextBrowseState, + page: 1, + }, + replaceCurrentEntry, + ); + } + + function handleClearResultCriteria() { + const nextBrowseState: CookbookBrowseState = { + ...DEFAULT_RECIPE_FILTER_STATE, + sort: browseState.sort, + }; + + setSearchInput(''); + + updateUrlState({ + scope, + search: '', + browseState: nextBrowseState, + page: 1, + }); + + requestAnimationFrame(() => { + searchInputRef.current?.focus(); + }); + } + + function handlePageChange(nextPage: number) { + updateUrlState({ + scope, + search, + browseState, + page: nextPage, + }); + + window.scrollTo({ + top: 0, + left: 0, + behavior: 'auto', + }); + } + + let emptyStateTitle = 'Your cookbook is empty'; + + let emptyStateDescription = + 'Save recipes from Explore or create your own recipe to build your cookbook.'; + + let emptyStateAction = ( + <> + + + + + ); + + if (hasSearchOrFilters) { + emptyStateTitle = hasSearch + ? `No cookbook recipes found for “${search}”` + : 'No cookbook recipes found with these filters'; + + emptyStateDescription = + 'Try changing your search or filters, or clear them to see more recipes.'; + + let clearActionLabel = 'Clear filters'; + + if (hasSearch && hasActiveFilters) { + clearActionLabel = 'Clear search and filters'; + } else if (hasSearch) { + clearActionLabel = 'Clear search'; + } + + emptyStateAction = ( + + ); + } else if (scope === 'saved') { + emptyStateTitle = 'No saved recipes yet'; + + emptyStateDescription = 'Recipes you save from Explore will appear here.'; + + emptyStateAction = ( + + ); + } else if (scope === 'created') { + emptyStateTitle = 'No created recipes yet'; + + emptyStateDescription = 'Recipes you create will appear here.'; + + emptyStateAction = ( + + ); + } + + return ( +
+
+

My Cookbook

+ +

+ Your saved and created recipes, all in one place. +

+
+ +
+ { + const value = event.currentTarget.value; + + setSearchInput(value); + + /** + * Match the current Explore behavior: + * clearing a submitted search immediately clears it from the URL. + */ + if (value === '' && search !== '') { + updateUrlState({ + scope, + search: '', + browseState, + page: 1, + }); + } + }} + /> + + + + +
+

+ Cookbook recipe results +

+ + + +

+ {result.totalItems} {result.totalItems === 1 ? 'recipe' : 'recipes'}{' '} + found + + {search ? ` for “${search}”` : ''} + + {result.pageCount > 0 + ? `. Page ${result.page} of ${result.pageCount}.` + : '.'} + +

+ + {result.totalItems > 0 ? ( + <> +
+ {result.items.map((recipe) => ( + + ))} +
+ +
+ +
+ + ) : ( + + )} +
+
+ ); +} + +export default CookbookPage; diff --git a/apps/web/src/features/cookbook/cookbookBrowseState.ts b/apps/web/src/features/cookbook/cookbookBrowseState.ts new file mode 100644 index 0000000..725ab93 --- /dev/null +++ b/apps/web/src/features/cookbook/cookbookBrowseState.ts @@ -0,0 +1,64 @@ +import { + DEFAULT_RECIPE_FILTER_STATE, + countActiveRecipeFilters, + getRecipeQueryFilters, + type RecipeFilterState, + type RecipeQueryFilters, +} from '../../lib/recipeBrowse/recipeBrowse'; + +export const COOKBOOK_SCOPE_OPTIONS = [ + { value: 'all', label: 'All' }, + { value: 'saved', label: 'Saved' }, + { value: 'created', label: 'Created' }, +] as const; + +export type CookbookScope = (typeof COOKBOOK_SCOPE_OPTIONS)[number]['value']; + +export const COOKBOOK_SORT_OPTIONS = [ + { value: 'recently-updated', label: 'Recently updated' }, + { value: 'cooking-time', label: 'Cooking time' }, + { value: 'alphabetical', label: 'A–Z' }, +] as const; + +export type CookbookSort = (typeof COOKBOOK_SORT_OPTIONS)[number]['value']; + +export type CookbookBrowseState = RecipeFilterState & { + sort: CookbookSort; +}; + +export type CookbookQueryFilters = RecipeQueryFilters & { + sort: CookbookSort; +}; + +export const DEFAULT_COOKBOOK_BROWSE_STATE: CookbookBrowseState = { + ...DEFAULT_RECIPE_FILTER_STATE, + sort: 'recently-updated', +}; + +export function isCookbookScope(value: string | null): value is CookbookScope { + return COOKBOOK_SCOPE_OPTIONS.some((option) => option.value === value); +} + +export function isCookbookSort(value: string | null): value is CookbookSort { + return COOKBOOK_SORT_OPTIONS.some((option) => option.value === value); +} + +export function getCookbookQueryFilters( + state: CookbookBrowseState, +): CookbookQueryFilters { + return { + ...getRecipeQueryFilters(state), + sort: state.sort, + }; +} + +export function countActiveCookbookFilters(state: CookbookBrowseState) { + return countActiveRecipeFilters(state); +} + +export function getCookbookSortLabel(sort: CookbookSort) { + return ( + COOKBOOK_SORT_OPTIONS.find((option) => option.value === sort)?.label ?? + 'Recently updated' + ); +} diff --git a/apps/web/src/features/cookbook/cookbookUrlState.test.ts b/apps/web/src/features/cookbook/cookbookUrlState.test.ts new file mode 100644 index 0000000..2f077ec --- /dev/null +++ b/apps/web/src/features/cookbook/cookbookUrlState.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; + +import { DEFAULT_COOKBOOK_BROWSE_STATE } from './cookbookBrowseState'; +import { + createCookbookSearchParams, + readCookbookUrlState, +} from './cookbookUrlState'; + +describe('Cookbook URL state', () => { + it('uses default state for an empty URL', () => { + expect(readCookbookUrlState(new URLSearchParams())).toEqual({ + scope: 'all', + search: '', + browseState: DEFAULT_COOKBOOK_BROWSE_STATE, + page: 1, + }); + }); + + it('reads scope, search, filters, sort, and page', () => { + const state = readCookbookUrlState( + new URLSearchParams( + 'view=saved&q=soup&category=dinner&time=lte60&sort=cooking-time&page=2', + ), + ); + + expect(state).toEqual({ + scope: 'saved', + search: 'soup', + browseState: { + category: 'dinner', + cookingTime: 'lte60', + customMaxMinutes: null, + sort: 'cooking-time', + }, + page: 2, + }); + }); + + it('omits defaults when writing URL state', () => { + const params = createCookbookSearchParams({ + scope: 'all', + search: '', + browseState: DEFAULT_COOKBOOK_BROWSE_STATE, + page: 1, + }); + + expect(params.toString()).toBe(''); + }); + + it('writes non-default state', () => { + const params = createCookbookSearchParams({ + scope: 'created', + search: ' cake ', + browseState: { + category: 'dessert', + cookingTime: 'custom', + customMaxMinutes: 75, + sort: 'alphabetical', + }, + page: 2, + }); + + expect(params.toString()).toBe( + 'view=created&q=cake&category=dessert&time=custom&maxTime=75&sort=alphabetical&page=2', + ); + }); + + it('restores written state', () => { + const params = createCookbookSearchParams({ + scope: 'saved', + search: 'soup', + browseState: { + category: 'soup', + cookingTime: 'lte60', + customMaxMinutes: null, + sort: 'cooking-time', + }, + page: 2, + }); + + expect(readCookbookUrlState(params)).toEqual({ + scope: 'saved', + search: 'soup', + browseState: { + category: 'soup', + cookingTime: 'lte60', + customMaxMinutes: null, + sort: 'cooking-time', + }, + page: 2, + }); + }); +}); diff --git a/apps/web/src/features/cookbook/cookbookUrlState.ts b/apps/web/src/features/cookbook/cookbookUrlState.ts new file mode 100644 index 0000000..3078b9d --- /dev/null +++ b/apps/web/src/features/cookbook/cookbookUrlState.ts @@ -0,0 +1,116 @@ +import { + isRecipeCategory, + isRecipeCookingTime, +} from '../../lib/recipeBrowse/recipeBrowse'; + +import { + DEFAULT_COOKBOOK_BROWSE_STATE, + isCookbookScope, + isCookbookSort, + type CookbookBrowseState, + type CookbookScope, +} from './cookbookBrowseState'; + +export type CookbookUrlState = { + scope: CookbookScope; + search: string; + browseState: CookbookBrowseState; + page: number; +}; + +function parsePositiveInteger(value: string | null) { + if (!value) { + return null; + } + + const parsed = Number(value); + + return Number.isInteger(parsed) && parsed > 0 ? parsed : null; +} + +export function readCookbookUrlState( + searchParams: URLSearchParams, +): CookbookUrlState { + const scopeParam = searchParams.get('view'); + const categoryParam = searchParams.get('category'); + const cookingTimeParam = searchParams.get('time'); + const sortParam = searchParams.get('sort'); + + const scope = isCookbookScope(scopeParam) ? scopeParam : 'all'; + + const category = isRecipeCategory(categoryParam) + ? categoryParam + : DEFAULT_COOKBOOK_BROWSE_STATE.category; + + const cookingTime = isRecipeCookingTime(cookingTimeParam) + ? cookingTimeParam + : DEFAULT_COOKBOOK_BROWSE_STATE.cookingTime; + + const sort = isCookbookSort(sortParam) + ? sortParam + : DEFAULT_COOKBOOK_BROWSE_STATE.sort; + + const customMaxMinutes = + cookingTime === 'custom' + ? parsePositiveInteger(searchParams.get('maxTime')) + : null; + + return { + scope, + + search: (searchParams.get('q') ?? '').trim(), + + browseState: { + category, + cookingTime, + customMaxMinutes, + sort, + }, + + page: parsePositiveInteger(searchParams.get('page')) ?? 1, + }; +} + +export function createCookbookSearchParams({ + scope, + search, + browseState, + page, +}: CookbookUrlState) { + const searchParams = new URLSearchParams(); + + const trimmedSearch = search.trim(); + + if (scope !== 'all') { + searchParams.set('view', scope); + } + + if (trimmedSearch) { + searchParams.set('q', trimmedSearch); + } + + if (browseState.category !== 'all') { + searchParams.set('category', browseState.category); + } + + if (browseState.cookingTime !== 'any') { + searchParams.set('time', browseState.cookingTime); + + if ( + browseState.cookingTime === 'custom' && + browseState.customMaxMinutes !== null + ) { + searchParams.set('maxTime', String(browseState.customMaxMinutes)); + } + } + + if (browseState.sort !== 'recently-updated') { + searchParams.set('sort', browseState.sort); + } + + if (page > 1) { + searchParams.set('page', String(page)); + } + + return searchParams; +} diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.test.ts b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts new file mode 100644 index 0000000..343a7f5 --- /dev/null +++ b/apps/web/src/features/cookbook/mockCookbookQuery.test.ts @@ -0,0 +1,182 @@ +import { describe, expect, it } from 'vitest'; + +import { INITIAL_SAVED_RECIPE_IDS } from '../../store'; + +import { getMockCookbookResult, type CookbookQuery } from './mockCookbookQuery'; + +function createQuery(overrides: Partial = {}): CookbookQuery { + return { + scope: 'all', + search: '', + savedRecipeIds: INITIAL_SAVED_RECIPE_IDS, + category: null, + maxCookingMinutes: null, + sort: 'recently-updated', + page: 1, + pageSize: 50, + ...overrides, + }; +} + +describe('getMockCookbookResult', () => { + it('returns the union of saved and created recipes for All', () => { + const result = getMockCookbookResult(createQuery()); + + expect(result.totalItems).toBe(8); + + expect( + result.items.every( + (recipe) => + recipe.isCreatedByCurrentUser || + INITIAL_SAVED_RECIPE_IDS.includes(recipe.id), + ), + ).toBe(true); + }); + + it('returns only runtime saved recipes for Saved', () => { + const result = getMockCookbookResult( + createQuery({ + scope: 'saved', + savedRecipeIds: ['salmon-pasta'], + }), + ); + + expect(result.items.map((recipe) => recipe.id)).toEqual(['salmon-pasta']); + }); + + it('returns only current-user recipes for Created', () => { + const result = getMockCookbookResult( + createQuery({ + scope: 'created', + }), + ); + + expect(result.items.every((recipe) => recipe.isCreatedByCurrentUser)).toBe( + true, + ); + }); + + it('includes current-user private recipes in Created', () => { + const result = getMockCookbookResult( + createQuery({ + scope: 'created', + }), + ); + + expect(result.items.map((recipe) => recipe.id)).toEqual( + expect.arrayContaining(['tomato-soup', 'lamb-stew']), + ); + }); + + it('uses the same ingredient search behavior as Explore', () => { + const result = getMockCookbookResult( + createQuery({ + search: 'red lentils', + }), + ); + + expect(result.items.map((recipe) => recipe.id)).toContain('lentil-soup'); + }); + + it('filters by category', () => { + const result = getMockCookbookResult( + createQuery({ + category: 'dinner', + }), + ); + + expect(result.items.every((recipe) => recipe.category === 'Dinner')).toBe( + true, + ); + }); + + it('filters by maximum cooking time', () => { + const result = getMockCookbookResult( + createQuery({ + maxCookingMinutes: 30, + }), + ); + + expect( + result.items.every( + (recipe) => recipe.prepMinutes + recipe.cookMinutes <= 30, + ), + ).toBe(true); + }); + + it('sorts recently updated by updatedAt descending', () => { + const result = getMockCookbookResult( + createQuery({ + sort: 'recently-updated', + }), + ); + + for (let index = 1; index < result.items.length; index += 1) { + const previous = result.items[index - 1]; + const current = result.items[index]; + + if (!previous || !current) { + continue; + } + + expect(Date.parse(previous.updatedAt)).toBeGreaterThanOrEqual( + Date.parse(current.updatedAt), + ); + } + }); + + it('sorts cooking time shortest first', () => { + const result = getMockCookbookResult( + createQuery({ + sort: 'cooking-time', + }), + ); + + for (let index = 1; index < result.items.length; index += 1) { + const previous = result.items[index - 1]; + const current = result.items[index]; + + if (!previous || !current) { + continue; + } + + const previousMinutes = previous.prepMinutes + previous.cookMinutes; + + const currentMinutes = current.prepMinutes + current.cookMinutes; + + expect(previousMinutes).toBeLessThanOrEqual(currentMinutes); + } + }); + + it('sorts alphabetically', () => { + const result = getMockCookbookResult( + createQuery({ + sort: 'alphabetical', + }), + ); + + const titles = result.items.map((recipe) => recipe.title); + + expect(titles).toEqual([...titles].sort((a, b) => a.localeCompare(b))); + }); + + it('paginates after scope, filtering, and sorting', () => { + const firstPage = getMockCookbookResult( + createQuery({ + page: 1, + pageSize: 6, + }), + ); + + const secondPage = getMockCookbookResult( + createQuery({ + page: 2, + pageSize: 6, + }), + ); + + expect(firstPage.totalItems).toBe(8); + expect(firstPage.items).toHaveLength(6); + expect(secondPage.items).toHaveLength(2); + }); +}); diff --git a/apps/web/src/features/cookbook/mockCookbookQuery.ts b/apps/web/src/features/cookbook/mockCookbookQuery.ts new file mode 100644 index 0000000..2a3d823 --- /dev/null +++ b/apps/web/src/features/cookbook/mockCookbookQuery.ts @@ -0,0 +1,101 @@ +import { recipes } from '../../data/recipes'; +import { paginate, type PageResult } from '../../lib/pagination/paginate'; +import { + filterRecipesByBrowseCriteria, + getRecipeTotalMinutes, + type RecipeQueryFilters, +} from '../../lib/recipeBrowse/recipeBrowse'; +import type { Recipe } from '../../types/recipe'; + +import type { CookbookScope, CookbookSort } from './cookbookBrowseState'; + +export type CookbookQuery = RecipeQueryFilters & { + scope: CookbookScope; + search: string; + savedRecipeIds: readonly string[]; + sort: CookbookSort; + page: number; + pageSize: number; +}; + +export type CookbookResult = PageResult; + +function compareRecentlyUpdated(a: Recipe, b: Recipe) { + const dateDifference = Date.parse(b.updatedAt) - Date.parse(a.updatedAt); + + if (dateDifference !== 0) { + return dateDifference; + } + + return a.title.localeCompare(b.title); +} + +function compareCookingTime(a: Recipe, b: Recipe) { + const timeDifference = getRecipeTotalMinutes(a) - getRecipeTotalMinutes(b); + + if (timeDifference !== 0) { + return timeDifference; + } + + return compareRecentlyUpdated(a, b); +} + +function compareAlphabetical(a: Recipe, b: Recipe) { + const titleDifference = a.title.localeCompare(b.title); + + if (titleDifference !== 0) { + return titleDifference; + } + + return compareRecentlyUpdated(a, b); +} + +const sortComparators: Record number> = + { + 'recently-updated': compareRecentlyUpdated, + 'cooking-time': compareCookingTime, + alphabetical: compareAlphabetical, + }; + +function sortRecipes(items: readonly Recipe[], sort: CookbookSort) { + return [...items].sort(sortComparators[sort]); +} + +export function getMockCookbookResult({ + scope, + search, + savedRecipeIds, + category, + maxCookingMinutes, + sort, + page, + pageSize, +}: CookbookQuery): CookbookResult { + const savedIds = new Set(savedRecipeIds); + + const scopedRecipes = recipes.filter((recipe) => { + const isSaved = savedIds.has(recipe.id); + const isCreated = recipe.isCreatedByCurrentUser; + + switch (scope) { + case 'saved': + return isSaved; + + case 'created': + return isCreated; + + case 'all': + return isSaved || isCreated; + } + }); + + const filteredRecipes = filterRecipesByBrowseCriteria(scopedRecipes, { + search, + category, + maxCookingMinutes, + }); + + const sortedRecipes = sortRecipes(filteredRecipes, sort); + + return paginate(sortedRecipes, page, pageSize); +} diff --git a/apps/web/src/features/explore/ExploreControls.css b/apps/web/src/features/explore/ExploreControls.css index 5808426..176e3f1 100644 --- a/apps/web/src/features/explore/ExploreControls.css +++ b/apps/web/src/features/explore/ExploreControls.css @@ -137,7 +137,7 @@ } } - @media (max-width: 64rem) { + @media (max-width: 60rem) { .explore-controls { padding: var(--space-3); } diff --git a/apps/web/src/features/explore/ExplorePage.tsx b/apps/web/src/features/explore/ExplorePage.tsx index 3ca8917..e4b00ce 100644 --- a/apps/web/src/features/explore/ExplorePage.tsx +++ b/apps/web/src/features/explore/ExplorePage.tsx @@ -11,6 +11,7 @@ import Toast, { type ToastTone } from '../../components/ui/Toast/Toast'; import { SearchIcon } from '../../icons/navigation'; import { useAppStore } from '../../store'; import type { Recipe } from '../../types/recipe'; +import { RECIPE_PAGE_SIZE } from '../../lib/recipeBrowse/recipeBrowse'; import ExploreControls from './ExploreControls'; import { @@ -27,8 +28,6 @@ import { import { getMockExploreResult } from './mockExploreQuery'; import './ExplorePage.css'; -const PAGE_SIZE = 6; - type SaveFeedback = { tone: ToastTone; title: string; @@ -67,7 +66,7 @@ function ExplorePage() { search, ...queryFilters, page, - pageSize: PAGE_SIZE, + pageSize: RECIPE_PAGE_SIZE, }); const activeFilterCount = countActiveExploreFilters(browseState); diff --git a/apps/web/src/features/explore/exploreBrowseState.ts b/apps/web/src/features/explore/exploreBrowseState.ts index 6ee5be7..28cea75 100644 --- a/apps/web/src/features/explore/exploreBrowseState.ts +++ b/apps/web/src/features/explore/exploreBrowseState.ts @@ -1,25 +1,22 @@ -export const EXPLORE_CATEGORY_OPTIONS = [ - { value: 'all', label: 'All categories' }, - { value: 'breakfast', label: 'Breakfast' }, - { value: 'lunch', label: 'Lunch' }, - { value: 'dinner', label: 'Dinner' }, - { value: 'dessert', label: 'Dessert' }, - { value: 'soup', label: 'Soup' }, -] as const; - -export type ExploreCategory = - (typeof EXPLORE_CATEGORY_OPTIONS)[number]['value']; - -export const EXPLORE_COOKING_TIME_OPTIONS = [ - { value: 'any', label: 'Any time' }, - { value: 'lte15', label: '15 min or less' }, - { value: 'lte30', label: '30 min or less' }, - { value: 'lte60', label: '60 min or less' }, - { value: 'custom', label: 'Custom maximum' }, -] as const; - -export type ExploreCookingTime = - (typeof EXPLORE_COOKING_TIME_OPTIONS)[number]['value']; +import { + DEFAULT_RECIPE_FILTER_STATE, + RECIPE_CATEGORY_OPTIONS, + RECIPE_COOKING_TIME_OPTIONS, + countActiveRecipeFilters, + getRecipeQueryFilters, + isRecipeCategory, + isRecipeCookingTime, + type RecipeCategory, + type RecipeCookingTime, + type RecipeFilterState, + type RecipeQueryFilters, +} from '../../lib/recipeBrowse/recipeBrowse'; + +export const EXPLORE_CATEGORY_OPTIONS = RECIPE_CATEGORY_OPTIONS; +export type ExploreCategory = RecipeCategory; + +export const EXPLORE_COOKING_TIME_OPTIONS = RECIPE_COOKING_TIME_OPTIONS; +export type ExploreCookingTime = RecipeCookingTime; export const EXPLORE_SORT_OPTIONS = [ { value: 'trending', label: 'Trending' }, @@ -30,33 +27,18 @@ export const EXPLORE_SORT_OPTIONS = [ export type ExploreSort = (typeof EXPLORE_SORT_OPTIONS)[number]['value']; -export type ExploreFilterState = { - category: ExploreCategory; - cookingTime: ExploreCookingTime; - customMaxMinutes: number | null; -}; +export type ExploreFilterState = RecipeFilterState; export type ExploreBrowseState = ExploreFilterState & { sort: ExploreSort; }; -/** - * Values passed from the UI layer to the catalog/data layer. - * - * UI-specific values such as "lte30" are translated into numeric values - * before reaching the data layer. This gives the mock query a shape that can - * later map naturally to GraphQL variables. - */ -export type ExploreQueryFilters = { - category: Exclude | null; - maxCookingMinutes: number | null; +export type ExploreQueryFilters = RecipeQueryFilters & { sort: ExploreSort; }; export const DEFAULT_EXPLORE_FILTER_STATE: ExploreFilterState = { - category: 'all', - cookingTime: 'any', - customMaxMinutes: null, + ...DEFAULT_RECIPE_FILTER_STATE, }; export const DEFAULT_EXPLORE_BROWSE_STATE: ExploreBrowseState = { @@ -67,13 +49,13 @@ export const DEFAULT_EXPLORE_BROWSE_STATE: ExploreBrowseState = { export function isExploreCategory( value: string | null, ): value is ExploreCategory { - return EXPLORE_CATEGORY_OPTIONS.some((option) => option.value === value); + return isRecipeCategory(value); } export function isExploreCookingTime( value: string | null, ): value is ExploreCookingTime { - return EXPLORE_COOKING_TIME_OPTIONS.some((option) => option.value === value); + return isRecipeCookingTime(value); } export function isExploreSort(value: string | null): value is ExploreSort { @@ -83,51 +65,14 @@ export function isExploreSort(value: string | null): value is ExploreSort { export function getExploreQueryFilters( state: ExploreBrowseState, ): ExploreQueryFilters { - let maxCookingMinutes: number | null = null; - - switch (state.cookingTime) { - case 'lte15': - maxCookingMinutes = 15; - break; - - case 'lte30': - maxCookingMinutes = 30; - break; - - case 'lte60': - maxCookingMinutes = 60; - break; - - case 'custom': - maxCookingMinutes = state.customMaxMinutes; - break; - - case 'any': - break; - } - return { - category: state.category === 'all' ? null : state.category, - maxCookingMinutes, + ...getRecipeQueryFilters(state), sort: state.sort, }; } export function countActiveExploreFilters(state: ExploreFilterState) { - let count = 0; - - if (state.category !== 'all') { - count += 1; - } - - if ( - state.cookingTime !== 'any' && - (state.cookingTime !== 'custom' || state.customMaxMinutes !== null) - ) { - count += 1; - } - - return count; + return countActiveRecipeFilters(state); } export function getExploreSortLabel(sort: ExploreSort) { diff --git a/apps/web/src/features/explore/mockExploreQuery.ts b/apps/web/src/features/explore/mockExploreQuery.ts index 8017c15..23b6b57 100644 --- a/apps/web/src/features/explore/mockExploreQuery.ts +++ b/apps/web/src/features/explore/mockExploreQuery.ts @@ -1,5 +1,6 @@ import { recipes } from '../../data/recipes'; import { paginate, type PageResult } from '../../lib/pagination/paginate'; +import { filterRecipesByBrowseCriteria } from '../../lib/recipeBrowse/recipeBrowse'; import type { Recipe } from '../../types/recipe'; import type { ExploreCategory, ExploreSort } from './exploreBrowseState'; @@ -27,45 +28,6 @@ export const MOCK_EXPLORE_NOW = '2026-09-05T12:00:00Z'; const MOCK_EXPLORE_NOW_MS = Date.parse(MOCK_EXPLORE_NOW); const TRENDING_WINDOW_MS = 14 * 24 * 60 * 60 * 1000; -function normalizeSearchText(value: string) { - return value.trim().toLowerCase().replace(/[-_]+/g, ' ').replace(/\s+/g, ' '); -} - -function matchesSearch(recipe: Recipe, search: string) { - if (!search) { - return true; - } - - const searchableValues = [ - recipe.title, - recipe.description, - ...recipe.tags, - ...recipe.ingredients.map((ingredient) => ingredient.name), - ]; - - return searchableValues.some((value) => - normalizeSearchText(value).includes(search), - ); -} - -function matchesCategory(recipe: Recipe, category: ExploreQuery['category']) { - if (!category) { - return true; - } - - return normalizeSearchText(recipe.category) === normalizeSearchText(category); -} - -function matchesCookingTime(recipe: Recipe, maxCookingMinutes: number | null) { - if (maxCookingMinutes === null) { - return true; - } - - const totalMinutes = recipe.prepMinutes + recipe.cookMinutes; - - return totalMinutes <= maxCookingMinutes; -} - export function getPopularityScore(recipe: Recipe) { return recipe.rating.average * Math.log1p(recipe.rating.count); } @@ -143,13 +105,15 @@ export function getMockExploreResult({ page, pageSize, }: ExploreQuery): ExploreResult { - const normalizedSearch = normalizeSearchText(search); + const publicRecipes = recipes.filter( + (recipe) => recipe.visibility === 'public', + ); - const filteredRecipes = recipes - .filter((recipe) => recipe.visibility === 'public') - .filter((recipe) => matchesSearch(recipe, normalizedSearch)) - .filter((recipe) => matchesCategory(recipe, category)) - .filter((recipe) => matchesCookingTime(recipe, maxCookingMinutes)); + const filteredRecipes = filterRecipesByBrowseCriteria(publicRecipes, { + search, + category, + maxCookingMinutes, + }); const sortCandidates = sort === 'trending' diff --git a/apps/web/src/lib/recipeBrowse/recipeBrowse.ts b/apps/web/src/lib/recipeBrowse/recipeBrowse.ts new file mode 100644 index 0000000..db14a47 --- /dev/null +++ b/apps/web/src/lib/recipeBrowse/recipeBrowse.ts @@ -0,0 +1,174 @@ +import type { Recipe } from '../../types/recipe'; + +/** + * Explore and Cookbook intentionally use the same page size. + * + * Change this one value later if both pages should show more/fewer recipes. + */ +export const RECIPE_PAGE_SIZE = 6; + +export const RECIPE_CATEGORY_OPTIONS = [ + { value: 'all', label: 'All categories' }, + { value: 'breakfast', label: 'Breakfast' }, + { value: 'lunch', label: 'Lunch' }, + { value: 'dinner', label: 'Dinner' }, + { value: 'dessert', label: 'Dessert' }, + { value: 'soup', label: 'Soup' }, +] as const; + +export type RecipeCategory = (typeof RECIPE_CATEGORY_OPTIONS)[number]['value']; + +export const RECIPE_COOKING_TIME_OPTIONS = [ + { value: 'any', label: 'Any time' }, + { value: 'lte15', label: '15 min or less' }, + { value: 'lte30', label: '30 min or less' }, + { value: 'lte60', label: '60 min or less' }, + { value: 'custom', label: 'Custom maximum' }, +] as const; + +export type RecipeCookingTime = + (typeof RECIPE_COOKING_TIME_OPTIONS)[number]['value']; + +export type RecipeFilterState = { + category: RecipeCategory; + cookingTime: RecipeCookingTime; + customMaxMinutes: number | null; +}; + +/** + * Values understood by the mock query/data layer. + * + * The UI's "lte30" style values are translated before reaching the query. + * This should also map reasonably well to future GraphQL variables. + */ +export type RecipeQueryFilters = { + category: Exclude | null; + maxCookingMinutes: number | null; +}; + +export type RecipeBrowseCriteria = RecipeQueryFilters & { + search: string; +}; + +export const DEFAULT_RECIPE_FILTER_STATE: RecipeFilterState = { + category: 'all', + cookingTime: 'any', + customMaxMinutes: null, +}; + +export function isRecipeCategory( + value: string | null, +): value is RecipeCategory { + return RECIPE_CATEGORY_OPTIONS.some((option) => option.value === value); +} + +export function isRecipeCookingTime( + value: string | null, +): value is RecipeCookingTime { + return RECIPE_COOKING_TIME_OPTIONS.some((option) => option.value === value); +} + +export function getRecipeQueryFilters( + state: RecipeFilterState, +): RecipeQueryFilters { + let maxCookingMinutes: number | null = null; + + switch (state.cookingTime) { + case 'lte15': + maxCookingMinutes = 15; + break; + + case 'lte30': + maxCookingMinutes = 30; + break; + + case 'lte60': + maxCookingMinutes = 60; + break; + + case 'custom': + maxCookingMinutes = state.customMaxMinutes; + break; + + case 'any': + break; + } + + return { + category: state.category === 'all' ? null : state.category, + maxCookingMinutes, + }; +} + +export function countActiveRecipeFilters(state: RecipeFilterState) { + let count = 0; + + if (state.category !== 'all') { + count += 1; + } + + if ( + state.cookingTime !== 'any' && + (state.cookingTime !== 'custom' || state.customMaxMinutes !== null) + ) { + count += 1; + } + + return count; +} + +export function getRecipeTotalMinutes(recipe: Recipe) { + return recipe.prepMinutes + recipe.cookMinutes; +} + +function normalizeSearchText(value: string) { + return value.trim().toLowerCase().replace(/[-_]+/g, ' ').replace(/\s+/g, ' '); +} + +function matchesSearch(recipe: Recipe, normalizedSearch: string) { + if (!normalizedSearch) { + return true; + } + + const searchableValues = [ + recipe.title, + recipe.description, + ...recipe.tags, + ...recipe.ingredients.map((ingredient) => ingredient.name), + ]; + + return searchableValues.some((value) => + normalizeSearchText(value).includes(normalizedSearch), + ); +} + +function matchesCategory( + recipe: Recipe, + category: RecipeQueryFilters['category'], +) { + if (!category) { + return true; + } + + return normalizeSearchText(recipe.category) === normalizeSearchText(category); +} + +function matchesCookingTime(recipe: Recipe, maxCookingMinutes: number | null) { + if (maxCookingMinutes === null) { + return true; + } + + return getRecipeTotalMinutes(recipe) <= maxCookingMinutes; +} + +export function filterRecipesByBrowseCriteria( + items: readonly Recipe[], + { search, category, maxCookingMinutes }: RecipeBrowseCriteria, +) { + const normalizedSearch = normalizeSearchText(search); + + return items + .filter((recipe) => matchesSearch(recipe, normalizedSearch)) + .filter((recipe) => matchesCategory(recipe, category)) + .filter((recipe) => matchesCookingTime(recipe, maxCookingMinutes)); +} From 74bf1086a63c998322991959b6dcebaee7163f53 Mon Sep 17 00:00:00 2001 From: olestang Date: Fri, 9 Oct 2026 11:46:48 +0200 Subject: [PATCH 2/4] fix: refine cookbook filters and navigation semantics --- .../components/ui/LinkButton/LinkButton.tsx | 39 +++++++++++++++++ .../features/cookbook/CookbookControls.css | 2 +- .../features/cookbook/CookbookControls.tsx | 23 +++++----- .../src/features/cookbook/CookbookPage.tsx | 43 ++++++++++++++----- .../src/features/explore/ExploreControls.css | 2 +- 5 files changed, 83 insertions(+), 26 deletions(-) create mode 100644 apps/web/src/components/ui/LinkButton/LinkButton.tsx diff --git a/apps/web/src/components/ui/LinkButton/LinkButton.tsx b/apps/web/src/components/ui/LinkButton/LinkButton.tsx new file mode 100644 index 0000000..ee891c0 --- /dev/null +++ b/apps/web/src/components/ui/LinkButton/LinkButton.tsx @@ -0,0 +1,39 @@ +import type { ReactNode } from 'react'; +import { Link, type LinkProps } from 'react-router-dom'; + +import type { ButtonSize, ButtonVariant } from '../Button/Button'; +import '../Button/Button.css'; + +export type LinkButtonProps = LinkProps & { + children: ReactNode; + variant?: ButtonVariant; + size?: ButtonSize; + wide?: boolean; +}; + +function LinkButton({ + children, + variant = 'primary', + size = 'md', + wide = false, + className = '', + ...props +}: LinkButtonProps) { + const classes = [ + 'button', + `button--${variant}`, + `button--${size}`, + wide && 'button--wide', + className, + ] + .filter(Boolean) + .join(' '); + + return ( + + {children} + + ); +} + +export default LinkButton; diff --git a/apps/web/src/features/cookbook/CookbookControls.css b/apps/web/src/features/cookbook/CookbookControls.css index c1acba3..e0de5fb 100644 --- a/apps/web/src/features/cookbook/CookbookControls.css +++ b/apps/web/src/features/cookbook/CookbookControls.css @@ -137,7 +137,7 @@ * Cookbook has one additional desktop select, so its desktop toolbar * switches to the compact version a little earlier than Explore. */ - @media (min-width: 70.0625rem) { + @media (min-width: 72.0625rem) { .cookbook-controls__desktop-control--sort { position: relative; diff --git a/apps/web/src/features/cookbook/CookbookControls.tsx b/apps/web/src/features/cookbook/CookbookControls.tsx index 6dd0bf5..1f6d7bf 100644 --- a/apps/web/src/features/cookbook/CookbookControls.tsx +++ b/apps/web/src/features/cookbook/CookbookControls.tsx @@ -36,6 +36,7 @@ export type CookbookControlsProps = { browseState: CookbookBrowseState; onScopeChange: (scope: CookbookScope) => void; onBrowseStateChange: (value: CookbookBrowseState) => void; + onFiltersChange: (scope: CookbookScope, value: CookbookBrowseState) => void; }; function parseCustomMaxMinutes(value: string) { @@ -66,10 +67,13 @@ function CookbookControls({ browseState, onScopeChange, onBrowseStateChange, + onFiltersChange, }: CookbookControlsProps) { const [filterSheetOpen, setFilterSheetOpen] = useState(false); const [sortSheetOpen, setSortSheetOpen] = useState(false); + const [scopeDraft, setScopeDraft] = useState(scope); + const [filterDraft, setFilterDraft] = useState({ category: browseState.category, cookingTime: browseState.cookingTime, @@ -79,11 +83,6 @@ function CookbookControls({ const [sortDraft, setSortDraft] = useState(browseState.sort); const [showCustomTimeError, setShowCustomTimeError] = useState(false); - /* - * On mobile, Saved / Created lives inside the filter sheet. - * Count a non-default scope as an active filter so the Filters button - * communicates that the Cookbook has been narrowed. - */ const activeFilterCount = countActiveRecipeFilters(browseState) + (scope === 'all' ? 0 : 1); @@ -112,6 +111,8 @@ function CookbookControls({ } function openFilterSheet() { + setScopeDraft(scope); + setFilterDraft({ category: browseState.category, cookingTime: browseState.cookingTime, @@ -142,7 +143,7 @@ function CookbookControls({ return; } - onBrowseStateChange({ + onFiltersChange(scopeDraft, { ...browseState, ...filterDraft, }); @@ -151,11 +152,7 @@ function CookbookControls({ } function handleClearFilters() { - /* - * Scope is applied immediately in the mobile sheet, so reset it - * immediately as well. Category/time remain draft values until Apply. - */ - onScopeChange('all'); + setScopeDraft('all'); setFilterDraft({ ...DEFAULT_RECIPE_FILTER_STATE, @@ -348,8 +345,8 @@ function CookbookControls({ {COOKBOOK_SCOPE_OPTIONS.map((option) => ( onScopeChange(option.value)} + selected={scopeDraft === option.value} + onClick={() => setScopeDraft(option.value)} > {option.label} diff --git a/apps/web/src/features/cookbook/CookbookPage.tsx b/apps/web/src/features/cookbook/CookbookPage.tsx index d478604..a6796ad 100644 --- a/apps/web/src/features/cookbook/CookbookPage.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.tsx @@ -1,11 +1,12 @@ import { useEffect, useMemo, useRef, useState, type SubmitEvent } from 'react'; -import { useNavigate, useSearchParams } from 'react-router-dom'; +import { useSearchParams } from 'react-router-dom'; import RecipeCard from '../../components/recipe/RecipeCard/RecipeCard'; import { toRecipeCardProps } from '../../components/recipe/toRecipeCardProps'; import Button from '../../components/ui/Button/Button'; import EmptyState from '../../components/ui/EmptyState/EmptyState'; import Field from '../../components/ui/Field/Field'; +import LinkButton from '../../components/ui/LinkButton/LinkButton'; import Pagination from '../../components/ui/Pagination/Pagination'; import { CookbookIcon, SearchIcon } from '../../icons/navigation'; import { @@ -32,7 +33,6 @@ import './CookbookPage.css'; function CookbookPage() { const searchInputRef = useRef(null); - const navigate = useNavigate(); const [searchParams, setSearchParams] = useSearchParams(); const savedRecipeIds = useAppStore((state) => state.savedRecipeIds); @@ -129,6 +129,30 @@ function CookbookPage() { ); } + /* + * Mobile Filters applies scope, category, and cooking time together. + * Keeping this as one URL update avoids one filter change overwriting + * another when Apply filters is pressed. + */ + function handleFiltersChange( + nextScope: CookbookScope, + nextBrowseState: CookbookBrowseState, + ) { + const replaceCurrentEntry = + browseState.cookingTime === 'custom' && + nextBrowseState.cookingTime === 'custom'; + + updateUrlState( + { + scope: nextScope, + search, + browseState: nextBrowseState, + page: 1, + }, + replaceCurrentEntry, + ); + } + function handleClearResultCriteria() { const nextBrowseState: CookbookBrowseState = { ...DEFAULT_RECIPE_FILTER_STATE, @@ -171,11 +195,11 @@ function CookbookPage() { let emptyStateAction = ( <> - + Explore recipes - + ); @@ -205,17 +229,13 @@ function CookbookPage() { emptyStateDescription = 'Recipes you save from Explore will appear here.'; - emptyStateAction = ( - - ); + emptyStateAction = Explore recipes; } else if (scope === 'created') { emptyStateTitle = 'No created recipes yet'; emptyStateDescription = 'Recipes you create will appear here.'; - emptyStateAction = ( - - ); + emptyStateAction = Add recipe; } return ( @@ -281,6 +301,7 @@ function CookbookPage() { browseState={browseState} onScopeChange={handleScopeChange} onBrowseStateChange={handleBrowseStateChange} + onFiltersChange={handleFiltersChange} />

diff --git a/apps/web/src/features/explore/ExploreControls.css b/apps/web/src/features/explore/ExploreControls.css index 176e3f1..e7ab09d 100644 --- a/apps/web/src/features/explore/ExploreControls.css +++ b/apps/web/src/features/explore/ExploreControls.css @@ -116,7 +116,7 @@ width: 100%; } - @media (min-width: 64.0625rem) { + @media (min-width: 60.0625rem) { .explore-controls__desktop-control--sort { position: relative; From ec023aea21bc1a9a51ea75b4b993e9b09c535394 Mon Sep 17 00:00:00 2001 From: olestang Date: Fri, 9 Oct 2026 12:23:02 +0200 Subject: [PATCH 3/4] fix: make sheet body scroll within viewport --- apps/web/src/components/ui/Sheet/Sheet.css | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/web/src/components/ui/Sheet/Sheet.css b/apps/web/src/components/ui/Sheet/Sheet.css index 01fb11e..6870b4b 100644 --- a/apps/web/src/components/ui/Sheet/Sheet.css +++ b/apps/web/src/components/ui/Sheet/Sheet.css @@ -38,6 +38,9 @@ } .sheet[open] { + display: flex; + flex-direction: column; + animation: sheet-enter var(--duration-normal) var(--ease-standard) both; } @@ -47,6 +50,7 @@ .sheet__handle-area { display: flex; + flex: 0 0 auto; align-items: center; justify-content: center; @@ -76,6 +80,7 @@ .sheet__header { display: flex; + flex: 0 0 auto; align-items: flex-start; justify-content: space-between; gap: var(--space-4); @@ -119,6 +124,8 @@ ========================================================= */ .sheet__body { + flex: 1 1 auto; + min-height: 0; padding: var(--space-4) var(--space-5) @@ -143,6 +150,7 @@ .sheet__footer { display: flex; + flex: 0 0 auto; flex-wrap: wrap; align-items: center; justify-content: flex-end; From e6bc5f7e26ea77b03cdcfdd01badd1f8c5422049 Mon Sep 17 00:00:00 2001 From: olestang Date: Sun, 11 Oct 2026 22:24:50 +0200 Subject: [PATCH 4/4] test(cookbook): cover apply, clear and invalid mobile filters --- .../features/cookbook/CookbookPage.test.tsx | 185 ++++++++++++++++++ 1 file changed, 185 insertions(+) diff --git a/apps/web/src/features/cookbook/CookbookPage.test.tsx b/apps/web/src/features/cookbook/CookbookPage.test.tsx index 370494e..48b2177 100644 --- a/apps/web/src/features/cookbook/CookbookPage.test.tsx +++ b/apps/web/src/features/cookbook/CookbookPage.test.tsx @@ -233,4 +233,189 @@ describe('CookbookPage', () => { }), ).toBeTruthy(); }); + + it('applies mobile filters to the results and URL', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Soup', + }), + ); + + await user.click( + screen.getByRole('button', { + name: '30 min or less', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Simple tomato soup', + }), + ).toBeTruthy(); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?category=soup&time=lte30', + ); + }); + + it('discards mobile filter changes when closed without Apply', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Created', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Dinner', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Close filters', + }), + ); + + expect(screen.getByText('8 recipes found')).toBeTruthy(); + expect(screen.getByTestId('location-search').textContent).toBe(''); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + expect( + screen.getByRole('button', { name: 'All' }).getAttribute('aria-pressed'), + ).toBe('true'); + + expect( + screen + .getByRole('button', { name: 'Created' }) + .getAttribute('aria-pressed'), + ).toBe('false'); + + expect( + screen + .getByRole('button', { name: 'All categories' }) + .getAttribute('aria-pressed'), + ).toBe('true'); + + expect( + screen + .getByRole('button', { name: 'Dinner' }) + .getAttribute('aria-pressed'), + ).toBe('false'); + }); + + it('prevents Apply when custom cooking time is invalid', async () => { + const user = userEvent.setup(); + + renderCookbookPage(); + + await user.click( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Custom maximum', + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect( + screen.getByText('Enter a maximum cooking time before applying filters.'), + ).toBeTruthy(); + + expect(screen.getByText('8 recipes found')).toBeTruthy(); + expect(screen.getByTestId('location-search').textContent).toBe(''); + }); + + it('clears mobile filters and applies the cleared state', async () => { + const user = userEvent.setup(); + + renderCookbookPage('/cookbook?view=created&category=soup&time=lte30'); + + expect(screen.getByText('1 recipe found')).toBeTruthy(); + + expect( + screen.getByRole('link', { + name: 'Simple tomato soup', + }), + ).toBeTruthy(); + + await user.click( + screen.getByRole('button', { + name: 'Filters (3)', + hidden: true, + }), + ); + + await user.click( + screen.getByRole('button', { + name: 'Clear filters', + }), + ); + + expect(screen.getByTestId('location-search').textContent).toBe( + '?view=created&category=soup&time=lte30', + ); + + await user.click( + screen.getByRole('button', { + name: 'Apply filters', + }), + ); + + expect(screen.getByText('8 recipes found')).toBeTruthy(); + expect(screen.getByTestId('location-search').textContent).toBe(''); + + expect( + screen.getByRole('button', { + name: 'Filters', + hidden: true, + }), + ).toBeTruthy(); + }); });