110 lines
2.6 KiB
TypeScript
110 lines
2.6 KiB
TypeScript
import { DangerButton, SecondaryButton } from "$/component/button";
|
|
import type { FileInputProps } from "$/types/InputTypes";
|
|
import { humanReadableBytes } from "$/util/FileUtil";
|
|
import clsx from "clsx";
|
|
import { useRef, useState } from "react";
|
|
import { FaRegFolderOpen } from "react-icons/fa6";
|
|
import { MdClose } from "react-icons/md";
|
|
|
|
|
|
export default function FileInput({
|
|
id,
|
|
className,
|
|
name,
|
|
ariaLabel,
|
|
minSize,
|
|
maxSize,
|
|
showFileName = true,
|
|
showSize = true,
|
|
onChange,
|
|
disabled,
|
|
children
|
|
}: Readonly<FileInputProps>){
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
const [ file, setFile ] = useState<File>();
|
|
|
|
|
|
return (
|
|
<div
|
|
className={clsx(
|
|
"flex flex-row items-center justify-between border-2 rounded-lg",
|
|
className
|
|
)}
|
|
>
|
|
<input
|
|
ref={inputRef}
|
|
id={id}
|
|
type="file"
|
|
className="sr-only"
|
|
name={name}
|
|
aria-label={ariaLabel}
|
|
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-row items-center justify-between grow w-full px-2"
|
|
>
|
|
{
|
|
children && !showFileName &&
|
|
<div>{children}</div>
|
|
}
|
|
{
|
|
showFileName &&
|
|
<div>{file?.name}</div>
|
|
}
|
|
{
|
|
file &&
|
|
<DangerButton
|
|
shape="square"
|
|
variant="icon"
|
|
onClick={(e) => { e.preventDefault(); setFile(undefined); onChange?.(undefined); }}
|
|
>
|
|
<MdClose size={22} className="fill-danger"/>
|
|
</DangerButton>
|
|
}
|
|
{
|
|
!children && !showFileName &&
|
|
<> </>
|
|
}
|
|
{
|
|
showSize &&
|
|
<div
|
|
className={clsx(
|
|
"ml-4",
|
|
{
|
|
"text-danger": minSize && file?.size && file?.size < minSize,
|
|
"text-danger ": maxSize && file?.size && file?.size > maxSize,
|
|
"text-success": minSize && !maxSize && file?.size && file?.size > minSize,
|
|
"text-success ": !minSize && maxSize && file?.size && file?.size < maxSize,
|
|
" text-success": minSize && maxSize && file?.size && file?.size > minSize && file?.size < maxSize
|
|
}
|
|
)}
|
|
>
|
|
{humanReadableBytes(file?.size ?? 0)}
|
|
</div>
|
|
}
|
|
</div>
|
|
<div
|
|
className="border-l-2"
|
|
>
|
|
<SecondaryButton
|
|
className="text-nowrap rounded-r-lg"
|
|
rounding="none"
|
|
shape="square"
|
|
size="lg"
|
|
onClick={() => { inputRef.current?.click(); }}
|
|
disabled={disabled}
|
|
aria-label="Select File"
|
|
>
|
|
<FaRegFolderOpen />
|
|
</SecondaryButton>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|