Skip to content
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

Add KeyboardAvoidingView #4339

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
2 changes: 1 addition & 1 deletion app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ function findExamples(search: string) {
}

function HomeScreen({ navigation }: HomeScreenProps) {
const [search, setSearch] = React.useState('');
const [search, setSearch] = React.useState('KeyboardAvoidingView');

React.useLayoutEffect(() => {
navigation.setOptions({
Expand Down
251 changes: 251 additions & 0 deletions app/src/examples/KeyboardAvoidingViewExample.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,251 @@
import Animated, {
KeyboardState,
// runOnJS,
// runOnUI,
useAnimatedKeyboard,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
} from 'react-native-reanimated';
import {
FlatList,
Modal,
Pressable,
ScrollView,
ScrollViewProps,
StyleSheet,
Switch,
Text,
TextInput,
View,
KeyboardAvoidingView as RNKeyboardAvoidingView,
} from 'react-native';
import React, { useCallback, useState } from 'react';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { TouchableOpacity } from 'react-native-gesture-handler';

function ListItem({
title,
onLongPress,
}: {
title: string;
onLongPress: () => void;
}) {
return (
<TouchableOpacity onLongPress={onLongPress}>
<View style={styles.item}>
<Text>Open keyboard and long press on message number {title}</Text>
</View>
</TouchableOpacity>
);
}

function KeyboardSpace({
// modalVisible,
children,
...props
}: ScrollViewProps & {
modalVisible?: Animated.SharedValue<boolean>;
children: React.ReactNode;
}) {
const keyboard = useAnimatedKeyboard();

const [ctx] = useState({
lastHeight: 0,
keyboardWasOpen: false,
});

const translateY = useDerivedValue(() => {
const { height, state } = keyboard;

if (state.value === KeyboardState.OPEN) {
ctx.lastHeight = height.value;
}

console.log(
'height',
height.value,
'ctx.lastHeight',
ctx.lastHeight,
'state.value',
state.value
);

if (state.value === KeyboardState.CLOSED) {
return Math.max(ctx.lastHeight - 17, 0);
}

return 0;
});

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

return (
<ScrollView {...props}>
<Animated.View style={[{ flex: 1 }, animatedStyle]}>
{children}
</Animated.View>
</ScrollView>
);
}

export default function KeyboardAvoidingViewExample(): React.ReactElement {
const insets = useSafeAreaInsets();

const [useReanimated, setUseReanimated] = useState(true);

const [isModalVisible, setIsModalVisible] = useState(false);
const modalVisible = useSharedValue(false);

const showModal = useCallback(() => {
// runOnUI(() => {
// 'worklet';

// modalVisible.value = true;

// runOnJS(setIsModalVisible)(true);
// })();

setIsModalVisible(true);
}, [setIsModalVisible]);

const hideModal = useCallback(() => {
// runOnUI(() => {
// 'worklet';

// modalVisible.value = false;

// runOnJS(setIsModalVisible)(false);
// })();

setIsModalVisible(false);
}, [setIsModalVisible]);

const renderScrollComponent = useCallback(
(props: ScrollViewProps) => {
// @ts-expect-error
return <KeyboardSpace {...props} modalVisible={modalVisible} />;
},
[modalVisible]
);

const KeyboardAvoidingView = useReanimated
? // @ts-expect-error
Animated.KeyboardAvoidingView
: RNKeyboardAvoidingView;

return (
<View style={[styles.container]}>
<View style={styles.header}>
<Text>Use Reanimated KeyboardAvoidingView</Text>
<Switch
value={useReanimated}
onChange={(evt) => setUseReanimated(evt.nativeEvent.value)}
/>
</View>

<FlatList
inverted
renderScrollComponent={renderScrollComponent}
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="always"
data={Array.from({ length: 20 }).map((_, i) => i)}
renderItem={({ item }) => (
<ListItem onLongPress={showModal} title={`Item ${item}`} />
)}
/>

<KeyboardAvoidingView
behavior="padding"
keyboardVerticalOffset={40 + insets.bottom}>
<View
style={{
paddingBottom: insets.bottom,
}}>
<TextInput
placeholder="Message here..."
style={[styles.textInput]}
autoCorrect
/>
</View>
</KeyboardAvoidingView>

<Modal
style={styles.sheetContainer}
visible={isModalVisible}
Copy link
Member

@tomekzaw tomekzaw Apr 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @terrysahaidak, I've tested your example with the PR #4360.

If you look closely, there's still some flickering when opening the modal and it happens both with Reanimated's and React Native's KeyboardAvoidingView:

KeyboardAvoidingView from Reanimated
reanimated.mp4
KeyboardAvoidingView from React Native
react.native.mp4

I believe the root cause of this flicker is not the implementation of useAnimatedKeyboard hook but rather the fact that the visibility of <Modal> component is controlled using React state whereas the other part of the logic uses a shared value. In particular, there are two sources of truth and it takes 1-2 frames to render the changes from the JS thread when the React state is updated:

const [isModalVisible, setIsModalVisible] = useState(false);
const modalVisible = useSharedValue(false);

Instead, you should keep the state only in shared value and control the visibility of the modal via animated props on the UI thread:

import Animated, { useAnimatedProps } from 'react-native-reanimated';

const AnimatedModal = Animated.createAnimatedComponent(Modal);

const animatedProps = useAnimatedProps(() => {
  return { visible: isModalVisible.value };
});

return <AnimatedModal {/* props */} animatedProps={animatedProps} />;

Edit: looks like visible prop is available only on iOS, on Android it's implemented on JS side

transparent
animationType="none">
<Pressable style={styles.sheetBackdrop} onPress={hideModal} />

<View style={styles.sheet}>
<Text style={styles.sheetText}>
This modal should cover the keyboard, but the latest message should
be in the same place.
</Text>
</View>
</Modal>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 40,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: 'rgba(29, 28, 29, 0.13)',
},
item: {
paddingHorizontal: 20,
paddingVertical: 20,
borderTopWidth: 1,
marginHorizontal: 20,
borderColor: 'rgba(29, 28, 29, 0.13)',
},
textInput: {
borderColor: 'rgba(29, 28, 29, 0.13)',
borderStyle: 'solid',
borderWidth: 1,
height: 48,
borderRadius: 20,
marginHorizontal: 20,
paddingHorizontal: 20,
},
sheetContainer: {
flex: 1,
backgroundColor: 'transparent',
},
sheet: {
borderColor: 'rgba(29, 28, 29, 0.13)',
borderWidth: 1,
backgroundColor: 'white',
height: 300,
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
borderTopLeftRadius: 20,
borderTopRightRadius: 20,
padding: 20,
},
sheetBackdrop: {
...StyleSheet.absoluteFillObject,
backgroundColor: 'rgba(0, 0, 0, 0.2)',
},
sheetText: {
fontSize: 20,
},
});
6 changes: 6 additions & 0 deletions app/src/examples/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import IPodExample from './IPodExample';
import ImageStackExample from './SharedElementTransitions/ImageStack';
import InvertedFlatListExample from './InvertedFlatListExample';
import KeyframeAnimation from './LayoutAnimations/KeyframeAnimation';
import KeyboardAvoidingViewExample from './KeyboardAvoidingViewExample';
import LayoutAnimationExample from './SharedElementTransitions/LayoutAnimation';
import LightBoxExample from './LightBoxExample';
import LiquidSwipe from './LiquidSwipe/LiquidSwipe';
Expand Down Expand Up @@ -187,6 +188,11 @@ export const EXAMPLES: Record<string, Example> = {
title: 'Bouncing box',
screen: BouncingBoxExample,
},
KeyboardAvoidingViewExample: {
icon: '⌨️',
title: 'KeyboardAvoidingView',
screen: KeyboardAvoidingViewExample,
},
AnimatedKeyboardExample: {
icon: '⌨️',
title: 'useAnimatedKeyboard',
Expand Down
1 change: 1 addition & 0 deletions src/Animated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export { default as View } from './reanimated2/component/View';
export { default as ScrollView } from './reanimated2/component/ScrollView';
export { default as Image } from './reanimated2/component/Image';
export { default as FlatList } from './reanimated2/component/FlatList';
export { default as KeyboardAvoidingView } from './reanimated2/component/KeyboardAvoidingView';
Loading