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 -[![Build Status](https://secure.travis-ci.org/YouCanBookMe/react-datetime.svg)](https://travis-ci.org/YouCanBookMe/react-datetime) +[![Build Status](https://secure.travis-ci.org/arqex/react-datetime.svg)](https://travis-ci.org/arqex/react-datetime) [![npm version](https://badge.fury.io/js/react-datetime.svg)](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 { '0' + currentDate.date() }; - }, - renderMonth: function( props, month, year, selectedDate){ - return { month }; - }, - renderYear: function( props, year, selectedDate ){ - return { year % 100 }; +class MyDTPicker extends React.Component { + render(){ + return ; + } + renderInput( props, openCalendar, closeCalendar ){ + function clear(){ + props.onChange({target: {value: ''}}); + } + 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 - - - diff --git a/example/react-datetime.css b/example/react-datetime.css deleted file mode 100644 index f529623d5..000000000 --- a/example/react-datetime.css +++ /dev/null @@ -1,222 +0,0 @@ -/*! - * https://github.com/arqex/react-datetime - */ - -.rdt { - position: relative; -} - -.rdt > input { - border: 1px solid #000; -} - -.rdtPicker { - display: none; - position: absolute; - width: 250px; - padding: 4px; - margin-top: 1px; - z-index: 99999 !important; - background: #fff; - box-shadow: 0 1px 3px rgba(0,0,0,.1); - border: 1px solid #f9f9f9; -} -.rdtOpen .rdtPicker { - display: block; -} -.rdtStatic .rdtPicker { - box-shadow: none; - position: static; -} - -.rdtPicker .rdtTimeToggle { - text-align: center; -} - -.rdtPicker table { - width: 100%; - margin: 0; -} -.rdtPicker td, -.rdtPicker th { - text-align: center; - height: 28px; -} -.rdtPicker td { - cursor: pointer; -} -.rdtPicker td.rdtToday:hover, -.rdtPicker td.rdtHour:hover, -.rdtPicker td.rdtMinute:hover, -.rdtPicker td.rdtSecond:hover, -.rdtPicker .rdtTimeToggle:hover { - background: #eeeeee; - cursor: pointer; -} -.rdtPicker td.rdtOld, -.rdtPicker td.rdtNew { - color: #999999; -} -.rdtPicker td.rdtToday { - position: relative; -} -.rdtPicker td.rdtToday:before { - content: ''; - display: inline-block; - border-left: 7px solid transparent; - border-bottom: 7px solid #428bca; - border-top-color: rgba(0, 0, 0, 0.2); - position: absolute; - bottom: 4px; - right: 4px; -} -.rdtPicker td.rdtActive, -.rdtPicker td.rdtActive:hover { - background-color: #428bca; - color: #fff; - text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); -} -.rdtPicker td.rdtActive.rdtToday:before { - border-bottom-color: #fff; -} -.rdtPicker td.rdtDisabled, -.rdtPicker td.rdtDisabled:hover { - background: none; - color: #999999; - cursor: not-allowed; -} - -.rdtPicker td span.rdtOld { - color: #999999; -} -.rdtPicker td span.rdtDisabled, -.rdtPicker td span.rdtDisabled:hover { - background: none; - color: #999999; - cursor: not-allowed; -} -.rdtPicker th { - border-bottom: 1px solid #f9f9f9; -} -.rdtPicker .dow { - width: 14.2857%; - border-bottom: none; -} -.rdtPicker th.rdtSwitch { - width: 100px; -} -.rdtPicker th.rdtNext, -.rdtPicker th.rdtPrev { - font-size: 21px; - vertical-align: top; -} - -.rdtPrev span, -.rdtNext span { - display: block; - -webkit-touch-callout: none; /* iOS Safari */ - -webkit-user-select: none; /* Chrome/Safari/Opera */ - -khtml-user-select: none; /* Konqueror */ - -moz-user-select: none; /* Firefox */ - -ms-user-select: none; /* Internet Explorer/Edge */ - user-select: none; -} - -.rdtPicker th.rdtDisabled, -.rdtPicker th.rdtDisabled:hover { - background: none; - color: #999999; - cursor: not-allowed; -} -.rdtPicker thead tr:first-child th { - cursor: pointer; -} -.rdtPicker thead tr:first-child th:hover { - background: #eeeeee; -} - -.rdtPicker tfoot { - border-top: 1px solid #f9f9f9; -} - -.rdtPicker button { - border: none; - background: none; - cursor: pointer; -} -.rdtPicker button:hover { - background-color: #eee; -} - -.rdtPicker thead button { - width: 100%; - height: 100%; -} - -td.rdtMonth, -td.rdtYear { - height: 50px; - width: 25%; - cursor: pointer; -} -td.rdtMonth:hover, -td.rdtYear:hover { - background: #eee; -} - -.rdtCounters { - display: inline-block; -} - -.rdtCounters > div { - float: left; -} - -.rdtCounter { - height: 100px; -} - -.rdtCounter { - width: 40px; -} - -.rdtCounterSeparator { - line-height: 100px; -} - -.rdtCounter .rdtBtn { - height: 40%; - line-height: 40px; - cursor: pointer; - display: block; - - -webkit-touch-callout: none; /* iOS Safari */ - -webkit-user-select: none; /* Chrome/Safari/Opera */ - -khtml-user-select: none; /* Konqueror */ - -moz-user-select: none; /* Firefox */ - -ms-user-select: none; /* Internet Explorer/Edge */ - user-select: none; -} -.rdtCounter .rdtBtn:hover { - background: #eee; -} -.rdtCounter .rdtCount { - height: 20%; - font-size: 1.2em; -} - -.rdtMilli { - vertical-align: middle; - padding-left: 8px; - width: 48px; -} - -.rdtMilli input { - width: 100%; - font-size: 1.2em; - margin-top: 37px; -} - -.rdtDayPart { - margin-top: 43px; -} \ No newline at end of file diff --git a/example/webpack.config.js b/example/webpack.config.js deleted file mode 100644 index a8e608989..000000000 --- a/example/webpack.config.js +++ /dev/null @@ -1,17 +0,0 @@ -var path = require('path'); - -module.exports = { - entry: [ - 'webpack/hot/dev-server', - 'webpack-dev-server/client?http://localhost:8080', - path.resolve(__dirname, 'example.js') - ], - - output: { - path: path.resolve(__dirname, '.'), - filename: 'bundle.js' - }, - resolve: { - extensions: ['', '.js'] - } -} diff --git a/gulpfile.js b/gulpfile.js deleted file mode 100644 index 5176a4948..000000000 --- a/gulpfile.js +++ /dev/null @@ -1,59 +0,0 @@ -var gulp = require('gulp'), - uglify = require('gulp-uglify'), - insert = require('gulp-insert'), - webpack = require('gulp-webpack') -; - -var packageName = 'react-datetime'; -var pack = require( './package.json' ); - -var getWPConfig = function( filename ){ - return { - externals: { - react: 'React', - 'react-dom': 'ReactDOM', - moment: 'moment' - }, - output: { - libraryTarget: 'umd', - library: 'Datetime', - filename: filename + '.js' - } - }; -}; - -var cr = ('/*\n%%name%% v%%version%%\n%%homepage%%\n%%license%%: https://github.com/arqex/' + packageName + '/raw/master/LICENSE\n*/\n') - .replace( '%%name%%', pack.name) - .replace( '%%version%%', pack.version) - .replace( '%%license%%', pack.license) - .replace( '%%homepage%%', pack.homepage) -; - -var handleError = function( err ){ - console.log( 'Error: ', err ); -}; - -function wp( config, minify ){ - var stream = gulp.src('./Datetime.js') - .pipe( webpack( config ) ) - ; - - if( minify ){ - stream = stream.pipe( uglify() ).on( 'error', handleError ); - } - - return stream.pipe( insert.prepend( cr ) ) - .pipe( gulp.dest('dist/') ) - ; -} - -gulp.task( 'build', function( callback ) { - var config = getWPConfig( 'react-datetime' ); - config.devtool = '#eval'; - wp( config ); - - config = getWPConfig( 'react-datetime.min' ); - return wp( config, true ); -}); - -gulp.task( 'default', ['build'] ); diff --git a/migrateToV3.md b/migrateToV3.md new file mode 100644 index 000000000..3dee585c6 --- /dev/null +++ b/migrateToV3.md @@ -0,0 +1,60 @@ +# Migrate react-datetime to v3 + +A new decade has begun and a new major version of react-datetime is released. It's been some years since the first release of v2 and a lot has changed in the react ecosystem. + +In v3 we have updated the whole base code of react-datetime, catching up with the latest tools and practices. We can proudly say that this is the best performant, most customizable and easiest to understand version of the library so far. This version also makes the mantainance of react-datetime much simpler, this way we are ready to keep shipping new features and improvements. + + +## Steps to migrate to version 3 + +The easiest way of migrating to v3 is updating the dependency in your package.json: +``` +react-datetime: "^3.0.0" +``` + +Then tell npm to start updating in your CLI: +``` +npm update react-datetime +``` + +Once the update has finished, try your app. + +It might seem to be working ok but [some props have changed](#whats-new-in-react-datetime-v3) and, even if they don't break your app, your pickers might be behaving a little bit differently. + +We should better search for the following props in our code and replace them as recommended in the points below: +* Search for `defaultValue` prop in your datetime code. Remame it to `initialValue`. +* Search for `defaultViewDate` props and replace them with `initialViewDate`. +* Search for `viewMode` props and replace them with `initialViewMode`. +* Search for `disableCloseOnClickOutside`. If you are using it, replace it with `closeOnClickOutside={false}`. +* Search for `` components using `onBlur` or `onFocus`. Replace those props with `onClose` or `onOpen`. `onOpen` doesn't receive any parameters anymore, so don't try to access to them. +* Search for `onViewModeChange`. If you find it, rename it to `onNavigate`. +* Search for `Datetime.setView`. If you were using this imperative method, replace it with `Datetime.navigate`. + +Those are the main changes that might break your app, if you weren't able to find any of those, react-datetime v3 should keep working as usual in your project. + +## What's new in react-datetime v3 +Version 3 is a big refactor of react-datetime. We have tried to not to change the API drastically, but some of the props has been renamed or removed, trying to make them clearer for the developer. A complete list of changes is: + +* The props are read directly when possible, not deriving the state from them anymore. +* The props that were used to set initial values, like `defaultValue`, `viewDate` or `viewMode` are renamed with the `initial` prefix to better express their intention. `initialValue`, `initialViewDate`, `initialViewMode`. +* `disableCloseOnClickOutside` prop is now `closeOnClickOutside` (avoid double negations). +* `onBlur` and `onFocus` props are renamed to `onClose` and `onOpen` since they had nothing to do with the blur event and it was misleading for some users. If we want to listen to the input's `onBlur` and `onFocus` use `inputProps`. +* Time is not updated anymore on right clicks. +* The new prop `renderView` can be used to customize the whole calendar markup. +* The new prop `updateOnView` can be used to decide when to update the date. +* `onViewModeChange` prop has been renamed to `onNavigate` when the current view has changed. +* We can add a listener to new prop `onBeforeNavigate` in order to detect when the current view is going to change. We can use it to block the navigation or create custom navigation flows. +* Two new imperative methods `setViewDate` and `navigate` methods allows to update the current view shown by the app. +* Clicking on days from the previous or next month in the days view should work properly now. +* Month, year and time views for locales that don't use gregorian numbers should work properly now. +* A playground has been added to the repo, that makes simpler to work on react-datetime development and test out changes quickly. To run it: `npm run playground`. +* Not using the deprecated method `componentWillReceiveProps` anymore. +* We are not using create-react-class anymore, bye bye 2016's react! +* Updated typescript definitions. +* Not depending on gulp to create the build anymore. +* Updated most of the dependencies. + +## Contribute +react-datetime is made by the community for the community. People like you, interested in contribute, are the key of the project! ๐Ÿ™Œ๐Ÿ™Œ๐Ÿ™Œ + +Have a look at [our contribute page](contribute-home.md) to know how to get started. \ No newline at end of file diff --git a/package.json b/package.json index bf00e7755..d2a562b11 100644 --- a/package.json +++ b/package.json @@ -1,20 +1,30 @@ { "name": "react-datetime", - "version": "2.5.0", - "description": "A lightweight but complete datetime picker React.js component.", + "version": "3.3.1", + "description": "A lightweight but complete datetime picker React.js component", "homepage": "https://github.com/arqex/react-datetime", "repository": { "type": "git", "url": "https://github.com/arqex/react-datetime" }, - "main": "./DateTime.js", + "main": "./dist/react-datetime.cjs.js", + "typings": "./typings/DateTime.d.ts", + "files": [ + "css", + "dist", + "typings" + ], "scripts": { - "build:win": "./node_modules/.bin/gulp.cmd", - "build:mac": "./node_modules/.bin/gulp", - "test": "node node_modules/mocha/bin/mocha tests", - "test:watch": "node node_modules/mocha/bin/mocha --watch tests", - "dev": "webpack-dev-server --config example/webpack.config.js --devtool eval --progress --colors --hot --content-base example", - "lint": "./node_modules/.bin/eslint src/ DateTime.js" + "build": "webpack --config config/webpack.config.build.js", + "lint": "eslint src/DateTime.js test/ && echo 'Linting OK! ๐Ÿ’ช'", + "notify-pre-commit-hook": "echo '### Starting pre-commit hook ๐Ÿฆ„'", + "playground": "node scripts/start.js", + "test": "jest", + "test:typings": "tsc -p ./typings", + "test:snapshot": "jest snapshot", + "test:snapshot:update": "jest snapshot --updateSnapshot", + "test:all": "echo 'Running tests...' && npm run test:typings && npm run test && echo 'All tests passed! ๐Ÿค˜'", + "test:watch": "jest --watch" }, "keywords": [ "react", @@ -27,33 +37,149 @@ "author": "Javier Marquez", "license": "MIT", "peerDependencies": { - "react": ">=0.13", - "react-dom": ">=0.13", - "moment": ">=2.8.1" + "moment": "^2.16.0", + "react": "^16.5.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "devDependencies": { - "eslint": "^3.1.0", - "gulp": "^3.9.0", - "gulp-insert": "^0.4.0", - "gulp-uglify": "^1.2.0", - "gulp-webpack": "^1.5.0", + "@babel/core": "7.7.4", + "@babel/plugin-proposal-class-properties": "^7.7.4", + "@babel/preset-env": "^7.7.7", + "@babel/preset-react": "^7.7.4", + "@svgr/webpack": "4.3.3", + "@testing-library/jest-dom": "^4.2.4", + "@testing-library/react": "^9.3.2", + "@testing-library/user-event": "^7.1.2", + "@types/react": "^16.5.0", + "@typescript-eslint/eslint-plugin": "^2.8.0", + "@typescript-eslint/parser": "^2.8.0", + "babel-eslint": "10.0.3", + "babel-jest": "^24.9.0", + "babel-loader": "8.0.6", + "babel-plugin-named-asset-import": "^0.3.5", + "camelcase": "^5.3.1", + "case-sensitive-paths-webpack-plugin": "2.2.0", + "css-loader": "3.2.0", + "dotenv": "8.2.0", + "dotenv-expand": "5.1.0", + "enzyme": "^3.0.0", + "enzyme-adapter-react-16": "^1.15.2", + "eslint": "^6.6.0", + "eslint-config-react-app": "^5.1.0", + "eslint-loader": "3.0.2", + "eslint-plugin-flowtype": "3.13.0", + "eslint-plugin-import": "2.18.2", + "eslint-plugin-jsx-a11y": "6.2.3", + "eslint-plugin-react": "7.16.0", + "eslint-plugin-react-hooks": "^1.6.1", + "file-loader": "4.3.0", + "fs-extra": "^8.1.0", + "html-webpack-plugin": "4.0.0-beta.5", + "identity-obj-proxy": "3.0.0", + "jest": "24.9.0", + "jest-environment-jsdom-fourteen": "0.1.0", + "jest-resolve": "24.9.0", + "jest-watch-typeahead": "0.4.2", "jsdom": "^7.0.2", - "mocha": "^2.2.5", - "moment": "2.14.1", + "mini-css-extract-plugin": "0.8.0", + "moment": "^2.16.0", + "moment-timezone": "^0.5.13", + "optimize-css-assets-webpack-plugin": "5.0.3", + "pnp-webpack-plugin": "1.5.0", + "postcss-flexbugs-fixes": "4.1.0", + "postcss-loader": "3.0.0", + "postcss-normalize": "8.0.1", + "postcss-preset-env": "6.7.0", + "postcss-safe-parser": "4.0.1", "pre-commit": "^1.1.3", - "react": ">=0.13", - "react-addons-test-utils": ">=0.13", - "react-dom": "15.2.1", - "react-tools": "^0.13.2", - "webpack": "^1.5.1", - "webpack-dev-server": "^1.7.0" + "react": "^16.5.0", + "react-app-polyfill": "^1.0.5", + "react-dev-utils": "10.1.0", + "react-dom": "^16.5.0", + "react-onclickoutside": "^6.9.0", + "react-test-renderer": "^16.5.0", + "resolve": "1.12.2", + "resolve-url-loader": "3.1.1", + "sass-loader": "8.0.0", + "semver": "6.3.0", + "style-loader": "1.0.0", + "terser-webpack-plugin": "4.2.1", + "through2": "^2.0.3", + "ts-pnp": "1.1.5", + "typescript": "^3.7.4", + "url-loader": "2.3.0", + "webpack": "4.41.2", + "webpack-cli": "^3.3.10", + "webpack-dev-server": "3.11.0", + "webpack-manifest-plugin": "2.2.0", + "workbox-webpack-plugin": "4.3.1" }, "dependencies": { - "object-assign": "^3.0.0", - "react-onclickoutside": "^4.1.0" + "prop-types": "^15.5.7" }, "pre-commit": [ + "notify-pre-commit-hook", "lint", - "test" - ] + "test:all" + ], + "jest": { + "roots": [ + "/test" + ], + "collectCoverageFrom": [ + "src/**/*.{js,jsx,ts,tsx}", + "!src/playground/**", + "!src/**/*.d.ts" + ], + "setupFiles": [ + "react-app-polyfill/jsdom" + ], + "setupFilesAfterEnv": [], + "testMatch": [ + "/test/**/__tests__/**/*.{js,jsx,ts,tsx}", + "/test/**/*.{spec,test}.{js,jsx,ts,tsx}" + ], + "testEnvironment": "jest-environment-jsdom-fourteen", + "transform": { + "^.+\\.(js|jsx|ts|tsx)$": "/node_modules/babel-jest", + "^.+\\.css$": "/config/jest/cssTransform.js", + "^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "/config/jest/fileTransform.js" + }, + "transformIgnorePatterns": [ + "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$", + "^.+\\.module\\.(css|sass|scss)$" + ], + "modulePaths": [], + "moduleNameMapper": { + "^react-native$": "react-native-web", + "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy" + }, + "moduleFileExtensions": [ + "web.js", + "js", + "web.ts", + "ts", + "web.tsx", + "tsx", + "json", + "web.jsx", + "jsx", + "node" + ], + "watchPlugins": [ + "jest-watch-typeahead/filename", + "jest-watch-typeahead/testname" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } } diff --git a/public/index.html b/public/index.html new file mode 100644 index 000000000..aa069f27c --- /dev/null +++ b/public/index.html @@ -0,0 +1,43 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/react-datetime.d.ts b/react-datetime.d.ts index eec98c9a5..1343d0843 100644 --- a/react-datetime.d.ts +++ b/react-datetime.d.ts @@ -1,6 +1,10 @@ // Type definitions for react-datetime -// Project: https://github.com/YouCanBookMe/react-datetime +// Project: https://github.com/arqex/react-datetime // Definitions by: Ivan Verevkin +// Updates by: Javier Marquez + +// These are the typings for Typescript 1.8 +// for Typescript 2.0+ see DateTime.d.ts //// @@ -13,12 +17,31 @@ declare module ReactDatetime { Represents the selected date by the component, in order to use it as a controlled component. This prop is parsed by moment.js, so it is possible to use a date string or a moment.js date. */ - value?: string; + value?: Date; /* Represents the selected date for the component to use it as a uncontrolled component. This prop is parsed by moment.js, so it is possible to use a date string or a moment.js date. */ - defaultValue?: string; + initialValue?: 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. + */ + initialViewDate?: Date; + /* + The default view to display when the picker is shown for the first time. ('years', 'months', 'days', 'time') + */ + initialViewMode?: string; + /* + In the calendar we can navigate through years and months without actualling updating the selected view. 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. + */ + updateOnView?: string; /* Defines the format for the date. It accepts any moment.js date format. If true the date will be displayed using the defaults for the current locale. @@ -46,25 +69,54 @@ declare module ReactDatetime { */ locale?: string; /* - 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. + Whether to interpret input times as UTC or the user's local timezone. */ - onChange?:(x: string) => void; + utc?: boolean; + /* + 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). + */ + displayTimeZone?: string; + /* + 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). + */ + onChange?: (momentOrInputString: string|any) => void; /* Callback trigger for when the user opens the datepicker. */ - onFocus?: (e) => void; + onOpen?: () => void; /* - 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. + Callback trigger for when the datepicker is 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 receives the value of the + input (a string). */ - onBlurs?: (e) => void; + onClose?: (momentOrInputString : string|any) => void; + /* + Callback trigger when the view mode changes. The callback receives the selected view mode + string ('years', 'months', 'days', 'time') as only parameter. + */ + onNavigate?: (viewMode: string) => void; /* - The default view to display when the picker is shown. ('years', 'months', 'days', 'time') + 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. + */ + onBeforeNavigate?: (nextView: string, currentView: string, viewDate: Moment) => string; + /* + Callback trigger when the user navigates to the previous month, year or decade. + The callback receives the amount and type ('month', 'year') as parameters. + */ + onNavigateBack?: (amount: number, type: string) => void; + /* + 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|number; + onNavigateForward?: (amount: number, type: string) => void; /* Extra class names for the component markup. */ @@ -73,46 +125,74 @@ declare module ReactDatetime { Defines additional attributes for the input element of the component. */ inputProps?: Object; + /* + Customize the way the calendar is rendered. The accepted function receives view mode that + is 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. + */ + renderView?: (viewMode: string, renderCalendar: Function) => React.Component; + /* + Replace the rendering of the input element. The accepted function has openCalendar + (a function which opens the calendar) and the default calculated props for the input. + Must return a React component or null. + */ + renderInput?: (props: Object, openCalendar: Function, closeCalendar: Function) => React.Component; /* 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. */ - isValidDate?: (x: string) => void; + isValidDate?: (currentDate: any, selectedDate: any) => boolean; /* 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 */ - renderDay?: (x: string) => void; + renderDay?: (props: any, currentDate: any, selectedDate: any) => React.Component; /* 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 */ - renderMonth?: (x: string) => void; + renderMonth?: (props: any, month: number, year: number, selectedDate: any) => React.Component; /* 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 */ - renderYear?: (x: string) => void; + renderYear?: (props: any, year: number, selectedDate: any) => React.Component; /* Whether to use moment's strict parsing when parsing input. */ strictParsing?: boolean; + /* + When true and the input is focused, pressing the tab key will close the datepicker. + */ + closeOnTab?: boolean; /* When true, once the day has been selected, the react-datetime will be automatically closed. */ closeOnSelect?: boolean; + /* + 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. + */ + timeConstraints?: Object; + /* + When true the picker get closed when clicking outside of the calendar or the input box. When false, it stays open. + */ + closeOnClickOutside?: boolean; } interface DatetimeComponent extends React.ComponentClass { } } -declare module "react-datetime" { - var ReactDatetime: ReactDatetime.DatetimeComponent; - export = ReactDatetime; +declare module 'react-datetime' { + var DateTime: ReactDatetime.DatetimeComponent; + export = DateTime; } diff --git a/resources.md b/resources.md new file mode 100644 index 000000000..11af8e311 --- /dev/null +++ b/resources.md @@ -0,0 +1,21 @@ +# Resources + +Here a list of handy resouces that will help you getting started to use react-datetime. + +If you have written a nice article about react-datetime feel free to make a pull request to add it to the list! + +### Articles +We don't have any articles yet. Yours can be the first! Create a PR to update this page. + +### Examples +* [An basic code sandbox example to check how it works](https://codesandbox.io/s/boring-dew-uzln3). +* [i18n - datepicker in other languages](https://codesandbox.io/s/interesting-kare-0707b) +* [Passing props to the input](https://codesandbox.io/s/clever-wildflower-81r26?file=/src/App.js) +* [Using a custom input element](https://codesandbox.io/s/peaceful-water-3gb5m) +* [Datepicker without an input](https://codesandbox.io/s/busy-vaughan-wh773) +* [Using custom elements for the year/month/day views](https://codesandbox.io/s/busy-vaughan-wh773) +* [Override the datepicker views completely](https://codesandbox.io/s/frosty-fog-nrwk2) +* [Timepicker only](https://codesandbox.io/s/loving-nobel-sbok2) +* [Year and month picker only](https://codesandbox.io/s/recursing-pascal-xl643) +* [Blocking dates in the past](https://codesandbox.io/s/thirsty-shape-l4qg4) +* [Blocking selection of weekends](https://codesandbox.io/s/laughing-keller-3wq1g) \ No newline at end of file diff --git a/scripts/build.js b/scripts/build.js new file mode 100644 index 000000000..4fa3737d0 --- /dev/null +++ b/scripts/build.js @@ -0,0 +1,211 @@ +'use strict'; + +// Do this as the first thing so that any code reading it knows the right env. +process.env.BABEL_ENV = 'production'; +process.env.NODE_ENV = 'production'; + +// Makes the script crash on unhandled rejections instead of silently +// ignoring them. In the future, promise rejections that are not handled will +// terminate the Node.js process with a non-zero exit code. +process.on('unhandledRejection', err => { + throw err; +}); + +// Ensure environment variables are read. +require('../config/env'); + + +const path = require('path'); +const chalk = require('react-dev-utils/chalk'); +const fs = require('fs-extra'); +const webpack = require('webpack'); +const configFactory = require('../config/webpack.config'); +const paths = require('../config/paths'); +const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); +const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); +const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); +const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); +const printBuildError = require('react-dev-utils/printBuildError'); + +const measureFileSizesBeforeBuild = + FileSizeReporter.measureFileSizesBeforeBuild; +const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; +const useYarn = fs.existsSync(paths.yarnLockFile); + +// These sizes are pretty large. We'll warn for bundles exceeding them. +const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; +const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; + +const isInteractive = process.stdout.isTTY; + +// Warn and crash if required files are missing +if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { + process.exit(1); +} + +// Generate configuration +const config = configFactory('production'); + +// We require that you explicitly set browsers and do not fall back to +// browserslist defaults. +const { checkBrowsers } = require('react-dev-utils/browsersHelper'); +checkBrowsers(paths.appPath, isInteractive) + .then(() => { + // First, read the current file sizes in build directory. + // This lets us display how much they changed later. + return measureFileSizesBeforeBuild(paths.appBuild); + }) + .then(previousFileSizes => { + // Remove all content but keep the directory so that + // if you're in it, you don't end up in Trash + fs.emptyDirSync(paths.appBuild); + // Merge with the public folder + copyPublicFolder(); + // Start the webpack build + return build(previousFileSizes); + }) + .then( + ({ stats, previousFileSizes, warnings }) => { + if (warnings.length) { + console.log(chalk.yellow('Compiled with warnings.\n')); + console.log(warnings.join('\n\n')); + console.log( + '\nSearch for the ' + + chalk.underline(chalk.yellow('keywords')) + + ' to learn more about each warning.' + ); + console.log( + 'To ignore, add ' + + chalk.cyan('// eslint-disable-next-line') + + ' to the line before.\n' + ); + } else { + console.log(chalk.green('Compiled successfully.\n')); + } + + console.log('File sizes after gzip:\n'); + printFileSizesAfterBuild( + stats, + previousFileSizes, + paths.appBuild, + WARN_AFTER_BUNDLE_GZIP_SIZE, + WARN_AFTER_CHUNK_GZIP_SIZE + ); + console.log(); + + const appPackage = require(paths.appPackageJson); + const publicUrl = paths.publicUrl; + const publicPath = config.output.publicPath; + const buildFolder = path.relative(process.cwd(), paths.appBuild); + printHostingInstructions( + appPackage, + publicUrl, + publicPath, + buildFolder, + useYarn + ); + }, + err => { + const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; + if (tscCompileOnError) { + console.log( + chalk.yellow( + 'Compiled with the following type errors (you may want to check these before deploying your app):\n' + ) + ); + printBuildError(err); + } else { + console.log(chalk.red('Failed to compile.\n')); + printBuildError(err); + process.exit(1); + } + } + ) + .catch(err => { + if (err && err.message) { + console.log(err.message); + } + process.exit(1); + }); + +// Create the production build and print the deployment instructions. +function build(previousFileSizes) { + // We used to support resolving modules according to `NODE_PATH`. + // This now has been deprecated in favor of jsconfig/tsconfig.json + // This lets you use absolute paths in imports inside large monorepos: + if (process.env.NODE_PATH) { + console.log( + chalk.yellow( + 'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.' + ) + ); + console.log(); + } + + console.log('Creating an optimized production build...'); + + const compiler = webpack(config); + return new Promise((resolve, reject) => { + compiler.run((err, stats) => { + let messages; + if (err) { + if (!err.message) { + return reject(err); + } + + let errMessage = err.message; + + // Add additional information for postcss errors + if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) { + errMessage += + '\nCompileError: Begins at CSS selector ' + + err['postcssNode'].selector; + } + + messages = formatWebpackMessages({ + errors: [errMessage], + warnings: [], + }); + } else { + messages = formatWebpackMessages( + stats.toJson({ all: false, warnings: true, errors: true }) + ); + } + if (messages.errors.length) { + // Only keep the first error. Others are often indicative + // of the same problem, but confuse the reader with noise. + if (messages.errors.length > 1) { + messages.errors.length = 1; + } + return reject(new Error(messages.errors.join('\n\n'))); + } + if ( + process.env.CI && + (typeof process.env.CI !== 'string' || + process.env.CI.toLowerCase() !== 'false') && + messages.warnings.length + ) { + console.log( + chalk.yellow( + '\nTreating warnings as errors because process.env.CI = true.\n' + + 'Most CI servers set it automatically.\n' + ) + ); + return reject(new Error(messages.warnings.join('\n\n'))); + } + + return resolve({ + stats, + previousFileSizes, + warnings: messages.warnings, + }); + }); + }); +} + +function copyPublicFolder() { + fs.copySync(paths.appPublic, paths.appBuild, { + dereference: true, + filter: file => file !== paths.appHtml, + }); +} diff --git a/scripts/start.js b/scripts/start.js new file mode 100644 index 000000000..55322b951 --- /dev/null +++ b/scripts/start.js @@ -0,0 +1,146 @@ +/* global process */ + +// Do this as the first thing so that any code reading it knows the right env. +process.env.BABEL_ENV = 'development'; +process.env.NODE_ENV = 'development'; + +// Makes the script crash on unhandled rejections instead of silently +// ignoring them. In the future, promise rejections that are not handled will +// terminate the Node.js process with a non-zero exit code. +process.on('unhandledRejection', err => { + throw err; +}); + +// Ensure environment variables are read. +require('../config/env'); + +const fs = require('fs'); +const chalk = require('react-dev-utils/chalk'); +const webpack = require('webpack'); +const WebpackDevServer = require('webpack-dev-server'); +const clearConsole = require('react-dev-utils/clearConsole'); +const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); +const { + choosePort, + createCompiler, + prepareProxy, + prepareUrls, +} = require('react-dev-utils/WebpackDevServerUtils'); +const openBrowser = require('react-dev-utils/openBrowser'); +const paths = require('../config/paths'); +const configFactory = require('../config/webpack.config'); +const createDevServerConfig = require('../config/webpackDevServer.config'); + +const useYarn = fs.existsSync(paths.yarnLockFile); +const isInteractive = process.stdout.isTTY; + +// Warn and crash if required files are missing +if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { + process.exit(1); +} + +// Tools like Cloud9 rely on this. +const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; +const HOST = process.env.HOST || '0.0.0.0'; + +if (process.env.HOST) { + console.log( + chalk.cyan( + `Attempting to bind to HOST environment variable: ${chalk.yellow( + chalk.bold(process.env.HOST) + )}` + ) + ); + console.log( + `If this was unintentional, check that you haven't mistakenly set it in your shell.` + ); + console.log( + `Learn more here: ${chalk.yellow('https://bit.ly/CRA-advanced-config')}` + ); + console.log(); +} + +// We require that you explicitly set browsers and do not fall back to +// browserslist defaults. +const { checkBrowsers } = require('react-dev-utils/browsersHelper'); +checkBrowsers(paths.appPath, isInteractive) + .then(() => { + // We attempt to use the default port but if it is busy, we offer the user to + // run on a different port. `choosePort()` Promise resolves to the next free port. + return choosePort(HOST, DEFAULT_PORT); + }) + .then(port => { + if (port == null) { + // We have not found a port. + return; + } + const config = configFactory('development'); + const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; + const appName = require(paths.appPackageJson).name; + const useTypeScript = fs.existsSync(paths.appTsConfig); + const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; + const urls = prepareUrls(protocol, HOST, port); + const devSocket = { + warnings: warnings => + devServer.sockWrite(devServer.sockets, 'warnings', warnings), + errors: errors => + devServer.sockWrite(devServer.sockets, 'errors', errors), + }; + // Create a webpack compiler that is configured with custom messages. + const compiler = createCompiler({ + appName, + config, + devSocket, + urls, + useYarn, + useTypeScript, + tscCompileOnError, + webpack, + }); + // Load proxy config + const proxySetting = require(paths.appPackageJson).proxy; + const proxyConfig = prepareProxy(proxySetting, paths.appPublic); + // Serve webpack assets generated by the compiler over a web server. + const serverConfig = createDevServerConfig( + proxyConfig, + urls.lanUrlForConfig + ); + const devServer = new WebpackDevServer(compiler, serverConfig); + // Launch WebpackDevServer. + devServer.listen(port, HOST, err => { + if (err) { + return console.log(err); + } + if (isInteractive) { + clearConsole(); + } + + // We used to support resolving modules according to `NODE_PATH`. + // This now has been deprecated in favor of jsconfig/tsconfig.json + // This lets you use absolute paths in imports inside large monorepos: + if (process.env.NODE_PATH) { + console.log( + chalk.yellow( + 'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.' + ) + ); + console.log(); + } + + console.log(chalk.cyan('Starting the development server...\n')); + openBrowser(urls.localUrlForBrowser); + }); + + ['SIGINT', 'SIGTERM'].forEach(function(sig) { + process.on(sig, function() { + devServer.close(); + process.exit(); + }); + }); + }) + .catch(err => { + if (err && err.message) { + console.log(err.message); + } + process.exit(1); + }); diff --git a/scripts/test.js b/scripts/test.js new file mode 100644 index 000000000..35ac142a3 --- /dev/null +++ b/scripts/test.js @@ -0,0 +1,52 @@ +/* global process */ +'use strict'; + +// Do this as the first thing so that any code reading it knows the right env. +process.env.BABEL_ENV = 'test'; +process.env.NODE_ENV = 'test'; +process.env.PUBLIC_URL = ''; + +// Makes the script crash on unhandled rejections instead of silently +// ignoring them. In the future, promise rejections that are not handled will +// terminate the Node.js process with a non-zero exit code. +process.on('unhandledRejection', err => { + throw err; +}); + +// Ensure environment variables are read. +require('../config/env'); + +const jest = require('jest'); +const execSync = require('child_process').execSync; +let argv = process.argv.slice(2); + +function isInGitRepository() { + try { + execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' }); + return true; + } catch (e) { + return false; + } +} + +function isInMercurialRepository() { + try { + execSync('hg --cwd . root', { stdio: 'ignore' }); + return true; + } catch (e) { + return false; + } +} + +// Watch unless on CI or explicitly running all tests +if ( + !process.env.CI && + argv.indexOf('--watchAll') === -1 && + argv.indexOf('--watchAll=false') === -1 +) { + // https://github.com/facebook/create-react-app/issues/5210 + const hasSourceControl = isInGitRepository() || isInMercurialRepository(); + argv.push(hasSourceControl ? '--watch' : '--watchAll'); +} + +jest.run(argv); diff --git a/src/DateTime.js b/src/DateTime.js new file mode 100644 index 000000000..6b2e8aebb --- /dev/null +++ b/src/DateTime.js @@ -0,0 +1,636 @@ +import PropTypes from 'prop-types'; +import moment from 'moment'; +import React from 'react'; +import DaysView from './views/DaysView'; +import MonthsView from './views/MonthsView'; +import YearsView from './views/YearsView'; +import TimeView from './views/TimeView'; +import onClickOutside from 'react-onclickoutside'; + +const viewModes = { + YEARS: 'years', + MONTHS: 'months', + DAYS: 'days', + TIME: 'time', +}; + +const TYPES = PropTypes; +const nofn = function () {}; +const datetype = TYPES.oneOfType([ TYPES.instanceOf(moment), TYPES.instanceOf(Date), TYPES.string ]); + +export default class Datetime extends React.Component { + static propTypes = { + value: datetype, + initialValue: datetype, + initialViewDate: datetype, + initialViewMode: TYPES.oneOf([viewModes.YEARS, viewModes.MONTHS, viewModes.DAYS, viewModes.TIME]), + onOpen: TYPES.func, + onClose: TYPES.func, + onChange: TYPES.func, + onNavigate: TYPES.func, + onBeforeNavigate: TYPES.func, + onNavigateBack: TYPES.func, + onNavigateForward: TYPES.func, + updateOnView: TYPES.string, + locale: TYPES.string, + utc: TYPES.bool, + displayTimeZone: TYPES.string, + input: TYPES.bool, + dateFormat: TYPES.oneOfType([TYPES.string, TYPES.bool]), + timeFormat: TYPES.oneOfType([TYPES.string, TYPES.bool]), + inputProps: TYPES.object, + timeConstraints: TYPES.object, + isValidDate: TYPES.func, + open: TYPES.bool, + strictParsing: TYPES.bool, + closeOnSelect: TYPES.bool, + closeOnTab: TYPES.bool, + renderView: TYPES.func, + renderInput: TYPES.func, + renderDay: TYPES.func, + renderMonth: TYPES.func, + renderYear: TYPES.func, + } + + static defaultProps = { + onOpen: nofn, + onClose: nofn, + onCalendarOpen: nofn, + onCalendarClose: nofn, + onChange: nofn, + onNavigate: nofn, + onBeforeNavigate: function(next) { return next; }, + onNavigateBack: nofn, + onNavigateForward: nofn, + dateFormat: true, + timeFormat: true, + utc: false, + className: '', + input: true, + inputProps: {}, + timeConstraints: {}, + isValidDate: function() { return true; }, + strictParsing: true, + closeOnSelect: false, + closeOnTab: true, + closeOnClickOutside: true, + renderView: ( _, renderFunc ) => renderFunc(), + } + + // Make moment accessible through the Datetime class + static moment = moment; + + constructor( props ) { + super( props ); + this.state = this.getInitialState(); + } + + render() { + return ( + + { this.renderInput() } +
+ { this.renderView() } +
+
+ ); + } + + renderInput() { + if ( !this.props.input ) return; + + const finalInputProps = { + type: 'text', + className: 'form-control', + value: this.getInputValue(), + ...this.props.inputProps, + onFocus: this._onInputFocus, + onChange: this._onInputChange, + onKeyDown: this._onInputKeyDown, + onClick: this._onInputClick + }; + + if ( this.props.renderInput ) { + return ( +
+ { this.props.renderInput( finalInputProps, this._openCalendar, this._closeCalendar ) } +
+ ); + } + + return ( + + ); + } + + renderView() { + return this.props.renderView( this.state.currentView, this._renderCalendar ); + } + + _renderCalendar = () => { + const props = this.props; + const state = this.state; + + let viewProps = { + viewDate: state.viewDate.clone(), + selectedDate: this.getSelectedDate(), + isValidDate: props.isValidDate, + updateDate: this._updateDate, + navigate: this._viewNavigate, + moment: moment, + showView: this._showView + }; + + // Probably updateOn, updateSelectedDate and setDate can be merged in the same method + // that would update viewDate or selectedDate depending on the view and the dateFormat + switch ( state.currentView ) { + case viewModes.YEARS: + // Used viewProps + // { viewDate, selectedDate, renderYear, isValidDate, navigate, showView, updateDate } + viewProps.renderYear = props.renderYear; + return ; + + case viewModes.MONTHS: + // { viewDate, selectedDate, renderMonth, isValidDate, navigate, showView, updateDate } + viewProps.renderMonth = props.renderMonth; + return ; + + case viewModes.DAYS: + // { viewDate, selectedDate, renderDay, isValidDate, navigate, showView, updateDate, timeFormat + viewProps.renderDay = props.renderDay; + viewProps.timeFormat = this.getFormat('time'); + return ; + + default: + // { viewDate, selectedDate, timeFormat, dateFormat, timeConstraints, setTime, showView } + viewProps.dateFormat = this.getFormat('date'); + viewProps.timeFormat = this.getFormat('time'); + viewProps.timeConstraints = props.timeConstraints; + viewProps.setTime = this._setTime; + return ; + } + } + + getInitialState() { + let props = this.props; + let inputFormat = this.getFormat('datetime'); + let selectedDate = this.parseDate( props.value || props.initialValue, inputFormat ); + + this.checkTZ(); + + return { + open: !props.input, + currentView: props.initialViewMode || this.getInitialView(), + viewDate: this.getInitialViewDate( selectedDate ), + selectedDate: selectedDate && selectedDate.isValid() ? selectedDate : undefined, + inputValue: this.getInitialInputValue( selectedDate ) + }; + } + + getInitialViewDate( selectedDate ) { + const propDate = this.props.initialViewDate; + let viewDate; + if ( propDate ) { + viewDate = this.parseDate( propDate, this.getFormat('datetime') ); + if ( viewDate && viewDate.isValid() ) { + return viewDate; + } + else { + log('The initialViewDated given "' + propDate + '" is not valid. Using current date instead.'); + } + } + else if ( selectedDate && selectedDate.isValid() ) { + return selectedDate.clone(); + } + return this.getInitialDate(); + } + + getInitialDate() { + let m = this.localMoment(); + m.hour(0).minute(0).second(0).millisecond(0); + return m; + } + + getInitialView() { + const dateFormat = this.getFormat( 'date' ); + return dateFormat ? this.getUpdateOn( dateFormat ) : viewModes.TIME; + } + + parseDate(date, dateFormat) { + let parsedDate; + + if (date && typeof date === 'string') + parsedDate = this.localMoment(date, dateFormat); + else if (date) + parsedDate = this.localMoment(date); + + if (parsedDate && !parsedDate.isValid()) + parsedDate = null; + + return parsedDate; + } + + getClassName() { + let cn = 'rdt'; + let props = this.props; + let propCn = props.className; + + if ( Array.isArray( propCn ) ) { + cn += ' ' + propCn.join(' '); + } + else if ( propCn ) { + cn += ' ' + propCn; + } + + if ( !props.input ) { + cn += ' rdtStatic'; + } + if ( this.isOpen() ) { + cn += ' rdtOpen'; + } + + return cn; + } + + isOpen() { + return !this.props.input || (this.props.open === undefined ? this.state.open : this.props.open); + } + + getUpdateOn( dateFormat ) { + if ( this.props.updateOnView ) { + return this.props.updateOnView; + } + + if ( dateFormat.match(/[lLD]/) ) { + return viewModes.DAYS; + } + + if ( dateFormat.indexOf('M') !== -1 ) { + return viewModes.MONTHS; + } + + if ( dateFormat.indexOf('Y') !== -1 ) { + return viewModes.YEARS; + } + + return viewModes.DAYS; + } + + getLocaleData() { + let p = this.props; + return this.localMoment( p.value || p.defaultValue || new Date() ).localeData(); + } + + getDateFormat() { + const locale = this.getLocaleData(); + let format = this.props.dateFormat; + if ( format === true ) return locale.longDateFormat('L'); + if ( format ) return format; + return ''; + } + + getTimeFormat() { + const locale = this.getLocaleData(); + let format = this.props.timeFormat; + if ( format === true ) { + return locale.longDateFormat('LT'); + } + return format || ''; + } + + getFormat( type ) { + if ( type === 'date' ) { + return this.getDateFormat(); + } + else if ( type === 'time' ) { + return this.getTimeFormat(); + } + + let dateFormat = this.getDateFormat(); + let timeFormat = this.getTimeFormat(); + return dateFormat && timeFormat ? dateFormat + ' ' + timeFormat : (dateFormat || timeFormat ); + } + + _showView = ( view, date ) => { + const d = ( date || this.state.viewDate ).clone(); + const nextView = this.props.onBeforeNavigate( view, this.state.currentView, d ); + + if ( nextView && this.state.currentView !== nextView ) { + this.props.onNavigate( nextView ); + this.setState({ currentView: nextView }); + } + } + + updateTime( op, amount, type, toSelected ) { + let update = {}; + const date = toSelected ? 'selectedDate' : 'viewDate'; + + update[ date ] = this.state[ date ].clone()[ op ]( amount, type ); + + this.setState( update ); + } + + viewToMethod = {days: 'date', months: 'month', years: 'year'}; + nextView = { days: 'time', months: 'days', years: 'months'}; + _updateDate = e => { + let state = this.state; + let currentView = state.currentView; + let updateOnView = this.getUpdateOn( this.getFormat('date') ); + let viewDate = this.state.viewDate.clone(); + + // Set the value into day/month/year + viewDate[ this.viewToMethod[currentView] ]( + parseInt( e.target.getAttribute('data-value'), 10 ) + ); + + // Need to set month and year will for days view (prev/next month) + if ( currentView === 'days' ) { + viewDate.month( parseInt( e.target.getAttribute('data-month'), 10 ) ); + viewDate.year( parseInt( e.target.getAttribute('data-year'), 10 ) ); + } + + let update = {viewDate: viewDate}; + if ( currentView === updateOnView ) { + update.selectedDate = viewDate.clone(); + update.inputValue = viewDate.format( this.getFormat('datetime') ); + + if ( this.props.open === undefined && this.props.input && this.props.closeOnSelect ) { + this._closeCalendar(); + } + + this.props.onChange( viewDate.clone() ); + } + else { + this._showView( this.nextView[ currentView ], viewDate ); + } + + this.setState( update ); + } + + _viewNavigate = ( modifier, unit ) => { + let viewDate = this.state.viewDate.clone(); + + // Subtracting is just adding negative time + viewDate.add( modifier, unit ); + + if ( modifier > 0 ) { + this.props.onNavigateForward( modifier, unit ); + } + else { + this.props.onNavigateBack( -(modifier), unit ); + } + + this.setState({viewDate}); + } + + _setTime = ( type, value ) => { + let date = (this.getSelectedDate() || this.state.viewDate).clone(); + + date[ type ]( value ); + + if ( !this.props.value ) { + this.setState({ + selectedDate: date, + viewDate: date.clone(), + inputValue: date.format( this.getFormat('datetime') ) + }); + } + + this.props.onChange( date ); + } + + _openCalendar = () => { + if ( this.isOpen() ) return; + this.setState({open: true}, this.props.onOpen ); + } + + _closeCalendar = () => { + if ( !this.isOpen() ) return; + + this.setState({open: false}, () => { + this.props.onClose( this.state.selectedDate || this.state.inputValue ); + }); + } + + _handleClickOutside = () => { + let props = this.props; + + if ( props.input && this.state.open && props.open === undefined && props.closeOnClickOutside ) { + this._closeCalendar(); + } + } + + localMoment( date, format, props ) { + props = props || this.props; + let m = null; + + if (props.utc) { + m = moment.utc(date, format, props.strictParsing); + } else if (props.displayTimeZone) { + m = moment.tz(date, format, props.displayTimeZone); + } else { + m = moment(date, format, props.strictParsing); + } + + if ( props.locale ) + m.locale( props.locale ); + return m; + } + + checkTZ() { + const { displayTimeZone } = this.props; + if ( displayTimeZone && !this.tzWarning && !moment.tz ) { + this.tzWarning = true; + log('displayTimeZone prop with value "' + displayTimeZone + '" is used but moment.js timezone is not loaded.', 'error'); + } + } + + componentDidUpdate( prevProps ) { + if ( prevProps === this.props ) return; + + let needsUpdate = false; + let thisProps = this.props; + + ['locale', 'utc', 'displayZone', 'dateFormat', 'timeFormat'].forEach( function(p) { + prevProps[p] !== thisProps[p] && (needsUpdate = true); + }); + + if ( needsUpdate ) { + this.regenerateDates(); + } + + if ( thisProps.value && thisProps.value !== prevProps.value ) { + this.setViewDate( thisProps.value ); + } + + this.checkTZ(); + } + + regenerateDates() { + const props = this.props; + let viewDate = this.state.viewDate.clone(); + let selectedDate = this.state.selectedDate && this.state.selectedDate.clone(); + + if ( props.locale ) { + viewDate.locale( props.locale ); + selectedDate && selectedDate.locale( props.locale ); + } + if ( props.utc ) { + viewDate.utc(); + selectedDate && selectedDate.utc(); + } + else if ( props.displayTimeZone ) { + viewDate.tz( props.displayTimeZone ); + selectedDate && selectedDate.tz( props.displayTimeZone ); + } + else { + viewDate.locale(); + selectedDate && selectedDate.locale(); + } + + let update = { viewDate: viewDate, selectedDate: selectedDate}; + if ( selectedDate && selectedDate.isValid() ) { + update.inputValue = selectedDate.format( this.getFormat('datetime') ); + } + + this.setState( update ); + } + + getSelectedDate() { + if ( this.props.value === undefined ) return this.state.selectedDate; + let selectedDate = this.parseDate( this.props.value, this.getFormat('datetime') ); + return selectedDate && selectedDate.isValid() ? selectedDate : false; + } + + getInitialInputValue( selectedDate ) { + const props = this.props; + if ( props.inputProps.value ) + return props.inputProps.value; + + if ( selectedDate && selectedDate.isValid() ) + return selectedDate.format( this.getFormat('datetime') ); + + if ( props.value && typeof props.value === 'string' ) + return props.value; + + if ( props.initialValue && typeof props.initialValue === 'string' ) + return props.initialValue; + + return ''; + } + + getInputValue() { + let selectedDate = this.getSelectedDate(); + return selectedDate ? selectedDate.format( this.getFormat('datetime') ) : this.state.inputValue; + } + + /** + * 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. + * @param dateType date + * @public + */ + setViewDate( date ) { + let logError = function() { + return log( 'Invalid date passed to the `setViewDate` method: ' + date ); + }; + + if ( !date ) return logError(); + + let viewDate; + if ( typeof date === 'string' ) { + viewDate = this.localMoment(date, this.getFormat('datetime') ); + } + else { + viewDate = this.localMoment( date ); + } + + if ( !viewDate || !viewDate.isValid() ) return logError(); + this.setState({ viewDate: viewDate }); + } + + /** + * Set the view currently shown by the calendar. View modes shipped with react-datetime are 'years', 'months', 'days' and 'time'. + * @param TYPES.string mode + */ + navigate( mode ) { + this._showView( mode ); + } + + _onInputFocus = e => { + if ( !this.callHandler( this.props.inputProps.onFocus, e ) ) return; + this._openCalendar(); + } + + _onInputChange = e => { + if ( !this.callHandler( this.props.inputProps.onChange, e ) ) return; + + const value = e.target ? e.target.value : e; + const localMoment = this.localMoment( value, this.getFormat('datetime') ); + let update = { inputValue: value }; + + if ( localMoment.isValid() ) { + update.selectedDate = localMoment; + update.viewDate = localMoment.clone().startOf('month'); + } + else { + update.selectedDate = null; + } + + this.setState( update, () => { + this.props.onChange( localMoment.isValid() ? localMoment : this.state.inputValue ); + }); + } + + _onInputKeyDown = e => { + if ( !this.callHandler( this.props.inputProps.onKeyDown, e ) ) return; + + if ( e.which === 9 && this.props.closeOnTab ) { + this._closeCalendar(); + } + } + + _onInputClick = e => { + // Focus event should open the calendar, but there is some case where + // the input is already focused and the picker is closed, so clicking the input + // should open it again see https://github.com/arqex/react-datetime/issues/717 + if ( !this.callHandler( this.props.inputProps.onClick, e ) ) return; + this._openCalendar(); + } + + callHandler( method, e ) { + if ( !method ) return true; + return method(e) !== false; + } +} + +function log( message, method ) { + let con = typeof window !== 'undefined' && window.console; + if ( !con ) return; + + if ( !method ) { + method = 'warn'; + } + con[ method ]( '***react-datetime:' + message ); +} + +class ClickOutBase extends React.Component { + container = React.createRef(); + + render() { + return ( +
+ { this.props.children } +
+ ); + } + handleClickOutside(e) { + this.props.onClickOut( e ); + } + + setClickOutsideRef() { + return this.container.current; + } +} + +const ClickableWrapper = onClickOutside( ClickOutBase ); diff --git a/src/DaysView.js b/src/DaysView.js deleted file mode 100644 index 132309943..000000000 --- a/src/DaysView.js +++ /dev/null @@ -1,136 +0,0 @@ -'use strict'; - -var React = require('react'), - moment = require('moment') -; - -var DOM = React.DOM; -var DateTimePickerDays = React.createClass({ - - render: function() { - var footer = this.renderFooter(), - date = this.props.viewDate, - locale = date.localeData(), - tableChildren - ; - - tableChildren = [ - DOM.thead({ key: 'th'}, [ - DOM.tr({ key: 'h'}, [ - DOM.th({ key: 'p', className: 'rdtPrev' }, DOM.span({onClick: this.props.subtractTime(1, 'months')}, 'โ€น')), - DOM.th({ key: 's', className: 'rdtSwitch', onClick: this.props.showView('months'), colSpan: 5, 'data-value': this.props.viewDate.month() }, locale.months( date ) + ' ' + date.year() ), - DOM.th({ key: 'n', className: 'rdtNext' }, DOM.span({onClick: this.props.addTime(1, 'months')}, 'โ€บ')) - ]), - DOM.tr({ key: 'd'}, this.getDaysOfWeek( locale ).map( function( day, index ){ return DOM.th({ key: day + index, className: 'dow'}, day ); }) ) - ]), - DOM.tbody({key: 'tb'}, this.renderDays()) - ]; - - if ( footer ) - tableChildren.push( footer ); - - return DOM.div({ className: 'rdtDays' }, - DOM.table({}, tableChildren ) - ); - }, - - /** - * Get a list of the days of the week - * depending on the current locale - * @return {array} A list with the shortname of the days - */ - getDaysOfWeek: function( locale ){ - var days = locale._weekdaysMin, - first = locale.firstDayOfWeek(), - dow = [], - i = 0 - ; - - days.forEach( function( day ){ - dow[ (7 + (i++) - first) % 7 ] = day; - }); - - return dow; - }, - - renderDays: function() { - var date = this.props.viewDate, - selected = this.props.selectedDate && this.props.selectedDate.clone(), - prevMonth = date.clone().subtract( 1, 'months' ), - currentYear = date.year(), - currentMonth = date.month(), - weeks = [], - days = [], - renderer = this.props.renderDay || this.renderDay, - isValid = this.props.isValidDate || this.isValidDate, - classes, disabled, dayProps, currentDate - ; - - // Go to the last week of the previous month - prevMonth.date( prevMonth.daysInMonth() ).startOf('week'); - var lastDay = prevMonth.clone().add(42, 'd'); - - while ( prevMonth.isBefore( lastDay ) ){ - classes = 'rdtDay'; - currentDate = prevMonth.clone(); - - if ( ( prevMonth.year() === currentYear && prevMonth.month() < currentMonth ) || ( prevMonth.year() < currentYear ) ) - classes += ' rdtOld'; - else if ( ( prevMonth.year() === currentYear && prevMonth.month() > currentMonth ) || ( prevMonth.year() > currentYear ) ) - classes += ' rdtNew'; - - if ( selected && prevMonth.isSame(selected, 'day') ) - classes += ' rdtActive'; - - if (prevMonth.isSame(moment(), 'day') ) - classes += ' rdtToday'; - - disabled = !isValid( currentDate, selected ); - if ( disabled ) - classes += ' rdtDisabled'; - - dayProps = { - key: prevMonth.format('M_D'), - 'data-value': prevMonth.date(), - className: classes - }; - if ( !disabled ) - dayProps.onClick = this.updateSelectedDate; - - days.push( renderer( dayProps, currentDate, selected ) ); - - if ( days.length === 7 ){ - weeks.push( DOM.tr( {key: prevMonth.format('M_D')}, days ) ); - days = []; - } - - prevMonth.add( 1, 'd' ); - } - - return weeks; - }, - - updateSelectedDate: function( event ) { - this.props.updateSelectedDate(event, true); - }, - - renderDay: function( props, currentDate ){ - return DOM.td( props, currentDate.date() ); - }, - - renderFooter: function(){ - if ( !this.props.timeFormat ) - return ''; - - var date = this.props.selectedDate || this.props.viewDate; - - return DOM.tfoot({ key: 'tf'}, - DOM.tr({}, - DOM.td({ onClick: this.props.showView('time'), colSpan: 7, className: 'rdtTimeToggle'}, date.format( this.props.timeFormat )) - ) - ); - }, - isValidDate: function(){ return 1; } -}); - -module.exports = DateTimePickerDays; diff --git a/src/MonthsView.js b/src/MonthsView.js deleted file mode 100644 index cede357fa..000000000 --- a/src/MonthsView.js +++ /dev/null @@ -1,71 +0,0 @@ -'use strict'; - -var React = require('react'); - -var DOM = React.DOM; -var DateTimePickerMonths = React.createClass({ - render: function() { - return DOM.div({ className: 'rdtMonths' }, [ - DOM.table({ key: 'a'}, DOM.thead({}, DOM.tr({}, [ - DOM.th({ key: 'prev', className: 'rdtPrev' }, DOM.span({onClick: this.props.subtractTime(1, 'years')}, 'โ€น')), - DOM.th({ key: 'year', className: 'rdtSwitch', onClick: this.props.showView('years'), colSpan: 2, 'data-value': this.props.viewDate.year()}, this.props.viewDate.year() ), - DOM.th({ key: 'next', className: 'rdtNext' }, DOM.span({onClick: this.props.addTime(1, 'years')}, 'โ€บ')) - ]))), - DOM.table({ key: 'months'}, DOM.tbody({ key: 'b'}, this.renderMonths())) - ]); - }, - - renderMonths: function() { - var date = this.props.selectedDate, - month = this.props.viewDate.month(), - year = this.props.viewDate.year(), - rows = [], - i = 0, - months = [], - renderer = this.props.renderMonth || this.renderMonth, - classes, props - ; - - while (i < 12) { - classes = 'rdtMonth'; - if ( date && i === month && year === date.year() ) - classes += ' rdtActive'; - - props = { - key: i, - 'data-value': i, - className: classes, - onClick: this.props.updateOn === 'months'? this.updateSelectedMonth : this.props.setDate('month') - }; - - months.push( renderer( props, i, year, date && date.clone() )); - - if ( months.length === 4 ){ - rows.push( DOM.tr({ key: month + '_' + rows.length }, months) ); - months = []; - } - - i++; - } - - return rows; - }, - - updateSelectedMonth: function( event ) { - this.props.updateSelectedDate(event, true); - }, - - renderMonth: function( props, month ) { - var monthsShort = this.props.viewDate.localeData()._monthsShort; - return DOM.td( props, monthsShort.standalone - ? capitalize( monthsShort.standalone[ month ] ) - : monthsShort[ month ] - ); - } -}); - -function capitalize(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} - -module.exports = DateTimePickerMonths; diff --git a/src/TimeView.js b/src/TimeView.js deleted file mode 100644 index ea8f39671..000000000 --- a/src/TimeView.js +++ /dev/null @@ -1,204 +0,0 @@ -'use strict'; - -var React = require('react'), - assign = require('object-assign'); - -var DOM = React.DOM; -var DateTimePickerTime = React.createClass({ - getInitialState: function(){ - return this.calculateState( this.props ); - }, - calculateState: function( props ){ - var date = props.selectedDate || props.viewDate, - format = props.timeFormat, - counters = [] - ; - - if ( format.indexOf('H') !== -1 || format.indexOf('h') !== -1 ){ - counters.push('hours'); - if ( format.indexOf('m') !== -1 ){ - counters.push('minutes'); - if ( format.indexOf('s') !== -1 ){ - counters.push('seconds'); - } - } - } - - var daypart = false; - if ( this.props.timeFormat.indexOf(' A') !== -1 && this.state !== null ){ - daypart = ( this.state.hours >= 12 ) ? 'PM' : 'AM'; - } - - return { - hours: date.format('H'), - minutes: date.format('mm'), - seconds: date.format('ss'), - milliseconds: date.format('SSS'), - daypart: daypart, - counters: counters - }; - }, - renderCounter: function( type ){ - if (type !== 'daypart') { - var value = this.state[ type ]; - if (type === 'hours' && this.props.timeFormat.indexOf(' A') !== -1) { - value = (value - 1) % 12 + 1; - - if (value === 0) { - value = 12; - } - } - return DOM.div({ key: type, className: 'rdtCounter'}, [ - DOM.span({ key:'up', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'increase', type ) }, 'โ–ฒ' ), - DOM.div({ key:'c', className: 'rdtCount' }, value ), - DOM.span({ key:'do', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'decrease', type ) }, 'โ–ผ' ) - ]); - } - return ''; - }, - renderDayPart: function() { - return DOM.div({ className: 'rdtCounter', key: 'dayPart'}, [ - DOM.span({ key:'up', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'toggleDayPart', 'hours') }, 'โ–ฒ' ), - DOM.div({ key: this.state.daypart, className: 'rdtCount'}, this.state.daypart ), - DOM.span({ key:'do', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'toggleDayPart', 'hours') }, 'โ–ผ' ) - ]); - }, - render: function() { - var me = this, - counters = [] - ; - - this.state.counters.forEach( function(c){ - if ( counters.length ) - counters.push( DOM.div( {key: 'sep' + counters.length, className: 'rdtCounterSeparator' }, ':' )); - counters.push( me.renderCounter( c ) ); - }); - - if (this.state.daypart !== false) { - counters.push( me.renderDayPart() ); - } - - if ( this.state.counters.length === 3 && this.props.timeFormat.indexOf('S') !== -1 ){ - counters.push( DOM.div( {className: 'rdtCounterSeparator', key: 'sep5' }, ':' )); - counters.push( - DOM.div( {className: 'rdtCounter rdtMilli', key:'m'}, - DOM.input({ value: this.state.milliseconds, type: 'text', onChange: this.updateMilli }) - ) - ); - } - - return DOM.div( {className: 'rdtTime'}, - DOM.table( {}, [ - this.renderHeader(), - DOM.tbody({key: 'b'}, DOM.tr({}, DOM.td({}, - DOM.div({ className: 'rdtCounters' }, counters ) - ))) - ]) - ); - }, - componentWillMount: function() { - var me = this; - me.timeConstraints = { - hours: { - min: 0, - max: 23, - step: 1 - }, - minutes: { - min: 0, - max: 59, - step: 1 - }, - seconds: { - min: 0, - max: 59, - step: 1, - }, - milliseconds: { - min: 0, - max: 999, - step: 1 - } - }; - ['hours', 'minutes', 'seconds', 'milliseconds'].forEach(function(type) { - assign(me.timeConstraints[type], me.props.timeConstraints[type]); - }); - this.setState( this.calculateState( this.props ) ); - }, - componentWillReceiveProps: function( nextProps ){ - this.setState( this.calculateState( nextProps ) ); - }, - updateMilli: function( e ){ - var milli = parseInt( e.target.value, 10 ); - if ( milli === e.target.value && milli >= 0 && milli < 1000 ){ - this.props.setTime( 'milliseconds', milli ); - this.setState({ milliseconds: milli }); - } - }, - renderHeader: function(){ - if ( !this.props.dateFormat ) - return null; - - var date = this.props.selectedDate || this.props.viewDate; - return DOM.thead({ key: 'h'}, DOM.tr({}, - DOM.th( {className: 'rdtSwitch', colSpan: 4, onClick: this.props.showView('days')}, date.format( this.props.dateFormat ) ) - )); - }, - onStartClicking: function( action, type ){ - var me = this; - - return function(){ - var update = {}; - update[ type ] = me[ action ]( type ); - me.setState( update ); - - me.timer = setTimeout( function(){ - me.increaseTimer = setInterval( function(){ - update[ type ] = me[ action ]( type ); - me.setState( update ); - }, 70); - }, 500); - - me.mouseUpListener = function(){ - clearTimeout( me.timer ); - clearInterval( me.increaseTimer ); - me.props.setTime( type, me.state[ type ] ); - document.body.removeEventListener('mouseup', me.mouseUpListener); - }; - - document.body.addEventListener('mouseup', me.mouseUpListener); - }; - }, - padValues: { - hours: 1, - minutes: 2, - seconds: 2, - milliseconds: 3 - }, - toggleDayPart: function( type ){ // type is always 'hours' - var value = parseInt(this.state[ type ], 10) + 12; - if ( value > this.timeConstraints[ type ].max ) - value = this.timeConstraints[ type ].min + (value - (this.timeConstraints[ type ].max + 1)); - return this.pad( type, value ); - }, - increase: function( type ){ - var value = parseInt(this.state[ type ], 10) + this.timeConstraints[ type ].step; - if ( value > this.timeConstraints[ type ].max ) - value = this.timeConstraints[ type ].min + ( value - ( this.timeConstraints[ type ].max + 1) ); - return this.pad( type, value ); - }, - decrease: function( type ){ - var value = parseInt(this.state[ type ], 10) - this.timeConstraints[ type ].step; - if ( value < this.timeConstraints[ type ].min ) - value = this.timeConstraints[ type ].max + 1 - ( this.timeConstraints[ type ].min - value ); - return this.pad( type, value ); - }, - pad: function( type, value ){ - var str = value + ''; - while ( str.length < this.padValues[ type ] ) - str = '0' + str; - return str; - } -}); - -module.exports = DateTimePickerTime; diff --git a/src/YearsView.js b/src/YearsView.js deleted file mode 100644 index eae50ee1e..000000000 --- a/src/YearsView.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict'; - -var React = require('react'); - -var DOM = React.DOM; -var DateTimePickerYears = React.createClass({ - render: function() { - var year = parseInt(this.props.viewDate.year() / 10, 10) * 10; - - return DOM.div({ className: 'rdtYears' }, [ - DOM.table({ key: 'a'}, DOM.thead({}, DOM.tr({}, [ - DOM.th({ key: 'prev', className: 'rdtPrev' }, DOM.span({onClick: this.props.subtractTime(10, 'years')}, 'โ€น')), - DOM.th({ key: 'year', className: 'rdtSwitch', onClick: this.props.showView('years'), colSpan: 2 }, year + '-' + (year + 9) ), - DOM.th({ key: 'next', className: 'rdtNext'}, DOM.span({onClick: this.props.addTime(10, 'years')}, 'โ€บ')) - ]))), - DOM.table({ key: 'years'}, DOM.tbody({}, this.renderYears( year ))) - ]); - }, - - renderYears: function( year ) { - var years = [], - i = -1, - rows = [], - renderer = this.props.renderYear || this.renderYear, - selectedDate = this.props.selectedDate, - classes, props - ; - - year--; - while (i < 11) { - classes = 'rdtYear'; - if ( i === -1 | i === 10 ) - classes += ' rdtOld'; - if ( selectedDate && selectedDate.year() === year ) - classes += ' rdtActive'; - - props = { - key: year, - 'data-value': year, - className: classes, - onClick: this.props.updateOn === 'years' ? this.updateSelectedYear : this.props.setDate('year') - }; - - years.push( renderer( props, year, selectedDate && selectedDate.clone() )); - - if ( years.length === 4 ){ - rows.push( DOM.tr({ key: i }, years ) ); - years = []; - } - - year++; - i++; - } - - return rows; - }, - - updateSelectedYear: function( event ) { - this.props.updateSelectedDate(event, true); - }, - - renderYear: function( props, year ){ - return DOM.td( props, year ); - } -}); - -module.exports = DateTimePickerYears; diff --git a/src/onClickOutside.js b/src/onClickOutside.js deleted file mode 100644 index 86ebce131..000000000 --- a/src/onClickOutside.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict'; - -// This is extracted from https://github.com/Pomax/react-onclickoutside -// And modified to support react 0.13 and react 0.14 - -var React = require('react'), - version = React.version && React.version.split('.') -; - -if ( version && ( version[0] > 0 || version[1] > 13 ) ) - React = require('react-dom'); - -// Use a parallel array because we can't use -// objects as keys, they get toString-coerced -var registeredComponents = []; -var handlers = []; - -var IGNORE_CLASS = 'ignore-react-onclickoutside'; - -var isSourceFound = function(source, localNode) { - if (source === localNode) { - return true; - } - // SVG elements do not technically reside in the rendered DOM, so - // they do not have classList directly, but they offer a link to their - // corresponding element, which can have classList. This extra check is for - // that case. - // See: http://www.w3.org/TR/SVG11/struct.html#InterfaceSVGUseElement - // Discussion: https://github.com/Pomax/react-onclickoutside/pull/17 - if (source.correspondingElement) { - return source.correspondingElement.classList.contains(IGNORE_CLASS); - } - return source.classList.contains(IGNORE_CLASS); -}; - -module.exports = { - componentDidMount: function() { - if (typeof this.handleClickOutside !== 'function') - throw new Error('Component lacks a handleClickOutside(event) function for processing outside click events.'); - - var fn = this.__outsideClickHandler = (function(localNode, eventHandler) { - return function(evt) { - evt.stopPropagation(); - var source = evt.target; - var found = false; - // If source=local then this event came from "somewhere" - // inside and should be ignored. We could handle this with - // a layered approach, too, but that requires going back to - // thinking in terms of Dom node nesting, running counter - // to React's "you shouldn't care about the DOM" philosophy. - while (source.parentNode) { - found = isSourceFound(source, localNode); - if (found) return; - source = source.parentNode; - } - eventHandler(evt); - }; - }(React.findDOMNode(this), this.handleClickOutside)); - - var pos = registeredComponents.length; - registeredComponents.push(this); - handlers[pos] = fn; - - // If there is a truthy disableOnClickOutside property for this - // component, don't immediately start listening for outside events. - if (!this.props.disableOnClickOutside) { - this.enableOnClickOutside(); - } - }, - - componentWillUnmount: function() { - this.disableOnClickOutside(); - this.__outsideClickHandler = false; - var pos = registeredComponents.indexOf(this); - if ( pos>-1) { - if (handlers[pos]) { - // clean up so we don't leak memory - handlers.splice(pos, 1); - registeredComponents.splice(pos, 1); - } - } - }, - - /** - * Can be called to explicitly enable event listening - * for clicks and touches outside of this element. - */ - enableOnClickOutside: function() { - var fn = this.__outsideClickHandler; - document.addEventListener('mousedown', fn); - document.addEventListener('touchstart', fn); - }, - - /** - * Can be called to explicitly disable event listening - * for clicks and touches outside of this element. - */ - disableOnClickOutside: function() { - var fn = this.__outsideClickHandler; - document.removeEventListener('mousedown', fn); - document.removeEventListener('touchstart', fn); - } -}; diff --git a/src/parts/ViewNavigation.js b/src/parts/ViewNavigation.js new file mode 100644 index 000000000..a04d63454 --- /dev/null +++ b/src/parts/ViewNavigation.js @@ -0,0 +1,17 @@ +import React from 'react'; + +export default function ViewNavigation( { onClickPrev, onClickSwitch, onClickNext, switchContent, switchColSpan, switchProps } ) { + return ( + + + โ€น + + + { switchContent } + + + โ€บ + + + ); +} diff --git a/src/playground/App.js b/src/playground/App.js new file mode 100644 index 000000000..2673b5f9f --- /dev/null +++ b/src/playground/App.js @@ -0,0 +1,24 @@ +// This file is the playground used for development purposes (npm run playground) +// not part of the library +import React from 'react'; +import Datetime from '../DateTime'; + +// import moment from 'moment'; +// import 'moment/locale/tzm-latn'; +// moment.locale('tzm-latn'); + +class App extends React.Component { + state = { + date: new Date() + } + + render() { + return ( +
+ +
+ ); + } +} + +export default App; diff --git a/src/playground/index.js b/src/playground/index.js new file mode 100644 index 000000000..b0701525d --- /dev/null +++ b/src/playground/index.js @@ -0,0 +1,9 @@ +// This is the entry file for the playground, not part of the library +// it's used by running `npm run playground` + +import React from 'react'; +import ReactDOM from 'react-dom'; +import '../../css/react-datetime.css'; +import App from './App'; + +ReactDOM.render(, document.getElementById('root')); diff --git a/src/views/DaysView.js b/src/views/DaysView.js new file mode 100644 index 000000000..90499e126 --- /dev/null +++ b/src/views/DaysView.js @@ -0,0 +1,160 @@ +import React from 'react'; +import ViewNavigation from '../parts/ViewNavigation'; + +export default class DaysView extends React.Component { + static defaultProps = { + isValidDate: () => true, + renderDay: ( props, date ) => { date.date() }, + } + + render() { + return ( +
+ + + { this.renderNavigation() } + { this.renderDayHeaders() } + + + { this.renderDays() } + + { this.renderFooter() } +
+
+ ); + } + + renderNavigation() { + const date = this.props.viewDate; + const locale = date.localeData(); + return ( + this.props.navigate( -1, 'months' ) } + onClickSwitch={ () => this.props.showView( 'months' ) } + onClickNext={ () => this.props.navigate( 1, 'months' ) } + switchContent={ locale.months( date ) + ' ' + date.year() } + switchColSpan={5} + switchProps={ { 'data-value': this.props.viewDate.month() } } + /> + ); + } + + renderDayHeaders() { + const locale = this.props.viewDate.localeData(); + let dayItems = getDaysOfWeek( locale ).map( (day, index) => ( + { day } + )); + + return ( + + { dayItems } + + ); + } + + renderDays() { + const date = this.props.viewDate; + const startOfMonth = date.clone().startOf('month'); + const endOfMonth = date.clone().endOf('month'); + + // We need 42 days in 6 rows + // starting in the last week of the previous month + let rows = [[], [], [], [], [], []]; + + let startDate = date.clone().subtract( 1, 'months'); + startDate.date( startDate.daysInMonth() ).startOf('week'); + + let endDate = startDate.clone().add( 42, 'd' ); + let i = 0; + + while ( startDate.isBefore( endDate ) ) { + let row = getRow( rows, i++ ); + row.push( this.renderDay( startDate, startOfMonth, endOfMonth ) ); + startDate.add( 1, 'd' ); + } + + return rows.map( (r, i) => ( + { r } + )); + } + + renderDay( date, startOfMonth, endOfMonth ) { + let selectedDate = this.props.selectedDate; + + let dayProps = { + key: date.format('M_D'), + 'data-value': date.date(), + 'data-month': date.month(), + 'data-year': date.year() + }; + + let className = 'rdtDay'; + if ( date.isBefore( startOfMonth ) ) { + className += ' rdtOld'; + } + else if ( date.isAfter( endOfMonth ) ) { + className += ' rdtNew'; + } + if ( selectedDate && date.isSame( selectedDate, 'day' ) ) { + className += ' rdtActive'; + } + if ( date.isSame( this.props.moment(), 'day' ) ) { + className += ' rdtToday'; + } + + if ( this.props.isValidDate(date) ) { + dayProps.onClick = this._setDate; + } + else { + className += ' rdtDisabled'; + } + + dayProps.className = className; + + return this.props.renderDay( + dayProps, date.clone(), selectedDate && selectedDate.clone() + ); + } + + renderFooter() { + if ( !this.props.timeFormat ) return; + + const date = this.props.viewDate; + return ( + + + this.props.showView('time') } + colSpan={7} + className="rdtTimeToggle"> + { date.format( this.props.timeFormat ) } + + + + ); + } + + _setDate = e => { + this.props.updateDate( e ); + } +} + +function getRow( rows, day ) { + return rows[ Math.floor( day / 7 ) ]; +} + +/** + * Get a list of the days of the week + * depending on the current locale + * @return {array} A list with the shortname of the days + */ +function getDaysOfWeek( locale ) { + const first = locale.firstDayOfWeek(); + let dow = []; + let i = 0; + + locale._weekdaysMin.forEach(function (day) { + dow[(7 + (i++) - first) % 7] = day; + }); + + return dow; +} diff --git a/src/views/MonthsView.js b/src/views/MonthsView.js new file mode 100644 index 000000000..4fa629490 --- /dev/null +++ b/src/views/MonthsView.js @@ -0,0 +1,132 @@ +import React from 'react'; +import ViewNavigation from '../parts/ViewNavigation'; + +export default class MonthsView extends React.Component { + render() { + return ( +
+ + + { this.renderNavigation() } + +
+ + + { this.renderMonths() } + +
+
+ ); + } + + renderNavigation() { + let year = this.props.viewDate.year(); + + return ( + this.props.navigate( -1, 'years' ) } + onClickSwitch={ () => this.props.showView( 'years' ) } + onClickNext={ () => this.props.navigate( 1, 'years' ) } + switchContent={ year } + switchColSpan="2" + /> + ); + } + + renderMonths() { + // 12 months in 3 rows for every view + let rows = [ [], [], [] ]; + + for ( let month = 0; month < 12; month++ ) { + let row = getRow( rows, month ); + + row.push( this.renderMonth( month ) ); + } + + return rows.map( (months, i) => ( + { months } + )); + } + + renderMonth( month ) { + const selectedDate = this.props.selectedDate; + let className = 'rdtMonth'; + let onClick; + + if ( this.isDisabledMonth( month ) ) { + className += ' rdtDisabled'; + } + else { + onClick = this._updateSelectedMonth; + } + + if ( selectedDate && selectedDate.year() === this.props.viewDate.year() && selectedDate.month() === month ) { + className += ' rdtActive'; + } + + let props = {key: month, className, 'data-value': month, onClick }; + + if ( this.props.renderMonth ) { + return this.props.renderMonth( + props, + month, + this.props.viewDate.year(), + this.props.selectedDate && this.props.selectedDate.clone() + ); + } + + return ( + + { this.getMonthText( month ) } + + ); + } + + isDisabledMonth( month ) { + let isValidDate = this.props.isValidDate; + + if ( !isValidDate ) { + // If no validator is set, all days are valid + return false; + } + + // If one day in the month is valid, the year should be clickable + let date = this.props.viewDate.clone().set({month}); + let day = date.endOf( 'month' ).date() + 1; + + while ( day-- > 1 ) { + if ( isValidDate( date.date(day) ) ) { + return false; + } + } + return true; + } + + getMonthText( month ) { + const localMoment = this.props.viewDate; + const monthStr = localMoment.localeData().monthsShort( localMoment.month( month ) ); + + // Because some months are up to 5 characters long, we want to + // use a fixed string length for consistency + return capitalize( monthStr.substring( 0, 3 ) ); + } + + _updateSelectedMonth = event => { + this.props.updateDate( event ); + } +} + +function getRow( rows, year ) { + if ( year < 4 ) { + return rows[0]; + } + if ( year < 8 ) { + return rows[1]; + } + + return rows[2]; +} + +function capitalize( str ) { + return str.charAt( 0 ).toUpperCase() + str.slice( 1 ); +} diff --git a/src/views/TimeView.js b/src/views/TimeView.js new file mode 100644 index 000000000..210cdce22 --- /dev/null +++ b/src/views/TimeView.js @@ -0,0 +1,248 @@ +import React from 'react'; + +const timeConstraints = { + hours: { + min: 0, + max: 23, + step: 1 + }, + minutes: { + min: 0, + max: 59, + step: 1 + }, + seconds: { + min: 0, + max: 59, + step: 1 + }, + milliseconds: { + min: 0, + max: 999, + step: 1 + } +}; + +function createConstraints( overrideTimeConstraints ) { + let constraints = {}; + + Object.keys( timeConstraints ).forEach( type => { + constraints[ type ] = { ...timeConstraints[type], ...(overrideTimeConstraints[type] || {}) }; + }); + + return constraints; +} + +export default class TimeView extends React.Component { + constructor( props ) { + super( props ); + + this.constraints = createConstraints( props.timeConstraints ); + + // This component buffers the time part values in the state + // while the user is pressing down the buttons + // and call the prop `setTime` when the buttons are released + this.state = this.getTimeParts( props.selectedDate || props.viewDate ); + } + + render() { + let items = []; + const timeParts = this.state; + + this.getCounters().forEach( (c, i) => { + if ( i && c !== 'ampm' ) { + items.push( +
:
+ ); + } + + items.push( this.renderCounter(c, timeParts[c]) ); + }); + + return ( +
+ + { this.renderHeader() } + + + + + +
+
+ { items } +
+
+
+ ); + } + + renderCounter( type, value ) { + if ( type === 'hours' && this.isAMPM() ) { + value = ( value - 1 ) % 12 + 1; + + if ( value === 0 ) { + value = 12; + } + } + + if ( type === 'ampm' ) { + if ( this.props.timeFormat.indexOf(' A') !== -1 ) { + value = this.props.viewDate.format('A'); + } + else { + value = this.props.viewDate.format('a'); + } + } + + return ( +
+ this.onStartClicking( e, 'increase', type)}>โ–ฒ +
{ value }
+ this.onStartClicking( e, 'decrease', type)}>โ–ผ +
+ ); + } + + renderHeader() { + if ( !this.props.dateFormat ) return; + + const date = this.props.selectedDate || this.props.viewDate; + + return ( + + + this.props.showView('days') }> + { date.format( this.props.dateFormat ) } + + + + ); + } + + onStartClicking( e, action, type ) { + if ( e && e.button && e.button !== 0 ) { + // Only left clicks, thanks + return; + } + + if ( type === 'ampm' ) return this.toggleDayPart(); + + let update = {}; + let body = document.body; + update[ type ] = this[ action ]( type ); + this.setState( update ); + + this.timer = setTimeout( () => { + this.increaseTimer = setInterval( () => { + update[ type ] = this[ action ]( type ); + this.setState( update ); + }, 70); + }, 500); + + this.mouseUpListener = () => { + clearTimeout( this.timer ); + clearInterval( this.increaseTimer ); + this.props.setTime( type, parseInt( this.state[ type ], 10 ) ); + body.removeEventListener( 'mouseup', this.mouseUpListener ); + body.removeEventListener( 'touchend', this.mouseUpListener ); + }; + + body.addEventListener( 'mouseup', this.mouseUpListener ); + body.addEventListener( 'touchend', this.mouseUpListener ); + } + + toggleDayPart() { + let hours = parseInt( this.state.hours, 10 ); + + if ( hours >= 12 ) { + hours -= 12; + } + else { + hours += 12; + } + + this.props.setTime( 'hours', hours ); + } + + increase( type ) { + const tc = this.constraints[ type ]; + let value = parseInt( this.state[ type ], 10) + tc.step; + if ( value > tc.max ) + value = tc.min + ( value - ( tc.max + 1 ) ); + return pad( type, value ); + } + + decrease( type ) { + const tc = this.constraints[ type ]; + let value = parseInt( this.state[ type ], 10) - tc.step; + if ( value < tc.min ) + value = tc.max + 1 - ( tc.min - value ); + return pad( type, value ); + } + + getCounters() { + let counters = []; + let format = this.props.timeFormat; + + if ( format.toLowerCase().indexOf('h') !== -1 ) { + counters.push('hours'); + if ( format.indexOf('m') !== -1 ) { + counters.push('minutes'); + if ( format.indexOf('s') !== -1 ) { + counters.push('seconds'); + if ( format.indexOf('S') !== -1 ) { + counters.push('milliseconds'); + } + } + } + } + + if ( this.isAMPM() ) { + counters.push('ampm'); + } + + return counters; + } + + isAMPM() { + return this.props.timeFormat.toLowerCase().indexOf( ' a' ) !== -1; + } + + getTimeParts( date ) { + const hours = date.hours(); + + return { + hours: pad( 'hours', hours ), + minutes: pad( 'minutes', date.minutes() ), + seconds: pad( 'seconds', date.seconds() ), + milliseconds: pad('milliseconds', date.milliseconds() ), + ampm: hours < 12 ? 'am' : 'pm' + }; + } + + componentDidUpdate( prevProps ) { + if ( this.props.selectedDate ) { + if ( this.props.selectedDate !== prevProps.selectedDate ) { + this.setState( this.getTimeParts( this.props.selectedDate ) ); + } + } + else if ( prevProps.viewDate !== this.props.viewDate ) { + this.setState( this.getTimeParts( this.props.viewDate ) ); + } + } +} + +function pad( type, value ) { + const padValues = { + hours: 1, + minutes: 2, + seconds: 2, + milliseconds: 3 + }; + + let str = value + ''; + while ( str.length < padValues[ type ] ) + str = '0' + str; + return str; +} diff --git a/src/views/YearsView.js b/src/views/YearsView.js new file mode 100644 index 000000000..933d7c4dd --- /dev/null +++ b/src/views/YearsView.js @@ -0,0 +1,131 @@ +import React from 'react'; +import ViewNavigation from '../parts/ViewNavigation'; + +export default class YearsView extends React.Component { + static defaultProps = { + renderYear: ( props, year ) => { year }, + }; + + render() { + return ( +
+ + + { this.renderNavigation() } + +
+ + + { this.renderYears() } + +
+
+ ); + } + + renderNavigation() { + const viewYear = this.getViewYear(); + return ( + this.props.navigate( -10, 'years' ) } + onClickSwitch={ () => this.props.showView( 'years' ) } + onClickNext={ () => this.props.navigate( 10, 'years' ) } + switchContent={ `${viewYear}-${viewYear + 9}` } + /> + ); + } + + renderYears() { + const viewYear = this.getViewYear(); + // 12 years in 3 rows for every view + let rows = [ [], [], [] ]; + for ( let year = viewYear - 1; year < viewYear + 11; year++ ) { + let row = getRow( rows, year - viewYear ); + + row.push( + this.renderYear( year ) + ); + } + + return rows.map( (years, i) => ( + { years } + )); + } + + renderYear( year ) { + const selectedYear = this.getSelectedYear(); + let className = 'rdtYear'; + let onClick; + + if ( this.isDisabledYear( year ) ) { + className += ' rdtDisabled'; + } + else { + onClick = this._updateSelectedYear; + } + + if ( selectedYear === year ) { + className += ' rdtActive'; + } + + let props = {key: year, className, 'data-value': year, onClick }; + + return this.props.renderYear( + props, + year, + this.props.selectedDate && this.props.selectedDate.clone() + ); + } + + getViewYear() { + return parseInt( this.props.viewDate.year() / 10, 10 ) * 10; + } + + getSelectedYear() { + return this.props.selectedDate && this.props.selectedDate.year(); + } + + disabledYearsCache = {}; + isDisabledYear( year ) { + let cache = this.disabledYearsCache; + if ( cache[year] !== undefined ) { + return cache[year]; + } + + let isValidDate = this.props.isValidDate; + + if ( !isValidDate ) { + // If no validator is set, all days are valid + return false; + } + + // If one day in the year is valid, the year should be clickable + let date = this.props.viewDate.clone().set({year}); + let day = date.endOf( 'year' ).dayOfYear() + 1; + + while ( day-- > 1 ) { + if ( isValidDate( date.dayOfYear(day) ) ) { + cache[year] = false; + return false; + } + } + + cache[year] = true; + return true; + } + + _updateSelectedYear = event => { + this.props.updateDate( event ); + } +} + +function getRow( rows, year ) { + if ( year < 3 ) { + return rows[0]; + } + if ( year < 7 ) { + return rows[1]; + } + + return rows[2]; +} diff --git a/test/__snapshots__/snapshots.spec.js.snap b/test/__snapshots__/snapshots.spec.js.snap new file mode 100644 index 000000000..7dcf4ee1b --- /dev/null +++ b/test/__snapshots__/snapshots.spec.js.snap @@ -0,0 +1,11920 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`className: set to arbitraty value 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`dateFormat set to false 1`] = ` +
+ +
+
+ + + + + + +
+
+
+ + โ–ฒ + +
+ 12 +
+ + โ–ผ + +
+
+ : +
+
+ + โ–ฒ + +
+ 00 +
+ + โ–ผ + +
+
+ + โ–ฒ + +
+ AM +
+ + โ–ผ + +
+
+
+
+
+
+`; + +exports[`dateFormat set to true 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`defaultValue: set to arbitrary value 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`everything default: renders correctly 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`input input: set to false 1`] = ` +
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`input input: set to true 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`inputProps with className specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`inputProps with disabled specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`inputProps with name specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`inputProps with placeholder specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`inputProps with required specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`isValidDate: only valid if after yesterday 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`open set to false 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`open set to true 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`renderDay: specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 027 + + 028 + + 029 + + 030 + + 01 + + 02 + + 03 +
+ 04 + + 05 + + 06 + + 07 + + 08 + + 09 + + 010 +
+ 011 + + 012 + + 013 + + 014 + + 015 + + 016 + + 017 +
+ 018 + + 019 + + 020 + + 021 + + 022 + + 023 + + 024 +
+ 025 + + 026 + + 027 + + 028 + + 029 + + 030 + + 031 +
+ 01 + + 02 + + 03 + + 04 + + 05 + + 06 + + 07 +
+ 12:00 AM +
+
+
+
+`; + +exports[`renderMonth: specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`renderYear: specified 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`timeFormat set to false 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+
+
+
+`; + +exports[`timeFormat set to true 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`value: set to arbitrary value 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`viewMode set to days 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`viewMode set to months 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`viewMode set to time 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; + +exports[`viewMode set to years 1`] = ` +
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + โ€น + + + December 2016 + + + โ€บ + +
+ Su + + Mo + + Tu + + We + + Th + + Fr + + Sa +
+ 27 + + 28 + + 29 + + 30 + + 1 + + 2 + + 3 +
+ 4 + + 5 + + 6 + + 7 + + 8 + + 9 + + 10 +
+ 11 + + 12 + + 13 + + 14 + + 15 + + 16 + + 17 +
+ 18 + + 19 + + 20 + + 21 + + 22 + + 23 + + 24 +
+ 25 + + 26 + + 27 + + 28 + + 29 + + 30 + + 31 +
+ 1 + + 2 + + 3 + + 4 + + 5 + + 6 + + 7 +
+ 12:00 AM +
+
+
+
+`; diff --git a/test/snapshots.spec.js b/test/snapshots.spec.js new file mode 100644 index 000000000..79e050ba6 --- /dev/null +++ b/test/snapshots.spec.js @@ -0,0 +1,210 @@ +/* global it, describe, expect, jest */ + +import React from 'react'; // eslint-disable-line no-unused-vars +import Datetime from '../src/DateTime'; +import renderer from 'react-test-renderer'; + +// findDOMNode is not supported by the react-test-renderer, +// and even though this component is not using that method +// a dependency is probably using it. So we need to mock it +// to make the tests pass. +// https://github.com/facebook/react/issues/7371 +jest.mock('react-dom', () => ({ + findDOMNode: () => {}, +})); + +// Mock date to get rid of time as a factor to make tests deterministic +// 2016-12-21T23:36:07.071Z +Date.now = jest.fn(() => 1482363367071); + +it('everything default: renders correctly', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +it('value: set to arbitrary value', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +it('defaultValue: set to arbitrary value', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +describe('dateFormat', () => { + it('set to true', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('set to false', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); +}); + +describe('timeFormat', () => { + it('set to true', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('set to false', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); +}); + +describe('input', () => { + it('input: set to true', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('input: set to false', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); +}); + +describe('open', () => { + it('set to true', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('set to false', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); +}); + +describe('viewMode', () => { + it('set to days', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('set to months', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('set to years', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('set to time', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); +}); + +it('className: set to arbitraty value', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +describe('inputProps', () => { + it('with placeholder specified', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('with disabled specified', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('with required specified', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('with name specified', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); + + it('with className specified', () => { + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); + }); +}); + +it('isValidDate: only valid if after yesterday', () => { + const yesterday = Datetime.moment().subtract(1, 'day'); + const valid = (current) => current.isAfter(yesterday); + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +it('renderDay: specified', () => { + const renderDay = (props, currentDate) => { '0' + currentDate.date() }; + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +it('renderMonth: specified', () => { + const renderMonth = (props, currentDate) => { '0' + currentDate.date() }; + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); + +it('renderYear: specified', () => { + const renderYear = (props, currentDate) => { '0' + currentDate.date() }; + const tree = renderer.create( + + ).toJSON(); + expect(tree).toMatchSnapshot(); +}); diff --git a/test/testUtils.js b/test/testUtils.js new file mode 100644 index 000000000..c1d35f821 --- /dev/null +++ b/test/testUtils.js @@ -0,0 +1,141 @@ +import React from 'react'; // eslint-disable-line no-unused-vars +import { mount, shallow } from 'enzyme'; +import Datetime from '../dist/react-datetime.cjs'; // eslint-disable-line no-unused-vars + +const _simulateClickOnElement = (element) => { + if (element.length === 0) { + // eslint-disable-next-line no-console + console.warn('Element not clicked since it doesn\'t exist'); + return; + } + return element.simulate('click'); +}; + +module.exports = { + createDatetime: (props) => { + return mount(); + }, + + createDatetimeShallow: (props) => { + return shallow(); + }, + + /* + * Click Simulations + */ + openDatepicker: (datetime) => { + datetime.find('.form-control').simulate('focus'); + }, + + openDatepickerByClick: datetime => { + datetime.find('.form-control').simulate('click'); + }, + + clickOnElement: (element) => { + return _simulateClickOnElement(element); + }, + + clickNthDay: (datetime, n) => { + return _simulateClickOnElement(datetime.find('.rdtDay').at(n)); + }, + + clickNthMonth: (datetime, n) => { + return _simulateClickOnElement(datetime.find('.rdtMonth').at(n)); + }, + + clickNthYear: (datetime, n) => { + return _simulateClickOnElement(datetime.find('.rdtYear').at(n)); + }, + + clickClassItem: (datetime, cn, n) => { + return _simulateClickOnElement( datetime.find(cn).at(n) ); + }, + + /* + * Boolean Checks + */ + isOpen: (datetime) => { + var open = datetime.find('.rdt.rdtOpen').length > 0; + return open; + }, + + isDayView: (datetime) => { + return datetime.find('.rdtPicker .rdtDays').length > 0; + }, + + isMonthView: (datetime) => { + return datetime.find('.rdtPicker .rdtMonths').length > 0; + }, + + isYearView: (datetime) => { + return datetime.find('.rdtPicker .rdtYears').length > 0; + }, + + isTimeView: (datetime) => { + return datetime.find('.rdtPicker .rdtTime').length > 0; + }, + + /* + * Change Time Values + * + * These functions only work when the time view is open + */ + increaseHour: (datetime) => { + datetime.find('.rdtCounter .rdtBtn').at(0).simulate('mouseDown'); + }, + + decreaseHour: (datetime) => { + datetime.find('.rdtCounter .rdtBtn').at(1).simulate('mouseDown'); + }, + + increaseMinute: (datetime) => { + datetime.find('.rdtCounter .rdtBtn').at(2).simulate('mouseDown'); + }, + + decreaseMinute: (datetime) => { + datetime.find('.rdtCounter .rdtBtn').at(3).simulate('mouseDown'); + }, + + increaseSecond: (datetime) => { + datetime.find('.rdtCounter .rdtBtn').at(4).simulate('mouseDown'); + }, + + decreaseSecond: (datetime) => { + datetime.find('.rdtCounter .rdtBtn').at(5).simulate('mouseDown'); + }, + + /* + * Get Values + */ + getNthDay: (datetime, n) => { + return datetime.find('.rdtDay').at(n); + }, + + getNthMonth: (datetime, n) => { + return datetime.find('.rdtMonth').at(n); + }, + + getNthYear: (datetime, n) => { + return datetime.find('.rdtYear').at(n); + }, + + getHours: (datetime) => { + return datetime.find('.rdtCount').at(0).text(); + }, + + getMinutes: (datetime) => { + return datetime.find('.rdtCount').at(1).text(); + }, + + getSeconds: (datetime) => { + return datetime.find('.rdtCount').at(2).text(); + }, + + getInputValue: (datetime) => { + return datetime.find('.rdt > .form-control').getDOMNode().value; + }, + + getViewDateValue: (datetime) => { + return datetime.find('.rdtSwitch').getDOMNode().innerHTML; + } +}; diff --git a/test/tests.spec.js b/test/tests.spec.js new file mode 100644 index 000000000..498afa2ec --- /dev/null +++ b/test/tests.spec.js @@ -0,0 +1,1534 @@ +/* global it, xit, describe, expect, done, jest */ + +import React from 'react'; +import moment from 'moment'; +import 'moment/locale/nl'; +import 'moment/locale/sv'; +import _momentTimezone from 'moment-timezone'; // eslint-disable-line +import utils from './testUtils'; +import Enzyme from 'enzyme'; +import Adapter from 'enzyme-adapter-react-16'; + +moment.locale('en'); + +Enzyme.configure({ adapter: new Adapter() }); + +describe('Datetime', () => { + it('create component', () => { + const component = utils.createDatetime({}); + + expect(component).toBeDefined(); + expect(component.find('.rdt > .form-control').length).toEqual(1); + expect(component.find('.rdt > .rdtPicker').length).toEqual(1); + }); + + it('initialViewMode=days: renders days, week days, month, year', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'days', initialValue: date }); + utils.openDatepicker(component); + + // Month and year + expect(component.find('.rdtSwitch').text()).toEqual('January 2000'); + + // Week days + const expectedWeekDays = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + actualWeekdays = component.find('.rdtDays .dow').map((element) => + element.text() + ); + expect(actualWeekdays).toEqual(expectedWeekDays); + + // Dates + // "Old" dates belonging to prev month + const oldDatesIndexes = [0, 1, 2, 3, 4, 5]; + oldDatesIndexes.forEach((index) => { + expect(utils.getNthDay(component, index).hasClass('rdtOld')).toBeTruthy(); + }); + + // Dates belonging to current month + for (let i = 6; i < 37; i++) { + expect(utils.getNthDay(component, i).hasClass('rdtDay')).toBeTruthy(); + expect(utils.getNthDay(component, i).hasClass('rdtOld')).toBeFalsy(); + expect(utils.getNthDay(component, i).hasClass('rdtNew')).toBeFalsy(); + } + + // "New" dates belonging to next month + const nextDatesIndexes = [37, 38, 39, 40, 41]; + nextDatesIndexes.forEach((index) => { + expect(utils.getNthDay(component, index).hasClass('rdtNew')).toBeTruthy(); + }); + }); + + it('switch from day view to time view and back', () => { + const component = utils.createDatetime({}); + + expect(utils.isDayView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtTimeToggle')); + expect(utils.isTimeView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isDayView(component)).toBeTruthy(); + }); + + it('persistent valid months going monthView->yearView->monthView', () => { + const oldNow = Date.now; + Date.now = () => new Date('2018-06-01T00:00:00').getTime(); + + const dateBefore = '2018-06-01'; + const component = utils.createDatetime({ + initialViewMode: 'months', + value: new Date(2018, 10, 10), + isValidDate: current => current.isBefore(moment(dateBefore, 'YYYY-MM-DD')) + }); + + expect(utils.isMonthView(component)).toBeTruthy(); + expect(utils.getNthMonth(component, 4).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthMonth(component, 5).hasClass('rdtDisabled')).toEqual(true); + + // Go to year view + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isYearView(component)).toBeTruthy(); + + expect(utils.getNthYear(component, 0).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthYear(component, 10).hasClass('rdtDisabled')).toEqual(true); + + utils.clickNthYear(component, 9); + expect(utils.getNthMonth(component, 4).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthMonth(component, 5).hasClass('rdtDisabled')).toEqual(true); + + Date.now = oldNow; + }); + + it('step through views', () => { + const component = utils.createDatetime({ initialViewMode: 'time' }); + + expect(utils.isTimeView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isDayView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isMonthView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isYearView(component)).toBeTruthy(); + }); + + it('toggles calendar when open prop changes', () => { + const component = utils.createDatetime({ open: false }); + expect(utils.isOpen(component)).toBeFalsy(); + // expect(component.find('.rdtOpen').length).toEqual(0); + component.setProps({ open: true }); + expect(utils.isOpen(component)).toBeTruthy(); + // expect(component.find('.rdtOpen').length).toEqual(1); + component.setProps({ open: false }); + expect(utils.isOpen(component)).toBeFalsy(); + // expect(component.find('.rdtOpen').length).toEqual(0); + }); + + it('selectYear', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'years', initialValue: date }); + expect(utils.isYearView(component)).toBeTruthy(); + expect(component.find('.rdtSwitch').text()).toEqual('2000-2009'); + + // Click first year (1999) + utils.clickOnElement(component.find('.rdtYear').at(0)); + expect(utils.isMonthView(component)).toBeTruthy(); + expect(component.find('.rdtSwitch').text()).toEqual('1999'); + }); + + it('increase decade', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'years', initialValue: date }); + + expect(component.find('.rdtSwitch').text()).toEqual('2000-2009'); + utils.clickOnElement(component.find('.rdtNext span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('2010-2019'); + utils.clickOnElement(component.find('.rdtNext span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('2020-2029'); + }); + + it('decrease decade', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'years', initialValue: date }); + + expect(component.find('.rdtSwitch').text()).toEqual('2000-2009'); + utils.clickOnElement(component.find('.rdtPrev span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('1990-1999'); + utils.clickOnElement(component.find('.rdtPrev span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('1980-1989'); + }); + + it('select month', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'months', initialValue: date }); + + expect(utils.isMonthView(component)).toBeTruthy(); + expect(component.find('.rdtSwitch').text()).toEqual('2000'); + // Click any month to enter day view + utils.clickNthMonth(component, 1); + expect(utils.isDayView(component)).toBeTruthy(); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('1'); + }); + + it('increase year', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'months', initialValue: date }); + + expect(component.find('.rdtSwitch').text()).toEqual('2000'); + utils.clickOnElement(component.find('.rdtNext span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('2001'); + utils.clickOnElement(component.find('.rdtNext span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('2002'); + }); + + it('decrease year', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'months', initialValue: date }); + + expect(component.find('.rdtSwitch').text()).toEqual('2000'); + utils.clickOnElement(component.find('.rdtPrev span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('1999'); + utils.clickOnElement(component.find('.rdtPrev span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('1998'); + }); + + it('increase month', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialValue: date }); + + expect(component.find('.rdtSwitch').text()).toEqual('January 2000'); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('0'); + utils.clickOnElement(component.find('.rdtNext span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('February 2000'); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('1'); + utils.clickOnElement(component.find('.rdtNext span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('March 2000'); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('2'); + }); + + it('decrease month', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialValue: date }); + + expect(component.find('.rdtSwitch').text()).toEqual('January 2000'); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('0'); + utils.clickOnElement(component.find('.rdtPrev span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('December 1999'); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('11'); + utils.clickOnElement(component.find('.rdtPrev span').at(0)); + expect(component.find('.rdtSwitch').text()).toEqual('November 1999'); + expect(component.find('.rdtSwitch').getDOMNode().getAttribute('data-value')).toEqual('10'); + }); + + it('open picker', () => { + const component = utils.createDatetime(); + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + }); + + it('click on day of the next month', () => { + const component = utils.createDatetime({ + initialViewMode: 'days', + initialValue: new Date(2019, 0, 1) + }); + + utils.openDatepicker(component); + utils.clickClassItem(component, '.rdtNew', 1); + + expect(component.find('.rdtSwitch').text()).toEqual('February 2019'); + }); + + it('click on day of the prev month', () => { + const component = utils.createDatetime({ + initialViewMode: 'days', + initialValue: new Date(2019, 0, 1) + }); + + utils.openDatepicker(component); + utils.clickClassItem(component, '.rdtOld', 1); + + expect(component.find('.rdtSwitch').text()).toEqual('December 2018'); + }); + + it('sets CSS class on selected item (day)', () => { + const component = utils.createDatetime({ initialViewMode: 'days' }); + utils.openDatepicker(component); + utils.clickNthDay(component, 13); + expect(utils.getNthDay(component, 13).hasClass('rdtActive')).toBeTruthy(); + }); + + it('sets CSS class on selected item (month)', () => { + const component = utils.createDatetime({ initialViewMode: 'months', dateFormat: 'YYYY-MM' }); + utils.openDatepicker(component); + utils.clickNthMonth(component, 4); + expect(utils.getNthMonth(component, 4).hasClass('rdtActive')).toBeTruthy(); + }); + + it('sets CSS class on selected item (year)', () => { + const component = utils.createDatetime({ initialViewMode: 'years', dateFormat: 'YYYY' }); + utils.openDatepicker(component); + utils.clickNthYear(component, 3); + expect(utils.getNthYear(component, 3).hasClass('rdtActive')).toBeTruthy(); + }); + + it('sets CSS class on days outside of month', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + prevMonthDaysIndexes = [0, 1, 2, 3, 4, 5], + nextMonthDaysIndexes = [37, 38, 39, 40, 41], + component = utils.createDatetime({ initialViewMode: 'days', initialValue: date }); + + utils.openDatepicker(component); + + prevMonthDaysIndexes.forEach((index) => { + expect(utils.getNthDay(component, index).hasClass('rdtOld')).toBeTruthy(); + }); + nextMonthDaysIndexes.forEach((index) => { + expect(utils.getNthDay(component, index).hasClass('rdtNew')).toBeTruthy(); + }); + }); + + it('selected day persists (in UI) when navigating to prev month', () => { + const date = new Date(2000, 0, 3, 2, 2, 2, 2), + component = utils.createDatetime({ initialViewMode: 'days', initialValue: date }); + + utils.openDatepicker(component); + expect(utils.getNthDay(component, 8).hasClass('rdtActive')).toBeTruthy(); + // Go to previous month + utils.clickOnElement(component.find('.rdtDays .rdtPrev span')); + expect(utils.getNthDay(component, 36).hasClass('rdtActive')).toBeTruthy(); + }); + + it('sets CSS class on today date', () => { + const specificDate = moment(), + day = specificDate.date(), + component = utils.createDatetime({ initialValue: specificDate }) + ; + + utils.openDatepicker(component); + expect(component.find('.rdtToday').text()).toEqual( day+'' ); + }); + + describe('with custom props', () => { + it('input=false', () => { + const component = utils.createDatetime({ input: false }); + expect(component.find('.rdt > .form-control').length).toEqual(0); + expect(component.find('.rdt > .rdtPicker').length).toEqual(1); + }); + + it('dateFormat', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + component = utils.createDatetime({ value: date, dateFormat: 'M&D' }); + expect(utils.getInputValue(component)).toEqual(mDate.format('M&D LT')); + }); + + it('dateFormat=false', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + component = utils.createDatetime({ value: date, dateFormat: false }); + expect(utils.getInputValue(component)).toEqual(mDate.format('LT')); + // Make sure time view is active + expect(utils.isTimeView(component)).toBeTruthy(); + // Make sure the date toggle is not rendered + expect(component.find('thead').length).toEqual(0); + }); + + it('timeFormat', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + format = 'HH:mm:ss:SSS', + component = utils.createDatetime({ value: date, timeFormat: format }); + expect(utils.getInputValue(component)).toEqual(mDate.format('L ' + format)); + }); + + it('timeFormat=false', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + component = utils.createDatetime({ value: date, timeFormat: false }); + expect(utils.getInputValue(component)).toEqual(mDate.format('L')); + // Make sure day view is active + expect(utils.isDayView(component)).toBeTruthy(); + // Make sure the time toggle is not rendered + expect(component.find('.timeToggle').length).toEqual(0); + }); + + it('timeFormat with lowercase \'am\'', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + format = 'HH:mm:ss:SSS a', + component = utils.createDatetime({ value: date, timeFormat: format }); + expect(utils.getInputValue(component)).toEqual(expect.stringMatching('.*am$')); + }); + + it('timeFormat with uppercase \'AM\'', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + format = 'HH:mm:ss:SSS A', + component = utils.createDatetime({ value: date, timeFormat: format }); + expect(utils.getInputValue(component)).toEqual(expect.stringMatching('.*AM$')); + }); + + it('initialViewMode=years', () => { + const component = utils.createDatetime({ initialViewMode: 'years' }); + expect(utils.isYearView(component)).toBeTruthy(); + }); + + it('initialViewMode=months', () => { + const component = utils.createDatetime({ initialViewMode: 'months' }); + expect(utils.isMonthView(component)).toBeTruthy(); + }); + + it('initialViewMode=time', () => { + const component = utils.createDatetime({ initialViewMode: 'time' }); + expect(utils.isTimeView(component)).toBeTruthy(); + }); + + it('className -> type string', () => { + const component = utils.createDatetimeShallow({ className: 'custom-class' }); + expect(component.find('.custom-class').length).toEqual(1); + }); + + it('className -> type string array', () => { + const component = utils.createDatetimeShallow({ className: ['custom-class1', 'custom-class2'] }); + expect(component.find('.custom-class1').length).toEqual(1); + expect(component.find('.custom-class2').length).toEqual(1); + }); + + it('inputProps', () => { + const component = utils.createDatetime({ + inputProps: { className: 'custom-class', type: 'email', placeholder: 'custom-placeholder' } + }); + expect(component.find('input.custom-class').length).toEqual(1); + expect(component.find('input').getDOMNode().type).toEqual('email'); + expect(component.find('input').getDOMNode().placeholder).toEqual('custom-placeholder'); + }); + + it('renderInput', () => { + const renderInput = (props, openCalendar) => { + return ( +
+ + +
+ ); + }; + const component = utils.createDatetime({ renderInput }); + + expect(component.find('button.custom-open').length).toEqual(1); + expect(utils.isOpen(component)).toBeFalsy(); + utils.clickOnElement(component.find('button.custom-open')); + expect(utils.isOpen(component)).toBeTruthy(); + }); + + it('renderDay', () => { + let props = {}, + currentDate = '', + selectedDate = ''; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + renderDayFn = (fnProps, current, selected) => { + props = fnProps; + currentDate = current; + selectedDate = selected; + + return custom-content; + }; + + const component = utils.createDatetime({ value: mDate, renderDay: renderDayFn }); + + // Last day should be 6th of february + expect(currentDate.day()).toEqual(6); + expect(currentDate.month()).toEqual(1); + + // The date must be the same + expect(selectedDate.isSame(mDate)).toEqual(true); + + // There should be a onClick function in the props + expect(typeof props.onClick).toEqual('function'); + + // The cell text should match + expect(component.find('.rdtDay').at(0).text()).toEqual('custom-content'); + }); + + it('renderMonth', () => { + let props = {}, + month = '', + year = '', + selectedDate = ''; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + renderMonthFn = (fnProps, fnMonth, fnYear, selected) => { + props = fnProps; + month = fnMonth; + year = fnYear; + selectedDate = selected; + + return custom-content; + }; + + const component = utils.createDatetime({ value: mDate, initialViewMode: 'months', renderMonth: renderMonthFn }); + + expect(month).toEqual(11); + expect(year).toEqual(2000); + + // The date must be the same + expect(selectedDate.isSame(mDate)).toEqual(true); + + // There should be a onClick function in the props + expect(typeof props.onClick).toEqual('function'); + + // The cell text should match + expect(component.find('.rdtMonth').at(0).text()).toEqual('custom-content'); + }); + + it('renderYear', () => { + let props = {}, + year = '', + selectedDate = ''; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + renderYearFn = (fnProps, fnYear, selected) => { + props = fnProps; + year = fnYear; + selectedDate = selected; + + return custom-content; + }; + + const component = utils.createDatetime({ value: mDate, initialViewMode: 'years', renderYear: renderYearFn }); + + expect(year).toEqual(2010); + + // The date must be the same + expect(selectedDate.isSame(mDate)).toEqual(true); + + // There should be a onClick function in the props + expect(typeof props.onClick).toEqual('function'); + + // The cell text should match + expect(component.find('.rdtYear').at(0).text()).toEqual('custom-content'); + }); + + it('renderView', () => { + let renderView = ( viewType, renderDefault ) => { + return ( +
+ { viewType } + { renderDefault() } +
+ ); + }; + + let component = utils.createDatetime({ + renderView, initialViewMode: 'years', input: false + }); + + expect( component.find('.viewType').text() ).toEqual('years'); + expect( component.find('.rdtYear').length ).not.toBe(0); + }); + + it('closeOnTab=true', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ value: date }); + + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + component.find('.form-control').simulate('keyDown', { key: 'Tab', keyCode: 9, which: 9 }); + expect(utils.isOpen(component)).toBeFalsy(); + }); + + it('closeOnTab=false', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ value: date, closeOnTab: false }); + + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + component.find('.form-control').simulate('keyDown', { key: 'Tab', keyCode: 9, which: 9 }); + expect(utils.isOpen(component)).toBeTruthy(); + }); + + it('closeOnClickOutside=true', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ value: date, closeOnClickOutside: false }); + + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + document.dispatchEvent(new Event('mousedown')); + component.update(); + expect(utils.isOpen(component)).toBeTruthy(); + }); + + it('closeOnClickOutside=false', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ value: date, closeOnClickOutside: true }); + + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + document.dispatchEvent(new Event('mousedown')); + component.update(); + expect(utils.isOpen(component)).toBeFalsy(); + }); + + it('open by click', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2); + const component = utils.createDatetime({ value: date, closeOnClickOutside: true }); + + utils.openDatepicker(component); + expect( component.instance().state.open ).toBeTruthy(); + component.instance().setState({open: false}); + expect( component.instance().state.open ).toBeFalsy(); + utils.openDatepickerByClick(component); + expect( component.instance().state.open ).toBeTruthy(); + }); + + it('increase time', () => { + let i = 0; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ timeFormat: 'HH:mm:ss:SSS', initialViewMode: 'time', + initialValue: date, onChange: (selected) => { + // TODO: Trigger onChange when increasing time + i++; + if (i > 2) { + expect(true).toEqual(false); // Proof that this is not called + expect(selected.hour()).toEqual(3); + expect(selected.minute()).toEqual(3); + expect(selected.second()).toEqual(3); + done(); + } + }}); + + // Check hour + expect(utils.getHours(component)).toEqual('2'); + utils.increaseHour(component); + expect(utils.getHours(component)).toEqual('3'); + + // Check minute + expect(utils.getMinutes(component)).toEqual('02'); + utils.increaseMinute(component); + expect(utils.getMinutes(component)).toEqual('03'); + + // Check second + expect(utils.getSeconds(component)).toEqual('02'); + utils.increaseSecond(component); + expect(utils.getSeconds(component)).toEqual('03'); + }); + + it('decrease time', () => { + let i = 0; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ timeFormat: 'HH:mm:ss:SSS', initialViewMode: 'time', + initialValue: date, onChange: (selected) => { + // TODO: Trigger onChange when increasing time + i++; + if (i > 2) { + expect(true).toEqual(false); // Proof that this is not called + expect(selected.hour()).toEqual(1); + expect(selected.minute()).toEqual(1); + expect(selected.second()).toEqual(1); + done(); + } + }}); + + // Check hour + expect(utils.getHours(component)).toEqual('2'); + utils.decreaseHour(component); + expect(utils.getHours(component)).toEqual('1'); + + // Check minute + expect(utils.getMinutes(component)).toEqual('02'); + utils.decreaseMinute(component); + expect(utils.getMinutes(component)).toEqual('01'); + + // Check second + expect(utils.getSeconds(component)).toEqual('02'); + utils.decreaseSecond(component); + expect(utils.getSeconds(component)).toEqual('01'); + }); + + it('long increase time', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ timeFormat: 'HH:mm:ss:SSS', initialViewMode: 'time', initialValue: date }); + + utils.increaseHour(component); + setTimeout(() => { + expect(utils.getHours(component)).not.toEqual('2'); + expect(utils.getHours(component)).not.toEqual('3'); + done(); + }, 920); + }); + + it('long decrease time', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ timeFormat: 'HH:mm:ss:SSS', initialViewMode: 'time', initialValue: date }); + + utils.decreaseHour(component); + setTimeout(() => { + expect(utils.getHours(component)).not.toEqual('1'); + expect(utils.getHours(component)).not.toEqual('0'); + done(); + }, 920); + }); + + it('timeConstraints -> increase time', () => { + let i = 0; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ timeFormat: 'HH:mm:ss:SSS', initialViewMode: 'time', + initialValue: date, timeConstraints: { hours: { max: 6, step: 8 }, minutes: { step: 15 }}, + onChange: (selected) => { + // TODO + i++; + if (i > 2) { + expect(selected.minute()).toEqual(17); + expect(selected.second()).toEqual(3); + done(); + } + } + }); + + utils.increaseHour(component); + expect(utils.getHours(component)).toEqual('3'); + + utils.increaseMinute(component); + expect(utils.getMinutes(component)).toEqual('17'); + + utils.increaseSecond(component); + expect(utils.getSeconds(component)).toEqual('03'); + }); + + it('timeConstraints -> decrease time', () => { + let i = 0; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ timeFormat: 'HH:mm:ss:SSS', initialViewMode: 'time', + initialValue: date, timeConstraints: { minutes: { step: 15 }}, onChange: (selected) => { + // TODO + i++; + if (i > 2) { + expect(selected.minute()).toEqual(17); + expect(selected.second()).toEqual(3); + done(); + } + } + }); + + utils.decreaseMinute(component); + expect(utils.getMinutes(component)).toEqual('47'); + }); + + it('strictParsing=true', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + invalidStrDate = strDate + 'x', + component = utils.createDatetime({ initialValue: '', strictParsing: true, + onChange: updated => { + expect(updated).toBe( invalidStrDate ); + done(); + } + }) + ; + + component.find('.form-control').simulate('change', { target: { value: invalidStrDate }}); + }); + + it('strictParsing=false', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + invalidStrDate = strDate + 'x', + component = utils.createDatetime({ initialValue: '', strictParsing: false, + onChange: (updated) => { + expect(mDate.format('L LT')).toEqual(updated.format('L LT')); + done(); + }}); + + component.find('.form-control').simulate('change', { target: { value: invalidStrDate }}); + }); + + it('isValidDate -> disable months', () => { + const dateBefore = new Date().getFullYear() + '-06-01', + component = utils.createDatetime({ initialViewMode: 'months', isValidDate: (current) => + current.isBefore(moment(dateBefore, 'YYYY-MM-DD')) + }); + + expect(utils.getNthMonth(component, 0).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthMonth(component, 4).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthMonth(component, 5).hasClass('rdtDisabled')).toEqual(true); + expect(utils.getNthMonth(component, 11).hasClass('rdtDisabled')).toEqual(true); + }); + + it('isValidDate -> disable years', () => { + const component = utils.createDatetime({ + initialViewMode: 'years', + value: moment('2025-01-01', 'YYYY-MM-DD'), + isValidDate: current => current.isBefore(moment('2026-01-01', 'YYYY-MM-DD')) + }); + + expect(utils.getNthYear(component, 0).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthYear(component, 6).hasClass('rdtDisabled')).toEqual(false); + expect(utils.getNthYear(component, 7).hasClass('rdtDisabled')).toEqual(true); + }); + + it('locale', () => { + const component = utils.createDatetime({ locale: 'nl' }), + expectedWeekDays = ['ma', 'di', 'wo', 'do', 'vr', 'za', 'zo'], + actualWeekDays = component.find('.rdtDays .dow').map((element) => + element.text().toLowerCase() + ); + + expect(actualWeekDays).toEqual(expectedWeekDays); + }); + + it('locale with initialViewMode=months', () => { + const component = utils.createDatetime({ locale: 'nl', initialViewMode: 'months' }), + expectedMonths = ['Mrt', 'Mei'], + actualMonths = [utils.getNthMonth(component, 2).text(), utils.getNthMonth(component, 4).text()]; + + expect(actualMonths).toEqual(expectedMonths); + }); + + it('closeOnSelect=false', (done) => { + const component = utils.createDatetime({ closeOnSelect: false }); + + // A unknown race condition is causing this test to fail without this time out, + // and when the test fails it says: + // 'Timeout - Async callback was not invoked within timeout' + // Ideally it would say something else but at least we know the tests are passing now + setTimeout(() => { + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + utils.clickNthDay(component, 2); + expect(utils.isOpen(component)).toBeTruthy(); + done(); + }, 0); + }); + + it('closeOnSelect=true', (done) => { + const component = utils.createDatetime({ closeOnSelect: true }); + + // A unknown race condition is causing this test to fail without this time out, + // and when the test fails it says: + // 'Timeout - Async callback was not invoked within timeout' + // Ideally it would say something else but at least we know the tests are passing now + setTimeout(() => { + expect(utils.isOpen(component)).toBeFalsy(); + utils.openDatepicker(component); + expect(utils.isOpen(component)).toBeTruthy(); + utils.clickNthDay(component, 2); + expect(utils.isOpen(component)).toBeFalsy(); + done(); + }, 0); + }); + + describe('initialValue of type', () => { + it('date', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + strDate = momentDate.format('L') + ' ' + momentDate.format('LT'), + component = utils.createDatetime({ initialValue: date }); + expect(utils.getInputValue(component)).toEqual(strDate); + }); + + it('moment', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + strDate = momentDate.format('L') + ' ' + momentDate.format('LT'), + component = utils.createDatetime({ initialValue: momentDate }); + expect(utils.getInputValue(component)).toEqual(strDate); + }); + + it('string', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + strDate = momentDate.format('L') + ' ' + momentDate.format('LT'), + component = utils.createDatetime({ initialValue: strDate }); + expect(utils.getInputValue(component)).toEqual(strDate); + }); + }); + + describe('timeFormat with', () => { + it('milliseconds', () => { + const component = utils.createDatetime({ initialViewMode: 'time', timeFormat: 'HH:mm:ss:SSS' }); + expect(component.find('.rdtCounter').length).toEqual(4); + // TODO: Test that you can input a value in milli seconds input + }); + + it('seconds', () => { + const component = utils.createDatetime({ initialViewMode: 'time', timeFormat: 'HH:mm:ss' }); + expect(component.find('.rdtCounter').length).toEqual(3); + }); + + it('minutes', () => { + const component = utils.createDatetime({ initialViewMode: 'time', timeFormat: 'HH:mm' }); + expect(component.find('.rdtCounter').length).toEqual(2); + }); + + it('hours', () => { + const component = utils.createDatetime({ initialViewMode: 'time', timeFormat: 'HH' }); + expect(component.find('.rdtCounter').length).toEqual(1); + }); + }); + + describe('being updated and should trigger update', () => { + it('dateFormat -> value should change format', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ + dateFormat: 'YYYY-MM-DD', timeFormat: false, initialValue: date + }); + + const valueBefore = utils.getInputValue(component); + // A unknown race condition is causing this test to fail without this time out, + // and when the test fails it says: + // 'Timeout - Async callback was not invoked within timeout' + // Ideally it would say something else but at least we know the tests are passing now + setTimeout(() => { + component.setProps({ dateFormat: 'DD.MM.YYYY' }); + const valueAfter = utils.getInputValue(component); + + expect(valueBefore).not.toEqual(valueAfter); + done(); + }, 0); + }); + + it('UTC -> value should change format (true->false)', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + component = utils.createDatetime({ value: momentDate, utc: true }); + + const valueBefore = utils.getInputValue(component); + component.setProps({ utc: false }, () => { + const valueAfter = utils.getInputValue(component); + + expect(valueBefore).not.toEqual(valueAfter); + }); + }); + + it('UTC -> value should change format (false->true)', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + component = utils.createDatetime({ value: momentDate, utc: false }); + + const valueBefore = utils.getInputValue(component); + component.setProps({ utc: true }, () => { + const valueAfter = utils.getInputValue(component); + + expect(valueBefore).not.toEqual(valueAfter); + }); + }); + + it('displayTimeZone -> value should change format (undefined->America/New_York)', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + component = utils.createDatetime({ value: momentDate }), + displayTimeZone = (moment.tz.guess() === 'America/New_York' ? 'America/Los_Angeles' : 'America/New_York'); + + const valueBefore = utils.getInputValue(component); + component.setProps({ displayTimeZone: displayTimeZone }, () => { + const valueAfter = utils.getInputValue(component); + + expect(valueBefore).not.toEqual(valueAfter); + }); + }); + + it('displayTimeZone -> value should change format (America/New_York->undefined)', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + displayTimeZone = (moment.tz.guess() === 'America/New_York' ? 'America/Los_Angeles' : 'America/New_York'), + component = utils.createDatetime({ value: momentDate, displayTimeZone: displayTimeZone }); + + const valueBefore = utils.getInputValue(component); + component.setProps({ displayTimeZone: undefined }, () => { + const valueAfter = utils.getInputValue(component); + + expect(valueBefore).not.toEqual(valueAfter); + }); + }); + + it('locale -> picker should change language (initialViewMode=days)', () => { + const component = utils.createDatetime({ initialViewMode: 'days', locale: 'en' }); + const weekdaysBefore = component.find('.rdtDays .dow').map( element => + element.text() + ); + + component.setProps({ locale: 'nl' }); + + // I don't know why the component doesn't get updated automatically in this case + // In the next test case it's working ok without using update() + component.update(); + + const weekdaysAfter = component.find('.rdtDays .dow').map((element) => + element.text() + ); + + expect(weekdaysBefore).not.toEqual(weekdaysAfter); + }); + + it('locale -> picker should change language (initialViewMode=months)', () => { + const component = utils.createDatetime({ initialViewMode: 'months', locale: 'nl' }), + monthsBefore = [utils.getNthMonth(component, 2).text(), utils.getNthMonth(component, 4).text()]; + + component.setProps({ locale: 'sv' }); + const monthsAfter = [utils.getNthMonth(component, 2).text(), utils.getNthMonth(component, 4).text()]; + + expect(monthsBefore).not.toEqual(monthsAfter); + }); + }); + }); + + describe('event listeners', () => { + describe('onClose', () => { + it('when selecting a date', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + onCloseFn = jest.fn(), + component = utils.createDatetime({ value: date, onClose: onCloseFn, closeOnSelect: true }); + + utils.openDatepicker(component); + // Close component by selecting a date + utils.clickNthDay(component, 2); + expect(onCloseFn).toHaveBeenCalledTimes(1); + }); + + it('when selecting date (value=null and closeOnSelect=true)', () => { + const onCloseFn = jest.fn(), + component = utils.createDatetime({ value: null, onClose: onCloseFn, closeOnSelect: true }); + + utils.openDatepicker(component); + // Close component by selecting a date + utils.clickNthDay(component, 2); + expect(onCloseFn).toHaveBeenCalledTimes(1); + }); + + it('when selecting date (value=null and closeOnSelect=false)', () => { + const onCloseFn = jest.fn(), + component = utils.createDatetime({ value: null, onClose: onCloseFn, closeOnSelect: false }); + + utils.openDatepicker(component); + // Close component by selecting a date + utils.clickNthDay(component, 2); + expect(onCloseFn).not.toHaveBeenCalled(); + }); + }); + + it('onOpen when opening datepicker', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + onOpenFn = jest.fn(), + component = utils.createDatetime({ value: date, onOpen: onOpenFn }); + + utils.openDatepicker(component); + expect(onOpenFn).toHaveBeenCalledTimes(1); + }); + + describe('onNavigate', () => { + it('when switch from days to time view mode', () => { + const component = utils.createDatetime({ onNavigate: (initialViewMode) => { + expect(initialViewMode).toEqual('time'); + }}); + expect(utils.isDayView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtTimeToggle')); + expect(utils.isTimeView(component)).toBeTruthy(); + }); + + it('when switch from time to days view mode', () => { + const component = utils.createDatetime({ initialViewMode: 'time', onNavigate: (initialViewMode) => { + expect(initialViewMode).toEqual('days'); + }}); + expect(utils.isTimeView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isDayView(component)).toBeTruthy(); + }); + + it('when switch from days to months view mode', () => { + const component = utils.createDatetime({ onNavigate: (initialViewMode) => { + expect(initialViewMode).toEqual('months'); + }}); + expect(utils.isDayView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isMonthView(component)).toBeTruthy(); + }); + + it('when switch from months to years view mode', () => { + const component = utils.createDatetime({ initialViewMode: 'months', onNavigate: (initialViewMode) => { + expect(initialViewMode).toEqual('years'); + }}); + expect(utils.isMonthView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isYearView(component)).toBeTruthy(); + }); + + it('only when switch from years to months view mode', () => { + const component = utils.createDatetime({ initialViewMode: 'years', onNavigate: (initialViewMode) => { + expect(initialViewMode).toEqual('months'); + }}); + expect(utils.isYearView(component)).toBeTruthy(); + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isYearView(component)).toBeTruthy(); + utils.clickNthYear(component, 2); + expect(utils.isMonthView(component)).toBeTruthy(); + }); + + it('when switch from months to days view mode', () => { + const component = utils.createDatetime({ initialViewMode: 'months', onNavigate: (initialViewMode) => { + expect(initialViewMode).toEqual('days'); + }}); + expect(utils.isMonthView(component)).toBeTruthy(); + utils.clickNthMonth(component, 2); + expect(utils.isDayView(component)).toBeTruthy(); + }); + + it('when onBeforeNavigate is defined', done => { + const date = moment( new Date(2000, 0, 15, 2, 2, 2, 2) ); + let on = viewMode => { + expect( viewMode ).toEqual('days'); + done(); + }; + let obn = (next, current, viewDate) => { + expect( next ).toEqual('days'); + expect( current ).toEqual('months'); + expect( viewDate.month() ).toEqual( 2 ); + expect( viewDate.year() ).toEqual( date.year() ); + return next; + }; + const component = utils.createDatetime( + { value: date, initialViewMode: 'months', onNavigate: on, onBeforeNavigate: obn } + ); + + expect(utils.isMonthView(component)).toBeTruthy(); + utils.clickNthMonth(component, 2); + expect(utils.isDayView(component)).toBeTruthy(); + }); + + it('prevent navigation using onBeforeNavigate', () => { + const date = moment( new Date(2000, 0, 15, 2, 2, 2, 2) ); + let on = jest.fn(); + let obn = (next, current, viewDate) => { + expect( next ).toEqual('years'); + expect( current ).toEqual('months'); + expect( viewDate.month() ).toEqual( date.month() ); + expect( viewDate.year() ).toEqual( date.year() ); + return false; + }; + + const component = utils.createDatetime( + { value: date, initialViewMode: 'months', onNavigate: on, onBeforeNavigate: obn } + ); + + expect(utils.isMonthView(component)).toBeTruthy(); + // Go to year view + utils.clickOnElement(component.find('.rdtSwitch')); + expect(utils.isMonthView(component)).toBeTruthy(); + expect(utils.isYearView(component)).toBeFalsy(); + expect(on).not.toHaveBeenCalled(); + }); + + it('go to a different screen when navigating using onBeforeNavigate', done => { + // race condition fix + setTimeout( () => { + let on = viewMode => { + expect( viewMode ).toEqual('years'); + }; + let obn = (next, current) => { + expect( next ).toEqual('days'); + expect( current ).toEqual('months'); + return 'years'; + }; + const component = utils.createDatetime( + { initialViewMode: 'months', onNavigate: on, onBeforeNavigate: obn } + ); + + expect(utils.isMonthView(component)).toBeTruthy(); + utils.clickNthMonth(component, 2); + expect(utils.isYearView(component)).toBeTruthy(); + done(); + }); + }); + }); + + describe('onChange', () => { + it('trigger only when last selection type is selected', done => { + // race condition fix + setTimeout( () => { + // By selection type I mean if you CAN select day, then selecting a month + // should not trigger onChange + const onChangeFn = jest.fn(), + component = utils.createDatetime({ initialViewMode: 'years', onChange: onChangeFn }); + + utils.openDatepicker(component); + + utils.clickNthYear(component, 2); + expect(onChangeFn).not.toHaveBeenCalled(); + + utils.clickNthMonth(component, 2); + expect(onChangeFn).not.toHaveBeenCalled(); + + utils.clickNthDay(component, 2); + expect(onChangeFn).toHaveBeenCalled(); + done(); + }); + }); + + it('when selecting date', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + component = utils.createDatetime({ initialValue: date, onChange: (selected) => { + expect(selected.date()).toEqual(2); + expect(selected.month()).toEqual(mDate.month()); + expect(selected.year()).toEqual(mDate.year()); + done(); + }}); + + utils.clickNthDay(component, 7); + }); + + it('when selecting multiple date in a row', (done) => { + let i = 0; + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + component = utils.createDatetime({ initialValue: date, onChange: (selected) => { + i++; + if (i > 2) { + expect(selected.date()).toEqual(4); + expect(selected.month()).toEqual(mDate.month()); + expect(selected.year()).toEqual(mDate.year()); + done(); + } + }}); + + utils.clickNthDay(component, 7); + utils.clickNthDay(component, 8); + utils.clickNthDay(component, 9); + }); + + it('when selecting month', () => { + const date = _momentTimezone.tz('2000-03-15T02:02:02.002Z', 'UTC'), + onChangeFn = jest.fn(), + component = utils.createDatetime({ initialValue: date, dateFormat: 'YYYY-MM', onChange: onChangeFn }); + + utils.clickNthMonth(component, 2); + expect(onChangeFn).toHaveBeenCalledTimes(1); + expect(onChangeFn.mock.calls[0][0].toJSON()).toEqual('2000-03-15T02:02:02.002Z'); + }); + + // Passes locally but not on Travis + xit('when selecting year', () => { + const date = Date.UTC(2000, 0, 15, 2, 2, 2, 2), + onChangeFn = jest.fn(), + component = utils.createDatetime({ initialValue: date, dateFormat: 'YYYY', onChange: onChangeFn }); + + utils.clickNthYear(component, 2); + expect(onChangeFn).toHaveBeenCalledTimes(1); + expect(onChangeFn.mock.calls[0][0].toJSON()).toEqual('2001-01-15T02:02:02.002Z'); + }); + + it('when selecting time', () => { + // Did not manage to be able to get onChange to trigger, even though I know it does. + // The listener for the time buttons are set up differently because of having to handle both + // onMouseDown and onMouseUp. Not sure how to test it. + expect(true).toEqual(true); + }); + + }); + + }); + + describe('onNavigateForward', () => { + it('when moving to next month', () => { + const component = utils.createDatetime({ onNavigateForward: (amount, type) => { + expect(amount).toEqual(1); + expect(type).toEqual('months'); + }}); + + utils.clickOnElement(component.find('.rdtNext')); + }); + + it('when moving to next year', () => { + const component = utils.createDatetime({ initialViewMode: 'months', onNavigateForward: (amount, type) => { + expect(amount).toEqual(1); + expect(type).toEqual('years'); + }}); + + utils.clickOnElement(component.find('.rdtNext')); + }); + + it('when moving decade forward', () => { + const component = utils.createDatetime({ initialViewMode: 'years', onNavigateForward: (amount, type) => { + expect(amount).toEqual(10); + expect(type).toEqual('years'); + }}); + + utils.clickOnElement(component.find('.rdtNext')); + }); + }); + + describe('onNavigateBack', () => { + it('when moving to previous month', () => { + const component = utils.createDatetime({ onNavigateBack: (amount, type) => { + expect(amount).toEqual(1); + expect(type).toEqual('months'); + }}); + + utils.clickOnElement(component.find('.rdtPrev')); + }); + + it('when moving to previous year', () => { + const component = utils.createDatetime({ initialViewMode: 'months', onNavigateBack: (amount, type) => { + expect(amount).toEqual(1); + expect(type).toEqual('years'); + }}); + + utils.clickOnElement(component.find('.rdtPrev')); + }); + + it('when moving decade back', () => { + const component = utils.createDatetime({ initialViewMode: 'years', onNavigateBack: (amount, type) => { + expect(amount).toEqual(10); + expect(type).toEqual('years'); + }}); + + utils.clickOnElement(component.find('.rdtPrev')); + }); + }); + + describe('with set value', () => { + it('date value', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + component = utils.createDatetime({ value: date }); + expect(utils.getInputValue(component)).toEqual(strDate); + }); + + it('moment value', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + component = utils.createDatetime({ value: mDate }); + expect(utils.getInputValue(component)).toEqual(strDate); + }); + + it('string value', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + component = utils.createDatetime({ value: strDate }); + expect(utils.getInputValue(component)).toEqual(strDate); + }); + + it('UTC value from local moment', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDate = moment(date), + momentDateUTC = moment.utc(date), + strDateUTC = momentDateUTC.format('L') + ' ' + momentDateUTC.format('LT'), + component = utils.createDatetime({ value: momentDate, utc: true }); + expect(utils.getInputValue(component)).toEqual(strDateUTC); + }); + + it('UTC value from UTC moment', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDateUTC = moment.utc(date), + strDateUTC = momentDateUTC.format('L') + ' ' + momentDateUTC.format('LT'), + component = utils.createDatetime({ value: momentDateUTC, utc: true }); + expect(utils.getInputValue(component)).toEqual(strDateUTC); + }); + + it('UTC value from UTC string', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDateUTC = moment.utc(date), + strDateUTC = momentDateUTC.format('L') + ' ' + momentDateUTC.format('LT'), + component = utils.createDatetime({ value: strDateUTC, utc: true }); + expect(utils.getInputValue(component)).toEqual(strDateUTC); + }); + + it('TZ value from local moment', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + displayTimeZone = 'America/New_York', + momentDate = moment(date), + momentDateTZ = moment.tz(date, displayTimeZone), + strDateTZ = momentDateTZ.format('L') + ' ' + momentDateTZ.format('LT'), + component = utils.createDatetime({ value: momentDate, displayTimeZone: displayTimeZone }); + expect(utils.getInputValue(component)).toEqual(strDateTZ); + }); + + it('TZ value from UTC moment', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + displayTimeZone = 'America/New_York', + momentDateUTC = moment.utc(date), + momentDateTZ = moment.tz(date, displayTimeZone), + strDateTZ = momentDateTZ.format('L') + ' ' + momentDateTZ.format('LT'), + component = utils.createDatetime({ value: momentDateUTC, displayTimeZone: displayTimeZone }); + expect(utils.getInputValue(component)).toEqual(strDateTZ); + }); + + it('invalid string value', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + component = utils.createDatetime({ initialValue: 'invalid-value', onChange: (updated) => { + expect(mDate.format('L LT')).toEqual(updated.format('L LT')); + done(); + }}); + + expect(component.find('.form-control').getDOMNode().value).toEqual('invalid-value'); + component.find('.form-control').simulate('change', { target: { value: strDate }}); + }); + + it('delete invalid string value', (done) => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + component = utils.createDatetime({ initialValue: date, onChange: (date) => { + expect(date).toEqual(''); + done(); + }}); + + component.find('.form-control').simulate('change', { target: { value: '' }}); + }); + + it('invalid moment object', (done) => { + const invalidValue = moment(null), + date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + component = utils.createDatetime({ value: invalidValue, onChange: (updated) => { + expect(mDate.format('L LT')).toEqual(updated.format('L LT')); + done(); + }}); + + expect(component.find('.form-control').getDOMNode().value).toEqual(''); + component.find('.form-control').simulate('change', { target: { value: strDate }}); + }); + + it('should update the view date when updating the value prop', done => { + const value1 = moment('2020-03-04T13:00:10.121Z'); + const value2 = moment('2021-06-04T13:00:10.121Z'); + + let component = utils.createDatetime({ value: value1 }); + expect( component.instance().state.viewDate.toISOString() ).toBe(value1.toISOString()); + + component.setProps({ value: value2 }); + setTimeout( () => { + expect( component.instance().state.viewDate.toISOString() ).toBe(value2.toISOString()); + done(); + }); + }); + }); + + describe('View navigation', () => { + it('The calendar must be open in the updateOnView when not initialViewModel is defined', () => { + const component = utils.createDatetime({ updateOnView: 'months' }); + + expect( component.find('.rdtMonth').length ).not.toBe(0); + expect( component.find('.rdtDay').length ).toBe(0); + }); + + it('The calendar must be open in the initialViewModel if it is defined', () => { + const component = utils.createDatetime({ updateOnView: 'months', initialViewMode: 'days' }); + + expect( component.find('.rdtMonth').length ).toBe(0); + expect( component.find('.rdtDay').length ).not.toBe(0); + }); + + it('The calendar must be closed on select in the updateView, if closeOnSelect defined', done => { + + const component = utils.createDatetime( + { updateOnView: 'months', closeOnSelect: true, input: true } + ); + + // Race condition fix + setTimeout( () => { + utils.openDatepicker( component ); + expect( utils.isOpen(component) ).toBeTruthy(); + utils.clickNthMonth( component, 1 ); + expect( utils.isOpen(component) ).toBeFalsy(); + done(); + }); + }); + + it('The selected date must change when selecting in the updateView', done => { + const initialDate = new Date(2000, 6, 15, 2, 2, 2, 2); + const onChange = updated => { + expect( updated.month() ).toBe( 1 ); + expect( updated.year() ).toBe( 2000 ); + + // We shouldn't navigate when selecting in an updateView + expect( component.find('.rdtMonth').length ).not.toBe(0); + expect( component.find('.rdtDay').length ).toBe(0); + + done(); + }; + + const component = utils.createDatetime({ + updateOnView: 'months', input: false, initialValue: initialDate, onChange + }); + + utils.clickNthMonth( component, 1 ); + }); + + it('If the updateView is "time" clicking on a day shouldn`t update the selected date and navigate to the time', done => { + const initialDate = new Date(2000, 6, 15, 2, 2, 2, 2); + const onChangeFn = jest.fn(); + const component = utils.createDatetime({ + updateOnView: 'time', initialViewMode: 'days', input: false, initialValue: initialDate, onChangeFn + }); + + // Race condition fix + setTimeout( () => { + + utils.clickNthDay( component, 1 ); + + expect( component.find('.rdtDay').length ).toBe(0); + expect( component.find('.rdtTime').length ).not.toBe(0); + + setTimeout(() => { + expect(onChangeFn).toHaveBeenCalledTimes(0); + done(); + }, 10 ); + }); + }); + }); + +}); + +describe('Imperative methods', function() { + it('Calling setViewDate should navigate to the given date', function() { + const initialDate = new Date(2000, 6, 15, 2, 2, 2, 2); + const component = utils.createDatetime({ initialViewMode: 'months', initialViewDate: initialDate } ); + + expect( utils.isMonthView( component ) ).toBeTruthy(); + expect( component.find('.rdtSwitch').text() ).toBe('2000'); + + const nextDate = new Date( 2012, 10, 10 ); + component.instance().setViewDate( nextDate ); + + expect( utils.isMonthView( component ) ).toBeTruthy(); + expect( component.find('.rdtSwitch').text() ).toBe('2012'); + }); + + // This test is just not working, but it's using the setView method internally, + // That is well tested by other specs in this file + xit('Calling navigate should update to the given view', function( done ) { + const initialDate = new Date(2000, 6, 15, 2, 2, 2, 2); + const component = utils.createDatetime( + { initialViewMode: 'months', initialViewDate: initialDate } + ); + + expect( utils.isMonthView( component ) ).toBeTruthy(); + + component.instance().navigate( 'days' ); + + // Sync fix + setTimeout( () => { + expect( utils.isDayView( component ) ).toBeTruthy(); + component.instance().navigate( 'time' ); + expect( utils.isTimeView( component ) ).toBeTruthy(); + + component.instance().navigate( 'years' ); + expect( utils.isYearView( component ) ).toBeTruthy(); + + component.instance().navigate( 'months' ); + expect( utils.isMonthView( component ) ).toBeTruthy(); + + // The date should stay unmodified + expect( component.find('.rdtSwitch').text() ).toBe('2000'); + done(); + }, 100); + + }); +}); diff --git a/test/viewDate.spec.js b/test/viewDate.spec.js new file mode 100644 index 000000000..ade27150a --- /dev/null +++ b/test/viewDate.spec.js @@ -0,0 +1,58 @@ +/* global it, describe, expect */ + +import React from 'react'; // eslint-disable-line no-unused-vars +import moment from 'moment'; +import utils from './testUtils'; +import Enzyme from 'enzyme'; +import Adapter from 'enzyme-adapter-react-16'; + +Enzyme.configure({adapter: new Adapter()}); + +describe('with initialViewDate', () => { + it('date value', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + strDate = moment(date).format('MMMM YYYY'), + component = utils.createDatetime({initialViewDate: date}); + expect(utils.getViewDateValue(component)).toEqual(strDate); + }); + + it('moment value', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('MMMM YYYY'), + component = utils.createDatetime({initialViewDate: mDate}); + expect(utils.getViewDateValue(component)).toEqual(strDate); + }); + + it('string value', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + mDate = moment(date), + strDate = mDate.format('L') + ' ' + mDate.format('LT'), + expectedStrDate = mDate.format('MMMM YYYY'), + component = utils.createDatetime({initialViewDate: strDate}); + expect(utils.getViewDateValue(component)).toEqual(expectedStrDate); + }); + + it('UTC value from UTC string', () => { + const date = new Date(2000, 0, 15, 2, 2, 2, 2), + momentDateUTC = moment.utc(date), + strDateUTC = momentDateUTC.format('L') + ' ' + momentDateUTC.format('LT'), + expectedStrDate = momentDateUTC.format('MMMM YYYY'), + component = utils.createDatetime({initialViewDate: strDateUTC, utc: true}); + expect(utils.getViewDateValue(component)).toEqual(expectedStrDate); + }); + + it('invalid string value', () => { + const strDate = 'invalid string', + expectedStrDate = moment().format('MMMM YYYY'), + component = utils.createDatetime({initialViewDate: strDate}); + expect(utils.getViewDateValue(component)).toEqual(expectedStrDate); + }); + + it('invalid moment object', () => { + const mDate = moment(null), + expectedStrDate = moment().format('MMMM YYYY'), + component = utils.createDatetime({initialViewDate: mDate}); + expect(utils.getViewDateValue(component)).toEqual(expectedStrDate); + }); +}); diff --git a/tests/datetime-spec.js b/tests/datetime-spec.js deleted file mode 100644 index ac9a7ffa0..000000000 --- a/tests/datetime-spec.js +++ /dev/null @@ -1,654 +0,0 @@ -// Create the dom before requiring react -var DOM = require( './testdom'); -DOM(); - - -// Needs to be global to work in Travis CI -React = require('react'); -ReactDOM = require('react-dom'); - -var Datetime = require('../DateTime'), - assert = require('assert'), - moment = require('moment'), - TestUtils = require('react-addons-test-utils') -; - -var createDatetime = function( props ){ - document.body.innerHTML = '
'; - - ReactDOM.render( - React.createElement( Datetime, props ), - document.getElementById('root') - ); - - return document.getElementById('root').children[0]; -}; - -var trigger = function( name, element ){ - var ev = document.createEvent("MouseEvents"); - ev.initEvent(name, true, true); - element.dispatchEvent( ev ); -}; - -var ev = TestUtils.Simulate; -var dt = { - dt: function(){ - return document.getElementById('root').children[0]; - }, - view: function(){ - return this.dt().children[1].children[0]; - }, - input: function(){ - return this.dt().children[0]; - }, - switcher: function(){ - return document.querySelector('.rdtSwitch'); - }, - timeSwitcher: function(){ - return document.querySelector('.rdtTimeToggle'); - }, - year: function( n ){ - var years = document.querySelectorAll('.rdtYear'); - return years[ n || 0 ]; - }, - month: function( n ){ - var months = document.querySelectorAll('.rdtMonth'); - return months[ n || 0 ]; - }, - day: function( n ){ - return document.querySelector('.rdtDay[data-value="' + n + '"]'); - }, - next: function(){ - return document.querySelector('.rdtNext span'); - }, - prev: function(){ - return document.querySelector('.rdtPrev span'); - }, - timeUp: function( n ){ - return document.querySelectorAll('.rdtCounter')[ n ].children[0]; - }, - timeDown: function( n ){ - return document.querySelectorAll('.rdtCounter')[ n ].children[2]; - }, - hour: function(){ - return document.querySelectorAll('.rdtCount')[0]; - }, - minute: function(){ - return document.querySelectorAll('.rdtCount')[1]; - }, - second: function(){ - return document.querySelectorAll('.rdtCount')[2]; - }, - milli: function(){ - return document.querySelector('.rdtMilli input'); - } -}; - -var date = new Date( 2000, 0, 15, 2, 2, 2, 2 ), - mDate = moment( date ), - strDate = mDate.format('L') + ' ' + mDate.format('LT') -; - -describe( 'Datetime', function(){ - it( 'Create Datetime', function(){ - var component = createDatetime({}); - assert( component ); - assert.equal( component.children.length, 2 ); - assert.equal( component.children[0].tagName , 'INPUT' ); - assert.equal( component.children[1].tagName , 'DIV' ); - }); - - it( 'input=false', function(){ - var component = createDatetime({ input: false }); - assert( component ); - assert.equal( component.children.length, 1 ); - assert.equal( component.children[0].tagName , 'DIV' ); - }); - - - it( 'Date value', function(){ - var component = createDatetime({ value: date }), - input = component.children[0] - ; - assert.equal( input.value, strDate ); - }); - - it( 'Moment value', function(){ - var component = createDatetime({ value: mDate }), - input = component.children[0] - ; - assert.equal( input.value, strDate ); - }); - - it( 'String value', function(){ - var component = createDatetime({ value: strDate }), - input = component.children[0] - ; - assert.equal( input.value, strDate ); - }); - - it( 'Date defaultValue', function(){ - var component = createDatetime({ defaultValue: date }), - input = component.children[0] - ; - assert.equal( input.value, strDate ); - }); - - it( 'Moment defaultValue', function(){ - var component = createDatetime({ defaultValue: mDate }), - input = component.children[0] - ; - assert.equal( input.value, strDate ); - }); - - it( 'String defaultValue', function(){ - var component = createDatetime({ defaultValue: strDate }), - input = component.children[0] - ; - assert.equal( input.value, strDate ); - }); - - it( 'dateFormat', function(){ - var component = createDatetime({ value: date, dateFormat: 'M&D' }), - input = component.children[0] - ; - assert.equal( input.value, mDate.format('M&D LT') ); - }); - - it( 'dateFormat=false', function(){ - var component = createDatetime({ value: date, dateFormat: false }), - input = component.children[0], - view = dt.view() - ; - assert.equal( input.value, mDate.format('LT') ); - // The view must be the timepicker - assert.equal( view.className, 'rdtTime' ); - // There must not be a date toggle - assert.equal( view.querySelectorAll('thead').length, 0); - }); - it( 'timeFormat', function(){ - var format = 'HH:mm:ss:SSS', - component = createDatetime({ value: date, timeFormat: format }), - input = component.children[0] - ; - assert.equal( input.value, mDate.format('L ' + format) ); - }); - - it( 'timeFormat=false', function(){ - var component = createDatetime({ value: date, timeFormat: false }), - input = component.children[0], - view = dt.view() - ; - assert.equal( input.value, mDate.format('L') ); - // The view must be the daypicker - assert.equal( view.className, 'rdtDays' ); - // There must not be a time toggle - assert.equal( view.querySelectorAll('.timeToggle').length, 0); - }); - - it( 'viewMode=years', function(){ - var component = createDatetime({ viewMode: 'years' }), - view = dt.view() - ; - - assert.equal( view.className, 'rdtYears' ); - }); - - it( 'viewMode=months', function(){ - var component = createDatetime({ viewMode: 'months' }), - view = dt.view() - ; - - assert.equal( view.className, 'rdtMonths' ); - }); - - it( 'viewMode=time', function(){ - var component = createDatetime({ viewMode: 'time' }), - view = dt.view() - ; - - assert.equal( view.className, 'rdtTime' ); - }); - - it( 'className of type string', function(){ - var component = createDatetime({ className: 'custom' }); - assert.notEqual( component.className.indexOf('custom'), -1 ); - }); - - it( 'className of type string array', function(){ - var component = createDatetime({ className: ['custom1', 'custom2'] }); - assert.notEqual( component.className.indexOf('custom1'), -1 ); - assert.notEqual( component.className.indexOf('custom2'), -1 ); - }); - - it( 'inputProps', function(){ - var component = createDatetime({ inputProps: { className: 'myInput', type: 'email' } }), - input = component.children[0] - ; - - assert.equal( input.className, 'myInput' ); - assert.equal( input.type, 'email' ); - }); - - it( 'renderDay', function(){ - var props, currentDate, selectedDate, - component = createDatetime({ value: mDate, renderDay: function( p, current, selected ){ - props = p; - currentDate = current; - selectedDate = selected; - - return React.DOM.td( props, 'day' ); - }}), - view = dt.view() - ; - - // Last day should be 6th of february - assert.equal( currentDate.day(), 6 ); - assert.equal( currentDate.month(), 1 ); - - // The date must be the same - assert.equal( selectedDate.isSame( mDate ), true ); - - // There should be a onClick function in the props - assert.equal( typeof props.onClick, 'function' ); - - // The cell text should be 'day' - assert.equal( view.querySelector('.rdtDay').innerHTML, 'day' ); - }); - - - it( 'renderMonth', function(){ - var props, month, year, selectedDate, - component = createDatetime({ value: mDate, viewMode: 'months', renderMonth: function( p, m, y, selected ){ - props = p; - month = m; - year = y; - selectedDate = selected; - - return React.DOM.td( props, 'month' ); - }}), - view = dt.view() - ; - - // The date must be the same - assert.equal( selectedDate.isSame( mDate ), true ); - - assert.equal( month, 11 ); - assert.equal( year, 2000 ); - - // There should be a onClick function in the props - assert.equal( typeof props.onClick, 'function' ); - - // The cell text should be 'day' - assert.equal( view.querySelector('.rdtMonth').innerHTML, 'month' ); - }); - - it( 'renderYear', function(){ - var props, year, selectedDate, - component = createDatetime({ value: mDate, viewMode: 'years', renderYear: function( p, y, selected ){ - props = p; - year = y; - selectedDate = selected; - - return React.DOM.td( props, 'year' ); - }}), - view = dt.view() - ; - - // The date must be the same - assert.equal( selectedDate.isSame( mDate ), true ); - - assert.equal( year, 2010 ); - - // There should be a onClick function in the props - assert.equal( typeof props.onClick, 'function' ); - - // The cell text should be 'day' - assert.equal( view.querySelector('.rdtYear').innerHTML, 'year' ); - }); - - it( 'Time pickers depends on the time format', function() { - createDatetime({ viewMode: 'time', timeFormat: "HH:mm:ss:SSS"}); - assert.equal( document.querySelectorAll('.rdtCounter').length, 4 ); - - createDatetime({ viewMode: 'time', timeFormat: "HH:mm:ss"}); - assert.equal( document.querySelectorAll('.rdtCounter').length, 3 ); - - createDatetime({ viewMode: 'time', timeFormat: "HH:mm"}); - assert.equal( document.querySelectorAll('.rdtCounter').length, 2 ); - - createDatetime({ viewMode: 'time', timeFormat: "HH"}); - assert.equal( document.querySelectorAll('.rdtCounter').length, 1 ); - }); - - it( 'viewChange', function() { - createDatetime({viewMode: 'time' }); - - assert.equal( dt.view().className, 'rdtTime' ); - ev.click( dt.switcher() ); - assert.equal( dt.view().className, 'rdtDays' ); - ev.click( dt.switcher() ); - assert.equal( dt.view().className, 'rdtMonths' ); - ev.click( dt.switcher() ); - assert.equal( dt.view().className, 'rdtYears' ); - }); - - it( 'switch to time', function(){ - createDatetime({}); - assert.equal( dt.view().className, 'rdtDays' ); - ev.click( dt.timeSwitcher() ); - assert.equal( dt.view().className, 'rdtTime' ); - }) - - it( 'selectYear', function(){ - createDatetime({ viewMode: 'years', defaultValue: date }); - assert.equal( dt.view().className, 'rdtYears' ); - assert.equal( dt.switcher().innerHTML, '2000-2009' ); - - // First year is 1999 - ev.click( dt.year() ); - assert.equal( dt.view().className, 'rdtMonths' ); - assert.equal( dt.switcher().innerHTML, '1999' ); - }); - - it( 'increase decade', function(){ - createDatetime({ viewMode: 'years', defaultValue: date }); - - assert.equal( dt.switcher().innerHTML, '2000-2009' ); - ev.click( dt.next() ); - assert.equal( dt.switcher().innerHTML, '2010-2019' ); - ev.click( dt.next() ); - assert.equal( dt.switcher().innerHTML, '2020-2029' ); - }); - - - it( 'decrease decade', function(){ - createDatetime({ viewMode: 'years', defaultValue: date }); - - assert.equal( dt.switcher().innerHTML, '2000-2009' ); - ev.click( dt.prev() ); - assert.equal( dt.switcher().innerHTML, '1990-1999' ); - ev.click( dt.prev() ); - assert.equal( dt.switcher().innerHTML, '1980-1989' ); - }); - - it( 'selectMonth', function(){ - createDatetime({ viewMode: 'months', defaultValue: date }); - assert.equal( dt.view().className, 'rdtMonths' ); - assert.equal( dt.switcher().innerHTML, '2000' ); - - ev.click( dt.month(1) ); - assert.equal( dt.view().className, 'rdtDays' ); - assert.equal( dt.switcher().getAttribute('data-value'), "1" ); - }); - - it( 'increase year', function(){ - createDatetime({ viewMode: 'months', defaultValue: date }); - - assert.equal( dt.switcher().getAttribute('data-value'), '2000' ); - ev.click( dt.next() ); - assert.equal( dt.switcher().getAttribute('data-value'), '2001' ); - ev.click( dt.next() ); - assert.equal( dt.switcher().getAttribute('data-value'), '2002' ); - }); - - - it( 'decrease year', function(){ - createDatetime({ viewMode: 'months', defaultValue: date }); - - assert.equal( dt.switcher().getAttribute('data-value'), '2000' ); - ev.click( dt.prev() ); - assert.equal( dt.switcher().getAttribute('data-value'), '1999' ); - ev.click( dt.prev() ); - assert.equal( dt.switcher().getAttribute('data-value'), '1998' ); - }); - - it( 'increase month', function(){ - createDatetime({ defaultValue: date }); - - assert.equal( dt.switcher().getAttribute('data-value'), '0' ); - ev.click( dt.next() ); - assert.equal( dt.switcher().getAttribute('data-value'), '1' ); - ev.click( dt.next() ); - assert.equal( dt.switcher().getAttribute('data-value'), '2' ); - }); - - it( 'decrease month', function(){ - createDatetime({ defaultValue: date }); - - assert.equal( dt.switcher().getAttribute('data-value'), '0' ); - ev.click( dt.prev() ); - assert.equal( dt.switcher().getAttribute('data-value'), '11' ); - ev.click( dt.prev() ); - assert.equal( dt.switcher().getAttribute('data-value'), '10' ); - }); - - it( 'open picker', function(){ - createDatetime({}); - assert.equal(dt.dt().className.indexOf('rdtOpen'), -1); - ev.focus( dt.input() ); - assert.notEqual(dt.dt().className.indexOf('rdtOpen'), -1); - }); - - it( 'onSelect', function( done ){ - createDatetime({ defaultValue: date, onChange: function( selected ){ - assert.equal( selected.date(), 2 ); - assert.equal( selected.month(), mDate.month() ); - assert.equal( selected.year(), mDate.year() ); - done(); - }}); - - ev.click( dt.day( 2 ) ); - }); - - it( 'multiple onSelect', function( done ){ - var i = 0; - createDatetime({ defaultValue: date, onChange: function( selected ){ - i++; - if( i > 2 ){ - assert.equal( selected.date(), 4 ); - assert.equal( selected.month(), mDate.month() ); - assert.equal( selected.year(), mDate.year() ); - done(); - } - }}); - - ev.click( dt.day( 2 ) ); - ev.click( dt.day( 3 ) ); - ev.click( dt.day( 4 ) ); - }); - - it( 'onFocus', function(){ - var focus = false; - createDatetime({ value: date, onFocus: function( selected ){ - focus = true; - }}); - - ev.focus( dt.input() ); - assert.equal( focus, true ); - }); - - it( 'onBlur', function(){ - createDatetime({ value: date, onBlur: function( selected ){ - assert.equal( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - assert.equal( selected.date(), mDate.date() ); - assert.equal( selected.month(), mDate.month() ); - assert.equal( selected.year(), mDate.year() ); - done(); - }}); - - assert.equal( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - ev.focus( dt.input() ); - assert.notEqual( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - trigger( 'click', document.body ); - }); - - it( 'closeOnTab:true', function(){ - createDatetime({ value: date }); - - assert.equal( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - ev.focus( dt.input() ); - assert.notEqual( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - TestUtils.Simulate.keyDown(dt.input(), {key: "Tab", keyCode: 9, which: 9}); - assert.equal( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - trigger( 'click', document.body ); - }); - - it( 'closeOnTab:false', function(){ - createDatetime({ value: date, closeOnTab: false }); - - assert.equal( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - ev.focus( dt.input() ); - assert.notEqual( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - TestUtils.Simulate.keyDown(dt.input(), {key: "Tab", keyCode: 9, which: 9}); - assert.notEqual( dt.dt().className.indexOf( 'rdtOpen' ), -1 ); - trigger( 'click', document.body ); - }); - - it( 'increase time', function( done ){ - var i = 0; - createDatetime({ timeFormat: "HH:mm:ss:SSS", viewMode: 'time', defaultValue: date, onChange: function( selected ){ - i++; - if( i > 2 ){ - assert.equal( selected.hour(), 3 ); - assert.equal( selected.minute(), 3 ); - assert.equal( selected.second(), 3 ); - done(); - } - }}); - - trigger( 'mousedown', dt.timeUp( 0 ) ); - trigger('mouseup', document.body ); - assert.equal( dt.hour().innerHTML, 3 ); - trigger( 'mousedown', dt.timeUp( 1 ) ); - trigger( 'mouseup', dt.timeUp( 1 ) ); - assert.equal( dt.minute().innerHTML, 3 ); - trigger( 'mousedown', dt.timeUp( 2 ) ); - trigger( 'mouseup', dt.timeUp( 2 ) ); - assert.equal( dt.second().innerHTML, 3 ); - }); - - it( 'decrease time', function( done ){ - var i = 0; - createDatetime({ timeFormat: "HH:mm:ss:SSS", viewMode: 'time', defaultValue: date, onChange: function( selected ){ - i++; - if( i > 2 ){ - assert.equal( selected.hour(), 1 ); - assert.equal( selected.minute(), 1 ); - assert.equal( selected.second(), 1 ); - done(); - } - }}); - - trigger('mousedown', dt.timeDown( 0 ) ); - trigger('mouseup', dt.timeDown( 0 ) ); - assert.equal( dt.hour().innerHTML, 1 ); - trigger('mousedown', dt.timeDown( 1 ) ); - trigger('mouseup', dt.timeDown( 1 ) ); - assert.equal( dt.minute().innerHTML, 1 ); - trigger('mousedown', dt.timeDown( 2 ) ); - trigger('mouseup', dt.timeDown( 2 ) ); - assert.equal( dt.second().innerHTML, 1 ); - }); - - it( 'long increase time', function( done ){ - var i = 0; - createDatetime({ timeFormat: "HH:mm:ss:SSS", viewMode: 'time', defaultValue: date}); - - trigger( 'mousedown', dt.timeUp( 0 ) ); - setTimeout( function(){ - trigger('mouseup', document.body ); - assert.notEqual( dt.hour().innerHTML, 2 ); - assert.notEqual( dt.hour().innerHTML, 3 ); - done(); - }, 920 ); - }); - - it( 'long decrease time', function( done ){ - var i = 0; - createDatetime({ timeFormat: "HH:mm:ss:SSS", viewMode: 'time', defaultValue: date}); - - trigger( 'mousedown', dt.timeDown( 0 ) ); - setTimeout( function(){ - trigger('mouseup', document.body ); - assert.notEqual( dt.hour().innerHTML, 1 ); - assert.notEqual( dt.hour().innerHTML, 0 ); - done(); - }, 920 ); - }); - - it( 'increase time with timeConstraints', function( done ){ - var i = 0; - createDatetime({ timeFormat: "HH:mm:ss:SSS", viewMode: 'time', defaultValue: date, onChange: function( selected ){ - i++; - if( i > 2 ){ - assert.equal( selected.minute(), 17 ); - assert.equal( selected.second(), 3 ); - done(); - } - }, timeConstraints: { hours: { max: 6, step: 8 }, minutes: { step: 15 }}}); - - trigger( 'mousedown', dt.timeUp( 0 ) ); - trigger('mouseup', document.body ); - assert.equal( dt.hour().innerHTML, 3 ); - trigger( 'mousedown', dt.timeUp( 1 ) ); - trigger( 'mouseup', dt.timeUp( 1 ) ); - assert.equal( dt.minute().innerHTML, 17 ); - trigger( 'mousedown', dt.timeUp( 2 ) ); - trigger( 'mouseup', dt.timeUp( 2 ) ); - assert.equal( dt.second().innerHTML, 3 ); - }); - - it( 'decrease time with timeConstraints', function( done ){ - createDatetime({ timeFormat: "HH:mm:ss:SSS", viewMode: 'time', defaultValue: date, onChange: function( selected ){ - assert.equal( selected.minute(), 47 ); - done(); - }, timeConstraints: { minutes: { step: 15 }}}); - - trigger( 'mousedown', dt.timeDown( 1 ) ); - trigger( 'mouseup', dt.timeDown( 1 ) ); - assert.equal( dt.minute().innerHTML, 47 ); - }); - - it( 'invalid input value', function( done ){ - createDatetime({ defaultValue: 'luis', onChange: function( updated ){ - assert.equal( mDate.format('L LT'), updated.format('L LT') ); - done(); - }}); - - assert.equal( dt.input().value, 'luis' ); - dt.input().value = strDate; - ev.change( dt.input() ); - }); - - it( 'delete input value', function( done ){ - createDatetime({ defaultValue: date, onChange: function( date ){ - assert.equal( date, '' ); - done(); - }}); - dt.input().value = ''; - ev.change( dt.input() ); - }); - - it( 'strictParsing=true', function( done ){ - var invalidStrDate = strDate + 'x'; - createDatetime({ defaultValue: '', strictParsing: true, onChange: function( updated ){ - assert.equal( updated, invalidStrDate); - done(); - }}); - - dt.input().value = invalidStrDate; - ev.change( dt.input() ); - }); - - it( 'strictParsing=false', function( done ){ - var invalidStrDate = strDate + 'x'; - createDatetime({ defaultValue: '', strictParsing: false, onChange: function( updated ){ - assert.equal( mDate.format('L LT'), updated.format('L LT') ); - done(); - }}); - - dt.input().value = invalidStrDate; - ev.change( dt.input() ); - }); -}); diff --git a/tests/testdom.js b/tests/testdom.js deleted file mode 100644 index ed640e410..000000000 --- a/tests/testdom.js +++ /dev/null @@ -1,12 +0,0 @@ -module.exports = function(markup) { - if (typeof document !== 'undefined') return; - var jsdom = require("jsdom").jsdom; - global.document = jsdom(markup || ''); - global.window = document.defaultView; - - global.navigator = global.window.navigator = {}; - navigator.userAgent = 'NodeJs JsDom'; - navigator.appVersion = ''; - - return document; -}; diff --git a/typings/DateTime.d.ts b/typings/DateTime.d.ts new file mode 100644 index 000000000..99bbc4134 --- /dev/null +++ b/typings/DateTime.d.ts @@ -0,0 +1,216 @@ +// Type definitions for react-datetime +// Project: https://github.com/arqex/react-datetime +// Definitions by: Ivan Verevkin +// Updates by: Aaron Spaulding , +// Karol Janyst , +// Javier Marquez + +import { Component, ChangeEvent, FocusEvent, FocusEventHandler } from 'react'; +import { Moment } from 'moment'; + +export = ReactDatetimeClass; + +declare namespace ReactDatetimeClass { + /* + The view mode can be any of the following strings. + */ + export type ViewMode = 'years' | 'months' | 'days' | 'time'; + + export interface TimeConstraint { + min: number; + max: number; + step: number; + } + + export interface TimeConstraints { + hours?: TimeConstraint; + minutes?: TimeConstraint; + seconds?: TimeConstraint; + milliseconds?: TimeConstraint; + } + + type EventOrValueHandler = (event: Event | Moment | string) => void; + + export interface DatetimepickerProps { + /* + Represents the selected date by the component, in order to use it as a controlled component. + This prop is parsed by moment.js, so it is possible to use a date string or a moment.js date. + */ + value?: Date | string | Moment; + /* + Represents the selected date for the component to use it as a uncontrolled component. + This prop is parsed by moment.js, so it is possible to use a date string or a moment.js date. + */ + initialValue?: Date | string | Moment; + /* + 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. + */ + initialViewDate?: Date | string | Moment; + /* + The default view to display when the picker is shown for the first time. ('years', 'months', 'days', 'time') + */ + initialViewMode?: ViewMode; + /* + In the calendar we can navigate through years and months without actualling updating the selected view. 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. + */ + updateOnView?: string; + /* + Defines the format for the date. It accepts any moment.js date 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. + */ + dateFormat?: boolean | string; + /* + Defines the format for the time. It accepts any moment.js time 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. + */ + timeFormat?: boolean | string; + /* + Whether to show an input field to edit the date manually. + */ + input?: boolean; + /* + 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. + */ + open?: boolean; + /* + Manually set the locale for the react-datetime instance. + Moment.js locale needs to be loaded to be used, see i18n docs. + */ + locale?: string; + /* + Whether to interpret input times as UTC or the user's local timezone. + */ + utc?: boolean; + /* + 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). + */ + displayTimeZone?: string; + /* + 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). + */ + onChange?: (value: Moment | string) => void; + /* + Callback trigger for when the user opens the datepicker. + */ + onOpen?: FocusEventHandler; + /* + Callback trigger for when the datepicker is 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 receives the value of the + input (a string). + */ + onClose?: EventOrValueHandler>; + /* + Callback trigger when the view mode changes. The callback receives the selected view mode + string ('years', 'months', 'days', 'time') as only parameter. + */ + onNavigate?: (viewMode: string) => void; + /* + 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. + */ + onBeforeNavigate?: (nextView: string, currentView: string, viewDate: Moment) => string; + /* + Callback trigger when the user navigates to the previous month, year or decade. + The callback receives the amount and type ('month', 'year') as parameters. + */ + onNavigateBack?: (amount: number, type: string) => void; + /* + Callback trigger when the user navigates to the next month, year or decade. + The callback receives the amount and type ('month', 'year') as parameters. + */ + onNavigateForward?: (amount: number, type: string) => void; + /* + Extra class names for the component markup. + */ + className?: string; + /* + Defines additional attributes for the input element of the component. + */ + inputProps?: React.HTMLProps; + /* + 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. + */ + isValidDate?: (currentDate: any, selectedDate: any) => boolean; + /* + Customize the way the calendar is rendered. The accepted function receives the view mode that + is 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. + */ + renderView?: (viewMode: string, renderCalendar: Function) => JSX.Element; + /* + 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 + */ + renderDay?: (props: any, currentDate: any, selectedDate: any) => JSX.Element; + /* + 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 + */ + renderMonth?: (props: any, month: number, year: number, selectedDate: any) => JSX.Element; + /* + 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 + */ + renderYear?: (props: any, year: number, selectedDate: any) => JSX.Element; + /* + Replace the rendering of the input element. The accepted function has openCalendar + (a function which opens the calendar) and the default calculated props for the input. + Must return a React component or null. + */ + renderInput?: (props: any, openCalendar: Function, closeCalendar: Function) => JSX.Element; + /* + Whether to use moment's strict parsing when parsing input. + */ + strictParsing?: boolean; + /* + When true, once the day has been selected, the react-datetime will be automatically closed. + */ + closeOnSelect?: boolean; + /* + 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. + */ + timeConstraints?: TimeConstraints; + /* + When true the picker get closed when clicking outside of the calendar or the input box. When false, it stays open. + */ + closeOnClickOutside?: boolean; + } + + export interface DatetimepickerState { + updateOn: string; + inputFormat: string; + viewDate: Moment; + selectedDate: Moment; + inputValue: string; + open: boolean; + } +} + +declare class ReactDatetimeClass extends Component {} diff --git a/typings/react-datetime-tests.tsx b/typings/react-datetime-tests.tsx new file mode 100644 index 000000000..0742aaf41 --- /dev/null +++ b/typings/react-datetime-tests.tsx @@ -0,0 +1,200 @@ +import * as React from "react"; +import { Moment } from "moment"; +import * as moment from "moment"; +import * as ReactDatetime from "react-datetime"; + +/* + Test the datetime picker. + */ + +const TEST_BASIC_USAGE: JSX.Element = ; + +/* + Test date properties + */ + +const TEST_DATE_PROPS_FOR_VALUE: JSX.Element = ; + +const TEST_DATE_PROPS_FOR_DEFAULT_VALUE: JSX.Element = ; + +const TEST_DATE_PROPS_FOR_VALUE_AS_MOMENT: JSX.Element = ; + +const TEST_DATE_PROPS_FOR_VALUE_AS_STRING: JSX.Element = ; + +const TEST_DATE_PROPS_FOR_DEFAULT_VALUE_AS_MOMENT: JSX.Element = ; + +const TEST_DATE_PROPS_FOR_DEFAULT_VALUE_AS_STRING: JSX.Element = ; + +/* + Test formats + */ + +const TEST_FORMAT_PROPS_AS_STRINGS: JSX.Element = ; + +const TEST_FORMAT_PROPS_AS_BOOLEANS: JSX.Element = ; + +/* + Test boolean options + */ + +const TEST_BOOLEAN_PROPS: JSX.Element = ; + +/* + Test locale options + */ + +const TEST_LOCALE_PROPS: JSX.Element = ; + +/* + Test input props + */ + +const TEST_INPUT_PROPS: JSX.Element = ; + +/* + Test Event handlers + */ + + const TEST_EVENT_HANDLERS_WITH_STRINGS: JSX.Element = {} + } + onOpen={ + () => {} + } + onClose={ + (momentOrInputString:string) => {} + } + onNavigate={ + (initialViewMode:string) => {} + } + onBeforeNavigate={ + (nextView:string, currentView:string, viewDate: any ) => { return 'ok' } + } + />; + +const TEST_EVENT_HANDLERS_WITH_MOMENT: JSX.Element = {} + } + onClose={ + (momentOrInputString:Moment) => {} + } + />; + +/* + Test view mode and className + */ + +const TEST_VIEW_MODE_AND_CLASS_PROPS: JSX.Element = ; + +/* + Test date validator + */ + +const TEST_DATE_VALIDATOR_PROP: JSX.Element = { + return true; + } } + />; + +/* + Test customizable components + */ + +const TEST_CUSTOMIZABLE_COMPONENT_PROPS: JSX.Element = { + return { '0' + currentDate.date() }; + } } + renderMonth={ (props: any, month: any, year: any, selectedDate: any) => { + return { month }; + } } + renderYear={ (props: any, year: any, selectedDate: any) => { + return { year % 100 }; + } } + renderInput={ (props: any, openCalendar: Function, closeCalendar: Function) => { + return + }} + renderView={ (viewMode: string, renderCalendar: Function ) => { + return renderCalendar() + }} + />; + +/* + Test time constraints. + */ + +const TEST_BASIC_TIME_CONSTRAINTS: JSX.Element = ; + +const TEST_TIME_CONSTRAINTS_WITH_ONE: JSX.Element = ; + +const TEST_TIME_CONSTRAINTS_WITH_ALL: JSX.Element = ; diff --git a/typings/tsconfig.json b/typings/tsconfig.json new file mode 100644 index 000000000..4bc02eef5 --- /dev/null +++ b/typings/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "noImplicitAny": true, + "strictNullChecks": false, + "types": [], + "noEmit": true, + "jsx": "react", + "baseUrl": "../", + "lib": ["es6"], + "paths": { + "react-datetime": ["./"] + } + }, + "files": [ + "./DateTime.d.ts", + "react-datetime-tests.tsx" + ] +} diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index c0f00979a..000000000 --- a/webpack.config.js +++ /dev/null @@ -1,30 +0,0 @@ -var webpack = require('webpack'); - -var plugins = [ - new webpack.DefinePlugin({ - 'process.env': { NODE_ENV: '"production"'} - }) -]; - -module.exports = { - - entry: ['./DateTime.js'], - - output: { - path: __dirname + '/dist/', - library: 'Datetime', - libraryTarget: 'umd' - }, - - resolve: { - extensions: ['', '.js'] - }, - - externals: { - 'react': 'React', - 'react-dom': 'ReactDOM', - 'moment': 'moment' - }, - - plugins: plugins -};