Skip to content

Commit

Permalink
Simplify useVirtualKeyboard hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Temzasse committed May 14, 2024
1 parent 45538c4 commit 1c0ddb7
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 18 deletions.
20 changes: 3 additions & 17 deletions example/components/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,6 @@ export function useMetaThemeColor({
export function useVirtualKeyboard() {
const [isKeyboardOpen, setKeyboardOpen] = useState(false);
const [keyboardHeight, setKeyboardHeight] = useState(0);
const [windowHeight, setWindowHeight] = useState(() =>
typeof window !== 'undefined' ? window.innerHeight : 0
);

useEffect(() => {
const visualViewport = window.visualViewport;
Expand All @@ -48,9 +45,9 @@ export function useVirtualKeyboard() {
focusedElement.tagName === 'TEXTAREA';

// Virtual keyboard should only be visible if an input is focused
if (isInputFocused && visualViewport.height < windowHeight) {
if (isInputFocused && visualViewport.height < window.innerHeight) {
setKeyboardOpen(true);
setKeyboardHeight(Math.max(0, windowHeight - visualViewport.height));
setKeyboardHeight(window.innerHeight - visualViewport.height);
} else if (isKeyboardOpen) {
// Reset keyboard height if it was open
setKeyboardOpen(false);
Expand All @@ -64,18 +61,7 @@ export function useVirtualKeyboard() {
visualViewport.removeEventListener('resize', onResize);
};
}
}, [windowHeight, isKeyboardOpen]);

// Keep track of the window height
useEffect(() => {
const onResize = () => setWindowHeight(window.innerHeight);

window.addEventListener('resize', onResize);

return () => {
window.removeEventListener('resize', onResize);
};
}, []);
}, [isKeyboardOpen]);

return { keyboardHeight, isKeyboardOpen };
}
Expand Down
2 changes: 1 addition & 1 deletion example/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1c0ddb7

Please sign in to comment.