gorhom / react-native-bottom-sheet

A performant interactive bottom sheet with fully configurable options 🚀
https://gorhom.dev/react-native-bottom-sheet/
MIT License
7.13k stars 779 forks source link

[v4] | Keyboard causing bottom-sheet to close down completely when using enableDynamicSizing (Android only) #1602

Open anurbecirovic opened 1 year ago

anurbecirovic commented 1 year ago

Bug

I've recently refactored old logic behind the bottom sheet modal since I used useBottomSheetDynamicSnapPoints and changed it to enableDynamicSizing. Everything is working fine but when using with Input Field the bottom-sheet is closing only on Android larger devices.

Changing the keyboardBehavior: 'interactive' to: keyboardBehavior={Platform.OS === 'ios' ? 'interactive' : 'fillParent'} made unwanted closing to go away but now the modal doesn't look really good since it will take up whole screen. Ideally I want to have modal just above the keyboard, something that I had before with older logic.

The linked issue but without using enableDynamicSizing is here it's same now for me since 'interactive' doesn't work.

Environment info

Library Version
@gorhom/bottom-sheet 4.5.1
react-native 0.72.4
react-native-reanimated 3.5.2
react-native-gesture-handler 2.12.1

Steps To Reproduce

  1. Using enableDynamicSizing
  2. Add these properties:
     keyboardBehavior='interactive'
      keyboardBlurBehavior='restore'
      android_keyboardInputMode='adjustResize'
  3. Add input field inside the Bottom Sheet modal
  4. Open the bottom sheet and try to enter something.
  5. FYI: I also tried the: BottomSheetTextInput and regular input

Describe what you expected to happen:

  1. Open the keyboard bellow the modal.
  2. Render modal above the keyboard same as it's onIOS devices

When I added logging before closing down I get this in console:

LOG [BottomSheetContainer::handleContainerLayout] height:779.8095092773438 LOG [BottomSheetModal::handleDismiss] currentIndexRef:0 minimized:false LOG [BottomSheetModal::handleDismiss] currentIndexRef:0 minimized:false LOG [BottomSheetModal::handleDismiss] currentIndexRef:-1 minimized:false LOG [BottomSheetModal::handleDismiss] currentIndexRef:-1 minimized:false LOG [BottomSheetModal::handleDismiss] currentIndexRef:1 minimized:false

Not sure if info can be used for debugging. 🤔

Reproducible sample code

 <BottomSheetModal
      ref={bottomSheetModalRef}
      enableDynamicSizing
      onDismiss={handleDismiss}
      enablePanDownToClose={dismissOnPanDown}
      backdropComponent={renderBackdrop}
      backgroundComponent={backgroundComponent}
      keyboardBehavior='interactive'
      keyboardBlurBehavior='restore'
      android_keyboardInputMode='adjustResize'
      handleIndicatorStyle={!dismissOnPanDown && styles.handleIndicator}
      {...rest}
    >
      <BottomSheetScrollView
        contentContainerStyle={[
          styles.scrollViewContainer,
          styleScrollViewContent,
        ]}
        keyboardDismissMode='on-drag'
        bounces={bounces}
        keyboardShouldPersistTaps='handled'
        showsVerticalScrollIndicator={false}
      >
        <BottomSheetView
          style={[styles.container, styleContainer]}
        >
          {children} // <---- HERE I HAVE INPUT FIELD
        </BottomSheetView>
        <KeyboardHeight />
      </BottomSheetScrollView>
    </BottomSheetModal>

Any help would be amazing. 🙏

ajsmth commented 1 year ago

I've run into this same issue without the new dynamic sizing API as well - from what I can tell the internal animated index is being set to -1 which leads to the sheet closing. Here are the logs I've found that might be helpful, but I haven't been able to fix this after poking around the codebase:

image
jamiefrew commented 1 year ago

Having the same issue 😢

ivoneug commented 1 year ago

We have the same issue

dibyopra commented 1 year ago

same issue, it will close when height of bottom sheet is to low note: only on BottomSheetModal

z1haze commented 1 year ago

I have this same issue! It seems to only be an issue on android. When monitoring the onChange handler of the BottomSheetModal, when opening the keyboard using "interactor" behavior, the index goes to -1, then back to 0, where as on ios, opening the keyboard does not trigger the onChange and therefore no issues arise.

I've also found that if you do not use dynamic sizing, and specify a rather tall snappoint, it does not occur, but that sort of defeats the purpose of automatic sizing, and having the keyboard push the modal up just far enough to fit in the keyboard.

mangeshkchauhan commented 1 year ago

