mui-dynamic-field
Version:
A dynamic and customizable input field component for React, built with Material UI & TypeScript.
5,697 lines • 175 kB
JavaScript
'use strict';
var material = require('@mui/material');
var React = require('react');
var Visibility = require('@mui/icons-material/Visibility');
var VisibilityOff = require('@mui/icons-material/VisibilityOff');
var jsxRuntime = require('react/jsx-runtime');
var CloseIcon = require('@mui/icons-material/Close');
var VolumeOffIcon = require('@mui/icons-material/VolumeOff');
var HeadsetIcon = require('@mui/icons-material/Headset');
var DescriptionIcon = require('@mui/icons-material/Description');
var LaunchIcon = require('@mui/icons-material/Launch');
var BrokenImageIcon = require('@mui/icons-material/BrokenImage');
var DeleteIcon = require('@mui/icons-material/Delete');
var PictureAsPdfIcon = require('@mui/icons-material/PictureAsPdf');
var ArrowBackIcon = require('@mui/icons-material/ArrowBack');
var ArrowForwardIcon = require('@mui/icons-material/ArrowForward');
var VideocamOffIcon = require('@mui/icons-material/VideocamOff');
var PlayCircleIcon = require('@mui/icons-material/PlayCircle');
var ImageIcon = require('@mui/icons-material/Image');
var CloudUploadIcon = require('@mui/icons-material/CloudUpload');
var DoneIcon = require('@mui/icons-material/Done');
var FlipIcon = require('@mui/icons-material/Flip');
var FlipCameraIcon = require('@mui/icons-material/FlipCameraAndroid');
var Menu = require('@mui/material/Menu');
var MenuItem = require('@mui/material/MenuItem');
var emStyled = require('@emotion/styled');
var react = require('@emotion/react');
var Divider = require('@mui/material/Divider');
var Checkbox = require('@mui/material/Checkbox');
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n.default = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
const PasswordInput = props => {
const {
color,
name,
error,
errorText,
label,
value,
onChange,
disabled,
size,
slotProps,
...restProps
} = props;
const [showPassword, setShowPassword] = React.useState(false);
const toggleShowPassword = () => setShowPassword(!showPassword);
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
type: showPassword ? "text" : "password",
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: label,
name: name,
disabled: disabled,
variant: "outlined",
value: value ?? "",
onChange: onChange,
size: size,
onWheel: e => e.target.blur(),
slotProps: {
...slotProps,
input: {
...(slotProps?.input || {}),
endAdornment: /*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: toggleShowPassword,
children: showPassword ? /*#__PURE__*/jsxRuntime.jsx(VisibilityOff, {}) : /*#__PURE__*/jsxRuntime.jsx(Visibility, {})
})
}
},
...restProps
});
};
const getUpdatedKey = _key => `updated_${_key}`;
const getErrorKey = _key => `er_${_key}`;
const getErrorText = _key => `er_txt_${_key}`;
const validateFields = ({
_state,
fields,
getLocalizedText,
customFunctions,
ignoreFields
}) => {
let isValid = true;
const updatedState = {
..._state
};
// Helper to set an error message
const setError = (_key, message, localizedKey, localizedParams) => {
isValid = false;
updatedState[getErrorKey(_key)] = true;
updatedState[getErrorText(_key)] = getLocalizedText && localizedKey ? getLocalizedText(localizedKey, localizedParams) : message;
};
fields.forEach(({
isOptional,
regex,
_key,
dependent,
minLength,
maxLength,
min,
max,
placeholder
}) => {
const fieldValue = updatedState[_key];
// Skip if _key is in ignoreFields
if (ignoreFields?.includes(_key)) return;
// Skip validation if the field is optional and empty
if (!fieldValue && isOptional || !_key) return;
// Skip validation if the field has a dependency that isn't met
if (dependent && updatedState[dependent._key] !== dependent.value) return;
// Handle array fields
if (Array.isArray(fieldValue) && fieldValue.length) {
updatedState[getErrorKey(_key)] = false;
updatedState[getErrorText(_key)] = "";
return;
}
if (Array.isArray(fieldValue) && !fieldValue.length) {
setError(_key, `${placeholder || "Field"} is required`, "placeholderIsRequired", {
placeholder: getLocalizedText?.(placeholder || "field")
});
return;
}
// Handle required fields
if (fieldValue === undefined || fieldValue === null) {
setError(_key, `${placeholder || "Field"} is required`, "placeholderIsRequired", {
placeholder: getLocalizedText?.(placeholder || "field")
});
return;
}
// Handle min/max length validation
if (typeof fieldValue === "string") {
if (minLength && fieldValue.length < minLength || min && fieldValue.length < min) {
setError(_key, `Minimum length should be ${minLength || min}`, "minLengthError", {
minLength: minLength || min
});
return;
}
if (maxLength && fieldValue.length > maxLength || max && fieldValue.length > max) {
setError(_key, `Maximum length should be ${maxLength || max}`, "maxLengthError", {
maxLength: maxLength || max
});
return;
}
}
// Handle negative number validation
if (typeof +fieldValue === "number" && +fieldValue < 0) {
setError(_key, "Please enter a valid value", "invalidValue");
return;
}
// Handle empty or whitespace-only fields
if (typeof fieldValue === "string" && !fieldValue.trim().length) {
setError(_key, "Please enter a valid value", "invalidValue");
return;
}
// Handle regex validation
if (regex && typeof fieldValue === "string") {
const _regexExp = new RegExp(regex.pattern);
if (!_regexExp.test(fieldValue)) {
setError(_key, "Invalid format", regex.message);
return;
}
}
// Validate using custom functions
if (customFunctions?.[_key]) {
const error = customFunctions[_key]();
if (error) {
setError(_key, error);
return;
}
}
// Clear previous errors if validation passes
updatedState[getErrorKey(_key)] = false;
updatedState[getErrorText(_key)] = "";
updatedState[_key] = typeof fieldValue === "string" ? fieldValue.trim() : fieldValue;
});
return {
isValid,
_state: updatedState
};
};
const queryString = obj => {
return Object.entries(obj).reduce((acc, [key, value]) => {
if (value !== undefined && value !== "") {
if (Array.isArray(value)) {
const val = value.map(item => typeof item === "object" ? item.label || item : item);
val.forEach(v => {
acc.push(`${encodeURIComponent(key)}=${encodeURIComponent(v)}`);
});
} else {
acc.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
}
}
return acc;
}, []).join("&");
};
function extractValue(obj, key) {
if (!obj?.toString()) {
return "";
}
return obj[key] ?? obj ?? "";
}
const AutocompleteSelect = props => {
const {
_key,
error,
errorText,
value,
onChange,
disabled,
size,
placeholder,
extraProps = {},
extraData = []
} = props;
const {
textFieldProps = {},
...restProps
} = extraProps || {};
const {
slotProps = {},
...restTextFieldProps
} = textFieldProps;
return /*#__PURE__*/jsxRuntime.jsx(material.Autocomplete, {
size: size,
openOnFocus: true,
disablePortal: true,
disabled: disabled,
isOptionEqualToValue: (option, value) => extractValue(option, "value") === value,
getOptionLabel: option => {
if (!option?.toString()) return "";
const selected = extraData?.find(item => {
return extractValue(option, "value") === extractValue(item, "value");
});
if (!selected) {
return "";
}
return String(extractValue(selected, "label"));
},
options: extraData,
value: extractValue(value, "value"),
onChange: (_, value) => {
onChange && onChange({
value: extractValue(value, "value"),
_key,
textValue: extractValue(value, "label")
});
},
renderOption: ({
key,
...restProps
}, option) => {
return /*#__PURE__*/jsxRuntime.jsx(material.MenuItem, {
...restProps,
children: String(extractValue(option, "label"))
}, key);
},
renderInput: params => {
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
...params,
label: placeholder,
helperText: errorText,
error: error,
sx: {
"& .MuiAutocomplete-inputRoot": {
...(slotProps?.input?.style || {})
}
},
...restTextFieldProps
});
},
...restProps
});
};
const ModalHeader = ({
title,
onClose
}) => {
return /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
id: "modal-modal-title",
component: "div",
sx: {
display: "flex",
borderTopLeftRadius: "8px",
borderTopRightRadius: "8px",
alignItems: "center",
justifyContent: "space-between"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.Typography, {
variant: "h6",
component: "h2",
children: title
}), onClose && /*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: onClose,
children: /*#__PURE__*/jsxRuntime.jsx(CloseIcon, {
fontSize: "small"
})
})]
});
};
const ModalFooter = ({
children,
sx = {}
}) => {
return /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
id: "modal-modal-footer",
component: "div",
sx: sx,
children: children
});
};
const CustomModal = ({
title,
isOpen,
onClose,
children,
sx,
className = "",
buttons
}) => {
return /*#__PURE__*/jsxRuntime.jsx(material.Modal, {
open: isOpen,
"aria-labelledby": "modal-modal-title",
"aria-describedby": "modal-modal-description",
sx: {
outline: "none",
overflow: "auto"
},
children: /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
component: "div",
sx: {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
minWidth: "40vw",
width: {
xs: "80%",
sm: "30%"
},
bgcolor: "background.paper",
boxShadow: 4,
borderRadius: "8px",
p: 2,
maxHeight: "100%",
overflow: "auto",
...sx
},
className: `hide-scrollbar ${className}`,
children: [title && /*#__PURE__*/jsxRuntime.jsx(ModalHeader, {
title: title,
onClose: onClose
}), /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
component: "div",
sx: {
display: "flex",
flex: 1,
flexDirection: "column",
justifyContent: "space-between"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.Typography, {
component: "div",
children: children
}), !!buttons?.length && /*#__PURE__*/jsxRuntime.jsx(ModalFooter, {
children: /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
sx: {
display: "flex",
alignItems: "center",
justifyContent: "flex-end",
gap: 2
},
children: buttons.map(({
title,
hidden,
...rest
}) => !hidden && /*#__PURE__*/jsxRuntime.jsx(material.Button, {
...rest,
children: title
}, title))
})
})]
})]
})
});
};
async function getMedia(deviceId) {
console.log("getMedia");
let stream = null;
try {
stream = await navigator.mediaDevices.getUserMedia({
video: {
deviceId
},
audio: false
});
return stream;
} catch (err) {
console.log(err);
}
}
async function takePicture(canvas, video, width, height) {
const context = canvas.getContext("2d");
const ratio = window.devicePixelRatio || 1;
if (context) {
canvas.width = width * ratio;
canvas.height = height * ratio;
// Scale the context to match the devicePixelRatio
context.setTransform(ratio, 0, 0, ratio, 0, 0);
context.imageSmoothingEnabled = true;
context.imageSmoothingQuality = "high";
context.clearRect(0, 0, width, height);
context.drawImage(video, 0, 0, width, height);
return getImageFromCanvas(canvas);
}
console.error("Canvas context is not available.");
return false;
}
async function flipPicture(canvas) {
const context = canvas.getContext("2d");
const ratio = window.devicePixelRatio || 1;
if (context) {
// Save the current image as a source
const imageBitmap = await createImageBitmap(canvas);
// Clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// Save the context state before applying transformations
context.save();
// Apply horizontal flip transformation with devicePixelRatio compensation
context.scale(-1, 1);
context.translate(-canvas.width / ratio, 0);
// Draw the flipped image
context.drawImage(imageBitmap, 0, 0, canvas.width / ratio, canvas.height / ratio);
// Restore the context state to reset transformations
context.restore();
return getImageFromCanvas(canvas);
}
console.error("Canvas context is not available.");
return false;
}
async function getImageFromCanvas(canvas) {
const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/jpeg", 1.0));
if (blob) {
return new File([blob], "fileName.jpg", {
type: "image/jpeg"
});
}
return false;
}
async function getVideoDeviceList() {
try {
console.log("getVideoDeviceList");
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: true
});
if (!navigator.mediaDevices?.enumerateDevices || !stream) {
console.log("enumerateDevices() not supported.");
} else {
const devices = await navigator.mediaDevices.enumerateDevices();
return devices.filter(device => device.kind === "videoinput");
}
} catch (error) {
console.log(error);
}
}
function RenderCameraList({
list,
selectedCamera,
onChangeCamera
}) {
const [anchorEl, setAnchorEl] = React__namespace.useState(null);
const open = Boolean(anchorEl);
const handleClick = event => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const handleCameraChange = deviceId => {
onChangeCamera(deviceId);
handleClose();
};
return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: [/*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
id: "basic-button",
"aria-controls": open ? "basic-menu" : undefined,
"aria-haspopup": "true",
"aria-expanded": open ? "true" : undefined,
onClick: handleClick,
sx: {
justifySelf: "self-start"
},
children: /*#__PURE__*/jsxRuntime.jsx(FlipCameraIcon, {
fontSize: "medium",
sx: {
color: "white",
aspectRatio: 1
}
})
}), /*#__PURE__*/jsxRuntime.jsx(Menu, {
id: "basic-menu",
anchorEl: anchorEl,
open: open,
onClose: handleClose,
slotProps: {
list: {
"aria-labelledby": "basic-button"
}
},
children: list.map(device => /*#__PURE__*/jsxRuntime.jsx(MenuItem, {
selected: selectedCamera === device.deviceId,
onClick: () => handleCameraChange(device.deviceId),
children: device.label
}, device.deviceId))
})]
});
}
const CameraFooter = ({
devices,
selectedDeviceId,
onChangeSelectedDevice,
isPictureClicked,
onClickPicture,
onAccept,
onDecline,
onMirror
}) => {
return /*#__PURE__*/jsxRuntime.jsx(material.Box, {
component: "div",
sx: {
position: "absolute",
bottom: 0,
background: "rgba(0, 0, 0, 0.5)",
width: "100%",
zIndex: 9999,
height: 80,
display: "flex",
alignItems: "center"
},
children: isPictureClicked ? /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
sx: {
width: "100%",
display: "flex",
alignItems: "center",
justifyContent: "space-between"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: onDecline,
children: /*#__PURE__*/jsxRuntime.jsx(CloseIcon, {
fontSize: "large",
sx: {
color: "#fff"
}
})
}), /*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: onMirror,
children: /*#__PURE__*/jsxRuntime.jsx(FlipIcon, {
fontSize: "large",
sx: {
color: "#fff"
}
})
}), /*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: onAccept,
children: /*#__PURE__*/jsxRuntime.jsx(DoneIcon, {
fontSize: "large",
sx: {
color: "#fff"
}
})
})]
}) : /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
sx: {
width: "100%",
textAlign: "center",
display: "grid",
gridTemplateColumns: "0.9fr 1.1fr"
},
children: [/*#__PURE__*/jsxRuntime.jsx(RenderCameraList, {
list: devices,
selectedCamera: selectedDeviceId,
onChangeCamera: onChangeSelectedDevice
}), /*#__PURE__*/jsxRuntime.jsx("button", {
style: {
background: "#fff",
borderRadius: "100%",
border: "none",
outline: "none",
cursor: "pointer",
width: "50px",
height: "auto",
aspectRatio: 1
},
onClick: onClickPicture
})]
})
});
};
const UploadFromCamera = ({
onChange,
getLocalizedText
}) => {
const [isCameraLoading, setIsCameraLoading] = React.useState(false);
const [selectedDeviceId, setSelectedDeviceId] = React.useState("");
const [devices, setDevices] = React.useState([]);
const [clickedPicture, setClickedPicture] = React.useState(null);
const [isMirrored, setIsMirrored] = React.useState(false);
const streamRef = React.useRef(null);
const audioRef = React.useRef(null);
const videoRef = React.useRef(null);
const canvasRef = React.useRef(null);
// handling accept picture
const handleAcceptPicture = async () => {
if (clickedPicture) {
onChange([clickedPicture]);
}
setClickedPicture(null);
};
// handling decline picture
const handleDeclinePicture = async () => {
setClickedPicture(null);
};
// handling flip picture
const handleFlipPicture = async () => {
if (canvasRef.current) {
const pic = await flipPicture(canvasRef.current);
if (pic) {
setClickedPicture(pic);
setIsMirrored(!isMirrored);
}
}
};
// handling click picture
const handleClickPicture = async () => {
const canvas = canvasRef.current;
const video = videoRef.current;
const audio = audioRef.current;
if (canvas && video && audio) {
await audio.play();
setTimeout(async () => {
const {
width,
height
} = video.getBoundingClientRect();
canvas.width = width;
canvas.height = height;
const pic = await takePicture(canvas, video, canvas.width, canvas.height);
pic && setClickedPicture(pic);
}, 1000);
}
};
const playMediaStream = deviceId => {
if (streamRef.current) {
stopMediaStream();
}
getMedia(deviceId).then(mediaStream => {
const video = videoRef.current;
if (video && mediaStream) {
streamRef.current = mediaStream;
video.srcObject = mediaStream;
video.onloadedmetadata = () => {
setIsCameraLoading(false);
};
}
});
};
const stopMediaStream = () => {
if (videoRef.current) {
videoRef.current.srcObject = null;
videoRef.current.src = "";
}
if (streamRef.current) {
console.log("stopping track");
const track = streamRef.current.getVideoTracks()[0];
track.stop();
track.enabled = false;
streamRef.current = null;
}
};
const getDevices = async () => {
const deviceList = (await getVideoDeviceList()) || [];
setDevices(deviceList);
setSelectedDeviceId(deviceList[0]?.deviceId || "");
};
const handleCameraChange = deviceId => {
setSelectedDeviceId(deviceId);
};
React.useMemo(() => {
selectedDeviceId && playMediaStream(selectedDeviceId);
}, [selectedDeviceId]);
React.useEffect(() => {
getDevices();
setIsCameraLoading(true);
return () => {
stopMediaStream();
};
}, []);
return /*#__PURE__*/jsxRuntime.jsx("div", {
style: {
textAlign: "center"
},
children: /*#__PURE__*/jsxRuntime.jsxs("div", {
style: {
margin: "auto",
position: "relative",
background: "rgba(0, 0, 0, 0.1)"
},
children: [/*#__PURE__*/jsxRuntime.jsx("video", {
ref: videoRef,
style: {
width: "100%",
height: "100%",
objectFit: "contain",
display: !!clickedPicture ? "none" : "block"
},
autoPlay: true,
playsInline: true
}), /*#__PURE__*/jsxRuntime.jsx("canvas", {
ref: canvasRef,
style: {
display: !!clickedPicture ? "block" : "none",
margin: "auto",
width: "100%",
height: "auto"
}
}), isCameraLoading && /*#__PURE__*/jsxRuntime.jsx("div", {
style: {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)"
},
children: getLocalizedText?.("loading") || "Loading..."
}), /*#__PURE__*/jsxRuntime.jsx("audio", {
ref: audioRef,
style: {
display: "none"
}
}), /*#__PURE__*/jsxRuntime.jsx(CameraFooter, {
devices: devices,
selectedDeviceId: selectedDeviceId,
onChangeSelectedDevice: handleCameraChange,
isPictureClicked: !!clickedPicture,
onClickPicture: handleClickPicture,
onAccept: handleAcceptPicture,
onDecline: handleDeclinePicture,
onMirror: handleFlipPicture
})]
})
});
};
const filterFilesByMaxSize = ({
files,
maxSize
}) => {
let filteredFiles = [];
for (let file of files) {
if (Number((file.size / (1024 * 1024)).toFixed(2)) <= maxSize) {
filteredFiles.push(file);
}
}
return filteredFiles;
};
// export const getFileType = (file: IMedia.FileData) => {
// if (!file) return null;
// if (file instanceof File) {
// if (file.type.startsWith("application")) {
// return file.type.split("/")[1];
// }
// return file.type.split("/")[0];
// }
// if (typeof file === "string") {
// return file;
// }
// if (file.fileType.startsWith("application")) {
// return file.fileType.split("/")[1];
// }
// return file.fileType.split("/")[0];
// };
function getFileType(file) {
const ext = file.name?.split(".").pop()?.toLowerCase();
if (!ext) return "unknown";
if (["jpg", "jpeg", "png", "gif", "webp"].includes(ext)) return "image";
if (["mp4", "webm", "ogg", "mov"].includes(ext)) return "video";
if (["mp3", "wav", "aac", "flac"].includes(ext)) return "audio";
if (["pdf"].includes(ext)) return "pdf";
if (["doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt"].includes(ext)) return "document";
return "unknown";
}
function getFileExtension(filePath) {
if (!filePath) return "";
return filePath.split(".").pop() || "jpg";
}
function getFileMetaData(file, filePath) {
return {
url: URL.createObjectURL(file),
name: file.name,
type: file.type,
size: file.size,
path: filePath || file.name,
extension: getFileExtension(file.name),
file
};
}
function checkIsMobile() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
return true;
}
return false;
}
const UploadFromGallery = ({
name,
multiple = false,
onChange,
disabled,
extraProps,
inputProps,
onError,
getLocalizedText
}) => {
const {
maxFileSize = 5,
supportedFiles = ["*"]
} = extraProps || {};
const supportedFilesString = React.useMemo(() => {
if (supportedFiles.includes("*")) {
return getLocalizedText?.("allFileTypesSupported") || "All file types are supported";
}
const friendlyTypesMap = {
"image/*": "images",
"video/*": "videos",
"audio/*": "audio files",
"application/pdf": "PDFs",
"application/msword": "Word documents",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "Word documents",
"application/vnd.ms-excel": "Excel spreadsheets",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "Excel spreadsheets",
"application/vnd.ms-powerpoint": "PowerPoint presentations",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "PowerPoint presentations",
"text/plain": "text files"
};
const friendlyNames = supportedFiles.map(type => friendlyTypesMap[type] || type).filter((value, index, self) => self.indexOf(value) === index); // remove duplicates
return `${getLocalizedText?.("supportedFiles") || "Supported files"}: ${friendlyNames.join(", ")}`;
}, [supportedFiles]);
const handleChange = files => {
const filteredFiles = filterFilesByMaxSize({
files,
maxSize: maxFileSize
});
if (filteredFiles.length < files.length) {
onError?.(getLocalizedText?.("ignoringFilesGreaterSize") || "Ignoring files greater than max size");
}
onChange(filteredFiles);
};
return /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
component: "div",
children: /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
component: "label",
htmlFor: `input-file-${name}`,
color: "primary",
sx: {
border: "1px dashed",
height: 200,
width: "100%",
borderRadius: 2,
display: "flex",
alignItems: "center",
justifyContent: "center",
cursor: "pointer"
},
onDragOver: e => e.preventDefault(),
onDrop: e => {
e.preventDefault();
handleChange(e.dataTransfer.files);
},
children: [/*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
sx: {
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.Typography, {
component: "span",
children: /*#__PURE__*/jsxRuntime.jsx(CloudUploadIcon, {
fontSize: "large"
})
}), /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
component: "span",
color: "textPrimary",
children: getLocalizedText?.("dropFile") || "Drop your file here, or browse"
}), /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
component: "span",
sx: {
fontSize: 14
},
children: supportedFilesString
}), /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
component: "span",
color: "warning",
sx: {
fontSize: 12
},
children: getLocalizedText?.("maxFileSize", {
size: maxFileSize
}) || `Max file size ${maxFileSize}MB`
})]
}), /*#__PURE__*/jsxRuntime.jsx("input", {
id: `input-file-${name}`,
type: "file",
style: {
display: "none"
},
accept: supportedFiles.join(", "),
multiple: multiple,
disabled: disabled,
onChange: e => {
if (e.target.files) {
handleChange(e.target.files);
}
},
...inputProps
})]
})
});
};
const RenderUploadOption = ({
uploadOption,
...rest
}) => {
switch (uploadOption) {
case "camera":
return /*#__PURE__*/jsxRuntime.jsx(UploadFromCamera, {
...rest
});
case "gallery":
return /*#__PURE__*/jsxRuntime.jsx(UploadFromGallery, {
...rest
});
}
};
function ScrollableTabs({
groups,
onTabChange,
activeTab,
renderContent,
getLocalizedText
}) {
return /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
sx: {
width: "100%"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
display: "flex",
overflowX: "auto"
},
children: groups.map(({
label,
_key
}, index) => /*#__PURE__*/jsxRuntime.jsx(material.Button, {
onClick: () => onTabChange(index),
sx: {
flex: "0 0 auto",
borderRadius: 0,
borderBottom: 2,
borderColor: activeTab === index ? "primary.main" : "transparent",
color: activeTab === index ? "primary.main" : "text.primary",
fontWeight: 600,
textTransform: "uppercase",
"&:hover": {
backgroundColor: "transparent"
},
fontSize: "0.875rem",
lineHeight: 1.25,
letterSpacing: "0.02857em",
maxWidth: "360px",
minWidth: "90px",
position: "relative",
minHeight: "48px",
flexShrink: 0,
padding: "12px 16px",
overflow: "hidden",
whiteSpace: "normal",
textAlign: "center",
flexDirection: "column"
},
children: getLocalizedText?.(`${_key}`) || label
}, _key))
}), /*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
my: 2
},
children: renderContent
})]
});
}
const Image = ({
src,
alt = "Media image",
width = "100%",
height = "100%",
containerStyle = {},
style = {},
...rest
}) => {
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(false);
return /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
position: "relative",
width: width,
height: height,
display: "flex",
alignItems: "center",
justifyContent: "center",
borderRadius: 1,
overflow: "hidden",
style: containerStyle,
children: [loading && !error && /*#__PURE__*/jsxRuntime.jsx(material.CircularProgress, {
size: 32
}), !error ? /*#__PURE__*/jsxRuntime.jsx("img", {
src: src,
alt: alt,
onLoad: () => {
setLoading(false);
},
onError: () => {
setLoading(false);
setError(true);
},
style: {
display: loading ? "none" : "block",
width: "100%",
height: "100%",
objectFit: "cover",
...style
},
...rest
}) : /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
display: "flex",
flexDirection: "column",
alignItems: "center",
children: [/*#__PURE__*/jsxRuntime.jsx(BrokenImageIcon, {
color: "disabled",
fontSize: "large"
}), /*#__PURE__*/jsxRuntime.jsx("span", {
style: {
fontSize: 12,
color: "#888"
},
children: "Image not found"
})]
})]
});
};
const Video = ({
src,
poster,
width = "100%",
height = "100%",
style = {},
isPlaceholder,
iconProps = {},
...rest
}) => {
const theme = material.useTheme();
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(false);
const videoRef = React.useRef(null);
const handleLoadedData = React.useCallback(() => {
setLoading(false);
}, []);
const handleError = React.useCallback(() => {
setLoading(false);
setError(true);
}, []);
React.useEffect(() => {
if (videoRef.current && videoRef.current.readyState > 3) {
setLoading(false);
}
}, []);
return /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
position: "relative",
width: width,
display: "flex",
alignItems: "center",
justifyContent: "center",
borderRadius: 1,
overflow: "hidden",
style: {
aspectRatio: 1,
background: isPlaceholder ? "transparent" : "black",
...style
},
children: [loading && !error && !isPlaceholder && /*#__PURE__*/jsxRuntime.jsx(material.CircularProgress, {
size: 32
}), !!isPlaceholder && /*#__PURE__*/jsxRuntime.jsx(PlayCircleIcon, {
sx: {
fontSize: "auto",
zIndex: 10,
position: "absolute",
color: theme.palette.primary.main
},
...iconProps
}), !isPlaceholder && (!error ? /*#__PURE__*/jsxRuntime.jsx("video", {
ref: videoRef,
src: src,
poster: poster,
preload: "metadata",
loop: false,
onLoadedMetadata: handleLoadedData,
onError: handleError,
style: {
display: loading ? "none" : "block",
width: "100%",
// height: "100%",
aspectRatio: 1,
objectFit: isPlaceholder ? "cover" : "contain",
opacity: isPlaceholder ? 0 : 1
},
...rest
}) : /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
display: "flex",
flexDirection: "column",
alignItems: "center",
children: [/*#__PURE__*/jsxRuntime.jsx(VideocamOffIcon, {
color: "disabled",
fontSize: "large"
}), /*#__PURE__*/jsxRuntime.jsx("span", {
style: {
fontSize: 12,
color: "#888"
},
children: "Video not available"
})]
}))]
});
};
const Audio = ({
src,
style = {}
}) => {
const audioRef = React.useRef(null);
const [loading, setLoading] = React.useState(true);
const [error, setError] = React.useState(false);
React.useEffect(() => {
if (audioRef.current && audioRef.current.readyState >= 3) {
setLoading(false);
}
}, []);
const handleLoaded = () => setLoading(false);
const handleError = () => {
setLoading(false);
setError(true);
};
return /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
width: "100%",
height: "100%",
padding: 2,
borderRadius: 1,
style: {
position: "relative",
display: "flex",
alignItems: "flex-end",
justifyContent: "flex-end",
...style
},
children: [loading && !error && /*#__PURE__*/jsxRuntime.jsx(material.CircularProgress, {
sx: {
position: "absolute",
top: "50%",
left: "50%",
translate: "-50% -50%"
},
size: 32
}), !error ? /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
sx: {
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "space-between",
bgcolor: "grey.300",
borderRadius: 2
},
children: [!loading && /*#__PURE__*/jsxRuntime.jsx(AudioPlaceholder, {
sx: {
fontSize: 120
}
}), /*#__PURE__*/jsxRuntime.jsx("audio", {
ref: audioRef,
src: src,
controls: true,
onLoadedMetadata: handleLoaded
// onCanPlayThrough={handleLoaded}
,
onError: handleError,
style: {
display: loading ? "none" : "block",
width: "100%",
borderRadius: 0
}
})]
}) : /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
display: "flex",
alignItems: "center",
flexDirection: "column",
children: [/*#__PURE__*/jsxRuntime.jsx(VolumeOffIcon, {
color: "disabled",
fontSize: "large"
}), /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
variant: "body2",
color: "textSecondary",
children: "Audio not available"
})]
})]
});
};
const AudioPlaceholder = ({
sx,
containerSx
}) => {
const theme = material.useTheme();
return /*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
...containerSx
},
children: /*#__PURE__*/jsxRuntime.jsx(HeadsetIcon, {
sx: {
fontSize: "auto",
color: theme.palette.primary.main,
...sx
}
})
});
};
const Document = ({
data
}) => {
const handleRedirect = () => {
window.open(data.url);
};
return /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
sx: {
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "space-between",
bgcolor: "grey.300",
borderRadius: 2,
position: "relative",
overflow: "hidden"
},
children: [/*#__PURE__*/jsxRuntime.jsx(LaunchIcon, {
sx: {
position: "absolute",
right: 0,
bgcolor: "white",
width: "40px",
height: "40px",
p: "5px",
cursor: "pointer"
},
onClick: handleRedirect
}), /*#__PURE__*/jsxRuntime.jsx(DocumentPlaceholder, {
sx: {
fontSize: 50
}
})]
});
};
const DocumentPlaceholder = ({
sx,
containerSx
}) => {
const theme = material.useTheme();
return /*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
...containerSx
},
children: /*#__PURE__*/jsxRuntime.jsx(DescriptionIcon, {
sx: {
fontSize: "auto",
color: theme.palette.primary.main,
...sx
}
})
});
};
/**
* WARNING: Don't import this directly. It's imported by the code generated by
* `@mui/interal-babel-plugin-minify-errors`. Make sure to always use string literals in `Error`
* constructors to ensure the plugin works as expected. Supported patterns include:
* throw new Error('My message');
* throw new Error(`My message: ${foo}`);
* throw new Error(`My message: ${foo}` + 'another string');
* ...
* @param {number} code
*/
function formatMuiErrorMessage(code, ...args) {
const url = new URL(`https://mui.com/production-error/?code=${code}`);
args.forEach(arg => url.searchParams.append('args[]', arg));
return `Minified MUI error #${code}; visit ${url} for the full message.`;
}
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var propTypes = {exports: {}};
var reactIs$1 = {exports: {}};
var reactIs_production_min = {};
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_production_min;
function requireReactIs_production_min () {
if (hasRequiredReactIs_production_min) return reactIs_production_min;
hasRequiredReactIs_production_min = 1;
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}reactIs_production_min.AsyncMode=l;reactIs_production_min.ConcurrentMode=m;reactIs_production_min.ContextConsumer=k;reactIs_production_min.ContextProvider=h;reactIs_production_min.Element=c;reactIs_production_min.ForwardRef=n;reactIs_production_min.Fragment=e;reactIs_production_min.Lazy=t;reactIs_production_min.Memo=r;reactIs_production_min.Portal=d;
reactIs_production_min.Profiler=g;reactIs_production_min.StrictMode=f;reactIs_production_min.Suspense=p;reactIs_production_min.isAsyncMode=function(a){return A(a)||z(a)===l};reactIs_production_min.isConcurrentMode=A;reactIs_production_min.isContextConsumer=function(a){return z(a)===k};reactIs_production_min.isContextProvider=function(a){return z(a)===h};reactIs_production_min.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};reactIs_production_min.isForwardRef=function(a){return z(a)===n};reactIs_production_min.isFragment=function(a){return z(a)===e};reactIs_production_min.isLazy=function(a){return z(a)===t};
reactIs_production_min.isMemo=function(a){return z(a)===r};reactIs_production_min.isPortal=function(a){return z(a)===d};reactIs_production_min.isProfiler=function(a){return z(a)===g};reactIs_production_min.isStrictMode=function(a){return z(a)===f};reactIs_production_min.isSuspense=function(a){return z(a)===p};
reactIs_production_min.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};reactIs_production_min.typeOf=z;
return reactIs_production_min;
}
var reactIs_development$1 = {};
/** @license React v16.13.1
* react-is.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_development$1;
function requireReactIs_development$1 () {
if (hasRequiredReactIs_development$1) return reactIs_development$1;
hasRequiredReactIs_development$1 = 1;
if (process.env.NODE_ENV !== "production") {
(function() {
// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
// nor polyfill, then a plain number is used for performance.
var hasSymbol = typeof Symbol === 'function' && Symbol.for;
var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7;
var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
// (unstable) APIs that have been removed. Can we remove the symbols?
var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf;
var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8;
var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9;
var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5;
var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6;
var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7;
function isValidElementType(type) {
return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill.
type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE);
}
function typeOf(object) {
if (typeof object === 'object' && object !== null) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
var type = object.type;
switch (type) {
case REACT_ASYNC_MODE_TYPE:
case REACT_CONCURRENT_MODE_TYPE:
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
return type;
default:
var $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
case REACT_PROVIDER_TYPE:
return $$typeofType;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
return undefined;
} // AsyncMode is deprecated along with isAsyncMode
var AsyncMode = REACT_ASYNC_MODE_TYPE;
var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE;
var ContextConsumer = REACT_CONTEXT_TYPE;
var ContextProvider = REACT_PROVIDER_TYPE;
var Element = REACT_ELEMENT_TYPE;
var ForwardRef = REACT_FORWARD_REF_TYPE;
var Fragment = REACT_FRAGMENT_TYPE;
var Lazy = REACT_LAZY_TYPE;
var Memo = REACT_MEMO_TYPE;
var Portal = REACT_PORTAL_TYPE;
var Profiler = REACT_PROFILER_TYPE;
var StrictMode = REACT_STRICT_MODE_TYPE;
var Suspense = REACT_SUSPENSE_TYPE;
var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated
function isAsyncMode(object) {
{
if (!hasWarnedAboutDeprecatedIsAsyncMode) {
hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint
console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.');
}
}
return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE;
}
function isConcurrentMode(object) {
return typeOf(object) === REACT_CONCURRENT_MODE_TYPE;
}
function isContextConsumer(object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
}
function isContextProvider(object) {
return typeOf(object) === REACT_PROVIDER_TYPE;
}
function isElement(object) {
return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
}
function isForwardRef(object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
}
function isFragment(object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
}
function isLazy(object) {
return typeOf(object) === REACT_LAZY_TYPE;
}
function isMemo(object) {
return typeOf(object) === REACT_MEMO_TYPE;
}
function isPortal(object) {
return typeOf(object) === REACT_PORTAL_TYPE;
}
function isProfiler(object) {
return typeOf(object) === REACT_PROFILER_TYPE;
}
function isStrictMode(object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
}
function isSuspense(object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
}
reactIs_development$1.AsyncMode = AsyncMode;
reactIs_development$1.ConcurrentMode = ConcurrentMode;
reactIs_development$1.ContextConsumer = ContextConsumer;
reactIs_development$1.ContextProvider = ContextProvider;
reactIs_development$1.Element = Element;
reactIs_development$1.ForwardRef = ForwardRef;
reactIs_development$1.Fragment = Fragment;
reactIs_development$1.Lazy = Lazy;
reactIs_development$1.Memo = Memo;
reactIs_development$1.Portal = Portal;
reactIs_development$1.Profiler = Profiler;
reactIs_development$1.StrictMode = StrictMode;
reactIs_development$1.Suspense = Suspense;
reactIs_development$1.isAsyncMode = isAsyncMode;
reactIs_development$1.isConcurrentMode = isConcurrentMode;
reactIs_development$1.isContextConsumer = isContextConsumer;
reactIs_development$1.isContextProvider = isContextProvider;
reactIs_development$1.isElement = isElement;
reactIs_development$1.isForwardRef = isForwardRef;
reactIs_development$1.isFragment = isFragment;
reactIs_development$1.isLazy = isLazy;
reactIs_development$1.isMemo = isMemo;
reactIs_development$1.isPortal = isPortal;
reactIs_development$1.isProfiler = isProfiler;
reactIs_development$1.isStrictMode = isStrictMode;
reactIs_development$1.isSuspense = isSuspense;
reactIs_development$1.isValidElementType = isValidElementType;
reactIs_development$1.typeOf = typeOf;
})();
}
return reactIs_development$1;
}
var hasRequiredReactIs$1;
function requireReactIs$1 () {
if (hasRequiredReactIs$1) return reactIs$1.exports;
hasRequiredReactIs$1 = 1;
if (process.env.NODE_ENV === 'production') {
reactIs$1.exports = requireReactIs_production_min();
} else {
reactIs$1.exports = requireReactIs_development$1();
}
return reactIs$1.exports;
}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var objectAssign;
var hasRequiredObjectAssign;
function requireObjectAssign () {
if (hasRequiredObjectAssign) return objectAssign;
hasRequiredObjectAssign = 1;
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
return objectAssign;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret_1;
var hasRequiredReactPropTypesSecret;
function requireReactPropTypesSecret () {
if (hasRequiredReactPropTypesSecret) return ReactPropTypesSecret_1;
hasRequiredReactPropTypesSecret = 1;
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
ReactPropTypesSecret_1 = ReactPropTypesSecret;
return ReactPropTypesSecret_1;
}
var has;
var hasRequiredHas;
function requireHas () {
if (hasRequiredHas) return has;
hasRequiredHas = 1;
has = Function.call.bind(Object.prototype.hasOwnProperty);
return has;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var checkPropTypes_1;
var hasRequiredCheckPropTypes;
function requireCheckPropTypes () {
if (hasRequiredCheckPropTypes) return checkPropTypes_1;
hasRequiredCheckPropTypes = 1;
var printWarning = function() {};
if (process.env.NODE_ENV !== 'production') {
var ReactPropTypesSecret = /*@__PURE__*/ requireReactPropTypesSecret();
var loggedTypeFailures = {};
var has = /*@__PURE__*/ requireHas();
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) { /**/ }
};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (process.env.NODE_ENV !== 'production') {
for (var typeSpecName in typeSpecs) {
if (has(typeSpecs, typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if (typeof typeSpecs[typeSpecName] !== 'function') {
var err = Error(
(componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' +
'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.'
);
err.name = 'Invariant Violation';
throw err;
}
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
if (error && !(error instanceof Error)) {
printWarning(
(componentName || 'React class') + ': type specification of ' +
location + ' `' + typeSpecName + '` is invalid; the type checker ' +
'function must return `null` or an `Error` but returned a ' + typeof error + '. ' +
'You may have forgotten to pass an argument to the type checker ' +
'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
'shape all require an argument).'
);
}
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
printWarning(
'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '')
);
}
}
}
}
}
/**
* Resets warning cache when testing.
*
* @private
*/
checkPropTypes.resetWarningCache = function() {
if (process.env.NODE_ENV !== 'production') {
loggedTypeFailures = {};
}
};
checkPropTypes_1 = checkPropTypes;
return checkPropTypes_1;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var factoryWithTypeCheckers;
var hasRequiredFactoryWithTypeCheckers;
function requireFactoryWithTypeCheckers () {
if (hasRequiredFactoryWithTypeCheckers) return factoryWithTypeCheckers;
hasRequiredFactoryWithTypeCheckers = 1;
var ReactIs = requireReactIs$1();
var assign = requireObjectAssign();
var ReactPropTypesSecret = /*@__PURE__*/ requireReactPropTypesSecret();
var has = /*@__PURE__*/ requireHas();
var checkPropTypes = /*@__PURE__*/ requireCheckPropTypes();
var printWarning = function() {};
if (process.env.NODE_ENV !== 'production') {
printWarning = function(text) {
var message = 'Warning: ' + text;
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
}
function emptyFunctionThatReturnsNull() {
return null;
}
factoryWithTypeCheckers = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bigint: createPrimitiveTypeChecker('bigint'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
elementType: createElementTypeTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message, data) {
this.message = message;
this.data = data && typeof data === 'object' ? data: {};
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (process.env.NODE_ENV !== 'production') {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} else if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
printWarning(
'You are manually calling a React.PropTypes validation ' +
'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.'
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'),
{expectedType: expectedType}
);
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunctionThatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!ReactIs.isValidElementType(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
if (process.env.NODE_ENV !== 'production') {
if (arguments.length > 1) {
printWarning(
'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' +
'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).'
);
} else {
printWarning('Invalid argument supplied to oneOf, expected an array.');
}
}
return emptyFunctionThatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues, function replacer(key, value) {
var type = getPreciseType(value);
if (type === 'symbol') {
return String(value);
}
return value;
});
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (has(propValue, key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
process.env.NODE_ENV !== 'production' ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunctionThatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
printWarning(
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.'
);
return emptyFunctionThatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
var expectedTypes = [];
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
var checkerResult = checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret);
if (checkerResult == null) {
return null;
}
if (checkerResult.data && has(checkerResult.data, 'expectedType')) {
expectedTypes.push(checkerResult.data.expectedType);
}
}
var expectedTypesMessage = (expectedTypes.length > 0) ? ', expected one of type [' + expectedTypes.join(', ') + ']': '';
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`' + expectedTypesMessage + '.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function invalidValidatorError(componentName, location, propFullName, key, type) {
return new PropTypeError(
(componentName || 'React class') + ': ' + location + ' type `' + propFullName + '.' + key + '` is invalid; ' +
'it must be a function, usually from the `prop-types` package, but received `' + type + '`.'
);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (typeof checker !== 'function') {
return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from props.
var allKeys = assign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (has(shapeTypes, key) && typeof checker !== 'function') {
return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker));
}
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// falsy value can't be a Symbol
if (!propValue) {
return false;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
return factoryWithTypeCheckers;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var factoryWithThrowingShims;
var hasRequiredFactoryWithThrowingShims;
function requireFactoryWithThrowingShims () {
if (hasRequiredFactoryWithThrowingShims) return factoryWithThrowingShims;
hasRequiredFactoryWithThrowingShims = 1;
var ReactPropTypesSecret = /*@__PURE__*/ requireReactPropTypesSecret();
function emptyFunction() {}
function emptyFunctionWithReset() {}
emptyFunctionWithReset.resetWarningCache = emptyFunction;
factoryWithThrowingShims = function() {
function shim(props, propName, componentName, location, propFullName, secret) {
if (secret === ReactPropTypesSecret) {
// It is still safe when called from React.
return;
}
var err = new Error(
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use PropTypes.checkPropTypes() to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
err.name = 'Invariant Violation';
throw err;
} shim.isRequired = shim;
function getShim() {
return shim;
} // Important!
// Keep this list in sync with production version in `./factoryWithTypeCheckers.js`.
var ReactPropTypes = {
array: shim,
bigint: shim,
bool: shim,
func: shim,
number: shim,
object: shim,
string: shim,
symbol: shim,
any: shim,
arrayOf: getShim,
element: shim,
elementType: shim,
instanceOf: getShim,
node: shim,
objectOf: getShim,
oneOf: getShim,
oneOfType: getShim,
shape: getShim,
exact: getShim,
checkPropTypes: emptyFunctionWithReset,
resetWarningCache: emptyFunction
};
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
return factoryWithThrowingShims;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredPropTypes;
function requirePropTypes () {
if (hasRequiredPropTypes) return propTypes.exports;
hasRequiredPropTypes = 1;
if (process.env.NODE_ENV !== 'production') {
var ReactIs = requireReactIs$1();
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
propTypes.exports = /*@__PURE__*/ requireFactoryWithTypeCheckers()(ReactIs.isElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
propTypes.exports = /*@__PURE__*/ requireFactoryWithThrowingShims()();
}
return propTypes.exports;
}
var propTypesExports = /*@__PURE__*/ requirePropTypes();
var PropTypes = /*@__PURE__*/getDefaultExportFromCjs(propTypesExports);
/**
* @mui/styled-engine v6.5.0
*
* @license MIT
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-underscore-dangle */
function styled(tag, options) {
const stylesFactory = emStyled(tag, options);
if (process.env.NODE_ENV !== 'production') {
return (...styles) => {
const component = `"${tag}"` ;
if (styles.length === 0) {
console.error([`MUI: Seems like you called \`styled(${component})()\` without a \`style\` argument.`, 'You must provide a `styles` argument: `styled("div")(styleYouForgotToPass)`.'].join('\n'));
} else if (styles.some(style => style === undefined)) {
console.error(`MUI: the styled(${component})(...args) API requires all its args to be defined.`);
}
return stylesFactory(...styles);
};
}
return stylesFactory;
}
var reactIs = {exports: {}};
var reactIs_production = {};
/**
* @license React
* react-is.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_production;
function requireReactIs_production () {
if (hasRequiredReactIs_production) return reactIs_production;
hasRequiredReactIs_production = 1;
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"),
REACT_PORTAL_TYPE = Symbol.for("react.portal"),
REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
REACT_PROFILER_TYPE = Symbol.for("react.profiler");
var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
REACT_CONTEXT_TYPE = Symbol.for("react.context"),
REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"),
REACT_MEMO_TYPE = Symbol.for("react.memo"),
REACT_LAZY_TYPE = Symbol.for("react.lazy"),
REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"),
REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference");
function typeOf(object) {
if ("object" === typeof object && null !== object) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
switch (((object = object.type), object)) {
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
case REACT_SUSPENSE_LIST_TYPE:
case REACT_VIEW_TRANSITION_TYPE:
return object;
default:
switch (((object = object && object.$$typeof), object)) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
return object;
case REACT_CONSUMER_TYPE:
return object;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
}
reactIs_production.ContextConsumer = REACT_CONSUMER_TYPE;
reactIs_production.ContextProvider = REACT_CONTEXT_TYPE;
reactIs_production.Element = REACT_ELEMENT_TYPE;
reactIs_production.ForwardRef = REACT_FORWARD_REF_TYPE;
reactIs_production.Fragment = REACT_FRAGMENT_TYPE;
reactIs_production.Lazy = REACT_LAZY_TYPE;
reactIs_production.Memo = REACT_MEMO_TYPE;
reactIs_production.Portal = REACT_PORTAL_TYPE;
reactIs_production.Profiler = REACT_PROFILER_TYPE;
reactIs_production.StrictMode = REACT_STRICT_MODE_TYPE;
reactIs_production.Suspense = REACT_SUSPENSE_TYPE;
reactIs_production.SuspenseList = REACT_SUSPENSE_LIST_TYPE;
reactIs_production.isContextConsumer = function (object) {
return typeOf(object) === REACT_CONSUMER_TYPE;
};
reactIs_production.isContextProvider = function (object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
};
reactIs_production.isElement = function (object) {
return (
"object" === typeof object &&
null !== object &&
object.$$typeof === REACT_ELEMENT_TYPE
);
};
reactIs_production.isForwardRef = function (object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
};
reactIs_production.isFragment = function (object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
};
reactIs_production.isLazy = function (object) {
return typeOf(object) === REACT_LAZY_TYPE;
};
reactIs_production.isMemo = function (object) {
return typeOf(object) === REACT_MEMO_TYPE;
};
reactIs_production.isPortal = function (object) {
return typeOf(object) === REACT_PORTAL_TYPE;
};
reactIs_production.isProfiler = function (object) {
return typeOf(object) === REACT_PROFILER_TYPE;
};
reactIs_production.isStrictMode = function (object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
};
reactIs_production.isSuspense = function (object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
};
reactIs_production.isSuspenseList = function (object) {
return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
};
reactIs_production.isValidElementType = function (type) {
return "string" === typeof type ||
"function" === typeof type ||
type === REACT_FRAGMENT_TYPE ||
type === REACT_PROFILER_TYPE ||
type === REACT_STRICT_MODE_TYPE ||
type === REACT_SUSPENSE_TYPE ||
type === REACT_SUSPENSE_LIST_TYPE ||
("object" === typeof type &&
null !== type &&
(type.$$typeof === REACT_LAZY_TYPE ||
type.$$typeof === REACT_MEMO_TYPE ||
type.$$typeof === REACT_CONTEXT_TYPE ||
type.$$typeof === REACT_CONSUMER_TYPE ||
type.$$typeof === REACT_FORWARD_REF_TYPE ||
type.$$typeof === REACT_CLIENT_REFERENCE ||
void 0 !== type.getModuleId))
? true
: false;
};
reactIs_production.typeOf = typeOf;
return reactIs_production;
}
var reactIs_development = {};
/**
* @license React
* react-is.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var hasRequiredReactIs_development;
function requireReactIs_development () {
if (hasRequiredReactIs_development) return reactIs_development;
hasRequiredReactIs_development = 1;
"production" !== process.env.NODE_ENV &&
(function () {
function typeOf(object) {
if ("object" === typeof object && null !== object) {
var $$typeof = object.$$typeof;
switch ($$typeof) {
case REACT_ELEMENT_TYPE:
switch (((object = object.type), object)) {
case REACT_FRAGMENT_TYPE:
case REACT_PROFILER_TYPE:
case REACT_STRICT_MODE_TYPE:
case REACT_SUSPENSE_TYPE:
case REACT_SUSPENSE_LIST_TYPE:
case REACT_VIEW_TRANSITION_TYPE:
return object;
default:
switch (((object = object && object.$$typeof), object)) {
case REACT_CONTEXT_TYPE:
case REACT_FORWARD_REF_TYPE:
case REACT_LAZY_TYPE:
case REACT_MEMO_TYPE:
return object;
case REACT_CONSUMER_TYPE:
return object;
default:
return $$typeof;
}
}
case REACT_PORTAL_TYPE:
return $$typeof;
}
}
}
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"),
REACT_PORTAL_TYPE = Symbol.for("react.portal"),
REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
REACT_PROFILER_TYPE = Symbol.for("react.profiler");
var REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
REACT_CONTEXT_TYPE = Symbol.for("react.context"),
REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"),
REACT_MEMO_TYPE = Symbol.for("react.memo"),
REACT_LAZY_TYPE = Symbol.for("react.lazy"),
REACT_VIEW_TRANSITION_TYPE = Symbol.for("react.view_transition"),
REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference");
reactIs_development.ContextConsumer = REACT_CONSUMER_TYPE;
reactIs_development.ContextProvider = REACT_CONTEXT_TYPE;
reactIs_development.Element = REACT_ELEMENT_TYPE;
reactIs_development.ForwardRef = REACT_FORWARD_REF_TYPE;
reactIs_development.Fragment = REACT_FRAGMENT_TYPE;
reactIs_development.Lazy = REACT_LAZY_TYPE;
reactIs_development.Memo = REACT_MEMO_TYPE;
reactIs_development.Portal = REACT_PORTAL_TYPE;
reactIs_development.Profiler = REACT_PROFILER_TYPE;
reactIs_development.StrictMode = REACT_STRICT_MODE_TYPE;
reactIs_development.Suspense = REACT_SUSPENSE_TYPE;
reactIs_development.SuspenseList = REACT_SUSPENSE_LIST_TYPE;
reactIs_development.isContextConsumer = function (object) {
return typeOf(object) === REACT_CONSUMER_TYPE;
};
reactIs_development.isContextProvider = function (object) {
return typeOf(object) === REACT_CONTEXT_TYPE;
};
reactIs_development.isElement = function (object) {
return (
"object" === typeof object &&
null !== object &&
object.$$typeof === REACT_ELEMENT_TYPE
);
};
reactIs_development.isForwardRef = function (object) {
return typeOf(object) === REACT_FORWARD_REF_TYPE;
};
reactIs_development.isFragment = function (object) {
return typeOf(object) === REACT_FRAGMENT_TYPE;
};
reactIs_development.isLazy = function (object) {
return typeOf(object) === REACT_LAZY_TYPE;
};
reactIs_development.isMemo = function (object) {
return typeOf(object) === REACT_MEMO_TYPE;
};
reactIs_development.isPortal = function (object) {
return typeOf(object) === REACT_PORTAL_TYPE;
};
reactIs_development.isProfiler = function (object) {
return typeOf(object) === REACT_PROFILER_TYPE;
};
reactIs_development.isStrictMode = function (object) {
return typeOf(object) === REACT_STRICT_MODE_TYPE;
};
reactIs_development.isSuspense = function (object) {
return typeOf(object) === REACT_SUSPENSE_TYPE;
};
reactIs_development.isSuspenseList = function (object) {
return typeOf(object) === REACT_SUSPENSE_LIST_TYPE;
};
reactIs_development.isValidElementType = function (type) {
return "string" === typeof type ||
"function" === typeof type ||
type === REACT_FRAGMENT_TYPE ||
type === REACT_PROFILER_TYPE ||
type === REACT_STRICT_MODE_TYPE ||
type === REACT_SUSPENSE_TYPE ||
type === REACT_SUSPENSE_LIST_TYPE ||
("object" === typeof type &&
null !== type &&
(type.$$typeof === REACT_LAZY_TYPE ||
type.$$typeof === REACT_MEMO_TYPE ||
type.$$typeof === REACT_CONTEXT_TYPE ||
type.$$typeof === REACT_CONSUMER_TYPE ||
type.$$typeof === REACT_FORWARD_REF_TYPE ||
type.$$typeof === REACT_CLIENT_REFERENCE ||
void 0 !== type.getModuleId))
? true
: false;
};
reactIs_development.typeOf = typeOf;
})();
return reactIs_development;
}
var hasRequiredReactIs;
function requireReactIs () {
if (hasRequiredReactIs) return reactIs.exports;
hasRequiredReactIs = 1;
if (process.env.NODE_ENV === 'production') {
reactIs.exports = /*@__PURE__*/ requireReactIs_production();
} else {
reactIs.exports = /*@__PURE__*/ requireReactIs_development();
}
return reactIs.exports;
}
var reactIsExports = /*@__PURE__*/ requireReactIs();
// https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
function isPlainObject(item) {
if (typeof item !== 'object' || item === null) {
return false;
}
const prototype = Object.getPrototypeOf(item);
return (prototype === null || prototype === Object.prototype || Object.getPrototypeOf(prototype) === null) && !(Symbol.toStringTag in item) && !(Symbol.iterator in item);
}
function deepClone(source) {
if (/*#__PURE__*/React__namespace.isValidElement(source) || reactIsExports.isValidElementType(source) || !isPlainObject(source)) {
return source;
}
const output = {};
Object.keys(source).forEach(key => {
output[key] = deepClone(source[key]);
});
return output;
}
/**
* Merge objects deeply.
* It will shallow copy React elements.
*
* If `options.clone` is set to `false` the source object will be merged directly into the target object.
*
* @example
* ```ts
* deepmerge({ a: { b: 1 }, d: 2 }, { a: { c: 2 }, d: 4 });
* // => { a: { b: 1, c: 2 }, d: 4 }
* ````
*
* @param target The target object.
* @param source The source object.
* @param options The merge options.
* @param options.clone Set to `false` to merge the source object directly into the target object.
* @returns The merged object.
*/
function deepmerge(target, source, options = {
clone: true
}) {
const output = options.clone ? {
...target
} : target;
if (isPlainObject(target) && isPlainObject(source)) {
Object.keys(source).forEach(key => {
if (/*#__PURE__*/React__namespace.isValidElement(source[key]) || reactIsExports.isValidElementType(source[key])) {
output[key] = source[key];
} else if (isPlainObject(source[key]) &&
// Avoid prototype pollution
Object.prototype.hasOwnProperty.call(target, key) && isPlainObject(target[key])) {
// Since `output` is a clone of `target` and we have narrowed `target` in this block we can cast to the same type.
output[key] = deepmerge(target[key], source[key], options);
} else if (options.clone) {
output[key] = isPlainObject(source[key]) ? deepClone(source[key]) : source[key];
} else {
output[key] = source[key];
}
});
}
return output;
}
// Sorted ASC by size. That's important.
// It can't be configured as it's used statically for propTypes.
const sortBreakpointsValues = values => {
const breakpointsAsArray = Object.keys(values).map(key => ({
key,
val: values[key]
})) || [];
// Sort in ascending order
breakpointsAsArray.sort((breakpoint1, breakpoint2) => breakpoint1.val - breakpoint2.val);
return breakpointsAsArray.reduce((acc, obj) => {
return {
...acc,
[obj.key]: obj.val
};
}, {});
};
// Keep in mind that @media is inclusive by the CSS specification.
function createBreakpoints(breakpoints) {
const {
// The breakpoint **start** at this value.
// For instance with the first breakpoint xs: [xs, sm).
values = {
xs: 0,
// phone
sm: 600,
// tablet
md: 900,
// small laptop
lg: 1200,
// desktop
xl: 1536 // large screen
},
unit = 'px',
step = 5,
...other
} = breakpoints;
const sortedValues = sortBreakpointsValues(values);
const keys = Object.keys(sortedValues);
function up(key) {
const value = typeof values[key] === 'number' ? values[key] : key;
return `@media (min-width:${value}${unit})`;
}
function down(key) {
const value = typeof values[key] === 'number' ? values[key] : key;
return `@media (max-width:${value - step / 100}${unit})`;
}
function between(start, end) {
const endIndex = keys.indexOf(end);
return `@media (min-width:${typeof values[start] === 'number' ? values[start] : start}${unit}) and ` + `(max-width:${(endIndex !== -1 && typeof values[keys[endIndex]] === 'number' ? values[keys[endIndex]] : end) - step / 100}${unit})`;
}
function only(key) {
if (keys.indexOf(key) + 1 < keys.length) {
return between(key, keys[keys.indexOf(key) + 1]);
}
return up(key);
}
function not(key) {
// handle first and last key separately, for better readability
const keyIndex = keys.indexOf(key);
if (keyIndex === 0) {
return up(keys[1]);
}
if (keyIndex === keys.length - 1) {
return down(keys[keyIndex]);
}
return between(key, keys[keys.indexOf(key) + 1]).replace('@media', '@media not all and');
}
return {
keys,
values: sortedValues,
up,
down,
between,
only,
not,
unit,
...other
};
}
/**
* For using in `sx` prop to sort the breakpoint from low to high.
* Note: this function does not work and will not support multiple units.
* e.g. input: { '@container (min-width:300px)': '1rem', '@container (min-width:40rem)': '2rem' }
* output: { '@container (min-width:40rem)': '2rem', '@container (min-width:300px)': '1rem' } // since 40 < 300 eventhough 40rem > 300px
*/
function sortContainerQueries(theme, css) {
if (!theme.containerQueries) {
return css;
}
const sorted = Object.keys(css).filter(key => key.startsWith('@container')).sort((a, b) => {
const regex = /min-width:\s*([0-9.]+)/;
return +(a.match(regex)?.[1] || 0) - +(b.match(regex)?.[1] || 0);
});
if (!sorted.length) {
return css;
}
return sorted.reduce((acc, key) => {
const value = css[key];
delete acc[key];
acc[key] = value;
return acc;
}, {
...css
});
}
function isCqShorthand(breakpointKeys, value) {
return value === '@' || value.startsWith('@') && (breakpointKeys.some(key => value.startsWith(`@${key}`)) || !!value.match(/^@\d/));
}
function getContainerQuery(theme, shorthand) {
const matches = shorthand.match(/^@([^/]+)?\/?(.+)?$/);
if (!matches) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(process.env.NODE_ENV !== "production" ? `MUI: The provided shorthand ${`(${shorthand})`} is invalid. The format should be \`@<breakpoint | number>\` or \`@<breakpoint | number>/<container>\`.\n` + 'For example, `@sm` or `@600` or `@40rem/sidebar`.' : formatMuiErrorMessage(18, `(${shorthand})`));
}
return null;
}
const [, containerQuery, containerName] = matches;
const value = Number.isNaN(+containerQuery) ? containerQuery || 0 : +containerQuery;
return theme.containerQueries(containerName).up(value);
}
function cssContainerQueries(themeInput) {
const toContainerQuery = (mediaQuery, name) => mediaQuery.replace('@media', name ? `@container ${name}` : '@container');
function attachCq(node, name) {
node.up = (...args) => toContainerQuery(themeInput.breakpoints.up(...args), name);
node.down = (...args) => toContainerQuery(themeInput.breakpoints.down(...args), name);
node.between = (...args) => toContainerQuery(themeInput.breakpoints.between(...args), name);
node.only = (...args) => toContainerQuery(themeInput.breakpoints.only(...args), name);
node.not = (...args) => {
const result = toContainerQuery(themeInput.breakpoints.not(...args), name);
if (result.includes('not all and')) {
// `@container` does not work with `not all and`, so need to invert the logic
return result.replace('not all and ', '').replace('min-width:', 'width<').replace('max-width:', 'width>').replace('and', 'or');
}
return result;
};
}
const node = {};
const containerQueries = name => {
attachCq(node, name);
return node;
};
attachCq(containerQueries);
return {
...themeInput,
containerQueries
};
}
const shape = {
borderRadius: 4
};
const responsivePropType = process.env.NODE_ENV !== 'production' ? PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.object, PropTypes.array]) : {};
function merge(acc, item) {
if (!item) {
return acc;
}
return deepmerge(acc, item, {
clone: false // No need to clone deep, it's way faster.
});
}
// The breakpoint **start** at this value.
// For instance with the first breakpoint xs: [xs, sm[.
const values = {
xs: 0,
// phone
sm: 600,
// tablet
md: 900,
// small laptop
lg: 1200,
// desktop
xl: 1536 // large screen
};
const defaultBreakpoints = {
// Sorted ASC by size. That's important.
// It can't be configured as it's used statically for propTypes.
keys: ['xs', 'sm', 'md', 'lg', 'xl'],
up: key => `@media (min-width:${values[key]}px)`
};
const defaultContainerQueries = {
containerQueries: containerName => ({
up: key => {
let result = typeof key === 'number' ? key : values[key] || key;
if (typeof result === 'number') {
result = `${result}px`;
}
return containerName ? `@container ${containerName} (min-width:${result})` : `@container (min-width:${result})`;
}
})
};
function handleBreakpoints(props, propValue, styleFromPropValue) {
const theme = props.theme || {};
if (Array.isArray(propValue)) {
const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
return propValue.reduce((acc, item, index) => {
acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);
return acc;
}, {});
}
if (typeof propValue === 'object') {
const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
return Object.keys(propValue).reduce((acc, breakpoint) => {
if (isCqShorthand(themeBreakpoints.keys, breakpoint)) {
const containerKey = getContainerQuery(theme.containerQueries ? theme : defaultContainerQueries, breakpoint);
if (containerKey) {
acc[containerKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
}
}
// key is breakpoint
else if (Object.keys(themeBreakpoints.values || values).includes(breakpoint)) {
const mediaKey = themeBreakpoints.up(breakpoint);
acc[mediaKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
} else {
const cssKey = breakpoint;
acc[cssKey] = propValue[cssKey];
}
return acc;
}, {});
}
const output = styleFromPropValue(propValue);
return output;
}
function createEmptyBreakpointObject(breakpointsInput = {}) {
const breakpointsInOrder = breakpointsInput.keys?.reduce((acc, key) => {
const breakpointStyleKey = breakpointsInput.up(key);
acc[breakpointStyleKey] = {};
return acc;
}, {});
return breakpointsInOrder || {};
}
function removeUnusedBreakpoints(breakpointKeys, style) {
return breakpointKeys.reduce((acc, key) => {
const breakpointOutput = acc[key];
const isBreakpointUnused = !breakpointOutput || Object.keys(breakpointOutput).length === 0;
if (isBreakpointUnused) {
delete acc[key];
}
return acc;
}, style);
}
// It should to be noted that this function isn't equivalent to `text-transform: capitalize`.
//
// A strict capitalization should uppercase the first letter of each word in the sentence.
// We only handle the first word.
function capitalize(string) {
if (typeof string !== 'string') {
throw new Error(process.env.NODE_ENV !== "production" ? 'MUI: `capitalize(string)` expects a string argument.' : formatMuiErrorMessage(7));
}
return string.charAt(0).toUpperCase() + string.slice(1);
}
function getPath(obj, path, checkVars = true) {
if (!path || typeof path !== 'string') {
return null;
}
// Check if CSS variables are used
if (obj && obj.vars && checkVars) {
const val = `vars.${path}`.split('.').reduce((acc, item) => acc && acc[item] ? acc[item] : null, obj);
if (val != null) {
return val;
}
}
return path.split('.').reduce((acc, item) => {
if (acc && acc[item] != null) {
return acc[item];
}
return null;
}, obj);
}
function getStyleValue(themeMapping, transform, propValueFinal, userValue = propValueFinal) {
let value;
if (typeof themeMapping === 'function') {
value = themeMapping(propValueFinal);
} else if (Array.isArray(themeMapping)) {
value = themeMapping[propValueFinal] || userValue;
} else {
value = getPath(themeMapping, propValueFinal) || userValue;
}
if (transform) {
value = transform(value, userValue, themeMapping);
}
return value;
}
function style$1(options) {
const {
prop,
cssProperty = options.prop,
themeKey,
transform
} = options;
// false positive
// eslint-disable-next-line react/function-component-definition
const fn = props => {
if (props[prop] == null) {
return null;
}
const propValue = props[prop];
const theme = props.theme;
const themeMapping = getPath(theme, themeKey) || {};
const styleFromPropValue = propValueFinal => {
let value = getStyleValue(themeMapping, transform, propValueFinal);
if (propValueFinal === value && typeof propValueFinal === 'string') {
// Haven't found value
value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal);
}
if (cssProperty === false) {
return value;
}
return {
[cssProperty]: value
};
};
return handleBreakpoints(props, propValue, styleFromPropValue);
};
fn.propTypes = process.env.NODE_ENV !== 'production' ? {
[prop]: responsivePropType
} : {};
fn.filterProps = [prop];
return fn;
}
function memoize(fn) {
const cache = {};
return arg => {
if (cache[arg] === undefined) {
cache[arg] = fn(arg);
}
return cache[arg];
};
}
const properties = {
m: 'margin',
p: 'padding'
};
const directions = {
t: 'Top',
r: 'Right',
b: 'Bottom',
l: 'Left',
x: ['Left', 'Right'],
y: ['Top', 'Bottom']
};
const aliases = {
marginX: 'mx',
marginY: 'my',
paddingX: 'px',
paddingY: 'py'
};
// memoize() impact:
// From 300,000 ops/sec
// To 350,000 ops/sec
const getCssProperties = memoize(prop => {
// It's not a shorthand notation.
if (prop.length > 2) {
if (aliases[prop]) {
prop = aliases[prop];
} else {
return [prop];
}
}
const [a, b] = prop.split('');
const property = properties[a];
const direction = directions[b] || '';
return Array.isArray(direction) ? direction.map(dir => property + dir) : [property + direction];
});
const marginKeys = ['m', 'mt', 'mr', 'mb', 'ml', 'mx', 'my', 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'marginX', 'marginY', 'marginInline', 'marginInlineStart', 'marginInlineEnd', 'marginBlock', 'marginBlockStart', 'marginBlockEnd'];
const paddingKeys = ['p', 'pt', 'pr', 'pb', 'pl', 'px', 'py', 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'paddingX', 'paddingY', 'paddingInline', 'paddingInlineStart', 'paddingInlineEnd', 'paddingBlock', 'paddingBlockStart', 'paddingBlockEnd'];
const spacingKeys = [...marginKeys, ...paddingKeys];
function createUnaryUnit(theme, themeKey, defaultValue, propName) {
const themeSpacing = getPath(theme, themeKey, true) ?? defaultValue;
if (typeof themeSpacing === 'number' || typeof themeSpacing === 'string') {
return val => {
if (typeof val === 'string') {
return val;
}
if (process.env.NODE_ENV !== 'production') {
if (typeof val !== 'number') {
console.error(`MUI: Expected ${propName} argument to be a number or a string, got ${val}.`);
}
}
if (typeof themeSpacing === 'string') {
return `calc(${val} * ${themeSpacing})`;
}
return themeSpacing * val;
};
}
if (Array.isArray(themeSpacing)) {
return val => {
if (typeof val === 'string') {
return val;
}
const abs = Math.abs(val);
if (process.env.NODE_ENV !== 'production') {
if (!Number.isInteger(abs)) {
console.error([`MUI: The \`theme.${themeKey}\` array type cannot be combined with non integer values.` + `You should either use an integer value that can be used as index, or define the \`theme.${themeKey}\` as a number.`].join('\n'));
} else if (abs > themeSpacing.length - 1) {
console.error([`MUI: The value provided (${abs}) overflows.`, `The supported values are: ${JSON.stringify(themeSpacing)}.`, `${abs} > ${themeSpacing.length - 1}, you need to add the missing values.`].join('\n'));
}
}
const transformed = themeSpacing[abs];
if (val >= 0) {
return transformed;
}
if (typeof transformed === 'number') {
return -transformed;
}
return `-${transformed}`;
};
}
if (typeof themeSpacing === 'function') {
return themeSpacing;
}
if (process.env.NODE_ENV !== 'production') {
console.error([`MUI: The \`theme.${themeKey}\` value (${themeSpacing}) is invalid.`, 'It should be a number, an array or a function.'].join('\n'));
}
return () => undefined;
}
function createUnarySpacing(theme) {
return createUnaryUnit(theme, 'spacing', 8, 'spacing');
}
function getValue(transformer, propValue) {
if (typeof propValue === 'string' || propValue == null) {
return propValue;
}
return transformer(propValue);
}
function getStyleFromPropValue(cssProperties, transformer) {
return propValue => cssProperties.reduce((acc, cssProperty) => {
acc[cssProperty] = getValue(transformer, propValue);
return acc;
}, {});
}
function resolveCssProperty(props, keys, prop, transformer) {
// Using a hash computation over an array iteration could be faster, but with only 28 items,
// it's doesn't worth the bundle size.
if (!keys.includes(prop)) {
return null;
}
const cssProperties = getCssProperties(prop);
const styleFromPropValue = getStyleFromPropValue(cssProperties, transformer);
const propValue = props[prop];
return handleBreakpoints(props, propValue, styleFromPropValue);
}
function style(props, keys) {
const transformer = createUnarySpacing(props.theme);
return Object.keys(props).map(prop => resolveCssProperty(props, keys, prop, transformer)).reduce(merge, {});
}
function margin(props) {
return style(props, marginKeys);
}
margin.propTypes = process.env.NODE_ENV !== 'production' ? marginKeys.reduce((obj, key) => {
obj[key] = responsivePropType;
return obj;
}, {}) : {};
margin.filterProps = marginKeys;
function padding(props) {
return style(props, paddingKeys);
}
padding.propTypes = process.env.NODE_ENV !== 'production' ? paddingKeys.reduce((obj, key) => {
obj[key] = responsivePropType;
return obj;
}, {}) : {};
padding.filterProps = paddingKeys;
process.env.NODE_ENV !== 'production' ? spacingKeys.reduce((obj, key) => {
obj[key] = responsivePropType;
return obj;
}, {}) : {};
// The different signatures imply different meaning for their arguments that can't be expressed structurally.
// We express the difference with variable names.
function createSpacing(spacingInput = 8,
// Material Design layouts are visually balanced. Most measurements align to an 8dp grid, which aligns both spacing and the overall layout.
// Smaller components, such as icons, can align to a 4dp grid.
// https://m2.material.io/design/layout/understanding-layout.html
transform = createUnarySpacing({
spacing: spacingInput
})) {
// Already transformed.
if (spacingInput.mui) {
return spacingInput;
}
const spacing = (...argsInput) => {
if (process.env.NODE_ENV !== 'production') {
if (!(argsInput.length <= 4)) {
console.error(`MUI: Too many arguments provided, expected between 0 and 4, got ${argsInput.length}`);
}
}
const args = argsInput.length === 0 ? [1] : argsInput;
return args.map(argument => {
const output = transform(argument);
return typeof output === 'number' ? `${output}px` : output;
}).join(' ');
};
spacing.mui = true;
return spacing;
}
function compose(...styles) {
const handlers = styles.reduce((acc, style) => {
style.filterProps.forEach(prop => {
acc[prop] = style;
});
return acc;
}, {});
// false positive
// eslint-disable-next-line react/function-component-definition
const fn = props => {
return Object.keys(props).reduce((acc, prop) => {
if (handlers[prop]) {
return merge(acc, handlers[prop](props));
}
return acc;
}, {});
};
fn.propTypes = process.env.NODE_ENV !== 'production' ? styles.reduce((acc, style) => Object.assign(acc, style.propTypes), {}) : {};
fn.filterProps = styles.reduce((acc, style) => acc.concat(style.filterProps), []);
return fn;
}
function borderTransform(value) {
if (typeof value !== 'number') {
return value;
}
return `${value}px solid`;
}
function createBorderStyle(prop, transform) {
return style$1({
prop,
themeKey: 'borders',
transform
});
}
const border = createBorderStyle('border', borderTransform);
const borderTop = createBorderStyle('borderTop', borderTransform);
const borderRight = createBorderStyle('borderRight', borderTransform);
const borderBottom = createBorderStyle('borderBottom', borderTransform);
const borderLeft = createBorderStyle('borderLeft', borderTransform);
const borderColor = createBorderStyle('borderColor');
const borderTopColor = createBorderStyle('borderTopColor');
const borderRightColor = createBorderStyle('borderRightColor');
const borderBottomColor = createBorderStyle('borderBottomColor');
const borderLeftColor = createBorderStyle('borderLeftColor');
const outline = createBorderStyle('outline', borderTransform);
const outlineColor = createBorderStyle('outlineColor');
// false positive
// eslint-disable-next-line react/function-component-definition
const borderRadius = props => {
if (props.borderRadius !== undefined && props.borderRadius !== null) {
const transformer = createUnaryUnit(props.theme, 'shape.borderRadius', 4, 'borderRadius');
const styleFromPropValue = propValue => ({
borderRadius: getValue(transformer, propValue)
});
return handleBreakpoints(props, props.borderRadius, styleFromPropValue);
}
return null;
};
borderRadius.propTypes = process.env.NODE_ENV !== 'production' ? {
borderRadius: responsivePropType
} : {};
borderRadius.filterProps = ['borderRadius'];
compose(border, borderTop, borderRight, borderBottom, borderLeft, borderColor, borderTopColor, borderRightColor, borderBottomColor, borderLeftColor, borderRadius, outline, outlineColor);
// false positive
// eslint-disable-next-line react/function-component-definition
const gap = props => {
if (props.gap !== undefined && props.gap !== null) {
const transformer = createUnaryUnit(props.theme, 'spacing', 8, 'gap');
const styleFromPropValue = propValue => ({
gap: getValue(transformer, propValue)
});
return handleBreakpoints(props, props.gap, styleFromPropValue);
}
return null;
};
gap.propTypes = process.env.NODE_ENV !== 'production' ? {
gap: responsivePropType
} : {};
gap.filterProps = ['gap'];
// false positive
// eslint-disable-next-line react/function-component-definition
const columnGap = props => {
if (props.columnGap !== undefined && props.columnGap !== null) {
const transformer = createUnaryUnit(props.theme, 'spacing', 8, 'columnGap');
const styleFromPropValue = propValue => ({
columnGap: getValue(transformer, propValue)
});
return handleBreakpoints(props, props.columnGap, styleFromPropValue);
}
return null;
};
columnGap.propTypes = process.env.NODE_ENV !== 'production' ? {
columnGap: responsivePropType
} : {};
columnGap.filterProps = ['columnGap'];
// false positive
// eslint-disable-next-line react/function-component-definition
const rowGap = props => {
if (props.rowGap !== undefined && props.rowGap !== null) {
const transformer = createUnaryUnit(props.theme, 'spacing', 8, 'rowGap');
const styleFromPropValue = propValue => ({
rowGap: getValue(transformer, propValue)
});
return handleBreakpoints(props, props.rowGap, styleFromPropValue);
}
return null;
};
rowGap.propTypes = process.env.NODE_ENV !== 'production' ? {
rowGap: responsivePropType
} : {};
rowGap.filterProps = ['rowGap'];
const gridColumn = style$1({
prop: 'gridColumn'
});
const gridRow = style$1({
prop: 'gridRow'
});
const gridAutoFlow = style$1({
prop: 'gridAutoFlow'
});
const gridAutoColumns = style$1({
prop: 'gridAutoColumns'
});
const gridAutoRows = style$1({
prop: 'gridAutoRows'
});
const gridTemplateColumns = style$1({
prop: 'gridTemplateColumns'
});
const gridTemplateRows = style$1({
prop: 'gridTemplateRows'
});
const gridTemplateAreas = style$1({
prop: 'gridTemplateAreas'
});
const gridArea = style$1({
prop: 'gridArea'
});
compose(gap, columnGap, rowGap, gridColumn, gridRow, gridAutoFlow, gridAutoColumns, gridAutoRows, gridTemplateColumns, gridTemplateRows, gridTemplateAreas, gridArea);
function paletteTransform(value, userValue) {
if (userValue === 'grey') {
return userValue;
}
return value;
}
const color = style$1({
prop: 'color',
themeKey: 'palette',
transform: paletteTransform
});
const bgcolor = style$1({
prop: 'bgcolor',
cssProperty: 'backgroundColor',
themeKey: 'palette',
transform: paletteTransform
});
const backgroundColor = style$1({
prop: 'backgroundColor',
themeKey: 'palette',
transform: paletteTransform
});
compose(color, bgcolor, backgroundColor);
function sizingTransform(value) {
return value <= 1 && value !== 0 ? `${value * 100}%` : value;
}
const width = style$1({
prop: 'width',
transform: sizingTransform
});
const maxWidth = props => {
if (props.maxWidth !== undefined && props.maxWidth !== null) {
const styleFromPropValue = propValue => {
const breakpoint = props.theme?.breakpoints?.values?.[propValue] || values[propValue];
if (!breakpoint) {
return {
maxWidth: sizingTransform(propValue)
};
}
if (props.theme?.breakpoints?.unit !== 'px') {
return {
maxWidth: `${breakpoint}${props.theme.breakpoints.unit}`
};
}
return {
maxWidth: breakpoint
};
};
return handleBreakpoints(props, props.maxWidth, styleFromPropValue);
}
return null;
};
maxWidth.filterProps = ['maxWidth'];
const minWidth = style$1({
prop: 'minWidth',
transform: sizingTransform
});
const height = style$1({
prop: 'height',
transform: sizingTransform
});
const maxHeight = style$1({
prop: 'maxHeight',
transform: sizingTransform
});
const minHeight = style$1({
prop: 'minHeight',
transform: sizingTransform
});
style$1({
prop: 'size',
cssProperty: 'width',
transform: sizingTransform
});
style$1({
prop: 'size',
cssProperty: 'height',
transform: sizingTransform
});
const boxSizing = style$1({
prop: 'boxSizing'
});
compose(width, maxWidth, minWidth, height, maxHeight, minHeight, boxSizing);
const defaultSxConfig = {
// borders
border: {
themeKey: 'borders',
transform: borderTransform
},
borderTop: {
themeKey: 'borders',
transform: borderTransform
},
borderRight: {
themeKey: 'borders',
transform: borderTransform
},
borderBottom: {
themeKey: 'borders',
transform: borderTransform
},
borderLeft: {
themeKey: 'borders',
transform: borderTransform
},
borderColor: {
themeKey: 'palette'
},
borderTopColor: {
themeKey: 'palette'
},
borderRightColor: {
themeKey: 'palette'
},
borderBottomColor: {
themeKey: 'palette'
},
borderLeftColor: {
themeKey: 'palette'
},
outline: {
themeKey: 'borders',
transform: borderTransform
},
outlineColor: {
themeKey: 'palette'
},
borderRadius: {
themeKey: 'shape.borderRadius',
style: borderRadius
},
// palette
color: {
themeKey: 'palette',
transform: paletteTransform
},
bgcolor: {
themeKey: 'palette',
cssProperty: 'backgroundColor',
transform: paletteTransform
},
backgroundColor: {
themeKey: 'palette',
transform: paletteTransform
},
// spacing
p: {
style: padding
},
pt: {
style: padding
},
pr: {
style: padding
},
pb: {
style: padding
},
pl: {
style: padding
},
px: {
style: padding
},
py: {
style: padding
},
padding: {
style: padding
},
paddingTop: {
style: padding
},
paddingRight: {
style: padding
},
paddingBottom: {
style: padding
},
paddingLeft: {
style: padding
},
paddingX: {
style: padding
},
paddingY: {
style: padding
},
paddingInline: {
style: padding
},
paddingInlineStart: {
style: padding
},
paddingInlineEnd: {
style: padding
},
paddingBlock: {
style: padding
},
paddingBlockStart: {
style: padding
},
paddingBlockEnd: {
style: padding
},
m: {
style: margin
},
mt: {
style: margin
},
mr: {
style: margin
},
mb: {
style: margin
},
ml: {
style: margin
},
mx: {
style: margin
},
my: {
style: margin
},
margin: {
style: margin
},
marginTop: {
style: margin
},
marginRight: {
style: margin
},
marginBottom: {
style: margin
},
marginLeft: {
style: margin
},
marginX: {
style: margin
},
marginY: {
style: margin
},
marginInline: {
style: margin
},
marginInlineStart: {
style: margin
},
marginInlineEnd: {
style: margin
},
marginBlock: {
style: margin
},
marginBlockStart: {
style: margin
},
marginBlockEnd: {
style: margin
},
// display
displayPrint: {
cssProperty: false,
transform: value => ({
'@media print': {
display: value
}
})
},
display: {},
overflow: {},
textOverflow: {},
visibility: {},
whiteSpace: {},
// flexbox
flexBasis: {},
flexDirection: {},
flexWrap: {},
justifyContent: {},
alignItems: {},
alignContent: {},
order: {},
flex: {},
flexGrow: {},
flexShrink: {},
alignSelf: {},
justifyItems: {},
justifySelf: {},
// grid
gap: {
style: gap
},
rowGap: {
style: rowGap
},
columnGap: {
style: columnGap
},
gridColumn: {},
gridRow: {},
gridAutoFlow: {},
gridAutoColumns: {},
gridAutoRows: {},
gridTemplateColumns: {},
gridTemplateRows: {},
gridTemplateAreas: {},
gridArea: {},
// positions
position: {},
zIndex: {
themeKey: 'zIndex'
},
top: {},
right: {},
bottom: {},
left: {},
// shadows
boxShadow: {
themeKey: 'shadows'
},
// sizing
width: {
transform: sizingTransform
},
maxWidth: {
style: maxWidth
},
minWidth: {
transform: sizingTransform
},
height: {
transform: sizingTransform
},
maxHeight: {
transform: sizingTransform
},
minHeight: {
transform: sizingTransform
},
boxSizing: {},
// typography
font: {
themeKey: 'font'
},
fontFamily: {
themeKey: 'typography'
},
fontSize: {
themeKey: 'typography'
},
fontStyle: {
themeKey: 'typography'
},
fontWeight: {
themeKey: 'typography'
},
letterSpacing: {},
textTransform: {},
lineHeight: {},
textAlign: {},
typography: {
cssProperty: false,
themeKey: 'typography'
}
};
function objectsHaveSameKeys(...objects) {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
const union = new Set(allKeys);
return objects.every(object => union.size === Object.keys(object).length);
}
function callIfFn(maybeFn, arg) {
return typeof maybeFn === 'function' ? maybeFn(arg) : maybeFn;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
function unstable_createStyleFunctionSx() {
function getThemeValue(prop, val, theme, config) {
const props = {
[prop]: val,
theme
};
const options = config[prop];
if (!options) {
return {
[prop]: val
};
}
const {
cssProperty = prop,
themeKey,
transform,
style
} = options;
if (val == null) {
return null;
}
// TODO v6: remove, see https://github.com/mui/material-ui/pull/38123
if (themeKey === 'typography' && val === 'inherit') {
return {
[prop]: val
};
}
const themeMapping = getPath(theme, themeKey) || {};
if (style) {
return style(props);
}
const styleFromPropValue = propValueFinal => {
let value = getStyleValue(themeMapping, transform, propValueFinal);
if (propValueFinal === value && typeof propValueFinal === 'string') {
// Haven't found value
value = getStyleValue(themeMapping, transform, `${prop}${propValueFinal === 'default' ? '' : capitalize(propValueFinal)}`, propValueFinal);
}
if (cssProperty === false) {
return value;
}
return {
[cssProperty]: value
};
};
return handleBreakpoints(props, val, styleFromPropValue);
}
function styleFunctionSx(props) {
const {
sx,
theme = {},
nested
} = props || {};
if (!sx) {
return null; // Emotion & styled-components will neglect null
}
const config = theme.unstable_sxConfig ?? defaultSxConfig;
/*
* Receive `sxInput` as object or callback
* and then recursively check keys & values to create media query object styles.
* (the result will be used in `styled`)
*/
function traverse(sxInput) {
let sxObject = sxInput;
if (typeof sxInput === 'function') {
sxObject = sxInput(theme);
} else if (typeof sxInput !== 'object') {
// value
return sxInput;
}
if (!sxObject) {
return null;
}
const emptyBreakpoints = createEmptyBreakpointObject(theme.breakpoints);
const breakpointsKeys = Object.keys(emptyBreakpoints);
let css = emptyBreakpoints;
Object.keys(sxObject).forEach(styleKey => {
const value = callIfFn(sxObject[styleKey], theme);
if (value !== null && value !== undefined) {
if (typeof value === 'object') {
if (config[styleKey]) {
css = merge(css, getThemeValue(styleKey, value, theme, config));
} else {
const breakpointsValues = handleBreakpoints({
theme
}, value, x => ({
[styleKey]: x
}));
if (objectsHaveSameKeys(breakpointsValues, value)) {
css[styleKey] = styleFunctionSx({
sx: value,
theme,
nested: true
});
} else {
css = merge(css, breakpointsValues);
}
}
} else {
css = merge(css, getThemeValue(styleKey, value, theme, config));
}
}
});
if (!nested && theme.modularCssLayers) {
return {
'@layer sx': sortContainerQueries(theme, removeUnusedBreakpoints(breakpointsKeys, css))
};
}
return sortContainerQueries(theme, removeUnusedBreakpoints(breakpointsKeys, css));
}
return Array.isArray(sx) ? sx.map(traverse) : traverse(sx);
}
return styleFunctionSx;
}
const styleFunctionSx = unstable_createStyleFunctionSx();
styleFunctionSx.filterProps = ['sx'];
/**
* A universal utility to style components with multiple color modes. Always use it from the theme object.
* It works with:
* - [Basic theme](https://mui.com/material-ui/customization/dark-mode/)
* - [CSS theme variables](https://mui.com/material-ui/customization/css-theme-variables/overview/)
* - Zero-runtime engine
*
* Tips: Use an array over object spread and place `theme.applyStyles()` last.
*
* With the styled function:
* ✅ [{ background: '#e5e5e5' }, theme.applyStyles('dark', { background: '#1c1c1c' })]
* 🚫 { background: '#e5e5e5', ...theme.applyStyles('dark', { background: '#1c1c1c' })}
*
* With the sx prop:
* ✅ [{ background: '#e5e5e5' }, theme => theme.applyStyles('dark', { background: '#1c1c1c' })]
* 🚫 { background: '#e5e5e5', ...theme => theme.applyStyles('dark', { background: '#1c1c1c' })}
*
* @example
* 1. using with `styled`:
* ```jsx
* const Component = styled('div')(({ theme }) => [
* { background: '#e5e5e5' },
* theme.applyStyles('dark', {
* background: '#1c1c1c',
* color: '#fff',
* }),
* ]);
* ```
*
* @example
* 2. using with `sx` prop:
* ```jsx
* <Box sx={[
* { background: '#e5e5e5' },
* theme => theme.applyStyles('dark', {
* background: '#1c1c1c',
* color: '#fff',
* }),
* ]}
* />
* ```
*
* @example
* 3. theming a component:
* ```jsx
* extendTheme({
* components: {
* MuiButton: {
* styleOverrides: {
* root: ({ theme }) => [
* { background: '#e5e5e5' },
* theme.applyStyles('dark', {
* background: '#1c1c1c',
* color: '#fff',
* }),
* ],
* },
* }
* }
* })
*```
*/
function applyStyles(key, styles) {
// @ts-expect-error this is 'any' type
const theme = this;
if (theme.vars) {
if (!theme.colorSchemes?.[key] || typeof theme.getColorSchemeSelector !== 'function') {
return {};
}
// If CssVarsProvider is used as a provider, returns '*:where({selector}) &'
let selector = theme.getColorSchemeSelector(key);
if (selector === '&') {
return styles;
}
if (selector.includes('data-') || selector.includes('.')) {
// '*' is required as a workaround for Emotion issue (https://github.com/emotion-js/emotion/issues/2836)
selector = `*:where(${selector.replace(/\s*&$/, '')}) &`;
}
return {
[selector]: styles
};
}
if (theme.palette.mode === key) {
return styles;
}
return {};
}
function createTheme(options = {}, ...args) {
const {
breakpoints: breakpointsInput = {},
palette: paletteInput = {},
spacing: spacingInput,
shape: shapeInput = {},
...other
} = options;
const breakpoints = createBreakpoints(breakpointsInput);
const spacing = createSpacing(spacingInput);
let muiTheme = deepmerge({
breakpoints,
direction: 'ltr',
components: {},
// Inject component definitions.
palette: {
mode: 'light',
...paletteInput
},
spacing,
shape: {
...shape,
...shapeInput
}
}, other);
muiTheme = cssContainerQueries(muiTheme);
muiTheme.applyStyles = applyStyles;
muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);
muiTheme.unstable_sxConfig = {
...defaultSxConfig,
...other?.unstable_sxConfig
};
muiTheme.unstable_sx = function sx(props) {
return styleFunctionSx({
sx: props,
theme: this
});
};
return muiTheme;
}
function isObjectEmpty(obj) {
return Object.keys(obj).length === 0;
}
function useTheme$1(defaultTheme = null) {
const contextTheme = React__namespace.useContext(react.ThemeContext);
return !contextTheme || isObjectEmpty(contextTheme) ? defaultTheme : contextTheme;
}
const systemDefaultTheme = createTheme();
function useTheme(defaultTheme = systemDefaultTheme) {
return useTheme$1(defaultTheme);
}
const splitProps = props => {
const result = {
systemProps: {},
otherProps: {}
};
const config = props?.theme?.unstable_sxConfig ?? defaultSxConfig;
Object.keys(props).forEach(prop => {
if (config[prop]) {
result.systemProps[prop] = props[prop];
} else {
result.otherProps[prop] = props[prop];
}
});
return result;
};
function extendSxProp(props) {
const {
sx: inSx,
...other
} = props;
const {
systemProps,
otherProps
} = splitProps(other);
let finalSx;
if (Array.isArray(inSx)) {
finalSx = [systemProps, ...inSx];
} else if (typeof inSx === 'function') {
finalSx = (...args) => {
const result = inSx(...args);
if (!isPlainObject(result)) {
return systemProps;
}
return {
...systemProps,
...result
};
};
} else {
finalSx = {
...systemProps,
...inSx
};
}
return {
...otherProps,
sx: finalSx
};
}
const defaultGenerator = componentName => componentName;
const createClassNameGenerator = () => {
let generate = defaultGenerator;
return {
configure(generator) {
generate = generator;
},
generate(componentName) {
return generate(componentName);
},
reset() {
generate = defaultGenerator;
}
};
};
const ClassNameGenerator = createClassNameGenerator();
function r(e){var t,f,n="";if("string"==typeof e||"number"==typeof e)n+=e;else if("object"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f);}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}
function createBox(options = {}) {
const {
themeId,
defaultTheme,
defaultClassName = 'MuiBox-root',
generateClassName
} = options;
const BoxRoot = styled('div', {
shouldForwardProp: prop => prop !== 'theme' && prop !== 'sx' && prop !== 'as'
})(styleFunctionSx);
const Box = /*#__PURE__*/React__namespace.forwardRef(function Box(inProps, ref) {
const theme = useTheme(defaultTheme);
const {
className,
component = 'div',
...other
} = extendSxProp(inProps);
return /*#__PURE__*/jsxRuntime.jsx(BoxRoot, {
as: component,
ref: ref,
className: clsx(className, generateClassName ? generateClassName(defaultClassName) : defaultClassName),
theme: themeId ? theme[themeId] || theme : theme,
...other
});
});
return Box;
}
const globalStateClasses = {
active: 'active',
checked: 'checked',
completed: 'completed',
disabled: 'disabled',
error: 'error',
expanded: 'expanded',
focused: 'focused',
focusVisible: 'focusVisible',
open: 'open',
readOnly: 'readOnly',
required: 'required',
selected: 'selected'
};
function generateUtilityClass(componentName, slot, globalStatePrefix = 'Mui') {
const globalStateClass = globalStateClasses[slot];
return globalStateClass ? `${globalStatePrefix}-${globalStateClass}` : `${ClassNameGenerator.generate(componentName)}-${slot}`;
}
function generateUtilityClasses(componentName, slots, globalStatePrefix = 'Mui') {
const result = {};
slots.forEach(slot => {
result[slot] = generateUtilityClass(componentName, slot, globalStatePrefix);
});
return result;
}
const boxClasses = generateUtilityClasses('MuiBox', ['root']);
const Box = createBox({
defaultClassName: boxClasses.root,
generateClassName: ClassNameGenerator.generate
});
process.env.NODE_ENV !== "production" ? Box.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the d.ts file and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* @ignore
*/
children: PropTypes.node,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])
} : void 0;
const Pdf = ({
data
}) => {
const [isLoading, setIsLoading] = React.useState(true);
const handleLoad = React.useCallback(() => {
setIsLoading(false);
}, []);
return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
children: [isLoading && /*#__PURE__*/jsxRuntime.jsx(material.CircularProgress, {
size: 40,
sx: {
position: "fixed",
top: "50%",
left: "50%",
translate: "-50% -50%"
}
}), /*#__PURE__*/jsxRuntime.jsx("iframe", {
src: `https://docs.google.com/gview?url=${encodeURIComponent(data.url)}&embedded=true`,
width: "100%",
height: "600px",
style: {
border: "none"
},
onLoad: handleLoad
})]
});
};
const PdfPlaceholder = ({
sx,
containerSx
}) => {
const theme = material.useTheme();
return /*#__PURE__*/jsxRuntime.jsx(Box, {
sx: {
width: "100%",
height: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
...containerSx
},
children: /*#__PURE__*/jsxRuntime.jsx(PictureAsPdfIcon, {
sx: {
fontSize: "auto",
color: theme.palette.primary.main,
...sx
}
})
});
};
const PreviewModal = ({
isOpen,
onClose,
data,
currentIndex
}) => {
const [visibleItem, setVisibleItem] = React.useState(currentIndex);
const handlePrev = React.useCallback(() => {
setVisibleItem(prev => prev > 0 ? prev - 1 : prev);
}, []);
const handleNext = React.useCallback(() => {
setVisibleItem(prev => prev < data.length - 1 ? prev + 1 : prev);
}, [data]);
const handleKeyPress = React.useCallback(e => {
switch (e.key) {
case "ArrowLeft":
handlePrev();
break;
case "ArrowRight":
handleNext();
break;
case "Escape":
onClose();
break;
}
}, [handlePrev, handleNext, onClose]);
React.useEffect(() => {
window.addEventListener("keydown", handleKeyPress);
return () => {
window.removeEventListener("keydown", handleKeyPress);
};
}, [handleKeyPress]);
React.useEffect(() => {
setVisibleItem(currentIndex);
}, [currentIndex]);
if (!data[currentIndex]) return null;
return /*#__PURE__*/jsxRuntime.jsx(material.Modal, {
open: isOpen,
"aria-labelledby": "modal-modal-title",
"aria-describedby": "modal-modal-description",
sx: {
outline: "none",
overflow: "auto",
backgroundColor: "rgba(0, 0, 0, 0.7)"
},
disableEscapeKeyDown: true,
children: /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
children: [/*#__PURE__*/jsxRuntime.jsx(IconWrapper, {
onClick: onClose,
children: /*#__PURE__*/jsxRuntime.jsx(CloseIcon, {})
}), /*#__PURE__*/jsxRuntime.jsx(IconWrapper, {
sx: {
left: 6,
top: "50%"
},
onClick: handlePrev,
children: /*#__PURE__*/jsxRuntime.jsx(ArrowBackIcon, {})
}), /*#__PURE__*/jsxRuntime.jsx(IconWrapper, {
sx: {
right: 6,
top: "50%"
},
onClick: handleNext,
children: /*#__PURE__*/jsxRuntime.jsx(ArrowForwardIcon, {})
}), /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
sx: {
position: "absolute",
bgcolor: "grey.300",
zIndex: 1,
bottom: 5,
left: "50%",
transform: "translateX(-50%)",
borderRadius: 1,
px: 1,
fontSize: 15,
fontWeight: 500
},
children: [visibleItem + 1, " / ", data.length]
}), /*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
minWidth: "40vw",
width: {
xs: "100%",
md: "auto"
},
aspectRatio: 1,
borderRadius: "8px",
outline: "none"
},
children: /*#__PURE__*/jsxRuntime.jsx(PreviewMedia, {
data: data[visibleItem]
})
})]
})
});
};
const PreviewMedia = ({
data = {}
}) => {
switch (getFileType(data)) {
case "video":
return /*#__PURE__*/jsxRuntime.jsx(Video, {
src: data.url,
controls: true
});
case "audio":
return /*#__PURE__*/jsxRuntime.jsx(Audio, {
src: data.url
});
case "document":
return /*#__PURE__*/jsxRuntime.jsx(Document, {
data: data
});
case "pdf":
return /*#__PURE__*/jsxRuntime.jsx(Pdf, {
data: data
});
case "image":
default:
return /*#__PURE__*/jsxRuntime.jsx(Image, {
src: data.url,
alt: data.name,
style: {
objectFit: "contain"
}
});
}
};
const IconWrapper = ({
children,
sx,
...rest
}) => {
return /*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
position: "fixed",
right: 10,
top: 10,
zIndex: 1,
bgcolor: "grey.300",
borderRadius: "50%",
width: 30,
aspectRatio: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
cursor: "pointer",
transition: "all",
transitionDuration: 300,
":hover": {
scale: 1.1
},
...sx
},
...rest,
children: children
});
};
const RenderMedia = ({
media,
onRemove,
progressMap,
required,
disabled
}) => {
const [previewData, setPreviewData] = React.useState(null);
const closePreview = () => setPreviewData(null);
const onView = React.useCallback(index => {
setPreviewData({
selectedIndex: index
});
}, []);
return /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
component: "div",
sx: {
mt: disabled ? 1 : 0
},
children: [media.map((file, index) => {
return /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
component: "div",
color: "secondary",
sx: {
border: "0.5px solid",
borderRadius: 2,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
height: "50px",
p: 0.5,
pl: 1,
mt: index !== 0 ? 1 : 0
},
children: [/*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
sx: {
flex: 1,
display: "flex",
alignItems: "center",
gap: 0.5,
maxWidth: "80%",
justifyContent: "center"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.Box, {
sx: {
width: "30px",
height: "30px",
display: "flex",
alignItems: "center",
justifyContent: "center"
},
children: /*#__PURE__*/jsxRuntime.jsx(RenderMediaItem, {
data: file
})
}), /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
color: "textPrimary",
component: "span",
sx: {
fontSize: 13,
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
flex: 1
},
children: file.name
})]
}), !!progressMap[index] && progressMap[index] !== 100 && /*#__PURE__*/jsxRuntime.jsx(material.LinearProgress, {
sx: {
width: 200,
height: 4,
borderRadius: 4
},
variant: "determinate",
value: progressMap[index]
}), progressMap[index] === 100 && /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
sx: {
flex: 1,
display: "flex",
justifyContent: "flex-end"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: () => onView(index),
children: /*#__PURE__*/jsxRuntime.jsx(Visibility, {
fontSize: "small"
})
}), !disabled && /*#__PURE__*/jsxRuntime.jsx(material.IconButton, {
onClick: () => onRemove(index),
disabled: media.length === 1 && required,
children: /*#__PURE__*/jsxRuntime.jsx(DeleteIcon, {
fontSize: "small",
color: media.length === 1 && required ? "disabled" : "error"
})
})]
})]
}, file.name + index);
}), /*#__PURE__*/jsxRuntime.jsx(PreviewModal, {
isOpen: !!previewData,
onClose: closePreview,
data: media,
currentIndex: previewData?.selectedIndex
})]
});
};
const RenderMediaItem = ({
data
}) => {
switch (getFileType(data)) {
case "video":
return /*#__PURE__*/jsxRuntime.jsx(Video, {
src: data.url,
isPlaceholder: true
});
case "audio":
return /*#__PURE__*/jsxRuntime.jsx(AudioPlaceholder, {});
case "document":
return /*#__PURE__*/jsxRuntime.jsx(DocumentPlaceholder, {});
case "pdf":
return /*#__PURE__*/jsxRuntime.jsx(PdfPlaceholder, {});
case "image":
default:
return /*#__PURE__*/jsxRuntime.jsx(Image, {
src: data.url,
alt: data.name
});
}
};
const UPLOAD_OPTIONS = [{
_key: "gallery",
label: "Gallery"
}, {
_key: "camera",
label: "Camera"
}];
const UploaderModal = ({
isOpen,
onClose,
extraProps,
disabled,
files: _files,
onChange,
multiple,
getLocalizedText,
...rest
}) => {
const {
onUploadFile,
onDeleteFile,
onSubmit
} = extraProps || {};
const [activeTab, setActiveTab] = React.useState(0);
const [progressMap, setProgressMap] = React.useState([...Array(_files.length).fill(100)]);
const [isUploading, setIsUploading] = React.useState(false);
const [files, setFiles] = React.useState(parseInputFiles(Array.isArray(_files) ? _files : [_files]) || []);
const {
uploadOptions = []
} = extraProps || {};
const onTabChange = newTab => {
!isUploading && setActiveTab(newTab);
};
const handleUploadProgress = (progress, index, _) => {
setProgressMap(_state => {
_state[index] = progress;
return [..._state];
});
};
const handleChange = async files => {
const filesToUpload = files.filter(file => file instanceof File);
if (!filesToUpload.length) return;
setProgressMap([...(multiple ? Array(_files.length).fill(100) : []), ...(onUploadFile ? Array(filesToUpload.length) : Array(filesToUpload.length).fill(100))]);
setFiles(multiple ? [..._files, ...filesToUpload.map(file => getFileMetaData(file))] : [getFileMetaData(filesToUpload[0])]);
onUploadFile && setIsUploading(true);
const uploadPromises = filesToUpload.map(async (file, index) => {
if (onUploadFile) {
try {
const filePath = await onUploadFile(file, progress => handleUploadProgress(progress, multiple ? _files.length + index : index, filesToUpload.length));
return getFileMetaData(file, filePath);
} catch (error) {
rest.onError?.(error instanceof Error ? error.message : getLocalizedText?.("uploadFailed") || "Upload failed");
setFiles(_files);
return null;
}
} else {
return getFileMetaData(file);
}
});
const results = await Promise.all(uploadPromises);
const successfulUploads = results.filter(Boolean);
setIsUploading(false);
if (multiple) {
onChange([..._files, ...successfulUploads]);
} else {
onChange(successfulUploads);
}
};
const handleRemove = async index => {
if (onDeleteFile && _files[index].id) {
await onDeleteFile(_files[index].id);
}
const filteredFiles = _files.filter((_, indx) => indx !== index);
onChange(filteredFiles);
setFiles(filteredFiles);
};
const handleCancel = () => {
if (onUploadFile) {
const filteredFiles = _files.filter(file => file.id);
onChange(filteredFiles);
setFiles(filteredFiles);
}
onClose();
};
const handleSubmit = async () => {
if (onSubmit) {
await onSubmit();
}
onClose();
};
const isMobile = checkIsMobile();
const VISIBLE_UPLOAD_OPTIONS = React.useMemo(() => {
if (isMobile) {
return [UPLOAD_OPTIONS[0]];
}
return uploadOptions.length ? UPLOAD_OPTIONS.filter(({
_key
}) => !!uploadOptions.includes(_key)) : UPLOAD_OPTIONS;
}, [uploadOptions, isMobile]);
const isUploadDisabled = React.useMemo(() => {
return !files.some(file => !file.id) || isUploading;
}, [files, isUploading]);
return /*#__PURE__*/jsxRuntime.jsxs(CustomModal, {
title: getLocalizedText ? `${getLocalizedText?.("uploadFile", {
label: getLocalizedText(rest.label)
})}` : `Upload ${rest.label}`,
isOpen: isOpen,
sx: {
width: {
xs: "90%",
sm: 600
},
minWidth: {
xs: 200,
sm: 600
},
height: 600,
display: "flex",
flexDirection: "column",
overflow: "auto"
},
className: "hide-scrollbar",
buttons: [{
title: getLocalizedText?.("cancel") || "Cancel",
variant: "outlined",
disabled: isUploading,
onClick: handleCancel,
sx: {
mt: 2
}
}, {
title: getLocalizedText?.("submit") || "Submit",
variant: "contained",
disabled: isUploadDisabled,
hidden: disabled,
onClick: handleSubmit,
sx: {
mt: 2
}
}],
children: [!disabled && /*#__PURE__*/jsxRuntime.jsx(ScrollableTabs, {
groups: VISIBLE_UPLOAD_OPTIONS,
activeTab: activeTab,
onTabChange: onTabChange,
getLocalizedText: getLocalizedText,
renderContent: /*#__PURE__*/jsxRuntime.jsx(RenderUploadOption, {
uploadOption: VISIBLE_UPLOAD_OPTIONS[activeTab]?._key,
extraProps: extraProps,
onChange: handleChange,
multiple: multiple,
disabled: isUploading,
getLocalizedText: getLocalizedText,
...rest
})
}), /*#__PURE__*/jsxRuntime.jsx(RenderMedia, {
media: files,
onRemove: handleRemove,
progressMap: progressMap,
required: !rest.isOptional,
disabled: disabled
})]
});
};
function parseInputFiles(files) {
return files.map((file, index) => {
if (typeof file === "string") {
const fileName = `filename${index + 1}.jpg`;
return {
name: fileName,
path: fileName,
size: 0,
type: "image/jpeg",
url: file
};
}
if (file instanceof File) {
return getFileMetaData(file);
}
return file;
});
}
const FileUploader = ({
error,
files = [],
size,
getLocalizedText,
...rest
}) => {
const [showModal, setShowModal] = React.useState(false);
const handleCloseModal = () => {
setShowModal(false);
};
const {
label
} = rest;
return /*#__PURE__*/jsxRuntime.jsxs(material.Typography, {
component: "div",
sx: {
width: "100%"
},
children: [/*#__PURE__*/jsxRuntime.jsx(material.TextField, {
label: `${getLocalizedText ? getLocalizedText(label) : label} ${rest.extraProps?.count ? `(${files.length})` : ""}`,
size: "small",
variant: "outlined",
value: files.map(file => file.name).join(", "),
onClick: () => setShowModal(true),
fullWidth: true,
error: !!error,
helperText: error,
slotProps: {
htmlInput: {
sx: {
cursor: "pointer"
}
},
inputLabel: {
shrink: !!files.length,
sx: {
pl: files.length ? 0 : 3,
overflow: "hidden",
textOverflow: "ellipsis"
}
},
input: {
sx: {
pr: 0.5,
pl: 1
},
readOnly: true,
startAdornment: /*#__PURE__*/jsxRuntime.jsx(ImageIcon, {
color: error ? "error" : "inherit",
fontSize: "medium",
sx: {
pr: 0,
mr: 0.5
}
})
}
}
}), showModal && /*#__PURE__*/jsxRuntime.jsx(UploaderModal, {
isOpen: showModal,
onClose: handleCloseModal,
files: files,
getLocalizedText: getLocalizedText,
...rest
})]
});
};
const contextDefaultValue = {
onSelectAll: _selectedAll => void 0,
selectedAll: false,
indeterminate: false
};
const MuiAutocompleteSelectAllContext = /*#__PURE__*/React.createContext(contextDefaultValue);
const MuiAutocompleteSelectAllListBox = /*#__PURE__*/React.forwardRef(function ListBoxBase(props, ref) {
const theme = material.useTheme();
const {
children,
...rest
} = props;
const innerRef = React.useRef(null);
React.useImperativeHandle(ref, () => innerRef.current);
const {
onSelectAll,
selectedAll,
indeterminate
} = React.useContext(MuiAutocompleteSelectAllContext);
return /*#__PURE__*/jsxRuntime.jsxs("ul", {
...rest,
ref: innerRef,
role: "list-box",
children: [/*#__PURE__*/jsxRuntime.jsxs("li", {
style: {
display: "flex",
alignItems: "center"
},
children: [/*#__PURE__*/jsxRuntime.jsx(Checkbox, {
id: "selectAll",
indeterminate: indeterminate,
checked: selectedAll,
onChange: _e => onSelectAll(selectedAll)
// TODO: use primary color without defining
,
sx: {
ml: 2,
color: `${theme.palette.primary.main} !important`
}
}), "Select All"]
}), /*#__PURE__*/jsxRuntime.jsx(Divider, {}), children]
});
});
const MuiAutocompleteSelectAll = {
Provider: MuiAutocompleteSelectAllContext.Provider,
ListBox: MuiAutocompleteSelectAllListBox
};
const MultiSelect = ({
_key,
value,
onChange,
disabled,
extraData,
color,
size,
error,
errorText,
placeholder,
ChipProps = {},
extraProps
}) => {
const selectedAll = value?.length === extraData?.length;
const {
textFieldProps = {},
...restProps
} = extraProps || {};
const {
slotProps = {},
...restTextFieldProps
} = textFieldProps;
return /*#__PURE__*/jsxRuntime.jsx(MuiAutocompleteSelectAll.Provider, {
value: {
onSelectAll: selectedAll => {
onChange && (selectedAll ? onChange({
_key,
value: []
}) : onChange({
_key,
value: extraData
}));
},
selectedAll,
indeterminate: !!value?.length && !selectedAll
},
children: /*#__PURE__*/jsxRuntime.jsx(material.Autocomplete, {
disablePortal: true,
multiple: true,
disabled: disabled,
options: extraData || [],
onChange: (_, value) => {
onChange && onChange({
_key,
value
});
},
value: Array.isArray(value) ? value : [value],
color: color,
size: size,
getOptionLabel: option => extractValue(option, "label"),
disableCloseOnSelect: true,
limitTags: 3,
slotProps: {
listbox: {
component: MuiAutocompleteSelectAll.ListBox
}
},
isOptionEqualToValue: (option, value) => {
return extractValue(option, "value") === extractValue(value, "value");
},
renderTags: (tags, getTagProps) => {
return tags.map((tag, index) => {
const {
disabled,
onDelete,
...tagProps
} = getTagProps({
index
});
return /*#__PURE__*/jsxRuntime.jsx(material.Chip, {
onClick: e => {
e.stopPropagation();
ChipProps.onClick && ChipProps.onClick(tag);
},
onDelete: deleteProps => !disabled && onDelete(deleteProps),
label: extractValue(tag, "label"),
...tagProps
});
});
},
renderInput: params => {
const {
InputProps,
...restParams
} = params;
const {
startAdornment,
...restInputProps
} = InputProps;
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
...restParams,
variant: "outlined",
size: size,
error: error,
helperText: errorText,
label: placeholder,
slotProps: {
inputLabel: slotProps.inputLabel,
input: {
startAdornment: /*#__PURE__*/jsxRuntime.jsx("div", {
style: {
maxHeight: 100,
overflowY: "auto"
},
className: "hide-scrollbar",
children: startAdornment
}),
...restInputProps,
...(slotProps?.input || {})
}
},
...restTextFieldProps
});
},
renderOption: ({
key,
...rest
}, option, {
selected
}) => {
return /*#__PURE__*/jsxRuntime.jsxs(material.MenuItem, {
...rest,
children: [/*#__PURE__*/jsxRuntime.jsx(material.Checkbox, {
checked: selected
}), String(extractValue(option, "label"))]
}, key);
},
...restProps
})
});
};
const REGEX = {
NUMBERS: {
pattern: /[^0-9]/
},
PHONE: {
pattern: /^\d{8,15}$/
},
EMAIL: {
pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
},
DECIMALS: {
pattern: /^\d+(\.\d{1,2})?$/
},
COUNTRY_CODE: {
pattern: /^\+\d{1,4}$/
},
PASSWORD: {
pattern: /[0-9A-Za-z!@#$*&^%]{8}/,
message: "Include upper, lower, digit, and special character"
}
};
const PhoneNumberInput = props => {
const {
color,
name,
error,
errorText,
label,
value,
handleChange,
disabled,
size,
countryCode,
countryCodeField,
countryCodes,
sx,
slotProps,
...restProps
} = props;
const selectedOption = countryCodes?.find(c => c.value === countryCode);
const [inputValue, setInputValue] = React.useState("");
React.useEffect(() => {
if (!inputValue && selectedOption) {
setInputValue(""); // keep input blank when not typing
}
}, [selectedOption]);
const showFlag = !inputValue && selectedOption?.shortCode;
return /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
sx: {
display: "flex",
alignItems: "flex-start"
},
children: [!!countryCodes?.length && /*#__PURE__*/jsxRuntime.jsx(material.Autocomplete, {
id: "country-code-autocomplete",
options: countryCodes,
value: selectedOption,
inputValue: inputValue,
onInputChange: (_, newInputValue) => {
setInputValue(newInputValue);
},
getOptionLabel: () => "" // Always return empty label
,
filterOptions: (options, {
inputValue
}) => options.filter(opt => opt.label?.toLowerCase().includes(inputValue.toLowerCase())),
isOptionEqualToValue: (option, value) => {
return `${option.label}${option.value}` === `${value.label}${value.value}`;
},
onChange: (_, newValue) => {
if (!countryCodeField) return;
handleChange({
_key: countryCodeField,
value: newValue.value
});
setInputValue("");
},
disableClearable: true,
disabled: disabled,
size: size,
slotProps: {
popper: {
sx: {
width: "fit-content !important",
maxWidth: 300
}
}
},
renderInput: params => /*#__PURE__*/jsxRuntime.jsxs(material.Box, {
sx: {
position: "relative",
width: 70
},
children: [showFlag && /*#__PURE__*/jsxRuntime.jsx(material.Box, {
component: "img",
src: `https://flagsapi.com/${selectedOption.shortCode}/flat/32.png`,
alt: "flag",
sx: {
position: "absolute",
left: 10,
top: "50%",
transform: "translateY(-50%)",
width: 24,
height: 24,
zIndex: 1,
pointerEvents: "none"
}
}), /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
...params,
variant: "outlined",
sx: {
"& input": {
paddingLeft: showFlag ? "40px" : "12px"
}
}
})]
}),
renderOption: (props, option) => /*#__PURE__*/jsxRuntime.jsxs("li", {
...props,
children: [/*#__PURE__*/jsxRuntime.jsx("img", {
src: `https://flagsapi.com/${option.shortCode}/flat/32.png`,
style: {
width: 24,
height: 24,
marginRight: 8,
borderRadius: 4
},
alt: "flag"
}), option.label]
}),
sx: {
[`& .MuiAutocomplete-inputRoot`]: {
paddingRight: "8px !important"
},
...sx
}
}), /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
type: "tel",
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: label,
name: name,
disabled: disabled,
variant: "outlined",
value: value ?? "",
onChange: e => {
if (e.target.value.match(REGEX.NUMBERS.pattern) || !name) {
return;
}
handleChange({
_key: name,
value: e.target.value
});
},
size: size,
onWheel: e => e.target.blur(),
slotProps: {
...(slotProps || {}),
input: {
...(slotProps?.input || {}),
startAdornment: /*#__PURE__*/jsxRuntime.jsx(material.Typography, {
sx: {
color: "black !important",
whiteSpace: "nowrap"
},
children: selectedOption?.value
})
}
},
sx: {
"& .MuiOutlinedInput-root": {
paddingLeft: "7px !important"
},
"& input": {
paddingLeft: "4px !important"
}
},
...restProps
})]
});
};
function formatDateToISOString(dateInput, withTime) {
const date = new Date(dateInput);
const year = date.getFullYear();
// Pad month, date, hours, minutes with leading zeros if needed
const month = String(date.getMonth() + 1).padStart(2, "0"); // getMonth() is zero-based
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
if (withTime) {
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
return `${year}-${month}-${day}`;
}
const DynamicField = ({
item,
itemData,
error,
errorText,
color = "primary",
disabled,
value,
onChange,
size = "medium",
sx,
onError,
getLocalizedText
}) => {
const {
placeholder: _placeholder,
isOptional,
_key,
fieldType,
overRideValues = {},
maxLength,
multiple,
countryCodeField,
extraProps = {},
extraData = []
} = item;
const {
slotProps = {},
...restProps
} = {
...(extraProps ?? {})
};
const onChangeValue = ({
target
}) => {
handleChange({
value: target.value,
_key
});
};
const handleChange = data => {
if (maxLength && data?.value?.length > maxLength) {
return;
}
onChange && onChange({
overRideValues,
maxLength,
value: data.value,
_key: data._key,
textValue: data.textValue
});
};
const placeholder = _placeholder ? (getLocalizedText?.(_placeholder) || _placeholder) + (isOptional ? "" : "*") : "";
switch (fieldType) {
case "text":
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
value: value ?? "",
onChange: onChangeValue,
size: size,
sx: sx,
...extraProps
});
case "password":
return /*#__PURE__*/jsxRuntime.jsx(PasswordInput, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
value: value ?? "",
onChange: onChangeValue,
size: size,
sx: sx,
...extraProps
});
case "dropdown":
return /*#__PURE__*/jsxRuntime.jsxs(material.FormControl, {
size: size,
disabled: disabled,
error: error,
color: color,
fullWidth: true,
children: [/*#__PURE__*/jsxRuntime.jsx(material.InputLabel, {
id: _key,
...(slotProps?.inputLabel || {}),
children: placeholder
}), /*#__PURE__*/jsxRuntime.jsx(material.Select, {
labelId: _key,
name: _key,
label: placeholder,
value: value ?? "",
MenuProps: {
PaperProps: {
sx: {
maxHeight: 300
}
}
},
onChange: onChangeValue,
sx: sx,
slotProps: slotProps,
children: extraData?.map((_item, index) => /*#__PURE__*/jsxRuntime.jsx(material.MenuItem, {
sx: {
textTransform: "capitalize"
},
value: _item?.value ?? _item?.id ?? _item,
children: _item?.label || _item?.name || _item
}, index))
}), !!errorText && /*#__PURE__*/jsxRuntime.jsx(material.FormHelperText, {
error: error,
children: errorText
})]
});
case "number":
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
type: "tel",
value: value ?? "",
onChange: e => {
if (e.target.value.match(REGEX.NUMBERS.pattern)) {
return e.preventDefault();
}
handleChange({
_key,
value: e.target.value
});
},
size: size,
onWheel: event => event.currentTarget.blur(),
...extraProps
});
case "textarea":
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
fullWidth: true,
multiline: !disabled,
minRows: 1,
maxRows: 10,
error: error,
color: color,
helperText: errorText,
label: placeholder,
name: _key,
variant: "outlined",
value: value ?? "",
disabled: disabled,
onChange: onChangeValue,
sx: sx,
...extraProps
});
case "date":
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
type: "date",
value: value ? formatDateToISOString(value.toString()) : "",
onChange: onChangeValue,
size: size,
sx: sx,
slotProps: {
inputLabel: {
shrink: true
},
...slotProps
},
...restProps
});
case "time":
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
type: "time",
value: value ?? "",
onChange: onChangeValue,
size: size,
sx: sx,
slotProps: {
inputLabel: {
shrink: true
},
...slotProps
},
...restProps
});
case "datetime":
return /*#__PURE__*/jsxRuntime.jsx(material.TextField, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
type: "datetime-local",
value: value ? formatDateToISOString(value.toString(), true) : "",
onChange: onChangeValue,
size: size,
sx: sx,
slotProps: {
inputLabel: {
shrink: true
},
...slotProps
},
...restProps
});
case "autocomplete":
return /*#__PURE__*/jsxRuntime.jsx(AutocompleteSelect, {
...item,
fullWidth: true,
color: color,
error: error,
errorText: errorText,
placeholder: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
value: value ?? "",
onChange: handleChange,
size: size,
sx: sx,
_key: _key,
fieldType: fieldType
});
case "checkbox":
const {
labelProps,
checkboxProps
} = extraProps;
return /*#__PURE__*/jsxRuntime.jsx(material.FormGroup, {
children: /*#__PURE__*/jsxRuntime.jsx(material.FormControlLabel, {
control: /*#__PURE__*/jsxRuntime.jsx(material.Checkbox, {
checked: !!value,
onChange: () => handleChange({
_key,
value: !value
}),
...checkboxProps
}),
label: getLocalizedText?.(_placeholder || "") || _placeholder,
name: _key,
disabled: disabled,
sx: sx,
...labelProps
})
});
case "file":
return /*#__PURE__*/jsxRuntime.jsx(FileUploader, {
...item,
size: size,
name: _key,
label: placeholder,
files: value ? Array.isArray(value) ? value : [value] : [],
onChange: value => handleChange({
_key,
value
}),
onError: onError,
disabled: disabled,
multiple: multiple,
getLocalizedText: getLocalizedText,
error: errorText,
isOptional: isOptional,
extraProps: extraProps
});
case "multiselect":
return /*#__PURE__*/jsxRuntime.jsx(MultiSelect, {
...item,
sx: sx,
fullWidth: true,
multiline: !disabled,
error: error,
errorText: errorText,
color: color,
placeholder: placeholder,
variant: "outlined",
value: value ?? [],
disabled: disabled,
onChange: onChange,
extraData: extraData,
size: size
});
case "phone":
return /*#__PURE__*/jsxRuntime.jsx(PhoneNumberInput, {
fullWidth: true,
color: color,
error: error,
helperText: errorText,
label: placeholder,
name: _key,
disabled: disabled,
variant: "outlined",
value: value ?? "",
handleChange: handleChange,
size: size,
sx: sx,
countryCode: itemData && item.countryCodeField ? itemData[item.countryCodeField] : "",
countryCodeField: countryCodeField,
...extraProps
});
default:
return null;
}
};
exports.DynamicField = DynamicField;
exports.REGEX = REGEX;
exports.extractValue = extractValue;
exports.getErrorKey = getErrorKey;
exports.getErrorText = getErrorText;
exports.getUpdatedKey = getUpdatedKey;
exports.queryString = queryString;
exports.validateFields = validateFields;
//# sourceMappingURL=mui-dynamic-field.cjs.map