1 import { Directive, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'
2 import 'rxjs/add/operator/debounceTime'
3 import 'rxjs/add/operator/distinct'
4 import 'rxjs/add/operator/distinctUntilChanged'
5 import 'rxjs/add/operator/filter'
6 import 'rxjs/add/operator/map'
7 import 'rxjs/add/operator/share'
8 import 'rxjs/add/operator/startWith'
9 import 'rxjs/add/operator/throttleTime'
10 import { fromEvent } from 'rxjs/observable/fromEvent'
11 import { Subscription } from 'rxjs/Subscription'
14 selector: '[myInfiniteScroller]'
16 export class InfiniteScrollerDirective implements OnInit, OnDestroy {
17 private static PAGE_VIEW_TOP_MARGIN = 500
19 @Input() containerHeight: number
20 @Input() pageHeight: number
21 @Input() percentLimit = 70
22 @Input() autoLoading = false
24 @Output() nearOfBottom = new EventEmitter<void>()
25 @Output() nearOfTop = new EventEmitter<void>()
26 @Output() pageChanged = new EventEmitter<number>()
28 private decimalLimit = 0
29 private lastCurrentBottom = -1
30 private lastCurrentTop = 0
31 private scrollDownSub: Subscription
32 private scrollUpSub: Subscription
33 private pageChangeSub: Subscription
36 this.decimalLimit = this.percentLimit / 100
40 if (this.autoLoading === true) return this.initialize()
44 if (this.scrollDownSub) this.scrollDownSub.unsubscribe()
45 if (this.scrollUpSub) this.scrollUpSub.unsubscribe()
46 if (this.pageChangeSub) this.pageChangeSub.unsubscribe()
50 // Emit the last value
51 const throttleOptions = { leading: true, trailing: true }
53 const scrollObservable = fromEvent(window, 'scroll')
55 .throttleTime(200, undefined, throttleOptions)
56 .map(() => ({ current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }))
57 .distinctUntilChanged((o1, o2) => o1.current === o2.current)
61 this.scrollDownSub = scrollObservable
62 // Check we scroll down
63 .filter(({ current }) => {
64 const res = this.lastCurrentBottom < current
66 this.lastCurrentBottom = current
69 .filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
70 .subscribe(() => this.nearOfBottom.emit())
73 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
84 .subscribe(() => this.nearOfTop.emit())
87 this.pageChangeSub = scrollObservable
89 .map(({ current }) => this.calculateCurrentPage(current))
90 .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))