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'
6 selector: '[myInfiniteScroller]'
8 export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterViewChecked {
9 @Input() percentLimit = 70
10 @Input() autoInit = false
11 @Input() onItself = false
12 @Input() dataObservable: Observable<any[]>
14 @Output() nearOfBottom = new EventEmitter<void>()
16 private decimalLimit = 0
17 private lastCurrentBottom = -1
18 private scrollDownSub: Subscription
19 private container: HTMLElement
21 private checkScroll = false
23 constructor (private el: ElementRef) {
24 this.decimalLimit = this.percentLimit / 100
27 ngAfterViewChecked () {
28 if (this.checkScroll) {
29 this.checkScroll = false
33 if (this.hasScroll() === false) this.nearOfBottom.emit()
39 if (this.autoInit === true) return this.initialize()
43 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
47 this.container = this.onItself
48 ? this.el.nativeElement
49 : document.documentElement
51 // Emit the last value
52 const throttleOptions = { leading: true, trailing: true }
54 const scrollableElement = this.onItself ? this.container : window
55 const scrollObservable = fromEvent(scrollableElement, 'scroll')
58 throttleTime(200, undefined, throttleOptions),
59 map(() => this.getScrollInfo()),
60 distinctUntilChanged((o1, o2) => o1.current === o2.current),
65 this.scrollDownSub = scrollObservable
67 filter(({ current }) => this.isScrollingDown(current)),
68 filter(({ current, maximumScroll }) => (current / maximumScroll) > this.decimalLimit)
70 .subscribe(() => this.nearOfBottom.emit())
72 if (this.dataObservable) {
74 .pipe(filter(d => d.length !== 0))
75 .subscribe(() => this.checkScroll = true)
79 private getScrollInfo () {
80 return { current: this.container.scrollTop, maximumScroll: this.getMaximumScroll() }
83 private getMaximumScroll () {
84 const elementHeight = this.onItself ? this.container.clientHeight : window.innerHeight
86 return this.container.scrollHeight - elementHeight
89 private hasScroll () {
90 return this.getMaximumScroll() > 0
93 private isScrollingDown (current: number) {
94 const result = this.lastCurrentBottom < current
96 this.lastCurrentBottom = current