aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/shared/video/infinite-scroller.directive.ts
blob: 5f8a1dd6e49606ec65294f8b4ad9b22a02db8a0a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { distinct, distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
import { Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
import { fromEvent, Subscription } from 'rxjs'

@Directive({
  selector: '[myInfiniteScroller]'
})
export class InfiniteScrollerDirective implements OnInit, OnDestroy {
  @Input() percentLimit = 70
  @Input() autoInit = false
  @Input() onItself = false

  @Output() nearOfBottom = new EventEmitter<void>()

  private decimalLimit = 0
  private lastCurrentBottom = -1
  private scrollDownSub: Subscription
  private container: HTMLElement

  constructor (private el: ElementRef) {
    this.decimalLimit = this.percentLimit / 100
  }

  ngOnInit () {
    if (this.autoInit === true) return this.initialize()
  }

  ngOnDestroy () {
    if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
  }

  initialize () {
    if (this.onItself) {
      this.container = this.el.nativeElement
    }

    // Emit the last value
    const throttleOptions = { leading: true, trailing: true }

    const scrollObservable = fromEvent(this.container || window, 'scroll')
      .pipe(
        startWith(null),
        throttleTime(200, undefined, throttleOptions),
        map(() => this.getScrollInfo()),
        distinctUntilChanged((o1, o2) => o1.current === o2.current),
        share()
      )

    // Scroll Down
    this.scrollDownSub = scrollObservable
      .pipe(
        // Check we scroll down
        filter(({ current }) => {
          const res = this.lastCurrentBottom < current

          this.lastCurrentBottom = current
          return res
        }),
        filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
      )
      .subscribe(() => this.nearOfBottom.emit())
  }

  private getScrollInfo () {
    if (this.container) {
      return { current: this.container.scrollTop, maximumScroll: this.container.scrollHeight }
    }

    return { current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }
  }
}