Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SegmentedControl.tsx

78 lines3.1 KB

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