react-native-reanimated#Value TypeScript Examples

The following examples show how to use react-native-reanimated#Value. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private isAndroid = new Value(Number(Platform.OS === 'android'));
Example #2
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private scrollUpAndPullDown = new Value(0);
Example #3
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private dragWithHandle = new Value(0);
Example #4
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private lastSnap: Animated.Value<number>;
Example #5
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private destSnapPoint = new Value(0);
Example #6
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private translationY: Animated.Value<number>;
Example #7
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private prevTranslateYOffset: Animated.Value<number>;
Example #8
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private lastStartScrollY: Animated.Value<number> = new Value(0);
Example #9
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private velocityY = new Value(0);
Example #10
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private animationFrameTime = new Value(0);
Example #11
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private animationFinished = new Value(0);
Example #12
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private animationPosition = new Value(0);
Example #13
Source File: CardModal.tsx    From react-native-template with MIT License 5 votes vote down vote up
CardModal = ({
  children,
  visible,
  cardHeight = layoutUtil.height,
  almostTuckedIn = false,
  cardStyle,
}: Props) => {
  const animation = useValue(0)
  const heightValue = useMemo(() => multiply(-cardHeight, HEIGHT_OFFSET), [
    cardHeight,
  ])

  const isTuckedIn = bin(visible)
  const isAlmostTuckedIn = bin(almostTuckedIn)

  useCode(
    () => [
      cond(
        // down animation
        or(not(isTuckedIn), isAlmostTuckedIn),
        set(
          animation,
          spring({
            to: cond(isAlmostTuckedIn, TUCK_IN_HEIGHT, 0),
            from: animation,
            config: {
              damping: new Value(20),
              mass: 0.6,
            },
          })
        ),
        cond(or(isTuckedIn, not(isAlmostTuckedIn)), [
          // up animation
          set(
            animation,
            spring({
              to: heightValue,
              from: animation,
              config: {
                damping: new Value(20),
                mass: 0.8,
              },
            })
          ),
        ])
      ),
    ],
    [visible, heightValue, almostTuckedIn]
  )

  return (
    <>
      <Animated.View
        style={[
          styles.card,
          {
            height: cardHeight * HEIGHT_OFFSET,
            bottom: -cardHeight * HEIGHT_OFFSET,
            transform: [{ translateY: animation }],
          },
          cardStyle,
        ]}
      >
        {children}
      </Animated.View>
    </>
  )
}
Example #14
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private tempDestSnapPoint = new Value(0);
Example #15
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private prevDragY = new Value(0);
Example #16
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
private dragY = new Value(0);
Example #17
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
/**
   * Deceleration rate of the scroll component. This is used only on Android to
   * compensate the unexpected glide it gets sometimes.
   */
  private decelerationRate: Animated.Value<number>;
Example #18
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
/**
   * Keeps track of the current index
   */
  private nextSnapIndex: Animated.Value<number>;
Example #19
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
/**
   * Manual snapping amount
   */
  private manualYOffset: Animated.Value<number> = new Value(0);
Example #20
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
/**
   * Flag to indicate imperative snapping
   */
  private isManuallySetValue: Animated.Value<number> = new Value(0);
