# Rolling number (滚动数字)

A number whose digits roll like an odometer when the value changes, formatted with Intl for any locale or currency, with reduced-motion and screen reader support.

- Ref: `component/rolling-number` (component · counters)
- Page: https://uifino.com/en/components/counters/rolling-number
- Markdown: https://uifino.com/md/components/rolling-number.md
- Preview image: https://uifino.com/blocks/covers/rolling-number-dark.webp

## Install

- shadcn: `npx shadcn@latest add "https://uifino.com/r/blocks/rolling-number.json"`
- UIFino CLI: `npx uifino@latest add component/rolling-number`

## Dependencies

`lucide-react`, `motion`

## shadcn/ui components it builds on

- `button`, `card`, `toggle-group`. The shadcn CLI installs them together with the block.

## Theme

The block reads the project's shadcn theme variables, so it follows whatever DESIGN.md the project uses and needs no options of its own.
To give the project the look of a UIFino brand or style, install its theme: `npx shadcn@latest add "https://uifino.com/r/themes/vercel.json"`.

## Usage

The files under `examples/` show the block wired with content, including its loading, empty and error states where it has them.

## Files

| Path | Role | Size |
| :--- | :--- | ---: |
| components/blocks/rolling-number/examples/content.ts | demo | 2.0 KB |
| components/blocks/rolling-number/examples/default.tsx | demo | 3.7 KB |
| components/blocks/rolling-number/examples/regions.tsx | demo | 1.9 KB |
| components/blocks/rolling-number/examples/stat.tsx | demo | 941 B |
| components/blocks/rolling-number/rolling-number.tsx | source | 3.9 KB |

### components/blocks/rolling-number/rolling-number.tsx

```tsx
"use client";

import { useMemo } from "react";
import { motion, useReducedMotion } from "motion/react";

import { cn } from "@/lib/utils";

const DIGITS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as const;

type RollingNumberProps = {
  value: number;
  locale?: string;
  format?: Intl.NumberFormatOptions;
  duration?: number;
  stagger?: number;
  className?: string;
  announce?: boolean;
};

type Cell = { kind: "digit"; key: string; digit: number; order: number } | { kind: "text"; key: string; text: string };

function readDigit(char: string, localDigits: readonly string[]) {
  const index = localDigits.indexOf(char);
  return index === -1 ? Number(char) || 0 : index;
}

function buildCells(parts: Intl.NumberFormatPart[], localDigits: readonly string[]): Cell[] {
  const decimalAt = parts.findIndex((part) => part.type === "decimal");
  const integerEnd = decimalAt === -1 ? parts.length : decimalAt;
  const cells: Cell[] = [];
  let integerDigitsLeft = parts.slice(0, integerEnd).reduce((sum, part) => (part.type === "integer" ? sum + part.value.length : sum), 0);
  let fractionIndex = 0;
  parts.forEach((part, partIndex) => {
    if (part.type === "integer") {
      for (const char of part.value) {
        integerDigitsLeft -= 1;
        cells.push({ kind: "digit", key: `i${integerDigitsLeft}`, digit: readDigit(char, localDigits), order: integerDigitsLeft });
      }
    } else if (part.type === "fraction") {
      for (const char of part.value) {
        cells.push({ kind: "digit", key: `f${fractionIndex}`, digit: readDigit(char, localDigits), order: fractionIndex });
        fractionIndex += 1;
      }
    } else {
      cells.push({ kind: "text", key: `t${partIndex}-${part.type}-${part.value}`, text: part.value });
    }
  });
  return cells;
}

function RollingNumber({
  value,
  locale = "en-US",
  format,
  duration = 0.6,
  stagger = 0.04,
  className,
  announce = true
}: RollingNumberProps) {
  const reduceMotion = useReducedMotion();
  const formatKey = JSON.stringify(format ?? null);
  const formatter = useMemo(
    () => new Intl.NumberFormat(locale, (JSON.parse(formatKey) as Intl.NumberFormatOptions | null) ?? undefined),
    [locale, formatKey]
  );
  const localDigits = useMemo(() => {
    const digitFormatter = new Intl.NumberFormat(locale, {
      numberingSystem: formatter.resolvedOptions().numberingSystem,
      useGrouping: false
    });
    return DIGITS.map((digit) => digitFormatter.format(digit));
  }, [locale, formatter]);
  const label = formatter.format(value);
  const cells = useMemo(
    () => buildCells(formatter.formatToParts(value), localDigits),
    [formatter, localDigits, value]
  );

  return (
    <span className={cn("inline-flex items-baseline tabular-nums leading-none", className)}>
      <span className="sr-only" aria-live={announce ? "polite" : "off"} aria-atomic="true">
        {label}
      </span>
      <span aria-hidden="true" className="inline-flex items-baseline">
        {cells.map((cell) =>
          cell.kind === "text" ? (
            <span key={cell.key} className="whitespace-pre">
              {cell.text}
            </span>
          ) : (
            <span key={cell.key} className="relative inline-block h-[1em] w-[1ch] overflow-hidden align-baseline">
              <motion.span
                className="flex flex-col"
                initial={false}
                animate={{ y: `${-cell.digit}em` }}
                transition={
                  reduceMotion
                    ? { duration: 0 }
                    : { type: "tween", ease: [0.22, 1, 0.36, 1], duration, delay: Math.min(cell.order, 4) * stagger }
                }
              >
                {DIGITS.map((digit) => (
                  <span key={digit} className="block h-[1em] text-center leading-none">
                    {localDigits[digit]}
                  </span>
                ))}
              </motion.span>
            </span>
          )
        )}
      </span>
    </span>
  );
}

export { RollingNumber };
export type { RollingNumberProps };
```

Not inlined (4 files, 8.6 KB). Full sources: https://uifino.com/r/blocks/rolling-number.json
