]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/video/infinite-scroller.directive.ts
Throttle infinite scroller
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / video / infinite-scroller.directive.ts
CommitLineData
0cd4344f 1import { Directive, EventEmitter, Input, OnInit, Output } from '@angular/core'
8cac1b64 2import 'rxjs/add/operator/debounceTime'
0cd4344f 3import 'rxjs/add/operator/distinct'
3bcfff7f 4import 'rxjs/add/operator/distinctUntilChanged'
8cac1b64
C
5import 'rxjs/add/operator/filter'
6import 'rxjs/add/operator/map'
0cd4344f 7import 'rxjs/add/operator/startWith'
a9ca764e 8import 'rxjs/add/operator/throttleTime'
0cd4344f
C
9import { fromEvent } from 'rxjs/observable/fromEvent'
10
11@Directive({
12 selector: '[myInfiniteScroller]'
13})
14export class InfiniteScrollerDirective implements OnInit {
15 private static PAGE_VIEW_TOP_MARGIN = 500
16
17 @Input() containerHeight: number
18 @Input() pageHeight: number
19 @Input() percentLimit = 70
20 @Input() autoLoading = false
21
22 @Output() nearOfBottom = new EventEmitter<void>()
23 @Output() nearOfTop = new EventEmitter<void>()
24 @Output() pageChanged = new EventEmitter<number>()
25
26 private decimalLimit = 0
27 private lastCurrentBottom = -1
28 private lastCurrentTop = 0
29
30 constructor () {
31 this.decimalLimit = this.percentLimit / 100
32 }
33
34 ngOnInit () {
35 if (this.autoLoading === true) return this.initialize()
36 }
37
38 initialize () {
39 const scrollObservable = fromEvent(window, 'scroll')
40 .startWith(true)
a9ca764e 41 .throttleTime(200)
0cd4344f
C
42 .map(() => ({ current: window.scrollY, maximumScroll: document.body.clientHeight - window.innerHeight }))
43
44 // Scroll Down
45 scrollObservable
46 // Check we scroll down
47 .filter(({ current }) => {
48 const res = this.lastCurrentBottom < current
49
50 this.lastCurrentBottom = current
51 return res
52 })
53 .filter(({ current, maximumScroll }) => maximumScroll <= 0 || (current / maximumScroll) > this.decimalLimit)
0cd4344f
C
54 .distinct()
55 .subscribe(() => this.nearOfBottom.emit())
56
57 // Scroll up
58 scrollObservable
59 // Check we scroll up
60 .filter(({ current }) => {
61 const res = this.lastCurrentTop > current
62
63 this.lastCurrentTop = current
64 return res
65 })
66 .filter(({ current, maximumScroll }) => {
67 return current !== 0 && (1 - (current / maximumScroll)) > this.decimalLimit
68 })
0cd4344f
C
69 .distinct()
70 .subscribe(() => this.nearOfTop.emit())
71
72 // Page change
73 scrollObservable
0cd4344f
C
74 .distinct()
75 .map(({ current }) => Math.max(1, Math.round((current + InfiniteScrollerDirective.PAGE_VIEW_TOP_MARGIN) / this.pageHeight)))
76 .distinctUntilChanged()
77 .subscribe(res => this.pageChanged.emit(res))
78 }
79
80}