Files
Fastchat/app/(auth)/profile/avatar-upload.tsx
T

83 lines
2.6 KiB
TypeScript

"use client";
import { useActionState, useRef } from "react";
import { uploadAvatarAction, type UploadAvatarState } from "./actions";
import Image from "next/image";
const initialState: UploadAvatarState = null;
export function AvatarUpload({ avatarUrl }: Readonly<{ avatarUrl: string | null }>) {
const [state, action, pending] = useActionState(
uploadAvatarAction,
initialState,
);
const inputRef = useRef<HTMLInputElement>(null);
const handleClick = () => {
inputRef.current?.click();
};
const handleChange = () => {
const file = inputRef.current?.files?.[0];
if (!file) return;
const formData = new FormData();
formData.append("avatar", file);
// Submit via the form's requestSubmit to trigger the action
const form = inputRef.current?.closest("form");
if (form) {
form.requestSubmit();
}
};
return (
<form action={action} className="inline-block">
<input
ref={inputRef}
name="avatar"
type="file"
accept="image/png,image/jpeg,image/jpg"
className="hidden"
onChange={handleChange}
/>
<button
type="button"
onClick={handleClick}
disabled={pending}
className="group relative"
>
{avatarUrl ? (
<Image
src={avatarUrl}
alt=""
loading="eager"
width={200}
height={200}
className="size-20 rounded-full border-4 border-white object-cover shadow-md transition group-hover:opacity-80"
/>
) : (
<div className="flex size-20 items-center justify-center rounded-full border-4 border-white bg-neutral-900 text-2xl font-semibold text-white shadow-md transition group-hover:bg-neutral-700">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
className="size-6"
>
<path d="M10 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM3.465 14.493a1.23 1.23 0 0 0 .41 1.412A9.957 9.957 0 0 0 10 18c2.31 0 4.438-.784 6.131-2.1.43-.333.604-.903.408-1.41a7.002 7.002 0 0 0-13.074.003Z" />
</svg>
</div>
)}
{pending && (
<div className="absolute inset-0 flex items-center justify-center rounded-full bg-black/30">
<div className="size-5 animate-spin rounded-full border-2 border-white border-t-transparent" />
</div>
)}
</button>
{state && "error" in state && (
<p className="mt-2 text-center text-xs text-red-600">{state.error}</p>
)}
</form>
);
}