-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
777 lines (658 loc) · 23.4 KB
/
app.js
File metadata and controls
777 lines (658 loc) · 23.4 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
(function () {
"use strict";
// -----------------------------
// State + persistence
// -----------------------------
const STORAGE_KEY = "calorie-tracker-data";
let state = loadState();
let viewDate = todayKey();
function loadState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw);
return {
goal: parsed.goal || 2000,
days: parsed.days || {}
};
}
} catch (e) {
// ignore
}
return { goal: 2000, days: {} };
}
function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
function getEntries(dateKey) {
return state.days[dateKey] || [];
}
function setEntries(dateKey, entries) {
if (!entries || entries.length === 0) {
delete state.days[dateKey];
} else {
state.days[dateKey] = entries;
}
saveState();
}
// -----------------------------
// Helpers
// -----------------------------
function todayKey() {
const d = new Date();
return (
d.getFullYear() +
"-" +
String(d.getMonth() + 1).padStart(2, "0") +
"-" +
String(d.getDate()).padStart(2, "0")
);
}
function formatDisplayDate(key) {
const t = todayKey();
if (key === t) return "Today";
const y = new Date();
y.setDate(y.getDate() - 1);
const yKey =
y.getFullYear() +
"-" +
String(y.getMonth() + 1).padStart(2, "0") +
"-" +
String(y.getDate()).padStart(2, "0");
if (key === yKey) return "Yesterday";
const parts = key.split("-").map(Number);
const date = new Date(parts[0], parts[1] - 1, parts[2]);
return date.toLocaleDateString("en-US", {
weekday: "short",
month: "short",
day: "numeric"
});
}
function shiftDate(key, delta) {
const parts = key.split("-").map(Number);
const date = new Date(parts[0], parts[1] - 1, parts[2]);
date.setDate(date.getDate() + delta);
return (
date.getFullYear() +
"-" +
String(date.getMonth() + 1).padStart(2, "0") +
"-" +
String(date.getDate()).padStart(2, "0")
);
}
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}
function formatTime(iso) {
const d = new Date(iso);
return d.toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" });
}
function escapeHtml(str) {
const div = document.createElement("div");
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// -----------------------------
// Ring
// -----------------------------
const CIRCUMFERENCE = 2 * Math.PI * 52; // ~326.73
function updateRing(consumed, goal) {
const ratio = Math.min(consumed / goal, 1);
const offset = CIRCUMFERENCE - ratio * CIRCUMFERENCE;
ringFill.style.strokeDashoffset = offset;
if (consumed > goal) ringFill.classList.add("over");
else ringFill.classList.remove("over");
}
// -----------------------------
// DOM refs
// -----------------------------
const currentDateEl = document.getElementById("current-date");
const prevDayBtn = document.getElementById("prev-day");
const nextDayBtn = document.getElementById("next-day");
const caloriesConsumedEl = document.getElementById("calories-consumed");
const caloriesRemainingEl = document.getElementById("calories-remaining");
const calorieGoalEl = document.getElementById("calorie-goal");
const ringFill = document.getElementById("ring-fill");
const entryForm = document.getElementById("entry-form");
const foodNameInput = document.getElementById("food-name");
const foodCaloriesInput = document.getElementById("food-calories");
const entriesList = document.getElementById("entries-list");
const noEntries = document.getElementById("no-entries");
const clearAllBtn = document.getElementById("clear-all");
const goalInput = document.getElementById("goal-input");
// Calendar
const toggleCalBtn = document.getElementById("toggle-calendar");
const calendarSection = document.getElementById("calendar-section");
const calMonthLabel = document.getElementById("cal-month-label");
const prevMonthBtn = document.getElementById("prev-month");
const nextMonthBtn = document.getElementById("next-month");
const calDaysContainer = document.getElementById("cal-days");
let calendarOpen = false;
let calYear = new Date().getFullYear();
let calMonth = new Date().getMonth();
// Barcode tools
const barcodeInput = document.getElementById("barcode-input");
const barcodeLookupBtn = document.getElementById("barcode-lookup");
const barcodeScanBtn = document.getElementById("barcode-scan");
const barcodeStatus = document.getElementById("barcode-status");
// Saved scans UI
const savedSearchInput = document.getElementById("saved-search");
const savedListEl = document.getElementById("saved-list");
const savedEmptyEl = document.getElementById("saved-empty");
const savedClearBtn = document.getElementById("saved-clear");
// Saved scans persistence
const SCAN_DB_KEY = "calorie-tracker-scan-db-v1";
let scanDb = loadScanDb();
// Scanner modal
const scannerModal = document.getElementById("scanner-modal");
const scannerVideo = document.getElementById("scanner-video");
const scannerCloseBtn = document.getElementById("scanner-close");
let scanControls = null;
let codeReader = null;
// -----------------------------
// Render
// -----------------------------
function render() {
const entries = getEntries(viewDate);
const consumed = entries.reduce((sum, e) => sum + e.calories, 0);
const remaining = Math.max(0, state.goal - consumed);
currentDateEl.textContent = formatDisplayDate(viewDate);
nextDayBtn.disabled = viewDate >= todayKey();
nextDayBtn.style.opacity = viewDate >= todayKey() ? 0.3 : 1;
caloriesConsumedEl.textContent = consumed.toLocaleString();
caloriesRemainingEl.textContent = remaining.toLocaleString();
calorieGoalEl.textContent = state.goal.toLocaleString();
updateRing(consumed, state.goal);
goalInput.value = state.goal;
if (calendarOpen) {
const parts = viewDate.split("-").map(Number);
calYear = parts[0];
calMonth = parts[1] - 1;
renderCalendar();
}
entriesList.innerHTML = "";
if (entries.length === 0) {
noEntries.classList.remove("hidden");
} else {
noEntries.classList.add("hidden");
entries
.slice()
.reverse()
.forEach((entry) => {
const li = document.createElement("li");
li.className = "entry-item";
li.innerHTML =
'<div class="entry-info">' +
'<div class="entry-name">' +
escapeHtml(entry.name) +
"</div>" +
'<div class="entry-time">' +
formatTime(entry.time) +
"</div>" +
"</div>" +
'<div class="entry-right">' +
'<div class="entry-calories">' +
entry.calories +
" cal</div>" +
'<button class="btn-delete" type="button" aria-label="Delete" data-id="' +
entry.id +
'">×</button>' +
"</div>";
entriesList.appendChild(li);
});
}
}
// -----------------------------
// Event handlers: entries
// -----------------------------
entryForm.addEventListener("submit", function (e) {
e.preventDefault();
const name = foodNameInput.value.trim();
const calories = parseInt(foodCaloriesInput.value, 10);
if (!name || !calories || calories <= 0) return;
const entries = getEntries(viewDate);
entries.push({
id: generateId(),
name,
calories,
time: new Date().toISOString()
});
setEntries(viewDate, entries);
foodNameInput.value = "";
foodCaloriesInput.value = "";
foodNameInput.focus();
render();
});
entriesList.addEventListener("click", function (e) {
const btn = e.target.closest(".btn-delete");
if (!btn) return;
const id = btn.dataset.id;
const entries = getEntries(viewDate).filter((entry) => entry.id !== id);
setEntries(viewDate, entries);
render();
});
clearAllBtn.addEventListener("click", function () {
const entries = getEntries(viewDate);
if (entries.length === 0) return;
if (!confirm("Clear all entries for " + formatDisplayDate(viewDate) + "?")) return;
setEntries(viewDate, []);
render();
});
prevDayBtn.addEventListener("click", function () {
viewDate = shiftDate(viewDate, -1);
render();
});
nextDayBtn.addEventListener("click", function () {
if (viewDate >= todayKey()) return;
viewDate = shiftDate(viewDate, 1);
render();
});
goalInput.addEventListener("change", function () {
const val = parseInt(goalInput.value, 10);
if (val && val >= 500 && val <= 10000) {
state.goal = val;
saveState();
render();
} else {
goalInput.value = state.goal;
}
});
// -----------------------------
// Calendar
// -----------------------------
function renderCalendar() {
const monthNames = [
"January","February","March","April","May","June",
"July","August","September","October","November","December"
];
calMonthLabel.textContent = monthNames[calMonth] + " " + calYear;
const now = new Date();
const isFutureMonth = calYear > now.getFullYear() || (calYear === now.getFullYear() && calMonth >= now.getMonth());
nextMonthBtn.disabled = isFutureMonth;
nextMonthBtn.style.opacity = isFutureMonth ? 0.3 : 1;
calDaysContainer.innerHTML = "";
const firstDay = new Date(calYear, calMonth, 1).getDay();
const daysInMonth = new Date(calYear, calMonth + 1, 0).getDate();
const todayStr = todayKey();
for (let i = 0; i < firstDay; i++) {
const empty = document.createElement("div");
empty.className = "cal-cell cal-empty";
calDaysContainer.appendChild(empty);
}
for (let d = 1; d <= daysInMonth; d++) {
const dateKey =
calYear +
"-" +
String(calMonth + 1).padStart(2, "0") +
"-" +
String(d).padStart(2, "0");
const cell = document.createElement("div");
cell.className = "cal-cell";
if (dateKey > todayStr) {
cell.classList.add("cal-future");
} else {
cell.dataset.date = dateKey;
}
if (dateKey === todayStr) cell.classList.add("cal-today");
if (dateKey === viewDate) cell.classList.add("cal-selected");
const dayNum = document.createElement("span");
dayNum.className = "cal-day-num";
dayNum.textContent = d;
cell.appendChild(dayNum);
const entries = getEntries(dateKey);
if (entries.length > 0 && dateKey <= todayStr) {
const total = entries.reduce((sum, e) => sum + e.calories, 0);
const cals = document.createElement("span");
cals.className = "cal-day-cals";
if (total > state.goal) cals.classList.add("cal-over");
else cals.classList.add("cal-under");
cals.textContent = total;
cell.appendChild(cals);
cell.classList.add("cal-has-data");
}
calDaysContainer.appendChild(cell);
}
}
function toggleCalendar() {
calendarOpen = !calendarOpen;
if (calendarOpen) {
calendarSection.classList.remove("hidden");
toggleCalBtn.classList.add("active");
const parts = viewDate.split("-").map(Number);
calYear = parts[0];
calMonth = parts[1] - 1;
renderCalendar();
} else {
calendarSection.classList.add("hidden");
toggleCalBtn.classList.remove("active");
}
}
toggleCalBtn.addEventListener("click", toggleCalendar);
prevMonthBtn.addEventListener("click", function () {
calMonth--;
if (calMonth < 0) {
calMonth = 11;
calYear--;
}
renderCalendar();
});
nextMonthBtn.addEventListener("click", function () {
const now = new Date();
if (calYear === now.getFullYear() && calMonth >= now.getMonth()) return;
calMonth++;
if (calMonth > 11) {
calMonth = 0;
calYear++;
}
renderCalendar();
});
calDaysContainer.addEventListener("click", function (e) {
const cell = e.target.closest(".cal-cell[data-date]");
if (!cell) return;
viewDate = cell.dataset.date;
calendarOpen = false;
calendarSection.classList.add("hidden");
toggleCalBtn.classList.remove("active");
render();
});
function loadScanDb() {
try {
const raw = localStorage.getItem(SCAN_DB_KEY);
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed : [];
} catch (e) {
return [];
}
}
function saveScanDb() {
localStorage.setItem(SCAN_DB_KEY, JSON.stringify(scanDb));
}
function upsertScanItem(item) {
const barcode = String(item.barcode || "").replace(/\D/g, "");
if (!barcode) return;
const nowIso = new Date().toISOString();
const idx = scanDb.findIndex((x) => x.barcode === barcode);
const base = {
barcode,
name: String(item.name || "Scanned item").trim(),
kcalPerServing: item.kcalPerServing != null ? Number(item.kcalPerServing) : null,
kcalPer100g: item.kcalPer100g != null ? Number(item.kcalPer100g) : null,
servingText: item.servingText ? String(item.servingText).trim() : "",
updatedAt: nowIso,
timesUsed: 0
};
if (idx >= 0) {
scanDb[idx] = Object.assign({}, scanDb[idx], base);
} else {
scanDb.unshift(base);
}
// Keep a reasonable size
if (scanDb.length > 200) scanDb = scanDb.slice(0, 200);
saveScanDb();
renderSavedScans();
}
function incrementSavedUse(barcode) {
const cleaned = String(barcode || "").replace(/\D/g, "");
const idx = scanDb.findIndex((x) => x.barcode === cleaned);
if (idx < 0) return;
scanDb[idx].timesUsed = (scanDb[idx].timesUsed || 0) + 1;
scanDb[idx].updatedAt = new Date().toISOString();
// Move to top
const [it] = scanDb.splice(idx, 1);
scanDb.unshift(it);
saveScanDb();
renderSavedScans();
}
function forgetSavedScan(barcode) {
const cleaned = String(barcode || "").replace(/\D/g, "");
scanDb = scanDb.filter((x) => x.barcode !== cleaned);
saveScanDb();
renderSavedScans();
}
function renderSavedScans() {
if (!savedListEl) return;
const q = String(savedSearchInput && savedSearchInput.value ? savedSearchInput.value : "")
.trim()
.toLowerCase();
const items = scanDb.filter((x) => {
if (!q) return true;
return (
(x.name || "").toLowerCase().includes(q) ||
String(x.barcode || "").includes(q)
);
});
savedListEl.innerHTML = "";
if (items.length === 0) {
savedEmptyEl.classList.remove("hidden");
return;
}
savedEmptyEl.classList.add("hidden");
items.slice(0, 30).forEach((it) => {
const li = document.createElement("li");
li.className = "saved-item";
const subParts = [];
subParts.push(it.barcode);
if (it.kcalPerServing != null) subParts.push(Math.round(it.kcalPerServing) + " cal/serv");
else if (it.kcalPer100g != null) subParts.push(Math.round(it.kcalPer100g) + " cal/100g");
if (it.servingText) subParts.push(it.servingText);
li.innerHTML =
'<div class="saved-left">' +
'<div class="saved-name">' + escapeHtml(it.name || "Scanned item") + "</div>" +
'<div class="saved-sub">' + escapeHtml(subParts.join(" • ")) + "</div>" +
"</div>" +
'<div class="saved-actions">' +
'<button class="btn-add-small" type="button" data-action="add" data-barcode="' + escapeHtml(it.barcode) + '">Add</button>' +
'<button class="btn-forget" type="button" data-action="forget" data-barcode="' + escapeHtml(it.barcode) + '">✕</button>' +
"</div>";
savedListEl.appendChild(li);
});
}
function addSavedScanToLog(barcode) {
const cleaned = String(barcode || "").replace(/\D/g, "");
const it = scanDb.find((x) => x.barcode === cleaned);
if (!it) return;
let calories = null;
if (it.kcalPerServing != null) {
calories = Math.round(it.kcalPerServing);
} else if (it.kcalPer100g != null) {
let grams = prompt("Calories are per 100g. How many grams did you eat?", "100");
if (grams == null) return;
grams = parseFloat(String(grams).replace(/[^0-9.]/g, ""));
if (!grams || grams <= 0) {
alert("Invalid grams amount.");
return;
}
calories = Math.round((it.kcalPer100g * grams) / 100);
} else {
alert("This saved item has no calories data. Scan again or enter manually.");
return;
}
const entries = getEntries(viewDate);
entries.push({
id: generateId(),
name: it.name || "Scanned item",
calories,
time: new Date().toISOString()
});
setEntries(viewDate, entries);
incrementSavedUse(cleaned);
render();
}
// -----------------------------
// Barcode + Open Food Facts
// -----------------------------
function setBarcodeStatus(msg, isError) {
barcodeStatus.textContent = msg || "";
barcodeStatus.classList.toggle("error", !!isError);
}
async function lookupBarcode(barcode) {
const cleaned = String(barcode || "").replace(/\D/g, "");
if (!cleaned) {
setBarcodeStatus("Enter a barcode number first.", true);
return;
}
setBarcodeStatus("Looking up product...", false);
try {
const url = "https://world.openfoodfacts.net/api/v2/product/" + encodeURIComponent(cleaned) + ".json";
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) {
setBarcodeStatus("Lookup failed (" + res.status + "). Try again.", true);
return;
}
const data = await res.json();
if (!data || data.status !== 1 || !data.product) {
setBarcodeStatus("Product not found in Open Food Facts.", true);
return;
}
const p = data.product;
const name = (p.product_name || p.generic_name || "Scanned item").trim();
// Calories can appear in multiple places depending on the product.
const n = p.nutriments || {};
const kcalPerServing = numOrNull(n["energy-kcal_serving"]) || numOrNull(n["energy-kcal"]) || null;
const kcalPer100g = numOrNull(n["energy-kcal_100g"]) || null;
if (kcalPerServing != null) {
foodNameInput.value = name;
foodCaloriesInput.value = Math.round(kcalPerServing);
upsertScanItem({ barcode: cleaned, name, kcalPerServing: kcalPerServing, kcalPer100g: kcalPer100g, servingText: (p.serving_size || "") });
setBarcodeStatus("Found: " + name + " (per serving).", false);
foodCaloriesInput.focus();
return;
}
if (kcalPer100g != null) {
let grams = prompt("Calories are per 100g. How many grams did you eat?", "100");
if (grams == null) {
setBarcodeStatus("Found: " + name + " (per 100g). Enter grams to calculate.", false);
return;
}
grams = parseFloat(String(grams).replace(/[^0-9.]/g, ""));
if (!grams || grams <= 0) {
setBarcodeStatus("Invalid grams amount. Try again.", true);
return;
}
const cals = (kcalPer100g * grams) / 100;
foodNameInput.value = name;
foodCaloriesInput.value = Math.round(cals);
upsertScanItem({ barcode: cleaned, name, kcalPerServing: null, kcalPer100g: kcalPer100g, servingText: (p.serving_size || "") });
setBarcodeStatus("Found: " + name + " (" + grams + "g).", false);
foodCaloriesInput.focus();
return;
}
foodNameInput.value = name;
upsertScanItem({ barcode: cleaned, name, kcalPerServing: null, kcalPer100g: null, servingText: (p.serving_size || "") });
setBarcodeStatus("Found product name, but calories are missing. Enter calories manually.", true);
foodNameInput.focus();
} catch (err) {
setBarcodeStatus("Lookup error. Check your connection and try again.", true);
}
}
function numOrNull(v) {
const n = typeof v === "string" ? parseFloat(v) : v;
return Number.isFinite(n) ? n : null;
}
barcodeLookupBtn.addEventListener("click", function () {
lookupBarcode(barcodeInput.value);
});
barcodeInput.addEventListener("keydown", function (e) {
if (e.key === "Enter") {
e.preventDefault();
lookupBarcode(barcodeInput.value);
}
});
// Saved scans interactions
if (savedSearchInput) {
savedSearchInput.addEventListener("input", renderSavedScans);
}
if (savedListEl) {
savedListEl.addEventListener("click", function (e) {
const btn = e.target.closest("button[data-action]");
if (!btn) return;
const action = btn.dataset.action;
const barcode = btn.dataset.barcode;
if (action === "add") {
addSavedScanToLog(barcode);
} else if (action === "forget") {
forgetSavedScan(barcode);
}
});
}
if (savedClearBtn) {
savedClearBtn.addEventListener("click", function () {
if (scanDb.length === 0) return;
if (!confirm("Clear saved scans?")) return;
scanDb = [];
saveScanDb();
renderSavedScans();
});
}
// -----------------------------
// Barcode scanning (Safari-compatible via ZXing)
// -----------------------------
function openScanner() {
scannerModal.classList.remove("hidden");
setBarcodeStatus("", false);
}
function closeScanner() {
scannerModal.classList.add("hidden");
try {
if (scanControls && typeof scanControls.stop === "function") scanControls.stop();
} catch (e) {}
scanControls = null;
try {
if (codeReader && typeof codeReader.reset === "function") codeReader.reset();
} catch (e) {}
codeReader = null;
// Ensure camera stream stops (iOS can be sticky)
try {
const stream = scannerVideo.srcObject;
if (stream && stream.getTracks) stream.getTracks().forEach((t) => t.stop());
} catch (e) {}
scannerVideo.srcObject = null;
}
async function startScan() {
if (!window.ZXingBrowser || !ZXingBrowser.BrowserMultiFormatReader) {
setBarcodeStatus("Scanner library did not load. Try refreshing.", true);
return;
}
openScanner();
try {
codeReader = new ZXingBrowser.BrowserMultiFormatReader();
// Prefer back camera on phones
const constraints = { video: { facingMode: { ideal: "environment" } } };
scanControls = await codeReader.decodeFromConstraints(constraints, scannerVideo, (result, error, controls) => {
if (result) {
const text = result.getText ? result.getText() : String(result.text || "");
if (text) {
barcodeInput.value = text.replace(/\D/g, "");
setBarcodeStatus("Scanned: " + barcodeInput.value, false);
// Stop scanning immediately
try { controls.stop(); } catch (e) {}
closeScanner();
lookupBarcode(barcodeInput.value);
}
}
});
} catch (err) {
closeScanner();
setBarcodeStatus(
"Camera access failed. Make sure Safari has camera permission for this site.",
true
);
}
}
barcodeScanBtn.addEventListener("click", startScan);
scannerCloseBtn.addEventListener("click", closeScanner);
scannerModal.addEventListener("click", function (e) {
if (e.target === scannerModal) closeScanner();
});
// -----------------------------
// Service worker
// -----------------------------
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("sw.js");
}
// -----------------------------
// Init
// -----------------------------
renderSavedScans();
render();
})();