JEISA-WEBAPP/src/components/stock/QRScannerDialog.tsx

74 lines
No EOL
1.8 KiB
TypeScript

"use client"
import { useEffect } from "react"
import { Html5QrcodeScanner } from "html5-qrcode"
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
} from "@/components/ui/dialog"
interface QRScannerDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onScanSuccess: (decodedText: string) => void
}
const QRScannerDialog = ({ open, onOpenChange, onScanSuccess }: QRScannerDialogProps) => {
useEffect(() => {
if (!open) return;
const scanner = new Html5QrcodeScanner(
"reader", // The ID of the element to render the scanner in
{
qrbox: {
width: 250,
height: 250,
},
fps: 5,
},
false // verbose
);
const handleSuccess = (decodedText: string) => {
scanner.clear();
onScanSuccess(decodedText);
};
const handleError = (error: any) => {
// Don't log common errors like QR code not found
if (typeof error !== 'string' || !error.includes('No QR code found')) {
console.error("QR Scanner Error:", error);
}
};
scanner.render(handleSuccess, handleError);
// Cleanup function to stop the scanner when the component unmounts or dialog closes
return () => {
if (scanner) {
scanner.clear().catch(error => {
console.error("Failed to clear scanner.", error);
});
}
};
}, [open, onScanSuccess]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Scan QR Code</DialogTitle>
<DialogDescription>
Point your camera at a QR code to scan it.
</DialogDescription>
</DialogHeader>
<div id="reader" className="w-full"></div>
</DialogContent>
</Dialog>
);
};
export default QRScannerDialog;