Compare commits

..

10 commits

Author SHA1 Message Date
fred
9656888cb7 prep/cook times and some fit and finish 2025-07-29 09:34:33 -07:00
fred
a3b0fffe45 switch in .env for dev/prod 2025-07-25 16:00:55 -07:00
773b4773eb initial production commit 2025-07-25 18:07:20 +00:00
fred
6f43d17ddd recipe author and stars and a bit of cleanup 2025-07-24 12:11:32 -07:00
fred
c47dac9986 revert cors for now 2025-07-17 10:07:36 -07:00
fred
6ad2d6d7d3 tidy up 2025-07-17 09:17:10 -07:00
fred
3510cf28a9 remove cors 2025-07-15 12:04:09 -07:00
fred
091a21c8e6 dockerize app 2025-07-15 12:02:11 -07:00
fred
af99a9b4c2 search recipes page 2025-07-15 09:23:16 -07:00
fred
f3f5f232e6 styling 2025-07-11 17:06:41 -07:00
43 changed files with 1939 additions and 491 deletions

1
.gitignore vendored
View file

@ -1,4 +1,5 @@
examp_frontend/
postgres/db
*/.env
.env
todo

1
backend/.gitignore vendored
View file

@ -1 +1,2 @@
node_modules
scratch

14
backend/Dockerfile Normal file
View file

@ -0,0 +1,14 @@
FROM node:22
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
# CMD ["npm", "run", "dev"]
CMD npm run $NODE_ENV

View file

