Skip to content

Instantly share code, notes, and snippets.

@tobiaslins
Last active September 21, 2019 18:44

Revisions

  1. tobiaslins renamed this gist Sep 21, 2019. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. tobiaslins revised this gist Sep 21, 2019. No changes.
  3. tobiaslins created this gist Sep 21, 2019.
    90 changes: 90 additions & 0 deletions Reanimated Button on Hold
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,90 @@
    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>
    );
    };