forked from gpbl/react-day-picker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDayPickerInput.js
More file actions
581 lines (528 loc) · 15.1 KB
/
Copy pathDayPickerInput.js
File metadata and controls
581 lines (528 loc) · 15.1 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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
import React from 'react';
import PropTypes from 'prop-types';
import DayPicker from './DayPicker';
import { isSameMonth, isDate } from './DateUtils';
import { getModifiersForDay } from './ModifiersUtils';
import { ESC, TAB } from './keys';
// When clicking on a day cell, overlay will be hidden after this timeout
export const HIDE_TIMEOUT = 100;
/**
* The default component used as Overlay.
*
* @param {Object} props
*/
export function OverlayComponent({
input,
selectedDay,
month,
children,
classNames,
...props
}) {
return (
<div className={classNames.overlayWrapper} {...props}>
<div className={classNames.overlay}>{children}</div>
</div>
);
}
OverlayComponent.propTypes = {
input: PropTypes.any,
selectedDay: PropTypes.any,
month: PropTypes.instanceOf(Date),
children: PropTypes.node,
classNames: PropTypes.object,
};
/**
* The default function used to format a Date to String, passed to the `format`
* prop.
* @param {Date} d
* @return {String}
*/
export function defaultFormat(d) {
if (isDate(d)) {
const year = d.getFullYear();
const month = `${d.getMonth() + 1}`;
const day = `${d.getDate()}`;
return `${year}-${month}-${day}`;
}
return '';
}
/**
* The default function used to parse a String as Date, passed to the `parse`
* prop.
* @param {String} str
* @return {Date}
*/
export function defaultParse(str) {
if (typeof str !== 'string') {
return undefined;
}
const split = str.split('-');
if (split.length !== 3) {
return undefined;
}
const year = parseInt(split[0], 10);
const month = parseInt(split[1], 10) - 1;
const day = parseInt(split[2], 10);
if (
isNaN(year) ||
String(year).length > 4 ||
isNaN(month) ||
isNaN(day) ||
day <= 0 ||
day > 31 ||
month < 0 ||
month >= 12
) {
return undefined;
}
return new Date(year, month, day);
}
export default class DayPickerInput extends React.Component {
static propTypes = {
value: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]),
inputProps: PropTypes.object,
placeholder: PropTypes.string,
format: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
formatDate: PropTypes.func,
parseDate: PropTypes.func,
showOverlay: PropTypes.bool,
dayPickerProps: PropTypes.object,
hideOnDayClick: PropTypes.bool,
clickUnselectsDay: PropTypes.bool,
keepFocus: PropTypes.bool,
component: PropTypes.any,
overlayComponent: PropTypes.any,
classNames: PropTypes.shape({
container: PropTypes.string,
overlayWrapper: PropTypes.string,
overlay: PropTypes.string.isRequired,
}),
onDayChange: PropTypes.func,
onDayPickerHide: PropTypes.func,
onChange: PropTypes.func,
onClick: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onKeyUp: PropTypes.func,
};
static defaultProps = {
dayPickerProps: {},
value: '',
placeholder: 'YYYY-M-D',
format: 'L',
formatDate: defaultFormat,
parseDate: defaultParse,
showOverlay: false,
hideOnDayClick: true,
clickUnselectsDay: false,
keepFocus: true,
component: 'input',
inputProps: {},
overlayComponent: OverlayComponent,
classNames: {
container: 'DayPickerInput',
overlayWrapper: 'DayPickerInput-OverlayWrapper',
overlay: 'DayPickerInput-Overlay',
},
};
input = null;
daypicker = null;
clickTimeout = null;
hideTimeout = null;
inputBlurTimeout = null;
inputFocusTimeout = null;
constructor(props) {
super(props);
this.state = this.getInitialStateFromProps(props);
this.state.showOverlay = props.showOverlay;
this.hideAfterDayClick = this.hideAfterDayClick.bind(this);
this.handleInputClick = this.handleInputClick.bind(this);
this.handleInputFocus = this.handleInputFocus.bind(this);
this.handleInputBlur = this.handleInputBlur.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleInputKeyDown = this.handleInputKeyDown.bind(this);
this.handleInputKeyUp = this.handleInputKeyUp.bind(this);
this.handleDayClick = this.handleDayClick.bind(this);
this.handleMonthChange = this.handleMonthChange.bind(this);
this.handleOverlayFocus = this.handleOverlayFocus.bind(this);
this.handleOverlayBlur = this.handleOverlayBlur.bind(this);
}
componentDidUpdate(prevProps) {
const newState = {};
// Current props
const { value, formatDate, format, dayPickerProps } = this.props;
// Update the input value if the `value` prop has changed
if (value !== prevProps.value) {
if (isDate(value)) {
newState.value = formatDate(value, format, dayPickerProps.locale);
} else {
newState.value = value;
}
}
// Update the month if the months from props changed
const prevMonth = prevProps.dayPickerProps.month;
if (
dayPickerProps.month &&
dayPickerProps.month !== prevMonth &&
!isSameMonth(dayPickerProps.month, prevMonth)
) {
newState.month = dayPickerProps.month;
}
// Updated the selected days from props if they changed
if (prevProps.dayPickerProps.selectedDays !== dayPickerProps.selectedDays) {
newState.selectedDays = dayPickerProps.selectedDays;
}
if (Object.keys(newState).length > 0) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState(newState);
}
}
componentWillUnmount() {
clearTimeout(this.clickTimeout);
clearTimeout(this.hideTimeout);
clearTimeout(this.inputFocusTimeout);
clearTimeout(this.inputBlurTimeout);
clearTimeout(this.overlayBlurTimeout);
}
getInitialMonthFromProps(props) {
const { dayPickerProps, format } = props;
let day;
if (props.value) {
if (isDate(props.value)) {
day = props.value;
} else {
day = props.parseDate(props.value, format, dayPickerProps.locale);
}
}
return (
dayPickerProps.initialMonth || dayPickerProps.month || day || new Date()
);
}
getInitialStateFromProps(props) {
const { dayPickerProps, formatDate, format } = props;
let { value } = props;
if (props.value && isDate(props.value)) {
value = formatDate(props.value, format, dayPickerProps.locale);
}
return {
value,
month: this.getInitialMonthFromProps(props),
selectedDays: dayPickerProps.selectedDays,
};
}
getInput() {
return this.input;
}
getDayPicker() {
return this.daypicker;
}
/**
* Update the component's state and fire the `onDayChange` event passing the
* day's modifiers to it.
*
* @param {Date} day - Will be used for changing the month
* @param {String} value - Input field value
* @private
*/
updateState(day, value, callback) {
const { dayPickerProps, onDayChange } = this.props;
this.setState({ month: day, value, typedValue: undefined }, () => {
if (callback) {
callback();
}
if (!onDayChange) {
return;
}
const modifiersObj = {
disabled: dayPickerProps.disabledDays,
selected: dayPickerProps.selectedDays,
...dayPickerProps.modifiers,
};
const modifiers = getModifiersForDay(day, modifiersObj).reduce(
(obj, modifier) => ({
...obj,
[modifier]: true,
}),
{}
);
onDayChange(day, modifiers, this);
});
}
/**
* Show the Day Picker overlay.
*
* @memberof DayPickerInput
*/
showDayPicker() {
const { parseDate, format, dayPickerProps } = this.props;
const { value, showOverlay } = this.state;
if (showOverlay) {
return;
}
// Reset the current displayed month when showing the overlay
const month = value
? parseDate(value, format, dayPickerProps.locale) // Use the month in the input field
: this.getInitialMonthFromProps(this.props); // Restore the month from the props
this.setState(state => ({
showOverlay: true,
month: month || state.month,
}));
}
/**
* Hide the Day Picker overlay
*
* @memberof DayPickerInput
*/
hideDayPicker() {
if (this.state.showOverlay === false) {
return;
}
this.setState({ showOverlay: false }, () => {
if (this.props.onDayPickerHide) this.props.onDayPickerHide();
});
}
hideAfterDayClick() {
if (!this.props.hideOnDayClick) {
return;
}
this.hideTimeout = setTimeout(() => this.hideDayPicker(), HIDE_TIMEOUT);
}
handleInputClick(e) {
this.showDayPicker();
if (this.props.inputProps.onClick) {
e.persist();
this.props.inputProps.onClick(e);
}
}
handleInputFocus(e) {
this.showDayPicker();
// Set `overlayHasFocus` after a timeout so the overlay can be hidden when
// the input is blurred
this.inputFocusTimeout = setTimeout(() => {
this.overlayHasFocus = false;
}, 2);
if (this.props.inputProps.onFocus) {
e.persist();
this.props.inputProps.onFocus(e);
}
}
// When the input is blurred, the overlay should disappear. However the input
// is blurred also when the user interacts with the overlay (e.g. the overlay
// get the focus by clicking it). In these cases, the overlay should not be
// hidden. There are different approaches to avoid hiding the overlay when
// this happens, but the only cross-browser hack we’ve found is to set all
// these timeouts in code before changing `overlayHasFocus`.
handleInputBlur(e) {
this.inputBlurTimeout = setTimeout(() => {
if (!this.overlayHasFocus) {
this.hideDayPicker();
}
}, 1);
if (this.props.inputProps.onBlur) {
e.persist();
this.props.inputProps.onBlur(e);
}
}
handleOverlayFocus(e) {
e.preventDefault();
this.overlayHasFocus = true;
if (
!this.props.keepFocus ||
!this.input ||
typeof this.input.focus !== 'function'
) {
return;
}
this.input.focus();
}
handleOverlayBlur() {
// We need to set a timeout otherwise IE11 will hide the overlay when
// focusing it
this.overlayBlurTimeout = setTimeout(() => {
this.overlayHasFocus = false;
}, 3);
}
handleInputChange(e) {
const {
dayPickerProps,
format,
inputProps,
onDayChange,
parseDate,
} = this.props;
if (inputProps.onChange) {
e.persist();
inputProps.onChange(e);
}
const { value } = e.target;
if (value.trim() === '') {
this.setState({ value, typedValue: undefined });
if (onDayChange) onDayChange(undefined, {}, this);
return;
}
const day = parseDate(value, format, dayPickerProps.locale);
if (!day) {
// Day is invalid: we save the value in the typedValue state
this.setState({ value, typedValue: value });
if (onDayChange) onDayChange(undefined, {}, this);
return;
}
this.updateState(day, value);
}
handleInputKeyDown(e) {
if (e.keyCode === TAB) {
this.hideDayPicker();
} else {
this.showDayPicker();
}
if (this.props.inputProps.onKeyDown) {
e.persist();
this.props.inputProps.onKeyDown(e);
}
}
handleInputKeyUp(e) {
if (e.keyCode === ESC) {
this.hideDayPicker();
} else {
this.showDayPicker();
}
if (this.props.inputProps.onKeyUp) {
e.persist();
this.props.inputProps.onKeyUp(e);
}
}
handleMonthChange(month) {
this.setState({ month }, () => {
if (
this.props.dayPickerProps &&
this.props.dayPickerProps.onMonthChange
) {
this.props.dayPickerProps.onMonthChange(month);
}
});
}
handleDayClick(day, modifiers, e) {
const {
clickUnselectsDay,
dayPickerProps,
onDayChange,
formatDate,
format,
} = this.props;
if (dayPickerProps.onDayClick) {
dayPickerProps.onDayClick(day, modifiers, e);
}
// Do nothing if the day is disabled
if (
modifiers.disabled ||
(dayPickerProps &&
dayPickerProps.classNames &&
modifiers[dayPickerProps.classNames.disabled])
) {
return;
}
// If the clicked day is already selected, remove the clicked day
// from the selected days and empty the field value
if (modifiers.selected && clickUnselectsDay) {
let { selectedDays } = this.state;
if (Array.isArray(selectedDays)) {
selectedDays = selectedDays.slice(0);
const selectedDayIdx = selectedDays.indexOf(day);
selectedDays.splice(selectedDayIdx, 1);
} else if (selectedDays) {
selectedDays = null;
}
this.setState(
{ value: '', typedValue: undefined, selectedDays },
this.hideAfterDayClick
);
if (onDayChange) {
onDayChange(undefined, modifiers, this);
}
return;
}
const value = formatDate(day, format, dayPickerProps.locale);
this.setState({ value, typedValue: undefined, month: day }, () => {
if (onDayChange) {
onDayChange(day, modifiers, this);
}
this.hideAfterDayClick();
});
}
renderOverlay() {
const {
classNames,
dayPickerProps,
parseDate,
formatDate,
format,
} = this.props;
const { selectedDays, value } = this.state;
let selectedDay;
if (!selectedDays && value) {
const day = parseDate(value, format, dayPickerProps.locale);
if (day) {
selectedDay = day;
}
} else if (selectedDays) {
selectedDay = selectedDays;
}
let onTodayButtonClick;
if (dayPickerProps.todayButton) {
// Set the current day when clicking the today button
onTodayButtonClick = () =>
this.updateState(
new Date(),
formatDate(new Date(), format, dayPickerProps.locale),
this.hideAfterDayClick
);
}
const Overlay = this.props.overlayComponent;
return (
<Overlay
classNames={classNames}
month={this.state.month}
selectedDay={selectedDay}
input={this.input}
tabIndex={0} // tabIndex is necessary to catch focus/blur events on Safari
onFocus={this.handleOverlayFocus}
onBlur={this.handleOverlayBlur}
>
<DayPicker
ref={el => (this.daypicker = el)}
onTodayButtonClick={onTodayButtonClick}
{...dayPickerProps}
month={this.state.month}
selectedDays={selectedDay}
onDayClick={this.handleDayClick}
onMonthChange={this.handleMonthChange}
/>
</Overlay>
);
}
render() {
const Input = this.props.component;
const { inputProps } = this.props;
return (
<div className={this.props.classNames.container}>
<Input
ref={el => (this.input = el)}
placeholder={this.props.placeholder}
{...inputProps}
value={this.state.typedValue || this.state.value}
onChange={this.handleInputChange}
onFocus={this.handleInputFocus}
onBlur={this.handleInputBlur}
onKeyDown={this.handleInputKeyDown}
onKeyUp={this.handleInputKeyUp}
onClick={!inputProps.disabled ? this.handleInputClick : undefined}
/>
{this.state.showOverlay && this.renderOverlay()}
</div>
);
}
}