feat(frontend): implement recipe detail/edit page with full CRUD functionality

- Created useRecipe hook for fetching single recipe with loading/error states
- Created RecipeForm component with comprehensive validation
  - Title, ingredients, and instructions marked as required fields
  - One ingredient/instruction per line with textarea inputs
  - Optional metadata: servings, prep time, cook time, source URL, notes
  - Real-time form validation with error messaging
- Implemented RecipeDetailPage with three modes:
  - Create mode: /recipe/new route for adding new recipes
  - View mode: Display recipe with formatted ingredients and instructions
  - Edit mode: Toggle to edit existing recipe with pre-populated form
- Added delete functionality with two-step confirmation
- Included metadata cards for servings, prep time, and cook time
- Added navigation: Cook Mode button, back to list link
- Styled with Tailwind CSS for consistent UI/UX
- Verified TypeScript compilation and Vite build succeed
- Updated TODO.md to mark task complete
This commit is contained in:
Paul Huliganga 2026-03-24 03:27:51 -04:00
parent c6c5d0e3f4
commit 67a9a8ce16
4 changed files with 593 additions and 15 deletions

13
TODO.md
View File

@ -20,7 +20,7 @@
- [x] Configure Tailwind CSS
- [x] Set up React Router
- [x] Create recipe list page
- [ ] Create recipe detail/edit page
- [x] Create recipe detail/edit page
- [ ] Implement cook mode UI
### Features
@ -46,6 +46,17 @@
## ✅ Completed Tasks
### 2026-03-24
- **Recipe detail/edit page implementation**
- Created useRecipe hook for fetching single recipe with loading/error states
- Created RecipeForm component with full validation (title, ingredients, instructions required)
- Implemented RecipeDetailPage with view/edit modes
- Added create new recipe functionality (/recipe/new route)
- Implemented edit existing recipe with form pre-population
- Added delete recipe with confirmation dialog
- Included metadata display (servings, prep time, cook time)
- Added navigation to cook mode and back to list
- Verified TypeScript compilation and Vite build succeed
- **Recipe list page implementation**
- Created API client service (src/services/api.ts) with all CRUD operations
- Created useRecipes hook for data fetching with search and pagination

View File

