|
| 1 | +import { useEffect, useMemo, useRef, useState } from 'react'; |
| 2 | +import { Animated, Pressable, Text, View, ViewProps } from 'react-native'; |
| 3 | + |
| 4 | +type SegmentedControlProps = { |
| 5 | + options: string[]; |
| 6 | + selectedIndex: number; |
| 7 | + onChange: (index: number) => void; |
| 8 | + containerProps?: ViewProps; |
| 9 | +}; |
| 10 | + |
| 11 | +const SegmentedControl = ({ |
| 12 | + options, |
| 13 | + selectedIndex, |
| 14 | + onChange, |
| 15 | + containerProps, |
| 16 | +}: SegmentedControlProps) => { |
| 17 | + const translateValue = useRef(new Animated.Value(selectedIndex)).current; |
| 18 | + const [containerWidth, setContainerWidth] = useState(0); |
| 19 | + |
| 20 | + useEffect(() => { |
| 21 | + Animated.spring(translateValue, { |
| 22 | + toValue: selectedIndex, |
| 23 | + useNativeDriver: true, |
| 24 | + tension: 200, |
| 25 | + friction: 20, |
| 26 | + }).start(); |
| 27 | + }, [selectedIndex, translateValue]); |
| 28 | + |
| 29 | + const { segmentWidth, indicatorOffset } = useMemo(() => { |
| 30 | + const horizontalPadding = 8; // p-[4px] on container |
| 31 | + const contentWidth = Math.max(containerWidth - horizontalPadding, 0); |
| 32 | + return { |
| 33 | + segmentWidth: contentWidth > 0 ? contentWidth / options.length : 0, |
| 34 | + indicatorOffset: horizontalPadding / 2, |
| 35 | + }; |
| 36 | + }, [containerWidth, options.length]); |
| 37 | + |
| 38 | + const indicatorStyle = useMemo( |
| 39 | + () => ({ |
| 40 | + width: segmentWidth, |
| 41 | + transform: [{ translateX: Animated.multiply(translateValue, segmentWidth || 0) }], |
| 42 | + }), |
| 43 | + [segmentWidth, translateValue] |
| 44 | + ); |
| 45 | + |
| 46 | + return ( |
| 47 | + <View |
| 48 | + className='my-[10px] flex-row items-center rounded-full bg-gray-300 p-[4px]' |
| 49 | + onLayout={(event) => setContainerWidth(event.nativeEvent.layout.width)} |
| 50 | + {...containerProps}> |
| 51 | + <Animated.View |
| 52 | + pointerEvents='none' |
| 53 | + className='absolute h-full rounded-full bg-gray-800 shadow-[0px_1px_4px_0px_rgba(12,12,13,0.05),0px_1px_4px_0px_rgba(12,12,13,0.10)]' |
| 54 | + style={[{ left: indicatorOffset }, indicatorStyle]} |
| 55 | + /> |
| 56 | + {options.map((option, index) => { |
| 57 | + const isSelected = index === selectedIndex; |
| 58 | + return ( |
| 59 | + <Pressable key={option} className='z-10 flex-1 py-[8px]' onPress={() => onChange(index)}> |
| 60 | + <Text |
| 61 | + className={`text-center ${isSelected ? 'text-14b text-white' : 'text-13m text-black'}`}> |
| 62 | + {option} |
| 63 | + </Text> |
| 64 | + </Pressable> |
| 65 | + ); |
| 66 | + })} |
| 67 | + </View> |
| 68 | + ); |
| 69 | +}; |
| 70 | + |
| 71 | +export default SegmentedControl; |
0 commit comments