All files / src/hooks/common/masquerade useLocalMasquerade.tsx

8.1% Statements 3/37
0% Branches 0/21
0% Functions 0/7
9.09% Lines 3/33

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                      117x           117x             117x                                                                                      
import { setMasqueradeMode, updatePermissions } from "@redux/slices/app";
import { MasqueradeModeType } from "@redux/slices/app/types";
import React from "react";
import { useAppDispatch } from "@redux/hooks";
import NiceModal from "@ebay/nice-modal-react";
import { MERCHANT_PREVIEW_PANEL_MODAL } from "modals/modal_names";
import { useNavigate } from "react-router-dom";
import { checkPortals } from "@utils/routing";
import { useQueryClient } from "react-query";
import { safeParse } from "@utils/index";
 
export const getMasqueradeData = () => {
  const item = localStorage.getItem("masquerade-mode");
  if (!item) return undefined;
  return safeParse(item) as MasqueradeModeType | undefined;
};
 
const isSameData = (event: StorageEvent) => {
  const oldValue = event.oldValue ? safeParse(event.oldValue) : null;
  const newValue = event.newValue ? safeParse(event.newValue) : null;
 
  return oldValue?.id === newValue?.id;
};
 
const useLocalMasquerade = () => {
  const [data, setData] = React.useState<MasqueradeModeType | undefined>(
    undefined,
  );
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { isPrivacyPolicy, isTOS, isSLA } = checkPortals();
 
  const resetMasqueradeModeUI = (data: MasqueradeModeType) => {
    NiceModal.remove(MERCHANT_PREVIEW_PANEL_MODAL);
    queryClient.clear();
    dispatch(updatePermissions({ reset: true }));
    if (data?.id) {
      dispatch(setMasqueradeMode({ ...data, saveInReduxOnly: true }));
    }
    navigate("/");
  };
 
  const isPublicRoute = isPrivacyPolicy || isTOS || isSLA;
 
  React.useEffect(() => {
    function handleStorageChange(e: StorageEvent) {
      if (isPublicRoute || isSameData(e)) {
        return;
      }
 
      if (e?.key && e.key !== "masquerade-mode") return;
 
      const masqueradeData = getMasqueradeData();
      if (masqueradeData === undefined) return;
      resetMasqueradeModeUI(masqueradeData);
      setData(masqueradeData);
    }
 
    window.addEventListener("storage", handleStorageChange);
    return () => window.removeEventListener("storage", handleStorageChange);
  }, []);
 
  return data;
};
 
export default useLocalMasquerade;