import { detectFileType } from "@/server/lib/detect-type-of-file"; import { Flex, Image, Loader, Modal } from "@mantine/core"; import { useEffect, useState } from "react"; import notification from "./notificationGlobal"; export default function ModalFile({ open, onClose, folder, fileName, }: { open: boolean; onClose: () => void; folder: string; fileName: string; }) { const [viewFile, setViewFile] = useState(""); const [loading, setLoading] = useState(false); const [typeFile, setTypeFile] = useState(""); const [error, setError] = useState(false); useEffect(() => { if (open && fileName) { loadImage(); } }, [open, fileName]); const loadImage = async () => { try { setViewFile(""); setLoading(true); // detect type of file const { ext, type } = detectFileType(fileName); setTypeFile(type || ""); // load file const urlApi = "/api/pengaduan/image?folder=" + folder + "&fileName=" + fileName; const res = await fetch(urlApi); if (!res.ok) { setError(true); return notification({ title: "Error", message: "Failed to load image", type: "error", }); } const blob = await res.blob(); const url = URL.createObjectURL(blob); setViewFile(url); } catch (err) { setError(true); notification({ title: "Error", message: "Failed to load image", type: "error", }); } finally { setLoading(false); } }; useEffect(() => { if (error) { onClose(); } }, [error]); return ( {loading && ( )} {viewFile && ( <> {typeFile == "pdf" ? ( ) : ( )} )} ); }