-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
234 lines (187 loc) · 8.97 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// main.js
document.addEventListener('DOMContentLoaded', () => {
let StandardPortion = 4;
let Dinners = [];
let AvailableRecipes = new Set(Object.keys(Recipes));
let Ingredients = {};
// Tracks the dragged element
let draggedElement = null;
// Allows for the adding, removal and updating of the dinner portions
const addDinner = (dinner) => {
Dinners.push({ dinner: dinner, portions: StandardPortion });
AvailableRecipes.delete(dinner);
updateDinnersContent();
updateIngredients();
};
const removeDinner = (dinner) => {
Dinners = Dinners.filter(d => d.dinner !== dinner);
AvailableRecipes.add(dinner);
updateDinnersContent();
updateIngredients();
};
const addRandomDinner = () => {
if (AvailableRecipes.size > 0) {
const arrayFromSet = Array.from(AvailableRecipes);
const randomDinner = arrayFromSet[Math.floor(Math.random() * arrayFromSet.length)];
addDinner(randomDinner);
} else {
alert("Ingen flere oppskrifter å legge til");
}
};
const incrementDinnerPortion = (dinner, increment) => {
const dinnerObject = Dinners.find(d => d.dinner === dinner);
if (dinnerObject && (dinnerObject.portions + increment >= 0)) {
dinnerObject.portions += increment;
updateDinnersContent();
updateIngredients();
}
};
// Updates the dinners section content and the ingredients section content
const updateDinnersContent = () => {
const dinnersContent = document.getElementById('dinnersContent');
dinnersContent.innerHTML = '';
Dinners.forEach((dinnerItem, index) => {
const dinnerCard = document.createElement('div');
dinnerCard.className = 'dinner-card';
dinnerCard.draggable = true;
dinnerCard.addEventListener('dragstart', handleDragStart);
dinnerCard.addEventListener('dragover', handleDragOver);
dinnerCard.addEventListener('drop', handleDrop);
dinnerCard.addEventListener('dragend', handleDragEnd);
const cardTop = document.createElement('div');
cardTop.className = 'card-top';
const dinnerText = document.createElement('div');
dinnerText.className = 'dinner-text';
dinnerText.textContent = `${index + 1}. ${dinnerItem.dinner}`;
const crossButton = document.createElement('i');
crossButton.className = 'fas fa-circle-xmark cross-button';
crossButton.addEventListener('click', () => removeDinner(dinnerItem.dinner));
const cardBottom = document.createElement('div');
cardBottom.className = 'card-bottom';
const portionsDiv = document.createElement('div');
portionsDiv.className = 'portions';
portionsDiv.textContent = dinnerItem.portions;
const minusButton = document.createElement('i');
minusButton.className = 'fas fa-circle-minus fa-xl blue-button';
minusButton.addEventListener('click', () => incrementDinnerPortion(dinnerItem.dinner, -1));
const plusButton = document.createElement('i');
plusButton.className = 'fas fa-circle-plus fa-xl blue-button';
plusButton.addEventListener('click', () => incrementDinnerPortion(dinnerItem.dinner, 1));
cardTop.appendChild(dinnerText);
cardTop.appendChild(crossButton);
cardBottom.appendChild(portionsDiv);
cardBottom.appendChild(minusButton);
cardBottom.appendChild(plusButton);
dinnerCard.appendChild(cardTop);
dinnerCard.appendChild(cardBottom);
dinnersContent.appendChild(dinnerCard);
});
};
// Updates the "Ingredients" content with notepad lines containing the Dinners ingredients
function updateIngredientsContent() {
const ingredientsContent = document.getElementById('ingredientsContent');
ingredientsContent.innerHTML = '';
const ingredientKeys = Object.keys(Ingredients).sort((a, b) => SortAsciiWeight(a) - SortAsciiWeight(b));
ingredientKeys.forEach((ingredient) => {
const ingredientItem = document.createElement('div');
ingredientItem.className = 'ingredient';
ingredientItem.textContent = `${Math.round(Ingredients[ingredient] * 100) / 100} ${ingredient}`;
ingredientsContent.appendChild(ingredientItem);
});
}
// Updates Ingredients dictionary to be up to date with the dinners and portion state
function updateIngredients() {
Ingredients = {};
Dinners.forEach(dinnerItem => {
const dinnerIngredients = Recipes[dinnerItem.dinner]["Ingredients"];
for (const [ingredient, amount] of Object.entries(dinnerIngredients)) {
if (Ingredients.hasOwnProperty(ingredient)) {
Ingredients[ingredient] += Math.round(amount * dinnerItem.portions * 100) / 100;
} else {
Ingredients[ingredient] = Math.round(amount * dinnerItem.portions * 100) / 100;
}
}
});
// Removes ingredients with zero quantity
Object.keys(Ingredients).forEach((key) => {
if (Ingredients[key] === 0) {
delete Ingredients[key];
}
});
updateIngredientsContent();
}
// Functions allowing drag and drop of dinners
function handleDragStart(e) {
draggedElement = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text', this.innerHTML);
}
function handleDragOver(e) {
e.preventDefault();
}
function handleDrop(e) {
e.preventDefault();
if (draggedElement !== this) {
// Identify the index of both source and target
let sourceIndex = Array.from(dinnersContent.children).indexOf(draggedElement);
let targetIndex = Array.from(dinnersContent.children).indexOf(this);
// Swap dinner objects in the array
[Dinners[sourceIndex], Dinners[targetIndex]] = [Dinners[targetIndex], Dinners[sourceIndex]];
// Update the display to reflect the new swapped array state
updateDinnersContent();
updateIngredients();
}
}
function handleDragEnd() {
draggedElement = null; // Reset the dragged element
}
// Functions used for sorting the ingredients by quantity measurement (eg 'g', 'stk', 'ts', etc)
function GetAsciiNumber(character) {
return character.charCodeAt(0)
};
function GetMeasurementAsciiWeight(measurementString) {
let weight = 0
for (let i = 0; i < measurementString.length; i++) {
weight += GetAsciiNumber(measurementString[i])
}
return weight
};
function SortAsciiWeight(ingredientString) {
const ingredientParsed = ingredientString.split(/(\s)/)
return GetMeasurementAsciiWeight(ingredientParsed[0])
};
// Function allowing for the "sharing" of the ingredients list with accompanying recipes in the state's order
function shareTextToNotes(text) {
if (navigator.share) {
navigator.share({ text: text })
.then(() => console.log('Successfully shared the text.'))
.catch((error) => console.error('Error sharing:', error));
} else {
alert('Deling av handlelisten er ikke støttet av nettleseren, prøv en annen.');
}
}
// Builds the text that contains the shopping list (all ingredients), the dinners sequentially ordered (with their ingredients and recipe)
// So that the state's dinner plan can be added to notes, or shared with others
function handleShareClick() {
let shoppingList = 'Handleliste\n\n';
for (const ingredient in Ingredients) {
const amount = Ingredients[ingredient];
shoppingList += `${Math.round(amount * 100) / 100} ${ingredient}\n`;
}
shoppingList += '\n\n\n';
Dinners.forEach((dinnerItem, index) => {
let dinnerIngredients = 'Ingredienser:\n';
Object.entries(Recipes[dinnerItem.dinner]['Ingredients']).forEach(([ingredient, qty]) => {
dinnerIngredients += `${Math.round(qty * dinnerItem.portions * 100) / 100} ${ingredient}\n`;
});
shoppingList += `Middag ${index + 1}: ${dinnerItem.dinner}\n${dinnerIngredients}\n${Recipes[dinnerItem.dinner]['Recipe']}\n\n`;
});
shareTextToNotes(shoppingList);
}
// Adds event listeners to the main buttons for the website, for adding dinners, and for sharing of the shopping list and recipes selected
document.getElementById('addRandomDinnerButton').addEventListener('click', addRandomDinner);
document.getElementById('shareButton').addEventListener('click', handleShareClick);
// Initial population of the content
updateDinnersContent();
updateIngredients();
});