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 Group
Group of toggle buttons for single or multiple selection. A highlight glides between choices, or neighbouring picks join into one continuous run.
Preview
TSX components/ui/toggle-group/toggle-group.tsx
import * as React from "react";
import { createContext, forwardRef, useContext, useMemo } from "react";
import { View, type LayoutChangeEvent, type ViewProps, type Pressable } from "react-native";
import Animated, {
Easing,
interpolateColor,
useAnimatedStyle,
useSharedValue,
withSpring,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import {
AnimatedPressable,
cn,
ease,
spring,
timing,
useHaptic,
usePressAnimation,
useReducedMotion,
useTheme,
} from "@lumioui/core";
/*
* ToggleGroup — the selection is light laid under the labels.
*
* single one shared ink indicator glides between items on
* spring.indicator; each label's ink follows how much of the
* indicator covers it, so no label flips before the light arrives.
* multiple every picked item lights; neighbours that are both lit join
* through a bridge that grows across the gap on spring.layout —
* their inner corners square off and the run reads as one bar,
* only its two ends stay round.
*
* Items report their frames to the group, which draws the resting pills, the
* light and the bridges in one underlay behind them. Items should be direct
* children of the group.
*/
/** Gaps wider than this are separate pills, never one run. */
const RUN_GAP_MAX = 16;
/** Disabled-tap kick — the 4px flicker, released into spring.shake. */
const FLICKER_KICK = 4;
type Frame = { x: number; y: number; w: number; h: number };
type Entry = Frame & { scale: SharedValue<number>; kick: SharedValue<number> };
interface ToggleGroupCtx {
type: "single" | "multiple";
value: string | string[] | undefined;
onValueChange: (value: string | string[]) => void;
disabled?: boolean;
report: (value: string, entry: Entry) => void;
measured: (value: string) => boolean;
/** Indicator centre and size (single), read by labels for coverage. */
ind: { cx: SharedValue<number>; cy: SharedValue<number>; w: SharedValue<number>; h: SharedValue<number>; sx: SharedValue<number>; on: SharedValue<number> };
}
const ToggleGroupCtx = createContext<ToggleGroupCtx | null>(null);
function useToggleGroupCtx() {
const ctx = useContext(ToggleGroupCtx);
if (!ctx) throw new Error("ToggleGroup.Item must be inside ToggleGroup");
return ctx;
}
export interface ToggleGroupProps extends ViewProps {
/** Single select or multiple select. */
type: "single" | "multiple";
/** Controlled selected value(s). Omit with defaultValue for uncontrolled use. */
value?: string | string[];
/** Initial value(s) for uncontrolled use. */
defaultValue?: string | string[];
/** Called when the selection changes. */
onValueChange?: (value: string | string[]) => void;
disabled?: boolean;
className?: string;
children?: React.ReactNode;
}
export interface ToggleGroupItemProps extends Omit<ViewProps, "style"> {
value: string;
disabled?: boolean;
className?: string;
/** Extra classes for a string label (weight, style, decoration). */
textClassName?: string;
children?: React.ReactNode;
}
const igniteTo = (v: number) => withTiming(v, { ...timing.fast, easing: Easing.bezier(...ease.out) });
const dimTo = (v: number) => withTiming(v, { ...timing.recede, easing: Easing.bezier(...ease.in) });
/** A resting pill — the unlit slot under each item. */
function RestPill({ entry }: { entry: Entry }) {
const style = useAnimatedStyle(() => ({
transform: [{ translateX: entry.kick.value }, { scale: entry.scale.value }],
}));
return (
<Animated.View
pointerEvents="none"
className="absolute bg-secondary"
style={[{ left: entry.x, top: entry.y, width: entry.w, height: entry.h, borderRadius: entry.h / 2 }, style]}
/>
);
}
/** Multiple: the light inside one picked item. Ignites in, dims out. */
function LitSegment({ entry, lit }: { entry: Entry; lit: boolean }) {
const on = useSharedValue(lit ? 1 : 0);
React.useEffect(() => {
on.value = lit ? igniteTo(1) : dimTo(0);
}, [lit, on]);
const style = useAnimatedStyle(() => ({
opacity: on.value,
transform: [{ translateX: entry.kick.value }, { scale: entry.scale.value }],
}));
return (
<Animated.View
pointerEvents="none"
className="absolute bg-primary"
style={[{ left: entry.x, top: entry.y, width: entry.w, height: entry.h, borderRadius: entry.h / 2 }, style]}
/>
);
}
/** Multiple: the bridge joining two lit neighbours — centre of one to centre
* of the next, square, so the inner corners of the run square off. */
function Bridge({ a, b, linked }: { a: Entry; b: Entry; linked: boolean }) {
const reduce = useReducedMotion();
const link = useSharedValue(linked ? 1 : 0);
React.useEffect(() => {
if (reduce) link.value = linked ? igniteTo(1) : dimTo(0);
else link.value = withSpring(linked ? 1 : 0, spring.layout);
}, [linked, link, reduce]);
const left = a.x + a.w - a.h / 2;
const width = b.x + b.h / 2 - left;
const style = useAnimatedStyle(() => ({
opacity: Math.min(1, link.value * 2),
transform: [{ scaleX: reduce ? 1 : Math.max(0.001, link.value) }],
}));
return (
<Animated.View
pointerEvents="none"
className="absolute bg-primary"
style={[{ left, top: a.y, width, height: Math.min(a.h, b.h) }, style]}
/>
);
}
/** Single: the one indicator. Size is set once per move, then the glide runs
* on transforms only (centre + a scale from the previous width). */
function Indicator({ ind, press }: { ind: ToggleGroupCtx["ind"]; press?: SharedValue<number> }) {
const style = useAnimatedStyle(() => ({
opacity: ind.on.value,
width: ind.w.value,
height: ind.h.value,
borderRadius: ind.h.value / 2,
transform: [
{ translateX: ind.cx.value - ind.w.value / 2 },
{ translateY: ind.cy.value - ind.h.value / 2 },
{ scaleX: ind.sx.value * (press ? press.value : 1) },
{ scaleY: press ? press.value : 1 },
],
}));
return <Animated.View pointerEvents="none" className="absolute left-0 top-0 bg-primary" style={style} />;
}
/** ToggleGroup — single or multiple selection; the selection is light. */
function ToggleGroupRoot(
{
type,
value: controlledValue,
defaultValue,
onValueChange,
disabled,
className,
children,
accessibilityLabel,
"aria-label": ariaLabel,
...props
}: ToggleGroupProps,
ref: React.ForwardedRef<React.ElementRef<typeof View>>
) {
const reduce = useReducedMotion();
// Single-select starts with no selection (undefined) — "" is a sentinel
// that could collide with a real empty-string item value.
const [uncontrolledValue, setUncontrolledValue] = React.useState<string | string[] | undefined>(
defaultValue ?? (type === "single" ? undefined : [])
);
// Resolve active selection during render, never in a passive effect.
const value = controlledValue ?? uncontrolledValue;
const handleValueChange = React.useCallback(
(v: string | string[]) => {
if (controlledValue === undefined) setUncontrolledValue(v);
onValueChange?.(v);
},
[controlledValue, onValueChange]
);
const [entries, setEntries] = React.useState<Record<string, Entry>>({});
const report = React.useCallback((v: string, e: Entry) => {
setEntries((prev) => {
const p = prev[v];
if (p && p.x === e.x && p.y === e.y && p.w === e.w && p.h === e.h) return prev;
return { ...prev, [v]: e };
});
}, []);
const measured = React.useCallback((v: string) => entries[v] != null, [entries]);
const cx = useSharedValue(0);
const cy = useSharedValue(0);
const w = useSharedValue(0);
const h = useSharedValue(0);
const sx = useSharedValue(1);
const on = useSharedValue(0);
const ind = useMemo(() => ({ cx, cy, w, h, sx, on }), [cx, cy, w, h, sx, on]);
const selected = useMemo(
() => (type === "single" ? (typeof value === "string" && value !== "" ? [value] : []) : Array.isArray(value) ? value : []),
[type, value]
);
const singleTarget = type === "single" ? entries[selected[0] ?? ""] : undefined;
// Single: glide the indicator to the picked item's frame.
const placed = React.useRef(false);
React.useEffect(() => {
if (type !== "single") return;
if (!singleTarget) {
on.value = dimTo(0);
return;
}
const tx = singleTarget.x + singleTarget.w / 2;
const ty = singleTarget.y + singleTarget.h / 2;
const prevW = w.value;
w.value = singleTarget.w;
h.value = singleTarget.h;
if (!placed.current || reduce || on.value === 0) {
// First placement (or nothing lit): appear in place, no glide.
placed.current = true;
cx.value = tx;
cy.value = ty;
sx.value = 1;
on.value = igniteTo(1);
return;
}
sx.value = prevW > 0 ? prevW / singleTarget.w : 1;
sx.value = withSpring(1, spring.indicator);
cx.value = withSpring(tx, spring.indicator);
cy.value = withSpring(ty, spring.indicator);
on.value = igniteTo(1);
}, [type, singleTarget, reduce, cx, cy, w, h, sx, on]);
// Multiple: neighbours on the same row with a small gap can join into a run.
const pairs = useMemo(() => {
if (type !== "multiple") return [];
const list = Object.entries(entries).sort(([, a], [, b]) => (Math.abs(a.y - b.y) < 1 ? a.x - b.x : a.y - b.y));
const out: { key: string; a: Entry; b: Entry; linked: boolean }[] = [];
for (let i = 0; i < list.length - 1; i++) {
const [va, a] = list[i]!;
const [vb, b] = list[i + 1]!;
if (Math.abs(a.y - b.y) >= 1) continue;
const gap = b.x - (a.x + a.w);
if (gap < 0 || gap > RUN_GAP_MAX) continue;
out.push({ key: `${va}|${vb}`, a, b, linked: selected.includes(va) && selected.includes(vb) });
}
return out;
}, [type, entries, selected]);
const ctx = useMemo(
() => ({ type, value, onValueChange: handleValueChange, disabled, report, measured, ind }),
[type, value, handleValueChange, disabled, report, measured, ind]
);
const list = Object.entries(entries);
return (
<ToggleGroupCtx.Provider value={ctx}>
<View
ref={ref}
className={cn("flex-row flex-wrap gap-2", className)}
// Honest grouping role: radiogroup for single-select, group for
// multi. `role` carries the full ARIA union (accessibilityRole's
// legacy union has no "group").
role={type === "single" ? "radiogroup" : "group"}
accessibilityLabel={accessibilityLabel ?? ariaLabel}
aria-label={ariaLabel ?? accessibilityLabel}
accessibilityState={{ disabled: disabled ?? false }}
{...props}
>
{/* Underlay — resting pills, then the light, behind every label. */}
{list.map(([v, e]) => (
<RestPill key={`rest-${v}`} entry={e} />
))}
{type === "multiple"
? list.map(([v, e]) => <LitSegment key={`lit-${v}`} entry={e} lit={selected.includes(v)} />)
: null}
{pairs.map((p) => (
<Bridge key={p.key} a={p.a} b={p.b} linked={p.linked} />
))}
{type === "single" ? <Indicator ind={ind} press={singleTarget?.scale} /> : null}
{children}
</View>
</ToggleGroupCtx.Provider>
);
}
export const ToggleGroupItem = forwardRef<React.ElementRef<typeof Pressable>, ToggleGroupItemProps>(
function ToggleGroupItem({ value, disabled, className, textClassName, children, onLayout, accessibilityLabel, ...props }, ref) {
const ctx = useToggleGroupCtx();
const { colors } = useTheme();
const haptics = useHaptic();
const reduce = useReducedMotion();
const press = usePressAnimation({ pressedScale: 0.94 });
const isDisabled = disabled || ctx.disabled;
const selected =
ctx.type === "single" ? ctx.value === value : Array.isArray(ctx.value) && ctx.value.includes(value);
const kick = useSharedValue(0);
const fx = useSharedValue(0);
const fy = useSharedValue(0);
const fw = useSharedValue(0);
const fh = useSharedValue(0);
// Multiple: this label's own light, on the same ignite / dim as its segment.
const lit = useSharedValue(selected ? 1 : 0);
React.useEffect(() => {
lit.value = selected ? igniteTo(1) : dimTo(0);
}, [selected, lit]);
const { report } = ctx;
const handleLayout = (e: LayoutChangeEvent) => {
const { x, y, width, height } = e.nativeEvent.layout;
fx.value = x;
fy.value = y;
fw.value = width;
fh.value = height;
report(value, { x, y, w: width, h: height, scale: press.scale, kick });
onLayout?.(e);
};
const single = ctx.type === "single";
const { ind } = ctx;
const inkStyle = useAnimatedStyle(() => {
let cover = lit.value;
if (single) {
// Ink follows the indicator's coverage of this slot.
const iw = ind.w.value * ind.sx.value;
const ox = Math.max(0, Math.min(ind.cx.value + iw / 2, fx.value + fw.value) - Math.max(ind.cx.value - iw / 2, fx.value));
const oy = Math.max(0, Math.min(ind.cy.value + ind.h.value / 2, fy.value + fh.value) - Math.max(ind.cy.value - ind.h.value / 2, fy.value));
cover = fw.value > 0 && fh.value > 0 ? Math.min(1, (ox / fw.value) * (oy / fh.value)) * ind.on.value : 0;
}
return { color: interpolateColor(cover, [0, 1], [colors.secondaryForeground, colors.primaryForeground]) };
});
const bodyStyle = useAnimatedStyle(() => ({
transform: [{ translateX: kick.value }, { scale: press.scale.value }],
}));
const handlePress = () => {
if (isDisabled) {
// Flicker for "can't": one 4px kick, released into the shake spring.
haptics.warning();
if (!reduce) {
kick.value = FLICKER_KICK;
kick.value = withSpring(0, spring.shake);
}
return;
}
haptics.selection();
const pressed = !selected;
if (single) {
ctx.onValueChange(pressed ? value : "");
} else {
const arr = Array.isArray(ctx.value) ? [...ctx.value] : [];
if (pressed) {
if (!arr.includes(value)) arr.push(value);
} else {
const idx = arr.indexOf(value);
if (idx > -1) arr.splice(idx, 1);
}
ctx.onValueChange(arr);
}
};
const label = accessibilityLabel ?? (typeof children === "string" ? children : value);
return (
<AnimatedPressable
ref={ref}
onLayout={handleLayout}
onPress={handlePress}
onPressIn={isDisabled ? undefined : press.onPressIn}
onPressOut={isDisabled ? undefined : press.onPressOut}
hitSlop={6}
style={bodyStyle}
className={cn(
"min-h-[44px] flex-row items-center justify-center gap-2 rounded-full px-4 py-2.5",
// Until the group has measured this slot, the item wears its own pill.
!ctx.measured(value) && (selected ? "bg-primary" : "bg-secondary"),
isDisabled && "opacity-50",
className
)}
// Honest selection semantics: radios in single-select, checkboxes in multi.
accessibilityRole={single ? "radio" : "checkbox"}
accessibilityState={{ checked: selected, disabled: isDisabled ?? false }}
aria-checked={selected}
aria-disabled={isDisabled ?? false}
accessibilityLabel={label}
{...props}
>
{typeof children === "string" ? (
<Animated.Text style={inkStyle} className={cn("text-base font-medium", textClassName)}>
{children}
</Animated.Text>
) : (
children
)}
</AnimatedPressable>
);
}
);
export const ToggleGroup = Object.assign(forwardRef(ToggleGroupRoot), {
Item: ToggleGroupItem,
});
ToggleGroup.displayName = "ToggleGroup";
ToggleGroupItem.displayName = "ToggleGroupItem"; TSX example.tsx
import { ToggleGroup } from "@/components/ui/toggle-group/toggle-group";
export function Example() {
return (
<ToggleGroup />
);
} Installation
npx @lumioui/cli add toggle-group
Install the dependencies
npx expo install react-native-reanimatedCopy the source from the Code tab into your project
components/ui/toggle-group/toggle-group.tsxcomponents/ui/toggle-group/index.tsUpdate the import paths to match your project setup.
Usage
import { ToggleGroupItem, ToggleGroup } from "@/components/ui/toggle-group/toggle-group"; <ToggleGroup /> Also exported: ToggleGroupItem.
Examples
The formatting bar of a field-notes editor.
npx @lumioui/cli add toggle-group-multiple
TSX components/ui/toggle-group/variants/multiple.tsx
import * as React from "react";
import { View } from "react-native";
import Animated, { FadeIn, FadeOut } from "react-native-reanimated";
import { cn, timing } from "@lumioui/core";
import { ToggleGroup, ToggleGroupItem } from "../toggle-group";
import { Text } from "../../text/text";
const MARKS = [
{ value: "bold", glyph: "B", label: "Bold", text: "font-bold" },
{ value: "italic", glyph: "I", label: "Italic", text: "italic" },
{ value: "underline", glyph: "U", label: "Underline", text: "underline" },
{ value: "strike", glyph: "S", label: "Strikethrough", text: "line-through" },
] as const;
function summary(marks: string[]) {
if (marks.length === 0) return "Plain text";
return MARKS.filter((m) => marks.includes(m.value))
.map((m) => m.label)
.join(" + ");
}
/** ToggleGroupMultiple — the formatting bar of a field-notes editor. Picked
* marks light up; neighbours that are both on join into one bar of light.
* The selected phrase restyles live and the summary swaps in place. */
export function ToggleGroupMultiple() {
const [marks, setMarks] = React.useState<string[]>(["bold", "italic"]);
const ordered = MARKS.map((m) => m.value).filter((v) => marks.includes(v));
const phrase = cn(
"text-[17px] leading-7 text-foreground",
MARKS.filter((m) => marks.includes(m.value)).map((m) => m.text)
);
const line = summary(ordered);
return (
<View className="w-full">
<View className="w-full gap-5 rounded-3xl bg-card p-5">
<View className="gap-1">
<Text className="text-[13px] font-medium text-muted-foreground">Field notes · Tue 14 Oct</Text>
<Text className="text-[22px] font-bold tracking-tight">Low tide at Harrow Point</Text>
</View>
<Text className="text-[17px] leading-7 text-muted-foreground">
The pools filled again by noon.{" "}
<Text className={cn(phrase, "bg-primary/10")}>Three sea hares under the kelp ledge</Text>
, none of them there on Sunday.
</Text>
<View className="flex-row items-center justify-between">
<ToggleGroup
type="multiple"
value={ordered}
onValueChange={(v) => setMarks(v as string[])}
accessibilityLabel="Text style"
className="flex-nowrap gap-1"
>
{MARKS.map((m) => (
<ToggleGroupItem
key={m.value}
value={m.value}
className="h-11 w-12 px-0"
textClassName={cn("text-[17px]", m.text)}
accessibilityLabel={m.label}
>
{m.glyph}
</ToggleGroupItem>
))}
</ToggleGroup>
{/* Summary — the outgoing line dims while the new one ignites. */}
<View className="h-6 flex-1 items-end justify-center" accessibilityLiveRegion="polite">
<Animated.View
key={line}
entering={FadeIn.duration(timing.fast.duration)}
exiting={FadeOut.duration(timing.recede.duration)}
className="absolute right-0"
>
<Text className="text-[13px] font-medium text-muted-foreground">{line}</Text>
</Animated.View>
</View>
</View>
</View>
</View>
);
} A map's layer picker.
npx @lumioui/cli add toggle-group-single
TSX components/ui/toggle-group/variants/single.tsx
import * as React from "react";
import { View } from "react-native";
import Animated, { Easing, useAnimatedStyle, useSharedValue, withTiming } from "react-native-reanimated";
import Svg, { Circle, Path, Rect } from "react-native-svg";
import { Accent, ease, timing, useTheme } from "@lumioui/core";
import { ToggleGroup, ToggleGroupItem } from "../toggle-group";
import { Text } from "../../text/text";
type Layer = "standard" | "transit" | "satellite";
const LAYERS: { value: Layer; label: string }[] = [
{ value: "standard", label: "Standard" },
{ value: "transit", label: "Transit" },
{ value: "satellite", label: "Satellite" },
];
const NOTES: Record<Layer, string> = {
standard: "Streets and places",
transit: "Lines 4, 11 and the harbour ferry",
satellite: "Imagery from 9 days ago",
};
// One street plan shared by every layer, so a swap changes the light, not the place.
const ROADS = "M-10 70 C 80 60 140 90 400 80 M-10 150 L 400 140 M 90 -10 L 120 240 M 250 -10 C 240 80 260 150 230 240";
const LANES = "M-10 110 L 400 105 M 170 -10 L 180 240 M 320 -10 L 330 240";
const WATER = "M-10 190 C 80 170 160 200 240 185 C 300 175 360 190 400 180 L 400 240 L -10 240 Z";
/** One map layer, drawn in react-native-svg. It dims out and ignites in place. */
function MapLayer({ layer, on }: { layer: Layer; on: boolean }) {
const { colors, scheme } = useTheme();
const lit = useSharedValue(on ? 1 : 0);
React.useEffect(() => {
lit.value = on
? withTiming(1, { ...timing.fast, easing: Easing.bezier(...ease.out) })
: withTiming(0, { ...timing.recede, easing: Easing.bezier(...ease.in) });
}, [on, lit]);
const style = useAnimatedStyle(() => ({ opacity: lit.value }));
const dark = scheme === "dark";
const sat = layer === "satellite";
// Map paper and imagery tones are physical colours, not theme tokens.
const land = sat ? (dark ? "#1F2A1C" : "#4E6340") : dark ? "#1C1C20" : "#ECEAE4";
const water = sat ? "#1E3A4C" : dark ? "#18283A" : "#C9DDEC";
const road = sat ? "rgba(255,255,255,0.35)" : dark ? "#34343A" : "#FFFFFF";
return (
<Animated.View pointerEvents="none" className="absolute inset-0" style={style}>
<Svg width="100%" height="100%" viewBox="0 0 390 230" preserveAspectRatio="xMidYMid slice">
<Rect x="0" y="0" width="390" height="230" fill={land} />
{sat ? (
<>
<Path d="M 20 20 L 80 30 L 70 60 L 15 50 Z M 200 20 L 240 15 L 245 60 L 195 55 Z" fill="#5C7650" />
<Path d="M 280 95 L 360 90 L 365 130 L 285 132 Z M 30 95 L 85 92 L 88 135 L 35 138 Z" fill="#6B5E48" />
</>
) : (
<Path d="M 200 20 L 240 15 L 245 60 L 195 55 Z" fill={dark ? "#1E2A20" : "#D6E5CF"} />
)}
<Path d={WATER} fill={water} />
<Path d={LANES} stroke={road} strokeWidth={sat ? 2 : 4} fill="none" />
<Path d={ROADS} stroke={road} strokeWidth={sat ? 3 : 8} fill="none" strokeLinecap="round" />
{layer === "transit" ? (
<>
<Path d="M -10 150 L 400 140" stroke={colors.primary} strokeWidth={4} fill="none" />
<Path d="M 90 -10 L 120 240" stroke={colors.warning} strokeWidth={4} fill="none" />
<Path d="M 60 205 C 160 190 260 215 400 200" stroke={colors.primary} strokeWidth={2} strokeDasharray="6 6" fill="none" />
{[
[115, 146],
[235, 143],
[104, 60],
].map(([x, y]) => (
<Circle key={`${x}-${y}`} cx={x} cy={y} r={6} fill={colors.card} stroke={colors.foreground} strokeWidth={2} />
))}
</>
) : null}
<Circle cx={196} cy={112} r={9} fill={colors.primary} stroke={colors.card} strokeWidth={3} />
</Svg>
</Animated.View>
);
}
/** ToggleGroupSingle — a map's layer picker. One ink indicator glides
* between Standard, Transit and Satellite, each label's ink following it,
* and the map above swaps layers in place. */
export function ToggleGroupSingle() {
const [layer, setLayer] = React.useState<Layer>("transit");
return (
<Accent color="teal" className="w-full">
<View className="w-full gap-4 rounded-3xl bg-card p-4">
<View className="h-56 w-full overflow-hidden rounded-2xl bg-muted" accessibilityRole="image" accessibilityLabel={`Map of Wren Harbour, ${layer} layer`}>
{LAYERS.map((l) => (
<MapLayer key={l.value} layer={l.value} on={l.value === layer} />
))}
</View>
<View className="gap-1 px-1">
<Text className="text-[22px] font-bold tracking-tight">Wren Harbour</Text>
<Text variant="muted">{NOTES[layer]}</Text>
</View>
<ToggleGroup
type="single"
value={layer}
// A map always shows one layer — a tap on the lit one keeps it.
onValueChange={(v) => typeof v === "string" && v && setLayer(v as Layer)}
accessibilityLabel="Map layer"
className="w-full flex-nowrap"
>
{LAYERS.map((l) => (
<ToggleGroupItem key={l.value} value={l.value} className="flex-1 px-0">
{l.label}
</ToggleGroupItem>
))}
</ToggleGroup>
</View>
</Accent>
);
} API reference
ToggleGroup
Prop Type Default
type* "single" | "multiple" Single select or multiple select.
—value string | string[] Controlled selected value(s). Omit with defaultValue for uncontrolled use.
—defaultValue string | string[] Initial value(s) for uncontrolled use.
—onValueChange (value: string | string[]) => void Called when the selection changes.
—disabled boolean — className string — children React.ReactNode — ToggleGroupItem
Prop Type Default
value* string — disabled boolean — className string — textClassName string Extra classes for a string label (weight, style, decoration).
—children React.ReactNode —