-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathImageCropModal.tsx
189 lines (177 loc) · 5.54 KB
/
ImageCropModal.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
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
import { useState } from 'react'
import Cropper from 'react-easy-crop'
import { Area } from 'react-easy-crop/types'
import { mutate } from 'swr'
import { useUserData } from '@src/context/UserContext'
import { storage } from '@src/firebase'
import { onErrorToast } from '@src/hooks/useErrorToast'
import { useUserBigAvatar } from '@src/profile/useAvartar'
import { Button } from '@src/ui/Button'
import {
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
ModalOverlay,
} from '@src/ui/Modal'
interface ImageUploadModalProps {
isOpen: boolean
onClose: () => void
}
// ref: https://codesandbox.io/s/q8q1mnr01w
export const createImage = (url: string) =>
new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image()
image.addEventListener('load', () => resolve(image))
image.addEventListener('error', (error) => reject(error))
image.setAttribute('crossOrigin', 'anonymous')
image.src = url
})
export const createImageFromFile = (file: File) =>
new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image()
const fileReader = new FileReader()
fileReader.onload = (event) => {
image.src = event.target?.result as string
}
image.addEventListener('load', () => resolve(image))
image.addEventListener('error', (error) => reject(error))
fileReader.readAsDataURL(file)
})
/**
* This function was adapted from the one in the ReadMe of https://github.com/DominicTobias/react-image-crop
* @param {File} image - Image File url
* @param {Object} pixelCrop - pixelCrop Object provided by react-easy-crop
* @param {number} rotation - optional rotation parameter
*/
const BOX_SIZE = 320 * 2
export async function getCroppedImage(
image: HTMLImageElement,
sourceArea?: Area
) {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
if (context) {
if (sourceArea) {
canvas.width = BOX_SIZE
canvas.height = BOX_SIZE
context.drawImage(
image,
sourceArea.x,
sourceArea.y,
sourceArea.width,
sourceArea.height,
0,
0,
BOX_SIZE,
BOX_SIZE
)
} else {
const sWidth = image.naturalWidth
const sHeight = image.naturalHeight
const size = Math.min(sWidth, sHeight)
const dWidth = (sWidth / size) * BOX_SIZE
const dHeight = (sHeight / size) * BOX_SIZE
canvas.width = dWidth
canvas.height = dHeight
context.drawImage(image, 0, 0, sWidth, sHeight, 0, 0, dWidth, dHeight)
}
// As a blob
return new Promise<File | null>((resolve) => {
canvas.toBlob((blob) => {
resolve(blob && new File([blob], 'tmp.jpeg'))
}, 'image/jpeg')
})
}
throw new Error(`This browser doesn't support 2D Context`)
}
export const ImageCropModal = (props: ImageUploadModalProps) => {
const { isOpen, onClose } = props
const { user } = useUserData()
const { url, fetchUrl } = useUserBigAvatar()
const [crop, setCrop] = useState({ x: 0, y: 0 })
const [zoom, setZoom] = useState(1)
const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area>()
const onCropComplete = (croppedArea: Area, croppedAreaPixels: Area) => {
setCroppedAreaPixels(croppedAreaPixels)
}
const uploadCroppedImage = async () => {
if (user && url && croppedAreaPixels) {
try {
const image = await createImage(url)
const croppedImage = await getCroppedImage(image, croppedAreaPixels)
if (croppedImage) {
const uploadTask = storage
.ref(`images/${user.id}.jpeg`)
.put(croppedImage, { contentType: 'image/jpeg' })
uploadTask.on(
'state_changed',
() => {
// const progress = Math.round(
// (snapshot.bytesTransferred / snapshot.totalBytes) * 100
// )
// setProgress(progress)
},
(error) => {
onErrorToast(error)
},
() => {
fetchUrl()
onClose()
setZoom(1)
setCrop({ x: 0, y: 0 })
setTimeout(() => {
mutate([user.id, true])
}, 1000)
}
)
}
} catch (e: any) {
onErrorToast(e)
}
}
}
return (
<Modal isOpen={isOpen} onClose={onClose} size="md">
<ModalOverlay />
<ModalContent>
<ModalHeader>แก้ไข</ModalHeader>
<ModalCloseButton />
<ModalBody>
<div className="flex flex-col gap-2">
<div className="relative h-[400px] w-full">
<Cropper
aspect={1}
image={url ?? undefined}
crop={crop}
onCropChange={setCrop}
zoom={zoom}
onZoomChange={setZoom}
onCropComplete={onCropComplete}
cropShape="round"
/>
</div>
<input
className="mt-2 h-1 w-full cursor-pointer appearance-none rounded-lg bg-gray-200 dark:bg-gray-600"
type="range"
min={1}
max={3}
onChange={(e) => setZoom(Number(e.target.value))}
value={zoom}
step={0.01}
/>
</div>
</ModalBody>
<ModalFooter>
<div className="flex gap-2">
<Button colorScheme="otog" onClick={uploadCroppedImage}>
เสร็จสิ้น
</Button>
</div>
</ModalFooter>
</ModalContent>
</Modal>
)
}