Fixed a redirect

This commit is contained in:
Madeleine Stamp
2026-04-21 13:58:29 -06:00
parent edb4ef7c0d
commit 022db901ae
+247 -156
View File
@@ -1,19 +1,19 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en" xmlns:th="http://www.thymeleaf.org">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="_csrf_header" th:content="${_csrf.headerName}"/> <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta name="_csrf" th:content="${_csrf.token}"/> <meta name="_csrf" th:content="${_csrf.token}"/>
<title>Create Thyme Crunch Recipe</title> <title>Create Thyme Crunch Recipe</title>
<link rel="stylesheet" th:href="@{css/create-recipe.css}"> <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"> <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> </head>
<body> <body>
<header class="top-header"> <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> <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> </header>
<div class="form-wrap"> <div class="form-wrap">
@@ -36,15 +36,14 @@
<div class="field"> <div class="field">
<label>Ingredients <span class="required">*</span></label> <label>Ingredients <span class="required">*</span></label>
<div id="ingredients-container"></div> <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>
<div class="field"> <div class="field">
<label>Instructions <span class="required">*</span></label> <label>Instructions <span class="required">*</span></label>
<div id="steps-container"></div> <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>
</div> </div>
<!-- Cover image / Right --> <!-- Cover image / Right -->
@@ -53,9 +52,9 @@
<div class="image-drop" id="drop-zone"> <div class="image-drop" id="drop-zone">
<p class="upload-title">Click to upload or drag and drop an image.</p> <p class="upload-title">Click to upload or drag and drop an image.</p>
</div> </div>
<div class="image-preview" id="preview"> <div class="image-preview" id="preview" style="display: none;">
<img id="preview-img" src="" alt="Cover preview"> <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> </div>
<input type="file" id="img-input" accept="image/*" style="display: none;"> <input type="file" id="img-input" accept="image/*" style="display: none;">
</div> </div>
@@ -73,12 +72,9 @@
<div class="field"> <div class="field">
<label for="servings">Servings: <span class="required">*</span></label> <label for="servings">Servings: <span class="required">*</span></label>
<input type="text" id="servings" placeholder="0"> <input type="text" id="servings" placeholder="0">
</div>
</div> </div>
<div class="field"> <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> <label>Estimated Cost: <span class="required">*</span></label>
<div class="cost-selector" id="cost-selector"> <div class="cost-selector" id="cost-selector">
<span class="dollar" data-value="1">$</span> <span class="dollar" data-value="1">$</span>
@@ -89,63 +85,78 @@
<input type="hidden" id="cost" value="0"> <input type="hidden" id="cost" value="0">
</div> </div>
</div> </div>
</div> </div>
<!-- Tags --> <!-- Tags -->
<div class="form-section"> <div class="form-section">
<div class="field"> <div class="field">
<label>Tags</label> <label>Tags</label>
<div class="tag-input-row"> <div class="tag-input-row">
<input type="text" id="tag-input" placeholder="Type in a tag and click Add"> <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>
<div class="tag-wrap" id="tag-wrap"></div> <div class="tag-wrap" id="tag-wrap"></div>
</div> </div>
</div> </div>
<div id="form-message" class="form-message" style="display:none;"></div>
<div class="actions"> <div class="actions">
<button class="btn-create" id="publish-btn">CREATE</button> <button class="btn-create" id="publish-btn" type="button">CREATE</button>
</div> </div>
</div> </div>
<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 = [];
// ---- Ingredients ---- // ---- Ingredients ----
const ingredientContainer = document.getElementById('ingredients-container'); document.getElementById('add-ingredient-btn').addEventListener('click', function (e) {
document.getElementById('add-ingredient-btn').addEventListener('click', addIngredient); e.preventDefault();
addIngredient(); // start with one addIngredient();
});
addIngredient();
function addIngredient() { function addIngredient(data = {}) {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'dynamic-row'; row.className = 'dynamic-row';
row.innerHTML = ` row.innerHTML = `
<input type="text" class="ing-name" placeholder="Ingredient (e.g. Sugar)"> <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)"> <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)"> <input type="text" class="ing-unit" placeholder="Unit (e.g. tbsp)" value="${escapeHtml(data.unit || '')}">
<input type="text" class="ing-notes" placeholder="Notes (optional)"> <input type="text" class="ing-notes" placeholder="Notes (optional)" value="${escapeHtml(data.notes || '')}">
<button class="btn-remove" title="Remove">✕</button>`; <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(); row.remove();
}); });
ingredientContainer.appendChild(row); ingredientContainer.appendChild(row);
} }
// ---- Steps ---- // ---- Steps ----
const stepsContainer = document.getElementById('steps-container'); document.getElementById('add-step-btn').addEventListener('click', function (e) {
document.getElementById('add-step-btn').addEventListener('click', addStep); e.preventDefault();
addStep(); // start with one addStep();
});
addStep();
function addStep() { function addStep(data = {}) {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'dynamic-row'; row.className = 'dynamic-row';
row.innerHTML = ` row.innerHTML = `
<div class="step-bubble">?</div> <div class="step-bubble">?</div>
<textarea placeholder="Describe this step..."></textarea> <textarea placeholder="Describe this step...">${escapeHtml(data.instruction || '')}</textarea>
<button class="btn-remove" title="Remove">✕</button> <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(); row.remove();
renumberSteps(); renumberSteps();
}); });
@@ -156,10 +167,10 @@ function addStep() {
function renumberSteps() { function renumberSteps() {
stepsContainer.querySelectorAll('.step-bubble').forEach((bubble, i) => { stepsContainer.querySelectorAll('.step-bubble').forEach((bubble, i) => {
bubble.textContent = i + 1; bubble.textContent = i + 1;
bubble.textContent = i + 1;
}); });
} }
// Cost display
// ---- Cost display ----
const dollars = document.querySelectorAll('.dollar'); const dollars = document.querySelectorAll('.dollar');
dollars.forEach(dollar => { dollars.forEach(dollar => {
@@ -169,6 +180,7 @@ dollars.forEach(dollar => {
dollars.forEach(d => { dollars.forEach(d => {
d.classList.toggle('active', parseInt(d.dataset.value) <= val); d.classList.toggle('active', parseInt(d.dataset.value) <= val);
}); });
clearError(document.getElementById('cost-selector'));
}); });
dollar.addEventListener('mouseover', () => { dollar.addEventListener('mouseover', () => {
@@ -186,53 +198,27 @@ dollars.forEach(dollar => {
}); });
}); });
// ---- Image upload preview ----
// ---- 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');
dropZone.addEventListener('click', () => imgInput.click()); dropZone.addEventListener('click', () => imgInput.click());
imgInput.addEventListener('change', function () { imgInput.addEventListener('change', function () {
if (!this.files || !this.files[0]) return; if (!this.files || !this.files[0]) return;
const url = URL.createObjectURL(this.files[0]); const url = URL.createObjectURL(this.files[0]);
document.getElementById('preview-img').src = url; previewImg.src = url;
dropZone.style.display = 'none'; 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 = ''; imgInput.value = '';
document.getElementById('preview').style.display = 'none'; previewImg.src = '';
previewBox.style.display = 'none';
dropZone.style.display = 'block'; dropZone.style.display = 'block';
}); });
// --- Tags --- // ---- Tags ----
const tags = [];
document.getElementById('tag-input').addEventListener('keydown', function (e) { document.getElementById('tag-input').addEventListener('keydown', function (e) {
if (e.key === 'Enter') { if (e.key === 'Enter') {
e.preventDefault(); e.preventDefault();
@@ -240,12 +226,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() { function addTag() {
const input = document.getElementById('tag-input'); const input = document.getElementById('tag-input');
const val = input.value.trim().toLowerCase().replace(/\s+/g, '-'); 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); tags.push(val);
input.value = ''; input.value = '';
renderTags(); renderTags();
@@ -258,7 +250,7 @@ function removeTag(t) {
function renderTags() { function renderTags() {
document.getElementById('tag-wrap').innerHTML = tags 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(''); .join('');
document.querySelectorAll('.remove-tag').forEach(btn => { document.querySelectorAll('.remove-tag').forEach(btn => {
@@ -266,118 +258,217 @@ function renderTags() {
}); });
} }
async function getLoggedInUser() { // ---- Helpers ----
try { function escapeHtml(str) {
const res = await fetch('http://localhost:8080/api/users/me', { return String(str ?? '')
credentials: 'include' .replace(/&/g, '&amp;')
}); .replace(/</g, '&lt;')
if (!res.ok) throw new Error('Failed to get logged-in user'); .replace(/>/g, '&gt;')
return await res.json(); .replace(/"/g, '&quot;')
} catch (err) { .replace(/'/g, '&#39;');
console.error('Error fetching user:', err); }
return null;
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 = '/';
}, 1500);
}
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 buildRecipeJSON(user) { function clearError(input) {
const title = document.getElementById('title').value.trim(); input.classList.remove('invalid');
const description = document.getElementById('desc').value.trim(); const error = input.parentElement.querySelector('.error-message');
const prepTimeMinutes = Number(document.getElementById('prep').value); if (error) error.remove();
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 clearAllErrors() {
document.querySelectorAll('.invalid').forEach(el => el.classList.remove('invalid'));
document.querySelectorAll('.error-message').forEach(el => el.remove());
const box = document.getElementById('form-message');
box.style.display = 'none';
box.textContent = '';
}
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 costSelector = document.getElementById('cost-selector');
const costValue = Number(document.getElementById('cost').value);
[title, desc, prep, cooking, servings].forEach(clearError);
clearError(costSelector);
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 (!costValue || costValue <= 0) {
showError(costSelector, 'Select an estimated cost');
valid = false;
}
const ingredientRows = [...document.querySelectorAll('#ingredients-container .dynamic-row')];
const filledIngredientRows = ingredientRows.filter(row => row.querySelector('.ing-name').value.trim() !== '');
if (filledIngredientRows.length === 0 && ingredientRows.length > 0) {
showError(ingredientRows[0].querySelector('.ing-name'), 'Add at least one ingredient');
valid = false;
}
filledIngredientRows.forEach(row => {
const nameInput = row.querySelector('.ing-name');
const qtyInput = row.querySelector('.ing-qty');
clearError(nameInput);
clearError(qtyInput);
if (!nameInput.value.trim()) {
showError(nameInput, 'Ingredient name is required');
valid = false;
}
if (!qtyInput.value.trim() || isNaN(Number(qtyInput.value)) || Number(qtyInput.value) <= 0) {
showError(qtyInput, 'Enter a valid quantity');
valid = false;
}
});
const stepAreas = [...document.querySelectorAll('#steps-container textarea')];
const filledSteps = stepAreas.filter(textarea => textarea.value.trim() !== '');
if (filledSteps.length === 0 && 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;
}
// ---- Create recipe with multipart upload ----
document.getElementById('publish-btn').addEventListener('click', async function(e) { document.getElementById('publish-btn').addEventListener('click', async function(e) {
e.preventDefault(); e.preventDefault();
clearAllErrors();
const user = await getLoggedInUser(); if (!validateForm()) {
if (!user) { showMessage('Please fix the highlighted fields and try again.', true);
alert("Unable to fetch logged-in user. Please refresh and try again.");
return; return;
} }
console.log("Logged-in user:", user); const formData = new FormData();
const recipeJSON = buildRecipeJSON(user); formData.append('title', document.getElementById('title').value.trim());
console.log("Recipe JSON to submit:", JSON.stringify(recipeJSON, null, 2)); 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());
document.querySelectorAll('#ingredients-container .dynamic-row').forEach(row => {
const ingredientName = row.querySelector('.ing-name').value.trim();
if (!ingredientName) return;
formData.append('ingredientName', ingredientName);
formData.append('ingredientQuantity', row.querySelector('.ing-qty').value.trim());
formData.append('ingredientUnit', row.querySelector('.ing-unit').value.trim());
formData.append('ingredientNotes', row.querySelector('.ing-notes').value.trim());
});
document.querySelectorAll('#steps-container textarea').forEach(textarea => {
const instruction = textarea.value.trim();
if (instruction) {
formData.append('stepInstruction', instruction);
}
});
tags.forEach(tag => formData.append('tags', tag));
if (imgInput.files && imgInput.files[0]) {
formData.append('image', imgInput.files[0]);
}
try { try {
const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content'); const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content'); const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
const res = await fetch('/api/recipes/upload', {
const res = await fetch('http://localhost:8080/api/recipes', {
method: 'POST', method: 'POST',
headers: { headers: {
[csrfHeader]: csrfToken, [csrfHeader]: csrfToken
'Content-Type': 'application/json'
}, },
body: JSON.stringify(recipeJSON), body: formData,
credentials: 'include' credentials: 'include'
}); });
const responseText = await res.text();
if (res.ok) { if (res.ok) {
const data = await res.json(); showSuccessAndRedirect('Recipe created successfully!');
console.log("Recipe created:", data);
alert("Recipe created successfully!");
} else { } else {
const errorData = await res.json(); console.error('Recipe creation failed:', responseText);
console.error("Validation errors:", errorData); showMessage(responseText || 'Failed to create recipe.', true);
const firstError = Object.values(errorData)[0];
alert(firstError);
} }
} catch (err) { } catch (err) {
console.error("Network error:", err); console.error('Network error:', err);
alert("Network error. Check console for details."); showMessage('Network error. Please try again.', true);
} }
}); });
</script> </script>
</body> </body>
</html> </html>