UNPKG

primeng

Version:

[![npm version](https://badge.fury.io/js/primeng.svg)](https://badge.fury.io/js/primeng) [![npm downloads](https://img.shields.io/npm/dm/primeng.svg)](https://www.npmjs.com/package/primeng) [![Actions CI](https://github.com/primefaces/primeng/workflows/No

1,522 lines (1,521 loc) 178 kB
import { trigger, state, style, transition, animate } from '@angular/animations'; import * as i2 from '@angular/common'; import { DOCUMENT, CommonModule } from '@angular/common'; import * as i0 from '@angular/core'; import { forwardRef, EventEmitter, booleanAttribute, numberAttribute, Component, ChangeDetectionStrategy, ViewEncapsulation, Inject, Input, Output, ContentChildren, ViewChild, NgModule } from '@angular/core'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import * as i1 from 'primeng/api'; import { TranslationKeys, PrimeTemplate, SharedModule } from 'primeng/api'; import * as i3 from 'primeng/button'; import { ButtonModule } from 'primeng/button'; import { DomHandler, ConnectedOverlayScrollHandler } from 'primeng/dom'; import * as i4 from 'primeng/ripple'; import { RippleModule } from 'primeng/ripple'; import { UniqueComponentId, ObjectUtils, ZIndexUtils } from 'primeng/utils'; import { ChevronLeftIcon } from 'primeng/icons/chevronleft'; import { ChevronRightIcon } from 'primeng/icons/chevronright'; import { ChevronUpIcon } from 'primeng/icons/chevronup'; import { ChevronDownIcon } from 'primeng/icons/chevrondown'; import { TimesIcon } from 'primeng/icons/times'; import { CalendarIcon } from 'primeng/icons/calendar'; import * as i5 from 'primeng/autofocus'; import { AutoFocusModule } from 'primeng/autofocus'; const CALENDAR_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => Calendar), multi: true }; /** * Calendar also known as DatePicker, is a form component to work with dates. * @group Components */ class Calendar { document; el; renderer; cd; zone; config; overlayService; iconDisplay = 'button'; /** * Inline style of the component. * @group Props */ style; /** * Style class of the component. * @group Props */ styleClass; /** * Inline style of the input field. * @group Props */ inputStyle; /** * Identifier of the focus input to match a label defined for the component. * @group Props */ inputId; /** * Name of the input element. * @group Props */ name; /** * Style class of the input field. * @group Props */ inputStyleClass; /** * Placeholder text for the input. * @group Props */ placeholder; /** * Establishes relationships between the component and label(s) where its value should be one or more element IDs. * @group Props */ ariaLabelledBy; /** * Defines a string that labels the input for accessibility. * @group Props */ ariaLabel; /** * Defines a string that labels the icon button for accessibility. * @group Props */ iconAriaLabel; /** * When specified, disables the component. * @group Props */ disabled; /** * Format of the date which can also be defined at locale settings. * @group Props */ dateFormat; /** * Separator for multiple selection mode. * @group Props */ multipleSeparator = ','; /** * Separator for joining start and end dates on range selection mode. * @group Props */ rangeSeparator = '-'; /** * When enabled, displays the calendar as inline. Default is false for popup mode. * @group Props */ inline = false; /** * Whether to display dates in other months (non-selectable) at the start or end of the current month. To make these days selectable use the selectOtherMonths option. * @group Props */ showOtherMonths = true; /** * Whether days in other months shown before or after the current month are selectable. This only applies if the showOtherMonths option is set to true. * @group Props */ selectOtherMonths; /** * When enabled, displays a button with icon next to input. * @group Props */ showIcon; /** * Icon of the calendar button. * @group Props */ icon; /** * Target element to attach the overlay, valid values are "body" or a local ng-template variable of another element (note: use binding with brackets for template variables, e.g. [appendTo]="mydiv" for a div element having#mydiv as variable name). * @group Props */ appendTo; /** * When specified, prevents entering the date manually with keyboard. * @group Props */ readonlyInput; /** * The cutoff year for determining the century for a date. * @group Props */ shortYearCutoff = '+10'; /** * Whether the month should be rendered as a dropdown instead of text. * @group Props * @deprecated Navigator is always on. */ monthNavigator; /** * Whether the year should be rendered as a dropdown instead of text. * @group Props * @deprecated Navigator is always on. */ yearNavigator; /** * Specifies 12 or 24 hour format. * @group Props */ hourFormat = '24'; /** * Whether to display timepicker only. * @group Props */ timeOnly; /** * Years to change per step in yearpicker. * @group Props */ stepYearPicker = 10; /** * Hours to change per step. * @group Props */ stepHour = 1; /** * Minutes to change per step. * @group Props */ stepMinute = 1; /** * Seconds to change per step. * @group Props */ stepSecond = 1; /** * Whether to show the seconds in time picker. * @group Props */ showSeconds = false; /** * When present, it specifies that an input field must be filled out before submitting the form. * @group Props */ required; /** * When disabled, datepicker will not be visible with input focus. * @group Props */ showOnFocus = true; /** * When enabled, calendar will show week numbers. * @group Props */ showWeek = false; /** * When enabled, calendar will start week numbers from first day of the year. * @group Props */ startWeekFromFirstDayOfYear = false; /** * When enabled, a clear icon is displayed to clear the value. * @group Props */ showClear = false; /** * Type of the value to write back to ngModel, default is date and alternative is string. * @group Props */ dataType = 'date'; /** * Defines the quantity of the selection, valid values are "single", "multiple" and "range". * @group Props */ selectionMode = 'single'; /** * Maximum number of selectable dates in multiple mode. * @group Props */ maxDateCount; /** * Whether to display today and clear buttons at the footer * @group Props */ showButtonBar; /** * Style class of the today button. * @group Props */ todayButtonStyleClass = 'p-button-text'; /** * Style class of the clear button. * @group Props */ clearButtonStyleClass = 'p-button-text'; /** * When present, it specifies that the component should automatically get focus on load. * @group Props */ autofocus; /** * Whether to automatically manage layering. * @group Props */ autoZIndex = true; /** * Base zIndex value to use in layering. * @group Props */ baseZIndex = 0; /** * Style class of the datetimepicker container element. * @group Props */ panelStyleClass; /** * Inline style of the datetimepicker container element. * @group Props */ panelStyle; /** * Keep invalid value when input blur. * @group Props */ keepInvalid = false; /** * Whether to hide the overlay on date selection. * @group Props */ hideOnDateTimeSelect = true; /** * When enabled, calendar overlay is displayed as optimized for touch devices. * @group Props */ touchUI; /** * Separator of time selector. * @group Props */ timeSeparator = ':'; /** * When enabled, can only focus on elements inside the calendar. * @group Props */ focusTrap = true; /** * Transition options of the show animation. * @group Props */ showTransitionOptions = '.12s cubic-bezier(0, 0, 0.2, 1)'; /** * Transition options of the hide animation. * @group Props */ hideTransitionOptions = '.1s linear'; /** * Index of the element in tabbing order. * @group Props */ tabindex; /** * Specifies the input variant of the component. * @group Props */ variant = 'outlined'; /** * The minimum selectable date. * @group Props */ get minDate() { return this._minDate; } set minDate(date) { this._minDate = date; if (this.currentMonth != undefined && this.currentMonth != null && this.currentYear) { this.createMonths(this.currentMonth, this.currentYear); } } /** * The maximum selectable date. * @group Props */ get maxDate() { return this._maxDate; } set maxDate(date) { this._maxDate = date; if (this.currentMonth != undefined && this.currentMonth != null && this.currentYear) { this.createMonths(this.currentMonth, this.currentYear); } } /** * Array with dates that should be disabled (not selectable). * @group Props */ get disabledDates() { return this._disabledDates; } set disabledDates(disabledDates) { this._disabledDates = disabledDates; if (this.currentMonth != undefined && this.currentMonth != null && this.currentYear) { this.createMonths(this.currentMonth, this.currentYear); } } /** * Array with weekday numbers that should be disabled (not selectable). * @group Props */ get disabledDays() { return this._disabledDays; } set disabledDays(disabledDays) { this._disabledDays = disabledDays; if (this.currentMonth != undefined && this.currentMonth != null && this.currentYear) { this.createMonths(this.currentMonth, this.currentYear); } } /** * The range of years displayed in the year drop-down in (nnnn:nnnn) format such as (2000:2020). * @group Props * @deprecated Years are based on decades by default. */ get yearRange() { return this._yearRange; } set yearRange(yearRange) { this._yearRange = yearRange; if (yearRange) { const years = yearRange.split(':'); const yearStart = parseInt(years[0]); const yearEnd = parseInt(years[1]); this.populateYearOptions(yearStart, yearEnd); } } /** * Whether to display timepicker. * @group Props */ get showTime() { return this._showTime; } set showTime(showTime) { this._showTime = showTime; if (this.currentHour === undefined) { this.initTime(this.value || new Date()); } this.updateInputfield(); } /** * An array of options for responsive design. * @group Props */ get responsiveOptions() { return this._responsiveOptions; } set responsiveOptions(responsiveOptions) { this._responsiveOptions = responsiveOptions; this.destroyResponsiveStyleElement(); this.createResponsiveStyle(); } /** * Number of months to display. * @group Props */ get numberOfMonths() { return this._numberOfMonths; } set numberOfMonths(numberOfMonths) { this._numberOfMonths = numberOfMonths; this.destroyResponsiveStyleElement(); this.createResponsiveStyle(); } /** * Defines the first of the week for various date calculations. * @group Props */ get firstDayOfWeek() { return this._firstDayOfWeek; } set firstDayOfWeek(firstDayOfWeek) { this._firstDayOfWeek = firstDayOfWeek; this.createWeekDays(); } /** * Option to set calendar locale. * @group Props * @deprecated Locale property has no effect, use new i18n API instead. */ set locale(newLocale) { console.warn('Locale property has no effect, use new i18n API instead.'); } /** * Type of view to display, valid values are "date" for datepicker and "month" for month picker. * @group Props */ get view() { return this._view; } set view(view) { this._view = view; this.currentView = this._view; } /** * Set the date to highlight on first opening if the field is blank. * @group Props */ get defaultDate() { return this._defaultDate; } set defaultDate(defaultDate) { this._defaultDate = defaultDate; if (this.initialized) { const date = defaultDate || new Date(); this.currentMonth = date.getMonth(); this.currentYear = date.getFullYear(); this.initTime(date); this.createMonths(this.currentMonth, this.currentYear); } } get inputClass() { return { 'p-inputtext p-component': true, 'p-variant-filled': this.variant === 'filled' || this.config.inputStyle() === 'filled' }; } /** * Callback to invoke on focus of input field. * @param {Event} event - browser event. * @group Emits */ onFocus = new EventEmitter(); /** * Callback to invoke on blur of input field. * @param {Event} event - browser event. * @group Emits */ onBlur = new EventEmitter(); /** * Callback to invoke when date panel closed. * @param {Event} event - Mouse event * @group Emits */ onClose = new EventEmitter(); /** * Callback to invoke on date select. * @param {Date} date - date value. * @group Emits */ onSelect = new EventEmitter(); /** * Callback to invoke when input field cleared. * @group Emits */ onClear = new EventEmitter(); /** * Callback to invoke when input field is being typed. * @param {Event} event - browser event * @group Emits */ onInput = new EventEmitter(); /** * Callback to invoke when today button is clicked. * @param {Date} date - today as a date instance. * @group Emits */ onTodayClick = new EventEmitter(); /** * Callback to invoke when clear button is clicked. * @param {Event} event - browser event. * @group Emits */ onClearClick = new EventEmitter(); /** * Callback to invoke when a month is changed using the navigators. * @param {CalendarMonthChangeEvent} event - custom month change event. * @group Emits */ onMonthChange = new EventEmitter(); /** * Callback to invoke when a year is changed using the navigators. * @param {CalendarYearChangeEvent} event - custom year change event. * @group Emits */ onYearChange = new EventEmitter(); /** * Callback to invoke when clicked outside of the date panel. * @group Emits */ onClickOutside = new EventEmitter(); /** * Callback to invoke when datepicker panel is shown. * @group Emits */ onShow = new EventEmitter(); templates; containerViewChild; inputfieldViewChild; set content(content) { this.contentViewChild = content; if (this.contentViewChild) { if (this.isMonthNavigate) { Promise.resolve(null).then(() => this.updateFocus()); this.isMonthNavigate = false; } else { if (!this.focus && !this.inline) { this.initFocusableCell(); } } } } contentViewChild; value; dates; months; weekDays; currentMonth; currentYear; currentHour; currentMinute; currentSecond; pm; mask; maskClickListener; overlay; responsiveStyleElement; overlayVisible; onModelChange = () => { }; onModelTouched = () => { }; calendarElement; timePickerTimer; documentClickListener; animationEndListener; ticksTo1970; yearOptions; focus; isKeydown; filled; inputFieldValue = null; _minDate; _maxDate; _showTime; _yearRange; preventDocumentListener; dateTemplate; headerTemplate; footerTemplate; disabledDateTemplate; decadeTemplate; previousIconTemplate; nextIconTemplate; triggerIconTemplate; clearIconTemplate; decrementIconTemplate; incrementIconTemplate; inputIconTemplate; _disabledDates; _disabledDays; selectElement; todayElement; focusElement; scrollHandler; documentResizeListener; navigationState = null; isMonthNavigate; initialized; translationSubscription; _locale; _responsiveOptions; currentView; attributeSelector; panelId; _numberOfMonths = 1; _firstDayOfWeek; _view = 'date'; preventFocus; _defaultDate; _focusKey = null; window; get locale() { return this._locale; } get iconButtonAriaLabel() { return this.iconAriaLabel ? this.iconAriaLabel : this.getTranslation('chooseDate'); } get prevIconAriaLabel() { return this.currentView === 'year' ? this.getTranslation('prevDecade') : this.currentView === 'month' ? this.getTranslation('prevYear') : this.getTranslation('prevMonth'); } get nextIconAriaLabel() { return this.currentView === 'year' ? this.getTranslation('nextDecade') : this.currentView === 'month' ? this.getTranslation('nextYear') : this.getTranslation('nextMonth'); } constructor(document, el, renderer, cd, zone, config, overlayService) { this.document = document; this.el = el; this.renderer = renderer; this.cd = cd; this.zone = zone; this.config = config; this.overlayService = overlayService; this.window = this.document.defaultView; } ngOnInit() { this.attributeSelector = UniqueComponentId(); this.panelId = this.attributeSelector + '_panel'; const date = this.defaultDate || new Date(); this.createResponsiveStyle(); this.currentMonth = date.getMonth(); this.currentYear = date.getFullYear(); this.yearOptions = []; this.currentView = this.view; if (this.view === 'date') { this.createWeekDays(); this.initTime(date); this.createMonths(this.currentMonth, this.currentYear); this.ticksTo1970 = ((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000; } this.translationSubscription = this.config.translationObserver.subscribe(() => { this.createWeekDays(); this.cd.markForCheck(); }); this.initialized = true; } ngAfterContentInit() { this.templates.forEach((item) => { switch (item.getType()) { case 'date': this.dateTemplate = item.template; break; case 'decade': this.decadeTemplate = item.template; break; case 'disabledDate': this.disabledDateTemplate = item.template; break; case 'header': this.headerTemplate = item.template; break; case 'inputicon': this.inputIconTemplate = item.template; break; case 'previousicon': this.previousIconTemplate = item.template; break; case 'nexticon': this.nextIconTemplate = item.template; break; case 'triggericon': this.triggerIconTemplate = item.template; break; case 'clearicon': this.clearIconTemplate = item.template; break; case 'decrementicon': this.decrementIconTemplate = item.template; break; case 'incrementicon': this.incrementIconTemplate = item.template; break; case 'footer': this.footerTemplate = item.template; break; default: this.dateTemplate = item.template; break; } }); } ngAfterViewInit() { if (this.inline) { this.contentViewChild && this.contentViewChild.nativeElement.setAttribute(this.attributeSelector, ''); if (!this.disabled && !this.inline) { this.initFocusableCell(); if (this.numberOfMonths === 1) { if (this.contentViewChild && this.contentViewChild.nativeElement) { this.contentViewChild.nativeElement.style.width = DomHandler.getOuterWidth(this.containerViewChild?.nativeElement) + 'px'; } } } } } getTranslation(option) { return this.config.getTranslation(option); } populateYearOptions(start, end) { this.yearOptions = []; for (let i = start; i <= end; i++) { this.yearOptions.push(i); } } createWeekDays() { this.weekDays = []; let dayIndex = this.getFirstDateOfWeek(); let dayLabels = this.getTranslation(TranslationKeys.DAY_NAMES_MIN); for (let i = 0; i < 7; i++) { this.weekDays.push(dayLabels[dayIndex]); dayIndex = dayIndex == 6 ? 0 : ++dayIndex; } } monthPickerValues() { let monthPickerValues = []; for (let i = 0; i <= 11; i++) { monthPickerValues.push(this.config.getTranslation('monthNamesShort')[i]); } return monthPickerValues; } yearPickerValues() { let yearPickerValues = []; let base = this.currentYear - (this.currentYear % this.stepYearPicker); for (let i = 0; i < this.stepYearPicker; i++) { yearPickerValues.push(base + i); } return yearPickerValues; } createMonths(month, year) { this.months = this.months = []; for (let i = 0; i < this.numberOfMonths; i++) { let m = month + i; let y = year; if (m > 11) { m = (m % 11) - 1; y = year + 1; } this.months.push(this.createMonth(m, y)); } } getWeekNumber(date) { let checkDate = new Date(date.getTime()); if (this.startWeekFromFirstDayOfYear) { let firstDayOfWeek = +this.getFirstDateOfWeek(); checkDate.setDate(checkDate.getDate() + 6 + firstDayOfWeek - checkDate.getDay()); } else { checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); } let time = checkDate.getTime(); checkDate.setMonth(0); checkDate.setDate(1); return Math.floor(Math.round((time - checkDate.getTime()) / 86400000) / 7) + 1; } createMonth(month, year) { let dates = []; let firstDay = this.getFirstDayOfMonthIndex(month, year); let daysLength = this.getDaysCountInMonth(month, year); let prevMonthDaysLength = this.getDaysCountInPrevMonth(month, year); let dayNo = 1; let today = new Date(); let weekNumbers = []; let monthRows = Math.ceil((daysLength + firstDay) / 7); for (let i = 0; i < monthRows; i++) { let week = []; if (i == 0) { for (let j = prevMonthDaysLength - firstDay + 1; j <= prevMonthDaysLength; j++) { let prev = this.getPreviousMonthAndYear(month, year); week.push({ day: j, month: prev.month, year: prev.year, otherMonth: true, today: this.isToday(today, j, prev.month, prev.year), selectable: this.isSelectable(j, prev.month, prev.year, true) }); } let remainingDaysLength = 7 - week.length; for (let j = 0; j < remainingDaysLength; j++) { week.push({ day: dayNo, month: month, year: year, today: this.isToday(today, dayNo, month, year), selectable: this.isSelectable(dayNo, month, year, false) }); dayNo++; } } else { for (let j = 0; j < 7; j++) { if (dayNo > daysLength) { let next = this.getNextMonthAndYear(month, year); week.push({ day: dayNo - daysLength, month: next.month, year: next.year, otherMonth: true, today: this.isToday(today, dayNo - daysLength, next.month, next.year), selectable: this.isSelectable(dayNo - daysLength, next.month, next.year, true) }); } else { week.push({ day: dayNo, month: month, year: year, today: this.isToday(today, dayNo, month, year), selectable: this.isSelectable(dayNo, month, year, false) }); } dayNo++; } } if (this.showWeek) { weekNumbers.push(this.getWeekNumber(new Date(week[0].year, week[0].month, week[0].day))); } dates.push(week); } return { month: month, year: year, dates: dates, weekNumbers: weekNumbers }; } initTime(date) { this.pm = date.getHours() > 11; if (this.showTime) { this.currentMinute = date.getMinutes(); this.currentSecond = date.getSeconds(); this.setCurrentHourPM(date.getHours()); } else if (this.timeOnly) { this.currentMinute = 0; this.currentHour = 0; this.currentSecond = 0; } } navBackward(event) { if (this.disabled) { event.preventDefault(); return; } this.isMonthNavigate = true; if (this.currentView === 'month') { this.decrementYear(); setTimeout(() => { this.updateFocus(); }, 1); } else if (this.currentView === 'year') { this.decrementYearPickerStep(); setTimeout(() => { this.updateFocus(); }, 1); } else { if (this.currentMonth === 0) { this.currentMonth = 11; this.decrementYear(); } else { this.currentMonth--; } this.onMonthChange.emit({ month: this.currentMonth + 1, year: this.currentYear }); this.createMonths(this.currentMonth, this.currentYear); } } navForward(event) { if (this.disabled) { event.preventDefault(); return; } this.isMonthNavigate = true; if (this.currentView === 'month') { this.incrementYear(); setTimeout(() => { this.updateFocus(); }, 1); } else if (this.currentView === 'year') { this.incrementYearPickerStep(); setTimeout(() => { this.updateFocus(); }, 1); } else { if (this.currentMonth === 11) { this.currentMonth = 0; this.incrementYear(); } else { this.currentMonth++; } this.onMonthChange.emit({ month: this.currentMonth + 1, year: this.currentYear }); this.createMonths(this.currentMonth, this.currentYear); } } decrementYear() { this.currentYear--; let _yearOptions = this.yearOptions; if (this.yearNavigator && this.currentYear < _yearOptions[0]) { let difference = _yearOptions[_yearOptions.length - 1] - _yearOptions[0]; this.populateYearOptions(_yearOptions[0] - difference, _yearOptions[_yearOptions.length - 1] - difference); } } decrementYearPickerStep() { this.currentYear = this.currentYear - this.stepYearPicker; } incrementYearPickerStep() { this.currentYear = this.currentYear + this.stepYearPicker; } incrementYear() { this.currentYear++; let _yearOptions = this.yearOptions; if (this.yearNavigator && this.currentYear > _yearOptions[_yearOptions.length - 1]) { let difference = _yearOptions[_yearOptions.length - 1] - _yearOptions[0]; this.populateYearOptions(_yearOptions[0] + difference, _yearOptions[_yearOptions.length - 1] + difference); } } switchToMonthView(event) { this.setCurrentView('month'); event.preventDefault(); } switchToYearView(event) { this.setCurrentView('year'); event.preventDefault(); } onDateSelect(event, dateMeta) { if (this.disabled || !dateMeta.selectable) { event.preventDefault(); return; } if (this.isMultipleSelection() && this.isSelected(dateMeta)) { this.value = this.value.filter((date, i) => { return !this.isDateEquals(date, dateMeta); }); if (this.value.length === 0) { this.value = null; } this.updateModel(this.value); } else { if (this.shouldSelectDate(dateMeta)) { this.selectDate(dateMeta); } } if (this.hideOnDateTimeSelect && (this.isSingleSelection() || (this.isRangeSelection() && this.value[1]))) { setTimeout(() => { event.preventDefault(); this.hideOverlay(); if (this.mask) { this.disableModality(); } this.cd.markForCheck(); }, 150); } this.updateInputfield(); event.preventDefault(); } shouldSelectDate(dateMeta) { if (this.isMultipleSelection()) return this.maxDateCount != null ? this.maxDateCount > (this.value ? this.value.length : 0) : true; else return true; } onMonthSelect(event, index) { if (this.view === 'month') { this.onDateSelect(event, { year: this.currentYear, month: index, day: 1, selectable: true }); } else { this.currentMonth = index; this.createMonths(this.currentMonth, this.currentYear); this.setCurrentView('date'); this.onMonthChange.emit({ month: this.currentMonth + 1, year: this.currentYear }); } } onYearSelect(event, year) { if (this.view === 'year') { this.onDateSelect(event, { year: year, month: 0, day: 1, selectable: true }); } else { this.currentYear = year; this.setCurrentView('month'); this.onYearChange.emit({ month: this.currentMonth + 1, year: this.currentYear }); } } updateInputfield() { let formattedValue = ''; if (this.value) { if (this.isSingleSelection()) { formattedValue = this.formatDateTime(this.value); } else if (this.isMultipleSelection()) { for (let i = 0; i < this.value.length; i++) { let dateAsString = this.formatDateTime(this.value[i]); formattedValue += dateAsString; if (i !== this.value.length - 1) { formattedValue += this.multipleSeparator + ' '; } } } else if (this.isRangeSelection()) { if (this.value && this.value.length) { let startDate = this.value[0]; let endDate = this.value[1]; formattedValue = this.formatDateTime(startDate); if (endDate) { formattedValue += ' ' + this.rangeSeparator + ' ' + this.formatDateTime(endDate); } } } } this.inputFieldValue = formattedValue; this.updateFilledState(); if (this.inputfieldViewChild && this.inputfieldViewChild.nativeElement) { this.inputfieldViewChild.nativeElement.value = this.inputFieldValue; } } formatDateTime(date) { let formattedValue = this.keepInvalid ? date : null; const isDateValid = this.isValidDateForTimeConstraints(date); if (this.isValidDate(date)) { if (this.timeOnly) { formattedValue = this.formatTime(date); } else { formattedValue = this.formatDate(date, this.getDateFormat()); if (this.showTime) { formattedValue += ' ' + this.formatTime(date); } } } else if (this.dataType === 'string') { formattedValue = date; } formattedValue = isDateValid ? formattedValue : ''; return formattedValue; } formatDateMetaToDate(dateMeta) { return new Date(dateMeta.year, dateMeta.month, dateMeta.day); } formatDateKey(date) { return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`; } setCurrentHourPM(hours) { if (this.hourFormat == '12') { this.pm = hours > 11; if (hours >= 12) { this.currentHour = hours == 12 ? 12 : hours - 12; } else { this.currentHour = hours == 0 ? 12 : hours; } } else { this.currentHour = hours; } } setCurrentView(currentView) { this.currentView = currentView; this.cd.detectChanges(); this.alignOverlay(); } selectDate(dateMeta) { let date = this.formatDateMetaToDate(dateMeta); if (this.showTime) { if (this.hourFormat == '12') { if (this.currentHour === 12) date.setHours(this.pm ? 12 : 0); else date.setHours(this.pm ? this.currentHour + 12 : this.currentHour); } else { date.setHours(this.currentHour); } date.setMinutes(this.currentMinute); date.setSeconds(this.currentSecond); } if (this.minDate && this.minDate > date) { date = this.minDate; this.setCurrentHourPM(date.getHours()); this.currentMinute = date.getMinutes(); this.currentSecond = date.getSeconds(); } if (this.maxDate && this.maxDate < date) { date = this.maxDate; this.setCurrentHourPM(date.getHours()); this.currentMinute = date.getMinutes(); this.currentSecond = date.getSeconds(); } if (this.isSingleSelection()) { this.updateModel(date); } else if (this.isMultipleSelection()) { this.updateModel(this.value ? [...this.value, date] : [date]); } else if (this.isRangeSelection()) { if (this.value && this.value.length) { let startDate = this.value[0]; let endDate = this.value[1]; if (!endDate && date.getTime() >= startDate.getTime()) { endDate = date; } else { startDate = date; endDate = null; } this.updateModel([startDate, endDate]); } else { this.updateModel([date, null]); } } this.onSelect.emit(date); } updateModel(value) { this.value = value; if (this.dataType == 'date') { this.onModelChange(this.value); } else if (this.dataType == 'string') { if (this.isSingleSelection()) { this.onModelChange(this.formatDateTime(this.value)); } else { let stringArrValue = null; if (Array.isArray(this.value)) { stringArrValue = this.value.map((date) => this.formatDateTime(date)); } this.onModelChange(stringArrValue); } } } getFirstDayOfMonthIndex(month, year) { let day = new Date(); day.setDate(1); day.setMonth(month); day.setFullYear(year); let dayIndex = day.getDay() + this.getSundayIndex(); return dayIndex >= 7 ? dayIndex - 7 : dayIndex; } getDaysCountInMonth(month, year) { return 32 - this.daylightSavingAdjust(new Date(year, month, 32)).getDate(); } getDaysCountInPrevMonth(month, year) { let prev = this.getPreviousMonthAndYear(month, year); return this.getDaysCountInMonth(prev.month, prev.year); } getPreviousMonthAndYear(month, year) { let m, y; if (month === 0) { m = 11; y = year - 1; } else { m = month - 1; y = year; } return { month: m, year: y }; } getNextMonthAndYear(month, year) { let m, y; if (month === 11) { m = 0; y = year + 1; } else { m = month + 1; y = year; } return { month: m, year: y }; } getSundayIndex() { let firstDayOfWeek = this.getFirstDateOfWeek(); return firstDayOfWeek > 0 ? 7 - firstDayOfWeek : 0; } isSelected(dateMeta) { if (this.value) { if (this.isSingleSelection()) { return this.isDateEquals(this.value, dateMeta); } else if (this.isMultipleSelection()) { let selected = false; for (let date of this.value) { selected = this.isDateEquals(date, dateMeta); if (selected) { break; } } return selected; } else if (this.isRangeSelection()) { if (this.value[1]) return this.isDateEquals(this.value[0], dateMeta) || this.isDateEquals(this.value[1], dateMeta) || this.isDateBetween(this.value[0], this.value[1], dateMeta); else return this.isDateEquals(this.value[0], dateMeta); } } else { return false; } } isComparable() { return this.value != null && typeof this.value !== 'string'; } isMonthSelected(month) { if (this.isComparable() && !this.isMultipleSelection()) { const [start, end] = this.isRangeSelection() ? this.value : [this.value, this.value]; const selected = new Date(this.currentYear, month, 1); return selected >= start && selected <= (end ?? start); } return false; } isMonthDisabled(month, year) { const yearToCheck = year ?? this.currentYear; for (let day = 1; day < this.getDaysCountInMonth(month, yearToCheck) + 1; day++) { if (this.isSelectable(day, month, yearToCheck, false)) { return false; } } return true; } isYearDisabled(year) { return Array(12) .fill(0) .every((v, month) => this.isMonthDisabled(month, year)); } isYearSelected(year) { if (this.isComparable()) { let value = this.isRangeSelection() ? this.value[0] : this.value; return !this.isMultipleSelection() ? value.getFullYear() === year : false; } return false; } isDateEquals(value, dateMeta) { if (value && ObjectUtils.isDate(value)) return value.getDate() === dateMeta.day && value.getMonth() === dateMeta.month && value.getFullYear() === dateMeta.year; else return false; } isDateBetween(start, end, dateMeta) { let between = false; if (ObjectUtils.isDate(start) && ObjectUtils.isDate(end)) { let date = this.formatDateMetaToDate(dateMeta); return start.getTime() <= date.getTime() && end.getTime() >= date.getTime(); } return between; } isSingleSelection() { return this.selectionMode === 'single'; } isRangeSelection() { return this.selectionMode === 'range'; } isMultipleSelection() { return this.selectionMode === 'multiple'; } isToday(today, day, month, year) { return today.getDate() === day && today.getMonth() === month && today.getFullYear() === year; } isSelectable(day, month, year, otherMonth) { let validMin = true; let validMax = true; let validDate = true; let validDay = true; if (otherMonth && !this.selectOtherMonths) { return false; } if (this.minDate) { if (this.minDate.getFullYear() > year) { validMin = false; } else if (this.minDate.getFullYear() === year && this.currentView != 'year') { if (this.minDate.getMonth() > month) { validMin = false; } else if (this.minDate.getMonth() === month) { if (this.minDate.getDate() > day) { validMin = false; } } } } if (this.maxDate) { if (this.maxDate.getFullYear() < year) { validMax = false; } else if (this.maxDate.getFullYear() === year) { if (this.maxDate.getMonth() < month) { validMax = false; } else if (this.maxDate.getMonth() === month) { if (this.maxDate.getDate() < day) { validMax = false; } } } } if (this.disabledDates) { validDate = !this.isDateDisabled(day, month, year); } if (this.disabledDays) { validDay = !this.isDayDisabled(day, month, year); } return validMin && validMax && validDate && validDay; } isDateDisabled(day, month, year) { if (this.disabledDates) { for (let disabledDate of this.disabledDates) { if (disabledDate.getFullYear() === year && disabledDate.getMonth() === month && disabledDate.getDate() === day) { return true; } } } return false; } isDayDisabled(day, month, year) { if (this.disabledDays) { let weekday = new Date(year, month, day); let weekdayNumber = weekday.getDay(); return this.disabledDays.indexOf(weekdayNumber) !== -1; } return false; } onInputFocus(event) { this.focus = true; if (this.showOnFocus) { this.showOverlay(); } this.onFocus.emit(event); } onInputClick() { if (this.showOnFocus && !this.overlayVisible) { this.showOverlay(); } } onInputBlur(event) { this.focus = false; this.onBlur.emit(event); if (!this.keepInvalid) { this.updateInputfield(); } this.onModelTouched(); } onButtonClick(event, inputfield = this.inputfieldViewChild?.nativeElement) { if (!this.overlayVisible) { inputfield.focus(); this.showOverlay(); } else { this.hideOverlay(); } } clear() { this.inputFieldValue = null; this.value = null; this.onModelChange(this.value); this.onClear.emit(); } onOverlayClick(event) { this.overlayService.add({ originalEvent: event, target: this.el.nativeElement }); } getMonthName(index) { return this.config.getTranslation('monthNames')[index]; } getYear(month) { return this.currentView === 'month' ? this.currentYear : month.year; } switchViewButtonDisabled() { return this.numberOfMonths > 1 || this.disabled; } onPrevButtonClick(event) { this.navigationState = { backward: true, button: true }; this.navBackward(event); } onNextButtonClick(event) { this.navigationState = { backward: false, button: true }; this.navForward(event); } onContainerButtonKeydown(event) { switch (event.which) { //tab case 9: if (!this.inline) { this.trapFocus(event); } if (this.inline) { const headerElements = DomHandler.findSingle(this.containerViewChild?.nativeElement, '.p-datepicker-header'); const element = event.target; if (this.timeOnly) { return; } else { if (element == headerElements.children[headerElements?.children?.length - 1]) { this.initFocusableCell(); } } } break; //escape case 27: this.inputfieldViewChild?.nativeElement.focus(); this.overlayVisible = false; event.preventDefault(); break; default: //Noop break; } } onInputKeydown(event) { this.isKeydown = true; if (event.keyCode === 40 && this.contentViewChild) { this.trapFocus(event); } else if (event.keyCode === 27) { if (this.overlayVisible) { this.inputfieldViewChild?.nativeElement.focus(); this.overlayVisible = false; event.preventDefault(); } } else if (event.keyCode === 13) { if (this.overlayVisible) { this.overlayVisible = false; event.preventDefault(); } } else if (event.keyCode === 9 && this.contentViewChild) { DomHandler.getFocusableElements(this.contentViewChild.nativeElement).forEach((el) => (el.tabIndex = '-1')); if (this.overlayVisible) { this.overlayVisible = false; } } } onDateCellKeydown(event, dateMeta, groupIndex) { const cellContent = event.currentTarget; const cell = cellContent.parentElement; const currentDate = this.formatDateMetaToDate(dateMeta); switch (event.which) { //down arrow case 40: { cellContent.tabIndex = '-1'; let cellIndex = DomHandler.index(cell); let nextRow = cell.parentElement.nextElementSibling; if (nextRow) { let focusCell = nextRow.children[cellIndex].children[0]; if (DomHandler.hasClass(focusCell, 'p-disabled')) { this.navigationState = { backward: false }; this.navForward(event); } else { nextRow.children[cellIndex].children[0].tabIndex = '0'; nextRow.children[cellIndex].children[0].focus(); } } else { this.navigationState = { backward: false }; this.navForward(event); } event.preventDefault(); break; } //up arrow case 38: { cellContent.tabIndex = '-1'; let cellIndex = DomHandler.index(cell); let prevRow = cell.parentElement.previousElementSibling; if (prevRow) { let focusCell = prevRow.children[cellIndex].children[0]; if (DomHandler.hasClass(focusCell, 'p-disabled')) { this.navigationState = { backward: true }; this.navBackward(event); } else { focusCell.tabIndex = '0'; focusCell.focus(); } } else { this.navigationState = { backward: true }; this.navBackward(event); } event.preventDefault(); break; } //left arrow case 37: { cellContent.tabIndex = '-1'; let prevCell = cell.previousElementSibling; if (prevCell) { let focusCell = prevCell.children[0]; if (DomHandler.hasClass(focusCell, 'p-disabled') || Do