UNPKG

@etsoo/materialui

Version:

TypeScript Material-UI Implementation

75 lines (74 loc) 3.27 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FileUploadButton = FileUploadButton; const jsx_runtime_1 = require("react/jsx-runtime"); const material_1 = require("@mui/material"); const Button_1 = __importDefault(require("@mui/material/Button")); const react_1 = __importDefault(require("react")); const FlexBox_1 = require("./FlexBox"); /** * File upload button * @param props Props * @returns Component */ function FileUploadButton(props) { // Destruct const { dropFilesLabel, maxFiles = 1, maxFileSize, inputProps, onFileInvalid, onUploadFiles, children = "Browse", ...rest } = props; const { onChange } = inputProps ?? {}; const [dragOver, setDragOver] = react_1.default.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 ((0, jsx_runtime_1.jsxs)(FlexBox_1.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" ? ((0, jsx_runtime_1.jsx)(material_1.Typography, { variant: "body2", children: dropFilesLabel })) : (dropFilesLabel)), (0, jsx_runtime_1.jsxs)(Button_1.default, { component: "label", sx: { textTransform: "none" }, ...rest, children: [children, (0, jsx_runtime_1.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 })] })] })); }