All files / src/components/common/DatePickers DatePicker.tsx

63.09% Statements 53/84
54.68% Branches 35/64
63.15% Functions 12/19
65.38% Lines 51/78

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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442                                                                                          138x                                       138x                                         138x       138x                                                                                                                                                             1233x 1233x 1233x 1233x 1233x 1233x   1233x 47x       1233x 50x 50x   50x   123x   10x         1233x         1233x           1233x 2x 2x       1233x               1233x   1520x 93x 1427x         1233x   196x 55x             55x 4x 4x     51x       1233x 1233x 1233x   1233x     1233x                                                                                 1458x                                                                                                 2x                                         138x                       138x 50x                   50x                         138x             55x 55x   55x   55x                                                        
import * as React from "react";
import { palette } from "@palette";
import { TextFieldProps } from "@mui/material/TextField";
import { DatePicker as MuiDatePicker } from "@mui/x-date-pickers/DatePicker";
import { DateTimePicker as MuiDateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import { debounce, isDate } from "lodash";
import { PopperPlacementType, PopperProps, SxProps } from "@mui/material";
import {
  CalendarBlankIcon,
  CaretDownIcon,
  CaretLeftIcon,
  CaretRightIcon,
} from "@phosphor-icons/react";
import { useAppTheme } from "@theme/v2/Provider";
import moment from "moment";
import { getUTCDefaultValue } from "@utils/date.helpers";
 
export type DatePickerProps = {
  width?: number;
  value: any;
  defaultValue?: any;
  time?: boolean;
  disabled?: boolean;
  inputFormat?: string;
  inputFormatTime?: string;
  size?: "small" | "medium";
  label?: React.ReactNode;
  minDate?: any;
  maxDate?: any;
  openTo?: "day" | "month" | "year";
  adornmentPosition?: "start" | "end";
  inputRef?: React.Ref<HTMLInputElement>;
  disablePast?: boolean;
  disableFuture?: boolean;
  renderInput: (props: TextFieldProps) => React.ReactElement;
  onChange: (value: any, keyboardInputValue?: string | undefined) => void;
  openPickerOnFocus?: boolean;
  popperPlacement?: PopperPlacementType;
  popperProps?: Omit<PopperProps, "open">;
  useGMT?: boolean;
  useUTCMoment?: boolean;
  setInitialValue?: (val: string) => void;
  paperStyle?: SxProps;
};
 
const paperStyle = {
  "& .PrivatePickersYear-yearButton.Mui-selected": {
    backgroundColor: `${palette.black.main} !important`,
    "&:hover": {
      backgroundColor: palette.black.main,
      opacity: 0.8,
    },
  },
  "& .MuiPickersDay-root.Mui-selected": {
    backgroundColor: `${palette.black.main} !important`,
    "&:hover": {
      backgroundColor: palette.black.main,
      opacity: 0.8,
    },
  },
  "& .Mui-disabled.Mui-selected": {
    backgroundColor: "transparent !important",
  },
};
 
const iconsSx = {
  "& .MuiIconButton-root": {
    height: "auto",
    border: "none",
    boxShadow: "none",
    padding: 0,
    marginLeft: "1px",
    marginRight: "1px",
 
    "&:hover": {
      background: "none",
      boxShadow: "none",
    },
    "&:active, &:focus": {
      border: "none",
      boxShadow: "none",
    },
  },
  ...paperStyle,
};
 
const inputSx = {
  ...iconsSx,
};
 
const dialogStyle = {
  "& .MuiDialog-container": {
    alignItems: "center",
  },
  "& .MuiDialogContent-root": {
    padding: 0,
    borderBottom: "none",
 
    ".MuiPickersToolbar-root.MuiDatePickerToolbar-root > .MuiGrid-root.MuiGrid-container":
      {
        alignItems: "flex-start",
      },
  },
  "& .MuiDialog-paper": {
    background: "#FFFFFF",
 
    ...iconsSx,
 
    "@media (max-width: 600px)": {
      top: "initial",
      height: "auto",
      borderRadius: "4.5px",
      maxHeight: "calc(100% - 64px)",
    },
  },
  "& .MuiDialogActions-root": {
    backgroundColor: "#FFFFFF",
 
    "& .MuiButton-root.MuiButton-primary": {
      border: "none",
      color: "#1976d2",
      boxShadow: "none",
      textTransform: "uppercase",
      backgroundColor: "transparent",
 
      "&:hover": {
        boxShadow: "none",
        background: "none",
        backgroundColor: "none",
      },
    },
 
    "@media (max-width: 600px)": {
      flexDirection: "row",
      justifyContent: "flex-end",
 
      "& > :not(:first-of-type)": {
        marginLeft: 0,
      },
 
      "& .MuiButton-root": {
        width: "auto",
      },
    },
  },
  ...paperStyle,
};
 
export default function DatePicker({
  inputRef,
  minDate,
  maxDate,
  renderInput,
  inputFormat = "MM/dd/yyyy",
  adornmentPosition = "start",
  inputFormatTime = "MM/dd/yyyy 'at' hh:mm a",
  disablePast,
  disableFuture,
  openTo = "day",
  openPickerOnFocus = false,
  popperPlacement = "bottom",
  useGMT = true,
  popperProps = {},
  defaultValue,
  setInitialValue,
  useUTCMoment = false,
  paperStyle: customPaperStyle,
  ...props
}: DatePickerProps) {
  const keyboardInputRef = React.useRef<string>("");
  const [isOpen, setIsOpen] = React.useState<boolean>(false);
  const [anchorEl, setAnchorEl] = React.useState<HTMLElement | null>(null);
  const anchorRef = React.useRef<HTMLInputElement>(null);
  const popupDisabledRef = React.useRef(false);
  const { palette } = useAppTheme();
 
  const handleChange = (value: any, keyboardInputValue?: string) => {
    if (useUTCMoment) props.onChange(value);
    else Eprops.onChange(validatedDate({ value, render: false, useGMT }));
  };
 
  const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
    const key = event.key;
    const regex = getValidationRegex(inputFormat);
 
    if (
      !regex.test(keyboardInputRef.current + key) &&
      !navigationKeys.some((item) => item === key)
    ) {
      event.preventDefault();
    }
  };
 
  //Prevents picker from reopening onfocus after blur when value is empty
  const preventInstantReopen = () => {
    popupDisabledRef.current = true;
    setTimeout(() => (popupDisabledRef.current = false), 500);
  };
 
  const handleClose = () => {
    if (anchorEl) setAnchorEl(null);
    setIsOpen(false);
    preventInstantReopen();
  };
 
  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    Iif (anchorEl) return; //to avoid glitches if picker is already open
    setAnchorEl(event.currentTarget);
  };
 
  //debounce is needed to avoid glitchy behavour
  const handleOpenPicker = debounce(() => {
    if (anchorRef.current && !anchorEl && !popupDisabledRef.current) {
      setAnchorEl(anchorRef.current);
      setIsOpen(true);
      anchorRef.current.focus();
    }
  }, 200);
 
  const handleRenderInput = React.useCallback(
    (props: TextFieldProps) => {
      if (openPickerOnFocus)
        return renderInput({ ...props, onFocus: () => handleOpenPicker() });
      else return renderInput(props);
    },
    [renderInput, openPickerOnFocus],
  );
 
  React.useEffect(() => {
    // on first render make sure date is formatted - otherwise on save it will change to wrong date
    if (props.value) {
      const value = validatedDate({
        value: new Date(props.value),
        render: true,
        useGMT,
        useUTCMoment,
      });
 
      if (setInitialValue) {
        setInitialValue(value);
        return;
      }
 
      props.onChange(value, "initial");
    }
  }, []);
 
  const { val, defVal } = (() => {
    const val = getUTCDefaultValue(props?.value, useUTCMoment);
    const defVal = getUTCDefaultValue(defaultValue, useUTCMoment);
 
    return { val, defVal };
  })();
 
  return (
    <>
      {props.time ? (
        <MuiDateTimePicker
          components={{
            OpenPickerIcon: () => <CalendarBlankIcon size={20} />,
          }}
          InputProps={{
            sx: inputSx,
          }}
          PopperProps={{
            sx: iconsSx,
            placement: popperPlacement,
            anchorEl,
            open: Boolean(anchorEl),
          }}
          DialogProps={{
            sx: dialogStyle,
          }}
          InputAdornmentProps={{
            position: adornmentPosition,
            onClick: handleClick,
          }}
          open={isOpen}
          onOpen={() => setIsOpen(true)}
          onClose={handleClose}
          minDate={minDate}
          maxDate={maxDate}
          inputRef={inputRef}
          inputFormat={inputFormatTime}
          value={val}
          defaultCalendarMonth={defVal ? moment(defVal) : undefined}
          onChange={props.onChange}
          renderInput={renderInput}
          disabled={props.disabled}
          disableMaskedInput
        />
      ) : (
        <MuiDatePicker
          components={{
            OpenPickerIcon: () => (
              <CalendarBlankIcon
                size={20}
                color={
                  props.disabled
                    ? palette.icon?.["remain-light"]
                    : palette.icon?.["icon-primary"]
                }
              />
            ),
            SwitchViewIcon: CaretDownIcon,
            RightArrowIcon: CaretRightIcon,
            LeftArrowIcon: CaretLeftIcon,
          }}
          InputProps={{
            sx: inputSx,
            onKeyDown: handleKeyDown,
          }}
          PaperProps={{
            sx: { ...paperStyle, ...customPaperStyle },
            style: {
              borderRadius: "12px",
              overflow: "hidden",
              boxShadow: "0px 4px 8px rgba(0, 0, 0, 0.1)",
              border: "1px solid #CCCCC9",
            },
          }}
          PopperProps={{
            sx: iconsSx,
            placement: popperPlacement,
            anchorEl,
            open: Boolean(anchorEl),
            modifiers: [
              {
                name: "offset",
                options: {
                  offset: [-15, 40],
                },
              },
            ],
            ...popperProps,
          }}
          DialogProps={{
            sx: dialogStyle,
          }}
          InputAdornmentProps={{
            position: adornmentPosition,
            onClick: handleClick,
          }}
          open={isOpen}
          onOpen={() => setIsOpen(true)}
          onClose={handleClose}
          minDate={minDate}
          maxDate={maxDate}
          inputFormat={inputFormat}
          value={val}
          defaultCalendarMonth={defVal ? moment(defVal) : undefined}
          onChange={handleChange}
          renderInput={handleRenderInput}
          disabled={props.disabled}
          disablePast={disablePast}
          disableFuture={disableFuture}
          // disableMaskedInput
          openTo={openTo}
          inputRef={anchorRef}
        />
      )}
    </>
  );
}
 
