-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDateInput.js
More file actions
450 lines (408 loc) · 13.9 KB
/
DateInput.js
File metadata and controls
450 lines (408 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
import addDays from 'date-fns/add_days';
import addMonths from 'date-fns/add_months';
import addWeeks from 'date-fns/add_weeks';
import addYears from 'date-fns/add_years';
import format from 'date-fns/format';
import isSameDay from 'date-fns/is_same_day';
import isValid from 'date-fns/is_valid';
import enLocale from 'date-fns/locale/en';
import startOfToday from 'date-fns/start_of_today';
import deprecated from 'deprecated-prop-type';
import Fecha from 'fecha'; // TODO replace with date-fns/parse after v2 is released
import PropTypes from 'prop-types';
import React from 'react';
import Button from '../Button/Button';
import ButtonGroup from '../Button/ButtonGroup';
import Calendar from '../Calendar/Calendar';
import Dropdown from '../Dropdown/Dropdown';
import DropdownMenu from '../Dropdown/DropdownMenu';
import DropdownToggle from '../Dropdown/DropdownToggle';
import Icon from '../Icon/Icon';
import InputGroup from '../InputGroup/InputGroup';
const { parse: dateParser } = Fecha;
/**
* Given a defaultValue, return the corresponding calendar date and input string value:
*
* | defaultValue | date | string |
* |----------------|-------|----------------|
* | null, | today | '' |
* | Date | Date | 'M/D/YYYY' |
* | 'M/D/YYYY' | Date | 'M/D/YYYY' |
* | invalid string | today | invalid string |
*/
function parseValue(defaultValue, dateFormat, parseDate) {
let date;
if (defaultValue) {
if (defaultValue instanceof Date) {
date = defaultValue;
} else {
date = parseDate(defaultValue, dateFormat);
try {
if (!isValid(date)) {
date = new Date();
}
} catch (e) {
date = new Date();
}
}
} else {
date = new Date();
}
return date;
}
export default class DateInput extends React.Component {
static propTypes = {
className: PropTypes.string,
dateEnabled: PropTypes.func,
dateVisible: PropTypes.func,
dateFormat: PropTypes.string,
defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
direction: PropTypes.string,
disabled: PropTypes.bool,
footer: deprecated(PropTypes.node, 'Use renderFooter instead.'),
header: deprecated(PropTypes.node, 'Use renderHeader insread.'),
renderFooter: PropTypes.func,
renderHeader: PropTypes.func,
id: PropTypes.string,
keyboard: PropTypes.bool,
locale: PropTypes.object,
onBlur: PropTypes.func,
onChange: PropTypes.func,
onClose: PropTypes.func,
parse: PropTypes.func,
positionFixed: PropTypes.bool,
showOnFocus: PropTypes.bool,
state: PropTypes.any,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
container: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
};
static defaultProps = {
className: '',
dateFormat: 'M/D/YYYY',
dateEnabled: () => true,
dateVisible: () => true,
disabled: false,
keyboard: true,
locale: enLocale,
onBlur: () => {},
onChange: () => {},
parse: (value, dateFormat) => dateParser(value, dateFormat),
renderHeader: () => {},
renderFooter: () => {},
showOnFocus: true,
};
constructor(props) {
super(props);
let value = props.defaultValue || '';
if (props.defaultValue instanceof Date) {
value = format(value, props.dateFormat, { locale: props.locale });
}
this.state = {
open: false,
value,
};
}
onChange = (value) => {
this.setState({
value,
});
this.parseInput(value);
};
onSelect = (newDate) => this.setDate(newDate, true);
onKeyDown = (event) => {
// Ignore arrows if closed, disabled, or modifiers are down:
const allowArrows =
this.state.open &&
this.props.keyboard &&
!(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey);
switch (event.keyCode) {
case 9: // TAB
this.setState({ open: false });
break;
case 13: // Enter
if (this.state.open) {
// To avoid submitting the form if DateInput is contained in a form
event.preventDefault();
this.setState({ open: false });
}
break;
case 27: // Esc
if (this.state.open) {
// To avoid parent elements handling the ESC key (like modals closing)
event.stopPropagation();
this.setState({ open: false });
}
break;
case 37: // Left
if (allowArrows) {
this.setDate(addDays(this.getCurrentDate(), -1));
}
break;
case 38: // Up
if (allowArrows) {
this.setDate(addWeeks(this.getCurrentDate(), -1));
}
break;
case 39: // Right
if (allowArrows) {
this.setDate(addDays(this.getCurrentDate(), 1));
}
break;
case 40: // Down
if (allowArrows) {
this.setDate(addWeeks(this.getCurrentDate(), 1));
}
break;
default:
}
return true;
};
setDate = (date, close = false) => {
const newState = close
? {
value: format(date, this.props.dateFormat, { locale: this.props.locale }),
open: false,
}
: {
value: format(date, this.props.dateFormat, { locale: this.props.locale }),
};
this.setState(newState, () => {
this.inputEl.setAttribute('value', newState.value);
this.props.onChange(date, true);
});
};
getCurrentValue = () => {
if (this.props.value !== undefined) {
if (this.props.value instanceof Date) {
return format(this.props.value, this.props.dateFormat, { locale: this.props.locale });
}
return this.props.value;
}
return this.state.value;
};
getCurrentDate = () =>
parseValue(
this.props.value !== undefined ? this.props.value : this.state.value,
this.props.dateFormat,
this.props.parse
);
parseInput = (value) => {
const date = this.props.parse(value, this.props.dateFormat);
if (date) {
this.props.onChange(date, true);
} else {
this.props.onChange(value, false);
}
this.inputEl.setAttribute('value', value);
};
clear = () => this.onChange('');
close = () => this.setState({ open: false });
nextMonth = () => this.setDate(addMonths(this.getCurrentDate(), 1));
nextYear = () => this.setDate(addYears(this.getCurrentDate(), 1));
prevMonth = () => this.setDate(addMonths(this.getCurrentDate(), -1));
prevYear = () => this.setDate(addYears(this.getCurrentDate(), -1));
show = () => this.setState({ open: true });
today = () => this.setDate(startOfToday(), true);
toggle = () => (this.state.open ? this.close() : this.show());
setInputValue = () => {
if (!this.inputEl) {
return;
}
const currentValue = this.getCurrentValue();
const inputValue = this.inputEl.value;
const currentValueAsDate =
currentValue && this.props.parse(currentValue, this.props.dateFormat);
const inputValueAsDate = this.props.parse(inputValue || '', this.props.dateFormat);
const isSame =
(currentValueAsDate && inputValueAsDate && isSameDay(currentValueAsDate, inputValueAsDate)) ||
inputValue === currentValue;
if (!isSame) {
this.inputEl.value = currentValue;
this.inputEl.setAttribute('value', currentValue);
}
};
onBlur = (e) => {
this.props.onBlur(e);
const parsedDate = this.props.parse(this.inputEl.value, this.props.dateFormat);
if (parsedDate) {
const value = format(parsedDate, this.props.dateFormat, { locale: this.props.locale });
this.inputEl.value = value;
this.inputEl.setAttribute('value', value);
}
};
/* eslint-disable-next-line react/no-unused-class-component-methods -- Address this when converting to functional component */
focus() {
this.inputEl.focus();
}
componentDidMount() {
this.setInputValue();
}
componentDidUpdate(prevProps, prevState) {
this.setInputValue();
if (this.props.onClose && this.state.open !== prevState.open && !this.state.open) {
const value = this.props.value !== undefined ? this.props.value : this.state.value;
const date = this.props.parse(value, this.props.dateFormat);
if (date) {
this.props.onClose(date, true);
} else {
this.props.onClose(value, false);
}
}
}
render() {
/* eslint-disable @typescript-eslint/no-unused-vars -- This should go away when converted to function component */
const {
className,
dateEnabled,
dateVisible,
direction,
disabled,
footer,
header,
renderFooter,
renderHeader,
id,
showOnFocus,
dateFormat,
defaultValue,
keyboard,
locale,
onBlur,
onChange,
parse,
positionFixed,
value,
state,
container,
...props
} = this.props;
/* eslint-enable @typescript-eslint/no-unused-vars */
const { open } = this.state;
const date = this.getCurrentDate();
const dropdownProps = open && positionFixed ? { strategy: 'fixed' } : {};
// <DropdownToggle tag="div" disabled> is to wrap the input in a container for positioning dropdown/up, without breaking showOnFocus
// TODO extract a DropdownInput component that can encapsulate the defaultValue/value controlled/uncontrolled behavior.
return (
<div>
<Dropdown direction={direction} isOpen={!disabled && open} toggle={this.toggle}>
<DropdownToggle tag="div" disabled>
<InputGroup className={className}>
<input
id={id}
className="form-control"
data-testid="react-gears-dateinput-inputgroup-input"
ref={(el) => {
this.inputEl = el;
}}
type="text"
onBlur={this.onBlur}
onChange={(e) => this.onChange(e.target.value)}
onClick={showOnFocus ? this.show : undefined}
onFocus={showOnFocus ? this.show : undefined}
onKeyDown={this.onKeyDown}
disabled={disabled}
{...props}
/>
<Button
className="px-2"
data-testid="react-gears-dateinput-inputgroup-button"
disabled={disabled}
active={open}
type="button"
tabIndex={-1}
onClick={this.toggle}
>
<Icon name="calendar" iconStyle="regular" fixedWidth />
<span className="visually-hidden">Open Calendar</span>
</Button>
</InputGroup>
</DropdownToggle>
<DropdownMenu
className="p-0"
onKeyDown={this.onKeyDown}
container={container}
{...dropdownProps}
>
{renderHeader(this.prevMonth, this.nextMonth, this.prevYear, this.nextYear) || header || (
<header className="d-flex py-2">
<ButtonGroup size="sm">
<Button
className="js-prev-year"
color="link"
data-testid="react-gears-dateinput-dropdownmenu-button-prev-year"
onClick={() => this.prevYear()}
>
<Icon name="angle-double-left" fixedWidth />
<span className="visually-hidden">Previous Year</span>
</Button>
<Button
className="js-prev-month"
color="link"
data-testid="react-gears-dateinput-dropdownmenu-button-prev-month"
onClick={() => this.prevMonth()}
>
<Icon name="angle-left" fixedWidth />
<span className="visually-hidden">Previous Month</span>
</Button>
</ButtonGroup>
<span className="js-date-header m-auto">
{format(date, 'MMMM YYYY', { locale })}
</span>
<ButtonGroup size="sm">
<Button
className="js-next-month"
color="link"
data-testid="react-gears-dateinput-dropdownmenu-button-next-month"
onClick={() => this.nextMonth()}
>
<Icon name="angle-right" fixedWidth />
<span className="visually-hidden">Next Month</span>
</Button>
<Button
className="js-next-year"
color="link"
data-testid="react-gears-dateinput-dropdownmenu-button-next-year"
onClick={() => this.nextYear()}
>
<Icon name="angle-double-right" fixedWidth />
<span className="visually-hidden">Next Year</span>
</Button>
</ButtonGroup>
</header>
)}
<Calendar
date={date}
data-testid="react-gears-dateinput-dropdownmenu-calendar"
dateEnabled={dateEnabled}
dateVisible={dateVisible}
locale={locale}
onSelect={this.onSelect}
className="m-0"
style={{ minWidth: '19rem' }}
/>
{renderFooter(this.today, this.clear) || footer || (
<footer className="text-center pb-2 pt-1">
<div>
<Button
onClick={this.today}
className="me-2"
data-testid="react-gears-dateinput-footer-button-today"
>
Today
</Button>
<Button
onClick={this.clear}
className="me-2"
data-testid="react-gears-dateinput-footer-button-clear"
>
Clear
</Button>
</div>
</footer>
)}
</DropdownMenu>
</Dropdown>
</div>
);
}
}