@ -0,0 +1,278 @@
import { useState, useEffect } from 'react';
import type { Recipe } from '../types/recipe';
interface RecipeFormProps {
recipe?: Recipe | null;
onSubmit: (data: RecipeFormData) => Promise<void>;
onCancel: () => void;
submitLabel?: string;
}
export interface RecipeFormData {
title: string;
description?: string;
ingredients: string[];
instructions: string[];
source_url?: string;
notes?: string;
servings?: number;
prep_time_minutes?: number;
cook_time_minutes?: number;
}
/**
* RecipeForm - Form component for creating/editing recipes
*/
export function RecipeForm({ recipe, onSubmit, onCancel, submitLabel = 'Save Recipe' }: RecipeFormProps) {
// Form state
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [ingredientsText, setIngredientsText] = useState('');
const [instructionsText, setInstructionsText] = useState('');
const [sourceUrl, setSourceUrl] = useState('');
const [notes, setNotes] = useState('');
const [servings, setServings] = useState('');
const [prepTime, setPrepTime] = useState('');
const [cookTime, setCookTime] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Populate form from recipe prop
useEffect(() => {
if (recipe) {
setTitle(recipe.title || '');
setDescription(recipe.description || '');
setIngredientsText(recipe.ingredients.join('\n'));
setInstructionsText(recipe.instructions.join('\n'));
setSourceUrl(recipe.source_url || '');
setNotes(recipe.notes || '');
setServings(recipe.servings?.toString() || '');
setPrepTime(recipe.prep_time_minutes?.toString() || '');
setCookTime(recipe.cook_time_minutes?.toString() || '');
}
}, [recipe]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
// Validation
if (!title.trim()) {
setError('Title is required');
return;
}
const ingredientsList = ingredientsText
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
if (ingredientsList.length === 0) {
setError('At least one ingredient is required');
return;
}
const instructionsList = instructionsText
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
if (instructionsList.length === 0) {
setError('At least one instruction step is required');
return;
}
const data: RecipeFormData = {
title: title.trim(),
description: description.trim() || undefined,
ingredients: ingredientsList,
instructions: instructionsList,
source_url: sourceUrl.trim() || undefined,
notes: notes.trim() || undefined,
servings: servings ? parseInt(servings, 10) : undefined,
prep_time_minutes: prepTime ? parseInt(prepTime, 10) : undefined,
cook_time_minutes: cookTime ? parseInt(cookTime, 10) : undefined,
};
try {
setIsSubmitting(true);
await onSubmit(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to save recipe');
setIsSubmitting(false);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-6">
{error && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded">
{error}
</div>
)}
{/* Title */}
<div>
<label htmlFor="title" className="block text-sm font-medium text-gray-700">
Title <span className="text-red-500">*</span>
</label>
<input
type="text"
id="title"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="e.g., Chocolate Chip Cookies"
required
/>
</div>
{/* Description */}
<div>
<label htmlFor="description" className="block text-sm font-medium text-gray-700">
Description
</label>
<textarea
id="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={2}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Brief description of the recipe..."
/>
</div>
{/* Ingredients */}
<div>
<label htmlFor="ingredients" className="block text-sm font-medium text-gray-700">
Ingredients <span className="text-red-500">*</span>
</label>
<p className="mt-1 text-sm text-gray-500">One ingredient per line</p>
<textarea
id="ingredients"
value={ingredientsText}
onChange={(e) => setIngredientsText(e.target.value)}
rows={8}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 font-mono text-sm"
placeholder="2 cups all-purpose flour&#10;1 cup butter, softened&#10;3/4 cup sugar"
required
/>
</div>
{/* Instructions */}
<div>
<label htmlFor="instructions" className="block text-sm font-medium text-gray-700">
Instructions <span className="text-red-500">*</span>
</label>
<p className="mt-1 text-sm text-gray-500">One step per line</p>
<textarea
id="instructions"
value={instructionsText}
onChange={(e) => setInstructionsText(e.target.value)}
rows={10}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 font-mono text-sm"
placeholder="Preheat oven to 350°F&#10;Mix flour and baking soda&#10;Cream butter and sugar"
required
/>
</div>
{/* Metadata Grid */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label htmlFor="servings" className="block text-sm font-medium text-gray-700">
Servings
</label>
<input
type="number"
id="servings"
value={servings}
onChange={(e) => setServings(e.target.value)}
min="1"
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="4"
/>
</div>
<div>
<label htmlFor="prep_time" className="block text-sm font-medium text-gray-700">
Prep Time (min)
</label>
<input
type="number"
id="prep_time"
value={prepTime}
onChange={(e) => setPrepTime(e.target.value)}
min="0"
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="15"
/>
</div>
<div>
<label htmlFor="cook_time" className="block text-sm font-medium text-gray-700">
Cook Time (min)
</label>
<input
type="number"
id="cook_time"
value={cookTime}
onChange={(e) => setCookTime(e.target.value)}
min="0"
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="30"
/>
</div>
</div>
{/* Source URL */}
<div>
<label htmlFor="source_url" className="block text-sm font-medium text-gray-700">
Source URL
</label>
<input
type="url"
id="source_url"
value={sourceUrl}
onChange={(e) => setSourceUrl(e.target.value)}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="https://example.com/recipe"
/>
</div>
{/* Notes */}
<div>
<label htmlFor="notes" className="block text-sm font-medium text-gray-700">
Notes
</label>
<textarea
id="notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={3}
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="Personal notes, substitutions, tips..."
/>
</div>
{/* Form Actions */}
<div className="flex gap-3 pt-4">
<button
type="submit"
disabled={isSubmitting}
className="flex-1 bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed font-medium"
>
{isSubmitting ? 'Saving...' : submitLabel}
</button>
<button
type="button"
onClick={onCancel}
disabled={isSubmitting}
className="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed font-medium"
>
Cancel
</button>
</div>
</form>
);
}

View File

@ -0,0 +1,52 @@
import { useState, useEffect } from 'react';
import { fetchRecipe } from '../services/api';
import type { Recipe } from '../types/recipe';
/**
* Hook for fetching and managing a single recipe
*/
export function useRecipe(id: number | null) {
const [recipe, setRecipe] = useState<Recipe | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (id === null) {
// New recipe mode - no fetch needed
setRecipe(null);
setLoading(false);
return;
}
let mounted = true;
async function loadRecipe() {
if (id === null) return; // Type guard for TypeScript
try {
setLoading(true);
setError(null);
const data = await fetchRecipe(id);
if (mounted) {
setRecipe(data);
}
} catch (err) {
if (mounted) {
setError(err instanceof Error ? err.message : 'Failed to load recipe');
}
} finally {
if (mounted) {
setLoading(false);
}
}
}
loadRecipe();
return () => {
mounted = false;
};
}, [id]);
return { recipe, loading, error, refetch: () => setRecipe(null) };
}

