index.tsx 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import React, { ReactNode } from 'react';
  2. import HookModal, { HookModalRef } from './HookModal';
  3. import { ConfirmProps, withConfirm, withError, withInfo, withSuccess, withWarning } 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<HookModalRef>();
  23. // eslint-disable-next-line prefer-const
  24. let closeFunc: () => void;
  25. const modal = (
  26. <HookModal
  27. key={`semi-modal-${uuid}`}
  28. config={withFunc(config)}
  29. ref={modalRef}
  30. afterClose={() => {
  31. closeFunc();
  32. }}
  33. />
  34. );
  35. closeFunc = patchElement(modal);
  36. return {
  37. destroy: () => {
  38. if (modalRef.current) {
  39. modalRef.current.destroy();
  40. }
  41. },
  42. update: (newConfig: ConfirmProps) => {
  43. if (modalRef.current) {
  44. modalRef.current.update(newConfig);
  45. }
  46. },
  47. };
  48. };
  49. }
  50. return [
  51. {
  52. info: getConfirmFunc(withInfo),
  53. success: getConfirmFunc(withSuccess),
  54. error: getConfirmFunc(withError),
  55. warning: getConfirmFunc(withWarning),
  56. confirm: getConfirmFunc(withConfirm),
  57. },
  58. <>{elements}</>,
  59. ];
  60. }