Skip to content
Shaken UI
Sign in

Notification Center

Save

A bell with an unread badge that opens a panel of notifications grouped by day, with filter tabs and counts, unread dots, inline actions, and mark one or all as read.

Category
Overlays
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Notification Center preview
Northwind Labs

Installation

npx @shakenui/cli add notification-center

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add notification-center --dry-run

Usage

notification-center-example.tsx
"use client";

import { NotificationCenter, type NotificationItem } from "@/components/shaken/ui/notification-center";

const now = new Date("2026-11-16T15:30:00");
const ago = (minutes: number) => new Date(now.getTime() - minutes * 60_000);

function Initials({ children }: { children: string }) {
  return (
    <span className="flex size-8 items-center justify-center rounded-full bg-zinc-950/[0.06] text-[11px] font-medium text-zinc-700 dark:bg-white/[0.1] dark:text-zinc-300">
      {children}
    </span>
  );
}

const items: NotificationItem[] = [
  {
    id: "deploy",
    category: "approvals",
    tone: "warning",
    title: "Deploy to production needs approval",
    body: "release-2.4 from Theo Brandt, 14 files changed, all checks passed.",
    time: ago(6),
    actions: [
      { label: "Approve", primary: true, resolvedLabel: "Approved" },
      { label: "View diff" },
    ],
  },
  {
    id: "mention",
    category: "mentions",
    avatar: <Initials>IA</Initials>,
    title: "Ines Alvarez mentioned you",
    body: "Can you check whether the 88% holds on the long-context set before we flip the flag?",
    time: ago(24),
    actions: [{ label: "Reply" }],
  },
  { id: "eval", category: "system", tone: "success", title: "Nightly evaluation finished", body: "320 of 320 cases passed in 11m 42s.", time: ago(130) },
  {
    id: "billing",
    category: "system",
    tone: "danger",
    title: "Billing worker failed 3 times",
    body: "The payments webhook timed out after 30s. Retries are paused.",
    time: ago(60 * 22),
    read: true,
  },
  {
    id: "invite",
    avatar: <Initials>MO</Initials>,
    title: "Mara Okafor invited you to Northwind Labs",
    time: ago(60 * 24 * 3),
    read: true,
    resolved: "Accepted",
  },
  { id: "key", category: "system", tone: "warning", title: "Key sk_test_0d77 expires in 7 days", time: ago(60 * 24 * 9), read: true },
];

export default function NotificationCenterExample() {
  return (
    <div className="flex w-full max-w-md items-center justify-between rounded-xl border border-zinc-950/10 bg-white py-1.5 pr-1.5 pl-4 dark:border-white/10 dark:bg-black">
      <span className="text-sm font-medium text-zinc-950 dark:text-white">Northwind Labs</span>
      <NotificationCenter
        defaultItems={items}
        now={now}
        filters={[
          { value: "all", label: "All" },
          { value: "mentions", label: "Mentions", empty: { title: "No mentions", description: "When someone mentions you in a run or thread, it shows up here." } },
          { value: "approvals", label: "Approvals", empty: { title: "Nothing to approve", description: "Deploys and tool calls that wait for you land here." } },
          { value: "system", label: "System" },
        ]}
      />
    </div>
  );
}

API

PropTypeDefaultDescription
items / defaultItemsNotificationItem[]—NotificationCenter, NotificationPanel: the notifications. Each has id, title, time, and optional body, read, category, avatar, tone, actions, and resolved.
onItemsChange(items) => void—Called when items are marked read or resolved.
onAction(item, action) => void—Called after an inline action runs. Pressing an action also marks its item read.
filters{ value, label, match?, empty? }[][{ value: "all", label: "All" }]Tabs above the list with unread counts. A filter matches items whose category equals its value unless match is given; all shows everything. empty sets the tab's empty state.
NotificationItem actions{ label, primary?, resolvedLabel?, onSelect? }[]—Inline buttons. resolvedLabel replaces the buttons with a result line, such as Approved.
nowDatenew Date()Reference time for day groups (Today, Yesterday, This week, Earlier) and relative times. Pass a fixed date when rendering on the server.
title / footerReactNode"Notifications"NotificationPanel: the heading and optional content under the list.
open / defaultOpen / onOpenChangeboolean / Popover onOpenChange—NotificationCenter: the popover's open state.
side / align"top" | "bottom" | "left" | "right" / "start" | "center" | "end""bottom" / "end"NotificationCenter: where the panel opens.
container / initialFocusPopover Portal container / Popup initialFocus—NotificationCenter: where the panel portals to, and where focus goes when it opens.
NotificationBell count / maxnumbermax 99The badge count; zero hides the badge and counts above max show as max+.

