Files
crosscode-platform/apps/events/frontend/src/hooks/useQRScanner.ts
T
joshuaandClaude Opus 5.5 9e8244bb71 Fix frontend lint: links, unused code, quotes, img elements
- Internal links use next/link instead of <a> (no full page reload).
- Remove dead code: RegisterForm's unreachable Yoco checkout branch, the
  unused AttendeeForms on the registration success page, unused Geist
  fonts, and assorted unused variables and catch bindings.
- Escape quotes in JSX text; replace @ts-ignore in apiFetch with a cast.
- Keep the intentional raw <img> elements (data URLs, runtime API host)
  with a documented lint exception; the event editor uses ApiImage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:10:00 +02:00

79 lines
2.4 KiB
TypeScript

"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { BrowserQRCodeReader } from "@zxing/browser";
export type UseQRScannerOptions = {
onResult?: (text: string) => void;
onError?: (error: unknown) => void;
};
// Hook to decode QR codes from a HTMLVideoElement using @zxing/browser
export function useQRScanner(videoEl: HTMLVideoElement | null, opts: UseQRScannerOptions = {}) {
const { onResult, onError } = opts;
const [active, setActive] = useState(false);
const [permissionError, setPermissionError] = useState<string | null>(null);
const readerRef = useRef<BrowserQRCodeReader | null>(null);
const cancelRef = useRef<(() => void) | undefined>(undefined);
const stop = useCallback(() => {
cancelRef.current?.();
cancelRef.current = undefined;
}, []);
const toggle = useCallback(() => setActive((p) => !p), []);
useEffect(() => {
readerRef.current = new BrowserQRCodeReader();
return () => {
stop();
readerRef.current = null;
};
}, [stop]);
useEffect(() => {
let cancelled = false;
async function run() {
setPermissionError(null);
try {
// Start decode loop
const reader = readerRef.current!;
const scan = async () => {
if (cancelled) return;
try {
if (!videoEl) return;
const result = await reader.decodeOnceFromVideoElement(videoEl);
const text = (result as any)?.getText ? (result as any).getText() : (result as any)?.text ?? String(result ?? "");
if (text) onResult?.(text);
} catch {
// Ignore transient decode errors and retry
} finally {
if (!cancelled && active) setTimeout(scan, 200);
}
};
scan();
cancelRef.current = () => {
cancelled = true;
};
} catch (err: any) {
if (err?.name === "NotAllowedError") {
setPermissionError("Camera permission denied. Please enable camera access.");
} else if (err?.name === "NotFoundError") {
setPermissionError("No suitable camera found. Try a device with a back camera.");
} else {
setPermissionError("Unable to access camera.");
}
onError?.(err);
setActive(false);
}
}
if (active && videoEl) run();
else stop();
}, [active, onError, onResult, stop, videoEl]);
return { active, toggle, stop, permissionError };
}