Activity feed
A list of team events grouped under sticky day headings (Today, Yesterday, then dates). Each event shows an initials avatar tinted from the theme's chart colours, an icon for its type, the actor, verb and target, optional detail such as a quoted comment, and a relative time that updates every minute. A load-more button shows a loading state while your async loader runs.
Source
"use client";
import * as React from "react";
import {
CircleCheck,
GitMerge,
LoaderCircle,
MessageSquare,
Plus,
Rocket,
TriangleAlert,
Upload,
UserPlus,
type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
export type ActivityType = "comment" | "deploy" | "merge" | "invite" | "upload" | "alert" | "resolve" | "create";
export interface ActivityEvent {
id: string;
actor: { name: string; initials?: string };
type: ActivityType;
/** Verb phrase after the actor, e.g. "merged". */
action: string;
/** The object acted on, e.g. "Pricing page v2". */
target?: string;
timestamp: Date | string | number;
/** Optional detail: a quoted comment, a file, a diff summary. */
body?: React.ReactNode;
}
export interface ActivityFeedProps {
items: ActivityEvent[];
hasMore?: boolean;
/** Called by "Load more". Return a promise to show a loading state until it settles. */
onLoadMore?: () => void | Promise<void>;
loadMoreLabel?: string;
emptyMessage?: string;
/** Background behind the sticky day headings. Match the surface the feed sits on. */
surfaceClassName?: string;
className?: string;
}
const ICONS: Record<ActivityType, { icon: LucideIcon; tone: string }> = {
comment: { icon: MessageSquare, tone: "text-muted-foreground" },
deploy: { icon: Rocket, tone: "text-sky-600 dark:text-sky-400" },
merge: { icon: GitMerge, tone: "text-violet-600 dark:text-violet-400" },
invite: { icon: UserPlus, tone: "text-muted-foreground" },
upload: { icon: Upload, tone: "text-muted-foreground" },
alert: { icon: TriangleAlert, tone: "text-amber-600 dark:text-amber-400" },
resolve: { icon: CircleCheck, tone: "text-emerald-600 dark:text-emerald-400" },
create: { icon: Plus, tone: "text-muted-foreground" },
};
const TINTS = ["var(--chart-1)", "var(--chart-2)", "var(--chart-3)", "var(--chart-4)", "var(--chart-5)"];
function initialsOf(name: string) {
const parts = name.trim().split(/\s+/);
return ((parts[0]?.[0] || "") + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase();
}
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];
}
const DAY = 86_400_000;
const startOfDay = (time: number) => new Date(time).setHours(0, 0, 0, 0);
function dayLabel(time: number, now: number) {
const diff = Math.round((startOfDay(now) - startOfDay(time)) / DAY);
if (diff === 0) return "Today";
if (diff === 1) return "Yesterday";
return new Intl.DateTimeFormat(undefined, {
weekday: "long",
month: "short",
day: "numeric",
year: new Date(time).getFullYear() === new Date(now).getFullYear() ? undefined : "numeric",
}).format(time);
}
const relative = new Intl.RelativeTimeFormat(undefined, { numeric: "auto", style: "short" });
function timeLabel(time: number, now: number) {
const seconds = Math.round((now - time) / 1000);
if (startOfDay(time) === startOfDay(now)) {
if (seconds < 45) return "Just now";
if (seconds < 3600) return relative.format(-Math.round(seconds / 60), "minute");
return relative.format(-Math.round(seconds / 3600), "hour");
}
return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(time);
}
/* Re-renders every minute so relative times stay current. */
function useNow(interval = 60_000) {
const [now, setNow] = React.useState(() => Date.now());
React.useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), interval);
return () => clearInterval(timer);
}, [interval]);
return now;
}
export function ActivityAvatar({ name, initials, type }: { name: string; initials?: string; type?: ActivityType }) {
const tint = tintOf(name);
const meta = type ? ICONS[type] : undefined;
return (
<span className="relative inline-flex shrink-0">
<span
aria-hidden
className="grid size-9 place-items-center rounded-full text-xs font-semibold text-foreground"
style={{ background: `color-mix(in oklab, ${tint} 24%, var(--card))`, boxShadow: `inset 0 0 0 1px color-mix(in oklab, ${tint} 30%, transparent)` }}
>
{initials || initialsOf(name)}
</span>
{meta && (
<span aria-hidden className="absolute -right-1 -bottom-1 grid size-[18px] place-items-center rounded-full border bg-card">
<meta.icon className={cn("size-2.5", meta.tone)} strokeWidth={2.5} />
</span>
)}
</span>
);
}
export function ActivityFeed({
items,
hasMore = false,
onLoadMore,
loadMoreLabel = "Load more",
emptyMessage = "No activity yet",
surfaceClassName = "bg-card",
className,
}: ActivityFeedProps) {
const now = useNow();
const [loading, setLoading] = React.useState(false);
const headingId = React.useId();
const groups = React.useMemo(() => {
const sorted = [...items].sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
const map = new Map<number, ActivityEvent[]>();
for (const item of sorted) {
const key = startOfDay(new Date(item.timestamp).getTime());
map.set(key, [...(map.get(key) || []), item]);
}
return [...map.entries()];
}, [items]);
async function loadMore() {
if (!onLoadMore || loading) return;
setLoading(true);
try {
await onLoadMore();
} finally {
setLoading(false);
}
}
if (!items.length) {
return <p className={cn("py-10 text-center text-sm text-muted-foreground", className)}>{emptyMessage}</p>;
}
return (
<div className={className} aria-busy={loading}>
{groups.map(([day, events], groupIndex) => (
<section key={day} aria-labelledby={`${headingId}-${groupIndex}`}>
<h3
id={`${headingId}-${groupIndex}`}
className={cn("sticky top-0 z-10 py-2 text-xs font-medium text-muted-foreground", surfaceClassName)}
>
{dayLabel(day, now)}
</h3>
<ol>
{events.map((event, index) => {
const time = new Date(event.timestamp).getTime();
return (
<li key={event.id} className="relative flex gap-3 pt-2 pb-4">
{index < events.length - 1 && <span aria-hidden className="absolute top-12 bottom-0 left-[17.5px] w-px bg-border" />}
<ActivityAvatar name={event.actor.name} initials={event.actor.initials} type={event.type} />
<div className="min-w-0 flex-1 pt-0.5">
<div className="flex items-baseline justify-between gap-3">
<p className="min-w-0 text-sm leading-5">
<span className="font-medium">{event.actor.name}</span>{" "}
<span className="text-muted-foreground">{event.action}</span>
{event.target && (
<>
{" "}
<span className="font-medium">{event.target}</span>
</>
)}
</p>
<time
dateTime={new Date(time).toISOString()}
title={new Date(time).toLocaleString()}
suppressHydrationWarning
className="shrink-0 text-xs whitespace-nowrap text-muted-foreground tabular-nums"
>
{timeLabel(time, now)}
</time>
</div>
{event.body && <div className="mt-2 text-sm">{event.body}</div>}
</div>
</li>
);
})}
</ol>
</section>
))}
{onLoadMore && (
<div className="pt-2">
{hasMore ? (
<button
type="button"
onClick={loadMore}
disabled={loading}
className="inline-flex h-9 w-full items-center justify-center gap-2 rounded-md border bg-background text-sm font-medium outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-70"
>
{loading && <LoaderCircle aria-hidden className="size-4 motion-safe:animate-spin" />}
{loading ? "Loading…" : loadMoreLabel}
</button>
) : (
<p className="py-2 text-center text-xs text-muted-foreground">No older activity</p>
)}
</div>
)}
<p aria-live="polite" className="sr-only">
{loading ? "Loading older activity" : ""}
</p>
</div>
);
}
