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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,3 @@
import "../css/Modal.css"
interface ModalProps {
isOpen: boolean;
onClose: () => void;
@ -12,14 +10,14 @@ const Modal = ({ isOpen, onClose, message, confirmAction, cancelAction }: ModalP
if (!isOpen) return null;
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
<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 bg-amber-200 p-12 rounded-md shadow-md" onClick={(e) => e.stopPropagation()}>
<div className="modal-msg">
<span aria-labelledby="message">{message}</span>
</div>
<div className="modal-buttons">
<button 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={confirmAction}>Yes, Delete</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>

View file

@ -1,4 +1,3 @@
import React, { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
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 { useNavigate } from "react-router-dom";
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 { 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() {
const [newRecipeId, setNewRecipeId] = useState<number | null>(null);
const navigate = useNavigate();
const [ingredients, setIngredients] = useState<Ingredient[]>([]);
const [ingredients, setIngredients] = useState<string[]>([]);
const [steps, setSteps] = useState<Step[]>([]);
const [showBulkForm, setShowBulkForm] = useState(true);
const [recipeName, setRecipeName] = useState("");
const [recipeCuisine, setRecipeCuisine] = useState("");
const [author, setAuthor] = useState("");
const [stars, setStars] = useState(0);
const addRecipeForm = async (event: React.FormEvent) => {
event.preventDefault();
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) {
const recipeData = {
name: recipeName,
cuisine: recipeCuisine,
author: author,
stars: stars,
ingredients: ingredients,
steps: stepsHash
}
@ -47,7 +55,7 @@ function AddRecipe() {
<form onSubmit={addRecipeForm} className="add-recipe-form">
<input
type="text"
placeholder="name"
placeholder="recipe name"
className="recipe-name mb-4 p-2 border border-gray-300 rounded w-full"
value={recipeName}
onChange={(e) => setRecipeName(e.target.value)}
@ -59,6 +67,16 @@ function AddRecipe() {
value={recipeCuisine}
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">
submit
</button>
@ -71,50 +89,29 @@ function AddRecipe() {
onChange={(e) => setShowBulkForm(e.target.checked)}
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>
<span className="ml-3 text-amber-800 font-medium">Bulk Entry</span>
</label>
<div>
{showBulkForm ?
<AddBulkIngredients ingredients={ingredients} onChange={setIngredients} /> :
<AddIngredientsForm ingredients={ingredients} onSubmit={setIngredients} />
}
<AddBulkIngredients ingredients={ingredients} onChange={setIngredients} />
</div>
<ul className="mb-4">
{/*<ul className="mb-4">
{ingredients.map((ing, index) => (
<li key={index} className="text-gray-700 flex items-start mb-2">
<span>{`${ing.quantity} ${ing.unit} ${ing.name}`}</span>
<span>{ing}</span>
</li>
))}
</ul>
</ul>*/}
<div>
{showBulkForm ?
<AddBulkSteps steps={steps} onChange={setSteps} /> :
<AddStepsForm steps={steps} onSubmit={setSteps} />
}
<AddBulkSteps steps={steps} onChange={setSteps} />
</div>
<ul className="mb-4">
{/*<ul className="mb-4">
{steps.map((step) => (
<li key={step.idx} className="text-gray-700 flex items-start mb-2">
<span>{`${step.idx}. ${step.instructions}`}</span>
<li key={step.step_number} className="text-gray-700 flex items-start mb-2">
<span>{`${step.step_number}. ${step.instruction}`}</span>
</li>
))}
</ul>
</ul>*/}
</div>
)
}

View file

@ -1,14 +1,13 @@
import { useState, useEffect } from "react";
import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx"
import { getRecipes, deleteRecipe } from "../services/frontendApi.js";
import { type RecipeSmall } from "../types/Recipe.ts"
function AllRecipes() {
const [searchQuery, setSearchQuery] = useState("");
const [recipes, setRecipes] = useState([]);
const [cuisines, setCuisines] = useState([]);
const [recipes, setRecipes] = useState<RecipeSmall[]>([]);
const [cuisines, setCuisines] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);
@ -20,7 +19,9 @@ function AllRecipes() {
const recipes = await getRecipes();
setRecipes(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)
console.log(cuisines)
} 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 { getRecipeById } from "../services/frontendApi.js";
import { type Recipe, type Ingredient } from "../types/Recipe"
import StarRating from "../components/StarRating.tsx"
import { setDBStars } from "../services/frontendApi.js";
function RecipePage() {
const [recipe, setRecipe] = useState<Recipe>({
details: {},
ingredients: [],
steps: {}
steps: []
});
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
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(() => {
const loadRecipe = async () => {
try {
const recipe = await getRecipeById(id);
setRecipe(recipe);
setStars(recipe.details?.stars ?? 0)
setInitialStars(recipe.details?.stars ?? 0);
console.log(recipe)
} catch (error) {
console.log(error);
@ -28,7 +37,21 @@ function RecipePage() {
};
loadRecipe();
}, [id]);
useEffect(() => {
if (initialStars === null || initialStars === stars) {
return;
}
const updateStarsInDB = async () => {
await setDBStars(id, stars);
};
updateStarsInDB();
}, [stars]);
console.log(recipe)
console.log(stars)
console.log(initialStars)
return (
<div className="recipe page-outer">
@ -40,11 +63,11 @@ function RecipePage() {
<div className="recipe-card">
<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>
</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">
<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>
@ -54,7 +77,7 @@ function RecipePage() {
{recipe.ingredients.map((ingredient: Ingredient, index) => (
<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="font-medium">{ingredient.quantity} {ingredient.unit} {ingredient.name}</span>
<span className="font-medium">{ingredient.raw}</span>
</li>
))}
</ul>
@ -69,9 +92,9 @@ function RecipePage() {
{recipe.steps && Object.keys(recipe.steps || {}).map((stepNumber) => (
<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">
{stepNumber}
{recipe.steps[parseInt(stepNumber)].step_number}
</span>
<span className="leading-relaxed">{recipe.steps[parseInt(stepNumber)]}</span>
<span className="leading-relaxed">{recipe.steps[parseInt(stepNumber)].instruction}</span>
</li>
))}
</ol>
@ -80,8 +103,14 @@ function RecipePage() {
<div className="border-t-2 border-amber-300 pt-4">
<div className="flex justify-between items-center text-sm text-amber-600">
<span>From the Kitchen of</span>
<span> </span>
{isWebSource ? (
<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>

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;
};
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) => {
const response = await fetch(`http://localhost:3000/recipe/${id}`);
const data = await response.json();
@ -19,10 +31,23 @@ export const addRecipe = async (recipeData) => {
body: JSON.stringify(recipeData)
});
const data = await response.json();
console.log(data)
console.log(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) => {
console.log(id)
// return

View file

@ -1,22 +1,33 @@
interface Step {
idx: number;
instructions: string;
id: number;
step_number: number;
instruction: string;
}
interface Ingredient {
name: string;
quantity: number;
unit: string;
id?: number;
name?: string;
quantity?: number;
unit?: string;
raw?: string;
}
interface Recipe {
details: {
id?: number;
name?: string;
author?: string;
stars?: number;
cuisine?: string;
},
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 }