87 lines
2.4 KiB
TypeScript
87 lines
2.4 KiB
TypeScript
|
|
/**
|
|||
|
|
* 头像工具函数
|
|||
|
|
* 使用 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)}`
|
|||
|
|
}
|