Accessibility

  • The bell is a button labeled "Notifications, 3 unread"; the badge is decorative.
  • The panel is a Base UI Popover: focus moves into it on open, Escape closes it, and focus returns to the bell.
  • Filter tabs are a Base UI tablist; arrow keys move between them and each tab's name includes its unread count.
  • Each unread dot is a 24px button labeled "Mark as read" and described by the item's title; inline action buttons are described by the title too.
  • Marking read, mark all, and resolved actions are announced in a polite live region; read state also shows as a lighter title, not only the dot.
  • Under reduced motion the badge, bell swing, row entrances, tab pill, and dot cascade are instant.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/notification-center.tsxnotification-center
  • npm packages: @base-ui/react@^1.9.0, motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/notification-center/0.1.0.json.

ui/notification-center.tsxShow
ui/notification-center.tsx
"use client";

import { Popover as BasePopover } from "@base-ui/react/popover";
import { Tabs as BaseTabs } from "@base-ui/react/tabs";
import { AnimatePresence, MotionConfig, motion, useAnimate, useReducedMotion } from "motion/react";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = [0.23, 1, 0.32, 1] as const;

export type NotificationTone = "neutral" | "info" | "success" | "danger" | "warning";

export interface NotificationAction {
  label: string;
  /** Renders as the primary button. */
  primary?: boolean;
  /** Replaces the buttons with this result once pressed, such as "Approved". */
  resolvedLabel?: string;
  onSelect?: (item: NotificationItem) => void;
}

export interface NotificationItem {
  id: string;
  title: ReactNode;
  body?: ReactNode;
  /** When it happened. Groups the list and shows as a relative time. */
  time: Date | string | number;
  read?: boolean;
  /** Matched by a filter's `value`, such as "mentions". */
  category?: string;
  /** A 32px avatar or icon. Defaults to a glyph for `tone`. */
  avatar?: ReactNode;
  tone?: NotificationTone;
  /** Inline buttons, such as Approve and View. Pressing one marks the item read. */
  actions?: NotificationAction[];
  /** The result of an action that set `resolvedLabel`. */
  resolved?: string;
}

export interface NotificationFilter {
  value: string;
  label: string;
  /** Which items the tab shows. Defaults to items whose `category` equals `value`; `all` shows everything. */
  match?: (item: NotificationItem) => boolean;
  /** Empty state for this tab. */
  empty?: { title: string; description?: string };
}

export interface NotificationPanelProps {
  /** Controlled items. */
  items?: NotificationItem[];
  defaultItems?: NotificationItem[];
  onItemsChange?: (items: NotificationItem[]) => void;
  /** Called after an inline action runs. */
  onAction?: (item: NotificationItem, action: NotificationAction) => void;
  /** Tabs above the list. Defaults to a single All tab, which hides the tab row. */
  filters?: NotificationFilter[];
  /** The reference time for grouping and relative times. Defaults to now. */
  now?: Date;
  title?: ReactNode;
  /** Content under the list, such as a link to settings. */
  footer?: ReactNode;
  className?: string;
}

const allFilter: NotificationFilter = { value: "all", label: "All" };

function useItems(itemsProp: NotificationItem[] | undefined, defaultItems: NotificationItem[], onItemsChange?: (items: NotificationItem[]) => void) {
  const [state, setState] = useState(defaultItems);
  const items = itemsProp ?? state;
  const set = (next: NotificationItem[]) => {
    if (itemsProp === undefined) setState(next);
    onItemsChange?.(next);
  };
  return [items, set] as const;
}

/**
 * The notification list on its own: a header with the unread count and Mark all as read, filter
 * tabs with counts, items grouped by day with unread dots and inline actions, and an empty state
 * per tab. Use it inside NotificationCenter, a sheet, or a page.
 */
export function NotificationPanel(props: NotificationPanelProps) {
  const [items, setItems] = useItems(props.items, props.defaultItems ?? [], props.onItemsChange);
  return <PanelView {...props} items={items} setItems={setItems} />;
}

interface PanelViewProps extends NotificationPanelProps {
  items: NotificationItem[];
  setItems: (items: NotificationItem[]) => void;
}

