All files / DateSelect DateSelect.tsx

82.75% Statements 48/58
61.11% Branches 11/18
92.3% Functions 12/13
82.45% Lines 47/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                              1x 1x 1x 35x   1x               1x   1x 1x     1x                                                                                                                                                                             1x                                                           1x   1x     21x     21x 21x 21x           1x           1x                                                                                                                                                                                                                                   1x             672x 1519x                     1x   21x         2x   2x 1x       21x 2x 1x       1x           21x 1x         21x 1x     21x 1x     21x 9x   9x   9x                                     21x                                     47x                                                                       26x   26x           26x   26x         26x                                                                                                                                                                                                                          
/* eslint-disable react/prop-types */
import _, { omit } from 'lodash';
import PropTypes from 'prop-types';
import React from 'react';
import DayPicker from 'react-day-picker';
 
import { buildModernHybridComponent } from '../../util/state-management';
import { lucidClassNames } from '../../util/style-helpers';
import { StandardProps, getFirst } from '../../util/component-types';
import * as reducers from './DateSelect.reducers';
import InfiniteSlidePanel from '../InfiniteSlidePanel/InfiniteSlidePanel';
import { ISlidePanelProps } from '../SlidePanel/SlidePanel';
import CalendarMonth, { ICalendarProps } from '../CalendarMonth/CalendarMonth';
import ChevronIcon from '../Icon/ChevronIcon/ChevronIcon';
 
const cx = lucidClassNames.bind('&-DateSelect');
const DateUtils = DayPicker.DateUtils;
const NAV_BUTTON_SIZE = 32;
const clampMonthsShown = (monthsShown: number) => _.clamp(monthsShown, 1, 6);
 
const { any, bool, node, func, instanceOf, number, oneOf, string } = PropTypes;
 
/** Date Select Calendar Month */
export interface IDateSelectCalendarMonthProps extends StandardProps {
	modifiers: any;
	description?: string;
}
 
const DateSelectCalendarMonth = (_props: IDateSelectCalendarMonthProps): null =>
	null;
DateSelectCalendarMonth.displayName = 'DateSelect.CalendarMonth';
DateSelectCalendarMonth.peek = {
	description: `Child component to pass thru props to underlying CalendarMonth.`,
};
DateSelectCalendarMonth.propName = 'CalendarMonth';
 
/** Date Select */
export interface IDateSelectProps extends StandardProps {
	/** Number of calendar months to show. Min 1, suggested max 3. Actual max is 6. */
	monthsShown: number;
 
	/** Number of calendar months rendered at any given time (including those out
			of view).  In practice it should be at least (2 * monthsShown) + 2. It's
			got some issues that still need to be ironed out but it works. */
	calendarsRendered: number;
 
	/** The offset of the leftmost month in view, where 0 is the
			\`initialMonth\`.  Negative values will show previous months. */
	offset: number;
 
	/** Sets the start date in a date range. */
	from: Date | null;
 
	/** Sets the end date in a date range. */
	to: Date | null;
 
	/** The next selection that is expected. Primarily used to preview expected
			ranges when the cursor is on a target date. */
	selectMode?: 'day' | 'from' | 'to';
 
	/** Sets first month in view on render. The 0 value for the \`offset\` prop
			refers to this month. */
	initialMonth: Date;
 
	/** Sets selected days. Passed through to \`CalendarMonth\` ->
			\`react-day-picker\`. */
	selectedDays: (date: Date) => boolean | Date | Date[];
 
	/** Sets disabled days. Passed through to \`CalendarMonth\` ->
			\`react-day-picker\`.*/
	disabledDays: (date: Date) => boolean | Date | Date[];
 
	/** Display a divider between each month. */
	showDivider: boolean;
 
	/** Called when user's swipe would change the month \`offset\`. Callback
			passes number of months swiped by the user (positive for forward swipes,
			negative for backwards swipes). */
	onSwipe: (
		monthsSwipes: number,
		{ event, props }: { event: React.TouchEvent; props: ISlidePanelProps }
	) => void;
 
	/** Called when user clicks the previous button.   */
	onPrev: ({
		event,
		props,
	}: {
		event: React.MouseEvent;
		props: IDateSelectProps;
	}) => void;
 
