UNPKG

@wordpress/components

Version:
72 lines (68 loc) 2.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useKeyboardOffset; var _reactNative = require("react-native"); var _element = require("@wordpress/element"); /** * External dependencies */ /** * WordPress dependencies */ /** * 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. */ function useKeyboardOffset(scrollEnabled, shouldPreventAutomaticScroll) { const [keyboardOffset, setKeyboardOffset] = (0, _element.useState)(0); const timeoutRef = (0, _element.useRef)(); const onKeyboardDidHide = (0, _element.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 = (0, _element.useCallback)(({ endCoordinates }) => { clearTimeout(timeoutRef.current); setKeyboardOffset(endCoordinates.height); }, []); const onKeyboardWillShow = (0, _element.useCallback)(() => { clearTimeout(timeoutRef.current); }, []); (0, _element.useEffect)(() => { let willShowSubscription; let showSubscription; let hideSubscription; if (scrollEnabled) { willShowSubscription = _reactNative.Keyboard.addListener('keyboardWillShow', onKeyboardWillShow); showSubscription = _reactNative.Keyboard.addListener('keyboardDidShow', onKeyboardDidShow); hideSubscription = _reactNative.Keyboard.addListener('keyboardDidHide', onKeyboardDidHide); } else { willShowSubscription?.remove(); showSubscription?.remove(); hideSubscription?.remove(); } return () => { clearTimeout(timeoutRef.current); willShowSubscription?.remove(); showSubscription?.remove(); hideSubscription?.remove(); }; }, [onKeyboardDidHide, onKeyboardDidShow, onKeyboardWillShow, scrollEnabled]); return [keyboardOffset]; } //# sourceMappingURL=use-keyboard-offset.native.js.map