-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (76 loc) · 2.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { setNavBar, setSearch, fetchRecipes, storeRecipes } from "./common.js";
document.addEventListener("DOMContentLoaded", () => {
setNavBar();
setSearch();
createNewRecipeForm();
});
// Add new recipe
function createNewRecipeForm() {
const newRecipeForm = document.getElementById("new-recipe-form");
if (newRecipeForm) {
newRecipeForm.addEventListener("submit", (event) => {
event.preventDefault();
const hideRecipeParts = document.querySelectorAll(".hide-recipe-part");
if (hideRecipeParts) {
hideRecipeParts.forEach((part) => part.classList.remove("hide"));
}
const title = document.getElementById("title").value;
const imageUrl = document.getElementById("image-url").value;
const description = document.getElementById("description").value;
const ingredientsInput = document
.getElementById("ingredients")
.value.split("\n");
const preparationStepsInput = document
.getElementById("preparation-steps")
.value.split("\n");
if (ingredientsInput.length < 5) {
alert("Please provide at least 5 ingredients.");
return;
}
const ingredients = [];
ingredientsInput.forEach((ingredientLine) => {
if (ingredientLine.trim() === "") return;
const parts = ingredientLine.split(":");
if (parts.length !== 2) {
alert(
"Invalid ingredient format. Please use 'Ingredient Name: Amount' format."
);
return;
}
const name = parts[0].trim();
const amount = parts[1].trim();
ingredients.push({ NAME: name, AMOUNT: amount });
});
const preparationSteps = [];
preparationStepsInput.forEach((preparationStepLine) => {
if (preparationStepLine.trim() === "") return;
preparationSteps.push(preparationStepLine);
});
const recipes = fetchRecipes();
const newRecipeData = {
id: recipes.length + 1,
title,
imageUrl,
description,
ingredients,
preparationSteps,
};
addNewRecipe(newRecipeData);
function addNewRecipe(newRecipeData) {
let recipes = fetchRecipes();
const newRecipe = {
id: recipes.length + 1,
title: newRecipeData.title,
picture_url: newRecipeData.imageUrl,
description: newRecipeData.description,
ingredients: newRecipeData.ingredients,
preparationSteps: newRecipeData.preparationSteps,
};
recipes.push(newRecipe);
storeRecipes(recipes);
window.location.assign(`recipe-details.html?id=${newRecipe.id}`);
}
newRecipeForm.reset();
});
}
}