feat: improves upload and attachment components

This commit is contained in:
chenos 2020-12-23 16:03:37 +08:00
parent eb7d5c594e
commit 5f69f0d9e1
6 changed files with 75 additions and 273 deletions

View File

@ -1,7 +1,6 @@
import React from 'react' import React, { useState } from 'react'
import { connect } from '@formily/react-schema-renderer' import { connect } from '@formily/react-schema-renderer'
import { Button, Upload as AntdUpload } from 'antd' import { Button, Upload as AntdUpload, Popconfirm } from 'antd'
import styled from 'styled-components'
import { toArr, isArr, isEqual, mapStyledProps } from '../shared' import { toArr, isArr, isEqual, mapStyledProps } from '../shared'
import { import {
LoadingOutlined, LoadingOutlined,
@ -11,282 +10,59 @@ import {
} from '@ant-design/icons' } from '@ant-design/icons'
const { Dragger: UploadDragger } = AntdUpload const { Dragger: UploadDragger } = AntdUpload
const exts = [ function toFileObject(item) {
{ if (item.id && item.uid && item.url) {
ext: /\.docx?$/i, return item;
icon: '//img.alicdn.com/tfs/TB1n8jfr1uSBuNjy1XcXXcYjFXa-200-200.png'
},
{
ext: /\.pptx?$/i,
icon: '//img.alicdn.com/tfs/TB1ItgWr_tYBeNjy1XdXXXXyVXa-200-200.png'
},
{
ext: /\.jpe?g$/i,
icon: '//img.alicdn.com/tfs/TB1wrT5r9BYBeNjy0FeXXbnmFXa-200-200.png'
},
{
ext: /\.pdf$/i,
icon: '//img.alicdn.com/tfs/TB1GwD8r9BYBeNjy0FeXXbnmFXa-200-200.png'
},
{
ext: /\.png$/i,
icon: '//img.alicdn.com/tfs/TB1BHT5r9BYBeNjy0FeXXbnmFXa-200-200.png'
},
{
ext: /\.eps$/i,
icon: '//img.alicdn.com/tfs/TB1G_iGrVOWBuNjy0FiXXXFxVXa-200-200.png'
},
{
ext: /\.ai$/i,
icon: '//img.alicdn.com/tfs/TB1B2cVr_tYBeNjy1XdXXXXyVXa-200-200.png'
},
{
ext: /\.gif$/i,
icon: '//img.alicdn.com/tfs/TB1DTiGrVOWBuNjy0FiXXXFxVXa-200-200.png'
},
{
ext: /\.svg$/i,
icon: '//img.alicdn.com/tfs/TB1uUm9rY9YBuNjy0FgXXcxcXXa-200-200.png'
},
{
ext: /\.xlsx?$/i,
icon: '//img.alicdn.com/tfs/TB1any1r1OSBuNjy0FdXXbDnVXa-200-200.png'
},
{
ext: /\.psd?$/i,
icon: '//img.alicdn.com/tfs/TB1_nu1r1OSBuNjy0FdXXbDnVXa-200-200.png'
},
{
ext: /\.(wav|aif|aiff|au|mp1|mp2|mp3|ra|rm|ram|mid|rmi)$/i,
icon: '//img.alicdn.com/tfs/TB1jPvwr49YBuNjy0FfXXXIsVXa-200-200.png'
},
{
ext: /\.(avi|wmv|mpg|mpeg|vob|dat|3gp|mp4|mkv|rm|rmvb|mov|flv)$/i,
icon: '//img.alicdn.com/tfs/TB1FrT5r9BYBeNjy0FeXXbnmFXa-200-200.png'
},
{
ext: /\.(zip|rar|arj|z|gz|iso|jar|ace|tar|uue|dmg|pkg|lzh|cab)$/i,
icon: '//img.alicdn.com/tfs/TB10jmfr29TBuNjy0FcXXbeiFXa-200-200.png'
},
{
ext: /\.[^.]+$/i,
icon: '//img.alicdn.com/tfs/TB10.R4r3mTBuNjy1XbXXaMrVXa-200-200.png'
} }
] if (item.response && item.response.data) {
return toFileObject(item.response.data);
const UploadPlaceholder = styled(props => (
<div>
{props.loading ? <LoadingOutlined /> : <PlusOutlined />}
<div className={'ant-upload-text'}></div>
</div>
))``
const testOpts = (ext, options) => {
if (options && isArr(options.include)) {
return options.include.some(url => ext.test(url))
} }
return {
if (options && isArr(options.exclude)) { id: item.id,
return !options.exclude.some(url => ext.test(url)) uid: `${item.id}`,
} name: item.title,
url: item.url,
return true status: 'done',
};
} }
const getImageByUrl = (url, options) => { function toFileList(value: any) {
for (let i = 0; i < exts.length; i++) { if (!value) {
if (exts[i].ext.test(url) && testOpts(exts[i].ext, options)) { return [];
return exts[i].icon || url
}
} }
if (!Array.isArray(value) && typeof value === 'object') {
return url value = [value];
}
const normalizeFileList = fileList => {
if (fileList && fileList.length) {
return fileList.map(file => {
return {
uid: file.uid,
status: file.status,
name: file.name,
url: file.downloadURL || file.imgURL || file.url,
...file.response,
thumbUrl: file.imgURL || getImageByUrl(file.downloadURL || file.url, {
exclude: ['.png', '.jpg', '.jpeg', '.gif']
})
}
})
} }
return [] return value.map(toFileObject);
}
const shallowClone = val => {
let result = isArr(val)
? [...val]
: typeof val === 'object'
? { ...val }
: val
if (isArr(result)) {
result = result.map(item => ({
...item,
// 必须要有一个不重复的uid
uid:
item.uid ||
Math.random()
.toFixed(16)
.slice(2, 10)
}))
}
return result
}
export interface IUploaderState {
value: any[]
}
// TODO 能不能直接引用 antd 里面的接口定义呢 ?
export declare type UploadListType = 'text' | 'picture' | 'picture-card'
export interface IUploaderProps {
onChange: (value: any[]) => void
locale: { [name: string]: any }
value: any[]
listType?: UploadListType
} }
export const Upload = connect({ export const Upload = connect({
getProps: mapStyledProps getProps: mapStyledProps
})( })((props) => {
class Uploader extends React.Component<IUploaderProps, IUploaderState> { const { value, onChange } = props;
public static defaultProps = { const [fileList, setFileList] = useState(toFileList(value));
action: const uploadProps = {
'https://www.easy-mock.com/mock/5b713974309d0d7d107a74a3/alifd/upload', name: 'file',
listType: 'text', action: `${process.env.API}/attachments:upload`,
multiple: true, onChange({ file, fileList }) {
className: 'antd-uploader' if (file.status === 'done') {
} const values = toFileList(fileList);
console.log(values);
readonly state: IUploaderState setFileList(values);
onChange(values.map(item => item.id));
constructor(props) {
super(props)
this.state = {
value: shallowClone(toArr(props.value))
} }
} },
};
return (
<div>
<AntdUpload
{...uploadProps}
fileList={fileList}
>
<Button><UploadOutlined /> </Button>
</AntdUpload>
</div>
)
});
public onRemoveHandler = file => { export default Upload;
const { value } = this.state
const fileList = []
value.forEach(item => {
if (item.uid !== file.uid) {
fileList.push(item)
}
})
this.props.onChange(fileList)
}
public onChangeHandler = ({ fileList }) => {
const { onChange } = this.props
fileList = toArr(fileList)
if (
fileList.every(file => {
if (
file.status === 'done' ||
file.imgURL ||
file.downloadURL ||
file.url ||
file.thumbUrl
)
return true
if (file.response) {
if (
file.response.imgURL ||
file.response.downloadURL ||
file.response.url ||
file.response.thumbUrl
)
return true
}
return false
}) &&
fileList.length
) {
fileList = normalizeFileList(fileList)
this.setState(
{
value: fileList
},
() => {
onChange(fileList.length > 0 ? fileList : undefined)
}
)
} else {
this.setState({
value: fileList
})
}
}
public componentDidUpdate(preProps) {
if (this.props.value && !isEqual(this.props.value, preProps.value)) {
this.setState({
value: shallowClone(this.props.value)
})
}
}
public render() {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { listType, locale, onChange, value, ...others } = this.props
if (listType.indexOf('card') > -1) {
return (
<AntdUpload
{...others}
fileList={this.state.value}
onChange={this.onChangeHandler}
onRemove={this.onRemoveHandler}
listType={'picture-card'}
>
<UploadPlaceholder />
</AntdUpload>
)
}
if (listType.indexOf('dragger') > -1) {
return (
<UploadDragger
{...others}
fileList={this.state.value}
onChange={this.onChangeHandler}
onRemove={this.onRemoveHandler}
// TODO image 类型是跟 picture 一样 ?
listType={listType.indexOf('image') > -1 ? 'picture' : 'text'}
>
<p className={'ant-upload-drag-icon'}>
<InboxOutlined />
</p>
<p className={'ant-upload-text'}></p>
</UploadDragger>
)
}
return (
<AntdUpload
{...others}
fileList={this.state.value}
onChange={this.onChangeHandler}
onRemove={this.onRemoveHandler}
listType={listType}
>
<Button style={{ margin: '0 0 10px' }}>
<UploadOutlined />
{(locale && locale.uploadText) || '上传文件'}
</Button>
</AntdUpload>
)
}
}
)
export default Upload

View File

@ -223,6 +223,26 @@ export function LinkToFieldLink(props) {
); );
} }
export function AttachmentField(props: any) {
const { value, schema } = props;
if (!value) {
return null;
}
const values = Array.isArray(value) ? value : [value];
return (
<div className={'attachment-field'}>
{values.map(item => <AttachmentFieldItem data={item} schema={schema}/>)}
</div>
);
}
export function AttachmentFieldItem(props: any) {
const { title, url } = props.data || {};
return (
<a className={'attachment-field-item'} target={'_blank'} href={url}>{title}</a>
);
}
registerFieldComponents({ registerFieldComponents({
string: StringField, string: StringField,
textarea: TextareaField, textarea: TextareaField,
@ -241,6 +261,7 @@ registerFieldComponents({
updatedBy: RealtionField, updatedBy: RealtionField,
subTable: SubTableField, subTable: SubTableField,
linkTo: LinkToField, linkTo: LinkToField,
attachment: AttachmentField,
}); });
export default function Field(props: any) { export default function Field(props: any) {

View File

@ -109,14 +109,17 @@ export const wysiwyg = {
*/ */
export const attachment = { export const attachment = {
title: '附件', title: '附件',
disabled: true, // disabled: true,
options: { options: {
interface: 'attachment', interface: 'attachment',
type: 'belongsToMany', type: 'belongsToMany',
filterable: true, filterable: true,
target: 'attachments', target: 'attachments',
// storage: {
// name: 'local',
// },
component: { component: {
type: 'fileManager', type: 'upload',
}, },
}, },
}; };

View File

@ -4,6 +4,7 @@ export default {
name: 'attachments', name: 'attachments',
title: '文件管理器', title: '文件管理器',
internal: true, internal: true,
developerMode: true,
fields: [ fields: [
{ {
comment: '用户文件名(不含扩展名)', comment: '用户文件名(不含扩展名)',

View File

@ -4,6 +4,7 @@ export default {
name: 'storages', name: 'storages',
title: '存储引擎', title: '存储引擎',
internal: true, internal: true,
developerMode: true,
fields: [ fields: [
{ {
title: '存储引擎名称', title: '存储引擎名称',

View File

@ -203,7 +203,7 @@ export default async (ctx, next) => {
const viewType = view.get('type'); const viewType = view.get('type');
const actionDefaultParams:any = {}; const actionDefaultParams:any = {};
const appends = fields.filter(field => { const appends = fields.filter(field => {
if (!['subTable', 'linkTo'].includes(field.get('interface'))) { if (!['subTable', 'linkTo', 'attachment'].includes(field.get('interface'))) {
return false; return false;
} }
if (viewType === 'table') { if (viewType === 'table') {