feat(avatar-upload): implement avatar upload modal and related functionality

- Introduced `AvatarUploadModal` component for user-friendly avatar image uploads, including cropping and validation for file type and size.
- Added `uploadAvatarBlob` function to handle the upload process to the server.
- Updated `ProfileSettingForm` to integrate the avatar upload modal, allowing users to upload and preview their avatars seamlessly.
- Enhanced localization with new strings for avatar upload instructions and error messages.

These changes aim to improve the user experience by providing a straightforward method for uploading and managing profile images.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-06-17 23:14:54 +08:00
parent e25451aa2b
commit 8130bbceb3
8 changed files with 518 additions and 59 deletions
@@ -0,0 +1,355 @@
import { Button } from "@follow/components/ui/button/index.js"
import { DropZone } from "@follow/components/ui/drop-zone/index.js"
import { useCallback, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"
interface AvatarUploadModalProps {
onConfirm: (blob: Blob) => Promise<void>
onCancel: () => void
maxSizeKB?: number
}
export const AvatarUploadModal = ({
onConfirm,
onCancel,
maxSizeKB = 300,
}: AvatarUploadModalProps) => {
const { t } = useTranslation("settings")
const [selectedImage, setSelectedImage] = useState<string | null>(null)
const [isProcessing, setIsProcessing] = useState(false)
const canvasRef = useRef<HTMLCanvasElement>(null)
const imageRef = useRef<HTMLImageElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
// Crop settings
const [cropData, setCropData] = useState({
x: 0,
y: 0,
width: 400,
height: 400,
})
const [isDragging, setIsDragging] = useState(false)
const [resizeHandle, setResizeHandle] = useState<string | null>(null)
const [dragStart, setDragStart] = useState({
x: 0,
y: 0,
cropX: 0,
cropY: 0,
cropWidth: 0,
cropHeight: 0,
})
const handleFileSelect = useCallback(
(files: FileList) => {
const file = files[0]
if (!file) return
if (!file.type.startsWith("image/")) {
toast.error(t("profile.avatar.invalidFileType"))
return
}
if (file.size > maxSizeKB * 1024) {
toast.error(t("profile.avatar.fileTooLarge", { size: `${maxSizeKB}KB` }))
return
}
const reader = new FileReader()
reader.onload = (e) => {
const result = e.target?.result as string
setSelectedImage(result)
}
reader.readAsDataURL(file)
},
[maxSizeKB, t],
)
const handleImageLoad = useCallback(() => {
if (imageRef.current) {
const img = imageRef.current
const size = Math.min(img.naturalWidth, img.naturalHeight) * 0.8
setCropData({
x: (img.naturalWidth - size) / 2,
y: (img.naturalHeight - size) / 2,
width: size,
height: size,
})
}
}, [])
const handleCropMouseDown = useCallback(
(e: React.MouseEvent) => {
e.preventDefault()
setIsDragging(true)
setDragStart({
x: e.clientX,
y: e.clientY,
cropX: cropData.x,
cropY: cropData.y,
cropWidth: cropData.width,
cropHeight: cropData.height,
})
},
[cropData],
)
const handleResizeMouseDown = useCallback(
(e: React.MouseEvent, handle: string) => {
e.preventDefault()
e.stopPropagation()
setResizeHandle(handle)
setDragStart({
x: e.clientX,
y: e.clientY,
cropX: cropData.x,
cropY: cropData.y,
cropWidth: cropData.width,
cropHeight: cropData.height,
})
},
[cropData],
)
const handleCropMouseMove = useCallback(
(e: React.MouseEvent) => {
if (!isDragging && !resizeHandle) return
e.preventDefault()
if (!imageRef.current || !containerRef.current) return
const img = imageRef.current
const rect = containerRef.current.getBoundingClientRect()
const scaleX = img.naturalWidth / rect.width
const scaleY = img.naturalHeight / rect.height
const deltaX = e.clientX - dragStart.x
const deltaY = e.clientY - dragStart.y
if (resizeHandle) {
const { cropX, cropY, cropWidth, cropHeight } = dragStart
let newX = cropX
let newY = cropY
let newWidth = cropWidth
let newHeight = cropHeight
if (resizeHandle.includes("r")) newWidth += deltaX * scaleX
if (resizeHandle.includes("l")) {
newWidth -= deltaX * scaleX
newX += deltaX * scaleX
}
if (resizeHandle.includes("b")) newHeight += deltaY * scaleY
if (resizeHandle.includes("t")) {
newHeight -= deltaY * scaleY
newY += deltaY * scaleY
}
const size = Math.max(newWidth, newHeight)
if (resizeHandle.includes("t")) newY = cropY + cropHeight - size
if (resizeHandle.includes("l")) newX = cropX + cropWidth - size
newWidth = size
newHeight = size
// Boundary checks
if (newWidth < 50) newWidth = 50
if (newHeight < 50) newHeight = 50
if (newX < 0) {
newWidth += newX
newX = 0
}
if (newY < 0) {
newHeight += newY
newY = 0
}
if (newX + newWidth > img.naturalWidth) {
newWidth = img.naturalWidth - newX
}
if (newY + newHeight > img.naturalHeight) {
newHeight = img.naturalHeight - newY
}
const finalSize = Math.min(newWidth, newHeight)
setCropData({
width: finalSize,
height: finalSize,
x: resizeHandle.includes("l") ? newX + (newWidth - finalSize) : newX,
y: resizeHandle.includes("t") ? newY + (newHeight - finalSize) : newY,
})
} else if (isDragging) {
const newX = dragStart.cropX + deltaX * scaleX
const newY = dragStart.cropY + deltaY * scaleY
setCropData((prev) => ({
...prev,
x: Math.max(0, Math.min(newX, img.naturalWidth - prev.width)),
y: Math.max(0, Math.min(newY, img.naturalHeight - prev.height)),
}))
}
},
[isDragging, resizeHandle, dragStart],
)
const handleCropMouseUp = useCallback(() => {
setIsDragging(false)
setResizeHandle(null)
}, [])
const cropImage = useCallback((): Promise<Blob> => {
return new Promise((resolve, reject) => {
if (!imageRef.current || !canvasRef.current) {
reject(new Error("Image or canvas not available"))
return
}
const canvas = canvasRef.current
const ctx = canvas.getContext("2d")
if (!ctx) {
reject(new Error("Canvas context not available"))
return
}
const img = imageRef.current
canvas.width = 400
canvas.height = 400
ctx.drawImage(img, cropData.x, cropData.y, cropData.width, cropData.height, 0, 0, 400, 400)
canvas.toBlob(
(blob) => {
if (blob) {
resolve(blob)
} else {
reject(new Error("Failed to create blob"))
}
},
"image/jpeg",
0.9,
)
})
}, [cropData])
const handleConfirm = useCallback(async () => {
if (!selectedImage) return
try {
setIsProcessing(true)
const blob = await cropImage()
await onConfirm(blob)
} catch (error) {
console.error("Error processing image:", error)
toast.error(t("profile.avatar.processingError"))
} finally {
setIsProcessing(false)
}
}, [selectedImage, cropImage, onConfirm, t])
const cropStyle = useMemo(() => {
if (!imageRef.current) return {}
const img = imageRef.current
return {
left: `${(cropData.x / img.naturalWidth) * 100}%`,
top: `${(cropData.y / img.naturalHeight) * 100}%`,
width: `${(cropData.width / img.naturalWidth) * 100}%`,
height: `${(cropData.height / img.naturalHeight) * 100}%`,
}
}, [cropData])
return (
<div className="flex flex-col gap-4">
{!selectedImage ? (
<div className="aspect-square h-[400px] space-y-4">
<DropZone onDrop={handleFileSelect} className="size-full">
<div className="flex flex-col items-center gap-2 p-8">
<i className="i-mgc-file-upload-cute-re text-text-secondary text-4xl" />
<div className="text-center">
<p className="text-sm font-medium">{t("profile.avatar.dropZoneText")}</p>
<p className="text-text-secondary text-xs">{t("profile.avatar.dropZoneSubtext")}</p>
</div>
</div>
</DropZone>
</div>
) : (
<div className="space-y-4">
<div
ref={containerRef}
className="relative mx-auto size-[400px] select-none overflow-hidden rounded-lg border bg-gray-100 dark:bg-zinc-800"
onMouseMove={handleCropMouseMove}
onMouseUp={handleCropMouseUp}
onMouseLeave={handleCropMouseUp}
>
<img
ref={imageRef}
src={selectedImage}
alt="Preview"
className="size-full object-contain"
draggable={false}
onLoad={handleImageLoad}
/>
{/* Crop overlay */}
<div
className="absolute rounded-full"
style={{
...cropStyle,
boxShadow: "0 0 0 9999px rgba(0, 0, 0, 0.3)",
}}
/>
<div
className="absolute"
style={{
...cropStyle,
boxShadow: "0 0 0 9999px rgba(0, 0, 0, 0.3)",
}}
>
<div className="size-full cursor-move" onMouseDown={handleCropMouseDown}>
{/* Grid lines */}
<div className="bg-material-medium-light absolute left-1/3 top-0 h-full w-px" />
<div className="bg-material-medium-light absolute left-2/3 top-0 h-full w-px" />
<div className="bg-material-medium-light absolute left-0 top-1/3 h-px w-full" />
<div className="bg-material-medium-light absolute left-0 top-2/3 h-px w-full" />
{/* Resize handles */}
<div
className="bg-accent absolute -left-1 -top-1 size-3 cursor-nwse-resize rounded-full border-2 border-white"
onMouseDown={(e) => handleResizeMouseDown(e, "tl")}
/>
<div
className="bg-accent absolute -right-1 -top-1 size-3 cursor-nesw-resize rounded-full border-2 border-white"
onMouseDown={(e) => handleResizeMouseDown(e, "tr")}
/>
<div
className="bg-accent absolute -bottom-1 -left-1 size-3 cursor-nesw-resize rounded-full border-2 border-white"
onMouseDown={(e) => handleResizeMouseDown(e, "bl")}
/>
<div
className="bg-accent absolute -bottom-1 -right-1 size-3 cursor-nwse-resize rounded-full border-2 border-white"
onMouseDown={(e) => handleResizeMouseDown(e, "br")}
/>
</div>
</div>
</div>
<div className="text-text-secondary text-center text-sm">
{t("profile.avatar.cropInstructions")}
</div>
</div>
)}
<canvas ref={canvasRef} className="hidden" />
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={onCancel}>
{t("words.cancel", { ns: "common" })}
</Button>
<Button onClick={handleConfirm} disabled={!selectedImage} isLoading={isProcessing}>
{t("words.confirm", { ns: "common" })}
</Button>
</div>
</div>
)
}
@@ -1,15 +1,35 @@
import { MotionButtonBase } from "@follow/components/ui/button/index.js"
import { useTypeScriptHappyCallback } from "@follow/hooks"
import { cn } from "@follow/utils/utils"
import type { VariantProps } from "class-variance-authority"
import { cva } from "class-variance-authority"
import type { HTMLMotionProps, Variants } from "motion/react"
import { AnimatePresence, m } from "motion/react"
import type { FC } from "react"
import * as React from "react"
import { cloneElement, useRef, useState } from "react"
interface AnimatedCommandButtonProps {
const animatedCommandButtonVariants = cva(
["center pointer-events-auto flex text-xs", "rounded-md p-1.5 duration-200"],
{
variants: {
variant: {
solid: ["border-accent/5 bg-accent/80 text-white border backdrop-blur"],
outline: ["text-accent hover:bg-material-ultra-thick"],
ghost: [
"border-accent/5 bg-accent/80 text-accent border backdrop-blur",
"bg-theme-item-active hover:bg-theme-item-hover",
],
},
},
defaultVariants: {
variant: "solid",
},
},
)
interface AnimatedCommandButtonProps extends VariantProps<typeof animatedCommandButtonVariants> {
icon: React.JSX.Element
variant?: "solid" | "outline" | "ghost"
}
const iconVariants: Variants = {
@@ -31,7 +51,7 @@ export const AnimatedCommandButton: FC<AnimatedCommandButtonProps & HTMLMotionPr
icon,
className,
style,
variant = "solid",
variant,
...props
}) => {
const [pressed, setPressed] = useState(false)
@@ -40,15 +60,7 @@ export const AnimatedCommandButton: FC<AnimatedCommandButtonProps & HTMLMotionPr
return (
<MotionButtonBase
type="button"
className={cn(
"center pointer-events-auto flex text-xs",
"rounded-md p-1.5 duration-200",
variant === "solid" || variant === "ghost"
? "border-accent/5 bg-accent/80 text-accent border backdrop-blur"
: "text-accent hover:bg-material-ultra-thick",
variant === "ghost" && "bg-theme-item-active hover:bg-theme-item-hover",
className,
)}
className={cn(animatedCommandButtonVariants({ variant }), className)}
onClick={useTypeScriptHappyCallback(
(e) => {
setPressed(true)
@@ -3,7 +3,7 @@ import { useCallback, useRef } from "react"
import { m } from "~/components/common/Motion"
import { copyToClipboard } from "~/lib/clipboard"
import { AnimatedCommandButton } from "./base"
import { AnimatedCommandButton } from "./AnimatedCommandButton"
export const CopyButton: Component<{
value: string
@@ -0,0 +1,28 @@
import { toast } from "sonner"
import { apiClient, apiFetch } from "./api-fetch"
import { getFetchErrorMessage } from "./error-parser"
/**
* Upload avatar blob to server
*
* @param blob - The image blob to upload
* @returns Promise<string> - The uploaded image URL
*/
export async function uploadAvatarBlob(blob: Blob): Promise<string> {
const formData = new FormData()
formData.append("file", blob, "avatar.jpg")
const res = await apiFetch<{
url: string
}>(apiClient.upload.avatar.$url().toString(), {
method: "POST",
body: formData,
}).catch((err) => {
toast.error(getFetchErrorMessage(err))
throw err
})
return res.url
}
@@ -19,7 +19,7 @@ import { toast } from "sonner"
import { z } from "zod"
import { setWhoami, useWhoami } from "~/atoms/user"
import { AnimatedCommandButton } from "~/components/ui/button/base"
import { AnimatedCommandButton } from "~/components/ui/button/AnimatedCommandButton"
import { CopyButton } from "~/components/ui/button/CopyButton"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
import { changeEmail, sendVerificationEmail } from "~/lib/auth"
@@ -48,7 +48,7 @@ export function EmailManagement() {
const { present } = useModalStack()
return (
<>
<div className="mb-2 flex items-center space-x-1">
<div className="mb-2 flex items-center space-x-1 pl-3">
<Label className="text-sm">{t("profile.email.label")}</Label>
<span
className={cn(
@@ -59,7 +59,7 @@ export function EmailManagement() {
{user?.emailVerified ? t("profile.email.verified") : t("profile.email.unverified")}
</span>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center justify-between pl-3">
<div className="text-text-secondary group flex items-center gap-2">
{user?.email}
@@ -19,20 +19,23 @@ import { toast } from "sonner"
import { z } from "zod"
import { setWhoami, useWhoami } from "~/atoms/user"
import { AvatarUploadModal } from "~/components/ui/avatar-upload-modal"
import { useModalStack } from "~/components/ui/modal/stacked/hooks"
import { updateUser } from "~/lib/auth"
import { uploadAvatarBlob } from "~/lib/avatar-upload"
import { toastFetchError } from "~/lib/error-parser"
const socialLinksSchema = z.object({
twitter: z.string().max(64).optional(),
github: z.string().max(64).optional(),
instagram: z.string().max(64).optional(),
facebook: z.string().max(64).optional(),
youtube: z.string().max(64).optional(),
discord: z.string().max(64).optional(),
twitter: z.string().max(32).optional(),
github: z.string().max(32).optional(),
instagram: z.string().max(32).optional(),
facebook: z.string().max(32).optional(),
youtube: z.string().max(32).optional(),
discord: z.string().max(32).optional(),
})
const formSchema = z.object({
handle: z.string().max(50).optional(),
handle: z.string().max(32).regex(/^\w+$/).optional(),
name: z.string().min(3).max(50),
image: z.string().url().or(z.literal("")).optional(),
bio: z.string().max(256).optional(),
@@ -73,6 +76,7 @@ export const ProfileSettingForm = ({
}) => {
const { t } = useTranslation("settings")
const user = useWhoami() as ExtendedUser
const { present } = useModalStack()
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
@@ -94,7 +98,7 @@ export const ProfileSettingForm = ({
})
const updateMutation = useMutation({
mutationFn: (values: z.infer<typeof formSchema>) =>
mutationFn: (values: Partial<z.infer<typeof formSchema>>) =>
updateUser({
handle: values.handle,
image: values.image,
@@ -121,6 +125,34 @@ export const ProfileSettingForm = ({
updateMutation.mutate(values)
}
const handleAvatarUpload = async (blob: Blob) => {
try {
const imageUrl = await uploadAvatarBlob(blob)
form.setValue("image", imageUrl)
toast.success(t("profile.avatar.uploadSuccess"))
updateMutation.mutate({ image: imageUrl })
} catch (error) {
console.error("Upload error:", error)
toast.error(t("profile.avatar.uploadError"))
}
}
const openAvatarUpload = () => {
present({
title: t("profile.avatar.uploadTitle"),
content: ({ dismiss }) => (
<AvatarUploadModal
maxSizeKB={1024}
onConfirm={async (blob) => {
await handleAvatarUpload(blob)
dismiss()
}}
onCancel={dismiss}
/>
),
})
}
const socialLinkFields: (keyof z.infer<typeof socialLinksSchema>)[] = [
"twitter",
"github",
@@ -142,6 +174,35 @@ export const ProfileSettingForm = ({
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className={cn("mt-4 space-y-4", className)}>
<FormField
control={form.control}
name="image"
render={({ field }) => (
<div className="absolute right-0 flex -translate-y-full gap-4">
<FormItem className="w-full">
<FormControl>
<div className="flex items-center gap-4">
<button
type="button"
onClick={openAvatarUpload}
className="group relative cursor-pointer transition-all duration-200 hover:opacity-80"
>
<Avatar className="size-16">
<AvatarImage src={field.value} />
<AvatarFallback>{user?.name?.[0] || ""}</AvatarFallback>
</Avatar>
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
<i className="i-mgc-pic-cute-fi text-xl text-white" />
</div>
</button>
</div>
</FormControl>
<FormMessage />
</FormItem>
</div>
)}
/>
<FormField
control={form.control}
name="handle"
@@ -151,7 +212,9 @@ export const ProfileSettingForm = ({
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>{t("profile.handle.description")}</FormDescription>
<FormDescription className={formItemLabelClassName}>
{t("profile.handle.description")}
</FormDescription>
<FormMessage />
</FormItem>
)}
@@ -165,38 +228,14 @@ export const ProfileSettingForm = ({
<FormControl>
<Input {...field} />
</FormControl>
<FormDescription>{t("profile.name.description")}</FormDescription>
<FormDescription className={formItemLabelClassName}>
{t("profile.name.description")}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="image"
render={({ field }) => (
<div className="flex gap-4">
<FormItem className="w-full">
<FormLabel className={formItemLabelClassName}>
{t("profile.avatar.label")}
</FormLabel>
<FormControl>
<div className="flex items-center gap-4">
<Input {...field} />
{field.value && (
<Avatar className="size-9">
<AvatarImage src={field.value} />
<AvatarFallback>{user?.name[0] || ""}</AvatarFallback>
</Avatar>
)}
</div>
</FormControl>
<FormMessage />
</FormItem>
</div>
)}
/>
<FormField
control={form.control}
name="bio"
@@ -247,8 +286,8 @@ export const ProfileSettingForm = ({
<FormControl>
<label
className={cn(
"ring-accent/20 focus-within:border-accent/80 duration-200 focus-within:outline-none focus-within:ring-2",
"border-border bg-theme-background hover:bg-accent/5 flex cursor-text items-center gap-2 rounded-md border px-3 py-2 transition-colors dark:bg-zinc-700/[0.15]",
"ring-accent/20 focus-within:border-accent/80 h-9 duration-200 focus-within:outline-none focus-within:ring-2",
"border-border bg-theme-background hover:bg-accent/5 flex cursor-text items-center gap-2 rounded-lg border px-3 py-2 transition-colors dark:bg-zinc-700/[0.15]",
)}
>
<i
+11
View File
@@ -394,7 +394,18 @@
"notifications.token": "Client Token",
"privacy.privacy": "Privacy",
"privacy.terms": "Terms",
"profile.avatar.cropInstructions": "Drag the crop area to adjust your avatar",
"profile.avatar.dropZoneSubtext": "or click to select from your computer",
"profile.avatar.dropZoneText": "Drag and drop an image here",
"profile.avatar.fileTooLarge": "File size must be less than {{size}}",
"profile.avatar.invalidFileType": "Please select a valid image file",
"profile.avatar.label": "Avatar",
"profile.avatar.processingError": "Error processing image",
"profile.avatar.selectAnother": "Select Another",
"profile.avatar.selectFile": "Select File",
"profile.avatar.uploadError": "Failed to upload avatar",
"profile.avatar.uploadSuccess": "Avatar uploaded successfully",
"profile.avatar.uploadTitle": "Upload Avatar",
"profile.change_password.label": "Change Password",
"profile.confirm_password.label": "Confirm Password",
"profile.current_password.label": "Current Password",
@@ -1,5 +1,6 @@
import { cn } from "@follow/utils/utils"
import type { DragEvent, ReactNode } from "react"
import { useCallback, useRef, useState } from "react"
import { useCallback, useId, useRef, useState } from "react"
// Ported from https://github.com/react-dropzone/react-dropzone/issues/753#issuecomment-774782919
const useDragAndDrop = ({ callback }: { callback: (file: FileList) => void | Promise<void> }) => {
@@ -51,21 +52,34 @@ const useDragAndDrop = ({ callback }: { callback: (file: FileList) => void | Pro
export const DropZone = ({
onDrop,
children,
className,
}: {
onDrop: (file: FileList) => void | Promise<void>
className?: string
children?: ReactNode
}) => {
const { isDragging, dragHandlers } = useDragAndDrop({ callback: onDrop })
const id = useId()
return (
<label
className={`center cursor-button flex h-[100px] w-full rounded-md border border-dashed ${
isDragging ? "border-accent bg-accent/10" : ""
}`}
htmlFor="upload-file"
className={cn(
"center flex h-[100px] w-full cursor-pointer rounded-md border border-dashed",
isDragging ? "border-accent bg-accent/10" : "",
"hover:border-accent/50 duration-200",
className,
)}
htmlFor={id}
{...dragHandlers}
>
{children}
<input
id={id}
type="file"
accept="image/*"
onChange={(e) => e.target.files && onDrop(e.target.files)}
className="hidden"
/>
</label>
)
}