UNPKG

react-nepali-datepicker-bs

Version:

Nepali Datepicker (Bikram Sambat) as a ReactJS component

1,163 lines (1,134 loc) 42.6 kB
import React, { createContext, useReducer, useContext, useState, useMemo, useCallback, useEffect, Fragment, useRef, useLayoutEffect } from 'react'; import { BSToAD, ADToBS } from 'bikram-sambat-js'; export * from 'bikram-sambat-js'; import { nepaliToEnglishNumber, englishToNepaliNumber } from 'nepali-number'; function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } var CalenderConfig = { maxBSYear: 2099, minBSYear: 1970, outputSeparator: "-" }; var months = { en: ["Baisakh", "Jestha", "Asar", "Shrawan", "Bhadra", "Asoj", "Kartik", "Mangsir", "Pouse", "Magh", "Falgun", "Chaitra"], ne: ["बैशाख", "जेठ", "असार", "सावन", "भदौ", "असोज", "कार्तिक", "मंसिर", "पौष", "माघ", "फागुन", "चैत"] }; var weekDaysLabel = { sm: { en: ["S", "M", "T", "W", "T", "F", "S"], ne: ["आ", "सो", "मं", "बु", "बि", "शु", "श"] }, md: { en: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], ne: ["आईत", "सोम", "मंगल", "बुध", "बिही", "शुक्र", "शनि"] }, lg: { en: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], ne: ["आईतबार", "सोमबार", "मंगलबार", "बुधबार", "बिहीबार", "शुक्रबार", "शनिबार"] } }; var minBSYear = CalenderConfig.minBSYear; var bsMonthMaxDays = [[30, 31], [31, 32], [31, 32], [31, 32], [31, 32], [30, 31], [29, 30], [29, 30], [29, 30], [29, 30], [29, 30], [30, 31]]; var bsMonthCalculatedData = [[0, 1, 1, 22, 1, 3, 1, 1, 1, 3, 1, 22, 1, 3, 1, 3, 1, 22, 1, 3, 1, 19, 1, 3, 1, 1, 3, 1, 2, 2, 1, 3, 1], [1, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 2, 2, 2, 3, 2, 2, 2, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 1, 3, 1, 1, 2], [0, 1, 2, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 3, 1, 1, 2], [1, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 2, 2, 1, 3, 1, 2, 2, 2, 1, 2], [59, 1, 26, 1, 28, 1, 2, 1, 12], [0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 1, 1, 2, 2, 1, 3, 1, 2, 1, 2], [0, 12, 1, 3, 1, 3, 1, 5, 1, 11, 1, 3, 1, 3, 1, 18, 1, 3, 1, 3, 1, 18, 1, 3, 1, 3, 1, 27, 1, 2], [1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 3, 1, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 15, 2, 4], [0, 1, 2, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 3, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 2, 2, 2, 15, 2, 4], [1, 1, 3, 1, 3, 1, 14, 1, 3, 1, 1, 1, 3, 1, 14, 1, 3, 1, 3, 1, 3, 1, 18, 1, 3, 1, 3, 1, 3, 1, 14, 1, 3, 15, 1, 2, 1, 1], [0, 1, 1, 3, 1, 3, 1, 10, 1, 3, 1, 3, 1, 1, 1, 3, 1, 3, 1, 10, 1, 3, 1, 3, 1, 3, 1, 3, 1, 14, 1, 3, 1, 3, 1, 3, 1, 3, 1, 10, 1, 20, 1, 1, 1], [1, 2, 2, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 3, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 3, 1, 3, 1, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 3, 1, 20, 3]]; var ENGLISH = "en"; var NEPALI = "ne"; var BS = "BS"; var AD = "AD"; var parsedDateInitialValue = { adDate: new Date(), bsDay: 0, bsMonth: 0, bsYear: 0, firstAdDayInBSMonth: new Date(), numberOfDaysInBSMonth: 0, weekDay: 0 }; var getTodayADDate = function getTodayADDate() { return new Date().toISOString().split("T")[0]; }; var validateAdYear = function validateAdYear(year) { var minAdYear = CalenderConfig.minBSYear - 57; var maxAdYear = CalenderConfig.maxBSYear - 57; if (year < minAdYear || year > maxAdYear) { throw new RangeError("AD year should be in range of " + minAdYear + " to " + maxAdYear); } }; var giveValidAdYear = function giveValidAdYear(year) { var minAdYear = CalenderConfig.minBSYear - 57; var maxAdYear = CalenderConfig.maxBSYear - 57; return { message: Math.min(Math.max(year, minAdYear), maxAdYear), validity: !(year < minAdYear || year > maxAdYear) }; }; var validateAdMonth = function validateAdMonth(month) { if (month < 1 || month > 12) { throw new RangeError("AD month should be in range of 1 to 12"); } }; var giveValidAdMonth = function giveValidAdMonth(month) { return { message: Math.min(Math.max(month, 1), 12), validity: !(month < 1 || month > 12) }; }; var validateAdDay = function validateAdDay(day) { if (day < 1 || day > 31) { throw new RangeError("AD day should be in range of 1 to 31"); } }; var giveValidAdDay = function giveValidAdDay(day) { return { message: Math.min(Math.max(day, 1), 31), validity: !(day < 1 || day > 31) }; }; var validateBsYear = function validateBsYear(year) { var minBsYear = CalenderConfig.minBSYear; var maxBsYear = CalenderConfig.maxBSYear; if (year < minBsYear || year > maxBsYear) { throw new RangeError("BS year should be in range of " + minBsYear + " to " + maxBsYear); } }; var giveValidBsYear = function giveValidBsYear(year) { var minBsYear = CalenderConfig.minBSYear; var maxBsYear = CalenderConfig.maxBSYear; return { message: Math.min(Math.max(year, minBsYear), maxBsYear), validity: !(year < minBsYear || year > maxBsYear) }; }; var validateBsMonth = function validateBsMonth(month) { if (month < 1 || month > 12) { throw new RangeError("BS month should be in range of 1 to 12"); } }; var giveValidBsMonth = function giveValidBsMonth(month) { return { message: Math.min(Math.max(month, 1), 12), validity: !(month < 1 || month > 12) }; }; var validateBsDay = function validateBsDay(day) { if (day < 1 || day > 32) { throw new RangeError("BS day should be in range of 1 to 32"); } }; var giveValidBsDay = function giveValidBsDay(day) { return { message: Math.min(Math.max(day, 1), 32), validity: !(day < 1 || day > 32) }; }; var defaultFormatOptions = { separator: "-", format: "YYYY-MM-DD" }; var range = function range(start, end, step) { if (step === void 0) { step = 1; } var list = []; for (var i = start; i <= end; i = i + step) { list.push(i); } return list; }; var zeroPad = function zeroPad(num) { return "" + (num > 9 ? num : "0" + num); }; var executionDelegation = function executionDelegation(execution, delegatedExecution) { new Promise(function (resolve) { execution(); resolve(); }).then(function () { delegatedExecution(); }); }; var dateSplitterWithSeparator = function dateSplitterWithSeparator(date, separator) { var parts = date.replaceAll(separator, "-").split("-"); return parts; }; var splitDate = function splitDate(date, _ref) { var separator = _ref.separator, format = _ref.format; var parts = dateSplitterWithSeparator(date, separator); var year, month, day; if (format === "YYYY" + separator + "MM" + separator + "DD") { year = parts[0]; month = parts[1]; day = parts[2]; } else if (format === "DD" + separator + "MM" + separator + "YYYY") { day = parts[0]; month = parts[1]; year = parts[2]; } else if (format === "MM" + separator + "DD" + separator + "YYYY") { month = parts[0]; day = parts[1]; year = parts[2]; } else { throw new Error("Unsupported date format: " + format); } return { day: parseInt(day, 10), month: parseInt(month, 10), year: parseInt(year, 10) }; }; var stitchDate = function stitchDate(date, _ref2) { var separator = _ref2.separator, format = _ref2.format; var returnDate = "" + date.year + separator + zeroPad(date.month) + separator + zeroPad(date.day); if (format === "YYYY" + separator + "MM" + separator + "DD") { returnDate = "" + date.year + separator + zeroPad(date.month) + separator + zeroPad(date.day); } else if (format === "DD" + separator + "MM" + separator + "YYYY") { returnDate = "" + zeroPad(date.day) + separator + zeroPad(date.month) + separator + date.year; } else if (format === "MM" + separator + "DD" + separator + "YYYY") { returnDate = "" + zeroPad(date.day) + separator + zeroPad(date.month) + separator + date.year; } else { throw new Error("Unsupported date format: " + format); } return returnDate; }; var giveValidateObject = function giveValidateObject(date, type) { if (type === void 0) { type = BS; } var year = date.year, month = date.month, day = date.day; if (type === BS) { validateBsYear(year); validateBsMonth(month); validateBsDay(day); return; } validateAdYear(year); validateAdMonth(month); validateAdDay(day); }; var giveValidDateObject = function giveValidDateObject(date, type) { if (type === void 0) { type = BS; } var todayADDate = getTodayADDate(); var splittedADDate = splitDate(todayADDate, { separator: "-", format: "YYYY-MM-DD" }); var year = date.year, month = date.month, day = date.day; if (type === BS) { var todayBSDate = BSToAD(todayADDate); var splittedBSDate = splitDate(todayBSDate, { separator: "-", format: "YYYY-MM-DD" }); var bsYearValidity = giveValidBsYear(year || splittedBSDate.year); var bsMonthValidity = giveValidBsMonth(month || splittedBSDate.month); var bsDayValidity = giveValidBsDay(day || splittedBSDate.day); var _validBufferYear = isNaN(year) || !bsYearValidity.validity ? bsYearValidity.message : year; var _validBufferMonth = isNaN(month) || !bsMonthValidity.validity ? bsMonthValidity.message : month; var _validBufferDay = isNaN(day) || !bsDayValidity.validity ? bsDayValidity.message : day; return { year: giveValidBsYear(_validBufferYear).message, month: giveValidBsMonth(_validBufferMonth).message, day: giveValidBsDay(_validBufferDay).message }; } var adYearValidity = giveValidAdYear(year || splittedADDate.year); var adMonthValidity = giveValidAdMonth(month || splittedADDate.month); var adDayValidity = giveValidAdDay(day || splittedADDate.day); var validBufferYear = isNaN(year) || !adYearValidity.validity ? adYearValidity.message : year; var validBufferMonth = isNaN(month) || !adMonthValidity.validity ? adMonthValidity.message : month; var validBufferDay = isNaN(day) || !adDayValidity.validity ? adDayValidity.message : day; return { year: giveValidAdYear(validBufferYear).message, month: giveValidAdMonth(validBufferMonth).message, day: giveValidAdDay(validBufferDay).message }; }; var getNumberOfDaysInBSMonth = function getNumberOfDaysInBSMonth(yearMonth) { var year = yearMonth.year, month = yearMonth.month; validateBsYear(year); validateBsMonth(month); var yearCount = 0; var totalYears = year + 1 - minBSYear; var bsMonthData = bsMonthCalculatedData[month - 1]; return bsMonthData === null || bsMonthData === void 0 ? void 0 : bsMonthData.reduce(function (numberOfDays, monthData, index) { if (monthData === 0 || numberOfDays !== 0) { return numberOfDays; } var bsMonthUpperDaysIndex = index % 2; yearCount += monthData; if (totalYears > yearCount) { return numberOfDays; } if (year === 2081 && month === 2) { return bsMonthMaxDays[month - 1][bsMonthUpperDaysIndex + 1]; } if (year === 2081 && month === 3) { return bsMonthMaxDays[month - 1][bsMonthUpperDaysIndex - 1]; } if (year === 2081 && month === 11) { return bsMonthMaxDays[month - 1][bsMonthUpperDaysIndex] - 1; } if (year === 2081 && month === 12) { return bsMonthMaxDays[month - 1][bsMonthUpperDaysIndex] + 1; } if (year === 2085 && month === 5 || year === 2088 && month === 5) { return bsMonthMaxDays[month - 1][bsMonthUpperDaysIndex] - 2; } return bsMonthMaxDays[month - 1][bsMonthUpperDaysIndex]; }, 0); }; var parseBSDate = function parseBSDate(date, formatOptions) { var ogSplittedDate = splitDate(date, formatOptions); var _giveValidDateObject = giveValidDateObject(ogSplittedDate, "BS"), year = _giveValidDateObject.year, month = _giveValidDateObject.month, day = _giveValidDateObject.day; var validStitchedDate = stitchDate({ year: year, month: month, day: day }, { separator: "-", format: "YYYY-MM-DD" }); var adDate = new Date(BSToAD(validStitchedDate)); var firstBsDateInBSMonth = stitchDate({ year: year, month: month, day: 1 }, { separator: "-", format: "YYYY-MM-DD" }); var firstAdDateInBSMonth = new Date(BSToAD(firstBsDateInBSMonth)); var numberOfDaysInMonth = getNumberOfDaysInBSMonth({ year: year, month: month }); return { adDate: adDate, bsDay: day, bsMonth: month, bsYear: year, firstAdDayInBSMonth: firstAdDateInBSMonth, numberOfDaysInBSMonth: numberOfDaysInMonth, weekDay: adDate.getDay() }; }; var childOf = function childOf(childNode, parentNode) { return parentNode.contains(childNode); }; var SET_CONFIG = "set_config"; var initialState = { currentLocale: NEPALI, minYear: CalenderConfig.minBSYear, maxYear: CalenderConfig.maxBSYear, theme: "light", weekDayLabelSize: "sm", formatOptions: defaultFormatOptions }; var ConfigReducer = function ConfigReducer(state, action) { if (state === void 0) { state = initialState; } if (action.type === SET_CONFIG) { var _extends2; return _extends({}, state, (_extends2 = {}, _extends2[action.key] = action.value, _extends2)); } return state; }; var ConfigContext = createContext({ dispatch: function dispatch() { return null; }, state: initialState }); var ConfigProvider = function ConfigProvider(_ref) { var children = _ref.children, minYear = _ref.minYear, maxYear = _ref.maxYear, theme = _ref.theme, weekDayLabelSize = _ref.weekDayLabelSize, formatOptions = _ref.formatOptions, currentLocale = _ref.currentLocale; var _useReducer = useReducer(ConfigReducer, { minYear: minYear, maxYear: maxYear, theme: theme, weekDayLabelSize: weekDayLabelSize, formatOptions: formatOptions, currentLocale: currentLocale }), state = _useReducer[0], dispatch = _useReducer[1]; var contextValue = { state: state, dispatch: dispatch }; return React.createElement(ConfigContext.Provider, { value: contextValue }, children); }; var useConfig = function useConfig() { var _useContext = useContext(ConfigContext), state = _useContext.state, dispatch = _useContext.dispatch; function setConfig(key, value) { dispatch({ key: key, type: SET_CONFIG, value: value }); } function getConfig(key) { return state[key]; } return { setConfig: setConfig, getConfig: getConfig }; }; var _excluded = ["size", "viewBoxSize", "color", "children"]; var IconBase = function IconBase(props) { var _props$size = props.size, size = _props$size === void 0 ? 16 : _props$size, _props$viewBoxSize = props.viewBoxSize, viewBoxSize = _props$viewBoxSize === void 0 ? 24 : _props$viewBoxSize, _props$color = props.color, color = _props$color === void 0 ? "#6b6b6b" : _props$color, children = props.children, options = _objectWithoutPropertiesLoose(props, _excluded); return React.createElement("svg", Object.assign({ xmlns: 'http://www.w3.org/2000/svg', xmlnsXlink: 'http://www.w3.org/1999/xlink', width: size, height: size, color: color }, options, { viewBox: "0 0 " + viewBoxSize + " " + viewBoxSize }), children); }; var Next = function Next(props) { var rotationOrigin = parseInt(props.size || "24", 10) / 2; return React.createElement(IconBase, Object.assign({}, props), React.createElement("path", { transform: "rotate(180 " + rotationOrigin + " " + rotationOrigin + ")", fill: 'none', fillRule: 'evenodd', stroke: 'currentcolor', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2.4', d: 'M16.283 18.907L9.6 12l6.683-5.438' })); }; var Previous = function Previous(props) { return React.createElement(IconBase, Object.assign({}, props), React.createElement("path", { fill: 'none', fillRule: 'evenodd', stroke: 'currentcolor', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '2.4', d: 'M16.283 18.907L9.6 12l6.683-5.438' })); }; var Today = function Today(props) { props = _extends({}, props, { viewBoxSize: "512", size: "15" }); return React.createElement(IconBase, Object.assign({}, props), React.createElement("defs", null, React.createElement("path", { id: 'a', d: 'M468 160H44c-6.6 0-12-5.4-12-12v-36c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48v36c0 6.6-5.4 12-12 12zM44 192h424c6.6 0 12 5.4 12 12v260c0 26.5-21.5 48-48 48H80c-26.5 0-48-21.5-48-48V204c0-6.6 5.4-12 12-12zm116 204c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm0-128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm128 128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm0-128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm128 128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm0-128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40z' })), React.createElement("g", { fill: 'none', fillRule: 'evenodd' }, React.createElement("mask", { id: 'b', fill: '#fff' }, React.createElement("use", { xlinkHref: '#a' })), React.createElement("use", { fill: '#000', fillRule: 'nonzero', xlinkHref: '#a' }), React.createElement("g", { fill: 'currentcolor', mask: 'url(#b)' }, React.createElement("path", { d: 'M0 0h512v512H0z' })))); }; var translations = { previous: { en: "Previous", ne: "अघिल्लो" }, next: { en: "Next", ne: "अर्को" }, today: { en: "Today", ne: "आज" } }; var useTrans = function useTrans(currentLocale) { return { trans: function trans(key, locale) { if (!translations.hasOwnProperty(key)) { return key; } return translations[key][locale || currentLocale]; }, numberTrans: function numberTrans(num, locale) { return "" + (locale || currentLocale) === ENGLISH ? nepaliToEnglishNumber(num) : englishToNepaliNumber(num); } }; }; var DropDown = function DropDown(_ref) { var options = _ref.options, value = _ref.value, onSelect = _ref.onSelect; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var currentTheme = getConfig("theme"); return React.createElement("div", { className: 'drop-down' }, React.createElement("div", { className: "option-wrapper " + currentTheme }, React.createElement("ul", null, options.map(function (option, index) { return React.createElement("li", { key: index, className: option.value === value ? "active" : "", onClick: function onClick() { onSelect(option); } }, option.label); })))); }; var MonthPicker = function MonthPicker(_ref) { var date = _ref.date, onSelect = _ref.onSelect; var _useState = useState(false), showDropdown = _useState[0], setShowDropdown = _useState[1]; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var currentLocale = useMemo(function () { return getConfig("currentLocale"); }, [getConfig]); var currentMonth = useMemo(function () { var month = date.bsMonth; return { label: months[currentLocale][month - 1], value: month }; }, [date, currentLocale]); var monthList = useMemo(function () { return months[currentLocale].map(function (month, index) { return { label: month, value: index + 1 }; }); }, [currentLocale]); var handleDropdownView = function handleDropdownView(selected) { setShowDropdown(!showDropdown); onSelect(selected.value); }; return React.createElement("div", { className: "control month" }, React.createElement("span", { className: 'current-month', onClick: function onClick() { return setShowDropdown(!showDropdown); } }, currentMonth.label), showDropdown && React.createElement(DropDown, { options: monthList, value: currentMonth.value, onSelect: handleDropdownView })); }; var YearPicker = function YearPicker(_ref) { var date = _ref.date, onSelect = _ref.onSelect; var _useState = useState(false), showDropdown = _useState[0], setShowDropdown = _useState[1]; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var _useTrans = useTrans(getConfig("currentLocale")), numberTrans = _useTrans.numberTrans; var currentYear = useMemo(function () { var year = date.bsYear; return { label: numberTrans(year), value: year }; }, [date]); var years = useMemo(function () { return range(getConfig("minYear"), getConfig("maxYear")).reverse().map(function (year) { return { label: numberTrans(year), value: year }; }); }, []); var handleDropdownView = function handleDropdownView(selected) { setShowDropdown(!showDropdown); onSelect(selected.value); }; return React.createElement("div", { className: "control year" }, React.createElement("span", { className: 'current-year', onClick: function onClick() { return setShowDropdown(!showDropdown); } }, currentYear.label), showDropdown && React.createElement(DropDown, { options: years, value: currentYear.value, onSelect: handleDropdownView })); }; var CalenderController = function CalenderController(props) { var onNextMonth = props.onNextMonth, onPreviousMonth = props.onPreviousMonth, calenderDate = props.calenderDate, onToday = props.onToday, onYearSelect = props.onYearSelect, onMonthSelect = props.onMonthSelect; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var _useTrans = useTrans(getConfig("currentLocale")), trans = _useTrans.trans; return React.createElement("div", { className: 'calendar-controller' }, React.createElement("span", { className: 'control icon', title: trans("previous"), onClick: onPreviousMonth }, React.createElement(Previous, null)), React.createElement("div", { className: 'date-indicator' }, React.createElement(MonthPicker, { date: calenderDate, onSelect: onMonthSelect }), React.createElement(YearPicker, { date: calenderDate, onSelect: onYearSelect })), React.createElement("span", { className: 'control icon icon-today', title: trans("today"), onClick: onToday }, React.createElement(Today, { color: '#2096f5' })), React.createElement("span", { className: 'control icon', title: trans("next"), onClick: onNextMonth }, React.createElement(Next, null))); }; var DayPickerBody = function DayPickerBody(_ref) { var selectedDate = _ref.selectedDate, date = _ref.calenderDate, onSelect = _ref.onSelect; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var _useTrans = useTrans(getConfig("currentLocale")), numberTrans = _useTrans.numberTrans; var formatOptions = getConfig("formatOptions"); var currentTheme = getConfig("theme"); var weeksInMonth = useMemo(function () { return Math.ceil((date.firstAdDayInBSMonth.getDay() + date.numberOfDaysInBSMonth) / 7) - 1; }, [date]); var previousMonth = useMemo(function () { return date.bsMonth - 1 !== 0 ? date.bsMonth - 1 : 12; }, [date]); var previousYear = useMemo(function () { return previousMonth === 12 ? date.bsYear - 1 : date.bsYear; }, [previousMonth, date]); var previousMonthDays = useMemo(function () { return previousYear >= minBSYear ? getNumberOfDaysInBSMonth({ month: previousMonth, year: previousYear }) : 30; }, [previousYear]); var getDayInfo = useCallback(function (weekNum, weekDayNum) { var day = weekNum * 7 + weekDayNum - date.firstAdDayInBSMonth.getDay(); var month = date.bsMonth; var year = date.bsYear; var isCurrentMonth = true; if (day <= 0) { day = previousMonthDays + day; isCurrentMonth = false; } else if (day > date.numberOfDaysInBSMonth) { day = day - date.numberOfDaysInBSMonth; isCurrentMonth = false; } var today = splitDate(ADToBS(new Date()), formatOptions != null ? formatOptions : defaultFormatOptions); var isToday = isCurrentMonth ? today.day === day && today.month === date.bsMonth && today.year === date.bsYear : false; var isSelected = selectedDate && isCurrentMonth ? selectedDate.bsDay === day && selectedDate.bsMonth === date.bsMonth && selectedDate.bsYear === date.bsYear : false; return { day: day, month: month, year: year, isCurrentMonth: isCurrentMonth, isToday: isToday, isSelected: isSelected }; }, [date, selectedDate, previousMonthDays]); var onDateSelectHandler = useCallback(function (dayInfo) { if (dayInfo.isCurrentMonth) { onSelect({ year: dayInfo.year, month: dayInfo.month, day: dayInfo.day }); } }, [onSelect]); return React.createElement("tbody", null, range(0, weeksInMonth).map(function (weekNum) { return React.createElement("tr", { key: weekNum }, range(1, 7).map(function (weekDayNum) { var dayInfo = getDayInfo(weekNum, weekDayNum); return React.createElement("td", { key: weekDayNum, className: "month-day " + (dayInfo.isCurrentMonth ? "current" : "disabled-" + currentTheme) + " " + (dayInfo.isToday ? "today" : "") + " " + (dayInfo.isSelected ? "selected" : ""), onClick: function onClick() { return onDateSelectHandler(dayInfo); } }, numberTrans(dayInfo.day)); })); })); }; var DayPickerHeader = function DayPickerHeader() { var _getConfig; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var currentLocale = useMemo(function () { return getConfig("currentLocale"); }, [getConfig]); var currentWeeksVal = weekDaysLabel[(_getConfig = getConfig("weekDayLabelSize")) != null ? _getConfig : "sm"][currentLocale]; return React.createElement("thead", null, React.createElement("tr", null, currentWeeksVal.map(function (weekDay, index) { return React.createElement("td", { key: index }, weekDay); }))); }; var DayPicker = function DayPicker(_ref) { var selectedDate = _ref.selectedDate, calenderDate = _ref.calenderDate, onDaySelect = _ref.onDaySelect; return React.createElement("table", null, React.createElement(DayPickerHeader, null), React.createElement(DayPickerBody, { selectedDate: selectedDate, calenderDate: calenderDate, onSelect: onDaySelect })); }; var Calender = function Calender(_ref) { var value = _ref.value, events = _ref.events, _ref$formatOptions = _ref.formatOptions, formatOptions = _ref$formatOptions === void 0 ? defaultFormatOptions : _ref$formatOptions; var _useState = useState(false), isInitialized = _useState[0], setIsInitialized = _useState[1]; var _useState2 = useState(null), selectedDate = _useState2[0], setSelectedDate = _useState2[1]; var _useState3 = useState(parsedDateInitialValue), calenderDate = _useState3[0], setCalenderDate = _useState3[1]; var _useConfig = useConfig(), getConfig = _useConfig.getConfig; var currentTheme = getConfig("theme"); useEffect(function () { var parsedDateValue = value ? parseBSDate(value, formatOptions) : null; if (parsedDateValue) { setSelectedDate(parsedDateValue); setCalenderDate(parsedDateValue); } else { var today = parseBSDate(ADToBS(new Date()), formatOptions); setCalenderDate(today); setSelectedDate(null); } setIsInitialized(true); }, []); useEffect(function () { if (isInitialized && selectedDate) { events.change(stitchDate({ year: selectedDate.bsYear, month: selectedDate.bsMonth, day: selectedDate.bsDay }, formatOptions)); } }, [selectedDate, formatOptions, isInitialized]); var onPreviousMonthHandler = useCallback(function () { executionDelegation(function () { setCalenderDate(function (date) { var _getConfig, _getConfig2; var year = date.bsYear; var month = date.bsMonth - 1; if (month < 1) { month = 12; year--; } if (year < ((_getConfig = getConfig("minYear")) != null ? _getConfig : 0) || year > ((_getConfig2 = getConfig("maxYear")) != null ? _getConfig2 : 0)) { return date; } return parseBSDate(stitchDate({ day: date.bsDay, month: month, year: year }, formatOptions), formatOptions); }); }, function () { if (events.previousMonthSelect) { events.previousMonthSelect({ month: calenderDate.bsMonth, year: calenderDate.bsYear }); } }); }, [formatOptions]); var onNextMonthClickHandler = useCallback(function () { executionDelegation(function () { setCalenderDate(function (date) { var year = date.bsYear; var month = date.bsMonth + 1; if (month > 12) { month = 1; year++; } return parseBSDate(stitchDate({ day: date.bsDay, month: month, year: year }, formatOptions), formatOptions); }); }, function () { if (events.nextMonthSelect) { events.nextMonthSelect({ year: calenderDate.bsYear, month: calenderDate.bsMonth }); } }); }, [formatOptions]); var onTodayClickHandler = useCallback(function () { var today = parseBSDate(ADToBS(new Date()), formatOptions); executionDelegation(function () { setCalenderDate(today); setSelectedDate(today); }, function () { if (events.todaySelect) { events.todaySelect({ year: today.bsYear, month: today.bsMonth, day: today.bsDay }); } }); }, [formatOptions]); var onYearSelectHandler = useCallback(function (year) { executionDelegation(function () { setCalenderDate(parseBSDate(stitchDate({ year: year, month: calenderDate.bsMonth, day: calenderDate.bsDay }, formatOptions), formatOptions)); }, function () { if (events.yearSelect) { events.yearSelect(year); } }); }, [calenderDate, formatOptions]); var onMonthSelectHandler = useCallback(function (month) { executionDelegation(function () { setCalenderDate(parseBSDate(stitchDate({ year: calenderDate.bsYear, month: month, day: calenderDate.bsDay }, formatOptions), formatOptions)); }, function () { if (events.monthSelect) { events.monthSelect({ year: calenderDate.bsYear, month: month }); } }); }, [calenderDate, formatOptions]); var onDaySelectHandler = useCallback(function (date) { executionDelegation(function () { var newDate = parseBSDate(stitchDate(date, formatOptions), formatOptions); setCalenderDate(newDate); setSelectedDate(newDate); }, function () { if (events.daySelect) { events.daySelect(date); } }); }, []); return React.createElement("div", { className: "calender " + currentTheme }, React.createElement("div", { className: 'calendar-wrapper' }, isInitialized && React.createElement(Fragment, null, React.createElement(CalenderController, { onPreviousMonth: onPreviousMonthHandler, onNextMonth: onNextMonthClickHandler, calenderDate: calenderDate, onToday: onTodayClickHandler, onYearSelect: onYearSelectHandler, onMonthSelect: onMonthSelectHandler }), React.createElement(DayPicker, { selectedDate: selectedDate, calenderDate: calenderDate, onDaySelect: onDaySelectHandler })))); }; var NepaliDatePicker = function NepaliDatePicker(props) { var className = props.className, inputClassName = props.inputClassName, value = props.value, onChange = props.onChange, onSelect = props.onSelect, options = props.options, todayIfEmpty = props.todayIfEmpty, placeholder = props.placeholder, style = props.style, inputStyle = props.inputStyle, _props$formatOptions = props.formatOptions, formatOptions = _props$formatOptions === void 0 ? defaultFormatOptions : _props$formatOptions; var nepaliDatePickerWrapper = useRef(null); var nepaliDatePickerInput = useRef(null); var _useState = useState(""), date = _useState[0], setDate = _useState[1]; var _useState2 = useState(false), showCalendar = _useState2[0], setShowCalendar = _useState2[1]; var _useConfig = useConfig(), setConfig = _useConfig.setConfig, getConfig = _useConfig.getConfig; var _useTrans = useTrans(getConfig("currentLocale")), numberTrans = _useTrans.numberTrans; var toEnglish = useCallback(function (val) { return numberTrans(val, ENGLISH); }, []); var returnDateValue = useCallback(function (val) { return numberTrans(val, options === null || options === void 0 ? void 0 : options.valueLocale); }, [options === null || options === void 0 ? void 0 : options.valueLocale]); useEffect(function () { var _options$calenderLoca; setConfig("currentLocale", (_options$calenderLoca = options === null || options === void 0 ? void 0 : options.calenderLocale) != null ? _options$calenderLoca : "ne"); }, [options === null || options === void 0 ? void 0 : options.calenderLocale]); useEffect(function () { setDate(returnDateValue(value || (todayIfEmpty ? ADToBS(new Date()) : ""))); }, [value]); var handleClickOutside = useCallback(function (event) { if (nepaliDatePickerWrapper.current && childOf(event.target, nepaliDatePickerWrapper.current)) { return; } setShowCalendar(false); }, []); useLayoutEffect(function () { if (showCalendar) { document.addEventListener("mousedown", handleClickOutside); } return function () { document.removeEventListener("mousedown", handleClickOutside); }; }, [showCalendar]); useLayoutEffect(function () { if (showCalendar && nepaliDatePickerWrapper.current) { var nepaliDatePicker = nepaliDatePickerWrapper.current.getBoundingClientRect(); var screenHeight = window.innerHeight; var calender = nepaliDatePickerWrapper.current.querySelector(".calender"); if (calender) { setTimeout(function () { var calenderHeight = calender.clientHeight; if (calenderHeight + nepaliDatePicker.bottom > screenHeight) { if (calenderHeight < nepaliDatePicker.top) { calender.style.bottom = nepaliDatePicker.height + "px"; } } }, 0); } } }, [showCalendar]); var handleOnChange = useCallback(function (changedDate) { executionDelegation(function () { setDate(changedDate); }, function () { if (onChange) { onChange(returnDateValue(changedDate)); } }); }, [onChange]); var handleOnDaySelect = useCallback(function (selectedDate) { executionDelegation(function () { if (options !== null && options !== void 0 && options.closeOnSelect) { setShowCalendar(false); } }, function () { if (onSelect) { onSelect(returnDateValue(stitchDate(selectedDate, formatOptions))); } }); }, [onSelect]); var datepickerEvents = { change: handleOnChange, daySelect: handleOnDaySelect, todaySelect: handleOnDaySelect }; var onInputChange = useCallback(function (changedDate) { executionDelegation(function () { setDate(changedDate); }, function () { if (onChange) { onChange(returnDateValue(changedDate)); } }); }, [onChange]); var getSeparatorPositionsAndPatterns = useCallback(function () { var escapedSeparator = formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); var positions = [3, 5]; var pattern = ""; var dayPattern = "(0[1-9]|[1-2][0-9]|3[01])"; var monthPattern = "(0[1-9]|1[0-2])"; var yearPattern = "\\d{4}"; switch (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.format) { case "DD" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "MM" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "YYYY": positions = [3, 5]; pattern = "^" + dayPattern + escapedSeparator + monthPattern + escapedSeparator + yearPattern + "$"; break; case "MM" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "DD" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "YYYY": positions = [3, 5]; pattern = "^" + monthPattern + escapedSeparator + dayPattern + escapedSeparator + yearPattern + "$"; break; case "YYYY" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "MM" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "DD": default: positions = [4, 6]; pattern = "^" + yearPattern + escapedSeparator + monthPattern + escapedSeparator + dayPattern + "$"; } return { positions: positions, pattern: pattern }; }, [formatOptions]); var _getSeparatorPosition = getSeparatorPositionsAndPatterns(), positions = _getSeparatorPosition.positions, pattern = _getSeparatorPosition.pattern; var formatDateString = useCallback(function (value) { var digitsOnly = value.replace(/\D/g, ""); var result = ""; var digitIndex = 0; var maxDigits = 8; var _loop = function _loop(i) { var _positions$find; if (positions.includes(i) && digitIndex > 0 && i !== digitsOnly.length && digitIndex >= ((_positions$find = positions.find(function (p) { return p === i; })) != null ? _positions$find : 0)) { result += formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator; } if (digitIndex < digitsOnly.length && digitIndex < maxDigits) { result += digitsOnly[digitIndex]; digitIndex++; } }; for (var i = 0; i < 10; i++) { _loop(i); } return result; }, [formatOptions, positions]); var handleInputChange = function handleInputChange(e) { setShowCalendar(false); var newValue = toEnglish(e.target.value); var sanitized = newValue.replace(new RegExp("[^0-9" + (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.separator) + "]", "g"), ""); var digitCount = sanitized.length; if (digitCount > 0) { var formatted = formatDateString(sanitized); formatted = (options === null || options === void 0 ? void 0 : options.valueLocale) === "en" ? toEnglish(formatted) : formatted; setDate(formatted); onInputChange(formatted); } else { setDate(""); onInputChange(""); } }; return React.createElement("div", { ref: nepaliDatePickerWrapper, className: "nepali-date-picker " + className, style: style }, React.createElement("input", { type: 'text', ref: nepaliDatePickerInput, className: inputClassName, value: numberTrans(date), onClick: function onClick() { return setShowCalendar(function (visible) { return !visible; }); }, style: inputStyle, placeholder: placeholder || (formatOptions === null || formatOptions === void 0 ? void 0 : formatOptions.format), onInput: handleInputChange, maxLength: 10, pattern: pattern }), showCalendar && React.createElement(Calender, { value: date && date, events: datepickerEvents, formatOptions: formatOptions })); }; var NepaliDatePickerWrapper = function NepaliDatePickerWrapper(props) { var _props$maxYear, _props$minYear; var calenderOptions = useMemo(function () { return _extends({ closeOnSelect: true, calenderLocale: NEPALI, valueLocale: ENGLISH }, props.options); }, [props.options]); return React.createElement(ConfigProvider, { maxYear: (_props$maxYear = props.maxYear) != null ? _props$maxYear : CalenderConfig.maxBSYear, minYear: (_props$minYear = props.minYear) != null ? _props$minYear : CalenderConfig.minBSYear, theme: props.theme, weekDayLabelSize: props.weekDayLabelSize, formatOptions: props.formatOptions, currentLocale: calenderOptions.calenderLocale }, React.createElement(NepaliDatePicker, Object.assign({}, _extends({}, props, { options: calenderOptions, formatOptions: _extends({ separator: "-", format: "YYYY-MM-DD" }, props.formatOptions) })))); }; export { AD, BS, ENGLISH, NEPALI, NepaliDatePickerWrapper as NepaliDatePicker, childOf, dateSplitterWithSeparator, defaultFormatOptions, executionDelegation, getNumberOfDaysInBSMonth, getTodayADDate, giveValidAdDay, giveValidAdMonth, giveValidAdYear, giveValidBsDay, giveValidBsMonth, giveValidBsYear, giveValidDateObject, giveValidateObject, parseBSDate, parsedDateInitialValue, range, splitDate, stitchDate, validateAdDay, validateAdMonth, validateAdYear, validateBsDay, validateBsMonth, validateBsYear, zeroPad }; //# sourceMappingURL=index.modern.js.map