{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"notification-bell","type":"registry:component","title":"Notification bell","description":"Rings when something new arrives, and the badge rolls up with each one.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/notification-bell.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, MotionConfig, motion } from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type BellNotification = { id: string; title: string; time: string };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst ITEM = { type: \"spring\", duration: 0.35, bounce: 0 } as const;\n// A little bounce is the point here: the badge should feel like it landed.\nconst BADGE_IN = { type: \"spring\", duration: 0.3, bounce: 0.35 } as const;\nconst BADGE_OUT = { duration: 0.15, ease: EASE_OUT } as const;\n// Five swings that die away. A ring needs several beats to read as ringing\n// rather than a twitch, so this runs 500ms instead of the usual 300ms cap;\n// each swing is still under 100ms.\nconst RING: Keyframe[] = [\n  { rotate: \"0deg\" },\n  { rotate: \"14deg\" },\n  { rotate: \"-12deg\" },\n  { rotate: \"8deg\" },\n  { rotate: \"-5deg\" },\n  { rotate: \"2deg\" },\n  { rotate: \"0deg\" },\n];\n\nexport function NotificationBell({\n  notifications,\n  defaultReadId,\n  ignoreOutside,\n  className,\n}: {\n  // Newest first.\n  notifications: BellNotification[];\n  // This one and everything older start out read.\n  defaultReadId?: string;\n  // Presses inside this element don't count as clicking away.\n  ignoreOutside?: React.RefObject<HTMLElement | null>;\n  className?: string;\n}) {\n  const [open, setOpen] = useState(false);\n  // One marker is all the state needed: everything newer is unread.\n  const [readId, setReadId] = useState(defaultReadId);\n  const rootRef = useRef<HTMLDivElement>(null);\n  const bellRef = useRef<HTMLButtonElement>(null);\n  const iconRef = useRef<SVGSVGElement>(null);\n  const liveRef = useRef<HTMLSpanElement>(null);\n  const newestId = useRef(notifications[0]?.id);\n  const panelId = useId();\n\n  const marker = notifications.findIndex((n) => n.id === readId);\n  const unreadCount = marker === -1 ? notifications.length : marker;\n  // Opening the panel is reading, so the badge leaves at once. The dots stay\n  // until it closes, so you can still see which ones were new.\n  const badge = open ? 0 : unreadCount;\n  const label = badge > 9 ? \"9+\" : String(badge);\n\n  const close = () => {\n    setOpen(false);\n    setReadId(newestId.current);\n  };\n\n  useEffect(() => {\n    const newest = notifications[0];\n    if (!newest || newest.id === newestId.current) return;\n    newestId.current = newest.id;\n    // Written straight to the DOM so announcing costs no render.\n    if (liveRef.current)\n      liveRef.current.textContent = `New notification: ${newest.title}`;\n    const icon = iconRef.current;\n    if (!icon || matchMedia(\"(prefers-reduced-motion: reduce)\").matches)\n      return;\n    const ring = icon.animate(RING, { duration: 500, easing: \"ease-in-out\" });\n    return () => ring.cancel();\n  }, [notifications]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onDown = (e: PointerEvent) => {\n      const target = e.target as Node;\n      if (rootRef.current?.contains(target)) return;\n      if (ignoreOutside?.current?.contains(target)) return;\n      setOpen(false);\n      setReadId(newestId.current);\n    };\n    document.addEventListener(\"pointerdown\", onDown);\n    return () => document.removeEventListener(\"pointerdown\", onDown);\n  }, [open, ignoreOutside]);\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <div\n        ref={rootRef}\n        className={cn(\"relative inline-flex\", className)}\n        onKeyDown={(e) => {\n          if (e.key !== \"Escape\" || !open) return;\n          close();\n          bellRef.current?.focus();\n        }}\n      >\n        <button\n          ref={bellRef}\n          type=\"button\"\n          aria-label={\n            badge > 0 ? `Notifications, ${unreadCount} unread` : \"Notifications\"\n          }\n          aria-expanded={open}\n          aria-controls={panelId}\n          onClick={() => (open ? close() : setOpen(true))}\n          className=\"relative flex size-11 touch-manipulation items-center justify-center rounded-full bg-muted text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n        >\n          <svg\n            ref={iconRef}\n            viewBox=\"0 0 16 16\"\n            // Swings from where a bell hangs, not from its middle.\n            className=\"size-[22px] origin-[50%_12%]\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={1.5}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            aria-hidden\n          >\n            <path d=\"M4 6.75a4 4 0 0 1 8 0c0 3 1.25 4.25 1.25 4.25H2.75S4 9.75 4 6.75Z\" />\n            <path d=\"M6.5 13.25a1.5 1.5 0 0 0 3 0\" />\n          </svg>\n\n          <AnimatePresence initial={false}>\n            {badge > 0 && (\n              <motion.span\n                key=\"badge\"\n                aria-hidden\n                initial={{ scale: 0.6, opacity: 0 }}\n                animate={{ scale: 1, opacity: 1, transition: BADGE_IN }}\n                exit={{ scale: 0.6, opacity: 0, transition: BADGE_OUT }}\n                // The page-colored ring cuts the badge out of the bell.\n                className=\"absolute -top-1 -right-1 grid h-5 min-w-5 overflow-hidden rounded-full bg-destructive px-1.5 text-xs leading-5 font-semibold text-background tabular-nums ring-2 ring-background\"\n              >\n                <AnimatePresence initial={false} mode=\"popLayout\">\n                  <motion.span\n                    key={label}\n                    className=\"col-start-1 row-start-1 text-center\"\n                    initial={{ y: \"100%\", opacity: 0 }}\n                    animate={{ y: \"0%\", opacity: 1 }}\n                    exit={{ y: \"-100%\", opacity: 0 }}\n                    transition={{ duration: 0.2, ease: EASE_OUT }}\n                  >\n                    {label}\n                  </motion.span>\n                </AnimatePresence>\n              </motion.span>\n            )}\n          </AnimatePresence>\n        </button>\n\n        {/* Out of flow and hanging from the bell, so opening it moves nothing\n            else. Enters in 150ms and leaves in 100ms. */}\n        <div\n          id={panelId}\n          role=\"region\"\n          aria-label=\"Notifications\"\n          inert={!open}\n          className={cn(\n            \"absolute top-full left-0 z-10 mt-2.5 w-[340px] max-w-[calc(100vw-2rem)] origin-top-left rounded-[20px] bg-background p-2 shadow-raised\",\n            \"transition-[opacity,scale,translate,visibility] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity,visibility]\",\n            open\n              ? \"visible translate-y-0 scale-100 opacity-100 duration-150\"\n              : \"invisible -translate-y-1 scale-[0.97] opacity-0 duration-100 motion-reduce:translate-y-0 motion-reduce:scale-100\",\n          )}\n        >\n          <p className=\"px-3 pt-2 pb-1.5 text-[13px] font-medium text-muted-foreground\">\n            Notifications\n          </p>\n          <SmoothHeight>\n            <ul>\n              <AnimatePresence initial={false} mode=\"popLayout\">\n                {notifications.map((n, i) => (\n                  <motion.li\n                    key={n.id}\n                    layout=\"position\"\n                    initial={{ opacity: 0, y: -8, filter: \"blur(4px)\" }}\n                    animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                    exit={{\n                      opacity: 0,\n                      filter: \"blur(4px)\",\n                      transition: { duration: 0.15, ease: EASE_OUT },\n                    }}\n                    transition={ITEM}\n                    // 20px panel radius minus its 8px padding.\n                    className=\"flex items-start gap-3 rounded-xl px-3 py-2.5\"\n                  >\n                    <span\n                      aria-hidden\n                      className={cn(\n                        // 6px centers the 8px dot on the first 20px line.\n                        \"mt-1.5 size-2 shrink-0 rounded-full bg-destructive transition-opacity duration-200 ease-out\",\n                        i >= unreadCount && \"opacity-0\",\n                      )}\n                    />\n                    <span className=\"flex min-w-0 flex-1 flex-col\">\n                      <span className=\"text-sm text-foreground\">\n                        {i < unreadCount && (\n                          <span className=\"sr-only\">Unread: </span>\n                        )}\n                        {n.title}\n                      </span>\n                      <span className=\"mt-0.5 text-[13px] text-muted-foreground\">{n.time}</span>\n                    </span>\n                  </motion.li>\n                ))}\n              </AnimatePresence>\n            </ul>\n          </SmoothHeight>\n        </div>\n\n        <span ref={liveRef} className=\"sr-only\" aria-live=\"polite\" />\n      </div>\n    </MotionConfig>\n  );\n}\n\n// Follows its content's height with a spring instead of jumping, so the\n// panel's bottom edge glides down when a row arrives.\nfunction SmoothHeight({ children }: { children: React.ReactNode }) {\n  const inner = useRef<HTMLDivElement>(null);\n  const [height, setHeight] = useState<number | \"auto\">(\"auto\");\n\n  useLayoutEffect(() => {\n    const el = inner.current;\n    if (!el) return;\n    const observer = new ResizeObserver(([entry]) =>\n      setHeight(entry.borderBoxSize[0].blockSize),\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  return (\n    <motion.div\n      initial={false}\n      animate={{ height }}\n      transition={ITEM}\n      className=\"overflow-hidden\"\n    >\n      <div ref={inner}>{children}</div>\n    </motion.div>\n  );\n}\n\nconst INCOMING = [\n  \"Maya commented on Roadmap\",\n  \"Deploy to production finished\",\n  \"Leo mentioned you in Design review\",\n  \"Your export is ready\",\n  \"Priya requested your review\",\n  \"Weekly report is available\",\n];\n\n// Enough to show the list moving without the panel outgrowing the page.\nconst MAX_ITEMS = 4;\n\nexport default function NotificationBellDemo() {\n  const [items, setItems] = useState<BellNotification[]>([\n    { id: \"n3\", title: \"Sam invited you to Q3 planning\", time: \"5m\" },\n    { id: \"n2\", title: \"Backup completed\", time: \"1h\" },\n    { id: \"n1\", title: \"Welcome to the workspace\", time: \"2d\" },\n  ]);\n  const next = useRef(0);\n  const simulateRef = useRef<HTMLButtonElement>(null);\n\n  const simulate = () => {\n    const n = next.current++;\n    setItems((list) =>\n      [\n        { id: `live-${n}`, title: INCOMING[n % INCOMING.length], time: \"now\" },\n        ...list,\n      ].slice(0, MAX_ITEMS),\n    );\n  };\n\n  return (\n    <div className=\"flex items-center gap-4\">\n      <NotificationBell\n        notifications={items}\n        defaultReadId=\"n2\"\n        ignoreOutside={simulateRef}\n      />\n      <button\n        ref={simulateRef}\n        type=\"button\"\n        onClick={simulate}\n        className=\"h-11 touch-manipulation rounded-full bg-muted px-5 text-[15px] font-medium text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-none\"\n      >\n        Simulate notification\n      </button>\n    </div>\n  );\n}\n"}],"cssVars":{"light":{"marker":"#d93d31","shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"marker":"#ff6b5f","shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"color-marker":"var(--marker)","shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/notification-bell"}