1 import { distinctUntilChanged, filter, map, share, startWith, tap, throttleTime } from 'rxjs/operators'
2 import { AfterContentChecked, Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
3 import { fromEvent, Observable, Subscription } from 'rxjs'
6 selector: '[myInfiniteScroller]'
8 export class InfiniteScrollerDirective implements OnInit, OnDestroy, AfterContentChecked {
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 ngAfterContentChecked () {
28 if (this.checkScroll) {
29 this.checkScroll = false
31 console.log('Checking if the initial state has a scroll.')
33 if (this.hasScroll() === false) this.nearOfBottom.emit()
38 if (this.autoInit === true) return this.initialize()
42 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
46 this.container = this.onItself
47 ? this.el.nativeElement
48 : document.documentElement
50 // Emit the last value
51 const throttleOptions = { leading: true, trailing: true }
53 const scrollableElement = this.onItself ? this.container : window
54 const scrollObservable = fromEvent(scrollableElement, 'scroll')
56 startWith(null as string), // FIXME: typings
57 throttleTime(200, undefined, throttleOptions),
58 map(() => this.getScrollInfo()),
59 distinctUntilChanged((o1, o2) => o1.current === o2.current),
64 this.scrollDownSub = scrollObservable
66 filter(({ current }) => this.isScrollingDown(current)),
67 filter(({ current, maximumScroll }) => (current / maximumScroll) > this.decimalLimit)
69 .subscribe(() => this.nearOfBottom.emit())
71 if (this.dataObservable) {
73 .pipe(filter(d => d.length !== 0))
74 .subscribe(() => this.checkScroll = true)
78 private getScrollInfo () {
79 return { current: this.container.scrollTop, maximumScroll: this.getMaximumScroll() }
82 private getMaximumScroll () {
83 return this.container.scrollHeight - window.innerHeight
86 private hasScroll () {
87 return this.getMaximumScroll() > 0
90 private isScrollingDown (current: number) {
91 const result = this.lastCurrentBottom < current
93 this.lastCurrentBottom = current