Avatar stack

Overlapping initials avatars for showing who is in a room, a project or a document. Four sizes, presence dots (online, away, busy, offline), name tips on hover and tints taken from the theme's chart colours. Past the limit, a "+N" button opens a list of everyone with their presence and role; it closes with Escape or an outside click. A standalone Avatar is exported too.

Tables & dataComponentTailwind v4

Source

"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

export type Presence = "online" | "away" | "busy" | "offline";
export type AvatarSize = "xs" | "sm" | "md" | "lg";

export interface Person {
  id?: string;
  name: string;
  initials?: string;
  presence?: Presence;
  /** Secondary line in the overflow list, e.g. a role. */
  detail?: string;
}

const SIZES: Record<AvatarSize, { box: string; dot: string; overlap: string; chip: string }> = {
  xs: { box: "size-6 text-[10px]", dot: "size-2", overlap: "-ml-1.5", chip: "h-6 min-w-6 px-1.5 text-[10px]" },
  sm: { box: "size-8 text-xs", dot: "size-2.5", overlap: "-ml-2", chip: "h-8 min-w-8 px-2 text-xs" },
  md: { box: "size-10 text-sm", dot: "size-3", overlap: "-ml-2.5", chip: "h-10 min-w-10 px-2.5 text-sm" },
  lg: { box: "size-12 text-base", dot: "size-3.5", overlap: "-ml-3", chip: "h-12 min-w-12 px-3 text-sm" },
};

const PRESENCE: Record<Presence, { label: string; dot: string }> = {
  online: { label: "Online", dot: "bg-emerald-500" },
  away: { label: "Away", dot: "bg-amber-400" },
  busy: { label: "Busy", dot: "bg-rose-500" },
  offline: { label: "Offline", dot: "bg-background shadow-[inset_0_0_0_2px_var(--muted-foreground)]" },
};

const TINTS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];

function tintOf(name: string) {
  let hash = 0;
  for (const char of name) hash = (hash * 31 + char.charCodeAt(0)) | 0;
  return TINTS[Math.abs(hash) % TINTS.length];
}

export function initialsOf(name: string) {
  const parts = name.trim().split(/\s+/);
  return ((parts[0]?.[0] || "") + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase();
}

export interface AvatarProps {
  person: Person;
  size?: AvatarSize;
  /** Draws a ring so overlapping avatars stay separate. */
  ringed?: boolean;
  /** Ring colour; match the surface behind the avatar (ring-card on cards). */
  ringClassName?: string;
  className?: string;
}

export function Avatar({ person, size = "md", ringed = false, ringClassName = "ring-background", className }: AvatarProps) {
  const tint = tintOf(person.name);
  const presence = person.presence ? PRESENCE[person.presence] : undefined;
  return (
    <span className={cn("relative inline-flex shrink-0", className)}>
      <span
        aria-hidden
        className={cn("grid place-items-center rounded-full font-semibold text-foreground select-none", SIZES[size].box, ringed && cn("ring-2", ringClassName))}
        style={{ background: `color-mix(in oklab, ${tint} 26%, var(--background))` }}
      >
        {person.initials || initialsOf(person.name)}
      </span>
      {presence && <span aria-hidden className={cn("absolute right-0 bottom-0 rounded-full ring-2", ringClassName, SIZES[size].dot, presence.dot)} />}
      <span className="sr-only">
        {person.name}
        {presence ? `, ${presence.label.toLowerCase()}` : ""}
      </span>
    </span>
  );
}

export interface AvatarStackProps {
  people: Person[];
  /** How many avatars to show before the "+N" button. */
  max?: number;
  size?: AvatarSize;
  /** Accessible name for the group, e.g. "Design review attendees". */
  label?: string;
  /** Ring colour around each avatar; match the surface (ring-card on cards). */
  ringClassName?: string;
  className?: string;
}

export function AvatarStack({ people, max = 4, size = "sm", label, ringClassName = "ring-background", className }: AvatarStackProps) {
  const [open, setOpen] = React.useState(false);
  const buttonRef = React.useRef<HTMLButtonElement>(null);
  const panelRef = React.useRef<HTMLDivElement>(null);
  const panelId = React.useId();
  const visible = people.length > max ? people.slice(0, max) : people;
  const hidden = people.length - visible.length;

  React.useEffect(() => {
    if (!open) return;
    panelRef.current?.focus();
    const onPointerDown = (event: PointerEvent) => {
      const target = event.target as Node;
      if (!panelRef.current?.contains(target) && !buttonRef.current?.contains(target)) setOpen(false);
    };
    document.addEventListener("pointerdown", onPointerDown);
    return () => document.removeEventListener("pointerdown", onPointerDown);
  }, [open]);

  return (
    <div className={cn("relative inline-flex items-center", className)}>
      <ul aria-label={label ?? `${people.length} people`} className="flex items-center">
        {visible.map((person, index) => {
          const presence = person.presence ? PRESENCE[person.presence] : undefined;
          return (
            <li
              key={person.id ?? person.name}
              // Earlier avatars sit on top so every presence dot stays visible.
              style={{ "--z": visible.length - index } as React.CSSProperties}
              className={cn(
                "group relative z-[var(--z)] hover:z-50 motion-safe:transition-transform motion-safe:duration-150 motion-safe:hover:-translate-y-0.5",
                index > 0 && SIZES[size].overlap,
              )}
            >
              <Avatar person={person} size={size} ringed ringClassName={ringClassName} />
              <span
                aria-hidden
                className="pointer-events-none absolute bottom-full left-1/2 z-20 mb-2 -translate-x-1/2 rounded-md bg-primary px-2 py-1 text-xs font-medium whitespace-nowrap text-primary-foreground opacity-0 shadow-md transition-opacity group-hover:opacity-100"
              >
                {person.name}
                {presence && <span className="font-normal opacity-70"> · {presence.label}</span>}
              </span>
            </li>
          );
        })}
      </ul>
      {hidden > 0 && (
        <>
          <button
            ref={buttonRef}
            type="button"
            aria-expanded={open}
            aria-controls={panelId}
            aria-label={`Show all ${people.length} people`}
            onClick={() => setOpen((value) => !value)}
            className={cn(
              "relative inline-flex items-center justify-center rounded-full bg-muted font-semibold text-muted-foreground ring-2 outline-none transition-colors tabular-nums hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring",
              ringClassName,
              SIZES[size].chip,
              SIZES[size].overlap,
            )}
          >
            +{hidden}
          </button>
          {open && (
            <div
              ref={panelRef}
              id={panelId}
              tabIndex={-1}
              role="dialog"
              aria-label={label ?? "People"}
              onKeyDown={(event) => {
                if (event.key === "Escape") {
                  setOpen(false);
                  buttonRef.current?.focus();
                }
              }}
              className="absolute top-full left-0 z-30 mt-2 w-64 rounded-lg border bg-popover p-1 text-popover-foreground shadow-lg outline-none"
            >
              <p className="px-2 pt-1.5 pb-1 text-xs font-medium text-muted-foreground">{people.length} people</p>
              <ul className="max-h-64 overflow-y-auto">
                {people.map((person) => (
                  <li key={person.id ?? person.name} className="flex items-center gap-2.5 rounded-md px-2 py-1.5">
                    <Avatar person={person} size="sm" />
                    <span className="min-w-0 flex-1">
                      <span aria-hidden className="block truncate text-sm font-medium">{person.name}</span>
                      {person.detail && <span className="block truncate text-xs text-muted-foreground">{person.detail}</span>}
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </>
      )}
    </div>
  );
}