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.
Toggle
On/off control that shows as a switch, or as a button whose fill spreads out from where you press. Turning off fades the fill back, and a disabled toggle flickers once when tapped.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { Pressable, View, type GestureResponderEvent, type LayoutChangeEvent, type PressableProps } from "react-native";
import Animated, {
Easing,
interpolateColor,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
} from "react-native-reanimated";
import {
AnimatedPressable,
cn,
createVariant,
ease,
spring,
timing,
useHaptic,
usePressAnimation,
useReducedMotion,
useTheme,
} from "@lumioui/core";
import { Glass } from "../glass";
import { Switch } from "../switch";
export interface ToggleProps extends Omit<PressableProps, "onPress" | "children" | "style"> {
/** Controlled pressed/checked state. Omit with defaultPressed for
* uncontrolled use. */
pressed?: boolean;
/** Initial pressed state (uncontrolled). Default false. */
defaultPressed?: boolean;
/** Called when the user toggles. */
onPressedChange?: (pressed: boolean) => void;
/** Toggle style — "button" renders a pill toggle, "switch" renders a Switch. */
style?: "button" | "switch";
/** Glass pill (button style only). */
glass?: boolean;
/** Haptic feedback. Default "selection". Set false to disable. */
haptic?: "selection" | "light" | false;
/** Icon rendered before the label (button style only). */
icon?: React.ReactNode;
/**
* Icon in its "on" ink (button style only). When given, it crossfades
* over `icon` as the fill covers the pill, so the glyph's ink follows
* the light instead of flipping before it arrives.
*/
iconOn?: React.ReactNode;
/** Extra classes for the label. */
textClassName?: string;
/** Extra classes for the container. */
className?: string;
/** Optional label text. In switch style, renders to the left of the switch. */
children?: React.ReactNode;
/** Disable interaction. A tap flickers and warns. */
disabled?: boolean;
}
const toggleVariants = createVariant({
// Colour rides the ink fill layer below — the container keeps a constant
// secondary bg, and overflow-hidden clips the fill to the pill.
// min-h-[44px] keeps the whole pill inside the 44pt touch-target floor.
base: "flex-row min-h-[44px] items-center justify-center rounded-full px-4 py-2.5 gap-2 bg-secondary overflow-hidden",
variants: {
pressed: {
true: "",
false: "",
},
},
defaultVariants: { pressed: "false" },
});
const toggleTextVariants = createVariant({
// Text colour follows fill coverage (see textStyle) — the variant only
// carries typography so the ink never snaps.
base: "text-base font-medium text-secondary-foreground",
variants: {
pressed: {
true: "",
false: "",
},
},
defaultVariants: { pressed: "false" },
});
/** Disabled flicker — one kick this far, released into spring.shake. */
const FLICKER_KICK = 4;
/** Reduced-motion flicker — an opacity dip instead of travel. */
const FLICKER_DIM = 0.6;
/** The fill ignites from the touch at this share of its full size, so the
* first frame already reads as a lamp switching on, not a growing dot. */
const FILL_SEED = 0.12;
/**
* Toggle — a two-state control.
*
* - `style="switch"` (default): delegates to `Switch`. If `children` is a
* string it renders as the label to the left.
*
* - `style="button"`: a pill that switches on like a lamp — the ink fill
* grows out of the point you pressed (a clipped circle on `spring.swap`
* while it ignites over `timing.fast`), and the label and icon ink follow
* the fill's coverage on the UI thread. Off dims the fill in place in
* 120ms. No overshoot. A tap while disabled flickers once and warns.
*/
export const Toggle = forwardRef<React.ElementRef<typeof Pressable>, ToggleProps>(
function Toggle(
{
pressed,
defaultPressed = false,
onPressedChange,
style: toggleStyle = "switch",
glass = false,
haptic = "selection",
icon,
iconOn,
textClassName,
className,
children,
disabled,
...props
},
ref
) {
// Hooks run before the style branch — `style` can change between
// renders, and an early return would break hook ordering.
const haptics = useHaptic();
const press = usePressAnimation({ pressedScale: 0.94 });
const reduceMotion = useReducedMotion();
const { colors } = useTheme();
// Resolve pressed during render — controlled wins, else internal state.
const isControlled = pressed !== undefined;
const [internalPressed, setInternalPressed] = React.useState(defaultPressed);
const isOn = isControlled ? pressed : internalPressed;
// Fill: lit (opacity) and reach (circle scale, 0–1), grown from origin.
const lit = useSharedValue(isOn ? 1 : 0);
const reach = useSharedValue(isOn ? 1 : 0);
const kick = useSharedValue(0);
const dip = useSharedValue(1);
const [box, setBox] = React.useState({ w: 0, h: 0 });
// Where the light starts — the press point, else the pill's centre.
const [seed, setSeed] = React.useState<{ x: number; y: number } | null>(null);
const firstRender = React.useRef(true);
React.useEffect(() => {
if (firstRender.current) {
firstRender.current = false;
return;
}
if (isOn) {
lit.value = withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) });
if (reduceMotion) reach.value = 1;
else {
reach.value = FILL_SEED;
reach.value = withSpring(1, spring.swap);
}
} else {
// Off dims in place — the circle keeps its size while the light goes.
lit.value = withTiming(0, { ...timing.recede, easing: Easing.bezier(...ease.in) });
}
}, [isOn, lit, reach, reduceMotion]);
// Circle big enough to cover the pill from the seed point.
const sx = seed?.x ?? box.w / 2;
const sy = seed?.y ?? box.h / 2;
const radius = Math.hypot(Math.max(sx, box.w - sx), Math.max(sy, box.h - sy));
const diameter = Math.max(1, radius * 2);
const containerAnim = useAnimatedStyle(() => ({
opacity: dip.value,
transform: [{ translateX: kick.value }, { scale: press.scale.value }],
}));
const fillStyle = useAnimatedStyle(() => ({
opacity: lit.value,
transform: [{ scale: reach.value }],
}));
// Coverage — how much of the pill the light owns right now.
const textStyle = useAnimatedStyle(() => ({
color: interpolateColor(
lit.value * reach.value,
[0, 1],
[colors.secondaryForeground, colors.primaryForeground]
),
}));
const iconOffStyle = useAnimatedStyle(() => ({ opacity: 1 - lit.value * reach.value }));
const iconOnStyle = useAnimatedStyle(() => ({ opacity: lit.value * reach.value }));
// --- Switch style (default) ---
if (toggleStyle === "switch") {
return (
<Switch
ref={ref}
checked={isOn}
onCheckedChange={(next) => {
if (!isControlled) setInternalPressed(next);
onPressedChange?.(next);
}}
disabled={disabled}
haptic={haptic}
label={typeof children === "string" ? children : undefined}
className={className}
{...props}
/>
);
}
// --- Button style ---
const pressedKey = isOn ? "true" : ("false" as const);
const flicker = () => {
haptics.warning();
if (reduceMotion) {
dip.value = FLICKER_DIM;
dip.value = withTiming(1, timing.normal);
return;
}
kick.value = FLICKER_KICK;
kick.value = withSpring(0, spring.shake);
};
const handlePress = () => {
if (disabled) {
flicker();
return;
}
if (haptic) haptics[haptic === "selection" ? "selection" : "light"]();
if (!isControlled) setInternalPressed(!isOn);
onPressedChange?.(!isOn);
};
const handlePressIn = (e: GestureResponderEvent) => {
// Seed only while off: a lit pill is fully covered from any point, so
// moving the seed then is invisible.
if (!isOn) setSeed({ x: e.nativeEvent.locationX, y: e.nativeEvent.locationY });
if (!disabled) press.onPressIn();
};
const handlePressOut = () => {
press.onPressOut();
};
const onLayout = (e: LayoutChangeEvent) => {
const { width, height } = e.nativeEvent.layout;
if (width !== box.w || height !== box.h) setBox({ w: width, h: height });
};
const hasOnIcon = icon != null && iconOn != null;
return (
<AnimatedPressable
ref={ref}
// Deliberately not `disabled` — a tap on a disabled toggle must still
// land so it can flicker. a11y reports disabled below.
onPress={handlePress}
onPressIn={handlePressIn}
onPressOut={handlePressOut}
onLayout={onLayout}
style={containerAnim}
className={cn(
toggleVariants({ pressed: pressedKey }),
glass && "bg-transparent",
disabled && "opacity-50",
className
)}
accessibilityRole="button"
accessibilityState={{ selected: isOn, disabled: disabled ?? false }}
// accessibilityState isn't forwarded to the DOM on web — mirror it.
// role=button takes aria-pressed; checkbox/radio callers (e.g.
// ToggleGroupItem) take aria-checked instead.
aria-pressed={
props.accessibilityRole == null || props.accessibilityRole === "button"
? isOn
: undefined
}
aria-checked={
props.accessibilityRole === "checkbox" || props.accessibilityRole === "radio"
? isOn
: undefined
}
aria-disabled={disabled ?? false}
accessibilityLabel={typeof children === "string" ? children : props.accessibilityLabel}
hitSlop={6}
{...props}
>
{glass ? (
<Glass
effect="regular"
sheen={0.5}
className="absolute inset-0 rounded-full"
pointerEvents="none"
/>
) : null}
{/* Ink fill — a circle of light grown from the press point. */}
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
left: sx - diameter / 2,
top: sy - diameter / 2,
width: diameter,
height: diameter,
borderRadius: diameter / 2,
backgroundColor: colors.primary,
},
fillStyle,
]}
/>
{/* Content takes no touches, so press points are always measured
against the pill itself. */}
<View pointerEvents="none" className="flex-row items-center justify-center gap-2">
{hasOnIcon ? (
<View>
<Animated.View style={iconOffStyle}>{icon}</Animated.View>
<Animated.View style={[{ position: "absolute", top: 0, left: 0 }, iconOnStyle]}>{iconOn}</Animated.View>
</View>
) : (
icon
)}
{typeof children === "string" ? (
<Animated.Text
style={textStyle}
className={cn(toggleTextVariants({ pressed: pressedKey }), textClassName)}
>
{children}
</Animated.Text>
) : (
children
)}
</View>
</AnimatedPressable>
);
}
);
Toggle.displayName = "Toggle";
import { Toggle } from "@/components/ui/toggle/toggle";
export function Example() {
return (
<Toggle />
);
} Installation
Usage
import { Toggle } from "@/components/ui/toggle/toggle"; <Toggle /> Examples
Button-style toggles as the Shuffle / Repeat pair above a music queue.
import * as React from "react";
import { Image, View } from "react-native";
import Animated, { LinearTransition } from "react-native-reanimated";
import { Accent, ROW_STAGGER, spring, useReducedMotion } from "@lumioui/core";
import { Toggle } from "../toggle";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
const A = { title: "Cold Little Harbour", artist: "Michael Kiwele", time: "9:52" };
const B = { title: "Night Swim", artist: "Frank Oyelaran", time: "5:07" };
const C = { title: "Motion Blur", artist: "Phoebe Brennan", time: "3:49" };
const D = { title: "Two Weeks Out", artist: "Grizzly Coast", time: "4:03" };
const QUEUE = [A, B, C, D];
const SHUFFLED = [C, A, D, B];
/** ToggleButton — button-style toggles as the Shuffle / Repeat pair above a
* music queue. Each pill switches on from where it was pressed. Shuffle
* reorders the queue in place — rows move on spring.layout, 40ms apart;
* Repeat changes the footer line. Pink for media. */
export function ToggleButton() {
const [shuffle, setShuffle] = React.useState(false);
const [repeat, setRepeat] = React.useState(true);
const reduce = useReducedMotion();
const list = shuffle ? SHUFFLED : QUEUE;
const move = (i: number) =>
reduce
? undefined
: LinearTransition.springify()
.stiffness(spring.layout.stiffness)
.damping(spring.layout.damping)
.mass(spring.layout.mass)
.delay(i * ROW_STAGGER);
return (
<Accent color="pink" className="w-full">
<View className="w-full gap-4 rounded-3xl bg-card p-5">
<View className="flex-row items-center gap-3">
<Image
source={{ uri: "https://images.unsplash.com/photo-1458560871784-56d23406c091?w=200&h=200&fit=crop&q=70&auto=format" }}
className="h-14 w-14 rounded-xl bg-muted"
accessibilityIgnoresInvertColors
/>
<View className="flex-1">
<Text className="text-[17px] font-semibold">Late Drive</Text>
<Text variant="muted">Playlist · 24 songs, 1 hr 38 min</Text>
</View>
</View>
<View className="w-full flex-row gap-2">
<Toggle
style="button"
pressed={shuffle}
onPressedChange={setShuffle}
className="flex-1"
icon={<Icon name="shuffle" size="sm" color="foreground" />}
iconOn={<Icon name="shuffle" size="sm" color="primaryForeground" />}
>
Shuffle
</Toggle>
<Toggle
style="button"
pressed={repeat}
onPressedChange={setRepeat}
className="flex-1"
icon={<Icon name="repeat" size="sm" color="foreground" />}
iconOn={<Icon name="repeat" size="sm" color="primaryForeground" />}
>
Repeat
</Toggle>
</View>
<View>
<Text className="pb-1 text-[13px] text-muted-foreground">Up next</Text>
{list.map((s, i) => (
<Animated.View
key={s.title}
layout={move(i)}
className="flex-row items-center gap-3 border-t border-border py-3"
>
<View className="flex-1">
<Text className="text-[15px] font-medium" numberOfLines={1}>{s.title}</Text>
<Text variant="muted" numberOfLines={1}>{s.artist}</Text>
</View>
<Text className="text-sm tabular-nums text-muted-foreground">{s.time}</Text>
</Animated.View>
))}
<Text className="pt-2 text-xs text-muted-foreground">
{repeat ? "Playlist repeats after the last song" : "Playback stops after the last song"}
</Text>
</View>
</View>
</Accent>
);
} Switch-style toggles in a travel eSIM app's line settings.
import * as React from "react";
import { View } from "react-native";
import { Accent } from "@lumioui/core";
import { Toggle } from "../toggle";
import { Form } from "../../form/form";
import { Icon, type IconName } from "../../icon/icon";
import { Text } from "../../text/text";
function Tile({ name, className }: { name: IconName; className: string }) {
return (
<View className={`h-8 w-8 items-center justify-center rounded-lg ${className}`}>
<Icon name={name} size="sm" color="#FFFFFF" />
</View>
);
}
/** ToggleConnectivity — switch-style toggles in a travel eSIM app's line
* settings. Roaming gates the rows below it; the usage meter on top shows
* what the plan is for. Teal for travel. */
export function ToggleConnectivity() {
const [roaming, setRoaming] = React.useState(true);
const [lowData, setLowData] = React.useState(false);
const [hotspot, setHotspot] = React.useState(false);
return (
<Accent color="teal" className="w-full">
<View className="w-full gap-6">
<View className="w-full gap-3 rounded-2xl bg-card p-4">
<View className="flex-row items-center gap-2">
<Icon name="globe" size="sm" color="primary" />
<Text className="flex-1 text-[17px] font-semibold">Japan · 10 GB</Text>
<Text variant="muted">12 days left</Text>
</View>
<View className="h-2 w-full overflow-hidden rounded-full bg-muted">
<View className="h-full w-5/12 rounded-full bg-primary" />
</View>
<Text variant="muted" className="tabular-nums">4.2 GB of 10 GB used</Text>
</View>
<View className="gap-2">
<View className="overflow-hidden rounded-2xl bg-card">
<Form.Row
label="Data roaming"
description={roaming ? "Using Travelink on Sakura Mobile" : "Off · no data abroad"}
leading={<Tile name="globe" className="bg-tint-teal" />}
trailing={<Toggle pressed={roaming} onPressedChange={setRoaming} accessibilityLabel="Data roaming" />}
/>
<Form.Separator />
<Form.Row
label="Low Data Mode"
leading={<Tile name="droplet" className="bg-tint-amber" />}
trailing={
<Toggle pressed={lowData && roaming} onPressedChange={setLowData} disabled={!roaming} accessibilityLabel="Low Data Mode" />
}
/>
<Form.Separator />
<Form.Row
label="Personal Hotspot"
leading={<Tile name="wifi" className="bg-tint-green" />}
trailing={
<Toggle pressed={hotspot && roaming} onPressedChange={setHotspot} disabled={!roaming} accessibilityLabel="Personal Hotspot" />
}
/>
</View>
<Text variant="muted" className="px-4">
Low Data Mode pauses photo backups and app updates until you're on Wi-Fi.
</Text>
</View>
</View>
</Accent>
);
} Glass pill toggles as camera viewfinder controls floating over the live frame.
import * as React from "react";
import { Image, StyleSheet, View } from "react-native";
import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import { LightPool, ease, tempo, timing } from "@lumioui/core";
import { Toggle } from "../toggle";
import { Icon, type IconName } from "../../icon/icon";
import { Text } from "../../text/text";
const PHOTO =
"https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=800&h=1000&fit=crop&q=70&auto=format";
/** Night mode lowers the live frame to this brightness — the scene dims as
* the sensor settles into a long exposure. */
const NIGHT_FRAME = 0.85;
/** The flash fires one pool of light from the top edge, held this long. */
const FLASH_HOLD = tempo.roll;
/** ToggleGlass — glass pill toggles as camera viewfinder controls floating
* over the live frame. Each pill switches on from where it was pressed, and
* the frame answers: Night dims the scene, Flash fires one pool of light
* down from the top edge. The mode line reports what the next shot uses. */
export function ToggleGlass() {
const [flash, setFlash] = React.useState(false);
const [night, setNight] = React.useState(true);
const [live, setLive] = React.useState(true);
const [firing, setFiring] = React.useState(false);
const timer = React.useRef<ReturnType<typeof setTimeout> | null>(null);
React.useEffect(() => () => {
if (timer.current) clearTimeout(timer.current);
}, []);
const frame = useSharedValue(night ? NIGHT_FRAME : 1);
React.useEffect(() => {
frame.value = withTiming(night ? NIGHT_FRAME : 1, { ...timing.slow, easing: Easing.bezier(...ease.inOut) });
}, [night, frame]);
const frameStyle = useAnimatedStyle(() => ({ opacity: frame.value }));
const onFlash = (on: boolean) => {
setFlash(on);
if (!on) return;
setFiring(true);
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => setFiring(false), FLASH_HOLD);
};
const mode = [night && "Night 3s", live && "Live", flash && "Flash"].filter(Boolean).join(" · ") || "Photo";
const icons = (name: IconName) => ({
icon: <Icon name={name} size="sm" color="foreground" />,
iconOn: <Icon name={name} size="sm" color="primaryForeground" />,
});
return (
<View className="relative h-[460px] w-full overflow-hidden rounded-3xl bg-black">
<Animated.View style={[StyleSheet.absoluteFill, frameStyle]}>
<Image
source={{ uri: PHOTO }}
style={StyleSheet.absoluteFill}
resizeMode="cover"
accessibilityIgnoresInvertColors
/>
</Animated.View>
<LightPool on={firing} color="#FFFFFF" size={520} strength={0.5} className="absolute -top-64 self-center" />
<View className="absolute inset-x-4 top-4 flex-row gap-2">
<Toggle glass style="button" pressed={flash} onPressedChange={onFlash} {...icons("zap")}>
Flash
</Toggle>
<Toggle glass style="button" pressed={night} onPressedChange={setNight} {...icons("moon")}>
Night
</Toggle>
<Toggle glass style="button" pressed={live} onPressedChange={setLive} {...icons("film")}>
Live
</Toggle>
</View>
<View className="absolute inset-x-0 bottom-8 items-center gap-4">
<View className="rounded-full bg-black/50 px-3 py-1" accessibilityLiveRegion="polite">
<Text className="text-[13px] font-medium text-white">{mode}</Text>
</View>
<View className="h-[72px] w-[72px] items-center justify-center rounded-full border-4 border-white">
<View className="h-14 w-14 rounded-full bg-white" />
</View>
</View>
</View>
);
} API reference
pressed boolean Controlled pressed/checked state. Omit with defaultPressed for uncontrolled use.
—defaultPressed boolean Initial pressed state (uncontrolled). Default false.
false onPressedChange (pressed: boolean) => void Called when the user toggles.
—style "button" | "switch" Toggle style — "button" renders a pill toggle, "switch" renders a Switch.
"switch" glass boolean Glass pill (button style only).
false haptic "selection" | "light" | false Haptic feedback. Default "selection". Set false to disable.
"selection" icon React.ReactNode Icon rendered before the label (button style only).
—iconOn React.ReactNode Icon in its "on" ink (button style only). When given, it crossfades over icon as the fill covers the pill, so the glyph's ink follows the light instead of flipping before it arrives.
textClassName string Extra classes for the label.
—className string Extra classes for the container.
—children React.ReactNode Optional label text. In switch style, renders to the left of the switch.
—disabled boolean Disable interaction. A tap flickers and warns.
—