index.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import {Component, Fragment, useCallback, useEffect, useRef} from 'react';
  2. import {createPortal} from 'react-dom';
  3. import {browserHistory} from 'react-router';
  4. import {css} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import {createFocusTrap, FocusTrap} from 'focus-trap';
  7. import {AnimatePresence, motion} from 'framer-motion';
  8. import {closeModal as actionCloseModal} from 'sentry/actionCreators/modal';
  9. import {ROOT_ELEMENT} from 'sentry/constants';
  10. import ModalStore from 'sentry/stores/modalStore';
  11. import space from 'sentry/styles/space';
  12. import getModalPortal from 'sentry/utils/getModalPortal';
  13. import testableTransition from 'sentry/utils/testableTransition';
  14. import {makeClosableHeader, makeCloseButton, ModalBody, ModalFooter} from './components';
  15. type ModalOptions = {
  16. /**
  17. * Set to `false` to disable the ability to click outside the modal to
  18. * close it. This is useful for modals containing user input which will
  19. * disappear on an accidental click. Defaults to `true`.
  20. */
  21. allowClickClose?: boolean;
  22. /**
  23. * Set to `false` to disable the backdrop from being rendered. Set to
  24. * `static` to disable the 'click outside' behavior from closing the modal.
  25. * Set to true (the default) to show a translucent backdrop
  26. */
  27. backdrop?: 'static' | boolean;
  28. /**
  29. * Additional CSS which will be applied to the modals `role="dialog"`
  30. * component. You may use the `[role="document"]` selector to target the
  31. * actual modal content to style the visual element of the modal.
  32. */
  33. modalCss?: ReturnType<typeof css>;
  34. /**
  35. * Callback for when the modal is closed
  36. */
  37. onClose?: () => void;
  38. };
  39. type ModalRenderProps = {
  40. /**
  41. * Body container for the modal
  42. */
  43. Body: typeof ModalBody;
  44. /**
  45. * Looks like a close button. Useful for when you don't want to render the
  46. * header which can include the close button.
  47. */
  48. CloseButton: ReturnType<typeof makeCloseButton>;
  49. /**
  50. * Footer container for the modal, typically for actions
  51. */
  52. Footer: typeof ModalFooter;
  53. /**
  54. * The modal header, optionally includes a close button which will close the
  55. * modal.
  56. */
  57. Header: ReturnType<typeof makeClosableHeader>;
  58. /**
  59. * Closes the modal
  60. */
  61. closeModal: () => void;
  62. };
  63. /**
  64. * Meta-type to make re-exporting these in the action creator easy without
  65. * polluting the global API namespace with duplicate type names.
  66. *
  67. * eg. you won't accidentally import ModalRenderProps from here.
  68. */
  69. export type ModalTypes = {
  70. options: ModalOptions;
  71. renderProps: ModalRenderProps;
  72. };
  73. type Props = {
  74. /**
  75. * Configuration of the modal
  76. */
  77. options: ModalOptions;
  78. /**
  79. * Is the modal visible
  80. */
  81. visible: boolean;
  82. /**
  83. * A function that returns a React Element
  84. */
  85. children?: null | ((renderProps: ModalRenderProps) => React.ReactNode);
  86. /**
  87. * Note this is the callback for the main App container and NOT the calling
  88. * component. GlobalModal is never used directly, but is controlled via
  89. * stores. To access the onClose callback from the component, you must
  90. * specify it when using the action creator.
  91. */
  92. onClose?: () => void;
  93. };
  94. function GlobalModal({visible = false, options = {}, children, onClose}: Props) {
  95. const closeModal = useCallback(() => {
  96. // Option close callback, from the thing which opened the modal
  97. options.onClose?.();
  98. // Action creator, actually closes the modal
  99. actionCloseModal();
  100. // GlobalModal onClose prop callback
  101. onClose?.();
  102. }, [options, onClose]);
  103. const handleEscapeClose = useCallback(
  104. (e: KeyboardEvent) => e.key === 'Escape' && closeModal(),
  105. [closeModal]
  106. );
  107. const portal = getModalPortal();
  108. const focusTrap = useRef<FocusTrap>();
  109. // SentryApp might be missing on tests
  110. if (window.SentryApp) {
  111. window.SentryApp.modalFocusTrap = focusTrap;
  112. }
  113. useEffect(() => {
  114. focusTrap.current = createFocusTrap(portal, {
  115. preventScroll: true,
  116. escapeDeactivates: false,
  117. fallbackFocus: portal,
  118. });
  119. }, [portal]);
  120. useEffect(() => {
  121. const body = document.querySelector('body');
  122. const root = document.getElementById(ROOT_ELEMENT);
  123. if (!body || !root) {
  124. return () => void 0;
  125. }
  126. const reset = () => {
  127. body.style.removeProperty('overflow');
  128. root.removeAttribute('aria-hidden');
  129. focusTrap.current?.deactivate();
  130. document.removeEventListener('keydown', handleEscapeClose);
  131. };
  132. if (visible) {
  133. body.style.overflow = 'hidden';
  134. root.setAttribute('aria-hidden', 'true');
  135. focusTrap.current?.activate();
  136. document.addEventListener('keydown', handleEscapeClose);
  137. } else {
  138. reset();
  139. }
  140. return reset;
  141. }, [portal, handleEscapeClose, visible]);
  142. // Close the modal when the browser history changes
  143. useEffect(() => browserHistory.listen(() => actionCloseModal()), []);
  144. const renderedChild = children?.({
  145. CloseButton: makeCloseButton(closeModal),
  146. Header: makeClosableHeader(closeModal),
  147. Body: ModalBody,
  148. Footer: ModalFooter,
  149. closeModal,
  150. });
  151. // Default to enabled backdrop
  152. const backdrop = options.backdrop ?? true;
  153. // Default to enabled click close
  154. const allowClickClose = options.allowClickClose ?? true;
  155. // Only close when we directly click outside of the modal.
  156. const containerRef = useRef<HTMLDivElement>(null);
  157. const clickClose = (e: React.MouseEvent) =>
  158. containerRef.current === e.target && allowClickClose && closeModal();
  159. return createPortal(
  160. <Fragment>
  161. <Backdrop
  162. style={backdrop && visible ? {opacity: 0.5, pointerEvents: 'auto'} : {}}
  163. />
  164. <Container
  165. ref={containerRef}
  166. style={{pointerEvents: visible ? 'auto' : 'none'}}
  167. onClick={backdrop === true ? clickClose : undefined}
  168. >
  169. <AnimatePresence>
  170. {visible && (
  171. <Modal role="dialog" aria-modal css={options.modalCss}>
  172. <Content role="document">{renderedChild}</Content>
  173. </Modal>
  174. )}
  175. </AnimatePresence>
  176. </Container>
  177. </Fragment>,
  178. portal
  179. );
  180. }
  181. const fullPageCss = css`
  182. position: fixed;
  183. top: 0;
  184. right: 0;
  185. bottom: 0;
  186. left: 0;
  187. `;
  188. const Backdrop = styled('div')`
  189. ${fullPageCss};
  190. z-index: ${p => p.theme.zIndex.modal};
  191. background: ${p => p.theme.black};
  192. will-change: opacity;
  193. transition: opacity 200ms;
  194. pointer-events: none;
  195. opacity: 0;
  196. `;
  197. const Container = styled('div')`
  198. ${fullPageCss};
  199. z-index: ${p => p.theme.zIndex.modal};
  200. display: flex;
  201. justify-content: center;
  202. align-items: flex-start;
  203. overflow-y: auto;
  204. `;
  205. const Modal = styled(motion.div)`
  206. max-width: 100%;
  207. width: 640px;
  208. pointer-events: auto;
  209. padding: 80px ${space(1.5)} ${space(2)} ${space(1.5)};
  210. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  211. padding: 80px ${space(2)} ${space(4)} ${space(2)};
  212. }
  213. `;
  214. Modal.defaultProps = {
  215. initial: {opacity: 0, y: -10},
  216. animate: {opacity: 1, y: 0},
  217. exit: {opacity: 0, y: 15},
  218. transition: testableTransition({
  219. opacity: {duration: 0.2},
  220. y: {duration: 0.25},
  221. }),
  222. };
  223. const Content = styled('div')`
  224. background: ${p => p.theme.background};
  225. border-radius: 8px;
  226. box-shadow: 0 0 0 1px ${p => p.theme.translucentBorder}, ${p => p.theme.dropShadowHeavy};
  227. position: relative;
  228. padding: ${space(4)} ${space(3)};
  229. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  230. padding: ${space(4)};
  231. }
  232. `;
  233. type State = {
  234. modalStore: ReturnType<typeof ModalStore.getState>;
  235. };
  236. class GlobalModalContainer extends Component<Partial<Props>, State> {
  237. state: State = {
  238. modalStore: ModalStore.getState(),
  239. };
  240. componentWillUnmount() {
  241. this.unlistener?.();
  242. }
  243. unlistener = ModalStore.listen(
  244. (modalStore: State['modalStore']) => this.setState({modalStore}),
  245. undefined
  246. );
  247. render() {
  248. const {modalStore} = this.state;
  249. const visible = !!modalStore && typeof modalStore.renderer === 'function';
  250. return (
  251. <GlobalModal {...this.props} {...modalStore} visible={visible}>
  252. {visible ? modalStore.renderer : null}
  253. </GlobalModal>
  254. );
  255. }
  256. }
  257. export default GlobalModalContainer;