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.

Drawer.js 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // @flow
  2. import React, { useEffect, useRef, useState } from 'react';
  3. import { Icon, IconArrowUp, IconArrowDown } from '../../../base/icons';
  4. type Props = {
  5. /**
  6. * Whether the drawer should have a button that expands its size or not.
  7. */
  8. canExpand: ?boolean,
  9. /**
  10. * The component(s) to be displayed within the drawer menu.
  11. */
  12. children: React$Node,
  13. /**
  14. Whether the drawer should be shown or not.
  15. */
  16. isOpen: boolean,
  17. /**
  18. Function that hides the drawer.
  19. */
  20. onClose: Function
  21. };
  22. /**
  23. * Component that displays the mobile friendly drawer on web.
  24. *
  25. * @returns {ReactElement}
  26. */
  27. function Drawer({
  28. canExpand,
  29. children,
  30. isOpen,
  31. onClose }: Props) {
  32. const [ expanded, setExpanded ] = useState(false);
  33. const drawerRef: Object = useRef(null);
  34. /**
  35. * Closes the drawer when clicking outside of it.
  36. *
  37. * @param {Event} event - Mouse down event object.
  38. * @returns {void}
  39. */
  40. function handleOutsideClick(event: MouseEvent) {
  41. if (drawerRef.current && !drawerRef.current.contains(event.target)) {
  42. onClose();
  43. }
  44. }
  45. useEffect(() => {
  46. window.addEventListener('mousedown', handleOutsideClick);
  47. return () => {
  48. window.removeEventListener('mousedown', handleOutsideClick);
  49. };
  50. }, [ drawerRef ]);
  51. /**
  52. * Toggles the menu state between expanded/collapsed.
  53. *
  54. * @returns {void}
  55. */
  56. function toggleExpanded() {
  57. setExpanded(!expanded);
  58. }
  59. return (
  60. isOpen ? (
  61. <div
  62. className = { `drawer-menu${expanded ? ' expanded' : ''}` }
  63. ref = { drawerRef }>
  64. {canExpand && (
  65. <div
  66. className = 'drawer-toggle'
  67. onClick = { toggleExpanded }>
  68. <Icon src = { expanded ? IconArrowDown : IconArrowUp } />
  69. </div>
  70. )}
  71. {children}
  72. </div>
  73. ) : null
  74. );
  75. }
  76. export default Drawer;