-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.js
More file actions
1818 lines (1677 loc) · 76.5 KB
/
Copy pathscanner.js
File metadata and controls
1818 lines (1677 loc) · 76.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
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================
// Barcode Scanner Module for Absolute Universe Collection Tracker
// ============================================================
// Phase 4: Scan sounds & haptics, collection value, offline queue
// ============================================================
(function() {
'use strict';
// ── Helpers ──
function formatPrice(val) {
if (val === 0) return 'FREE';
return '$' + val.toFixed(2);
}
// ── State ──
var scanner = null; // Html5Qrcode instance
var isScanning = false;
var overlay = null; // DOM overlay element
var lastScannedCode = ''; // Debounce duplicate scans
var lastScanTime = 0;
var batchMode = false; // Rapid batch scanning
var cartMode = false; // Shopping cart mode — scans add to cart, not owned
var cart = []; // Cart items: { key, title, slug, type, variant, variantName, price, alreadyOwned }
var CART_KEY = 'au_scanner_cart';
var scanHistory = []; // Session scan log
var sessionValue = 0; // Running $ value scanned this session
// ── Audio Context (scan beep) ──
var audioCtx = null;
function getAudioCtx() {
if (!audioCtx) {
try { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) {}
}
return audioCtx;
}
function playBeep(type) {
// type: 'success' | 'error' | 'batch'
var ctx = getAudioCtx();
if (!ctx) return;
try {
var osc = ctx.createOscillator();
var gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
if (type === 'success' || type === 'batch') {
// Pleasant two-tone rising beep
osc.type = 'sine';
osc.frequency.setValueAtTime(880, ctx.currentTime); // A5
osc.frequency.setValueAtTime(1174.66, ctx.currentTime + 0.08); // D6
gain.gain.setValueAtTime(0.15, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.18);
osc.start(ctx.currentTime);
osc.stop(ctx.currentTime + 0.18);
} else if (type === 'error') {
// Low buzz for not-found
osc.type = 'triangle';
osc.frequency.setValueAtTime(220, ctx.currentTime);
osc.frequency.setValueAtTime(165, ctx.currentTime + 0.1);
gain.gain.setValueAtTime(0.12, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.2);
osc.start(ctx.currentTime);
osc.stop(ctx.currentTime + 0.2);
}
} catch(e) {}
}
function vibrate(pattern) {
if (navigator.vibrate) {
try { navigator.vibrate(pattern); } catch(e) {}
}
}
// ── Barcode Index ──
var barcodeIndex = {};
var variantData = null; // loaded from variants.json
var coverFingerprints = null; // loaded from cover-fingerprints.json
var FINGERPRINT_GRID = 8; // 8x8 grid = 64 pixels = 192 RGB values
var seriesIndex = {}; // maps 12-digit UPC-A base to array of entries
function buildBarcodeIndex() {
barcodeIndex = {};
seriesIndex = {};
// Index individual issues
if (typeof ALL_ISSUES !== 'undefined') {
ALL_ISSUES.forEach(function(issue) {
if (!issue.barcodes) return;
var slug = issue.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
var key = issue.series + '|' + issue.issue;
var entry = { slug: slug, title: issue.title, key: key, variant: null, variantName: 'Cover A', type: 'issue', price: issue.price || 4.99 };
if (issue.barcodes.upc) {
barcodeIndex[issue.barcodes.upc] = entry;
// DC UPCs are 17 digits (12-digit UPC-A + 5-digit add-on).
// Cameras usually only read the 12-digit part, so build a series index.
if (issue.barcodes.upc.length >= 12) {
var upc12 = issue.barcodes.upc.substring(0, 12);
if (!seriesIndex[upc12]) seriesIndex[upc12] = [];
seriesIndex[upc12].push(entry);
// Also index EAN-13 form (leading 0 + 12-digit UPC-A)
var ean13 = '0' + upc12;
if (!seriesIndex[ean13]) seriesIndex[ean13] = [];
seriesIndex[ean13].push(entry);
}
}
if (issue.barcodes.isbn) {
barcodeIndex[issue.barcodes.isbn] = entry;
}
if (issue.barcodes.variants) {
Object.keys(issue.barcodes.variants).forEach(function(varId) {
barcodeIndex[issue.barcodes.variants[varId]] = { slug: slug, title: issue.title, key: key, variant: varId, variantName: 'Variant ' + varId, type: 'issue', price: issue.price || 4.99 };
});
}
});
}
// Index variant covers from variants.json
if (variantData) {
Object.keys(variantData).forEach(function(slug) {
var variants = variantData[slug];
// Find matching issue for this slug
var matchedIssue = null;
if (typeof ALL_ISSUES !== 'undefined') {
for (var i = 0; i < ALL_ISSUES.length; i++) {
var issueSlug = ALL_ISSUES[i].title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
if (issueSlug === slug) { matchedIssue = ALL_ISSUES[i]; break; }
}
}
if (!matchedIssue) return;
var key = matchedIssue.series + '|' + matchedIssue.issue;
variants.forEach(function(v, idx) {
if (!v.upc) return;
var coverName = v.cover || v.name || ('Variant #' + (idx + 1));
var entry = {
slug: slug,
title: matchedIssue.title,
key: key,
variant: String(idx),
variantName: coverName,
variantFullName: v.name || coverName,
type: 'issue',
price: matchedIssue.price || 4.99
};
barcodeIndex[v.upc] = entry;
// Also index the 12-digit prefix for camera scans
if (v.upc.length >= 12) {
var upc12 = v.upc.substring(0, 12);
// Don't overwrite the base issue's 12-digit entry
// Only add the full 17-digit variant UPC
}
});
});
}
// Index trade paperbacks
if (typeof TRADES !== 'undefined') {
TRADES.forEach(function(trade) {
if (!trade.isbn) return;
var slug = trade.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
var key = trade.title;
var entry = { slug: slug, title: trade.title, key: key, variant: null, type: 'trade', subtitle: trade.subtitle || '', price: trade.price || 16.99 };
barcodeIndex[trade.isbn] = entry;
var clean = trade.isbn.replace(/[-\s]/g, '');
if (clean !== trade.isbn) barcodeIndex[clean] = entry;
if (clean.length === 13 && clean.indexOf('978') === 0) {
barcodeIndex[clean.substring(3, 12)] = entry;
}
});
}
}
// ── Lookup ──
// DC comics have a 12-digit UPC-A main barcode + a 5-digit add-on (issue/print).
// Cameras typically only read the 12-digit UPC-A portion, but our index stores the
// full 17-digit composite (e.g. "76194138632100111"). So we need prefix matching.
// When a 12-digit scan matches multiple issues in a series, returns a multi-match
// object so the UI can show a picker.
function lookupBarcode(code) {
code = code.trim().replace(/[-\s]/g, '');
// 1. Exact match (full 17-digit UPC, ISBN, etc.)
if (barcodeIndex[code]) return barcodeIndex[code];
// 2. Strip leading zeros
var stripped = code.replace(/^0+/, '');
if (barcodeIndex[stripped]) return barcodeIndex[stripped];
// 3. Series index match — camera scanned 12 or 13 digit code
if (code.length >= 10 && code.length <= 14) {
// Check series index for multi-match
if (seriesIndex[code] && seriesIndex[code].length === 1) {
return seriesIndex[code][0];
}
if (seriesIndex[code] && seriesIndex[code].length > 1) {
return { multiMatch: true, matches: seriesIndex[code], code: code };
}
if (seriesIndex[stripped] && seriesIndex[stripped].length === 1) {
return seriesIndex[stripped][0];
}
if (seriesIndex[stripped] && seriesIndex[stripped].length > 1) {
return { multiMatch: true, matches: seriesIndex[stripped], code: stripped };
}
// Fallback: prefix match against full barcodeIndex keys
var keys = Object.keys(barcodeIndex);
for (var i = 0; i < keys.length; i++) {
if (keys[i].indexOf(code) === 0) return barcodeIndex[keys[i]];
if (keys[i].indexOf(stripped) === 0) return barcodeIndex[keys[i]];
}
}
// 4. Long code — try matching first 15 or 12 chars
if (code.length >= 15) {
var prefix15 = code.substring(0, 15);
var keys2 = Object.keys(barcodeIndex);
for (var j = 0; j < keys2.length; j++) {
if (keys2[j].length >= 15 && keys2[j].substring(0, 15) === prefix15) return barcodeIndex[keys2[j]];
}
}
if (code.length >= 11) {
var prefix = code.substring(0, 11);
if (barcodeIndex[prefix]) return barcodeIndex[prefix];
}
return null;
}
// ── Owned State Helpers ──
function getOwnedState() {
try { return JSON.parse(localStorage.getItem('au_owned') || '{}'); } catch(e) { return {}; }
}
function getOwnedTrades() {
try { return JSON.parse(localStorage.getItem('au_trades') || '{}'); } catch(e) { return {}; }
}
function setOwnedState(key, val, type) {
var storageKey = (type === 'trade') ? 'au_trades' : 'au_owned';
var state;
try { state = JSON.parse(localStorage.getItem(storageKey) || '{}'); } catch(e) { state = {}; }
if (val) { state[key] = true; } else { delete state[key]; }
localStorage.setItem(storageKey, JSON.stringify(state));
if (type !== 'trade' && typeof syncOwnedToCloud === 'function') {
try { syncOwnedToCloud(); } catch(e) {}
}
if (type !== 'trade' && typeof owned !== 'undefined' && typeof saveOwned === 'function') {
if (val) { owned[key] = true; } else { delete owned[key]; }
saveOwned();
}
if (type === 'trade' && typeof ownedTrades !== 'undefined' && typeof saveTrades === 'function') {
if (val) { ownedTrades[key] = true; } else { delete ownedTrades[key]; }
saveTrades();
}
}
function isOwned(key, type) {
var state = (type === 'trade') ? getOwnedTrades() : getOwnedState();
return !!state[key];
}
// ── Offline Scan Queue ──
var OFFLINE_QUEUE_KEY = 'au_scan_offline_queue';
function getOfflineQueue() {
try { return JSON.parse(localStorage.getItem(OFFLINE_QUEUE_KEY) || '[]'); } catch(e) { return []; }
}
function saveOfflineQueue(queue) {
localStorage.setItem(OFFLINE_QUEUE_KEY, JSON.stringify(queue));
updateOfflineBadge();
}
function queueOfflineScan(key, type) {
var queue = getOfflineQueue();
// Avoid duplicates
for (var i = 0; i < queue.length; i++) {
if (queue[i].key === key && queue[i].type === type) return;
}
queue.push({ key: key, type: type, time: Date.now() });
saveOfflineQueue(queue);
}
function syncOfflineQueue() {
var queue = getOfflineQueue();
if (queue.length === 0) return;
var synced = 0;
queue.forEach(function(item) {
try {
setOwnedState(item.key, true, item.type);
synced++;
} catch(e) {}
});
saveOfflineQueue([]);
if (synced > 0 && overlay && overlay.classList.contains('open')) {
showToast('<span style="color:#22c55e;">☁</span> Synced ' + synced + ' offline scan' + (synced > 1 ? 's' : ''), 3000);
}
}
function isOnline() {
return navigator.onLine !== false;
}
function updateOfflineBadge() {
var badge = document.getElementById('scannerOfflineBadge');
var queue = getOfflineQueue();
if (badge) {
if (queue.length > 0) {
badge.textContent = queue.length;
badge.style.display = 'flex';
} else {
badge.style.display = 'none';
}
}
}
// Listen for online events to auto-sync
window.addEventListener('online', function() {
syncOfflineQueue();
});
// ── Shopping Cart ──
function loadCart() {
try { cart = JSON.parse(localStorage.getItem(CART_KEY) || '[]'); } catch(e) { cart = []; }
}
function saveCart() {
localStorage.setItem(CART_KEY, JSON.stringify(cart));
updateCartBadge();
}
function addToCart(result) {
// Check for duplicates in cart
var isDupe = false;
for (var i = 0; i < cart.length; i++) {
if (cart[i].key === result.key && cart[i].variant === (result.variant || null)) {
isDupe = true;
break;
}
}
if (isDupe) return 'duplicate';
var isVariant = !!(result.variantName && result.variantName !== 'Cover A');
var alreadyOwned = false;
if (isVariant && typeof isVariantOwned === 'function') {
alreadyOwned = isVariantOwned(result.key, result.variant);
} else {
alreadyOwned = isOwned(result.key, result.type);
}
cart.push({
key: result.key,
title: result.title,
slug: result.slug,
type: result.type || 'issue',
variant: result.variant || null,
variantName: isVariant ? result.variantName : null,
variantFullName: result.variantFullName || null,
price: result.price || 4.99,
alreadyOwned: alreadyOwned
});
saveCart();
return alreadyOwned ? 'owned' : 'added';
}
function removeFromCart(index) {
cart.splice(index, 1);
saveCart();
}
function clearCart() {
cart = [];
saveCart();
}
function getCartTotal() {
var total = 0;
for (var i = 0; i < cart.length; i++) {
total += cart[i].price || 0;
}
return total;
}
function checkoutCart() {
var count = 0;
for (var i = 0; i < cart.length; i++) {
var item = cart[i];
if (item.variant && item.variant !== null && typeof toggleVariantOwned === 'function') {
if (typeof isVariantOwned === 'function' && !isVariantOwned(item.key, item.variant)) {
toggleVariantOwned(item.key, item.variant);
}
// Also mark base issue as owned
if (!isOwned(item.key, 'issue')) {
setOwnedState(item.key, true, 'issue');
}
} else {
if (!isOwned(item.key, item.type)) {
if (isOnline()) {
setOwnedState(item.key, true, item.type);
} else {
var sk = (item.type === 'trade') ? 'au_trades' : 'au_owned';
var st;
try { st = JSON.parse(localStorage.getItem(sk) || '{}'); } catch(e) { st = {}; }
st[item.key] = true;
localStorage.setItem(sk, JSON.stringify(st));
queueOfflineScan(item.key, item.type);
}
}
}
count++;
}
clearCart();
return count;
}
function updateCartBadge() {
var badge = document.getElementById('scannerCartBadge');
if (badge) {
if (cart.length > 0) {
badge.textContent = cart.length;
badge.style.display = 'flex';
} else {
badge.style.display = 'none';
}
}
}
function toggleCartMode() {
if (batchMode) {
// Turn off batch mode first
batchMode = false;
var batchBtn = document.getElementById('scannerBatchBtn');
batchBtn.style.color = '#aaa';
batchBtn.style.background = 'rgba(255,255,255,0.06)';
batchBtn.style.borderColor = 'rgba(255,255,255,0.12)';
batchBtn.title = 'Batch mode: auto-add on scan';
}
cartMode = !cartMode;
var btn = document.getElementById('scannerCartBtn');
btn.style.color = cartMode ? '#06b6d4' : '#aaa';
btn.style.background = cartMode ? 'rgba(6,182,212,0.15)' : 'rgba(255,255,255,0.06)';
btn.style.borderColor = cartMode ? 'rgba(6,182,212,0.3)' : 'rgba(255,255,255,0.12)';
btn.title = cartMode ? 'Cart mode ON: scans add to cart' : 'Cart mode: scan to cart';
var hint = document.getElementById('scannerHint');
if (cartMode) {
hint.textContent = 'Cart mode — scan to add to cart';
document.getElementById('scannerResult').style.display = 'none';
lastScannedCode = '';
resumeScanning();
renderCartTray();
} else {
hint.textContent = 'Point your camera at a barcode';
hideCartTray();
}
}
function renderCartTray() {
var tray = document.getElementById('scannerCartTray');
if (!tray) return;
if (!cartMode && cart.length === 0) {
tray.style.display = 'none';
return;
}
if (cart.length === 0) {
tray.style.display = 'flex';
tray.innerHTML = '<div class="cart-tray-header">'
+ '<span class="cart-tray-title">🛒 Cart empty</span>'
+ '</div>'
+ '<div class="cart-tray-hint">Scan comics to add them to your cart</div>';
return;
}
var total = getCartTotal();
var ownedCount = 0;
for (var i = 0; i < cart.length; i++) {
if (cart[i].alreadyOwned) ownedCount++;
}
var html = '<div class="cart-tray-header">'
+ '<span class="cart-tray-title">🛒 Cart: ' + cart.length + ' issue' + (cart.length !== 1 ? 's' : '') + ' · $' + total.toFixed(2) + '</span>'
+ '<button class="cart-checkout-btn" id="cartCheckoutBtn">Checkout</button>'
+ '</div>';
if (ownedCount > 0) {
html += '<div class="cart-tray-warning">⚠️ ' + ownedCount + ' item' + (ownedCount !== 1 ? 's' : '') + ' already owned</div>';
}
html += '<div class="cart-tray-list">';
for (var j = 0; j < cart.length; j++) {
var item = cart[j];
var variantTag = item.variantName ? ' <span class="cart-variant-tag">' + item.variantName + '</span>' : '';
var ownedTag = item.alreadyOwned ? '<span class="cart-owned-tag">⚠️ owned</span>' : '';
html += '<div class="cart-tray-item' + (item.alreadyOwned ? ' already-owned' : '') + '" data-idx="' + j + '">'
+ '<div class="cart-item-info">'
+ '<span class="cart-item-title">' + item.title + variantTag + '</span>'
+ '<span class="cart-item-price">' + formatPrice(item.price) + ' ' + ownedTag + '</span>'
+ '</div>'
+ '<button class="cart-item-remove" data-idx="' + j + '">✕</button>'
+ '</div>';
}
html += '</div>';
html += '<div class="cart-tray-footer">'
+ '<button class="cart-clear-btn" id="cartClearBtn">Clear Cart</button>'
+ '</div>';
tray.style.display = 'flex';
tray.innerHTML = html;
// Bind events
var checkoutBtn = document.getElementById('cartCheckoutBtn');
if (checkoutBtn) {
checkoutBtn.onclick = function() {
var count = checkoutCart();
playBeep('success');
vibrate([50, 30, 50, 30, 50]);
showToast('<span style="color:#22c55e;">✓</span> Checked out <strong>' + count + ' item' + (count !== 1 ? 's' : '') + '</strong> — marked as owned!', 3000);
renderCartTray();
updateCartBadge();
// Refresh main UI if possible
if (typeof renderAll === 'function') try { renderAll(); } catch(e) {}
};
}
var clearBtn = document.getElementById('cartClearBtn');
if (clearBtn) {
clearBtn.onclick = function() {
clearCart();
renderCartTray();
showToast('🛒 Cart cleared', 2000);
};
}
var removeBtns = tray.querySelectorAll('.cart-item-remove');
for (var k = 0; k < removeBtns.length; k++) {
removeBtns[k].onclick = function() {
var idx = parseInt(this.getAttribute('data-idx'));
removeFromCart(idx);
renderCartTray();
playBeep('error');
};
}
}
function hideCartTray() {
var tray = document.getElementById('scannerCartTray');
if (tray && cart.length === 0) {
tray.style.display = 'none';
}
}
// ── Cover Fingerprint Matching ──
// Computes an 8x8 RGB color fingerprint from a video element's current frame.
// Returns an array of 192 numbers (64 pixels × 3 RGB channels).
function computeFingerprint(videoEl) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var vw = videoEl.videoWidth;
var vh = videoEl.videoHeight;
if (!vw || !vh) return null;
// Center-crop to square (same as Python generator)
var dim = Math.min(vw, vh);
var sx = Math.floor((vw - dim) / 2);
var sy = Math.floor((vh - dim) / 2);
canvas.width = FINGERPRINT_GRID;
canvas.height = FINGERPRINT_GRID;
ctx.drawImage(videoEl, sx, sy, dim, dim, 0, 0, FINGERPRINT_GRID, FINGERPRINT_GRID);
var imageData = ctx.getImageData(0, 0, FINGERPRINT_GRID, FINGERPRINT_GRID);
var pixels = imageData.data; // RGBA flat array
var fp = [];
for (var i = 0; i < pixels.length; i += 4) {
fp.push(pixels[i], pixels[i + 1], pixels[i + 2]); // skip alpha
}
return fp;
}
// Euclidean distance between two fingerprint arrays
function fingerprintDistance(a, b) {
if (!a || !b || a.length !== b.length) return Infinity;
var sum = 0;
for (var i = 0; i < a.length; i++) {
var d = a[i] - b[i];
sum += d * d;
}
return Math.sqrt(sum);
}
// Match a captured fingerprint against all covers for a set of issue slugs.
// Returns sorted array of { slug, coverKey, distance, match } objects.
function matchCoverFingerprint(capturedFP, matches) {
if (!coverFingerprints || !capturedFP) return [];
var results = [];
for (var i = 0; i < matches.length; i++) {
var slug = matches[i].slug;
var fps = coverFingerprints[slug];
if (!fps) continue;
var keys = Object.keys(fps);
for (var j = 0; j < keys.length; j++) {
var coverKey = keys[j]; // 'a' for Cover A, 'v0', 'v1' etc for variants
var dist = fingerprintDistance(capturedFP, fps[coverKey]);
results.push({
slug: slug,
coverKey: coverKey,
distance: dist,
match: matches[i]
});
}
}
results.sort(function(a, b) { return a.distance - b.distance; });
return results;
}
// Build a result entry from a fingerprint match result
function buildResultFromMatch(fpMatch) {
var issueMatch = fpMatch.match;
var coverKey = fpMatch.coverKey;
// Cover A (standard)
if (coverKey === 'a') {
return issueMatch;
}
// Variant cover — coverKey is 'v0', 'v1', etc.
var variantIdx = parseInt(coverKey.substring(1));
var variants = variantData ? variantData[issueMatch.slug] : null;
if (variants && variants[variantIdx]) {
var v = variants[variantIdx];
var coverName = v.cover || v.name || ('Variant #' + (variantIdx + 1));
return {
slug: issueMatch.slug,
title: issueMatch.title,
key: issueMatch.key,
variant: String(variantIdx),
variantName: coverName,
variantFullName: v.name || coverName,
type: 'issue',
price: issueMatch.price || 4.99
};
}
// Fallback to base issue
return issueMatch;
}
// ── Cover Photo Capture UI ──
// Shows a "Point camera at cover" overlay with capture button.
// After capture, compares fingerprint and shows best match.
function showCoverCaptureUI(matches, code) {
// Pause barcode scanning but keep the video feed alive
if (scanner && isScanning) {
try { scanner.pause(true); } catch(e) {}
}
playBeep('success');
vibrate([50, 30, 50]);
var resultEl = document.getElementById('scannerResult');
var titleEl = document.getElementById('scannerResultTitle');
var codeEl = document.getElementById('scannerResultCode');
var viewBtn = document.getElementById('scannerViewBtn');
var ownedBtn = document.getElementById('scannerOwnedBtn');
var priceEl = document.getElementById('scannerResultPrice');
// Get the series name from the first match
var seriesName = matches[0].title.replace(/#\d+.*$/, '').trim();
titleEl.innerHTML = '<span style="color:var(--accent-gold,#eab308);">📸</span> ' + seriesName + ' detected';
codeEl.textContent = matches.length + ' issues in series — show the cover to identify';
priceEl.style.display = 'none';
viewBtn.style.display = 'none';
ownedBtn.style.display = 'none';
// Remove any old picker
var oldPicker = document.getElementById('scannerMultiPicker');
if (oldPicker) oldPicker.remove();
var container = document.createElement('div');
container.id = 'scannerMultiPicker';
container.style.cssText = 'margin-top:8px;display:flex;flex-direction:column;gap:8px;align-items:center;';
// Instruction text
var hint = document.createElement('div');
hint.style.cssText = 'font-size:0.82rem;color:rgba(255,255,255,0.6);text-align:center;padding:4px 0;';
hint.textContent = 'Point camera at the full cover, then tap Capture';
container.appendChild(hint);
// Capture button
var captureBtn = document.createElement('button');
captureBtn.className = 'scanner-result-btn primary';
captureBtn.style.cssText = 'width:100%;padding:12px 16px;font-size:0.95rem;';
captureBtn.innerHTML = '📷 Capture Cover';
captureBtn.onclick = function() {
// Get the video element from the scanner
var videoEl = document.querySelector('#scannerReader video');
if (!videoEl) {
hint.textContent = 'Camera not available — use manual picker below';
hint.style.color = '#eab308';
return;
}
// Resume briefly to get a live frame, then capture
try { scanner.resume(); } catch(e) {}
setTimeout(function() {
var fp = computeFingerprint(videoEl);
try { scanner.pause(true); } catch(e) {}
if (!fp) {
hint.textContent = 'Could not capture frame — try again';
hint.style.color = '#eab308';
return;
}
var results = matchCoverFingerprint(fp, matches);
if (results.length === 0) {
hint.textContent = 'No fingerprint data for this series — use manual picker';
hint.style.color = '#eab308';
return;
}
// Show the best match with confidence
var best = results[0];
var second = results.length > 1 ? results[1] : null;
var confidence = second ? (1 - best.distance / (best.distance + second.distance)) : 0.5;
// Normalize distance to a rough confidence percentage
var maxReasonableDistance = 3000;
var distConfidence = Math.max(0, 1 - best.distance / maxReasonableDistance);
var displayConfidence = Math.round(Math.max(confidence, distConfidence) * 100);
showCoverMatchResult(best, displayConfidence, matches, code);
}, 200); // Small delay to ensure frame is fresh after resume
};
container.appendChild(captureBtn);
// "Or pick manually" fallback link
var manualLink = document.createElement('button');
manualLink.className = 'scanner-result-btn secondary';
manualLink.style.cssText = 'width:100%;padding:10px 16px;font-size:0.82rem;';
manualLink.textContent = 'Pick manually instead';
manualLink.onclick = function() {
container.remove();
showMultiMatchPicker(matches, code);
};
container.appendChild(manualLink);
var inner = resultEl.querySelector('.scanner-result-inner');
if (inner) inner.appendChild(container);
resultEl.style.display = 'flex';
document.getElementById('scannerHint').textContent = 'Show the cover to the camera';
}
// Show the fingerprint match result with confirm/reject options
function showCoverMatchResult(fpMatch, confidence, allMatches, code) {
var resultEl = document.getElementById('scannerResult');
var titleEl = document.getElementById('scannerResultTitle');
var codeEl = document.getElementById('scannerResultCode');
var viewBtn = document.getElementById('scannerViewBtn');
var ownedBtn = document.getElementById('scannerOwnedBtn');
var priceEl = document.getElementById('scannerResultPrice');
var entry = buildResultFromMatch(fpMatch);
var isVariant = fpMatch.coverKey !== 'a';
var coverLabel = isVariant ? (entry.variantName || fpMatch.coverKey) : 'Cover A';
// Remove old picker
var oldPicker = document.getElementById('scannerMultiPicker');
if (oldPicker) oldPicker.remove();
var confColor = confidence >= 70 ? '#22c55e' : confidence >= 40 ? '#eab308' : '#ef4444';
titleEl.innerHTML = '<span style="color:' + confColor + ';">' + (confidence >= 70 ? '✓' : '?') + '</span> '
+ entry.title
+ (isVariant ? ' <span style="color:var(--accent-gold,#eab308);font-size:0.8em;">' + coverLabel + '</span>' : '');
codeEl.textContent = 'Confidence: ' + confidence + '% — Is this correct?';
priceEl.style.display = 'none';
viewBtn.style.display = 'none';
ownedBtn.style.display = 'none';
var container = document.createElement('div');
container.id = 'scannerMultiPicker';
container.style.cssText = 'margin-top:8px;display:flex;flex-direction:column;gap:6px;';
// Yes button
var yesBtn = document.createElement('button');
yesBtn.className = 'scanner-result-btn primary';
yesBtn.style.cssText = 'width:100%;padding:10px 16px;';
yesBtn.innerHTML = '✓ Yes, that\'s it';
yesBtn.onclick = function() {
container.remove();
barcodeIndex[code] = entry;
handleScanResult(code);
};
container.appendChild(yesBtn);
// Retry capture button
var retryBtn = document.createElement('button');
retryBtn.className = 'scanner-result-btn secondary';
retryBtn.style.cssText = 'width:100%;padding:10px 16px;';
retryBtn.innerHTML = '📷 Try again';
retryBtn.onclick = function() {
container.remove();
showCoverCaptureUI(allMatches, code);
};
container.appendChild(retryBtn);
// No — pick manually button
var noBtn = document.createElement('button');
noBtn.className = 'scanner-result-btn secondary';
noBtn.style.cssText = 'width:100%;padding:10px 16px;font-size:0.82rem;';
noBtn.textContent = 'No — pick manually';
noBtn.onclick = function() {
container.remove();
showMultiMatchPicker(allMatches, code);
};
container.appendChild(noBtn);
var inner = resultEl.querySelector('.scanner-result-inner');
if (inner) inner.appendChild(container);
resultEl.style.display = 'flex';
document.getElementById('scannerHint').textContent = confidence >= 70 ? 'High confidence match!' : 'Low confidence — verify or try again';
}
// ── Create Scanner Button ──
function createScannerButton() {
var btn = document.createElement('button');
btn.id = 'scannerBtn';
btn.setAttribute('aria-label', 'Scan barcode');
btn.setAttribute('title', 'Scan Barcode');
btn.style.cssText = 'position:fixed;top:1rem;right:10rem;z-index:998;width:38px;height:38px;border-radius:50%;border:1px solid rgba(255,255,255,0.12);background:rgba(255,255,255,0.08);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s;color:#aaa;';
btn.innerHTML = '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7V5a2 2 0 0 1 2-2h2"/><path d="M17 3h2a2 2 0 0 1 2 2v2"/><path d="M21 17v2a2 2 0 0 1-2 2h-2"/><path d="M7 21H5a2 2 0 0 1-2-2v-2"/><line x1="7" y1="12" x2="17" y2="12"/><line x1="7" y1="8" x2="13" y2="8"/><line x1="7" y1="16" x2="11" y2="16"/></svg>';
btn.onmouseenter = function() { btn.style.background = 'rgba(255,255,255,0.14)'; btn.style.color = '#fff'; };
btn.onmouseleave = function() { btn.style.background = 'rgba(255,255,255,0.08)'; btn.style.color = '#aaa'; };
btn.onclick = openScanner;
document.body.appendChild(btn);
// On mobile (<=768px), hide the fixed button — scanner is accessible via bottom nav
var style = document.createElement('style');
style.textContent = '@media(max-width:768px){#scannerBtn{display:none!important;}}';
document.head.appendChild(style);
}
// ── Scanner Overlay ──
function createOverlay() {
if (overlay) return;
overlay = document.createElement('div');
overlay.id = 'scannerOverlay';
overlay.innerHTML = ''
+ '<div class="scanner-header">'
+ '<button class="scanner-close-btn" id="scannerCloseBtn" aria-label="Close scanner">'
+ '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
+ '</button>'
+ '<span class="scanner-title">Scan Barcode</span>'
+ '<button class="scanner-batch-btn" id="scannerBatchBtn" aria-label="Toggle batch mode" title="Batch mode: auto-add on scan">'
+ '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>'
+ '</button>'
+ '<button class="scanner-cart-btn" id="scannerCartBtn" aria-label="Toggle cart mode" title="Cart mode: scan to cart" style="position:relative;">'
+ '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>'
+ '<span class="cart-badge" id="scannerCartBadge" style="display:none;">0</span>'
+ '</button>'
+ '<button class="scanner-torch-btn" id="scannerTorchBtn" aria-label="Toggle flashlight" title="Toggle flashlight" style="display:none;">'
+ '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>'
+ '</button>'
+ '</div>'
+ '<div class="scanner-body">'
+ '<div id="scannerReader"></div>'
+ '<div class="scanner-hint" id="scannerHint">Point your camera at a barcode</div>'
+ '<div class="scanner-toast" id="scannerToast"></div>'
+ '<div class="scanner-session-value" id="scannerSessionValue" style="display:none;"></div>'
+ '</div>'
+ '<div class="scanner-history" id="scannerHistory" style="display:none;">'
+ '<div class="scanner-history-header">'
+ '<span id="scannerHistoryTitle">Scan History</span>'
+ '<button class="scanner-history-clear" id="scannerHistoryClear">Clear</button>'
+ '</div>'
+ '<div class="scanner-history-list" id="scannerHistoryList"></div>'
+ '</div>'
+ '<div class="scanner-offline-bar" id="scannerOfflineBar" style="display:none;">'
+ '<span class="offline-icon">⚡</span>'
+ '<span>Offline — scans will sync when reconnected</span>'
+ '<span class="offline-badge" id="scannerOfflineBadge" style="display:none;">0</span>'
+ '</div>'
+ '<div class="scanner-cart-tray" id="scannerCartTray" style="display:none;"></div>'
+ '<div class="scanner-footer">'
+ '<div class="scanner-manual">'
+ '<input type="text" id="manualBarcodeInput" class="scanner-manual-input" placeholder="Or enter UPC / ISBN manually..." maxlength="20">'
+ '<button class="scanner-manual-btn" id="manualLookupBtn">Look Up</button>'
+ '</div>'
+ '</div>'
+ '<div class="scanner-result" id="scannerResult" style="display:none;">'
+ '<div class="scanner-result-inner">'
+ '<div class="scanner-result-title" id="scannerResultTitle"></div>'
+ '<div class="scanner-result-price" id="scannerResultPrice"></div>'
+ '<div class="scanner-result-code" id="scannerResultCode"></div>'
+ '<div class="scanner-result-actions">'
+ '<a class="scanner-result-btn primary" id="scannerViewBtn">View Issue</a>'
+ '<button class="scanner-result-btn secondary" id="scannerRescanBtn">Scan Another</button>'
+ '</div>'
+ '<button class="scanner-result-btn owned-btn" id="scannerOwnedBtn" style="display:none;margin-top:8px;width:100%;">Mark as Owned</button>'
+ '</div>'
+ '</div>';
document.body.appendChild(overlay);
// Event listeners
document.getElementById('scannerCloseBtn').addEventListener('click', closeScanner);
document.getElementById('scannerBatchBtn').addEventListener('click', toggleBatchMode);
document.getElementById('scannerCartBtn').addEventListener('click', toggleCartMode);
document.getElementById('scannerHistoryClear').addEventListener('click', clearHistory);
document.getElementById('scannerRescanBtn').addEventListener('click', function() {
document.getElementById('scannerResult').style.display = 'none';
document.getElementById('scannerHint').textContent = batchMode ? 'Batch mode — scanning...' : 'Point your camera at a barcode';
lastScannedCode = '';
resumeScanning();
});
document.getElementById('manualLookupBtn').addEventListener('click', function() {
var code = document.getElementById('manualBarcodeInput').value.trim();
if (code) handleScanResult(code);
});
document.getElementById('manualBarcodeInput').addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
var code = this.value.trim();
if (code) handleScanResult(code);
}
});
overlay._escHandler = function(e) {
if (e.key === 'Escape') closeScanner();
};
}
// ── Batch Mode ──
function toggleBatchMode() {
if (cartMode) {
// Turn off cart mode first
cartMode = false;
var cartBtn = document.getElementById('scannerCartBtn');
cartBtn.style.color = '#aaa';
cartBtn.style.background = 'rgba(255,255,255,0.06)';
cartBtn.style.borderColor = 'rgba(255,255,255,0.12)';
cartBtn.title = 'Cart mode: scan to cart';
hideCartTray();
}
batchMode = !batchMode;
var btn = document.getElementById('scannerBatchBtn');
btn.style.color = batchMode ? '#ffc107' : '#aaa';
btn.style.background = batchMode ? 'rgba(255,193,7,0.15)' : 'rgba(255,255,255,0.06)';
btn.style.borderColor = batchMode ? 'rgba(255,193,7,0.3)' : 'rgba(255,255,255,0.12)';
btn.title = batchMode ? 'Batch mode ON: auto-adds to collection' : 'Batch mode: auto-add on scan';
var hint = document.getElementById('scannerHint');
if (batchMode) {
hint.textContent = 'Batch mode — scanning...';
document.getElementById('scannerResult').style.display = 'none';
lastScannedCode = '';
resumeScanning();
} else {
hint.textContent = 'Point your camera at a barcode';
}
}
// ── Toast (for batch mode) ──
var toastTimer = null;
function showToast(html, duration) {
var el = document.getElementById('scannerToast');
el.innerHTML = html;
el.classList.add('show');
if (toastTimer) clearTimeout(toastTimer);
toastTimer = setTimeout(function() {
el.classList.remove('show');
}, duration || 2000);
}
// ── Session Value Display ──
function updateSessionValue() {
var el = document.getElementById('scannerSessionValue');
if (!el) return;
if (sessionValue > 0) {
el.innerHTML = '<span class="sv-label">Session total</span><span class="sv-amount">$' + sessionValue.toFixed(2) + '</span>';
el.style.display = 'flex';
} else {
el.style.display = 'none';
}
}
// ── Scan History ──
function addToHistory(code, result) {
var entry = {
code: code,
title: result ? result.title : 'Unknown',
type: result ? result.type : 'unknown',
key: result ? result.key : null,
slug: result ? result.slug : null,
found: !!result,
owned: result ? isOwned(result.key, result.type) : false,
price: result ? (result.price || 0) : 0,
time: new Date()
};
scanHistory.unshift(entry);
if (scanHistory.length > 50) scanHistory.pop();
renderHistory();
}
function renderHistory() {
var container = document.getElementById('scannerHistory');