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.

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