Avatars

Avatar

Loads over a real request with real latency. Initials sit underneath the image from the first frame, so a 500 costs nothing but a fade.

  • image
  • fallback
  • initials
  • decode

Preview

ALAda LovelaceAda
GHGrace HopperGrace
ATAlan TuringAlan
RPRadia PerlmanRadia

Usage

<Avatar src={user.avatarUrl} name={user.name} size={56} status="online" />
"use client";

import { useCallback, useState } from "react";
import { cn } from "@/lib/cn";
import { hueFrom, initialsFrom } from "./initials";
import { Skeleton } from "../skeleton/Skeleton";

export type AvatarStatus = "online" | "away" | "busy" | "offline";
export type AvatarLoadingStyle = "skeleton" | "blur" | "tint" | "none";
export type AvatarShape = "circle" | "squircle";

export interface AvatarProps {
  src?: string | null;
  name: string;
  size?: number;
  shape?: AvatarShape;
  /** How the gap before the image decodes is filled. */
  loadingStyle?: AvatarLoadingStyle;
  status?: AvatarStatus;
  /** Accent ring around the avatar (stories / active speaker). */
  ring?: boolean;
  className?: string;
}

const statusColor: Record<AvatarStatus, string> = {
  online: "var(--color-positive)",
  away: "#f5a524",
  busy: "var(--color-negative)",
  offline: "var(--color-ink-3)",
};

export function Avatar({
  src,
  name,
  size = 44,
  shape = "circle",
  loadingStyle = "blur",
  status,
  ring = false,
  className,
}: AvatarProps) {
  const [state, setState] = useState<"loading" | "ready" | "error">(src ? "loading" : "error");
  const [seenSrc, setSeenSrc] = useState(src);

  // A new `src` restarts the cycle. Adjusting state during render (rather than
  // in an effect) means the placeholder never flashes the previous image's state.
  if (src !== seenSrc) {
    setSeenSrc(src);
    setState(src ? "loading" : "error");
  }

  // Images already in the browser cache are `complete` before React attaches
  // `onLoad`, which would otherwise leave the placeholder up forever.
  const bindImage = useCallback((el: HTMLImageElement | null) => {
    if (el?.complete && el.naturalWidth > 0) setState("ready");
  }, []);

  const hue = hueFrom(name);
  const radius = shape === "circle" ? "9999px" : `${size * 0.3}px`;
  const showPlaceholder = state === "loading" && loadingStyle !== "none";

  return (
    <span
      className={cn("relative inline-block shrink-0 align-middle", className)}
      style={{ width: size, height: size }}
    >
      <span
        className="relative block h-full w-full overflow-hidden"
        style={{
          borderRadius: radius,
          boxShadow: ring
            ? `0 0 0 2px var(--color-canvas), 0 0 0 4px var(--color-accent)`
            : `inset 0 0 0 1px color-mix(in oklab, var(--color-ink) 10%, transparent)`,
        }}
      >
        {/* Fallback layer: initials on a name-derived tint. Always rendered so
            a failed image reveals it with no extra work. */}
        <span
          className="absolute inset-0 flex items-center justify-center font-semibold"
          style={{
            background: `linear-gradient(140deg, hsl(${hue} 70% 62%), hsl(${(hue + 48) % 360} 70% 48%))`,
            color: "white",
            fontSize: size * 0.38,
            letterSpacing: "-0.02em",
          }}
        >
          {initialsFrom(name)}
        </span>

        {showPlaceholder && loadingStyle === "skeleton" && (
          <Skeleton shape="rect" className="absolute inset-0 h-full w-full" style={{ borderRadius: radius }} />
        )}
        {showPlaceholder && loadingStyle === "tint" && (
          <span className="absolute inset-0 animate-breathe" style={{ background: `hsl(${hue} 40% 50% / .55)` }} />
        )}

        {src && (
          // Intentionally a plain <img>: this component is meant to be copied
          // into any React project, framework image loaders included or not.
          // eslint-disable-next-line @next/next/no-img-element
          <img
            ref={bindImage}
            src={src}
            alt={name}
            width={size}
            height={size}
            decoding="async"
            onLoad={() => setState("ready")}
            onError={() => setState("error")}
            className="absolute inset-0 h-full w-full object-cover"
            style={{
              opacity: state === "ready" ? 1 : 0,
              filter: state === "ready" ? "blur(0px)" : "blur(12px)",
              transform: state === "ready" ? "scale(1)" : "scale(1.08)",
              transition:
                "opacity 420ms var(--ease-out-quint), filter 420ms var(--ease-out-quint), transform 520ms var(--ease-out-quint)",
            }}
          />
        )}
      </span>

      {status && (
        <span
          className="absolute rounded-full"
          style={{
            width: Math.max(8, size * 0.26),
            height: Math.max(8, size * 0.26),
            right: shape === "circle" ? size * 0.02 : -size * 0.04,
            bottom: shape === "circle" ? size * 0.02 : -size * 0.04,
            background: statusColor[status],
            boxShadow: "0 0 0 2px var(--color-canvas)",
          }}
          aria-label={status}
        />
      )}
    </span>
  );
}

export default Avatar;