-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
439 lines (389 loc) · 19.5 KB
/
script.js
File metadata and controls
439 lines (389 loc) · 19.5 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/* ════════════════════════════════════════
SmartChef · script.js v4
Photos: Pexels CDN (always reliable)
Filters: fully independent of search
════════════════════════════════════════ */
/* ── STATE ── */
let lastSearch = "";
let lastUserIngredients = [];
let currentRecipeName = "";
const filters = { skill:"all", time:"all", fire:"all", category:"all" };
/* ── SPEECH ── */
const synth = window.speechSynthesis;
let currentStep = -1;
let isSpeaking = false;
/* ── EMOJI MAP ── */
const recipeEmoji = {"Fresh Orange Juice": "🍊",
"Watermelon Juice": "🍉",
"Pineapple Juice": "🍍",
"Mosambi Juice": "🍋","Orange Iced Tea": "🍹",
"Plain Omelette":"🍳","Masala Omelette":"🍳","Cheese Omelette":"🧀","Scrambled Eggs":"🥚",
"Boiled Eggs":"🥚","Egg Sandwich":"🥪","Egg Bhurji":"🍳","Egg Curry":"🥚","Egg Biryani":"🍳",
"Bread Butter Toast":"🍞","Garlic Bread":"🧄","Avocado Toast":"🥑","Grilled Sandwich":"🥪",
"French Toast":"🍞","Mushroom Toast":"🍄","Peanut Butter Toast":"🥜",
"Poha":"🌾","Upma":"🫕","Idli":"🍚","Dosa":"🫓","Masala Dosa":"🫓","Uttapam":"🫓",
"Medu Vada":"🍩","Rava Idli":"🍚","Pesarattu":"🫓","Pongal":"🍲","Ven Pongal":"🍲",
"Chicken Biryani":"🍛","Veg Biryani":"🍛","Mutton Biryani":"🍛","Hyderabadi Biryani":"🍛",
"Prawn Biryani":"🦐","Mushroom Biryani":"🍄","Egg Biryani":"🥚",
"Veg Fried Rice":"🍚","Egg Fried Rice":"🍳","Tomato Rice":"🍅","Lemon Rice":"🍋",
"Curd Rice":"🍚","Coconut Rice":"🥥","Tamarind Rice":"🍚","Veg Pulao":"🌿",
"Khichdi":"🍲","Rice and Dal":"🫘","Dahi Rice (Curd Rice)":"🍚",
"Chicken Curry":"🍛","Butter Chicken":"🍗","Palak Paneer":"🥬","Dal Makhani":"🫘",
"Dal Tadka":"🫘","Chana Masala":"🫘","Rajma":"🫘","Sambar":"🥣","Rasam":"🥣",
"Paneer Butter Masala":"🧀","Aloo Gobi":"🥔","Malai Kofta":"🍛","Dum Aloo":"🥔",
"Baingan Bharta":"🍆","Bhindi Masala":"🥬","Matar Paneer":"🧀","Lauki Sabzi":"🥒",
"Chicken 65":"🍗","Chicken Tikka":"🍗","Chicken Sandwich":"🥪","Chicken Burger":"🍔",
"Seekh Kebab":"🍢","Tandoori Chicken":"🍗","Shami Kebab":"🍢","Keema":"🥩",
"Mutton Curry":"🍛","Mutton Biryani":"🍛",
"Pav Bhaji":"🥔","Vada Pav":"🍔","Chole Bhature":"🫘","Samosa":"🥟","Pakora":"🧅",
"Aloo Tikki":"🥔","Dahi Puri":"🫙","Bhel Puri":"🌾",
"Coconut Chutney":"🥥","Kachumber Salad":"🥗",
"Roti":"🫓","Paratha":"🫓","Aloo Paratha":"🥔","Naan":"🫓","Puri":"🫓","Kulcha":"🫓",
"Maggi Noodles":"🍜","Veg Noodles":"🥦","Veg Pasta":"🍝","Cheese Pasta":"🧀",
"Aloo Fry":"🥔","Potato Sandwich":"🥔","Vegetable Stir Fry":"🥦",
"Veg Soup":"🥣","Tomato Soup":"🍅","Paneer Sandwich":"🫓",
"Paneer Fry":"🧀","Chilli Paneer":"🌶️","Paneer Tikka":"🧀","Paneer Curry":"🍛","Paneer Wrap":"🌯",
"Veg Roll":"🌯","Butter Corn":"🌽",
"Fruit Salad":"🍎","Veg Salad":"🥗","Sprouts Salad":"🌱",
"Fish Curry":"🐟","Prawn Masala":"🦐","Fish Fry":"🐟",
"Sarson Ka Saag":"🥬","Kadhi Pakora":"🍲","Punjabi Chole":"🫘",
"Shahi Paneer":"🧀","Pista Kulfi":"🍦","Gajar Ka Halwa":"🥕",
"Besan Ladoo":"🟡","Kheer":"🍚","Halwa":"🟡","Gulab Jamun":"🍩","Rasgulla":"⚪",
"Payasam":"🍚","Banana Halwa":"🍌","Suji Halwa":"🟡","Jalebi":"🌀",
"Coconut Ladoo":"🥥","Sooji Kheer":"🍚",
"Masala Chai":"🍵","Cold Coffee":"☕","Lemon Juice":"🍋","Mango Lassi":"🥭",
"Banana Milkshake":"🍌","Mango Shake":"🥭","Rose Milk":"🌸",
"Fruit Smoothie":"🍓","Chocolate Milkshake":"🍫","Iced Tea":"🧋",
"Lassi":"🥛","Buttermilk":"🥛","Coconut Water Cooler":"🥥",
"Bread Upma":"🍞","Dahi Rice":"🍚"
};
function getEmoji(name) { return recipeEmoji[name] || "🍽️"; }
/* ════════════════════════════════════════
PHOTO URL — Handles both Pexels IDs and Full URLs
════════════════════════════════════════ */
function photoUrl(recipe, w=600, h=400) {
if (!recipe || !recipe.photo) return null;
const imgData = recipe.photo;
// If the photo data is already a full URL (like from Wikipedia), just return it directly!
if (imgData.startsWith('http')) {
return imgData;
}
// Otherwise, treat it as a Pexels ID (your fallback)
return `https://images.pexels.com/photos/${imgData}/pexels-photo-${imgData}.jpeg?auto=compress&cs=tinysrgb&w=${w}&h=${h}&fit=crop`;
}
/* ── LAZY IMAGE LOADER ── */
function loadImg(imgEl) {
if (!imgEl) return;
const src = imgEl.dataset.src;
if (!src) return;
const tmp = new Image();
tmp.onload = () => { imgEl.src = src; imgEl.classList.add("loaded"); };
tmp.onerror = () => { imgEl.style.display = "none"; }; // shows emoji placeholder
tmp.src = src;
}
/* ════════════════════════════════════════
FILTER CHIPS
════════════════════════════════════════ */
document.querySelectorAll(".chip").forEach(btn => {
btn.addEventListener("click", () => {
const ft = btn.dataset.filter;
document.querySelectorAll(`.chip[data-filter="${ft}"]`).forEach(c => c.classList.remove("active"));
btn.classList.add("active");
filters[ft] = btn.dataset.value;
runSearch(); // always run — works with or without ingredients
});
});
/* ════════════════════════════════════════
FIND RECIPES (button / Enter key)
════════════════════════════════════════ */
function findRecipes(silent = false) {
const input = document.getElementById("ingredientsInput").value.trim();
if (input) {
lastSearch = input;
lastUserIngredients = input.toLowerCase().split(",").map(s => s.trim()).filter(Boolean);
}
if (!lastSearch && lastUserIngredients.length === 0) { shakeSearch(); return; }
runSearch();
if (!silent) document.getElementById("ingredientsInput").value = "";
setTimeout(() => document.getElementById("results").scrollIntoView({ behavior:"smooth", block:"start" }), 80);
}
/* ════════════════════════════════════════
CORE SEARCH — runs on both ingredient
search AND any filter chip change
════════════════════════════════════════ */
function runSearch() {
const hasIngredients = lastUserIngredients.length > 0;
const matched = [];
recipes.forEach(recipe => {
// FILTERS (always applied regardless of ingredients)
const skillOk = filters.skill === "all" || recipe.skill === filters.skill;
const timeOk = filters.time === "all" || recipe.time <= parseInt(filters.time);
const fireOk = filters.fire === "all"
|| (filters.fire === "fire" && recipe.fire === true)
|| (filters.fire === "fireless" && recipe.fire === false);
const categoryOk = filters.category === "all" || recipe.category === filters.category;
if (!skillOk || !timeOk || !fireOk || !categoryOk) return;
if (hasIngredients) {
// ingredient matching
let score = 0, missing = [], heroMatch = false;
recipe.hero.forEach(h => {
if (lastUserIngredients.includes(h)) { score += 5; heroMatch = true; }
});
recipe.ingredients.forEach(item => {
if (lastUserIngredients.includes(item)) score += 1;
else missing.push(item);
});
if (!heroMatch) return;
matched.push({ recipe, score, missing });
} else {
// no ingredients typed → show everything that passes filters
matched.push({ recipe, score: 0, missing: [] });
}
});
matched.sort((a, b) => b.score - a.score || a.recipe.name.localeCompare(b.recipe.name));
renderResults(matched, hasIngredients);
}
/* ════════════════════════════════════════
RENDER CARDS
════════════════════════════════════════ */
function renderResults(matched, hasIngredients) {
const el = document.getElementById("results");
if (!matched.length) {
el.innerHTML = `
<div class="empty-state">
<span class="empty-emoji">🤷</span>
<h3>Nothing found</h3>
<p>${hasIngredients ? "Try different ingredients or" : "Try"} relaxing the filters above.</p>
<div class="suggestion-pills">
${["egg","chicken","rice","bread","paneer","dal","potato","mutton","dosa batter","milk"]
.map(s => `<button class="suggestion-pill" onclick="tryIngredient('${s}')">${s}</button>`)
.join("")}
</div>
</div>`;
return;
}
const maxScore = matched[0].score || 1;
const label = hasIngredients
? `<span>${matched.length}</span> recipe${matched.length!==1?"s":""} matching "<em>${lastSearch}</em>"`
: `<span>${matched.length}</span> recipe${matched.length!==1?"s":""} available`;
const metaHTML = `<p class="result-meta">${label}</p>`;
const cardsHTML = matched.map(({ recipe, score, missing }, idx) => {
const pct = hasIngredients ? Math.round((score / maxScore) * 100) : 100;
const emoji = getEmoji(recipe.name);
const url = photoUrl(recipe);
const skillBadge = `<span class="badge badge-${recipe.skill}">${recipe.skill}</span>`;
const fireBadge = recipe.fire
? `<span class="badge badge-fire">🔥 Fire</span>`
: `<span class="badge badge-nofire">❄️ No Fire</span>`;
const drinkBadge = recipe.category === "drink"
? `<span class="badge badge-drink">🥤</span>` : "";
let missTxt, missCls = "";
if (hasIngredients) {
missTxt = missing.length
? `Need: <span class="miss-ing">${missing.slice(0,4).join(", ")}${missing.length>4?" …":""}</span>`
: `✅ You have everything!`;
if (!missing.length) missCls = "all-good";
} else {
missTxt = `${recipe.ingredients.length} ingredients`;
}
const photoHTML = url
? `<img data-src="${url}" alt="${recipe.name}" loading="lazy">`
: "";
return `
<div class="recipe-card" style="animation-delay:${Math.min(idx,12)*0.04}s"
onclick="openModal('${recipe.name.replace(/'/g,"\\'")}')">
<div class="card-photo">
<div class="card-photo-placeholder">${emoji}</div>
${photoHTML}
<div class="card-photo-overlay"></div>
<div class="card-top-badges">${skillBadge}${fireBadge}${drinkBadge}</div>
<span class="card-time-badge">⏱ ${recipe.time} min</span>
</div>
<div class="card-body">
<h3 class="card-title">${recipe.name}</h3>
<p class="card-hero">Key: <strong>${recipe.hero.join(", ")}</strong></p>
<p class="card-missing ${missCls}">${missTxt}</p>
<div class="match-bar-wrap"><div class="match-bar" style="width:${pct}%"></div></div>
</div>
</div>`;
}).join("");
el.innerHTML = metaHTML + `<div id="cardsGrid">${cardsHTML}</div>`;
el.querySelector("#cardsGrid").style.cssText =
"display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:24px;";
// Lazy-load all card photos
el.querySelectorAll(".card-photo img[data-src]").forEach(loadImg);
}
/* ════════════════════════════════════════
MODAL
════════════════════════════════════════ */
function openModal(recipeName) {
stopSpeech();
currentRecipeName = recipeName;
const recipe = recipes.find(r => r.name === recipeName);
if (!recipe) return;
const emoji = getEmoji(recipe.name);
const url = photoUrl(recipe, 800, 420);
const skillBadge = `<span class="badge badge-${recipe.skill}">${cap(recipe.skill)}</span>`;
const fireBadge = recipe.fire
? `<span class="badge badge-fire">🔥 Fire cooking</span>`
: `<span class="badge badge-nofire">❄️ No fire needed</span>`;
const catBadge = recipe.category === "drink"
? `<span class="badge badge-drink">🥤 Drink</span>`
: `<span class="badge badge-beginner">🍽️ Food</span>`;
const timeBadge = `<span class="badge badge-nofire">⏱ ${recipe.time} min</span>`;
const ingHTML = recipe.ingredients.map(ing => {
const have = lastUserIngredients.includes(ing);
return `<span class="ing-chip ${have?"ing-have":"ing-need"}">${have?"✓":"+"} ${ing}</span>`;
}).join("");
const stepsHTML = recipe.steps.map((step, i) =>
`<li class="step-item" id="step-${i}">
<span class="step-num">${i+1}</span>
<span class="step-text">${step}</span>
</li>`
).join("");
const photoHTML = url
? `<img class="modal-photo" data-src="${url}" alt="${recipe.name}">`
: "";
const voiceHTML = ('speechSynthesis' in window) ? `
<div class="voice-controls" id="voiceControls">
<button class="voice-btn" id="voiceBtn" onclick="toggleVoice('${recipe.name.replace(/'/g,"\\'")}')">
${iconPlay()}
</button>
<div class="voice-info">
<p class="voice-status" id="voiceStatus">🎙️ Read all steps aloud</p>
<p class="voice-step-indicator" id="voiceStepInd">${recipe.steps.length} steps · tap to start</p>
</div>
<div class="voice-speed">
<label for="speedRange">Speed</label>
<input type="range" id="speedRange" min="0.6" max="1.6" step="0.1" value="0.9">
<span id="speedVal">0.9×</span>
</div>
</div>` : "";
document.getElementById("modalContent").innerHTML = `
<div class="modal-photo-wrap">
<div class="modal-photo-placeholder">${emoji}</div>
${photoHTML}
<div class="modal-photo-overlay"></div>
</div>
<div class="modal-body">
<p class="modal-eyebrow">SmartChef Recipe</p>
<h2 class="modal-title">${recipe.name}</h2>
<div class="modal-badges">${skillBadge}${fireBadge}${catBadge}${timeBadge}</div>
<hr class="modal-divider">
<p class="section-label">Ingredients</p>
<div class="ingredients-chips">${ingHTML}</div>
<p class="ing-legend">✓ green = you have it | + red = still needed</p>
<hr class="modal-divider">
<p class="section-label">How to Cook</p>
${voiceHTML}
<ol class="steps-list">${stepsHTML}</ol>
</div>`;
// Load modal photo
const mImg = document.querySelector(".modal-photo[data-src]");
if (mImg) {
const tmp = new Image();
tmp.onload = () => { mImg.src = mImg.dataset.src; mImg.classList.add("loaded"); };
tmp.onerror = () => { mImg.style.display = "none"; };
tmp.src = mImg.dataset.src;
}
// Speed slider
const rng = document.getElementById("speedRange");
const valEl = document.getElementById("speedVal");
if (rng && valEl) {
rng.addEventListener("input", () => {
valEl.textContent = parseFloat(rng.value).toFixed(1) + "×";
});
}
document.getElementById("modal").classList.add("open");
document.body.style.overflow = "hidden";
}
function closeModal() {
stopSpeech();
document.getElementById("modal").classList.remove("open");
document.body.style.overflow = "";
}
document.addEventListener("keydown", e => { if (e.key === "Escape") closeModal(); });
/* ════════════════════════════════════════
VOICE — Web Speech API
════════════════════════════════════════ */
function toggleVoice(recipeName) {
isSpeaking ? stopSpeech() : startSpeech(recipeName);
}
function startSpeech(recipeName) {
if (!('speechSynthesis' in window)) return;
const recipe = recipes.find(r => r.name === recipeName);
if (!recipe) return;
stopSpeech();
isSpeaking = true;
const rate = parseFloat(document.getElementById("speedRange")?.value || 0.9);
synth.cancel();
const speak = (text, onStart, onEnd) => {
const u = new SpeechSynthesisUtterance(text);
u.rate = rate; u.pitch = 1.0;
if (onStart) u.onstart = onStart;
if (onEnd) u.onend = onEnd;
synth.speak(u);
};
setVoiceBtn(true);
setVoiceStatus(`▶ ${recipe.name}`);
speak(`Let's cook ${recipe.name}. Here are ${recipe.steps.length} steps.`);
recipe.steps.forEach((step, i) => {
const isLast = i === recipe.steps.length - 1;
speak(
`Step ${i+1}. ${step}`,
() => { currentStep = i; highlightStep(i); setVoiceStepInd(`Step ${i+1} of ${recipe.steps.length}`); },
isLast ? () => {
speak("All done! Enjoy your meal!", null, () => {
isSpeaking = false; currentStep = -1;
setVoiceBtn(false);
setVoiceStatus("🎙️ Read all steps aloud");
setVoiceStepInd(`${recipe.steps.length} steps · tap to start`);
clearHighlight();
});
} : null
);
});
}
function stopSpeech() {
if (synth) synth.cancel();
isSpeaking = false; currentStep = -1;
setVoiceBtn(false);
setVoiceStatus("🎙️ Read all steps aloud");
clearHighlight();
const r = recipes.find(r => r.name === currentRecipeName);
if (r) setVoiceStepInd(`${r.steps.length} steps · tap to start`);
}
function highlightStep(idx) {
document.querySelectorAll(".step-item").forEach(el => el.classList.remove("active"));
const el = document.getElementById(`step-${idx}`);
if (el) { el.classList.add("active"); el.scrollIntoView({ behavior:"smooth", block:"nearest" }); }
}
function clearHighlight() {
document.querySelectorAll(".step-item").forEach(el => el.classList.remove("active"));
}
function setVoiceBtn(on) {
const btn = document.getElementById("voiceBtn");
if (btn) { btn.innerHTML = on ? iconStop() : iconPlay(); btn.classList.toggle("speaking", on); }
}
function setVoiceStatus(t) { const e=document.getElementById("voiceStatus"); if(e) e.textContent=t; }
function setVoiceStepInd(t) { const e=document.getElementById("voiceStepInd"); if(e) e.textContent=t; }
function iconPlay() { return `<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg>`; }
function iconStop() { return `<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>`; }
/* ════════════════════════════════════════
UTILS
════════════════════════════════════════ */
function cap(s) { return s.charAt(0).toUpperCase() + s.slice(1); }
function tryIngredient(ing) {
lastSearch = ing;
lastUserIngredients = [ing];
runSearch();
setTimeout(() => document.getElementById("results").scrollIntoView({ behavior:"smooth", block:"start" }), 80);
}
function shakeSearch() {
const w = document.querySelector(".search-wrap");
w.style.animation = "none"; w.offsetHeight;
w.style.animation = "shake .4s ease";
}
document.getElementById("ingredientsInput")
.addEventListener("keypress", e => { if (e.key === "Enter") findRecipes(); });
window.addEventListener("beforeunload", () => synth && synth.cancel());