# Avatar

A circular image that represents a person, with initials or an icon when no image is available.

Avatar is an open-source component from suiss/ui for React, React Native, SwiftUI and Jetpack Compose. The @esuiss/ui CLI copies its source into your project, so you own the code.

Source: https://ui.suiss.app/docs/components/avatar

**React**

**Example**

```tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

const people = [
  {
    name: "Emma Wilson",
    initials: "EW",
    src: "https://i.pravatar.cc/128?img=47",
  },
  {
    name: "Liam Carter",
    initials: "LC",
    src: "https://i.pravatar.cc/128?img=12",
  },
  {
    name: "Sofia Martinez",
    initials: "SM",
    src: "https://i.pravatar.cc/128?img=32",
  },
] as const

export default function AvatarDemo() {
  return (
    <Avatar>
      <AvatarImage src={people[0].src} alt={people[0].name} />
      <AvatarFallback>{people[0].initials}</AvatarFallback>
    </Avatar>
  )
}
```

Avatar wraps the avatar primitive of the chosen base. An `Avatar` contains an `AvatarImage` and an `AvatarFallback`; the fallback shows while the image is loading or if it fails to load. Add an `AvatarBadge` to show a status dot or icon in the bottom-end corner.

To show several people together, place avatars in an `AvatarGroup`, which overlaps them and rings each one with the background color. End the group with an `AvatarGroupCount` to indicate how many more people there are.

## Installation

### CLI

```bash title="Terminal"
npx shadcn@latest add @esuiss/avatar
```

