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
14 @Input() container = document.body
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
26 private middleScreen: number
29 this.decimalLimit = this.percentLimit / 100
33 if (this.autoInit === true) return this.initialize()
37 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
38 if (this.scrollUpSub) this.scrollUpSub.unsubscribe()
39 if (this.pageChangeSub) this.pageChangeSub.unsubscribe()
43 this.middleScreen = window.innerHeight / 2
45 // Emit the last value
46 const throttleOptions = { leading: true, trailing: true }
48 const scrollObservable = fromEvent(window, 'scroll')
51 throttleTime(200, undefined, throttleOptions),
52 map(() => ({ current: window.scrollY, maximumScroll: this.container.clientHeight - window.innerHeight })),
53 distinctUntilChanged((o1, o2) => o1.current === o2.current),
58 this.scrollDownSub = scrollObservable
60 // Check we scroll down
61 filter(({ current }) => {
62 const res = this.lastCurrentBottom < current
64 this.lastCurrentBottom = current
67 filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
69 .subscribe(() => this.nearOfBottom.emit())
72 this.scrollUpSub = scrollObservable
75 filter(({ current }) => {
76 const res = this.lastCurrentTop > current
78 this.lastCurrentTop = current
81 filter(({ current, maximumScroll }) => {
82 return current !== 0 && (1 - (current / maximumScroll)) > this.decimalLimit
85 .subscribe(() => this.nearOfTop.emit())
88 this.pageChangeSub = scrollObservable
91 map(({ current }) => this.calculateCurrentPage(current)),
92 distinctUntilChanged()
94 .subscribe(res => this.pageChanged.emit(res))
97 private calculateCurrentPage (current: number) {
98 const scrollY = current + this.middleScreen
100 const page = Math.max(1, Math.ceil(scrollY / this.pageHeight))
103 return page + (this.firstLoadedPage - 1)