Last active
September 21, 2019 18:44
Reanimated Button on Hold
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { ReactNode } from "react"; | |
import { ViewStyle } from "react-native"; | |
import { State, TapGestureHandler } from "react-native-gesture-handler"; | |
import Animated, { Easing } from "react-native-reanimated"; | |
import { contains, delay, onGestureEvent, timing } from "react-native-redash"; | |
interface TapHandlerProps { | |
value: Animated.Value<number>; | |
onPress: () => void; | |
onCancel: () => void; | |
children: ReactNode; | |
style: ViewStyle; | |
} | |
const { | |
Value, | |
Clock, | |
useCode, | |
block, | |
cond, | |
eq, | |
set, | |
call, | |
or, | |
and, | |
stopClock, | |
onChange, | |
} = Animated; | |
const { BEGAN, FAILED, CANCELLED, END, UNDETERMINED } = State; | |
export default ({ | |
onPress, | |
onCancel, | |
children, | |
value, | |
style, | |
}: TapHandlerProps) => { | |
const clock = new Clock(); | |
const shouldSpring = new Value(-1); | |
const shouldReset = new Value(-1); | |
const state = new Value(UNDETERMINED); | |
const gestureHandler = onGestureEvent({ state }); | |
useCode( | |
block([ | |
cond(eq(state, BEGAN), [ | |
set(shouldSpring, 1), | |
// delay(set(shouldReset, 1), 1000), // IF I add this line the spring animation is just sometimes | |
]), | |
cond(contains([END, FAILED, CANCELLED], state), set(shouldSpring, 0)), | |
onChange(state, cond(eq(state, END), call([], onPress))), | |
cond(eq(state, END), [delay(set(shouldSpring, 0), 100)]), | |
cond( | |
eq(shouldSpring, 1), | |
set( | |
value, | |
timing({ | |
clock, | |
from: value, | |
to: 1, | |
duration: 100, | |
easing: Easing.inOut(Easing.ease), | |
}), | |
), | |
), | |
cond( | |
eq(shouldSpring, 0), | |
set( | |
value, | |
timing({ | |
clock, | |
from: value, | |
to: 0, | |
duration: 400, | |
easing: Easing.elastic(5), | |
}), | |
), | |
), | |
]), | |
[], | |
); | |
return ( | |
<TapGestureHandler maxDeltaX={10} maxDeltaY={10} {...gestureHandler}> | |
{children} | |
</TapGestureHandler> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment