forked from WikiEducationFoundation/WikiEduDashboard
/
date_picker.jsx
354 lines (316 loc) · 10.1 KB
/
date_picker.jsx
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
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import DayPicker from 'react-day-picker';
import OnClickOutside from 'react-onclickoutside';
import { range, includes } from 'lodash-es';
import { startOfDay, endOfDay, isValid, isAfter, parseISO, getHours, getMinutes, setHours, setMinutes, formatISO } from 'date-fns';
import InputHOC from '../high_order/input_hoc.jsx';
import Conditional from '../high_order/conditional.jsx';
import CourseDateUtils from '../../utils/course_date_utils.js';
import { formatDateWithoutTime, toDate } from '../../utils/date_utils.js';
const DatePicker = createReactClass({
displayName: 'DatePicker',
propTypes: {
id: PropTypes.string,
value: PropTypes.string,
value_key: PropTypes.string,
spacer: PropTypes.string,
label: PropTypes.string,
timeLabel: PropTypes.string,
valueClass: PropTypes.string,
editable: PropTypes.bool,
enabled: PropTypes.bool,
focus: PropTypes.bool,
inline: PropTypes.bool,
isClearable: PropTypes.bool,
placeholder: PropTypes.string,
p_tag_classname: PropTypes.string,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
onChange: PropTypes.func,
onClick: PropTypes.func,
append: PropTypes.string,
date_props: PropTypes.object,
showTime: PropTypes.bool
},
getDefaultProps() {
return {
invalidMessage: I18n.t('application.field_invalid_date')
};
},
getInitialState() {
if (this.props.value) {
const dateObj = toDate(this.props.value);
return {
value: formatDateWithoutTime(dateObj),
hour: getHours(dateObj),
minute: getMinutes(dateObj),
datePickerVisible: false
};
}
return {
value: '',
hour: 0,
minute: 0,
datePickerVisible: false
};
},
/**
* Update parent component with new date value.
* Used instead of onChange() in InputMixin because we need to
* call this.props.onChange with the full date string, not just YYYY-MM-DD
* @return {null}
*/
onChangeHandler() {
const e = { target: { value: formatISO(this.getDate()) } };
this.props.onChange(e);
},
/**
* Get date object of currently select date, hour and minute
* @return {Date}
*/
getDate() {
let dateObj = toDate(this.state.value);
dateObj = setHours(dateObj, this.state.hour);
return setMinutes(dateObj, this.state.minute);
},
getFormattedDate() {
return formatDateWithoutTime(this.getDate());
},
/**
* Get formatted date to be displayed as text,
* based on whether or not to include the time
* @return {String} formatted date
*/
getFormattedDateTime() {
return CourseDateUtils.formattedDateTime(this.getDate(), this.props.showTime);
},
getTimeDropdownOptions(type) {
return range(0, type === 'hour' ? 24 : 60).map((value) => {
return (
<option value={value} key={`timedropdown-${type}-${value}`}>
{(`00${value}`).slice(-2)}
</option>
);
});
},
handleDatePickerChange(selectedDate) {
const date = toDate(selectedDate);
if (this.isDayDisabled(date)) {
return;
}
this.refs.datefield.focus();
this.setState({
value: formatDateWithoutTime(date),
datePickerVisible: false
}, this.onChangeHandler);
},
/**
* Update value of date input field.
* Does not issue callbacks to parent component.
* @param {Event} e - input change event
* @return {null}
*/
handleDateFieldChange(e) {
const { value } = e.target;
if (value !== this.state.value) {
this.setState({ value });
}
},
/**
* When they blur out of the date input field,
* update the state if valid or revert back to last valid value
* @param {Event} e - blur event
* @return {null}
*/
handleDateFieldBlur(e) {
const { value } = e.target;
if (this.isValidDate(value) && !this.isDayDisabled(parseISO(value))) {
this.setState({ value }, () => {
this.onChangeHandler();
});
} else {
this.setState({ value: this.getInitialState().value });
}
},
handleHourFieldChange(e) {
this.setState({
hour: e.target.value
}, this.onChangeHandler);
},
handleMinuteFieldChange(e) {
this.setState({
minute: e.target.value
}, this.onChangeHandler);
},
handleClickOutside() {
if (this.state.datePickerVisible) {
this.setState({ datePickerVisible: false });
}
},
handleDateFieldClick() {
if (!this.state.datePickerVisible) {
this.setState({ datePickerVisible: true });
}
},
handleDateFieldFocus() {
this.setState({ datePickerVisible: true });
},
handleDateFieldKeyDown(e) {
// Close picker if tab, enter, or escape
if (includes([9, 13, 27], e.keyCode)) {
this.setState({ datePickerVisible: false });
}
},
isDaySelected(date) {
const currentDate = formatDateWithoutTime(date);
return currentDate === this.state.value;
},
isDayDisabled(currentDate) {
if (this.props.date_props) {
const minDate = startOfDay(this.props.date_props.minDate);
if (isValid(minDate) && isAfter(minDate, currentDate)) {
return true;
}
const maxDate = endOfDay(this.props.date_props.maxDate);
if (isValid(maxDate) && isAfter(currentDate, maxDate)) {
return true;
}
}
},
/**
* Validates given date string (should be similar to YYYY-MM-DD).
* This is implemented here to be self-contained within DatePicker.
* @param {String} value - date string
* @return {Boolean} valid or not
*/
isValidDate(value) {
const validationRegex = /^20\d\d-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])/;
return validationRegex.test(value) && isValid(toDate(value));
},
showCurrentDate() {
return this.refs.daypicker.showMonth(this.state.month);
},
render() {
const spacer = this.props.spacer || ': ';
let label;
let timeLabel;
let currentMonth;
if (this.props.label) {
label = this.props.label;
label += spacer;
}
if (this.props.timeLabel) {
timeLabel = this.props.timeLabel;
timeLabel += spacer;
} else {
// use unicode for to account for spacing when there is no label
timeLabel = '\u00A0';
}
let valueClass = 'text-input-component__value ';
if (this.props.valueClass) { valueClass += this.props.valueClass; }
if (this.props.editable) {
let labelClass = '';
let inputClass = (this.props.inline !== null) && this.props.inline ? ' inline' : '';
if (this.props.invalid) {
labelClass += 'red';
inputClass += 'invalid';
}
let minDate;
if (this.props.date_props && this.props.date_props.minDate) {
if (isValid(this.props.date_props.minDate)) {
minDate = this.props.date_props.minDate;
}
}
// don't validate YYYY-MM-DD format so we can update the daypicker as they type
const date = parseISO(this.state.value);
if (isValid(date)) {
currentMonth = date;
} else if (minDate) {
currentMonth = minDate;
} else {
currentMonth = new Date();
}
const modifiers = {
selected: this.isDaySelected,
disabled: this.isDayDisabled
};
const dateInput = (
<div className="date-input">
<input
id={this.props.id}
ref="datefield"
value={this.state.value || ''}
className={`${inputClass} ${this.props.value_key}`}
onChange={this.handleDateFieldChange}
onClick={this.handleDateFieldClick}
disabled={this.props.enabled && !this.props.enabled}
autoFocus={this.props.focus}
onFocus={this.handleDateFieldFocus}
onBlur={this.handleDateFieldBlur}
onKeyDown={this.handleDateFieldKeyDown}
placeholder={this.props.placeholder}
/>
<DayPicker
className={this.state.datePickerVisible ? 'DayPicker--visible ignore-react-onclickoutside' : null}
ref="daypicker"
tabIndex={-1}
modifiers={modifiers}
disabledDays={this.isDayDisabled}
onDayClick={this.handleDatePickerChange}
month={currentMonth}
/>
</div>
);
const timeControlNode = (
<span className={`form-group time-picker--form-group ${inputClass}`}>
<label htmlFor={`${this.props.id}-hour`} className={labelClass}>
{timeLabel}
</label>
<div className="time-input">
<select
className={`time-input__hour ${inputClass}`}
onChange={this.handleHourFieldChange}
value={this.state.hour}
>
{this.getTimeDropdownOptions('hour')}
</select>
:
<select
className={`time-input__minute ${inputClass}`}
onChange={this.handleMinuteFieldChange}
value={this.state.minute}
>
{this.getTimeDropdownOptions('minute')}
</select>
</div>
</span>
);
return (
<div className={`form-group datetime-control ${this.props.id}-datetime-control ${inputClass}`}>
<span className={`form-group date-picker--form-group ${inputClass}`}>
<label htmlFor={this.props.id}className={labelClass}>{label}</label>
{dateInput}
</span>
{this.props.showTime ? timeControlNode : null}
</div>
);
} else if (this.props.label !== null) {
return (
<p className={this.props.p_tag_classname}>
<span className="text-input-component__label"><strong>{label}</strong></span>
<span>{(this.props.value !== null || this.props.editable) && !this.props.label ? spacer : null}</span>
<span onBlur={this.props.onBlur} onClick={this.props.onClick} className={valueClass}>
{this.getFormattedDateTime()}
</span>
{this.props.append}
</p>
);
}
return (
<span>{this.getFormattedDateTime()}</span>
);
}
});
export default Conditional(InputHOC(OnClickOutside(DatePicker)));