All files / app/features/donations DonationBanner.tsx

100% Statements 31/31
100% Branches 8/8
100% Functions 5/5
100% Lines 29/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 74 75 76 77 78 79 801x 1x 1x 1x 1x 1x 1x   1x 1x   1x   9x                             15x 33x 33x   33x     33x     33x   33x   19x     19x         9x   10x       33x 4x 4x     33x 1x 1x     33x                          
import { Button, styled } from "@mui/material";
import { useTranslation } from "i18n";
import { GLOBAL } from "i18n/namespaces";
import { useRouter } from "next/router";
import { usePersistedState } from "platform/usePersistedState";
import { useCallback, useEffect, useState } from "react";
import { donationsRoute } from "routes";
 
import useAccountInfo from "../auth/useAccountInfo";
import DonationDriveBlock from "./DonationDriveBlock";
 
const TIME_BETWEEN_NAGS_MS = 24 * 60 * 60 * 1000; // 24 hours
 
const StyledButton = styled(Button)(({ theme }) => ({
  backgroundColor: "var(--mui-palette-secondary-main)",
  flexShrink: 0,
  alignSelf: "center",
  paddingLeft: theme.spacing(3),
  paddingRight: theme.spacing(3),
  "&:hover": {
    backgroundColor: "var(--mui-palette-secondary-dark)",
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
    alignSelf: "stretch",
  },
}));
 
export function DonationBanner() {
  const { t } = useTranslation(GLOBAL);
  const router = useRouter();
 
  const [lastDismissedEpoch, setLastDismissedEpoch] = usePersistedState<
    number | null
  >("donation_banner.dismissed", null);
  const [bannerVisible, setBannerVisible] = useState<boolean>(false);
 
  const { data: accountInfo, isLoading: isAccountInfoLoading } =
    useAccountInfo();
 
  useEffect(() => {
    const notDismissedRecently =
      !lastDismissedEpoch ||
      new Date().getTime() - lastDismissedEpoch > TIME_BETWEEN_NAGS_MS;
 
    if (
      !isAccountInfoLoading &&
      accountInfo?.shouldShowDonationBanner &&
      notDismissedRecently
    ) {
      setBannerVisible(true);
    } else {
      setBannerVisible(false);
    }
  }, [isAccountInfoLoading, accountInfo, lastDismissedEpoch]);
 
  const handleClose = useCallback(() => {
    setLastDismissedEpoch(new Date().getTime());
    setBannerVisible(false);
  }, [setLastDismissedEpoch]);
 
  const handleDonateClick = useCallback(() => {
    router.push(`${donationsRoute}?utm_source=donation_banner`);
    setBannerVisible(false);
  }, [router]);
 
  if (!bannerVisible) return null;
 
  return (
    <DonationDriveBlock
      onClose={handleClose}
      action={
        <StyledButton variant="contained" onClick={handleDonateClick}>
          {t("donation_banner.button")}
        </StyledButton>
      }
    />
  );
}