ModalContent.tsx 11 KB

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