UNPKG

@wordpress/components

Version:
73 lines (65 loc) 3.06 kB
/** * External dependencies */ import { Keyboard } from 'react-native'; /** * WordPress dependencies */ import { useEffect, useCallback, useState, useRef } from '@wordpress/element'; /** * Hook that adds Keyboard listeners to get the offset space * when the keyboard is opened, taking into account focused AztecViews. * * @param {boolean} scrollEnabled Whether the scroll is enabled or not. * @param {Function} shouldPreventAutomaticScroll Whether to prevent scrolling when there's a Keyboard offset set. * @return {[number]} Keyboard offset. */ export default function useKeyboardOffset(scrollEnabled, shouldPreventAutomaticScroll) { const [keyboardOffset, setKeyboardOffset] = useState(0); const timeoutRef = useRef(); const onKeyboardDidHide = useCallback(() => { if (shouldPreventAutomaticScroll()) { clearTimeout(timeoutRef.current); return; } // A timeout is being used to delay resetting the offset in cases // where the focus is changed to a different TextInput. clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { setKeyboardOffset(0); }, 200); }, [shouldPreventAutomaticScroll]); const onKeyboardDidShow = useCallback(_ref => { let { endCoordinates } = _ref; clearTimeout(timeoutRef.current); setKeyboardOffset(endCoordinates.height); }, []); const onKeyboardWillShow = useCallback(() => { clearTimeout(timeoutRef.current); }, []); useEffect(() => { let willShowSubscription; let showSubscription; let hideSubscription; if (scrollEnabled) { willShowSubscription = Keyboard.addListener('keyboardWillShow', onKeyboardWillShow); showSubscription = Keyboard.addListener('keyboardDidShow', onKeyboardDidShow); hideSubscription = Keyboard.addListener('keyboardDidHide', onKeyboardDidHide); } else { var _willShowSubscription, _showSubscription, _hideSubscription; (_willShowSubscription = willShowSubscription) === null || _willShowSubscription === void 0 ? void 0 : _willShowSubscription.remove(); (_showSubscription = showSubscription) === null || _showSubscription === void 0 ? void 0 : _showSubscription.remove(); (_hideSubscription = hideSubscription) === null || _hideSubscription === void 0 ? void 0 : _hideSubscription.remove(); } return () => { var _willShowSubscription2, _showSubscription2, _hideSubscription2; clearTimeout(timeoutRef.current); (_willShowSubscription2 = willShowSubscription) === null || _willShowSubscription2 === void 0 ? void 0 : _willShowSubscription2.remove(); (_showSubscription2 = showSubscription) === null || _showSubscription2 === void 0 ? void 0 : _showSubscription2.remove(); (_hideSubscription2 = hideSubscription) === null || _hideSubscription2 === void 0 ? void 0 : _hideSubscription2.remove(); }; }, [onKeyboardDidHide, onKeyboardDidShow, onKeyboardWillShow, scrollEnabled]); return [keyboardOffset]; } //# sourceMappingURL=use-keyboard-offset.native.js.map