]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/shared/video/abstract-video-list.ts
Try to improve infinite pagination
[github/Chocobozzz/PeerTube.git] / client / src / app / shared / video / abstract-video-list.ts
CommitLineData
db400f44 1import { debounceTime } from 'rxjs/operators'
9af61e84 2import { ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'
fd45e8f4 3import { ActivatedRoute, Router } from '@angular/router'
2a2c19df 4import { Location } from '@angular/common'
0cd4344f 5import { InfiniteScrollerDirective } from '@app/shared/video/infinite-scroller.directive'
fd45e8f4 6import { NotificationsService } from 'angular2-notifications'
db400f44 7import { fromEvent, Observable, Subscription } from 'rxjs'
b2731bff 8import { AuthService } from '../../core/auth'
4635f59d 9import { ComponentPagination } from '../rest/component-pagination.model'
7b87d2d5 10import { VideoSortField } from './sort-field.type'
202f6b6c 11import { Video } from './video.model'
b1d40cff 12import { I18n } from '@ngx-translate/i18n-polyfill'
bbe0f064 13import { ScreenService } from '@app/shared/misc/screen.service'
22a16e36 14import { OwnerDisplayType } from '@app/shared/video/video-miniature.component'
fd45e8f4 15
9af61e84 16export abstract class AbstractVideoList implements OnInit, OnDestroy {
75236b98 17 private static LINES_PER_PAGE = 4
0cd4344f 18
1ff8d7d6 19 @ViewChild('videosElement') videosElement: ElementRef
0cd4344f
C
20 @ViewChild(InfiniteScrollerDirective) infiniteScroller: InfiniteScrollerDirective
21
4635f59d 22 pagination: ComponentPagination = {
fd45e8f4 23 currentPage: 1,
0cd4344f 24 itemsPerPage: 10,
fd45e8f4
C
25 totalItems: null
26 }
136cce4d 27 sort: VideoSortField = '-publishedAt'
d59cba29 28 categoryOneOf?: number
136cce4d 29 defaultSort: VideoSortField = '-publishedAt'
cc1561f9 30 syndicationItems = []
244e76a5 31
f3aaa9a9 32 loadOnInit = true
0626e7af 33 marginContent = true
0cd4344f 34 pageHeight: number
caae7a06
C
35 videoWidth: number
36 videoHeight: number
37 videoPages: Video[][] = []
22a16e36 38 ownerDisplayType: OwnerDisplayType = 'account'
fd45e8f4 39
9af61e84 40 protected baseVideoWidth = 215
a8ecc6f6 41 protected baseVideoHeight = 205
9af61e84 42
b2731bff
C
43 protected abstract notificationsService: NotificationsService
44 protected abstract authService: AuthService
45 protected abstract router: Router
46 protected abstract route: ActivatedRoute
bbe0f064 47 protected abstract screenService: ScreenService
b1d40cff 48 protected abstract i18n: I18n
2a2c19df 49 protected abstract location: Location
2bbb3412 50 protected abstract currentRoute: string
9bf9d2a5 51 abstract titlePage: string
c88593f7 52
0cd4344f 53 protected loadedPages: { [ id: number ]: Video[] } = {}
5f73f5da 54 protected loadingPage: { [ id: number ]: boolean } = {}
0cd4344f 55 protected otherRouteParams = {}
2bbb3412 56
9af61e84 57 private resizeSubscription: Subscription
a8ecc6f6 58 private firstLoadedPage: number
9af61e84 59
0cd4344f 60 abstract getVideosObservable (page: number): Observable<{ videos: Video[], totalVideos: number}>
244e76a5 61 abstract generateSyndicationList ()
fd45e8f4 62
b2731bff
C
63 get user () {
64 return this.authService.getUser()
65 }
66
fd45e8f4
C
67 ngOnInit () {
68 // Subscribe to route changes
5b5e333f 69 const routeParams = this.route.snapshot.queryParams
2bbb3412 70 this.loadRouteParams(routeParams)
a2b817d3 71
9af61e84 72 this.resizeSubscription = fromEvent(window, 'resize')
db400f44 73 .pipe(debounceTime(500))
6194c1b4 74 .subscribe(() => this.calcPageSizes())
3290f37c 75
6194c1b4 76 this.calcPageSizes()
0cd4344f 77 if (this.loadOnInit === true) this.loadMoreVideos(this.pagination.currentPage)
fd45e8f4
C
78 }
79
9af61e84
C
80 ngOnDestroy () {
81 if (this.resizeSubscription) this.resizeSubscription.unsubscribe()
82 }
83
2bbb3412 84 onNearOfTop () {
0cd4344f 85 this.previousPage()
2bbb3412
C
86 }
87
88 onNearOfBottom () {
89 if (this.hasMoreVideos()) {
90 this.nextPage()
91 }
92 }
93
0cd4344f
C
94 onPageChanged (page: number) {
95 this.pagination.currentPage = page
96 this.setNewRouteParams()
97 }
98
f3aaa9a9 99 reloadVideos () {
f3aaa9a9 100 this.loadedPages = {}
0cd4344f 101 this.loadMoreVideos(this.pagination.currentPage)
f3aaa9a9
C
102 }
103
a8ecc6f6
C
104 loadMoreVideos (page: number, loadOnTop = false) {
105 this.adjustVideoPageHeight()
106
107 const currentY = window.scrollY
108
0cd4344f 109 if (this.loadedPages[page] !== undefined) return
5f73f5da 110 if (this.loadingPage[page] === true) return
fd45e8f4 111
5f73f5da 112 this.loadingPage[page] = true
0cd4344f 113 const observable = this.getVideosObservable(page)
fd45e8f4
C
114
115 observable.subscribe(
116 ({ videos, totalVideos }) => {
5f73f5da
C
117 this.loadingPage[page] = false
118
a8ecc6f6
C
119 if (this.firstLoadedPage === undefined || this.firstLoadedPage > page) this.firstLoadedPage = page
120
a2b817d3 121 // Paging is too high, return to the first one
f595d394 122 if (this.pagination.currentPage > 1 && totalVideos <= ((this.pagination.currentPage - 1) * this.pagination.itemsPerPage)) {
a2b817d3
C
123 this.pagination.currentPage = 1
124 this.setNewRouteParams()
125 return this.reloadVideos()
126 }
127
0cd4344f
C
128 this.loadedPages[page] = videos
129 this.buildVideoPages()
fd45e8f4 130 this.pagination.totalItems = totalVideos
2bbb3412 131
0cd4344f
C
132 // Initialize infinite scroller now we loaded the first page
133 if (Object.keys(this.loadedPages).length === 1) {
134 // Wait elements creation
a8ecc6f6
C
135 setTimeout(() => {
136 this.infiniteScroller.initialize()
137
138 // At our first load, we did not load the first page
139 // Load the previous page so the user can move on the top (and browser previous pages)
140 if (this.pagination.currentPage > 1) this.loadMoreVideos(this.pagination.currentPage - 1, true)
141 }, 500)
2bbb3412 142 }
a8ecc6f6
C
143
144 // Insert elements on the top but keep the scroll in the previous position
145 if (loadOnTop) setTimeout(() => { window.scrollTo(0, currentY + this.pageHeight) }, 0)
fd45e8f4 146 },
5f73f5da
C
147 error => {
148 this.loadingPage[page] = false
b1d40cff 149 this.notificationsService.error(this.i18n('Error'), error.message)
5f73f5da 150 }
fd45e8f4
C
151 )
152 }
153
2bbb3412 154 protected hasMoreVideos () {
f595d394
C
155 // No results
156 if (this.pagination.totalItems === 0) return false
157
158 // Not loaded yet
2bbb3412
C
159 if (!this.pagination.totalItems) return true
160
202f6b6c 161 const maxPage = this.pagination.totalItems / this.pagination.itemsPerPage
6a6d92b1 162 return maxPage > this.maxPageLoaded()
2bbb3412
C
163 }
164
165 protected previousPage () {
0cd4344f 166 const min = this.minPageLoaded()
2bbb3412 167
0cd4344f
C
168 if (min > 1) {
169 this.loadMoreVideos(min - 1)
170 }
2bbb3412
C
171 }
172
173 protected nextPage () {
0cd4344f 174 this.loadMoreVideos(this.maxPageLoaded() + 1)
fd45e8f4
C
175 }
176
fd45e8f4
C
177 protected buildRouteParams () {
178 // There is always a sort and a current page
179 const params = {
180 sort: this.sort,
181 page: this.pagination.currentPage
182 }
183
0cd4344f 184 return Object.assign(params, this.otherRouteParams)
fd45e8f4
C
185 }
186
187 protected loadRouteParams (routeParams: { [ key: string ]: any }) {
7b87d2d5 188 this.sort = routeParams['sort'] as VideoSortField || this.defaultSort
d59cba29 189 this.categoryOneOf = routeParams['categoryOneOf']
fd45e8f4
C
190 if (routeParams['page'] !== undefined) {
191 this.pagination.currentPage = parseInt(routeParams['page'], 10)
192 } else {
193 this.pagination.currentPage = 1
194 }
195 }
196
2bbb3412 197 protected setNewRouteParams () {
2a2c19df
C
198 const paramsObject = this.buildRouteParams()
199
200 const queryParams = Object.keys(paramsObject).map(p => p + '=' + paramsObject[p]).join('&')
201 this.location.replaceState(this.currentRoute, queryParams)
fd45e8f4 202 }
0cd4344f
C
203
204 protected buildVideoPages () {
205 this.videoPages = Object.values(this.loadedPages)
206 }
207
a8ecc6f6
C
208 protected adjustVideoPageHeight () {
209 const numberOfPagesLoaded = Object.keys(this.loadedPages).length
210 if (!numberOfPagesLoaded) return
211
212 this.pageHeight = this.videosElement.nativeElement.offsetHeight / numberOfPagesLoaded
213 }
214
a86887a4
C
215 protected buildVideoHeight () {
216 // Same ratios than base width/height
217 return this.videosElement.nativeElement.offsetWidth * (this.baseVideoHeight / this.baseVideoWidth)
218 }
219
0cd4344f
C
220 private minPageLoaded () {
221 return Math.min(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
222 }
223
224 private maxPageLoaded () {
225 return Math.max(...Object.keys(this.loadedPages).map(e => parseInt(e, 10)))
226 }
6194c1b4
C
227
228 private calcPageSizes () {
bbe0f064 229 if (this.screenService.isInMobileView() || this.baseVideoWidth === -1) {
6194c1b4
C
230 this.pagination.itemsPerPage = 5
231
232 // Video takes all the width
233 this.videoWidth = -1
a86887a4 234 this.videoHeight = this.buildVideoHeight()
6194c1b4
C
235 this.pageHeight = this.pagination.itemsPerPage * this.videoHeight
236 } else {
9af61e84
C
237 this.videoWidth = this.baseVideoWidth
238 this.videoHeight = this.baseVideoHeight
caae7a06 239
6194c1b4
C
240 const videosWidth = this.videosElement.nativeElement.offsetWidth
241 this.pagination.itemsPerPage = Math.floor(videosWidth / this.videoWidth) * AbstractVideoList.LINES_PER_PAGE
242 this.pageHeight = this.videoHeight * AbstractVideoList.LINES_PER_PAGE
243 }
244
245 // Rebuild pages because maybe we modified the number of items per page
caae7a06 246 const videos = [].concat(...this.videoPages)
6194c1b4
C
247 this.loadedPages = {}
248
caae7a06
C
249 let i = 1
250 // Don't include the last page if it not complete
251 while (videos.length >= this.pagination.itemsPerPage && i < 10000) { // 10000 -> Hard limit in case of infinite loop
252 this.loadedPages[i] = videos.splice(0, this.pagination.itemsPerPage)
253 i++
6194c1b4
C
254 }
255
9af61e84
C
256 // Re fetch the last page
257 if (videos.length !== 0) {
258 this.loadMoreVideos(i)
259 } else {
260 this.buildVideoPages()
261 }
6194c1b4 262
caae7a06 263 console.log('Rebuilt pages with %s elements per page.', this.pagination.itemsPerPage)
6194c1b4 264 }
fd45e8f4 265}