import { Injectable , Inject , OnDestroy } from '@angular/core' ; import { ActivatedRoute , NavigationEnd , NavigationStart , Router } from '@angular/router' ; import { Subscription } from 'rxjs' ; import { filter , map , pairwise } from 'rxjs/operators' ; import { isNonNull } from '../helpers' ; import { MatomoModuleConfiguration , MATOMO_CONFIGURATION } from './matomo-configuration' ; import { MatomoTracker } from './matomo-tracker.service' ; export @ Injectable ( ) export class MatomoRouteTracker implements OnDestroy { /**
     * Previous route url of matomo route tracker.
     */ private previousPageUrl ? : string ; /**
     * Subscription for managing route events.
     */ private subscription ? : Subscription ; param configuration param matomoTracker param router param activatedRoute constructor ( @ Inject ( MATOMO_CONFIGURATION ) private readonly configuration , private readonly matomoTracker , private readonly router , private readonly activatedRoute ) { } /**
     * Starts tracking route changes.
     * Matomo DocumentTitle will be set with `data.motomoTitle` of your routes.
     *
     * This service shall not be used directly within an application.
     */ startTracking ( ) { this . subscription = this . router . events . pipe ( filter ( ( event ) => event instanceof NavigationStart || event instanceof NavigationEnd ) , map ( ( event ) => ( { timestamp : new Date ( ) . getTime ( ) , event } ) ) , pairwise ( ) , filter ( ( [ a , b ] ) => a . event instanceof NavigationStart && b . event instanceof NavigationEnd ) ) . subscribe ( { next : ( [ start , end ] ) => { let currentRoute = this . activatedRoute . root ; while ( currentRoute . children [ 0 ] !== undefined ) { currentRoute = currentRoute . children [ 0 ] ; } if ( this . previousPageUrl ) { this . matomoTracker . setReferrerUrl ( this . previousPageUrl ) ; } if ( ! ! currentRoute . snapshot . data . matomoTitle ) { this . matomoTracker . setDocumentTitle ( currentRoute . snapshot . data . matomoTitle ) ; } this . matomoTracker . setCustomUrl ( window . location . href ) ; this . matomoTracker . deleteCustomVariables ( 'page' ) ; this . matomoTracker . setGenerationTimeMs ( end . timestamp - start . timestamp ) ; this . matomoTracker . trackPageView ( ) ; this . previousPageUrl = window . location . href ; this . configuration ?. routeTracking ?. contentIds ?. map ( document . getElementById ) ?. filter ( isNonNull ) ?. forEach ( ( content ) => { this . matomoTracker . trackContentImpressionsWithinNode ( content ) ; } ) ; if ( this . configuration . trackLinks === true ) { this . matomoTracker . enableLinkTracking ( this . configuration . trackLinkValue ) ; } } , } ) ; } /**
     * Stops tracking route changes.
     */ stopTracking ( ) { this . subscription ?. unsubscribe ( ) ; } /**
     * Angular OnDestroy lifecycle hook.
     */ ngOnDestroy ( ) { if ( ! ! this . subscription ) { this . subscription . unsubscribe ( ) ; } } }