All files / src/shared/DateRangePicker GiveDateRangePicker.tsx

28.2% Statements 22/78
23.8% Branches 15/63
46.15% Functions 6/13
28.16% Lines 20/71

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                                                                                                                18x 18x 18x 18x     18x 18x 18x                           18x   18x 18x     18x                                   18x           18x 2x     18x                                                         18x                                                         18x                                                                         6x                                                                                                                                         127x     18x                
import { Popover, Stack } from "@mui/material";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import RangePicker from "./RangePicker";
import {
  useState,
  useRef,
  MouseEventHandler,
  ChangeEventHandler,
  useEffect,
} from "react";
import { CalendarBlankIcon } from "@phosphor-icons/react";
import { useAppTheme } from "@theme/v2/Provider";
import { GiveInput, InputProps } from "@shared/GiveInputs/GiveInput";
import { RangeValue } from "./DateRangePicker.types";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import {
  fixDate,
  formatForInput,
  formatInput,
  isValidDateRange,
  stringToDate,
} from "./utils";
import GiveButton from "@shared/Button/GiveButton";
import { isEmpty } from "lodash";
import { useFormatDateInTimezone } from "@utils/date.helpers";
import moment from "moment";
 
interface Props {
  inputProps?: InputProps;
  value: RangeValue | string;
  onChange: (val: RangeValue | string) => void;
  maxDate?: Date;
  minDate?: Date;
  validateDate?: boolean;
  useUTCMoment?: boolean;
  useTimezone?: boolean;
  customAnchorEl?: HTMLButtonElement | HTMLDivElement | null;
  onClose?: () => void;
  popoverZIndex?: number;
  onApply?: (range: RangeValue) => void;
}
 
