import { useCallback, useState } from "react"; import { useRouter } from "next/router"; // react-dropzone import { useDropzone } from "react-dropzone"; // services import fileService from "services/file.service"; // hooks import useToast from "hooks/use-toast"; // icons import { getFileIcon } from "components/icons"; // helpers import { getFileExtension, getFileName } from "helpers/attachment.helper"; // types import { Props } from "./types"; import useWorkspaceDetails from "hooks/use-workspace-details"; const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB export const CustomFileAttribute: React.FC = (props) => { const { attributeDetails, onChange, value } = props; const [isUploading, setIsUploading] = useState(false); const router = useRouter(); const { workspaceSlug } = router.query; const { workspaceDetails } = useWorkspaceDetails(); const { setToastAlert } = useToast(); const onDrop = useCallback( (acceptedFiles: File[]) => { if (!acceptedFiles[0] || !workspaceSlug) return; const extension = getFileExtension(acceptedFiles[0].name); if (!attributeDetails.extra_settings?.file_formats?.includes(`.${extension}`)) { setToastAlert({ type: "error", title: "Error!", message: `File format not accepted. Accepted file formats- ${attributeDetails.extra_settings?.file_formats?.join( ", " )}`, }); return; } const formData = new FormData(); formData.append("asset", acceptedFiles[0]); formData.append( "attributes", JSON.stringify({ name: acceptedFiles[0].name, size: acceptedFiles[0].size, }) ); setIsUploading(true); fileService .uploadFile(workspaceSlug.toString(), formData) .then((res) => { const imageUrl = res.asset; onChange(imageUrl); if (value && value !== "" && workspaceDetails) fileService.deleteFile(workspaceDetails.id, value); }) .finally(() => setIsUploading(false)); }, [ attributeDetails.extra_settings?.file_formats, onChange, setToastAlert, value, workspaceDetails, workspaceSlug, ] ); const { getRootProps, getInputProps, isDragActive, isDragReject, fileRejections } = useDropzone({ onDrop, maxSize: MAX_FILE_SIZE, multiple: false, disabled: isUploading, }); const fileError = fileRejections.length > 0 ? `Invalid file type or size (max ${MAX_FILE_SIZE / 1024 / 1024} MB)` : null; return (
{value && value !== "" && ( {getFileIcon(getFileExtension(value))} {getFileName(value)} )}
{isDragActive ? (

Drop here...

) : fileError ? (

{fileError}

) : isUploading ? (

Uploading...

) : (

Upload {value && value !== "" ? "new " : ""}file

)}
); };