All files / src/components/common/CustomIntegerInput CustomIntegerInput.tsx

30.76% Statements 4/13
0% Branches 0/17
0% Functions 0/2
33.33% Lines 4/12

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          5x 5x 5x                                         5x                                                                            
import * as React from "react";
import { Box, BoxProps, SxProps } from "@mui/material";
import NumberFormat from "react-number-format";
import { Input } from "@common/Input";
 
const MAX_INT_VALUE = Number.MAX_SAFE_INTEGER;
const MIN_INT_VALUE = Number.MIN_SAFE_INTEGER;
const MAX_STOCK = 99999;
 
export type CustomAmountInputProps = {
  min?: number;
  max?: number;
  label?: string | React.ReactNode;
  placeholder?: string;
  error?: boolean;
  disabled?: boolean;
  helperText?: string | React.ReactNode;
  endIcon?: React.ReactNode;
  allowNegative?: boolean;
  inputRef?: React.Ref<any>;
  sx?: SxProps;
  value?: string | number | null | undefined;
  onChange?: React.ChangeEventHandler<HTMLInputElement>;
  onBlur?: React.FocusEventHandler<HTMLInputElement>;
  containerProps?: BoxProps;
  inputProps?: Record<any, any>;
};
 
const CustomIntegerInput = ({
  min = MIN_INT_VALUE,
  max = MAX_INT_VALUE,
  allowNegative = false,
  containerProps,
  ...props
}: CustomAmountInputProps) => {
  const minValue = min === MIN_INT_VALUE ? (allowNegative ? min : 0) : min;
 
  const isAllowed = (values: any) => {
    const { formattedValue, floatValue, value } = values;
    if (value > MAX_STOCK) return false;
 
    if (!floatValue && floatValue !== 0) {
      return formattedValue === "" || formattedValue === "-";
    } else {
      return floatValue >= minValue && floatValue <= max;
    }
  };
 
  return (
    <Box sx={{ width: "100%", ...containerProps?.sx }} {...containerProps}>
      <NumberFormat
        customInput={Input}
        thousandSeparator={false}
        allowLeadingZeros={false}
        allowNegative={allowNegative}
        decimalScale={0}
        isAllowed={isAllowed}
        fullWidth
        min={minValue}
        {...props}
      />
    </Box>
  );
};
 
export default CustomIntegerInput;