All files / src/components/common/Modal/ModalFactory ModalFactory.tsx

93.33% Statements 14/15
85.71% Branches 6/7
100% Functions 2/2
93.33% Lines 14/15

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                                              37x 186x         221x 221x       221x       221x   118x 118x   76x 76x   27x 27x       221x             37x              
import { isFunction } from "lodash";
import DialogVariant, { DialogVariantProps } from "./variants/ModalVariant";
import SidePanelVariant, {
  SidePanelVariantProps,
} from "./variants/SidePanelVariant";
import { useCustomTheme } from "@theme/hooks/useCustomTheme";
import PopupVariant, { PopupVariantProps } from "./variants/PopupVariant";
 
export type TModalVariants = "dialog" | "popup" | "sidepanel";
 
type ModalPropsByVariant = {
  dialog: DialogVariantProps;
  popup: PopupVariantProps;
  sidepanel: SidePanelVariantProps;
};
 
interface IModalFactory<T extends TModalVariants> {
  renderMobile?: boolean | ((isMobileView: boolean) => boolean);
  variant: T;
  modalProps: Omit<ModalPropsByVariant[T], "children">;
  children: React.ReactNode;
}
 
const ModalFactory = <T extends TModalVariants>({
  renderMobile = (isMobile) => isMobile,
  variant,
  modalProps,
  children,
}: IModalFactory<T>) => {
  const { isMobileView } = useCustomTheme();
  const showMobileDrawer = isFunction(renderMobile)
    ? renderMobile(isMobileView)
    : renderMobile;
 
  const ModalComponent = Modal[variant];
 
  let refinedModalProps: any;
 
  switch (variant) {
    case "dialog":
      refinedModalProps = modalProps as DialogVariantProps;
      break;
    case "popup":
      refinedModalProps = modalProps as PopupVariantProps;
      break;
    case "sidepanel":
      refinedModalProps = modalProps as SidePanelVariantProps;
      break;
    default:
      throw new Error("Invalid variant");
  }
  return (
    <ModalComponent {...refinedModalProps} showMobileView={showMobileDrawer}>
      {children}
    </ModalComponent>
  );
};
 
const Modal = {
  dialog: DialogVariant,
  popup: PopupVariant,
  sidepanel: SidePanelVariant,
};
 
export default ModalFactory;