-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
332 lines (296 loc) · 10.6 KB
/
script.js
File metadata and controls
332 lines (296 loc) · 10.6 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// API Endpoints
const API_BASE_URL = "https://www.themealdb.com/api/json/v1/1/";
// DOM Elements
const searchInput = document.getElementById("search-input");
const searchBtn = document.getElementById("search-btn");
const randomBtn = document.getElementById("random-btn");
const categoryFilter = document.getElementById("category-filter");
const areaFilter = document.getElementById("area-filter");
const resultsContainer = document.getElementById("results-container");
const favoritesSection = document.getElementById("favorites-section");
const favoritesContainer = document.getElementById("favorites-container");
const loadingIndicator = document.getElementById("loading-indicator");
const mealModal = document.getElementById("meal-modal");
const closeModalBtn = document.getElementById("close-modal-btn");
const modalContent = document.getElementById("modal-content");
// --- Global State ---
let allMeals = [];
const FAVORITES_KEY = "savouryFavorites";
const CACHE_KEY = "savouryCache";
let favorites = JSON.parse(localStorage.getItem(FAVORITES_KEY)) || [];
// Fxns
function showLoading(show) {
loadingIndicator.classList.toggle("hidden", !show);
}
async function fetchAPI(endpoint) {
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Fetch error:", error);
return { meals: [] };
}
}
// fetch category/area filters
async function fetchCategories() {
const data = await fetchAPI("list.php?c=list");
if (data.meals) {
data.meals.forEach((category) => {
const option = document.createElement("option");
option.value = category.strCategory;
option.textContent = category.strCategory;
categoryFilter.appendChild(option);
});
}
}
async function fetchAreas() {
const data = await fetchAPI("list.php?a=list");
if (data.meals) {
data.meals.forEach((area) => {
const option = document.createElement("option");
option.value = area.strArea;
option.textContent = area.strArea;
areaFilter.appendChild(option);
});
}
}
// search
async function searchMeals() {
const query = searchInput.value.trim();
if (query) {
showLoading(true);
const data = await fetchAPI(`search.php?s=${query}`);
allMeals = data.meals || [];
saveToLocalStorage(CACHE_KEY, allMeals);
displayMeals(allMeals);
showLoading(false);
}
}
// Random pick
async function fetchRandomMeal() {
showLoading(true);
const data = await fetchAPI("random.php");
allMeals = data.meals || [];
saveToLocalStorage(CACHE_KEY, allMeals);
displayMeals(allMeals);
showLoading(false);
}
// filter display
async function filterMeals() {
const category = categoryFilter.value;
const area = areaFilter.value;
let endpoint = "";
if (category) {
endpoint = `filter.php?c=${category}`;
} else if (area) {
endpoint = `filter.php?a=${area}`;
}
if (endpoint) {
showLoading(true);
const data = await fetchAPI(endpoint);
allMeals = data.meals || [];
saveToLocalStorage(CACHE_KEY, allMeals);
displayMeals(allMeals);
showLoading(false);
}
}
// display
function displayMeals(meals, container = resultsContainer) {
container.innerHTML = "";
if (!meals || meals.length === 0) {
container.innerHTML =
'<p class="text-center text-gray-500 text-lg col-span-full">No meals found. Try a different search term or filter.</p>';
return;
}
meals.forEach((meal) => {
const isFavorite = favorites.some((fav) => fav.idMeal === meal.idMeal);
const mealCard = document.createElement("div");
mealCard.className =
"relative bg-gray-700 rounded-lg shadow-lg overflow-hidden transform hover:scale-105 transition-transform duration-300";
mealCard.innerHTML = `
<button class="absolute top-2 right-2 p-2 rounded-full bg-black/50 hover:bg-red-600 transition-colors duration-200" onclick="toggleFavorite(event, '${
meal.idMeal
}')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transition-transform transform" viewBox="0 0 24 24" fill="${
isFavorite ? "#f56565" : "none"
}" stroke="${
isFavorite ? "none" : "currentColor"
}" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
</button>
<img src="${meal.strMealThumb}" alt="${
meal.strMeal
}" class="w-full h-48 object-cover cursor-pointer" onclick="fetchMealDetails('${
meal.idMeal
}')">
<div class="p-4 cursor-pointer" onclick="fetchMealDetails('${
meal.idMeal
}')">
<h3 class="text-lg font-semibold text-gray-200">${
meal.strMeal
}</h3>
</div>
`;
container.appendChild(mealCard);
});
}
// toggle fav
async function toggleFavorite(event, mealId) {
event.stopPropagation();
const meal = allMeals.find((m) => m.idMeal === mealId);
const index = favorites.findIndex((fav) => fav.idMeal === mealId);
if (index > -1) {
// Remove from favorites
favorites.splice(index, 1);
} else if (meal) {
// Add to favorites
const detailsData = await fetchAPI(`lookup.php?i=${mealId}`);
const fullMeal = detailsData.meals[0];
favorites.push(fullMeal);
}
saveToLocalStorage(FAVORITES_KEY, favorites);
displayMeals(allMeals);
displayMeals(favorites, favoritesContainer);
}
// meal details
async function fetchMealDetails(mealId) {
showLoading(true);
const data = await fetchAPI(`lookup.php?i=${mealId}`);
const meal = data.meals[0];
showLoading(false);
displayMealDetails(meal);
}
// modal
function displayMealDetails(meal) {
const ingredientsList = [];
for (let i = 1; i <= 20; i++) {
const ingredient = meal[`strIngredient${i}`];
const measure = meal[`strMeasure${i}`];
if (ingredient) {
ingredientsList.push(`<li>${measure} ${ingredient}</li>`);
}
}
const isFavorite = favorites.some((fav) => fav.idMeal === meal.idMeal);
const heartSvg = `
<svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 transition-transform transform" viewBox="0 0 24 24" fill="${
isFavorite ? "#f56565" : "none"
}" stroke="${isFavorite ? "none" : "currentColor"}" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
</svg>
`;
modalContent.innerHTML = `
<div class="flex flex-col items-center">
<img src="${meal.strMealThumb}" alt="${
meal.strMeal
}" class="w-full rounded-md mb-4">
<h3 class="text-2xl font-bold text-gray-100 mb-2">${
meal.strMeal
}</h3>
<p class="text-gray-400 mb-4">Category: ${
meal.strCategory
} | Area: ${meal.strArea}</p>
</div>
<div class="absolute top-4 right-16 p-2 rounded-full bg-black/50 hover:bg-red-600 transition-colors duration-200 cursor-pointer" onclick="toggleFavorite(event, '${
meal.idMeal
}')">
${heartSvg}
</div>
<div class="mb-4">
<h4 class="text-lg font-semibold text-gray-200">Ingredients:</h4>
<ul class="list-disc list-inside text-gray-300 ml-4">
${ingredientsList.join("")}
</ul>
</div>
<div class="mb-4">
<h4 class="text-lg font-semibold text-gray-200">Instructions:</h4>
<p class="text-gray-300 whitespace-pre-line">${
meal.strInstructions
}</p>
</div>
${
meal.strYoutube
? `<a href="${meal.strYoutube}" target="_blank" class="block text-center text-blue-400 hover:underline">Watch on YouTube</a>`
: ""
}
`;
mealModal.classList.remove("hidden");
mealModal.classList.add("flex");
}
// local storage
function saveToLocalStorage(key, data) {
localStorage.setItem(key, JSON.stringify(data));
}
// Event Listeners
searchBtn.addEventListener("click", searchMeals);
randomBtn.addEventListener("click", fetchRandomMeal);
categoryFilter.addEventListener("change", filterMeals);
areaFilter.addEventListener("change", filterMeals);
closeModalBtn.addEventListener("click", () => {
mealModal.classList.add("hidden");
mealModal.classList.remove("flex");
});
mealModal.addEventListener("click", (e) => {
if (e.target === mealModal) {
mealModal.classList.add("hidden");
mealModal.classList.remove("flex");
}
});
// POST Request using JSONPlaceholder
const postForm = document.getElementById("post-form");
const postTitle = document.getElementById("post-title");
const postBody = document.getElementById("post-body");
const postResponse = document.getElementById("post-response");
if (postForm) {
postForm.addEventListener("submit", async (e) => {
e.preventDefault();
const title = postTitle.value.trim();
const body = postBody.value.trim();
if (!title || !body) {
postResponse.innerHTML = `<p class="text-red-400"> Please fill in both fields.</p>`;
return;
}
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts",
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title,
body,
userId: 1,
}),
}
);
const data = await response.json();
postResponse.innerHTML = `
<p class="text-green-400 font-semibold"> Recipe idea submitted!</p>
<p><strong>ID:</strong> ${data.id}</p>
<p><strong>Title:</strong> ${data.title}</p>
<p><strong>Description:</strong> ${data.body}</p>
`;
postForm.reset();
} catch (error) {
console.error("POST Error:", error);
postResponse.innerHTML = `<p class="text-red-400"> Error submitting recipe.</p>`;
}
});
}
// Initialization
document.addEventListener("DOMContentLoaded", () => {
fetchCategories();
fetchAreas();
const cachedMeals = JSON.parse(localStorage.getItem(CACHE_KEY));
if (cachedMeals && cachedMeals.length > 0) {
allMeals = cachedMeals;
displayMeals(allMeals);
} else {
resultsContainer.innerHTML =
'<p class="text-center text-gray-500 text-lg col-span-full">Use the search bar or filters to find delicious meals!</p>';
}
displayMeals(favorites, favoritesContainer);
});