{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "number-animation",
  "title": "Number Animation",
  "description": "Animated number and rolling digit ticker for changing values.",
  "registryDependencies": [
    "@pestoui/style",
    "@pestoui/utils"
  ],
  "files": [
    {
      "path": "pestoui/ui/number-animation.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/* Every column holds all ten glyphs and slides to expose one. Building the list\n   once at module scope keeps the render free of throwaway arrays. */\nconst GLYPHS = Array.from({ length: 10 }, (_, glyph) => glyph)\n\n/* ---------------------------------------------------------------------------\n   Shared start trigger\n\n   Both components animate *from* a resting state, so both need the same answer\n   to \"when does the animation begin\". Deferring to the next frame is not a nice\n   touch, it is load-bearing for the ticker: the columns have to paint once at\n   zero before their translate changes, or the browser has no start value to\n   transition from and the digits simply appear in place.\n*/\nfunction useStartTrigger(\n  startOnView: boolean,\n  forwardedRef: React.Ref<HTMLSpanElement> | undefined\n) {\n  const nodeRef = React.useRef<HTMLSpanElement | null>(null)\n  const [started, setStarted] = React.useState(false)\n\n  /* Compose rather than clobber — the observer needs the node, and a consumer\n     that passed a ref still gets it. */\n  const ref = React.useCallback(\n    (node: HTMLSpanElement | null) => {\n      nodeRef.current = node\n      if (typeof forwardedRef === \"function\") return forwardedRef(node)\n      if (forwardedRef) forwardedRef.current = node\n    },\n    [forwardedRef]\n  )\n\n  React.useEffect(() => {\n    const node = nodeRef.current\n\n    if (!startOnView || !node || typeof IntersectionObserver === \"undefined\") {\n      const frame = requestAnimationFrame(() => setStarted(true))\n      return () => cancelAnimationFrame(frame)\n    }\n\n    const observer = new IntersectionObserver(\n      (entries) => {\n        if (!entries.some((entry) => entry.isIntersecting)) return\n        setStarted(true)\n        /* One-shot: a number that re-rolls every time it scrolls past reads as\n           a glitch, not a reveal. */\n        observer.disconnect()\n      },\n      { threshold: 0.35 }\n    )\n\n    observer.observe(node)\n    return () => observer.disconnect()\n  }, [startOnView])\n\n  return { ref, started }\n}\n\n/* ---------------------------------------------------------------------------\n   NumberTicker\n*/\n\ntype TickerCell =\n  | { key: string; kind: \"digit\"; digit: number; stagger: number }\n  | { key: string; kind: \"static\"; text: string }\n\n/* Flattens a value into positioned cells plus the plain string assistive tech\n   receives.\n\n   The keys are the whole trick. A digit is identified by its PLACE VALUE — ones\n   are 0, tens 1, hundreds 2, and the fractional side runs negative — never by\n   its index in the array. Index keys break the moment the number changes width:\n   going 99 -> 100 shifts every index by one, so React would tear down the two\n   nines and mount three fresh columns, animating digits that did not change.\n   Keyed by place, the ones and tens columns survive and roll 9 -> 0 while the\n   new hundreds column mounts already showing its 1, on the left, silently.\n\n   Group separators are keyed by the place they sit in front of for the same\n   reason: the comma in 1,234 and the comma in 12,345 are the same node.\n*/\nfunction toCells(\n  value: number,\n  decimals: number,\n  separator: string,\n  prefix: string,\n  suffix: string\n): { cells: TickerCell[]; text: string } {\n  const safe = Number.isFinite(value) ? value : 0\n  const places = Math.max(0, Math.min(20, Math.trunc(decimals)))\n  const fixed = Math.abs(safe).toFixed(places)\n  const [intPart, fracPart = \"\"] = fixed.split(\".\")\n  const fracLength = fracPart.length\n\n  const cells: TickerCell[] = []\n  let text = \"\"\n\n  const pushStatic = (key: string, chunk: string) => {\n    if (!chunk) return\n    cells.push({ key, kind: \"static\", text: chunk })\n    text += chunk\n  }\n\n  /* Sign leads the prefix — a negative currency reads \"-$5\", not \"$-5\". */\n  pushStatic(\"sign\", safe < 0 ? \"-\" : \"\")\n  pushStatic(\"prefix\", prefix)\n\n  for (let i = 0; i < intPart.length; i++) {\n    const place = intPart.length - 1 - i\n\n    if (separator && i > 0 && (place + 1) % 3 === 0) {\n      pushStatic(`group-${place}`, separator)\n    }\n\n    cells.push({\n      key: `digit-${place}`,\n      kind: \"digit\",\n      digit: Number(intPart[i]),\n      /* Stagger counts digits to the right, so the ones column leaves first and\n         the leading digit lands last — the order a geared odometer moves in. */\n      stagger: place + fracLength,\n    })\n    text += intPart[i]\n  }\n\n  if (fracLength > 0) {\n    pushStatic(\"point\", \".\")\n\n    for (let i = 0; i < fracLength; i++) {\n      cells.push({\n        key: `digit-${-(i + 1)}`,\n        kind: \"digit\",\n        digit: Number(fracPart[i]),\n        stagger: fracLength - 1 - i,\n      })\n      text += fracPart[i]\n    }\n  }\n\n  pushStatic(\"suffix\", suffix)\n\n  return { cells, text }\n}\n\ninterface NumberTickerProps\n  extends Omit<React.ComponentProps<\"span\">, \"children\" | \"prefix\"> {\n  /** The number to display. Rolls to any new value it is given. */\n  value: number\n  /** Fixed number of decimal places. Fixed on purpose — a width that changes\n   *  with the value would re-key the columns on every update. */\n  decimals?: number\n  /** Thousands separator. Pass an empty string to group nothing. */\n  separator?: string\n  prefix?: string\n  suffix?: string\n  /** Hold at zero until the ticker scrolls into view, then roll once. */\n  startOnView?: boolean\n}\n\n/* Rolling odometer. Each digit position is a window one glyph tall clipping a\n   column of all ten, and the column translates by -(digit x --digit-height) to\n   bring the right one into frame.\n\n   The height comes from `digit-column`, which pins it to its own token rather\n   than to body leading. Deriving it from a line-height would couple the ticker\n   to typography and move layout the next time type is retuned.\n*/\nfunction NumberTicker({\n  className,\n  value,\n  decimals = 0,\n  separator = \",\",\n  prefix = \"\",\n  suffix = \"\",\n  startOnView = false,\n  ref,\n  ...props\n}: NumberTickerProps) {\n  const trigger = useStartTrigger(startOnView, ref)\n  const { cells, text } = toCells(value, decimals, separator, prefix, suffix)\n\n  return (\n    <span\n      ref={trigger.ref}\n      data-slot=\"number-ticker\"\n      /* `digit-column` here establishes --digit-height and tabular leading for\n         the whole ticker, so separators and columns share one baseline. */\n      className={cn(\"digit-column relative inline-flex items-center\", className)}\n      {...props}\n    >\n      <span className=\"sr-only\">{text}</span>\n      {/* Selecting the glyph stack would copy all ten digits of every column;\n          the sr-only string above is the copyable one. */}\n      <span aria-hidden=\"true\" className=\"inline-flex items-center select-none\">\n        {cells.map((cell) => {\n          if (cell.kind === \"static\") {\n            return (\n              <span key={cell.key} data-slot=\"number-ticker-static\">\n                {cell.text}\n              </span>\n            )\n          }\n\n          /* Before the trigger fires every column sits at zero, so the ticker\n             already holds the target's exact shape and rolls into it — nothing\n             reflows when the real digits arrive. */\n          const offset = trigger.started ? cell.digit : 0\n\n          return (\n            <span\n              key={cell.key}\n              data-slot=\"number-ticker-digit\"\n              className=\"inline-block overflow-hidden\"\n              style={{ height: \"var(--digit-height)\" }}\n            >\n              <span\n                className=\"digit-column flex flex-col\"\n                style={{\n                  translate: `0 calc(${offset} * var(--digit-height) * -1)`,\n                  transitionDelay: `calc(${cell.stagger} * var(--stagger-base))`,\n                }}\n              >\n                {GLYPHS.map((glyph) => (\n                  <span key={glyph}>{glyph}</span>\n                ))}\n              </span>\n            </span>\n          )\n        })}\n      </span>\n    </span>\n  )\n}\n\n/* ---------------------------------------------------------------------------\n   AnimatedNumber\n*/\n\nconst formatCount = (n: number, locale?: string) => Math.round(n).toLocaleString(locale)\n\ninterface AnimatedNumberProps\n  extends Omit<React.ComponentProps<\"span\">, \"children\"> {\n  /** Target value. Changing it re-aims the count from wherever it currently is. */\n  value: number\n  /** Count duration in milliseconds. */\n  duration?: number\n  /** Hold at zero until the number scrolls into view, then count once. */\n  startOnView?: boolean\n  /** Renders the in-flight value. Also renders the announced target. */\n  format?: (n: number) => string\n  /** Locale for the default format's digit grouping; the browser's own when\n   *  unset. Set it on a server-rendered page, so the server's markup and the\n   *  browser's first render agree. Unused when `format` is given. */\n  locale?: string\n}\n\n/* Plain count-up: one value interpolated to the next on a rAF loop.\n\n   Duration-eased rather than spring-driven, and that is not a stylistic call.\n   Every spring in the system except the overdamped pair crosses its target\n   before settling, and a counter that crosses its target briefly displays a\n   number that was never true. Overshoot is free on a knob and wrong on a\n   quantity, so this one eases out and approaches from a single side.\n*/\nfunction AnimatedNumber({\n  className,\n  value,\n  duration = 1200,\n  startOnView = false,\n  locale,\n  format = (n) => formatCount(n, locale),\n  ref,\n  ...props\n}: AnimatedNumberProps) {\n  const trigger = useStartTrigger(startOnView, ref)\n  const [display, setDisplay] = React.useState(0)\n  /* The rendered value mirrored outside React state so a value change landing\n     mid-flight can pick up from the frame actually on screen. */\n  const displayRef = React.useRef(0)\n  const frameRef = React.useRef<number | null>(null)\n  const target = Number.isFinite(value) ? value : 0\n\n  React.useEffect(() => {\n    if (!trigger.started) return\n\n    const from = displayRef.current\n    const settle = () => {\n      displayRef.current = target\n      setDisplay(target)\n    }\n\n    /* The one place a media query belongs in code. Reduced motion is handled in\n       the token layer for everything that animates in CSS, but a rAF loop\n       cannot read a collapsed duration token — the preference has to be asked\n       for directly. Answer: skip the travel, show the number. */\n    const prefersReducedMotion =\n      typeof window !== \"undefined\" &&\n      window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n\n    if (prefersReducedMotion || duration <= 0 || from === target) {\n      settle()\n      return\n    }\n\n    let startTime: number | null = null\n\n    const tick = (now: number) => {\n      startTime ??= now\n      const elapsed = Math.min(1, (now - startTime) / duration)\n\n      if (elapsed < 1) {\n        /* ease-out-quart, the JS counterpart of the bezier of the same name. */\n        const eased = 1 - Math.pow(1 - elapsed, 4)\n        const next = from + (target - from) * eased\n        displayRef.current = next\n        setDisplay(next)\n        frameRef.current = requestAnimationFrame(tick)\n      } else {\n        /* Land on the exact target rather than on the last eased sample. */\n        frameRef.current = null\n        settle()\n      }\n    }\n\n    frameRef.current = requestAnimationFrame(tick)\n\n    /* Fires on unmount and on every re-aim, so an in-flight frame is always\n       dropped before a second loop can start against the same state. */\n    return () => {\n      if (frameRef.current === null) return\n      cancelAnimationFrame(frameRef.current)\n      frameRef.current = null\n    }\n  }, [target, duration, trigger.started])\n\n  return (\n    <span\n      ref={trigger.ref}\n      data-slot=\"animated-number\"\n      /* Tabular figures so the box does not twitch as digits change width. */\n      className={cn(\"relative inline-flex items-center tabular-nums\", className)}\n      {...props}\n    >\n      {/* The target, not the frame. Announcing every tick would flood a screen\n          reader with a hundred readings of a number that has not settled. */}\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {format(target)}\n      </span>\n      <span aria-hidden=\"true\">{format(display)}</span>\n    </span>\n  )\n}\n\nexport { NumberTicker, AnimatedNumber }\nexport type { NumberTickerProps, AnimatedNumberProps }\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}