| 1 |
import { __rest } from "tslib"; |
| 2 |
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; |
| 3 |
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'; |
| 4 |
import { css } from '@patternfly/react-styles'; |
| 5 |
import styles from '@patternfly/react-styles/css/components/DatePicker/date-picker.mjs'; |
| 6 |
import calendarMonthStyles from '@patternfly/react-styles/css/components/CalendarMonth/calendar-month.mjs'; |
| 7 |
import { TextInput } from '../TextInput/TextInput'; |
| 8 |
import { Button } from '../Button'; |
| 9 |
import { Popover } from '../Popover/Popover'; |
| 10 |
import { InputGroup, InputGroupItem } from '../InputGroup'; |
| 11 |
import RhUiCalendarIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-calendar-icon'; |
| 12 |
import { CalendarMonth } from '../CalendarMonth'; |
| 13 |
import { KeyTypes } from '../../helpers'; |
| 14 |
import { isValidDate } from '../../helpers/datetimeUtils'; |
| 15 |
import { HelperText, HelperTextItem } from '../HelperText'; |
| 16 |
import cssFormControlWidthChars from '@patternfly/react-tokens/dist/esm/c_date_picker__input_c_form_control_width_chars'; |
| 17 |
export const yyyyMMddFormat = (date) => `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date |
| 18 |
.getDate() |
| 19 |
.toString() |
| 20 |
.padStart(2, '0')}`; |
| 21 |
const DatePickerBase = (_a, ref) => { |
| 22 |
var { className, locale = undefined, dateFormat = yyyyMMddFormat, dateParse = (val) => (val.split('-').length === 3 ? new Date(`${val}T00:00:00`) : new Date(undefined)), isDisabled = false, placeholder = 'YYYY-MM-DD', value: valueProp = '', 'aria-label': ariaLabel = 'Date picker', buttonAriaLabel = 'Toggle date picker', onChange = () => undefined, onBlur = () => undefined, invalidFormatText = 'Invalid date', requiredDateOptions, helperText, appendTo = 'inline', popoverProps, monthFormat, weekdayFormat, longWeekdayFormat, dayFormat, weekStart, validators = [], rangeStart, style: styleProps = {}, inputProps = {} } = _a, props = __rest(_a, ["className", "locale", "dateFormat", "dateParse", "isDisabled", "placeholder", "value", 'aria-label', "buttonAriaLabel", "onChange", "onBlur", "invalidFormatText", "requiredDateOptions", "helperText", "appendTo", "popoverProps", "monthFormat", "weekdayFormat", "longWeekdayFormat", "dayFormat", "weekStart", "validators", "rangeStart", "style", "inputProps"]); |
| 23 |
const [value, setValue] = useState(valueProp); |
| 24 |
const [valueDate, setValueDate] = useState(dateParse(value)); |
| 25 |
const [errorText, setErrorText] = useState(''); |
| 26 |
const [popoverOpen, setPopoverOpen] = useState(false); |
| 27 |
const [selectOpen, setSelectOpen] = useState(false); |
| 28 |
const [pristine, setPristine] = useState(true); |
| 29 |
const [textInputFocused, setTextInputFocused] = useState(false); |
| 30 |
const widthChars = useMemo(() => Math.max(dateFormat(new Date()).length, placeholder.length), [dateFormat]); |
| 31 |
const style = Object.assign({ [cssFormControlWidthChars.name]: widthChars }, styleProps); |
| 32 |
const buttonRef = useRef(undefined); |
| 33 |
const datePickerWrapperRef = useRef(undefined); |
| 34 |
const triggerRef = useRef(undefined); |
| 35 |
const dateIsRequired = (requiredDateOptions === null || requiredDateOptions === void 0 ? void 0 : requiredDateOptions.isRequired) || false; |
| 36 |
const emptyDateText = (requiredDateOptions === null || requiredDateOptions === void 0 ? void 0 : requiredDateOptions.emptyDateText) || 'Date cannot be blank'; |
| 37 |
useEffect(() => { |
| 38 |
setValue(valueProp); |
| 39 |
setValueDate(dateParse(valueProp)); |
| 40 |
}, [valueProp]); |
| 41 |
useEffect(() => { |
| 42 |
if (isValidDate(valueDate)) { |
| 43 |
applyValidators(valueDate); |
| 44 |
} |
| 45 |
}, [validators]); |
| 46 |
useEffect(() => { |
| 47 |
setPristine(!value); |
| 48 |
const newValueDate = dateParse(value); |
| 49 |
if (errorText && isValidDate(newValueDate)) { |
| 50 |
applyValidators(newValueDate); |
| 51 |
} |
| 52 |
if (value === '' && !pristine && !textInputFocused) { |
| 53 |
dateIsRequired ? setErrorText(emptyDateText) : setErrorText(''); |
| 54 |
} |
| 55 |
}, [value]); |
| 56 |
const applyValidators = (date) => { |
| 57 |
const validatorResults = validators.map((validator) => validator(date)); |
| 58 |
const validatorsToApply = validatorResults.filter((validator) => validator !== ''); |
| 59 |
setErrorText(validatorsToApply.join('\n') || ''); |
| 60 |
}; |
| 61 |
const onTextInput = (event, value) => { |
| 62 |
setValue(value); |
| 63 |
setErrorText(''); |
| 64 |
const newValueDate = dateParse(value); |
| 65 |
setValueDate(newValueDate); |
| 66 |
if (isValidDate(newValueDate)) { |
| 67 |
onChange(event, value, new Date(newValueDate)); |
| 68 |
} |
| 69 |
else { |
| 70 |
onChange(event, value); |
| 71 |
} |
| 72 |
}; |
| 73 |
const onInputBlur = (event) => { |
| 74 |
setTextInputFocused(false); |
| 75 |
const newValueDate = dateParse(value); |
| 76 |
const dateIsValid = isValidDate(newValueDate); |
| 77 |
const onBlurDateArg = dateIsValid ? new Date(newValueDate) : undefined; |
| 78 |
onBlur(event, value, onBlurDateArg); |
| 79 |
if (dateIsValid) { |
| 80 |
applyValidators(newValueDate); |
| 81 |
} |
| 82 |
if (!dateIsValid && !pristine) { |
| 83 |
setErrorText(invalidFormatText); |
| 84 |
} |
| 85 |
if (!dateIsValid && pristine && (requiredDateOptions === null || requiredDateOptions === void 0 ? void 0 : requiredDateOptions.isRequired)) { |
| 86 |
setErrorText(emptyDateText); |
| 87 |
} |
| 88 |
}; |
| 89 |
const onDateClick = (_event, newValueDate) => { |
| 90 |
const newValue = dateFormat(newValueDate); |
| 91 |
setValue(newValue); |
| 92 |
setValueDate(newValueDate); |
| 93 |
applyValidators(newValueDate); |
| 94 |
setPopoverOpen(false); |
| 95 |
onChange(null, newValue, new Date(newValueDate)); |
| 96 |
}; |
| 97 |
const onKeyPress = (ev) => { |
| 98 |
if (ev.key === 'Enter' && value) { |
| 99 |
if (isValidDate(valueDate)) { |
| 100 |
applyValidators(valueDate); |
| 101 |
} |
| 102 |
else { |
| 103 |
setErrorText(invalidFormatText); |
| 104 |
} |
| 105 |
} |
| 106 |
}; |
| 107 |
useImperativeHandle(ref, () => ({ |
| 108 |
setCalendarOpen: (isOpen) => setPopoverOpen(isOpen), |
| 109 |
toggleCalendar: (setOpen) => { |
| 110 |
setPopoverOpen((prev) => (setOpen !== undefined ? setOpen : !prev)); |
| 111 |
}, |
| 112 |
isCalendarOpen: popoverOpen |
| 113 |
}), [setPopoverOpen, popoverOpen, selectOpen]); |
| 114 |
const createFocusSelectorString = (modifierClass) => `.${calendarMonthStyles.calendarMonthDatesCell}.${modifierClass} .${calendarMonthStyles.calendarMonthDate}`; |
| 115 |
const focusSelectorForSelectedDate = createFocusSelectorString(calendarMonthStyles.modifiers.selected); |
| 116 |
const focusSelectorForSelectedEndRangeDate = createFocusSelectorString(`${calendarMonthStyles.modifiers.selected}.${calendarMonthStyles.modifiers.endRange}`); |
| 117 |
const focusSelectorForUnselectedDate = createFocusSelectorString(calendarMonthStyles.modifiers.current); |
| 118 |
/** |
| 119 |
* Returns a CSS selector for a date button element which will receive initial focus after opening calendar popover. |
| 120 |
* In case of a range picker it returns the end date, if it is selected, start date otherwise. |
| 121 |
* In case of a normal datepicker it returns the selected date, if present, today otherwise. |
| 122 |
*/ |
| 123 |
const getElementSelectorToFocus = () => { |
| 124 |
if (isValidDate(valueDate) && isValidDate(rangeStart)) { |
| 125 |
return focusSelectorForSelectedEndRangeDate; |
| 126 |
} |
| 127 |
if (isValidDate(valueDate) || isValidDate(rangeStart)) { |
| 128 |
return focusSelectorForSelectedDate; |
| 129 |
} |
| 130 |
return focusSelectorForUnselectedDate; |
| 131 |
}; |
| 132 |
return (_jsxs("div", Object.assign({ className: css(styles.datePicker, className), ref: datePickerWrapperRef, style: style }, props, { children: [_jsx(Popover, Object.assign({ elementToFocus: getElementSelectorToFocus(), position: "bottom", bodyContent: _jsx(CalendarMonth, { date: valueDate, onChange: onDateClick, locale: locale, |
| 133 |
// Use truthy values of strings |
| 134 |
validators: validators.map((validator) => (date) => !validator(date)), onSelectToggle: (open) => setSelectOpen(open), monthFormat: monthFormat, weekdayFormat: weekdayFormat, longWeekdayFormat: longWeekdayFormat, dayFormat: dayFormat, weekStart: weekStart, rangeStart: rangeStart }), showClose: false, isVisible: popoverOpen, shouldClose: (event, hideFunction) => { |
| 135 |
event = event; |
| 136 |
if (event.key === KeyTypes.Escape && selectOpen) { |
| 137 |
event.stopPropagation(); |
| 138 |
setSelectOpen(false); |
| 139 |
return false; |
| 140 |
} |
| 141 |
// Let our button handle toggling |
| 142 |
if (buttonRef.current && buttonRef.current.contains(event.target)) { |
| 143 |
return false; |
| 144 |
} |
| 145 |
if (popoverOpen) { |
| 146 |
event.stopPropagation(); |
| 147 |
setPopoverOpen(false); |
| 148 |
hideFunction(); |
| 149 |
// If datepicker is required and the popover is opened without the text input |
| 150 |
// first receiving focus, we want to validate that the text input is not blank upon |
| 151 |
// closing the popover |
| 152 |
(requiredDateOptions === null || requiredDateOptions === void 0 ? void 0 : requiredDateOptions.isRequired) && !value && setErrorText(emptyDateText); |
| 153 |
} |
| 154 |
if (event.key === KeyTypes.Escape && popoverOpen) { |
| 155 |
event.stopPropagation(); |
| 156 |
} |
| 157 |
return true; |
| 158 |
}, withFocusTrap: true, hasNoPadding: true, hasAutoWidth: true, appendTo: appendTo, triggerRef: triggerRef }, popoverProps, { children: _jsx("div", { className: styles.datePickerInput, ref: triggerRef, children: _jsxs(InputGroup, { children: [_jsx(InputGroupItem, { children: _jsx(TextInput, Object.assign({ isDisabled: isDisabled, isRequired: requiredDateOptions === null || requiredDateOptions === void 0 ? void 0 : requiredDateOptions.isRequired, "aria-label": ariaLabel, placeholder: placeholder, validated: errorText.trim() ? 'error' : 'default', value: value, onChange: onTextInput, onBlur: onInputBlur, onFocus: () => setTextInputFocused(true), onKeyPress: onKeyPress }, inputProps)) }), _jsx(InputGroupItem, { children: _jsx(Button, { ref: buttonRef, variant: "control", "aria-label": buttonAriaLabel, onClick: () => setPopoverOpen(!popoverOpen), isDisabled: isDisabled, icon: _jsx(RhUiCalendarIcon, {}), "aria-haspopup": "dialog" }) })] }) }) })), (errorText || helperText) && (_jsx("div", { className: styles.datePickerHelperText, children: errorText ? (_jsx(HelperText, { children: _jsx(HelperTextItem, { variant: "error", children: errorText }) })) : (helperText) }))] }))); |
| 159 |
}; |
| 160 |
export const DatePicker = forwardRef(DatePickerBase); |
| 161 |
DatePicker.displayName = 'DatePicker'; |
| 162 |
//# sourceMappingURL=DatePicker.js.map |