ModalContent.tsx 12 KB

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