angular-weblineindia-date-picker
Version:
Date Picker component built in AngularJS to select date and time. Supports Angular 9 version.
1,234 lines (1,224 loc) • 133 kB
JavaScript
import { __decorate, __assign, __param } from 'tslib';
import { ɵɵdefineInjectable, Injectable, EventEmitter, ElementRef, Renderer2, ChangeDetectorRef, Input, HostBinding, Output, ViewChild, HostListener, Component, ViewEncapsulation, ChangeDetectionStrategy, forwardRef, ViewContainerRef, ComponentFactoryResolver, Optional, Directive, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, NgControl, FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
import * as momentNs from 'moment';
var ECalendarMode;
(function (ECalendarMode) {
ECalendarMode[ECalendarMode["Day"] = 0] = "Day";
ECalendarMode[ECalendarMode["DayTime"] = 1] = "DayTime";
ECalendarMode[ECalendarMode["Month"] = 2] = "Month";
ECalendarMode[ECalendarMode["Time"] = 3] = "Time";
})(ECalendarMode || (ECalendarMode = {}));
var ECalendarValue;
(function (ECalendarValue) {
ECalendarValue[ECalendarValue["Moment"] = 1] = "Moment";
ECalendarValue[ECalendarValue["MomentArr"] = 2] = "MomentArr";
ECalendarValue[ECalendarValue["String"] = 3] = "String";
ECalendarValue[ECalendarValue["StringArr"] = 4] = "StringArr";
})(ECalendarValue || (ECalendarValue = {}));
var SelectEvent;
(function (SelectEvent) {
SelectEvent["INPUT"] = "input";
SelectEvent["SELECTION"] = "selection";
})(SelectEvent || (SelectEvent = {}));
var DomHelper = /** @class */ (function () {
function DomHelper() {
}
DomHelper_1 = DomHelper;
DomHelper.setYAxisPosition = function (element, container, anchor, drops) {
var anchorRect = anchor.getBoundingClientRect();
var containerRect = container.getBoundingClientRect();
var bottom = anchorRect.bottom - containerRect.top;
var top = anchorRect.top - containerRect.top;
if (drops === 'down') {
element.style.top = (bottom + 1 + 'px');
}
else {
element.style.top = (top - 1 - element.scrollHeight) + 'px';
}
};
DomHelper.setXAxisPosition = function (element, container, anchor, dimElem, opens) {
var anchorRect = anchor.getBoundingClientRect();
var containerRect = container.getBoundingClientRect();
var left = anchorRect.left - containerRect.left;
if (opens === 'right') {
element.style.left = left + 'px';
}
else {
element.style.left = left - dimElem.offsetWidth + anchor.offsetWidth + 'px';
}
};
DomHelper.isTopInView = function (el) {
var top = el.getBoundingClientRect().top;
return (top >= 0);
};
DomHelper.isBottomInView = function (el) {
var bottom = el.getBoundingClientRect().bottom;
return (bottom <= window.innerHeight);
};
DomHelper.isLeftInView = function (el) {
var left = el.getBoundingClientRect().left;
return (left >= 0);
};
DomHelper.isRightInView = function (el) {
var right = el.getBoundingClientRect().right;
return (right <= window.innerWidth);
};
DomHelper.prototype.appendElementToPosition = function (config) {
var _this = this;
var container = config.container, element = config.element;
if (!container.style.position || container.style.position === 'static') {
container.style.position = 'relative';
}
if (element.style.position !== 'absolute') {
element.style.position = 'absolute';
}
element.style.visibility = 'hidden';
setTimeout(function () {
_this.setElementPosition(config);
element.style.visibility = 'visible';
});
};
DomHelper.prototype.setElementPosition = function (_a) {
var element = _a.element, container = _a.container, anchor = _a.anchor, dimElem = _a.dimElem, drops = _a.drops, opens = _a.opens;
DomHelper_1.setYAxisPosition(element, container, anchor, 'down');
DomHelper_1.setXAxisPosition(element, container, anchor, dimElem, 'right');
if (drops !== 'down' && drops !== 'up') {
if (DomHelper_1.isBottomInView(dimElem)) {
DomHelper_1.setYAxisPosition(element, container, anchor, 'down');
}
else if (DomHelper_1.isTopInView(dimElem)) {
DomHelper_1.setYAxisPosition(element, container, anchor, 'up');
}
}
else {
DomHelper_1.setYAxisPosition(element, container, anchor, drops);
}
if (opens !== 'left' && opens !== 'right') {
if (DomHelper_1.isRightInView(dimElem)) {
DomHelper_1.setXAxisPosition(element, container, anchor, dimElem, 'right');
}
else if (DomHelper_1.isLeftInView(dimElem)) {
DomHelper_1.setXAxisPosition(element, container, anchor, dimElem, 'left');
}
}
else {
DomHelper_1.setXAxisPosition(element, container, anchor, dimElem, opens);
}
};
var DomHelper_1;
DomHelper.ɵprov = ɵɵdefineInjectable({ factory: function DomHelper_Factory() { return new DomHelper(); }, token: DomHelper, providedIn: "root" });
DomHelper = DomHelper_1 = __decorate([
Injectable({
providedIn: 'root'
})
], DomHelper);
return DomHelper;
}());
var moment = momentNs;
var UtilsService = /** @class */ (function () {
function UtilsService() {
}
UtilsService.debounce = function (func, wait) {
var timeout;
return function () {
var context = this, args = arguments;
timeout = clearTimeout(timeout);
setTimeout(function () {
func.apply(context, args);
}, wait);
};
};
;
UtilsService.prototype.createArray = function (size) {
return new Array(size).fill(1);
};
UtilsService.prototype.convertToMoment = function (date, format) {
if (!date) {
return null;
}
else if (typeof date === 'string') {
return moment(date, format);
}
else {
return date.clone();
}
};
UtilsService.prototype.isDateValid = function (date, format) {
if (date === '') {
return true;
}
return moment(date, format, true).isValid();
};
// todo:: add unit test
UtilsService.prototype.getDefaultDisplayDate = function (current, selected, allowMultiSelect, minDate) {
if (current) {
return current.clone();
}
else if (minDate && minDate.isAfter(moment())) {
return minDate.clone();
}
else if (allowMultiSelect) {
if (selected && selected[selected.length]) {
return selected[selected.length].clone();
}
}
else if (selected && selected[0]) {
return selected[0].clone();
}
return moment();
};
// todo:: add unit test
UtilsService.prototype.getInputType = function (value, allowMultiSelect) {
if (Array.isArray(value)) {
if (!value.length) {
return ECalendarValue.MomentArr;
}
else if (typeof value[0] === 'string') {
return ECalendarValue.StringArr;
}
else if (moment.isMoment(value[0])) {
return ECalendarValue.MomentArr;
}
}
else {
if (typeof value === 'string') {
return ECalendarValue.String;
}
else if (moment.isMoment(value)) {
return ECalendarValue.Moment;
}
}
return allowMultiSelect ? ECalendarValue.MomentArr : ECalendarValue.Moment;
};
// todo:: add unit test
UtilsService.prototype.convertToMomentArray = function (value, config) {
var retVal;
switch (this.getInputType(value, config.allowMultiSelect)) {
case (ECalendarValue.String):
retVal = value ? [moment(value, config.format, true)] : [];
break;
case (ECalendarValue.StringArr):
retVal = value.map(function (v) { return v ? moment(v, config.format, true) : null; }).filter(Boolean);
break;
case (ECalendarValue.Moment):
retVal = value ? [value.clone()] : [];
break;
case (ECalendarValue.MomentArr):
retVal = (value || []).map(function (v) { return v.clone(); });
break;
default:
retVal = [];
}
return retVal;
};
// todo:: add unit test
UtilsService.prototype.convertFromMomentArray = function (format, value, convertTo) {
switch (convertTo) {
case (ECalendarValue.String):
return value[0] && value[0].format(format);
case (ECalendarValue.StringArr):
return value.filter(Boolean).map(function (v) { return v.format(format); });
case (ECalendarValue.Moment):
return value[0] ? value[0].clone() : value[0];
case (ECalendarValue.MomentArr):
return value ? value.map(function (v) { return v.clone(); }) : value;
default:
return value;
}
};
UtilsService.prototype.convertToString = function (value, format) {
var _this = this;
var tmpVal;
if (typeof value === 'string') {
tmpVal = [value];
}
else if (Array.isArray(value)) {
if (value.length) {
tmpVal = value.map(function (v) {
return _this.convertToMoment(v, format).format(format);
});
}
else {
tmpVal = value;
}
}
else if (moment.isMoment(value)) {
tmpVal = [value.format(format)];
}
else {
return '';
}
return tmpVal.filter(Boolean).join(' | ');
};
// todo:: add unit test
UtilsService.prototype.clearUndefined = function (obj) {
if (!obj) {
return obj;
}
Object.keys(obj).forEach(function (key) { return (obj[key] === undefined) && delete obj[key]; });
return obj;
};
UtilsService.prototype.updateSelected = function (isMultiple, currentlySelected, date, granularity) {
if (granularity === void 0) { granularity = 'day'; }
if (isMultiple) {
return !date.selected
? currentlySelected.concat([date.date])
: currentlySelected.filter(function (d) { return !d.isSame(date.date, granularity); });
}
else {
return !date.selected ? [date.date] : [];
}
};
UtilsService.prototype.closestParent = function (element, selector) {
if (!element) {
return undefined;
}
var match = element.querySelector(selector);
return match || this.closestParent(element.parentElement, selector);
};
UtilsService.prototype.onlyTime = function (m) {
return m && moment.isMoment(m) && moment(m.format('HH:mm:ss'), 'HH:mm:ss');
};
UtilsService.prototype.granularityFromType = function (calendarType) {
switch (calendarType) {
case 'time':
return 'second';
case 'daytime':
return 'second';
default:
return calendarType;
}
};
UtilsService.prototype.createValidator = function (_a, format, calendarType) {
var _this = this;
var minDate = _a.minDate, maxDate = _a.maxDate, minTime = _a.minTime, maxTime = _a.maxTime;
var isValid;
var value;
var validators = [];
var granularity = this.granularityFromType(calendarType);
if (minDate) {
var md_1 = this.convertToMoment(minDate, format);
validators.push({
key: 'minDate',
isValid: function () {
var _isValid = value.every(function (val) { return val.isSameOrAfter(md_1, granularity); });
isValid = isValid ? _isValid : false;
return _isValid;
}
});
}
if (maxDate) {
var md_2 = this.convertToMoment(maxDate, format);
validators.push({
key: 'maxDate',
isValid: function () {
var _isValid = value.every(function (val) { return val.isSameOrBefore(md_2, granularity); });
isValid = isValid ? _isValid : false;
return _isValid;
}
});
}
if (minTime) {
var md_3 = this.onlyTime(this.convertToMoment(minTime, format));
validators.push({
key: 'minTime',
isValid: function () {
var _isValid = value.every(function (val) { return _this.onlyTime(val).isSameOrAfter(md_3); });
isValid = isValid ? _isValid : false;
return _isValid;
}
});
}
if (maxTime) {
var md_4 = this.onlyTime(this.convertToMoment(maxTime, format));
validators.push({
key: 'maxTime',
isValid: function () {
var _isValid = value.every(function (val) { return _this.onlyTime(val).isSameOrBefore(md_4); });
isValid = isValid ? _isValid : false;
return _isValid;
}
});
}
return function (inputVal) {
isValid = true;
value = _this.convertToMomentArray(inputVal, {
format: format,
allowMultiSelect: true
}).filter(Boolean);
if (!value.every(function (val) { return val.isValid(); })) {
return {
format: {
given: inputVal
}
};
}
var errors = validators.reduce(function (map, err) {
if (!err.isValid()) {
map[err.key] = {
given: value
};
}
return map;
}, {});
return !isValid ? errors : null;
};
};
UtilsService.prototype.datesStringToStringArray = function (value) {
return (value || '').split('|').map(function (m) { return m.trim(); }).filter(Boolean);
};
UtilsService.prototype.getValidMomentArray = function (value, format) {
var _this = this;
return this.datesStringToStringArray(value)
.filter(function (d) { return _this.isDateValid(d, format); })
.map(function (d) { return moment(d, format); });
};
UtilsService.prototype.shouldShowCurrent = function (showGoToCurrent, mode, min, max) {
return showGoToCurrent &&
mode !== 'time' &&
this.isDateInRange(moment(), min, max);
};
UtilsService.prototype.isDateInRange = function (date, from, to) {
return date.isBetween(from, to, 'day', '[]');
};
UtilsService.prototype.convertPropsToMoment = function (obj, format, props) {
var _this = this;
props.forEach(function (prop) {
if (obj.hasOwnProperty(prop)) {
obj[prop] = _this.convertToMoment(obj[prop], format);
}
});
};
UtilsService.prototype.shouldResetCurrentView = function (prevConf, currentConf) {
if (prevConf && currentConf) {
if (!prevConf.min && currentConf.min) {
return true;
}
else if (prevConf.min && currentConf.min && !prevConf.min.isSame(currentConf.min, 'd')) {
return true;
}
else if (!prevConf.max && currentConf.max) {
return true;
}
else if (prevConf.max && currentConf.max && !prevConf.max.isSame(currentConf.max, 'd')) {
return true;
}
return false;
}
return false;
};
UtilsService.prototype.getNativeElement = function (elem) {
if (!elem) {
return null;
}
else if (typeof elem === 'string') {
return document.querySelector(elem);
}
else {
return elem;
}
};
UtilsService.ɵprov = ɵɵdefineInjectable({ factory: function UtilsService_Factory() { return new UtilsService(); }, token: UtilsService, providedIn: "root" });
UtilsService = __decorate([
Injectable({
providedIn: 'root'
})
], UtilsService);
return UtilsService;
}());
var moment$1 = momentNs;
var DayCalendarService = /** @class */ (function () {
function DayCalendarService(utilsService) {
this.utilsService = utilsService;
this.DEFAULT_CONFIG = {
showNearMonthDays: true,
showWeekNumbers: false,
firstDayOfWeek: 'su',
weekDayFormat: 'ddd',
format: 'DD-MM-YYYY',
allowMultiSelect: false,
monthFormat: 'MMM, YYYY',
enableMonthSelector: true,
locale: moment$1.locale(),
dayBtnFormat: 'DD',
unSelectOnClick: true
};
this.DAYS = ['su', 'mo', 'tu', 'we', 'th', 'fr', 'sa'];
}
DayCalendarService.prototype.getConfig = function (config) {
var _config = __assign(__assign({}, this.DEFAULT_CONFIG), this.utilsService.clearUndefined(config));
this.utilsService.convertPropsToMoment(_config, _config.format, ['min', 'max']);
moment$1.locale(_config.locale);
return _config;
};
DayCalendarService.prototype.generateDaysMap = function (firstDayOfWeek) {
var firstDayIndex = this.DAYS.indexOf(firstDayOfWeek);
var daysArr = this.DAYS.slice(firstDayIndex, 7).concat(this.DAYS.slice(0, firstDayIndex));
return daysArr.reduce(function (map, day, index) {
map[day] = index;
return map;
}, {});
};
DayCalendarService.prototype.generateMonthArray = function (config, month, selected) {
var _this = this;
var monthArray = [];
var firstDayOfWeekIndex = this.DAYS.indexOf(config.firstDayOfWeek);
var firstDayOfBoard = month.clone().startOf('month');
while (firstDayOfBoard.day() !== firstDayOfWeekIndex) {
firstDayOfBoard.subtract(1, 'day');
}
var current = firstDayOfBoard.clone();
var prevMonth = month.clone().subtract(1, 'month');
var nextMonth = month.clone().add(1, 'month');
var today = moment$1();
var daysOfCalendar = this.utilsService.createArray(42)
.reduce(function (array) {
array.push({
date: current.clone(),
selected: !!selected.find(function (selectedDay) { return current.isSame(selectedDay, 'day'); }),
currentMonth: current.isSame(month, 'month'),
prevMonth: current.isSame(prevMonth, 'month'),
nextMonth: current.isSame(nextMonth, 'month'),
currentDay: current.isSame(today, 'day'),
disabled: _this.isDateDisabled(current, config)
});
current.add(1, 'day');
return array;
}, []);
daysOfCalendar.forEach(function (day, index) {
var weekIndex = Math.floor(index / 7);
if (!monthArray[weekIndex]) {
monthArray.push([]);
}
monthArray[weekIndex].push(day);
});
if (!config.showNearMonthDays) {
monthArray = this.removeNearMonthWeeks(month, monthArray);
}
return monthArray;
};
DayCalendarService.prototype.generateWeekdays = function (firstDayOfWeek) {
var weekdayNames = {
su: moment$1().day(0),
mo: moment$1().day(1),
tu: moment$1().day(2),
we: moment$1().day(3),
th: moment$1().day(4),
fr: moment$1().day(5),
sa: moment$1().day(6)
};
var weekdays = [];
var daysMap = this.generateDaysMap(firstDayOfWeek);
for (var dayKey in daysMap) {
if (daysMap.hasOwnProperty(dayKey)) {
weekdays[daysMap[dayKey]] = weekdayNames[dayKey];
}
}
return weekdays;
};
DayCalendarService.prototype.isDateDisabled = function (date, config) {
if (config.isDayDisabledCallback) {
return config.isDayDisabledCallback(date);
}
if (config.min && date.isBefore(config.min, 'day')) {
return true;
}
return !!(config.max && date.isAfter(config.max, 'day'));
};
// todo:: add unit tests
DayCalendarService.prototype.getHeaderLabel = function (config, month) {
if (config.monthFormatter) {
return config.monthFormatter(month);
}
return month.format(config.monthFormat);
};
// todo:: add unit tests
DayCalendarService.prototype.shouldShowLeft = function (min, currentMonthView) {
return min ? min.isBefore(currentMonthView, 'month') : true;
};
// todo:: add unit tests
DayCalendarService.prototype.shouldShowRight = function (max, currentMonthView) {
return max ? max.isAfter(currentMonthView, 'month') : true;
};
DayCalendarService.prototype.generateDaysIndexMap = function (firstDayOfWeek) {
var firstDayIndex = this.DAYS.indexOf(firstDayOfWeek);
var daysArr = this.DAYS.slice(firstDayIndex, 7).concat(this.DAYS.slice(0, firstDayIndex));
return daysArr.reduce(function (map, day, index) {
map[index] = day;
return map;
}, {});
};
DayCalendarService.prototype.getMonthCalendarConfig = function (componentConfig) {
return this.utilsService.clearUndefined({
min: componentConfig.min,
max: componentConfig.max,
format: componentConfig.format,
isNavHeaderBtnClickable: true,
allowMultiSelect: false,
locale: componentConfig.locale,
yearFormat: componentConfig.yearFormat,
yearFormatter: componentConfig.yearFormatter,
monthBtnFormat: componentConfig.monthBtnFormat,
monthBtnFormatter: componentConfig.monthBtnFormatter,
monthBtnCssClassCallback: componentConfig.monthBtnCssClassCallback,
multipleYearsNavigateBy: componentConfig.multipleYearsNavigateBy,
showMultipleYearsNavigation: componentConfig.showMultipleYearsNavigation,
showGoToCurrent: componentConfig.showGoToCurrent,
numOfMonthRows: componentConfig.numOfMonthRows
});
};
DayCalendarService.prototype.getDayBtnText = function (config, day) {
if (config.dayBtnFormatter) {
return config.dayBtnFormatter(day);
}
return day.format(config.dayBtnFormat);
};
DayCalendarService.prototype.getDayBtnCssClass = function (config, day) {
if (config.dayBtnCssClassCallback) {
return config.dayBtnCssClassCallback(day);
}
return '';
};
DayCalendarService.prototype.removeNearMonthWeeks = function (currentMonth, monthArray) {
if (monthArray[monthArray.length - 1].find(function (day) { return day.date.isSame(currentMonth, 'month'); })) {
return monthArray;
}
else {
return monthArray.slice(0, -1);
}
};
DayCalendarService.ctorParameters = function () { return [
{ type: UtilsService }
]; };
DayCalendarService = __decorate([
Injectable()
], DayCalendarService);
return DayCalendarService;
}());
var moment$2 = momentNs;
var FIRST_PM_HOUR = 12;
var TimeSelectService = /** @class */ (function () {
function TimeSelectService(utilsService) {
this.utilsService = utilsService;
this.DEFAULT_CONFIG = {
hours12Format: 'hh',
hours24Format: 'HH',
meridiemFormat: 'A',
minutesFormat: 'mm',
minutesInterval: 1,
secondsFormat: 'ss',
secondsInterval: 1,
showSeconds: false,
showTwentyFourHours: false,
timeSeparator: ':',
locale: moment$2.locale()
};
}
TimeSelectService.prototype.getConfig = function (config) {
var timeConfigs = {
maxTime: this.utilsService.onlyTime(config && config.maxTime),
minTime: this.utilsService.onlyTime(config && config.minTime)
};
var _config = __assign(__assign(__assign({}, this.DEFAULT_CONFIG), this.utilsService.clearUndefined(config)), timeConfigs);
moment$2.locale(_config.locale);
return _config;
};
TimeSelectService.prototype.getTimeFormat = function (config) {
return (config.showTwentyFourHours ? config.hours24Format : config.hours12Format)
+ config.timeSeparator + config.minutesFormat
+ (config.showSeconds ? (config.timeSeparator + config.secondsFormat) : '')
+ (config.showTwentyFourHours ? '' : ' ' + config.meridiemFormat);
};
TimeSelectService.prototype.getHours = function (config, t) {
var time = t || moment$2();
return time && time.format(config.showTwentyFourHours ? config.hours24Format : config.hours12Format);
};
TimeSelectService.prototype.getMinutes = function (config, t) {
var time = t || moment$2();
return time && time.format(config.minutesFormat);
};
TimeSelectService.prototype.getSeconds = function (config, t) {
var time = t || moment$2();
return time && time.format(config.secondsFormat);
};
TimeSelectService.prototype.getMeridiem = function (config, time) {
return time && time.format(config.meridiemFormat);
};
TimeSelectService.prototype.decrease = function (config, time, unit) {
var amount = 1;
switch (unit) {
case 'minute':
amount = config.minutesInterval;
break;
case 'second':
amount = config.secondsInterval;
break;
}
return time.clone().subtract(amount, unit);
};
TimeSelectService.prototype.increase = function (config, time, unit) {
var amount = 1;
switch (unit) {
case 'minute':
amount = config.minutesInterval;
break;
case 'second':
amount = config.secondsInterval;
break;
}
return time.clone().add(amount, unit);
};
TimeSelectService.prototype.toggleMeridiem = function (time) {
if (time.hours() < FIRST_PM_HOUR) {
return time.clone().add(12, 'hour');
}
else {
return time.clone().subtract(12, 'hour');
}
};
TimeSelectService.prototype.shouldShowDecrease = function (config, time, unit) {
if (!config.min && !config.minTime) {
return true;
}
var newTime = this.decrease(config, time, unit);
return (!config.min || config.min.isSameOrBefore(newTime))
&& (!config.minTime || config.minTime.isSameOrBefore(this.utilsService.onlyTime(newTime)));
};
TimeSelectService.prototype.shouldShowIncrease = function (config, time, unit) {
if (!config.max && !config.maxTime) {
return true;
}
var newTime = this.increase(config, time, unit);
return (!config.max || config.max.isSameOrAfter(newTime))
&& (!config.maxTime || config.maxTime.isSameOrAfter(this.utilsService.onlyTime(newTime)));
};
TimeSelectService.prototype.shouldShowToggleMeridiem = function (config, time) {
if (!config.min && !config.max && !config.minTime && !config.maxTime) {
return true;
}
var newTime = this.toggleMeridiem(time);
return (!config.max || config.max.isSameOrAfter(newTime))
&& (!config.min || config.min.isSameOrBefore(newTime))
&& (!config.maxTime || config.maxTime.isSameOrAfter(this.utilsService.onlyTime(newTime)))
&& (!config.minTime || config.minTime.isSameOrBefore(this.utilsService.onlyTime(newTime)));
};
TimeSelectService.ctorParameters = function () { return [
{ type: UtilsService }
]; };
TimeSelectService = __decorate([
Injectable()
], TimeSelectService);
return TimeSelectService;
}());
var moment$3 = momentNs;
var DAY_FORMAT = 'YYYYMMDD';
var TIME_FORMAT = 'HH:mm:ss';
var COMBINED_FORMAT = DAY_FORMAT + TIME_FORMAT;
var DayTimeCalendarService = /** @class */ (function () {
function DayTimeCalendarService(utilsService, dayCalendarService, timeSelectService) {
this.utilsService = utilsService;
this.dayCalendarService = dayCalendarService;
this.timeSelectService = timeSelectService;
this.DEFAULT_CONFIG = {
locale: moment$3.locale()
};
}
DayTimeCalendarService.prototype.getConfig = function (config) {
var _config = __assign(__assign(__assign({}, this.DEFAULT_CONFIG), this.timeSelectService.getConfig(config)), this.dayCalendarService.getConfig(config));
moment$3.locale(config.locale);
return _config;
};
DayTimeCalendarService.prototype.updateDay = function (current, day, config) {
var time = current ? current : moment$3();
var updated = moment$3(day.format(DAY_FORMAT) + time.format(TIME_FORMAT), COMBINED_FORMAT);
if (config.min) {
var min = config.min;
updated = min.isAfter(updated) ? min : updated;
}
if (config.max) {
var max = config.max;
updated = max.isBefore(updated) ? max : updated;
}
return updated;
};
DayTimeCalendarService.prototype.updateTime = function (current, time) {
var day = current ? current : moment$3();
return moment$3(day.format(DAY_FORMAT) + time.format(TIME_FORMAT), COMBINED_FORMAT);
};
DayTimeCalendarService.ctorParameters = function () { return [
{ type: UtilsService },
{ type: DayCalendarService },
{ type: TimeSelectService }
]; };
DayTimeCalendarService = __decorate([
Injectable()
], DayTimeCalendarService);
return DayTimeCalendarService;
}());
var moment$4 = momentNs;
var DatePickerService = /** @class */ (function () {
function DatePickerService(utilsService, timeSelectService, daytimeCalendarService) {
this.utilsService = utilsService;
this.timeSelectService = timeSelectService;
this.daytimeCalendarService = daytimeCalendarService;
this.onPickerClosed = new EventEmitter();
this.defaultConfig = {
closeOnSelect: true,
closeOnSelectDelay: 100,
closeOnEnter: true,
format: 'DD-MM-YYYY',
openOnFocus: true,
openOnClick: true,
onOpenDelay: 0,
disableKeypress: false,
showNearMonthDays: true,
showWeekNumbers: false,
enableMonthSelector: true,
showGoToCurrent: true,
locale: moment$4.locale(),
hideOnOutsideClick: true
};
}
// todo:: add unit tests
DatePickerService.prototype.getConfig = function (config, mode) {
if (mode === void 0) { mode = 'daytime'; }
var _config = __assign(__assign(__assign({}, this.defaultConfig), { format: this.getDefaultFormatByMode(mode) }), this.utilsService.clearUndefined(config));
this.utilsService.convertPropsToMoment(_config, _config.format, ['min', 'max']);
if (config && config.allowMultiSelect && config.closeOnSelect === undefined) {
_config.closeOnSelect = false;
}
moment$4.locale(_config.locale);
return _config;
};
DatePickerService.prototype.getDayConfigService = function (pickerConfig) {
return {
min: pickerConfig.min,
max: pickerConfig.max,
isDayDisabledCallback: pickerConfig.isDayDisabledCallback,
weekDayFormat: pickerConfig.weekDayFormat,
weekDayFormatter: pickerConfig.weekDayFormatter,
showNearMonthDays: pickerConfig.showNearMonthDays,
showWeekNumbers: pickerConfig.showWeekNumbers,
firstDayOfWeek: pickerConfig.firstDayOfWeek,
format: pickerConfig.format,
allowMultiSelect: pickerConfig.allowMultiSelect,
monthFormat: pickerConfig.monthFormat,
monthFormatter: pickerConfig.monthFormatter,
enableMonthSelector: pickerConfig.enableMonthSelector,
yearFormat: pickerConfig.yearFormat,
yearFormatter: pickerConfig.yearFormatter,
dayBtnFormat: pickerConfig.dayBtnFormat,
dayBtnFormatter: pickerConfig.dayBtnFormatter,
dayBtnCssClassCallback: pickerConfig.dayBtnCssClassCallback,
monthBtnFormat: pickerConfig.monthBtnFormat,
monthBtnFormatter: pickerConfig.monthBtnFormatter,
monthBtnCssClassCallback: pickerConfig.monthBtnCssClassCallback,
multipleYearsNavigateBy: pickerConfig.multipleYearsNavigateBy,
showMultipleYearsNavigation: pickerConfig.showMultipleYearsNavigation,
locale: pickerConfig.locale,
returnedValueType: pickerConfig.returnedValueType,
showGoToCurrent: pickerConfig.showGoToCurrent,
unSelectOnClick: pickerConfig.unSelectOnClick,
numOfMonthRows: pickerConfig.numOfMonthRows
};
};
DatePickerService.prototype.getDayTimeConfigService = function (pickerConfig) {
return this.daytimeCalendarService.getConfig(pickerConfig);
};
DatePickerService.prototype.getTimeConfigService = function (pickerConfig) {
return this.timeSelectService.getConfig(pickerConfig);
};
DatePickerService.prototype.pickerClosed = function () {
this.onPickerClosed.emit();
};
// todo:: add unit tests
DatePickerService.prototype.isValidInputDateValue = function (value, config) {
var _this = this;
value = value ? value : '';
var datesStrArr = this.utilsService.datesStringToStringArray(value);
return datesStrArr.every(function (date) { return _this.utilsService.isDateValid(date, config.format); });
};
// todo:: add unit tests
DatePickerService.prototype.convertInputValueToMomentArray = function (value, config) {
value = value ? value : '';
var datesStrArr = this.utilsService.datesStringToStringArray(value);
return this.utilsService.convertToMomentArray(datesStrArr, config);
};
DatePickerService.prototype.getDefaultFormatByMode = function (mode) {
switch (mode) {
case 'day':
return 'DD-MM-YYYY';
case 'daytime':
return 'DD-MM-YYYY HH:mm:ss';
case 'time':
return 'HH:mm:ss';
case 'month':
return 'MMM, YYYY';
}
};
DatePickerService.ctorParameters = function () { return [
{ type: UtilsService },
{ type: TimeSelectService },
{ type: DayTimeCalendarService }
]; };
DatePickerService = __decorate([
Injectable()
], DatePickerService);
return DatePickerService;
}());
var DatePickerComponent = /** @class */ (function () {
function DatePickerComponent(dayPickerService, domHelper, elemRef, renderer, utilsService, cd) {
this.dayPickerService = dayPickerService;
this.domHelper = domHelper;
this.elemRef = elemRef;
this.renderer = renderer;
this.utilsService = utilsService;
this.cd = cd;
this.isInitialized = false;
this.mode = 'day';
this.placeholder = '';
this.disabled = false;
this.open = new EventEmitter();
this.close = new EventEmitter();
this.onChange = new EventEmitter();
this.onGoToCurrent = new EventEmitter();
this.onLeftNav = new EventEmitter();
this.onRightNav = new EventEmitter();
this.onSelect = new EventEmitter();
this.hideStateHelper = false;
this.isFocusedTrigger = false;
this.handleInnerElementClickUnlisteners = [];
this.globalListenersUnlisteners = [];
this.api = {
open: this.showCalendars.bind(this),
close: this.hideCalendar.bind(this),
moveCalendarTo: this.moveCalendarTo.bind(this)
};
this.selectEvent = SelectEvent;
this._areCalendarsShown = false;
this._selected = [];
}
DatePickerComponent_1 = DatePickerComponent;
Object.defineProperty(DatePickerComponent.prototype, "openOnFocus", {
get: function () {
return this.componentConfig.openOnFocus;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DatePickerComponent.prototype, "openOnClick", {
get: function () {
return this.componentConfig.openOnClick;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DatePickerComponent.prototype, "areCalendarsShown", {
get: function () {
return this._areCalendarsShown;
},
set: function (value) {
if (value) {
this.startGlobalListeners();
this.domHelper.appendElementToPosition({
container: this.appendToElement,
element: this.calendarWrapper,
anchor: this.inputElementContainer,
dimElem: this.popupElem,
drops: this.componentConfig.drops,
opens: this.componentConfig.opens
});
}
else {
this.stopGlobalListeners();
this.dayPickerService.pickerClosed();
}
this._areCalendarsShown = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DatePickerComponent.prototype, "selected", {
get: function () {
return this._selected;
},
set: function (selected) {
this._selected = selected;
this.inputElementValue = this.utilsService
.convertFromMomentArray(this.componentConfig.format, selected, ECalendarValue.StringArr)
.join(' | ');
var val = this.processOnChangeCallback(selected);
this.onChangeCallback(val, false);
this.onChange.emit(val);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DatePickerComponent.prototype, "currentDateView", {
get: function () {
return this._currentDateView;
},
set: function (date) {
this._currentDateView = date;
if (this.dayCalendarRef) {
this.dayCalendarRef.moveCalendarTo(date);
}
if (this.monthCalendarRef) {
this.monthCalendarRef.moveCalendarTo(date);
}
if (this.dayTimeCalendarRef) {
this.dayTimeCalendarRef.moveCalendarTo(date);
}
},
enumerable: true,
configurable: true
});
DatePickerComponent.prototype.onClick = function () {
if (!this.openOnClick) {
return;
}
if (!this.isFocusedTrigger && !this.disabled) {
this.hideStateHelper = true;
if (!this.areCalendarsShown) {
this.showCalendars();
}
}
};
DatePickerComponent.prototype.onBodyClick = function () {
if (this.componentConfig.hideOnOutsideClick) {
if (!this.hideStateHelper && this.areCalendarsShown) {
this.hideCalendar();
}
this.hideStateHelper = false;
}
};
DatePickerComponent.prototype.onScroll = function () {
if (this.areCalendarsShown) {
this.domHelper.setElementPosition({
container: this.appendToElement,
element: this.calendarWrapper,
anchor: this.inputElementContainer,
dimElem: this.popupElem,
drops: this.componentConfig.drops,
opens: this.componentConfig.opens
});
}
};
DatePickerComponent.prototype.writeValue = function (value) {
this.inputValue = value;
if (value || value === '') {
this.selected = this.utilsService
.convertToMomentArray(value, this.componentConfig);
this.init();
}
else {
this.selected = [];
}
this.cd.markForCheck();
};
DatePickerComponent.prototype.registerOnChange = function (fn) {
this.onChangeCallback = fn;
};
DatePickerComponent.prototype.onChangeCallback = function (_, changedByInput) {
};
DatePickerComponent.prototype.registerOnTouched = function (fn) {
this.onTouchedCallback = fn;
};
DatePickerComponent.prototype.onTouchedCallback = function () {
};
DatePickerComponent.prototype.validate = function (formControl) {
return this.validateFn(formControl.value);
};
DatePickerComponent.prototype.processOnChangeCallback = function (selected) {
if (typeof selected === 'string') {
return selected;
}
else {
return this.utilsService.convertFromMomentArray(this.componentConfig.format, selected, this.componentConfig.returnedValueType || this.utilsService.getInputType(this.inputValue, this.componentConfig.allowMultiSelect));
}
};
DatePickerComponent.prototype.initValidators = function () {
this.validateFn = this.utilsService.createValidator({
minDate: this.minDate,
maxDate: this.maxDate,
minTime: this.minTime,
maxTime: this.maxTime
}, this.componentConfig.format, this.mode);
this.onChangeCallback(this.processOnChangeCallback(this.selected), false);
};
DatePickerComponent.prototype.ngOnInit = function () {
this.isInitialized = true;
this.init();
};
DatePickerComponent.prototype.ngOnChanges = function (changes) {
if (this.isInitialized) {
this.init();
}
};
DatePickerComponent.prototype.ngAfterViewInit = function () {
this.setElementPositionInDom();
};
DatePickerComponent.prototype.setDisabledState = function (isDisabled) {
this.disabled = isDisabled;
this.cd.markForCheck();
};
DatePickerComponent.prototype.setElementPositionInDom = function () {
this.calendarWrapper = this.calendarContainer.nativeElement;
this.setInputElementContainer();
this.popupElem = this.elemRef.nativeElement.querySelector('.dp-popup');
this.handleInnerElementClick(this.popupElem);
var appendTo = this.componentConfig.appendTo;
if (appendTo) {
if (typeof appendTo === 'string') {
this.appendToElement = document.querySelector(appendTo);
}
else {
this.appendToElement = appendTo;
}
}
else {
this.appendToElement = this.elemRef.nativeElement;
}
this.appendToElement.appendChild(this.calendarWrapper);
};
DatePickerComponent.prototype.setInputElementContainer = function () {
this.inputElementContainer = this.utilsService.getNativeElement(this.componentConfig.inputElementContainer)
|| this.elemRef.nativeElement.querySelector('.dp-input-container')
|| document.body;
};
DatePickerComponent.prototype.handleInnerElementClick = function (element) {
var _this = this;
this.handleInnerElementClickUnlisteners.push(this.renderer.listen(element, 'click', function () {
_this.hideStateHelper = true;
}));
};
DatePickerComponent.prototype.init = function () {
this.componentConfig = this.dayPickerService.getConfig(this.config, this.mode);
this.currentDateView = this.displayDate
? this.utilsService.convertToMoment(this.displayDate, this.componentConfig.format).clone()
: this.utilsService
.getDefaultDisplayDate(this.currentDateView, this.selected, this.componentConfig.allowMultiSelect, this.componentConfig.min);
this.dayCalendarConfig = this.dayPickerService.getDayConfigService(this.componentConfig);
this.dayTimeCalendarConfig = this.dayPickerService.getDayTimeConfigService(this.componentConfig);
this.timeSelectConfig = this.dayPickerService.getTimeConfigService(this.componentConfig);
this.initValidators();
};
DatePickerComponent.prototype.inputFocused = function () {
var _this = this;
if (!this.openOnFocus) {
return;
}
clearTimeout(this.onOpenDelayTimeoutHandler);
this.isFocusedTrigger = true;
this.onOpenDelayTimeoutHandler = setTimeout(function () {
if (!_this.areCalendarsShown) {
_this.showCalendars();
}
_this.hideStateHelper = false;
_this.isFocusedTrigger = false;
_this.cd.markForCheck();
}, this.componentConfig.onOpenDelay);
};
DatePickerComponent.prototype.inputBlurred = function () {
clearTimeout(this.onOpenDelayTimeoutHandler);
this.onTouchedCallback();
};
DatePickerComponent.prototype.showCalendars = function () {
this.hideStateHelper = true;
this.areCalendarsShown = true;
if (this.timeSelectRef) {
this.timeSelectRef.api.triggerChange();
}
this.open.emit();
this.cd.markForCheck();
};
DatePickerComponent.prototype.hideCalendar = function () {
this.areCalendarsShown = false;
if (this.dayCalendarRef) {
this.dayCalendarRef.api.toggleCalendarMode(ECalendarMode.Day);
}
this.close.emit();
this.cd.markForCheck();
};
DatePickerComponent.prototype.onViewDateChange = function (value) {
var strVal = value ? this.utilsService.convertToString(value, this.componentConfig.format) : '';
if (this.dayPickerService.isValidInputDateValue(strVal, this.componentConfig)) {
this.selected = this.dayPickerService.convertInputValueToMomentArray(strVal, this.componentConfig);
this.currentDateView = this.selected.length
? this.utilsService.getDefaultDisplayDate(null, this.selected, this.componentConfig.allowMultiSelect, this.componentConfig.min)
: this.currentDateView;
this.onSelect.emit({
date: strVal,
type: SelectEvent.INPUT,
granularity: null
});
}
else {
this._selected = this.utilsService
.getValidMomentArray(strVal, this.componentConfig.format);
this.onChangeCallback(this.processOnChangeCallback(strVal), true);
}
};
DatePickerComponent.prototype.dateSelected = function (date, granularity, type, ignoreClose) {
this.selected = this.utilsService
.updateSelected(this.componentConfig.allowMultiSelect, this.selected, date, granularity);
if (!ignoreClose) {
this.onDateClick();
}
this.onSelect.emit({
date: date.date,
granularity: granularity,
type: type
});
};
DatePickerComponent.prototype.onDateClick = function () {
if (this.componentConfig.closeOnSelect) {
setTimeout(this.hideCalendar.bind(this), this.componentConfig.closeOnSelectDelay);
}
};
DatePickerComponent.prototype.onKeyPress = function (event) {
switch (event.keyCode) {
case (9):
case (27):
this.hideCalendar();
break;
}
};
DatePickerComponent.prototype.moveCalendarTo = function (date) {
var momentDate = this.utilsService.convertToMoment(date, this.componentConfig.format);
this.currentDateView = momentDate;
};
DatePickerComponent.prototype.onLeftNavClick = function (change) {
this.onLeftNav.emit(change);
};
DatePickerComponent.prototype.onRightNavClick = function (change) {
this.onRightNav.emit(change);
};
DatePickerComponent.prototype.startGlobalListeners = function () {
var _this = this;
this.globalListenersUnlisteners.push(this.renderer.listen(document, 'keydown', function (e) {
_this.onKeyPress(e);
}), this.renderer.listen(document, 'scroll', function () {
_this.onScroll();
}), this.renderer.listen(document, 'click', function () {
_this.onBodyClick();
}));
};
DatePickerComponent.prototype.stopGlobalListeners = function () {
this.globalListenersUnlisteners.forEach(function (ul) { return ul(); });
this.globalListenersUnlisteners = [];
};
DatePickerComponent.prototype.ngOnDestroy = function () {
this.handleInnerElementClickUnlisteners.forEach(function (ul) { return ul(); });
if (this.appendToElement) {
this.appendToElement.removeChild(this.calendarWrapper);
}
};
var DatePickerComponent_1;
DatePickerComponent.ctorParameters = function () { return [
{ type: DatePickerService },
{ type: DomHelper },
{ type: ElementRef },
{ type: Re