import ActivityIndicator from "@/components/indicators/activity-indicator"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormMessage, } from "@/components/ui/form"; import { cn } from "@/lib/utils"; import { convertHeicToJpeg, HEIC_EXTENSIONS, isHeicFile, } from "@/utils/heicUtil"; import { zodResolver } from "@hookform/resolvers/zod"; import { useCallback, useEffect, useRef, useState } from "react"; import { useDropzone } from "react-dropzone"; import { useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { LuUpload, LuX } from "react-icons/lu"; import { z } from "zod"; type ImageEntryProps = { onSave: (file: File) => void; children?: React.ReactNode; maxSize?: number; accept?: Record; }; export default function ImageEntry({ onSave, children, maxSize = 20 * 1024 * 1024, // 20MB default accept = { "image/*": [".jpeg", ".jpg", ".png", ".gif", ".webp", ...HEIC_EXTENSIONS], }, }: ImageEntryProps) { const { t } = useTranslation(["views/faceLibrary"]); const [preview, setPreview] = useState(null); const [converting, setConverting] = useState(false); const dropzoneRef = useRef(null); // Bumped on every selection and clear, so a HEIC conversion that finishes // after the selection changed is discarded instead of applied const selectionId = useRef(0); // Discard conversions that finish after the component unmounts useEffect(() => { const id = selectionId; return () => { id.current += 1; }; }, []); // Auto focus the dropzone useEffect(() => { if (dropzoneRef.current && !preview) { dropzoneRef.current.focus(); } }, [preview]); // Clean up preview URL on unmount or preview change useEffect(() => { return () => { if (preview) { URL.revokeObjectURL(preview); } }; }, [preview]); const formSchema = z.object({ file: z .instanceof(File, { message: t("imageEntry.validation.selectImage") }) .refine((file) => accept["image/*"].includes(`.${file.type.split("/")[1]}`), ), }); const form = useForm>({ resolver: zodResolver(formSchema), }); const selectFile = useCallback( async (file: File) => { const id = ++selectionId.current; let selected = file; if (isHeicFile(file)) { setConverting(true); const converted = await convertHeicToJpeg(file).catch(() => null); // the selection was cleared or replaced while converting if (id !== selectionId.current) { return; } setConverting(false); if (!converted) { form.setError("file", { message: t("imageEntry.validation.heicConversionFailed"), }); return; } selected = converted; } form.setValue("file", selected, { shouldValidate: true }); // Create preview const objectUrl = URL.createObjectURL(selected); setPreview(objectUrl); }, [form, t], ); const onDrop = useCallback( (acceptedFiles: File[]) => { if (acceptedFiles.length > 0) { selectFile(acceptedFiles[0]); } }, [selectFile], ); const { getRootProps, getInputProps, isDragActive, isDragReject } = useDropzone({ onDrop, maxSize, accept, multiple: false, disabled: converting, }); const handlePaste = useCallback( (event: React.ClipboardEvent) => { event.preventDefault(); if (converting) { return; } const clipboardItems = Array.from(event.clipboardData.items); for (const item of clipboardItems) { if (item.type.startsWith("image/")) { const blob = item.getAsFile(); if (blob && blob.size <= maxSize) { const mimeType = blob.type.split("/")[1]; const extension = `.${mimeType}`; if (accept["image/*"].includes(extension)) { const fileName = blob.name || `pasted-image.${mimeType}`; const file = new File([blob], fileName, { type: blob.type }); selectFile(file); return; // Take the first valid image } } } } }, [converting, maxSize, accept, selectFile], ); const onSubmit = useCallback( (data: z.infer) => { // the form still holds the previous image until a replacement // finishes converting, so saving now would upload the wrong one if (!data.file || converting) return; onSave(data.file); }, [converting, onSave], ); const clearSelection = () => { // drop any running conversion so it can't restore the selection selectionId.current += 1; setConverting(false); form.reset(); setPreview(null); }; return (
(
{!preview ? (
{converting ? ( <>

{t("imageEntry.converting")}

) : ( <>

{isDragActive ? t("imageEntry.dropActive") : t("imageEntry.dropInstructions")}

{t("imageEntry.maxSize", { size: Math.round(maxSize / (1024 * 1024)), })}

)}
) : (
Preview {converting && (

{t("imageEntry.converting")}

)}
)}
)} />
{children}
); }