Update 17 files

- /src/main/resources/application.properties
- /src/main/resources/templates/view-recipe.html
- /src/main/resources/templates/create-recipe.html
- /src/main/resources/templates/home.html
- /src/main/resources/templates/explore.html
- /src/main/resources/templates/public-profile.html
- /src/main/resources/templates/my-profile.html
- /src/main/resources/templates/update-recipe.html
- /src/main/resources/static/css/view-recipe.css
- /src/main/java/com/example/demo/controller/SiteController.java
- /src/main/java/com/example/demo/controller/RecipeUploadController.java
- /src/main/java/com/example/demo/controller/RecipeUploadForm.java
- /src/main/java/com/example/demo/config/WebConfig
- /src/main/java/com/example/demo/config/SecurityConfig.java
- /src/main/java/com/example/demo/config/WebConfig.java
- /src/main/java/com/example/demo/service/Impl/RecipeServiceImpl.java
- /src/main/java/com/example/demo/service/RecipeService.java
This commit is contained in:
Madeleine Stamp
2026-04-21 13:37:02 -06:00
parent ce3cea01c3
commit 267d5c7bdf
17 changed files with 924 additions and 327 deletions
@@ -18,3 +18,8 @@ spring.jpa.open-in-view=false
#spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
server.port=8080
spring.servlet.multipart.max-file-size=20MB
spring.servlet.multipart.max-request-size=20MB
server.tomcat.max-swallow-size=-1
server.tomcat.max-part-count=100
@@ -30,7 +30,8 @@ body, html {
margin: 0;
font-family: 'Mali', cursive;
background-color: var(--pale-yellow);
overflow: clip;
overflow-x: hidden;
overflow-y: auto;
}
/* =========================
@@ -73,9 +73,12 @@
<div class="field">
<label for="servings">Servings: <span class="required">*</span></label>
<input type="text" id="servings" placeholder="0">
</div>
</div>
<div class="field">
<label for="cost">Estimated Cost: <span class="required">*</span></label>
<input type="text" id="cost" placeholder="0">
<label>Estimated Cost: <span class="required">*</span></label>
<div class="cost-selector" id="cost-selector">
<span class="dollar" data-value="1">$</span>
@@ -153,6 +156,7 @@ function addStep() {
function renumberSteps() {
stepsContainer.querySelectorAll('.step-bubble').forEach((bubble, i) => {
bubble.textContent = i + 1;
bubble.textContent = i + 1;
});
}
// Cost display
@@ -184,6 +188,7 @@ dollars.forEach(dollar => {
// ---- Collecting on submit ----
// Call this wherever you build your POST payload:
function getIngredients() {
return [...ingredientContainer.querySelectorAll('.dynamic-row')].map(row => {
qtyValue = row.querySelector('.ing-qty').value.trim(); // quantity should be a number NOT A STRING
@@ -375,4 +380,4 @@ document.getElementById('publish-btn').addEventListener('click', async function(
</script>
</body>
</html>
</html>
+4 -9
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta name="_csrf" th:content="${_csrf.token}"/>
<title>Explore - Thyme Crunch</title>
<title>Thyme Crunch Home</title>
<link rel="stylesheet" th:href="@{css/explore.css}">
<link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
@@ -52,7 +52,7 @@
<button type="submit"><i class="fa fa-search"></i></button>
</div>
</form>
</div>
</div>
<p th:if="${#lists.isEmpty(recipes)}">There are no recipes that fit this description.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
@@ -65,10 +65,11 @@
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div>
<p class="card-cost" th:text="${recipe.cost}">Cost</p>
<p th:text="${recipe.cost}">Cost</p>
</div>
</a>
</div>
</main>
<!--Filter -->
@@ -234,12 +235,6 @@
window.location.href = '/explore?' + out.toString();
}
})();
// For cost display
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
});
</script>
</body>
+3 -12
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home - Thyme Crunch</title>
<title>Thyme Crunch Home</title>
<link rel="stylesheet" th:href="@{css/home.css}">
<link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
</head>
@@ -38,7 +38,6 @@
<!-- Main Content -->
<main class="main-content">
<div class="recipe-card">
<p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
@@ -51,7 +50,7 @@
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div>
<p class="card-cost" th:text="${recipe.cost}">Cost</p>
<p th:text="${recipe.cost}">Cost</p>
</div>
</a>
</div>
@@ -64,13 +63,5 @@
</div>
</div>
</div>
<script>
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
});
</script>
</body>
</html>
</html>
+4 -11
View File
@@ -53,10 +53,10 @@
<p th:text="${recipe.description}">Description</p>
</div>
<div class="card-right">
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div>
<p class="card-cost" th:text="${recipe.cost}"><b>Cost</b></p>
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image" style="max-width: 200px;">
</div>
<p th:text="${recipe.cost}">Cost</p>
</div>
</a>
<a th:href="@{/recipes/{id}/edit(id=${recipe.id})}" class="edit-link">Edit</a>
@@ -91,12 +91,5 @@
</div>
<script>
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
});
</script>
</body>
</html>
@@ -4,16 +4,16 @@
<meta charset="UTF-8">
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta name="_csrf" th:content="${_csrf.token}"/>
<title>My Profile - Thyme Crunch</title>
<link rel="stylesheet" th:href="@{css/my-profile.css}">
<title>Profile - Thyme Crunch</title>
<link rel="stylesheet" th:href="@{/css/my-profile.css}">
<link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
</head>
<body>
<header class="top-header">
<img th:src="@{images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
<img th:src="@{/images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
<h1 class="site-name">Thyme Crunch</h1>
<img th:src="@{images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
<img th:src="@{/images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
</header>
<div class="body">
@@ -27,65 +27,50 @@
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<form th:action="@{/logout}" method="post">
<input type="image" th:src="@{images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
<input type="image" th:src="@{/images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
</form>
</li>
</ul>
</nav>
<a th:href="@{/create}" target="_blank" class="create_icon">
<img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
<img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
</a>
</div>
<!-- Main Content — recipes -->
<main class="main-content">
<h2>My Recipes</h2>
<h2 th:text="${profile.effectiveDisplayName} + '\'s Recipes'">User's Recipes</h2>
<p th:if="${#lists.isEmpty(profile.recipes)}">You have not created any recipes yet.</p>
<p th:if="${#lists.isEmpty(profile.recipes)}">This user has not created any recipes yet.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(profile.recipes)}">
<th:block th:each="recipe : ${profile.recipes}">
<div class="card-wrapper">
<a th:href="@{/recipes/{id}(id=${recipe.id})}" class="card">
<div class="card-text">
<h2 th:text="${recipe.title}">Recipe Title</h2>
<p th:text="${recipe.description}">Description</p>
</div>
<div class="card-right">
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div>
<p th:text="${recipe.cost}">Cost</p>
</div>
</a>
</div>
</th:block>
</div>
<th:block th:each="recipe : ${profile.recipes}">
<div class="card-wrapper">
<a th:href="@{/recipes/{id}(id=${recipe.id})}" class="card">
<div class="card-text">
<h2 th:text="${recipe.title}">Recipe Title</h2>
<p th:text="${recipe.description}">Description</p>
</div>
<div class="card-right">
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image" style="max-width: 200px;">
</div>
<p th:text="${recipe.cost}">Cost</p>
</div>
</a>
</div>
</th:block>
</div>
</main>
<!-- Right Sidebar — profile info & edit -->
<!-- Right Sidebar — public profile info only -->
<div class="body-right">
<div class="sidebar-right">
<p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p>
<p th:text="'@' + ${profile.username}">@username</p>
<p th:if="${profile.bio != null}" th:text="${profile.bio}">Bio goes here.</p>
<a th:href="@{/users/{id}(id=${profile.id})}" class="view-profile-btn">View public profile</a>
<form th:action="@{/my-profile/update}" method="post" th:object="${updateProfileDto}" class="profile-form">
<div class="rows">
<label for="displayName">Display Name</label>
<input type="text" id="displayName" th:field="*{displayName}" maxlength="100">
</div>
<div class="rows">
<label for="bio">Bio</label>
<textarea id="bio" th:field="*{bio}" rows="6" maxlength="1000"></textarea>
</div>
<button type="submit">Save</button>
</form>
<p th:if="${profile.bio != null and !#strings.isEmpty(profile.bio)}" th:text="${profile.bio}">Bio goes here.</p>
</div>
</div>
+307 -177
View File
@@ -1,19 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta name="_csrf" th:content="${_csrf.token}"/>
<title>Create Thyme Crunch Recipe</title>
<link rel="stylesheet" th:href="@{css/create-recipe.css}">
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta name="_csrf" th:content="${_csrf.token}"/>
<title>Update Thyme Crunch Recipe</title>
<link rel="stylesheet" th:href="@{/css/create-recipe.css}">
<link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
</head>
<body>
<header class="top-header">
<img th:src="@{images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
<img th:src="@{/images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
<h1 class="site-name">Thyme Crunch</h1>
<img th:src="@{images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
<img th:src="@{/images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
</header>
<div class="form-wrap">
@@ -21,7 +21,7 @@
<!-- Main Content -->
<div class="form-section">
<div class="section-title">New Recipe</div>
<div class="section-title">Update Recipe</div>
<div class="field">
<label for="title">Title <span class="required">*</span></label>
@@ -34,17 +34,16 @@
</div>
<div class="field">
<label>Ingredients <span class="required">*</span></label>
<label>Ingredients <span class="required">*</span></label>
<div id="ingredients-container"></div>
<button class="btn-add" id="add-ingredient-btn">+ Add ingredient</button>
<button class="btn-add" id="add-ingredient-btn" type="button">+ Add ingredient</button>
</div>
<div class="field">
<label>Instructions <span class="required">*</span></label>
<div id="steps-container"></div>
<button class="btn-add" id="add-step-btn">+ Add step</button>
<button class="btn-add" id="add-step-btn" type="button">+ Add step</button>
</div>
</div>
<!-- Cover image / Right -->
@@ -53,90 +52,107 @@
<div class="image-drop" id="drop-zone">
<p class="upload-title">Click to upload or drag and drop an image.</p>
</div>
<div class="image-preview" id="preview">
<div class="image-preview" id="preview" style="display: none;">
<img id="preview-img" src="" alt="Cover preview">
<button class="remove-img" id="remove-img-btn">Remove</button>
<button class="remove-img" id="remove-img-btn" type="button">Remove</button>
</div>
<input type="file" id="img-input" accept="image/*" style="display: none;">
</div>
<div class="field">
<label for="prep">Preparation Time: <span class="required">*</span></label>
<input type="text" id="prep" placeholder="0">
</div>
<div class="field">
<div class="field">
<label for="cooking">Cooking Time: <span class="required">*</span></label>
<input type="text" id="cooking" placeholder="0">
</div>
<div class="field">
<label for="servings">Servings: <span class="required">*</span></label>
<input type="text" id="servings" placeholder="0">
</div>
<div class="field">
<div class="field">
<label for="cost">Estimated Cost: <span class="required">*</span></label>
<input type="text" id="cost" placeholder="0">
</div>
</div>
</div>
</div>
<!-- Tags -->
<div class="form-section">
<div class="field">
<label>Tags</label>
<div class="tag-input-row">
<input type="text" id="tag-input" placeholder="Type in a tag and click Add">
<button class="btn" id="add-tag-btn">Add</button>
<button class="btn" id="add-tag-btn" type="button">Add</button>
</div>
<div class="tag-wrap" id="tag-wrap"></div>
</div>
</div>
<div class="actions">
<button class="btn-create" id="publish-btn">CREATE</button>
</div>
<div id="form-message" class="form-message" style="display:none;"></div>
<div class="actions">
<button class="btn-create" id="publish-btn" type="button">UPDATE</button>
</div>
</div>
<script th:inline="javascript">
const existingRecipe = /*[[${recipe}]]*/ null;
</script>
<script>
// ---- DOM refs ----
const ingredientContainer = document.getElementById('ingredients-container');
const stepsContainer = document.getElementById('steps-container');
const dropZone = document.getElementById('drop-zone');
const imgInput = document.getElementById('img-input');
const previewImg = document.getElementById('preview-img');
const previewBox = document.getElementById('preview');
const tags = [];
let imageRemoved = false;
// ---- Ingredients ----
const ingredientContainer = document.getElementById('ingredients-container');
document.getElementById('add-ingredient-btn').addEventListener('click', addIngredient);
addIngredient(); // start with one
document.getElementById('add-ingredient-btn').addEventListener('click', function (e) {
e.preventDefault();
addIngredient();
});
function addIngredient() {
function addIngredient(data = {}) {
const row = document.createElement('div');
row.className = 'dynamic-row';
row.innerHTML = `
<input type="text" class="ing-name" placeholder="Ingredient (e.g. Sugar)">
<input type="text" class="ing-qty" placeholder="Qty (e.g. 3)">
<input type="text" class="ing-unit" placeholder="Unit (e.g. tbsp)">
<input type="text" class="ing-notes" placeholder="Notes (optional)">
<button class="btn-remove" title="Remove">✕</button>`;
row.querySelector('.btn-remove').addEventListener('click', () => {
<input type="text" class="ing-name" placeholder="Ingredient (e.g. Sugar)" value="${escapeHtml(data.ingredientName || '')}">
<input type="text" class="ing-qty" placeholder="Qty (e.g. 3)" value="${data.quantity ?? ''}">
<input type="text" class="ing-unit" placeholder="Unit (e.g. tbsp)" value="${escapeHtml(data.unit || '')}">
<input type="text" class="ing-notes" placeholder="Notes (optional)" value="${escapeHtml(data.notes || '')}">
<button class="btn-remove" title="Remove" type="button">✕</button>`;
row.querySelector('.btn-remove').addEventListener('click', function (e) {
e.preventDefault();
row.remove();
});
ingredientContainer.appendChild(row);
}
// ---- Steps ----
const stepsContainer = document.getElementById('steps-container');
document.getElementById('add-step-btn').addEventListener('click', addStep);
addStep(); // start with one
document.getElementById('add-step-btn').addEventListener('click', function (e) {
e.preventDefault();
addStep();
});
function addStep() {
function addStep(data = {}) {
const row = document.createElement('div');
row.className = 'dynamic-row';
row.innerHTML = `
<div class="step-bubble">?</div>
<textarea placeholder="Describe this step..."></textarea>
<button class="btn-remove" title="Remove">✕</button>
<textarea placeholder="Describe this step...">${escapeHtml(data.instruction || '')}</textarea>
<button class="btn-remove" title="Remove" type="button">✕</button>
`;
row.querySelector('.btn-remove').addEventListener('click', () => {
row.querySelector('.btn-remove').addEventListener('click', function (e) {
e.preventDefault();
row.remove();
renumberSteps();
});
@@ -150,52 +166,30 @@ function renumberSteps() {
});
}
// ---- Collecting on submit ----
// Call this wherever you build your POST payload:
function getIngredients() {
return [...ingredientContainer.querySelectorAll('.dynamic-row')].map(row => {
qtyValue = row.querySelector('.ing-qty').value.trim(); // quantity should be a number NOT A STRING
return {
ingredient: {
name: row.querySelector('.ing-name').value.trim()
},
quantity: Number(qtyValue),
unit: row.querySelector('.ing-unit').value.trim(),
notes: row.querySelector('.ing-notes').value.trim()
};
}).filter(item => item.ingredient.name);
}
function getSteps() {
return [...stepsContainer.querySelectorAll('textarea')]
.map((el, i) => ({ step_number: i + 1, instruction: el.value.trim() }))
.filter(item => item.instruction);
}
// --- Image upload ---
const dropZone = document.getElementById('drop-zone');
const imgInput = document.getElementById('img-input');
// ---- Image upload preview ----
dropZone.addEventListener('click', () => imgInput.click());
imgInput.addEventListener('change', function () {
if (!this.files || !this.files[0]) return;
imageRemoved = false;
const url = URL.createObjectURL(this.files[0]);
document.getElementById('preview-img').src = url;
previewImg.src = url;
dropZone.style.display = 'none';
document.getElementById('preview').style.display = 'block';
previewBox.style.display = 'block';
});
document.getElementById('remove-img-btn').addEventListener('click', function () {
document.getElementById('remove-img-btn').addEventListener('click', function (e) {
e.preventDefault();
imgInput.value = '';
document.getElementById('preview').style.display = 'none';
previewImg.src = '';
previewBox.style.display = 'none';
dropZone.style.display = 'block';
imageRemoved = true;
});
// --- Tags ---
const tags = [];
// ---- Tags ----
document.getElementById('tag-input').addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
@@ -203,12 +197,18 @@ document.getElementById('tag-input').addEventListener('keydown', function (e) {
}
});
document.getElementById('add-tag-btn').addEventListener('click', addTag);
document.getElementById('add-tag-btn').addEventListener('click', function (e) {
e.preventDefault();
addTag();
});
function addTag() {
const input = document.getElementById('tag-input');
const val = input.value.trim().toLowerCase().replace(/\s+/g, '-');
if (!val || tags.includes(val)) { input.value = ''; return; }
if (!val || tags.includes(val)) {
input.value = '';
return;
}
tags.push(val);
input.value = '';
renderTags();
@@ -221,7 +221,7 @@ function removeTag(t) {
function renderTags() {
document.getElementById('tag-wrap').innerHTML = tags
.map(t => `<div class="tag">${t} <span class="remove-tag" data-tag="${t}">✕</span></div>`)
.map(t => `<div class="tag">${escapeHtml(t)} <span class="remove-tag" data-tag="${escapeHtml(t)}">✕</span></div>`)
.join('');
document.querySelectorAll('.remove-tag').forEach(btn => {
@@ -229,118 +229,248 @@ function renderTags() {
});
}
async function getLoggedInUser() {
try {
const res = await fetch('http://localhost:8080/api/users/me', {
credentials: 'include'
});
if (!res.ok) throw new Error('Failed to get logged-in user');
return await res.json();
} catch (err) {
console.error('Error fetching user:', err);
return null;
}
// ---- Helpers ----
function escapeHtml(str) {
return String(str ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
function buildRecipeJSON(user) {
const title = document.getElementById('title').value.trim();
const description = document.getElementById('desc').value.trim();
const prepTimeMinutes = Number(document.getElementById('prep').value);
const cookTimeMinutes = Number(document.getElementById('cooking').value);
const servings = Number(document.getElementById('servings').value);
const status = "DRAFT";
const cost = Number(document.getElementById('cost').value);
// Ingredients
const recipeIngredients = [...document.querySelectorAll('#ingredients-container .dynamic-row')]
.map(row => {
const qtyValue = Number(row.querySelector('.ing-qty').value.trim());
return {
ingredient: { name: row.querySelector('.ing-name').value.trim() },
quantity: qtyValue,
unit: row.querySelector('.ing-unit').value.trim(),
notes: row.querySelector('.ing-notes').value.trim()
};
})
.filter(item => item.ingredient.name);
// Steps
const steps = [...document.querySelectorAll('#steps-container textarea')]
.map((el, i) => ({ stepNumber: i + 1, instruction: el.value.trim() }))
.filter(item => item.instruction);
// Images
// Tags
const tagsInput = tags;
const tagsArray = tagsInput.map(t => ({ name: t }));
return {
title,
description,
prepTimeMinutes,
cookTimeMinutes,
servings,
status,
cost,
user,
recipeIngredients,
steps,
//images,
tags: tagsArray
};
function showMessage(message, isError = false) {
const box = document.getElementById('form-message');
box.textContent = message;
box.style.display = 'block';
box.style.backgroundColor = isError ? '#ffd7d7' : '#dff5dd';
box.style.color = isError ? '#7a0000' : '#1f5c2c';
box.style.border = isError ? '1px solid #d88' : '1px solid #8bc48b';
box.style.padding = '12px';
box.style.marginTop = '20px';
box.style.borderRadius = '8px';
}
function showSuccessAndRedirect(message) {
showMessage(message, false);
setTimeout(() => {
window.location.href = '/explore';
}, 1500);
}
function fillRecipeForm(recipe) {
if (!recipe) return;
document.getElementById('title').value = recipe.title || '';
document.getElementById('desc').value = recipe.description || '';
document.getElementById('prep').value = recipe.prepTimeMinutes ?? '';
document.getElementById('cooking').value = recipe.cookTimeMinutes ?? '';
document.getElementById('servings').value = recipe.servings ?? '';
document.getElementById('cost').value = recipe.cost ?? '';
ingredientContainer.innerHTML = '';
if (recipe.ingredients && recipe.ingredients.length > 0) {
recipe.ingredients.forEach(item => addIngredient(item));
} else {
addIngredient();
}
stepsContainer.innerHTML = '';
if (recipe.steps && recipe.steps.length > 0) {
recipe.steps.forEach(step => addStep(step));
} else {
addStep();
}
if (recipe.tags && recipe.tags.length > 0) {
recipe.tags.forEach(tag => {
if (tag.name && !tags.includes(tag.name.toLowerCase())) {
tags.push(tag.name.toLowerCase());
}
});
renderTags();
}
imageRemoved = false;
if (recipe.images && recipe.images.length > 0 && recipe.images[0].imageUrl) {
previewImg.src = recipe.images[0].imageUrl;
dropZone.style.display = 'none';
previewBox.style.display = 'block';
} else {
previewImg.src = '';
previewBox.style.display = 'none';
dropZone.style.display = 'block';
}
}
// ---- Inline validation ----
function showError(input, message) {
input.classList.add('invalid');
let error = input.parentElement.querySelector('.error-message');
if (!error) {
error = document.createElement('p');
error.className = 'error-message';
error.style.color = 'red';
error.style.fontSize = '0.9em';
error.style.marginTop = '6px';
input.parentElement.appendChild(error);
}
error.textContent = message;
}
function clearError(input) {
input.classList.remove('invalid');
const error = input.parentElement.querySelector('.error-message');
if (error) error.remove();
}
function validateForm() {
let valid = true;
const title = document.getElementById('title');
const desc = document.getElementById('desc');
const prep = document.getElementById('prep');
const cooking = document.getElementById('cooking');
const servings = document.getElementById('servings');
const cost = document.getElementById('cost');
[title, desc, prep, cooking, servings, cost].forEach(clearError);
if (!title.value.trim()) {
showError(title, 'Title is required');
valid = false;
}
if (!desc.value.trim()) {
showError(desc, 'Description is required');
valid = false;
}
if (!prep.value.trim() || isNaN(Number(prep.value)) || Number(prep.value) <= 0) {
showError(prep, 'Enter a valid prep time');
valid = false;
}
if (!cooking.value.trim() || isNaN(Number(cooking.value)) || Number(cooking.value) <= 0) {
showError(cooking, 'Enter a valid cook time');
valid = false;
}
if (!servings.value.trim() || isNaN(Number(servings.value)) || Number(servings.value) <= 0) {
showError(servings, 'Enter valid servings');
valid = false;
}
if (!cost.value.trim() || isNaN(Number(cost.value)) || Number(cost.value) <= 0) {
showError(cost, 'Enter a valid cost');
valid = false;
}
const ingredientRows = [...document.querySelectorAll('#ingredients-container .dynamic-row')];
const hasIngredient = ingredientRows.some(row => row.querySelector('.ing-name').value.trim() !== '');
if (!hasIngredient && ingredientRows.length > 0) {
showError(ingredientRows[0].querySelector('.ing-name'), 'Add at least one ingredient');
valid = false;
}
const stepAreas = [...document.querySelectorAll('#steps-container textarea')];
const hasStep = stepAreas.some(textarea => textarea.value.trim() !== '');
if (!hasStep && stepAreas.length > 0) {
showError(stepAreas[0], 'Add at least one instruction step');
valid = false;
}
if (!valid) {
document.querySelector('.invalid')?.scrollIntoView({
behavior: 'smooth',
block: 'center'
});
}
return valid;
}
// ---- Initial fill ----
fillRecipeForm(existingRecipe);
// ---- Update recipe with multipart upload ----
document.getElementById('publish-btn').addEventListener('click', async function(e) {
e.preventDefault();
e.preventDefault();
const user = await getLoggedInUser();
if (!user) {
alert("Unable to fetch logged-in user. Please refresh and try again.");
return;
if (!existingRecipe || !existingRecipe.id) {
showMessage('Recipe data was not loaded correctly.', true);
return;
}
if (!validateForm()) {
return;
}
const formData = new FormData();
formData.append('title', document.getElementById('title').value.trim());
formData.append('description', document.getElementById('desc').value.trim());
formData.append('prepTimeMinutes', document.getElementById('prep').value.trim());
formData.append('cookTimeMinutes', document.getElementById('cooking').value.trim());
formData.append('servings', document.getElementById('servings').value.trim());
formData.append('cost', document.getElementById('cost').value.trim());
formData.append('removeImage', String(imageRemoved));
document.querySelectorAll('#ingredients-container .dynamic-row').forEach(row => {
const ingredientName = row.querySelector('.ing-name').value.trim();
if (!ingredientName) return;
formData.append('ingredientName', ingredientName);
const qty = row.querySelector('.ing-qty').value.trim();
const unit = row.querySelector('.ing-unit').value.trim();
const notes = row.querySelector('.ing-notes').value.trim();
formData.append('ingredientQuantity', qty);
if (unit) formData.append('ingredientUnit', unit);
if (notes) formData.append('ingredientNotes', notes);
});
document.querySelectorAll('#steps-container textarea').forEach(textarea => {
const instruction = textarea.value.trim();
if (instruction) {
formData.append('stepInstruction', instruction);
}
});
console.log("Logged-in user:", user);
const recipeJSON = buildRecipeJSON(user);
console.log("Recipe JSON to submit:", JSON.stringify(recipeJSON, null, 2));
tags.forEach(tag => formData.append('tags', tag));
try {
const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
if (imgInput.files && imgInput.files[0]) {
formData.append('image', imgInput.files[0]);
}
try {
const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
const res = await fetch('http://localhost:8080/api/recipes', {
method: 'POST',
headers: {
[csrfHeader]: csrfToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(recipeJSON),
credentials: 'include'
});
const res = await fetch(`/api/recipes/${existingRecipe.id}/upload`, {
method: 'POST',
headers: {
[csrfHeader]: csrfToken
},
body: formData,
credentials: 'include'
});
if (res.ok) {
const data = await res.json();
console.log("Recipe created:", data);
alert("Recipe created successfully!");
} else {
const errorData = await res.json();
console.error("Validation errors:", errorData);
const responseText = await res.text();
const firstError = Object.values(errorData)[0];
alert(firstError);
}
} catch (err) {
console.error("Network error:", err);
alert("Network error. Check console for details.");
if (res.ok) {
showSuccessAndRedirect('Recipe updated successfully!');
} else {
console.error('Recipe update failed:', responseText);
showMessage(responseText || 'Failed to update recipe.', true);
}
} catch (err) {
console.error('Network error:', err);
showMessage('Network error. Check console for details.', true);
}
});
</script>
</body>
</html>
+103 -29
View File
@@ -1,64 +1,138 @@
<!DOCTYPE html>
<html lang="en">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thyme Crunch View Recipe</title>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta name="_csrf" th:content="${_csrf.token}"/>
<title th:text="${recipe != null ? recipe.title : 'Recipe'}">Recipe</title>
<link rel="stylesheet" th:href="@{/css/view-recipe.css}">
<link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
</head>
<body>
<header class="top-header">
<img th:src="@{images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
<img th:src="@{/images/header_left.png}" alt="Left header swirl" class="swirl">
<h1 class="site-name">Thyme Crunch</h1>
<img th:src="@{images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
<img th:src="@{/images/header_right.png}" alt="Right header swirl" class="swirl">
</header>
<div class="body">
<!--Navigation Bar -->
<div class="body-left">
<nav class="sidebar-left">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Explore</a></li>
<li><a href="#">Profile</a></li>
<li><a href="#">Saved</a></li>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<form th:action="@{/logout}" method="post">
<input type="image" th:src="@{images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
<input type="image" th:src="@{/images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
</form>
</li>
</ul>
</nav>
<a th:href="@{/create}" target="_blank" class="create_icon">
<img th:src="@{images/create_icon.png}" alt="Description of the icon">
<img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.">
</a>
</div>
<!-- Main Content -->
<main class="main-content">
<div class="form-wrap">
<h1 th:text="${recipe.title}"></h1>
<p th:text="${recipe.description}"></p>
<div th:if="${recipe != null}" style="width: 100%; max-width: 950px; margin: 35px auto;">
<div class="form-section">
<div class="section-title">Ingredients</div>
<ul>
<li th:each="ingredient : ${recipe.ingredients}"
th:text="${ingredient.name}"></li>
</ul>
</div>
<section style="background: var(--peach); border-radius: 20px; padding: 18px 24px; color: var(--dark);">
<h1 style="margin-top: 0; font-size: 2.8em;" th:text="${recipe.title}">Recipe Title</h1>
<div class="form-section">
<div class="section-title">Instructions</div>
<ol class="step-list">
<li th:each="step : ${#lists.sort(recipe.steps, comparingInt(step -> step.stepNumber))}">
</ol
</div>
</div>
<p th:if="${recipe.userDto != null}" style="font-size: 1.2em; margin-bottom: 20px;">
<strong>Author:</strong>
<a th:href="@{/users/{id}(id=${recipe.userDto.id})}"
th:text="${recipe.userDto.displayName != null and !#strings.isEmpty(recipe.userDto.displayName) ? recipe.userDto.displayName : recipe.userDto.username}">
Author Name
</a>
</p>
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}" style="margin-bottom: 28px;">
<img th:src="${recipe.images[0].imageUrl}"
alt="Recipe Image"
style="display:block; width:100%; max-width:700px; max-height:420px; object-fit:cover; border-radius:16px; margin:0 auto;">
</div>
<p th:unless="${recipe.images != null and !#lists.isEmpty(recipe.images)}"
style="margin-bottom: 28px; font-style: italic;">
No image uploaded for this recipe.
</p>
<div style="margin-bottom: 25px;">
<h2>Description</h2>
<p th:text="${recipe.description}">Recipe description</p>
</div>
<div style="display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 30px; font-size: 1.1em;">
<p><strong>Prep Time:</strong> <span th:text="${recipe.prepTimeMinutes}">0</span> minutes</p>
<p><strong>Cook Time:</strong> <span th:text="${recipe.cookTimeMinutes}">0</span> minutes</p>
<p><strong>Servings:</strong> <span th:text="${recipe.servings}">0</span></p>
<p><strong>Cost:</strong> <span th:text="${recipe.cost}">0</span></p>
</div>
<div style="margin-bottom: 30px;">
<h2>Ingredients</h2>
<ul th:if="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}" style="line-height: 1.8;">
<li th:each="ingredient : ${recipe.ingredients}">
<span th:text="${ingredient.quantity}">1</span>
<span th:text="${ingredient.unit}">cup</span>
<span th:text="${ingredient.ingredientName}">Ingredient</span>
<span th:if="${ingredient.notes != null and !#strings.isEmpty(ingredient.notes)}"
th:text="${'(' + ingredient.notes + ')'}">(notes)</span>
</li>
</ul>
<p th:unless="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}">No ingredients listed.</p>
</div>
<div style="margin-bottom: 30px;">
<h2>Steps</h2>
<ol th:if="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}" style="line-height: 1.9;">
<li th:each="step : ${recipe.steps}" th:text="${step.instruction}">Step instruction</li>
</ol>
<p th:unless="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}">No steps listed.</p>
</div>
<div style="margin-bottom: 25px;">
<h2>Tags</h2>
<div th:if="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}" style="display: flex; flex-wrap: wrap; gap: 10px;">
<span th:each="tag : ${recipe.tags}"
th:text="${tag.name}"
style="background: var(--pale-yellow); padding: 8px 14px; border-radius: 999px; font-weight: 700;">
Tag
</span>
</div>
<p th:unless="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}">No tags listed.</p>
</div>
<div style="display: flex; gap: 20px; flex-wrap: wrap; margin-top: 25px;">
<a th:if="${recipe.userDto != null}"
th:href="@{/users/{id}(id=${recipe.userDto.id})}">
View author's profile
</a>
<a th:href="@{/explore}">Back to Explore</a>
</div>
</section>
</div>
<div th:unless="${recipe != null}" style="width: 100%; max-width: 950px; margin: 35px auto;">
<section style="background: var(--peach); border-radius: 20px; padding: 28px 32px; color: var(--dark);">
<h1>Recipe not found</h1>
<p><a th:href="@{/explore}">Back to Explore</a></p>
</section>
</div>
</main>
<!-- Right spacer/sidebar -->
<div class="body-right">
<div class="sidebar-right"></div>
</div>
</div>
</body>
</html>
</html>