-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
206 lines (180 loc) · 6.36 KB
/
Copy pathscript.js
File metadata and controls
206 lines (180 loc) · 6.36 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
const API_URL = 'https://www.themealdb.com/api/json/v1/1/random.php';
const LOCAL_URL = './kenyan-dishes.json';
const WIKI_SUMMARY_URL = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
const generateBtn = document.getElementById('generateBtn');
const recipeCard = document.getElementById('recipeCard');
const loading = document.getElementById('loading');
const loadingText = document.getElementById('loadingText');
const emptyState = document.getElementById('emptyState');
const filterBtns = document.querySelectorAll('.filter-btn');
const LOADING_LINES = [
'Firing up the stove...',
'Chasing down a recipe...',
'Checking the pantry...',
'Plating something good...'
];
let localRecipes = [];
let currentFilter = 'surprise';
const wikiImageCache = {};
function init() {
fetch(LOCAL_URL)
.then(res => {
if (!res.ok) throw new Error('Failed to load local recipes');
return res.json();
})
.then(data => {
localRecipes = data;
})
.catch(err => {
console.error('Local recipes load failed:', err);
});
}
function normalizeMeal(meal) {
const ingredients = [];
for (let i = 1; i <= 20; i++) {
const ingredient = meal[`strIngredient${i}`];
const measure = meal[`strMeasure${i}`];
if (ingredient && ingredient.trim()) {
ingredients.push({
item: ingredient.trim(),
measure: measure ? measure.trim() : ''
});
}
}
const category = meal.strCategory ? meal.strCategory.toLowerCase() : 'main';
return {
id: meal.idMeal || `api-${Date.now()}`,
name: meal.strMeal,
origin: meal.strArea || 'Unknown',
category: category,
image: meal.strMealThumb || '',
ingredients: ingredients,
instructions: meal.strInstructions || 'No instructions provided.',
source: 'api'
};
}
// TheMealDB has no Kenyan entries, but if it ever returns something
// tagged Kenyan we still don't want it showing up under "World only" -
// that filter's whole point is to guarantee non-Kenyan results.
async function fetchRandomApiMeal(excludeKenyan) {
for (let attempt = 0; attempt < 3; attempt++) {
const res = await fetch(API_URL);
if (!res.ok) throw new Error('API fetch failed');
const data = await res.json();
const meal = normalizeMeal(data.meals[0]);
if (!excludeKenyan || meal.origin.toLowerCase() !== 'kenyan') {
return meal;
}
}
throw new Error('Could not find a non-Kenyan meal after retries');
}
function getRandomLocalMeal() {
if (!localRecipes.length) throw new Error('No local recipes available');
const idx = Math.floor(Math.random() * localRecipes.length);
return { ...localRecipes[idx] };
}
// Kenyan dishes don't have a reliable image API, so we look up a real
// photo from Wikipedia's page-summary endpoint at render time and fall
// back to the bundled illustration only if that lookup fails.
async function resolveLocalImage(recipe) {
if (!recipe.wikiTitle) return recipe.fallbackImage;
if (wikiImageCache[recipe.wikiTitle]) return wikiImageCache[recipe.wikiTitle];
try {
const res = await fetch(WIKI_SUMMARY_URL + encodeURIComponent(recipe.wikiTitle));
if (!res.ok) throw new Error('Wikipedia lookup failed');
const data = await res.json();
const src = (data.thumbnail && data.thumbnail.source) || (data.originalimage && data.originalimage.source);
if (!src) throw new Error('No image in Wikipedia summary');
wikiImageCache[recipe.wikiTitle] = src;
return src;
} catch (err) {
console.warn(`Wikipedia photo lookup failed for "${recipe.wikiTitle}", using fallback:`, err);
return recipe.fallbackImage;
}
}
function setLoading(isLoading) {
if (isLoading) {
loadingText.textContent = LOADING_LINES[Math.floor(Math.random() * LOADING_LINES.length)];
loading.classList.remove('hidden');
emptyState.classList.add('hidden');
recipeCard.classList.add('hidden');
recipeCard.classList.remove('visible');
generateBtn.disabled = true;
} else {
loading.classList.add('hidden');
generateBtn.disabled = false;
}
}
function renderRecipe(recipe, imageSrc) {
const img = document.getElementById('recipeImage');
img.src = imageSrc;
img.alt = recipe.name;
document.getElementById('recipeName').textContent = recipe.name;
document.getElementById('categoryTag').textContent = recipe.category;
document.getElementById('originBadge').textContent = recipe.origin;
const ingredientList = document.getElementById('ingredientList');
ingredientList.innerHTML = recipe.ingredients.map(ing => {
const measure = ing.measure ? `<span class="measure">${ing.measure}</span>` : '';
return `<li><span class="item">${ing.item}</span>${measure}</li>`;
}).join('');
ingredientList.querySelectorAll('li').forEach(li => {
li.addEventListener('click', () => li.classList.toggle('checked'));
});
const instructionList = document.getElementById('instructionList');
const steps = recipe.instructions
.split('\n')
.map(s => s.trim())
.filter(s => /^\d+\./.test(s));
const finalSteps = steps.length
? steps
: recipe.instructions.split('.').map(s => s.trim()).filter(Boolean);
instructionList.innerHTML = finalSteps
.map(step => `<li>${step.replace(/^\d+\.\s*/, '')}</li>`)
.join('');
emptyState.classList.add('hidden');
recipeCard.classList.remove('hidden');
requestAnimationFrame(() => {
recipeCard.classList.add('visible');
});
}
async function generateRecipe() {
setLoading(true);
let recipe;
let source;
if (currentFilter === 'kenyan') {
source = 'local';
} else if (currentFilter === 'world') {
source = 'api';
} else {
const rand = Math.random();
source = rand < 0.3 ? 'local' : 'api';
}
try {
if (source === 'api') {
recipe = await fetchRandomApiMeal(true);
} else {
recipe = getRandomLocalMeal();
}
} catch (err) {
console.warn('Primary source failed, falling back to local:', err);
if (!localRecipes.length) {
setLoading(false);
return;
}
recipe = getRandomLocalMeal();
}
const imageSrc = recipe.source === 'local'
? await resolveLocalImage(recipe)
: recipe.image;
setLoading(false);
renderRecipe(recipe, imageSrc);
}
filterBtns.forEach(btn => {
btn.addEventListener('click', () => {
filterBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentFilter = btn.dataset.filter;
});
});
generateBtn.addEventListener('click', generateRecipe);
init();