All files / src/componentsV2/SideMenu/hooks useDrawerCollapse.ts

87.87% Statements 29/33
62.5% Branches 10/16
87.5% Functions 7/8
87.5% Lines 28/32

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                        15x   15x 80x 80x 80x 80x 80x     80x   80x 4x     80x 2x 2x 2x 2x       80x 1x 1x     80x 1x 1x     80x 72x 52x 2x 2x     50x           80x    
import { useEffect, useState } from "react";
import { breakpoints } from "@theme/v2/breakpoints";
import {
  DRAWER_STATE_KEY,
  PRE_MASQUERADE_DRAWER_STATE,
} from "@constants/constants";
import { selectMasqueradeMode } from "@redux/slices/app";
import { useAppSelector } from "@redux/hooks";
import { delay, isNull } from "lodash";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { safeParse } from "@utils/index";
 
const SCREEN_THRESHOLD = breakpoints.values?.v2_md || 1339;
 
export const useDrawerCollapse = () => {
  const { isMobileView } = useCustomThemeV2();
  const { name: isMasquerade } = useAppSelector(selectMasqueradeMode);
  const isDrawerOpened = localStorage.getItem(DRAWER_STATE_KEY);
  const preMasqueradeState = localStorage.getItem(PRE_MASQUERADE_DRAWER_STATE);
  const defaultState = isDrawerOpened
    ? (safeParse(isDrawerOpened) ?? window.innerWidth > SCREEN_THRESHOLD)
    : window.innerWidth > SCREEN_THRESHOLD;
  const [open, setOpen] = useState<boolean>(defaultState);
 
  const trackState = (open: boolean) => {
    localStorage.setItem(DRAWER_STATE_KEY, JSON.stringify(open));
  };
 
  const toggleDrawer = () => {
    setOpen((open) => {
      const newState = !open;
      trackState(newState);
      return newState;
    });
  };
 
  const handleDrawerClose = () => {
    trackState(false);
    setOpen(false);
  };
 
  const handleDrawerOpen = () => {
    setOpen(true);
    trackState(true);
  };
 
  useEffect(() => {
    if (isMobileView) return;
    if (isMasquerade) {
      localStorage.setItem(PRE_MASQUERADE_DRAWER_STATE, JSON.stringify(open));
      delay(() => {
        handleDrawerOpen();
      }, 0);
    } else Iif (preMasqueradeState && !isNull(safeParse(preMasqueradeState))) {
      const oldState = safeParse(preMasqueradeState) as boolean | null;
      oldState ? handleDrawerOpen() : handleDrawerClose();
      localStorage.setItem(PRE_MASQUERADE_DRAWER_STATE, JSON.stringify(null));
    }
  }, [isMasquerade, preMasqueradeState, isMobileView]);
  return { open, toggleDrawer, handleDrawerClose, handleDrawerOpen };
};