UNPKG

@douyinfe/semi-ui

Version:

A modern, comprehensive, flexible design system and UI library. Connect DesignOps & DevOps. Quickly build beautiful React apps. Maintained by Douyin-fe team.

1,071 lines 37.3 kB
import _pick from "lodash/pick"; import _noop from "lodash/noop"; var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import React from 'react'; import cls from 'classnames'; import PropTypes from 'prop-types'; import UploadFoundation from '@douyinfe/semi-foundation/lib/es/upload/foundation'; import { strings, cssClasses } from '@douyinfe/semi-foundation/lib/es/upload/constants'; import FileCard from './fileCard'; import BaseComponent from '../_base/baseComponent'; import LocaleConsumer from '../locale/localeConsumer'; import { IconUpload } from '@douyinfe/semi-icons'; import Cropper from '../cropper'; import Modal from '../modal'; import '@douyinfe/semi-foundation/lib/es/upload/upload.css'; const prefixCls = cssClasses.PREFIX; class Upload extends BaseComponent { constructor(props) { var _this; super(props); _this = this; this.inputRef = null; this.replaceInputRef = null; this.cropperRef = null; this.pastingCb = null; this.pasteEventCb = null; this.onClick = () => { const { inputRef, props } = this; const { onOpenFileDialog } = props; const isDisabled = Boolean(this.props.disabled); if (isDisabled || !inputRef || !inputRef.current) { return; } inputRef.current.click(); if (onOpenFileDialog && typeof onOpenFileDialog) { onOpenFileDialog(); } }; this.onChange = e => { const { files } = e.target; const { crop } = this.props; if (crop && files && files.length > 0) { const fileArr = Array.from(files); if (fileArr.some(file => this.isImageFile(file))) { this.handleCropFiles(fileArr); return; } } this.foundation.handleChange(files); }; /** * Check if file is an image */ this.isImageFile = file => { return file.type.startsWith('image/'); }; /** * Entry point that decides whether incoming files need cropping. * Image files are queued for sequential cropping; non-image files are kept aside * and uploaded together with the cropped results once the queue drains. */ this.handleCropFiles = function (files) { let isReplaceOperation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return __awaiter(_this, void 0, void 0, function* () { const imageFiles = files.filter(file => this.isImageFile(file)); const nonImageFiles = files.filter(file => !this.isImageFile(file)); if (imageFiles.length === 0) { // No images to crop, fall back to the normal upload path this.dispatchUpload(files, isReplaceOperation); return; } const shouldCrop = yield this.shouldCropFile(imageFiles[0], files); if (!shouldCrop) { this.dispatchUpload(files, isReplaceOperation); return; } // Replace only ever consumes a single file, ignore extras for safety const queue = isReplaceOperation ? [imageFiles[0]] : imageFiles; const [first, ...rest] = queue; this.setState({ cropperVisible: true, cropperFile: first, cropperSrc: URL.createObjectURL(first), pendingImageFiles: rest, nonImageFiles: isReplaceOperation ? [] : nonImageFiles, croppedFiles: [], isReplaceOperation }); }); }; /** * Run the user-provided beforeCrop hook (if any) and return whether cropping should proceed. * Errors fall back to skipping cropping so users are never blocked. */ this.shouldCropFile = (file, files) => __awaiter(this, void 0, void 0, function* () { const { beforeCrop, onCropError } = this.props; if (!beforeCrop) { return true; } try { const result = yield beforeCrop(file, files); return result !== false; } catch (error) { onCropError === null || onCropError === void 0 ? void 0 : onCropError(error); return false; } }); /** * Forward files to the appropriate foundation handler based on operation type. */ this.dispatchUpload = (files, isReplaceOperation) => { if (isReplaceOperation) { this.foundation.handleReplaceChange(files); } else { this.foundation.handleChange(files); } }; /** * Confirm the current crop. If more images are queued, advance to the next one; * otherwise dispatch the accumulated cropped files together with any non-image files. */ this.handleCropOk = () => __awaiter(this, void 0, void 0, function* () { var _a; const { cropperFile, pendingImageFiles, nonImageFiles, croppedFiles, isReplaceOperation } = this.state; const { crop, onCropError } = this.props; try { const cropperInstance = this.cropperRef.current; if (!cropperInstance || !cropperFile) { throw new Error('Cropper instance not found'); } const canvas = cropperInstance.getCropperCanvas(); const cropConfig = typeof crop === 'object' ? crop : {}; const quality = (_a = cropConfig.quality) !== null && _a !== void 0 ? _a : 0.92; const type = cropperFile.type || 'image/png'; const blob = yield new Promise((resolve, reject) => { canvas.toBlob(b => b ? resolve(b) : reject(new Error('Failed to create blob')), type, quality); }); // Preserve the original filename and lastModified so downstream consumers // can keep meaningful metadata about the user-chosen file. const croppedFile = new File([blob], cropperFile.name, { type, lastModified: cropperFile.lastModified }); const nextCropped = [...croppedFiles, croppedFile]; if (pendingImageFiles.length > 0) { // Move on to the next queued image const [next, ...rest] = pendingImageFiles; if (this.state.cropperSrc) { URL.revokeObjectURL(this.state.cropperSrc); } this.setState({ cropperFile: next, cropperSrc: URL.createObjectURL(next), pendingImageFiles: rest, croppedFiles: nextCropped }); return; } // Queue exhausted: close cropper and dispatch results this.closeCropperAndReset(); this.dispatchUpload([...nextCropped, ...nonImageFiles], isReplaceOperation); } catch (error) { onCropError === null || onCropError === void 0 ? void 0 : onCropError(error); } }); /** * Cancel the current crop session, revoke object URLs and reset state. */ this.handleCropCancel = () => { this.closeCropperAndReset(); }; /** Internal helper that tears down crop state and resets the file input. */ this.closeCropperAndReset = () => { const { cropperSrc } = this.state; if (cropperSrc) { URL.revokeObjectURL(cropperSrc); } this.setState({ cropperVisible: false, cropperFile: null, cropperSrc: '', pendingImageFiles: [], nonImageFiles: [], croppedFiles: [], isReplaceOperation: false, // Reset input key so picking the same file again re-triggers onChange inputKey: Math.random(), replaceInputKey: Math.random() }); }; this.replace = index => { this.setState({ replaceIdx: index }, () => { this.replaceInputRef.current.click(); }); }; this.onReplaceChange = e => { const { files } = e.target; const { crop } = this.props; if (crop && files && files.length > 0) { const fileArr = Array.from(files); if (fileArr.some(file => this.isImageFile(file))) { this.handleCropFiles(fileArr, true); return; } } this.foundation.handleReplaceChange(files); }; this.clear = () => { this.foundation.handleClear(); }; this.remove = fileItem => { this.foundation.handleRemove(fileItem); }; /** * ref method * insert files at index * @param files Array<CustomFile> * @param index number * @returns */ this.insert = (files, index) => { return this.foundation.insertFileToList(files, index); }; /** * ref method * manual upload by user */ this.upload = () => { this.foundation.manualUpload(); }; /** * ref method * manual open file select dialog */ this.openFileDialog = () => { this.onClick(); }; this.renderFile = (file, index, locale) => { const { name, status, validateMessage, _sizeInvalid, uid } = file; const { previewFile, listType, itemStyle, showPicInfo, renderPicInfo, renderPicClose, renderPicPreviewIcon, renderFileOperation, renderFileItem, renderThumbnail, disabled, onPreviewClick, picWidth, picHeight, showTooltip } = this.props; const onRemove = () => this.remove(file); const onRetry = () => { this.foundation.retry(file); }; const onReplace = () => { this.replace(index); }; const fileCardProps = Object.assign(Object.assign(Object.assign({}, _pick(this.props, ['showRetry', 'showReplace', ''])), file), { previewFile, listType, onRemove, onRetry, index, key: uid || `${name}${index}`, style: itemStyle, disabled, showPicInfo, renderPicInfo, renderPicPreviewIcon, renderPicClose, renderFileOperation, renderThumbnail, onReplace, onPreviewClick: typeof onPreviewClick !== 'undefined' ? () => this.foundation.handlePreviewClick(file) : undefined, picWidth, picHeight, showTooltip }); if (status === strings.FILE_STATUS_UPLOAD_FAIL && !validateMessage) { fileCardProps.validateMessage = locale.fail; } if (_sizeInvalid && !validateMessage) { fileCardProps.validateMessage = locale.illegalSize; } if (typeof renderFileItem === 'undefined') { return /*#__PURE__*/React.createElement(FileCard, Object.assign({}, fileCardProps)); } else { return renderFileItem(fileCardProps); } }; this.renderFileList = () => { const { listType } = this.props; if (listType === strings.FILE_LIST_PIC) { return this.renderFileListPic(); } if (listType === strings.FILE_LIST_DEFAULT) { return this.renderFileListDefault(); } return null; }; this.renderFileListPic = () => { const { showUploadList, limit, disabled, children, draggable, hotSpotLocation, picHeight, picWidth } = this.props; const { fileList: stateFileList, dragAreaStatus } = this.state; const fileList = this.props.fileList || stateFileList; const showAddTriggerInList = limit ? limit > fileList.length : true; const dragAreaBaseCls = `${prefixCls}-drag-area`; const uploadAddCls = cls(`${prefixCls}-add`, { [`${prefixCls}-picture-add`]: true, [`${prefixCls}-picture-add-disabled`]: disabled }); const fileListCls = cls(`${prefixCls}-file-list`, { [`${prefixCls}-picture-file-list`]: true }); const dragAreaCls = cls({ [`${dragAreaBaseCls}-legal`]: dragAreaStatus === strings.DRAG_AREA_LEGAL, [`${dragAreaBaseCls}-illegal`]: dragAreaStatus === strings.DRAG_AREA_ILLEGAL }); const mainCls = `${prefixCls}-file-list-main`; const addContentProps = { role: 'button', className: uploadAddCls, onClick: this.onClick, style: { height: picHeight, width: picWidth } }; const containerProps = { className: fileListCls }; const draggableProps = { onDrop: this.onDrop, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDragEnter: this.onDragEnter }; if (draggable) { Object.assign(addContentProps, draggableProps, { className: cls(uploadAddCls, dragAreaCls) }); } const addContent = /*#__PURE__*/React.createElement("div", Object.assign({}, addContentProps, { "x-semi-prop": "children" }), children); if (!showUploadList || !fileList.length) { if (showAddTriggerInList) { return addContent; } return null; } return /*#__PURE__*/React.createElement(LocaleConsumer, { componentName: "Upload" }, locale => (/*#__PURE__*/React.createElement("div", Object.assign({}, containerProps), /*#__PURE__*/React.createElement("div", { className: mainCls, role: "list", "aria-label": "picture list" }, showAddTriggerInList && hotSpotLocation === 'start' ? addContent : null, fileList.map((file, index) => this.renderFile(file, index, locale)), showAddTriggerInList && hotSpotLocation === 'end' ? addContent : null)))); }; this.renderFileListDefault = () => { const { showUploadList, limit, disabled, fileListTitle } = this.props; const { fileList: stateFileList } = this.state; const fileList = this.props.fileList || stateFileList; const fileListCls = cls(`${prefixCls}-file-list`); const titleCls = `${prefixCls}-file-list-title`; const mainCls = `${prefixCls}-file-list-main`; const showTitle = limit !== 1 && fileList.length; const showClear = this.props.showClear && !disabled; const containerProps = { className: fileListCls }; if (!showUploadList || !fileList.length) { return null; } return /*#__PURE__*/React.createElement(LocaleConsumer, { componentName: "Upload" }, locale => { let titleContent; if (typeof fileListTitle === 'function') { // 函数形式:用户完全控制标题区域 titleContent = fileListTitle({ fileList, onClear: this.clear, clearText: locale.clear }); } else { // ReactNode 或默认值:显示标题文字和清空按钮 titleContent = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", { className: `${titleCls}-choosen` }, fileListTitle || locale.selectedFiles), showClear ? (/*#__PURE__*/React.createElement("span", { role: "button", tabIndex: 0, onClick: this.clear, className: `${titleCls}-clear` }, locale.clear)) : null); } return /*#__PURE__*/React.createElement("div", Object.assign({}, containerProps), showTitle ? (/*#__PURE__*/React.createElement("div", { className: titleCls }, titleContent)) : null, /*#__PURE__*/React.createElement("div", { className: mainCls, role: "list", "aria-label": "file list" }, fileList.map((file, index) => this.renderFile(file, index, locale)))); }); }; this.onDrop = e => { const { crop, directory, disabled } = this.props; // For disabled / directory / no-crop scenarios, defer to the foundation // so existing accept / limit / drag-area-status / notifyDrop logic still applies. if (disabled || directory || !crop) { this.foundation.handleDrop(e); return; } const files = e.dataTransfer && e.dataTransfer.files ? Array.from(e.dataTransfer.files) : []; if (files.length === 0 || !files.some(file => this.isImageFile(file))) { this.foundation.handleDrop(e); return; } // We need to short-circuit the foundation's default handling so the original files // are not uploaded before cropping. Reproduce only the side effects that would // otherwise happen: prevent default browser open, reset drag status, fire onDrop. e.preventDefault(); e.stopPropagation(); const fileList = this.state.fileList.slice(); this.setState({ dragAreaStatus: 'default' }); const eventForCb = e.nativeEvent || e; this.props.onDrop(eventForCb, files, fileList); this.handleCropFiles(files); }; this.onDragOver = e => { // When a drag element moves within the target element this.foundation.handleDragOver(e); }; this.onDragLeave = e => { this.foundation.handleDragLeave(e); }; this.onDragEnter = e => { this.foundation.handleDragEnter(e); }; this.renderAddContent = () => { const { draggable, children, listType, disabled } = this.props; const uploadAddCls = cls(`${prefixCls}-add`); if (listType === strings.FILE_LIST_PIC) { return null; } if (draggable) { return this.renderDragArea(); } return /*#__PURE__*/React.createElement("div", { role: "button", tabIndex: 0, "aria-disabled": disabled, className: uploadAddCls, onClick: this.onClick }, children); }; this.renderDragArea = () => { const { dragAreaStatus } = this.state; const { children, dragIcon, dragMainText, dragSubText, disabled } = this.props; const dragAreaBaseCls = `${prefixCls}-drag-area`; const dragAreaCls = cls(dragAreaBaseCls, { [`${dragAreaBaseCls}-legal`]: dragAreaStatus === strings.DRAG_AREA_LEGAL, [`${dragAreaBaseCls}-illegal`]: dragAreaStatus === strings.DRAG_AREA_ILLEGAL, [`${dragAreaBaseCls}-custom`]: children }); return /*#__PURE__*/React.createElement(LocaleConsumer, { componentName: "Upload" }, locale => (/*#__PURE__*/React.createElement("div", { role: "button", tabIndex: 0, "aria-disabled": disabled, className: dragAreaCls, onDrop: this.onDrop, onDragOver: this.onDragOver, onDragLeave: this.onDragLeave, onDragEnter: this.onDragEnter, onClick: this.onClick }, children ? children : (/*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { className: `${dragAreaBaseCls}-icon`, "x-semi-prop": "dragIcon" }, dragIcon || /*#__PURE__*/React.createElement(IconUpload, { size: "extra-large" })), /*#__PURE__*/React.createElement("div", { className: `${dragAreaBaseCls}-text` }, /*#__PURE__*/React.createElement("div", { className: `${dragAreaBaseCls}-main-text`, "x-semi-prop": "dragMainText" }, dragMainText || locale.mainText), /*#__PURE__*/React.createElement("div", { className: `${dragAreaBaseCls}-sub-text`, "x-semi-prop": "dragSubText" }, dragSubText), /*#__PURE__*/React.createElement("div", { className: `${dragAreaBaseCls}-tips` }, dragAreaStatus === strings.DRAG_AREA_LEGAL && (/*#__PURE__*/React.createElement("span", { className: `${dragAreaBaseCls}-tips-legal` }, locale.legalTips)), dragAreaStatus === strings.DRAG_AREA_ILLEGAL && (/*#__PURE__*/React.createElement("span", { className: `${dragAreaBaseCls}-tips-illegal` }, locale.illegalTips))))))))); }; this.renderCropperModal = () => { const { cropperVisible, cropperSrc } = this.state; const { crop, cropModalProps } = this.props; const cropConfig = typeof crop === 'object' ? crop : {}; const _a = cropModalProps || {}, { style: modalStyle, bodyStyle: modalBodyStyle } = _a, restModalProps = __rest(_a, ["style", "bodyStyle"]); return /*#__PURE__*/React.createElement(LocaleConsumer, { componentName: "Upload" }, locale => { const modalTitle = cropConfig.modalTitle || locale.cropTitle || '裁切图片'; const modalOkText = cropConfig.modalOkText || locale.cropOk || '确定'; const modalCancelText = cropConfig.modalCancelText || locale.cropCancel || '取消'; return /*#__PURE__*/React.createElement(Modal, Object.assign({}, restModalProps, { width: 600, title: modalTitle, visible: cropperVisible, onOk: this.handleCropOk, onCancel: this.handleCropCancel, okText: modalOkText, cancelText: modalCancelText, style: Object.assign({ height: 500 }, modalStyle || {}), bodyStyle: Object.assign({ height: 400 }, modalBodyStyle || {}) }), cropperSrc && (/*#__PURE__*/React.createElement(Cropper, { ref: this.cropperRef, src: cropperSrc, shape: cropConfig.shape || 'rect', aspectRatio: cropConfig.aspectRatio, minZoom: cropConfig.minZoom, maxZoom: cropConfig.maxZoom, zoomStep: cropConfig.zoomStep, fill: cropConfig.fill, style: { width: '100%', height: '100%' } }))); }); }; this.state = { fileList: props.defaultFileList || [], replaceIdx: -1, inputKey: Math.random(), replaceInputKey: Math.random(), // Status of the drag zone dragAreaStatus: 'default', localUrls: [], // Cropper state cropperVisible: false, cropperFile: null, cropperSrc: '', pendingImageFiles: [], nonImageFiles: [], croppedFiles: [], isReplaceOperation: false }; this.foundation = new UploadFoundation(this.adapter); this.inputRef = /*#__PURE__*/React.createRef(); this.replaceInputRef = /*#__PURE__*/React.createRef(); this.cropperRef = /*#__PURE__*/React.createRef(); } /** * Notes: * The input parameter and return value here do not declare the type, otherwise tsc may report an error in form/fields.tsx when wrap after withField * `The types of the parameters "props" and "nextProps" are incompatible. The attribute "action" is missing in the type "Readonly<any>", but it is required in the type "UploadProps".` * which seems to be a bug, remove props type declare here */ static getDerivedStateFromProps(props) { const { fileList } = props; if ('fileList' in props) { return { fileList: fileList || [] }; } return null; } get adapter() { return Object.assign(Object.assign({}, super.adapter), { notifyFileSelect: files => this.props.onFileChange(files), notifyError: (error, fileInstance, fileList, xhr) => this.props.onError(error, fileInstance, fileList, xhr), notifySuccess: (responseBody, file, fileList) => this.props.onSuccess(responseBody, file, fileList), notifyProgress: (percent, file, fileList) => this.props.onProgress(percent, file, fileList), notifyRemove: (file, fileList, fileItem) => this.props.onRemove(file, fileList, fileItem), notifySizeError: (file, fileList) => this.props.onSizeError(file, fileList), notifyExceed: fileList => this.props.onExceed(fileList), updateFileList: (fileList, cb) => { if (typeof cb === 'function') { this.setState({ fileList }, cb); } else { this.setState({ fileList }); } }, notifyBeforeUpload: _ref => { let { file, fileList } = _ref; return this.props.beforeUpload({ file, fileList }); }, notifyAfterUpload: _ref2 => { let { response, file, fileList } = _ref2; return this.props.afterUpload({ response, file, fileList }); }, resetInput: () => { this.setState(prevState => ({ inputKey: Math.random() })); }, resetReplaceInput: () => { this.setState(prevState => ({ replaceInputKey: Math.random() })); }, isMac: () => { return navigator.platform.toUpperCase().indexOf('MAC') >= 0; }, registerPastingHandler: cb => { // Wrap the callback to intercept cropping const wrappedCb = e => { const { crop } = this.props; // Handle keydown event (Ctrl/Cmd+V) with crop interception if (crop && e.type === 'keydown' && 'code' in e) { const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0; const isCombineKeydown = isMac ? e.metaKey : e.ctrlKey; if (isCombineKeydown && e.code === 'KeyV') { // Check if navigator.clipboard is available if (navigator.clipboard && typeof navigator.clipboard.read === 'function') { const permissionName = 'clipboard-read'; navigator.permissions.query({ name: permissionName }).then(result => { if (result.state === 'granted' || result.state === 'prompt') { navigator.clipboard.read().then(clipboardItems => { const files = []; const processClipboardItems = () => __awaiter(this, void 0, void 0, function* () { for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) { if (type.startsWith('image')) { const blob = yield clipboardItem.getType(type); const buffer = yield blob.arrayBuffer(); const format = type.split('/')[1]; const file = new File([buffer], `paste.${format}`, { type }); files.push(file); } } } if (files.length > 0) { const imageFiles = files.filter(file => this.isImageFile(file)); if (imageFiles.length > 0) { // Start cropping this.handleCropFiles(files); } else { // No images, let foundation handle it this.foundation.handleChange(files); } } }); processClipboardItems(); }).catch(error => { this.props.onPastingError(error); }); } }).catch(error => { this.props.onPastingError(error); }); // Don't call original callback, we've handled it return; } } } // Otherwise, call original callback cb === null || cb === void 0 ? void 0 : cb(e); }; document.body.addEventListener('keydown', wrappedCb); this.pastingCb = wrappedCb; }, unRegisterPastingHandler: () => { if (this.pastingCb) { document.body.removeEventListener('keydown', this.pastingCb); } }, registerPasteEventHandler: cb => { // Intercept paste events when crop is enabled and the clipboard contains images; // otherwise pass through to the foundation-supplied handler unchanged. const wrappedCb = e => { const { crop } = this.props; if (crop && e.clipboardData && e.clipboardData.items) { const files = []; for (let i = 0; i < e.clipboardData.items.length; i++) { const item = e.clipboardData.items[i]; if (item.kind === 'file') { const file = item.getAsFile(); if (file) { files.push(file); } } } if (files.length > 0 && files.some(file => this.isImageFile(file))) { e.preventDefault(); this.handleCropFiles(files); return; } } cb === null || cb === void 0 ? void 0 : cb(e); }; document.body.addEventListener('paste', wrappedCb); this.pasteEventCb = wrappedCb; }, unRegisterPasteEventHandler: () => { if (this.pasteEventCb) { document.body.removeEventListener('paste', this.pasteEventCb); } }, notifyPastingError: error => this.props.onPastingError(error), updateDragAreaStatus: dragAreaStatus => this.setState({ dragAreaStatus }), notifyChange: _ref3 => { let { currentFile, fileList } = _ref3; return this.props.onChange({ currentFile, fileList }); }, updateLocalUrls: urls => this.setState({ localUrls: urls }), notifyClear: () => this.props.onClear(), notifyPreviewClick: file => this.props.onPreviewClick(file), notifyDrop: (e, files, fileList) => this.props.onDrop(e, files, fileList), notifyAcceptInvalid: invalidFiles => this.props.onAcceptInvalid(invalidFiles), notifyBeforeRemove: (file, fileList) => this.props.beforeRemove(file, fileList), notifyBeforeClear: fileList => this.props.beforeClear(fileList) }); } componentDidMount() { this.foundation.init(); } componentWillUnmount() { this.foundation.destroy(); } render() { const _a = this.props, { style, className, multiple, accept, disabled, children, capture, listType, prompt, promptPosition, draggable, validateMessage, validateStatus, directory } = _a, rest = __rest(_a, ["style", "className", "multiple", "accept", "disabled", "children", "capture", "listType", "prompt", "promptPosition", "draggable", "validateMessage", "validateStatus", "directory"]); const uploadCls = cls(prefixCls, { [`${prefixCls}-picture`]: listType === strings.FILE_LIST_PIC, [`${prefixCls}-disabled`]: disabled, [`${prefixCls}-default`]: validateStatus === 'default', [`${prefixCls}-error`]: validateStatus === 'error', [`${prefixCls}-warning`]: validateStatus === 'warning', [`${prefixCls}-success`]: validateStatus === 'success' }, className); const inputCls = cls(`${prefixCls}-hidden-input`); const inputReplaceCls = cls(`${prefixCls}-hidden-input-replace`); const promptCls = cls(`${prefixCls}-prompt`); const validateMsgCls = cls(`${prefixCls}-validate-message`); const dirProps = directory ? { directory: 'directory', webkitdirectory: 'webkitdirectory' } : {}; return /*#__PURE__*/React.createElement("div", Object.assign({ className: uploadCls, style: style, "x-prompt-pos": promptPosition }, this.getDataAttr(rest)), /*#__PURE__*/React.createElement("input", Object.assign({ key: this.state.inputKey, capture: capture, multiple: multiple, accept: accept, onChange: this.onChange, type: "file", autoComplete: "off", tabIndex: -1, className: inputCls, ref: this.inputRef }, dirProps)), /*#__PURE__*/React.createElement("input", { key: this.state.replaceInputKey, multiple: false, accept: accept, onChange: this.onReplaceChange, type: "file", autoComplete: "off", tabIndex: -1, className: inputReplaceCls, ref: this.replaceInputRef }), this.renderAddContent(), prompt ? (/*#__PURE__*/React.createElement("div", { className: promptCls, "x-semi-prop": "prompt" }, prompt)) : null, validateMessage ? (/*#__PURE__*/React.createElement("div", { className: validateMsgCls, "x-semi-prop": "validateMessage" }, validateMessage)) : null, this.renderFileList(), this.renderCropperModal()); } } Upload.propTypes = { accept: PropTypes.string, action: PropTypes.string.isRequired, addOnPasting: PropTypes.bool, afterUpload: PropTypes.func, beforeClear: PropTypes.func, beforeRemove: PropTypes.func, beforeUpload: PropTypes.func, children: PropTypes.node, className: PropTypes.string, customRequest: PropTypes.func, data: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), defaultFileList: PropTypes.array, directory: PropTypes.bool, disabled: PropTypes.bool, dragIcon: PropTypes.node, dragMainText: PropTypes.node, dragSubText: PropTypes.node, draggable: PropTypes.bool, fileList: PropTypes.array, fileName: PropTypes.string, headers: PropTypes.oneOfType([PropTypes.object, PropTypes.func]), hotSpotLocation: PropTypes.oneOf(['start', 'end']), itemStyle: PropTypes.object, limit: PropTypes.number, listType: PropTypes.oneOf(strings.LIST_TYPE), maxSize: PropTypes.number, minSize: PropTypes.number, multiple: PropTypes.bool, name: PropTypes.string, onAcceptInvalid: PropTypes.func, onChange: PropTypes.func, onClear: PropTypes.func, onDrop: PropTypes.func, onError: PropTypes.func, onExceed: PropTypes.func, onFileChange: PropTypes.func, onOpenFileDialog: PropTypes.func, onPreviewClick: PropTypes.func, onProgress: PropTypes.func, onRemove: PropTypes.func, onRetry: PropTypes.func, onSizeError: PropTypes.func, onSuccess: PropTypes.func, onPastingError: PropTypes.func, previewFile: PropTypes.func, prompt: PropTypes.node, promptPosition: PropTypes.oneOf(strings.PROMPT_POSITION), picWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), picHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), renderFileItem: PropTypes.func, renderPicPreviewIcon: PropTypes.func, renderFileOperation: PropTypes.func, renderPicClose: PropTypes.func, renderPicInfo: PropTypes.func, renderThumbnail: PropTypes.func, fileListTitle: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), showClear: PropTypes.bool, showPicInfo: PropTypes.bool, showReplace: PropTypes.bool, showRetry: PropTypes.bool, showUploadList: PropTypes.bool, style: PropTypes.object, timeout: PropTypes.number, transformFile: PropTypes.func, uploadTrigger: PropTypes.oneOf(strings.UPLOAD_TRIGGER), validateMessage: PropTypes.node, validateStatus: PropTypes.oneOf(strings.VALIDATE_STATUS), withCredentials: PropTypes.bool, showTooltip: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), crop: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), beforeCrop: PropTypes.func, onCropError: PropTypes.func, cropModalProps: PropTypes.object }; Upload.defaultProps = { defaultFileList: [], disabled: false, listType: 'list', hotSpotLocation: 'end', multiple: false, onAcceptInvalid: _noop, onChange: _noop, beforeRemove: () => true, beforeClear: () => true, onClear: _noop, onDrop: _noop, onError: _noop, onExceed: _noop, onFileChange: _noop, onOpenFileDialog: _noop, onProgress: _noop, onRemove: _noop, onRetry: _noop, onSizeError: _noop, onSuccess: _noop, onPastingError: _noop, promptPosition: 'right', showClear: true, showPicInfo: false, showReplace: false, showRetry: true, showUploadList: true, uploadTrigger: 'auto', withCredentials: false, showTooltip: true }; Upload.FileCard = FileCard; export default Upload;