1 import { fromEvent, Observable, Subscription } from 'rxjs'
2 import { distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
3 import { AfterViewChecked, Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
4 import { PeerTubeRouterService, RouterSetting } from '@app/core'
7 selector: '[myInfiniteScroller]'
9 export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewChecked {
10 @Input() percentLimit = 70
11 @Input() onItself = false
12 @Input() dataObservable: Observable<any[]>
14 // Add angular state in query params to reuse the routed component
15 @Input() setAngularState: boolean
17 @Output() nearOfBottom = new EventEmitter<void>()
19 private decimalLimit = 0
20 private lastCurrentBottom = -1
21 private scrollDownSub: Subscription
22 private container: HTMLElement
24 private checkScroll = false
27 private peertubeRouter: PeerTubeRouterService,
28 private el: ElementRef
30 this.decimalLimit = this.percentLimit / 100
33 ngAfterViewChecked () {
34 if (this.checkScroll) {
35 this.checkScroll = false
39 if (this.hasScroll() === false) this.nearOfBottom.emit()
49 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
53 this.container = this.onItself
54 ? this.el.nativeElement
55 : document.documentElement
57 // Emit the last value
58 const throttleOptions = { leading: true, trailing: true }
60 const scrollableElement = this.onItself ? this.container : window
61 const scrollObservable = fromEvent(scrollableElement, 'scroll')
64 throttleTime(200, undefined, throttleOptions),
65 map(() => this.getScrollInfo()),
66 distinctUntilChanged((o1, o2) => o1.current === o2.current),
71 this.scrollDownSub = scrollObservable
73 filter(({ current }) => this.isScrollingDown(current)),
74 filter(({ current, maximumScroll }) => (current / maximumScroll) > this.decimalLimit)
77 if (this.setAngularState) this.setScrollRouteParams()
79 this.nearOfBottom.emit()
82 if (this.dataObservable) {
84 .pipe(filter(d => d.length !== 0))
85 .subscribe(() => this.checkScroll = true)
89 private getScrollInfo () {
90 return { current: this.container.scrollTop, maximumScroll: this.getMaximumScroll() }
93 private getMaximumScroll () {
94 const elementHeight = this.onItself ? this.container.clientHeight : window.innerHeight
96 return this.container.scrollHeight - elementHeight
99 private hasScroll () {
100 return this.getMaximumScroll() > 0
103 private isScrollingDown (current: number) {
104 const result = this.lastCurrentBottom < current
106 this.lastCurrentBottom = current
110 private setScrollRouteParams () {
111 this.peertubeRouter.addRouteSetting(RouterSetting.REUSE_COMPONENT)