react-native-reanimated#useAnimatedGestureHandler TypeScript Examples

The following examples show how to use react-native-reanimated#useAnimatedGestureHandler. 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: Cursor.tsx    From react-native-wagmi-charts with MIT License 5 votes vote down vote up
export function LineChartCursor({
  children,
  type,
  ...props
}: LineChartCursorProps) {
  const { pathWidth: width, path } = React.useContext(
    LineChartDimensionsContext
  );
  const { currentX, currentIndex, isActive, data } = useLineChart();

  const parsedPath = React.useMemo(
    () => (path ? parse(path) : undefined),
    [path]
  );

  const onGestureEvent = useAnimatedGestureHandler<
    GestureEvent<LongPressGestureHandlerEventPayload>
  >({
    onActive: ({ x }) => {
      if (parsedPath) {
        const boundedX = x <= width ? x : width;
        isActive.value = true;
        currentX.value = boundedX;

        // on Web, we could drag the cursor to be negative, breaking it
        // so we clamp the index at 0 to fix it
        // https://github.com/coinjar/react-native-wagmi-charts/issues/24
        const minIndex = 0;
        const boundedIndex = Math.max(
          minIndex,
          Math.round(boundedX / width / (1 / (data.length - 1)))
        );

        currentIndex.value = boundedIndex;
      }
    },
    onEnd: () => {
      isActive.value = false;
      currentIndex.value = -1;
    },
  });

  return (
    <CursorContext.Provider value={{ type }}>
      <LongPressGestureHandler
        minDurationMs={0}
        maxDist={999999}
        onGestureEvent={onGestureEvent}
        {...props}
      >
        <Animated.View style={StyleSheet.absoluteFill}>
          {children}
        </Animated.View>
      </LongPressGestureHandler>
    </CursorContext.Provider>
  );
}
Example #2
Source File: Picker.tsx    From swiftui-react-native with MIT License 4 votes vote down vote up
Picker = ({
  children,
  selection,
  backgroundColor,
  opacity,
  frame,
  cornerRadius,
  scaleEffect,
  rotationEffect,
  padding,
  border,
  shadow,
  zIndex,
  style,
  alert,
  onChange,
  onAppear,
  onDisappear,
}: PickerProps) => {
  useAlert(alert);
  useLifecycle(onAppear, onDisappear);
  const colorScheme = useColorScheme();
  const childCount = Children.count(children);
  const [optionDimensions, setOptionDimensions] = useState(null);
  const tempSelection = useSharedValue(selection.value);
  const width = optionDimensions ? optionDimensions.width : 0;
  const slidePosition = useSharedValue(
    selectedToPosition(selection.value, width, childCount)
  );

  const sliderHeight = optionDimensions ? optionDimensions.height - 5 : 0;
  const sliderWidth = optionDimensions
    ? optionDimensions.width / childCount
    : 0;

  const animatedSliderStyle = useAnimatedStyle(() => {
    return {
      transform: [{ translateX: slidePosition.value }],
    };
  }, [slidePosition.value]);

  const gestureHandler = useAnimatedGestureHandler<
    PanGestureHandlerGestureEvent,
    GestureHandlerContext
  >({
    onStart: (_, ctx) => {
      ctx.offsetX = slidePosition.value;
    },
    onActive: (e, ctx) => {
      const currentXPos = e.translationX + ctx.offsetX;
      const optionWidth = width / childCount;
      const slideTo = clamp(
        Math.round((currentXPos - optionWidth / 2) / optionWidth) * optionWidth,
        0,
        (childCount - 1) * optionWidth
      );
      if (slideTo !== slidePosition.value) {
        slidePosition.value = withTiming(slideTo);
        tempSelection.value = positionToSelected(slideTo, width, childCount);
        console.log(tempSelection.value);
      }
    },
    onEnd: () => {
      const newValue = positionToSelected(
        slidePosition.value,
        width,
        childCount
      );

      runOnJS(selection.setValue)(newValue);
      if (onChange) {
        runOnJS(onChange)(newValue);
      }
    },
  });

  return (
    <Fragment>
      <View
        onLayout={(e) => setOptionDimensions(e.nativeEvent.layout)}
        style={[
          styles.container,
          {
            opacity,
            zIndex,
            backgroundColor: getColor(
              backgroundColor,
              colorScheme,
              'secondarySystemBackground'
            ),
            ...getCornerRadius(cornerRadius),
            ...getShadow(shadow),
            ...getPadding(padding),
            ...getFrame(frame),
            ...getBorder(border),
            ...getTransform(scaleEffect, rotationEffect),
          },
          style,
        ]}
      >
        <View style={styles.options}>
          {React.Children.map(children as ReactElement<any>, (child, i) => {
            const textChild =
              child?.type === Text
                ? cloneElement(child, { fontSize: 12, ...child.props })
                : child;
            return (
              <Fragment key={i}>
                <TouchableOpacity
                  style={[styles.option, { flexBasis: `${100 / childCount}%` }]}
                  disabled={selection.value === i}
                  onPress={() => {
                    slidePosition.value = withTiming(
                      selectedToPosition(i, width, childCount)
                    );
                    tempSelection.value = i;
                    runOnJS(selection.setValue)(i);
                    if (onChange) {
                      runOnJS(onChange)(i);
                    }
                  }}
                >
                  {textChild}
                </TouchableOpacity>
                <Divider
                  color={getColor('systemGray4', colorScheme)}
                  index={i}
                  selection={tempSelection.value}
                  childCount={childCount}
                />
              </Fragment>
            );
          })}
        </View>
        <Animated.View
          style={[
            styles.slider,
            animatedSliderStyle,
            {
              width: sliderWidth,
              height: sliderHeight,
              backgroundColor:
                colorScheme === 'dark'
                  ? getColor('secondarySystemBackground', 'dark')
                  : getColor('systemBackground', 'light'),
            },
          ]}
        />
      </View>

      <PanGestureHandler onGestureEvent={gestureHandler}>
        <Animated.View
          style={[
            styles.slider,
            animatedSliderStyle,
            {
              width: sliderWidth,
              height: sliderHeight,
              zIndex: 0,
              left: 10,
              top: 12,
            },
          ]}
        />
      </PanGestureHandler>
    </Fragment>
  );
}
Example #3
Source File: Slider.tsx    From swiftui-react-native with MIT License 4 votes vote down vote up
Slider: React.FC<SliderProps> = ({
  tint,
  trackTint,
  thumbTint,
  range = [0, 10],
  step = 1,
  value,
  updateOnSlide = true,
  frame,
  backgroundColor,
  style,
  padding,
  cornerRadius,
  rotationEffect,
  scaleEffect,
  shadow,
  border,
  opacity,
  zIndex,
  alert,
  onAppear,
  onDisappear,
  onChange,
}) => {
  useAlert(alert);
  useLifecycle(onAppear, onDisappear);
  const colorScheme = useColorScheme();
  const [sliderWidth, sliderHeight] = getSliderWidth(frame);
  const [from, through] = range;
  const midPoint = (through + from) / 2;
  const slope = (midPoint - from) / (sliderWidth / 2);

  const translateX = useSharedValue(
    value2Position(value.value, midPoint, slope)
  );

  useEffect(() => {
    const newPos = value2Position(value.value, midPoint, slope);
    translateX.value = withTiming(newPos);
  }, [value.value]);

  const animatedCursorStyle = useAnimatedStyle(() => {
    return {
      transform: [
        {
          translateX: translateX.value,
        },
      ],
    };
  });

  const animatedFillStyle = useAnimatedStyle(() => {
    return {
      width: translateX.value + sliderWidth / 2,
    };
  });

  const gestureHandler = useAnimatedGestureHandler<
    PanGestureHandlerGestureEvent,
    GestureHandlerContext
  >({
    onStart: (_, ctx) => {
      ctx.offsetX = translateX.value;
    },
    onActive: (e, ctx) => {
      const prevPos = translateX.value;
      const newPos = e.translationX + ctx.offsetX;
      if (newPos < sliderWidth / 2 && newPos > -sliderWidth / 2) {
        translateX.value = newPos;
        const prevVal = position2Value(prevPos, midPoint, slope, step);
        const newVal = position2Value(newPos, midPoint, slope, step);
        if (updateOnSlide && prevVal !== newVal) {
          runOnJS(value.setValue)(newVal);
          if (onChange) runOnJS(onChange)(newVal);
        }
      }
    },
    onEnd: () => {
      if (!updateOnSlide) {
        const newVal = position2Value(translateX.value, midPoint, slope, step);
        runOnJS(value.setValue)(newVal);
        if (onChange) runOnJS(onChange)(newVal);
      }
    },
  });

  return (
    <View
      style={[
        {
          opacity,
          zIndex,
          backgroundColor: getColor(backgroundColor, colorScheme),
          ...getCornerRadius(cornerRadius),
          ...getPadding(padding),
          ...getBorder(border),
          ...getShadow(shadow),
          ...getTransform(scaleEffect, rotationEffect),
        },
        style,
      ]}
    >
      <View
        style={[
          styles.slider,
          {
            width: sliderWidth,
            height: sliderHeight,
            marginTop: CIRCLE_WIDTH / 2,
            marginBottom: CIRCLE_WIDTH / 2,
            backgroundColor: getColor(trackTint, colorScheme, 'systemGray4'),
          },
        ]}
      >
        <Animated.View
          style={[
            {
              height: sliderHeight,
              borderRadius: 10,
              backgroundColor: getColor(tint, colorScheme, 'systemBlue'),
            },
            animatedFillStyle,
          ]}
        />
        <PanGestureHandler onGestureEvent={gestureHandler}>
          <Animated.View
            style={[
              styles.cursor,
              {
                left: sliderWidth / 2 - CIRCLE_WIDTH / 2,
                top: -CIRCLE_WIDTH / 2,
                height: CIRCLE_WIDTH,
                width: CIRCLE_WIDTH,
                backgroundColor: getColor(thumbTint, colorScheme, '#fff'),
              },
              animatedCursorStyle,
            ]}
          />
        </PanGestureHandler>
      </View>
    </View>
  );
}
Example #4
Source File: Crosshair.tsx    From react-native-wagmi-charts with MIT License 4 votes vote down vote up
export function CandlestickChartCrosshair({
  color,
  onCurrentXChange,
  children,
  horizontalCrosshairProps = {},
  verticalCrosshairProps = {},
  lineProps = {},
  ...props
}: CandlestickChartCrosshairProps) {
  const { width, height } = React.useContext(CandlestickChartDimensionsContext);
  const { currentX, currentY, step } = useCandlestickChart();

  const tooltipPosition = useSharedValue<'left' | 'right'>('left');

  const opacity = useSharedValue(0);
  const onGestureEvent = useAnimatedGestureHandler<
    GestureEvent<LongPressGestureHandlerEventPayload>
  >({
    onActive: ({ x, y }) => {
      const boundedX = x <= width - 1 ? x : width - 1;
      if (boundedX < 100) {
        tooltipPosition.value = 'right';
      } else {
        tooltipPosition.value = 'left';
      }
      opacity.value = 1;
      currentY.value = clamp(y, 0, height);
      currentX.value = boundedX - (boundedX % step) + step / 2;
    },
    onEnd: () => {
      opacity.value = 0;
      currentY.value = -1;
      currentX.value = -1;
    },
  });
  const horizontal = useAnimatedStyle(() => ({
    opacity: opacity.value,
    transform: [{ translateY: currentY.value }],
  }));
  const vertical = useAnimatedStyle(() => ({
    opacity: opacity.value,
    transform: [{ translateX: currentX.value }],
  }));

  useAnimatedReaction(
    () => currentX.value,
    (data, prevData) => {
      if (data !== -1 && data !== prevData && onCurrentXChange) {
        runOnJS(onCurrentXChange)(data);
      }
    }
  );

  return (
    <LongPressGestureHandler
      minDurationMs={0}
      maxDist={999999}
      onGestureEvent={onGestureEvent}
      {...props}
    >
      <Animated.View style={StyleSheet.absoluteFill}>
        <Animated.View
          style={[StyleSheet.absoluteFill, horizontal]}
          {...horizontalCrosshairProps}
        >
          <CandlestickChartLine color={color} x={width} y={0} {...lineProps} />
          <CandlestickChartCrosshairTooltipContext.Provider
            value={{ position: tooltipPosition }}
          >
            {children}
          </CandlestickChartCrosshairTooltipContext.Provider>
        </Animated.View>
        <Animated.View
          style={[StyleSheet.absoluteFill, vertical]}
          {...verticalCrosshairProps}
        >
          <CandlestickChartLine color={color} x={0} y={height} {...lineProps} />
        </Animated.View>
      </Animated.View>
    </LongPressGestureHandler>
  );
}