diff --git a/.babelrc b/.babelrc
new file mode 100644
index 000000000..2d42f2173
--- /dev/null
+++ b/.babelrc
@@ -0,0 +1,9 @@
+{
+ "presets": [
+ "@babel/preset-react",
+ "@babel/preset-env"
+ ],
+ "plugins": [
+ "@babel/plugin-proposal-class-properties"
+ ]
+}
\ No newline at end of file
diff --git a/.eslintrc.js b/.eslintrc.js
index 0c024d710..33d30ef45 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -1,5 +1,6 @@
module.exports = {
"env": {
+ "es6": true,
"browser": true
},
"globals": {
@@ -30,9 +31,17 @@ module.exports = {
"semi": 2,
// Enforce consistent spacing before and after semicolons
"semi-spacing": 2,
+ // Enforce consistent spacing before blocks
+ "space-before-blocks": 2,
// Enforce consistent spacing inside parentheses
// "space-in-parens": [2, "always"],
// Enforce the consistent use of either backticks, double, or single quotes
- "quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }]
- }
+ "quotes": [2, "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
+ // Enforce using tabs for indentation
+ "indent": [2, "tab", { "SwitchCase": 1 }]
+ },
+ "parserOptions": {
+ "sourceType": "module"
+ },
+ "extends": "react-app"
};
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
new file mode 100644
index 000000000..7f9429e7f
--- /dev/null
+++ b/.github/CONTRIBUTING.md
@@ -0,0 +1,42 @@
+# Contributing
+:raised_hands::tada: First off, thanks for taking the time to contribute! :tada::raised_hands:
+
+The following is a set of guidelines for contributing to react-datetime. The purpose of these
+guidelines is to maintain a high quality of code *and* traceability. Please respect these
+guidelines.
+
+## General
+This repository use tests and a linter as automatic tools to maintain the quality of the code.
+These two tasks are run locally on your machine before every commit (as a pre-commit git hook),
+if any test fail or the linter gives an error the commit will not be created. They are also run on
+a Travis CI machine when you create a pull request, and the PR will not be merged unless Travis
+says all tests and the linting pass.
+
+## Git Commit Messages
+* Use the present tense ("Add feature" not "Added feature")
+* Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
+ * Think of it as you are *commanding* what your commit is doing
+ * Git itself uses the imperative whenever it creates a commit on your behalf, so it makes sense
+ for you to use it too
+* Use the body to explain *what* and *why*
+ * If the commit is non-trivial, please provide more detailed information in the commit body
+ message
+ * *How* you made the change is visible in the code and is therefore rarely necessary to include
+ in the commit body message, but *why* you made the change is often harder to guess and is
+ therefore useful to include in the commit body message
+
+[Here's a nice blog post on how to write great git messages.](http://chris.beams.io/posts/git-commit/)
+
+## Pull Requests
+* Follow the current code style
+* Write tests for your changes
+* Document your changes in the README if it's needed
+* End files with a newline
+* There's no need to create a new build for each pull request, we (the maintainers) do this when we
+ release a new version
+
+## Issues
+* Please be descriptive when you fill in the issue template, this will greatly help us maintainers
+ in helping you which will lead to your issue being resolved faster
+* Feature requests are very welcomed, but not every feature that is requested can be guaranteed
+ to be implemented
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 000000000..ae97d57ff
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,60 @@
+
+
+
+### I'm Submitting a ...
+
+```
+[ ] Bug report
+[ ] Feature request
+[ ] Support request
+```
+
+### Steps to Reproduce
+
+
+### Expected Results
+
+
+### Actual Results
+
+
+### Minimal Reproduction of the Problem
+
+
+### Other Information (e.g. stacktraces, related issues, suggestions how to fix)
+
+
+
+
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 000000000..16511b84d
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,34 @@
+
+
+### Description
+
+
+### Motivation and Context
+
+
+### Checklist
+
+```
+[ ] I have not included any built dist files (us maintainers do that prior to a new release)
+[ ] I have added tests covering my changes
+[ ] All new and existing tests pass
+[ ] My changes required the documentation to be updated
+ [ ] I have updated the documentation accordingly
+ [ ] I have updated the TypeScript 1.8 type definitions accordingly
+ [ ] I have updated the TypeScript 2.0+ type definitions accordingly
+```
+
+
+
diff --git a/.gitignore b/.gitignore
index ef15daab9..5a38e4006 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,9 @@
*~
node_modules
+.idea
+tmp
.DS_Store
npm-debug.log
-test_bundle.js
-test-built/*
-.idea
-docs/*.html
-docs/assets/bundle.js
-lib/*
+
+# Don't force sha validation (it differs depending on the OS)
+package-lock.json
\ No newline at end of file
diff --git a/.npmignore b/.npmignore
index c2388fa48..3bd16454e 100644
--- a/.npmignore
+++ b/.npmignore
@@ -1,12 +1,11 @@
-*~
+# Folders
node_modules
+example
+.idea
+test
+
+# Files
+*~
.DS_Store
npm-debug.log
-test_bundle.js
-test-built
-.idea
-examples
-bower.json
webpack.config.js
-TODO.md
-karma.dev.js
diff --git a/.travis.yml b/.travis.yml
index 55bcb3a81..5c5b7fded 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,7 +1,14 @@
language: node_js
sudo: false
+os:
+ - linux
node_js:
-- '4'
+ - '8'
+ - 'stable'
script:
-- npm run lint
-- npm run test
+ - npm run lint
+ - npm run test:all
+before_install:
+- export TZ=Europe/Stockholm
+notifications:
+ email: false
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 000000000..6082ce4cc
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,5 @@
+{
+ "editor.codeActionsOnSave": {
+ "source.fixAll.eslint": true
+ }
+}
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a481cb259..255ac5d54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,186 @@
Changelog
=========
+## 3.3.1
+* Restores compatibility with React ^16.5.0
+
+## 3.3.0
+* Adds support for React 19
+
+## 3.2.0
+* Adds support for React 18
+
+## 3.1.0
+* Adds support for React 17
+
+## 3.0.3
+* Localize AM and PM strings
+* Make calendar fluid width
+* Fixes findDOMNode deprecated warning in Strict Mode - Thanks @kkalve
+* Simplification of the base code - Thanks @onlined
+
+## 3.0.2
+* Fixes typescript typings not being exposed publicly
+
+## 3.0.1
+* Big refactor, the state is not derived from the props after every update.
+* `disableCloseOnClickOutside` prop is now `closeOnClickOutside` (avoid double negations).
+* `onBlur` and `onFocus` are renamed to `onClose` and `onOpen` since they had nothing to do with the blur event and it was misleading some users. If we want to listen to the input's `onBlur` and `onFocus` use `inputProps`.
+* `defaultValue` prop is now called `initialValue`.
+* Updated typescript definitions.
+* Time is not updated anymore on right clicks.
+* Creates `renderView` prop to customize the whole calendar.
+* Creates `updateOnView` prop to decide when to update the date.
+* `onViewModeChange` prop renamed to `onNavigate`.
+* Creates `onBeforeNavigate` prop.
+* Creates `setViewData` and `navigate` methods.
+* Fixes error clicking on days from the previous or next month in the days view.
+* Fixes month, year and time views for locales that doesn't use gregorian numbers.
+* Adds a playground to make simpler to try out the library by `npm run playground`.
+* Not depending on gulp to create the build anymore
+* Updated most of the dependencies.
+
+## 3.0.0
+- This version was published by error and can't be overriden. The first release for v3 branch is 3.0.1
+
+## 2.16.2
+* Turns moment timezone peer dependency in a runtime error when missing using `displayTimezone`.
+
+## 2.16.1
+* Fixes input event overriding
+
+## 2.16.0
+* The prop `disableOnClickOutside` has been renamed to `disableCloseOnClickOutside`
+* The calendar doesn't get closed an open when clicking in the input anymore.
+* Fixes errors not finding dates when customizing day rendering.
+* Event listeners in `inputProps` now only override default behaviour when returning `false`.
+* Adds the `displayTimeZone` prop. Thanks to @martingordon
+
+## 2.15.0
+* New `onNavigateBack` and `onNavigateForward` hooks thanks to @DaanDD and @simeg.
+* Touch improvements by @NicoDos
+* TS and debugging improvements
+
+## 2.14.0
+* Make `viewDate` dynamic
+
+## 2.13.0
+* Use more appropriate cursor for empty space in time picker and in day texts
+* Add `viewDate` prop that sets a value when opening the calendar when there is no selected date
+* Make `disableOnClickOutside` work as intended
+* Better touch support for tapping and holding
+* Use static property `defaultProps` instead of `getDefaultProps`
+
+## 2.12.0
+* The `renderInput` prop now receives `closeCalendar` function as well
+
+## 2.11.1
+* The open prop should now work as intended
+
+## 2.11.0
+* onFocus now receives the browser event
+* Do not open browser menu on right click of arrows in time view
+* Open calendar when onClick is triggered, before it would just react to onFocus
+* Update TypeScript definitions for value and defaultValue to comply with code
+* Fix bug where AM/PM would not sync between component value and input field value
+* Add renderInput prop which let's the consumer of the component render their own HTML input element
+
+## 2.10.3
+* Update react-onclickoutside dependency
+* Remove isValidDate check before rendering as implementation was causing crashes in some edge cases.
+
+## 2.10.2
+* Move @types/react back to devDependencies
+* Add [demo](https://codesandbox.io/s/boring-dew-uzln3) app.
+
+## 2.10.1
+* Fix build files.
+
+## 2.10.0
+* Add isValidDate check before rendering so it doesn't render with an invalid date.
+
+## 2.9.0
+* Trigger callback method on view mode changes
+
+## 2.8.11
+* Update TypeScript definitions
+* Replace deprecated React method with non-deprecated method
+
+## 2.8.10
+* Increase click area of arrows for changing day/month/year
+* Update code according to React 15.5.0
+ * Remove usage of React.createClass
+ * Use separate module for PropTypes
+
+## 2.8.9
+* Fixes issue where incorrect current month is shown
+
+## 2.8.8
+* Fixes issues introduced in v2.8.7 recognizing any calendar view as clickingOutside trigger
+
+## 2.8.7
+* Update react-onclickoutside dependency. That should fix most of the problems about closeOnSelect.
+
+## 2.8.6
+* Revert commits related to `closeOnSelect` that did not fix all issues they were meant to
+
+## 2.8.5
+* Fix bug where `closeOnSelect` was not closing when it was set to `true`
+* Fix bug where component would not immediately re-render when updating either `utc` or `locale` prop
+
+## 2.8.4
+* Fix bug where `closeOnSelect=true` would cause component to close on state change
+
+## 2.8.3
+* Fix `isValidDate` related bug where current month would be invalid
+* Trigger re-render of component when `viewMode` changes
+* Never append `rdtOld` class in year view
+
+## 2.8.2
+* Fix year related bug in tests where year was set to 2016
+* Add a yarnfile so yarn is now possible to use for installing dependencies
+
+## 2.8.1
+* Fix timeFormat related bug where 'A' was being picked up but not 'a', for setting 12-hour clock.
+
+## 2.8.0
+* Add typings for TypeScript 2.0. We now support TypeScript typings for versions 1.8 and 2.0.
+
+## 2.7.5
+* Bumps the version to skip buggy deployment 2.7.4
+
+## 2.7.4
+* Reverting updating `react` related dependencies. They were not the issue so they should not be set to the latest version of `react`.
+
+## 2.7.3
+* When updating `moment` to `2.16.0` something broke, hopefully by updating all `react` prefixed dependencies to `15.4.0` and changing the syntax in the dependency object a bit will resolve this issue.
+
+## 2.7.2
+* Bug fix: When setting `locale` and entering month view mode the component would sometimes freeze, depending on the locale. This has now been fixed.
+
+## 2.7.1
+* Bug fix: `onFocus` and `onBlur` were being called in a way causing state to reset. This unwanted behavior is now adjusted.
+
+## 2.7.0
+* `isValidDate` now supports months and years.
+* `utc` prop was added, by setting it to `true` input time values will be interpreted as UTC (Zulu time).
+* Bug fix: The input value now updates when `dateFormat` changes.
+* Removed the source-map file because the commit it was introduced in was causing the minified file to be bigger than the non-minified.
+
+## 2.6.2
+* Update file references in `package.json`
+
+## 2.6.1
+* Added a source-map file.
+* Fixed bug with invalid moment object.
+* Decreased npm package size by ~29.3KB.
+
+## 2.6.0
+* Fixed hover styles for days
+* Added multiple simultaneous datetime component support.
+* `className` prop now supports string arrays
+* Fixes 12:00am
+* Removed warning for missing element keys.
+
## 2.5.0
* Added pre-commit hook for tests.
* Added the `timeConstraints` prop.
diff --git a/DateTime.js b/DateTime.js
deleted file mode 100644
index 41eb5f3b2..000000000
--- a/DateTime.js
+++ /dev/null
@@ -1,401 +0,0 @@
-'use strict';
-
-var assign = require('object-assign'),
- React = require('react'),
- DaysView = require('./src/DaysView'),
- MonthsView = require('./src/MonthsView'),
- YearsView = require('./src/YearsView'),
- TimeView = require('./src/TimeView'),
- moment = require('moment')
-;
-
-var TYPES = React.PropTypes;
-var Datetime = React.createClass({
- mixins: [
- require('./src/onClickOutside')
- ],
- viewComponents: {
- days: DaysView,
- months: MonthsView,
- years: YearsView,
- time: TimeView
- },
- propTypes: {
- // value: TYPES.object | TYPES.string,
- // defaultValue: TYPES.object | TYPES.string,
- onFocus: TYPES.func,
- onBlur: TYPES.func,
- onChange: TYPES.func,
- locale: TYPES.string,
- input: TYPES.bool,
- // dateFormat: TYPES.string | TYPES.bool,
- // timeFormat: TYPES.string | TYPES.bool,
- inputProps: TYPES.object,
- timeConstraints: TYPES.object,
- viewMode: TYPES.oneOf(['years', 'months', 'days', 'time']),
- isValidDate: TYPES.func,
- open: TYPES.bool,
- strictParsing: TYPES.bool,
- closeOnSelect: TYPES.bool,
- closeOnTab: TYPES.bool
- },
-
- getDefaultProps: function() {
- var nof = function(){};
- return {
- className: '',
- defaultValue: '',
- inputProps: {},
- input: true,
- onFocus: nof,
- onBlur: nof,
- onChange: nof,
- timeFormat: true,
- timeConstraints: {},
- dateFormat: true,
- strictParsing: true,
- closeOnSelect: false,
- closeOnTab: true
- };
- },
-
- getInitialState: function() {
- var state = this.getStateFromProps( this.props );
-
- if ( state.open === undefined )
- state.open = !this.props.input;
-
- state.currentView = this.props.dateFormat ? (this.props.viewMode || state.updateOn || 'days') : 'time';
-
- return state;
- },
-
- getStateFromProps: function( props ){
- var formats = this.getFormats( props ),
- date = props.value || props.defaultValue,
- selectedDate, viewDate, updateOn
- ;
-
- if ( date && typeof date === 'string' )
- selectedDate = this.localMoment( date, formats.datetime );
- else if ( date )
- selectedDate = this.localMoment( date );
-
- if ( selectedDate && !selectedDate.isValid() )
- selectedDate = null;
-
- viewDate = selectedDate ?
- selectedDate.clone().startOf('month') :
- this.localMoment().startOf('month')
- ;
-
- updateOn = this.getUpdateOn(formats);
-
- return {
- updateOn: updateOn,
- inputFormat: formats.datetime,
- viewDate: viewDate,
- selectedDate: selectedDate,
- inputValue: selectedDate ? selectedDate.format( formats.datetime ) : (date || ''),
- open: props.open
- };
- },
-
- getUpdateOn: function(formats){
- if ( formats.date.match(/[lLD]/) ){
- return 'days';
- }
- else if ( formats.date.indexOf('M') !== -1 ){
- return 'months';
- }
- else if ( formats.date.indexOf('Y') !== -1 ){
- return 'years';
- }
-
- return 'days';
- },
-
- getFormats: function( props ){
- var formats = {
- date: props.dateFormat || '',
- time: props.timeFormat || ''
- },
- locale = this.localMoment( props.date ).localeData()
- ;
-
- if ( formats.date === true ){
- formats.date = locale.longDateFormat('L');
- }
- else if ( this.getUpdateOn(formats) !== 'days' ){
- formats.time = '';
- }
-
- if ( formats.time === true ){
- formats.time = locale.longDateFormat('LT');
- }
-
- formats.datetime = formats.date && formats.time ?
- formats.date + ' ' + formats.time :
- formats.date || formats.time
- ;
-
- return formats;
- },
-
- componentWillReceiveProps: function(nextProps) {
- var formats = this.getFormats( nextProps ),
- update = {}
- ;
-
- if ( nextProps.value !== this.props.value ){
- update = this.getStateFromProps( nextProps );
- }
- if ( formats.datetime !== this.getFormats( this.props ).datetime ) {
- update.inputFormat = formats.datetime;
- }
-
- if ( update.open === undefined ){
- if ( this.props.closeOnSelect && this.state.currentView !== 'time' ){
- update.open = false;
- }
- else {
- update.open = this.state.open;
- }
- }
-
- this.setState( update );
- },
-
- onInputChange: function( e ) {
- var value = e.target === null ? e : e.target.value,
- localMoment = this.localMoment( value, this.state.inputFormat ),
- update = { inputValue: value }
- ;
-
- if ( localMoment.isValid() && !this.props.value ) {
- update.selectedDate = localMoment;
- update.viewDate = localMoment.clone().startOf('month');
- }
- else {
- update.selectedDate = null;
- }
-
- return this.setState( update, function() {
- return this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue );
- });
- },
-
- onInputKey: function( e ){
- if ( e.which === 9 && this.props.closeOnTab ){
- this.closeCalendar();
- }
- },
-
- showView: function( view ){
- var me = this;
- return function(){
- me.setState({ currentView: view });
- };
- },
-
- setDate: function( type ){
- var me = this,
- nextViews = {
- month: 'days',
- year: 'months'
- }
- ;
- return function( e ){
- me.setState({
- viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.getAttribute('data-value'), 10) ).startOf( type ),
- currentView: nextViews[ type ]
- });
- };
- },
-
- addTime: function( amount, type, toSelected ){
- return this.updateTime( 'add', amount, type, toSelected );
- },
-
- subtractTime: function( amount, type, toSelected ){
- return this.updateTime( 'subtract', amount, type, toSelected );
- },
-
- updateTime: function( op, amount, type, toSelected ){
- var me = this;
-
- return function(){
- var update = {},
- date = toSelected ? 'selectedDate' : 'viewDate'
- ;
-
- update[ date ] = me.state[ date ].clone()[ op ]( amount, type );
-
- me.setState( update );
- };
- },
-
- allowedSetTime: ['hours', 'minutes', 'seconds', 'milliseconds'],
- setTime: function( type, value ){
- var index = this.allowedSetTime.indexOf( type ) + 1,
- state = this.state,
- date = (state.selectedDate || state.viewDate).clone(),
- nextType
- ;
-
- // It is needed to set all the time properties
- // to not to reset the time
- date[ type ]( value );
- for (; index < this.allowedSetTime.length; index++) {
- nextType = this.allowedSetTime[index];
- date[ nextType ]( date[nextType]() );
- }
-
- if ( !this.props.value ){
- this.setState({
- selectedDate: date,
- inputValue: date.format( state.inputFormat )
- });
- }
- this.props.onChange( date );
- },
-
- updateSelectedDate: function( e, close ) {
- var target = e.target,
- modifier = 0,
- viewDate = this.state.viewDate,
- currentDate = this.state.selectedDate || viewDate,
- date
- ;
-
- if (target.className.indexOf('rdtDay') !== -1){
- if (target.className.indexOf('rdtNew') !== -1)
- modifier = 1;
- else if (target.className.indexOf('rdtOld') !== -1)
- modifier = -1;
-
- date = viewDate.clone()
- .month( viewDate.month() + modifier )
- .date( parseInt( target.getAttribute('data-value'), 10 ) );
- } else if (target.className.indexOf('rdtMonth') !== -1){
- date = viewDate.clone()
- .month( parseInt( target.getAttribute('data-value'), 10 ) )
- .date( currentDate.date() );
- } else if (target.className.indexOf('rdtYear') !== -1){
- date = viewDate.clone()
- .month( currentDate.month() )
- .date( currentDate.date() )
- .year( parseInt( target.getAttribute('data-value'), 10 ) );
- }
-
- date.hours( currentDate.hours() )
- .minutes( currentDate.minutes() )
- .seconds( currentDate.seconds() )
- .milliseconds( currentDate.milliseconds() );
-
- if ( !this.props.value ){
- this.setState({
- selectedDate: date,
- viewDate: date.clone().startOf('month'),
- inputValue: date.format( this.state.inputFormat ),
- open: !(this.props.closeOnSelect && close )
- });
- } else {
- if (this.props.closeOnSelect && close) {
- this.closeCalendar();
- }
- }
-
- this.props.onChange( date );
- },
-
- openCalendar: function() {
- if (!this.state.open) {
- this.props.onFocus();
- this.setState({ open: true });
- }
- },
-
- closeCalendar: function() {
- this.setState({ open: false });
- this.props.onBlur( this.state.selectedDate || this.state.inputValue );
- },
-
- handleClickOutside: function(){
- if ( this.props.input && this.state.open && !this.props.open ){
- this.setState({ open: false });
- this.props.onBlur( this.state.selectedDate || this.state.inputValue );
- }
- },
-
- localMoment: function( date, format ){
- var m = moment( date, format, this.props.strictParsing );
- if ( this.props.locale )
- m.locale( this.props.locale );
- return m;
- },
-
- componentProps: {
- fromProps: ['value', 'isValidDate', 'renderDay', 'renderMonth', 'renderYear', 'timeConstraints'],
- fromState: ['viewDate', 'selectedDate', 'updateOn'],
- fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateSelectedDate', 'localMoment']
- },
-
- getComponentProps: function(){
- var me = this,
- formats = this.getFormats( this.props ),
- props = {dateFormat: formats.date, timeFormat: formats.time}
- ;
-
- this.componentProps.fromProps.forEach( function( name ){
- props[ name ] = me.props[ name ];
- });
- this.componentProps.fromState.forEach( function( name ){
- props[ name ] = me.state[ name ];
- });
- this.componentProps.fromThis.forEach( function( name ){
- props[ name ] = me[ name ];
- });
-
- return props;
- },
-
- render: function() {
- var Component = this.viewComponents[ this.state.currentView ],
- DOM = React.DOM,
- className = 'rdt' + (this.props.className ?
- ( Array.isArray( this.props.className ) ?
- ' ' + this.props.className.join( ' ' ) : ' ' + this.props.className) : ''),
- children = []
- ;
-
- if ( this.props.input ){
- children = [ DOM.input( assign({
- key: 'i',
- type:'text',
- className: 'form-control',
- onFocus: this.openCalendar,
- onChange: this.onInputChange,
- onKeyDown: this.onInputKey,
- value: this.state.inputValue
- }, this.props.inputProps ))];
- } else {
- className += ' rdtStatic';
- }
-
- if ( this.state.open )
- className += ' rdtOpen';
-
- return DOM.div({className: className}, children.concat(
- DOM.div(
- { key: 'dt', className: 'rdtPicker' },
- React.createElement( Component, this.getComponentProps())
- )
- ));
- }
-});
-
-// Make moment accessible through the Datetime class
-Datetime.moment = moment;
-
-module.exports = Datetime;
diff --git a/LICENSE b/LICENSE.txt
similarity index 89%
rename from LICENSE
rename to LICENSE.txt
index 35db66f0d..4849e2ff8 100644
--- a/LICENSE
+++ b/LICENSE.txt
@@ -1,6 +1,6 @@
The MIT License (MIT)
-Copyright (c) 2014 Quri, Loรฏc CHOLLIER
+Copyright (c) Javier Marquez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -14,7 +14,7 @@ copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
diff --git a/README.md b/README.md
index 5e78225a2..867e40d95 100644
--- a/README.md
+++ b/README.md
@@ -1,148 +1,302 @@
-react-datetime
-===============================
-A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time.
+# react-datetime
-[](https://travis-ci.org/YouCanBookMe/react-datetime)
+[](https://travis-ci.org/arqex/react-datetime)
[](http://badge.fury.io/js/react-datetime)
-It allows to edit even date's milliseconds.
+A date and time picker in the same React.js component. It can be used as a datepicker, timepicker or both at the same time. It is **highly customizable** and it even allows to edit date's milliseconds.
-This project started as a fork of https://github.com/quri/react-bootstrap-datetimepicker but the code and the API has changed a lot.
+> **Back to the roots!** Thanks to the people of [YouCanBook.me (best scheduling tool)](https://youcanbook.me) for sponsoring react-datetime for so long. Now the project returns to the community and we are **looking for contributors** to continue improving react-datetime. [Would you like to give a hand?](contribute-home.md)
-Usage
-===============================
+**Version 3 is out!** These are the docs for version 3 of the library. If you are still using the deprecated v2, [here it is its documentation](https://github.com/arqex/react-datetime/blob/2a83208452ac5e41c43fea31ef47c65efba0bb56/README.md), but we strongly recommend to migrate to version 3 in order to keep receiving updates. Please check [migrating react-datetime to version 3](migrateToV3.md) to safely update your app.
-Installation:
-```
+## Installation
+
+Install using npm:
+```sh
npm install --save react-datetime
```
-[React.js](http://facebook.github.io/react/) and [Moment.js](http://momentjs.com/) are peer dependencies for react-datetime. These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datetime picker work.
+Install using yarn:
+```sh
+yarn add react-datetime
+```
-Then
-```javascript
-require('react-datetime');
+## Usage
-...
+[React.js](http://facebook.github.io/react/) and [Moment.js](http://momentjs.com/) are peer dependencies for react-datetime (as well as [Moment.js timezones](https://momentjs.com/timezone/) if you want to use the `displayTimeZone` prop). These dependencies are not installed along with react-datetime automatically, but your project needs to have them installed in order to make the datepicker work. You can then use the datepicker like in the example below.
-render: function() {
- return ;
-}
+```js
+// Import the library
+import Datetime from 'react-datetime';
+
+// return it from your components
+return ;
```
-[See this example working](http://codepen.io/simeg/pen/mEmQmP).
+[See this example working](https://codesandbox.io/s/boring-dew-uzln3).
-**Don't forget to add the [CSS stylesheet](https://github.com/arqex/react-datetime/blob/master/css/react-datetime.css) to make it work out of the box.**
+Do you want more examples? [Have a look at our resources gallery](resources.md).
-Build the component (Mac / Linux):
-```
-npm run build:mac
-```
+**Don't forget to add the [CSS stylesheet](https://github.com/arqex/react-datetime/blob/master/css/react-datetime.css) to make it work out of the box.**. You only need to do this once in your app:
-Build the component (Windows):
-```
-npm run build:windows
+```js
+import "react-datetime/css/react-datetime.css";
```
-API
-===============================
+## API
+
+Below we have all the props that we can use with the `` component. There are also some methods that can be used imperatively.
| Name | Type | Default | Description |
| ------------ | ------- | ------- | ----------- |
-| **value** | Date | new Date() | Represents the selected date by the component, in order to use it as a [controlled component](https://facebook.github.io/react/docs/forms.html#controlled-components). This prop is parsed by moment.js, so it is possible to use a date string or a moment.js date. |
-| **defaultValue** | Date | new Date() | Represents the selected date for the component to use it as a [uncontrolled component](https://facebook.github.io/react/docs/forms.html#uncontrolled-components). This prop is parsed by moment.js, so it is possible to use a date string or a moment.js date. |
-| **dateFormat** | `bool` or `string` | `true` | Defines the format for the date. It accepts any [moment.js date format](http://momentjs.com/docs/#/displaying/format/). If `true` the date will be displayed using the defaults for the current locale. If `false` the datepicker is disabled and the component can be used as timepicker. |
-| **timeFormat** | `bool` or `string` | `true` | Defines the format for the time. It accepts any [moment.js time format](http://momentjs.com/docs/#/displaying/format/). If `true` the time will be displayed using the defaults for the current locale. If `false` the timepicker is disabled and the component can be used as datepicker. |
-| **input** | boolean | true | Whether to show an input field to edit the date manually. |
-| **open** | boolean | null | Whether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside. |
-| **locale** | string | null | Manually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see [i18n docs](#i18n).
-| **onChange** | function | empty function | Callback trigger when the date changes. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If it isn't, the value of the input (a string) is returned. |
-| **onFocus** | function | empty function | Callback trigger for when the user opens the datepicker. |
-| **onBlur** | function | empty function | Callback trigger for when the user clicks outside of the input, simulating a regular onBlur. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If it isn't, the value of the input (a string) is returned. |
-| **viewMode** | string or number | 'days' | The default view to display when the picker is shown. ('years', 'months', 'days', 'time') |
-| **className** | string or string array | `""` | Extra class name for the outermost markup element. |
-| **inputProps** | object | undefined | Defines additional attributes for the input element of the component. |
-| **isValidDate** | function | () => true | Define the dates that can be selected. The function receives `(currentDate, selectedDate)` and should return a `true` or `false` whether the `currentDate` is valid or not. See [selectable dates](#selectable-dates).|
-| **renderDay** | function | DOM.td( day ) | Customize the way that the days are shown in the day picker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, and must return a React component. See [appearance customization](#appearance-customization) |
-| **renderMonth** | function | DOM.td( month ) | Customize the way that the months are shown in the month picker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `month` and the `year` to be shown, and must return a React component. See [appearance customization](#appearance-customization) |
-| **renderYear** | function | DOM.td( year ) | Customize the way that the years are shown in the year picker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `year` to be shown, and must return a React component. See [appearance customization](#appearance-customization) |
-| **strictParsing** | boolean | false | Whether to use moment's [strict parsing](http://momentjs.com/docs/#/parsing/string-format/) when parsing input.
-| **closeOnSelect** | boolean | false | When `true`, once the day has been selected, the react-datetime will be automatically closed.
-| **closeOnTab** | boolean | true | When `true` and the input is focused, pressing the `tab` key will close the picker.
-| **timeConstraints** | object | null | Allow to add some constraints to the time selector. It accepts an object with the format `{hours:{ min: 9, max: 15, step:2}}` so the hours can't be lower than 9 or higher than 15, and it will change adding or subtracting 2 hours everytime the buttons are clicked. The constraints can be added to the `hours`, `minutes`, `seconds` and `milliseconds`.
-| **disableOnClickOutside** | boolean | false | When `true`, keep the picker open when click event is triggered outside of component. When `false`, close it.
+| **value** | `Date` | `new Date()` | Represents the selected date by the component, in order to use it as a [controlled component](https://facebook.github.io/react/docs/forms.html#controlled-components). This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. |
+| **initialValue** | `Date` | `new Date()` | Represents the selected date for the component to use it as a [uncontrolled component](https://facebook.github.io/react/docs/uncontrolled-components.html). This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. If you need to set the selected date programmatically after the picker is initialized, please use the `value` prop instead. |
+| **initialViewDate** | `Date` | `new Date()` | Define the month/year/decade/time which is viewed on opening the calendar. This prop is parsed by Moment.js, so it is possible to use a date `string` or a `moment` object. If you want to set the view date after the component has been initialize [see the imperative API](#imperative-api). |
+| **initialViewMode** | `string` or `number` | `'days'` | The default view to display when the picker is shown for the first time (`'years'`, `'months'`, `'days'`, `'time'`). If you want to set the view mode after the component has been initialize [see the imperative API](#imperative-api). |
+| **updateOnView** | `string` | Intelligent guess | By default we can navigate through years and months without actualling updating the selected date. Only when we get to one view called the "updating view", we make a selection there and the value gets updated, triggering an `onChange` event. By default the updating view will get guessed by using the `dateFormat` so if our dates only show months and never days, the update is done in the `months` view. If we set `updateOnView="time"` selecting a day will navigate to the time view. The time view always updates the selected date, never navigates. If `closeOnSelect={ true }`, making a selection in the view defined by `updateOnView` will close the calendar. |
+| **dateFormat** | `boolean` or `string` | `true` | Defines the format for the date. It accepts any [Moment.js date format](http://momentjs.com/docs/#/displaying/format/) (not in localized format). If `true` the date will be displayed using the defaults for the current locale. If `false` the datepicker is disabled and the component can be used as timepicker, see [available units docs](#specify-available-units). |
+| **timeFormat** | `boolean` or `string` | `true` | Defines the format for the time. It accepts any [Moment.js time format](http://momentjs.com/docs/#/displaying/format/) (not in localized format). If `true` the time will be displayed using the defaults for the current locale. If `false` the timepicker is disabled and the component can be used as datepicker, see [available units docs](#specify-available-units). |
+| **input** | `boolean` | `true` | Whether to show an input field to edit the date manually. |
+| **open** | `boolean` | `null` | Whether to open or close the picker. If not set react-datetime will open the datepicker on input focus and close it on click outside. |
+| **locale** | `string` | `null` | Manually set the locale for the react-datetime instance. Moment.js locale needs to be loaded to be used, see [i18n docs](#i18n).
+| **utc** | `boolean` | `false` | When true, input time values will be interpreted as UTC (Zulu time) by Moment.js. Otherwise they will default to the user's local timezone.
+| **displayTimeZone** | `string` | `null` | **Needs [moment's timezone](https://momentjs.com/timezone/) available in your project.** When specified, input time values will be displayed in the given time zone. Otherwise they will default to the user's local timezone (unless `utc` specified).
+| **onChange** | `function` | empty function | Callback trigger when the date changes. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string). |
+| **onOpen** | `function` | empty function | Callback trigger for when the user opens the datepicker. |
+| **onClose** | `function` | empty function | Callback trigger for when the calendar get closed. The callback receives the selected `moment` object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback returns the value in the input. |
+| **onNavigate** | `function` | empty function | Callback trigger when the view mode changes. The callback receives the selected view mode string (`years`, `months`, `days` or `time`) as only parameter.|
+| **onBeforeNavigate** | `function` | ( nextView, currentView, viewDate ) => nextView | Allows to intercept a change of the calendar view. The accepted function receives the view that it's supposed to navigate to, the view that is showing currently and the date currently shown in the view. Return a viewMode ( default ones are `years`, `months`, `days` or `time`) to navigate to it. If the function returns a "falsy" value, the navigation is stopped and we will remain in the current view. |
+| **onNavigateBack** | `function` | empty function | Callback trigger when the user navigates to the previous month, year or decade. The callback receives the amount and type ('month', 'year') as parameters. |
+| **onNavigateForward** | `function` | empty function | Callback trigger when the user navigates to the next month, year or decade. The callback receives the amount and type ('month', 'year') as parameters. |
+| **className** | `string` or `string array` | `''` | Extra class name for the outermost markup element. |
+| **inputProps** | `object` | `undefined` | Defines additional attributes for the input element of the component. For example: `onClick`, `placeholder`, `disabled`, `required`, `name` and `className` (`className` *sets* the class attribute for the input element). See [Customize the Input Appearance](#customize-the-input-appearance). |
+| **isValidDate** | `function` | `() => true` | Define the dates that can be selected. The function receives `(currentDate, selectedDate)` and shall return a `true` or `false` whether the `currentDate` is valid or not. See [selectable dates](#selectable-dates).|
+| **renderInput** | `function` | `undefined` | Replace the rendering of the input element. The function has the following arguments: the default calculated `props` for the input, `openCalendar` (a function which opens the calendar) and `closeCalendar` (a function which closes the calendar). Must return a React component or `null`. See [Customize the Input Appearance](#customize-the-input-appearance). |
+| **renderView** | `function` | `(viewMode, renderDefault) => renderDefault()` | Customize the way the calendar is rendered. The accepted function receives the type of the view it's going to be rendered `'years', 'months', 'days', 'time'` and a function to render the default view of react-datetime, this way it's possible to wrap the original view adding our own markup or override it completely with our own code. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
+| **renderDay** | `function` | `DOM.td(day)` | Customize the way that the days are shown in the daypicker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
+| **renderMonth** | `function` | `DOM.td(month)` | Customize the way that the months are shown in the monthpicker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `month` and the `year` to be shown, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
+| **renderYear** | `function` | `DOM.td(year)` | Customize the way that the years are shown in the year picker. The accepted function has the `selectedDate`, the current date and the default calculated `props` for the cell, the `year` to be shown, and must return a React component. See [Customize the Datepicker Appearance](#customize-the-datepicker-appearance). |
+| **strictParsing** | `boolean` | `true` | Whether to use Moment.js's [strict parsing](http://momentjs.com/docs/#/parsing/string-format/) when parsing input.
+| **closeOnSelect** | `boolean` | `false` | When `true`, once the day has been selected, the datepicker will be automatically closed.
+| **closeOnTab** | `boolean` | `true` | When `true` and the input is focused, pressing the `tab` key will close the datepicker.
+| **timeConstraints** | `object` | `null` | Add some constraints to the timepicker. It accepts an `object` with the format `{ hours: { min: 9, max: 15, step: 2 }}`, this example means the hours can't be lower than `9` and higher than `15`, and it will change adding or subtracting `2` hours everytime the buttons are clicked. The constraints can be added to the `hours`, `minutes`, `seconds` and `milliseconds`.
+| **closeOnClickOutside** | `boolean` | `true` | When the calendar is open and `closeOnClickOutside` is `true` (its default value), clickin outside of the calendar or input closes the calendar. If `false` the calendar stays open.
+
+## Imperative API
+Besides controlling the selected date, there is a navigation through months, years, decades that react-datetime handles for us. We can interfere in it, stopping view transtions by using the prop `onBeforeNavigate`, but we can also navigate to a specific view and date by using some imperative methods.
+
+To do so, we need to create our component with a `ref` prop amd use the reference.
+```js
+// This would be the code to render the picker
+
+
+// ... once rendered we can use the imperative API
+// let's show the years view
+this.refs.datetime.navigate('years')
+```
+
+Available methods are:
+* **navigate( viewMode )**: Set the view currently shown by the calendar. View modes shipped with react-datetime are `years`, `months`, `days` and `time`, but you can alse navigate to custom modes that can be defined by using the `renderView` prop.
+* **setViewDate( date )**: Set the date that is currently shown in the calendar. This is independent from the selected date and it's the one used to navigate through months or days in the calendar. It accepts a string in the format of the current locale, a `Date` or a `Moment` object as parameter.
## i18n
-Different language and date formats are supported by react-datetime. React uses [moment.js](http://momentjs.com/) to format the dates, and the easiest way of changing the language of the calendar is [changing the moment.js locale](http://momentjs.com/docs/#/i18n/changing-locale/).
+Different language and date formats are supported by react-datetime. React uses [Moment.js](http://momentjs.com/) to format the dates, and the easiest way of changing the language of the calendar is [changing the Moment.js locale](http://momentjs.com/docs/#/i18n/changing-locale/).
+
+Don't forget to import your locale file from the moment's `moment/locale` folder.
```js
-var moment = require('moment');
-require('moment/locale/fr');
+import moment from 'moment';
+import 'moment/locale/fr';
// Now react-datetime will be in french
```
-If there are multiple locales loaded, you can use the prop `locale` to define what language should be used by the instance:
+If there are multiple locales loaded, you can use the prop `locale` to define what language shall be used by the instance.
```js
```
-[Here you can see the i18n example working](http://codepen.io/arqex/pen/PqJMQV).
+[Here you can see the i18n example working](https://codesandbox.io/s/interesting-kare-0707b).
+
+## Customize the Input Appearance
+It is possible to customize the way that the input is displayed. The simplest is to supply `inputProps` which will get directly assigned to the `` element within the component. We can tweak the inputs this way:
+
+```js
+let inputProps = {
+ placeholder: 'N/A',
+ disabled: true,
+ onMouseLeave: () => alert('You went to the input but it was disabled')
+};
+
+
+```
+[See the customized input working](https://codesandbox.io/s/clever-wildflower-81r26?file=/src/App.js)
-## Appearance customization
-It is possible to customize the way that the datetime picker display the days, months and years in the calendar. To adapt the calendar to every need it is possible to use the props `renderDay( props, currentDate, selectedDate )`, `renderMonth( props, month, year, selectedDate )` and `renderYear( props, year, selectedDate )` of react-datetime.
+
+Alternatively, if you need to render different content than an `` element, you may supply a `renderInput` function which is called instead.
```js
-var MyDTPicker = React.createClass({
- render: function(){
- return ;
- },
- renderDay: function( props, currentDate, selectedDate ){
- return
+ );
}
-});
+}
```
-[You can see this customized calendar here.](http://codepen.io/arqex/pen/mJzRwM)
-* `props` is the object that react-date picker has calculated for this object. It is convenient to use this object as the props for your custom component, since it knows how to handle the click event and its `className` attribute is used by the default styles.
-* `selectedDate` and `currentDate` are Moment.js objects and can be used to change the output depending on the selected date, or the date for the current day.
-* `month` and `year` are the numeric representation of the current month and year to be displayed. Notice that the possible `month` values go from `0` to `11`.
+[See this example working](https://codesandbox.io/s/peaceful-water-3gb5m)
+
+
+Or maybe you just want to shown the calendar and don't need an input at all. In that case `input={ false }` will make the trick:
+
+```js
+ ;
+```
+[See react-datetime calendar working without an input](https://codesandbox.io/s/busy-vaughan-wh773)
-## Selectable dates
-It is possible to disable dates in the calendar if we don't want the user to select them. It is possible thanks to the prop `isValidDate`, which admits a function in the form `function( currentDate, selectedDate )` where both arguments are moment.js objects. The function should return `true` for selectable dates, and `false` for disabled ones.
+## Customize the Datepicker Appearance
+It is possible to customize the way that the datepicker display the days, months and years in the calendar. To adapt the calendar for every need it is possible to use the props `renderDay(props, currentDate, selectedDate)`, `renderMonth(props, month, year, selectedDate)` and `renderYear(props, year, selectedDate)` to customize the output of each rendering method.
-If we want to disable all the dates before today we can do like
```js
-// Let's use moment static reference in the Datetime component.
-var yesterday = Datetime.moment().subtract(1,'day');
+class MyDTPicker extends React.Component {
+ render() {
+ return (
+
+ );
+ }
+ renderDay(props, currentDate, selectedDate) {
+ // Adds 0 to the days in the days view
+ return
{"0" + currentDate.date()}
;
+ }
+ renderMonth(props, month, year, selectedDate) {
+ // Display the month index in the months view
+ return
{month}
;
+ }
+ renderYear(props, year, selectedDate) {
+ // Just display the last 2 digits of the year in the years view
+ return
{year % 100}
;
+ }
+}
+```
+[See the customized calendar here.](https://codesandbox.io/s/peaceful-kirch-69e06)
+
+It's also possible to override some view in the calendar completelly. Let's say that we want to add a today button in our calendars, when we click it we go to the today view:
+```js
+class MyDTPicker extends React.Component {
+ render() {
+ return (
+
+ this.renderView(mode, renderDefault)
+ }
+ />
+ );
+ }
+
+ renderView(mode, renderDefault) {
+ // Only for years, months and days view
+ if (mode === "time") return renderDefault();
+
+ return (
+
+ {renderDefault()}
+
+
+
+
+ );
+ }
+
+ goToToday() {
+ // Reset
+ this.refs.datetime.setViewDate(new Date());
+ this.refs.datetime.navigate("days");
+ }
+}
+```
+[See it working](https://codesandbox.io/s/frosty-fog-nrwk2)
+
+#### Method Parameters
+* `props` is the object that the datepicker has calculated for this object. It is convenient to use this object as the `props` for your custom component, since it knows how to handle the click event and its `className` attribute is used by the default styles.
+* `selectedDate` and `currentDate` are [moment objects](http://momentjs.com) and can be used to change the output depending on the selected date, or the date for the current day.
+* `month` and `year` are the numeric representation of the current month and year to be displayed. Notice that the possible `month` values range from `0` to `11`.
+
+## Make it work as a year picker or a time picker
+You can filter out what you want the user to be able to pick by using `dateFormat` and `timeFormat`, e.g. to create a timepicker, yearpicker etc.
+
+In this example the component is being used as a *timepicker* and can *only be used for selecting a time*.
+```js
+
+```
+[Working example of a timepicker here.](https://codesandbox.io/s/loving-nobel-sbok2)
+
+In this example you can *only select a year and month*.
+```js
+
+```
+[Working example of only selecting year and month here.](https://codesandbox.io/s/recursing-pascal-xl643)
+
+## Blocking some dates to be selected
+It is possible to disable dates in the calendar if the user are not allowed to select them, e.g. dates in the past. This is done using the prop `isValidDate`, which admits a function in the form `function(currentDate, selectedDate)` where both arguments are [moment objects](http://momentjs.com). The function shall return `true` for selectable dates, and `false` for disabled ones.
+
+In the example below are *all dates before today* disabled.
+
+```js
+import moment from 'moment';
+var yesterday = moment().subtract( 1, 'day' );
var valid = function( current ){
return current.isAfter( yesterday );
};
```
-[See the isValidDate prop working here](http://codepen.io/arqex/pen/jPeyGX).
+[Working example of disabled days here.](https://codesandbox.io/s/thirsty-shape-l4qg4)
-If we want to disable the weekends
+It's also possible to disable *the weekends*, as shown in the example below.
```js
var valid = function( current ){
- return current.day() != 0 && current.day() != 6;
+ return current.day() !== 0 && current.day() !== 6;
};
```
-[The example working here](http://codepen.io/arqex/pen/VLEPXb).
+[Working example of disabled weekends here.](https://codesandbox.io/s/laughing-keller-3wq1g)
+
+## Usage with TypeScript
+
+This project includes typings for TypeScript versions 1.8 and 2.0. Additional typings are not
+required.
+
+Typings for 1.8 are found in `react-datetime.d.ts` and typings for 2.0 are found in `typings/index.d.ts`.
+
+```js
+import * as Datetime from 'react-datetime';
+
+class MyDTPicker extends React.Component {
+ render() JSX.Element {
+ return ;
+ }
+}
+```
+
+## Contributions
+react-datetime is made by the community for the community. People like you, interested in contribute, are the key of the project! ๐๐๐
-Contributions
-===============================
-Any help is always welcome :)
+Have a look at [our contribute page](contribute-home.md) to know how to get started.
### [Changelog](CHANGELOG.md)
-### [MIT Licensed](LICENSE)
+### [MIT Licensed](LICENSE.md)
diff --git a/config/env.js b/config/env.js
new file mode 100644
index 000000000..211711b2d
--- /dev/null
+++ b/config/env.js
@@ -0,0 +1,93 @@
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const paths = require('./paths');
+
+// Make sure that including paths.js after env.js will read .env variables.
+delete require.cache[require.resolve('./paths')];
+
+const NODE_ENV = process.env.NODE_ENV;
+if (!NODE_ENV) {
+ throw new Error(
+ 'The NODE_ENV environment variable is required but was not specified.'
+ );
+}
+
+// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
+const dotenvFiles = [
+ `${paths.dotenv}.${NODE_ENV}.local`,
+ `${paths.dotenv}.${NODE_ENV}`,
+ // Don't include `.env.local` for `test` environment
+ // since normally you expect tests to produce the same
+ // results for everyone
+ NODE_ENV !== 'test' && `${paths.dotenv}.local`,
+ paths.dotenv,
+].filter(Boolean);
+
+// Load environment variables from .env* files. Suppress warnings using silent
+// if this file is missing. dotenv will never modify any environment variables
+// that have already been set. Variable expansion is supported in .env files.
+// https://github.com/motdotla/dotenv
+// https://github.com/motdotla/dotenv-expand
+dotenvFiles.forEach(dotenvFile => {
+ if (fs.existsSync(dotenvFile)) {
+ require('dotenv-expand')(
+ require('dotenv').config({
+ path: dotenvFile,
+ })
+ );
+ }
+});
+
+// We support resolving modules according to `NODE_PATH`.
+// This lets you use absolute paths in imports inside large monorepos:
+// https://github.com/facebook/create-react-app/issues/253.
+// It works similar to `NODE_PATH` in Node itself:
+// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
+// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
+// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
+// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
+// We also resolve them to make sure all tools using them work consistently.
+const appDirectory = fs.realpathSync(process.cwd());
+process.env.NODE_PATH = (process.env.NODE_PATH || '')
+ .split(path.delimiter)
+ .filter(folder => folder && !path.isAbsolute(folder))
+ .map(folder => path.resolve(appDirectory, folder))
+ .join(path.delimiter);
+
+// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
+// injected into the application via DefinePlugin in Webpack configuration.
+const REACT_APP = /^REACT_APP_/i;
+
+function getClientEnvironment(publicUrl) {
+ const raw = Object.keys(process.env)
+ .filter(key => REACT_APP.test(key))
+ .reduce(
+ (env, key) => {
+ env[key] = process.env[key];
+ return env;
+ },
+ {
+ // Useful for determining whether weโre running in production mode.
+ // Most importantly, it switches React into the correct mode.
+ NODE_ENV: process.env.NODE_ENV || 'development',
+ // Useful for resolving the correct path to static assets in `public`.
+ // For example, .
+ // This should only be used as an escape hatch. Normally you would put
+ // images into the `src` and `import` them in code to get their paths.
+ PUBLIC_URL: publicUrl,
+ }
+ );
+ // Stringify all values so we can feed into Webpack DefinePlugin
+ const stringified = {
+ 'process.env': Object.keys(raw).reduce((env, key) => {
+ env[key] = JSON.stringify(raw[key]);
+ return env;
+ }, {}),
+ };
+
+ return { raw, stringified };
+}
+
+module.exports = getClientEnvironment;
diff --git a/config/jest/cssTransform.js b/config/jest/cssTransform.js
new file mode 100644
index 000000000..8f6511481
--- /dev/null
+++ b/config/jest/cssTransform.js
@@ -0,0 +1,14 @@
+'use strict';
+
+// This is a custom Jest transformer turning style imports into empty objects.
+// http://facebook.github.io/jest/docs/en/webpack.html
+
+module.exports = {
+ process() {
+ return 'module.exports = {};';
+ },
+ getCacheKey() {
+ // The output is always the same.
+ return 'cssTransform';
+ },
+};
diff --git a/config/jest/fileTransform.js b/config/jest/fileTransform.js
new file mode 100644
index 000000000..aab67618c
--- /dev/null
+++ b/config/jest/fileTransform.js
@@ -0,0 +1,40 @@
+'use strict';
+
+const path = require('path');
+const camelcase = require('camelcase');
+
+// This is a custom Jest transformer turning file imports into filenames.
+// http://facebook.github.io/jest/docs/en/webpack.html
+
+module.exports = {
+ process(src, filename) {
+ const assetFilename = JSON.stringify(path.basename(filename));
+
+ if (filename.match(/\.svg$/)) {
+ // Based on how SVGR generates a component name:
+ // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
+ const pascalCaseFilename = camelcase(path.parse(filename).name, {
+ pascalCase: true,
+ });
+ const componentName = `Svg${pascalCaseFilename}`;
+ return `const React = require('react');
+ module.exports = {
+ __esModule: true,
+ default: ${assetFilename},
+ ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
+ return {
+ $$typeof: Symbol.for('react.element'),
+ type: 'svg',
+ ref: ref,
+ key: null,
+ props: Object.assign({}, props, {
+ children: ${assetFilename}
+ })
+ };
+ }),
+ };`;
+ }
+
+ return `module.exports = ${assetFilename};`;
+ },
+};
diff --git a/config/modules.js b/config/modules.js
new file mode 100644
index 000000000..c8efd0dd0
--- /dev/null
+++ b/config/modules.js
@@ -0,0 +1,141 @@
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const paths = require('./paths');
+const chalk = require('react-dev-utils/chalk');
+const resolve = require('resolve');
+
+/**
+ * Get additional module paths based on the baseUrl of a compilerOptions object.
+ *
+ * @param {Object} options
+ */
+function getAdditionalModulePaths(options = {}) {
+ const baseUrl = options.baseUrl;
+
+ // We need to explicitly check for null and undefined (and not a falsy value) because
+ // TypeScript treats an empty string as `.`.
+ if (baseUrl == null) {
+ // If there's no baseUrl set we respect NODE_PATH
+ // Note that NODE_PATH is deprecated and will be removed
+ // in the next major release of create-react-app.
+
+ const nodePath = process.env.NODE_PATH || '';
+ return nodePath.split(path.delimiter).filter(Boolean);
+ }
+
+ const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
+
+ // We don't need to do anything if `baseUrl` is set to `node_modules`. This is
+ // the default behavior.
+ if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
+ return null;
+ }
+
+ // Allow the user set the `baseUrl` to `appSrc`.
+ if (path.relative(paths.appSrc, baseUrlResolved) === '') {
+ return [paths.appSrc];
+ }
+
+ // If the path is equal to the root directory we ignore it here.
+ // We don't want to allow importing from the root directly as source files are
+ // not transpiled outside of `src`. We do allow importing them with the
+ // absolute path (e.g. `src/Components/Button.js`) but we set that up with
+ // an alias.
+ if (path.relative(paths.appPath, baseUrlResolved) === '') {
+ return null;
+ }
+
+ // Otherwise, throw an error.
+ throw new Error(
+ chalk.red.bold(
+ "Your project's `baseUrl` can only be set to `src` or `node_modules`." +
+ ' Create React App does not support other values at this time.'
+ )
+ );
+}
+
+/**
+ * Get webpack aliases based on the baseUrl of a compilerOptions object.
+ *
+ * @param {*} options
+ */
+function getWebpackAliases(options = {}) {
+ const baseUrl = options.baseUrl;
+
+ if (!baseUrl) {
+ return {};
+ }
+
+ const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
+
+ if (path.relative(paths.appPath, baseUrlResolved) === '') {
+ return {
+ src: paths.appSrc,
+ };
+ }
+}
+
+/**
+ * Get jest aliases based on the baseUrl of a compilerOptions object.
+ *
+ * @param {*} options
+ */
+function getJestAliases(options = {}) {
+ const baseUrl = options.baseUrl;
+
+ if (!baseUrl) {
+ return {};
+ }
+
+ const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
+
+ if (path.relative(paths.appPath, baseUrlResolved) === '') {
+ return {
+ '^src/(.*)$': '/src/$1',
+ };
+ }
+}
+
+function getModules() {
+ // Check if TypeScript is setup
+ const hasTsConfig = fs.existsSync(paths.appTsConfig);
+ const hasJsConfig = fs.existsSync(paths.appJsConfig);
+
+ if (hasTsConfig && hasJsConfig) {
+ throw new Error(
+ 'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
+ );
+ }
+
+ let config;
+
+ // If there's a tsconfig.json we assume it's a
+ // TypeScript project and set up the config
+ // based on tsconfig.json
+ if (hasTsConfig) {
+ const ts = require(resolve.sync('typescript', {
+ basedir: paths.appNodeModules,
+ }));
+ config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
+ // Otherwise we'll check if there is jsconfig.json
+ // for non TS projects.
+ } else if (hasJsConfig) {
+ config = require(paths.appJsConfig);
+ }
+
+ config = config || {};
+ const options = config.compilerOptions || {};
+
+ const additionalModulePaths = getAdditionalModulePaths(options);
+
+ return {
+ additionalModulePaths: additionalModulePaths,
+ webpackAliases: getWebpackAliases(options),
+ jestAliases: getJestAliases(options),
+ hasTsConfig,
+ };
+}
+
+module.exports = getModules();
diff --git a/config/paths.js b/config/paths.js
new file mode 100644
index 000000000..385d25b38
--- /dev/null
+++ b/config/paths.js
@@ -0,0 +1,86 @@
+const path = require('path');
+const fs = require('fs');
+const url = require('url');
+
+// Make sure any symlinks in the project folder are resolved:
+// https://github.com/facebook/create-react-app/issues/637
+const appDirectory = path.join( __dirname, '..' );
+const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
+
+const envPublicUrl = process.env.PUBLIC_URL;
+
+function ensureSlash(inputPath, needsSlash) {
+ const hasSlash = inputPath.endsWith('/');
+ if (hasSlash && !needsSlash) {
+ return inputPath.substr(0, inputPath.length - 1);
+ } else if (!hasSlash && needsSlash) {
+ return `${inputPath}/`;
+ } else {
+ return inputPath;
+ }
+}
+
+const getPublicUrl = appPackageJson =>
+ envPublicUrl || require(appPackageJson).homepage;
+
+// We use `PUBLIC_URL` environment variable or "homepage" field to infer
+// "public path" at which the app is served.
+// Webpack needs to know it to put the right
-
-