recipe author and stars and a bit of cleanup

This commit is contained in:
fred 2025-07-24 12:11:32 -07:00
parent c47dac9986
commit 6f43d17ddd
21 changed files with 361 additions and 207 deletions

1
backend/.gitignore vendored
View file

@ -1 +1,2 @@
node_modules node_modules
scratch

View file

@ -22,17 +22,34 @@ app.get("/recipes", async (req, res) => {
res.status(500).json({ error: err.message }); res.status(500).json({ error: err.message });
} }
}); });
// ### GET ALL RECIPE_INGREDIENTS ###
app.get("/recipe-ingredients", async (req, res) => {
try {
const recipe_ingredients = await db('recipe_ingredients').select('*');
res.json(recipe_ingredients);
} catch (err) {
console.log(err);
res.status(500).json({ error: err.message });
}
});
// ### GET ALL RECIPE_STEPS ###
app.get("/recipe-steps", async (req, res) => {
try {
const recipe_steps = await db('recipe_steps').select('*');
res.json(recipe_steps);
} catch (err) {
console.log(err);
res.status(500).json({ error: err.message });
}
});
// ### GET RECIPE ### // ### GET RECIPE ###
app.get("/recipe/:id", async (req, res) => { app.get("/recipe/:id", async (req, res) => {
const id = req.params.id const id = req.params.id
try { try {
const recipeQuery = db('recipes').where('id', '=', id).select('id', 'name', 'cuisine'); const recipeQuery = db('recipes').where('id', '=', id).select('id', 'name', 'author', 'cuisine', 'stars');
const ingredientsQuery = db.from('recipe_ingredients as ri') const ingredientsQuery = db.from('recipe_ingredients').where('recipe_id', '=', id).select('raw');
.join('ingredients as i', 'ri.ingredient_id', 'i.id')
.where('ri.recipe_id', id)
.select('i.name', 'ri.quantity', 'ri.unit');
const stepsQuery = db('recipe_steps').where('recipe_id', id).select('step_number', 'instruction'); const stepsQuery = db('recipe_steps').where('recipe_id', id).select('step_number', 'instruction');
@ -40,15 +57,8 @@ app.get("/recipe/:id", async (req, res) => {
const result = { const result = {
details: recipe[0], details: recipe[0],
ingredients: ingredients.map(ingredient => ({ ingredients: ingredients,
name: ingredient.name, steps: steps
quantity: ingredient.quantity,
unit: ingredient.unit
})),
steps: steps.reduce((acc, step) => {
acc[step.step_number] = step.instruction;
return acc;
}, {})
}; };
res.json(result); res.json(result);
@ -60,38 +70,22 @@ app.get("/recipe/:id", async (req, res) => {
// ### ADD RECIPE ### // ### ADD RECIPE ###
app.post("/add-recipe", async (req, res) => { app.post("/add-recipe", async (req, res) => {
const { name, cuisine, ingredients, steps } = req.body; const { name, author, cuisine, stars, ingredients, steps } = req.body;
try { try {
const [id] = await db('recipes').insert({ const [id] = await db('recipes').insert({
name: name, name: name,
cuisine: cuisine author: author,
cuisine: cuisine,
stars: stars
}, ['id']) }, ['id'])
const existingIngredients = await db('ingredients').whereIn('name', ingredients.map(ing => ing.name)); const ingredientInserts = ingredients.map(ing => ({
let ingredientData = []; recipe_id: id.id,
for (let ingredient of ingredients) { raw: ing
const existingIngredient = existingIngredients.find(ing => ing.name === ingredient.name);
if (!existingIngredient) {
// create the ingredient if there is no entry
const [newIngredient] = await db('ingredients').insert({
name: ingredient.name
}, ['id']);
ingredientData.push({ id: newIngredient.id, quantity: ingredient.quantity, unit: ingredient.unit });
} else {
// if the ingredient exists use existing entry
ingredientData.push({ id: existingIngredient.id, quantity: ingredient.quantity, unit: ingredient.unit });
}
}
const ingredientInserts = ingredientData.map(ing => ({
ingredient_id: ing.id,
quantity: ing.quantity,
unit: ing.unit,
recipe_id: id.id
})); }));
//
await db('recipe_ingredients').insert(ingredientInserts); await db('recipe_ingredients').insert(ingredientInserts);
// Step 4: Insert steps into recipe_steps
const stepInserts = Object.keys(steps).map(stepNumber => ({ const stepInserts = Object.keys(steps).map(stepNumber => ({
recipe_id: id.id, recipe_id: id.id,
step_number: parseInt(stepNumber), step_number: parseInt(stepNumber),
@ -106,10 +100,26 @@ app.post("/add-recipe", async (req, res) => {
} }
}); });
// ### SET STARS ###
app.post("/set-stars", async (req, res) => {
const { id, stars } = req.body;
try {
await db('recipes')
.where({ id: id })
.update({ stars: stars })
res.status(200).send({ message: "stars updated" })
} catch (err) {
console.log(err);
res.status(500).json({ error: err.message });
}
});
// ### DELETE RECIPE ### // ### DELETE RECIPE ###
app.delete("/delete-recipe", async (req, res) => { app.delete("/delete-recipe", async (req, res) => {
const { id } = req.body; const { id } = req.body;
try { try {
await db('recipe_steps').where({ recipe_id: id }).del();
await db('recipe_ingredients').where({ recipe_id: id }).del();
await db('recipes').where({ id: id }).del(); await db('recipes').where({ id: id }).del();
res.status(200).send({ message: "Recipe deleted" }); res.status(200).send({ message: "Recipe deleted" });
} catch (err) { } catch (err) {

View file

@ -0,0 +1,24 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = function (knex) {
return knex.schema.table('recipe_ingredients', table => {
table.string('raw', 255).defaultTo('');
table.integer('ingredient_id').nullable().alter();
table.string('quantity').nullable().alter();
table.string('unit').nullable().alter();
}).table('recipe_steps', table => {
table.string('instruction', 510).alter();
});
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = function (knex) {
return knex.schema.table('recipe_ingredients', table => {
table.dropColumn('raw');
});
};

View file

@ -0,0 +1,22 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = function (knex) {
return knex.schema.table('recipes', table => {
table.string('author');
table.integer('stars');
})
};
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = function (knex) {
return knex.schema.table('recipes', table => {
table.dropColumn('author');
table.dropColumn('stars')
})
};

View file

@ -3,7 +3,7 @@
@tailwind utilities; @tailwind utilities;
#root { #root {
@apply mx-auto text-center; @apply mx-auto text-center max-w-screen-lg;
} }
.page-outer { .page-outer {

View file

@ -3,6 +3,8 @@ import Index from "./pages/Index.tsx";
import RecipePage from "./pages/RecipePage.tsx"; import RecipePage from "./pages/RecipePage.tsx";
import AddRecipe from "./pages/AddRecipe.tsx"; import AddRecipe from "./pages/AddRecipe.tsx";
import About from "./pages/About.tsx" import About from "./pages/About.tsx"
import RecipeIngredients from "./pages/RecipeIngredients.tsx"
import RecipeSteps from "./pages/RecipeSteps.tsx"
import RecipeBookTabs from "./components/RecipeBookTabs.tsx"; import RecipeBookTabs from "./components/RecipeBookTabs.tsx";
import { Routes, Route } from "react-router-dom"; import { Routes, Route } from "react-router-dom";
@ -17,6 +19,8 @@ function App() {
<Route path="/recipe/:id" element={<RecipePage />} /> <Route path="/recipe/:id" element={<RecipePage />} />
<Route path="/add-recipe" element={<AddRecipe />} /> <Route path="/add-recipe" element={<AddRecipe />} />
<Route path="/about" element={<About />} /> <Route path="/about" element={<About />} />
<Route path="/recipe-ingredients" element={<RecipeIngredients />} />
<Route path="/recipe-steps" element={<RecipeSteps />} />
</Routes> </Routes>
</main> </main>
</div> </div>

View file

@ -1,44 +1,22 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { type Ingredient } from "../types/Recipe";
interface AddBulkIngredientsProps { interface AddBulkIngredientsProps {
ingredients: Ingredient[]; ingredients: string[];
onChange?: (ingredients: Ingredient[]) => void; onChange?: (ingredients: string[]) => void;
} }
const AddBulkIngredients: React.FC<AddBulkIngredientsProps> = ({ ingredients, onChange }) => { const AddBulkIngredients: React.FC<AddBulkIngredientsProps> = ({ ingredients, onChange }) => {
const [textValue, setTextValue] = useState<string>(''); const [textValue, setTextValue] = useState<string>('');
useEffect(() => { useEffect(() => {
const textRepresentation = ingredients.map(ingredient => const textRepresentation = ingredients.join('\n');
`${ingredient.quantity} ${ingredient.unit} ${ingredient.name}`
).join('\n');
setTextValue(textRepresentation); setTextValue(textRepresentation);
}, [ingredients]); }, [ingredients]);
const parseAndUpdate = (value: string) => { const parseAndUpdate = (value: string) => {
const lines = value.split('\n').filter(line => line.trim() !== ''); const lines = value.split('\n').filter(line => line.trim() !== '');
const pattern = /^([0-9/.]+)?\s*(\S+)\s*((\w+\s*)*)$/;
const parsedIngredients = lines.map(line => { if (onChange) onChange(lines);
const parts = line.match(pattern);
let quantity = 0;
if (parts?.[1]) {
const [num, denom] = parts[1].split('/');
if (denom) {
quantity = parseFloat(num) / parseFloat(denom);
} else {
quantity = parseFloat(parts[1]);
}
}
return {
quantity: +quantity.toFixed(2),
unit: parts?.[2]?.trim() || '',
name: parts?.[3]?.trim() || ''
};
});
if (onChange) onChange(parsedIngredients);
}; };
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => { const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {

View file

@ -1,5 +1,9 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { type Step } from "../types/Recipe";
interface Step {
step_number: number;
instruction: string;
}
interface AddBulkStepsProps { interface AddBulkStepsProps {
steps: Step[]; steps: Step[];
@ -11,7 +15,7 @@ const AddBulkSteps: React.FC<AddBulkStepsProps> = ({ steps, onChange }) => {
useEffect(() => { useEffect(() => {
const textRepresentation = steps.map(step => const textRepresentation = steps.map(step =>
`${step.instructions}` `${step.instruction}`
).join('\n'); ).join('\n');
setTextValue(textRepresentation); setTextValue(textRepresentation);
}, [steps]); }, [steps]);
@ -24,8 +28,8 @@ const AddBulkSteps: React.FC<AddBulkStepsProps> = ({ steps, onChange }) => {
const parseAndUpdate = (value: string) => { const parseAndUpdate = (value: string) => {
const lines = value.split('\n').filter(line => line.trim() !== ''); const lines = value.split('\n').filter(line => line.trim() !== '');
const parsedSteps = lines.map((line, idx) => { const parsedSteps: Step[] = lines.map((line, idx) => {
return { idx: idx + 1, instructions: line } return { step_number: idx + 1, instruction: line }
}) })
if (onChange) onChange(parsedSteps); if (onChange) onChange(parsedSteps);

View file

@ -1,17 +1,17 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { type Recipe } from "../types/Recipe" import { type RecipeSmall } from "../types/Recipe"
import Modal from '../components/Modal.tsx' import Modal from '../components/Modal.tsx'
interface CookbookRecipeTileProps { interface CookbookRecipeTileProps {
recipe: Recipe; recipe: RecipeSmall;
handleDelete: (id: number | undefined) => void; handleDelete: (id: number | undefined) => void;
} }
function CookbookRecipeTile({ recipe, handleDelete }: CookbookRecipeTileProps) { function CookbookRecipeTile({ recipe, handleDelete }: CookbookRecipeTileProps) {
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const openModal = () => setIsModalOpen(true); const openModal = () => { setIsModalOpen(true) };
const closeModal = () => setIsModalOpen(false); const closeModal = () => { setIsModalOpen(false) };
const confirmDelete = () => { const confirmDelete = () => {
handleDelete(recipe.id); handleDelete(recipe.id);
closeModal(); closeModal();

View file

@ -1,5 +1,3 @@
import "../css/Modal.css"
interface ModalProps { interface ModalProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
@ -12,14 +10,14 @@ const Modal = ({ isOpen, onClose, message, confirmAction, cancelAction }: ModalP
if (!isOpen) return null; if (!isOpen) return null;
return ( return (
<div className="modal-overlay" onClick={onClose}> <div className="modal-overlay fixed top-0 left-0 w-full h-full bg-black bg-opacity-50 flex justify-center items-center" onClick={onClose}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}> <div className="modal-content bg-amber-200 p-12 rounded-md shadow-md" onClick={(e) => e.stopPropagation()}>
<div className="modal-msg"> <div className="modal-msg">
<span aria-labelledby="message">{message}</span> <span aria-labelledby="message">{message}</span>
</div> </div>
<div className="modal-buttons"> <div className="modal-buttons">
<button onClick={confirmAction}>Yes, Delete</button> <button className="bg-amber-600 rounded-md m-4 pt-1 pb-1 pr-2 pl-2" onClick={confirmAction}>Yes, Delete</button>
<button onClick={cancelAction}>Cancel</button> <button className="bg-amber-600 rounded-md m-4 pt-1 pb-1 pr-2 pl-2" onClick={cancelAction}>Cancel</button>
</div> </div>
</div> </div>
</div> </div>

View file

@ -1,4 +1,3 @@
import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom'; import { Link, useLocation } from 'react-router-dom';
const RecipeBookTabs = () => { const RecipeBookTabs = () => {

View file

@ -0,0 +1,26 @@
interface StarRatingProps {
rating: number;
onRatingChange: (newRating: number) => void;
}
const StarRating = ({ rating, onRatingChange }: StarRatingProps) => {
return (
<div>
{[...Array(5)].map((star, index) => {
index += 1;
return (
<span
key={index}
onClick={() => onRatingChange(index)}
style={{ color: index <= rating ? 'gold' : 'gray', fontSize: '2rem', cursor: 'pointer' }}
>
</span>
);
})}
</div>
);
};
export default StarRating;

View file

@ -1,23 +0,0 @@
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: darkblue;
padding: 50px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.modal-content button {
background: gray;
margin: 1em;
}

View file

@ -1,47 +0,0 @@
.navbar {
background-color: #000000;
padding: 1rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.navbar-brand {
font-size: 1.5rem;
font-weight: bold;
}
.navbar-links {
display: flex;
gap: 2rem;
}
.nav-link {
font-size: 1rem;
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.2s;
}
.nav-link:hover {
background-color: rgba(255, 255, 255, 0.1);
}
@media (max-width: 768px) {
.navbar {
padding: 1rem;
}
.navbar-brand {
font-size: 1.2rem;
}
.navbar-links {
gap: 1rem;
}
.nav-link {
padding: 0.5rem;
}
}

View file

@ -2,29 +2,37 @@ import React, { useState } from 'react';
import { addRecipe } from "../services/frontendApi.js"; import { addRecipe } from "../services/frontendApi.js";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import AddBulkIngredients from "../components/AddBulkIngredients.tsx" import AddBulkIngredients from "../components/AddBulkIngredients.tsx"
import AddIngredientsForm from "../components/AddIngredientsForm.tsx"
import AddStepsForm from "../components/AddStepsForm.tsx"
import AddBulkSteps from "../components/AddBulkSteps.tsx" import AddBulkSteps from "../components/AddBulkSteps.tsx"
import { type Ingredient, type Step } from "../types/Recipe"; import StarRating from "../components/StarRating.tsx"
// import { type Step } from "../types/Recipe";
interface Step {
step_number: number;
instruction: string;
}
function AddRecipe() { function AddRecipe() {
const [newRecipeId, setNewRecipeId] = useState<number | null>(null); const [newRecipeId, setNewRecipeId] = useState<number | null>(null);
const navigate = useNavigate(); const navigate = useNavigate();
const [ingredients, setIngredients] = useState<Ingredient[]>([]); const [ingredients, setIngredients] = useState<string[]>([]);
const [steps, setSteps] = useState<Step[]>([]); const [steps, setSteps] = useState<Step[]>([]);
const [showBulkForm, setShowBulkForm] = useState(true); const [showBulkForm, setShowBulkForm] = useState(true);
const [recipeName, setRecipeName] = useState(""); const [recipeName, setRecipeName] = useState("");
const [recipeCuisine, setRecipeCuisine] = useState(""); const [recipeCuisine, setRecipeCuisine] = useState("");
const [author, setAuthor] = useState("");
const [stars, setStars] = useState(0);
const addRecipeForm = async (event: React.FormEvent) => { const addRecipeForm = async (event: React.FormEvent) => {
event.preventDefault(); event.preventDefault();
const stepsHash = Object.fromEntries( const stepsHash = Object.fromEntries(
steps.map(step => [step.idx, step.instructions]) steps.map(step => [step.step_number, step.instruction])
); );
if (recipeName && recipeCuisine && Object.keys(stepsHash).length > 0 && ingredients.length > 0) { if (recipeName && recipeCuisine && Object.keys(stepsHash).length > 0 && ingredients.length > 0) {
const recipeData = { const recipeData = {
name: recipeName, name: recipeName,
cuisine: recipeCuisine, cuisine: recipeCuisine,
author: author,
stars: stars,
ingredients: ingredients, ingredients: ingredients,
steps: stepsHash steps: stepsHash
} }
@ -47,7 +55,7 @@ function AddRecipe() {
<form onSubmit={addRecipeForm} className="add-recipe-form"> <form onSubmit={addRecipeForm} className="add-recipe-form">
<input <input
type="text" type="text"
placeholder="name" placeholder="recipe name"
className="recipe-name mb-4 p-2 border border-gray-300 rounded w-full" className="recipe-name mb-4 p-2 border border-gray-300 rounded w-full"
value={recipeName} value={recipeName}
onChange={(e) => setRecipeName(e.target.value)} onChange={(e) => setRecipeName(e.target.value)}
@ -59,6 +67,16 @@ function AddRecipe() {
value={recipeCuisine} value={recipeCuisine}
onChange={(e) => setRecipeCuisine(e.target.value)} onChange={(e) => setRecipeCuisine(e.target.value)}
/> />
<input
type="text"
placeholder="author or source"
className="recipe-cusine mb-4 p-2 border border-gray-300 rounded w-full"
value={author}
onChange={(e) => setAuthor(e.target.value)}
/>
<div>
<StarRating rating={stars} onRatingChange={(newRating: number) => setStars(newRating)} />
</div>
<button type="submit" className="ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700"> <button type="submit" className="ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700">
submit submit
</button> </button>
@ -71,50 +89,29 @@ function AddRecipe() {
onChange={(e) => setShowBulkForm(e.target.checked)} onChange={(e) => setShowBulkForm(e.target.checked)}
className="sr-only" className="sr-only"
/> />
<div className={`
w-12 h-6 rounded-full shadow-sm transition-all duration-75 transform
${showBulkForm
? 'bg-amber-300 shadow-lg'
: 'bg-amber-100 hover:bg-amber-200'
}
`}>
<div className={`
absolute top-0.5 left-0.5 w-5 h-5 rounded-full shadow-sm transition-all duration-100 transform
${showBulkForm
? 'translate-x-6 bg-white border-2 border-amber-400'
: 'translate-x-0 bg-white border-2 border-amber-200'
}
`}></div>
</div>
</div> </div>
<span className="ml-3 text-amber-800 font-medium">Bulk Entry</span> <span className="ml-3 text-amber-800 font-medium">Bulk Entry</span>
</label> </label>
<div> <div>
{showBulkForm ? <AddBulkIngredients ingredients={ingredients} onChange={setIngredients} />
<AddBulkIngredients ingredients={ingredients} onChange={setIngredients} /> :
<AddIngredientsForm ingredients={ingredients} onSubmit={setIngredients} />
}
</div> </div>
<ul className="mb-4"> {/*<ul className="mb-4">
{ingredients.map((ing, index) => ( {ingredients.map((ing, index) => (
<li key={index} className="text-gray-700 flex items-start mb-2"> <li key={index} className="text-gray-700 flex items-start mb-2">
<span>{`${ing.quantity} ${ing.unit} ${ing.name}`}</span> <span>{ing}</span>
</li> </li>
))} ))}
</ul> </ul>*/}
<div> <div>
{showBulkForm ? <AddBulkSteps steps={steps} onChange={setSteps} />
<AddBulkSteps steps={steps} onChange={setSteps} /> :
<AddStepsForm steps={steps} onSubmit={setSteps} />
}
</div> </div>
<ul className="mb-4"> {/*<ul className="mb-4">
{steps.map((step) => ( {steps.map((step) => (
<li key={step.idx} className="text-gray-700 flex items-start mb-2"> <li key={step.step_number} className="text-gray-700 flex items-start mb-2">
<span>{`${step.idx}. ${step.instructions}`}</span> <span>{`${step.step_number}. ${step.instruction}`}</span>
</li> </li>
))} ))}
</ul> </ul>*/}
</div> </div>
) )
} }

View file

@ -1,14 +1,13 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx" import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx"
import { getRecipes, deleteRecipe } from "../services/frontendApi.js"; import { getRecipes, deleteRecipe } from "../services/frontendApi.js";
import { type RecipeSmall } from "../types/Recipe.ts"
function AllRecipes() { function AllRecipes() {
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [recipes, setRecipes] = useState([]); const [recipes, setRecipes] = useState<RecipeSmall[]>([]);
const [cuisines, setCuisines] = useState([]); const [cuisines, setCuisines] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true); const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);
@ -20,7 +19,9 @@ function AllRecipes() {
const recipes = await getRecipes(); const recipes = await getRecipes();
setRecipes(recipes); setRecipes(recipes);
console.log(recipes) console.log(recipes)
const uniqueCuisines: [] = Array.from(new Set(recipes.map(recipe => recipe.cuisine))) const uniqueCuisines: string[] = recipes.length > 0
? Array.from(new Set(recipes.map((recipe: RecipeSmall) => recipe.cuisine)))
: [];
setCuisines(uniqueCuisines) setCuisines(uniqueCuisines)
console.log(cuisines) console.log(cuisines)
} catch (error) { } catch (error) {

View file

@ -0,0 +1,48 @@
import { getRecipeIngredients } from "../services/frontendApi.js";
import { useState, useEffect } from "react";
import { type Ingredient } from "../types/Recipe.ts"
function RecipeIngredients() {
const [recipeIngredients, setRecipeIngredients] = useState<Ingredient[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadRecipeIngredients = async () => {
try {
const recipeIngredients = await getRecipeIngredients();
setRecipeIngredients(recipeIngredients);
console.log(recipeIngredients)
} catch (err) {
console.log(err);
setError("Failed to load recipe ingredients...");
console.log(error)
} finally {
setLoading(false);
}
};
loadRecipeIngredients();
}, []);
console.log(recipeIngredients)
return (
// should this be a string[]? only if we are only returning raw. otherwise i will need to type and return the ingredient object. This template shoudl work for steps though, so maybe setting that up is a good first step
<div className='page-outer'>
{loading ? (
<div className="loading">Loading...</div>
) : (
<div className="recipe-outer bg-amber-100 p-4 md:p-8 lg:p-12">
<div className="recipes-grid grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-8">
{recipeIngredients.map(ing => (
<li key={ing.id}>
{ing.raw}
</li>
))}
</div>
</div>
)}
</div>
)
}
export default RecipeIngredients

View file

@ -2,22 +2,31 @@ import { useParams } from "react-router-dom";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { getRecipeById } from "../services/frontendApi.js"; import { getRecipeById } from "../services/frontendApi.js";
import { type Recipe, type Ingredient } from "../types/Recipe" import { type Recipe, type Ingredient } from "../types/Recipe"
import StarRating from "../components/StarRating.tsx"
import { setDBStars } from "../services/frontendApi.js";
function RecipePage() { function RecipePage() {
const [recipe, setRecipe] = useState<Recipe>({ const [recipe, setRecipe] = useState<Recipe>({
details: {}, details: {},
ingredients: [], ingredients: [],
steps: {} steps: []
}); });
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const { id } = useParams(); const { id } = useParams();
const isWebSource = recipe && recipe.details && recipe.details.author
? /http|com/.test(recipe.details.author) //etc
: false;
const [stars, setStars] = useState<number>(0);
const [initialStars, setInitialStars] = useState<number | null>(null);
useEffect(() => { useEffect(() => {
const loadRecipe = async () => { const loadRecipe = async () => {
try { try {
const recipe = await getRecipeById(id); const recipe = await getRecipeById(id);
setRecipe(recipe); setRecipe(recipe);
setStars(recipe.details?.stars ?? 0)
setInitialStars(recipe.details?.stars ?? 0);
console.log(recipe) console.log(recipe)
} catch (error) { } catch (error) {
console.log(error); console.log(error);
@ -28,7 +37,21 @@ function RecipePage() {
}; };
loadRecipe(); loadRecipe();
}, [id]); }, [id]);
useEffect(() => {
if (initialStars === null || initialStars === stars) {
return;
}
const updateStarsInDB = async () => {
await setDBStars(id, stars);
};
updateStarsInDB();
}, [stars]);
console.log(recipe) console.log(recipe)
console.log(stars)
console.log(initialStars)
return ( return (
<div className="recipe page-outer"> <div className="recipe page-outer">
@ -40,11 +63,11 @@ function RecipePage() {
<div className="recipe-card"> <div className="recipe-card">
<div className="border-b-2 border-amber-300 pb-4 mb-6"> <div className="border-b-2 border-amber-300 pb-4 mb-6">
<h3 className="text-2xl md:text-3xl font-bold text-amber-900 mb-2">{recipe.details.name}</h3> <h3 className="text-2xl lg:text-3xl font-bold text-amber-900 mb-2">{recipe.details.name}</h3>
<p className="text-amber-700 italic text-lg">{recipe.details.cuisine}</p> <p className="text-amber-700 italic text-lg">{recipe.details.cuisine}</p>
</div> </div>
<div className="grid md:grid-cols-2 gap-6 mb-6"> <div className="grid lg:grid-cols-2 gap-6 mb-6">
<div className="bg-white rounded-lg p-4 shadow-sm border border-amber-100"> <div className="bg-white rounded-lg p-4 shadow-sm border border-amber-100">
<h4 className="text-xl font-semibold text-amber-800 mb-3 flex items-center"> <h4 className="text-xl font-semibold text-amber-800 mb-3 flex items-center">
<span className="w-2 h-2 bg-amber-500 rounded-full mr-2"></span> <span className="w-2 h-2 bg-amber-500 rounded-full mr-2"></span>
@ -54,7 +77,7 @@ function RecipePage() {
{recipe.ingredients.map((ingredient: Ingredient, index) => ( {recipe.ingredients.map((ingredient: Ingredient, index) => (
<li key={index} className="text-gray-700 flex items-start"> <li key={index} className="text-gray-700 flex items-start">
<span className="w-1.5 h-1.5 bg-amber-400 rounded-full mt-2 mr-3 flex-shrink-0"></span> <span className="w-1.5 h-1.5 bg-amber-400 rounded-full mt-2 mr-3 flex-shrink-0"></span>
<span className="font-medium">{ingredient.quantity} {ingredient.unit} {ingredient.name}</span> <span className="font-medium">{ingredient.raw}</span>
</li> </li>
))} ))}
</ul> </ul>
@ -69,9 +92,9 @@ function RecipePage() {
{recipe.steps && Object.keys(recipe.steps || {}).map((stepNumber) => ( {recipe.steps && Object.keys(recipe.steps || {}).map((stepNumber) => (
<li key={stepNumber} className="text-gray-700 flex items-start"> <li key={stepNumber} className="text-gray-700 flex items-start">
<span className="bg-amber-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-3 mt-0.5 flex-shrink-0"> <span className="bg-amber-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-3 mt-0.5 flex-shrink-0">
{stepNumber} {recipe.steps[parseInt(stepNumber)].step_number}
</span> </span>
<span className="leading-relaxed">{recipe.steps[parseInt(stepNumber)]}</span> <span className="leading-relaxed">{recipe.steps[parseInt(stepNumber)].instruction}</span>
</li> </li>
))} ))}
</ol> </ol>
@ -80,8 +103,14 @@ function RecipePage() {
<div className="border-t-2 border-amber-300 pt-4"> <div className="border-t-2 border-amber-300 pt-4">
<div className="flex justify-between items-center text-sm text-amber-600"> <div className="flex justify-between items-center text-sm text-amber-600">
<span>From the Kitchen of</span> {isWebSource ? (
<span> </span> <span>Source: {recipe.details.author}</span>
) : (
<span>From the kitchen of {recipe.details.author}</span>
)}
<span>
<StarRating rating={stars} onRatingChange={(newRating: number) => setStars(newRating)} />
</span>
</div> </div>
</div> </div>
</div> </div>

View file

@ -0,0 +1,47 @@
import { getRecipeSteps } from "../services/frontendApi.js";
import { useState, useEffect } from "react";
import { type Step } from "../types/Recipe.ts"
function RecipeSteps() {
const [recipeSteps, setRecipeSteps] = useState<Step[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadRecipeSteps = async () => {
try {
const recipeSteps = await getRecipeSteps();
setRecipeSteps(recipeSteps);
console.log(recipeSteps)
} catch (err) {
console.log(err);
setError("Failed to load recipe ingredients...");
console.log(error)
} finally {
setLoading(false);
}
};
loadRecipeSteps();
}, []);
console.log(recipeSteps)
return (
<div className='page-outer'>
{loading ? (
<div className="loading">Loading...</div>
) : (
<div className="recipe-outer bg-amber-100 p-4 md:p-8 lg:p-12">
<div className="recipes-grid grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-8">
{recipeSteps.map(step => (
<li key={step.id}>
{step.instruction}
</li>
))}
</div>
</div>
)}
</div>
)
}
export default RecipeSteps

View file

@ -4,6 +4,18 @@ export const getRecipes = async () => {
return data; return data;
}; };
export const getRecipeSteps = async () => {
const response = await fetch("http://localhost:3000/recipe-steps");
const data = await response.json();
return data;
};
export const getRecipeIngredients = async () => {
const response = await fetch("http://localhost:3000/recipe-ingredients");
const data = await response.json();
return data;
};
export const getRecipeById = async (id) => { export const getRecipeById = async (id) => {
const response = await fetch(`http://localhost:3000/recipe/${id}`); const response = await fetch(`http://localhost:3000/recipe/${id}`);
const data = await response.json(); const data = await response.json();
@ -19,10 +31,23 @@ export const addRecipe = async (recipeData) => {
body: JSON.stringify(recipeData) body: JSON.stringify(recipeData)
}); });
const data = await response.json(); const data = await response.json();
console.log(data) console.log(data);
return data; return data;
}; };
export const setDBStars = async (id, stars) => {
console.log(JSON.stringify({ id: id, stars: stars }))
// return
const response = await fetch("http://localhost:3000/set-stars", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: id, stars: stars })
});
const data = await response.json();
console.log(data);
return data;
}
export const deleteRecipe = async (id) => { export const deleteRecipe = async (id) => {
console.log(id) console.log(id)
// return // return

View file

@ -1,22 +1,33 @@
interface Step { interface Step {
idx: number; id: number;
instructions: string; step_number: number;
instruction: string;
} }
interface Ingredient { interface Ingredient {
name: string; id?: number;
quantity: number; name?: string;
unit: string; quantity?: number;
unit?: string;
raw?: string;
} }
interface Recipe { interface Recipe {
details: { details: {
id?: number; id?: number;
name?: string; name?: string;
author?: string;
stars?: number;
cuisine?: string; cuisine?: string;
}, },
ingredients: Ingredient[], ingredients: Ingredient[],
steps?: Step[]; steps: Step[];
}
// smaller Recipe type returned by backend at /recipes for all
interface RecipeSmall {
id: number;
name: string;
cuisine: string;
} }
export type { Recipe, Ingredient, Step } export type { Recipe, Ingredient, Step, RecipeSmall }