1"use client";
2
3import { UploadIcon } from "lucide-react";
4import type { ReactNode } from "react";
5import { createContext, useContext } from "react";
6import type { DropEvent, DropzoneOptions, FileRejection } from "react-dropzone";
7import { useDropzone } from "react-dropzone";
8import { Button } from "@/components/ui/button";
9import { cn } from "@/lib/utils";
10
11type DropzoneContextType = {
12 src?: File[];
13 accept?: DropzoneOptions["accept"];
14 maxSize?: DropzoneOptions["maxSize"];
15 minSize?: DropzoneOptions["minSize"];
16 maxFiles?: DropzoneOptions["maxFiles"];
17};
18
19const renderBytes = (bytes: number) => {
20 const units = ["B", "KB", "MB", "GB", "TB", "PB"];
21 let size = bytes;
22 let unitIndex = 0;
23
24 while (size >= 1024 && unitIndex < units.length - 1) {
25 size /= 1024;
26 unitIndex++;
27 }
28
29 return `${size.toFixed(2)}${units[unitIndex]}`;
30};
31
32const DropzoneContext = createContext<DropzoneContextType | undefined>(
33 undefined
34);
35
36export type DropzoneProps = Omit<DropzoneOptions, "onDrop"> & {
37 src?: File[];
38 className?: string;
39 onDrop?: (
40 acceptedFiles: File[],
41 fileRejections: FileRejection[],
42 event: DropEvent
43 ) => void;
44 children?: ReactNode;
45};
46
47export const Dropzone = ({
48 accept,
49 maxFiles = 1,
50 maxSize,
51 minSize,
52 onDrop,
53 onError,
54 disabled,
55 src,
56 className,
57 children,
58 ...props
59}: DropzoneProps) => {
60 const { getRootProps, getInputProps, isDragActive } = useDropzone({
61 accept,
62 maxFiles,
63 maxSize,
64 minSize,
65 onError,
66 disabled,
67 onDrop: (acceptedFiles, fileRejections, event) => {
68 if (fileRejections.length > 0) {
69 const message = fileRejections.at(0)?.errors.at(0)?.message;
70 onError?.(new Error(message));
71 return;
72 }
73
74 onDrop?.(acceptedFiles, fileRejections, event);
75 },
76 ...props,
77 });
78
79 return (
80 <DropzoneContext.Provider
81 key={JSON.stringify(src)}
82 value={{ src, accept, maxSize, minSize, maxFiles }}
83 >
84 <Button
85 className={cn(
86 "relative h-auto w-full flex-col overflow-hidden p-8",
87 isDragActive && "outline-none ring-1 ring-ring",
88 className
89 )}
90 disabled={disabled}
91 type="button"
92 variant="outline"
93 {...getRootProps()}
94 >
95 <input {...getInputProps()} disabled={disabled} />
96 {children}
97 </Button>
98 </DropzoneContext.Provider>
99 );
100};
101
102const useDropzoneContext = () => {
103 const context = useContext(DropzoneContext);
104
105 if (!context) {
106 throw new Error("useDropzoneContext must be used within a Dropzone");
107 }
108
109 return context;
110};
111
112export type DropzoneContentProps = {
113 children?: ReactNode;
114 className?: string;
115};
116
117const maxLabelItems = 3;
118
119export const DropzoneContent = ({
120 children,
121 className,
122}: DropzoneContentProps) => {
123 const { src } = useDropzoneContext();
124
125 if (!src) {
126 return null;
127 }
128
129 if (children) {
130 return children;
131 }
132
133 return (
134 <div className={cn("flex flex-col items-center justify-center", className)}>
135 <div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
136 <UploadIcon size={16} />
137 </div>
138 <p className="my-2 w-full truncate font-medium text-sm">
139 {src.length > maxLabelItems
140 ? `${new Intl.ListFormat("en").format(
141 src.slice(0, maxLabelItems).map((file) => file.name)
142 )} and ${src.length - maxLabelItems} more`
143 : new Intl.ListFormat("en").format(src.map((file) => file.name))}
144 </p>
145 <p className="w-full text-wrap text-muted-foreground text-xs">
146 Drag and drop or click to replace
147 </p>
148 </div>
149 );
150};
151
152export type DropzoneEmptyStateProps = {
153 children?: ReactNode;
154 className?: string;
155};
156
157export const DropzoneEmptyState = ({
158 children,
159 className,
160}: DropzoneEmptyStateProps) => {
161 const { src, accept, maxSize, minSize, maxFiles } = useDropzoneContext();
162
163 if (src) {
164 return null;
165 }
166
167 if (children) {
168 return children;
169 }
170
171 let caption = "";
172
173 if (accept) {
174 caption += "Accepts ";
175 caption += new Intl.ListFormat("en").format(Object.keys(accept));
176 }
177
178 if (minSize && maxSize) {
179 caption += ` between ${renderBytes(minSize)} and ${renderBytes(maxSize)}`;
180 } else if (minSize) {
181 caption += ` at least ${renderBytes(minSize)}`;
182 } else if (maxSize) {
183 caption += ` less than ${renderBytes(maxSize)}`;
184 }
185
186 return (
187 <div className={cn("flex flex-col items-center justify-center", className)}>
188 <div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
189 <UploadIcon size={16} />
190 </div>
191 <p className="my-2 w-full truncate text-wrap font-medium text-sm">
192 Upload {maxFiles === 1 ? "a file" : "files"}
193 </p>
194 <p className="w-full truncate text-wrap text-muted-foreground text-xs">
195 Drag and drop or click to upload
196 </p>
197 {caption && (
198 <p className="text-wrap text-muted-foreground text-xs">{caption}.</p>
199 )}
200 </div>
201 );
202};
203