Skip to content

Instantly share code, notes, and snippets.

@brentvatne
Created May 17, 2017 07:24
Show Gist options
  • Save brentvatne/5b147fb5629b024aebbce84d2fe1cda9 to your computer and use it in GitHub Desktop.
Save brentvatne/5b147fb5629b024aebbce84d2fe1cda9 to your computer and use it in GitHub Desktop.
import { LayoutAnimation, Keyboard, Platform } from 'react-native';
export default class KeyboardEventListener {
static subscribe(callback) {
const listener = new KeyboardEventListener(callback);
return () => {
listener.unsubscribe();
};
}
constructor(callback) {
this._callback = callback;
if (Platform.OS === 'ios') {
this._keyboardDidChangeSubscription = Keyboard.addListener(
'keyboardWillChangeFrame',
this._onKeyboardChange
);
} else {
this._keyboardDidShowSubscription = Keyboard.addListener(
'keyboardDidShow',
this._onKeyboardChange
);
this._keyboardDidHideSubscription = Keyboard.addListener(
'keyboardDidHide',
this._onKeyboardChange
);
}
}
unsubscribe() {
this._keyboardDidChangeSubscription &&
this._keyboardDidChangeSubscription.remove();
this._keyboardDidShowSubscription &&
this._keyboardDidShowSubscription.remove();
this._keyboardDidHideSubscription &&
this._keyboardDidHideSubscription.remove();
}
_onKeyboardChange = event => {
if (!event) {
this._callback({ keyboardHeight: 0 });
return;
}
const { duration, easing, startCoordinates, endCoordinates } = event;
let keyboardHeight;
if (
Platform.OS === 'ios' &&
endCoordinates.screenY > startCoordinates.screenY
) {
keyboardHeight = 0;
} else if (
Platform.OS === 'ios' &&
endCoordinates.screenY === startCoordinates.screenY
) {
return;
} else {
keyboardHeight = endCoordinates.height;
}
let layoutAnimationConfig;
if (duration && easing) {
layoutAnimationConfig = {
duration,
update: {
duration,
type: LayoutAnimation.Types[easing] || 'keyboard',
},
};
}
this._callback({ keyboardHeight, layoutAnimationConfig });
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment