-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscan.html
More file actions
585 lines (545 loc) · 20.9 KB
/
scan.html
File metadata and controls
585 lines (545 loc) · 20.9 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Scan Product — Sustainable Food Tracker</title>
<style>
:root{
--bg:#fbf9f7;
--muted:#7a8a85;
--green-1:#2cc07a;
--green-2:#11a0f2; /* used for gradient */
--card:#ffffff;
--radius:14px;
--soft-shadow: 0 8px 30px rgba(10,30,20,0.06);
--glass: rgba(255,255,255,0.85);
font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial;
}
*{box-sizing:border-box}
html,body{height:100%}
body{
margin:0;
background:var(--bg);
color:#16302f;
-webkit-font-smoothing:antialiased;
-moz-osx-font-smoothing:grayscale;
display:flex;
flex-direction:column;
align-items:stretch;
min-height:100vh;
}
/* Top bar (modal header) */
header.modal-header{
height:58px;
display:flex;
align-items:center;
justify-content:center;
position:relative;
border-bottom:1px solid rgba(10,20,18,0.04);
background:transparent;
}
header.modal-header .title{
margin-top:16px;
font-weight:600;
font-size:18px;
color:#0a1412;
line-height:1.3;
}
header.modal-header .placeholder{
display:flex;
flex-direction:column;
align-items:center;
justify-content:center;
text-align:center;
color:var(--muted);
width:100%;
padding:20px;
}
header.modal-header .close{
position:absolute;
right:18px;
top:50%;
transform:translateY(-50%);
background:transparent;
border:0;
font-size:20px;
line-height:1;
cursor:pointer;
color:var(--muted);
}
/* Content area */
.content{
width:100%;
max-width:780px;
margin:0 auto;
padding:20px 18px 100px;
display:flex;
flex-direction:column;
align-items:center;
justify-content:center;
min-height:calc(100vh - 58px); /* Subtract header height */
box-sizing:border-box;
}
/* camera frame */
.frame-wrap{
display:flex;
justify-content:center;
align-items:center;
width:100%;
padding:20px 0;
flex-grow:1;
}
.frame{
width:100%;
max-width:360px;
aspect-ratio:1/1;
border-radius:18px;
background: linear-gradient(180deg, rgba(196,247,234,0.5), rgba(223,245,255,0.65));
box-shadow: 0 18px 36px rgba(4,120,76,0.06);
display:flex;
align-items:center;
justify-content:center;
position:relative;
margin:0 auto;
padding:18px;
}
/* inner decorative border */
.frame .inner{
position:absolute;
inset:28px;
border-radius:12px;
border:4px solid rgba(12,185,121,0.9);
pointer-events:none;
box-shadow: inset 0 0 0 8px rgba(255,255,255,0.3);
}
/* video/canvas */
.camera{
width:100%;
height:100%;
position:relative;
overflow:hidden;
border-radius:12px;
display:flex;
align-items:center;
justify-content:center;
background:rgba(255,255,255,0.3);
}
/* icon & hint centered when camera not ready */
.placeholder{
display:flex;
flex-direction:column;
align-items:center;
justify-content:center;
gap:10px;
text-align:center;
max-width:240px;
}
.placeholder svg{opacity:0.9}
.placeholder .title{font-weight:700}
.placeholder .sub{color:var(--muted); font-size:13px}
/* instruction card */
.info-card{
width:100%;
max-width:540px;
background:var(--card);
border-radius:12px;
padding:18px;
box-shadow:var(--soft-shadow);
border:1px solid rgba(10,20,18,0.03);
}
.info-row{
display:flex;
gap:12px;
align-items:flex-start;
}
.info-icon{
width:36px;height:36px;border-radius:8px;background:linear-gradient(180deg, rgba(16,211,130,0.12), rgba(16,211,130,0.06));display:flex;align-items:center;justify-content:center;color:var(--green-1);
font-weight:700;
}
.info-card h3{margin:0 0 8px 0;font-size:16px}
.howlist{margin:0;padding-left:20px;color:var(--muted);font-size:14px}
.howlist li{margin:8px 0 8px 0}
/* scan button */
.scan-now{
display:inline-flex;
align-items:center;
justify-content:center;
gap:8px;
padding:14px 24px;
background:linear-gradient(to right, var(--green-1), var(--green-2));
color:white;
border:none;
border-radius:12px;
font-weight:600;
font-size:16px;
cursor:pointer;
transition:all 0.2s ease;
box-shadow:0 4px 12px rgba(12,185,121,0.2);
width:100%;
max-width:280px;
margin:0 auto;
}
/* small helper row (file input) */
.capture-options{
margin-top:12px;
text-align:center;
width:100%;
}
.file-label{
background:transparent;border:1px dashed rgba(10,20,18,0.06);padding:8px 12px;border-radius:10px;color:var(--muted);cursor:pointer;font-size:14px;
}
.hidden{display:none}
/* bottom nav */
.bottom-nav{
position:fixed;
left:50%;
transform:translateX(-50%);
bottom:12px;
width:96%;
max-width:780px;
background:rgba(255,255,255,1);
border-radius:16px;
padding:8px 18px;
box-shadow:0 18px 40px rgba(12,30,25,0.06);
display:flex;
justify-content:space-around;
align-items:center;
gap:10px;
border:1px solid rgba(10,20,18,0.04);
}
.nav-item{display:flex;flex-direction:column;align-items:center;gap:6px;color:var(--muted);font-size:12px;text-decoration:none}
.nav-item.active{background:#e9fff4;padding:8px 12px;border-radius:12px;color:var(--green-1)}
/* responsiveness */
@media (max-width:680px){
.frame{width:300px;height:300px}
.content{padding:12px;margin-bottom:120px}
}
@media (max-width:420px){
.frame{width:260px;height:260px}
.info-card{padding:14px}
.scan-now{width:100%}
.bottom-nav{padding:10px;gap:6px}
}
</style>
</head>
<body>
<header class="modal-header" role="banner" aria-label="Scan header">
<button class="close" aria-label="Close" onclick="onClose()">✕</button>
<h1>Scan Product</h1>
</header>
<main class="content" role="main">
<div class="frame-wrap" aria-hidden="false">
<div class="frame" id="frame">
<!-- inner decorative border -->
<div class="inner" aria-hidden="true"></div>
<!-- camera area -->
<div class="camera" id="cameraArea">
<!-- video will be injected here or fallback placeholder shown -->
<div class="placeholder" id="placeholder">
<svg width="72" height="72" viewBox="0 0 24 24" fill="none" aria-hidden>
<path d="M3 7h3l2-2h6l2 2h3v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z" stroke="#23b07a" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="12" cy="12.2" r="3" stroke="#23b07a" stroke-width="1.6"/>
</svg>
<div class="title">Position barcode in frame</div>
<div class="sub">Or take a photo</div>
</div>
</div>
</div>
</div>
<div class="info-card" role="region" aria-labelledby="how-title">
<div class="info-row">
<div class="info-icon" aria-hidden>⎋</div>
<div>
<h3 id="how-title">How to scan</h3>
<ol class="howlist">
<li>Position the barcode inside the frame</li>
<li>Hold steady until it scans automatically</li>
<li>Or tap the <strong>Scan Now</strong> button below</li>
</ol>
</div>
</div>
<div class="actions" style="flex-direction:column;gap:8px">
<button class="scan-now" id="scanBtn" aria-label="Scan now">
<!-- small icon -->
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden>
<path d="M3 7v10" stroke="white" stroke-width="1.6" stroke-linecap="round"/>
<path d="M7 7v10" stroke="white" stroke-width="1.6" stroke-linecap="round"/>
<path d="M11 7v10" stroke="white" stroke-width="1.6" stroke-linecap="round"/>
<path d="M15 7v10" stroke="white" stroke-width="1.6" stroke-linecap="round"/>
<path d="M19 7v10" stroke="white" stroke-width="1.6" stroke-linecap="round"/>
</svg>
<span id="scanLabel">Scan Now</span>
</button>
<div class="capture-options">
<!-- file input fallback for devices without camera or for image upload -->
<label class="file-label" for="fileInput">📷 Upload photo</label>
<input id="fileInput" class="hidden" type="file" accept="image/*" capture="environment" />
</div>
</div>
</div>
</main>
<nav class="bottom-nav" role="navigation" aria-label="Main navigation">
<a href="Index.html" class="nav-item" aria-label="Home">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><path d="M3 11.5L12 4l9 7.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 21h14V11" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>Home</span>
</a>
<a href="scan.html" class="nav-item active" aria-current="page" aria-label="Scan">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><rect x="3" y="3" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/><rect x="14" y="14" width="7" height="7" rx="1.5" stroke="currentColor" stroke-width="1.4"/><path d="M21 3v7M3 21v-7" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
<span>Scan</span>
</a>
<a href="history.html" class="nav-item" aria-label="History">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><path d="M3 12a9 9 0 1 0 9-9" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 7v6l4 2" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>History</span>
</a>
<a href="rewards.html" class="nav-item" aria-label="Rewards">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden><path d="M12 2l2.5 6L20 9l-5 3.8L16 20l-4-2.5L8 20l1-7.2L4 9l5.5-1L12 2z" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>
<span>Rewards</span>
</a>
</nav>
<!-- hidden canvas used to grab frame */
<canvas id="captureCanvas" class="hidden"></canvas>
<!-- ZXing barcode library -->
<script src="https://unpkg.com/@zxing/library@0.20.0"></script>
<script>
(function(){
const frame = document.getElementById('frame');
const cameraArea = document.getElementById('cameraArea');
const placeholder = document.getElementById('placeholder');
const scanBtn = document.getElementById('scanBtn');
const scanLabel = document.getElementById('scanLabel');
const fileInput = document.getElementById('fileInput');
const captureCanvas = document.getElementById('captureCanvas');
let videoEl = null;
let stream = null;
let scanning = false;
let codeReader = null;
// Try to start camera on load (best-effort)
async function startCamera(){
// create video element if not exist
if (videoEl) return;
videoEl = document.createElement('video');
videoEl.setAttribute('playsinline','');
videoEl.style.width = '100%';
videoEl.style.height = '100%';
videoEl.autoplay = true;
videoEl.muted = true;
videoEl.controls = false;
// place video under inner border
cameraArea.appendChild(videoEl);
placeholder.style.display = 'none';
try {
if (!window.ZXing || !window.ZXing.BrowserMultiFormatReader) {
throw new Error('Scanner library not loaded');
}
codeReader = new window.ZXing.BrowserMultiFormatReader();
await codeReader.decodeFromVideoDevice(undefined, videoEl, (result, err) => {
if (result) {
onBarcode(result.getText());
}
});
} catch (err) {
// permissions denied or no camera -> show placeholder and file input option
console.warn('Camera unavailable:', err);
cameraArea.removeChild(videoEl);
videoEl = null;
placeholder.style.display = '';
}
}
// capture current frame and return blob (dataURL)
function captureFrame(){
return new Promise((resolve, reject) => {
if (!videoEl || videoEl.readyState < 2) {
return reject(new Error('Camera not ready'));
}
const w = videoEl.videoWidth;
const h = videoEl.videoHeight;
captureCanvas.width = w;
captureCanvas.height = h;
const ctx = captureCanvas.getContext('2d');
// draw center crop matching frame aspect ratio
const frameRect = frame.getBoundingClientRect();
const aspect = frameRect.width / frameRect.height;
let srcW = w, srcH = h, sx = 0, sy = 0;
if (w / h > aspect) {
// video wider -> crop horizontally
srcW = h * aspect;
sx = (w - srcW) / 2;
} else {
// crop vertically
srcH = w / aspect;
sy = (h - srcH) / 2;
}
ctx.drawImage(videoEl, sx, sy, srcW, srcH, 0, 0, w, h);
captureCanvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.85);
});
}
const API_URL = 'http://localhost:3000/api';
let _apiOk = null;
async function apiAvailable(){
if (_apiOk !== null) return _apiOk;
try{ const r = await fetch(`${API_URL}/health`, { cache: 'no-store' }); _apiOk = r.ok; }
catch(e){ _apiOk = false; }
return _apiOk;
}
async function onBarcode(code){
if (!code) return;
if (scanning) return;
scanning = true;
try {
const product = await resolveProductFromCode(code);
// try backend first (non-blocking error)
try{
if (await apiAvailable()){
await fetch(`${API_URL}/scans`, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ barcode: code, title: product.title }) });
}
}catch(e){}
persistScan(product);
alert('Scanned → ' + product.title + '\nBarcode/Code: ' + code);
} finally {
scanning = false;
}
}
function estimateCarbonKg(name){
// simple heuristic: assign lower carbon to fruits/plant-based keywords
const n = String(name || '').toLowerCase();
const low = /(apple|banana|lettuce|spinach|oat|almond|plant|vegan|bean|chickpea|pasta)/.test(n);
const base = low ? 0.3 : 1.2;
const jitter = Math.random()*0.6; // 0-0.6
return Number((base + jitter).toFixed(2));
}
async function resolveProductFromCode(code){
const digitsOnly = /^[0-9]{8,14}$/.test(String(code));
if (digitsOnly) {
try{
const res = await fetch(`https://world.openfoodfacts.org/api/v0/product/${code}.json`);
const data = await res.json();
if (data && data.status === 1 && data.product) {
const name = data.product.product_name || data.product.brands || ('Product ' + code);
const ecoGrade = (data.product.ecoscore_grade || '').toUpperCase();
// Try extract carbon from nutriments
const nutr = data.product.nutriments || {};
let carbonVal = null;
const keys = ['carbon-footprint_100g','carbon-footprint_100g_estimate','carbon-footprint-from-meat-or-fish_100g'];
for (const k of keys) {
if (typeof nutr[k] === 'number') { carbonVal = nutr[k] / 1000; break; }
}
if (carbonVal === null && typeof nutr['carbon-footprint_100g'] === 'string') {
const v = parseFloat(nutr['carbon-footprint_100g']);
if (!Number.isNaN(v)) carbonVal = v / 1000;
}
const carbonFinal = (carbonVal !== null) ? Number(carbonVal.toFixed(2)) : estimateCarbonKg(name);
const rawNutri = (data.product.nutriscore_grade || data.product.nutriscore_grade_producer || data.product.nutrition_grades || data.product.nutrition_grade_fr || '').toString().trim().toUpperCase();
const health = (/^[A-E]$/.test(rawNutri) ? rawNutri : (/vegan|plant|fruit|veg|bean|chickpea|oat|almond/i.test(name) ? 'A' : 'B'));
return {
title: name,
health,
eco: ecoGrade ? ('Eco ' + ecoGrade) : 'Eco ' + (['A','B','C','D'][Math.floor(Math.random()*4)]),
carbon: carbonFinal,
barcode: code,
time: 'Just now'
};
}
} catch(e){ /* fall through to fallback */ }
const name = 'Product ' + code;
return { title: name, health: ['A','B','C','D'][Math.floor(Math.random()*4)], eco: ['Eco A','Eco B','Eco C','Eco D'][Math.floor(Math.random()*4)], carbon: estimateCarbonKg(name), barcode: code, time: 'Just now' };
} else {
const name = String(code);
return { title: name, health: ['A','B','C','D'][Math.floor(Math.random()*4)], eco: ['Eco A','Eco B','Eco C','Eco D'][Math.floor(Math.random()*4)], carbon: estimateCarbonKg(name), barcode: String(code), time: 'Just now' };
}
}
function persistScan(item){
try{
const maxRecent = 10;
const recent = JSON.parse(localStorage.getItem('recentScans')||'[]');
recent.unshift(item);
while(recent.length>maxRecent) recent.pop();
localStorage.setItem('recentScans', JSON.stringify(recent));
const history = JSON.parse(localStorage.getItem('historyScans')||'[]');
history.unshift({
title: item.title,
time: new Date().toLocaleString(),
nutri: item.health,
eco: item.eco,
carbon: item.carbon,
points: 10
});
localStorage.setItem('historyScans', JSON.stringify(history));
}catch(e){ console.warn('Persist failed', e); }
}
// wire up events
scanBtn.addEventListener('click', async () => {
if (scanning) return;
scanning = true;
if (videoEl) {
alert('Align the barcode within the frame. It will scan automatically.');
} else {
fileInput.click();
}
scanning = false;
});
fileInput.addEventListener('change', async (e) => {
const f = e.target.files && e.target.files[0];
if (!f) return;
try{
if (!window.ZXing || !window.ZXing.BrowserMultiFormatReader) throw new Error('Scanner library not loaded');
const url = URL.createObjectURL(f);
const img = new Image();
img.onload = async () => {
try{
const reader = new window.ZXing.BrowserMultiFormatReader();
const result = await reader.decodeFromImage(img);
onBarcode(result.getText());
} catch(err){
alert('Could not decode barcode from image.');
} finally {
URL.revokeObjectURL(url);
}
};
img.onerror = () => { URL.revokeObjectURL(url); alert('Failed to load image.'); };
img.src = url;
} finally {
fileInput.value = '';
}
});
// close button - for demo just show a message
window.onClose = function(){
// in a real modal: close modal and return to previous screen
if (confirm('Close scanner?')) {
// stop camera if running
stopCamera();
alert('Scanner closed (demo).');
}
};
// attempt to start camera shortly after load for better UX
window.addEventListener('load', () => {
// best-effort camera start
startCamera();
});
// cleanup camera
function stopCamera(){
try{
if (codeReader) { codeReader.reset(); codeReader = null; }
}catch(e){}
if (stream) {
stream.getTracks().forEach(t => t.stop());
stream = null;
}
if (videoEl){
try { videoEl.pause(); videoEl.srcObject = null; } catch(e){}
if (videoEl.parentNode) videoEl.parentNode.removeChild(videoEl);
videoEl = null;
}
placeholder.style.display = '';
}
// try stopping camera when page hidden
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopCamera();
});
// expose debug start/stop (not needed but handy)
window._startCamera = startCamera;
window._stopCamera = stopCamera;
})();
</script>
</body>
</html>