{
  "schemaVersion": 1,
  "target": "react",
  "name": "animated-number",
  "version": "0.1.0",
  "category": "core",
  "title": "Animated Number",
  "description": "A formatted number whose changed digits move to the new value, by rolling like an odometer, springing in, or sliding with a quiet cross-fade.",
  "tags": [
    "number",
    "counter",
    "odometer",
    "currency",
    "percent",
    "intl",
    "motion"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/animated-number",
  "props": [
    {
      "name": "value",
      "type": "number",
      "description": "The number to show. Only digits that differ from the previous value move."
    },
    {
      "name": "format",
      "type": "Intl.NumberFormatOptions",
      "description": "Formatting, for example { style: \"currency\", currency: \"USD\" }, { style: \"percent\" } or { notation: \"compact\" }."
    },
    {
      "name": "locale",
      "type": "Intl.LocalesArgument",
      "description": "Locale for formatting. Defaults to the runtime locale."
    },
    {
      "name": "mode",
      "type": "\"fade\" | \"roll\" | \"pop\"",
      "default": "\"fade\"",
      "description": "fade slides a short way and cross-fades; roll turns each digit like an odometer wheel through every value between; pop springs the new digit in."
    },
    {
      "name": "trend",
      "type": "boolean",
      "default": "false",
      "description": "Tints changed digits green when the value rises and red when it falls, then fades back."
    },
    {
      "name": "live",
      "type": "boolean",
      "default": "false",
      "description": "Announces each new value once to screen readers through a polite live region."
    },
    {
      "name": "animated",
      "type": "boolean",
      "default": "true",
      "description": "Set to false to swap values instantly."
    },
    {
      "name": "stagger",
      "type": "number",
      "default": "0.035",
      "description": "Seconds between neighboring changed digits."
    }
  ],
  "accessibility": [
    "The formatted value is plain text in a visually hidden span; the moving digits are aria-hidden, so screen readers read the whole value once, never digit by digit.",
    "With live set, the hidden text sits in an aria-live=\"polite\" region and only the final value is announced after each change.",
    "Digits use tabular numbers, so columns keep their width while they move.",
    "Rising values move digits up and falling values move them down; the roll mode turns forward through 9 to 0 when the value carries.",
    "With reduced motion preferred, the value is plain text that changes instantly; the trend tint does not animate."
  ],
  "states": [
    "fade",
    "roll",
    "pop",
    "trend up",
    "trend down",
    "reduced motion"
  ],
  "files": [
    {
      "path": "ui/animated-number.tsx",
      "content": "\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n  useVelocity,\n  type AnimationPlaybackControls,\n  type Variants,\n} from \"motion/react\";\nimport { type ComponentProps, useEffect, useMemo, useRef, useState } from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nexport type AnimatedNumberMode = \"fade\" | \"roll\" | \"pop\";\n\nexport interface AnimatedNumberProps extends Omit<ComponentProps<\"span\">, \"children\"> {\n  /** The number to show. Only the digits that differ from the previous value move. */\n  value: number;\n  /** Intl formatting, for example `{ style: \"currency\", currency: \"USD\" }`, `{ style: \"percent\" }` or `{ notation: \"compact\" }`. */\n  format?: Intl.NumberFormatOptions;\n  /** Locale for formatting. Defaults to the runtime locale. */\n  locale?: Intl.LocalesArgument;\n  /**\n   * How changed digits move. `fade` slides a short way and cross-fades, `roll` turns each digit\n   * like an odometer wheel through every value in between, and `pop` springs the new digit in.\n   */\n  mode?: AnimatedNumberMode;\n  /** Tints the changed digits green when the value rises and red when it falls, then fades back. */\n  trend?: boolean;\n  /** Announces each new value to screen readers once, after it changes. Off by default so dashboards stay quiet. */\n  live?: boolean;\n  /** Set to false to swap values instantly. */\n  animated?: boolean;\n  /** Seconds between neighboring changed digits. */\n  stagger?: number;\n}\n\nconst ease = [0.23, 1, 0.32, 1] as const;\n\n/** Reduced-motion preference, read only after hydration so server and client render the same markup first. */\nfunction useReducedMotionAfterMount() {\n  const reduce = useReducedMotion();\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  return mounted && reduce === true;\n}\nconst DIGITS = \"0123456789\";\n\ntype Slot = { key: string; char: string; digit: boolean };\n\n/**\n * Turns formatted parts into keyed slots. Integer digits are keyed by place value (ones, tens,\n * ...) and fraction digits by position after the decimal, so 9.99 to 10.00 keeps each column\n * on its own place instead of shifting by string index.\n */\nfunction toSlots(parts: Intl.NumberFormatPart[]): Slot[] {\n  let integerCount = 0;\n  for (const part of parts) if (part.type === \"integer\") integerCount += part.value.length;\n\n  const slots: Slot[] = [];\n  const seen: Record<string, number> = {};\n  let integerSeen = 0;\n  let fractionSeen = 0;\n  for (const part of parts) {\n    if (part.type === \"integer\") {\n      for (const char of part.value) {\n        slots.push({ key: `i${integerCount - 1 - integerSeen}`, char, digit: true });\n        integerSeen += 1;\n      }\n    } else if (part.type === \"fraction\") {\n      for (const char of part.value) {\n        slots.push({ key: `f${fractionSeen}`, char, digit: true });\n        fractionSeen += 1;\n      }\n    } else if (part.type === \"group\") {\n      slots.push({ key: `g${integerCount - integerSeen}`, char: part.value, digit: false });\n    } else if (part.type === \"decimal\") {\n      slots.push({ key: \"d\", char: part.value, digit: false });\n    } else {\n      const side = integerSeen + fractionSeen > 0 ? \"post\" : \"pre\";\n      const name = `${side}-${part.type}`;\n      seen[name] = (seen[name] ?? 0) + 1;\n      slots.push({ key: `${name}-${seen[name]}`, char: part.value, digit: false });\n    }\n  }\n  return slots;\n}\n\ninterface Snapshot {\n  text: string;\n  value: number;\n  slots: Slot[];\n  /** 1 when the value rose, -1 when it fell, 0 on first render. */\n  direction: number;\n  /** Delay in seconds for each slot that changed in the last update. */\n  delays: Map<string, number>;\n  version: number;\n}\n\nfunction diff(previous: Snapshot, slots: Slot[], value: number, text: string, mode: AnimatedNumberMode, stagger: number): Snapshot {\n  const before = new Map(previous.slots.map((slot) => [slot.key, slot.char]));\n  const changed = slots.filter((slot) => slot.digit && before.has(slot.key) && before.get(slot.key) !== slot.char);\n  // An odometer turns from the ones column outward; fade and pop read left to right.\n  const ordered = mode === \"roll\" ? changed.slice().reverse() : changed;\n  const delays = new Map<string, number>();\n  ordered.forEach((slot, index) => delays.set(slot.key, index * stagger));\n  for (const slot of slots) if (!before.has(slot.key)) delays.set(slot.key, 0);\n  return {\n    text,\n    value,\n    slots,\n    direction: value === previous.value ? previous.direction : value > previous.value ? 1 : -1,\n    delays,\n    version: previous.version + 1,\n  };\n}\n\n// Fade: the old digit leaves the way the value moves and the new one arrives from the other\n// side, the same language as Number Input's stepper digits.\nconst fadeVariants: Variants = {\n  enter: ({ direction }: DigitCustom) => ({ y: direction >= 0 ? \"0.55em\" : \"-0.55em\", opacity: 0, filter: \"blur(2px)\" }),\n  center: ({ delay }: DigitCustom) => ({\n    y: \"0em\",\n    opacity: 1,\n    filter: \"blur(0px)\",\n    transition: { duration: 0.34, ease, delay },\n  }),\n  exit: ({ direction, delay }: DigitCustom) => ({\n    y: direction >= 0 ? \"-0.55em\" : \"0.55em\",\n    opacity: 0,\n    filter: \"blur(2px)\",\n    transition: { duration: 0.24, ease, delay },\n  }),\n};\n\n// Pop: the old digit shrinks away quickly; the new one springs up from below and overshoots its\n// line a touch before it settles. Opacity and blur run on a tween so the spring cannot push blur\n// below zero.\nconst popVariants: Variants = {\n  enter: ({ direction }: DigitCustom) => ({ y: direction >= 0 ? \"0.6em\" : \"-0.6em\", scale: 0.55, opacity: 0, filter: \"blur(4px)\" }),\n  center: ({ delay }: DigitCustom) => ({\n    y: \"0em\",\n    scale: 1,\n    opacity: 1,\n    filter: \"blur(0px)\",\n    transition: {\n      default: { type: \"spring\", visualDuration: 0.42, bounce: 0.4, delay: delay + 0.05 },\n      opacity: { duration: 0.18, ease, delay: delay + 0.05 },\n      filter: { duration: 0.26, ease, delay: delay + 0.05 },\n    },\n  }),\n  exit: ({ direction, delay }: DigitCustom) => ({\n    y: direction >= 0 ? \"-0.45em\" : \"0.45em\",\n    scale: 0.6,\n    opacity: 0,\n    filter: \"blur(3px)\",\n    transition: { duration: 0.16, ease, delay },\n  }),\n};\n\ntype DigitCustom = { direction: number; delay: number };\n\nfunction SwapDigit({ char, direction, delay, mode }: { char: string; direction: number; delay: number; mode: \"fade\" | \"pop\" }) {\n  const custom: DigitCustom = { direction, delay };\n  return (\n    <span className=\"relative inline-block\">\n      <AnimatePresence initial={false} mode=\"popLayout\" custom={custom}>\n        <motion.span\n          key={char}\n          custom={custom}\n          variants={mode === \"pop\" ? popVariants : fadeVariants}\n          initial=\"enter\"\n          animate=\"center\"\n          exit=\"exit\"\n          className=\"inline-block\"\n        >\n          {char}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  );\n}\n\n// Three turns of the wheel so a digit can travel up to nine steps either way and still show\n// a neighbor above and below.\nconst WHEEL = Array.from({ length: 30 }, (_, index) => index % 10);\n\n/**\n * One odometer wheel. Its position is continuous (10 to 20 at rest), so rising values always turn\n * the wheel forward through 9 to 0 and falling values turn it back. While it spins, a ghost copy\n * shows the neighbors above and below, faint and blurred in proportion to the speed.\n */\nfunction RollDigit({ char, direction, delay }: { char: string; direction: number; delay: number }) {\n  const digit = DIGITS.indexOf(char);\n  const position = useMotionValue(10 + Math.max(digit, 0));\n  const velocity = useVelocity(position);\n  const y = useTransform(position, (value) => `${(-value / 30) * 100}%`);\n  const blur = useTransform(velocity, (value) => `blur(${Math.min(Math.abs(value) / 18, 0.9).toFixed(2)}px)`);\n  const ghost = useTransform(velocity, (value) => Math.min(Math.abs(value) / 14, 1) * 0.3);\n  const controls = useRef<AnimationPlaybackControls | null>(null);\n\n  useEffect(() => {\n    if (digit < 0) return;\n    controls.current?.stop();\n    // Re-center the wheel in its middle turn, which looks identical, before measuring the trip.\n    const now = position.get();\n    const start = now - Math.floor(now / 10 - 1) * 10;\n    const steps = direction >= 0 ? (((digit - start) % 10) + 10) % 10 : (((start - digit) % 10) + 10) % 10;\n    if (steps < 0.001) return;\n    const speed = velocity.get();\n    position.jump(start);\n    const target = direction >= 0 ? start + steps : start - steps;\n    controls.current = animate(position, target, {\n      type: \"spring\",\n      visualDuration: Math.min(0.32 + steps * 0.045, 0.72),\n      bounce: 0.2,\n      velocity: speed,\n      delay,\n    });\n    return () => controls.current?.stop();\n    // The wheel moves only when its digit changes.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [digit]);\n\n  if (digit < 0) return <span className=\"inline-block\">{char}</span>;\n\n  const column = WHEEL.map((value, index) => (\n    <span key={index} className=\"block\">\n      {value}\n    </span>\n  ));\n\n  return (\n    <span className=\"relative inline-block\">\n      <span className=\"invisible\">{char}</span>\n      <span className=\"absolute inset-0 overflow-hidden\">\n        <motion.span style={{ y, filter: blur }} className=\"absolute inset-x-0 top-0 flex flex-col\">\n          {column}\n        </motion.span>\n      </span>\n      <motion.span\n        style={{ opacity: ghost }}\n        className=\"pointer-events-none absolute inset-x-0 -top-full h-[300%] overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,black_28%,transparent_33.4%,transparent_66.6%,black_72%,transparent)]\"\n      >\n        <motion.span style={{ y, filter: blur }} className=\"absolute inset-x-0 top-1/3 flex flex-col\">\n          {column}\n        </motion.span>\n      </motion.span>\n    </span>\n  );\n}\n\nconst slotTransition = { duration: 0.3, ease };\n\n/**\n * A formatted number whose changed digits animate while the rest stay still. Columns that appear\n * or disappear (999 to 1,000) fade in and out while their neighbors glide to their new places.\n * Screen readers get the formatted value as plain text; the moving digits are hidden from them.\n */\nexport function AnimatedNumber({\n  value,\n  format,\n  locale,\n  mode = \"fade\",\n  trend = false,\n  live = false,\n  animated = true,\n  stagger = 0.035,\n  className,\n  ...props\n}: AnimatedNumberProps) {\n  const reduceMotion = useReducedMotionAfterMount();\n  // Keyed by content, so an inline `format={{ ... }}` object does not rebuild the formatter each render.\n  const formatKey = JSON.stringify(format ?? {});\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  const formatter = useMemo(() => new Intl.NumberFormat(locale, format), [locale, formatKey]);\n  const text = formatter.format(value);\n\n  const [snapshot, setSnapshot] = useState<Snapshot>(() => ({\n    text,\n    value,\n    slots: toSlots(formatter.formatToParts(value)),\n    direction: 0,\n    delays: new Map(),\n    version: 0,\n  }));\n\n  // Derive the new snapshot during render so the diff is computed once per value change.\n  let current = snapshot;\n  if (snapshot.text !== text || snapshot.value !== value) {\n    current = diff(snapshot, toSlots(formatter.formatToParts(value)), value, text, mode, stagger);\n    setSnapshot(current);\n  }\n\n  const [tint, setTint] = useState<{ version: number; up: boolean } | null>(null);\n  useEffect(() => {\n    if (!trend || current.version === 0 || current.direction === 0) return;\n    setTint({ version: current.version, up: current.direction > 0 });\n    const timer = window.setTimeout(() => setTint(null), 900);\n    return () => window.clearTimeout(timer);\n  }, [trend, current.version, current.direction]);\n\n  const still = !animated || reduceMotion;\n\n  return (\n    <span className={cx(\"relative inline-flex whitespace-nowrap tabular-nums\", className)} {...props}>\n      <span className=\"sr-only select-none\" aria-live={live ? \"polite\" : undefined} aria-atomic={live ? true : undefined}>\n        {text}\n      </span>\n      {still ? (\n        <span aria-hidden=\"true\">{text}</span>\n      ) : (\n        <motion.span aria-hidden=\"true\" layoutRoot className=\"relative inline-flex select-none\">\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            {current.slots.map((slot) => {\n              const delay = current.delays.get(slot.key) ?? 0;\n              const tinted = tint && tint.version === current.version && current.delays.has(slot.key) && slot.digit;\n              return (\n                <motion.span\n                  key={slot.digit ? slot.key : `${slot.key}:${slot.char}`}\n                  layout=\"position\"\n                  initial={{ opacity: 0, scale: 0.8, filter: \"blur(3px)\" }}\n                  animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                  exit={{ opacity: 0, scale: 0.8, filter: \"blur(3px)\", transition: { duration: 0.18, ease } }}\n                  transition={slotTransition}\n                  className={cx(\n                    // The tint arrives quickly and drains back to the text color slowly.\n                    \"inline-block whitespace-pre transition-colors ease-out motion-reduce:transition-none\",\n                    !tinted\n                      ? \"duration-700\"\n                      : tint.up\n                        ? \"text-emerald-600 duration-150 dark:text-emerald-400\"\n                        : \"text-red-600 duration-150 dark:text-red-400\",\n                  )}\n                >\n                  {!slot.digit ? (\n                    slot.char\n                  ) : mode === \"roll\" ? (\n                    <RollDigit char={slot.char} direction={current.direction} delay={delay} />\n                  ) : (\n                    <SwapDigit char={slot.char} direction={current.direction} delay={delay} mode={mode} />\n                  )}\n                </motion.span>\n              );\n            })}\n          </AnimatePresence>\n        </motion.span>\n      )}\n    </span>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { AnimatedNumber } from \"@/components/shaken/ui/animated-number\";\n\nconst readings = [\n  { spend: 12480.32, runs: 7, hitRate: 0.934 },\n  { spend: 12496.05, runs: 9, hitRate: 0.941 },\n  { spend: 12611.8, runs: 12, hitRate: 0.928 },\n  { spend: 13004.12, runs: 8, hitRate: 0.917 },\n];\n\nexport default function AnimatedNumberExample() {\n  const [index, setIndex] = useState(0);\n  const reading = readings[index] ?? readings[0]!;\n\n  return (\n    <div className=\"grid w-full max-w-sm gap-4\">\n      <dl className=\"grid divide-y divide-zinc-950/[0.07] rounded-xl border border-zinc-950/10 bg-white dark:divide-white/[0.08] dark:border-white/10 dark:bg-black\">\n        <div className=\"grid gap-1 px-4 py-3.5\">\n          <dt className=\"text-xs font-medium text-zinc-500\">Spend this month</dt>\n          <dd className=\"text-2xl font-semibold tracking-[-0.01em] text-zinc-950 dark:text-white\">\n            <AnimatedNumber value={reading.spend} mode=\"roll\" format={{ style: \"currency\", currency: \"USD\" }} />\n          </dd>\n        </div>\n        <div className=\"grid grid-cols-2 divide-x divide-zinc-950/[0.07] dark:divide-white/[0.08]\">\n          <div className=\"grid gap-1 px-4 py-3\">\n            <dt className=\"text-xs font-medium text-zinc-500\">Runs in progress</dt>\n            <dd className=\"text-lg font-semibold text-zinc-950 dark:text-white\">\n              <AnimatedNumber value={reading.runs} mode=\"pop\" />\n            </dd>\n          </div>\n          <div className=\"grid gap-1 px-4 py-3\">\n            <dt className=\"text-xs font-medium text-zinc-500\">Cache hit rate</dt>\n            <dd className=\"text-lg font-semibold text-zinc-950 dark:text-white\">\n              <AnimatedNumber value={reading.hitRate} trend format={{ style: \"percent\", minimumFractionDigits: 1 }} />\n            </dd>\n          </div>\n        </div>\n      </dl>\n      <button\n        type=\"button\"\n        onClick={() => setIndex((current) => (current + 1) % readings.length)}\n        className=\"inline-flex h-8 w-fit items-center rounded-lg border border-zinc-950/12 bg-white px-3 text-sm font-medium text-zinc-950 transition-colors duration-150 ease-out hover:bg-zinc-950/[0.03] focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:border-white/15 dark:bg-black dark:text-white dark:hover:bg-white/[0.06]\"\n      >\n        Refresh\n      </button>\n    </div>\n  );\n}\n"
  }
}
