import { MAX_SEARCH_IMAGE_BASE64_LENGTH } from '@shumai/dtos' import { ImagePlus, Loader2 } from 'lucide-react' import { useEffect, useRef, useState } from 'react' import { ulid } from 'ulid' import { Button } from '@/ui/components/ui/button' import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from '@/ui/components/ui/dialog' import { m } from '@/ui/paraglide/messages.js' export interface SearchImage { id: string name: string base64: string } async function resizeImage(file: File): Promise { if (file.type && !file.type.startsWith('image/')) throw new Error('Invalid file type') const bitmap = await createImageBitmap(file) try { const landscape = bitmap.width >= bitmap.height const scale = Math.min( 1, (landscape ? 1280 : 720) / bitmap.width, (landscape ? 720 : 1280) / bitmap.height, ) const canvas = document.createElement('canvas') canvas.width = Math.max(1, Math.round(bitmap.width * scale)) canvas.height = Math.max(1, Math.round(bitmap.height * scale)) const context = canvas.getContext('2d') if (!context) throw new Error('Unable to resize image') context.fillStyle = '#fff' context.fillRect(0, 0, canvas.width, canvas.height) context.drawImage(bitmap, 0, 0, canvas.width, canvas.height) const dataUrl = canvas.toDataURL('image/jpeg', 0.85) const base64 = dataUrl.split(',')[1] if (!base64 || base64.length > MAX_SEARCH_IMAGE_BASE64_LENGTH) { throw new Error('Invalid resized image') } return { id: ulid(), name: file.name, base64 } } finally { bitmap.close() } } export function SearchImagePicker({ onSelect }: { onSelect: (image: SearchImage) => void }) { const [open, setOpen] = useState(false) const [error, setError] = useState(false) const [processing, setProcessing] = useState(false) const input = useRef(null) const pending = useRef(null) useEffect(() => () => pending.current?.abort(), []) function setPickerOpen(next: boolean) { if (!next) { pending.current?.abort() pending.current = null setError(false) setProcessing(false) } setOpen(next) } async function selectFile(file: File) { if (pending.current) return const controller = new AbortController() pending.current = controller setError(false) setProcessing(true) try { const image = await resizeImage(file) if (controller.signal.aborted) return onSelect(image) setPickerOpen(false) } catch { if (!controller.signal.aborted) setError(true) } finally { if (pending.current === controller) { pending.current = null setProcessing(false) } } } return ( { event.stopPropagation() const image = Array.from(event.clipboardData.files).find((file) => file.type.startsWith('image/'), ) if (!image) return event.preventDefault() void selectFile(image) }} > {m.image_search_attach()} {m.image_search_select_description()} { const file = event.currentTarget.files?.[0] event.currentTarget.value = '' if (file) void selectFile(file) }} /> {error && (

{m.image_search_invalid_image()}

)}
) }