Debian Codegraph @

node/@patternfly/react-core/dist/esm/components/TimePicker/TimePicker.js

raw
1 import { __rest } from "tslib";
2 import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3 import { Component, createRef } from 'react';
4 import { css } from '@patternfly/react-styles';
5 import datePickerStyles from '@patternfly/react-styles/css/components/DatePicker/date-picker.mjs';
6 import menuStyles from '@patternfly/react-styles/css/components/Menu/menu.mjs';
7 import { Popper } from '../../helpers/Popper/Popper';
8 import { Menu, MenuContent, MenuList, MenuItem } from '../Menu';
9 import { InputGroup, InputGroupItem } from '../InputGroup';
10 import { TextInput } from '../TextInput';
11 import { KeyTypes } from '../../helpers/constants';
12 import { parseTime, validateTime, makeTimeOptions, amSuffix, pmSuffix, getHours, getMinutes, isWithinMinMax, getSeconds } from './TimePickerUtils';
13 import { HelperText, HelperTextItem } from '../HelperText';
14 import RhUiClockIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-clock-icon';
15 import cssDatePickerFormControlWidth from '@patternfly/react-tokens/dist/esm/c_date_picker__input_c_form_control_Width';
16 import { GenerateId } from '../../helpers';
17 class TimePicker extends Component {
18 constructor(props) {
19 super(props);
20 this.baseComponentRef = createRef();
21 this.toggleRef = createRef();
22 this.inputRef = createRef();
23 this.menuRef = createRef();
24 this.onDocClick = (event) => {
25 var _a, _b, _c, _d;
26 const clickedOnToggle = (_b = (_a = this.toggleRef) === null || _a === void 0 ? void 0 : _a.current) === null || _b === void 0 ? void 0 : _b.contains(event.target);
27 const clickedWithinMenu = (_d = (_c = this.menuRef) === null || _c === void 0 ? void 0 : _c.current) === null || _d === void 0 ? void 0 : _d.contains(event.target);
28 if (this.state.isTimeOptionsOpen && !(clickedOnToggle || clickedWithinMenu)) {
29 this.onToggle(false);
30 }
31 };
32 this.handleGlobalKeys = (event) => {
33 var _a, _b, _c, _d;
34 const { isTimeOptionsOpen, focusedIndex, scrollIndex } = this.state;
35 // keyboard pressed while focus on toggle
36 if ((_b = (_a = this.inputRef) === null || _a === void 0 ? void 0 : _a.current) === null || _b === void 0 ? void 0 : _b.contains(event.target)) {
37 if (!isTimeOptionsOpen && event.key !== KeyTypes.Tab && event.key !== KeyTypes.Escape) {
38 this.onToggle(true);
39 }
40 else if (isTimeOptionsOpen) {
41 if (event.key === KeyTypes.Escape || event.key === KeyTypes.Tab) {
42 this.onToggle(false);
43 }
44 else if (event.key === KeyTypes.Enter) {
45 if (focusedIndex !== null) {
46 this.focusSelection(focusedIndex);
47 event.stopPropagation();
48 }
49 else {
50 this.onToggle(false);
51 }
52 }
53 else if (event.key === KeyTypes.ArrowDown || event.key === KeyTypes.ArrowUp) {
54 this.focusSelection(scrollIndex);
55 this.updateFocusedIndex(0);
56 event.preventDefault();
57 }
58 }
59 // keyboard pressed while focus on menu item
60 }
61 else if ((_d = (_c = this.menuRef) === null || _c === void 0 ? void 0 : _c.current) === null || _d === void 0 ? void 0 : _d.contains(event.target)) {
62 if (event.key === KeyTypes.ArrowDown) {
63 this.updateFocusedIndex(1);
64 event.preventDefault();
65 }
66 else if (event.key === KeyTypes.ArrowUp) {
67 this.updateFocusedIndex(-1);
68 event.preventDefault();
69 }
70 else if (event.key === KeyTypes.Escape || event.key === KeyTypes.Tab) {
71 this.inputRef.current.focus();
72 this.onToggle(false);
73 }
74 }
75 };
76 this.updateFocusedIndex = (increment) => {
77 this.setState((prevState) => {
78 const maxIndex = this.getOptions().length - 1;
79 let nextIndex = prevState.focusedIndex !== null ? prevState.focusedIndex + increment : prevState.scrollIndex + increment;
80 if (nextIndex < 0) {
81 nextIndex = maxIndex;
82 }
83 else if (nextIndex > maxIndex) {
84 nextIndex = 0;
85 }
86 this.scrollToIndex(nextIndex);
87 return {
88 focusedIndex: nextIndex
89 };
90 });
91 };
92 // fixes issue where menuAppendTo="inline" results in the menu item that should be scrolled to being out of view; this will select the menu item that comes before the intended one, causing that before-item to be placed out of view instead
93 this.getIndexToScroll = (index) => {
94 if (this.props.menuAppendTo === 'inline') {
95 return index > 0 ? index - 1 : 0;
96 }
97 return index;
98 };
99 this.scrollToIndex = (index) => {
100 this.getOptions()[index].closest(`.${menuStyles.menuContent}`).scrollTop =
101 this.getOptions()[this.getIndexToScroll(index)].offsetTop;
102 };
103 this.focusSelection = (index) => {
104 var _a;
105 const indexToFocus = index !== -1 ? index : 0;
106 if ((_a = this.menuRef) === null || _a === void 0 ? void 0 : _a.current) {
107 this.getOptions()[indexToFocus].querySelector(`.${menuStyles.menuItem}`).focus();
108 }
109 };
110 this.scrollToSelection = (time) => {
111 const { delimiter, is24Hour } = this.props;
112 let splitTime = time.split(this.props.delimiter);
113 let focusedIndex = null;
114 // build out the rest of the time assuming hh:00 if it's a partial time
115 if (splitTime.length < 2) {
116 time = `${time}${delimiter}00`;
117 splitTime = time.split(delimiter);
118 // due to only the input including seconds when includeSeconds=true, we need to build a temporary time here without those seconds so that an exact or close match can be scrolled to within the menu (which does not include seconds in any of the options)
119 }
120 else if (splitTime.length > 2) {
121 time = parseTime(time, this.state.timeRegex, delimiter, !is24Hour, false);
122 splitTime = time.split(delimiter);
123 }
124 // for 12hr variant, autoscroll to pm if it's currently the afternoon, otherwise autoscroll to am
125 if (!is24Hour && splitTime.length > 1 && splitTime[1].length < 2) {
126 const minutes = splitTime[1].length === 0 ? '00' : splitTime[1] + '0';
127 time = `${splitTime[0]}${delimiter}${minutes}${new Date().getHours() > 11 ? pmSuffix : amSuffix}`;
128 }
129 else if (!is24Hour &&
130 splitTime.length > 1 &&
131 splitTime[1].length === 2 &&
132 !time.toUpperCase().includes(amSuffix.toUpperCase().trim()) &&
133 !time.toUpperCase().includes(pmSuffix.toUpperCase().trim())) {
134 time = `${time}${new Date().getHours() > 11 ? pmSuffix : amSuffix}`;
135 }
136 let scrollIndex = this.getOptions().findIndex((option) => option.textContent === time);
137 // if we found an exact match, scroll to match and return index of match for focus
138 if (scrollIndex !== -1) {
139 this.scrollToIndex(scrollIndex);
140 focusedIndex = scrollIndex;
141 }
142 else if (splitTime.length === 2) {
143 // no exact match, scroll to closest hour but don't return index for focus
144 let amPm = '';
145 if (!is24Hour) {
146 if (splitTime[1].toUpperCase().includes('P')) {
147 amPm = pmSuffix;
148 }
149 else if (splitTime[1].toUpperCase().includes('A')) {
150 amPm = amSuffix;
151 }
152 }
153 time = `${splitTime[0]}${delimiter}00${amPm}`;
154 scrollIndex = this.getOptions().findIndex((option) => option.textContent === time);
155 if (scrollIndex !== -1) {
156 this.scrollToIndex(scrollIndex);
157 }
158 }
159 this.setState({
160 focusedIndex,
161 scrollIndex
162 });
163 };
164 this.getRegExp = (includeSeconds = true) => {
165 const { is24Hour, delimiter } = this.props;
166 let baseRegex = `\\s*(\\d\\d?)${delimiter}([0-5]\\d)`;
167 if (includeSeconds) {
168 baseRegex += `${delimiter}?([0-5]\\d)?`;
169 }
170 return new RegExp(`^${baseRegex}${is24Hour ? '' : '\\s*([AaPp][Mm])?'}\\s*$`);
171 };
172 this.getOptions = () => {
173 var _a;
174 return (((_a = this.menuRef) === null || _a === void 0 ? void 0 : _a.current)
175 ? Array.from(this.menuRef.current.querySelectorAll(`.${menuStyles.menuListItem}`))
176 : []);
177 };
178 this.isValidFormat = (time) => {
179 if (this.props.validateTime) {
180 return this.props.validateTime(time);
181 }
182 const { delimiter, is24Hour, includeSeconds } = this.props;
183 return validateTime(time, this.getRegExp(includeSeconds), delimiter, !is24Hour);
184 };
185 this.isValidTime = (time) => {
186 const { delimiter, includeSeconds } = this.props;
187 const { minTimeState, maxTimeState } = this.state;
188 return isWithinMinMax(minTimeState, maxTimeState, time, delimiter, includeSeconds);
189 };
190 this.isValid = (time) => this.isValidFormat(time) && this.isValidTime(time);
191 this.onToggle = (isOpen) => {
192 // on close, parse and validate input
193 this.setState((prevState) => {
194 const { timeRegex, isInvalid, timeState } = prevState;
195 const { delimiter, is24Hour, includeSeconds, onChange } = this.props;
196 const time = parseTime(timeState, timeRegex, delimiter, !is24Hour, includeSeconds);
197 // Call onChange when Enter is pressed in input and timeoption does not exist in menu
198 if (onChange && !isOpen && time !== timeState) {
199 onChange(null, time, getHours(time, timeRegex), getMinutes(time, timeRegex), getSeconds(time, timeRegex), this.isValid(time));
200 }
201 return {
202 isTimeOptionsOpen: isOpen,
203 timeState: time,
204 isInvalid: isOpen ? isInvalid : !this.isValid(time)
205 };
206 });
207 this.props.setIsOpen(isOpen);
208 if (!isOpen) {
209 this.inputRef.current.focus();
210 }
211 };
212 this.onSelect = (e) => {
213 const { timeRegex, timeState } = this.state;
214 const { delimiter, is24Hour, includeSeconds, setIsOpen } = this.props;
215 const time = parseTime(e.target.textContent, timeRegex, delimiter, !is24Hour, includeSeconds);
216 if (time !== timeState) {
217 this.onInputChange(e, time);
218 }
219 this.inputRef.current.focus();
220 this.setState({
221 isTimeOptionsOpen: false,
222 isInvalid: false
223 });
224 setIsOpen(false);
225 };
226 this.onInputClick = (e) => {
227 if (!this.state.isTimeOptionsOpen) {
228 this.onToggle(true);
229 }
230 e.stopPropagation();
231 };
232 this.onInputChange = (event, newTime) => {
233 const { onChange } = this.props;
234 const { timeRegex } = this.state;
235 if (onChange) {
236 onChange(event, newTime, getHours(newTime, timeRegex), getMinutes(newTime, timeRegex), getSeconds(newTime, timeRegex), this.isValid(newTime));
237 }
238 this.scrollToSelection(newTime);
239 this.setState({
240 timeState: newTime
241 });
242 };
243 const { is24Hour, delimiter, time, includeSeconds, isOpen } = this.props;
244 let { minTime, maxTime } = this.props;
245 if (minTime === '') {
246 const minSeconds = includeSeconds ? `${delimiter}00` : '';
247 minTime = is24Hour ? `00${delimiter}00${minSeconds}` : `12${delimiter}00${minSeconds} AM`;
248 }
249 if (maxTime === '') {
250 const maxSeconds = includeSeconds ? `${delimiter}59` : '';
251 maxTime = is24Hour ? `23${delimiter}59${maxSeconds}` : `11${delimiter}59${maxSeconds} PM`;
252 }
253 const timeRegex = this.getRegExp();
254 this.state = {
255 isInvalid: false,
256 isTimeOptionsOpen: isOpen,
257 timeState: parseTime(time, timeRegex, delimiter, !is24Hour, includeSeconds),
258 focusedIndex: null,
259 scrollIndex: 0,
260 timeRegex,
261 minTimeState: parseTime(minTime, timeRegex, delimiter, !is24Hour, includeSeconds),
262 maxTimeState: parseTime(maxTime, timeRegex, delimiter, !is24Hour, includeSeconds)
263 };
264 }
265 componentDidMount() {
266 document.addEventListener('mousedown', this.onDocClick);
267 document.addEventListener('touchstart', this.onDocClick);
268 document.addEventListener('keydown', this.handleGlobalKeys);
269 this.setState({ isInvalid: !this.isValid(this.state.timeState) });
270 }
271 componentWillUnmount() {
272 document.removeEventListener('mousedown', this.onDocClick);
273 document.removeEventListener('touchstart', this.onDocClick);
274 document.removeEventListener('keydown', this.handleGlobalKeys);
275 }
276 componentDidUpdate(prevProps, prevState) {
277 const { timeState, isTimeOptionsOpen, isInvalid, timeRegex } = this.state;
278 const { time, is24Hour, delimiter, includeSeconds, isOpen, minTime, maxTime } = this.props;
279 if (prevProps.isOpen !== isOpen) {
280 this.onToggle(isOpen);
281 }
282 if (isTimeOptionsOpen && !prevState.isTimeOptionsOpen && timeState && !isInvalid) {
283 this.scrollToSelection(timeState);
284 }
285 if (delimiter !== prevProps.delimiter) {
286 this.setState({
287 timeRegex: this.getRegExp()
288 });
289 }
290 if (time !== '' && time !== prevProps.time) {
291 const parsedTime = parseTime(time, timeRegex, delimiter, !is24Hour, includeSeconds);
292 this.setState({
293 timeState: parsedTime,
294 isInvalid: !this.isValid(parsedTime)
295 });
296 }
297 if (minTime !== '' && minTime !== prevProps.minTime) {
298 this.setState({
299 minTimeState: parseTime(minTime, timeRegex, delimiter, !is24Hour, includeSeconds)
300 });
301 }
302 if (maxTime !== '' && maxTime !== prevProps.maxTime) {
303 this.setState({
304 maxTimeState: parseTime(maxTime, timeRegex, delimiter, !is24Hour, includeSeconds)
305 });
306 }
307 }
308 render() {
309 const _a = this.props, { 'aria-label': ariaLabel, isDisabled, className, placeholder, id, menuAppendTo, is24Hour, invalidFormatErrorMessage, invalidMinMaxErrorMessage, stepMinutes, width, delimiter, inputProps,
310 /* eslint-disable @typescript-eslint/no-unused-vars */
311 onChange,
312 /* eslint-disable @typescript-eslint/no-unused-vars */
313 setIsOpen,
314 /* eslint-disable @typescript-eslint/no-unused-vars */
315 isOpen, time, validateTime, minTime, maxTime, includeSeconds, zIndex } = _a, props = __rest(_a, ['aria-label', "isDisabled", "className", "placeholder", "id", "menuAppendTo", "is24Hour", "invalidFormatErrorMessage", "invalidMinMaxErrorMessage", "stepMinutes", "width", "delimiter", "inputProps", "onChange", "setIsOpen", "isOpen", "time", "validateTime", "minTime", "maxTime", "includeSeconds", "zIndex"]);
316 const { timeState, isTimeOptionsOpen, isInvalid, minTimeState, maxTimeState } = this.state;
317 const style = { [cssDatePickerFormControlWidth.name]: width };
318 const options = makeTimeOptions(stepMinutes, !is24Hour, delimiter, minTimeState, maxTimeState, includeSeconds);
319 const isValidFormat = this.isValidFormat(timeState);
320 return (_jsx(GenerateId, { prefix: "time-picker-", children: (generatedId) => {
321 const randomId = id || generatedId;
322 const getParentElement = () => {
323 if (this.baseComponentRef && this.baseComponentRef.current) {
324 return this.baseComponentRef.current.parentElement;
325 }
326 return null;
327 };
328 const menuContainer = (_jsx(Menu, { ref: this.menuRef, isScrollable: true, children: _jsx(MenuContent, { maxMenuHeight: "200px", children: _jsx(MenuList, { "aria-label": ariaLabel, children: options.map((option, index) => (_jsx(MenuItem, { onClick: this.onSelect, id: `${randomId}-option-${index}`, children: option }, option))) }) }) }));
329 const textInput = (_jsx(TextInput, Object.assign({ "aria-haspopup": "menu", id: `${randomId}-input`, "aria-label": ariaLabel, validated: isInvalid ? 'error' : 'default', placeholder: placeholder, value: timeState || '', type: "text", customIcon: _jsx(RhUiClockIcon, {}), onClick: this.onInputClick, onChange: this.onInputChange, autoComplete: "off", isDisabled: isDisabled, isExpanded: isTimeOptionsOpen, ref: this.inputRef }, inputProps)));
330 let calculatedAppendTo;
331 switch (menuAppendTo) {
332 case 'inline':
333 calculatedAppendTo = () => this.toggleRef.current;
334 break;
335 case 'parent':
336 calculatedAppendTo = getParentElement;
337 break;
338 default:
339 calculatedAppendTo = menuAppendTo;
340 }
341 return (_jsx("div", { ref: this.baseComponentRef, className: css(datePickerStyles.datePicker, className), children: _jsxs("div", Object.assign({ className: css(datePickerStyles.datePickerInput), style: style }, props, { children: [_jsx(InputGroup, { children: _jsx(InputGroupItem, { children: _jsx("div", { id: randomId, children: _jsx("div", { ref: this.toggleRef, style: { paddingLeft: '0' }, children: _jsx(Popper, { appendTo: calculatedAppendTo, trigger: textInput, triggerRef: this.toggleRef, popper: menuContainer, popperRef: this.menuRef, isVisible: isTimeOptionsOpen, zIndex: zIndex }) }) }) }) }), isInvalid && (_jsx("div", { className: css(datePickerStyles.datePickerHelperText), children: _jsx(HelperText, { children: _jsx(HelperTextItem, { variant: "error", children: !isValidFormat ? invalidFormatErrorMessage : invalidMinMaxErrorMessage }) }) }))] })) }));
342 } }));
343 }
344 }
345 TimePicker.displayName = 'TimePicker';
346 TimePicker.defaultProps = {
347 className: '',
348 isDisabled: false,
349 time: '',
350 is24Hour: false,
351 invalidFormatErrorMessage: 'Invalid time format',
352 invalidMinMaxErrorMessage: 'Invalid time entered',
353 placeholder: 'hh:mm',
354 delimiter: ':',
355 'aria-label': 'Time picker',
356 width: '150px',
357 menuAppendTo: 'inline',
358 stepMinutes: 30,
359 inputProps: {},
360 minTime: '',
361 maxTime: '',
362 isOpen: false,
363 setIsOpen: () => { },
364 zIndex: 9999
365 };
366 export { TimePicker };
367 //# sourceMappingURL=TimePicker.js.map