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.
Alert
Inline status card that can resolve in place: its icon draws a check and the card can fold down to a shorter message. Also includes a modal alert that rises over a dimmed screen.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { View, Text, Modal, Pressable, type ViewProps, type TextProps } from "react-native";
import Animated, {
Easing,
LinearTransition,
useAnimatedProps,
useSharedValue,
useAnimatedStyle,
withDelay,
withSpring,
withTiming,
} from "react-native-reanimated";
import Svg, { Circle, Path } from "react-native-svg";
import {
BAND_STAGGER,
cn,
createVariant,
ease,
spring,
timing,
useReducedMotion,
useHaptic,
usePressAnimation,
useTheme,
AnimatedPath,
AnimatedPressable,
Sheen,
} from "@lumioui/core";
import { Glass } from "../glass";
import { iconMap } from "../icon/icon";
import { useSafeAreaInsets } from "react-native-safe-area-context";
const alertVariants = createVariant({
base: "w-full overflow-hidden rounded-2xl border p-5",
variants: {
variant: {
default: "border-border bg-card",
destructive: "border-destructive/30 bg-card",
success: "border-success/30 bg-card",
warning: "border-warning/30 bg-card",
},
},
defaultVariants: { variant: "default" },
});
/** Edge colour per variant — the layer that dims out when the status changes. */
const EDGE: Record<AlertVariant, string> = {
default: "border-border",
destructive: "border-destructive/30",
success: "border-success/30",
warning: "border-warning/30",
};
type AlertVariant = "default" | "destructive" | "success" | "warning";
export interface AlertProps extends ViewProps {
variant?: AlertVariant;
/** Grow or fold in place on spring.layout when the content changes
* (e.g. a resolved alert collapsing to one line). Default false. */
animateLayout?: boolean;
className?: string;
}
const AlertContext = React.createContext<AlertVariant>("default");
/** Content changes inside an alert grow or fold it on the layout spring. */
const foldInPlace = LinearTransition.springify()
.stiffness(spring.layout.stiffness)
.damping(spring.layout.damping)
.mass(spring.layout.mass);
/** Exit beats for the modal: content dims, the panel follows half a dim
* later, the backdrop clears last; the Modal unmounts after the room. */
const PANEL_EXIT_DELAY = timing.recede.duration / 2;
const ROOM_EXIT_DELAY = timing.recede.duration;
const ALERT_EXIT_MS = ROOM_EXIT_DELAY + timing.recede.duration + 20;
/** Light before motion: the room dims this long before the panel rises. */
const LIGHT_LEAD = timing.instant.duration;
/** Panel rise on entry (pt) — a dialog rises toward the eye. */
const PANEL_RISE = 12;
/** Modal alert panel metrics: 270pt wide, 14pt corner radius.
* Kept as consts so the values aren't anonymous magic numbers. */
const MODAL_ALERT_WIDTH = 270;
const MODAL_ALERT_RADIUS = 14;
/** The previous status edge, dimming out over the new one — a retint. */
function EdgeFade({ variant }: { variant: AlertVariant }) {
const o = useSharedValue(1);
React.useEffect(() => {
o.value = withTiming(0, { ...timing.normal, easing: Easing.bezier(...ease.inOut) });
}, [o]);
const style = useAnimatedStyle(() => ({ opacity: o.value }));
return (
<Animated.View
pointerEvents="none"
style={[{ position: "absolute", top: -1, left: -1, right: -1, bottom: -1 }, style]}
className={cn("rounded-2xl border", EDGE[variant])}
/>
);
}
/**
* Alert — inline status card. When `variant` changes the same card resolves:
* the 1px status edge retints over timing.normal while one sheen of the new
* status colour crosses it, and `Alert.Glyph` morphs in place. Copy swaps
* are the caller's; pass `animateLayout` to let the card fold or grow.
*/
const AlertRoot = forwardRef<React.ElementRef<typeof View>, AlertProps>(
function Alert({ variant = "default", animateLayout = false, className, children, ...props }, ref) {
const { colors } = useTheme();
const reduce = useReducedMotion();
// Track status changes during render: the last variant shown, the one
// it changed from, and a counter that fires one sheen per change.
const [shown, setShown] = React.useState(variant);
const [from, setFrom] = React.useState<AlertVariant | null>(null);
const [run, setRun] = React.useState(0);
if (shown !== variant) {
setFrom(shown);
setShown(variant);
setRun((n) => n + 1);
}
const light =
variant === "success"
? colors.success
: variant === "warning"
? colors.warning
: variant === "destructive"
? colors.destructive
: colors.primary;
return (
<AlertContext.Provider value={variant}>
<Animated.View
ref={ref as React.Ref<React.ElementRef<typeof Animated.View>>}
layout={animateLayout && !reduce ? foldInPlace : undefined}
className={cn(alertVariants({ variant }), className)}
accessibilityRole="alert"
{...props}
>
{children}
{from && run ? <EdgeFade key={run} variant={from} /> : null}
<Sheen run={run} color={light} strength={0.22} />
</Animated.View>
</AlertContext.Provider>
);
}
);
/** Glyph per status. Success is drawn by hand so its check can draw on. */
const GLYPH: Record<Exclude<AlertVariant, "success">, { name: "alert-triangle" | "info"; color: "warning" | "destructive" | "mutedForeground" }> = {
warning: { name: "alert-triangle", color: "warning" },
destructive: { name: "alert-triangle", color: "destructive" },
default: { name: "info", color: "mutedForeground" },
};
/** Non-success status glyph at an exact size. */
function StatusIcon({ variant, size }: { variant: Exclude<AlertVariant, "success">; size: number }) {
const { colors } = useTheme();
const G = iconMap[GLYPH[variant].name];
return <G size={size} color={colors[GLYPH[variant].color]} />;
}
/** Check stroke length in the 24pt grid (two legs of the mark). */
const CHECK_LEN = 12;
/** The check draws over this long once the ring has opened (§5b). */
const CHECK_DRAW_MS = 240;
/** The outgoing glyph shrinks to a dot of this scale before the new one opens. */
const DOT_SCALE = 0.25;
export interface AlertGlyphProps {
/** Override the status; defaults to the enclosing Alert's variant. */
variant?: AlertVariant;
/** Glyph size in pt. Default 22. */
size?: number;
className?: string;
}
/** One glyph layer: either the resting glyph or the incoming one opening. */
function GlyphFace({ variant, size, enter }: { variant: AlertVariant; size: number; enter: boolean }) {
const reduce = useReducedMotion();
const { colors } = useTheme();
const o = useSharedValue(enter ? 0 : 1);
const s = useSharedValue(enter && !reduce ? DOT_SCALE : 1);
const draw = useSharedValue(enter && !reduce ? 0 : 1);
React.useEffect(() => {
if (!enter) return;
// Opens after the outgoing glyph has shrunk to its dot.
const after = timing.recede.duration;
o.value = withDelay(after, withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) }));
if (reduce) return;
s.value = withDelay(after, withSpring(1, spring.swap));
draw.value = withDelay(after + timing.instant.duration, withTiming(1, { duration: CHECK_DRAW_MS, easing: Easing.bezier(...ease.out) }));
}, [enter, reduce, o, s, draw]);
const style = useAnimatedStyle(() => ({ opacity: o.value, transform: [{ scale: s.value }] }));
const checkProps = useAnimatedProps(() => ({ strokeDashoffset: CHECK_LEN * (1 - draw.value) }));
return (
<Animated.View style={[{ position: "absolute", width: size, height: size }, style]}>
{variant === "success" ? (
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
<Circle cx={12} cy={12} r={8.5} stroke={colors.success} strokeWidth={2} />
<AnimatedPath
d="M8.4 12.5L11.3 15.4L16.1 9.6"
stroke={colors.success}
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
strokeDasharray={`${CHECK_LEN} ${CHECK_LEN}`}
animatedProps={checkProps}
/>
</Svg>
) : (
<StatusIcon variant={variant} size={size} />
)}
</Animated.View>
);
}
/** The outgoing glyph — shrinks to a dot and dims (it never un-draws). */
function GlyphLeave({ variant, size }: { variant: AlertVariant; size: number }) {
const reduce = useReducedMotion();
const { colors } = useTheme();
const o = useSharedValue(1);
const s = useSharedValue(1);
React.useEffect(() => {
const dim = { ...timing.recede, easing: Easing.bezier(...ease.in) };
o.value = withTiming(0, dim);
if (!reduce) s.value = withTiming(DOT_SCALE, dim);
}, [reduce, o, s]);
const style = useAnimatedStyle(() => ({ opacity: o.value, transform: [{ scale: s.value }] }));
return (
<Animated.View style={[{ position: "absolute", width: size, height: size }, style]}>
{variant === "success" ? (
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
<Circle cx={12} cy={12} r={8.5} stroke={colors.success} strokeWidth={2} />
<Path d="M8.4 12.5L11.3 15.4L16.1 9.6" stroke={colors.success} strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" />
</Svg>
) : (
<StatusIcon variant={variant} size={size} />
)}
</Animated.View>
);
}
/**
* Alert.Glyph — the status mark, performing the change in place: the old
* glyph shrinks to a dot and dims, then the new one opens out of that dot;
* a success check draws itself on over 240ms. Static until the status
* changes. Hidden from screen readers (the alert's copy carries the state).
*/
function AlertGlyph({ variant: override, size = 22, className }: AlertGlyphProps) {
const ctx = React.useContext(AlertContext);
const variant = override ?? ctx;
const [shown, setShown] = React.useState(variant);
const [from, setFrom] = React.useState<AlertVariant | null>(null);
const [run, setRun] = React.useState(0);
if (shown !== variant) {
setFrom(shown);
setShown(variant);
setRun((n) => n + 1);
}
return (
<View
className={cn("items-center justify-center", className)}
style={{ width: size, height: size }}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
{from && run ? <GlyphLeave key={`out${run}`} variant={from} size={size} /> : null}
<GlyphFace key={`in${run}`} variant={variant} size={size} enter={run > 0} />
</View>
);
}const AlertTitle = forwardRef<React.ElementRef<typeof Text>, TextProps & { className?: string }>(
function AlertTitle({ className, ...props }, ref) {
return (
<Text
ref={ref}
className={cn("mb-1 text-base font-semibold text-foreground", className)}
accessibilityRole="header"
{...props}
/>
);
}
);
const AlertDescription = forwardRef<React.ElementRef<typeof Text>, TextProps & { className?: string }>(
function AlertDescription({ className, ...props }, ref) {
return (
<Text ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
);
}
);
// --- Modal alert ---
export interface ModalAlertProps {
open: boolean;
onOpenChange: (open: boolean) => void;
title: string;
message?: string;
buttons?: ModalAlertButton[];
/** Haptic style when alert appears. Default "warning". */
haptic?: "warning" | "error" | "success" | false;
/** Frosted glass panel instead of the solid card. Use only when
* the screen behind is photographic / moving content. Default false. */
glass?: boolean;
}
export interface ModalAlertButton {
text: string;
onPress?: () => void;
/** Visual style. Default "default". */
style?: "default" | "cancel" | "destructive";
}
/** Alert button row — own component so it can hold a usePressAnimation hook. */
function ModalAlertButtonRow({
button,
onSelect,
}: {
button: ModalAlertButton;
onSelect: (button: ModalAlertButton) => void;
}) {
const press = usePressAnimation({ pressedScale: 0.98 });
return (
<AnimatedPressable
onPress={() => onSelect(button)}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
style={press.animatedStyle}
className="items-center py-3 active:bg-muted"
accessibilityRole="button"
accessibilityLabel={button.text}
>
<Text
className={cn(
"text-[17px]",
button.style === "destructive" ? "text-destructive" : "text-primary-text",
button.style === "cancel" && "font-semibold"
)}
>
{button.text}
</Text>
</AnimatedPressable>
);
}
/**
* ModalAlert — a centered alert card with title, message and buttons
* separated by hairlines (two side by side, otherwise stacked).
* The cancel button is bold; destructive buttons are red. Light before
* motion: the room dims first, the panel rises 12pt (0.96 → 1 on
* spring.panel) 80ms later and its content switches on a band behind it.
* Leaving dims content, then the panel, and the room clears last.
*/
export function ModalAlert({ open, onOpenChange, title, message, buttons = [], haptic = "warning", glass = false }: ModalAlertProps) {
const reduceMotion = useReducedMotion();
const insets = useSafeAreaInsets();
const haptics = useHaptic();
/** Panel arrival (0 → 1) and its light while leaving. */
const rise = useSharedValue(0);
const opacity = useSharedValue(0);
/** Title, message and buttons switch on after the panel. */
const content = useSharedValue(0);
const backdropOpacity = useSharedValue(0);
// Held mounted through the exit — without this the Modal drops the
// moment `open` flips false and the dim-out never renders.
const [rendered, setRendered] = React.useState(open);
React.useEffect(() => {
const ignite = { ...timing.fast, easing: Easing.bezier(...ease.out) };
const dim = { ...timing.recede, easing: Easing.bezier(...ease.in) };
if (open) {
setRendered(true);
if (haptic) haptics[haptic]();
// Light before motion: the room dims first, the panel rises after the
// lead, and its content switches on a beat behind the panel.
backdropOpacity.value = withTiming(1, timing.normal);
opacity.value = withDelay(LIGHT_LEAD, withTiming(1, ignite));
content.value = withDelay(LIGHT_LEAD + BAND_STAGGER, withTiming(1, ignite));
if (reduceMotion) rise.value = 1;
else {
rise.value = 0;
rise.value = withDelay(LIGHT_LEAD, withSpring(1, spring.panel));
}
return;
}
if (!rendered) return;
// Dim in place: content first, then the panel (settling to 0.97, no
// retreat), and the room clears last.
content.value = withTiming(0, dim);
opacity.value = withDelay(PANEL_EXIT_DELAY, withTiming(0, dim));
backdropOpacity.value = withDelay(ROOM_EXIT_DELAY, withTiming(0, dim));
const t = setTimeout(() => setRendered(false), ALERT_EXIT_MS);
return () => clearTimeout(t);
}, [open, rendered, reduceMotion, haptic, haptics, rise, opacity, content, backdropOpacity]);
const contentStyle = useAnimatedStyle(() => {
// Leaving: the panel settles toward 0.97 as it dims, never shrinking away.
const leaving = rise.value >= 1 ? 1 - opacity.value : 0;
const scale = reduceMotion ? 1 : (0.96 + 0.04 * Math.min(1, rise.value)) * (1 - 0.03 * leaving);
return {
opacity: opacity.value,
transform: [{ translateY: reduceMotion ? 0 : (1 - rise.value) * PANEL_RISE }, { scale }],
};
});
const innerStyle = useAnimatedStyle(() => ({ opacity: content.value }));
const backdropStyle = useAnimatedStyle(() => ({ opacity: backdropOpacity.value }));
const handleButtonPress = (button: ModalAlertButton) => {
// Destructive confirms land a warning buzz; ordinary dismissals answer
// with a light tap (the appearance haptic already fired on open).
if (button.style === "destructive") haptics.warning();
else haptics.light();
onOpenChange(false);
button.onPress?.();
};
const handleBackdropClose = () => {
haptics.light();
onOpenChange(false);
};
return (
<Modal visible={rendered} transparent animationType="none" onRequestClose={() => onOpenChange(false)} statusBarTranslucent>
<View
style={{
flex: 1,
alignItems: "center",
justifyContent: "center",
// Centered modal must clear the notch/island and home indicator.
paddingVertical: Math.max(40, insets.top + insets.bottom + 8),
backgroundColor: "transparent",
}}
>
<Animated.View
style={[{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }, backdropStyle]}
className="bg-overlay"
>
<Pressable style={{ width: "100%", height: "100%" }} onPress={handleBackdropClose} accessibilityLabel="Close alert" accessibilityRole="button" />
</Animated.View>
<Animated.View
style={[{ width: MODAL_ALERT_WIDTH, borderRadius: MODAL_ALERT_RADIUS, overflow: "hidden" }, contentStyle]}
accessibilityViewIsModal
accessibilityRole="alert"
>
{(() => {
const body = (
<Animated.View style={innerStyle}>
<View style={{ paddingTop: 20, paddingBottom: 18, paddingHorizontal: 16, alignItems: "center", gap: 4 }}>
<Text className="text-center text-[17px] font-semibold leading-tight text-card-foreground">
{title}
</Text>
{message ? (
<Text className="text-center text-[13px] leading-snug text-muted-foreground">
{message}
</Text>
) : null}
</View>
{buttons.length > 0 && <View className="bg-border" style={{ height: 0.5 }} />}
{/* Exactly two actions sit side by side; one or 3+ stack. */}
{buttons.length === 2 ? (
<View className="flex-row">
<View className="flex-1">
<ModalAlertButtonRow button={buttons[0]!} onSelect={handleButtonPress} />
</View>
<View className="bg-border" style={{ width: 0.5 }} />
<View className="flex-1">
<ModalAlertButtonRow button={buttons[1]!} onSelect={handleButtonPress} />
</View>
</View>
) : (
buttons.map((button, i) => (
<React.Fragment key={i}>
{i > 0 && <View className="bg-border" style={{ height: 0.5 }} />}
<ModalAlertButtonRow button={button} onSelect={handleButtonPress} />
</React.Fragment>
))
)}
</Animated.View>
);
// Solid card by default: the panel sits on a dimmed backdrop, and
// a frost fallback there loses contrast in dark mode. `glass`
// opts into the material when the app behind is photographic.
return glass ? (
<Glass effect="regular" className="w-full">{body}</Glass>
) : (
<View className="w-full bg-card">{body}</View>
);
})()}
</Animated.View>
</View>
</Modal>
);
}
export const Alert = Object.assign(AlertRoot, {
Title: AlertTitle,
Description: AlertDescription,
Glyph: AlertGlyph,
Modal: ModalAlert,
});
Alert.displayName = "Alert";
AlertTitle.displayName = "AlertTitle";
AlertDescription.displayName = "AlertDescription";
ModalAlert.displayName = "ModalAlert";
AlertGlyph.displayName = "AlertGlyph";
/** @deprecated Use `ModalAlert` (or `Alert.Modal`). */
export const IOSAlert = ModalAlert;
/** @deprecated Use `ModalAlertProps`. */
export type IOSAlertProps = ModalAlertProps;
/** @deprecated Use `ModalAlertButton`. */
export type IOSAlertButton = ModalAlertButton; import { Alert } from "@/components/ui/alert/alert";
export function Example() {
return (
<Alert />
);
} 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/alert/alert.tsxcomponents/ui/alert/index.tsUpdate the import paths to match your project setup.
Usage
import { ModalAlert, Alert, IOSAlert } from "@/components/ui/alert/alert"; <Alert /> Also exported: ModalAlert, IOSAlert.
Examples
A trip page where one inline alert blocks check-in.
import * as React from "react";
import { View } from "react-native";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { Accent, timing } from "@lumioui/core";
import { Alert } from "../alert";
import { Button } from "../../button/button";
import { Text } from "../../text/text";
type Phase = "needed" | "resolved" | "folded";
/** Saving the passport is a short round trip — the button's light band runs. */
const SAVE_MS = 900;
/** Act → hold → resolve: the checked-in card holds before it folds. */
const HOLD_MS = 700;
const ignite = FadeIn.duration(timing.fast.duration);
const dim = FadeOut.duration(timing.recede.duration);
/** AlertInline — a trip page where one inline alert blocks check-in. The
* alert carries its own fix, and fixing it resolves the same card: the
* triangle shrinks to a dot and opens into a check that draws on, the
* edge retints amber → green under one sheen, the copy swaps in place,
* and after a 700ms hold the card folds into a single line. */
export function AlertInline() {
const [phase, setPhase] = React.useState<Phase>("needed");
const timers = React.useRef<ReturnType<typeof setTimeout>[]>([]);
React.useEffect(() => () => timers.current.forEach(clearTimeout), []);
const addPassport = () =>
new Promise<void>((done) => {
timers.current.push(
setTimeout(() => {
setPhase("resolved");
done();
timers.current.push(setTimeout(() => setPhase("folded"), HOLD_MS));
}, SAVE_MS)
);
});
return (
<Accent color="teal" className="w-full">
<View className="w-full gap-4">
<View className="gap-1 px-1">
<Text className="text-3xl font-bold tracking-tight">Norhaven</Text>
<Text variant="muted">Fri 14 Nov · ELD → NHV · Flight LM 680</Text>
</View>
<Alert variant={phase === "needed" ? "warning" : "success"} animateLayout className="gap-3 p-4">
<View className="flex-row gap-3">
<Alert.Glyph />
{phase === "needed" ? (
<Animated.View key="needed" entering={ignite} exiting={dim} className="flex-1">
<Alert.Title>Passport details needed</Alert.Title>
<Alert.Description>
Norhaven requires them before online check-in opens. It takes about a minute.
</Alert.Description>
</Animated.View>
) : phase === "resolved" ? (
<Animated.View key="resolved" entering={ignite} exiting={dim} className="flex-1">
<Alert.Title>You're checked in</Alert.Title>
<Alert.Description>Seat 14A. Your boarding pass is in Lumio Pass.</Alert.Description>
</Animated.View>
) : (
<Animated.View key="folded" entering={ignite} exiting={dim} className="flex-1 justify-center">
<Alert.Title className="mb-0">Checked in · Seat 14A</Alert.Title>
</Animated.View>
)}
</View>
{phase === "needed" ? (
<Animated.View key="fix" entering={ignite} exiting={dim} className="ml-9 self-start">
<Button size="sm" onPress={addPassport}>
Add passport
</Button>
</Animated.View>
) : null}
</Alert>
<View className="overflow-hidden rounded-2xl bg-card">
{[
{ label: "Departs", value: "8:25 PM", sub: "Elden International, Gate S9" },
{ label: "Arrives", value: "6:40 AM", sub: "Norhaven, next day" },
{ label: "Bags", value: "1 checked", sub: "23 kg included" },
].map((r, i) => (
<View key={r.label} className={`flex-row items-center px-4 py-3 ${i > 0 ? "border-t border-border" : ""}`}>
<View className="flex-1">
<Text className="text-[15px] font-medium">{r.label}</Text>
<Text variant="muted">{r.sub}</Text>
</View>
<Text className="text-base font-semibold tabular-nums">{r.value}</Text>
</View>
))}
</View>
{phase === "folded" ? (
<Animated.View entering={ignite}>
<Button size="lg" variant="secondary" className="w-full" onPress={() => setPhase("needed")}>
Undo check-in
</Button>
</Animated.View>
) : null}
</View>
</Accent>
);
} A photo library in select mode.
import * as React from "react";
import { Image, Pressable, View } from "react-native";
import { Alert } from "../alert";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const photo = (id: string) => `https://images.unsplash.com/${id}?w=300&h=300&fit=crop&q=70&auto=format`;
const ALL = [
"photo-1506905925346-21bda4d32df4",
"photo-1470071459604-3b5ec3a7fe05",
"photo-1501785888041-af3ef285b470",
"photo-1507525428034-b723cf961d3e",
"photo-1476514525535-07fb3b4ae5f1",
"photo-1509316785289-025f5b846b35",
];
/** AlertModal — a photo library in select mode. Delete asks first with the
* centred alert (two actions side by side); confirming removes the
* picked photos from the grid. */
export function AlertModal() {
const [photos, setPhotos] = React.useState(ALL);
const [picked, setPicked] = React.useState<string[]>([ALL[1]!, ALL[4]!]);
const [confirm, setConfirm] = React.useState(false);
const toggle = (id: string) =>
setPicked((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));
const n = picked.length;
return (
<View className="w-full gap-3">
<View className="flex-row items-center justify-between px-1">
<Text className="text-2xl font-bold tracking-tight">Recents</Text>
<Pressable
onPress={() => {
setPhotos(ALL);
setPicked([]);
}}
accessibilityRole="button"
className="h-11 justify-center"
>
<Text className="text-base font-medium text-primary-text">Restore all</Text>
</Pressable>
</View>
<View className="w-full flex-row flex-wrap gap-1 overflow-hidden rounded-2xl">
{photos.map((id) => {
const on = picked.includes(id);
return (
<Pressable
key={id}
onPress={() => toggle(id)}
accessibilityRole="checkbox"
accessibilityState={{ checked: on }}
accessibilityLabel="Photo"
className="aspect-square w-[32.8%]"
>
<Image source={{ uri: photo(id) }} className={`h-full w-full bg-muted ${on ? "opacity-70" : ""}`} />
{on ? (
<View className="absolute bottom-2 right-2 h-6 w-6 items-center justify-center rounded-full border-2 border-white bg-primary">
<Icon name="check" size="sm" color="primaryForeground" strokeWidth={3} />
</View>
) : null}
</Pressable>
);
})}
</View>
<View className="h-14 flex-row items-center justify-between rounded-2xl bg-card px-4">
<Text className="text-[15px] font-medium">
{n === 0 ? "Select photos" : `${n} photo${n === 1 ? "" : "s"} selected`}
</Text>
<Pressable
onPress={() => n > 0 && setConfirm(true)}
disabled={n === 0}
accessibilityRole="button"
accessibilityLabel="Delete selected photos"
className={`h-11 w-11 items-center justify-center ${n === 0 ? "opacity-40" : ""}`}
>
<Icon name="trash" size="md" color="destructive" />
</Pressable>
</View>
<Alert.Modal
open={confirm}
onOpenChange={setConfirm}
title={`Delete ${n} Photo${n === 1 ? "" : "s"}?`}
message="They'll stay in Recently Deleted for 30 days, then they're gone from all your devices."
buttons={[
{ text: "Cancel", style: "cancel" },
{
text: "Delete",
style: "destructive",
onPress: () => {
setPhotos((p) => p.filter((id) => !picked.includes(id)));
setPicked([]);
},
},
]}
/>
</View>
);
} API reference
Alert
variant AlertVariant — animateLayout boolean Grow or fold in place on spring.layout when the content changes (e.g. a resolved alert collapsing to one line). Default false.
—className string — AlertGlyph
variant AlertVariant Override the status; defaults to the enclosing Alert's variant.
—size number Glyph size in pt. Default 22.
—className string — ModalAlert
open* boolean — onOpenChange* (open: boolean) => void — title* string — message string — buttons ModalAlertButton[] [] haptic "warning" | "error" | "success" | false Haptic style when alert appears. Default "warning".
"warning" glass boolean Frosted glass panel instead of the solid card. Use only when the screen behind is photographic / moving content. Default false.
false