import { isPlatformServer } from '@angular/common' ; import { Component , ElementRef , Inject , Input , PLATFORM_ID , ViewChild , } from '@angular/core' ; import { BehaviorSubject , interval , Observable } from 'rxjs' ; import { distinctUntilChanged , last , map , startWith , switchMap , } from 'rxjs/operators' ; import { FriendlyDateDiffPipe } from '../../../../../common/pipes/friendlydatediff' ; import { ActivityEntity } from '../../activity.service' ; /**
 * Shows relative time ago in a span element e.g. 30s ago
 * Time will only update when the host is on screen.
 */ @ Component ( { selector : 'm-relativeTimeSpan' , template : `
    <span
      class="m-relativeTime__span"
      [title]="entity.time_created * 1000 | date: 'medium'"
      #relativeTimeSpan
      *mIfBrowser
    >
      {{ pauseableRelativeTimeAgo$ | async }}
    </span>
  ` , providers : [ FriendlyDateDiffPipe ] , } ) export class ActivityRelativeTimeSpanComponent { @ Input ( 'entity' ) entity : ActivityEntity ; @ ViewChild ( 'relativeTimeSpan' ) relativeTimeSpan : ElementRef ; /**
     * Relative time ago - e.g. 42 seconds ago.
     * Emits every second.
     */ private relativeTimeAgo$ : Observable < string > = interval ( 1000 ) . pipe ( startWith ( 0 ) , map ( ( ) => this . datePipe . transform ( this . entity . time_created , '' , false ) ) , distinctUntilChanged ( ) ) ; public pauseableRelativeTimeAgo$ : Observable < any > = this . relativeTimeAgo$ ; private readonly isIntersecting$ : BehaviorSubject < boolean > = new BehaviorSubject < boolean > ( false ) ; private interceptionObserver : IntersectionObserver ; constructor ( public datePipe , @ Inject ( PLATFORM_ID ) protected platformId ) { } ngAfterViewInit ( ) { try { this . setupInterceptionObserver ( ) ; this . setupPauseableRelativeTime ( ) ; } catch ( e ) { } } returns { void } setupPauseableRelativeTime ( ) { this . pauseableRelativeTimeAgo$ = this . isIntersecting$ . pipe ( switchMap ( value => ! value ? this . relativeTimeAgo$ . pipe ( last ( ) ) : this . relativeTimeAgo$ ) ) ; } returns { void } setupInterceptionObserver ( ) { if ( isPlatformServer ( this . platformId ) ) { return ; } let options = { root : null , rootMargin : '0px' , threshold : 1.0 , } ; this . interceptionObserver = new IntersectionObserver ( ( entries , observer ) => { entries . forEach ( entry => { this . isIntersecting$ . next ( entry . isIntersecting ) ; } ) ; } , options ) ; this . interceptionObserver . observe ( this . relativeTimeSpan . nativeElement ) ; } ngOnDestroy ( ) { if ( this . interceptionObserver ) { this . interceptionObserver . disconnect ( ) ; } } }