const navigationKeys = [
  "ArrowDown",
  "ArrowUp",
  "ArrowLeft",
  "ArrowRight",
  "Enter",
  "Escape",
  "Backspace",
  "Delete",
  "Tab",
];
 
const getValidationRegex = (inputFormat: string): RegExp => {
  switch (inputFormat) {
    case "dd/MM/yyyy":
      return /^0?$|^(?:0?[1-9]|1[012]?)(?:\/(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:\/\d{0,4})?)?)?$/;
    case "MM/dd/yyyy":
      return /^0?$|^(?:0?[1-9]|1[012]?)(?:\/(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:\/\d{0,4})?)?)?$/;
    case "dd-MM-yyyy":
      return /^0?$|^(?:0?[1-9]|[12]\d|3[01])(?:-(?:(?:0$|0?[1-9]|1[012]?)(?:-\d{0,4})?)?)?$/;
    case "MM-dd-yyyy":
      return /^0?$|^(?:0?[1-9]|1[012]?)(?:-(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:-\d{0,4})?)?)?$/;
    default:
      return /^0?$|^(?:0?[1-9]|1[012]?)(?:\/(?:(?:0$|0?[1-9]|[12]\d|3[01])(?:\/\d{0,4})?)?)?$/;
  }
};
 
// Todo: refactor this function to accpet an obj as param for better readability
type ValidateDateType = {
  value: any;
  render?: boolean;
  useGMT?: boolean;
  useUTCMoment?: boolean;
};
 
