ant-design/components/upload/Upload.tsx

366 lines
9.0 KiB
TypeScript
Raw Normal View History

import * as React from 'react';
import RcUpload from 'rc-upload';
import classNames from 'classnames';
import Dragger from './Dragger';
import UploadList from './UploadList';
import {
RcFile,
UploadProps,
UploadFile,
UploadLocale,
UploadChangeParam,
UploadType,
UploadListType,
} from './interface';
import { T, fileToObject, getFileItem, removeFileItem } from './utils';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale/default';
import { ConfigContext } from '../config-provider';
import devWarning from '../_util/devWarning';
2020-08-19 09:50:04 +08:00
import useSyncState from '../_util/hooks/useSyncState';
import useForceUpdate from '../_util/hooks/useForceUpdate';
export { UploadProps };
const InternalUpload: React.ForwardRefRenderFunction<unknown, UploadProps> = (props, ref) => {
const {
fileList: fileListProp,
defaultFileList,
onRemove,
showUploadList,
listType,
onPreview,
onDownload,
previewFile,
disabled,
locale: propLocale,
iconRender,
isImageUrl,
progress,
prefixCls: customizePrefixCls,
className,
type,
children,
style,
} = props;
const [getFileList, setFileList] = useSyncState<Array<UploadFile>>(
fileListProp || defaultFileList || [],
);
const [dragState, setDragState] = React.useState<string>('drop');
const upload = React.useRef<any>();
React.useEffect(() => {
setFileList(fileListProp || defaultFileList || []);
devWarning(
'fileList' in props || !('value' in props),
'Upload',
'`value` is not a valid prop, do you mean `fileList`?',
);
}, []);
React.useEffect(() => {
if ('fileList' in props) {
setFileList(fileListProp || []);
}
}, [fileListProp]);
const onChange = (info: UploadChangeParam) => {
if (!('fileList' in props)) {
setFileList(info.fileList);
}
const { onChange: onChangeProp } = props;
if (onChangeProp) {
onChangeProp({
...info,
fileList: [...info.fileList],
});
}
2019-08-05 18:38:10 +08:00
};
const onStart = (file: RcFile) => {
const targetItem = fileToObject(file);
2017-11-20 16:53:56 +08:00
targetItem.status = 'uploading';
const nextFileList = getFileList().concat();
const fileIndex = nextFileList.findIndex(({ uid }: UploadFile) => uid === targetItem.uid);
if (fileIndex === -1) {
nextFileList.push(targetItem);
} else {
nextFileList[fileIndex] = targetItem;
}
onChange({
file: targetItem,
fileList: nextFileList,
});
2018-12-07 20:02:01 +08:00
};
const onSuccess = (response: any, file: UploadFile, xhr: any) => {
try {
if (typeof response === 'string') {
response = JSON.parse(response);
}
2018-12-07 20:02:01 +08:00
} catch (e) {
/* do nothing */
}
const targetItem = getFileItem(file, getFileList());
// removed
if (!targetItem) {
return;
}
targetItem.status = 'done';
targetItem.response = response;
targetItem.xhr = xhr;
onChange({
file: { ...targetItem },
fileList: getFileList().concat(),
});
2018-12-07 20:02:01 +08:00
};
const onProgress = (e: { percent: number }, file: UploadFile) => {
const targetItem = getFileItem(file, getFileList());
// removed
if (!targetItem) {
return;
}
targetItem.percent = e.percent;
onChange({
event: e,
file: { ...targetItem },
fileList: getFileList().concat(),
});
2018-12-07 20:02:01 +08:00
};
const onError = (error: Error, response: any, file: UploadFile) => {
const targetItem = getFileItem(file, getFileList());
// removed
if (!targetItem) {
return;
}
targetItem.error = error;
targetItem.response = response;
targetItem.status = 'error';
onChange({
file: { ...targetItem },
fileList: getFileList().concat(),
});
2018-12-07 20:02:01 +08:00
};
const handleRemove = (file: UploadFile) => {
Promise.resolve(typeof onRemove === 'function' ? onRemove(file) : onRemove).then(ret => {
// Prevent removing file
if (ret === false) {
return;
}
const removedFileList = removeFileItem(file, getFileList());
if (removedFileList) {
file.status = 'removed';
if (upload.current) {
upload.current.abort(file);
}
onChange({
file,
fileList: removedFileList,
});
}
});
2018-12-07 20:02:01 +08:00
};
const onFileDrop = (e: React.DragEvent<HTMLDivElement>) => {
setDragState(e.type);
2018-12-07 20:02:01 +08:00
};
const beforeUpload = (file: RcFile, fileListArgs: RcFile[]) => {
const { beforeUpload: beforeUploadProp } = props;
if (!beforeUploadProp) {
return true;
}
const result = beforeUploadProp(file, fileListArgs);
if (result === false) {
// Get unique file list
const uniqueList: UploadFile<any>[] = [];
getFileList()
.concat(fileListArgs.map(fileToObject))
.forEach(f => {
if (uniqueList.every(uf => uf.uid !== f.uid)) {
uniqueList.push(f);
}
});
onChange({
file,
fileList: uniqueList,
});
return false;
2019-01-11 17:20:48 +08:00
}
if (result && (result as PromiseLike<any>).then) {
return result;
}
return true;
2018-12-07 20:02:01 +08:00
};
// Test needs
const forceUpdate = useForceUpdate();
React.useImperativeHandle(ref, () => ({
onStart,
onSuccess,
onProgress,
onError,
fileList: getFileList(),
upload: upload.current,
forceUpdate,
}));
const renderUploadList = (locale: UploadLocale) => {
2020-02-19 13:20:43 +08:00
const {
showRemoveIcon,
showPreviewIcon,
showDownloadIcon,
removeIcon,
downloadIcon,
} = showUploadList as any;
return (
<UploadList
listType={listType}
items={getFileList()}
meger feature to master (#16421) * use ul in list * update snapshot * update comment * feat: TreeSelect support `showSearch` in multiple mode (#15933) * update rc-tree-select * typo * update desc & snapshot * update desc & snapshot * check default showSearch * feat: table customizing variable (#15971) * feat: added table selected row color variable * fix: @table-selected-row-color default is inherit * feat: Upload support customize previewFile (#15984) * support preview file * use promise * dealy load * use canvas of render * use domHook of test * update demo * add snapshot * update types * update testcase * feat: form customizing variables (#15954) * fix: added styling form input background-color * feat: added '@form-warning-input-bg' variable * feat: added '@form-error-input-bg' variable * use li wrap with comment * feat: Support append theme less file with less-variable (#16118) * add override * add override support * update doc * feat: dropdown support set right icon * docs: update doc of dropdown component * style: format dropdown-button.md * test: update updateSnapshot * style: format dropdown-button.md * test: update updateSnapshot * test: update updateSnapshot * style: change style of dropdown-button demo * fix: fix document table order * feat: Support SkeletonAvatarProps.size accept number (#16078) (#16128) * chore:update style of demo * feat: Notification functions accept top, bottom and getContainer as arguments * drawer: add afterVisibleChange * rm onVisibleChange * update * feat: 🇭🇷 hr_HR locale (#16258) * Added Croatian locale * fixed lint error * :white_check_mark: Add test cases for hr_HR * :memo: update i18n documentation * feat: add `htmlFor` in Form.Item (#16278) * add htmlFor in Form.Item * update doc * feat: Button support `link` type (#16289) close #15892 * feat: Add Timeline.Item.position (#16148) (#16193) * fix: Timeline.pendingDot interface documentation there is a small problem (#16177) * feat: Add Timeline.Item.position (#16148) * doc: add version infomation for Timeline.Item.position * refactor: Update Tree & TreeSelect deps (#16330) * use CSSMotion * update snapshot * feat: Collapse support `expandIconPosition` (#16365) * update doc * support expandIconPosition * update snapshot * feat: Breadcrumb support DropDown (#16315) * breadcrumbs support drop down menu * update doc * add require less * fix test * fix md doc * less code * fix style warning * update snap * add children render test * feat: TreeNode support checkable * feat: add optional to support top and left slick dots (#16186) (#16225) * add optional to support top and left slick dots * update carousel snapshot * Update doc, add placement demo * update carousel placement demo snapshots * rename dots placement to position * update vertical as deprecated * rename dotsPosition to dotPosition * refine code * add warning testcase for vertical * remove unused warning * update expression * Additional test case for dotPosition * refactor: Upgrade `rc-tree-select` to support pure React motion (#16402) * upgrade `rc-tree-select` * update snapshot * 3.17.0 changelog * fix warning * fix review warning
2019-05-06 12:04:39 +08:00
previewFile={previewFile}
onPreview={onPreview}
onDownload={onDownload}
onRemove={handleRemove}
2019-05-25 16:34:38 +08:00
showRemoveIcon={!disabled && showRemoveIcon}
showPreviewIcon={showPreviewIcon}
showDownloadIcon={showDownloadIcon}
removeIcon={removeIcon}
downloadIcon={downloadIcon}
iconRender={iconRender}
2019-08-05 18:38:10 +08:00
locale={{ ...locale, ...propLocale }}
isImageUrl={isImageUrl}
progress={progress}
/>
);
2018-12-07 20:02:01 +08:00
};
const { getPrefixCls, direction } = React.useContext(ConfigContext);
const prefixCls = getPrefixCls('upload', customizePrefixCls);
const rcUploadProps = {
onStart,
onError,
onProgress,
onSuccess,
...props,
prefixCls,
beforeUpload,
};
delete rcUploadProps.className;
delete rcUploadProps.style;
// Remove id to avoid open by label when trigger is hidden
// !children: https://github.com/ant-design/ant-design/issues/14298
// disabled: https://github.com/ant-design/ant-design/issues/16478
// https://github.com/ant-design/ant-design/issues/24197
if (!children || disabled) {
delete rcUploadProps.id;
}
2019-07-22 19:18:47 +08:00
const uploadList = showUploadList ? (
<LocaleReceiver componentName="Upload" defaultLocale={defaultLocale.Upload}>
{renderUploadList}
</LocaleReceiver>
) : null;
if (type === 'drag') {
const dragCls = classNames(
prefixCls,
{
[`${prefixCls}-drag`]: true,
[`${prefixCls}-drag-uploading`]: getFileList().some(file => file.status === 'uploading'),
[`${prefixCls}-drag-hover`]: dragState === 'dragover',
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-rtl`]: direction === 'rtl',
},
className,
);
return (
<span>
<div
className={dragCls}
onDrop={onFileDrop}
onDragOver={onFileDrop}
onDragLeave={onFileDrop}
style={style}
>
<RcUpload {...rcUploadProps} ref={upload} className={`${prefixCls}-btn`}>
<div className={`${prefixCls}-drag-container`}>{children}</div>
</RcUpload>
</div>
{uploadList}
</span>
);
}
const uploadButtonCls = classNames(prefixCls, {
[`${prefixCls}-select`]: true,
[`${prefixCls}-select-${listType}`]: true,
[`${prefixCls}-disabled`]: disabled,
[`${prefixCls}-rtl`]: direction === 'rtl',
});
const uploadButton = (
<div className={uploadButtonCls} style={children ? undefined : { display: 'none' }}>
<RcUpload {...rcUploadProps} ref={upload} />
</div>
);
if (listType === 'picture-card') {
return (
<span className={classNames(className, `${prefixCls}-picture-card-wrapper`)}>
{uploadList}
{uploadButton}
</span>
);
}
return (
<span className={className}>
{uploadButton}
{uploadList}
</span>
);
};
interface CompoundedComponent
extends React.ForwardRefExoticComponent<UploadProps & React.RefAttributes<any>> {
Dragger: typeof Dragger;
}
const Upload = React.forwardRef<unknown, UploadProps>(InternalUpload) as CompoundedComponent;
Upload.Dragger = Dragger;
Upload.displayName = 'Upload';
Upload.defaultProps = {
type: 'select' as UploadType,
multiple: false,
action: '',
data: {},
accept: '',
beforeUpload: T,
showUploadList: true,
listType: 'text' as UploadListType, // or picture
className: '',
disabled: false,
supportServerRender: true,
};
export default Upload;