UNPKG

cocori-ng

Version:

Cocori-ng is an Angular full of great components & utilites based on Material

1,189 lines (1,172 loc) 65.6 kB
import * as i1 from '@angular/common/http'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import * as i0 from '@angular/core'; import { Injectable, Inject } from '@angular/core'; import { map, filter, finalize } from 'rxjs/operators'; import { Subject, BehaviorSubject, of } from 'rxjs'; import * as i1$1 from '@angular/router'; import { Router } from '@angular/router'; var SkipHeaders; (function (SkipHeaders) { SkipHeaders["TRUE"] = "true"; SkipHeaders["FALSE"] = "false"; })(SkipHeaders || (SkipHeaders = {})); class HttpService { constructor(http, httpBackend) { this.http = http; this.httpBackend = httpBackend; this.withCredentialsOption = false; this.skip = SkipHeaders.FALSE; this.httpWithoutInterceptor = new HttpClient(httpBackend); } set withCredentials(value) { this.withCredentialsOption = value; } get withCredentials() { return this.withCredentialsOption; } /** TODO: à tester car pas sûr que cela fonctionne... */ delete(path, params, skip = SkipHeaders.FALSE) { let options = { params: this.buildUrlParams(params), withCredentials: this.withCredentialsOption }; if (skip === SkipHeaders.FALSE) { options['headers'] = { skip: skip }; return this.http.delete(`${path}`, options) .pipe(map(this.extractData.bind(this))); } else { return this.httpWithoutInterceptor.delete(`${path}`, options) .pipe(map(this.extractData.bind(this))); } } get(path, params, skip = SkipHeaders.FALSE) { let options = { params: this.buildUrlParams(params), withCredentials: this.withCredentialsOption }; if (skip === SkipHeaders.FALSE) { options['headers'] = { skip: skip }; return this.http.get(`${path}`, options) .pipe(map(this.extractData.bind(this))); } else { return this.httpWithoutInterceptor.get(`${path}`, options) .pipe(map(this.extractData.bind(this))); } } post(path, body = {}, skip = SkipHeaders.FALSE) { let options = { withCredentials: this.withCredentialsOption }; if (skip === SkipHeaders.FALSE) { options['headers'] = new HttpHeaders().set('skip', skip); return this.http.post(`${path}`, JSON.stringify(body), options).pipe(map(this.extractData.bind(this))); } else { options['headers'] = new HttpHeaders() .set('Content-Type', 'application/json; charset=utf-8'); return this.httpWithoutInterceptor.post(`${path}`, JSON.stringify(body), options).pipe(map(this.extractData.bind(this))); } } put(path, body = {}, skip = SkipHeaders.FALSE) { let options = { withCredentials: this.withCredentialsOption }; if (skip === SkipHeaders.FALSE) { options['headers'] = { skip: skip }; return this.http.put(`${path}`, JSON.stringify(body), options).pipe(map(this.extractData.bind(this))); } else { return this.httpWithoutInterceptor.put(`${path}`, JSON.stringify(body)) .pipe(map(this.extractData.bind(this))); } } patch(path, body = {}, skip = SkipHeaders.FALSE) { let options = { withCredentials: this.withCredentialsOption }; if (skip === SkipHeaders.FALSE) { options['headers'] = new HttpHeaders().set('skip', skip); return this.http.patch(`${path}`, JSON.stringify(body), options).pipe(map(this.extractData.bind(this))); } else { options['headers'] = new HttpHeaders() .set('Content-Type', 'application/json; charset=utf-8'); return this.httpWithoutInterceptor.patch(`${path}`, JSON.stringify(body), options).pipe(map(this.extractData.bind(this))); } } file(path, params) { return this.http.get(`${path}`, { params: this.buildUrlParams(params), withCredentials: this.withCredentialsOption, responseType: 'blob' }) .pipe(map(this.extractData.bind(this))); } upload(path, body = {}, options = { withCredentials: this.withCredentialsOption }) { options['headers'] = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8'); options['reportProgress'] = true; options['observe'] = "events"; return this.http.post(`${path}`, JSON.stringify(body), options); } extractData(res) { if (!res) return res; const body = res.body; if (res.status === 204) return res.body; if (body) { return typeof res.body === 'string' ? JSON.parse(res.body) : res.body; } return res; } buildUrlParams(parameters) { let params = new HttpParams(); for (const property in parameters) { if (parameters.hasOwnProperty(property)) { params = params.append(property, parameters[property]); } } return params; } } HttpService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: HttpService, deps: [{ token: i1.HttpClient }, { token: i1.HttpBackend }], target: i0.ɵɵFactoryTarget.Injectable }); HttpService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: HttpService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: HttpService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: function () { return [{ type: i1.HttpClient }, { type: i1.HttpBackend }]; } }); class StorageService { constructor() { } setSessionStorageItem(key, item) { sessionStorage.setItem(key, JSON.stringify(item)); } getSessionStorageItem(key) { let a = null; try { a = JSON.parse(sessionStorage.getItem(key)); } catch (e) { console.error(`Session storage, erreur in parsing JSON : `, e); } finally { return a; } } deleteSessionStorageItem(key) { sessionStorage.removeItem(key); } setLocalStorageItem(key, item) { localStorage.setItem(key, JSON.stringify(item)); } getLocalStorageItem(key) { let a = null; try { a = JSON.parse(localStorage.getItem(key)); } catch (e) { console.error(`Local storage, erreur in parsing JSON : `, e); } finally { return a; } } deleteLocalStorageItem(key) { localStorage.removeItem(key); } } StorageService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: StorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); StorageService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: StorageService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: StorageService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }], ctorParameters: function () { return []; } }); class TokenService { constructor(storageService) { this.storageService = storageService; } get accessToken() { const token = this.storageService.getLocalStorageItem('accessToken'); return token || null; } set accessToken(token) { this.storageService.setLocalStorageItem('accessToken', token); } get refreshToken() { const token = this.storageService.getLocalStorageItem('refreshToken'); return token || null; } set refreshToken(token) { this.storageService.setLocalStorageItem('refreshToken', token); } deleteTokens() { this.storageService.deleteLocalStorageItem('refreshToken'); this.storageService.deleteLocalStorageItem('accessToken'); } decryptAccessToken() { if (this.accessToken) { const base64Array = this.accessToken.split('.'); const decodedToken = JSON.parse(window.atob(base64Array[1])); return decodedToken; } return null; } } TokenService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: TokenService, deps: [{ token: StorageService }], target: i0.ɵɵFactoryTarget.Injectable }); TokenService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: TokenService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: TokenService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }], ctorParameters: function () { return [{ type: StorageService }]; } }); class BroadcastEventService { constructor() { this._broadcastedEvents = []; this._eventBus = new Subject(); } broadcast(event) { this._eventBus.next(event); } listen(keys) { const eventKey = keys.join("-"); if (!this.isEventKnown(eventKey)) { const newEvent = this._eventBus.asObservable() .pipe(filter(event => (event.eventKeys.join("-")) === eventKey), map(event => event.eventData)); this._broadcastedEvents.push({ eventKey: eventKey, event: newEvent }); return newEvent; } else { return this.returnEvent(eventKey); } } isEventKnown(eventKey) { const index = this._broadcastedEvents.findIndex(entrée => entrée.eventKey === eventKey); return index >= 0; } returnEvent(eventKey) { const event = this._broadcastedEvents.find(event => event.eventKey === eventKey); return event.event; } } BroadcastEventService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: BroadcastEventService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); BroadcastEventService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: BroadcastEventService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: BroadcastEventService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: function () { return []; } }); const LIMIT_MAX_RELOAD = 2; const TIME_MAX_RELOAD = 30; // secondes class GlobalErrorInterceptorService { // public globalErrorsHandlerSubject: Subject<boolean> = new Subject<boolean>(); constructor(injector, storageService) { this.injector = injector; this.storageService = storageService; } handleError(error) { const chunkFailedMessage = /Loading chunk [\d]+ failed/; const router = this.injector.get(Router); if (error.stack) { console.error("details errors 😱 :"); console.error(error.stack.toString()); } else { console.error("error undefined 😡"); } if (chunkFailedMessage.test(error.message)) { // this.globalErrorsHandlerSubject.next(true) this.handleReloadPage(error.message.toString()); } } handleReloadPage(message) { console.log('%cPage reloaded : errors chunk versions', 'color: blue;'); const reloadPage = this.storageService.getSessionStorageItem('reloadPage'); if (!reloadPage) { this.storageService.setSessionStorageItem('reloadPage', { date: new Date(), count: 1 }); } else if (reloadPage.count < LIMIT_MAX_RELOAD && (new Date().getTime() - new Date(reloadPage.date).getTime()) / 1000 < TIME_MAX_RELOAD) { this.storageService.setSessionStorageItem('reloadPage', { date: reloadPage.date, count: reloadPage.count + 1 }); } else { message = `Veuillez communiquer cette erreur à l'administrateur du site : \n\n ${message}`; alert(message); this.storageService.deleteSessionStorageItem('reloadPage'); return; } window.location.reload(); } } GlobalErrorInterceptorService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: GlobalErrorInterceptorService, deps: [{ token: i0.Injector }, { token: StorageService }], target: i0.ɵɵFactoryTarget.Injectable }); GlobalErrorInterceptorService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: GlobalErrorInterceptorService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: GlobalErrorInterceptorService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }], ctorParameters: function () { return [{ type: i0.Injector }, { type: StorageService }]; } }); class LoadingService { constructor() { this.subject = new BehaviorSubject(false); } startLoading() { this.subject.next(true); } stopLoading() { this.subject.next(false); } } LoadingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: LoadingService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); LoadingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: LoadingService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: LoadingService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: function () { return []; } }); class LoadingInterceptorService { constructor(loadingScreenService) { this.loadingScreenService = loadingScreenService; this.activeRequests = 0; } intercept(request, next) { if (this.activeRequests === 0) { this.loadingScreenService.startLoading(); } this.activeRequests++; clearTimeout(this.timer); this.timer = setTimeout(() => { this.forceFinalize(); }, 5000); return next.handle(request).pipe(finalize(() => { this.activeRequests--; if (this.activeRequests === 0) { this.loadingScreenService.stopLoading(); clearTimeout(this.timer); } })); } forceFinalize() { this.activeRequests = 0; this.loadingScreenService.stopLoading(); } } LoadingInterceptorService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: LoadingInterceptorService, deps: [{ token: LoadingService }], target: i0.ɵɵFactoryTarget.Injectable }); LoadingInterceptorService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: LoadingInterceptorService, providedIn: "root" }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: LoadingInterceptorService, decorators: [{ type: Injectable, args: [{ providedIn: "root", }] }], ctorParameters: function () { return [{ type: LoadingService }]; } }); class RequestInterceptorService { constructor(tokenService, httpService) { this.tokenService = tokenService; this.httpService = httpService; } intercept(request, next) { request = this.addAccessTokenRequest(request); return next.handle(request); } addAccessTokenRequest(request, token) { const accessToken = token || this.tokenService.accessToken; if (request.headers.get("skip") === SkipHeaders.TRUE) { return request = request.clone({ headers: request.headers.delete('skip') }); } if (!accessToken) { return request; } return request.clone({ headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}` }) }); } } RequestInterceptorService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: RequestInterceptorService, deps: [{ token: TokenService }, { token: HttpService }], target: i0.ɵɵFactoryTarget.Injectable }); RequestInterceptorService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: RequestInterceptorService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: RequestInterceptorService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }], ctorParameters: function () { return [{ type: TokenService }, { type: HttpService }]; } }); class SortService { sortObjectByKeys(objectData) { return Object.keys(objectData).sort().reduce((obj, key) => { obj[key] = objectData[key]; return obj; }, {}); } } SortService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: SortService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); SortService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: SortService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: SortService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); class ScrollService { constructor() { this.onScroll = new Subject(); } currentScrollPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) { return document.documentElement.scrollTop; } // Internet Explorer 6, 7 and 8 if (document.body.scrollTop) return document.body.scrollTop; return 0; } getElementDomPosition(elm) { let y = elm.offsetTop - 100; let node = elm; while (node.offsetParent && node.offsetParent !== document.body) { node = node.offsetParent; y += node.offsetTop; } return y; } scrollToTop() { const that = this; let timeOut; if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) { window.scrollBy(0, -50); timeOut = setTimeout(function () { that.scrollToTop(); }, 10); } else { clearTimeout(timeOut); } } scrollToIdSmooth(eID) { const startY = this.currentScrollPosition(); const elm = document.getElementById(eID); const stopY = this.getElementDomPosition(elm); const distance = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { scrollTo(0, stopY); return; } let speed = Math.round(distance / 100); if (speed >= 20) { speed = 20; } const step = Math.round(distance / 25); let leapY = stopY > startY ? startY + step : startY - step; let timer = 0; if (stopY > startY) { for (let i = startY; i < stopY; i += step) { setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed); leapY += step; if (leapY > stopY) leapY = stopY; timer++; } return; } for (let i = startY; i > stopY; i -= step) { setTimeout("window.scrollTo(0, " + leapY + ")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY; timer++; } return false; } getScrollDistanceTo(eID) { const elm = document.getElementById(eID); if (!elm) return -1; // element not found const stopY = this.getElementDomPosition(elm); return stopY; } } ScrollService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: ScrollService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); ScrollService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: ScrollService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: ScrollService, decorators: [{ type: Injectable, args: [{ providedIn: 'root' }] }], ctorParameters: function () { return []; } }); class InjectComponentService { constructor() { this.componentsRefs = []; } /** * Exemple d'utilisation: * this.injectComponentService.loadAndAddComponentToContainer(MyClasseComponent, #DomReference, { @InputName_1: Value, @InputName_2: Value }, { @OutputName_1: (valueEmited: any) => this.callback(valueEmited)}) * Ou si le composant n'a pas de @Output * this.injectComponentService.loadAndAddComponentToContainer(MyClasseComponent, #DomReference, { @InputName_1: Value, @InputName_2: Value }, null) */ loadAndAddComponentToContainer(componentClass, viewContainerRef, inputs, outputs, index) { // const factory = this.componentFactoryResolver.resolveComponentFactory(componentClass); const componentRef = viewContainerRef.createComponent(componentClass, { index: index ? index : null }); /** inputs */ for (const [key, value] of Object.entries(inputs)) { (componentRef.instance)[key] = value; } /** outputs */ if (outputs) { for (const [key, value] of Object.entries(outputs)) { if (key && value && (componentRef.instance)[key]) (componentRef.instance)[key].subscribe(data => value(data)); } } componentRef.changeDetectorRef.detectChanges(); this.componentsRefs.push(componentRef); } removeComponentFromViewContainer(index, viewContainerRef) { viewContainerRef.remove(index); this.componentsRefs.splice(index, 1); } moveComponentFromViewContainer(currentIndex, previousIndex, viewContainerRef) { viewContainerRef.move(viewContainerRef.get(previousIndex), currentIndex); this.componentsRefs.splice(previousIndex, 0, this.componentsRefs.splice(currentIndex, 1)[0]); } } InjectComponentService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: InjectComponentService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); InjectComponentService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: InjectComponentService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: InjectComponentService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); class HelperService { generateGuid() { return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + this.s4() + this.s4(); } s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } removeValueFromArrayByIndex(arrayValues, index) { if (index === -1) return arrayValues; return [...arrayValues.slice(0, index), ...arrayValues.slice(index + 1)]; } /** arrondir un nombre */ roundUp(num, precision) { precision = Math.pow(10, precision); return Math.ceil(num * precision) / precision; } /** */ static retourneNomDeDomaine() { return location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : ''); } static enleverNomDomaineUrl(url) { if (!url) return null; if (!/^http[s]?:\/\//.test(url)) return url; const urlSansHttp = url.split(/^http[s]?:\/\//); const indexSlash = urlSansHttp[1].indexOf("/"); const urlValide = urlSansHttp[1].substring(indexSlash); return urlValide; } static retourneSegmentsURL() { const pathName = window.location.pathname; // on supprime du pathname le dernier caractères s'il s'agit d'un / return pathName.replace(/\/$/, '').split('/'); } static ouvrirUrlExterne(lien, estceNouvelOnglet = false) { if (!this.retourneNullSiNonDéfini(lien)) return; let url = ''; if (!/^http[s]?:\/\//.test(lien)) { url += 'http://'; } url += lien; if (estceNouvelOnglet) { window.open(url); } else { window.location.href = url; } } static nettoyerParametresUrl(ancienneUrl) { let index = 0; let nouvelleUrl = ancienneUrl; index = ancienneUrl.indexOf('?'); if (index === -1) { index = ancienneUrl.indexOf('#'); } if (index !== -1) { nouvelleUrl = ancienneUrl.substring(0, index); } return nouvelleUrl; } static construireUrl(url) { return this.retourneNomDeDomaine() + '/' + url; } static segmentsURL(url) { if (!url) return []; // on supprime de l'url le 1er / et le de dernier / return url.replace(/\/*/, '').replace(/\/$/, '').split('/'); } static estceUrlValide(string) { const res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g); if (!res) { return false; } else { return true; } } static encoderParamètresUrl(data) { const ret = []; for (const key in data) { if (data.hasOwnProperty(key)) { const element = data[key]; ret.push(encodeURIComponent(key) + '=' + encodeURIComponent(element)); } } return ret.join('&'); } static concaténerParamètresUrl(url, paramètres) { return url + '?' + paramètres; } static ajouterParamètreUrl(url, param, value) { const a = document.createElement('a'), regex = /(?:\?|&amp;|&)+([^=]+)(?:=([^&]*))*/g; let match = null; const str = []; a.href = url; param = encodeURIComponent(param); while (match = regex.exec(a.search)) { if (param !== match[1]) str.push(match[1] + (match[2] ? "=" + match[2] : "")); } str.push(param + (value ? "=" + encodeURIComponent(value) : "")); a.search = str.join("&"); return a.href; } /** * Retourne l'url courante sans les paramètres */ static donneUrlCouranteSansParamètre() { return window.location.href.split(/[?#]/)[0]; } /** * JavaScript Get URL Parameter * @param String prop The specific URL parameter you want to retreive the value for * @return String|Object If prop is provided a string value is returned, otherwise an object of all properties is returned */ static donneParamètresUrl(prop, urlStatique) { const params = {}; const urlCourante = urlStatique ? urlStatique : window.location.href; const search = decodeURIComponent(urlCourante.slice(urlCourante.indexOf('?') + 1)); if (search === urlCourante) return null; const definitions = search.split('&'); definitions.forEach(function (val, key) { const parts = val.split('=', 2); params[parts[0]] = parts[1]; }); if ((prop && !(prop in params))) { return null; } return (prop && prop in params) ? params[prop] : params; } static retourneParamètresAccolades(url) { if (!this.retourneNullSiNonDéfini(url)) { return []; } const résultat = url.match(/\{(.*?)\}/g); // entre {} return !résultat ? [] : résultat; } /** efface les paramètres entre accolades d'une chaîne */ static effacerParamètresAccolades(chaine) { return this.éviterDoubleSlash(this.replaceAll(chaine, /\{(.*?)\}/g, "")); } static remplacerParamètresAccolades(chercherDans, motif, valeur) { return HelperService.replaceAll(chercherDans, `{${motif}}`, valeur); } static estceObjetVide(objet) { return Object.keys(objet).length === 0 && objet.constructor === Object; } /** * Détection de savoir s'il l'on vient d'une nouvelle page ou d'une page du site */ static pageOuverteDepuisScript() { return window.opener !== null; } static éviterDoubleSlash(chaine) { return HelperService.replaceAll(chaine, /(https?:\/\/)|(\/){2,}/g, "$1$2"); } /** * Vérifie s'il existe une concordance entre les `paramètres de l'url courante` et les `paramètres de la source de données` * @param urlSourceDonnées : exemple : la source de données d'une page de type formulaire, http://api.sonate-dev.fr:85/tiers/individus/{id} * @param urlCouranteStatique : l'url du navigateur, http://localhost:1200/page/lab-formulaire?id=016247a2-2c1c-4e08-bd78-9b05659ec5ee */ static siConcordanceParamètresURLetSourceDonnées(urlSourceDonnées, urlCouranteStatique) { if (!urlSourceDonnées) return null; const urlCourante = urlCouranteStatique ? urlCouranteStatique : window.location.search; const paramètresAccolades = this.retourneParamètresAccolades(urlSourceDonnées); if (!paramètresAccolades.length) { return false; } for (let index = 0; index < paramètresAccolades.length; index++) { const paramètreAvecAccolades = paramètresAccolades[index]; const paramètreSansAccolade = paramètreAvecAccolades.substring(paramètreAvecAccolades.lastIndexOf("{") + 1, paramètreAvecAccolades.lastIndexOf("}")); const valeurParamètre = this.donneParamètresUrl(paramètreSansAccolade, urlCourante); if (!valeurParamètre) { return false; } } return true; } static retourneNullSiNonDéfini(valeur) { if (Array.isArray(valeur)) { valeur = valeur.length === 0 ? null : valeur; } else if (typeof valeur === 'number') { return valeur; } else { valeur = typeof valeur === "string" ? valeur.trim() : valeur; } return !valeur ? null : valeur; } static replaceAll(text, pattern, newText) { return text.replace(new RegExp(pattern, 'g'), newText); } static valeurTexteBooléen(valeur) { if (typeof (valeur) === "boolean") { return valeur ? "Oui" : "Non"; } return null; } static estNumerique(n) { return !isNaN(parseFloat(n)) && isFinite(n); } // 01 02 03 04 05 -> 0102030405 static adapteurEcritureTelephone(valeurAvecEspace) { let valeurSansEspace; if (!this.retourneNullSiNonDéfini(valeurAvecEspace)) { return null; } const tmp = valeurAvecEspace.split(' '); valeurSansEspace = tmp[0] + tmp[1] + tmp[2] + tmp[3] + tmp[4]; return valeurSansEspace; } static retourneValeurObjet(objet, propriété) { if (typeof objet !== 'undefined' && objet.hasOwnProperty(propriété)) { return objet[propriété]; } return null; } static dupliquerTableau(tableau) { return [...tableau]; } static ajouterValeurTableau(tableau, valeur) { return [...tableau, valeur]; } static ajouterValeurUniqueTableau(tableau, valeur) { if (tableau.indexOf(valeur) === -1) { return [...tableau, valeur]; } return tableau; } static arrondirZeroCinqPrès(nombre) { return Math.round(nombre * 2) * 0.5; } /** * Un GUID envoyé depuis le back au front est de la forme : (inheritor) {_value: "0163d59a-bcd8-44fe-852f-100af77dfb9b"} * @param objetInheritor objet GUID envoyé depuis le backoffice */ static désérialiserInheritorGuid(objetInheritor) { return objetInheritor._value ? objetInheritor._value : null; } static sérialiserInheritorGuid(valeur) { return null; // return valeur._value ? valeur : new Guid(valeur); } static estdetypeInheritorGuid(valeur) { return valeur.hasOwnProperty("_value"); } static estdetypeGuid(valeur) { if (!valeur) return false; return /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(valeur); } /** fin bloc GUID */ static valeurDéfautBooléen(valeur) { return (typeof valeur !== "undefined" && !valeur) ? false : true; } } HelperService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: HelperService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); HelperService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: HelperService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: HelperService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); class ValidatorsService { getValidationErrorMessage(error) { const configClésErreurs = { 'required': (!error.message ? 'Veuillez saisir ce champ' : error.message), 'invalidEmailAddress': 'L\'e-mail n\'est pas valide.', 'invalidCodePostal': 'Le code postal n\'est pas valide.', 'invalidDate': "Veuillez saisir une date valide.", 'invalidHeure': "L'heure n'est pas au bon format.", 'invalideDateHeure': "La date/heure n'est pas valide.", 'regexInvalide': (!error.value.formatRegexEnClair ? 'Le format attendu est incorrect.' : `Fomat attendu : ${error.value.formatRegexEnClair}.`), 'invalidTypeMime': "Le type du document n'est pas accepté.", 'invalidTailleTotaleUpload': `La taille totale des pièces jointes est atteinte.`, 'invalidTailleUpload': `La taille limite de la pièce jointe est atteinte.`, 'datePasseeInvalide': "La date doit être dans le passé.", 'dateFutureInvalide': "La date doit être dans le future.", 'datePasseeOuPresenteInvalide': "La date doit être passée ou présente.", 'dateFutureOuPresenteInvalide': "La date doit être présente ou future.", 'invalidIMEI': "Le numéro IMEI est invalide.", 'invalidDateAnterieure': "La date doit être antérieure.", 'dateAvantUneAutre': "La date B doit être antérieure à la date A.", 'invalidNumeroTelephone': 'Le numéro de téléphone n\'est pas valide.', 'adresseMailDejaUtilisee': 'L\'adresse e-mail est déjà utilisée.', 'identiqueValidator': 'Le champ n\'est pas identique.', 'pseudoDejaUtilisee': 'Le pseudo est déjà utilisé.', 'utilisateurMajeurInvalide': 'Vous devez être majeur.', 'entierInvalide': 'Saisissez un entier.', 'auMoinsUnChampRequis': 'Veuillez saisir au moins un critère de recherche.' }; return configClésErreurs[error.key]; } static require(control) { const value = HelperService.retourneNullSiNonDéfini(control.value); if (control.hasValidator(ValidatorsService.dateValidator)) { return value === null ? { invalidDate: true } : null; } else { return value === null ? { "required": true } : null; } } static emailValidator(control) { if (!control.value) return null; // RFC 2822 compliant regex if (control.value.match(/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/)) { return null; } else { return { 'invalidEmailAddress': true }; } } static dateValidator(control) { return null; } static telephoneValidator(control) { if (!control.value) return null; if (control.value.match(/^0[1-9](\s[0-9][0-9]){4}$/)) { return null; } else { return { 'invalidNumeroTelephone': true }; } } static codepostalValidator(control) { if (!control.value) return null; if (control.value.match(/^(([0-8][0-9])|(9[0-5]))[0-9]{3}$/)) { return null; } else { return { 'invalidCodePostal': true }; } } /** VALIDATEURS DATES */ /** * La date à valider est au format UTC : 1982-11-06T00:00:00Z */ // public static dateValidateurUTC(control: FormControl): any { // if (!control.value) return null; // const str = control.value; // const dateValide: boolean = DateFunctions.validerDateUTC(str); // return dateValide ? null : { 'invalidDate': true }; // } // l'heure est au format 11h12 // public static heureValidateur(control: FormControl): any { // if (!control.value) return null; // const str = control.value; // if (DateFunctions.validerUneHeure(str)) { // return null; // } else { // return { 'invalidHeure': true }; // } // } // la date heure est au format 01/01/2018 à 12h14 // public static dateHeureValidateur(control: FormControl): any { // if (!control.value) return null; // const str: string = control.value; // const valeurSplit: string[] = str.split(configdefault.date.dateTimeSeparator); // const dateValide: boolean = DateFunctions.validerDateJJMMAAAA(valeurSplit[0]); // const heureValide: boolean = DateFunctions.validerUneHeure(valeurSplit[1]); // if (!dateValide) { // return { 'invalidDate': true }; // } else if (!heureValide) { // return { 'invalidHeure': true }; // } else { // return null; // } // } /** * La date à valider est au format UTC : 1982-11-06T15:15:15Z * invalideDateHeure */ // public static dateHeureValidateurUTC(control: FormControl): any { // if (!control.value) return null; // const str = control.value; // const dateValide: boolean = DateFunctions.validerDateUTC(str); // return dateValide ? null : { 'invalideDateHeure': true }; // } // public static datePasséeValidateur(control: FormControl): any { // if (!control.value) return null; // const dates: Date[] = DateFunctions.validateurDatesAides(control.value); // if (dates[0] >= dates[1]) { // return { // 'datePasseeInvalide': true // }; // } // return null; // } // public static dateFutureValidateur(control: FormControl): any { // if (!control.value) return null; // const dates: Date[] = DateFunctions.validateurDatesAides(control.value); // if (dates[0] <= dates[1]) { // return { // 'dateFutureInvalide': true // }; // } // return null; // } // public static datePasséeOuPrésenteValidateur(control: FormControl): any { // if (!control.value) return null; // const dates: Date[] = DateFunctions.validateurDatesAides(control.value); // if (dates[0] > dates[1]) { // return { // 'datePasseeOuPresenteInvalide': true // }; // } // return null; // } // public static dateFutureOuPrésenteValidateur(control: FormControl): any { // if (!control.value) return null; // const dates: Date[] = DateFunctions.validateurDatesAides(control.value); // if (dates[0] < dates[1]) { // return { // 'dateFutureOuPresenteInvalide': true // }; // } // return null; // } /** / VALIDATEURS DATES */ // https://medium.com/front-end-hacking/reactive-forms-and-form-validation-with-angular-fdcbcf98e1e8 static regexValidator(regle, formatRegexEnClair) { return (control) => { if (!control.value) return null; const regexp = new RegExp(regle); return !regexp.test(control.value) ? { 'regexInvalide': { formatRegexEnClair } } : null; }; } static numeroSinistreValidator(control) { if (!control.value) return null; if (control.value.match(/^([A-z0-9]{2})?(L|l)[A-z0-9](T|t)[A-z0-9]{5}$/)) { return null; } else { return { 'invalidNumeroSinistre': true }; } } static caseACocherRequireValidator(control) { if (control.value === true) { return null; } else { return { 'required': true }; } } static dateAvantUneAutre(champDateAvant, champDateAprès) { return (group) => { if (!group.get(champDateAvant) || !group.get(champDateAprès)) return null; const dateDébut = group.get(champDateAvant).value; const dateFin = group.get(champDateAprès).value; if (dateDébut > dateFin) { return { 'erreurDateFinAvantDébut': true }; } return null; }; } // https://gist.github.com/DiegoSalazar/4075533 static luhnValidator(control) { let valeur = control.value; // accept only digits, dashes or spaces if (/[^0-9-\s]+/.test(valeur)) return { 'invalidIMEI': true }; // The Luhn Algorithm. It's so pretty. let nCheck = 0; let nDigit = 0; let bEven = false; valeur = valeur.replace(/\D/g, ""); for (let n = valeur.length - 1; n >= 0; n--) { const cDigit = valeur.charAt(n); nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = !bEven; } if (nCheck % 10 === 0) { return null; } else { return { 'invalidIMEI': true }; } } static identiqueValidator(controle, controleConfirme) { return (group) => { const password = group.controls[controle]; const confirmPassword = group.controls[controleConfirme]; if (password.value !== confirmPassword.value) { return { 'identiqueValidator': true }; } }; } static êtreMajeurValidateur(control) { if (parseInt(control.value) >= 18) { return null; } else { return { 'utilisateurMajeurInvalide': true }; } } static entierValidateur(control) { if (control.value.match(/^\d+$/)) { return null; } else { return { 'entierInvalide': true }; } } static auMoinsUnChampDoitEtreRequisValidateur() { return (group) => { let isAtLeastOne = false; if (group && group.controls) { for (const control in group.controls) { if (group.controls.hasOwnProperty(control) && group.controls[control].valid && HelperService.retourneNullSiNonDéfini(group.controls[control].value)) { isAtLeastOne = true; break; } } } return isAtLeastOne ? null : { 'auMoinsUnChampRequis': true }; }; } } ValidatorsService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: ValidatorsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); ValidatorsService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: ValidatorsService, providedIn: 'root' }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: ValidatorsService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }] }); class CurrentUrlRoutingService { constructor() { this.currentUrl = new BehaviorSubject(undefined); } } CurrentUrlRoutingService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: CurrentUrlRoutingService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); CurrentUrlRoutingService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: CurrentUrlRoutingService }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.1", ngImport: i0, type: CurrentUrlRoutingService, decorators: [{ type: Injectable }] }); var FragmentType; (function (FragmentType) { FragmentType[FragmentType["OrderBy"] = 1] = "OrderBy"; FragmentType[FragmentType["Top"] = 2] = "Top"; FragmentType[FragmentType["Skip"] = 3] = "Skip"; FragmentType[FragmentType["Count"] = 4] = "Count"; FragmentType[FragmentType["Expand"] = 5] = "Expand"; FragmentType[FragmentType["Filter"] = 6] = "Filter"; FragmentType[FragmentType["Select"] = 7] = "Select"; })(FragmentType || (FragmentType = {})); class QueryFragment { constructor(type, value) { this.type = type; this.value = value; } } class FilterBuilder { constructor() { this.fragments = []; this.filterExpression = (field, operator, value) => { this.fragments.push(new QueryFragment(FragmentType.Filter, `${field} ${operator} ${this.getValue(value)}`)); return this; }; this.filterPhrase = (phrase) => { this.fragments.push(new QueryFragment(FragmentType.Filter, phrase)); return this; }; this.and = (predicate) => { this.fragments.push(new QueryFragment(FragmentType.Filter, `(${predicate(new FilterBuilder()).toQuery('and')})`)); return this; }; this.or = (predicate) => { this.fragments.push(new QueryFragment(FragmentType.Filter, `(${predicate(new FilterBuilder()).toQuery('or')})`)); return this; }; this.toQuery = (operator) => { if (!this.fragments || this.fragments.length < 1) return ''; return this.fragments.map(f => f.value).join(` ${operator} `); }; } getValue(value) { let type = typeof value; if (value instanceof Date) type = 'date'; switch (type) { case 'string': return `'${value}'`; case 'date': return `${value.toISOString()}`; default: return `${value}`; } } } class QueryBuilder { constructor() { this.fragments = []; this.orderBy = (fields) => { this.clear(FragmentType.OrderBy); this.fragments.push(new QueryFragment(FragmentType.OrderBy, `$orderby=${fields}`)); return this; }; this.top = (top) => { this.clear(FragmentType.Top); this.fragments.push(new QueryFragment(FragmentType.Top, `$top=${top}`)); return this; }; this.skip = (skip) => { this.clear(FragmentType.Skip); this.fragments.push(new QueryFragment(FragmentType.Skip, `$skip=${skip}`)