//TODO: the function should be refactored int he scope of TDI report we have for the dates logic
export const validatedDate: any = ({
  value,
  render = false,
  useGMT = true,
  useUTCMoment = false,
}: ValidateDateType) => {
  // Check if the provided value is a valid date, if yes we format it
  if (isDate(value) && !isNaN(value.getTime())) {
    const format = "ddd MMM DD YYYY HH:mm:ss";
    const isValidDate =
      moment(value.toString().substring(0, 24), format, true).isValid() &&
      value.getFullYear() > 1924;
    Eif (useUTCMoment && isValidDate) return new Date(value);
  } else E{
    //TODO: this else could most likely be cleaned up
    // Set the hour, minute, and second to the one the dateinput is using by default
    //we need to add this otherwise the manually inputed date will have the hour as 00.00.00 which will be a problem later when we send it to BE
    //it is better to handle this here, instead of where we create a payload, to avoid issues in all places
    value?.setHours(1);
    value?.setMinutes(44);
    value?.setSeconds(26);
  }
 
  // first we convert time in miliseconds to localtimezone
  const timezoneOffsetMillis = value?.getTimezoneOffset() * 60 * 1000;
  // then we add 2 hours to account for GMT+2 offset
  // - 1 second = 1000 milliseconds
  // - 1 minute = 60 seconds
  // - 1 hour = 60 minutes
  // - 2 hours = 2 * 60 * 60 * 1000
  const gmt2ffsetMillis = 2 * 60 * 60 * 1000;
 
  if (useGMT && !useUTCMoment) {
    value?.setTime(value?.getTime() - timezoneOffsetMillis + gmt2ffsetMillis);
  } else if (value && render) {
    const newValue = new Date(value);
    return validatedDate({ value: newValue });
  }
  return value;
};