All files / components/Modal ModalProvider.tsx

97.14% Statements 68/70
88.88% Branches 8/9
100% Functions 5/5
97.14% Lines 68/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 4x 4x     4x 4x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 10x 10x 10x 10x 10x 5x 2x 2x 5x 1x 1x 5x 1x 1x 5x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x  
import { ReactNode, useCallback, useMemo, useState } from 'react';
 
import Modal from './Modal';
import { ModalTypes } from './ModalConstants';
import ModalContext from './ModalContext';
import {
  ModalCloseType,
  ModalContextProps,
  ModalProps,
  ModalType,
  ShowModalProps,
} from './ModalProps';
 
const defaultModalProps = {
  children: <></>,
  title: '',
  visible: false,
};
 
function ModalProvider({ children }: { children: ReactNode }): JSX.Element {
  const [modalProps, setModalProps] = useState<ModalProps>(defaultModalProps);
 
  const handleModalOpen = useCallback(
    (props: ShowModalProps, type: ModalType) => {
      setModalProps(state => {
        if (state.visible) {
          return state;
        }
 
        const handleClose = (type: ModalCloseType): void => {
          setModalProps(defaultModalProps);
          props.onClose?.(type);
        };
 
        return {
          ...props,
          children: props.content,
          onClose: handleClose,
          type,
          visible: !state.visible,
        };
      });
    },
    []
  );
 
  const value = useMemo<ModalContextProps>(
    () => ({
      showModalAccept: (props: ShowModalProps): void => {
        handleModalOpen(props, ModalTypes.ACCEPT);
      },
      showModalConfirm: (props): void => {
        handleModalOpen(props, ModalTypes.CONFIRM);
      },
      showModalInfo: (props): void => {
        handleModalOpen(props, ModalTypes.INFO);
      },
    }),
    [handleModalOpen]
  );
 
  return (
    <ModalContext.Provider value={value}>
      {children}
      <Modal {...modalProps} />
    </ModalContext.Provider>
  );
}
 
export default ModalProvider;