	/** Called when user clicks the next button */
	onNext: ({
		event,
		props,
	}: {
		event: React.MouseEvent;
		props: IDateSelectProps;
	}) => void;
 
	/** Called when user selects a date. Callback passes a Date object as the
			first argument. */
	onSelectDate: (
		selectedDate: any,
		{ event, props }: { event: React.MouseEvent; props: IDateSelectProps }
	) => void;
 
	/** Render initial font size relative to size of the component so it scales
			with the calendar size. */
	isFontSizeRelative: boolean;
 
	/** Highlight dates and ranges based on cursor position. */
	showCursorHighlight: boolean;
 
	/** Render the calendar months in a touch-friendly slider with some being
			rendered out-of-view. Set to \`false\` to disable this feature and gain a
			performance boost. */
	useSlidePanel: boolean;
}
 
const nonPassThroughs = [
	'className',
	'monthsShown',
	'calendarsRendered',
	'offset',
	'from',
	'to',
	'selectMode',
	'initialMonth',
	'selectedDays',
	'disabledDays',
	'showDivider',
	'onSwipe',
	'onPrev',
	'onNext',
	'onSelectDate',
	'isFontSizeRelative',
	'showCursorHighlight',
	'useSlidePanel',
	'CalendarMonth',
	'callbackId',
	'initialState',
];
 
export interface IDateSelectState {
	offset: number;
	cursor: Date | null;
}
 
class DateSelect extends React.Component<IDateSelectProps, IDateSelectState> {
	static displayName = 'DateSelect';
 
	static CalendarMonth = DateSelectCalendarMonth;
 
	private initialMonth: Date;
	private rootRef: HTMLElement | null = null;
 
	constructor(props: IDateSelectProps) {
		super(props);
		this.initialMonth = new Date(this.props.initialMonth);
		this.state = {
			offset: 0,
			cursor: null,
		};
	}
 
	static peek = {
		description: `A date selection component capabaple of supporting single date and date range selections.`,
		categories: ['controls', 'selectors'],
		madeFrom: ['InfiniteSlidePanel', 'CalendarMonth'],
	};
 
	static propTypes = {
		/**
			Appended to the component-specific class names set on the root element.
		*/
		className: string,
 
		/**
			Number of calendar months to show. Min 1, suggested max 3. Actual max is 6.
		*/
		monthsShown: number,
 
		calendarsRendered: number /**
			Number of calendar months rendered at any given time (including those out
			of view).  In practice it should be at least (2 * monthsShown) + 2. It's
			got some issues that still need to be ironed out but it works.
		*/,
 
		/**
			The offset of the leftmost month in view, where 0 is the
			\`initialMonth\`.  Negative values will show previous months.
		*/
		offset: number,
 
		/**
			Sets the start date in a date range.
		*/
		from: instanceOf(Date),
 
		/**
			Sets the end date in a date range.
		*/
		to: instanceOf(Date),
 
		/**
			The next selection that is expected. Primarily used to preview expected
			ranges when the cursor is on a target date.
		*/
		selectMode: oneOf(['day', 'from', 'to']),
 
		/**
			Sets first month in view on render. The 0 value for the \`offset\` prop
			refers to this month.
		*/
		initialMonth: instanceOf(Date),
 
		/**
			Sets selected days. Passed through to \`CalendarMonth\` ->
			\`react-day-picker\`. Can be a \`Date\`, array of \`Date\`s or a function
			with the signature \`(date) => Boolean\`.
		*/
		selectedDays: any,
 
		/**
			Sets disabled days. Passed through to \`CalendarMonth\` ->
			\`react-day-picker\`. Can be a \`Date\`, array of \`Date\`s or a function
			with the signature \`(date) => Boolean\`.
		*/
		disabledDays: any,
 
		/**
			Display a divider between each month.
		*/
		showDivider: bool,
 
		/**
			Called when user's swipe would change the month \`offset\`. Callback
			passes number of months swiped by the user (positive for forward swipes,
			negative for backwards swipes).  Signature:
			\`(monthsSwiped, { event, props }) => {}\`
		*/
		onSwipe: func,
 
		/**
			Called when user clicks the previous button.  Signature:
			\`({ event, props }) => {}\`
		*/
		onPrev: func,
 
		/**
			Called when user clicks the next button.  Signature:
			\`({ event, props }) => {}\`
		*/
		onNext: func,
 
		/**
			Called when user selects a date. Callback passes a Date object as the
			first argument.  Signature: \`(selectedDate, { event, props }) => {}\`
		*/
		onSelectDate: func,
 
		/**
			Render initial font size relative to size of the component so it scales
			with the calendar size.
		*/
		isFontSizeRelative: bool,
 
		/**
			Highlight dates and ranges based on cursor position.
		*/
		showCursorHighlight: bool,
 
		/**
			Render the calendar months in a touch-friendly slider with some being
			rendered out-of-view. Set to \`false\` to disable this feature and gain a
			performance boost.
		*/
		useSlidePanel: bool,
 
		/**
			Child component to pass thru props to underlying CalendarMonth.
		*/
		CalendarMonth: node,
	};
 
