@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
191 lines (190 loc) • 7.86 kB
JavaScript
"use client";
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
const _excluded = ["id", "className", "width", "value", "label", "labelDescription", "help", "htmlAttributes", "handleChange", "handleFocus", "handleBlur", "fileHandler"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import classnames from 'classnames';
import FieldBlock from '../../FieldBlock';
import { useFieldProps, useTranslation as useFormsTranslation } from '../../hooks';
import Upload from '../../../../components/Upload';
import useUpload from '../../../../components/upload/useUpload';
import { pickSpacingProps } from '../../../../components/flex/utils';
import HelpButtonInline, { HelpButtonInlineContent } from '../../../../components/help-button/HelpButtonInline';
import { useTranslation as useSharedTranslation } from '../../../../shared';
import { FormError } from '../../utils';
const validateRequired = (value, {
required,
isChanged,
error
}) => {
const hasError = value === null || value === void 0 ? void 0 : value.some(file => file.errorMessage);
if (hasError) {
return new FormError('Upload.errorInvalidFiles');
}
const hasFiles = (value === null || value === void 0 ? void 0 : value.length) > 0;
if (required && (!isChanged && !hasFiles || !hasFiles)) {
return error;
}
return undefined;
};
function UploadComponent(props) {
const sharedTr = useSharedTranslation().Upload;
const formsTr = useFormsTranslation().Upload;
const errorMessages = useMemo(() => ({
'Field.errorRequired': formsTr.errorRequired
}), [formsTr.errorRequired]);
const fromInput = useCallback(value => {
value.forEach((item, index) => {
var _item$file;
value[index] = item;
value[index]['name'] = item['name'] || ((_item$file = item.file) === null || _item$file === void 0 ? void 0 : _item$file.name);
});
return value;
}, []);
const preparedProps = _objectSpread({
errorMessages,
validateRequired,
fromInput,
toInput: transformFiles
}, props);
const _useFieldProps = useFieldProps(preparedProps, {
executeOnChangeRegardlessOfError: true
}),
{
id,
className,
width: widthProp = 'stretch',
value,
label,
labelDescription,
help,
htmlAttributes,
handleChange,
handleFocus,
handleBlur,
fileHandler
} = _useFieldProps,
rest = _objectWithoutProperties(_useFieldProps, _excluded);
const {
title = sharedTr.title,
text = sharedTr.text,
acceptedFileTypes = ['pdf', 'png', 'jpg', 'jpeg'],
filesAmountLimit = 100,
fileMaxSize = 5,
skeleton,
onFileDelete,
onFileClick,
download,
allowDuplicates,
disableDragAndDrop
} = rest;
const {
files,
setFiles
} = useUpload(id);
const filesRef = useRef();
useEffect(() => {
filesRef.current = files;
}, [files]);
useEffect(() => {
setFiles(value);
}, [setFiles, value]);
const handleChangeAsync = useCallback(async files => {
var _filesRef$current;
const existingFileIds = ((_filesRef$current = filesRef.current) === null || _filesRef$current === void 0 ? void 0 : _filesRef$current.map(file => file.id)) || [];
const newFiles = files.filter(file => !existingFileIds.includes(file.id));
const newValidFiles = newFiles.filter(file => !file.errorMessage);
if (newValidFiles.length > 0) {
const newFilesLoading = newFiles.map(file => _objectSpread(_objectSpread({}, file), {}, {
isLoading: !file.errorMessage
}));
setFiles([...filesRef.current, ...newFilesLoading]);
const incomingFiles = await fileHandler(newValidFiles);
incomingFiles.forEach(file => {
const incomingFileObj = _objectSpread(_objectSpread({}, file), {}, {
isLoading: false
});
const foundIndex = newFilesLoading.findIndex(newFile => newFile.isLoading);
if (foundIndex >= 0) {
newFilesLoading[foundIndex] = incomingFileObj;
} else {
newFilesLoading.push(incomingFileObj);
}
});
const indexOfFirstNewFile = filesRef.current.findIndex(({
id
}) => id === newFiles[0].id);
const updatedFiles = [...filesRef.current.slice(0, indexOfFirstNewFile), ...newFilesLoading, ...filesRef.current.slice(indexOfFirstNewFile + newFilesLoading.length)];
handleChange(updatedFiles);
} else {
handleChange(files);
}
}, [setFiles, fileHandler, handleChange]);
const changeHandler = useCallback(({
files
}) => {
handleBlur();
handleFocus();
if (fileHandler) {
handleChangeAsync(files);
} else {
handleChange(files);
}
}, [handleBlur, handleFocus, fileHandler, handleChangeAsync, handleChange]);
const width = widthProp;
const fieldBlockProps = _objectSpread({
id,
forId: `${id}-input`,
labelSrOnly: true,
className: classnames('dnb-forms-field-upload', className),
width,
help: undefined
}, pickSpacingProps(props));
return React.createElement(FieldBlock, fieldBlockProps, React.createElement(Upload, _extends({
id: id,
acceptedFileTypes: acceptedFileTypes,
filesAmountLimit: filesAmountLimit,
download: download,
allowDuplicates: allowDuplicates,
disableDragAndDrop: disableDragAndDrop,
fileMaxSize: fileMaxSize,
skeleton: skeleton,
onChange: changeHandler,
onFileDelete: onFileDelete,
onFileClick: onFileClick,
title: label !== null && label !== void 0 ? label : title,
text: help ? React.createElement(React.Fragment, null, labelDescription !== null && labelDescription !== void 0 ? labelDescription : text, React.createElement(HelpButtonInline, {
contentId: `${id}-help`,
left: text ? 'x-small' : false,
help: help
})) : labelDescription !== null && labelDescription !== void 0 ? labelDescription : text
}, htmlAttributes), help && React.createElement(HelpButtonInlineContent, {
contentId: `${id}-help`,
help: help,
roundedCorner: false
})));
}
export default UploadComponent;
UploadComponent._supportsSpacingProps = true;
export function transformFiles(value) {
if (Array.isArray(value)) {
if (value.length === 0) {
return undefined;
}
value.map(item => {
if (item !== null && item !== void 0 && item.file && !(item.file instanceof File)) {
var _lastModified, _item$file2, _type, _item$file3;
item['file'] = new File([], item['name'] || (item === null || item === void 0 ? void 0 : item.file['name']), {
lastModified: (_lastModified = (_item$file2 = item.file) === null || _item$file2 === void 0 ? void 0 : _item$file2.lastModified) !== null && _lastModified !== void 0 ? _lastModified : 0,
type: (_type = (_item$file3 = item.file) === null || _item$file3 === void 0 ? void 0 : _item$file3.type) !== null && _type !== void 0 ? _type : ''
});
}
return item;
});
}
return value;
}
//# sourceMappingURL=Upload.js.map