All files / app/components Datepicker.tsx

100% Statements 14/14
80% Branches 4/5
100% Functions 4/4
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 938x         8x 8x 8x     8x   8x 451x                                         8x                             435x 435x               451x                                     228x 26x 26x                          
import DateFnsUtils from "@date-io/dayjs";
import {
  DatePickerView,
  KeyboardDatePicker,
  MuiPickersUtilsProvider,
} from "@material-ui/pickers";
import { useTranslation } from "i18n";
import { Control, Controller, UseControllerOptions } from "react-hook-form";
import { Dayjs } from "utils/dayjs";
 
import { dateFormats } from "./constants";
 
const getLocaleFormat = () => {
  return navigator.language in dateFormats
    ? dateFormats[navigator.language as keyof typeof dateFormats]
    : "DD/MM/YYYY";
};
 
interface DatepickerProps {
  className?: string;
  control: Control;
  defaultValue?: Dayjs | null;
  error: boolean;
  helperText: React.ReactNode;
  id: string;
  rules?: UseControllerOptions["rules"];
  label?: string;
  name: string;
  minDate?: Date;
  openTo?: DatePickerView;
  onPostChange?(date: Dayjs): void;
  testId?: string;
}
 
export default function Datepicker({
  className,
  control,
  defaultValue,
  error,
  helperText,
  id,
  rules,
  label,
  minDate = new Date(),
  name,
  openTo = "date",
  onPostChange,
  testId,
}: DatepickerProps) {
  const { t } = useTranslation();
  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <Controller
        control={control}
        defaultValue={defaultValue}
        name={name}
        rules={rules}
        render={({ onChange, value }) => (
          <KeyboardDatePicker
            animateYearScrolling={true}
            autoOk
            className={className}
            data-testid={testId}
            error={error}
            format={getLocaleFormat()}
            fullWidth
            helperText={helperText}
            id={id}
            KeyboardButtonProps={{
              "aria-label": t("components.datepicker.change_date"),
            }}
            InputLabelProps={{
              shrink: true,
            }}
            label={label}
            minDate={minDate}
            onChange={(date) => {
              if (date?.isValid()) {
                onChange(date);
                onPostChange?.(date);
              }
            }}
            openTo={openTo}
            views={["year", "month", "date"]}
            value={value}
            variant="inline"
          />
        )}
      />
    </MuiPickersUtilsProvider>
  );
}