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
3 changes: 2 additions & 1 deletion apps/api/src/features/recipes/recipeValidation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { GraphQLError } from 'graphql';
import { z } from 'zod';
import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe';
import { uploadedImagePattern } from './imagePaths.js';

export const categorySchema = z.enum([
Expand Down Expand Up @@ -31,7 +32,7 @@ export const recipeInputSchema = z.object({
visibility: z.enum(['public', 'private']),
prepMinutes: z.number().int().min(0).max(10080),
cookMinutes: z.number().int().min(0).max(10080),
servings: z.number().int().min(1).max(1000),
servings: z.number().int().min(MIN_SERVINGS).max(MAX_SERVINGS),
ingredients: z
.array(
z.object({
Expand Down
4 changes: 4 additions & 0 deletions apps/validation/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
".": {
"types": "./dist/auth.d.ts",
"import": "./dist/auth.js"
},
"./recipe": {
"types": "./dist/recipe.d.ts",
"import": "./dist/recipe.js"
}
},
"scripts": {
Expand Down
7 changes: 7 additions & 0 deletions apps/validation/src/recipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* Servings a recipe can be written for and scaled to. Shared by the API's
* input validation, the recipe form and the detail page's servings control,
* so the three can never disagree.
*/
export const MIN_SERVINGS = 1;
export const MAX_SERVINGS = 1000;
25 changes: 24 additions & 1 deletion apps/web/src/features/recipe-detail/RecipeDetailPage.css
Original file line number Diff line number Diff line change
Expand Up @@ -284,11 +284,34 @@
line-height: var(--line-height-tight);
}

.recipe-detail-page__servings-value strong {
.recipe-detail-page__servings-input {
width: 4.5ch;
padding: 0;

border: var(--border-width-thin) solid transparent;
border-radius: var(--radius-sm);

color: var(--color-text-primary);
background: transparent;

font: inherit;
font-size: var(--font-size-2xl);
font-weight: var(--font-weight-semibold);
line-height: var(--line-height-tight);
text-align: center;

/* Hide the browser's own spinner; the −/+ buttons do that job. */
appearance: textfield;
}

.recipe-detail-page__servings-input::-webkit-inner-spin-button,
.recipe-detail-page__servings-input::-webkit-outer-spin-button {
margin: 0;
appearance: none;
}

.recipe-detail-page__servings-input:hover {
border-color: var(--color-border-input);
}

.recipe-detail-page__content-card {
Expand Down
28 changes: 28 additions & 0 deletions apps/web/src/features/recipe-detail/RecipeDetailPage.test.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import '@testing-library/jest-dom/vitest';
import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
Expand Down Expand Up @@ -139,3 +140,30 @@ it('keeps a failed rating editable and refreshes the persisted rating after retr
await screen.findByRole('button', { name: 'Rate Recipe' }),
).toBeTruthy();
});
it('scales beyond 20 servings and accepts a typed number within the API limits', async () => {
mockRecipeFetch(() => ({ data: { recipe: { ...apiRecipe, servings: 40 } } }));
mount();
await screen.findByRole('heading', { name: 'API soup' });
const user = userEvent.setup();
const [servings] = screen.getAllByLabelText('Servings (1–1000)');
expect(servings).toHaveValue(40);
await user.click(
screen.getAllByRole('button', { name: 'Increase servings' })[0]!,
);
expect(servings).toHaveValue(41);
await user.clear(servings!);
await user.type(servings!, '250');
expect(servings).toHaveValue(250);
// Out-of-range input is clamped when the field is left.
await user.clear(servings!);
await user.type(servings!, '5000');
await user.tab();
expect(servings).toHaveValue(1000);
expect(
screen.getAllByRole('button', { name: 'Increase servings' })[0],
).toBeDisabled();
// Clearing the field and leaving restores the last valid value.
await user.clear(servings!);
await user.tab();
expect(servings).toHaveValue(1000);
});
89 changes: 12 additions & 77 deletions apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,10 @@ import Button from '../../components/ui/Button/Button';
import ConfirmationDialog from '../../components/ui/ConfirmationDialog/ConfirmationDialog';
import EmptyState from '../../components/ui/EmptyState/EmptyState';
import { Icon } from '../../components/ui/Icon/Icon';
import IconButton from '../../components/ui/IconButton/IconButton';
import LinkButton from '../../components/ui/LinkButton/LinkButton';
import Tag from '../../components/ui/Tag/Tag';
import Toast, { type ToastTone } from '../../components/ui/Toast/Toast';
import {
BookmarkIcon,
EditIcon,
MinusIcon,
PlusIcon,
} from '../../icons/actions';
import { BookmarkIcon, EditIcon } from '../../icons/actions';
import { BackIcon } from '../../icons/navigation';
import { EmptyStateIcon, PrivateIcon } from '../../icons/recipe';
import { useAppStore } from '../../store';
Expand All @@ -37,10 +31,9 @@ import {
} from '../recipes/recipeApi';
import { useRecipeQuery } from '../recipes/useRecipeQuery';
import RecipeQueryStatus from '../recipes/RecipeQueryStatus';
import ServingsStepper from './ServingsStepper';
import './RecipeDetailPage.css';

const MIN_SERVINGS = 1;
const MAX_SERVINGS = 20;
const MAX_VISIBLE_TAGS = 5;

interface RecipeDetailLocationState {
Expand Down Expand Up @@ -450,40 +443,11 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
<p>Ingredient amounts update automatically.</p>
</div>

<div className="recipe-detail-page__stepper">
<IconButton
icon={MinusIcon}
variant="secondary"
aria-label="Decrease servings"
disabled={selectedServings <= MIN_SERVINGS}
onClick={() =>
setSelectedServings((current) =>
Math.max(MIN_SERVINGS, current - 1),
)
}
/>

<output
className="recipe-detail-page__servings-value"
aria-live="polite"
>
<strong>{selectedServings}</strong>

<span>{selectedServings === 1 ? 'serving' : 'servings'}</span>
</output>

<IconButton
icon={PlusIcon}
variant="secondary"
aria-label="Increase servings"
disabled={selectedServings >= MAX_SERVINGS}
onClick={() =>
setSelectedServings((current) =>
Math.min(MAX_SERVINGS, current + 1),
)
}
/>
</div>
<ServingsStepper
id="mobile"
value={selectedServings}
onChange={setSelectedServings}
/>
</section>
</header>
</div>
Expand All @@ -507,40 +471,11 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
<p>Ingredient amounts update automatically.</p>
</div>

<div className="recipe-detail-page__stepper">
<IconButton
icon={MinusIcon}
variant="secondary"
aria-label="Decrease servings"
disabled={selectedServings <= MIN_SERVINGS}
onClick={() =>
setSelectedServings((current) =>
Math.max(MIN_SERVINGS, current - 1),
)
}
/>

<output
className="recipe-detail-page__servings-value"
aria-live="polite"
>
<strong>{selectedServings}</strong>

<span>{selectedServings === 1 ? 'serving' : 'servings'}</span>
</output>

<IconButton
icon={PlusIcon}
variant="secondary"
aria-label="Increase servings"
disabled={selectedServings >= MAX_SERVINGS}
onClick={() =>
setSelectedServings((current) =>
Math.min(MAX_SERVINGS, current + 1),
)
}
/>
</div>
<ServingsStepper
id="desktop"
value={selectedServings}
onChange={setSelectedServings}
/>
</section>

<div
Expand Down
95 changes: 95 additions & 0 deletions apps/web/src/features/recipe-detail/ServingsStepper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { useState } from 'react';
import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe';

import IconButton from '../../components/ui/IconButton/IconButton';
import { MinusIcon, PlusIcon } from '../../icons/actions';

type ServingsStepperProps = {
/** Unique per instance; the page renders one for mobile and one for desktop. */
id: string;
value: number;
onChange: (servings: number) => void;
};

const clamp = (servings: number) =>
Math.min(MAX_SERVINGS, Math.max(MIN_SERVINGS, servings));

/**
* −/+ buttons around a number field. Typing a whole number within the limits
* updates the recipe right away; anything else is corrected when the field
* loses focus (clamped to the limits, or restored if not a number).
*/
export default function ServingsStepper({
id,
value,
onChange,
}: ServingsStepperProps) {
// The text being typed may be briefly invalid (e.g. empty while retyping).
const [draft, setDraft] = useState<string | null>(null);
const inputId = `${id}-servings-input`;

function commit(text: string) {
const typed = Number(text);
if (text.trim() === '' || !Number.isFinite(typed)) return;
onChange(clamp(Math.round(typed)));
}

return (
<div className="recipe-detail-page__stepper">
<IconButton
icon={MinusIcon}
variant="secondary"
aria-label="Decrease servings"
disabled={value <= MIN_SERVINGS}
onClick={() => onChange(clamp(value - 1))}
/>

<div className="recipe-detail-page__servings-value">
<label className="sr-only" htmlFor={inputId}>
Servings ({MIN_SERVINGS}–{MAX_SERVINGS})
</label>
<input
id={inputId}
className="recipe-detail-page__servings-input"
type="number"
inputMode="numeric"
min={MIN_SERVINGS}
max={MAX_SERVINGS}
step={1}
value={draft ?? String(value)}
onChange={(event) => {
const text = event.currentTarget.value;
setDraft(text);
const typed = Number(text);
if (
Number.isInteger(typed) &&
typed >= MIN_SERVINGS &&
typed <= MAX_SERVINGS
)
onChange(typed);
}}
onBlur={(event) => {
commit(event.currentTarget.value);
setDraft(null);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') event.currentTarget.blur();
}}
/>
<span aria-hidden="true">{value === 1 ? 'serving' : 'servings'}</span>
{/* Announces changes made with the buttons. */}
<span className="sr-only" aria-live="polite">
{value} {value === 1 ? 'serving' : 'servings'}
</span>
</div>

<IconButton
icon={PlusIcon}
variant="secondary"
aria-label="Increase servings"
disabled={value >= MAX_SERVINGS}
onClick={() => onChange(clamp(value + 1))}
/>
</div>
);
}
7 changes: 4 additions & 3 deletions apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { useRecipeQuery } from './useRecipeQuery';
import RecipeQueryStatus from './RecipeQueryStatus';
import LinkButton from '../../components/ui/LinkButton/LinkButton';
import RecipeImageField from './RecipeImageField';
import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe';

import './RecipeCreatePage.css';

Expand Down Expand Up @@ -309,10 +310,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
if (
!servings ||
!Number.isInteger(Number(servings)) ||
Number(servings) < 1 ||
Number(servings) > 1000
Number(servings) < MIN_SERVINGS ||
Number(servings) > MAX_SERVINGS
) {
nextErrors.servings = 'Enter whole servings from 1 to 1000.';
nextErrors.servings = `Enter whole servings from ${MIN_SERVINGS} to ${MAX_SERVINGS}.`;
}
if (!category) nextErrors.category = 'Choose a recipe category.';
if (!visibility) {
Expand Down