index.tsx 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. // eslint-disable-next-line max-len
  26. function getConfirmFunc(withFunc: (typeof withConfirm | typeof withInfo | typeof withSuccess | typeof withError | typeof withWarning)) {
  27. return function hookConfirm(config: ModalReactProps) {
  28. uuid += 1;
  29. const modalRef = React.createRef<HookModalRef>();
  30. // eslint-disable-next-line prefer-const
  31. let closeFunc: () => void;
  32. const modal = (
  33. <HookModal
  34. key={`semi-modal-${uuid}`}
  35. config={withFunc(config)}
  36. ref={modalRef}
  37. afterClose={() => {
  38. closeFunc();
  39. }}
  40. />
  41. );
  42. closeFunc = patchElement(modal);
  43. return {
  44. destroy: () => {
  45. if (modalRef.current) {
  46. modalRef.current.destroy();
  47. }
  48. },
  49. update: (newConfig: ConfirmProps) => {
  50. if (modalRef.current) {
  51. modalRef.current.update(newConfig);
  52. }
  53. },
  54. };
  55. };
  56. }
  57. return [
  58. {
  59. info: getConfirmFunc(withInfo),
  60. success: getConfirmFunc(withSuccess),
  61. error: getConfirmFunc(withError),
  62. warning: getConfirmFunc(withWarning),
  63. confirm: getConfirmFunc(withConfirm),
  64. },
  65. <>{elements}</>,
  66. ];
  67. }