diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index acd747d..fd1846a 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -7,11 +7,7 @@ import LoginPage from './features/auth/LoginPage'; import RegisterPage from './features/auth/RegisterPage'; import ExplorePage from './features/explore/ExplorePage'; - -const pages = [ - ['/cookbook', 'My Cookbook'], - ['/recipes/new', 'Add Recipe'], -] as const; +import RecipeCreatePage from './features/recipes/RecipeCreatePage'; export function App() { return ( @@ -19,13 +15,11 @@ export function App() { }> } /> - {pages.map(([path, title]) => ( - } - /> - ))} + } + /> + } /> } diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css new file mode 100644 index 0000000..e5e79e6 --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -0,0 +1,308 @@ +@layer components { + .recipe-create-page { + padding-block: var(--space-6) var(--space-8); + } + + .recipe-create-page__header { + display: flex; + flex-direction: column; + gap: var(--space-1); + max-width: 42rem; + margin-inline: auto; + text-align: center; + } + + .recipe-create-page__eyebrow { + margin: 0; + color: var(--color-text-accent); + font-size: var(--font-size-sm); + font-weight: var(--font-weight-bold); + letter-spacing: var(--letter-spacing-wide); + text-transform: uppercase; + } + + .recipe-create-page__intro { + color: var(--color-text-secondary); + } + + .recipe-create-page__header h1 { + font-size: var(--font-size-2xl); + } + + .recipe-create-page__content { + display: flex; + flex-direction: column; + gap: var(--space-4); + max-width: 64rem; + margin: var(--space-6) auto 0; + } + + .recipe-create-page__form { + width: 100%; + } + + .recipe-create-page__section { + display: grid; + grid-template-columns: minmax(10rem, 0.6fr) minmax(0, 1.4fr); + gap: var(--space-4); + padding: var(--space-4); + background: var(--color-surface); + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + } + + .recipe-create-page__section--basic { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .recipe-create-page__section h2 { + margin-bottom: var(--space-1); + font-size: var(--font-size-lg); + } + + .recipe-create-page__section-heading { + display: flex; + flex-direction: column; + gap: var(--space-2); + } + + .recipe-create-page__basic-fields, + .recipe-create-page__repeatable-list { + display: flex; + flex-direction: column; + gap: var(--space-3); + } + + .recipe-create-page__image-field { + display: flex; + flex-direction: column; + gap: var(--space-1); + min-width: 0; + } + + .recipe-create-page__image-selector { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-2); + padding: var(--space-5) var(--space-4); + color: var(--color-text-primary); + background: var(--color-surface-raised); + border: var(--border-width-thin) dashed var(--color-border-default); + border-radius: var(--radius-md); + cursor: pointer; + text-align: center; + transition: + border-color var(--duration-fast) var(--ease-standard), + background-color var(--duration-fast) var(--ease-standard); + } + + .recipe-create-page__section--basic .recipe-create-page__image-field, + .recipe-create-page__section--basic .recipe-create-page__image-selector, + .recipe-create-page__section--basic .recipe-create-page__image-preview-panel { + min-height: 100%; + } + + .recipe-create-page__image-selector { + flex: 1; + justify-content: center; + } + + .recipe-create-page__image-selector:hover { + background: var(--color-surface-hover); + border-color: var(--color-brand-primary); + } + + .recipe-create-page__image-selector--dragging { + background: var(--color-surface-selected); + border-color: var(--color-brand-primary); + } + + .recipe-create-page__image-selector:has( + .recipe-create-page__image-input:focus-visible + ) { + border-color: var(--color-focus-ring); + outline: var(--border-width-thin) solid var(--color-focus-ring); + outline-offset: 2px; + } + + .recipe-create-page__image-selector-icon { + display: grid; + place-items: center; + width: 2.5rem; + height: 2.5rem; + color: var(--color-text-accent); + background: var(--color-surface); + border-radius: var(--radius-full); + } + + .recipe-create-page__image-selector-title { + font-weight: var(--font-weight-semibold); + } + + .recipe-create-page__image-selector-help, + .recipe-create-page__image-name { + font-size: var(--font-size-sm); + } + + .recipe-create-page__image-selector-help { + color: var(--color-text-secondary); + } + + .recipe-create-page__image-selector-action { + padding: var(--space-2) var(--space-3); + color: var(--color-text-accent); + font-size: var(--font-size-sm); + font-weight: var(--font-weight-semibold); + background: var(--color-surface); + border: var(--border-width-thin) solid var(--color-border-default); + border-radius: var(--radius-sm); + } + + .recipe-create-page__image-input { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + white-space: nowrap; + clip: rect(0 0 0 0); + clip-path: inset(50%); + } + + .recipe-create-page__image-field > p[role='alert'] { + color: var(--color-feedback-error); + font-size: var(--font-size-sm); + } + + .recipe-create-page__image-preview { + display: block; + width: 100%; + height: 100%; + min-height: 12rem; + max-height: 20rem; + object-fit: cover; + border-radius: var(--radius-md); + } + + .recipe-create-page__image-preview-panel { + display: flex; + flex: 1; + flex-direction: column; + gap: var(--space-2); + } + + .recipe-create-page__image-preview-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + } + + .recipe-create-page__step-textarea { + min-height: 4.5rem; + max-height: 8rem; + } + + .recipe-create-page__details-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-3); + grid-column: 2; + } + + .recipe-create-page__details-grid + .field, + .recipe-create-page__details-grid + .field + .radio-group { + grid-column: 2; + } + + .recipe-create-page__repeatable-row { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: end; + gap: var(--space-2); + } + + .recipe-create-page__repeatable-row--dragging { + opacity: 0.55; + } + + .recipe-create-page__drag-handle { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: var(--target-size-min); + min-height: var(--target-size-min); + color: var(--color-text-muted); + cursor: grab; + } + + .recipe-create-page__drag-handle:active { + cursor: grabbing; + } + + .recipe-create-page__repeatable-row > .field, + .recipe-create-page__repeatable-row > .textarea { + min-width: 0; + } + + .recipe-create-page__actions { + display: flex; + justify-content: flex-end; + gap: var(--space-3); + } + + .recipe-create-page__section p { + color: var(--color-text-secondary); + } + + @media (max-width: 40rem) { + .recipe-create-page { + padding-block: var(--space-6) var(--space-8); + } + + .recipe-create-page__content { + margin-top: var(--space-6); + } + + .recipe-create-page__section { + display: flex; + flex-direction: column; + padding: var(--space-3); + } + + .recipe-create-page__section--basic { + grid-template-columns: 1fr; + } + + .recipe-create-page__section--basic .recipe-create-page__image-selector, + .recipe-create-page__section--basic + .recipe-create-page__image-preview-panel { + min-height: 12rem; + } + + .recipe-create-page__details-grid, + .recipe-create-page__details-grid + .field, + .recipe-create-page__details-grid + .field + .radio-group { + grid-column: auto; + } + + .recipe-create-page__details-grid { + display: flex; + flex-direction: column; + } + + .recipe-create-page__repeatable-row { + grid-template-columns: auto minmax(0, 1fr) auto; + } + + .recipe-create-page__actions { + flex-direction: column-reverse; + } + + .recipe-create-page__actions .button { + width: 100%; + } + } +} diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx new file mode 100644 index 0000000..c741d1e --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -0,0 +1,185 @@ +import '@testing-library/jest-dom/vitest'; +import { fireEvent, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { describe, expect, it, vi } from 'vitest'; + +import RecipeCreatePage from './RecipeCreatePage'; + +describe('RecipeCreatePage', () => { + it('exposes the recipe fields through accessible labels', () => { + render(); + + expect( + screen.getByRole('heading', { name: 'Add Recipe' }), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe title/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Short description/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Cooking time/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Servings/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Category/)).toBeInTheDocument(); + expect(screen.getByLabelText(/Tags/)).toBeInTheDocument(); + expect( + screen.getByRole('group', { name: /Visibility/ }), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe image/)).toBeInTheDocument(); + }); + + it('shows inline errors and focuses the first invalid field', async () => { + const user = userEvent.setup(); + + render(); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + + expect(screen.getByText('Enter a recipe title.')).toBeInTheDocument(); + expect( + screen.getByText('Enter a cooking time of at least 1 minute.'), + ).toBeInTheDocument(); + expect(screen.getByText('Choose a recipe category.')).toBeInTheDocument(); + expect(screen.getByText('Add an ingredient.')).toBeInTheDocument(); + expect(screen.getByText('Add an instruction.')).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe title/)).toHaveAttribute( + 'aria-invalid', + 'true', + ); + }); + + it('adds and removes ingredient and instruction rows', async () => { + const user = userEvent.setup(); + + render(); + + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + expect(screen.getByLabelText('Ingredient 2')).toBeInTheDocument(); + + await user.click( + screen.getByRole('button', { name: 'Remove ingredient 2' }), + ); + expect(screen.queryByLabelText('Ingredient 2')).not.toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Add step' })); + expect(screen.getByLabelText('Step 2')).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Remove step 2' })); + expect(screen.queryByLabelText('Step 2')).not.toBeInTheDocument(); + }); + + it('reorders ingredients and instructions by drag and drop', async () => { + const user = userEvent.setup(); + + render(); + + await user.click(screen.getByRole('button', { name: 'Add ingredient' })); + await user.type(screen.getByLabelText('Ingredient 1'), 'Flour'); + await user.type(screen.getByLabelText('Ingredient 2'), 'Sugar'); + + const firstIngredientRow = screen + .getByLabelText('Ingredient 1') + .closest('.recipe-create-page__repeatable-row'); + const secondIngredientRow = screen + .getByLabelText('Ingredient 2') + .closest('.recipe-create-page__repeatable-row'); + + fireEvent.dragStart(firstIngredientRow!); + fireEvent.drop(secondIngredientRow!, { dataTransfer: {} }); + + expect(screen.getByLabelText('Ingredient 1')).toHaveValue('Sugar'); + expect(screen.getByLabelText('Ingredient 2')).toHaveValue('Flour'); + + await user.click(screen.getByRole('button', { name: 'Add step' })); + await user.type(screen.getByLabelText('Step 1'), 'Mix'); + await user.type(screen.getByLabelText('Step 2'), 'Bake'); + + const firstInstructionRow = screen + .getByLabelText('Step 1') + .closest('.recipe-create-page__repeatable-row'); + const secondInstructionRow = screen + .getByLabelText('Step 2') + .closest('.recipe-create-page__repeatable-row'); + + fireEvent.dragStart(firstInstructionRow!); + fireEvent.drop(secondInstructionRow!, { dataTransfer: {} }); + + expect(screen.getByLabelText('Step 1')).toHaveValue('Bake'); + expect(screen.getByLabelText('Step 2')).toHaveValue('Mix'); + }); + + it('reports an invalid image without sending it anywhere', () => { + render(); + fireEvent.change(screen.getByLabelText(/Recipe image/), { + target: { + files: [ + new File(['not an image'], 'recipe.gif', { type: 'image/gif' }), + ], + }, + }); + + expect( + screen.getByText('Choose a JPG, PNG, or WebP image.'), + ).toBeInTheDocument(); + expect(screen.getByLabelText(/Recipe image/)).toHaveAttribute( + 'aria-invalid', + 'true', + ); + }); + + it('supports dropping, previewing, and removing an image', async () => { + vi.stubGlobal('URL', { + createObjectURL: vi.fn(() => 'blob:recipe-preview'), + revokeObjectURL: vi.fn(), + }); + + try { + const user = userEvent.setup(); + render(); + const imageFile = new File(['image data'], 'recipe.png', { + type: 'image/png', + }); + const imageSelector = screen + .getByText('Choose a recipe image') + .closest('label'); + + fireEvent.drop(imageSelector!, { + dataTransfer: { files: [imageFile] }, + }); + + expect( + screen.getByRole('img', { + name: 'Selected recipe', + }), + ).toHaveAttribute('src', 'blob:recipe-preview'); + expect(screen.getByText('recipe.png')).toBeInTheDocument(); + + await user.click( + screen.getByRole('button', { name: 'Remove recipe image' }), + ); + + expect(screen.getByText('Choose a recipe image')).toBeInTheDocument(); + expect( + screen.queryByRole('img', { + name: 'Selected recipe', + }), + ).not.toBeInTheDocument(); + } finally { + vi.unstubAllGlobals(); + } + }); + + it('shows local success feedback for a valid recipe', async () => { + const user = userEvent.setup(); + + render(); + + await user.type(screen.getByLabelText(/Recipe title/), 'Pasta'); + await user.type(screen.getByLabelText(/Cooking time/), '20'); + await user.type(screen.getByLabelText(/Servings/), '2'); + await user.selectOptions(screen.getByLabelText(/Category/), 'dinner'); + await user.type(screen.getByLabelText('Ingredient 1'), '200g pasta'); + await user.type(screen.getByLabelText('Step 1'), 'Boil the pasta.'); + await user.click(screen.getByRole('button', { name: 'Publish recipe' })); + + expect(screen.getByText('Recipe ready to publish')).toBeInTheDocument(); + expect( + screen.getByText(/No data was sent to a server/), + ).toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx new file mode 100644 index 0000000..e990910 --- /dev/null +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -0,0 +1,709 @@ +import { + useEffect, + useRef, + useState, + type DragEvent, + type FormEvent, +} from 'react'; + +import { + DeleteIcon, + DragHandleIcon, + UploadPhotoIcon, +} from '../../icons/actions'; +import Button from '../../components/ui/Button/Button'; +import Field from '../../components/ui/Field/Field'; +import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage'; +import IconButton from '../../components/ui/IconButton/IconButton'; +import { Icon } from '../../components/ui/Icon/Icon'; +import Radio from '../../components/ui/Radio/Radio'; +import RadioGroup from '../../components/ui/Radio/RadioGroup'; +import Select from '../../components/ui/Select/Select'; +import Textarea from '../../components/ui/Textarea/Textarea'; + +import './RecipeCreatePage.css'; + +type RecipeErrors = { + title?: string; + description?: string; + cookingTime?: string; + servings?: string; + category?: string; + visibility?: string; + image?: string; + ingredients?: string[]; + instructions?: string[]; +}; + +type FormStatus = 'idle' | 'draft' | 'published'; + +const MAX_IMAGE_SIZE = 5 * 1024 * 1024; +const ACCEPTED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp']; + +function moveItem(items: T[], fromIndex: number, toIndex: number) { + const nextItems = [...items]; + const [movedItem] = nextItems.splice(fromIndex, 1); + if (movedItem === undefined) return nextItems; + nextItems.splice(toIndex, 0, movedItem); + return nextItems; +} + +function RecipeCreatePage() { + const [title, setTitle] = useState(''); + const [description, setDescription] = useState(''); + const [cookingTime, setCookingTime] = useState(''); + const [servings, setServings] = useState(''); + const [category, setCategory] = useState(''); + const [tags, setTags] = useState(''); + const [visibility, setVisibility] = useState('public'); + const [imageName, setImageName] = useState(''); + const [imagePreviewUrl, setImagePreviewUrl] = useState(''); + const [isDraggingImage, setIsDraggingImage] = useState(false); + const imageInputRef = useRef(null); + const [ingredients, setIngredients] = useState(['']); + const [instructions, setInstructions] = useState(['']); + const [draggingRow, setDraggingRow] = useState< + { type: 'ingredient' | 'instruction'; index: number } | undefined + >(); + const [errors, setErrors] = useState({}); + const [status, setStatus] = useState('idle'); + + useEffect(() => { + return () => { + if (imagePreviewUrl) URL.revokeObjectURL(imagePreviewUrl); + }; + }, [imagePreviewUrl]); + + function clearError(key: keyof RecipeErrors) { + setErrors((currentErrors) => { + const nextErrors = { ...currentErrors }; + delete nextErrors[key]; + return nextErrors; + }); + setStatus('idle'); + } + + function addIngredient() { + setIngredients((currentIngredients) => [...currentIngredients, '']); + } + + function removeIngredient(index: number) { + setIngredients((currentIngredients) => + currentIngredients.filter( + (_, ingredientIndex) => ingredientIndex !== index, + ), + ); + } + + function updateIngredient(index: number, value: string) { + setIngredients((currentIngredients) => + currentIngredients.map((ingredient, ingredientIndex) => + ingredientIndex === index ? value : ingredient, + ), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + ingredients: currentErrors.ingredients?.map((error, errorIndex) => + errorIndex === index ? '' : error, + ), + })); + setStatus('idle'); + } + + function reorderIngredients(fromIndex: number, toIndex: number) { + if (fromIndex === toIndex) return; + + setIngredients((currentIngredients) => + moveItem(currentIngredients, fromIndex, toIndex), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + ingredients: currentErrors.ingredients + ? moveItem(currentErrors.ingredients, fromIndex, toIndex) + : undefined, + })); + setStatus('idle'); + } + + function addInstruction() { + setInstructions((currentInstructions) => [...currentInstructions, '']); + } + + function removeInstruction(index: number) { + setInstructions((currentInstructions) => + currentInstructions.filter( + (_, instructionIndex) => instructionIndex !== index, + ), + ); + } + + function updateInstruction(index: number, value: string) { + setInstructions((currentInstructions) => + currentInstructions.map((instruction, instructionIndex) => + instructionIndex === index ? value : instruction, + ), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + instructions: currentErrors.instructions?.map((error, errorIndex) => + errorIndex === index ? '' : error, + ), + })); + setStatus('idle'); + } + + function reorderInstructions(fromIndex: number, toIndex: number) { + if (fromIndex === toIndex) return; + + setInstructions((currentInstructions) => + moveItem(currentInstructions, fromIndex, toIndex), + ); + setErrors((currentErrors) => ({ + ...currentErrors, + instructions: currentErrors.instructions + ? moveItem(currentErrors.instructions, fromIndex, toIndex) + : undefined, + })); + setStatus('idle'); + } + + function handleRowDragEnd() { + setDraggingRow(undefined); + } + + function handleIngredientDrop( + event: DragEvent, + toIndex: number, + ) { + event.preventDefault(); + if (draggingRow?.type === 'ingredient') { + reorderIngredients(draggingRow.index, toIndex); + } + setDraggingRow(undefined); + } + + function handleInstructionDrop( + event: DragEvent, + toIndex: number, + ) { + event.preventDefault(); + if (draggingRow?.type === 'instruction') { + reorderInstructions(draggingRow.index, toIndex); + } + setDraggingRow(undefined); + } + + function handleImageChange(file: File | undefined) { + clearError('image'); + + if (!file) { + setImageName(''); + setImagePreviewUrl(''); + return; + } + + if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) { + setErrors((currentErrors) => ({ + ...currentErrors, + image: 'Choose a JPG, PNG, or WebP image.', + })); + setImageName(''); + setImagePreviewUrl(''); + return; + } + + if (file.size > MAX_IMAGE_SIZE) { + setErrors((currentErrors) => ({ + ...currentErrors, + image: 'Choose an image smaller than 5 MB.', + })); + setImageName(''); + setImagePreviewUrl(''); + return; + } + + setImageName(file.name); + setImagePreviewUrl(URL.createObjectURL(file)); + } + + function handleImageDrop(event: DragEvent) { + event.preventDefault(); + setIsDraggingImage(false); + handleImageChange(event.dataTransfer.files[0]); + } + + function removeImage() { + clearError('image'); + setImageName(''); + setImagePreviewUrl(''); + setIsDraggingImage(false); + if (imageInputRef.current) imageInputRef.current.value = ''; + } + + function validateForm(): RecipeErrors { + const nextErrors: RecipeErrors = {}; + + if (!title.trim()) nextErrors.title = 'Enter a recipe title.'; + if (description.trim().length > 200) { + nextErrors.description = 'Keep the description under 200 characters.'; + } + if (!cookingTime || Number(cookingTime) < 1) { + nextErrors.cookingTime = 'Enter a cooking time of at least 1 minute.'; + } + if (!servings || Number(servings) < 1) { + nextErrors.servings = 'Enter at least 1 serving.'; + } + if (!category) nextErrors.category = 'Choose a recipe category.'; + if (!visibility) { + nextErrors.visibility = 'Choose who can see this recipe.'; + } + + const ingredientErrors = ingredients.map((ingredient) => + ingredient.trim() ? '' : 'Add an ingredient.', + ); + if (ingredientErrors.some(Boolean)) + nextErrors.ingredients = ingredientErrors; + + const instructionErrors = instructions.map((instruction) => + instruction.trim() ? '' : 'Add an instruction.', + ); + if (instructionErrors.some(Boolean)) { + nextErrors.instructions = instructionErrors; + } + + return nextErrors; + } + + function handleSubmit(event: FormEvent) { + event.preventDefault(); + + const nextErrors = validateForm(); + setErrors(nextErrors); + + if (Object.keys(nextErrors).length > 0) { + const firstInvalidId = [ + 'recipe-title', + 'cooking-time', + 'servings', + 'category', + 'ingredient-0', + 'instruction-0', + ].find((id) => { + if (id === 'ingredient-0') return nextErrors.ingredients?.[0]; + if (id === 'instruction-0') return nextErrors.instructions?.[0]; + return Boolean(nextErrors[id as keyof RecipeErrors]); + }); + + window.setTimeout( + () => + document.getElementById(firstInvalidId ?? 'recipe-title')?.focus(), + 0, + ); + return; + } + + setStatus('published'); + } + + return ( +
+
+

Share with the community

+

Add Recipe

+

+ Share your favorite recipe with the community. +

+
+ +
+
+ {status === 'published' && ( + + Your recipe has been prepared locally. No data was sent to a + server. + + )} + + {status === 'draft' && ( + + Your draft is available in this form until you leave the page. + + )} + +
+
+
+

Basic Information

+

Tell us about your recipe.

+
+ +
+ { + setTitle(event.target.value); + clearError('title'); + }} + required + /> + +