Example #21
Source File: HorizontalFlatListExample.tsx    From react-native-scroll-bottom-sheet with MIT License 5 votes vote down vote up
HorizontalFlatListExample: React.FC<Props> = ({ navigation }) => {
  const bottomSheetRef = React.useRef<ScrollBottomSheet<any> | null>(null);

  const animatedPosition = React.useRef(new Value(0));
  const opacity = interpolate(animatedPosition.current, {
    inputRange: [0, 1],
    outputRange: [0, 0.75],
    extrapolate: Extrapolate.CLAMP,
  });

  const renderRow = React.useCallback(
    ({ index }) => <Carousel index={index} />,
    []
  );

  return (
    <View style={styles.container}>
      <MapView
        style={StyleSheet.absoluteFillObject}
        initialRegion={initialRegion}
      />
      <Animated.View
        pointerEvents="box-none"
        style={[
          StyleSheet.absoluteFillObject,
          { backgroundColor: 'black', opacity },
        ]}
      />
      <View style={StyleSheet.absoluteFillObject} pointerEvents="box-none">
        <TouchableRipple
          style={[styles.iconContainer, { right: 16 }]}
          onPress={() => {
            bottomSheetRef.current?.snapTo(2);
          }}
          borderless
        >
          <MaterialCommunityIcons
            name="close"
            size={32}
            color="white"
            style={styles.icon}
          />
        </TouchableRipple>
        {Platform.OS === 'ios' && (
          <TouchableRipple
            style={[styles.iconContainer, { left: 16 }]}
            onPress={() => {
              navigation.goBack();
            }}
            borderless
          >
            <Ionicons
              name="ios-arrow-back"
              size={32}
              color="white"
              style={styles.icon}
            />
          </TouchableRipple>
        )}
      </View>
      <ScrollBottomSheet<string>
        ref={bottomSheetRef}
        componentType="FlatList"
        topInset={24}
        animatedPosition={animatedPosition.current}
        snapPoints={snapPointsFromTop}
        initialSnapIndex={2}
        renderHandle={() => <Handle />}
        keyExtractor={i => `row-${i}`}
        initialNumToRender={5}
        contentContainerStyle={styles.contentContainerStyle}
        data={Array.from({ length: 100 }).map((_, i) => String(i))}
        renderItem={renderRow}
      />
    </View>
  );
}
Example #22
Source File: index.tsx    From react-native-scroll-bottom-sheet with MIT License 4 votes vote down vote up
constructor(props: Props<T>) {
    super(props);
    const { initialSnapIndex, animationType } = props;

    const animationDriver = animationType === 'timing' ? 0 : 1;
    const animationDuration =
      (props.animationType === 'timing' && props.animationConfig?.duration) ||
      DEFAULT_ANIMATION_DURATION;

    const ScrollComponent = this.getScrollComponent();
    // @ts-ignore
    this.scrollComponent = Animated.createAnimatedComponent(ScrollComponent);

    const snapPoints = this.getNormalisedSnapPoints();
    const openPosition = snapPoints[0];
    const closedPosition = this.props.enableOverScroll
      ? windowHeight
      : snapPoints[snapPoints.length - 1];
    const initialSnap = snapPoints[initialSnapIndex];
    this.nextSnapIndex = new Value(initialSnapIndex);

    const initialDecelerationRate = Platform.select({
      android:
        props.initialSnapIndex === 0 ? ANDROID_NORMAL_DECELERATION_RATE : 0,
      ios: IOS_NORMAL_DECELERATION_RATE,
    });
    this.decelerationRate = new Value(initialDecelerationRate);

    const handleGestureState = new Value<GestureState>(-1);
    const handleOldGestureState = new Value<GestureState>(-1);
    const drawerGestureState = new Value<GestureState>(-1);
    const drawerOldGestureState = new Value<GestureState>(-1);

    const lastSnapInRange = new Value(1);
    this.prevTranslateYOffset = new Value(initialSnap);
    this.translationY = new Value(initialSnap);

    this.lastSnap = new Value(initialSnap);

    this.onHandleGestureEvent = event([
      {
        nativeEvent: {
          translationY: this.dragY,
          oldState: handleOldGestureState,
          state: handleGestureState,
          velocityY: this.velocityY,
        },
      },
    ]);
    this.onDrawerGestureEvent = event([
      {
        nativeEvent: {
          translationY: this.dragY,
          oldState: drawerOldGestureState,
          state: drawerGestureState,
          velocityY: this.velocityY,
        },
      },
    ]);
    this.onScrollBeginDrag = event([
      {
        nativeEvent: {
          contentOffset: { y: this.lastStartScrollY },
        },
      },
    ]);

    const didHandleGestureBegin = eq(handleGestureState, GestureState.ACTIVE);

    const isAnimationInterrupted = and(
      or(
        eq(handleGestureState, GestureState.BEGAN),
        eq(drawerGestureState, GestureState.BEGAN),
        and(
          eq(this.isAndroid, 0),
          eq(animationDriver, 1),
          or(
            eq(drawerGestureState, GestureState.ACTIVE),
            eq(handleGestureState, GestureState.ACTIVE)
          )
        )
      ),
      clockRunning(this.animationClock)
    );

    this.didGestureFinish = or(
      and(
        eq(handleOldGestureState, GestureState.ACTIVE),
        eq(handleGestureState, GestureState.END)
      ),
      and(
        eq(drawerOldGestureState, GestureState.ACTIVE),
        eq(drawerGestureState, GestureState.END)
      )
    );

    // Function that determines if the last snap point is in the range {snapPoints}
    // In the case of interruptions in the middle of an animation, we'll get
    // lastSnap values outside the range
    const isLastSnapPointInRange = (i: number = 0): Animated.Node<number> =>
      i === snapPoints.length
        ? lastSnapInRange
        : cond(
            eq(this.lastSnap, snapPoints[i]),
            [set(lastSnapInRange, 1)],
            isLastSnapPointInRange(i + 1)
          );

    const scrollY = [
      set(lastSnapInRange, 0),
      isLastSnapPointInRange(),
      cond(
        or(
          didHandleGestureBegin,
          and(
            this.isManuallySetValue,
            not(eq(this.manualYOffset, snapPoints[0]))
          )
        ),
        [set(this.dragWithHandle, 1), 0]
      ),
      cond(
        // This is to account for a continuous scroll on the drawer from a snap point
        // Different than top, bringing the drawer to the top position, so that if we
        // change scroll direction without releasing the gesture, it doesn't pull down the drawer again
        and(
          eq(this.dragWithHandle, 1),
          greaterThan(snapPoints[0], add(this.lastSnap, this.dragY)),
          and(not(eq(this.lastSnap, snapPoints[0])), lastSnapInRange)
        ),
        [
          set(this.lastSnap, snapPoints[0]),
          set(this.dragWithHandle, 0),
          this.lastStartScrollY,
        ],
        cond(eq(this.dragWithHandle, 1), 0, this.lastStartScrollY)
      ),
    ];

    this.didScrollUpAndPullDown = cond(
      and(
        greaterOrEq(this.dragY, this.lastStartScrollY),
        greaterThan(this.lastStartScrollY, 0)
      ),
      set(this.scrollUpAndPullDown, 1)
    );

    this.setTranslationY = cond(
      and(
        not(this.dragWithHandle),
        not(greaterOrEq(this.dragY, this.lastStartScrollY))
      ),
      set(this.translationY, sub(this.dragY, this.lastStartScrollY)),
      set(this.translationY, this.dragY)
    );

    this.extraOffset = cond(
      eq(this.scrollUpAndPullDown, 1),
      this.lastStartScrollY,
      0
    );
    const endOffsetY = add(
      this.lastSnap,
      this.translationY,
      multiply(1 - props.friction, this.velocityY)
    );

    this.calculateNextSnapPoint = (i = 0): Animated.Node<number> | number =>
      i === snapPoints.length
        ? this.tempDestSnapPoint
        : cond(
            greaterThan(
              abs(sub(this.tempDestSnapPoint, endOffsetY)),
              abs(sub(add(snapPoints[i], this.extraOffset), endOffsetY))
            ),
            [
              set(this.tempDestSnapPoint, add(snapPoints[i], this.extraOffset)),
              set(this.nextSnapIndex, i),
              this.calculateNextSnapPoint(i + 1),
            ],
            this.calculateNextSnapPoint(i + 1)
          );

    const runAnimation = ({
      clock,
      from,
      to,
      position,
      finished,
      velocity,
      frameTime,
    }: TimingParams) => {
      const state = {
        finished,
        velocity: new Value(0),
        position,
        time: new Value(0),
        frameTime,
      };

      const timingConfig = {
        duration: animationDuration,
        easing:
          (props.animationType === 'timing' && props.animationConfig?.easing) ||
          DEFAULT_EASING,
        toValue: new Value(0),
      };

      const springConfig = {
        ...DEFAULT_SPRING_PARAMS,
        ...((props.animationType === 'spring' && props.animationConfig) || {}),
        toValue: new Value(0),
      };

      return [
        cond(and(not(clockRunning(clock)), not(eq(finished, 1))), [
          // If the clock isn't running, we reset all the animation params and start the clock
          set(state.finished, 0),
          set(state.velocity, velocity),
          set(state.time, 0),
          set(state.position, from),
          set(state.frameTime, 0),
          set(timingConfig.toValue, to),
          set(springConfig.toValue, to),
          startClock(clock),
        ]),
        // We run the step here that is going to update position
        cond(
          eq(animationDriver, 0),
          timing(clock, state, timingConfig),
          spring(clock, state, springConfig)
        ),
        cond(
          state.finished,
          [
            call([this.nextSnapIndex], ([value]) => {
              if (value !== this.prevSnapIndex) {
                this.props.onSettle?.(value);
              }
              this.prevSnapIndex = value;
            }),
            // Resetting appropriate values
            set(drawerOldGestureState, GestureState.END),
            set(handleOldGestureState, GestureState.END),
            set(this.prevTranslateYOffset, state.position),
            cond(eq(this.scrollUpAndPullDown, 1), [
              set(
                this.prevTranslateYOffset,
                sub(this.prevTranslateYOffset, this.lastStartScrollY)
              ),
              set(this.lastStartScrollY, 0),
              set(this.scrollUpAndPullDown, 0),
            ]),
            cond(eq(this.destSnapPoint, snapPoints[0]), [
              set(this.dragWithHandle, 0),
            ]),
            set(this.isManuallySetValue, 0),
            set(this.manualYOffset, 0),
            stopClock(clock),
            this.prevTranslateYOffset,
          ],
          // We made the block return the updated position,
          state.position
        ),
      ];
    };

    const translateYOffset = cond(
      isAnimationInterrupted,
      [
        // set(prevTranslateYOffset, animationPosition) should only run if we are
        // interrupting an animation when the drawer is currently in a different
        // position than the top
        cond(
          or(
            this.dragWithHandle,
            greaterOrEq(abs(this.prevDragY), this.lastStartScrollY)
          ),
          set(this.prevTranslateYOffset, this.animationPosition)
        ),
        set(this.animationFinished, 1),
        set(this.translationY, 0),
        // Resetting appropriate values
        set(drawerOldGestureState, GestureState.END),
        set(handleOldGestureState, GestureState.END),
        // By forcing that frameTime exceeds duration, it has the effect of stopping the animation
        set(this.animationFrameTime, add(animationDuration, 1000)),
        set(this.velocityY, 0),
        stopClock(this.animationClock),
        this.prevTranslateYOffset,
      ],
      cond(
        or(
          this.didGestureFinish,
          this.isManuallySetValue,
          clockRunning(this.animationClock)
        ),
        [
          runAnimation({
            clock: this.animationClock,
            from: cond(
              this.isManuallySetValue,
              this.prevTranslateYOffset,
              add(this.prevTranslateYOffset, this.translationY)
            ),
            to: this.destSnapPoint,
            position: this.animationPosition,
            finished: this.animationFinished,
            frameTime: this.animationFrameTime,
            velocity: this.velocityY,
          }),
        ],
        [
          set(this.animationFrameTime, 0),
          set(this.animationFinished, 0),
          // @ts-ignore
          this.prevTranslateYOffset,
        ]
      )
    );

    this.translateY = interpolate(
      add(translateYOffset, this.dragY, multiply(scrollY, -1)),
      {
        inputRange: [openPosition, closedPosition],
        outputRange: [openPosition, closedPosition],
        extrapolate: Extrapolate.CLAMP,
      }
    );

    this.position = interpolate(this.translateY, {
      inputRange: [openPosition, snapPoints[snapPoints.length - 1]],
      outputRange: [1, 0],
      extrapolate: Extrapolate.CLAMP,
    });
  }
