Skip to content

Commit

Permalink
fix: interactive keyboard example
Browse files Browse the repository at this point in the history
  • Loading branch information
kirillzyusko committed Mar 12, 2024
1 parent 1bc01fe commit 0af2c7d
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions example/src/screens/Examples/InteractiveKeyboardIOS/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { useCallback, useRef } from "react";
import { TextInput, View } from "react-native";
import { useKeyboardHandler } from "react-native-keyboard-controller";
import Reanimated, {
useAnimatedProps,
useAnimatedScrollHandler,
useAnimatedStyle,
useSharedValue,
} from "react-native-reanimated";
Expand All @@ -16,7 +18,11 @@ const AnimatedTextInput = Reanimated.createAnimatedComponent(TextInput);
const useKeyboardAnimation = () => {
const progress = useSharedValue(0);
const height = useSharedValue(0);
const inset = useSharedValue(0);
const offset = useSharedValue(0);
const scroll = useSharedValue(0);
const shouldUseOnMoveHandler = useSharedValue(false);

useKeyboardHandler({
onStart: (e) => {
"worklet";
Expand All @@ -32,6 +38,10 @@ const useKeyboardAnimation = () => {

progress.value = e.progress;
height.value = e.height;

inset.value = e.height;
// Math.max is needed to prevent overscroll when keyboard hides (and user scrolled to the top, for example)
offset.value = Math.max(e.height + scroll.value, 0);
},
onInteractive: (e) => {
"worklet";
Expand All @@ -56,7 +66,13 @@ const useKeyboardAnimation = () => {
},
});

return { height, progress };
const onScroll = useAnimatedScrollHandler({
onScroll: (e) => {
scroll.value = e.contentOffset.y - inset.value;
},
});

return { height, progress, onScroll, inset, offset };
};

const TEXT_INPUT_HEIGHT = 50;
Expand All @@ -67,7 +83,7 @@ const contentContainerStyle = {

function InteractiveKeyboard() {
const ref = useRef<Reanimated.ScrollView>(null);
const { height } = useKeyboardAnimation();
const { height, onScroll, inset, offset } = useKeyboardAnimation();

const scrollToBottom = useCallback(() => {
ref.current?.scrollToEnd({ animated: false });
Expand All @@ -84,14 +100,26 @@ function InteractiveKeyboard() {
[],
);

const props = useAnimatedProps(() => ({
contentInset: {
bottom: inset.value,
},
contentOffset: {
x: 0,
y: offset.value,
},
}));

return (
<View style={styles.container}>
<Reanimated.ScrollView
ref={ref}
onContentSizeChange={scrollToBottom}
contentContainerStyle={contentContainerStyle}
keyboardDismissMode="interactive"
automaticallyAdjustKeyboardInsets
animatedProps={props}
onScroll={onScroll}
// automaticallyAdjustKeyboardInsets
automaticallyAdjustContentInsets={false}
contentInsetAdjustmentBehavior="never"
>
Expand Down

0 comments on commit 0af2c7d

Please sign in to comment.