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 @Input() containerHeight: number
10 @Input() pageHeight: number
11 @Input() firstLoadedPage = 1
12 @Input() percentLimit = 70
13 @Input() autoInit = false
15 @Output() nearOfBottom = new EventEmitter<void>()
16 @Output() nearOfTop = new EventEmitter<void>()
17 @Output() pageChanged = new EventEmitter<number>()
19 private decimalLimit = 0
20 private lastCurrentBottom = -1
21 private lastCurrentTop = 0
22 private scrollDownSub: Subscription
23 private scrollUpSub: Subscription
24 private pageChangeSub: Subscription
25 private middleScreen: number
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 this.middleScreen = window.innerHeight / 2
44 // Emit the last value
45 const throttleOptions = { leading: true, trailing: true }
47 const scrollObservable = fromEvent(window, 'scroll')
50 throttleTime(200, undefined, throttleOptions),
51 map(() => ({ current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight })),
52 distinctUntilChanged((o1, o2) => o1.current === o2.current),
57 this.scrollDownSub = scrollObservable
59 // Check we scroll down
60 filter(({ current }) => {
61 const res = this.lastCurrentBottom < current
63 this.lastCurrentBottom = current
66 filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
68 .subscribe(() => this.nearOfBottom.emit())
71 this.scrollUpSub = scrollObservable
74 filter(({ current }) => {
75 const res = this.lastCurrentTop > current
77 this.lastCurrentTop = current
80 filter(({ current, maximumScroll }) => {
81 return current !== 0 && (1 - (current / maximumScroll)) > this.decimalLimit
84 .subscribe(() => this.nearOfTop.emit())
87 this.pageChangeSub = scrollObservable
90 map(({ current }) => this.calculateCurrentPage(current)),
91 distinctUntilChanged()
93 .subscribe(res => this.pageChanged.emit(res))
96 private calculateCurrentPage (current: number) {
97 const scrollY = current + this.middleScreen
99 const page = Math.max(1, Math.ceil(scrollY / this.pageHeight))
102 return page + (this.firstLoadedPage - 1)