@koalarx/ui
Version:
Koala UI is a Design System developed in Angular whose objective is to facilitate and make your development faster and simpler, making this framework your greatest ally.
881 lines (870 loc) • 82.7 kB
JavaScript
import * as i0 from '@angular/core';
import { Component, ChangeDetectionStrategy, Input, EventEmitter, Output, Injectable, ViewChild, NgModule } from '@angular/core';
import * as i1 from '@angular/common';
import { CommonModule, HashLocationStrategy } from '@angular/common';
import * as i2 from '@angular/material/progress-bar';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import * as i2$1 from '@angular/router';
import { NavigationError, NavigationEnd, NavigationCancel, NavigationStart, RouterModule } from '@angular/router';
import * as i3 from '@angular/material/tooltip';
import { MatTooltipModule } from '@angular/material/tooltip';
import * as i4 from '@angular/material/button';
import { MatButtonModule } from '@angular/material/button';
import * as i5 from '@angular/material/icon';
import { MatIconModule } from '@angular/material/icon';
import * as i6 from '@angular/material/list';
import { MatListModule } from '@angular/material/list';
import * as i7 from '@angular/material/core';
import { BehaviorSubject, interval, Observable, skipWhile } from 'rxjs';
import jwt from 'jwt-decode';
import * as i4$1 from '@koalarx/ui/menu';
import { menuStateSubject } from '@koalarx/ui/menu';
import jwtEncode from 'jwt-encode';
import { koala } from '@koalarx/utils';
import { delay } from '@koalarx/utils/operators/delay';
import { randomString } from '@koalarx/utils/operators/string';
import * as i1$1 from '@angular/common/http';
import { HttpErrorResponse, HttpParams, HttpClientModule } from '@angular/common/http';
import * as i6$1 from 'ngx-device-detector';
import * as i8 from '@angular/material/badge';
import { MatBadgeModule } from '@angular/material/badge';
import * as i9 from '@angular/material/progress-spinner';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import * as i10 from '@angular/material/toolbar';
import { MatToolbarModule } from '@angular/material/toolbar';
import * as i13 from '@angular/material/sidenav';
import { MatSidenavModule } from '@angular/material/sidenav';
import * as i14 from '@angular/material/menu';
import { MatMenuModule } from '@angular/material/menu';
import * as i1$2 from '@koalarx/ui/alert';
import { KoalaAlertEnum, KoalaRequestCodeToAlertEnumTranslate } from '@koalarx/ui/alert';
import { map, first } from 'rxjs/operators';
import { EventSourcePolyfill } from 'event-source-polyfill';
class LoaderBarPageComponent {
constructor() {
this.show = false;
this.progress = 0;
this.typeLoader = 'indeterminate';
}
}
LoaderBarPageComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: LoaderBarPageComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
LoaderBarPageComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "14.3.0", type: LoaderBarPageComponent, selector: "app-loader-page", inputs: { show: "show", progress: "progress", typeLoader: "typeLoader" }, ngImport: i0, template: "<div [ngClass]=\"{'bouncedInDown d-block': show}\" class=\"animated loader-bar-page\">\n <mat-progress-bar\n [bufferValue]=\"progress\"\n [mode]=\"typeLoader\"\n [value]=\"progress\"\n color=\"primary\">\n </mat-progress-bar>\n</div>\n", styles: [".loader-bar-page{position:absolute;display:none;top:0;left:0;width:100vw;height:100vh;z-index:100000}\n"], dependencies: [{ kind: "directive", type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { kind: "component", type: i2.MatProgressBar, selector: "mat-progress-bar", inputs: ["color", "value", "bufferValue", "mode"], outputs: ["animationEnd"], exportAs: ["matProgressBar"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: LoaderBarPageComponent, decorators: [{
type: Component,
args: [{ selector: 'app-loader-page', changeDetection: ChangeDetectionStrategy.OnPush, template: "<div [ngClass]=\"{'bouncedInDown d-block': show}\" class=\"animated loader-bar-page\">\n <mat-progress-bar\n [bufferValue]=\"progress\"\n [mode]=\"typeLoader\"\n [value]=\"progress\"\n color=\"primary\">\n </mat-progress-bar>\n</div>\n", styles: [".loader-bar-page{position:absolute;display:none;top:0;left:0;width:100vw;height:100vh;z-index:100000}\n"] }]
}], propDecorators: { show: [{
type: Input
}], progress: [{
type: Input
}], typeLoader: [{
type: Input
}] } });
class NotificationComponent {
constructor() {
this.deleteAll = new EventEmitter(false);
this.delete = new EventEmitter(null);
}
ngOnChanges(changes) {
this.appName = document.title.indexOf(') ') >= 0 ? document.title.split(') ')[1] : document.title;
if (changes.notifications && this.notifications.length > 0) {
document.title = `(${this.notifications.length}) ${this.appName}`;
}
else {
document.title = this.appName;
}
}
deleteAllNotifications() {
this.deleteAll.emit(true);
}
deleteNotification(notification) {
this.delete.emit(notification);
}
}
NotificationComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: NotificationComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
NotificationComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "14.3.0", type: NotificationComponent, selector: "koala-notification-list", inputs: { notifications: "notifications" }, outputs: { deleteAll: "deleteAll", delete: "delete" }, usesOnChanges: true, ngImport: i0, template: "<div (click)=\"$event.stopPropagation()\" class=\"notifications-content\">\n <div class=\"title\">\n <mat-icon>info</mat-icon>\n <h2>Notifica\u00E7\u00F5es</h2>\n <span class=\"spacer\"></span>\n <button (click)=\"deleteAllNotifications()\" *ngIf=\"notifications.length > 0\" class=\"btn-delete-all\"\n mat-icon-button\n matTooltip=\"Excluir Todas\" matTooltipPosition=\"above\">\n <mat-icon>delete_sweep</mat-icon>\n </button>\n </div>\n <mat-action-list *ngIf=\"notifications.length > 0 else noNotifications\">\n <mat-list-item *ngFor=\"let notification of notifications\" [routerLink]=\"notification.redirectTo\" class=\"itemList\">\n <button (click)=\"deleteNotification(notification)\" class=\"delete-notification\" color=\"warn\" mat-icon-button\n matTooltip=\"Excluir\" matTooltipPosition=\"above\"\n mat-list-icon>\n <mat-icon>delete</mat-icon>\n </button>\n <mat-icon class=\"iconList\" mat-list-icon>announcement</mat-icon>\n <h4 class=\"titleList\" mat-line>{{notification.title}}</h4>\n <p [innerHTML]=\"notification.text\" class=\"textList\" mat-line></p>\n </mat-list-item>\n </mat-action-list>\n <ng-template #noNotifications>\n <div class=\"empty\">\n <mat-icon>mood</mat-icon>\n <p>Tudo certo por aqui!</p>\n </div>\n </ng-template>\n</div>\n", styles: [".title{color:#616161;padding:5px 20px 15px}.title h2{vertical-align:middle;display:inline-flex;padding:0 10px;margin:0;font-family:OpenSans,sans-serif;font-size:.8em}.title mat-icon{vertical-align:middle;display:inline-flex;width:22px;height:22px;font-size:22px;line-height:22px}.title .btn-delete-all{position:absolute;right:20px;top:5px}.iconList{color:#1976d2}.titleList{font-family:OpenSansLight,sans-serif;font-size:.7em!important;color:#616161}.textList{font-family:OpenSans,sans-serif;font-size:.9em!important;color:#212121;white-space:inherit!important}.itemList{height:-moz-fit-content!important;height:fit-content!important;padding:8px 0!important}.delete-notification{background:#b71c1c;border-radius:0!important;height:100%!important;margin-left:-75px;margin-right:10px;position:absolute;transition:.3s;width:50px!important}.delete-notification mat-icon{color:#fff;vertical-align:middle}mat-action-list{max-height:70vh;overflow-y:auto}mat-list-item:hover .delete-notification{margin-left:-15px}.empty{padding:50px;text-align:center;color:#616161}.empty mat-icon{width:40px;height:40px;font-size:40px;line-height:40px}.empty p{text-align:center;font-family:OpenSansLight,sans-serif;font-size:1em}\n"], dependencies: [{ kind: "directive", type: i1.NgForOf, selector: "[ngFor][ngForOf]", inputs: ["ngForOf", "ngForTrackBy", "ngForTemplate"] }, { kind: "directive", type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "directive", type: i2$1.RouterLink, selector: ":not(a):not(area)[routerLink]", inputs: ["queryParams", "fragment", "queryParamsHandling", "state", "relativeTo", "preserveFragment", "skipLocationChange", "replaceUrl", "routerLink"] }, { kind: "directive", type: i3.MatTooltip, selector: "[matTooltip]", exportAs: ["matTooltip"] }, { kind: "component", type: i4.MatButton, selector: "button[mat-button], button[mat-raised-button], button[mat-icon-button], button[mat-fab], button[mat-mini-fab], button[mat-stroked-button], button[mat-flat-button]", inputs: ["disabled", "disableRipple", "color"], exportAs: ["matButton"] }, { kind: "component", type: i5.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "component", type: i6.MatList, selector: "mat-list, mat-action-list", inputs: ["disableRipple", "disabled"], exportAs: ["matList"] }, { kind: "component", type: i6.MatListItem, selector: "mat-list-item, a[mat-list-item], button[mat-list-item]", inputs: ["disableRipple", "disabled"], exportAs: ["matListItem"] }, { kind: "directive", type: i7.MatLine, selector: "[mat-line], [matLine]" }, { kind: "directive", type: i6.MatListIconCssMatStyler, selector: "[mat-list-icon], [matListIcon]" }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: NotificationComponent, decorators: [{
type: Component,
args: [{ selector: 'koala-notification-list', changeDetection: ChangeDetectionStrategy.OnPush, template: "<div (click)=\"$event.stopPropagation()\" class=\"notifications-content\">\n <div class=\"title\">\n <mat-icon>info</mat-icon>\n <h2>Notifica\u00E7\u00F5es</h2>\n <span class=\"spacer\"></span>\n <button (click)=\"deleteAllNotifications()\" *ngIf=\"notifications.length > 0\" class=\"btn-delete-all\"\n mat-icon-button\n matTooltip=\"Excluir Todas\" matTooltipPosition=\"above\">\n <mat-icon>delete_sweep</mat-icon>\n </button>\n </div>\n <mat-action-list *ngIf=\"notifications.length > 0 else noNotifications\">\n <mat-list-item *ngFor=\"let notification of notifications\" [routerLink]=\"notification.redirectTo\" class=\"itemList\">\n <button (click)=\"deleteNotification(notification)\" class=\"delete-notification\" color=\"warn\" mat-icon-button\n matTooltip=\"Excluir\" matTooltipPosition=\"above\"\n mat-list-icon>\n <mat-icon>delete</mat-icon>\n </button>\n <mat-icon class=\"iconList\" mat-list-icon>announcement</mat-icon>\n <h4 class=\"titleList\" mat-line>{{notification.title}}</h4>\n <p [innerHTML]=\"notification.text\" class=\"textList\" mat-line></p>\n </mat-list-item>\n </mat-action-list>\n <ng-template #noNotifications>\n <div class=\"empty\">\n <mat-icon>mood</mat-icon>\n <p>Tudo certo por aqui!</p>\n </div>\n </ng-template>\n</div>\n", styles: [".title{color:#616161;padding:5px 20px 15px}.title h2{vertical-align:middle;display:inline-flex;padding:0 10px;margin:0;font-family:OpenSans,sans-serif;font-size:.8em}.title mat-icon{vertical-align:middle;display:inline-flex;width:22px;height:22px;font-size:22px;line-height:22px}.title .btn-delete-all{position:absolute;right:20px;top:5px}.iconList{color:#1976d2}.titleList{font-family:OpenSansLight,sans-serif;font-size:.7em!important;color:#616161}.textList{font-family:OpenSans,sans-serif;font-size:.9em!important;color:#212121;white-space:inherit!important}.itemList{height:-moz-fit-content!important;height:fit-content!important;padding:8px 0!important}.delete-notification{background:#b71c1c;border-radius:0!important;height:100%!important;margin-left:-75px;margin-right:10px;position:absolute;transition:.3s;width:50px!important}.delete-notification mat-icon{color:#fff;vertical-align:middle}mat-action-list{max-height:70vh;overflow-y:auto}mat-list-item:hover .delete-notification{margin-left:-15px}.empty{padding:50px;text-align:center;color:#616161}.empty mat-icon{width:40px;height:40px;font-size:40px;line-height:40px}.empty p{text-align:center;font-family:OpenSansLight,sans-serif;font-size:1em}\n"] }]
}], ctorParameters: function () { return []; }, propDecorators: { notifications: [{
type: Input
}], deleteAll: [{
type: Output
}], delete: [{
type: Output
}] } });
// @dynamic
class KoalaLanguageHelper {
static setLanguage(language) {
this.language = language;
}
static getLanguage() {
return this.language;
}
static getBtnLabel() {
switch (this.language) {
case "enUs":
return 'Send';
default:
return 'Enviar';
}
}
static getYesMessage() {
switch (this.language) {
case "enUs":
return 'Yes';
default:
return 'Sim';
}
}
static getNoMessage() {
switch (this.language) {
case "enUs":
return 'No';
default:
return 'Não';
}
}
static getInternalServerErrorMessage() {
switch (this.language) {
case "enUs":
return 'We had a problem with your request.<br/>Sorry for the inconvenience.<br/><br/>Please try again later.';
default:
return 'Tivemos um problema com sua requisição.<br/>Sinto muito pelo transtorno.<br/><br/>Gentileza tentar novamente mais tarde.';
}
}
static getRequiredMessage(label) {
switch (this.language) {
case "enUs":
return `${label} is required.`;
default:
return `Nenhum valor informado.`;
}
}
static getInvalidMessage(label) {
switch (this.language) {
case "enUs":
return `${label} is invalid.`;
default:
return `Registro inválido.`;
}
}
static getMinMessage(min) {
switch (this.language) {
case "enUs":
return `Inform at least the value of ${min}.`;
default:
return `Informe no mínimo o valor de ${min}.`;
}
}
static getMaxMessage(max) {
switch (this.language) {
case "enUs":
return `Inform at most the value of ${max}.`;
default:
return `Informe no máximo o valor de ${max}.`;
}
}
static getMinLengthMessage(minLength) {
switch (this.language) {
case "enUs":
return `Enter a value with at least ${minLength} characters.`;
default:
return `Informe um valor com no mínimo ${minLength} caracteres.`;
}
}
static getMaxLengthMessage(maxLength) {
switch (this.language) {
case "enUs":
return `Enter a value with at most ${maxLength} characters.`;
default:
return `Informe um valor com no máximo ${maxLength} caracteres.`;
}
}
static getDateMinMessage() {
switch (this.language) {
case "enUs":
return `Inform at least the date of `;
default:
return `Informe no mínimo a data de `;
}
}
static getDateMaxMessage() {
switch (this.language) {
case "enUs":
return `Inform at most the date of `;
default:
return `Informe no máximo a data de `;
}
}
static getAutocompleteMessage(label) {
switch (this.language) {
case "enUs":
return `You must select a option.`;
default:
return `Você deve selecionar uma opção.`;
}
}
}
// @dynamic
class KoalaEnvironment {
}
// @dynamic
class TokenFactory {
static init() {
if (!!localStorage.getItem(KoalaEnvironment.environment?.storageTokenName)) {
TokenFactory.setToken(localStorage.getItem(KoalaEnvironment.environment?.storageTokenName));
}
}
static setToken(token) {
localStorage.setItem(KoalaEnvironment.environment?.storageTokenName, token);
this.token = token;
}
static getToken() {
return this.token;
}
static removeToken() {
localStorage.removeItem(KoalaEnvironment.environment?.storageTokenName);
this.token = null;
}
static hasToken() {
return !!this.token && !!localStorage.getItem(KoalaEnvironment.environment?.storageTokenName);
}
static logout() {
this.removeToken();
}
}
class MatFormFieldHelper {
// Devido a mudanças constantes de estado dos campos de formulário, em certos casos o componente do Material Angular não se comporta conforme o esperado, devido a isso, este Helper tem essa função
static fixDisabledStateForDisabledFields() {
document.querySelectorAll(".mat-form-field input:disabled").forEach(inputEl => {
let matFormFieldElement;
let tmpElement;
do {
tmpElement = tmpElement ? tmpElement.parentElement : inputEl.parentElement;
if (tmpElement.classList.contains('mat-form-field')) {
matFormFieldElement = tmpElement;
}
} while (!matFormFieldElement);
matFormFieldElement?.classList.add('mat-form-field-disabled');
});
}
}
class KoalaTokenService {
constructor() {
this.token$ = new BehaviorSubject(null);
this.verifySession();
}
ngOnDestroy() {
this.intervalToken?.unsubscribe();
this.intervalFixMatFormField?.unsubscribe();
}
setToken(token) {
if (TokenFactory.hasToken()) {
this.token$.next(token);
}
TokenFactory.setToken(token);
this.intervalFixMatFormField = interval(1000).subscribe(() => MatFormFieldHelper.fixDisabledStateForDisabledFields());
}
getToken() {
return this.token$;
}
getDecodedToken() {
return (TokenFactory.hasToken() ? jwt(TokenFactory.getToken()) : null);
}
getOAuth2Token() {
return (TokenFactory.hasToken() ? jwt(TokenFactory.getToken()) : null);
}
removeToken() {
TokenFactory.removeToken();
this.intervalFixMatFormField?.unsubscribe();
}
verifySession() {
TokenFactory.init();
this.token$.next(TokenFactory.getToken());
this.intervalToken = interval(300).subscribe(() => {
if (!TokenFactory.hasToken() && this.token$.getValue()) {
this.token$.next(null);
}
else if (TokenFactory.hasToken() && !this.token$.getValue()) {
this.token$.next(TokenFactory.getToken());
}
});
}
}
KoalaTokenService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaTokenService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
KoalaTokenService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaTokenService, providedIn: "any" });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaTokenService, decorators: [{
type: Injectable,
args: [{ providedIn: "any" }]
}], ctorParameters: function () { return []; } });
// @dynamic
class KoalaOauthConfig {
static getConfig() {
return localStorage.getItem(KoalaEnvironment.environment?.storageOAuthTypeName);
}
static hasConfig() {
return !!this.getConfig();
}
static setConfig(type) {
localStorage.setItem(KoalaEnvironment.environment?.storageOAuthTypeName, type);
this.config.next(this.getOAuthConfig(type));
}
static getOAuthConfig(type) {
const environment = KoalaEnvironment.environment?.oauthConfig?.find(config => config.name === type) ?? null;
return environment ?? {
customQueryParams: {
client_secret: null
},
clientId: null,
scope: null,
domain: null,
strictDiscoveryDocumentValidation: false,
indexLoginName: 'name'
};
}
}
KoalaOauthConfig.config = new BehaviorSubject(KoalaOauthConfig.getOAuthConfig(KoalaOauthConfig.getConfig()));
const KOALA_LOADER_SUBJECT = new BehaviorSubject({
typeLoader: 'indeterminate',
progress: 0,
show: false
});
class KoalaLoaderService {
getLoaderSubject() {
return KOALA_LOADER_SUBJECT;
}
create(loaderConfig) {
KOALA_LOADER_SUBJECT.next({
show: true,
progress: loaderConfig.progress ? loaderConfig.progress : 0,
typeLoader: loaderConfig.typeLoader ? loaderConfig.typeLoader : 'indeterminate'
});
}
dismiss() {
KOALA_LOADER_SUBJECT.next({
show: false,
progress: 0,
typeLoader: 'indeterminate'
});
}
}
KoalaLoaderService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaLoaderService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
KoalaLoaderService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaLoaderService, providedIn: "any" });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaLoaderService, decorators: [{
type: Injectable,
args: [{ providedIn: "any" }]
}] });
const STATE_STORAGE_NAME = 'koala_openid_state';
class KoalaOAuth2Service {
constructor(http, router, tokenService) {
this.http = http;
this.router = router;
this.tokenService = tokenService;
this.events = new BehaviorSubject(null);
this.token = {};
this.generateState();
}
ngOnDestroy() {
this.eventSubscription?.unsubscribe();
this.refreshTokenInterval?.unsubscribe();
}
hasOpenIdConfig() {
return !!this.openIdOptions;
}
configure(options) {
this.config = options;
}
loadDiscoveryDocumentAndTryLogin() {
if (this.eventSubscription) {
this.eventSubscription.unsubscribe();
}
this.eventSubscription = this.events.subscribe(event => {
if (event === 'authenticate') {
this.generateState();
localStorage.setItem(STATE_STORAGE_NAME, this.state);
window.location.href = `${this.openIdOptions.authorization_endpoint}?response_type=${this.config.responseType}&client_id=${this.config.clientId}&state=${this.state}&redirect_uri=${this.config.redirectUri}&scope=${this.config.scope}`;
}
else if (event === 'getToken') {
const urlParams = new URLSearchParams(window.location.search);
const state = urlParams.get('state');
if (state === this.state) {
const code = urlParams.get('code');
this.getToken(code);
}
else {
this.logout();
}
}
else if (event === 'getClaims' || (event === 'refreshToken' && !this.claims)) {
this.getClaims();
}
});
return new Promise((resolve, reject) => {
this.http.get(`${this.config.issuer}/.well-known/openid-configuration`).subscribe(options => {
this.openIdOptions = options;
if (window.location.href.indexOf(`state=${this.state}`) >= 0) {
this.events.next('getToken');
}
else if (!this.tokenService.getOAuth2Token()) {
this.events.next('loadedConfig');
}
resolve(true);
}, e => {
console.error(e);
this.events.next('errorLoadConfig');
reject(e);
});
});
}
async initLoginFlow(name) {
if (name) {
KoalaOauthConfig.setConfig(name);
await delay(1000);
}
this.events.next('authenticate');
}
getIdentityClaims() {
return this.claims;
}
getAccessToken() {
return this.token.access_token;
}
getIdToken() {
return this.token.id_token;
}
getRefreshToken() {
return this.token.refresh_token;
}
getAccessTokenExpiration() {
const expires_in = new Date();
expires_in.setSeconds(this.token.expires_in);
return expires_in.toString();
}
getCode() {
return this.code;
}
logout() {
const logoutInterval = setInterval(() => {
if (this.hasOpenIdConfig()) {
if (this.openIdOptions.end_session_endpoint) {
this.claims = null;
this.token = null;
const iframeLogout = document.createElement('iframe');
iframeLogout.style.display = 'none';
iframeLogout.src = this.openIdOptions.end_session_endpoint;
document.querySelector('body').appendChild(iframeLogout);
}
this.events.next('logout');
clearInterval(logoutInterval);
}
}, 300);
}
initRefreshTokenInterval(code, refreshToken) {
this.refreshTokenInterval?.unsubscribe();
this.refreshTokenInterval = interval(1000).subscribe(() => {
const refreshTokenDate = new Date();
refreshTokenDate.setMinutes(refreshTokenDate.getMinutes() + 1);
const token = this.tokenService.getOAuth2Token();
if (token) {
const expires_in = token.expired;
if (expires_in) {
if (new Date(expires_in) <= refreshTokenDate) {
this.getToken(code, refreshToken);
}
}
}
});
}
getToken(code, refreshToken) {
if (refreshToken) {
this.refreshTokenInterval?.unsubscribe();
}
const formData = new URLSearchParams();
let data = koala({
grant_type: (refreshToken ? 'refresh_token' : 'authorization_code'),
code,
redirect_uri: this.config.redirectUri,
client_id: this.config.clientId
}).object().merge(this.config.customQueryParams ?? {}).getValue();
if (refreshToken) {
data = koala(data).object().merge({ refresh_token: refreshToken }).getValue();
}
if (!this.code) {
this.code = code;
}
Object.keys(data).forEach(indexName => {
formData.append(indexName, data[indexName]);
});
this.http.post(this.config.endpointToken ?? this.openIdOptions.token_endpoint, formData.toString(), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).subscribe((token) => {
this.token = token;
this.events.next((refreshToken ? 'refreshToken' : 'getClaims'));
}, () => this.events.next('getTokenError'));
}
getClaims() {
this.http.get((this.config.endpointClaims ?? this.openIdOptions.userinfo_endpoint), {
headers: {
Authorization: `Bearer ${this.getAccessToken()}`
}
}).subscribe(userInfo => {
this.claims = userInfo;
this.state = null;
localStorage.removeItem(STATE_STORAGE_NAME);
this.events.next(this.events.getValue() === 'refreshToken' ? 'refreshToken' : 'userAuthenticated');
}, () => this.events.next('loadedConfig'));
}
generateState() {
this.state = localStorage.getItem(STATE_STORAGE_NAME) ?
localStorage.getItem(STATE_STORAGE_NAME) :
randomString(30, {
numbers: true,
uppercase: true,
lowercase: true
});
}
}
KoalaOAuth2Service.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaOAuth2Service, deps: [{ token: i1$1.HttpClient }, { token: i2$1.Router }, { token: KoalaTokenService }], target: i0.ɵɵFactoryTarget.Injectable });
KoalaOAuth2Service.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaOAuth2Service });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: KoalaOAuth2Service, decorators: [{
type: Injectable
}], ctorParameters: function () { return [{ type: i1$1.HttpClient }, { type: i2$1.Router }, { type: KoalaTokenService }]; } });
class PageComponent {
constructor(tokenService, router, loaderService, menuService, oauth2Service, deviceService) {
this.tokenService = tokenService;
this.router = router;
this.loaderService = loaderService;
this.menuService = menuService;
this.oauth2Service = oauth2Service;
this.deviceService = deviceService;
this.showMenu = true;
this.startMenuOpened = true;
this.userMenuOptions = [];
this.language = 'ptBr';
this.validatingScope = new EventEmitter(false);
this.logoutEmitter = new EventEmitter(false);
this.deleteAllNotifications = new EventEmitter(false);
this.deleteNotification = new EventEmitter(null);
this.username$ = new BehaviorSubject('');
this.firstUserLetter$ = new BehaviorSubject('');
this.logged$ = new BehaviorSubject(false);
this.validationScope$ = new BehaviorSubject(false);
this.isMobile = this.deviceService.isMobile();
this.defaultPalletColors = {
scrollbarColor: '#1976D2',
scrollbarColorHover: '#1565C0',
userPresentationBackground: '#f1f1f1',
userPresentationUserBackground: '#1976D2',
userPresentationUserFontColor: '#fff',
firstColor: '#fff',
secondColor: '#F1F1F1',
bodyBackground: '#eeeeee',
checkboxBackground: '#1976d2',
checkboxColor: '#ffffff',
fontColor: '#1976D2',
fontHoverColor: '#1976D2',
fontActiveColor: '#1565C0',
menuTitleBackground: 'rgba(0,0,0,.1)',
menuTitleColor: 'rgba(0,0,0,.3)',
menuBackground: '#fafafa',
menuOptionsBackground: '#eaeaea',
menuOptionsColor: '#a5a5a5',
menuOptionsColorHover: '#1976D2',
menuOptionsColorActive: '#1565c0',
toolbarBackground: '#ffffff',
toolbarColor: '#1976d2',
listBackground: '#fff',
listContentBackground: '#fff',
listTitleItemColor: '#838383',
listItemColor: '#3e3e3e',
listItemBackgroudHover: '#F1F1F1',
listItemBackgroundActive: '#EEE',
shadowColorTableList: 'rgba(25, 118, 210, .4)'
};
this.loaderSubject = loaderService.getLoaderSubject();
}
ngOnInit() {
KoalaLanguageHelper.setLanguage(this.language);
this.initOAuth2();
if (this.openPages) {
if (this.openPages.indexOf('/') < 0) {
this.openPages.push('/');
}
if (this.openPages.indexOf('/login') < 0) {
this.openPages.push('/login');
}
}
else {
this.openPages = [
'/',
'/login'
];
}
this.tokenService.getToken()?.subscribe(token => {
this.logged$.next(!!token);
if (this.logged$.getValue()) {
const decodedToken = this.tokenService.getDecodedToken();
this.username$.next(decodedToken.login);
this.firstUserLetter$.next(decodedToken.login.charAt(0).toUpperCase());
if (!this.isMobile) {
this.menuService.open();
}
}
if (this.logged$.getValue() && this.openPages?.indexOf(this.currentUrl) >= 0 && this.defaultPage) {
this.router.navigate([this.defaultPage]).then();
}
else if (!this.logged$.getValue() && this.currentUrl && this.openPages?.indexOf(this.currentUrl) < 0) {
this.router.navigate(['login']).then();
return false;
}
});
this.router.events.subscribe(event => {
switch (true) {
case event instanceof NavigationStart: {
this.loaderService.create({ typeLoader: 'indeterminate' });
break;
}
case event instanceof NavigationEnd:
case event instanceof NavigationCancel:
case event instanceof NavigationError: {
this.loaderService.dismiss();
if (event instanceof NavigationEnd) {
if (this.isMobile) {
this.menuService.close();
}
this.currentUrl = event.url.split('?')[0];
if (event.url.indexOf('/login?clientId=') < 0) {
if (this.logged$.getValue() && this.defaultPage && this.openPages?.indexOf(this.currentUrl) >= 0) {
this.router.navigate([this.defaultPage]).then();
return false;
}
else if (!this.logged$.getValue() && this.openPages?.indexOf(this.currentUrl) < 0) {
this.router.navigate(['login']).then();
return false;
}
}
}
break;
}
default: {
break;
}
}
});
if (this.palletColors) {
Object.keys(this.defaultPalletColors).forEach(indexName => {
if (!this.palletColors.hasOwnProperty(indexName) ||
!this.palletColors[indexName]) {
this.palletColors[indexName] = this.defaultPalletColors[indexName];
}
});
}
else {
this.palletColors = this.defaultPalletColors;
}
this.defineColor();
if (this.showMenu) {
menuStateSubject.subscribe(async (state) => {
if (this.menu) {
if (state === 'close') {
if (this.menu.opened) {
await this.menu.close();
}
}
else if (state === 'open') {
if (!this.menu.opened) {
await this.menu.open();
}
}
}
});
if (this.startMenuOpened && this.logged$.getValue()) {
if (!this.isMobile) {
this.menuService.open();
}
}
else {
this.menuService.close();
}
}
else {
this.menuService.close();
}
this.validationScope$.subscribe(scope => this.validatingScope.emit(scope));
}
async toogleMenu() {
this.menuService.clearConfig();
if (this.menu) {
await this.menu.toggle();
}
}
async logout() {
if (KoalaEnvironment.environment?.oauthConfig) {
this.oauth2Service.logout();
}
this.menuService.close();
this.tokenService.removeToken();
this.tokenService.getToken().next(null);
this.logoutEmitter.emit(true);
}
defineColor() {
const css = `
*::-webkit-scrollbar-thumb {background: ${this.palletColors.scrollbarColor};width: 2px;}
*::-webkit-scrollbar-thumb:hover {background: ${this.palletColors.scrollbarColorHover};}
input:-webkit-autofill, input:-webkit-autofill:focus, input:-webkit-autofill:hover {color: ${this.palletColors.fontColor}!important;}
.menu-container,
body {background: ${this.palletColors.bodyBackground}!important;}
input:-webkit-autofill, input:-webkit-autofill:focus, input:-webkit-autofill:hover {-webkit-box-shadow: 0 0 0 1000px ${this.palletColors.firstColor} inset !important;}
.mat-button-disabled,
input::placeholder,
.mat-form-field-appearance-outline .mat-form-field-outline {color: ${this.palletColors.fontColor}!important;opacity: .6;}
.mat-hint,
.mat-expansion-indicator::after,
.more-items-content .items .titleForm,
fieldset legend,
.mat-paginator-container,
.mat-form-field-flex mat-icon {color: ${this.palletColors.fontColor}!important;}
.mat-paginator-container,
.mat-card,
.mat-expansion-panel,
.mat-select-panel,
.mat-autocomplete-panel,
.mat-menu-panel {background: ${this.palletColors.firstColor}}
.mat-selected {background-color: rgba(0,0,0,.3)!important;}
.question p,
.alert-message,
.mat-action-row,
.mat-option,
.mat-menu-item,
.mat-menu-item mat-icon {color: ${this.palletColors.fontColor}!important}
.mat-select-value,
.mat-select-arrow,
.mat-form-field input,
.mat-form-field textarea,
.mat-form-field-appearance-outline:not(.mat-form-field-invalid) .mat-form-field-outline-thick,
.mat-form-field label,
.select-multiple-native select {color: ${this.palletColors.fontColor}!important;caret-color: ${this.palletColors.fontColor}!important;}
.mat-form-field-underline,
.mat-form-field-appearance-fill .mat-form-field-underline::before,
.mat-form-field-ripple {background: ${this.palletColors.fontColor}!important;}
.mat-checkbox-checked.mat-accent .mat-checkbox-background, .mat-checkbox-indeterminate.mat-accent .mat-checkbox-background,
.mat-checkbox:not(.mat-checkbox-disabled).mat-accent .mat-checkbox-ripple .mat-ripple-element {background-color: ${this.palletColors.checkboxBackground} !important;}
.mat-checkbox-checkmark-path {stroke: ${this.palletColors.checkboxColor} !important;}
.mat-checkbox-checkmark {fill: ${this.palletColors.checkboxColor} !important;}
.mat-checkbox-mixedmark {background-color: ${this.palletColors.checkboxColor} !important;}
.mat-checkbox-frame {border-color: ${this.palletColors.checkboxOutlineColor}!important;}
.mat-checkbox-label {color: ${this.palletColors.fontColor}!important;}
.mat-radio-outer-circle {border-color: ${this.palletColors.checkboxBackground}!important;}
.mat-radio-ripple .mat-ripple-element, .mat-radio-inner-circle {background-color: ${this.palletColors.checkboxBackground} !important;}
.home-list-cards .list .mat-list-item-content .mat-icon {color: ${this.palletColors.fontColor};}
.home-list-cards .list button .mat-badge-content {background: ${this.palletColors.fontColor};}
.koala-dialog .mat-dialog-title h2 {color: ${this.palletColors.fontColor};}
.koala-dialog .mat-dialog-title mat-icon {color: ${this.palletColors.fontColor}!important;}
.koala-dialog .mat-dialog-container {background: ${this.palletColors.firstColor}}
.list-filter mat-icon {color: ${this.palletColors.filterIconColor}!important;}
koala-page .menu-options {background: ${this.palletColors.menuBackground};}
koala-page .toolbar {background: ${this.palletColors.toolbarBackground};}
koala-page .toolbar .btn-collapse-menu,
koala-page .btn-toolbar span{color: ${this.palletColors.toolbarColor};}
koala-page .btn-toolbar span.icon-user,
.user-presentation span.icon-user {background: ${this.palletColors.userPresentationUserBackground};color: ${this.palletColors.userPresentationUserFontColor};}
.user-presentation {background: ${this.palletColors.userPresentationBackground};}
.user-presentation span.username {color: ${this.palletColors.toolbarColor};}
.mat-drawer.mat-drawer-push {background-color: ${this.palletColors.bodyBackground};}
koala-menu .title {background: ${this.palletColors.menuTitleBackground};color: ${this.palletColors.menuTitleColor};}
koala-menu ul li,
koala-menu ul li a {color: ${this.palletColors.menuOptionsColor};}
koala-menu ul li:hover,
koala-menu ul li:hover a {color: ${this.palletColors.menuOptionsColorHover} !important;}
koala-menu ul li.active,
koala-menu ul li.expanded {color: ${this.palletColors.menuOptionsColorActive} !important;border-left: 4px solid ${this.palletColors.menuOptionsColorActive} !important;background: ${this.palletColors.menuOptionsBackground} !important;}
koala-menu ul li.active a,
koala-menu ul li.expanded a {color: ${this.palletColors.menuOptionsColorActive} !important;background: ${this.palletColors.menuOptionsBackground} !important;}
koala-menu ul li li:hover,
koala-menu ul li li:hover a {color: ${this.palletColors.menuOptionsColorHover} !important;}
koala-menu ul li li.active,
koala-menu ul li li.active a {color: ${this.palletColors.menuOptionsColorActive} !important;}
koala-menu ul li koala-icon svg *,
koala-menu ul li a koala-icon svg * {fill: ${this.palletColors.menuOptionsColor};}
koala-menu ul li:hover koala-icon svg *,
koala-menu ul li:hover a koala-icon svg * {fill: ${this.palletColors.menuOptionsColorHover} !important;}
koala-menu ul li.active koala-icon *,
koala-menu ul li.expanded koala-icon * {fill: ${this.palletColors.menuOptionsColorActive} !important;}
koala-menu ul li li:hover koala-icon *,
koala-menu ul li li:hover a koala-icon * {fill: ${this.palletColors.menuOptionsColorHover} !important;}
koala-menu ul li li.active koala-icon *,
koala-menu ul li li.active a koala-icon * {fill: ${this.palletColors.menuOptionsColorActive}!important;}
.notifications-content .title {color: ${this.palletColors.notificationTitleColor}!important;}
.notifications-content .empty,
.notifications-content .titleList {color: ${this.palletColors.notificationContentTitleColor}!important;}
.notifications-content .iconList {color: ${this.palletColors.notificationContentIconColor}!important;}
.notifications-content .textList {color: ${this.palletColors.notificationTitleColor}!important;}
.list-container {box-shadow: 0 1px 3px ${this.palletColors.shadowColorTableList};}
.list-container .list table.table-hover tr:hover {background: ${this.palletColors.listItemBackgroudHover};}
.list-container .list table.table-hover tr:active {background: ${this.palletColors.listItemBackgroundActive};}
.list-container .list-filter .advanced {background: ${this.palletColors.firstColor};}
.list-container nav.menu-list {background: ${this.palletColors.firstColor};color: rgba(25, 118, 210, .3);}
.content {background: ${this.palletColors.listContentBackground};}
.mat-tab-group .mat-tab-label {color: ${this.palletColors.fontColor};}
.mat-tab-group .mat-ink-bar {background-color: ${this.palletColors.fontColor}!important;}
.mat-table {background: ${this.palletColors.listBackground};color: ${this.palletColors.fontColor};}
.mat-table th {color: ${this.palletColors.listTitleItemColor}!important;}
.mat-sort-header-arrow {color: ${this.palletColors.listItemColor}!important;}
.mat-table td {color: ${this.palletColors.listItemColor}!important;}`;
const head = document.head || document.getElementsByTagName('head')[0];
const style = document.createElement('style');
head.appendChild(style);
style.appendChild(document.createTextNode(css));
}
initOAuth2() {
KoalaOauthConfig.config.subscribe(config => this.startConfig(config));
if (KoalaOauthConfig.hasConfig()) {
KoalaOauthConfig.setConfig(KoalaOauthConfig.getConfig());
}
}
startConfig(config) {
if (config.clientId) {
this.oauth2Service.configure({
redirectUri: window.location.origin,
redirectUriAfterAuth: this.defaultPage,
responseType: 'code',
clientId: config.clientId,
scope: config.scope,
issuer: config.domain,
customQueryParams: config.customQueryParams,
endpointToken: config.endpointToken ?? null,
endpointClaims: config.endpointClaims ?? null
});
this.oauth2Service.loadDiscoveryDocumentAndTryLogin().then();
if (this.oauthEventsSubscription) {
this.oauthEventsSubscription.unsubscribe();
}
this.oauthEventsSubscription = this.oauth2Service.events.subscribe(event => {
if (event === 'userAuthenticated' || event === 'refreshToken') {
const claims = this.oauth2Service.getIdentityClaims();
if (claims && (!TokenFactory.hasToken() ||
(TokenFactory.hasToken() && event === 'refreshToken'))) {
this.tokenService.setToken(jwtEncode({
accessToken: this.oauth2Service.getAccessToken(),
idToken: this.oauth2Service.getIdToken(),
refreshToken: this.oauth2Service.getRefreshToken(),
login: claims[config.indexLoginName] ?? 'Undefined',
expired: this.oauth2Service.getAccessTokenExpiration(),
code: this.oauth2Service.getCode()
}, 'secret'));
}
if (event === 'userAuthenticated') {
setTimeout(() => this.validationScope$.next(false), 300);
}
}
else if (event === 'getToken') {
this.validationScope$.next(true);
}
});
}
}
}
PageComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.3.0", ngImport: i0, type: PageComponent, deps: [{ token: KoalaTokenService }, { token: i2$1.Router }, { token: KoalaLoaderService }, { token: i4$1.KoalaMenuService }, { token: KoalaOAuth2Service }, { token: i6$1.DeviceDetectorService }], target: i0.ɵɵFactoryTarget.Component });
PageComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "14.3.0", type: PageComponent, selector: "koala-page", inputs: { showMenu: "showMenu", color: "color", logo: "logo", startMenuOpened: "startMenuOpened", showLoaderPage: "showLoaderPage", messageLoaderPage: "messageLoaderPage", defaultPage: "defaultPage", openPages: "openPages", notifications: "notifications", userMenuOptions: "userMenuOptions", palletColors: "palletColors", language: "language" }, outputs: { validatingScope: "validatingScope", logoutEmitter: "logoutEmitter", deleteAllNotifications: "deleteAllNotifications", deleteNotification: "deleteNotification" }, providers: [KoalaTokenService], viewQueries: [{ propertyName: "menu", first: true, predicate: ["drawer"], descendants: true, static: true }], ngImport: i0, template: "<div *ngIf=\"showLoaderPage | async\" class=\"koala-loader-pg\">\n <div class=\"loader-content\">\n <figure>\n <img [src]=\"logo\" alt=\"Logotipo\"/>\n <figcaption *ngIf=\"(messageLoaderPage | async) as messageLoader\" [innerHTML]=\"messageLoader\"></figcaption>\n </figure>\n <mat-spinner></mat-spinner>\n </div>\n</div>\n<app-loader-page *ngIf=\"(loaderSubject | async) as loader\" [progress]=\"loader.progress\" [show]=\"loader.show\"\n [typeLoader]=\"loader.typeLoader\"></app-loader-page>\n<mat-drawer-container autosize class=\"menu-container\">\n <mat-drawer #drawer class=\"menu-options\" [mode]=\"isMobile ? 'push' : 'side'\">\n <img [src]=\"logo\" alt=\"Logotipo\" id=\"logotipo\"/>\n <ng-content *ngIf=\"showMenu\" select=\"[menu-options]\"></ng-content>\n </mat-drawer>\n\n <mat-toolbar *ngIf=\"!!(logged$ | async) && (username$ | async)\" class=\"toolbar\">\n <img *ngIf=\"!showMenu\" [src]=\"logo\" alt=\"Logotipo Toolbar\" id=\"logotipo-toolbar\"/>\n <button (click)=\"toogleMenu()\" *ngIf=\"showMenu\" [color]=\"color\" class=\"btn-collapse-menu\" mat-icon-button>\n <mat-icon>menu</mat-icon>\n </button>\n <span class=\"spacer\"></span>\n\t <div class=\"menu-toolbar\">\n\t\t <ng-content select=\"[menu-toolbar]\"></ng-content>\n\t </div>\n <div *ngIf=\"(notifications | async) as notificationList\">\n <button *ngIf=\"notifications\" [color]=\"color\" [matMenuTriggerFor]=\"notificationsMenu\" class=\"btn-toolbar\"\n mat-icon-button>\n <mat-icon\n\t [matBadgeHidden]=\"notificationList.length === 0\"\n\t [matBadge]=\"notificationList.length.toString()\"\n\t