react-datepicker
Version:
A simple and reusable datepicker component for React
1,202 lines (1,193 loc) • 314 kB
JavaScript
/*!
react-datepicker v9.0.0
https://github.com/Hacker0x01/react-datepicker
Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('clsx'), require('react'), require('date-fns'), require('@floating-ui/react'), require('react-dom')) :
typeof define === 'function' && define.amd ? define(['exports', 'clsx', 'react', 'date-fns', '@floating-ui/react', 'react-dom'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.DatePicker = {}, global.clsx, global.React, global.dateFns, global.FloatingUIReact, global.ReactDOM));
})(this, (function (exports, clsx, React, dateFns, react, ReactDOM) { 'use strict';
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
var React__default = /*#__PURE__*/_interopDefaultCompat(React);
var ReactDOM__default = /*#__PURE__*/_interopDefaultCompat(ReactDOM);
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var _extendStatics = function extendStatics(d, b) {
_extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return _extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
_extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var _assign = function __assign() {
_assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return _assign.apply(this, arguments);
};
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var CalendarContainer = function (_a) {
var _b = _a.showTimeSelectOnly, showTimeSelectOnly = _b === void 0 ? false : _b, _c = _a.showTime, showTime = _c === void 0 ? false : _c, className = _a.className, children = _a.children, inline = _a.inline;
var ariaLabel = showTimeSelectOnly
? "Choose Time"
: "Choose Date".concat(showTime ? " and Time" : "");
return (React__default.default.createElement("div", { className: className, "aria-label": ariaLabel, role: inline ? undefined : "dialog", "aria-modal": inline ? undefined : "true" }, children));
};
var useDetectClickOutside = function (onClickOutside, ignoreClass) {
var ref = React.useRef(null);
var onClickOutsideRef = React.useRef(onClickOutside);
React.useEffect(function () {
onClickOutsideRef.current = onClickOutside;
}, [onClickOutside]);
var handleClickOutside = React.useCallback(function (event) {
var _a;
var target = (event.composed &&
event.composedPath &&
event
.composedPath()
.find(function (eventTarget) { return eventTarget instanceof Node; })) ||
event.target;
if (ref.current && !ref.current.contains(target)) {
if (!(ignoreClass &&
target instanceof HTMLElement &&
target.classList.contains(ignoreClass))) {
(_a = onClickOutsideRef.current) === null || _a === void 0 ? void 0 : _a.call(onClickOutsideRef, event);
}
}
}, [ignoreClass]);
React.useEffect(function () {
document.addEventListener("mousedown", handleClickOutside);
return function () {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [handleClickOutside]);
return ref;
};
var ClickOutsideWrapper = function (_a) {
var children = _a.children, onClickOutside = _a.onClickOutside, className = _a.className, containerRef = _a.containerRef, style = _a.style, ignoreClass = _a.ignoreClass;
var detectRef = useDetectClickOutside(onClickOutside, ignoreClass);
return (React__default.default.createElement("div", { className: className, style: style, ref: function (node) {
detectRef.current = node;
if (containerRef) {
containerRef.current = node;
}
} }, children));
};
// Cache for the date-fns-tz module
var dateFnsTz = null;
var dateFnsTzLoadAttempted = false;
/**
* Attempts to load date-fns-tz module.
* Returns null if the module is not installed.
*/
function getDateFnsTz() {
if (dateFnsTzLoadAttempted) {
return dateFnsTz;
}
dateFnsTzLoadAttempted = true;
try {
// Dynamic require for date-fns-tz
// eslint-disable-next-line @typescript-eslint/no-require-imports
dateFnsTz = require("date-fns-tz");
}
catch (_a) {
/* istanbul ignore next - only executes when date-fns-tz is not installed */
dateFnsTz = null;
}
return dateFnsTz;
}
/**
* Converts a date to the specified timezone.
* If no timezone is specified or date-fns-tz is not installed, returns the original date.
*
* @param date - The date to convert
* @param timeZone - The IANA timezone identifier (e.g., "America/New_York", "UTC")
* @returns The date in the specified timezone
*/
function toZonedTime(date, timeZone) {
if (!timeZone) {
return date;
}
var tz = getDateFnsTz();
if (!tz) {
if (process.env.NODE_ENV !== "production") {
console.warn('react-datepicker: timeZone prop requires "date-fns-tz" package. ' +
"Please install it: npm install date-fns-tz");
}
return date;
}
return tz.toZonedTime(date, timeZone);
}
/**
* Converts a date from the specified timezone to UTC.
* If no timezone is specified or date-fns-tz is not installed, returns the original date.
*
* @param date - The date in the specified timezone
* @param timeZone - The IANA timezone identifier (e.g., "America/New_York", "UTC")
* @returns The date in UTC
*/
function fromZonedTime(date, timeZone) {
if (!timeZone) {
return date;
}
var tz = getDateFnsTz();
if (!tz) {
if (process.env.NODE_ENV !== "production") {
console.warn('react-datepicker: timeZone prop requires "date-fns-tz" package. ' +
"Please install it: npm install date-fns-tz");
}
return date;
}
return tz.fromZonedTime(date, timeZone);
}
var KeyType;
(function (KeyType) {
KeyType["ArrowUp"] = "ArrowUp";
KeyType["ArrowDown"] = "ArrowDown";
KeyType["ArrowLeft"] = "ArrowLeft";
KeyType["ArrowRight"] = "ArrowRight";
KeyType["PageUp"] = "PageUp";
KeyType["PageDown"] = "PageDown";
KeyType["Home"] = "Home";
KeyType["End"] = "End";
KeyType["Enter"] = "Enter";
KeyType["Space"] = " ";
KeyType["Tab"] = "Tab";
KeyType["Escape"] = "Escape";
KeyType["Backspace"] = "Backspace";
KeyType["X"] = "x";
})(KeyType || (KeyType = {}));
function getLocaleScope() {
// Use this cast to avoid messing with users globalThis (like window) and the rest of keys in the globalThis object we don't care about
var scope = (typeof window !== "undefined"
? window
: globalThis);
return scope;
}
var DEFAULT_YEAR_ITEM_NUMBER = 12;
// ** Date Constructors **
function newDate(value) {
if (value == null) {
return new Date();
}
var d = typeof value === "string" ? dateFns.parseISO(value) : dateFns.toDate(value);
return isValid(d) ? d : new Date();
}
/**
* Parses a date.
*
* @param value - The string representing the Date in a parsable form, e.g., ISO 1861
* @param dateFormat - The date format.
* @param locale - The locale.
* @param strictParsing - The strict parsing flag.
* @param refDate - The base date to be passed to date-fns parse() function.
* @returns - The parsed date or null.
*/
function parseDate(value, dateFormat, locale, strictParsing, refDate) {
if (refDate === void 0) { refDate = newDate(); }
var localeObject = getLocaleObject(locale) || getLocaleObject(getDefaultLocale());
var formats = Array.isArray(dateFormat) ? dateFormat : [dateFormat];
for (var _i = 0, formats_1 = formats; _i < formats_1.length; _i++) {
var format_1 = formats_1[_i];
var parsedDate = dateFns.parse(value, format_1, refDate, {
locale: localeObject,
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
if (isValid(parsedDate) &&
(!strictParsing || value === formatDate(parsedDate, format_1, locale))) {
return parsedDate;
}
}
return null;
}
/**
* Parses a partial date string for calendar navigation purposes.
* Unlike parseDate, this function attempts to extract whatever date
* information is available (year, month) from a partial input,
* returning a date suitable for navigating the calendar view.
*
* @param value - The date string to parse.
* @param refDate - The reference date to use for missing components.
* @returns - A date for navigation or null if no date info could be extracted.
*/
function parseDateForNavigation(value, refDate) {
if (refDate === void 0) { refDate = newDate(); }
if (!value)
return null;
// Try to extract a 4-digit year from the input
var yearMatch = value.match(/\b(1\d{3}|2\d{3})\b/);
if (!yearMatch || !yearMatch[1])
return null;
var year = parseInt(yearMatch[1], 10);
// Try to extract a month (1-12) from the input
// Look for patterns like "03/", "/03", "03-", "-03" or standalone "03" at start
var monthMatch = value.match(/(?:^|[/\-\s])?(0?[1-9]|1[0-2])(?:[/\-\s]|$)/);
var month = monthMatch && monthMatch[1]
? parseInt(monthMatch[1], 10) - 1
: refDate.getMonth();
// Return a date with the extracted year and month, using day 1
return new Date(year, month, 1);
}
/**
* Checks if a given date is a valid Date object.
* @param date - The date to be checked.
* @returns A boolean value indicating whether the date is valid.
*/
function isValid(date) {
return dateFns.isValid(date);
}
// ** Date Formatting **
/**
* Formats a date.
*
* @param date - The date.
* @param formatStr - The format string.
* @param locale - The locale.
* @returns - The formatted date.
*/
function formatDate(date, formatStr, locale) {
if (locale === "en") {
return dateFns.format(date, formatStr, {
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
}
var localeObj = locale ? getLocaleObject(locale) : undefined;
if (locale && !localeObj) {
console.warn("A locale object was not found for the provided string [\"".concat(locale, "\"]."));
}
localeObj = localeObj || getLocaleObject(getDefaultLocale());
return dateFns.format(date, formatStr, {
locale: localeObj,
useAdditionalWeekYearTokens: true,
useAdditionalDayOfYearTokens: true,
});
}
/**
* Safely formats a date.
*
* @param date - The date.
* @param options - An object containing the dateFormat and locale.
* @returns - The formatted date or an empty string.
*/
function safeDateFormat(date, _a) {
var dateFormat = _a.dateFormat, locale = _a.locale;
var formatStr = (Array.isArray(dateFormat) && dateFormat.length > 0
? dateFormat[0]
: dateFormat); // Cast to string because it's impossible to get `string | string[] | undefined` here and typescript doesn't know that
return (date && formatDate(date, formatStr, locale)) || "";
}
/**
* Used as a delimiter to separate two dates when formatting a date range
*/
var DATE_RANGE_SEPARATOR = " - ";
/**
* Safely formats a date range.
*
* @param startDate - The start date.
* @param endDate - The end date.
* @param props - The props.
* @returns - The formatted date range or an empty string.
*/
function safeDateRangeFormat(startDate, endDate, props) {
if (!startDate && !endDate) {
return "";
}
var formattedStartDate = startDate ? safeDateFormat(startDate, props) : "";
var formattedEndDate = endDate ? safeDateFormat(endDate, props) : "";
var dateRangeSeparator = props.rangeSeparator || DATE_RANGE_SEPARATOR;
return "".concat(formattedStartDate).concat(dateRangeSeparator).concat(formattedEndDate);
}
/**
* Safely formats multiple dates.
*
* @param dates - The dates.
* @param props - The props.
* @returns - The formatted dates or an empty string.
*/
function safeMultipleDatesFormat(dates, props) {
if (!(dates === null || dates === void 0 ? void 0 : dates.length)) {
return "";
}
var formattedFirstDate = dates[0] ? safeDateFormat(dates[0], props) : "";
if (dates.length === 1) {
return formattedFirstDate;
}
if (dates.length === 2 && dates[1]) {
var formattedSecondDate = safeDateFormat(dates[1], props);
return "".concat(formattedFirstDate, ", ").concat(formattedSecondDate);
}
var extraDatesCount = dates.length - 1;
return "".concat(formattedFirstDate, " (+").concat(extraDatesCount, ")");
}
// ** Date Setters **
/**
* Sets the time for a given date.
*
* @param date - The date.
* @param time - An object containing the hour, minute, and second.
* @returns - The date with the time set.
*/
function setTime(date, _a) {
var _b = _a.hour, hour = _b === void 0 ? 0 : _b, _c = _a.minute, minute = _c === void 0 ? 0 : _c, _d = _a.second, second = _d === void 0 ? 0 : _d;
return dateFns.setHours(dateFns.setMinutes(dateFns.setSeconds(date, second), minute), hour);
}
/**
* Gets the week of the year for a given date.
*
* @param date - The date.
* @returns - The week of the year.
*/
function getWeek(date) {
return dateFns.getISOWeek(date);
}
/**
* Gets the day of the week code for a given day.
*
* @param day - The day.
* @param locale - The locale.
* @returns - The day of the week code.
*/
function getDayOfWeekCode(day, locale) {
return formatDate(day, "ddd", locale);
}
// *** Start of ***
/**
* Gets the start of the day for a given date.
*
* @param date - The date.
* @returns - The start of the day.
*/
function getStartOfDay(date) {
return dateFns.startOfDay(date);
}
/**
* Gets the start of the week for a given date.
*
* @param date - The date.
* @param locale - The locale.
* @param calendarStartDay - The day the calendar starts on.
* @returns - The start of the week.
*/
function getStartOfWeek(date, locale, calendarStartDay) {
var localeObj = locale
? getLocaleObject(locale)
: getLocaleObject(getDefaultLocale());
return dateFns.startOfWeek(date, {
locale: localeObj,
weekStartsOn: calendarStartDay,
});
}
/**
* Gets the start of the month for a given date.
*
* @param date - The date.
* @returns - The start of the month.
*/
function getStartOfMonth(date) {
return dateFns.startOfMonth(date);
}
/**
* Gets the start of the year for a given date.
*
* @param date - The date.
* @returns - The start of the year.
*/
function getStartOfYear(date) {
return dateFns.startOfYear(date);
}
/**
* Gets the start of the quarter for a given date.
*
* @param date - The date.
* @returns - The start of the quarter.
*/
function getStartOfQuarter(date) {
return dateFns.startOfQuarter(date);
}
/**
* Gets the start of today.
*
* @returns - The start of today.
*/
function getStartOfToday() {
return dateFns.startOfDay(newDate());
}
// *** End of ***
/**
* Gets the end of the day for a given date.
*
* @param date - The date.
* @returns - The end of the day.
*/
function getEndOfDay(date) {
return dateFns.endOfDay(date);
}
/**
* Gets the end of the week for a given date.
*
* @param date - The date.
* @returns - The end of the week.
*/
function getEndOfWeek(date) {
return dateFns.endOfWeek(date);
}
/**
* Gets the end of the month for a given date.
*
* @param date - The date.
* @returns - The end of the month.
*/
function getEndOfMonth(date) {
return dateFns.endOfMonth(date);
}
/**
* Checks if two dates are in the same year.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are in the same year, false otherwise.
*/
function isSameYear(date1, date2) {
if (date1 && date2) {
return dateFns.isSameYear(date1, date2);
}
else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are in the same month.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are in the same month, false otherwise.
*/
function isSameMonth(date1, date2) {
if (date1 && date2) {
return dateFns.isSameMonth(date1, date2);
}
else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are in the same quarter.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are in the same quarter, false otherwise.
*/
function isSameQuarter(date1, date2) {
if (date1 && date2) {
return dateFns.isSameQuarter(date1, date2);
}
else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are on the same day.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are on the same day, false otherwise.
*/
function isSameDay(date1, date2) {
if (date1 && date2) {
return dateFns.isSameDay(date1, date2);
}
else {
return !date1 && !date2;
}
}
/**
* Checks if two dates are equal.
*
* @param date1 - The first date.
* @param date2 - The second date.
* @returns - True if the dates are equal, false otherwise.
*/
function isEqual(date1, date2) {
if (date1 && date2) {
return dateFns.isEqual(date1, date2);
}
else {
return !date1 && !date2;
}
}
/**
* Checks if a day is within a date range.
*
* @param day - The day to check.
* @param startDate - The start date of the range.
* @param endDate - The end date of the range.
* @returns - True if the day is within the range, false otherwise.
*/
function isDayInRange(day, startDate, endDate) {
var valid;
var start = dateFns.startOfDay(startDate);
var end = dateFns.endOfDay(endDate);
try {
valid = dateFns.isWithinInterval(day, { start: start, end: end });
}
catch (err) {
valid = false;
}
return valid;
}
// ** Date Localization **
/**
* Registers a locale.
*
* @param localeName - The name of the locale.
* @param localeData - The data of the locale.
*/
function registerLocale(localeName, localeData) {
var scope = getLocaleScope();
if (!scope.__localeData__) {
scope.__localeData__ = {};
}
scope.__localeData__[localeName] = localeData;
}
/**
* Sets the default locale.
*
* @param localeName - The name of the locale.
*/
function setDefaultLocale(localeName) {
var scope = getLocaleScope();
scope.__localeId__ = localeName;
}
/**
* Gets the default locale.
*
* @returns - The default locale.
*/
function getDefaultLocale() {
var scope = getLocaleScope();
return scope.__localeId__;
}
/**
* Gets the locale object.
*
* @param localeSpec - The locale specification.
* @returns - The locale object.
*/
function getLocaleObject(localeSpec) {
if (typeof localeSpec === "string") {
// Treat it as a locale name registered by registerLocale
var scope = getLocaleScope();
// Null was replaced with undefined to avoid type coercion
return scope.__localeData__ ? scope.__localeData__[localeSpec] : undefined;
}
else {
// Treat it as a raw date-fns locale object
return localeSpec;
}
}
/**
* Formats the weekday in a given locale.
*
* @param date - The date to format.
* @param formatFunc - The formatting function.
* @param locale - The locale to use for formatting.
* @returns - The formatted weekday.
*/
function getFormattedWeekdayInLocale(date, formatFunc, locale) {
return formatFunc(formatDate(date, "EEEE", locale));
}
/**
* Gets the minimum weekday in a given locale.
*
* @param date - The date to format.
* @param locale - The locale to use for formatting.
* @returns - The minimum weekday.
*/
function getWeekdayMinInLocale(date, locale) {
return formatDate(date, "EEEEEE", locale);
}
/**
* Gets the short weekday in a given locale.
*
* @param date - The date to format.
* @param locale - The locale to use for formatting.
* @returns - The short weekday.
*/
function getWeekdayShortInLocale(date, locale) {
return formatDate(date, "EEE", locale);
}
/**
* Gets the month in a given locale.
*
* @param month - The month to format.
* @param locale - The locale to use for formatting.
* @returns - The month.
*/
function getMonthInLocale(month, locale) {
return formatDate(dateFns.setMonth(newDate(), month), "LLLL", locale);
}
/**
* Gets the short month in a given locale.
*
* @param month - The month to format.
* @param locale - The locale to use for formatting.
* @returns - The short month.
*/
function getMonthShortInLocale(month, locale) {
return formatDate(dateFns.setMonth(newDate(), month), "LLL", locale);
}
/**
* Gets the short quarter in a given locale.
*
* @param quarter - The quarter to format.
* @param locale - The locale to use for formatting.
* @returns - The short quarter.
*/
function getQuarterShortInLocale(quarter, locale) {
return formatDate(dateFns.setQuarter(newDate(), quarter), "QQQ", locale);
}
/**
* Checks if a day is disabled.
*
* @param day - The day to check.
* @param options - The options to consider when checking.
* @returns - Returns true if the day is disabled, false otherwise.
*/
function isDayDisabled(day, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, maxDate = _b.maxDate, excludeDates = _b.excludeDates, excludeDateIntervals = _b.excludeDateIntervals, includeDates = _b.includeDates, includeDateIntervals = _b.includeDateIntervals, filterDate = _b.filterDate, disabled = _b.disabled;
if (disabled) {
return true;
}
return (isOutOfBounds(day, { minDate: minDate, maxDate: maxDate }) ||
(excludeDates &&
excludeDates.some(function (excludeDate) {
if (excludeDate instanceof Date) {
return isSameDay(day, excludeDate);
}
else {
return isSameDay(day, excludeDate.date);
}
})) ||
(excludeDateIntervals &&
excludeDateIntervals.some(function (_a) {
var start = _a.start, end = _a.end;
return dateFns.isWithinInterval(day, { start: start, end: end });
})) ||
(includeDates &&
!includeDates.some(function (includeDate) { return isSameDay(day, includeDate); })) ||
(includeDateIntervals &&
!includeDateIntervals.some(function (_a) {
var start = _a.start, end = _a.end;
return dateFns.isWithinInterval(day, { start: start, end: end });
})) ||
(filterDate && !filterDate(newDate(day))) ||
false);
}
/**
* Checks if a day is excluded.
*
* @param day - The day to check.
* @param options - The options to consider when checking.
* @returns - Returns true if the day is excluded, false otherwise.
*/
function isDayExcluded(day, _a) {
var _b = _a === void 0 ? {} : _a, excludeDates = _b.excludeDates, excludeDateIntervals = _b.excludeDateIntervals;
if (excludeDateIntervals && excludeDateIntervals.length > 0) {
return excludeDateIntervals.some(function (_a) {
var start = _a.start, end = _a.end;
return dateFns.isWithinInterval(day, { start: start, end: end });
});
}
return ((excludeDates &&
excludeDates.some(function (excludeDate) {
var _a;
if (excludeDate instanceof Date) {
return isSameDay(day, excludeDate);
}
else {
return isSameDay(day, (_a = excludeDate.date) !== null && _a !== void 0 ? _a : new Date());
}
})) ||
false);
}
function isMonthDisabled(month, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, maxDate = _b.maxDate, excludeDates = _b.excludeDates, includeDates = _b.includeDates, filterDate = _b.filterDate;
return (isOutOfBounds(month, {
minDate: minDate ? dateFns.startOfMonth(minDate) : undefined,
maxDate: maxDate ? dateFns.endOfMonth(maxDate) : undefined,
}) ||
(excludeDates === null || excludeDates === void 0 ? void 0 : excludeDates.some(function (excludeDate) {
return isSameMonth(month, excludeDate instanceof Date ? excludeDate : excludeDate.date);
})) ||
(includeDates &&
!includeDates.some(function (includeDate) { return isSameMonth(month, includeDate); })) ||
(filterDate && !filterDate(newDate(month))) ||
false);
}
function isMonthInRange(startDate, endDate, m, day) {
var startDateYear = dateFns.getYear(startDate);
var startDateMonth = dateFns.getMonth(startDate);
var endDateYear = dateFns.getYear(endDate);
var endDateMonth = dateFns.getMonth(endDate);
var dayYear = dateFns.getYear(day);
if (startDateYear === endDateYear && startDateYear === dayYear) {
return startDateMonth <= m && m <= endDateMonth;
}
else if (startDateYear < endDateYear) {
return ((dayYear === startDateYear && startDateMonth <= m) ||
(dayYear === endDateYear && endDateMonth >= m) ||
(dayYear < endDateYear && dayYear > startDateYear));
}
return false;
}
/**
* To check if a date's month and year are disabled/excluded
* @param date Date to check
* @returns {boolean} true if month and year are disabled/excluded, false otherwise
*/
function isMonthYearDisabled(date, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, maxDate = _b.maxDate, excludeDates = _b.excludeDates, includeDates = _b.includeDates;
return (isOutOfBounds(date, { minDate: minDate, maxDate: maxDate }) ||
(excludeDates &&
excludeDates.some(function (excludedDate) {
return isSameMonth(excludedDate instanceof Date ? excludedDate : excludedDate.date, date);
})) ||
(includeDates &&
!includeDates.some(function (includedDate) { return isSameMonth(includedDate, date); })) ||
false);
}
function isQuarterDisabled(quarter, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, maxDate = _b.maxDate, excludeDates = _b.excludeDates, includeDates = _b.includeDates, filterDate = _b.filterDate, disabled = _b.disabled;
if (disabled) {
return true;
}
return (isOutOfBounds(quarter, { minDate: minDate, maxDate: maxDate }) ||
(excludeDates === null || excludeDates === void 0 ? void 0 : excludeDates.some(function (excludeDate) {
return isSameQuarter(quarter, excludeDate instanceof Date ? excludeDate : excludeDate.date);
})) ||
(includeDates &&
!includeDates.some(function (includeDate) {
return isSameQuarter(quarter, includeDate);
})) ||
(filterDate && !filterDate(newDate(quarter))) ||
false);
}
function isYearInRange(year, start, end) {
if (!start || !end)
return false;
if (!dateFns.isValid(start) || !dateFns.isValid(end))
return false;
var startYear = dateFns.getYear(start);
var endYear = dateFns.getYear(end);
return startYear <= year && endYear >= year;
}
function isYearDisabled(year, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, maxDate = _b.maxDate, excludeDates = _b.excludeDates, includeDates = _b.includeDates, filterDate = _b.filterDate, disabled = _b.disabled;
if (disabled) {
return true;
}
var date = new Date(year, 0, 1);
return (isOutOfBounds(date, {
minDate: minDate ? dateFns.startOfYear(minDate) : undefined,
maxDate: maxDate ? dateFns.endOfYear(maxDate) : undefined,
}) ||
(excludeDates === null || excludeDates === void 0 ? void 0 : excludeDates.some(function (excludeDate) {
return isSameYear(date, excludeDate instanceof Date ? excludeDate : excludeDate.date);
})) ||
(includeDates &&
!includeDates.some(function (includeDate) { return isSameYear(date, includeDate); })) ||
(filterDate && !filterDate(newDate(date))) ||
false);
}
function isQuarterInRange(startDate, endDate, q, day) {
var startDateYear = dateFns.getYear(startDate);
var startDateQuarter = dateFns.getQuarter(startDate);
var endDateYear = dateFns.getYear(endDate);
var endDateQuarter = dateFns.getQuarter(endDate);
var dayYear = dateFns.getYear(day);
if (startDateYear === endDateYear && startDateYear === dayYear) {
return startDateQuarter <= q && q <= endDateQuarter;
}
else if (startDateYear < endDateYear) {
return ((dayYear === startDateYear && startDateQuarter <= q) ||
(dayYear === endDateYear && endDateQuarter >= q) ||
(dayYear < endDateYear && dayYear > startDateYear));
}
return false;
}
function isOutOfBounds(day, _a) {
var _b;
var _c = _a === void 0 ? {} : _a, minDate = _c.minDate, maxDate = _c.maxDate;
return ((_b = ((minDate && dateFns.differenceInCalendarDays(day, minDate) < 0) ||
(maxDate && dateFns.differenceInCalendarDays(day, maxDate) > 0))) !== null && _b !== void 0 ? _b : false);
}
function isTimeInList(time, times) {
return times.some(function (listTime) {
return dateFns.getHours(listTime) === dateFns.getHours(time) &&
dateFns.getMinutes(listTime) === dateFns.getMinutes(time) &&
dateFns.getSeconds(listTime) === dateFns.getSeconds(time);
});
}
function isTimeDisabled(time, _a) {
var _b = _a === void 0 ? {} : _a, excludeTimes = _b.excludeTimes, includeTimes = _b.includeTimes, filterTime = _b.filterTime;
return ((excludeTimes && isTimeInList(time, excludeTimes)) ||
(includeTimes && !isTimeInList(time, includeTimes)) ||
(filterTime && !filterTime(time)) ||
false);
}
function isTimeInDisabledRange(time, _a) {
var minTime = _a.minTime, maxTime = _a.maxTime;
if (!minTime || !maxTime) {
throw new Error("Both minTime and maxTime props required");
}
var baseTime = newDate();
baseTime = dateFns.setHours(baseTime, dateFns.getHours(time));
baseTime = dateFns.setMinutes(baseTime, dateFns.getMinutes(time));
baseTime = dateFns.setSeconds(baseTime, dateFns.getSeconds(time));
var min = newDate();
min = dateFns.setHours(min, dateFns.getHours(minTime));
min = dateFns.setMinutes(min, dateFns.getMinutes(minTime));
min = dateFns.setSeconds(min, dateFns.getSeconds(minTime));
var max = newDate();
max = dateFns.setHours(max, dateFns.getHours(maxTime));
max = dateFns.setMinutes(max, dateFns.getMinutes(maxTime));
max = dateFns.setSeconds(max, dateFns.getSeconds(maxTime));
var valid;
try {
valid = !dateFns.isWithinInterval(baseTime, { start: min, end: max });
}
catch (err) {
/* istanbul ignore next - date-fns historically threw on invalid intervals */
valid = false;
}
return valid;
}
function monthDisabledBefore(day, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, includeDates = _b.includeDates;
var previousMonth = dateFns.subMonths(day, 1);
return ((minDate && dateFns.differenceInCalendarMonths(minDate, previousMonth) > 0) ||
(includeDates &&
includeDates.every(function (includeDate) {
return dateFns.differenceInCalendarMonths(includeDate, previousMonth) > 0;
})) ||
false);
}
function monthDisabledAfter(day, _a) {
var _b = _a === void 0 ? {} : _a, maxDate = _b.maxDate, includeDates = _b.includeDates;
var nextMonth = dateFns.addMonths(day, 1);
return ((maxDate && dateFns.differenceInCalendarMonths(nextMonth, maxDate) > 0) ||
(includeDates &&
includeDates.every(function (includeDate) { return dateFns.differenceInCalendarMonths(nextMonth, includeDate) > 0; })) ||
false);
}
function quarterDisabledBefore(date, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, includeDates = _b.includeDates;
var firstDateOfYear = dateFns.startOfYear(date);
var previousQuarter = dateFns.subQuarters(firstDateOfYear, 1);
return ((minDate && dateFns.differenceInCalendarQuarters(minDate, previousQuarter) > 0) ||
(includeDates &&
includeDates.every(function (includeDate) {
return dateFns.differenceInCalendarQuarters(includeDate, previousQuarter) > 0;
})) ||
false);
}
function quarterDisabledAfter(date, _a) {
var _b = _a === void 0 ? {} : _a, maxDate = _b.maxDate, includeDates = _b.includeDates;
var lastDateOfYear = dateFns.endOfYear(date);
var nextQuarter = dateFns.addQuarters(lastDateOfYear, 1);
return ((maxDate && dateFns.differenceInCalendarQuarters(nextQuarter, maxDate) > 0) ||
(includeDates &&
includeDates.every(function (includeDate) {
return dateFns.differenceInCalendarQuarters(nextQuarter, includeDate) > 0;
})) ||
false);
}
function yearDisabledBefore(day, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, includeDates = _b.includeDates;
var previousYear = dateFns.subYears(day, 1);
return ((minDate && dateFns.differenceInCalendarYears(minDate, previousYear) > 0) ||
(includeDates &&
includeDates.every(function (includeDate) {
return dateFns.differenceInCalendarYears(includeDate, previousYear) > 0;
})) ||
false);
}
function yearsDisabledBefore(day, _a) {
var _b = _a === void 0 ? {} : _a, minDate = _b.minDate, _c = _b.yearItemNumber, yearItemNumber = _c === void 0 ? DEFAULT_YEAR_ITEM_NUMBER : _c;
var previousYear = getStartOfYear(dateFns.subYears(day, yearItemNumber));
var endPeriod = getYearsPeriod(previousYear, yearItemNumber).endPeriod;
var minDateYear = minDate && dateFns.getYear(minDate);
return (minDateYear && minDateYear > endPeriod) || false;
}
function yearDisabledAfter(day, _a) {
var _b = _a === void 0 ? {} : _a, maxDate = _b.maxDate, includeDates = _b.includeDates;
var nextYear = dateFns.addYears(day, 1);
return ((maxDate && dateFns.differenceInCalendarYears(nextYear, maxDate) > 0) ||
(includeDates &&
includeDates.every(function (includeDate) { return dateFns.differenceInCalendarYears(nextYear, includeDate) > 0; })) ||
false);
}
function yearsDisabledAfter(day, _a) {
var _b = _a === void 0 ? {} : _a, maxDate = _b.maxDate, _c = _b.yearItemNumber, yearItemNumber = _c === void 0 ? DEFAULT_YEAR_ITEM_NUMBER : _c;
var nextYear = dateFns.addYears(day, yearItemNumber);
var startPeriod = getYearsPeriod(nextYear, yearItemNumber).startPeriod;
var maxDateYear = maxDate && dateFns.getYear(maxDate);
return (maxDateYear && maxDateYear < startPeriod) || false;
}
function getEffectiveMinDate(_a) {
var minDate = _a.minDate, includeDates = _a.includeDates;
if (includeDates && minDate) {
var minDates = includeDates.filter(function (includeDate) { return dateFns.differenceInCalendarDays(includeDate, minDate) >= 0; });
return dateFns.min(minDates);
}
else if (includeDates) {
return dateFns.min(includeDates);
}
else {
return minDate;
}
}
function getEffectiveMaxDate(_a) {
var maxDate = _a.maxDate, includeDates = _a.includeDates;
if (includeDates && maxDate) {
var maxDates = includeDates.filter(function (includeDate) { return dateFns.differenceInCalendarDays(includeDate, maxDate) <= 0; });
return dateFns.max(maxDates);
}
else if (includeDates) {
return dateFns.max(includeDates);
}
else {
return maxDate;
}
}
/**
* Get a map of highlighted dates with their corresponding classes.
* @param highlightDates The dates to highlight.
* @param defaultClassName The default class to use for highlighting.
* @returns A map with dates as keys and arrays of class names as values.
*/
function getHighLightDaysMap(highlightDates, defaultClassName) {
var _a;
if (highlightDates === void 0) { highlightDates = []; }
if (defaultClassName === void 0) { defaultClassName = "react-datepicker__day--highlighted"; }
var dateClasses = new Map();
for (var i = 0, len = highlightDates.length; i < len; i++) {
var obj = highlightDates[i];
if (dateFns.isDate(obj)) {
var key = formatDate(obj, "MM.dd.yyyy");
var classNamesArr = dateClasses.get(key) || [];
if (!classNamesArr.includes(defaultClassName)) {
classNamesArr.push(defaultClassName);
dateClasses.set(key, classNamesArr);
}
}
else if (typeof obj === "object") {
var keys = Object.keys(obj);
var className = (_a = keys[0]) !== null && _a !== void 0 ? _a : "";
var arrOfDates = obj[className];
if (typeof className === "string" && Array.isArray(arrOfDates)) {
for (var k = 0, len_1 = arrOfDates.length; k < len_1; k++) {
var dateK = arrOfDates[k];
if (dateK) {
var key = formatDate(dateK, "MM.dd.yyyy");
var classNamesArr = dateClasses.get(key) || [];
if (!classNamesArr.includes(className)) {
classNamesArr.push(className);
dateClasses.set(key, classNamesArr);
}
}
}
}
}
}
return dateClasses;
}
/**
* Compare the two arrays
* @param array1 The first array to compare.
* @param array2 The second array to compare.
* @returns true, if the passed arrays are equal, false otherwise.
*/
function arraysAreEqual(array1, array2) {
if (array1.length !== array2.length) {
return false;
}
return array1.every(function (value, index) { return value === array2[index]; });
}
/**
* Assign the custom class to each date
* @param holidayDates array of object containing date and name of the holiday
* @param defaultClassName className to be added.
* @returns Map containing date as key and array of className and holiday name as value
*/
function getHolidaysMap(holidayDates, defaultClassName) {
if (holidayDates === void 0) { holidayDates = []; }
if (defaultClassName === void 0) { defaultClassName = "react-datepicker__day--holidays"; }
var dateClasses = new Map();
holidayDates.forEach(function (holiday) {
var dateObj = holiday.date, holidayName = holiday.holidayName;
if (!dateFns.isDate(dateObj)) {
return;
}
var key = formatDate(dateObj, "MM.dd.yyyy");
var classNamesObj = dateClasses.get(key) || {
className: "",
holidayNames: [],
};
if ("className" in classNamesObj &&
classNamesObj["className"] === defaultClassName &&
arraysAreEqual(classNamesObj["holidayNames"], [holidayName])) {
return;
}
classNamesObj["className"] = defaultClassName;
var holidayNameArr = classNamesObj["holidayNames"];
classNamesObj["holidayNames"] = holidayNameArr
? __spreadArray(__spreadArray([], holidayNameArr, true), [holidayName], false) : [holidayName];
dateClasses.set(key, classNamesObj);
});
return dateClasses;
}
/**
* Determines the times to inject after a given start of day, current time, and multiplier.
* @param startOfDay The start of the day.
* @param currentTime The current time.
* @param currentMultiplier The current multiplier.
* @param intervals The intervals.
* @param injectedTimes The times to potentially inject.
* @returns An array of times to inject.
*/
function timesToInjectAfter(startOfDay, currentTime, currentMultiplier, intervals, injectedTimes) {
var l = injectedTimes.length;
var times = [];
for (var i = 0; i < l; i++) {
var injectedTime = startOfDay;
var injectedTimeValue = injectedTimes[i];
if (injectedTimeValue) {
injectedTime = dateFns.addHours(injectedTime, dateFns.getHours(injectedTimeValue));
injectedTime = dateFns.addMinutes(injectedTime, dateFns.getMinutes(injectedTimeValue));
injectedTime = dateFns.addSeconds(injectedTime, dateFns.getSeconds(injectedTimeValue));
}
var nextTime = dateFns.addMinutes(startOfDay, (currentMultiplier + 1) * intervals);
if (dateFns.isAfter(injectedTime, currentTime) &&
dateFns.isBefore(injectedTime, nextTime) &&
injectedTimeValue != undefined) {
times.push(injectedTimeValue);
}
}
return times;
}
/**
* Adds a leading zero to a number if it's less than 10.
* @param i The number to add a leading zero to.
* @returns The number as a string, with a leading zero if it was less than 10.
*/
function addZero(i) {
return i < 10 ? "0".concat(i) : "".concat(i);
}
/**
* Gets the start and end years for a period.
* @param date The date to get the period for.
* @param yearItemNumber The number of years in the period. Defaults to DEFAULT_YEAR_ITEM_NUMBER.
* @returns An object with the start and end years for the period.
*/
function getYearsPeriod(date, yearItemNumber) {
if (yearItemNumber === void 0) { yearItemNumber = DEFAULT_YEAR_ITEM_NUMBER; }
var endPeriod = Math.ceil(dateFns.getYear(date) / yearItemNumber) * yearItemNumber;
var startPeriod = endPeriod - (yearItemNumber - 1);
return { startPeriod: startPeriod, endPeriod: endPeriod };
}
/**
* Gets the number of hours in a day.
* @param d The date to get the number of hours for.
* @returns The number of hours in the day.
*/
function getHoursInDay(d) {
var startOfDay = new Date(d.getFullYear(), d.getMonth(), d.getDate());
var startOfTheNextDay = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 24);
return Math.round((+startOfTheNextDay - +startOfDay) / 3600000);
}
/**
* Returns the start of the minute for the given date
*
* NOTE: this function is a DST and timezone-safe analog of `date-fns/startOfMinute`
* do not make changes unless you know what you're doing
*
* See comments on https://github.com/Hacker0x01/react-datepicker/pull/4244
* for more details
*
* @param d date
* @returns start of the minute
*/
function startOfMinute(d) {
var seconds = d.getSeconds();
var milliseconds = d.getMilliseconds();
return dateFns.toDate(d.getTime() - seconds * 1000 - milliseconds);
}
/**
* Returns whether the given dates are in the same minute
*
* This function is a DST and timezone-safe analog of `date-fns/isSameMinute`
*
* @param d1
* @param d2
* @returns
*/
function isSameMinute(d1, d2) {
return startOfMinute(d1).getTime() === startOfMinute(d2).getTime();
}
/**
* Returns a new datetime object representing the input date with midnight time
* @param date The date to get the midnight time for
* @returns A new datetime object representing the input date with midnight time
*/
function getMidnightDate(date) {
if (!dateFns.isDate(date)) {
throw new Error("Invalid date");
}
var dateWithoutTime = new Date(date);
dateWithoutTime.setHours(0, 0, 0, 0);
return dateWithoutTime;
}
/**
* Is the first date before the