@flatbiz/antd
Version:
359 lines (354 loc) • 13.8 kB
JavaScript
/*! @flatjs/forge MIT @flatbiz/antd */
import _PlusOutlined from '@ant-design/icons/es/icons/PlusOutlined.js';
import { classNames } from '@dimjs/utils/class-names/class-names';
import { hooks } from '@wove/react/hooks';
import { _ as _objectWithoutProperties, a as _slicedToArray, c as _toConsumableArray, b as _objectSpread2, i as _defineProperty } from './_rollupPluginBabelHelpers-BYm17lo8.js';
import { isPlainObject } from '@dimjs/lang/is-plain-object';
import { extend } from '@dimjs/utils/extend/extend';
import { useState, useMemo, Fragment, cloneElement } from 'react';
import { flushSync } from 'react-dom';
import { message, Upload, Image, Button } from 'antd';
import { isUndefinedOrNull, toArray, openNewWindow } from '@flatbiz/utils';
import { B as ButtonWrapper } from './button-wrapper-l9FUsrWl.js';
import { fbaHooks } from './fba-hooks/index.js';
import { jsxs, jsx } from 'react/jsx-runtime';
var getBase64 = function getBase64(file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return resolve(reader.result);
};
reader.onerror = function (error) {
return reject(error);
};
});
};
var _excluded = ["onChange", "onUploadError", "value", "triggerText", "limitHidden", "autoSubmit", "imagePreviewSwitch", "imagePreviewAccept", "extraOperate"];
/**
* 文件上传
* ```
* demo: https://fex.qa.tcshuke.com/docs/admin/main/file/upload
* 1. 可通过配置children替换默认上传触发布局
* 2. 接口返回结构:
* formData上传接口返回值
* {
* code: '0000',
* data: {
* uid: '唯一值,可使用fileKey值'
* name: '文件名称'
* url: '预览地址'
* }
* }
* 3. 如果接口返回的不是上面的字段名称,可通过fieldNames配置接口返回字段名称映射
*
* 4. 最佳使用方式,与Form结合使用
* <Form.Item name="attachmentList" label="附件">
* <UploadWrapper action={uploadUrl} />
* </Form.Item>
*
* 5. 回填数据结构
* [{
* uid: '唯一值',
* name(非必填): 'image.png',
* url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
* }]
* 1. 其中 uid、name、url 可为其他命名,通过 fieldNames 进行映射即可,
* 2. 其他需要的字段可在对象中添加 responseData 对象
* 例如:
* [{
* uid: '唯一值',
* name(非必填): 'image.png',
* url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
* responseData: { 'xx':'xxx' }
* }]
* ```
*
*/
var UploadWrapper = function UploadWrapper(props) {
var onChange = props.onChange,
onUploadError = props.onUploadError,
value = props.value,
triggerText = props.triggerText,
limitHidden = props.limitHidden,
autoSubmit = props.autoSubmit,
imagePreviewSwitch = props.imagePreviewSwitch,
imagePreviewAccept = props.imagePreviewAccept,
extraOperate = props.extraOperate,
otherProps = _objectWithoutProperties(props, _excluded);
var imagePreviewAcceptFt = isUndefinedOrNull(imagePreviewAccept) ? ['png', 'jpg', 'jpeg', 'gif'] : imagePreviewAccept;
var _useState = useState(),
_useState2 = _slicedToArray(_useState, 2),
previewImage = _useState2[0],
setPreviewImage = _useState2[1];
var _useState3 = useState(),
_useState4 = _slicedToArray(_useState3, 2),
uploadList = _useState4[0],
setUploadList = _useState4[1];
var fieldNames = extend({
uid: 'uid',
name: 'name',
url: 'url',
size: 'size'
}, props.fieldNames);
var valueList = useMemo(function () {
return isUndefinedOrNull(value) ? undefined : toArray(value);
}, [value]);
fbaHooks.useEffectCustom(function () {
var errorList = (uploadList === null || uploadList === void 0 ? void 0 : uploadList.filter(function (item) {
return item['status'] === 'error';
})) || [];
var newList = [];
valueList === null || valueList === void 0 || valueList.forEach(function (item) {
// 判断item 为 File类型
if (item['lastModified']) {
newList.push(item);
} else {
newList.push({
uid: item[fieldNames.uid],
name: item[fieldNames.name],
url: item[fieldNames.url],
size: item[fieldNames.size],
responseData: item['responseData'],
status: 'done',
isOriginal: true
});
}
});
if (errorList.length > 0) {
var newErrorList = errorList.map(function (item) {
return {
uid: item.uid,
name: item.name,
status: 'error',
isOriginal: true,
response: item['response']
};
});
newList = newList.concat(newErrorList);
}
setUploadList(newList);
}, [fieldNames.name, fieldNames.uid, fieldNames.url, valueList]);
var handleResponse = function handleResponse(fileList) {
var newFileList = [];
var hasError = false;
fileList.forEach(function (item) {
if (item['isOriginal']) {
if (item['status'] !== 'error') {
var target = _defineProperty(_defineProperty(_defineProperty({}, fieldNames.uid, item.uid), fieldNames.name, item.name), fieldNames.url, item.url);
if (!isUndefinedOrNull(item.size)) {
target[fieldNames.size] = item.size;
}
if (item['responseData']) {
target.responseData = item['responseData'];
}
newFileList.push(target);
}
} else if (isPlainObject(item.response)) {
if (item.response.code === '0000') {
var _props$onRequestResul;
var respData = item.response.data;
var result = ((_props$onRequestResul = props.onRequestResultAdapter) === null || _props$onRequestResul === void 0 ? void 0 : _props$onRequestResul.call(props, respData)) || respData;
var _target2 = _defineProperty(_defineProperty(_defineProperty({}, fieldNames.uid, result[fieldNames.uid] || item.uid), fieldNames.name, result[fieldNames.name] || item.name), fieldNames.url, result[fieldNames.url]);
if (!isUndefinedOrNull(result[fieldNames.size])) {
_target2[fieldNames.size] = result[fieldNames.size];
}
newFileList.push(_objectSpread2(_objectSpread2({}, _target2), {}, {
responseData: respData
}));
} else {
var errorMsg = item.response.message || '上传失败';
hasError = true;
item.status = 'error';
item.response = item.response.message || '上传失败';
if (onUploadError) {
onUploadError === null || onUploadError === void 0 || onUploadError(errorMsg);
} else {
void message.error('上传操作失败...');
}
}
}
});
if (hasError) {
setUploadList(_toConsumableArray(fileList));
}
onChange === null || onChange === void 0 || onChange(newFileList);
};
var onUploadChange = hooks.useCallbackRef(function (info) {
var _props$onUploadChange;
var fileList = info.fileList;
if (info.file.status === 'done') {
var newFileList = _toConsumableArray(info.fileList);
var donwList = newFileList.filter(function (item) {
return item.status === 'done' || item['isOriginal'];
});
var allDone = donwList.length === newFileList.length;
if (allDone) {
handleResponse(newFileList);
}
flushSync(function () {
return setUploadList(newFileList);
});
return;
} else if (info.file.status === 'removed') {
var uid = info.file.uid;
var targetList = valueList !== undefined ? _toConsumableArray(valueList) : [];
var targetIndex = targetList.findIndex(function (item) {
var tempUid = item[fieldNames.uid] || item.uid;
return tempUid === uid;
});
if (targetIndex >= 0) {
targetList.splice(targetIndex, 1);
}
onChange === null || onChange === void 0 || onChange(targetList);
} else if (info.file.status === 'error') {
if (onUploadError) {
onUploadError();
} else {
void message.error('上传操作失败...');
}
}
// https://github.com/ant-design/ant-design/issues/2423
setUploadList(_toConsumableArray(fileList));
(_props$onUploadChange = props.onUploadChange) === null || _props$onUploadChange === void 0 || _props$onUploadChange.call(props, info);
});
var hiddenEmtry = useMemo(function () {
if (otherProps.maxCount === undefined || !limitHidden) return false;
if (otherProps.maxCount === 0) return true;
if (uploadList && uploadList.length >= otherProps.maxCount) return true;
return false;
}, [limitHidden, otherProps.maxCount, uploadList]);
var beforeUpload = function beforeUpload(_file, fileList) {
if (autoSubmit === false) {
var _props$onChange;
var maxCount = otherProps.maxCount;
var mergeList = [].concat(_toConsumableArray(valueList || []), _toConsumableArray(fileList));
var uploadListMerge = [].concat(_toConsumableArray(uploadList || []), _toConsumableArray(fileList));
if (maxCount !== undefined && maxCount !== null) {
if (mergeList.length > maxCount) {
mergeList = mergeList.slice(mergeList.length - maxCount);
uploadListMerge = uploadListMerge.slice(uploadListMerge.length - maxCount);
}
}
setUploadList(uploadListMerge);
(_props$onChange = props.onChange) === null || _props$onChange === void 0 || _props$onChange.call(props, mergeList);
return false;
}
return true;
};
var handlePreview = function handlePreview(file) {
return new Promise(function ($return, $error) {
var name, extension, acceptTarget;
name = file.name || '';
extension = name.slice(name.lastIndexOf('.') + 1);
acceptTarget = imagePreviewAcceptFt === null || imagePreviewAcceptFt === void 0 ? void 0 : imagePreviewAcceptFt.find(function (item) {
return item.toLocaleLowerCase() === extension.toLocaleLowerCase();
});
if (acceptTarget) {
if (!file.url && !file.preview) {
return Promise.resolve(getBase64(file.originFileObj)).then(function ($await_3) {
try {
file.preview = $await_3;
return $If_2.call(this);
} catch ($boundEx) {
return $error($boundEx);
}
}.bind(this), $error);
}
function $If_2() {
setPreviewImage(file.url || file.preview);
return $If_1.call(this);
}
return $If_2.call(this);
} else {
openNewWindow(file.url);
return $If_1.call(this);
}
function $If_1() {
return $return();
}
});
};
return /*#__PURE__*/jsxs(Fragment, {
children: [/*#__PURE__*/jsx(Upload, _objectSpread2(_objectSpread2({
beforeUpload: beforeUpload,
onPreview: imagePreviewSwitch ? handlePreview : undefined,
showUploadList: true,
itemRender: function itemRender(originNode, file, fileList) {
if (!extraOperate || !extraOperate.length) return originNode;
var countSign = "".concat(otherProps.disabled ? 1 : 2, "-").concat(extraOperate.length);
return /*#__PURE__*/jsx("div", {
className: classNames('v-upload-list-item-actions-wrapper', "v-upload-list-item-extra-actions-".concat(countSign)),
style: {
height: '100%'
},
children: /*#__PURE__*/cloneElement(originNode, {
children: [originNode.props.children, /*#__PURE__*/jsx("div", {
className: "v-upload-list-item-extra-actions",
children: extraOperate.map(function (item, index) {
return /*#__PURE__*/jsx(ButtonWrapper, {
size: "small",
type: "text",
icon: item.icon,
onClick: item.onClick.bind(null, file, fileList)
}, index);
})
}, "extra-actions")].filter(Boolean)
})
});
}
}, otherProps), {}, {
onChange: onUploadChange,
fileList: uploadList,
className: classNames('v-upload-wrapper', otherProps.className),
children: otherProps.disabled || hiddenEmtry ? null : /*#__PURE__*/jsx(UploadTrigger, {
triggerText: triggerText,
listType: otherProps.listType,
children: props.children
})
})), previewImage ? /*#__PURE__*/jsx(Image, {
wrapperStyle: {
display: 'none'
},
preview: {
visible: !!previewImage,
onVisibleChange: function onVisibleChange() {
return setPreviewImage(undefined);
},
afterOpenChange: function afterOpenChange(visible) {
return !visible && setPreviewImage('');
}
},
src: previewImage
}) : null]
});
};
var UploadTrigger = function UploadTrigger(props) {
if (props.children) return /*#__PURE__*/jsx(Fragment, {
children: props.children
});
if (props.listType === 'picture-card') {
return /*#__PURE__*/jsxs("div", {
children: [/*#__PURE__*/jsx(_PlusOutlined, {}), /*#__PURE__*/jsx("div", {
style: {
marginTop: 8
},
children: props.triggerText || '上传图片'
})]
});
}
if (props.listType === 'picture') {
return /*#__PURE__*/jsx(Button, {
type: "primary",
ghost: true,
children: props.triggerText || '选择图片上传'
});
}
return /*#__PURE__*/jsx(Button, {
type: "primary",
ghost: true,
children: props.triggerText || '选择文件上传'
});
};
export { UploadWrapper as U };
//# sourceMappingURL=upload-wrapper-CwKeqggJ.js.map