Update 13 files

- /src/main/java/com/example/demo/service/Impl/UserServiceImpl.java
- /src/main/java/com/example/demo/service/Impl/RecipeServiceImpl.java
- /src/main/java/com/example/demo/service/UserService.java
- /src/main/java/com/example/demo/controller/SiteController.java
- /src/main/java/com/example/demo/controller/RecipeUploadForm.java
- /src/main/java/com/example/demo/controller/ProfileController.java
- /src/main/java/com/example/demo/config/SecurityConfig.java
- /src/main/java/com/example/demo/config/WebConfig.java
- /src/main/resources/templates/explore.html
- /src/main/resources/templates/view-recipe.html
- /src/main/resources/templates/public-profile.html
- /src/main/resources/templates/my-profile.html
- /src/main/resources/templates/home.html
This commit is contained in:
Madeleine Stamp
2026-04-23 12:33:42 -06:00
parent 2ed5f11b21
commit 339cbbdf6e
13 changed files with 556 additions and 304 deletions
@@ -19,18 +19,11 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
// public pages and static files
.requestMatchers("/", "/login", "/register", "/css/**", "/images/**").permitAll()
.requestMatchers("/", "/login", "/register", "/css/**", "/images/**", "/uploads/**").permitAll()
.requestMatchers("/api/users").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
// 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
@@ -3,6 +3,7 @@ package com.example.demo.config;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -10,11 +11,14 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${app.upload.dir}")
private String uploadDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
Path uploadPath = Paths.get("uploads").toAbsolutePath().normalize();
Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:///" + uploadPath.toString().replace("\\", "/") + "/");
.addResourceLocations(uploadPath.toUri().toString());
}
}
@@ -23,9 +23,10 @@ public class ProfileController {
}
@GetMapping("/users/{id}")
public String viewPublicProfile(@PathVariable Integer id, Model model) {
public String viewPublicProfile(@PathVariable Integer id, Model model, Principal principal) {
ProfileDto profile = userService.getProfileByUserId(id);
model.addAttribute("profile", profile);
model.addAttribute("guest", principal == null);
return "public-profile";
}
@@ -52,3 +53,18 @@ public class ProfileController {
return "redirect:/my-profile";
}
}
updateProfileDto.setBio(profile.getBio());
model.addAttribute("profile", profile);
model.addAttribute("updateProfileDto", updateProfileDto);
return "my-profile";
}
@PostMapping("/my-profile/update")
public String updateMyProfile(@ModelAttribute UpdateProfileDto dto, Principal principal) {
String username = principal.getName();
userService.updateProfile(username, dto);
return "redirect:/my-profile";
}
}
@@ -1,141 +1,233 @@
package com.example.demo.controller;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
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;
public class RecipeUploadForm {
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;
private String title;
private String description;
private String prepTimeMinutes;
private String cookTimeMinutes;
private String servings;
private String cost;
@RestController
public class RecipeUploadController {
private List<String> ingredientName;
private List<String> ingredientQuantity;
private List<String> ingredientUnit;
private List<String> ingredientNotes;
private final RecipeService recipeService;
private List<String> stepInstruction;
private List<String> tags;
private MultipartFile image;
private Boolean removeImage;
public RecipeUploadForm() {
public RecipeUploadController(RecipeService recipeService) {
this.recipeService = recipeService;
}
public String getTitle() {
return title;
@PostMapping(value = "/api/recipes/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> createRecipeWithUpload(@ModelAttribute RecipeUploadForm form, Principal principal) {
try {
RecipeDto dto = buildRecipeDto(form, true);
String currentUsername = principal.getName();
RecipeDto saved = recipeService.saveRecipe(dto, currentUsername);
return new ResponseEntity<>(saved, HttpStatus.CREATED);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Recipe creation failed: " + e.getMessage());
}
}
public void setTitle(String title) {
this.title = title;
@PostMapping(value = "/api/recipes/{id}/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> updateRecipeWithUpload(
@PathVariable Integer id,
@ModelAttribute RecipeUploadForm form,
Principal principal) {
try {
RecipeDto dto = buildRecipeDto(form, false);
String currentUsername = principal.getName();
RecipeDto updated = recipeService.updateRecipe(dto, id, currentUsername);
return new ResponseEntity<>(updated, HttpStatus.OK);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Recipe update failed: " + e.getMessage());
}
}
public String getDescription() {
return description;
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;
}
public void setDescription(String description) {
this.description = description;
String quantityString = getListValue(form.getIngredientQuantity(), i);
BigDecimal quantity = null;
if (quantityString != null && !quantityString.isBlank()) {
quantity = parseQuantity(quantityString.trim());
}
public String getPrepTimeMinutes() {
return prepTimeMinutes;
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);
} else if (removeImage) {
dto.setImages(new ArrayList<>());
} else if (isCreate) {
dto.setImages(new ArrayList<>());
} else {
dto.setImages(null);
}
public void setPrepTimeMinutes(String prepTimeMinutes) {
this.prepTimeMinutes = prepTimeMinutes;
return dto;
}
public String getCookTimeMinutes() {
return cookTimeMinutes;
private Integer parseInteger(String value) {
if (value == null || value.isBlank()) {
return null;
}
return Integer.valueOf(value.trim());
}
public void setCookTimeMinutes(String cookTimeMinutes) {
this.cookTimeMinutes = cookTimeMinutes;
private String getListValue(List<String> list, int index) {
if (list == null || index >= list.size()) {
return null;
}
return list.get(index);
}
public String getServings() {
return servings;
private String safeTrim(String value) {
return value == null ? null : value.trim();
}
public void setServings(String servings) {
this.servings = servings;
private BigDecimal parseQuantity(String value) {
String cleaned = value.trim();
if (cleaned.matches("^\\d+(\\.\\d+)?$")) {
return new BigDecimal(cleaned);
}
public String getCost() {
return cost;
if (cleaned.matches("^\\d+/\\d+$")) {
String[] parts = cleaned.split("/");
BigDecimal numerator = new BigDecimal(parts[0]);
BigDecimal denominator = new BigDecimal(parts[1]);
if (denominator.compareTo(BigDecimal.ZERO) == 0) {
throw new IllegalArgumentException("Ingredient quantity cannot have a zero denominator.");
}
public void setCost(String cost) {
this.cost = cost;
return numerator.divide(denominator, 8, RoundingMode.HALF_UP).stripTrailingZeros();
}
public List<String> getIngredientName() {
return ingredientName;
if (cleaned.matches("^\\d+\\s+\\d+/\\d+$")) {
String[] mixed = cleaned.split("\\s+");
BigDecimal whole = new BigDecimal(mixed[0]);
String[] fraction = mixed[1].split("/");
BigDecimal numerator = new BigDecimal(fraction[0]);
BigDecimal denominator = new BigDecimal(fraction[1]);
if (denominator.compareTo(BigDecimal.ZERO) == 0) {
throw new IllegalArgumentException("Ingredient quantity cannot have a zero denominator.");
}
public void setIngredientName(List<String> ingredientName) {
this.ingredientName = ingredientName;
BigDecimal fractionalPart = numerator.divide(denominator, 8, RoundingMode.HALF_UP);
return whole.add(fractionalPart).stripTrailingZeros();
}
public List<String> getIngredientQuantity() {
return ingredientQuantity;
throw new IllegalArgumentException(
"Invalid ingredient quantity: " + value + ". Use values like 1, 1.5, 1/4, or 2 1/2.");
}
public void setIngredientQuantity(List<String> ingredientQuantity) {
this.ingredientQuantity = ingredientQuantity;
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);
}
public List<String> getIngredientUnit() {
return ingredientUnit;
String storedFilename = UUID.randomUUID() + extension;
Path uploadDir = Paths.get("uploads");
if (!Files.exists(uploadDir)) {
Files.createDirectories(uploadDir);
}
public void setIngredientUnit(List<String> ingredientUnit) {
this.ingredientUnit = ingredientUnit;
}
Path destination = uploadDir.resolve(storedFilename);
Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
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;
return "/uploads/" + storedFilename;
}
}
@@ -1,9 +1,11 @@
package com.example.demo.controller;
import java.security.Principal;
import java.util.List;
import com.example.demo.service.RecipeService;
import com.example.demo.dto.RecipeDto;
import com.example.demo.service.RecipeService;
import com.example.demo.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
@@ -19,22 +21,29 @@ import org.springframework.web.multipart.MultipartFile;
public class SiteController {
private final RecipeService recipeService;
private final UserService userService;
public SiteController(RecipeService recipeService) {
public SiteController(RecipeService recipeService, UserService userService) {
this.recipeService = recipeService;
this.userService = userService;
}
@GetMapping("/")
public String viewHomePage(Model model) {
List<RecipeDto> recipes = recipeService.getAllRecipes();
List<RecipeDto> newest = recipeService.getNewestRecipes(5);
model.addAttribute("recipes", recipes);
model.addAttribute("newestRecipes", newest);
public String viewHomePage(Model model, Principal principal) {
model.addAttribute("guest", principal == null);
if (principal == null) {
model.addAttribute("recipes", List.of());
} else {
model.addAttribute("recipes", userService.getFavoriteRecipesByUsername(principal.getName()));
}
return "home";
}
@GetMapping("/login")
public String viewLoginPage(Model model) {
public String viewLoginPage(@RequestParam(required = false) String redirect, Model model) {
model.addAttribute("redirect", redirect);
return "login";
}
@@ -76,12 +85,14 @@ public class SiteController {
@RequestParam(required = false) List<Integer> prices,
@RequestParam(required = false) List<Integer> cookTime,
@RequestParam(required = false) List<Integer> prepTime,
Model model
Model model,
Principal principal
) {
List<RecipeDto> recipes = recipeService.getRecipes(q, tags, prices, cookTime, prepTime);
model.addAttribute("recipes", recipes);
model.addAttribute("q", q);
model.addAttribute("tags", tags);
model.addAttribute("guest", principal == null);
return "explore";
}
@@ -91,4 +102,5 @@ public class SiteController {
@RequestParam("image") MultipartFile image) {
recipeService.updateRecipeImage(id, image);
return ResponseEntity.ok().build();
}}
}
}
@@ -142,24 +142,56 @@ public class RecipeServiceImpl implements RecipeService {
ensureUserNotBanned(currentUser);
enforceUploadLimit(currentUser);
Recipe recipe = new Recipe(dto.getTitle(), dto.getDescription(), dto.getPrepTimeMinutes(),
dto.getCookTimeMinutes(), dto.getServings(), currentUser, dto.getStatus(), dto.getCost());
Recipe recipe = new Recipe(
dto.getTitle(),
dto.getDescription(),
dto.getPrepTimeMinutes(),
dto.getCookTimeMinutes(),
dto.getServings(),
currentUser,
dto.getStatus(),
dto.getCost()
);
if (dto.getIngredients() != null) {
for (RecipeIngredientDto riDto : dto.getIngredients()) {
java.util.Set<String> seenIngredientNames = new java.util.HashSet<>();
java.util.Set<Integer> seenIngredientIds = new java.util.HashSet<>();
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName())
.orElseGet(() -> new Ingredient(riDto.getIngredientName()));
for (int i = 0; i < dto.getIngredients().size(); i++) {
RecipeIngredientDto riDto = dto.getIngredients().get(i);
String rawName = riDto.getIngredientName();
String normalizedName = rawName == null ? "" : rawName.trim().toLowerCase();
if (normalizedName.isBlank()) {
continue;
}
if (!seenIngredientNames.add(normalizedName)) {
throw new IllegalArgumentException("Duplicate ingredient entry: " + rawName.trim());
}
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(rawName.trim())
.orElseGet(() -> new Ingredient(rawName.trim()));
if (ingredient.getId() == null) {
ingredientRepository.save(ingredient);
}
RecipeIngredient ri = new RecipeIngredient(recipe, ingredient, riDto.getQuantity(), riDto.getUnit(),
riDto.getNotes());
if (ingredient.getId() != null && !seenIngredientIds.add(ingredient.getId())) {
throw new IllegalArgumentException("Duplicate ingredient entry: " + rawName.trim());
}
RecipeIngredient ri = new RecipeIngredient(
recipe,
ingredient,
riDto.getQuantity(),
riDto.getUnit(),
riDto.getNotes()
);
ri.setOrderIndex(i);
recipe.getRecipeIngredients().add(ri);
}
}
@@ -179,7 +211,6 @@ public class RecipeServiceImpl implements RecipeService {
if (dto.getTags() != null) {
for (TagDto tDto : dto.getTags()) {
Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName()));
if (tag.getId() == null) {
@@ -423,7 +454,22 @@ public class RecipeServiceImpl implements RecipeService {
if (prices != null && !prices.isEmpty() && !recipes.isEmpty()) {
recipes = recipes.stream()
.filter(recipe -> prices.contains(recipe.getCost()))
.filter(recipe -> {
Integer cost = recipe.getCost();
if (cost == null) {
return false;
}
for (Integer price : prices) {
if (price == 4 && cost >= 4) {
return true;
}
if (price != 4 && cost.equals(price)) {
return true;
}
}
return false;
})
.collect(Collectors.toList());
}
@@ -7,9 +7,9 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.example.demo.dto.ProfileDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.UpdateProfileDto;
import com.example.demo.dto.UserDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.entity.Recipe;
import com.example.demo.entity.User;
import com.example.demo.exception.NotFoundException;
@@ -220,4 +220,19 @@ public class UserServiceImpl implements UserService {
return getProfileByUserId(user.getId());
}
@Override
@Transactional
public List<RecipeDto> getFavoriteRecipesByUsername(String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new NotFoundException("User", "username", username));
List<RecipeDto> favoriteDtos = new ArrayList<>();
for (Recipe recipe : user.getFavRecipes()) {
favoriteDtos.add(recipeService.convertToDto(recipe));
}
return favoriteDtos;
}
}
@@ -3,6 +3,7 @@ package com.example.demo.service;
import java.util.List;
import com.example.demo.dto.ProfileDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.UpdateProfileDto;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.User;
@@ -39,4 +40,6 @@ public interface UserService {
ProfileDto getCurrentUserProfile(String username);
ProfileDto updateProfile(String username, UpdateProfileDto dto);
List<RecipeDto> getFavoriteRecipesByUsername(String username);
}
+28 -25
View File
@@ -19,40 +19,42 @@
</header>
<div class="body">
<!--Navigation Bar -->
<div class="body-left">
<nav class="sidebar-left">
<ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="${guest} ? @{/login} : @{/}">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<li th:if="${guest}">
<a th:href="@{/login(redirect='/explore')}" class="login-link">Login</a>
</li>
<li th:unless="${guest}">
<form th:action="@{/logout}" method="post">
<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.">
<a th:href="@{/create}" 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.)">
</a>
</div>
</div>
<!-- Main Content -->
<main class="main-content">
<div class="search-bar">
<form action="/explore" method="get" id="search-form">
<label for="site-search">Search:</label>
<div class="search-btn">
<div id="tag-input-wrapper">
<!-- <div id="chips-container"></div> -->
<input type="text" id="site-search" name="q" th:value="${q}" placeholder="Search for recipes...">
</div>
<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)}">
@@ -72,7 +74,6 @@
</main>
<!--Filter -->
<div class="body-right">
<div class="sidebar-right">
<h1> FILTER </h1>
@@ -97,6 +98,7 @@
<label>
<input type="checkbox" name="prepTime" value="241">4+ hours
</label>
<h3>Cook Time</h3>
<label>
@@ -117,6 +119,7 @@
<label>
<input type="checkbox" name="cookTime" value="121">2+ hours
</label>
<h3>Price</h3>
<label>
@@ -138,43 +141,40 @@
</div>
</div>
</div>
<script>
(function () {
const input = document.getElementById('site-search');
const tags = [];
// Restore price checkboxes from URL
const params = new URLSearchParams(window.location.search);
params.getAll('prices').forEach(p => {
const cb = document.querySelector(`input[name="price"][value="${p}"]`);
if (cb) cb.checked = true;
});
// Restore cookTime checkboxes from URL
params.getAll('cookTime').forEach(p => {
const cb = document.querySelector(`input[name="cookTime"][value="${p}"]`);
if (cb) cb.checked = true;
});
// Restore prepTime checkboxes from URL
params.getAll('prepTime').forEach(p => {
const cb = document.querySelector(`input[name="prepTime"][value="${p}"]`);
if (cb) cb.checked = true;
});
// Restore tag chips from URL
params.getAll('tags').forEach(addChip);
input.addEventListener('keydown', (e) => {
if ((e.key === ' ' || e.key === 'Enter') && input.value.includes('#')) {
const val = input.value + ' ';
const match = val.match(/(^|\s)(#\w+)(\s)/); // NASTY regex ):
const match = val.match(/(^|\s)(#\w+)(\s)/);
if (match) {
e.preventDefault();
addChip(match[2].substring(1));
input.value = val.replace(match[0], '');
input.value += ' ';
}
}
});
@@ -193,7 +193,6 @@
document.getElementById('search-form').addEventListener('submit', (e) => {
e.preventDefault();
submitSearch();
});
@@ -216,13 +215,12 @@
}
function submitSearch() {
// Only use chips for tags, not strings!
const cleanedQuery = input.value.replace(/#\w+/g, '').trim();
const out = new URLSearchParams();
if (cleanedQuery) out.set('q', cleanedQuery);
tags.forEach(t => out.append('tags', t));
document.querySelectorAll('input[name="price"]:checked')
.forEach(cb => out.append('prices', cb.value));
@@ -234,12 +232,17 @@
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);
function renderCost(cost) {
const num = parseInt(cost, 10);
if (!num || num <= 0) return '';
if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
});
</script>
+34 -25
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Thyme Crunch Home</title>
<title>Thyme Crunch Favorites</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>
@@ -15,29 +15,40 @@
</header>
<div class="body">
<!--Navigation Bar -->
<div class="body-left">
<nav class="sidebar-left">
<ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="${guest} ? @{/login} : @{/}">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<li th:if="${guest}">
<a th:href="@{/login}" class="login-link">Login</a>
</li>
<li th:unless="${guest}">
<form th:action="@{/logout}" method="post">
<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.">
<a th:href="@{/create}" 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.)">
</a>
</div>
<!-- Main Content -->
<main class="main-content">
<div class="recipe-card">
<div th:if="${guest}" style="text-align:center; padding: 20px 0;">
<p style="margin-bottom:16px;">Log in to view and save your favorite recipes.</p>
<a th:href="@{/login}" style="display:inline-block; padding:10px 18px; background:#850000; color:white; text-decoration:none; border-radius:8px;">
Login
</a>
</div>
<div th:unless="${guest}">
<p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
@@ -54,33 +65,31 @@
</div>
</a>
</div>
</div>
</div>
</main>
<!--New Bar -->
<div class="body-right">
<div class="sidebar-right">
<h1> NEW </h1>
<div class="new-recipes">
<a th:each="recipe : ${newestRecipes}"
th:href="@{/recipes/{id}(id=${recipe.id})}"
class="new-recipe-item">
<p th:text="${recipe.title}">Title</p>
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div>
</a>
</div>
<h1>FAVES</h1>
<p style="text-align:center; padding:0 16px;">
Your saved recipes appear here.
</p>
</div>
</div>
</div>
<script>
// For cost display
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
});
function renderCost(cost) {
const num = parseInt(cost, 10);
if (!num || num <= 0) return '';
if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
});
</script>
</body>
+12 -6
View File
@@ -22,8 +22,8 @@
<div class="body-left">
<nav class="sidebar-left">
<ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li>
<li><a href="/">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<form th:action="@{/logout}" method="post">
@@ -32,7 +32,7 @@
</li>
</ul>
</nav>
<a th:href="@{/create}" target="_blank" class="create_icon">
<a th:href="@{/create}" 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.)">
</a>
</div>
@@ -92,10 +92,16 @@
</div>
<script>
// For cost display
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
// For cost display <!-- Cost change -->
function renderCost(cost) {
const num = parseInt(cost, 10);
if (!num || num <= 0) return '';
if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
});
</script>
@@ -18,28 +18,31 @@
<div class="body">
<!-- Left Navigation -->
<div class="body-left">
<nav class="sidebar-left">
<ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="${guest} ? @{/login} : @{/}">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<li th:if="${guest}">
<a th:href="@{/login}" class="login-link">Login</a>
</li>
<li th:unless="${guest}">
<form th:action="@{/logout}" method="post">
<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">
<a th:href="@{/create}" 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.)">
</a>
</div>
<!-- Main Content — recipes -->
<main class="main-content">
<h2 th:text="${profile.effectiveDisplayName} + '\'s Recipes'">User's Recipes</h2>
<p th:if="${#lists.isEmpty(profile.recipes)}">This user has not created any recipes yet.</p>
@@ -62,10 +65,8 @@
</div>
</th:block>
</div>
</main>
<!-- Right Sidebar — public profile info only -->
<div class="body-right">
<div class="sidebar-right">
<p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p>
@@ -79,10 +80,15 @@
</div>
<script>
// For cost display
document.querySelectorAll('.card-cost').forEach(el => {
const num = parseInt(el.textContent);
el.textContent = num === 0 ? '' : '$'.repeat(num);
function renderCost(cost) {
const num = parseInt(cost, 10);
if (!num || num <= 0) return '';
if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
});
</script>
+56 -9
View File
@@ -18,12 +18,11 @@
<div class="body">
<!--Navigation Bar -->
<div class="body-left">
<nav class="sidebar-left">
<ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li>
<li><a href="/">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<form th:action="@{/logout}" method="post">
@@ -32,12 +31,11 @@
</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.">
<a th:href="@{/create}" 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.)">
</a>
</div>
<!-- Main Content -->
<main class="main-content">
<div th:if="${recipe != null}" class="recipe-container">
<section class="recipe-section">
@@ -93,10 +91,9 @@
<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="${#strings.repeat('$', recipe.cost)}">$</span></p>
<p><strong>Cost:</strong> <span th:text="${recipe.cost >= 4 ? '$$$$' : #strings.repeat('$', recipe.cost)}">$</span></p>
</div>
<div class="recipe-tags">
<h2>Tags: </h2>
<div th:if="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}" class="tag-list">
@@ -111,7 +108,7 @@
</div>
</section>
<button class="save-btn" th:data-recipe-id="${recipe.id}">Save Recipe</button>
<button type="button" class="save-btn" th:data-recipe-id="${recipe.id}">Save Recipe</button>
</div>
<div th:unless="${recipe != null}" class="recipe-not-found">
@@ -120,8 +117,58 @@
</section>
</div>
</main>
</div>
</div>
<script>
async function getCurrentUser() {
const response = await fetch('/api/users/me', {
credentials: 'same-origin'
});
if (!response.ok) {
return null;
}
const user = await response.json();
return user || null;
}
async function saveRecipe(recipeId, button) {
const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.content;
const csrfToken = document.querySelector('meta[name="_csrf"]')?.content;
const user = await getCurrentUser();
if (!user || !user.id) {
window.location.href = '/login';
return;
}
const response = await fetch(`/api/users/${user.id}/favorites/${recipeId}`, {
method: 'POST',
credentials: 'same-origin',
headers: {
...(csrfHeader && csrfToken ? { [csrfHeader]: csrfToken } : {})
}
});
if (!response.ok) {
const text = await response.text();
alert(text || 'Could not save recipe.');
return;
}
button.textContent = 'Saved';
button.disabled = true;
}
document.querySelectorAll('.save-btn').forEach(button => {
button.addEventListener('click', async () => {
const recipeId = button.dataset.recipeId;
await saveRecipe(recipeId, button);
});
});
</script>
</body>
</html>