Works in any project with a `components.json`. See [Installation](https://ui.suiss.app/docs/installation#add-components) for the one-line registry setup. Or use the suiss/ui CLI:

```bash title="Terminal"
npx @esuiss/ui@latest add avatar
```

### Manual

1. Install the dependencies and add the [`cn` helper](https://ui.suiss.app/docs/installation#the-cn-helper):

```bash title="Terminal"
npm install @base-ui/react
```

2. Copy the source into `components/ui/avatar.tsx`:

```tsx title="components/ui/avatar.tsx"
"use client"

import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
import type * as React from "react"
import { cn } from "@/lib/utils"

function Avatar({
  className,
  size = "default",
  ...props
}: AvatarPrimitive.Root.Props & {
  size?: "default" | "sm" | "lg" | "xl"
}) {
  return (
    <AvatarPrimitive.Root
      data-slot="avatar"
      data-size={size}
      className={cn(
        "group/avatar relative flex size-8 shrink-0 rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xl]:size-16",
        className
      )}
      {...props}
    />
  )
}

function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
  return (
    <AvatarPrimitive.Image
      data-slot="avatar-image"
      className={cn(
        "aspect-square size-full rounded-full object-cover",
        className
      )}
      {...props}
    />
  )
}

function AvatarFallback({
  className,
  ...props
}: AvatarPrimitive.Fallback.Props) {
  return (
    <AvatarPrimitive.Fallback
      data-slot="avatar-fallback"
      className={cn(
        "flex size-full items-center justify-center rounded-full bg-linear-to-b from-muted-foreground/90 to-muted-foreground text-xs font-semibold text-primary-foreground uppercase group-data-[size=lg]/avatar:text-base group-data-[size=sm]/avatar:text-xs group-data-[size=xl]/avatar:text-2xl dark:from-muted-foreground/70 dark:to-muted-foreground/50 *:[svg]:size-3/5",
        className
      )}
      {...props}
    />
  )
}

function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
  return (
    <span
      data-slot="avatar-badge"
      className={cn(
        "absolute inset-e-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none",
        "group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
        "group-data-[size=default]/avatar:size-3 group-data-[size=default]/avatar:[&>svg]:size-2",
        "group-data-[size=lg]/avatar:size-3.5 group-data-[size=lg]/avatar:[&>svg]:size-2.5",
        "group-data-[size=xl]/avatar:size-4.5 group-data-[size=xl]/avatar:[&>svg]:size-3",
        className
      )}
      {...props}
    />
  )
}

function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="avatar-group"
      className={cn(
        "group/avatar-group flex -space-x-2 has-[[data-slot=avatar][data-size=xl]]:-space-x-4 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
        className
      )}
      {...props}
    />
  )
}

function AvatarGroupCount({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="avatar-group-count"
      className={cn(
        "relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-semibold text-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=lg]/avatar-group:text-base group-has-data-[size=sm]/avatar-group:size-6 group-has-data-[size=sm]/avatar-group:text-xs group-has-data-[size=xl]/avatar-group:size-16 group-has-data-[size=xl]/avatar-group:text-2xl [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3 group-has-data-[size=xl]/avatar-group:[&>svg]:size-7",
        className
      )}
      {...props}
    />
  )
}

export {
  Avatar,
  AvatarBadge,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
}
```

3. Update the import paths to match your project.

## Usage

```tsx
import { Avatar, AvatarImage, AvatarFallback, AvatarBadge, AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"
```

```tsx
<Avatar>
  <AvatarImage src={people[0].src} alt={people[0].name} />
  <AvatarFallback>{people[0].initials}</AvatarFallback>
</Avatar>
```

Always provide an `AvatarFallback` alongside `AvatarImage`, usually the person's initials. The fallback can also hold an icon, which scales to 60% of the avatar.

Set `size` on each `Avatar`. Inside an `AvatarGroup`, `AvatarGroupCount` matches the size of the avatars in the group automatically.

## Examples

### Fallback

Shows initials when no image is provided.

**Example**

```tsx
import { Avatar, AvatarFallback } from "@/components/ui/avatar"

export default function AvatarFallbackExample() {
  return (
    <Avatar>
      <AvatarFallback>LC</AvatarFallback>
    </Avatar>
  )
}
```

### Fallback sizes

Initials fallbacks at every size.

**Example**

```tsx
import { Avatar, AvatarFallback } from "@/components/ui/avatar"

const people = [
  {
    name: "Emma Wilson",
    initials: "EW",
    src: "https://i.pravatar.cc/128?img=47",
  },
  {
    name: "Liam Carter",
    initials: "LC",
    src: "https://i.pravatar.cc/128?img=12",
  },
  {
    name: "Sofia Martinez",
    initials: "SM",
    src: "https://i.pravatar.cc/128?img=32",
  },
] as const

export default function AvatarFallbackSizes() {
  return (
    <div className="flex items-center gap-3">
      {(["sm", "default", "lg", "xl"] as const).map((size) => (
        <Avatar key={size} size={size}>
          <AvatarFallback>{people[0].initials}</AvatarFallback>
        </Avatar>
      ))}
    </div>
  )
}
```

### Placeholder

Uses a person icon as the fallback at every size.

**Example**

```tsx
import { UserIcon } from "@phosphor-icons/react"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"

export default function AvatarPlaceholder() {
  return (
    <div className="flex items-center gap-3">
      {(["sm", "default", "lg", "xl"] as const).map((size) => (
        <Avatar key={size} size={size}>
          <AvatarFallback>
            <UserIcon className="fill-current" />
          </AvatarFallback>
        </Avatar>
      ))}
    </div>
  )
}
```

### Sizes

Image avatars in the `sm`, `default`, `lg` and `xl` sizes.

**Example**

```tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

const people = [
  {
    name: "Emma Wilson",
    initials: "EW",
    src: "https://i.pravatar.cc/128?img=47",
  },
  {
    name: "Liam Carter",
    initials: "LC",
    src: "https://i.pravatar.cc/128?img=12",
  },
  {
    name: "Sofia Martinez",
    initials: "SM",
    src: "https://i.pravatar.cc/128?img=32",
  },
] as const

export default function AvatarSizes() {
  return (
    <div className="flex items-center gap-3">
      {(["sm", "default", "lg", "xl"] as const).map((size) => (
        <Avatar key={size} size={size}>
          <AvatarImage src={people[1].src} alt={people[1].name} />
          <AvatarFallback>{people[1].initials}</AvatarFallback>
        </Avatar>
      ))}
    </div>
  )
}
```

### With badge

Adds a check-mark status badge to each size.

**Example**

```tsx
import { CheckIcon } from "@phosphor-icons/react"
import {
  Avatar,
  AvatarBadge,
  AvatarFallback,
  AvatarImage,
} from "@/components/ui/avatar"

const people = [
  {
    name: "Emma Wilson",
    initials: "EW",
    src: "https://i.pravatar.cc/128?img=47",
  },
  {
    name: "Liam Carter",
    initials: "LC",
    src: "https://i.pravatar.cc/128?img=12",
  },
  {
    name: "Sofia Martinez",
    initials: "SM",
    src: "https://i.pravatar.cc/128?img=32",
  },
] as const

export default function AvatarWithBadge() {
  return (
    <div className="flex items-center gap-4">
      {(["sm", "default", "lg", "xl"] as const).map((size) => (
        <Avatar key={size} size={size}>
          <AvatarImage src={people[2].src} alt={people[2].name} />
          <AvatarFallback>{people[2].initials}</AvatarFallback>
          <AvatarBadge className="bg-green-500">
            <CheckIcon />
          </AvatarBadge>
        </Avatar>
      ))}
    </div>
  )
}
```

### Group

Overlaps several avatars and ends with a `+4` count.

**Example**

```tsx
import {
  Avatar,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
} from "@/components/ui/avatar"

const people = [
  {
    name: "Emma Wilson",
    initials: "EW",
    src: "https://i.pravatar.cc/128?img=47",
  },
  {
    name: "Liam Carter",
    initials: "LC",
    src: "https://i.pravatar.cc/128?img=12",
  },
  {
    name: "Sofia Martinez",
    initials: "SM",
    src: "https://i.pravatar.cc/128?img=32",
  },
] as const

export default function AvatarGroupExample() {
  return (
    <AvatarGroup>
      {people.map((person) => (
        <Avatar key={person.name}>
          <AvatarImage src={person.src} alt={person.name} />
          <AvatarFallback>{person.initials}</AvatarFallback>
        </Avatar>
      ))}
      <AvatarGroupCount>+4</AvatarGroupCount>
    </AvatarGroup>
  )
}
```

### Group with icon count

A large group whose count shows a plus icon instead of a number.

**Example**

```tsx
import { PlusIcon } from "@phosphor-icons/react"
import {
  Avatar,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
} from "@/components/ui/avatar"

const people = [
  {
    name: "Emma Wilson",
    initials: "EW",
    src: "https://i.pravatar.cc/128?img=47",
  },
  {
    name: "Liam Carter",
    initials: "LC",
    src: "https://i.pravatar.cc/128?img=12",
  },
  {
    name: "Sofia Martinez",
    initials: "SM",
    src: "https://i.pravatar.cc/128?img=32",
  },
] as const

export default function AvatarGroupWithIconCount() {
  return (
    <AvatarGroup>
      {people.map((person) => (
        <Avatar key={person.name} size="lg">
          <AvatarImage src={person.src} alt={person.name} />
          <AvatarFallback>{person.initials}</AvatarFallback>
        </Avatar>
      ))}
      <AvatarGroupCount>
        <PlusIcon />
      </AvatarGroupCount>
    </AvatarGroup>
  )
}
```

## API Reference

- `Avatar`
- `AvatarImage`
- `AvatarFallback`
- `AvatarBadge`
- `AvatarGroup`
- `Avatar`
  - `AvatarImage`
  - `AvatarFallback`
- `AvatarGroupCount`

### Avatar

The circular root that sets the size.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `"default" \| "sm" \| "lg" \| "xl"` | `"default"` | Diameter of the avatar: `sm`, `default`, `lg` or `xl`. Also scales the fallback text and badge. |

Also accepts the props of the primitive part it wraps.

### AvatarImage

The person's image, cropped to a circle.

Also accepts the props of the primitive part it wraps.

### AvatarFallback

Content shown when the image is missing or still loading.

Also accepts the props of the primitive part it wraps.

### AvatarBadge

A small status indicator pinned to the bottom-end corner.

Also accepts the props of `React.ComponentProps<"span">`.

### AvatarGroup

A row that overlaps avatars with a ring between them.

Also accepts the props of `React.ComponentProps<"div">`.

### AvatarGroupCount

A trailing circle that shows how many avatars are not displayed.

Also accepts the props of `React.ComponentProps<"div">`.

## Accessibility

- Give `AvatarImage` an `alt` that names the person.
- `AvatarBadge` and `AvatarGroupCount` are plain elements; if they carry meaning, label them or describe the status in nearby text.

## Notes

- Styling hooks: `data-slot="avatar"`, `"avatar-image"`, `"avatar-fallback"`, `"avatar-badge"`, `"avatar-group"` and `"avatar-group-count"`, plus `data-size` on the root.
- `AvatarBadge` uses `bg-primary` by default; override it, for example with `bg-green-500`. At the `sm` size, icons inside the badge are hidden.
- The fallback uses a vertical gradient of `muted-foreground` with `text-primary-foreground`.

**React Native, SwiftUI, Jetpack Compose**

![Preview](https://ui.suiss.app/previews/components-avatar--default.light.webp)

```tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Text } from "@/components/ui/text"

export function AvatarExample() {
  return (
    <Avatar>
      <AvatarImage
        alt="Ada Lovelace"
        source={{ uri: "https://i.pravatar.cc/150?img=5" }}
      />
      <AvatarFallback>
        <Text>AL</Text>
      </AvatarFallback>
    </Avatar>
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct AvatarExample: View {
  var body: some View {
    Avatar(url: URL(string: "https://i.pravatar.cc/150?img=5"), initials: "AL")
      .accessibilityLabel(Text("Ada Lovelace"))
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.semantics.contentDescription
import com.esuiss.ui.components.Avatar
import com.esuiss.ui.components.AvatarFallback
import com.esuiss.ui.components.AvatarSize
import com.esuiss.ui.theme.Palette

class AvatarPerson(val name: String, val initials: String, val tones: @Composable () -> List<Color>)

val avatarPeople = listOf(
    AvatarPerson("Ada Lovelace", "AL") { listOf(Palette.pink500, Palette.purple500) },
    AvatarPerson("Alan Turing", "AT") { listOf(Palette.teal500, Palette.blue500) },
    AvatarPerson("Grace Hopper", "GH") { listOf(Palette.orange500, Palette.red500) },
)

@Composable
fun AvatarPhoto(person: AvatarPerson, size: AvatarSize = AvatarSize.Default, badge: (@Composable () -> Unit)? = null) {
    val tones = person.tones()
    val photo = remember(tones) { BrushPainter(Brush.linearGradient(tones)) }
    Avatar(
        size = size,
        image = photo,
        contentDescription = person.name,
        badge = badge,
        fallback = { AvatarFallback(person.initials) },
    )
}

@Composable
fun AvatarDefault() {
    Row {
        AvatarPhoto(avatarPeople[0])
    }
}
```

`Avatar` is a round `View` that holds an `AvatarImage` and an `AvatarFallback`. The image stays hidden until it loads, and the fallback is shown while it loads or if it fails. Four sizes are available: `sm`, `default`, `lg` and `xl`; the fallback text, icons and badge scale with the size.

`AvatarBadge` adds a small status dot in the bottom-end corner, and `AvatarGroup` overlaps several avatars with an outline between them, with `AvatarGroupCount` for the remaining number.

## Installation

**React Native**

```bash title="Terminal"
npx shadcn@latest add @esuiss-rn/avatar
```

See [Installation](https://ui.suiss.app/docs/installation) for the `components.json` setup. Or use the suiss/ui CLI:

```bash title="Terminal"
npx @esuiss/ui@latest add avatar
```

**SwiftUI**

```bash title="Terminal"
npx @esuiss/ui@latest add avatar --platform swift
```

**Jetpack Compose**

```bash title="Terminal"
npx @esuiss/ui@latest add avatar --platform kotlin
```

The CLI also adds what it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text).

### Manual

**React Native**

**Uniwind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install cn
```

2. Add the pieces it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/avatar.tsx`, `components/primitives/use-render.tsx`.

3. Copy the source into `components/ui/avatar.tsx`:

```tsx title="uniwind/components/ui/avatar.tsx"
import { cn } from "cn"
import * as React from "react"
import { View } from "react-native"
import * as AvatarPrimitive from "@/components/primitives/avatar"
import { resolveClassName } from "@/components/primitives/use-render"
import { IconClassContext } from "@/components/ui/icon"
import { Text, TextClassContext } from "@/components/ui/text"

type AvatarSize = "default" | "sm" | "lg" | "xl"

const AvatarSizeContext = React.createContext<AvatarSize>("default")

const AvatarGroupItemContext = React.createContext<number | null>(null)

const ROOT_SIZE: Record<AvatarSize, string> = {
  sm: "size-6",
  default: "size-8",
  lg: "size-10",
  xl: "size-16",
}

const FALLBACK_TEXT: Record<AvatarSize, string> = {
  sm: "text-xs",
  default: "text-xs",
  lg: "text-base",
  xl: "text-2xl",
}

const FALLBACK_ICON: Record<AvatarSize, string> = {
  sm: "size-3.5",
  default: "size-5",
  lg: "size-6",
  xl: "size-10",
}

const BADGE_SIZE: Record<AvatarSize, string> = {
  sm: "size-3",
  default: "size-4",
  lg: "size-4.5",
  xl: "size-5.5",
}

const BADGE_ICON: Record<AvatarSize, string> = {
  sm: "size-0",
  default: "size-2",
  lg: "size-2.5",
  xl: "size-3",
}

const COUNT_ICON: Record<AvatarSize, string> = {
  sm: "size-3",
  default: "size-4",
  lg: "size-5",
  xl: "size-7",
}

function Avatar({
  className,
  size = "default",
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
  size?: AvatarSize
}) {
  const groupIndex = React.useContext(AvatarGroupItemContext)
  const grouped = groupIndex !== null
  return (
    <AvatarSizeContext.Provider value={size}>
      <AvatarGroupItemContext.Provider value={null}>
        <AvatarPrimitive.Root
          className={(state) =>
            cn(
              "relative shrink-0 rounded-full",
              ROOT_SIZE[size],
              grouped && "border-2 border-background",
              grouped && groupIndex > 0 && (size === "xl" ? "-ms-4" : "-ms-2"),
              resolveClassName(className, state)
            )
          }
          {...props}
        />
      </AvatarGroupItemContext.Provider>
    </AvatarSizeContext.Provider>
  )
}

function AvatarImage({
  className,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
  return (
    <AvatarPrimitive.Image
      className={(state) =>
        cn(
          "aspect-square size-full rounded-full",
          resolveClassName(className, state)
        )
      }
      resizeMode="cover"
      {...props}
    />
  )
}

function AvatarFallback({
  className,
  children,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
  const size = React.useContext(AvatarSizeContext)
  return (
    <TextClassContext.Provider
      value={cn(
        "font-semibold uppercase text-primary-foreground",
        FALLBACK_TEXT[size]
      )}
    >
      <IconClassContext.Provider value={FALLBACK_ICON[size]}>
        <AvatarPrimitive.Fallback
          className={(state) =>
            cn(
              "size-full flex-row items-center justify-center rounded-full bg-muted-foreground dark:bg-muted-foreground/60",
              resolveClassName(className, state)
            )
          }
          {...props}
        >
          {typeof children === "string" || typeof children === "number" ? (
            <Text>{children}</Text>
          ) : (
            children
          )}
        </AvatarPrimitive.Fallback>
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

function AvatarBadge({
  className,
  children,
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>>) {
  const size = React.useContext(AvatarSizeContext)
  return (
    <TextClassContext.Provider value="text-primary-foreground">
      <IconClassContext.Provider value={BADGE_ICON[size]}>
        <View
          className={cn(
            "absolute -end-0.5 -bottom-0.5 z-10 items-center justify-center rounded-full border-2 border-background bg-primary",
            BADGE_SIZE[size],
            className
          )}
          {...props}
        >
          {size === "sm" ? null : children}
        </View>
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

function AvatarGroup({
  className,
  children,
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>>) {
  let index = 0
  const items = React.Children.map(children, (child) => {
    if (!React.isValidElement(child)) return child
    const value = index
    index += 1
    return (
      <AvatarGroupItemContext.Provider value={value}>
        {child}
      </AvatarGroupItemContext.Provider>
    )
  })
  return (
    <View className={cn("flex-row items-center", className)} {...props}>
      {items}
    </View>
  )
}

function AvatarGroupCount({
  className,
  size = "default",
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    size?: AvatarSize
  }) {
  const groupIndex = React.useContext(AvatarGroupItemContext)
  return (
    <TextClassContext.Provider
      value={cn("font-semibold text-foreground", FALLBACK_TEXT[size])}
    >
      <IconClassContext.Provider value={COUNT_ICON[size]}>
        <View
          className={cn(
            "relative shrink-0 items-center justify-center rounded-full border-2 border-background bg-muted",
            ROOT_SIZE[size],
            groupIndex !== null &&
              groupIndex > 0 &&
              (size === "xl" ? "-ms-4" : "-ms-2"),
            className
          )}
          {...props}
        />
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

export {
  Avatar,
  AvatarBadge,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
}
```

4. Update the import paths to match your project.

**NativeWind**

1. Install the dependencies:

```bash title="Terminal"
npx expo install cn
```

2. Add the pieces it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/avatar.tsx`, `components/primitives/use-render.tsx`.

3. Copy the source into `components/ui/avatar.tsx`:

```tsx title="nativewind/components/ui/avatar.tsx"
import { cn } from "cn"
import * as React from "react"
import { View } from "react-native"
import * as AvatarPrimitive from "@/components/primitives/avatar"
import { resolveClassName } from "@/components/primitives/use-render"
import { IconClassContext } from "@/components/ui/icon"
import { Text, TextClassContext } from "@/components/ui/text"

type AvatarSize = "default" | "sm" | "lg" | "xl"

const AvatarSizeContext = React.createContext<AvatarSize>("default")

const AvatarGroupItemContext = React.createContext<number | null>(null)

const ROOT_SIZE: Record<AvatarSize, string> = {
  sm: "size-6",
  default: "size-8",
  lg: "size-10",
  xl: "size-16",
}

const FALLBACK_TEXT: Record<AvatarSize, string> = {
  sm: "text-xs",
  default: "text-xs",
  lg: "text-base",
  xl: "text-2xl",
}

const FALLBACK_ICON: Record<AvatarSize, string> = {
  sm: "size-3.5",
  default: "size-5",
  lg: "size-6",
  xl: "size-10",
}

const BADGE_SIZE: Record<AvatarSize, string> = {
  sm: "size-3",
  default: "size-4",
  lg: "size-[1.125rem]",
  xl: "size-[1.375rem]",
}

const BADGE_ICON: Record<AvatarSize, string> = {
  sm: "size-0",
  default: "size-2",
  lg: "size-2.5",
  xl: "size-3",
}

const COUNT_ICON: Record<AvatarSize, string> = {
  sm: "size-3",
  default: "size-4",
  lg: "size-5",
  xl: "size-7",
}

function Avatar({
  className,
  size = "default",
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
  size?: AvatarSize
}) {
  const groupIndex = React.useContext(AvatarGroupItemContext)
  const grouped = groupIndex !== null
  return (
    <AvatarSizeContext.Provider value={size}>
      <AvatarGroupItemContext.Provider value={null}>
        <AvatarPrimitive.Root
          className={(state) =>
            cn(
              "relative shrink-0 rounded-full",
              ROOT_SIZE[size],
              grouped && "border-2 border-background",
              grouped && groupIndex > 0 && (size === "xl" ? "-ms-4" : "-ms-2"),
              resolveClassName(className, state)
            )
          }
          {...props}
        />
      </AvatarGroupItemContext.Provider>
    </AvatarSizeContext.Provider>
  )
}

function AvatarImage({
  className,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
  return (
    <AvatarPrimitive.Image
      className={(state) =>
        cn(
          "aspect-square size-full rounded-full",
          resolveClassName(className, state)
        )
      }
      resizeMode="cover"
      {...props}
    />
  )
}

function AvatarFallback({
  className,
  children,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
  const size = React.useContext(AvatarSizeContext)
  return (
    <TextClassContext.Provider
      value={cn(
        "font-semibold uppercase text-primary-foreground",
        FALLBACK_TEXT[size]
      )}
    >
      <IconClassContext.Provider value={FALLBACK_ICON[size]}>
        <AvatarPrimitive.Fallback
          className={(state) =>
            cn(
              "size-full flex-row items-center justify-center rounded-full bg-muted-foreground dark:bg-muted-foreground-60",
              resolveClassName(className, state)
            )
          }
          {...props}
        >
          {typeof children === "string" || typeof children === "number" ? (
            <Text>{children}</Text>
          ) : (
            children
          )}
        </AvatarPrimitive.Fallback>
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

function AvatarBadge({
  className,
  children,
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>>) {
  const size = React.useContext(AvatarSizeContext)
  return (
    <TextClassContext.Provider value="text-primary-foreground">
      <IconClassContext.Provider value={BADGE_ICON[size]}>
        <View
          className={cn(
            "absolute -end-0.5 -bottom-0.5 z-10 items-center justify-center rounded-full border-2 border-background bg-primary",
            BADGE_SIZE[size],
            className
          )}
          {...props}
        >
          {size === "sm" ? null : children}
        </View>
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

function AvatarGroup({
  className,
  children,
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>>) {
  let index = 0
  const items = React.Children.map(children, (child) => {
    if (!React.isValidElement(child)) return child
    const value = index
    index += 1
    return (
      <AvatarGroupItemContext.Provider value={value}>
        {child}
      </AvatarGroupItemContext.Provider>
    )
  })
  return (
    <View className={cn("flex-row items-center", className)} {...props}>
      {items}
    </View>
  )
}

function AvatarGroupCount({
  className,
  size = "default",
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    size?: AvatarSize
  }) {
  const groupIndex = React.useContext(AvatarGroupItemContext)
  return (
    <TextClassContext.Provider
      value={cn("font-semibold text-foreground", FALLBACK_TEXT[size])}
    >
      <IconClassContext.Provider value={COUNT_ICON[size]}>
        <View
          className={cn(
            "relative shrink-0 items-center justify-center rounded-full border-2 border-background bg-muted",
            ROOT_SIZE[size],
            groupIndex !== null &&
              groupIndex > 0 &&
              (size === "xl" ? "-ms-4" : "-ms-2"),
            className
          )}
          {...props}
        />
      </IconClassContext.Provider>
    </TextClassContext.Provider>
  )
}

export {
  Avatar,
  AvatarBadge,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
}
```

4. Update the import paths to match your project.

**StyleSheet**

1. Add the pieces it builds on: [Icon](https://ui.suiss.app/docs/components/icon), [Text](https://ui.suiss.app/docs/components/text), and the primitives `components/primitives/avatar.tsx`, `components/primitives/use-render.tsx`.

2. Copy the source into `components/ui/avatar.tsx`:

```tsx title="stylesheet/components/ui/avatar.tsx"
import * as React from "react"
import { StyleSheet, View } from "react-native"
import * as AvatarPrimitive from "@/components/primitives/avatar"
import { IconSizeContext } from "@/components/ui/icon"
import { Text, TextStyleContext } from "@/components/ui/text"
import { fontSize, radius, useTheme } from "@/components/ui/theme"

type AvatarSize = "default" | "sm" | "lg" | "xl"

const AvatarSizeContext = React.createContext<AvatarSize>("default")

const AvatarGroupItemContext = React.createContext<number | null>(null)

const ROOT_SIZE: Record<AvatarSize, number> = {
  sm: 24,
  default: 32,
  lg: 40,
  xl: 64,
}

const TEXT_SIZE: Record<AvatarSize, keyof typeof fontSize> = {
  sm: "xs",
  default: "xs",
  lg: "base",
  xl: "2xl",
}

const FALLBACK_ICON: Record<AvatarSize, number> = {
  sm: 14,
  default: 19,
  lg: 24,
  xl: 38,
}

const BADGE_SIZE: Record<AvatarSize, number> = {
  sm: 12,
  default: 16,
  lg: 18,
  xl: 22,
}

const BADGE_ICON: Record<AvatarSize, number> = {
  sm: 0,
  default: 8,
  lg: 10,
  xl: 12,
}

const COUNT_ICON: Record<AvatarSize, number> = {
  sm: 12,
  default: 16,
  lg: 20,
  xl: 28,
}

const styles = StyleSheet.create({
  root: {
    position: "relative",
    flexShrink: 0,
    borderRadius: radius.full,
  },
  ring: { borderWidth: 2 },
  image: {
    aspectRatio: 1,
    width: "100%",
    height: "100%",
    borderRadius: radius.full,
  },
  fallback: {
    width: "100%",
    height: "100%",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    borderRadius: radius.full,
  },
  badge: {
    position: "absolute",
    end: -2,
    bottom: -2,
    zIndex: 10,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: radius.full,
    borderWidth: 2,
  },
  group: { flexDirection: "row", alignItems: "center" },
  count: {
    position: "relative",
    flexShrink: 0,
    alignItems: "center",
    justifyContent: "center",
    borderRadius: radius.full,
    borderWidth: 2,
  },
})

function withAlpha(color: string, alpha: number) {
  if (!color.startsWith("#") || color.length !== 7) return color
  const r = Number.parseInt(color.slice(1, 3), 16)
  const g = Number.parseInt(color.slice(3, 5), 16)
  const b = Number.parseInt(color.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

function groupOffset(index: number | null, size: AvatarSize) {
  if (index === null || index === 0) return undefined
  return { marginStart: size === "xl" ? -16 : -8 }
}

function Avatar({
  style,
  size = "default",
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
  size?: AvatarSize
}) {
  const { colors } = useTheme()
  const groupIndex = React.useContext(AvatarGroupItemContext)
  const dimension = ROOT_SIZE[size]
  return (
    <AvatarSizeContext.Provider value={size}>
      <AvatarGroupItemContext.Provider value={null}>
        <AvatarPrimitive.Root
          style={(state) => [
            styles.root,
            { width: dimension, height: dimension },
            groupIndex !== null && [
              styles.ring,
              { borderColor: colors.background },
            ],
            groupOffset(groupIndex, size),
            typeof style === "function" ? style(state) : style,
          ]}
          {...props}
        />
      </AvatarGroupItemContext.Provider>
    </AvatarSizeContext.Provider>
  )
}

function AvatarImage({
  style,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
  return (
    <AvatarPrimitive.Image
      style={(state) => [
        styles.image,
        typeof style === "function" ? style(state) : style,
      ]}
      resizeMode="cover"
      {...props}
    />
  )
}

function AvatarFallback({
  style,
  children,
  ...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
  const { colors, isDark } = useTheme()
  const size = React.useContext(AvatarSizeContext)
  return (
    <TextStyleContext.Provider
      value={{
        ...fontSize[TEXT_SIZE[size]],
        fontWeight: "600",
        textTransform: "uppercase",
        color: colors.primaryForeground,
      }}
    >
      <IconSizeContext.Provider value={FALLBACK_ICON[size]}>
        <AvatarPrimitive.Fallback
          style={(state) => [
            styles.fallback,
            {
              backgroundColor: isDark
                ? withAlpha(colors.mutedForeground, 0.6)
                : colors.mutedForeground,
            },
            typeof style === "function" ? style(state) : style,
          ]}
          {...props}
        >
          {typeof children === "string" || typeof children === "number" ? (
            <Text>{children}</Text>
          ) : (
            children
          )}
        </AvatarPrimitive.Fallback>
      </IconSizeContext.Provider>
    </TextStyleContext.Provider>
  )
}

function AvatarBadge({
  style,
  children,
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>>) {
  const { colors } = useTheme()
  const size = React.useContext(AvatarSizeContext)
  const dimension = BADGE_SIZE[size]
  return (
    <TextStyleContext.Provider value={{ color: colors.primaryForeground }}>
      <IconSizeContext.Provider value={BADGE_ICON[size]}>
        <View
          style={[
            styles.badge,
            {
              width: dimension,
              height: dimension,
              backgroundColor: colors.primary,
              borderColor: colors.background,
            },
            style,
          ]}
          {...props}
        >
          {size === "sm" ? null : children}
        </View>
      </IconSizeContext.Provider>
    </TextStyleContext.Provider>
  )
}

function AvatarGroup({
  style,
  children,
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>>) {
  let index = 0
  const items = React.Children.map(children, (child) => {
    if (!React.isValidElement(child)) return child
    const value = index
    index += 1
    return (
      <AvatarGroupItemContext.Provider value={value}>
        {child}
      </AvatarGroupItemContext.Provider>
    )
  })
  return (
    <View style={[styles.group, style]} {...props}>
      {items}
    </View>
  )
}

function AvatarGroupCount({
  style,
  size = "default",
  ...props
}: React.ComponentProps<typeof View> &
  React.RefAttributes<React.ComponentRef<typeof View>> & {
    size?: AvatarSize
  }) {
  const { colors } = useTheme()
  const groupIndex = React.useContext(AvatarGroupItemContext)
  const dimension = ROOT_SIZE[size]
  return (
    <TextStyleContext.Provider
      value={{
        ...fontSize[TEXT_SIZE[size]],
        fontWeight: "600",
        color: colors.foreground,
      }}
    >
      <IconSizeContext.Provider value={COUNT_ICON[size]}>
        <View
          style={[
            styles.count,
            {
              width: dimension,
              height: dimension,
              backgroundColor: colors.muted,
              borderColor: colors.background,
            },
            groupOffset(groupIndex, size),
            style,
          ]}
          {...props}
        />
      </IconSizeContext.Provider>
    </TextStyleContext.Provider>
  )
}

export {
  Avatar,
  AvatarBadge,
  AvatarFallback,
  AvatarGroup,
  AvatarGroupCount,
  AvatarImage,
}
```

3. Update the import paths to match your project.

**SwiftUI**

1. Target iOS 17 or later.

2. Copy the theme files every view uses:

- `swift/Theme/Theme.swift`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/swiftui/Sources/EsuissUI/Theme/Theme.swift)

- `swift/Theme/Tokens.swift`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/swiftui/Sources/EsuissUI/Theme/Tokens.swift)

3. Copy the source and every file it uses:

```swift title="swift/Components/Avatar.swift"
import SwiftUI

public enum AvatarSize: CaseIterable, Sendable {
  case sm, `default`, lg, xl

  var dimension: CGFloat {
    switch self {
    case .sm: 24
    case .default: 32
    case .lg: 40
    case .xl: 64
    }
  }

  var overlap: CGFloat {
    self == .xl ? 16 : 8
  }

  var textStyle: TextStyle {
    switch self {
    case .sm: .xs
    case .default: .xs
    case .lg: .base
    case .xl: .xl2
    }
  }

  var fallbackIcon: CGFloat {
    switch self {
    case .sm: 14
    case .default: 20
    case .lg: 24
    case .xl: 40
    }
  }

  var badge: CGFloat {
    switch self {
    case .sm: 12
    case .default: 16
    case .lg: 18
    case .xl: 22
    }
  }

  var badgeIcon: CGFloat {
    switch self {
    case .sm: 0
    case .default: 8
    case .lg: 10
    case .xl: 12
    }
  }

  var countIcon: CGFloat {
    switch self {
    case .sm: 12
    case .default: 16
    case .lg: 20
    case .xl: 28
    }
  }
}

public struct Avatar<Content: View>: View {
  public typealias Size = AvatarSize

  let size: Size
  let content: Content

  @Environment(\.avatarGrouped) private var grouped

  public init(size: Size = .default, @ViewBuilder content: () -> Content) {
    self.size = size
    self.content = content()
  }

  public var body: some View {
    ZStack {
      content
    }
    .padding(grouped ? 2 : 0)
    .background {
      if grouped {
        Circle().fill(EsuissColor.background)
      }
    }
    .frame(width: size.dimension, height: size.dimension)
    .environment(\.avatarSize, size)
    .environment(\.avatarGrouped, false)
    .accessibilityElement(children: .combine)
    .accessibilityAddTraits(.isImage)
    .layoutValue(key: AvatarOverlapKey.self, value: size.overlap)
  }
}

extension Avatar {
  public init<Fallback: View>(
    url: URL?,
    size: Size = .default,
    @ViewBuilder fallback: () -> Fallback
  ) where Content == TupleView<(AvatarFallback<Fallback>, AvatarImage)> {
    let fallback = fallback()
    self.init(size: size) {
      AvatarFallback { fallback }
      AvatarImage(url: url)
    }
  }

  public init(
    url: URL?,
    initials: String,
    size: Size = .default
  ) where Content == TupleView<(AvatarFallback<Text>, AvatarImage)> {
    self.init(size: size) {
      AvatarFallback(initials)
      AvatarImage(url: url)
    }
  }
}

public struct AvatarImage: View {
  enum Source {
    case url(URL?)
    case image(Image)
  }

  let source: Source

  public init(url: URL?) {
    source = .url(url)
  }

  public init(_ image: Image) {
    source = .image(image)
  }

  public var body: some View {
    Group {
      switch source {
      case .image(let image):
        image.resizable().scaledToFill()
      case .url(let url):
        AsyncImage(url: url) { phase in
          if let image = phase.image {
            image.resizable().scaledToFill()
          } else {
            Color.clear
          }
        }
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .clipShape(Circle())
  }
}

public struct AvatarFallback<Content: View>: View {
  let content: Content

  @Environment(\.avatarSize) private var size
  @Environment(\.colorScheme) private var colorScheme

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    content
      .textCase(.uppercase)
      .scaledFont(size.textStyle, weight: .semibold)
      .lineLimit(1)
      .minimumScaleFactor(0.5)
      .foregroundStyle(EsuissColor.primaryForeground)
      .environment(\.avatarIconSize, size.fallbackIcon)
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .background(EsuissColor.mutedForeground.opacity(colorScheme == .dark ? 0.6 : 1), in: Circle())
  }
}

extension AvatarFallback where Content == Text {
  public init(_ initials: String) {
    self.init { Text(verbatim: initials) }
  }
}

extension AvatarFallback where Content == AvatarIcon {
  public init(icon: Image) {
    self.init { AvatarIcon(icon) }
  }
}

public struct AvatarIcon: View {
  let image: Image

  @Environment(\.avatarIconSize) private var size

  public init(_ image: Image) {
    self.image = image
  }

  public var body: some View {
    image
      .resizable()
      .scaledToFit()
      .frame(width: size, height: size)
  }
}

public struct AvatarBadge<Content: View>: View {
  let content: Content

  @Environment(\.avatarSize) private var size

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    ZStack {
      Circle().fill(EsuissColor.background)
      Circle().fill(EsuissColor.primary).padding(2)
      if size != .sm {
        content
          .foregroundStyle(EsuissColor.primaryForeground)
          .environment(\.avatarIconSize, size.badgeIcon)
      }
    }
    .frame(width: size.badge, height: size.badge)
    .offset(x: 2, y: 2)
    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
  }
}

extension AvatarBadge where Content == EmptyView {
  public init() {
    self.init { EmptyView() }
  }
}

extension AvatarBadge where Content == AvatarIcon {
  public init(icon: Image) {
    self.init { AvatarIcon(icon) }
  }
}

public struct AvatarGroup<Content: View>: View {
  let content: Content

  public init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  public var body: some View {
    AvatarGroupLayout {
      content
    }
    .environment(\.avatarGrouped, true)
    .accessibilityElement(children: .contain)
  }
}

public struct AvatarGroupCount<Content: View>: View {
  let size: AvatarSize
  let content: Content

  public init(size: AvatarSize = .default, @ViewBuilder content: () -> Content) {
    self.size = size
    self.content = content()
  }

  public var body: some View {
    content
      .scaledFont(size.textStyle, weight: .semibold)
      .lineLimit(1)
      .minimumScaleFactor(0.5)
      .foregroundStyle(EsuissColor.foreground)
      .environment(\.avatarIconSize, size.countIcon)
      .frame(maxWidth: .infinity, maxHeight: .infinity)
      .background(EsuissColor.muted, in: Circle())
      .padding(2)
      .background(EsuissColor.background, in: Circle())
      .frame(width: size.dimension, height: size.dimension)
      .environment(\.avatarGrouped, false)
      .layoutValue(key: AvatarOverlapKey.self, value: size.overlap)
  }
}

extension AvatarGroupCount where Content == Text {
  public init(_ count: String, size: AvatarSize = .default) {
    self.init(size: size) { Text(verbatim: count) }
  }
}

struct AvatarOverlapKey: LayoutValueKey {
  static let defaultValue: CGFloat = 8
}

struct AvatarGroupLayout: Layout {
  func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
    var width: CGFloat = 0
    var height: CGFloat = 0
    for (index, subview) in subviews.enumerated() {
      let size = subview.sizeThatFits(.unspecified)
      width += size.width - (index > 0 ? subview[AvatarOverlapKey.self] : 0)
      height = max(height, size.height)
    }
    return CGSize(width: max(0, width), height: height)
  }

  func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
    var x = bounds.minX
    for (index, subview) in subviews.enumerated() {
      let size = subview.sizeThatFits(.unspecified)
      if index > 0 {
        x -= subview[AvatarOverlapKey.self]
      }
      subview.place(at: CGPoint(x: x, y: bounds.midY), anchor: .leading, proposal: ProposedViewSize(size))
      x += size.width
    }
  }
}

extension EnvironmentValues {
  @Entry var avatarSize: AvatarSize = .default
  @Entry var avatarGrouped = false
  @Entry var avatarIconSize: CGFloat = 20
}
```

- `swift/Components/TextVariant.swift`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/swiftui/Sources/EsuissUI/Components/TextVariant.swift)

4. Add the files to your app target.

**Jetpack Compose**

1. Set `minSdk` to 24 or higher and add the dependencies:

```kotlin title="build.gradle.kts"
implementation(platform("androidx.compose:compose-bom:2026.09.00"))
implementation("androidx.compose.foundation:foundation")
implementation("androidx.compose.ui:ui")
```

2. Copy the theme files every view uses:

- `kotlin/theme/Theme.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/theme/Theme.kt)

- `kotlin/theme/Tokens.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/theme/Tokens.kt)

3. Copy the source and every file it uses:

```kt title="kotlin/components/Avatar.kt"
package com.esuiss.ui.components

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.constrainHeight
import androidx.compose.ui.unit.constrainWidth
import androidx.compose.ui.unit.dp
import com.esuiss.ui.theme.EsuissTheme
import com.esuiss.ui.theme.Typography

enum class AvatarSize(
    val size: Dp,
    internal val iconSize: Dp,
    internal val badgeSize: Dp,
    internal val badgeIconSize: Dp,
    internal val countIconSize: Dp,
) {
    Sm(24.dp, 14.dp, 12.dp, 0.dp, 12.dp),
    Default(32.dp, 20.dp, 16.dp, 8.dp, 16.dp),
    Lg(40.dp, 24.dp, 18.dp, 10.dp, 20.dp),
    Xl(64.dp, 40.dp, 22.dp, 12.dp, 28.dp),
    ;

    internal val textStyle: TextStyle
        get() = when (this) {
            Sm -> Typography.xs
            Default -> Typography.xs
            Lg -> Typography.base
            Xl -> Typography.xl2
        }
}

private val LocalAvatarSize = staticCompositionLocalOf { AvatarSize.Default }

private val LocalAvatarGrouped = staticCompositionLocalOf { false }

@Composable
fun Avatar(
    modifier: Modifier = Modifier,
    size: AvatarSize = AvatarSize.Default,
    image: Painter? = null,
    contentDescription: String? = null,
    badge: (@Composable () -> Unit)? = null,
    fallback: (@Composable () -> Unit)? = null,
) {
    val colors = EsuissTheme.colors
    val grouped = LocalAvatarGrouped.current
    CompositionLocalProvider(LocalAvatarSize provides size, LocalAvatarGrouped provides false) {
        Box(modifier.size(size.size)) {
            Box(
                Modifier
                    .fillMaxSize()
                    .then(
                        if (grouped) {
                            Modifier.background(colors.background, CircleShape).padding(2.dp)
                        } else {
                            Modifier
                        },
                    )
                    .clip(CircleShape),
                contentAlignment = Alignment.Center,
            ) {
                fallback?.invoke()
                if (image != null) {
                    Image(
                        painter = image,
                        contentDescription = contentDescription,
                        modifier = Modifier.fillMaxSize(),
                        contentScale = ContentScale.Crop,
                    )
                }
            }
            if (badge != null) {
                Box(Modifier.align(Alignment.BottomEnd).offset(2.dp, 2.dp)) {
                    badge()
                }
            }
        }
    }
}

@Composable
fun AvatarFallback(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit,
) {
    val colors = EsuissTheme.colors
    val size = LocalAvatarSize.current
    val background = if (colors.isDark) {
        colors.mutedForeground.copy(alpha = colors.mutedForeground.alpha * 0.6f)
    } else {
        colors.mutedForeground
    }
    Box(
        modifier = modifier.fillMaxSize().background(background, CircleShape),
        contentAlignment = Alignment.Center,
    ) {
        CompositionLocalProvider(
            LocalContentStyle provides size.textStyle.copy(color = colors.primaryForeground, fontWeight = FontWeight.SemiBold),
            LocalContentColor provides colors.primaryForeground,
            LocalIconSize provides size.iconSize,
        ) {
            content()
        }
    }
}

@Composable
fun AvatarFallback(
    text: String,
    modifier: Modifier = Modifier,
) {
    AvatarFallback(modifier) {
        BasicText(text.uppercase(), style = LocalContentStyle.current, maxLines = 1)
    }
}

@Composable
fun AvatarBadge(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit = {},
) {
    val colors = EsuissTheme.colors
    val size = LocalAvatarSize.current
    Box(
        modifier = modifier
            .size(size.badgeSize)
            .background(colors.background, CircleShape)
            .padding(2.dp)
            .background(colors.primary, CircleShape),
        contentAlignment = Alignment.Center,
    ) {
        if (size != AvatarSize.Sm) {
            CompositionLocalProvider(
                LocalContentStyle provides Typography.xs.copy(color = colors.primaryForeground),
                LocalContentColor provides colors.primaryForeground,
                LocalIconSize provides size.badgeIconSize,
            ) {
                content()
            }
        }
    }
}

@Composable
fun AvatarGroup(
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit,
) {
    Layout(
        content = { CompositionLocalProvider(LocalAvatarGrouped provides true, content = content) },
        modifier = modifier,
    ) { measurables, constraints ->
        val loose = constraints.copy(minWidth = 0, minHeight = 0)
        val placeables = measurables.map { it.measure(loose) }
        val large = AvatarSize.Xl.size.roundToPx()
        val offsets = IntArray(placeables.size)
        var x = 0
        placeables.forEachIndexed { index, placeable ->
            if (index > 0) x -= if (placeable.height >= large) 16.dp.roundToPx() else 8.dp.roundToPx()
            offsets[index] = x
            x += placeable.width
        }
        val height = placeables.maxOfOrNull { it.height } ?: 0
        layout(constraints.constrainWidth(x.coerceAtLeast(0)), constraints.constrainHeight(height)) {
            placeables.forEachIndexed { index, placeable ->
                placeable.placeRelative(offsets[index], (height - placeable.height) / 2)
            }
        }
    }
}

@Composable
fun AvatarGroupCount(
    modifier: Modifier = Modifier,
    size: AvatarSize = AvatarSize.Default,
    content: @Composable () -> Unit,
) {
    val colors = EsuissTheme.colors
    Box(
        modifier = modifier
            .size(size.size)
            .background(colors.background, CircleShape)
            .padding(2.dp)
            .background(colors.muted, CircleShape),
        contentAlignment = Alignment.Center,
    ) {
        CompositionLocalProvider(
            LocalContentStyle provides size.textStyle.copy(color = colors.foreground, fontWeight = FontWeight.SemiBold),
            LocalContentColor provides colors.foreground,
            LocalIconSize provides size.countIconSize,
        ) {
            content()
        }
    }
}

@Composable
fun AvatarGroupCount(
    text: String,
    modifier: Modifier = Modifier,
    size: AvatarSize = AvatarSize.Default,
) {
    AvatarGroupCount(modifier, size) {
        BasicText(text, style = LocalContentStyle.current, maxLines = 1)
    }
}
```

- `kotlin/components/Content.kt`: [source](https://github.com/e-suiss/ui/blob/main/packages/mobile/kotlin/ui/src/main/kotlin/com/esuiss/ui/components/Content.kt)

4. Update the `com.esuiss.ui` package names to match your project.

## Usage

```tsx
import { Avatar, AvatarImage, AvatarFallback, AvatarBadge, AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar"
```

```tsx
<Avatar>
  <AvatarImage
    alt="Ada Lovelace"
    source={{ uri: "https://i.pravatar.cc/150?img=5" }}
  />
  <AvatarFallback>
    <Text>AL</Text>
  </AvatarFallback>
</Avatar>
```

Give `AvatarImage` a `source` and an `alt`. Put initials or an `Icon` in `AvatarFallback`; plain strings are wrapped in `Text`. Use `delay` on the fallback to avoid a flash on fast connections, and `onLoadingStatusChange` on the image to react to loading.

Set `size` on each `Avatar`, and pass the same `size` to `AvatarGroupCount`. On the `sm` size, the badge hides its children and shows a plain dot.

## Examples

### Fallback

Initials shown when there is no image.

![Preview](https://ui.suiss.app/previews/components-avatar--fallback.light.webp)

```tsx
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Text } from "@/components/ui/text"

export function AvatarFallbackExample() {
  return (
    <Avatar accessibilityLabel="Alan Turing">
      <AvatarFallback>
        <Text>AT</Text>
      </AvatarFallback>
    </Avatar>
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct AvatarFallbackExample: View {
  var body: some View {
    Avatar {
      AvatarFallback("AT")
    }
    .accessibilityLabel(Text("Alan Turing"))
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import com.esuiss.ui.components.Avatar
import com.esuiss.ui.components.AvatarFallback

@Composable
fun AvatarFallbackOnly() {
    Row {
        Avatar(
            modifier = Modifier.semantics { contentDescription = "Alan Turing" },
            fallback = { AvatarFallback("AT") },
        )
    }
}
```

### Sizes

The `sm`, `default`, `lg` and `xl` sizes.

![Preview](https://ui.suiss.app/previews/components-avatar--sizes.light.webp)

```tsx
import { View } from "react-native"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Text } from "@/components/ui/text"

export function AvatarSizesExample() {
  return (
    <View className="flex-row items-center gap-4">
      {(["sm", "default", "lg", "xl"] as const).map((size) => (
        <Avatar key={size} size={size}>
          <AvatarImage
            alt="Ada Lovelace"
            source={{ uri: "https://i.pravatar.cc/150?img=5" }}
          />
          <AvatarFallback>
            <Text>AL</Text>
          </AvatarFallback>
        </Avatar>
      ))}
    </View>
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct AvatarSizesExample: View {
  var body: some View {
    HStack(spacing: 16) {
      ForEach(AvatarSize.allCases, id: \.self) { size in
        Avatar(url: URL(string: "https://i.pravatar.cc/150?img=5"), initials: "AL", size: size)
          .accessibilityLabel(Text("Ada Lovelace"))
      }
    }
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import com.esuiss.ui.components.Avatar
import com.esuiss.ui.components.AvatarFallback
import com.esuiss.ui.components.AvatarSize
import com.esuiss.ui.theme.Palette

class AvatarPerson(val name: String, val initials: String, val tones: @Composable () -> List<Color>)

val avatarPeople = listOf(
    AvatarPerson("Ada Lovelace", "AL") { listOf(Palette.pink500, Palette.purple500) },
    AvatarPerson("Alan Turing", "AT") { listOf(Palette.teal500, Palette.blue500) },
    AvatarPerson("Grace Hopper", "GH") { listOf(Palette.orange500, Palette.red500) },
)

@Composable
fun AvatarPhoto(person: AvatarPerson, size: AvatarSize = AvatarSize.Default, badge: (@Composable () -> Unit)? = null) {
    val tones = person.tones()
    val photo = remember(tones) { BrushPainter(Brush.linearGradient(tones)) }
    Avatar(
        size = size,
        image = photo,
        contentDescription = person.name,
        badge = badge,
        fallback = { AvatarFallback(person.initials) },
    )
}

@Composable
fun AvatarSizes() {
    Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {
        AvatarSize.entries.forEach { size -> AvatarPhoto(avatarPeople[0], size) }
    }
}
```

### Group

Overlapping avatars in an `AvatarGroup` with a count.

![Preview](https://ui.suiss.app/previews/components-avatar--group.light.webp)

```tsx
import { Avatar, AvatarFallback, AvatarGroup, AvatarGroupCount, AvatarImage } from "@/components/ui/avatar"
import { Text } from "@/components/ui/text"

const people = [
  {
    name: "Ada Lovelace",
    initials: "AL",
    uri: "https://i.pravatar.cc/150?img=5",
  },
  {
    name: "Alan Turing",
    initials: "AT",
    uri: "https://i.pravatar.cc/150?img=12",
  },
  {
    name: "Grace Hopper",
    initials: "GH",
    uri: "https://i.pravatar.cc/150?img=47",
  },
]

export function AvatarGroupExample() {
  return (
    <AvatarGroup>
      {people.map((person) => (
        <Avatar key={person.name}>
          <AvatarImage alt={person.name} source={{ uri: person.uri }} />
          <AvatarFallback>
            <Text>{person.initials}</Text>
          </AvatarFallback>
        </Avatar>
      ))}
      <AvatarGroupCount accessibilityLabel="4 more">
        <Text>+4</Text>
      </AvatarGroupCount>
    </AvatarGroup>
  )
}
```

```swift
import EsuissUI
import SwiftUI

struct AvatarGroupExample: View {
  var body: some View {
    AvatarGroup {
      ForEach(avatarPeople, id: \.name) { person in
        Avatar(url: URL(string: person.uri), initials: person.initials)
          .accessibilityLabel(Text(verbatim: person.name))
      }
      AvatarGroupCount("+4")
        .accessibilityLabel(Text("4 more"))
    }
  }
}

struct AvatarPerson {
  let name: String
  let initials: String
  let uri: String
}

let avatarPeople = [
  AvatarPerson(name: "Ada Lovelace", initials: "AL", uri: "https://i.pravatar.cc/150?img=5"),
  AvatarPerson(name: "Alan Turing", initials: "AT", uri: "https://i.pravatar.cc/150?img=12"),
  AvatarPerson(name: "Grace Hopper", initials: "GH", uri: "https://i.pravatar.cc/150?img=47"),
]
```

```kotlin
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import com.esuiss.ui.components.Avatar
import com.esuiss.ui.components.AvatarFallback
import com.esuiss.ui.components.AvatarGroup
import com.esuiss.ui.components.AvatarGroupCount
import com.esuiss.ui.components.AvatarSize
import com.esuiss.ui.theme.Palette

class AvatarPerson(val name: String, val initials: String, val tones: @Composable () -> List<Color>)

val avatarPeople = listOf(
    AvatarPerson("Ada Lovelace", "AL") { listOf(Palette.pink500, Palette.purple500) },
    AvatarPerson("Alan Turing", "AT") { listOf(Palette.teal500, Palette.blue500) },
    AvatarPerson("Grace Hopper", "GH") { listOf(Palette.orange500, Palette.red500) },
)

@Composable
fun AvatarPhoto(person: AvatarPerson, size: AvatarSize = AvatarSize.Default, badge: (@Composable () -> Unit)? = null) {
    val tones = person.tones()
    val photo = remember(tones) { BrushPainter(Brush.linearGradient(tones)) }
    Avatar(
        size = size,
        image = photo,
        contentDescription = person.name,
        badge = badge,
        fallback = { AvatarFallback(person.initials) },
    )
}

@Composable
fun AvatarGroupStory() {
    Row {
        AvatarGroup {
            avatarPeople.forEach { person -> AvatarPhoto(person) }
            AvatarGroupCount("+4", Modifier.semantics { contentDescription = "4 more" })
        }
    }
}
```

### With badge

A check badge at each size.

![Preview](https://ui.suiss.app/previews/components-avatar--with-badge.light.webp)

```tsx
import { CheckIcon } from "phosphor-react-native"
import { View } from "react-native"
import { Avatar, AvatarBadge, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Icon } from "@/components/ui/icon"
import { Text } from "@/components/ui/text"

export function AvatarWithBadgeExample() {
  return (
    <View className="flex-row items-center gap-4">
      {(["sm", "default", "lg", "xl"] as const).map((size) => (
        <Avatar key={size} size={size}>
          <AvatarImage
            alt="Alan Turing"
            source={{ uri: "https://i.pravatar.cc/150?img=12" }}
          />
          <AvatarFallback>
            <Text>AT</Text>
          </AvatarFallback>
          <AvatarBadge>
            <Icon as={CheckIcon} weight="bold" />
          </AvatarBadge>
        </Avatar>
      ))}
    </View>
  )
}
```

```swift
import EsuissUI
import PhosphorSwift
import SwiftUI

struct AvatarWithBadgeExample: View {
  var body: some View {
    HStack(spacing: 16) {
      ForEach(AvatarSize.allCases, id: \.self) { size in
        Avatar(size: size) {
          AvatarFallback("AT")
          AvatarImage(url: URL(string: "https://i.pravatar.cc/150?img=12"))
          AvatarBadge(icon: Ph.check.bold)
        }
        .accessibilityLabel(Text("Alan Turing"))
      }
    }
  }
}
```

```kotlin
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BrushPainter
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.unit.dp
import com.adamglin.PhosphorIcons
import com.adamglin.phosphoricons.Bold
import com.adamglin.phosphoricons.bold.Check
import com.esuiss.ui.components.Avatar
import com.esuiss.ui.components.AvatarBadge
import com.esuiss.ui.components.AvatarFallback
import com.esuiss.ui.components.AvatarSize
import com.esuiss.ui.components.Icon
import com.esuiss.ui.theme.Palette

class AvatarPerson(val name: String, val initials: String, val tones: @Composable () -> List<Color>)

val avatarPeople = listOf(
    AvatarPerson("Ada Lovelace", "AL") { listOf(Palette.pink500, Palette.purple500) },
    AvatarPerson("Alan Turing", "AT") { listOf(Palette.teal500, Palette.blue500) },
    AvatarPerson("Grace Hopper", "GH") { listOf(Palette.orange500, Palette.red500) },
)

@Composable
fun AvatarPhoto(person: AvatarPerson, size: AvatarSize = AvatarSize.Default, badge: (@Composable () -> Unit)? = null) {
    val tones = person.tones()
    val photo = remember(tones) { BrushPainter(Brush.linearGradient(tones)) }
    Avatar(
        size = size,
        image = photo,
        contentDescription = person.name,
        badge = badge,
        fallback = { AvatarFallback(person.initials) },
    )
}

@Composable
fun AvatarWithBadge() {
    Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {
        AvatarSize.entries.forEach { size ->
            AvatarPhoto(avatarPeople[1], size) {
                AvatarBadge {
                    Icon(PhosphorIcons.Bold.Check, contentDescription = null)
                }
            }
        }
    }
}
```

## API Reference

### Avatar

Round container that sets the size.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `AvatarSize` | `"default"` | `sm`, `default`, `lg` or `xl`. |

Also accepts the props of `React.ComponentProps<typeof AvatarPrimitive.Root>`.

### AvatarImage

Image that appears once it has loaded.

Also accepts the props of `React.ComponentProps<typeof AvatarPrimitive.Image>`.

### AvatarFallback

Initials or icon shown while the image is missing.

Also accepts the props of `React.ComponentProps<typeof AvatarPrimitive.Fallback>`.

### AvatarBadge

Status dot in the bottom-end corner.

Also accepts the props of `React.ComponentProps<typeof View>`, `React.RefAttributes<View>`.

### AvatarGroup

Row that overlaps its avatars.

Also accepts the props of `React.ComponentProps<typeof View>`, `React.RefAttributes<View>`.

### AvatarGroupCount

Round counter for the remaining items in a group.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `AvatarSize` | `"default"` | Matches the size of the avatars in the group. |

Also accepts the props of `React.ComponentProps<typeof View>`, `React.RefAttributes<View>`.

## Accessibility

- `AvatarImage` uses `alt` as its `accessibilityLabel`.
- The image is hidden from screen readers until it has loaded.
- The badge has no label; describe the status in nearby text if it matters.

## Notes

- Uses `bg-muted-foreground`, `bg-primary`, `bg-muted` and `border-background` tokens; the fallback is softer in dark mode.
- Light and dark follow the system appearance.

