Add barcode-detector-api-polyfill dependency and update environment variable declarations in SvelteKit project
This commit is contained in:
@@ -50,17 +50,30 @@
|
||||
skuValue = defaultSku;
|
||||
});
|
||||
|
||||
const hasBarcodeDetector = $derived(typeof globalThis !== "undefined" && "BarcodeDetector" in globalThis);
|
||||
async function ensureBarcodeDetector(): Promise<boolean> {
|
||||
if (typeof globalThis === "undefined" || "BarcodeDetector" in globalThis) return true;
|
||||
try {
|
||||
const mod = await import("barcode-detector-api-polyfill");
|
||||
(globalThis as unknown as { BarcodeDetector: typeof BarcodeDetector }).BarcodeDetector =
|
||||
mod.BarcodeDetector;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function startScan() {
|
||||
scanError = null;
|
||||
if (!hasBarcodeDetector) {
|
||||
scanError = "Barcode scan is not supported in this browser. Try Chrome or Edge.";
|
||||
const hasDetector = await ensureBarcodeDetector();
|
||||
if (!hasDetector) {
|
||||
scanError = "Failed to load barcode scanner. Try again or use Chrome/Edge.";
|
||||
showScanner = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
|
||||
stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: { facingMode: "environment", width: { ideal: 1280 }, height: { ideal: 720 } },
|
||||
});
|
||||
showScanner = true;
|
||||
} catch (e) {
|
||||
scanError = e instanceof Error ? e.message : "Could not access camera.";
|
||||
@@ -77,23 +90,31 @@
|
||||
};
|
||||
});
|
||||
|
||||
const SCAN_INTERVAL_MS = 300;
|
||||
|
||||
function scanLoop() {
|
||||
if (!showScanner || !videoEl || !("BarcodeDetector" in globalThis)) return;
|
||||
const detector = new (globalThis as unknown as { BarcodeDetector: typeof BarcodeDetector }).BarcodeDetector();
|
||||
let lastScan = 0;
|
||||
async function detect() {
|
||||
if (!showScanner || !videoEl || videoEl.readyState < 2) {
|
||||
if (!showScanner || !videoEl) return;
|
||||
if (videoEl.readyState < 2) {
|
||||
scanRAF = requestAnimationFrame(detect);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const barcodes = await detector.detect(videoEl);
|
||||
if (barcodes.length > 0) {
|
||||
skuValue = barcodes[0].rawValue;
|
||||
stopScan();
|
||||
return;
|
||||
const now = Date.now();
|
||||
if (now - lastScan >= SCAN_INTERVAL_MS) {
|
||||
lastScan = now;
|
||||
try {
|
||||
const barcodes = await detector.detect(videoEl);
|
||||
if (barcodes.length > 0) {
|
||||
skuValue = barcodes[0].rawValue;
|
||||
stopScan();
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// ignore frame errors
|
||||
}
|
||||
} catch {
|
||||
// ignore frame errors
|
||||
}
|
||||
scanRAF = requestAnimationFrame(detect);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user