11import { useState } from "react" ;
22import { I18nManager , Platform , Pressable , View } from "react-native" ;
3- import Animated , { useAnimatedStyle , useReducedMotion , withTiming } from "react-native-reanimated" ;
3+ import Animated , {
4+ useAnimatedStyle ,
5+ useDerivedValue ,
6+ useReducedMotion ,
7+ withTiming ,
8+ } from "react-native-reanimated" ;
49
510import { segmentedControlColors } from "./segmentedControlColors" ;
611import { AppText } from "./AppText" ;
@@ -18,10 +23,14 @@ export function SegmentedControl<Value extends string | number>(
1823 const reduceMotion = useReducedMotion ( ) ;
1924 const selectedIndex = props . options . findIndex ( ( option ) => option . value === props . selected ) ;
2025 const segmentWidth = props . options . length ? Math . max ( 0 , width - 6 ) / props . options . length : 0 ;
21- const selectionOffset = selectedIndex * segmentWidth * ( I18nManager . isRTL ? - 1 : 1 ) ;
26+ const direction = I18nManager . isRTL ? - 1 : 1 ;
27+ // The index animates, not the offset, so a resize moves the selection without sliding it.
28+ const selectedPosition = useDerivedValue ( ( ) =>
29+ withTiming ( selectedIndex , { duration : reduceMotion ? 0 : 160 } ) ,
30+ ) ;
2231 const selectionStyle = useAnimatedStyle ( ( ) => ( {
2332 width : segmentWidth ,
24- transform : [ { translateX : withTiming ( selectionOffset , { duration : reduceMotion ? 0 : 160 } ) } ] ,
33+ transform : [ { translateX : selectedPosition . value * segmentWidth * direction } ] ,
2534 } ) ) ;
2635 const { trackColor, selectedColor, selectedTextColor, mutedColor } = segmentedControlColors (
2736 colors ,
0 commit comments