index.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /* eslint-disable max-len */
  2. import React, { ReactNode, CSSProperties, RefObject, ChangeEvent, DragEvent } from 'react';
  3. import cls from 'classnames';
  4. import PropTypes from 'prop-types';
  5. import { noop } from 'lodash-es';
  6. import UploadFoundation, { BaseFileItem, UploadAdapter, BeforeUploadObjectResult, AfterUploadResult } from '@douyinfe/semi-foundation/upload/foundation';
  7. import { strings, cssClasses } from '@douyinfe/semi-foundation/upload/constants';
  8. import FileCard from './fileCard';
  9. import BaseComponent, { ValidateStatus } from '../_base/baseComponent';
  10. import LocaleConsumer from '../locale/localeConsumer';
  11. import { IconUpload } from '@douyinfe/semi-icons';
  12. import { FileItem, RenderFileItemProps, UploadListType, PromptPositionType, BeforeUploadProps, AfterUploadProps, OnChangeProps, customRequestArgs, CustomError } from './interface';
  13. import { Locale } from '../locale/interface';
  14. import '@douyinfe/semi-foundation/upload/upload.scss';
  15. const prefixCls = cssClasses.PREFIX;
  16. export { FileItem, RenderFileItemProps, UploadListType, PromptPositionType, BeforeUploadProps, AfterUploadProps, OnChangeProps, customRequestArgs, CustomError, BeforeUploadObjectResult, AfterUploadResult };
  17. export interface UploadProps {
  18. accept?: string;
  19. action: string;
  20. afterUpload?: (object: AfterUploadProps) => AfterUploadResult;
  21. beforeUpload?: (object: BeforeUploadProps) => BeforeUploadObjectResult | Promise<BeforeUploadObjectResult> | boolean;
  22. beforeClear?: (fileList: Array<FileItem>) => boolean | Promise<boolean>;
  23. beforeRemove?: (file: FileItem, fileList: Array<FileItem>) => boolean | Promise<boolean>;
  24. capture?: boolean | string | undefined;
  25. children?: ReactNode;
  26. className?: string;
  27. customRequest?: (object: customRequestArgs) => void;
  28. data?: Record<string, any> | ((file: File) => Record<string, unknown>);
  29. defaultFileList?: Array<FileItem>;
  30. directory?: boolean;
  31. disabled?: boolean;
  32. dragIcon?: ReactNode;
  33. dragMainText?: ReactNode;
  34. dragSubText?: ReactNode;
  35. draggable?: boolean;
  36. fileList?: Array<FileItem>;
  37. fileName?: string;
  38. headers?: Record<string, any> | ((file: File) => Record<string, string>);
  39. itemStyle?: CSSProperties;
  40. limit?: number;
  41. listType?: UploadListType;
  42. maxSize?: number;
  43. minSize?: number;
  44. multiple?: boolean;
  45. name?: string;
  46. onAcceptInvalid?: (files: File[]) => void;
  47. onChange?: (object: OnChangeProps) => void;
  48. onClear?: () => void;
  49. onDrop?: (e: Event, files: Array<File>, fileList: Array<FileItem>) => void;
  50. onError?: (e: CustomError, file: File, fileList: Array<FileItem>, xhr: XMLHttpRequest) => void;
  51. onExceed?: (fileList: Array<File>) => void;
  52. onFileChange?: (files: Array<File>) => void;
  53. onOpenFileDialog?: () => void;
  54. onPreviewClick?: (fileItem: FileItem) => void;
  55. onProgress?: (percent: number, file: File, fileList: Array<FileItem>) => void;
  56. onRemove?: (currentFile: File, fileList: Array<FileItem>, currentFileItem: FileItem) => void;
  57. onRetry?: (fileItem: FileItem) => void;
  58. onSizeError?: (file: File, fileList: Array<FileItem>) => void;
  59. onSuccess?: (responseBody: any, file: File, fileList: Array<FileItem>) => void;
  60. previewFile?: (renderFileItemProps: RenderFileItemProps) => ReactNode;
  61. prompt?: ReactNode;
  62. promptPosition?: PromptPositionType;
  63. renderFileItem?: (renderFileItemProps: RenderFileItemProps) => ReactNode;
  64. showClear?: boolean;
  65. showReplace?: boolean; // Display replacement function
  66. showRetry?: boolean;
  67. showUploadList?: boolean;
  68. style?: CSSProperties;
  69. timeout?: number;
  70. transformFile?: (file: File) => FileItem;
  71. uploadTrigger?: 'auto' | 'custom';
  72. validateMessage?: ReactNode;
  73. validateStatus?: ValidateStatus;
  74. withCredentials?: boolean;
  75. }
  76. export interface UploadState {
  77. dragAreaStatus: 'default' | 'legal' | 'illegal'; // Status of the drag zone
  78. fileList: Array<FileItem>;
  79. inputKey: number;
  80. localUrls: Array<string>;
  81. replaceIdx: number;
  82. replaceInputKey: number;
  83. }
  84. class Upload extends BaseComponent<UploadProps, UploadState> {
  85. static propTypes = {
  86. accept: PropTypes.string, // Limit allowed file types
  87. action: PropTypes.string.isRequired,
  88. afterUpload: PropTypes.func,
  89. beforeClear: PropTypes.func,
  90. beforeRemove: PropTypes.func,
  91. beforeUpload: PropTypes.func,
  92. children: PropTypes.node,
  93. className: PropTypes.string,
  94. customRequest: PropTypes.func,
  95. data: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), // Extra parameters attached when uploading
  96. defaultFileList: PropTypes.array,
  97. directory: PropTypes.bool, // Support folder upload
  98. disabled: PropTypes.bool,
  99. dragIcon: PropTypes.node,
  100. dragMainText: PropTypes.node,
  101. dragSubText: PropTypes.node,
  102. draggable: PropTypes.bool,
  103. fileList: PropTypes.array, // files had been uploaded
  104. fileName: PropTypes.string, // same as name, to avoid props conflict in Form.Upload
  105. headers: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
  106. itemStyle: PropTypes.object,
  107. limit: PropTypes.number, // 最大允许上传文件个数
  108. listType: PropTypes.oneOf<UploadProps['listType']>(strings.LIST_TYPE),
  109. maxSize: PropTypes.number, // 文件大小限制,单位kb
  110. minSize: PropTypes.number, // 文件大小限制,单位kb
  111. multiple: PropTypes.bool,
  112. name: PropTypes.string, // file name
  113. onAcceptInvalid: PropTypes.func,
  114. onChange: PropTypes.func,
  115. onClear: PropTypes.func,
  116. onDrop: PropTypes.func,
  117. onError: PropTypes.func,
  118. onExceed: PropTypes.func, // Callback exceeding limit
  119. onFileChange: PropTypes.func, // Callback when file is selected
  120. onOpenFileDialog: PropTypes.func,
  121. onPreviewClick: PropTypes.func,
  122. onProgress: PropTypes.func,
  123. onRemove: PropTypes.func,
  124. onRetry: PropTypes.func,
  125. onSizeError: PropTypes.func, // Callback with invalid file size
  126. onSuccess: PropTypes.func,
  127. previewFile: PropTypes.func, // Custom preview
  128. prompt: PropTypes.node,
  129. promptPosition: PropTypes.oneOf<UploadProps['promptPosition']>(strings.PROMPT_POSITION),
  130. renderFileItem: PropTypes.func,
  131. showClear: PropTypes.bool,
  132. showReplace: PropTypes.bool,
  133. showRetry: PropTypes.bool,
  134. showUploadList: PropTypes.bool, // whether to show fileList
  135. style: PropTypes.object,
  136. timeout: PropTypes.number,
  137. transformFile: PropTypes.func,
  138. uploadTrigger: PropTypes.oneOf<UploadProps['uploadTrigger']>(strings.UPLOAD_TRIGGER), // auto、custom
  139. validateMessage: PropTypes.node,
  140. validateStatus: PropTypes.oneOf<UploadProps['validateStatus']>(strings.VALIDATE_STATUS),
  141. withCredentials: PropTypes.bool,
  142. };
  143. static defaultProps: Partial<UploadProps> = {
  144. defaultFileList: [],
  145. disabled: false,
  146. listType: 'list' as const,
  147. multiple: false,
  148. onAcceptInvalid: noop,
  149. onChange: noop,
  150. beforeRemove: () => true,
  151. beforeClear: () => true,
  152. onClear: noop,
  153. onDrop: noop,
  154. onError: noop,
  155. onExceed: noop,
  156. onFileChange: noop,
  157. onOpenFileDialog: noop,
  158. onProgress: noop,
  159. onRemove: noop,
  160. onRetry: noop,
  161. onSizeError: noop,
  162. onSuccess: noop,
  163. promptPosition: 'right' as const,
  164. showClear: true,
  165. showReplace: false,
  166. showRetry: true,
  167. showUploadList: true,
  168. uploadTrigger: 'auto' as const,
  169. withCredentials: false,
  170. };
  171. static FileCard = FileCard;
  172. constructor(props: UploadProps) {
  173. super(props);
  174. this.state = {
  175. fileList: props.defaultFileList || [],
  176. replaceIdx: -1,
  177. inputKey: Math.random(),
  178. replaceInputKey: Math.random(),
  179. // Status of the drag zone
  180. dragAreaStatus: 'default',
  181. localUrls: [],
  182. };
  183. this.foundation = new UploadFoundation(this.adapter);
  184. this.inputRef = React.createRef<HTMLInputElement>();
  185. this.replaceInputRef = React.createRef<HTMLInputElement>();
  186. }
  187. static getDerivedStateFromProps(props: UploadProps): Partial<UploadState> | null {
  188. const { fileList } = props;
  189. if ('fileList' in props) {
  190. return {
  191. fileList: fileList || []
  192. };
  193. }
  194. return null;
  195. }
  196. get adapter(): UploadAdapter<UploadProps, UploadState> {
  197. return {
  198. ...super.adapter,
  199. notifyFileSelect: (files): void => this.props.onFileChange(files),
  200. notifyError: (error, fileInstance, fileList, xhr): void => this.props.onError(error, fileInstance, fileList, xhr),
  201. notifySuccess: (responseBody, file, fileList): void => this.props.onSuccess(responseBody, file, fileList),
  202. notifyProgress: (percent, file, fileList): void => this.props.onProgress(percent, file, fileList),
  203. notifyRemove: (file, fileList, fileItem): void => this.props.onRemove(file, fileList, fileItem),
  204. notifySizeError: (file, fileList): void => this.props.onSizeError(file, fileList),
  205. notifyExceed: (fileList): void => this.props.onExceed(fileList),
  206. updateFileList: (fileList, cb): void => {
  207. if (typeof cb === 'function') {
  208. this.setState({ fileList }, cb);
  209. } else {
  210. this.setState({ fileList });
  211. }
  212. },
  213. notifyBeforeUpload: ({ file, fileList }): boolean | BeforeUploadObjectResult | Promise<BeforeUploadObjectResult> => this.props.beforeUpload({ file, fileList }),
  214. notifyAfterUpload: ({ response, file, fileList }): AfterUploadResult => this.props.afterUpload({ response, file, fileList }),
  215. resetInput: (): void => {
  216. this.setState(prevState => ({
  217. inputKey: Math.random()
  218. }));
  219. },
  220. resetReplaceInput: (): void => {
  221. this.setState(prevState => ({
  222. replaceInputKey: Math.random()
  223. }));
  224. },
  225. updateDragAreaStatus: (dragAreaStatus: string): void => this.setState({ dragAreaStatus } as { dragAreaStatus: 'default' | 'legal' | 'illegal' }),
  226. notifyChange: ({ currentFile, fileList }): void => this.props.onChange({ currentFile, fileList }),
  227. updateLocalUrls: (urls): void => this.setState({ localUrls: urls }),
  228. notifyClear: (): void => this.props.onClear(),
  229. notifyPreviewClick: (file): void => this.props.onPreviewClick(file),
  230. notifyDrop: (e, files, fileList): void => this.props.onDrop(e, files, fileList),
  231. notifyAcceptInvalid: (invalidFiles): void => this.props.onAcceptInvalid(invalidFiles),
  232. notifyBeforeRemove: (file, fileList): boolean | Promise<boolean> => this.props.beforeRemove(file, fileList),
  233. notifyBeforeClear: (fileList): boolean | Promise<boolean> => this.props.beforeClear(fileList),
  234. };
  235. }
  236. foundation: UploadFoundation;
  237. inputRef: RefObject<HTMLInputElement> = null;
  238. replaceInputRef: RefObject<HTMLInputElement> = null;
  239. componentWillUnmount(): void {
  240. this.foundation.destroy();
  241. }
  242. onClick = (): void => {
  243. const { inputRef, props } = this;
  244. const { onOpenFileDialog } = props;
  245. const isDisabled = Boolean(this.props.disabled);
  246. if (isDisabled || !inputRef || !inputRef.current) {
  247. return;
  248. }
  249. inputRef.current.click();
  250. if (onOpenFileDialog && typeof onOpenFileDialog) {
  251. onOpenFileDialog();
  252. }
  253. };
  254. onChange = (e: ChangeEvent<HTMLInputElement>): void => {
  255. const { files } = e.target;
  256. this.foundation.handleChange(files);
  257. };
  258. replace = (index: number): void => {
  259. this.setState({ replaceIdx: index }, () => {
  260. this.replaceInputRef.current.click();
  261. });
  262. };
  263. onReplaceChange = (e: ChangeEvent<HTMLInputElement>): void => {
  264. const { files } = e.target;
  265. this.foundation.handleReplaceChange(files);
  266. };
  267. clear = (): void => {
  268. this.foundation.handleClear();
  269. };
  270. remove = (fileItem: FileItem): void => {
  271. this.foundation.handleRemove(fileItem);
  272. };
  273. upload = (): void => {
  274. const { fileList } = this.state;
  275. this.foundation.startUpload(fileList);
  276. };
  277. renderFile = (file: FileItem, index: number, locale: Locale['Upload']): ReactNode => {
  278. const { name, status, validateMessage, _sizeInvalid } = file;
  279. const { previewFile, listType, itemStyle, showRetry, renderFileItem, disabled, onPreviewClick, showReplace } = this.props;
  280. const onRemove = (): void => this.remove(file);
  281. const onRetry = (): void => {
  282. this.foundation.retry(file);
  283. };
  284. const onReplace = (): void => {
  285. this.replace(index);
  286. };
  287. const fileCardProps = {
  288. ...file,
  289. previewFile,
  290. listType,
  291. onRemove,
  292. onRetry,
  293. key: `${name}${index}`,
  294. showRetry: typeof file.showRetry !== 'undefined' ? file.showRetry : showRetry,
  295. style: itemStyle,
  296. disabled,
  297. showReplace: typeof file.showReplace !== 'undefined' ? file.showReplace : showReplace,
  298. onReplace,
  299. onPreviewClick: typeof onPreviewClick !== 'undefined' ? (): void => this.foundation.handlePreviewClick(file) : undefined,
  300. };
  301. if (status === strings.FILE_STATUS_UPLOAD_FAIL && !validateMessage) {
  302. fileCardProps.validateMessage = locale.fail;
  303. }
  304. if (_sizeInvalid && !validateMessage) {
  305. fileCardProps.validateMessage = locale.illegalSize;
  306. }
  307. if (typeof renderFileItem === 'undefined') {
  308. return <FileCard {...fileCardProps} />;
  309. } else {
  310. return renderFileItem(fileCardProps);
  311. }
  312. };
  313. renderFileList = (): ReactNode => {
  314. const { showUploadList, listType, limit, disabled, children } = this.props;
  315. const { fileList: stateFileList } = this.state;
  316. const fileList = this.props.fileList || stateFileList;
  317. const isPicType = listType === strings.FILE_LIST_PIC;
  318. const showAddTriggerInList = isPicType && (limit ? limit > fileList.length : true);
  319. const uploadAddCls = cls(`${prefixCls }-add`, {
  320. [`${prefixCls }-picture-add`]: isPicType,
  321. [`${prefixCls}-picture-add-disabled`]: disabled
  322. });
  323. const addContent = (
  324. <div className={uploadAddCls} onClick={this.onClick}>
  325. {children}
  326. </div>
  327. );
  328. if (!showUploadList || !fileList.length) {
  329. if (showAddTriggerInList) {
  330. return addContent;
  331. }
  332. return null;
  333. }
  334. const fileListCls = cls(`${prefixCls }-file-list`, {
  335. [`${prefixCls }-picture-file-list`]: isPicType,
  336. });
  337. const titleCls = `${prefixCls }-file-list-title`;
  338. const mainCls = `${prefixCls }-file-list-main`;
  339. const showTitle = limit !== 1 && fileList.length && listType !== strings.FILE_LIST_PIC;
  340. const showClear = this.props.showClear && !disabled;
  341. return (
  342. <LocaleConsumer componentName="Upload">
  343. {(locale: Locale['Upload']): ReactNode => (
  344. <div className={fileListCls}>
  345. {showTitle ? (
  346. <div className={titleCls}>
  347. <span className={`${titleCls }-choosen`}>{locale.selectedFiles}</span>
  348. {showClear ? (
  349. <span onClick={this.clear} className={`${titleCls }-clear`}>
  350. {locale.clear}
  351. </span>
  352. ) : null}
  353. </div>
  354. ) : null}
  355. <div className={mainCls}>
  356. {fileList.map((file, index) => this.renderFile(file, index, locale))}
  357. {showAddTriggerInList ? addContent : null}
  358. </div>
  359. </div>
  360. )}
  361. </LocaleConsumer>
  362. );
  363. };
  364. onDrop = (e: DragEvent<HTMLDivElement>): void => {
  365. this.foundation.handleDrop(e);
  366. };
  367. onDragOver = (e: DragEvent<HTMLDivElement>): void => {
  368. // When a drag element moves within the target element
  369. this.foundation.handleDragOver(e);
  370. };
  371. onDragLeave = (e: DragEvent<HTMLDivElement>): void => {
  372. this.foundation.handleDragLeave(e);
  373. };
  374. onDragEnter = (e: DragEvent<HTMLDivElement>): void => {
  375. this.foundation.handleDragEnter(e);
  376. };
  377. renderDragArea = (): ReactNode => {
  378. const { dragAreaStatus } = this.state;
  379. const { children, dragIcon, dragMainText, dragSubText } = this.props;
  380. const dragAreaBaseCls = `${prefixCls }-drag-area`;
  381. const dragAreaCls = cls(dragAreaBaseCls, {
  382. [`${dragAreaBaseCls }-legal`]: dragAreaStatus === strings.DRAG_AREA_LEGAL,
  383. [`${dragAreaBaseCls }-illegal`]: dragAreaStatus === strings.DRAG_AREA_ILLEGAL,
  384. [`${dragAreaBaseCls }-custom`]: children,
  385. });
  386. return (
  387. <LocaleConsumer componentName="Upload">
  388. {(locale: Locale['Upload']): ReactNode => (
  389. <div
  390. className={dragAreaCls}
  391. onDrop={this.onDrop}
  392. onDragOver={this.onDragOver}
  393. onDragLeave={this.onDragLeave}
  394. onDragEnter={this.onDragEnter}
  395. onClick={this.onClick}
  396. >
  397. {children ? (
  398. children
  399. ) : (
  400. <>
  401. <div className={`${dragAreaBaseCls }-icon`}>
  402. {dragIcon || <IconUpload size="extra-large" />}
  403. </div>
  404. <div className={`${dragAreaBaseCls }-text`}>
  405. <div className={`${dragAreaBaseCls }-main-text`}>
  406. {dragMainText || locale.mainText}
  407. </div>
  408. <div className={`${dragAreaBaseCls }-sub-text`}>{dragSubText}</div>
  409. <div className={`${dragAreaBaseCls }-tips`}>
  410. {dragAreaStatus === strings.DRAG_AREA_LEGAL && (
  411. <span className={`${dragAreaBaseCls }-tips-legal`}>{locale.legalTips}</span>
  412. )}
  413. {dragAreaStatus === strings.DRAG_AREA_ILLEGAL && (
  414. <span className={`${dragAreaBaseCls }-tips-illegal`}>
  415. {locale.illegalTips}
  416. </span>
  417. )}
  418. </div>
  419. </div>
  420. </>
  421. )}
  422. </div>
  423. )}
  424. </LocaleConsumer>
  425. );
  426. };
  427. render(): ReactNode {
  428. const {
  429. style,
  430. className,
  431. multiple,
  432. accept,
  433. disabled,
  434. children,
  435. capture,
  436. listType,
  437. prompt,
  438. promptPosition,
  439. draggable,
  440. validateMessage,
  441. validateStatus,
  442. directory,
  443. } = this.props;
  444. const uploadCls = cls(prefixCls, {
  445. [`${prefixCls }-picture`]: listType === strings.FILE_LIST_PIC,
  446. [`${prefixCls }-disabled`]: disabled,
  447. [`${prefixCls }-default`]: validateStatus === 'default',
  448. [`${prefixCls }-error`]: validateStatus === 'error',
  449. [`${prefixCls }-warning`]: validateStatus === 'warning',
  450. [`${prefixCls }-success`]: validateStatus === 'success',
  451. }, className);
  452. const uploadAddCls = cls(`${prefixCls }-add`);
  453. const inputCls = cls(`${prefixCls }-hidden-input`);
  454. const inputReplaceCls = cls(`${prefixCls }-hidden-input-replace`);
  455. const promptCls = cls(`${prefixCls }-prompt`);
  456. const validateMsgCls = cls(`${prefixCls }-validate-message`);
  457. const dirProps = directory ? { directory: 'directory', webkitdirectory: 'webkitdirectory' } : {};
  458. const addContent =
  459. listType !== strings.FILE_LIST_PIC ? (
  460. <div className={uploadAddCls} onClick={this.onClick}>
  461. {children}
  462. </div>
  463. ) : null;
  464. return (
  465. <div className={uploadCls} style={style} x-prompt-pos={promptPosition}>
  466. <input
  467. key={this.state.inputKey}
  468. capture={capture}
  469. multiple={multiple}
  470. accept={accept}
  471. onChange={this.onChange}
  472. type="file"
  473. autoComplete="off"
  474. tabIndex={-1}
  475. className={inputCls}
  476. ref={this.inputRef}
  477. {...dirProps}
  478. />
  479. <input
  480. key={this.state.replaceInputKey}
  481. multiple={false}
  482. accept={accept}
  483. onChange={this.onReplaceChange}
  484. type="file"
  485. autoComplete="off"
  486. tabIndex={-1}
  487. className={inputReplaceCls}
  488. ref={this.replaceInputRef}
  489. />
  490. {draggable ? this.renderDragArea() : addContent}
  491. {prompt ? <div className={promptCls}>{prompt}</div> : null}
  492. {validateMessage ? <div className={validateMsgCls}>{validateMessage}</div> : null}
  493. {this.renderFileList()}
  494. </div>
  495. );
  496. }
  497. }
  498. export default Upload;