squared off qr scanner

This commit is contained in:
lemonknowsall committed 2025-10-27 23:01:13 -07:00
1 parent 5687faa746
commit 5d18a2acf1
3 files changed
+111 -38

No files matched your search

+4 -2
View File
@@ -45,7 +45,7 @@ export function CashuWallet() {
const { user } = useCurrentUser();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
const { toast } = useToast();
const { generateQRCode, isScanning, startScanning, stopScanning, error: qrError, classifyQRCode } = useQRCode();
const { generateQRCode, isScanning, startScanning, stopScanning, error: qrError, classifyQRCode, setModalOpen } = useQRCode();
const { copy: copyToClipboard } = useCopyToClipboard();
const { hasNsecAccess } = useNsecAccess();
@@ -336,12 +336,14 @@ export function CashuWallet() {
// Start/stop QR scanner when modal opens/closes
useEffect(() => {
if (showQRScanner) {
setModalOpen?.(true);
startScanning(handleQRScanResult);
} else {
setModalOpen?.(false);
stopScanning();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showQRScanner, startScanning, stopScanning]);
}, [showQRScanner, startScanning, stopScanning, setModalOpen]);
// ============================================================================
// EFFECTS - Cleanup
+29 -33
View File
@@ -3,7 +3,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2 } from 'lucide-react';
import { X, Coins, AlertTriangle, RefreshCw, Key, ArrowRightLeft, Loader2, Clipboard } from 'lucide-react';
import { QRModal } from '@/components/ui/qr-modal';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { nip19 } from 'nostr-tools';
@@ -487,51 +487,47 @@ export function WalletModals({
)}
{/* QR Scanner Modal */}
<Dialog open={showQRScanner} onOpenChange={(open) => {
<Dialog open={showQRScanner} onOpenChange={async (open) => {
if (!open) {
setShowQRScanner(false);
stopScanning();
await stopScanning();
}
}}>
<DialogContent
className="max-w-none w-screen h-screen !h-[100dvh] p-6 bg-background border-0 rounded-none !top-0 !left-0 !right-0 !bottom-0 !translate-x-0 !translate-y-0 flex flex-col"
style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
transform: 'none',
maxWidth: '100vw',
maxHeight: '100vh',
}}
>
{/* Camera view with rounded corners */}
<div
id="qr-reader"
className="flex-1 rounded-2xl overflow-hidden"
style={{
width: '100%',
height: '100%',
}}
/>
<DialogContent className="max-w-[min(90vw,500px)] w-full p-4 sm:p-6">
{/* Header */}
<DialogHeader>
<DialogTitle></DialogTitle>
</DialogHeader>
{/* Error message */}
{qrError && (
<div className="absolute bottom-28 left-6 right-6 p-3 bg-destructive text-destructive-foreground rounded-lg text-center z-50">
{qrError}
</div>
)}
{/* Camera container with square aspect ratio */}
<div className="relative w-full" style={{ aspectRatio: '1 / 1' }}>
<div
id="qr-reader"
className="w-full h-full rounded-xl overflow-hidden bg-muted"
/>
{/* Scanning area overlay frame */}
{/* <div className="absolute inset-0 pointer-events-none flex items-center justify-center">
<div className="w-4/5 h-4/5 border-4 border-white/30 rounded-xl shadow-lg" />
</div> */}
{/* Error message */}
{qrError && (
<div className="absolute inset-x-4 top-4 p-3 bg-destructive text-destructive-foreground rounded-lg text-center z-50 shadow-lg">
{qrError}
</div>
)}
</div>
{/* Paste Button */}
<div className="mt-4 pb-safe flex justify-center">
<div className="mt-4 flex justify-center">
<Button
onClick={async () => {
if (onPasteQRCode) {
await onPasteQRCode();
}
}}
className="rounded-full px-8"
className="h-12 px-12 rounded-full"
size="lg"
>
Paste
+78 -3
View File
@@ -20,6 +20,7 @@ interface UseQRCodeReturn {
startScanning: (onResult: (result: QRScanResult) => void) => Promise<void>;
stopScanning: () => Promise<void>;
classifyQRCode: (text: string) => QRScanResult;
setModalOpen?: (isOpen: boolean) => void;
}
/**
@@ -38,8 +39,15 @@ export function useQRCode(): UseQRCodeReturn {
const [isScanning, setIsScanning] = useState(false);
const [scanError, setScanError] = useState<string | null>(null);
const scannerRef = useRef<Html5Qrcode | null>(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<string> => {
setIsGenerating(true);
setError(null);
@@ -105,6 +113,8 @@ export function useQRCode(): UseQRCodeReturn {
const startScanning = useCallback(async (onResult: (result: QRScanResult) => void): Promise<void> => {
try {
isStartingRef.current = true;
shouldCancelRef.current = false;
setScanError(null);
// Find available cameras
@@ -113,6 +123,12 @@ export function useQRCode(): UseQRCodeReturn {
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
@@ -126,7 +142,9 @@ export function useQRCode(): UseQRCodeReturn {
await scanner.start(
cameraId,
{
fps: 10
fps: 10,
aspectRatio: 1,
qrbox: 250
},
(decodedText) => {
const result = classifyQRCode(decodedText);
@@ -141,8 +159,24 @@ export function useQRCode(): UseQRCodeReturn {
}
);
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;
@@ -165,16 +199,56 @@ export function useQRCode(): UseQRCodeReturn {
const stopScanning = useCallback(async (): Promise<void> => {
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) {
await scannerRef.current.stop();
await scannerRef.current.clear();
// 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;
}
}, []);
@@ -186,5 +260,6 @@ export function useQRCode(): UseQRCodeReturn {
startScanning,
stopScanning,
classifyQRCode,
setModalOpen,
};
}