1
0

index.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. type UseModalReturnHooksType = (config: ModalReactProps) => { destroy: () => void; update: (newConfig: ConfirmProps) => void };
  17. export default function useModal(): [{
  18. info: UseModalReturnHooksType;
  19. success: UseModalReturnHooksType;
  20. error: UseModalReturnHooksType;
  21. warning: UseModalReturnHooksType;
  22. confirm: UseModalReturnHooksType
  23. }, ReactNode] {
  24. const [elements, patchElement] = usePatchElement();
  25. function getConfirmFunc(withFunc: (typeof withConfirm | typeof withInfo | typeof withSuccess | typeof withError | typeof withWarning)) {
  26. return function hookConfirm(config: ModalReactProps) {
  27. uuid += 1;
  28. const modalRef = React.createRef<HookModalRef>();
  29. let closeFunc: () => void;
  30. const modal = (
  31. <HookModal
  32. key={`semi-modal-${uuid}`}
  33. config={withFunc(config)}
  34. ref={modalRef}
  35. afterClose={() => {
  36. closeFunc();
  37. }}
  38. />
  39. );
  40. closeFunc = patchElement(modal);
  41. return {
  42. destroy: () => {
  43. if (modalRef.current) {
  44. modalRef.current.destroy();
  45. }
  46. },
  47. update: (newConfig: ConfirmProps) => {
  48. if (modalRef.current) {
  49. modalRef.current.update(newConfig);
  50. }
  51. },
  52. };
  53. };
  54. }
  55. return [
  56. {
  57. info: getConfirmFunc(withInfo),
  58. success: getConfirmFunc(withSuccess),
  59. error: getConfirmFunc(withError),
  60. warning: getConfirmFunc(withWarning),
  61. confirm: getConfirmFunc(withConfirm),
  62. },
  63. <>{elements}</>,
  64. ];
  65. }