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.
Action Swap
Building blocks for swapping a label or icon in place: the old one fades as the new one appears, plainly, with a small lift or letter by letter. Includes button, text, icon and multi-state versions.
Preview
import * as React from "react";
import { forwardRef, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { Pressable, StyleSheet, View, type PressableProps, type ViewProps, type GestureResponderEvent, } from "react-native";
import Animated, {
type SharedValue,
useSharedValue,
useAnimatedStyle,
withDelay,
withSpring,
withTiming,
Easing,
} from "react-native-reanimated";
import { cn, useHaptic, useReducedMotion, usePressAnimation, spring, ease, timing, tempo, AnimatedPressable, } from "@lumioui/core";
import { Icon, type IconName } from "../icon";
/**
* ActionSwap — multi-mode content-swap primitives.
*
* ActionSwapButton — spring-pressed pill cycling items (prefix icon slot +
* active label swap), controlled or uncontrolled.
* ActionSwapText — standalone label swap (roll / blur / cascade).
* ActionSwapIcon — icon-slot swap.
* ActionSwap — backward-compatible multi-state cycler built on the
* primitives above (accent colors, IconName icons).
*
* Every mode swaps in place: the outgoing layer dims (timing.recede, →0.96)
* while the incoming one ignites (opacity on timing.fast ease.out, 0.96→1 on
* spring.swap). Modes differ only in what rides on top of that:
* blur — the plain in-place swap; nothing travels.
* roll — adds a small upward lift (≤6px) for sequences with direction.
* cascade — the new label ignites letter by letter, left to right.
*
* Opt-in `light` gives cascade reading order: each letter of the incoming
* label switches on in place, left → right, on one shared front — the label
* is lit into place, not typed. No band of light is drawn across it.
*/
export type ActionSwapMode = "roll" | "blur" | "cascade";
/** Modes with a single-element variant set — cascade animates per letter. */
type CoreSwapMode = "roll" | "blur";
/** Legacy alias accepted on `animation` props — "fade" maps to "blur". */
type LegacySwapAnimation = ActionSwapMode | "fade";
/** Scale the outgoing layer dims to and the incoming layer ignites from. */
const SWAP_SCALE = 0.96;
/** Icons are ~16px — the same 4% would be invisible, so glyphs bloom wider. */
const ICON_SWAP_SCALE = 0.86;
/** Roll lift (px): incoming rises this far, outgoing leaves half as far. */
const ROLL_LIFT = 5;
/** Cascade letters rise this far as they ignite. */
const LETTER_LIFT = 3;
// Dim — exits lead with opacity and finish before the ignite does.
const SWAP_DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
// Ignite — opacity of the arriving layer.
const SWAP_IGNITE = { duration: timing.fast.duration, easing: Easing.bezier(...ease.out) };
// One letter every tempo.flick / 8 (20ms): a 10-letter label fully lit in
// ~360ms, inside the ~400ms entrance budget.
const LETTER_STAGGER = tempo.flick / 8;
/** Window after which a finished outgoing layer unmounts — outlasts the 120ms dim. */
const EXIT_WINDOW = tempo.drift;
// Reading order — one steady front across the label (no visible band);
// each letter switches on in place as the front reaches it.
const READ_SWEEP = { duration: tempo.glow, easing: Easing.bezier(...ease.inOut) };
/** A letter goes dark → lit over this much of the front's travel (pt). */
const READ_SOFT = 12;
/** Map the deprecated `animation` alias to a mode. */
function resolveMode(mode: ActionSwapMode | undefined, animation: LegacySwapAnimation | undefined): ActionSwapMode {
if (mode) return mode;
if (animation === "fade") return "blur";
return animation ?? "roll";
}
interface SwapLayer<T> {
key: string;
payload: T;
}
/**
* Two-layer swap state shared by every primitive: the incoming payload
* renders in flow (sizing the slot) while the outgoing payload lingers as
* an absolute overlay for one dim, then unmounts. Drives the shared
* dim / ignite / bloom values; cascade letters ignite themselves on mount
* but the outgoing label still dims as one layer.
*
* Layers are resolved during render (not in a passive effect) so the
* outgoing overlay mounts on the same commit the new payload appears —
* the effect version left one frame where the old label blinked out.
* Reduced motion keeps the swap as a plain opacity crossfade.
*/
function useSwapLayers<T>(key: string, payload: T, reduce: boolean) {
const [layers, setLayers] = useState<{ display: SwapLayer<T>; outgoing: SwapLayer<T> | null; gen: number }>(
() => ({ display: { key, payload }, outgoing: null, gen: 0 })
);
if (key !== layers.display.key) {
setLayers({ display: { key, payload }, outgoing: layers.display, gen: layers.gen + 1 });
} else if (payload !== layers.display.payload) {
// Same slot, fresh payload — refresh silently, no choreography.
setLayers({ ...layers, display: { key, payload } });
}
const { display, outgoing, gen } = layers;
/** 0 → 1 as the outgoing layer dims. */
const dimT = useSharedValue(1);
/** 0 → 1 opacity of the incoming layer. */
const igniteT = useSharedValue(1);
/** 0 → 1 scale/lift settle of the incoming layer (spring.swap). */
const bloomT = useSharedValue(1);
useLayoutEffect(() => {
if (gen === 0) return;
dimT.value = 0;
igniteT.value = 0;
if (reduce) {
dimT.value = withTiming(1, timing.recede);
igniteT.value = withTiming(1, timing.fast);
bloomT.value = 1;
return;
}
bloomT.value = 0;
dimT.value = withTiming(1, SWAP_DIM);
igniteT.value = withTiming(1, SWAP_IGNITE);
bloomT.value = withSpring(1, spring.swap);
}, [gen, reduce, dimT, igniteT, bloomT]);
// Drop the spent layer once its dim has run.
useEffect(() => {
if (!outgoing) return;
const id = setTimeout(
() => setLayers((l) => (l.gen === gen ? { ...l, outgoing: null } : l)),
EXIT_WINDOW
);
return () => clearTimeout(id);
}, [outgoing, gen]);
return { display, outgoing, dimT, igniteT, bloomT };
}
// --- CascadeLetter — one glyph of a cascade swap ---
interface CascadeLetterProps {
char: string;
index: number;
/** First paint renders lit — no intro replay on mount. */
skipIntro: boolean;
className?: string;
}
function CascadeLetter({ char, index, skipIntro, className }: CascadeLetterProps) {
const lit = useSharedValue(skipIntro ? 1 : 0);
const rise = useSharedValue(skipIntro ? 1 : 0);
useEffect(() => {
if (skipIntro) return;
const delay = index * LETTER_STAGGER;
lit.value = withDelay(delay, withTiming(1, SWAP_IGNITE));
rise.value = withDelay(delay, withSpring(1, spring.swap));
}, [index, skipIntro, lit, rise]);
const style = useAnimatedStyle(() => ({
opacity: lit.value,
transform: [{ translateY: (1 - rise.value) * LETTER_LIFT }],
}));
return (
<Animated.Text className={className} style={style}>
{/* A lone " " Text collapses to zero width — nbsp keeps the slot. */}
{char === " " ? "\u00A0" : char}
</Animated.Text>
);
}
// --- Lit cascade — the reading-light flavour of cascade ---
interface LitLetterProps {
char: string;
/** 0 → 1 pass of the reading light. */
sweep: SharedValue<number>;
/** Measured row width; 0 until laid out. */
rowW: SharedValue<number>;
className?: string;
}
/** One glyph that switches on when the band's front reaches its x. */
function LitLetter({ char, sweep, rowW, className }: LitLetterProps) {
const x = useSharedValue(-1);
const style = useAnimatedStyle(() => {
if (sweep.value >= 1) return { opacity: 1, transform: [{ translateY: 0 }] };
if (x.value < 0 || rowW.value <= 0) return { opacity: 0, transform: [{ translateY: LETTER_LIFT }] };
const front = sweep.value * (rowW.value + READ_SOFT);
const on = Math.min(1, Math.max(0, (front - x.value) / READ_SOFT));
return { opacity: on, transform: [{ translateY: (1 - on) * LETTER_LIFT }] };
});
return (
<Animated.Text
className={className}
style={style}
onLayout={(e) => {
x.value = e.nativeEvent.layout.x;
}}
>
{char === " " ? "\u00A0" : char}
</Animated.Text>
);
}
interface LitCascadeRowProps {
label: string;
skipIntro: boolean;
className?: string;
}
/**
* The incoming label lit in reading order: every letter reads one shared
* front on the UI thread and switches on in place. No band is drawn.
*/
function LitCascadeRow({ label, skipIntro, className }: LitCascadeRowProps) {
const sweep = useSharedValue(skipIntro ? 1 : 0);
const rowW = useSharedValue(0);
useEffect(() => {
if (skipIntro) return;
sweep.value = withTiming(1, READ_SWEEP);
}, [skipIntro, sweep]);
return (
<View
style={styles.letterRow}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
onLayout={(e) => {
rowW.value = e.nativeEvent.layout.width;
}}
>
{label.split("").map((char, i) => (
<LitLetter key={i} char={char} sweep={sweep} rowW={rowW} className={className} />
))}
</View>
);
}
// --- ActionSwapText — standalone animated text swap ---
export interface ActionSwapTextProps extends ViewProps {
/** Slot identity — when this changes, the text animates. */
value: string;
children: ReactNode;
/** Swap choreography. "cascade" needs a string child. Default "roll". */
mode?: ActionSwapMode;
/** @deprecated Use `mode`. "fade" maps to "blur". */
animation?: LegacySwapAnimation;
/** Cascade only: each letter of the incoming label switches on in place
* in reading order (over 390ms). No band is drawn. Default false. */
light?: boolean;
/** @deprecated No effect: no reading-light band is drawn any more. */
lightColor?: string;
/** @deprecated No effect: no reading-light band is drawn any more. */
lightOnFill?: boolean;
/** Applied to the root View AND the swapped text (text classes are
* inert on the View, layout classes are inert on the Text). */
className?: string;
}
/**
* Incoming / outgoing layer styles for one swap: dim + ignite, scaled
* around `scale`, with an optional upward `lift`. Reduced motion: opacity only.
*/
function useSwapStyles(
dimT: SharedValue<number>,
igniteT: SharedValue<number>,
bloomT: SharedValue<number>,
scale: number,
lift: number,
reduce: boolean
) {
const incomingStyle = useAnimatedStyle(() => ({
opacity: igniteT.value,
transform: reduce
? []
: [
{ translateY: (1 - bloomT.value) * lift },
{ scale: scale + bloomT.value * (1 - scale) },
],
}));
const outgoingStyle = useAnimatedStyle(() => ({
opacity: 1 - dimT.value,
transform: reduce
? []
: [
// Dim to leave: the exit travels half as far as the entrance.
{ translateY: -dimT.value * lift * 0.5 },
{ scale: 1 - dimT.value * (1 - scale) },
],
}));
return { incomingStyle, outgoingStyle };
}
/**
* ActionSwapText — animated text that swaps when `value` changes.
* Cascade splits a string label into per-letter layers that ignite left to
* right; non-string children and reduced motion fall back to the plain swap.
*/
export const ActionSwapText = forwardRef<React.ElementRef<typeof View>, ActionSwapTextProps>(
function ActionSwapText(
{ value, children, mode, animation, light = false, lightColor: _lightColor, lightOnFill: _lightOnFill, className, ...props },
ref
) {
const reduce = useReducedMotion();
const resolvedMode = resolveMode(mode, animation);
const label = typeof children === "string" ? children : null;
const cascadeActive = resolvedMode === "cascade" && label !== null && !reduce;
const coreMode: CoreSwapMode = resolvedMode === "cascade" ? "roll" : resolvedMode;
// Mode joins the slot key so switching choreography replays cleanly.
const swapKey = `${cascadeActive ? "cascade" : coreMode}:${value}`;
const { display, outgoing, dimT, igniteT, bloomT } = useSwapLayers(swapKey, children, reduce);
const firstPaint = useRef(true);
useEffect(() => {
firstPaint.current = false;
}, []);
// Cascade's incoming layer is the letters themselves — its whole-layer
// style only carries the outgoing dim.
const lift = coreMode === "roll" && !cascadeActive ? ROLL_LIFT : 0;
const { incomingStyle, outgoingStyle } = useSwapStyles(dimT, igniteT, bloomT, SWAP_SCALE, lift, reduce);
// Text layers default to the foreground ink so a bare <ActionSwapText>
// reads in both themes; caller text classes override via cn().
const textClass = cn("text-foreground", className);
const displayLabel = typeof display.payload === "string" ? display.payload : null;
const outgoingLabel = outgoing && typeof outgoing.payload === "string" ? outgoing.payload : null;
return (
<View
ref={ref}
className={cn(className)}
style={styles.clip}
accessibilityRole="text"
accessibilityLabel={displayLabel ?? undefined}
{...props}
>
{cascadeActive && displayLabel !== null ? (
<>
{outgoingLabel !== null && outgoing ? (
// The leaving label dims as one layer — only arrivals cascade.
<Animated.Text
key={`out-${outgoing.key}`}
style={[styles.outgoing, outgoingStyle]}
className={textClass}
numberOfLines={1}
ellipsizeMode="clip"
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no"
>
{outgoingLabel}
</Animated.Text>
) : null}
{/* Letters are decorative fragments; the container label above
is what screen readers announce. */}
{light ? (
<LitCascadeRow
key={display.key}
label={displayLabel}
skipIntro={firstPaint.current}
className={textClass}
/>
) : (
<View
key={display.key}
style={styles.letterRow}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
{displayLabel.split("").map((char, i) => (
<CascadeLetter
key={i}
char={char}
index={i}
skipIntro={firstPaint.current}
className={textClass}
/>
))}
</View>
)}
</>
) : (
<>
{outgoing ? (
<Animated.Text
key={outgoing.key}
style={[styles.outgoing, outgoingStyle]}
className={textClass}
// One line, clipped: a longer leaving label must not wrap
// into the new (narrower) slot mid-exit.
numberOfLines={1}
ellipsizeMode="clip"
accessibilityElementsHidden
importantForAccessibility="no"
>
{outgoing.payload}
</Animated.Text>
) : null}
<Animated.Text
style={incomingStyle}
className={textClass}
>
{display.payload}
</Animated.Text>
</>
)}
</View>
);
}
);
ActionSwapText.displayName = "ActionSwapText";
// --- ActionSwapIcon — icon slot swap ---
export interface ActionSwapIconProps extends ViewProps {
/** Slot identity — when this changes, the icon animates. */
value: string;
children: ReactNode;
/** Swap choreography ("cascade" falls back to roll — icons are single
* glyphs). Default "roll". */
mode?: ActionSwapMode;
/** @deprecated Use `mode`. */
animation?: LegacySwapAnimation;
className?: string;
}
/**
* ActionSwapIcon — swaps its child when `value` changes: the old glyph
* dims while the new one ignites in place (roll adds a small lift).
*/
export const ActionSwapIcon = forwardRef<React.ElementRef<typeof View>, ActionSwapIconProps>(
function ActionSwapIcon({ value, children, mode, animation, className, ...props }, ref) {
const reduce = useReducedMotion();
const resolvedMode = resolveMode(mode, animation);
const coreMode: CoreSwapMode = resolvedMode === "cascade" ? "roll" : resolvedMode;
const swapKey = `${coreMode}:${value}`;
const { display, outgoing, dimT, igniteT, bloomT } = useSwapLayers(swapKey, children, reduce);
const { incomingStyle, outgoingStyle } = useSwapStyles(
dimT,
igniteT,
bloomT,
ICON_SWAP_SCALE,
coreMode === "roll" ? ROLL_LIFT : 0,
reduce
);
return (
<View
ref={ref}
className={cn("items-center justify-center", className)}
style={styles.clip}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
{...props}
>
{outgoing ? (
<Animated.View key={outgoing.key} style={[styles.outgoingCenter, outgoingStyle]} pointerEvents="none">
{outgoing.payload}
</Animated.View>
) : null}
<Animated.View style={incomingStyle}>{display.payload}</Animated.View>
</View>
);
}
);
ActionSwapIcon.displayName = "ActionSwapIcon";
// --- ActionSwapButton — cycling button ---
export interface ActionSwapItem {
id: string;
label: ReactNode;
icon?: ReactNode;
/** Overrides the accessibility label derived from `label`. */
ariaLabel?: string;
}
export type ActionSwapButtonVariant = "primary" | "secondary" | "outline" | "ghost";
export type ActionSwapButtonSize = "sm" | "md" | "lg" | "icon";
export interface ActionSwapButtonProps extends Omit<PressableProps, "children"> {
items: ActionSwapItem[];
/** Controlled active item id. */
value?: string;
/** Initial active item id (uncontrolled). Defaults to the first item. */
defaultValue?: string;
onValueChange?: (value: string, item: ActionSwapItem) => void;
variant?: ActionSwapButtonVariant;
size?: ActionSwapButtonSize;
/** Swap choreography for icon + label slots. Default "roll". */
mode?: ActionSwapMode;
/** @deprecated Use `mode`. */
animation?: LegacySwapAnimation;
/** Cascade only: light the incoming label into place with a reading
* light (see ActionSwapText). Default false. */
light?: boolean;
/** Hide the label — icon slot only. Defaults to size === "icon". */
iconOnly?: boolean;
/** Advance to the next item on press. Default true. */
cycle?: boolean;
disabled?: boolean;
className?: string;
}
const BUTTON_VARIANT_CLASS: Record<ActionSwapButtonVariant, string> = {
primary: "bg-primary",
secondary: "bg-secondary",
outline: "border border-border bg-transparent",
ghost: "bg-transparent",
};
const BUTTON_TEXT_CLASS: Record<ActionSwapButtonVariant, string> = {
primary: "text-primary-foreground",
secondary: "text-secondary-foreground",
outline: "text-foreground",
ghost: "text-muted-foreground",
};
const BUTTON_SIZE_CLASS: Record<ActionSwapButtonSize, string> = {
// Heights match Button (sm 36 / md 44 / lg 52) so swap buttons sit flush
// in a row of regular buttons.
sm: "h-9 gap-1.5 rounded-full px-3.5",
md: "h-11 gap-2 rounded-full px-4",
lg: "h-[52px] gap-2 rounded-full px-6",
icon: "h-11 w-11 rounded-full",
};
const BUTTON_LABEL_SIZE: Record<ActionSwapButtonSize, string> = {
sm: "text-sm",
md: "text-[15px]",
lg: "text-[17px]",
icon: "text-[15px]",
};
const BUTTON_ICON_SIZE: Record<ActionSwapButtonSize, string> = {
sm: "h-4 w-4",
md: "h-4 w-4",
lg: "h-5 w-5",
icon: "h-5 w-5",
};
/**
* ActionSwapButton — spring-pressed pill that cycles `items` on press,
* swapping the prefix icon slot and active label with the chosen mode.
* Controlled via `value`/`onValueChange` or uncontrolled via `defaultValue`.
*/
export const ActionSwapButton = forwardRef<React.ElementRef<typeof Pressable>, ActionSwapButtonProps>(
function ActionSwapButton(
{
items,
value,
defaultValue,
onValueChange,
variant = "secondary",
size = "md",
mode,
animation,
iconOnly = size === "icon",
cycle = true,
light = false,
className,
disabled,
onPress,
...props
},
ref
) {
const haptics = useHaptic();
const press = usePressAnimation({ disabled });
// Hooks live above the `!activeItem` early return below.
const resolvedMode = resolveMode(mode, animation);
const [internal, setInternal] = useState(defaultValue ?? items[0]?.id);
const currentId = value ?? internal;
const activeIndex = Math.max(0, items.findIndex((item) => item.id === currentId));
const activeItem = items[activeIndex] ?? items[0];
const hasIcon = items.some((item) => item.icon);
const nextItem = cycle && items.length > 1 ? items[(activeIndex + 1) % items.length] : undefined;
if (!activeItem) return null;
const accessibleLabel =
activeItem.ariaLabel ??
(typeof activeItem.label === "string" ? activeItem.label : undefined);
const handlePress = (e: GestureResponderEvent) => {
onPress?.(e);
if (disabled || !nextItem) return;
haptics.selection();
if (value === undefined) setInternal(nextItem.id);
onValueChange?.(nextItem.id, nextItem);
};
const handlePressIn = () => {
press.onPressIn();
};
const handlePressOut = () => {
press.onPressOut();
};
return (
<AnimatedPressable
ref={ref}
disabled={disabled}
onPress={handlePress}
onPressIn={handlePressIn}
onPressOut={handlePressOut}
style={press.animatedStyle}
className={cn(
"flex-row items-center justify-center overflow-hidden",
BUTTON_VARIANT_CLASS[variant],
BUTTON_SIZE_CLASS[size],
disabled && "opacity-50",
className
)}
accessibilityRole="button"
accessibilityLabel={accessibleLabel}
accessibilityState={{ disabled }}
hitSlop={6}
{...props}
>
{hasIcon ? (
<ActionSwapIcon
value={activeItem.id}
mode={resolvedMode}
className={BUTTON_ICON_SIZE[size]}
>
{activeItem.icon ?? null}
</ActionSwapIcon>
) : null}
{!iconOnly ? (
<ActionSwapText
value={activeItem.id}
mode={resolvedMode}
light={light}
lightOnFill={variant === "primary"}
className={cn("font-medium", BUTTON_LABEL_SIZE[size], BUTTON_TEXT_CLASS[variant])}
>
{activeItem.label}
</ActionSwapText>
) : null}
</AnimatedPressable>
);
}
);
ActionSwapButton.displayName = "ActionSwapButton";
// --- ActionSwap — legacy multi-state cycler (backward compatible) ---
export interface ActionSwapState {
label: string;
icon?: IconName;
/** Optional accent color token for this state. */
accent?: "primary" | "destructive" | "success" | "warning";
}
export interface ActionSwapProps extends Omit<PressableProps, "children"> {
/** States to cycle through. Must have at least 2. */
states: ActionSwapState[];
/** Controlled active index. */
value?: number;
/** Initial active index (uncontrolled). Default 0. */
defaultValue?: number;
onStateChange?: (index: number) => void;
/** Visual style. Default "pill". */
variant?: "pill" | "plain" | "outline";
/** Swap choreography for icon + label. Default "roll". */
mode?: ActionSwapMode;
/** Cascade only: light the incoming label into place with a reading
* light (see ActionSwapText). Default false. */
light?: boolean;
/** Accessible label prefix. Default "Swap to". */
accessibilityLabelPrefix?: string;
disabled?: boolean;
className?: string;
}
const accentClass: Record<NonNullable<ActionSwapState["accent"]>, string> = {
primary: "bg-primary",
destructive: "bg-destructive",
success: "bg-success",
warning: "bg-warning",
};
/** Foreground text class that pairs with each accent background. */
const accentTextClass: Record<NonNullable<ActionSwapState["accent"]>, string> = {
primary: "text-primary-foreground",
destructive: "text-destructive-foreground",
success: "text-success-foreground",
warning: "text-warning-foreground",
};
/** Foreground color token for the leading icon on each accent background. */
const accentIconColor: Record<
NonNullable<ActionSwapState["accent"]>,
"primaryForeground" | "destructiveForeground" | "successForeground" | "warningForeground"
> = {
primary: "primaryForeground",
destructive: "destructiveForeground",
success: "successForeground",
warning: "warningForeground",
};
const variantClass: Record<NonNullable<ActionSwapProps["variant"]>, string> = {
pill: "rounded-full",
plain: "rounded-lg",
outline: "rounded-full border border-border",
};
/**
* ActionSwap — multi-step button that cycles through states on press.
* Composes ActionSwapIcon + ActionSwapText, so every `mode` works here too.
*/
export const ActionSwap = forwardRef<React.ElementRef<typeof Pressable>, ActionSwapProps>(
function ActionSwap(
{
states,
value,
defaultValue = 0,
onStateChange,
variant = "pill",
mode = "roll",
accessibilityLabelPrefix = "Swap to",
light = false,
disabled,
className,
onPress,
...props
},
ref
) {
const haptics = useHaptic();
const press = usePressAnimation({ pressedScale: 0.94, disabled });
const [internal, setInternal] = useState(defaultValue);
const current = value ?? internal;
const activeState = states[current] ?? states[0];
const accent = activeState?.accent;
const handlePress = (e: GestureResponderEvent) => {
onPress?.(e);
if (disabled || states.length < 2) return;
haptics.selection();
const next = (current + 1) % states.length;
if (value === undefined) setInternal(next);
onStateChange?.(next);
};
if (!activeState) return null;
return (
<AnimatedPressable
ref={ref}
disabled={disabled}
onPress={handlePress}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
style={press.animatedStyle}
className={cn(
"h-11 flex-row items-center justify-center gap-2 px-5",
variantClass[variant],
// plain = bare label/icon, no fill — pill without a fill is
// indistinguishable from the default treatment.
variant === "plain" ? "bg-transparent" : accent ? accentClass[accent] : "bg-secondary",
className
)}
accessibilityRole="button"
accessibilityLabel={`${accessibilityLabelPrefix} ${activeState.label}`}
accessibilityState={{ disabled }}
hitSlop={6}
{...props}
>
{activeState.icon ? (
<ActionSwapIcon value={String(current)} mode={mode} className="h-4 w-4">
<Icon
name={activeState.icon}
size="sm"
color={accent ? accentIconColor[accent] : "foreground"}
/>
</ActionSwapIcon>
) : null}
<ActionSwapText
value={String(current)}
mode={mode}
light={light}
lightOnFill={variant !== "plain" && !!accent}
className={cn(
"text-base font-semibold leading-tight",
accent ? accentTextClass[accent] : "text-foreground"
)}
>
{activeState.label}
</ActionSwapText>
</AnimatedPressable>
);
}
);
ActionSwap.displayName = "ActionSwap";
const styles = StyleSheet.create({
/** Vertical clip only matters — layers never overflow horizontally. */
clip: { position: "relative", overflow: "hidden" },
letterRow: { flexDirection: "row" },
outgoing: { position: "absolute" },
outgoingCenter: {
...StyleSheet.absoluteFillObject,
alignItems: "center",
justifyContent: "center",
},
}); import { ActionSwap } from "@/components/ui/action-swap/action-swap";
export function Example() {
return (
<ActionSwap />
);
} 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/action-swap/action-swap.tsxcomponents/ui/action-swap/index.tsUpdate the import paths to match your project setup.
Usage
import { ActionSwapText, ActionSwapIcon, ActionSwapButton, ActionSwap } from "@/components/ui/action-swap/action-swap"; <ActionSwap /> Also exported: ActionSwapText, ActionSwapIcon, ActionSwapButton.
Examples
A shared folder's settings group.
import * as React from "react";
import { View } from "react-native";
import { ActionSwapButton, type ActionSwapButtonVariant, type ActionSwapItem, type ActionSwapMode } from "../action-swap";
import { Icon, type IconName } from "../../icon/icon";
import { Text } from "../../text/text";
type IconColor = "primaryForeground" | "secondaryForeground" | "foreground";
function items(list: [string, string, IconName][], color: IconColor): ActionSwapItem[] {
return list.map(([id, label, icon]) => ({ id, label, icon: <Icon name={icon} size="sm" color={color} /> }));
}
const ROWS: {
mode: ActionSwapMode;
title: string;
sub: string;
variant: ActionSwapButtonVariant;
items: ActionSwapItem[];
}[] = [
{
mode: "roll",
title: "Layout",
sub: "How files appear in this folder",
variant: "secondary",
items: items([["list", "List", "list"], ["grid", "Grid", "grid"], ["gallery", "Gallery", "image"]], "secondaryForeground"),
},
{
mode: "blur",
title: "Sort by",
sub: "Applies to every view",
variant: "outline",
items: items([["date", "Date", "calendar"], ["name", "Name", "type"], ["size", "Size", "archive"]], "foreground"),
},
{
mode: "cascade",
title: "Offline access",
sub: "1.2 GB on this phone",
variant: "primary",
items: items([["off", "Download", "download"], ["on", "Offline", "check"]], "primaryForeground"),
},
];
/** ActionSwapModes — a shared folder's settings group. Each row's
* control swaps its label a different way (lift, in place, lit letter by letter), so
* tapping down the list compares all three in a real context. */
export function ActionSwapModes() {
return (
<View className="w-full gap-4">
<View className="gap-0.5 px-1">
<Text className="text-2xl font-bold tracking-tight text-foreground">Q3 brand review</Text>
<Text className="text-sm text-muted-foreground">24 files · shared with Studio North</Text>
</View>
<View className="w-full rounded-2xl bg-card">
{ROWS.map((row, i) => (
<View key={row.mode} className="flex-row items-center gap-3 pl-4 pr-3">
<View className={`flex-1 py-3.5 ${i > 0 ? "border-t border-border" : ""}`}>
<Text className="text-base font-medium text-foreground">{row.title}</Text>
<Text className="text-sm text-muted-foreground" numberOfLines={1}>
{row.sub}
</Text>
</View>
<ActionSwapButton
items={row.items}
mode={row.mode}
light={row.mode === "cascade"}
variant={row.variant}
size="sm"
className="w-[128px]"
/>
</View>
))}
</View>
</View>
);
} A podcast's episode list with a sort cycler in the section header.
import * as React from "react";
import { View } from "react-native";
import { ActionSwap } from "../action-swap";
import { Text } from "../../text/text";
const EPISODES = [
{ n: 214, title: "The tide-pool economists", date: "Oct 6", mins: 52 },
{ n: 213, title: "Why bridges hum in the wind", date: "Sep 29", mins: 38 },
{ n: 212, title: "A short history of the night shift", date: "Sep 22", mins: 61 },
{ n: 211, title: "Inside a seed vault", date: "Sep 15", mins: 27 },
];
const SORTS = [
{ label: "Newest", icon: "arrow-down" as const },
{ label: "Oldest", icon: "arrow-up" as const },
{ label: "Shortest", icon: "clock" as const },
];
/** ActionSwapSort — a podcast's episode list with a sort cycler in the
* section header. Each tap swaps the label to the next order and the
* list underneath really re-sorts. */
export function ActionSwapSort() {
const [sort, setSort] = React.useState(0);
const rows = React.useMemo(() => {
const list = [...EPISODES];
if (sort === 1) list.reverse();
if (sort === 2) list.sort((a, b) => a.mins - b.mins);
return list;
}, [sort]);
return (
<View className="w-full gap-3">
<View className="flex-row items-end justify-between px-1">
<View className="gap-0.5">
<Text className="text-2xl font-bold tracking-tight text-foreground">Episodes</Text>
<Text className="text-sm text-muted-foreground">Deep Field · 214 episodes</Text>
</View>
<ActionSwap
states={SORTS}
value={sort}
onStateChange={setSort}
accessibilityLabelPrefix="Sorted by"
className="h-9 px-4"
/>
</View>
<View className="w-full rounded-2xl bg-card">
{rows.map((e, i) => (
<View key={e.n} className="flex-row items-center gap-3 pl-4 pr-4">
<View className={`flex-1 flex-row items-center gap-3 py-3 ${i > 0 ? "border-t border-border" : ""}`}>
<View className="flex-1 gap-0.5">
<Text className="text-[15px] font-medium text-foreground" numberOfLines={1}>
{e.title}
</Text>
<Text className="text-sm text-muted-foreground">
#{e.n} · {e.date}
</Text>
</View>
<Text className="text-sm tabular-nums text-muted-foreground">{e.mins} min</Text>
</View>
</View>
))}
</View>
</View>
);
} A smart-home room.
import * as React from "react";
import { View } from "react-native";
import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { LightFall, ease, timing, useTheme } from "@lumioui/core";
import { ActionSwap, ActionSwapText, type ActionSwapProps } from "../action-swap";
import { Icon, type IconName } from "../../icon/icon";
import { Text } from "../../text/text";
/** The climate stage retints like a room changing temperature — a calm crossfade. */
const RETINT = { duration: timing.normal.duration, easing: Easing.bezier(...ease.inOut) };
const MODES: ActionSwapProps["states"] = [{ label: "Heat" }, { label: "Cool" }, { label: "Auto" }];
const MODE_COPY = ["Heating to 22°", "Cooling to 20°", "Holding 20–23°"];
/** One light per mode, crossfaded — the stage is lit from above in the mode's hue. */
function ModeLight({ active, color }: { active: boolean; color: string }) {
const lit = useSharedValue(active ? 1 : 0);
React.useEffect(() => {
lit.value = withTiming(active ? 1 : 0, RETINT);
}, [active, lit]);
const style = useAnimatedStyle(() => ({ opacity: lit.value }));
return (
<Animated.View pointerEvents="none" style={[{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0 }, style]}>
<LightFall color={color} reach={0.9} />
</Animated.View>
);
}
const ROWS: {
icon: IconName;
tile: string;
title: string;
sub: string;
variant: NonNullable<ActionSwapProps["variant"]>;
states: ActionSwapProps["states"];
}[] = [
{
icon: "sun",
tile: "bg-tint-amber",
title: "Ceiling lights",
sub: "3 bulbs · 80%",
variant: "pill",
states: [{ label: "On", accent: "primary" }, { label: "Off" }],
},
{
icon: "grid",
tile: "bg-tint-slate",
title: "Blinds",
sub: "Bay window",
variant: "plain",
states: [{ label: "Open" }, { label: "Closed" }],
},
];
/** ActionSwapStyles — a smart-home room. The climate card is the hero: its
* mode cycles Heat → Cool → Auto and the new word switches on letter by
* letter in place, while the card's light from above retints with the
* mode. Quieter swaps (lights, blinds) sit in the list below. */
export function ActionSwapStyles() {
const { colors } = useTheme();
const [mode, setMode] = React.useState(0);
const hues = [colors.tintOrange, colors.tintTeal, colors.tintGreen];
return (
<View className="w-full gap-3">
<View className="gap-0.5 px-1">
<Text className="text-2xl font-bold tracking-tight text-foreground">Living room</Text>
<Text className="text-sm text-muted-foreground">3 devices · all responding</Text>
</View>
<View className="w-full overflow-hidden rounded-[28px] bg-card">
{hues.map((hue, i) => (
<ModeLight key={i} active={mode === i} color={hue} />
))}
<View className="gap-5 p-5">
<View className="flex-row items-center gap-2">
<Icon name="flame" size="sm" color="mutedForeground" />
<Text className="text-sm font-medium text-muted-foreground">Thermostat</Text>
</View>
<View className="flex-row items-end justify-between">
<View className="gap-1">
<Text className="text-6xl font-semibold tabular-nums tracking-tight text-foreground">21°</Text>
<ActionSwapText value={String(mode)} mode="blur" className="text-[15px] text-muted-foreground">
{MODE_COPY[mode] ?? ""}
</ActionSwapText>
</View>
<ActionSwap
states={MODES}
value={mode}
onStateChange={setMode}
mode="cascade"
light
variant="outline"
accessibilityLabelPrefix="Climate mode:"
className="min-w-[96px] bg-card px-5"
/>
</View>
</View>
</View>
<View className="w-full rounded-2xl bg-card">
{ROWS.map((r, i) => (
<View key={r.title} className="flex-row items-center gap-3 pl-4 pr-3">
<View className={`h-8 w-8 items-center justify-center rounded-lg ${r.tile}`}>
<Icon name={r.icon} size="sm" color="#FFFFFF" />
</View>
<View className={`flex-1 flex-row items-center gap-3 py-3 ${i > 0 ? "border-t border-border" : ""}`}>
<View className="flex-1">
<Text className="text-base font-medium text-foreground">{r.title}</Text>
<Text className="text-sm text-muted-foreground" numberOfLines={1}>
{r.sub}
</Text>
</View>
<ActionSwap
variant={r.variant}
states={r.states}
accessibilityLabelPrefix={`${r.title}:`}
className="min-w-[84px] px-4"
/>
</View>
</View>
))}
</View>
</View>
);
} A running coach's interval screen.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { ActionSwapText } from "../action-swap";
import { Button } from "../../button/button";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const INTERVALS = [
{ name: "Warm-up", time: "5:00", effort: "Easy, conversational" },
{ name: "Sprint", time: "0:45", effort: "All out, 9 of 10" },
{ name: "Recover", time: "1:30", effort: "Walk or slow jog" },
{ name: "Hill repeat", time: "1:00", effort: "Strong, 8 of 10" },
{ name: "Cool-down", time: "5:00", effort: "Easy, then stretch" },
];
/** ActionSwapTextSwap — a running coach's interval screen. The interval
* name is the hero; tap Next and the next block's name switches on
* letter by letter in reading order, while the time and
* effort swap with it. Red accent. */
export function ActionSwapTextSwap() {
const [i, setI] = React.useState(1);
const cur = INTERVALS[i] ?? INTERVALS[0]!;
const next = INTERVALS[(i + 1) % INTERVALS.length]!;
return (
<Accent color="red" className="w-full">
<View className="w-full gap-6 rounded-[20px] bg-card p-5">
<View className="flex-row items-center justify-between">
<Text className="text-sm font-medium text-muted-foreground">
Interval {i + 1} of {INTERVALS.length}
</Text>
<View className="flex-row items-center gap-1.5">
<Icon name="footprints" size="sm" color="mutedForeground" />
<Text className="text-sm tabular-nums text-muted-foreground">3.2 km</Text>
</View>
</View>
<View className="gap-2">
<ActionSwapText value={String(i)} mode="cascade" light className="text-5xl font-bold tracking-tight text-foreground">
{cur.name}
</ActionSwapText>
<View className="flex-row items-center gap-2">
<ActionSwapText value={String(i)} className="text-2xl font-semibold tabular-nums text-primary-text">
{cur.time}
</ActionSwapText>
<ActionSwapText value={String(i)} mode="blur" className="text-base text-muted-foreground">
{cur.effort}
</ActionSwapText>
</View>
</View>
<View className="flex-row items-center gap-3">
<View className="flex-1">
<Text className="text-xs text-muted-foreground">Up next</Text>
<Text className="text-[15px] font-medium text-foreground">
{next.name} · {next.time}
</Text>
</View>
<Button size="lg" onPress={() => setI((v) => (v + 1) % INTERVALS.length)} className="px-6">
Next
</Button>
</View>
</View>
</Accent>
);
} An album header whose view toggle swaps List → Grid → Gallery and the photos below really re-lay out.
import * as React from "react";
import { Image, View } from "react-native";
import { ActionSwap } from "../action-swap";
import { Text } from "../../text/text";
const img = (id: string, w = 300, h = 300) =>
`https://images.unsplash.com/photo-${id}?w=${w}&h=${h}&fit=crop&q=70&auto=format`;
const PHOTOS = [
{ id: "1506905925346-21bda4d32df4", name: "Ridge at first light", when: "Jun 12, 5:48 AM" },
{ id: "1501785888041-af3ef285b470", name: "Lake, west shore", when: "Jun 12, 7:15 PM" },
{ id: "1441974231531-c6227db76b6e", name: "Forest trail", when: "Jun 13, 9:02 AM" },
{ id: "1470071459604-3b5ec3a7fe05", name: "Valley overlook", when: "Jun 14, 11:40 AM" },
{ id: "1507525428034-b723cf961d3e", name: "Beach day off", when: "Jun 15, 3:21 PM" },
{ id: "1611978891391-c7e65da1b749", name: "Boats at the dock", when: "Jun 16, 8:10 AM" },
];
/** ActionSwapViewModes — an album header whose view toggle swaps
* List → Grid → Gallery and the photos below really re-lay out. */
export function ActionSwapViewModes() {
const [mode, setMode] = React.useState(1);
return (
<View className="w-full gap-3">
<View className="flex-row items-end justify-between px-1">
<View className="gap-0.5">
<Text className="text-2xl font-bold tracking-tight text-foreground">Summer on foot</Text>
<Text className="text-sm text-muted-foreground">214 photos · 9 videos</Text>
</View>
<ActionSwap
states={[
{ label: "List", icon: "list" },
{ label: "Grid", icon: "grid" },
{ label: "Gallery", icon: "image" },
]}
value={mode}
onStateChange={setMode}
accessibilityLabelPrefix="View as"
className="h-9 min-w-[112px] px-4"
/>
</View>
{mode === 0 ? (
<View className="w-full rounded-2xl bg-card">
{PHOTOS.slice(0, 4).map((p, i) => (
<View key={p.id} className="flex-row items-center gap-3 pl-3 pr-4">
<Image source={{ uri: img(p.id, 120, 120) }} className="h-12 w-12 rounded-lg" accessibilityIgnoresInvertColors />
<View className={`flex-1 py-3 ${i > 0 ? "border-t border-border" : ""}`}>
<Text className="text-[15px] font-medium text-foreground">{p.name}</Text>
<Text className="text-sm text-muted-foreground">{p.when}</Text>
</View>
</View>
))}
</View>
) : mode === 1 ? (
<View className="w-full gap-1 overflow-hidden rounded-2xl">
{[PHOTOS.slice(0, 3), PHOTOS.slice(3, 6)].map((row, r) => (
<View key={r} className="w-full flex-row gap-1">
{row.map((p) => (
<Image
key={p.id}
source={{ uri: img(p.id) }}
className="flex-1"
style={{ aspectRatio: 1 }}
accessibilityLabel={p.name}
/>
))}
</View>
))}
</View>
) : (
<View className="w-full gap-2">
<Image
source={{ uri: img(PHOTOS[0]!.id, 800, 600) }}
className="w-full rounded-2xl"
style={{ aspectRatio: 4 / 3 }}
accessibilityLabel={PHOTOS[0]!.name}
/>
<View className="px-1">
<Text className="text-[15px] font-medium text-foreground">{PHOTOS[0]!.name}</Text>
<Text className="text-sm text-muted-foreground">{PHOTOS[0]!.when} · 1 of 214</Text>
</View>
</View>
)}
</View>
);
} API reference
ActionSwapText
value* string Slot identity — when this changes, the text animates.
—children* ReactNode — mode ActionSwapMode Swap choreography. "cascade" needs a string child. Default "roll".
—animation LegacySwapAnimation @deprecated Use mode. "fade" maps to "blur".
light boolean Cascade only: each letter of the incoming label switches on in place in reading order (over 390ms). No band is drawn. Default false.
false lightColor string @deprecated No effect: no reading-light band is drawn any more.
—lightOnFill boolean @deprecated No effect: no reading-light band is drawn any more.
—className string Applied to the root View AND the swapped text (text classes are inert on the View, layout classes are inert on the Text).
—ActionSwapIcon
value* string Slot identity — when this changes, the icon animates.
—children* ReactNode — mode ActionSwapMode Swap choreography ("cascade" falls back to roll — icons are single glyphs). Default "roll".
—animation LegacySwapAnimation @deprecated Use mode.
className string — ActionSwapButton
items* ActionSwapItem[] — value string Controlled active item id.
—defaultValue string Initial active item id (uncontrolled). Defaults to the first item.
—onValueChange (value: string, item: ActionSwapItem) …
(value: string, item: ActionSwapItem) => void variant ActionSwapButtonVariant "secondary" size ActionSwapButtonSize "md" mode ActionSwapMode Swap choreography for icon + label slots. Default "roll".
—animation LegacySwapAnimation @deprecated Use mode.
light boolean Cascade only: light the incoming label into place with a reading light (see ActionSwapText). Default false.
false iconOnly boolean Hide the label — icon slot only. Defaults to size === "icon".
size === "icon" cycle boolean Advance to the next item on press. Default true.
true disabled boolean — className string — ActionSwap
states* ActionSwapState[] States to cycle through. Must have at least 2.
—value number Controlled active index.
—defaultValue number Initial active index (uncontrolled). Default 0.
0 onStateChange (index: number) => void — variant "pill" | "plain" | "outline" Visual style. Default "pill".
"pill" mode ActionSwapMode Swap choreography for icon + label. Default "roll".
"roll" light boolean Cascade only: light the incoming label into place with a reading light (see ActionSwapText). Default false.
false accessibilityLabelPrefix string Accessible label prefix. Default "Swap to".
"Swap to" disabled boolean — className string —