import { HttpErrorResponse } from '@angular/common/http'; import { Inject, Injectable, RendererFactory2 } from '@angular/core'; import { IAppConstants } from '../helpers/constants/app-constants.interface'; import { AppConstants } from '../helpers/constants/app.constants'; import { ArticleFilters } from '../helpers/enum/app.enum'; import { NumberParsePipe } from '../helpers/pipes/parse-numeric.pipe'; import { ScriptService } from '../helpers/script/script.helper'; import { ArticleFilterModel } from '../models/article-filter.Model'; import { ArticleModel } from '../models/article.model'; import { FilterDataModel } from '../models/filter-data.model'; import { SummaryDataModel } from '../models/internal/summary-data.model'; import { ArticlePageFilterModel } from '../models/page-filter.model'; import { SearchFilterModel } from '../models/search-filter.model'; import { GlobalDataService } from './global-data.service'; import { GoogleTagManagerService } from './gtm.service'; @Injectable() export class SharedService { public isArticleCountClicked = false; // #region Constructor constructor( public globalData: GlobalDataService, public numberParsePipe: NumberParsePipe, public scriptService: ScriptService, public gtmService: GoogleTagManagerService, public rendererFactory: RendererFactory2, @Inject(AppConstants) private constants: IAppConstants, ) { } // #region Constructor // #region public methods public ManageContentLoader(key: string, isVisible?: boolean): void { isVisible = isVisible || false; this.globalData.IsSearchSpinnerVisible = isVisible; if (this.globalData.Settings.hasOwnProperty(key)) { this.globalData.Settings[key].IsContentLoaderVisible = isVisible; } } public ManageRequest(isRequestProcessing?: boolean): void { isRequestProcessing = isRequestProcessing || false; this.globalData.Settings.IsRequestProcessing = isRequestProcessing; } public SetElementScrollTop(elementId?: string, value?: number): void { value = value || 0; elementId = elementId || 'articles_list'; document.getElementById(elementId).scrollTop = value; } public EnableActions(flag?: boolean): void { flag = flag || false; this.globalData.Settings.IsActionDisabled = !flag; } public RemoveImageContainer(event: any): void { const elementImageContainer = event.currentTarget.closest('.card-a-rt__img-mask'); if (elementImageContainer) { elementImageContainer.classList.add('hidden'); } } public ManageHintIndicators(message?: string, isVisible?: boolean): void { isVisible = isVisible || false; const query = this.globalData.SearchQuery.trim() || ''; message = message || this.constants.MESSAGE_NO_MATCH_FOUND; if (query.length > 0 && query.length < 3) { message = this.constants.MESSAGE_SEARCH_QUERY_WARNING; isVisible = true; } this.globalData.IsHintIndicatorVisible = isVisible; this.globalData.HintMessage = message; } public ManagePageLoader(isVisible?: boolean): void { isVisible = isVisible || false; this.globalData.IsPageLoaderVisible = isVisible; } public ManageSearchData(data?: any): void { const summary = data ? data.Summary : new SummaryDataModel(); const lstFilter = data ? data.Filters : new Array(); const lstArticles = data ? data.Articles : new Array(); this.globalData.Filters = lstFilter.map(x => Object.assign({}, x)); this.globalData.Summary = Object.assign({}, summary); this.globalData.SearchData = Object.assign({}, data); this.globalData.Articles = lstArticles.map(x => Object.assign({}, x)); this.globalData.HasSearchRecords = this.getSearchStatus(); this.globalData.Settings.HasRecords = this.getStatus(); const isFilterEnabled = this.globalData.Settings.HasRecords; this.globalData.Settings.IsFilterEnabled = isFilterEnabled; this.ManageSearchSpinner(); this.ManagePageLoader(); if (isFilterEnabled) { this.SetActivePageFilters(); } else { this.ActivatePageFilters(); } let message = this.constants.DEFAULT_STRING_VALUE; if (!this.globalData.HasSearchRecords) { message = this.constants.MESSAGE_NO_MATCH_FOUND; } if (message.length > 0) { this.ManageHintIndicators(message, true); } this.ScrollToElementTop(); } public ShowModalPageLoader(isVisible?: boolean): void { isVisible = isVisible || false; this.globalData.IsModalPageLoaderVisible = isVisible; } public ManageSearchSpinner(isVisible?: boolean): void { isVisible = isVisible || false; this.globalData.IsSearchSpinnerVisible = isVisible; } public HandleError(message?: string): void { message = message || this.constants.MESSAGE_SEARCH_ERROR; this.ManageSearchSpinner(); this.manageResponseMessage(message, true); } public GetSearchFilters(): SearchFilterModel { return { Search: this.globalData.SearchQuery, Skip: this.globalData.Settings.Pagination.Skip, Top: this.globalData.Settings.Pagination.Top, Filter: this.GetArticleFilters(), ArticleIds: new Array(), PageNumber: this.globalData.QueryPageNumber, DisableFilter: this.globalData.DisableFilter }; } public ManagePagination(): void { const page = 0; const top = this.globalData.Settings.Pagination.Top || 0; const skip = this.globalData.DefaultPageSize * top; this.setPagination(page, skip); } public ScrollToElementTop(top?: number, left?: number): void { top = top || 0; left = left || 0; window.scroll({ top: 0, left: 0, behavior: 'smooth', }); } public GetArticleFilters(pageFilters?: ArticlePageFilterModel): ArticleFilterModel { const articlefilter = new ArticleFilterModel(); pageFilters = pageFilters || this.globalData.Settings.ActiveFilters; for (const key of Object.keys(pageFilters)) { const filter = pageFilters[key]; if (filter) { if (key === this.globalData.FiltersEnum.Type) { articlefilter.ArticleType = filter.Id; } if (key === this.globalData.FiltersEnum.Journals) { articlefilter.JournalId = filter.Id; } if (key === this.globalData.FiltersEnum.Sections) { articlefilter.SectionId = filter.Id; } if (key === this.globalData.FiltersEnum.Date) { articlefilter.Date = filter.Id; } if (key === this.globalData.FiltersEnum.Sort) { articlefilter.Sort = filter.Id; } if (key === this.globalData.FiltersEnum.Domains) { articlefilter.DomainId = filter.Id; } if (key === this.globalData.FiltersEnum.PartOfResearchTopic) { articlefilter.PartOfResearchTopic = filter.Id; } } } return articlefilter; } public ManageError(error: HttpErrorResponse): void { let message = ''; if (error.status === this.constants.API_RESPONSE_STATUS_NOT_FOUND) { message = this.constants.MESSAGE_NO_RESULTS_FOUND; } else { message = this.constants.MESSAGE_SEARCH_ERROR; } if (message.length > 0) { this.ManageHintIndicators(message, true); } else { this.ManageSearchData(); } } public LoadScript(pageId: number, status: any) { if (this.globalData.IsNextTagVisible) { this.scriptService.GenerateScriptTag(pageId + 1, 'next'); } if (pageId > 1) { this.scriptService.GenerateScriptTag(pageId - 1, 'prev'); } if (status === 404 && this.globalData.QueryPageNumber > 0) { this.scriptService.RemoveTag(`rel=next`); } } public LoadAltMetricScript(scriptUrl: string) { return new Promise((resolve, reject) => { const scriptElement = document.createElement('script'); scriptElement.src = scriptUrl; scriptElement.onload = resolve; document.body.appendChild(scriptElement); }); } public GetParsedInput(value: string): number { return this.numberParsePipe.transform(value); } public IsValidSearchTerm(query: string): boolean { return (query.length > 2 || query.length === 0) ? true : false; } public GetParsedBoolean(value: string): boolean { if (value && value.length > 0) { return (/true/i).test(value.toLocaleLowerCase()); } else { return null; } } public IsSearchTermLimitExceeded(): boolean { let isExceeded = false; const query = this.globalData.SearchQuery.trim() || this.constants.DEFAULT_STRING_VALUE; if (query.length > this.constants.SEARCH_CHARACTER_LIMIT) { isExceeded = true; } return isExceeded; } public ManageUrlFilterData(filterData?: ArticlePageFilterModel): void { filterData = filterData || new ArticlePageFilterModel(); this.globalData.ActiveUrlFilters = Object.assign({}, filterData); } public trackUserActionFilterChanged(IsInitialPageLoad?: boolean): void { const aggreatedFilterValues = this.getAggregatedFilterValues(this.globalData.Settings.ActiveFilters); if (IsInitialPageLoad && aggreatedFilterValues === this.constants.FILTER_TOKEN_ANY) { return; } this.gtmService.trackUserAction(this.constants.ARTICLE_FILTER_CHANGED, aggreatedFilterValues); } public trackUserActionSearchTriggered(): void { this.gtmService.trackUserAction(this.constants.ARTICLE_SEARCH_TRIGGERED, this.constants.DEFAULT_STRING_VALUE); } public trackUserActionSearchResultsLoaded(): void { this.gtmService.trackUserAction(this.constants.ARTICLE_SEARCH_LOADED, this.constants.DEFAULT_STRING_VALUE); } public trackUserActionOnScrollDown(): void { this.gtmService.trackUserAction(this.constants.MORE_ARTICLES_LOADED, this.globalData.Articles.length.toString()); } public ToggleLandingPage() { this.globalData.SelectedPageType = this.globalData.ArticlePageType.Articles; } public loadHeader() { if (this.globalData.IsConfigurableHeaderEnabled) { this.loadScriptText(`$(document).ready(function () { header.Render("#ibar-nav"); });`); } else { this.loadScriptText(`$(document).ready(function () { iBar.Render("#ibar-nav"); });`); } } public SetPageSettings(data: any): void { this.globalData.HomePageUrl = data.HomePageUrl; this.globalData.KeyStrokeDelay = data.KeyStrokeDelay || this.constants.KEY_STROKE_DELAY; this.globalData.DefaultPageSize = data.DefaultPageSize || this.constants.SEARCH_DEFAULT_PAGE_SIZE; this.globalData.IntegerMaximumValue = this.constants.INTEGER_MAXIMUM_VALUE - this.globalData.DefaultPageSize; this.globalData.IsConfigurableHeaderEnabled = data.IsConfigurableHeaderEnabled; } // #region Public Methods // #region Private Methods private loadScriptText(scripts: string) { const body = document.body as HTMLBodyElement; const script = document.createElement('script'); script.text = scripts; body.appendChild(script); } private setPagination(page: number, skip: number): void { this.globalData.Settings.Pagination = { Page: page, Skip: skip, Top: this.globalData.DefaultPageSize, }; } private RemoveLink(key: string) { const scriptElement = document.createElement('link'); scriptElement.rel = key; scriptElement.remove(); } private manageResponseMessage(message?: string, isVisible?: boolean) { isVisible = isVisible || !this.globalData.HasSearchRecords; this.globalData.IsHintIndicatorVisible = isVisible; this.ManageHintIndicators(message, isVisible); } private getStatus(): boolean { let hasFilters = false; for (const key of Object.keys(this.globalData.ActiveUrlFilters)) { const item = this.globalData.ActiveUrlFilters[key]; if (item && item.Id > 0) { hasFilters = true; break; } } return hasFilters && this.globalData.Articles.length === 0 ? false : true; } private getSearchStatus(): boolean { let hasRecords = this.globalData.Summary.Count > 0 ? true : false; if (!hasRecords) { for (const key of Object.keys(this.globalData.ActiveUrlFilters)) { const item = this.globalData.ActiveUrlFilters[key]; if (item && item.Id > 0) { hasRecords = true; break; } } } return hasRecords; } private getAggregatedFilterValues(ActiveFilters: ArticlePageFilterModel): string { const aggregatedFilterValues = new Array(); if (this.IsFilterActive(this.globalData.FiltersEnum.Domains)) { const domain = `${ArticleFilters.Domains}=${ActiveFilters.Domains.Name}`; aggregatedFilterValues.push(domain); } if (this.IsFilterActive(this.globalData.FiltersEnum.Journals)) { const journal = `${ArticleFilters.Journals}=${ActiveFilters.Journals.Name}`; aggregatedFilterValues.push(journal); } if (this.IsFilterActive(this.globalData.FiltersEnum.Sections)) { const section = `${ArticleFilters.Sections}=${ActiveFilters.Sections.Name}`; aggregatedFilterValues.push(section); } if (this.IsFilterActive(this.globalData.FiltersEnum.Type)) { const type = `${ArticleFilters.Type}=${ActiveFilters.Type.Name}`; aggregatedFilterValues.push(type); } if (this.IsFilterActive(this.globalData.FiltersEnum.Date)) { const date = `${ArticleFilters.Date}=${ActiveFilters.Date.Name}`; aggregatedFilterValues.push(date); } if (this.IsFilterActive(this.globalData.FiltersEnum.PartOfResearchTopic)) { const partOfResearchTopic = `${this.constants.FILTER_TOKEN_PART_OF_RESEARCH_TOPICS}=${ActiveFilters.PartOfResearchTopic.Name}`; aggregatedFilterValues.push(partOfResearchTopic); } if (this.IsFilterActive(this.globalData.FiltersEnum.Sort)) { const sort = `${ArticleFilters.Sort}=${ActiveFilters.Sort.Name}`; aggregatedFilterValues.push(sort); } // tslint:disable-next-line: max-line-length const aggregatedFilter = aggregatedFilterValues.join(',').length > 0 ? aggregatedFilterValues.join(',') : this.constants.FILTER_TOKEN_ANY; return aggregatedFilter; } private IsFilterActive(key: any): boolean { const filter = this.globalData.Filters.find(x => x.Key === key); const selectedFilter = this.globalData.Settings.ActiveFilters[key]; return (selectedFilter.Id !== filter.DefaultValue) ? true : false; } public GetImageClass(imageId: string): string { let imageClass = this.constants.IMAGE_ORIENTATION_LANDSCAPE; const elementImage = document.getElementById(imageId) as HTMLImageElement; const height = elementImage ? elementImage.naturalHeight : 0; const width = elementImage ? elementImage.naturalWidth : 0; if (height >= width) { imageClass = this.constants.IMAGE_ORIENTATION_PORTRAIT; } return imageClass; } public SetImageClass(event: any): void { const target = event.target || event.srcElement || event.currentTarget; let imageClass = this.constants.IMAGE_ORIENTATION_LANDSCAPE; if (target) { const height = target ? target.naturalHeight : 0; const width = target ? target.naturalWidth : 0; if (height >= width) { imageClass = this.constants.IMAGE_ORIENTATION_PORTRAIT; } target.setAttribute('class', imageClass); } } public SetActivePageFilters(selectedKey?: string, selectedValue?: number): void { this.globalData.Filters.forEach( obj => { const isValid = selectedKey ? selectedKey === obj.Key : true; if (isValid) { obj.Value.forEach(data => { selectedValue = selectedValue || obj.DefaultValue; if (data.Id === selectedValue) { this.globalData.Settings.ActiveFilters[obj.Key] = data; } }); } }); } public ActivatePageFilters(selectedKey?: string, selectedValue?: number): void { this.globalData.Filters.forEach( obj => { const isValid = selectedKey ? selectedKey === obj.Key : true; if (isValid) { obj.Value.forEach(data => { selectedValue = selectedValue || obj.DefaultValue; if (data.Id === selectedValue) { this.globalData.Settings.ActiveFilters[obj.Key] = data; } }); } }); } public ResetDataFilters() { this.globalData.ActiveUrlFilters = new ArticlePageFilterModel(); this.globalData.Articles = new Array(); this.globalData.UrlFilters = new Array(); this.globalData.Filters = new Array(); } // #region public methods }