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 loadingPage: { [ id: number ]: boolean } = {}
49 protected otherRouteParams = {}
51 private resizeSubscription: Subscription
53 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
54 abstract generateSyndicationList ()
57 return this.authService.getUser()
61 // Subscribe to route changes
62 const routeParams = this.route.snapshot.queryParams
63 this.loadRouteParams(routeParams)
65 this.resizeSubscription = fromEvent(window, 'resize')
66 .pipe(debounceTime(500))
67 .subscribe(() => this.calcPageSizes())
70 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
74 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
82 if (this.hasMoreVideos()) {
87 onPageChanged (page: number) {
88 this.pagination.currentPage = page
89 this.setNewRouteParams()
94 this.loadMoreVideos(this.pagination.currentPage)
97 loadMoreVideos (page: number) {
98 if (this.loadedPages[page] !== undefined) return
99 if (this.loadingPage[page] === true) return
101 this.loadingPage[page] = true
102 const observable = this.getVideosObservable(page)
104 observable.subscribe(
105 ({ videos, totalVideos }) => {
106 this.loadingPage[page] = false
108 // Paging is too high, return to the first one
109 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
110 this.pagination.currentPage = 1
111 this.setNewRouteParams()
112 return this.reloadVideos()
115 this.loadedPages[page] = videos
116 this.buildVideoPages()
117 this.pagination.totalItems = totalVideos
119 // Initialize infinite scroller now we loaded the first page
120 if (Object.keys(this.loadedPages).length === 1) {
121 // Wait elements creation
122 setTimeout(() => this.infiniteScroller.initialize(), 500)
126 this.loadingPage[page] = false
127 this.notificationsService.error('Error', error.message)
132 protected hasMoreVideos () {
134 if (this.pagination.totalItems === 0) return false
137 if (!this.pagination.totalItems) return true
139 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
140 return maxPage > this.maxPageLoaded()
143 protected previousPage () {
144 const min = this.minPageLoaded()
147 this.loadMoreVideos(min - 1)
151 protected nextPage () {
152 this.loadMoreVideos(this.maxPageLoaded() + 1)
155 protected buildRouteParams () {
156 // There is always a sort and a current page
159 page: this.pagination.currentPage
162 return Object.assign(params, this.otherRouteParams)
165 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
166 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
168 if (routeParams['page'] !== undefined) {
169 this.pagination.currentPage = parseInt(routeParams['page'], 10)
171 this.pagination.currentPage = 1
175 protected setNewRouteParams () {
176 const paramsObject = this.buildRouteParams()
178 const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
179 this.location.replaceState(this.currentRoute, queryParams)
182 protected buildVideoPages () {
183 this.videoPages = Object.values(this.loadedPages)
186 protected buildVideoHeight () {
187 // Same ratios than base width/height
188 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
191 private minPageLoaded () {
192 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
195 private maxPageLoaded () {
196 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
199 private calcPageSizes () {
200 if (isInMobileView() || this.baseVideoWidth === -1) {
201 this.pagination.itemsPerPage = 5
203 // Video takes all the width
205 this.videoHeight = this.buildVideoHeight()
206 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
208 this.videoWidth = this.baseVideoWidth
209 this.videoHeight = this.baseVideoHeight
211 const videosWidth = this.videosElement.nativeElement.offsetWidth
212 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
213 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
216 // Rebuild pages because maybe we modified the number of items per page
217 const videos = [].concat(...this.videoPages)
218 this.loadedPages = {}
221 // Don't include the last page if it not complete
222 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
223 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
227 // Re fetch the last page
228 if (videos.length !== 0) {
229 this.loadMoreVideos(i)
231 this.buildVideoPages()
234 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)