SCANNER WORKS!!! JUST ADD THE MORE CLUE BUTTONS !!! AND NEXT CLUE ERROR CHECKING

This commit is contained in:
bobbert committed 2025-03-17 12:41:17 +00:00
1 parent 07099ba6b4
commit 02a0088d28
11 files changed
+861 -217

No files matched your search

+343 -70
View File
@@ -1,6 +1,7 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { Scanner } from "@yudiel/react-qr-scanner";
import { useZxing } from "react-zxing";
import { ensureScannerCompatibility } from "./scanner-polyfill";
export default function EnhancedQRScanner({
onScan,
@@ -12,12 +13,38 @@ export default function EnhancedQRScanner({
const [initialized, setInitialized] = useState(false);
const [cameraActive, setCameraActive] = useState(false);
const [hasCameras, setHasCameras] = useState(true);
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 3;
const scannerRef = useRef(null);
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
// 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);
@@ -25,6 +52,23 @@ export default function EnhancedQRScanner({
// 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"
@@ -37,38 +81,88 @@ export default function EnhancedQRScanner({
setHasCameras(false);
} else {
setHasCameras(true);
setCameraActive(true); // Activate camera if we have permission
}
setInitialized(true);
} catch (err) {
console.error("Error checking camera devices:", err);
setError(`Camera initialization error: ${err.message}`);
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);
}
}
checkCameraAccess();
if (isSecureContext) {
checkCameraAccess();
} else {
setInitialized(true); // Still mark as initialized even if not secure
}
}, []);
// Handle successful scan
const handleDecode = (result) => {
if (onScan && result) {
onScan(result);
// Toggle torch/flashlight
const toggleTorch = () => {
if (torch) {
setTorchEnabled(!torchEnabled);
torch.toggled = !torchEnabled;
}
};
// Try to restart the camera
const retryCamera = () => {
if (retryCount < maxRetries) {
// 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);
setRetryCount((prev) => prev + 1);
// Force re-render of scanner component
setCameraActive(false);
setTimeout(() => setCameraActive(true), 500);
} else {
setError(
"Could not access camera after multiple attempts. Please refresh the page or try another device."
);
// 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("");
}
};
@@ -89,6 +183,7 @@ export default function EnhancedQRScanner({
) {
errorMessage +=
"Camera permission denied. Please allow camera access in your browser settings.";
setCameraPermissionDenied(true);
} else if (
error.name === "NotFoundError" ||
error.name === "DevicesNotFoundError"
@@ -111,13 +206,6 @@ export default function EnhancedQRScanner({
setError(errorMessage);
};
// When initialized, activate camera
useEffect(() => {
if (initialized && hasCameras && isSecureContext && !error) {
setCameraActive(true);
}
}, [initialized, hasCameras, isSecureContext, error]);
// Handle secure context warning
if (!isSecureContext) {
return (
@@ -129,6 +217,7 @@ export default function EnhancedQRScanner({
network IP.
</p>
</div>
<ManualInput onScan={onScan} />
</div>
);
}
@@ -147,8 +236,29 @@ export default function EnhancedQRScanner({
{error && (
<div className="scanner-error">
<p>{error}</p>
{retryCount < maxRetries && (
<button className="retry-button" onClick={retryCamera}>
{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>
)}
@@ -157,63 +267,54 @@ export default function EnhancedQRScanner({
{cameraActive && !error && (
<div
className="scanner-container"
className={`scanner-container ${scanSuccess ? "scan-success" : ""}`}
style={{ width, height }}
ref={scannerRef}
>
<Scanner
onResult={handleDecode}
onError={handleError}
constraints={{
facingMode: "environment",
width: { min: 640, ideal: 1280, max: 1920 },
height: { min: 480, ideal: 720, max: 1080 },
aspectRatio: { ideal: 1 },
<video
ref={ref}
className="scanner-video"
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
}}
containerStyle={{
width: "100%",
height: "100%",
borderRadius: "8px",
overflow: "hidden",
}}
videoStyle={{
objectFit: "cover",
width: "100%",
height: "100%",
}}
scanDelay={500}
/>
{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">
Having trouble with the camera? Try entering a code manually:
</p>
<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" && e.target.value) {
onScan(e.target.value);
e.target.value = "";
if (e.key === "Enter") {
handleManualSubmit();
}
}}
ref={inputRef}
/>
<button
className="submit-button"
onClick={(e) => {
const input = e.target.previousSibling;
if (input.value) {
onScan(input.value);
input.value = "";
}
}}
>
<button className="submit-button" onClick={handleManualSubmit}>
Submit
</button>
</div>
@@ -237,6 +338,29 @@ export default function EnhancedQRScanner({
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;
@@ -271,6 +395,76 @@ export default function EnhancedQRScanner({
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 {
@@ -315,3 +509,82 @@ export default function EnhancedQRScanner({
</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>
);
}
+35 -5
View File
@@ -1,6 +1,6 @@
"use client";
import { useState, useEffect } from "react";
import { Scanner } from "@yudiel/react-qr-scanner";
import QrScanner from "@yudiel/react-qr-scanner"; // Correct import
export default function QRScanner({ onScan, width = 300, height = 300 }) {
const [error, setError] = useState(null);
@@ -39,8 +39,37 @@ export default function QRScanner({ onScan, width = 300, height = 300 }) {
}, []);
const handleDecode = (result) => {
if (onScan && result) {
onScan(result);
console.log("QR scan result:", result);
if (!onScan || !result) return;
try {
// Handle different result formats
if (result && typeof result === "object") {
if (result.text) {
onScan(result.text);
return;
}
if (result.data) {
onScan(result.data);
return;
}
if (result.toString && typeof result.toString === "function") {
const stringValue = result.toString();
if (stringValue !== "[object Object]") {
onScan(stringValue);
return;
}
}
} else if (typeof result === "string") {
onScan(result);
return;
}
// Last resort
onScan(String(result));
} catch (err) {
console.error("Error processing QR scan result:", err);
}
};
@@ -112,8 +141,8 @@ export default function QRScanner({ onScan, width = 300, height = 300 }) {
)}
<div className="scanner-container" style={{ width, height }}>
<Scanner
onResult={handleDecode}
<QrScanner
onDecode={handleDecode} // Using onDecode instead of onResult
onError={handleError}
constraints={{
facingMode: "environment",
@@ -131,6 +160,7 @@ export default function QRScanner({ onScan, width = 300, height = 300 }) {
width: "100%",
height: "100%",
}}
scanDelay={300} // Faster scanning
/>
</div>
+78
View File
@@ -0,0 +1,78 @@
// This is a helper function to ensure QR scanner compatibility
export const ensureScannerCompatibility = () => {
// Add basic polyfills for methods that might be missing
if (typeof Function.prototype.bind !== "function") {
Function.prototype.bind = function (context) {
const fn = this;
return function () {
return fn.apply(context, arguments);
};
};
}
// Ensure MediaDevices API is available
if (typeof window !== "undefined") {
if (!navigator.mediaDevices) {
navigator.mediaDevices = {};
}
// Polyfill for older browsers that don't implement getUserMedia
if (!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = function(constraints) {
const getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
// Return a rejected promise if getUserMedia is not implemented
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
// Otherwise, wrap the call to the old navigator.getUserMedia with a Promise
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
// Ensure console methods exist for debugging
if (!window.console) window.console = {};
const methods = ["log", "error", "warn", "info"];
methods.forEach((method) => {
if (!window.console[method]) {
window.console[method] = function () {};
}
});
}
return true;
};
// Helper function to check if camera is available and accessible
export const checkCameraAvailability = async () => {
try {
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
return { available: false, error: 'MediaDevices API not supported' };
}
// Try to access the camera with explicit video request
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
});
// If we get here, camera is available - stop the stream
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
return { available: true };
} catch (error) {
return {
available: false,
error: error.message,
name: error.name,
permission: error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError'
? 'denied'
: 'unknown'
};
}
};