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