Skip to content
Shaken UI
Sign in

Animated Number

Save

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.

Category
Core
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Animated Number preview
$2,849.50

Installation

npx @shakenui/cli add animated-number

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add animated-number --dry-run

Usage

animated-number-example.tsx
"use client";

import { useState } from "react";
import { AnimatedNumber } from "@/components/shaken/ui/animated-number";

const readings = [
  { spend: 12480.32, runs: 7, hitRate: 0.934 },
  { spend: 12496.05, runs: 9, hitRate: 0.941 },
  { spend: 12611.8, runs: 12, hitRate: 0.928 },
  { spend: 13004.12, runs: 8, hitRate: 0.917 },
];

export default function AnimatedNumberExample() {
  const [index, setIndex] = useState(0);
  const reading = readings[index] ?? readings[0]!;

  return (
    <div className="grid w-full max-w-sm gap-4">
      <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">
        <div className="grid gap-1 px-4 py-3.5">
          <dt className="text-xs font-medium text-zinc-500">Spend this month</dt>
          <dd className="text-2xl font-semibold tracking-[-0.01em] text-zinc-950 dark:text-white">
            <AnimatedNumber value={reading.spend} mode="roll" format={{ style: "currency", currency: "USD" }} />
          </dd>
        </div>
        <div className="grid grid-cols-2 divide-x divide-zinc-950/[0.07] dark:divide-white/[0.08]">
          <div className="grid gap-1 px-4 py-3">
            <dt className="text-xs font-medium text-zinc-500">Runs in progress</dt>
            <dd className="text-lg font-semibold text-zinc-950 dark:text-white">
              <AnimatedNumber value={reading.runs} mode="pop" />
            </dd>
          </div>
          <div className="grid gap-1 px-4 py-3">
            <dt className="text-xs font-medium text-zinc-500">Cache hit rate</dt>
            <dd className="text-lg font-semibold text-zinc-950 dark:text-white">
              <AnimatedNumber value={reading.hitRate} trend format={{ style: "percent", minimumFractionDigits: 1 }} />
            </dd>
          </div>
        </div>
      </dl>
      <button
        type="button"
        onClick={() => setIndex((current) => (current + 1) % readings.length)}
        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]"
      >
        Refresh
      </button>
    </div>
  );
}

API

PropTypeDefaultDescription
valuenumber—The number to show. Only digits that differ from the previous value move.
formatIntl.NumberFormatOptions—Formatting, for example { style: "currency", currency: "USD" }, { style: "percent" } or { notation: "compact" }.
localeIntl.LocalesArgument—Locale for formatting. Defaults to the runtime locale.
mode"fade" | "roll" | "pop""fade"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.
trendbooleanfalseTints changed digits green when the value rises and red when it falls, then fades back.
livebooleanfalseAnnounces each new value once to screen readers through a polite live region.
animatedbooleantrueSet to false to swap values instantly.
staggernumber0.035Seconds 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.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/animated-number.tsxanimated-number
  • npm packages: motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/animated-number/0.1.0.json.

ui/animated-number.tsxShow
ui/animated-number.tsx
"use client";

