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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // @flow
  2. import React, { useEffect, useRef, useState } from 'react';
  3. import { Icon, IconArrowUpWide, IconArrowDownWide } 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
  69. size = { 24 }
  70. src = { expanded ? IconArrowDownWide : IconArrowUpWide } />
  71. </div>
  72. )}
  73. {children}
  74. </div>
  75. ) : null
  76. );
  77. }
  78. export default Drawer;