-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdrop-zone.tsx
More file actions
309 lines (269 loc) · 8.23 KB
/
drop-zone.tsx
File metadata and controls
309 lines (269 loc) · 8.23 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
'use client'
import type { ReactNode } from 'react'
import React from 'react'
import type { DropEvent, DropzoneOptions, DropzoneState, FileRejection } from 'react-dropzone'
import { useDropzone as useReactDropzone } from 'react-dropzone'
import { PaperclipIcon } from '@phosphor-icons/react'
import { Button } from './button'
import { Typography } from './typography'
import { createRequiredContext } from '../../hooks/internals/create-required-context'
import { cn } from '../../utils/cn'
declare namespace Intl {
type ListType = 'conjunction' | 'disjunction'
interface ListFormatOptions {
localeMatcher?: 'lookup' | 'best fit'
type?: ListType
style?: 'long' | 'short' | 'narrow'
}
interface ListFormatPart {
type: 'element' | 'literal'
value: string
}
class ListFormat {
constructor(locales?: string | string[], options?: ListFormatOptions)
format(values: any[]): string
formatToParts(values: any[]): ListFormatPart[]
supportedLocalesOf(locales: string | string[], options?: ListFormatOptions): string[]
}
}
interface DropzoneContextType extends DropzoneState {
src?: File[]
previews: { type: string; url: string }[]
accept?: DropzoneOptions['accept']
maxSize?: DropzoneOptions['maxSize']
minSize?: DropzoneOptions['minSize']
maxFiles?: DropzoneOptions['maxFiles']
disabled?: DropzoneOptions['disabled']
}
interface FinalDropzoneContextType extends DropzoneContextType {
caption: string
}
const renderBytes = (bytes: number) => {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
let size = bytes
let unitIndex = 0
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024
unitIndex++
}
return `${size.toFixed(2)}${units[unitIndex]}`
}
export const [_DropzoneProvider, useDropZone] = createRequiredContext<
DropzoneContextType,
FinalDropzoneContextType
>('Dropzone context', {
valueMapper(value) {
let caption = ''
if (value.accept) {
caption += 'Accepts '
caption += new Intl.ListFormat('en').format(Object.keys(value.accept))
}
if (value.minSize && value.maxSize) {
caption += ` between ${renderBytes(value.minSize)} and ${renderBytes(value.maxSize)}`
} else if (value.minSize) {
caption += ` at least ${renderBytes(value.minSize)}`
} else if (value.maxSize) {
caption += ` less than ${renderBytes(value.maxSize)}`
}
return { ...value, caption }
},
})
export interface DropzoneProps extends Omit<DropzoneOptions, 'onDrop'> {
id?: string
src: File[]
previews: { type: string; url: string }[]
className?: string
onDrop?: (acceptedFiles: File[], fileRejections: FileRejection[], event: DropEvent) => void
children?: ReactNode
}
/**
* @description Dropzone provider, children under this component can use `useDropZone`
* @default maxSize is 20MB
*/
export const DropzoneProvider = ({
src,
accept,
maxSize,
minSize,
maxFiles = 1,
previews = [],
onDrop,
onError,
disabled,
children,
...props
}: DropzoneProps) => {
const dropzoneCtx = useReactDropzone({
accept,
maxFiles,
maxSize: maxSize ?? 1024 * 1024 * 20, // 20MB
minSize,
onError,
disabled,
onDrop: (acceptedFiles, fileRejections, event) => {
if (fileRejections.length > 0) {
const message = fileRejections.at(0)?.errors.at(0)?.message
onError?.(new Error(message))
return
}
onDrop?.(acceptedFiles, fileRejections, event)
},
...props,
})
return (
<_DropzoneProvider
src={src}
previews={previews}
accept={accept}
maxSize={maxSize}
minSize={minSize}
maxFiles={maxFiles}
disabled={disabled}
{...dropzoneCtx}
>
{children}
</_DropzoneProvider>
)
}
/**
* @description render if no previewable item
*/
export const DropZoneNonemptyContent = (props: { children?: React.ReactNode }) => {
const dropzoneCtx = useDropZone()
if (dropzoneCtx.previews.length === 0) return null
return props.children
}
/**
* @description render if has a previewable item
*/
export const DropZoneEmptyContent = (props: { children?: React.ReactNode }) => {
const dropzoneCtx = useDropZone()
if (dropzoneCtx.previews.length > 0) return null
return props.children
}
export const DropZoneArea = (
props: Pick<React.ComponentPropsWithRef<'button'>, 'className' | 'id' | 'children'>
) => {
const dropzoneCtx = useDropZone()
return (
<div
data-drag-active={dropzoneCtx.isDragActive}
data-drag-accept={dropzoneCtx.isDragAccept}
data-drag-reject={dropzoneCtx.isDragReject}
data-focused={dropzoneCtx.isFocused}
data-file-dialog-active={dropzoneCtx.isFileDialogActive}
data-disabled={dropzoneCtx.disabled}
className={cn(
'group/dropzone relative h-auto w-full flex-col overflow-hidden rounded-md border border-dashed p-12',
'data-[drag-active=true]:ring-ring ring-offset-2 data-[drag-active=true]:outline-none data-[drag-active=true]:ring-[2px]',
'data-[disabled=true]:bg-surface-primary-disabled',
props.className
)}
{...dropzoneCtx.getRootProps({
style: {
border: '2px dashed var(--color-border)',
},
})}
>
<input
{...dropzoneCtx.getInputProps()}
disabled={dropzoneCtx.disabled}
aria-disabled={dropzoneCtx.disabled}
id={props.id}
/>
{props.children}
</div>
)
}
export type DropzoneContentProps = {
children?: ReactNode
className?: string
}
// /**
// * @description `DropzoneContent` displays content after user upload media,
// * you can pass a children as a custom renderer and empower with `useDropZone`
// * hook to access underlying uploaded items data
// */
// export const DropzoneContent = ({ children, className }: DropzoneContentProps) => {
// const { previews } = useDropZone()
// if (previews.length === 0) return null
// if (children) return children
// return (
// <div className={cn('flex flex-col items-center justify-center', className)}>
// {previews?.map(({ type, url }) => (
// <Fragment key={url}>
// {type.startsWith('image/') ? (
// <img src={url} key={url} onLoad={() => URL.revokeObjectURL(url)} />
// ) : type.startsWith('video/') ? (
// <video controls width="640" height="480" autoPlay>
// <source src={url} key={url} type={type} onLoad={() => URL.revokeObjectURL(url)} />
// </video>
// ) : type.startsWith('audio/') ? (
// <audio controls>
// <source src={url} key={url} type={type} onLoad={() => URL.revokeObjectURL(url)} />
// </audio>
// ) : (
// <Typography className="text-text-secondary">Unsupported file type</Typography>
// )}
// </Fragment>
// ))}
// </div>
// )
// }
export type DropzoneEmptyStateProps = {
children?: ReactNode
className?: string
}
export const DropZoneEmptyUploadButton = ({
className,
...props
}: React.ComponentPropsWithRef<typeof Button>) => {
const { maxFiles } = useDropZone()
return (
<Button
variant="outline"
asChild
className={cn(
'group-data-[disabled=true]/dropzone:bg-surface-primary-disabled group-data-[disabled=true]/dropzone:active:bg-surface-primary-disabled group-data-[disabled=true]/dropzone:cursor-default',
className
)}
children={
<span>
<PaperclipIcon />
<span>Upload {maxFiles === 1 ? 'a file' : 'files'}</span>
</span>
}
{...props}
/>
)
}
export const DropZoneEmptyUploadDescription = ({
className,
...props
}: React.ComponentPropsWithRef<typeof Typography>) => {
return (
<Typography
weight="medium"
className={cn('min-w-[270px] text-text-tertiary', className)}
children={
<>
<span className="text-text-info">Click to upload</span> or drag and drop PNG, JPG, GIF
(max. 2MB)
</>
}
{...props}
/>
)
}
export const DropZoneEmptyUploadCaption = ({
className,
...props
}: React.ComponentPropsWithRef<typeof Typography>) => {
const { caption } = useDropZone()
if (!caption) return null
return (
<Typography type="caption" className={cn('text-secondary-fg', className)} {...props}>
{caption}.
</Typography>
)
}