DONG-WEI-YANG
Claude Sonnet 5
chore(lint): add ESLint, fix mechanical violations, remove dead code
01fbb71
Raw History Blame Contribute Delete
11.4 kB
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<string | null>(null)
const scannerRef = useRef<HTMLDivElement>(null)
const html5QrRef = useRef<import('html5-qrcode').Html5Qrcode | null>(null)
const inputRef = useRef<HTMLInputElement>(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<HTMLInputElement>) => {
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 (
<Card padding="lg" className="mx-auto max-w-md">
{/* Header */}
<div className="mb-6 text-center">
<div className="mb-3 flex justify-center">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-indigo-100">
<svg
className="h-6 w-6 text-indigo-600"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M15.75 5.25a3 3 0 013 3m3 0a6 6 0 01-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1121.75 8.25z"
/>
</svg>
</div>
</div>
<h2 className="text-lg font-semibold text-slate-900">查詢紀錄</h2>
<p className="mt-1 text-sm text-slate-500">
請輸入金鑰或掃描 QR Code 以查閱您的紀錄
</p>
</div>
<form onSubmit={handleSubmit}>
{/* Key input */}
<div className="mb-4">
<label
htmlFor="key-input"
className="mb-1.5 block text-sm font-medium text-slate-700"
>
金鑰代碼
</label>
<input
ref={inputRef}
id="key-input"
type="text"
value={keyInput}
onChange={handleKeyChange}
placeholder="XXXXXXX-XXXXXXX-XXXXXXX-XXXXXXX"
autoComplete="off"
spellCheck={false}
disabled={loading}
className={[
'block w-full rounded-lg border bg-white px-3 py-3 text-center font-mono text-lg tracking-wider text-slate-900 placeholder-slate-300 shadow-sm transition-colors duration-150',
'focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500',
'disabled:bg-slate-50 disabled:text-slate-500 disabled:cursor-not-allowed',
error
? 'border-red-400 focus:ring-red-500 focus:border-red-500'
: 'border-slate-300',
].join(' ')}
aria-invalid={error ? true : undefined}
aria-describedby={error ? 'key-error' : undefined}
/>
</div>
{/* Error message */}
{error && (
<div
id="key-error"
className="mb-4 flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3"
>
<svg
className="h-5 w-5 shrink-0 text-red-500"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
/>
</svg>
<p className="text-sm font-medium text-red-700">{error}</p>
</div>
)}
{/* Divider */}
<div className="mb-4 flex items-center gap-3">
<div className="h-px flex-1 bg-slate-200" />
<span className="text-xs text-slate-400">或</span>
<div className="h-px flex-1 bg-slate-200" />
</div>
{/* QR Scanner button */}
<div className="mb-4">
{!scanning ? (
<Button
type="button"
variant="outline"
size="md"
className="w-full"
onClick={startScanner}
disabled={loading}
>
<svg
className="mr-2 h-4 w-4"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M3.75 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 013.75 9.375v-4.5zM3.75 14.625c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5a1.125 1.125 0 01-1.125-1.125v-4.5zM13.5 4.875c0-.621.504-1.125 1.125-1.125h4.5c.621 0 1.125.504 1.125 1.125v4.5c0 .621-.504 1.125-1.125 1.125h-4.5A1.125 1.125 0 0113.5 9.375v-4.5z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6.75 6.75h.75v.75h-.75v-.75zM6.75 16.5h.75v.75h-.75v-.75zM16.5 6.75h.75v.75h-.75v-.75zM13.5 13.5h.75v.75h-.75v-.75zM13.5 19.5h.75v.75h-.75v-.75zM19.5 13.5h.75v.75h-.75v-.75zM19.5 19.5h.75v.75h-.75v-.75zM16.5 16.5h.75v.75h-.75v-.75z"
/>
</svg>
掃描 QR Code
</Button>
) : (
<Button
type="button"
variant="danger"
size="md"
className="w-full"
onClick={stopScanner}
>
<svg
className="mr-2 h-4 w-4"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
關閉相機
</Button>
)}
</div>
{/* Camera preview area */}
<div
ref={scannerRef}
className={[
'mb-5 overflow-hidden rounded-lg border border-slate-200 bg-slate-900 transition-all duration-300',
scanning ? 'h-64' : 'h-0 border-0',
].join(' ')}
>
<div id="qr-scanner-region" className="h-full w-full" />
</div>
{/* Camera error */}
{cameraError && (
<div className="mb-4 flex items-center gap-2 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3">
<svg
className="h-5 w-5 shrink-0 text-amber-500"
fill="none"
viewBox="0 0 24 24"
strokeWidth={2}
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
/>
</svg>
<p className="text-sm text-amber-700">{cameraError}</p>
</div>
)}
{/* Submit button */}
<Button
type="submit"
variant="primary"
size="lg"
className="w-full"
disabled={!isComplete}
loading={loading}
>
{loading ? '查詢中...' : '查詢'}
</Button>
</form>
</Card>
)
}