Modal.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import React, { CSSProperties, LegacyRef, ReactNode } from 'react';
  2. import { cssClasses, strings } from '@douyinfe/semi-foundation/modal/constants';
  3. import Button from '../button';
  4. import ModalFoundation, { ModalAdapter, ModalProps, ModalState } from '@douyinfe/semi-foundation/modal/modalFoundation';
  5. import ModalContent from './ModalContent';
  6. import Portal from '../_portal';
  7. import LocaleConsumer from '../locale/localeConsumer';
  8. import cls from 'classnames';
  9. import PropTypes from 'prop-types';
  10. import { noop } from 'lodash';
  11. import '@douyinfe/semi-foundation/modal/modal.scss';
  12. import BaseComponent from '../_base/baseComponent';
  13. import confirm, { withConfirm, withError, withInfo, withSuccess, withWarning } from './confirm';
  14. import { Locale } from '../locale/interface';
  15. import useModal from './useModal';
  16. import { ButtonProps } from '../button/Button';
  17. import CSSAnimation from "../_cssAnimation";
  18. import { getScrollbarWidth } from '../_utils';
  19. export const destroyFns: any[] = [];
  20. export type ConfirmType = 'leftTop' | 'leftBottom' | 'rightTop' | 'rightBottom';
  21. export type Directions = 'ltr' | 'rtl';
  22. export type { ModalState };
  23. export interface ModalReactProps extends ModalProps {
  24. cancelButtonProps?: ButtonProps;
  25. children?: React.ReactNode;
  26. okButtonProps?: ButtonProps;
  27. bodyStyle?: CSSProperties;
  28. maskStyle?: CSSProperties;
  29. style?: CSSProperties;
  30. icon?: ReactNode;
  31. closeIcon?: ReactNode;
  32. title?: ReactNode;
  33. content?: ReactNode;
  34. footer?: ReactNode;
  35. header?: ReactNode;
  36. onCancel?: (e: React.MouseEvent) => void | Promise<any>;
  37. onOk?: (e: React.MouseEvent) => void | Promise<any>
  38. }
  39. class Modal extends BaseComponent<ModalReactProps, ModalState> {
  40. static propTypes = {
  41. mask: PropTypes.bool,
  42. closable: PropTypes.bool,
  43. centered: PropTypes.bool,
  44. visible: PropTypes.bool,
  45. width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  46. height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  47. confirmLoading: PropTypes.bool,
  48. cancelLoading: PropTypes.bool,
  49. okText: PropTypes.string,
  50. okType: PropTypes.string,
  51. cancelText: PropTypes.string,
  52. maskClosable: PropTypes.bool,
  53. onCancel: PropTypes.func,
  54. onOk: PropTypes.func,
  55. afterClose: PropTypes.func,
  56. okButtonProps: PropTypes.object,
  57. cancelButtonProps: PropTypes.object,
  58. style: PropTypes.object,
  59. className: PropTypes.string,
  60. maskStyle: PropTypes.object,
  61. bodyStyle: PropTypes.object,
  62. zIndex: PropTypes.number,
  63. title: PropTypes.node,
  64. icon: PropTypes.node,
  65. header: PropTypes.node,
  66. footer: PropTypes.node,
  67. hasCancel: PropTypes.bool,
  68. motion: PropTypes.bool,
  69. children: PropTypes.node,
  70. getPopupContainer: PropTypes.func,
  71. getContainerContext: PropTypes.func,
  72. maskFixed: PropTypes.bool,
  73. closeIcon: PropTypes.node,
  74. closeOnEsc: PropTypes.bool,
  75. size: PropTypes.oneOf(strings.SIZE),
  76. keepDOM: PropTypes.bool,
  77. lazyRender: PropTypes.bool,
  78. direction: PropTypes.oneOf(strings.directions),
  79. fullScreen: PropTypes.bool,
  80. footerFill: PropTypes.bool,
  81. };
  82. static defaultProps = {
  83. zIndex: 1000,
  84. motion: true,
  85. mask: true,
  86. centered: false,
  87. closable: true,
  88. visible: false,
  89. okType: 'primary',
  90. maskClosable: true,
  91. hasCancel: true,
  92. onCancel: noop,
  93. onOk: noop,
  94. afterClose: noop,
  95. maskFixed: false,
  96. closeOnEsc: true,
  97. size: 'small',
  98. keepDOM: false,
  99. lazyRender: true,
  100. fullScreen: false,
  101. };
  102. static useModal = useModal;
  103. foundation: ModalFoundation;
  104. private readonly modalRef: LegacyRef<ModalContent>;
  105. private bodyOverflow: string|null = null;
  106. private scrollBarWidth: number;
  107. private originBodyWidth: string;
  108. private _haveRendered: boolean;
  109. constructor(props: ModalReactProps) {
  110. super(props);
  111. this.state = {
  112. displayNone: !props.visible,
  113. isFullScreen: props.fullScreen,
  114. };
  115. this.foundation = new ModalFoundation(this.adapter);
  116. this.modalRef = React.createRef();
  117. this.scrollBarWidth = 0;
  118. this.originBodyWidth = '100%';
  119. }
  120. get adapter(): ModalAdapter {
  121. return {
  122. ...super.adapter,
  123. getProps: () => this.props,
  124. disabledBodyScroll: () => {
  125. const { getPopupContainer } = this.props;
  126. this.bodyOverflow = document.body.style.overflow || '';
  127. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  128. document.body.style.overflow = 'hidden';
  129. document.body.style.width = `calc(${this.originBodyWidth || '100%'} - ${this.scrollBarWidth}px)`;
  130. }
  131. },
  132. enabledBodyScroll: () => {
  133. const { getPopupContainer } = this.props;
  134. if (!getPopupContainer && this.bodyOverflow !== null && this.bodyOverflow !== 'hidden') {
  135. document.body.style.overflow = this.bodyOverflow;
  136. document.body.style.width = this.originBodyWidth;
  137. }
  138. },
  139. notifyCancel: (e: React.MouseEvent) => {
  140. return this.props.onCancel(e);
  141. },
  142. notifyOk: (e: React.MouseEvent) => {
  143. return this.props.onOk(e);
  144. },
  145. notifyClose: () => {
  146. this.props.afterClose();
  147. },
  148. toggleDisplayNone: (displayNone: boolean, callback?: (hidden: boolean) => void) => {
  149. if (displayNone !== this.state.displayNone) {
  150. this.setState({ displayNone: displayNone }, callback || noop);
  151. }
  152. },
  153. notifyFullScreen: (isFullScreen: boolean) => {
  154. if (isFullScreen !== this.state.isFullScreen) {
  155. this.setState({ isFullScreen });
  156. }
  157. },
  158. };
  159. }
  160. static getDerivedStateFromProps(props: ModalReactProps, prevState: ModalState) {
  161. const newState: Partial<ModalState> = {};
  162. if (props.fullScreen !== prevState.isFullScreen) {
  163. newState.isFullScreen = props.fullScreen;
  164. }
  165. if (props.visible && prevState.displayNone) {
  166. newState.displayNone = false;
  167. }
  168. //
  169. // if (!props.visible && !props.motion && !prevState.displayNone) {
  170. // newState.displayNone = true;
  171. // }
  172. return newState;
  173. }
  174. static info = function (props: ModalReactProps) {
  175. return confirm<ReturnType<typeof withInfo>>(withInfo(props));
  176. };
  177. static success = function (props: ModalReactProps) {
  178. return confirm<ReturnType<typeof withSuccess>>(withSuccess(props));
  179. };
  180. static error = function (props: ModalReactProps) {
  181. return confirm<ReturnType<typeof withError>>(withError(props));
  182. };
  183. static warning = function (props: ModalReactProps) {
  184. return confirm<ReturnType<typeof withWarning>>(withWarning(props));
  185. };
  186. static confirm = function (props: ModalReactProps) {
  187. return confirm<ReturnType<typeof withConfirm>>(withConfirm(props));
  188. };
  189. static destroyAll = function destroyAllFn() {
  190. while (destroyFns.length) {
  191. const close = destroyFns.pop();
  192. if (close) {
  193. close();
  194. }
  195. }
  196. };
  197. componentDidMount() {
  198. this.scrollBarWidth = getScrollbarWidth();
  199. this.originBodyWidth = document.body.style.width;
  200. if (this.props.visible) {
  201. this.foundation.beforeShow();
  202. }
  203. }
  204. componentDidUpdate(prevProps: ModalReactProps, prevState: ModalState, snapshot: any) {
  205. // hide => show
  206. if (!prevProps.visible && this.props.visible) {
  207. this.foundation.beforeShow();
  208. }
  209. if (!prevState.displayNone && this.state.displayNone) {
  210. this.foundation.afterHide();
  211. }
  212. }
  213. componentWillUnmount() {
  214. if (this.props.visible) {
  215. this.foundation.destroy();
  216. } else {
  217. this.foundation.enabledBodyScroll();
  218. }
  219. }
  220. handleCancel = (e: React.MouseEvent) => {
  221. this.foundation.handleCancel(e);
  222. };
  223. handleOk = (e: React.MouseEvent) => {
  224. this.foundation.handleOk(e);
  225. };
  226. updateState = () => {
  227. const { visible } = this.props;
  228. this.foundation.toggleDisplayNone(!visible);
  229. };
  230. renderFooter = (): ReactNode => {
  231. const {
  232. okText,
  233. okType,
  234. cancelText,
  235. confirmLoading,
  236. cancelLoading,
  237. hasCancel,
  238. footerFill,
  239. } = this.props;
  240. const getCancelButton = (locale: Locale['Modal']) => {
  241. if (!hasCancel) {
  242. return null;
  243. } else {
  244. return (
  245. <Button
  246. aria-label="cancel"
  247. onClick={this.handleCancel}
  248. loading={cancelLoading === undefined ? this.state.onCancelReturnPromiseStatus === "pending" : cancelLoading}
  249. type="tertiary"
  250. block={footerFill}
  251. autoFocus={true}
  252. {...this.props.cancelButtonProps}
  253. x-semi-children-alias="cancelText"
  254. >
  255. {cancelText || locale.cancel}
  256. </Button>
  257. );
  258. }
  259. };
  260. return (
  261. <LocaleConsumer componentName="Modal">
  262. {(locale: Locale['Modal'], localeCode: Locale['code']) => (
  263. <div className={cls({
  264. [`${cssClasses.DIALOG}-footerfill`]: footerFill
  265. })}>
  266. {getCancelButton(locale)}
  267. <Button
  268. aria-label="confirm"
  269. type={okType}
  270. theme="solid"
  271. block={footerFill}
  272. loading={confirmLoading === undefined ? this.state.onOKReturnPromiseStatus === "pending" : confirmLoading}
  273. onClick={this.handleOk}
  274. {...this.props.okButtonProps}
  275. x-semi-children-alias="okText"
  276. >
  277. {okText || locale.confirm}
  278. </Button>
  279. </div>
  280. )}
  281. </LocaleConsumer>
  282. );
  283. };
  284. // getDialog = () => {
  285. // const {
  286. // footer,
  287. // ...restProps
  288. // } = this.props;
  289. // const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  290. // return <ModalContent {...restProps} footer={renderFooter} onClose={this.handleCancel}/>;
  291. // };
  292. renderDialog = () => {
  293. let {
  294. footer,
  295. className,
  296. motion,
  297. maskStyle: maskStyleFromProps,
  298. keepDOM,
  299. style: styleFromProps,
  300. zIndex,
  301. getPopupContainer,
  302. visible,
  303. ...restProps
  304. } = this.props;
  305. let style = styleFromProps;
  306. const maskStyle = maskStyleFromProps;
  307. const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  308. let wrapperStyle: {
  309. zIndex?: CSSProperties['zIndex'];
  310. position?: CSSProperties['position']
  311. } = {
  312. zIndex,
  313. };
  314. if (getPopupContainer) {
  315. wrapperStyle = {
  316. zIndex,
  317. position: 'static',
  318. };
  319. }
  320. const classList = cls(className, {
  321. [`${cssClasses.DIALOG}-displayNone`]: keepDOM && this.state.displayNone,
  322. });
  323. const shouldRender = this.props.visible || (this.props.keepDOM && (!this.props.lazyRender || this._haveRendered)) || (this.props.motion && !this.state.displayNone /* When there is animation, we use displayNone to judge whether animation is ended and judge whether to unmount content */);
  324. if (shouldRender) {
  325. this._haveRendered = true;
  326. }
  327. return (
  328. <CSSAnimation
  329. motion={this.props.motion}
  330. animationState={visible ? 'enter' : 'leave'}
  331. startClassName={visible ? `${cssClasses.DIALOG}-content-animate-show` : `${cssClasses.DIALOG}-content-animate-hide`}
  332. onAnimationEnd={() => {
  333. this.updateState();
  334. }}
  335. >
  336. {
  337. ({ animationClassName, animationEventsNeedBind }) => {
  338. return <CSSAnimation motion={this.props.motion} animationState={visible ? 'enter' : 'leave'}
  339. startClassName={visible ? `${cssClasses.DIALOG}-mask-animate-show` : `${cssClasses.DIALOG}-mask-animate-hide`}
  340. onAnimationEnd={() => {
  341. this.updateState();
  342. }}
  343. >
  344. {
  345. ({ animationClassName: maskAnimationClassName, animationEventsNeedBind: maskAnimationEventsNeedBind }) => {
  346. return shouldRender ? <Portal style={wrapperStyle} getPopupContainer={getPopupContainer}> <ModalContent
  347. {...restProps}
  348. contentExtraProps={animationEventsNeedBind}
  349. maskExtraProps={maskAnimationEventsNeedBind}
  350. isFullScreen={this.state.isFullScreen}
  351. contentClassName={animationClassName}
  352. maskClassName={maskAnimationClassName}
  353. className={classList}
  354. getPopupContainer={getPopupContainer}
  355. maskStyle={maskStyle}
  356. style={style}
  357. ref={this.modalRef}
  358. footer={renderFooter}
  359. onClose={this.handleCancel}
  360. /></Portal> : <></>;
  361. }
  362. }
  363. </CSSAnimation>;
  364. }
  365. }
  366. </CSSAnimation>
  367. );
  368. };
  369. render() {
  370. const {
  371. visible,
  372. keepDOM,
  373. lazyRender,
  374. } = this.props;
  375. return this.renderDialog();
  376. }
  377. }
  378. export default Modal;