-
Notifications
You must be signed in to change notification settings - Fork 350
/
Copy pathbutton.tsx
325 lines (291 loc) · 9.94 KB
/
button.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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
"use client";
import { useCallback, useMemo, useRef, useState } from "react";
import { twMerge } from "tailwind-merge";
import {
allowedContentTextLabelGenerator,
contentFieldToContent,
generateMimeTypes,
generatePermittedFileTypes,
getFilesFromClipboardEvent,
resolveMaybeUrlArg,
styleFieldToClassName,
styleFieldToCssObject,
UploadAbortedError,
} from "@uploadthing/shared";
import type {
ContentField,
ErrorMessage,
StyleField,
} from "@uploadthing/shared";
import type { FileRouter } from "uploadthing/types";
import { usePaste } from "../hooks/use-paste";
import { INTERNAL_uploadthingHookGen } from "../hooks/use-uploadthing";
import type { UploadthingComponentProps } from "../types";
import { Cancel, progressWidths, Spinner } from "./shared";
type ButtonStyleFieldCallbackArgs = {
__runtime: "react";
ready: boolean;
isUploading: boolean;
uploadProgress: number;
fileTypes: string[];
};
type ButtonAppearance = {
container?: StyleField<ButtonStyleFieldCallbackArgs>;
button?: StyleField<ButtonStyleFieldCallbackArgs>;
allowedContent?: StyleField<ButtonStyleFieldCallbackArgs>;
clearBtn?: StyleField<ButtonStyleFieldCallbackArgs>;
};
type ButtonContent = {
button?: ContentField<ButtonStyleFieldCallbackArgs>;
allowedContent?: ContentField<ButtonStyleFieldCallbackArgs>;
clearBtn?: ContentField<ButtonStyleFieldCallbackArgs>;
};
export type UploadButtonProps<
TRouter extends FileRouter,
TEndpoint extends keyof TRouter,
TSkipPolling extends boolean = false,
> = UploadthingComponentProps<TRouter, TEndpoint, TSkipPolling> & {
/**
* @see https://docs.uploadthing.com/theming#style-using-the-classname-prop
*/
className?: string;
/**
* @see https://docs.uploadthing.com/theming#style-using-the-appearance-prop
*/
appearance?: ButtonAppearance;
/**
* @see https://docs.uploadthing.com/theming#content-customisation
*/
content?: ButtonContent;
disabled?: boolean;
};
/** These are some internal stuff we use to test the component and for forcing a state in docs */
type UploadThingInternalProps = {
__internal_state?: "readying" | "ready" | "uploading";
__internal_upload_progress?: number;
__internal_button_disabled?: boolean;
};
/**
* @remarks It is not recommended using this directly as it requires manually binding generics. Instead, use `createUploadButton`.
* @example
* <UploadButton<OurFileRouter, "someEndpoint">
* endpoint="someEndpoint"
* onUploadComplete={(res) => console.log(res)}
* onUploadError={(err) => console.log(err)}
* />
*/
export function UploadButton<
TRouter extends FileRouter,
TEndpoint extends keyof TRouter,
TSkipPolling extends boolean = false,
>(
props: FileRouter extends TRouter
? ErrorMessage<"You forgot to pass the generic">
: UploadButtonProps<TRouter, TEndpoint, TSkipPolling>,
) {
// Cast back to UploadthingComponentProps<TRouter> to get the correct type. ErrorMessage is unreachable
const $props = props as unknown as UploadButtonProps<
TRouter,
TEndpoint,
TSkipPolling
> &
UploadThingInternalProps;
const fileRouteInput = "input" in $props ? $props.input : undefined;
const { mode = "auto", appendOnPaste = false } = $props.config ?? {};
const acRef = useRef(new AbortController());
const useUploadThing = INTERNAL_uploadthingHookGen<TRouter>({
url: resolveMaybeUrlArg($props.url),
});
const fileInputRef = useRef<HTMLInputElement>(null);
const labelRef = useRef<HTMLLabelElement>(null);
const [uploadProgress, setUploadProgress] = useState(
$props.__internal_upload_progress ?? 0,
);
const [files, setFiles] = useState<File[]>([]);
const { startUpload, isUploading, routeConfig } = useUploadThing(
$props.endpoint,
{
signal: acRef.current.signal,
headers: $props.headers,
skipPolling: !$props?.onClientUploadComplete ? true : $props?.skipPolling,
onClientUploadComplete: (res) => {
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
setFiles([]);
void $props.onClientUploadComplete?.(res);
setUploadProgress(0);
},
onUploadProgress: (p) => {
setUploadProgress(p);
$props.onUploadProgress?.(p, undefined);
},
onUploadError: $props.onUploadError,
onUploadBegin: $props.onUploadBegin,
onBeforeUploadBegin: $props.onBeforeUploadBegin,
},
);
const uploadFiles = useCallback(
(files: File[]) => {
void startUpload(files, fileRouteInput).catch((e) => {
if (e instanceof UploadAbortedError) {
void $props.onUploadAborted?.();
} else {
throw e;
}
});
},
[$props, startUpload, fileRouteInput],
);
const { fileTypes, multiple } = generatePermittedFileTypes(routeConfig);
const inputProps = useMemo(
() => ({
type: "file",
ref: fileInputRef,
multiple,
accept: generateMimeTypes(fileTypes).join(", "),
onChange: (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files) return;
const selectedFiles = Array.from(e.target.files);
if (mode === "manual") {
setFiles(selectedFiles);
return;
}
uploadFiles(selectedFiles);
},
disabled: fileTypes.length === 0,
tabIndex: fileTypes.length === 0 ? -1 : 0,
}),
[fileTypes, mode, multiple, uploadFiles],
);
if ($props.__internal_button_disabled) inputProps.disabled = true;
if ($props.disabled) inputProps.disabled = true;
const state = (() => {
if ($props.__internal_state) return $props.__internal_state;
if (inputProps.disabled) return "readying";
if (!inputProps.disabled && !isUploading) return "ready";
return "uploading";
})();
usePaste((event) => {
if (!appendOnPaste) return;
if (document.activeElement !== fileInputRef.current) return;
const pastedFiles = getFilesFromClipboardEvent(event);
if (!pastedFiles) return;
let filesToUpload = pastedFiles as File[];
setFiles((prev) => {
filesToUpload = [...prev, ...pastedFiles];
return filesToUpload;
});
if (mode === "auto") uploadFiles(files);
});
const styleFieldArg = {
ready: state !== "readying",
isUploading: state === "uploading",
uploadProgress,
fileTypes,
} as ButtonStyleFieldCallbackArgs;
const renderButton = () => {
const customContent = contentFieldToContent(
$props.content?.button,
styleFieldArg,
);
if (customContent) return customContent;
if (state === "readying") return "Loading...";
if (state !== "uploading") {
if (mode === "manual" && files.length > 0) {
return `Upload ${files.length} file${files.length === 1 ? "" : "s"}`;
}
return `Choose File${inputProps.multiple ? `(s)` : ``}`;
}
if (uploadProgress === 100) return <Spinner />;
return (
<span className="z-50">
<span className="block group-hover:hidden">{uploadProgress}%</span>
<Cancel className="hidden size-4 group-hover:block" />
</span>
);
};
const renderClearButton = () => (
<button
onClick={() => {
setFiles([]);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}}
className={twMerge(
"h-[1.25rem] cursor-pointer rounded border-none bg-transparent text-gray-500 transition-colors hover:bg-slate-200 hover:text-gray-600",
styleFieldToClassName($props.appearance?.clearBtn, styleFieldArg),
)}
style={styleFieldToCssObject($props.appearance?.clearBtn, styleFieldArg)}
data-state={state}
data-ut-element="clear-btn"
>
{contentFieldToContent($props.content?.clearBtn, styleFieldArg) ??
"Clear"}
</button>
);
const renderAllowedContent = () => (
<div
className={twMerge(
"h-[1.25rem] text-xs leading-5 text-gray-600",
styleFieldToClassName($props.appearance?.allowedContent, styleFieldArg),
)}
style={styleFieldToCssObject(
$props.appearance?.allowedContent,
styleFieldArg,
)}
data-state={state}
data-ut-element="allowed-content"
>
{contentFieldToContent($props.content?.allowedContent, styleFieldArg) ??
allowedContentTextLabelGenerator(routeConfig)}
</div>
);
return (
<div
className={twMerge(
"flex flex-col items-center justify-center gap-1",
$props.className,
styleFieldToClassName($props.appearance?.container, styleFieldArg),
)}
style={styleFieldToCssObject($props.appearance?.container, styleFieldArg)}
data-state={state}
>
<label
className={twMerge(
"group relative flex h-10 w-36 cursor-pointer items-center justify-center overflow-hidden rounded-md text-white after:transition-[width] after:duration-500 focus-within:ring-2 focus-within:ring-blue-600 focus-within:ring-offset-2",
state === "readying" && "cursor-not-allowed bg-blue-400",
state === "uploading" &&
`bg-blue-400 after:absolute after:left-0 after:h-full after:bg-blue-600 after:content-[''] ${progressWidths[uploadProgress]}`,
state === "ready" && "bg-blue-600",
styleFieldToClassName($props.appearance?.button, styleFieldArg),
)}
style={styleFieldToCssObject($props.appearance?.button, styleFieldArg)}
data-state={state}
data-ut-element="button"
ref={labelRef}
onClick={(e) => {
if (state === "uploading") {
e.preventDefault();
e.stopPropagation();
acRef.current.abort();
acRef.current = new AbortController();
return;
}
if (mode === "manual" && files.length > 0) {
e.preventDefault();
e.stopPropagation();
uploadFiles(files);
}
}}
>
<input {...inputProps} className="sr-only" />
{renderButton()}
</label>
{mode === "manual" && files.length > 0
? renderClearButton()
: renderAllowedContent()}
</div>
);
}