Fix express validator
[oweals/peertube.git] / client / src / app / shared / video / infinite-scroller.directive.ts
1 import { distinct, distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
2 import { Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
3 import { fromEvent, Subscription } from 'rxjs'
4
5 @Directive({
6   selector: '[myInfiniteScroller]'
7 })
8 export class InfiniteScrollerDirective implements OnInit, OnDestroy {
9   @Input() percentLimit = 70
10   @Input() autoInit = false
11   @Input() onItself = false
12
13   @Output() nearOfBottom = new EventEmitter<void>()
14
15   private decimalLimit = 0
16   private lastCurrentBottom = -1
17   private scrollDownSub: Subscription
18   private container: HTMLElement
19
20   constructor (private el: ElementRef) {
21     this.decimalLimit = this.percentLimit / 100
22   }
23
24   ngOnInit () {
25     if (this.autoInit === true) return this.initialize()
26   }
27
28   ngOnDestroy () {
29     if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
30   }
31
32   initialize () {
33     if (this.onItself) {
34       this.container = this.el.nativeElement
35     }
36
37     // Emit the last value
38     const throttleOptions = { leading: true, trailing: true }
39
40     const scrollObservable = fromEvent(this.container || window, 'scroll')
41       .pipe(
42         startWith(null as string), // FIXME: typings
43         throttleTime(200, undefined, throttleOptions),
44         map(() => this.getScrollInfo()),
45         distinctUntilChanged((o1, o2) => o1.current === o2.current),
46         share()
47       )
48
49     // Scroll Down
50     this.scrollDownSub = scrollObservable
51       .pipe(
52         // Check we scroll down
53         filter(({ current }) => {
54           const res = this.lastCurrentBottom < current
55
56           this.lastCurrentBottom = current
57           return res
58         }),
59         filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
60       )
61       .subscribe(() => this.nearOfBottom.emit())
62   }
63
64   private getScrollInfo () {
65     if (this.container) {
66       return { current: this.container.scrollTop, maximumScroll: this.container.scrollHeight }
67     }
68
69     return { current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }
70   }
71 }