View File

@ -1,27 +1,264 @@
import { useParams } from 'react-router-dom';
import { useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useRecipe } from '../hooks/useRecipe';
import { RecipeForm, type RecipeFormData } from '../components/RecipeForm';
import { createRecipe, updateRecipe, deleteRecipe } from '../services/api';
/**
* RecipeDetailPage - View and edit a single recipe
* RecipeDetailPage - View, create, and edit recipes
*/
export function RecipeDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
// Parse ID or null for "new" route
const recipeId = id === 'new' ? null : (id ? parseInt(id, 10) : null);
const { recipe, loading, error } = useRecipe(recipeId);
const [isEditing, setIsEditing] = useState(recipeId === null); // Start in edit mode for new recipes
const [deleteConfirm, setDeleteConfirm] = useState(false);
// Handle form submission
const handleSubmit = async (data: RecipeFormData) => {
if (recipeId === null) {
// Create new recipe
const newRecipe = await createRecipe(data);
navigate(`/recipe/${newRecipe.id}`);
} else {
// Update existing recipe
await updateRecipe(recipeId, data);
setIsEditing(false);
// Refresh the page to show updated data
window.location.reload();
}
};
// Handle delete
const handleDelete = async () => {
if (recipeId === null) return;
await deleteRecipe(recipeId);
navigate('/');
};
// Loading state
if (loading) {
return (
<div className="text-center py-12">
<div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
<p className="mt-4 text-gray-600">Loading recipe...</p>
</div>
);
}
// Error state
if (error) {
return (
<div className="bg-red-50 border border-red-200 rounded-lg p-6">
<h3 className="text-red-800 font-semibold mb-2">Error Loading Recipe</h3>
<p className="text-red-600">{error}</p>
<Link to="/" className="mt-4 inline-block text-blue-600 hover:text-blue-700">
Back to recipes
</Link>
</div>
);
}
// New recipe mode (always in edit)
if (recipeId === null) {
return (
<div>
<div className="mb-6">
<h2 className="text-2xl font-bold text-gray-900">
Recipe Details {id ? `#${id}` : '(New)'}
</h2>
<h2 className="text-2xl font-bold text-gray-900">Create New Recipe</h2>
<p className="mt-1 text-sm text-gray-500">
View and edit recipe information
Fill in the details below to add a new recipe
</p>
</div>
<div className="bg-white rounded-lg shadow p-6">
<p className="text-gray-600">
Recipe detail/edit form will be implemented here (next task)
<RecipeForm
onSubmit={handleSubmit}
onCancel={() => navigate('/')}
submitLabel="Create Recipe"
/>
</div>
</div>
);
}
// Recipe not found
if (!recipe) {
return (
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-6">
<h3 className="text-yellow-800 font-semibold mb-2">Recipe Not Found</h3>
<p className="text-yellow-600">The recipe you're looking for doesn't exist.</p>
<Link to="/" className="mt-4 inline-block text-blue-600 hover:text-blue-700">
Back to recipes
</Link>
</div>
);
}
// Edit mode
if (isEditing) {
return (
<div>
<div className="mb-6">
<h2 className="text-2xl font-bold text-gray-900">Edit Recipe</h2>
<p className="mt-1 text-sm text-gray-500">
Update recipe information
</p>
</div>
<div className="bg-white rounded-lg shadow p-6">
<RecipeForm
recipe={recipe}
onSubmit={handleSubmit}
onCancel={() => setIsEditing(false)}
submitLabel="Save Changes"
/>
</div>
</div>
);
}
// View mode
return (
<div>
{/* Header with actions */}
<div className="mb-6 flex items-start justify-between">
<div>
<h2 className="text-3xl font-bold text-gray-900">{recipe.title}</h2>
{recipe.description && (
<p className="mt-2 text-gray-600">{recipe.description}</p>
)}
</div>
<div className="flex gap-2 ml-4">
<button
onClick={() => setIsEditing(true)}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 font-medium"
>
Edit
</button>
<Link
to={`/recipe/${recipe.id}/cook`}
className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 font-medium"
>
Cook Mode
</Link>
{!deleteConfirm ? (
<button
onClick={() => setDeleteConfirm(true)}
className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 font-medium"
>
Delete
</button>
) : (
<div className="flex gap-2">
<button
onClick={handleDelete}
className="px-3 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 text-sm font-medium"
>
Confirm Delete
</button>
<button
onClick={() => setDeleteConfirm(false)}
className="px-3 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 text-sm font-medium"
>
Cancel
</button>
</div>
)}
</div>
</div>
{/* Metadata */}
<div className="grid grid-cols-3 gap-4 mb-6">
{recipe.servings && (
<div className="bg-gray-50 rounded-lg p-4">
<div className="text-sm text-gray-500">Servings</div>
<div className="text-lg font-semibold text-gray-900">{recipe.servings}</div>
</div>
)}
{recipe.prep_time_minutes && (
<div className="bg-gray-50 rounded-lg p-4">
<div className="text-sm text-gray-500">Prep Time</div>
<div className="text-lg font-semibold text-gray-900">{recipe.prep_time_minutes} min</div>
</div>
)}
{recipe.cook_time_minutes && (
<div className="bg-gray-50 rounded-lg p-4">
<div className="text-sm text-gray-500">Cook Time</div>
<div className="text-lg font-semibold text-gray-900">{recipe.cook_time_minutes} min</div>
</div>
)}
</div>
{/* Main content */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Ingredients */}
<div className="bg-white rounded-lg shadow p-6">
<h3 className="text-xl font-bold text-gray-900 mb-4">Ingredients</h3>
<ul className="space-y-2">
{recipe.ingredients.map((ingredient, index) => (
<li key={index} className="flex items-start">
<span className="inline-block w-2 h-2 bg-blue-600 rounded-full mt-2 mr-3 flex-shrink-0"></span>
<span className="text-gray-700">{ingredient}</span>
</li>
))}
</ul>
</div>
{/* Instructions */}
<div className="bg-white rounded-lg shadow p-6">
<h3 className="text-xl font-bold text-gray-900 mb-4">Instructions</h3>
<ol className="space-y-4">
{recipe.instructions.map((instruction, index) => (
<li key={index} className="flex items-start">
<span className="inline-flex items-center justify-center w-6 h-6 bg-blue-600 text-white rounded-full text-sm font-bold mr-3 flex-shrink-0">
{index + 1}
</span>
<span className="text-gray-700 pt-0.5">{instruction}</span>
</li>
))}
</ol>
</div>
</div>
{/* Additional info */}
{(recipe.source_url || recipe.notes) && (
<div className="mt-6 bg-white rounded-lg shadow p-6">
<h3 className="text-xl font-bold text-gray-900 mb-4">Additional Information</h3>
{recipe.source_url && (
<div className="mb-4">
<div className="text-sm font-medium text-gray-700 mb-1">Source</div>
<a
href={recipe.source_url}
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 hover:text-blue-700 underline break-all"
>
{recipe.source_url}
</a>
</div>
)}
{recipe.notes && (
<div>
<div className="text-sm font-medium text-gray-700 mb-1">Notes</div>
<p className="text-gray-700 whitespace-pre-wrap">{recipe.notes}</p>
</div>
)}
</div>
)}
{/* Back button */}
<div className="mt-6">
<Link to="/" className="text-blue-600 hover:text-blue-700 font-medium">
Back to all recipes
</Link>
</div>
</div>
);
}