diff --git a/apps/desktop/layer/renderer/src/components/ui/avatar-upload-modal.tsx b/apps/desktop/layer/renderer/src/components/ui/avatar-upload-modal.tsx new file mode 100644 index 000000000..957a88389 --- /dev/null +++ b/apps/desktop/layer/renderer/src/components/ui/avatar-upload-modal.tsx @@ -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 + onCancel: () => void + maxSizeKB?: number +} + +export const AvatarUploadModal = ({ + onConfirm, + onCancel, + maxSizeKB = 300, +}: AvatarUploadModalProps) => { + const { t } = useTranslation("settings") + const [selectedImage, setSelectedImage] = useState(null) + const [isProcessing, setIsProcessing] = useState(false) + const canvasRef = useRef(null) + const imageRef = useRef(null) + const containerRef = useRef(null) + + // Crop settings + const [cropData, setCropData] = useState({ + x: 0, + y: 0, + width: 400, + height: 400, + }) + const [isDragging, setIsDragging] = useState(false) + const [resizeHandle, setResizeHandle] = useState(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 => { + 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 ( +
+ {!selectedImage ? ( +
+ +
+ +
+

{t("profile.avatar.dropZoneText")}

+

{t("profile.avatar.dropZoneSubtext")}

+
+
+
+
+ ) : ( +
+
+ Preview + + {/* Crop overlay */} +
+
+
+ {/* Grid lines */} +
+
+
+
+ + {/* Resize handles */} +
handleResizeMouseDown(e, "tl")} + /> +
handleResizeMouseDown(e, "tr")} + /> +
handleResizeMouseDown(e, "bl")} + /> +
handleResizeMouseDown(e, "br")} + /> +
+
+
+ +
+ {t("profile.avatar.cropInstructions")} +
+
+ )} + + + +
+ + +
+
+ ) +} diff --git a/apps/desktop/layer/renderer/src/components/ui/button/base.tsx b/apps/desktop/layer/renderer/src/components/ui/button/AnimatedCommandButton.tsx similarity index 64% rename from apps/desktop/layer/renderer/src/components/ui/button/base.tsx rename to apps/desktop/layer/renderer/src/components/ui/button/AnimatedCommandButton.tsx index 03fe1cce8..4aaa574f5 100644 --- a/apps/desktop/layer/renderer/src/components/ui/button/base.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/button/AnimatedCommandButton.tsx @@ -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 { icon: React.JSX.Element - variant?: "solid" | "outline" | "ghost" } const iconVariants: Variants = { @@ -31,7 +51,7 @@ export const AnimatedCommandButton: FC { const [pressed, setPressed] = useState(false) @@ -40,15 +60,7 @@ export const AnimatedCommandButton: FC { setPressed(true) diff --git a/apps/desktop/layer/renderer/src/components/ui/button/CopyButton.tsx b/apps/desktop/layer/renderer/src/components/ui/button/CopyButton.tsx index 9456aee6a..28b20bf72 100644 --- a/apps/desktop/layer/renderer/src/components/ui/button/CopyButton.tsx +++ b/apps/desktop/layer/renderer/src/components/ui/button/CopyButton.tsx @@ -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 diff --git a/apps/desktop/layer/renderer/src/lib/avatar-upload.ts b/apps/desktop/layer/renderer/src/lib/avatar-upload.ts new file mode 100644 index 000000000..2db9092f8 --- /dev/null +++ b/apps/desktop/layer/renderer/src/lib/avatar-upload.ts @@ -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 - The uploaded image URL + */ +export async function uploadAvatarBlob(blob: Blob): Promise { + 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 +} diff --git a/apps/desktop/layer/renderer/src/modules/profile/email-management.tsx b/apps/desktop/layer/renderer/src/modules/profile/email-management.tsx index 20a2d6612..6a9812e36 100644 --- a/apps/desktop/layer/renderer/src/modules/profile/email-management.tsx +++ b/apps/desktop/layer/renderer/src/modules/profile/email-management.tsx @@ -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 ( <> -
+
-
+
{user?.email} diff --git a/apps/desktop/layer/renderer/src/modules/profile/profile-setting-form.tsx b/apps/desktop/layer/renderer/src/modules/profile/profile-setting-form.tsx index f9cb12f82..68f31e32b 100644 --- a/apps/desktop/layer/renderer/src/modules/profile/profile-setting-form.tsx +++ b/apps/desktop/layer/renderer/src/modules/profile/profile-setting-form.tsx @@ -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>({ resolver: zodResolver(formSchema), @@ -94,7 +98,7 @@ export const ProfileSettingForm = ({ }) const updateMutation = useMutation({ - mutationFn: (values: z.infer) => + mutationFn: (values: Partial>) => 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 }) => ( + { + await handleAvatarUpload(blob) + dismiss() + }} + onCancel={dismiss} + /> + ), + }) + } + const socialLinkFields: (keyof z.infer)[] = [ "twitter", "github", @@ -142,6 +174,35 @@ export const ProfileSettingForm = ({ return (
+ ( +
+ + +
+ +
+
+ +
+
+ )} + /> + - {t("profile.handle.description")} + + {t("profile.handle.description")} + )} @@ -165,38 +228,14 @@ export const ProfileSettingForm = ({ - {t("profile.name.description")} + + {t("profile.name.description")} + )} /> - ( -
- - - {t("profile.avatar.label")} - - -
- - {field.value && ( - - - {user?.name[0] || ""} - - )} -
-
- -
-
- )} - /> -