|
| 1 | +import { requireNativeView } from "expo"; |
| 2 | +import { View, type NativeSyntheticEvent, type ViewProps } from "react-native"; |
| 3 | + |
| 4 | +import { |
| 5 | + flattenThemeColor, |
| 6 | + themeColorWithAlpha, |
| 7 | + themeColorWithContrast, |
| 8 | +} from "../../lib/mobileTheme"; |
| 9 | +import { useControlTheme } from "./useControlTheme"; |
| 10 | +import type { SegmentedControlProps } from "./SegmentedControl.types"; |
| 11 | + |
| 12 | +export type { SegmentedControlProps } from "./SegmentedControl.types"; |
| 13 | + |
| 14 | +const NativeSegmentedControl = requireNativeView< |
| 15 | + ViewProps & { |
| 16 | + labels: string[]; |
| 17 | + selectedIndex: number; |
| 18 | + trackColor: string; |
| 19 | + selectedColor: string; |
| 20 | + textColor: string; |
| 21 | + mutedColor: string; |
| 22 | + appearance: string; |
| 23 | + onSelectionChange: (event: NativeSyntheticEvent<{ index: number }>) => void; |
| 24 | + } |
| 25 | +>("T3NativeControls", "SegmentedControl"); |
| 26 | + |
| 27 | +export function SegmentedControl<Value extends string | number>( |
| 28 | + props: SegmentedControlProps<Value>, |
| 29 | +) { |
| 30 | + const { colors, colorScheme } = useControlTheme(); |
| 31 | + const trackColor = flattenThemeColor( |
| 32 | + themeColorWithAlpha(colors["--color-primary"], colorScheme === "dark" ? 0.18 : 0.07), |
| 33 | + colors["--color-screen"], |
| 34 | + ); |
| 35 | + const selectedColor = |
| 36 | + colorScheme === "dark" ? colors["--color-primary"] : colors["--color-secondary"]; |
| 37 | + const selectedTextColor = |
| 38 | + colorScheme === "dark" |
| 39 | + ? colors["--color-primary-foreground"] |
| 40 | + : colors["--color-secondary-foreground"]; |
| 41 | + return ( |
| 42 | + <View className={props.className}> |
| 43 | + <NativeSegmentedControl |
| 44 | + labels={props.options.map((option) => option.label)} |
| 45 | + selectedIndex={props.options.findIndex((option) => option.value === props.selected)} |
| 46 | + trackColor={trackColor} |
| 47 | + selectedColor={selectedColor} |
| 48 | + textColor={selectedTextColor} |
| 49 | + mutedColor={themeColorWithContrast( |
| 50 | + colors["--color-foreground-muted"], |
| 51 | + trackColor, |
| 52 | + colorScheme === "dark" ? 7 : 4.5, |
| 53 | + )} |
| 54 | + appearance={colorScheme} |
| 55 | + onSelectionChange={({ nativeEvent }) => { |
| 56 | + const option = props.options[nativeEvent.index]; |
| 57 | + if (option) props.onSelect(option.value); |
| 58 | + }} |
| 59 | + style={{ height: props.size === "compact" ? 32 : 36 }} |
| 60 | + /> |
| 61 | + </View> |
| 62 | + ); |
| 63 | +} |
0 commit comments