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
@@ -19,15 +19,23 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http http
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
.requestMatchers("/login", "/register", "/css/**", "/images/**").permitAll() // public pages and static files
.requestMatchers("/", "/login", "/register", "/css/**", "/images/**").permitAll()
.requestMatchers("/api/users").permitAll() .requestMatchers("/api/users").permitAll()
.requestMatchers("/users/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN") .requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
// protected create recipe routes
.requestMatchers("/create", "/api/recipes/upload").authenticated()
// protected my profile routes
.requestMatchers("/my-profile", "/my-profile/update").authenticated()
// everything else public
.anyRequest().permitAll()
) )
.formLogin(form -> form .formLogin(form -> form
.loginPage("/login") .loginPage("/login")
.defaultSuccessUrl("/", true) .defaultSuccessUrl("/")
.permitAll() .permitAll()
) )
.logout(logout -> logout.permitAll()); .logout(logout -> logout.permitAll());
@@ -0,0 +1,20 @@
package com.example.demo.config;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
Path uploadPath = Paths.get("uploads").toAbsolutePath().normalize();
registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:///" + uploadPath.toString().replace("\\", "/") + "/");
}
}
@@ -0,0 +1,212 @@
package com.example.demo.controller;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.dto.ImageDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.RecipeIngredientDto;
import com.example.demo.dto.StepDto;
import com.example.demo.dto.TagDto;
import com.example.demo.service.RecipeService;
@RestController
public class RecipeUploadController {
private final RecipeService recipeService;
public RecipeUploadController(RecipeService recipeService) {
this.recipeService = recipeService;
}
@PostMapping(value = "/api/recipes/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> createRecipeWithUpload(@ModelAttribute RecipeUploadForm form, Principal principal) {
try {
System.out.println("UPLOAD ENDPOINT HIT");
System.out.println("Title: " + form.getTitle());
System.out.println("Image present: " + (form.getImage() != null && !form.getImage().isEmpty()));
RecipeDto dto = buildRecipeDto(form, true);
System.out.println("Image DTO count: " + (dto.getImages() == null ? 0 : dto.getImages().size()));
String currentUsername = principal.getName();
RecipeDto saved = recipeService.saveRecipe(dto, currentUsername);
System.out.println("Saved recipe id: " + saved.getId());
return new ResponseEntity<>(saved, HttpStatus.CREATED);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Recipe creation failed: " + e.getMessage());
}
}
@PostMapping(value = "/api/recipes/{id}/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> updateRecipeWithUpload(
@PathVariable Integer id,
@ModelAttribute RecipeUploadForm form,
Principal principal) {
try {
System.out.println("UPDATE UPLOAD ENDPOINT HIT");
System.out.println("Recipe id: " + id);
System.out.println("Title: " + form.getTitle());
System.out.println("Image present: " + (form.getImage() != null && !form.getImage().isEmpty()));
System.out.println("Remove image: " + form.getRemoveImage());
RecipeDto dto = buildRecipeDto(form, false);
String currentUsername = principal.getName();
RecipeDto updated = recipeService.updateRecipe(dto, id, currentUsername);
System.out.println("Updated recipe id: " + updated.getId());
return new ResponseEntity<>(updated, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Recipe update failed: " + e.getMessage());
}
}
private RecipeDto buildRecipeDto(RecipeUploadForm form, boolean isCreate) throws IOException {
RecipeDto dto = new RecipeDto();
dto.setTitle(safeTrim(form.getTitle()));
dto.setDescription(safeTrim(form.getDescription()));
dto.setPrepTimeMinutes(parseInteger(form.getPrepTimeMinutes()));
dto.setCookTimeMinutes(parseInteger(form.getCookTimeMinutes()));
dto.setServings(parseInteger(form.getServings()));
dto.setStatus("DRAFT");
dto.setCost(parseInteger(form.getCost()));
List<RecipeIngredientDto> ingredientDtos = new ArrayList<>();
if (form.getIngredientName() != null) {
for (int i = 0; i < form.getIngredientName().size(); i++) {
String ingredientName = getListValue(form.getIngredientName(), i);
if (ingredientName == null || ingredientName.isBlank()) {
continue;
}
String quantityString = getListValue(form.getIngredientQuantity(), i);
BigDecimal quantity = null;
if (quantityString != null && !quantityString.isBlank()) {
quantity = new BigDecimal(quantityString.trim());
}
String unit = getListValue(form.getIngredientUnit(), i);
String notes = getListValue(form.getIngredientNotes(), i);
ingredientDtos.add(new RecipeIngredientDto(
ingredientName.trim(),
quantity,
unit != null ? unit.trim() : "",
notes != null ? notes.trim() : ""));
}
}
dto.setIngredients(ingredientDtos);
List<StepDto> stepDtos = new ArrayList<>();
if (form.getStepInstruction() != null) {
for (int i = 0; i < form.getStepInstruction().size(); i++) {
String instruction = form.getStepInstruction().get(i);
if (instruction == null || instruction.isBlank()) {
continue;
}
stepDtos.add(new StepDto(i + 1, instruction.trim()));
}
}
dto.setSteps(stepDtos);
List<TagDto> tagDtos = new ArrayList<>();
if (form.getTags() != null) {
for (String tag : form.getTags()) {
if (tag != null && !tag.isBlank()) {
tagDtos.add(new TagDto(tag.trim()));
}
}
}
dto.setTags(tagDtos);
MultipartFile imageFile = form.getImage();
boolean removeImage = Boolean.TRUE.equals(form.getRemoveImage());
if (imageFile != null && !imageFile.isEmpty()) {
List<ImageDto> imageDtos = new ArrayList<>();
String imageUrl = saveUploadedFile(imageFile);
imageDtos.add(new ImageDto(imageUrl));
dto.setImages(imageDtos);
System.out.println("Saved file path: " + imageUrl);
} else if (removeImage) {
// Empty list means remove all images on update
dto.setImages(new ArrayList<>());
} else if (isCreate) {
dto.setImages(new ArrayList<>());
} else {
// Null on update means keep the existing image as-is
dto.setImages(null);
}
return dto;
}
private Integer parseInteger(String value) {
if (value == null || value.isBlank()) {
return null;
}
return Integer.valueOf(value.trim());
}
private String getListValue(List<String> list, int index) {
if (list == null || index >= list.size()) {
return null;
}
return list.get(index);
}
private String safeTrim(String value) {
return value == null ? null : value.trim();
}
private String saveUploadedFile(MultipartFile file) throws IOException {
String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
String extension = "";
int dotIndex = originalFilename.lastIndexOf('.');
if (dotIndex >= 0) {
extension = originalFilename.substring(dotIndex);
}
String storedFilename = UUID.randomUUID() + extension;
Path uploadDir = Paths.get("uploads");
if (!Files.exists(uploadDir)) {
Files.createDirectories(uploadDir);
}
Path destination = uploadDir.resolve(storedFilename);
Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
return "/uploads/" + storedFilename;
}
}
@@ -0,0 +1,141 @@
package com.example.demo.controller;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class RecipeUploadForm {
private String title;
private String description;
private String prepTimeMinutes;
private String cookTimeMinutes;
private String servings;
private String cost;
private List<String> ingredientName;
private List<String> ingredientQuantity;
private List<String> ingredientUnit;
private List<String> ingredientNotes;
private List<String> stepInstruction;
private List<String> tags;
private MultipartFile image;
private Boolean removeImage;
public RecipeUploadForm() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrepTimeMinutes() {
return prepTimeMinutes;
}
public void setPrepTimeMinutes(String prepTimeMinutes) {
this.prepTimeMinutes = prepTimeMinutes;
}
public String getCookTimeMinutes() {
return cookTimeMinutes;
}
public void setCookTimeMinutes(String cookTimeMinutes) {
this.cookTimeMinutes = cookTimeMinutes;
}
public String getServings() {
return servings;
}
public void setServings(String servings) {
this.servings = servings;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public List<String> getIngredientName() {
return ingredientName;
}
public void setIngredientName(List<String> ingredientName) {
this.ingredientName = ingredientName;
}
public List<String> getIngredientQuantity() {
return ingredientQuantity;
}
public void setIngredientQuantity(List<String> ingredientQuantity) {
this.ingredientQuantity = ingredientQuantity;
}
public List<String> getIngredientUnit() {
return ingredientUnit;
}
public void setIngredientUnit(List<String> ingredientUnit) {
this.ingredientUnit = ingredientUnit;
}
public List<String> getIngredientNotes() {
return ingredientNotes;
}
public void setIngredientNotes(List<String> ingredientNotes) {
this.ingredientNotes = ingredientNotes;
}
public List<String> getStepInstruction() {
return stepInstruction;
}
public void setStepInstruction(List<String> stepInstruction) {
this.stepInstruction = stepInstruction;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public Boolean getRemoveImage() {
return removeImage;
}
public void setRemoveImage(Boolean removeImage) {
this.removeImage = removeImage;
}
}
@@ -4,11 +4,16 @@ import java.util.List;
import com.example.demo.service.RecipeService; import com.example.demo.service.RecipeService;
import com.example.demo.dto.RecipeDto; import com.example.demo.dto.RecipeDto;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller @Controller
public class SiteController { public class SiteController {
@@ -55,6 +60,13 @@ public class SiteController {
return "update-recipe"; return "update-recipe";
} }
@GetMapping("/update-recipe/{id}")
public String showUpdateRecipePage(@PathVariable Integer id, Model model) {
RecipeDto recipe = recipeService.getRecipeById(id);
model.addAttribute("recipe", recipe);
return "update-recipe";
}
@GetMapping("/explore") @GetMapping("/explore")
public String explore( public String explore(
@RequestParam(required = false) String q, @RequestParam(required = false) String q,
@@ -70,4 +82,11 @@ public class SiteController {
model.addAttribute("tags", tags); model.addAttribute("tags", tags);
return "explore"; return "explore";
} }
}
@PostMapping("/api/recipes/{id}/image")
@ResponseBody
public ResponseEntity<?> updateRecipeImage(@PathVariable Integer id,
@RequestParam("image") MultipartFile image) {
recipeService.updateRecipeImage(id, image);
return ResponseEntity.ok().build();
}}
@@ -7,6 +7,7 @@ import java.util.stream.Collectors;
import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.dto.RecipeDto; import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.UserDto; import com.example.demo.dto.UserDto;
@@ -57,6 +58,13 @@ public class RecipeServiceImpl implements RecipeService {
this.tagRepository = tagRepository; this.tagRepository = tagRepository;
} }
@Override
public void updateRecipeImage(Integer id, MultipartFile image) {
if (image == null || image.isEmpty()) {
return;
}
}
@Override @Override
public RecipeDto convertToDto(Recipe recipe) { public RecipeDto convertToDto(Recipe recipe) {
List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream() List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream()
@@ -236,6 +244,7 @@ public class RecipeServiceImpl implements RecipeService {
List<TagDto> updatedTags = recipeDto.getTags(); List<TagDto> updatedTags = recipeDto.getTags();
List<Tag> tagsToRemove = new ArrayList<>(); List<Tag> tagsToRemove = new ArrayList<>();
if (updatedIngredients != null) {
for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) { for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) {
boolean existsInUpdatedList = false; boolean existsInUpdatedList = false;
@@ -243,7 +252,7 @@ public class RecipeServiceImpl implements RecipeService {
String updatedName = dto.getIngredientName(); String updatedName = dto.getIngredientName();
String existingName = ri.getIngredient().getName(); String existingName = ri.getIngredient().getName();
if (updatedName.equals(existingName)) { if (java.util.Objects.equals(updatedName, existingName)) {
existsInUpdatedList = true; existsInUpdatedList = true;
break; break;
} }
@@ -259,7 +268,8 @@ public class RecipeServiceImpl implements RecipeService {
for (RecipeIngredientDto riDto : updatedIngredients) { for (RecipeIngredientDto riDto : updatedIngredients) {
RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream() RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
.filter(ri -> ri.getIngredient().getName().equals(riDto.getIngredientName())).findFirst() .filter(ri -> java.util.Objects.equals(ri.getIngredient().getName(), riDto.getIngredientName()))
.findFirst()
.orElse(null); .orElse(null);
if (existingRI != null) { if (existingRI != null) {
@@ -284,6 +294,7 @@ public class RecipeServiceImpl implements RecipeService {
existingRecipe.getRecipeIngredients().add(newRI); existingRecipe.getRecipeIngredients().add(newRI);
} }
} }
}
if (updatedSteps != null) { if (updatedSteps != null) {
for (Step step : existingRecipe.getSteps()) { for (Step step : existingRecipe.getSteps()) {
@@ -314,7 +325,7 @@ public class RecipeServiceImpl implements RecipeService {
if (updatedImages != null) { if (updatedImages != null) {
for (Image image : existingRecipe.getImages()) { for (Image image : existingRecipe.getImages()) {
boolean existsInUpdatedList = updatedImages.stream() boolean existsInUpdatedList = updatedImages.stream()
.anyMatch(dto -> dto.getImageUrl().equals(image.getImageUrl())); .anyMatch(dto -> java.util.Objects.equals(dto.getImageUrl(), image.getImageUrl()));
if (!existsInUpdatedList) if (!existsInUpdatedList)
imagesToRemove.add(image); imagesToRemove.add(image);
} }
@@ -323,7 +334,9 @@ public class RecipeServiceImpl implements RecipeService {
for (ImageDto imageDto : updatedImages) { for (ImageDto imageDto : updatedImages) {
Image existingImage = existingRecipe.getImages().stream() Image existingImage = existingRecipe.getImages().stream()
.filter(img -> img.getImageUrl().equals(imageDto.getImageUrl())).findFirst().orElse(null); .filter(img -> java.util.Objects.equals(img.getImageUrl(), imageDto.getImageUrl()))
.findFirst()
.orElse(null);
if (existingImage != null) { if (existingImage != null) {
existingImage.setImageUrl(imageDto.getImageUrl()); existingImage.setImageUrl(imageDto.getImageUrl());
@@ -336,7 +349,8 @@ public class RecipeServiceImpl implements RecipeService {
if (updatedTags != null) { if (updatedTags != null) {
for (Tag tag : existingRecipe.getTags()) { for (Tag tag : existingRecipe.getTags()) {
boolean existsInUpdatedList = updatedTags.stream().anyMatch(dto -> dto.getName().equals(tag.getName())); boolean existsInUpdatedList = updatedTags.stream()
.anyMatch(dto -> java.util.Objects.equals(dto.getName(), tag.getName()));
if (!existsInUpdatedList) if (!existsInUpdatedList)
tagsToRemove.add(tag); tagsToRemove.add(tag);
} }
@@ -345,7 +359,9 @@ public class RecipeServiceImpl implements RecipeService {
for (TagDto tagDto : updatedTags) { for (TagDto tagDto : updatedTags) {
Tag existingTag = existingRecipe.getTags().stream() Tag existingTag = existingRecipe.getTags().stream()
.filter(tag -> tag.getName().equals(tagDto.getName())).findFirst().orElse(null); .filter(tag -> java.util.Objects.equals(tag.getName(), tagDto.getName()))
.findFirst()
.orElse(null);
if (existingTag != null) { if (existingTag != null) {
existingTag.setName(tagDto.getName()); existingTag.setName(tagDto.getName());
@@ -3,6 +3,7 @@ package com.example.demo.service;
import java.util.List; import java.util.List;
import org.jspecify.annotations.Nullable; import org.jspecify.annotations.Nullable;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.dto.RecipeDto; import com.example.demo.dto.RecipeDto;
import com.example.demo.entity.Recipe; import com.example.demo.entity.Recipe;
@@ -23,5 +24,6 @@ public interface RecipeService {
void deleteRecipe(Integer Id, String currentUsername); void deleteRecipe(Integer Id, String currentUsername);
} void updateRecipeImage(Integer id, MultipartFile image);
}
@@ -18,3 +18,8 @@ spring.jpa.open-in-view=false
#spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect #spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
server.port=8080 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; margin: 0;
font-family: 'Mali', cursive; font-family: 'Mali', cursive;
background-color: var(--pale-yellow); background-color: var(--pale-yellow);
overflow: clip; overflow-x: hidden;
overflow-y: auto;
} }
/* ========================= /* =========================
@@ -73,9 +73,12 @@
<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>
@@ -153,6 +156,7 @@ 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
@@ -184,6 +188,7 @@ dollars.forEach(dollar => {
// ---- Collecting on submit ---- // ---- Collecting on submit ----
// Call this wherever you build your POST payload:
function getIngredients() { function getIngredients() {
return [...ingredientContainer.querySelectorAll('.dynamic-row')].map(row => { return [...ingredientContainer.querySelectorAll('.dynamic-row')].map(row => {
qtyValue = row.querySelector('.ing-qty').value.trim(); // quantity should be a number NOT A STRING qtyValue = row.querySelector('.ing-qty').value.trim(); // quantity should be a number NOT A STRING
+3 -8
View File
@@ -4,7 +4,7 @@
<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>Explore - Thyme Crunch</title> <title>Thyme Crunch Home</title>
<link rel="stylesheet" th:href="@{css/explore.css}"> <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 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"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
@@ -65,10 +65,11 @@
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}"> <div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image"> <img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div> </div>
<p class="card-cost" th:text="${recipe.cost}">Cost</p> <p th:text="${recipe.cost}">Cost</p>
</div> </div>
</a> </a>
</div> </div>
</main> </main>
<!--Filter --> <!--Filter -->
@@ -234,12 +235,6 @@
window.location.href = '/explore?' + out.toString(); 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> </script>
</body> </body>
+2 -11
View File
@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Home - Thyme Crunch</title> <title>Thyme Crunch Home</title>
<link rel="stylesheet" th:href="@{css/home.css}"> <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"> <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>
@@ -38,7 +38,6 @@
<!-- Main Content --> <!-- Main Content -->
<main class="main-content"> <main class="main-content">
<div class="recipe-card"> <div class="recipe-card">
<p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p> <p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}"> <div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
@@ -51,7 +50,7 @@
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}"> <div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image"> <img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div> </div>
<p class="card-cost" th:text="${recipe.cost}">Cost</p> <p th:text="${recipe.cost}">Cost</p>
</div> </div>
</a> </a>
</div> </div>
@@ -64,13 +63,5 @@
</div> </div>
</div> </div>
</div> </div>
<script>
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
});
</script>
</body> </body>
</html> </html>
+2 -9
View File
@@ -54,9 +54,9 @@
</div> </div>
<div class="card-right"> <div class="card-right">
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}"> <div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image"> <img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image" style="max-width: 200px;">
</div> </div>
<p class="card-cost" th:text="${recipe.cost}"><b>Cost</b></p> <p th:text="${recipe.cost}">Cost</p>
</div> </div>
</a> </a>
<a th:href="@{/recipes/{id}/edit(id=${recipe.id})}" class="edit-link">Edit</a> <a th:href="@{/recipes/{id}/edit(id=${recipe.id})}" class="edit-link">Edit</a>
@@ -91,12 +91,5 @@
</div> </div>
<script>
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
});
</script>
</body> </body>
</html> </html>
@@ -4,16 +4,16 @@
<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>My Profile - Thyme Crunch</title> <title>Profile - Thyme Crunch</title>
<link rel="stylesheet" th:href="@{css/my-profile.css}"> <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"> <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="body"> <div class="body">
@@ -27,22 +27,22 @@
<li><a th:href="@{/my-profile}">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li> <li>
<form th:action="@{/logout}" method="post"> <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> </form>
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon"> <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> </a>
</div> </div>
<!-- Main Content — recipes --> <!-- Main Content — recipes -->
<main class="main-content"> <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)}"> <div class="recipe-card" th:unless="${#lists.isEmpty(profile.recipes)}">
<th:block th:each="recipe : ${profile.recipes}"> <th:block th:each="recipe : ${profile.recipes}">
@@ -54,7 +54,7 @@
</div> </div>
<div class="card-right"> <div class="card-right">
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}"> <div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image"> <img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image" style="max-width: 200px;">
</div> </div>
<p th:text="${recipe.cost}">Cost</p> <p th:text="${recipe.cost}">Cost</p>
</div> </div>
@@ -65,27 +65,12 @@
</main> </main>
<!-- Right Sidebar — profile info & edit --> <!-- Right Sidebar — public profile info only -->
<div class="body-right"> <div class="body-right">
<div class="sidebar-right"> <div class="sidebar-right">
<p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p> <p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p>
<p th:text="'@' + ${profile.username}">@username</p> <p th:text="'@' + ${profile.username}">@username</p>
<p th:if="${profile.bio != null}" th:text="${profile.bio}">Bio goes here.</p> <p th:if="${profile.bio != null and !#strings.isEmpty(profile.bio)}" 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>
</div> </div>
</div> </div>
+281 -151
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>Update 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">
@@ -21,7 +21,7 @@
<!-- Main Content --> <!-- Main Content -->
<div class="form-section"> <div class="form-section">
<div class="section-title">New Recipe</div> <div class="section-title">Update Recipe</div>
<div class="field"> <div class="field">
<label for="title">Title <span class="required">*</span></label> <label for="title">Title <span class="required">*</span></label>
@@ -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>
@@ -84,59 +83,76 @@
<!-- 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">UPDATE</button>
</div>
</div> </div>
</div> <script th:inline="javascript">
const existingRecipe = /*[[${recipe}]]*/ null;
</script>
<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 ---- // ---- 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();
});
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();
});
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();
}); });
@@ -150,52 +166,30 @@ function renumberSteps() {
}); });
} }
// ---- Collecting on submit ---- // ---- Image upload preview ----
// 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;
imageRemoved = false;
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';
imageRemoved = true;
}); });
// --- 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();
@@ -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() { 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();
@@ -221,7 +221,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 => {
@@ -229,118 +229,248 @@ 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;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
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());
}
}); });
if (!res.ok) throw new Error('Failed to get logged-in user'); renderTags();
return await res.json(); }
} catch (err) {
console.error('Error fetching user:', err); imageRemoved = false;
return null;
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';
} }
} }
function buildRecipeJSON(user) { // ---- Inline validation ----
const title = document.getElementById('title').value.trim(); function showError(input, message) {
const description = document.getElementById('desc').value.trim(); input.classList.add('invalid');
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 let error = input.parentElement.querySelector('.error-message');
const recipeIngredients = [...document.querySelectorAll('#ingredients-container .dynamic-row')] if (!error) {
.map(row => { error = document.createElement('p');
const qtyValue = Number(row.querySelector('.ing-qty').value.trim()); error.className = 'error-message';
return { error.style.color = 'red';
ingredient: { name: row.querySelector('.ing-name').value.trim() }, error.style.fontSize = '0.9em';
quantity: qtyValue, error.style.marginTop = '6px';
unit: row.querySelector('.ing-unit').value.trim(), input.parentElement.appendChild(error);
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
};
} }
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) { document.getElementById('publish-btn').addEventListener('click', async function(e) {
e.preventDefault(); e.preventDefault();
const user = await getLoggedInUser(); if (!existingRecipe || !existingRecipe.id) {
if (!user) { showMessage('Recipe data was not loaded correctly.', true);
alert("Unable to fetch logged-in user. Please refresh and try again.");
return; return;
} }
console.log("Logged-in user:", user); if (!validateForm()) {
const recipeJSON = buildRecipeJSON(user); return;
console.log("Recipe JSON to submit:", JSON.stringify(recipeJSON, null, 2)); }
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);
}
});
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/${existingRecipe.id}/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 updated successfully!');
console.log("Recipe created:", data);
alert("Recipe created successfully!");
} else { } else {
const errorData = await res.json(); console.error('Recipe update failed:', responseText);
console.error("Validation errors:", errorData); showMessage(responseText || 'Failed to update 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. Check console for details.', true);
} }
}); });
</script> </script>
</body> </body>
</html> </html>
+98 -24
View File
@@ -1,64 +1,138 @@
<!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">
<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 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"> <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="Left header swirl" 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="Right header swirl" class="swirl">
</header> </header>
<div class="body"> <div class="body">
<!--Navigation Bar --> <!--Navigation Bar -->
<div class="body-left"> <div class="body-left">
<nav class="sidebar-left"> <nav class="sidebar-left">
<ul> <ul>
<li><a href="#">Home</a></li> <li><a href="/">Home</a></li>
<li><a href="#">Explore</a></li> <li><a th:href="@{/explore}">Explore</a></li>
<li><a href="#">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li><a href="#">Saved</a></li>
<li> <li>
<form th:action="@{/logout}" method="post"> <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> </form>
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon"> <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> </a>
</div> </div>
<!-- Main Content --> <!-- Main Content -->
<main class="main-content"> <main class="main-content">
<div class="form-wrap"> <div th:if="${recipe != null}" style="width: 100%; max-width: 950px; margin: 35px auto;">
<h1 th:text="${recipe.title}"></h1>
<p th:text="${recipe.description}"></p>
<div class="form-section"> <section style="background: var(--peach); border-radius: 20px; padding: 18px 24px; color: var(--dark);">
<div class="section-title">Ingredients</div> <h1 style="margin-top: 0; font-size: 2.8em;" th:text="${recipe.title}">Recipe Title</h1>
<ul>
<li th:each="ingredient : ${recipe.ingredients}" <p th:if="${recipe.userDto != null}" style="font-size: 1.2em; margin-bottom: 20px;">
th:text="${ingredient.name}"></li> <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> </ul>
<p th:unless="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}">No ingredients listed.</p>
</div> </div>
<div class="form-section"> <div style="margin-bottom: 30px;">
<div class="section-title">Instructions</div> <h2>Steps</h2>
<ol class="step-list"> <ol th:if="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}" style="line-height: 1.9;">
<li th:each="step : ${#lists.sort(recipe.steps, comparingInt(step -> step.stepNumber))}"> <li th:each="step : ${recipe.steps}" th:text="${step.instruction}">Step instruction</li>
</ol </ol>
<p th:unless="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}">No steps listed.</p>
</div> </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> </div>
</main> </main>
<!-- Right spacer/sidebar -->
<div class="body-right">
<div class="sidebar-right"></div>
</div> </div>
</div>
</body> </body>
</html> </html>