Last active
January 21, 2020 19:39
-
-
Save tannerlinsley/30769bf569a8f96444198bd0eece1fdb to your computer and use it in GitHub Desktop.
A refactor of the old version as requested here in this tweet: https://twitter.com/sseraphini/status/1219701281331257345
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import PropTypes from 'prop-types' | |
import { Keyboard, LayoutAnimation, Dimensions, Platform } from 'react-native' | |
const defaultAnimation = { | |
duration: 500, | |
create: { | |
duration: 300, | |
type: LayoutAnimation.Types.easeInEaseOut, | |
property: LayoutAnimation.Properties.opacity, | |
}, | |
update: { | |
type: LayoutAnimation.Types.spring, | |
springDamping: 200, | |
}, | |
} | |
export default function useKeyboardSpacer({ | |
topSpacing = 0, | |
onChange = () => {}, | |
}) { | |
const [keyboardSpace, setKeyboardSpace] = React.useState(0) | |
const onChangeRef = React.useRef() | |
onChangeRef.current = onChange | |
React.useEffect(() => { | |
const updateListener = | |
Platform.OS === 'android' ? 'keyboardDidShow' : 'keyboardWillShow' | |
const resetListener = | |
Platform.OS === 'android' ? 'keyboardDidHide' : 'keyboardWillHide' | |
const updateKeyboardSpace = event => { | |
if (!event.endCoordinates) { | |
return | |
} | |
let animationConfig = defaultAnimation | |
if (Platform.OS === 'ios') { | |
animationConfig = LayoutAnimation.create( | |
event.duration, | |
LayoutAnimation.Types[event.easing], | |
LayoutAnimation.Properties.opacity | |
) | |
} | |
LayoutAnimation.configureNext(animationConfig) | |
const newSpace = | |
Dimensions.get('window').height - | |
event.endCoordinates.screenY + | |
topSpacing | |
setKeyboardSpace(newSpace) | |
onChangeRef.current(newSpace) | |
} | |
const resetKeyboardSpace = event => { | |
let animationConfig = defaultAnimation | |
if (Platform.OS === 'ios') { | |
animationConfig = LayoutAnimation.create( | |
event.duration, | |
LayoutAnimation.Types[event.easing], | |
LayoutAnimation.Properties.opacity | |
) | |
} | |
LayoutAnimation.configureNext(animationConfig) | |
setKeyboardSpace(0) | |
onChangeRef.current(0) | |
} | |
Keyboard.addListener(updateListener, this.updateKeyboardSpace) | |
Keyboard.addListener(resetListener, this.resetKeyboardSpace) | |
return () => { | |
Keyboard.removeListener(updateListener, updateKeyboardSpace) | |
Keyboard.removeListener(resetListener, resetKeyboardSpace) | |
} | |
}, [topSpacing]) | |
return keyboardSpace | |
} | |
useKeyboardSpacer.propTypes = { | |
topSpacing: PropTypes.number, | |
onChange: PropTypes.func, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment