-
Notifications
You must be signed in to change notification settings - Fork 704
Expand file tree
/
Copy pathImageUpload.tsx
More file actions
166 lines (149 loc) · 4.69 KB
/
ImageUpload.tsx
File metadata and controls
166 lines (149 loc) · 4.69 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
'use client'
import { SpinnerNoMargin } from '@/components/Shared/Spinner'
import { upload } from '@vercel/blob/client'
import { ImageIcon } from 'lucide-react'
import { useEffect, useRef, useState } from 'react'
import { twMerge } from 'tailwind-merge'
const ImageUpload = ({
onUploaded,
validate,
defaultValue,
height,
width,
}: {
onUploaded: (url: string) => void
validate?: (el: HTMLImageElement) => string | undefined
defaultValue?: string
height?: number
width?: number
}) => {
const inputFileRef = useRef<HTMLInputElement>(null)
const [imagePreviewSrc, setImagePreviewSrc] = useState<string | undefined>()
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
setImagePreviewSrc(defaultValue)
}, [defaultValue])
const [isLoading, setIsLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState<string | undefined>()
const handleUpload = async () => {
if (!inputFileRef.current?.files) {
throw new Error('No file selected')
}
const file = inputFileRef.current.files[0]
setIsLoading(true)
setErrorMessage(undefined)
try {
const newBlob = await upload(file.name, file, {
access: 'public',
handleUploadUrl: '/api/blob/upload',
})
onUploaded(newBlob.url)
} catch {
setErrorMessage('Failed to upload image')
} finally {
setIsLoading(false)
}
}
const onLoad = (e: React.ChangeEvent<HTMLImageElement>) => {
if (validate) {
const res = validate(e.currentTarget)
setErrorMessage(res)
}
}
const imageRef = useRef<HTMLImageElement>(null)
useEffect(() => {
if (validate && imageRef.current) {
const res = validate(imageRef.current)
setErrorMessage(res)
}
}, [height, width, validate, imageRef])
return (
<form
onSubmit={async (event) => {
event.preventDefault()
await handleUpload()
}}
>
<input
style={{ display: 'none', height: 0 }}
name="file"
ref={inputFileRef}
type="file"
required
accept="image/*"
onChange={async (e) => {
if (e.target.files && e.target.files[0]) {
const reader = new FileReader()
reader.onload = (readerLoad) => {
if (
readerLoad.target &&
typeof readerLoad.target.result === 'string'
) {
setImagePreviewSrc(readerLoad.target.result)
}
}
reader.readAsDataURL(e.target.files[0])
await handleUpload()
} else {
setImagePreviewSrc(undefined)
}
}}
/>
<div className="flex flex-col items-start gap-4">
{imagePreviewSrc ? (
<div className="relative">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
ref={imageRef}
src={imagePreviewSrc}
className={twMerge(
'flex cursor-pointer items-center justify-center rounded-xl border border-gray-200 bg-gray-50 object-cover hover:opacity-80',
isLoading ? 'opacity-50' : '',
errorMessage ? 'border-red-500' : '',
!height && !width ? 'h-32 w-32' : '',
)}
onClick={() => {
inputFileRef.current?.click()
}}
onLoad={onLoad}
height={height}
width={width}
/>
{isLoading ? (
<div className="absolute top-0 right-0 bottom-0 left-0 flex items-center justify-center">
<SpinnerNoMargin />
</div>
) : null}
</div>
) : (
<div
onClick={() => {
inputFileRef.current?.click()
}}
className={twMerge(
'dark:bg-polar-700 dark:border-polar-600 flex cursor-pointer flex-col items-center justify-center gap-y-2 rounded-xl border border-gray-200 bg-gray-50 hover:bg-gray-100',
!height && !width ? 'h-32 w-32' : '',
)}
style={{
maxWidth: width,
maxHeight: height,
width: width && height ? '100%' : undefined,
aspectRatio: `${width} / ${height}`,
}}
>
<ImageIcon className="h-6 w-6 text-gray-600" />
{height && width ? (
<div className="text-xs text-gray-600">
{height} x {width}px
</div>
) : null}
</div>
)}
{errorMessage ? (
<div className="text-sm text-red-500">{errorMessage}</div>
) : null}
</div>
</form>
)
}
export default ImageUpload