function PanelView({ items, setItems, onAction, filters = [allFilter], now: nowProp, title = "Notifications", footer, className }: PanelViewProps) {
  const reduce = useReducedMotion();
  const [active, setActive] = useState(filters[0]?.value ?? "all");
  const [message, setMessage] = useState("");
  // Set for one pass after Mark all as read, so the dots leave top to bottom.
  const [cascade, setCascade] = useState(false);
  const titleId = useId();
  const pillId = `notification-tab-${useId()}`;
  const now = nowProp ?? new Date();

  const matches = (filter: NotificationFilter, item: NotificationItem) =>
    filter.match ? filter.match(item) : filter.value === "all" || item.category === filter.value;
  const filter = filters.find((f) => f.value === active) ?? filters[0] ?? allFilter;
  const visible = items.filter((item) => matches(filter, item));
  const unread = items.filter((item) => !item.read).length;

  useEffect(() => {
    if (!cascade) return;
    const id = window.setTimeout(() => setCascade(false), 600);
    return () => window.clearTimeout(id);
  }, [cascade]);

  const markRead = (id: string) => {
    setItems(items.map((item) => (item.id === id ? { ...item, read: true } : item)));
    setMessage("Marked as read.");
  };

  const markAll = () => {
    setCascade(true);
    setItems(items.map((item) => (item.read ? item : { ...item, read: true })));
    setMessage("All notifications marked as read.");
  };

  const runAction = (item: NotificationItem, action: NotificationAction) => {
    action.onSelect?.(item);
    onAction?.(item, action);
    setItems(items.map((i) => (i.id === item.id ? { ...i, read: true, resolved: action.resolvedLabel ?? i.resolved } : i)));
    if (action.resolvedLabel) setMessage(`${action.resolvedLabel}.`);
  };

  const groups = groupByDay(visible, now);
  let dotIndex = 0;

  return (
    <MotionConfig reducedMotion="user">
      <section aria-labelledby={titleId} className={cx("flex min-h-0 flex-col text-sm", className)}>
        <header className="flex items-center justify-between gap-3 px-4 pt-3.5 pb-2.5">
          <h2 id={titleId} className="flex items-baseline gap-2 text-sm font-semibold text-zinc-950 dark:text-white">
            {title}
            <span className="text-xs font-normal text-zinc-500 tabular-nums">{unread > 0 ? `${unread} unread` : "All read"}</span>
          </h2>
          <button
            type="button"
            onClick={markAll}
            disabled={unread === 0}
            className={cx(
              "-mr-1.5 h-7 shrink-0 rounded-md px-1.5 text-xs font-medium text-zinc-600 select-none dark:text-zinc-400",
              "transition-[background-color,color,opacity] duration-150 ease-out motion-reduce:transition-none",
              "enabled:hover:bg-zinc-950/[0.04] enabled:hover:text-zinc-950 dark:enabled:hover:bg-white/[0.06] dark:enabled:hover:text-white",
              "disabled:opacity-40",
              "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
            )}
          >
            Mark all as read
          </button>
        </header>
        <BaseTabs.Root value={active} onValueChange={(value) => setActive(value as string)} className="flex min-h-0 flex-col">
          {filters.length > 1 ? (
            <BaseTabs.List className="mx-3 mb-1 flex gap-0.5 rounded-lg bg-zinc-950/[0.035] p-0.5 dark:bg-white/[0.06]">
              {filters.map((f) => {
                const count = items.filter((item) => !item.read && matches(f, item)).length;
                return (
                  <BaseTabs.Tab
                    key={f.value}
                    value={f.value}
                    aria-label={count > 0 ? `${f.label}, ${count} unread` : f.label}
                    className={cx(
                      "relative flex h-7 flex-1 items-center justify-center gap-1.5 rounded-md px-2 text-xs font-medium whitespace-nowrap select-none",
                      "text-zinc-600 hover:text-zinc-950 data-[active]:text-zinc-950 dark:text-zinc-400 dark:hover:text-white dark:data-[active]:text-white",
                      "transition-colors duration-150 ease-out motion-reduce:transition-none",
                      "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
                    )}
                  >
                    {f.value === active ? (
                      <motion.span
                        aria-hidden="true"
                        layoutId={pillId}
                        transition={{ type: "spring", bounce: 0, duration: 0.35 }}
                        className="absolute inset-0 rounded-md bg-white shadow-[0_1px_2px_rgb(0_0_0/0.08),0_0_0_1px_rgb(0_0_0/0.05)] dark:bg-black dark:shadow-[0_0_0_1px_rgb(255_255_255/0.12)]"
                      />
                    ) : null}
                    <span className="relative">{f.label}</span>
                    {count > 0 ? <span className="relative font-mono text-[11px] text-zinc-500 tabular-nums">{count}</span> : null}
                  </BaseTabs.Tab>
                );
              })}
            </BaseTabs.List>
          ) : null}
          {/* One panel whose value follows the active tab, so switching cross-fades instead of remounting. */}
          <BaseTabs.Panel value={active} className="min-h-0 overflow-y-auto overscroll-contain outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500">
            <AnimatePresence mode="popLayout" initial={false}>
              <motion.div
                key={active}
                initial={{ opacity: 0, y: reduce ? 0 : 4 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, transition: { duration: reduce ? 0 : 0.08 } }}
                transition={{ duration: reduce ? 0 : 0.2, ease }}
                className="pb-1.5"
              >
                {visible.length === 0 ? (
                  <EmptyState title={filter.empty?.title ?? "You are all caught up"} description={filter.empty?.description ?? "New notifications will show up here."} />
                ) : (
                  groups.map((group) => (
                    <section key={group.label} aria-label={group.label}>
                      <h3 className="px-4 pt-2.5 pb-1 text-xs font-medium text-zinc-500">{group.label}</h3>
                      <ul>
                        <AnimatePresence initial={false}>
                          {group.items.map((item) => {
                            const index = item.read ? 0 : dotIndex++;
                            return (
                              <Row
                                key={item.id}
                                item={item}
                                now={now}
                                cascadeDelay={cascade ? Math.min(index, 10) * 0.035 : 0}
                                onRead={() => markRead(item.id)}
                                onAction={(action) => runAction(item, action)}
                              />
                            );
                          })}
                        </AnimatePresence>
                      </ul>
                    </section>
                  ))
                )}
              </motion.div>
            </AnimatePresence>
          </BaseTabs.Panel>
        </BaseTabs.Root>
        {footer ? <footer className="border-t border-zinc-950/[0.07] px-4 py-2.5 dark:border-white/[0.08]">{footer}</footer> : null}
        <span role="status" aria-live="polite" className="sr-only">
          {message}
        </span>
      </section>
    </MotionConfig>
  );
}

