All files / src/components/DatePicker DatePicker.tsx

0% Statements 0/30
0% Branches 0/60
0% Functions 0/8
0% Lines 0/30

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                                                                                                                                                                                                                                                                                                                                                                                               
import React, { useState, KeyboardEventHandler } from 'react';
import { Box, SxProps } from '@mui/material';
import { LocalizationProvider, DesktopDatePicker, DesktopDateTimePicker } from '@mui/x-date-pickers';
import { AdapterLuxon } from '@mui/x-date-pickers/AdapterLuxon';
import { DateTime, Settings } from 'luxon';
import Icon from '../Icon/Icon';
import './styles.scss';
import { DateType, getDate, tz } from '../../utils/date';
 
/**
 * TODO: remove support for JS Date in DatePickerDateType once
 * clients have moved to only using DateTime objects in input props
 * and callback arguments.
 * export type DatePickerDateType = Exclude<DateType, Date> | null;
 */
export type DatePickerDateType = DateType | null;
 
export interface Props {
  'aria-label': string;
  autoFocus?: boolean;
  className?: string;
  defaultTimeZone?: string;
  disabled?: boolean;
  errorText?: string;
  helperText?: string;
  id: string;
  label: React.ReactNode;
  locale?: string;
  maxDate?: DatePickerDateType;
  minDate?: DatePickerDateType;
  /**
   * @deprecated Use onDateChange and switch to
   *  handling luxon DateTime arguments.
   */
  onChange?: (value?: Date | null) => void;
  /**
   * TODO: remove deprecated onChange and
   * make onDateChange required once all clients
   * have migrated to using onDateChange.
   */
  onDateChange?: (value?: DateTime) => void;
  onError?: (reason: any, value: any) => void;
  onKeyPress?: KeyboardEventHandler;
  sx?: SxProps;
  value?: DatePickerDateType;
  showTime?: boolean;
  placeholder?: string;
}
 
const initializeDate = (value?: DatePickerDateType, timeZoneId?: string): DateTime | null => {
  if (!value) {
    return null;
  }
 
  const date = getDate(value, timeZoneId);
 
  return date?.isValid ? date : null;
};
 
export default function DatePicker(props: Props): JSX.Element {
  const [temporalValue, setTemporalValue] = useState<DateTime | null>(
    initializeDate(props.value, props.defaultTimeZone)
  );
  const [minDateTime, setMinDateTime] = useState<DateTime | null>(initializeDate(props.minDate, props.defaultTimeZone));
  const [maxDateTime, setMaxDateTime] = useState<DateTime | null>(initializeDate(props.maxDate, props.defaultTimeZone));
  const locale = props.locale ?? 'en';
  Settings.defaultZone = tz(props.defaultTimeZone);
 
  React.useEffect(() => {
    setTemporalValue((prev) => {
      if (props.value !== prev && props.value) {
        return initializeDate(props.value, props.defaultTimeZone);
      } else {
        return prev;
      }
    });
  }, [props.defaultTimeZone, props.value]);
 
  React.useEffect(() => {
    setMinDateTime(initializeDate(props.minDate, props.defaultTimeZone));
  }, [props.defaultTimeZone, props.minDate]);
 
  React.useEffect(() => {
    setMaxDateTime(initializeDate(props.maxDate, props.defaultTimeZone));
  }, [props.defaultTimeZone, props.maxDate]);
 
  // TODO: Localize the yyyy-mm-dd placeholder string that is shown to users when the input is
  //       empty. It appears to be generated programmatically deep in the guts of the MUI DatePicker
  //       code, and it most likely uses the browser's locale.
  return (
    <Box className={`date-picker ${props.className} ${props.errorText ? 'date-picker--error' : ''}`} sx={props.sx}>
      <LocalizationProvider dateAdapter={AdapterLuxon} adapterLocale={locale}>
        {props.label && (
          <label htmlFor={props.id} className='textfield-label'>
            {props.label}
          </label>
        )}
        {props.showTime ? (
          <DesktopDateTimePicker
            disabled={props.disabled}
            minDate={minDateTime && minDateTime.isValid ? minDateTime : undefined}
            maxDate={maxDateTime && maxDateTime.isValid ? maxDateTime : undefined}
            onChange={(newValue: DateTime | null) => {
              setTemporalValue(newValue);
              // TODO: remove onChange and make onDateChange required
              if (props.onChange) {
                props.onChange(newValue && newValue.isValid ? newValue.toJSDate() : null);
              }
              if (props.onDateChange) {
                props.onDateChange(newValue && newValue.isValid ? newValue : undefined);
              }
            }}
            onError={props.onError}
            slotProps={{
              textField: {
                sx: {
                  '& fieldset': {
                    border: 'none',
                  },
                  '& .MuiFormHelperText-root': {
                    marginLeft: 0,
                  },
                },
                helperText: props.errorText ? (
                  <div className='textfield-error-text-container'>
                    <Icon name='error' className='textfield-error-text--icon' />
                    <label htmlFor={props.id} className='textfield-error-text'>
                      {props.errorText}
                    </label>
                  </div>
                ) : (
                  props.helperText
                ),
                id: props.id,
                placeholder: props.placeholder,
                autoFocus: props.autoFocus,
                onKeyPress: props.onKeyPress,
              },
            }}
            value={temporalValue}
          />
        ) : (
          <DesktopDatePicker
            disabled={props.disabled}
            format='yyyy-MM-dd'
            minDate={minDateTime && minDateTime.isValid ? minDateTime : undefined}
            maxDate={maxDateTime && maxDateTime.isValid ? maxDateTime : undefined}
            onChange={(newValue: DateTime | null) => {
              setTemporalValue(newValue);
              // TODO: remove onChange and make onDateChange required
              if (props.onChange) {
                props.onChange(newValue && newValue.isValid ? newValue.toJSDate() : null);
              }
              if (props.onDateChange) {
                props.onDateChange(newValue && newValue.isValid ? newValue : undefined);
              }
            }}
            onError={props.onError}
            slotProps={{
              textField: {
                sx: {
                  '& fieldset': {
                    border: 'none',
                  },
                  '& .MuiFormHelperText-root': {
                    marginLeft: 0,
                  },
                },
                helperText: props.errorText ? (
                  <div className='textfield-error-text-container'>
                    <Icon name='error' className='textfield-error-text--icon' />
                    <label htmlFor={props.id} className='textfield-error-text'>
                      {props.errorText}
                    </label>
                  </div>
                ) : (
                  props.helperText
                ),
                id: props.id,
                placeholder: props.placeholder,
                autoFocus: props.autoFocus,
                onKeyPress: props.onKeyPress,
              },
            }}
            value={temporalValue}
          />
        )}
      </LocalizationProvider>
    </Box>
  );
}