Use BottomSheetTextInput instead of TextInput from react native to fix this.

anurbecirovic commented 1 year ago

hey @mangeshkchauhan. As I mentioned above, using the BottomSheetTextInput doesn't fix the problem :/

z1haze commented 1 year ago

Correct, it doesn't fix the issue.

calebpanza commented 1 year ago

Running into this same issue atm. Anyone have a solution for it?

markymc commented 11 months ago

I've also just seen this issue. For me, setting keyboardBehavior={Platform.OS === 'ios' ? 'interactive' : 'fillParent'} didn't seem to help... will keep looking into it.

junchenjun commented 11 months ago

Same issue here. The problem for is not even about the enableDynamicSizing. As long as the height of the modal is too low, it closes itself upon opening the keyboard. This includes the snapoints.

BottomSheetTextInput doesn't fix it neither.

mhsfh commented 11 months ago

i have same issue

mhsfh commented 11 months ago

I could fix this by adding enableDismissOnClose={false} to BottomSheetModal

Otherwise, you need to put the minHeight of the content more than the keyboard height

Edit: you will have a small problem when you set enableDismissOnClose to false, the keyboard won't be dismissed when you close the bottom sheet you can fix it by adding this callback to onChange:

import debounce from 'lodash/debounce';

const debouncedOnChange = debounce((index) => {
  if (index === -1) {
    Keyboard.dismiss();
  }
}, 10);
dealvz commented 11 months ago

I could fix this by adding enableDismissOnClose={false} to BottomSheetModal

Otherwise, you need to put the minHeight of the content more than the keyboard height

@mhsfh this does work, however if you're using the backdropComponent prop then that component will remain. I tried to just work around this by implementing my own backdrop component but I can't get the modal to show again if im using enableDismissOnClose={false}

Guess I'll have to use the larger snap point.

mhsfh commented 11 months ago

@dealvz that's how I'm closing and opening the bottom sheet:

const handleOpen = React.useCallback((): void => {
      Keyboard.dismiss();
      bottomSheetRef?.current?.present();
      bottomSheetRef?.current?.expand();
      if (Platform.OS === 'ios') KeyboardManager.setEnable(false);
    }, []);

     const handleClose = React.useCallback((): void => {
      bottomSheetRef?.current?.close();
      if (Platform.OS === 'ios') KeyboardManager.setEnable(true);
    }, []);

and by the way, you will have a small problem when you set enableDismissOnClose to false, the keyboard won't be dismissed when you close the bottom sheet you can fix it by adding this callback to onChange:

    import debounce from 'lodash/debounce';
    const debouncedOnChange = debounce((index) => {
  if (index === -1) {
    Keyboard.dismiss();
  }
}, 10);
victorkvarghese commented 11 months ago

I have same issue with and without enableDynamicSizing. Bottom sheet get dismissed when keyboard is opened in Android.

Any workarounds ?

@gorhom any workaround would be helpful.

gorhom commented 11 months ago

let me have a look

gorhom commented 11 months ago

could someone provide a repo using Expo Snack: https://snack.expo.io/@gorhom/bottom-sheet-v4-reproducible-issue-template

mhsfh commented 11 months ago

I have same issue with and without enableDynamicSizing. Bottom sheet get dismissed when keyboard is opened in Android.

Any workarounds ?

@gorhom any workaround would be helpful.

@victorkvarghese enableDynamicSizing is by default true so you need to set it manually to false, did you do that?

gorhom commented 11 months ago

tested it , and it did not dismiss.

while you are here, could you test this issue against v5

mhsfh commented 11 months ago

tested it , and it did not dismiss.

while you are here, could you test this issue against v5

@gorhom I couldn't reproduce the bug in 5.0.0-alpha.5 but in "^4.5.1" it exist

<BottomSheetModal
keyboardBehavior="interactive"
        keyboardBlurBehavior="restore"
        android_keyboardInputMode="adjustResize"
        ...
zguo123 commented 11 months ago

I have "expo": "^49.0.21" which is preventing me from installing v.5.0.0

johnnywang commented 11 months ago

Here to report the same/similar issue, except I'm seeing it in both Android AND iOS, and can confirm that it seems to only happen when dynamic sizing is enabled. I will note that the UI does not auto-dismiss unless I have some custom onAnimate code in place, which is necessary for us to pop the nav stack:

  const handleAnimationChange = useCallback((fromIndex: number, toIndex: number) => {
    console.log('--------from: ', fromIndex);
    console.log('--------to: ', toIndex);
    if (fromIndex !== -1 && toIndex <= 0) {
      navigation.pop();
    }
  }, []);

  <BottomSheet
      animationConfigs={hasInput ? undefined : animationConfigs}
      backdropComponent={renderBackdrop}
      backgroundStyle={styles.drawerContainer}
      contentHeight={Dimensions.get('screen').height}
      enableDynamicSizing
      enablePanDownToClose={fullyMounted}
      handleComponent={null}
      keyboardBlurBehavior="restore"
      onAnimate={handleAnimationChange}
      onChange={handleIndexChange}
      ref={bottomSheetRef}
    >
    <BottomSheetTextInput />
  </>

