Simon Egersand
2017-12-01 d0b63bcd5330053a64331014be9e118c66205e80
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 ) {
d0b63b 155             if ( typeof nextProps.open !== 'undefined' ) {
SE 156                 updatedState.open = nextProps.open;
157             } else if ( this.props.closeOnSelect && this.state.currentView !== 'time' ) {
fee412 158                 updatedState.open = false;
SE 159             } else {
160                 updatedState.open = this.state.open;
161             }
433f26 162         }
SE 163
583af6 164         if ( nextProps.viewMode !== this.props.viewMode ) {
64fc6a 165             updatedState.currentView = nextProps.viewMode;
583af6 166         }
a8a17a 167
64fc6a 168         if ( nextProps.locale !== this.props.locale ) {
SE 169             if ( this.state.viewDate ) {
170                 var updatedViewDate = this.state.viewDate.clone().locale( nextProps.locale );
171                 updatedState.viewDate = updatedViewDate;
172             }
173             if ( this.state.selectedDate ) {
174                 var updatedSelectedDate = this.state.selectedDate.clone().locale( nextProps.locale );
175                 updatedState.selectedDate = updatedSelectedDate;
176                 updatedState.inputValue = updatedSelectedDate.format( formats.datetime );
177             }
178         }
179
180         if ( nextProps.utc !== this.props.utc ) {
181             if ( nextProps.utc ) {
182                 if ( this.state.viewDate )
183                     updatedState.viewDate = this.state.viewDate.clone().utc();
184                 if ( this.state.selectedDate ) {
185                     updatedState.selectedDate = this.state.selectedDate.clone().utc();
186                     updatedState.inputValue = updatedState.selectedDate.format( formats.datetime );
187                 }
188             } else {
189                 if ( this.state.viewDate )
190                     updatedState.viewDate = this.state.viewDate.clone().local();
191                 if ( this.state.selectedDate ) {
192                     updatedState.selectedDate = this.state.selectedDate.clone().local();
193                     updatedState.inputValue = updatedState.selectedDate.format(formats.datetime);
194                 }
195             }
196         }
39b827 197         //we should only show a valid date if we are provided a isValidDate function. Removed in 2.10.3
LA 198         /*if (this.props.isValidDate) {
9509fa 199             updatedState.viewDate = updatedState.viewDate || this.state.viewDate;
JC 200             while (!this.props.isValidDate(updatedState.viewDate)) {
201                 updatedState.viewDate = updatedState.viewDate.add(1, 'day');
202             }
39b827 203         }*/
64fc6a 204         this.setState( updatedState );
c658ad 205     },
M 206
207     onInputChange: function( e ) {
462115 208         var value = e.target === null ? e : e.target.value,
c658ad 209             localMoment = this.localMoment( value, this.state.inputFormat ),
M 210             update = { inputValue: value }
cf3d92 211             ;
c658ad 212
M 213         if ( localMoment.isValid() && !this.props.value ) {
214             update.selectedDate = localMoment;
462115 215             update.viewDate = localMoment.clone().startOf('month');
2bcc09 216         } else {
62fd2f 217             update.selectedDate = null;
M 218         }
c658ad 219
M 220         return this.setState( update, function() {
62fd2f 221             return this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue );
c7776a 222         });
M 223     },
224
9f1b61 225     onInputKey: function( e ) {
SE 226         if ( e.which === 9 && this.props.closeOnTab ) {
9012e8 227             this.closeCalendar();
M 228         }
c7776a 229     },
M 230
9f1b61 231     showView: function( view ) {
c7776a 232         var me = this;
9f1b61 233         return function() {
5377a9 234             me.state.currentView !== view && me.props.onViewModeChange( view );
c7776a 235             me.setState({ currentView: view });
M 236         };
237     },
238
9f1b61 239     setDate: function( type ) {
c7776a 240         var me = this,
4ad788 241             nextViews = {
M 242                 month: 'days',
243                 year: 'months'
244             }
c7776a 245         ;
9f1b61 246         return function( e ) {
c7776a 247             me.setState({
462115 248                 viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.getAttribute('data-value'), 10) ).startOf( type ),
c7776a 249                 currentView: nextViews[ type ]
M 250             });
5377a9 251             me.props.onViewModeChange( nextViews[ type ] );
9fb8e8 252         };
c7776a 253     },
M 254
9f1b61 255     addTime: function( amount, type, toSelected ) {
c7776a 256         return this.updateTime( 'add', amount, type, toSelected );
M 257     },
9fb8e8 258
9f1b61 259     subtractTime: function( amount, type, toSelected ) {
c7776a 260         return this.updateTime( 'subtract', amount, type, toSelected );
M 261     },
9fb8e8 262
9f1b61 263     updateTime: function( op, amount, type, toSelected ) {
c7776a 264         var me = this;
M 265
9f1b61 266         return function() {
c7776a 267             var update = {},
M 268                 date = toSelected ? 'selectedDate' : 'viewDate'
269             ;
270
271             update[ date ] = me.state[ date ].clone()[ op ]( amount, type );
272
273             me.setState( update );
274         };
275     },
276
462115 277     allowedSetTime: ['hours', 'minutes', 'seconds', 'milliseconds'],
9f1b61 278     setTime: function( type, value ) {
c7776a 279         var index = this.allowedSetTime.indexOf( type ) + 1,
62fd2f 280             state = this.state,
M 281             date = (state.selectedDate || state.viewDate).clone(),
c7776a 282             nextType
cf3d92 283             ;
c7776a 284
4ad788 285         // It is needed to set all the time properties
M 286         // to not to reset the time
c7776a 287         date[ type ]( value );
M 288         for (; index < this.allowedSetTime.length; index++) {
289             nextType = this.allowedSetTime[index];
290             date[ nextType ]( date[nextType]() );
291         }
4ad788 292
9f1b61 293         if ( !this.props.value ) {
c658ad 294             this.setState({
M 295                 selectedDate: date,
62fd2f 296                 inputValue: date.format( state.inputFormat )
c658ad 297             });
M 298         }
4e9d38 299         this.props.onChange( date );
c7776a 300     },
M 301
1fdc4e 302     updateSelectedDate: function( e, close ) {
c7776a 303         var target = e.target,
c37f80 304             modifier = 0,
62fd2f 305             viewDate = this.state.viewDate,
M 306             currentDate = this.state.selectedDate || viewDate,
c37f80 307             date
cf3d92 308             ;
c7776a 309
9f1b61 310         if (target.className.indexOf('rdtDay') !== -1) {
462115 311             if (target.className.indexOf('rdtNew') !== -1)
d1be3f 312                 modifier = 1;
462115 313             else if (target.className.indexOf('rdtOld') !== -1)
d1be3f 314                 modifier = -1;
c7776a 315
d1be3f 316             date = viewDate.clone()
SA 317                 .month( viewDate.month() + modifier )
462115 318                 .date( parseInt( target.getAttribute('data-value'), 10 ) );
9f1b61 319         } else if (target.className.indexOf('rdtMonth') !== -1) {
d1be3f 320             date = viewDate.clone()
462115 321                 .month( parseInt( target.getAttribute('data-value'), 10 ) )
SE 322                 .date( currentDate.date() );
9f1b61 323         } else if (target.className.indexOf('rdtYear') !== -1) {
d1be3f 324             date = viewDate.clone()
SA 325                 .month( currentDate.month() )
326                 .date( currentDate.date() )
462115 327                 .year( parseInt( target.getAttribute('data-value'), 10 ) );
d1be3f 328         }
SA 329
330         date.hours( currentDate.hours() )
c7776a 331             .minutes( currentDate.minutes() )
M 332             .seconds( currentDate.seconds() )
462115 333             .milliseconds( currentDate.milliseconds() );
c7776a 334
9f1b61 335         if ( !this.props.value ) {
794700 336             var open = !( this.props.closeOnSelect && close );
SE 337             if ( !open ) {
338                 this.props.onBlur( date );
339             }
340
c658ad 341             this.setState({
M 342                 selectedDate: date,
343                 viewDate: date.clone().startOf('month'),
50a0c2 344                 inputValue: date.format( this.state.inputFormat ),
794700 345                 open: open
c658ad 346             });
462115 347         } else {
794700 348             if ( this.props.closeOnSelect && close ) {
50a0c2 349                 this.closeCalendar();
M 350             }
c658ad 351         }
4e9d38 352
M 353         this.props.onChange( date );
c7776a 354     },
M 355
689227 356     openCalendar: function( e ) {
SE 357         if ( !this.state.open ) {
f72983 358             this.setState({ open: true }, function() {
689227 359                 this.props.onFocus( e );
f72983 360             });
aca9e6 361         }
c7776a 362     },
M 363
1fdc4e 364     closeCalendar: function() {
f72983 365         this.setState({ open: false }, function () {
GV 366             this.props.onBlur( this.state.selectedDate || this.state.inputValue );
367         });
1fdc4e 368     },
EC 369
9f1b61 370     handleClickOutside: function() {
SE 371         if ( this.props.input && this.state.open && !this.props.open ) {
f72983 372             this.setState({ open: false }, function() {
GV 373                 this.props.onBlur( this.state.selectedDate || this.state.inputValue );
374             });
62fd2f 375         }
c7776a 376     },
M 377
64fc6a 378     localMoment: function( date, format, props ) {
SE 379         props = props || this.props;
380         var momentFn = props.utc ? moment.utc : moment;
381         var m = momentFn( date, format, props.strictParsing );
382         if ( props.locale )
383             m.locale( props.locale );
c37f80 384         return m;
M 385     },
386
c7776a 387     componentProps: {
0b3475 388         fromProps: ['value', 'isValidDate', 'renderDay', 'renderMonth', 'renderYear', 'timeConstraints'],
d1be3f 389         fromState: ['viewDate', 'selectedDate', 'updateOn'],
11612b 390         fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateSelectedDate', 'localMoment', 'handleClickOutside']
c7776a 391     },
M 392
9f1b61 393     getComponentProps: function() {
c7776a 394         var me = this,
a3a33b 395             formats = this.getFormats( this.props ),
M 396             props = {dateFormat: formats.date, timeFormat: formats.time}
cf3d92 397             ;
c7776a 398
9f1b61 399         this.componentProps.fromProps.forEach( function( name ) {
c7776a 400             props[ name ] = me.props[ name ];
M 401         });
9f1b61 402         this.componentProps.fromState.forEach( function( name ) {
c7776a 403             props[ name ] = me.state[ name ];
M 404         });
9f1b61 405         this.componentProps.fromThis.forEach( function( name ) {
c7776a 406             props[ name ] = me[ name ];
M 407         });
408
409         return props;
410     },
411
412     render: function() {
f4e62d 413         // TODO: Make a function or clean up this code,
SE 414         // logic right now is really hard to follow
a50b2e 415         var className = 'rdt' + (this.props.className ?
386942 416                   ( Array.isArray( this.props.className ) ?
SE 417                   ' ' + this.props.className.join( ' ' ) : ' ' + this.props.className) : ''),
cf3d92 418             children = [];
a3a33b 419
9f1b61 420         if ( this.props.input ) {
b6f2dd 421             var finalInputProps = assign({
DF 422                 type: 'text',
423                 className: 'form-control',
424                 onClick: this.openCalendar,
425                 onFocus: this.openCalendar,
426                 onChange: this.onInputChange,
427                 onKeyDown: this.onInputKey,
428                 value: this.state.inputValue,
429             }, this.props.inputProps);
b8a9a7 430             if ( this.props.renderInput ) {
b6f2dd 431                 children = [ React.createElement('div', { key: 'i' }, this.props.renderInput( finalInputProps, this.openCalendar )) ];
b8a9a7 432             } else {
b6f2dd 433                 children = [ React.createElement('input', assign({ key: 'i' }, finalInputProps ))];
b8a9a7 434             }
462115 435         } else {
a3a33b 436             className += ' rdtStatic';
M 437         }
d76f7b 438
462115 439         if ( this.state.open )
a3a33b 440             className += ' rdtOpen';
M 441
f37c3f 442         return React.createElement( 'div', { className: className }, children.concat(
SE 443             React.createElement( 'div',
a3a33b 444                 { key: 'dt', className: 'rdtPicker' },
f37c3f 445                 React.createElement( CalendarContainer, { view: this.state.currentView, viewProps: this.getComponentProps(), onClickOutside: this.handleClickOutside })
d76f7b 446             )
a3a33b 447         ));
c7776a 448     }
47e834 449 });
LC 450
cc4dda 451 // Make moment accessible through the Datetime class
M 452 Datetime.moment = moment;
453
9fb8e8 454 module.exports = Datetime;