{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "number-ticker",
  "type": "registry:component",
  "title": "Number ticker",
  "description": "An odometer-style number for live metrics: each digit rolls on its own wheel when the value changes.",
  "categories": [
    "metrics"
  ],
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/number-ticker.tsx",
      "type": "registry:component",
      "target": "components/overtrue/number-ticker.tsx",
      "content": "\"use client\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useState,\n  useSyncExternalStore,\n  type ComponentProps,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type NumberTickerFormat = \"number\" | \"currency\" | \"percent\" | \"compact\";\n\nexport interface NumberTickerProps extends Omit<\n  ComponentProps<\"span\">,\n  \"children\" | \"prefix\"\n> {\n  value: number;\n  /** Preset Intl options. Percent expects a fraction: 0.124 renders 12.4%. */\n  format?: NumberTickerFormat;\n  /** Merged over the preset, e.g. `{ maximumFractionDigits: 0 }`. */\n  formatOptions?: Intl.NumberFormatOptions;\n  locale?: string;\n  /** ISO 4217 code used by the currency preset. */\n  currency?: string;\n  prefix?: ReactNode;\n  suffix?: ReactNode;\n  /** Roll duration in milliseconds. */\n  duration?: number;\n  /** Tint the number briefly: emerald when it rises, red when it falls. */\n  highlightChanges?: boolean;\n  /** Roll up from zero on first mount instead of rendering the value directly. */\n  animateOnMount?: boolean;\n}\n\n// Each column is a wheel of five 0–9 runs. It rests in the middle run, so two\n// rapid changes in either direction can always roll forward or backward.\nconst CELLS = 50;\nconst REST = 20;\nconst STAGGER = 32;\nconst MAX_STAGGER = 224;\nconst SLIDE_EASE = \"cubic-bezier(0.2, 1, 0.32, 1)\";\n// Overshoot scales with distance, so longer rolls get a gentler curve: every\n// wheel settles past its digit by about a tenth of a cell, whatever it travelled.\nconst SETTLE = [1.534, 1.368, 1.3, 1.262, 1.236, 1.217, 1.203, 1.191, 1.181];\nconst rollEase = (cells: number) =>\n  `cubic-bezier(0.2, ${SETTLE[Math.min(Math.max(Math.abs(cells), 1), 9) - 1]}, 0.32, 1)`;\nconst SIZE_EASE = \"cubic-bezier(0.32, 0.72, 0, 1)\";\nconst REDUCED_QUERY = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeReducedMotion(callback: () => void) {\n  const query = window.matchMedia(REDUCED_QUERY);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction usePrefersReducedMotion() {\n  return useSyncExternalStore(\n    subscribeReducedMotion,\n    () => window.matchMedia(REDUCED_QUERY).matches,\n    () => false,\n  );\n}\n\nconst presets: Record<\n  NumberTickerFormat,\n  (currency: string) => Intl.NumberFormatOptions\n> = {\n  number: () => ({}),\n  currency: (currency) => ({ style: \"currency\", currency }),\n  percent: () => ({\n    style: \"percent\",\n    minimumFractionDigits: 1,\n    maximumFractionDigits: 1,\n  }),\n  compact: () => ({ notation: \"compact\", maximumSignificantDigits: 3 }),\n};\n\ninterface TickerFormatter {\n  format: Intl.NumberFormat;\n  /** The locale's digit glyphs, so Arabic-Indic or Devanagari numerals roll too. */\n  glyphs: string[];\n  /** One padded cell per wheel position, created once and shared by every column. */\n  cells: ReactNode[];\n}\n\nconst formatterCache = new Map<string, TickerFormatter>();\n\nfunction resolveOptions(\n  format: NumberTickerFormat,\n  currency: string,\n  overrides: Intl.NumberFormatOptions | undefined,\n): Intl.NumberFormatOptions {\n  const options = { ...presets[format](currency), ...overrides };\n  // Keep a preset's fixed precision from conflicting with a partial override.\n  const { minimumFractionDigits: min, maximumFractionDigits: max } = options;\n  if (min !== undefined && max !== undefined && min > max) {\n    if (overrides?.maximumFractionDigits !== undefined)\n      options.minimumFractionDigits = max;\n    else options.maximumFractionDigits = min;\n  }\n  return options;\n}\n\nfunction getFormatter(\n  locale: string,\n  options: Intl.NumberFormatOptions,\n): TickerFormatter {\n  const key = `${locale}|${JSON.stringify(options)}`;\n  let entry = formatterCache.get(key);\n  if (!entry) {\n    let format: Intl.NumberFormat;\n    try {\n      format = new Intl.NumberFormat(locale, options);\n    } catch {\n      format = new Intl.NumberFormat(\"en-US\");\n    }\n    const digits = new Intl.NumberFormat(format.resolvedOptions().locale, {\n      useGrouping: false,\n      numberingSystem: format.resolvedOptions().numberingSystem,\n    } as Intl.NumberFormatOptions);\n    const glyphs = Array.from({ length: 10 }, (_, digit) =>\n      digits.format(digit),\n    );\n    const cells = Array.from({ length: CELLS }, (_, cell) => (\n      <span key={cell} className=\"block py-(--ticker-gap)\">\n        {glyphs[cell % 10]}\n      </span>\n    ));\n    entry = { format, glyphs, cells };\n    formatterCache.set(key, entry);\n  }\n  return entry;\n}\n\ntype Slot =\n  | { key: string; kind: \"digit\"; digit: number; order: number }\n  | { key: string; kind: \"char\"; char: string };\n\ntype Item = Slot & { phase: \"idle\" | \"enter\" | \"exit\" };\n\n/**\n * Split a formatted number into keyed slots. Integer digits are keyed by place\n * value and fraction digits by position, so the ones column stays the ones\n * column when 999 becomes 1,000 and only the new leading columns enter.\n */\nfunction toSlots(value: number, formatter: TickerFormatter) {\n  if (!Number.isFinite(value)) {\n    return {\n      text: \"—\",\n      slots: [{ key: \"missing\", kind: \"char\", char: \"—\" }] as Slot[],\n    };\n  }\n  const parts = formatter.format.formatToParts(value);\n  const isDigit = (char: string) => formatter.glyphs.includes(char);\n  let integerDigits = 0;\n  for (const part of parts)\n    if (part.type === \"integer\")\n      for (const char of part.value) if (isDigit(char)) integerDigits++;\n\n  const slots: Slot[] = [];\n  const seen = new Map<string, number>();\n  let integerIndex = 0;\n  let fractionIndex = 0;\n  const pushChar = (type: string, char: string) => {\n    const count = seen.get(type) ?? 0;\n    seen.set(type, count + 1);\n    slots.push({ key: `${type}${count}:${char}`, kind: \"char\", char });\n  };\n  for (const part of parts) {\n    if (part.type === \"integer\" || part.type === \"fraction\") {\n      for (const char of part.value) {\n        const digit = formatter.glyphs.indexOf(char);\n        if (digit < 0) pushChar(part.type, char);\n        else if (part.type === \"integer\")\n          slots.push({\n            key: `i${integerDigits - 1 - integerIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n        else\n          slots.push({\n            key: `f${fractionIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n      }\n    } else if (part.type === \"group\") {\n      slots.push({\n        key: `g${integerDigits - integerIndex}:${part.value}`,\n        kind: \"char\",\n        char: part.value,\n      });\n    } else {\n      pushChar(part.type, part.value);\n    }\n  }\n  // Stagger from the rightmost digit outward, like a carry moving left.\n  let order = 0;\n  for (let i = slots.length - 1; i >= 0; i--) {\n    const slot = slots[i];\n    if (slot.kind === \"digit\") slots[i] = { ...slot, order: order++ };\n  }\n  return { text: parts.map((part) => part.value).join(\"\"), slots };\n}\n\n/** Keep removed slots in place for one transition so they can collapse out. */\nfunction mergeSlots(previous: Item[], next: Slot[], animate: boolean): Item[] {\n  const previousKeys = new Set(previous.map((item) => item.key));\n  const live: Item[] = next.map((slot) => ({\n    ...slot,\n    phase: animate && !previousKeys.has(slot.key) ? \"enter\" : \"idle\",\n  }));\n  if (!animate) return live;\n  const nextKeys = new Set(next.map((slot) => slot.key));\n  const leadingExits = new Map<string, Item[]>();\n  let pending: Item[] = [];\n  for (const item of previous) {\n    if (nextKeys.has(item.key)) {\n      if (pending.length) leadingExits.set(item.key, pending);\n      pending = [];\n    } else if (item.phase !== \"exit\") {\n      pending.push({ ...item, phase: \"exit\" });\n    }\n  }\n  const merged: Item[] = [];\n  for (const item of live) {\n    const exits = leadingExits.get(item.key);\n    if (exits) merged.push(...exits);\n    merged.push(item);\n  }\n  return merged.concat(pending);\n}\n\nfunction zeroed(slots: Slot[]): Slot[] {\n  return slots.map((slot) =>\n    slot.kind === \"digit\" ? { ...slot, digit: 0 } : slot,\n  );\n}\n\ninterface TickerState {\n  signature: string;\n  value: number;\n  items: Item[];\n  direction: number;\n  flash: \"up\" | \"down\" | null;\n  version: number;\n}\n\n/** An odometer-style number: each digit rolls on its own wheel when `value` changes. */\nexport function NumberTicker({\n  value,\n  format = \"number\",\n  formatOptions,\n  locale = \"en-US\",\n  currency = \"USD\",\n  prefix,\n  suffix,\n  duration = 800,\n  highlightChanges = false,\n  animateOnMount = false,\n  className,\n  ...props\n}: NumberTickerProps) {\n  const reduced = usePrefersReducedMotion();\n  const optionsKey = JSON.stringify(formatOptions ?? null);\n  const formatter = useMemo(\n    () => getFormatter(locale, resolveOptions(format, currency, formatOptions)),\n    // formatOptions is compared by content so inline objects stay cheap.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [locale, format, currency, optionsKey],\n  );\n  const { text, slots } = useMemo(\n    () => toSlots(value, formatter),\n    [value, formatter],\n  );\n\n  const [armed, setArmed] = useState(!animateOnMount);\n  const shown = armed ? slots : zeroed(slots);\n  const signature = (armed ? \"\" : \"0|\") + shown.map(slotKey).join(\"|\");\n  const shownValue = armed ? value : 0;\n\n  const [state, setState] = useState<TickerState>(() => ({\n    signature,\n    value: shownValue,\n    items: shown.map((slot) => ({ ...slot, phase: \"idle\" })),\n    direction: 0,\n    flash: null,\n    version: 0,\n  }));\n  if (state.signature !== signature) {\n    const direction = Math.sign(shownValue - state.value);\n    // The first roll up from zero is an entrance, not a change worth tinting.\n    const entrance = state.signature.startsWith(\"0|\");\n    setState({\n      signature,\n      value: shownValue,\n      items: mergeSlots(state.items, shown, !reduced),\n      direction,\n      flash:\n        highlightChanges && !entrance && direction !== 0\n          ? direction > 0\n            ? \"up\"\n            : \"down\"\n          : null,\n      version: state.version + 1,\n    });\n  }\n\n  // Roll up from zero after the first paint (or settle at once without motion).\n  useLayoutEffect(() => {\n    if (armed) return;\n    if (reduced) {\n      setArmed(true);\n      return;\n    }\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setArmed(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [armed, reduced]);\n\n  // Drop collapsed slots and fade the tint once the roll has settled.\n  const { version } = state;\n  const hasExits = state.items.some((item) => item.phase === \"exit\");\n  useEffect(() => {\n    if (!hasExits) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version\n            ? {\n                ...current,\n                items: current.items.filter((item) => item.phase !== \"exit\"),\n              }\n            : current,\n        ),\n      duration + MAX_STAGGER,\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, hasExits, duration]);\n  const flashing = state.flash !== null;\n  useEffect(() => {\n    if (!flashing) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version ? { ...current, flash: null } : current,\n        ),\n      Math.max(360, duration * 0.75),\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, flashing, duration]);\n\n  const animate = !reduced;\n  return (\n    <span\n      data-slot=\"number-ticker\"\n      data-direction={\n        state.direction > 0 ? \"up\" : state.direction < 0 ? \"down\" : undefined\n      }\n      className={cn(\"inline-block whitespace-nowrap tabular-nums\", className)}\n      {...props}\n    >\n      {prefix}\n      <span className=\"sr-only\">{text}</span>\n      {/* Digits always run left to right, even inside right-to-left text. */}\n      <span\n        aria-hidden=\"true\"\n        dir=\"ltr\"\n        data-slot=\"number-ticker-value\"\n        className={cn(\n          \"transition-colors motion-reduce:transition-none\",\n          state.flash === \"up\" && \"text-emerald-700 dark:text-emerald-400\",\n          state.flash === \"down\" && \"text-red-600 dark:text-red-400\",\n        )}\n        style={{ transitionDuration: state.flash ? \"140ms\" : \"900ms\" }}\n      >\n        {state.items.map((item) => (\n          <TickerSlot\n            key={item.key}\n            item={item}\n            direction={state.direction}\n            formatter={formatter}\n            duration={duration}\n            animate={animate}\n          />\n        ))}\n      </span>\n      {suffix}\n    </span>\n  );\n}\n\nfunction slotKey(slot: Slot) {\n  return slot.kind === \"digit\" ? `${slot.key}=${slot.digit}` : slot.key;\n}\n\nfunction TickerSlot({\n  item,\n  direction,\n  formatter,\n  duration,\n  animate,\n}: {\n  item: Item;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  animate: boolean;\n}) {\n  // New slots mount collapsed, then open on the next frame so the change transitions.\n  const [open, setOpen] = useState(item.phase !== \"enter\" || !animate);\n  useEffect(() => {\n    if (open) return;\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setOpen(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [open]);\n\n  const collapsed = !open || item.phase === \"exit\";\n  const travel = direction < 0 ? -1 : 1;\n  const offset = item.phase === \"exit\" ? -travel : travel;\n  const delay =\n    item.kind === \"digit\" ? Math.min(item.order * STAGGER, MAX_STAGGER) : 0;\n  const style: CSSProperties = {\n    gridTemplateColumns: collapsed ? \"0fr\" : \"1fr\",\n    opacity: collapsed ? 0 : 1,\n    transform: collapsed ? `translateY(${offset * 0.42}em)` : undefined,\n    transition: animate\n      ? `grid-template-columns ${duration * 0.7}ms ${SIZE_EASE}, opacity ${duration * 0.5}ms ease, transform ${duration}ms ${SLIDE_EASE}`\n      : \"none\",\n  };\n  return (\n    <span className=\"inline-grid\" style={style} data-phase={item.phase}>\n      <span className=\"min-w-0 [clip-path:inset(-50%_0)]\">\n        {item.kind === \"digit\" ? (\n          <DigitWheel\n            digit={item.digit}\n            direction={direction}\n            formatter={formatter}\n            duration={duration}\n            delay={delay}\n            animate={animate}\n          />\n        ) : (\n          <span className=\"whitespace-pre\">{item.char}</span>\n        )}\n      </span>\n    </span>\n  );\n}\n\nfunction DigitWheel({\n  digit,\n  direction,\n  formatter,\n  duration,\n  delay,\n  animate,\n}: {\n  digit: number;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  delay: number;\n  animate: boolean;\n}) {\n  const [wheel, setWheel] = useState({\n    digit,\n    cell: REST + digit,\n    travel: 0,\n    rolling: false,\n  });\n  if (wheel.digit !== digit) {\n    // Roll forward when the value rises and backward when it falls, wrapping\n    // through 9 → 0 the way a mechanical counter carries.\n    const forward = (digit - wheel.digit + 10) % 10;\n    const backward = (wheel.digit - digit + 10) % 10;\n    const step =\n      direction > 0\n        ? forward\n        : direction < 0\n          ? -backward\n          : forward <= backward\n            ? forward\n            : -backward;\n    let cell = wheel.cell + step;\n    if (cell < 0 || cell >= CELLS) cell = REST + digit;\n    setWheel(\n      animate\n        ? { digit, cell, travel: cell - wheel.cell, rolling: true }\n        : { digit, cell: REST + digit, travel: 0, rolling: false },\n    );\n  }\n\n  // Once settled, jump back to the matching cell in the middle run (same glyph).\n  useEffect(() => {\n    if (!wheel.rolling) return;\n    const timer = window.setTimeout(\n      () =>\n        setWheel((current) => ({\n          digit: current.digit,\n          cell: REST + current.digit,\n          travel: 0,\n          rolling: false,\n        })),\n      duration + delay + 40,\n    );\n    return () => window.clearTimeout(timer);\n  }, [wheel, duration, delay]);\n\n  // Cells carry --ticker-gap of padding above and below, and the clipping window\n  // reaches that far past the line box. At rest only padding shows in the\n  // overhang; while rolling, neighbors fade through it like a real wheel.\n  return (\n    <span className=\"relative inline-block [--ticker-gap:0.2em]\">\n      <span className=\"invisible\">{formatter.glyphs[digit]}</span>\n      <span className=\"absolute inset-x-0 -inset-y-(--ticker-gap) overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,#000_var(--ticker-gap),#000_calc(100%_-_var(--ticker-gap)),transparent)]\">\n        <span\n          className=\"absolute inset-x-0 top-0 flex flex-col text-center\"\n          style={{\n            transform: `translateY(${(-wheel.cell * 100) / CELLS}%)`,\n            transition: wheel.rolling\n              ? `transform ${duration}ms ${rollEase(wheel.travel)} ${delay}ms`\n              : \"none\",\n            willChange: wheel.rolling ? \"transform\" : undefined,\n          }}\n        >\n          {formatter.cells}\n        </span>\n      </span>\n    </span>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/number-ticker. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
