ModalContent.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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);
  75. }
  76. },
  77. removeKeyDownEventListener: () => {
  78. if (this.props.closeOnEsc) {
  79. document.removeEventListener('keydown', this.foundation.handleKeyDown);
  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. const nodes = FocusTrapHandle.getFocusableElements(this.modalDialogRef.current);
  112. if (!this.modalDialogRef.current.contains(document.activeElement)) {
  113. // focus on first focusable element
  114. nodes[0]?.focus();
  115. }
  116. }
  117. componentWillUnmount() {
  118. clearTimeout(this.timeoutId);
  119. this.foundation.destroy();
  120. }
  121. onKeyDown = (e: React.MouseEvent) => {
  122. this.foundation.handleKeyDown(e);
  123. };
  124. // Record when clicking the modal box
  125. onDialogMouseDown = () => {
  126. this.foundation.handleDialogMouseDown();
  127. };
  128. // Cancel recording when clicking the modal box at the end
  129. onMaskMouseUp = () => {
  130. this.foundation.handleMaskMouseUp();
  131. };
  132. // onMaskClick will judge dialogMouseDown before onMaskMouseUp updates dialogMouseDown
  133. onMaskClick = (e: React.MouseEvent) => {
  134. this.foundation.handleMaskClick(e);
  135. };
  136. close = (e: React.MouseEvent) => {
  137. this.foundation.close(e);
  138. };
  139. getMaskElement = () => {
  140. const { ...props } = this.props;
  141. const { mask, maskClassName } = props;
  142. if (mask) {
  143. const className = cls(`${cssClasses.DIALOG}-mask`, {
  144. // [`${cssClasses.DIALOG}-mask-hidden`]: !props.visible,
  145. });
  146. return <div key="mask" {...this.props.maskExtraProps} className={cls(className, maskClassName)} style={props.maskStyle}/>;
  147. }
  148. return null;
  149. };
  150. renderCloseBtn = () => {
  151. const {
  152. closable,
  153. closeIcon,
  154. } = this.props;
  155. let closer;
  156. if (closable) {
  157. const iconType = closeIcon || <IconClose x-semi-prop="closeIcon"/>;
  158. closer = (
  159. <Button
  160. aria-label="close"
  161. className={`${cssClasses.DIALOG}-close`}
  162. key="close-btn"
  163. onClick={this.close}
  164. type="tertiary"
  165. icon={iconType}
  166. theme="borderless"
  167. size="small"
  168. />
  169. );
  170. }
  171. return closer;
  172. };
  173. renderIcon = () => {
  174. const { icon } = this.props;
  175. return icon ? <span className={`${cssClasses.DIALOG}-icon-wrapper`} x-semi-prop="icon">{icon}</span> : null;
  176. };
  177. renderHeader = () => {
  178. if ('header' in this.props) {
  179. return this.props.header;
  180. }
  181. const { title } = this.props;
  182. const closer = this.renderCloseBtn();
  183. const icon = this.renderIcon();
  184. return (title === null || title === undefined) ?
  185. null :
  186. (
  187. <div className={`${cssClasses.DIALOG}-header`}>
  188. {icon}
  189. <Typography.Title
  190. heading={5}
  191. className={`${cssClasses.DIALOG}-title`}
  192. id={`${cssClasses.DIALOG}-title`}
  193. x-semi-prop="title"
  194. >
  195. {title}
  196. </Typography.Title>
  197. {closer}
  198. </div>
  199. );
  200. };
  201. renderBody = () => {
  202. const {
  203. bodyStyle,
  204. children,
  205. title,
  206. } = this.props;
  207. const bodyCls = cls(`${cssClasses.DIALOG}-body`, {
  208. [`${cssClasses.DIALOG}-withIcon`]: this.props.icon,
  209. });
  210. const closer = this.renderCloseBtn();
  211. const icon = this.renderIcon();
  212. const hasHeader = title !== null && title !== undefined || 'header' in this.props;
  213. return hasHeader ? (
  214. <div className={bodyCls} id={`${cssClasses.DIALOG}-body`} style={bodyStyle} x-semi-prop="children">
  215. {children}
  216. </div>
  217. ) : (
  218. <div className={`${cssClasses.DIALOG}-body-wrapper`}>
  219. {icon}
  220. <div className={bodyCls} style={bodyStyle} x-semi-prop="children">
  221. {children}
  222. </div>
  223. {closer}
  224. </div>
  225. );
  226. };
  227. getDialogElement = () => {
  228. const { ...props } = this.props;
  229. const style: CSSProperties = {};
  230. const digCls = cls(`${cssClasses.DIALOG}`, {
  231. [`${cssClasses.DIALOG}-centered`]: props.centered,
  232. [`${cssClasses.DIALOG}-${props.size}`]: props.size,
  233. });
  234. if (props.width) {
  235. style.width = props.width;
  236. }
  237. if (props.height) {
  238. style.height = props.height;
  239. }
  240. if (props.isFullScreen) {
  241. style.width = '100%';
  242. style.height = '100%';
  243. style.margin = 'unset';
  244. }
  245. const body = this.renderBody();
  246. const header = this.renderHeader();
  247. const footer = props.footer ? (
  248. <div className={`${cssClasses.DIALOG}-footer`} x-semi-prop="footer">
  249. {props.footer}
  250. </div>
  251. ) : null;
  252. const dialogElement = (
  253. // eslint-disable-next-line jsx-a11y/no-static-element-interactions
  254. <div
  255. key="dialog-element"
  256. className={digCls}
  257. onMouseDown={this.onDialogMouseDown}
  258. style={{ ...props.style, ...style }}
  259. id={this.dialogId}
  260. >
  261. <div
  262. role="dialog"
  263. ref={this.modalDialogRef}
  264. aria-modal="true"
  265. aria-labelledby={`${cssClasses.DIALOG}-title`}
  266. aria-describedby={`${cssClasses.DIALOG}-body`}
  267. onAnimationEnd={props.onAnimationEnd}
  268. className={cls([`${cssClasses.DIALOG}-content`,
  269. props.contentClassName,
  270. { [`${cssClasses.DIALOG}-content-fullScreen`]: props.isFullScreen }])}>
  271. {header}
  272. {body}
  273. {footer}
  274. </div>
  275. </div>
  276. );
  277. // return props.visible ? dialogElement : null;
  278. return dialogElement;
  279. };
  280. render() {
  281. const {
  282. maskClosable,
  283. className,
  284. getPopupContainer,
  285. maskFixed,
  286. getContainerContext,
  287. } = this.props;
  288. const { direction } = this.context;
  289. const classList = cls(className, {
  290. [`${cssClasses.DIALOG}-popup`]: getPopupContainer && !maskFixed,
  291. [`${cssClasses.DIALOG}-fixed`]: maskFixed,
  292. [`${cssClasses.DIALOG}-rtl`]: direction === 'rtl',
  293. });
  294. const containerContext = getContainerContext();
  295. const elem = (
  296. <div className={classList}>
  297. {this.getMaskElement()}
  298. <div
  299. role="none"
  300. className={cls({
  301. [`${cssClasses.DIALOG}-wrap`]: true,
  302. [`${cssClasses.DIALOG}-wrap-center`]: this.props.centered
  303. })}
  304. onClick={maskClosable ? this.onMaskClick : null}
  305. onMouseUp={maskClosable ? this.onMaskMouseUp : null}
  306. {...this.props.contentExtraProps}
  307. >
  308. {this.getDialogElement()}
  309. </div>
  310. </div>
  311. );
  312. // eslint-disable-next-line max-len
  313. return containerContext && containerContext.Provider ?
  314. <containerContext.Provider value={containerContext.value}>{elem}</containerContext.Provider> : elem;
  315. }
  316. }