UNPKG

react-datepicker

Version:

A simple and reusable datepicker component for React

1,306 lines (1,293 loc) 535 kB
/*! react-datepicker v8.2.1 https://github.com/Hacker0x01/react-datepicker Released under the MIT License. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var clsx = require('clsx'); var React = require('react'); var dateFns = require('date-fns'); var react = require('@floating-ui/react'); var ReactDOM = require('react-dom'); 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; var ariaLabel = showTimeSelectOnly ? "Choose Time" : "Choose Date".concat(showTime ? " and Time" : ""); return (React__default.default.createElement("div", { className: className, role: "dialog", "aria-label": ariaLabel, "aria-modal": "true" }, children)); }; var useDetectClickOutside = function (onClickOutside, ignoreClass) { var ref = React.useRef(null); var onClickOutsideRef = React.useRef(onClickOutside); onClickOutsideRef.current = 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)); }; 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; } /** * Checks if a given date is valid and not before the minimum date. * @param date - The date to be checked. * @param minDate - The minimum date allowed. If not provided, defaults to "1/1/1800". * @returns A boolean value indicating whether the date is valid and not before the minimum date. */ function isValid(date, minDate) { /* the fallback date is essential to not break test case * `should auto update calendar when the updated date text is after props.minDate` * and backward compatibility respectfully */ return dateFns.isValid(date) && !dateFns.isBefore(date, new Date("1/1/1800")); } // ** 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)) || ""; } /** * 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) { return ""; } var formattedStartDate = safeDateFormat(startDate, props); var formattedEndDate = endDate ? safeDateFormat(endDate, props) : ""; return "".concat(formattedStartDate, " - ").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; 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; 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; 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) { 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 second one? * @param date The date that should be before the other one to return true * @param dateToCompare The date to compare with * @returns The first date is before the second date * * Note: * This function considers the mid-night of the given dates for comparison. * It evaluates whether date is before dateToCompare based on their mid-night timestamps. */ function isDateBefore(date, dateToCompare) { if (!dateFns.isDate(date) || !dateFns.isDate(dateToCompare)) { throw new Error("Invalid date received"); } var midnightDate = getMidnightDate(date); var midnightDateToCompare = getMidnightDate(dateToCompare); return dateFns.isBefore(midnightDate, midnightDateToCompare); } /** * Checks if the space key was pressed down. * * @param event - The keyboard event. * @returns - Returns true if the space key was pressed down, false otherwise. */ function isSpaceKeyDown(event) { return event.key === KeyType.Space; } /** * `InputTime` is a React component that manages time input. * * @component * @example * <InputTime timeString="12:00" /> * * @param props - The properties that define the `InputTime` component. * @param props.onChange - Function that is called when the date changes. * @param props.date - The initial date value. * @param props.timeString - The initial time string value. * @param props.timeInputLabel - The label for the time input. * @param props.customTimeInput - An optional custom time input element. * * @returns The `InputTime` component. */ var InputTime = /** @class */ (function (_super) { __extends(InputTime, _super); function InputTime(props) { var _this = _super.call(this, props) || this; _this.inputRef = React__default.default.createRef(); _this.onTimeChange = function (time) { var _a, _b; _this.setState({ time: time }); var propDate = _this.props.date; var isPropDateValid = propDate instanceof Date && !isNaN(+propDate); var date = isPropDateValid ? propDate : new Date(); if (time === null || time === void 0 ? void 0 : time.includes(":")) { var _c = time.split(":"), hours = _c[0], minutes = _c[1]; date.setHours(Number(hours)); date.setMinutes(Number(minutes)); } (_b = (_a = _this.props).onChange) === null || _b === void 0 ? void 0 : _b.call(_a, date); }; _this.renderTimeInput = function () { var time = _this.state.time; var _a = _this.props, date = _a.date, timeString = _a.timeString, customTimeInput = _a.customTimeInput; if (customTimeInput) { return React.cloneElement(customTimeInput, { date: date, value: time, onChange: _this.onTimeChange, }); } return (React__default.default.createElement("input", { type: "time", className: "react-datepicker-time__input", placeholder: "Time", name: "time-input", ref: _this.inputRef, onClick: function () { var _a; (_a = _this.inputRef.current) === null || _a === void 0 ? void 0 : _a.focus(); }, required: true, value: time, onChange: function (event) { _this.onTimeChange(event.target.value || timeString); } })); }; _this.state = { time: _this.props.timeString, }; return _this; } InputTime.getDerivedStateFromProps = function (props, state) { if (props.timeString !== state.time) { return { time: props.timeString, }; } // Return null to indicate no change to state. return null; }; InputTime.prototype.render = function () { return (React__default.default.createElement("div", { className: "react-datepicker__input-time-container" }, React__default.default.createElement("div", { className: "react-datepicker-time__caption" }, this.props.timeInputLabel), React__default.default.createElement("div", { className: "react-datepicker-time__input-container" }, React__default.default.createElement("div", { className: "react-datepicker-time__input" }, this.renderTimeInput())))); }; return InputTime; }(React.Component)); /** * `Day` is a React component that represents a single day in a date picker. * It handles the rendering and interaction of a day. * * @prop ariaLabelPrefixWhenEnabled - Aria label prefix when the day is enabled. * @prop ariaLabelPrefixWhenDisabled - Aria label prefix when the day is disabled. * @prop disabledKeyboardNavigation - Whether keyboard navigation is disabled. * @prop day - The day to be displayed. * @prop dayClassName - Function to customize the CSS class of the day. * @prop endDate - The end date in a range. * @prop highlightDates - Map of dates to be highlighted. * @prop holidays - Map of holiday dates. * @prop inline - Whether the date picker is inline. * @prop shouldFocusDayInline - Whether the day should be focused when date picker is inline. * @prop month - The month the day belongs to. * @prop onClick - Click event handler. * @prop onMouseEnter - Mouse enter event handler. * @prop handleOnKeyDown - Key down event handler. * @prop usePointerEvent - Whether to use pointer events. * @prop preSelection - The date that is currently selected. * @prop selected - The selected date. * @prop selectingDate - The date currently being selected. * @prop selectsEnd - Whether the day can be the end date in a range. * @prop selectsStart - Whether the day can be the start date in a range. * @prop selectsRange - Whether the day can be in a range. * @prop showWeekPicker - Whether to show week picker. * @prop showWeekNumber - Whether to show week numbers. * @prop selectsDisabledDaysInRange - Whether to select disabled days in a range. * @prop selectsMultiple - Whether to allow multiple date selection. * @prop selectedDates - Array of selected dates. * @prop startDate - The start date in a range. * @prop renderDayContents - Function to customize the rendering of the day's contents. * @prop containerRef - Ref for the container. * @prop excludeDates - Array of dates to be excluded. * @prop calendarStartDay - The start day of the week. * @prop locale - The locale object. * @prop monthShowsDuplicateDaysEnd - Whether to show duplicate days at the end of the month. * @prop monthShowsDuplicateDaysStart - Whether to show duplicate days at the start of the month. * @prop includeDates - Array of dates to be included. * @prop includeDateIntervals - Array of date intervals to be included. * @prop minDate - The minimum date that can be selected. * @prop maxDate - The maximum date that can be selected. * * @example * ```tsx * import React from 'react'; * import Day from './day'; * * function MyComponent() { * const handleDayClick = (event) => { * console.log('Day clicked', event); * }; * * const handleDayMouseEnter = (event) => { * console.log('Mouse entered day', event); * }; * * const renderDayContents = (date) => { * return <div>{date.getDate()}</div>; * }; * * return ( * <Day * day={new Date()} * onClick={handleDayClick} * onMouseEnter={handleDayMouseEnter} * renderDayContents={renderDayContents} * /> * ); * } * * export default MyComponent; * ``` */ var Day = /** @class */ (function (_super) { __extends(Day, _super); function Day() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.dayEl = React.createRef(); _this.handleClick = function (event) { if (!_this.isDisabled() && _this.props.onClick) { _this.props.onClick(event); } }; _this.handleMouseEnter = function (event) { if (!_this.isDisabled() && _this.props.onMouseEnter) { _this.props.onMouseEnter(event); } }; _this.handleOnKeyDown = function (event) { var _a, _b; var eventKey = event.key; if (eventKey === KeyType.Space) { event.preventDefault(); event.key = KeyType.Enter; } (_b = (_a = _this.props).handleOnKeyDown) === null || _b === void 0 ? void 0 : _b.call(_a, event); }; _this.isSameDay = function (other) { return isSameDay(_this.props.day, other); }; _this.isKeyboardSelected = function () { var _a; if (_this.props.disabledKeyboardNavigation) { return false; } var