From 929719e5137348aabd6935606f9fbaf11f300ceb Mon Sep 17 00:00:00 2001 From: Claudio Ortolina Date: Fri, 14 Feb 2025 11:16:16 +0000 Subject: [PATCH] Open camera via a button --- assets/js/barcode-scanner.js | 50 ++++++++++--------- .../record_live/barcode_scanner_component.ex | 23 ++++++++- priv/gettext/default.pot | 5 ++ 3 files changed, 53 insertions(+), 25 deletions(-) diff --git a/assets/js/barcode-scanner.js b/assets/js/barcode-scanner.js index 35bfa77d..36bc43b4 100644 --- a/assets/js/barcode-scanner.js +++ b/assets/js/barcode-scanner.js @@ -22,32 +22,34 @@ export default { } }, }; + this.el.addEventListener("camera_request", () => { + navigator.mediaDevices + .getUserMedia(constraints) + .then((mediaStream) => { + console.debug("Camera access allowed") + this.pushEventTo(this.cameraPreview, "camera_allowed", {}); + this.cameraPreview.srcObject = mediaStream; + this.cameraPreview.onloadedmetadata = () => { + this.cameraPreview.play(); + this.scanInterval = window.setInterval(async () => { + const barcodes = await barcodeDetector.detect(this.cameraPreview); + if (barcodes.length <= 0) return; - navigator.mediaDevices - .getUserMedia(constraints) - .then((mediaStream) => { - console.debug("Camera access allowed") - this.pushEventTo(this.cameraPreview, "camera_allowed", {}); - this.cameraPreview.srcObject = mediaStream; - this.cameraPreview.onloadedmetadata = () => { - this.cameraPreview.play(); - this.scanInterval = window.setInterval(async () => { - const barcodes = await barcodeDetector.detect(this.cameraPreview); - if (barcodes.length <= 0) return; + barcodes.forEach(barcode => { + if (!detectedBarcodes.has(barcode.rawValue)) { + this.pushEventTo(this.cameraPreview, "barcode_scanned", { number: barcode.rawValue }); + detectedBarcodes.add(barcode.rawValue); + }; + }); + }, 500) + }; + }) + .catch((err) => { + console.error(`${err.name}: ${err.message}`); + this.pushEventTo(this.cameraPreview, "camera_denied", {}); + }); + }) - barcodes.forEach(barcode => { - if (!detectedBarcodes.has(barcode.rawValue)) { - this.pushEventTo(this.cameraPreview, "barcode_scanned", { number: barcode.rawValue }); - detectedBarcodes.add(barcode.rawValue); - }; - }); - }, 500) - }; - }) - .catch((err) => { - console.error(`${err.name}: ${err.message}`); - this.pushEventTo(this.cameraPreview, "camera_denied", {}); - }); }, destroyed() { this.cameraPreview.srcObject.getTracks().forEach(track => track.stop()); diff --git a/lib/music_library_web/live/record_live/barcode_scanner_component.ex b/lib/music_library_web/live/record_live/barcode_scanner_component.ex index 510f3164..168fad85 100644 --- a/lib/music_library_web/live/record_live/barcode_scanner_component.ex +++ b/lib/music_library_web/live/record_live/barcode_scanner_component.ex @@ -25,7 +25,28 @@ defmodule MusicLibraryWeb.RecordLive.BarcodeScannerComponent do

{@camera}

- + +