{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"notification-bell","type":"registry:component","title":"Notification bell","description":"A bell that behaves like one: each notification hits it, a burst rings harder, and the clapper lags behind on its own.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/notification-bell.tsx","type":"registry:component","content":"// Hairline UI · notification-bell · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { INTERACTION_FOCUS, INTERACTION_PRESS, MATERIAL_LIFT, createSpring, useInteractionReducedMotion, type Spring } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * NOTIFICATION BELL: a bell that behaves like one\n *\n *   ring     a new notification hits the bell: it takes a push\n *            sized by how many came, added to whatever swing it\n *            already has, so a burst rings harder instead of\n *            starting over\n *   clapper  nothing animates it: it reads the bell's speed and\n *            falls behind on a softer spring of its own\n *   badge    jumps with each hit and leans against the swing; the\n *            count rolls up or down\n *   read     the count falling never rings; at zero the badge\n *            shrinks away\n *\n * Reduced motion: the count changes in place and the bell stays still.\n * ───────────────────────────────────────────────────────── */\n\nexport interface NotificationBellProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, \"children\"> {\n  /** Unread notifications. Going up rings the bell. */\n  count?: number;\n  /** Above this the badge says \"99+\". */\n  max?: number;\n  /** \"dot\" hides the number. */\n  variant?: \"count\" | \"dot\";\n  /** Diameter in px. */\n  size?: number;\n  /** The button's name; the count is added to it. */\n  label?: string;\n  /** Change this to ring without changing the count. */\n  ringKey?: string | number;\n}\n\n// A heavy thing on a light hinge: it keeps swinging for a while. Speeds are degrees per second.\nconst SWING = { stiffness: 150, damping: 3.4 };\nconst CLAPPER = { stiffness: 210, damping: 8 };\nconst BADGE = { stiffness: 420, damping: 15 };\nconst HIT = 210;\nconst HIT_MOST = 360;\nconst FASTEST = 480;\nconst CLAPPER_LAG = 0.058;\nconst CLAPPER_MOST = 24;\nconst BADGE_LEAN = 0.11;\n\nconst BELL = \"M12 2.2a1.35 1.35 0 0 0-1.33 1.59C7.87 4.42 6 6.87 6 9.9v2.72c0 1.1-.46 2.16-1.27 2.91l-.52.48c-.84.78-.29 2.19.86 2.19h13.86c1.15 0 1.7-1.41.86-2.19l-.52-.48A3.97 3.97 0 0 1 18 12.62V9.9c0-3.03-1.87-5.48-4.67-6.11A1.35 1.35 0 0 0 12 2.2Z\";\n\nconst clamp = (n: number, limit: number) => Math.max(-limit, Math.min(limit, n));\n\nconst ROLL_FORMAT: Intl.NumberFormatOptions = { maximumFractionDigits: 0, useGrouping: false };\n\nexport function NotificationBell({ count = 0, max = 99, variant = \"count\", size = 44, label = \"Notifications\", ringKey, className = \"\", style, onPointerEnter, ...props }: NotificationBellProps) {\n  const reduced = useInteractionReducedMotion();\n  const total = Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0;\n\n  const bodyRef = React.useRef<SVGGElement>(null);\n  const clapperRef = React.useRef<SVGGElement>(null);\n  const badgeRef = React.useRef<HTMLSpanElement>(null);\n  const shineId = React.useId();\n  const springs = React.useRef<{ swing: Spring; clapper: Spring; badge: Spring } | null>(null);\n\n  // The badge keeps its last number while it shrinks away, so it never empties on the way out.\n  const [shown, setShown] = React.useState(total);\n  if (total > 0 && total !== shown) setShown(total);\n\n  const previous = React.useRef(total);\n\n  React.useLayoutEffect(() => {\n    const paint = () => {\n      const s = springs.current;\n      if (!s) return;\n      const swing = s.swing.get();\n      bodyRef.current?.setAttribute(\"transform\", `rotate(${swing.toFixed(2)} 12 3.4)`);\n      // The clapper hangs from the bell: while the bell moves one way, it's left behind the other way.\n      s.clapper.set(clamp(-s.swing.getVelocity() * CLAPPER_LAG, CLAPPER_MOST));\n      clapperRef.current?.setAttribute(\"transform\", `rotate(${s.clapper.get().toFixed(2)} 12 17)`);\n      const badge = badgeRef.current;\n      if (badge) {\n        const scale = Math.max(0, s.badge.get());\n        badge.style.transform = `translate3d(${(-swing * BADGE_LEAN).toFixed(2)}px, 0, 0) scale(${scale.toFixed(3)})`;\n        badge.style.opacity = `${Math.min(1, scale * 2.5)}`;\n      }\n    };\n    const s = {\n      swing: createSpring(0, SWING, paint, 0.02),\n      clapper: createSpring(0, CLAPPER, paint, 0.02),\n      badge: createSpring(previous.current > 0 ? 1 : 0, BADGE, paint, 0.002),\n    };\n    springs.current = s;\n    paint();\n    return () => {\n      s.swing.stop();\n      s.clapper.stop();\n      s.badge.stop();\n      springs.current = null;\n    };\n  }, []);\n\n  const hit = React.useCallback((strength: number) => {\n    const s = springs.current;\n    if (!s) return;\n    const moving = s.swing.getVelocity();\n    // With the swing it's moving in, so a second hit adds to it; capped so a flood doesn't spin the bell over.\n    const along = moving === 0 ? (s.swing.get() > 0 ? -1 : 1) : Math.sign(moving);\n    s.swing.push(clamp(moving + along * strength, FASTEST) - moving);\n  }, []);\n\n  React.useEffect(() => {\n    const s = springs.current;\n    const delta = total - previous.current;\n    previous.current = total;\n    if (!s) return;\n    if (reduced) {\n      s.badge.jump(total > 0 ? 1 : 0);\n      return;\n    }\n    s.badge.set(total > 0 ? 1 : 0);\n    if (delta <= 0) return;\n    hit(HIT + (HIT_MOST - HIT) * (Math.min(delta, 5) / 5));\n    s.badge.push(Math.min(delta, 5) * 0.9 + 2.4);\n  }, [total, reduced, hit]);\n\n  const lastRing = React.useRef(ringKey);\n  React.useEffect(() => {\n    if (lastRing.current === ringKey) return;\n    lastRing.current = ringKey;\n    if (!reduced) hit(HIT);\n  }, [ringKey, reduced, hit]);\n\n  const dot = variant === \"dot\";\n  const name = total > 0 ? `${label}, ${total} unread` : label;\n  const over = shown > max;\n  const badgeSize = size * (dot ? 0.24 : 0.42);\n\n  return (\n    <span className=\"relative inline-flex\">\n      <button\n        type=\"button\"\n        aria-label={name}\n        {...props}\n        onPointerEnter={(event) => {\n          onPointerEnter?.(event);\n          // A nudge under the mouse, so it plainly hangs loose.\n          if (event.pointerType === \"mouse\" && !reduced && Math.abs(springs.current?.swing.getVelocity() ?? 0) < 40) hit(46);\n        }}\n        className={`relative grid cursor-pointer place-items-center rounded-full bg-[linear-gradient(to_bottom,var(--background),color-mix(in_oklab,var(--foreground)_4%,var(--background)))] text-foreground ${MATERIAL_LIFT} ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${className}`}\n        style={{ width: size, height: size, ...style }}\n      >\n        <svg viewBox=\"0 0 24 24\" aria-hidden=\"true\" className=\"overflow-visible [contain:layout]\" style={{ width: size * 0.58, height: size * 0.58 }}>\n          <defs>\n            {/* Polished metal: a band of light down the left of the dome, falling away to the right. */}\n            <linearGradient id={shineId} x1=\"0\" x2=\"1\" y1=\"0\" y2=\"0.18\">\n              <stop offset=\"0.08\" stopColor=\"var(--background)\" stopOpacity=\"0.06\" />\n              <stop offset=\"0.3\" stopColor=\"var(--background)\" stopOpacity=\"0.5\" />\n              <stop offset=\"0.5\" stopColor=\"var(--background)\" stopOpacity=\"0.12\" />\n              <stop offset=\"1\" stopColor=\"var(--background)\" stopOpacity=\"0\" />\n            </linearGradient>\n          </defs>\n          <g ref={bodyRef}>\n            {/* Behind the body, so only the part below the rim shows. */}\n            <g ref={clapperRef}>\n              <path d=\"M12 16.5v3.1\" stroke=\"currentColor\" strokeWidth=\"1.1\" strokeLinecap=\"round\" />\n              <circle cx=\"12\" cy=\"20.6\" r=\"1.95\" fill=\"var(--primary)\" />\n            </g>\n            <path fill=\"currentColor\" d={BELL} />\n            <path fill={`url(#${shineId})`} d={BELL} />\n            {/* The rim: a bright lip along the flare, so the mouth of the bell reads as a separate edge. */}\n            <path d=\"M5.2 16.3c1.6.5 3.9.8 6.8.8s5.2-.3 6.8-.8\" fill=\"none\" stroke=\"var(--background)\" strokeOpacity=\"0.34\" strokeWidth=\"0.7\" strokeLinecap=\"round\" />\n          </g>\n        </svg>\n      </button>\n\n      <span\n        ref={badgeRef}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute grid origin-center place-items-center rounded-full bg-primary font-semibold leading-none text-primary-foreground will-change-transform\"\n        style={{\n          right: dot ? size * 0.15 : size * 0.02,\n          top: dot ? size * 0.13 : size * -0.04,\n          height: badgeSize,\n          minWidth: badgeSize,\n          padding: dot ? 0 : `0 ${size * 0.08}px`,\n          fontSize: size * 0.235,\n          boxShadow: \"0 0 0 2px var(--background)\",\n          transform: \"scale(0)\",\n        }}\n      >\n        {!dot && <NumberRoll value={Math.min(shown, max)} format={ROLL_FORMAT} suffix={over ? \"+\" : \"\"} duration={620} />}\n      </span>\n\n      <span role=\"status\" className=\"sr-only\">\n        {total > 0 ? `${total} unread` : \"\"}\n      </span>\n    </span>\n  );\n}\n\nexport default NotificationBell;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · notification-bell · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/notification-bell. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}