1 import { distinct, distinctUntilChanged, filter, map, share, startWith, throttleTime } from 'rxjs/operators'
2 import { Directive, 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 private static PAGE_VIEW_TOP_MARGIN = 500
11 @Input() containerHeight: number
12 @Input() pageHeight: number
13 @Input() percentLimit = 70
14 @Input() autoInit = false
16 @Output() nearOfBottom = new EventEmitter<void>()
17 @Output() nearOfTop = new EventEmitter<void>()
18 @Output() pageChanged = new EventEmitter<number>()
20 private decimalLimit = 0
21 private lastCurrentBottom = -1
22 private lastCurrentTop = 0
23 private scrollDownSub: Subscription
24 private scrollUpSub: Subscription
25 private pageChangeSub: Subscription
28 this.decimalLimit = this.percentLimit / 100
32 if (this.autoInit === true) return this.initialize()
36 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
37 if (this.scrollUpSub) this.scrollUpSub.unsubscribe()
38 if (this.pageChangeSub) this.pageChangeSub.unsubscribe()
42 // Emit the last value
43 const throttleOptions = { leading: true, trailing: true }
45 const scrollObservable = fromEvent(window, 'scroll')
48 throttleTime(200, undefined, throttleOptions),
49 map(() => ({ current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight })),
50 distinctUntilChanged((o1, o2) => o1.current === o2.current),
55 this.scrollDownSub = scrollObservable
57 // Check we scroll down
58 filter(({ current }) => {
59 const res = this.lastCurrentBottom < current
61 this.lastCurrentBottom = current
64 filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
66 .subscribe(() => this.nearOfBottom.emit())
69 this.scrollUpSub = scrollObservable
72 filter(({ current }) => {
73 const res = this.lastCurrentTop > current
75 this.lastCurrentTop = current
78 filter(({ current, maximumScroll }) => {
79 return current !== 0 && (1 - (current / maximumScroll)) > this.decimalLimit
82 .subscribe(() => this.nearOfTop.emit())
85 this.pageChangeSub = scrollObservable
88 map(({ current }) => this.calculateCurrentPage(current)),
89 distinctUntilChanged()
91 .subscribe(res => this.pageChanged.emit(res))
94 private calculateCurrentPage (current: number) {
95 return Math.max(1, Math.round((current + InfiniteScrollerDirective.PAGE_VIEW_TOP_MARGIN) / this.pageHeight))