-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUploadRenderer.tsx
83 lines (71 loc) · 2.45 KB
/
UploadRenderer.tsx
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
import {JsonSchema} from '@jsonforms/core'
import {withJsonFormsControlProps} from '@jsonforms/react'
import {Box, Hidden} from '@mui/material'
import React, {useCallback, useMemo} from 'react'
import {ID, useArmoredDatastore} from '../../state'
import AddAttachmentButton from '../forms/AddAttachmentButton'
import AttachmentsList from '../forms/AttachmentsList'
type Upload = {
id: ID,
description: string,
fileName: string,
fileType: string,
}
type UploadRendererProps = {
data: any;
handleChange(path: string, value: any): void;
path: string;
label: string;
schema: JsonSchema;
visible?: boolean
}
const UploadRenderer = ({data, handleChange, path, label, schema, visible}: UploadRendererProps) => {
const isArray = useMemo(() => schema.type === 'array', [schema])
const uploads = useMemo(() =>
data
? ((isArray ? data : [data]) as Upload[])
: []
, [data, isArray])
const setUploads = useCallback(
(uploads: Upload[]) => {
isArray
? handleChange( path, uploads)
: handleChange( path, uploads[0])
},
[path, handleChange, isArray])
const { attachments } = useArmoredDatastore()
const ownAttachmentStates = useMemo(() => attachments.filter(({id}) => uploads.some(upload => upload.id === id)), [attachments, uploads])
const handleAddUploads = useCallback(
(newUploads: { id: ID, fileName: string, fileType: string }[]) => {
setUploads([
...uploads,
...newUploads.map(upload => ({ ...upload, description: '' })),
])
}, [uploads, setUploads])
const handleDelete = useCallback(
(_id: ID) => {
setUploads( uploads.filter(({ id }) => _id !== id) )
},
[uploads, setUploads])
const handleChangeDescription = useCallback(
(id: ID, description: string) => {
setUploads( uploads.map(upload =>
upload.id === id
? { ...upload, description }
: upload
) )
},
[ uploads, setUploads ])
return <Hidden xsUp={!visible}>
<Box style={{marginTop: '1em'}}>
<AddAttachmentButton ids={uploads.map(({ id }) => id)} onUploadsAdded={handleAddUploads} multiple={isArray} label={label} path={path} uploadCount={ownAttachmentStates.length}/>
<AttachmentsList
attachmentStates={ownAttachmentStates}
descriptions={uploads}
onChangeDescription={handleChangeDescription}
onDeleteItem={handleDelete}
/>
</Box>
</Hidden>
}
export default withJsonFormsControlProps(UploadRenderer)