diff --git a/.babelrc b/.babelrc
index 040c38ef2..2d42f2173 100644
--- a/.babelrc
+++ b/.babelrc
@@ -1,7 +1,9 @@
{
- "presets": [
- "es2015",
- "react"
- ],
- "plugins": ["transform-remove-strict-mode"]
-}
+ "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 94be45418..33d30ef45 100644
--- a/.eslintrc.js
+++ b/.eslintrc.js
@@ -1,5 +1,6 @@
module.exports = {
"env": {
+ "es6": true,
"browser": true
},
"globals": {
@@ -38,5 +39,9 @@ module.exports = {
"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/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
index 01adb5d30..ae97d57ff 100644
--- a/.github/ISSUE_TEMPLATE.md
+++ b/.github/ISSUE_TEMPLATE.md
@@ -9,10 +9,10 @@
2) Some of the most frequently asked questions have the answer for them in the documentation.
Be sure to read through the API carefully before publishing an issue:
- https://github.com/YouCanBookMe/react-datetime#api
+ https://github.com/arqex/react-datetime#api
We also use the label *Documentation* for issues that have code examples in them which may be
useful for other developers, please have a look there as well:
- https://github.com/YouCanBookMe/react-datetime/issues?utf8=%E2%9C%93&q=label%3Adocumentation%20
+ https://github.com/arqex/react-datetime/issues?utf8=%E2%9C%93&q=label%3Adocumentation%20
3) Discussions for version 3 of react-datetime has been initiated, and we have come up with some
feature and bug candidates. This means that if a feature or bug has been requested/reported many
@@ -20,7 +20,7 @@
in this list before publishing it.
You can find all the candidates here in the *Candidates* column:
- https://github.com/YouCanBookMe/react-datetime/projects/1
+ https://github.com/arqex/react-datetime/projects/1
-->
diff --git a/.gitignore b/.gitignore
index 9df99f371..5a38e4006 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,6 @@ node_modules
tmp
.DS_Store
npm-debug.log
+
+# Don't force sha validation (it differs depending on the OS)
+package-lock.json
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
index 8bda51f2d..5c5b7fded 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,9 +2,7 @@ language: node_js
sudo: false
os:
- linux
- - windows
node_js:
- - '7'
- '8'
- 'stable'
script:
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 02a5dd084..255ac5d54 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,65 @@
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
@@ -30,7 +90,7 @@ Changelog
## 2.10.2
* Move @types/react back to devDependencies
-* Add [demo](https://youcanbookme.github.io/react-datetime) app.
+* Add [demo](https://codesandbox.io/s/boring-dew-uzln3) app.
## 2.10.1
* Fix build files.
diff --git a/DateTime.js b/DateTime.js
deleted file mode 100644
index 6f8e90856..000000000
--- a/DateTime.js
+++ /dev/null
@@ -1,481 +0,0 @@
-'use strict';
-
-var assign = require('object-assign'),
- PropTypes = require('prop-types'),
- createClass = require('create-react-class'),
- moment = require('moment'),
- React = require('react'),
- CalendarContainer = require('./src/CalendarContainer')
- ;
-
-var viewModes = Object.freeze({
- YEARS: 'years',
- MONTHS: 'months',
- DAYS: 'days',
- TIME: 'time',
-});
-
-var TYPES = PropTypes;
-var Datetime = createClass({
- displayName: 'DateTime',
- propTypes: {
- // value: TYPES.object | TYPES.string,
- // defaultValue: TYPES.object | TYPES.string,
- // viewDate: TYPES.object | TYPES.string,
- onFocus: TYPES.func,
- onBlur: TYPES.func,
- onChange: TYPES.func,
- onViewModeChange: TYPES.func,
- onNavigateBack: TYPES.func,
- onNavigateForward: TYPES.func,
- locale: TYPES.string,
- utc: TYPES.bool,
- input: TYPES.bool,
- // dateFormat: TYPES.string | TYPES.bool,
- // timeFormat: TYPES.string | TYPES.bool,
- inputProps: TYPES.object,
- timeConstraints: TYPES.object,
- viewMode: TYPES.oneOf([viewModes.YEARS, viewModes.MONTHS, viewModes.DAYS, viewModes.TIME]),
- isValidDate: TYPES.func,
- open: TYPES.bool,
- strictParsing: TYPES.bool,
- closeOnSelect: TYPES.bool,
- closeOnTab: TYPES.bool
- },
-
- 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 || viewModes.DAYS) : viewModes.TIME;
-
- return state;
- },
-
- parseDate: function (date, formats) {
- var parsedDate;
-
- if (date && typeof date === 'string')
- parsedDate = this.localMoment(date, formats.datetime);
- else if (date)
- parsedDate = this.localMoment(date);
-
- if (parsedDate && !parsedDate.isValid())
- parsedDate = null;
-
- return parsedDate;
- },
-
- getStateFromProps: function( props ) {
- var formats = this.getFormats( props ),
- date = props.value || props.defaultValue,
- selectedDate, viewDate, updateOn, inputValue
- ;
-
- selectedDate = this.parseDate(date, formats);
-
- viewDate = this.parseDate(props.viewDate, formats);
-
- viewDate = selectedDate ?
- selectedDate.clone().startOf('month') :
- viewDate ? viewDate.clone().startOf('month') : this.localMoment().startOf('month');
-
- updateOn = this.getUpdateOn(formats);
-
- if ( selectedDate )
- inputValue = selectedDate.format(formats.datetime);
- else if ( date.isValid && !date.isValid() )
- inputValue = '';
- else
- inputValue = date || '';
-
- return {
- updateOn: updateOn,
- inputFormat: formats.datetime,
- viewDate: viewDate,
- selectedDate: selectedDate,
- inputValue: inputValue,
- open: props.open
- };
- },
-
- getUpdateOn: function( formats ) {
- if ( formats.date.match(/[lLD]/) ) {
- return viewModes.DAYS;
- } else if ( formats.date.indexOf('M') !== -1 ) {
- return viewModes.MONTHS;
- } else if ( formats.date.indexOf('Y') !== -1 ) {
- return viewModes.YEARS;
- }
-
- return viewModes.DAYS;
- },
-
- getFormats: function( props ) {
- var formats = {
- date: props.dateFormat || '',
- time: props.timeFormat || ''
- },
- locale = this.localMoment( props.date, null, props ).localeData()
- ;
-
- if ( formats.date === true ) {
- formats.date = locale.longDateFormat('L');
- }
- else if ( this.getUpdateOn(formats) !== viewModes.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 ),
- updatedState = {}
- ;
-
- if ( nextProps.value !== this.props.value ||
- formats.datetime !== this.getFormats( this.props ).datetime ) {
- updatedState = this.getStateFromProps( nextProps );
- }
-
- if ( updatedState.open === undefined ) {
- if ( typeof nextProps.open !== 'undefined' ) {
- updatedState.open = nextProps.open;
- } else if ( this.props.closeOnSelect && this.state.currentView !== viewModes.TIME ) {
- updatedState.open = false;
- } else {
- updatedState.open = this.state.open;
- }
- }
-
- if ( nextProps.viewMode !== this.props.viewMode ) {
- updatedState.currentView = nextProps.viewMode;
- }
-
- if ( nextProps.locale !== this.props.locale ) {
- if ( this.state.viewDate ) {
- var updatedViewDate = this.state.viewDate.clone().locale( nextProps.locale );
- updatedState.viewDate = updatedViewDate;
- }
- if ( this.state.selectedDate ) {
- var updatedSelectedDate = this.state.selectedDate.clone().locale( nextProps.locale );
- updatedState.selectedDate = updatedSelectedDate;
- updatedState.inputValue = updatedSelectedDate.format( formats.datetime );
- }
- }
-
- if ( nextProps.utc !== this.props.utc ) {
- if ( nextProps.utc ) {
- if ( this.state.viewDate )
- updatedState.viewDate = this.state.viewDate.clone().utc();
- if ( this.state.selectedDate ) {
- updatedState.selectedDate = this.state.selectedDate.clone().utc();
- updatedState.inputValue = updatedState.selectedDate.format( formats.datetime );
- }
- } else {
- if ( this.state.viewDate )
- updatedState.viewDate = this.state.viewDate.clone().local();
- if ( this.state.selectedDate ) {
- updatedState.selectedDate = this.state.selectedDate.clone().local();
- updatedState.inputValue = updatedState.selectedDate.format(formats.datetime);
- }
- }
- }
-
- if ( nextProps.viewDate !== this.props.viewDate ) {
- updatedState.viewDate = moment(nextProps.viewDate);
- }
- //we should only show a valid date if we are provided a isValidDate function. Removed in 2.10.3
- /*if (this.props.isValidDate) {
- updatedState.viewDate = updatedState.viewDate || this.state.viewDate;
- while (!this.props.isValidDate(updatedState.viewDate)) {
- updatedState.viewDate = updatedState.viewDate.add(1, 'day');
- }
- }*/
- this.setState( updatedState );
- },
-
- 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.state.currentView !== view && me.props.onViewModeChange( view );
- me.setState({ currentView: view });
- };
- },
-
- setDate: function( type ) {
- var me = this,
- nextViews = {
- month: viewModes.DAYS,
- year: viewModes.MONTHS,
- }
- ;
- return function( e ) {
- me.setState({
- viewDate: me.state.viewDate.clone()[ type ]( parseInt(e.target.getAttribute('data-value'), 10) ).startOf( type ),
- currentView: nextViews[ type ]
- });
- me.props.onViewModeChange( nextViews[ type ] );
- };
- },
-
- subtractTime: function( amount, type, toSelected ) {
- var me = this;
- return function() {
- me.props.onNavigateBack( amount, type );
- me.updateTime( 'subtract', amount, type, toSelected );
- };
- },
-
- addTime: function( amount, type, toSelected ) {
- var me = this;
- return function() {
- me.props.onNavigateForward( amount, type );
- me.updateTime( 'add', amount, type, toSelected );
- };
- },
-
- updateTime: function( op, amount, type, toSelected ) {
- var update = {},
- date = toSelected ? 'selectedDate' : 'viewDate';
-
- update[ date ] = this.state[ date ].clone()[ op ]( amount, type );
-
- this.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 ) {
- var open = !( this.props.closeOnSelect && close );
- if ( !open ) {
- this.props.onBlur( date );
- }
-
- this.setState({
- selectedDate: date,
- viewDate: date.clone().startOf('month'),
- inputValue: date.format( this.state.inputFormat ),
- open: open
- });
- } else {
- if ( this.props.closeOnSelect && close ) {
- this.closeCalendar();
- }
- }
-
- this.props.onChange( date );
- },
-
- openCalendar: function( e ) {
- if ( !this.state.open ) {
- this.setState({ open: true }, function() {
- this.props.onFocus( e );
- });
- }
- },
-
- closeCalendar: function() {
- this.setState({ open: false }, function () {
- this.props.onBlur( this.state.selectedDate || this.state.inputValue );
- });
- },
-
- handleClickOutside: function() {
- if ( this.props.input && this.state.open && !this.props.open && !this.props.disableOnClickOutside ) {
- this.setState({ open: false }, function() {
- this.props.onBlur( this.state.selectedDate || this.state.inputValue );
- });
- }
- },
-
- localMoment: function( date, format, props ) {
- props = props || this.props;
- var momentFn = props.utc ? moment.utc : moment;
- var m = momentFn( date, format, props.strictParsing );
- if ( props.locale )
- m.locale( props.locale );
- return m;
- },
-
- componentProps: {
- fromProps: ['value', 'isValidDate', 'renderDay', 'renderMonth', 'renderYear', 'timeConstraints'],
- fromState: ['viewDate', 'selectedDate', 'updateOn'],
- fromThis: ['setDate', 'setTime', 'showView', 'addTime', 'subtractTime', 'updateSelectedDate', 'localMoment', 'handleClickOutside']
- },
-
- 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() {
- // TODO: Make a function or clean up this code,
- // logic right now is really hard to follow
- var className = 'rdt' + (this.props.className ?
- ( Array.isArray( this.props.className ) ?
- ' ' + this.props.className.join( ' ' ) : ' ' + this.props.className) : ''),
- children = [];
-
- if ( this.props.input ) {
- var finalInputProps = assign({
- type: 'text',
- className: 'form-control',
- onClick: this.openCalendar,
- onFocus: this.openCalendar,
- onChange: this.onInputChange,
- onKeyDown: this.onInputKey,
- value: this.state.inputValue,
- }, this.props.inputProps);
- if ( this.props.renderInput ) {
- children = [ React.createElement('div', { key: 'i' }, this.props.renderInput( finalInputProps, this.openCalendar, this.closeCalendar )) ];
- } else {
- children = [ React.createElement('input', assign({ key: 'i' }, finalInputProps ))];
- }
- } else {
- className += ' rdtStatic';
- }
-
- if ( this.state.open )
- className += ' rdtOpen';
-
- return React.createElement( 'div', { className: className }, children.concat(
- React.createElement( 'div',
- { key: 'dt', className: 'rdtPicker' },
- React.createElement( CalendarContainer, { view: this.state.currentView, viewProps: this.getComponentProps(), onClickOutside: this.handleClickOutside })
- )
- ));
- }
-});
-
-Datetime.defaultProps = {
- className: '',
- defaultValue: '',
- inputProps: {},
- input: true,
- onFocus: function() {},
- onBlur: function() {},
- onChange: function() {},
- onViewModeChange: function() {},
- onNavigateBack: function() {},
- onNavigateForward: function() {},
- timeFormat: true,
- timeConstraints: {},
- dateFormat: true,
- strictParsing: true,
- closeOnSelect: false,
- closeOnTab: true,
- utc: false
-};
-
-// Make moment accessible through the Datetime class
-Datetime.moment = moment;
-
-module.exports = Datetime;
diff --git a/LICENSE.md b/LICENSE.txt
similarity index 89%
rename from LICENSE.md
rename to LICENSE.txt
index e0c6b33b1..4849e2ff8 100644
--- a/LICENSE.md
+++ b/LICENSE.txt
@@ -1,6 +1,6 @@
The MIT License (MIT)
-Copyright (c) 2017 Javier Marquez
+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/Makefile b/Makefile
deleted file mode 100644
index e6a90fc44..000000000
--- a/Makefile
+++ /dev/null
@@ -1,19 +0,0 @@
-.PHONY: all clean dev install snapshot test test-watch
-
-clean:
- rm -rf node_modules
-
-dev:
- npm run dev
-
-install:
- npm install
-
-snapshot:
- npm run test:snapshot:update
-
-test:
- npm run test
-
-test-watch:
- npm run test:watch
diff --git a/README.md b/README.md
index fb97b2ebc..867e40d95 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,13 @@
# react-datetime
-[](https://travis-ci.org/YouCanBookMe/react-datetime)
+[](https://travis-ci.org/arqex/react-datetime)
[](http://badge.fury.io/js/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. 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)
+
+**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
@@ -21,46 +23,55 @@ yarn add react-datetime
## Usage
-[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 datepicker work. You can then use the datepicker like in the example below.
-
+[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.
```js
-require('react-datetime');
-
-...
+// Import the library
+import Datetime from 'react-datetime';
-render: function() {
- return ;
-}
+// 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).
+
+Do you want more examples? [Have a look at our resources gallery](resources.md).
-**Don't forget to add the [CSS stylesheet](https://github.com/YouCanBookMe/react-datetime/blob/master/css/react-datetime.css) to make it work out of the box.**
+**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:
+
+```js
+import "react-datetime/css/react-datetime.css";
+```
## 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` object. |
-| **defaultValue** | `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. |
-| **viewDate** | `Date` | `new Date()` | Represents the month which is viewed on opening the calendar when there is no selected date. 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). |
-| **onFocus** | `function` | empty function | Callback trigger for when the user opens the datepicker. The callback receives an event of type SyntheticEvent. |
-| **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 the date in the input is not valid, the callback returned. |
-| **onViewModeChange** | `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.|
+| **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. |
-| **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. 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). |
@@ -68,14 +79,33 @@ render: function() {
| **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`.
-| **disableOnClickOutside** | `boolean` | `false` | When `true`, keep the datepicker open when click event is triggered outside of component. When `false`, close it.
+| **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/).
+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
```
@@ -84,23 +114,31 @@ If there are multiple locales loaded, you can use the prop `locale` to define wh
```
-[Here you can see the i18n example working](http://codepen.io/simeg/pen/yVVjdJ).
+[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 get assigned to the default `` element within the component.
+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)
+
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(){
+class MyDTPicker extends React.Component {
+ render(){
return ;
- },
- renderInput: function( props, openCalendar, closeCalendar ){
+ }
+ renderInput( props, openCalendar, closeCalendar ){
function clear(){
props.onChange({target: {value: ''}});
}
@@ -112,69 +150,121 @@ var MyDTPicker = React.createClass({
);
- },
-});
+ }
+}
+```
+
+[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)
## 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.
```js
-var MyDTPicker = React.createClass({
- render: function(){
- return ;
- },
- renderDay: function( props, currentDate, selectedDate ){
- return
;
- }
-});
+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}
;
+ }
+}
```
-[You can see a customized calendar here.](http://codepen.io/simeg/pen/YppLmO)
+[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`.
-## Specify Available Units
+## 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.](http://codepen.io/simeg/pen/mRQBrp)
+[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.](http://codepen.io/simeg/pen/apQLdd)
+[Working example of only selecting year and month here.](https://codesandbox.io/s/recursing-pascal-xl643)
-## Selectable Dates
+## 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
-// Let's use the static moment reference in the Datetime component
-var yesterday = Datetime.moment().subtract( 1, 'day' );
+import moment from 'moment';
+var yesterday = moment().subtract( 1, 'day' );
var valid = function( current ){
return current.isAfter( yesterday );
};
```
-[Working example of disabled days here.](http://codepen.io/simeg/pen/XNNYJg)
+[Working example of disabled days here.](https://codesandbox.io/s/thirsty-shape-l4qg4)
It's also possible to disable *the weekends*, as shown in the example below.
```js
@@ -183,7 +273,7 @@ var valid = function( current ){
};
```
-[Working example of disabled weekends here.](http://codepen.io/simeg/pen/jVVKWq)
+[Working example of disabled weekends here.](https://codesandbox.io/s/laughing-keller-3wq1g)
## Usage with TypeScript
@@ -203,15 +293,9 @@ class MyDTPicker extends React.Component {
```
## Contributions
-For information about how to contribute, see the [CONTRIBUTING](.github/CONTRIBUTING.md) file.
-
-## Development
-```sh
-npm run dev
-```
-This will start a local `webpack-dev-server` based on `example/example.js` where most development can be done.
+react-datetime is made by the community for the community. People like you, interested in contribute, are the key of the project! πππ
-If you want to develop using the component inside a React application, we recommend that you use [react-datetime-playground](https://github.com/arqex/react-datetime-playground).
+Have a look at [our contribute page](contribute-home.md) to know how to get started.
### [Changelog](CHANGELOG.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
-
-