import { isWeb } from '@tamagui/core' ; import { useEffect } from 'react' ; import { BackHandler } from 'react-native' ; type IParams = { enabled ? : boolean ; callback : ( ) => any ; } ; let keyboardDismissHandlers = [ ] ; export const keyboardDismissHandlerManager = { push : ( handler ) => { keyboardDismissHandlers . push ( handler ) ; return ( ) => { keyboardDismissHandlers = keyboardDismissHandlers . filter ( ( h ) => h !== handler ) ; } ; } , length : ( ) => keyboardDismissHandlers . length , pop : ( ) => { return keyboardDismissHandlers . pop ( ) ; } , } ; export const useKeyboardDismissable = ( { enabled , callback } ) => { useEffect ( ( ) => { let cleanupFn = ( ) => { } ; if ( enabled ) { cleanupFn = keyboardDismissHandlerManager . push ( callback ) ; } else { cleanupFn ( ) ; } return ( ) => { cleanupFn ( ) ; } ; } , [ enabled , callback ] ) ; useBackHandler ( { enabled , callback } ) ; } ; const callbackOnEscape = ( callback ) => ( e ) => { if ( e . key === 'Escape' ) { if ( ! ( document . activeElement instanceof HTMLInputElement ) && ! ( document . activeElement instanceof HTMLTextAreaElement ) ) { e . preventDefault ( ) ; e . stopPropagation ( ) ; callback ( ) ; } } } ; export function useBackHandler ( { enabled , callback } ) { useEffect ( ( ) => { let backHandler = ( ) => { callback ( ) ; return true ; } ; const keyHandler = callbackOnEscape ( callback ) ; if ( enabled ) { BackHandler . addEventListener ( 'hardwareBackPress' , backHandler ) ; if ( isWeb ) { window . addEventListener ( 'keydown' , keyHandler ) ; } } else { BackHandler . removeEventListener ( 'hardwareBackPress' , backHandler ) ; } return ( ) => { BackHandler . removeEventListener ( 'hardwareBackPress' , backHandler ) ; if ( isWeb ) { window . removeEventListener ( 'keydown' , keyHandler ) ; } } ; } , [ enabled , callback ] ) ; }