kevinejohn / react-native-keyevent

Capture external keyboard keys or remote control button events
MIT License
208 stars 95 forks source link

onKeyDownListener not being called when a Modal is being shown #63

Open marianolc opened 2 years ago

marianolc commented 2 years ago

A simple example:

This in the App.js will always show the key pressed:

  useEffect(() => {
    KeyEvent.onKeyDownListener((keyEvent: any) => {
      console.log(`Key: ${keyEvent.pressedKey}`);
    return () => KeyEvent.removeKeyDownListener();
  }, []);

But at the moment I show any modal, the event stop being called. A simple modal:

import React, { useState } from 'react';
import { Button, Modal } from 'react-native';

interface Props {
  visible: boolean;
  setVisible: (value: boolean) => void;
}

const KeyListenerModalTest = ({ visible, setVisible }: Props) => {
  return (
    <Modal visible={visible}>
      <Button title={'HIDE'} onPress={() => setVisible(false)} />
    </Modal>
  );
};

export default KeyListenerModalTest;

And the keys log won't show. After I press the button HIDE the keys start to be logged again without any problem.

douugdev commented 2 years ago

The current workaround I am using is to use a component to emulate a modal with the fade animation type:

import React, { useEffect, useState } from 'react';
import { ModalProps, StyleSheet } from 'react-native';
import Animated, { useAnimatedStyle, useSharedValue, withTiming, Easing, runOnJS } from 'react-native-reanimated';

const FakeModal: React.FC<ModalProps> = ({ visible, animationType, children }) => {
  const opacity = useSharedValue(0);
  const [viewable, setViewable] = useState(false);
  const setViewableFalse = () => setViewable(false);

  useEffect(() => {
    if (visible) {
      setViewable(true);
      opacity.value = withTiming(1, {
        duration: animationType === 'fade' ? 200 : 0,
        easing: Easing.linear,
      });
    } else {
      opacity.value = withTiming(0, { duration: animationType === 'fade' ? 200 : 0 }, finished => {
        if (finished) {
          runOnJS(setViewableFalse)();
        }
      });
    }
  }, [visible]);

  const animatedStyles = useAnimatedStyle(() => {
    return {
      opacity: opacity.value,
    };
  });

  return viewable ? <Animated.View style={[styles.modal, animatedStyles]}>{children}</Animated.View> : <></>;
};

const styles = StyleSheet.create({
  modal: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    zIndex: 100,
  },
});

export default FakeModal;

It has almost no features compared to the native modal but it currently logs the keyboard.