|
| 1 | +import { forwardRef, useImperativeHandle, type ForwardedRef } from 'react' |
| 2 | +import { Dimensions } from 'react-native' |
| 3 | +import Animated, { |
| 4 | + useSharedValue, |
| 5 | + useAnimatedStyle, |
| 6 | + useAnimatedReaction, |
| 7 | + runOnJS, |
| 8 | + withTiming, |
| 9 | +} from 'react-native-reanimated' |
| 10 | +import { Gesture, GestureDetector } from 'react-native-gesture-handler' |
| 11 | + |
| 12 | +import { styles } from './styles' |
| 13 | + |
| 14 | +const { width: SCREEN_WIDTH } = Dimensions.get('window') |
| 15 | + |
| 16 | +export type AnimatedPagedScrollViewRef = { |
| 17 | + scrollTo: (value: number) => void |
| 18 | +} |
| 19 | + |
| 20 | +export const AnimatedPagedView = forwardRef( |
| 21 | + ( |
| 22 | + props: { |
| 23 | + onScroll: (value: number) => void |
| 24 | + onScrollBeginDrag: () => void |
| 25 | + children: React.ReactNode |
| 26 | + }, |
| 27 | + ref: ForwardedRef<AnimatedPagedScrollViewRef>, |
| 28 | + ) => { |
| 29 | + const translateX = useSharedValue(0) |
| 30 | + const context = useSharedValue({ x: 0 }) |
| 31 | + |
| 32 | + const gesture = Gesture.Pan() |
| 33 | + .onStart(() => { |
| 34 | + context.value = { x: translateX.value } |
| 35 | + runOnJS(props.onScrollBeginDrag)() |
| 36 | + }) |
| 37 | + .onUpdate((event) => { |
| 38 | + translateX.value = context.value.x - event.translationX |
| 39 | + }) |
| 40 | + .onEnd((event) => { |
| 41 | + const velocity = event.velocityX |
| 42 | + const currentPage = Math.round(translateX.value / SCREEN_WIDTH) |
| 43 | + const targetPage = |
| 44 | + velocity > 500 ? currentPage - 1 : velocity < -500 ? currentPage + 1 : currentPage |
| 45 | + // in case the gesture overshoots, snap to the nearest page |
| 46 | + if (Math.abs(context.value.x - translateX.value) > SCREEN_WIDTH / 2) { |
| 47 | + translateX.value = withTiming(currentPage * SCREEN_WIDTH) |
| 48 | + } else { |
| 49 | + translateX.value = withTiming(targetPage * SCREEN_WIDTH) |
| 50 | + } |
| 51 | + }) |
| 52 | + |
| 53 | + const animatedStyle = useAnimatedStyle(() => { |
| 54 | + return { |
| 55 | + transform: [{ translateX: -translateX.value }], |
| 56 | + } |
| 57 | + }, []) |
| 58 | + |
| 59 | + useAnimatedReaction( |
| 60 | + () => translateX.value, |
| 61 | + (value) => { |
| 62 | + props.onScroll?.(value) |
| 63 | + }, |
| 64 | + ) |
| 65 | + |
| 66 | + useImperativeHandle(ref, () => ({ |
| 67 | + scrollTo: (value: number) => { |
| 68 | + 'worklet' |
| 69 | + translateX.value = value |
| 70 | + }, |
| 71 | + })) |
| 72 | + |
| 73 | + return ( |
| 74 | + <GestureDetector gesture={gesture}> |
| 75 | + <Animated.View style={[styles.container]}> |
| 76 | + <Animated.View style={[styles.contentContainer, animatedStyle]}> |
| 77 | + {props.children} |
| 78 | + </Animated.View> |
| 79 | + </Animated.View> |
| 80 | + </GestureDetector> |
| 81 | + ) |
| 82 | + }, |
| 83 | +) |
| 84 | + |
| 85 | +AnimatedPagedView.displayName = 'AnimatedPagedView' |
0 commit comments