import React, { useCallback, useState } from "react"; import NextImage from "next/image"; import { useRouter } from "next/router"; // react-dropzone import { useDropzone } from "react-dropzone"; // headless ui import { Transition, Dialog } from "@headlessui/react"; // services import fileServices from "services/file.service"; // ui import { PrimaryButton, SecondaryButton } from "components/ui"; // icons import { UserCircleIcon } from "components/icons"; type TImageUploadModalProps = { value?: string | null; onClose: () => void; isOpen: boolean; onSuccess: (url: string) => void; userImage?: boolean; }; export const ImageUploadModal: React.FC = ({ value, onSuccess, isOpen, onClose, userImage, }) => { const [image, setImage] = useState(null); const [isImageUploading, setIsImageUploading] = useState(false); const router = useRouter(); const { workspaceSlug } = router.query; const onDrop = useCallback((acceptedFiles: File[]) => { setImage(acceptedFiles[0]); }, []); const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop, }); const handleSubmit = async () => { setIsImageUploading(true); if (!image || !workspaceSlug) return; const formData = new FormData(); formData.append("asset", image); formData.append("attributes", JSON.stringify({})); if (userImage) { fileServices .uploadUserFile(formData) .then((res) => { const imageUrl = res.asset; onSuccess(imageUrl); setIsImageUploading(false); }) .catch((err) => { console.error(err); }); } else fileServices .uploadFile(workspaceSlug as string, formData) .then((res) => { const imageUrl = res.asset; onSuccess(imageUrl); setIsImageUploading(false); }) .catch((err) => { console.error(err); }); }; const handleClose = () => { onClose(); }; return (
Upload Image
{image !== null || (value && value !== "") ? ( <> ) : ( <> {isDragActive ? "Drop image here to upload" : "Drag & drop image here"} )}
Cancel {isImageUploading ? "Uploading..." : "Upload & Save"}
); };