ProfileForm 组件

ProfileForm 组件

概述

ProfileForm 是用户个人资料编辑表单组件,提供完整的用户信息管理功能,包括基本信息、头像、简介和社交链接。

文件路径

src/components/settings/profile-form.tsx

功能特性

  • 基本信息编辑: 名称、用户名、头像 URL
  • 个人简介: 支持 250 字符的个人描述
  • 自定义链接: 最多 5 个社交链接(GitHub、Twitter、LinkedIn 等)
  • 链接排序: 支持拖拽调整链接顺序
  • 实时预览: 头像和名称实时预览
  • 认证徽章: 显示和购买认证徽章
  • 表单验证: Zod schema 验证
  • 分析追踪: 用户行为分析

接口定义

type CustomLinkType = 
  | "website" | "github" | "twitter" | "linkedin" 
  | "instagram" | "youtube" | "twitch" | "discord" 
  | "mastodon" | "bluesky" | "sponsor";

interface CustomLink {
  type: CustomLinkType;
  url: string;
  label?: string;
}

interface ProfileFormProps {
  user: {
    id: string;
    name: string | null;
    username: string;
    email: string;
    avatar: string | null;
    verified: boolean;
    bio?: string | null;
    customLinks?: CustomLink[] | null;
  };
  showVerifiedSection?: boolean;  // 是否显示认证区域
}

// 表单值类型
type ProfileFormValues = {
  name: string;
  username: string;
  avatar?: string;
  bio?: string;
  customLinks?: CustomLink[];
};

链接类型

类型图标悬停颜色
websiteGlobe默认
githubGitHub默认
twitterX默认
linkedinLinkedIn蓝色
instagramInstagram粉色
youtubeYouTube红色
twitchTwitch紫色
discordDiscord靛蓝
mastodonMastodon紫色
blueskyBluesky天蓝
sponsorHeart粉色

使用示例

import { ProfileForm } from "@/components/settings/profile-form";

export default async function SettingsPage() {
  const user = await getUser();
  
  return (
    <ProfileForm 
      user={user}
      showVerifiedSection={true}
    />
  );
}

表单验证规则

const profileSchema = z.object({
  name: z.string().min(1).max(100),  // 必填,最多 100 字符
  username: z.string()
    .min(1).max(30)
    .regex(/^[a-zA0-9_]+$/),  // 只允许字母、数字、下划线
  avatar: z.string().url().optional(),  // 可选,必须是 URL
  bio: z.string().max(250).optional(),  // 可选,最多 250 字符
  customLinks: z.array(customLinkSchema).max(5).optional(),
});

主要功能

1. 头像预览

<Avatar className="h-16 w-16">
  <AvatarImage src={watchedAvatar} />
  <AvatarFallback>
    {watchedName?.charAt(0)?.toUpperCase()}
  </AvatarFallback>
</Avatar>

2. 链接管理

  • 添加链接(最多 5 个)
  • 删除链接
  • 上移/下移排序
  • 类型选择和 URL 输入

3. 认证徽章

  • 显示已认证状态
  • 购买认证徽章(未认证用户)
  • 可折叠的购买区域

依赖

  • next/navigation - 路由
  • next-auth/react - 认证
  • next-intl - 国际化
  • react-hook-form - 表单管理
  • @hookform/resolvers/zod - Zod 验证
  • zod - 验证库
  • lucide-react - 图标
  • sonner - toast 通知
  • @/components/ui/* - UI 组件
  • @/lib/analytics - 分析

API 端点

PATCH /api/user/profile

注意事项

  1. 用户名修改会触发页面重定向到新 URL
  2. 邮箱地址只读显示,不可修改
  3. 认证徽章需要付费购买
  4. 表单使用 React Hook Form 管理
  5. 提交成功后刷新会话和页面数据
  6. 链接排序通过数组交换实现
← 返回目录