buster/web/src/components/ui/avatar/Avatar.tsx

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-02-27 05:06:23 +08:00
import React from 'react';
import { Avatar as AvatarBase, AvatarFallback, AvatarImage } from './AvatarBase';
import { getFirstTwoCapitalizedLetters } from '@/lib/text';
import { Tooltip } from '../tooltip/Tooltip';
import { BusterLogo } from '@/assets/svg/BusterLogo';
import { cn } from '@/lib/utils';
2025-02-27 14:25:53 +08:00
export interface AvatarProps {
2025-02-27 05:06:23 +08:00
image?: string;
name?: string | null;
className?: string;
useToolTip?: boolean;
2025-02-27 14:25:53 +08:00
size?: number;
2025-02-27 05:06:23 +08:00
}
2025-02-27 14:25:53 +08:00
export const Avatar: React.FC<AvatarProps> = React.memo(
({ image, name, className, useToolTip, size }) => {
2025-02-27 05:06:23 +08:00
const hasName = !!name;
const nameLetters = hasName ? createNameLetters(name, image) : '';
return (
2025-03-06 14:14:02 +08:00
<Tooltip delayDuration={550} title={useToolTip ? name || '' : ''}>
2025-02-27 14:25:53 +08:00
<AvatarBase
className={className}
style={{
width: size,
height: size
}}>
2025-02-27 05:06:23 +08:00
{image && <AvatarImage src={image} />}
2025-03-02 12:00:19 +08:00
<AvatarFallback className={cn(!hasName && !image && 'border bg-white')}>
2025-02-27 05:06:23 +08:00
{nameLetters || <BusterAvatarFallback />}
</AvatarFallback>
</AvatarBase>
</Tooltip>
);
}
);
Avatar.displayName = 'Avatar';
const BusterAvatarFallback: React.FC = () => {
return (
2025-02-27 05:08:55 +08:00
<div className="text-foreground flex h-full w-full items-center justify-center">
<BusterLogo className="h-full w-full translate-x-[1px] p-1" />
2025-02-27 05:06:23 +08:00
</div>
);
};
const createNameLetters = (name?: string | null, image?: string | null | React.ReactNode) => {
if (name && !image) {
const firstTwoLetters = getFirstTwoCapitalizedLetters(name);
if (firstTwoLetters.length == 2) return firstTwoLetters;
//Get First Name Initial
const _name = name.split(' ') as [string, string];
const returnName = `${_name[0][0]}`.toUpperCase().replace('@', '');
return returnName;
}
return '';
};