You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

KeyboardAvoider.js 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // @flow
  2. import React, { useEffect, useState } from 'react';
  3. import styled from 'styled-components';
  4. import { isIosMobileBrowser } from '../../../base/environment/utils';
  5. const Avoider = styled.div`
  6. height: ${props => props.elementHeight}px;
  7. `;
  8. /**
  9. * Component that renders an element to lift the chat input above the Safari keyboard,
  10. * computing the appropriate height comparisons based on the {@code visualViewport}.
  11. *
  12. * @returns {ReactElement}
  13. */
  14. function KeyboardAvoider() {
  15. if (!isIosMobileBrowser()) {
  16. return null;
  17. }
  18. const [ elementHeight, setElementHeight ] = useState(0);
  19. const [ storedHeight, setStoredHeight ] = useState(window.innerHeight);
  20. /**
  21. * Handles the resizing of the visual viewport in order to compute
  22. * the {@code KeyboardAvoider}'s height.
  23. *
  24. * @returns {void}
  25. */
  26. function handleViewportResize() {
  27. const { innerWidth, visualViewport: { width, height } } = window;
  28. // Compare the widths to make sure the {@code visualViewport} didn't resize due to zooming.
  29. if (width === innerWidth) {
  30. if (height < storedHeight) {
  31. setElementHeight(storedHeight - height);
  32. } else {
  33. setElementHeight(0);
  34. }
  35. setStoredHeight(height);
  36. }
  37. }
  38. useEffect(() => {
  39. // Call the handler in case the keyboard is open when the {@code KeyboardAvoider} is mounted.
  40. handleViewportResize();
  41. window.visualViewport.addEventListener('resize', handleViewportResize);
  42. return () => {
  43. window.visualViewport.removeEventListener('resize', handleViewportResize);
  44. };
  45. }, []);
  46. return <Avoider elementHeight = { elementHeight } />;
  47. }
  48. export default KeyboardAvoider;