Live Number
A number that shows a change without pulling the eye: only the digits that changed cross-fade.
Installation
$
npx shadcn@latest add https://ui.mattdowney.com/r/live-number.jsonUsage
import { LiveNumber } from "@/components/ui/live-number"Examples
Default
Only the digits that changed move, 0.14em in the direction of the change. Screen readers hear the whole value once, never digit by digit.
1,2841,284
Roll-in for a moment
variant="roll" lifts each changed digit in from below and lets it settle a little past its place, the last two trailing. For a total that lands once, not a value that ticks.
$4,820.00$4,820.00
API Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| value* | number | None | The number to show. |
| format | Intl.NumberFormatOptions | None | Passed to Intl.NumberFormat: currency, percent, decimals. |
| locale | string | string[] | "en-US" | Fixed so the server and the browser print the same string. Set it to the reader's locale when you know it. |
| variant | "subtle" | "roll" | "subtle" | subtle for a value that changes often; roll for a rare moment. |
| value*numberThe number to show. |
formatIntl.NumberFormatOptionsPassed to Intl.NumberFormat: currency, percent, decimals. |
| localestring | string[] = "en-US"Fixed so the server and the browser print the same string. Set it to the reader's locale when you know it. |
variant"subtle" | "roll" = "subtle"subtle for a value that changes often; roll for a rare moment. |
"use client"
import * as React from "react"
import { cn } from "@/registry/lib/utils"
type LiveNumberVariant = "subtle" | "roll"
type Glyph = {
char: string
/** The character it replaced, when it changed. Absent when it stayed. */
old?: string
changed: boolean
/** Changed glyphs counted from the end: 0 is the last one. */
fromEnd: number
}
/** Line the new string up with the old one from the right, since a number
* grows on the left (99 to 100), and mark which characters changed. */
function diff(prev: string | null, next: string): Glyph[] {
const glyphs: Glyph[] = [...next].map((char, i) => {
if (prev === null) return { char, changed: false, fromEnd: 0 }
const old = prev[prev.length - (next.length - i)]
return old === char
? { char, changed: false, fromEnd: 0 }
: { char, old, changed: true, fromEnd: 0 }
})
let n = 0
for (let i = glyphs.length - 1; i >= 0; i--) {
if (glyphs[i].changed) glyphs[i].fromEnd = n++
}
return glyphs
}
// The quiet default: a changed digit cross-fades in place, moving 0.14em
// with the number's direction and clearing a slight blur. Distances are in em
// so the motion fits the number's size.
// motion-role-exempt: a live value's digit swap runs 455ms on the expressive curve, the one number that may move (rules, Motion)
const SUBTLE = {
in: "animate-in fade-in blur-in-[0.042em] duration-[455ms] ease-expressive motion-reduce:animate-none",
out: "animate-out fade-out blur-out-[0.042em] duration-[455ms] ease-expressive fill-mode-forwards motion-reduce:animate-none",
up: { in: "slide-in-from-bottom-[0.14em]", out: "slide-out-to-top-[0.14em]" },
down: { in: "slide-in-from-top-[0.14em]", out: "slide-out-to-bottom-[0.14em]" },
}
// The rare moment: the old digit leaves upward fast, the new one rises 0.52em
// from 70% size a beat later and springs a little past its place. The last two
// changed digits trail by 40ms each.
// motion-role-exempt: the roll-in is an expressive moment, opt-in only; its 600ms and 50ms beat follow the moment's own timing
const ROLL = {
in: "animate-in fade-in zoom-in-70 slide-in-from-bottom-[0.52em] blur-in-[0.07em] duration-[600ms] ease-expressive-spring fill-mode-backwards motion-reduce:animate-none",
out: "animate-out fade-out zoom-out-70 slide-out-to-top-[0.52em] blur-out-[0.07em] duration-small ease-expressive fill-mode-forwards motion-reduce:animate-none",
// motion-role-exempt: a stagger offset, not a duration
delayIn: ["delay-[50ms]", "delay-[90ms]", "delay-[130ms]"],
delayOut: ["delay-0", "delay-[40ms]", "delay-[80ms]"],
}
// @use-when a number that changes while someone watches it (a live count, a
// running total, a price that updates) and should show the change without
// pulling the eye: only the changed digits move. Not MetricCard's value, which
// stays still because it is read often.
function LiveNumber({
value,
format,
locale = "en-US",
variant = "subtle",
className,
...props
}: Omit<React.ComponentProps<"span">, "children"> & {
value: number
/** Passed to `Intl.NumberFormat`: currency, percent, decimals. */
format?: Intl.NumberFormatOptions
/** Fixed by default so the server and the browser print the same string. */
locale?: string | string[]
/** `subtle` (default) for a value that changes often. `roll` for a rare
* moment, a number landing once: never both on one screen. */
variant?: LiveNumberVariant
}) {
const formatKey = JSON.stringify(format ?? null)
const localeKey = String(locale)
const formatter = React.useMemo(
() => new Intl.NumberFormat(locale, format),
// The keys stand in for the objects, which a caller often rebuilds each render.
// eslint-disable-next-line react-hooks/exhaustive-deps
[localeKey, formatKey]
)
const text = formatter.format(value)
const [state, setState] = React.useState({
text,
prev: null as string | null,
value,
rising: true,
change: 0,
})
if (state.text !== text) {
setState({
text,
prev: state.text,
value,
rising: value >= state.value,
change: state.change + 1,
})
}
const glyphs = diff(state.prev, state.text)
const dir = state.rising ? "up" : "down"
return (
<span
data-slot="live-number"
data-variant={variant}
className={cn("inline-block whitespace-nowrap tabular-nums", className)}
{...props}
>
{/* Read as one value, never digit by digit. */}
<span className="sr-only">{state.text}</span>
<span aria-hidden="true">
{glyphs.map((g, i) => {
if (!g.changed) {
return (
<span key={i} className="inline-block">
{g.char}
</span>
)
}
const step = Math.min(g.fromEnd, 2)
const enter =
variant === "roll"
? cn(ROLL.in, ROLL.delayIn[2 - step])
: cn(SUBTLE.in, SUBTLE[dir].in)
const leave =
variant === "roll"
? cn(ROLL.out, ROLL.delayOut[2 - step])
: cn(SUBTLE.out, SUBTLE[dir].out)
return (
// A new key per change, so the swap plays again on every change.
<span key={`${state.change}-${i}`} className="relative inline-block">
{g.old !== undefined && (
<span
className={cn(
"absolute inset-0 text-center motion-reduce:hidden",
leave
)}
>
{g.old}
</span>
)}
<span
className={cn("inline-block", enter)}
>
{g.char}
</span>
</span>
)
})}
</span>
</span>
)
}
export { LiveNumber, type LiveNumberVariant }