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

SegmentedControl.tsx

71 lines2.3 KB

1import { Platform, Pressable, View } from "react-native";
2import Animated, { Easing, LinearTransition, ReduceMotion } from "react-native-reanimated";
3import { AppText as Text } from "./AppText";
4import { cn } from "../lib/cn";
5import { MaterialSegmentedControl } from "./MaterialSegmentedControl";
6import type { SegmentedControlProps } from "./SegmentedControl.types";
7​
8export type { SegmentedControlProps } from "./SegmentedControl.types";
9​
10export function SegmentedControl<Value extends number | string>(
11 props: SegmentedControlProps<Value>,
12) {
13 const compact = props.size === "compact";
14 if (Platform.OS === "android") {
15 return <MaterialSegmentedControl {...props} />;
16 }
17 return (
18 <View
19 accessible={false}
20 className={cn(
21 "flex-row overflow-hidden",
22 "rounded-full border-continuous bg-card",
23 props.className,
24 )}
25 >
26 <Animated.View
27 pointerEvents="none"
28 layout={LinearTransition.duration(200)
29 .easing(Easing.out(Easing.cubic))
30 .reduceMotion(ReduceMotion.System)}
31 className="absolute inset-y-0 rounded-full bg-secondary"
32 style={{
33 width: `${100 / props.options.length}%`,
34 start: `${
35 (Math.max(
36 0,
37 props.options.findIndex((option) => option.value === props.selected),
38 ) *
39 100) /
40 props.options.length
41 }%`,
42 }}
43 />
44 {props.options.map((option) => {
45 const active = option.value === props.selected;
46 return (
47 <Pressable
48 key={String(option.value)}
49 accessibilityRole={Platform.OS === "ios" ? "button" : (props.role ?? "button")}
50 accessibilityLabel={option.accessibilityLabel ?? option.label}
51 accessibilityState={{ selected: active }}
52 onPress={() => props.onSelect(option.value)}
53 className={cn(
54 "flex-1 items-center justify-center rounded-full",
55 compact ? "h-9" : "h-11",
56 )}
57 >
58 <Text
59 className={cn(
60 compact ? "text-xs" : "text-sm",
61 active ? "font-t3-medium text-secondary-foreground" : "text-foreground-muted",
62 )}
63 >
64 {option.label}
65 </Text>
66 </Pressable>
67 );
68 })}
69 </View>
70 );