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.
Segmented Control
Segmented control for switching between a few options, with text segments that can carry icons. The highlight slides smoothly to your pick and can be dragged, and a glass style suits photos.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { PanResponder, View, type ViewProps } from "react-native";
import Animated, {
useAnimatedReaction,
useSharedValue,
useAnimatedStyle,
withSpring,
withTiming,
interpolateColor,
type SharedValue,
} from "react-native-reanimated";
import { cn, useHaptic, spring, timing, useReducedMotion, useTheme, usePressAnimation, AnimatedPressable, LitEdge } from "@lumioui/core";
import { Glass } from "../glass";
export interface SegmentedControlOption {
/** Unique value for this segment. */
value: string;
/** Display label. */
label: string;
/** Optional icon rendered before the label. */
icon?: React.ReactNode;
}
export interface SegmentedControlProps extends ViewProps {
/** Options to display. Can be string[] or SegmentedControlOption[]. */
options: string[] | SegmentedControlOption[];
/** Currently selected value. */
value: string;
onValueChange: (value: string) => void;
/** Disable all segments. Default false. */
disabled?: boolean;
/** Extra classes for the container. */
className?: string;
/** Haptic feedback on segment change. Default "selection". */
haptic?: "selection" | "light" | false;
/** Density — "sm" compresses rows for toolbars and card headers. */
size?: "sm" | "md";
/** Glass treatment — the track becomes a glass capsule and the
* gliding indicator a raised glass pill that refracts what's beneath. */
glass?: boolean;
/** Let the finger drag the thumb: it tracks 1:1, ticks the haptic as it
* crosses each segment and snaps to the nearest one on release. Default false. */
draggable?: boolean;
/** Mirrors the thumb's position (0 to n-1, fractional while gliding) on the
* UI thread, so the content below can follow the glide. */
progress?: SharedValue<number>;
}
function normalizeOptions(options: string[] | SegmentedControlOption[]): SegmentedControlOption[] {
return options.map((o) =>
typeof o === "string" ? { value: o, label: o } : o
);
}
/** The container's p-1 padding (4px each side) — the indicator glides
* inside the padded track, so segment width excludes it. */
const TRACK_PAD = 4;
/** Dark-mode thumb — the selected segment lifts ABOVE the track (a
* lighter translucent white). No semantic token sits lighter than `muted`
* in dark, and `bg-background` reads as a hole punched into the track. */
const DARK_THUMB = "rgba(255,255,255,0.14)";
/** The light trail stretches at most this far behind a travelling thumb. */
const TRAIL = 10;
/** Peak brightness of the trail mid-glide; it settles to nothing on landing. */
const TRAIL_LIGHT = 0.45;
/** A drag claims the gesture only after this much sideways travel, so taps stay taps. */
const DRAG_SLOP = 6;
/**
* SegmentedControl — segmented picker with a gliding indicator.
*
* A compact control for choosing between 2-5 mutually exclusive options.
* The thumb is a light: it glides on spring.indicator with a faint trail
* stretching behind it that settles as it lands, and each label's ink
* follows the thumb's coverage on the UI thread. With `draggable` the finger
* moves the thumb 1:1; `progress` hands its position to the content below.
*/
export const SegmentedControl = forwardRef<React.ElementRef<typeof View>, SegmentedControlProps>(
function SegmentedControl(
{
options: rawOptions,
value,
onValueChange,
disabled,
className,
haptic = "selection",
size = "md",
glass = false,
draggable = false,
progress,
...props
},
ref
) {
const reduceMotion = useReducedMotion();
const haptics = useHaptic();
const { scheme } = useTheme();
const [w, setW] = React.useState(0);
const options = React.useMemo(() => normalizeOptions(rawOptions), [rawOptions]);
const count = Math.max(options.length, 1);
// Start on the selected segment — the first real layout shouldn't
// glide in from segment 0.
const initialIndex = React.useRef(
Math.max(0, options.findIndex((o) => o.value === value))
).current;
const index = useSharedValue(initialIndex);
/** Where the thumb is headed — the trail reads its distance from here. */
const target = useSharedValue(initialIndex);
/** Indicator entrance — fades in once the track has measured itself. */
const indicatorVis = useSharedValue(0);
React.useEffect(() => {
const i = options.findIndex((o) => o.value === value);
if (i >= 0) {
target.value = i;
// Reduced motion: set directly — the indicator jumps, no glide.
if (reduceMotion) index.value = i;
else index.value = withSpring(i, spring.indicator);
}
}, [value, index, target, options, reduceMotion]);
useAnimatedReaction(
() => index.value,
(now) => {
if (progress) progress.value = now;
},
[progress]
);
// Segment width is static per layout — only the transform animates.
const segW = Math.max(0, (w - TRACK_PAD * 2) / count);
const indicatorStyle = useAnimatedStyle(() => ({
// `left: TRACK_PAD` on the base style supplies the leading inset;
// translateX only walks between padded segment slots.
transform: [{ translateX: index.value * segW }],
opacity: indicatorVis.value,
}), [segW]);
// Light trail — lags behind a travelling thumb by its distance from the
// target, so it stretches mid-glide and settles to nothing on landing.
const trailStyle = useAnimatedStyle(() => {
const away = Math.max(-1, Math.min(1, index.value - target.value));
return {
opacity: indicatorVis.value * Math.abs(away) * TRAIL_LIGHT,
transform: [{ translateX: index.value * segW + away * TRAIL }],
};
}, [segW]);
// Drag: the finger writes the thumb directly; React hears only the
// crossings (haptic tick) and the release (snap + onValueChange).
const dragFrom = React.useRef(0);
const dragSlot = React.useRef(0);
const live = React.useRef({ value, options, onValueChange, segW, count, disabled, haptic });
React.useEffect(() => {
live.current = { value, options, onValueChange, segW, count, disabled, haptic };
});
const pan = React.useMemo(
() =>
PanResponder.create({
onMoveShouldSetPanResponderCapture: (_, g) =>
!live.current.disabled && Math.abs(g.dx) > DRAG_SLOP && Math.abs(g.dx) > Math.abs(g.dy),
onPanResponderGrant: () => {
const i = Math.max(0, live.current.options.findIndex((o) => o.value === live.current.value));
dragFrom.current = i;
dragSlot.current = i;
},
onPanResponderMove: (_, g) => {
const { segW: sw, count: n, haptic: h } = live.current;
if (sw <= 0) return;
const next = Math.max(0, Math.min(n - 1, dragFrom.current + g.dx / sw));
index.value = next;
target.value = next;
const slot = Math.round(next);
if (slot !== dragSlot.current) {
dragSlot.current = slot;
if (h) haptics[h === "selection" ? "selection" : "light"]();
}
},
onPanResponderRelease: () => {
const { options: opts, value: v, onValueChange: change } = live.current;
const slot = dragSlot.current;
target.value = slot;
index.value = withSpring(slot, spring.indicator);
const picked = opts[slot];
if (picked && picked.value !== v) change(picked.value);
},
onPanResponderTerminate: () => {
const i = Math.max(0, live.current.options.findIndex((o) => o.value === live.current.value));
target.value = i;
index.value = withSpring(i, spring.indicator);
},
}),
[haptics, index, target]
);
const track = (
<View
ref={ref}
className={cn(
// Capsule track and capsule thumb.
"w-full flex-row rounded-full p-1",
!glass && "bg-muted",
disabled && "opacity-50",
!glass && className
)}
onLayout={(e) => {
setW(e.nativeEvent.layout.width);
// Reveal the indicator only once the track knows its width —
// before that it would sit at a wrong zero-width slot.
if (indicatorVis.value === 0) {
indicatorVis.value = reduceMotion ? 1 : withTiming(1, timing.fast);
}
}}
accessibilityRole="tablist"
{...(draggable ? pan.panHandlers : null)}
{...props}
>
{/* Light trail behind the travelling thumb (flat track only). */}
{glass ? null : (
<Animated.View
pointerEvents="none"
style={[
{
position: "absolute",
top: TRACK_PAD,
bottom: TRACK_PAD,
left: TRACK_PAD,
width: segW,
borderRadius: 999,
...(scheme === "dark" ? { backgroundColor: DARK_THUMB } : null),
},
trailStyle,
]}
className="bg-card"
/>
)}
{/* Gliding indicator — a whisper of shadow so it floats above the
track; raw black is intentional (no shadow token).
In glass mode the pill is Lumio glass instead of a flat card. */}
<Animated.View
style={[
{
position: "absolute",
top: TRACK_PAD,
bottom: TRACK_PAD,
left: TRACK_PAD,
width: segW,
borderRadius: 999,
...(glass
? {}
: {
...(scheme === "dark" ? { backgroundColor: DARK_THUMB } : null),
shadowColor: "#000",
shadowOpacity: 0.08,
shadowRadius: 2,
shadowOffset: { width: 0, height: 1 },
elevation: 1,
}),
},
indicatorStyle,
]}
className={glass ? undefined : "bg-card"}
>
{glass ? (
<Glass
effect="regular"
sheen={0.5}
bend={0.3}
className="absolute inset-0 rounded-full"
/>
) : (
<LitEdge tone="surface" radius={999} />
)}
</Animated.View>
{options.map((option, i) => {
const active = option.value === value;
return (
<Segment
key={option.value}
option={option}
slot={i}
index={index}
active={active}
disabled={disabled}
haptic={haptic}
size={size}
glass={glass}
onSelect={onValueChange}
/>
);
})}
</View>
);
if (!glass) return track;
return (
<Glass effect="clear" className={cn("w-full rounded-full", className)}>
{track}
</Glass>
);
}
);
/** One segment — own component so each can hold a usePressAnimation hook.
* The press dip lives on the segment itself, so the whole padded target
* (icon + label) responds, not just the label. */
function Segment({
option,
slot,
index,
active,
disabled,
haptic,
size = "md",
glass = false,
onSelect,
}: {
option: SegmentedControlOption;
slot: number;
index: SharedValue<number>;
active: boolean;
disabled?: boolean;
haptic: "selection" | "light" | false;
size?: "sm" | "md";
glass?: boolean;
onSelect: (value: string) => void;
}) {
const haptics = useHaptic();
// Opacity dip survives reduced motion (scale is auto-dropped) — keeps
// press feedback for everyone, mirroring the old label-only dip.
const press = usePressAnimation({ pressedScale: 0.96, pressedOpacity: 0.7 });
return (
<AnimatedPressable
disabled={disabled}
onPress={() => {
if (disabled) return;
if (haptic) haptics[haptic === "selection" ? "selection" : "light"]();
onSelect(option.value);
}}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
style={press.animatedStyle}
className={cn(
"flex-1 items-center justify-center rounded-full",
// sm 36 / md 44 overall (segment + the track's 4pt padding).
size === "sm" ? "min-h-7 px-2" : "min-h-9 px-3"
)}
hitSlop={2}
accessibilityRole="tab"
accessibilityState={{ selected: active, disabled }}
// accessibilityState isn't forwarded to the DOM on web — mirror it.
aria-selected={active}
aria-disabled={disabled}
accessibilityLabel={option.label}
>
<SegmentLabel option={option} slot={slot} index={index} glass={glass} />
</AnimatedPressable>
);
}
// Label ink rides the gliding thumb (an inverted label is clipped label to the
// moving pill): coverage = 1 − distance between the thumb and this slot, so a
// label darkens as the thumb arrives instead of flipping on tap.
const SegmentLabel = React.memo(function SegmentLabel({
option,
slot,
index,
glass,
}: {
option: SegmentedControlOption;
slot: number;
index: SharedValue<number>;
glass: boolean;
}) {
const { colors } = useTheme();
// The selected label is ink on the raised thumb — selection is
// carried by the thumb, never by an accent-tinted label. Unselected
// labels stay readable (muted on the flat track, full foreground over a
// photo where grey would vanish).
const activeColor = colors.foreground;
const inactiveColor = glass ? colors.foreground : colors.mutedForeground;
const textStyle = useAnimatedStyle(() => {
const coverage = Math.max(0, 1 - Math.abs(index.value - slot));
return { color: interpolateColor(coverage, [0, 1], [inactiveColor, activeColor]) };
}, [slot, inactiveColor, activeColor]);
const activeIconStyle = useAnimatedStyle(() => ({
opacity: Math.max(0, 1 - Math.abs(index.value - slot)),
}), [slot]);
// Option icons are ReactNodes: stack the consumer's glyph under a
// foreground copy (cloneElement) and crossfade on the same coverage.
const icon = React.isValidElement(option.icon) ? (
<View>
{option.icon}
<Animated.View style={activeIconStyle} pointerEvents="none" className="absolute inset-0">
{React.cloneElement(option.icon as React.ReactElement<{ color?: string }>, { color: "foreground" })}
</Animated.View>
</View>
) : (
option.icon
);
return (
// Icon sits beside the label so icon
// segments keep the same 44pt control height as text-only ones.
<View style={{ flexDirection: "row", alignItems: "center", justifyContent: "center" }} className="gap-1.5">
{icon}
<Animated.Text style={textStyle} className="text-sm font-semibold leading-tight" numberOfLines={1}>
{option.label}
</Animated.Text>
</View>
);
});
SegmentedControl.displayName = "SegmentedControl"; import { SegmentedControl } from "@/components/ui/segmented-control/segmented-control";
export function Example() {
return (
<SegmentedControl />
);
} 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/segmented-control/segmented-control.tsxcomponents/ui/segmented-control/index.tsUpdate the import paths to match your project setup.
Usage
import { SegmentedControl } from "@/components/ui/segmented-control/segmented-control"; <SegmentedControl /> Examples
A photo-library switcher: a glass capsule floating over the library it controls.
import * as React from "react";
import { View } from "react-native";
import { SegmentedControl } from "../segmented-control";
import { Image } from "../../image/image";
import { Text } from "../../text/text";
const U = (id: string, s = 400) => `https://images.unsplash.com/${id}?w=${s}&h=${s}&fit=crop&q=70&auto=format`;
const LIB = [
"photo-1506905925346-21bda4d32df4",
"photo-1519681393784-d120267933ba",
"photo-1470071459604-3b5ec3a7fe05",
"photo-1500530855697-b586d89ba3ee",
"photo-1483412033650-1015ddeb83d1",
"photo-1500382017468-9049fed747ef",
"photo-1488646953014-85cb44e25828",
"photo-1446776811953-b23d57bd21aa",
"photo-1513735492246-483525079686",
"photo-1489749798305-4fea3ae63d43",
"photo-1493976040374-85c8e12f0c0e",
"photo-1506126613408-eca07ce68773",
];
const COLS: Record<string, number> = { Years: 1, Months: 2, All: 3 };
/** SegmentedGlass — a photo-library switcher: a glass capsule floating
* over the library it controls. Years / Months / All changes the grid
* density beneath, so the glass always sits over moving content. */
export function SegmentedGlass() {
const [value, setValue] = React.useState("All");
const cols = COLS[value] ?? 3;
const shots = value === "Years" ? LIB.slice(0, 2) : value === "Months" ? LIB.slice(0, 6) : LIB;
const w = cols === 1 ? "100%" : cols === 2 ? "49.6%" : "32.9%";
return (
<View className="relative h-[520px] w-full overflow-hidden rounded-3xl bg-background">
<View className="flex-row flex-wrap gap-0.5">
{shots.map((id, i) => (
<View key={`${value}-${id}`} style={{ width: w }} className={cols === 1 ? "h-64" : "aspect-square"}>
<Image source={{ uri: U(id, cols === 1 ? 800 : 400) }} className="h-full w-full" alt={`Photo ${i + 1}`} />
{cols === 1 ? (
<Text className="absolute left-4 top-3 text-3xl font-bold text-white">{i === 0 ? "2025" : "2024"}</Text>
) : null}
</View>
))}
</View>
<View className="absolute bottom-5 left-5 right-5">
<SegmentedControl glass options={["Years", "Months", "All"]} value={value} onValueChange={setValue} />
</View>
</View>
);
} Icon + label segments choosing a travel mode in a maps route card.
import * as React from "react";
import { View } from "react-native";
import { Accent, SwitchOn, rowDelay } from "@lumioui/core";
import { SegmentedControl } from "../segmented-control";
import { Icon } from "../../icon/icon";
import { Text } from "../../text/text";
type Route = { eta: string; arrive: string; via: string; note: string };
const ROUTES: Record<string, Route[]> = {
drive: [
{ eta: "18 min", arrive: "Arrive 9:04", via: "via I-280 N", note: "Fastest · light traffic" },
{ eta: "23 min", arrive: "Arrive 9:09", via: "via Alemany Blvd", note: "Avoids tolls" },
],
transit: [
{ eta: "34 min", arrive: "Arrive 9:20", via: "J Church → 24th St BART", note: "Leaves in 4 min · $2.50" },
{ eta: "41 min", arrive: "Arrive 9:27", via: "Bus 49", note: "Every 8 min · $2.50" },
],
walk: [
{ eta: "1 h 12 min", arrive: "Arrive 9:58", via: "via Valencia St", note: "5.6 km · mostly flat" },
],
};
/** SegmentedObjects — icon + label segments choosing a travel mode in a
* maps route card. The routes below swap with the segment, teal for
* travel. */
export function SegmentedObjects() {
const [mode, setMode] = React.useState("drive");
const routes = ROUTES[mode] ?? ROUTES.drive!;
return (
<Accent color="teal" className="w-full">
<View className="w-full gap-4 rounded-3xl bg-card p-5">
<View className="gap-1">
<Text className="text-[17px] font-semibold">Ferry Building</Text>
<Text className="text-sm text-muted-foreground">1 Ferry Plaza, San Francisco</Text>
</View>
<SegmentedControl
options={[
{ value: "drive", label: "Drive", icon: <Icon name="car" size="sm" color="mutedForeground" /> },
{ value: "transit", label: "Transit", icon: <Icon name="tram-front" size="sm" color="mutedForeground" /> },
{ value: "walk", label: "Walk", icon: <Icon name="footprints" size="sm" color="mutedForeground" /> },
]}
value={mode}
onValueChange={setMode}
/>
<View>
{routes.map((r, i) => (
// New routes switch on in place, 40ms apart, when the mode changes.
<SwitchOn
key={`${mode}-${r.via}`}
delay={rowDelay(i)}
className={`flex-row items-center gap-3 py-3 ${i > 0 ? "border-t border-border" : ""}`}
>
<View className="flex-1 gap-0.5">
<View className="flex-row items-baseline gap-2">
<Text className={`text-xl font-semibold tabular-nums ${i === 0 ? "text-primary-text" : ""}`}>{r.eta}</Text>
<Text className="text-sm text-muted-foreground">{r.arrive}</Text>
</View>
<Text className="text-[15px]">{r.via}</Text>
<Text className="text-[13px] text-muted-foreground">{r.note}</Text>
</View>
{i === 0 ? (
<View className="h-11 min-w-16 items-center justify-center rounded-full bg-primary px-4">
<Text className="text-[15px] font-semibold text-primary-foreground">Go</Text>
</View>
) : null}
</SwitchOn>
))}
</View>
</View>
</Accent>
);
} The chart-header habitat: Day / Week / Month on a screen-time chart.
import * as React from "react";
import { View } from "react-native";
import Animated, {
Easing,
useAnimatedStyle,
useSharedValue,
withDelay,
withSpring,
withTiming,
} from "react-native-reanimated";
import { ease, rowDelay, spring, timing, useReducedMotion } from "@lumioui/core";
import { SegmentedControl } from "../segmented-control";
import { ActionSwapText } from "../../action-swap/action-swap";
import { Text } from "../../text/text";
type Period = { total: string; caption: string; bars: number[]; ticks: string[]; delta: string };
const DATA: Record<string, Period> = {
Day: {
total: "3h 41m",
caption: "Today",
bars: [2, 0, 0, 1, 6, 9, 7, 5, 8, 10, 6, 3],
ticks: ["12a", "6a", "12p", "6p"],
delta: "38 min less than yesterday",
},
Week: {
total: "4h 12m",
caption: "Daily average",
bars: [7, 5, 6, 8, 9, 4, 3],
ticks: ["M", "T", "W", "T", "F", "S", "S"],
delta: "12% lower than last week",
},
Month: {
total: "4h 36m",
caption: "Daily average, September",
bars: [8, 7, 9, 6, 5],
ticks: ["Wk 1", "Wk 2", "Wk 3", "Wk 4", "Wk 5"],
delta: "Up 9% on August",
},
};
/** The old chart dims to this scale as it leaves. */
const DIM_SCALE = 0.96;
const DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
/** One bar growing from the baseline — scaleY from the bottom, rows 40ms apart. */
function Bar({ value, max, index }: { value: number; max: number; index: number }) {
const reduce = useReducedMotion();
const grow = useSharedValue(reduce ? 1 : 0);
React.useEffect(() => {
if (reduce) return;
grow.value = withDelay(rowDelay(index), withSpring(1, spring.layout));
}, [reduce, index, grow]);
const style = useAnimatedStyle(() => ({
transform: [{ scaleY: Math.max(0, grow.value) }],
}));
return (
<Animated.View
className={`flex-1 rounded-t-md ${value === max ? "bg-primary" : "bg-primary/30"}`}
style={[{ height: `${Math.max(3, (value / max) * 100)}%`, transformOrigin: "bottom" }, style]}
/>
);
}
/** A period's bars. `leaving` sets render as a dimming overlay. */
function Bars({ period, leaving }: { period: Period; leaving?: boolean }) {
const reduce = useReducedMotion();
const max = Math.max(...period.bars, 1);
const out = useSharedValue(0);
React.useEffect(() => {
if (leaving) out.value = withTiming(1, DIM);
}, [leaving, out]);
const style = useAnimatedStyle(() => ({
opacity: 1 - out.value,
transform: [{ scale: reduce ? 1 : 1 - (1 - DIM_SCALE) * out.value }],
}));
return (
<Animated.View
pointerEvents="none"
className={leaving ? "absolute inset-0 flex-row items-end gap-1" : "h-full flex-row items-end gap-1"}
style={style}
>
{period.bars.map((b, i) => (
<Bar key={i} value={b} max={max} index={i} />
))}
</Animated.View>
);
}
/** SegmentedStrings — the chart-header habitat: Day / Week / Month on a
* screen-time chart. Tap or drag the thumb: it glides with a light trail,
* the old bars dim in place while the new ones grow from the baseline
* 40ms apart, and the hero figure swaps in place. */
export function SegmentedStrings() {
const [value, setValue] = React.useState("Week");
const [leaving, setLeaving] = React.useState<{ key: string; period: Period } | null>(null);
const d = DATA[value] ?? DATA.Week!;
const change = (next: string) => {
if (next === value) return;
setLeaving({ key: value, period: d });
setValue(next);
};
React.useEffect(() => {
if (!leaving) return;
const t = setTimeout(() => setLeaving(null), DIM.duration + timing.fast.duration);
return () => clearTimeout(t);
}, [leaving]);
return (
<View className="w-full">
<View className="w-full gap-5 rounded-3xl bg-card p-5">
<SegmentedControl options={["Day", "Week", "Month"]} value={value} onValueChange={change} draggable />
<View className="gap-1">
<ActionSwapText value={value} mode="blur" className="text-[13px] text-muted-foreground">
{d.caption}
</ActionSwapText>
<ActionSwapText value={value} mode="roll" className="text-4xl font-semibold tracking-tight tabular-nums">
{d.total}
</ActionSwapText>
<ActionSwapText value={value} mode="blur" className="text-sm text-muted-foreground">
{d.delta}
</ActionSwapText>
</View>
<View className="gap-2">
<View className="h-36 border-b border-border">
{leaving ? <Bars key={`out-${leaving.key}`} period={leaving.period} leaving /> : null}
<Bars key={value} period={d} />
</View>
<View className="flex-row justify-between">
{d.ticks.map((t, i) => (
<Text key={`${value}-${t}-${i}`} className="text-xs text-muted-foreground">{t}</Text>
))}
</View>
</View>
</View>
</View>
);
} API reference
options* string[] | SegmentedControlOption[] Options to display. Can be string[] or SegmentedControlOption[].
—value* string Currently selected value.
—onValueChange* (value: string) => void — disabled boolean Disable all segments. Default false.
—className string Extra classes for the container.
—haptic "selection" | "light" | false Haptic feedback on segment change. Default "selection".
"selection" size "sm" | "md" Density — "sm" compresses rows for toolbars and card headers.
"md" glass boolean Glass treatment — the track becomes a glass capsule and the gliding indicator a raised glass pill that refracts what's beneath.
false draggable boolean Let the finger drag the thumb: it tracks 1:1, ticks the haptic as it crosses each segment and snaps to the nearest one on release. Default false.
false progress SharedValue<number> Mirrors the thumb's position (0 to n-1, fractional while gliding) on the UI thread, so the content below can follow the glide.
—