Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/components/app-navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
import { ActiveContext } from "@/components/utils/active-context";
import { WithPermission } from "@/components/utils/with-permission";
import type { Permissions } from "@/lib/auth/extensions/permissions";
import { useImageUrl } from "@/lib/build-image-url";
import { cn } from "@/lib/utils";
import { useAuth } from "@/providers/client-auth-provider";
import ChevronRight from "@public/assets/icons/caret-right.svg";
Expand Down Expand Up @@ -75,6 +76,7 @@ export const navbarItems = [
function ProfileCard() {
const { user } = useAuth();
const userFullname = `${user?.name} ${user?.lastName}`;
const imageUrl = useImageUrl(user?.image);

return (
<SettingsDropdown
Expand All @@ -95,7 +97,7 @@ function ProfileCard() {
>
<Avatar
className="size-10 shrink-0 group-data-[state=collapsed]:rounded-sm"
src={user?.image ?? undefined}
src={imageUrl}
fallbackText={userFullname}
/>

Expand Down
4 changes: 2 additions & 2 deletions src/components/classes/edit/hooks/use-class-upsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { Term } from "@/models/term";
import { useState } from "react";
import { toast } from "sonner";
import type { ClassFormValues } from "../schema";
import { useClassImageUpload } from "./use-class-image-upload";
import { useImageUpload } from "@/hooks/use-image-upload";
import { useClassMutations } from "./use-class-mutations";

export function useClassUpsert({
Expand All @@ -22,7 +22,7 @@ export function useClassUpsert({
const [isSaveAndPublish, setSaveAndPublish] = useState(false);

const { createClass, updateClass, publishClass } = useClassMutations();
const { uploadImage } = useClassImageUpload();
const { uploadImage } = useImageUpload();

const submitHandler = async (data: ClassFormValues): Promise<string> => {
const payload = { ...data };
Expand Down
3 changes: 0 additions & 3 deletions src/components/settings/pages/profile-settings-content.tsx

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { createContext, useContext } from "react";
import { useForm, type UseFormReturn } from "react-hook-form";

import { GeneralProfileSchema, type GeneralProfileSchemaType } from "./schema";

const GeneralProfileFormContext = createContext<{
form: UseFormReturn<GeneralProfileSchemaType>;
} | null>(null);

export function GeneralProfileFormProvider({
initial,
onSubmit,
children,
}: {
initial: GeneralProfileSchemaType;
onSubmit: (data: GeneralProfileSchemaType) => void;
children: React.ReactNode;
}) {
const form = useForm<GeneralProfileSchemaType>({
resolver: zodResolver(GeneralProfileSchema),
defaultValues: initial,
mode: "onSubmit",
reValidateMode: "onChange",
});

return (
<GeneralProfileFormContext.Provider value={{ form }}>
<form onSubmit={form.handleSubmit(onSubmit)}>{children}</form>
</GeneralProfileFormContext.Provider>
);
}

export function useGeneralProfileForm() {
const ctx = useContext(GeneralProfileFormContext);
if (!ctx)
throw new Error(
"useGeneralProfileForm must be used inside GeneralProfileFormProvider",
);
return ctx;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"use client";

import { useGeneralProfileForm } from "./general-form-provider";
import { ProfileImageInput } from "./profile-image-input";

import { FieldLabel } from "@/components/ui/field";
import { FormInputField } from "@/components/form/FormInput";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Button } from "@/components/primitives/button";

export function GeneralProfileSection({
fallbackName,
isPending,
}: {
fallbackName: string;
isPending: boolean;
}) {
const {
form: { control, watch, setValue },
} = useGeneralProfileForm();

return (
<Card>
<CardHeader>
<CardTitle>Profile Information</CardTitle>
</CardHeader>

<CardContent className="grid gap-4">
<div className="flex flex-col gap-2">
<FieldLabel>Profile Picture</FieldLabel>
<ProfileImageInput
watch={watch}
setValue={setValue}
fallbackName={fallbackName}
/>
</div>

<div className="flex gap-8">
<FormInputField
name="firstName"
control={control}
label="First Name"
required
/>
<FormInputField
name="lastName"
control={control}
label="Last Name"
required
/>
</div>

<FormInputField
name="email"
control={control}
label="Email"
type="email"
disabled
/>

<div className="flex justify-end">
<Button type="submit" pending={isPending}>
Save Changes
</Button>
</div>
</CardContent>
</Card>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { authClient } from "@/lib/auth/client";
import { getBetterAuthErrorMessage } from "@/lib/auth/extensions/get-better-auth-error";
import { useImageUpload } from "@/hooks/use-image-upload";
import type { GeneralProfileSchemaType } from "../schema";

export function useGeneralProfileSubmit() {
const { refetch: refetchSession } = authClient.useSession();
const { uploadImage } = useImageUpload();

const mutation = useMutation({
mutationFn: async (data: GeneralProfileSchemaType) => {
let imageKey: string | null = null;

if (data.image?.startsWith("blob:")) {
// New image selected - upload it
imageKey = await uploadImage(data.image);
} else if (data.image) {
// Existing image URL - extract key from URL or use as-is
const parts = data.image.split("/");
imageKey = parts[parts.length - 1] ?? data.image;
}
// If data.image is null/undefined, imageKey stays null (clear image)

const { error } = await authClient.updateUser({
name: data.firstName,
lastName: data.lastName,
image: imageKey,
});

if (error) {
throw new Error(getBetterAuthErrorMessage(error.code));
}

await refetchSession();
},
onSuccess: () => {
toast.success("Your profile has been successfully updated!");
},
onError: (error: Error) => {
toast.error(error.message);
},
});

return {
onSubmit: mutation.mutateAsync,
isPending: mutation.isPending,
};
}
121 changes: 121 additions & 0 deletions src/components/settings/pages/profile/general/profile-image-input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"use client";

import { useEffect, useRef } from "react";
import type { UseFormSetValue, UseFormWatch } from "react-hook-form";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import {
Dropzone,
DropzoneArea,
DropzoneDescription,
DropzoneHeader,
DropzoneHint,
DropzoneMedia,
} from "@/components/ui/dropzone";
import { cropImageToSquare } from "@/lib/crop-image";
import { Trash2, Upload } from "lucide-react";
import { toast } from "sonner";

type Props = {
watch: UseFormWatch<any>;
setValue: UseFormSetValue<any>;
fallbackName?: string;
};

export function ProfileImageInput({
watch,
setValue,
fallbackName = "U",
}: Props) {
const imageValue = watch("image") as string | undefined;
const previousImageRef = useRef<string | null>(imageValue ?? null);

// Clean up old blob URLs
useEffect(() => {
const prev = previousImageRef.current;
const next = imageValue ?? null;

if (prev && prev !== next && prev.startsWith("blob:")) {
URL.revokeObjectURL(prev);
}

previousImageRef.current = next;
}, [imageValue]);

// Clean up on unmount
useEffect(() => {
return () => {
const last = previousImageRef.current;
if (last?.startsWith("blob:")) {
URL.revokeObjectURL(last);
}
};
}, []);

return (
<Dropzone
accept="image/*"
multiple={false}
maxSize={4 * 1024 * 1024}
onFilesChange={async (files) => {
const file = files[0]?.file;

if (file instanceof File) {
const { previewUrl } = await cropImageToSquare(file, {
size: 512,
mimeType: "image/webp",
quality: 0.8,
});

setValue("image", previewUrl, {
shouldDirty: true,
shouldTouch: true,
});
} else {
setValue("image", undefined);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setting to undefined when file is invalid, but schema expects null. This should be null to match the schema definition.

Suggested change
setValue("image", undefined);
setValue("image", null);
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/components/settings/pages/profile/content/profile-image-input.tsx
Line: 76:76

Comment:
Setting to `undefined` when file is invalid, but schema expects `null`. This should be `null` to match the schema definition.

```suggestion
          setValue("image", null);
```

How can I resolve this? If you propose a fix, please make it concise.

}
}}
onError={(errors) => toast.error(errors[0])}
>
<div className="flex gap-4 items-start">
<div className="flex flex-col items-center gap-4">
<Avatar className="aspect-square size-[140px] shrink-0 rounded-md pointer-events-none">
<AvatarImage
src={imageValue ?? undefined}
className="rounded-md object-cover"
/>
<AvatarFallback className="rounded-md text-4xl">
{fallbackName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>

<Button
type="button"
size="sm"
variant="outline"
onClick={() => setValue("image", null, { shouldDirty: true })}
className="w-full max-w-[140px] text-destructive hover:text-destructive hover:bg-destructive/10"
>
<Trash2 className="mr-2 h-4 w-4" />
Clear
</Button>
</div>

<DropzoneArea>
<DropzoneHeader>
<DropzoneMedia variant="icon">
<Upload />
</DropzoneMedia>

<DropzoneDescription>
Drag and drop or click to upload
</DropzoneDescription>

<DropzoneHint>JPG, PNG, WEBP (max 4MB)</DropzoneHint>
</DropzoneHeader>
</DropzoneArea>
</div>
</Dropzone>
);
}
10 changes: 10 additions & 0 deletions src/components/settings/pages/profile/general/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { z } from "zod";

export const GeneralProfileSchema = z.object({
firstName: z.string().nonempty("Please enter your first name."),
lastName: z.string().nonempty("Please enter your last name."),
email: z.string().email("Please enter a valid email address."),
image: z.string().nullable(),
});

export type GeneralProfileSchemaType = z.infer<typeof GeneralProfileSchema>;
Loading