Modal.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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-es';
  12. import '@douyinfe/semi-foundation/modal/modal.scss';
  13. import BaseComponent from '../_base/baseComponent';
  14. import confirm, { withConfirm, withError, withInfo, withSuccess, withWarning } from '../modal/confirm';
  15. import { Locale } from '../locale/interface';
  16. import useModal from '../modal/useModal';
  17. import { ButtonProps } from '../button/Button';
  18. export const destroyFns: any[] = [];
  19. export type ConfirmType = 'leftTop' | 'leftBottom' | 'rightTop' | 'rightBottom';
  20. export type Directions = 'ltr' | 'rtl';
  21. export interface ModalReactProps extends ModalProps {
  22. cancelButtonProps?: ButtonProps;
  23. okButtonProps?: ButtonProps;
  24. bodyStyle?: CSSProperties;
  25. maskStyle?: CSSProperties;
  26. style?: CSSProperties;
  27. icon?: ReactNode;
  28. closeIcon?: ReactNode;
  29. title?: ReactNode;
  30. content?: ReactNode;
  31. footer?: ReactNode;
  32. header?: ReactNode;
  33. onCancel?: (e: React.MouseEvent) => void | Promise<any>;
  34. onOk?: (e: React.MouseEvent) => void | Promise<any>;
  35. }
  36. export {
  37. ModalState
  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.number,
  46. height: 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: false,
  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 _active: boolean;
  110. constructor(props: ModalReactProps) {
  111. super(props);
  112. this.state = {
  113. hidden: !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. toggleHidden: (hidden: boolean, callback?: (hidden: boolean) => void) => {
  151. if (hidden !== this.state.hidden) {
  152. this.setState({ hidden }, 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. return newState;
  168. }
  169. static getScrollbarWidth() {
  170. if (globalThis && Object.prototype.toString.call(globalThis) === '[object Window]') {
  171. return window.innerWidth - document.documentElement.clientWidth;
  172. }
  173. return 0;
  174. }
  175. static info = function (props: ModalReactProps) {
  176. return confirm(withInfo(props));
  177. };
  178. static success = function (props: ModalReactProps) {
  179. return confirm(withSuccess(props));
  180. };
  181. static error = function (props: ModalReactProps) {
  182. return confirm(withError(props));
  183. };
  184. static warning = function (props: ModalReactProps) {
  185. return confirm(withWarning(props));
  186. };
  187. static confirm = function (props: ModalReactProps) {
  188. return confirm(withConfirm(props));
  189. };
  190. static destroyAll = function destroyAllFn() {
  191. while (destroyFns.length) {
  192. const close = destroyFns.pop();
  193. if (close) {
  194. close();
  195. }
  196. }
  197. };
  198. componentDidMount() {
  199. this.scrollBarWidth = Modal.getScrollbarWidth();
  200. this.originBodyWith = document.body.style.width;
  201. if (this.props.visible) {
  202. this.foundation.beforeShow();
  203. this._active = this._active || this.props.visible;
  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. // show => hide
  212. if (prevProps.visible && !this.props.visible) {
  213. this.foundation.afterHide();
  214. }
  215. if (!this.props.motion) {
  216. this.updateHiddenState();
  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. updateHiddenState = () => {
  231. const { visible } = this.props;
  232. const { hidden } = this.state;
  233. if (!visible && !hidden) {
  234. this.foundation.toggleHidden(true, () => this.foundation.afterClose());
  235. } else if (visible && this.state.hidden) {
  236. this.foundation.toggleHidden(false)
  237. }
  238. }
  239. renderFooter = (): ReactNode => {
  240. const {
  241. okText,
  242. okType,
  243. cancelText,
  244. confirmLoading,
  245. cancelLoading,
  246. hasCancel,
  247. } = this.props;
  248. const getCancelButton = (locale: Locale['Modal']) => {
  249. if (!hasCancel) {
  250. return null;
  251. } else {
  252. return (
  253. <Button
  254. onClick={this.handleCancel}
  255. loading={cancelLoading}
  256. type="tertiary"
  257. {...this.props.cancelButtonProps}
  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. type={okType}
  271. theme="solid"
  272. loading={confirmLoading}
  273. onClick={this.handleOk}
  274. {...this.props.okButtonProps}
  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. if (this.props.centered) {
  308. style = {
  309. transform: 'translateY(-50%)',
  310. top: '50%', ...style,
  311. };
  312. }
  313. let wrapperStyle: {
  314. zIndex?: CSSProperties['zIndex'];
  315. position?: CSSProperties['position'];
  316. } = {
  317. zIndex,
  318. };
  319. if (getPopupContainer) {
  320. wrapperStyle = {
  321. zIndex,
  322. position: 'static',
  323. };
  324. }
  325. const classList = cls(className, {
  326. [`${cssClasses.DIALOG}-displayNone`]: keepDOM && this.state.hidden && !visible,
  327. });
  328. const contentClassName = motion ? cls({
  329. [`${cssClasses.DIALOG}-content-animate-hide`]: !visible,
  330. [`${cssClasses.DIALOG}-content-animate-show`]: visible
  331. }) : null;
  332. const maskClassName = motion ? cls({
  333. [`${cssClasses.DIALOG}-mask-animate-hide`]: !visible,
  334. [`${cssClasses.DIALOG}-mask-animate-show`]: visible
  335. }) : null;
  336. return (
  337. <Portal style={wrapperStyle} getPopupContainer={getPopupContainer}>
  338. <ModalContent
  339. {...restProps}
  340. isFullScreen={this.state.isFullScreen}
  341. contentClassName={contentClassName}
  342. maskClassName={maskClassName}
  343. className={classList}
  344. getPopupContainer={getPopupContainer}
  345. maskStyle={maskStyle}
  346. style={style}
  347. ref={this.modalRef}
  348. onAnimationEnd={() => {
  349. this.updateHiddenState();
  350. }}
  351. footer={renderFooter}
  352. onClose={this.handleCancel}
  353. />
  354. </Portal>
  355. );
  356. };
  357. render() {
  358. const {
  359. visible,
  360. keepDOM,
  361. lazyRender,
  362. } = this.props;
  363. this._active = this._active || visible;
  364. const shouldRender = ((visible || keepDOM) && (!lazyRender || this._active)) || !this.state.hidden;
  365. if (shouldRender) {
  366. return this.renderDialog();
  367. }
  368. return null;
  369. }
  370. }
  371. export default Modal;