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