Modal.tsx 13 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 { isUndefined } from 'lodash-es';
  12. import '@douyinfe/semi-foundation/modal/modal.scss';
  13. import { noop } from 'lodash-es';
  14. import ContentTransition from './ModalTransition';
  15. import BaseComponent from '../_base/baseComponent';
  16. import confirm, {
  17. withConfirm,
  18. withError,
  19. withInfo,
  20. withSuccess,
  21. withWarning
  22. } from '../modal/confirm';
  23. import { Locale } from '../locale/interface';
  24. import useModal from '../modal/useModal';
  25. import { ButtonProps } from '../button/Button';
  26. export const destroyFns: any[] = [];
  27. export type ConfirmType = 'leftTop' | 'leftBottom' | 'rightTop' | 'rightBottom';
  28. export type Directions = 'ltr' | 'rtl';
  29. export interface ModalReactProps extends ModalProps {
  30. cancelButtonProps?: ButtonProps;
  31. okButtonProps?: ButtonProps;
  32. bodyStyle?: CSSProperties;
  33. maskStyle?: CSSProperties;
  34. style?: CSSProperties;
  35. icon?: ReactNode;
  36. closeIcon?: ReactNode;
  37. title?: ReactNode;
  38. content?: ReactNode;
  39. footer?: ReactNode;
  40. header?: ReactNode;
  41. onCancel?: (e: React.MouseEvent) => void | Promise<any>;
  42. onOk?: (e: React.MouseEvent) => void | Promise<any>;
  43. }
  44. export {
  45. ModalState
  46. };
  47. class Modal extends BaseComponent<ModalReactProps, ModalState> {
  48. static propTypes = {
  49. mask: PropTypes.bool,
  50. closable: PropTypes.bool,
  51. centered: PropTypes.bool,
  52. visible: PropTypes.bool,
  53. width: PropTypes.number,
  54. height: PropTypes.number,
  55. confirmLoading: PropTypes.bool,
  56. cancelLoading: PropTypes.bool,
  57. okText: PropTypes.string,
  58. okType: PropTypes.string,
  59. cancelText: PropTypes.string,
  60. maskClosable: PropTypes.bool,
  61. onCancel: PropTypes.func,
  62. onOk: PropTypes.func,
  63. afterClose: PropTypes.func,
  64. okButtonProps: PropTypes.object,
  65. cancelButtonProps: PropTypes.object,
  66. style: PropTypes.object,
  67. className: PropTypes.string,
  68. maskStyle: PropTypes.object,
  69. bodyStyle: PropTypes.object,
  70. zIndex: PropTypes.number,
  71. title: PropTypes.node,
  72. icon: PropTypes.node,
  73. header: PropTypes.node,
  74. footer: PropTypes.node,
  75. hasCancel: PropTypes.bool,
  76. motion: PropTypes.oneOfType([PropTypes.bool, PropTypes.func, PropTypes.object]),
  77. children: PropTypes.node,
  78. getPopupContainer: PropTypes.func,
  79. getContainerContext: PropTypes.func,
  80. maskFixed: PropTypes.bool,
  81. closeIcon: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  82. closeOnEsc: PropTypes.bool,
  83. size: PropTypes.oneOf(strings.SIZE),
  84. keepDOM: PropTypes.bool,
  85. lazyRender: PropTypes.bool,
  86. direction: PropTypes.oneOf(strings.directions),
  87. fullScreen: PropTypes.bool,
  88. };
  89. static defaultProps = {
  90. zIndex: 1000,
  91. motion: true,
  92. mask: true,
  93. centered: false,
  94. closable: true,
  95. visible: false,
  96. confirmLoading: false,
  97. cancelLoading: false,
  98. okType: 'primary',
  99. maskClosable: true,
  100. hasCancel: true,
  101. onCancel: noop,
  102. onOk: noop,
  103. afterClose: noop,
  104. maskFixed: false,
  105. closeOnEsc: false,
  106. size: 'small',
  107. keepDOM: false,
  108. lazyRender: true,
  109. fullScreen: false,
  110. };
  111. static useModal = useModal;
  112. foundation: ModalFoundation;
  113. private readonly modalRef: LegacyRef<ModalContent>;
  114. private bodyOverflow: string;
  115. private scrollBarWidth: number;
  116. private originBodyWith: string;
  117. private _active: boolean;
  118. constructor(props: ModalReactProps) {
  119. super(props);
  120. this.state = {
  121. hidden: !props.visible,
  122. isFullScreen: props.fullScreen,
  123. };
  124. this.foundation = new ModalFoundation(this.adapter);
  125. this.modalRef = React.createRef();
  126. this.bodyOverflow = '';
  127. this.scrollBarWidth = 0;
  128. this.originBodyWith = '100%';
  129. }
  130. get adapter(): ModalAdapter {
  131. return {
  132. ...super.adapter,
  133. getProps: () => this.props,
  134. disabledBodyScroll: () => {
  135. const { getPopupContainer } = this.props;
  136. this.bodyOverflow = document.body.style.overflow || '';
  137. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  138. document.body.style.overflow = 'hidden';
  139. document.body.style.width = `calc(${this.originBodyWith || '100%'} - ${this.scrollBarWidth}px)`;
  140. }
  141. },
  142. enabledBodyScroll: () => {
  143. const { getPopupContainer } = this.props;
  144. if (!getPopupContainer && this.bodyOverflow !== 'hidden') {
  145. document.body.style.overflow = this.bodyOverflow;
  146. document.body.style.width = this.originBodyWith;
  147. }
  148. },
  149. notifyCancel: (e: React.MouseEvent) => {
  150. this.props.onCancel(e);
  151. },
  152. notifyOk: (e: React.MouseEvent) => {
  153. this.props.onOk(e);
  154. },
  155. notifyClose: () => {
  156. this.props.afterClose();
  157. },
  158. toggleHidden: (hidden: boolean) => {
  159. if (hidden !== this.state.hidden) {
  160. this.setState({ hidden });
  161. }
  162. },
  163. notifyFullScreen: (isFullScreen: boolean) => {
  164. if (isFullScreen !== this.state.isFullScreen) {
  165. this.setState({ isFullScreen });
  166. }
  167. },
  168. };
  169. }
  170. static getDerivedStateFromProps(props: ModalReactProps, prevState: ModalState) {
  171. const newState: Partial<ModalState> = {};
  172. if (props.visible && prevState.hidden) {
  173. newState.hidden = false;
  174. }
  175. if (props.fullScreen !== prevState.isFullScreen) {
  176. newState.isFullScreen = props.fullScreen;
  177. }
  178. // if not using animation, need to update hidden state from props
  179. if (!props.visible && !props.motion && !prevState.hidden) {
  180. newState.hidden = true;
  181. }
  182. return newState;
  183. }
  184. static getScrollbarWidth() {
  185. if (Object.prototype.toString.call(globalThis) === '[object Window]') {
  186. return window.innerWidth - document.documentElement.clientWidth;
  187. }
  188. return 0;
  189. }
  190. static info = function (props: ModalReactProps) {
  191. return confirm(withInfo(props));
  192. };
  193. static success = function (props: ModalReactProps) {
  194. return confirm(withSuccess(props));
  195. };
  196. static error = function (props: ModalReactProps) {
  197. return confirm(withError(props));
  198. };
  199. static warning = function (props: ModalReactProps) {
  200. return confirm(withWarning(props));
  201. };
  202. static confirm = function (props: ModalReactProps) {
  203. return confirm(withConfirm(props));
  204. };
  205. static destroyAll = function destroyAllFn() {
  206. while (destroyFns.length) {
  207. const close = destroyFns.pop();
  208. if (close) {
  209. close();
  210. }
  211. }
  212. };
  213. componentDidMount() {
  214. this.scrollBarWidth = Modal.getScrollbarWidth();
  215. this.originBodyWith = document.body.style.width;
  216. if (this.props.visible) {
  217. this.foundation.beforeShow();
  218. this._active = this._active || this.props.visible;
  219. }
  220. }
  221. componentDidUpdate(prevProps: ModalReactProps, prevState: ModalState, snapshot: any) {
  222. // hide => show
  223. if (!prevProps.visible && this.props.visible) {
  224. this.foundation.beforeShow();
  225. }
  226. // show => hide
  227. if (prevProps.visible && !this.props.visible) {
  228. this.foundation.afterHide();
  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. renderFooter = (): ReactNode => {
  243. const {
  244. okText,
  245. okType,
  246. cancelText,
  247. confirmLoading,
  248. cancelLoading,
  249. hasCancel,
  250. } = this.props;
  251. const getCancelButton = (locale: Locale['Modal']) => {
  252. if (!hasCancel) {
  253. return null;
  254. } else {
  255. return (
  256. <Button
  257. onClick={this.handleCancel}
  258. loading={cancelLoading}
  259. type="tertiary"
  260. {...this.props.cancelButtonProps}
  261. >
  262. {cancelText || locale.cancel}
  263. </Button>
  264. );
  265. }
  266. };
  267. return (
  268. <LocaleConsumer componentName="Modal">
  269. {(locale: Locale['Modal'], localeCode: Locale['code']) => (
  270. <div>
  271. {getCancelButton(locale)}
  272. <Button
  273. type={okType}
  274. theme="solid"
  275. loading={confirmLoading}
  276. onClick={this.handleOk}
  277. {...this.props.okButtonProps}
  278. >
  279. {okText || locale.confirm}
  280. </Button>
  281. </div>
  282. )}
  283. </LocaleConsumer>
  284. );
  285. };
  286. getDialog = () => {
  287. const {
  288. footer,
  289. ...restProps
  290. } = this.props;
  291. const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  292. return <ModalContent {...restProps} footer={renderFooter} onClose={this.handleCancel} />;
  293. };
  294. renderDialogWithTransition = ({
  295. opacity,
  296. scale,
  297. }: {
  298. opacity?: CSSProperties['opacity'];
  299. scale?: number;
  300. } = {}) => {
  301. let {
  302. footer,
  303. className,
  304. motion,
  305. maskStyle: maskStyleFromProps,
  306. keepDOM,
  307. style: styleFromProps,
  308. zIndex,
  309. getPopupContainer,
  310. ...restProps
  311. } = this.props;
  312. let maskStyle = maskStyleFromProps;
  313. let style = styleFromProps;
  314. const renderFooter = 'footer' in this.props ? footer : this.renderFooter();
  315. if (this.props.centered) {
  316. style = {
  317. transform: 'translateY(-50%)',
  318. top: '50%', ...style,
  319. };
  320. }
  321. if (!isUndefined(opacity)) {
  322. maskStyle = { opacity, ...maskStyle };
  323. style = { opacity, ...style };
  324. }
  325. if (!isUndefined(scale)) {
  326. style = { transform: `scale(${scale})`, ...style };
  327. if (this.props.centered) {
  328. style = {
  329. ...style,
  330. transform: `scale(${scale}) translateY(-${50 / scale}%)`,
  331. };
  332. }
  333. }
  334. let wrapperStyle: {
  335. zIndex?: CSSProperties['zIndex'];
  336. position?: CSSProperties['position'];
  337. } = {
  338. zIndex,
  339. };
  340. if (getPopupContainer) {
  341. wrapperStyle = {
  342. zIndex,
  343. position: 'static',
  344. };
  345. }
  346. const classList = cls(className, {
  347. [`${cssClasses.DIALOG}-hidden`]: keepDOM && this.state.hidden,
  348. });
  349. return (
  350. <Portal style={wrapperStyle} getPopupContainer={getPopupContainer}>
  351. <ModalContent
  352. {...restProps}
  353. isFullScreen={this.state.isFullScreen}
  354. className={classList}
  355. getPopupContainer={getPopupContainer}
  356. maskStyle={maskStyle}
  357. style={style}
  358. ref={this.modalRef}
  359. footer={renderFooter}
  360. onClose={this.handleCancel}
  361. />
  362. </Portal>
  363. );
  364. };
  365. render() {
  366. const {
  367. visible,
  368. keepDOM,
  369. lazyRender,
  370. } = this.props;
  371. this._active = this._active || visible;
  372. const shouldRender = (visible || keepDOM) && (!lazyRender || this._active);
  373. const mergedMotion = this.foundation.getMergedMotion();
  374. if (mergedMotion) {
  375. return (
  376. <ContentTransition motion={mergedMotion} controlled={keepDOM} visible={visible}>
  377. {shouldRender ? this.renderDialogWithTransition : null}
  378. </ContentTransition>
  379. );
  380. }
  381. if (shouldRender) {
  382. return this.renderDialogWithTransition();
  383. }
  384. return null;
  385. }
  386. }
  387. export default Modal;