| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307 |
- /*! flatpickr v2.0, @license MIT */
- function Flatpickr(element, config) {
- const self = this;
- function init() {
- self.element = element;
- self.instanceConfig = config || {};
- self.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
- .test(navigator.userAgent);
- setupFormats();
- parseConfig();
- setupInputs();
- setupDates();
- setupHelperFunctions();
- self.changeMonth = changeMonth;
- self.clear = clear;
- self.close = close;
- self.destroy = destroy;
- self.formatDate = formatDate;
- self.jumpToDate = jumpToDate;
- self.open = open;
- self.parseDate = parseDate;
- self.redraw = redraw;
- self.set = set;
- self.setDate = setDate;
- self.toggle = toggle;
- if (self.isMobile && !self.config.disableMobile) {
- bind();
- setupMobile();
- }
- else {
- build();
- bind();
- }
- if (self.selectedDateObj)
- updateValue();
- triggerEvent("Ready");
- }
- function updateTime(e) {
- timeWrapper(e);
- updateValue(e);
- }
- function bind() {
- if (self.config.wrap) {
- ["open", "close", "toggle", "clear"].forEach(el => {
- try {
- self.element.querySelector(`[data-${el}]`)
- .addEventListener("click", self[el]);
- }
- catch (e) {
- //
- }
- });
- }
- if (self.isMobile)
- return;
- document.addEventListener("keydown", onKeyDown);
- window.addEventListener("resize", debounce(onResize, 300));
- document.addEventListener("click", documentClick);
- document.addEventListener("blur", documentClick);
- if (self.config.clickOpens)
- (self.altInput || self.input).addEventListener("focus", open);
- if (!self.config.noCalendar) {
- self.prevMonthNav.addEventListener("click", () => changeMonth(-1));
- self.nextMonthNav.addEventListener("click", () => changeMonth(1));
- self.currentYearElement.addEventListener("wheel", yearScroll);
- self.currentYearElement.addEventListener("focus", () => {
- self.currentYearElement.select();
- });
- self.currentYearElement.addEventListener("input", event => {
- if (event.target.value.length === 4)
- self.currentYearElement.blur();
- self.currentYear = parseInt(event.target.value, 10) || self.currentYear;
- self.redraw();
- });
- self.days.addEventListener("click", selectDate);
- }
- if (self.config.enableTime) {
- self.timeContainer.addEventListener("wheel", updateTime);
- self.timeContainer.addEventListener("wheel", debounce(() => triggerEvent("Change"), 1000));
- self.timeContainer.addEventListener("input", updateTime);
- self.hourElement.addEventListener("focus", () => self.hourElement.select());
- self.minuteElement.addEventListener("focus", () => self.minuteElement.select());
- if (self.secondElement)
- self.secondElement.addEventListener("focus", () => self.secondElement.select());
- if (self.amPM)
- self.amPM.addEventListener("click", updateTime);
- }
- }
- function jumpToDate(jumpDate) {
- jumpDate = jumpDate
- ? parseDate(jumpDate)
- : self.selectedDateObj || self.config.defaultDate || self.config.minDate || self.now;
- self.currentYear = jumpDate.getFullYear();
- self.currentMonth = jumpDate.getMonth();
- self.redraw();
- }
- function build() {
- const fragment = document.createDocumentFragment();
- self.calendarContainer = createElement("div", "flatpickr-calendar");
- if (!self.config.noCalendar) {
- fragment.appendChild(buildMonthNav());
- if (self.config.weekNumbers)
- fragment.appendChild(buildWeeks());
- self.rContainer = createElement("div", "flatpickr-rContainer");
- self.rContainer.appendChild(buildWeekdays());
- self.rContainer.appendChild(buildDays());
- fragment.appendChild(self.rContainer);
- }
- if (self.config.enableTime)
- fragment.appendChild(buildTime());
- self.calendarContainer.appendChild(fragment);
- if (self.config.inline || self.config.static) {
- self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
- positionCalendar();
- self.element.parentNode.appendChild(self.calendarContainer);
- }
- else
- document.body.appendChild(self.calendarContainer);
- }
- function buildDays() {
- if (!self.days) {
- self.days = createElement("div", "flatpickr-days");
- self.days.tabIndex = -1;
- }
- const firstOfMonth = (
- new Date(self.currentYear, self.currentMonth, 1).getDay() -
- Flatpickr.l10n.firstDayOfWeek + 7
- ) % 7,
- daysInMonth = self.utils.getDaysinMonth(),
- prevMonthDays = self.utils.getDaysinMonth((self.currentMonth - 1 + 12) % 12),
- days = document.createDocumentFragment();
- let dayNumber = prevMonthDays + 1 - firstOfMonth,
- currentDate,
- dateIsDisabled;
- if (self.config.weekNumbers)
- self.weekNumbers.innerHTML = "";
- self.days.innerHTML = "";
- // prepend days from the ending of previous month
- for (; dayNumber <= prevMonthDays; dayNumber++) {
- const curDate = new Date(self.currentYear, self.currentMonth - 1, dayNumber, 0, 0, 0, 0, 0),
- dateIsEnabled = isEnabled(curDate),
- dayElem = createElement(
- "span",
- "flatpickr-day prevMonthDay" + (dateIsEnabled ? "" : " disabled"),
- dayNumber
- );
- if (dateIsEnabled)
- dayElem.tabIndex = 0;
- days.appendChild(dayElem);
- }
- // Start at 1 since there is no 0th day
- for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++) {
- currentDate = new Date(self.currentYear, self.currentMonth, dayNumber, 0, 0, 0, 0, 0);
- if (self.config.weekNumbers && dayNumber % 7 === 1) {
- self.weekNumbers.insertAdjacentHTML(
- "beforeend",
- "<span class='disabled flatpickr-day'>" + self.getWeek(currentDate) + "</span>"
- );
- }
- dateIsDisabled = !isEnabled(currentDate);
- const dayElement = createElement(
- "span",
- dateIsDisabled ? "flatpickr-day disabled" : "flatpickr-day",
- dayNumber
- );
- if (!dateIsDisabled) {
- dayElement.tabIndex = 0;
- if (equalDates(currentDate, new Date()))
- dayElement.classList.add("today");
- if (self.selectedDateObj && equalDates(currentDate, self.selectedDateObj)) {
- dayElement.classList.add("selected");
- self.selectedDateElem = dayElement;
- }
- }
- days.appendChild(dayElement);
- }
- // append days from the next month
- for (let dayNum = daysInMonth + 1; dayNum <= 42 - firstOfMonth; dayNum++) {
- const curDate = new Date(
- self.currentYear,
- self.currentMonth + 1,
- dayNum % daysInMonth,
- 0, 0, 0, 0, 0
- ),
- dateIsEnabled = isEnabled(curDate),
- dayElement = createElement(
- "span",
- "flatpickr-day nextMonthDay" + (dateIsEnabled ? "" : " disabled"),
- dayNum % daysInMonth
- );
- if (self.config.weekNumbers && dayNum % 7 === 1) {
- self.weekNumbers.insertAdjacentHTML(
- "beforeend",
- "<span class='disabled flatpickr-day'>" + self.getWeek(curDate) + "</span>"
- );
- }
- if (dateIsEnabled)
- dayElement.tabIndex = 0;
- days.appendChild(dayElement);
- }
- self.days.appendChild(days);
- return self.days;
- }
- function buildMonthNav() {
- const monthNavFragment = document.createDocumentFragment();
- self.monthNav = createElement("div", "flatpickr-month");
- self.prevMonthNav = createElement("span", "flatpickr-prev-month");
- self.prevMonthNav.innerHTML = self.config.prevArrow;
- self.currentMonthElement = createElement("span", "cur_month");
- self.currentYearElement = createElement("input", "cur_year");
- self.currentYearElement.type = "number";
- self.currentYearElement.title = Flatpickr.l10n.scrollTitle;
- self.nextMonthNav = createElement("span", "flatpickr-next-month");
- self.nextMonthNav.innerHTML = self.config.nextArrow;
- self.navigationCurrentMonth = createElement("span", "flatpickr-current-month");
- self.navigationCurrentMonth.appendChild(self.currentMonthElement);
- self.navigationCurrentMonth.appendChild(self.currentYearElement);
- monthNavFragment.appendChild(self.prevMonthNav);
- monthNavFragment.appendChild(self.navigationCurrentMonth);
- monthNavFragment.appendChild(self.nextMonthNav);
- self.monthNav.appendChild(monthNavFragment);
- updateNavigationCurrentMonth();
- return self.monthNav;
- }
- function buildTime() {
- self.calendarContainer.classList.add("hasTime");
- self.timeContainer = createElement("div", "flatpickr-time");
- self.timeContainer.tabIndex = -1;
- const separator = createElement("span", "flatpickr-time-separator", ":");
- self.hourElement = createElement("input", "flatpickr-hour");
- self.minuteElement = createElement("input", "flatpickr-minute");
- self.hourElement.tabIndex = self.minuteElement.tabIndex = 0;
- self.hourElement.type = self.minuteElement.type = "number";
- self.hourElement.value =
- self.selectedDateObj ? pad(self.selectedDateObj.getHours()) : 12;
- self.minuteElement.value =
- self.selectedDateObj ? pad(self.selectedDateObj.getMinutes()) : "00";
- self.hourElement.step = self.config.hourIncrement;
- self.minuteElement.step = self.config.minuteIncrement;
- self.hourElement.min = -(self.config.time_24hr ? 1 : 0);
- self.hourElement.max = self.config.time_24hr ? 24 : 13;
- self.minuteElement.min = -self.minuteElement.step;
- self.minuteElement.max = 60;
- self.hourElement.title = self.minuteElement.title = Flatpickr.l10n.scrollTitle;
- self.timeContainer.appendChild(self.hourElement);
- self.timeContainer.appendChild(separator);
- self.timeContainer.appendChild(self.minuteElement);
- if (self.config.enableSeconds) {
- self.timeContainer.classList.add("has-seconds");
- self.secondElement = createElement("input", "flatpickr-second");
- self.secondElement.type = "number";
- self.secondElement.value =
- self.selectedDateObj ? pad(self.selectedDateObj.getSeconds()) : "00";
- self.secondElement.step = self.minuteElement.step;
- self.secondElement.min = self.minuteElement.min;
- self.secondElement.max = self.minuteElement.max;
- self.timeContainer.appendChild(
- createElement("span", "flatpickr-time-separator", ":")
- );
- self.timeContainer.appendChild(self.secondElement);
- }
- if (!self.config.time_24hr) { // add self.amPM if appropriate
- self.amPM = createElement(
- "span",
- "flatpickr-am-pm",
- ["AM", "PM"][(self.hourElement.value > 11) | 0]
- );
- self.amPM.title = Flatpickr.l10n.toggleTitle;
- self.amPM.tabIndex = 0;
- self.timeContainer.appendChild(self.amPM);
- }
- return self.timeContainer;
- }
- function buildWeekdays() {
- if (!self.weekdayContainer)
- self.weekdayContainer = createElement("div", "flatpickr-weekdays");
- const firstDayOfWeek = Flatpickr.l10n.firstDayOfWeek;
- let weekdays = Flatpickr.l10n.weekdays.shorthand.slice();
- if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) {
- weekdays = [].concat(
- weekdays.splice(firstDayOfWeek, weekdays.length),
- weekdays.splice(0, firstDayOfWeek)
- );
- }
- self.weekdayContainer.innerHTML = `<span class=flatpickr-weekday>${weekdays.join("</span><span class=flatpickr-weekday>")}</span>`;
- return self.weekdayContainer;
- }
- function buildWeeks() {
- self.calendarContainer.classList.add("hasWeeks");
- self.weekWrapper = createElement("div", "flatpickr-weekwrapper");
- self.weekWrapper.appendChild(
- createElement("span", "flatpickr-weekday", Flatpickr.l10n.weekAbbreviation)
- );
- self.weekNumbers = createElement("div", "flatpickr-weeks");
- self.weekWrapper.appendChild(self.weekNumbers);
- return self.weekWrapper;
- }
- function changeMonth(offset) {
- self.currentMonth += offset;
- handleYearChange();
- updateNavigationCurrentMonth();
- buildDays();
- (self.config.noCalendar ? self.timeContainer : self.days).focus();
- }
- function clear() {
- self.input.value = "";
- if (self.altInput)
- self.altInput.value = "";
- self.selectedDateObj = null;
- triggerEvent("Change");
- jumpToDate(self.now);
- }
- function close() {
- self.isOpen = false;
- self.calendarContainer.classList.remove("open");
- (self.altInput || self.input).classList.remove("active");
- triggerEvent("Close");
- }
- function destroy() {
- self.calendarContainer.parentNode.removeChild(self.calendarContainer);
- self.input.value = "";
- if (self.altInput) {
- self.input.type = "text";
- self.altInput.parentNode.removeChild(self.altInput);
- }
- document.removeEventListener("keydown", onKeyDown);
- window.removeEventListener("resize", onResize);
- document.removeEventListener("click", documentClick);
- document.removeEventListener("blur", documentClick);
- delete self.input._flatpickr;
- }
- function documentClick(e) {
- const isCalendarElement = self.calendarContainer.contains(e.target),
- isInput = self.element.contains(e.target) || e.target === self.altInput;
- if (self.isOpen && !isCalendarElement && !isInput)
- self.close();
- }
- function formatDate(frmt, dateObj) {
- const chars = frmt.split("");
- return chars.map((c, i) => self.formats[c] && chars[i - 1] !== "\\"
- ? self.formats[c](dateObj)
- : c !== "\\" ? c : ""
- ).join("");
- }
- function handleYearChange() {
- if (self.currentMonth < 0 || self.currentMonth > 11) {
- self.currentYear += self.currentMonth % 11;
- self.currentMonth = (self.currentMonth + 12) % 12;
- }
- }
- function isEnabled(dateToCheck) {
- if (
- (self.config.minDate && dateToCheck < self.config.minDate) ||
- (self.config.maxDate && dateToCheck > self.config.maxDate)
- )
- return false;
- if (!self.config.enable.length && !self.config.disable.length)
- return true;
- dateToCheck = parseDate(dateToCheck, true); // timeless
- const bool = self.config.enable.length > 0,
- array = bool ? self.config.enable : self.config.disable;
- let d;
- for (let i = 0; i < array.length; i++) {
- d = array[i];
- if (d instanceof Function && d(dateToCheck)) // disabled by function
- return bool;
- else if ((d instanceof Date || (typeof d === "string")) &&
- parseDate(d, true).getTime() === dateToCheck.getTime()
- )
- // disabled by date string
- return bool;
- else if ( // disabled by range
- typeof d === "object" &&
- d.hasOwnProperty("from") &&
- dateToCheck >= parseDate(d.from) &&
- dateToCheck <= parseDate(d.to)
- )
- return bool;
- }
- return !bool;
- }
- function onKeyDown(e) {
- if (!self.isOpen)
- return;
- switch (e.which) {
- case 13:
- if (self.timeContainer && self.timeContainer.contains(e.target))
- updateValue(e);
- else
- selectDate(e);
- break;
- case 27:
- self.close();
- break;
- case 37:
- if (e.target !== self.input & e.target !== self.altInput)
- changeMonth(-1);
- break;
- case 38:
- e.preventDefault();
- if (self.timeContainer.contains(e.target))
- updateTime(e);
- else {
- self.currentYear++;
- self.redraw();
- }
- break;
- case 39:
- if (e.target !== self.input & e.target !== self.altInput)
- changeMonth(1);
- break;
- case 40:
- e.preventDefault();
- if (self.timeContainer.contains(e.target))
- updateTime(e);
- else {
- self.currentYear--;
- self.redraw();
- }
- break;
- default: break;
- }
- }
- function onResize() {
- if (self.isOpen && !self.config.inline && !self.config.static)
- positionCalendar();
- }
- function open(e) {
- if (self.isMobile) {
- e.preventDefault();
- e.target.blur();
- setTimeout(() => {
- self.mobileInput.click();
- }, 0);
- triggerEvent("Open");
- return;
- }
- else if (self.isOpen || (self.altInput || self.input).disabled || self.config.inline)
- return;
- self.calendarContainer.classList.add("open");
- if (!self.config.static)
- positionCalendar();
- self.isOpen = true;
- if (!self.config.allowInput) {
- (self.altInput || self.input).blur();
- (self.config.noCalendar
- ? self.timeContainer
- : self.selectedDateObj
- ? self.selectedDateElem
- : self.days).focus();
- }
- (self.altInput || self.input).classList.add("active");
- triggerEvent("Open");
- }
- function pad(number) {
- return `0${number}`.slice(-2);
- }
- function parseConfig() {
- self.config = self.instanceConfig;
- Object.keys(self.element.dataset).forEach(
- k => self.config[k] = typeof Flatpickr.defaultConfig[k] === "boolean"
- ? self.element.dataset[k] !== "false"
- : self.element.dataset[k]
- );
- if (!self.config.dateFormat && self.config.enableTime) {
- self.config.dateFormat = Flatpickr.defaultConfig.dateFormat;
- if (self.config.noCalendar) { // time picker
- self.config.dateFormat = "H:i" + (self.config.enableSeconds ? ":S" : "");
- self.config.altFormat = "h:i" + (self.config.enableSeconds ? ":S K" : " K");
- }
- else {
- self.config.dateFormat += " H:i" + (self.config.enableSeconds ? ":S" : "");
- self.config.altFormat = `h:i${self.config.enableSeconds ? ":S" : ""} K`;
- }
- }
- Object.keys(Flatpickr.defaultConfig).forEach(k =>
- self.config[k] = typeof self.config[k] !== "undefined"
- ? self.config[k]
- : Flatpickr.defaultConfig[k]
- );
- }
- function parseDate(date, timeless = false) {
- if (typeof date === "string") {
- date = date.trim();
- if (date === "today") {
- date = new Date();
- timeless = true;
- }
- else if (self.config.parseDate)
- date = self.config.parseDate(date);
- else if (/^\d\d:\d\d/.test(date)) { // time picker
- const m = date.match(/^(\d{1,2})[:\s]?(\d\d)?[:\s]?(\d\d)?/);
- date = new Date();
- date.setHours(m[1], m[2] || 0, m[2] || 0);
- }
- else if (/Z$/.test(date) || /GMT$/.test(date)) // datestrings w/ timezone
- date = new Date(date);
- else if (/(\d+)/g.test(date)) {
- const d = date.match(/(\d+)/g);
- date = new Date(
- `${d[0]}/${d[1] || 1}/${d[2] || 1} ${d[3] || 0}:${d[4] || 0}:${d[5] || 0}`
- );
- }
- }
- if (!(date instanceof Date) || !date.getTime()) {
- console.warn(`flatpickr: invalid date ${date}`);
- console.info(self.element);
- return null;
- }
- if (self.config.utc && !date.fp_isUTC)
- date = date.fp_toUTC();
- if (timeless)
- date.setHours(0, 0, 0, 0);
- return date;
- }
- function positionCalendar() {
- const calendarHeight = self.calendarContainer.offsetHeight,
- input = (self.altInput || self.input),
- inputBounds = input.getBoundingClientRect(),
- distanceFromBottom = window.innerHeight - inputBounds.bottom + input.offsetHeight;
- let top,
- left = (window.pageXOffset + inputBounds.left);
- if (distanceFromBottom < calendarHeight) {
- top = (window.pageYOffset - calendarHeight + inputBounds.top) - 2;
- self.calendarContainer.classList.remove("arrowTop");
- self.calendarContainer.classList.add("arrowBottom");
- }
- else {
- top = (window.pageYOffset + input.offsetHeight + inputBounds.top) + 2;
- self.calendarContainer.classList.remove("arrowBottom");
- self.calendarContainer.classList.add("arrowTop");
- }
- if (!self.config.inline) {
- self.calendarContainer.style.top = `${top}px`;
- self.calendarContainer.style.left = `${left}px`;
- }
- }
- function redraw() {
- if (self.config.noCalendar || self.isMobile)
- return;
- buildWeekdays();
- updateNavigationCurrentMonth();
- buildDays();
- }
- function selectDate(e) {
- e.preventDefault();
- e.stopPropagation();
- if (self.config.allowInput && (e.target === self.altInput || e.target === self.input) && e.which === 13)
- self.setDate((self.altInput || self.input).value);
- else if (e.target.classList.contains("flatpickr-day") && !e.target.classList.contains("disabled")) {
- const isPrevMonthDay = e.target.classList.contains("prevMonthDay"),
- isNextMonthDay = e.target.classList.contains("nextMonthDay");
- if (isPrevMonthDay || isNextMonthDay)
- changeMonth(+isNextMonthDay - isPrevMonthDay);
- self.selectedDateObj = parseDate(new Date(self.currentYear, self.currentMonth, e.target.innerHTML));
- updateValue(e);
- buildDays();
- triggerEvent("Change");
- if (!self.config.enableTime)
- self.close();
- }
- }
- function set(option, value) {
- self.config[option] = value;
- jumpToDate();
- }
- function setDate(date, triggerChange) {
- date = parseDate(date);
- if (date instanceof Date && date.getTime()) {
- self.selectedDateObj = date;
- jumpToDate(self.selectedDateObj);
- updateValue(false);
- if (triggerChange)
- triggerEvent("Change");
- }
- else
- (self.altInput || self.input).value = "";
- }
- function setupDates() {
- self.now = new Date();
- if (self.config.defaultDate || self.input.value)
- self.selectedDateObj = parseDate(self.config.defaultDate || self.input.value);
- if (self.config.minDate)
- self.config.minDate = parseDate(self.config.minDate, true);
- if (self.config.maxDate)
- self.config.maxDate = parseDate(self.config.maxDate, true);
- const initialDate = (self.selectedDateObj || self.config.defaultDate ||
- self.config.minDate || new Date()
- );
- self.currentYear = initialDate.getFullYear();
- self.currentMonth = initialDate.getMonth();
- }
- function setupFormats() {
- self.formats = {
- // weekday name, short, e.g. Thu
- D: date => Flatpickr.l10n.weekdays.shorthand[self.formats.w(date)],
- // full month name e.g. January
- F: date => self.utils.monthToStr(self.formats.n(date) - 1, false),
- // hours with leading zero e.g. 03
- H: date => pad(date.getHours()),
- // day (1-30) with ordinal suffix e.g. 1st, 2nd
- J: date => date.getDate() + Flatpickr.l10n.ordinal(date.getDate()),
- // AM/PM
- K: date => date.getHours() > 11 ? "PM" : "AM",
- // shorthand month e.g. Jan, Sep, Oct, etc
- M: date => self.utils.monthToStr(date.getMonth(), true),
- // seconds 00-59
- S: date => pad(date.getSeconds()),
- // unix timestamp
- U: date => date.getTime() / 1000,
- // full year e.g. 2016
- Y: date => date.getFullYear(),
- // day in month, padded (01-30)
- d: date => pad(self.formats.j(date)),
- // hour from 1-12 (am/pm)
- h: date => date.getHours() % 12 ? date.getHours() % 12 : 12,
- // minutes, padded with leading zero e.g. 09
- i: date => pad(date.getMinutes()),
- // day in month (1-30)
- j: date => date.getDate(),
- // weekday name, full, e.g. Thursday
- l: date => Flatpickr.l10n.weekdays.longhand[self.formats.w(date)],
- // padded month number (01-12)
- m: date => pad(self.formats.n(date)),
- // the month number (1-12)
- n: date => date.getMonth() + 1,
- // seconds 0-59
- s: date => date.getSeconds(),
- // number of the day of the week
- w: date => date.getDay(),
- // last two digits of year e.g. 16 for 2016
- y: date => String(self.formats.Y(date)).substring(2)
- };
- }
- function setupHelperFunctions() {
- self.utils = {
- getDaysinMonth: (month = self.currentMonth, yr = self.currentYear) => {
- if (month === 1 && ((yr % 4 === 0) && (yr % 100 !== 0)) || (yr % 400 === 0))
- return 29;
- return Flatpickr.l10n.daysInMonth[month];
- },
- monthToStr: (monthNumber, short = self.config.shorthandCurrentMonth) =>
- Flatpickr.l10n.months[(`${short ? "short" : "long"}hand`)][monthNumber],
- };
- }
- function setupInputs() {
- self.input = self.config.wrap ? self.element.querySelector("[data-input]") : self.element;
- self.input.classList.add("flatpickr-input");
- if (self.config.altInput) {
- // replicate self.element
- self.altInput = createElement(self.input.nodeName, "flatpickr-input " + self.config.altInputClass);
- self.altInput.placeholder = self.input.placeholder;
- self.altInput.type = "text";
- self.input.type = "hidden";
- self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
- }
- if (!self.config.allowInput)
- (self.altInput || self.input).setAttribute("readonly", "readonly");
- }
- function setupMobile() {
- const inputType = self.config.enableTime
- ? (self.config.noCalendar ? "time" : "datetime-local")
- : "date";
- self.mobileInput = createElement("input", "flatpickr-input");
- self.mobileInput.step = "any";
- self.mobileInput.tabIndex = -1;
- self.mobileInput.type = inputType;
- if (self.selectedDateObj) {
- const formatStr = inputType === "datetime-local" ? "Y-m-d\\TH:i:S" :
- inputType === "date" ? "Y-m-d" : "H:i:S";
- const mobileFormattedDate = formatDate(formatStr, self.selectedDateObj);
- self.mobileInput.defaultValue = self.mobileInput.value = mobileFormattedDate;
- }
- if (self.config.minDate)
- self.mobileInput.min = formatDate("Y-m-d", self.config.minDate);
- if (self.config.maxDate)
- self.mobileInput.max = formatDate("Y-m-d", self.config.maxDate);
- self.input.type = "hidden";
- if (self.config.altInput)
- self.altInput.type = "hidden";
- try {
- self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
- }
- catch (e) {
- //
- }
- self.mobileInput.addEventListener("change", e => {
- self.setDate(e.target.value);
- triggerEvent("Change");
- triggerEvent("Close");
- });
- }
- function toggle() {
- if (self.isOpen)
- self.close();
- else
- self.open();
- }
- function triggerEvent(event) {
- if (self.config["on" + event])
- self.config["on" + event](self.selectedDateObj, self.input.value, self);
- }
- function updateNavigationCurrentMonth() {
- self.currentMonthElement.textContent = self.utils.monthToStr(self.currentMonth) + " ";
- self.currentYearElement.value = self.currentYear;
- }
- function updateValue(readTimeInput = true) {
- if (self.config.noCalendar && !self.selectedDateObj)
- // picking time only and method triggered from picker
- self.selectedDateObj = new Date();
- else if (!self.selectedDateObj)
- return;
- if (self.config.enableTime && !self.isMobile) {
- let hours,
- minutes,
- seconds;
- if (readTimeInput) {
- // update time
- hours = (parseInt(self.hourElement.value, 10) || 0);
- minutes = (60 + (parseInt(self.minuteElement.value, 10) || 0)) % 60;
- if (self.config.enableSeconds)
- seconds = (60 + (parseInt(self.secondElement.value, 10)) || 0) % 60;
- if (!self.config.time_24hr)
- // the real number of hours for the date object
- hours = hours % 12 + 12 * (self.amPM.innerHTML === "PM");
- self.selectedDateObj.setHours(hours, minutes, seconds || 0, 0);
- }
- else {
- hours = self.selectedDateObj.getHours();
- minutes = self.selectedDateObj.getMinutes();
- seconds = self.selectedDateObj.getSeconds();
- }
- self.hourElement.value = pad(
- !self.config.time_24hr ? (12 + hours) % 12 + 12 * (hours % 12 === 0) : hours
- );
- self.minuteElement.value = pad(minutes);
- if (self.secondElement !== undefined)
- self.secondElement.value = pad(seconds);
- }
- self.input.value = formatDate(self.config.dateFormat, self.selectedDateObj);
- if (self.altInput)
- self.altInput.value = formatDate(self.config.altFormat, self.selectedDateObj);
- triggerEvent("ValueUpdate");
- }
- function yearScroll(e) {
- e.preventDefault();
- const delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.deltaY)));
- self.currentYear = e.target.value = parseInt(e.target.value, 10) + delta;
- self.redraw();
- }
- function createElement(tag, className = "", content = "") {
- const e = document.createElement(tag);
- e.className = className;
- if (content)
- e.textContent = content;
- return e;
- }
- function debounce(func, wait, immediate) {
- let timeout;
- return function (...args) {
- const context = this;
- const later = function () {
- timeout = null;
- if (!immediate)
- func.apply(context, args);
- };
- clearTimeout(timeout);
- timeout = setTimeout(later, wait);
- if (immediate && !timeout)
- func.apply(context, args);
- };
- }
- function equalDates(date1, date2) {
- return date1.getDate() === date2.getDate() &&
- date1.getMonth() === date2.getMonth() &&
- date1.getFullYear() === date2.getFullYear();
- }
- function timeWrapper(e) {
- e.preventDefault();
- if (e && e.type !== "keydown")
- e.target.blur();
- if (e.target.className === "flatpickr-am-pm") {
- e.target.textContent = ["AM", "PM"][(e.target.textContent === "AM") | 0];
- e.stopPropagation();
- return;
- }
- const min = parseInt(e.target.min, 10),
- max = parseInt(e.target.max, 10),
- step = parseInt(e.target.step, 10),
- value = parseInt(e.target.value, 10);
- let newValue = value;
- if (e.type === "wheel")
- newValue = value + step * (Math.max(-1, Math.min(1, (e.wheelDelta || -e.deltaY))));
- else if (e.type === "keydown")
- newValue = value + step * (e.which === 38 ? 1 : -1);
- if (newValue <= min)
- newValue = max - step;
- else if (newValue >= max)
- newValue = min + step;
- e.target.value = pad(newValue);
- }
- init();
- return self;
- }
- Flatpickr.defaultConfig = {
- /* if true, dates will be parsed, formatted, and displayed in UTC.
- preloading date strings w/ timezones is recommended but not necessary */
- utc: false,
- // wrap: see https://chmln.github.io/flatpickr/#strap
- wrap: false,
- // enables week numbers
- weekNumbers: false,
- allowInput: false,
- /*
- clicking on input opens the date(time)picker.
- disable if you wish to open the calendar manually with .open()
- */
- clickOpens: true,
- // display time picker in 24 hour mode
- time_24hr: false,
- // enables the time picker functionality
- enableTime: false,
- // noCalendar: true will hide the calendar. use for a time picker along w/ enableTime
- noCalendar: false,
- // more date format chars at https://chmln.github.io/flatpickr/#dateformat
- dateFormat: "Y-m-d",
- // altInput - see https://chmln.github.io/flatpickr/#altinput
- altInput: null,
- // the created altInput element will have this class.
- altInputClass: "",
- // same as dateFormat, but for altInput
- altFormat: "F j, Y", // defaults to e.g. June 10, 2016
- // defaultDate - either a datestring or a date object. used for datetimepicker"s initial value
- defaultDate: null,
- // the minimum date that user can pick (inclusive)
- minDate: null,
- // the maximum date that user can pick (inclusive)
- maxDate: null,
- // dateparser that transforms a given string to a date object
- parseDate: null,
- // see https://chmln.github.io/flatpickr/#disable
- enable: [],
- // see https://chmln.github.io/flatpickr/#disable
- disable: [],
- // display the short version of month names - e.g. Sep instead of September
- shorthandCurrentMonth: false,
- // displays calendar inline. see https://chmln.github.io/flatpickr/#inline-calendar
- inline: false,
- // position calendar inside wrapper and next to the input element
- // leave at false unless you know what you"re doing
- static: false,
- // code for previous/next icons. this is where you put your custom icon code e.g. fontawesome
- prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
- nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
- // enables seconds in the time picker
- enableSeconds: false,
- // step size used when scrolling/incrementing the hour element
- hourIncrement: 1,
- // step size used when scrolling/incrementing the minute element
- minuteIncrement: 5,
- // disable native mobile datetime input support
- disableMobile: false,
- // onChange callback when user selects a date or time
- onChange: null, // function (dateObj, dateStr) {}
- // called every time calendar is opened
- onOpen: null, // function (dateObj, dateStr) {}
- // called every time calendar is closed
- onClose: null, // function (dateObj, dateStr) {}
- // called after calendar is ready
- onReady: null, // function (dateObj, dateStr) {}
- onValueUpdate: null
- };
- Flatpickr.l10n = {
- weekdays: {
- shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
- longhand: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
- },
- months: {
- shorthand: [
- "Jan", "Feb", "Mar", "Apr",
- "May", "Jun", "Jul", "Aug",
- "Sep", "Oct", "Nov", "Dec"
- ],
- longhand: [
- "January", "February", "March", "April",
- "May", "June", "July", "August",
- "September", "October", "November", "December"
- ]
- },
- daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
- firstDayOfWeek: 0,
- ordinal: (nth) => {
- const s = nth % 100;
- if (s > 3 && s < 21) return "th";
- switch (s % 10) {
- case 1: return "st";
- case 2: return "nd";
- case 3: return "rd";
- default: return "th";
- }
- },
- weekAbbreviation: "Wk",
- scrollTitle: "Scroll to increment",
- toggleTitle: "Click to toggle"
- };
- Flatpickr.localize = function (l10n) {
- Object.keys(l10n).forEach(k => Flatpickr.l10n[k] = l10n[k]);
- };
- function _flatpickr(nodeList, config) {
- let instances = [];
- for (let i = 0; i < nodeList.length; i++) {
- if (nodeList[i]._flatpickr)
- nodeList[i]._flatpickr.destroy();
- try {
- nodeList[i]._flatpickr = new Flatpickr(nodeList[i], config || {});
- instances.push(nodeList[i]._flatpickr);
- }
- catch (e) {
- console.warn(e, e.stack);
- }
- }
- return instances.length === 1 ? instances[0] : instances;
- }
- HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function (config) {
- return _flatpickr(this, config);
- };
- HTMLElement.prototype.flatpickr = function (config) {
- return _flatpickr([this], config);
- };
- if (typeof jQuery !== "undefined") {
- jQuery.fn.flatpickr = function (config) {
- return _flatpickr(this, config);
- };
- }
- Date.prototype.fp_incr = function (days) {
- return new Date(
- this.getFullYear(),
- this.getMonth(),
- this.getDate() + parseInt(days, 10)
- );
- };
- Date.prototype.fp_isUTC = false;
- Date.prototype.fp_toUTC = function () {
- const newDate = new Date(this.getTime() + this.getTimezoneOffset() * 60000);
- newDate.fp_isUTC = true;
- return newDate;
- };
- Flatpickr.prototype.getWeek = function (givenDate) {
- const date = new Date(givenDate.getTime());
- date.setHours(0, 0, 0, 0);
- // Thursday in current week decides the year.
- date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
- // January 4 is always in week 1.
- const week1 = new Date(date.getFullYear(), 0, 4);
- // Adjust to Thursday in week 1 and count number of weeks from date to week1.
- return 1 +
- Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 +
- (week1.getDay() + 6) % 7) / 7);
- };
- // IE9 classList polyfill
- if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== "undefined") {
- Object.defineProperty(HTMLElement.prototype, "classList", {
- get: function () {
- let self = this;
- function update(fn) {
- return function (value) {
- let classes = self.className.split(/\s+/),
- index = classes.indexOf(value);
- fn(classes, index, value);
- self.className = classes.join(" ");
- };
- }
- let ret = {
- add: update((classes, index, value) => {
- ~index || classes.push(value);
- }),
- remove: update((classes, index) => {
- ~index && classes.splice(index, 1);
- }),
- toggle: update((classes, index, value) => {
- ~index ? classes.splice(index, 1) : classes.push(value);
- }),
- contains: value => !!~self.className.split(/\s+/).indexOf(value),
- item: function (i) {
- return self.className.split(/\s+/)[i] || null;
- }
- };
- Object.defineProperty(ret, "length", {
- get: function () {
- return self.className.split(/\s+/).length;
- }
- });
- return ret;
- }
- });
- }
- if (typeof module !== "undefined")
- module.exports = Flatpickr;
|