confirm.tsx 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { destroyFns, ModalReactProps } from './Modal';
  4. import ConfirmModal from './ConfirmModal';
  5. import '@douyinfe/semi-foundation/modal/modal.scss';
  6. import { get } from 'lodash';
  7. import { IconAlertCircle, IconAlertTriangle, IconHelpCircle, IconInfoCircle, IconTickCircle } from '@douyinfe/semi-icons';
  8. import { Motion } from '../_base/base';
  9. export interface ConfirmProps extends ModalReactProps {
  10. type: 'success' | 'info' | 'warning' | 'error' | 'confirm';
  11. }
  12. export default function confirm<T>(props: ConfirmProps) {
  13. // create a dom in adapter?
  14. const div = document.createElement('div');
  15. document.body.appendChild(div);
  16. let currentConfig = { ...props };
  17. const destroy = () => {
  18. const unmountResult = ReactDOM.unmountComponentAtNode(div);
  19. if (unmountResult && div.parentNode) {
  20. div.parentNode.removeChild(div);
  21. }
  22. for (let i = 0; i < destroyFns.length; i++) {
  23. const fn = destroyFns[i];
  24. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  25. if (fn === close) {
  26. destroyFns.splice(i, 1);
  27. break;
  28. }
  29. }
  30. };
  31. function render(renderProps: ConfirmProps) {
  32. ReactDOM.render(<ConfirmModal {...renderProps} motion={props.motion}/>, div);
  33. }
  34. function close() {
  35. currentConfig = {
  36. ...currentConfig,
  37. visible: false,
  38. };
  39. render(currentConfig);
  40. }
  41. function update(newConfig: T extends { type: Exclude<ConfirmProps['type'], 'confirm'> } ? ModalReactProps : ConfirmProps) {
  42. currentConfig = {
  43. ...currentConfig,
  44. ...newConfig,
  45. };
  46. render(currentConfig);
  47. }
  48. render(currentConfig);
  49. destroyFns.push(close);
  50. return {
  51. destroy: close,
  52. update,
  53. };
  54. }
  55. export function withInfo(props: ModalReactProps) {
  56. return {
  57. type: 'info' as const,
  58. icon: <IconInfoCircle/>,
  59. ...props
  60. };
  61. }
  62. export function withSuccess(props: ModalReactProps) {
  63. return {
  64. type: 'success' as const,
  65. icon: <IconTickCircle/>,
  66. ...props
  67. };
  68. }
  69. export function withWarning(props: ModalReactProps) {
  70. return {
  71. type: 'warning' as const,
  72. icon: <IconAlertTriangle/>,
  73. ...props
  74. };
  75. }
  76. export function withError(props: ModalReactProps) {
  77. return {
  78. type: 'error' as const,
  79. icon: <IconAlertCircle/>,
  80. ...props
  81. };
  82. }
  83. export function withConfirm(props: ModalReactProps) {
  84. return {
  85. type: 'confirm' as const,
  86. icon: <IconHelpCircle/>,
  87. ...props
  88. };
  89. }