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.

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