]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/video/infinite-scroller.directive.ts
Restore videos list components
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / video / infinite-scroller.directive.ts
CommitLineData
db400f44 1import { distinct, distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
bce47964 2import { Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
db400f44 3import { fromEvent, Subscription } from 'rxjs'
0cd4344f
C
4
5@Directive({
6 selector: '[myInfiniteScroller]'
7})
9af61e84 8export class InfiniteScrollerDirective implements OnInit, OnDestroy {
0cd4344f 9 @Input() percentLimit = 70
aa55a4da 10 @Input() autoInit = false
bce47964 11 @Input() onItself = false
0cd4344f
C
12
13 @Output() nearOfBottom = new EventEmitter<void>()
0cd4344f
C
14
15 private decimalLimit = 0
16 private lastCurrentBottom = -1
9af61e84 17 private scrollDownSub: Subscription
bce47964 18 private container: HTMLElement
0cd4344f 19
bce47964 20 constructor (private el: ElementRef) {
0cd4344f
C
21 this.decimalLimit = this.percentLimit / 100
22 }
23
24 ngOnInit () {
aa55a4da 25 if (this.autoInit === true) return this.initialize()
0cd4344f
C
26 }
27
9af61e84
C
28 ngOnDestroy () {
29 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
9af61e84
C
30 }
31
0cd4344f 32 initialize () {
bce47964
C
33 if (this.onItself) {
34 this.container = this.el.nativeElement
35 }
36
6a6d92b1 37 // Emit the last value
2c6bbd97 38 const throttleOptions = { leading: true, trailing: true }
6a6d92b1 39
bce47964 40 const scrollObservable = fromEvent(this.container || window, 'scroll')
db400f44
C
41 .pipe(
42 startWith(null),
43 throttleTime(200, undefined, throttleOptions),
bce47964 44 map(() => this.getScrollInfo()),
db400f44
C
45 distinctUntilChanged((o1, o2) => o1.current === o2.current),
46 share()
47 )
0cd4344f
C
48
49 // Scroll Down
9af61e84 50 this.scrollDownSub = scrollObservable
db400f44
C
51 .pipe(
52 // Check we scroll down
53 filter(({ current }) => {
54 const res = this.lastCurrentBottom < current
0cd4344f 55
db400f44
C
56 this.lastCurrentBottom = current
57 return res
58 }),
59 filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
60 )
0cd4344f 61 .subscribe(() => this.nearOfBottom.emit())
6a6d92b1 62 }
bce47964
C
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 }
0cd4344f 71}