@ -1,51 +1,75 @@
const express = require("express");
const db = require("./db");
const port = 6063;
const cors = require('cors'); // to remove cors origin error in dev TODO: remove when dockerized
const port = 3000;
const cors = require("cors");
const app = express();
app.use(cors()); // to remove cors origin error in dev TODO: remove when dockerized
app.use(cors());
app.use(express.json());
// ####### ROUTES #######
app.get("/backend/test", async (req, res) => {
console.log("test");
res.json({ test: "test" });
});
// ### GET ALL RECIPES ###
app.get("/recipes", async (req, res) => {
app.get("/backend/recipes", async (req, res) => {
try {
const recipes = await db('recipes').select('id', 'name');
const recipes = await db("recipes").select("id", "name", "cuisine");
res.json(recipes);
} catch (err) {
console.log(err);
res.status(500).json({ error: err.message });
}
});
// ### GET ALL RECIPE_INGREDIENTS ###
app.get("/backend/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("/backend/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 ###
app.get("/recipe/:id", async (req, res) => {
const id = req.params.id
app.get("/backend/recipe/:id", async (req, res) => {
const id = req.params.id;
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", "prep_minutes", "cook_minutes");
const ingredientsQuery = db.from('recipe_ingredients as ri')
.join('ingredients as i', 'ri.ingredient_id', 'i.id')
.where('ri.recipe_id', id)
.select('i.name', 'ri.quantity', 'ri.unit');
const ingredientsQuery = db
.from("recipe_ingredients")
.where("recipe_id", "=", id)
.select("raw");
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");
const [recipe, ingredients, steps] = await Promise.all([recipeQuery, ingredientsQuery, stepsQuery]);
const [recipe, ingredients, steps] = await Promise.all([
recipeQuery,
ingredientsQuery,
stepsQuery,
]);
const result = {
details: recipe[0],
ingredients: ingredients.map(ingredient => ({
name: ingredient.name,
quantity: ingredient.quantity,
unit: ingredient.unit
})),
steps: steps.reduce((acc, step) => {
acc[step.step_number] = step.instruction;
return acc;
}, {})
ingredients: ingredients,
steps: steps,
};
res.json(result);
@ -56,45 +80,34 @@ app.get("/recipe/:id", async (req, res) => {
});
// ### ADD RECIPE ###
app.post("/add-recipe", async (req, res) => {
const { name, cuisine, ingredients, steps } = req.body;
app.post("/backend/add-recipe", async (req, res) => {
const { name, author, cuisine, stars, ingredients, steps, prep_minutes, cook_minutes } = req.body;
try {
const [id] = await db('recipes').insert({
const [id] = await db("recipes").insert(
{
name: name,
cuisine: cuisine
}, ['id'])
author: author,
cuisine: cuisine,
prep_minutes: prep_minutes,
cook_minutes: cook_minutes,
stars: stars,
},
["id"],
);
const existingIngredients = await db('ingredients').whereIn('name', ingredients.map(ing => ing.name));
let ingredientData = [];
for (let ingredient of ingredients) {
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
const ingredientInserts = ingredients.map((ing) => ({
recipe_id: id.id,
raw: ing,
}));
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,
step_number: parseInt(stepNumber),
instruction: steps[stepNumber]
instruction: steps[stepNumber],
}));
await db('recipe_steps').insert(stepInserts);
await db("recipe_steps").insert(stepInserts);
res.status(200).send({ message: "Recipe added", id: id.id });
} catch (err) {
@ -103,11 +116,25 @@ app.post("/add-recipe", async (req, res) => {
}
});
// ### SET STARS ###
app.post("/backend/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 ###
app.delete("/delete-recipe", async (req, res) => {
app.delete("/backend/delete-recipe", async (req, res) => {
const { id } = req.body;
try {
await db('recipes').where({ id: id }).del();
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();
res.status(200).send({ message: "Recipe deleted" });
} catch (err) {
console.log(err);
@ -117,8 +144,8 @@ app.delete("/delete-recipe", async (req, res) => {
app.listen(port, () => console.log(`Server has started on port: ${port}`));
process.on('SIGINT', async () => {
console.log('Closing database connection...');
process.on("SIGINT", async () => {
console.log("Closing database connection...");
await db.destroy();
process.exit(0);
});

View file

@ -1,7 +1,7 @@
const knex = require('knex');
const knexConfig = require('./knexfile.js');
const environment = process.env.NODE_ENV || 'development';
const environment = process.env.NODE_ENV || 'dev';
const config = knexConfig[environment];
const db = knex(config);

View file

@ -1,40 +1,41 @@
require('dotenv').config();
require("dotenv").config();
module.exports = {
development: {
client: 'postgresql',
dev: {
client: "postgresql",
connection: {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
host: "db",
port: 5432,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
password: process.env.DB_PASSWORD,
},
pool: {
min: 2,
max: 10
max: 10,
},
migrations: {
tableName: 'knex_migrations',
directory: './migrations'
}
tableName: "knex_migrations",
directory: "./migrations",
},
},
production: {
client: 'postgresql',
client: "postgresql",
connection: {
database: 'my_db',
user: 'username',
password: 'password'
host: "db",
port: process.env.DB_PORT,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
},
pool: {
min: 2,
max: 10
max: 10,
},
migrations: {
tableName: 'knex_migrations'
}
}
tableName: "knex_migrations",
directory: "./migrations",
},
},
};

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

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

View file

@ -4,7 +4,8 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "node backendServer.js"
"dev": "node backendServer.js",
"production": "node backendServer.js"
},
"keywords": [],
"author": "",

44
docker-compose.yaml Normal file
View file

@ -0,0 +1,44 @@
services:
db:
container_name: recipes_postgres
image: docker.io/library/postgres:17
# restart: always
env_file:
- .env
environment:
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_DB=${DB_NAME}
ports:
- "${DB_PORT}:5432"
volumes:
- ./postgres/db:/var/lib/postgresql/data
backend:
image: recipes_backend
container_name: recipes_backend
build:
context: ./backend
args:
NODE_ENV: ${NODE_ENV}
ports:
- "3000:3000"
volumes:
- ./backend:/usr/src/app
environment:
- NODE_ENV=${NODE_ENV}
- DB_USER=${DB_USER}
- DB_PASSWORD=${DB_PASSWORD}
- DB_NAME=${DB_NAME}
frontend:
image: recipes_frontend
container_name: recipes_frontend
build:
context: ./backend
args:
NODE_ENV: ${NODE_ENV}
ports:
- "8081:80"
volumes:
- ./frontend:/usr/src/app
environment:
- NODE_ENV=${NODE_ENV}

14
frontend/Dockerfile Normal file
View file

@ -0,0 +1,14 @@
FROM node:22
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 80
# CMD ["npm", "run", "$NODE_ENV"]
CMD npm run $NODE_ENV

View file

@ -2,9 +2,9 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dev Recipe App</title>
<title>Recipe App</title>
</head>
<body>
<div id="root"></div>

File diff suppressed because it is too large Load diff

View file

@ -4,12 +4,14 @@
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite --host 0.0.0.0 --port 80",
"production": "vite --host 0.0.0.0 --port 80",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"autoprefixer": "^10.4.21",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.3"
@ -23,6 +25,7 @@
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"globals": "^16.2.0",
"tailwindcss": "^3.4.17",
"typescript": "~5.8.3",
"typescript-eslint": "^8.34.1",
"vite": "^7.0.0"

View file

@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

1
frontend/public/icon.svg Normal file
View file

@ -0,0 +1 @@
<svg width="800px" height="800px" viewBox="0 0 128 128" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--noto" preserveAspectRatio="xMidYMid meet"><path d="M5.01 52.21c-1.14 2.55-2.24 27.27 12.35 44.04c10.89 12.51 25.62 17.63 45.02 18.36s38.13-5.78 47.13-16.09c16.25-18.63 14.55-41.06 13.7-44.4c-2.15-8.46-19.07-14.44-58.56-14.44c-36.72.02-56.72 6-59.64 12.53z" fill="#6bb8fe"></path><path d="M93.71 49.99c.41-.1 8.04.74 8.19.64s3.37-7.58 3.37-7.58s-2.87-.6-4.25-.86c-1.38-.24-7.31 7.8-7.31 7.8z" fill="#1d89fe"></path><path d="M33.39 100.91c-1.57 1.89-10.9-3.51-17.11-16.13c-5.44-11.05-5.3-17.05-4.28-18c1.34-1.25 5.26-.09 6.15 2.76c1.2 3.84 1.16 8.29 5.35 16.49c6.37 12.47 11.23 13.27 9.89 14.88z" fill="#e0ebf6"></path><path d="M12.27 54.07c.56 6.06 20.79 9.72 52.79 10.26c32 .54 52.25-3.92 52.25-9.59s-21.2-9.72-50.9-9.99s-54.68 3.52-54.14 9.32z" fill="#1d89fe"></path><path d="M96.29 62.95l6.93-15.18l-8.85-1.32l-11.22 1.73l-7.41 16.08s7.41-.11 11.82-.44c4.41-.34 8.73-.87 8.73-.87z" fill="#025abc"></path><path d="M82.64 64.11S98 47.63 106.71 38.61s16.4-15.86 16.55-18.52c.19-3.42-6.34-4.91-6.34-4.91L75.74 60.97l-1.09 3.27s2.96.08 4.43 0c1.49-.08 3.56-.13 3.56-.13z" fill="#9d9c9c"></path><path d="M116.78 15.12s4.79 1.05 4.58 2.87c-.27 2.36-2.18 4.35-4.52 6.76S79.08 64.23 79.08 64.23l-3.37.1l-.4-1.72l41.47-47.49z" fill="#e0e0e0"></path><path d="M68.18 64.36S80.91 48.5 92.04 35.27s16.53-20.44 18.09-20.91s9.33.99 9.61 1.98c.4 1.38-.12 2.77-4.17 6.97c-4.05 4.2-39.07 41-39.07 41s-1.81.06-3.58.07s-4.74-.02-4.74-.02z" fill="#c8c8c8"></path><path d="M110.57 16.88c-2.3.83-9.94 9.08-7.93 9.94c1.62.7 6.58-4.72 9.22-6.22c2.64-1.5 4.22-.79 4.5-2c.29-1.22-3.43-2.58-5.79-1.72z" fill="#ffffff"></path></svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

View file

@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View file

@ -1,42 +1,11 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
@apply mx-auto text-center max-w-screen-lg w-full;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
.page-outer {
@apply bg-amber-100 border border-amber-200 rounded-bl-lg rounded-br-lg p-6 md:p-8 lg:p-10 max-w-6xl mx-auto font-serif;
}

View file

@ -1,22 +1,29 @@
import "./App.css";
import Cookbook from "./pages/Cookbook.tsx";
import Index from "./pages/Index.tsx";
import RecipePage from "./pages/RecipePage.tsx";
import AddRecipe from "./pages/AddRecipe.tsx";
import NavBar from "./components/NavBar.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";
function App() {
return (
<>
<NavBar />
<main className="main-content">
<div className="min-h-screen flex flex-col">
<RecipeBookTabs />
<main className="flex-1 overflow-auto">
<Routes>
<Route path="/" element={<Cookbook />} />
<Route path="/" element={<Index />} />
<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>
);
}
export default App;

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>) => {
@ -57,15 +35,15 @@ const AddBulkIngredients: React.FC<AddBulkIngredientsProps> = ({ ingredients, on
return (
<div>
<p>Please enter ingredients: Quantity, Unit, Name</p>
<p>Please enter each ingredient on a new line:</p>
<textarea
rows={4}
cols={50}
rows={8}
value={textValue}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
placeholder="Enter ingredients separated by newline..."
className="mb-4 p-2 border border-gray-300 rounded w-full"
/>
</div>
);

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);
@ -43,15 +47,15 @@ const AddBulkSteps: React.FC<AddBulkStepsProps> = ({ steps, onChange }) => {
return (
<div>
<p>Please enter each step on a new line</p>
<p>Please enter each step on a new line:</p>
<textarea
rows={4}
cols={50}
rows={8}
value={textValue}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
placeholder="Enter ingredients separated by newline..."
placeholder="Enter steps separated by newline..."
className="mb-4 p-2 border border-gray-300 rounded w-full"
/>
</div>
);

View file

@ -1,17 +1,18 @@
import React, { useState } from 'react';
import { type Recipe } from "../types/Recipe"
import { type RecipeSmall } from "../types/Recipe"
import Modal from '../components/Modal.tsx'
import { Link } from 'react-router-dom';
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();
@ -19,12 +20,15 @@ function CookbookRecipeTile({ recipe, handleDelete }: CookbookRecipeTileProps) {
return (
<div className="recipe-card">
<div className="recipe-info">
<h3><a href={`/recipe/${recipe.id}`}>{recipe.name}</a></h3>
<button onClick={openModal}>Delete Recipe</button>
<div className="recipe-card m-2 bg-amber-300 p-4 rounded shadow">
<div className="flex justify-between items-center recipe-name">
<h3 className="font-bold"><Link to={`/recipe/${recipe.id}`} className="text-blue-500">{recipe.name}</Link></h3>
<button onClick={openModal} className="text-red-500 focus:outline-none">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="w-6 h-6">
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<Modal
isOpen={isModalOpen}
onClose={closeModal}
@ -34,6 +38,6 @@ function CookbookRecipeTile({ recipe, handleDelete }: CookbookRecipeTileProps) {
/>
</div>
);
}
};
export default CookbookRecipeTile;

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,19 +0,0 @@
import { Link } from "react-router-dom";
import "../css/Navbar.css";
function NavBar() {
return (
<nav className="navbar">
<div className="navbar-links">
<Link to="/" className="nav-link">
Cookbook
</Link>
<Link to="/add-recipe" className="nav-link">
Add Recipe
</Link>
</div>
</nav>
);
}
export default NavBar;

View file

@ -0,0 +1,95 @@
import React from 'react';
import { useState, useEffect } from "react";
import { Link, useLocation } from 'react-router-dom';
import { getRecipes } from "../services/frontendApi.js";
const RecipeBookTabs = () => {
const location = useLocation();
const [lastViewedRecipeId, setLastViewedRecipeId] = useState<number | null>(null);
const loadRandomRecipeId = async () => {
try {
const recipes = await getRecipes();
if (recipes.length > 0) {
const randomIndex = Math.floor(Math.random() * recipes.length);
setLastViewedRecipeId(recipes[randomIndex].id);
}
} catch (error) {
console.error('Error loading recipes:', error);
}
};
// update lastViewedRecipe id if we navigate to /recipe/${id}
useEffect(() => {
const match = /^\/recipe\/(\d+)$/.exec(location.pathname);
if (match) {
setLastViewedRecipeId(parseInt(match[1]));
}
}, [location.pathname, lastViewedRecipeId]);
// choose random recipe on first load
useEffect(() => {
if (!lastViewedRecipeId) {
loadRandomRecipeId();
} else {
console.log('id found', lastViewedRecipeId)
}
}, []);
const tabs = [
{ id: '/', label: 'All Recipes', icon: '📚' },
{ id: `/recipe/${lastViewedRecipeId}`, label: 'Recipe', icon: '🥗' },
{ id: '/add-recipe', label: 'Add Recipe', icon: '' },
{ id: '/about', label: 'About', icon: '🍽️' },
];
return (
<div className="bg-amber-50 h-16 flex-shrink-0 rounded-tl-lg rounded-tr-lg">
<div className="relative h-full">
<div className="absolute bottom-0 left-0 right-0 h-0.5 bg-amber-200"></div>
<div className="flex space-x-1 px-6 pt-4 h-full items-end justify-center">
{tabs.map((tab) => {
const isActive = location.pathname === tab.id || (location.pathname.startsWith(tab.id) && tab.id === "/recipe/");
return (
<Link
key={tab.id}
to={tab.id}
className={`
relative px-6 py-3 rounded-t-lg font-medium text-sm transform
${isActive
? 'bg-amber-100 text-amber-800 scale-105 z-10 border-t-2 border-amber-200'
: 'bg-amber-200 text-amber-600 hover:bg-amber-100 hover:text-amber-700 hover:scale-102 shadow-sm'
}
before:absolute before:bottom-0 before:left-0 before:right-0 before:h-0.5
${isActive ? '' : ''}
`}
>
<div className="flex items-center space-x-2">
<span className="text-lg">{tab.icon}</span>
<span>{tab.label}</span>
</div>
{isActive && (
<>
<div className={`absolute -left-2 bottom-0 w-2 h-2 bg-white ${location.pathname === '/' ? 'hidden' : ''}`}>
<div className="absolute top-0 left-0 w-2 h-2 bg-amber-200 rounded-br-lg"></div>
</div>
<div className={`absolute -right-2 bottom-0 w-2 h-2 bg-white ${location.pathname === '/about' ? 'hidden' : ''}`}>
<div className="absolute top-0 right-0 w-2 h-2 bg-amber-200 rounded-bl-lg"></div>
</div>
</>
)}
</Link>
);
})}
</div>
</div>
</div>
);
};
export default RecipeBookTabs;

View file

@ -1,26 +0,0 @@
import { type Recipe, type Ingredient } from "../types/Recipe"
function RecipeCard({ recipe }: { recipe: Recipe }) {
return (
<div className="recipe-card">
<div className="recipe-info">
<h3>{recipe.details.name}</h3>
<p>{recipe.details.cuisine}</p>
<h4>Ingredients:</h4>
<ul>
{recipe.ingredients.map((ingredient: Ingredient, index) => (
<li key={index}>{ingredient.quantity} {ingredient.unit} {ingredient.name}</li>
))}
</ul>
<h4>Steps:</h4>
<ol>
{recipe.steps && Object.keys(recipe.steps || {}).map((stepNumber) => (
<li key={stepNumber}>{recipe.steps?.[parseInt(stepNumber)]}</li>
))}
</ol>
</div>
</div>
);
}
export default RecipeCard;

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

@ -1,10 +1,10 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
/* font-family: system-ui, Avenir, Helvetica, Arial, sans-serif; */
/* line-height: 1.5; */
/* font-weight: 400; */
/**/
/* color-scheme: light dark; */
/* color: rgba(255, 255, 255, 0.87); */
background-color: #242424;
font-synthesis: none;
@ -13,15 +13,6 @@
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
@ -29,40 +20,3 @@ body {
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View file

@ -0,0 +1,25 @@
function About() {
return (
<div className="about page-outer">
<div>
<h2 className="text-xl">Hi,</h2>
<h2 className="text-xl">I am Fred.</h2>
<h2 className="text-xl">I made this app using the following components:</h2>
<h2 className="mt-4 font-bold text-xl">Frontend:</h2>
<ul><li>React</li><li>TypeScript</li><li>Vite</li></ul>
<h2 className="mt-4 font-bold text-xl">Backend:</h2>
<ul><li>Node.js & Express</li><li>PostgreSQL</li></ul>
<h2 className="mt-4 font-bold text-xl">Containerization:</h2>
<ul><li>Docker</li></ul>
<h2 className="mt-4 font-bold text-xl">Styling/UI:</h2>
<ul><li>Tailwind CSS</li></ul>
<p className="mt-4">More about me <a className="text-blue-600" target="_blank" href="https://fredzernia.com">here</a> |
Code for this app <a className="text-blue-600" target="_blank" href="https://forgejo.fredzernia.com/fred/recipe_app">here</a></p>
</div>
</div >
)
}
export default About

View file

@ -2,29 +2,41 @@ 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 [prepMinutes, setPrepMinutes] = useState(5);
const [cookMinutes, setCookMinutes] = useState(5);
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,
prep_minutes: prepMinutes,
cook_minutes: cookMinutes,
stars: stars,
ingredients: ingredients,
steps: stepsHash
}
@ -43,58 +55,90 @@ function AddRecipe() {
}, [newRecipeId, navigate]);
return (
<div className="add-recipe-outer">
<div className="add-recipe-card page-outer">
<form onSubmit={addRecipeForm} className="add-recipe-form">
<input
type="text"
placeholder="name"
className="recipe-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)}
/>
<input
type="text"
placeholder="cuisine"
className="recipe-cusine"
className="recipe-cusine mb-4 p-2 border border-gray-300 rounded w-full"
value={recipeCuisine}
onChange={(e) => setRecipeCuisine(e.target.value)}
/>
<button type="submit" className="ar-button">
submit
</button>
</form>
<label>
<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 className="flex items-center justify-between mb-4">
<div>
<label htmlFor="prepTime" className="mr-2 font-bold">Prep Time:</label>
<input
type="number"
placeholder="prep time in minutes"
className="recipe-cusine p-2 border border-gray-300 rounded w-24"
value={prepMinutes}
onChange={(e) => setPrepMinutes(e.target.value)}
/>
<span className="ml-2">minutes</span>
</div>
<div>
<label htmlFor="cookTime" className="mr-2 font-bold">Cook Time:</label>
<input
type="text"
placeholder="cook time in minutes"
className="recipe-cusine p-2 border border-gray-300 rounded w-24"
value={cookMinutes}
onChange={(e) => setCookMinutes(e.target.value)}
/>
<span className="ml-2">minutes</span>
</div>
<div>
<StarRating rating={stars} onRatingChange={(newRating: number) => setStars(newRating)} />
</div>
</div>
<label className="mb-4 flex items-center cursor-pointer">
<div className="relative">
<input
type="checkbox"
checked={showBulkForm}
onChange={(e) => setShowBulkForm(e.target.checked)}
className="sr-only"
/>
Bulk Entry
</div>
</label>
<div>
{showBulkForm ?
<AddBulkIngredients ingredients={ingredients} onChange={setIngredients} /> :
<AddIngredientsForm ingredients={ingredients} onSubmit={setIngredients} />
}
<AddBulkIngredients ingredients={ingredients} onChange={setIngredients} />
</div>
<div>
<ul>
{/*<ul className="mb-4">
{ingredients.map((ing, index) => (
<li key={index}>{`${ing.quantity} ${ing.unit} ${ing.name}`}</li>
<li key={index} className="text-gray-700 flex items-start mb-2">
<span>{ing}</span>
</li>
))}
</ul>
</div>
</ul>*/}
<div>
{showBulkForm ?
<AddBulkSteps steps={steps} onChange={setSteps} /> :
<AddStepsForm steps={steps} onSubmit={setSteps} />
}
<AddBulkSteps steps={steps} onChange={setSteps} />
</div>
<ul>
{/*<ul className="mb-4">
{steps.map((step) => (
<li key={step.idx}>{`${step.idx}. ${step.instructions}`}</li>
<li key={step.step_number} className="text-gray-700 flex items-start mb-2">
<span>{`${step.step_number}. ${step.instruction}`}</span>
</li>
))}
</ul>
</ul>*/}
<button type="submit" className="ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700">
submit
</button>
</form>
</div>
)
}

View file

@ -1,57 +0,0 @@
import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx"
import { useState, useEffect } from "react";
import { getRecipes, deleteRecipe } from "../services/frontendApi.js";
import { type Recipe } from "../types/Recipe"
function Cookbook() {
const [recipes, setRecipes] = useState([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);
useEffect(() => {
const loadRecipes = async () => {
try {
const recipes = await getRecipes();
setRecipes(recipes);
} catch (error) {
console.log(error);
setError("Failed to load recipes...");
} finally {
setLoading(false);
}
};
if (shouldFetchRecipes) {
loadRecipes().then(() => setShouldFetchRecipes(false));
}
}, [shouldFetchRecipes]);
const handleDelete = async (id: number | void) => {
try {
await deleteRecipe(id);
setShouldFetchRecipes(true);
} catch (error) {
console.error("Error deleting recipe:", error);
}
};
return (
<div className="home">
{error && <div className="error-message">{error}</div>}
{loading ? (
<div className="loading">Loading...</div>
) : (
<div className="recipes-grid">
{recipes.map((recipe: Recipe) => (
<CookbookRecipeTile recipe={recipe} key={recipe.id} handleDelete={handleDelete} />
))}
</div>
)}
</div>
);
}
export default Cookbook;

View file

@ -0,0 +1,86 @@
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<RecipeSmall[]>([]);
const [cuisines, setCuisines] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);
const [selectedCuisine, setSelectedCuisine] = useState("");
useEffect(() => {
const loadRecipes = async () => {
try {
const recipes = await getRecipes();
setRecipes(recipes);
console.log(recipes)
const uniqueCuisines: string[] = recipes.length > 0
? Array.from(new Set(recipes.map((recipe: RecipeSmall) => recipe.cuisine)))
: [];
setCuisines(uniqueCuisines)
console.log(cuisines)
} catch (error) {
console.log(error);
setError("Failed to load recipes...");
} finally {
setLoading(false);
}
};
if (shouldFetchRecipes) {
loadRecipes().then(() => setShouldFetchRecipes(false));
}
}, [shouldFetchRecipes]);
const handleDelete = async (id: number | void) => {
try {
await deleteRecipe(id);
setShouldFetchRecipes(true);
} catch (error) {
console.error("Error deleting recipe:", error);
}
};
const filteredRecipes = selectedCuisine ? recipes.filter(recipe => recipe.cuisine === selectedCuisine) : recipes;
return (
<div className="add-recipe-card bg-amber-100 border border-amber-200 rounded-bl-lg rounded-br-lg p-6 md:p-8 lg:p-10 max-w-6xl mx-auto font-serif">
<h1 className="text-center text-3xl sm:text-4xl md:text-5xl font-bold mb-6 text-amber-800">Recipe Index</h1>
<div className="cuisines-buttons flex flex-wrap justify-center">
<input
type="text"
placeholder="search"
className="recipe-name mb-4 p-2 border border-gray-300 rounded w-full"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
{cuisines.map((cuisine) => (
<button
key={cuisine}
className={`ar-button bg-amber-600 text-white py-2 px-4 rounded hover:bg-amber-700 m-2 ${selectedCuisine === cuisine ? 'selected bg-amber-800' : ''}`}
onClick={() => setSelectedCuisine((prevState => prevState === cuisine ? "" : cuisine))}
>
{cuisine}
</button>
))}
</div> {error && <div className="error-message">{error}</div>}
{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">
{filteredRecipes.map((recipe) => (
recipe.name.toLowerCase().startsWith(searchQuery) &&
<CookbookRecipeTile recipe={recipe} key={recipe.id} handleDelete={handleDelete} />
))}
</div>
</div>
)}
</div>
);
}
export default AllRecipes

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

@ -1,24 +1,32 @@
import RecipeCard from "../components/RecipeCard.tsx"
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { getRecipeById } from "../services/frontendApi.js";
import { type Recipe } 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() {
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);
@ -30,16 +38,79 @@ function RecipePage() {
loadRecipe();
}, [id]);
useEffect(() => {
if (initialStars === null || initialStars === stars) {
return;
}
const updateStarsInDB = async () => {
await setDBStars(id, stars);
};
updateStarsInDB();
}, [stars]);
return (
<div className="recipe">
<div className="recipe page-outer">
{error && <div className="error-message">{error}</div>}
{loading ? (
<div className="loading">Loading...</div>
) : (
<div className="recipe-card">
<RecipeCard recipe={recipe} key={recipe.details.id} />
<div className="border-b-2 border-amber-300 pb-4 mb-6">
<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>prep: {recipe.details.prep_minutes} min | cook: {recipe.details.cook_minutes} min</p>
</div>
<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>
Ingredients:
</h4>
<ul className="space-y-2">
{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.raw}</span>
</li>
))}
</ul>
</div>
<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>
Instructions:
</h4>
<ol className="space-y-3">
{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">
{recipe.steps[parseInt(stepNumber)].step_number}
</span>
<span className="leading-relaxed">{recipe.steps[parseInt(stepNumber)].instruction}</span>
</li>
))}
</ol>
</div>
</div>
<div className="border-t-2 border-amber-300 pt-4">
<div className="flex justify-between items-center text-sm text-amber-600">
{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>
)}
</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

@ -1,38 +1,65 @@
const baseUrl = process.env.NODE_ENV === 'production'
? '/'
: 'http://localhost:3000/';
export const getRecipes = async () => {
const response = await fetch("http://localhost:6063/recipes");
const response = await fetch(`${baseUrl}backend/recipes`);
const data = await response.json();
return data;
};
export const getRecipeSteps = async () => {
const response = await fetch(`${baseUrl}backend/recipe-steps`);
const data = await response.json();
return data;
};
export const getRecipeIngredients = async () => {
const response = await fetch(`${baseUrl}backend/recipe-ingredients`);
const data = await response.json();
return data;
};
export const getRecipeById = async (id) => {
const response = await fetch(`http://localhost:6063/recipe/${id}`);
const response = await fetch(`${baseUrl}backend/recipe/${id}`);
const data = await response.json();
return data;
};
export const addRecipe = async (recipeData) => {
console.log(JSON.stringify(recipeData))
console.log(JSON.stringify(recipeData));
// return
const response = await fetch("http://localhost:6063/add-recipe", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(recipeData)
const response = await fetch(`${baseUrl}backend/add-recipe`, {
method: "POST",
headers: { "Content-Type": "application/json" },
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(`${baseUrl}backend/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('run delete')
console.log(id)
console.log(id);
// return
const response = await fetch("http://localhost:6063/delete-recipe", {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id })
const response = await fetch(`${baseUrl}backend/delete-recipe`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id }),
});
const data = await response.json();
return data;
};

View file

@ -1,22 +1,35 @@
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;
prep_minutes?: number;
cook_minutes?: number;
},
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 }

View file

@ -0,0 +1,12 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}

View file

@ -1,7 +1,11 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
})
server: {
host: "ec683cee72d30c5030.fredzernia.com",
allowedHosts: ["ec683cee72d30c5030.fredzernia.com"],
},
});

View file

@ -10,6 +10,6 @@ services:
- POSTGRES_PASSWORD=${DB_PASSWORD}
- POSTGRES_DB=${DB_NAME}
ports:
- "${DB_PORT}:5432"
- "5432:5432"
volumes:
- ./db:/var/lib/postgresql/data