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