forked from shesha-io/shesha-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
358 lines (315 loc) · 12.2 KB
/
index.tsx
File metadata and controls
358 lines (315 loc) · 12.2 KB
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import Dragger, { DraggerProps } from 'antd/lib/upload/Dragger';
import React, { FC, useEffect, useMemo, useState } from 'react';
import {
Alert,
Button,
ButtonProps,
App,
Upload,
Image,
UploadFile,
ConfigProvider,
} from 'antd';
import { DraggerStub } from '@/components/fileUpload/stubs';
import { DownloadOutlined, FileZipOutlined, UploadOutlined } from '@ant-design/icons';
import { IDownloadFilePayload, IStoredFile, IUploadFilePayload } from '@/providers/storedFiles/contexts';
import { RcFile, UploadChangeParam } from 'antd/lib/upload/interface';
import { useStyles } from './styles/styles';
import { getStyle, IInputStyles, IStyleType, pickStyleFromModel, useSheshaApplication, ValidationErrors } from '@/index';
import { layoutType, listType } from '@/designer-components/attachmentsEditor/attachmentsEditor';
import { getFileIcon, isImageType } from '@/icons/fileIcons';
import { getSizeStyle } from '@/designer-components/_settings/utils/dimensions/utils';
import { getBorderStyle } from '@/designer-components/_settings/utils/border/utils';
import { getFontStyle } from '@/designer-components/_settings/utils/font/utils';
import { getShadowStyle } from '@/designer-components/_settings/utils/shadow/utils';
import { getBackgroundStyle } from '@/designer-components/_settings/utils/background/utils';
import { isValidGuid } from '../formDesigner/components/utils';
import { removeUndefinedProps } from '@/utils/object';
import { CSSProperties } from 'styled-components';
import { addPx } from '@/designer-components/_settings/utils';
interface IUploaderFileTypes {
name: string;
type: string;
}
export interface IStoredFilesRendererBaseProps extends IInputStyles {
fileList?: IStoredFile[];
allowUpload?: boolean;
allowDelete?: boolean;
showDragger?: boolean;
ownerId?: string;
ownerType?: string;
multiple?: boolean;
isDownloadingFileListZip?: boolean;
isDownloadZipSucceeded?: boolean;
fetchFilesError?: boolean;
downloadZipFileError?: boolean;
deleteFile: (fileIdToDelete: string) => void;
uploadFile: (payload: IUploadFilePayload) => void;
downloadZipFile?: () => void;
downloadZip?: boolean;
downloadFile: (payload: IDownloadFilePayload) => void;
onFileListChanged?: (list: IStoredFile[]) => void;
validFileTypes?: IUploaderFileTypes[];
maxFileLength?: number;
isDragger?: boolean;
disabled?: boolean;
uploadBtnProps?: ButtonProps;
/* isStub is used just to fix strange error when the user is reordering components on the form */
isStub?: boolean;
allowedFileTypes?: string[];
maxHeight?: string;
layout: layoutType;
listType: listType;
thumbnailWidth?: string;
thumbnailHeight?: string;
borderRadius?: number;
hideFileName?: boolean;
gap?: number;
container?: IStyleType;
primaryColor?: string;
}
export const StoredFilesRendererBase: FC<IStoredFilesRendererBaseProps> = ({
multiple = true,
fileList = [],
isDownloadingFileListZip,
isDownloadZipSucceeded,
deleteFile,
uploadFile,
downloadZipFile,
downloadFile,
onFileListChanged,
ownerId,
ownerType,
fetchFilesError,
downloadZipFileError,
uploadBtnProps,
validFileTypes = [],
maxFileLength = 0,
isDragger = false,
primaryColor,
disabled,
isStub = false,
allowedFileTypes = [],
downloadZip,
allowDelete,
layout,
listType,
gap,
...rest
}) => {
const { message, notification } = App.useApp();
const [previewOpen, setPreviewOpen] = useState(false);
const [previewImage, setPreviewImage] = useState({ url: '', uid: '', name: '' });
const [imageUrls, setImageUrls] = useState<{ [key: string]: string }>(fileList.reduce((acc, { uid, url }) => ({ ...acc, [uid]: url }), {}));
const model = rest;
const hasFiles = !!fileList.length;
const { backendUrl, httpHeaders } = useSheshaApplication();
const dimensions = model?.dimensions;
const border = model?.border;
const font = model?.font;
const shadow = model?.shadow;
const background = model?.background;
const jsStyle = getStyle(model.style, model);
const containerJsStyle = getStyle(model.container?.style, model.container);
const dimensionsStyles = useMemo(() => getSizeStyle(dimensions), [dimensions]);
const containerDimensions = useMemo(() => getSizeStyle(model.container?.dimensions), [model.container?.dimensions]);
const borderStyles = useMemo(() => getBorderStyle(border, jsStyle), [border, jsStyle]);
const fontStyles = useMemo(() => getFontStyle(font), [font]);
const [backgroundStyles, setBackgroundStyles] = useState({});
const shadowStyles = useMemo(() => getShadowStyle(shadow), [shadow]);
useEffect(() => {
const fetchStyles = async () => {
const storedImageUrl = background?.storedFile?.id && background?.type === 'storedFile'
? await fetch(`${backendUrl}/api/StoredFile/Download?id=${background?.storedFile?.id}`,
{ headers: { ...httpHeaders, "Content-Type": "application/octet-stream" } })
.then((response) => {
return response.blob();
})
.then((blob) => {
return URL.createObjectURL(blob);
}) : '';
const style = await getBackgroundStyle(background, jsStyle, storedImageUrl);
setBackgroundStyles(style);
};
fetchStyles();
}, [background, backendUrl, httpHeaders, jsStyle]);
const styling = JSON.parse(model.stylingBox || '{}');
const stylingBoxAsCSS = pickStyleFromModel(styling);
const additionalStyles: CSSProperties = removeUndefinedProps({
...stylingBoxAsCSS,
...dimensionsStyles,
...borderStyles,
...fontStyles,
...backgroundStyles,
...shadowStyles
});
const finalStyle = removeUndefinedProps(additionalStyles);
const { styles } = useStyles({
containerStyles: { ...{ ...containerDimensions, width: layout === 'vertical' ? '' : addPx(containerDimensions.width), height: layout === 'horizontal' ? '' : addPx(containerDimensions.height) }, ...containerJsStyle },
style: finalStyle, model: { gap, layout: listType === 'thumbnail' && !isDragger, hideFileName: rest.hideFileName && listType === 'thumbnail', isDragger },
primaryColor
});
const listTypeAndLayout = listType === 'text' || !listType || isDragger ? 'text' : 'picture-card';
const openFilesZipNotification = () =>
notification.success({
message: `Download success!`,
description: 'Your files have been downloaded successfully. Please check your download folder.',
placement: 'topRight',
});
const fetchStoredFile = (url: string) => {
const response = fetch(`${url}`,
{ headers: { ...httpHeaders, "Content-Type": "application/octet-stream" } })
.then((response) => {
return response.blob();
})
.then((blob) => {
return URL.createObjectURL(blob);
});
return response;
};
useEffect(() => {
if (isDownloadZipSucceeded) {
openFilesZipNotification();
}
}, [isDownloadZipSucceeded]);
useEffect(() => {
const fetchImages = async () => {
const newImageUrls = { ...imageUrls };
for (const file of fileList) {
if (isImageType(file.type) && !newImageUrls[file.uid]) {
const imageUrl = await fetchStoredFile(file.url);
newImageUrls[file.uid] = imageUrl;
}
}
setImageUrls(newImageUrls);
};
fetchImages();
}, [fileList]);
const handlePreview = async (file: UploadFile) => {
setPreviewImage({ url: imageUrls[file.uid], uid: file.uid, name: file.name });
setPreviewOpen(true);
};
const iconRender = (file) => {
const { type, uid } = file;
if (isImageType(type)) {
if (listType === 'thumbnail' && !isDragger) {
return <Image src={imageUrls[uid]} alt={file.name} preview={false} />;
}
}
return getFileIcon(type);
};
if (model?.background?.type === 'storedFile' && model?.background.storedFile?.id && !isValidGuid(model?.background.storedFile.id)) {
return <ValidationErrors error="The provided StoredFileId is invalid" />;
}
const props: DraggerProps = {
name: '',
accept: allowedFileTypes?.join(','),
multiple,
fileList,
disabled,
onChange(info: UploadChangeParam) {
const { status } = info.file;
if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
onFileListChanged(info.fileList);
},
onRemove(file) {
deleteFile(file.uid);
},
customRequest(options: any) {
// It used to be RcCustomRequestOptions, but it doesn't seem to be found anymore
uploadFile({ file: options.file, ownerId, ownerType });
},
beforeUpload(file: RcFile) {
const { type, size } = file;
const isValidFileType =
validFileTypes.length === 0 ? true : validFileTypes.map(({ type: fileType }) => fileType).includes(type);
if (!isValidFileType) {
const validTypes = validFileTypes.map(({ name }) => name).join(',');
message.error(`You can only upload files of type: (${validTypes})`);
}
const isAcceptableFileSize = maxFileLength === 0 ? true : size / 1024 / 1024 <= maxFileLength;
if (!isAcceptableFileSize) {
message.error(`Image must smaller than ${maxFileLength}MB!`);
}
return isValidFileType && isAcceptableFileSize;
},
onDownload: ({ uid, name }) => {
downloadFile({ fileId: uid, fileName: name });
},
onPreview: (file) => {
const { uid, name } = file;
if (isImageType(file.type)) {
handlePreview(file);
} else downloadFile({ fileId: uid, fileName: name });
},
showUploadList: {
showRemoveIcon: allowDelete,
showDownloadIcon: true,
},
iconRender,
};
const renderUploadContent = () => {
return (
<Button type="link" icon={<UploadOutlined />} disabled={disabled} {...uploadBtnProps}>
{listType === 'text' && '(press to upload)'}
</Button>
);
};
return (
<div className={`${styles.shaStoredFilesRenderer} ${layout === 'horizontal' && listTypeAndLayout !== 'text' ? styles.shaStoredFilesRendererHorizontal :
layout === 'vertical' && listTypeAndLayout !== 'text' ? styles.shaStoredFilesRendererVertical : layout === 'grid' && listTypeAndLayout !== 'text' ? styles.shaStoredFilesRendererGrid : ''}`}>
<ConfigProvider
theme={{
components: {
Upload: {
actionsColor: '#1890ff',
},
},
}}
>
{isStub
? (isDragger
? <Dragger disabled><DraggerStub /></Dragger>
: <div>{renderUploadContent()}</div>)
: (props.disabled
? <Upload {...props} style={finalStyle} listType={listTypeAndLayout} />
: isDragger
? <Dragger {...props}><DraggerStub /></Dragger>
: <Upload {...props} listType={listTypeAndLayout}>{!disabled ? renderUploadContent() : null}</Upload>)
}
</ConfigProvider>
{previewImage && (
<Image
wrapperStyle={{ display: 'none' }}
preview={{
visible: previewOpen,
onVisibleChange: (visible) => setPreviewOpen(visible),
afterOpenChange: (visible) => !visible && setPreviewImage(null),
toolbarRender: (original) => {
return <div style={{ display: 'flex', flexDirection: 'row-reverse' }}><DownloadOutlined className={styles.antPreviewDownloadIcon} onClick={() => downloadFile({ fileId: previewImage.uid, fileName: previewImage.name })} />{original}</div>;
},
}}
src={previewImage.url}
/>
)}
{fetchFilesError && (
<Alert message="Error" description="Sorry, an error occurred while trying to fetch file list." type="error" />
)}
{downloadZipFileError && (
<Alert message="Error" description="Sorry, an error occurred while trying to download zip file." type="error" />
)}
{downloadZip && hasFiles && !!downloadZipFile && (
<div className={styles.storedFilesRendererBtnContainer}>
<Button size="small" type="link" icon onClick={() => downloadZipFile()} loading={isDownloadingFileListZip}>
{!isDownloadingFileListZip && <FileZipOutlined />} Download Zip
</Button>
</div>
)}
</div>
);
};
export default StoredFilesRendererBase;