UNPKG

acud

Version:

acg react 组件库

397 lines • 14 kB
import _extends from "@babel/runtime/helpers/esm/extends"; import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import _readOnlyError from "@babel/runtime/helpers/esm/readOnlyError"; import _typeof from "@babel/runtime/helpers/esm/typeof"; import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray"; import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck"; import _createClass from "@babel/runtime/helpers/esm/createClass"; import _possibleConstructorReturn from "@babel/runtime/helpers/esm/possibleConstructorReturn"; import _isNativeReflectConstruct from "@babel/runtime/helpers/esm/isNativeReflectConstruct"; import _getPrototypeOf from "@babel/runtime/helpers/esm/getPrototypeOf"; import _inherits from "@babel/runtime/helpers/esm/inherits"; import _regeneratorRuntime from "@babel/runtime/regenerator"; function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } /* eslint react/no-is-mounted:0,react/sort-comp:0,react/prop-types:0 */ /* * base-upload * author zhousheng */ 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, { Component } from 'react'; import classNames from 'classnames'; import pickAttrs from "rc-util/es/pickAttrs"; import defaultRequest from './request'; import getUid from './uid'; import attrAccept from './attr-accept'; import traverseFileTree from './traverseFileTree'; var AjaxUploader = /*#__PURE__*/function (_Component) { function AjaxUploader() { var _this; _classCallCheck(this, AjaxUploader); _this = _callSuper(this, AjaxUploader, arguments); _this.state = { uid: getUid() }; _this.reqs = {}; _this.onChange = function (e) { var _this$props = _this.props, accept = _this$props.accept, directory = _this$props.directory; var files = e.target.files; var acceptedFiles = _toConsumableArray(files).filter(function (file) { return !directory || attrAccept(file, accept); }); _this.uploadFiles(acceptedFiles); _this.reset(); }; _this.onClick = function (e) { var el = _this.fileInput; if (!el) { return; } var _this$props2 = _this.props, children = _this$props2.children, onClick = _this$props2.onClick; if (children && children.type === 'button') { var parent = el.parentNode; parent.focus(); parent.querySelector('button').blur(); } el.click(); if (onClick) { onClick(e); } }; _this.onKeyDown = function (e) { if (e.key === 'Enter') { _this.onClick(e); } }; _this.onFileDrop = function (e) { var multiple = _this.props.multiple; e.preventDefault(); if (e.type === 'dragover') { return; } if (_this.props.directory) { traverseFileTree(Array.prototype.slice.call(e.dataTransfer.items), _this.uploadFiles, function (_file) { return attrAccept(_file, _this.props.accept); }); } else { var files = _toConsumableArray(e.dataTransfer.files).filter(function (file) { return attrAccept(file, _this.props.accept); }); if (multiple === false) { files = files.slice(0, 1); } _this.uploadFiles(files); } }; _this.uploadFiles = function (files) { var originFiles = _toConsumableArray(files); var postFiles = originFiles.map(function (file) { // eslint-disable-next-line no-param-reassign // 处理重新上传文件时已有uid的情况 file.uid = (file === null || file === void 0 ? void 0 : file.uid) || getUid(); return _this.processFile(file, originFiles); }); // Batch upload files Promise.all(postFiles).then(function (fileList) { var onBatchStart = _this.props.onBatchStart; onBatchStart === null || onBatchStart === void 0 ? void 0 : onBatchStart(fileList.map(function (_ref) { var origin = _ref.origin, parsedFile = _ref.parsedFile; return { file: origin, parsedFile: parsedFile }; })); fileList.filter(function (file) { return file.parsedFile !== null; }).forEach(function (file) { _this.post(file); }); }); }; /** * Process file before upload. When all the file is ready, we start upload. */ _this.processFile = function (file, fileList) { return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() { var beforeUpload, transformedFile, action, mergedAction, data, mergedData, parsedData, parsedFile, mergedParsedFile, _t; return _regeneratorRuntime.wrap(function (_context) { while (1) switch (_context.prev = _context.next) { case 0: beforeUpload = this.props.beforeUpload; transformedFile = file; if (!beforeUpload) { _context.next = 5; break; } _context.prev = 1; _context.next = 2; return beforeUpload(file, fileList); case 2: transformedFile = _context.sent; _context.next = 4; break; case 3: _context.prev = 3; _t = _context["catch"](1); // Rejection will also trade as false transformedFile = false; case 4: if (!(transformedFile === false)) { _context.next = 5; break; } return _context.abrupt("return", { origin: file, parsedFile: null, action: null, data: null }); case 5: // Get latest action action = this.props.action; if (!(typeof action === 'function')) { _context.next = 7; break; } _context.next = 6; return action(file); case 6: mergedAction = _context.sent; _context.next = 8; break; case 7: mergedAction = action; case 8: // Get latest data data = this.props.data; if (!(typeof data === 'function')) { _context.next = 10; break; } _context.next = 9; return data(file); case 9: mergedData = _context.sent; _context.next = 11; break; case 10: mergedData = data; case 11: parsedData // string type is from legacy `transformFile`. // Not sure if this will work since no related test case works with it = (_typeof(transformedFile) === 'object' || typeof transformedFile === 'string') && transformedFile ? transformedFile : file; if (parsedData instanceof File) { parsedFile = parsedData; } else { parsedFile = new File([parsedData], file.name, { type: file.type }); } mergedParsedFile = parsedFile; mergedParsedFile.uid = file.uid; return _context.abrupt("return", { origin: file, data: mergedData, parsedFile: mergedParsedFile, action: mergedAction }); case 12: case "end": return _context.stop(); } }, _callee, this, [[1, 3]]); })); }; _this.saveFileInput = function (node) { _this.fileInput = node; }; return _this; } _inherits(AjaxUploader, _Component); return _createClass(AjaxUploader, [{ key: "componentDidMount", value: function componentDidMount() { this._isMounted = true; } }, { key: "componentWillUnmount", value: function componentWillUnmount() { this._isMounted = false; this.abort(); } }, { key: "post", value: function post(_ref2) { var _this2 = this; var data = _ref2.data, origin = _ref2.origin, action = _ref2.action, parsedFile = _ref2.parsedFile; if (!this._isMounted) { return; } var _this$props3 = this.props, onStart = _this$props3.onStart, customRequest = _this$props3.customRequest, name = _this$props3.name, headers = _this$props3.headers, withCredentials = _this$props3.withCredentials, method = _this$props3.method; var uid = origin.uid; var request = customRequest || defaultRequest; var requestOption = { action: action, filename: name, data: data, file: parsedFile, headers: headers, withCredentials: withCredentials, method: method || 'post', onProgress: function onProgress(e) { var onProgress = _this2.props.onProgress; onProgress === null || onProgress === void 0 ? void 0 : onProgress(e, parsedFile); }, onSuccess: function onSuccess(ret, xhr) { var onSuccess = _this2.props.onSuccess; onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(ret, parsedFile, xhr); delete _this2.reqs[uid]; }, onError: function onError(err, ret) { var onError = _this2.props.onError; onError === null || onError === void 0 ? void 0 : onError(err, ret, parsedFile); delete _this2.reqs[uid]; } }; onStart(origin); this.reqs[uid] = request(requestOption); } }, { key: "reset", value: function reset() { this.setState({ uid: getUid() }); } }, { key: "abort", value: function abort(file) { var reqs = this.reqs; if (file) { var uid = file.uid ? file.uid : file; if (reqs[uid] && reqs[uid].abort) { reqs[uid].abort(); } delete reqs[uid]; } else { Object.keys(reqs).forEach(function (uid) { if (reqs[uid] && reqs[uid].abort) { reqs[uid].abort(); } delete reqs[uid]; }); } } }, { key: "render", value: function render() { var _a = this.props, Tag = _a.component, prefixCls = _a.prefixCls, className = _a.className, disabled = _a.disabled, id = _a.id, style = _a.style, multiple = _a.multiple, accept = _a.accept, capture = _a.capture, children = _a.children, directory = _a.directory, openFileDialogOnClick = _a.openFileDialogOnClick, onMouseEnter = _a.onMouseEnter, onMouseLeave = _a.onMouseLeave, otherProps = __rest(_a, ["component", "prefixCls", "className", "disabled", "id", "style", "multiple", "accept", "capture", "children", "directory", "openFileDialogOnClick", "onMouseEnter", "onMouseLeave"]); var cls = classNames(_defineProperty(_defineProperty(_defineProperty({}, prefixCls, true), "".concat(prefixCls, "-disabled"), disabled), className, className)); // because input don't have directory/webkitdirectory type declaration var dirProps = directory ? { directory: 'directory', webkitdirectory: 'webkitdirectory' } : {}; var events = disabled ? {} : { onClick: openFileDialogOnClick ? this.onClick : function () {}, onKeyDown: openFileDialogOnClick ? this.onKeyDown : function () {}, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onDrop: this.onFileDrop, onDragOver: this.onFileDrop, tabIndex: '0' }; return /*#__PURE__*/React.createElement(Tag, _extends({}, events, { className: cls, role: "button", disabled: disabled, style: style }), /*#__PURE__*/React.createElement("input", _extends({}, pickAttrs(otherProps, { aria: true, data: true }), { id: id, type: "file", ref: this.saveFileInput, onClick: function onClick(e) { return e.stopPropagation(); }, key: this.state.uid, style: { display: 'none' }, accept: accept }, dirProps, { multiple: multiple, onChange: this.onChange }, capture != null ? { capture: capture } : {})), children); } }]); }(Component); export default AjaxUploader;