import { useState } from "react"; import { I18nManager, Platform, Pressable, View } from "react-native"; import Animated, { useAnimatedStyle, useDerivedValue, useReducedMotion, withTiming, } from "react-native-reanimated"; import { segmentedControlColors } from "./segmentedControlColors"; import { AppText } from "./AppText"; import { useControlTheme } from "./useControlTheme"; import type { SegmentedControlProps } from "./SegmentedControl.types"; export type { SegmentedControlProps } from "./SegmentedControl.types"; export function SegmentedControl( props: SegmentedControlProps, ) { const { colorScheme, colors, themeId } = useControlTheme(); const [layout, setLayout] = useState({ width: 0, height: 0 }); const { width } = layout; const reduceMotion = useReducedMotion(); const selectedIndex = props.options.findIndex((option) => option.value === props.selected); const segmentWidth = props.options.length ? Math.max(0, width - 6) / props.options.length : 0; const direction = I18nManager.isRTL ? -1 : 1; // The index animates, not the offset, so a resize moves the selection without sliding it. const selectedPosition = useDerivedValue(() => withTiming(selectedIndex, { duration: reduceMotion ? 0 : 160 }), ); const selectionStyle = useAnimatedStyle(() => ({ width: segmentWidth, transform: [{ translateX: selectedPosition.value * segmentWidth * direction }], })); const { trackColor, selectedColor, selectedTextColor, mutedColor } = segmentedControlColors( colors, colorScheme, props.variant, Platform.OS, themeId, ); const minHeight = props.size === "compact" ? 32 : Platform.OS === "android" ? 40 : 36; return ( setLayout(event.nativeEvent.layout)} className="flex-row rounded-full p-[3px]" style={{ minHeight, backgroundColor: trackColor, }} > {selectedIndex >= 0 && width > 0 ? ( ) : null} {props.options.map((option) => { const selected = option.value === props.selected; return ( props.onSelect(option.value)} className="flex-1 items-center justify-center rounded-full px-2 py-1 active:opacity-70" style={{ minHeight: minHeight - 6 }} > {option.label} ); })} ); }