1
0

Modal.tsx 15 KB

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