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.
Toast
Toast notifications that grow out of the screen edge and stack neatly. A loading toast can turn into a success in place, and you can swipe one away or let it fade.
Preview
import * as React from "react";
import { createContext, useContext, useCallback, useRef, useMemo, useState, useEffect } from "react";
import { View, Text, Pressable, PanResponder, StyleSheet, type ViewProps } from "react-native";
import Animated, {
useSharedValue,
useAnimatedStyle,
withSpring,
withTiming,
withDelay,
interpolate,
runOnJS,
Easing,
withRepeat,
withSequence,
useAnimatedProps,
} from "react-native-reanimated";
import Svg from "react-native-svg";
import {
AnimatedPath,
Sheen,
cn,
useHaptic,
useTheme,
spring,
tempo,
timing,
ease,
useReducedMotion,
usePressAnimation,
} from "@lumioui/core";
import { Icon, type IconName } from "../icon";
import { Glass } from "../glass";
import { useSafeAreaInsets } from "react-native-safe-area-context";
/**
* Toast — born at the edge. A 1px lit line brightens at the stack's screen
* edge (timing.instant), the card grows out of it (scaleY 0.92→1 with a 16px
* rise on spring.surface) and its face switches on 100ms after the
* container. Statuses swap in place; loading → success stops the rotor, draws
* the check (240ms, ease.out) and sends one sheen across the card. Collapsed
* stack with slot reordering, swipe-to-dismiss that flings with the finger,
* auto-dismiss that dims in place, and configurable position.
* <ToastProvider position="top">
* {children}
* </ToastProvider>
* const { show, success, error, warning } = useToast();
* show("Saved", { description: "Your changes are live", variant: "success" });
*/
type ToastVariant = "default" | "success" | "error" | "warning" | "info" | "loading";
type ToastPosition = "top" | "bottom";
interface ToastData {
id: number;
title: string;
description?: string;
variant: ToastVariant;
duration: number;
dismissible: boolean;
action?: ToastAction;
/** Set by the provider to start the exit animation; removed from state once it finishes. */
leaving?: boolean;
/** Stack depth captured when the exit started — drives the dismissAll stagger. */
exitIndex?: number;
}
interface ToastAction {
label: string;
onPress: () => void;
/** Dismiss the toast after the action runs. Default true — set false for
* actions like Retry that swap the same toast in place. */
dismiss?: boolean;
}
interface ToastApi {
show: (
title: string,
opts?: {
description?: string;
variant?: ToastVariant;
duration?: number;
dismissible?: boolean;
action?: ToastAction;
}
) => number;
success: (title: string, description?: string) => number;
error: (title: string, description?: string) => number;
warning: (title: string, description?: string) => number;
info: (title: string, description?: string) => number;
loading: (title: string, description?: string) => number;
dismiss: (id: number) => void;
dismissAll: () => void;
update: (id: number, patch: Partial<Omit<ToastData, "id">>) => void;
}
const Ctx = createContext<ToastApi | null>(null);
/** Imperative toast API — call `useToast()` anywhere inside <ToastProvider>. */
export function useToast(): ToastApi {
const ctx = useContext(Ctx);
if (!ctx) throw new Error("useToast must be inside <ToastProvider>");
return ctx;
}
const variantIconBg: Record<ToastVariant, string> = {
default: "bg-muted",
success: "bg-success/15",
error: "bg-destructive/15",
warning: "bg-warning/15",
info: "bg-primary/15",
loading: "bg-primary/15",
};
const variantIconColor: Record<ToastVariant, string> = {
default: "mutedForeground",
// Foreground tokens are near-white on light scheme — invisible on the /15
// tinted icon wells. Use the saturated variant color instead.
success: "success",
error: "destructive",
warning: "warning",
info: "primary",
loading: "primary",
};
const variantIcon: Record<ToastVariant, IconName> = {
default: "bell",
success: "check",
error: "x",
warning: "alert-triangle",
info: "info",
loading: "loader",
};
const variantHaptic: Record<ToastVariant, "selection" | "success" | "error" | "warning" | "light"> = {
default: "selection",
success: "success",
error: "error",
warning: "warning",
info: "light",
loading: "light",
};
/** Horizontal swipe distance that dismisses (72px). */
const DISMISS_DX = 72;
const DISMISS_DY = 40;
/** Fling-to-dismiss velocity — 520px/s expressed in PanResponder's px/ms. */
const DISMISS_VX = 0.52;
/** Collapsed stack: each older toast peeks this far past the card in front. */
const STACK_GAP = 10;
/** Collapsed stack: scale shrink per level of depth. */
const STACK_SCALE_STEP = 0.04;
/** Collapsed stack: older cards dim a step per level so the front one leads. */
const STACK_DIM_STEP = 0.18;
/** Per-depth delay so a dismissAll collapse dims front-to-back. */
const EXIT_STAGGER_MS = 40;
const EASE_OUT = Easing.bezier(...ease.out);
/** Entrance: rises 16px at 0.97 on spring.surface while igniting. */
const ENTER_RISE = 16;
const ENTER_SCALE = 0.97;
const IGNITE = { duration: timing.fast.duration, easing: EASE_OUT };
/** Auto / tap dismiss: the card dims in place over 160ms. */
const DIM = { duration: tempo.flick, easing: Easing.bezier(...ease.in) };
/** Swipe dismiss: the card keeps going the way it was flung. */
const FLING = { duration: tempo.flick, easing: EASE_OUT };
const FLING_DISTANCE = 400;
/** Content swap: outgoing dims to 0.96, incoming ignites 0.96→1. */
const SWAP_SCALE = 0.96;
const SWAP_DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
/** Born at the edge: the card starts this flat against its lit line. */
const ENTER_SCALE_Y = 0.92;
/** The face switches on after the container (§5c rule 2). */
const FACE_AFTER = 100;
/** The check draws at the mark-drawing pace shared with Checkbox (240ms). */
const CHECK_DRAW = { duration: timing.recede.duration * 2, easing: EASE_OUT };
const CHECK_PATH = "M5 12.5l4.5 4.5L19 7.5";
const CHECK_LEN = 22;
/** Loading rotor — one lap every 1.1s, linear. */
const SPIN_CYCLE = { duration: 1100, easing: Easing.linear };
/** The success mark draws itself in rather than appearing. */
function DrawnCheck({ color }: { color: string }) {
const reduce = useReducedMotion();
const draw = useSharedValue(reduce ? 1 : 0);
useEffect(() => {
if (!reduce) draw.value = withTiming(1, CHECK_DRAW);
}, [reduce, draw]);
const props = useAnimatedProps(() => ({ strokeDashoffset: CHECK_LEN * (1 - draw.value) }));
return (
<Svg width={16} height={16} viewBox="0 0 24 24">
<AnimatedPath
d={CHECK_PATH}
stroke={color}
strokeWidth={2.6}
strokeLinecap="round"
strokeLinejoin="round"
fill="none"
strokeDasharray={`${CHECK_LEN} ${CHECK_LEN}`}
animatedProps={props}
/>
</Svg>
);
}
/** Animated.View as registered with NativeWind cssInterop in core/styled.ts. */
const AnimatedView = Animated.View as React.ComponentType<ViewProps & { className?: string }>;
/** Depth map over active (non-leaving) toasts — newest is depth 0. Leaving
* toasts are skipped so siblings can reorder while the exit plays. */
function depthOrder(list: ToastData[]) {
const map = new Map<number, number>();
let d = 0;
for (let i = list.length - 1; i >= 0; i--) {
const t = list[i]!;
if (!t.leaving) map.set(t.id, d++);
}
return map;
}
/** The face currently rendered inside the card — staged so variant/title
* changes can crossfade in place instead of remounting. */
interface ShownContent {
variant: ToastVariant;
title: string;
description?: string;
}
interface ToastItemProps {
toast: ToastData;
position: ToastPosition;
/** Index from the front of the stack — 0 is the newest, fully visible card. */
depth: number;
/** Stack levels that stay visible; deeper toasts fade out behind the pile. */
maxVisible: number;
/** Card material — "solid" card (default) or liquid "glass". */
surface: "solid" | "glass";
onRequestDismiss: (id: number) => void;
onDone: (id: number) => void;
}
function ToastItem({ toast, position, depth, maxVisible, surface, onRequestDismiss, onDone }: ToastItemProps) {
const haptics = useHaptic();
const reduce = useReducedMotion();
const { colors } = useTheme();
// Slot transform — where this toast sits in the collapsed stack. Driven
// per depth so removing a sibling settles everyone into their new slot.
const stackY = useSharedValue(0);
const stackScale = useSharedValue(1);
const stackOpacity = useSharedValue(1);
// Entrance + drag layers compose on top of the slot transform.
// The toast rises 16px from its edge at 0.97 scale.
const enterY = useSharedValue(reduce ? 0 : position === "top" ? -ENTER_RISE : ENTER_RISE);
const enterScale = useSharedValue(reduce ? 1 : ENTER_SCALE);
const enterScaleY = useSharedValue(reduce ? 1 : ENTER_SCALE_Y);
const opacity = useSharedValue(0);
/** The lit line at the stack's edge the card is born from. */
const edge = useSharedValue(0);
/** The face switches on after the container. */
const faceOn = useSharedValue(0);
const [sheen, setSheen] = useState(0);
const dragX = useSharedValue(0);
const dragY = useSharedValue(0);
const spin = useSharedValue(0);
const morphIn = useSharedValue(1);
const morphInScale = useSharedValue(1);
const morphOut = useSharedValue(0);
const exited = useRef(false);
// Press scale feedback for the action + dismiss buttons.
const actionPress = usePressAnimation({ pressedScale: 0.92 });
const dismissPress = usePressAnimation({ pressedScale: 0.92 });
const signature = `${toast.variant}|${toast.title}|${toast.description ?? ""}`;
const [shown, setShown] = useState<ShownContent>({
variant: toast.variant,
title: toast.title,
description: toast.description,
});
const [outgoing, setOutgoing] = useState<ShownContent | null>(null);
// Only the front card is touchable — stacked slivers behind it don't
// steal gestures, and a leaving toast ignores input while it exits.
const interactive = !toast.leaving && depth === 0;
// Status swap in place (icon + content). The previous face renders in an
// overlay that dims out while the new face ignites — the card surface
// itself never remounts.
useEffect(() => {
if (shown.variant === toast.variant && shown.title === toast.title && shown.description === toast.description) return;
const next: ShownContent = { variant: toast.variant, title: toast.title, description: toast.description };
if (reduce) {
setShown(next);
setOutgoing(null);
morphIn.value = 1;
return;
}
setOutgoing(shown);
setShown(next);
// Resolve: a loading face that lands on success is the commit — one sheen.
if (shown.variant === "loading" && next.variant === "success") setSheen((n) => n + 1);
morphIn.value = 0;
morphIn.value = withTiming(1, IGNITE);
morphInScale.value = SWAP_SCALE;
morphInScale.value = withSpring(1, spring.swap);
morphOut.value = 1;
morphOut.value = withTiming(0, SWAP_DIM, (finished) => {
if (finished) runOnJS(setOutgoing)(null);
});
// `shown` is read for the outgoing copy — `signature` is the real trigger.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [signature, reduce]);
// Entrance — mount only. The variant haptic lives in the provider's
// show() so toast.update() can't refire it.
useEffect(() => {
if (reduce) {
enterY.value = 0;
enterScale.value = 1;
enterScaleY.value = 1;
opacity.value = withTiming(1, IGNITE);
faceOn.value = withDelay(FACE_AFTER, withTiming(1, IGNITE));
} else {
// Light first: the edge line brightens, then the card grows out of it
// on spring.surface while the line hands its light to the card.
const born = timing.instant.duration;
edge.value = withSequence(withTiming(1, timing.instant), withTiming(0, timing.fast));
enterY.value = withDelay(born, withSpring(0, spring.surface));
enterScale.value = withDelay(born, withSpring(1, spring.surface));
enterScaleY.value = withDelay(born, withSpring(1, spring.surface));
opacity.value = withDelay(born, withTiming(1, IGNITE));
faceOn.value = withDelay(born + FACE_AFTER, withTiming(1, IGNITE));
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Auto-dismiss timer — re-keys on duration so update() can extend/reset it.
useEffect(() => {
if (toast.leaving || toast.duration <= 0) return;
const t = setTimeout(() => onRequestDismiss(toast.id), toast.duration);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [toast.duration, toast.leaving]);
// Exit — the provider flags `leaving`, the item plays its exit, then
// reports back so the provider unmounts it. A swiped card keeps going the
// way it was flung; every other dismissal dims in place. Slight per-depth
// stagger makes a dismissAll collapse run front-to-back.
useEffect(() => {
if (!toast.leaving || exited.current) return;
exited.current = true;
const delay = reduce ? 0 : (toast.exitIndex ?? depth) * EXIT_STAGGER_MS;
// dragX/dragY still hold the release position after a swipe.
if (!reduce && dragX.value !== 0) {
dragX.value = withTiming(Math.sign(dragX.value) * FLING_DISTANCE, FLING);
} else if (!reduce && dragY.value !== 0) {
dragY.value = withTiming(Math.sign(dragY.value) * FLING_DISTANCE, FLING);
}
opacity.value = withDelay(
delay,
withTiming(0, DIM, (finished) => {
if (finished) runOnJS(onDone)(toast.id);
})
);
// Fallback unmount if the worklet completion callback is dropped.
const t = setTimeout(() => onDone(toast.id), delay + DIM.duration + 60);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [toast.leaving]);
// Loading rotor — keyed on the shown face so a loading→success swap stops
// the spin with the swap, not before.
useEffect(() => {
if (shown.variant === "loading" && !reduce) {
spin.value = 0;
spin.value = withRepeat(withTiming(360, SPIN_CYCLE), -1, false);
}
return () => { spin.value = 0; };
}, [shown.variant, reduce, spin]);
const spinStyle = useAnimatedStyle(() => ({
transform: [{ rotate: `${spin.value}deg` }],
}));
// Slot choreography — every toast springs to its slot, so removing one
// makes the rest settle into place. Leaving toasts freeze at their last
// slot while the exit plays so siblings can settle in behind them.
useEffect(() => {
if (toast.leaving) return;
if (reduce) {
// Reduced motion: collapse becomes opacity-only — no lift or scale.
stackY.value = 0;
stackScale.value = 1;
stackOpacity.value = depth >= maxVisible ? 0 : 1;
return;
}
const dir = position === "top" ? 1 : -1;
// Restacking is a layout change — spring.layout settles cards into
// their slots without bouncing past them.
stackY.value = withSpring(dir * depth * STACK_GAP, spring.layout);
stackScale.value = withSpring(Math.max(1 - depth * STACK_SCALE_STEP, 0), spring.layout);
stackOpacity.value = withTiming(depth >= maxVisible ? 0 : 1 - depth * STACK_DIM_STEP, timing.fast);
}, [depth, position, maxVisible, reduce, toast.leaving, stackY, stackScale, stackOpacity]);
function requestDismissWithHaptic() {
haptics.light();
onRequestDismiss(toast.id);
}
// Swipe-to-dismiss via PanResponder — free components stay Expo Go
// compatible, so no react-native-gesture-handler here. Capture on move
// lets the pan steal the responder from the inner Pressable only once
// the gesture is clearly a swipe, so taps still dismiss normally.
const panResponder = useMemo(() => {
if (reduce || !interactive || !toast.dismissible) return null;
return PanResponder.create({
onMoveShouldSetPanResponderCapture: (_e, g) =>
Math.abs(g.dx) > 8 || (position === "top" ? g.dy < -8 : g.dy > 8),
onPanResponderMove: (_e, g) => {
dragX.value = g.dx;
dragY.value = position === "top" ? Math.min(g.dy, 0) : Math.max(g.dy, 0);
},
onPanResponderRelease: (_e, g) => {
if (
Math.abs(g.dx) > DISMISS_DX ||
Math.abs(g.vx) > DISMISS_VX ||
(position === "top" ? -g.dy > DISMISS_DY : g.dy > DISMISS_DY)
) {
requestDismissWithHaptic();
} else {
// Carry the release fling into the snap-back (vx is px/ms,
// Reanimated velocity is px/s) so a fast abort whips home.
const v = g.vx * 1000;
dragX.value = withSpring(0, { ...spring.layout, velocity: v });
dragY.value = withSpring(0, { ...spring.layout, velocity: g.vy * 1000 });
}
},
onPanResponderTerminate: () => {
dragX.value = withSpring(0, spring.layout);
dragY.value = withSpring(0, spring.layout);
},
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reduce, interactive, toast.dismissible, position, dragX, dragY]);
const style = useAnimatedStyle(() => ({
transform: [
{ translateX: dragX.value },
{ translateY: stackY.value + enterY.value + dragY.value },
{ scale: stackScale.value * enterScale.value },
{ scaleY: enterScaleY.value },
// Slight tilt while swiping sideways — the card feels held, not on rails.
{ rotate: `${interpolate(dragX.value, [-160, 0, 160], [-2.5, 0, 2.5], "clamp")}deg` },
],
// The card's own light rides cardStyle so the edge line can shine first.
opacity: stackOpacity.value,
}));
const cardStyle = useAnimatedStyle(() => ({ opacity: opacity.value }));
// The edge line brightens in place, not a rule — half-bright at its peak.
const edgeStyle = useAnimatedStyle(() => ({ opacity: edge.value * 0.5 }));
const morphInStyle = useAnimatedStyle(() => ({
opacity: morphIn.value * faceOn.value,
transform: [{ scale: morphInScale.value }],
}));
const morphOutStyle = useAnimatedStyle(() => ({
opacity: morphOut.value,
transform: [{ scale: SWAP_SCALE + (1 - SWAP_SCALE) * morphOut.value }],
}));
// The card face — icon + text rendered from a `ShownContent` snapshot so
// the outgoing copy can crossfade under the incoming one.
const renderFace = (face: ShownContent) => (
<View className="flex-1 flex-row items-start gap-3">
{/* Status icon */}
<View className={cn("h-8 w-8 shrink-0 items-center justify-center rounded-full", variantIconBg[face.variant])}>
<Animated.View style={face.variant === "loading" ? spinStyle : undefined}>
{face.variant === "success" ? (
<DrawnCheck color={colors.success} />
) : (
<Icon name={variantIcon[face.variant]} size="sm" color={variantIconColor[face.variant]} />
)}
</Animated.View>
</View>
{/* Content */}
<View className="flex-1">
<Text className="text-[15px] font-semibold text-card-foreground" numberOfLines={1}>
{face.title}
</Text>
{face.description ? (
<Text className="mt-0.5 text-sm leading-snug text-muted-foreground" numberOfLines={2}>
{face.description}
</Text>
) : null}
{toast.action ? (
<Animated.View style={actionPress.animatedStyle}>
<Pressable
onPressIn={actionPress.onPressIn}
onPressOut={actionPress.onPressOut}
onPress={() => {
toast.action?.onPress();
if (toast.action?.dismiss === false) haptics.light();
else requestDismissWithHaptic();
}}
className="mt-2 h-8 flex-row items-center self-start rounded-full bg-secondary px-3"
hitSlop={8}
accessibilityRole="button"
accessibilityLabel={toast.action.label}
>
<Text className="text-sm font-semibold text-foreground">{toast.action.label}</Text>
</Pressable>
</Animated.View>
) : null}
</View>
</View>
);
// Status lives in the icon well; the card edge stays neutral. Solid is an
// opaque card that reads in both schemes; glass is opt-in for apps whose
// content behind the stack is photographic or moving.
// The sheen is clipped apart from the card so the card keeps its shadow.
const sheenLayer = (
<View pointerEvents="none" className="absolute inset-0 overflow-hidden rounded-2xl">
<Sheen run={sheen} color={colors.success} strength={0.22} />
</View>
);
const renderSurface = (inner: React.ReactNode) =>
surface === "glass" ? (
<Glass effect="regular" className="rounded-2xl shadow-lg">
{inner}
{sheenLayer}
</Glass>
) : (
<View className="rounded-2xl border border-border bg-card shadow-lg">
{inner}
{sheenLayer}
</View>
);
const toastContent = (
<Pressable
onPress={toast.dismissible ? requestDismissWithHaptic : undefined}
accessibilityRole="alert"
accessibilityLabel={`${shown.variant}: ${shown.title}${shown.description ? `. ${shown.description}` : ""}`}
>
{renderSurface(
<View className={cn("flex-row items-start gap-3 p-4")}>
{/* Swap zone — icon + text swap in place here when the status or
content changes; the action rides along, the dismiss button
stays put. */}
<View className="relative flex-1">
<AnimatedView style={morphInStyle}>{renderFace(shown)}</AnimatedView>
{outgoing ? (
<AnimatedView
pointerEvents="none"
style={[StyleSheet.absoluteFillObject, morphOutStyle]}
>
{renderFace(outgoing)}
</AnimatedView>
) : null}
</View>
{/* Dismiss button */}
{toast.dismissible ? (
<Animated.View style={dismissPress.animatedStyle}>
<Pressable
onPressIn={dismissPress.onPressIn}
onPressOut={dismissPress.onPressOut}
onPress={requestDismissWithHaptic}
hitSlop={8}
className="h-7 w-7 shrink-0 items-center justify-center rounded-full"
accessibilityRole="button"
accessibilityLabel="Dismiss toast"
>
<Icon name="x" size="sm" color="mutedForeground" />
</Pressable>
</Animated.View>
) : null}
</View>
)}
</Pressable>
);
return (
<AnimatedView
pointerEvents={interactive ? "auto" : "none"}
style={[
// Absolute slot anchored to the stack's screen edge — every toast
// lives at the same anchor and animates to its slot via stackY.
{
position: "absolute",
left: 0,
right: 0,
zIndex: 100 - depth,
},
position === "top" ? { top: 0, transformOrigin: "top" } : { bottom: 0, transformOrigin: "bottom" },
style,
]}
>
{/* The lit line the card is born from, on the stack's screen edge. */}
<AnimatedView
pointerEvents="none"
style={[
{ position: "absolute", left: 24, right: 24, height: 1, backgroundColor: colors.foreground },
position === "top" ? { top: 0 } : { bottom: 0 },
edgeStyle,
]}
/>
<AnimatedView style={cardStyle}>
{panResponder ? (
<View collapsable={false} {...panResponder.panHandlers}>
{toastContent}
</View>
) : (
toastContent
)}
</AnimatedView>
</AnimatedView>
);
}
export interface ToastProviderProps {
children: React.ReactNode;
/** Where toasts appear. Default "top". */
position?: ToastPosition;
/** Auto-dismiss duration in ms. 0 = manual dismiss only. Default 4000. */
defaultDuration?: number;
/** Max simultaneous toasts. Older ones are dismissed with an exit animation. Default 4. */
limit?: number;
/** Stack levels that peek out behind the front toast. Deeper toasts stay
* queued (timers running) until a slot frees. Default 3. */
maxVisible?: number;
/** Card material. "solid" (default) is an opaque card with a hairline
* and soft shadow that reads in both schemes; "glass" is the Lumio glass
* material for apps whose content behind is photographic / moving. */
surface?: "solid" | "glass";
}
/**
* Mount once at the app root. Toasts land on a collapsed stack — the newest
* card is full-size, older ones scale down, dim and peek past it. When one
* leaves (swipe, tap, timeout, limit overflow, dismissAll), the rest settle
* into their new slots.
*/
export const ToastProvider = React.forwardRef<View, ToastProviderProps>(function ToastProvider(
{ children, position = "top", defaultDuration = 4000, limit = 4, maxVisible = 3, surface = "solid" },
ref
) {
const [toasts, setToasts] = useState<ToastData[]>([]);
const idRef = useRef(0);
const insets = useSafeAreaInsets();
const haptics = useHaptic();
// Flag-based dismissal: mark `leaving` and let the item run its exit
// animation; `remove` is the callback that actually unmounts it.
const requestDismiss = useCallback((id: number) => {
setToasts((prev) => {
const order = depthOrder(prev);
return prev.map((t) =>
t.id === id && !t.leaving ? { ...t, leaving: true, exitIndex: order.get(id) ?? 0 } : t
);
});
}, []);
const remove = useCallback((id: number) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const dismissAll = useCallback(() => {
setToasts((prev) => {
const order = depthOrder(prev);
return prev.map((t) => (t.leaving ? t : { ...t, leaving: true, exitIndex: order.get(t.id) ?? 0 }));
});
}, []);
const update = useCallback((id: number, patch: Partial<Omit<ToastData, "id">>) => {
setToasts((prev) => prev.map((t) => (t.id === id ? { ...t, ...patch } : t)));
}, []);
const show = useCallback<ToastApi["show"]>(
(title, opts) => {
const id = ++idRef.current;
const variant = opts?.variant ?? "default";
// Mount haptic fires once at creation — updates swap in place quietly.
haptics[variantHaptic[variant]]();
setToasts((prev) => {
const next: ToastData[] = [
...prev,
{
id,
title,
description: opts?.description,
variant,
duration: opts?.duration ?? defaultDuration,
dismissible: opts?.dismissible ?? true,
action: opts?.action,
},
];
const active = next.filter((t) => !t.leaving);
if (active.length <= limit) return next;
// Over limit: instead of hard-dropping the oldest, flag them leaving
// so they dim out like any other dismissal.
const order = depthOrder(next);
const overflow = new Set(active.slice(0, active.length - limit).map((t) => t.id));
return next.map((t) =>
overflow.has(t.id) ? { ...t, leaving: true, exitIndex: order.get(t.id) ?? 0 } : t
);
});
return id;
},
[defaultDuration, limit, haptics]
);
const api = React.useMemo<ToastApi>(
() => ({
show,
success: (title, description) => show(title, { description, variant: "success" }),
error: (title, description) => show(title, { description, variant: "error" }),
warning: (title, description) => show(title, { description, variant: "warning" }),
info: (title, description) => show(title, { description, variant: "info" }),
loading: (title, description) => show(title, { description, variant: "loading", duration: 0, dismissible: false }),
dismiss: requestDismiss,
dismissAll,
update,
}),
[show, requestDismiss, dismissAll, update]
);
const depthById = depthOrder(toasts);
return (
<Ctx.Provider value={api}>
{children}
{/* Single live region for the whole stack — screen readers announce
arrivals/morphs once, not per-toast. Items are absolutely slotted
so reorder never reflows the container. */}
<View
ref={ref}
pointerEvents="box-none"
accessibilityRole="alert"
accessibilityLiveRegion="polite"
// max-w + mx-auto keeps the stack phone-width on wide canvases
// (docs stage, tablets) while staying edge-inset on phones.
className="absolute left-4 right-4 z-[9999] mx-auto max-w-[440px]"
// Only the edge offset is dynamic (safe-area aware) — the rest
// lives in className.
style={
position === "top"
? { top: insets.top + 8 }
: { bottom: insets.bottom + 8 }
}
>
{toasts.map((t) => (
<ToastItem
key={t.id}
toast={t}
position={position}
depth={depthById.get(t.id) ?? t.exitIndex ?? 0}
maxVisible={maxVisible}
surface={surface}
onRequestDismiss={requestDismiss}
onDone={remove}
/>
))}
</View>
</Ctx.Provider>
);
});
ToastProvider.displayName = "ToastProvider"; import { Toast } from "@/components/ui/toast/toast";
export function Example() {
return (
<Toast />
);
} Installation
Install the dependencies
npx expo install react-native-reanimated react-native-svg react-native-safe-area-contextAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/toast/toast.tsxcomponents/ui/toast/index.tsIcons it renders
Update the import paths to match your project setup.
Usage
import { useToast, ToastProvider } from "@/components/ui/toast/toast"; <Toast /> Also exported: useToast, ToastProvider.
Examples
Archiving mail.
import * as React from "react";
import { Pressable, View, type LayoutChangeEvent } from "react-native";
import Animated, { Easing, useAnimatedStyle, useSharedValue, withSpring, withTiming } from "react-native-reanimated";
import { ease, spring, timing, useReducedMotion } from "@lumioui/core";
import { useToast } from "../toast";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
interface Mail {
id: string;
from: string;
subject: string;
preview: string;
time: string;
}
const INBOX: Mail[] = [
{ id: "1", from: "Harrow Rail", subject: "Your seat for the 07:52 to Lindqvist", preview: "Coach C, seat 41 · platform 6", time: "8:02" },
{ id: "2", from: "Elena Vasquez", subject: "Re: Lease renewal", preview: "Signed and sent back, thanks for chasing", time: "7:15" },
{ id: "3", from: "Fieldnotes Weekly", subject: "The case for slower software", preview: "This week: why the best tools feel calm", time: "Tue" },
{ id: "4", from: "Bramble Dental", subject: "Reminder: cleaning on Friday", preview: "10:30 AM with Dr. Osei", time: "Mon" },
];
const DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
const IGNITE = { duration: timing.fast.duration, easing: Easing.bezier(...ease.out) };
/** An archived row dims, then folds its height away on spring.layout; Undo
* unfolds the slot and the row re-ignites in place. */
function FoldRow({ archived, children }: { archived: boolean; children: React.ReactNode }) {
const reduce = useReducedMotion();
const [h, setH] = React.useState(0);
const open = useSharedValue(archived ? 0 : 1);
const light = useSharedValue(archived ? 0 : 1);
React.useEffect(() => {
light.value = withTiming(archived ? 0 : 1, archived ? DIM : IGNITE);
open.value = reduce ? (archived ? 0 : 1) : withSpring(archived ? 0 : 1, spring.layout);
}, [archived, reduce, open, light]);
const style = useAnimatedStyle(() => ({
height: h ? h * open.value : undefined,
opacity: light.value,
}));
return (
<Animated.View style={style} className="overflow-hidden" pointerEvents={archived ? "none" : "auto"}>
<View onLayout={(e: LayoutChangeEvent) => setH(e.nativeEvent.layout.height)}>{children}</View>
</Animated.View>
);
}
/** ToastAction — archiving mail. Tap a row's archive button: the row dims
* and folds out of the list as the toast is born at the top edge; Undo
* unfolds its slot and the row switches back on where it was. */
export function ToastAction() {
const { show } = useToast();
const [archived, setArchived] = React.useState<Set<string>>(new Set());
const setOne = (id: string, on: boolean) =>
setArchived((prev) => {
const next = new Set(prev);
if (on) next.add(id);
else next.delete(id);
return next;
});
const archive = (m: Mail, duration = 5000) => {
setOne(m.id, true);
show("Conversation archived", {
description: m.subject,
duration,
action: { label: "Undo", onPress: () => setOne(m.id, false) },
});
};
// Archive the newsletter once on mount so the preview opens on the toast
// (held until dismissed); every later archive auto-hides after 5s.
React.useEffect(() => {
const t = setTimeout(() => archive(INBOX[2]!, 0), 500);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const firstVisible = INBOX.find((m) => !archived.has(m.id))?.id;
return (
<View className="w-full gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-3xl font-bold tracking-tight">Inbox</Text>
{archived.size ? (
<Pressable onPress={() => setArchived(new Set())} accessibilityRole="button" className="h-11 justify-center">
<Text className="text-base font-medium text-primary-text">Restore</Text>
</Pressable>
) : null}
</View>
<View className="overflow-hidden rounded-2xl bg-card">
{INBOX.map((m) => (
<FoldRow key={m.id} archived={archived.has(m.id)}>
<View className={`flex-row items-center gap-2 py-3 pl-4 pr-2 ${m.id !== firstVisible ? "border-t border-border" : ""}`}>
<View className="flex-1 gap-1">
<View className="flex-row items-center justify-between gap-2">
<Text className="flex-1 text-base font-semibold" numberOfLines={1}>{m.from}</Text>
<Text className="text-xs text-muted-foreground">{m.time}</Text>
</View>
<Text className="text-[15px]" numberOfLines={1}>{m.subject}</Text>
<Text variant="muted" numberOfLines={1}>{m.preview}</Text>
</View>
<Pressable
onPress={() => archive(m)}
accessibilityRole="button"
accessibilityLabel={`Archive ${m.subject}`}
className="h-11 w-11 items-center justify-center rounded-full"
>
<Icon name="archive" size="sm" color="mutedForeground" />
</Pressable>
</View>
</FoldRow>
))}
{archived.size === INBOX.length ? (
<View className="items-center py-10">
<Text variant="muted">Inbox zero</Text>
</View>
) : null}
</View>
</View>
);
} Sending calendar invites.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { useToast } from "../toast";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const GUESTS = ["Ines", "Tomás", "Wen", "Kofi", "Maren", "Arjun", "Leila", "Sam"];
/** ToastLoading — sending calendar invites. One toast starts as loading and
* morphs in place to success (no second toast), the status icon and copy
* crossfading while the card stays put. */
export function ToastLoading() {
const { loading, update } = useToast();
const [sent, setSent] = React.useState(false);
const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
React.useEffect(() => () => {
if (timer.current) clearTimeout(timer.current);
}, []);
const send = () => {
const id = loading("Sending 8 invites…", "Design review · Thu 16 Oct, 2:00 PM");
timer.current = setTimeout(() => {
update(id, {
variant: "success",
title: "Invites sent",
description: "8 people will get an email with the agenda",
duration: 3500,
dismissible: true,
});
setSent(true);
}, 2200);
};
return (
<Accent color="orange" className="w-full">
<View className="w-full gap-5 rounded-3xl bg-card p-5">
<View className="gap-1">
<Text className="text-2xl font-bold tracking-tight">Design review</Text>
<Text variant="muted">Thursday 16 October · 2:00 to 3:00 PM</Text>
</View>
<View className="overflow-hidden rounded-2xl bg-secondary">
<View className="flex-row items-center gap-3 px-4 py-3">
<Icon name="map-pin" size="sm" color="mutedForeground" />
<Text className="flex-1 text-[15px]">Room 4B, Harbour Building</Text>
</View>
<View className="flex-row items-center gap-3 border-t border-border px-4 py-3">
<Icon name="users" size="sm" color="mutedForeground" />
<Text className="flex-1 text-[15px]" numberOfLines={1}>{GUESTS.join(", ")}</Text>
<Text className="text-[15px] text-muted-foreground tabular-nums">8</Text>
</View>
</View>
<Button size="lg" className="w-full" onPress={send}>
{sent ? "Send again" : "Send invites"}
</Button>
</View>
</Accent>
);
} One export, one card.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { useToast } from "../toast";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
/** The first attempt fails; the retry goes through. */
const EXPORT_MS = 1800;
/** ToastVariants — one export, one card. Export the notebook: the toast is
* born loading, swaps in place to an error with Retry (the card stays put),
* and Retry runs it again until it resolves to success — the check draws
* and a sheen crosses the card. */
export function ToastVariants() {
const { loading, update } = useToast();
const [state, setState] = React.useState<"idle" | "busy" | "done">("idle");
const timers = React.useRef<ReturnType<typeof setTimeout>[]>([]);
React.useEffect(() => () => timers.current.forEach(clearTimeout), []);
const run = (id: number, attempt: number) => {
timers.current.push(
setTimeout(() => {
if (attempt === 0) {
update(id, {
variant: "error",
title: "Export failed",
description: "The connection dropped at 61 of 214 notes",
dismissible: true,
action: {
label: "Retry",
dismiss: false,
onPress: () => {
update(id, { variant: "loading", title: "Exporting 214 notes…", description: "Trying again", action: undefined, dismissible: false });
run(id, 1);
},
},
});
setState("idle");
return;
}
update(id, {
variant: "success",
title: "Notebook exported",
description: "Garden Club · 214 notes · 38 MB PDF in Files",
duration: 3500,
dismissible: true,
});
setState("done");
}, EXPORT_MS)
);
};
const start = () => {
setState("busy");
const id = loading("Exporting 214 notes…", "Garden Club · PDF with attachments");
run(id, 0);
};
return (
<Accent color="teal" 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-12 w-12 items-center justify-center rounded-2xl bg-primary">
<Icon name="leaf" size="md" color="primaryForeground" />
</View>
<View className="flex-1">
<Text className="text-xl font-bold tracking-tight">Garden Club</Text>
<Text variant="muted">214 notes · edited 9:14 AM</Text>
</View>
</View>
<View className="overflow-hidden rounded-2xl bg-secondary">
<View className="flex-row items-center gap-3 px-4 py-3">
<Icon name="file-text" size="sm" color="mutedForeground" />
<Text className="flex-1 text-[15px]">Format</Text>
<Text className="text-[15px] text-muted-foreground">PDF</Text>
</View>
<View className="flex-row items-center gap-3 border-t border-border px-4 py-3">
<Icon name="paperclip" size="sm" color="mutedForeground" />
<Text className="flex-1 text-[15px]">Attachments</Text>
<Text className="text-[15px] text-muted-foreground">Included</Text>
</View>
</View>
<Button size="lg" className="w-full" onPress={start} disabled={state === "busy"}>
{state === "done" ? "Export again" : "Export notebook"}
</Button>
</View>
</Accent>
);
} API reference
children* React.ReactNode — position ToastPosition Where toasts appear. Default "top".
"top" defaultDuration number Auto-dismiss duration in ms. 0 = manual dismiss only. Default 4000.
4000 limit number Max simultaneous toasts. Older ones are dismissed with an exit animation. Default 4.
4 maxVisible number Stack levels that peek out behind the front toast. Deeper toasts stay queued (timers running) until a slot frees. Default 3.
3 surface "solid" | "glass" Card material. "solid" (default) is an opaque card with a hairline and soft shadow that reads in both schemes; "glass" is the Lumio glass material for apps whose content behind is photographic / moving.
"solid"