1import { useSyncExternalStore } from "react";
2import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller";
3
4// `useKeyboardState` only flips on willShow and didHide. This follows the will-events, so a
5// layout that makes room for the keyboard gives it back as soon as the keyboard starts hiding.
6let keyboardShowing = KeyboardController.isVisible();
7function subscribeKeyboardShowing(onChange: () => void) {
8 keyboardShowing = KeyboardController.isVisible();
9 const willShow = KeyboardEvents.addListener("keyboardWillShow", () => {
10 keyboardShowing = true;
11 onChange();
12 });
13 const willHide = KeyboardEvents.addListener("keyboardWillHide", () => {
14 keyboardShowing = false;
15 onChange();
16 });
17 return () => {
18 willShow.remove();
19 willHide.remove();
20 };
21}
22const getKeyboardShowing = () => keyboardShowing;
23
24export function useSoftKeyboardShowing() {
25 return useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing);
26}