@etsoo/materialui
Version:
TypeScript Material-UI Implementation
69 lines (68 loc) • 2.86 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Typography } from "@mui/material";
import Button from "@mui/material/Button";
import React from "react";
import { HBox } from "./FlexBox";
/**
* File upload button
* @param props Props
* @returns Component
*/
export function FileUploadButton(props) {
// Destruct
const { dropFilesLabel, maxFiles = 1, maxFileSize, inputProps, onFileInvalid, onUploadFiles, children = "Browse", ...rest } = props;
const { onChange } = inputProps ?? {};
const [dragOver, setDragOver] = React.useState(false);
const handleDrop = (e) => {
e.preventDefault();
setDragOver(false);
validateFiles(e.dataTransfer.files);
};
const handleDragOver = (e) => {
e.preventDefault();
setDragOver(true);
};
const handleDragLeave = () => setDragOver(false);
const validateFiles = (files) => {
const fl = files.length;
if (fl === 0)
return;
if (maxFiles > 0 && fl > maxFiles) {
if (onFileInvalid)
onFileInvalid([maxFiles, fl]);
return;
}
if (maxFileSize && maxFileSize > 0) {
for (let f = 0; f < fl; f++) {
const file = files[f];
if (file.size > maxFileSize) {
if (onFileInvalid)
onFileInvalid([maxFileSize, file.size], file);
return;
}
}
}
onUploadFiles(files);
};
// Layout
return (_jsxs(HBox, { alignItems: "center", flexWrap: "wrap", border: (theme) => dragOver ? "1px dashed " + theme.palette.warning.main : undefined, spacing: 0.5, ...(dropFilesLabel == null
? undefined
: {
onDrop: handleDrop,
onDragOver: handleDragOver,
onDragLeave: handleDragLeave
}), children: [dropFilesLabel &&
(typeof dropFilesLabel === "string" ? (_jsx(Typography, { variant: "body2", children: dropFilesLabel })) : (dropFilesLabel)), _jsxs(Button, { component: "label", sx: { textTransform: "none" }, ...rest, children: [children, _jsx("input", { type: "file", multiple: maxFiles > 1, hidden: true, onChange: (event) => {
if (onChange)
onChange(event);
if (event.isDefaultPrevented())
return;
const files = event.target.files;
if (files == null)
return;
const fl = files.length;
if (fl === 0)
return;
validateFiles(files);
}, ...inputProps })] })] }));
}