Debian Codegraph @

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

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