Files
peworkshop/components/EnhancedQRScanner.js
T

591 lines
16 KiB
JavaScript

"use client";
import { useState, useEffect, useRef } from "react";
import { useZxing } from "react-zxing";
import { ensureScannerCompatibility } from "./scanner-polyfill";
export default function EnhancedQRScanner({
onScan,
width = 300,
height = 300,
}) {
const [error, setError] = useState(null);
const [isSecureContext, setIsSecureContext] = useState(true);
const [initialized, setInitialized] = useState(false);
const [cameraActive, setCameraActive] = useState(false);
const [hasCameras, setHasCameras] = useState(true);
const [scanSuccess, setScanSuccess] = useState(false);
const [manualInputValue, setManualInputValue] = useState("");
const [torchEnabled, setTorchEnabled] = useState(false);
const inputRef = useRef(null);
const [cameraPermissionDenied, setCameraPermissionDenied] = useState(false);
// Define video constraints explicitly
const videoConstraints = {
facingMode: "environment",
width: { min: 640, ideal: 1280, max: 1920 },
height: { min: 480, ideal: 720, max: 1080 },
};
// Setup the zxing scanner hook with explicit video constraints
const { ref, torch } = useZxing({
onDecodeResult(result) {
handleDecode(result.getText());
},
onError(error) {
handleError(error);
},
constraints: {
video: videoConstraints,
},
paused: !cameraActive,
});
// Check if we're in a secure context and if camera is accessible
useEffect(() => {
// Ensure scanner compatibility
ensureScannerCompatibility();
// Check if we're in a secure context (https or localhost)
const secure = window.isSecureContext;
setIsSecureContext(secure);
// Check if camera can be accessed
async function checkCameraAccess() {
try {
// First check if MediaDevices API is supported
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
throw new Error("MediaDevices API is not supported in this browser");
}
// Explicitly request video permission - important to avoid the error
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
});
// If we got a stream, we have permission - release it immediately
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
// Now enumerate devices to confirm we have video devices
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(
(device) => device.kind === "videoinput"
);
if (videoDevices.length === 0) {
setError(
"No camera detected. Please make sure your device has a camera."
);
setHasCameras(false);
} else {
setHasCameras(true);
setCameraActive(true); // Activate camera if we have permission
}
setInitialized(true);
} catch (err) {
console.error("Camera access error:", err);
// Handle permission denied specifically
if (err.name === "NotAllowedError" || err.name === "PermissionDeniedError") {
setCameraPermissionDenied(true);
setError("Camera permission denied. Please allow camera access in your browser settings.");
} else {
setError(`Camera error: ${err.message}`);
}
setInitialized(true);
}
}
if (isSecureContext) {
checkCameraAccess();
} else {
setInitialized(true); // Still mark as initialized even if not secure
}
}, []);
// Toggle torch/flashlight
const toggleTorch = () => {
if (torch) {
setTorchEnabled(!torchEnabled);
torch.toggled = !torchEnabled;
}
};
// Handle decode result
const handleDecode = (text) => {
console.log("QR scan result:", text);
if (!onScan || !text) return;
try {
// Show success visual
setScanSuccess(true);
setTimeout(() => setScanSuccess(false), 1500);
// Call the onScan callback with the decoded text
onScan(text);
} catch (err) {
console.error("Error processing QR scan result:", err);
}
};
// Manually request camera access
const requestCameraAccess = async () => {
try {
setError(null);
// Explicitly request video permission
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
});
// If we got a stream, we have permission
if (stream) {
// Release the stream since useZxing will request it again
stream.getTracks().forEach(track => track.stop());
setCameraActive(true);
setCameraPermissionDenied(false);
}
} catch (err) {
console.error("Failed to get camera permission:", err);
setError(`Camera error: ${err.message}`);
setCameraPermissionDenied(true);
}
};
// Handle manual input submission
const handleManualSubmit = () => {
if (manualInputValue.trim()) {
onScan(manualInputValue.trim());
setManualInputValue("");
}
};
// Handle camera errors
const handleError = (error) => {
console.error("QR Scanner error:", error);
setCameraActive(false);
// More descriptive error messages
let errorMessage = "Camera access error. ";
if (!isSecureContext) {
errorMessage +=
"Your browser requires HTTPS for camera access. When running locally, use http://localhost instead of your IP address.";
} else if (
error.name === "NotAllowedError" ||
error.name === "PermissionDeniedError"
) {
errorMessage +=
"Camera permission denied. Please allow camera access in your browser settings.";
setCameraPermissionDenied(true);
} else if (
error.name === "NotFoundError" ||
error.name === "DevicesNotFoundError"
) {
errorMessage +=
"No camera found. Please ensure your device has a working camera.";
} else if (
error.name === "NotReadableError" ||
error.name === "TrackStartError"
) {
errorMessage +=
"Camera is already in use by another application or encountered a hardware error.";
} else {
errorMessage += `${
error.message ||
"Please check your camera permissions and refresh the page."
}`;
}
setError(errorMessage);
};
// Handle secure context warning
if (!isSecureContext) {
return (
<div className="enhanced-qr-scanner">
<div className="scanner-error">
<p>Camera access requires a secure context (HTTPS or localhost).</p>
<p>
When running locally, use http://localhost:3000 instead of your
network IP.
</p>
</div>
<ManualInput onScan={onScan} />
</div>
);
}
// Handle initialization state
if (!initialized) {
return (
<div className="enhanced-qr-scanner">
<div className="scanner-loading">Initializing camera...</div>
</div>
);
}
return (
<div className="enhanced-qr-scanner">
{error && (
<div className="scanner-error">
<p>{error}</p>
{cameraPermissionDenied ? (
<div className="permission-help">
<p>To fix this issue:</p>
<ol>
<li>Click the camera icon in your browser's address bar</li>
<li>Select "Allow" for camera access</li>
<li>Refresh this page</li>
</ol>
<button
className="retry-button"
onClick={requestCameraAccess}
>
Request Camera Permission
</button>
</div>
) : (
<button
className="retry-button"
onClick={() => {
setError(null);
requestCameraAccess();
}}
>
Retry Camera Access
</button>
)}
</div>
)}
{cameraActive && !error && (
<div
className={`scanner-container ${scanSuccess ? "scan-success" : ""}`}
style={{ width, height }}
>
<video
ref={ref}
className="scanner-video"
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
/>
{scanSuccess && <div className="scan-overlay">✓</div>}
{/* Scanning frame to help user focus */}
<div className="scanning-frame"></div>
{/* Add flashlight toggle button if available */}
{torch && (
<button
className={`torch-button ${torchEnabled ? 'active' : ''}`}
onClick={toggleTorch}
>
{torchEnabled ? '💡 Off' : '💡 On'}
</button>
)}
</div>
)}
{/* Text input fallback when camera fails */}
{(!cameraActive || error) && (
<div className="manual-input-container">
<p className="fallback-text">Enter the QR code manually:</p>
<div className="input-container">
<input
type="text"
placeholder="Enter QR code (e.g. QR1)"
className="manual-input"
value={manualInputValue}
onChange={(e) => setManualInputValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
handleManualSubmit();
}
}}
ref={inputRef}
/>
<button className="submit-button" onClick={handleManualSubmit}>
Submit
</button>
</div>
</div>
)}
<style jsx>{`
.enhanced-qr-scanner {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.scanner-error {
color: #d32f2f;
margin-bottom: 15px;
text-align: center;
padding: 12px;
background-color: #ffebee;
border-radius: 8px;
width: 100%;
}
.permission-help {
margin-top: 12px;
background-color: #f8f8f8;
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
text-align: left;
}
.permission-help p {
margin: 0 0 8px 0;
font-weight: bold;
}
.permission-help ol {
margin: 0 0 10px 0;
padding-left: 20px;
}
.permission-help li {
margin-bottom: 5px;
}
.retry-button {
margin-top: 10px;
padding: 8px 16px;
background-color: #2196f3;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
.retry-button:hover {
background-color: #1976d2;
}
.scanner-loading {
text-align: center;
padding: 12px;
background-color: #e8f5e9;
border-radius: 8px;
width: 100%;
margin-bottom: 15px;
}
.scanner-container {
position: relative;
width: 100%;
max-width: ${width}px;
height: ${height}px;
border-radius: 8px;
overflow: hidden;
border: 2px solid #ddd;
background-color: #f5f5f5;
transition: all 0.3s ease;
}
.scanning-frame {
position: absolute;
top: 50%;
left: 50%;
width: 70%;
height: 70%;
transform: translate(-50%, -50%);
border: 2px solid rgba(255, 255, 255, 0.8);
border-radius: 8px;
box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.3);
z-index: 2;
}
.torch-button {
position: absolute;
bottom: 15px;
left: 50%;
transform: translateX(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: white;
border: none;
border-radius: 20px;
padding: 8px 16px;
cursor: pointer;
z-index: 3;
font-size: 14px;
}
.torch-button.active {
background-color: rgba(255, 193, 7, 0.8);
color: black;
}
.scan-success {
border-color: #4caf50;
box-shadow: 0 0 15px rgba(76, 175, 80, 0.5);
}
.scan-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: rgba(76, 175, 80, 0.5);
color: white;
font-size: 80px;
animation: fade-in-out 1.5s forwards;
z-index: 10;
}
@keyframes fade-in-out {
0% {
opacity: 0;
}
20% {
opacity: 1;
}
80% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.manual-input-container {
margin-top: 15px;
width: 100%;
max-width: ${width}px;
text-align: center;
}
.fallback-text {
margin-bottom: 10px;
color: #555;
}
.input-container {
display: flex;
width: 100%;
}
.manual-input {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px 0 0 4px;
font-size: 16px;
}
.submit-button {
padding: 10px 15px;
background-color: #68543c;
color: white;
border: none;
border-radius: 0 4px 4px 0;
cursor: pointer;
font-weight: bold;
}
.submit-button:hover {
background-color: #4a3c2a;
}
`}</style>
</div>
);
}
// Helper component for manual input
function ManualInput({ onScan }) {
const [value, setValue] = useState("");
const handleSubmit = () => {
if (value.trim()) {
onScan(value.trim());
setValue("");
}
};
return (
<div className="manual-input-wrapper">
<h3>Manual Code Entry</h3>
<p>Enter the QR code value manually:</p>
<div className="input-row">
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Enter code (e.g. QR1)"
onKeyDown={(e) => {
if (e.key === "Enter") {
handleSubmit();
}
}}
/>
<button onClick={handleSubmit}>Submit</button>
</div>
<style jsx>{`
.manual-input-wrapper {
width: 100%;
max-width: 300px;
margin: 20px 0;
padding: 15px;
background-color: #f5f5f5;
border-radius: 8px;
text-align: center;
}
h3 {
margin-top: 0;
color: #333;
margin-bottom: 10px;
}
p {
margin-bottom: 15px;
color: #666;
font-size: 14px;
}
.input-row {
display: flex;
}
input {
flex: 1;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px 0 0 4px;
font-size: 16px;
}
button {
padding: 10px 15px;
background-color: #68543c;
color: white;
border: none;
border-radius: 0 4px 4px 0;
cursor: pointer;
font-weight: bold;
}
`}</style>
</div>
);
}