"use client"; // Image association control used by media, music, categories, etc. // Lets the user either (a) pick an existing image from the /images library // (sets `image_id`) or (b) upload a new image file (sets `image` File). Shows a // live thumbnail of the current choice. import { useEffect, useMemo, useState } from "react"; import { useList } from "@/lib/useResource"; import { pickUrl, IMAGE_KEYS } from "@/lib/media"; import { Button, Modal, Spinner, EmptyState } from "./ui"; import { ImageIcon, CloseIcon } from "./icons"; interface LibImage { id: number; title?: string | null; } export function ImagePicker({ imageId, onPickId, file, onPickFile, existingUrl, }: { imageId: number | null; onPickId: (id: number | null) => void; file: File | null; onPickFile: (f: File | null) => void; // URL of the already-saved image (edit mode) when no new choice is made. existingUrl?: string | null; }) { const [libOpen, setLibOpen] = useState(false); const { data: images, loading } = useList( libOpen ? "/images/all" : null, ); // Object URL preview for a freshly uploaded file. const [filePreview, setFilePreview] = useState(null); useEffect(() => { if (!file) { setFilePreview(null); return; } const url = URL.createObjectURL(file); setFilePreview(url); return () => URL.revokeObjectURL(url); }, [file]); // Resolve the thumbnail for the currently chosen library image (if loaded). const pickedLibUrl = useMemo(() => { if (!imageId || !images.length) return null; const found = images.find((i) => i.id === imageId); return found ? pickUrl(found, IMAGE_KEYS) : null; }, [imageId, images]); const preview = filePreview ?? pickedLibUrl ?? existingUrl ?? null; function clearAll() { onPickId(null); onPickFile(null); } return (
{preview ? ( // eslint-disable-next-line @next/next/no-img-element ) : ( )}
{(preview || imageId || file) && ( )}
setLibOpen(false)} title="انتخاب تصویر از کتابخانه" > {loading ? (
) : !images.length ? ( ) : (
{images.map((img) => { const url = pickUrl(img, IMAGE_KEYS); const selected = img.id === imageId; return ( ); })}
)}
); }