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 { segmentedControlColors } from "./segmentedControlColors";
6import { AppText } from "./AppText";
7import { useControlTheme } from "./useControlTheme";
8import type { SegmentedControlProps } from "./SegmentedControl.types";
9
10export type { SegmentedControlProps } from "./SegmentedControl.types";
11
12export function SegmentedControl<Value extends string | number>(
13 props: SegmentedControlProps<Value>,
14) {
15 const { colorScheme, colors, themeId } = 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 { trackColor, selectedColor, selectedTextColor, mutedColor } = segmentedControlColors(
27 colors,
28 colorScheme,
29 props.variant,
30 Platform.OS,
31 themeId,
32 );
33 const minHeight = props.size === "compact" ? 32 : Platform.OS === "android" ? 40 : 36;
34
35 return (
36 <View collapsable={false} className={props.className}>
37 <View
38 onLayout={(event) => setLayout(event.nativeEvent.layout)}
39 className="flex-row rounded-full p-[3px]"
40 style={{
41 minHeight,
42 backgroundColor: trackColor,
43 }}
44 >
45 {selectedIndex >= 0 && width > 0 ? (
46 <Animated.View
47 pointerEvents="none"
48 className="absolute bottom-[3px] start-[3px] top-[3px] rounded-full"
49 style={[
50 {
51 backgroundColor: selectedColor,
52 },
53 selectionStyle,
54 ]}
55 />
56 ) : null}
57 {props.options.map((option) => {
58 const selected = option.value === props.selected;
59 return (
60 <Pressable
61 key={`${typeof option.value}:${option.value}`}
62 accessibilityRole={props.role ?? "button"}
63 accessibilityLabel={option.accessibilityLabel ?? option.label}
64 accessibilityState={{ selected }}
65 onPress={() => props.onSelect(option.value)}
66 className="flex-1 items-center justify-center rounded-full px-2 py-1 active:opacity-70"
67 style={{ minHeight: minHeight - 6 }}
68 >
69 <AppText
70 textRole="footnote"
71 className={selected ? "font-t3-bold" : "font-t3-medium"}
72 style={{
73 color: selected ? selectedTextColor : mutedColor,
74 }}
75 >
76 {option.label}
77 </AppText>
78 </Pressable>
79 );
80 })}
81 </View>
82 </View>
83 );
84}