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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
import { Popover } from '@automattic/components';
import clsx from 'clsx';
import { localize } from 'i18n-calypso';
import { debounce } from 'lodash';
import moment from 'moment';
import PropTypes from 'prop-types';
import { createRef, Component } from 'react';
import { withLocalizedMoment } from 'calypso/components/localized-moment';
import DateRangePicker from './date-range-picker';
import DateRangeFooter from './footer';
import DateRangeHeader from './header';
import DateRangeInputs from './inputs';
import Shortcuts from './shortcuts';
import DateRangeTrigger from './trigger';

import './style.scss';

/**
 * Module variables
 */
const NO_DATE_SELECTED_VALUE = null;
const noop = () => {};

export class DateRange extends Component {
	static propTypes = {
		selectedStartDate: PropTypes.oneOfType( [
			PropTypes.instanceOf( Date ),
			PropTypes.instanceOf( moment ),
		] ),
		selectedEndDate: PropTypes.oneOfType( [
			PropTypes.instanceOf( Date ),
			PropTypes.instanceOf( moment ),
		] ),
		selectedShortcutId: PropTypes.string,
		onDateSelect: PropTypes.func,
		onDateCommit: PropTypes.func,
		firstSelectableDate: PropTypes.oneOfType( [
			PropTypes.instanceOf( Date ),
			PropTypes.instanceOf( moment ),
		] ),
		lastSelectableDate: PropTypes.oneOfType( [
			PropTypes.instanceOf( Date ),
			PropTypes.instanceOf( moment ),
		] ),
		triggerText: PropTypes.func,
		isCompact: PropTypes.bool,
		showTriggerClear: PropTypes.bool,
		renderTrigger: PropTypes.func,
		renderHeader: PropTypes.func,
		renderFooter: PropTypes.func,
		renderInputs: PropTypes.func,
		displayShortcuts: PropTypes.bool,
		rootClass: PropTypes.string,
		useArrowNavigation: PropTypes.bool,
		overlay: PropTypes.node,
		customTitle: PropTypes.string,
		onShortcutClick: PropTypes.func,
		trackExternalDateChanges: PropTypes.bool,
		shortcutList: PropTypes.array,
	};

	static defaultProps = {
		onDateSelect: noop,
		onDateCommit: noop,
		isCompact: false,
		focusedMonth: null,
		showTriggerClear: true,
		renderTrigger: ( props ) => <DateRangeTrigger { ...props } />,
		renderHeader: ( props ) => <DateRangeHeader { ...props } />,
		renderFooter: ( props ) => <DateRangeFooter { ...props } />,
		renderInputs: ( props ) => <DateRangeInputs { ...props } />,
		displayShortcuts: false,
		rootClass: '',
		useArrowNavigation: false,
		overlay: null,
		customTitle: '',
		trackExternalDateChanges: false,
	};

	constructor( props ) {
		super( props );

		// Define the date range that is selectable (ie: not disabled)
		const firstSelectableDate =
			this.props.firstSelectableDate && this.props.moment( this.props.firstSelectableDate );
		const lastSelectableDate =
			this.props.lastSelectableDate && this.props.moment( this.props.lastSelectableDate );

		// Clamp start/end dates to ranges (if specified)
		let startDate =
			this.props.selectedStartDate == null
				? NO_DATE_SELECTED_VALUE
				: this.clampDateToRange( this.props.moment( this.props.selectedStartDate ), {
						dateFrom: firstSelectableDate,
						dateTo: lastSelectableDate,
				  } );

		let endDate =
			this.props.selectedEndDate == null
				? NO_DATE_SELECTED_VALUE
				: this.clampDateToRange( this.props.moment( this.props.selectedEndDate ), {
						dateFrom: firstSelectableDate,
						dateTo: lastSelectableDate,
				  } );

		const selectedShortcutId = this.props.selectedShortcutId || null;

		// Ensure start is before end otherwise flip the values
		if ( startDate && endDate && endDate.isBefore( startDate ) ) {
			// flip values via array destructuring (think about it...)
			[ startDate, endDate ] = [ endDate, startDate ];
		}

		// Build initial state
		this.state = {
			popoverVisible: false,
			staleStartDate: null,
			staleEndDate: null,
			startDate: startDate,
			endDate: endDate,
			selectedShortcutId,
			staleDatesSaved: false,
			// this needs to be independent from startDate because we must independently validate them
			// before updating the central source of truth (ie: startDate)
			textInputStartDate: this.toDateString( startDate ),
			textInputEndDate: this.toDateString( endDate ),
			initialStartDate: startDate, // cache values in case we need to reset to them
			initialEndDate: endDate, // cache values in case we need to reset to them
			focusedMonth: this.props.focusedMonth,
			numberOfMonths: this.getNumberOfMonths(),
		};

		// Ref to the Trigger <button> used to position the Popover component
		this.triggerButtonRef = createRef();
		this.throttledHandleResize = debounce( () => {
			this.setState( {
				numberOfMonths: this.getNumberOfMonths(),
			} );
		}, 250 );
	}

