import { useApp } from "../../../hooks"; import clsx from "clsx"; import { ReactNode, useEffect, useState } from "react"; import { FileBase64 } from "../../../application/dtos/shared/FileBase64"; interface Props { name?: string; title?: string; accept?: string; multiple?: boolean; description?: string; icon?: ReactNode; disabled?: boolean; className?: string; uploadText?: string; autoFocus?: boolean; onDropped?: (base64: string, file: File) => void; onDroppedFiles?: (fileBase64: FileBase64[], files: any[]) => void; } export default function UploadDocuments({ name = "uploadmyfile", className, title = "", accept, multiple, description, icon = "", disabled, onDropped, onDroppedFiles, uploadText, autoFocus, }: Props) { const { t } = useApp(); const [isDragging, setIsDragging] = useState(false); const [loading] = useState(false); const [customClasses, setCustomClasses] = useState(""); function dragOver(e: any) { e.preventDefault(); if (!loading) { setIsDragging(true); } } function dragLeave() { setIsDragging(false); } // async function compressFile(imageFile: File): Promise { // const options = { // maxSizeMB: 0.5, // maxWidthOrHeight: 1920 / 2, // useWebWorker: true, // }; // try { // return await imageCompression(imageFile, options); // } catch (error) { // return await Promise.reject(error); // } // } // async function compressFileNotImage(imageFile: File): Promise { // return Promise.resolve(imageFile); // } function drop(e: any) { try { e.preventDefault(); } catch { // ignore } //@ts-ignore const files: File[] = await Promise.all( [...e.dataTransfer.files].map(async (element: File) => { return element; // if (element.type.includes("image")) { // return await compressFile(element); // } else { // return await compressFileNotImage(element); // } }) ); const filesArray: FileBase64[] = []; Promise.all( files.map(async (file) => { const base64 = await getBase64(file); filesArray.push({ base64, file, }); if (onDropped) { onDropped(base64, file); } }) ); if (onDroppedFiles) { onDroppedFiles(filesArray, files); } setIsDragging(false); } function requestUploadFile() { const src = document.querySelector("#" + name); drop({ dataTransfer: src }); } function getBase64(file: File): Promise { const reader = new FileReader(); return new Promise((resolve) => { reader.onload = (ev) => { resolve(ev?.target?.result?.toString() ?? ""); }; reader.readAsDataURL(file); }); } useEffect(() => { setCustomClasses(isDragging && !loading && !disabled ? "bg-theme-200 border-2 border-dashed border-theme-800" : ""); }, [isDragging, loading, disabled]); return (
{(() => { if (loading) { return
{t("shared.loading")}...
; } else { return (

{title}

{icon}

{t("shared.or")} {t("shared.dragAndDrop")}

{description}

); } })()}
); }