library-picturebook-activity/lesingle-creation-frontend/src/utils/avatar.ts
En 98e9ad1d28 feat(前端): 测试环境登录框支持自动填充测试账号
通过 VITE_AUTO_FILL_TEST 环境变量控制,在 .env.test 中启用,
使测试环境构建后登录框也能自动填充测试账号,方便测试人员使用。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 17:03:22 +08:00

87 lines
2.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 头像工具函数
* 使用 DiceBear API 自动生成默认头像
*/
// DiceBear 头像风格
export type AvatarStyle =
| 'initials' // 首字母风格
| 'avataaars' // 卡通人物风格
| 'bottts' // 机器人风格
| 'pixel-art' // 像素风格
| 'identicon' // GitHub风格的几何图案
| 'thumbs' // 拇指风格
| 'shapes' // 几何形状风格
export interface AvatarOptions {
style?: AvatarStyle
backgroundColor?: string
textColor?: string
size?: number
}
const defaultOptions: AvatarOptions = {
style: 'initials',
backgroundColor: '01412b', // 深绿色主题(与侧边栏一致)
textColor: 'ffffff',
size: 64,
}
/**
* 生成 DiceBear 头像 URL
* @param seed - 用于生成头像的种子值通常是用户名或ID
* @param options - 头像配置选项
* @returns 头像 URL
*/
export function generateAvatarUrl(seed: string, options?: AvatarOptions): string {
const opts = { ...defaultOptions, ...options }
const params = new URLSearchParams()
params.set('seed', seed)
if (opts.backgroundColor) {
params.set('backgroundColor', opts.backgroundColor)
}
if (opts.style === 'initials' && opts.textColor) {
params.set('textColor', opts.textColor)
}
if (opts.size) {
params.set('size', opts.size.toString())
}
return `https://api.dicebear.com/7.x/${opts.style}/svg?${params.toString()}`
}
/**
* 获取用户头像 URL
* 如果用户有自定义头像则返回自定义头像,否则自动生成默认头像
* @param user - 用户对象
* @param options - 头像配置选项
* @returns 头像 URL
*/
export function getUserAvatar(
user: { avatar?: string | null; username?: string; nickname?: string; id?: number } | null | undefined,
options?: AvatarOptions
): string {
// 如果用户有自定义头像,直接返回
if (user?.avatar) {
return user.avatar
}
// 否则根据用户名或昵称生成默认头像
const seed = user?.username || user?.nickname || user?.id?.toString() || 'user'
return generateAvatarUrl(seed, options)
}
/**
* 生成随机颜色的头像
* @param seed - 用于生成头像的种子值
* @param style - 头像风格
* @returns 头像 URL
*/
export function generateRandomAvatar(seed: string, style: AvatarStyle = 'initials'): string {
return `https://api.dicebear.com/7.x/${style}/svg?seed=${encodeURIComponent(seed)}`
}