test

mail@pastecode.io avatar
unknown
plain_text
a month ago
7.0 kB
2
Indexable
Never
import { createContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";

import { isNotEnvironment } from "AccessControl/Permissions";
import { handleOpenMobileMenu } from "Redux/CommonSlice";
import { user } from "Redux/UserSlice";
import { useExplorerParams } from "hooks/useExplorerParams";
import { useScreen } from "hooks/useScreen";
import { useTutorialScenarios } from "hooks/useTutorialScenarios";
import { TipMessage, TipScenario } from "models/tips.types";
import { EPaths } from "routes/Routing";
import {
  FirstLoginContextProps,
  FirstLoginProviderProps,
} from "./FirstLoginProvider.types";
import { tipMessages } from "./tipMessages";
import { initialData, useSavedData } from "./useSavedData";

export const FirstLoginContext = createContext<FirstLoginContextProps>({
  tutorialVisible: false,
  tip: null,
  steps: {
    currentStep: 0,
    totalSteps: 0,
  },
  savedTutorialData: initialData,
  isFinalTip: false,
  shouldTipBeVisible: () => false,
  showNextTip: () => {},
  showPreviousTip: () => {},
  skipAllTips: () => {},
  handleOpenTutorial: () => {},
  handleRemindLater: () => {},
  setRemind: () => {},
  handleInitialLogin: () => {},
  showRemindWindow: () => {},
  handleCloseTip: () => {},
});

const { welcome } = tipMessages;

const getCurrentTip = (
  scenarios: TipScenario[],
  currentTipMessage: TipMessage | null
) => {
  return scenarios.find((tip) => tip.message === currentTipMessage);
};

export const FirstLoginProvider = ({ children }: FirstLoginProviderProps) => {
  const { navigateWithSearchResults } = useExplorerParams();
  const {
    savedTutorialData,
    showRemindWindow,
    setLastTip,
    setRemind,
    setFirstAuth,
    setSavedTutorialData,
    checkIfUserHaveSavedTutorialData,
    getTutorialDataByUserId,
    getParsedData,
    setInitialTutorialData,
    setTutorialDataByUserId,
    getSavedDataOnLoad,
  } = useSavedData();
  console.log("tutorial prov");

  const lastTip = savedTutorialData ? savedTutorialData.lastTip : 0;

  const [tutorialVisible, setTutorialVisible] = useState<boolean>(
    isNotEnvironment() && !!savedTutorialData?.isFirstAuth
  );
  const isMobile = useScreen({ screenSize: "sm" });
  const userInfo = useSelector(user);

  const {
    adminTipScenario,
    clientTipScenario,
    partnerTipScenario,
    menuOptions,
  } = useTutorialScenarios();

  const getTipScenario = (role: "admin" | "partner" | "client") => {
    if (role === "admin") return adminTipScenario;
    if (role === "partner") return partnerTipScenario;
    return clientTipScenario;
  };

  const userRole = userInfo?.user_info?.user_metadata?.entity;
  const userId = userInfo?.user_info?.sub;
  const currentTipScenario = getTipScenario(userRole);
  const totalSteps = currentTipScenario.length - 1;

  const savedTip = currentTipScenario[lastTip];

  const isNotFinalTip = lastTip <= totalSteps;
  const isFinalTip = lastTip === totalSteps;

  const initialTip = isNotFinalTip ? savedTip.message : welcome;
  const isTutorialActive = tutorialVisible ? initialTip : null;
  const [tip, setTip] = useState<TipMessage | null>(isTutorialActive);
  const currentTip = getCurrentTip(currentTipScenario, tip);
  const dispatch = useDispatch();

  const [steps, setSteps] = useState({
    currentStep: isNotFinalTip ? savedTip.id : 0,
    totalSteps: totalSteps,
  });

  const closeTutorialTip = () => {
    setTip(null);
    savedTutorialData?.isFirstAuth && setFirstAuth(false);
    setTutorialVisible(false);
  };

  const skipAllTips = () => {
    closeTutorialTip();
    setLastTip(1);
    setRemind(false);
  };
  const shouldTipBeVisible = (tipName: TipMessage) => tip === tipName;

  const saveLastVisitedTip = (tipNumberToSave: number) => {
    if (!currentTip || currentTip.id === totalSteps) return setLastTip(1);
    setLastTip(tipNumberToSave);
  };

  const saveCurrentTip = () => {
    if (!currentTip) return setLastTip(1);
    setLastTip(currentTip.id);
  };

  const moveToPageWithNextTip = (currentTip: TipMessage) => {
    const isCurrentTipInsideMenu = menuOptions.some(
      (option) => option === currentTip
    );
    if (isMobile) dispatch(handleOpenMobileMenu(isCurrentTipInsideMenu));
    if (isCurrentTipInsideMenu) return;
    navigateWithSearchResults(EPaths.dashboard);
  };

  const handleSetNextMessage = (nextTip: number) => {
    const tipMessage = currentTipScenario[nextTip].message;
    setTip(tipMessage);
    moveToPageWithNextTip(tipMessage);
    setSteps((prev) => ({
      ...prev,
      currentStep: nextTip,
    }));
  };

  const showNextTip = (currentTipMessage: TipMessage | null) => {
    if (!currentTipMessage) return skipAllTips();
    if (!currentTip) return;
    const nextTipId = currentTip.id + 1;
    if (isFinalTip) {
      skipAllTips();
      return;
    }
    handleSetNextMessage(nextTipId);
    saveLastVisitedTip(nextTipId);
  };

  const showPreviousTip = (currentTipMessage: TipMessage | null) => {
    if (!currentTipMessage) return skipAllTips();
    if (!currentTip) return;
    const previousTipId = currentTip.id - 1;
    handleSetNextMessage(previousTipId);
    saveLastVisitedTip(previousTipId);
  };

  const handleCloseTip = () => {
    closeTutorialTip();
    saveCurrentTip();
  };

  const handleRemindLater = () => {
    closeTutorialTip();
    setLastTip(0);
    setRemind(true);
  };

  const handleOpenTutorial = () => {
    const firstTip = currentTip?.id ?? 0;
    const currentTipNumber = isNotFinalTip && savedTip ? savedTip.id : firstTip;
    const currentTipMessage = savedTip ? savedTip.message : welcome;
    setTip(currentTipMessage);
    moveToPageWithNextTip(currentTipMessage);
    setSteps((prev) => ({
      ...prev,
      currentStep: currentTipNumber,
    }));
    setTutorialVisible(true);
  };

  const handleInitialLogin = (userId: string) => {
    const foundData = getTutorialDataByUserId(userId);
    if (!checkIfUserHaveSavedTutorialData(userId) || !foundData) {
      setInitialTutorialData(userId);
      handleOpenTutorial();
      return;
    }
    const parsedData = getParsedData(foundData);
    setSavedTutorialData(parsedData);
    setTutorialDataByUserId(parsedData);
    parsedData.remind && parsedData?.showRemindWindow && handleOpenTutorial();
    showRemindWindow(false);
  };

  useEffect(() => {
    setSteps((prev) => ({
      ...prev,
      totalSteps: totalSteps,
    }));
  }, [totalSteps]);

  useEffect(() => {
    setSavedTutorialData(getSavedDataOnLoad(userId as string));
  }, [setSavedTutorialData, userId, getSavedDataOnLoad]);

  return (
    <FirstLoginContext.Provider
      value={{
        shouldTipBeVisible,
        showNextTip,
        showPreviousTip,
        skipAllTips,
        handleOpenTutorial,
        handleRemindLater,
        handleInitialLogin,
        setRemind,
        showRemindWindow,
        handleCloseTip,
        tip,
        steps,
        tutorialVisible,
        savedTutorialData,
        isFinalTip,
      }}
    >
      {children}
    </FirstLoginContext.Provider>
  );
};
Leave a Comment