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

SegmentedControl.tsx

83 lines2.7 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";
6​
7export interface SegmentedControlProps<Value extends number | string> {
8 readonly options: readonly {
9 readonly value: Value;
10 readonly label: string;
11 readonly accessibilityLabel?: string;
12 }[];
13 readonly selected: Value;
14 readonly onSelect: (value: Value) => void;
15 /** Compact sizing applies to the non-Material control. */
16 readonly size?: "default" | "compact";
17 /** "tab" for the view switcher; filters stay plain buttons. */
18 readonly role?: "tab" | "button";
19 readonly className?: string;
21​
22export function SegmentedControl<Value extends number | string>(
23 props: SegmentedControlProps<Value>,
24) {
25 const compact = props.size === "compact";
26 if (Platform.OS === "android") {
27 return <MaterialSegmentedControl {...props} />;
28 }
29 return (
30 <View
31 accessible={false}
32 className={cn(
33 "flex-row overflow-hidden",
34 "rounded-full border-continuous bg-card",
35 props.className,
36 )}
37 >
38 <Animated.View
39 pointerEvents="none"
40 layout={LinearTransition.duration(200)
41 .easing(Easing.out(Easing.cubic))
42 .reduceMotion(ReduceMotion.System)}
43 className="absolute inset-y-0 rounded-full bg-subtle-strong"
44 style={{
45 width: `${100 / props.options.length}%`,
46 start: `${
47 (Math.max(
48 0,
49 props.options.findIndex((option) => option.value === props.selected),
50 ) *
51 100) /
52 props.options.length
53 }%`,
54 }}
55 />
56 {props.options.map((option) => {
57 const active = option.value === props.selected;
58 return (
59 <Pressable
60 key={String(option.value)}
61 accessibilityRole={Platform.OS === "ios" ? "button" : (props.role ?? "button")}
62 accessibilityLabel={option.accessibilityLabel ?? option.label}
63 accessibilityState={{ selected: active }}
64 onPress={() => props.onSelect(option.value)}
65 className={cn(
66 "flex-1 items-center justify-center rounded-full",
67 compact ? "h-9" : "h-11",
68 )}
69 >
70 <Text
71 className={cn(
72 compact ? "text-xs" : "text-sm",
73 active ? "font-t3-medium text-foreground" : "text-foreground-muted",
74 )}
75 >
76 {option.label}
77 </Text>
78 </Pressable>
79 );
80 })}
81 </View>
82 );