diff --git a/apps/api/src/features/recipes/recipeValidation.ts b/apps/api/src/features/recipes/recipeValidation.ts index 326ae0b..cbf9e55 100644 --- a/apps/api/src/features/recipes/recipeValidation.ts +++ b/apps/api/src/features/recipes/recipeValidation.ts @@ -1,6 +1,13 @@ import { GraphQLError } from 'graphql'; import { z } from 'zod'; -import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe'; +import { + MAX_INGREDIENTS, + MAX_INSTRUCTIONS, + MAX_SERVINGS, + MAX_TAG_LENGTH, + MAX_TAGS, + MIN_SERVINGS, +} from '@t31/validation/recipe'; import { uploadedImagePattern } from './imagePaths.js'; export const categorySchema = z.enum([ @@ -50,11 +57,14 @@ export const recipeInputSchema = z.object({ }), ) .min(1) - .max(100), - instructions: z.array(z.string().trim().min(1).max(5000)).min(1).max(100), + .max(MAX_INGREDIENTS), + instructions: z + .array(z.string().trim().min(1).max(5000)) + .min(1) + .max(MAX_INSTRUCTIONS), tags: z - .array(z.string().trim().toLowerCase().min(1).max(50)) - .max(30) + .array(z.string().trim().toLowerCase().min(1).max(MAX_TAG_LENGTH)) + .max(MAX_TAGS) .transform((values) => [...new Set(values)]), }); diff --git a/apps/validation/src/recipe.test.ts b/apps/validation/src/recipe.test.ts new file mode 100644 index 0000000..e8caaec --- /dev/null +++ b/apps/validation/src/recipe.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest'; +import { parseTags } from './recipe'; + +describe('parseTags', () => { + it('trims, lower-cases and drops empty and repeated tags, keeping order', () => { + expect(parseTags(' Quick , vegan,, QUICK, ,Italian ')).toEqual([ + 'quick', + 'vegan', + 'italian', + ]); + expect(parseTags('')).toEqual([]); + }); +}); diff --git a/apps/validation/src/recipe.ts b/apps/validation/src/recipe.ts index 27c8376..71e5736 100644 --- a/apps/validation/src/recipe.ts +++ b/apps/validation/src/recipe.ts @@ -5,3 +5,29 @@ */ export const MIN_SERVINGS = 1; export const MAX_SERVINGS = 1000; + +/* + * Size limits of a recipe, enforced by the API (recipeValidation.ts) and + * checked by the recipe form before it submits, so a form that looks valid + * is never rejected by the API. + */ +export const MAX_INGREDIENTS = 100; +export const MAX_INSTRUCTIONS = 100; +export const MAX_TAGS = 30; +export const MAX_TAG_LENGTH = 50; + +/** + * Tags from the form's comma-separated text, as the API stores them: + * trimmed, lower-case, without empty entries or repeats. The form sends this + * list, so the API's MAX_TAGS counts the same tags the form counted. + */ +export function parseTags(text: string) { + return [ + ...new Set( + text + .split(',') + .map((tag) => tag.trim().toLowerCase()) + .filter(Boolean), + ), + ]; +} diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css index 9e6c650..f1d8bf4 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.css +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -343,6 +343,13 @@ margin-top: var(--space-2); } + /* Shown next to a disabled Add button once a list is full. */ + .recipe-create-page__limit { + margin: 0; + color: var(--color-text-secondary); + font-size: var(--font-size-sm); + } + /* Move up / move down / remove buttons at the end of each row. */ .recipe-create-page__delete-control { display: flex; diff --git a/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx new file mode 100644 index 0000000..125df6d --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx @@ -0,0 +1,185 @@ +import '@testing-library/jest-dom/vitest'; +import { act, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { useAppStore } from '../../store'; +import { + apiRecipe, + apiUser, + mockRecipeFetch, +} from '../../test/recipeApiFixtures'; +import RecipeCreatePage from './RecipeCreatePage'; + +/* + * The real limits are 100 ingredients and 100 steps (shared with the API in + * @t31/validation/recipe). Rendering 100 rows takes seconds in jsdom, so + * this file lowers them to 3; the behaviour at the limit is the same. + */ +vi.mock('@t31/validation/recipe', async (importOriginal) => ({ + ...(await importOriginal()), + MAX_INGREDIENTS: 3, + MAX_INSTRUCTIONS: 3, +})); + +afterEach(() => { + vi.unstubAllGlobals(); + localStorage.clear(); +}); +beforeEach(() => + useAppStore.setState({ + currentUser: apiUser, + sessionStatus: 'authenticated', + }), +); + +const rows = (count: number) => ({ + ingredients: Array.from({ length: count }, (_, i) => ({ + id: `ingredient-${i}`, + name: `Spice ${i + 1}`, + amount: 1, + unit: 'g', + note: null, + })), + instructions: Array.from({ length: count }, (_, i) => ({ + step: i + 1, + text: `Step ${i + 1}`, + })), +}); +function edit(recipe: object) { + const fetch = mockRecipeFetch(() => ({ + data: { recipe: { ...apiRecipe, isCreatedByCurrentUser: true, ...recipe } }, + })); + render( + + + } /> + } /> + + , + ); + return fetch; +} + +it('stops adding rows at the limit and says why', async () => { + edit(rows(3)); + const addIngredient = await screen.findByRole('button', { + name: 'Add ingredient', + }); + expect(addIngredient).toBeDisabled(); + expect(addIngredient).toHaveAccessibleDescription( + 'A recipe can have at most 3 ingredients.', + ); + const addStep = screen.getByRole('button', { name: 'Add step' }); + expect(addStep).toBeDisabled(); + expect(addStep).toHaveAccessibleDescription( + 'A recipe can have at most 3 steps.', + ); + // Removing a row allows adding again. + await userEvent.click( + screen.getByRole('button', { name: 'Remove ingredient 3' }), + ); + expect(addIngredient).toBeEnabled(); +}); + +it('flags a recipe with more rows than allowed and focuses the message', async () => { + const fetch = edit(rows(4)); + await userEvent.click( + await screen.findByRole('button', { name: 'Save changes' }), + ); + await act(() => new Promise((resolve) => setTimeout(resolve))); + const message = screen.getByText( + 'A recipe can have at most 3 ingredients. Remove 1 to save.', + ); + expect(message.closest('[data-form-error]')).toHaveFocus(); + expect( + screen.getByText('A recipe can have at most 3 steps. Remove 1 to save.'), + ).toBeInTheDocument(); + expect(fetch).toHaveBeenCalledTimes(1); // only the initial load +}); + +it('keeps the row-limit error, with the remaining count, until the list fits', async () => { + edit(rows(5)); + await userEvent.click( + await screen.findByRole('button', { name: 'Save changes' }), + ); + await act(() => new Promise((resolve) => setTimeout(resolve))); + expect( + screen.getByText( + 'A recipe can have at most 3 ingredients. Remove 2 to save.', + ), + ).toBeInTheDocument(); + + // One removed, still over the limit: the message stays and recounts. + await userEvent.click( + screen.getByRole('button', { name: 'Remove ingredient 5' }), + ); + expect( + screen.getByText( + 'A recipe can have at most 3 ingredients. Remove 1 to save.', + ), + ).toBeInTheDocument(); + await userEvent.click( + screen.getByRole('button', { name: 'Remove ingredient 4' }), + ); + expect(screen.queryByText(/at most 3 ingredients\. Remove/)).toBeNull(); + + // Steps behave the same, independently of the ingredients. + expect( + screen.getByText('A recipe can have at most 3 steps. Remove 2 to save.'), + ).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: 'Remove step 5' })); + expect( + screen.getByText('A recipe can have at most 3 steps. Remove 1 to save.'), + ).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', { name: 'Remove step 4' })); + expect(screen.queryByText(/at most 3 steps\. Remove/)).toBeNull(); +}); + +it('shows the row-limit errors as soon as an over-limit draft is restored', async () => { + localStorage.setItem( + `recipe-platform:draft:${apiUser.id}:new`, + JSON.stringify({ + version: 1, + savedAt: '2026-10-01T10:00:00Z', + baseUpdatedAt: null, + fields: { + title: 'Big soup', + description: '', + category: 'soup', + difficulty: 'easy', + visibility: 'public', + prepTime: '1', + cookingTime: '1', + servings: '1', + tags: '', + imageUrl: null, + ingredients: rows(5).ingredients.map(({ name }) => ({ + name, + amount: '1', + unit: 'g', + })), + instructions: rows(4).instructions.map(({ text }) => text), + }, + }), + ); + render( + + + } /> + + , + ); + await userEvent.click( + await screen.findByRole('button', { name: 'Restore draft' }), + ); + // No submit needed. + expect( + screen.getByText( + 'A recipe can have at most 3 ingredients. Remove 2 to save.', + ), + ).toBeInTheDocument(); + expect( + screen.getByText('A recipe can have at most 3 steps. Remove 1 to save.'), + ).toBeInTheDocument(); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index 058a87a..b68cef3 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -671,3 +671,104 @@ describe('edit page titles', () => { expect(document.title).toBe('Recipe unavailable – Recipe Platform'); }); }); + +describe('recipe size limits and error focus', () => { + /** A valid new recipe, filled without per-key typing (fast on CI). */ + function fillValid() { + const change = (label: string | RegExp, value: string) => + fireEvent.change(screen.getByLabelText(label), { target: { value } }); + change(/Recipe title/, 'New soup'); + change(/Preparation time/, '5'); + change(/Cooking time/, '10'); + change(/Difficulty/, 'easy'); + change(/Servings/, '2'); + change(/Category/, 'soup'); + change('Ingredient 1', 'Water'); + change('Ingredient 1 amount', '1'); + change('Step 1', 'Boil.'); + } + const publish = () => + userEvent.click(screen.getByRole('button', { name: 'Publish recipe' })); + const tick = () => act(() => new Promise((resolve) => setTimeout(resolve))); + + it('rejects more than 30 tags or a tag over 50 characters before submitting', async () => { + const fetch = mockRecipeFetch(() => ({ + data: { createRecipe: apiRecipe }, + })); + mount(); + fillValid(); + const tags = screen.getByLabelText(/Tags/); + fireEvent.change(tags, { + target: { + value: Array.from({ length: 31 }, (_, i) => `tag${i}`).join(', '), + }, + }); + await publish(); + await tick(); + expect( + screen.getByText('Use at most 30 tags (you have 31).'), + ).toBeInTheDocument(); + expect(tags).toHaveFocus(); + + fireEvent.change(tags, { target: { value: `quick, ${'x'.repeat(51)}` } }); + await publish(); + await tick(); + expect( + screen.getByText(/Keep each tag to 50 characters/), + ).toBeInTheDocument(); + expect(tags).toHaveFocus(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it('counts and sends tags as the API stores them: lower-case, without repeats', async () => { + let input: { tags?: string[] } = {}; + mockRecipeFetch((_operation, variables) => { + input = variables.input as typeof input; + return { data: { createRecipe: apiRecipe } }; + }); + mount(); + fillValid(); + // 30 distinct tags, written 60 times in different cases: allowed. + const distinct = Array.from({ length: 30 }, (_, i) => `tag${i}`); + fireEvent.change(screen.getByLabelText(/Tags/), { + target: { + value: [...distinct, ...distinct.map((tag) => tag.toUpperCase())].join( + ', ', + ), + }, + }); + await publish(); + expect( + await screen.findByRole('heading', { name: 'Saved recipe destination' }), + ).toBeInTheDocument(); + expect(input.tags).toEqual(distinct); + }); + + it('focuses the first invalid field in a later ingredient or step row', async () => { + mockRecipeFetch(() => ({ data: { createRecipe: apiRecipe } })); + const user = userEvent.setup(); + mount(); + fillValid(); + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + fireEvent.change(screen.getByLabelText('Ingredient 2'), { + target: { value: 'Salt' }, + }); + // Ingredient 2 has no amount: focus goes there, not to the title. + await publish(); + await tick(); + expect(screen.getByLabelText('Ingredient 2 amount')).toHaveFocus(); + + fireEvent.change(screen.getByLabelText('Ingredient 2 amount'), { + target: { value: '2' }, + }); + await user.click(screen.getByRole('button', { name: 'Add step' })); + await user.click(screen.getByRole('button', { name: 'Add step' })); + fireEvent.change(screen.getByLabelText('Step 2'), { + target: { value: 'Salt it.' }, + }); + // Step 3 is empty. + await publish(); + await tick(); + expect(screen.getByLabelText('Step 3')).toHaveFocus(); + }); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index c5296be..783dc3a 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -40,7 +40,15 @@ import { type RecipeDraftFields, } from '../../lib/recipeDrafts'; import { INGREDIENT_UNITS, normalizeUnit } from '../../lib/ingredientUnits'; -import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe'; +import { + MAX_INGREDIENTS, + MAX_INSTRUCTIONS, + MAX_SERVINGS, + MAX_TAG_LENGTH, + MAX_TAGS, + MIN_SERVINGS, + parseTags, +} from '@t31/validation/recipe'; import './RecipeCreatePage.css'; @@ -54,8 +62,12 @@ type RecipeErrors = { category?: string; visibility?: string; image?: string; + tags?: string; ingredients?: IngredientFieldErrors[]; instructions?: string[]; + // Too many rows (possible from a restored draft); shown above the list. + ingredientCount?: string; + instructionCount?: string; }; type IngredientFieldErrors = { @@ -94,6 +106,16 @@ function formatDraftTime(savedAt: string) { }); } +/** Row-count messages for lists over the API's limits; none when they fit. */ +function rowCountErrors(ingredientCount: number, instructionCount: number) { + const errors: Pick = {}; + if (ingredientCount > MAX_INGREDIENTS) + errors.ingredientCount = `A recipe can have at most ${MAX_INGREDIENTS} ingredients. Remove ${ingredientCount - MAX_INGREDIENTS} to save.`; + if (instructionCount > MAX_INSTRUCTIONS) + errors.instructionCount = `A recipe can have at most ${MAX_INSTRUCTIONS} steps. Remove ${instructionCount - MAX_INSTRUCTIONS} to save.`; + return errors; +} + function moveItem(items: T[], fromIndex: number, toIndex: number) { const nextItems = [...items]; const [movedItem] = nextItems.splice(fromIndex, 1); @@ -105,6 +127,7 @@ function moveItem(items: T[], fromIndex: number, toIndex: number) { function RecipeEditor({ recipe }: { recipe?: Recipe }) { usePageTitle(recipe ? `Edit ${recipe.title}` : 'Add recipe'); const navigate = useNavigate(); + const formRef = useRef(null); const busyRef = useRef(false); const [pending, setPending] = useState(false); const [submitError, setSubmitError] = useState(''); @@ -248,7 +271,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { setInstructions( fields.instructions.map((text) => ({ key: newRowKey(), text })), ); - setErrors({}); + // A draft can hold more rows than the API accepts: say so right away. + setErrors( + rowCountErrors(fields.ingredients.length, fields.instructions.length), + ); setOfferedDraft(null); // Unused uploads are cleaned up after 24 hours, so the draft's image may // be gone; keep the current image instead of a broken one. @@ -315,6 +341,17 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function removeIngredient(index: number) { + // Keep the message, with the remaining count, until the list fits. + setErrors((currentErrors) => { + if (!currentErrors.ingredientCount) return currentErrors; + const nextErrors = { ...currentErrors }; + delete nextErrors.ingredientCount; + return { + ...nextErrors, + ...rowCountErrors(ingredients.length - 1, 0), + }; + }); + setStatus('idle'); setIngredients((currentIngredients) => currentIngredients.filter( (_, ingredientIndex) => ingredientIndex !== index, @@ -369,6 +406,16 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function removeInstruction(index: number) { + setErrors((currentErrors) => { + if (!currentErrors.instructionCount) return currentErrors; + const nextErrors = { ...currentErrors }; + delete nextErrors.instructionCount; + return { + ...nextErrors, + ...rowCountErrors(0, instructions.length - 1), + }; + }); + setStatus('idle'); setInstructions((currentInstructions) => currentInstructions.filter( (_, instructionIndex) => instructionIndex !== index, @@ -543,6 +590,16 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { if (!visibility) { nextErrors.visibility = 'Choose who can see this recipe.'; } + const tagList = parseTags(tags); + const longTag = tagList.find((tag) => tag.length > MAX_TAG_LENGTH); + if (tagList.length > MAX_TAGS) + nextErrors.tags = `Use at most ${MAX_TAGS} tags (you have ${tagList.length}).`; + else if (longTag) + nextErrors.tags = `Keep each tag to ${MAX_TAG_LENGTH} characters. "${longTag.slice(0, 20)}…" is ${longTag.length}.`; + Object.assign( + nextErrors, + rowCountErrors(ingredients.length, instructions.length), + ); const ingredientErrors = ingredients.map((ingredient) => ({ name: !ingredient.name.trim() @@ -592,37 +649,15 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { setErrors(nextErrors); if (Object.keys(nextErrors).length > 0) { - const firstIngredientError = nextErrors.ingredients?.[0]; - const firstInvalidId = [ - { id: 'recipe-title', invalid: Boolean(nextErrors.title) }, - { id: 'prep-time', invalid: Boolean(nextErrors.prepTime) }, - { id: 'difficulty', invalid: Boolean(nextErrors.difficulty) }, - { id: 'cooking-time', invalid: Boolean(nextErrors.cookingTime) }, - { id: 'servings', invalid: Boolean(nextErrors.servings) }, - { id: 'category', invalid: Boolean(nextErrors.category) }, - { - id: 'ingredient-0', - invalid: Boolean(firstIngredientError?.name), - }, - { - id: 'ingredient-0-amount', - invalid: Boolean(firstIngredientError?.amount), - }, - { - id: 'ingredient-0-unit', - invalid: Boolean(firstIngredientError?.unit), - }, - { - id: 'instruction-0', - invalid: Boolean(nextErrors.instructions?.[0]), - }, - ].find((field) => field.invalid)?.id; - - window.setTimeout( - () => - document.getElementById(firstInvalidId ?? 'recipe-title')?.focus(), - 0, - ); + // Once the errors are rendered, focus the first invalid control in + // page order, whichever field or row it is in. Row-count messages are + // marked with data-form-error. + window.setTimeout(() => { + const firstInvalid = formRef.current?.querySelector( + '[aria-invalid="true"], [data-form-error]', + ); + (firstInvalid ?? document.getElementById('recipe-title'))?.focus(); + }, 0); return; } @@ -646,10 +681,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { note: item.note, })), instructions: instructions.map(({ text }) => text.trim()), - tags: tags - .split(',') - .map((tag) => tag.trim()) - .filter(Boolean), + tags: parseTags(tags), imageUrl, cuisine: recipe?.cuisine || null, }; @@ -684,6 +716,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
setTags(event.target.value)} + error={errors.tags} + onChange={(event) => { + setTags(event.target.value); + clearError('tags'); + }} /> Ingredients

Add each ingredient with its name, amount, and unit.

+ {errors.ingredientCount && ( +
+ + {errors.ingredientCount} + +
+ )}
{ingredients.map((ingredient, index) => ( @@ -1060,9 +1105,20 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { variant="secondary" size="sm" onClick={addIngredient} + disabled={ingredients.length >= MAX_INGREDIENTS} + aria-describedby={ + ingredients.length >= MAX_INGREDIENTS + ? 'ingredient-limit' + : undefined + } > Add ingredient + {ingredients.length >= MAX_INGREDIENTS && ( +

+ A recipe can have at most {MAX_INGREDIENTS} ingredients. +

+ )}
Instructions

Share the step-by-step process.

+ {errors.instructionCount && ( +
+ + {errors.instructionCount} + +
+ )}
{instructions.map((instruction, index) => ( @@ -1148,9 +1211,20 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { variant="secondary" size="sm" onClick={addInstruction} + disabled={instructions.length >= MAX_INSTRUCTIONS} + aria-describedby={ + instructions.length >= MAX_INSTRUCTIONS + ? 'instruction-limit' + : undefined + } > Add step + {instructions.length >= MAX_INSTRUCTIONS && ( +

+ A recipe can have at most {MAX_INSTRUCTIONS} steps. +

+ )}