All files / src/features/common OTP.tsx

100% Statements 14/14
82.75% Branches 24/29
100% Functions 5/5
100% Lines 14/14

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165                2x     2x 2x 2x 40x                                                   2x                               162x 162x     162x       162x                         1008x                                                                                                                                       2x 326x 162x                                  
import GivePayment from "@assets/icons/GivePayment";
import { Box, Stack, SxProps } from "@mui/material";
import GiveLink from "@shared/Link/GiveLink";
import GiveText from "@shared/Text/GiveText";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { styled, useAppTheme } from "@theme/v2/Provider";
import OTPInput from "react-otp-input";
 
const OTP_GENERIC_ERROR = "Invalid or expired code. Please try again";
 
// Defaults are the Send Money step's copy; the checkout modal overrides all three.
const DEFAULT_RESEND_PROMPT = "Haven't received the code?";
const DEFAULT_RESEND_LABEL = "Resend it now";
const DefaultCountdownPrefix = () => (
  <>
    A new code was sent to your email. <br />
    Resend available in{" "}
  </>
);
 
interface OTPVerificationProps {
  email: string;
  otp: string;
  setOtp: (otp: string) => void;
  error?: any | null;
  timer: number;
  onResend: (e: React.MouseEvent) => void;
  title?: React.ReactNode;
  description?: string | JSX.Element;
  showLogo?: boolean;
  numInputs?: number;
  timerSx?: SxProps;
  /** "clock" renders m:ss, which is what a cooldown over a minute has to read as. */
  timerFormat?: "seconds" | "clock";
  resendPrompt?: string;
  /** Leads the countdown; the time itself is appended in the primary colour. */
  countdownPrefix?: React.ReactNode;
  resendLabel?: string;
}
 
export const OTPVerification = ({
  otp,
  setOtp,
  error,
  timer,
  onResend,
  title,
  description,
  showLogo = false,
  numInputs = 6,
  timerSx = {},
  timerFormat = "seconds",
  resendPrompt = DEFAULT_RESEND_PROMPT,
  countdownPrefix = <DefaultCountdownPrefix />,
  resendLabel = DEFAULT_RESEND_LABEL,
}: OTPVerificationProps) => {
  const { palette } = useAppTheme();
  const { isMobileView } = useCustomThemeV2();
 
  const countdown =
    timerFormat === "clock"
      ? `${Math.floor(timer / 60)}:${String(timer % 60).padStart(2, "0")}`
      : `${timer}s`;
 
  return (
    <Stack gap="40px" alignItems="center">
      {showLogo && <GivePayment width={196} height={20} />}
 
      {title && title}
      {description && description}
 
      <OTPContainer error={!!error}>
        <OTPInput
          value={otp}
          onChange={setOtp}
          numInputs={numInputs}
          renderInput={(props, index) => (
            <>
              <input {...props} data-testid={`otp-input-${index}`} />
              {/* Chrome renders the dash 1px narrower than the 7px Figma
                  text node, which shortens the whole row. */}
              {index === 2 && (
                <GiveText
                  variant="bodyM"
                  sx={{ width: "7px" }}
                  textAlign="center"
                >
                  -
                </GiveText>
              )}
            </>
          )}
          inputType="number"
          inputStyle={{
            width: isMobileView ? "49px" : "54px",
            height: isMobileView ? "54px" : "64px",
            padding: "8px",
            userSelect: "none",
            fontSize: "18px",
            fontWeight: 400,
          }}
          containerStyle={{ margin: "0 auto", gap: "8px" }}
        />
        {error && (
          <GiveText
            variant="bodyS"
            color="error"
            textAlign="center"
            role="alert"
          >
            {/* A string is the API's own wording, which names the cause the
                generic copy cannot -- an expiry, or a spent attempt cap. Other
                callers pass a form FieldError and keep the default. */}
            {typeof error === "string" ? error : OTP_GENERIC_ERROR}
          </GiveText>
        )}
      </OTPContainer>
 
      <Box sx={timerSx}>
        {timer === 0 ? (
          <Stack gap="12px" alignItems="center">
            <GiveText variant="bodyS">{resendPrompt}</GiveText>
            {/* A button, not a Link: an empty target navigates ("/" for a
                modal portaled outside the routes). */}
            <GiveLink component="button" color="secondary" onClick={onResend}>
              {resendLabel}
            </GiveLink>
          </Stack>
        ) : (
          <Stack gap="12px">
            <GiveText variant="bodyS" textAlign="center">
              {resendPrompt}
            </GiveText>
            <GiveText variant="bodyS" color="secondary" textAlign="center">
              {countdownPrefix}
              <span style={{ color: palette.text.primary }}>{countdown}</span>
            </GiveText>
          </Stack>
        )}
      </Box>
    </Stack>
  );
};
 
// Styled OTP input container
const OTPContainer = styled(Stack, {
  shouldForwardProp: (prop) => prop !== "error",
})<{ error: boolean }>(({ theme, error }) => ({
  "& input": {
    borderRadius: "12px",
    border: `solid 1.5px ${theme.palette.border?.secondary}`,
    textAlign: "center",
    "&:focus": {
      border: "solid 1.5px transparent",
      outline: "none",
      backgroundImage: `linear-gradient(${theme.palette.surface?.primary}, ${theme.palette.surface?.primary}), ${theme.palette.gradient?.["aqua-horizon"]?.border}`,
      backgroundOrigin: "border-box",
      backgroundClip: "padding-box, border-box",
    },
    ...(error && {
      border: `solid 1.5px ${theme.palette.primitive?.error[50]}`,
    }),
  },
}));