	componentDidMount() {
		window.addEventListener( 'resize', this.throttledHandleResize );
	}

	componentWillUnmount() {
		window.removeEventListener( 'resize', this.throttledHandleResize );
	}

	/**
	 * Opens the popover
	 * Note this does not commit the current date state
	 */
	openPopover = () => {
		const newState = {
			popoverVisible: true,
		};
		if ( this.props.trackExternalDateChanges ) {
			newState.startDate = this.props.selectedStartDate;
			newState.endDate = this.props.selectedEndDate;
			newState.selectedShortcutId = this.props.selectedShortcutId;
			newState.textInputStartDate = this.toDateString( this.props.selectedStartDate );
			newState.textInputEndDate = this.toDateString( this.props.selectedEndDate );
			newState.staleStartDate = this.props.selectedStartDate;
			newState.staleEndDate = this.props.selectedEndDate;
		}
		this.setState( newState );
	};

	/**
	 * Closes the popover
	 * Note this does not commit the current date state
	 */
	closePopover = () => {
		this.setState( {
			popoverVisible: false,
		} );
	};

	/**
	 * Toggles the popover between open/closed
	 * Note this does not commit the current date state
	 */
	togglePopover = () => {
		if ( this.state.popoverVisible ) {
			this.closePopover();
		} else {
			this.openPopover();
		}
	};

	closePopoverAndRevert = () => {
		this.closePopover();
		this.revertDates();
	};

	closePopoverAndCommit = () => {
		this.closePopover();
		this.commitDates();
	};

	/**
	 * Updates state with current value of start/end
	 * text inputs
	 * @param  {string} val        the value of the input
	 * @param  {string} startOrEnd either "Start" or "End"
	 */
	handleInputChange = ( val, startOrEnd ) => {
		this.setState( {
			[ `textInput${ startOrEnd }Date` ]: val,
		} );
	};

	/**
	 * Updates the state when the date text inputs are blurred
	 * @param  {string} val        the value of the input
	 * @param  {string} startOrEnd either "Start" or "End"
	 */
	handleInputBlur = ( val, startOrEnd ) => {
		if ( val === '' ) {
			return;
		}
		const date = this.props.moment( val, this.getLocaleDateFormat() );

		if ( ! date.isValid() ) {
			return; // bail out
		}

		// Either `startDate` or `endDate`
		const stateKey = `${ startOrEnd.toLowerCase() }Date`;

		const isSameDate =
			this.state[ stateKey ] !== null ? this.state[ stateKey ].isSame( date, 'day' ) : false;

		if ( isSameDate ) {
			return;
		}
		// Should we juggle the dates more??
		if ( ! this.state.startDate ) {
			this.setState( {
				startDate: date,
			} );
			return;
		}

		this.setState( {
			[ stateKey ]: date,
		} );
	};

	/**
	 * Updates the currently focused date picker month when one of the
	 * inputs is focused.
	 * http://react-day-picker.js.org/api/DayPicker/#month
	 * @param  {string} val        the value of the input
	 * @param  {string} startOrEnd either "Start" or "End"
	 */
	handleInputFocus = ( val, startOrEnd ) => {
		if ( val === '' ) {
			return;
		}

		const date = this.props.moment( val, this.getLocaleDateFormat() );

		if ( ! date.isValid() ) {
			return; // bail out
		}

		const numMonthsShowing = this.getNumberOfMonths(); // 2 or 1

		// If we focused the endDate and we're showing more than 1 month
		// then the picker should focus the month before
		if ( startOrEnd === 'End' && numMonthsShowing > 1 ) {
			// moment isn't immutable so this modifies
			// the existing moment instance
			date.subtract( 1, 'months' );
		}

		this.setState( {
			focusedMonth: date.toDate(),
		} );
	};

	/**
	 * Updates the "stale" data to reflect the current start/end dates
	 * This causes any cached data to be lost and thus the current start/end
	 * dates are persisted. Typically called when user clicks "Apply"
	 */
	commitDates = () => {
		this.setState(
			( previousState ) => ( {
				staleStartDate: previousState.startDate, // update cached stale dates
				staleEndDate: previousState.endDate, // update cached stale dates
				staleDatesSaved: false,
			} ),
			() => {
				this.props.onDateCommit(
					this.state.startDate,
					this.state.endDate,
					this.state.selectedShortcutId
				);
				this.closePopover();
			}
		);
	};

