Open History to see the last commit
1import { useState } from "react";
2import { I18nManager, Platform, Pressable, View } from "react-native";
3import Animated, { useAnimatedStyle, useReducedMotion, withTiming } from "react-native-reanimated";
4
5import { AppText } from "./AppText";
6import { useControlTheme } from "./useControlTheme";
7import type { SegmentedControlProps } from "./SegmentedControl.types";
8
9export type { SegmentedControlProps } from "./SegmentedControl.types";
10
11/** Shared capsule control with native press targets and a flat, themed selection. */
12export function SegmentedControl<Value extends string | number>(
13 props: SegmentedControlProps<Value>,
14) {
15 const { colorScheme, colors } = useControlTheme();
16 const [layout, setLayout] = useState({ width: 0, height: 0 });
17 const { width } = layout;
18 const reduceMotion = useReducedMotion();
19 const selectedIndex = props.options.findIndex((option) => option.value === props.selected);
20 const segmentWidth = props.options.length ? Math.max(0, width - 6) / props.options.length : 0;
21 const selectionOffset = selectedIndex * segmentWidth * (I18nManager.isRTL ? -1 : 1);
22 const selectionStyle = useAnimatedStyle(() => ({
23 width: segmentWidth,
24 transform: [{ translateX: withTiming(selectionOffset, { duration: reduceMotion ? 0 : 160 }) }],
25 }));
26 const dark = colorScheme === "dark";
27 const minHeight = props.size === "compact" ? 32 : Platform.OS === "android" ? 40 : 36;
28
29 return (
30 <View collapsable={false} className={props.className}>
31 <View
32 onLayout={(event) => setLayout(event.nativeEvent.layout)}
33 className="flex-row rounded-full p-[3px]"
34 style={{
35 minHeight,
36 backgroundColor: colors[dark ? "--color-screen" : "--color-grouped-card"],
37 }}
38 >
39 {selectedIndex >= 0 && width > 0 ? (
40 <Animated.View
41 pointerEvents="none"
42 className="absolute bottom-[3px] start-[3px] top-[3px] rounded-full"
43 style={[
44 {
45 backgroundColor: colors[dark ? "--color-secondary" : "--color-screen"],
46 },
47 selectionStyle,
48 ]}
49 />
50 ) : null}
51 {props.options.map((option) => {
52 const selected = option.value === props.selected;
53 return (
54 <Pressable
55 key={`${typeof option.value}:${option.value}`}
56 accessibilityRole={props.role ?? "button"}
57 accessibilityLabel={option.accessibilityLabel ?? option.label}
58 accessibilityState={{ selected }}
59 onPress={() => props.onSelect(option.value)}
60 className="flex-1 items-center justify-center rounded-full px-2 py-1 active:opacity-70"
61 style={{ minHeight: minHeight - 6 }}
62 >
63 <AppText
64 textRole="footnote"
65 className={selected ? "font-t3-bold" : "font-t3-medium"}
66 style={{
67 color:
68 colors[selected ? "--color-secondary-foreground" : "--color-foreground-muted"],
69 }}
70 >
71 {option.label}
72 </AppText>
73 </Pressable>
74 );
75 })}
76 </View>
77 </View>
78 );
79}