Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions apps/api/src/features/recipes/recipeValidation.ts
Original file line number Diff line number Diff line change
@@ -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([
Expand Down Expand Up @@ -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)]),
});

Expand Down
13 changes: 13 additions & 0 deletions apps/validation/src/recipe.test.ts
Original file line number Diff line number Diff line change
@@ -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([]);
});
});
26 changes: 26 additions & 0 deletions apps/validation/src/recipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
),
];
}
7 changes: 7 additions & 0 deletions apps/web/src/features/recipes/RecipeCreatePage.css
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
95 changes: 95 additions & 0 deletions apps/web/src/features/recipes/RecipeCreatePage.limits.test.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof import('@t31/validation/recipe')>()),
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(
<MemoryRouter initialEntries={[`/recipes/${apiRecipe.id}/edit`]}>
<Routes>
<Route path="/recipes/:id/edit" element={<RecipeCreatePage />} />
</Routes>
</MemoryRouter>,
);
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
});
101 changes: 101 additions & 0 deletions apps/web/src/features/recipes/RecipeCreatePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
Loading