ModalContent.tsx 11 KB

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