logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

modal_root.js (2212B)


  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. }
  29. componentDidUpdate (prevProps) {
  30. if (!this.props.children && !!prevProps.children) {
  31. this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
  32. this.activeElement.focus();
  33. this.activeElement = null;
  34. }
  35. if (this.props.children) {
  36. requestAnimationFrame(() => {
  37. this.setState({ revealed: true });
  38. });
  39. }
  40. }
  41. componentWillUnmount () {
  42. window.removeEventListener('keyup', this.handleKeyUp);
  43. }
  44. getSiblings = () => {
  45. return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
  46. }
  47. setRef = ref => {
  48. this.node = ref;
  49. }
  50. render () {
  51. const { children, onClose } = this.props;
  52. const { revealed } = this.state;
  53. const visible = !!children;
  54. if (!visible) {
  55. return (
  56. <div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
  57. );
  58. }
  59. return (
  60. <div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}>
  61. <div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
  62. <div role='presentation' className='modal-root__overlay' onClick={onClose} />
  63. <div role='dialog' className='modal-root__container'>{children}</div>
  64. </div>
  65. </div>
  66. );
  67. }
  68. }