summaryrefslogtreecommitdiff
path: root/src/components/auth/user-avatar.tsx
blob: 53b20b502b6c6c310100e04205d53f04d11d9808 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import type { ComponentProps } from 'react';

import { Icons } from '@/components/icons/icons';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import type { User } from '@/lib/auth-client';
import { cn } from '@/lib/utils';

export interface UserAvatarClassNames {
  base?: string;
  image?: string;
  fallback?: string;
  fallbackIcon?: string;
}

export interface UserAvatarProps {
  user?: User | null;
  classNames?: UserAvatarClassNames;
}

export function UserAvatar({
  user,
  classNames,
  className,
  ...props
}: UserAvatarProps & ComponentProps<typeof Avatar>) {
  const name = user?.name || user?.email;
  const src = user?.image;

  return (
    <Avatar
      key={src}
      className={cn('rounded-md', className, classNames?.base)}
      {...props}
    >
      <AvatarImage
        alt={name ?? 'Avatar'}
        className={cn('rounded-md', classNames?.image)}
        src={src ?? undefined}
      />

      <AvatarFallback
        className={cn(
          'rounded-md bg-transparent uppercase',
          classNames?.fallback,
        )}
        delayMs={src ? 200 : 0}
      >
        {firstTwoCharacters(name) ?? (
          <Icons.user className={cn('w-[55%]', classNames?.fallbackIcon)} />
        )}
      </AvatarFallback>
    </Avatar>
  );
}

const firstTwoCharacters = (name?: string | null) => name?.slice(0, 2);