1 import { debounceTime } from 'rxjs/operators'
2 import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { Location } from '@angular/common'
5 import { isInMobileView } from '@app/shared/misc/utils'
6 import { InfiniteScrollerDirective } from '@app/shared/video/infinite-scroller.directive'
7 import { NotificationsService } from 'angular2-notifications'
8 import { fromEvent, Observable, Subscription } from 'rxjs'
9 import { AuthService } from '../../core/auth'
10 import { ComponentPagination } from '../rest/component-pagination.model'
11 import { VideoSortField } from './sort-field.type'
12 import { Video } from './video.model'
14 export abstract class AbstractVideoList implements OnInit, OnDestroy {
15 private static LINES_PER_PAGE = 4
17 @ViewChild('videosElement') videosElement: ElementRef
18 @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
20 pagination: ComponentPagination = {
25 sort: VideoSortField = '-publishedAt'
26 defaultSort: VideoSortField = '-publishedAt'
34 videoPages: Video[][] = []
36 protected baseVideoWidth = 215
37 protected baseVideoHeight = 230
39 protected abstract notificationsService: NotificationsService
40 protected abstract authService: AuthService
41 protected abstract router: Router
42 protected abstract route: ActivatedRoute
43 protected abstract location: Location
44 protected abstract currentRoute: string
45 abstract titlePage: string
47 protected loadedPages: { [ id: number ]: Video[] } = {}
48 protected otherRouteParams = {}
50 private resizeSubscription: Subscription
52 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
53 abstract generateSyndicationList ()
56 return this.authService.getUser()
60 // Subscribe to route changes
61 const routeParams = this.route.snapshot.queryParams
62 this.loadRouteParams(routeParams)
64 this.resizeSubscription = fromEvent(window, 'resize')
65 .pipe(debounceTime(500))
66 .subscribe(() => this.calcPageSizes())
69 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
73 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
81 if (this.hasMoreVideos()) {
86 onPageChanged (page: number) {
87 this.pagination.currentPage = page
88 this.setNewRouteParams()
93 this.loadMoreVideos(this.pagination.currentPage)
96 loadMoreVideos (page: number) {
97 if (this.loadedPages[page] !== undefined) return
99 const observable = this.getVideosObservable(page)
101 observable.subscribe(
102 ({ videos, totalVideos }) => {
103 // Paging is too high, return to the first one
104 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
105 this.pagination.currentPage = 1
106 this.setNewRouteParams()
107 return this.reloadVideos()
110 this.loadedPages[page] = videos
111 this.buildVideoPages()
112 this.pagination.totalItems = totalVideos
114 // Initialize infinite scroller now we loaded the first page
115 if (Object.keys(this.loadedPages).length === 1) {
116 // Wait elements creation
117 setTimeout(() => this.infiniteScroller.initialize(), 500)
120 error => this.notificationsService.error('Error', error.message)
124 protected hasMoreVideos () {
126 if (this.pagination.totalItems === 0) return false
129 if (!this.pagination.totalItems) return true
131 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
132 return maxPage > this.maxPageLoaded()
135 protected previousPage () {
136 const min = this.minPageLoaded()
139 this.loadMoreVideos(min - 1)
143 protected nextPage () {
144 this.loadMoreVideos(this.maxPageLoaded() + 1)
147 protected buildRouteParams () {
148 // There is always a sort and a current page
151 page: this.pagination.currentPage
154 return Object.assign(params, this.otherRouteParams)
157 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
158 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
160 if (routeParams['page'] !== undefined) {
161 this.pagination.currentPage = parseInt(routeParams['page'], 10)
163 this.pagination.currentPage = 1
167 protected setNewRouteParams () {
168 const paramsObject = this.buildRouteParams()
170 const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
171 this.location.replaceState(this.currentRoute, queryParams)
174 protected buildVideoPages () {
175 this.videoPages = Object.values(this.loadedPages)
178 protected buildVideoHeight () {
179 // Same ratios than base width/height
180 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
183 private minPageLoaded () {
184 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
187 private maxPageLoaded () {
188 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
191 private calcPageSizes () {
192 if (isInMobileView() || this.baseVideoWidth === -1) {
193 this.pagination.itemsPerPage = 5
195 // Video takes all the width
197 this.videoHeight = this.buildVideoHeight()
198 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
200 this.videoWidth = this.baseVideoWidth
201 this.videoHeight = this.baseVideoHeight
203 const videosWidth = this.videosElement.nativeElement.offsetWidth
204 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
205 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
208 // Rebuild pages because maybe we modified the number of items per page
209 const videos = [].concat(...this.videoPages)
210 this.loadedPages = {}
213 // Don't include the last page if it not complete
214 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
215 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
219 // Re fetch the last page
220 if (videos.length !== 0) {
221 this.loadMoreVideos(i)
223 this.buildVideoPages()
226 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)