import { Location } from '@angular/common'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Component, Inject, Input, OnChanges, OnInit, SimpleChanges, ViewEncapsulation } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { ActivatedRoute, convertToParamMap, NavigationEnd, Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { ArticleDiscoveryService } from './article-discovery.service'; import { IAppConstants } from './helpers/constants/app-constants.interface'; import { AppConstants } from './helpers/constants/app.constants'; import { NumberParsePipe } from './helpers/pipes/parse-numeric.pipe'; import { TokenReplacePipe } from './helpers/pipes/token-replace.pipe'; import { ScriptService } from './helpers/script/script.helper'; import { QueryParamsModel } from './models/query-params.model'; import { SearchFilterModel } from './models/search-filter.model'; import { UrlSearchFilter } from './models/url-search-filter.model'; import { BaseService } from './services/base.service'; import { GlobalDataService } from './services/global-data.service'; import { GoogleTagManagerService } from './services/gtm.service'; import { SharedService } from './services/shared.service'; @Component({ selector: 'lib-article-discovery', templateUrl: './article-discovery.component.html', styleUrls: ['./article-discovery.component.css'], encapsulation: ViewEncapsulation.None }) export class ArticleDiscoveryComponent implements OnInit, OnChanges { @Input() baseUrl: string; @Input() disableFilter: string[]; // #region Private Fields private isSearchProcessing = false; private inValidInputParam: string = this.constants.DEFAULT_STRING_VALUE; private searchSubscription: Subscription; private queryParams: QueryParamsModel; private isValidRequest = true; // #region Private Fields // #region Constructor public constructor( public router: Router, public location: Location, public titleService: Title, public route: ActivatedRoute, public baseService: BaseService, public tokenPipe: TokenReplacePipe, public sharedService: SharedService, public scriptService: ScriptService, public globalData: GlobalDataService, public numberParsePipe: NumberParsePipe, public gtmService: GoogleTagManagerService, public articleService: ArticleDiscoveryService, @Inject(AppConstants) private constants: IAppConstants ) { this.queryParams = new QueryParamsModel(); router.events.forEach(event => { if (event instanceof NavigationEnd) { this.manageRouterNavigation(event); } }); this.scriptService.RemoveMetaTag( `name=${this.constants.ELEMENT_ATTRIBUTE_META_DESCRIPTION}` ); } ngOnInit(): void { this.titleService.setTitle(this.constants.ARTICLE_PAGE_TITLE); } ngOnChanges(changes: SimpleChanges) { if (changes.baseUrl && changes.baseUrl.currentValue && changes.disableFilter && changes.disableFilter.currentValue) { this.baseUrl = changes.baseUrl.currentValue; this.globalData.BaseUrl = this.baseUrl; this.disableFilter = changes.disableFilter.currentValue; this.globalData.DisableFilter = this.disableFilter; this.getSearchSettings(); this.getMetadata(); } } public onScrollDown(): void { if ( this.globalData.QueryPageNumber > 0 || this.queryParams.ArticleIds.length > 0 ) { return; } if (!this.isSearchProcessing) { const page = this.globalData.Settings.Pagination.Page + 1; const pageSkip = this.globalData.DefaultPageSize * page; if (this.globalData.Summary.Count > pageSkip) { this.globalData.Settings.Pagination.Page = page; this.globalData.Settings.Pagination.Skip = pageSkip; this.managePageDefaults(true); this.getSearchResult(true); } } } public ArticleHandler(event?: any): void { const isSearchTermUpdate = (event && event.isSearchTermUpdate) || false; const isReplaceHistory = (event && event.isReplaceHistory) || false; this.globalData.PageNumber = 0; this.globalData.QueryPageNumber = 0; this.queryParams = new QueryParamsModel(); this.queryParams.Query = this.globalData.SearchQuery.trim(); this.updateUrlParams(isSearchTermUpdate, isReplaceHistory); } public manageRequest(): void { let hasFilters = true; let hasQueryFilters = false; let pageNumber = 0; this.isValidRequest = true; this.queryParams = new QueryParamsModel(); this.globalData.IsPageInitialization = true; this.sharedService.ManagePageLoader(true); this.sharedService.ManageSearchSpinner(true); this.route.queryParams.subscribe(params => { const map = convertToParamMap(params); if (map.keys.length > 0) { let articleIds: string = this.constants.DEFAULT_STRING_VALUE; const lstFilter = this.baseService.GetFilteredQueryParams( params[this.constants.QUERY_PARAMETER_ARTICLE_IDS], true ); for (const value of lstFilter) { if (value.length > 0) { articleIds = articleIds.length > 0 ? `${articleIds},${value}` : `${value}`; } } this.queryParams.Page = this.baseService.GetFilteredQueryParams( params[this.constants.QUERY_PARAMETER_PAGE] ); this.queryParams.ArticleIds = this.getArticleFilters(articleIds); if (articleIds.length > 0) { hasFilters = false; this.processValidRequest(); } else if (this.queryParams.Page.length > 0) { hasFilters = false; pageNumber = this.sharedService.GetParsedInput(this.queryParams.Page); if ( pageNumber === 0 || pageNumber > this.constants.INTEGER_MAXIMUM_VALUE ) { this.isValidRequest = false; // tslint:disable-next-line: max-line-length this.inValidInputParam = this.tokenPipe.transform( this.constants.MESSAGE_INVALID_PAGE_NUMBER, this.constants.TOKEN_PAGE_NUMBER, this.queryParams.Page.trim() ); } else { this.globalData.PageNumber = pageNumber; } this.processValidRequest(); } else { hasQueryFilters = true; this.queryParams = this.baseService.ManageFilterParams( params, this.queryParams ); } } }); if (hasFilters) { this.manageQueryParams(hasQueryFilters, pageNumber); } } public getSearchSettings(): void { this.articleService.getPageSettings().subscribe( (response: HttpResponse) => { if (response.ok) { const data = response.body; if (data) { this.sharedService.SetPageSettings(data); this.sharedService.loadHeader(); if (!data.IsSEOCrawlersAllowed) { this.generateMetaTag( this.constants.ELEMENT_ATTRIBUTE_META_ROBOTS, this.constants.META_DATA_CONTENT ); } } this.manageRequest(); } }, (error: HttpErrorResponse) => { this.globalData.IsInitialization = false; this.globalData.IsPageInitialization = false; this.sharedService.ManagePageLoader(); this.sharedService.HandleError(); } ); } public getSearchResult(isPageScroll?: boolean): void { isPageScroll = isPageScroll || false; this.isValidRequest = true; this.cancelSearchRequest(); const filters = this.generateSearchFilters(isPageScroll); if (this.isValidRequest) { this.searchSubscription = this.articleService .getSearch(filters) .subscribe( (response: HttpResponse) => { if (response.ok) { const data = response.body; if (isPageScroll) { if (data && data.Articles) { const lstArticles = this.globalData.Articles.map((x: any) => Object.assign({}, x) ); // tslint:disable-next-line: only-arrow-functions data.Articles.forEach(function(item: any) { lstArticles.push(item); }); this.globalData.Articles = []; this.globalData.Articles = lstArticles.map((x: any) => Object.assign({}, x) ); this.sharedService.trackUserActionOnScrollDown(); } } else { this.sharedService.ManagePagination(); this.sharedService.ManageSearchData(response.body); if (this.globalData.Summary.Count > 0) { this.sharedService.trackUserActionSearchResultsLoaded(); } if (this.globalData.Settings.HasRecords) { setTimeout(() => { this.setActivePageFilters(), this.updateUrlParams(); }, 300); setTimeout(() => { this.globalData.IsInitialization = false; }, 400); } this.sharedService.LoadScript( this.globalData.QueryPageNumber > 0 ? this.globalData.QueryPageNumber : 1, response.body ); } this.sharedService.LoadAltMetricScript( 'https://d1bxh8uas1mnw7.cloudfront.net/assets/embed.js' ); this.managePageDefaults(); this.getArticleSchema(); } }, (error: HttpErrorResponse) => { let message = this.constants.DEFAULT_STRING_VALUE; if (error.status === this.constants.API_RESPONSE_STATUS_NOT_FOUND) { this.sharedService.LoadScript( this.globalData.QueryPageNumber > 0 ? this.globalData.QueryPageNumber : 1, error.status ); if (this.globalData.QueryPageNumber > 0) { message = this.constants.MESSAGE_NO_MATCH_FOUND; } else { message = this.constants.MESSAGE_NO_RESULTS_FOUND; } } else { message = this.constants.MESSAGE_SEARCH_ERROR; } if (message.length > 0) { this.sharedService.ManageHintIndicators(message, true); } else { this.sharedService.ManageSearchData(); } this.managePageDefaults(); this.globalData.IsInitialization = false; } ); if (!isPageScroll && this.globalData.SearchQuery.trim().length > 2) { this.sharedService.trackUserActionSearchTriggered(); } } else { this.resetPageDefaults(); } } public getPageFilters(): void { const filter: UrlSearchFilter = this.baseService.GetUrlPageFilterParams( this.queryParams ); this.articleService.getPageFilters(filter).subscribe( (response: HttpResponse) => { if (response.ok) { const data = response.body; if (data) { this.globalData.UrlFilters = data.map((x: any) => Object.assign({}, x) ); } this.validateRequest(); } }, (error: HttpErrorResponse) => { this.globalData.IsPageInitialization = false; this.globalData.IsInitialization = false; this.sharedService.HandleError(); this.managePageDefaults(); } ); } public getMetadata(): void { this.articleService.getMetadata().subscribe( (response: HttpResponse) => { if (response.ok) { const data = response.body; if (data) { this.generateMetaTag( this.constants.ELEMENT_ATTRIBUTE_META_TITLE, data.Title ); this.generateMetaTag( this.constants.ELEMENT_ATTRIBUTE_META_DESCRIPTION, data.Description ); this.generateMetaTag( this.constants.ELEMENT_ATTRIBUTE_META_KEYWORDS, data.Keywords ); } } }, (error: HttpErrorResponse) => { this.globalData.IsPageInitialization = false; } ); } // #endregion Public Methods // #region Private Methods private getArticleSchema(): void { this.articleService .getArticleSchema(this.generateSearchFilters()) .subscribe( (response: HttpResponse) => { if (response.ok) { const data = response.body; this.generateSchema(data); } }, (error: HttpErrorResponse) => { this.globalData.IsPageInitialization = false; } ); } private generateSchemaFilters(): SearchFilterModel { const filter = new SearchFilterModel(); filter.Skip = this.getPageSkip(); filter.Top = this.constants.SEARCH_DEFAULT_PAGE_SIZE; filter.Search = this.constants.DEFAULT_STRING_VALUE; filter.ArticleIds = new Array(); filter.Filter = this.globalData.Filters; return filter; } private generateSchema(jsnSchemaData?: any): void { if (jsnSchemaData) { const head = document.head; const script = document.createElement('script'); script.type = this.constants.ELEMENT_ATTRIBUTE_TYPE; script.text = JSON.stringify(jsnSchemaData, null, 4); head.appendChild(script); } } private generateSearchFilters(isPageScroll?: boolean): SearchFilterModel { isPageScroll = isPageScroll || false; const filter = new SearchFilterModel(); // tslint:disable-next-line: max-line-length const filterData = this.globalData.IsPageInitialization ? this.sharedService.GetArticleFilters( this.baseService.GetPageUrlFilters(this.queryParams) ) : this.sharedService.GetArticleFilters(); filter.Skip = isPageScroll ? this.globalData.Settings.Pagination.Skip : this.getPageSkip(); filter.Top = this.globalData.DefaultPageSize; filter.Search = this.globalData.SearchQuery.trim(); filter.Filter = Object.assign({}, filterData); filter.PageNumber = this.globalData.QueryPageNumber; filter.ArticleIds = this.queryParams.ArticleIds; filter.DisableFilter = this.globalData.DisableFilter; return filter; } private getPageSkip(): number { const page = this.globalData.PageNumber || this.constants.DEFAULT_NUMBER_VALUE; const index = page > this.constants.DEFAULT_NUMBER_VALUE ? page - 1 : this.constants.DEFAULT_NUMBER_VALUE; const skip = index * this.globalData.DefaultPageSize; return skip <= this.globalData.IntegerMaximumValue ? skip : this.globalData.IntegerMaximumValue; } private resetPageDefaults(): void { if (this.inValidInputParam.length > 0) { setTimeout(() => this.sharedService.HandleError(this.inValidInputParam)); } this.sharedService.ManagePageLoader(); this.globalData.IsPageInitialization = false; } private managePageDefaults(flag?: boolean): void { flag = flag || false; this.showLoader(flag); this.isSearchProcessing = flag; this.sharedService.ManageSearchSpinner(flag); this.globalData.IsPageInitialization = false; this.sharedService.ManagePageLoader(); } private showLoader(flag: boolean): void { flag = flag || false; this.globalData.Settings.IsContentLoaderVisible = flag; } private cancelSearchRequest(): void { if (this.searchSubscription) { this.searchSubscription.unsubscribe(); this.searchSubscription = null; } } private isValidRequestParams(): boolean { return this.inValidInputParam.length > 0 ? false : true; } private updateUrlParams( isSearchTermUpdate?: boolean, isReplaceHistory?: boolean ): void { isSearchTermUpdate = isSearchTermUpdate || false; const siteUrl = this.baseService.GetUpdatedUrl(this.queryParams); if (isReplaceHistory && this.location.path() !== siteUrl) { this.globalData.UrlAfterRedirection = siteUrl; this.location.replaceState(siteUrl); return; } if (isSearchTermUpdate) { this.globalData.UrlAfterRedirection = siteUrl; this.location.replaceState(siteUrl); } else { if ( this.location.path() !== siteUrl || this.globalData.UrlAfterRedirection !== siteUrl ) { this.globalData.UrlAfterRedirection = siteUrl; const articleBaseUrl = `/${this.constants.ARTICLES_ROUTE_PREFIX}`; if (this.location.path() !== articleBaseUrl) { this.router.navigateByUrl(siteUrl); } else { this.location.replaceState(siteUrl); } } } } private getArticleFilters(articleIds?: string): Array { let message: string = this.constants.DEFAULT_STRING_VALUE; const lstarticleFilter = new Array(); if (articleIds && articleIds.length > 0) { const lstFilter = articleIds.split(this.constants.TOKEN_COMMA); for (const value of lstFilter) { const articleId = this.sharedService.GetParsedInput(value); if ( articleId > 0 && articleId <= this.constants.INTEGER_MAXIMUM_VALUE ) { lstarticleFilter.push(articleId); } else { message = message.length > 0 ? `${message}, ${value}` : `${value} `; } } this.isValidRequest = lstarticleFilter.length > 0 ? true : false; if (!this.isValidRequest && message.length > 0) { // tslint:disable-next-line: max-line-length this.inValidInputParam = this.tokenPipe.transform( this.constants.MESSAGE_INVALID_ARTICLE_IDS, this.constants.TOKEN_ARTICLE_ID, message.trim() ); } } return lstarticleFilter.length > 0 ? Array.from(new Set(lstarticleFilter)) : []; } private processValidRequest(): void { if (this.isValidRequestParams()) { this.updateUrlParams(true); this.getSearchResult(); } else { this.resetPageDefaults(); } } private manageQueryParams( hasQueryFilters: boolean, pageNumber?: number ): void { this.globalData.PageNumber = pageNumber || this.globalData.PageNumber; if ( !this.sharedService.IsSearchTermLimitExceeded() && this.sharedService.IsValidSearchTerm(this.queryParams.Query) ) { this.globalData.SearchQuery = this.queryParams.Query; this.globalData.SearchTerm = this.queryParams.Query; } if (hasQueryFilters) { this.getPageFilters(); } else { this.getSearchResult(); } } private validateRequest(): void { const filterData = this.baseService.GetPageUrlFilters(this.queryParams); this.sharedService.ManageUrlFilterData(filterData); this.getSearchResult(); } private manageRouterNavigation(event?: any) { if (!this.globalData.IsInitialization) { if (!this.globalData.IsPageFilterUpdated) { const pageUrl = decodeURIComponent(event.url); if ( this.globalData.UrlAfterRedirection.length > 0 && this.globalData.UrlAfterRedirection.toLowerCase() !== pageUrl.toLowerCase() ) { this.manageRequest(); } } this.globalData.IsPageFilterUpdated = false; } } private setActivePageFilters() { for (const key of Object.keys(this.globalData.ActiveUrlFilters)) { const item = this.globalData.ActiveUrlFilters[key]; const filter = this.globalData.Filters.find( (x: { Key: string }) => x.Key === key ); if (item && item.Id !== filter.DefaultValue) { this.sharedService.SetActivePageFilters(key, item.Id); } } this.sharedService.trackUserActionFilterChanged(true); } private generateMetaTag(metTag: string, content: string): void { const metaTitle = document.createElement('meta'); metaTitle.name = metTag; metaTitle.content = content; document.head.appendChild(metaTitle); } }