import { useId, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { ImagePlus } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { cn } from '@/lib/utils'; import { validateUpload } from '../lib/validateUpload'; import type { PhotoItem } from './PhotoSelectionList'; interface ImagePickerProps { /** The photos of the library to choose from, newest first. */ items: readonly PhotoItem[]; /** The id of the chosen photo, or null. */ value: string | null; onChange: (id: string) => void; /** * Uploads one file and answers with the photo as the library lists it. The module decides how (the hero uses its own * upload and background processing); the picker only shows the state and chooses the result. Without it there is no * upload button. */ onUpload?: (file: File) => Promise; /** The largest file the host accepts, in bytes. */ maxUploadBytes: number; /** A short line about formats and limits, shown under the buttons. */ limitsText?: string; /** Accessible name of the group (what the image is for, for example "Image of slide 2"). */ label: string; } /** * "Choose an image or upload one": the photos of the library as a group of radio buttons (arrow keys move and choose) * and an upload button that adds the new photo to the library and chooses it at once. One component for every module that * needs an image. It holds no data of its own and calls nothing by itself: the module passes the list and the upload. */ export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes, limitsText, label }: ImagePickerProps) { const { t } = useTranslation(); const groupName = useId(); const fileInput = useRef(null); const [uploading, setUploading] = useState(false); const [problem, setProblem] = useState(null); const upload = async (file: File | undefined) => { if (!file || !onUpload || uploading) return; const refused = validateUpload(file, maxUploadBytes); if (refused) { setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage')); return; } setProblem(null); setUploading(true); try { const photo = await onUpload(file); onChange(photo.id); } catch { setProblem(t('media.picker.failed')); } finally { setUploading(false); if (fileInput.current) fileInput.current.value = ''; } }; return (
{onUpload && (
void upload(event.target.files?.[0])} /> {limitsText &&

{limitsText}

}
)} {problem && (

{problem}

)} {items.length === 0 ? (

{t('media.picker.empty')}

) : (
{items.map((item) => ( ))}
)}
); }