Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add profile image upload and display support (#1214)

Richie McIlroy19d9ce10267d
diff --git a/apps/web/actions/account/remove-profile-image.ts b/apps/web/actions/account/remove-profile-image.ts
new file mode 100644
index 000000000..268bf7b02
--- /dev/null
+++ b/apps/web/actions/account/remove-profile-image.ts
@@ -0,0 +1,22 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { users } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+
+export async function removeProfileImage() {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Unauthorized");
+ }
+
+ await db().update(users).set({ image: null }).where(eq(users.id, user.id));
+
+ revalidatePath("/dashboard/settings/account");
+ revalidatePath("/dashboard", "layout");
+
+ return { success: true } as const;
+}
diff --git a/apps/web/actions/account/upload-profile-image.ts b/apps/web/actions/account/upload-profile-image.ts
new file mode 100644
index 000000000..f445937ea
--- /dev/null
+++ b/apps/web/actions/account/upload-profile-image.ts
@@ -0,0 +1,94 @@
+"use server";
+
+import { randomUUID } from "node:crypto";
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { users } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import { S3Buckets } from "@cap/web-backend";
+import { eq } from "drizzle-orm";
+import { Effect, Option } from "effect";
+import { revalidatePath } from "next/cache";
+import { sanitizeFile } from "@/lib/sanitizeFile";
+import { runPromise } from "@/lib/server";
+
+const MAX_FILE_SIZE_BYTES = 3 * 1024 * 1024; // 3MB
+const ALLOWED_IMAGE_TYPES = new Map<string, string>([
+ ["image/png", "png"],
+ ["image/jpeg", "jpg"],
+ ["image/jpg", "jpg"],
+]);
+
+export async function uploadProfileImage(formData: FormData) {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ throw new Error("Unauthorized");
+ }
+
+ const file = formData.get("image") as File | null;
+
+ if (!file) {
+ throw new Error("No file provided");
+ }
+
+ const normalizedType = file.type.toLowerCase();
+ const fileExtension = ALLOWED_IMAGE_TYPES.get(normalizedType);
+
+ if (!fileExtension) {
+ throw new Error("Only PNG or JPEG images are supported");
+ }
+
+ if (file.size > MAX_FILE_SIZE_BYTES) {
+ throw new Error("File size must be 3MB or less");
+ }
+
+ const fileKey = `users/${user.id}/profile-${Date.now()}-${randomUUID()}.${fileExtension}`;
+
+ try {
+ const sanitizedFile = await sanitizeFile(file);
+ let imageUrl: string | undefined;
+
+ await Effect.gen(function* () {
+ const [bucket] = yield* S3Buckets.getBucketAccess(Option.none());
+
+ const bodyBytes = yield* Effect.promise(async () => {
+ const buf = await sanitizedFile.arrayBuffer();
+ return new Uint8Array(buf);
+ });
+
+ yield* bucket.putObject(fileKey, bodyBytes, {
+ contentType: file.type,
+ });
+
+ if (serverEnv().CAP_AWS_BUCKET_URL) {
+ imageUrl = `${serverEnv().CAP_AWS_BUCKET_URL}/${fileKey}`;
+ } else if (serverEnv().CAP_AWS_ENDPOINT) {
+ imageUrl = `${serverEnv().CAP_AWS_ENDPOINT}/${bucket.bucketName}/${fileKey}`;
+ } else {
+ imageUrl = `https://${bucket.bucketName}.s3.${
+ serverEnv().CAP_AWS_REGION || "us-east-1"
+ }.amazonaws.com/${fileKey}`;
+ }
+ }).pipe(runPromise);
+
+ if (typeof imageUrl !== "string" || imageUrl.length === 0) {
+ throw new Error("Failed to resolve uploaded profile image URL");
+ }
+
+ const finalImageUrl = imageUrl;
+
+ await db()
+ .update(users)
+ .set({ image: finalImageUrl })
+ .where(eq(users.id, user.id));
+
+ revalidatePath("/dashboard/settings/account");
+ revalidatePath("/dashboard", "layout");
+
+ return { success: true, imageUrl: finalImageUrl } as const;
+ } catch (error) {
+ console.error("Error uploading profile image:", error);
+ throw new Error(error instanceof Error ? error.message : "Upload failed");
+ }
+}
diff --git a/apps/web/actions/videos/new-comment.ts b/apps/web/actions/videos/new-comment.ts
index f12729c3d..9f83404a9 100644
--- a/apps/web/actions/videos/new-comment.ts
+++ b/apps/web/actions/videos/new-comment.ts
@@ -67,6 +67,7 @@ export async function newComment(data: {
const commentWithAuthor = {
...newComment,
authorName: user.name,
+ authorImage: user.image ?? null,
sending: false,
};
diff --git a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
index 96393b26f..59bf7b4f7 100644
--- a/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
+++ b/apps/web/app/(org)/dashboard/_components/Navbar/Top.tsx
@@ -269,21 +269,12 @@ const User = () => {
className="flex gap-2 justify-between items-center p-2 rounded-xl border data-[state=open]:border-gray-3 data-[state=open]:bg-gray-3 border-transparent transition-colors cursor-pointer group lg:gap-6 hover:border-gray-3"
>
<div className="flex items-center">
- {user.image ? (
- <Image
- src={user.image}
- alt={user.name ?? "User"}
- width={24}
- height={24}
- className="rounded-full"
- />
- ) : (
- <Avatar
- letterClass="text-xs lg:text-md"
- name={user.name ?? "User"}
- className="size-[24px] text-gray-12"
- />
- )}
+ <Avatar
+ letterClass="text-xs lg:text-md"
+ name={user.name ?? "User"}
+ imageUrl={user.image ?? undefined}
+ className="flex-shrink-0 size-[24px] text-gray-12"
+ />
<span className="ml-2 text-sm truncate lg:ml-2 lg:text-md text-gray-12">
{user.name ?? "User"}
</span>
diff --git a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
index 6c8dc3ade..463e58a1a 100644
--- a/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
+++ b/apps/web/app/(org)/dashboard/settings/account/Settings.tsx
@@ -12,8 +12,11 @@ import {
import { Organisation } from "@cap/web-domain";
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
-import { useEffect, useState } from "react";
+import { useEffect, useId, useState } from "react";
import { toast } from "sonner";
+import { removeProfileImage } from "@/actions/account/remove-profile-image";
+import { uploadProfileImage } from "@/actions/account/upload-profile-image";
+import { FileInput } from "@/components/FileInput";
import { useDashboardContext } from "../../Contexts";
import { patchAccountSettings } from "./server";
@@ -29,6 +32,24 @@ export const Settings = ({
const [defaultOrgId, setDefaultOrgId] = useState<
Organisation.OrganisationId | undefined
>(user?.defaultOrgId || undefined);
+ const avatarInputId = useId();
+ const initialProfileImage = user?.image ?? null;
+ const [profileImageOverride, setProfileImageOverride] = useState<
+ string | null | undefined
+ >(undefined);
+ const profileImagePreviewUrl =
+ profileImageOverride !== undefined
+ ? profileImageOverride
+ : initialProfileImage;
+
+ useEffect(() => {
+ if (
+ profileImageOverride !== undefined &&
+ profileImageOverride === initialProfileImage
+ ) {
+ setProfileImageOverride(undefined);
+ }
+ }, [initialProfileImage, profileImageOverride]);
// Track if form has unsaved changes
const hasChanges =
@@ -66,6 +87,74 @@ export const Settings = ({
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [hasChanges]);
+ const {
+ mutate: uploadProfileImageMutation,
+ isPending: isUploadingProfileImage,
+ } = useMutation({
+ mutationFn: async (file: File) => {
+ const formData = new FormData();
+ formData.append("image", file);
+ return uploadProfileImage(formData);
+ },
+ onSuccess: (result) => {
+ if (result.success) {
+ setProfileImageOverride(undefined);
+ toast.success("Profile image updated successfully");
+ router.refresh();
+ }
+ },
+ onError: (error) => {
+ console.error("Error uploading profile image:", error);
+ setProfileImageOverride(undefined);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to upload profile image",
+ );
+ },
+ });
+
+ const {
+ mutate: removeProfileImageMutation,
+ isPending: isRemovingProfileImage,
+ } = useMutation({
+ mutationFn: removeProfileImage,
+ onSuccess: (result) => {
+ if (result.success) {
+ setProfileImageOverride(null);
+ toast.success("Profile image removed");
+ router.refresh();
+ }
+ },
+ onError: (error) => {
+ console.error("Error removing profile image:", error);
+ setProfileImageOverride(initialProfileImage);
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : "Failed to remove profile image",
+ );
+ },
+ });
+
+ const isProfileImageMutating =
+ isUploadingProfileImage || isRemovingProfileImage;
+
+ const handleProfileImageChange = (file: File | null) => {
+ if (!file || isProfileImageMutating) {
+ return;
+ }
+ uploadProfileImageMutation(file);
+ };
+
+ const handleProfileImageRemove = () => {
+ if (isProfileImageMutating) {
+ return;
+ }
+ setProfileImageOverride(null);
+ removeProfileImageMutation();
+ };
+
return (
<form
onSubmit={(e) => {
@@ -73,8 +162,27 @@ export const Settings = ({
updateName();
}}
>
- <div className="flex flex-col flex-wrap gap-6 w-full md:flex-row">
- <Card className="flex-1 space-y-1">
+ <div className="grid gap-6 w-full md:grid-cols-2">
+ <Card className="flex flex-col gap-4">
+ <div className="space-y-1">
+ <CardTitle>Profile image</CardTitle>
+ <CardDescription>
+ This image appears in your profile, comments, and shared caps.
+ </CardDescription>
+ </div>
+ <FileInput
+ id={avatarInputId}
+ name="profileImage"
+ height={120}
+ previewIconSize={28}
+ initialPreviewUrl={profileImagePreviewUrl}
+ onChange={handleProfileImageChange}
+ onRemove={handleProfileImageRemove}
+ disabled={isProfileImageMutating}
+ isLoading={isProfileImageMutating}
+ />
+ </Card>
+ <Card className="space-y-1">
<CardTitle>Your name</CardTitle>
<CardDescription>
Changing your name below will update how your name appears when
@@ -103,7 +211,7 @@ export const Settings = ({
</div>
</div>
</Card>
- <Card className="flex flex-col flex-1 gap-4 justify-between items-stretch">
+ <Card className="flex flex-col gap-4">
<div className="space-y-1">
<CardTitle>Contact email address</CardTitle>
<CardDescription>
@@ -118,7 +226,7 @@ export const Settings = ({
disabled
/>
</Card>
- <Card className="flex flex-col flex-1 gap-4 justify-between items-stretch">
+ <Card className="flex flex-col gap-4">
<div className="space-y-1">
<CardTitle>Default organization</CardTitle>
<CardDescription>This is the default organization</CardDescription>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
index 8a08735d2..3ef262d73 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MemberSelect.tsx
@@ -12,7 +12,6 @@ import { faPlus, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { ChevronDown } from "lucide-react";
-import Image from "next/image";
import { forwardRef, useEffect, useRef, useState } from "react";
import { useDashboardContext } from "../../../Contexts";
@@ -196,17 +195,12 @@ export const MemberSelect = forwardRef<HTMLDivElement, MemberSelectProps>(
key={opt.value}
className="flex gap-2 items-center justify-start p-1.5 text-[13px] rounded-xl cursor-pointer"
>
- {opt.image ? (
- <Image
- src={opt.image}
- alt={opt.label}
- width={20}
- height={20}
- className="w-5 h-5 rounded-full"
- />
- ) : (
- <Avatar name={opt.label} className="w-5 h-5" />
- )}
+ <Avatar
+ name={opt.label}
+ imageUrl={opt.image}
+ className="w-5 h-5"
+ letterClass="text-[11px]"
+ />
{opt.label}
</DropdownMenuItem>
))}
@@ -224,17 +218,12 @@ export const MemberSelect = forwardRef<HTMLDivElement, MemberSelectProps>(
className="flex gap-4 items-center hover:scale-[1.02] transition-transform h-full px-2 py-1.5 min-h-full text-xs rounded-xl bg-gray-3 text-gray-11 wobble"
>
<div className="flex gap-2 items-center">
- {tag.image ? (
- <Image
- src={tag.image}
- alt={tag.label}
- width={20}
- height={20}
- className="w-5 h-5 rounded-full"
- />
- ) : (
- <Avatar name={tag.label} className="w-5 h-5" />
- )}
+ <Avatar
+ name={tag.label}
+ imageUrl={tag.image}
+ className="w-5 h-5"
+ letterClass="text-[11px]"
+ />
<p className="truncate text-[13px] text-gray-12">
{tag.label}
</p>
diff --git a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
index f5681a20c..81bf454ab 100644
--- a/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
+++ b/apps/web/app/(org)/dashboard/spaces/[spaceId]/components/MembersIndicator.tsx
@@ -17,7 +17,6 @@ import { type Space, User } from "@cap/web-domain";
import { faPlus, faUserGroup } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
-import Image from "next/image";
import { useCallback, useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -166,20 +165,12 @@ export const MembersIndicator = ({
key={member.userId}
className="flex gap-2 items-center p-3 rounded-lg border bg-gray-3 border-gray-4"
>
- {member.image ? (
- <Image
- src={member.image}
- alt={member.name || member.email}
- width={24}
- height={24}
- className="rounded-full size-8"
- />
- ) : (
- <Avatar
- name={member.name || member.email}
- className="size-8"
- />
- )}
+ <Avatar
+ name={member.name || member.email}
+ imageUrl={member.image || undefined}
+ className="size-8"
+ letterClass="text-sm"
+ />
<span className="text-sm text-gray-12">
{member.name || member.email}
</span>
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index fb28603fc..63dd9a922 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -25,10 +25,12 @@ import { Toolbar } from "./_components/Toolbar";
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
+ authorImage: string | null;
};
export type CommentType = typeof commentsSchema.$inferSelect & {
authorName?: string | null;
+ authorImage?: string | null;
sending?: boolean;
};
diff --git a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
index 732bcba60..a346cc8fc 100644
--- a/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
+++ b/apps/web/app/s/[videoId]/_components/CapVideoPlayer.tsx
@@ -50,6 +50,7 @@ interface Props {
type: "text" | "emoji";
content: string;
authorName?: string | null;
+ authorImage?: string | null;
}>;
onSeek?: (time: number) => void;
}
diff --git a/apps/web/app/s/[videoId]/_components/CommentStamp.tsx b/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
index 8492839f5..b4feeabd6 100644
--- a/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
+++ b/apps/web/app/s/[videoId]/_components/CommentStamp.tsx
@@ -9,6 +9,7 @@ interface CommentStampsProps {
type: "text" | "emoji";
content: string;
authorName?: string | null;
+ authorImage?: string | null;
};
adjustedPosition: string;
handleMouseEnter: (id: string) => void;
@@ -65,6 +66,7 @@ const CommentStamp: React.FC<CommentStampsProps> = ({
className="size-6"
letterClass="text-sm"
name={comment.authorName}
+ imageUrl={comment.authorImage ?? undefined}
/>
{/* Comment content */}
<div className="flex-1 min-w-0">
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 50989fb70..87e0675f5 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -9,7 +9,6 @@ import { faChevronDown, faLock } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Check, Copy, Globe2 } from "lucide-react";
import moment from "moment";
-import Image from "next/image";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";
@@ -238,18 +237,12 @@ export const ShareHeader = ({
</div>
<div className="flex gap-7 items-center">
<div className="flex gap-2 items-center">
- {data.ownerImage ? (
- <Image
- src={data.ownerImage}
- alt={data.ownerName || ""}
- width={32}
- unoptimized
- height={32}
- className="rounded-full"
- />
- ) : (
- <Avatar name={data.ownerName} className="size-8" />
- )}
+ <Avatar
+ name={data.ownerName}
+ imageUrl={data.ownerImage ?? undefined}
+ className="size-8"
+ letterClass="text-base"
+ />
<div className="flex flex-col text-left">
<p className="text-sm text-gray-12">{data.ownerName}</p>
<p className="text-xs text-gray-10">
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 0b8a6ef6c..6f006c658 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -29,6 +29,7 @@ declare global {
type CommentWithAuthor = typeof commentsSchema.$inferSelect & {
authorName: string | null;
+ authorImage: string | null;
};
export const ShareVideo = forwardRef<
diff --git a/apps/web/app/s/[videoId]/_components/Sidebar.tsx b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
index b3e15dac6..ab4eb2472 100644
--- a/apps/web/app/s/[videoId]/_components/Sidebar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Sidebar.tsx
@@ -15,6 +15,7 @@ type TabType = "activity" | "transcript" | "summary" | "settings";
type CommentType = typeof commentsSchema.$inferSelect & {
authorName?: string | null;
+ authorImage?: string | null;
};
type VideoWithOrganizationInfo = typeof videos.$inferSelect & {
diff --git a/apps/web/app/s/[videoId]/_components/Toolbar.tsx b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
index 45eb245f2..9fe6d3125 100644
--- a/apps/web/app/s/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
@@ -40,6 +40,7 @@ export const Toolbar = ({
id: Comment.CommentId.make(`temp-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
+ authorImage: user?.image ?? null,
content: emoji,
createdAt: new Date(),
videoId: data.id,
@@ -80,7 +81,8 @@ export const Toolbar = ({
const optimisticComment: CommentType = {
id: Comment.CommentId.make(`temp-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
- authorName: Comment.CommentId.make(user?.name || "Anonymous"),
+ authorName: user?.name || "Anonymous",
+ authorImage: user?.image ?? null,
content: comment,
createdAt: new Date(),
videoId: data.id,
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
index e7210cf3c..e856f48e5 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comment.tsx
@@ -78,6 +78,7 @@ const CommentComponent: React.FC<{
className="size-6"
letterClass="text-sm"
name={comment.authorName}
+ imageUrl={comment.authorImage ?? undefined}
/>
<motion.div
viewport={{
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
index 62f03fa63..e26d8ff2c 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Activity/Comments.tsx
@@ -88,6 +88,7 @@ export const Comments = Object.assign(
id: Comment.CommentId.make(`temp-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
+ authorImage: user?.image ?? null,
content,
createdAt: new Date(),
videoId: props.videoId,
@@ -130,6 +131,7 @@ export const Comments = Object.assign(
id: Comment.CommentId.make(`temp-reply-${Date.now()}`),
authorId: User.UserId.make(user?.id || "anonymous"),
authorName: user?.name || "Anonymous",
+ authorImage: user?.image ?? null,
content,
createdAt: new Date(),
videoId: props.videoId,
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 18b01175d..eb83b755a 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -661,6 +661,7 @@ async function AuthorizedContent({
updatedAt: comments.updatedAt,
parentCommentId: comments.parentCommentId,
authorName: users.name,
+ authorImage: users.image,
})
.from(comments)
.leftJoin(users, eq(comments.authorId, users.id))
diff --git a/apps/web/components/FileInput.tsx b/apps/web/components/FileInput.tsx
index 7c39a7af5..cf0f4e861 100644
--- a/apps/web/components/FileInput.tsx
+++ b/apps/web/components/FileInput.tsx
@@ -14,6 +14,10 @@ import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Tooltip } from "./Tooltip";
+const ALLOWED_IMAGE_TYPES = new Set(["image/jpeg", "image/png"]);
+const MAX_FILE_SIZE_BYTES = 3 * 1024 * 1024;
+const ACCEPTED_IMAGE_TYPES = Array.from(ALLOWED_IMAGE_TYPES).join(",");
+
export interface FileInputProps {
onChange?: (file: File | null) => void;
disabled?: boolean;
@@ -43,7 +47,6 @@ export const FileInput: React.FC<FileInputProps> = ({
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [isDragging, setIsDragging] = useState(false);
- const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [previewUrl, setPreviewUrl] = useState<string | null>(
initialPreviewUrl,
);
@@ -117,24 +120,19 @@ export const FileInput: React.FC<FileInputProps> = ({
const handleFileChange = () => {
const file = fileInputRef.current?.files?.[0];
if (file) {
- // Validate file type - only allow jpg, jpeg, svg, and png
- const allowedTypes = [
- "image/jpeg",
- "image/jpg",
- "image/png",
- "image/svg+xml",
- ];
- if (!allowedTypes.includes(file.type)) {
- toast.error("Please select a JPG, JPEG, PNG, or SVG file");
+ // Validate file type - only allow jpg, jpeg, and png
+ const normalizedType = file.type.toLowerCase();
+ if (!ALLOWED_IMAGE_TYPES.has(normalizedType)) {
+ toast.error("Please select a PNG or JPEG image");
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
return;
}
- // Validate file size (limit to 2MB)
- if (file.size > 2 * 1024 * 1024) {
- toast.error("File size must be less than 2MB");
+ // Validate file size (limit to 3MB)
+ if (file.size > MAX_FILE_SIZE_BYTES) {
+ toast.error("File size must be 3MB or less");
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
@@ -149,7 +147,6 @@ export const FileInput: React.FC<FileInputProps> = ({
// Create a new preview URL for immediate feedback
const newPreviewUrl = URL.createObjectURL(file);
setPreviewUrl(newPreviewUrl);
- setSelectedFile(null);
// Call the onChange callback
if (onChange) {
@@ -167,7 +164,6 @@ export const FileInput: React.FC<FileInputProps> = ({
}
setPreviewUrl(null);
- setSelectedFile(null);
if (fileInputRef.current) {
fileInputRef.current.value = "";
@@ -185,51 +181,39 @@ export const FileInput: React.FC<FileInputProps> = ({
};
return (
- <div className={`relative ${className}`}>
+ <div className={clsx("relative", className)}>
<div
style={{
- height: height,
+ height,
}}
>
- {" "}
{/* Fixed height container to prevent resizing */}
- {selectedFile || previewUrl ? (
- <div className="flex gap-2 items-center p-1.5 rounded-xl border border-dashed bg-gray-1 border-gray-4 h-full">
- <div className="flex flex-1 gap-1.5 items-center">
- <div className="flex flex-1 gap-1 items-center">
- {selectedFile ? (
- <>
- <p className="text-xs font-medium w-fit max-w-[150px] truncate text-gray-12">
- {selectedFile.name}
- </p>
- <p className="text-xs text-gray-10 min-w-fit">
- {(selectedFile.size / 1024).toFixed(1)} KB
- </p>
- </>
- ) : (
- <div className="flex gap-2 items-center px-2">
- <p className="text-xs font-medium text-gray-12">
- Current icon:{" "}
- </p>
- <div
- style={{
- width: previewIconSize,
- height: previewIconSize,
- }}
- className="flex overflow-hidden relative flex-shrink-0 justify-center items-center rounded-full"
- >
- {previewUrl && (
- <Image
- src={previewUrl}
- width={32}
- height={32}
- alt="File preview"
- className="object-cover rounded-full"
- />
- )}
- </div>
+ {previewUrl ? (
+ <div className="flex h-full items-center gap-2 rounded-xl border border-dashed border-gray-4 bg-gray-1 p-1.5">
+ <div className="flex flex-1 items-center gap-1.5">
+ <div className="flex flex-1 items-center gap-1">
+ <div className="flex items-center gap-2 px-2">
+ <p className="text-xs font-medium text-gray-12">
+ Current icon:{" "}
+ </p>
+ <div
+ style={{
+ width: previewIconSize,
+ height: previewIconSize,
+ }}
+ className="relative flex flex-shrink-0 items-center justify-center overflow-hidden rounded-full"
+ >
+ {previewUrl && (
+ <Image
+ src={previewUrl}
+ width={32}
+ height={32}
+ alt="File preview"
+ className="object-cover rounded-full"
+ />
+ )}
</div>
- )}
+ </div>
</div>
</div>
<Tooltip content="Remove icon">
@@ -255,25 +239,25 @@ export const FileInput: React.FC<FileInputProps> = ({
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={clsx(
- "flex gap-3 justify-center items-center px-4 w-full rounded-xl border border-dashed transition-all duration-300 cursor-pointer h-full",
+ "flex h-full w-full cursor-pointer items-center justify-center gap-3 rounded-xl border border-dashed px-4 transition-all duration-300",
isDragging
? "border-blue-500 bg-gray-5"
- : "hover:bg-gray-2 border-gray-5 " + notDraggingClassName,
- isLoading || disabled ? "opacity-50 pointer-events-none" : "",
+ : `border-gray-5 hover:bg-gray-2 ${notDraggingClassName}`,
+ isLoading || disabled ? "pointer-events-none opacity-50" : "",
)}
>
{isLoading ? (
<FontAwesomeIcon
- className="animate-spin text-gray-10 size-4"
+ className="size-4 animate-spin text-gray-10"
icon={faSpinner}
/>
) : (
<FontAwesomeIcon
- className="text-gray-10 size-4"
+ className="size-4 text-gray-10"
icon={faCloudUpload}
/>
)}
- <p className="text-[13px] truncate text-gray-11">
+ <p className="truncate text-[13px] text-gray-11">
{isLoading
? "Uploading..."
: "Choose a file or drag & drop it here"}
@@ -287,7 +271,7 @@ export const FileInput: React.FC<FileInputProps> = ({
ref={fileInputRef}
id={id}
disabled={disabled || isLoading}
- accept="image/jpeg, image/jpg, image/png, image/svg+xml"
+ accept={ACCEPTED_IMAGE_TYPES}
onChange={handleFileChange}
name={name}
/>
diff --git a/packages/ui/src/components/Avatar.tsx b/packages/ui/src/components/Avatar.tsx
index 40b352f5b..2bac16450 100644
--- a/packages/ui/src/components/Avatar.tsx
+++ b/packages/ui/src/components/Avatar.tsx
@@ -64,15 +64,29 @@ const avatarTextPalette = [
export interface AvatarProps {
name: string | null | undefined;
+ imageUrl?: string | null;
className?: string;
letterClass?: string;
}
export const Avatar: React.FC<AvatarProps> = ({
name,
+ imageUrl,
className = "",
letterClass = "text-xs",
}) => {
+ if (imageUrl) {
+ return (
+ <img
+ src={imageUrl}
+ alt={name ?? "Avatar"}
+ className={clsx("rounded-full object-cover size-4", className)}
+ loading="lazy"
+ referrerPolicy="no-referrer"
+ />
+ );
+ }
+
const initial = name?.[0]?.toUpperCase() || "A";
const charCode = initial.charCodeAt(0);
const isAlpha = charCode >= 65 && charCode <= 90;