-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
345 lines (314 loc) · 11.8 KB
/
app.js
File metadata and controls
345 lines (314 loc) · 11.8 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
/* Recipe Manager (single-file JS)
Features:
- add / edit / delete recipes
- persist to localStorage
- search recipes by title/description/ingredient
- serving-size scaling (adjust ingredient quantities)
- recipe image upload and display
Data model (stored in localStorage under 'recipes'):
[{
id: string,
title: string,
description: string,
time: number, // minutes
servings: number, // original servings
imageUrl: string, // base64 encoded image data
ingredients: [{qty:number|null, unit:string, name:string}],
procedure: string
}]
*/
// Image handling function
function handleImageUpload(event) {
const file = event.target.files[0];
if (!file) return;
// Basic file size validation (max 2MB)
if (file.size > 2 * 1024 * 1024) {
alert('Image size should be less than 2MB');
event.target.value = '';
return;
}
const reader = new FileReader();
reader.onload = function(e) {
document.getElementById('recipeImagePreview').src = e.target.result;
document.getElementById('imageData').value = e.target.result;
};
reader.readAsDataURL(file);
}
const LS_KEY = 'recipes_v1';
/* ---------- Utilities ---------- */
function uid(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}
function qs(sel){return document.querySelector(sel)}
function qsa(sel){return Array.from(document.querySelectorAll(sel))}
function loadRecipes(){
try{
const raw = localStorage.getItem(LS_KEY)
return raw ? JSON.parse(raw) : []
}catch(e){console.error('Error parsing recipes', e); return []}
}
function saveRecipes(data){localStorage.setItem(LS_KEY, JSON.stringify(data))}
/* Format numbers nicely (e.g., 1.5 -> 1 1/2) */
function formatQuantity(q){
if(q==null) return ''
if(Number.isInteger(q)) return String(q)
// try fractions for simple denominators
const tolerance = 1e-6
const maxDen = 8
for(let den=1; den<=maxDen; den++){
const num = Math.round(q*den)
if(Math.abs(q - num/den) < tolerance){
const whole = Math.floor(num/den)
const rem = num - whole*den
if(whole>0 && rem>0) return `${whole} ${rem}/${den}`
if(rem>0) return `${rem}/${den}`
return String(whole)
}
}
return +(Math.round(q*100)/100)
}
/* ---------- App State & Rendering ---------- */
let recipes = loadRecipes()
let selectedId = null
let filtered = recipes
const recipeListEl = qs('#recipeList')
const recipeViewEl = qs('#recipeView')
const searchInput = qs('#searchInput')
const addRecipeBtn = qs('#addRecipeBtn')
const formModal = qs('#formModal')
const recipeForm = qs('#recipeForm')
const formTitle = qs('#formTitle')
const closeFormBtn = qs('#closeFormBtn')
const cancelBtn = qs('#cancelBtn')
const ingredientsList = qs('#ingredientsList')
const addIngredientBtn = qs('#addIngredientBtn')
// wire up image input if present so handleImageUpload is used (avoids unused var lint)
// also wire up the recipe image file input (matches id in index.html)
const imageInput = qs('#recipeImage')
if(imageInput) imageInput.addEventListener('change', handleImageUpload)
function renderList(list){
recipeListEl.innerHTML = ''
if(list.length===0){
recipeListEl.innerHTML = '<p class="small">No recipes yet. Click + Add Recipe to create one.</p>'
return
}
list.forEach(r=>{
const div = document.createElement('div')
div.className='recipe-card'
div.tabIndex=0
div.innerHTML = `<strong>${escapeHtml(r.title)}</strong><div class="small">${escapeHtml(r.description||'')}</div>`
div.onclick = ()=>selectRecipe(r.id)
div.onkeypress = (e)=>{if(e.key==='Enter') selectRecipe(r.id)}
const controls = document.createElement('div')
controls.className='small'
controls.innerHTML = `Time: ${r.time||'–'} min · Serves: ${r.servings || '–'}`
div.appendChild(controls)
recipeListEl.appendChild(div)
})
}
function renderView(){
const r = recipes.find(x=>x.id===selectedId)
if(!r){
recipeViewEl.innerHTML = '<p class="placeholder">Select a recipe to view its details, or add a new recipe.</p>'
return
}
recipeViewEl.innerHTML = ''
const title = document.createElement('h2')
title.textContent = r.title
recipeViewEl.appendChild(title)
if(r.imageUrl) {
const img = document.createElement('img')
img.src = r.imageUrl
img.alt = r.title
img.className = 'recipe-image'
recipeViewEl.appendChild(img)
}
if(r.description) recipeViewEl.appendChild(el('p', r.description))
recipeViewEl.appendChild(el('p', `Time: ${r.time||'–'} min · Serves: ${r.servings}`))
// serving scaler
const scalerRow = document.createElement('div')
scalerRow.className='small'
scalerRow.innerHTML = `Change servings: <input id="scaleInput" type="number" min="1" value="${r.servings}" style="width:6rem"> <button id="applyScale" class="btn-inline">Apply</button>`
recipeViewEl.appendChild(scalerRow)
const ingTitle = el('h3','Ingredients')
recipeViewEl.appendChild(ingTitle)
const ul = document.createElement('ul')
ul.id='ingredientsUL'
r.ingredients.forEach(ing=>{
const li = document.createElement('li')
const qtyText = ing.qty==null? '': formatQuantity(ing.qty)
li.textContent = `${qtyText} ${ing.unit || ''} ${ing.name}`.trim()
ul.appendChild(li)
})
recipeViewEl.appendChild(ul)
const procTitle = el('h3','Procedure')
recipeViewEl.appendChild(procTitle)
recipeViewEl.appendChild(el('div', r.procedure || ''))
// actions
const actions = document.createElement('div')
actions.style.marginTop='1rem'
const editBtn = document.createElement('button')
editBtn.textContent='Edit'
editBtn.onclick = ()=>openForm(r.id)
const delBtn = document.createElement('button')
delBtn.textContent='Delete'
delBtn.onclick = ()=>{ if(confirm('Delete this recipe?')){ deleteRecipe(r.id) }}
actions.appendChild(editBtn)
actions.appendChild(delBtn)
recipeViewEl.appendChild(actions)
// scaling behavior
qs('#applyScale').onclick = ()=>{
const newServ = Number(qs('#scaleInput').value) || r.servings
applyScale(r.id, newServ)
}
}
function applyScale(id, newServings){
const r = recipes.find(x=>x.id===id)
if(!r) return
const factor = newServings / r.servings
// clone and scale quantities for view
const ul = qs('#ingredientsUL')
ul.innerHTML = ''
r.ingredients.forEach(ing=>{
const li = document.createElement('li')
const qty = ing.qty==null? null: ing.qty*factor
const qtyText = qty==null? '': formatQuantity(qty)
li.textContent = `${qtyText} ${ing.unit || ''} ${ing.name}`.trim()
ul.appendChild(li)
})
// update header
const p = qs('#recipeView > p')
if(p) p.textContent = `Time: ${r.time||'–'} min · Serves: ${newServings}`
}
/* ---------- CRUD ---------- */
function addRecipe(recipe){
recipe.id = uid()
recipes.unshift(recipe)
saveRecipes(recipes)
filtered = recipes
renderList(filtered)
selectRecipe(recipe.id)
}
function updateRecipe(id, patch){
const i = recipes.findIndex(r=>r.id===id)
if(i===-1) return
recipes[i] = Object.assign({}, recipes[i], patch)
saveRecipes(recipes)
filtered = recipes
renderList(filtered)
selectRecipe(id)
}
function deleteRecipe(id){
recipes = recipes.filter(r=>r.id!==id)
saveRecipes(recipes)
filtered = recipes
renderList(filtered)
if(selectedId===id) selectedId=null
renderView()
}
/* ---------- Forms & Helpers ---------- */
function openForm(id){
formModal.classList.remove('hidden')
if(id){
formTitle.textContent='Edit Recipe'
const r = recipes.find(x=>x.id===id)
if(!r) return
qs('#recipeId').value = r.id
qs('#title').value = r.title
qs('#description').value = r.description || ''
qs('#imageData').value = r.imageUrl || ''
qs('#recipeImagePreview').src = r.imageUrl || ''
qs('#time').value = r.time || ''
qs('#servings').value = r.servings || 1
qs('#procedure').value = r.procedure || ''
ingredientsList.innerHTML=''
r.ingredients.forEach(it=>addIngredientRow(it))
}else{
formTitle.textContent='Add Recipe'
recipeForm.reset()
qs('#recipeId').value=''
ingredientsList.innerHTML=''
// add two empty ingredient rows
addIngredientRow()
addIngredientRow()
}
}
function closeForm(){
formModal.classList.add('hidden')
}
function addIngredientRow(data={qty:'',unit:'',name:''}){
const row = document.createElement('div')
row.className='ingredient-row'
row.innerHTML = `\
<input placeholder="qty (optional)" class="ing-qty" value="${data.qty}" />\
<input placeholder="unit" class="ing-unit" value="${data.unit}" />\
<input placeholder="ingredient name" class="ing-name" value="${escapeAttr(data.name)}" />\
<button class="btn-inline remove-ing">Remove</button>`
const removeBtn = row.querySelector('.remove-ing')
removeBtn.onclick = ()=>row.remove()
ingredientsList.appendChild(row)
}
recipeForm.addEventListener('submit', e=>{
e.preventDefault()
const id = qs('#recipeId').value || null
const title = qs('#title').value.trim()
const description = qs('#description').value.trim()
const imageUrl = qs('#imageData').value || ''
const time = Number(qs('#time').value) || null
const servings = Number(qs('#servings').value) || 1
const procedure = qs('#procedure').value.trim()
// use qsa to select ingredient rows (ensures qsa helper is used and returns an array)
const ingRows = qsa('#ingredientsList .ingredient-row')
const ingredients = ingRows.map(r=>{
const qty = parseFloat(r.querySelector('.ing-qty').value) || null
const unit = r.querySelector('.ing-unit').value.trim()
const name = r.querySelector('.ing-name').value.trim()
return {qty,unit,name}
}).filter(i=>i.name)
const obj = {title,description,imageUrl,time,servings,ingredients,procedure}
if(id){ updateRecipe(id, obj) } else { addRecipe(obj) }
closeForm()
})
addIngredientBtn.addEventListener('click', ()=>addIngredientRow())
closeFormBtn.addEventListener('click', closeForm)
cancelBtn.addEventListener('click', closeForm)
addRecipeBtn.addEventListener('click', ()=>openForm(null))
/* ---------- Selection & Search ---------- */
function selectRecipe(id){
selectedId = id
renderView()
}
searchInput.addEventListener('input', ()=>{
const q = searchInput.value.trim().toLowerCase()
if(!q){ filtered = recipes; renderList(filtered); return }
filtered = recipes.filter(r=>{
if(r.title.toLowerCase().includes(q)) return true
if((r.description||'').toLowerCase().includes(q)) return true
if((r.procedure||'').toLowerCase().includes(q)) return true
if(r.ingredients.some(ing=>ing.name.toLowerCase().includes(q))) return true
return false
})
renderList(filtered)
})
/* ---------- Helpers ---------- */
function el(tag, text){const e=document.createElement(tag); e.textContent = text; return e}
function escapeHtml(s){ if(!s) return ''; return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>') }
function escapeAttr(s){ if(!s) return ''; return s.replace(/"/g,'"') }
/* ---------- Init & sample data ---------- */
function ensureSample(){
if(recipes.length===0){
recipes = [
{ id: uid(), title:'Pancakes', description:'Fluffy breakfast pancakes', time:20, servings:4,
ingredients:[{qty:1.5,unit:'cups',name:'flour'},{qty:1.25,unit:'cups',name:'milk'},{qty:1,unit:'',name:'egg'},{qty:2,unit:'tbsp',name:'sugar'},{qty:1,unit:'tbsp',name:'baking powder'}],
procedure:'Mix dry ingredients, whisk wet ingredients, combine and cook on griddle.'
},
{ id: uid(), title:'Tomato Pasta', description:'Simple tomato pasta', time:25, servings:2,
ingredients:[{qty:200,unit:'g',name:'pasta'},{qty:1,unit:'cup',name:'tomato sauce'},{qty:1,unit:'tbsp',name:'olive oil'},{qty:null,unit:'',name:'salt to taste'}],
procedure:'Cook pasta, heat sauce, combine and serve.'
}
]
saveRecipes(recipes)
}
}
ensureSample()
filtered = recipes
renderList(filtered)
renderView()