diff --git a/src/WheelPicker.tsx b/src/WheelPicker.tsx index 21dfdd6..c29263b 100644 --- a/src/WheelPicker.tsx +++ b/src/WheelPicker.tsx @@ -10,6 +10,7 @@ import { ViewProps, FlatListProps, FlatList, + Platform, } from 'react-native'; import styles from './WheelPicker.styles'; import WheelPickerItem from './WheelPickerItem'; @@ -50,7 +51,10 @@ const WheelPicker: React.FC = ({ const flatListRef = useRef(null); const [scrollY] = useState(new Animated.Value(0)); + const lastScrollTimestamp = useRef(new Date().getTime()); + const containerHeight = (1 + visibleRest * 2) * itemHeight; + const [scrollIndex, setScrollIndex] = useState(selectedIndex); const paddedOptions = useMemo(() => { const array: (string | null)[] = [...options]; for (let i = 0; i < visibleRest; i++) { @@ -94,6 +98,41 @@ const WheelPicker: React.FC = ({ }); }, [selectedIndex]); + useEffect(() => { + if (Platform.OS === 'web') { + const SCROLL_COOLDOWN_MILLISECONDS = 100; + const SCROLL_DID_STOP_TIMEOUT = 500; + const intervalID = setInterval(() => { + const time = new Date().getTime(); + const difference = time - lastScrollTimestamp.current; + if (difference > SCROLL_DID_STOP_TIMEOUT) { + flatListRef.current?.scrollToIndex({ + index: scrollIndex, + animated: true, + }); + } + }, SCROLL_COOLDOWN_MILLISECONDS); + return () => { + clearInterval(intervalID); + }; + } + }, [scrollIndex]); + + useEffect(() => { + if (Platform.OS === 'web') { + onChange(scrollIndex); + } + }, [scrollIndex, onChange]); + + const handleScroll = (event: NativeSyntheticEvent) => { + if (Platform.OS === 'web') { + const positionY = event.nativeEvent.contentOffset.y; + const index = Math.round(positionY / itemHeight); + setScrollIndex(index); + lastScrollTimestamp.current = new Date().getTime(); + } + }; + return ( = ({ showsVerticalScrollIndicator={false} onScroll={Animated.event( [{ nativeEvent: { contentOffset: { y: scrollY } } }], - { useNativeDriver: true }, + { + useNativeDriver: true, + listener: (event: NativeSyntheticEvent) => handleScroll(event), + }, )} onMomentumScrollEnd={handleMomentumScrollEnd} snapToOffsets={offsets} diff --git a/src/index.ts b/src/index.ts index 35313b4..8ae2caf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,3 @@ import WheelPicker from './WheelPicker'; -export default WheelPicker; \ No newline at end of file +export default WheelPicker;