function Row({
  item,
  now,
  cascadeDelay,
  onRead,
  onAction,
}: {
  item: NotificationItem;
  now: Date;
  cascadeDelay: number;
  onRead: () => void;
  onAction: (action: NotificationAction) => void;
}) {
  const reduce = useReducedMotion();
  const titleId = useId();
  const date = toDate(item.time);

  return (
    // New arrivals open their space and fade in; rows below shift down rather than jump.
    <motion.li
      layout={reduce ? false : "position"}
      initial={{ opacity: 0, height: 0 }}
      animate={{ opacity: 1, height: "auto" }}
      exit={{ opacity: 0, height: 0, transition: { duration: reduce ? 0 : 0.16 } }}
      transition={reduce ? { duration: 0 } : { height: { duration: 0.28, ease }, opacity: { duration: 0.22, delay: 0.08 }, layout: { duration: 0.28, ease } }}
      className="relative overflow-hidden"
    >
      <div className="relative grid grid-cols-[2rem_1fr] gap-x-3 px-4 py-2.5">
      <span aria-hidden="true" className="flex size-8 items-center justify-center">
        {item.avatar ?? <ToneGlyph tone={item.tone ?? "neutral"} />}
      </span>
      <div className="grid min-w-0 gap-0.5 pr-5">
        <div className="flex items-baseline justify-between gap-3">
          <p
            id={titleId}
            className={cx(
              "min-w-0 leading-5 transition-colors duration-200 motion-reduce:transition-none",
              item.read ? "text-zinc-600 dark:text-zinc-400" : "font-medium text-zinc-950 dark:text-white",
            )}
          >
            {item.title}
          </p>
          <time dateTime={date.toISOString()} title={date.toLocaleString()} className="shrink-0 font-mono text-[11px] text-zinc-500 tabular-nums">
            {relativeTime(date, now)}
          </time>
        </div>
        {item.body ? <p className="line-clamp-2 leading-5 text-zinc-600 dark:text-zinc-400">{item.body}</p> : null}
        {item.actions?.length || item.resolved ? (
          <div className="relative mt-1.5 h-7">
            <AnimatePresence mode="popLayout" initial={false}>
              {item.resolved ? (
                <motion.p
                  key="resolved"
                  initial={{ opacity: 0, y: reduce ? 0 : 4 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: reduce ? 0 : 0.22, ease }}
                  className="flex h-7 items-center gap-1.5 text-xs text-zinc-600 dark:text-zinc-400"
                >
                  <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4 text-emerald-600 dark:text-emerald-400">
                    <circle cx="8" cy="8" r="6.25" />
                    <path d="m5.5 8.25 1.75 1.75 3.25-3.5" />
                  </svg>
                  {item.resolved}
                </motion.p>
              ) : (
                <motion.div
                  key="actions"
                  exit={{ opacity: 0, y: reduce ? 0 : -4, transition: { duration: reduce ? 0 : 0.12 } }}
                  className="flex gap-1.5"
                >
                  {item.actions!.map((action) => (
                    <button
                      key={action.label}
                      type="button"
                      aria-describedby={titleId}
                      onClick={() => onAction(action)}
                      className={cx(
                        "inline-flex h-7 items-center rounded-md px-2.5 text-xs font-medium whitespace-nowrap select-none",
                        "transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
                        "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
                        action.primary
                          ? "bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12)] hover:bg-zinc-800 dark:bg-white dark:text-black dark:hover:bg-zinc-200"
                          : "border border-zinc-950/12 bg-white text-zinc-950 hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]",
                      )}
                    >
                      {action.label}
                    </button>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        ) : null}
      </div>
      <AnimatePresence initial={false}>
        {item.read ? null : (
          <motion.button
            key="dot"
            type="button"
            aria-label="Mark as read"
            aria-describedby={titleId}
            onClick={onRead}
            exit={{ opacity: 0, scale: 0.3, transition: { duration: reduce ? 0 : 0.18, ease: "easeOut", delay: reduce ? 0 : cascadeDelay } }}
            className={cx(
              "group/dot absolute top-3 right-2.5 flex size-6 items-center justify-center rounded-full",
              "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
            )}
          >
            <span
              className={cx(
                "size-2 rounded-full bg-sky-500",
                "transition-[scale,box-shadow] duration-150 ease-out motion-reduce:transition-none",
                "group-hover/dot:scale-125 group-hover/dot:shadow-[0_0_0_3px_rgb(14_165_233/0.18)]",
              )}
            />
          </motion.button>
        )}
      </AnimatePresence>
      </div>
    </motion.li>
  );
}

function EmptyState({ title, description }: { title: string; description?: string }) {
  return (
    <div className="flex flex-col items-center px-6 pt-8 pb-9 text-center">
      <span aria-hidden="true" className="mb-3 flex size-10 items-center justify-center rounded-full border border-zinc-950/10 text-zinc-500 dark:border-white/15">
        <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
          <path d="M4.25 6.5a3.75 3.75 0 0 1 7.5 0c0 2.5.75 3.75 1.5 4.5H2.75c.75-.75 1.5-2 1.5-4.5Z" />
          <path d="M6.5 13.25a1.6 1.6 0 0 0 3 0" />
        </svg>
      </span>
      <p className="font-medium text-zinc-950 dark:text-white">{title}</p>
      {description ? <p className="mt-1 max-w-56 text-xs leading-5 text-zinc-500">{description}</p> : null}
    </div>
  );
}

function ToneGlyph({ tone }: { tone: NotificationTone }) {
  const color = {
    neutral: "text-zinc-500",
    info: "text-sky-600 dark:text-sky-400",
    success: "text-emerald-600 dark:text-emerald-400",
    danger: "text-red-600 dark:text-red-400",
    warning: "text-amber-600 dark:text-amber-400",
  }[tone];
  return (
    <span className={cx("flex size-8 items-center justify-center rounded-full border border-zinc-950/10 dark:border-white/12", color)}>
      <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
        <circle cx="8" cy="8" r="6.25" />
        {tone === "success" ? <path d="m5.5 8.25 1.75 1.75 3.25-3.5" /> : null}
        {tone === "danger" ? <path d="m6 6 4 4m0-4-4 4" /> : null}
        {tone === "warning" ? <path d="M6.75 6v4M9.25 6v4" /> : null}
        {tone === "info" ? <path d="M8 7.5v3M8 5.25v.01" /> : null}
        {tone === "neutral" ? <path d="M8 5.5v2.75l1.75 1" /> : null}
      </svg>
    </span>
  );
}

export interface NotificationBellProps extends Omit<BasePopover.Trigger.Props, "className" | "children"> {
  /** Unread count. Zero hides the badge. */
  count: number;
  /** Counts above this show as `max+`. */
  max?: number;
  className?: string;
}

/**
 * The bell trigger. Its badge slides out from behind the bell's corner and pops in, its digits pop
 * when the count changes, the bell swings once when the count grows, and the badge shrinks away
 * when everything is read.
 */
export function NotificationBell({ count, max = 99, className, ...props }: NotificationBellProps) {
  const reduce = useReducedMotion();
  const [scope, animateBell] = useAnimate<HTMLSpanElement>();
  const previous = useRef(count);

  useEffect(() => {
    if (count > previous.current && !reduce && scope.current) {
      void animateBell(scope.current, { rotate: [0, 14, -10, 6, -3, 0] }, { duration: 0.6, ease: "easeOut" });
    }
    previous.current = count;
  }, [count, reduce, animateBell, scope]);

  const shown = count > max ? `${max}+` : String(count);

  return (
    <BasePopover.Trigger
      aria-label={count > 0 ? `Notifications, ${count} unread` : "Notifications"}
      className={cx(
        "relative inline-flex size-9 items-center justify-center rounded-lg select-none",
        "text-zinc-600 hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:text-zinc-400 dark:hover:bg-white/[0.06] dark:hover:text-white",
        "data-[popup-open]:bg-zinc-950/[0.06] data-[popup-open]:text-zinc-950 dark:data-[popup-open]:bg-white/[0.09] dark:data-[popup-open]:text-white",
        "transition-[background-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.95] motion-reduce:transition-none",
        "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
        className,
      )}
      {...props}
    >
      <span ref={scope} className="flex origin-[50%_2px]">
        <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-[18px]">
          <path d="M4.25 6.5a3.75 3.75 0 0 1 7.5 0c0 2.5.75 3.75 1.5 4.5H2.75c.75-.75 1.5-2 1.5-4.5Z" />
          <path d="M6.5 13.25a1.6 1.6 0 0 0 3 0" />
        </svg>
      </span>
      <AnimatePresence initial={false}>
        {count > 0 ? (
          // Outer: slides out from behind the bell. Inner: pops. On exit only the inner shrinks away.
          <motion.span
            key="badge"
            aria-hidden="true"
            className="pointer-events-none absolute top-1 left-[55%]"
            initial={reduce ? false : { x: -7, y: 7 }}
            animate={{ x: 0, y: 0 }}
            exit={{ x: 0, y: 0 }}
            transition={{ duration: reduce ? 0 : 0.26, ease }}
          >
            <motion.span
              className={cx(
                "flex h-4 min-w-4 items-center justify-center overflow-hidden rounded-full px-1",
                "bg-zinc-950 font-mono text-[10px] leading-none font-medium text-white tabular-nums ring-2 ring-white",
                "dark:bg-white dark:text-black dark:ring-black",
              )}
              initial={reduce ? false : { scale: 0.4, opacity: 0, filter: "blur(2px)" }}
              animate={{ scale: 1, opacity: 1, filter: "blur(0px)" }}
              exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { scale: 0.4, opacity: 0, filter: "blur(2px)", transition: { duration: 0.16, ease: "easeIn" } }}
              transition={reduce ? { duration: 0 } : { type: "spring", bounce: 0.4, duration: 0.42 }}
            >
              <AnimatePresence mode="popLayout" initial={false}>
                <motion.span
                  key={shown}
                  initial={reduce ? false : { y: "70%", scale: 0.7, opacity: 0, filter: "blur(1.5px)" }}
                  animate={{ y: 0, scale: 1, opacity: 1, filter: "blur(0px)" }}
                  exit={reduce ? { opacity: 0, transition: { duration: 0 } } : { y: "-70%", scale: 0.7, opacity: 0, filter: "blur(1.5px)", transition: { duration: 0.14, ease: "easeOut" } }}
                  transition={{ type: "spring", bounce: 0.35, duration: 0.45, delay: reduce ? 0 : 0.04 }}
                  className="block"
                >
                  {shown}
                </motion.span>
              </AnimatePresence>
            </motion.span>
          </motion.span>
        ) : null}
      </AnimatePresence>
    </BasePopover.Trigger>
  );
}

export interface NotificationCenterProps extends NotificationPanelProps {
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: BasePopover.Root.Props["onOpenChange"];
  /** Where focus goes when the panel opens. Defaults to the first control in the panel. */
  initialFocus?: BasePopover.Popup.Props["initialFocus"];
  side?: "top" | "bottom" | "left" | "right";
  align?: "start" | "center" | "end";
  /** Element to portal the panel into. Defaults to `document.body`. */
  container?: BasePopover.Portal.Props["container"];
  /** Classes for the bell. */
  triggerClassName?: string;
}

/** A bell with an unread badge that opens the notification panel in a popover. */
export function NotificationCenter({
  open,
  defaultOpen,
  onOpenChange,
  side = "bottom",
  align = "end",
  container,
  initialFocus,
  triggerClassName,
  items: itemsProp,
  defaultItems = [],
  onItemsChange,
  className,
  ...panelProps
}: NotificationCenterProps) {
  const [items, setItems] = useItems(itemsProp, defaultItems, onItemsChange);
  const unread = items.filter((item) => !item.read).length;

  return (
    <BasePopover.Root open={open} defaultOpen={defaultOpen} onOpenChange={onOpenChange}>
      <NotificationBell count={unread} className={triggerClassName} />
      <BasePopover.Portal container={container}>
        <BasePopover.Positioner
          side={side}
          align={align}
          sideOffset={8}
          collisionPadding={12}
          // Flip between below and above, but never to the side, where the panel would cover its own bar.
          collisionAvoidance={{ side: "flip", align: "shift", fallbackAxisSide: "none" }}
          className="z-50"
        >
          <BasePopover.Popup
            initialFocus={initialFocus}
            className={cx(
              "flex max-h-[min(34rem,var(--available-height))] w-[min(23rem,calc(100vw-1.5rem))] origin-(--transform-origin) flex-col overflow-hidden rounded-xl",
              "border border-zinc-950/10 bg-white text-zinc-950 shadow-[0_12px_32px_-8px_rgb(0_0_0/0.18)]",
              "dark:border-white/15 dark:bg-black dark:text-white dark:shadow-[0_16px_48px_-12px_rgb(0_0_0/1),inset_0_1px_0_rgb(255_255_255/0.08)]",
              "transition-[opacity,scale] duration-160 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
              "data-[starting-style]:opacity-0 motion-safe:data-[starting-style]:scale-96",
              "data-[ending-style]:opacity-0 data-[ending-style]:duration-110 data-[ending-style]:ease-out motion-safe:data-[ending-style]:scale-98",
              "outline-none",
              className,
            )}
          >
            <PanelView {...panelProps} items={items} setItems={setItems} />
          </BasePopover.Popup>
        </BasePopover.Positioner>
      </BasePopover.Portal>
    </BasePopover.Root>
  );
}

function toDate(value: Date | string | number) {
  return value instanceof Date ? value : new Date(value);
}

function dayDiff(date: Date, now: Date) {
  const a = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
  const b = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
  return Math.round((b - a) / 86_400_000);
}

function groupByDay(items: NotificationItem[], now: Date) {
  const order = ["Today", "Yesterday", "This week", "Earlier"];
  const buckets = new Map<string, NotificationItem[]>();
  const sorted = items.slice().sort((a, b) => toDate(b.time).getTime() - toDate(a.time).getTime());
  for (const item of sorted) {
    const diff = dayDiff(toDate(item.time), now);
    const label = diff <= 0 ? "Today" : diff === 1 ? "Yesterday" : diff < 7 ? "This week" : "Earlier";
    const list = buckets.get(label) ?? [];
    list.push(item);
    buckets.set(label, list);
  }
  return order.filter((label) => buckets.has(label)).map((label) => ({ label, items: buckets.get(label)! }));
}

function relativeTime(date: Date, now: Date) {
  const minutes = Math.round((now.getTime() - date.getTime()) / 60_000);
  const diff = dayDiff(date, now);
  if (diff <= 0) {
    if (minutes < 1) return "now";
    if (minutes < 60) return `${minutes}m`;
    return `${Math.floor(minutes / 60)}h`;
  }
  if (diff === 1) return new Intl.DateTimeFormat(undefined, { hour: "numeric", minute: "2-digit" }).format(date);
  if (diff < 7) return new Intl.DateTimeFormat(undefined, { weekday: "short" }).format(date);
  return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(date);
}