Modal.tsx 15 KB

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