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;
  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.bodyOverflow = '';
  118. this.scrollBarWidth = 0;
  119. this.originBodyWidth = '100%';
  120. }
  121. get adapter(): ModalAdapter {
  122. return {
  123. ...super.adapter,
  124. getProps: () => this.props,
  125. disabledBodyScroll: () => {
  126. const { getPopupContainer } = this.props;
  127. this.bodyOverflow = document.body.style.overflow || '';
  128. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  129. document.body.style.overflow = 'hidden';
  130. document.body.style.width = `calc(${this.originBodyWidth || '100%'} - ${this.scrollBarWidth}px)`;
  131. }
  132. },
  133. enabledBodyScroll: () => {
  134. const { getPopupContainer } = this.props;
  135. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  136. document.body.style.overflow = this.bodyOverflow;
  137. document.body.style.width = this.originBodyWidth;
  138. }
  139. },
  140. notifyCancel: (e: React.MouseEvent) => {
  141. return this.props.onCancel(e);
  142. },
  143. notifyOk: (e: React.MouseEvent) => {
  144. return this.props.onOk(e);
  145. },
  146. notifyClose: () => {
  147. this.props.afterClose();
  148. },
  149. toggleDisplayNone: (displayNone: boolean, callback?: (hidden: boolean) => void) => {
  150. if (displayNone !== this.state.displayNone) {
  151. this.setState({ displayNone: displayNone }, callback || noop);
  152. }
  153. },
  154. notifyFullScreen: (isFullScreen: boolean) => {
  155. if (isFullScreen !== this.state.isFullScreen) {
  156. this.setState({ isFullScreen });
  157. }
  158. },
  159. };
  160. }
  161. static getDerivedStateFromProps(props: ModalReactProps, prevState: ModalState) {
  162. const newState: Partial<ModalState> = {};
  163. if (props.fullScreen !== prevState.isFullScreen) {
  164. newState.isFullScreen = props.fullScreen;
  165. }
  166. if (props.visible && prevState.displayNone) {
  167. newState.displayNone = false;
  168. }
  169. //
  170. // if (!props.visible && !props.motion && !prevState.displayNone) {
  171. // newState.displayNone = true;
  172. // }
  173. return newState;
  174. }
  175. static info = function (props: ModalReactProps) {
  176. return confirm<ReturnType<typeof withInfo>>(withInfo(props));
  177. };
  178. static success = function (props: ModalReactProps) {
  179. return confirm<ReturnType<typeof withSuccess>>(withSuccess(props));
  180. };
  181. static error = function (props: ModalReactProps) {
  182. return confirm<ReturnType<typeof withError>>(withError(props));
  183. };
  184. static warning = function (props: ModalReactProps) {
  185. return confirm<ReturnType<typeof withWarning>>(withWarning(props));
  186. };
  187. static confirm = function (props: ModalReactProps) {
  188. return confirm<ReturnType<typeof withConfirm>>(withConfirm(props));
  189. };
  190. static destroyAll = function destroyAllFn() {
  191. while (destroyFns.length) {
  192. const close = destroyFns.pop();
  193. if (close) {
  194. close();
  195. }
  196. }
  197. };
  198. componentDidMount() {
  199. this.scrollBarWidth = getScrollbarWidth();
  200. this.originBodyWidth = document.body.style.width;
  201. if (this.props.visible) {
  202. this.foundation.beforeShow();
  203. }
  204. }
  205. componentDidUpdate(prevProps: ModalReactProps, prevState: ModalState, snapshot: any) {
  206. // hide => show
  207. if (!prevProps.visible && this.props.visible) {
  208. this.foundation.beforeShow();
  209. }
  210. if (!prevState.displayNone && this.state.displayNone) {
  211. this.foundation.afterHide();
  212. }
  213. }
  214. componentWillUnmount() {
  215. if (this.props.visible) {
  216. this.foundation.destroy();
  217. } else {
  218. this.foundation.enabledBodyScroll();
  219. }
  220. }
  221. handleCancel = (e: React.MouseEvent) => {
  222. this.foundation.handleCancel(e);
  223. };
  224. handleOk = (e: React.MouseEvent) => {
  225. this.foundation.handleOk(e);
  226. };
  227. updateState = () => {
  228. const { visible } = this.props;
  229. this.foundation.toggleDisplayNone(!visible);
  230. };
  231. renderFooter = (): ReactNode => {
  232. const {
  233. okText,
  234. okType,
  235. cancelText,
  236. confirmLoading,
  237. cancelLoading,
  238. hasCancel,
  239. footerFill,
  240. } = this.props;
  241. const getCancelButton = (locale: Locale['Modal']) => {
  242. if (!hasCancel) {
  243. return null;
  244. } else {
  245. return (
  246. <Button
  247. aria-label="cancel"
  248. onClick={this.handleCancel}
  249. loading={cancelLoading === undefined ? this.state.onCancelReturnPromiseStatus === "pending" : cancelLoading}
  250. type="tertiary"
  251. block={footerFill}
  252. autoFocus={true}
  253. {...this.props.cancelButtonProps}
  254. x-semi-children-alias="cancelText"
  255. >
  256. {cancelText || locale.cancel}
  257. </Button>
  258. );
  259. }
  260. };
  261. return (
  262. <LocaleConsumer componentName="Modal">
  263. {(locale: Locale['Modal'], localeCode: Locale['code']) => (
  264. <div className={cls({
  265. [`${cssClasses.DIALOG}-footerfill`]: footerFill
  266. })}>
  267. {getCancelButton(locale)}
  268. <Button
  269. aria-label="confirm"
  270. type={okType}
  271. theme="solid"
  272. block={footerFill}
  273. loading={confirmLoading === undefined ? this.state.onOKReturnPromiseStatus === "pending" : confirmLoading}
  274. onClick={this.handleOk}
  275. {...this.props.okButtonProps}
  276. x-semi-children-alias="okText"
  277. >
  278. {okText || locale.confirm}
  279. </Button>
  280. </div>
  281. )}
  282. </LocaleConsumer>
  283. );
  284. };
  285. // getDialog = () => {
  286. // const {
  287. // footer,
  288. // ...restProps
  289. // } = this.props;
  290. // const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  291. // return <ModalContent {...restProps} footer={renderFooter} onClose={this.handleCancel}/>;
  292. // };
  293. renderDialog = () => {
  294. let {
  295. footer,
  296. className,
  297. motion,
  298. maskStyle: maskStyleFromProps,
  299. keepDOM,
  300. style: styleFromProps,
  301. zIndex,
  302. getPopupContainer,
  303. visible,
  304. ...restProps
  305. } = this.props;
  306. let style = styleFromProps;
  307. const maskStyle = maskStyleFromProps;
  308. const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  309. let wrapperStyle: {
  310. zIndex?: CSSProperties['zIndex'];
  311. position?: CSSProperties['position']
  312. } = {
  313. zIndex,
  314. };
  315. if (getPopupContainer) {
  316. wrapperStyle = {
  317. zIndex,
  318. position: 'static',
  319. };
  320. }
  321. const classList = cls(className, {
  322. [`${cssClasses.DIALOG}-displayNone`]: keepDOM && this.state.displayNone,
  323. });
  324. 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 */);
  325. if (shouldRender) {
  326. this._haveRendered = true;
  327. }
  328. return (
  329. <CSSAnimation
  330. motion={this.props.motion}
  331. animationState={visible ? 'enter' : 'leave'}
  332. startClassName={visible ? `${cssClasses.DIALOG}-content-animate-show` : `${cssClasses.DIALOG}-content-animate-hide`}
  333. onAnimationEnd={() => {
  334. this.updateState();
  335. }}
  336. >
  337. {
  338. ({ animationClassName, animationEventsNeedBind }) => {
  339. return <CSSAnimation motion={this.props.motion} animationState={visible ? 'enter' : 'leave'}
  340. startClassName={visible ? `${cssClasses.DIALOG}-mask-animate-show` : `${cssClasses.DIALOG}-mask-animate-hide`}
  341. onAnimationEnd={() => {
  342. this.updateState();
  343. }}
  344. >
  345. {
  346. ({ animationClassName: maskAnimationClassName, animationEventsNeedBind: maskAnimationEventsNeedBind }) => {
  347. return shouldRender ? <Portal style={wrapperStyle} getPopupContainer={getPopupContainer}> <ModalContent
  348. {...restProps}
  349. contentExtraProps={animationEventsNeedBind}
  350. maskExtraProps={maskAnimationEventsNeedBind}
  351. isFullScreen={this.state.isFullScreen}
  352. contentClassName={animationClassName}
  353. maskClassName={maskAnimationClassName}
  354. className={classList}
  355. getPopupContainer={getPopupContainer}
  356. maskStyle={maskStyle}
  357. style={style}
  358. ref={this.modalRef}
  359. footer={renderFooter}
  360. onClose={this.handleCancel}
  361. /></Portal> : <></>;
  362. }
  363. }
  364. </CSSAnimation>;
  365. }
  366. }
  367. </CSSAnimation>
  368. );
  369. };
  370. render() {
  371. const {
  372. visible,
  373. keepDOM,
  374. lazyRender,
  375. } = this.props;
  376. return this.renderDialog();
  377. }
  378. }
  379. export default Modal;