Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
302419802b | ||
|
|
3f5856c86b | ||
|
|
8c347d124a | ||
|
|
0b69384fb7 | ||
|
|
2d19d9a06f | ||
|
|
70338266f2 | ||
|
|
00ac28aebf | ||
|
|
c9c38f07ad | ||
|
|
7af099f022 | ||
|
|
b4eb339657 | ||
|
|
79443930e2 | ||
|
|
08315359c7 | ||
|
|
b3ec0257d5 | ||
|
|
1dd335e166 | ||
|
|
f33b979bcb | ||
|
|
69389afdb7 | ||
|
|
593c540d81 | ||
|
|
dfff051b55 | ||
|
|
97de073621 | ||
|
|
6c227dcaad | ||
|
|
df90bf21d1 | ||
|
|
5f9ce78476 | ||
|
|
e008e2583e | ||
|
|
f2a5419064 | ||
|
|
a89225fce6 | ||
|
|
9e58b18e43 | ||
|
|
b2badea855 | ||
|
|
d222604fcf | ||
|
|
c99d5f4347 | ||
|
|
9b552b88f8 | ||
|
|
5886777854 | ||
|
|
730248f3e8 | ||
|
|
01dd5c9089 | ||
|
|
9c0d704748 | ||
|
|
e736170735 | ||
|
|
1290df93f6 | ||
|
|
ed05aa3a53 | ||
|
|
e715e66929 | ||
|
|
6233d27d7b | ||
|
|
76a4b201b8 | ||
|
|
4622e91f26 | ||
|
|
c6bc6cf8f9 | ||
|
|
a39eee06e9 | ||
|
|
4137b511bb | ||
|
|
2e11917ea1 | ||
|
|
148c33cf6e | ||
|
|
d9fd91ad8d | ||
|
|
b5293e246c | ||
|
|
b1aa5bec07 | ||
|
|
fd984529e7 | ||
|
|
7136a7b16c | ||
|
|
f005069ee2 | ||
|
|
9ed72aa23e | ||
|
|
377d888221 | ||
|
|
b6ad218fdb | ||
|
|
02e523cb62 | ||
|
|
11ee9dcf6e | ||
|
|
facf5a63d0 | ||
|
|
2d967fd5ad | ||
|
|
2ee3895a28 | ||
|
|
e84b02f8d5 | ||
|
|
97f2d91323 | ||
|
|
1c74a56586 | ||
|
|
5ce49d672b | ||
|
|
7b02a51867 | ||
|
|
d77a4918fe | ||
|
|
5957fa442a | ||
|
|
83cf78d00d | ||
|
|
ad9fc0e02a | ||
|
|
5e0b6d7477 | ||
|
|
3152c92ac0 | ||
|
|
9b10ce153d | ||
|
|
80220c903c | ||
|
|
297f338a17 | ||
|
|
714d523020 | ||
|
|
d572a55ce6 | ||
|
|
75ae18a6ca | ||
|
|
98a4483771 | ||
|
|
2298ac3895 | ||
|
|
d94dec9062 | ||
|
|
fe1f9fdfd9 | ||
|
|
fd68ce2f34 | ||
|
|
88be63384f | ||
|
|
ad942e38ff | ||
|
|
1aeeecb32b | ||
|
|
68daed2bcc | ||
|
|
35ef1a2bc8 | ||
|
|
da996b5922 | ||
|
|
f1fa9ffcb4 | ||
|
|
b4def65ec0 | ||
|
|
4ba8b4d823 | ||
|
|
f108692809 |
No files matched your search
@@ -1,5 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Controller;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
@@ -40,7 +41,7 @@ public class PageController {
|
||||
*/
|
||||
@GetMapping("/list/{id}")
|
||||
public String list(Model model, @PathVariable UUID id){
|
||||
ShoppingList list = shoppingListRepository.findById(id).orElseThrow();
|
||||
ShoppingList list = shoppingListRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Seite",id));
|
||||
List<ShoppingList> lists = shoppingListRepository.findAll();
|
||||
model.addAttribute("lists", lists);
|
||||
model.addAttribute("list", list);
|
||||
|
||||
+3
-2
@@ -11,6 +11,7 @@ import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -32,7 +33,7 @@ public class ShoppingCategoryController {
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
|
||||
@PostMapping("/api/categories")
|
||||
public ResponseEntity<ShoppingCategoryResponseDTO> addCategory(@RequestBody ShoppingCategoryPostDTO newCategory){
|
||||
public ResponseEntity<ShoppingCategoryResponseDTO> addCategory(@Valid @RequestBody ShoppingCategoryPostDTO newCategory){
|
||||
|
||||
String name = newCategory.categoryName();
|
||||
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow(() -> new ResourceNotFoundException("listID",newCategory.listID()));
|
||||
@@ -51,7 +52,7 @@ public class ShoppingCategoryController {
|
||||
}
|
||||
|
||||
@PatchMapping("/api/categories/{categoryID}")
|
||||
public ResponseEntity<Void> editCategory(@PathVariable UUID categoryID,@RequestBody ShoppingCategoryPatchDTO toChange){
|
||||
public ResponseEntity<Void> editCategory(@PathVariable UUID categoryID,@Valid @RequestBody ShoppingCategoryPatchDTO toChange){
|
||||
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID",categoryID));
|
||||
|
||||
if(toChange.categoryName() != null) category.setCategoryName(toChange.categoryName());
|
||||
|
||||
@@ -12,6 +12,7 @@ import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -33,7 +34,7 @@ public class ShoppingItemController {
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
|
||||
@PostMapping("/api/items")
|
||||
public ResponseEntity<ShoppingItemResponseDTO> addItem(@RequestBody ShoppingItemPostDTO newItem){
|
||||
public ResponseEntity<ShoppingItemResponseDTO> addItem(@Valid @RequestBody ShoppingItemPostDTO newItem){
|
||||
String name = newItem.itemName();
|
||||
String amount = newItem.itemAmount();
|
||||
ShoppingCategory c;
|
||||
@@ -57,7 +58,7 @@ public class ShoppingItemController {
|
||||
}
|
||||
|
||||
@PatchMapping("/api/items/{itemID}")
|
||||
public ResponseEntity<Void> editItem(@PathVariable UUID itemID ,@RequestBody ShoppingItemPatchDTO toChange){
|
||||
public ResponseEntity<Void> editItem(@PathVariable UUID itemID , @Valid @RequestBody ShoppingItemPatchDTO toChange){
|
||||
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow(() -> new ResourceNotFoundException("itemID",itemID));
|
||||
|
||||
if(toChange.itemName() != null) item.setItemName(toChange.itemName());
|
||||
|
||||
@@ -10,6 +10,7 @@ import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
import de.timaldinger.einkaufsliste.Service.ShoppingListService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -34,7 +35,7 @@ public class ShoppingListController {
|
||||
private ShoppingListService shoppingListService;
|
||||
|
||||
@PostMapping("/api/lists")
|
||||
public ResponseEntity<ShoppingListResponseDTO> addList(@RequestBody ShoppingListPostDTO newList){
|
||||
public ResponseEntity<ShoppingListResponseDTO> addList(@Valid @RequestBody ShoppingListPostDTO newList){
|
||||
ShoppingList list = new ShoppingList(newList.listName(), null, null, 0, 0);
|
||||
|
||||
shoppingListRepository.save(list);
|
||||
@@ -57,7 +58,7 @@ public class ShoppingListController {
|
||||
}
|
||||
|
||||
@PatchMapping("/api/lists/{listID}")
|
||||
public ResponseEntity<Void> editList(@PathVariable UUID listID,@RequestBody ShoppingListPatchDTO toChange){
|
||||
public ResponseEntity<Void> editList(@PathVariable UUID listID,@Valid @RequestBody ShoppingListPatchDTO toChange){
|
||||
ShoppingList list = shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
|
||||
if(toChange.newListName() != null) list.setListName(toChange.newListName());
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
public record ShoppingCategoryPatchDTO(String categoryName) {
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record ShoppingCategoryPatchDTO(@NotBlank(message = "categoryName can't be blank") String categoryName) {
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPatchDTO(String itemName, String itemAmount, Boolean isDone, UUID categoryID) {
|
||||
|
||||
@AssertTrue(message = "itemName and itemAmount both cant be blank!")
|
||||
private boolean isAtleastOneNotBlank(){
|
||||
boolean n = itemName != null && !itemName.isBlank();
|
||||
boolean a = itemAmount != null && !itemAmount.isBlank();
|
||||
return n || a || isDone != null || categoryID != null;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
public record ShoppingListPatchDTO(String newListName) {
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record ShoppingListPatchDTO(@NotBlank(message = "listName must not be blank!") String newListName) {
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingCategoryPostDTO(String categoryName, UUID listID) {
|
||||
public record ShoppingCategoryPostDTO(@NotBlank String categoryName, UUID listID) {
|
||||
}
|
||||
@@ -1,6 +1,20 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPostDTO(String itemName, String itemAmount, UUID categoryID, UUID listID){
|
||||
public record ShoppingItemPostDTO(String itemName,
|
||||
String itemAmount,
|
||||
UUID categoryID,
|
||||
@NotNull(message = "listID must not be empty!")
|
||||
UUID listID){
|
||||
|
||||
@AssertTrue(message = "itemName and itemAmount cant both be blank!")
|
||||
private boolean isAtleastOneNotBlank(){
|
||||
boolean n = itemName != null && !itemName.isBlank();
|
||||
boolean a = itemAmount != null && !itemAmount.isBlank();
|
||||
return n || a;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
public record ShoppingListPostDTO(String listName) {
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record ShoppingListPostDTO(@NotBlank(message = "listName must not be blank!") String listName) {
|
||||
}
|
||||
@@ -2,19 +2,28 @@ package de.timaldinger.einkaufsliste.Exceptions;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.ServletWebRequest;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BadRequestException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBadRequest(BadRequestException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
@@ -28,6 +37,7 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleAll(Exception e, HttpServletRequest req){
|
||||
log.error("{}",req.getRequestURI(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorResponse(500,"Internal error", req.getRequestURI()));
|
||||
}
|
||||
|
||||
@@ -36,4 +46,13 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
var error = new ErrorResponse(statusCode.value(), ex.getMessage(),((ServletWebRequest) request).getRequest().getRequestURI());
|
||||
return new ResponseEntity<>(error,headers,statusCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @Nullable ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
|
||||
String msg = ex.getBindingResult().getFieldErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
var error = new ErrorResponse(status.value(), msg ,((ServletWebRequest) request).getRequest().getRequestURI());
|
||||
return new ResponseEntity<>(error,headers,status);
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,6 @@ import java.util.List;
|
||||
@NoArgsConstructor
|
||||
public class ShoppingCategory extends ShoppingElement{
|
||||
|
||||
@NotBlank
|
||||
private String categoryName;
|
||||
@OneToMany(mappedBy = "category") //eine Liste hat mehrere Kategorien, diese sind mappedBy category (Feld in ShoppingItem) damit keine extra Tabelle erzeugt wird
|
||||
private List<ShoppingItem> itemsInCategory;
|
||||
|
||||
@@ -14,7 +14,6 @@ import lombok.*;
|
||||
@ToString
|
||||
public class ShoppingItem extends ShoppingElement {
|
||||
|
||||
@NotBlank
|
||||
private String itemName;
|
||||
private String itemAmount;
|
||||
private boolean isDone;
|
||||
|
||||
@@ -15,7 +15,6 @@ import java.sql.Date;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ShoppingList extends ShoppingElement {
|
||||
@NotBlank
|
||||
private String listName;
|
||||
private Date dateCreated;
|
||||
private Date lastChanged;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
font-size : 1.5rem;
|
||||
}
|
||||
|
||||
.item:has(.item__markAsDone:checked) .item__text{
|
||||
shopping-item[is-checked="true"] .item__text{
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,40 +1,58 @@
|
||||
export class ShoppingCategory {
|
||||
constructor(categoryName) {
|
||||
this.categoryName = categoryName;
|
||||
this.categoryID = null;
|
||||
export class ShoppingCategory extends HTMLElement {
|
||||
|
||||
static get observedAttributes() { return ["category-name"] }
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._rendered = false;
|
||||
}
|
||||
|
||||
static fromJSON(categoryAsJSON) {
|
||||
const category = new ShoppingCategory(categoryAsJSON.categoryName);
|
||||
category.categoryID = categoryAsJSON.categoryID;
|
||||
return category;
|
||||
}
|
||||
|
||||
render() {
|
||||
const li = document.createElement("li");
|
||||
connectedCallback() {
|
||||
if (this._rendered) return;
|
||||
const categoryHeaderDiv = document.createElement("div");
|
||||
const span = document.createElement("span");
|
||||
const deleteCategoryButton = document.createElement("button");
|
||||
const labelDeleteAllItems = document.createElement("label");
|
||||
const deleteAllItemsCheckbox = document.createElement("input");
|
||||
const innerUl = document.createElement("ul");
|
||||
li.id = this.categoryID;
|
||||
li.classList.add("category");
|
||||
const ul = document.createElement("ul");
|
||||
|
||||
|
||||
categoryHeaderDiv.classList.add("category__div");
|
||||
|
||||
span.textContent = this.categoryName;
|
||||
categoryHeaderDiv.classList.add("category__header");
|
||||
|
||||
span.textContent = this.getAttribute("category-name");
|
||||
span.classList.add("category__name", "category__name--bold", "category__name--big");
|
||||
|
||||
labelDeleteAllItems.classList.add("category__labelDeleteAll");
|
||||
labelDeleteAllItems.textContent = "Gegenstände mit Kategorie löschen?";
|
||||
|
||||
deleteCategoryButton.classList.add("category__deleteButton");
|
||||
deleteCategoryButton.textContent = "Kategorie löschen";
|
||||
|
||||
deleteAllItemsCheckbox.setAttribute("type", "checkbox");
|
||||
|
||||
categoryHeaderDiv.append(span, deleteCategoryButton, deleteAllItemsCheckbox);
|
||||
labelDeleteAllItems.append(deleteAllItemsCheckbox);
|
||||
|
||||
li.append(categoryHeaderDiv, innerUl);
|
||||
categoryHeaderDiv.append(span, deleteCategoryButton, labelDeleteAllItems);
|
||||
|
||||
return li;
|
||||
this.prepend(categoryHeaderDiv);
|
||||
|
||||
if (!this.querySelector("ul")) this.append(ul);
|
||||
|
||||
this._rendered = true;
|
||||
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldVal, newVal) {
|
||||
if (!this._rendered) return;
|
||||
if (newVal == oldVal) return;
|
||||
switch (name) {
|
||||
case "category-name":
|
||||
this.querySelector(".category__name").textContent = newVal;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,55 +1,59 @@
|
||||
export class ShoppingItem {
|
||||
export class ShoppingItem extends HTMLElement {
|
||||
|
||||
constructor(itemName, itemAmount) {
|
||||
this.itemName = itemName;
|
||||
this.itemAmount = itemAmount;
|
||||
this.itemID = null;
|
||||
this.isEditing = true;
|
||||
static get observedAttributes() { return ["item-name", "item-amount"] }
|
||||
constructor() {
|
||||
super();
|
||||
this._rendered = false;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
if (this._rendered) return;
|
||||
|
||||
static fromJSON(itemAsJSON) {
|
||||
const item = new ShoppingItem(itemAsJSON.itemName, itemAsJSON.itemAmount);
|
||||
item.itemID = itemAsJSON.itemID;
|
||||
return item;
|
||||
}
|
||||
|
||||
// gibt das darzustellende <li> zurück
|
||||
render() {
|
||||
const li = document.createElement("li");
|
||||
|
||||
console.log(`rendering element shopping-item`);
|
||||
const checkboxDone = document.createElement("input");
|
||||
const span = document.createElement("span");
|
||||
const spanText = document.createElement("span");
|
||||
const spanName = document.createElement("span");
|
||||
const spanAmount = document.createElement("span");
|
||||
const buttonDelete = document.createElement("button");
|
||||
|
||||
const deleteItemButton = document.createElement("button");
|
||||
|
||||
li.id = this.itemID;
|
||||
li.classList.add("item");
|
||||
|
||||
checkboxDone.classList.add("item__checkboxDone");
|
||||
checkboxDone.setAttribute("type", "checkbox");
|
||||
checkboxDone.setAttribute("autocomplete", "off");
|
||||
checkboxDone.classList.add("item__markAsDone");
|
||||
checkboxDone.checked = this.getAttribute("is-checked") === "true";
|
||||
|
||||
span.classList.add("item__text");
|
||||
spanName.classList.add("item__textName");
|
||||
spanAmount.classList.add("item__textAmount");
|
||||
spanText.classList.add("item__text");
|
||||
|
||||
spanName.textContent = this.itemName;
|
||||
spanAmount.textContent = this.itemAmount;
|
||||
spanName.classList.add("item__itemName");
|
||||
spanAmount.classList.add("item__itemAmount");
|
||||
|
||||
deleteItemButton.classList.add("item__deleteButton");
|
||||
deleteItemButton.textContent = "Löschen";
|
||||
spanName.textContent = this.getAttribute("item-name");
|
||||
spanAmount.textContent = this.getAttribute("item-amount");
|
||||
|
||||
span.appendChild(spanName);
|
||||
span.appendChild(spanAmount);
|
||||
buttonDelete.classList.add("item__buttonDeleteItem");
|
||||
buttonDelete.setAttribute("type", "button ");
|
||||
buttonDelete.textContent = "Löschen";
|
||||
|
||||
li.appendChild(checkboxDone)
|
||||
li.appendChild(span);
|
||||
li.appendChild(deleteItemButton);
|
||||
spanText.append(spanName, spanAmount);
|
||||
|
||||
return li;
|
||||
this.append(checkboxDone, spanText, buttonDelete);
|
||||
this._rendered = true;
|
||||
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldVal, newVal) {
|
||||
if (!this._rendered) return;
|
||||
if (newVal == oldVal) return;
|
||||
switch (name) {
|
||||
case "item-name":
|
||||
this.querySelector(".item__itemName").textContent = newVal;
|
||||
break;
|
||||
case "item-amount":
|
||||
this.querySelector(".item__itemAmount").textContent = newVal;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
|
||||
|
||||
|
||||
export async function addList(listName) {
|
||||
return await fetch(`/api/lists`,
|
||||
export function addList(listName) {
|
||||
return fetch(`/api/lists`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ listName: listName }),
|
||||
@@ -12,14 +12,14 @@ export async function addList(listName) {
|
||||
|
||||
}
|
||||
|
||||
export async function deleteList(id) {
|
||||
return await fetch(`/api/lists/${id}`, { method: "DELETE" });
|
||||
export function deleteList(id) {
|
||||
return fetch(`/api/lists/${id}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
|
||||
|
||||
export async function editList(listID, toChange) {
|
||||
return await fetch(`/api/lists/${listID}`,
|
||||
export function editList(listID, toChange) {
|
||||
return fetch(`/api/lists/${listID}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(toChange),
|
||||
|
||||
@@ -29,9 +29,10 @@ export function createEditListForm(textElement) {
|
||||
abortButton.textContent = "Abbrechen";
|
||||
saveButton.textContent = "Speichern";
|
||||
|
||||
editForm.appendChild(inputName);
|
||||
editForm.appendChild(saveButton);
|
||||
editForm.appendChild(abortButton);
|
||||
saveButton.classList.add("editForm__saveButton");
|
||||
abortButton.classList.add("editForm__abortButton");
|
||||
|
||||
editForm.append(inputName, saveButton, abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
@@ -46,5 +47,6 @@ export function editList(id, formElement, formData, listLi) {
|
||||
listLi.querySelector(".list__name").textContent = newName;
|
||||
listLi.setAttribute("href", `/list/${id}`);
|
||||
formElement.replaceWith(listLi);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
import { ShoppingList } from "../../models/ShoppingList.js";
|
||||
import { initErrors } from "../../shared/error.js";
|
||||
import { handleResponse } from "../../shared/helper.js";
|
||||
import { abortEditing } from "../../shared/sharedUI.js";
|
||||
import * as api from "./api/indexAPI.js";
|
||||
import * as ui from "./frontend/indexUI.js"
|
||||
|
||||
const addListForm = document.querySelector(".addListForm");
|
||||
|
||||
async function addList(listName) {
|
||||
const response = await api.addList(listName);
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`error creating list ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
ui.addList(json);
|
||||
const json = await handleResponse(api.addList(listName), `error creating list`);
|
||||
if (json) ui.addList(json);
|
||||
}
|
||||
|
||||
function editList(listLi) {
|
||||
@@ -25,48 +20,33 @@ function editList(listLi) {
|
||||
|
||||
formElement.querySelector(".editForm__name").focus();
|
||||
|
||||
async function save() {
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
|
||||
console.log(`editing catogory ${id} with ${formData}`)
|
||||
const response = await api.editList(id, { newListName: formData.newListName });
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`error editing list ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
ui.editList(id, formElement, formData, listLi);
|
||||
}
|
||||
|
||||
formElement.addEventListener("submit", (event) => {
|
||||
formElement.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
const result = await handleResponse(api.editList(id, { newListName: formData.newListName }), `error editing list`);
|
||||
if (result) ui.editList(id, formElement, formData, listLi);
|
||||
});
|
||||
|
||||
formElement.querySelector(".editForm__abortButton").addEventListener("click", () => {
|
||||
abortEditing(formElement, listLi);
|
||||
})
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") formElement.replaceWith(listLi);
|
||||
if (e.key == "Escape") abortEditing(formElement, listLi);
|
||||
})
|
||||
|
||||
|
||||
}
|
||||
|
||||
async function deleteList(listElement) {
|
||||
|
||||
const response = await api.deleteList(listElement.dataset.id);
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`error deleting list ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
ui.deleteList(listElement);
|
||||
const json = await handleResponse(api.deleteList(listElement.dataset.id), `error deleting list`);
|
||||
if (json) ui.deleteList(listElement);
|
||||
}
|
||||
|
||||
|
||||
function init() {
|
||||
|
||||
initErrors(document.querySelector(".nav"));
|
||||
addListForm.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const formData = Object.fromEntries(new FormData(addListForm));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export async function addCategory(listID, categoryName) {
|
||||
return await fetch(`/api/categories`,
|
||||
export function addCategory(listID, categoryName) {
|
||||
return fetch(`/api/categories`,
|
||||
{
|
||||
method: "POST"
|
||||
, body: JSON.stringify({ "categoryName": categoryName, "listID": listID })
|
||||
@@ -7,9 +7,8 @@ export async function addCategory(listID, categoryName) {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
export async function editCategory(categoryID, toChange) {
|
||||
return await fetch(`/api/categories/${categoryID}`,
|
||||
export function editCategory(categoryID, toChange) {
|
||||
return fetch(`/api/categories/${categoryID}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(toChange),
|
||||
@@ -17,6 +16,6 @@ export async function editCategory(categoryID, toChange) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteCategory(deleteAllItems, categoryID) {
|
||||
return await fetch(`/api/categories/${categoryID}?deleteAllItems=${deleteAllItems}`, { method: "DELETE" });
|
||||
export function deleteCategory(deleteAllItems, categoryID) {
|
||||
return fetch(`/api/categories/${categoryID}?deleteAllItems=${deleteAllItems}`, { method: "DELETE" });
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
|
||||
|
||||
export async function addItem(listID, itemName, itemAmount, categoryID) {
|
||||
return await fetch(`/api/items`,
|
||||
export function addItem(listID, itemName, itemAmount, categoryID) {
|
||||
return fetch(`/api/items`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
@@ -14,15 +12,14 @@ export async function addItem(listID, itemName, itemAmount, categoryID) {
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteItem(itemID) {
|
||||
|
||||
export async function deleteItem(itemID) {
|
||||
|
||||
return await fetch(`/api/items/${itemID}`, { method: "DELETE" });
|
||||
return fetch(`/api/items/${itemID}`, { method: "DELETE" });
|
||||
|
||||
}
|
||||
|
||||
export async function editItem(itemID, toChange) {
|
||||
return await fetch(`/api/items/${itemID}`,
|
||||
export function editItem(itemID, toChange) {
|
||||
return fetch(`/api/items/${itemID}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(toChange),
|
||||
@@ -31,10 +28,6 @@ export async function editItem(itemID, toChange) {
|
||||
|
||||
}
|
||||
|
||||
export async function deleteAllDoneItems(listID) {
|
||||
|
||||
return await fetch(`/api/lists/${listID}/items?done=true`, { method: "DELETE" });
|
||||
|
||||
|
||||
export function deleteAllDoneItems(listID) {
|
||||
return fetch(`/api/lists/${listID}/items?done=true`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
@@ -1,58 +1,30 @@
|
||||
|
||||
import { ShoppingCategory } from "../../../models/ShoppingCategory.js";
|
||||
|
||||
export function addCategory(categoryAsJSON) {
|
||||
const list = document.querySelector(".displayedList");
|
||||
const category = ShoppingCategory.fromJSON(categoryAsJSON);
|
||||
const category = document.createElement("shopping-category");
|
||||
const li = document.createElement("li");
|
||||
|
||||
list.appendChild(category.render()); //fügt Kategorie der Liste hinzu
|
||||
li.classList.add("category");
|
||||
li.dataset.id = categoryAsJSON.categoryID;
|
||||
category.setAttribute("category-name", categoryAsJSON.categoryName);
|
||||
|
||||
li.append(category); //fügt Kategorie der Liste hinzu
|
||||
|
||||
list.append(li);
|
||||
|
||||
const categorySelect = document.querySelector(".addItemForm__categorySelect");
|
||||
const newCategoryOption = document.createElement("option");
|
||||
newCategoryOption.setAttribute("value", category.categoryID);
|
||||
newCategoryOption.textContent = category.categoryName;
|
||||
newCategoryOption.setAttribute("value", categoryAsJSON.categoryID);
|
||||
newCategoryOption.textContent = categoryAsJSON.categoryName;
|
||||
|
||||
categorySelect.appendChild(newCategoryOption);
|
||||
categorySelect.append(newCategoryOption);
|
||||
}
|
||||
|
||||
export function deleteCategory(deleteAllItems, categoryID) {
|
||||
const category = document.getElementById(categoryID);
|
||||
const category = document.querySelector(`li[data-id='${categoryID}']`);
|
||||
if (!deleteAllItems) {
|
||||
const ul = category.querySelector("ul");
|
||||
if (ul) document.querySelector(".displayedList").append(...ul.children);
|
||||
}
|
||||
category.remove()
|
||||
document.querySelector(`option[value='${categoryID}']`).remove();
|
||||
|
||||
}
|
||||
|
||||
export function createEditCategoryForm(textElement) {
|
||||
const editForm = document.createElement("form");
|
||||
const inputName = document.createElement("input");
|
||||
const abortButton = document.createElement("button");
|
||||
const saveButton = document.createElement("button");
|
||||
|
||||
inputName.setAttribute("name", "newCategoryName");
|
||||
inputName.setAttribute("value", textElement.querySelector(".category__name").textContent);
|
||||
inputName.classList.add("editForm__name");
|
||||
|
||||
abortButton.textContent = "Abbrechen";
|
||||
saveButton.textContent = "Speichern";
|
||||
|
||||
editForm.appendChild(inputName);
|
||||
editForm.appendChild(saveButton);
|
||||
editForm.appendChild(abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
export function editCategory(id, formElement, formData, categoryDiv) {
|
||||
|
||||
let newName = formData.newCategoryName;
|
||||
|
||||
categoryDiv.querySelector(".category__name").textContent = newName;
|
||||
formElement.replaceWith(categoryDiv);
|
||||
|
||||
document.querySelector(`option[value='${id}']`).textContent = newName;
|
||||
|
||||
}
|
||||
@@ -1,55 +1,21 @@
|
||||
import { ShoppingItem } from "../../../models/ShoppingItem.js";
|
||||
|
||||
export function addItem(itemAsJSON) {
|
||||
let list;
|
||||
if (!itemAsJSON.categoryID) {
|
||||
list = document.querySelector(".displayedList");
|
||||
} else {
|
||||
list = document.getElementById(`${itemAsJSON.categoryID}`).querySelector("ul");
|
||||
list = document.querySelector(`li[data-id='${itemAsJSON.categoryID}']`).querySelector("ul");
|
||||
}
|
||||
const li = document.createElement("li");
|
||||
const item = document.createElement("shopping-item");
|
||||
|
||||
const item = ShoppingItem.fromJSON(itemAsJSON);
|
||||
li.dataset.id = itemAsJSON.itemID;
|
||||
li.classList.add("item");
|
||||
|
||||
list.appendChild(item.render());
|
||||
}
|
||||
|
||||
export function createEditItemForm(textElement) {
|
||||
const editForm = document.createElement("form");
|
||||
const inputName = document.createElement("input");
|
||||
const inputAmount = document.createElement("input");
|
||||
const abortButton = document.createElement("button");
|
||||
const saveButton = document.createElement("button");
|
||||
|
||||
inputName.setAttribute("name", "newItemName");
|
||||
inputName.setAttribute("value", textElement.querySelector(".item__textName").textContent);
|
||||
inputName.classList.add("editForm__name");
|
||||
|
||||
inputAmount.setAttribute("name", "newItemAmount");
|
||||
inputAmount.setAttribute("value", textElement.querySelector(".item__textAmount").textContent);
|
||||
inputAmount.classList.add("editForm__amount");
|
||||
|
||||
|
||||
abortButton.textContent = "Abbrechen";
|
||||
saveButton.textContent = "Speichern";
|
||||
|
||||
|
||||
editForm.appendChild(inputName);
|
||||
editForm.appendChild(inputAmount);
|
||||
editForm.appendChild(saveButton);
|
||||
editForm.appendChild(abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
export function editItem(textElement, formElement, formData) {
|
||||
|
||||
let newName = formData.newItemName;
|
||||
let newAmount = formData.newItemAmount;
|
||||
textElement.querySelector(".item__textName").textContent = newName;
|
||||
textElement.querySelector(".item__textAmount").textContent = newAmount;
|
||||
|
||||
formElement.replaceWith(textElement);
|
||||
item.setAttribute("item-name", itemAsJSON.itemName);
|
||||
item.setAttribute("item-amount", itemAsJSON.itemAmount);
|
||||
|
||||
li.append(item);
|
||||
list.append(li);
|
||||
}
|
||||
|
||||
export function deleteItem(li) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
|
||||
export * from "./itemUI.js";
|
||||
export * from "./categoryUI.js";
|
||||
|
||||
export function deleteAllDoneItems() {
|
||||
const doneItems = document.querySelectorAll("li.item:has(input[type=checkbox]:checked)");
|
||||
const doneItems = document.querySelectorAll("li.item:has(shopping-item[is-checked=true])");
|
||||
doneItems.forEach((li) => {
|
||||
li.remove();
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { ShoppingCategory } from "../../models/ShoppingCategory.js";
|
||||
import { ShoppingItem } from "../../models/ShoppingItem.js";
|
||||
import { initErrors } from "../../shared/error.js";
|
||||
import * as api from "./api/listAPI.js"
|
||||
import * as ui from "./frontend/listUI.js"
|
||||
|
||||
import { handleResponse } from "../../shared/helper.js";
|
||||
import { editElement } from "../../shared/editing.js";
|
||||
import * as sharedUI from "../../shared/sharedUI.js";
|
||||
|
||||
const addCategoryForm = document.querySelector(".addCategoryForm");
|
||||
const addItemForm = document.querySelector(".addItemForm");
|
||||
@@ -8,150 +13,47 @@ const currentList = document.querySelector(".list");
|
||||
const deleteAllDoneItemsButton = document.querySelector(".deleteAllDoneItemsButton");
|
||||
|
||||
async function addItem(itemName, itemAmount, categoryID) {
|
||||
console.log(` adding item with id:${currentList.id}, name: ${itemName}, amount: ${itemAmount}, category: ${categoryID}`)
|
||||
console.log(` adding item with id:${currentList.dataset.id}, name: ${itemName}, amount: ${itemAmount}, category: ${categoryID}`)
|
||||
|
||||
const response = await api.addItem(currentList.id, itemName, itemAmount, categoryID);
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Error, item couldnt be created ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`rendering frontend item: ${json}`);
|
||||
ui.addItem(json);
|
||||
const json = await handleResponse(api.addItem(currentList.dataset.id, itemName, itemAmount, categoryID), `item couldnt be created!`);
|
||||
if (json) ui.addItem(json);
|
||||
}
|
||||
|
||||
async function addCategory(categoryName) {
|
||||
console.log(`adding category ${categoryName}`)
|
||||
|
||||
const response = await api.addCategory(currentList.id, categoryName);
|
||||
const json = await response.json();
|
||||
const json = await handleResponse(api.addCategory(currentList.dataset.id, categoryName), `category couldnt be added!`);
|
||||
if (json) ui.addCategory(json);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Error, category couldnt be created ${json}`)
|
||||
return;
|
||||
}
|
||||
|
||||
ui.addCategory(json);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//textElement ist immer das li mit der id
|
||||
async function editItem(textElement) {
|
||||
|
||||
|
||||
//erstellen das Forms
|
||||
const formElement = ui.createEditItemForm(textElement)
|
||||
let id = textElement.id;
|
||||
|
||||
textElement.replaceWith(formElement);
|
||||
|
||||
formElement.querySelector(".editForm__name").focus();
|
||||
|
||||
async function save() {
|
||||
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
console.log(`editing item ${id} with ${formData}`)
|
||||
|
||||
const response = await api.editItem(id, { itemName: formData.newName, itemAmount: formData.newAmount });
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`Error editingItem ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
ui.editItem(textElement, formElement, formData);
|
||||
}
|
||||
|
||||
formElement.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
});
|
||||
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") formElement.replaceWith(textElement);
|
||||
})
|
||||
|
||||
|
||||
}
|
||||
|
||||
function editCategory(categoryElement) {
|
||||
//erstellen das Forms
|
||||
//wir nutzen für das Element nur das div, weil sonst alle items mitgelöscht werden würden
|
||||
const categoryDiv = categoryElement.querySelector(".category__div");
|
||||
const formElement = ui.createEditCategoryForm(categoryDiv);
|
||||
let id = categoryElement.id;
|
||||
|
||||
categoryDiv.replaceWith(formElement);
|
||||
|
||||
formElement.querySelector(".editForm__name").focus();
|
||||
|
||||
async function save() {
|
||||
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
|
||||
console.log(`editing catogory ${id} with ${formData}`)
|
||||
|
||||
const response = await api.editCategory(id, { categoryName: formData.newCategoryName });
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`Error editing category ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
ui.editCategory(id, formElement, formData, categoryDiv);
|
||||
}
|
||||
|
||||
formElement.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
});
|
||||
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") formElement.replaceWith(categoryDiv);
|
||||
})
|
||||
}
|
||||
|
||||
async function deleteItem(li) {
|
||||
const response = await api.deleteItem(li.id);
|
||||
console.log(`deleting item ${li.dataset.id}`)
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`Error deleting item ${json}`);
|
||||
return;
|
||||
}
|
||||
|
||||
ui.deleteItem(li);
|
||||
const json = await handleResponse(api.deleteItem(li.dataset.id), `error deleting item`);
|
||||
if (json) ui.deleteItem(li);
|
||||
}
|
||||
|
||||
async function deleteCategory(deleteAllItems, categoryID) {
|
||||
console.log(`deleting category with allItems: ${deleteAllItems} id: ${categoryID}`);
|
||||
const response = await api.deleteCategory(deleteAllItems, categoryID);
|
||||
const json = await handleResponse(api.deleteCategory(deleteAllItems, categoryID), `error deleting category`);
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`Error deleting category ${json}`);
|
||||
return;
|
||||
}
|
||||
ui.deleteCategory(deleteAllItems, categoryID);
|
||||
if (json) ui.deleteCategory(deleteAllItems, categoryID);
|
||||
}
|
||||
|
||||
async function deleteAllDoneItems() {
|
||||
console.log(`deleting all done items...`)
|
||||
const response = await api.deleteAllDoneItems(currentList.id);
|
||||
|
||||
if (!response.ok) {
|
||||
const json = await response.json();
|
||||
console.error(`Error deleting all done items ${json}`);
|
||||
return;
|
||||
}
|
||||
ui.deleteAllDoneItems();
|
||||
const json = await handleResponse(api.deleteAllDoneItems(currentList.dataset.id), `error deleting all done items`);
|
||||
if (json) ui.deleteAllDoneItems();
|
||||
}
|
||||
|
||||
function init() {
|
||||
|
||||
initErrors(document.querySelector(".nav"));
|
||||
|
||||
customElements.define("shopping-item", ShoppingItem);
|
||||
customElements.define("shopping-category", ShoppingCategory);
|
||||
|
||||
addCategoryForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
let formData = Object.fromEntries(new FormData(addCategoryForm));
|
||||
@@ -170,31 +72,70 @@ function init() {
|
||||
|
||||
//event delegation ist schon geil
|
||||
document.querySelector(".displayedList").addEventListener("click", (event) => {
|
||||
if (event.target.matches(".item__deleteButton")) {
|
||||
if (event.target.matches(".item__buttonDeleteItem")) {
|
||||
deleteItem(event.target.closest("li"));
|
||||
|
||||
} else if (event.target.matches(".category__deleteButton")) {
|
||||
|
||||
const li = event.target.closest("li");
|
||||
const checkbox = li.querySelector("input[type=checkbox]");
|
||||
deleteCategory(checkbox.checked, li.id);
|
||||
deleteCategory(checkbox.checked, li.dataset.id);
|
||||
|
||||
} else if (event.target.closest(".item__text")) {
|
||||
editItem(event.target.closest("li"));
|
||||
|
||||
const shoppingItemElement = event.target.closest("shopping-item");
|
||||
const id = event.target.closest("li").dataset.id;
|
||||
|
||||
let itemName = shoppingItemElement.querySelector(".item__itemName").textContent;
|
||||
let itemAmount = shoppingItemElement.querySelector(".item__itemAmount").textContent;
|
||||
/*
|
||||
* { name: "", value: "", class: "", attr: ""}
|
||||
*/
|
||||
|
||||
editElement({
|
||||
element: shoppingItemElement, apiCall: api.editItem, id: id,
|
||||
fields: [
|
||||
{ name: "itemName", value: itemName, class: "editForm__name", attr: "item-name" },
|
||||
{ name: "itemAmount", value: itemAmount, class: "editForm__amount", attr: "item-amount" }
|
||||
]
|
||||
, onSuccess: (f) => { sharedUI.setElementAttributes(shoppingItemElement, { "item-name": f.itemName, "item-amount": f.itemAmount }) }
|
||||
, errmsg: `konnte Item nicht bearbeiten`
|
||||
});
|
||||
|
||||
} else if (event.target.closest(".category__name")) {
|
||||
editCategory(event.target.closest("li"));
|
||||
|
||||
const categoryElement = event.target.closest("shopping-category");
|
||||
const categoryHeader = event.target.closest(".category__header");
|
||||
const id = event.target.closest("li").dataset.id;
|
||||
|
||||
let categoryName = categoryElement.querySelector(".category__name").textContent;
|
||||
|
||||
editElement({
|
||||
element: categoryHeader, apiCall: api.editCategory, id: id,
|
||||
fields: [
|
||||
{ name: "categoryName", value: categoryName, class: "editForm__name", attr: "category-name" },
|
||||
]
|
||||
, onSuccess: (f) => {
|
||||
sharedUI.setElementAttributes(categoryElement, { "category-name": f.categoryName })
|
||||
document.querySelector(`option[value='${id}']`).textContent = f.categoryName;
|
||||
}
|
||||
, errmsg: `konnte Kategorie nicht bearbeiten`
|
||||
});
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector(".displayedList").addEventListener("change", (e) => {
|
||||
if (e.target.matches(".item__markAsDone")) {
|
||||
if (e.target.matches(".item__checkboxDone")) {
|
||||
const item = e.target.closest("li");
|
||||
api.editItem(item.id, { isDone: e.target.checked });
|
||||
e.target.closest("shopping-item").setAttribute("is-checked", e.target.checked);
|
||||
api.editItem(item.dataset.id, { isDone: e.target.checked });
|
||||
}
|
||||
});
|
||||
|
||||
console.log("javascript initialized!");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
@@ -0,0 +1,29 @@
|
||||
import { abortEditing, createEditForm } from "./sharedUI.js";
|
||||
import { handleResponse } from "./helper.js";
|
||||
|
||||
export async function editElement({ element, fields, apiCall, id, onSuccess, errmsg }) {
|
||||
const formElement = createEditForm(fields);
|
||||
|
||||
element.replaceWith(formElement);
|
||||
|
||||
formElement.querySelector("input").focus();
|
||||
|
||||
formElement.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
let result = await handleResponse(apiCall(id, formData), errmsg);
|
||||
|
||||
abortEditing(formElement, element);
|
||||
|
||||
if (result) onSuccess(formData);
|
||||
});
|
||||
|
||||
formElement.addEventListener("click", (e) => {
|
||||
if (e.target.matches(".editForm__buttonAbort")) abortEditing(formElement, element);
|
||||
})
|
||||
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") abortEditing(formElement, element);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
const errorDiv = document.createElement("div");
|
||||
const errorSpan = document.createElement("span");
|
||||
let errorTimer;
|
||||
|
||||
export function showError(msg) {
|
||||
errorSpan.textContent = msg;
|
||||
errorDiv.hidden = false
|
||||
|
||||
clearTimeout(errorTimer);
|
||||
errorTimer = (setTimeout(() => {
|
||||
errorDiv.hidden = true;
|
||||
errorSpan.textContent = "";
|
||||
}, 3000));
|
||||
}
|
||||
|
||||
|
||||
export function initErrors(element) {
|
||||
errorDiv.hidden = true;
|
||||
errorDiv.append(errorSpan);
|
||||
|
||||
element.append(errorDiv);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { showError } from "./error.js";
|
||||
|
||||
export async function handleResponse(promise, errorMsg) {
|
||||
const response = await promise;
|
||||
|
||||
//weil 204 kein body ist un damit unparsbar, geben wir vorab true zurück
|
||||
if (response.status == 204) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
showError(json.msg);
|
||||
console.error(errorMsg);
|
||||
return false;
|
||||
}
|
||||
|
||||
return json;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
export function abortEditing(formElement, old) {
|
||||
formElement.replaceWith(old);
|
||||
}
|
||||
|
||||
export function createEditForm(fields) {
|
||||
const editForm = document.createElement("form");
|
||||
const abortButton = document.createElement("button");
|
||||
const saveButton = document.createElement("button");
|
||||
|
||||
const inputs = fields.map(f => {
|
||||
const input = document.createElement("input");
|
||||
input.setAttribute("name", f.name);
|
||||
input.setAttribute("value", f.value);
|
||||
input.classList.add(f.class);
|
||||
return input;
|
||||
});
|
||||
|
||||
abortButton.setAttribute("type", "button");
|
||||
abortButton.classList.add("editForm__buttonAbort");
|
||||
abortButton.textContent = "Abbrechen";
|
||||
|
||||
saveButton.textContent = "Speichern";
|
||||
saveButton.classList.add("editForm__buttonSave");
|
||||
saveButton.setAttribute("type", "submit");
|
||||
|
||||
|
||||
editForm.append(...inputs, saveButton, abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
export function setElementAttributes(element, attributes) {
|
||||
|
||||
for (const [attr, val] of Object.entries(attributes)) element.setAttribute(attr, val);
|
||||
|
||||
}
|
||||
@@ -27,7 +27,7 @@
|
||||
<h1 th:text="${list.listName}"></h1>
|
||||
</div>
|
||||
|
||||
<div class="list" th:id="${list.id}">
|
||||
<div class="list" th:data-id="${list.id}">
|
||||
<form class="addCategoryForm">
|
||||
<span>Neue Kategorie hinzufügen:</span>
|
||||
<input type="text" class="addCategoryForm__nameInput" name="categoryName" placeholder="Neue Kategorie hinzufügen...">
|
||||
@@ -52,32 +52,18 @@
|
||||
|
||||
<ul class="displayedList">
|
||||
<!-- Es werden erste alle Kategorien erstellt, jede Kategorie muss ein ul in einem li sein um Verschachtelung zu ermöglichen -->
|
||||
<li th:each="category: ${categories}" th:id="${category.id}" class="category">
|
||||
<div class="category__div">
|
||||
<span class="category__name category__name--big category__name--bold" th:text="${category.categoryName}"></span>
|
||||
<button class="category__deleteButton">Kategorie löschen</button>
|
||||
<input type="checkbox">
|
||||
</div>
|
||||
<!-- Items der Kategorie -->
|
||||
<ul>
|
||||
<li th:each="item: ${category.itemsInCategory}" th:id="${item.id}" class="item"> <!-- erstellung von einem Item -->
|
||||
<input type="checkbox" class="item__markAsDone" th:checked="${item.isDone}" autocomplete="off">
|
||||
<span class="item__text">
|
||||
<span th:text="${item.itemName}" class="item__textName"></span>
|
||||
<span th:text="${item.itemAmount}" class="item__textAmount"></span>
|
||||
</span>
|
||||
<button class="item__deleteButton">Löschen</button>
|
||||
<li th:each="category: ${categories}" th:data-id="${category.id}" class="category">
|
||||
<shopping-category th:attr="category-name=${category.categoryName}">
|
||||
<ul>
|
||||
<li th:each="item: ${category.itemsInCategory}" th:data-id="${item.id}" class="item">
|
||||
<shopping-item th:attr="item-name=${item.itemName}, item-amount=${item.itemAmount}, is-checked=${item.isDone}"></shopping-item>
|
||||
</li>
|
||||
</ul>
|
||||
</ul>
|
||||
</shopping-category>
|
||||
</li>
|
||||
|
||||
<li th:each="item: ${items}" th:id="${item.id}" class="item"> <!-- erstellung items ohne Kategorie -->
|
||||
<input type="checkbox" class="item__markAsDone" th:checked="${item.isDone}" autocomplete="off">
|
||||
<span class="item__text">
|
||||
<span th:text="${item.itemName}" class="item__textName"></span>
|
||||
<span th:text="${item.itemAmount}" class="item__textAmount"></span>
|
||||
</span>
|
||||
<button class="item__deleteButton">Löschen</button>
|
||||
<li th:each="item: ${items}" th:data-id="${item.id}" class="item"> <!-- erstellung items ohne Kategorie -->
|
||||
<shopping-item th:attr="item-name=${item.itemName}, item-amount=${item.itemAmount}, is-checked=${item.isDone}"></shopping-item>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
Reference in new issue
Block a user