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.
Checkbox
Checkbox whose fill appears as the check draws on, with a gentle haptic tick. Supports an indeterminate dash, can strike through a task’s label when ticked, and clearing fades the check out.
Preview
import * as React from "react";
import { forwardRef } from "react";
import { Pressable, Text, View, type PressableProps, type GestureResponderEvent } from "react-native";
import Animated, {
useSharedValue,
useAnimatedStyle,
useAnimatedProps,
Easing,
withDelay,
withTiming,
interpolateColor,
} from "react-native-reanimated";
import Svg from "react-native-svg";
import { cn, ease, useHaptic, usePressAnimation, useTheme, useReducedMotion, timing, AnimatedPath } from "@lumioui/core";
import { Icon, type IconName } from "../icon";
/** Lumio check on the 24 grid — short stroke, long stroke (length ≈17.7). */
const CHECK_PATH = "M6 12.5l4 4 8-9";
const CHECK_LEN = 18;
/** Indeterminate dash (length 10). */
const DASH_PATH = "M7 12h10";
const DASH_LEN = 10;
// Checking: the fill ignites over 120ms while the mark draws over 240ms on
// the ignite curve — both start on the tap, no beat. Clearing dims the
// mark and the fill together; the mark is never un-drawn.
const IGNITE = Easing.bezier(...ease.out);
const FILL_IGNITE = { duration: timing.recede.duration, easing: IGNITE };
const CHECK_DRAW = { duration: 240, easing: IGNITE };
/** The dash is ~half the check's length — it draws in proportion. */
const DASH_DRAW = { duration: timing.fast.duration, easing: IGNITE };
const DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
/** The strike starts once the check is under way — the mark leads, the label follows. */
const STRIKE_AFTER = timing.recede.duration;
export interface CheckboxProps extends Omit<PressableProps, "onPress" | "children"> {
checked: boolean;
onCheckedChange: (checked: boolean) => void;
/** Renders a dash instead of a check (partial selection). Implies the filled state. */
indeterminate?: boolean;
/** Text label rendered beside the box — tapping it toggles too, and the
* box announces it via accessibilityLabelledBy/aria-labelledby. */
label?: string;
/** Leading icon rendered between the box and the label. */
icon?: IconName;
/** Secondary text under the label. */
subtitle?: string;
/** Custom leading node between the box and the label (brand mark, colour
* tile, avatar). Wins over `icon`. */
leading?: React.ReactNode;
/** Trailing node pinned to the row's right edge (price, count, badge).
* Only rendered with `label`. */
trailing?: React.ReactNode;
/** Strike the label through and mute it while checked — task-list idiom. */
strikeWhenChecked?: boolean;
disabled?: boolean;
className?: string;
}
/** Checkbox — fill ignites while the check draws on, indeterminate dash, press dip, haptic. */
export const Checkbox = forwardRef<React.ElementRef<typeof Pressable>, CheckboxProps>(
function Checkbox({ checked, onCheckedChange, indeterminate = false, label, icon, subtitle, leading, trailing, strikeWhenChecked = false, disabled, className, ...props }, ref) {
const { colors } = useTheme();
const haptics = useHaptic();
const reducedMotion = useReducedMotion();
const active = checked || indeterminate;
// Label association — the rendered text carries a nativeID the
// Pressable points back to (accessibilityLabelledBy / aria-labelledby).
const autoId = React.useId();
const labelId = `${autoId}-label`;
const press = usePressAnimation({ pressedScale: 0.94 });
/** 0 → mark hidden, 1 → mark fully drawn. */
const draw = useSharedValue(active ? 1 : 0);
/** Mark opacity — clearing dims it so the stroke is never un-drawn. */
const markO = useSharedValue(active ? 1 : 0);
/** 0 → empty box, 1 → filled box. Drives the fill + border crossfade so
* the check lands on a surface that's already arriving, not snapping. */
const fill = useSharedValue(active ? 1 : 0);
/** The label strike: drawn across from the left a beat after the check, never un-drawn. */
const struck = strikeWhenChecked && checked;
const strike = useSharedValue(struck ? 1 : 0);
const strikeO = useSharedValue(struck ? 1 : 0);
// Only animate real changes — mount (and a strict-mode re-run) shows the
// resting state, so already-checked rows don't all draw on at once.
const shownRef = React.useRef({ active, indeterminate });
React.useEffect(() => {
const prev = shownRef.current;
if (prev.active === active && prev.indeterminate === indeterminate) return;
shownRef.current = { active, indeterminate };
if (reducedMotion) {
// Opacity and colour only — the mark appears whole.
draw.value = 1;
markO.value = withTiming(active ? 1 : 0, active ? FILL_IGNITE : DIM);
fill.value = withTiming(active ? 1 : 0, active ? FILL_IGNITE : DIM);
return;
}
if (active) {
// The fill ignites fast so the mark draws onto a lit surface.
// Fresh draw each time — including check ↔ dash swaps.
fill.value = withTiming(1, FILL_IGNITE);
markO.value = 1;
draw.value = 0;
draw.value = withTiming(1, indeterminate ? DASH_DRAW : CHECK_DRAW);
} else {
fill.value = withTiming(0, DIM);
markO.value = withTiming(0, DIM);
}
}, [active, indeterminate, draw, markO, fill, reducedMotion]);
// The task performs the action: the check lands, then a strike draws
// across the label and the label dims. Clearing dims the strike away.
const struckRef = React.useRef(struck);
React.useEffect(() => {
if (struckRef.current === struck) return;
struckRef.current = struck;
if (!struck) {
strikeO.value = withTiming(0, DIM);
return;
}
strikeO.value = 1;
if (reducedMotion) {
strike.value = 1;
return;
}
strike.value = 0;
strike.value = withDelay(STRIKE_AFTER, withTiming(1, CHECK_DRAW));
}, [struck, strike, strikeO, reducedMotion]);
const strikeStyle = useAnimatedStyle(() => ({
opacity: strikeO.value,
transform: [{ scaleX: Math.max(0.0001, strike.value) }],
}));
// A done task dims as a whole (title and subtitle together) so the
// secondary line never ends up louder than the struck title.
const labelStyle = useAnimatedStyle(() => ({ opacity: 1 - 0.45 * strike.value * strikeO.value }));
const boxStyle = useAnimatedStyle(() => ({
transform: [{ scale: press.scale.value }],
// Empty box takes mutedForeground — `muted` is a fill tone and
// vanished against cards.
// No coloured shadow: depth is never a glow.
borderColor: interpolateColor(fill.value, [0, 1], [colors.mutedForeground, colors.primary]),
}));
// Primary fill lives on its own layer so it can fade in — interpolating
// a backgroundColor to "transparent" muddies the midpoint.
const fillStyle = useAnimatedStyle(() => ({
opacity: fill.value,
}));
const markStyle = useAnimatedStyle(() => ({
opacity: markO.value,
}));
const markLen = indeterminate ? DASH_LEN : CHECK_LEN;
const pathProps = useAnimatedProps(() => ({
strokeDashoffset: (1 - draw.value) * markLen,
}));
const handlePress = (_e: GestureResponderEvent) => {
haptics.selection();
onCheckedChange(!checked);
};
return (
<Pressable
ref={ref}
disabled={disabled}
onPress={handlePress}
onPressIn={press.onPressIn}
onPressOut={press.onPressOut}
className={cn(label != null && "flex-row items-center gap-3", disabled && "opacity-50", className)}
accessibilityRole="checkbox"
accessibilityLabel={label ?? props.accessibilityLabel}
accessibilityLabelledBy={label != null ? labelId : undefined}
aria-labelledby={label != null ? labelId : undefined}
accessibilityState={{ checked: indeterminate ? "mixed" : checked, disabled }}
// accessibilityState isn't forwarded to the DOM on web — mirror it
// with explicit aria-* props like Switch/Toggle do.
aria-checked={indeterminate ? "mixed" : checked}
aria-disabled={disabled ?? false}
hitSlop={10}
{...props}
// minHeight in style, not a class: it must hold on the outer box
// whatever padding the caller adds, so a bare label is never under 44.
// Merged after the spread so a caller's style keeps it.
style={
typeof props.style === "function"
? props.style
: [label != null ? { minHeight: 44 } : null, props.style]
}
>
<Animated.View
style={[{ width: 24, height: 24, borderRadius: 6, borderWidth: 2 }, boxStyle]}
className="items-center justify-center"
>
{/* Fill layer — fades in beneath the mark */}
<Animated.View
pointerEvents="none"
style={[
// Covers the border too, so the filled box has no light seam
// where the fill's edge would meet the border's inner edge.
{ position: "absolute", top: -2, left: -2, right: -2, bottom: -2, borderRadius: 6, backgroundColor: colors.primary },
fillStyle,
]}
/>
<Animated.View style={markStyle}>
<Svg width={18} height={18} viewBox="0 0 24 24" fill="none">
<AnimatedPath
d={indeterminate ? DASH_PATH : CHECK_PATH}
stroke={colors.primaryForeground}
strokeWidth={3.2}
strokeLinecap="round"
strokeLinejoin="round"
strokeDasharray={markLen}
animatedProps={pathProps}
/>
</Svg>
</Animated.View>
</Animated.View>
{leading ?? (icon ? (
<View className="h-8 w-8 items-center justify-center rounded-lg bg-muted">
<Icon name={icon} size="sm" color="foreground" />
</View>
) : null)}
{label != null ? (
<Animated.View style={labelStyle} className="min-w-0 shrink gap-0.5">
<View className="self-start">
<Text nativeID={labelId} className="text-base text-foreground" numberOfLines={2}>
{label}
</Text>
{strikeWhenChecked ? (
<Animated.View
pointerEvents="none"
style={[{ transformOrigin: "left", top: "50%" }, strikeStyle]}
className="absolute inset-x-0 h-[2px] rounded-full bg-muted-foreground"
/>
) : null}
</View>
{subtitle ? (
<Text className="text-sm text-muted-foreground" numberOfLines={1}>{subtitle}</Text>
) : null}
</Animated.View>
) : null}
{label != null && trailing != null ? <View className="ml-auto pl-3">{trailing}</View> : null}
</Pressable>
);
}
);
Checkbox.displayName = "Checkbox"; import { Checkbox } from "@/components/ui/checkbox/checkbox";
export function Example() {
return (
<Checkbox />
);
} Playground
The bare component on an empty canvas. Change its props below; it updates live.
Installation
Install the dependencies
npx expo install react-native-reanimated react-native-svgAdd the components it builds on
Copy the source from the Code tab into your project
components/ui/checkbox/checkbox.tsxcomponents/ui/checkbox/index.tsUpdate the import paths to match your project setup.
Usage
import { Checkbox } from "@/components/ui/checkbox/checkbox"; <Checkbox /> Examples
A to-do app's Today list in orange.
import * as React from "react";
import { View } from "react-native";
import Animated, {
Easing,
FadeIn,
runOnJS,
useAnimatedStyle,
useSharedValue,
withDelay,
withSpring,
withTiming,
} from "react-native-reanimated";
import { Accent, ease, spring, timing, useReducedMotion } from "@lumioui/core";
import { Checkbox } from "../checkbox";
import { Text } from "../../text/text";
interface Task {
id: string;
title: string;
/** One plain fact: a time, a due date or a cadence. */
meta: string;
}
const TASKS: Task[] = [
{ id: "a", title: "Send Q3 deck to Henrik", meta: "10:30" },
{ id: "b", title: "Book flights for the offsite", meta: "Due today" },
{ id: "c", title: "Review Ines's pricing change", meta: "Before standup" },
{ id: "d", title: "Renew passport photos", meta: "Friday" },
{ id: "e", title: "Water the fig", meta: "Every Sunday" },
];
/** The act: the check draws (240ms) and the strike follows it
* (timing.recede later, 240ms). The done row then holds 700ms before it
* folds down into Done (act, hold, resolve). */
const ACT_MS = timing.recede.duration + 240;
const HOLD_MS = 700;
/** Un-checking is seen before the row moves back up. */
const UNDO_HOLD_MS = 2 * timing.recede.duration;
/** The fold's light: the row dims in place before it moves, and switches on
* again while its new slot is still opening (revealed as the slot grows). */
const FOLD_DIM = { duration: timing.recede.duration, easing: Easing.bezier(...ease.in) };
const FOLD_IGNITE = { duration: timing.fast.duration, easing: Easing.bezier(...ease.out) };
/** The row ignites ~40% of the way into its slot opening. */
const IGNITE_INTO_OPEN = timing.recede.duration;
/** Today's progress, as one slim line that fills in the accent. */
function ProgressLine({ value }: { value: number }) {
const reduced = useReducedMotion();
const p = useSharedValue(value);
React.useEffect(() => {
p.value = reduced ? value : withSpring(value, spring.indicator);
}, [value, reduced, p]);
// Transform, not width: the fill scales from its left edge.
const fill = useAnimatedStyle(() => ({ transform: [{ scaleX: p.value }] }));
return (
<View className="h-[6px] w-full overflow-hidden rounded-full bg-secondary">
<Animated.View style={[fill, { transformOrigin: "left" }]} className="h-full w-full rounded-full bg-primary" />
</View>
);
}
/** The empty slot a row leaves behind: it closes from the row's height to 0
* on spring.layout (a measured collapse), so the rows below rise into it by
* normal flow and the card's top edge never moves. */
function ClosingSlot({ height, onClosed }: { height: number; onClosed: () => void }) {
const h = useSharedValue(height);
React.useEffect(() => {
h.value = withSpring(0, spring.layout, (done) => { if (done) runOnJS(onClosed)(); });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const style = useAnimatedStyle(() => ({ height: h.value }));
return <Animated.View style={style} />;
}
/** One task row.
* - leaving: it dims in place (timing.recede) and then hands its measured
* height to the list, which moves it and leaves a ClosingSlot behind.
* - arriving: its slot opens from 0 to its height on spring.layout while the
* row ignites into it partway through, so it unfolds rather than waiting
* in an empty band.
* Reduced motion: no dim and no slot motion; the row simply changes place. */
function TaskRow({
folding,
onFolded,
arriving,
onArrived,
children,
}: {
folding: boolean;
onFolded: (height: number) => void;
arriving: boolean;
onArrived: () => void;
children: React.ReactNode;
}) {
const reduced = useReducedMotion();
const animateIn = arriving && !reduced;
const o = useSharedValue(animateIn ? 0 : 1);
/** Slot height while opening; -1 = natural height. */
const h = useSharedValue(animateIn ? 0 : -1);
const natural = React.useRef(0);
const [measured, setMeasured] = React.useState(false);
React.useEffect(() => {
if (!folding) return;
if (reduced) { onFolded(natural.current); return; }
const hNow = natural.current;
o.value = withTiming(0, FOLD_DIM, (dimmed) => { if (dimmed) runOnJS(onFolded)(hNow); });
// onFolded is recreated each render; the fold only reacts to `folding`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [folding, reduced]);
React.useEffect(() => {
if (!animateIn || !measured) return;
o.value = withDelay(IGNITE_INTO_OPEN, withTiming(1, FOLD_IGNITE));
h.value = withSpring(natural.current, spring.layout, (open) => {
if (!open) return;
h.value = -1;
runOnJS(onArrived)();
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [animateIn, measured]);
const slot = useAnimatedStyle(() =>
h.value < 0 ? { opacity: o.value } : { height: h.value, opacity: o.value, overflow: "hidden" },
);
return (
<Animated.View style={slot}>
{/* Measures the row's natural height; inside a closed slot it still
lays out at full size and is revealed as the slot grows. */}
<View
onLayout={(e) => {
natural.current = e.nativeEvent.layout.height;
if (!measured) setMeasured(true);
}}
>
{children}
</View>
</Animated.View>
);
}
type Group = "open" | "done";
interface Ghost { key: string; group: Group; index: number; height: number }
/** CheckboxList — a to-do app's Today list in orange. Checking a task fills
* the box while the mark draws on and the title strikes through; the row
* holds, then folds: it dims, and in one move its old slot closes while a
* slot in Done opens and the row switches on inside it. The progress line
* steps with the count. */
export function CheckboxList() {
const reduced = useReducedMotion();
const [checked, setChecked] = React.useState<Record<string, boolean>>({ b: true });
// Where each row sits lags its checkbox, so the act is seen first.
const [settled, setSettled] = React.useState<Record<string, boolean>>({ b: true });
const [folding, setFolding] = React.useState<Record<string, boolean>>({});
const [arriving, setArriving] = React.useState<Record<string, boolean>>({});
const [ghosts, setGhosts] = React.useState<Ghost[]>([]);
const timers = React.useRef<Record<string, ReturnType<typeof setTimeout>>>({});
const target = React.useRef<Record<string, boolean>>({});
React.useEffect(() => () => Object.values(timers.current).forEach(clearTimeout), []);
const open = TASKS.filter((t) => !settled[t.id]);
const done = TASKS.filter((t) => settled[t.id]);
const count = TASKS.filter((t) => checked[t.id]).length;
const toggle = (id: string, v: boolean) => {
setChecked((s) => ({ ...s, [id]: v }));
target.current[id] = v;
clearTimeout(timers.current[id]);
timers.current[id] = setTimeout(() => setFolding((s) => ({ ...s, [id]: true })), v ? ACT_MS + HOLD_MS : UNDO_HOLD_MS);
};
// The dim has landed: move the row now. Its old slot closes while the new
// one opens, both at once.
const commitMove = (id: string, height: number) => {
const from: Group = settled[id] ? "done" : "open";
const list = from === "open" ? open : done;
const index = list.findIndex((t) => t.id === id);
if (!reduced && index >= 0) setGhosts((g) => [...g, { key: `${id}-${Date.now()}`, group: from, index, height }]);
setArriving((s) => ({ ...s, [id]: !reduced }));
setSettled((s) => ({ ...s, [id]: !!target.current[id] }));
setFolding((s) => ({ ...s, [id]: false }));
};
const renderGroup = (group: Group, tasks: Task[]) => {
const nodes: React.ReactNode[] = tasks.map((task, i) => (
<TaskRow
key={task.id}
folding={!!folding[task.id]}
onFolded={(height) => commitMove(task.id, height)}
arriving={!!arriving[task.id]}
onArrived={() => setArriving((s) => ({ ...s, [task.id]: false }))}
>
<Checkbox
className="px-4 py-2"
checked={!!checked[task.id]}
onCheckedChange={(v) => toggle(task.id, v)}
label={task.title}
subtitle={task.meta}
strikeWhenChecked
/>
{/* The separator is the row's bottom edge, so a closing slot at the
top of a card never shows a stray hairline under its corner. */}
{i < tasks.length - 1 ? <View className="ml-[52px] h-px bg-border" /> : null}
</TaskRow>
));
// Closing slots sit where the leaving row was.
ghosts
.filter((g) => g.group === group)
.sort((a, b) => b.index - a.index)
.forEach((g) =>
nodes.splice(
Math.min(g.index, nodes.length),
0,
<ClosingSlot key={g.key} height={g.height} onClosed={() => setGhosts((all) => all.filter((x) => x.key !== g.key))} />,
),
);
return nodes;
};
const doneVisible = done.length > 0 || ghosts.some((g) => g.group === "done");
const openVisible = open.length > 0 || ghosts.some((g) => g.group === "open");
return (
<Accent color="orange" className="w-full">
<View className="w-full gap-3">
<View className="gap-3 px-1">
<View className="flex-row items-end justify-between">
<Text className="text-3xl font-bold tracking-tight">Today</Text>
<Text variant="muted" className="pb-1 tabular-nums">
{count} of {TASKS.length} done
</Text>
</View>
<ProgressLine value={count / TASKS.length} />
</View>
{/* Each group is one card whose top edge stays put. */}
{openVisible ? (
<View className="w-full overflow-hidden rounded-2xl bg-card">{renderGroup("open", open)}</View>
) : null}
{doneVisible ? (
<Animated.View entering={reduced ? undefined : FadeIn.duration(timing.fast.duration)} className="w-full gap-2 pt-2">
<Text variant="muted" className="px-1 text-[13px] font-medium">Done</Text>
<View className="w-full overflow-hidden rounded-2xl bg-card">{renderGroup("done", done)}</View>
</Animated.View>
) : null}
</View>
</Accent>
);
} The real home of the indeterminate state: an email preferences parent that summarises its children.
import * as React from "react";
import { View } from "react-native";
import { Checkbox } from "../checkbox";
import { Text } from "../../text/text";
type Topic = "digest" | "mentions" | "product" | "events";
const TOPICS: { key: Topic; label: string; subtitle: string }[] = [
{ key: "digest", label: "Weekly digest", subtitle: "Mondays, 8:00 AM" },
{ key: "mentions", label: "Mentions and replies", subtitle: "When someone tags you" },
{ key: "product", label: "Product updates", subtitle: "About once a month" },
{ key: "events", label: "Meetups near Rotterdam", subtitle: "Only for cities you follow" },
];
/** CheckboxStates — the real home of the indeterminate state: an email
* preferences parent that summarises its children. Tap children and watch
* the parent go empty → dash → check; tap the parent to set all. The
* required security row stays checked and disabled. Ink, no accent. */
export function CheckboxStates() {
const [on, setOn] = React.useState<Record<Topic, boolean>>({
digest: true,
mentions: true,
product: false,
events: false,
});
const count = TOPICS.filter((t) => on[t.key]).length;
const all = count === TOPICS.length;
const some = count > 0 && !all;
const setAll = (v: boolean) =>
setOn({ digest: v, mentions: v, product: v, events: v });
return (
<View className="w-full gap-2">
<Text className="px-4 text-[13px] text-muted-foreground">Email from Lumio</Text>
<View className="overflow-hidden rounded-2xl bg-card">
<Checkbox
className="px-4 py-2"
checked={all}
indeterminate={some}
onCheckedChange={() => setAll(!all)}
label="All emails"
subtitle={`${count} of ${TOPICS.length} selected`}
/>
{TOPICS.map((t, i) => (
<View key={t.key}>
<View className={`${i === 0 ? "ml-[52px]" : "ml-[76px]"} h-px bg-border`} />
<Checkbox
className="py-2 pl-10 pr-4"
checked={on[t.key]}
onCheckedChange={(v) => setOn((s) => ({ ...s, [t.key]: v }))}
label={t.label}
subtitle={t.subtitle}
/>
</View>
))}
</View>
<View className="mt-4 overflow-hidden rounded-2xl bg-card">
<Checkbox
className="px-4 py-2"
checked
disabled
onCheckedChange={() => {}}
label="Security alerts"
subtitle="Sign-ins and password changes"
/>
</View>
<Text variant="muted" className="px-4">
Security alerts can't be turned off while two-step sign-in is on.
</Text>
</View>
);
} API reference
checked* boolean — onCheckedChange* (checked: boolean) => void — indeterminate boolean Renders a dash instead of a check (partial selection). Implies the filled state.
false label string Text label rendered beside the box — tapping it toggles too, and the box announces it via accessibilityLabelledBy/aria-labelledby.
—icon IconName Leading icon rendered between the box and the label.
—subtitle string Secondary text under the label.
—leading React.ReactNode Custom leading node between the box and the label (brand mark, colour tile, avatar). Wins over icon.
trailing React.ReactNode Trailing node pinned to the row's right edge (price, count, badge). Only rendered with label.
strikeWhenChecked boolean Strike the label through and mute it while checked — task-list idiom.
false disabled boolean — className string —