Simon Egersand
2017-07-29 5377a9c3033f36d6adddc3aefcde415d50fdb3c1
commit | author | age
c7776a 1 'use strict';
417bf4 2
c7776a 3 var assign = require('object-assign'),
2bcc09 4     PropTypes = require('prop-types'),
SE 5     createClass = require('create-react-class'),
9f1b61 6     moment = require('moment'),
4ad788 7     React = require('react'),
e09432 8     CalendarContainer = require('./src/CalendarContainer')
c7776a 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
c7776a 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 ) {
2bcc09 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()
c37f80 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         }
195
196         this.setState( updatedState );
c658ad 197     },
M 198
199     onInputChange: function( e ) {
462115 200         var value = e.target === null ? e : e.target.value,
c658ad 201             localMoment = this.localMoment( value, this.state.inputFormat ),
M 202             update = { inputValue: value }
203         ;
204
205         if ( localMoment.isValid() && !this.props.value ) {
206             update.selectedDate = localMoment;
462115 207             update.viewDate = localMoment.clone().startOf('month');
2bcc09 208         } else {
62fd2f 209             update.selectedDate = null;
M 210         }
c658ad 211
M 212         return this.setState( update, function() {
62fd2f 213             return this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue );
c7776a 214         });
M 215     },
216
9f1b61 217     onInputKey: function( e ) {
SE 218         if ( e.which === 9 && this.props.closeOnTab ) {
9012e8 219             this.closeCalendar();
M 220         }
c7776a 221     },
M 222
9f1b61 223     showView: function( view ) {
c7776a 224         var me = this;
9f1b61 225         return function() {
5377a9 226             me.state.currentView !== view && me.props.onViewModeChange( view );
c7776a 227             me.setState({ currentView: view });
M 228         };
229     },
230
9f1b61 231     setDate: function( type ) {
c7776a 232         var me = this,
4ad788 233             nextViews = {
M 234                 month: 'days',
235                 year: 'months'
236             }
c7776a 237         ;
9f1b61 238         return function( e ) {
c7776a 239             me.setState({
462115 240                 viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.getAttribute('data-value'), 10) ).startOf( type ),
c7776a 241                 currentView: nextViews[ type ]
M 242             });
5377a9 243             me.props.onViewModeChange( nextViews[ type ] );
9fb8e8 244         };
c7776a 245     },
M 246
9f1b61 247     addTime: function( amount, type, toSelected ) {
c7776a 248         return this.updateTime( 'add', amount, type, toSelected );
M 249     },
9fb8e8 250
9f1b61 251     subtractTime: function( amount, type, toSelected ) {
c7776a 252         return this.updateTime( 'subtract', amount, type, toSelected );
M 253     },
9fb8e8 254
9f1b61 255     updateTime: function( op, amount, type, toSelected ) {
c7776a 256         var me = this;
M 257
9f1b61 258         return function() {
c7776a 259             var update = {},
M 260                 date = toSelected ? 'selectedDate' : 'viewDate'
261             ;
262
263             update[ date ] = me.state[ date ].clone()[ op ]( amount, type );
264
265             me.setState( update );
266         };
267     },
268
462115 269     allowedSetTime: ['hours', 'minutes', 'seconds', 'milliseconds'],
9f1b61 270     setTime: function( type, value ) {
c7776a 271         var index = this.allowedSetTime.indexOf( type ) + 1,
62fd2f 272             state = this.state,
M 273             date = (state.selectedDate || state.viewDate).clone(),
c7776a 274             nextType
M 275         ;
276
4ad788 277         // It is needed to set all the time properties
M 278         // to not to reset the time
c7776a 279         date[ type ]( value );
M 280         for (; index < this.allowedSetTime.length; index++) {
281             nextType = this.allowedSetTime[index];
282             date[ nextType ]( date[nextType]() );
283         }
4ad788 284
9f1b61 285         if ( !this.props.value ) {
c658ad 286             this.setState({
M 287                 selectedDate: date,
62fd2f 288                 inputValue: date.format( state.inputFormat )
c658ad 289             });
M 290         }
4e9d38 291         this.props.onChange( date );
c7776a 292     },
M 293
1fdc4e 294     updateSelectedDate: function( e, close ) {
c7776a 295         var target = e.target,
c37f80 296             modifier = 0,
62fd2f 297             viewDate = this.state.viewDate,
M 298             currentDate = this.state.selectedDate || viewDate,
c37f80 299             date
2bcc09 300         ;
c7776a 301
9f1b61 302         if (target.className.indexOf('rdtDay') !== -1) {
462115 303             if (target.className.indexOf('rdtNew') !== -1)
d1be3f 304                 modifier = 1;
462115 305             else if (target.className.indexOf('rdtOld') !== -1)
d1be3f 306                 modifier = -1;
c7776a 307
d1be3f 308             date = viewDate.clone()
SA 309                 .month( viewDate.month() + modifier )
462115 310                 .date( parseInt( target.getAttribute('data-value'), 10 ) );
9f1b61 311         } else if (target.className.indexOf('rdtMonth') !== -1) {
d1be3f 312             date = viewDate.clone()
462115 313                 .month( parseInt( target.getAttribute('data-value'), 10 ) )
SE 314                 .date( currentDate.date() );
9f1b61 315         } else if (target.className.indexOf('rdtYear') !== -1) {
d1be3f 316             date = viewDate.clone()
SA 317                 .month( currentDate.month() )
318                 .date( currentDate.date() )
462115 319                 .year( parseInt( target.getAttribute('data-value'), 10 ) );
d1be3f 320         }
SA 321
322         date.hours( currentDate.hours() )
c7776a 323             .minutes( currentDate.minutes() )
M 324             .seconds( currentDate.seconds() )
462115 325             .milliseconds( currentDate.milliseconds() );
c7776a 326
9f1b61 327         if ( !this.props.value ) {
794700 328             var open = !( this.props.closeOnSelect && close );
SE 329             if ( !open ) {
330                 this.props.onBlur( date );
331             }
332
c658ad 333             this.setState({
M 334                 selectedDate: date,
335                 viewDate: date.clone().startOf('month'),
50a0c2 336                 inputValue: date.format( this.state.inputFormat ),
794700 337                 open: open
c658ad 338             });
462115 339         } else {
794700 340             if ( this.props.closeOnSelect && close ) {
50a0c2 341                 this.closeCalendar();
M 342             }
c658ad 343         }
4e9d38 344
M 345         this.props.onChange( date );
c7776a 346     },
M 347
348     openCalendar: function() {
aca9e6 349         if (!this.state.open) {
f72983 350             this.setState({ open: true }, function() {
GV 351                 this.props.onFocus();
352             });
aca9e6 353         }
c7776a 354     },
M 355
1fdc4e 356     closeCalendar: function() {
f72983 357         this.setState({ open: false }, function () {
GV 358             this.props.onBlur( this.state.selectedDate || this.state.inputValue );
359         });
1fdc4e 360     },
EC 361
9f1b61 362     handleClickOutside: function() {
SE 363         if ( this.props.input && this.state.open && !this.props.open ) {
f72983 364             this.setState({ open: false }, function() {
GV 365                 this.props.onBlur( this.state.selectedDate || this.state.inputValue );
366             });
62fd2f 367         }
c7776a 368     },
M 369
64fc6a 370     localMoment: function( date, format, props ) {
SE 371         props = props || this.props;
372         var momentFn = props.utc ? moment.utc : moment;
373         var m = momentFn( date, format, props.strictParsing );
374         if ( props.locale )
375             m.locale( props.locale );
c37f80 376         return m;
M 377     },
378
c7776a 379     componentProps: {
0b3475 380         fromProps: ['value', 'isValidDate', 'renderDay', 'renderMonth', 'renderYear', 'timeConstraints'],
d1be3f 381         fromState: ['viewDate', 'selectedDate', 'updateOn'],
11612b 382         fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateSelectedDate', 'localMoment', 'handleClickOutside']
c7776a 383     },
M 384
9f1b61 385     getComponentProps: function() {
c7776a 386         var me = this,
a3a33b 387             formats = this.getFormats( this.props ),
M 388             props = {dateFormat: formats.date, timeFormat: formats.time}
c7776a 389         ;
M 390
9f1b61 391         this.componentProps.fromProps.forEach( function( name ) {
c7776a 392             props[ name ] = me.props[ name ];
M 393         });
9f1b61 394         this.componentProps.fromState.forEach( function( name ) {
c7776a 395             props[ name ] = me.state[ name ];
M 396         });
9f1b61 397         this.componentProps.fromThis.forEach( function( name ) {
c7776a 398             props[ name ] = me[ name ];
M 399         });
400
401         return props;
402     },
403
404     render: function() {
a50b2e 405         var className = 'rdt' + (this.props.className ?
386942 406                   ( Array.isArray( this.props.className ) ?
SE 407                   ' ' + this.props.className.join( ' ' ) : ' ' + this.props.className) : ''),
a3a33b 408             children = []
M 409         ;
410
9f1b61 411         if ( this.props.input ) {
a50b2e 412             children = [ React.createElement('input', assign({
18dc17 413                 key: 'i',
9f1b61 414                 type: 'text',
2bb9ca 415                 className: 'form-control',
d76f7b 416                 onFocus: this.openCalendar,
c658ad 417                 onChange: this.onInputChange,
9012e8 418                 onKeyDown: this.onInputKey,
d76f7b 419                 value: this.state.inputValue
a3a33b 420             }, this.props.inputProps ))];
462115 421         } else {
a3a33b 422             className += ' rdtStatic';
M 423         }
d76f7b 424
462115 425         if ( this.state.open )
a3a33b 426             className += ' rdtOpen';
M 427
a50b2e 428         return React.createElement('div', {className: className}, children.concat(
GL 429             React.createElement('div',
a3a33b 430                 { key: 'dt', className: 'rdtPicker' },
e09432 431                 React.createElement( CalendarContainer, {view: this.state.currentView, viewProps: this.getComponentProps(), onClickOutside: this.handleClickOutside })
d76f7b 432             )
a3a33b 433         ));
c7776a 434     }
47e834 435 });
LC 436
cc4dda 437 // Make moment accessible through the Datetime class
M 438 Datetime.moment = moment;
439
9fb8e8 440 module.exports = Datetime;