Skip to content

Commit

Permalink
Merge pull request #143 from keypom/development
Browse files Browse the repository at this point in the history
fix scanning issues
  • Loading branch information
BenKurrek authored Nov 9, 2024
2 parents 2d48211 + 7be73e7 commit e04efc8
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 44 deletions.
82 changes: 47 additions & 35 deletions src/components/scanner/qr-scanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import { isTestEnv } from "@/constants/common";
import { Box } from "@chakra-ui/react";
import { Scanner, useDevices } from "@yudiel/react-qr-scanner";
import { motion } from "framer-motion";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { ErrorBox } from "../ui/error-box";
import { LoadingOverlay } from "./loading-overlay";
import eventHelperInstance from "@/lib/event";

export const QrScanner = ({
handleScan,
Expand All @@ -23,44 +22,60 @@ export const QrScanner = ({
const [selectedDevice, setSelectedDevice] = useState<string | undefined>(
undefined,
);
const [isOnCooldown, setIsOnCooldown] = useState(false);
const [isScanning, setIsScanning] = useState(false);
const [showAnimation, setShowAnimation] = useState(false);
const devices = useDevices();

const cooldownDelay = 3000; // Cooldown period after processing (in milliseconds)
// Use refs for scanning logic
const isScanningRef = useRef(false);
const isOnCooldownRef = useRef(false);

// Use state for triggering re-renders
const [isScanning, setIsScanning] = useState(false);
const [isOnCooldown, setIsOnCooldown] = useState(false);

const variants = {
open: { x: [0, -50, 50, -50, 50, -50, 50, 0] },
closed: { x: 0 },
};

const onScan = async (result) => {
if (isOnCooldown || isScanning) return;
const enableCooldown = useCallback(() => {
isOnCooldownRef.current = true; // Set cooldown flag
setIsOnCooldown(true); // Trigger re-render

const value = result[0].rawValue;
setShowAnimation(true); // Optional: Show animation or overlay

setIsScanning(true);
setTimeout(() => {
isOnCooldownRef.current = false; // Reset cooldown flag after 3 seconds
setIsOnCooldown(false); // Trigger re-render
setShowAnimation(false); // Hide animation or overlay
}, 3000); // Cooldown duration in milliseconds
}, []);

try {
await handleScan(value);
} catch (error: any) {
// Errors are handled within handleScan
eventHelperInstance.debugLog(error, "error");
} finally {
setIsScanning(false);
enableCooldown();
}
};
const onScan = useCallback(
async (result: any) => {
if (isOnCooldownRef.current || isScanningRef.current) {
// Ignore scans during cooldown or if already scanning
return;
}

const enableCooldown = () => {
setIsOnCooldown(true);
setShowAnimation(true);
setTimeout(() => {
setIsOnCooldown(false);
setShowAnimation(false);
}, cooldownDelay);
};
isScanningRef.current = true; // Set scanning flag to true
setIsScanning(true); // Trigger re-render

const value = result[0]?.rawValue;

try {
await handleScan(value);
} catch (error) {
// Handle errors
console.error(error);
} finally {
isScanningRef.current = false; // Reset scanning flag
setIsScanning(false); // Trigger re-render
enableCooldown(); // Start cooldown
}
},
[handleScan, enableCooldown],
);

const useNextDevice = () => {
if (devices.length > 0) {
Expand All @@ -83,18 +98,17 @@ export const QrScanner = ({
// DO NOT REMOVE: Exposes the triggerTestScan function to the window in test environment
useEffect(() => {
if (isTestEnv) {
// @ts-expect-error - Expose the triggerTestScan function to the window
window.triggerTestScan = (result) => {
// Expose the triggerTestScan function to the window
(window as any).triggerTestScan = (result) => {
onScan(result);
};
}
return () => {
if (isTestEnv) {
// @ts-expect-error - Expose the triggerTestScan function to the window
delete window.triggerTestScan;
delete (window as any).triggerTestScan;
}
};
}, []);
}, [onScan]);

if (!devices) {
return (
Expand Down Expand Up @@ -163,9 +177,7 @@ export const QrScanner = ({
},
video: {
borderRadius: "1rem",
border: `3px solid ${
showAnimation ? "red" : "var(--green, #00EC97)"
}`,
border: `3px solid var(--green, #00EC97)`,
background: "#00ec97",
objectFit: "cover",
aspectRatio: "1/1",
Expand Down
1 change: 1 addition & 0 deletions src/lib/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,7 @@ class EventJS {
isScav: boolean;
accountId?: string;
}) => {
console.log("claimEventDrop", { secretKey, dropId, dropSecretKey });
const pkToClaim = this.getPubFromSecret(dropSecretKey);
this.debugLog(`pkToClaim: ${pkToClaim}`, "log");

Expand Down
19 changes: 10 additions & 9 deletions src/routes/scan.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ import { useEffect, useState } from "react";
import eventHelperInstance from "@/lib/event";
import { useEventCredentials } from "@/stores/event-credentials";
import { useAccountData } from "@/hooks/useAccountData";
import { LoadingBox } from "@/components/ui/loading-box";
import { ErrorBox } from "@/components/ui/error-box";
import { useExternalLinkModalStore } from "@/stores/external-link-modal";
import { ExternalLinkModal } from "@/components/modals/external-link-modal";
import { CameraAccess } from "@/components/ui/camera-access";
import { LoadingBox } from "@/components/ui/loading-box";

export default function Scan() {
const navigate = useNavigate();
Expand All @@ -37,14 +37,10 @@ export default function Scan() {
const [statusMessage, setStatusMessage] = useState("");

const handleScan = async (value: string): Promise<void> => {
console.log("Scanning: ", value);

if (!accountId || !secretKey) {
toast({
title: "Error",
description: "Account information is missing.",
status: "error",
duration: 5000,
isClosable: true,
});
console.log("Missing credentials");
return;
}

Expand Down Expand Up @@ -127,6 +123,8 @@ export default function Scan() {
eventHelperInstance.debugLog(`Scan failed: ${error}`, "error");
setScanStatus("error");
setStatusMessage(`Error scanning QR code: ${error.message || error}`);
} finally {
console.log("Scanning complete");
}
};

Expand All @@ -152,6 +150,10 @@ export default function Scan() {
}
}, [scanStatus, statusMessage, toast]);

if (isLoading) {
return <LoadingBox />;
}

return (
<Box p={4} display={"flex"} flexDirection={"column"} gap={4}>
<PageHeading title="Scan" />
Expand All @@ -171,7 +173,6 @@ export default function Scan() {
transform="translateY(-50%)"
zIndex={-1}
/>
{isLoading && <LoadingBox />}
{isError && <ErrorBox message={`Error: ${error?.message}`} />}
<Box display={"flex"} justifyContent={"center"} alignItems="center">
<QrScanner
Expand Down

0 comments on commit e04efc8

Please sign in to comment.