DONG-WEI-YANG
Claude Opus 4.6 (1M context)
fix: comprehensive security hardening, iOS voice fallback, and UX resilience
94a07ff
Raw History Blame Contribute Delete
6.64 kB
// src/components/ImageUploadButton.tsx
// Upload a photo of a hand-drawn genogram/ecomap and OCR it via Gemini Vision
import { useState, useRef, useCallback } from 'react'
import { trpc } from '@/lib/trpc'
interface ImageUploadButtonProps {
type: 'genogram' | 'ecomap'
onResult: (data: unknown) => void
onError?: (error: string) => void
color?: string
}
const COLOR_MAP: Record<string, { bg: string; hover: string; disabled: string }> = {
indigo: { bg: 'bg-indigo-600', hover: 'hover:bg-indigo-700', disabled: 'disabled:bg-indigo-300' },
blue: { bg: 'bg-blue-600', hover: 'hover:bg-blue-700', disabled: 'disabled:bg-blue-300' },
amber: { bg: 'bg-amber-600', hover: 'hover:bg-amber-700', disabled: 'disabled:bg-amber-300' },
emerald: { bg: 'bg-emerald-600', hover: 'hover:bg-emerald-700', disabled: 'disabled:bg-emerald-300' },
purple: { bg: 'bg-purple-600', hover: 'hover:bg-purple-700', disabled: 'disabled:bg-purple-300' },
}
const DEFAULT_COLOR = COLOR_MAP.indigo
const ACCEPT = 'image/png,image/jpeg,image/webp'
function fileToBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => {
const result = reader.result as string
// Strip data URI prefix: "data:image/jpeg;base64,..."
const base64 = result.split(',')[1] || result
resolve(base64)
}
reader.onerror = reject
reader.readAsDataURL(file)
})
}
export default function ImageUploadButton({
type,
onResult,
onError,
color = 'indigo',
}: ImageUploadButtonProps) {
const [errorMsg, setErrorMsg] = useState<string | null>(null)
const [preview, setPreview] = useState<string | null>(null)
const inputRef = useRef<HTMLInputElement>(null)
const genogramMutation = trpc.ai.ocrGenogram.useMutation()
const ecomapMutation = trpc.ai.ocrEcomap.useMutation()
const isLoading = genogramMutation.isPending || ecomapMutation.isPending
const colors = COLOR_MAP[color] ?? DEFAULT_COLOR
const handleFile = useCallback(async (file: File) => {
// Validate file type
if (!file.type.match(/^image\/(png|jpeg|webp)$/)) {
const msg = '僅支援 PNG、JPEG、WebP 格式'
setErrorMsg(msg)
onError?.(msg)
return
}
// Validate file size (max 10MB)
if (file.size > 10 * 1024 * 1024) {
const msg = '圖片檔案過大(上限 10MB)'
setErrorMsg(msg)
onError?.(msg)
return
}
// Show preview
const previewUrl = URL.createObjectURL(file)
setPreview(previewUrl)
setErrorMsg(null)
try {
const imageBase64 = await fileToBase64(file)
const mimeType = (file.type || 'image/jpeg') as 'image/jpeg'
const mutation = type === 'genogram' ? genogramMutation : ecomapMutation
const result = await mutation.mutateAsync({ imageBase64, mimeType })
if (!result.ok) {
setErrorMsg(result.error ?? '圖片辨識失敗')
onError?.(result.error ?? '圖片辨識失敗')
return
}
onResult(result.data)
} catch (err) {
const msg = err instanceof Error ? err.message : '圖片辨識失敗'
setErrorMsg(msg)
onError?.(msg)
}
}, [type, genogramMutation, ecomapMutation, onResult, onError])
const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) handleFile(file)
// Reset input so same file can be re-selected
if (inputRef.current) inputRef.current.value = ''
}, [handleFile])
const handleClick = useCallback(() => {
inputRef.current?.click()
}, [])
const label = type === 'genogram' ? '家系圖' : '生態圖'
return (
<div className="space-y-2">
{/* Hidden file input */}
<input
ref={inputRef}
type="file"
accept={ACCEPT}
capture="environment"
onChange={handleChange}
className="hidden"
/>
{/* Upload button */}
<button
type="button"
disabled={isLoading}
onClick={handleClick}
className={[
'flex w-full items-center justify-center gap-2 rounded-lg px-4 py-3 text-sm font-semibold text-white shadow-sm transition-colors',
colors.bg, colors.hover, colors.disabled,
].join(' ')}
>
{isLoading ? (
<>
<svg className="h-4 w-4 animate-spin" viewBox="0 0 24 24" fill="none">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
{label}辨識中...
</>
) : (
<>
{/* Camera icon */}
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z" />
<path strokeLinecap="round" strokeLinejoin="round" d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0z" />
</svg>
上傳圖片辨識{label}
</>
)}
</button>
{/* Image preview */}
{preview && (
<div className="relative rounded-lg border border-slate-200 overflow-hidden">
<img
src={preview}
alt={`${label}圖片預覽`}
className="w-full max-h-48 object-contain bg-slate-50"
/>
{!isLoading && (
<button
type="button"
onClick={() => setPreview(null)}
className="absolute top-1 right-1 rounded-full bg-slate-800/60 p-1 text-white hover:bg-slate-800/80"
aria-label="移除圖片"
>
<svg className="h-3 w-3" 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>
)}
{/* Error message */}
{errorMsg && (
<div className="rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-700">
{errorMsg}
</div>
)}
</div>
)
}