import QrScanner from 'qr-scanner'; import Services from '../../services/service'; import { prepareAndSendPairingTx } from '~/utils/sp-address.utils'; export default class QrScannerComponent extends HTMLElement { videoElement: any; wrapper: any; qrScanner: any; constructor() { super(); this.attachShadow({ mode: 'open' }); this.wrapper = document.createElement('div'); this.wrapper.style.position = 'relative'; this.wrapper.style.width = '150px'; this.wrapper.style.height = '150px'; this.videoElement = document.createElement('video'); this.videoElement.style.width = '100%'; document.body?.append(this.wrapper); this.wrapper.prepend(this.videoElement); } connectedCallback() { this.initializeScanner(); } async initializeScanner() { if (!this.videoElement) { console.error('Video element not found!'); return; } console.log('🚀 ~ QrScannerComponent ~ initializeScanner ~ this.videoElement:', this.videoElement); this.qrScanner = new QrScanner(this.videoElement, (result) => this.onQrCodeScanned(result), { highlightScanRegion: true, highlightCodeOutline: true, }); try { await QrScanner.hasCamera(); this.qrScanner.start(); this.videoElement.style = 'height: 200px; width: 200px'; this.shadowRoot?.appendChild(this.wrapper); } catch (e) { console.error('No camera found or error starting the QR scanner', e); } } async onQrCodeScanned(result: any) { console.log(`QR Code detected:`, result); const data = result.data; const scannedUrl = new URL(data); // Extract the 'sp_address' parameter const spAddress = scannedUrl.searchParams.get('sp_address'); if (spAddress) { // Call the sendPairingTx function with the extracted sp_address try { await prepareAndSendPairingTx(spAddress); } catch (e) { console.error('Failed to pair:', e); } } this.qrScanner.stop(); // if you want to stop scanning after one code is detected } disconnectedCallback() { if (this.qrScanner) { this.qrScanner.destroy(); } } } customElements.define('qr-scanner', QrScannerComponent);