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

SegmentedControl.tsx

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