Skip to content

TextField - clearButton - fix animation #3136

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/components/textField/ClearButton.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, {useContext, useCallback, useMemo} from 'react';
import {StyleSheet} from 'react-native';
import {useAnimatedStyle, useSharedValue, withSpring} from 'react-native-reanimated';
import {useAnimatedStyle, useSharedValue, withTiming, Easing} from 'react-native-reanimated';
import {useDidUpdate} from '../../hooks';
import Assets from '../../assets';
import {Spacings, Colors} from '../../style';
Expand All @@ -10,28 +10,34 @@ import FieldContext from './FieldContext';
import {TextFieldProps} from './types';

const hitSlop = {top: 20, bottom: 20, left: 20, right: 20};
const NON_VISIBLE_POSITION = 100;
const NON_VISIBLE_POSITION = 18;
const VISIBLE_POSITION = 0;
const SPRING_ANIMATION_CONFIG = {velocity: 300, damping: 20, stiffness: 300, mass: 0.8};
const TIMING_CONFIG = {
duration: 200,
easing: Easing.bezier(0.33, 1, 0.68, 1)
};

const ClearButton = ({testID, onClear, onChangeText}: Pick<TextFieldProps, 'onClear' | 'testID' | 'onChangeText'>) => {
const {hasValue} = useContext(FieldContext);
const animatedValue = useSharedValue(hasValue ? VISIBLE_POSITION : NON_VISIBLE_POSITION);
const animatedOpacity = useSharedValue(hasValue ? 1 : 0);

// @ts-expect-error should be fixed in version 3.5 (https://github.com/software-mansion/react-native-reanimated/pull/4881)
const animatedStyle = useAnimatedStyle(() => {
return {
transform: [{translateX: animatedValue.value}, {translateY: 0}]
transform: [{translateY: animatedValue.value}, {translateX: 0}],
opacity: animatedOpacity.value
};
});

const style = useMemo(() => [styles.container, animatedStyle], [animatedStyle]);

const animate = useCallback(() => {
const toValue = hasValue ? VISIBLE_POSITION : NON_VISIBLE_POSITION;
animatedValue.value = withSpring(toValue, SPRING_ANIMATION_CONFIG);
animatedValue.value = withTiming(toValue, TIMING_CONFIG);
animatedOpacity.value = withTiming(hasValue ? 1 : 0, TIMING_CONFIG);
},
[animatedValue, hasValue]);
[animatedValue, animatedOpacity, hasValue]);

useDidUpdate(() => {
animate();
Expand Down