export default function GiveDateRangePicker({
  inputProps,
  value,
  onChange,
  validateDate = true,
  maxDate,
  minDate,
  useUTCMoment,
  useTimezone,
  customAnchorEl,
  onClose,
  popoverZIndex = 12000,
  onApply,
}: Props) {
  const { isMobileView } = useCustomThemeV2();
  const { palette } = useAppTheme();
  const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
  const [inputValue, setInputValue] = useState(
    typeof value === "string" ? value : "",
  );
  const { formatInTimezone, currentTimezone } = useFormatDateInTimezone();
  const defaultDate = (() => {
    Eif (typeof value === "string") return parseDateRange(value);
    if (useTimezone) {
      return {
        startDate: value.startDate
          ? new Date(formatInTimezone(value.startDate) as string)
          : undefined,
        endDate: value.endDate
          ? new Date(formatInTimezone(value.endDate) as string)
          : undefined,
      };
    }
    return value;
  })();
 
  const pendingRangeRef = useRef<RangeValue>(defaultDate);
 
  useEffect(() => {
    pendingRangeRef.current = defaultDate;
  }, [defaultDate]);
 
  const handleMobileActions = (isCancel = false) => {
    if (isCancel) {
      !validateDate
        ? onChange("")
        : onChange({ startDate: undefined, endDate: undefined });
      setInputValue("");
    } else {
      if (onApply) {
        onApply(pendingRangeRef.current);
      } else {
        const newInputValue = formatForInput(defaultDate).newInputValue;
        setInputValue(newInputValue);
      }
    }
    setAnchorEl(null);
    if (onClose) onClose();
  };
 
  const handleClose = () => {
    if (onClose) onClose();
    else setAnchorEl(null);
    if (isMobileView) handleMobileActions();
  };
 
  const handleOpenPicker: MouseEventHandler<HTMLButtonElement> = (e) => {
    setAnchorEl(e.currentTarget);
  };
 
  const handleChange = (value: RangeValue) => {
    pendingRangeRef.current = value;
    const newInputValue = fixDate({
      dateString: formatForInput(value, true).newInputValue,
      minDate,
      maxDate,
    });
 
    if (!validateDate || useTimezone) {
      const refineValue = formatDateRange(newInputValue);
      if (useTimezone) {
        const splitValues = refineValue.includes("-")
          ? refineValue.split(" - ")
          : [refineValue, refineValue];
        const start = moment
          .tz(splitValues[0], "MM/DD/YYYY", currentTimezone)
          .toDate();
        const end = moment
          .tz(splitValues[1], "MM/DD/YYYY", currentTimezone)
          .toDate();
        onChange({ startDate: start, endDate: end });
      } else onChange(refineValue);
      setInputValue(refineValue);
      return;
    }
    if (!isMobileView) setInputValue(newInputValue);
    onChange(value);
  };
 
  const handleChangeInput: ChangeEventHandler<HTMLInputElement> = (e) => {
    const inputValue = e.target.value;
    if ((e.nativeEvent as InputEvent).inputType === "deleteContentBackward") {
      setInputValue(e.target.value);
 
      !validateDate && onChange(e.target.value);
      return;
    }
    const formatted = fixDate({
      dateString: formatInput(inputValue),
      minDate,
      maxDate,
    });
 
    setInputValue(formatted);
 
    if (!validateDate) {
      onChange(formatted);
 
      return;
    }
    const isValid = isValidDateRange(formatted);
    if (!isValid) return;
 
    const { startDate, endDate } = stringToDate(formatted);
 
    onChange({ startDate, endDate });
  };
 
  return (
    <>
      {customAnchorEl === undefined && ( //important to check for undefined, as the anchor can be null
        <GiveInput
          name={inputProps?.name || "date"}
          onChange={handleChangeInput}
          value={inputValue}
          placeholder="MM/DD/YYYY"
          data-testid="date-range-input-id"
          {...inputProps}
          leftContent={
            <GiveIconButton
              Icon={CalendarBlankIcon}
              onClick={handleOpenPicker}
              variant="ghost"
              data-testid="date-range-input-calendar-icon"
            />
          }
        />
      )}
      <Popover
        id="date-range-picker-popover"
        open={Boolean(customAnchorEl || anchorEl)}
        anchorEl={customAnchorEl || anchorEl}
        onClose={handleClose}
        slotProps={{
          paper: {
            style: {
              borderRadius: "16px",
              boxShadow: isMobileView
                ? "none"
                : "0px 4px 8px rgba(0, 0, 0, 0.1)",
 
              backgroundColor: palette.surface?.primary,
              padding: "16px",
            },
            sx() {
              return {
                backgroundImage: "none !important",
                backgroundColor: `${palette.surface?.primary} !important`,
                border: `1px solid ${palette.border?.secondary} !important`,
              };
            },
          },
          root: {
            style: {
              zIndex: popoverZIndex,
            },
            slotProps: {
              backdrop: {
                style: {
                  backgroundColor: isMobileView
                    ? palette.surface?.overlay
                    : "transparent",
                },
              },
            },
          },
        }}
        anchorOrigin={{
          vertical: 45,
          horizontal: "center",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <RangePicker
          minDate={minDate}
          maxDate={maxDate}
          initialRange={defaultDate}
          onSelectionChange={handleChange}
          useUTCMoment={useUTCMoment}
          useTimezone={useTimezone}
        />
        {isMobileView && (
          <Stack
            direction="row"
            justifyContent="flex-end"
            gap="8px"
            marginTop="20px"
          >
            <GiveButton
              label="Cancel"
              variant="ghost"
              onClick={() => handleMobileActions(true)}
            />
            <GiveButton
              label="Apply"
              variant="filled"
              size="small"
              onClick={() => handleMobileActions()}
            />
          </Stack>
        )}
      </Popover>
    </>
  );
}
 
function formatDateRange(dateRange: string) {
  const [startDate, endDate] = dateRange.split(" - ");
  return startDate === endDate ? startDate : dateRange;
}
 
const parseDateRange = (
  dateRange: string,
): { startDate?: Date; endDate?: Date } => {
  Eif (isEmpty(dateRange)) return { startDate: new Date(), endDate: new Date() };
  const dates = dateRange.split(" - ").join("-").split("-");
 
  const startDate = new Date(dates[0]);
  const endDate = dates[1] ? new Date(dates[1]) : new Date(dates[0]);
 
  return { startDate, endDate };
};