	/**
	 * Reverts current start/end dates to the cache "stale" versions
	 * Typically required when the user makes a selection but then dismisses
	 * the DateRange without clicking "Apply"
	 */
	revertDates = () => {
		this.setState(
			( previousState, props ) => {
				const startDate = previousState.staleStartDate;
				const endDate = previousState.staleEndDate;
				const previousAppliedShortcutId = props.selectedShortcutId;

				const newState = {
					staleDatesSaved: false,
					startDate: startDate,
					endDate: endDate,
					selectedShortcutId: previousAppliedShortcutId,
					textInputStartDate: this.toDateString( startDate ),
					textInputEndDate: this.toDateString( endDate ),
				};

				return newState;
			},
			() => {
				this.props.onDateCommit(
					this.state.startDate,
					this.state.endDate,
					this.state.selectedShortcutId
				);
			}
		);
	};

	/**
	 * Resets any currently selected (not commmited!) dates
	 * but leaves stale dates untouched. This makes it possible
	 * for the user to revert back to the previous dates should
	 * they so choose. Required for scenario where user selects dates
	 * then wants to clear that selection entirely but then clicks away
	 * without selecting any dates
	 */
	resetDates = () => {
		this.setState( ( previousState, props ) => {
			const startDate = previousState.initialStartDate;
			const endDate = previousState.initialEndDate;
			const previousAppliedShortcutId = props.selectedShortcutId;

			const newState = {
				staleDatesSaved: false,
				startDate: startDate,
				endDate: endDate,
				selectedShortcutId: previousAppliedShortcutId,
				textInputStartDate: this.toDateString( startDate ),
				textInputEndDate: this.toDateString( endDate ),
			};

			return newState;
		} );
	};

	/**
	 * Fully clears all dates to empty values
	 * affectively saying "get rid of all dates"
	 */
	clearDates = () => {
		this.setState(
			{
				startDate: null,
				endDate: null,
				selectedShortcutId: null,
				staleStartDate: null,
				staleEndDate: null,
				textInputStartDate: '',
				textInputEndDate: '',
			},
			() => {
				// Fired to ensure date change is propagated upwards
				this.props.onDateCommit(
					this.state.startDate,
					this.state.endDate,
					this.state.selectedShortcutId
				);
			}
		);
	};

	/**
	 * Formats a given date to the appropriate format for the
	 * current locale
	 * @param  {import('moment').Moment | Date} date the date to be converted
	 * @returns {string}      the date as a formatted locale string
	 */
	formatDateToLocale( date ) {
		return this.props.moment( date ).format( 'L' );
	}

	/**
	 * 	Gets the locale appropriate date format (eg: "MM/DD/YYYY")
	 * @returns {string} date format as a string
	 */
	getLocaleDateFormat() {
		return this.props.moment.localeData().longDateFormat( 'L' );
	}

	/**
	 * Enforces that given date is within the bounds of the
	 * range specified
	 * @param  {import('moment').Moment}  date             momentJS instance
	 * @param  {Object} options          date range
	 * @param  {import('moment').Moment | Date}  options.dateFrom the start of the date range
	 * @param  {import('moment').Moment | Date}  options.dateTo   the end of the date range
	 * @returns {import('moment').Moment}                  the date clamped to be within the range
	 */
	clampDateToRange( date, { dateFrom, dateTo } ) {
		// Ensure endDate is within bounds of firstSelectableDate
		if ( dateFrom && date.isBefore( dateFrom ) ) {
			date = dateFrom;
		}

		if ( dateTo && date.isAfter( dateTo ) ) {
			date = dateTo;
		}

		return date;
	}

	/**
	 * Converts date-like object to a string suitable
	 * for display in a text input. Also converts
	 * to locale appropriate format.
	 * @param  {import('moment').Moment | Date} date the date for conversion
	 * @returns {string}      the date expressed as a locale appropriate string or if null
	 *                       then returns the locale format (eg: MM/DD/YYYY)
	 */
	toDateString( date ) {
		if ( this.props.moment.isMoment( date ) || this.props.moment.isDate( date ) ) {
			return this.formatDateToLocale( this.props.moment( date ) );
		}

		return this.getLocaleDateFormat(); // "MM/DD/YYY" or locale equivalent
	}

	getNumberOfMonths() {
		return window.matchMedia( '(min-width: 520px)' ).matches ? 2 : 1;
	}

