Notification Bell
A bell with an unread badge and a popover list. The panel scales from the bell's corner, the badge arrives from 0.9, and links render through your router.
Install
Add the @dxbh-ui registry to components.json once:
{
"registries": {
"@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
}
}Usage
"use client";
import { useState } from "react";
import { NotificationBell, type Notification } from "@/components/ui/notification-bell/notification-bell";
const initial: Notification[] = [
{ id: "1", title: "Review requested", body: "A draft is waiting for your comments.", href: "#review", time: "2m" },
{ id: "2", title: "Export finished", body: "Your file is ready to download.", href: "#export", time: "1h" },
{ id: "3", title: "New sign-in", body: "A new device signed in to your account.", time: "3h", read: true },
];
export default function NotificationBellDemo() {
const [items, setItems] = useState(initial);
const unread = items.filter((n) => !n.read).length;
const markRead = (id: string) => setItems((list) => list.map((n) => (n.id === id ? { ...n, read: true } : n)));
return (
<div className="flex w-full max-w-sm flex-col items-center gap-6">
<div className="flex w-full items-center justify-between rounded-lg border bg-background px-3 py-1.5">
<span className="text-sm font-medium">Workspace</span>
<NotificationBell
notifications={items}
onMarkAllRead={() => setItems((list) => list.map((n) => ({ ...n, read: true })))}
onSelect={(n) => markRead(n.id)}
renderLink={({ href, className, onClick, children }) => (
<a
href={href}
className={className}
onClick={(e) => {
e.preventDefault();
onClick();
}}
>
{children}
</a>
)}
/>
</div>
<button
type="button"
onClick={() => setItems(unread ? items.map((n) => ({ ...n, read: true })) : initial)}
className="cursor-pointer rounded-md border px-2.5 py-1 text-xs text-muted-foreground outline-none transition-transform duration-(--duration-press,120ms) ease-out hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 active:scale-[0.97]"
>
{unread ? "Clear badge" : "Bring back unread"}
</button>
</div>
);
}Props
| Prop | Type | Default |
|---|---|---|
notifications*{ id, title, body?, href?, read?, time? } rows, newest first. | Notification[] | — |
unreadCountBadge count. Defaults to the unread rows. | number | — |
onMarkAllReadShows a Mark all read button while anything is unread. | () => void | — |
onSelectCalled when a linked row is chosen. | (notification: Notification) => void | — |
renderLinkRender row links with your router. | (props: NotificationLinkProps) => ReactNode | <a> |
openControlled open state. | boolean | — |
defaultOpenInitial state when uncontrolled. | boolean | false |
onOpenChangeCalled when the panel opens or closes. | (open: boolean) => void | — |
alignEdge of the bell the panel lines up with; also sets the transform origin. | "start" | "end" | "end" |
labelAccessible name and panel heading. | string | "Notifications" |
maxBadge shows max+ above this. | number | 9 |
emptyShown with no notifications. | ReactNode | "You’re all caught up" |
Polish
- Fetching, polling and the PATCH call removed; callers pass notifications and onMarkAllRead.
- react-icons replaced with lucide; next/link replaced with a renderLink prop that defaults to <a>.
- Brand copper and accent tints replaced with foreground/background neutrals.
- Panel enters in 150ms with ease-out from scale 0.96 and opacity, with transform-origin on the bell's corner. Exit takes 100ms.
- Badge enters from scale 0.9, never 0, and uses tabular-nums.
- Unread rows carry a dot, heavier weight and a screen-reader prefix, so status never depends on colour.
- Escape and outside presses close it; Escape returns focus to the bell. The bell's name stays stable and the count is a description.
- Press feedback at active:scale-[0.97]. Reduced motion keeps the fade and drops the scale.
Source
"use client";
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
import { Bell } from "lucide-react";
import { cn } from "@/lib/utils";
export type Notification = {
id: string;
title: string;
body?: string;
/** Where the row leads. Rows without one render as plain text. */
href?: string;
read?: boolean;
/** Pre-formatted time, such as "2m" or a <time> element. */
time?: ReactNode;
};
export type NotificationLinkProps = {
href: string;
className: string;
onClick: () => void;
children: ReactNode;
};
export type NotificationBellProps = {
notifications: Notification[];
/** Badge count. Defaults to the number of unread notifications. */
unreadCount?: number;
onMarkAllRead?: () => void;
/** Called when a row is chosen, before the panel closes. */
onSelect?: (notification: Notification) => void;
/** Render links with your router (next/link, react-router…). Defaults to <a>. */
renderLink?: (props: NotificationLinkProps) => ReactNode;
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Which edge of the trigger the panel lines up with. */
align?: "start" | "end";
/** Accessible name of the trigger and heading of the panel. */
label?: string;
markAllReadLabel?: string;
empty?: ReactNode;
/** Badge shows `${max}+` above this. */
max?: number;
className?: string;
};
/** Enter is 150ms; exit runs faster. */
export const BELL_EXIT_MS = 100;
const defaultLink = ({ href, className, onClick, children }: NotificationLinkProps) => (
<a href={href} className={className} onClick={onClick}>
{children}
</a>
);
export function NotificationBell({
notifications,
unreadCount,
onMarkAllRead,
onSelect,
renderLink = defaultLink,
open: openProp,
defaultOpen = false,
onOpenChange,
align = "end",
label = "Notifications",
markAllReadLabel = "Mark all read",
empty = "You’re all caught up",
max = 9,
className,
}: NotificationBellProps) {
const id = useId();
const rootRef = useRef<HTMLDivElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const [openState, setOpenState] = useState(defaultOpen);
const controlled = openProp !== undefined;
const open = controlled ? openProp : openState;
const setOpen = useCallback(
(next: boolean) => {
if (!controlled) setOpenState(next);
onOpenChange?.(next);
},
[controlled, onOpenChange],
);
// Keep the panel mounted through its exit.
const [mounted, setMounted] = useState(open);
const [prevOpen, setPrevOpen] = useState(open);
if (prevOpen !== open) {
setPrevOpen(open);
if (open) setMounted(true);
}
useEffect(() => {
if (open || !mounted) return;
const t = setTimeout(() => setMounted(false), BELL_EXIT_MS);
return () => clearTimeout(t);
}, [open, mounted]);
// Outside press and Escape close it. Escape returns focus to the bell.
useEffect(() => {
if (!open) return;
const onPointer = (e: PointerEvent) => {
if (!rootRef.current?.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Escape") return;
setOpen(false);
triggerRef.current?.focus();
};
document.addEventListener("pointerdown", onPointer);
document.addEventListener("keydown", onKey);
return () => {
document.removeEventListener("pointerdown", onPointer);
document.removeEventListener("keydown", onKey);
};
}, [open, setOpen]);
const unread = unreadCount ?? notifications.filter((n) => !n.read).length;
const panelId = `${id}-panel`;
const countId = `${id}-count`;
const state = open ? "open" : "closed";
const choose = (n: Notification) => {
onSelect?.(n);
setOpen(false);
};
return (
<div ref={rootRef} className={cn("relative inline-flex", className)}>
<button
ref={triggerRef}
type="button"
aria-label={label}
aria-describedby={unread > 0 ? countId : undefined}
aria-expanded={open}
aria-controls={mounted ? panelId : undefined}
aria-haspopup="dialog"
onClick={() => setOpen(!open)}
className={cn(
"relative inline-flex size-9 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none select-none",
"transition-transform duration-(--duration-press,120ms) ease-out active:scale-[0.97]",
"hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50",
open && "bg-muted text-foreground",
)}
>
<Bell aria-hidden="true" className="size-[18px]" />
{unread > 0 ? (
<span
aria-hidden="true"
data-slot="notification-badge"
// Arrives from 0.9 so it reads as appearing, not growing from nothing.
className={cn(
"absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-foreground px-1 text-[10px] leading-none font-semibold text-background tabular-nums",
"transition-[opacity,transform] duration-150 ease-out starting:scale-[0.9] starting:opacity-0 motion-reduce:starting:scale-100",
)}
>
{unread > max ? `${max}+` : unread}
</span>
) : null}
</button>
<span id={countId} className="sr-only">
{unread > 0 ? `${unread} unread` : ""}
</span>
{mounted ? (
<div
id={panelId}
role="dialog"
aria-label={label}
data-state={state}
data-slot="notification-panel"
className={cn(
"absolute top-full z-50 mt-2 w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl border bg-popover text-popover-foreground shadow-lg",
// Scale from the corner the bell sits in, not from the centre.
align === "end" ? "right-0 origin-top-right" : "left-0 origin-top-left",
"transition-[opacity,transform] duration-150 ease-out starting:scale-[0.96] starting:opacity-0",
"data-[state=closed]:pointer-events-none data-[state=closed]:scale-[0.96] data-[state=closed]:opacity-0 data-[state=closed]:duration-100",
"motion-reduce:scale-100 motion-reduce:starting:scale-100 motion-reduce:data-[state=closed]:scale-100",
)}
>
<div className="flex items-center justify-between gap-2 border-b px-3 py-2">
<p className="text-sm font-medium">{label}</p>
{unread > 0 && onMarkAllRead ? (
<button
type="button"
onClick={onMarkAllRead}
className="cursor-pointer rounded px-1.5 py-1 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50"
>
{markAllReadLabel}
</button>
) : null}
</div>
{notifications.length === 0 ? (
<p className="px-3 py-8 text-center text-sm text-muted-foreground">{empty}</p>
) : (
<ul className="max-h-80 overflow-y-auto overscroll-contain p-1">
{notifications.map((n) => {
const content = (
<>
{/* A dot plus weight, so unread never depends on colour alone. */}
<span
aria-hidden="true"
className={cn("mt-1.5 size-1.5 shrink-0 rounded-full", n.read ? "bg-transparent" : "bg-foreground")}
/>
<span className="min-w-0 flex-1">
<span className="flex items-baseline gap-2">
<span className={cn("min-w-0 flex-1 truncate", n.read ? "text-muted-foreground" : "font-medium")}>
{n.read ? null : <span className="sr-only">Unread: </span>}
{n.title}
</span>
{n.time ? <span className="shrink-0 text-xs text-muted-foreground tabular-nums">{n.time}</span> : null}
</span>
{n.body ? <span className="mt-0.5 line-clamp-2 block text-xs text-muted-foreground">{n.body}</span> : null}
</span>
</>
);
const rowClass = "flex gap-2.5 rounded-lg px-2 py-2 text-sm";
return (
<li key={n.id}>
{n.href ? (
renderLink({
href: n.href,
onClick: () => choose(n),
className: cn(
rowClass,
"outline-none hover:bg-muted focus-visible:bg-muted focus-visible:ring-2 focus-visible:ring-ring/50",
),
children: content,
})
) : (
<div className={rowClass}>{content}</div>
)}
</li>
);
})}
</ul>
)}
</div>
) : null}
</div>
);
}Extracted from Vesrelle/components/layout/notification-bell.tsx at 4619651.