All files / client/src/components FirstLogin.tsx

93.75% Statements 30/32
100% Branches 11/11
85.71% Functions 6/7
93.1% Lines 27/29

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 71 72 73                  356x 356x   356x 320x   320x 320x 233x     87x     356x 768x 1932x 1932x 1932x 768x   768x   768x 436x 116x     320x 320x   320x   233x 233x   87x       768x 516x                                     1x      
import { ReactElement, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { z } from "zod";
import { useAppSelector } from "client/utils/hooks";
import { Button, ButtonStyle } from "./Button";
import { HighlightStyle, RaisedCard } from "client/components/RaisedCard";
import { browserStoragePrefix } from "shared/constants/browserStorage";
 
const firstLoginValue = "firstLogin";
const FirstLoginValueSchema = z.literal(firstLoginValue);
 
const getFirstLoginState = (key: string): typeof firstLoginValue | null => {
  const serializedValue = localStorage.getItem(key);
 
  const result = FirstLoginValueSchema.safeParse(serializedValue);
  if (!result.success) {
    return null;
  }
 
  return result.data;
};
 
export const FirstLogin = (): ReactElement | null => {
  const { t } = useTranslation();
  const serial = useAppSelector((state) => state.login.serial);
  const username = useAppSelector((state) => state.login.username);
  const kompassiId = useAppSelector((state) => state.login.kompassiId);
  const isLocalLogin = !kompassiId;
 
  const [isFirstLogin, setIsFirstLogin] = useState<boolean>(false);
 
  useEffect(() => {
    if (!username) {
      return;
    }
 
    const firstLoginKey = `${browserStoragePrefix}-firstLogin-${username}`;
    const firstLogin = getFirstLoginState(firstLoginKey);
 
    if (firstLogin === null) {
      // eslint-disable-next-line react-hooks/set-state-in-effect
      setIsFirstLogin(true);
      localStorage.setItem(firstLoginKey, firstLoginValue);
    } else {
      setIsFirstLogin(false);
    }
  }, [username]);
 
  if (!isFirstLogin || !serial || !isLocalLogin) {
    return null;
  }
 
  return (
    <StyledCard isHighlighted={true} highlightStyle={HighlightStyle.WARN}>
      <p>
        {t("firstLogin.serial")} <b>{serial}</b>
      </p>
      <p>{t("firstLogin.info")}</p>
      <Button
        onClick={() => setIsFirstLogin(false)}
        buttonStyle={ButtonStyle.PRIMARY}
      >
        {t("button.close")}
      </Button>
    </StyledCard>
  );
};
 
const StyledCard = styled(RaisedCard)`
  margin: 0 8px 0 8px;
`;