Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion src/WheelPicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
ViewProps,
FlatListProps,
FlatList,
Platform,
} from 'react-native';
import styles from './WheelPicker.styles';
import WheelPickerItem from './WheelPickerItem';
Expand Down Expand Up @@ -50,7 +51,10 @@ const WheelPicker: React.FC<Props> = ({
const flatListRef = useRef<FlatList>(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++) {
Expand Down Expand Up @@ -94,6 +98,41 @@ const WheelPicker: React.FC<Props> = ({
});
}, [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<any>) => {
if (Platform.OS === 'web') {
const positionY = event.nativeEvent.contentOffset.y;
const index = Math.round(positionY / itemHeight);
setScrollIndex(index);
lastScrollTimestamp.current = new Date().getTime();
}
};

return (
<View
style={[styles.container, { height: containerHeight }, containerStyle]}
Expand All @@ -116,7 +155,10 @@ const WheelPicker: React.FC<Props> = ({
showsVerticalScrollIndicator={false}
onScroll={Animated.event(
[{ nativeEvent: { contentOffset: { y: scrollY } } }],
{ useNativeDriver: true },
{
useNativeDriver: true,
listener: (event: NativeSyntheticEvent<any>) => handleScroll(event),
},
)}
onMomentumScrollEnd={handleMomentumScrollEnd}
snapToOffsets={offsets}
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import WheelPicker from './WheelPicker';

export default WheelPicker;
export default WheelPicker;