This seems to happen directly as a result of incorrect indices when the keyboard first appears, but only if it's brought up AFTER the bottom sheet has finished rendering/expanding/animating. So either it's brought up manually by tapping into a non-autofocused text input, or in the case of an autofocused input, after the keyboard is dismissed (i.e. in Android) and then brought back by tapping the input field again.

As others have mentioned, this seems to be a result of the onAnimate index unexpectedly going from 0 to -1 when the keyboard is brought up, which triggers our close handler above. It looks like this has also been previously reported in an issue that was auto-closed: https://github.com/gorhom/react-native-bottom-sheet/issues/1441

could someone provide a repo using Expo Snack: https://snack.expo.io/@gorhom/bottom-sheet-v4-reproducible-issue-template

@gorhom I tried to create a repro but was unable to even get the template snack to work: it seems to fail on a workletInit function missing, and some Googling suggested using a polyfill, which resulted in the app crashing. This was as far as I was able to diagnose, but I was not able to get that working: https://snack.expo.dev/@jwalt/bottom-sheet-v4-reproducible-issue-template

victorkvarghese commented 11 months ago

I am using 4.5.1. and enableDynamicSizing={true} is required, otherwise the sheet will break in small devices. Will try upgrading to latest versions

I had to wrap the view in BottomSheetView to make it visible with enableDynamicSizing={true}.

`

<BottomSheetModal
  ref={reusableBottomSheetModalRef}
  index={0}
  backdropComponent={renderBackdrop}
  enablePanDownToClose={false}
  enableDynamicSizing
  contentHeight={animatedContentHeight}
  android_keyboardInputMode="adjustResize"
  keyboardBehavior="interactive"
  keyboardBlurBehavior="restore"
  maxDynamicContentSize={Dimensions.get('window').height - 48}      onChange={handleSheetChanges}>
  <Suspense fallback={<CustomLoader />}>
    <BottomSheetView style={{ paddingBottom: insets.bottom }}> 
    {getBottomSheetView(bottomSheetProps.type)}
    </BottomSheetView> 
  </Suspense>
</BottomSheetModal>

`

EDIT: upgrading to latest v5 aplha version, keyboard is not dismissing in android.

mihalcinD commented 10 months ago

