Files
MattrixwvReactComponents/lib/component/input/file/DragAndDropFileInput.tsx

110 lines
3.0 KiB
TypeScript

import { DangerButton } from "$/component/button";
import type { FileInputProps } from "$/types/InputTypes";
import { humanReadableBytes } from "$/util/FileUtil";
import clsx from "clsx";
import { useRef, useState } from "react";
import { MdClose } from "react-icons/md";
export default function DragAndDropFileInput({
id,
className,
name,
ariaLabel,
minSize,
maxSize,
showFileName = true,
showSize = true,
onChange,
disabled,
children
}: Readonly<FileInputProps>){
const [ file, setFile ] = useState<File>();
const inputRef = useRef<HTMLInputElement>(null);
return (
<label
className={clsx(
"flex flex-col items-center justify-center border-2 rounded-lg cursor-pointer",
"data-drag:border-primary data-drag:text-primary",
className
)}
onDragOver={(e) => { e.preventDefault(); e.currentTarget.dataset.drag = "true"; }}
onDragLeave={(e) => { e.preventDefault(); delete e.currentTarget.dataset.drag; }}
onDrop={(e) => {
e.preventDefault();
delete e.currentTarget.dataset.drag;
const currentFile = e.dataTransfer.files[0];
setFile(currentFile);
if ((minSize && currentFile.size < minSize) || (maxSize && currentFile.size > maxSize)) return;
onChange?.(currentFile);
if(inputRef.current){ inputRef.current.files = e.dataTransfer.files; }
}}
aria-label={ariaLabel}
>
<input
ref={inputRef}
type="file"
id={id}
className="sr-only"
name={name}
onChange={(e) => {
const currentFile = e.target.files?.[0];
setFile(currentFile);
if ((minSize && currentFile && currentFile.size < minSize) || (maxSize && currentFile && currentFile.size > maxSize)) return;
onChange?.(currentFile);
}}
disabled={disabled}
/>
<div
className="flex flex-col items-center justify-between px-2"
>
<div className="flex flex-row items-center justify-center">
{children}
</div>
<div
className="flex flex-row items-center justify-between gap-x-2 w-full"
>
{
showFileName &&
<div className="flex flex-row items-center justify-center gap-x-2">
{file?.name}
</div>
}
{
file &&
<DangerButton
className="mr-4"
shape="square"
variant="icon"
onClick={(e) => { e.preventDefault(); setFile(undefined); onChange?.(undefined); }}
>
<MdClose size={22} className="fill-danger"/>
</DangerButton>
}
{
showSize &&
<div
className={clsx(
{
"text-red-600": minSize && file?.size && file?.size < minSize,
"text-red-600 ": maxSize && file?.size && file?.size > maxSize,
"text-green-600": minSize && !maxSize && file?.size && file?.size > minSize,
"text-green-600 ": !minSize && maxSize && file?.size && file?.size < maxSize,
" text-green-600": minSize && maxSize && file?.size && file?.size > minSize && file?.size < maxSize
}
)}
>
{humanReadableBytes(file?.size ?? 0)}
</div>
}
</div>
</div>
</label>
);
}