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.

154 lines
4.5 KiB

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