	static defaultProps = {
		monthsShown: 1,
		calendarsRendered: 6,
		offset: 0,
		from: null,
		to: null,
		initialMonth: new Date(),
		selectedDays: () => false,
		disabledDays: () => false,
		showDivider: false,
		onSwipe: _.noop,
		onPrev: _.noop,
		onNext: _.noop,
		onSelectDate: _.noop,
		isFontSizeRelative: false,
		showCursorHighlight: true,
		useSlidePanel: true,
	};
 
	static reducers = reducers;
 
	handleDayClick = (
		day: Date,
		{ disabled }: { disabled: boolean },
		event: React.MouseEvent
	): void => {
		const { onSelectDate } = this.props;
 
		if (!disabled) {
			onSelectDate(day, { event, props: this.props });
		}
	};
 
	handleDayMouseEnter = (day: Date, { disabled }: { disabled: boolean }) => {
		if (disabled) {
			this.setState({
				cursor: null,
			});
		} else {
			this.setState({
				cursor: day,
			});
		}
	};
 
	handleDayMouseLeave = () => {
		this.setState({
			cursor: null,
		});
	};
 
	handlePrev = ({ event }: { event: React.MouseEvent }) => {
		this.props.onPrev({ event, props: this.props });
	};
 
	handleNext = ({ event }: { event: React.MouseEvent }) => {
		this.props.onNext({ event, props: this.props });
	};
 
	componentDidMount = () => {
		const { isFontSizeRelative, monthsShown: monthsShownRaw } = this.props;
 
		const monthsShown = clampMonthsShown(monthsShownRaw);
 
		Iif (isFontSizeRelative && this.rootRef) {
			const rootElement = this.rootRef;
			const { width, height } = rootElement.getBoundingClientRect();
			const navButtonsWidth = NAV_BUTTON_SIZE * 2;
			const oneMonthShownWidth =
				(width - navButtonsWidth) / monthsShown + navButtonsWidth;
			const size = Math.sqrt(oneMonthShownWidth * height);
			const relativeFontSize = Math.round(size / 24);
			const relativeMinWidth =
				((((width - navButtonsWidth) / monthsShown) * 10.1075) /
					relativeFontSize) *
					monthsShown +
				navButtonsWidth;
 
			rootElement.style.fontSize = `${relativeFontSize}px`;
			rootElement.style.minWidth = `${relativeMinWidth}px`;
		}
	};
 
	renderCalendarMonth = (
		monthOffset: number,
		isRangeSameDay: boolean,
		selectedDays: (date: Date) => boolean | Date[] | Date,
		{
			key,
			initialMonth,
			cursor,
			from,
			to,
			disabledDays,
			selectMode,
			onDayClick,
			showCursorHighlight,
			onDayMouseEnter,
			onDayMouseLeave,
			...rest
		}: ICalendarProps
	) => {
		return (
			<CalendarMonth
				key={key}
				className={cx('&-CalendarMonth')}
				monthOffset={monthOffset}
				initialMonth={initialMonth}
				cursor={cursor}
				from={isRangeSameDay ? null : from}
				to={isRangeSameDay ? null : to}
				selectedDays={isRangeSameDay ? from : selectedDays}
				disabledDays={disabledDays}
				selectMode={selectMode}
				onDayClick={onDayClick}
				onDayMouseEnter={showCursorHighlight ? onDayMouseEnter : _.noop}
				onDayMouseLeave={showCursorHighlight ? onDayMouseLeave : _.noop}
				{...(rest as Partial<ICalendarProps>)}
			/>
		);
	};
 