Having same issue :(

stephenjarrett commented 10 months ago

Having same issue with enableDynamicSizing on android. Did try upgrading to 5.0.0-alpha but was still seeing this issue.

DenianFossatti commented 10 months ago

For people trying to replace the enableDismissOnClose param in version 5.0.0-alpha.6 I was able to make it work using the cancel method of the debounce return. I used a hook instead that handles it. With that, I make the keyboard close when the index is -1, and with the debounce cancel method, it resolves the issue mentioned on #1441.

The relevant parts

const debouncedOnChange = useDebounce((index: number) => {
      if (index === -1) {
        Keyboard.dismiss()
      }
    }, 50)

<BottomSheet
        index={-1}
        enableDynamicSizing={false}
        snapPoints={['50%']}
        keyboardBehavior="interactive"
        enableHandlePanningGesture
        keyboardBlurBehavior="restore"
        android_keyboardInputMode="adjustResize"
        onChange={debouncedOnChange}
        ...

useDebounce.ts

import debounce from 'lodash/debounce'
import { useEffect, useMemo, useRef } from 'react'

export const useDebounce = (func: any, wait: number) => {
  const throttle = useRef<any>()

  useEffect(() => {
    const debounced = debounce(func, wait, { leading: false })
    throttle.current = debounced

    return () => {
      debounced.cancel()
    }
  }, [func, wait])

  return useMemo(() => {
    const callback = (...args: any[]) => {
      return throttle.current(...args)
    }

    callback.cancel = () => {
      if (throttle.current) {
        throttle.current.cancel()
      }
    }

    callback.flush = () => {
      if (throttle.current) {
        throttle.current.flush()
      }
    }

    return callback
  }, [])
}
apetta commented 10 months ago

I'm also facing this issue at the moment on Android. The problem seems to stem from the fact that the content height is smaller than the keyboard height - regardless of whether you're using snap points or dynamic height. Setting the content height higher is, of course, a straightforward solution.

Alternatively, as @mhsfh mentioned, you can fix this by setting enableDismissOnClose={false}, but it has drawbacks as mentioned above.

Here is a slightly hacky workaround that should do the trick without interfering with the dismissal:

import {
  BottomSheetModal,
  BottomSheetBackdrop,
} from "@gorhom/bottom-sheet";
// ...
//...
  const [keyboardOpen, setKeyboardOpen] = useState(false);
  const [enableDismissOnClose, setEnableDismissOnClose] = useState(true);

  useEffect(() => {
    if (Platform.OS !== 'android') return;

    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => setKeyboardOpen(true),
    );

    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => setKeyboardOpen(false),
    );

    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

  useEffect(() => {
    if (keyboardOpen) {
      setEnableDismissOnClose(false);
    }
  }, [keyboardOpen]);

  useEffect(() => {
    if (!enableDismissOnClose && keyboardOpen) {
      setTimeout(() => {
        setEnableDismissOnClose(true);
      }, 10);
    }
  }, [enableDismissOnClose, keyboardOpen]);

  return (
    <BottomSheetModal
      // ... other props
      index={0}
      android_keyboardInputMode="adjustResize"
      keyboardBlurBehavior="restore"
      enableDismissOnClose={enableDismissOnClose}
      backdropComponent={(props) => (
        <BottomSheetBackdrop
          {...props}
          appearsOnIndex={0}
          disappearsOnIndex={-1}
        />
      )}

    >
      {children}
    </BottomSheetModal>
  );
//...

This works well for dynamic height content. For snap points, it works but I've found the keyboard height to obscure quite a lot of the content. So I would recommend snapping to full height on input focus instead if that works for your use case.

EDIT: @ssomarii thanks for pointing out the backdropComponent, I've added that from my approach above

ssomarii commented 10 months ago

Sooo, I've tried a solution from @apetta above and it didn't work for me (idk why...), but with some changes it works!

I added code from useEffect with setEnableDismissOnClose(true) and timer in some pressable component for "backdropComponent" prop:

  <BottomSheetModal
    enableDismissOnClose={enableDismissOnClose}
    ref={bottomSheetRef}
    snapPoints={snapPoints}
    enableDynamicSizing={enableDynamicSizing}
    backdropComponent={() => (
      <BackdropBottomSheetModal
        onPress={() => {
          if (!enableDismissOnClose && keyboardOpen) {
            setEnableDismissOnClose(true);
          }
          bottomSheetRef.current?.dismiss();
        }}
      />
    )}>
      {children}
  </BottomSheetModal>

const BackdropBottomSheetModal: FC<IPropsBackground> = observer(
  ({onPress = () => {}}) => (
    <Pressable onPress={onPress} />
  ),
);

And in the solution I changed this useEffect:

 useEffect(() => {
  if (keyboardOpen) {
    setEnableDismissOnClose(false);
  }
}, [keyboardOpen]);

to this:

   useEffect(() => {
    setEnableDismissOnClose(!keyboardOpen);
  }, [keyboardOpen]);
apetta commented 10 months ago

Sooo, I've tried a solution from @apetta above and it didn't work for me (idk why...), but with some changes it works!

I added code from useEffect with setEnableDismissOnClose(true) and timer in some pressable component for "backdropComponent" prop:

  <BottomSheetModal
    enableDismissOnClose={enableDismissOnClose}
    ref={bottomSheetRef}
    snapPoints={snapPoints}
    enableDynamicSizing={enableDynamicSizing}
    backdropComponent={() => (
      <BackdropBottomSheetModal
        onPress={() => {
          if (!enableDismissOnClose && keyboardOpen) {
            setEnableDismissOnClose(true);
          }
          bottomSheetRef.current?.dismiss();
        }}
      />
    )}>
      {children}
  </BottomSheetModal>

const BackdropBottomSheetModal: FC<IPropsBackground> = observer(
  ({onPress = () => {}}) => (
    <Pressable onPress={onPress} />
  ),
);

And in the solution I changed this useEffect:

 useEffect(() => {
  if (keyboardOpen) {
    setEnableDismissOnClose(false);
  }
}, [keyboardOpen]);

to this:

   useEffect(() => {
    setEnableDismissOnClose(!keyboardOpen);
  }, [keyboardOpen]);

@ssomarii Glad you got it working! I forgot to include the backdrop component in my previous comment, not sure if that's what was missing

badalsaibo commented 10 months ago

Can confirm this bug. Happens when the content height is short.

Adding some video for reference:

Normal behaviour where the sheet content height is big enough

https://github.com/gorhom/react-native-bottom-sheet/assets/14058003/695af348-278b-41a6-a8bf-6a74789b4964

Buggy behaviour where the sheet content height is small

https://github.com/gorhom/react-native-bottom-sheet/assets/14058003/c7aaa2c4-e74d-479d-b0e4-6a3301e3fb16

Fix as stated by @apetta and @ssomarii


  const bottomSheetModalRef = useRef();
  const [keyboardOpen, setKeyboardOpen] = useState(false);
  const [enableDismissOnClose, setEnableDismissOnClose] = useState(true);

  const renderBackdrop = useCallback(
    (props: any) => (
      <CustomBackdrop
        {...props}
        onPress={() => {
          if (!enableDismissOnClose && keyboardOpen) {
            setEnableDismissOnClose(true);
          }
          bottomSheetModalRef.current?.close();
        }}
      />
    ),
    [enableDismissOnClose, handleClose, keyboardOpen],
  );

  useEffect(() => {
    if (Platform.OS !== 'android') return;

    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => setKeyboardOpen(true),
    );

    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => setKeyboardOpen(false),
    );

    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);

  useEffect(() => {
    setEnableDismissOnClose(!keyboardOpen);
  }, [keyboardOpen]);

  return (
        <BottomSheetModal 
            ref={bottomSheetModalRef}
            enableDynamicSizing
            enableDismissOnClose={enableDismissOnClose} 
            backdropComponent={renderBackdrop}

         >
            {/* your content */}
        </BottomSheetModal>
  )
