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.
Number Input
Number field between minus and plus buttons, with a prefix or unit, limits, steps and decimals. Holding a button speeds up, and each tap nudges the figure up or down as it swaps.
Preview
import * as React from "react";
import { forwardRef, useState } from "react";
import { Text, TextInput, View, type TextInputProps } from "react-native";
import Animated, {
Easing,
interpolateColor,
useAnimatedStyle,
useSharedValue,
withSequence,
withSpring,
withTiming,
} from "react-native-reanimated";
import {
AnimatedPressable,
AnimatedTextInput,
cn,
createVariant,
ease,
spring,
timing,
useHaptic,
usePressAnimation,
useReducedMotion,
useTheme,
} from "@lumioui/core";
import { Icon, type IconName } from "../icon";
/**
* NumberInput — an editable numeric field flanked by − / + buttons, with a
* prefix (`$`) or unit suffix (`kg`, `servings`), min / max / step and
* decimal precision. Tap to type an exact value (clamped on commit), tap
* the buttons to step, hold them to repeat with acceleration.
*
* Motion: each step swaps the number in place with direction — the old
* figure dims and drifts 2pt the way the count is going while the new one
* ignites and settles 4pt into place, so a count up rises and a count down
* falls. Hitting a bound flickers the button once (a 4pt kick, opacity
* dipping to 0.6) with a warning haptic; an out-of-range typed value
* flickers the field the same way as it snaps back into range. `onStep`
* reports each step with its direction and whether a hold is repeating, so
* a screen can carry the change on (quantities below swapping in turn).
*
* <NumberInput label="Servings" defaultValue={4} min={1} max={12} unit="servings" />
*
* Expo Go compatible.
*/
/** Flicker for "can't": one small kick, released into spring.shake… */
const KICK = 4;
/** …while the light dips to this and comes back. */
const FLICKER_DIM = 0.6;
/** A swapping figure's travel (pt) — inside the §5 count cap. */
const SWAP_TRAVEL = 4;
/** Hold-to-repeat: first repeat after 380ms, then every 110ms, speeding to
* 45ms after ten ticks (stepper acceleration feel). */
const REPEAT_DELAY = 380;
const REPEAT_SLOW = 110;
const REPEAT_FAST = 45;
const fieldVariants = createVariant({
base: "flex-row items-center",
variants: {
variant: {
field: "rounded-xl border-[1.5px] bg-background px-1",
inline: "rounded-full bg-secondary px-1",
},
size: {
sm: "h-9",
md: "h-12",
lg: "h-14",
},
},
defaultVariants: { variant: "field", size: "md" },
});
const valueTextVariants = createVariant({
base: "text-center font-semibold tabular-nums text-foreground",
variants: {
size: { sm: "text-[15px]", md: "text-lg", lg: "text-2xl" },
},
defaultVariants: { size: "md" },
});
const BUTTON_SIZE = { sm: "h-7 w-7", md: "h-10 w-10", lg: "h-12 w-12" } as const;
const HIT = { sm: 8, md: 2, lg: 0 } as const;
/** Approximate tabular-digit advance per size (≈0.6em). The TextInput is
* sized to its content — on web an <input> otherwise claims its default
* ~20-character intrinsic width and an inline stepper balloons over its
* neighbours in a row. */
const DIGIT_WIDTH = { sm: 9, md: 11, lg: 15 } as const;
function round(n: number, precision: number) {
const f = 10 ** precision;
return Math.round(n * f) / f;
}
interface StepButtonProps {
icon: IconName;
label: string;
atBound: boolean;
disabled?: boolean;
size: "sm" | "md" | "lg";
/** Which way the button pushes — the flicker kicks that way. */
dir: 1 | -1;
onStep: (repeating: boolean) => boolean;
}
function StepButton({ icon, label, atBound, disabled, size, dir, onStep }: StepButtonProps) {
const haptics = useHaptic();
const reduceMotion = useReducedMotion();
const press = usePressAnimation({ pressedScale: 0.88, pressedOpacity: 0.7 });
const nudge = useSharedValue(0);
const flicker = useSharedValue(1);
const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const ticks = React.useRef(0);
const stepRef = React.useRef(onStep);
stepRef.current = onStep;
const stop = React.useCallback(() => {
if (timer.current) clearTimeout(timer.current);
timer.current = null;
ticks.current = 0;
}, []);
React.useEffect(() => stop, [stop]);
const nope = () => {
haptics.warning();
flicker.value = withSequence(withTiming(FLICKER_DIM, timing.instant), withTiming(1, timing.fast));
if (!reduceMotion) {
nudge.value = KICK * dir;
nudge.value = withSpring(0, spring.shake);
}
};
const repeat = () => {
const moved = stepRef.current(true);
if (!moved) {
stop();
return;
}
haptics.light();
ticks.current += 1;
timer.current = setTimeout(repeat, ticks.current > 10 ? REPEAT_FAST : REPEAT_SLOW);
};
const nudgeStyle = useAnimatedStyle(() => ({ opacity: flicker.value, transform: [{ translateX: nudge.value }] }));
const off = disabled || atBound;
return (
<AnimatedPressable
// Never responder-disabled so a tap at the bound can still answer.
disabled={disabled}
onPress={() => {
if (off) return nope();
if (stepRef.current(false)) haptics.selection();
}}
onLongPress={() => {
if (off) return;
timer.current = setTimeout(repeat, 0);
}}
delayLongPress={REPEAT_DELAY}
onPressIn={() => {
if (!off) press.onPressIn();
}}
onPressOut={() => {
press.onPressOut();
stop();
}}
style={press.animatedStyle}
className={cn(BUTTON_SIZE[size], "items-center justify-center rounded-full", off && "opacity-40")}
hitSlop={HIT[size]}
accessibilityRole="button"
accessibilityLabel={label}
accessibilityState={{ disabled: off }}
aria-disabled={off}
>
<Animated.View style={nudgeStyle}>
<Icon name={icon} size={size === "lg" ? "md" : "sm"} color="foreground" strokeWidth={2.5} />
</Animated.View>
</AnimatedPressable>
);
}
export interface NumberInputProps
extends Omit<TextInputProps, "value" | "defaultValue" | "onChangeText" | "className" | "keyboardType"> {
/** Controlled value. */
value?: number;
/** Uncontrolled initial value. Default `min` if finite, else 0. */
defaultValue?: number;
/** Fires on every committed change (step, hold tick, typed commit). */
onValueChange?: (value: number) => void;
/** Fires on each button / a11y step with its direction, and `repeating`
* while a held button is auto-stepping — e.g. to tighten a cascade. */
onStep?: (value: number, info: { direction: 1 | -1; repeating: boolean }) => void;
/** Lower bound. Default -Infinity. */
min?: number;
/** Upper bound. Default Infinity. */
max?: number;
/** Step for the buttons. Default 1. */
step?: number;
/** Decimal places kept and displayed. Default: the step's decimals. */
precision?: number;
/** Text before the number (`$`, `€`). */
prefix?: string;
/** Unit after the number (`kg`, `min`, `servings`). */
unit?: string;
/** Group thousands with commas (`1,250`). Default true. */
thousands?: boolean;
/** Label above the field. */
label?: string;
/** Helper text under the field — replaced by the range hint when a typed
* value was clamped. */
helper?: string;
/** Allow typing. Default true; false makes the value read-only text. */
editable?: boolean;
/** "field" bordered input (default) or "inline" pill for list rows. */
variant?: "field" | "inline";
/** sm 36 (rows) · md 48 · lg 56 (hero). Default md. */
size?: "sm" | "md" | "lg";
disabled?: boolean;
/** Stretch to the parent width. Default true for field, false for inline. */
fullWidth?: boolean;
/** Classes for the outer wrapper. */
className?: string;
}
export const NumberInput = forwardRef<React.ElementRef<typeof TextInput>, NumberInputProps>(function NumberInput(
{
value,
defaultValue,
onValueChange,
onStep,
min = -Infinity,
max = Infinity,
step = 1,
precision,
prefix,
unit,
thousands = true,
label,
helper,
editable = true,
variant = "field",
size = "md",
disabled,
fullWidth,
className,
onFocus,
onBlur,
accessibilityLabel,
...props
},
ref
) {
const haptics = useHaptic();
const reduceMotion = useReducedMotion();
const { colors } = useTheme();
const decimals = precision ?? (String(step).split(".")[1]?.length ?? 0);
const clamp = React.useCallback((n: number) => round(Math.min(max, Math.max(min, n)), decimals), [min, max, decimals]);
const [internal, setInternal] = useState(() => clamp(defaultValue ?? (Number.isFinite(min) ? min : 0)));
const current = value ?? internal;
const currentRef = React.useRef(current);
currentRef.current = current;
const [draft, setDraft] = useState<string | null>(null);
const [clampNote, setClampNote] = useState<string | null>(null);
// Swap in place: the incoming figure ignites (inT) and settles (rise); the
// outgoing copy dims (outT). swapDir is +1 counting up, −1 counting down.
const inT = useSharedValue(1);
const rise = useSharedValue(1);
const outT = useSharedValue(1);
const swapDir = useSharedValue(1);
const [outgoing, setOutgoing] = useState<string | null>(null);
const shake = useSharedValue(0);
const flicker = useSharedValue(1);
const focusT = useSharedValue(0);
const format = (n: number) => {
const fixed = n.toFixed(decimals);
if (!thousands) return fixed;
const [int, dec] = fixed.split(".");
const grouped = (int ?? "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return dec ? `${grouped}.${dec}` : grouped;
};
const commit = React.useCallback(
(next: number) => {
if (next === currentRef.current) return false;
currentRef.current = next;
if (value === undefined) setInternal(next);
onValueChange?.(next);
return true;
},
[value, onValueChange]
);
const stepBy = (dir: 1 | -1) => (repeating = false) => {
const prev = currentRef.current;
const next = clamp(prev + dir * step);
const moved = commit(next);
if (moved) {
setClampNote(null);
setDraft(null);
setOutgoing(format(prev));
swapDir.value = dir;
outT.value = 0;
outT.value = withTiming(1, { ...timing.recede, easing: Easing.bezier(...ease.in) });
inT.value = 0;
inT.value = withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) });
if (reduceMotion) rise.value = 1;
else {
rise.value = 0;
rise.value = withSpring(1, spring.swap);
}
onStep?.(next, { direction: dir, repeating });
}
return moved;
};
const commitDraft = () => {
if (draft === null) return;
const parsed = Number(draft.replace(/[^0-9.-]/g, ""));
setDraft(null);
if (!draft.trim() || Number.isNaN(parsed)) return;
const next = clamp(parsed);
if (next !== round(parsed, decimals)) {
haptics.warning();
setClampNote(
Number.isFinite(min) && Number.isFinite(max)
? `Between ${prefix ?? ""}${format(min)} and ${prefix ?? ""}${format(max)}${unit ? ` ${unit}` : ""}`
: next === max
? `Up to ${prefix ?? ""}${format(max)}${unit ? ` ${unit}` : ""}`
: `At least ${prefix ?? ""}${format(min)}${unit ? ` ${unit}` : ""}`
);
flicker.value = withSequence(withTiming(FLICKER_DIM, timing.instant), withTiming(1, timing.fast));
if (!reduceMotion) {
shake.value = -KICK;
shake.value = withSpring(0, spring.shake);
}
} else setClampNote(null);
commit(next);
};
const fieldStyle = useAnimatedStyle(() => ({
opacity: flicker.value * (disabled ? 0.5 : 1),
transform: [{ translateX: shake.value }],
borderColor:
variant === "inline"
? "transparent"
: clampNote
? colors.warning
: interpolateColor(focusT.value, [0, 1], [colors.input, colors.ring]),
}));
const incomingStyle = useAnimatedStyle(() => ({
opacity: inT.value,
transform: [{ translateY: (1 - rise.value) * SWAP_TRAVEL * swapDir.value }],
}));
// Dim to leave: the exit drifts half as far as the entrance, the way the count goes.
const outgoingStyle = useAnimatedStyle(() => ({
opacity: 1 - outT.value,
transform: reduceMotion ? [] : [{ translateY: -outT.value * (SWAP_TRAVEL / 2) * swapDir.value }],
}));
const handleA11y = (e: { nativeEvent: { actionName: string } }) => {
const moved = stepBy(e.nativeEvent.actionName === "increment" ? 1 : -1)();
if (moved) haptics.selection();
};
const wide = fullWidth ?? variant === "field";
const display = draft ?? format(current);
const textSize = valueTextVariants({ size });
const affix = cn(
"text-muted-foreground",
size === "lg" ? "text-lg font-medium" : size === "sm" ? "text-[15px]" : "text-base"
);
return (
<View className={cn(wide ? "w-full" : "self-start", "gap-1.5", className)}>
{label ? <Text className="text-sm font-medium text-foreground">{label}</Text> : null}
<Animated.View
style={fieldStyle}
className={cn(fieldVariants({ variant, size }), wide && "w-full")}
accessible
accessibilityRole="adjustable"
accessibilityLabel={accessibilityLabel ?? label}
accessibilityValue={{ min: Number.isFinite(min) ? min : undefined, max: Number.isFinite(max) ? max : undefined, now: current, text: `${prefix ?? ""}${format(current)}${unit ? ` ${unit}` : ""}` }}
accessibilityActions={[{ name: "increment" }, { name: "decrement" }]}
onAccessibilityAction={handleA11y}
>
<StepButton
icon="minus"
label="Decrease"
size={size}
atBound={current <= min}
dir={-1}
disabled={disabled}
onStep={stepBy(-1)}
/>
<View
className={cn("flex-row items-center justify-center gap-1", wide ? "flex-1" : size === "sm" ? "min-w-[56px] px-1" : "min-w-[88px] px-2")}
>
{prefix ? <Text className={affix}>{prefix}</Text> : null}
<View>
{outgoing !== null ? (
<Animated.View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className="absolute inset-0 items-center justify-center"
style={outgoingStyle}
>
<Text numberOfLines={1} className={textSize}>
{outgoing}
</Text>
</Animated.View>
) : null}
<Animated.View style={incomingStyle}>
{editable && !disabled ? (
<AnimatedTextInput
ref={ref}
value={display}
onChangeText={setDraft}
onFocus={(e) => {
focusT.value = reduceMotion ? 1 : withTiming(1, timing.fast);
setDraft(String(current));
onFocus?.(e);
}}
onBlur={(e) => {
focusT.value = reduceMotion ? 0 : withTiming(0, timing.fast);
commitDraft();
onBlur?.(e);
}}
onSubmitEditing={commitDraft}
keyboardType={decimals > 0 ? "decimal-pad" : "number-pad"}
returnKeyType="done"
selectTextOnFocus
className={cn(textSize, "min-w-[24px] p-0")}
style={{ width: Math.max(24, display.length * DIGIT_WIDTH[size] + 4) }}
accessibilityLabel={accessibilityLabel ?? label ?? "Value"}
{...props}
/>
) : (
<Text className={textSize}>{format(current)}</Text>
)}
</Animated.View>
</View>
{unit ? <Text className={affix}>{unit}</Text> : null}
</View>
<StepButton
icon="plus"
label="Increase"
size={size}
atBound={current >= max}
dir={1}
disabled={disabled}
onStep={stepBy(1)}
/>
</Animated.View>
{clampNote || helper ? (
<Text className={cn("text-sm", clampNote ? "text-foreground" : "text-muted-foreground")} accessibilityLiveRegion="polite">
{clampNote ?? helper}
</Text>
) : null}
</View>
);
});
NumberInput.displayName = "NumberInput"; import { NumberInput } from "@/components/ui/number-input/number-input";
export function Example() {
return (
<NumberInput />
);
} Installation
Install the dependencies
npx expo install react-native-reanimatedAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/number-input/number-input.tsxcomponents/ui/number-input/index.tsIcons it renders
Update the import paths to match your project setup.
Usage
import { NumberInput } from "@/components/ui/number-input/number-input"; <NumberInput /> Examples
A card's monthly spending limit in a banking app.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { NumberInput } from "../number-input";
import { Button } from "../../button/button";
import { Progress } from "../../progress/progress";
import { Text } from "../../text/text";
const SPENT = 1240;
/** NumberInputLimit — a card's monthly spending limit in a banking app.
* $50 steps from $250 to $10,000; type 20000 and the field shakes back
* to the cap with the allowed range spelled out. The bar shows how much
* of the new limit this month has used. Green, for money. */
export function NumberInputLimit() {
const [limit, setLimit] = React.useState(2000);
const used = Math.min(100, (SPENT / limit) * 100);
return (
<Accent color="green" className="w-full">
<View className="w-full gap-6">
<View className="gap-1 px-1">
<Text className="text-2xl font-bold tracking-tight">Monthly limit</Text>
<Text variant="muted">Debit card ending 7314</Text>
</View>
<NumberInput
value={limit}
onValueChange={setLimit}
min={250}
max={10000}
step={50}
prefix="$"
size="lg"
accessibilityLabel="Monthly spending limit"
helper="Card payments and ATM withdrawals count toward this."
/>
<View className="gap-2 rounded-2xl bg-card p-4">
<View className="flex-row justify-between">
<Text className="text-[15px] font-medium">Spent in November</Text>
<Text className="text-[15px] font-semibold tabular-nums">{`$${SPENT.toLocaleString("en-US")}`}</Text>
</View>
<Progress value={used} className="h-1.5" />
<Text variant="muted">
{SPENT >= limit
? "New payments will be declined until 1 December."
: `$${(limit - SPENT).toLocaleString("en-US")} left until 1 December`}
</Text>
</View>
<Button size="lg" className="w-full">
Save limit
</Button>
</View>
</Accent>
);
} A recipe app scaling shakshuka.
import * as React from "react";
import { View } from "react-native";
import Animated, { Easing, useAnimatedStyle, useSharedValue, withDelay, withSpring, withTiming } from "react-native-reanimated";
import { Accent, ROW_STAGGER, ease, spring, timing, useReducedMotion } from "@lumioui/core";
import { NumberInput } from "../number-input";
import { Text } from "../../text/text";
const BASE_SERVINGS = 4;
const INGREDIENTS: { name: string; qty: number; unit: string; step?: number }[] = [
{ name: "Ripe tomatoes", qty: 800, unit: "g" },
{ name: "Eggs", qty: 6, unit: "", step: 1 },
{ name: "Red pepper", qty: 2, unit: "", step: 0.5 },
{ name: "Feta", qty: 150, unit: "g" },
{ name: "Ground cumin", qty: 2, unit: "tsp", step: 0.25 },
{ name: "Olive oil", qty: 3, unit: "tbsp", step: 0.5 },
];
function scaled(qty: number, servings: number, step = 10) {
const v = Math.round(((qty * servings) / BASE_SERVINGS) / step) * step;
return Number.isInteger(v) ? String(v) : v.toFixed(2).replace(/0$/, "");
}
/** While a held + is auto-stepping the cascade tightens so it keeps up. */
const HELD_STAGGER = 24;
/** A quantity's swap travel (pt) — the same as the stepper's figure. */
const TRAVEL = 4;
/** One quantity that swaps in place when it changes, on its turn in the
* cascade: the old figure dims while the new one ignites and settles in the
* direction of the change. */
function Qty({ text, delay, dir }: { text: string; delay: number; dir: 1 | -1 }) {
const reduce = useReducedMotion();
const [shown, setShown] = React.useState({ text, prev: text });
if (shown.text !== text) setShown({ text, prev: shown.text });
const inT = useSharedValue(1);
const rise = useSharedValue(1);
const outT = useSharedValue(1);
React.useEffect(() => {
if (shown.prev === shown.text) return;
outT.value = 0;
outT.value = withDelay(delay, withTiming(1, { ...timing.recede, easing: Easing.bezier(...ease.in) }));
inT.value = 0;
inT.value = withDelay(delay, withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) }));
if (reduce) rise.value = 1;
else {
rise.value = 0;
rise.value = withDelay(delay, withSpring(1, spring.swap));
}
}, [shown, delay, reduce, inT, rise, outT]);
const inStyle = useAnimatedStyle(() => ({
opacity: inT.value,
transform: [{ translateY: (1 - rise.value) * TRAVEL * dir }],
}));
const outStyle = useAnimatedStyle(() => ({
opacity: 1 - outT.value,
transform: reduce ? [] : [{ translateY: -outT.value * (TRAVEL / 2) * dir }],
}));
return (
<View>
<Animated.View
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
className="absolute inset-y-0 right-0 justify-center"
style={outStyle}
>
<Text numberOfLines={1} className="text-base font-medium tabular-nums">
{shown.prev}
</Text>
</Animated.View>
<Animated.View style={inStyle}>
<Text className="text-base font-medium tabular-nums">{text}</Text>
</Animated.View>
</View>
);
}
/** NumberInputRecipe — a recipe app scaling shakshuka. Step servings (or
* type a number, clamped to 1–12) and the change runs down the list from
* the stepper: each ingredient quantity swaps in place 40ms after the one
* above it, rising as servings go up and falling as they go down. Holding
* + tightens the cascade to 24ms so it keeps pace. Orange. */
export function NumberInputRecipe() {
const [servings, setServings] = React.useState(BASE_SERVINGS);
const [run, setRun] = React.useState<{ dir: 1 | -1; held: boolean }>({ dir: 1, held: false });
return (
<Accent color="orange" className="w-full">
<View className="w-full gap-6">
<View className="gap-1 px-1">
<Text className="text-2xl font-bold tracking-tight">Shakshuka with feta</Text>
<Text variant="muted">35 min · One pan · Vegetarian</Text>
</View>
<NumberInput
label="Servings"
value={servings}
onValueChange={(n) => {
// Typed commits carry their direction here; steps refine it in onStep.
setRun((r) => ({ dir: n >= servings ? 1 : -1, held: r.held }));
setServings(n);
}}
onStep={(_, { direction, repeating }) => setRun({ dir: direction, held: repeating })}
min={1}
max={12}
unit={servings === 1 ? "serving" : "servings"}
size="lg"
/>
<View className="overflow-hidden rounded-2xl bg-card">
{INGREDIENTS.map((ing, i) => (
<View key={ing.name}>
{i > 0 ? <View className="ml-4 h-px bg-border" /> : null}
<View className="min-h-[48px] flex-row items-center px-4 py-2">
<Text className="flex-1 text-base">{ing.name}</Text>
<Qty
text={`${scaled(ing.qty, servings, ing.step)}${ing.unit ? ` ${ing.unit}` : ""}`}
delay={i * (run.held ? HELD_STAGGER : ROW_STAGGER)}
dir={run.dir}
/>
</View>
</View>
))}
</View>
</View>
</Accent>
);
} A strength log for back squats.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { NumberInput } from "../number-input";
import { Text } from "../../text/text";
interface SetRow {
kg: number;
reps: number;
}
/** NumberInputWorkout — a strength log for back squats. Each set row has
* two inline pill inputs (kg in 2.5 steps, reps in 1s); hold + to load
* plates fast. Volume for the session follows every change. Red. */
export function NumberInputWorkout() {
const [sets, setSets] = React.useState<SetRow[]>([
{ kg: 80, reps: 8 },
{ kg: 85, reps: 6 },
{ kg: 87.5, reps: 5 },
]);
const update = (i: number, patch: Partial<SetRow>) =>
setSets((cur) => cur.map((s, j) => (j === i ? { ...s, ...patch } : s)));
const volume = sets.reduce((sum, s) => sum + s.kg * s.reps, 0);
return (
<Accent color="red" className="w-full">
<View className="w-full gap-5">
<View className="flex-row items-end justify-between px-1">
<View className="gap-1">
<Text className="text-2xl font-bold tracking-tight">Back squat</Text>
<Text variant="muted">Last time: 85 kg × 6</Text>
</View>
<View className="items-end">
<Text className="text-2xl font-semibold tabular-nums">{volume.toLocaleString("en-GB")}</Text>
<Text variant="muted">kg volume</Text>
</View>
</View>
<View className="overflow-hidden rounded-2xl bg-card">
<View className="flex-row items-center px-4 pb-1 pt-3">
<Text className="w-10 text-[13px] text-muted-foreground">Set</Text>
<Text className="flex-1 text-center text-[13px] text-muted-foreground">Weight</Text>
<Text className="w-[120px] text-center text-[13px] text-muted-foreground">Reps</Text>
</View>
{sets.map((s, i) => (
<View key={i}>
{i > 0 ? <View className="ml-14 h-px bg-border" /> : null}
<View className="min-h-[56px] flex-row items-center gap-2 px-4 py-2">
<Text className="w-8 text-base font-semibold tabular-nums">{i + 1}</Text>
<View className="flex-1 items-center">
<NumberInput
variant="inline"
size="sm"
value={s.kg}
onValueChange={(kg) => update(i, { kg })}
min={20}
max={300}
step={2.5}
precision={1}
unit="kg"
accessibilityLabel={`Set ${i + 1} weight`}
/>
</View>
<NumberInput
variant="inline"
size="sm"
value={s.reps}
onValueChange={(reps) => update(i, { reps })}
min={1}
max={30}
accessibilityLabel={`Set ${i + 1} reps`}
/>
</View>
</View>
))}
</View>
</View>
</Accent>
);
} API reference
repeating* boolean }) => void — value number Controlled value.
—defaultValue number Uncontrolled initial value. Default min if finite, else 0.
onValueChange (value: number) => void Fires on every committed change (step, hold tick, typed commit).
—onStep (value: number, info: { direction: 1 | -1 Fires on each button / a11y step with its direction, and repeating while a held button is auto-stepping — e.g. to tighten a cascade.
min number Lower bound. Default -Infinity.
-Infinity max number Upper bound. Default Infinity.
Infinity step number Step for the buttons. Default 1.
1 precision number Decimal places kept and displayed. Default: the step's decimals.
—prefix string Text before the number ($, €).
unit string Unit after the number (kg, min, servings).
thousands boolean Group thousands with commas (1,250). Default true.
true label string Label above the field.
—helper string Helper text under the field — replaced by the range hint when a typed value was clamped.
—editable boolean Allow typing. Default true; false makes the value read-only text.
true variant "field" | "inline" "field" bordered input (default) or "inline" pill for list rows.
"field" size "sm" | "md" | "lg" sm 36 (rows) · md 48 · lg 56 (hero). Default md.
"md" disabled boolean — fullWidth boolean Stretch to the parent width. Default true for field, false for inline.
—className string Classes for the outer wrapper.
—