# Avatar

Shows who someone is with their photo or initials, and whether they are around right now.

Status: Stable. Group: Feedback.

## When to use

- Next to a name in messages, comments and the task owner column.
- A stack of the people on a project with AvatarGroup, where the count matters more than each name.
- Presence in chat: online, away or offline as a small dot.

## When not to use

- It stands for a project or a file, not a person. Use an icon or the project colour swatch instead.
- The state needs a word, such as Out of office. Use Badge instead.

## Scenarios

### Task owner

Each row of the task list starts with the owner as a small Avatar and their name next to it, so the face is a shortcut and the name is the label.

### Project team

The project header shows an AvatarGroup with four people and a +3 circle. The group is named Q3 launch team for screen readers.

## Do and avoid

- Do: Show the name next to the avatar where there is room.
- Avoid: Make people learn faces to tell teammates apart.
- Do: Let initials stand in when a photo is missing or fails.
- Avoid: Show a generic silhouette for everyone without a photo.

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` |  | Required. The accessible name and the source of the initials. |
| `src` | `string` |  | Photo URL. If it fails to load, the initials show instead. |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | 24, 32 or 40 px. |
| `status` | `'online' \| 'away' \| 'offline'` |  | A presence dot at the bottom right; the word is added to the accessible name. |
| `...rest` | `HTMLAttributes<HTMLSpanElement>` |  | Any span attribute. Wrap it in a link or button to make it interactive. |
| `people` | `AvatarPerson[]` |  | AvatarGroup: the people to stack, as name and optional src. |
| `max` | `number` | `4` | AvatarGroup: avatars shown before the +N circle. |
| `ring` | `'surface' \| 'sunken'` | `'surface'` | AvatarGroup: the colour of the 2 px ring between overlapping circles. Match the surface behind the group: sunken inside a well or a row. |
| `label` | `string` |  | AvatarGroup: names the group for assistive tech, such as Q3 launch team. |

## Anatomy

1. Circle (`data-part="root"`): Radius full, neutral-soft fill behind the photo or initials.
2. Initials (`data-part="initials"`): First letters of the first and last word in neutral-strong at weight 600, sized with the circle.
3. Status dot (`data-part="status"`): success (online), warning (away) or line-control (offline), with a 2 px surface ring to cut it out.

## Motion

| Interaction | Property | Duration | Easing | From the keyboard |
| --- | --- | --- | --- | --- |
| Status change | background-color | quick | out | Same, colour only. |
| Group hover (mouse) | translate: each circle 6 px further than the last, 20 ms apart, then back in reverse | gentle | spring | None: the group is not focusable. Touch keeps it folded. |

## Accessibility

| Keys | Action |
| --- | --- |
| None | Not interactive. For a profile link, wrap it in a link whose name is the person. |

- role img with the name as its label, plus the status word when there is one (Ana Ribeiro, online).
- The photo has an empty alt and the initials are aria-hidden, so the name is read once.
- AvatarGroup is a named group; the +N circle reads as 3 more.
- The status dot is never the only signal: the word is in the name.

## Code

### Avatar.tsx

```tsx
'use client'
import { useState, type CSSProperties, type HTMLAttributes, type Ref } from 'react'

// Nacre Avatar: a person as a photo or their initials, with an optional presence dot; AvatarGroup stacks a team.
// React plus Tailwind classes only; needs nacre-theme.css. Motion: the status dot changes colour quick 160 out. On a
// mouse hover over an AvatarGroup the stack fans out: each circle slides 6 px further than the one before it (translate,
// gentle 360 on the spring curve, 20 ms apart), so the overlapped initials become readable, and folds back when the
// pointer leaves; the transitions retarget, so a quick in and out never jumps. The group keeps its size. Touch, reduced
// motion and [data-nacre-motion="off"]: it stays folded.

export type AvatarSize = 'sm' | 'md' | 'lg'
export type AvatarStatus = 'online' | 'away' | 'offline'
export type AvatarPerson = { name: string; src?: string }

export type AvatarProps = Omit<HTMLAttributes<HTMLSpanElement>, 'children'> &
  AvatarPerson & { size?: AvatarSize; status?: AvatarStatus; ref?: Ref<HTMLSpanElement> }

export type AvatarRing = 'surface' | 'sunken'
export type AvatarGroupProps = { label: string; people: AvatarPerson[]; max?: number; size?: AvatarSize; /** The colour of the 2 px ring that separates overlapping circles: match the surface the group sits on. */ ring?: AvatarRing; className?: string }

// 24, 32 and 40 px; the initials scale with the circle.
const boxes: Record<AvatarSize, string> = { sm: 'size-6 text-[0.625rem]', md: 'size-8 text-caption', lg: 'size-10 text-label' }
// AvatarGroup overlap: 4 px at md and lg, 2 px at sm (spacing token steps), so the 2 px ring of the next circle
// never covers the second letter of the initials.
const overlaps: Record<AvatarSize, string> = { sm: '-space-x-0.5', md: '-space-x-1', lg: '-space-x-1' }
// The fan: circle i moves i * 6 px toward the end, 20 ms after the one before it; folding back runs in reverse order.
const fan =
  'transition-[translate] duration-(--nx-dur-gentle) ease-spring [transition-delay:calc((var(--n)_-_var(--i))*20ms)] ' +
  'motion-safe:group-hover/avatars:translate-x-[calc(var(--i)*6px)] motion-safe:group-hover/avatars:[transition-delay:calc(var(--i)*20ms)] ' +
  'rtl:motion-safe:group-hover/avatars:translate-x-[calc(var(--i)*-6px)]'
