confirm.tsx 2.6 KB

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