Skip to content
Organisms

Notification center

A bell and a panel of updates by day.

Primitive

Installation

Primitive
  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/, installs radix-ui, react-dom@base-ui/react, react-dom and the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.

    $ pnpm dlx asta-ui@latest add notification-center --radix

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/notification-center.json

  2. Or install the package

    Don’t want the file? Import from asta-uiasta-ui/base and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui radix-ui @base-ui/react
    import { NotificationCenter } from "asta-ui";
    import { NotificationCenter } from "asta-ui/base";
  3. Or copy it by hand

    Install radix-ui react-dom@base-ui/react react-dom, then copy these files. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
    import { Avatar } from "@/components/kit/avatar";
    import { Popover, type PopoverAlign } from "@/components/kit/popover";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    const CURVE = "cubic-bezier(.16,1,.3,1)";
    
    export interface NotificationEntry {
      id: string;
      title: string;
      body?: string;
      time: Date;
      read?: boolean;
      /** Who did it. Shows their avatar; without it a neutral bell is shown. */
      actor?: { name: string; src?: string };
    }
    
    export interface NotificationCenterProps {
      /** Controlled list. Pass with `onNotificationsChange`. */
      notifications?: NotificationEntry[];
      defaultNotifications?: NotificationEntry[];
      onNotificationsChange?: (notifications: NotificationEntry[]) => void;
      /** Called when a notification is clicked. It's marked read first. */
      onOpenItem?: (notification: NotificationEntry) => void;
      /** Override "now" for grouping and relative times. */
      now?: Date;
      locale?: string;
      align?: PopoverAlign;
      label?: string;
      className?: string;
    }
    
    const KEYFRAMES = `@keyframes kit-nc-ring { 0%, 100% { transform: rotate(0) } 15% { transform: rotate(14deg) } 30% { transform: rotate(-11deg) } 45% { transform: rotate(7deg) } 60% { transform: rotate(-4deg) } 75% { transform: rotate(2deg) } }
    @keyframes kit-nc-count { from { opacity: 0; transform: translateY(70%) } }
    @keyframes kit-nc-badge { from { opacity: 0; transform: scale(.4) } }
    @keyframes kit-nc-in { from { opacity: 0; transform: translateY(6px) } }
    @media (prefers-reduced-motion: reduce) { .kit-nc, .kit-nc * { animation: none !important; transition-duration: 0s !important; } }`;
    
    const DAY = 86_400_000;
    const day0 = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
    
    function BellIcon({ className }: { className?: string }) {
      return (
        <svg viewBox="0 0 24 24" className={className} fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <path d="M6.5 10a5.5 5.5 0 0 1 11 0v3.5l1.5 3h-14l1.5-3Z" />
          <path d="M10 19.5a2 2 0 0 0 4 0" />
        </svg>
      );
    }
    
    /* ---------- the panel (mounted while open) ---------- */
    
    function Panel({
      items,
      update,
      onOpenItem,
      now,
      locale,
      label,
    }: {
      items: NotificationEntry[];
      update: (next: NotificationEntry[]) => void;
      onOpenItem?: (n: NotificationEntry) => void;
      now: Date;
      locale?: string;
      label: string;
    }) {
      const [tab, setTab] = useState<"all" | "unread">("all");
      // What was unread when the Unread tab opened stays listed, so rows don't vanish as you read them.
      const [snap, setSnap] = useState<Set<string>>(() => new Set());
      const [status, setStatus] = useState("");
      const list = useRef<HTMLUListElement>(null);
      const tabsId = useId();
    
      const unread = items.filter((n) => !n.read).length;
      const shown = tab === "all" ? items : items.filter((n) => !n.read || snap.has(n.id));
    
      const fmt = useMemo(
        () => ({
          date: new Intl.DateTimeFormat(locale, { weekday: "short", month: "short", day: "numeric" }),
          clock: new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit" }),
        }),
        [locale],
      );
    
      const groups = useMemo(() => {
        const today = day0(now);
        const out: { label: string; items: NotificationEntry[] }[] = [];
        for (const n of [...shown].sort((a, b) => b.time.getTime() - a.time.getTime())) {
          const d = day0(n.time);
          const label = d === today ? "Today" : d === today - DAY ? "Yesterday" : fmt.date.format(n.time);
          const g = out[out.length - 1];
          if (g?.label === label) g.items.push(n);
          else out.push({ label, items: [n] });
        }
        return out;
      }, [shown, now, fmt]);
    
      const ago = (t: Date) => {
        const s = Math.max(0, (now.getTime() - t.getTime()) / 1000);
        if (s < 60) return "now";
        if (s < 3600) return `${Math.floor(s / 60)}m`;
        if (day0(t) === day0(now)) return `${Math.floor(s / 3600)}h`;
        return fmt.clock.format(t);
      };
    
      const markRead = (ids: string[]) => {
        const set = new Set(ids);
        if (!items.some((n) => set.has(n.id) && !n.read)) return;
        update(items.map((n) => (set.has(n.id) ? { ...n, read: true } : n)));
      };
    
      const pickTab = (t: "all" | "unread") => {
        if (t === "unread") setSnap(new Set(items.filter((n) => !n.read).map((n) => n.id)));
        setTab(t);
      };
    
      const onListKey = (e: KeyboardEvent) => {
        if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(e.key)) return;
        const rows = [...(list.current?.querySelectorAll<HTMLElement>("[data-nc-item]") ?? [])];
        if (!rows.length) return;
        e.preventDefault();
        const i = rows.indexOf(document.activeElement as HTMLElement);
        const next = e.key === "Home" ? 0 : e.key === "End" ? rows.length - 1 : Math.min(rows.length - 1, Math.max(0, i + (e.key === "ArrowDown" ? 1 : -1)));
        rows[next]?.focus();
      };
    
      return (
        <div className="flex max-h-[min(520px,calc(100vh-96px))] flex-col">
          <p className="sr-only" aria-live="polite">
            {status}
          </p>
          <div className="flex items-center justify-between gap-3 px-4 pb-2 pt-3.5">
            <h3 className="text-[14px] font-medium tracking-[-0.01em] text-ink">{label}</h3>
            <button
              type="button"
              onClick={() => {
                markRead(items.map((n) => n.id));
                setStatus("All notifications marked as read.");
              }}
              aria-disabled={!unread || undefined}
              className={cx(
                "rounded-md px-2 py-1 text-[12.5px] outline-none transition-[color,opacity] duration-200 focus-visible:ring-2 focus-visible:ring-brand/50",
                unread ? "text-brand hover:bg-[color-mix(in_srgb,var(--color-brand)_8%,transparent)]" : "pointer-events-none text-mute opacity-50",
              )}
            >
              Mark all read
            </button>
          </div>
    
          <div role="tablist" aria-label="Filter" className="relative mx-4 grid grid-cols-2 rounded-lg bg-paper-2 p-0.5">
            <span
              aria-hidden
              className="absolute bottom-0.5 left-0.5 top-0.5 w-[calc(50%-2px)] rounded-[7px] bg-paper shadow-[0_1px_2px_rgb(0_0_0/0.08),inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_7%,transparent)] transition-transform duration-500"
              style={{ transform: tab === "unread" ? "translateX(100%)" : "none", transitionTimingFunction: CURVE }}
            />
            {(["all", "unread"] as const).map((t) => (
              <button
                key={t}
                type="button"
                role="tab"
                id={`${tabsId}-${t}`}
                aria-selected={tab === t}
                aria-controls={`${tabsId}-panel`}
                tabIndex={tab === t ? 0 : -1}
                onClick={() => pickTab(t)}
                onKeyDown={(e) => {
                  if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
                    e.preventDefault();
                    const other = t === "all" ? "unread" : "all";
                    pickTab(other);
                    (e.currentTarget.parentElement?.querySelector(`#${CSS.escape(`${tabsId}-${other}`)}`) as HTMLElement | null)?.focus();
                  }
                }}
                className={cx(
                  "relative z-10 flex h-7 items-center justify-center gap-1.5 rounded-[7px] text-[12.5px] outline-none transition-colors duration-300 focus-visible:ring-2 focus-visible:ring-brand/50",
                  tab === t ? "text-ink" : "text-mute hover:text-ink",
                )}
              >
                {t === "all" ? "All" : "Unread"}
                {t === "unread" && unread > 0 && <span className="text-[11.5px] tabular-nums text-mute">{unread}</span>}
              </button>
            ))}
          </div>
    
          <div id={`${tabsId}-panel`} role="tabpanel" aria-labelledby={`${tabsId}-${tab}`} className="mt-2 min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2 [scrollbar-width:thin]">
            {groups.length === 0 ? (
              <div key={tab} className="flex flex-col items-center px-6 py-12 text-center" style={{ animation: `kit-nc-in .4s ${CURVE}` }}>
                <span className="grid h-11 w-11 place-items-center rounded-full bg-paper-2 text-mute">
                  <BellIcon className="h-5 w-5" />
                </span>
                <p className="mt-4 text-[14px] font-medium text-ink">{tab === "unread" ? "You're all caught up" : "No notifications yet"}</p>
                <p className="mt-1 text-[12.5px] text-mute">{tab === "unread" ? "New activity will show up here." : "When something happens, you'll see it here."}</p>
              </div>
            ) : (
              <ul ref={list} key={tab} onKeyDown={onListKey} aria-label={tab === "all" ? "All notifications" : "Unread notifications"}>
                {groups.map((g, gi) => (
                  <li key={g.label} style={{ animation: `kit-nc-in .4s ${CURVE} ${gi * 40}ms both` }}>
                    <p className="px-4 pb-1 pt-3 text-[11.5px] font-medium text-mute">{g.label}</p>
                    <ul>
                      {g.items.map((n) => (
                        <li key={n.id} className="group relative px-1.5">
                          <button
                            type="button"
                            data-nc-item
                            onClick={() => {
                              markRead([n.id]);
                              onOpenItem?.(n.read ? n : { ...n, read: true });
                            }}
                            className="flex w-full gap-3 rounded-[10px] py-2.5 pl-2.5 pr-9 text-left outline-none transition-colors duration-200 hover:bg-paper-2 focus-visible:bg-paper-2 focus-visible:ring-2 focus-visible:ring-brand/50"
                          >
                            {n.actor ? (
                              <Avatar name={n.actor.name} src={n.actor.src} size="sm" />
                            ) : (
                              <span aria-hidden className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-paper-2 text-mute">
                                <BellIcon className="h-4 w-4" />
                              </span>
                            )}
                            <span className="min-w-0 flex-1">
                              <span className={cx("block text-[13px] leading-snug transition-colors duration-300", n.read ? "text-ink-2" : "text-ink")}>
                                {!n.read && <span className="sr-only">Unread: </span>}
                                {n.title}
                              </span>
                              {n.body && <span className="mt-0.5 line-clamp-2 block text-[12.5px] leading-snug text-mute">{n.body}</span>}
                              <span className="mt-1 block text-[11.5px] tabular-nums text-mute">{ago(n.time)}</span>
                            </span>
                          </button>
                          {/* The dot doubles as "mark as read". It fades out once read. */}
                          <button
                            type="button"
                            aria-label={`Mark "${n.title}" as read`}
                            tabIndex={n.read ? -1 : 0}
                            aria-hidden={n.read || undefined}
                            onClick={(e) => {
                              markRead([n.id]);
                              setStatus("Marked as read.");
                              (e.currentTarget.previousElementSibling as HTMLElement | null)?.focus();
                            }}
                            className={cx(
                              "absolute right-3 top-3.5 grid h-6 w-6 place-items-center rounded-full outline-none transition-[opacity,transform] duration-500 focus-visible:ring-2 focus-visible:ring-brand/50",
                              n.read ? "pointer-events-none scale-50 opacity-0" : "opacity-100 hover:scale-110",
                            )}
                            style={{ transitionTimingFunction: CURVE }}
                          >
                            <span className="h-2 w-2 rounded-full bg-brand" />
                          </button>
                        </li>
                      ))}
                    </ul>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      );
    }
    
    /* ---------- bell + popover ---------- */
    
    /**
     * A bell with an unread count that opens a notification panel. Switch between All and Unread, read
     * them grouped by day, and mark one or all as read: the blue dot fades out. The bell rings when new
     * ones arrive. Arrow keys move through the list.
     */
    export function NotificationCenter({
      notifications,
      defaultNotifications = [],
      onNotificationsChange,
      onOpenItem,
      now: nowProp,
      locale,
      align = "end",
      label = "Notifications",
      className,
    }: NotificationCenterProps) {
      const [inner, setInner] = useState(defaultNotifications);
      const items = notifications ?? inner;
      const unread = items.filter((n) => !n.read).length;
      const [opened, setOpened] = useState(() => new Date());
    
      // Ring the bell when the unread count goes up.
      const [prev, setPrev] = useState(unread);
      const [rings, setRings] = useState(0);
      if (prev !== unread) {
        if (unread > prev) setRings((r) => r + 1);
        setPrev(unread);
      }
    
      const update = (next: NotificationEntry[]) => {
        if (notifications === undefined) setInner(next);
        onNotificationsChange?.(next);
      };
    
      return (
        <span className="kit-nc inline-flex">
          <style href="asta-notification-center" precedence="asta">{KEYFRAMES}</style>
          <Popover
            align={align}
            label={label}
            className="w-[380px] !p-0"
            onOpenChange={(o) => {
              if (o) setOpened(new Date());
            }}
            trigger={(props, open) => (
              <button
                type="button"
                {...props}
                aria-label={unread ? `${label}, ${unread} unread` : label}
                className={cx(
                  "relative grid h-9 w-9 place-items-center rounded-lg text-ink-2 outline-none transition-colors duration-200 hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50",
                  open && "bg-paper-2 text-ink",
                  className,
                )}
              >
                <span key={rings} className="grid origin-[50%_15%] place-items-center" style={rings ? { animation: `kit-nc-ring .9s ${CURVE}` } : undefined}>
                  <BellIcon className="h-[18px] w-[18px]" />
                </span>
                {unread > 0 && (
                  <span
                    aria-hidden
                    className="absolute -right-0.5 -top-0.5 flex h-[18px] min-w-[18px] items-center justify-center overflow-hidden rounded-full bg-brand px-1 text-[10.5px] font-medium tabular-nums text-on-brand shadow-[0_0_0_2px_var(--color-paper)]"
                    style={{ animation: `kit-nc-badge .35s ${CURVE}` }}
                  >
                    <span key={unread} className="block" style={{ animation: `kit-nc-count .35s ${CURVE}` }}>
                      {unread > 99 ? "99+" : unread}
                    </span>
                  </span>
                )}
              </button>
            )}
          >
            <Panel items={items} update={update} onOpenItem={onOpenItem} now={nowProp ?? opened} locale={locale} label={label} />
          </Popover>
        </span>
      );
    }
    
    export default NotificationCenter;
    
    "use client";
    
    import { useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
    import { Avatar } from "@/components/kit/base/avatar";
    import { Popover, type PopoverAlign } from "@/components/kit/popover";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    const CURVE = "cubic-bezier(.16,1,.3,1)";
    
    export interface NotificationEntry {
      id: string;
      title: string;
      body?: string;
      time: Date;
      read?: boolean;
      /** Who did it. Shows their avatar; without it a neutral bell is shown. */
      actor?: { name: string; src?: string };
    }
    
    export interface NotificationCenterProps {
      /** Controlled list. Pass with `onNotificationsChange`. */
      notifications?: NotificationEntry[];
      defaultNotifications?: NotificationEntry[];
      onNotificationsChange?: (notifications: NotificationEntry[]) => void;
      /** Called when a notification is clicked. It's marked read first. */
      onOpenItem?: (notification: NotificationEntry) => void;
      /** Override "now" for grouping and relative times. */
      now?: Date;
      locale?: string;
      align?: PopoverAlign;
      label?: string;
      className?: string;
    }
    
    const KEYFRAMES = `@keyframes kit-nc-ring { 0%, 100% { transform: rotate(0) } 15% { transform: rotate(14deg) } 30% { transform: rotate(-11deg) } 45% { transform: rotate(7deg) } 60% { transform: rotate(-4deg) } 75% { transform: rotate(2deg) } }
    @keyframes kit-nc-count { from { opacity: 0; transform: translateY(70%) } }
    @keyframes kit-nc-badge { from { opacity: 0; transform: scale(.4) } }
    @keyframes kit-nc-in { from { opacity: 0; transform: translateY(6px) } }
    @media (prefers-reduced-motion: reduce) { .kit-nc, .kit-nc * { animation: none !important; transition-duration: 0s !important; } }`;
    
    const DAY = 86_400_000;
    const day0 = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
    
    function BellIcon({ className }: { className?: string }) {
      return (
        <svg viewBox="0 0 24 24" className={className} fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
          <path d="M6.5 10a5.5 5.5 0 0 1 11 0v3.5l1.5 3h-14l1.5-3Z" />
          <path d="M10 19.5a2 2 0 0 0 4 0" />
        </svg>
      );
    }
    
    /* ---------- the panel (mounted while open) ---------- */
    
    function Panel({
      items,
      update,
      onOpenItem,
      now,
      locale,
      label,
    }: {
      items: NotificationEntry[];
      update: (next: NotificationEntry[]) => void;
      onOpenItem?: (n: NotificationEntry) => void;
      now: Date;
      locale?: string;
      label: string;
    }) {
      const [tab, setTab] = useState<"all" | "unread">("all");
      // What was unread when the Unread tab opened stays listed, so rows don't vanish as you read them.
      const [snap, setSnap] = useState<Set<string>>(() => new Set());
      const [status, setStatus] = useState("");
      const list = useRef<HTMLUListElement>(null);
      const tabsId = useId();
    
      const unread = items.filter((n) => !n.read).length;
      const shown = tab === "all" ? items : items.filter((n) => !n.read || snap.has(n.id));
    
      const fmt = useMemo(
        () => ({
          date: new Intl.DateTimeFormat(locale, { weekday: "short", month: "short", day: "numeric" }),
          clock: new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit" }),
        }),
        [locale],
      );
    
      const groups = useMemo(() => {
        const today = day0(now);
        const out: { label: string; items: NotificationEntry[] }[] = [];
        for (const n of [...shown].sort((a, b) => b.time.getTime() - a.time.getTime())) {
          const d = day0(n.time);
          const label = d === today ? "Today" : d === today - DAY ? "Yesterday" : fmt.date.format(n.time);
          const g = out[out.length - 1];
          if (g?.label === label) g.items.push(n);
          else out.push({ label, items: [n] });
        }
        return out;
      }, [shown, now, fmt]);
    
      const ago = (t: Date) => {
        const s = Math.max(0, (now.getTime() - t.getTime()) / 1000);
        if (s < 60) return "now";
        if (s < 3600) return `${Math.floor(s / 60)}m`;
        if (day0(t) === day0(now)) return `${Math.floor(s / 3600)}h`;
        return fmt.clock.format(t);
      };
    
      const markRead = (ids: string[]) => {
        const set = new Set(ids);
        if (!items.some((n) => set.has(n.id) && !n.read)) return;
        update(items.map((n) => (set.has(n.id) ? { ...n, read: true } : n)));
      };
    
      const pickTab = (t: "all" | "unread") => {
        if (t === "unread") setSnap(new Set(items.filter((n) => !n.read).map((n) => n.id)));
        setTab(t);
      };
    
      const onListKey = (e: KeyboardEvent) => {
        if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(e.key)) return;
        const rows = [...(list.current?.querySelectorAll<HTMLElement>("[data-nc-item]") ?? [])];
        if (!rows.length) return;
        e.preventDefault();
        const i = rows.indexOf(document.activeElement as HTMLElement);
        const next = e.key === "Home" ? 0 : e.key === "End" ? rows.length - 1 : Math.min(rows.length - 1, Math.max(0, i + (e.key === "ArrowDown" ? 1 : -1)));
        rows[next]?.focus();
      };
    
      return (
        <div className="flex max-h-[min(520px,calc(100vh-96px))] flex-col">
          <p className="sr-only" aria-live="polite">
            {status}
          </p>
          <div className="flex items-center justify-between gap-3 px-4 pb-2 pt-3.5">
            <h3 className="text-[14px] font-medium tracking-[-0.01em] text-ink">{label}</h3>
            <button
              type="button"
              onClick={() => {
                markRead(items.map((n) => n.id));
                setStatus("All notifications marked as read.");
              }}
              aria-disabled={!unread || undefined}
              className={cx(
                "rounded-md px-2 py-1 text-[12.5px] outline-none transition-[color,opacity] duration-200 focus-visible:ring-2 focus-visible:ring-brand/50",
                unread ? "text-brand hover:bg-[color-mix(in_srgb,var(--color-brand)_8%,transparent)]" : "pointer-events-none text-mute opacity-50",
              )}
            >
              Mark all read
            </button>
          </div>
    
          <div role="tablist" aria-label="Filter" className="relative mx-4 grid grid-cols-2 rounded-lg bg-paper-2 p-0.5">
            <span
              aria-hidden
              className="absolute bottom-0.5 left-0.5 top-0.5 w-[calc(50%-2px)] rounded-[7px] bg-paper shadow-[0_1px_2px_rgb(0_0_0/0.08),inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_7%,transparent)] transition-transform duration-500"
              style={{ transform: tab === "unread" ? "translateX(100%)" : "none", transitionTimingFunction: CURVE }}
            />
            {(["all", "unread"] as const).map((t) => (
              <button
                key={t}
                type="button"
                role="tab"
                id={`${tabsId}-${t}`}
                aria-selected={tab === t}
                aria-controls={`${tabsId}-panel`}
                tabIndex={tab === t ? 0 : -1}
                onClick={() => pickTab(t)}
                onKeyDown={(e) => {
                  if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
                    e.preventDefault();
                    const other = t === "all" ? "unread" : "all";
                    pickTab(other);
                    (e.currentTarget.parentElement?.querySelector(`#${CSS.escape(`${tabsId}-${other}`)}`) as HTMLElement | null)?.focus();
                  }
                }}
                className={cx(
                  "relative z-10 flex h-7 items-center justify-center gap-1.5 rounded-[7px] text-[12.5px] outline-none transition-colors duration-300 focus-visible:ring-2 focus-visible:ring-brand/50",
                  tab === t ? "text-ink" : "text-mute hover:text-ink",
                )}
              >
                {t === "all" ? "All" : "Unread"}
                {t === "unread" && unread > 0 && <span className="text-[11.5px] tabular-nums text-mute">{unread}</span>}
              </button>
            ))}
          </div>
    
          <div id={`${tabsId}-panel`} role="tabpanel" aria-labelledby={`${tabsId}-${tab}`} className="mt-2 min-h-0 flex-1 overflow-y-auto overscroll-contain pb-2 [scrollbar-width:thin]">
            {groups.length === 0 ? (
              <div key={tab} className="flex flex-col items-center px-6 py-12 text-center" style={{ animation: `kit-nc-in .4s ${CURVE}` }}>
                <span className="grid h-11 w-11 place-items-center rounded-full bg-paper-2 text-mute">
                  <BellIcon className="h-5 w-5" />
                </span>
                <p className="mt-4 text-[14px] font-medium text-ink">{tab === "unread" ? "You're all caught up" : "No notifications yet"}</p>
                <p className="mt-1 text-[12.5px] text-mute">{tab === "unread" ? "New activity will show up here." : "When something happens, you'll see it here."}</p>
              </div>
            ) : (
              <ul ref={list} key={tab} onKeyDown={onListKey} aria-label={tab === "all" ? "All notifications" : "Unread notifications"}>
                {groups.map((g, gi) => (
                  <li key={g.label} style={{ animation: `kit-nc-in .4s ${CURVE} ${gi * 40}ms both` }}>
                    <p className="px-4 pb-1 pt-3 text-[11.5px] font-medium text-mute">{g.label}</p>
                    <ul>
                      {g.items.map((n) => (
                        <li key={n.id} className="group relative px-1.5">
                          <button
                            type="button"
                            data-nc-item
                            onClick={() => {
                              markRead([n.id]);
                              onOpenItem?.(n.read ? n : { ...n, read: true });
                            }}
                            className="flex w-full gap-3 rounded-[10px] py-2.5 pl-2.5 pr-9 text-left outline-none transition-colors duration-200 hover:bg-paper-2 focus-visible:bg-paper-2 focus-visible:ring-2 focus-visible:ring-brand/50"
                          >
                            {n.actor ? (
                              <Avatar name={n.actor.name} src={n.actor.src} size="sm" />
                            ) : (
                              <span aria-hidden className="grid h-8 w-8 shrink-0 place-items-center rounded-full bg-paper-2 text-mute">
                                <BellIcon className="h-4 w-4" />
                              </span>
                            )}
                            <span className="min-w-0 flex-1">
                              <span className={cx("block text-[13px] leading-snug transition-colors duration-300", n.read ? "text-ink-2" : "text-ink")}>
                                {!n.read && <span className="sr-only">Unread: </span>}
                                {n.title}
                              </span>
                              {n.body && <span className="mt-0.5 line-clamp-2 block text-[12.5px] leading-snug text-mute">{n.body}</span>}
                              <span className="mt-1 block text-[11.5px] tabular-nums text-mute">{ago(n.time)}</span>
                            </span>
                          </button>
                          {/* The dot doubles as "mark as read". It fades out once read. */}
                          <button
                            type="button"
                            aria-label={`Mark "${n.title}" as read`}
                            tabIndex={n.read ? -1 : 0}
                            aria-hidden={n.read || undefined}
                            onClick={(e) => {
                              markRead([n.id]);
                              setStatus("Marked as read.");
                              (e.currentTarget.previousElementSibling as HTMLElement | null)?.focus();
                            }}
                            className={cx(
                              "absolute right-3 top-3.5 grid h-6 w-6 place-items-center rounded-full outline-none transition-[opacity,transform] duration-500 focus-visible:ring-2 focus-visible:ring-brand/50",
                              n.read ? "pointer-events-none scale-50 opacity-0" : "opacity-100 hover:scale-110",
                            )}
                            style={{ transitionTimingFunction: CURVE }}
                          >
                            <span className="h-2 w-2 rounded-full bg-brand" />
                          </button>
                        </li>
                      ))}
                    </ul>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      );
    }
    
    /* ---------- bell + popover ---------- */
    
    /**
     * A bell with an unread count that opens a notification panel. Switch between All and Unread, read
     * them grouped by day, and mark one or all as read: the blue dot fades out. The bell rings when new
     * ones arrive. Arrow keys move through the list.
     */
    export function NotificationCenter({
      notifications,
      defaultNotifications = [],
      onNotificationsChange,
      onOpenItem,
      now: nowProp,
      locale,
      align = "end",
      label = "Notifications",
      className,
    }: NotificationCenterProps) {
      const [inner, setInner] = useState(defaultNotifications);
      const items = notifications ?? inner;
      const unread = items.filter((n) => !n.read).length;
      const [opened, setOpened] = useState(() => new Date());
    
      // Ring the bell when the unread count goes up.
      const [prev, setPrev] = useState(unread);
      const [rings, setRings] = useState(0);
      if (prev !== unread) {
        if (unread > prev) setRings((r) => r + 1);
        setPrev(unread);
      }
    
      const update = (next: NotificationEntry[]) => {
        if (notifications === undefined) setInner(next);
        onNotificationsChange?.(next);
      };
    
      return (
        <span className="kit-nc inline-flex">
          <style href="asta-notification-center" precedence="asta">{KEYFRAMES}</style>
          <Popover
            align={align}
            label={label}
            className="w-[380px] !p-0"
            onOpenChange={(o) => {
              if (o) setOpened(new Date());
            }}
            trigger={(props, open) => (
              <button
                type="button"
                {...props}
                aria-label={unread ? `${label}, ${unread} unread` : label}
                className={cx(
                  "relative grid h-9 w-9 place-items-center rounded-lg text-ink-2 outline-none transition-colors duration-200 hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50",
                  open && "bg-paper-2 text-ink",
                  className,
                )}
              >
                <span key={rings} className="grid origin-[50%_15%] place-items-center" style={rings ? { animation: `kit-nc-ring .9s ${CURVE}` } : undefined}>
                  <BellIcon className="h-[18px] w-[18px]" />
                </span>
                {unread > 0 && (
                  <span
                    aria-hidden
                    className="absolute -right-0.5 -top-0.5 flex h-[18px] min-w-[18px] items-center justify-center overflow-hidden rounded-full bg-brand px-1 text-[10.5px] font-medium tabular-nums text-on-brand shadow-[0_0_0_2px_var(--color-paper)]"
                    style={{ animation: `kit-nc-badge .35s ${CURVE}` }}
                  >
                    <span key={unread} className="block" style={{ animation: `kit-nc-count .35s ${CURVE}` }}>
                      {unread > 99 ? "99+" : unread}
                    </span>
                  </span>
                )}
              </button>
            )}
          >
            <Panel items={items} update={update} onOpenItem={onOpenItem} now={nowProp ?? opened} locale={locale} label={label} />
          </Popover>
        </span>
      );
    }
    
    export default NotificationCenter;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Notification center component to my project.
    
    A bell and a panel of updates by day.
    It includes: bell, unread count, tabs, grouped by day, mark read, empty state.
    
    Install it (Radix build):
    ```sh
    pnpm dlx asta-ui@latest add notification-center --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/notification-center.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { NotificationCenter, type NotificationEntry } from "@/components/astabyte/notification-center";
    ```
    
    Usage example and props: https://ui.astabyte.com/notification-center
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package).
    - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
    Add the Astabyte UI Notification center component to my project.
    
    A bell and a panel of updates by day.
    It includes: bell, unread count, tabs, grouped by day, mark read, empty state.
    
    Install it (Base UI build):
    ```sh
    pnpm dlx asta-ui@latest add notification-center
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/notification-center.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { NotificationCenter, type NotificationEntry } from "@/components/astabyte/notification-center";
    ```
    
    Usage example and props: https://ui.astabyte.com/notification-center
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package).
    - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js to open the panel, switch tabs and mark items read; persisting reads needs a server endpoint. -->
    <div style="display:flex;justify-content:flex-end;max-width:520px;min-height:40px"><span class="asta-nc asta-notification-center" data-asta-nc data-label="Notifications"><button type="button" class="asta-notification-center-bell" data-asta-nc-trigger aria-haspopup="dialog" aria-expanded="false" aria-controls="notifications" aria-label="Notifications, 3 unread"><span class="asta-notification-center-bell-icon asta-nc-ring"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 8a5 5 0 0 1 10 0c0 4 1.5 5.5 1.5 5.5h-13S5 12 5 8Z"/><path d="M8.5 16.5a1.6 1.6 0 0 0 3 0"/></svg></span><span aria-hidden="true" class="asta-notification-center-badge" data-asta-nc-badge><span data-asta-nc-count>3</span></span></button>
    <div id="notifications" role="dialog" aria-label="Notifications" class="asta-notification-center-panel" data-asta-nc-panel data-tab="all" hidden><div class="asta-notification-center-inner"><p class="asta-sr-only" aria-live="polite" data-asta-nc-status></p><div class="asta-notification-center-header"><h3 class="asta-notification-center-title">Notifications</h3><button type="button" class="asta-notification-center-all" data-asta-nc-all>Mark all read</button></div><div role="tablist" aria-label="Filter" class="asta-notification-center-tabs"><span aria-hidden="true" class="asta-nc-thumb asta-notification-center-thumb"></span><button type="button" role="tab" class="asta-notification-center-tab" data-asta-nc-tab="all" aria-selected="true" tabindex="0">All</button><button type="button" role="tab" class="asta-notification-center-tab" data-asta-nc-tab="unread" aria-selected="false" tabindex="-1">Unread <span class="asta-notification-center-tabcount" data-asta-nc-tabcount>3</span></button></div><div role="tabpanel" aria-label="Notifications" class="asta-notification-center-body"><ul data-asta-nc-list aria-label="All notifications">
    <li data-asta-nc-group><p class="asta-notification-center-day">Today</p><ul><li class="asta-notification-center-entry" data-asta-nc-entry="n1"><button type="button" class="asta-notification-center-item" data-asta-nc-item><span class="asta-avatar asta-avatar-sm " role="img" aria-label="Maya Chen"><span class="asta-avatar-face asta-avatar-soft">MC</span></span><span class="asta-notification-center-text"><span class="asta-notification-center-item-title"><span class="asta-notification-center-unread">Unread: </span>Maya Chen commented on Pricing page</span><span class="asta-notification-center-item-body">Can we try the yearly toggle on the left?</span><span class="asta-notification-center-time">4m</span></span></button><button type="button" class="asta-notification-center-dot" data-asta-nc-dot aria-label="Mark “Maya Chen commented on Pricing page” as read"><span></span></button></li><li class="asta-notification-center-entry" data-asta-nc-entry="n2"><button type="button" class="asta-notification-center-item" data-asta-nc-item><span aria-hidden="true" class="asta-notification-center-icon"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 8a5 5 0 0 1 10 0c0 4 1.5 5.5 1.5 5.5h-13S5 12 5 8Z"/><path d="M8.5 16.5a1.6 1.6 0 0 0 3 0"/></svg></span><span class="asta-notification-center-text"><span class="asta-notification-center-item-title"><span class="asta-notification-center-unread">Unread: </span>Deploy finished</span><span class="asta-notification-center-item-body">astabyte.com is live with build 1042.</span><span class="asta-notification-center-time">52m</span></span></button><button type="button" class="asta-notification-center-dot" data-asta-nc-dot aria-label="Mark “Deploy finished” as read"><span></span></button></li><li class="asta-notification-center-entry" data-asta-nc-entry="n3" data-read><button type="button" class="asta-notification-center-item" data-asta-nc-item><span class="asta-avatar asta-avatar-sm " role="img" aria-label="Leo Park"><span class="asta-avatar-face asta-avatar-soft">LP</span></span><span class="asta-notification-center-text"><span class="asta-notification-center-item-title"><span class="asta-notification-center-unread">Unread: </span>Leo Park assigned you a task</span><span class="asta-notification-center-item-body">Audit image sizes</span><span class="asta-notification-center-time">3h</span></span></button><button type="button" class="asta-notification-center-dot" data-asta-nc-dot aria-label="Mark “Leo Park assigned you a task” as read" tabindex="-1" aria-hidden="true"><span></span></button></li></ul></li>
    <li data-asta-nc-group><p class="asta-notification-center-day">Yesterday</p><ul><li class="asta-notification-center-entry" data-asta-nc-entry="n4"><button type="button" class="asta-notification-center-item" data-asta-nc-item><span aria-hidden="true" class="asta-notification-center-icon"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 8a5 5 0 0 1 10 0c0 4 1.5 5.5 1.5 5.5h-13S5 12 5 8Z"/><path d="M8.5 16.5a1.6 1.6 0 0 0 3 0"/></svg></span><span class="asta-notification-center-text"><span class="asta-notification-center-item-title"><span class="asta-notification-center-unread">Unread: </span>Invoice INV-1044 was paid</span><span class="asta-notification-center-time">1:17 PM</span></span></button><button type="button" class="asta-notification-center-dot" data-asta-nc-dot aria-label="Mark “Invoice INV-1044 was paid” as read"><span></span></button></li><li class="asta-notification-center-entry" data-asta-nc-entry="n5" data-read><button type="button" class="asta-notification-center-item" data-asta-nc-item><span class="asta-avatar asta-avatar-sm " role="img" aria-label="Ana Ruiz"><span class="asta-avatar-face asta-avatar-soft">AR</span></span><span class="asta-notification-center-text"><span class="asta-notification-center-item-title"><span class="asta-notification-center-unread">Unread: </span>Ana Ruiz shared Brand guide.pdf</span><span class="asta-notification-center-time">9:17 AM</span></span></button><button type="button" class="asta-notification-center-dot" data-asta-nc-dot aria-label="Mark “Ana Ruiz shared Brand guide.pdf” as read" tabindex="-1" aria-hidden="true"><span></span></button></li></ul></li></ul>
    <div class="asta-notification-center-empty" data-asta-nc-empty hidden><span class="asta-notification-center-empty-icon"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 8a5 5 0 0 1 10 0c0 4 1.5 5.5 1.5 5.5h-13S5 12 5 8Z"/><path d="M8.5 16.5a1.6 1.6 0 0 0 3 0"/></svg></span><p class="asta-notification-center-empty-title" data-asta-nc-empty-title data-unread="You're all caught up">No notifications yet</p><p class="asta-notification-center-empty-text" data-asta-nc-empty-text data-unread="New activity will show up here.">When something happens, you'll see it here.</p></div></div></div></div></span></div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { NotificationCenter, type NotificationEntry } from "@/components/astabyte/notification-center";

const ago = (min: number) => new Date(Date.now() - min * 60_000);

const START: NotificationEntry[] = [
  { id: "n1", title: "Sekar Ayu commented on Pricing page v3", body: "Can we try the annual toggle above the cards?", time: ago(4), actor: { name: "Sekar Ayu" } },
  { id: "n2", title: "Dimas Arya assigned you Invoice PDF layout", time: ago(52), actor: { name: "Dimas Arya" } },
  { id: "n3", title: "Export finished", body: "orders-november.csv is ready to download.", time: ago(180) },
  { id: "n4", title: "Rani Pratama mentioned you in Weekly sync", body: "Let's ship the onboarding email on Thursday.", time: ago(60 * 26), actor: { name: "Rani Pratama" }, read: true },
  { id: "n5", title: "Your trial ends in 7 days", time: ago(60 * 30), read: true },
  { id: "n6", title: "Bayu Nugroho joined the workspace", time: ago(60 * 74), actor: { name: "Bayu Nugroho" }, read: true },
];

const INCOMING: Omit<NotificationEntry, "id" | "time">[] = [
  { title: "Laras Wening replied to your comment", body: "Agreed, the toggle reads better up top.", actor: { name: "Laras Wening" } },
  { title: "Deploy finished", body: "Production is on build 2.4.1." },
  { title: "Dimas Arya moved Audit empty states to Done", actor: { name: "Dimas Arya" } },
];

export default function NotificationCenterDemo() {
  const [items, setItems] = useState(START);
  const [n, setN] = useState(0);

  const simulate = () => {
    setItems((all) => [{ ...INCOMING[n % INCOMING.length], id: `new-${n}`, time: new Date() }, ...all]);
    setN((x) => x + 1);
  };

  return (
    <div className="flex min-h-[420px] w-full flex-col items-center justify-center gap-6 p-4 sm:p-8">
      <div className="flex w-full max-w-[560px] items-center justify-between rounded-[12px] bg-paper-2 py-2 pl-4 pr-2">
        <p className="text-[13.5px] font-medium tracking-[-0.01em] text-ink">Workspace</p>
        <NotificationCenter notifications={items} onNotificationsChange={setItems} />
      </div>
      <button
        type="button"
        onClick={simulate}
        className="rounded-lg px-3 py-1.5 text-[13px] text-mute outline-none transition-colors hover:bg-paper-2 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50"
      >
        Simulate a new notification
      </button>
    </div>
  );
}