$ git show word-drag
Word bank drag
Tap or drag word chips from a bank into a sentence line; they spring into their slots.
Inspired by DuolingoFrom William Candillon’s “Can it be done in React Native?” series. The code here is a simplified rewrite for Reanimated 4 and 3.
import { scheduleOnRN } from 'react-native-worklets';
function Word({ word, home, slot, inSentence, onToggle, onDrop }) {
// home = position in the bank, slot = position in the sentence (both from onLayout)
const tx = useSharedValue(0), ty = useSharedValue(0);
useEffect(() => {
const target = inSentence ? slot : home;
tx.value = withSpring(target.x - home.x);
ty.value = withSpring(target.y - home.y);
}, [inSentence, slot]);
const tap = Gesture.Tap().onEnd(() => scheduleOnRN(onToggle, word.id));
const pan = Gesture.Pan()
.onChange(e => { tx.value += e.changeX; ty.value += e.changeY; })
.onEnd(e => scheduleOnRN(onDrop, word.id, e.absoluteY)); // parent decides bank or sentence
const style = useAnimatedStyle(() => ({
transform: [{ translateX: tx.value }, { translateY: ty.value }],
}));
return (
<GestureDetector gesture={Gesture.Exclusive(pan, tap)}>
<Animated.View style={[styles.chip, style]}><Text>{word.text}</Text></Animated.View>
</GestureDetector>
);
}