Avatar
129 lines · 1 file · MIT
A picture, or initials in a tint of the person’s own when there is none, and a stacked group.
+2
6 membersimport { useEffect, useRef, useState, type ReactNode } from "react";
import { cn } from "./cn";
/** The tints an initials face can take, all from the tokens so both themes work. */
const TINTS = ["--accent", "--accent-2", "--butter", "--danger"] as const;
/** "Ada Lovelace" is "AL", "ada@example.com" is "A", nothing is "?". */
export function initialsOf(name: string): string {
const words = name
.trim()
.replace(/@.*$/, "")
.split(/[\s._-]+/)
.filter(Boolean);
if (words.length === 0) return "?";
const first = words[0][0];
const last = words.length > 1 ? words[words.length - 1][0] : "";
return (first + last).toUpperCase();
}
/** The same name always gets the same tint, so a person keeps their colour. */
function tintOf(name: string): string {
let hash = 0;
for (const ch of name) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;
return TINTS[hash % TINTS.length];
}
/**
* A person's picture, or their initials when there is none or it fails to
* load (removed since the list was fetched): never a broken image.
*/
export function Avatar({
name,
src,
size = 32,
className,
}: {
name: string;
src?: string | null;
/** Pixels, square. */
size?: number;
className?: string;
}) {
const [failed, setFailed] = useState<string | null>(null);
const img = useRef<HTMLImageElement>(null);
// A server-rendered image can fail before React attaches onError, so ask
// the element once on mount whether it already did.
useEffect(() => {
if (img.current?.complete && img.current.naturalWidth === 0) setFailed(src ?? null);
}, [src]);
const showImage = !!src && src !== failed;
const box = cn("shrink-0 rounded-full", className);
if (showImage)
return (
<img
ref={img}
src={src}
onError={() => setFailed(src)}
alt={name}
width={size}
height={size}
className={cn(box, "object-cover image-outline")}
/>
);
const tint = tintOf(name);
return (
<span
role="img"
aria-label={name}
style={{
width: size,
height: size,
fontSize: Math.max(10, Math.round(size * 0.38)),
backgroundColor: `color-mix(in oklab, var(${tint}) 18%, var(--surface))`,
boxShadow: `inset 0 0 0 1px color-mix(in oklab, var(${tint}) 30%, transparent)`,
}}
className={cn(box, "inline-grid place-items-center font-semibold text-text select-none")}
>
<span aria-hidden>{initialsOf(name)}</span>
</span>
);
}
/**
* Overlapping avatars, the first on top. Each wears a ring in the colour of
* what it sits on, so the overlap reads as a cut. More than `max` collapses
* into a "+3" that says how many are left.
*/
export function AvatarGroup({
people,
max = 4,
size = 28,
className,
}: {
people: { name: string; src?: string | null }[];
max?: number;
size?: number;
className?: string;
}) {
const shown = people.slice(0, max);
const rest = people.length - shown.length;
const ring = "rounded-full ring-2 ring-surface";
const items: ReactNode[] = shown.map((p, i) => (
<span key={`${p.name}-${i}`} className={ring} style={{ zIndex: shown.length - i }}>
<Avatar name={p.name} src={p.src} size={size} className="block" />
</span>
));
return (
<div
role="group"
aria-label={`${people.length} people`}
className={cn("flex items-center [&>*+*]:-ml-2", className)}
>
{items}
{rest > 0 && (
<span
className={cn(
ring,
"tnum inline-grid place-items-center bg-surface-2 text-xs font-semibold text-muted",
)}
style={{ width: size, height: size }}
title={`${rest} more`}
>
+{rest}
</span>
)}
</div>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/avatar- Category
- Display
- Files
- avatar.tsx