This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
ProductIcon.js
102 lines (98 loc) · 2.45 KB
/
ProductIcon.js
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
import { Icon, Upload } from 'antd'
import styled from 'styled-components'
import { useToggle } from 'react-use'
import noop from 'lodash/noop'
import { forwardRef, useEffect, useState } from 'react'
import gql from 'graphql-tag'
import get from 'lodash/get'
import { useMutation, useQuery } from '@apollo/react-hooks'
import { GET_MEDIA } from '../queries'
import useViewer from '../hooks/useViewer'
import IPFSImage from './IPFSImage'
const StyledUpload = styled(Upload)`
width: auto;
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
> .ant-upload {
width: 98px;
height: 98px;
margin: 0;
}
`
const StyledIPFSImage = styled(IPFSImage)`
width: 80px;
height: 80px;
object-fit: contain;
`
const CREATE_MEDIA = gql`
mutation($media: IMedia!) {
createMedia(media: $media) {
id,
hash
}
}
`
export default forwardRef(({ value, onChange = noop, onError = noop }, ref) => {
const { viewer: user } = useViewer()
const [loading, setLoading] = useToggle(false)
const [id, setId] = useState(value)
const [create, { loading: createLoading }] = useMutation(CREATE_MEDIA, {
onCompleted: data => {
fireChange(get(data, 'createMedia.id'))
},
onError
})
const { data, loading: getLoading, refetch } = useQuery(GET_MEDIA, {
variables: { id },
skip: !id
})
useEffect(() => {
fireChange(value)
value && refetch({ id: value })
}, [value])
const fireChange = id => {
setId(id)
onChange(id)
}
const handleChange = info => {
if (info.file.status === 'uploading') {
setLoading(true)
} else if (info.file.status === 'error') {
setLoading(false)
onError(info.file.response)
} else if (info.file.status === 'done') {
setLoading(false)
create({
variables: {
media: {
hash: info.file.response[0].hash
}
}
})
}
}
const uploadButton = (
<div>
<Icon type={(loading || getLoading || createLoading) ? 'loading' : 'plus'} />
<div className='ant-upload-text'>点击上传</div>
</div>
)
const hash = get(data, 'getMedia.hash')
return (
<StyledUpload
listType='picture-card'
className='avatar-uploader'
showUploadList={false}
action={process.env.UPLOAD}
onChange={handleChange}
headers={{
authorization: `Bearer ${user && user.token}`
}}
ref={ref}
>
{hash ? <StyledIPFSImage hash={hash} /> : uploadButton}
</StyledUpload>
)
})