Modal.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { cssClasses, strings } from '@douyinfe/semi-foundation/modal/constants';
  2. import '@douyinfe/semi-foundation/modal/modal.scss';
  3. import ModalFoundation, { ModalAdapter, ModalProps, ModalState } from '@douyinfe/semi-foundation/modal/modalFoundation';
  4. import cls from 'classnames';
  5. import { noop } from 'lodash';
  6. import PropTypes from 'prop-types';
  7. import React, { CSSProperties, LegacyRef, ReactNode } from 'react';
  8. import BaseComponent from '../_base/baseComponent';
  9. import CSSAnimation from "../_cssAnimation";
  10. import Portal from '../_portal';
  11. import { getDefaultPropsFromGlobalConfig, getScrollbarWidth } from '../_utils';
  12. import Button from '../button';
  13. import { ButtonProps } from '../button/Button';
  14. import { Locale } from '../locale/interface';
  15. import LocaleConsumer from '../locale/localeConsumer';
  16. import ModalContent from './ModalContent';
  17. import confirm, { withConfirm, withError, withInfo, withSuccess, withWarning } from './confirm';
  18. import useModal from './useModal';
  19. export let 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 __SemiComponentName__ = "Modal";
  83. static defaultProps = getDefaultPropsFromGlobalConfig(Modal.__SemiComponentName__, {
  84. zIndex: 1000,
  85. motion: true,
  86. mask: true,
  87. centered: false,
  88. closable: true,
  89. visible: false,
  90. okType: 'primary',
  91. maskClosable: true,
  92. hasCancel: true,
  93. onCancel: noop,
  94. onOk: noop,
  95. afterClose: noop,
  96. maskFixed: false,
  97. closeOnEsc: true,
  98. size: 'small',
  99. keepDOM: false,
  100. lazyRender: true,
  101. fullScreen: false,
  102. });
  103. static useModal = useModal;
  104. foundation: ModalFoundation;
  105. private readonly modalRef: LegacyRef<ModalContent>;
  106. private bodyOverflow: string|null = null;
  107. private scrollBarWidth: number;
  108. private originBodyWidth: string;
  109. private _haveRendered: boolean;
  110. constructor(props: ModalReactProps) {
  111. super(props);
  112. this.state = {
  113. displayNone: !props.visible,
  114. isFullScreen: props.fullScreen,
  115. };
  116. this.foundation = new ModalFoundation(this.adapter);
  117. this.modalRef = React.createRef();
  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 || getPopupContainer() === globalThis?.document?.body) && 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 || getPopupContainer() === globalThis?.document?.body) && this.bodyOverflow !== null && 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. for (let i = 0, len = destroyFns.length; i < len; i++) {
  192. const close = destroyFns[i];
  193. if (close) {
  194. close();
  195. }
  196. }
  197. destroyFns = [];
  198. };
  199. componentDidMount() {
  200. this.scrollBarWidth = getScrollbarWidth();
  201. this.originBodyWidth = document.body.style.width;
  202. if (this.props.visible) {
  203. this.foundation.beforeShow();
  204. }
  205. }
  206. componentDidUpdate(prevProps: ModalReactProps, prevState: ModalState, snapshot: any) {
  207. // hide => show
  208. if (!prevProps.visible && this.props.visible) {
  209. this.foundation.beforeShow();
  210. }
  211. if (!prevState.displayNone && this.state.displayNone) {
  212. this.foundation.afterHide();
  213. }
  214. }
  215. componentWillUnmount() {
  216. if (this.props.visible) {
  217. this.foundation.destroy();
  218. } else {
  219. this.foundation.enabledBodyScroll();
  220. }
  221. }
  222. handleCancel = (e: React.MouseEvent) => {
  223. this.foundation.handleCancel(e);
  224. };
  225. handleOk = (e: React.MouseEvent) => {
  226. this.foundation.handleOk(e);
  227. };
  228. updateState = () => {
  229. const { visible } = this.props;
  230. this.foundation.toggleDisplayNone(!visible);
  231. };
  232. renderFooter = (): ReactNode => {
  233. const {
  234. okText,
  235. okType,
  236. cancelText,
  237. confirmLoading,
  238. cancelLoading,
  239. hasCancel,
  240. footerFill,
  241. } = this.props;
  242. const getCancelButton = (locale: Locale['Modal']) => {
  243. if (!hasCancel) {
  244. return null;
  245. } else {
  246. return (
  247. <Button
  248. aria-label="cancel"
  249. onClick={this.handleCancel}
  250. loading={cancelLoading === undefined ? this.state.onCancelReturnPromiseStatus === "pending" : cancelLoading}
  251. type="tertiary"
  252. block={footerFill}
  253. autoFocus={true}
  254. {...this.props.cancelButtonProps}
  255. style={{
  256. ...footerFill ? { marginLeft: "unset" }:{},
  257. ...this.props.cancelButtonProps?.style
  258. }}
  259. x-semi-children-alias="cancelText"
  260. >
  261. {cancelText || locale.cancel}
  262. </Button>
  263. );
  264. }
  265. };
  266. return (
  267. <LocaleConsumer componentName="Modal">
  268. {(locale: Locale['Modal'], localeCode: Locale['code']) => (
  269. <div className={cls({
  270. [`${cssClasses.DIALOG}-footerfill`]: footerFill
  271. })}>
  272. {getCancelButton(locale)}
  273. <Button
  274. aria-label="confirm"
  275. type={okType}
  276. theme="solid"
  277. block={footerFill}
  278. loading={confirmLoading === undefined ? this.state.onOKReturnPromiseStatus === "pending" : confirmLoading}
  279. onClick={this.handleOk}
  280. {...this.props.okButtonProps}
  281. x-semi-children-alias="okText"
  282. >
  283. {okText || locale.confirm}
  284. </Button>
  285. </div>
  286. )}
  287. </LocaleConsumer>
  288. );
  289. };
  290. // getDialog = () => {
  291. // const {
  292. // footer,
  293. // ...restProps
  294. // } = this.props;
  295. // const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  296. // return <ModalContent {...restProps} footer={renderFooter} onClose={this.handleCancel}/>;
  297. // };
  298. renderDialog = () => {
  299. let {
  300. footer,
  301. className,
  302. motion,
  303. maskStyle: maskStyleFromProps,
  304. keepDOM,
  305. style: styleFromProps,
  306. zIndex,
  307. getPopupContainer,
  308. visible,
  309. modalContentClass,
  310. ...restProps
  311. } = this.props;
  312. let style = styleFromProps;
  313. const maskStyle = maskStyleFromProps;
  314. const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  315. let wrapperStyle: {
  316. zIndex?: CSSProperties['zIndex'];
  317. position?: CSSProperties['position']
  318. } = {
  319. zIndex,
  320. };
  321. if (getPopupContainer && getPopupContainer() !== globalThis?.document?.body) {
  322. wrapperStyle = {
  323. zIndex,
  324. position: 'static',
  325. };
  326. }
  327. const classList = cls(className, {
  328. [`${cssClasses.DIALOG}-displayNone`]: keepDOM && this.state.displayNone,
  329. });
  330. 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 */);
  331. if (shouldRender) {
  332. this._haveRendered = true;
  333. }
  334. return (
  335. <CSSAnimation
  336. motion={this.props.motion}
  337. animationState={visible ? 'enter' : 'leave'}
  338. startClassName={visible ? `${cssClasses.DIALOG}-content-animate-show` : `${cssClasses.DIALOG}-content-animate-hide`}
  339. onAnimationEnd={() => {
  340. this.updateState();
  341. }}
  342. >
  343. {
  344. ({ animationClassName, animationEventsNeedBind }) => {
  345. return <CSSAnimation motion={this.props.motion} animationState={visible ? 'enter' : 'leave'}
  346. startClassName={visible ? `${cssClasses.DIALOG}-mask-animate-show` : `${cssClasses.DIALOG}-mask-animate-hide`}
  347. onAnimationEnd={() => {
  348. this.updateState();
  349. }}
  350. >
  351. {
  352. ({ animationClassName: maskAnimationClassName, animationEventsNeedBind: maskAnimationEventsNeedBind }) => {
  353. return shouldRender ? <Portal style={wrapperStyle} getPopupContainer={getPopupContainer}> <ModalContent
  354. {...restProps}
  355. contentExtraProps={animationEventsNeedBind}
  356. maskExtraProps={maskAnimationEventsNeedBind}
  357. isFullScreen={this.state.isFullScreen}
  358. contentClassName={`${animationClassName} ${modalContentClass}`}
  359. maskClassName={maskAnimationClassName}
  360. className={classList}
  361. getPopupContainer={getPopupContainer}
  362. maskStyle={maskStyle}
  363. style={style}
  364. ref={this.modalRef}
  365. footer={renderFooter}
  366. onClose={this.handleCancel}
  367. /></Portal> : <></>;
  368. }
  369. }
  370. </CSSAnimation>;
  371. }
  372. }
  373. </CSSAnimation>
  374. );
  375. };
  376. render() {
  377. const {
  378. visible,
  379. keepDOM,
  380. lazyRender,
  381. } = this.props;
  382. return this.renderDialog();
  383. }
  384. }
  385. export default Modal;