/
shared.ts
234 lines (213 loc) · 6.26 KB
/
shared.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { Field } from '@formily/core';
import { useField } from '@formily/react';
import { reaction } from '@formily/reactive';
import { isArr, isValid, toArr as toArray } from '@formily/shared';
import { UploadChangeParam } from 'antd/es/upload';
import { UploadFile } from 'antd/es/upload/interface';
import { useEffect } from 'react';
import { useAPIClient } from '../../../api-client';
import { UPLOAD_PLACEHOLDER } from './placeholder';
import type { IUploadProps, UploadProps } from './type';
export const isImage = (extName: string) => {
const reg = /\.(png|jpg|gif|jpeg|webp)$/;
return reg.test(extName);
};
export const toMap = (fileList: any) => {
if (!fileList) {
return [];
}
if (typeof fileList !== 'object') {
return [];
}
let list = fileList;
if (!Array.isArray(fileList)) {
if (Object.keys({ ...fileList }).length === 0) {
return [];
}
list = [fileList];
}
return list.map((item) => {
return [item.id || item.uid, toItem(item)];
});
};
export const toImages = (fileList) => {
if (!fileList) {
return [];
}
if (typeof fileList !== 'object') {
return [];
}
if (Object.keys(fileList).length === 0) {
return [];
}
let list = fileList;
if (!Array.isArray(fileList) && typeof fileList === 'object') {
list = [fileList];
}
return list.map((item) => {
return {
...item,
title: item.title || item.name,
imageUrl: getImageByUrl(item.url, {
exclude: ['.png', '.jpg', '.jpeg', '.gif'],
}),
};
});
};
export const toArr = (value) => {
if (!isValid(value)) {
return [];
}
if (Object.keys(value).length === 0) {
return [];
}
return toArray(value);
};
export const testOpts = (ext: RegExp, options: { exclude?: string[]; include?: string[] }) => {
if (options && isArr(options.include)) {
return options.include.some((url) => ext.test(url));
}
if (options && isArr(options.exclude)) {
return !options.exclude.some((url) => ext.test(url));
}
return true;
};
export const getImageByUrl = (url: string, options: any) => {
for (let i = 0; i < UPLOAD_PLACEHOLDER.length; i++) {
if (UPLOAD_PLACEHOLDER[i].ext.test(url) && testOpts(UPLOAD_PLACEHOLDER[i].ext, options)) {
return UPLOAD_PLACEHOLDER[i].icon || url;
}
}
return url;
};
export const getURL = (target: any) => {
return target?.['url'] || target?.['downloadURL'] || target?.['imgURL'];
};
export const getThumbURL = (target: any) => {
return target?.['thumbUrl'] || target?.['url'] || target?.['downloadURL'] || target?.['imgURL'];
};
export const getErrorMessage = (target: any) => {
return target?.errorMessage ||
target?.errMsg ||
target?.errorMsg ||
target?.message ||
typeof target?.error === 'string'
? target.error
: '';
};
export const getState = (target: any) => {
if (target?.success === false) return 'error';
if (target?.failed === true) return 'error';
if (target?.error) return 'error';
return target?.state || target?.status;
};
export const normalizeFileList = (fileList: UploadFile[]) => {
if (fileList && fileList.length) {
return fileList.map((file, index) => {
return {
...file,
uid: file.uid || `${index}`,
status: getState(file.response) || getState(file),
url: getURL(file) || getURL(file?.response),
thumbUrl: getImageByUrl(getThumbURL(file) || getThumbURL(file?.response), {
exclude: ['.png', '.jpg', '.jpeg', '.gif'],
}),
};
});
}
return [];
};
export const useValidator = (validator: (value: any) => string) => {
const field = useField<Field>();
useEffect(() => {
const dispose = reaction(
() => field.value,
(value) => {
const message = validator(value);
field.setFeedback({
type: 'error',
code: 'UploadError',
messages: message ? [message] : [],
});
},
);
return () => {
dispose();
};
}, []);
};
export const useUploadValidator = (serviceErrorMessage = 'Upload Service Error') => {
useValidator((value) => {
const list = toArr(value);
for (let i = 0; i < list.length; i++) {
if (list[i]?.status === 'error') {
return getErrorMessage(list[i]?.response) || getErrorMessage(list[i]) || serviceErrorMessage;
}
}
});
};
export function useUploadProps<T extends IUploadProps = UploadProps>({ serviceErrorMessage, ...props }: T) {
useUploadValidator(serviceErrorMessage);
const onChange = (param: UploadChangeParam<UploadFile>) => {
props.onChange?.(normalizeFileList([...param.fileList]));
};
const api = useAPIClient();
return {
...props,
// in customRequest method can't modify form's status(e.g: form.disabled=true )
// that will be trigger Upload component(actual Underlying is AjaxUploader component )'s componentWillUnmount method
// which will cause multiple files upload fail
customRequest({ action, data, file, filename, headers, onError, onProgress, onSuccess, withCredentials }) {
const formData = new FormData();
if (data) {
Object.keys(data).forEach((key) => {
formData.append(key, data[key]);
});
}
formData.append(filename, file);
api.axios
.post(action, formData, {
withCredentials,
headers,
onUploadProgress: ({ total, loaded }) => {
onProgress({ percent: Math.round((loaded / total) * 100).toFixed(2) }, file);
},
})
.then(({ data }) => {
onSuccess(data, file);
})
.catch(onError)
.finally(() => {});
return {
abort() {
console.log('upload progress is aborted.');
},
};
},
onChange,
};
}
export const toItem = (file) => {
if (file?.response?.data) {
file = {
uid: file.uid,
...file.response.data,
};
}
return {
...file,
id: file.id || file.uid,
title: file.title || file.name,
imageUrl: getImageByUrl(file.url, {
exclude: ['.png', '.jpg', '.jpeg', '.gif'],
}),
};
};
export const toFileList = (fileList: any) => {
return toArr(fileList).map(toItem);
};
export const toValue = (fileList: any) => {
return toArr(fileList)
.filter((file) => !file.response || file.status === 'done')
.map((file) => file?.response?.data || file);
};