Files

60 lines
1.9 KiB
TypeScript
Raw Permalink Normal View History

2026-10-05 18:10:18 -04:00
import BoringAvatar from 'boring-avatars';
import { useCurrentUser } from '@/api/account/queries';
2026-10-12 09:04:03 -04:00
import { replaceable, useSkin } from '@/themes/skins';
2022-06-19 13:46:15 -04:00
2026-10-05 18:10:18 -04:00
const palette = ['var(--chart-1)', 'var(--chart-2)', 'var(--chart-3)', 'var(--chart-4)', 'var(--chart-5)'];
2022-06-19 13:46:15 -04:00
2026-10-12 09:04:03 -04:00
export type AvatarVariant = 'beam' | 'marble' | 'pixel' | 'sunset' | 'ring' | 'bauhaus';
2022-06-19 13:46:15 -04:00
2026-10-12 09:04:03 -04:00
export interface AvatarProps {
/** Seeds the generated pattern; the panel uses a user's UUID. */
name: string;
size?: number | string;
variant?: AvatarVariant;
square?: boolean;
title?: boolean;
className?: string;
2026-10-20 15:30:15 -04:00
/** An uploaded picture drawn in place of the pattern, such as a user's `avatar`. */
2026-10-20 21:09:33 +02:00
image?: string | null;
2026-10-12 09:04:03 -04:00
}
2022-06-19 13:46:15 -04:00
2026-10-20 15:30:15 -04:00
function CoreAvatar({ variant = 'beam', image, className, ...props }: AvatarProps) {
2026-10-12 09:04:03 -04:00
const ui = useSkin('Avatar', { variant });
2022-06-19 13:46:15 -04:00
2026-10-20 15:30:15 -04:00
if (image) {
// Shaped and sized like the pattern: round unless `square`, and as wide as its box without a `size`.
2026-10-20 21:09:33 +02:00
return (
<img
2026-10-20 15:30:15 -04:00
src={image}
2026-10-20 21:09:33 +02:00
alt={props.title ? props.name : ''}
2026-10-20 15:30:15 -04:00
style={{
width: props.size ?? '100%',
height: props.size,
aspectRatio: '1',
objectFit: 'cover',
borderRadius: props.square ? undefined : '50%',
}}
{...ui('root', className)}
2026-10-20 21:09:33 +02:00
/>
);
}
2026-10-12 09:04:03 -04:00
return <BoringAvatar colors={palette} variant={variant} {...props} {...ui('root', className)} />;
}
const _Avatar = replaceable('Avatar', CoreAvatar);
2026-10-20 21:09:33 +02:00
const UserAvatar = (props: Omit<AvatarProps, 'name'>) => {
const user = useCurrentUser();
return <_Avatar name={user.uuid} image={user.avatar} {...props} />;
};
2022-06-19 13:46:15 -04:00
2026-10-05 18:10:18 -04:00
UserAvatar.displayName = 'Avatar.User';
2022-06-19 13:46:15 -04:00
const Avatar = Object.assign(_Avatar, {
2026-10-05 18:10:18 -04:00
User: UserAvatar,
2022-06-19 13:46:15 -04:00
});
export default Avatar;