-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathuseAvatarUpload.ts
More file actions
99 lines (85 loc) · 2.59 KB
/
Copy pathuseAvatarUpload.ts
File metadata and controls
99 lines (85 loc) · 2.59 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
import * as React from "react";
import { uploadMediaBytes } from "@/shared/api/tauri";
const AVATAR_IMAGE_TYPES = [
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
];
type UseAvatarUploadOptions = {
onUploadSuccess: (url: string) => void;
};
type UseAvatarUploadReturn = {
inputRef: React.RefObject<HTMLInputElement | null>;
isUploading: boolean;
errorMessage: string | null;
clearError: () => void;
openPicker: () => void;
uploadFile: (file: File) => Promise<void>;
handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
};
export function useAvatarUpload({
onUploadSuccess,
}: UseAvatarUploadOptions): UseAvatarUploadReturn {
const inputRef = React.useRef<HTMLInputElement | null>(null);
const [isUploading, setIsUploading] = React.useState(false);
const [errorMessage, setErrorMessage] = React.useState<string | null>(null);
const clearError = React.useCallback(() => {
setErrorMessage(null);
}, []);
const openPicker = React.useCallback(() => {
inputRef.current?.click();
}, []);
const uploadFile = React.useCallback(
async (file: File) => {
if (!AVATAR_IMAGE_TYPES.includes(file.type)) {
setErrorMessage("Choose a PNG, JPG, GIF, or WebP image.");
return;
}
setIsUploading(true);
setErrorMessage(null);
try {
const buffer = await file.arrayBuffer();
const uploaded = await uploadMediaBytes([...new Uint8Array(buffer)]);
// The shared upload path is now generic (accepts any non-denied file),
// so the browser-provided `file.type` check above is no longer a
// backstop. Verify the server-detected MIME is actually an image before
// accepting it as an avatar — defends against spoofed/blank picker MIME.
if (!uploaded.type.startsWith("image/")) {
setErrorMessage("Choose a PNG, JPG, GIF, or WebP image.");
return;
}
onUploadSuccess(uploaded.url);
} catch (error) {
setErrorMessage(
error instanceof Error
? error.message
: "Could not upload that avatar.",
);
} finally {
setIsUploading(false);
}
},
[onUploadSuccess],
);
const handleFileChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) {
return;
}
void uploadFile(file);
},
[uploadFile],
);
return {
inputRef,
isUploading,
errorMessage,
clearError,
openPicker,
uploadFile,
handleFileChange,
};
}