Debian Codegraph @

node/@patternfly/react-core/src/components/TimePicker/TimePicker.tsx

raw
1 import { Component, createRef } from 'react';
2 import { css } from '@patternfly/react-styles';
3 import datePickerStyles from '@patternfly/react-styles/css/components/DatePicker/date-picker';
4 import menuStyles from '@patternfly/react-styles/css/components/Menu/menu';
5 import { Popper } from '../../helpers/Popper/Popper';
6 import { Menu, MenuContent, MenuList, MenuItem } from '../Menu';
7 import { InputGroup, InputGroupItem } from '../InputGroup';
8 import { TextInput, TextInputProps } from '../TextInput';
9 import { KeyTypes } from '../../helpers/constants';
10 import {
11 parseTime,
12 validateTime,
13 makeTimeOptions,
14 amSuffix,
15 pmSuffix,
16 getHours,
17 getMinutes,
18 isWithinMinMax,
19 getSeconds
20 } from './TimePickerUtils';
21 import { HelperText, HelperTextItem } from '../HelperText';
22 import RhUiClockIcon from '@patternfly/react-icons/dist/esm/icons/rh-ui-clock-icon';
23 import cssDatePickerFormControlWidth from '@patternfly/react-tokens/dist/esm/c_date_picker__input_c_form_control_Width';
24 import { GenerateId } from '../../helpers';
25
26 export interface TimePickerProps extends Omit<
27 React.HTMLProps<HTMLDivElement>,
28 'onChange' | 'onFocus' | 'onBlur' | 'disabled' | 'ref'
29 > {
30 /** Additional classes added to the time picker. */
31 className?: string;
32 /** Accessible label for the time picker */
33 'aria-label'?: string;
34 /** Flag indicating the time picker is disabled */
35 isDisabled?: boolean;
36 /** String to display in the empty time picker field as a hint for the expected time format */
37 placeholder?: string;
38 /** Character to display between the hour and minute */
39 delimiter?: string;
40 /** A time string. The format could be an ISO 8601 formatted date string or in 'HH{delimiter}MM' format */
41 time?: string | Date;
42 /** Error message to display when the time is provided in an invalid format. */
43 invalidFormatErrorMessage?: string;
44 /** Error message to display when the time provided is not within the minTime/maxTime constraints */
45 invalidMinMaxErrorMessage?: string;
46 /** True if the time is 24 hour time. False if the time is 12 hour time */
47 is24Hour?: boolean;
48 /** Optional event handler called each time the value in the time picker input changes. */
49 onChange?: (
50 event: React.FormEvent<HTMLInputElement>,
51 time: string,
52 hour?: number,
53 minute?: number,
54 seconds?: number,
55 isValid?: boolean
56 ) => void;
57 /** Optional validator can be provided to override the internal time validator. */
58 validateTime?: (time: string) => boolean;
59 /** Id of the time picker */
60 id?: string;
61 /** Width of the time picker. */
62 width?: string;
63 /** The container to append the menu to. Defaults to 'inline'.
64 * If your menu is being cut off you can append it to an element higher up the DOM tree.
65 * Some examples:
66 * menuAppendTo="parent"
67 * menuAppendTo={() => document.body}
68 * menuAppendTo={document.getElementById('target')}
69 */
70 menuAppendTo?: HTMLElement | (() => HTMLElement) | 'inline' | 'parent';
71 /** Size of step between time options in minutes.*/
72 stepMinutes?: number;
73 /** Additional props for input field */
74 inputProps?: TextInputProps;
75 /** A time string indicating the minimum value allowed. The format could be an ISO 8601 formatted date string or in 'HH{delimiter}MM' format */
76 minTime?: string | Date;
77 /** A time string indicating the maximum value allowed. The format could be an ISO 8601 formatted date string or in 'HH{delimiter}MM' format */
78 maxTime?: string | Date;
79 /** Includes number of seconds with the chosen time and allows users to manually edit the seconds value. */
80 includeSeconds?: boolean;
81 /** Flag to control the opened state of the time picker menu */
82 isOpen?: boolean;
83 /** Handler invoked each time the open state of time picker updates */
84 setIsOpen?: (isOpen?: boolean) => void;
85 /** z-index of the time picker */
86 zIndex?: number;
87 }
88
89 interface TimePickerState {
90 isInvalid: boolean;
91 isTimeOptionsOpen: boolean;
92 timeState: string;
93 focusedIndex: number;
94 scrollIndex: number;
95 timeRegex: RegExp;
96 minTimeState: string;
97 maxTimeState: string;
98 }
99
100 class TimePicker extends Component<TimePickerProps, TimePickerState> {
101 static displayName = 'TimePicker';
102 private baseComponentRef = createRef<any>();
103 private toggleRef = createRef<HTMLDivElement>();
104 private inputRef = createRef<HTMLInputElement>();
105 private menuRef = createRef<HTMLDivElement>();
106
107 static defaultProps = {
108 className: '',
109 isDisabled: false,
110 time: '',
111 is24Hour: false,
112 invalidFormatErrorMessage: 'Invalid time format',
113 invalidMinMaxErrorMessage: 'Invalid time entered',
114 placeholder: 'hh:mm',
115 delimiter: ':',
116 'aria-label': 'Time picker',
117 width: '150px',
118 menuAppendTo: 'inline',
119 stepMinutes: 30,
120 inputProps: {},
121 minTime: '',
122 maxTime: '',
123 isOpen: false,
124 setIsOpen: () => {},
125 zIndex: 9999
126 };
127
128 constructor(props: TimePickerProps) {
129 super(props);
130 const { is24Hour, delimiter, time, includeSeconds, isOpen } = this.props;
131 let { minTime, maxTime } = this.props;
132 if (minTime === '') {
133 const minSeconds = includeSeconds ? `${delimiter}00` : '';
134 minTime = is24Hour ? `00${delimiter}00${minSeconds}` : `12${delimiter}00${minSeconds} AM`;
135 }
136 if (maxTime === '') {
137 const maxSeconds = includeSeconds ? `${delimiter}59` : '';
138 maxTime = is24Hour ? `23${delimiter}59${maxSeconds}` : `11${delimiter}59${maxSeconds} PM`;
139 }
140 const timeRegex = this.getRegExp();
141 this.state = {
142 isInvalid: false,
143 isTimeOptionsOpen: isOpen,
144 timeState: parseTime(time, timeRegex, delimiter, !is24Hour, includeSeconds),
145 focusedIndex: null,
146 scrollIndex: 0,
147 timeRegex,
148 minTimeState: parseTime(minTime, timeRegex, delimiter, !is24Hour, includeSeconds),
149 maxTimeState: parseTime(maxTime, timeRegex, delimiter, !is24Hour, includeSeconds)
150 };
151 }
152
153 componentDidMount() {
154 document.addEventListener('mousedown', this.onDocClick);
155 document.addEventListener('touchstart', this.onDocClick);
156 document.addEventListener('keydown', this.handleGlobalKeys);
157
158 this.setState({ isInvalid: !this.isValid(this.state.timeState) });
159 }
160
161 componentWillUnmount() {
162 document.removeEventListener('mousedown', this.onDocClick);
163 document.removeEventListener('touchstart', this.onDocClick);
164 document.removeEventListener('keydown', this.handleGlobalKeys);
165 }
166
167 onDocClick = (event: MouseEvent | TouchEvent) => {
168 const clickedOnToggle = this.toggleRef?.current?.contains(event.target as Node);
169 const clickedWithinMenu = this.menuRef?.current?.contains(event.target as Node);
170 if (this.state.isTimeOptionsOpen && !(clickedOnToggle || clickedWithinMenu)) {
171 this.onToggle(false);
172 }
173 };
174
175 handleGlobalKeys = (event: KeyboardEvent) => {
176 const { isTimeOptionsOpen, focusedIndex, scrollIndex } = this.state;
177 // keyboard pressed while focus on toggle
178 if (this.inputRef?.current?.contains(event.target as Node)) {
179 if (!isTimeOptionsOpen && event.key !== KeyTypes.Tab && event.key !== KeyTypes.Escape) {
180 this.onToggle(true);
181 } else if (isTimeOptionsOpen) {
182 if (event.key === KeyTypes.Escape || event.key === KeyTypes.Tab) {
183 this.onToggle(false);
184 } else if (event.key === KeyTypes.Enter) {
185 if (focusedIndex !== null) {
186 this.focusSelection(focusedIndex);
187 event.stopPropagation();
188 } else {
189 this.onToggle(false);
190 }
191 } else if (event.key === KeyTypes.ArrowDown || event.key === KeyTypes.ArrowUp) {
192 this.focusSelection(scrollIndex);
193 this.updateFocusedIndex(0);
194 event.preventDefault();
195 }
196 }
197 // keyboard pressed while focus on menu item
198 } else if (this.menuRef?.current?.contains(event.target as Node)) {
199 if (event.key === KeyTypes.ArrowDown) {
200 this.updateFocusedIndex(1);
201 event.preventDefault();
202 } else if (event.key === KeyTypes.ArrowUp) {
203 this.updateFocusedIndex(-1);
204 event.preventDefault();
205 } else if (event.key === KeyTypes.Escape || event.key === KeyTypes.Tab) {
206 this.inputRef.current.focus();
207 this.onToggle(false);
208 }
209 }
210 };
211
212 componentDidUpdate(prevProps: TimePickerProps, prevState: TimePickerState) {
213 const { timeState, isTimeOptionsOpen, isInvalid, timeRegex } = this.state;
214 const { time, is24Hour, delimiter, includeSeconds, isOpen, minTime, maxTime } = this.props;
215 if (prevProps.isOpen !== isOpen) {
216 this.onToggle(isOpen);
217 }
218
219 if (isTimeOptionsOpen && !prevState.isTimeOptionsOpen && timeState && !isInvalid) {
220 this.scrollToSelection(timeState);
221 }
222 if (delimiter !== prevProps.delimiter) {
223 this.setState({
224 timeRegex: this.getRegExp()
225 });
226 }
227 if (time !== '' && time !== prevProps.time) {
228 const parsedTime = parseTime(time, timeRegex, delimiter, !is24Hour, includeSeconds);
229
230 this.setState({
231 timeState: parsedTime,
232 isInvalid: !this.isValid(parsedTime)
233 });
234 }
235 if (minTime !== '' && minTime !== prevProps.minTime) {
236 this.setState({
237 minTimeState: parseTime(minTime, timeRegex, delimiter, !is24Hour, includeSeconds)
238 });
239 }
240
241 if (maxTime !== '' && maxTime !== prevProps.maxTime) {
242 this.setState({
243 maxTimeState: parseTime(maxTime, timeRegex, delimiter, !is24Hour, includeSeconds)
244 });
245 }
246 }
247
248 updateFocusedIndex = (increment: number) => {
249 this.setState((prevState) => {
250 const maxIndex = this.getOptions().length - 1;
251 let nextIndex =
252 prevState.focusedIndex !== null ? prevState.focusedIndex + increment : prevState.scrollIndex + increment;
253 if (nextIndex < 0) {
254 nextIndex = maxIndex;
255 } else if (nextIndex > maxIndex) {
256 nextIndex = 0;
257 }
258 this.scrollToIndex(nextIndex);
259 return {
260 focusedIndex: nextIndex
261 };
262 });
263 };
264
265 // 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
266 getIndexToScroll = (index: number) => {
267 if (this.props.menuAppendTo === 'inline') {
268 return index > 0 ? index - 1 : 0;
269 }
270 return index;
271 };
272
273 scrollToIndex = (index: number) => {
274 this.getOptions()[index].closest(`.${menuStyles.menuContent}`).scrollTop =
275 this.getOptions()[this.getIndexToScroll(index)].offsetTop;
276 };
277
278 focusSelection = (index: number) => {
279 const indexToFocus = index !== -1 ? index : 0;
280
281 if (this.menuRef?.current) {
282 (this.getOptions()[indexToFocus].querySelector(`.${menuStyles.menuItem}`) as HTMLElement).focus();
283 }
284 };
285
286 scrollToSelection = (time: string) => {
287 const { delimiter, is24Hour } = this.props;
288 let splitTime = time.split(this.props.delimiter);
289 let focusedIndex = null;
290
291 // build out the rest of the time assuming hh:00 if it's a partial time
292 if (splitTime.length < 2) {
293 time = `${time}${delimiter}00`;
294 splitTime = time.split(delimiter);
295 // 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)
296 } else if (splitTime.length > 2) {
297 time = parseTime(time, this.state.timeRegex, delimiter, !is24Hour, false);
298 splitTime = time.split(delimiter);
299 }
300
301 // for 12hr variant, autoscroll to pm if it's currently the afternoon, otherwise autoscroll to am
302 if (!is24Hour && splitTime.length > 1 && splitTime[1].length < 2) {
303 const minutes = splitTime[1].length === 0 ? '00' : splitTime[1] + '0';
304 time = `${splitTime[0]}${delimiter}${minutes}${new Date().getHours() > 11 ? pmSuffix : amSuffix}`;
305 } else if (
306 !is24Hour &&
307 splitTime.length > 1 &&
308 splitTime[1].length === 2 &&
309 !time.toUpperCase().includes(amSuffix.toUpperCase().trim()) &&
310 !time.toUpperCase().includes(pmSuffix.toUpperCase().trim())
311 ) {
312 time = `${time}${new Date().getHours() > 11 ? pmSuffix : amSuffix}`;
313 }
314 let scrollIndex = this.getOptions().findIndex((option) => option.textContent === time);
315
316 // if we found an exact match, scroll to match and return index of match for focus
317 if (scrollIndex !== -1) {
318 this.scrollToIndex(scrollIndex);
319 focusedIndex = scrollIndex;
320 } else if (splitTime.length === 2) {
321 // no exact match, scroll to closest hour but don't return index for focus
322 let amPm = '';
323 if (!is24Hour) {
324 if (splitTime[1].toUpperCase().includes('P')) {
325 amPm = pmSuffix;
326 } else if (splitTime[1].toUpperCase().includes('A')) {
327 amPm = amSuffix;
328 }
329 }
330 time = `${splitTime[0]}${delimiter}00${amPm}`;
331 scrollIndex = this.getOptions().findIndex((option) => option.textContent === time);
332 if (scrollIndex !== -1) {
333 this.scrollToIndex(scrollIndex);
334 }
335 }
336 this.setState({
337 focusedIndex,
338 scrollIndex
339 });
340 };
341
342 getRegExp = (includeSeconds: boolean = true) => {
343 const { is24Hour, delimiter } = this.props;
344 let baseRegex = `\\s*(\\d\\d?)${delimiter}([0-5]\\d)`;
345
346 if (includeSeconds) {
347 baseRegex += `${delimiter}?([0-5]\\d)?`;
348 }
349
350 return new RegExp(`^${baseRegex}${is24Hour ? '' : '\\s*([AaPp][Mm])?'}\\s*$`);
351 };
352
353 getOptions = () =>
354 (this.menuRef?.current
355 ? Array.from(this.menuRef.current.querySelectorAll(`.${menuStyles.menuListItem}`))
356 : []) as HTMLElement[];
357
358 isValidFormat = (time: string) => {
359 if (this.props.validateTime) {
360 return this.props.validateTime(time);
361 }
362
363 const { delimiter, is24Hour, includeSeconds } = this.props;
364 return validateTime(time, this.getRegExp(includeSeconds), delimiter, !is24Hour);
365 };
366
367 isValidTime = (time: string) => {
368 const { delimiter, includeSeconds } = this.props;
369 const { minTimeState, maxTimeState } = this.state;
370
371 return isWithinMinMax(minTimeState, maxTimeState, time, delimiter, includeSeconds);
372 };
373
374 isValid = (time: string) => this.isValidFormat(time) && this.isValidTime(time);
375
376 onToggle = (isOpen: boolean) => {
377 // on close, parse and validate input
378 this.setState((prevState) => {
379 const { timeRegex, isInvalid, timeState } = prevState;
380 const { delimiter, is24Hour, includeSeconds, onChange } = this.props;
381 const time = parseTime(timeState, timeRegex, delimiter, !is24Hour, includeSeconds);
382
383 // Call onChange when Enter is pressed in input and timeoption does not exist in menu
384 if (onChange && !isOpen && time !== timeState) {
385 onChange(
386 null,
387 time,
388 getHours(time, timeRegex),
389 getMinutes(time, timeRegex),
390 getSeconds(time, timeRegex),
391 this.isValid(time)
392 );
393 }
394
395 return {
396 isTimeOptionsOpen: isOpen,
397 timeState: time,
398 isInvalid: isOpen ? isInvalid : !this.isValid(time)
399 };
400 });
401 this.props.setIsOpen(isOpen);
402 if (!isOpen) {
403 this.inputRef.current.focus();
404 }
405 };
406
407 onSelect = (e: any) => {
408 const { timeRegex, timeState } = this.state;
409 const { delimiter, is24Hour, includeSeconds, setIsOpen } = this.props;
410 const time = parseTime(e.target.textContent, timeRegex, delimiter, !is24Hour, includeSeconds);
411 if (time !== timeState) {
412 this.onInputChange(e, time);
413 }
414
415 this.inputRef.current.focus();
416 this.setState({
417 isTimeOptionsOpen: false,
418 isInvalid: false
419 });
420 setIsOpen(false);
421 };
422
423 onInputClick = (e: any) => {
424 if (!this.state.isTimeOptionsOpen) {
425 this.onToggle(true);
426 }
427 e.stopPropagation();
428 };
429
430 onInputChange = (event: React.FormEvent<HTMLInputElement>, newTime: string) => {
431 const { onChange } = this.props;
432 const { timeRegex } = this.state;
433 if (onChange) {
434 onChange(
435 event,
436 newTime,
437 getHours(newTime, timeRegex),
438 getMinutes(newTime, timeRegex),
439 getSeconds(newTime, timeRegex),
440 this.isValid(newTime)
441 );
442 }
443 this.scrollToSelection(newTime);
444 this.setState({
445 timeState: newTime
446 });
447 };
448
449 render() {
450 const {
451 'aria-label': ariaLabel,
452 isDisabled,
453 className,
454 placeholder,
455 id,
456 menuAppendTo,
457 is24Hour,
458 invalidFormatErrorMessage,
459 invalidMinMaxErrorMessage,
460 stepMinutes,
461 width,
462 delimiter,
463 inputProps,
464 /* eslint-disable @typescript-eslint/no-unused-vars */
465 onChange,
466 /* eslint-disable @typescript-eslint/no-unused-vars */
467 setIsOpen,
468 /* eslint-disable @typescript-eslint/no-unused-vars */
469 isOpen,
470 time,
471 validateTime,
472 minTime,
473 maxTime,
474 includeSeconds,
475 zIndex,
476 ...props
477 } = this.props;
478 const { timeState, isTimeOptionsOpen, isInvalid, minTimeState, maxTimeState } = this.state;
479 const style = { [cssDatePickerFormControlWidth.name]: width } as React.CSSProperties;
480 const options = makeTimeOptions(stepMinutes, !is24Hour, delimiter, minTimeState, maxTimeState, includeSeconds);
481 const isValidFormat = this.isValidFormat(timeState);
482
483 return (
484 <GenerateId prefix="time-picker-">
485 {(generatedId) => {
486 const randomId = id || generatedId;
487
488 const getParentElement = () => {
489 if (this.baseComponentRef && this.baseComponentRef.current) {
490 return this.baseComponentRef.current.parentElement;
491 }
492 return null;
493 };
494
495 const menuContainer = (
496 <Menu ref={this.menuRef} isScrollable>
497 <MenuContent maxMenuHeight="200px">
498 <MenuList aria-label={ariaLabel}>
499 {options.map((option, index) => (
500 <MenuItem onClick={this.onSelect} key={option} id={`${randomId}-option-${index}`}>
501 {option}
502 </MenuItem>
503 ))}
504 </MenuList>
505 </MenuContent>
506 </Menu>
507 );
508
509 const textInput = (
510 <TextInput
511 aria-haspopup="menu"
512 id={`${randomId}-input`}
513 aria-label={ariaLabel}
514 validated={isInvalid ? 'error' : 'default'}
515 placeholder={placeholder}
516 value={timeState || ''}
517 type="text"
518 customIcon={<RhUiClockIcon />}
519 onClick={this.onInputClick}
520 onChange={this.onInputChange}
521 autoComplete="off"
522 isDisabled={isDisabled}
523 isExpanded={isTimeOptionsOpen}
524 ref={this.inputRef}
525 {...inputProps}
526 />
527 );
528
529 let calculatedAppendTo;
530 switch (menuAppendTo) {
531 case 'inline':
532 calculatedAppendTo = () => this.toggleRef.current;
533 break;
534 case 'parent':
535 calculatedAppendTo = getParentElement;
536 break;
537 default:
538 calculatedAppendTo = menuAppendTo as HTMLElement;
539 }
540
541 return (
542 <div ref={this.baseComponentRef} className={css(datePickerStyles.datePicker, className)}>
543 <div className={css(datePickerStyles.datePickerInput)} style={style} {...props}>
544 <InputGroup>
545 <InputGroupItem>
546 <div id={randomId}>
547 <div ref={this.toggleRef} style={{ paddingLeft: '0' }}>
548 <Popper
549 appendTo={calculatedAppendTo}
550 trigger={textInput}
551 triggerRef={this.toggleRef}
552 popper={menuContainer}
553 popperRef={this.menuRef}
554 isVisible={isTimeOptionsOpen}
555 zIndex={zIndex}
556 />
557 </div>
558 </div>
559 </InputGroupItem>
560 </InputGroup>
561 {isInvalid && (
562 <div className={css(datePickerStyles.datePickerHelperText)}>
563 <HelperText>
564 <HelperTextItem variant="error">
565 {!isValidFormat ? invalidFormatErrorMessage : invalidMinMaxErrorMessage}
566 </HelperTextItem>
567 </HelperText>
568 </div>
569 )}
570 </div>
571 </div>
572 );
573 }}
574 </GenerateId>
575 );
576 }
577 }
578
579 export { TimePicker };