RakiroxFemsa commented 9 months ago

Is this issue being resolved in any alpha tag or pr ?

fab-nikhil commented 9 months ago

Facing this issue on Android

mmehul commented 9 months ago

same issue happening in my android also.

badalsaibo commented 9 months ago

Related with #1356

jgillick commented 8 months ago

could someone provide a repo using Expo Snack: https://snack.expo.io/@gorhom/bottom-sheet-v4-reproducible-issue-template

@gorhom Here's a minium reproducible snack: https://snack.expo.dev/@jeremyplura/bottom-sheet-v4-reproducible-issue-template

jgillick commented 8 months ago

In this snack, even setting explicit snap points doesn't fix the issue:

const snapPoints = useMemo(() => [200], []);

<BottomSheetModal
  ref={bottomSheetRef}
  snapPoints={snapPoints}
>
RoyalBosS-Ayush commented 7 months ago

Facing Same. Any Solution?

andreknieriem commented 7 months ago

Ah I just came here, because I thought I am doing something wrong. Happens to me too. Will try out some solutions too.

Mirthis commented 7 months ago

Same issue here. It doesn't look like having enableDynamicSizing make a difference and the issue is there regardless if the bottom sheet height is too small (I guess smaller than the keyboard height)> I'm currently setting minHeight to the BottomSheetView component to avoid this happening, but I'm not sure what is the best way to set this dynamically (I assume keyboard size may vary) and it's also not ideal cause I would like to have sheets smaller than the keyboard height if needed.

danbeo95 commented 7 months ago

Still get this bug

danbeo95 commented 7 months ago

I try with version 5.0.0-alpha.9 and this bug does not occur But feel close animation does not smoothly on Android only

UmidbekU commented 7 months ago

I've been using version 5.0.0-alpha.9 with the enableDynamicSizing parameter wrapped in a BottomSheetView, and it works flawlessly. However, in Android, the animation when the modal is raised upon opening the keyboard isn't smooth.

pesohub commented 6 months ago

I fixed the problem by installing react-native-keyboard-controller and adding keyboardBehavior and keyboardBlurBehavior.

<BottomSheetModal
  enableDynamicSizing={true}
  keyboardBehavior="interactive"
  keyboardBlurBehavior="restore"
>
  <BottomSheetTextInput />
<BottomSheetModal>
psk-dreampay commented 6 months ago

This is happening in case of BottomSheet as well.

anurbecirovic commented 6 months ago

I can confirm it's not happening anymore for me in the 5.0.0-alpha.10 version.

Jad-Jbara commented 4 months ago

Can confirm 5.0.0-alpha.10 fixes this issue. @gorhom any expectancy when this version will be released?

mashish584 commented 4 months ago

@Mirthis , I agree with your point. I am facing the same issue when the view height is less than the keyboard height.

Kakaranara commented 4 months ago

same issue

saaaab1213 commented 4 months ago

I was able to solve the issue turning on autofocus on the BottomSheetTextInput; Also adding 'react-native-keyboard-controller' as @pesohub said worked for me