UNPKG

@tapsellorg/angular-material-library

Version:

Angular library for Tapsell

1,024 lines (988 loc) 43.6 kB
import * as i0 from '@angular/core'; import { Pipe, NgModule, InjectionToken, Inject, Injectable, LOCALE_ID, DEFAULT_CURRENCY_CODE } from '@angular/core'; import { CommonModule } from '@angular/common'; import { startWith, catchError, tap, finalize, share, filter, map, mergeMap } from 'rxjs/operators'; import { Subject, EMPTY, throwError, of } from 'rxjs'; import * as i1 from '@angular/platform-browser'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import * as i2 from '@angular/router'; import { NavigationEnd } from '@angular/router'; import * as i2$1 from '@tapsellorg/angular-material-library/notif'; import { MAT_RIPPLE_GLOBAL_OPTIONS } from '@angular/material/core'; import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field'; import { MAT_TABS_CONFIG } from '@angular/material/tabs'; import { MAT_RADIO_DEFAULT_OPTIONS } from '@angular/material/radio'; import { MAT_CHECKBOX_DEFAULT_OPTIONS } from '@angular/material/checkbox'; import { MAT_SNACK_BAR_DEFAULT_OPTIONS } from '@angular/material/snack-bar'; import { MAT_PAGINATOR_DEFAULT_OPTIONS } from '@angular/material/paginator'; class PghArrayJoinPipe { transform(value, customField, joinWith = ',') { if (!value) return ''; if (!Array.isArray(value)) { throw new Error('pghArrayJoin: value is not an array'); } return (value ?? []) .filter(v => !!v) .map(v => (customField ? v[customField] : v)) .filter(v => !!v) .join(`${joinWith} `); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinPipe, isStandalone: false, name: "pghArrayJoin" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinPipe, decorators: [{ type: Pipe, args: [{ name: 'pghArrayJoin', pure: true, standalone: false, }] }] }); class PghReplaceWithPipe { transform(value, dictionary) { return dictionary.get(value) ?? 'تعریف نشده'; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithPipe, isStandalone: false, name: "pghReplaceWith" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithPipe, decorators: [{ type: Pipe, args: [{ name: 'pghReplaceWith', standalone: false, }] }] }); class PghReplaceWithModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithModule, declarations: [PghReplaceWithPipe], imports: [CommonModule], exports: [PghReplaceWithPipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghReplaceWithModule, decorators: [{ type: NgModule, args: [{ declarations: [PghReplaceWithPipe], imports: [CommonModule], exports: [PghReplaceWithPipe], }] }] }); class PghArrayJoinModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinModule, declarations: [PghArrayJoinPipe], imports: [CommonModule], exports: [PghArrayJoinPipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArrayJoinModule, decorators: [{ type: NgModule, args: [{ declarations: [PghArrayJoinPipe], exports: [PghArrayJoinPipe], imports: [CommonModule], }] }] }); class PghArraySplitPipe { transform(value, splitBy = '') { if (typeof value !== 'string') { throw new Error('pghArraySplit: value is not a string'); } return (value ?? '').split(splitBy); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitPipe, isStandalone: false, name: "pghArraySplit" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitPipe, decorators: [{ type: Pipe, args: [{ name: 'pghArraySplit', pure: true, standalone: false, }] }] }); class PghArraySplitModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitModule, declarations: [PghArraySplitPipe], imports: [CommonModule], exports: [PghArraySplitPipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghArraySplitModule, decorators: [{ type: NgModule, args: [{ declarations: [PghArraySplitPipe], imports: [CommonModule], exports: [PghArraySplitPipe], }] }] }); // @dynamic class StringUtils { static copyToClipboard(str) { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.append(el); el.select(); document.execCommand('copy'); el.remove(); } static { this.engNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; } static { this.perNumbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']; } static convertPersianNumbersToEnglish(theText) { return this.stringReplaceBulk(theText, StringUtils.perNumbers, StringUtils.engNumbers); } static convertEnglishNumbersToPersian(theText) { return this.stringReplaceBulk(theText, StringUtils.engNumbers, StringUtils.perNumbers); } static { this.convertToTwoCharactersNumber = (num) => num.toString().length < 2 ? `0${num}` : num; } static stringReplaceBulk(str, findArray, replaceArray) { if (!str) return ''; const regex = []; const map = {}; findArray.forEach((fItem, index) => { regex.push(fItem.replace(/([#$()*+,.?[\\\]^{|}-])/g, '\\$1')); map[fItem] = replaceArray[index]; }); const regexStr = regex.join('|'); str = str.replace(new RegExp(regexStr, 'g'), matched => map[matched]); return str; } static persianNimFasele() { return '‌'; // nim fasele dare! } static capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } static getNameTwoLettersAbbr(firstName, lastName, username) { return (firstName ? `${firstName.charAt(0)}` : lastName ? `${lastName.charAt(0)}` : `${username.charAt(0)}`).toUpperCase(); } static splitColumnedTextToObj(text) { if (!text) return {}; return text.split(':').reduce((result, key) => ({ ...result, [key]: true }), {}); } } class ArrayUtilsClass { removeDuplicates(array, uniqueBy) { const uniqueIds = Array.from(new Set(array.map(uniqueBy))); return array.filter(s => { const index = uniqueIds.findIndex(type => uniqueBy(s) === type); if (index !== -1) { uniqueIds.splice(index, 1); return true; } return false; }); } arraysAreSame(arr1, arr2) { if (arr1 === arr2) return true; if (!Array.isArray(arr1) || !Array.isArray(arr2)) return false; if (arr1.length !== arr2.length) return false; const sortedArr1 = arr1.concat().sort(); const sortedArr2 = arr2.concat().sort(); return sortedArr1.every((_x, i) => sortedArr1[i] === sortedArr2[i]); } convertArrayToKeyValue(arr, keyGetter, valueGetter) { return arr.reduce((res, x) => { const key = keyGetter(x); const value = valueGetter(x); return { ...res, [key]: value }; }, {}); } searchStringInArray(array, _term, valueFunc) { const term = _term ? _term.toLowerCase().replace(/\s+/g, ' ') : ''; return array.filter(item => (valueFunc(item) ?? '').toString().toLowerCase().replace(/\s+/g, ' ').includes(term)); } } const ArrayUtils = new ArrayUtilsClass(); class MiscUtils { static { this.colorsTheme = {}; } static { this.ALL_MATERIAL_COLORS = [ 'var(--red)', 'var(--green)', 'var(--blue)', 'var(--orange)', 'var(--purple)', 'var(--pink)', 'var(--teal)', 'var(--yellow)', 'var(--brown)', 'var(--lime)', 'var(--cyan)', ]; } static { this.RANDOM_COLORS = [ '#9966cc', '#800000', '#c95911', '#4169e1', '#1a9c8c', '#cea100', '#006400', '#ff69b4', '#003366', '#d52f12', '#e75480', '#36454f', '#279a13', '#999225', '#f88379', '#a78500', '#66023c', '#36454f', '#8f8b66', '#008080', '#cd7f32', '#b38b6d', '#612302', ]; } static getThemeColor(type) { return `var(--${type})`; } } class FileUtils { // static retrieveImageBase64(file: File) { // const reader = new FileReader(); // reader.readAsDataURL(file); // reader.onload = () => { // const base64 = reader.result as string; // }; // reader.onerror = error => {}; // } static { this.defaultFilename = 'tapsell-file'; } static async urlToFile(url, filename) { const res = await fetch(url); const blob = await res.blob(); return new File([blob], filename || this.defaultFilename, { type: blob.type }); } static base64ToBlob(file) { // Split into two parts const parts = file.split(';base64,'); // Hold the content type const imageType = parts[0].split(':')[1]; // Decode Base64 string const decodedData = window.atob(parts[1]); // Create UNIT8ARRAY of size same as row data length const uInt8Array = new Uint8Array(decodedData.length); // Insert all character code into uInt8Array for (let i = 0; i < decodedData.length; ++i) { uInt8Array[i] = decodedData.charCodeAt(i); } // Return BLOB image after conversion return new Blob([uInt8Array], { type: imageType }); } static base64ToFile(file, filename) { const blob = FileUtils.base64ToBlob(file); return new File([blob], filename || this.defaultFilename, { type: blob.type }); } static blobToFile(blob, filename) { return new File([blob], filename || this.defaultFilename, { type: blob.type }); } static fileOrBlobToBase64(file) { if (!file) return; return new Promise((resolve, _) => { const reader = new FileReader(); reader.onloadend = () => resolve(reader.result); reader.readAsDataURL(file); }); } static fileNameExtension(fileName) { return fileName.split('.').pop() ?? ''; } static convertFileListToArray(_files) { const files = []; for (let i = 0; i < _files.length; i++) { const file = _files[i]; files.push(file); } return files; } static downloadFile(file) { const urlCreator = window.URL || window.webkitURL, link = document.createElement('a'), url = urlCreator.createObjectURL(file); link.setAttribute('download', file.name); link.setAttribute('href', url); document.body.appendChild(link); link.click(); link.remove(); urlCreator.revokeObjectURL(url); } } class ObjectUtilsClass { convertObjToArrValues(obj) { return Object.keys(obj).map(key => obj[key]); } convertObjToArrKeyValue(obj) { return Object.keys(obj).map(key => ({ key, value: obj[key] })); } cloneObjWithKeys(obj, keys) { return keys.reduce((res, k) => ({ ...res, [k]: obj[k] }), {}); } removeNullKeysFromObject(obj) { return this.objectFilter(obj, (key, value) => value == null); } objectFilter(obj, keyFilterer) { Object.keys(obj).forEach(key => { if (keyFilterer(key, obj[key])) { delete obj[key]; } }); return obj; } isObject(item) { return item && typeof item === 'object' && !Array.isArray(item); } /** * Deep merge two objects. */ mergeDeep(target, ...sources) { if (!sources.length) return target; const source = sources.shift() ?? {}; if (ObjectUtils.isObject(target) && ObjectUtils.isObject(source)) { Object.keys(source).forEach(key => { if (ObjectUtils.isObject(source[key])) { if (!target[key]) { target[key] = {}; } ObjectUtils.mergeDeep(target[key], source[key]); } else { target[key] = source[key]; } }); } return ObjectUtils.mergeDeep(target, ...sources); } isEqualObject(obj1, obj2) { if (!ObjectUtils.isObject(obj1) || !ObjectUtils.isObject(obj2)) return false; if (Object.keys(obj1).length !== Object.keys(obj2).length) return false; return Object.keys(obj1).every(key => obj1[key] === obj2[key]); } } const ObjectUtils = new ObjectUtilsClass(); /** * @deprecated Use BehaviorSubject instead. Use its `.next()` and `.value` * @param obs * @constructor */ // eslint-disable-next-line @typescript-eslint/naming-convention function ObservedBy(obs) { return function (target, propertyName) { let store = target[propertyName]; const setter = (newVal) => { store = newVal; target[`_${obs}`].next(newVal); }; delete target[propertyName]; // if (delete target[propertyName]) { // Create new property with getter and setter Object.defineProperty(target, propertyName, { get: () => store, set: setter, enumerable: true, configurable: true, }); // } }; } /** * @deprecated Use BehaviorSubject instead. Use its `.next()` and `.value` * @param store * @constructor */ // eslint-disable-next-line @typescript-eslint/naming-convention function Observing(store) { return function (target, propertyName) { let subject = target[propertyName] || new Subject(); if (delete target[propertyName]) { // observable (getter) Object.defineProperty(target, propertyName, { get: () => subject.pipe(startWith(target[store])), set: () => { }, enumerable: true, configurable: true, }); // Subject Object.defineProperty(target, `_${propertyName}`, { get: () => subject, set: _subject => { subject = _subject; }, enumerable: true, configurable: true, }); } }; } function withDestroy(base = class { }) { return class extends base { constructor() { super(...arguments); this._destroyed$ = new Subject(); } ngOnDestroy() { this._destroyed$.next(undefined); this._destroyed$.complete(); } }; } /** * Debounce a method */ function pghDebounceTime(ms) { return function (target, key, descriptor) { const map = new WeakMap(); const originalMethod = descriptor.value; descriptor.value = function () { let debounced = map.get(this); if (!debounced) { debounced = debounceFn(() => originalMethod.apply(this, arguments), ms); map.set(this, debounced); } debounced(); }; return descriptor; }; } const debounceFn = (func, ms) => { let timeout; return function () { clearTimeout(timeout); timeout = window.setTimeout(func, ms); }; }; class PghSafePipe { constructor(sanitizer) { this.sanitizer = sanitizer; } transform(value, type) { switch (type) { case 'html': return this.sanitizer.bypassSecurityTrustHtml(value); case 'style': return this.sanitizer.bypassSecurityTrustStyle(value); case 'script': return this.sanitizer.bypassSecurityTrustScript(value); case 'url': return this.sanitizer.bypassSecurityTrustUrl(value); case 'resourceUrl': return this.sanitizer.bypassSecurityTrustResourceUrl(value); default: throw new Error(`Invalid safe type: ${type}`); } } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghSafePipe, deps: [{ token: i1.DomSanitizer }], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghSafePipe, isStandalone: false, name: "pghSafe" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghSafePipe, decorators: [{ type: Pipe, args: [{ name: 'pghSafe', pure: true, standalone: false, }] }], ctorParameters: () => [{ type: i1.DomSanitizer }] }); class PghShortNumberPipe { transform(number, args) { if (isNaN(number)) return null; if (number === null) return null; if (number === 0) return 0; const isNegative = number < 0; if (isNegative) number = number * -1; const suffixes = ['', 'K', 'M', 'B', 'T', 'Q']; const exp = Math.floor(Math.log(number) / Math.log(1000)); return (isNegative ? '-' : '') + (number / Math.pow(1000, exp)).toFixed(args) + suffixes[exp]; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberPipe, isStandalone: false, name: "pghShortNumber" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberPipe, decorators: [{ type: Pipe, args: [{ name: 'pghShortNumber', standalone: false, }] }] }); class PghSafeModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghSafeModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghSafeModule, declarations: [PghSafePipe], imports: [CommonModule], exports: [PghSafePipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghSafeModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghSafeModule, decorators: [{ type: NgModule, args: [{ declarations: [PghSafePipe], imports: [CommonModule], exports: [PghSafePipe], }] }] }); class PghEnumToArrayPipe { transform(object) { return Object.keys(object) .filter(key => isNaN(+key)) .map(key => ({ key: key, value: object[key] })); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); } static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayPipe, isStandalone: false, name: "pghEnumToArray" }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayPipe, decorators: [{ type: Pipe, args: [{ name: 'pghEnumToArray', standalone: false, }] }] }); class PghEnumToArrayModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayModule, declarations: [PghEnumToArrayPipe], imports: [CommonModule], exports: [PghEnumToArrayPipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghEnumToArrayModule, decorators: [{ type: NgModule, args: [{ declarations: [PghEnumToArrayPipe], imports: [CommonModule], exports: [PghEnumToArrayPipe], }] }] }); class PghShortNumberModule { static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); } static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberModule, declarations: [PghShortNumberPipe], imports: [CommonModule], exports: [PghShortNumberPipe] }); } static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberModule, imports: [CommonModule] }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghShortNumberModule, decorators: [{ type: NgModule, args: [{ declarations: [PghShortNumberPipe], imports: [CommonModule], exports: [PghShortNumberPipe], }] }] }); const PGH_ERROR_HANDLER_OPTIONS = new InjectionToken('PGH_ERROR_DEFINER', { providedIn: 'root', factory: () => ({ SERVER_ERRORS: [], UNHANDLED_ERROR_MESSAGE: 'یک خطای ناشناخته رخ داده است' }), }); class PghErrorHandlerService { static isHttpErrorResponse(error) { return error instanceof HttpErrorResponse || (error.error && typeof error.status === 'number'); } static getToastMessageOfErrorDef(textOrFunc, response) { return (textOrFunc && (typeof textOrFunc === 'string' ? textOrFunc : textOrFunc(response.error, response))); } constructor(router, errorDefiner) { this.router = router; this.errorDefiner = errorDefiner; } handleError(response) { if (!PghErrorHandlerService.isHttpErrorResponse(response)) { return { isHandled: false, message: this.errorDefiner.UNHANDLED_ERROR_MESSAGE }; } const errorDef = this.matchErrorDefinition(response); let message; if (errorDef) { const errorToastMessage = PghErrorHandlerService.getToastMessageOfErrorDef(errorDef.message, response); if (errorToastMessage) { message = errorToastMessage; } errorDef.callback?.(response.error, response); return { isHandled: errorDef.isHandled, message, action: errorDef.action }; } message = this.errorDefiner.UNHANDLED_ERROR_MESSAGE; return { isHandled: false, message }; } matchErrorDefinition(response) { return this.errorDefiner.SERVER_ERRORS.find(({ condition }) => (condition.status == null || condition.status === response.status) && (condition.pathEndsWith == null || response.url?.endsWith(condition.pathEndsWith)) && (condition.response == null || Object.keys(condition.response).every(k => response.error[k] === condition.response?.[k])) && (condition.custom == null || condition.custom(response.error, response))); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghErrorHandlerService, deps: [{ token: i2.Router }, { token: PGH_ERROR_HANDLER_OPTIONS }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghErrorHandlerService, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghErrorHandlerService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: () => [{ type: i2.Router }, { type: undefined, decorators: [{ type: Inject, args: [PGH_ERROR_HANDLER_OPTIONS] }] }] }); class PghErrorHandlerInterceptor { constructor(pghErrorHandlerService, pghNotifService) { this.pghErrorHandlerService = pghErrorHandlerService; this.pghNotifService = pghNotifService; } intercept(request, next) { return next.handle(request).pipe(catchError((response) => { const { isHandled, message, action } = this.pghErrorHandlerService.handleError(response); if (message) { const snack = this.pghNotifService.error(message, { action: action?.buttonName }); if (action?.afterClick) { snack.onAction().subscribe(() => action.afterClick(response.error, response)); } } if (isHandled) { return EMPTY; } return throwError(response); })); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghErrorHandlerInterceptor, deps: [{ token: PghErrorHandlerService }, { token: i2$1.PghNotifService }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghErrorHandlerInterceptor }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghErrorHandlerInterceptor, decorators: [{ type: Injectable }], ctorParameters: () => [{ type: PghErrorHandlerService }, { type: i2$1.PghNotifService }] }); class PghTrailingSlashInterceptor { static isSlashNeeded(request) { return (request.url.endsWith('/') || request.url.includes('?') || request.url.match(/\.[\w\d]+$/)); } constructor() { } intercept(request, next) { return PghTrailingSlashInterceptor.isSlashNeeded(request) ? next.handle(request) : next.handle(request.clone({ url: `${request.url}/` })); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghTrailingSlashInterceptor, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghTrailingSlashInterceptor }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghTrailingSlashInterceptor, decorators: [{ type: Injectable }], ctorParameters: () => [] }); const PGH_CACHE_INTERCEPTOR_OPTIONS = new InjectionToken('PGH_CACHE_INTERCEPTOR_OPTIONS', { providedIn: 'root', factory: () => ({}), }); class CacheControllerService { constructor() { this.clearCache$ = new Subject(); } clearAllCache() { this.clearCache$.next(null); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: CacheControllerService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: CacheControllerService, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: CacheControllerService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: () => [] }); class CacheInterceptor { constructor(options, cacheControllerService) { this.options = options; this.cacheControllerService = cacheControllerService; this.CACHE_EXPIRE_TIME = 5 * 60 * 1000; this.cachedResponses = new Map(); this.pendingRequests = new Map(); this.cacheControllerService.clearCache$.subscribe(() => { this.cachedResponses.clear(); }); } intercept(req, next) { if (!this.options.forceEnableCacheIf?.(req) && (req.method !== 'GET' || this.options.disableCacheIf?.(req))) { return next.handle(req); } // Check if there is a pending response for this request const cachedObservable = this.pendingRequests.get(req.urlWithParams); if (cachedObservable) { return cachedObservable; } // Check if there is a cached response for this request const cachedResponse = this.cachedResponses.get(req.urlWithParams); if (cachedResponse && cachedResponse.savedTime < Date.now() - this.CACHE_EXPIRE_TIME) { return of(cachedResponse.response.clone()); } const sharedReqObservable = next.handle(req).pipe(tap(event => { if (event instanceof HttpResponse) { this.cachedResponses.set(req.urlWithParams, { response: event.clone(), savedTime: Date.now(), }); } }), finalize(() => { this.pendingRequests.delete(req.urlWithParams); }), share()); this.pendingRequests.set(req.urlWithParams, sharedReqObservable); return sharedReqObservable; } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: CacheInterceptor, deps: [{ token: PGH_CACHE_INTERCEPTOR_OPTIONS }, { token: CacheControllerService }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: CacheInterceptor }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: CacheInterceptor, decorators: [{ type: Injectable }], ctorParameters: () => [{ type: undefined, decorators: [{ type: Inject, args: [PGH_CACHE_INTERCEPTOR_OPTIONS] }] }, { type: CacheControllerService }] }); const PGH_PRODUCT_TITLE = new InjectionToken('PGH_PRODUCT_TITLE', { providedIn: 'root', factory: () => 'tapsell', }); class PghTabTitleService { constructor(titleService, router, activatedRoute, PRODUCT_TITLE) { this.titleService = titleService; this.router = router; this.activatedRoute = activatedRoute; this.PRODUCT_TITLE = PRODUCT_TITLE; this.setupAllPageTitle(); } setupAllPageTitle() { this.router.events .pipe(filter(event => event instanceof NavigationEnd), map(() => this.activatedRoute), map(route => { while (route.firstChild) route = route.firstChild; return route; }), filter(route => route.outlet === 'primary'), mergeMap(route => route.data)) .subscribe(({ title }) => { this.setTitle(title); }); } setTitle(title) { const currentTitle = `${title} - ${this.PRODUCT_TITLE}`; this.titleService.setTitle(title ? currentTitle : this.PRODUCT_TITLE); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghTabTitleService, deps: [{ token: i1.Title }, { token: i2.Router }, { token: i2.ActivatedRoute }, { token: PGH_PRODUCT_TITLE }], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghTabTitleService, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghTabTitleService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: () => [{ type: i1.Title }, { type: i2.Router }, { type: i2.ActivatedRoute }, { type: undefined, decorators: [{ type: Inject, args: [PGH_PRODUCT_TITLE] }] }] }); const PGH_MAT_GLOBAL_OPTIONS = [ { provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: { appearance: 'outline' } }, { provide: LOCALE_ID, useValue: 'fa-IR' }, { provide: DEFAULT_CURRENCY_CODE, useValue: 'IRR' }, { provide: MAT_TABS_CONFIG, useValue: { animationDuration: '0ms' }, }, { provide: MAT_RADIO_DEFAULT_OPTIONS, useValue: { color: 'primary' }, }, { provide: MAT_CHECKBOX_DEFAULT_OPTIONS, useValue: { color: 'primary' }, }, { provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 3000, direction: 'rtl', horizontalPosition: 'start', }, }, { provide: MAT_RIPPLE_GLOBAL_OPTIONS, useValue: { animation: { enterDuration: 150, exitDuration: 100 } }, }, { provide: MAT_PAGINATOR_DEFAULT_OPTIONS, useValue: { pageSizeOptions: [15, 25, 50, 100], showFirstLastButtons: true, pageSize: 25, }, }, ]; // @dynamic class PghStorageFactory { static { this.KEY_PREFIX = '_pgh-'; } constructor(getStorage) { this.inMemoryStorage = {}; this.storage = getStorage?.(); this.checkStorageSupport(); } static { this.localStorageFactory = () => { try { return new PghStorageFactory(() => localStorage); } catch (e) { return new PghStorageFactory(); } }; } checkStorageSupport() { if (!this.storage) return; try { const testKey = '__pgh_rand__'; this.storage.setItem(testKey, testKey); this.storage.removeItem(testKey); } catch (_) { this.storage = undefined; } } clear() { if (this.storage) { this.storage.clear(); } else { this.inMemoryStorage = {}; } } static getPrefixedName(name) { return `${PghStorageFactory.KEY_PREFIX}${name}`; } getItem(name) { if (this.storage) { const prefixedName = PghStorageFactory.getPrefixedName(name); return this.storage.getItem(prefixedName); } if (this.inMemoryStorage.hasOwnProperty(name)) { return this.inMemoryStorage[name]; } return null; } key(index) { if (this.storage) { return this.storage.key(index); } else { return Object.keys(this.inMemoryStorage)[index] || null; } } removeItem(name) { if (this.storage) { const prefixedName = PghStorageFactory.getPrefixedName(name); this.storage.removeItem(prefixedName); } else { delete this.inMemoryStorage[name]; } } setItem(name, value) { if (this.storage) { const prefixedName = PghStorageFactory.getPrefixedName(name); this.storage.setItem(prefixedName, value); } else { this.inMemoryStorage[name] = String(value); // not everyone uses TypeScript } } get length() { if (this.storage) { return this.storage.length; } else { return Object.keys(this.inMemoryStorage).length; } } } // @dynamic class UrlUtils { static concatTwoPaths(path1 = '', path2 = '') { path1 = (path1 || '').toString(); path2 = (path2 || '').toString(); path1 = this.removeTrailingSlashes(path1); path2 = this.removeTrailingSlashes(path2); let result = path2 ? `${path1}/${path2}` : `${path1}`; // result = result.replace(/\/\//g, '/'); result = this.removeTrailingSlashes(result); return result; } static concatPaths(...paths) { return paths.reduce((res, p) => UrlUtils.concatTwoPaths(res, p), ''); } static removeTrailingSlashes(path) { return (path || '').replace(/^\/+|\/+$/g, ''); } static mergeParamsToUrl(url, params) { const urlObject = new URL(url); const urlParams = urlObject.searchParams; Object.keys(params).forEach(k => { urlParams.set(k, params[k]); }); return urlObject.toString(); } static removeOrigin(url) { const matchProtocolDomainHost = /^[a-zA-Z]{3,5}\:\/{2}[a-zA-Z0-9_.:-]+\//; return url.replace(matchProtocolDomainHost, ''); } static removeQueryParams(router, paramsToRemove) { const url = new URL(location.href); const params = {}; url.searchParams.forEach((value, key) => { if (!paramsToRemove.includes(key)) params[key] = value; }); // `[url.pathname]` is used instead of `[]` because when the function is executing, // the navigation is not complete yet, and we will always end up in the root path. // So, we have to manually provide the path data. router.navigate([url.pathname], { queryParams: params }); } } class PghDarkModeService { constructor() { this.isEnabledStorageKey = 'IS_DARK_MODE_ENABLED'; this.htmlElement = document.getElementsByTagName('html')[0]; this.localStorageFactory = PghStorageFactory.localStorageFactory(); this.isDarkModeEnabled = false; this.setupDarkModeToggle(); } setupDarkModeToggle() { const isDarkModeEnabled = this.getDarkModeEnabled(); this.setDarkMode(isDarkModeEnabled, { store: false }); } getUserDevicePreference() { return window.matchMedia('(prefers-color-scheme: dark)').matches; } getDarkModeEnabled() { const isStorageDarkModeEnabled = this.localStorageFactory.getItem(this.isEnabledStorageKey); return isStorageDarkModeEnabled == null ? this.getUserDevicePreference() : isStorageDarkModeEnabled === 'true'; } toggleDarkMode() { this.setDarkMode(!this.isDarkModeEnabled); } setDarkMode(isDarkModeEnabled, { store } = { store: true }) { this.isDarkModeEnabled = isDarkModeEnabled; if (store) { this.storeDarkModeInStorage(); } this.enableDarkTheme(); } storeDarkModeInStorage() { this.localStorageFactory.setItem(this.isEnabledStorageKey, this.isDarkModeEnabled ? 'true' : 'false'); } enableDarkTheme() { this.htmlElement.setAttribute('dark', `${this.isDarkModeEnabled}`); } static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghDarkModeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); } static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghDarkModeService, providedIn: 'root' }); } } i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.13", ngImport: i0, type: PghDarkModeService, decorators: [{ type: Injectable, args: [{ providedIn: 'root', }] }], ctorParameters: () => [] }); /** * Generated bundle index. Do not edit. */ export { ArrayUtils, CacheInterceptor, FileUtils, MiscUtils, ObjectUtils, ObservedBy, Observing, PGH_CACHE_INTERCEPTOR_OPTIONS, PGH_ERROR_HANDLER_OPTIONS, PGH_MAT_GLOBAL_OPTIONS, PGH_PRODUCT_TITLE, PghArrayJoinModule, PghArrayJoinPipe, PghArraySplitModule, PghArraySplitPipe, PghDarkModeService, PghEnumToArrayModule, PghEnumToArrayPipe, PghErrorHandlerInterceptor, PghErrorHandlerService, PghReplaceWithModule, PghReplaceWithPipe, PghSafeModule, PghSafePipe, PghShortNumberModule, PghShortNumberPipe, PghStorageFactory, PghTabTitleService, PghTrailingSlashInterceptor, StringUtils, UrlUtils, pghDebounceTime, withDestroy }; //# sourceMappingURL=tapsellorg-angular-material-library-src-lib-common.mjs.map