|
| 1 | +import { useCallback, useMemo, useRef } from 'react'; |
| 2 | +import { Text, View } from 'react-native'; |
| 3 | +import { Gesture, GestureDetector } from 'react-native-gesture-handler'; |
| 4 | +import { runOnJS } from 'react-native-reanimated'; |
| 5 | +import type { AlphabetProps } from './types'; |
| 6 | + |
| 7 | +const Alphabet = (props: AlphabetProps) => { |
| 8 | + const ref = useRef<View | null>(null); |
| 9 | + const height = useRef(1); |
| 10 | + const lastIndexRef = useRef(-1); |
| 11 | + |
| 12 | + const handle = useCallback( |
| 13 | + (localY: number) => { |
| 14 | + const data = props.data; |
| 15 | + const length = data?.length ?? 0; |
| 16 | + if (!data || length === 0) return; |
| 17 | + |
| 18 | + const yRel = Math.max(0, Math.min(height.current, localY)); |
| 19 | + const itemH = height.current / length; |
| 20 | + const idx = Math.max(0, Math.min(length - 1, Math.floor(yRel / itemH))); |
| 21 | + |
| 22 | + if (idx !== lastIndexRef.current) { |
| 23 | + lastIndexRef.current = idx; |
| 24 | + props.onCharSelect?.(data[idx]!); |
| 25 | + } |
| 26 | + }, |
| 27 | + [props] |
| 28 | + ); |
| 29 | + |
| 30 | + const tap = useMemo( |
| 31 | + () => |
| 32 | + Gesture.Tap() |
| 33 | + .hitSlop(props.hitSlop) |
| 34 | + .onEnd((e) => { |
| 35 | + runOnJS(handle)(e.y); |
| 36 | + }), |
| 37 | + [handle, props.hitSlop] |
| 38 | + ); |
| 39 | + |
| 40 | + const pan = useMemo( |
| 41 | + () => |
| 42 | + Gesture.Pan() |
| 43 | + .minDistance(4) |
| 44 | + .onChange((e) => { |
| 45 | + runOnJS(handle)(e.y); |
| 46 | + }) |
| 47 | + .onFinalize(() => { |
| 48 | + lastIndexRef.current = -1; |
| 49 | + }), |
| 50 | + [handle] |
| 51 | + ); |
| 52 | + |
| 53 | + const gesture = useMemo(() => Gesture.Race(tap, pan), [tap, pan]); |
| 54 | + |
| 55 | + return ( |
| 56 | + <GestureDetector gesture={gesture}> |
| 57 | + <View |
| 58 | + ref={ref} |
| 59 | + style={props.containerStyle} |
| 60 | + onLayout={(e) => { |
| 61 | + height.current = e.nativeEvent.layout.height; |
| 62 | + }} |
| 63 | + > |
| 64 | + {props.data?.map((letter) => ( |
| 65 | + <View key={letter} style={props.charContainerStyle}> |
| 66 | + <Text style={props.charStyle}>{letter}</Text> |
| 67 | + </View> |
| 68 | + ))} |
| 69 | + </View> |
| 70 | + </GestureDetector> |
| 71 | + ); |
| 72 | +}; |
| 73 | + |
| 74 | +export default Alphabet; |
0 commit comments