index.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import React, { ReactNode } from 'react';
  2. import HookModal from './HookModal';
  3. import { withConfirm, withInfo, withSuccess, withError, withWarning, ConfirmProps } from '../confirm';
  4. import { ModalReactProps } from '../Modal';
  5. let uuid = 0;
  6. function usePatchElement(): ([ReactNode[], (element: ReactNode) => () => void]) {
  7. const [elements, setElements] = React.useState<ReactNode[]>([]);
  8. function patchElement(element: ReactNode) {
  9. setElements(originElements => [...originElements, element]);
  10. return () => {
  11. setElements(originElements => originElements.filter(ele => ele !== element));
  12. };
  13. }
  14. return [elements, patchElement];
  15. }
  16. export default function useModal() {
  17. const [elements, patchElement] = usePatchElement();
  18. // eslint-disable-next-line max-len
  19. function getConfirmFunc(withFunc: (typeof withConfirm | typeof withInfo | typeof withSuccess | typeof withError | typeof withWarning)) {
  20. return function hookConfirm(config: ModalReactProps) {
  21. uuid += 1;
  22. const modalRef = React.createRef<{
  23. destroy: () => void;
  24. update: (newConfig: ConfirmProps) => void;
  25. }>();
  26. // eslint-disable-next-line prefer-const
  27. let closeFunc: () => void;
  28. const modal = (
  29. <HookModal
  30. key={`semi-modal-${uuid}`}
  31. config={withFunc(config)}
  32. ref={modalRef}
  33. afterClose={() => {
  34. closeFunc();
  35. }}
  36. />
  37. );
  38. closeFunc = patchElement(modal);
  39. return {
  40. destroy: () => {
  41. if (modalRef.current) {
  42. modalRef.current.destroy();
  43. }
  44. },
  45. update: (newConfig: ConfirmProps) => {
  46. if (modalRef.current) {
  47. modalRef.current.update(newConfig);
  48. }
  49. },
  50. };
  51. };
  52. }
  53. return [
  54. {
  55. info: getConfirmFunc(withInfo),
  56. success: getConfirmFunc(withSuccess),
  57. error: getConfirmFunc(withError),
  58. warning: getConfirmFunc(withWarning),
  59. confirm: getConfirmFunc(withConfirm),
  60. },
  61. <>{elements}</>,
  62. ];
  63. }