| 1 |
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; |
| 2 |
import { css } from '@patternfly/react-styles'; |
| 3 |
import styles from '@patternfly/react-styles/css/components/DatePicker/date-picker'; |
| 4 |
import calendarMonthStyles from '@patternfly/react-styles/css/components/CalendarMonth/calendar-month'; |
| 5 |
import { TextInput, TextInputProps } from '../TextInput/TextInput'; |
| 6 |
import { Button } from '../Button'; |
| 7 |
import { Popover, PopoverProps } from '../Popover/Popover'; |
| 8 |
import { InputGroup, InputGroupItem } from '../InputGroup'; |
| 9 |
import RhUiCalendarIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-calendar-icon'; |
| 10 |
import { CalendarMonth, CalendarFormat } from '../CalendarMonth'; |
| 11 |
import { KeyTypes } from '../../helpers'; |
| 12 |
import { isValidDate } from '../../helpers/datetimeUtils'; |
| 13 |
import { HelperText, HelperTextItem } from '../HelperText'; |
| 14 |
import cssFormControlWidthChars from '@patternfly/react-tokens/dist/esm/c_date_picker__input_c_form_control_width_chars'; |
| 15 |
|
| 16 |
/** Props that customize the requirement of a date */ |
| 17 |
export interface DatePickerRequiredObject { |
| 18 |
/** Flag indicating the date is required. */ |
| 19 |
isRequired?: boolean; |
| 20 |
/** Error message to display when the text input is empty and the isRequired prop is also passed in. */ |
| 21 |
emptyDateText?: string; |
| 22 |
} |
| 23 |
|
| 24 |
/** The main date picker component. */ |
| 25 |
|
| 26 |
export interface DatePickerProps |
| 27 |
extends |
| 28 |
CalendarFormat, |
| 29 |
Omit<React.HTMLProps<HTMLInputElement>, 'onChange' | 'onFocus' | 'onBlur' | 'disabled' | 'ref'> { |
| 30 |
/** The container to append the menu to. Defaults to 'inline'. |
| 31 |
* If your menu is being cut off you can append it to an element higher up the DOM tree. |
| 32 |
* Some examples: |
| 33 |
* menuAppendTo={() => document.body}; |
| 34 |
* menuAppendTo={document.getElementById('target')} |
| 35 |
*/ |
| 36 |
appendTo?: HTMLElement | ((ref?: HTMLElement) => HTMLElement) | 'inline'; |
| 37 |
/** Accessible label for the date picker. */ |
| 38 |
'aria-label'?: string; |
| 39 |
/** Accessible label for the button to open the date picker. */ |
| 40 |
buttonAriaLabel?: string; |
| 41 |
/** Additional classes added to the date picker. */ |
| 42 |
className?: string; |
| 43 |
/** How to format the date in the text input. */ |
| 44 |
dateFormat?: (date: Date) => string; |
| 45 |
/** How to parse the date in the text input. */ |
| 46 |
dateParse?: (value: string) => Date; |
| 47 |
/** Helper text to display alongside the date picker. Expects a HelperText component. */ |
| 48 |
helperText?: React.ReactNode; |
| 49 |
/** Additional props for the text input. */ |
| 50 |
inputProps?: TextInputProps; |
| 51 |
/** Flag indicating the date picker is disabled. */ |
| 52 |
isDisabled?: boolean; |
| 53 |
/** Error message to display when the text input contains a non-empty value in an invalid format. */ |
| 54 |
invalidFormatText?: string; |
| 55 |
/** Callback called every time the text input loses focus. */ |
| 56 |
onBlur?: (event: any, value: string, date?: Date) => void; |
| 57 |
/** Callback called every time the text input value changes. */ |
| 58 |
onChange?: (event: React.FormEvent<HTMLInputElement>, value: string, date?: Date) => void; |
| 59 |
/** String to display in the empty text input as a hint for the expected date format. */ |
| 60 |
placeholder?: string; |
| 61 |
/** Props to pass to the popover that contains the calendar month component. */ |
| 62 |
popoverProps?: Partial<Omit<PopoverProps, 'appendTo'>>; |
| 63 |
/** Options to customize the requirement of a date */ |
| 64 |
requiredDateOptions?: DatePickerRequiredObject; |
| 65 |
/** Functions that returns an error message if a date is invalid. */ |
| 66 |
validators?: ((date: Date) => string)[]; |
| 67 |
/** Value of the text input. */ |
| 68 |
value?: string; |
| 69 |
} |
| 70 |
|
| 71 |
/** Allows finer control over the calendar's open state when a React ref is passed into the |
| 72 |
* date picker component. Accessed via ref.current[property], e.g. ref.current.toggleCalendar(). |
| 73 |
*/ |
| 74 |
|
| 75 |
export interface DatePickerRef { |
| 76 |
/** Current calendar open status. */ |
| 77 |
isCalendarOpen: boolean; |
| 78 |
/** Sets the calendar open status. */ |
| 79 |
setCalendarOpen: (isOpen: boolean) => void; |
| 80 |
/** Toggles the calendar open status. If no parameters are passed, the calendar will simply |
| 81 |
* toggle its open status. |
| 82 |
* If the isOpen parameter is passed, that will set the calendar open status to the value |
| 83 |
* of the isOpen parameter. |
| 84 |
* If the eventKey parameter is set to 'Escape', that will invoke the date pickers |
| 85 |
* onEscapePress event to toggle the correct control appropriately. |
| 86 |
*/ |
| 87 |
toggleCalendar: (isOpen?: boolean) => void; |
| 88 |
} |
| 89 |
|
| 90 |
export const yyyyMMddFormat = (date: Date) => |
| 91 |
`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date |
| 92 |
.getDate() |
| 93 |
.toString() |
| 94 |
.padStart(2, '0')}`; |
| 95 |
|
| 96 |
const DatePickerBase = ( |
| 97 |
{ |
| 98 |
className, |
| 99 |
locale = undefined, |
| 100 |
dateFormat = yyyyMMddFormat, |
| 101 |
dateParse = (val: string) => (val.split('-').length === 3 ? new Date(`${val}T00:00:00`) : new Date(undefined)), |
| 102 |
isDisabled = false, |
| 103 |
placeholder = 'YYYY-MM-DD', |
| 104 |
value: valueProp = '', |
| 105 |
'aria-label': ariaLabel = 'Date picker', |
| 106 |
buttonAriaLabel = 'Toggle date picker', |
| 107 |
onChange = (): any => undefined, |
| 108 |
onBlur = (): any => undefined, |
| 109 |
invalidFormatText = 'Invalid date', |
| 110 |
requiredDateOptions, |
| 111 |
helperText, |
| 112 |
appendTo = 'inline', |
| 113 |
popoverProps, |
| 114 |
monthFormat, |
| 115 |
weekdayFormat, |
| 116 |
longWeekdayFormat, |
| 117 |
dayFormat, |
| 118 |
weekStart, |
| 119 |
validators = [], |
| 120 |
rangeStart, |
| 121 |
style: styleProps = {}, |
| 122 |
inputProps = {}, |
| 123 |
...props |
| 124 |
}: DatePickerProps, |
| 125 |
ref: React.Ref<DatePickerRef> |
| 126 |
) => { |
| 127 |
const [value, setValue] = useState(valueProp); |
| 128 |
const [valueDate, setValueDate] = useState(dateParse(value)); |
| 129 |
const [errorText, setErrorText] = useState(''); |
| 130 |
const [popoverOpen, setPopoverOpen] = useState(false); |
| 131 |
const [selectOpen, setSelectOpen] = useState(false); |
| 132 |
const [pristine, setPristine] = useState(true); |
| 133 |
const [textInputFocused, setTextInputFocused] = useState(false); |
| 134 |
const widthChars = useMemo(() => Math.max(dateFormat(new Date()).length, placeholder.length), [dateFormat]); |
| 135 |
const style = { [cssFormControlWidthChars.name]: widthChars, ...styleProps }; |
| 136 |
const buttonRef = useRef<HTMLButtonElement>(undefined); |
| 137 |
const datePickerWrapperRef = useRef<HTMLDivElement>(undefined); |
| 138 |
const triggerRef = useRef<HTMLDivElement>(undefined); |
| 139 |
const dateIsRequired = requiredDateOptions?.isRequired || false; |
| 140 |
const emptyDateText = requiredDateOptions?.emptyDateText || 'Date cannot be blank'; |
| 141 |
|
| 142 |
useEffect(() => { |
| 143 |
setValue(valueProp); |
| 144 |
setValueDate(dateParse(valueProp)); |
| 145 |
}, [valueProp]); |
| 146 |
|
| 147 |
useEffect(() => { |
| 148 |
if (isValidDate(valueDate)) { |
| 149 |
applyValidators(valueDate); |
| 150 |
} |
| 151 |
}, [validators]); |
| 152 |
|
| 153 |
useEffect(() => { |
| 154 |
setPristine(!value); |
| 155 |
const newValueDate = dateParse(value); |
| 156 |
if (errorText && isValidDate(newValueDate)) { |
| 157 |
applyValidators(newValueDate); |
| 158 |
} |
| 159 |
if (value === '' && !pristine && !textInputFocused) { |
| 160 |
dateIsRequired ? setErrorText(emptyDateText) : setErrorText(''); |
| 161 |
} |
| 162 |
}, [value]); |
| 163 |
|
| 164 |
const applyValidators = (date: Date) => { |
| 165 |
const validatorResults = validators.map((validator) => validator(date)); |
| 166 |
const validatorsToApply = validatorResults.filter((validator) => validator !== ''); |
| 167 |
setErrorText(validatorsToApply.join('\n') || ''); |
| 168 |
}; |
| 169 |
|
| 170 |
const onTextInput = (event: React.FormEvent<HTMLInputElement>, value: string) => { |
| 171 |
setValue(value); |
| 172 |
setErrorText(''); |
| 173 |
const newValueDate = dateParse(value); |
| 174 |
setValueDate(newValueDate); |
| 175 |
if (isValidDate(newValueDate)) { |
| 176 |
onChange(event, value, new Date(newValueDate)); |
| 177 |
} else { |
| 178 |
onChange(event, value); |
| 179 |
} |
| 180 |
}; |
| 181 |
|
| 182 |
const onInputBlur = (event: any) => { |
| 183 |
setTextInputFocused(false); |
| 184 |
const newValueDate = dateParse(value); |
| 185 |
const dateIsValid = isValidDate(newValueDate); |
| 186 |
const onBlurDateArg = dateIsValid ? new Date(newValueDate) : undefined; |
| 187 |
onBlur(event, value, onBlurDateArg); |
| 188 |
|
| 189 |
if (dateIsValid) { |
| 190 |
applyValidators(newValueDate); |
| 191 |
} |
| 192 |
|
| 193 |
if (!dateIsValid && !pristine) { |
| 194 |
setErrorText(invalidFormatText); |
| 195 |
} |
| 196 |
|
| 197 |
if (!dateIsValid && pristine && requiredDateOptions?.isRequired) { |
| 198 |
setErrorText(emptyDateText); |
| 199 |
} |
| 200 |
}; |
| 201 |
|
| 202 |
const onDateClick = (_event: React.MouseEvent<HTMLButtonElement, MouseEvent>, newValueDate: Date) => { |
| 203 |
const newValue = dateFormat(newValueDate); |
| 204 |
setValue(newValue); |
| 205 |
setValueDate(newValueDate); |
| 206 |
applyValidators(newValueDate); |
| 207 |
setPopoverOpen(false); |
| 208 |
onChange(null, newValue, new Date(newValueDate)); |
| 209 |
}; |
| 210 |
|
| 211 |
const onKeyPress = (ev: React.KeyboardEvent<HTMLInputElement>) => { |
| 212 |
if (ev.key === 'Enter' && value) { |
| 213 |
if (isValidDate(valueDate)) { |
| 214 |
applyValidators(valueDate); |
| 215 |
} else { |
| 216 |
setErrorText(invalidFormatText); |
| 217 |
} |
| 218 |
} |
| 219 |
}; |
| 220 |
|
| 221 |
useImperativeHandle<DatePickerRef, DatePickerRef>( |
| 222 |
ref, |
| 223 |
() => ({ |
| 224 |
setCalendarOpen: (isOpen: boolean) => setPopoverOpen(isOpen), |
| 225 |
toggleCalendar: (setOpen?: boolean) => { |
| 226 |
setPopoverOpen((prev) => (setOpen !== undefined ? setOpen : !prev)); |
| 227 |
}, |
| 228 |
isCalendarOpen: popoverOpen |
| 229 |
}), |
| 230 |
[setPopoverOpen, popoverOpen, selectOpen] |
| 231 |
); |
| 232 |
|
| 233 |
const createFocusSelectorString = (modifierClass: string) => |
| 234 |
`.${calendarMonthStyles.calendarMonthDatesCell}.${modifierClass} .${calendarMonthStyles.calendarMonthDate}`; |
| 235 |
const focusSelectorForSelectedDate = createFocusSelectorString(calendarMonthStyles.modifiers.selected); |
| 236 |
const focusSelectorForSelectedEndRangeDate = createFocusSelectorString( |
| 237 |
`${calendarMonthStyles.modifiers.selected}.${calendarMonthStyles.modifiers.endRange}` |
| 238 |
); |
| 239 |
const focusSelectorForUnselectedDate = createFocusSelectorString(calendarMonthStyles.modifiers.current); |
| 240 |
|
| 241 |
/** |
| 242 |
* Returns a CSS selector for a date button element which will receive initial focus after opening calendar popover. |
| 243 |
* In case of a range picker it returns the end date, if it is selected, start date otherwise. |
| 244 |
* In case of a normal datepicker it returns the selected date, if present, today otherwise. |
| 245 |
*/ |
| 246 |
const getElementSelectorToFocus = () => { |
| 247 |
if (isValidDate(valueDate) && isValidDate(rangeStart)) { |
| 248 |
return focusSelectorForSelectedEndRangeDate; |
| 249 |
} |
| 250 |
if (isValidDate(valueDate) || isValidDate(rangeStart)) { |
| 251 |
return focusSelectorForSelectedDate; |
| 252 |
} |
| 253 |
return focusSelectorForUnselectedDate; |
| 254 |
}; |
| 255 |
|
| 256 |
return ( |
| 257 |
<div className={css(styles.datePicker, className)} ref={datePickerWrapperRef} style={style} {...props}> |
| 258 |
<Popover |
| 259 |
elementToFocus={getElementSelectorToFocus()} |
| 260 |
position="bottom" |
| 261 |
bodyContent={ |
| 262 |
<CalendarMonth |
| 263 |
date={valueDate} |
| 264 |
onChange={onDateClick} |
| 265 |
locale={locale} |
| 266 |
// Use truthy values of strings |
| 267 |
validators={validators.map((validator) => (date: Date) => !validator(date))} |
| 268 |
onSelectToggle={(open) => setSelectOpen(open)} |
| 269 |
monthFormat={monthFormat} |
| 270 |
weekdayFormat={weekdayFormat} |
| 271 |
longWeekdayFormat={longWeekdayFormat} |
| 272 |
dayFormat={dayFormat} |
| 273 |
weekStart={weekStart} |
| 274 |
rangeStart={rangeStart} |
| 275 |
/> |
| 276 |
} |
| 277 |
showClose={false} |
| 278 |
isVisible={popoverOpen} |
| 279 |
shouldClose={(event, hideFunction) => { |
| 280 |
event = event as KeyboardEvent; |
| 281 |
if (event.key === KeyTypes.Escape && selectOpen) { |
| 282 |
event.stopPropagation(); |
| 283 |
setSelectOpen(false); |
| 284 |
return false; |
| 285 |
} |
| 286 |
// Let our button handle toggling |
| 287 |
if (buttonRef.current && buttonRef.current.contains(event.target as Node)) { |
| 288 |
return false; |
| 289 |
} |
| 290 |
|
| 291 |
if (popoverOpen) { |
| 292 |
event.stopPropagation(); |
| 293 |
setPopoverOpen(false); |
| 294 |
hideFunction(); |
| 295 |
// If datepicker is required and the popover is opened without the text input |
| 296 |
// first receiving focus, we want to validate that the text input is not blank upon |
| 297 |
// closing the popover |
| 298 |
requiredDateOptions?.isRequired && !value && setErrorText(emptyDateText); |
| 299 |
} |
| 300 |
if (event.key === KeyTypes.Escape && popoverOpen) { |
| 301 |
event.stopPropagation(); |
| 302 |
} |
| 303 |
return true; |
| 304 |
}} |
| 305 |
withFocusTrap |
| 306 |
hasNoPadding |
| 307 |
hasAutoWidth |
| 308 |
appendTo={appendTo} |
| 309 |
triggerRef={triggerRef} |
| 310 |
{...popoverProps} |
| 311 |
> |
| 312 |
<div className={styles.datePickerInput} ref={triggerRef}> |
| 313 |
<InputGroup> |
| 314 |
<InputGroupItem> |
| 315 |
<TextInput |
| 316 |
isDisabled={isDisabled} |
| 317 |
isRequired={requiredDateOptions?.isRequired} |
| 318 |
aria-label={ariaLabel} |
| 319 |
placeholder={placeholder} |
| 320 |
validated={errorText.trim() ? 'error' : 'default'} |
| 321 |
value={value} |
| 322 |
onChange={onTextInput} |
| 323 |
onBlur={onInputBlur} |
| 324 |
onFocus={() => setTextInputFocused(true)} |
| 325 |
onKeyPress={onKeyPress} |
| 326 |
{...inputProps} |
| 327 |
/> |
| 328 |
</InputGroupItem> |
| 329 |
<InputGroupItem> |
| 330 |
<Button |
| 331 |
ref={buttonRef} |
| 332 |
variant="control" |
| 333 |
aria-label={buttonAriaLabel} |
| 334 |
onClick={() => setPopoverOpen(!popoverOpen)} |
| 335 |
isDisabled={isDisabled} |
| 336 |
icon={<RhUiCalendarIcon />} |
| 337 |
aria-haspopup="dialog" |
| 338 |
/> |
| 339 |
</InputGroupItem> |
| 340 |
</InputGroup> |
| 341 |
</div> |
| 342 |
</Popover> |
| 343 |
{(errorText || helperText) && ( |
| 344 |
<div className={styles.datePickerHelperText}> |
| 345 |
{errorText ? ( |
| 346 |
<HelperText> |
| 347 |
<HelperTextItem variant="error">{errorText}</HelperTextItem> |
| 348 |
</HelperText> |
| 349 |
) : ( |
| 350 |
helperText |
| 351 |
)} |
| 352 |
</div> |
| 353 |
)} |
| 354 |
</div> |
| 355 |
); |
| 356 |
}; |
| 357 |
|
| 358 |
export const DatePicker = forwardRef<DatePickerRef, DatePickerProps>(DatePickerBase); |
| 359 |
DatePicker.displayName = 'DatePicker'; |