UNPKG

@universis/common

Version:

Universis - common directives and services

1,146 lines (1,131 loc) 240 kB
import 'bootstrap/js/dist/modal'; import * as jQuery from 'jquery'; import * as Toast from 'bootstrap/js/dist/toast'; import * as _numeral from 'numeral'; import _numeral__default, { } from 'numeral'; import 'numeral/locales'; import { template, uniqBy, slice, get, has, set, unset } from 'lodash'; import { X509 } from 'jsrsasign'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; import { saveAs } from 'file-saver'; import { utils, write } from 'xlsx'; import { BehaviorSubject, Observable, Subject } from 'rxjs'; import { EventSourcePolyfill } from 'event-source-polyfill'; import { HttpClient, HttpErrorResponse, HttpClientModule } from '@angular/common/http'; import { Args, ResponseError } from '@themost/client'; import { skip, filter, first, map, takeUntil } from 'rxjs/operators'; import { DATA_CONTEXT_CONFIG, AngularDataContext, MostModule } from '@themost/angular'; import { __extends, __awaiter, __generator, __values, __spread, __assign } from 'tslib'; import { Router, DefaultUrlSerializer, NavigationEnd, NavigationStart, PRIMARY_OUTLET, RouterModule, ActivatedRoute } from '@angular/router'; import { EventEmitter, Injectable, InjectionToken, Injector, isDevMode, Component, Input, ElementRef, ApplicationRef, ComponentFactoryResolver, Output, Pipe, Directive, Inject, TemplateRef, ViewContainerRef, CUSTOM_ELEMENTS_SCHEMA, NgModule, ErrorHandler, Optional, SkipSelf, ViewEncapsulation, ChangeDetectorRef, defineInjectable, inject, Renderer2 } from '@angular/core'; import { DecimalPipe, DatePipe, CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { TranslateService, TranslatePipe, TranslateModule } from '@ngx-translate/core'; import { AES, enc, lib, SHA256, SHA1 } from 'crypto-js'; var APP_CONFIGURATION = new InjectionToken('app.configuration'); /** * * This Service is used to get or set global configuration for the project * @export * @class ConfigurationService */ var ConfigurationService = /** @class */ (function () { function ConfigurationService(_translateService, _injector, _http) { this._translateService = _translateService; this._injector = _injector; this._http = _http; this.loaded = new EventEmitter(null); // } /** * * Load Configs saved in Project * @returns {Promise<any>} * @memberof ConfigurationService */ ConfigurationService.prototype.load = function () { return __awaiter(this, void 0, void 0, function () { var env, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: if (this.config) { return [2 /*return*/, true]; } env = isDevMode() ? 'development' : 'production'; _a.label = 1; case 1: _a.trys.push([1, 3, , 6]); return [4 /*yield*/, this.loadFrom("assets/config/app." + env + ".json")]; case 2: return [2 /*return*/, _a.sent()]; case 3: err_1 = _a.sent(); if (!(err_1.status === 404)) return [3 /*break*/, 5]; return [4 /*yield*/, this.loadFrom("assets/config/app.json")]; case 4: // not found // load default application configuration return [2 /*return*/, _a.sent()]; case 5: throw err_1; case 6: return [2 /*return*/]; } }); }); }; ConfigurationService.prototype.loadFrom = function (url) { return __awaiter(this, void 0, void 0, function () { var _a, dataContextConfig; var _this = this; return __generator(this, function (_b) { switch (_b.label) { case 0: // get configuration from url _a = this; return [4 /*yield*/, new Promise(function (resolve, reject) { _this._http.get(url).subscribe(function (result) { return resolve(result); }, function (err) { return reject(err); }); })]; case 1: // get configuration from url _a.config = _b.sent(); dataContextConfig = this._injector.get(DATA_CONTEXT_CONFIG); // IMPORTANT: Set DATA_CONTEXT_CONFIG base URI from configuration dataContextConfig.base = this.config.settings.remote.server; // set locale for translate service this._translateService.use(this.currentLocale); // emit event for loaded configuration this.loaded.emit(this.config); // return return [2 /*return*/, true]; } }); }); }; Object.defineProperty(ConfigurationService.prototype, "settings", { /** * Gets current application settings */ get: function () { return this.config && this.config.settings; }, enumerable: true, configurable: true }); Object.defineProperty(ConfigurationService.prototype, "currentLocale", { /** * Gets the current user language */ get: function () { var currentLang = localStorage.getItem('currentLang'); if (currentLang) { return currentLang; } if (this.settings && this.settings.i18n && this.settings.i18n.defaultLocale) { // return current language return this.settings.i18n.defaultLocale; } // use fallback language return 'en'; }, set: function (locale) { // save current locale localStorage.setItem('currentLang', locale); // set locale for translate service this._translateService.use(locale); }, enumerable: true, configurable: true }); ConfigurationService.decorators = [ { type: Injectable } ]; /** @nocollapse */ ConfigurationService.ctorParameters = function () { return [ { type: TranslateService }, { type: Injector }, { type: HttpClient } ]; }; return ConfigurationService; }()); var $$1 = jQuery; var DIALOG_BUTTONS; (function (DIALOG_BUTTONS) { DIALOG_BUTTONS[DIALOG_BUTTONS["Ok"] = 1] = "Ok"; DIALOG_BUTTONS[DIALOG_BUTTONS["Yes"] = 2] = "Yes"; DIALOG_BUTTONS[DIALOG_BUTTONS["No"] = 4] = "No"; DIALOG_BUTTONS[DIALOG_BUTTONS["Abort"] = 8] = "Abort"; DIALOG_BUTTONS[DIALOG_BUTTONS["Retry"] = 16] = "Retry"; DIALOG_BUTTONS[DIALOG_BUTTONS["Ignore"] = 32] = "Ignore"; DIALOG_BUTTONS[DIALOG_BUTTONS["Cancel"] = 64] = "Cancel"; DIALOG_BUTTONS[DIALOG_BUTTONS["YesNo"] = 6] = "YesNo"; DIALOG_BUTTONS[DIALOG_BUTTONS["AbortRetryIgnore"] = 54] = "AbortRetryIgnore"; DIALOG_BUTTONS[DIALOG_BUTTONS["OkCancel"] = 65] = "OkCancel"; DIALOG_BUTTONS[DIALOG_BUTTONS["YesNoCancel"] = 70] = "YesNoCancel"; })(DIALOG_BUTTONS || (DIALOG_BUTTONS = {})); var DialogComponent = /** @class */ (function () { function DialogComponent(_element, _translateService) { this._element = _element; this._translateService = _translateService; this.buttons = DIALOG_BUTTONS.Ok; this.language = 'en'; this.language = this._translateService.currentLang; } DialogComponent.prototype.bitwiseAnd = function (a, b) { return a & b; }; /** * Shows modal dialog * @returns Promise<any> */ DialogComponent.prototype.show = function () { var _this = this; return new Promise(function (resolve, reject) { if (_this.modalRef) { _this.modalRef.one('hide.bs.modal', function (event) { // get related target if any var result = _this.modalRef.data('result'); // return result return resolve(result); }); _this.modalRef.modal('show'); } else { reject('Modal element may not be empty at this context'); } }); }; /** * Hides modal dialog * @param value */ DialogComponent.prototype.hide = function (value) { this.modalRef.data('result', value); this.modalRef.modal('hide'); }; /** * Converts modal buttons classes modal-ok, modal-yes-no etc to dialog buttons * @param {Array<string>} classList */ DialogComponent.prototype.classListToButtons = function (classList) { return classList.map(function (classListElement) { // maps each item to an array of matches (if match) return /^modal(-ok)?(-yes)?(-no)?(-abort)?(-retry)?(-ignore)?(-cancel)?/ig.exec(classListElement); }).filter(function (match) { // filter not matched elements return match != null; }).map(function (match) { // maps each match as an array of 2 ^ k results return match.map(function (item, k) { if (item && k > 0) { return Math.pow(2, k - 1); } return 0; }).reduce(function (a, b) { // return a sum of results return a + b; }); }).reduce(function (a, b) { // return a final sum of results return a | b; }); }; DialogComponent.prototype.ngOnInit = function () { return __awaiter(this, void 0, void 0, function () { var classList, classListButtons; return __generator(this, function (_a) { classList = Array.from(this._element.nativeElement.classList); classListButtons = this.classListToButtons(classList); // if element has button classes (modal-ok, modal-yes-no etc) if (classListButtons) { // set dialog buttons this.buttons = classListButtons; } this.modalRef = $$1(this._element.nativeElement); // initialize modal this.modalRef.modal({ backdrop: 'static', focus: true, keyboard: false, show: false }); return [2 /*return*/]; }); }); }; DialogComponent.decorators = [ { type: Component, args: [{ selector: 'universis-dialog.modal', template: "\n <div class=\"modal-dialog\" [ngClass]=\"theme\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h4 class=\"modal-title\">{{title | translate}}</h4>\n </div>\n <div class=\"modal-body\" [innerHTML]=\"message\"></div>\n <div class=\"modal-footer\">\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 1)\"\n (click)=\"hide('ok')\" class=\"btn btn-theme btn-ok\" [translate]=\"'OK'\"></button>\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 2)\"\n (click)=\"hide('yes')\" class=\"btn btn-theme btn-yes\" [translate]=\"'Yes'\"></button>\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 4)\"\n (click)=\"hide('no')\" class=\"btn btn-gray-100 btn-no\" [translate]=\"'No'\"></button>\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 8)\"\n (click)=\"hide('abort')\" class=\"btn btn-danger btn-abort\" [translate]=\"'Abort'\"></button>\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 16)\"\n (click)=\"hide('retry')\" class=\"btn btn-gray-100 btn-retry\" [translate]=\"'Retry'\"></button>\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 32)\"\n (click)=\"hide('ignore')\" class=\"btn btn-gray-100 btn-ignore\" [translate]=\"'Ignore'\"></button>\n <button [lang]=\"language\" type=\"button\" *ngIf=\"bitwiseAnd(buttons, 64)\"\n (click)=\"hide('cancel')\" class=\"btn btn-gray-100 btn-cancel\" [translate]=\"'Cancel'\"></button>\n </div>\n </div>\n </div>\n ", styles: ["\n .modal-dialog .modal-body {\n margin-top: 0;\n margin-bottom: 0;\n }\n .modal-footer {\n border-top: 0;\n }\n .modal-ok {\n //\n }\n .modal-ok-cancel {\n //\n }\n .modal-yes-no {\n //\n }\n .modal-yes-no-cancel {\n //\n }\n .modal-abort-ignore-retry {\n //\n }\n .btn {\n text-transform: uppercase;\n font-size: 16px;\n }\n "] }] } ]; /** @nocollapse */ DialogComponent.ctorParameters = function () { return [ { type: ElementRef }, { type: TranslateService } ]; }; DialogComponent.propDecorators = { title: [{ type: Input }], message: [{ type: Input }], theme: [{ type: Input }] }; return DialogComponent; }()); /** * * Displays a Modal window or a type of Notification (based on choice the color changes) * @export * @class ModalService */ var ModalService = /** @class */ (function () { function ModalService(componentFactoryResolver, appRef, injector, modalService) { this.componentFactoryResolver = componentFactoryResolver; this.appRef = appRef; this.injector = injector; this.modalService = modalService; this.config = { ignoreBackdropClick: true, keyboard: false, initialState: null, class: 'modal-content-base' }; } ModalService.prototype.showDialog = function (title, message, buttons, extras) { var _this = this; if (buttons === void 0) { buttons = DIALOG_BUTTONS.Ok; } var componentRef = this.componentFactoryResolver .resolveComponentFactory(DialogComponent) .create(this.injector); componentRef.instance.title = title; componentRef.instance.message = message; componentRef.instance.buttons = buttons; if (extras) { componentRef.instance.theme = extras.theme; } // attach component to the appRef so that it's inside the ng component tree this.appRef.attachView(componentRef.hostView); // get DOM element from component var modalElement = componentRef.hostView .rootNodes[0]; // append DOM element to the body document.body.appendChild(modalElement); return componentRef.instance.ngOnInit().then(function () { // show dialog return componentRef.instance.show().then(function (result) { // detach view _this.appRef.detachView(componentRef.hostView); // destroy component ref componentRef.destroy(); // return Promise.resolve(result); }); }); }; ModalService.prototype.showWarningDialog = function (title, message, buttons, icon) { if (buttons === void 0) { buttons = DIALOG_BUTTONS.OkCancel; } return this.showDialog(null, "<div class=\"text-center\">\n <div class=\"icon-circle icon-circle-warning\">\n <i class=\"" + (icon || 'fa fa-exclamation') + "\"></i>\n </div>\n <div class=\"font-2xl font-weight-bold mt-2\">\n " + title + "\n </div>\n <p class=\"mt-2\">\n " + message + "\n </p>\n </div>\n ", buttons, { theme: 'modal-dialog-warning' }); }; ModalService.prototype.showSuccessDialog = function (title, message, buttons, icon) { if (buttons === void 0) { buttons = DIALOG_BUTTONS.Ok; } return this.showDialog(null, "<div class=\"text-center\">\n <div class=\"icon-circle icon-circle-success\">\n <i class=\"" + (icon || 'fa fa-check') + "\"></i>\n </div>\n <div class=\"font-2xl font-weight-bold mt-2\">\n " + title + "\n </div>\n <p class=\"mt-2\">\n " + message + "\n </p>\n </div>\n ", buttons, { theme: 'modal-dialog-success' }); }; ModalService.prototype.showErrorDialog = function (title, message, buttons, icon) { if (buttons === void 0) { buttons = DIALOG_BUTTONS.Ok; } return this.showDialog(null, "<div class=\"text-center\">\n <div class=\"icon-circle icon-circle-danger\">\n <i class=\"" + (icon || 'fa fa-times') + "\"></i>\n </div>\n <div class=\"font-2xl font-weight-bold mt-2\">\n " + title + "\n </div>\n <p class=\"mt-2\">\n " + message + "\n </p>\n </div>\n ", buttons, { theme: 'modal-dialog-danger' }); }; ModalService.prototype.showDangerDialog = function (title, message, buttons, icon) { if (buttons === void 0) { buttons = DIALOG_BUTTONS.Ok; } return this.showDialog(null, "<div class=\"text-center\">\n <div class=\"icon-circle icon-circle-danger\">\n <i class=\"" + (icon || 'fa fa-exclamation') + "\"></i>\n </div>\n <div class=\"font-2xl font-weight-bold mt-2\">\n " + title + "\n </div>\n <p class=\"mt-2\">\n " + message + "\n </p>\n </div>\n ", buttons, { theme: 'modal-dialog-danger' }); }; ModalService.prototype.showInfoDialog = function (title, message, buttons, icon) { if (buttons === void 0) { buttons = DIALOG_BUTTONS.Ok; } return this.showDialog(null, "<div class=\"text-center\">\n <div class=\"icon-circle icon-circle-info\">\n <i class=\"" + (icon || 'fa fa-info') + "\"></i>\n </div>\n <div class=\"font-2xl font-weight-bold mt-2\">\n " + title + "\n </div>\n <p class=\"mt-2\">\n " + message + "\n </p>\n </div>\n ", buttons, { theme: 'modal-dialog-info' }); }; ModalService.prototype.openModal = function (template$$1, customClass) { var config; if (customClass) { config = JSON.parse(JSON.stringify(this.config)); config.class = customClass; } else { config = this.config; } return this.modalRef = this.modalService.show(template$$1, config); }; ModalService.prototype.openModalComponent = function (template$$1, options) { return this.modalRef = this.modalService.show(template$$1, options); }; ModalService.decorators = [ { type: Injectable } ]; /** @nocollapse */ ModalService.ctorParameters = function () { return [ { type: ComponentFactoryResolver }, { type: ApplicationRef }, { type: Injector }, { type: BsModalService } ]; }; return ModalService; }()); /** * * Component for Card-Box element with Inputs: * Usage <universis-msgbox [title]="HelloWorld" ...></universis-msgbox> * @Input() title: Title of Box * @Input() icon: Icon displayed on the left of the element * @Input() info: The Status displayed on user * @Input() message: Explanation of the status * @Input() extraMessage: Some extra guidence * @Input() actionButton: Text displayed as Text in button * @Input() actionText: Text displayed as an action * @Input() disableBut: Disable button * @export */ var MsgboxComponent = /** @class */ (function () { function MsgboxComponent() { // Default class sets the color to green, otherwise pass it the correct bootstrap class this.buttonClass = 'btn-success'; // Usage (action)="someFunction()" this.action = new EventEmitter(); } MsgboxComponent.prototype.clicked = function () { this.action.emit(); }; MsgboxComponent.decorators = [ { type: Component, args: [{ selector: 'universis-msgbox', template: "<div class=\"card\">\n <div class=\"msgbox_main-container\">\n <div class=\"msgbox_icon\">\n <span class=\"fa-4x far {{icon}}\" style=\"color:#678898;\"></span>\n </div>\n <div class=\"msgbox_details\">\n <div *ngIf=\"title && !title.includes('title')\" class=\"msgbox_title\" id=\"title\">{{title}}</div>\n <div class=\"font pt-3 msgbox_item\" id=\"message\">{{message}}</div>\n <div class=\"pt-3 msgbox_item\" *ngIf=\"extraMessage && !extraMessage.includes('extraMessage')\">{{extraMessage}}</div>\n <div>\n <div class=\"pt-3 msgbox_item\" *ngIf=\"actionButton && !actionButton.includes('actionButton')\">\n <button type=\"button\" class=\"btn s--btn\" [ngClass]=\"buttonClass\" [disabled]=\"disableBut\" (click)=\"clicked()\">{{actionButton}}</button>\n </div>\n <div class=\"pt-3 msgbox_item\" *ngIf=\"actionText && !actionText.includes('actionText')\" id=\"text\">\n <span><span class=\"fa-1x icon-arrow-right\"></span>{{actionText}}</span>\n </div>\n </div>\n </div>\n </div>\n</div>\n", styles: [".msgbox_main-container{display:flex;margin:30px 40px}.msgbox_title{text-transform:uppercase;color:#536c79}.msgbox_details{display:flex;flex-direction:column;justify-content:center}.msgbox_icon{padding-right:60px;padding-left:20px;display:flex;align-items:center}.msgbox_item{display:flex}@media screen and (max-width:600px){.msgbox_main-container{flex-direction:column;align-items:center}.msgbox_title{text-align:center;justify-content:center;padding:1rem 5px 0}.msgbox_item{justify-content:center;text-align:center}.msgbox_icon{padding-right:0;padding-left:0;justify-content:center}}"] }] } ]; MsgboxComponent.propDecorators = { title: [{ type: Input }], icon: [{ type: Input }], info: [{ type: Input }], message: [{ type: Input }], extraMessage: [{ type: Input }], actionButton: [{ type: Input }], actionText: [{ type: Input }], disableBut: [{ type: Input }], buttonClass: [{ type: Input }], action: [{ type: Output }] }; return MsgboxComponent; }()); /** * * A native spinner component * @export * @class SpinnerComponent * @implements {OnInit} */ var SpinnerComponent = /** @class */ (function () { function SpinnerComponent() { } SpinnerComponent.prototype.ngOnInit = function () { // }; SpinnerComponent.decorators = [ { type: Component, args: [{ selector: 'universis-spinner', template: "\n <div class=\"s--spinner\">\n <div class=\"sk-three-bounce\">\n <div class=\"sk-child sk-bounce1\"></div>\n <div class=\"sk-child sk-bounce2\"></div>\n <div class=\"sk-child sk-bounce3\"></div>\n </div>\n </div>\n ", styles: [".s--spinner{position:fixed;width:100%;height:100%;top:0;background-color:rgba(127,127,127,.5);z-index:10000;display:flex!important;justify-content:center!important;align-items:center!important}@media screen and (-ms-high-contrast:active),(-ms-high-contrast:none){.s--spinner .sk-three-bounce{display:table-cell}}.sk-three-bounce{margin:40px auto;width:80px;text-align:center}.sk-three-bounce .sk-child{width:20px;height:20px;background-color:#333;border-radius:100%;display:inline-block;animation:1.4s ease-in-out infinite both sk-three-bounce}.sk-three-bounce .sk-bounce1{animation-delay:-.32s}.sk-three-bounce .sk-bounce2{animation-delay:-.16s}@keyframes sk-three-bounce{0%,100%,80%{transform:scale(0)}40%{transform:scale(1)}}"] }] } ]; /** @nocollapse */ SpinnerComponent.ctorParameters = function () { return []; }; return SpinnerComponent; }()); /** * * A native spinner component * @export * @class SpinnerComponent * @implements {OnInit} */ var ToastComponent = /** @class */ (function () { function ToastComponent(_element) { this._element = _element; this.autoHide = true; this.delay = 5000; this.dateCreated = new Date(); } ToastComponent.prototype.ngOnInit = function () { }; ToastComponent.prototype.ngAfterViewInit = function () { this.toast = new Toast(this._element.nativeElement, { animation: false, autohide: this.autoHide, delay: this.delay }); return this.toast.show(); }; ToastComponent.prototype.show = function () { if (this.toast) { this.toast.show(); } }; ToastComponent.prototype.hide = function () { var container = document.body.getElementsByClassName('universis-toast-container')[0]; if (container.getElementsByClassName('show').length === 1) { container.classList.add('hidden'); } if (this.toast) { this.toast.hide(); } }; ToastComponent.decorators = [ { type: Component, args: [{ selector: 'universis-toast.toast', template: "\n <div class=\"toast-header d-flex p-0\">\n <strong class=\"mr-auto\">{{ title }}</strong>\n <button type=\"button\" class=\"ml-2 mb-1 align-self-start close\" data-dismiss=\"toast\" (click)=\"hide();\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n <div class=\"toast-body p-0\">\n <div class=\"toast-body-content\" [innerHTML]=\"message\"></div>\n </div>\n <div class=\"toast-header p-0\">\n <small class=\"toast-date\">{{ dateCreated | date: 'shortTime'}}</small>\n </div>\n ", styles: [":host {\n z-index: auto;\n }"] }] } ]; /** @nocollapse */ ToastComponent.ctorParameters = function () { return [ { type: ElementRef } ]; }; ToastComponent.propDecorators = { title: [{ type: Input }], message: [{ type: Input }], autoHide: [{ type: Input }], delay: [{ type: Input }] }; return ToastComponent; }()); /** * @export * @class ToastService */ var ToastService = /** @class */ (function () { function ToastService(componentFactoryResolver, appRef, injector) { this.componentFactoryResolver = componentFactoryResolver; this.appRef = appRef; this.injector = injector; } /** * Shows a toast message * @param {string} title A string which represents message title * @param {string} message A string which represents message body * @param {boolean=} autoHide A boolean which indicates whether or not message will auto hide * @param {number=} delay A number which indicates the number of milliseconds before auto hide message */ ToastService.prototype.show = function (title, message, autoHide, delay) { if (autoHide === void 0) { autoHide = true; } if (delay === void 0) { delay = 5000; } // search for toast container var container = document.body.getElementsByClassName('universis-toast-container')[0]; if (container == null) { // create toast container container = document.createElement('div'); container.classList.add('universis-toast-container', 'p-3'); // append to boyd document.body.appendChild(container); } // create a component reference for toast component var componentRef = this.componentFactoryResolver .resolveComponentFactory(ToastComponent) .create(this.injector); componentRef.instance.title = title; componentRef.instance.message = message; componentRef.instance.autoHide = autoHide; componentRef.instance.delay = delay; componentRef.location.nativeElement.classList.add('ml-auto'); // attach component to the appRef so that it's inside the ng component tree this.appRef.attachView(componentRef.hostView); // get DOM element from component var domElem = componentRef.hostView.rootNodes[0]; // append DOM element to the body container.appendChild(domElem); container.classList.remove('hidden'); setTimeout(function () { componentRef.instance.hide(); }, delay); }; // noinspection JSMethodCanBeStatic /** * Clears toast messages */ ToastService.prototype.clear = function () { // search for toast container var container = document.body.getElementsByClassName('universis-toast-container')[0]; if (container) { // remove children while (container.firstChild) { container.removeChild(container.firstChild); } } }; ToastService.decorators = [ { type: Injectable } ]; /** @nocollapse */ ToastService.ctorParameters = function () { return [ { type: ComponentFactoryResolver }, { type: ApplicationRef }, { type: Injector } ]; }; return ToastService; }()); function round(x, n) { if (typeof x !== 'number') { return 0; } if (n) { return parseFloat(x.toFixed(n)); } return Math.round(x); } var GradeScale = /** @class */ (function () { function GradeScale(_locale, scale) { if (scale === void 0) { scale = null; } this._locale = _locale; this.scale = scale; this.formatPrecision = 2; this.scalePrecision = 2; // init decimal pipe this._formatter = new DecimalPipe(this._locale); // get decimal separator regular expression this._decimalCharRegExp = new RegExp('\\' + this._formatter.transform(0.1, '1.1-1').substr(1, 1), 'ig'); if (scale) { this.id = scale['id']; this.name = scale['name']; this.scaleType = scale['scaleType']; this.scaleFactor = scale['scaleFactor']; this.scaleBase = scale['scaleBase']; this.formatPrecision = scale['formatPrecision']; this.scalePrecision = scale['scalePrecision']; this.values = scale['values']; } } /** * Formats the specified based on this grade scale and returns the formatted value * @param {number} grade * @returns string */ GradeScale.prototype.format = function (grade) { if (this.scaleType === 0) { if (typeof this.scaleFactor !== 'number') { throw new TypeError('Grade scale factor must be a number.'); } if (this.scaleFactor <= 0) { throw new TypeError('Grade scale factor must greater than zero.'); } // arithmetic grade scale if (typeof grade === 'number') { // get final grade by applying rounding var finalGrade = round(round((grade / this.scaleFactor), 6), this.formatPrecision); // return formatted value based on the current locale return this._formatter.transform(finalGrade, "1." + this.formatPrecision + "-" + this.formatPrecision); } return; } else if (this.scaleType === 1 || this.scaleType === 3) { var finalValue_1 = round(grade, this.scalePrecision); var findValue = this.values.find(function (x) { return finalValue_1 >= x.valueFrom && finalValue_1 <= x.valueTo; }); if (findValue) { return findValue.name; } throw new RangeError('Out of range value for grade'); } throw new Error('Not yet implemented'); }; /** * Converts the given grade to the equivalent grade value base on this grade scale * @param grade */ GradeScale.prototype.convert = function (grade) { if (this.scaleType === 0) { var finalGrade = void 0; // if grade is a number if (typeof grade === 'undefined' || grade === null) { return; } else if (typeof grade === 'number') { finalGrade = grade; } else if (typeof grade === 'string') { // try to convert the given grade finalGrade = parseFloat(grade.replace(this._decimalCharRegExp, '.')); if (isNaN(finalGrade)) { return; } } if (typeof this.scaleFactor !== 'number') { throw new TypeError('Grade scale factor must be a number.'); } if (this.scaleFactor <= 0) { throw new TypeError('Grade scale factor must greater than zero.'); } // validate grade var res = round((finalGrade * this.scaleFactor), this.formatPrecision + 1); // throw error if result is greater than 1 if (res < 0 || res > 1) { throw new Error('Grade is out of range. It must be between 0 to 1.'); } return res; } else if (this.scaleType === 1 || this.scaleType === 3) { var findValue = this.values.find(function (x) { return x.name === grade || x.alternateName === grade; }); if (findValue) { return findValue.exactValue; } throw new RangeError('Out of range value for grade'); } throw new Error('Not yet implemented'); }; return GradeScale; }()); var GradeScaleService = /** @class */ (function () { function GradeScaleService(_context, _configurationService) { this._context = _context; this._configurationService = _configurationService; // } /** * Gets all the available grade scales */ GradeScaleService.prototype.getGradeScales = function () { var _this = this; if (this._gradeScales) { return Promise.resolve(this._gradeScales); } return this._context.model('GradeScales').getItems().then(function (result) { var locale = _this._configurationService.currentLocale; _this._gradeScales = result.map(function (x) { return Object.assign(new GradeScale(locale), x); }); return Promise.resolve(_this._gradeScales); }, function (err) { console.log(err); return null; }); }; /** * Gets a grade scale based on the given identifier * @param {*} id */ GradeScaleService.prototype.getGradeScale = function (id) { if (this._gradeScales) { return Promise.resolve(this._gradeScales.find(function (value) { return value.id === id; })); } return this.getGradeScales().then(function (res) { return Promise.resolve(res.find(function (value) { return value.id === id; })); }); }; GradeScaleService.decorators = [ { type: Injectable } ]; /** @nocollapse */ GradeScaleService.ctorParameters = function () { return [ { type: AngularDataContext }, { type: ConfigurationService } ]; }; return GradeScaleService; }()); var GradePipe = /** @class */ (function () { function GradePipe(_gradeScaleService) { this._gradeScaleService = _gradeScaleService; // } GradePipe.prototype.transform = function (value, gradeScale) { if (gradeScale instanceof GradeScale) { return Promise.resolve(gradeScale.format(value)); } return this._gradeScaleService.getGradeScale(gradeScale).then(function (result) { if (typeof result === 'undefined') { return Promise.reject(new Error('The specified grade scale cannot be found or is inaccessible')); } return Promise.resolve(result.format(value)); }); }; GradePipe.decorators = [ { type: Pipe, args: [{ name: 'grade' },] } ]; /** @nocollapse */ GradePipe.ctorParameters = function () { return [ { type: GradeScaleService } ]; }; return GradePipe; }()); /** * * Displays Loading Spinner * @export * @class LoadingService */ var LoadingService = /** @class */ (function () { function LoadingService(componentFactoryResolver, appRef, injector) { this.componentFactoryResolver = componentFactoryResolver; this.appRef = appRef; this.injector = injector; } LoadingService.prototype.appendComponentToBody = function (component) { // do nothing if component ref already exists if (this.componentRef) { return; } // create a component reference from the component this.componentRef = this.componentFactoryResolver .resolveComponentFactory(component) .create(this.injector); // attach component to the appRef so that it's inside the ng component tree this.appRef.attachView(this.componentRef.hostView); // get DOM element from component var domElem = this.componentRef.hostView .rootNodes[0]; // append DOM element to the body document.body.appendChild(domElem); }; /** * * Toggles show/hide state of spinner */ LoadingService.prototype.toggle = function () { if (this.componentRef) { this.hideLoading(); } else { this.showLoading(); } }; /** * * Shows spinner */ LoadingService.prototype.showLoading = function () { if (this.componentRef == null) { this.appendComponentToBody(SpinnerComponent); } }; /** * * Hides spinner */ LoadingService.prototype.hideLoading = function () { if (this.componentRef) { this.appRef.detachView(this.componentRef.hostView); this.componentRef.destroy(); this.componentRef = null; } }; LoadingService.decorators = [ { type: Injectable } ]; /** @nocollapse */ LoadingService.ctorParameters = function () { return [ { type: ComponentFactoryResolver }, { type: ApplicationRef }, { type: Injector } ]; }; return LoadingService; }()); /** * * Custom DatePipe representation * @export * @class LocalizedDatePipe * @implements {PipeTransform} */ var LocalizedDatePipe = /** @class */ (function () { function LocalizedDatePipe(translateService) { this.translateService = translateService; } /** * * Converts Date value that been passed * @param {*} value The Date that needs to be converted * @param {string} [pattern='mediumDate'] Pattern of Date * @returns {*} Converted Date * @memberof LocalizedDatePipe */ LocalizedDatePipe.prototype.transform = function (value, pattern) { if (pattern === void 0) { pattern = 'mediumDate'; } var datePipe = new DatePipe(this.translateService.currentLang); if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}$/.test(value)) { return datePipe.transform(new Date(value + ':00'), pattern); } return datePipe.transform(value, pattern); }; LocalizedDatePipe.decorators = [ { type: Pipe, args: [{ name: 'localizedDate', pure: false },] } ]; /** @nocollapse */ LocalizedDatePipe.ctorParameters = function () { return [ { type: TranslateService } ]; }; return LocalizedDatePipe; }()); function registration(_numeral$$1) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, _numeral$$1.register('locale', 'el', { delimiters: { thousands: '.', decimal: ',' }, abbreviations: { thousand: 'χιλ', million: 'εκ', billion: 'δισ', trillion: 'τρισ' }, ordinal: function (number) { return 'ο'; }, currency: { symbol: '€' } })]; case 1: _a.sent(); return [4 /*yield*/, _numeral$$1.register('locale', 'el-gr', { delimiters: { thousands: '.', decimal: ',' }, abbreviations: { thousand: 'χιλ', million: 'εκ', billion: 'δισ', trillion: 'τρισ' }, ordinal: function (number) { return 'ο'; }, currency: { symbol: '€' } })]; case 2: _a.sent(); return [4 /*yield*/, _numeral$$1.register('locale', 'cy', { delimiters: { thousands: '.', decimal: ',' }, abbreviations: { thousand: 'χιλ', million: 'εκ', billion: 'δισ', trillion: 'τρισ' }, ordinal: function (number) { return 'ο'; }, currency: { symbol: '€' } })]; case 3: _a.sent(); return [4 /*yield*/, _numeral$$1.register('locale', 'cy-cy', { delimiters: { thousands: '.', decimal: ',' }, abbreviations: { thousand: 'χιλ', million: 'εκ', billion: 'δισ', trillion: 'τρισ' }, ordinal: function (number) { return 'ο'; }, currency: { symbol: '€' } })]; case 4: _a.sent(); return [2 /*return*/]; } }); }); } var numeral = _numeral__default || _numeral; var SemesterPipe = /** @class */ (function () { function SemesterPipe(_translateService) { var _this = this; this._translateService = _translateService; if (numeral.locales['el'] === undefined) { registration(_numeral).then(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, Promise.resolve()]; case 1: _a.sent(); return [2 /*return*/]; } }); }); }); } } SemesterPipe.prototype.transform = function (value, pattern) { if (pattern === void 0) { pattern = 'long'; } if (typeof value === 'object') { value = value.id; } if (value >= 250) { return this._translateService.instant("Semester.full." + value); } numeral.locale(this._translateService.currentLang); return this._translateService.instant("Semester." + pattern, { value: value, ordinal: numeral(value).format('o') }); }; SemesterPipe.decorators = [ { type: Pipe, args: [{ name: 'semester', pure: false },] } ]; /** @nocollapse */ SemesterPipe.ctorParameters = function () { return [ { type: TranslateService } ]; }; return SemesterPipe; }()); /** * Template Pipe is an impure pipe that can escape * HTML and interpolated data properties and * execute JavaScript in "evaluate" delimiters */ var TemplatePipe = /** @class */ (function () { function TemplatePipe() { } /** * Uses lodash template function to generate a string * from a given template escaping the delimiters. It * deletes the template source after its initialization, * generates the string and nullifies the compiled template * function variable to be garbage-collected. * @param {string} inputTemplate: The template used to generate the string * @param {any} value: The parameter passed to compiled template function * @param {Object | undefined} options: Custom options to pass to lodash template */ TemplatePipe.prototype.transform = function (inputTemplate, value, options) { var _tpl; if (options !== undefined) { /* lodash doesn't throw error when options are not valid, so there is not need to add a try catch block */ _tpl = template(inputTemplate, options); } else { _tpl = template(inputTemplate); } delete _tpl.source; var _res = _tpl(value); _tpl = null; return _res; }; TemplatePipe.decorators = [ { type: Pipe, args: [{ name: 'template', pure: false },] } ]; /** @nocollapse */ TemplatePipe.ctorParameters = function () { return []; }; return TemplatePipe; }()); // tslint:disable directive-selector var NgVarDirective = /** @class */ (function () { function NgVarDirective() { } Object.defineProperty(NgVarDirective.prototype, "assign", { set: function (value) { if (value) { Object.assign(this, { $implicit: value }); } }, enumerable: true, configurable: true }); Object.defineProperty(NgVarDirective.prototype, "value", { get: function () { return this.$implicit; }, set: function (value) { this.$implicit = value; }, enumerable: true, configurable: true }); NgVarDirective.decorators = [ { type: Directive, args: [{ selector: '[ngVar]', exportAs: 'ngVar' },] } ]; /** @nocollapse */ NgVarDirective.ctorParameters = function () { return []; }; NgVarDirective.propDecorators = { assign: [{ type: Input, args: ['ngVar',] }] }; return NgVarDirective; }()); // tslint:enable directive-selector /** * @private */ var currentProfileProperty = 'currentProfile'; /** * @private */ var currentUserProperty = 'currentUser'; var UserService = /** @class */ (function () { function UserService(_context, _configurationService) { this._context = _context; this._configurationService = _configurationService; } /** * Refreshes user token taken by implicit authorization flow. */ UserService.prototype.checkLogin = function () { // set refresh frame var settings = this._configurationService.settings.auth; var _iframe = $('<iframe>', { /* tslint:disable max-line-length */ src: settings.authorizeURL + "?response_type=token&client_id=" + settings.oauth2.clientID + "&redirect_uri=" + settings.oauth2.callbackURL + "&prompt=none", id: 'openid', frameborder: 1, scrolling: 'no', onload: function () { // } }).hide().app