# Avatar

## Introduction

The Avatar component displays a user's profile image, initials, or icon. It is based on Joy UI Avatar and supports various sizes, colors, and variants. It is used to visually represent individuals, groups, or brands in a user interface.

```tsx
<Avatar alt="User avatar" />
```

| Field    | Description | Default       |
| -------- | ----------- | ------------- |
| variant  | —           | —             |
| color    | —           | —             |
| size     | —           | —             |
| src      | —           | —             |
| alt      | —           | "User avatar" |
| children | —           | —             |

## Usage

```tsx
import { Avatar } from '@ceed/cds';

function MyComponent() {
  return (
    <div>
      {/* Avatar with an image */}
      <Avatar src="/path/to/image.jpg" alt="사용자 이름" />

      {/* Initials avatar */}
      <Avatar>김철수</Avatar>

      {/* Single-character avatar */}
      <Avatar>김</Avatar>
    </div>
  );
}
```

## Examples

### Basic Usage

The most basic Avatar usage.

```tsx
<Avatar alt="User avatar" />
```

### With Image

An avatar that uses an image.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
    <Avatar {...args} />
  </Stack>
```

### With Text

An avatar that uses text or initials.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
    <Avatar {...args} />
  </Stack>
```

## Customization

### Variants

You can apply various visual styles.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
    {variants.map((variant) => (
      <Avatar key={variant} {...args} variant={variant} />
    ))}
  </Stack>
```

- **solid**: A style with a filled background color
- **soft**: A style with a soft background color
- **outlined**: A style with only a border
- **plain**: A minimal style

### Sizes

You can use avatars in various sizes.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
    {sizesWithXs.map((size) => (
      <Avatar key={size} {...args} size={size}>
        {getSizeContent(size)}
      </Avatar>
    ))}
  </Stack>
```

- **xs**: Extra small size (16px)
- **sm**: Small size (24px)
- **md**: Medium size (32px, default)
- **lg**: Large size (40px)

### Colors

You can apply various color themes.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
    {colors.map((color) => (
      <Avatar key={color} {...args} color={color} />
    ))}
  </Stack>
```

- **primary**: Primary brand color
- **neutral**: Neutral gray tone
- **danger**: Red for warnings or errors
- **success**: Green for success
- **warning**: Orange for caution

### All Combinations

You can review all variant, size, and color combinations.

```tsx
<Stack gap={8}>
    {variants.map((variant) => (
      <Stack key={variant} gap={2}>
        <Typography level="title-md">
          {variant.slice(0, 1).toLocaleUpperCase()}
          {variant.slice(1)} Variant
        </Typography>
        {colors.map((color) => (
          <Stack key={color} direction="row" gap={2} alignItems="center">
            {sizesWithXs.map((size) => (
              <Stack key={size} alignItems="center" gap={1}>
                <Avatar {...args} size={size} color={color} variant={variant}>
                  {getSizeContent(size)}
                </Avatar>
                <Typography level="body-sm">{size}</Typography>
              </Stack>
            ))}
            {/* With image */}
            <Stack alignItems="center" gap={1}>
              <Avatar {...args} size="md" color={color} variant={variant} />
              <Typography level="body-sm">image</Typography>
            </Stack>
          </Stack>
        ))}
      </Stack>
    ))}
  </Stack>
```

## Common Use Cases

### User Profile

An example of using an avatar in a user profile.

```tsx
<Stack direction="row" spacing={2} alignItems="center">
  <Avatar src="/user-profile.jpg" alt="김철수" size="lg" />
  <Stack>
    <Typography level="title-md">김철수</Typography>
    <Typography level="body-sm" color="neutral">
      kim@example.com
    </Typography>
  </Stack>
</Stack>
```

### Navigation Bar

Used to display the current user in a navigation bar.

```tsx
<Stack direction="row" spacing={2} alignItems="center" sx={{ ml: 'auto' }}>
  <Avatar size="sm" variant="soft" color="primary">
    김
  </Avatar>
  <Typography level="body-sm">김철수</Typography>
  <IconButton variant="plain" size="sm">
    <ExpandMoreIcon />
  </IconButton>
</Stack>
```

### Comment System

Used to represent a user in comments or feeds.

```tsx
<Stack direction="row" spacing={2}>
  <Avatar size="md" variant="soft" color="primary">
    김
  </Avatar>
  <Stack flex={1}>
    <Stack direction="row" spacing={1} alignItems="center">
      <Typography level="title-sm">김철수</Typography>
      <Typography level="body-xs" color="neutral">
        2시간 전
      </Typography>
    </Stack>
    <Typography level="body-md">이것은 사용자의 댓글 내용입니다.</Typography>
  </Stack>
</Stack>
```

### Team Members

Used to display a list of team members.

```tsx
<Stack spacing={3}>
  <Typography level="title-lg">팀 구성원</Typography>

  {teamMembers.map((member) => (
    <Stack key={member.id} direction="row" spacing={2} alignItems="center">
      <Avatar src={member.avatar} alt={member.name} size="md" variant="soft" color="primary">
        {member.name.charAt(0)}
      </Avatar>
      <Stack flex={1}>
        <Typography level="title-sm">{member.name}</Typography>
        <Typography level="body-sm" color="neutral">
          {member.role}
        </Typography>
      </Stack>
      <Chip variant="soft" size="sm" color="success">
        온라인
      </Chip>
    </Stack>
  ))}
