Modal.tsx 13 KB

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