primeng
Version:
PrimeNG is an open source UI library for Angular featuring a rich set of 80+ components, a theme designer, various theme alternatives such as Material, Bootstrap, Tailwind, premium templates and professional support. In addition, it integrates with PrimeB
1,538 lines (1,535 loc) • 192 kB
JavaScript
import { trigger, state, transition, style as style$1, animate } from '@angular/animations';
import * as i2 from '@angular/common';
import { CommonModule } from '@angular/common';
import * as i0 from '@angular/core';
import { Injectable, forwardRef, input, EventEmitter, inject, computed, numberAttribute, booleanAttribute, ContentChildren, ContentChild, ViewChild, Output, Input, ViewEncapsulation, ChangeDetectionStrategy, Component, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { uuid, getOuterWidth, isDate, findSingle, getFocusableElements, hasClass, getIndex, find, isNotEmpty, addStyle, appendChild, absolutePosition, relativePosition, addClass, setAttribute, isTouchDevice } from '@primeuix/utils';
import * as i1 from 'primeng/api';
import { TranslationKeys, SharedModule, PrimeTemplate } from 'primeng/api';
import { AutoFocus } from 'primeng/autofocus';
import { BaseInput } from 'primeng/baseinput';
import { Button } from 'primeng/button';
import { blockBodyScroll, unblockBodyScroll, ConnectedOverlayScrollHandler } from 'primeng/dom';
import { ChevronLeftIcon, ChevronRightIcon, ChevronUpIcon, ChevronDownIcon, TimesIcon, CalendarIcon } from 'primeng/icons';
import { InputText } from 'primeng/inputtext';
import { Ripple } from 'primeng/ripple';
import { ZIndexUtils } from 'primeng/utils';
import { style } from '@primeuix/styles/datepicker';
import { BaseStyle } from 'primeng/base';
const theme = /*css*/ `
${style}
/* For PrimeNG */
.p-datepicker.ng-invalid.ng-dirty .p-inputtext {
border-color: dt('inputtext.invalid.border.color');
}
`;
const inlineStyles = {
root: () => ({ position: 'relative' })
};
const classes = {
root: ({ instance }) => [
'p-datepicker p-component p-inputwrapper',
{
'p-invalid': instance.invalid(),
'p-datepicker-fluid': instance.hasFluid,
'p-inputwrapper-filled': instance.$filled(),
'p-variant-filled': instance.$variant() === 'filled',
'p-inputwrapper-focus': instance.focus || instance.overlayVisible,
'p-focus': instance.focus || instance.overlayVisible
}
],
pcInputText: 'p-datepicker-input',
dropdown: 'p-datepicker-dropdown',
inputIconContainer: 'p-datepicker-input-icon-container',
inputIcon: 'p-datepicker-input-icon',
panel: ({ instance }) => [
'p-datepicker-panel p-component',
{
'p-datepicker-panel p-component': true,
'p-datepicker-panel-inline': instance.inline,
'p-disabled': instance.$disabled(),
'p-datepicker-timeonly': instance.timeOnly
}
],
calendarContainer: 'p-datepicker-calendar-container',
calendar: 'p-datepicker-calendar',
header: 'p-datepicker-header',
pcPrevButton: 'p-datepicker-prev-button',
title: 'p-datepicker-title',
selectMonth: 'p-datepicker-select-month',
selectYear: 'p-datepicker-select-year',
decade: 'p-datepicker-decade',
pcNextButton: 'p-datepicker-next-button',
dayView: 'p-datepicker-day-view',
weekHeader: 'p-datepicker-weekheader p-disabled',
weekNumber: 'p-datepicker-weeknumber',
weekLabelContainer: 'p-datepicker-weeklabel-container p-disabled',
weekDayCell: 'p-datepicker-weekday-cell',
weekDay: 'p-datepicker-weekday',
dayCell: ({ date }) => [
'p-datepicker-day-cell',
{
'p-datepicker-other-month': date.otherMonth,
'p-datepicker-today': date.today
}
],
day: ({ instance, date }) => {
let selectedDayClass = '';
if (instance.isRangeSelection() && instance.isSelected(date) && date.selectable) {
const startDate = instance.value[0];
const endDate = instance.value[1];
const isStart = startDate && date.year === startDate.getFullYear() && date.month === startDate.getMonth() && date.day === startDate.getDate();
const isEnd = endDate && date.year === endDate.getFullYear() && date.month === endDate.getMonth() && date.day === endDate.getDate();
selectedDayClass = isStart || isEnd ? 'p-datepicker-day-selected' : 'p-datepicker-day-selected-range';
}
return {
'p-datepicker-day': true,
'p-datepicker-day-selected': !instance.isRangeSelection() && instance.isSelected(date) && date.selectable,
'p-disabled': instance.$disabled() || !date.selectable,
[selectedDayClass]: true
};
},
monthView: 'p-datepicker-month-view',
month: ({ instance, index }) => [
'p-datepicker-month',
{
'p-datepicker-month-selected': instance.isMonthSelected(index),
'p-disabled': instance.isMonthDisabled(index)
}
],
yearView: 'p-datepicker-year-view',
year: ({ instance, year }) => [
'p-datepicker-year',
{
'p-datepicker-year-selected': instance.isYearSelected(year),
'p-disabled': instance.isYearDisabled(year)
}
],
timePicker: 'p-datepicker-time-picker',
hourPicker: 'p-datepicker-hour-picker',
pcIncrementButton: 'p-datepicker-increment-button',
pcDecrementButton: 'p-datepicker-decrement-button',
separator: 'p-datepicker-separator',
minutePicker: 'p-datepicker-minute-picker',
secondPicker: 'p-datepicker-second-picker',
ampmPicker: 'p-datepicker-ampm-picker',
buttonbar: 'p-datepicker-buttonbar',
pcTodayButton: 'p-datepicker-today-button',
pcClearButton: 'p-datepicker-clear-button',
clearIcon: 'p-datepicker-clear-icon'
};
class DatePickerStyle extends BaseStyle {
name = 'datepicker';
theme = theme;
classes = classes;
inlineStyles = inlineStyles;
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DatePickerStyle, deps: null, target: i0.ɵɵFactoryTarget.Injectable });
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DatePickerStyle });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.1.3", ngImport: i0, type: DatePickerStyle, decorators: [{
type: Injectable
}] });
/**
*
* DatePicker is a form component to work with dates.
*
* [Live Demo](https://www.primeng.org/datepicker/)
*
* @module datepickerstyle
*
*/
var DatePickerClasses;
(function (DatePickerClasses) {
/**
* Class name of the root element
*/
DatePickerClasses["root"] = "p-datepicker";
/**
* Class name of the input element
*/
DatePickerClasses["pcInputText"] = "p-datepicker-input";
/**
* Class name of the dropdown element
*/
DatePickerClasses["dropdown"] = "p-datepicker-dropdown";
/**
* Class name of the input icon container element
*/
DatePickerClasses["inputIconContainer"] = "p-datepicker-input-icon-container";
/**
* Class name of the input icon element
*/
DatePickerClasses["inputIcon"] = "p-datepicker-input-icon";
/**
* Class name of the panel element
*/
DatePickerClasses["panel"] = "p-datepicker-panel";
/**
* Class name of the calendar container element
*/
DatePickerClasses["calendarContainer"] = "p-datepicker-calendar-container";
/**
* Class name of the calendar element
*/
DatePickerClasses["calendar"] = "p-datepicker-calendar";
/**
* Class name of the header element
*/
DatePickerClasses["header"] = "p-datepicker-header";
/**
* Class name of the previous button element
*/
DatePickerClasses["pcPrevButton"] = "p-datepicker-prev-button";
/**
* Class name of the title element
*/
DatePickerClasses["title"] = "p-datepicker-title";
/**
* Class name of the select month element
*/
DatePickerClasses["selectMonth"] = "p-datepicker-select-month";
/**
* Class name of the select year element
*/
DatePickerClasses["selectYear"] = "p-datepicker-select-year";
/**
* Class name of the decade element
*/
DatePickerClasses["decade"] = "p-datepicker-decade";
/**
* Class name of the next button element
*/
DatePickerClasses["pcNextButton"] = "p-datepicker-next-button";
/**
* Class name of the day view element
*/
DatePickerClasses["dayView"] = "p-datepicker-day-view";
/**
* Class name of the week header element
*/
DatePickerClasses["weekHeader"] = "p-datepicker-weekheader";
/**
* Class name of the week number element
*/
DatePickerClasses["weekNumber"] = "p-datepicker-weeknumber";
/**
* Class name of the week label container element
*/
DatePickerClasses["weekLabelContainer"] = "p-datepicker-weeklabel-container";
/**
* Class name of the week day cell element
*/
DatePickerClasses["weekDayCell"] = "p-datepicker-weekday-cell";
/**
* Class name of the week day element
*/
DatePickerClasses["weekDay"] = "p-datepicker-weekday";
/**
* Class name of the day cell element
*/
DatePickerClasses["dayCell"] = "p-datepicker-day-cell";
/**
* Class name of the day element
*/
DatePickerClasses["day"] = "p-datepicker-day";
/**
* Class name of the month view element
*/
DatePickerClasses["monthView"] = "p-datepicker-month-view";
/**
* Class name of the month element
*/
DatePickerClasses["month"] = "p-datepicker-month";
/**
* Class name of the year view element
*/
DatePickerClasses["yearView"] = "p-datepicker-year-view";
/**
* Class name of the year element
*/
DatePickerClasses["year"] = "p-datepicker-year";
/**
* Class name of the time picker element
*/
DatePickerClasses["timePicker"] = "p-datepicker-time-picker";
/**
* Class name of the hour picker element
*/
DatePickerClasses["hourPicker"] = "p-datepicker-hour-picker";
/**
* Class name of the increment button element
*/
DatePickerClasses["pcIncrementButton"] = "p-datepicker-increment-button";
/**
* Class name of the decrement button element
*/
DatePickerClasses["pcDecrementButton"] = "p-datepicker-decrement-button";
/**
* Class name of the separator element
*/
DatePickerClasses["separator"] = "p-datepicker-separator";
/**
* Class name of the minute picker element
*/
DatePickerClasses["minutePicker"] = "p-datepicker-minute-picker";
/**
* Class name of the second picker element
*/
DatePickerClasses["secondPicker"] = "p-datepicker-second-picker";
/**
* Class name of the ampm picker element
*/
DatePickerClasses["ampmPicker"] = "p-datepicker-ampm-picker";
/**
* Class name of the buttonbar element
*/
DatePickerClasses["buttonbar"] = "p-datepicker-buttonbar";
/**
* Class name of the today button element
*/
DatePickerClasses["pcTodayButton"] = "p-datepicker-today-button";
/**
* Class name of the clear button element
*/
DatePickerClasses["pcClearButton"] = "p-datepicker-clear-button";
/**
* Class name of the clear icon
*/
DatePickerClasses["clearIcon"] = "p-datepicker-clear-icon";
})(DatePickerClasses || (DatePickerClasses = {}));
const DATEPICKER_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatePicker),
multi: true
};
/**
* DatePicker is a form component to work with dates.
* @group Components
*/
class DatePicker extends BaseInput {
zone;
overlayService;
iconDisplay = 'button';
/**
* Style class of the component.
* @deprecated since v20.0.0, use `class` instead.
* @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;
/**
* 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;
/**
* Format of the date which can also be defined at locale settings.
* @group Props
*/
get dateFormat() {
return this._dateFormat;
}
set dateFormat(value) {
this._dateFormat = value;
if (this.initialized) {
this.updateInputfield();
}
}
/**
* 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 datepicker 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 datepicker button.
* @group Props
*/
icon;
/**
* 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';
/**
* Specifies 12 or 24 hour format.
* @group Props
*/
get hourFormat() {
return this._hourFormat;
}
set hourFormat(value) {
this._hourFormat = value;
if (this.initialized) {
this.updateInputfield();
}
}
/**
* Whether to display timepicker only.
* @group Props
*/
timeOnly;
/**
* 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 disabled, datepicker will not be visible with input focus.
* @group Props
*/
showOnFocus = true;
/**
* When enabled, datepicker will show week numbers.
* @group Props
*/
showWeek = false;
/**
* When enabled, datepicker 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;
/**
* Style class of the clear button.
* @group Props
*/
clearButtonStyleClass;
/**
* 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, datepicker 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 datepicker.
* @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;
/**
* 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);
}
}
/**
* 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();
}
/**
* 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);
}
}
/**
* 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).
* @defaultValue 'self'
* @group Props
*/
appendTo = input(undefined, ...(ngDevMode ? [{ debugName: "appendTo" }] : []));
/**
* 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 {DatePickerMonthChangeEvent} event - custom month change event.
* @group Emits
*/
onMonthChange = new EventEmitter();
/**
* Callback to invoke when a year is changed using the navigators.
* @param {DatePickerYearChangeEvent} 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();
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();
}
}
}
}
_componentStyle = inject(DatePickerStyle);
contentViewChild;
value;
dates;
months;
weekDays;
currentMonth;
currentYear;
currentHour;
currentMinute;
currentSecond;
p;
pm;
mask;
maskClickListener;
overlay;
responsiveStyleElement;
overlayVisible;
$appendTo = computed(() => this.appendTo() || this.config.overlayAppendTo(), ...(ngDevMode ? [{ debugName: "$appendTo" }] : []));
calendarElement;
timePickerTimer;
documentClickListener;
animationEndListener;
ticksTo1970;
yearOptions;
focus;
isKeydown;
_minDate;
_maxDate;
_dateFormat;
_hourFormat = '24';
_showTime;
_yearRange;
preventDocumentListener;
dayClass(date) {
return this._componentStyle.classes.day({ instance: this, date: date });
}
/**
* Custom template for date cells.
* @group Templates
*/
dateTemplate;
/**
* Custom template for header section.
* @group Templates
*/
headerTemplate;
/**
* Custom template for footer section.
* @group Templates
*/
footerTemplate;
/**
* Custom template for disabled date cells.
* @group Templates
*/
disabledDateTemplate;
/**
* Custom template for decade view.
* @group Templates
*/
decadeTemplate;
/**
* Custom template for previous month icon.
* @group Templates
*/
previousIconTemplate;
/**
* Custom template for next month icon.
* @group Templates
*/
nextIconTemplate;
/**
* Custom template for trigger icon.
* @group Templates
*/
triggerIconTemplate;
/**
* Custom template for clear icon.
* @group Templates
*/
clearIconTemplate;
/**
* Custom template for decrement icon.
* @group Templates
*/
decrementIconTemplate;
/**
* Custom template for increment icon.
* @group Templates
*/
incrementIconTemplate;
/**
* Custom template for input icon.
* @group Templates
*/
inputIconTemplate;
_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(zone, overlayService) {
super();
this.zone = zone;
this.overlayService = overlayService;
this.window = this.document.defaultView;
}
ngOnInit() {
super.ngOnInit();
this.attributeSelector = uuid('pn_id_');
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;
}
ngAfterViewInit() {
super.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 = getOuterWidth(this.el?.nativeElement) + 'px';
}
}
}
}
}
templates;
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;
}
});
}
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 % 10);
for (let i = 0; i < 10; 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 % 12;
y = year + Math.floor((month + i) / 12);
}
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.decrementDecade();
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.incrementDecade();
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.currentYear < _yearOptions[0]) {
let difference = _yearOptions[_yearOptions.length - 1] - _yearOptions[0];
this.populateYearOptions(_yearOptions[0] - difference, _yearOptions[_yearOptions.length - 1] - difference);
}
}
decrementDecade() {
this.currentYear = this.currentYear - 10;
}
incrementDecade() {
this.currentYear = this.currentYear + 10;
}
incrementYear() {
this.currentYear++;
let _yearOptions = this.yearOptions;
if (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.writeModelValue(formattedValue);
this.inputFieldValue = formattedValue;
if (this.inputfieldViewChild && this.inputfieldViewChild.nativeElement) {
this.inputfieldViewChild.nativeElement.value = this.inputFieldValue;
}
}
inputFieldValue = null;
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.writeModelValue(this.value);
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.writeModelValue(stringArrValue);
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())
return false;
if (this.isMultipleSelection()