	handleDateRangeChange = ( startDate, endDate ) => {
		this.setState( {
			startDate,
			endDate,
			selectedShortcutId: null,
			textInputStartDate: this.toDateString( startDate ),
			textInputEndDate: this.toDateString( endDate ),
		} );
		this.props.onDateSelect && this.props.onDateSelect( startDate, endDate );
	};

	handleDateRangeChangeByShortcutClick = ( startDate, endDate, shortcut ) => {
		this.handleDateRangeChange( startDate, endDate );

		this.setState( {
			selectedShortcutId: shortcut.id,
		} );
	};

	// Expose closePopoverAndCommit to the parent component for shortcut clicks.
	handleShortcutClick = ( shortcut ) => {
		this.props.onShortcutClick( shortcut, this.closePopoverAndCommit );
	};

	/**
	 * Renders the Popover component
	 * @returns {import('react').Element} the Popover component
	 */
	renderPopover() {
		const headerProps = {
			customTitle: this.props.customTitle,
			startDate: this.state.startDate,
			endDate: this.state.endDate,
			resetDates: this.resetDates,
		};

		const footerProps = {
			onApplyClick: this.commitDates,
			onCancelClick: this.closePopoverAndRevert,
		};

		const inputsProps = {
			startDateValue: this.state.textInputStartDate,
			endDateValue: this.state.textInputEndDate,
			onInputChange: this.handleInputChange,
			onInputBlur: this.handleInputBlur,
			onInputFocus: this.handleInputFocus,
		};

		return (
			<Popover
				className="date-range__popover"
				isVisible={ this.state.popoverVisible }
				context={ this.triggerButtonRef.current }
				position="bottom"
				onClose={ this.closePopover }
			>
				<div className="date-range__popover-content">
					<div
						className={ clsx( 'date-range__popover-inner', {
							'date-range__popover-inner__hasoverlay': !! this.props.overlay,
						} ) }
					>
						{ this.props.overlay && (
							<div className="date-range__popover-inner-overlay">{ this.props.overlay }</div>
						) }
						<div { ...( this.props.overlay && { 'aria-hidden': true, inert: '' } ) }>
							{ this.props.renderHeader( headerProps ) }
							{ this.props.renderInputs( inputsProps ) }
							{ this.renderDatePicker() }
							{ this.props.renderFooter( footerProps ) }
						</div>
					</div>
					{ /* Render shortcuts to the right of the calendar */ }
					{ this.props.displayShortcuts && (
						<div className="date-range-picker-shortcuts">
							<Shortcuts
								selectedShortcutId={ this.state.selectedShortcutId }
								shortcutList={ this.props.shortcutList }
								onClick={ this.handleDateRangeChangeByShortcutClick }
								locked={ !! this.props.overlay }
								startDate={ this.state.startDate }
								endDate={ this.state.endDate }
								onShortcutClick={ this.handleShortcutClick } // for tracking shortcut clicks
							/>
						</div>
					) }
				</div>
			</Popover>
		);
	}

	/**
	 * Renders the DatePicker component
	 * @returns {import('react').Element} the DatePicker component
	 */
	renderDatePicker() {
		return (
			<DateRangePicker
				firstSelectableDate={ this.props.firstSelectableDate }
				lastSelectableDate={ this.props.lastSelectableDate }
				selectedStartDate={ this.state.startDate }
				selectedEndDate={ this.state.endDate }
				onDateRangeChange={ this.handleDateRangeChange }
				focusedMonth={ this.state.focusedMonth }
				numberOfMonths={ this.state.numberOfMonths }
				useArrowNavigation={ this.props.useArrowNavigation }
			/>
		);
	}

	/**
	 * Renders the component
	 * @returns {import('react').Element} the DateRange component
	 */
	render() {
		const rootClassNames = clsx(
			{
				'date-range': true,
				'toggle-visible': this.state.popoverVisible,
			},
			this.props.rootClass
		);

		const triggerProps = {
			startDate: this.state.startDate,
			endDate: this.state.endDate,
			startDateText: this.toDateString( this.state.startDate ),
			endDateText: this.toDateString( this.state.endDate ),
			buttonRef: this.triggerButtonRef,
			onTriggerClick: this.togglePopover,
			onClearClick: this.clearDates,
			triggerText: this.props.triggerText,
			isCompact: this.props.isCompact,
			showClearBtn: this.props.showTriggerClear,
		};

		return (
			<div className={ rootClassNames }>
				{ this.props.renderTrigger( triggerProps ) }
				{ this.renderPopover() }
			</div>
		);
	}
}

export default localize( withLocalizedMoment( DateRange ) );