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.

86 lines
2.2 KiB

  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. export default class ModalRoot extends React.PureComponent {
  4. static propTypes = {
  5. children: PropTypes.node,
  6. onClose: PropTypes.func.isRequired,
  7. };
  8. state = {
  9. revealed: !!this.props.children,
  10. };
  11. activeElement = this.state.revealed ? document.activeElement : null;
  12. handleKeyUp = (e) => {
  13. if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
  14. && !!this.props.children) {
  15. this.props.onClose();
  16. }
  17. }
  18. componentDidMount () {
  19. window.addEventListener('keyup', this.handleKeyUp, false);
  20. }
  21. componentWillReceiveProps (nextProps) {
  22. if (!!nextProps.children && !this.props.children) {
  23. this.activeElement = document.activeElement;
  24. this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
  25. } else if (!nextProps.children) {
  26. this.setState({ revealed: false });
  27. }
  28. if (!nextProps.children && !!this.props.children) {
  29. this.activeElement.focus();
  30. this.activeElement = null;
  31. }
  32. }
  33. componentDidUpdate (prevProps) {
  34. if (!this.props.children && !!prevProps.children) {
  35. this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
  36. }
  37. if (this.props.children) {
  38. requestAnimationFrame(() => {
  39. this.setState({ revealed: true });
  40. });
  41. }
  42. }
  43. componentWillUnmount () {
  44. window.removeEventListener('keyup', this.handleKeyUp);
  45. }
  46. getSiblings = () => {
  47. return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
  48. }
  49. setRef = ref => {
  50. this.node = ref;
  51. }
  52. render () {
  53. const { children, onClose } = this.props;
  54. const { revealed } = this.state;
  55. const visible = !!children;
  56. if (!visible) {
  57. return (
  58. <div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
  59. );
  60. }
  61. return (
  62. <div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}>
  63. <div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
  64. <div role='presentation' className='modal-root__overlay' onClick={onClose} />
  65. <div role='dialog' className='modal-root__container'>{children}</div>
  66. </div>
  67. </div>
  68. );
  69. }
  70. }