Layne Anderson
2017-01-08 583af6d199035baa66dd99bf7cbc9014e5ad0ff3
commit | author | age
c7776a 1 'use strict';
417bf4 2
c7776a 3 var assign = require('object-assign'),
4ad788 4     React = require('react'),
d76f7b 5     DaysView = require('./src/DaysView'),
M 6     MonthsView = require('./src/MonthsView'),
7     YearsView = require('./src/YearsView'),
8     TimeView = require('./src/TimeView'),
4ad788 9     moment = require('moment')
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() {
4e9d38 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
75     getStateFromProps: function( props ){
76         var formats = this.getFormats( props ),
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
113     getUpdateOn: function(formats){
462115 114         if ( formats.date.match(/[lLD]/) ){
SE 115             return 'days';
d1be3f 116         }
462115 117         else if ( formats.date.indexOf('M') !== -1 ){
SE 118             return 'months';
92a2c6 119         }
462115 120         else if ( formats.date.indexOf('Y') !== -1 ){
SE 121             return 'years';
92a2c6 122         }
M 123
124         return 'days';
c7776a 125     },
aca70a 126
c7776a 127     getFormats: function( props ){
M 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
462115 135         if ( formats.date === true ){
3515a4 136             formats.date = locale.longDateFormat('L');
c7776a 137         }
462115 138         else if ( this.getUpdateOn(formats) !== 'days' ){
92a2c6 139             formats.time = '';
M 140         }
141
462115 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
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
583af6 164         if ( update.open === undefined ) {
LA 165             if ( this.props.closeOnSelect && this.state.currentView !== 'time' ) {
a8a17a 166                 update.open = false;
M 167             }
462115 168             else {
a8a17a 169                 update.open = this.state.open;
M 170             }
171         }
583af6 172         
LA 173         if ( nextProps.viewMode !== this.props.viewMode ) {
174             update.currentView = nextProps.viewMode;
175         }
a8a17a 176
c658ad 177         this.setState( update );
M 178     },
179
180     onInputChange: function( e ) {
462115 181         var value = e.target === null ? e : e.target.value,
c658ad 182             localMoment = this.localMoment( value, this.state.inputFormat ),
M 183             update = { inputValue: value }
184         ;
185
186         if ( localMoment.isValid() && !this.props.value ) {
187             update.selectedDate = localMoment;
462115 188             update.viewDate = localMoment.clone().startOf('month');
c658ad 189         }
62fd2f 190         else {
M 191             update.selectedDate = null;
192         }
c658ad 193
M 194         return this.setState( update, function() {
62fd2f 195             return this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue );
c7776a 196         });
M 197     },
198
9012e8 199     onInputKey: function( e ){
0b3475 200         if ( e.which === 9 && this.props.closeOnTab ){
9012e8 201             this.closeCalendar();
M 202         }
c7776a 203     },
M 204
205     showView: function( view ){
206         var me = this;
462115 207         return function(){
c7776a 208             me.setState({ currentView: view });
M 209         };
210     },
211
212     setDate: function( type ){
213         var me = this,
4ad788 214             nextViews = {
M 215                 month: 'days',
216                 year: 'months'
217             }
c7776a 218         ;
M 219         return function( e ){
220             me.setState({
462115 221                 viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.getAttribute('data-value'), 10) ).startOf( type ),
c7776a 222                 currentView: nextViews[ type ]
M 223             });
9fb8e8 224         };
c7776a 225     },
M 226
227     addTime: function( amount, type, toSelected ){
228         return this.updateTime( 'add', amount, type, toSelected );
229     },
9fb8e8 230
c7776a 231     subtractTime: function( amount, type, toSelected ){
M 232         return this.updateTime( 'subtract', amount, type, toSelected );
233     },
9fb8e8 234
c7776a 235     updateTime: function( op, amount, type, toSelected ){
M 236         var me = this;
237
238         return function(){
239             var update = {},
240                 date = toSelected ? 'selectedDate' : 'viewDate'
241             ;
242
243             update[ date ] = me.state[ date ].clone()[ op ]( amount, type );
244
245             me.setState( update );
246         };
247     },
248
462115 249     allowedSetTime: ['hours', 'minutes', 'seconds', 'milliseconds'],
c7776a 250     setTime: function( type, value ){
M 251         var index = this.allowedSetTime.indexOf( type ) + 1,
62fd2f 252             state = this.state,
M 253             date = (state.selectedDate || state.viewDate).clone(),
c7776a 254             nextType
M 255         ;
256
4ad788 257         // It is needed to set all the time properties
M 258         // to not to reset the time
c7776a 259         date[ type ]( value );
M 260         for (; index < this.allowedSetTime.length; index++) {
261             nextType = this.allowedSetTime[index];
262             date[ nextType ]( date[nextType]() );
263         }
4ad788 264
462115 265         if ( !this.props.value ){
c658ad 266             this.setState({
M 267                 selectedDate: date,
62fd2f 268                 inputValue: date.format( state.inputFormat )
c658ad 269             });
M 270         }
4e9d38 271         this.props.onChange( date );
c7776a 272     },
M 273
1fdc4e 274     updateSelectedDate: function( e, close ) {
c7776a 275         var target = e.target,
c37f80 276             modifier = 0,
62fd2f 277             viewDate = this.state.viewDate,
M 278             currentDate = this.state.selectedDate || viewDate,
c37f80 279             date
50a0c2 280     ;
c7776a 281
462115 282         if (target.className.indexOf('rdtDay') !== -1){
SE 283             if (target.className.indexOf('rdtNew') !== -1)
d1be3f 284                 modifier = 1;
462115 285             else if (target.className.indexOf('rdtOld') !== -1)
d1be3f 286                 modifier = -1;
c7776a 287
d1be3f 288             date = viewDate.clone()
SA 289                 .month( viewDate.month() + modifier )
462115 290                 .date( parseInt( target.getAttribute('data-value'), 10 ) );
SE 291         } else if (target.className.indexOf('rdtMonth') !== -1){
d1be3f 292             date = viewDate.clone()
462115 293                 .month( parseInt( target.getAttribute('data-value'), 10 ) )
SE 294                 .date( currentDate.date() );
295         } else if (target.className.indexOf('rdtYear') !== -1){
d1be3f 296             date = viewDate.clone()
SA 297                 .month( currentDate.month() )
298                 .date( currentDate.date() )
462115 299                 .year( parseInt( target.getAttribute('data-value'), 10 ) );
d1be3f 300         }
SA 301
302         date.hours( currentDate.hours() )
c7776a 303             .minutes( currentDate.minutes() )
M 304             .seconds( currentDate.seconds() )
462115 305             .milliseconds( currentDate.milliseconds() );
c7776a 306
462115 307         if ( !this.props.value ){
c658ad 308             this.setState({
M 309                 selectedDate: date,
310                 viewDate: date.clone().startOf('month'),
50a0c2 311                 inputValue: date.format( this.state.inputFormat ),
M 312                 open: !(this.props.closeOnSelect && close )
c658ad 313             });
462115 314         } else {
50a0c2 315             if (this.props.closeOnSelect && close) {
M 316                 this.closeCalendar();
317             }
c658ad 318         }
4e9d38 319
M 320         this.props.onChange( date );
c7776a 321     },
M 322
323     openCalendar: function() {
aca9e6 324         if (!this.state.open) {
f72983 325             this.setState({ open: true }, function() {
GV 326                 this.props.onFocus();
327             });
aca9e6 328         }
c7776a 329     },
M 330
1fdc4e 331     closeCalendar: function() {
f72983 332         this.setState({ open: false }, function () {
GV 333             this.props.onBlur( this.state.selectedDate || this.state.inputValue );
334         });
1fdc4e 335     },
EC 336
c7776a 337     handleClickOutside: function(){
462115 338         if ( this.props.input && this.state.open && !this.props.open ){
f72983 339             this.setState({ open: false }, function() {
GV 340                 this.props.onBlur( this.state.selectedDate || this.state.inputValue );
341             });
62fd2f 342         }
c7776a 343     },
M 344
c658ad 345     localMoment: function( date, format ){
049c33 346         var momentFn = this.props.utc ? moment.utc : moment;
TS 347         var m = momentFn( date, format, this.props.strictParsing );
462115 348         if ( this.props.locale )
c37f80 349             m.locale( this.props.locale );
M 350         return m;
351     },
352
c7776a 353     componentProps: {
0b3475 354         fromProps: ['value', 'isValidDate', 'renderDay', 'renderMonth', 'renderYear', 'timeConstraints'],
d1be3f 355         fromState: ['viewDate', 'selectedDate', 'updateOn'],
c658ad 356         fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateSelectedDate', 'localMoment']
c7776a 357     },
M 358
359     getComponentProps: function(){
360         var me = this,
a3a33b 361             formats = this.getFormats( this.props ),
M 362             props = {dateFormat: formats.date, timeFormat: formats.time}
c7776a 363         ;
M 364
365         this.componentProps.fromProps.forEach( function( name ){
366             props[ name ] = me.props[ name ];
367         });
368         this.componentProps.fromState.forEach( function( name ){
369             props[ name ] = me.state[ name ];
370         });
371         this.componentProps.fromThis.forEach( function( name ){
372             props[ name ] = me[ name ];
373         });
374
375         return props;
376     },
377
378     render: function() {
d76f7b 379         var Component = this.viewComponents[ this.state.currentView ],
a3a33b 380             DOM = React.DOM,
386942 381             className = 'rdt' + (this.props.className ?
SE 382                   ( Array.isArray( this.props.className ) ?
383                   ' ' + this.props.className.join( ' ' ) : ' ' + this.props.className) : ''),
a3a33b 384             children = []
M 385         ;
386
462115 387         if ( this.props.input ){
a3a33b 388             children = [ DOM.input( assign({
18dc17 389                 key: 'i',
d76f7b 390                 type:'text',
2bb9ca 391                 className: 'form-control',
d76f7b 392                 onFocus: this.openCalendar,
c658ad 393                 onChange: this.onInputChange,
9012e8 394                 onKeyDown: this.onInputKey,
d76f7b 395                 value: this.state.inputValue
a3a33b 396             }, this.props.inputProps ))];
462115 397         } else {
a3a33b 398             className += ' rdtStatic';
M 399         }
d76f7b 400
462115 401         if ( this.state.open )
a3a33b 402             className += ' rdtOpen';
M 403
404         return DOM.div({className: className}, children.concat(
405             DOM.div(
406                 { key: 'dt', className: 'rdtPicker' },
407                 React.createElement( Component, this.getComponentProps())
d76f7b 408             )
a3a33b 409         ));
c7776a 410     }
47e834 411 });
LC 412
cc4dda 413 // Make moment accessible through the Datetime class
M 414 Datetime.moment = moment;
415
9fb8e8 416 module.exports = Datetime;