import { useState, useRef, useCallback, useEffect } from 'react' import Button from '@/components/ui/Button' import Card from '@/components/ui/Card' interface RetrieveFormProps { onSubmit: (key: string) => void loading?: boolean error?: string } export default function RetrieveForm({ onSubmit, loading = false, error, }: RetrieveFormProps) { const [keyInput, setKeyInput] = useState('') const [scanning, setScanning] = useState(false) const [cameraError, setCameraError] = useState(null) const scannerRef = useRef(null) const html5QrRef = useRef(null) const inputRef = useRef(null) // The real access key (crypto.ts's generateKey()) is 28 case-sensitive // base64url characters — which legitimately include '-' and '_' as content, // not just as group separators — grouped 7-7-7-7. Because '-' is ambiguous // between "separator" and "real key character", there is no safe way to // reformat/reconstruct it: any uppercase/strip/regroup pass corrupts real // keys. So the input is passed through completely unmodified (matching // nurse/Retrieve.tsx's working `key.trim()` pattern) — never transformed. const isComplete = keyInput.trim().length > 0 const handleKeyChange = useCallback( (e: React.ChangeEvent) => { setKeyInput(e.target.value) }, [], ) const handleSubmit = useCallback( (e: React.FormEvent) => { e.preventDefault() if (isComplete && !loading) { onSubmit(keyInput.trim()) } }, [isComplete, loading, keyInput, onSubmit], ) // Submit when a QR code provides a key const handleQrResult = useCallback( (decodedText: string) => { const trimmed = decodedText.trim() setKeyInput(trimmed) // Stop scanner after successful scan stopScanner() if (trimmed) { onSubmit(trimmed) } }, // eslint-disable-next-line react-hooks/exhaustive-deps [onSubmit], ) const stopScanner = useCallback(async () => { if (html5QrRef.current) { try { const state = html5QrRef.current.getState() // Only stop if scanning (state 2 = SCANNING) if (state === 2) { await html5QrRef.current.stop() } } catch { // Ignore errors during cleanup } html5QrRef.current = null } setScanning(false) }, []) const startScanner = useCallback(async () => { setCameraError(null) // Dynamically import html5-qrcode to keep initial bundle small try { const { Html5Qrcode } = await import('html5-qrcode') const scannerId = 'qr-scanner-region' // Ensure any previous instance is cleaned up if (html5QrRef.current) { await stopScanner() } const scanner = new Html5Qrcode(scannerId) html5QrRef.current = scanner setScanning(true) await scanner.start( { facingMode: 'environment' }, { fps: 10, qrbox: { width: 250, height: 250 }, }, (decodedText) => { handleQrResult(decodedText) }, () => { // QR code not detected in this frame — no action needed }, ) } catch (err) { setScanning(false) if (err instanceof Error) { if ( err.name === 'NotAllowedError' || err.message.includes('Permission') ) { setCameraError('相機權限被拒絕,請在瀏覽器設定中允許使用相機') } else if ( err.name === 'NotFoundError' || err.message.includes('Requested device not found') ) { setCameraError('找不到相機裝置') } else { setCameraError(`無法啟動相機:${err.message}`) } } else { setCameraError('無法啟動相機,請確認裝置支援') } } }, [handleQrResult, stopScanner]) // Cleanup scanner on unmount useEffect(() => { return () => { if (html5QrRef.current) { try { const state = html5QrRef.current.getState() if (state === 2) { html5QrRef.current.stop() } } catch { // Ignore } } } }, []) return ( {/* Header */}

查詢紀錄

請輸入金鑰或掃描 QR Code 以查閱您的紀錄

{/* Key input */}
{/* Error message */} {error && (

{error}

)} {/* Divider */}
或
{/* QR Scanner button */}
{!scanning ? ( ) : ( )}
{/* Camera preview area */}
{/* Camera error */} {cameraError && (

{cameraError}

)} {/* Submit button */} ) }