Skip to content

Instantly share code, notes, and snippets.

@tobiaslins
Last active September 21, 2019 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiaslins/71aafd2d8acddd0cd4e992ef83f20cb5 to your computer and use it in GitHub Desktop.
Save tobiaslins/71aafd2d8acddd0cd4e992ef83f20cb5 to your computer and use it in GitHub Desktop.
Reanimated Button on Hold
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