aboutsummaryrefslogtreecommitdiff
path: root/packages/ui/components/shadcn-io/dropzone.tsx
blob: 4d78d9076cca22f6e7b3e080df99174324b0cc92 (plain) (blame)
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
"use client";

import { cn } from "@lib/utils";
import { Button } from "@ui/components/button";
import { UploadIcon } from "lucide-react";
import type { ReactNode } from "react";
import { createContext, useContext } from "react";
import type { DropEvent, DropzoneOptions, FileRejection } from "react-dropzone";
import { useDropzone } from "react-dropzone";

type DropzoneContextType = {
	src?: File[];
	accept?: DropzoneOptions["accept"];
	maxSize?: DropzoneOptions["maxSize"];
	minSize?: DropzoneOptions["minSize"];
	maxFiles?: DropzoneOptions["maxFiles"];
};

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]}`;
};

const DropzoneContext = createContext<DropzoneContextType | undefined>(
	undefined,
);

export type DropzoneProps = Omit<DropzoneOptions, "onDrop"> & {
	src?: File[];
	className?: string;
	onDrop?: (
		acceptedFiles: File[],
		fileRejections: FileRejection[],
		event: DropEvent,
	) => void;
	children?: ReactNode;
};

export const Dropzone = ({
	accept,
	maxFiles = 1,
	maxSize,
	minSize,
	onDrop,
	onError,
	disabled,
	src,
	className,
	children,
	...props
}: DropzoneProps) => {
	const { getRootProps, getInputProps, isDragActive } = useDropzone({
		accept,
		maxFiles,
		maxSize,
		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 (
		<DropzoneContext.Provider
			key={JSON.stringify(src)}
			value={{ src, accept, maxSize, minSize, maxFiles }}
		>
			<Button
				className={cn(
					"relative h-auto w-full flex-col overflow-hidden p-8 cursor-pointer",
					isDragActive && "outline-none ring-1 ring-ring",
					className,
				)}
				disabled={disabled}
				type="button"
				variant="outline"
				{...getRootProps()}
			>
				<input {...getInputProps()} disabled={disabled} />
				{children}
			</Button>
		</DropzoneContext.Provider>
	);
};

const useDropzoneContext = () => {
	const context = useContext(DropzoneContext);

	if (!context) {
		throw new Error("useDropzoneContext must be used within a Dropzone");
	}

	return context;
};

export type DropzoneContentProps = {
	children?: ReactNode;
	className?: string;
};

const maxLabelItems = 1;

export const DropzoneContent = ({
	children,
	className,
}: DropzoneContentProps) => {
	const { src } = useDropzoneContext();

	if (!src) {
		return null;
	}

	if (children) {
		return children;
	}

	return (
		<div className={cn("flex flex-col items-center justify-center", className)}>
			<div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
				<UploadIcon size={16} />
			</div>
			<p className="my-2 w-full truncate font-medium text-sm">
				{src.length > maxLabelItems
					? `${new Intl.ListFormat("en").format(
							src.slice(0, maxLabelItems).map((file) => file.name),
						)} and ${src.length - maxLabelItems} more`
					: new Intl.ListFormat("en").format(src.map((file) => file.name))}
			</p>
			<p className="w-full text-wrap text-muted-foreground text-xs">
				Drag and drop or click to replace
			</p>
		</div>
	);
};

export type DropzoneEmptyStateProps = {
	children?: ReactNode;
	className?: string;
};

export const DropzoneEmptyState = ({
	children,
	className,
}: DropzoneEmptyStateProps) => {
	const { src, accept, maxSize, minSize, maxFiles } = useDropzoneContext();

	if (src) {
		return null;
	}

	if (children) {
		return children;
	}

	let caption = "";

	if (accept) {
		caption += "Accepts ";
		caption += new Intl.ListFormat("en").format(Object.keys(accept));
	}

	if (minSize && maxSize) {
		caption += ` between ${renderBytes(minSize)} and ${renderBytes(maxSize)}`;
	} else if (minSize) {
		caption += ` at least ${renderBytes(minSize)}`;
	} else if (maxSize) {
		caption += ` less than ${renderBytes(maxSize)}`;
	}

	return (
		<div className={cn("flex flex-col items-center justify-center", className)}>
			<div className="flex size-8 items-center justify-center rounded-md bg-muted text-muted-foreground">
				<UploadIcon size={16} />
			</div>
			<p className="my-2 w-full truncate text-wrap font-medium text-sm">
				Upload {maxFiles === 1 ? "a file" : "files"}
			</p>
			<p className="w-full truncate text-wrap text-muted-foreground text-xs">
				Drag and drop or click to upload
			</p>
			{caption && (
				<p className="text-wrap text-muted-foreground text-xs">{caption}.</p>
			)}
		</div>
	);
};