ModalContent.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /* eslint-disable eqeqeq */
  2. import React, { CSSProperties } from 'react';
  3. import PropTypes from 'prop-types';
  4. import cls from 'classnames';
  5. import { cssClasses } from '@douyinfe/semi-foundation/modal/constants';
  6. import ConfigContext from '../configProvider/context';
  7. import Button from '../iconButton';
  8. import Typography from '../typography';
  9. import BaseComponent from '../_base/baseComponent';
  10. // eslint-disable-next-line max-len
  11. import ModalContentFoundation, {
  12. ModalContentAdapter,
  13. ModalContentProps,
  14. ModalContentState
  15. } from '@douyinfe/semi-foundation/modal/modalContentFoundation';
  16. import { noop, isFunction, get } from 'lodash';
  17. import { IconClose } from '@douyinfe/semi-icons';
  18. import { getActiveElement } from '../_utils';
  19. let uuid = 0;
  20. export default class ModalContent extends BaseComponent<ModalContentProps, ModalContentState> {
  21. static contextType = ConfigContext;
  22. static propTypes = {
  23. close: PropTypes.func,
  24. getContainerContext: PropTypes.func,
  25. contentClassName: PropTypes.string,
  26. maskClassName: PropTypes.string,
  27. onAnimationEnd: PropTypes.func
  28. };
  29. static defaultProps = {
  30. close: noop,
  31. getContainerContext: noop,
  32. contentClassName: '',
  33. maskClassName: ''
  34. };
  35. dialogId: string;
  36. private timeoutId: NodeJS.Timeout;
  37. modalDialogRef: React.MutableRefObject<HTMLDivElement>;
  38. foundation: ModalContentFoundation;
  39. constructor(props: ModalContentProps) {
  40. super(props);
  41. this.state = {
  42. dialogMouseDown: false,
  43. prevFocusElement: getActiveElement(),
  44. };
  45. this.foundation = new ModalContentFoundation(this.adapter);
  46. this.dialogId = `dialog-${uuid++}`;
  47. this.modalDialogRef = React.createRef();
  48. }
  49. get adapter(): ModalContentAdapter {
  50. return {
  51. ...super.adapter,
  52. notifyClose: (e: React.MouseEvent) => {
  53. this.props.onClose(e);
  54. },
  55. notifyDialogMouseDown: () => {
  56. this.setState({ dialogMouseDown: true });
  57. },
  58. notifyDialogMouseUp: () => {
  59. if (this.state.dialogMouseDown) {
  60. // Not setting setTimeout triggers close when modal external mouseUp
  61. this.timeoutId = setTimeout(() => {
  62. this.setState({ dialogMouseDown: false });
  63. }, 0);
  64. }
  65. },
  66. addKeyDownEventListener: () => {
  67. if (this.props.closeOnEsc) {
  68. document.addEventListener('keydown', this.foundation.handleKeyDown.bind(this.foundation));
  69. }
  70. },
  71. removeKeyDownEventListener: () => {
  72. if (this.props.closeOnEsc) {
  73. document.removeEventListener('keydown', this.foundation.handleKeyDown.bind(this.foundation));
  74. }
  75. },
  76. getMouseState: () => this.state.dialogMouseDown,
  77. modalDialogFocus: () => {
  78. let activeElementInDialog;
  79. if (this.modalDialogRef) {
  80. const activeElement = getActiveElement();
  81. activeElementInDialog = this.modalDialogRef.current.contains(activeElement);
  82. }
  83. if (!activeElementInDialog) {
  84. this.modalDialogRef && this.modalDialogRef.current.focus();
  85. }
  86. },
  87. modalDialogBlur: () => {
  88. this.modalDialogRef && this.modalDialogRef.current.blur();
  89. },
  90. prevFocusElementReFocus: () => {
  91. const { prevFocusElement } = this.state;
  92. const focus = get(prevFocusElement, 'focus');
  93. isFunction(focus) && prevFocusElement.focus();
  94. }
  95. };
  96. }
  97. componentDidMount() {
  98. this.foundation.handleKeyDownEventListenerMount();
  99. this.foundation.modalDialogFocus();
  100. }
  101. componentWillUnmount() {
  102. clearTimeout(this.timeoutId);
  103. this.foundation.destroy();
  104. }
  105. onKeyDown = (e: React.MouseEvent) => {
  106. this.foundation.handleKeyDown(e);
  107. };
  108. // Record when clicking the modal box
  109. onDialogMouseDown = () => {
  110. this.foundation.handleDialogMouseDown();
  111. };
  112. // Cancel recording when clicking the modal box at the end
  113. onMaskMouseUp = () => {
  114. this.foundation.handleMaskMouseUp();
  115. };
  116. // onMaskClick will judge dialogMouseDown before onMaskMouseUp updates dialogMouseDown
  117. onMaskClick = (e: React.MouseEvent) => {
  118. this.foundation.handleMaskClick(e);
  119. };
  120. close = (e: React.MouseEvent) => {
  121. this.foundation.close(e);
  122. };
  123. getMaskElement = () => {
  124. const { ...props } = this.props;
  125. const { mask, maskClassName } = props;
  126. if (mask) {
  127. const className = cls(`${cssClasses.DIALOG}-mask`, {
  128. // [`${cssClasses.DIALOG}-mask-hidden`]: !props.visible,
  129. });
  130. return <div key="mask" className={cls(className, maskClassName)} style={props.maskStyle}/>;
  131. }
  132. return null;
  133. };
  134. renderCloseBtn = () => {
  135. const {
  136. closable,
  137. closeIcon,
  138. } = this.props;
  139. let closer;
  140. if (closable) {
  141. const iconType = closeIcon || <IconClose/>;
  142. closer = (
  143. <Button
  144. aria-label="close"
  145. className={`${cssClasses.DIALOG}-close`}
  146. key="close-btn"
  147. onClick={this.close}
  148. type="tertiary"
  149. icon={iconType}
  150. theme="borderless"
  151. size="small"
  152. />
  153. );
  154. }
  155. return closer;
  156. };
  157. renderIcon = () => {
  158. const { icon } = this.props;
  159. return icon ? <span className={`${cssClasses.DIALOG}-icon-wrapper`}>{icon}</span> : null;
  160. };
  161. renderHeader = () => {
  162. if ('header' in this.props) {
  163. return this.props.header;
  164. }
  165. const { title } = this.props;
  166. const closer = this.renderCloseBtn();
  167. const icon = this.renderIcon();
  168. return (title === null || title === undefined) ?
  169. null :
  170. (
  171. <div className={`${cssClasses.DIALOG}-header`}>
  172. {icon}
  173. <Typography.Title heading={5} className={`${cssClasses.DIALOG}-title`} id={`${cssClasses.DIALOG}-title`}>{title}</Typography.Title>
  174. {closer}
  175. </div>
  176. );
  177. };
  178. renderBody = () => {
  179. const {
  180. bodyStyle,
  181. children,
  182. title,
  183. } = this.props;
  184. const bodyCls = cls(`${cssClasses.DIALOG}-body`, {
  185. [`${cssClasses.DIALOG}-withIcon`]: this.props.icon,
  186. });
  187. const closer = this.renderCloseBtn();
  188. const icon = this.renderIcon();
  189. const hasHeader = title !== null && title !== undefined || 'header' in this.props;
  190. return hasHeader ?
  191. <div className={bodyCls} id={`${cssClasses.DIALOG}-body`} style={bodyStyle}>{children}</div> :
  192. (
  193. <div className={`${cssClasses.DIALOG}-body-wrapper`}>
  194. {icon}
  195. <div className={bodyCls} style={bodyStyle}>{children}</div>
  196. {closer}
  197. </div>
  198. );
  199. };
  200. getDialogElement = () => {
  201. const { ...props } = this.props;
  202. const style: CSSProperties = {};
  203. const digCls = cls(`${cssClasses.DIALOG}`, {
  204. [`${cssClasses.DIALOG}-centered`]: props.centered,
  205. [`${cssClasses.DIALOG}-${props.size}`]: props.size,
  206. });
  207. if (props.width) {
  208. style.width = props.width;
  209. }
  210. if (props.height) {
  211. style.height = props.height;
  212. }
  213. if (props.isFullScreen) {
  214. style.width = '100%';
  215. style.height = '100%';
  216. style.margin = 'unset';
  217. }
  218. const body = this.renderBody();
  219. const header = this.renderHeader();
  220. const footer = props.footer ? <div className={`${cssClasses.DIALOG}-footer`}>{props.footer}</div> : null;
  221. const dialogElement = (
  222. // eslint-disable-next-line jsx-a11y/no-static-element-interactions
  223. <div
  224. key="dialog-element"
  225. className={digCls}
  226. onMouseDown={this.onDialogMouseDown}
  227. style={{ ...props.style, ...style }}
  228. id={this.dialogId}
  229. >
  230. <div
  231. role="dialog"
  232. ref={this.modalDialogRef}
  233. aria-modal="true"
  234. aria-labelledby={`${cssClasses.DIALOG}-title`}
  235. aria-describedby={`${cssClasses.DIALOG}-body`}
  236. onAnimationEnd={props.onAnimationEnd}
  237. className={cls([`${cssClasses.DIALOG}-content`,
  238. props.contentClassName,
  239. {[`${cssClasses.DIALOG}-content-fullScreen`]: props.isFullScreen }])}>
  240. {header}
  241. {body}
  242. {footer}
  243. </div>
  244. </div>
  245. );
  246. // return props.visible ? dialogElement : null;
  247. return dialogElement;
  248. };
  249. render() {
  250. const {
  251. maskClosable,
  252. className,
  253. getPopupContainer,
  254. maskFixed,
  255. getContainerContext,
  256. } = this.props;
  257. const { direction } = this.context;
  258. const classList = cls(className, {
  259. [`${cssClasses.DIALOG}-popup`]: getPopupContainer && !maskFixed,
  260. [`${cssClasses.DIALOG}-fixed`]: maskFixed,
  261. [`${cssClasses.DIALOG}-rtl`]: direction === 'rtl',
  262. });
  263. const containerContext = getContainerContext();
  264. const elem = (
  265. <div className={classList}>
  266. {this.getMaskElement()}
  267. <div
  268. role="none"
  269. tabIndex={-1}
  270. className={`${cssClasses.DIALOG}-wrap`}
  271. onClick={maskClosable ? this.onMaskClick : null}
  272. onMouseUp={maskClosable ? this.onMaskMouseUp : null}
  273. >
  274. {this.getDialogElement()}
  275. </div>
  276. </div>
  277. );
  278. // @ts-ignore Unreachable branch
  279. // eslint-disable-next-line max-len
  280. return containerContext && containerContext.Provider ?
  281. <containerContext.Provider value={containerContext.value}>{elem}</containerContext.Provider> : elem;
  282. }
  283. }