From 9a476c7b5396405e7548eac81cfab814ea415712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 16:39:41 +0100 Subject: [PATCH 1/2] fix(recipe): check the API's size limits in the form; focus any invalid row - MAX_INGREDIENTS, MAX_INSTRUCTIONS, MAX_TAGS and MAX_TAG_LENGTH live in @t31/validation/recipe and are used by the API schema and the form. - Tags are parsed with the shared parseTags() (trimmed, lower-case, no repeats), so the form counts and sends what the API stores. More than 30 tags or a tag over 50 characters is a field error on Tags. - Add ingredient / Add step are disabled at the limit with a visible explanation; a recipe or restored draft with too many rows gets a message above the list. - After a failed submit, focus moves to the first invalid control in page order (any row), instead of a fixed list that only knew row 1. Closes #120 --- .../src/features/recipes/recipeValidation.ts | 20 ++- apps/validation/src/recipe.test.ts | 13 ++ apps/validation/src/recipe.ts | 26 ++++ .../src/features/recipes/RecipeCreatePage.css | 7 ++ .../recipes/RecipeCreatePage.limits.test.tsx | 95 ++++++++++++++ .../recipes/RecipeCreatePage.test.tsx | 101 +++++++++++++++ .../src/features/recipes/RecipeCreatePage.tsx | 118 ++++++++++++------ 7 files changed, 337 insertions(+), 43 deletions(-) create mode 100644 apps/validation/src/recipe.test.ts create mode 100644 apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx 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..45a75cb --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx @@ -0,0 +1,95 @@ +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()); +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 +}); 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..175d236 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 = { @@ -105,6 +117,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(''); @@ -315,6 +328,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function removeIngredient(index: number) { + clearError('ingredientCount'); setIngredients((currentIngredients) => currentIngredients.filter( (_, ingredientIndex) => ingredientIndex !== index, @@ -369,6 +383,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function removeInstruction(index: number) { + clearError('instructionCount'); setInstructions((currentInstructions) => currentInstructions.filter( (_, instructionIndex) => instructionIndex !== index, @@ -543,6 +558,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}.`; + if (ingredients.length > MAX_INGREDIENTS) + nextErrors.ingredientCount = `A recipe can have at most ${MAX_INGREDIENTS} ingredients. Remove ${ingredients.length - MAX_INGREDIENTS} to save.`; + if (instructions.length > MAX_INSTRUCTIONS) + nextErrors.instructionCount = `A recipe can have at most ${MAX_INSTRUCTIONS} steps. Remove ${instructions.length - MAX_INSTRUCTIONS} to save.`; const ingredientErrors = ingredients.map((ingredient) => ({ name: !ingredient.name.trim() @@ -592,37 +617,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 +649,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 +684,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 +1073,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 +1179,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. +

+ )}
From 581a8334ad8e8237de08a151d275acee15447ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliver=20=C3=98rjavik?= Date: Tue, 17 Nov 2026 18:22:59 +0100 Subject: [PATCH 2/2] fix(recipe): keep row-limit errors until the list is within the limit Removing one ingredient or step cleared the "at most 100" message even when the list still had too many rows, so the form looked valid until the next submit. The message now stays and shows the remaining number to remove, and goes away only when the list fits. Restoring a draft with more rows than the API accepts also cleared every error, so the problem only appeared on submit. Restoring now shows the row-count messages straight away. Both paths share one helper, built on MAX_INGREDIENTS and MAX_INSTRUCTIONS from @t31/validation/recipe, which validation on submit uses as well. Tests: the message recounts after each removal and clears at the limit (ingredients and steps); an over-limit draft shows both messages when restored. --- .../recipes/RecipeCreatePage.limits.test.tsx | 92 ++++++++++++++++++- .../src/features/recipes/RecipeCreatePage.tsx | 46 ++++++++-- 2 files changed, 130 insertions(+), 8 deletions(-) diff --git a/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx index 45a75cb..125df6d 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx @@ -22,7 +22,10 @@ vi.mock('@t31/validation/recipe', async (importOriginal) => ({ MAX_INSTRUCTIONS: 3, })); -afterEach(() => vi.unstubAllGlobals()); +afterEach(() => { + vi.unstubAllGlobals(); + localStorage.clear(); +}); beforeEach(() => useAppStore.setState({ currentUser: apiUser, @@ -50,6 +53,7 @@ function edit(recipe: object) { render( + } /> } /> , @@ -93,3 +97,89 @@ it('flags a recipe with more rows than allowed and focuses the message', async ( ).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.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 175d236..783dc3a 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -106,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); @@ -261,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. @@ -328,7 +341,17 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function removeIngredient(index: number) { - clearError('ingredientCount'); + // 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, @@ -383,7 +406,16 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { } function removeInstruction(index: number) { - clearError('instructionCount'); + 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, @@ -564,10 +596,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { 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}.`; - if (ingredients.length > MAX_INGREDIENTS) - nextErrors.ingredientCount = `A recipe can have at most ${MAX_INGREDIENTS} ingredients. Remove ${ingredients.length - MAX_INGREDIENTS} to save.`; - if (instructions.length > MAX_INSTRUCTIONS) - nextErrors.instructionCount = `A recipe can have at most ${MAX_INSTRUCTIONS} steps. Remove ${instructions.length - MAX_INSTRUCTIONS} to save.`; + Object.assign( + nextErrors, + rowCountErrors(ingredients.length, instructions.length), + ); const ingredientErrors = ingredients.map((ingredient) => ({ name: !ingredient.name.trim()