import { useState, useCallback, useRef } from 'react'; import QRCode from 'qrcode'; import { Html5Qrcode } from 'html5-qrcode'; import { useToast } from '@/hooks/useToast'; export type QRScanResult = | { type: 'lightning_invoice'; value: string } | { type: 'lightning_address'; value: string } | { type: 'cashu_token'; value: string } | { type: 'bitcoin_address'; value: string } | { type: 'npub'; value: string } | { type: 'unknown'; value: string }; interface UseQRCodeReturn { generateQRCode: (text: string) => Promise; isGenerating: boolean; error: string | null; // Scanner functions isScanning: boolean; startScanning: (onResult: (result: QRScanResult) => void) => Promise; stopScanning: () => Promise; classifyQRCode: (text: string) => QRScanResult; setModalOpen?: (isOpen: boolean) => void; } /** * Hook for generating QR codes * * @example * ```tsx * const { generateQRCode, isGenerating, error } = useQRCode(); * * const qrCodeUrl = await generateQRCode('cashuBo2Ft...'); * ``` */ export function useQRCode(): UseQRCodeReturn { const [isGenerating, setIsGenerating] = useState(false); const [error, setError] = useState(null); const [isScanning, setIsScanning] = useState(false); const [scanError, setScanError] = useState(null); const scannerRef = useRef(null); const isStartingRef = useRef(false); const shouldCancelRef = useRef(false); const modalOpenRef = useRef(true); const { toast } = useToast(); const setModalOpen = useCallback((isOpen: boolean) => { modalOpenRef.current = isOpen; }, []); const generateQRCode = useCallback(async (text: string): Promise => { setIsGenerating(true); setError(null); try { const qrCodeUrl = await QRCode.toDataURL(text, { width: 256, margin: 2, color: { dark: '#000000', light: '#FFFFFF', }, }); setIsGenerating(false); return qrCodeUrl; } catch (err) { const errorMessage = 'Failed to generate QR code'; console.error(errorMessage, err); setError(errorMessage); setIsGenerating(false); toast({ variant: "destructive", title: "QR Code Failed", description: errorMessage, }); return ''; } }, [toast]); const classifyQRCode = useCallback((decodedText: string): QRScanResult => { // Lightning invoice: lnbc... or lightning:lnbc... (case insensitive) const lightningInvoiceMatch = decodedText.match(/^(?:lightning:)?(lnbc[a-z0-9]+)$/i); if (lightningInvoiceMatch) { return { type: 'lightning_invoice', value: lightningInvoiceMatch[1] }; } // Lightning address: name@domain.tld or lightning:name@domain.tld const lightningAddressMatch = decodedText.match(/^(?:lightning:)?([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/); if (lightningAddressMatch) { return { type: 'lightning_address', value: lightningAddressMatch[1] }; } // Cashu token: cashu... if (/^cashu[A-Za-z0-9+/=_-]+$/.test(decodedText)) { return { type: 'cashu_token', value: decodedText }; } // Bitcoin address: bc1... or legacy (1..., 3...) if (/^(bc1|3|1)[a-zA-Z0-9]{25,62}$/.test(decodedText)) { return { type: 'bitcoin_address', value: decodedText }; } // Nostr npub: npub1... or nostr:npub1... const npubMatch = decodedText.match(/^(?:nostr:)?(npub1[a-z0-9]{58})$/); if (npubMatch) { return { type: 'npub', value: npubMatch[1] }; } return { type: 'unknown', value: decodedText }; }, []); const startScanning = useCallback(async (onResult: (result: QRScanResult) => void): Promise => { try { isStartingRef.current = true; shouldCancelRef.current = false; setScanError(null); // Find available cameras const devices = await Html5Qrcode.getCameras(); if (devices.length === 0) { throw new Error('No cameras found'); } // Check if we should cancel before proceeding if (shouldCancelRef.current) { isStartingRef.current = false; return; } // Use the rear camera by default, or first available const cameraId = devices.length > 1 ? devices.find(d => d.label.toLowerCase().includes('back') || d.label.toLowerCase().includes('rear'))?.id || devices[0].id : devices[0].id; // Initialize scanner const scanner = new Html5Qrcode('qr-reader'); scannerRef.current = scanner; // Start scanning await scanner.start( cameraId, { fps: 10, aspectRatio: 1, qrbox: 250 }, (decodedText) => { const result = classifyQRCode(decodedText); onResult(result); }, (errorMessage) => { // Ignore decoding errors, camera is still running // Only log if it's not a "QR code not found" type error if (!errorMessage.includes('qr')) { console.debug('QR scan error:', errorMessage); } } ); isStartingRef.current = false; // Check if we should immediately stop after starting (cancel was requested during init) if (shouldCancelRef.current || !modalOpenRef.current) { try { await scanner.stop(); await scanner.clear(); scannerRef.current = null; } catch (err) { console.error('Error stopping scanner after cancelled init:', err); } return; } setIsScanning(true); } catch (err) { isStartingRef.current = false; shouldCancelRef.current = false; let errorMessage = 'Failed to start camera'; if (err instanceof Error) { errorMessage = err.message; } else if (typeof err === 'string') { errorMessage = err; } // Provide more helpful error messages if (errorMessage.includes('NotAllowedError') || errorMessage.includes('Permission denied')) { errorMessage = 'Camera permission denied. Please allow camera access.'; } else if (errorMessage.includes('NotFoundError') || errorMessage.includes('No device')) { errorMessage = 'No camera found. Please connect a camera.'; } setScanError(errorMessage); setIsScanning(false); console.error('Camera error:', err); } }, [classifyQRCode]); const stopScanning = useCallback(async (): Promise => { try { // If scanner is starting up, set cancel flag if (isStartingRef.current) { shouldCancelRef.current = true; // Wait for startup to complete and auto-stop let attempts = 0; while (isStartingRef.current && attempts < 50) { // Wait up to 5 seconds await new Promise(resolve => setTimeout(resolve, 100)); attempts++; } } if (scannerRef.current) { // Check if scanner is actually running before trying to stop const scanner = scannerRef.current; try { // Html5Qrcode has a getState() method to check if it's scanning const state = scanner.getState(); if (state === 2) { // State 2 = SCANNING await scanner.stop(); } else if (state === 1) { // State 1 = STARTING // Wait a bit more and try again await new Promise(resolve => setTimeout(resolve, 200)); const newState = scanner.getState(); if (newState === 2) { await scanner.stop(); } } } catch (stopErr) { // If stop fails, try to clear anyway console.warn('Error stopping scanner, attempting to clear:', stopErr); } try { await scanner.clear(); } catch (clearErr) { console.warn('Error clearing scanner:', clearErr); } scannerRef.current = null; } shouldCancelRef.current = false; isStartingRef.current = false; setIsScanning(false); setScanError(null); } catch (err) { console.error('Error stopping scanner:', err); shouldCancelRef.current = false; isStartingRef.current = false; setIsScanning(false); scannerRef.current = null; } }, []); return { generateQRCode, isGenerating, error: error || scanError, isScanning, startScanning, stopScanning, classifyQRCode, setModalOpen, }; }