Modal.tsx 15 KB

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