leaf-framework
Version:
Light Everis Angular Frontend Framework
1,117 lines (1,081 loc) • 56.9 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/http'), require('@ngx-translate/core'), require('@ngx-translate/http-loader'), require('@angular/common'), require('@angular/forms'), require('@angular/router'), require('ngx-bootstrap'), require('@angular/animations'), require('rxjs/Subject'), require('base-api-service'), require('rxjs/Rx'), require('rxjs/add/operator/map')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/core', '@angular/http', '@ngx-translate/core', '@ngx-translate/http-loader', '@angular/common', '@angular/forms', '@angular/router', 'ngx-bootstrap', '@angular/animations', 'rxjs/Subject', 'base-api-service', 'rxjs/Rx', 'rxjs/add/operator/map'], factory) :
(factory((global.ng = global.ng || {}, global.ng.leafFramework = global.ng.leafFramework || {}),global.ng.core,global._angular_http,global._ngxTranslate_core,global._ngxTranslate_httpLoader,global._angular_common,global._angular_forms,global._angular_router,global.ngxBootstrap,global._angular_animations,global.rxjs_Subject,global.baseApiService,global.rxjs_Rx));
}(this, (function (exports,_angular_core,_angular_http,_ngxTranslate_core,_ngxTranslate_httpLoader,_angular_common,_angular_forms,_angular_router,ngxBootstrap,_angular_animations,rxjs_Subject,baseApiService,rxjs_Rx) { 'use strict';
// custom TranslateLoader while using AoT compilation
function createTranslateLoader(http) {
return new _ngxTranslate_httpLoader.TranslateHttpLoader(http, '/assets/i18n/', '.json');
}
var ValidationService = (function () {
function ValidationService() {
}
ValidationService.getErrorMessage = function (validatorName, validatorValue) {
var config = new Map();
config.set('required', 'This field is mandatory');
config.set('invalidCreditCard', 'Is invalid credit card number');
config.set('invalidEmailAddress', 'Invalid email address');
config.set('invalidPassword', 'Password must be at least 6 characters long, and contain a number.');
config.set('minlength', "Minimum length " + (validatorValue ? validatorValue.requiredLength : 0));
config.set('invalidPositiveNumber', 'The value is invalid');
return config.get(validatorName);
};
ValidationService.positiveNumberValidator = function (control) {
// Visa, MasterCard, American Express, Diners Club, Discover, JCB
if (parseInt(control.value, 10) >= 0) {
return null;
}
else {
return { 'invalidPositiveNumber': true };
}
};
ValidationService.creditCardValidator = function (control) {
// Visa, MasterCard, American Express, Diners Club, Discover, JCB
if (control.value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/)) {
return null;
}
else {
return { 'invalidCreditCard': true };
}
};
ValidationService.emailValidator = function (control) {
// RFC 2822 compliant regex
if (control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) {
return null;
}
else {
return { 'invalidEmailAddress': true };
}
};
ValidationService.passwordValidator = function (control) {
// {6,100} - Assert password is between 6 and 100 characters
// (?=.*[0-9]) - Assert a string has at least one number
if (control.value.match(/^(?=.*[0-9])[a-zA-Z0-9!@#$%^&*]{6,100}$/)) {
return null;
}
else {
return { 'invalidPassword': true };
}
};
ValidationService.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
ValidationService.ctorParameters = function () { return []; };
return ValidationService;
}());
var ControlMessagesComponent = (function () {
function ControlMessagesComponent() {
}
ControlMessagesComponent.prototype.ngOnInit = function () { };
ControlMessagesComponent.prototype.isInvalid = function () {
return this.control && this.control.touched && !this.control.valid;
};
ControlMessagesComponent.prototype.hasError = function (validator) {
return this.control && this.control.hasError(validator) && this.control.touched;
};
Object.defineProperty(ControlMessagesComponent.prototype, "errorMessage", {
get: function () {
if (this.validator) {
this._errorMessage = this.hasError(this.validator) ? this.message || ValidationService.getErrorMessage(this.validator) : null;
}
else if (this.control.errors) {
// iterate all validators and display first error message
for (var propertyName in this.control.errors) {
if (this.hasError(propertyName)) {
this._errorMessage = this.message || ValidationService.getErrorMessage(propertyName);
break;
}
}
}
return this._errorMessage;
},
enumerable: true,
configurable: true
});
ControlMessagesComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: 'app-control-messages',
template: "\n<div *ngIf=\"isInvalid()\" class=\"help-block\">{{ errorMessage }}</div>\n "
},] },
];
/** @nocollapse */
ControlMessagesComponent.ctorParameters = function () { return []; };
ControlMessagesComponent.propDecorators = {
'control': [{ type: _angular_core.Input },],
'message': [{ type: _angular_core.Input },],
'validator': [{ type: _angular_core.Input },],
};
return ControlMessagesComponent;
}());
var LoggerService = (function () {
function LoggerService() {
}
return LoggerService;
}());
var PageNotFoundComponent = (function () {
function PageNotFoundComponent(loggerService) {
this.loggerService = loggerService;
this.title = 'Page not found';
this.message = 'Sorry, This page is not available';
}
PageNotFoundComponent.prototype.ngOnInit = function () {
this.loggerService.log('... initializing page not found component from shared module.');
};
PageNotFoundComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: 'leaf-layout-page-not-found',
template: "\n <div class=\"container text-center\">\n <h2>{{title}}</h2>\n <img class=\"img-responsive\" src=\"assets/images/404-Page-Not-Found.png\" class=\"text-center\">\n <h4>{{message}}</h4>\n </div>\n "
},] },
];
/** @nocollapse */
PageNotFoundComponent.ctorParameters = function () { return [
{ type: LoggerService, decorators: [{ type: _angular_core.Inject, args: ['LoggerService',] },] },
]; };
return PageNotFoundComponent;
}());
var AuthService = (function () {
function AuthService() {
}
return AuthService;
}());
var LoginComponent = (function () {
function LoginComponent(formBuilder, route, router, authService) {
this.formBuilder = formBuilder;
this.route = route;
this.router = router;
this.authService = authService;
this.loading = false;
}
LoginComponent.prototype.ngOnInit = function () {
// reset login status
this.authService.logout();
this.f = this.formBuilder.group({
'username': ['', _angular_forms.Validators.required],
'password': ['', _angular_forms.Validators.required]
});
};
LoginComponent.prototype.isInvalid = function (control) {
return control && control.touched && !control.valid;
};
LoginComponent.prototype.errorClass = function (control) {
var condition = this.isInvalid(control);
return {
'has-error': condition,
'has-feedback': condition
};
};
LoginComponent.prototype.login = function () {
var _this = this;
if (this.f.dirty && this.f.valid) {
this.loading = true;
var username = this.f.value.username, password = this.f.value.password;
this.authService.login(username, password)
.subscribe(function (userData) {
_this.loading = false;
// navigate to returnUrl just if login successfully
if (userData.access_token) {
_this.router.navigate([_this.route.snapshot.queryParams['returnUrl'] || '/']);
}
else {
_this.showAuthError('Token not sent from service during authentication.');
}
}, function (error) {
_this.showAuthError('The user is not authorized');
_this.loading = false;
});
}
};
LoginComponent.prototype.showAuthError = function (message) {
var that = this;
this.authError = message;
setTimeout(function () {
that.authError = null;
}, 1000);
};
LoginComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: 'app-login',
template: "\n <div class=\"col-md-6 col-md-offset-3\">\n <h2>Login</h2>\n <form [formGroup]=\"f\" (ngSubmit)=\"login()\" novalidate>\n <div *ngIf=\"authError\" id=\"message\" role=\"alert\" class=\"alert alert-danger\"><i class=\"fa fa-remove\"></i> {{authError}}</div>\n <div class=\"form-group\" [ngClass]=\"errorClass(f.controls.username)\">\n <label for=\"username\">User name:</label>\n <input type=\"text\" class=\"form-control\" id=\"username\" formControlName=\"username\" placeholder=\"Enter user name ...\">\n <span *ngIf=\"isInvalid(f.controls.username)\" class=\"glyphicon glyphicon-remove form-control-feedback\"></span>\n <leaf-layout-control-messages [formControl]=\"f.controls.username\" [message]=\"'Username is required!'\"></leaf-layout-control-messages>\n </div>\n <div class=\"form-group\" [ngClass]=\"errorClass(f.controls.password)\">\n <label for=\"pwd\">Password:</label>\n <input type=\"password\" class=\"form-control\" id=\"pwd\" formControlName=\"password\" placeholder=\"Enter password ...\">\n <span *ngIf=\"isInvalid(f.controls.password)\" class=\"glyphicon glyphicon-remove form-control-feedback\"></span>\n <leaf-layout-control-messages [formControl]=\"f.controls.password\" [message]=\"'Password is required!'\"></leaf-layout-control-messages>\n </div>\n <div class=\"form-group\">\n <button type=\"submit\" class=\"btn btn-primary\" [disabled]=\"(f.dirty && !f.valid) || loading\">Login</button>\n <img *ngIf=\"loading\" src=\"data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==\" />\n </div>\n </form>\n </div>\n "
},] },
];
/** @nocollapse */
LoginComponent.ctorParameters = function () { return [
{ type: _angular_forms.FormBuilder, },
{ type: _angular_router.ActivatedRoute, },
{ type: _angular_router.Router, },
{ type: AuthService, decorators: [{ type: _angular_core.Inject, args: ['AuthService',] },] },
]; };
return LoginComponent;
}());
// import the required animation functions from the angular animations module
var titleTemplateAnimation = _angular_animations.trigger('titleTemplateAnimation', [
_angular_animations.transition(':enter', [
_angular_animations.style({ opacity: 0, position: 'relative', top: '-100px', 'transition-timing-function': 'ease-out' }),
_angular_animations.animate('0.4s', _angular_animations.style({ opacity: 1, top: '0px' }))
])
]);
var LeafPageTemplate = (function () {
function LeafPageTemplate() {
}
LeafPageTemplate.decorators = [
{ type: _angular_core.Component, args: [{
selector: '[leaf-page-template]',
template: "\n <div class=\"row wrapper border-bottom white-bg page-heading ng-scope\" *ngIf=\"title\" [@titleTemplateAnimation]>\n <div [ngClass]=\"{'col-sm-4': (titleRightWrapper.children.length > 0), 'col-sm-12' : (titleRightWrapper.children.length === 0)}\">\n <h2 class=\"m-b-xxs\">{{ title }}</h2>\n </div>\n <div class=\"col-sm-8\" [ngClass]=\"{'hidden': titleRightWrapper.children.length === 0}\">\n <div class=\"pull-right m-t-md\" #titleRightWrapper>\n <ng-content select=\"[title-right]\"></ng-content>\n </div>\n </div>\n </div>\n <div class=\"row\" >\n <div class=\"col-lg-12\">\n <div class=\"wrapper wrapper-content\">\n <ng-content select=\"[content]\"></ng-content>\n </div>\n </div>\n </div>\n ",
animations: [titleTemplateAnimation]
},] },
];
/** @nocollapse */
LeafPageTemplate.ctorParameters = function () { return []; };
LeafPageTemplate.propDecorators = {
'title': [{ type: _angular_core.Input },],
};
return LeafPageTemplate;
}());
var SpinnerService = (function () {
function SpinnerService() {
this.spinnerSubject = new rxjs_Subject.Subject();
this.spinnerState = this.spinnerSubject.asObservable();
}
SpinnerService.prototype.show = function () {
this.spinnerSubject.next({ show: true });
};
SpinnerService.prototype.hide = function () {
this.spinnerSubject.next({ show: false });
};
SpinnerService.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
SpinnerService.ctorParameters = function () { return []; };
return SpinnerService;
}());
(function (CookieIdentifiers) {
CookieIdentifiers["USER_ID"] = "userId";
CookieIdentifiers["TOKEN_ID"] = "token";
})(exports.CookieIdentifiers || (exports.CookieIdentifiers = {}));
// import { environment } from '../../../environments/environment';
var AuthHelper = (function () {
function AuthHelper(apiConfig) {
this.apiConfig = apiConfig;
}
/**
* Determine if there is a user correctly logued in the app
*/
AuthHelper.prototype.isUserLogged = function () {
if (this.apiConfig.authService.name === 'SkypAuthService') {
return true;
}
var userId = this.getUserLogged();
var token = this.getToken();
return (!baseApiService.CommonUtil.isEmpty(userId) && !baseApiService.CommonUtil.isEmpty(token));
};
/**
* Returns the name of the user logged in the app
*/
AuthHelper.prototype.getUserLogged = function () {
if (this.apiConfig.authService.name === 'SkypAuthService') {
return null;
}
return baseApiService.CommonUtil.getCookie(exports.CookieIdentifiers.USER_ID);
};
/**
* Returns the token stored after login
*/
AuthHelper.prototype.getToken = function () {
if (this.apiConfig.authService.name === 'SkypAuthService') {
return null;
}
return baseApiService.CommonUtil.getCookie(exports.CookieIdentifiers.TOKEN_ID);
};
/**
* Add user id to the cookie
* @param value the value of the user id
* @param expiredTime the total seconds after the page should expire
*/
AuthHelper.prototype.addUserInfo = function (value, expiredTime) {
var expiredTimeString = baseApiService.CommonUtil.changeExpiredTime(expiredTime * 60 * 1000);
document.cookie = exports.CookieIdentifiers.USER_ID + '=' + value + '; expires=' + expiredTimeString + '; path=/';
};
/**
* Add token to the cookie
* @param value the value of the token
* @param expiredTime the total seconds after the page should expire
*/
AuthHelper.prototype.addTokenInfo = function (value, expiredTime) {
var expiredTimeString = baseApiService.CommonUtil.changeExpiredTime(expiredTime * 60 * 1000);
document.cookie = exports.CookieIdentifiers.TOKEN_ID + '=' + value + '; expires=' + expiredTimeString + '; path=/';
};
/**
* Remove the user id from the cookie
*/
AuthHelper.prototype.removeUserInfo = function () {
var expiredTimeString = baseApiService.CommonUtil.changeExpiredTime(0);
document.cookie = exports.CookieIdentifiers.USER_ID + '=; expires=' + expiredTimeString + '; path=/';
};
/**
* Remove the token from the cookie
*/
AuthHelper.prototype.removeTokenInfo = function () {
var expiredTimeString = baseApiService.CommonUtil.changeExpiredTime(0);
document.cookie = exports.CookieIdentifiers.TOKEN_ID + '=; expires=' + expiredTimeString + '; path=/';
};
/** @nocollapse */
AuthHelper.ctorParameters = function () { return [
{ type: baseApiService.ApiConfig, decorators: [{ type: _angular_core.Inject, args: ['api.config',] },] },
]; };
return AuthHelper;
}());
var __extends = (undefined && undefined.__extends) || (function () {
var 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 function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var InterceptedHttp = (function (_super) {
__extends(InterceptedHttp, _super);
function InterceptedHttp(backend, defaultOptions, spinnerService, authHelper) {
var _this = _super.call(this, backend, defaultOptions) || this;
_this.spinnerService = spinnerService;
_this.authHelper = authHelper;
// TODO how to inject these values into the service
_this.NOT_REQUIRE_AUTH = ['/oauth/token', 'logout'];
_this.AUTH_TYPE = 'Bearer';
return _this;
}
InterceptedHttp.prototype.get = function (url, options) {
var _this = this;
if (this.isHttpService(url)) {
if (this.canCallHttp(url)) {
this.requestInterceptor(url);
return _super.prototype.get.call(this, url, this.getRequestOptionArgs(options)).finally(function () { return _this.onFinally(); });
}
else {
return this.getAuthError();
}
}
else {
// if is other kind of resource
return _super.prototype.get.call(this, url, this.getRequestOptionArgs(options));
}
};
InterceptedHttp.prototype.post = function (url, body, options) {
var _this = this;
if (this.isHttpService(url)) {
if (this.canCallHttp(url)) {
this.requestInterceptor(url);
return _super.prototype.post.call(this, url, body, this.getRequestOptionArgs(options)).finally(function () { return _this.onFinally(); });
}
else {
return this.getAuthError();
}
}
else {
// if is other kind of resource
return _super.prototype.post.call(this, url, body, this.getRequestOptionArgs(options));
}
};
InterceptedHttp.prototype.put = function (url, body, options) {
var _this = this;
if (this.isHttpService(url)) {
if (this.canCallHttp(url)) {
this.requestInterceptor(url);
return _super.prototype.put.call(this, url, body, this.getRequestOptionArgs(options)).finally(function () { return _this.onFinally(); });
}
else {
return this.getAuthError();
}
}
else {
// if is other kind of resource
return _super.prototype.put.call(this, url, body, this.getRequestOptionArgs(options));
}
};
InterceptedHttp.prototype.delete = function (url, options) {
var _this = this;
if (this.isHttpService(url)) {
if (this.canCallHttp(url)) {
this.requestInterceptor(url);
return _super.prototype.delete.call(this, url, this.getRequestOptionArgs(options)).finally(function () { return _this.onFinally(); });
}
else {
return this.getAuthError();
}
}
else {
// if is other kind of resource
return _super.prototype.delete.call(this, url, this.getRequestOptionArgs(options));
}
};
/**
* Determine if the url is a valid http service
*/
InterceptedHttp.prototype.isHttpService = function (url) {
return url && url.startsWith('http');
};
/**
* Returns true If the url doesn't require previous authentication or require it bu the user is already logged in
*/
InterceptedHttp.prototype.canCallHttp = function (url) {
return this.authHelper.isUserLogged || !this.needAuthBefore(url);
};
InterceptedHttp.prototype.needAuthBefore = function (url) {
if (url == null) {
return null;
}
return this.NOT_REQUIRE_AUTH.find(function (partUrl) { return url.indexOf(partUrl) >= 0; }) == null;
};
InterceptedHttp.prototype.getAuthError = function () {
return rxjs_Rx.Observable.throw({ status: 401, statusText: 'UNAUTHORIZED' });
};
InterceptedHttp.prototype.getRequestOptionArgs = function (options) {
options = options || new _angular_http.RequestOptions();
options.headers = options.headers || new _angular_http.Headers();
if (!options.headers.get('content-type')) {
options.headers.append('content-type', 'application/json; charset=utf-8');
}
var token = baseApiService.CommonUtil.getCookie(exports.CookieIdentifiers.TOKEN_ID);
if (!baseApiService.CommonUtil.isEmpty(token)) {
options.headers.set('Authorization', this.AUTH_TYPE + " " + token);
}
return options;
};
/**
* Request interceptor.
*/
InterceptedHttp.prototype.requestInterceptor = function (url) {
if (this.needAuthBefore(url)) {
this.spinnerService.show();
}
};
/**
* Response interceptor.
*/
InterceptedHttp.prototype.responseInterceptor = function () {
this.spinnerService.hide();
};
/**
* onFinally
*/
InterceptedHttp.prototype.onFinally = function () {
this.responseInterceptor();
};
InterceptedHttp.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
InterceptedHttp.ctorParameters = function () { return [
{ type: _angular_http.ConnectionBackend, },
{ type: _angular_http.RequestOptions, },
{ type: SpinnerService, },
{ type: AuthHelper, },
]; };
return InterceptedHttp;
}(_angular_http.Http));
// translate
var LeafFrameworkShared = (function () {
function LeafFrameworkShared() {
}
LeafFrameworkShared.decorators = [
{ type: _angular_core.NgModule, args: [{
imports: [
_angular_common.CommonModule,
_angular_http.HttpModule,
_angular_forms.FormsModule,
_angular_forms.ReactiveFormsModule,
_angular_router.RouterModule,
ngxBootstrap.ModalModule.forRoot(),
_ngxTranslate_core.TranslateModule
],
declarations: [
LoginComponent,
PageNotFoundComponent,
ControlMessagesComponent,
LeafPageTemplate
],
exports: [
_angular_common.CommonModule,
_angular_http.HttpModule,
_angular_forms.FormsModule,
_angular_forms.ReactiveFormsModule,
_angular_router.RouterModule,
_ngxTranslate_core.TranslateModule,
ngxBootstrap.ModalModule,
LoginComponent,
PageNotFoundComponent,
ControlMessagesComponent,
LeafPageTemplate
],
providers: [
{ provide: _angular_http.Http, useClass: InterceptedHttp, deps: [_angular_http.XHRBackend, _angular_http.RequestOptions, SpinnerService, AuthHelper] }
],
schemas: [_angular_core.CUSTOM_ELEMENTS_SCHEMA]
},] },
];
/** @nocollapse */
LeafFrameworkShared.ctorParameters = function () { return []; };
return LeafFrameworkShared;
}());
var MinimalizeComponent = (function () {
function MinimalizeComponent(applicationRef) {
this.applicationRef = applicationRef;
}
MinimalizeComponent.prototype.minimaliza = function () {
this.applicationRef.components[0].instance.minimalize();
};
MinimalizeComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: '[leaf-layout-minimalize]',
template: "\n <a class=\"navbar-minimalize minimalize-styl-2 btn btn-primary\" (click)=\"minimaliza()\"><i class=\"fa fa-bars\"></i> </a>\n "
},] },
];
/** @nocollapse */
MinimalizeComponent.ctorParameters = function () { return [
{ type: _angular_core.ApplicationRef, },
]; };
return MinimalizeComponent;
}());
var JsonFileService = (function () {
function JsonFileService(http) {
this.http = http;
}
/**
* Load the data defined in the json file
*/
JsonFileService.prototype.getData = function () {
return this.http.get(this.getFilePath()).map(this.extractData);
};
/**
* Extract data that arrives from the response
* @param res the response
*/
JsonFileService.prototype.extractData = function (res) {
var body = res.json() || {};
return body.data || body;
};
return JsonFileService;
}());
var __extends$1 = (undefined && undefined.__extends) || (function () {
var 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 function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var MenuService = (function (_super) {
__extends$1(MenuService, _super);
function MenuService(http) {
var _this = _super.call(this, http) || this;
_this.http = http;
return _this;
}
MenuService.prototype.getFilePath = function () {
return 'assets/data/menu.json';
};
MenuService.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
MenuService.ctorParameters = function () { return [
{ type: _angular_http.Http, },
]; };
return MenuService;
}(JsonFileService));
var NavComponent = (function () {
function NavComponent(menuService) {
this.menuService = menuService;
}
NavComponent.prototype.ngOnInit = function () {
var _this = this;
if (!this.items || this.items.length === 0) {
this.menuService.getData().subscribe(function (data) {
_this.items = data;
});
}
};
NavComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: '[leaf-layout-navbar]',
template: "\n <li *ngFor=\"let menu of items\" [routerLinkActive]=\"['active']\" [routerLinkActiveOptions]=\"{exact:true}\">\n <a routerLink=\"{{menu.action}}\">\n <i class=\"fa {{menu.icon}}\"></i>\n <span class=\"nav-label ng-binding\">{{menu.title}}</span>\n <span class=\"fa arrow\" *ngIf=\"menu.items\"></span>\n </a>\n </li>\n "
},] },
];
/** @nocollapse */
NavComponent.ctorParameters = function () { return [
{ type: MenuService, },
]; };
NavComponent.propDecorators = {
'items': [{ type: _angular_core.Input },],
};
return NavComponent;
}());
var FooterComponent = (function () {
function FooterComponent(loggerService) {
this.loggerService = loggerService;
this.year = new Date().getFullYear();
}
FooterComponent.prototype.ngOnInit = function () {
this.loggerService.log('... initializing footer component from core module.');
};
FooterComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: '[leaf-layout-footer]',
template: "\n <div class=\"pull-right\">\n Welcome to the jungle!\n </div>\n <div>\n <strong>Copyright</strong> Demo full application © {{year}}\n </div>\n "
},] },
];
/** @nocollapse */
FooterComponent.ctorParameters = function () { return [
{ type: LoggerService, decorators: [{ type: _angular_core.Inject, args: ['LoggerService',] },] },
]; };
return FooterComponent;
}());
var HeaderComponent = (function () {
function HeaderComponent(authHelper, loggerService) {
this.authHelper = authHelper;
this.loggerService = loggerService;
}
HeaderComponent.prototype.ngOnInit = function () {
this.loggerService.log('... initializing header component from core module.');
};
HeaderComponent.prototype.isActive = function () {
return this.authHelper.isUserLogged();
};
HeaderComponent.prototype.getUser = function () {
return this.authHelper.getUserLogged();
};
HeaderComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: '[leaf-layout-header]',
template: "\n <div class=\"navbar-header\">\n <span><a leaf-layout-minimalize></a></span>\n <ng-content select=\"[header-left]\"></ng-content>\n <span leaf-spinner></span>\n </div>\n <ng-content select=\"[header-right]\"></ng-content>\n "
},] },
];
/** @nocollapse */
HeaderComponent.ctorParameters = function () { return [
{ type: AuthHelper, },
{ type: LoggerService, decorators: [{ type: _angular_core.Inject, args: ['LoggerService',] },] },
]; };
return HeaderComponent;
}());
(function (MessageType) {
MessageType["BLOCKING"] = "BLOCKING";
MessageType["CONFIRM"] = "CONFIRM";
})(exports.MessageType || (exports.MessageType = {}));
(function (MessageStatus) {
MessageStatus["SUCCESS"] = "SUCCESS";
MessageStatus["INFO"] = "INFO";
MessageStatus["WARNING"] = "WARNING";
MessageStatus["DANGER"] = "DANGER";
})(exports.MessageStatus || (exports.MessageStatus = {}));
var ModalMessageComponent = (function () {
function ModalMessageComponent() {
this.onOk = new _angular_core.EventEmitter();
this.onClose = new _angular_core.EventEmitter();
}
ModalMessageComponent.prototype.ngOnInit = function () { };
/**
* Mehtod that returns the modal icon to display depending of the modal status
*/
ModalMessageComponent.prototype.getIcon = function () {
switch (this.status) {
case exports.MessageStatus.DANGER:
return 'fa-times';
case exports.MessageStatus.INFO:
return 'fa-info-circle';
case exports.MessageStatus.SUCCESS:
return 'fa-check ';
case exports.MessageStatus.WARNING:
return 'fa-exclamation-triangle';
default:
return 'fa-times';
}
};
/**
* Mehtod that returns the modal title depending of the model status
*/
ModalMessageComponent.prototype.getTitle = function () {
switch (this.status) {
case exports.MessageStatus.DANGER:
return 'Error';
case exports.MessageStatus.INFO:
return 'Info';
case exports.MessageStatus.SUCCESS:
return 'Success ';
case exports.MessageStatus.WARNING:
return 'Warning';
default:
return 'Error';
}
};
/**
* Mehtod that returns the Ok title button translated
*/
ModalMessageComponent.prototype.getOkTitle = function () {
// TO be translated
return 'OK';
};
/**
* Method that returns the cancel title button translated
*/
ModalMessageComponent.prototype.getCancelTitle = function () {
// TO be translated
if (this.type === exports.MessageType.BLOCKING) {
return 'Close';
}
else {
return 'Cancel';
}
};
/**
* Event that show the modal dialog
*/
ModalMessageComponent.prototype.show = function () {
this.modal.show();
};
/**
* Event that hide the modal dialog
*/
ModalMessageComponent.prototype.hide = function () {
if (this.modal && this.modal.isShown) {
if (this.type === exports.MessageType.CONFIRM) {
this.onOk.emit(false);
}
this.modal.hide();
this.onClose.emit(null);
}
};
/**
* Event fired when click on ok button of confirm message
*/
ModalMessageComponent.prototype.onOKEvent = function () {
this.onOk.emit(true);
this.modal.hide();
this.onClose.emit(null);
};
/**
* Event fired when click on cancel or close button
*/
ModalMessageComponent.prototype.onCancelEvent = function () {
this.hide();
};
ModalMessageComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: 'app-modal-message',
template: "\n <div class=\"modal fade\" bsModal #modalMsg=\"bs-modal\" [config]=\"{backdrop: 'static'}\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"mySmallModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-sm\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <h4 class=\"modal-title pull-left\"><i class=\"fa {{getIcon()}}\" aria-hidden=\"true\"></i> {{getTitle()}}</h4>\n <button type=\"button\" class=\"close pull-right\" aria-label=\"Close\" (click)=\"modalMsg.hide()\">\n <span aria-hidden=\"true\">×</span>\n </button>\n </div>\n <div class=\"modal-body\">{{message}}</div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-primary\" (click)=\"onOKEvent()\" *ngIf=\"type == 'CONFIRM'\">{{getOkTitle()}}</button>\n <button type=\"button\" class=\"btn btn-primary\" (click)=\"onCancelEvent()\">{{getCancelTitle()}}</button>\n </div>\n </div>\n </div>\n </div>\n ",
styles: ["\n\n .fa-times {\n color: red;\n }\n .fa-info-circle {\n color: blue;\n }\n .fa-exclamation-triangle {\n color: orange;\n }\n\n .fa-exclamation-triangle {\n color: orange;\n }\n\n .fa-check {\n color: green;\n }\n "]
},] },
];
/** @nocollapse */
ModalMessageComponent.ctorParameters = function () { return []; };
ModalMessageComponent.propDecorators = {
'message': [{ type: _angular_core.Input },],
'status': [{ type: _angular_core.Input },],
'type': [{ type: _angular_core.Input },],
'onOk': [{ type: _angular_core.Output },],
'onClose': [{ type: _angular_core.Output },],
'modal': [{ type: _angular_core.ViewChild, args: ['modalMsg',] },],
};
return ModalMessageComponent;
}());
var MessageService = (function () {
function MessageService() {
this.subjectMsg = new rxjs_Subject.Subject();
this.subjectConfirmed = new rxjs_Subject.Subject();
}
MessageService.prototype.showMessage = function (message) {
this.subjectMsg.next(message);
};
MessageService.prototype.confirmMessage = function (value) {
this.subjectConfirmed.next(value);
};
MessageService.prototype.getMessage = function () {
return this.subjectMsg.asObservable();
};
MessageService.prototype.getConfirmed = function () {
return this.subjectConfirmed.asObservable();
};
MessageService.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
MessageService.ctorParameters = function () { return []; };
return MessageService;
}());
// import the required animation functions from the angular animations module
var fadeInAnimation = _angular_animations.trigger('fadeInAnimation', [
_angular_animations.transition(':enter', [
_angular_animations.style({ opacity: 0 }),
_angular_animations.animate('0.3s', _angular_animations.style({ opacity: 1 }))
]),
]);
var SpinnerComponent = (function () {
function SpinnerComponent(loggerService, spinnerService) {
this.loggerService = loggerService;
this.spinnerService = spinnerService;
this.visible = false;
}
SpinnerComponent.prototype.ngOnInit = function () {
var _this = this;
this.loggerService.log('... initializing spinner component from core module.');
this.spinnerStateChanged = this.spinnerService.spinnerState
.subscribe(function (state) {
_this.visible = state.show;
});
};
SpinnerComponent.prototype.ngOnDestroy = function () {
this.spinnerStateChanged.unsubscribe();
};
SpinnerComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: '[leaf-spinner]',
template: "\n <a class=\"btn btn-primary minimalize-styl-item\" *ngIf=\"visible\" [@fadeInAnimation]><i class=\"fa fa-circle-o-notch fa-spin\"></i></a>\n ",
animations: [fadeInAnimation]
},] },
];
/** @nocollapse */
SpinnerComponent.ctorParameters = function () { return [
{ type: LoggerService, decorators: [{ type: _angular_core.Inject, args: ['LoggerService',] },] },
{ type: SpinnerService, },
]; };
return SpinnerComponent;
}());
var __extends$2 = (undefined && undefined.__extends) || (function () {
var 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 function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var LanguageService = (function (_super) {
__extends$2(LanguageService, _super);
function LanguageService(http) {
var _this = _super.call(this, http) || this;
_this.http = http;
return _this;
}
LanguageService.prototype.getFilePath = function () {
return 'assets/data/languages.json';
};
LanguageService.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
LanguageService.ctorParameters = function () { return [
{ type: _angular_http.Http, },
]; };
return LanguageService;
}(JsonFileService));
var LanguageSelectorComponent = (function () {
function LanguageSelectorComponent(languageService, translate) {
this.languageService = languageService;
this.translate = translate;
this.languageSelected = localStorage['language'] || 'en';
}
LanguageSelectorComponent.prototype.ngOnInit = function () {
var _this = this;
if (!this.languages || this.languages.length === 0) {
this.languageService.getData().subscribe(function (data) {
_this.languages = data;
});
}
};
LanguageSelectorComponent.prototype.onLanguageChange = function (language) {
console.log('... language changed to: ' + language);
this.translate.use(language);
if (localStorage) {
localStorage['language'] = language;
}
this.languageSelected = language;
};
LanguageSelectorComponent.decorators = [
{ type: _angular_core.Component, args: [{
selector: 'leaf-language-selector',
template: "\n <select class=\"form-control\" id=\"languages\" [(ngModel)]=\"languageSelected\" (change)=\"onLanguageChange($event.target.value)\">\n <option *ngFor=\"let lang of languages\" [value]=\"lang.id\">{{lang.title}}</option>\n </select>\n "
},] },
];
/** @nocollapse */
LanguageSelectorComponent.ctorParameters = function () { return [
{ type: LanguageService, },
{ type: _ngxTranslate_core.TranslateService, },
]; };
LanguageSelectorComponent.propDecorators = {
'languages': [{ type: _angular_core.Input },],
};
return LanguageSelectorComponent;
}());
var AuthGuard = (function () {
function AuthGuard(router, authHelper) {
this.router = router;
this.authHelper = authHelper;
}
AuthGuard.prototype.canActivate = function (route, state) {
console.log('... check if can active menu');
if (this.authHelper.isUserLogged()) {
// logged in so return true
console.log('... the user is logged so you can activate the menu');
return true;
}
// not logged in so redirect to login page with the return url
console.log('... the user is NOT logged so you will be redirected to the login page');
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
};
AuthGuard.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
AuthGuard.ctorParameters = function () { return [
{ type: _angular_router.Router, },
{ type: AuthHelper, },
]; };
return AuthGuard;
}());
var LoginGuard = (function () {
function LoginGuard(router, authHelper) {
this.router = router;
this.authHelper = authHelper;
}
LoginGuard.prototype.canActivate = function (next, state) {
// go to default page if the user is already logged in
if (this.authHelper.isUserLogged()) {
this.router.navigate(['/'], { queryParams: { returnUrl: state.url } });
}
return true;
};
LoginGuard.decorators = [
{ type: _angular_core.Injectable },
];
/** @nocollapse */
LoginGuard.ctorParameters = function () { return [
{ type: _angular_router.Router, },
{ type: AuthHelper, },
]; };
return LoginGuard;
}());
function throwIfAlreadyLoaded(parentModule, moduleName) {
if (parentModule) {
throw new Error(moduleName + " has already been loaded. Import Core modules in the AppModule only.");
}
}
// translate
// layout
var LeafFrameworkCore = (function () {
function LeafFrameworkCore(parentModule) {
throwIfAlreadyLoaded(parentModule, 'LeafFrameworkCore');
}
LeafFrameworkCore.decorators = [
{ type: _angular_core.NgModule, args: [{
imports: [LeafFrameworkShared,
_ngxTranslate_core.TranslateModule.forRoot({
loader: {
provide: _ngxTranslate_core.TranslateLoader,
useFactory: (createTranslateLoader),
deps: [_angular_http.Http]
}
})
],
declarations: [
HeaderComponent,
FooterComponent,
NavComponent,
MinimalizeComponent,
SpinnerComponent,
LanguageSelectorComponent,
ModalMessageComponent
],
exports: [
LeafFrameworkShared,
HeaderComponent,
FooterComponent,
NavComponent,
MinimalizeComponent,
SpinnerComponent,
LanguageSelectorComponent,
ModalMessageComponent
],
providers: [
SpinnerService,
MenuService,
LanguageService,
AuthGuard,
LoginGuard,
AuthHelper,
MessageService
]
},] },
];
/** @nocollapse */
LeafFrameworkCore.ctorParameters = function () { return [
{ type: LeafFrameworkCore, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.SkipSelf },] },
]; };
return LeafFrameworkCore;
}());
var BaseAppComponent = (function () {
function BaseAppComponent() {
this.cssClass = 'fixed-sidebar fixed-nav md-skin pace-done';
}
BaseAppComponent.prototype.minimalize = function () {
var minimalizeClass = " mini-navbar";
var position = this.cssClass.indexOf(minimalizeClass);
if (position < 0) {
this.cssClass = this.cssClass + minimalizeClass;
}
else {
this.cssClass = this.cssClass.substring(0, position) + this.cssClass.substring(position + minimalizeClass.length);
}
};
BaseAppComponent.propDecorators = {
'cssClass': [{ type: _angular_core.HostBinding, args: ['class',] },],
};
return BaseAppComponent;
}());
var Menu = (function () {
function Menu(title, action, icon) {
this.title = title;
this.action = action;
this.icon = icon;
}
return Menu;
}());
var Message = (function () {
function Message(text, status, type) {
if (status === void 0) { status = exports.MessageStatus.DANGER; }
if (type === void 0) { type = exports.MessageType.BLOCKING; }
this.text = text;
this.status = status;
this.type = type;
status = status.toUpperCase();
if (status !== exports.MessageStatus.INFO &&
status !== exports.MessageStatus.SUCCESS &&
status !== exports.MessageStatus.WARNING &&
status !== exports.MessageStatus.DANGER) {
throw new Error('Invalid message status. Should be Info, Success, Warning or Danger.');
}
type = type.toUpperCase();
if (type !== exports.MessageType.BLOCKING &&
type !== exports.MessageType.CONFIRM) {
throw new Error('Invalid message type. Should be Blocking or Confirm.');
}
this.text = text;
this.status = status;
this.type = type;
}
return Message;
}());
var SimpleErrorHandler = (function () {
function SimpleErrorHandler() {
}
SimpleErrorHandler.prototype.unwrap = function (err) {
var res = err.rejection ? err.rejection : err;
res = res.originalError ? res.originalError : res.originalStack ? res.originalStack : res;
return res;
};
SimpleErrorHandler.proto