The camera stopped after decoding one code (by design, one scan at a time) but was only ever started on mount, so it stayed dead until staff navigated away and back. The parent now owns the lifecycle via a paused prop: Scan pauses while busy or any sheet is open (camera re-arms when the sheet closes), Login pauses while busy (re-arms after a failed scan). scannedRef guards duplicate callbacks between decode and stop.
198 lines
7.0 KiB
TypeScript
198 lines
7.0 KiB
TypeScript
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
|
import { QRCodeSVG } from 'qrcode.react';
|
|
import { Html5Qrcode } from 'html5-qrcode';
|
|
|
|
const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777'];
|
|
|
|
export function initials(name: string): string {
|
|
return name.split(' ').map((w) => w[0]).slice(0, 2).join('').toUpperCase();
|
|
}
|
|
|
|
export function avColor(seed: string): string {
|
|
let h = 0;
|
|
for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
|
return AV_COLORS[h % AV_COLORS.length];
|
|
}
|
|
|
|
export function Avatar({ name, id, size = 44, fs = 15 }: { name: string; id: string; size?: number; fs?: number }) {
|
|
return (
|
|
<span className="avatar" style={{ width: size, height: size, fontSize: fs, background: avColor(id) }}>
|
|
{initials(name)}
|
|
</span>
|
|
);
|
|
}
|
|
|
|
export function Spinner() {
|
|
return <span className="spinner" />;
|
|
}
|
|
|
|
export function Empty({ icon, text }: { icon: string; text: string }) {
|
|
return (
|
|
<div className="empty">
|
|
<div className="big">{icon}</div>
|
|
{text}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** Bottom-sheet modal. */
|
|
export function Sheet({ open, onClose, children }: { open: boolean; onClose: () => void; children: ReactNode }) {
|
|
if (!open) return null;
|
|
return (
|
|
<div className="backdrop" onClick={(e) => e.target === e.currentTarget && onClose()}>
|
|
<div className="sheet">
|
|
<div className="grab" />
|
|
{children}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** A small on/off switch with a label. */
|
|
export function Toggle({
|
|
checked,
|
|
onChange,
|
|
label,
|
|
testId,
|
|
}: {
|
|
checked: boolean;
|
|
onChange: (v: boolean) => void;
|
|
label: string;
|
|
testId?: string;
|
|
}) {
|
|
return (
|
|
<label className="toggle">
|
|
<input type="checkbox" data-testid={testId} checked={checked} onChange={(e) => onChange(e.target.checked)} />
|
|
<span className="track">
|
|
<span className="knob" />
|
|
</span>
|
|
<span className="toggle-lbl">{label}</span>
|
|
</label>
|
|
);
|
|
}
|
|
|
|
/** Render a string (e.g. a QR token) as a scannable QR code. */
|
|
export function QrImage({ value, size = 180 }: { value: string; size?: number }) {
|
|
return (
|
|
<div className="qr-frame">
|
|
<QRCodeSVG value={value} size={size} level="M" marginSize={0} />
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Camera QR scanner with a manual-entry fallback. Calls onResult with the
|
|
* decoded text. The camera only works on a secure context (https or localhost);
|
|
* the manual field always works.
|
|
*/
|
|
export function Scanner({ onResult, label = 'Scan a lanyard QR', entryLabel = 'QR code', placeholder = '…or type the code (e.g. CVV-XXX-NNNN)', submitLabel = 'Go', disabled = false, submitDisabled = false, onEntryChange, paused = false }: { onResult: (text: string) => void; label?: string; entryLabel?: string; placeholder?: string; submitLabel?: string; disabled?: boolean; submitDisabled?: boolean; onEntryChange?: (text: string) => void; paused?: boolean }) {
|
|
const [manual, setManual] = useState('');
|
|
const [camError, setCamError] = useState<string | null>(null);
|
|
const scannerRef = useRef<Html5Qrcode | null>(null);
|
|
const [camOn, setCamOn] = useState(false);
|
|
// The camera runs only while `paused` is false. The parent sets `paused`
|
|
// while it is busy or a result sheet is open, so a scan stops the camera
|
|
// (one code at a time) and closing the sheet restarts it automatically —
|
|
// no need to navigate away to re-arm it.
|
|
// The camera callback below is registered once per start; without a ref it
|
|
// would keep calling the FIRST render's onResult, whose closures over
|
|
// parent state (welcome mode, selected session) are stale. Always invoke
|
|
// the latest handler through this ref.
|
|
const onResultRef = useRef(onResult);
|
|
onResultRef.current = onResult;
|
|
// Guards against the callback firing again for the same lanyard in the
|
|
// frames between the decode and the camera actually stopping.
|
|
const scannedRef = useRef(false);
|
|
|
|
useEffect(() => {
|
|
if (paused) return;
|
|
let cancelled = false;
|
|
const el = document.getElementById('qr-reader');
|
|
if (!el) return;
|
|
|
|
// Camera requires a secure context + a real device. Fall back to manual
|
|
// entry (always available) when it's not usable.
|
|
const hasCamera =
|
|
typeof navigator !== 'undefined' &&
|
|
!!navigator.mediaDevices &&
|
|
typeof navigator.mediaDevices.getUserMedia === 'function';
|
|
if (!hasCamera) {
|
|
setCamError('Camera unavailable — type the code below');
|
|
return;
|
|
}
|
|
|
|
let scanner: Html5Qrcode | null = null;
|
|
scannedRef.current = false;
|
|
try {
|
|
scanner = new Html5Qrcode('qr-reader');
|
|
scannerRef.current = scanner;
|
|
scanner
|
|
.start(
|
|
{ facingMode: 'environment' },
|
|
{ fps: 10, qrbox: { width: 220, height: 220 } },
|
|
(text) => {
|
|
if (cancelled || scannedRef.current) return;
|
|
scannedRef.current = true;
|
|
setCamOn(false);
|
|
// One code at a time: stop the camera now; the parent's `paused`
|
|
// (busy / sheet open) keeps it off, and clearing it restarts it.
|
|
scanner?.stop().catch(() => {});
|
|
onResultRef.current(text);
|
|
},
|
|
() => {},
|
|
)
|
|
.then(() => {
|
|
if (!cancelled) setCamOn(true);
|
|
})
|
|
.catch((err) => {
|
|
if (!cancelled) setCamError(typeof err === 'string' ? err : 'Camera unavailable');
|
|
});
|
|
} catch {
|
|
if (!cancelled) setCamError('Camera unavailable — type the code below');
|
|
}
|
|
|
|
return () => {
|
|
cancelled = true;
|
|
try {
|
|
scanner?.stop().catch(() => {});
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
};
|
|
}, [paused]);
|
|
|
|
return (
|
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
|
<div className="viewfinder">
|
|
<span className="vf-corner tl" />
|
|
<span className="vf-corner tr" />
|
|
<span className="vf-corner bl" />
|
|
<span className="vf-corner br" />
|
|
<div id="qr-reader" style={{ position: 'absolute', inset: 0 }} />
|
|
{!camOn && !camError && <div className="vf-line" />}
|
|
{camError && (
|
|
<div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#cbb', fontSize: 13, padding: 20, textAlign: 'center' }}>
|
|
{label}
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="row" style={{ gap: 8 }}>
|
|
<input
|
|
className="input mono"
|
|
type="text"
|
|
data-testid="scanner-manual-code"
|
|
aria-label={entryLabel}
|
|
placeholder={placeholder}
|
|
disabled={disabled}
|
|
value={manual}
|
|
onChange={(e) => { setManual(e.target.value); onEntryChange?.(e.target.value); }}
|
|
onKeyDown={(e) => { if (e.key === 'Enter' && manual.trim() && !disabled && !submitDisabled) onResult(manual.trim()); }}
|
|
/>
|
|
<button className="btn primary small" data-testid="scanner-manual-go" disabled={disabled || submitDisabled || !manual.trim()} onClick={() => onResult(manual.trim())}>
|
|
{submitLabel}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|