import {
  AnimatePresence,
  animate,
  motion,
  useMotionValue,
  useReducedMotion,
  useTransform,
  useVelocity,
  type AnimationPlaybackControls,
  type Variants,
} from "motion/react";
import { type ComponentProps, useEffect, useMemo, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

export type AnimatedNumberMode = "fade" | "roll" | "pop";

export interface AnimatedNumberProps extends Omit<ComponentProps<"span">, "children"> {
  /** The number to show. Only the digits that differ from the previous value move. */
  value: number;
  /** Intl formatting, for example `{ style: "currency", currency: "USD" }`, `{ style: "percent" }` or `{ notation: "compact" }`. */
  format?: Intl.NumberFormatOptions;
  /** Locale for formatting. Defaults to the runtime locale. */
  locale?: Intl.LocalesArgument;
  /**
   * How changed digits move. `fade` slides a short way and cross-fades, `roll` turns each digit
   * like an odometer wheel through every value in between, and `pop` springs the new digit in.
   */
  mode?: AnimatedNumberMode;
  /** Tints the changed digits green when the value rises and red when it falls, then fades back. */
  trend?: boolean;
  /** Announces each new value to screen readers once, after it changes. Off by default so dashboards stay quiet. */
  live?: boolean;
  /** Set to false to swap values instantly. */
  animated?: boolean;
  /** Seconds between neighboring changed digits. */
  stagger?: number;
}

const ease = [0.23, 1, 0.32, 1] as const;

/** Reduced-motion preference, read only after hydration so server and client render the same markup first. */
function useReducedMotionAfterMount() {
  const reduce = useReducedMotion();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  return mounted && reduce === true;
}
const DIGITS = "0123456789";

type Slot = { key: string; char: string; digit: boolean };

/**
 * Turns formatted parts into keyed slots. Integer digits are keyed by place value (ones, tens,
 * ...) and fraction digits by position after the decimal, so 9.99 to 10.00 keeps each column
 * on its own place instead of shifting by string index.
 */
function toSlots(parts: Intl.NumberFormatPart[]): Slot[] {
  let integerCount = 0;
  for (const part of parts) if (part.type === "integer") integerCount += part.value.length;

  const slots: Slot[] = [];
  const seen: Record<string, number> = {};
  let integerSeen = 0;
  let fractionSeen = 0;
  for (const part of parts) {
    if (part.type === "integer") {
      for (const char of part.value) {
        slots.push({ key: `i${integerCount - 1 - integerSeen}`, char, digit: true });
        integerSeen += 1;
      }
    } else if (part.type === "fraction") {
      for (const char of part.value) {
        slots.push({ key: `f${fractionSeen}`, char, digit: true });
        fractionSeen += 1;
      }
    } else if (part.type === "group") {
      slots.push({ key: `g${integerCount - integerSeen}`, char: part.value, digit: false });
    } else if (part.type === "decimal") {
      slots.push({ key: "d", char: part.value, digit: false });
    } else {
      const side = integerSeen + fractionSeen > 0 ? "post" : "pre";
      const name = `${side}-${part.type}`;
      seen[name] = (seen[name] ?? 0) + 1;
      slots.push({ key: `${name}-${seen[name]}`, char: part.value, digit: false });
    }
  }
  return slots;
}

interface Snapshot {
  text: string;
  value: number;
  slots: Slot[];
  /** 1 when the value rose, -1 when it fell, 0 on first render. */
  direction: number;
  /** Delay in seconds for each slot that changed in the last update. */
  delays: Map<string, number>;
  version: number;
}

function diff(previous: Snapshot, slots: Slot[], value: number, text: string, mode: AnimatedNumberMode, stagger: number): Snapshot {
  const before = new Map(previous.slots.map((slot) => [slot.key, slot.char]));
  const changed = slots.filter((slot) => slot.digit && before.has(slot.key) && before.get(slot.key) !== slot.char);
  // An odometer turns from the ones column outward; fade and pop read left to right.
  const ordered = mode === "roll" ? changed.slice().reverse() : changed;
  const delays = new Map<string, number>();
  ordered.forEach((slot, index) => delays.set(slot.key, index * stagger));
  for (const slot of slots) if (!before.has(slot.key)) delays.set(slot.key, 0);
  return {
    text,
    value,
    slots,
    direction: value === previous.value ? previous.direction : value > previous.value ? 1 : -1,
    delays,
    version: previous.version + 1,
  };
}

// Fade: the old digit leaves the way the value moves and the new one arrives from the other
// side, the same language as Number Input's stepper digits.
const fadeVariants: Variants = {
  enter: ({ direction }: DigitCustom) => ({ y: direction >= 0 ? "0.55em" : "-0.55em", opacity: 0, filter: "blur(2px)" }),
  center: ({ delay }: DigitCustom) => ({
    y: "0em",
    opacity: 1,
    filter: "blur(0px)",
    transition: { duration: 0.34, ease, delay },
  }),
  exit: ({ direction, delay }: DigitCustom) => ({
    y: direction >= 0 ? "-0.55em" : "0.55em",
    opacity: 0,
    filter: "blur(2px)",
    transition: { duration: 0.24, ease, delay },
  }),
};

// Pop: the old digit shrinks away quickly; the new one springs up from below and overshoots its
// line a touch before it settles. Opacity and blur run on a tween so the spring cannot push blur
// below zero.
const popVariants: Variants = {
  enter: ({ direction }: DigitCustom) => ({ y: direction >= 0 ? "0.6em" : "-0.6em", scale: 0.55, opacity: 0, filter: "blur(4px)" }),
  center: ({ delay }: DigitCustom) => ({
    y: "0em",
    scale: 1,
    opacity: 1,
    filter: "blur(0px)",
    transition: {
      default: { type: "spring", visualDuration: 0.42, bounce: 0.4, delay: delay + 0.05 },
      opacity: { duration: 0.18, ease, delay: delay + 0.05 },
      filter: { duration: 0.26, ease, delay: delay + 0.05 },
    },
  }),
  exit: ({ direction, delay }: DigitCustom) => ({
    y: direction >= 0 ? "-0.45em" : "0.45em",
    scale: 0.6,
    opacity: 0,
    filter: "blur(3px)",
    transition: { duration: 0.16, ease, delay },
  }),
};

type DigitCustom = { direction: number; delay: number };

function SwapDigit({ char, direction, delay, mode }: { char: string; direction: number; delay: number; mode: "fade" | "pop" }) {
  const custom: DigitCustom = { direction, delay };
  return (
    <span className="relative inline-block">
      <AnimatePresence initial={false} mode="popLayout" custom={custom}>
        <motion.span
          key={char}
          custom={custom}
          variants={mode === "pop" ? popVariants : fadeVariants}
          initial="enter"
          animate="center"
          exit="exit"
          className="inline-block"
        >
          {char}
        </motion.span>
      </AnimatePresence>
    </span>
  );
}

// Three turns of the wheel so a digit can travel up to nine steps either way and still show
// a neighbor above and below.
const WHEEL = Array.from({ length: 30 }, (_, index) => index % 10);

/**
 * One odometer wheel. Its position is continuous (10 to 20 at rest), so rising values always turn
 * the wheel forward through 9 to 0 and falling values turn it back. While it spins, a ghost copy
 * shows the neighbors above and below, faint and blurred in proportion to the speed.
 */
function RollDigit({ char, direction, delay }: { char: string; direction: number; delay: number }) {
  const digit = DIGITS.indexOf(char);
  const position = useMotionValue(10 + Math.max(digit, 0));
  const velocity = useVelocity(position);
  const y = useTransform(position, (value) => `${(-value / 30) * 100}%`);
  const blur = useTransform(velocity, (value) => `blur(${Math.min(Math.abs(value) / 18, 0.9).toFixed(2)}px)`);
  const ghost = useTransform(velocity, (value) => Math.min(Math.abs(value) / 14, 1) * 0.3);
  const controls = useRef<AnimationPlaybackControls | null>(null);

  useEffect(() => {
    if (digit < 0) return;
    controls.current?.stop();
    // Re-center the wheel in its middle turn, which looks identical, before measuring the trip.
    const now = position.get();
    const start = now - Math.floor(now / 10 - 1) * 10;
    const steps = direction >= 0 ? (((digit - start) % 10) + 10) % 10 : (((start - digit) % 10) + 10) % 10;
    if (steps < 0.001) return;
    const speed = velocity.get();
    position.jump(start);
    const target = direction >= 0 ? start + steps : start - steps;
    controls.current = animate(position, target, {
      type: "spring",
      visualDuration: Math.min(0.32 + steps * 0.045, 0.72),
      bounce: 0.2,
      velocity: speed,
      delay,
    });
    return () => controls.current?.stop();
    // The wheel moves only when its digit changes.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [digit]);

  if (digit < 0) return <span className="inline-block">{char}</span>;

  const column = WHEEL.map((value, index) => (
    <span key={index} className="block">
      {value}
    </span>
  ));

  return (
    <span className="relative inline-block">
      <span className="invisible">{char}</span>
      <span className="absolute inset-0 overflow-hidden">
        <motion.span style={{ y, filter: blur }} className="absolute inset-x-0 top-0 flex flex-col">
          {column}
        </motion.span>
      </span>
      <motion.span
        style={{ opacity: ghost }}
        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)]"
      >
        <motion.span style={{ y, filter: blur }} className="absolute inset-x-0 top-1/3 flex flex-col">
          {column}
        </motion.span>
      </motion.span>
    </span>
  );
}

const slotTransition = { duration: 0.3, ease };

/**
 * A formatted number whose changed digits animate while the rest stay still. Columns that appear
 * or disappear (999 to 1,000) fade in and out while their neighbors glide to their new places.
 * Screen readers get the formatted value as plain text; the moving digits are hidden from them.
 */
export function AnimatedNumber({
  value,
  format,
  locale,
  mode = "fade",
  trend = false,
  live = false,
  animated = true,
  stagger = 0.035,
  className,
  ...props
}: AnimatedNumberProps) {
  const reduceMotion = useReducedMotionAfterMount();
  // Keyed by content, so an inline `format={{ ... }}` object does not rebuild the formatter each render.
  const formatKey = JSON.stringify(format ?? {});
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const formatter = useMemo(() => new Intl.NumberFormat(locale, format), [locale, formatKey]);
  const text = formatter.format(value);

  const [snapshot, setSnapshot] = useState<Snapshot>(() => ({
    text,
    value,
    slots: toSlots(formatter.formatToParts(value)),
    direction: 0,
    delays: new Map(),
    version: 0,
  }));

  // Derive the new snapshot during render so the diff is computed once per value change.
  let current = snapshot;
  if (snapshot.text !== text || snapshot.value !== value) {
    current = diff(snapshot, toSlots(formatter.formatToParts(value)), value, text, mode, stagger);
    setSnapshot(current);
  }

  const [tint, setTint] = useState<{ version: number; up: boolean } | null>(null);
  useEffect(() => {
    if (!trend || current.version === 0 || current.direction === 0) return;
    setTint({ version: current.version, up: current.direction > 0 });
    const timer = window.setTimeout(() => setTint(null), 900);
    return () => window.clearTimeout(timer);
  }, [trend, current.version, current.direction]);

  const still = !animated || reduceMotion;

  return (
    <span className={cx("relative inline-flex whitespace-nowrap tabular-nums", className)} {...props}>
      <span className="sr-only select-none" aria-live={live ? "polite" : undefined} aria-atomic={live ? true : undefined}>
        {text}
      </span>
      {still ? (
        <span aria-hidden="true">{text}</span>
      ) : (
        <motion.span aria-hidden="true" layoutRoot className="relative inline-flex select-none">
          <AnimatePresence initial={false} mode="popLayout">
            {current.slots.map((slot) => {
              const delay = current.delays.get(slot.key) ?? 0;
              const tinted = tint && tint.version === current.version && current.delays.has(slot.key) && slot.digit;
              return (
                <motion.span
                  key={slot.digit ? slot.key : `${slot.key}:${slot.char}`}
                  layout="position"
                  initial={{ opacity: 0, scale: 0.8, filter: "blur(3px)" }}
                  animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }}
                  exit={{ opacity: 0, scale: 0.8, filter: "blur(3px)", transition: { duration: 0.18, ease } }}
                  transition={slotTransition}
                  className={cx(
                    // The tint arrives quickly and drains back to the text color slowly.
                    "inline-block whitespace-pre transition-colors ease-out motion-reduce:transition-none",
                    !tinted
                      ? "duration-700"
                      : tint.up
                        ? "text-emerald-600 duration-150 dark:text-emerald-400"
                        : "text-red-600 duration-150 dark:text-red-400",
                  )}
                >
                  {!slot.digit ? (
                    slot.char
                  ) : mode === "roll" ? (
                    <RollDigit char={slot.char} direction={current.direction} delay={delay} />
                  ) : (
                    <SwapDigit char={slot.char} direction={current.direction} delay={delay} mode={mode} />
                  )}
                </motion.span>
              );
            })}
          </AnimatePresence>
        </motion.span>
      )}
    </span>
  );
}