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
16 @Input() parentDisabled = false
18 @Output() nearOfBottom = new EventEmitter<void>()
20 private decimalLimit = 0
21 private lastCurrentBottom = -1
22 private scrollDownSub: Subscription
23 private container: HTMLElement
25 private checkScroll = false
28 private peertubeRouter: PeerTubeRouterService,
29 private el: ElementRef
31 this.decimalLimit = this.percentLimit / 100
34 ngAfterViewChecked () {
35 if (this.checkScroll) {
36 this.checkScroll = false
40 if (this.hasScroll() === false) this.nearOfBottom.emit()
50 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
54 this.container = this.onItself
55 ? this.el.nativeElement
56 : document.documentElement
58 // Emit the last value
59 const throttleOptions = { leading: true, trailing: true }
61 const scrollableElement = this.onItself ? this.container : window
62 const scrollObservable = fromEvent(scrollableElement, 'scroll')
65 throttleTime(200, undefined, throttleOptions),
66 map(() => this.getScrollInfo()),
67 distinctUntilChanged((o1, o2) => o1.current === o2.current),
72 this.scrollDownSub = scrollObservable
74 filter(({ current }) => this.isScrollingDown(current)),
75 filter(({ current, maximumScroll }) => (current / maximumScroll) > this.decimalLimit)
78 if (this.setAngularState && !this.parentDisabled) this.setScrollRouteParams()
80 this.nearOfBottom.emit()
83 if (this.dataObservable) {
85 .pipe(filter(d => d.length !== 0))
86 .subscribe(() => this.checkScroll = true)
90 private getScrollInfo () {
91 return { current: this.container.scrollTop, maximumScroll: this.getMaximumScroll() }
94 private getMaximumScroll () {
95 const elementHeight = this.onItself ? this.container.clientHeight : window.innerHeight
97 return this.container.scrollHeight - elementHeight
100 private hasScroll () {
101 return this.getMaximumScroll() > 0
104 private isScrollingDown (current: number) {
105 const result = this.lastCurrentBottom < current
107 this.lastCurrentBottom = current
111 private setScrollRouteParams () {
112 this.peertubeRouter.addRouteSetting(RouterSetting.REUSE_COMPONENT)