angular-weblineindia-date-picker
Version:
Date Picker component built in AngularJS to select date and time. Supports Angular 9 version.
1,089 lines (1,052 loc) • 157 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/forms'), require('@angular/common'), require('moment')) :
typeof define === 'function' && define.amd ? define('ng2-date-picker', ['exports', '@angular/core', '@angular/forms', '@angular/common', 'moment'], factory) :
(global = global || self, factory(global['ng2-date-picker'] = {}, global.ng.core, global.ng.forms, global.ng.common, global.moment));
}(this, (function (exports, core, forms, common, momentNs) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __exportStar(m, exports) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
(function (ECalendarMode) {
ECalendarMode[ECalendarMode["Day"] = 0] = "Day";
ECalendarMode[ECalendarMode["DayTime"] = 1] = "DayTime";
ECalendarMode[ECalendarMode["Month"] = 2] = "Month";
ECalendarMode[ECalendarMode["Time"] = 3] = "Time";
})(exports.ECalendarMode || (exports.ECalendarMode = {}));
(function (ECalendarValue) {
ECalendarValue[ECalendarValue["Moment"] = 1] = "Moment";
ECalendarValue[ECalendarValue["MomentArr"] = 2] = "MomentArr";
ECalendarValue[ECalendarValue["String"] = 3] = "String";
ECalendarValue[ECalendarValue["StringArr"] = 4] = "StringArr";
})(exports.ECalendarValue || (exports.ECalendarValue = {}));
(function (SelectEvent) {
SelectEvent["INPUT"] = "input";
SelectEvent["SELECTION"] = "selection";
})(exports.SelectEvent || (exports.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 = core["ɵɵdefineInjectable"]({ factory: function DomHelper_Factory() { return new DomHelper(); }, token: DomHelper, providedIn: "root" });
DomHelper = DomHelper_1 = __decorate([
core.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 exports.ECalendarValue.MomentArr;
}
else if (typeof value[0] === 'string') {
return exports.ECalendarValue.StringArr;
}
else if (moment.isMoment(value[0])) {
return exports.ECalendarValue.MomentArr;
}
}
else {
if (typeof value === 'string') {
return exports.ECalendarValue.String;
}
else if (moment.isMoment(value)) {
return exports.ECalendarValue.Moment;
}
}
return allowMultiSelect ? exports.ECalendarValue.MomentArr : exports.ECalendarValue.Moment;
};
// todo:: add unit test
UtilsService.prototype.convertToMomentArray = function (value, config) {
var retVal;
switch (this.getInputType(value, config.allowMultiSelect)) {
case (exports.ECalendarValue.String):
retVal = value ? [moment(value, config.format, true)] : [];
break;
case (exports.ECalendarValue.StringArr):
retVal = value.map(function (v) { return v ? moment(v, config.format, true) : null; }).filter(Boolean);
break;
case (exports.ECalendarValue.Moment):
retVal = value ? [value.clone()] : [];
break;
case (exports.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 (exports.ECalendarValue.String):
return value[0] && value[0].format(format);
case (exports.ECalendarValue.StringArr):
return value.filter(Boolean).map(function (v) { return v.format(format); });
case (exports.ECalendarValue.Moment):
return value[0] ? value[0].clone() : value[0];
case (exports.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 = core["ɵɵdefineInjectable"]({ factory: function UtilsService_Factory() { return new UtilsService(); }, token: UtilsService, providedIn: "root" });
UtilsService = __decorate([
core.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([
core.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([
core.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([
core.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 core.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([
core.Injectable()