1 import { distinct, distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
2 import { Directive, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
3 import { fromEvent, Subscription } from 'rxjs'
6 selector: '[myInfiniteScroller]'
8 export class InfiniteScrollerDirective implements OnInit, OnDestroy {
9 @Input() percentLimit = 70
10 @Input() autoInit = false
11 @Input() onItself = false
13 @Output() nearOfBottom = new EventEmitter<void>()
15 private decimalLimit = 0
16 private lastCurrentBottom = -1
17 private scrollDownSub: Subscription
18 private container: HTMLElement
20 constructor (private el: ElementRef) {
21 this.decimalLimit = this.percentLimit / 100
25 if (this.autoInit === true) return this.initialize()
29 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
34 this.container = this.el.nativeElement
37 // Emit the last value
38 const throttleOptions = { leading: true, trailing: true }
40 const scrollObservable = fromEvent(this.container || window, 'scroll')
43 throttleTime(200, undefined, throttleOptions),
44 map(() => this.getScrollInfo()),
45 distinctUntilChanged((o1, o2) => o1.current === o2.current),
50 this.scrollDownSub = scrollObservable
52 // Check we scroll down
53 filter(({ current }) => {
54 const res = this.lastCurrentBottom < current
56 this.lastCurrentBottom = current
59 filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
61 .subscribe(() => this.nearOfBottom.emit())
64 private getScrollInfo () {
66 return { current: this.container.scrollTop, maximumScroll: this.container.scrollHeight }
69 return { current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }