From ccfd936f274ca2105745f9edbbb4aad80725e181 Mon Sep 17 00:00:00 2001 From: Yogendra Rawal Date: Thu, 24 Nov 2022 01:03:09 +0545 Subject: [PATCH] [fix] iOS not firing `resize` event when keyboard opens/closes The workaround is listening to window.visualViewport 'resize' event. Fix #2430 Close #2438 --- .../src/exports/Dimensions/index.js | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/packages/react-native-web/src/exports/Dimensions/index.js b/packages/react-native-web/src/exports/Dimensions/index.js index 78d0e2e0b..47616e2a8 100644 --- a/packages/react-native-web/src/exports/Dimensions/index.js +++ b/packages/react-native-web/src/exports/Dimensions/index.js @@ -52,13 +52,29 @@ function update() { } const win = window; - const docEl = win.document.documentElement; + let height; + let width; + + /** + * iOS does not update viewport dimensions on keyboard open/close. + * window.visualViewport(https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport) + * is used instead of document.documentElement.clientHeight (which remains as a fallback) + */ + if (win.visualViewport) { + const visualViewport = win.visualViewport; + height = Math.round(visualViewport.height); + width = Math.round(visualViewport.width); + } else { + const docEl = win.document.documentElement; + height = docEl.clientHeight; + width = docEl.clientWidth; + } dimensions.window = { fontScale: 1, - height: docEl.clientHeight, + height, scale: win.devicePixelRatio || 1, - width: docEl.clientWidth + width }; dimensions.screen = { @@ -128,5 +144,9 @@ export default class Dimensions { } if (canUseDOM) { - window.addEventListener('resize', handleResize, false); + if (window.visualViewport) { + window.visualViewport.addEventListener('resize', handleResize, false); + } else { + window.addEventListener('resize', handleResize, false); + } }