	render() {
		const {
			className,
			monthsShown: monthsShownRaw,
			calendarsRendered,
			offset,
			from,
			to,
			selectMode,
			selectedDays,
			disabledDays,
			showDivider,
			onSwipe,
			showCursorHighlight,
			useSlidePanel,
			...passThroughs
		} = this.props;
 
		const { cursor } = this.state;
 
		//@ts-ignore
		// For some reason react-day-pickers type doesn't allow `null` values but
		// we seem to be passing them in and it seems to "work" at least in that
		// the code doesn't blow up.
		const isRangeSameDay = DateUtils.isSameDay(from, to);
 
		const calendarMonthProps = _.get(
			getFirst(this.props, DateSelect.CalendarMonth),
			'props'
		);
 
		const monthsShown = clampMonthsShown(monthsShownRaw);
 
		/* istanbul ignore next */
		return (
			<section
				ref={(ref) => (this.rootRef = ref)}
				className={cx('&', className, {
					'&-show-divider': showDivider,
				})}
				style={{
					minWidth: NAV_BUTTON_SIZE * 2 + 185 * monthsShown,
					...passThroughs.style,
				}}
				{...omit(passThroughs, nonPassThroughs)}
			>
				<div>
					<ChevronIcon
						className={cx('&-chevron')}
						size={NAV_BUTTON_SIZE}
						isClickable
						direction='left'
						onClick={this.handlePrev}
					/>
				</div>
				{useSlidePanel ? (
					<InfiniteSlidePanel
						className={cx('&-InfiniteSlidePanel', '&-slidePanel')}
						totalSlides={calendarsRendered}
						slidesToShow={monthsShown}
						offset={offset}
						onSwipe={onSwipe}
					>
						<InfiniteSlidePanel.Slide className={cx('&-slide')}>
							{(slideOffset: number) => (
								<div className={cx('&-slide-content')}>
									{this.renderCalendarMonth(
										offset + slideOffset - offset,
										isRangeSameDay,
										selectedDays,
										{
											key: slideOffset,
											initialMonth: this.initialMonth,
											cursor,
											from,
											to,
											disabledDays,
											selectMode,
											onDayClick: this.handleDayClick,
											showCursorHighlight,
											onDayMouseEnter: this.handleDayMouseEnter,
											onDayMouseLeave: this.handleDayMouseLeave,
											...calendarMonthProps,
										}
									)}
								</div>
							)}
						</InfiniteSlidePanel.Slide>
					</InfiniteSlidePanel>
				) : (
					<div className={cx('&-slidePanel', '&-slidePanel-simple')}>
						{_.times(monthsShown, (calendarIndex) => (
							<div
								className={cx('&-slide', '&-slide-simple')}
								key={calendarIndex}
							>
								<div className={cx('&-slide-content')}>
									{this.renderCalendarMonth(
										offset + calendarIndex,
										isRangeSameDay,
										selectedDays,
										{
											initialMonth: this.initialMonth,
											cursor,
											from,
											to,
											disabledDays,
											selectMode,
											onDayClick: this.handleDayClick,
											showCursorHighlight,
											onDayMouseEnter: this.handleDayMouseEnter,
											onDayMouseLeave: this.handleDayMouseLeave,
											...calendarMonthProps,
										}
									)}
								</div>
							</div>
						))}
					</div>
				)}
				<div>
					<ChevronIcon
						className={cx('&-chevron')}
						size={NAV_BUTTON_SIZE}
						isClickable
						direction='right'
						onClick={this.handleNext}
					/>
				</div>
			</section>
		);
	}
}
 
export default buildModernHybridComponent<
	IDateSelectProps,
	IDateSelectState,
	typeof DateSelect
>(DateSelect as any, { reducers });
export { DateSelect as DateSelectDumb };