{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"badge-counter","type":"registry:component","title":"Badge counter","description":"Rolls its digits the way the count moved and bumps each time it changes.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/badge-counter.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  AnimatePresence,\n  motion,\n  type AnimationPlaybackControls,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Kicked from rest at 1, this spring peaks near 1.15 about 70ms in, dips\n// once to ~0.97 and settles. A spring (not keyframes) so a burst of changes\n// keeps the bump alive instead of restarting it from zero each time.\nconst BUMP = { type: \"spring\", stiffness: 600, damping: 20 } as const;\nconst BUMP_VELOCITY = 6.5;\n// Anything above this shows as \"99+\", which is all anyone reads anyway.\nconst CAP = 99;\n// A single digit sits in a circle this wide; more digits grow a pill.\nconst MIN_WIDTH = 20;\nconst PADDING_X = 12;\n\ntype Slot = { key: string; char: string };\n\n// Keyed by place value from the right, so only the digits that change roll\n// and the ones digit stays the ones digit when a tens digit arrives. When\n// capped, the two nines keep their slots and only the \"+\" is new.\nfunction slots(count: number): Slot[] {\n  if (count > CAP) {\n    return [\n      { key: \"2\", char: \"9\" },\n      { key: \"1\", char: \"9\" },\n      { key: \"plus\", char: \"+\" },\n    ];\n  }\n  const digits = String(count).split(\"\");\n  return digits.map((char, i) => ({ key: String(digits.length - i), char }));\n}\n\nexport function BadgeCounter({\n  count,\n  label = \"Inbox\",\n  noun = \"unread\",\n  onClick,\n  icon,\n  className,\n}: {\n  count: number;\n  label?: string;\n  noun?: string;\n  onClick?: () => void;\n  /** Replaces the inbox glyph; should be a 20px currentColor icon. */\n  icon?: React.ReactNode;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const bumpRef = useRef<HTMLSpanElement>(null);\n  const bump = useRef<AnimationPlaybackControls>(undefined);\n  const [prev, setPrev] = useState(count);\n  const [direction, setDirection] = useState(1);\n  if (prev !== count) {\n    setDirection(count > prev ? 1 : -1);\n    setPrev(count);\n  }\n\n  const lastCount = useRef(count);\n  useEffect(() => {\n    const was = lastCount.current;\n    lastCount.current = count;\n    // Appearing from zero already has its own entrance, and a capped badge\n    // shows the same \"99+\", so neither gets a bump.\n    if (was === count || was === 0 || count === 0) return;\n    if (was > CAP && count > CAP) return;\n    if (reduceMotion || !bumpRef.current) return;\n    bump.current?.stop();\n    bump.current = animate(\n      bumpRef.current,\n      { scale: 1 },\n      { ...BUMP, velocity: BUMP_VELOCITY },\n    );\n  }, [count, reduceMotion]);\n  useEffect(() => () => bump.current?.stop(), []);\n\n  const shown = count > CAP ? `${CAP}+` : String(count);\n  const summary =\n    count > 0 ? `${label}, ${shown} ${noun}` : `${label}, nothing ${noun}`;\n\n  return (\n    <span className={cn(\"relative inline-flex\", className)}>\n      <button\n        type=\"button\"\n        aria-label={summary}\n        onClick={onClick}\n        className=\"flex size-10 touch-manipulation items-center justify-center rounded-full bg-muted text-foreground shadow-raised outline-hidden transition-[scale,background-color] duration-150 ease-out select-none hover:bg-background focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[background-color]\"\n      >\n        {icon ?? <InboxGlyph />}\n      </button>\n\n      {/* Its left edge is pinned just inside the corner, so growing from one\n          digit to two widens it outward, away from the icon. */}\n      <AnimatePresence initial={false}>\n        {count > 0 && (\n          <motion.span\n            key=\"badge\"\n            aria-hidden\n            className=\"pointer-events-none absolute -top-1 left-[calc(100%-18px)] origin-bottom-left\"\n            initial={{\n              scale: reduceMotion ? 1 : 0.5,\n              opacity: 0,\n              filter: reduceMotion ? \"blur(0px)\" : \"blur(2px)\",\n            }}\n            animate={{\n              scale: 1,\n              opacity: 1,\n              filter: \"blur(0px)\",\n              transition: reduceMotion\n                ? { duration: 0.15 }\n                : {\n                    type: \"spring\",\n                    duration: 0.35,\n                    bounce: 0.3,\n                    // A spring overshoots, and blur below zero is invalid.\n                    filter: { duration: 0.2, ease: EASE_OUT },\n                  },\n            }}\n            // Clearing to zero is a soft shrink, quicker and without bounce.\n            exit={{\n              scale: reduceMotion ? 1 : 0.6,\n              opacity: 0,\n              filter: reduceMotion ? \"blur(0px)\" : \"blur(2px)\",\n              transition: { duration: 0.18, ease: EASE_OUT },\n            }}\n          >\n            <span ref={bumpRef} className=\"block origin-center\">\n              <Pill count={count} direction={direction} />\n            </span>\n          </motion.span>\n        )}\n      </AnimatePresence>\n\n      <span className=\"sr-only\" aria-live=\"polite\" aria-atomic>\n        {summary}\n      </span>\n    </span>\n  );\n}\n\nfunction Pill({ count, direction }: { count: number; direction: number }) {\n  const reduceMotion = useReducedMotion();\n  const text = useRef<HTMLSpanElement>(null);\n  const [width, setWidth] = useState(MIN_WIDTH);\n  // New places that arrive after mount (9 to 10) roll in; the first render\n  // does not.\n  const [ready, setReady] = useState(false);\n\n  useEffect(() => {\n    const frame = requestAnimationFrame(() => setReady(true));\n    const node = text.current;\n    if (!node) return () => cancelAnimationFrame(frame);\n    // Width is animated (not scale) because the pill must grow around its\n    // digits without stretching them; it is a 20px element, so the layout\n    // cost is negligible. Measured, so any font size just works.\n    const observer = new ResizeObserver(() => {\n      setWidth(Math.max(MIN_WIDTH, Math.ceil(node.offsetWidth) + PADDING_X));\n    });\n    observer.observe(node);\n    return () => {\n      cancelAnimationFrame(frame);\n      observer.disconnect();\n    };\n  }, []);\n\n  const custom = { direction, reduceMotion };\n\n  return (\n    <span\n      style={{ width }}\n      className={cn(\n        // text-background on danger clears 4.5:1 in both themes (5.2 light,\n        // 5.3 dark), and the ring cuts it cleanly off the button.\n        \"flex h-5 items-center justify-center overflow-hidden rounded-full bg-destructive text-[12px] leading-5 font-semibold text-background tabular-nums ring-2 ring-background\",\n        \"transition-[width] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n      )}\n    >\n      <span ref={text} className=\"flex\">\n        {slots(count).map((slot) => (\n          <span key={slot.key} className=\"inline-grid overflow-hidden\">\n            <AnimatePresence initial={ready} custom={custom}>\n              <motion.span\n                key={slot.char}\n                custom={custom}\n                variants={ROLL}\n                initial=\"enter\"\n                animate=\"center\"\n                exit=\"exit\"\n                className=\"col-start-1 row-start-1\"\n              >\n                {slot.char}\n              </motion.span>\n            </AnimatePresence>\n          </span>\n        ))}\n      </span>\n    </span>\n  );\n}\n\ntype Roll = { direction: number; reduceMotion: boolean | null };\n\n// Counting up brings the new digit in from below and sends the old one up,\n// like an odometer; counting down runs the other way.\nconst ROLL = {\n  enter: ({ direction, reduceMotion }: Roll) => ({\n    y: reduceMotion ? \"0%\" : `${direction * 100}%`,\n    opacity: 0,\n  }),\n  center: {\n    y: \"0%\",\n    opacity: 1,\n    transition: { duration: 0.24, ease: EASE_OUT },\n  },\n  // Leaves sooner than the new digit arrives, so the two never tangle.\n  exit: ({ direction, reduceMotion }: Roll) => ({\n    y: reduceMotion ? \"0%\" : `${direction * -100}%`,\n    opacity: 0,\n    transition: { duration: 0.18, ease: EASE_OUT },\n  }),\n};\n\nfunction InboxGlyph() {\n  return (\n    <svg\n      viewBox=\"0 0 24 24\"\n      className=\"size-5\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.75}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      aria-hidden\n    >\n      <path d=\"M22 12h-6l-2 3h-4l-2-3H2\" />\n      <path d=\"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11Z\" />\n    </svg>\n  );\n}\n\n// Holding a stepper repeats: a pause first so a click stays a single step,\n// then quick enough that reaching \"99+\" takes a few seconds.\nconst HOLD_DELAY = 380;\nconst HOLD_EVERY = 70;\n\nfunction Stepper({\n  label,\n  onStep,\n  disabled,\n  children,\n}: {\n  label: string;\n  onStep: () => void;\n  disabled?: boolean;\n  children: React.ReactNode;\n}) {\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const repeat = useRef<ReturnType<typeof setInterval>>(undefined);\n  const fromPointer = useRef(false);\n  const step = useRef(onStep);\n  useEffect(() => {\n    step.current = onStep;\n  });\n\n  const stop = () => {\n    clearTimeout(timer.current);\n    clearInterval(repeat.current);\n  };\n  useEffect(() => stop, []);\n  useEffect(() => {\n    if (disabled) stop();\n  }, [disabled]);\n\n  return (\n    <button\n      type=\"button\"\n      aria-label={label}\n      disabled={disabled}\n      onPointerDown={(e) => {\n        if (e.button !== 0) return;\n        fromPointer.current = true;\n        step.current();\n        stop();\n        timer.current = setTimeout(() => {\n          repeat.current = setInterval(() => step.current(), HOLD_EVERY);\n        }, HOLD_DELAY);\n      }}\n      onPointerUp={stop}\n      onPointerLeave={stop}\n      onPointerCancel={stop}\n      onClick={() => {\n        // Pointer presses already stepped on pointerdown; this path is the\n        // keyboard's (Enter and Space).\n        if (fromPointer.current) {\n          fromPointer.current = false;\n          return;\n        }\n        onStep();\n      }}\n      className=\"flex size-7 touch-manipulation items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[scale,color,background-color,opacity] duration-150 ease-out select-none hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-[color,background-color,opacity]\"\n    >\n      <svg\n        viewBox=\"0 0 16 16\"\n        className=\"size-3.5\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.75}\n        strokeLinecap=\"round\"\n        aria-hidden\n      >\n        {children}\n      </svg>\n    </button>\n  );\n}\n\n// The index card's hover show: a few messages land (the pill widens at 10),\n// the inbox gets opened and clears, then mail starts arriving again. Each\n// entry is [wait before it in ms, count]; the waits leave room for the roll\n// and the bump to finish before the next change.\nconst SHOW: [number, number][] = [\n  [350, 9],\n  [420, 10],\n  [420, 11],\n  [420, 12],\n  [1500, 0],\n  [1100, 8],\n];\n// A calm beat before the show starts over, so it never feels like a loop.\nconst SHOW_REST = 1400;\nconst REST_COUNT = 8;\n\nexport default function BadgeCounterDemo() {\n  const [count, setCount] = useState(REST_COUNT);\n  const play = usePreviewPlay();\n\n  useEffect(() => {\n    if (play !== true) return;\n    let timer: ReturnType<typeof setTimeout>;\n    const step = (i: number) => {\n      const [wait, value] = SHOW[i % SHOW.length];\n      const rest = i > 0 && i % SHOW.length === 0 ? SHOW_REST : 0;\n      timer = setTimeout(() => {\n        setCount(value);\n        step(i + 1);\n      }, wait + rest);\n    };\n    step(0);\n    // Unhovering rolls (or pops) back to the resting count.\n    return () => {\n      clearTimeout(timer);\n      setCount(REST_COUNT);\n    };\n  }, [play]);\n\n  return (\n    <div className=\"flex flex-col items-center gap-5\">\n      {/* Opening the inbox reads everything, which is how you see the badge\n          shrink away. */}\n      <BadgeCounter count={count} onClick={() => setCount(0)} />\n      <div className=\"flex items-center gap-1\">\n        <Stepper\n          label=\"One fewer message\"\n          disabled={count === 0}\n          onStep={() => setCount((c) => Math.max(0, c - 1))}\n        >\n          <path d=\"M3.5 8h9\" />\n        </Stepper>\n        <Stepper\n          label=\"One more message\"\n          disabled={count >= 150}\n          onStep={() => setCount((c) => Math.min(150, c + 1))}\n        >\n          <path d=\"M8 3.5v9M3.5 8h9\" />\n        </Stepper>\n      </div>\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"cssVars":{"light":{"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":{"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":{"shadow-raised":"var(--shadow-raised)"}},"categories":["feedback"],"docs":"From ui lab: https://lab.xevrion.dev/lab/badge-counter"}