Example #23
Source File: SectionListExample.tsx    From react-native-scroll-bottom-sheet with MIT License 4 votes vote down vote up
SectionListExample: React.FC<Props> = () => {
  const snapPointsFromTop = [96, '45%', windowHeight - 264];
  const animatedPosition = React.useRef(new Value(0.5));
  const handleLeftRotate = concat(
    interpolate(animatedPosition.current, {
      inputRange: [0, 0.4, 1],
      outputRange: [25, 0, 0],
      extrapolate: Extrapolate.CLAMP,
    }),
    'deg'
  );
  const handleRightRotate = concat(
    interpolate(animatedPosition.current, {
      inputRange: [0, 0.4, 1],
      outputRange: [-25, 0, 0],
      extrapolate: Extrapolate.CLAMP,
    }),
    'deg'
  );
  const cardScale = interpolate(animatedPosition.current, {
    inputRange: [0, 0.6, 1],
    outputRange: [1, 1, 0.9],
    extrapolate: Extrapolate.CLAMP,
  });

  const renderSectionHeader = React.useCallback(
    ({ section }) => (
      <View style={styles.section}>
        <Text>{section.title}</Text>
      </View>
    ),
    []
  );

  const renderItem = React.useCallback(
    ({ item }) => <Transaction {...item} />,
    []
  );

  return (
    <View style={styles.container}>
      <View style={styles.balanceContainer}>
        <Text style={styles.poundSign}>£</Text>
        <Text style={styles.balance}>4,345</Text>
      </View>
      <ProgressBar
        style={styles.progressBar}
        progress={0.8}
        color={Colors.green600}
      />
      <Animated.Image
        source={require('../assets/card-front.png')}
        style={[styles.card, { transform: [{ scale: cardScale }] }]}
      />
      <View style={styles.row}>
        <View>
          <View style={styles.action}>
            <FontAwesome5 name="credit-card" size={24} color="black" />
          </View>
          <Text style={{ textAlign: 'center' }}>Account</Text>
        </View>
        <View>
          <View style={styles.action}>
            <FontAwesome5 name="eye" size={24} color="black" />
          </View>
          <Text style={{ textAlign: 'center' }}>Pin</Text>
        </View>
        <View>
          <View style={styles.action}>
            <Ionicons name="md-snow" size={24} color="black" />
          </View>
          <Text style={{ textAlign: 'center' }}>Freeze</Text>
        </View>
        <View>
          <View style={styles.action}>
            <FontAwesome5 name="plus" size={24} color="black" />
          </View>
          <Text style={{ textAlign: 'center' }}>Top up</Text>
        </View>
      </View>
      <ScrollBottomSheet<ListItemData>
        enableOverScroll
        removeClippedSubviews={Platform.OS === 'android' && sections.length > 0}
        componentType="SectionList"
        topInset={statusBarHeight + navBarHeight}
        animatedPosition={animatedPosition.current}
        snapPoints={snapPointsFromTop}
        initialSnapIndex={1}
        animationConfig={{
          easing: Easing.inOut(Easing.linear),
        }}
        renderHandle={() => (
          <Handle style={{ paddingVertical: 20, backgroundColor: '#F3F4F9' }}>
            <Animated.View
              style={[
                styles.handle,
                {
                  left: windowWidth / 2 - 20,
                  transform: [{ rotate: handleLeftRotate }],
                },
              ]}
            />
            <Animated.View
              style={[
                styles.handle,
                {
                  right: windowWidth / 2 - 20,
                  transform: [{ rotate: handleRightRotate }],
                },
              ]}
            />
          </Handle>
        )}
        contentContainerStyle={styles.contentContainerStyle}
        stickySectionHeadersEnabled
        sections={sections}
        keyExtractor={i => i.id}
        renderSectionHeader={renderSectionHeader}
        renderItem={renderItem}
      />
    </View>
  );
}