/** @format */ /** * External dependencies */ import 'core-js/fn/object/assign'; import 'core-js/fn/array/from'; import { __, sprintf } from '@wordpress/i18n'; import classnames from 'classnames'; import { Component } from '@wordpress/element'; import { DayPickerRangeController, isInclusivelyAfterDay, isInclusivelyBeforeDay, } from 'react-dates'; import moment from 'moment'; import { partial } from 'lodash'; import PropTypes from 'prop-types'; import { withViewportMatch } from '@wordpress/viewport'; import 'react-dates/lib/css/_datepicker.css'; /** * WooCommerce dependencies */ import { validateDateInputForRange } from '@woocommerce/date'; /** * Internal dependencies */ import DateInput from './input'; import phrases from './phrases'; import './style.scss'; /** * This is wrapper for a [react-dates](https://github.com/airbnb/react-dates) powered calendar. */ class DateRange extends Component { constructor( props ) { super( props ); this.onDatesChange = this.onDatesChange.bind( this ); this.onFocusChange = this.onFocusChange.bind( this ); this.onInputChange = this.onInputChange.bind( this ); this.getOutsideRange = this.getOutsideRange.bind( this ); } onDatesChange( { startDate, endDate } ) { const { onUpdate, shortDateFormat } = this.props; onUpdate( { after: startDate, before: endDate, afterText: startDate ? startDate.format( shortDateFormat ) : '', beforeText: endDate ? endDate.format( shortDateFormat ) : '', afterError: null, beforeError: null, } ); } onFocusChange( focusedInput ) { this.props.onUpdate( { focusedInput: ! focusedInput ? 'startDate' : focusedInput, } ); } onInputChange( input, event ) { const value = event.target.value; const { after, before, shortDateFormat } = this.props; const { date, error } = validateDateInputForRange( input, value, before, after, shortDateFormat ); this.props.onUpdate( { [ input ]: date, [ input + 'Text' ]: value, [ input + 'Error' ]: value.length > 0 ? error : null, } ); } getOutsideRange() { const { invalidDays } = this.props; if ( 'string' === typeof invalidDays ) { switch ( invalidDays ) { case 'past': return day => isInclusivelyBeforeDay( day, moment() ); case 'future': return day => isInclusivelyAfterDay( day, moment() ); case 'none': default: return undefined; } } return 'function' === typeof invalidDays ? invalidDays : undefined; } setTnitialVisibleMonth( isDoubleCalendar, before ) { return () => { const visibleDate = before || moment(); if ( isDoubleCalendar ) { return visibleDate.clone().subtract( 1, 'month' ); } return visibleDate; }; } render() { const { after, before, focusedInput, afterText, beforeText, afterError, beforeError, shortDateFormat, isViewportMobile, isViewportSmall, } = this.props; const isOutsideRange = this.getOutsideRange(); const isDoubleCalendar = isViewportMobile && ! isViewportSmall; return (