Layne Anderson
2017-09-30 39b8275f9b2bbd8f11ffecba94fce7d339c4d577
commit | author | age
c7776a 1 'use strict';
417bf4 2
c7776a 3 var assign = require('object-assign'),
2bcc09 4     PropTypes = require('prop-types'),
cf3d92 5     createClass = require('create-react-class'),
9f1b61 6     moment = require('moment'),
4ad788 7     React = require('react'),
e09432 8     CalendarContainer = require('./src/CalendarContainer')
cf3d92 9     ;
417bf4 10
0cae6c 11 var TYPES = PropTypes;
84755c 12 var Datetime = createClass({
c7776a 13     propTypes: {
0d9dc7 14         // value: TYPES.object | TYPES.string,
M 15         // defaultValue: TYPES.object | TYPES.string,
aca9e6 16         onFocus: TYPES.func,
0ef08f 17         onBlur: TYPES.func,
c37f80 18         onChange: TYPES.func,
5377a9 19         onViewModeChange: TYPES.func,
c37f80 20         locale: TYPES.string,
049c33 21         utc: TYPES.bool,
c37f80 22         input: TYPES.bool,
cbe644 23         // dateFormat: TYPES.string | TYPES.bool,
M 24         // timeFormat: TYPES.string | TYPES.bool,
c37f80 25         inputProps: TYPES.object,
0b3475 26         timeConstraints: TYPES.object,
c37f80 27         viewMode: TYPES.oneOf(['years', 'months', 'days', 'time']),
e7f876 28         isValidDate: TYPES.func,
692390 29         open: TYPES.bool,
9012e8 30         strictParsing: TYPES.bool,
M 31         closeOnSelect: TYPES.bool,
32         closeOnTab: TYPES.bool
c7776a 33     },
8abb28 34
c7776a 35     getDefaultProps: function() {
9f1b61 36         var nof = function() {};
c7776a 37         return {
8abb28 38             className: '',
62fd2f 39             defaultValue: '',
d76f7b 40             inputProps: {},
a3a33b 41             input: true,
aca9e6 42             onFocus: nof,
4e9d38 43             onBlur: nof,
cbe644 44             onChange: nof,
5377a9 45             onViewModeChange: nof,
839cd8 46             timeFormat: true,
0b3475 47             timeConstraints: {},
0eb226 48             dateFormat: true,
9012e8 49             strictParsing: true,
M 50             closeOnSelect: false,
049c33 51             closeOnTab: true,
TS 52             utc: false
c7776a 53         };
M 54     },
c658ad 55
c7776a 56     getInitialState: function() {
c658ad 57         var state = this.getStateFromProps( this.props );
M 58
462115 59         if ( state.open === undefined )
87c677 60             state.open = !this.props.input;
M 61
92a2c6 62         state.currentView = this.props.dateFormat ? (this.props.viewMode || state.updateOn || 'days') : 'time';
c658ad 63
M 64         return state;
65     },
66
9f1b61 67     getStateFromProps: function( props ) {
c658ad 68         var formats = this.getFormats( props ),
M 69             date = props.value || props.defaultValue,
0eb496 70             selectedDate, viewDate, updateOn, inputValue
cf3d92 71             ;
3515a4 72
462115 73         if ( date && typeof date === 'string' )
c658ad 74             selectedDate = this.localMoment( date, formats.datetime );
462115 75         else if ( date )
c658ad 76             selectedDate = this.localMoment( date );
62fd2f 77
462115 78         if ( selectedDate && !selectedDate.isValid() )
62fd2f 79             selectedDate = null;
M 80
81         viewDate = selectedDate ?
462115 82             selectedDate.clone().startOf('month') :
SE 83             this.localMoment().startOf('month')
62fd2f 84         ;
3515a4 85
d1be3f 86         updateOn = this.getUpdateOn(formats);
SA 87
0eb496 88         if ( selectedDate )
SE 89             inputValue = selectedDate.format(formats.datetime);
90         else if ( date.isValid && !date.isValid() )
91             inputValue = '';
92         else
93             inputValue = date || '';
94
c7776a 95         return {
d1be3f 96             updateOn: updateOn,
c7776a 97             inputFormat: formats.datetime,
62fd2f 98             viewDate: viewDate,
0d9dc7 99             selectedDate: selectedDate,
0eb496 100             inputValue: inputValue,
50a0c2 101             open: props.open
c7776a 102         };
d1be3f 103     },
SA 104
9f1b61 105     getUpdateOn: function( formats ) {
cf3d92 106         if ( formats.date.match(/[lLD]/) ) {
462115 107             return 'days';
2bcc09 108         } else if ( formats.date.indexOf('M') !== -1 ) {
462115 109             return 'months';
2bcc09 110         } else if ( formats.date.indexOf('Y') !== -1 ) {
462115 111             return 'years';
92a2c6 112         }
M 113
114         return 'days';
c7776a 115     },
aca70a 116
9f1b61 117     getFormats: function( props ) {
c7776a 118         var formats = {
839cd8 119                 date: props.dateFormat || '',
M 120                 time: props.timeFormat || ''
c37f80 121             },
64fc6a 122             locale = this.localMoment( props.date, null, props ).localeData()
cf3d92 123             ;
5e870c 124
9f1b61 125         if ( formats.date === true ) {
3515a4 126             formats.date = locale.longDateFormat('L');
c7776a 127         }
9f1b61 128         else if ( this.getUpdateOn(formats) !== 'days' ) {
92a2c6 129             formats.time = '';
M 130         }
131
9f1b61 132         if ( formats.time === true ) {
3515a4 133             formats.time = locale.longDateFormat('LT');
c7776a 134         }
5e870c 135
0d9dc7 136         formats.datetime = formats.date && formats.time ?
M 137             formats.date + ' ' + formats.time :
138             formats.date || formats.time
139         ;
c7776a 140
M 141         return formats;
142     },
143
9f1b61 144     componentWillReceiveProps: function( nextProps ) {
c658ad 145         var formats = this.getFormats( nextProps ),
64fc6a 146             updatedState = {}
c37f80 147         ;
M 148
701646 149         if ( nextProps.value !== this.props.value ||
64fc6a 150             formats.datetime !== this.getFormats( this.props ).datetime ) {
SE 151             updatedState = this.getStateFromProps( nextProps );
c7776a 152         }
M 153
64fc6a 154         if ( updatedState.open === undefined ) {
fee412 155             if ( this.props.closeOnSelect && this.state.currentView !== 'time' ) {
SE 156                 updatedState.open = false;
157             } else {
158                 updatedState.open = this.state.open;
159             }
433f26 160         }
SE 161
583af6 162         if ( nextProps.viewMode !== this.props.viewMode ) {
64fc6a 163             updatedState.currentView = nextProps.viewMode;
583af6 164         }
a8a17a 165
64fc6a 166         if ( nextProps.locale !== this.props.locale ) {
SE 167             if ( this.state.viewDate ) {
168                 var updatedViewDate = this.state.viewDate.clone().locale( nextProps.locale );
169                 updatedState.viewDate = updatedViewDate;
170             }
171             if ( this.state.selectedDate ) {
172                 var updatedSelectedDate = this.state.selectedDate.clone().locale( nextProps.locale );
173                 updatedState.selectedDate = updatedSelectedDate;
174                 updatedState.inputValue = updatedSelectedDate.format( formats.datetime );
175             }
176         }
177
178         if ( nextProps.utc !== this.props.utc ) {
179             if ( nextProps.utc ) {
180                 if ( this.state.viewDate )
181                     updatedState.viewDate = this.state.viewDate.clone().utc();
182                 if ( this.state.selectedDate ) {
183                     updatedState.selectedDate = this.state.selectedDate.clone().utc();
184                     updatedState.inputValue = updatedState.selectedDate.format( formats.datetime );
185                 }
186             } else {
187                 if ( this.state.viewDate )
188                     updatedState.viewDate = this.state.viewDate.clone().local();
189                 if ( this.state.selectedDate ) {
190                     updatedState.selectedDate = this.state.selectedDate.clone().local();
191                     updatedState.inputValue = updatedState.selectedDate.format(formats.datetime);
192                 }
193             }
194         }
39b827 195         //we should only show a valid date if we are provided a isValidDate function. Removed in 2.10.3
LA 196         /*if (this.props.isValidDate) {
9509fa 197             updatedState.viewDate = updatedState.viewDate || this.state.viewDate;
JC 198             while (!this.props.isValidDate(updatedState.viewDate)) {
199                 updatedState.viewDate = updatedState.viewDate.add(1, 'day');
200             }
39b827 201         }*/
64fc6a 202         this.setState( updatedState );
c658ad 203     },
M 204
205     onInputChange: function( e ) {
462115 206         var value = e.target === null ? e : e.target.value,
c658ad 207             localMoment = this.localMoment( value, this.state.inputFormat ),
M 208             update = { inputValue: value }
cf3d92 209             ;
c658ad 210
M 211         if ( localMoment.isValid() && !this.props.value ) {
212             update.selectedDate = localMoment;
462115 213             update.viewDate = localMoment.clone().startOf('month');
2bcc09 214         } else {
62fd2f 215             update.selectedDate = null;
M 216         }
c658ad 217
M 218         return this.setState( update, function() {
62fd2f 219             return this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue );
c7776a 220         });
M 221     },
222
9f1b61 223     onInputKey: function( e ) {
SE 224         if ( e.which === 9 && this.props.closeOnTab ) {
9012e8 225             this.closeCalendar();
M 226         }
c7776a 227     },
M 228
9f1b61 229     showView: function( view ) {
c7776a 230         var me = this;
9f1b61 231         return function() {
5377a9 232             me.state.currentView !== view && me.props.onViewModeChange( view );
c7776a 233             me.setState({ currentView: view });
M 234         };
235     },
236
9f1b61 237     setDate: function( type ) {
c7776a 238         var me = this,
4ad788 239             nextViews = {
M 240                 month: 'days',
241                 year: 'months'
242             }
c7776a 243         ;
9f1b61 244         return function( e ) {
c7776a 245             me.setState({
462115 246                 viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.getAttribute('data-value'), 10) ).startOf( type ),
c7776a 247                 currentView: nextViews[ type ]
M 248             });
5377a9 249             me.props.onViewModeChange( nextViews[ type ] );
9fb8e8 250         };
c7776a 251     },
M 252
9f1b61 253     addTime: function( amount, type, toSelected ) {
c7776a 254         return this.updateTime( 'add', amount, type, toSelected );
M 255     },
9fb8e8 256
9f1b61 257     subtractTime: function( amount, type, toSelected ) {
c7776a 258         return this.updateTime( 'subtract', amount, type, toSelected );
M 259     },
9fb8e8 260
9f1b61 261     updateTime: function( op, amount, type, toSelected ) {
c7776a 262         var me = this;
M 263
9f1b61 264         return function() {
c7776a 265             var update = {},
M 266                 date = toSelected ? 'selectedDate' : 'viewDate'
267             ;
268
269             update[ date ] = me.state[ date ].clone()[ op ]( amount, type );
270
271             me.setState( update );
272         };
273     },
274
462115 275     allowedSetTime: ['hours', 'minutes', 'seconds', 'milliseconds'],
9f1b61 276     setTime: function( type, value ) {
c7776a 277         var index = this.allowedSetTime.indexOf( type ) + 1,
62fd2f 278             state = this.state,
M 279             date = (state.selectedDate || state.viewDate).clone(),
c7776a 280             nextType
cf3d92 281             ;
c7776a 282
4ad788 283         // It is needed to set all the time properties
M 284         // to not to reset the time
c7776a 285         date[ type ]( value );
M 286         for (; index < this.allowedSetTime.length; index++) {
287             nextType = this.allowedSetTime[index];
288             date[ nextType ]( date[nextType]() );
289         }
4ad788 290
9f1b61 291         if ( !this.props.value ) {
c658ad 292             this.setState({
M 293                 selectedDate: date,
62fd2f 294                 inputValue: date.format( state.inputFormat )
c658ad 295             });
M 296         }
4e9d38 297         this.props.onChange( date );
c7776a 298     },
M 299
1fdc4e 300     updateSelectedDate: function( e, close ) {
c7776a 301         var target = e.target,
c37f80 302             modifier = 0,
62fd2f 303             viewDate = this.state.viewDate,
M 304             currentDate = this.state.selectedDate || viewDate,
c37f80 305             date
cf3d92 306             ;
c7776a 307
9f1b61 308         if (target.className.indexOf('rdtDay') !== -1) {
462115 309             if (target.className.indexOf('rdtNew') !== -1)
d1be3f 310                 modifier = 1;
462115 311             else if (target.className.indexOf('rdtOld') !== -1)
d1be3f 312                 modifier = -1;
c7776a 313
d1be3f 314             date = viewDate.clone()
SA 315                 .month( viewDate.month() + modifier )
462115 316                 .date( parseInt( target.getAttribute('data-value'), 10 ) );
9f1b61 317         } else if (target.className.indexOf('rdtMonth') !== -1) {
d1be3f 318             date = viewDate.clone()
462115 319                 .month( parseInt( target.getAttribute('data-value'), 10 ) )
SE 320                 .date( currentDate.date() );
9f1b61 321         } else if (target.className.indexOf('rdtYear') !== -1) {
d1be3f 322             date = viewDate.clone()
SA 323                 .month( currentDate.month() )
324                 .date( currentDate.date() )
462115 325                 .year( parseInt( target.getAttribute('data-value'), 10 ) );
d1be3f 326         }
SA 327
328         date.hours( currentDate.hours() )
c7776a 329             .minutes( currentDate.minutes() )
M 330             .seconds( currentDate.seconds() )
462115 331             .milliseconds( currentDate.milliseconds() );
c7776a 332
9f1b61 333         if ( !this.props.value ) {
794700 334             var open = !( this.props.closeOnSelect && close );
SE 335             if ( !open ) {
336                 this.props.onBlur( date );
337             }
338
c658ad 339             this.setState({
M 340                 selectedDate: date,
341                 viewDate: date.clone().startOf('month'),
50a0c2 342                 inputValue: date.format( this.state.inputFormat ),
794700 343                 open: open
c658ad 344             });
462115 345         } else {
794700 346             if ( this.props.closeOnSelect && close ) {
50a0c2 347                 this.closeCalendar();
M 348             }
c658ad 349         }
4e9d38 350
M 351         this.props.onChange( date );
c7776a 352     },
M 353
354     openCalendar: function() {
aca9e6 355         if (!this.state.open) {
f72983 356             this.setState({ open: true }, function() {
GV 357                 this.props.onFocus();
358             });
aca9e6 359         }
c7776a 360     },
M 361
1fdc4e 362     closeCalendar: function() {
f72983 363         this.setState({ open: false }, function () {
GV 364             this.props.onBlur( this.state.selectedDate || this.state.inputValue );
365         });
1fdc4e 366     },
EC 367
9f1b61 368     handleClickOutside: function() {
SE 369         if ( this.props.input && this.state.open && !this.props.open ) {
f72983 370             this.setState({ open: false }, function() {
GV 371                 this.props.onBlur( this.state.selectedDate || this.state.inputValue );
372             });
62fd2f 373         }
c7776a 374     },
M 375
64fc6a 376     localMoment: function( date, format, props ) {
SE 377         props = props || this.props;
378         var momentFn = props.utc ? moment.utc : moment;
379         var m = momentFn( date, format, props.strictParsing );
380         if ( props.locale )
381             m.locale( props.locale );
c37f80 382         return m;
M 383     },
384
c7776a 385     componentProps: {
0b3475 386         fromProps: ['value', 'isValidDate', 'renderDay', 'renderMonth', 'renderYear', 'timeConstraints'],
d1be3f 387         fromState: ['viewDate', 'selectedDate', 'updateOn'],
11612b 388         fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateSelectedDate', 'localMoment', 'handleClickOutside']
c7776a 389     },
M 390
9f1b61 391     getComponentProps: function() {
c7776a 392         var me = this,
a3a33b 393             formats = this.getFormats( this.props ),
M 394             props = {dateFormat: formats.date, timeFormat: formats.time}
cf3d92 395             ;
c7776a 396
9f1b61 397         this.componentProps.fromProps.forEach( function( name ) {
c7776a 398             props[ name ] = me.props[ name ];
M 399         });
9f1b61 400         this.componentProps.fromState.forEach( function( name ) {
c7776a 401             props[ name ] = me.state[ name ];
M 402         });
9f1b61 403         this.componentProps.fromThis.forEach( function( name ) {
c7776a 404             props[ name ] = me[ name ];
M 405         });
406
407         return props;
408     },
409
410     render: function() {
f4e62d 411         // TODO: Make a function or clean up this code,
SE 412         // logic right now is really hard to follow
a50b2e 413         var className = 'rdt' + (this.props.className ?
386942 414                   ( Array.isArray( this.props.className ) ?
SE 415                   ' ' + this.props.className.join( ' ' ) : ' ' + this.props.className) : ''),
cf3d92 416             children = [];
a3a33b 417
9f1b61 418         if ( this.props.input ) {
a50b2e 419             children = [ React.createElement('input', assign({
18dc17 420                 key: 'i',
9f1b61 421                 type: 'text',
2bb9ca 422                 className: 'form-control',
d76f7b 423                 onFocus: this.openCalendar,
c658ad 424                 onChange: this.onInputChange,
9012e8 425                 onKeyDown: this.onInputKey,
d76f7b 426                 value: this.state.inputValue
a3a33b 427             }, this.props.inputProps ))];
462115 428         } else {
a3a33b 429             className += ' rdtStatic';
M 430         }
d76f7b 431
462115 432         if ( this.state.open )
a3a33b 433             className += ' rdtOpen';
M 434
a50b2e 435         return React.createElement('div', {className: className}, children.concat(
GL 436             React.createElement('div',
a3a33b 437                 { key: 'dt', className: 'rdtPicker' },
e09432 438                 React.createElement( CalendarContainer, {view: this.state.currentView, viewProps: this.getComponentProps(), onClickOutside: this.handleClickOutside })
d76f7b 439             )
a3a33b 440         ));
c7776a 441     }
47e834 442 });
LC 443
cc4dda 444 // Make moment accessible through the Datetime class
M 445 Datetime.moment = moment;
446
9fb8e8 447 module.exports = Datetime;