@crossed/sheet
Version:
A Cross Platform(Android & iOS) ActionSheet with a robust and flexible api, native performance and zero dependency code for react native. Create anything you want inside ActionSheet.
80 lines (79 loc) • 2.25 kB
JavaScript
import React, { useEffect, useRef, useState } from "react";
import {
Keyboard,
Platform
} from "react-native";
const emptyCoordinates = Object.freeze({
screenX: 0,
screenY: 0,
width: 0,
height: 0
});
const initialValue = {
start: emptyCoordinates,
end: emptyCoordinates
};
function useKeyboard(enabled) {
const pauseKeyboardHandler = useRef(false);
const [shown, setShown] = useState(false);
const [coordinates, setCoordinates] = useState(initialValue);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const handleKeyboardDidShow = React.useCallback(
(e) => {
if (pauseKeyboardHandler.current)
return;
setCoordinates({ start: e.startCoordinates, end: e.endCoordinates });
setKeyboardHeight(e.endCoordinates.height);
setShown(true);
},
[]
);
const handleKeyboardDidHide = React.useCallback(
(e) => {
setShown(false);
if (e) {
setCoordinates({ start: e.startCoordinates, end: e.endCoordinates });
} else {
setCoordinates(initialValue);
setKeyboardHeight(0);
}
},
[]
);
useEffect(() => {
let subscriptions = [];
if (enabled) {
subscriptions = [
Keyboard.addListener("keyboardDidChangeFrame", handleKeyboardDidShow),
Keyboard.addListener("keyboardDidHide", handleKeyboardDidHide)
];
if (Platform.OS == "android") {
subscriptions.push(
Keyboard.addListener("keyboardDidShow", handleKeyboardDidShow)
);
} else {
subscriptions.push(
Keyboard.addListener("keyboardWillShow", handleKeyboardDidShow),
Keyboard.addListener("keyboardWillHide", handleKeyboardDidHide)
);
}
}
return () => {
subscriptions.forEach((subscription) => subscription.remove());
};
}, [enabled, handleKeyboardDidHide, handleKeyboardDidShow]);
return {
keyboardShown: !enabled ? false : shown,
coordinates: !enabled || !shown ? emptyCoordinates : coordinates,
keyboardHeight: !enabled || !shown ? 0 : keyboardHeight,
pauseKeyboardHandler,
reset: () => {
setShown(false);
setKeyboardHeight(0);
}
};
}
export {
useKeyboard
};
//# sourceMappingURL=useKeyboard.js.map