// The ring matches the surface behind the group: a panel is surface, a well or row is sunken.
const rings: Record<AvatarRing, string> = { surface: 'ring-surface', sunken: 'ring-sunken' }
const at = (i: number, n: number) => ({ '--i': i, '--n': n - 1 }) as CSSProperties
// Initials get a tint from the name (the same four pastels as Tile), so a person always keeps the same colour.
const fills = [
  'bg-linear-to-b from-tint-lime to-tint-lime-wash text-tint-lime-ink',
  'bg-linear-to-b from-tint-pink to-tint-pink-wash text-tint-pink-ink',
  'bg-linear-to-b from-tint-blue to-tint-blue-wash text-tint-blue-ink',
  'bg-linear-to-b from-tint-violet to-tint-violet-wash text-tint-violet-ink',
]
const fillFor = (name: string) => fills[[...name].reduce((n, c) => n + c.charCodeAt(0), 0) % fills.length]
const dotSizes: Record<AvatarSize, string> = { sm: 'size-2', md: 'size-2.5', lg: 'size-3' }
const statusFill: Record<AvatarStatus, string> = { online: 'bg-success', away: 'bg-warning', offline: 'bg-line-control' }

/** First letter of the first and the last word: Ana Ribeiro is AR, Chen is C. */
export function initials(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean)
  if (words.length === 0) return ''
  return (words[0][0] + (words.length > 1 ? words[words.length - 1][0] : '')).toUpperCase()
}

export function Avatar({ name, src, size = 'md', status, className = '', ref, ...rest }: AvatarProps) {
  // A photo that fails to load falls back to the initials; a new src gets a new try.
  const [failed, setFailed] = useState<string | undefined>(undefined)
  const photo = src !== undefined && failed !== src
  return (
    <span
      ref={ref}
      role="img"
      aria-label={status ? `${name}, ${status}` : name}
      data-part="root"
      className={`relative inline-flex shrink-0 rounded-full ${boxes[size]} ${className}`}
      {...rest}
    >
      <span className={`flex size-full items-center justify-center overflow-hidden rounded-full ${fillFor(name)} leading-[1] font-[600]`}>
        {photo ? (
          // eslint-disable-next-line @next/next/no-img-element -- a copyable component, not tied to next/image
          <img src={src} alt="" onError={() => setFailed(src)} className="size-full object-cover" />
        ) : (
          <span data-part="initials" aria-hidden="true">{initials(name)}</span>
        )}
      </span>
      {status && (
        <span
          data-part="status"
          aria-hidden="true"
          className={`absolute end-0 bottom-0 rounded-full ring-2 ring-surface transition-colors duration-(--nx-dur-quick) ease-out ${dotSizes[size]} ${statusFill[status]}`}
        />
      )}
    </span>
  )
}

/** A team as overlapping avatars; past max, one more circle counts the rest. */
export function AvatarGroup({ label, people, max = 4, size = 'md', ring = 'surface', className = '' }: AvatarGroupProps) {
  const shown = people.slice(0, max)
  const more = people.length - shown.length
  const n = shown.length + (more > 0 ? 1 : 0)
  return (
    <div role="group" aria-label={label} data-part="group" className={`group/avatars flex items-center ${overlaps[size]} ${className}`}>
      {shown.map((p, i) => (
        <Avatar key={i} name={p.name} src={p.src} size={size} style={at(i, n)} className={`ring-2 ${rings[ring]} ${fan}`} />
      ))}
      {more > 0 && (
        <span
          role="img"
          aria-label={`${more} more`}
          data-part="more"
          style={at(shown.length, n)}
          className={`inline-flex shrink-0 items-center justify-center rounded-full bg-neutral-soft font-[600] text-neutral-strong ring-2 ${rings[ring]} ${fan} ${boxes[size]}`}
        >
          {`+${more}`}
        </span>
      )}
    </div>
  )
}
```

## HTML

The default example as plain HTML, for any stack. Needs nacre-theme.css.

```html
<span role="img" aria-label="Ana Ribeiro, online" data-part="root" class="relative inline-flex shrink-0 rounded-full size-8 text-caption ">
  <span class="flex size-full items-center justify-center overflow-hidden rounded-full bg-linear-to-b from-tint-lime to-tint-lime-wash text-tint-lime-ink leading-[1] font-[600]">
    <span data-part="initials" aria-hidden="true">AR</span>
  </span>
  <span data-part="status" aria-hidden="true" class="absolute end-0 bottom-0 rounded-full ring-2 ring-surface transition-colors duration-(--nx-dur-quick) ease-out size-2.5 bg-success"></span>
</span>
```

## Related

- [Badge](https://enxm.me/services/design-systems/nacre/components/badge)
- [Table](https://enxm.me/services/design-systems/nacre/components/table)
