Primitives
Animated Number Avatar Badge Button Button Group Toggle Toggle Group Checkbox Chip Countdown Divider Fab Grid Icon Image Input Search Input Textarea Label Loader Marquee Masked Input Message Bubble Notification Banner Offline Banner Progress Progress Ring Radio Group Range Slider Rating Separator Skeleton Slider Stack Stepper Switch Text Theme Toggle Ticker Typing IndicatorComposed
Accordion Achievement Badge Action Bar Action Sheet Action Swap Activity Rings Add to Cart Button Address Card Agenda List Alert Amount Keypad Animated Icons App Bar Audio Message Audio Recorder Autocomplete Avatar Group Balance Display Bar List Barcode Before After Biometric Gate Bloom Menu Bottom Sheet Paywall Sheet Side Sheet Breadcrumb Calendar Calendar Strip Card Carousel Cart Item Character Charts Chat Composer Chat List Item Choice Card Circle Reveal Coach Marks Collapsible Collapsible Header Color Picker Combobox Command Palette Comment Thread Confetti Consent Sheet Context Menu Copy Field Country Picker Coupon Input Currency Input Data Table Date Range Picker Day Schedule Dialog Dock Donut Chart Drawer Driver Card Dropdown Menu Drum Picker Emoji Picker Empty State Error State Event Card Expandable Control Fader Feature Gate File Picker Filter Bar Follow Button Form Gauge Glass Glass Cluster Glass Dock Morph Glass Fab Morph Glass Lab Glass Orb Glass Search Morph Glass Sheet Edge Gradient Button Headline New Heatmap Image Cropper Image Viewer Kanban Card Keyboard Avoiding Keyboard Toolbar Leaderboard Level Progress Lightbox Like Button Line Chart List Reorderable List Swipeable Row Location Card Location Search Map Sheet Map View Markdown View Media Controls Media Picker Media Tile Mention Input Meter Bar Mini Player Mood Slider Morphing Modal Multi Select Navigation Rail Notification Item Number Input Onboarding Pager Order Card Order Summary OTP Input Pagination Paper Clip New Parallax Header Pass Card Password Strength Payment Button Payment Card Payment Method Permission Primer Phone Input PIN Pad Polaroid New Poll Popover Post Card Postage Stamp New Price Tag Pricing Table Product Card Product Gallery Profile Header Promo Banner Prompt Input Property Card Pull To Refresh QR Code Quick Actions Quick Replies Rating Summary Reaction Picker Resend Timer Review Card Review Prompt Ride Option Save Button Scan Frame Scroll Spy Tabs Seat Map Section Header Section Index Segmented Control Select Share Button Share Sheet Shutter Button Signature Pad Slide to Confirm Slot Picker Smart Banner Social Login Button Sparkline Splash Screen Split Button Stat Card Stateful Button Status Dot Step Flow Steps Sticker New Stopwatch Stories Progress Stories Viewer Story Ring Streak Counter Streaming Text Success Seal Swipe Deck Tabs Tag Input Tape New Text Reveal Thinking Indicator Time Picker Timeline Timer Ring Tip Selector Toast Toolbar Tooltip Track Row Transaction Row Trip Progress Variant Picker Video Controls Waveform Weather Card Weekday Picker Zoom TransitionScreens
Account Switcher Biometric Setup Delete Account Forgot Password Grow Auth Login Login — Dark Stage Login — Dense Work Login — Editorial Login — Illustrated Login — Minimal Ink Login — Social Login — Video Loop Food Onboarding Onboarding Onboarding Dark Objects Onboarding Editorial Onboarding Illustrated Onboarding Personalize Onboarding Photo Carousel OTP Verification Passkey — Create Password Reset Permission — Notifications Phone Verification Onboarding Quiz Session Devices Signup Sign-up Chat Sign-up Photo Sheet Social Auth Split Auth Verify Identity Welcome AI Chat AI Assistant Channels List Chat Info Chat List Chat Media Chat Thread Create Group Group Info Message Requests New Message Kept Messages Accessibility Activity Log Appearance Authenticator Blocked Accounts Export Your Data Downloads Edit Profile Edit Profile — Rows Emergency Call Empty States Set Error State Send Feedback Device Locator Help Center Home — Bento Home — Dark Home — Editorial Home Feed Invite Friends Language & Region Linked Accounts Not Found (404) Notification Settings Notifications Password Vault Paywall Paywall — Comparison Paywall — Dark Stage Paywall — Editorial Paywall — Photo Paywall — Trial Timeline Privacy Profile Profile — Gamified Profile — Minimal Profile — Photo Hero QR Scanner Report Issue Saved Items Phone Time Search Search — Command Palette Search — Visual Account Health Settings Settings — Dark Device Settings — Search Storage & Data Terms & Privacy Dating Chat Dating Filters Profile Discover Its A Match Into You Matches Profile Detail Profile Editor Courier Matching Delivery History Delivery Support Package Schedule Parcel Tracking Proof Of Delivery Quick Aisle Quick Home Send Package Substitutions Add Payment Address Book Cart Categories Checkout Checkout — Steps Checkout Success Delivery Filters & Sort Flash Sale Gift Cards Loyalty Points Order Cancel Order Detail Orders Pay Later Checkout Payment Methods Product Detail Product Detail — Hero Product Grid Product Reviews Promo Codes Recently Viewed Return Items Search Results Shop Assistant Store Home Tip & Rate Courier Order Tracking Wishlist Write a Review Event Checkin Event Hero Events Discover My Tickets Seat Selection Ticket Checkout Add Card Bank Accounts Dashboard — Bento Bill Pay Budgets Card Details Crypto Portfolio Finance Dashboard Dashboard — Dark Exchange Currency Expense List Invoice Detail Manage Cards Plan Management Savings Goals Send Money Spending Analytics Split Bill Subscriptions Token Detail Token Swap Transactions Wallet Home Wallet Movers Courier Tracking Food Cart Food Home Food Orders Grocery List Recipe Detail Restaurant — Dark Restaurant Detail Activity Rings Fitness Home Habit Quest Habit Tracker Meal Planner Med Store Meditation Player Mood Check-in Nutrition Home Period Tracker Prior Auth Prior Auth Cases Quest Complete Run Tracking Rx Scan Sleep Tracker Telehealth Booking Walk Map Water Tracker Workout Complete Workout Detail Workout Session Applications Apply Company Interview Schedule Job Detail Job Feed Resume Saved Jobs Create Listing Item Chat Listing Detail Make Offer Market Checkout Market Home Market Search My Listings Offers Inbox Seller Profile Audiobook Player Camera Gallery Albums Game Store Mini Player Music Player Photo Editor Photo Gallery Playlist Detail Podcast Player Clips Feed Serene Home Sound Mixer Stories Video Call Video Player Article Reader Course Detail Event Detail Memory Onboarding Icon Lab Leaderboard Lesson Player Match Detail News Editorial News Home Plant Care Prediction Live Prediction Welcome Smart Home Standings Ticket Wallet Topics Follow Weather Detail Add Task Sheet Alarm Clock Calendar Day Calendar Month Doc Scanner File Manager Focus Timer Journal Kanban Board Mail Inbox Mail Thread Note Editor Notes List Reminders Task List Time Blocks Agent Profile Compare Homes Mortgage Calculator Property Detail Rental Application Saved Homes Schedule Tour Search List Search Map Complete Destination Driver Arriving Ev Charging History Home In Trip Matching Options Parking Receipt Safety Schedule Scooter Unlock Booking Confirmed Booking Review Booking Slots My Bookings Pro On The Way Provider Detail Provider List Rate Service Services Home Arc Create Arc Detail Arc Onboarding Avatar Creator Comments Sheet Create Post Explore Grid Followers List Hashtag Feed Mentions Post Detail Post Hero Social Profile Boarding Pass Booking Confirm Car Rental Trip Discover Flight Live Flight Preferences Flight Results Flight Search Hotel Detail Live Transit Trip — Map Day Trip — Rideshare Request Seat Select Travel Home Trip Itinerary Trip OnboardingNothing matches — try another word.
Animated Number
Number that moves to each new value as a calm count-up or a roll where only the changed digits turn, set in type or in dot-matrix LEDs whose dots switch on in place. Screen readers announce just the final value, not every step.
Preview
import * as React from "react";
import { forwardRef, useEffect, useRef, useState } from "react";
import {
Dimensions,
Text,
View,
type LayoutChangeEvent,
type StyleProp,
type TextProps,
type TextStyle,
} from "react-native";
import Animated, {
cancelAnimation,
Easing,
interpolate,
runOnJS,
useAnimatedReaction,
useAnimatedStyle,
useSharedValue,
withDelay,
withSpring,
withTiming,
} from "react-native-reanimated";
import { cn, useReducedMotion, ease, spring, timing } from "@lumioui/core";
import { DotMatrixText } from "./dot-matrix";
/**
* AnimatedNumber — a number that moves from the previous value to the new
* one when `value` changes. Set in the system font with tabular numerals so
* digits never jitter sideways.
* <AnimatedNumber value={1234} />
* <AnimatedNumber value={0.85} format={(n) => `${Math.round(n * 100)}%`} />
* <AnimatedNumber value={balance} format={usd} animation="roll" />
*
* Motion styles:
* - "ease" (default) counts the whole figure on the ease.out token.
* - "spring" counts it on the spring.roll token.
* - "roll" is the Lumio odometer: each character column swaps on its own,
* 30ms apart from the right, on spring.roll. Only the columns that
* change move — the incoming digit ignites half-bright, travels at most
* 6pt in the direction of the change and brightens as it settles, while
* the outgoing digit dims. Unchanged digits stay at rest.
*
* Faces: `face="led"` sets the figure in dot-matrix LEDs (DotMatrixText).
* With "roll" only the dots that differ switch, column by column; counts
* ("ease"/"spring") switch each step instantly, like a real panel.
* <AnimatedNumber value={steps} face="led" animation="roll" dot={6} />
*
* No count lands with a bounce: numbers are content, not a celebration.
* With `startOnView` (default) the first change waits until the number is
* actually visible on screen. Reduced motion keeps the brightening and
* drops the travel (counts jump straight to the value). Screen readers hear
* only the final value — never the mid-count chatter.
*
* Threading: counts tween on the UI thread; a worklet quantizes the tween to
* the displayed precision and hops to JS only when that step changes. The
* roll re-renders once per value change — every frame after that is a
* shared value. `format` (often `toLocaleString`, not a worklet) runs on JS.
*/
/** Visibility re-check cadence while a first count is still waiting. One
* shared timer serves every waiting instance and stops when none are left. */
const VISIBILITY_POLL_MS = 500;
/** Decimal places to track by default — enough for cents and percentages. */
const MAX_INFERRED_PRECISION = 3;
/** Columns step on this rhythm, rightmost first (the number-ticker beat). */
export const ROLL_STAGGER = 30;
/** Directional travel of a swapping digit (pt) — the §5 count cap. */
const ROLL_TRAVEL = 6;
/** A changed digit ignites to this brightness, then brightens to full as it settles. */
const ROLL_IGNITE = 0.5;
/** Share of the column's settle spent igniting to ROLL_IGNITE (~70ms on spring.roll). */
const ROLL_IGNITE_AT = 0.15;
const DIM_EASING = Easing.bezier(...ease.in);
const IGNITE_EASING = Easing.bezier(...ease.out);
// ── Shared visibility ticker ────────────────────────────────────────────────
// One interval for the whole app instead of one per instance: a dashboard
// with twelve stat tiles waiting below the fold costs one timer, not twelve,
// and the timer is torn down the moment the last waiter starts or unmounts.
const visibilityWaiters = new Set<() => void>();
let visibilityTimer: ReturnType<typeof setInterval> | null = null;
function watchVisibility(check: () => void): () => void {
visibilityWaiters.add(check);
if (visibilityTimer == null) {
visibilityTimer = setInterval(() => {
// Copy first — a check that starts its count unsubscribes mid-loop.
Array.from(visibilityWaiters).forEach((fn) => fn());
}, VISIBILITY_POLL_MS);
}
return () => {
visibilityWaiters.delete(check);
if (visibilityWaiters.size === 0 && visibilityTimer != null) {
clearInterval(visibilityTimer);
visibilityTimer = null;
}
};
}
/** Decimal places in a number's shortest representation, capped. */
function decimalsOf(n: number): number {
if (!Number.isFinite(n) || Number.isInteger(n)) return 0;
const s = String(n);
const e = s.indexOf("e-");
if (e !== -1) return MAX_INFERRED_PRECISION;
const dot = s.indexOf(".");
return dot === -1 ? 0 : Math.min(MAX_INFERRED_PRECISION, s.length - dot - 1);
}
// ── RollingText — the per-column odometer ───────────────────────────────────
export interface RollingTextProps {
/** The figure to show, already formatted ("$6,482.17"). */
text: string;
/** 1 = the value went up (digits rise into place), -1 = down. Default 1. */
direction?: 1 | -1;
/** Row container — placement only (margins, alignment). */
className?: string;
/** Typography for every glyph (size, weight, ink). */
glyphClassName?: string;
glyphStyle?: StyleProp<TextStyle>;
/** Characters from this index on use `minorClassName` — cents set smaller. */
minorFrom?: number;
minorClassName?: string;
/** Swap without motion (e.g. animation turned off by the caller). */
instant?: boolean;
/** Fires on JS once the last changed column has settled. */
onSettle?: () => void;
}
interface RollState {
text: string;
prev: string;
gen: number;
}
/**
* RollingText — renders a formatted figure as one column per character and
* swaps only the columns whose character changed. Columns are keyed from the
* right so units stay units as the figure grows ("999" → "1,000" adds
* columns on the left). Decorative glyphs; give the parent the a11y label.
*/
export function RollingText({
text,
direction = 1,
className,
glyphClassName,
glyphStyle,
minorFrom,
minorClassName,
instant = false,
onSettle,
}: RollingTextProps) {
const reduce = useReducedMotion();
// Previous text + a generation per change, resolved during render so the
// changed columns and their delays are known in the same pass.
const [roll, setRoll] = useState<RollState>({ text, prev: text, gen: 0 });
let current = roll;
if (roll.text !== text) {
current = { text, prev: roll.text, gen: roll.gen + 1 };
setRoll(current);
}
const settleRef = useRef(onSettle);
settleRef.current = onSettle;
const genRef = useRef(current.gen);
genRef.current = current.gen;
// Stable across renders so a column's effect never restarts mid-roll; a
// stale generation (interrupted by a newer change) is ignored.
const land = React.useCallback((gen: number) => {
if (gen === genRef.current) settleRef.current?.();
}, []);
const { prev, gen } = current;
const len = text.length;
const slots: { ch: string; old: string; changed: boolean; rank: number }[] = [];
let changedCount = 0;
// Walk from the right so the rank (stagger order) starts at the units.
for (let r = 0; r < len; r++) {
const ch = text[len - 1 - r]!;
const old = prev[prev.length - 1 - r] ?? "";
const changed = gen > 0 && ch !== old;
slots.push({ ch, old, changed, rank: changed ? changedCount++ : -1 });
}
slots.reverse();
// A change that moved no column (or only removed columns) settles at once.
useEffect(() => {
if (gen > 0 && changedCount === 0) land(gen);
}, [gen, changedCount, land]);
return (
<View className={cn("flex-row items-baseline", className)}>
{slots.map((slot, i) => {
const minor = minorFrom !== undefined && minorFrom >= 0 && i >= minorFrom;
return (
<RollColumn
key={len - 1 - i}
ch={slot.ch}
old={slot.old}
changed={slot.changed}
delay={Math.max(0, slot.rank) * ROLL_STAGGER}
isLast={slot.changed && slot.rank === changedCount - 1}
gen={gen}
dir={direction}
instant={instant}
reduce={reduce}
onLand={land}
className={cn("tabular-nums text-foreground", glyphClassName, minor && minorClassName)}
style={glyphStyle}
/>
);
})}
</View>
);
}
RollingText.displayName = "RollingText";
interface RollColumnProps {
ch: string;
old: string;
changed: boolean;
delay: number;
isLast: boolean;
gen: number;
dir: 1 | -1;
instant: boolean;
reduce: boolean;
onLand: (gen: number) => void;
className?: string;
style?: StyleProp<TextStyle>;
}
function RollColumn({
ch,
old,
changed,
delay,
isLast,
gen,
dir,
instant,
reduce,
onLand,
className,
style,
}: RollColumnProps) {
// t: incoming 0 → 1 on spring.roll. out: outgoing dims 0 → 1.
const t = useSharedValue(changed && !instant ? 0 : 1);
const out = useSharedValue(changed && !instant ? 0 : 1);
useEffect(() => {
if (!changed) return;
if (instant) {
t.value = 1;
out.value = 1;
if (isLast) onLand(gen);
return;
}
t.value = 0;
out.value = 0;
out.value = withDelay(delay, withTiming(1, { ...timing.recede, easing: DIM_EASING }));
t.value = withDelay(
delay,
withSpring(1, spring.roll, (finished) => {
if (finished && isLast) runOnJS(onLand)(gen);
})
);
}, [gen, changed, delay, instant, isLast, onLand, t, out]);
const inStyle = useAnimatedStyle(() => ({
opacity: interpolate(t.value, [0, ROLL_IGNITE_AT, 1], [0, ROLL_IGNITE, 1], "clamp"),
transform: [{ translateY: reduce ? 0 : (1 - t.value) * ROLL_TRAVEL * dir }],
}));
const outStyle = useAnimatedStyle(() => ({
opacity: 1 - out.value,
// Exits travel half as far as the entrance, the other way.
transform: [{ translateY: reduce ? 0 : -out.value * (ROLL_TRAVEL / 2) * dir }],
}));
return (
<View>
{changed && old !== "" ? (
<Animated.Text
className={className}
style={[style, { position: "absolute", left: 0, right: 0, textAlign: "center" }, outStyle]}
>
{old}
</Animated.Text>
) : null}
<Animated.Text className={className} style={[style, inStyle]}>
{ch}
</Animated.Text>
</View>
);
}
// ── AnimatedNumber ──────────────────────────────────────────────────────────
export interface AnimatedNumberProps extends TextProps {
/** Target value. */
value: number;
/** Value the first count starts from. Default 0. */
from?: number;
/** Count duration in ms for "ease". Default 1000. Ignored by "spring" and "roll". */
duration?: number;
/**
* Motion style — "ease" (default) counts with the ease.out token over
* `duration` ms; "spring" counts on the spring.roll token; "roll" swaps
* each changed digit column in place, 30ms apart from the right.
*/
animation?: "ease" | "spring" | "roll";
/** Format the displayed number. Default rounds and locale-formats. Runs on the JS thread. */
format?: (n: number) => string;
/**
* Decimal places the count re-renders at. Defaults to the precision of
* `value` / `from` (an integer target re-renders once per whole number).
* Raise it if your `format` shows more decimals than the value carries.
*/
precision?: number;
/** Wait until the number is visible before the first count. Default true. */
startOnView?: boolean;
/** Fires on JS when a change has landed — the moment to hold, sheen or move on. */
onSettle?: () => void;
/** Glyph typography (size, weight, ink). In "roll" mode it styles every column. */
className?: string;
/** "roll" and "led" — placement classes for the row of columns. */
containerClassName?: string;
/** "type" (default) sets the figure in the system font; "led" in dot-matrix LEDs. */
face?: "type" | "led";
/** "led" only — LED diameter in pt. Default 5. */
dot?: number;
/** "led" only — lit colour. Default the theme ink. */
color?: string;
/** "led" only — changed dots light in this colour for a beat, then settle.
* `animation="roll"` only — the ease/spring count-up switches instantly every
* frame, so it has no beat. */
beatColor?: string;
}
export const AnimatedNumber = forwardRef<React.ElementRef<typeof Text>, AnimatedNumberProps>(
function AnimatedNumber(
{
value,
from = 0,
duration = 1000,
animation = "ease",
format,
precision,
startOnView = true,
onSettle,
className,
containerClassName,
face = "type",
dot,
color,
beatColor,
onLayout,
style,
...props
},
ref
) {
const reduce = useReducedMotion();
const fmt = React.useMemo(
() => format ?? ((n: number) => Math.round(n).toLocaleString()),
[format]
);
// Latest formatter / settle handler for JS-side callbacks without re-subscribing.
const fmtRef = useRef(fmt);
fmtRef.current = fmt;
const settleRef = useRef(onSettle);
settleRef.current = onSettle;
const rolling = animation === "roll";
// Quantization scale: 10^decimals. The worklet works in integer steps
// (Math.round(v * scale)) so it can tell "the visible number changed"
// without ever calling the formatter on the UI thread.
const decimals = precision ?? Math.max(decimalsOf(value), decimalsOf(from));
const scale = Math.pow(10, Math.max(0, Math.min(6, Math.round(decimals))));
const [text, setText] = useState(() => fmt(from));
// Roll mode: the value the columns show and which way it last moved.
const [rollTo, setRollTo] = useState<{ to: number; dir: 1 | -1 }>({ to: from, dir: 1 });
const fromRef = useRef(from);
const anim = useSharedValue(from);
const started = useRef(false);
const hostRef = useRef<React.ElementRef<typeof Text> | null>(null);
// Re-render only when the visible string actually changes.
const setTextIfChanged = React.useCallback((next: string) => {
setText((prev) => (prev === next ? prev : next));
}, []);
/** JS side of the hop: an integer step index → formatted string. */
const onStep = React.useCallback(
(step: number, stepScale: number) => {
setTextIfChanged(fmtRef.current(step / stepScale));
},
[setTextIfChanged]
);
/** Landing: format the exact target (not the quantized step) on JS. */
const land = React.useCallback(
(to: number) => {
setTextIfChanged(fmtRef.current(to));
settleRef.current?.();
},
[setTextIfChanged]
);
const rollSettled = React.useCallback(() => settleRef.current?.(), []);
const animateTo = React.useCallback(
(to: number) => {
if (rolling) {
// The columns own the motion (and reduced motion); just move the target.
setRollTo({ to, dir: to >= fromRef.current ? 1 : -1 });
fromRef.current = to;
return;
}
if (reduce) {
cancelAnimation(anim);
anim.value = to;
fromRef.current = to;
setTextIfChanged(fmtRef.current(to));
settleRef.current?.();
return;
}
anim.value = fromRef.current;
if (animation === "spring") {
// spring.roll — the heavy odometer settle, so the count glides in
// like a reel instead of a fixed-duration tween.
anim.value = withSpring(to, spring.roll, (finished) => {
if (finished) runOnJS(land)(to);
});
} else {
anim.value = withTiming(to, { duration, easing: IGNITE_EASING }, (finished) => {
if (finished) runOnJS(land)(to);
});
}
fromRef.current = to;
},
[anim, duration, animation, rolling, reduce, land, setTextIfChanged]
);
const start = React.useCallback(() => {
if (started.current) return;
started.current = true;
animateTo(value);
}, [animateTo, value]);
// First count: immediately, or once visible. measureInWindow is async
// and can report garbage (0 height, NaN on web) before first layout —
// untrusted readings are skipped, not treated as "off screen".
const checkVisible = React.useCallback(() => {
if (started.current) return;
if (!startOnView) {
start();
return;
}
const node = hostRef.current as unknown as {
measureInWindow?: (cb: (x: number, y: number, w: number, h: number) => void) => void;
} | null;
if (!node?.measureInWindow) {
start();
return;
}
try {
node.measureInWindow((_x, y, _w, h) => {
if (started.current) return;
if (!Number.isFinite(y) || !Number.isFinite(h) || h <= 0) return;
const screenH = Dimensions.get("window").height;
if (y + h > 0 && y < screenH) start();
});
} catch {
start();
}
}, [start, startOnView]);
// Latest checker for the shared ticker — subscribing once per waiting
// period instead of on every callback identity change.
const checkRef = useRef(checkVisible);
checkRef.current = checkVisible;
useEffect(() => {
// Catch the already-on-screen case at mount, then join the shared
// ticker until the first count starts (covers mount-time layout races
// and scroll-into-view). Unsubscribes on start and on unmount.
checkRef.current();
if (!startOnView || started.current) return;
let unwatch: (() => void) | null = null;
unwatch = watchVisibility(() => {
if (started.current) {
unwatch?.();
unwatch = null;
return;
}
checkRef.current();
});
return () => unwatch?.();
}, [startOnView]);
// Later value changes always animate (covers lists that scrolled into
// view without a fresh layout pass). Skipped on mount — the mount
// effect above owns the first count so startOnView is honored.
const mounted = useRef(false);
useEffect(() => {
if (!mounted.current) {
mounted.current = true;
return;
}
if (!started.current) {
started.current = true;
}
animateTo(value);
return () => cancelAnimation(anim);
}, [value, animateTo, anim]);
// UI thread: quantize the tween to the displayed precision and hop to
// JS only when that integer step changes — never per frame for nothing,
// and never a JS-only formatter inside the worklet.
useAnimatedReaction(
() => Math.round(anim.value * scale),
(step, prev) => {
if (step !== prev) runOnJS(onStep)(step, scale);
},
[scale, onStep]
);
const setHost = (node: unknown) => {
const host = node as React.ElementRef<typeof Text> | null;
hostRef.current = host;
if (typeof ref === "function") ref(host as React.ElementRef<typeof Text>);
else if (ref) ref.current = host;
};
const handleLayout = (e: LayoutChangeEvent) => {
checkVisible();
onLayout?.(e);
};
if (face === "led") {
return (
<View
ref={setHost}
onLayout={handleLayout}
accessible
accessibilityRole="text"
accessibilityLabel={fmt(value)}
accessibilityLiveRegion="none"
testID={props.testID}
>
<DotMatrixText
text={rolling ? fmt(rollTo.to) : text}
instant={!rolling}
dot={dot}
color={color}
beatColor={beatColor}
className={containerClassName}
onSettle={rolling ? rollSettled : undefined}
/>
</View>
);
}
if (rolling) {
return (
<View
ref={setHost}
onLayout={handleLayout}
accessible
accessibilityRole="text"
accessibilityLabel={fmt(value)}
accessibilityLiveRegion="none"
testID={props.testID}
>
<RollingText
text={fmt(rollTo.to)}
direction={rollTo.dir}
className={containerClassName}
glyphClassName={className}
glyphStyle={style}
onSettle={rollSettled}
/>
</View>
);
}
return (
<Text
ref={setHost}
onLayout={handleLayout}
className={cn("tabular-nums text-foreground", className)}
style={style}
accessibilityRole="text"
accessibilityLabel={fmt(value)}
accessibilityLiveRegion="none"
{...props}
>
{text}
</Text>
);
}
);
AnimatedNumber.displayName = "AnimatedNumber"; import { AnimatedNumber } from "@/components/ui/animated-number/animated-number";
export function Example() {
return (
<AnimatedNumber />
);
} Installation
Install the dependencies
npx expo install react-native-reanimated react-native-svgCopy the source from the Code tab into your project
components/ui/animated-number/animated-number.tsxcomponents/ui/animated-number/dot-matrix.tsxcomponents/ui/animated-number/index.tsUpdate the import paths to match your project setup.
Usage
import { ROLL_STAGGER, RollingText, AnimatedNumber } from "@/components/ui/animated-number/animated-number"; <AnimatedNumber /> Also exported: ROLL_STAGGER, RollingText.
Examples
A savings goal in a banking app.
import * as React from "react";
import { View } from "react-native";
import Animated, { useAnimatedStyle, useSharedValue, withSpring } from "react-native-reanimated";
import { Accent, Sheen, spring, useReducedMotion, useTheme } from "@lumioui/core";
import { AnimatedNumber } from "../animated-number";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const GOAL = 10000;
const usd = (n: number) =>
`$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
/** AnimatedBalance — a savings goal in a banking app. A deposit rolls only
* the digits that change, 30ms apart from the right; as the last column
* lands one sheen crosses the figure. A withdrawal rolls down with no
* light. The goal bar follows on a spring. */
export function AnimatedBalance() {
const reduce = useReducedMotion();
const [balance, setBalance] = React.useState(6482.17);
const [last, setLast] = React.useState<string>("Round-ups · $3.60 yesterday");
const [sheen, setSheen] = React.useState(0);
const deposit = React.useRef(false);
const fill = useSharedValue(balance / GOAL);
const move = (delta: number, note: string) => {
const next = Math.min(GOAL, Math.max(0, Math.round((balance + delta) * 100) / 100));
const t = next / GOAL;
fill.value = reduce ? t : withSpring(t, spring.layout);
deposit.current = delta > 0;
setBalance(next);
setLast(note);
};
// Money in is the moment: light crosses the figure as it lands.
const landed = () => {
if (deposit.current) setSheen((n) => n + 1);
deposit.current = false;
};
const fillStyle = useAnimatedStyle(() => ({
transform: [{ scaleX: fill.value }],
}));
return (
<Accent color="green" className="w-full">
<View className="w-full gap-5 rounded-3xl bg-card p-5">
<View className="flex-row items-center gap-3">
<View className="h-10 w-10 items-center justify-center rounded-full bg-primary">
<Icon name="shield" size="sm" color="primaryForeground" />
</View>
<View className="flex-1">
<Text className="text-[17px] font-semibold">Emergency fund</Text>
<Text variant="muted">4.30% APY · Goal $10,000</Text>
</View>
</View>
<View className="gap-1">
<View className="self-start overflow-hidden">
<AnimatedNumber
value={balance}
format={usd}
animation="roll"
onSettle={landed}
className="text-5xl font-semibold tracking-tight"
/>
<FigureSheen run={sheen} />
</View>
<Text variant="muted">{last}</Text>
</View>
<View className="gap-2">
<View className="h-2 w-full overflow-hidden rounded-full bg-secondary">
<Animated.View
className="h-full w-full rounded-full bg-primary"
style={[{ transformOrigin: "left" }, fillStyle]}
/>
</View>
<View className="flex-row justify-between">
<Text className="text-xs text-muted-foreground tabular-nums">
{Math.round((balance / GOAL) * 100)}% saved
</Text>
<Text className="text-xs text-muted-foreground tabular-nums">
{usd(GOAL - balance)} to go
</Text>
</View>
</View>
<View className="flex-row gap-2">
<Button
size="lg"
className="flex-1"
onPress={() => move(250, "Deposit · $250.00 just now")}
disabled={balance >= GOAL}
>
Add $250
</Button>
<Button
size="lg"
variant="secondary"
className="flex-1"
onPress={() => move(-120, "Moved $120.00 to Checking")}
disabled={balance <= 0}
>
Withdraw
</Button>
</View>
</View>
</Accent>
);
}
/** Sheen in the surrounding accent on paper, white light on a dark stage —
* rendered inside the Accent so it picks up the demo's hue. */
function FigureSheen({ run }: { run: number }) {
const { colors, scheme } = useTheme();
return <Sheen run={run} color={scheme === "dark" ? "#FFFFFF" : colors.primary} strength={0.24} />;
} A living-room thermostat.
import * as React from "react";
import { Text, View } from "react-native";
import {
ACCENTS,
Accent,
AnimatedPressable,
LightFall,
cn,
useHaptic,
usePressAnimation,
useTheme,
type AccentName,
} from "@lumioui/core";
import { AnimatedNumber } from "../animated-number";
const SCENES: { name: string; hue: AccentName; target: number; note: string }[] = [
{ name: "Ember", hue: "coral", target: 23, note: "Warm and low for the evening" },
{ name: "Daylight", hue: "amber", target: 21, note: "Bright and steady for working" },
{ name: "Fresh", hue: "mint", target: 18, note: "Cool air for sleeping" },
];
function SceneButton({
name,
on,
onPress,
}: {
name: string;
on: boolean;
onPress: () => void;
}) {
const press = usePressAnimation({ pressedScale: 0.95 });
return (
<AnimatedPressable
onPress={onPress}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
style={press.animatedStyle}
className={cn("h-12 flex-1 items-center justify-center rounded-2xl", on ? "bg-primary" : "bg-secondary")}
accessibilityRole="radio"
accessibilityState={{ checked: on }}
accessibilityLabel={`${name} scene`}
>
<Text className={cn("text-[15px] font-semibold", on ? "text-primary-foreground" : "text-secondary-foreground")}>
{name}
</Text>
</AnimatedPressable>
);
}
/** AnimatedNumberLed — a living-room thermostat. The room temperature is a
* dot-matrix LED figure that creeps toward the scene's target as the room
* heats or cools, one tenth at a time — only the LEDs that differ switch.
* Picking a scene re-lights the stage: the light from above glides over the
* chosen scene and takes its colour. */
export function AnimatedNumberLed() {
const haptic = useHaptic();
const { colors } = useTheme();
const [pick, setPick] = React.useState(0);
const [room, setRoom] = React.useState(19.4);
const scene = SCENES[pick]!;
// The room drifts a tenth toward the target every couple of seconds.
React.useEffect(() => {
const id = setInterval(() => {
setRoom((t) => {
const d = scene.target - t;
if (Math.abs(d) < 0.05) return scene.target;
return Math.round((t + Math.sign(d) * 0.1) * 10) / 10;
});
}, 1800);
return () => clearInterval(id);
}, [scene.target]);
const heading = room < scene.target - 0.05 ? "Heating" : room > scene.target + 0.05 ? "Cooling" : "Holding";
return (
<Accent color={scene.hue} className="w-full">
<View className="w-full overflow-hidden rounded-3xl bg-card">
<LightFall color={ACCENTS[scene.hue].fill} at={(pick + 0.5) / SCENES.length} reach={0.85} />
<View className="gap-6 p-6">
<View className="flex-row items-center justify-between">
<Text className="text-[15px] font-semibold text-foreground">Living room</Text>
<Text className="text-sm text-muted-foreground">
{heading} to {scene.target}°
</Text>
</View>
<View className="items-center gap-3 py-6">
<AnimatedNumber
value={room}
from={room}
precision={1}
format={(n) => `${n.toFixed(1)}°`}
animation="roll"
face="led"
dot={8}
color={colors.foreground}
beatColor={colors.primaryText}
/>
<Text className="text-sm text-muted-foreground">{scene.note}</Text>
</View>
<View className="w-full flex-row gap-2" accessibilityRole="radiogroup">
{SCENES.map((s, i) => (
<SceneButton
key={s.name}
name={s.name}
on={i === pick}
onPress={() => {
if (i === pick) return;
haptic.selection();
setPick(i);
}}
/>
))}
</View>
</View>
</View>
</Accent>
);
} A running log's totals.
import * as React from "react";
import { View } from "react-native";
import { AnimatedNumber } from "../animated-number";
import { SegmentedControl } from "../../segmented-control/segmented-control";
import { Text } from "../../text/text";
type Range = "week" | "month" | "year";
const DATA: Record<Range, { km: number; minutes: number; climb: number; note: string }> = {
week: { km: 32.4, minutes: 171, climb: 412, note: "Longest run 12.1 km on Sunday" },
month: { km: 118.6, minutes: 642, climb: 1580, note: "14 runs · best 5K 23:48" },
year: { km: 1204.9, minutes: 6390, climb: 15220, note: "On pace for 1,450 km this year" },
};
const km = (n: number) => n.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
const hm = (n: number) => {
const m = Math.round(n);
return `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`;
};
const meters = (n: number) => Math.round(n).toLocaleString("en-US");
/** AnimatedStats — a running log's totals. Switch the range and every
* number counts from the old total to the new one. */
export function AnimatedStats() {
const [range, setRange] = React.useState<Range>("week");
const d = DATA[range];
const stats = [
{ label: "Distance", unit: "km", value: d.km, format: km, precision: 1 },
{ label: "Time", unit: "", value: d.minutes, format: hm, precision: 0 },
{ label: "Elevation", unit: "m", value: d.climb, format: meters, precision: 0 },
];
return (
<View className="w-full gap-4 rounded-3xl bg-card p-5">
<View className="flex-row items-center justify-between">
<Text className="text-[17px] font-semibold">Running</Text>
<Text variant="muted">Oct 6 – 12</Text>
</View>
<SegmentedControl
size="sm"
options={[
{ value: "week", label: "Week" },
{ value: "month", label: "Month" },
{ value: "year", label: "Year" },
]}
value={range}
onValueChange={(v) => setRange(v as Range)}
/>
<View className="flex-row">
{stats.map((s, i) => (
<View key={s.label} className={`flex-1 gap-1 ${i > 0 ? "border-l border-border pl-4" : ""}`}>
<Text variant="muted">{s.label}</Text>
<View className="flex-row items-baseline gap-1">
<AnimatedNumber
value={s.value}
format={s.format}
precision={s.precision}
duration={700}
className="text-xl font-semibold tracking-tight"
/>
{s.unit ? <Text className="text-sm text-muted-foreground">{s.unit}</Text> : null}
</View>
</View>
))}
</View>
<Text variant="muted" className="border-t border-border pt-3">{d.note}</Text>
</View>
);
} API reference
RollingText
text* string The figure to show, already formatted ("$6,482.17").
—direction 1 | -1 1 = the value went up (digits rise into place), -1 = down. Default 1.
1 className string Row container — placement only (margins, alignment).
—glyphClassName string Typography for every glyph (size, weight, ink).
—glyphStyle StyleProp<TextStyle> — minorFrom number Characters from this index on use minorClassName — cents set smaller.
minorClassName string — instant boolean Swap without motion (e.g. animation turned off by the caller).
false onSettle () => void Fires on JS once the last changed column has settled.
—AnimatedNumber
value* number Target value.
—from number Value the first count starts from. Default 0.
0 duration number Count duration in ms for "ease". Default 1000. Ignored by "spring" and "roll".
1000 animation "ease" | "spring" | "roll" Motion style — "ease" (default) counts with the ease.out token over duration ms; "spring" counts on the spring.roll token; "roll" swaps each changed digit column in place, 30ms apart from the right.
"ease" format (n: number) => string Format the displayed number. Default rounds and locale-formats. Runs on the JS thread.
—precision number Decimal places the count re-renders at. Defaults to the precision of value / from (an integer target re-renders once per whole number). Raise it if your format shows more decimals than the value carries.
startOnView boolean Wait until the number is visible before the first count. Default true.
true onSettle () => void Fires on JS when a change has landed — the moment to hold, sheen or move on.
—className string Glyph typography (size, weight, ink). In "roll" mode it styles every column.
—containerClassName string "roll" and "led" — placement classes for the row of columns.
—face "type" | "led" "type" (default) sets the figure in the system font; "led" in dot-matrix LEDs.
"type" dot number "led" only — LED diameter in pt. Default 5.
—color string "led" only — lit colour. Default the theme ink.
—beatColor string "led" only — changed dots light in this colour for a beat, then settle. animation="roll" only — the ease/spring count-up switches instantly every frame, so it has no beat.