Modal.tsx 15 KB

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