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

SegmentedControl.tsx

55 lines1.9 KB

1import { requireNativeView } from "expo";
2import { View, type NativeSyntheticEvent, type ViewProps } from "react-native";
3​
4import { SegmentedControl as FlatSegmentedControl } from "./SegmentedControl.shared";
5import { segmentedControlColors } from "./segmentedControlColors";
6import { useControlTheme } from "./useControlTheme";
7import type { SegmentedControlProps } from "./SegmentedControl.types";
8​
9export type { SegmentedControlProps } from "./SegmentedControl.types";
10​
11const NativeSegmentedControl = requireNativeView<
12 ViewProps & {
13 labels: string[];
14 selectedIndex: number;
15 trackColor: string;
16 selectedColor: string;
17 textColor: string;
18 mutedColor: string;
19 appearance: string;
20 onSelectionChange: (event: NativeSyntheticEvent<{ index: number }>) => void;
21 }
22>("T3NativeControls", "SegmentedControl");
23​
24export function SegmentedControl<Value extends string | number>(
25 props: SegmentedControlProps<Value>,
26) {
27 const { colors, colorScheme, themeId } = useControlTheme();
28 // UIKit adds a gray fill over the sunken card track.
29 if (props.variant === "card") return <FlatSegmentedControl {...props} />;
30 const { trackColor, selectedColor, selectedTextColor, mutedColor } = segmentedControlColors(
31 colors,
32 colorScheme,
33 props.variant,
34 "ios",
35 themeId,
36 );
37 return (
38 <View className={props.className}>
39 <NativeSegmentedControl
40 labels={props.options.map((option) => option.label)}
41 selectedIndex={props.options.findIndex((option) => option.value === props.selected)}
42 trackColor={trackColor}
43 selectedColor={selectedColor}
44 textColor={selectedTextColor}
45 mutedColor={mutedColor}
46 appearance={colorScheme}
47 onSelectionChange={({ nativeEvent }) => {
48 const option = props.options[nativeEvent.index];
49 if (option) props.onSelect(option.value);
50 }}
51 style={{ height: props.size === "compact" ? 32 : 36 }}
52 />
53 </View>
54 );