@rjsf/core
Version:
A simple React component capable of building HTML forms out of a JSON schema.
47 lines (46 loc) • 2.87 kB
JavaScript
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { getTemplate, TranslatableString, useFileWidgetProps, } from '@rjsf/utils';
import Markdown from 'markdown-to-jsx';
function FileInfoPreview({ fileInfo, registry, }) {
const { translateString } = registry;
const { dataURL, type, name } = fileInfo;
if (!dataURL) {
return null;
}
// If type is JPEG or PNG then show image preview.
// Originally, any type of image was supported, but this was changed into a whitelist
// since SVGs and animated GIFs are also images, which are generally considered a security risk.
if (['image/jpeg', 'image/png'].includes(type)) {
return _jsx("img", { src: dataURL, style: { maxWidth: '100%' }, className: 'file-preview' });
}
// otherwise, let users download file
return (_jsxs(_Fragment, { children: [' ', _jsx("a", { download: `preview-${name}`, href: dataURL, className: 'file-download', children: translateString(TranslatableString.PreviewLabel) })] }));
}
function FilesInfo({ filesInfo, registry, preview, onRemove, options, }) {
if (filesInfo.length === 0) {
return null;
}
const { translateString } = registry;
const { RemoveButton } = getTemplate('ButtonTemplates', registry, options);
return (_jsx("ul", { className: 'file-info', children: filesInfo.map((fileInfo, key) => {
const { name, size, type } = fileInfo;
const handleRemove = () => onRemove(key);
return (_jsxs("li", { children: [_jsx(Markdown, { children: translateString(TranslatableString.FilesInfo, [name, type, String(size)]) }), preview && _jsx(FileInfoPreview, { fileInfo: fileInfo, registry: registry }), _jsx(RemoveButton, { onClick: handleRemove, registry: registry })] }, key));
}) }));
}
/**
* The `FileWidget` is a widget for rendering file upload fields.
* It is typically used with a string property with data-url format.
*/
function FileWidget(props) {
const { disabled, readonly, required, multiple, onChange, value, options, registry } = props;
const { filesInfo, handleChange, handleRemove } = useFileWidgetProps(value, onChange, multiple);
const BaseInputTemplate = getTemplate('BaseInputTemplate', registry, options);
const handleOnChangeEvent = (event) => {
if (event.target.files) {
handleChange(event.target.files);
}
};
return (_jsxs("div", { children: [_jsx(BaseInputTemplate, { ...props, disabled: disabled || readonly, type: 'file', required: value ? false : required, onChangeOverride: handleOnChangeEvent, value: '', accept: options.accept ? String(options.accept) : undefined }), _jsx(FilesInfo, { filesInfo: filesInfo, onRemove: handleRemove, registry: registry, preview: options.filePreview, options: options })] }));
}
export default FileWidget;