</Stack>
```

### Avatar Groups

Used to display multiple users as a group.

```tsx
<Stack direction="row" spacing={-1}>
  <Avatar size="sm" variant="solid" color="primary">
    김
  </Avatar>
  <Avatar size="sm" variant="solid" color="success">
    이
  </Avatar>
  <Avatar size="sm" variant="solid" color="warning">
    박
  </Avatar>
  <Avatar size="sm" variant="outlined" color="neutral">
    <Typography level="body-xs">+3</Typography>
  </Avatar>
</Stack>
```

### Status Indicators

Used to display user status alongside the avatar.

```tsx
<Box sx={{ position: 'relative', display: 'inline-block' }}>
  <Avatar src="/user-avatar.jpg" alt="사용자" size="lg" />
  <Box
    sx={{
      position: 'absolute',
      bottom: 0,
      right: 0,
      width: 12,
      height: 12,
      bgcolor: 'success.500',
      borderRadius: '50%',
      border: '2px solid',
      borderColor: 'background.body',
    }}
  />
</Box>
```

### Empty State

Used as a placeholder when no data is available.

```tsx
<Stack alignItems="center" spacing={2}>
  <Avatar size="lg" variant="outlined" color="neutral">
    <PersonIcon />
  </Avatar>
  <Typography level="body-md" color="neutral">
    프로필 이미지를 업로드하세요
  </Typography>
  <Button variant="outlined" size="sm">
    이미지 선택
  </Button>
</Stack>
```

### List Items

Used to represent users or items in list items.

```tsx
<List>
  {users.map((user) => (
    <ListItem key={user.id}>
      <ListItemDecorator>
        <Avatar src={user.avatar} alt={user.name} size="sm">
          {user.name.charAt(0)}
        </Avatar>
      </ListItemDecorator>
      <ListItemContent>
        <Typography level="title-sm">{user.name}</Typography>
        <Typography level="body-sm" color="neutral">
          {user.email}
        </Typography>
      </ListItemContent>
    </ListItem>
  ))}
</List>
```

## Image Handling

### Fallback Behavior

If image loading fails, it automatically falls back to initials or an icon.

```tsx
<Avatar src="/broken-image-url.jpg" alt="김철수" color="primary" variant="soft">
  김
</Avatar>
```

### Loading States

While the image is loading, `children` are shown first, then the image is displayed once loading completes.

```tsx
<Avatar src="/slow-loading-image.jpg" alt="사용자" color="neutral" variant="soft">
  <PersonIcon />
</Avatar>
```

## Props and Customization

### Key Props

| Prop         | Type                                                           | Default         | Description                                     |
| ------------ | -------------------------------------------------------------- | --------------- | ----------------------------------------------- |
| `src`        | `string`                                                       | -               | Image URL for the avatar                        |
| `alt`        | `string`                                                       | -               | Alt text for the avatar image                   |
| `children`   | `ReactNode`                                                    | -               | Fallback content (text, icon) when no image     |
| `getInitial` | `(name: string) => string`                                     | First character | Custom function to extract initials from a name |
| `size`       | `'sm' \| 'md' \| 'lg'`                                         | `'md'`          | Avatar size                                     |
| `variant`    | `'solid' \| 'soft' \| 'outlined' \| 'plain'`                   | `'soft'`        | Visual style                                    |
| `color`      | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'neutral'`     | Color scheme                                    |
| `sx`         | `SxProps`                                                      | -               | Custom styles using the MUI system              |

> **Note**: Avatar also accepts all Joy UI Avatar props and Framer Motion props.

## Accessibility

Avatar provides the following accessibility features:

### Image Alt Text

For image avatars, provide appropriate alt text.

```tsx
<Avatar src="/user-profile.jpg" alt="김철수의 프로필 사진" />
```

### Semantic Meaning

If the avatar carries meaning rather than serving a purely decorative purpose, provide an appropriate role.

```tsx
<Avatar src="/user-avatar.jpg" alt="현재 사용자" role="img" aria-label="현재 로그인한 사용자의 프로필 이미지" />
```

### Color Contrast

For text avatars, maintain sufficient color contrast.

```tsx
// Color combinations that provide good contrast
<Avatar variant="solid" color="primary">김</Avatar>
<Avatar variant="soft" color="neutral">이</Avatar>
```

## Best Practices

1. **Choose an appropriate size**: Select a size that fits the usage context.

```tsx
// ✅ Appropriate size usage
<Avatar size="sm">김</Avatar>  // In a list item
<Avatar size="lg">김</Avatar>  // On a profile page

// ❌ Inappropriate size usage
<Avatar size="lg">김</Avatar>  // In a navigation bar (too large)
```

2. **Consistent styling**: Use consistent variants and colors within the same context.

3. **Optimize images**: Use avatar images optimized to an appropriate size.

4. **Provide a fallback**: Prepare an appropriate fallback for missing or failed image loads.

```tsx
<Avatar src={user.avatar} alt={user.name} color="primary" variant="soft">
  {user.name?.charAt(0) || '?'}
</Avatar>
```

5. **Meaningful usage**: It should be clear whom the avatar represents.

## Performance Considerations

1. **Image optimization**: Optimize avatar images to a small size to improve loading speed.

2. **Lazy Loading**: Consider lazy loading on pages with many avatars.

3. **Caching**: Cache frequently used avatar images appropriately.

Avatar is an important component for visually representing people in a user interface. By choosing the right size, color, and variant, you can provide a consistent and accessible user experience.
