modal_root.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import 'wicg-inert';
  4. import { createBrowserHistory } from 'history';
  5. import { multiply } from 'color-blend';
  6. export default class ModalRoot extends React.PureComponent {
  7. static contextTypes = {
  8. router: PropTypes.object,
  9. };
  10. static propTypes = {
  11. children: PropTypes.node,
  12. onClose: PropTypes.func.isRequired,
  13. backgroundColor: PropTypes.shape({
  14. r: PropTypes.number,
  15. g: PropTypes.number,
  16. b: PropTypes.number,
  17. }),
  18. ignoreFocus: PropTypes.bool,
  19. };
  20. activeElement = this.props.children ? document.activeElement : null;
  21. handleKeyUp = (e) => {
  22. if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
  23. && !!this.props.children) {
  24. this.props.onClose();
  25. }
  26. }
  27. handleKeyDown = (e) => {
  28. if (e.key === 'Tab') {
  29. const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none');
  30. const index = focusable.indexOf(e.target);
  31. let element;
  32. if (e.shiftKey) {
  33. element = focusable[index - 1] || focusable[focusable.length - 1];
  34. } else {
  35. element = focusable[index + 1] || focusable[0];
  36. }
  37. if (element) {
  38. element.focus();
  39. e.stopPropagation();
  40. e.preventDefault();
  41. }
  42. }
  43. }
  44. componentDidMount () {
  45. window.addEventListener('keyup', this.handleKeyUp, false);
  46. window.addEventListener('keydown', this.handleKeyDown, false);
  47. this.history = this.context.router ? this.context.router.history : createBrowserHistory();
  48. }
  49. componentWillReceiveProps (nextProps) {
  50. if (!!nextProps.children && !this.props.children) {
  51. this.activeElement = document.activeElement;
  52. this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
  53. }
  54. }
  55. componentDidUpdate (prevProps) {
  56. if (!this.props.children && !!prevProps.children) {
  57. this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
  58. // Because of the wicg-inert polyfill, the activeElement may not be
  59. // immediately selectable, we have to wait for observers to run, as
  60. // described in https://github.com/WICG/inert#performance-and-gotchas
  61. Promise.resolve().then(() => {
  62. if (!this.props.ignoreFocus) {
  63. this.activeElement.focus({ preventScroll: true });
  64. }
  65. this.activeElement = null;
  66. }).catch(console.error);
  67. this._handleModalClose();
  68. }
  69. if (this.props.children && !prevProps.children) {
  70. this._handleModalOpen();
  71. }
  72. if (this.props.children) {
  73. this._ensureHistoryBuffer();
  74. }
  75. }
  76. componentWillUnmount () {
  77. window.removeEventListener('keyup', this.handleKeyUp);
  78. window.removeEventListener('keydown', this.handleKeyDown);
  79. }
  80. _handleModalOpen () {
  81. this._modalHistoryKey = Date.now();
  82. this.unlistenHistory = this.history.listen((_, action) => {
  83. if (action === 'POP') {
  84. this.props.onClose();
  85. }
  86. });
  87. }
  88. _handleModalClose () {
  89. if (this.unlistenHistory) {
  90. this.unlistenHistory();
  91. }
  92. const { state } = this.history.location;
  93. if (state && state.mastodonModalKey === this._modalHistoryKey) {
  94. this.history.goBack();
  95. }
  96. }
  97. _ensureHistoryBuffer () {
  98. const { pathname, state } = this.history.location;
  99. if (!state || state.mastodonModalKey !== this._modalHistoryKey) {
  100. this.history.push(pathname, { ...state, mastodonModalKey: this._modalHistoryKey });
  101. }
  102. }
  103. getSiblings = () => {
  104. return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
  105. }
  106. setRef = ref => {
  107. this.node = ref;
  108. }
  109. render () {
  110. const { children, onClose } = this.props;
  111. const visible = !!children;
  112. if (!visible) {
  113. return (
  114. <div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
  115. );
  116. }
  117. let backgroundColor = null;
  118. if (this.props.backgroundColor) {
  119. backgroundColor = multiply({ ...this.props.backgroundColor, a: 1 }, { r: 0, g: 0, b: 0, a: 0.7 });
  120. }
  121. return (
  122. <div className='modal-root' ref={this.setRef}>
  123. <div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
  124. <div role='presentation' className='modal-root__overlay' onClick={onClose} style={{ backgroundColor: backgroundColor ? `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, 0.7)` : null }} />
  125. <div role='dialog' className='modal-root__container'>{children}</div>
  126. </div>
  127. </div>
  128. );
  129. }
  130. }