All files / src/shared/GiveInputs GiveCustomAmount.tsx

87.5% Statements 35/40
78.84% Branches 41/52
90% Functions 9/10
90.32% Lines 28/31

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                                                                      487x 24x   487x                                           1215x   1215x 120x 12x       1215x 24x 24x   24x     24x       1215x 16x           11x 16x     1215x 1215x   1197x     1208x         1215x 24x 18x 18x     1215x     1215x           1215x                                                               487x      
import React, { memo, useEffect, useImperativeHandle, useRef } from "react";
import { Box, SxProps } from "@mui/material";
import NumberFormat, { NumberFormatValues } from "react-number-format";
import { GiveInput, InputProps } from "./GiveInput";
import { InputAdornment } from "@mui/material";
import { MAX_ALLOWED_AMOUNT } from "@constants/constants";
 
export type GiveCustomAmountProps = {
  id?: string;
  min?: number;
  max?: number;
  bounded?: boolean;
  onBlur?: () => void;
  label?: string | React.ReactNode;
  placeholder?: string;
  error?: boolean;
  disabled?: boolean;
  helperText?: string | React.ReactNode;
  currency?: string;
  initialValue?: string;
  onChange?: (value: string) => void;
  isDirty?: boolean;
  value?: string;
  startIcon?: React.ReactNode;
  endIcon?: React.ReactNode;
  InputComponent?: React.FC<InputProps>;
  simpleNumber?: boolean;
  hidePlaceholder?: boolean;
  sx?: SxProps;
  decimalScale?: number;
  thousandSeparator?: boolean;
  fixedDecimalScale?: boolean;
  disableAutoFormat?: boolean;
};
 
export const getValueFromString = (value: string) =>
  parseFloat(value.replaceAll(",", ""));
 
const GiveCustomAmount = React.forwardRef<NumberFormat, GiveCustomAmountProps>(
  (
    {
      min = 1,
      max = MAX_ALLOWED_AMOUNT,
      onBlur,
      bounded = true,
      helperText,
      initialValue,
      onChange,
      value,
      startIcon,
      endIcon,
      InputComponent = GiveInput,
      simpleNumber = false,
      decimalScale = 2,
      thousandSeparator = true,
      disableAutoFormat = false,
      ...props
    },
    ref,
  ) => {
    const numberFormatRef = useRef<NumberFormat>(null);
 
    useEffect(() => {
      if (initialValue) {
        Eif (onChange) onChange(initialValue);
      }
    }, []);
 
    const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const trueValue = getValueFromString(e.target.value);
      Iif (trueValue < min) {
        if (onChange) onChange(min + ".00");
      } else Iif (trueValue > max && bounded) {
        if (onChange) onChange(max + ".00");
      } else {
        Eif (onChange) onChange(e.target.value);
      }
    };
 
    const formatAmount = () => {
      if (
        !simpleNumber &&
        typeof value === "string" &&
        !value.includes(".") &&
        !disableAutoFormat
      )
        if (onChange && value) onChange(value + ".00");
      Eif (onBlur) onBlur();
    };
 
    const formatCurrency = (currency: string | undefined): string => {
      if (!currency) return "";
 
      return currency
        .split(" ")
        .map((word) =>
          word.toLowerCase() === "usd" ? word.toUpperCase() : word,
        )
        .join(" ");
    };
 
    const isAllowed = (values: NumberFormatValues) => {
      if (!bounded) return true;
      const { value } = values;
      return +value >= 0 && +value <= max;
    };
 
    const isStringHelperText = typeof helperText === "string";
    // GiveCustomAmount forwards the ref to <NumberFormat>, but NumberFormat doesn't expose a .focus() method on its ref
    // it returns a ref to the NumberFormat instance, not the underlying <input> DOM element
    useImperativeHandle(ref, () => ({
      focus: () => {
        (numberFormatRef.current as any)?.inputElement?.focus();
      },
    }));
 
    return (
      <Box sx={{ width: "100%" }}>
        <NumberFormat
          ref={numberFormatRef}
          {...props}
          currency={formatCurrency(props?.currency)}
          customInput={InputComponent}
          value={value}
          thousandSeparator={thousandSeparator}
          onBlur={formatAmount}
          allowNegative={false}
          decimalScale={decimalScale}
          isAllowed={isAllowed}
          fullWidth
          {...(isStringHelperText && { helperText })}
          onChange={handleAmountChange}
          inputMode="numeric"
          InputProps={{
            startAdornment: startIcon && (
              <InputAdornment position="start">{startIcon}</InputAdornment>
            ),
            endAdornment: endIcon && (
              <InputAdornment position="end">{endIcon}</InputAdornment>
            ),
          }}
        />
        {!isStringHelperText && helperText}
      </Box>
    );
  },
);
 
GiveCustomAmount.displayName = "GiveCustomAmount";
 
export default memo(GiveCustomAmount);